1 /*        $NetBSD: ieee80211.c,v 1.31 2021/08/13 20:47:55 andvar Exp $          */
2 
3 /*
4  * Copyright (c) 1983, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __RCSID("$NetBSD: ieee80211.c,v 1.31 2021/08/13 20:47:55 andvar Exp $");
35 #endif /* not lint */
36 
37 #include <sys/param.h>
38 #include <sys/ioctl.h>
39 #include <sys/socket.h>
40 
41 #include <net/if.h>
42 #include <net/if_ether.h>
43 #include <net/if_media.h>
44 #include <net/route.h>
45 #include <net80211/ieee80211.h>
46 #include <net80211/ieee80211_ioctl.h>
47 #include <net80211/ieee80211_netbsd.h>
48 
49 #include <assert.h>
50 #include <ctype.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <netdb.h>
54 #include <string.h>
55 #include <stddef.h>
56 #include <stdlib.h>
57 #include <stdio.h>
58 #include <unistd.h>
59 #include <util.h>
60 
61 #include "extern.h"
62 #include "parse.h"
63 #include "env.h"
64 #include "util.h"
65 #include "prog_ops.h"
66 
67 static void ieee80211_statistics(prop_dictionary_t);
68 static void ieee80211_status(prop_dictionary_t, prop_dictionary_t);
69 static void ieee80211_constructor(void) __attribute__((constructor));
70 static int set80211(prop_dictionary_t env, uint16_t, int16_t, int16_t,
71     u_int8_t *);
72 static u_int ieee80211_mhz2ieee(u_int, u_int);
73 static int getmaxrate(const uint8_t [15], u_int8_t);
74 static const char * getcaps(int);
75 static void printie(const char*, const uint8_t *, size_t, int);
76 static int copy_essid(char [], size_t, const u_int8_t *, size_t);
77 static void scan_and_wait(prop_dictionary_t);
78 static void list_scan(prop_dictionary_t);
79 static int mappsb(u_int , u_int);
80 static int mapgsm(u_int , u_int);
81 
82 static int sethidessid(prop_dictionary_t, prop_dictionary_t);
83 static int setapbridge(prop_dictionary_t, prop_dictionary_t);
84 static int setifssid(prop_dictionary_t, prop_dictionary_t);
85 static int setifnwkey(prop_dictionary_t, prop_dictionary_t);
86 static int unsetifnwkey(prop_dictionary_t, prop_dictionary_t);
87 static int unsetifbssid(prop_dictionary_t, prop_dictionary_t);
88 static int setifbssid(prop_dictionary_t, prop_dictionary_t);
89 static int setifchan(prop_dictionary_t, prop_dictionary_t);
90 static int setiffrag(prop_dictionary_t, prop_dictionary_t);
91 static int setifpowersave(prop_dictionary_t, prop_dictionary_t);
92 static int setifpowersavesleep(prop_dictionary_t, prop_dictionary_t);
93 static int setifrts(prop_dictionary_t, prop_dictionary_t);
94 static int scan_exec(prop_dictionary_t, prop_dictionary_t);
95 
96 static void printies(const u_int8_t *, int, int);
97 static void printwmeparam(const char *, const u_int8_t *, size_t , int);
98 static void printwmeinfo(const char *, const u_int8_t *, size_t , int);
99 static const char * wpa_cipher(const u_int8_t *);
100 static const char * wpa_keymgmt(const u_int8_t *);
101 static void printwpaie(const char *, const u_int8_t *, size_t , int);
102 static const char * rsn_cipher(const u_int8_t *);
103 static const char * rsn_keymgmt(const u_int8_t *);
104 static void printrsnie(const char *, const u_int8_t *, size_t , int);
105 static void printssid(const char *, const u_int8_t *, size_t , int);
106 static void printrates(const char *, const u_int8_t *, size_t , int);
107 static void printcountry(const char *, const u_int8_t *, size_t , int);
108 static int iswpaoui(const u_int8_t *);
109 static int iswmeinfo(const u_int8_t *);
110 static int iswmeparam(const u_int8_t *);
111 static const char * iename(int);
112 
113 extern struct pinteger parse_chan, parse_frag, parse_rts;
114 extern struct pstr parse_bssid, parse_ssid, parse_nwkey;
115 extern struct pinteger parse_powersavesleep;
116 
117 static const struct kwinst ieee80211boolkw[] = {
118             {.k_word = "hidessid", .k_key = "hidessid", .k_neg = true,
119              .k_type = KW_T_BOOL, .k_bool = true, .k_negbool = false,
120              .k_exec = sethidessid}
121           , {.k_word = "apbridge", .k_key = "apbridge", .k_neg = true,
122              .k_type = KW_T_BOOL, .k_bool = true, .k_negbool = false,
123              .k_exec = setapbridge}
124           , {.k_word = "powersave", .k_key = "powersave", .k_neg = true,
125              .k_type = KW_T_BOOL, .k_bool = true, .k_negbool = false,
126              .k_exec = setifpowersave}
127 };
128 
129 static const struct kwinst listskw[] = {
130           {.k_word = "scan", .k_exec = scan_exec}
131 };
132 
133 static struct pkw lists = PKW_INITIALIZER(&lists, "ieee80211 lists", NULL,
134     "list", listskw, __arraycount(listskw), &command_root.pb_parser);
135 
136 static const struct kwinst kw80211kw[] = {
137             {.k_word = "bssid", .k_nextparser = &parse_bssid.ps_parser}
138           , {.k_word = "-bssid", .k_exec = unsetifbssid,
139              .k_nextparser = &command_root.pb_parser}
140           , {.k_word = "chan", .k_nextparser = &parse_chan.pi_parser}
141           , {.k_word = "-chan", .k_key = "chan", .k_type = KW_T_UINT,
142              .k_uint = IEEE80211_CHAN_ANY, .k_exec = setifchan,
143              .k_nextparser = &command_root.pb_parser}
144           , {.k_word = "frag", .k_nextparser = &parse_frag.pi_parser}
145           , {.k_word = "-frag", .k_key = "frag", .k_type = KW_T_INT,
146              .k_int = IEEE80211_FRAG_MAX, .k_exec = setiffrag,
147              .k_nextparser = &command_root.pb_parser}
148           , {.k_word = "list", .k_nextparser = &lists.pk_parser}
149           , {.k_word = "nwid", .k_nextparser = &parse_ssid.ps_parser}
150           , {.k_word = "nwkey", .k_nextparser = &parse_nwkey.ps_parser}
151           , {.k_word = "-nwkey", .k_exec = unsetifnwkey,
152              .k_nextparser = &command_root.pb_parser}
153           , {.k_word = "rts", .k_nextparser = &parse_rts.pi_parser}
154           , {.k_word = "-rts", .k_key = "rts", .k_type = KW_T_INT,
155              .k_int = IEEE80211_RTS_MAX, .k_exec = setifrts,
156              .k_nextparser = &command_root.pb_parser}
157           , {.k_word = "ssid", .k_nextparser = &parse_ssid.ps_parser}
158           , {.k_word = "powersavesleep",
159              .k_nextparser = &parse_powersavesleep.pi_parser}
160 };
161 
162 struct pkw kw80211 = PKW_INITIALIZER(&kw80211, "802.11 keywords", NULL, NULL,
163     kw80211kw, __arraycount(kw80211kw), NULL);
164 
165 struct pkw ieee80211bool = PKW_INITIALIZER(&ieee80211bool, "ieee80211 boolean",
166     NULL, NULL, ieee80211boolkw, __arraycount(ieee80211boolkw),
167     &command_root.pb_parser);
168 
169 struct pinteger parse_chan = PINTEGER_INITIALIZER1(&parse_chan, "chan",
170     0, UINT16_MAX, 10, setifchan, "chan", &command_root.pb_parser);
171 
172 struct pinteger parse_rts = PINTEGER_INITIALIZER1(&parse_rts, "rts",
173     IEEE80211_RTS_MIN, IEEE80211_RTS_MAX, 10,
174     setifrts, "rts", &command_root.pb_parser);
175 
176 struct pinteger parse_frag = PINTEGER_INITIALIZER1(&parse_frag, "frag",
177     IEEE80211_FRAG_MIN, IEEE80211_FRAG_MAX, 10,
178     setiffrag, "frag", &command_root.pb_parser);
179 
180 struct pstr parse_ssid = PSTR_INITIALIZER(&parse_pass, "ssid", setifssid,
181     "ssid", &command_root.pb_parser);
182 
183 struct pinteger parse_powersavesleep =
184     PINTEGER_INITIALIZER1(&parse_powersavesleep, "powersavesleep",
185     0, INT_MAX, 10, setifpowersavesleep, "powersavesleep",
186     &command_root.pb_parser);
187 
188 struct pstr parse_nwkey = PSTR_INITIALIZER1(&parse_nwkey, "nwkey", setifnwkey,
189     "nwkey", false, &command_root.pb_parser);
190 
191 struct pstr parse_bssid = PSTR_INITIALIZER1(&parse_bssid, "bssid", setifbssid,
192     "bssid", false, &command_root.pb_parser);
193 
194 static int
set80211(prop_dictionary_t env,uint16_t type,int16_t val,int16_t len,u_int8_t * data)195 set80211(prop_dictionary_t env, uint16_t type, int16_t val, int16_t len,
196     u_int8_t *data)
197 {
198           struct ieee80211req ireq;
199 
200           memset(&ireq, 0, sizeof(ireq));
201           ireq.i_type = type;
202           ireq.i_val = val;
203           ireq.i_len = len;
204           ireq.i_data = data;
205           if (direct_ioctl(env, SIOCS80211, &ireq) == -1) {
206                     warn("SIOCS80211");
207                     return -1;
208           }
209           return 0;
210 }
211 
212 static int
sethidessid(prop_dictionary_t env,prop_dictionary_t oenv)213 sethidessid(prop_dictionary_t env, prop_dictionary_t oenv)
214 {
215           bool on, rc;
216 
217           rc = prop_dictionary_get_bool(env, "hidessid", &on);
218           assert(rc);
219           return set80211(env, IEEE80211_IOC_HIDESSID, on ? 1 : 0, 0, NULL);
220 }
221 
222 static int
setapbridge(prop_dictionary_t env,prop_dictionary_t oenv)223 setapbridge(prop_dictionary_t env, prop_dictionary_t oenv)
224 {
225           bool on, rc;
226 
227           rc = prop_dictionary_get_bool(env, "apbridge", &on);
228           assert(rc);
229           return set80211(env, IEEE80211_IOC_APBRIDGE, on ? 1 : 0, 0, NULL);
230 }
231 
232 static enum ieee80211_opmode
get80211opmode(prop_dictionary_t env)233 get80211opmode(prop_dictionary_t env)
234 {
235           struct ifmediareq ifmr;
236 
237           memset(&ifmr, 0, sizeof(ifmr));
238           if (direct_ioctl(env, SIOCGIFMEDIA, &ifmr) == -1)
239                     ;
240           else if (ifmr.ifm_current & IFM_IEEE80211_ADHOC)
241                     return IEEE80211_M_IBSS;        /* XXX ahdemo */
242           else if (ifmr.ifm_current & IFM_IEEE80211_HOSTAP)
243                     return IEEE80211_M_HOSTAP;
244           else if (ifmr.ifm_current & IFM_IEEE80211_MONITOR)
245                     return IEEE80211_M_MONITOR;
246 
247           return IEEE80211_M_STA;
248 }
249 
250 static int
setifssid(prop_dictionary_t env,prop_dictionary_t oenv)251 setifssid(prop_dictionary_t env, prop_dictionary_t oenv)
252 {
253           struct ieee80211_nwid nwid;
254           ssize_t len;
255 
256           memset(&nwid, 0, sizeof(nwid));
257           if ((len = getargdata(env, "ssid", nwid.i_nwid,
258               sizeof(nwid.i_nwid))) == -1)
259                     errx(EXIT_FAILURE, "%s: SSID too long", __func__);
260           nwid.i_len = (uint8_t)len;
261           if (indirect_ioctl(env, SIOCS80211NWID, &nwid) == -1)
262                     err(EXIT_FAILURE, "SIOCS80211NWID");
263           return 0;
264 }
265 
266 static int
unsetifbssid(prop_dictionary_t env,prop_dictionary_t oenv)267 unsetifbssid(prop_dictionary_t env, prop_dictionary_t oenv)
268 {
269           struct ieee80211_bssid bssid;
270 
271           memset(&bssid, 0, sizeof(bssid));
272 
273           if (direct_ioctl(env, SIOCS80211BSSID, &bssid) == -1)
274                     err(EXIT_FAILURE, "SIOCS80211BSSID");
275           return 0;
276 }
277 
278 static int
setifbssid(prop_dictionary_t env,prop_dictionary_t oenv)279 setifbssid(prop_dictionary_t env, prop_dictionary_t oenv)
280 {
281           char buf[24];
282           struct ieee80211_bssid bssid;
283           struct ether_addr *ea;
284 
285           if (getargstr(env, "bssid", buf, sizeof(buf)) == -1)
286                     errx(EXIT_FAILURE, "%s: BSSID too long", __func__);
287 
288           ea = ether_aton(buf);
289           if (ea == NULL) {
290                     errx(EXIT_FAILURE, "malformed BSSID: %s", buf);
291                     return -1;
292           }
293           memcpy(&bssid.i_bssid, ea->ether_addr_octet,
294               sizeof(bssid.i_bssid));
295 
296           if (direct_ioctl(env, SIOCS80211BSSID, &bssid) == -1)
297                     err(EXIT_FAILURE, "SIOCS80211BSSID");
298           return 0;
299 }
300 
301 static int
setifrts(prop_dictionary_t env,prop_dictionary_t oenv)302 setifrts(prop_dictionary_t env, prop_dictionary_t oenv)
303 {
304           bool rc;
305           int16_t val;
306 
307           rc = prop_dictionary_get_int16(env, "rts", &val);
308           assert(rc);
309           if (set80211(env, IEEE80211_IOC_RTSTHRESHOLD, val, 0, NULL) == -1)
310                     err(EXIT_FAILURE, "IEEE80211_IOC_RTSTHRESHOLD");
311           return 0;
312 }
313 
314 static int
setiffrag(prop_dictionary_t env,prop_dictionary_t oenv)315 setiffrag(prop_dictionary_t env, prop_dictionary_t oenv)
316 {
317           bool rc;
318           int16_t val;
319 
320           rc = prop_dictionary_get_int16(env, "frag", &val);
321           assert(rc);
322           if (set80211(env, IEEE80211_IOC_FRAGTHRESHOLD, val, 0, NULL) == -1)
323                     err(EXIT_FAILURE, "IEEE80211_IOC_FRAGTHRESHOLD");
324           return 0;
325 }
326 
327 static int
setifchan(prop_dictionary_t env,prop_dictionary_t oenv)328 setifchan(prop_dictionary_t env, prop_dictionary_t oenv)
329 {
330           bool rc;
331           struct ieee80211chanreq channel;
332 
333           rc = prop_dictionary_get_uint16(env, "chan", &channel.i_channel);
334           assert(rc);
335           if (direct_ioctl(env, SIOCS80211CHANNEL, &channel) == -1)
336                     err(EXIT_FAILURE, "SIOCS80211CHANNEL");
337           return 0;
338 }
339 
340 static int
setifnwkey(prop_dictionary_t env,prop_dictionary_t oenv)341 setifnwkey(prop_dictionary_t env, prop_dictionary_t oenv)
342 {
343           const char *val;
344           char buf[256];
345           struct ieee80211_nwkey nwkey;
346           int i;
347           u_int8_t keybuf[IEEE80211_WEP_NKID][16];
348 
349           if (getargstr(env, "nwkey", buf, sizeof(buf)) == -1)
350                     errx(EXIT_FAILURE, "%s: nwkey too long", __func__);
351 
352           val = buf;
353 
354           nwkey.i_wepon = IEEE80211_NWKEY_WEP;
355           nwkey.i_defkid = 1;
356           for (i = 0; i < IEEE80211_WEP_NKID; i++) {
357                     nwkey.i_key[i].i_keylen = sizeof(keybuf[i]);
358                     nwkey.i_key[i].i_keydat = keybuf[i];
359           }
360           if (strcasecmp("persist", val) == 0) {
361                     /* use all values from persistent memory */
362                     nwkey.i_wepon |= IEEE80211_NWKEY_PERSIST;
363                     nwkey.i_defkid = 0;
364                     for (i = 0; i < IEEE80211_WEP_NKID; i++)
365                               nwkey.i_key[i].i_keylen = -1;
366           } else if (strncasecmp("persist:", val, 8) == 0) {
367                     val += 8;
368                     /* program keys in persistent memory */
369                     nwkey.i_wepon |= IEEE80211_NWKEY_PERSIST;
370                     goto set_nwkey;
371           } else {
372   set_nwkey:
373                     if (isdigit((unsigned char)val[0]) && val[1] == ':') {
374                               /* specifying a full set of four keys */
375                               nwkey.i_defkid = val[0] - '0';
376                               val += 2;
377                               for (i = 0; i < IEEE80211_WEP_NKID; i++) {
378                                         val = get_string(val, ",", keybuf[i],
379                                             &nwkey.i_key[i].i_keylen, true);
380                                         if (val == NULL) {
381                                                   errno = EINVAL;
382                                                   return -1;
383                                         }
384                               }
385                               if (*val != '\0') {
386                                         errx(EXIT_FAILURE, "SIOCS80211NWKEY: too many keys.");
387                               }
388                     } else {
389                               val = get_string(val, NULL, keybuf[0],
390                                   &nwkey.i_key[0].i_keylen, true);
391                               if (val == NULL) {
392                                         errno = EINVAL;
393                                         return -1;
394                               }
395                               i = 1;
396                     }
397           }
398           for (; i < IEEE80211_WEP_NKID; i++)
399                     nwkey.i_key[i].i_keylen = 0;
400 
401           if (direct_ioctl(env, SIOCS80211NWKEY, &nwkey) == -1)
402                     err(EXIT_FAILURE, "SIOCS80211NWKEY");
403           return 0;
404 }
405 
406 static int
unsetifnwkey(prop_dictionary_t env,prop_dictionary_t oenv)407 unsetifnwkey(prop_dictionary_t env, prop_dictionary_t oenv)
408 {
409           struct ieee80211_nwkey nwkey;
410           int i;
411 
412           nwkey.i_wepon = 0;
413           nwkey.i_defkid = 1;
414           for (i = 0; i < IEEE80211_WEP_NKID; i++) {
415                     nwkey.i_key[i].i_keylen = 0;
416                     nwkey.i_key[i].i_keydat = NULL;
417           }
418 
419           if (direct_ioctl(env, SIOCS80211NWKEY, &nwkey) == -1)
420                     err(EXIT_FAILURE, "SIOCS80211NWKEY");
421           return 0;
422 }
423 
424 static int
setifpowersave(prop_dictionary_t env,prop_dictionary_t oenv)425 setifpowersave(prop_dictionary_t env, prop_dictionary_t oenv)
426 {
427           struct ieee80211_power power;
428           bool on, rc;
429 
430           if (direct_ioctl(env, SIOCG80211POWER, &power) == -1)
431                     err(EXIT_FAILURE, "SIOCG80211POWER");
432 
433           rc = prop_dictionary_get_bool(env, "powersave", &on);
434           assert(rc);
435 
436           power.i_enabled = on ? 1 : 0;
437           if (direct_ioctl(env, SIOCS80211POWER, &power) == -1) {
438                     warn("SIOCS80211POWER");
439                     return -1;
440           }
441           return 0;
442 }
443 
444 static int
setifpowersavesleep(prop_dictionary_t env,prop_dictionary_t oenv)445 setifpowersavesleep(prop_dictionary_t env, prop_dictionary_t oenv)
446 {
447           struct ieee80211_power power;
448           int64_t maxsleep;
449           bool rc;
450 
451           rc = prop_dictionary_get_int64(env, "powersavesleep", &maxsleep);
452           assert(rc);
453 
454           if (direct_ioctl(env, SIOCG80211POWER, &power) == -1)
455                     err(EXIT_FAILURE, "SIOCG80211POWER");
456 
457           power.i_maxsleep = maxsleep;
458           if (direct_ioctl(env, SIOCS80211POWER, &power) == -1)
459                     err(EXIT_FAILURE, "SIOCS80211POWER");
460           return 0;
461 }
462 
463 static int
scan_exec(prop_dictionary_t env,prop_dictionary_t oenv)464 scan_exec(prop_dictionary_t env, prop_dictionary_t oenv)
465 {
466           struct ifreq ifr;
467 
468           if (direct_ioctl(env, SIOCGIFFLAGS, &ifr) == -1) {
469                     warn("ioctl(SIOCGIFFLAGS)");
470                     return -1;
471           }
472 
473           if ((ifr.ifr_flags & IFF_UP) == 0)
474                     errx(EXIT_FAILURE, "The interface must be up before scanning.");
475 
476           scan_and_wait(env);
477           list_scan(env);
478 
479           return 0;
480 }
481 
482 static void
ieee80211_statistics(prop_dictionary_t env)483 ieee80211_statistics(prop_dictionary_t env)
484 {
485 #ifndef SMALL
486           struct ieee80211_stats stats;
487           struct ifreq ifr;
488 
489           memset(&ifr, 0, sizeof(ifr));
490           ifr.ifr_buflen = sizeof(stats);
491           ifr.ifr_buf = (caddr_t)&stats;
492           if (direct_ioctl(env, (zflag) ? SIOCG80211ZSTATS : SIOCG80211STATS,
493               &ifr) == -1)
494                     return;
495 #define   STAT_PRINT(_member, _desc)    \
496           printf("\t" _desc ": %" PRIu32 "\n", stats._member)
497 
498           STAT_PRINT(is_rx_badversion, "rx frame with bad version");
499           STAT_PRINT(is_rx_tooshort, "rx frame too short");
500           STAT_PRINT(is_rx_wrongbss, "rx from wrong bssid");
501           STAT_PRINT(is_rx_dup, "rx discard 'cuz dup");
502           STAT_PRINT(is_rx_wrongdir, "rx w/ wrong direction");
503           STAT_PRINT(is_rx_mcastecho, "rx discard 'cuz mcast echo");
504           STAT_PRINT(is_rx_notassoc, "rx discard 'cuz sta !assoc");
505           STAT_PRINT(is_rx_noprivacy, "rx w/ wep but privacy off");
506           STAT_PRINT(is_rx_unencrypted, "rx w/o wep and privacy on");
507           STAT_PRINT(is_rx_wepfail, "rx wep processing failed");
508           STAT_PRINT(is_rx_decap, "rx decapsulation failed");
509           STAT_PRINT(is_rx_mgtdiscard, "rx discard mgt frames");
510           STAT_PRINT(is_rx_ctl, "rx discard ctrl frames");
511           STAT_PRINT(is_rx_beacon, "rx beacon frames");
512           STAT_PRINT(is_rx_rstoobig, "rx rate set truncated");
513           STAT_PRINT(is_rx_elem_missing, "rx required element missing");
514           STAT_PRINT(is_rx_elem_toobig, "rx element too big");
515           STAT_PRINT(is_rx_elem_toosmall, "rx element too small");
516           STAT_PRINT(is_rx_elem_unknown, "rx element unknown");
517           STAT_PRINT(is_rx_badchan, "rx frame w/ invalid chan");
518           STAT_PRINT(is_rx_chanmismatch, "rx frame chan mismatch");
519           STAT_PRINT(is_rx_nodealloc, "rx frame dropped");
520           STAT_PRINT(is_rx_ssidmismatch, "rx frame ssid mismatch ");
521           STAT_PRINT(is_rx_auth_unsupported, "rx w/ unsupported auth alg");
522           STAT_PRINT(is_rx_auth_fail, "rx sta auth failure");
523           STAT_PRINT(is_rx_auth_countermeasures, "rx auth discard 'cuz CM");
524           STAT_PRINT(is_rx_assoc_bss, "rx assoc from wrong bssid");
525           STAT_PRINT(is_rx_assoc_notauth, "rx assoc w/o auth");
526           STAT_PRINT(is_rx_assoc_capmismatch, "rx assoc w/ cap mismatch");
527           STAT_PRINT(is_rx_assoc_norate, "rx assoc w/ no rate match");
528           STAT_PRINT(is_rx_assoc_badwpaie, "rx assoc w/ bad WPA IE");
529           STAT_PRINT(is_rx_deauth, "rx deauthentication");
530           STAT_PRINT(is_rx_disassoc, "rx disassociation");
531           STAT_PRINT(is_rx_badsubtype, "rx frame w/ unknown subtyp");
532           STAT_PRINT(is_rx_nobuf, "rx failed for lack of buf");
533           STAT_PRINT(is_rx_decryptcrc, "rx decrypt failed on crc");
534           STAT_PRINT(is_rx_ahdemo_mgt, "rx discard ahdemo mgt frame");
535           STAT_PRINT(is_rx_bad_auth, "rx bad auth request");
536           STAT_PRINT(is_rx_unauth, "rx on unauthorized port");
537           STAT_PRINT(is_rx_badkeyid, "rx w/ incorrect keyid");
538           STAT_PRINT(is_rx_ccmpreplay, "rx seq# violation (CCMP)");
539           STAT_PRINT(is_rx_ccmpformat, "rx format bad (CCMP)");
540           STAT_PRINT(is_rx_ccmpmic, "rx MIC check failed (CCMP)");
541           STAT_PRINT(is_rx_tkipreplay, "rx seq# violation (TKIP)");
542           STAT_PRINT(is_rx_tkipformat, "rx format bad (TKIP)");
543           STAT_PRINT(is_rx_tkipmic, "rx MIC check failed (TKIP)");
544           STAT_PRINT(is_rx_tkipicv, "rx ICV check failed (TKIP)");
545           STAT_PRINT(is_rx_badcipher, "rx failed 'cuz key type");
546           STAT_PRINT(is_rx_nocipherctx, "rx failed 'cuz key !setup");
547           STAT_PRINT(is_rx_acl, "rx discard 'cuz acl policy");
548 
549           STAT_PRINT(is_tx_nobuf, "tx failed for lack of buf");
550           STAT_PRINT(is_tx_nonode, "tx failed for no node");
551           STAT_PRINT(is_tx_unknownmgt, "tx of unknown mgt frame");
552           STAT_PRINT(is_tx_badcipher, "tx failed 'cuz key type");
553           STAT_PRINT(is_tx_nodefkey, "tx failed 'cuz no defkey");
554           STAT_PRINT(is_tx_noheadroom, "tx failed 'cuz no space");
555           STAT_PRINT(is_tx_fragframes, "tx frames fragmented");
556           STAT_PRINT(is_tx_frags, "tx fragments created");
557 
558           STAT_PRINT(is_scan_active, "active scans started");
559           STAT_PRINT(is_scan_passive, "passive scans started");
560           STAT_PRINT(is_node_timeout, "nodes timed out inactivity");
561           STAT_PRINT(is_crypto_nomem, "no memory for crypto ctx");
562           STAT_PRINT(is_crypto_tkip, "tkip crypto done in s/w");
563           STAT_PRINT(is_crypto_tkipenmic, "tkip en-MIC done in s/w");
564           STAT_PRINT(is_crypto_tkipdemic, "tkip de-MIC done in s/w");
565           STAT_PRINT(is_crypto_tkipcm, "tkip counter measures");
566           STAT_PRINT(is_crypto_ccmp, "ccmp crypto done in s/w");
567           STAT_PRINT(is_crypto_wep, "wep crypto done in s/w");
568           STAT_PRINT(is_crypto_setkey_cipher, "cipher rejected key");
569           STAT_PRINT(is_crypto_setkey_nokey, "no key index for setkey");
570           STAT_PRINT(is_crypto_delkey, "driver key delete failed");
571           STAT_PRINT(is_crypto_badcipher, "unknown cipher");
572           STAT_PRINT(is_crypto_nocipher, "cipher not available");
573           STAT_PRINT(is_crypto_attachfail, "cipher attach failed");
574           STAT_PRINT(is_crypto_swfallback, "cipher fallback to s/w");
575           STAT_PRINT(is_crypto_keyfail, "driver key alloc failed");
576           STAT_PRINT(is_crypto_enmicfail, "en-MIC failed");
577           STAT_PRINT(is_ibss_capmismatch, "merge failed-cap mismatch");
578           STAT_PRINT(is_ibss_norate, "merge failed-rate mismatch");
579           STAT_PRINT(is_ps_unassoc, "ps-poll for unassoc. sta");
580           STAT_PRINT(is_ps_badaid, "ps-poll w/ incorrect aid");
581           STAT_PRINT(is_ps_qempty, "ps-poll w/ nothing to send");
582           STAT_PRINT(is_ff_badhdr, "fast frame rx'd w/ bad hdr");
583           STAT_PRINT(is_ff_tooshort, "fast frame rx decap error");
584           STAT_PRINT(is_ff_split, "fast frame rx split error");
585           STAT_PRINT(is_ff_decap, "fast frames decap'd");
586           STAT_PRINT(is_ff_encap, "fast frames encap'd for tx");
587           STAT_PRINT(is_rx_badbintval, "rx frame w/ bogus bintval");
588 #endif
589 }
590 
591 static void
ieee80211_status(prop_dictionary_t env,prop_dictionary_t oenv)592 ieee80211_status(prop_dictionary_t env, prop_dictionary_t oenv)
593 {
594           int i, nwkey_verbose;
595           struct ieee80211_nwid nwid;
596           struct ieee80211_nwkey nwkey;
597           struct ieee80211_power power;
598           u_int8_t keybuf[IEEE80211_WEP_NKID][16];
599           struct ieee80211_bssid bssid;
600           struct ieee80211chanreq channel;
601           struct ieee80211req ireq;
602           struct ether_addr ea;
603           static const u_int8_t zero_macaddr[IEEE80211_ADDR_LEN];
604           enum ieee80211_opmode opmode = get80211opmode(env);
605 
606           memset(&bssid, 0, sizeof(bssid));
607           memset(&nwkey, 0, sizeof(nwkey));
608           memset(&nwid, 0, sizeof(nwid));
609           memset(&nwid, 0, sizeof(nwid));
610 
611           if (indirect_ioctl(env, SIOCG80211NWID, &nwid) == -1)
612                     return;
613           if (nwid.i_len > IEEE80211_NWID_LEN) {
614                     errx(EXIT_FAILURE, "SIOCG80211NWID: wrong length of nwid (%d)", nwid.i_len);
615           }
616           printf("\tssid ");
617           print_string(nwid.i_nwid, nwid.i_len);
618 
619           if (opmode == IEEE80211_M_HOSTAP) {
620                     ireq.i_type = IEEE80211_IOC_HIDESSID;
621                     if (direct_ioctl(env, SIOCG80211, &ireq) != -1) {
622                         if (ireq.i_val)
623                                 printf(" [hidden]");
624                         else if (vflag)
625                                 printf(" [shown]");
626                 }
627 
628                     ireq.i_type = IEEE80211_IOC_APBRIDGE;
629                     if (direct_ioctl(env, SIOCG80211, &ireq) != -1) {
630                               if (ireq.i_val)
631                                         printf(" apbridge");
632                               else if (vflag)
633                                         printf(" -apbridge");
634                     }
635         }
636 
637           ireq.i_type = IEEE80211_IOC_RTSTHRESHOLD;
638           if (direct_ioctl(env, SIOCG80211, &ireq) == -1)
639                     ;
640           else if (ireq.i_val < IEEE80211_RTS_MAX)
641                     printf(" rts %d", ireq.i_val);
642           else if (vflag)
643                     printf(" -rts");
644 
645           ireq.i_type = IEEE80211_IOC_FRAGTHRESHOLD;
646           if (direct_ioctl(env, SIOCG80211, &ireq) == -1)
647                     ;
648           else if (ireq.i_val < IEEE80211_FRAG_MAX)
649                     printf(" frag %d", ireq.i_val);
650           else if (vflag)
651                     printf(" -frag");
652 
653           memset(&nwkey, 0, sizeof(nwkey));
654           /* show nwkey only when WEP is enabled */
655           if (direct_ioctl(env, SIOCG80211NWKEY, &nwkey) == -1 ||
656               nwkey.i_wepon == 0) {
657                     printf("\n");
658                     goto skip_wep;
659           }
660 
661           printf(" nwkey ");
662           /* try to retrieve WEP keys */
663           for (i = 0; i < IEEE80211_WEP_NKID; i++) {
664                     nwkey.i_key[i].i_keydat = keybuf[i];
665                     nwkey.i_key[i].i_keylen = sizeof(keybuf[i]);
666           }
667           if (direct_ioctl(env, SIOCG80211NWKEY, &nwkey) == -1) {
668                     printf("*****");
669           } else {
670                     nwkey_verbose = 0;
671                     /* check to see non default key or multiple keys defined */
672                     if (nwkey.i_defkid != 1) {
673                               nwkey_verbose = 1;
674                     } else {
675                               for (i = 1; i < IEEE80211_WEP_NKID; i++) {
676                                         if (nwkey.i_key[i].i_keylen != 0) {
677                                                   nwkey_verbose = 1;
678                                                   break;
679                                         }
680                               }
681                     }
682                     /* check extra ambiguity with keywords */
683                     if (!nwkey_verbose) {
684                               if (nwkey.i_key[0].i_keylen >= 2 &&
685                                   isdigit(nwkey.i_key[0].i_keydat[0]) &&
686                                   nwkey.i_key[0].i_keydat[1] == ':')
687                                         nwkey_verbose = 1;
688                               else if (nwkey.i_key[0].i_keylen >= 7 &&
689                                   strncasecmp("persist",
690                                   (const char *)nwkey.i_key[0].i_keydat, 7) == 0)
691                                         nwkey_verbose = 1;
692                     }
693                     if (nwkey_verbose)
694                               printf("%d:", nwkey.i_defkid);
695                     for (i = 0; i < IEEE80211_WEP_NKID; i++) {
696                               if (i > 0)
697                                         printf(",");
698                               if (nwkey.i_key[i].i_keylen < 0)
699                                         printf("persist");
700                               else
701                                         print_string(nwkey.i_key[i].i_keydat,
702                                             nwkey.i_key[i].i_keylen);
703                               if (!nwkey_verbose)
704                                         break;
705                     }
706           }
707           printf("\n");
708 
709  skip_wep:
710           if (direct_ioctl(env, SIOCG80211POWER, &power) == -1)
711                     goto skip_power;
712           printf("\tpowersave ");
713           if (power.i_enabled)
714                     printf("on (%dms sleep)", power.i_maxsleep);
715           else
716                     printf("off");
717           printf("\n");
718 
719  skip_power:
720           if (direct_ioctl(env, SIOCG80211BSSID, &bssid) == -1)
721                     return;
722           if (direct_ioctl(env, SIOCG80211CHANNEL, &channel) == -1)
723                     return;
724           if (memcmp(bssid.i_bssid, zero_macaddr, IEEE80211_ADDR_LEN) == 0) {
725                     if (channel.i_channel != (u_int16_t)-1)
726                               printf("\tchan %d\n", channel.i_channel);
727           } else {
728                     memcpy(ea.ether_addr_octet, bssid.i_bssid,
729                         sizeof(ea.ether_addr_octet));
730                     printf("\tbssid %s", ether_ntoa(&ea));
731                     if (channel.i_channel != IEEE80211_CHAN_ANY)
732                               printf(" chan %d", channel.i_channel);
733                     printf("\n");
734           }
735 }
736 
737 static void
scan_and_wait(prop_dictionary_t env)738 scan_and_wait(prop_dictionary_t env)
739 {
740           int sroute;
741 
742           sroute = prog_socket(PF_ROUTE, SOCK_RAW, 0);
743           if (sroute < 0) {
744                     warn("socket(PF_ROUTE,SOCK_RAW)");
745                     return;
746           }
747           /* NB: only root can trigger a scan so ignore errors */
748           if (set80211(env, IEEE80211_IOC_SCAN_REQ, 0, 0, NULL) >= 0) {
749                     char buf[2048];
750                     struct if_announcemsghdr *ifan;
751                     struct rt_msghdr *rtm;
752 
753                     do {
754                               if (prog_read(sroute, buf, sizeof(buf)) < 0) {
755                                         warn("read(PF_ROUTE)");
756                                         break;
757                               }
758                               rtm = (struct rt_msghdr *) buf;
759                               if (rtm->rtm_version != RTM_VERSION)
760                                         break;
761                               ifan = (struct if_announcemsghdr *) rtm;
762                     } while (rtm->rtm_type != RTM_IEEE80211 ||
763                         ifan->ifan_what != RTM_IEEE80211_SCAN);
764           }
765           prog_close(sroute);
766 }
767 
768 static int
calc_len(const u_int8_t * cp,int len)769 calc_len(const u_int8_t *cp, int len)
770 {
771           int maxlen = 0, curlen;
772           const struct ieee80211req_scan_result *sr;
773           char buf[IEEE80211_NWID_LEN];
774 
775           while (len >= (int)sizeof(*sr)) {
776                     sr = (const struct ieee80211req_scan_result *)cp;
777                     cp += sr->isr_len;
778                     len -= sr->isr_len;
779                     curlen = copy_essid(buf, sizeof(buf),
780                         (const u_int8_t *)(sr + 1), sr->isr_ssid_len);
781                     if (curlen >= IEEE80211_NWID_LEN)
782                               return IEEE80211_NWID_LEN;
783                     if (curlen > maxlen)
784                               maxlen = curlen;
785           }
786           return maxlen;
787 }
788 
789 static void
list_scan(prop_dictionary_t env)790 list_scan(prop_dictionary_t env)
791 {
792           u_int8_t buf[64*1024 - 1];
793           struct ieee80211req ireq;
794           char ssid[IEEE80211_NWID_LEN+1];
795           const u_int8_t *cp;
796           int len, ssidmax;
797           const struct ieee80211req_scan_result *sr;
798 
799           memset(&ireq, 0, sizeof(ireq));
800           ireq.i_type = IEEE80211_IOC_SCAN_RESULTS;
801           ireq.i_data = buf;
802           ireq.i_len = sizeof(buf);
803           if (direct_ioctl(env, SIOCG80211, &ireq) < 0)
804                     errx(EXIT_FAILURE, "unable to get scan results");
805           len = ireq.i_len;
806           if (len < (int)sizeof(*sr))
807                     return;
808 
809           ssidmax = calc_len(buf, len);
810 
811           printf("%-*.*s  %-17.17s  %4s %4s  %-7s %3s %4s\n"
812                     , ssidmax, ssidmax, "SSID"
813                     , "BSSID"
814                     , "CHAN"
815                     , "RATE"
816                     , "S:N"
817                     , "INT"
818                     , "CAPS"
819           );
820           cp = buf;
821           while (len >= (int)sizeof(*sr)) {
822                     const uint8_t *vp;
823 
824                     sr = (const struct ieee80211req_scan_result *) cp;
825                     vp = (const u_int8_t *)(sr+1);
826                     (void)copy_essid(ssid, sizeof(ssid), vp, sr->isr_ssid_len);
827                     printf("%-*.*s  %s  %3d  %3dM %3d:%-3d  %3d %-4.4s"
828                               , ssidmax, ssidmax, ssid
829                               , ether_ntoa((const struct ether_addr *) sr->isr_bssid)
830                               , ieee80211_mhz2ieee(sr->isr_freq, sr->isr_flags)
831                               , getmaxrate(sr->isr_rates, sr->isr_nrates)
832                               , sr->isr_rssi, sr->isr_noise
833                               , sr->isr_intval
834                               , getcaps(sr->isr_capinfo)
835                     );
836                     printies(vp + sr->isr_ssid_len, sr->isr_ie_len, 24);
837                     printf("\n");
838                     cp += sr->isr_len, len -= sr->isr_len;
839           }
840 }
841 /*
842  * Convert MHz frequency to IEEE channel number.
843  */
844 static u_int
ieee80211_mhz2ieee(u_int isrfreq,u_int isrflags)845 ieee80211_mhz2ieee(u_int isrfreq, u_int isrflags)
846 {
847           if ((isrflags & IEEE80211_CHAN_GSM) || (907 <= isrfreq && isrfreq <= 922))
848                     return mapgsm(isrfreq, isrflags);
849           if (isrfreq == 2484)
850                     return 14;
851           if (isrfreq < 2484)
852                     return (isrfreq - 2407) / 5;
853           if (isrfreq < 5000) {
854                     if (isrflags & (IEEE80211_CHAN_HALF|IEEE80211_CHAN_QUARTER))
855                               return mappsb(isrfreq, isrflags);
856                     else if (isrfreq > 4900)
857                               return (isrfreq - 4000) / 5;
858                     else
859                               return 15 + ((isrfreq - 2512) / 20);
860           }
861           return (isrfreq - 5000) / 5;
862 }
863 
864 static int
getmaxrate(const u_int8_t rates[15],u_int8_t nrates)865 getmaxrate(const u_int8_t rates[15], u_int8_t nrates)
866 {
867           int i, maxrate = -1;
868 
869           for (i = 0; i < nrates; i++) {
870                     int rate = rates[i] & IEEE80211_RATE_VAL;
871                     if (rate > maxrate)
872                               maxrate = rate;
873           }
874           return maxrate / 2;
875 }
876 
877 static const char *
getcaps(int capinfo)878 getcaps(int capinfo)
879 {
880           static char capstring[32];
881           char *cp = capstring;
882 
883           if (capinfo & IEEE80211_CAPINFO_ESS)
884                     *cp++ = 'E';
885           if (capinfo & IEEE80211_CAPINFO_IBSS)
886                     *cp++ = 'I';
887           if (capinfo & IEEE80211_CAPINFO_CF_POLLABLE)
888                     *cp++ = 'c';
889           if (capinfo & IEEE80211_CAPINFO_CF_POLLREQ)
890                     *cp++ = 'C';
891           if (capinfo & IEEE80211_CAPINFO_PRIVACY)
892                     *cp++ = 'P';
893           if (capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)
894                     *cp++ = 'S';
895           if (capinfo & IEEE80211_CAPINFO_PBCC)
896                     *cp++ = 'B';
897           if (capinfo & IEEE80211_CAPINFO_CHNL_AGILITY)
898                     *cp++ = 'A';
899           if (capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)
900                     *cp++ = 's';
901           if (capinfo & IEEE80211_CAPINFO_RSN)
902                     *cp++ = 'R';
903           if (capinfo & IEEE80211_CAPINFO_DSSSOFDM)
904                     *cp++ = 'D';
905           *cp = '\0';
906           return capstring;
907 }
908 
909 static void
printie(const char * tag,const uint8_t * ie,size_t ielen,int maxlen)910 printie(const char* tag, const uint8_t *ie, size_t ielen, int maxlen)
911 {
912           printf("%s", tag);
913 
914           maxlen -= strlen(tag)+2;
915           if ((int)(2*ielen) > maxlen)
916                     maxlen--;
917           printf("<");
918           for (; ielen > 0; ie++, ielen--) {
919                     if (maxlen-- <= 0)
920                               break;
921                     printf("%02x", *ie);
922           }
923           if (ielen != 0)
924                     printf("-");
925           printf(">");
926 }
927 
928 #define LE_READ_2(p)                                                  \
929           ((u_int16_t)                                                \
930            ((((const u_int8_t *)(p))[0]      ) |            \
931             (((const u_int8_t *)(p))[1] <<  8)))
932 #define LE_READ_4(p)                                                  \
933           ((u_int32_t)                                                \
934            ((((const u_int8_t *)(p))[0]      ) |            \
935             (((const u_int8_t *)(p))[1] <<  8) |            \
936             (((const u_int8_t *)(p))[2] << 16) |            \
937             (((const u_int8_t *)(p))[3] << 24)))
938 
939 /*
940  * NB: The decoding routines assume a properly formatted ie
941  *     which should be safe as the kernel only retains them
942  *     if they parse ok.
943  */
944 
945 static void
printwmeparam(const char * tag,const u_int8_t * ie,size_t ielen,int maxlen)946 printwmeparam(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
947 {
948 #define   MS(_v, _f)          (((_v) & _f) >> _f##_S)
949           static const char *acnames[] = { "BE", "BK", "VO", "VI" };
950           const struct ieee80211_wme_param *wme =
951               (const struct ieee80211_wme_param *) ie;
952           int i;
953 
954           printf("%s", tag);
955           if (!vflag)
956                     return;
957           printf("<qosinfo 0x%x", wme->param_qosInfo);
958           ie += offsetof(struct ieee80211_wme_param, params_acParams);
959           for (i = 0; i < WME_NUM_AC; i++) {
960                     const struct ieee80211_wme_acparams *ac =
961                         &wme->params_acParams[i];
962 
963                     printf(" %s[%saifsn %u cwmin %u cwmax %u txop %u]"
964                               , acnames[i]
965                               , MS(ac->acp_aci_aifsn, WME_PARAM_ACM) ? "acm " : ""
966                               , MS(ac->acp_aci_aifsn, WME_PARAM_AIFSN)
967                               , MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMIN)
968                               , MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMAX)
969                               , LE_READ_2(&ac->acp_txop)
970                     );
971           }
972           printf(">");
973 #undef MS
974 }
975 
976 static void
printwmeinfo(const char * tag,const u_int8_t * ie,size_t ielen,int maxlen)977 printwmeinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
978 {
979           printf("%s", tag);
980           if (vflag) {
981                     const struct ieee80211_wme_info *wme =
982                         (const struct ieee80211_wme_info *) ie;
983                     printf("<version 0x%x info 0x%x>",
984                         wme->wme_version, wme->wme_info);
985           }
986 }
987 
988 static const char *
wpa_cipher(const u_int8_t * sel)989 wpa_cipher(const u_int8_t *sel)
990 {
991 #define   WPA_SEL(x)          (((x)<<24)|WPA_OUI)
992           u_int32_t w = LE_READ_4(sel);
993 
994           switch (w) {
995           case WPA_SEL(WPA_CSE_NULL):
996                     return "NONE";
997           case WPA_SEL(WPA_CSE_WEP40):
998                     return "WEP40";
999           case WPA_SEL(WPA_CSE_WEP104):
1000                     return "WEP104";
1001           case WPA_SEL(WPA_CSE_TKIP):
1002                     return "TKIP";
1003           case WPA_SEL(WPA_CSE_CCMP):
1004                     return "AES-CCMP";
1005           }
1006           return "?";                   /* NB: so 1<< is discarded */
1007 #undef WPA_SEL
1008 }
1009 
1010 static const char *
wpa_keymgmt(const u_int8_t * sel)1011 wpa_keymgmt(const u_int8_t *sel)
1012 {
1013 #define   WPA_SEL(x)          (((x)<<24)|WPA_OUI)
1014           u_int32_t w = LE_READ_4(sel);
1015 
1016           switch (w) {
1017           case WPA_SEL(WPA_ASE_8021X_UNSPEC):
1018                     return "8021X-UNSPEC";
1019           case WPA_SEL(WPA_ASE_8021X_PSK):
1020                     return "8021X-PSK";
1021           case WPA_SEL(WPA_ASE_NONE):
1022                     return "NONE";
1023           }
1024           return "?";
1025 #undef WPA_SEL
1026 }
1027 
1028 static void
printwpaie(const char * tag,const u_int8_t * ie,size_t ielen,int maxlen)1029 printwpaie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1030 {
1031           u_int8_t len = ie[1];
1032 
1033           printf("%s", tag);
1034           if (vflag) {
1035                     const char *sep;
1036                     int n;
1037 
1038                     ie += 6, len -= 4;            /* NB: len is payload only */
1039 
1040                     printf("<v%u", LE_READ_2(ie));
1041                     ie += 2, len -= 2;
1042 
1043                     printf(" mc:%s", wpa_cipher(ie));
1044                     ie += 4, len -= 4;
1045 
1046                     /* unicast ciphers */
1047                     n = LE_READ_2(ie);
1048                     ie += 2, len -= 2;
1049                     sep = " uc:";
1050                     for (; n > 0; n--) {
1051                               printf("%s%s", sep, wpa_cipher(ie));
1052                               ie += 4, len -= 4;
1053                               sep = "+";
1054                     }
1055 
1056                     /* key management algorithms */
1057                     n = LE_READ_2(ie);
1058                     ie += 2, len -= 2;
1059                     sep = " km:";
1060                     for (; n > 0; n--) {
1061                               printf("%s%s", sep, wpa_keymgmt(ie));
1062                               ie += 4, len -= 4;
1063                               sep = "+";
1064                     }
1065 
1066                     if (len > 2)                  /* optional capabilities */
1067                               printf(", caps 0x%x", LE_READ_2(ie));
1068                     printf(">");
1069           }
1070 }
1071 
1072 static const char *
rsn_cipher(const u_int8_t * sel)1073 rsn_cipher(const u_int8_t *sel)
1074 {
1075 #define   RSN_SEL(x)          (((x)<<24)|RSN_OUI)
1076           u_int32_t w = LE_READ_4(sel);
1077 
1078           switch (w) {
1079           case RSN_SEL(RSN_CSE_NULL):
1080                     return "NONE";
1081           case RSN_SEL(RSN_CSE_WEP40):
1082                     return "WEP40";
1083           case RSN_SEL(RSN_CSE_WEP104):
1084                     return "WEP104";
1085           case RSN_SEL(RSN_CSE_TKIP):
1086                     return "TKIP";
1087           case RSN_SEL(RSN_CSE_CCMP):
1088                     return "AES-CCMP";
1089           case RSN_SEL(RSN_CSE_WRAP):
1090                     return "AES-OCB";
1091           }
1092           return "?";
1093 #undef WPA_SEL
1094 }
1095 
1096 static const char *
rsn_keymgmt(const u_int8_t * sel)1097 rsn_keymgmt(const u_int8_t *sel)
1098 {
1099 #define   RSN_SEL(x)          (((x)<<24)|RSN_OUI)
1100           u_int32_t w = LE_READ_4(sel);
1101 
1102           switch (w) {
1103           case RSN_SEL(RSN_ASE_8021X_UNSPEC):
1104                     return "8021X-UNSPEC";
1105           case RSN_SEL(RSN_ASE_8021X_PSK):
1106                     return "8021X-PSK";
1107           case RSN_SEL(RSN_ASE_NONE):
1108                     return "NONE";
1109           }
1110           return "?";
1111 #undef RSN_SEL
1112 }
1113 
1114 static void
printrsnie(const char * tag,const u_int8_t * ie,size_t ielen,int maxlen)1115 printrsnie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1116 {
1117           const char *sep;
1118           int n;
1119 
1120           printf("%s", tag);
1121           if (!vflag)
1122                     return;
1123 
1124           ie += 2, ielen -= 2;
1125 
1126           printf("<v%u", LE_READ_2(ie));
1127           ie += 2, ielen -= 2;
1128 
1129           printf(" mc:%s", rsn_cipher(ie));
1130           ie += 4, ielen -= 4;
1131 
1132           /* unicast ciphers */
1133           n = LE_READ_2(ie);
1134           ie += 2, ielen -= 2;
1135           sep = " uc:";
1136           for (; n > 0; n--) {
1137                     printf("%s%s", sep, rsn_cipher(ie));
1138                     ie += 4, ielen -= 4;
1139                     sep = "+";
1140           }
1141 
1142           /* key management algorithms */
1143           n = LE_READ_2(ie);
1144           ie += 2, ielen -= 2;
1145           sep = " km:";
1146           for (; n > 0; n--) {
1147                     printf("%s%s", sep, rsn_keymgmt(ie));
1148                     ie += 4, ielen -= 4;
1149                     sep = "+";
1150           }
1151 
1152           if (ielen > 2)                /* optional capabilities */
1153                     printf(", caps 0x%x", LE_READ_2(ie));
1154           /* XXXPMKID */
1155           printf(">");
1156 }
1157 
1158 /*
1159  * Copy the ssid string contents into buf, truncating to fit.  If the
1160  * ssid is entirely printable then just copy intact.  Otherwise convert
1161  * to hexadecimal.  If the result is truncated then replace the last
1162  * three characters with "...".
1163  */
1164 static int
copy_essid(char buf[],size_t bufsize,const u_int8_t * essid,size_t essid_len)1165 copy_essid(char buf[], size_t bufsize, const u_int8_t *essid, size_t essid_len)
1166 {
1167           const u_int8_t *p;
1168           int printable;
1169           size_t maxlen, i;
1170 
1171           if (essid_len + 1 > bufsize)
1172                     maxlen = bufsize;
1173           else
1174                     maxlen = essid_len + 1;
1175           /* determine printable or not */
1176           printable = 1;
1177           for (i = 0, p = essid; i < essid_len; i++, p++) {
1178                     if (*p < ' ' || *p > 0x7e) {
1179                               printable = 0;
1180                               break;
1181                     }
1182           }
1183           if (!printable) {             /* not printable, print as hex */
1184                     if (bufsize < 3)
1185                               return 0;
1186                     strlcpy(buf, "0x", bufsize);
1187                     bufsize -= 2;
1188                     p = essid;
1189                     for (i = 0; i < maxlen && bufsize >= 2; i++) {
1190                               sprintf(&buf[2+2*i], "%02x", p[i]);
1191                               bufsize -= 2;
1192                     }
1193                     maxlen = i;
1194           } else {
1195                     /* printable, truncate as needed */
1196                     strlcpy(buf, (const char *)essid, maxlen);
1197           }
1198           if (maxlen != essid_len + 1)
1199                     memcpy(&buf[maxlen - 4], "...", 4);
1200           return (int)strlen(buf);
1201 }
1202 
1203 static void
printssid(const char * tag,const u_int8_t * ie,size_t ielen,int maxlen)1204 printssid(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1205 {
1206           char ssid[2*IEEE80211_NWID_LEN+1];
1207 
1208           printf("%s<%.*s>", tag, copy_essid(ssid, maxlen, ie+2, ie[1]), ssid);
1209 }
1210 
1211 static void
printrates(const char * tag,const u_int8_t * ie,size_t ielen,int maxlen)1212 printrates(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1213 {
1214           const char *sep;
1215           size_t i;
1216 
1217           printf("%s", tag);
1218           sep = "<";
1219           for (i = 2; i < ielen; i++) {
1220                     printf("%s%s%d", sep,
1221                         ie[i] & IEEE80211_RATE_BASIC ? "B" : "",
1222                         ie[i] & IEEE80211_RATE_VAL);
1223                     sep = ",";
1224           }
1225           printf(">");
1226 }
1227 
1228 static void
printcountry(const char * tag,const u_int8_t * ie,size_t ielen,int maxlen)1229 printcountry(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1230 {
1231           const struct ieee80211_country_ie *cie =
1232              (const struct ieee80211_country_ie *) ie;
1233           int i, nbands, schan, nchan;
1234 
1235           printf("%s<%c%c%c", tag, cie->cc[0], cie->cc[1], cie->cc[2]);
1236           nbands = (cie->len - 3) / sizeof(cie->band[0]);
1237           for (i = 0; i < nbands; i++) {
1238                     schan = cie->band[i].schan;
1239                     nchan = cie->band[i].nchan;
1240                     if (nchan != 1)
1241                               printf(" %u-%u,%u", schan, schan + nchan-1,
1242                                   cie->band[i].maxtxpwr);
1243                     else
1244                               printf(" %u,%u", schan, cie->band[i].maxtxpwr);
1245           }
1246           printf(">");
1247 }
1248 
1249 /* unaligned little endian access */
1250 #define LE_READ_4(p)                                                  \
1251           ((u_int32_t)                                                \
1252            ((((const u_int8_t *)(p))[0]      ) |            \
1253             (((const u_int8_t *)(p))[1] <<  8) |            \
1254             (((const u_int8_t *)(p))[2] << 16) |            \
1255             (((const u_int8_t *)(p))[3] << 24)))
1256 
1257 static int
iswpaoui(const u_int8_t * frm)1258 iswpaoui(const u_int8_t *frm)
1259 {
1260           return frm[1] > 3 && LE_READ_4(frm+2) == ((WPA_OUI_TYPE<<24)|WPA_OUI);
1261 }
1262 
1263 static int
iswmeinfo(const u_int8_t * frm)1264 iswmeinfo(const u_int8_t *frm)
1265 {
1266           return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
1267                     frm[6] == WME_INFO_OUI_SUBTYPE;
1268 }
1269 
1270 static int
iswmeparam(const u_int8_t * frm)1271 iswmeparam(const u_int8_t *frm)
1272 {
1273           return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
1274                     frm[6] == WME_PARAM_OUI_SUBTYPE;
1275 }
1276 
1277 static const char *
iename(int elemid)1278 iename(int elemid)
1279 {
1280           switch (elemid) {
1281           case IEEE80211_ELEMID_FHPARMS:          return " FHPARMS";
1282           case IEEE80211_ELEMID_CFPARMS:          return " CFPARMS";
1283           case IEEE80211_ELEMID_TIM:    return " TIM";
1284           case IEEE80211_ELEMID_IBSSPARMS:return " IBSSPARMS";
1285           case IEEE80211_ELEMID_CHALLENGE:return " CHALLENGE";
1286           case IEEE80211_ELEMID_PWRCNSTR:         return " PWRCNSTR";
1287           case IEEE80211_ELEMID_PWRCAP: return " PWRCAP";
1288           case IEEE80211_ELEMID_TPCREQ: return " TPCREQ";
1289           case IEEE80211_ELEMID_TPCREP: return " TPCREP";
1290           case IEEE80211_ELEMID_SUPPCHAN:         return " SUPPCHAN";
1291           case IEEE80211_ELEMID_CHANSWITCHANN:return " CSA";
1292           case IEEE80211_ELEMID_MEASREQ:          return " MEASREQ";
1293           case IEEE80211_ELEMID_MEASREP:          return " MEASREP";
1294           case IEEE80211_ELEMID_QUIET:  return " QUIET";
1295           case IEEE80211_ELEMID_IBSSDFS:          return " IBSSDFS";
1296           case IEEE80211_ELEMID_TPC:    return " TPC";
1297           case IEEE80211_ELEMID_CCKM:   return " CCKM";
1298           }
1299           return " ???";
1300 }
1301 
1302 static void
printies(const u_int8_t * vp,int ielen,int maxcols)1303 printies(const u_int8_t *vp, int ielen, int maxcols)
1304 {
1305           while (ielen > 0) {
1306                     switch (vp[0]) {
1307                     case IEEE80211_ELEMID_SSID:
1308                               if (vflag)
1309                                         printssid(" SSID", vp, 2+vp[1], maxcols);
1310                               break;
1311                     case IEEE80211_ELEMID_RATES:
1312                     case IEEE80211_ELEMID_XRATES:
1313                               if (vflag)
1314                                         printrates(vp[0] == IEEE80211_ELEMID_RATES ?
1315                                             " RATES" : " XRATES", vp, 2+vp[1], maxcols);
1316                               break;
1317                     case IEEE80211_ELEMID_DSPARMS:
1318                               if (vflag)
1319                                         printf(" DSPARMS<%u>", vp[2]);
1320                               break;
1321                     case IEEE80211_ELEMID_COUNTRY:
1322                               if (vflag)
1323                                         printcountry(" COUNTRY", vp, 2+vp[1], maxcols);
1324                               break;
1325                     case IEEE80211_ELEMID_ERP:
1326                               if (vflag)
1327                                         printf(" ERP<0x%x>", vp[2]);
1328                               break;
1329                     case IEEE80211_ELEMID_VENDOR:
1330                               if (iswpaoui(vp))
1331                                         printwpaie(" WPA", vp, 2+vp[1], maxcols);
1332                               else if (iswmeinfo(vp))
1333                                         printwmeinfo(" WME", vp, 2+vp[1], maxcols);
1334                               else if (iswmeparam(vp))
1335                                         printwmeparam(" WME", vp, 2+vp[1], maxcols);
1336                               else if (vflag)
1337                                         printie(" VEN", vp, 2+vp[1], maxcols);
1338                               break;
1339                     case IEEE80211_ELEMID_RSN:
1340                               printrsnie(" RSN", vp, 2+vp[1], maxcols);
1341                               break;
1342                     default:
1343                               if (vflag)
1344                                         printie(iename(vp[0]), vp, 2+vp[1], maxcols);
1345                               break;
1346                     }
1347                     ielen -= 2+vp[1];
1348                     vp += 2+vp[1];
1349           }
1350 }
1351 
1352 static int
mapgsm(u_int isrfreq,u_int isrflags)1353 mapgsm(u_int isrfreq, u_int isrflags)
1354 {
1355           isrfreq *= 10;
1356           if (isrflags & IEEE80211_CHAN_QUARTER)
1357                     isrfreq += 5;
1358           else if (isrflags & IEEE80211_CHAN_HALF)
1359                     isrfreq += 10;
1360           else
1361                     isrfreq += 20;
1362           /* NB: there is no 907/20 wide but leave room */
1363           return (isrfreq - 906*10) / 5;
1364 }
1365 
1366 static int
mappsb(u_int isrfreq,u_int isrflags)1367 mappsb(u_int isrfreq, u_int isrflags)
1368 {
1369           return 37 + ((isrfreq * 10) + ((isrfreq % 5) == 2 ? 5 : 0) - 49400) / 5;
1370 }
1371 
1372 static status_func_t status;
1373 static usage_func_t usage;
1374 static statistics_func_t statistics;
1375 static cmdloop_branch_t branch[2];
1376 
1377 static void
ieee80211_usage(prop_dictionary_t env)1378 ieee80211_usage(prop_dictionary_t env)
1379 {
1380           fprintf(stderr,
1381               "\t[ nwid network_id ] [ nwkey network_key | -nwkey ]\n"
1382               "\t[ list scan ]\n"
1383               "\t[ powersave | -powersave ] [ powersavesleep duration ]\n"
1384               "\t[ hidessid | -hidessid ] [ apbridge | -apbridge ]\n");
1385 }
1386 
1387 static void
ieee80211_constructor(void)1388 ieee80211_constructor(void)
1389 {
1390           cmdloop_branch_init(&branch[0], &ieee80211bool.pk_parser);
1391           cmdloop_branch_init(&branch[1], &kw80211.pk_parser);
1392           register_cmdloop_branch(&branch[0]);
1393           register_cmdloop_branch(&branch[1]);
1394           status_func_init(&status, ieee80211_status);
1395           statistics_func_init(&statistics, ieee80211_statistics);
1396           usage_func_init(&usage, ieee80211_usage);
1397           register_status(&status);
1398           register_statistics(&statistics);
1399           register_usage(&usage);
1400 }
1401