Installation¶
BetterCap comes packaged as a Ruby gem, meaning you will need a Ruby interpreter ( >= 1.9 ) and a RubyGems environment installed. Moreover, it is fully compatible with GNU/Linux, Mac OS X and OpenBSD platforms.
Dependencies¶
All Ruby dependencies will be automatically installed through the GEM system, however some of the GEMS need native libraries in order to compile:
Installing on Kali Linux¶
Kali Linux has bettercap packaged and added to the kali-rolling repositories. To install bettercap and all dependencies in one fell swoop on the latest version of Kali Linux:
Stable Release ( GEM )¶
You can easily install bettercap using the gem install GEMNAME command:
To update to a newer release:
If you have trouble installing bettercap read the following sections about dependencies.
If you installed bettercap using a RVM installation, you will need to execute it using rvmsudo:
rvmsudo bettercap .
Otherwise, if you installed it globally ( sudo gem install bettercap ) you can use sudo:
sudo bettercap .
Development Release¶
Instead of the stable release, you can also clone the source code from the github repository, this will give you all the latest and experimental features, but remember that you’re using a potentially unstable release:
Quick Start¶
Once you’ve installed bettercap, quickly get started with:
The help menu will show you every available command line option and a few examples.
© Copyright 2016, Simone 'evilsocket' Margaritelli Revision b5dad875 .
Tool Documentation:
Scan the system in quiet mode ( -Q ) and output in cronjob format ( –cronjob ):
Packages and Binaries:
bettercap
The Swiss Army knife for 802.11, BLE, IPv4 and IPv6 networks reconnaissance and MITM attacks.
bettercap is a powerful, easily extensible and portable framework written in Go which aims to offer to security researchers, red teamers and reverse engineers an easy to use, all-in-one solution with all the features they might possibly need for performing reconnaissance and attacking WiFi networks, Bluetooth Low Energy devices, wireless HID devices and Ethernet networks.
- WiFi networks scanning, deauthentication attack, clientless PMKID association attack and automatic WPA/WPA2 client handshakes capture.
- Bluetooth Low Energy devices scanning, characteristics enumeration, reading and writing.
- 2.4Ghz wireless devices scanning and MouseJacking attacks with over-the-air HID frames injection (with DuckyScript support).
- Passive and active IP network hosts probing and recon.
- ARP, DNS, NDP and DHCPv6 spoofers for MITM attacks on IPv4 and IPv6 based networks.
- Proxies at packet level, TCP level and HTTP/HTTPS application level fully scriptable with easy to implement javascript plugins.
- A powerful network sniffer for credentials harvesting which can also be used as a network protocol fuzzer.
- A very fast port scanner.
- A powerful REST API with support for asynchronous events notification on websocket to orchestrate your attacks easily.
- A very convenient web UI.
- More! (https://www.bettercap.org/modules/)
This package contains a Swiss Army knife for 802.11, BLE and Ethernet networks reconnaissance and attacks.
Installed size: 24.05 MB
How to install: sudo apt install bettercap
Documentation¶
BetterCAP is a powerful, flexible and portable tool created to perform various types of MITM attacks against a network, manipulate HTTP, HTTPS and TCP traffic in realtime, sniff for credentials and much more.
Check on the Next button below and start hacking!
Introduction¶
BetterCAP is a powerful, flexible and portable tool created to perform various types of MITM attacks against a network, manipulate HTTP, HTTPS and TCP traffic in realtime, sniff for credentials and much more.
You Are the Man in the Middle¶
What is a MITM ( Man In The Middle ) attack? Let’s ask Wikipedia!
This is quite a generic description, mostly because ( if we’re talking about network MITM attacks ), the logic and details heavily rely on the technique being used ( more in the spoofing section ).
Nevertheless we can simplify the concept with an example. When you connect to some network ( your home network, some public WiFi, StarBucks, etc ), the router/switch is responsible for forwarding all of your packets to the correct destination, during a MITM attack we "force" the network to consider our device as the router ( we "spoof" the original router/switch address in some way ):
Once this happens, all of the network traffic goes through your computer instead of the legit router/switch and at that point you can do pretty much everything you want, from just sniffing for specific data ( emails, passwords, cookies, etc of other people on your network ) to actively intercepting and proxying all the requests of some specific protocol in order to modify them on the fly ( you can, for instance, replace all images of all websites being visited by everyone, kill connections, etc ).
BetterCap is responsible for giving the security researcher everything he needs in one single tool which simply works, on GNU/Linux, Mac OS X and OpenBSD systems.
Use Cases¶
You might think that BetterCAP is just another tool which helps script-kiddies to harm networks . but it’s much more than that, its use cases are many, for instance:
- Many professional penetration testers find a great companion in bettercap since its very first release.
- Reverse engineers are using it in order to reverse or modify closed network protocols.
- Mobile/IoT security researchers are exploiting bettercap capabilities to test the security of mobile systems.
Why another MITM tool?¶
This is exactly what you are thinking right now, isn’t it? 😀 But allow yourself to think about it for 5 more minutes . what you should be really asking is:
If your answer is "ettercap", let me tell you something:
- Ettercap was a great tool, but it made its time.
- Ettercap filters do not work most of the times, are outdated and hard to implement due to the specific language they’re implemented in.
- Ettercap is freaking unstable on big networks . try to launch the host discovery on a bigger network rather than the usual /24 😉
- Yeah you can see connections and raw pcap stuff, nice toy, but as a professional researcher I want to see only relevant stuff.
- Unless you’re a C/C++ developer, you can’t easily extend ettercap or make your own module.
- Ettercap’s and MITMf’s ICMP spoofing is completely useless, ours is not.
- Ettercap does not provide a builtin and modular HTTP(S) and TCP transparent proxies, we do.
- Ettercap does not provide a smart and fully customizable credentials sniffer, we do.
Installation¶
BetterCap comes packaged as a Ruby gem, meaning you will need a Ruby interpreter ( >= 1.9 ) and a RubyGems environment installed. Moreover, it is fully compatible with GNU/Linux, Mac OS X and OpenBSD platforms.
Dependencies¶
All Ruby dependencies will be automatically installed through the GEM system, however some of the GEMS need native libraries in order to compile:
Installing on Kali Linux¶
Kali Linux has bettercap packaged and added to the kali-rolling repositories. To install bettercap and all dependencies in one fell swoop on the latest version of Kali Linux:
Stable Release ( GEM )¶
You can easily install bettercap using the gem install GEMNAME command:
To update to a newer release:
If you have trouble installing bettercap read the following sections about dependencies.
If you installed bettercap using a RVM installation, you will need to execute it using rvmsudo:
rvmsudo bettercap .
Otherwise, if you installed it globally ( sudo gem install bettercap ) you can use sudo:
sudo bettercap .
Development Release¶
Instead of the stable release, you can also clone the source code from the github repository, this will give you all the latest and experimental features, but remember that you’re using a potentially unstable release:
Quick Start¶
Once you’ve installed bettercap, quickly get started with:
The help menu will show you every available command line option and a few examples.
Contributing¶
As any other open source projects, there’re many ways you can contribute to bettercap depending on your skills as a developer or will to help as a user.
Submitting Issues¶
If you find bugs or inconsistencies while using bettercap, you can create an Issue using the GitHub Issue tracker, but before doing that please make sure that:
- You are using a relatively new Ruby version ( >= 1.9 ) : ruby -v .
- Your GEM environment is configured properly and updated : sudo gem update .
- You are using the latest version of bettercap : bettercap —check-updates .
- The bug you’re reporting is actually related to bettercap and not to one of the other GEMs.
Once you’ve gone through this list, open an issue and please give us as much as informations as possible in order for us to fix the bug as soon as possible:
- Your OS version.
- Ruby version you’re using.
- Full output of the error ( exception backtrace, error message, etc ).
- Your network configuration: ifconfig -a
Also, you should attach to the issue a debug log that you can generate with:
Wait for the error to happen then close bettercap and paste the debug.log file inside the issue.
Improving the Documentation¶
If you want to help, you can improve this documentation cloning our code repository and updating the contents of the docs folder.
Pull Requests¶
If you know how to code in Ruby and have ideas to improve bettercap, you’re very welcome to send us pull requests, we’ll be happy to merge them whenever they comply to the following rules:
- You have at least manually tested your code, ideally you’ve created actual tests for it.
- Respect our coding standard, 2 spaces indentation and modular code.
- There’re no conflicts with the current dev branch.
- Your commit messages are enough explanatory to us.
There’re plenty of things you can to do improve the software:
- Implement a new proxy module and push it to the dedicated repository.
- Implement a new Spoofer module.
- Implement a new Sniffer credentials parser.
- Fix, extend or improve the core.
General Options¶
The following are the main options that determine the general behaviour of BetterCap, these options are not mandatory, in fact bettercap will automatically detect everything it needs in order to work, you just might need to use one or more of the following options to specify some custom behaviour in specific cases.
Examples¶
Attack specific targets:
sudo bettercap -T 192.168.1.10,192.168.1.11
Attack a specific target by its MAC address:
sudo bettercap -T 01:23:45:67:89:10
Attack a range of IP addresses:
sudo bettercap -T 192.168.1.1-30
Attack a specific subnet:
sudo bettercap -T 192.168.1.1/24
Randomize the interface MAC address during the attack:
sudo bettercap —random-mac
Options¶
-I, —interface IFACE ¶
BetterCAP will automatically detect your default network interface and use it, if you want to make it use another interface ( when you have more than one, let’s say eth0 and wlan0 ) you can use this option.
—use-mac ADDRESS ¶
Change the interface MAC address to this value before performing the attack.
—random-mac ¶
Change the interface MAC address to a random one before performing the attack.
-G, —gateway ADDRESS ¶
The same goes for the gateway, either let bettercap automatically detect it or manually specify its address.
-T, —target ADDRESS1,ADDRESS2 ¶
If no specific target is given on the command line, bettercap will spoof every single address on the network. There are cases when you already know the IP or MAC address of your target(s), in such cases you can use this option.
—ignore ADDRESS1,ADDRESS2 ¶
Ignore these IP addresses if found while searching for targets.
—no-discovery ¶
Do not actively search for hosts, just use the current ARP cache, default to false .
—no-target-nbns ¶
Disable target NBNS hostname resolution.
—packet-throttle NUMBER ¶
Number of seconds ( can be a decimal number ) to wait between each packet to be sent.
—check-updates ¶
Will check if any update is available and then exit.
-h, —help ¶
Display the available options.
Logging¶
These options determine how bettercap console logger is going to behave.
Examples¶
Save log output to the out.log file:
sudo bettercap —log out.log
Save log output to the out.log file and suppress terminal output:
sudo bettercap —log out.log —silent
Save log output to the out-ts.log file and enable timestamps for each line:
sudo bettercap —log-timestamp —log out-ts.log
Options¶
-O, —log LOG_FILE ¶
Log all messages into a file, if not specified the log messages will be only print into the shell.
—log-timestamp ¶
Enable logging with timestamps for each line, disabled by default.
-D, —debug ¶
Enable debug logging, it is good practice to use this option while reporting a bug in order to have the full debug log of the program.
—silent ¶
Suppress every message which is not an error or a warning, default to false .
Spoofing¶
As previously described in the introduction section, spoofing is the very hearth of every MITM attack. These options will determine which spoofing technique to use and how to use it.
BetterCap already includes an ARP spoofer ( working both in full duplex and half duplex mode which is the default ), a DNS spoofer and the first, fully working and completely automatized ICMP DoubleDirect spoofer in the world
Examples¶
Use the good old ARP spoofing:
sudo bettercap or sudo bettercap -S ARP or sudo bettercap —spoofer ARP
Use a full duplex ICMP redirect spoofing attack:
sudo bettercap -S ICMP or sudo bettercap —spoofer ICMP
sudo bettercap -S NONE or sudo bettercap —spoofer NONE or sudo bettercap —no-spoofing
No dear 192.168.1.2, you won’t connect to anything anymore 😀
sudo bettercap -T 192.168.1.2 —kill
Options¶
-S, —spoofer NAME ¶
Spoofer module to use, available: ARP , ICMP , NONE — default: ARP .
—no-spoofing ¶
Disable spoofing, alias for —spoofer NONE / -S NONE .
Instead of forwarding packets, this switch will make targets connections to be killed.
—full-duplex ¶
Enable full-duplex MITM, this will make bettercap attack both the target(s) and the router.
Sniffing & Credentials Harvesting¶
The builtin sniffer is currently able to dissect and print from the network ( or from a previously captured PCAP file ) the following informations:
- URLs being visited.
- HTTPS hosts being visited.
- HTTP POSTed data.
- HTTP Basic and Digest authentications.
- HTTP Cookies.
- FTP credentials.
- IRC credentials.
- POP, IMAP and SMTP credentials.
- NTLMv1/v2 ( HTTP, SMB, LDAP, etc ) credentials.
- DICT Protocol credentials.
- MPD Credentials.
- NNTP Credentials.
- DHCP messages and authentication.
- REDIS login credentials.
- RLOGIN credentials.
- SNPP credentials.
- And more!
New parsers are implemented almost on a regular basis for each new release, for a full and updated list check the SNIFFING section in the «bettercap —help» menu.
Examples¶
Use bettercap as a simple local network sniffer:
sudo bettercap —local or sudo bettercap -L
Use the capture.pcap file in your home directory as a packets source:
sudo bettercap —sniffer-source
Spoof the whole network and save every packet to the capture.pcap file in your home directory:
sudo bettercap —sniffer-output
Spoof the whole network but only sniff HTTP traffic:
sudo bettercap —sniffer-filter "tcp port http"
Spoof the whole network and extract data from packets containing the "password" word:
sudo bettercap —custom-parser ".*password.*"
Options¶
-X, —sniffer ¶
-L, —local ¶
By default bettercap will only parse packets coming from/to other addresses on the network, if you also want to process packets being sent or received from your own computer you can use this option ( NOTE: will enable the sniffer ).
—sniffer-source FILE ¶
Load packets from the specified PCAP file instead of the network interface ( NOTE: will enable the sniffer ).
—sniffer-output FILE ¶
Save all packets to the specified PCAP file ( NOTE: will enable the sniffer ).
—sniffer-filter EXPRESSION ¶
Configure the sniffer to use this BPF filter ( NOTE: will enable the sniffer ).
-P, —parsers PARSERS ¶
Comma separated list of packet parsers to enable, * for all ( NOTE: will enable the sniffer ), available: COOKIE , CREDITCARD , DHCP , DICT , FTP , HTTPAUTH , HTTPS , IRC , MAIL , MPD , MYSQL , NNTP , NTLMSS , PGSQL , POST , REDIS , RLOGIN , SNMP , SNPP , URL , WHATSAPP , default to * .
—custom-parser EXPRESSION ¶
Use a custom regular expression in order to capture and show sniffed data ( NOTE: will enable the sniffer ).
About Proxying¶
Bettercap is shipped with a HTTP/HTTPS ( with SSL Stripping and HSTS Bypass ) and raw TCP transparent proxies that you can use to manipulate HTTP/HTTPS or low level TCP traffic at runtime, for instance you could use the HTTP/HTTPS proxy to inject javascripts into the targets visited pages ( BeEF would be a great choice 😀 ), replace all the images, etc or use the TCP one for other protocols ( downgrade encryption with STARTTLS, dump custom protocols and so forth.
Once one or more proxies are enabled, bettercap will take care of the spoofing and the firewall rules needed in order to redirect your targets’ traffic to the proxy itself.
By default the builtin proxies won’t do anything but logging all the requests, additionally you can specify a "module" to use and you will be able to load one of the builtin plugins ( or your own ) and manipulate all the traffic as you like.
HTTP/HTTPS¶
Bettercap is shipped with both a HTTP and a HTTPS transparent proxies that you can use to manipulate HTTP and HTTPS traffic at runtime ( inject javascripts into the targets visited pages, replace the images, etc ). By default the builtin proxies won’t do anything but logging HTTP(S) requests, but if you specify a —proxy-module argument you will be able to load one of the builtin modules ( or your own ) and manipulate HTTP traffic as you like.
Builtin modules are:
- InjectJS ( —proxy-module injectjs ) : Used to inject javascript code/files inside HTML pages.
- InjectCSS ( —proxy-module injectcss ) : Used to inject CSS code/files inside HTML pages.
- InjectHTML ( —proxy-module injecthtml ) : Used to inject HTML code inside HTML pages.
HTTP/HTTPS proxy modules might want additional command line arguments, it’s always a good idea to look at their specific help menus:
bettercap —proxy-module NAME -h
Sample Module¶
You can easily implement a module to inject data into pages or just inspect the requests/responses creating a ruby file and passing it to bettercap with the —proxy-module argument, the following is a sample module that injects some contents into the title tag of each html page, you can find other examples modules in the proxy modules dedicated repository.
SSL Stripping¶
SSL stripping is a technique introduced by Moxie Marlinspike during BlackHat DC 2009, the website description of this technique goes like:
Long story short, this technique will replace every https link in webpages the target is browsing with http ones so, if a page would normally look like:
During a SSL stripping attack its HTML code will be modified as:
Being the man in the middle, this allow us to sniff and modify pages that normally we wouldn’t be able to even see.
HSTS Bypass¶
SSL stripping worked quite well until 2010, when the HSTS specification was introduced, Wikipedia says:
Moreover HSTS policies have been prebuilt into major browsers meaning that now, even with a SSL stripping attack running, the browser will connect to HTTPS anyway, even if the http:// schema is specified, making the attack itself useless.
Picture credits to Scott Helme
For this reason, Leonardo Nve Egea presented sslstrip+ ( or sslstrip2 ) during BlackHat Asia 2014. This tool was an improvement over the original Moxie’s version, specifically created to bypass HSTS policies. Since HSTS rules most of the time are applied on a per-hostname basis, the trick is to downgrade HTTPS links to HTTP and to prepend some custom sub domain name to them. Every resulting link won’t be valid for any DNS server, but since we’re MITMing we can resolve these hostnames anyway.
Let’s take the previous example page:
A HSTS bypass attack will change it to something like:
Notice that https has been downgraded to http and www replaced with wwww ).
When the "victim" will click on that link, no HSTS rule will be applied ( since there’s no rule for such subdomain we just created ) and the MITM software ( BetterCap in our case ^_^ ) will take care of the DNS resolution, allowing us to see and alter the traffic we weren’t supposed to see.
Demonstration¶
The following video demonstrates how to perform SSL Stripping and HSTS Bypass attacks in order to capture the Facebook login credentials of a specific target.
HTTPS¶
Server Name Indication¶
Using the SNI callback, BetterCAP’s HTTPS proxy is able to detect the upstream server host using the following logic:
- Client connects to a HTTPS server while being transparently proxied by us.
- We catch the upstream server hostname in the SNI callback.
- We pause the callback, connect to the upstream server and fetch its certificate.
- We resign that certificate with our own CA and use it to serve the client.
This way, as long as you have BetterCap’s certification authority PEM file installed on the target device, you won’t see any warnings or errors since correct certificate will be spoofed in realtime.
There’re a couple of caveats of course:
- If you don’t install either bettercap’s CA or your custom CA on the target device, you’ll see warnings and errors anyway (duh!).
- Every application using certificate/public Key pinning will detect the attack even with the CA installed.
Installing Certification Authority¶
Since version 1.4.4 BetterCAP comes with a pre made certification authority file which is extracted in your home directory the first time you’ll launch the HTTPS proxy, you’ll find the file as:
You’ll need to install this file on the device you want to transparently proxy HTTPS connection for, the procedure is OS specific as mentioned in a previous blog post:
- iOS — http://kb.mit.edu/confluence/pages/viewpage.action?pageId=152600377
- iOS Simulator — https://github.com/ADVTOOLS/ADVTrustStore#how-to-use-advtruststore
- Java — http://docs.oracle.com/cd/E19906-01/820-4916/geygn/index.html
- Android/Android Simulator — http://wiki.cacert.org/FAQ/ImportRootCert#Android_Phones_.26_Tablets
- Windows — http://windows.microsoft.com/en-ca/windows/import-export-certificates-private-keys#1TC=windows-7
- Mac OS X — https://support.apple.com/kb/PH7297?locale=en_US
- Ubuntu/Debian — http://askubuntu.com/questions/73287/how-do-i-install-a-root-certificate/94861#94861
- Mozilla Firefox — https://wiki.mozilla.org/MozillaRootCertificate#Mozilla_Firefox
- Chrome on Linux — https://code.google.com/p/chromium/wiki/LinuxCertManagement
Once you’ve done, just use the —proxy-https bettercap command line argument to enable the HTTPS proxy and you’re ready to go.
Options¶
—proxy-upstream-address ADDRESS ¶
If set, only requests coming from this server address will be redirected to the HTTP/HTTPS proxies.
—allow-local-connections ¶
Allow direct connections to the proxy instance, default to false .
—proxy ¶
Enable HTTP proxy and redirects all HTTP requests to it, default to false .
—proxy-port PORT ¶
Set HTTP proxy port, default to 8080 .
—no-sslstrip ¶
Disable SSL stripping and HSTS bypass.
—log-http-response ¶
Log HTTP responses.
—proxy-module MODULE ¶
Ruby proxy module to load, either a custom file or one of the following: injectcss , injecthtml , injectjs .
—http-ports PORT1,PORT2 ¶
Comma separated list of HTTP ports to redirect to the proxy, default to 80 .
—proxy-https ¶
Enable HTTPS proxy and redirects all HTTPS requests to it, default to false .
—proxy-https-port PORT ¶
Set HTTPS proxy port, default to 8083 .
—proxy-pem FILE ¶
Use a custom PEM CA certificate file for the HTTPS proxy, default to
—https-ports PORT1,PORT2 ¶
Comma separated list of HTTPS ports to redirect to the proxy, default to 443 .
If you want to actively modify packets of a TCP protocol which is not HTTP or HTTPS, you’ll need the TCP proxy. This event-based proxy will allow you to intercept anything sent/received to/from a specific host using your own custom module.
Sample Module¶
The following example module won’t do anything but dumping the data being transmitted from/to the target, you can access the event object in order to modify the data on the fly.
If you want to load such module and dump all the ( let’s say ) MySQL traffic from/to the mysql.example.com host you would do:
And you would be ready to go.
Options¶
—tcp-proxy ¶
Enable the TCP proxy ( requires other —tcp-proxy-* options to be specified ).
—tcp-proxy-module MODULE ¶
Ruby TCP proxy module to load.
—tcp-proxy-port PORT ¶
Set local TCP proxy port, default to 2222 .
—tcp-proxy-upstream-address ADDRESS ¶
Set TCP proxy upstream server address.
—tcp-proxy-upstream-port PORT ¶
Set TCP proxy upstream server port.
—tcp-proxy-upstream ADDRESS:PORT ¶
Set TCP proxy upstream server address and port ( shortcut for —tcp-proxy-upstream-address ADDRESS and —tcp-proxy-upstream-port PORT ).
If you want to actively modify packets of a UDP protocol, you’ll need the UDP proxy. This event-based proxy will allow you to intercept anything sent/received to/from a specific host using your own custom module.
Sample Module¶
The following example module won’t do anything but dumping the data being transmitted from/to the target, you can access the event object in order to modify the data on the fly.
If you want to load such module and dump all the ( let’s say ) DNS traffic from/to the ns01.example.com host you would do:
And you would be ready to go.
Options¶
—udp-proxy ¶
Enable the UDP proxy ( requires other —udp-proxy-* options to be specified ).
—udp-proxy-module MODULE ¶
Ruby UDP proxy module to load.
—udp-proxy-port PORT ¶
Set local UDP proxy port, default to 2222 .
—udp-proxy-upstream-address ADDRESS ¶
Set UDP proxy upstream server address.
—udp-proxy-upstream-port PORT ¶
Set UDP proxy upstream server port.
—udp-proxy-upstream ADDRESS:PORT ¶
Set UDP proxy upstream server address and port ( shortcut for —udp-proxy-upstream-address ADDRESS and —udp-proxy-upstream-port PORT ).
Third Party Proxies¶
If you want to use some custom proxy of yours ( BurpSuite for instance, or some custom app you wrote ) you can still use bettercap to make the whole process easier, no more crappy shell scripts to apply custom firewall rules and launch "esotic" commands!
For instance, if you want to attack the whole network and redirect all HTTP traffic to your local BurpSuite installation ( in this example 192.168.1.2 is your computer ip address ):
—custom-proxy ADDRESS ¶
Use a custom HTTP upstream proxy instead of the builtin one.
—custom-proxy-port PORT ¶
Specify a port for the custom HTTP upstream proxy, default to 8080 .
—custom-https-proxy ADDRESS ¶
Use a custom HTTPS upstream proxy instead of the builtin one.
—custom-https-proxy-port PORT ¶
Specify a port for the custom HTTPS upstream proxy, default to 8083.
—custom-redirection RULE ¶
Apply a custom port redirection, the format of the rule is PROTOCOL ORIGINAL_PORT NEW_PORT . For instance TCP 21 2100 will redirect all TCP traffic going to port 21 , to port 2100 .
You want to serve your custom javascript files on the network? Maybe you wanna inject some custom script or image into HTTP responses using a transparent proxy module but you got no public server to use? no worries dude :DA builtin HTTP server comes with bettercap, allowing you to serve custom contents from your own machine without installing and configuring other softwares such as Apache, nginx or lighttpd.
—httpd ¶
Enable HTTP server, default to false .
—httpd-port PORT ¶
Set HTTP server port, default to 8081 .
—httpd-path PATH ¶
Set HTTP server path, default to ./ .
If you want to perform DNS spoofing, you must specify the —dns FILE command line argument, where the FILE value is the name of a file composed by entries like the following:
HackWare.ru
Этичный хакинг и тестирование на проникновение, информационная безопасность
Новая версия bettercap 2.x: как установить и использовать в Kali Linux
Оглавление
Отличия bettercap 2 от bettercap 1.6
Я уже писал про bettercap, в том числе на страницах HackWare.ru:
- Инструкция по использованию Bettercap
- Bettercap на Kali.Tools
В конце февраля 2018 вышла bettercap 2 и с тех пор именно эта версия активно развивается, в неё добавляются новые функции. Версия bettercap 1.6 является устаревшей и больше не поддерживается.
В последних версиях bettercap очень много изменений – программа была переписана заново, причём на другом языке программирования: вместо Ruby теперь Go. Благодаря смене языка и другим применяемым методикам, драматически выросла производительность, оптимизировано использование ЦПУ и памяти.
Поменялась модель взаимодействия с программой – раньше это была утилита командной строки, при запуске которой использовались различные опции. Новую версию также можно запускать в не-интерактивном режиме, используя опции, но теперь доступен интерактивный режим, а также API.
Поменялось даже предназначение программы: раньше это была модульная платформа для реализации комплексных атак человек-посередине, теперь кроме поддержки атак человек-посередине, имеется функционал для мониторинга сети, мониторинга и атак на беспроводные сети 802.11 и BLE.
Функции программы стали более атомизированы, например, для запуска самой обычной атаки человек-посередине, состоящий из ARP-спуфинга и сниффинга, теперь нужно ввести несколько команд (раньше было достаточно одной опции). Это увеличивает гибкость использования программы и её модулей, но при этом и усложняет использование. Чтобы автоматизировать работу программы и упростить использование, теперь применяются каплеты, которые управляют работой bettercap и её модулями. Примеры каплетов собраны в репозитории https://github.com/bettercap/caplets.
И это даже не все изменения! Стоит упомянуть, что поддерживаются нативные плагины Go (через модуль packet.proxy), некоторые модули поддерживают скриптовый язык JavaScript для манипулирования данными и управления поведением программы, а сама программа и её каплеты поддерживают нативные системные команды.
В общем – это просто другая программа, в которой всё по-новому.
В связи с этим, была написана новая страница справки по программе: https://kali.tools/?p=3870. Она получилась большой, т.к. дам даны характеристики всех модулей.
Старая страница с описанием программы сохранена! Это сделано по той причине, что на момент написания в Kali Linux доступна именно прежняя версия. К тому же, наверняка найдутся поклонники прежней версии, которые предпочтут её новой.
Варианты установки bettercap 2 в Kali Linux
В репозиториях Kali Linux уже присутствует bettercap, но на момент написания там устаревшая версия 1.6.2. Чтобы проверить, какая версия bettercap в данный момент доступна для установки из официальных репозиториев, выполните:
Если будет выведено что-то вроде:
значит версия является устаревшей.
Если там появится версия 2.x, то для её установки достаточно выполнить:
Скачивание и установка последней версии bettercap
Удалим устаревшую версию bettercap, если она была установлена ранее:
Фикс для уже установленной библиотеки:
Скачиваем архив с бинарным файлом последней версии bettercap:
Распаковываем, перемещаем, делаем очистку и проверку:
Установка bettercap из исходного кода будет рассмотрена в конце статьи.
Инструкция по использованию bettercap
Теперь главной функциональной особенностью bettercap является не только и не столько различные атаки человек-посередине. Благодаря каплетам и скриптам, возможны реализации самых разных фишинговых атак и атак на основе манипуляции данными, отправной точкой которых является атака человек-посередине. По этой причине непросто написать исчерпывающую инструкцию по bettercap.
Чтобы примерно представить возможности программы, прочитайте перевод документации на русский язык, а также ознакомьтесь с репозиторием каплетов: многие из них имеют комментарии в исходном коде, которые помогают понять, что именно будет делать программа.
Далее будут рассмотрены совсем простые примеры запуска bettercap. Начнём с использования интерактивной сессии, для этого запустите bettercap:
Мониторинг локальной сети
Чтобы вывести список обнаруженных хостов локальной сети наберите команду:
Это пассивный метод мониторинга, поскольку поиск хостов основывается на считывании ARP кэша.
Чтобы выйти из программы, наберите q или нажмите CTRL+z.
А модуль net.probe активно ищет хосты, отправляя фиктивные UDP пакеты каждому возможному IP в подсети. Включаем этот модуль:
Смотрим обнаруженные хосты:
Это активный метод – анализаторам сети будет видно, что компьютер с bettercap массово рассылает пакеты.
С помощью bettercap можно непрерывно мониторить состояние сети, получая на экране данные в режиме реального времени, для этого последовательно выполните:
Первая команда net.probe on, как мы выяснили чуть раньше, включает активный поиск хостов, а вторая команда используется для периодического выполнения заданного набора команд. Поскольку мы не указали, какие именно команды выполнять, то выполняются команды по умолчанию, а именно clear; net.show, в результате достигается интересный эффект: в фоне постоянно происходит поиск хостов, а на экране в режиме реального времени выводится актуальная информация.
Интерактивный и неинтерактивный режим. Опции -eval и -caplet. Каплеты
Если вам неудобно каждый раз запускать bettercap в интерактивном режиме, то вы можете использовать опцию -eval, после которой укажите команды, которые нужно выполнить. Например, предыдущий пример равнозначен такому запуску:
Прямо в интерактивной сессии bettercap можно выполнять команды системы. К примеру, следующий набор команд проверяет, имеется ли подключение к глобальной сети:
Эту же команду (набор команд) можно выполнить прямо в интерактивной сессии, достаточно перед первой командой поставить восклицательный знак:
Теперь мы к мониторингу локальной сети добавим ещё и мониторинг подключения к Интернет. Запускаем активный поиск локальных хостов:
Устанавливаем значение переменной ticker.commands – там теперь три команды – две уже известные нам внутренние команды bettercap (это clear; net.show;) и ещё один набор системных команд:
При желании, можно увеличить период до трёх секунд (по умолчанию одна секунда):
Запускаем циклическое выполнение задачи:
В результатах выполнения обратите внимание на новую строку «Есть подключение к Интернету»:
Используя знакомую нам опцию -eval это всё можно запустить ещё и таким образом:
Но кроме опции -eval есть ещё опция -caplet, которая также позволяет запустить программу с заданными командами.
Давайте создадим наш первый каплет. Для этого создайте текстовый файл с именем netmon.cap (имя можно выбрать любое):
И просто скопируйте в него все наши команды, которые мы вводили в интерактивной сессии, должен получится файл следующего содержания:
Теперь запустим bettercap с опцией -caplet, после которой укажем путь до файла с каплетом:
Как запустить спуфинг и сниффинг в bettercap
Начнём с запуска ARP-спуфинга:
По умолчанию выполняется атака на всю подсеть, поэтому если ARP-спуфинг работает плохо, то установите IP целей с помощью переменной arp.spoof.targets. Её значением может быть один IP или несколько IP перечисленных через запятую, например:
Как уже было показано выше, чтобы увидеть все хосты в локальной сети и выбрать жертву используется команда:
Значения переменных нужно устанавливать до запуска соответствующего модуля. Если вам нужно поменять значение переменной уже запущенного модуля, то остановите уже запущенный модуль, установите новое значение и вновь запустите модуль, например:
Для сниффера по желанию, можно уменьшить уровень вербальности:
Если вы хотите сохранить захваченные во время сниффинга сетевые пакеты в файл, то в качестве значения net.sniff.output укажите файл для сохранения данных
Транспарентный (прозрачный) HTTP прокси
Для анализа HTTP трафика необходимо включить http.proxy. Если его использовать совместно со спуфером, весь HTTP трафик будет перенаправляться на него и при необходимости он будет автоматически обрабатывать перенаправление портов.
Если вы хотите использовать sslstrip, то необходимо изменить значение переменной http.proxy.sslstrip, которое по умолчанию установлено на false:
Сам прокси включается так:
Полный перечень команд для атаки на локальный IP 192.168.0.90, в результате будет выполняться непрерывный ARP-спуфинг данного адреса, что приведёт к тому, что трафик будет перенаправлен на машину атакующего, на прозрачный HTTP прокси, где, по возможности, с помощью sslstrip будет сделан переход с HTTPS на HTTP, вербальность сниффера понижена, чтобы не выводились не интересующие нас данные:
Для атаки на всю подсеть, из этого списка команд пропустите команду set arp.spoof.targets 192.168.0.90.
DNS-спуфинг в bettercap
За подмену DNS запросов отвечает модуль dns.spoof. Вы можете выполнить настройку перед его запуском.
По умолчанию спуфятся все домены, если вы хотите это изменить, то перечислите их через запятую в качестве значения переменной dns.spoof.domains. Например, я хочу спуфить только два домена suip.biz и mi-al.ru, тогда:
По умолчанию ответы DNS сервера подменяются так, что в каждый из них вставляется IP, указывающий на адрес интерфейса той машины, на которой запущен bettercap. IP адрес меняется через переменную dns.spoof.address:
Этот модуль будет отвечать только на те запросы, которые нацелены на локальный ПК, чтобы отвечать на все установите значение переменной dns.spoof.all на true:
Для запуска модуля:
Встроенный веб-сервер в bettercap
Для обработки запросов к веб-серверу вы можете использовать установленный в вашей системе сервер, например, в Kali Linux установлен Apache и его достаточно только запустить:
В bettercap также встроен простой сервер, который может отдавать HTML страницы и другие статичные файлы, например JavaScript, CSS, картинки и т.п.
Нужно указать адрес папки сервера, изменив значение переменной http.server.path:
О дополнительных опциях для настройки вы узнаете на странице с документацией.
Для запуска сервера (системный сервер, например Apache, должен быть остановлен, поскольку может возникнуть конфликт из-за того, что разные программы пытаются прослушивать один и тот же порт):
Мониторинг Wi-Fi сетей
Это новая функция bettercap. Кстати, ещё добавлена поддержка Bluetooth Low Energy.
Для работы с Wi-Fi нужно использовать опцию -iface, после которой указать имя беспроводного интерфейса:
В случае, если при последующих командах у вас будут возникать ошибки, например, такая:
То выйдете из bettercap и вручную переведите беспроводной интерфейс в режим монитора. Например, следующим образом:
Теперь, когда беспроводной интерфейс в режиме монитора, снова запускаем bettercap и вводим команду:
Она запускает обнаружение Wi-Fi устройств:
Если вы хотите ограничится мониторингом только определённых каналов, то выполните команду вроде этой (она устанавливает переключение только по первым трём каналам):
Кстати, если вам в дальнейшем понадобится очистить список каналов (сделать так, чтобы программа прыгала по всем каналам), то для этого используется следующая команда:
Чтобы показать результаты наберите:
Следующий набор команд запустит сбор информации о Wi-Fi устройствах, будет выводить таблицу с полным перечнем обнаруженных точек доступа, а также список из последних 20 обнаружений:
Захват рукопожатий в bettercap
Да, bettercap теперь умеет и это, причём также умеет выполнять атаку деаутентификация.
Если мы хотим захватить рукопожатие от конкретной точки доступа, то нам нужно знать канал, на котором она работает. В принципе, этого достаточно, если мы собираемся пассивно ожидать, когда клиент подключится/переподключится к ТД.
Для выполнения атаки деаутентификация нам нужно знать BSSID точки доступа (в этом случае атака будет выполняться в отношении всех клиентов) или BSSID клиента (в этом случае атака будет выполнятся в отношении одного клиента).
Начнём с настройки сниффера. Сделаем его вербальным:
Установим фильтр для пакетов рукопожатия:
Настроем сохранение полученных данных в файл wpa.pcap:
Сниффер каждый раз запускается одинаково. Дальнейшие значения переменных зависят от атакуемой цели.
Цель, которую я хочу атаковать, работает на 8 канале, поэтому устанавливаю канал:
Запускаем анализ сети:
Меня интересует ТД с BSSID 50:46:5d:6e:8c:20, можно установить фильтр:
Следующие две команды опциональные, они будут периодически очищать экран и выводить таблицу с увиденными базовыми станциями (можно посмотреть, есть ли вообще у атакуемой Точки Доступа клиенты), если вы этого не хотите, то пропустите эти команды:
Переходим к деаутентификации. Атаку можно выполнять в двух формах:
В первом случае будут деаутентифицироваться все клиенты, во втором – конкретный указанный клиент. Я хочу деаутентифицировать всех клиентов точки доступа, тогда моя команда:
Файл с захваченными фреймами можно открыть для проверки в Wireshark:
Чтобы отфильтровать четырёхэтапные рукопожатия, используйте фильтр:
Кроме bettercap уже существует достаточно программ, которые умеют захватывать рукопожатия. Преимуществом bettercap является то, что мы можем автоматизировать процесс.
К примеру, следующая команда проверяет файл захвата и выводит информацию о рукопожатии(ях) если они там обнаружены:
Чуть более вербальная команда:
Нам нужна эта команда для написания каплета, который будет работать по следующей логике:
- при старте запускает сниффер для захвата четырёхэтапного рукопожатия
- запускает атаку деаутентификации
- проверяет, было ли захвачено рукопожатие
- если рукопожатие захвачено – завершение работы bettercap
- если рукопожатие не захвачено, возврат к шагу 2
Для этого я создаю файл HS_capture_50465d6e8c20.cap со следующим содержимым:
Программа будет работать пока не захватит рукопожатие. Но после захвата рукопожатия, bettercap завершит свою работу и больше не будет беспокоить клиентов сети.
Создание мошеннической точки доступа
Среди Wi-Fi функций имеется возможность создавать мошенническую точку доступа – с шифрованием или без.
Создание поддельной точки доступа "Banana" с BSSID DE:AD:BE:EF:DE:AD на 5 канале без шифрования:
Как можно увидеть – имеется большой простор для автоматизации и различных комбинированных атак, в том числе автоматизированных атак на основе социальной инженерии.
Обзор каплетов bettercap
Как уже было сказано, каплеты размещены в официальном репозитории. Там есть как совсем простые примеры, автоматизирующие несколько типичных действий, так и довольно комплексные реализации современных атак.
Подцепление на BeEF
BeEF – это платформа эксплуатации веб-браузеров. Для начала эксплуатации необходимо внедрить в веб-страницу JavsScript код. Каплеты beef-passive.cap и beef-active.cap делают именно это. Внедрением управляет файл beef-inject.js, поэтому если вы хотите изменить адрес или порт JavsScript файла, то нужно отредактировать именно этот файл.
Перед началом данной атаки вам нужно самостоятельно запустить службу BeEF, либо отредактировать каплеты, добавив туда соответствующую команду.
Первый каплет внедряет пассивно, второй – активно, используя перенаправление трафика с других хостов с помощью ARP-спуфинга.
Внедрение майнера
crypto-miner.cap внедряет майнер (файл). Вам самостоятельно нужно ввести свой ключ, отредактировав файл crypto-miner.js.
Замена загружаемого файла на полезную нагрузку
Каплет download-autopwn.cap в зависимости от атакуемого устройства подсовывает ему подходящий файл. Настройка выполняется в download-autopwn.cap. В паре идёт файл download-autopwn.js, который предназначен НЕ для внедрения в браузер, он используется в качестве скрипта для модуля http.proxy (т.е. управляет поведением bettercap и манипуляцией трафиком).
Если кто-то загрузил полезную нагрузку:
Кража паролей Facebook
Каплет fb-phish.cap показывает фальшивую страницу входа Facebook на 80 порту, прерывает попытки входа, используя http.proxy, печатает учётные данные и перенаправляет цель на реальный Facebook.
В паре идёт файл fb-phish.js, который является скриптом для модуля http.proxy.
Вам самим нужно позаботится о создании фейковой страницы входа и запуске сервера. В этом вам поможет файл с инструкциями Makefile (если у вас скачен репозиторий каплетов, в командной строке Bash выполните):
Затем уже в bettercap:
Сбор HTTP запросов
http-req-dump.cap использует модуль http-req-dump.js, он написан на JavaScript и собирает разнообразные HTTP запросы. Можно комбинировать со сниффингом, для этого раскомментируйте соответствующие строки в файле http-req-dump.cap.
Сбор логинов и паролей с помощью невидимых форм
Суть атаки в следующем: если на сайте вы ранее вводили логин и пароль, то если на странице присутствует форма, браузер автоматически заполняет введённые ранее данные. Firefox делает это сразу, для Chrome требуется любое взаимодействие пользователя – например, клик в любом месте веб-страницы. Эта форма может быть невидимой. Итак, атакующий внедряет на страницы сайта невидимую форму, в которую браузер сам вводит логин и пароль, форма передаёт данные атакующему.
Это реализовано в каплете login-man-abuse.cap.
Имеется демо-страница, на которой вы можете увидеть пример атаки: введите любой e-mail и пароль, затем вас перекинет на другую страницу, которая «угадает», что именно вы ввели ранее.
Перенаправление IPv4 DNS запросов используя DHCPv6 ответы
Примерная суть в том, что в современных версиях Windows система настроена отдавать предпочтение IPv6. Атакующий отвечает DHCPv6 сообщениями, предоставляет системе link-local IPv6 адрес и указывает хост атакующего в качестве DNS сервера. Далее выполняется атака по сценарию DNS-спуфинга.
Атака реализована в mitm6.cap.
Тестирование скрипта http.proxy
Каплет proxy-script-test.cap поможет вам протестировать работу скрипта модуля на JavaScript. В паре идёт файл proxy-script-test.js.
Сниффер паролей
Очень просотой камплет simple-passwords-sniffer.cap. В нём показывается поиск данных по регулярному выражению и сохранение данных в файл, за это отвечают команды:
Изменение строки интерактивной сессии bettercap
Можно настраивать строку, в которую вы вводите команды. В том числе можно показывать в ней полезную информацию. Пример такой настройки с выводом статистики содержится в test-prompt-stats.cap.
Изменение содержимого загружаемых веб-страниц
Каплет web-override.cap переписывает любую загруженную страницу на ту, которую указал атакующий. В паре идёт файл web-override.js, это модуль http.proxy и именно в нём описываются выполняемые действия, например, какую страницу показывать.
Вы можете писать свои собственные каплеты, при желании, интересные примеры можно предлагать для добавления в репозиторий.
Установка bettercap из исходного кода в Kali Linux
Необходимо установить компилятор Go. Подробно процесс установки описан здесь: https://zalinux.ru/?p=1245
Установите необходимые для компиляции пакеты:
Фикс для уже установленной библиотеки:
Скачиваем исходный код, компилируем, устанавливаем:
Чтобы в дальнейшем обновить программу:
Заключение
Как можно увидеть, bettercap из простой и весёлой программы для атак человек-посередине разросся в мощный комбайн для анализа трафика, тестирования и выполнения разнообразных сетевых и беспроводных атак.
Для упрощения рутинных действий можно писать небольшие каплеты в несколько команд – например, для запуска сниффинга в локальной сети, или сбора информации о Wi-Fi сетях.