|
root / base / usr / src / cmd / cmd-inet / usr.lib / wpad
wpad Plain Text 5354 lines 146.4 KB
   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
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
# Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# Copyright (c) 2018, Joyent, Inc.

PROG =		wpad
MANIFEST =	wpa.xml
OBJS =		wpa_supplicant.o wpa.o wpa_enc.o eloop.o \
		driver_wifi.o l2_packet.o
SRCS =		$(OBJS:%.o=%.c)

include	../../../Makefile.cmd

ROOTMANIFESTDIR = $(ROOTSVCNETWORK)

# The wpa_enc.c file is not ported to the OpenSSL 3.x API yet and so we need to
# make sure the deprecated 1.x API is fully available for it.  Once the
# wpa_enc.c file is adapted for OpenSSL 3.x this should be updated or removed.
# See also https://www.illumos.org/issues/16917
CPPFLAGS +=	-DOPENSSL_API_COMPAT=10101

LDLIBS +=	-ldladm -ldlpi
all install : LDLIBS += -lcrypto

SMOFF += all_func_returns

.KEEP_STATE:

all:		$(PROG)

$(PROG):	$(OBJS)
		$(LINK.c) $(OBJS) -o $@ $(LDLIBS)
		$(POST_PROCESS)

include ../Makefile.lib

install:	all $(ROOTLIBINETPROG) $(ROOTMANIFEST)

check:		$(CHKMANIFEST)

clean:
		$(RM) $(OBJS)

include ../../../Makefile.targ
WPA Supplicant
==============

Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
All Rights Reserved.

Sun elects to license this software under the BSD license.


License
-------

BSD license:

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, 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.

3. Neither the name(s) of the above-listed copyright holder(s) nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"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 COPYRIGHT
OWNER OR CONTRIBUTORS 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.



Features
--------

Supported WPA/IEEE 802.11i features:
- WPA-PSK ("WPA-Personal")
- WPA with EAP (e.g., with RADIUS authentication server) ("WPA-Enterprise")
  Following authentication methods are supported with an integrate IEEE 802.1X
  Supplicant:
  * EAP-TLS
  * EAP-PEAP/MSCHAPv2 (both PEAPv0 and PEAPv1)
  * EAP-PEAP/TLS (both PEAPv0 and PEAPv1)
  * EAP-PEAP/GTC (both PEAPv0 and PEAPv1)
  * EAP-PEAP/OTP (both PEAPv0 and PEAPv1)
  * EAP-PEAP/MD5-Challenge (both PEAPv0 and PEAPv1)
  * EAP-TTLS/EAP-MD5-Challenge
  * EAP-TTLS/EAP-GTC
  * EAP-TTLS/EAP-OTP
  * EAP-TTLS/EAP-MSCHAPv2
  * EAP-TTLS/EAP-TLS
  * EAP-TTLS/MSCHAPv2
  * EAP-TTLS/MSCHAP
  * EAP-TTLS/PAP
  * EAP-TTLS/CHAP
  * EAP-SIM
  * LEAP (note: only with WEP keys, i.e., not for WPA; in addition, LEAP
	requires special support from the driver for IEEE 802.11
	authentication)
  (following methods are supported, but since they do not generate keying
   material, they cannot be used with WPA or IEEE 802.1X WEP keying)
  * EAP-MD5-Challenge
  * EAP-MSCHAPv2
  * EAP-GTC
  * EAP-OTP
  Alternatively, an external program, e.g., Xsupplicant, can be used for EAP
  authentication.
- key management for CCMP, TKIP, WEP104, WEP40
- RSN/WPA2 (IEEE 802.11i)
  * pre-authentication
  * PMKSA caching



Requirements
------------

Current hardware/software requirements:
- Linux kernel 2.4.x or 2.6.x
- Linux Wireless Extensions v15 or newer
- drivers:
	Host AP driver for Prism2/2.5/3 (development snapshot/v0.2.x)
	in Managed mode ('iwconfig wlan0 mode managed'). Please note that
	station firmware version needs to be 1.7.0 or newer to work in
	WPA mode.

	Linuxant DriverLoader (http://www.linuxant.com/driverloader/)
	with Windows NDIS driver for your wlan card supporting WPA.

	Agere Systems Inc. Linux Driver
	(http://www.agere.com/support/drivers/)
	Please note that the driver interface file (driver_hermes.c) and
	hardware specific include files are not included in the
	wpa_supplicant distribution. You will need to copy these from the
	source package of the Agere driver.

	madwifi driver for cards based on Atheros chip set (ar521x)
	(http://sourceforge.net/projects/madwifi/)
	Please note that you will need to modify the wpa_supplicant Makefile
	to use correct path for madwifi driver root directory
	(CFLAGS += -I../madwifi/wpa line in Makefile).

	ATMEL AT76C5XXx driver for USB and PCMCIA cards
	(http://atmelwlandriver.sourceforge.net/).

	Linux ndiswrapper (http://ndiswrapper.sourceforge.net/) with
	Windows NDIS driver.

	In theory, any driver that supports Linux wireless extensions can be
	used with IEEE 802.1X (i.e., not WPA) when using ap_scan=0 option in
	configuration file.

wpa_supplicant was designed to be portable for different drivers and
operating systems. Hopefully, support for more wlan cards will be
added in the future. See developer.txt for more information about the
design of wpa_supplicant and porting to other drivers. One main goal
is to add full WPA/WPA2 support to Linux wireless extensions to allow
new drivers to be supported without having to implement new
driver-specific interface code in wpa_supplicant.

Optional libraries for layer2 packet processing:
- libpcap (tested with 0.7.2, most relatively recent versions assumed to work,
	this is likely to be available with most distributions,
	http://tcpdump.org/)
- libdnet (tested with v1.4, most versions assumed to work,
	http://libdnet.sourceforge.net/)

These libraries are _not_ used in the default build. Instead, internal
Linux specific implementation is used. libpcap/libdnet are more
portable and they can be used by modifying Makefile (define
USE_DNET_PCAP and link with these libraries).


Optional libraries for EAP-TLS, EAP-PEAP, and EAP-TTLS:
- openssl (tested with 0.9.7c and 0.9.7d, assumed to work with most
  relatively recent versions; this is likely to be available with most
  distributions, http://www.openssl.org/)

This library is only needed when EAP-TLS, EAP-PEAP, or EAP-TTLS
support is enabled. WPA-PSK mode does not require this or EAPOL/EAP
implementation. A configuration file, .config, for compilation is
needed to enable IEEE 802.1X/EAPOL and EAP methods. Note that EAP-MD5,
EAP-GTC, EAP-OTP, and EAP-MSCHAPV2 cannot be used alone with WPA, so
they should only be enabled if testing the EAPOL/EAP state
machines. However, there can be used as inner authentication
algorithms with EAP-PEAP and EAP-TTLS.

See Building and installing section below for more detailed
information about the wpa_supplicant build time configuration.



WPA
---

The original security mechanism of IEEE 802.11 standard was not
designed to be strong and has proved to be insufficient for most
networks that require some kind of security. Task group I (Security)
of IEEE 802.11 working group (http://www.ieee802.org/11/) has worked
to address the flaws of the base standard and has in practice
completed its work in May 2004. The IEEE 802.11i amendment to the IEEE
802.11 standard was approved in June 2004 and this amendment is likely
to be published in July 2004.

Wi-Fi Alliance (http://www.wi-fi.org/) used a draft version of the
IEEE 802.11i work (draft 3.0) to define a subset of the security
enhancements that can be implemented with existing wlan hardware. This
is called Wi-Fi Protected Access<TM> (WPA). This has now become a
mandatory component of interoperability testing and certification done
by Wi-Fi Alliance. Wi-Fi provides information about WPA at its web
site (http://www.wi-fi.org/OpenSection/protected_access.asp).

IEEE 802.11 standard defined wired equivalent privacy (WEP) algorithm
for protecting wireless networks. WEP uses RC4 with 40-bit keys,
24-bit initialization vector (IV), and CRC32 to protect against packet
forgery. All these choice have proved to be insufficient: key space is
too small against current attacks, RC4 key scheduling is insufficient
(beginning of the pseudorandom stream should be skipped), IV space is
too small and IV reuse makes attacks easier, there is no replay
protection, and non-keyed authentication does not protect against bit
flipping packet data.

WPA is an intermediate solution for the security issues. It uses
temporal key integrity protocol (TKIP) to replace WEP. TKIP is a
compromise on strong security and possibility to use existing
hardware. It still uses RC4 for the encryption like WEP, but with
per-packet RC4 keys. In addition, it implements replay protection,
keyed packet authentication mechanism (Michael MIC).

Keys can be managed using two different mechanisms. WPA can either use
an external authentication server (e.g., RADIUS) and EAP just like
IEEE 802.1X is using or pre-shared keys without need for additional
servers. Wi-Fi calls these "WPA-Enterprise" and "WPA-Personal",
respectively. Both mechanisms will generate a master session key for
the Authenticator (AP) and Supplicant (client station).

WPA implements a new key handshake (4-Way Handshake and Group Key
Handshake) for generating and exchanging data encryption keys between
the Authenticator and Supplicant. This handshake is also used to
verify that both Authenticator and Supplicant know the master session
key. These handshakes are identical regardless of the selected key
management mechanism (only the method for generating master session
key changes).



IEEE 802.11i / WPA2
-------------------

The design for parts of IEEE 802.11i that were not included in WPA has
finished (May 2004) and this amendment to IEEE 802.11 was approved in
June 2004. Wi-Fi Alliance is using the final IEEE 802.11i as a new
version of WPA called WPA2. This includes, e.g., support for more
robust encryption algorithm (CCMP: AES in Counter mode with CBC-MAC)
to replace TKIP and optimizations for handoff (reduced number of
messages in initial key handshake, pre-authentication, key caching).

Some wireless LAN vendors are already providing support for CCMP in
their WPA products. There is no "official" interoperability
certification for CCMP and/or mixed modes using both TKIP and CCMP, so
some interoperability issues can be expected even though many
combinations seem to be working with equipment from different vendors.
Certification for WPA2 is likely to start during the second half of
2004.



wpa_supplicant
--------------

wpa_supplicant is an implementation of the WPA Supplicant component,
i.e., the part that runs in the client stations. It implements WPA key
negotiation with a WPA Authenticator and EAP authentication with
Authentication Server. In addition, it controls the roaming and IEEE
802.11 authentication/association of the wlan driver.

wpa_supplicant is designed to be a "daemon" program that runs in the
background and acts as the backend component controlling the wireless
connection. wpa_supplicant supports separate frontend programs and an
example text-based frontend, wpa_cli, is included with wpa_supplicant.

Following steps are used when associating with an AP using WPA:

- wpa_supplicant requests the kernel driver to scan neighboring BSSes
- wpa_supplicant selects a BSS based on its configuration
- wpa_supplicant requests the kernel driver to associate with the chosen
  BSS
- If WPA-EAP: integrated IEEE 802.1X Supplicant or external Xsupplicant
  completes EAP authentication with the authentication server (proxied
  by the Authenticator in the AP)
- If WPA-EAP: master key is received from the IEEE 802.1X Supplicant
- If WPA-PSK: wpa_supplicant uses PSK as the master session key
- wpa_supplicant completes WPA 4-Way Handshake and Group Key Handshake
  with the Authenticator (AP)
- wpa_supplicant configures encryption keys for unicast and broadcast
- normal data packets can be transmitted and received



Building and installing
-----------------------

In order to be able to build wpa_supplicant, you will first need to
select which parts of it will be included. This is done by creating a
build time configuration file, .config, in the wpa_supplicant root
directory. Configuration options are text lines using following
format: CONFIG_<option>=y. Lines starting with # are considered
comments and are ignored.

The build time configuration can be used to select only the needed
features and limit the binary size and requirements for external
libraries. The main configuration parts are the selection of which
driver interfaces (e.g., hostap, madwifi, ..) and which authentication
methods (e.g., EAP-TLS, EAP-PEAP, ..) are included.

Following build time configuration options are used to control IEEE
802.1X/EAPOL and EAP state machines and all EAP methods. Including
TLS, PEAP, or TTLS will require linking wpa_supplicant with openssl
library for TLS implementation.

CONFIG_IEEE8021X_EAPOL=y
CONFIG_EAP_MD5=y
CONFIG_MSCHAPV2=y
CONFIG_EAP_TLS=y
CONFIG_EAP_PEAP=y
CONFIG_EAP_TTLS=y
CONFIG_EAP_GTC=y
CONFIG_EAP_OTP=y
CONFIG_EAP_SIM=y
CONFIG_EAP_LEAP=y

Following option can be used to include GSM SIM/USIM interface for GSM
authentication algorithm (for EAP-SIM). This requires pcsc-lite
(http://www.linuxnet.com/) for smart card access.

CONFIG_PCSC=y

Following options can be added to .config to select which driver
interfaces are included. Prism54.org driver is not yet complete and
Hermes driver interface needs to be downloaded from Agere (see above).
Most Linux driver need to include CONFIG_WIRELESS_EXTENSION.

CONFIG_WIRELESS_EXTENSION=y
CONFIG_DRIVER_HOSTAP=y
CONFIG_DRIVER_PRISM54=y
CONFIG_DRIVER_HERMES=y
CONFIG_DRIVER_MADWIFI=y
CONFIG_DRIVER_ATMEL=y
CONFIG_DRIVER_WEXT=y
CONFIG_DRIVER_NDISWRAPPER=y

Following example includes all features and driver interfaces that are
included in the wpa_supplicant package:

CONFIG_DRIVER_HOSTAP=y
CONFIG_DRIVER_PRISM54=y
CONFIG_DRIVER_HERMES=y
CONFIG_DRIVER_MADWIFI=y
CONFIG_DRIVER_ATMEL=y
CONFIG_DRIVER_WEXT=y
CONFIG_DRIVER_NDISWRAPPER=y
CONFIG_WIRELESS_EXTENSION=y
CONFIG_IEEE8021X_EAPOL=y
CONFIG_EAP_MD5=y
CONFIG_MSCHAPV2=y
CONFIG_EAP_TLS=y
CONFIG_EAP_PEAP=y
CONFIG_EAP_TTLS=y
CONFIG_EAP_GTC=y
CONFIG_EAP_OTP=y
CONFIG_EAP_SIM=y
CONFIG_EAP_LEAP=y
CONFIG_PCSC=y

EAP-PEAP and EAP-TTLS will automatically include configured EAP
methods (MD5, OTP, GTC, MSCHAPV2) for inner authentication selection.


After you have created a configuration file, you can build
wpa_supplicant and wpa_cli with 'make' command. You may then install
the binaries to a suitable system directory, e.g., /usr/local/bin.

Example commands:

# build wpa_supplicant and wpa_cli
make
# install binaries (this may need root privileges)
cp wpa_cli wpa_supplicant /usr/local/bin


You will need to make a configuration file, e.g.,
/etc/wpa_supplicant.conf, with network configuration for the networks
you are going to use. Configuration file section below includes
explanation fo the configuration file format and includes various
examples. Once the configuration is ready, you can test whether the
configuration work by first running wpa_supplicant with following
command to start it on foreground with debugging enabled:

wpa_supplicant -iwlan0 -c/etc/wpa_supplicant.conf -d

Assuming everything goes fine, you can start using following command
to start wpa_supplicant on background without debugging:

wpa_supplicant -iwlan0 -c/etc/wpa_supplicant.conf -B

Please note that if you included more than one driver interface in the
build time configuration (.config), you may need to specify which
interface to use by including -D<driver name> option on the command
line. See following section for more details on command line options
for wpa_supplicant.



Command line options
--------------------

usage:
  wpa_supplicant [-BddehLqqvw] -i<ifname> -c<config file> [-D<driver>]

options:
  -B = run daemon in the background
  -d = increase debugging verbosity (-dd even more)
  -e = use external IEEE 802.1X Supplicant (e.g., xsupplicant)
       (this disables the internal Supplicant)
  -h = show this help text
  -L = show license (GPL and BSD)
  -q = decrease debugging verbosity (-qq even less)
  -v = show version
  -w = wait for interface to be added, if needed

drivers:
  hostap = Host AP driver (Intersil Prism2/2.5/3) [default]
	(this can also be used with Linuxant DriverLoader)
  prism54 = Prism54.org driver (Intersil Prism GT/Duette/Indigo)
	not yet fully implemented
  hermes = Agere Systems Inc. driver (Hermes-I/Hermes-II)
  madwifi = MADWIFI 802.11 support (Atheros, etc.)
  atmel = ATMEL AT76C5XXx (USB, PCMCIA)
  wext = Linux wireless extensions (generic)
  ndiswrapper = Linux ndiswrapper

In most common cases, wpa_supplicant is started with

wpa_supplicant -Bw -c/etc/wpa_supplicant.conf -iwlan0

This makes the process fork into background and wait for the wlan0
interface if it is not available at startup time.



Configuration file
------------------

wpa_supplicant is configured using a text file that lists all accepted
networks and security policies, including pre-shared keys. See
example configuration file, wpa_supplicant.conf, for detailed
information about the configuration format and supported fields.

Changes to configuration file can be reloaded be sending SIGHUP signal
to wpa_supplicant ('killall -HUP wpa_supplicant'). Similarily,
reloading can be triggered with 'wpa_cli reconfigure' command.

Configuration file can include one or more network blocks, e.g., one
for each used SSID. wpa_supplicant will automatically select the best
betwork based on the order of network blocks in the configuration
file, network security level (WPA/WPA2 is prefered), and signal
strength.

Example configuration files for some common configurations:

1) WPA-Personal (PSK) as home network and WPA-Enterprise with EAP-TLS as work
   network

# allow frontend (e.g., wpa_cli) to be used by all users in 'wheel' group
ctrl_interface=/var/run/wpa_supplicant
ctrl_interface_group=wheel
#
# home network; allow all valid ciphers
network={
	ssid="home"
	scan_ssid=1
	key_mgmt=WPA-PSK
	psk="very secret passphrase"
}
#
# work network; use EAP-TLS with WPA; allow only CCMP and TKIP ciphers
network={
	ssid="work"
	scan_ssid=1
	key_mgmt=WPA-EAP
	pairwise=CCMP TKIP
	group=CCMP TKIP
	eap=TLS
	identity="user@example.com"
	ca_cert="/etc/cert/ca.pem"
	client_cert="/etc/cert/user.pem"
	private_key="/etc/cert/user.prv"
	private_key_passwd="password"
}


2) WPA-RADIUS/EAP-PEAP/MSCHAPv2 with RADIUS servers that use old peaplabel
   (e.g., Funk Odyssey and SBR, Meetinghouse Aegis, Interlink RAD-Series)

ctrl_interface=/var/run/wpa_supplicant
ctrl_interface_group=wheel
network={
	ssid="example"
	scan_ssid=1
	key_mgmt=WPA-EAP
	eap=PEAP
	identity="user@example.com"
	password="foobar"
	ca_cert="/etc/cert/ca.pem"
	phase1="peaplabel=0"
	phase2="auth=MSCHAPV2"
}


3) EAP-TTLS/EAP-MD5-Challenge configuration with anonymous identity for the
   unencrypted use. Real identity is sent only within an encrypted TLS tunnel.

ctrl_interface=/var/run/wpa_supplicant
ctrl_interface_group=wheel
network={
	ssid="example"
	scan_ssid=1
	key_mgmt=WPA-EAP
	eap=TTLS
	identity="user@example.com"
	anonymous_identity="anonymous@example.com"
	password="foobar"
	ca_cert="/etc/cert/ca.pem"
	phase2="auth=MD5"
}


4) IEEE 802.1X (i.e., no WPA) with dynamic WEP keys (require both unicast and
   broadcast); use EAP-TLS for authentication

ctrl_interface=/var/run/wpa_supplicant
ctrl_interface_group=wheel
network={
	ssid="1x-test"
	scan_ssid=1
	key_mgmt=IEEE8021X
	eap=TLS
	identity="user@example.com"
	ca_cert="/etc/cert/ca.pem"
	client_cert="/etc/cert/user.pem"
	private_key="/etc/cert/user.prv"
	private_key_passwd="password"
	eapol_flags=3
}


5) Catch all example that allows more or less all configuration modes. The
   configuration options are used based on what security policy is used in the
   selected SSID. This is mostly for testing and is not recommended for normal
   use.

ctrl_interface=/var/run/wpa_supplicant
ctrl_interface_group=wheel
network={
	ssid="example"
	scan_ssid=1
	key_mgmt=WPA-EAP WPA-PSK IEEE8021X NONE
	pairwise=CCMP TKIP
	group=CCMP TKIP WEP104 WEP40
	psk="very secret passphrase"
	eap=TTLS PEAP TLS
	identity="user@example.com"
	password="foobar"
	ca_cert="/etc/cert/ca.pem"
	client_cert="/etc/cert/user.pem"
	private_key="/etc/cert/user.prv"
	private_key_passwd="password"
	phase1="peaplabel=0"
	ca_cert2="/etc/cert/ca2.pem"
	client_cert2="/etc/cer/user.pem"
	private_key2="/etc/cer/user.prv"
	private_key2_passwd="password"
}



Certificates
------------

Some EAP authentication methods require use of certificates. EAP-TLS
uses both server side and client certificates whereas EAP-PEAP and
EAP-TTLS only require the server side certificate. When client
certificate is used, a matching private key file has to also be
included in configuration. If the private key uses a passphrase, this
has to be configured in wpa_supplicant.conf ("private_key_passwd").

wpa_supplicant supports X.509 certificates in PEM and DER
formats. User certificate and private key can be included in the same
file.

If the user certificate and private key is received in PKCS#12/PFX
format, they need to be converted to suitable PEM/DER format for
wpa_supplicant. This can be done, e.g., with following commands:

# convert client certificate and private key to PEM format
openssl pkcs12 -in example.pfx -out user.pem -clcerts
# convert CA certificate (if included in PFX file) to PEM format
openssl pkcs12 -in example.pfx -out ca.pem -cacerts -nokeys



wpa_cli
-------

wpa_cli is a text-based frontend program for interacting with
wpa_supplicant. It is used to query current status, change
configuration, trigger events, and request interactive user input.

wpa_cli can show the current authentication status, selected security
mode, dot11 and dot1x MIBs, etc. In addition, it can configuring some
variables like EAPOL state machine parameters and trigger events like
reassociation and IEEE 802.1X logoff/logon. wpa_cli provides a user
interface to request authentication information, like username and
password, if these are not included in the configuration. This can be
used to implement, e.g., one-time-passwords or generic token card
authentication where the authentication is based on a
challenge-response that uses an external device for generating the
response.

The control interface of wpa_supplicant can be configured to allow
non-root user access (ctrl_interface_group in the configuration
file). This makes it possible to run wpa_cli with a normal user
account.

wpa_cli supports two modes: interactive and command line. Both modes
share the same command set and the main difference is in interactive
mode providing access to unsolicited messages (event messages,
username/password requests).

Interactive mode is started when wpa_cli is executed without including
the command as a command line parameter. Commands are then entered on
the wpa_cli prompt. In command line mode, the same commands are
entered as command line arguments for wpa_cli.


Interactive authentication parameters request

When wpa_supplicant need authentication parameters, like username and
password, which are not present in the configuration file, it sends a
request message to all attached frontend programs, e.g., wpa_cli in
interactive mode. wpa_cli shows these requests with
"CTRL-REQ-<type>-<id>:<text>" prefix. <type> is IDENTITY, PASSWORD, or
OTP (one-time-password). <id> is a unique identifier for the current
network. <text> is description of the request. In case of OTP request,
it includes the challenge from the authentication server.

The reply to these requests can be given with 'identity', 'password',
and 'otp' commands. <id> needs to be copied from the the matching
request. 'password' and 'otp' commands can be used regardless of
whether the request was for PASSWORD or OTP. The main difference
between these two commands is that values given with 'password' are
remembered as long as wpa_supplicant is running whereas values given
with 'otp' are used only once and then forgotten, i.e., wpa_supplicant
will ask frontend for a new value for every use. This can be used to
implement one-time-password lists and generic token card -based
authentication.

Example request for password and a matching reply:

CTRL-REQ-PASSWORD-1:Password needed for SSID foobar
> password 1 mysecretpassword

Example request for generic token card challenge-response:

CTRL-REQ-OTP-2:Challenge 1235663 needed for SSID foobar
> otp 2 9876


wpa_cli commands

  status = get current WPA/EAPOL/EAP status
  mib = get MIB variables (dot1x, dot11)
  help = show this usage help
  interface [ifname] = show interfaces/select interface
  level <debug level> = change debug level
  license = show full wpa_cli license
  logoff = IEEE 802.1X EAPOL state machine logoff
  logon = IEEE 802.1X EAPOL state machine logon
  set = set variables (shows list of variables when run without arguments)
  pmksa = show PMKSA cache
  reassociate = force reassociation
  reconfigure = force wpa_supplicant to re-read its configuration file
  preauthenticate <BSSID> = force preauthentication
  identity <network id> <identity> = configure identity for an SSID
  password <network id> <password> = configure password for an SSID
  otp <network id> <password> = configure one-time-password for an SSID
  quit = exit wpa_cli



Integrating with pcmcia-cs/cardmgr scripts
------------------------------------------

wpa_supplicant needs to be running when using a wireless network with
WPA. It can be started either from system startup scripts or from
pcmcia-cs/cardmgr scripts (when using PC Cards). WPA handshake must be
completed before data frames can be exchanged, so wpa_supplicant
should be started before DHCP client.

Command line option '-w' can be used if wpa_supplicant is started
before the wireless LAN interface is present (e.g., before inserting
the PC Card) or is not yet up.

For example, following small changes to pcmcia-cs scripts can be used
to enable WPA support:

Add MODE="Managed" and WPA="y" to the network scheme in
/etc/pcmcia/wireless.opts.

Add the following block to the end of 'start' action handler in
/etc/pcmcia/wireless:

    if [ "$WPA" = "y" -a -x /usr/local/bin/wpa_supplicant ]; then
	/usr/local/bin/wpa_supplicant -Bw -c/etc/wpa_supplicant.conf \
		-i$DEVICE
    fi

Add the following block to the end of 'stop' action handler (may need
to be separated from other actions) in /etc/pcmcia/wireless:

    if [ "$WPA" = "y" -a -x /usr/local/bin/wpa_supplicant ]; then
	killall wpa_supplicant
    fi

This will make cardmgr start wpa_supplicant when the card is plugged
in. wpa_supplicant will wait until the interface is set up--either
when a static IP address is configured or when DHCP client is
started--and will then negotiate keys with the AP.



Optional integration with Xsupplicant
-------------------------------------

wpa_supplicant has an integrated IEEE 802.1X Supplicant that supports
most commonly used EAP methods. In addition, wpa_supplicant has an
experimental interface for integrating it with Xsupplicant
(http://www.open1x.org/) for the WPA with EAP authentication.

Xsupplicant needs to be modified to send master session key to
wpa_supplicant after successful EAP authentication. The included patch
(xsupplicant.patch) shows the changes needed. This was merged into
xsupplicant CVS on February 6, 2004, so any snapshot after that should
have the needed functionality already included.

When using WPA-EAP, both wpa_supplicant and Xsupplicant must be
configured with the network security policy. See Xsupplicant documents
for information about its configuration. Please also note, that a new
command line option -W (enable WPA; added by xsupplicant.patch) must
be used when starting xsupplicant.

Example configuration for xsupplicant:

network_list = all
default_netname = jkm

jkm
{
	type = wireless
	allow_types = eap_peap
	identity = <BEGIN_ID>jkm<END_ID>
	eap-peap {
		random_file = /dev/urandom
		root_cert = /home/jkm/CA.pem
		chunk_size = 1398
		allow_types = eap_mschapv2
		eap-mschapv2 {
			username = <BEGIN_UNAME>jkm<END_UNAME>
			password = <BEGIN_PASS>jkm<END_PASS>
		}
	}
}


Example configuration for wpa_supplicant:

network={
	ssid="jkm"
	key_mgmt=WPA-EAP
}


Both wpa_supplicant and xsupplicant need to be started. Please remember
to add '-W' option for xsupplicant in order to provide keying material
for wpa_supplicant and '-e' option for wpa_supplicant to disable internal
IEEE 802.1X implementation.

wpa_supplicant -iwlan0 -cwpa_supplicant.conf -e
xsupplicant -iwlan0 -cxsupplicant.conf -W
WPA Supplicant
==============

Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
All Rights Reserved.

Sun elects to license this software under the BSD license.


License
-------

BSD license:

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, 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.

3. Neither the name(s) of the above-listed copyright holder(s) nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"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 COPYRIGHT
OWNER OR CONTRIBUTORS 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.

/*
 * Copyright (c) 2004, Sam Leffler <sam@errno.com>
 * Sun elects to license this software under the BSD license.
 * See README for more details.
 */
PORTIONS OF WPA FUNCTIONALITY
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
 * Sun elects to license this software under the BSD license.
 * See README for more details.
 */
#ifndef __DRIVER_H
#define	__DRIVER_H

#include <libdlwlan.h>
#include <libdllink.h>

#ifdef	__cplusplus
extern "C" {
#endif

typedef enum { WPA_ALG_NONE, WPA_ALG_WEP, WPA_ALG_TKIP, WPA_ALG_CCMP } wpa_alg;
typedef enum { CIPHER_NONE, CIPHER_WEP40, CIPHER_TKIP, CIPHER_CCMP,
	CIPHER_WEP104 } wpa_cipher;
typedef enum { KEY_MGMT_802_1X, KEY_MGMT_PSK, KEY_MGMT_NONE } wpa_key_mgmt;

struct wpa_driver_ops {
	int (*get_bssid)(dladm_handle_t, datalink_id_t, char *);
	int (*get_ssid)(dladm_handle_t, datalink_id_t, char *);
	int (*set_wpa)(dladm_handle_t, datalink_id_t, boolean_t);
	int (*set_key)(dladm_handle_t, datalink_id_t, wpa_alg, uint8_t *,
	    int, boolean_t, uint8_t *, uint32_t, uint8_t *, uint32_t);
	int (*scan)(dladm_handle_t, datalink_id_t);
	int (*get_scan_results)(dladm_handle_t, datalink_id_t,
	    dladm_wlan_ess_t *, uint32_t);
	int (*disassociate)(dladm_handle_t, datalink_id_t, int);
	int (*associate)(dladm_handle_t, datalink_id_t, const char *, uint8_t *,
	    uint32_t);
};

#ifdef __cplusplus
}
#endif

#endif /* __DRIVER_H */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2004, Sam Leffler <sam@errno.com>
 * Sun elects to license this software under the BSD license.
 * See README for more details.
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdarg.h>
#include <fcntl.h>
#include <unistd.h>
#include <stropts.h>
#include <string.h>
#include <stddef.h>

#include "wpa_impl.h"
#include "driver.h"

#define	WPA_STATUS(status)	(status == DLADM_STATUS_OK? 0 : -1)

/*
 * get_bssid - get the current BSSID
 * @linkid: linkid of the given interface
 * @bssid: buffer for BSSID (IEEE80211_ADDR_LEN = 6 bytes)
 *
 * Returns: 0 on success, -1 on failure
 *
 * Query kernel driver for the current BSSID and copy it to @bssid.
 * Setting @bssid to 00:00:00:00:00:00 is recommended if the STA is not
 * associated.
 */
int
wpa_driver_wifi_get_bssid(dladm_handle_t handle, datalink_id_t linkid,
    char *bssid)
{
	dladm_status_t status;
	dladm_wlan_linkattr_t attr;
	dladm_wlan_attr_t *wl_attrp;

	status = dladm_wlan_get_linkattr(handle, linkid, &attr);
	if (status != DLADM_STATUS_OK)
		return (-1);

	wl_attrp = &attr.la_wlan_attr;
	if ((attr.la_valid & DLADM_WLAN_LINKATTR_WLAN) == 0 ||
	    (wl_attrp->wa_valid & DLADM_WLAN_ATTR_BSSID) == 0)
		return (-1);

	(void) memcpy(bssid, wl_attrp->wa_bssid.wb_bytes, DLADM_WLAN_BSSID_LEN);

	wpa_printf(MSG_DEBUG, "wpa_driver_wifi_get_bssid: " MACSTR,
	    MAC2STR((unsigned char *)bssid));

	return (WPA_STATUS(status));
}

/*
 * get_ssid - get the current SSID
 * @linkid: linkid of the given interface
 * @ssid: buffer for SSID (at least 32 bytes)
 *
 * Returns: length of the SSID on success, -1 on failure
 *
 * Query kernel driver for the current SSID and copy it to @ssid.
 * Returning zero is recommended if the STA is not associated.
 */
int
wpa_driver_wifi_get_ssid(dladm_handle_t handle, datalink_id_t linkid,
    char *ssid)
{
	int ret;
	dladm_status_t status;
	dladm_wlan_linkattr_t attr;
	dladm_wlan_attr_t *wl_attrp;

	status = dladm_wlan_get_linkattr(handle, linkid, &attr);
	if (status != DLADM_STATUS_OK)
		return (-1);

	wl_attrp = &attr.la_wlan_attr;
	if ((attr.la_valid & DLADM_WLAN_LINKATTR_WLAN) == 0 ||
	    (wl_attrp->wa_valid & DLADM_WLAN_ATTR_ESSID) == 0)
		return (-1);

	(void) memcpy(ssid, wl_attrp->wa_essid.we_bytes, MAX_ESSID_LENGTH);
	ret = strlen(ssid);

	wpa_printf(MSG_DEBUG, "wpa_driver_wifi_get_ssid: ssid=%s len=%d",
	    ssid, ret);

	return (ret);
}

static int
wpa_driver_wifi_set_wpa_ie(dladm_handle_t handle, datalink_id_t linkid,
    uint8_t *wpa_ie, uint32_t wpa_ie_len)
{
	dladm_status_t status;

	wpa_printf(MSG_DEBUG, "%s", "wpa_driver_wifi_set_wpa_ie");
	status = dladm_wlan_wpa_set_ie(handle, linkid, wpa_ie, wpa_ie_len);

	return (WPA_STATUS(status));
}

/*
 * set_wpa - enable/disable WPA support
 * @linkid: linkid of the given interface
 * @enabled: 1 = enable, 0 = disable
 *
 * Returns: 0 on success, -1 on failure
 *
 * Configure the kernel driver to enable/disable WPA support. This may
 * be empty function, if WPA support is always enabled. Common
 * configuration items are WPA IE (clearing it when WPA support is
 * disabled), Privacy flag for capability field, roaming mode (need to
 * allow wpa_supplicant to control roaming).
 */
static int
wpa_driver_wifi_set_wpa(dladm_handle_t handle, datalink_id_t linkid,
    boolean_t enabled)
{
	dladm_status_t status;

	wpa_printf(MSG_DEBUG, "wpa_driver_wifi_set_wpa: enable=%d", enabled);

	if (!enabled && wpa_driver_wifi_set_wpa_ie(handle, linkid, NULL, 0) < 0)
		return (-1);

	status = dladm_wlan_wpa_set_wpa(handle, linkid, enabled);

	return (WPA_STATUS(status));
}

static int
wpa_driver_wifi_del_key(dladm_handle_t handle, datalink_id_t linkid,
    int key_idx, unsigned char *addr)
{
	dladm_status_t status;
	dladm_wlan_bssid_t bss;

	wpa_printf(MSG_DEBUG, "%s: id=%d", "wpa_driver_wifi_del_key",
	    key_idx);

	(void) memcpy(bss.wb_bytes, addr, DLADM_WLAN_BSSID_LEN);
	status = dladm_wlan_wpa_del_key(handle, linkid, key_idx, &bss);

	return (WPA_STATUS(status));
}

/*
 * set_key - configure encryption key
 * @linkid: linkid of the given interface
 * @alg: encryption algorithm (%WPA_ALG_NONE, %WPA_ALG_WEP,
 *	%WPA_ALG_TKIP, %WPA_ALG_CCMP); %WPA_ALG_NONE clears the key.
 * @addr: address of the peer STA or ff:ff:ff:ff:ff:ff for
 *	broadcast/default keys
 * @key_idx: key index (0..3), always 0 for unicast keys
 * @set_tx: configure this key as the default Tx key (only used when
 *	driver does not support separate unicast/individual key
 * @seq: sequence number/packet number, @seq_len octets, the next
 *	packet number to be used for in replay protection; configured
 *	for Rx keys (in most cases, this is only used with broadcast
 *	keys and set to zero for unicast keys)
 * @seq_len: length of the @seq, depends on the algorithm:
 *	TKIP: 6 octets, CCMP: 6 octets
 * @key: key buffer; TKIP: 16-byte temporal key, 8-byte Tx Mic key,
 *	8-byte Rx Mic Key
 * @key_len: length of the key buffer in octets (WEP: 5 or 13,
 *	TKIP: 32, CCMP: 16)
 *
 * Returns: 0 on success, -1 on failure
 *
 * Configure the given key for the kernel driver. If the driver
 * supports separate individual keys (4 default keys + 1 individual),
 * @addr can be used to determine whether the key is default or
 * individual. If only 4 keys are supported, the default key with key
 * index 0 is used as the individual key. STA must be configured to use
 * it as the default Tx key (@set_tx is set) and accept Rx for all the
 * key indexes. In most cases, WPA uses only key indexes 1 and 2 for
 * broadcast keys, so key index 0 is available for this kind of
 * configuration.
 */
static int
wpa_driver_wifi_set_key(dladm_handle_t handle, datalink_id_t linkid,
    wpa_alg alg, unsigned char *addr, int key_idx, boolean_t set_tx,
    uint8_t *seq, uint32_t seq_len, uint8_t *key, uint32_t key_len)
{
	char *alg_name;
	dladm_wlan_cipher_t cipher;
	dladm_wlan_bssid_t bss;
	dladm_status_t status;

	wpa_printf(MSG_DEBUG, "%s", "wpa_driver_wifi_set_key");
	if (alg == WPA_ALG_NONE)
		return (wpa_driver_wifi_del_key(handle, linkid, key_idx, addr));

	switch (alg) {
	case WPA_ALG_WEP:
		alg_name = "WEP";
		cipher = DLADM_WLAN_CIPHER_WEP;
		break;
	case WPA_ALG_TKIP:
		alg_name = "TKIP";
		cipher = DLADM_WLAN_CIPHER_TKIP;
		break;
	case WPA_ALG_CCMP:
		alg_name = "CCMP";
		cipher = DLADM_WLAN_CIPHER_AES_CCM;
		break;
	default:
		wpa_printf(MSG_DEBUG, "wpa_driver_wifi_set_key:"
		    " unknown/unsupported algorithm %d", alg);
		return (-1);
	}

	wpa_printf(MSG_DEBUG, "wpa_driver_wifi_set_key: alg=%s key_idx=%d"
	    " set_tx=%d seq_len=%d seq=%d key_len=%d",
	    alg_name, key_idx, set_tx,
	    seq_len, *(uint64_t *)(uintptr_t)seq, key_len);

	if (seq_len > sizeof (uint64_t)) {
		wpa_printf(MSG_DEBUG, "wpa_driver_wifi_set_key:"
		    " seq_len %d too big", seq_len);
		return (-1);
	}
	(void) memcpy(bss.wb_bytes, addr, DLADM_WLAN_BSSID_LEN);

	status = dladm_wlan_wpa_set_key(handle, linkid, cipher, &bss, set_tx,
	    *(uint64_t *)(uintptr_t)seq, key_idx, key, key_len);

	return (WPA_STATUS(status));
}

/*
 * disassociate - request driver to disassociate
 * @linkid: linkid of the given interface
 * @reason_code: 16-bit reason code to be sent in the disassociation
 * frame
 *
 * Return: 0 on success, -1 on failure
 */
static int
wpa_driver_wifi_disassociate(dladm_handle_t handle, datalink_id_t linkid,
    int reason_code)
{
	dladm_status_t status;

	wpa_printf(MSG_DEBUG, "wpa_driver_wifi_disassociate");

	status = dladm_wlan_wpa_set_mlme(handle, linkid,
	    DLADM_WLAN_MLME_DISASSOC, reason_code, NULL);

	return (WPA_STATUS(status));
}

/*
 * associate - request driver to associate
 * @linkid: linkid of the given interface
 * @bssid: BSSID of the selected AP
 * @wpa_ie: WPA information element to be included in (Re)Association
 *	Request (including information element id and length). Use of
 *	this WPA IE is optional. If the driver generates the WPA IE, it
 *	can use @pairwise_suite, @group_suite, and @key_mgmt_suite
 *	to select proper algorithms. In this case, the driver has to
 *	notify wpa_supplicant about the used WPA IE by generating an
 *	event that the interface code will convert into EVENT_ASSOCINFO
 *	data (see wpa_supplicant.h). When using WPA2/IEEE 802.11i,
 *	@wpa_ie is used for RSN IE instead. The driver can determine
 *	which version is used by looking at the first byte of the IE
 *	(0xdd for WPA, 0x30 for WPA2/RSN).
 * @wpa_ie_len: length of the @wpa_ie
 *
 * Return: 0 on success, -1 on failure
 */
static int
wpa_driver_wifi_associate(dladm_handle_t handle, datalink_id_t linkid,
    const char *bssid, uint8_t *wpa_ie, uint32_t wpa_ie_len)
{
	dladm_status_t status;
	dladm_wlan_bssid_t bss;

	wpa_printf(MSG_DEBUG, "wpa_driver_wifi_associate : "
	    MACSTR, MAC2STR(bssid));

	/*
	 * NB: Don't need to set the freq or cipher-related state as
	 * this is implied by the bssid which is used to locate
	 * the scanned node state which holds it.
	 */
	if (wpa_driver_wifi_set_wpa_ie(handle, linkid, wpa_ie, wpa_ie_len) < 0)
		return (-1);

	(void) memcpy(bss.wb_bytes, bssid, DLADM_WLAN_BSSID_LEN);
	status = dladm_wlan_wpa_set_mlme(handle, linkid, DLADM_WLAN_MLME_ASSOC,
	    0, &bss);

	return (WPA_STATUS(status));
}

/*
 * scan - request the driver to initiate scan
 * @linkid: linkid of the given interface
 *
 * Return: 0 on success, -1 on failure
 *
 * Once the scan results are ready, the driver should report scan
 * results event for wpa_supplicant which will eventually request the
 * results with wpa_driver_get_scan_results().
 */
static int
wpa_driver_wifi_scan(dladm_handle_t handle, datalink_id_t linkid)
{
	dladm_status_t status;

	wpa_printf(MSG_DEBUG, "%s", "wpa_driver_wifi_scan");
	/*
	 * We force the state to INIT before calling ieee80211_new_state
	 * to get ieee80211_begin_scan called.  We really want to scan w/o
	 * altering the current state but that's not possible right now.
	 */
	(void) wpa_driver_wifi_disassociate(handle, linkid,
	    DLADM_WLAN_REASON_DISASSOC_LEAVING);

	status = dladm_wlan_scan(handle, linkid, NULL, NULL);

	wpa_printf(MSG_DEBUG, "%s: return", "wpa_driver_wifi_scan");
	return (WPA_STATUS(status));
}

/*
 * get_scan_results - fetch the latest scan results
 * @linkid: linkid of the given interface
 * @results: pointer to buffer for scan results
 * @max_size: maximum number of entries (buffer size)
 *
 * Return: number of scan result entries used on success, -1 on failure
 *
 * If scan results include more than @max_size BSSes, @max_size will be
 * returned and the remaining entries will not be included in the
 * buffer.
 */
int
wpa_driver_wifi_get_scan_results(dladm_handle_t handle, datalink_id_t linkid,
    dladm_wlan_ess_t *results, uint32_t max_size)
{
	uint_t ret;

	wpa_printf(MSG_DEBUG, "%s: max size=%d\n",
	    "wpa_driver_wifi_get_scan_results", max_size);

	if (dladm_wlan_wpa_get_sr(handle, linkid, results, max_size, &ret)
	    != DLADM_STATUS_OK) {
		return (-1);
	}

	return (ret);
}

struct wpa_driver_ops wpa_driver_wifi_ops = {
	wpa_driver_wifi_get_bssid,
	wpa_driver_wifi_get_ssid,
	wpa_driver_wifi_set_wpa,
	wpa_driver_wifi_set_key,
	wpa_driver_wifi_scan,
	wpa_driver_wifi_get_scan_results,
	wpa_driver_wifi_disassociate,
	wpa_driver_wifi_associate
};
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
 * Sun elects to license this software under the BSD license.
 * See README for more details.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <poll.h>

#include "eloop.h"

static struct eloop_data eloop;
/*
 * Initialize global event loop data - must be called before any other eloop_*
 * function. user_data is a pointer to global data structure and will be passed
 * as eloop_ctx to signal handlers.
 */
void
eloop_init(void *user_data)
{
	(void) memset(&eloop, 0, sizeof (eloop));
	eloop.user_data = user_data;
}

/*
 * Register handler for read event
 */
int
eloop_register_read_sock(int sock,
    void (*handler)(int sock, void *eloop_ctx,
    void *sock_ctx), void *eloop_data, void *user_data)
{
	struct eloop_sock *tmp;

	tmp = (struct eloop_sock *)realloc(eloop.readers,
	    (eloop.reader_count + 1) * sizeof (struct eloop_sock));
	if (tmp == NULL)
		return (-1);

	tmp[eloop.reader_count].sock = sock;
	tmp[eloop.reader_count].eloop_data = eloop_data;
	tmp[eloop.reader_count].user_data = user_data;
	tmp[eloop.reader_count].handler = handler;
	eloop.reader_count++;
	eloop.readers = tmp;
	if (sock > eloop.max_sock)
		eloop.max_sock = sock;

	return (0);
}

void
eloop_unregister_read_sock(int sock)
{
	int i;

	if (eloop.readers == NULL || eloop.reader_count == 0)
		return;

	for (i = 0; i < eloop.reader_count; i++) {
		if (eloop.readers[i].sock == sock)
			break;
	}
	if (i == eloop.reader_count)
		return;
	if (i != eloop.reader_count - 1) {
		(void) memmove(&eloop.readers[i], &eloop.readers[i + 1],
		    (eloop.reader_count - i - 1) *
		    sizeof (struct eloop_sock));
	}
	eloop.reader_count--;
}

/*
 * Register timeout routines
 */
int
eloop_register_timeout(unsigned int secs, unsigned int usecs,
    void (*handler)(void *eloop_ctx, void *timeout_ctx),
    void *eloop_data, void *user_data)
{
	struct eloop_timeout *timeout, *tmp, *prev;

	timeout = (struct eloop_timeout *)malloc(sizeof (*timeout));
	if (timeout == NULL)
		return (-1);
	(void) gettimeofday(&timeout->time, NULL);
	timeout->time.tv_sec += secs;
	timeout->time.tv_usec += usecs;
	while (timeout->time.tv_usec >= 1000000) {
		timeout->time.tv_sec++;
		timeout->time.tv_usec -= 1000000;
	}
	timeout->eloop_data = eloop_data;
	timeout->user_data = user_data;
	timeout->handler = handler;
	timeout->next = NULL;

	if (eloop.timeout == NULL) {
		eloop.timeout = timeout;
		return (0);
	}

	prev = NULL;
	tmp = eloop.timeout;
	while (tmp != NULL) {
		if (timercmp(&timeout->time, &tmp->time, < /* */))
			break;
		prev = tmp;
		tmp = tmp->next;
	}

	if (prev == NULL) {
		timeout->next = eloop.timeout;
		eloop.timeout = timeout;
	} else {
		timeout->next = prev->next;
		prev->next = timeout;
	}

	return (0);
}

/*
 * Cancel timeouts matching <handler,eloop_data,user_data>.
 * ELOOP_ALL_CTX can be used as a wildcard for cancelling all timeouts
 * regardless of eloop_data/user_data.
 */
void
eloop_cancel_timeout(void (*handler)(void *eloop_ctx, void *sock_ctx),
    void *eloop_data, void *user_data)
{
	struct eloop_timeout *timeout, *prev, *next;

	prev = NULL;
	timeout = eloop.timeout;
	while (timeout != NULL) {
		next = timeout->next;

		if (timeout->handler == handler &&
		    (timeout->eloop_data == eloop_data ||
		    eloop_data == ELOOP_ALL_CTX) &&
		    (timeout->user_data == user_data ||
		    user_data == ELOOP_ALL_CTX)) {
			if (prev == NULL)
				eloop.timeout = next;
			else
				prev->next = next;
			free(timeout);
		} else
			prev = timeout;

		timeout = next;
	}
}

static void eloop_handle_signal(int sig)
{
	int i;

	eloop.signaled++;
	for (i = 0; i < eloop.signal_count; i++) {
		if (eloop.signals[i].sig == sig) {
			eloop.signals[i].signaled++;
			break;
		}
	}
}

static void eloop_process_pending_signals(void)
{
	int i;

	if (eloop.signaled == 0)
		return;
	eloop.signaled = 0;

	for (i = 0; i < eloop.signal_count; i++) {
		if (eloop.signals[i].signaled) {
			eloop.signals[i].signaled = 0;
			eloop.signals[i].handler(eloop.signals[i].sig,
			    eloop.user_data, eloop.signals[i].user_data);
		}
	}
}

/*
 * Register handler for signal.
 * Note: signals are 'global' events and there is no local eloop_data pointer
 * like with other handlers. The (global) pointer given to eloop_init() will be
 * used as eloop_ctx for signal handlers.
 */
int
eloop_register_signal(int sig,
    void (*handler)(int sig, void *eloop_ctx, void *signal_ctx),
    void *user_data)
{
	struct eloop_signal *tmp;

	tmp = (struct eloop_signal *)
	    realloc(eloop.signals,
	    (eloop.signal_count + 1) *
	    sizeof (struct eloop_signal));
	if (tmp == NULL)
		return (-1);

	tmp[eloop.signal_count].sig = sig;
	tmp[eloop.signal_count].user_data = user_data;
	tmp[eloop.signal_count].handler = handler;
	tmp[eloop.signal_count].signaled = 0;
	eloop.signal_count++;
	eloop.signals = tmp;
	(void) signal(sig, eloop_handle_signal);

	return (0);
}

/*
 * Start event loop and continue running as long as there are any registered
 * event handlers.
 */
void
eloop_run(void)
{
	struct pollfd pfds[MAX_POLLFDS];	/* array of polled fd */
	int i, res;
	int default_t, t;
	struct timeval tv, now;

	default_t = 5 * 1000;	/* 5 seconds */
	while (!eloop.terminate &&
	    (eloop.timeout || eloop.reader_count > 0)) {
		if (eloop.timeout) {
			(void) gettimeofday(&now, NULL);
			if (timercmp(&now, &eloop.timeout->time, < /* */))
				timersub(&eloop.timeout->time, &now, &tv);
			else
				tv.tv_sec = tv.tv_usec = 0;
		}

		t = (eloop.timeout == NULL ?
		    default_t : (tv.tv_sec * 1000 + tv.tv_usec / 1000));
		for (i = 0; i < eloop.reader_count; i++) {
			pfds[i].fd = eloop.readers[i].sock;
			pfds[i].events = POLLIN | POLLPRI;
		}
		res = poll(pfds, eloop.reader_count, t);
		if (res < 0 && errno != EINTR)
			return;

		eloop_process_pending_signals();

		/* check if some registered timeouts have occurred */
		if (eloop.timeout) {
			struct eloop_timeout *tmp;

			(void) gettimeofday(&now, NULL);
			if (!timercmp(&now, &eloop.timeout->time, < /* */)) {
				tmp = eloop.timeout;
				eloop.timeout = eloop.timeout->next;
				tmp->handler(tmp->eloop_data, tmp->user_data);
				free(tmp);
			}

		}

		if (res <= 0)
			continue;

		for (i = 0; i < eloop.reader_count; i++) {
			if (pfds[i].revents) {
				eloop.readers[i].handler(
				    eloop.readers[i].sock,
				    eloop.readers[i].eloop_data,
				    eloop.readers[i].user_data);
			}
		}
	}
}

/*
 * Terminate event loop even if there are registered events.
 */
void
eloop_terminate(void)
{
	eloop.terminate = 1;
}


/*
 * Free any reserved resources. After calling eloop_destoy(), other eloop_*
 * functions must not be called before re-running eloop_init().
 */
void
eloop_destroy(void)
{
	struct eloop_timeout *timeout, *prev;

	timeout = eloop.timeout;
	while (timeout != NULL) {
		prev = timeout;
		timeout = timeout->next;
		free(prev);
	}
	free(eloop.readers);
	free(eloop.signals);
}
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
 * Sun elects to license this software under the BSD license.
 * See README for more details.
 */
#ifndef __ELOOP_H
#define	__ELOOP_H

#ifdef	__cplusplus
extern "C" {
#endif

/* Magic number for eloop_cancel_timeout() */
#define	ELOOP_ALL_CTX		(void *) -1
#define	MAX_POLLFDS		32

struct eloop_sock {
	int sock;
	void *eloop_data;
	void *user_data;
	void (*handler)(int, void *, void *);
};

struct eloop_timeout {
	struct timeval time;
	void *eloop_data;
	void *user_data;
	void (*handler)(void *, void *);
	struct eloop_timeout *next;
};

struct eloop_signal {
	int sig;
	void *user_data;
	void (*handler)(int, void *, void *);
	int signaled;
};

struct eloop_data {
	void *user_data;

	int max_sock, reader_count;
	struct eloop_sock *readers;

	struct eloop_timeout *timeout;

	int signal_count;
	struct eloop_signal *signals;
	int signaled;

	int terminate;
};

void eloop_init(void *);

int eloop_register_read_sock(int,
	void (*handler)(int, void *, void *), void *, void *);

void eloop_unregister_read_sock(int);

int eloop_register_timeout(unsigned int, unsigned int,
	void (*handler)(void *, void *), void *, void *);

void eloop_cancel_timeout(void (*handler)(void *, void *), void *, void *);
int eloop_register_signal(int, void (*handler)(int, void *, void *), void *);

void eloop_run(void);
void eloop_terminate(void);
void eloop_destroy(void);

#ifdef __cplusplus
}
#endif

#endif /* __ELOOP_H */
/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
 * Sun elects to license this software under the BSD license.
 * See README for more details.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libdlpi.h>
#include <sys/ethernet.h>
#include <netinet/in.h>

#include "wpa_impl.h"
#include "eloop.h"
#include "l2_packet.h"

static int
link_init(struct l2_packet_data *l2)
{
	int retval;
	uint8_t paddr[DLPI_PHYSADDR_MAX];
	size_t paddrlen = sizeof (paddr);

	retval = dlpi_bind(l2->dh, DLPI_ANY_SAP, NULL);
	if (retval != DLPI_SUCCESS) {
		wpa_printf(MSG_ERROR, "cannot bind on %s: %s",
		    l2->ifname, dlpi_strerror(retval));
		return (-1);
	}

	retval = dlpi_promiscon(l2->dh, DL_PROMISC_SAP);
	if (retval != DLPI_SUCCESS) {
		wpa_printf(MSG_ERROR, "cannot enable promiscous"
		    " mode (SAP) on %s: %s",
		    l2->ifname, dlpi_strerror(retval));
		return (-1);
	}

	retval = dlpi_get_physaddr(l2->dh, DL_CURR_PHYS_ADDR, paddr, &paddrlen);
	if (retval != DLPI_SUCCESS) {
		wpa_printf(MSG_ERROR, "cannot get physical address for %s: %s",
		    l2->ifname, dlpi_strerror(retval));
		return (-1);
	}
	if (paddrlen != sizeof (l2->own_addr)) {
		wpa_printf(MSG_ERROR, "physical address for %s is not %d bytes",
		    l2->ifname, sizeof (l2->own_addr));
		return (-1);
	}
	(void) memcpy(l2->own_addr, paddr, sizeof (l2->own_addr));

	return (0);
}

/*
 * layer2 packet handling.
 */
int
l2_packet_get_own_addr(struct l2_packet_data *l2, uint8_t *addr)
{
	(void) memcpy(addr, l2->own_addr, sizeof (l2->own_addr));
	return (0);
}

int
l2_packet_send(struct l2_packet_data *l2, uint8_t *buf, size_t buflen)
{
	int retval;

	retval = dlpi_send(l2->dh, NULL, 0, buf, buflen, NULL);
	if (retval != DLPI_SUCCESS) {
		wpa_printf(MSG_ERROR, "l2_packet_send: cannot send "
		    "message on %s: %s", l2->ifname, dlpi_strerror(retval));
		return (-1);
	}
	return (0);
}

/* ARGSUSED */
static void
l2_packet_receive(int fd, void *eloop_ctx, void *sock_ctx)
{
	struct l2_packet_data *l2 = eloop_ctx;
	uint64_t buf[IEEE80211_MTU_MAX / sizeof (uint64_t)];
	size_t buflen = sizeof (buf);
	struct l2_ethhdr *ethhdr;
	int retval;

	retval = dlpi_recv(l2->dh, NULL, NULL, buf, &buflen, 0, NULL);
	if (retval != DLPI_SUCCESS) {
		wpa_printf(MSG_ERROR, "l2_packet_receive: cannot receive "
		    "message on %s: %s", l2->ifname, dlpi_strerror(retval));
		return;
	}

	ethhdr = (struct l2_ethhdr *)buf;
	if (buflen < sizeof (*ethhdr) ||
	    (ntohs(ethhdr->h_proto) != ETHERTYPE_EAPOL &&
	    ntohs(ethhdr->h_proto) != ETHERTYPE_RSN_PREAUTH))
		return;

	l2->rx_callback(l2->rx_callback_ctx, ethhdr->h_source,
	    (unsigned char *)(ethhdr + 1), buflen - sizeof (*ethhdr));
}

/* ARGSUSED */
struct l2_packet_data *
l2_packet_init(const char *ifname, unsigned short protocol,
	void (*rx_callback)(void *, unsigned char *, unsigned char *, size_t),
	void *rx_callback_ctx)
{
	int retval;
	struct l2_packet_data *l2;

	l2 = calloc(1, sizeof (struct l2_packet_data));
	if (l2 == NULL)
		return (NULL);

	(void) strlcpy(l2->ifname, ifname, sizeof (l2->ifname));
	l2->rx_callback = rx_callback;
	l2->rx_callback_ctx = rx_callback_ctx;

	retval = dlpi_open(l2->ifname, &l2->dh, DLPI_RAW);
	if (retval != DLPI_SUCCESS) {
		wpa_printf(MSG_ERROR, "unable to open DLPI link %s: %s",
		    l2->ifname, dlpi_strerror(retval));
		free(l2);
		return (NULL);
	}

	/* NOTE: link_init() sets l2->own_addr */
	if (link_init(l2) < 0) {
		dlpi_close(l2->dh);
		free(l2);
		return (NULL);
	}

	(void) eloop_register_read_sock(dlpi_fd(l2->dh), l2_packet_receive, l2,
	    NULL);

	return (l2);
}

void
l2_packet_deinit(struct l2_packet_data *l2)
{
	if (l2 == NULL)
		return;

	eloop_unregister_read_sock(dlpi_fd(l2->dh));
	dlpi_close(l2->dh);
	free(l2);
}
/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
 * Sun elects to license this software under the BSD license.
 * See README for more details.
 */
#ifndef __L2_PACKET_H
#define	__L2_PACKET_H

#ifdef	__cplusplus
extern "C" {
#endif

#include <sys/types.h>
#include <net/if.h>
#include <libdlpi.h>

#define	IEEE80211_MTU_MAX	2304

struct l2_packet_data {
	dlpi_handle_t	dh;	/* dlpi handle for EAPOL frames */
	char		ifname[DLPI_LINKNAME_MAX];
	uint8_t		own_addr[IEEE80211_ADDR_LEN];
	void		(*rx_callback)(void *, unsigned char *,
	    unsigned char *, size_t);
	void		*rx_callback_ctx;
};

#pragma pack(1)
struct l2_ethhdr {
	uint8_t h_dest[IEEE80211_ADDR_LEN];
	uint8_t h_source[IEEE80211_ADDR_LEN];
	uint16_t h_proto;
};
#pragma pack()

struct l2_packet_data *l2_packet_init(
	const char *, unsigned short,
	void (*rx_callback)(void *, unsigned char *,
			    unsigned char *, size_t),
	void *);
void l2_packet_deinit(struct l2_packet_data *);

int l2_packet_get_own_addr(struct l2_packet_data *, uint8_t *);
int l2_packet_send(struct l2_packet_data *, uint8_t *, size_t);

#ifdef __cplusplus
}
#endif

#endif /* __L2_PACKET_H */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
 * Sun elects to license this software under the BSD license.
 * See README for more details.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <netinet/in.h>
#include <sys/ethernet.h>
#include <fcntl.h>
#include <unistd.h>

#include "wpa_impl.h"
#include "wpa_enc.h"
#include "driver.h"
#include "eloop.h"
#include "l2_packet.h"

static void pmksa_cache_set_expiration(struct wpa_supplicant *);

/*
 * IEEE 802.11i/D3.0
 */
static const int WPA_SELECTOR_LEN = 4;
static const uint8_t WPA_OUI_AND_TYPE[] = { 0x00, 0x50, 0xf2, 1 };
static const uint8_t
WPA_AUTH_KEY_MGMT_UNSPEC_802_1X[] 		= { 0x00, 0x50, 0xf2, 1 };
static const uint8_t
WPA_AUTH_KEY_MGMT_PSK_OVER_802_1X[] 		= { 0x00, 0x50, 0xf2, 2 };
static const uint8_t WPA_CIPHER_SUITE_NONE[]	= { 0x00, 0x50, 0xf2, 0 };
static const uint8_t WPA_CIPHER_SUITE_WEP40[]	= { 0x00, 0x50, 0xf2, 1 };
static const uint8_t WPA_CIPHER_SUITE_TKIP[]	= { 0x00, 0x50, 0xf2, 2 };
static const uint8_t WPA_CIPHER_SUITE_CCMP[]	= { 0x00, 0x50, 0xf2, 4 };
static const uint8_t WPA_CIPHER_SUITE_WEP104[]	= { 0x00, 0x50, 0xf2, 5 };

/*
 * WPA IE version 1
 * 00-50-f2:1 (OUI:OUI type)
 * 0x01 0x00 (version; little endian)
 * (all following fields are optional:)
 * Group Suite Selector (4 octets) (default: TKIP)
 * Pairwise Suite Count (2 octets, little endian) (default: 1)
 * Pairwise Suite List (4 * n octets) (default: TKIP)
 * Authenticated Key Management Suite Count (2 octets, little endian)
 * (default: 1)
 * Authenticated Key Management Suite List (4 * n octets)
 * (default: unspec 802.1x)
 * WPA Capabilities (2 octets, little endian) (default: 0)
 */
#pragma pack(1)
struct wpa_ie_hdr {
	uint8_t		elem_id;
	uint8_t		len;
	uint8_t		oui[3];
	uint8_t		oui_type;
	uint16_t	version;
};
#pragma pack()

/*
 * IEEE 802.11i/D9.0
 */
static const int RSN_SELECTOR_LEN = 4;
static const uint16_t RSN_VERSION = 1;
static const uint8_t
RSN_AUTH_KEY_MGMT_UNSPEC_802_1X[]		= { 0x00, 0x0f, 0xac, 1 };
static const uint8_t
RSN_AUTH_KEY_MGMT_PSK_OVER_802_1X[]		= { 0x00, 0x0f, 0xac, 2 };
static const uint8_t RSN_CIPHER_SUITE_NONE[]	= { 0x00, 0x0f, 0xac, 0 };
static const uint8_t RSN_CIPHER_SUITE_WEP40[]	= { 0x00, 0x0f, 0xac, 1 };
static const uint8_t RSN_CIPHER_SUITE_TKIP[]	= { 0x00, 0x0f, 0xac, 2 };
static const uint8_t RSN_CIPHER_SUITE_CCMP[]	= { 0x00, 0x0f, 0xac, 4 };
static const uint8_t RSN_CIPHER_SUITE_WEP104[]	= { 0x00, 0x0f, 0xac, 5 };

/*
 * EAPOL-Key Key Data Encapsulation
 * GroupKey and STAKey require encryption, otherwise, encryption is optional.
 */
static const uint8_t RSN_KEY_DATA_GROUPKEY[]	= { 0x00, 0x0f, 0xac, 1 };
static const uint8_t RSN_KEY_DATA_PMKID[]	= { 0x00, 0x0f, 0xac, 4 };

/*
 * 1/4: PMKID
 * 2/4: RSN IE
 * 3/4: one or two RSN IEs + GTK IE (encrypted)
 * 4/4: empty
 * 1/2: GTK IE (encrypted)
 * 2/2: empty
 */

/*
 * RSN IE version 1
 * 0x01 0x00 (version; little endian)
 * (all following fields are optional:)
 * Group Suite Selector (4 octets) (default: CCMP)
 * Pairwise Suite Count (2 octets, little endian) (default: 1)
 * Pairwise Suite List (4 * n octets) (default: CCMP)
 * Authenticated Key Management Suite Count (2 octets, little endian)
 *    (default: 1)
 * Authenticated Key Management Suite List (4 * n octets)
 *    (default: unspec 802.1x)
 * RSN Capabilities (2 octets, little endian) (default: 0)
 * PMKID Count (2 octets) (default: 0)
 * PMKID List (16 * n octets)
 */
#pragma pack(1)
struct rsn_ie_hdr {
	uint8_t		elem_id; /* WLAN_EID_RSN */
	uint8_t		len;
	uint16_t	version;
};
#pragma pack()

static int
random_get_pseudo_bytes(uint8_t *ptr, size_t len)
{
	int fd;
	size_t resid = len;
	size_t bytes;

	fd = open("/dev/urandom", O_RDONLY);
	if (fd == -1) {
		wpa_printf(MSG_ERROR, "Could not open /dev/urandom.\n");
		return (-1);
	}

	while (resid != 0) {
		bytes = read(fd, ptr, resid);
		ptr += bytes;
		resid -= bytes;
	}

	(void) close(fd);

	return (0);
}

static void
inc_byte_array(uint8_t *counter, size_t len)
{
	int pos = len - 1;
	while (pos >= 0) {
		counter[pos]++;
		if (counter[pos] != 0)
			break;
		pos--;
	}
}

static int
wpa_selector_to_bitfield(uint8_t *s)
{
	if (memcmp(s, WPA_CIPHER_SUITE_NONE, WPA_SELECTOR_LEN) == 0)
		return (WPA_CIPHER_NONE);
	if (memcmp(s, WPA_CIPHER_SUITE_WEP40, WPA_SELECTOR_LEN) == 0)
		return (WPA_CIPHER_WEP40);
	if (memcmp(s, WPA_CIPHER_SUITE_TKIP, WPA_SELECTOR_LEN) == 0)
		return (WPA_CIPHER_TKIP);
	if (memcmp(s, WPA_CIPHER_SUITE_CCMP, WPA_SELECTOR_LEN) == 0)
		return (WPA_CIPHER_CCMP);
	if (memcmp(s, WPA_CIPHER_SUITE_WEP104, WPA_SELECTOR_LEN) == 0)
		return (WPA_CIPHER_WEP104);
	return (0);
}

static int
wpa_key_mgmt_to_bitfield(uint8_t *s)
{
	if (memcmp(s, WPA_AUTH_KEY_MGMT_UNSPEC_802_1X, WPA_SELECTOR_LEN) == 0)
		return (WPA_KEY_MGMT_IEEE8021X);
	if (memcmp(s, WPA_AUTH_KEY_MGMT_PSK_OVER_802_1X, WPA_SELECTOR_LEN) ==
	    0)
		return (WPA_KEY_MGMT_PSK);
	return (0);
}

static int
rsn_selector_to_bitfield(uint8_t *s)
{
	if (memcmp(s, RSN_CIPHER_SUITE_NONE, RSN_SELECTOR_LEN) == 0)
		return (WPA_CIPHER_NONE);
	if (memcmp(s, RSN_CIPHER_SUITE_WEP40, RSN_SELECTOR_LEN) == 0)
		return (WPA_CIPHER_WEP40);
	if (memcmp(s, RSN_CIPHER_SUITE_TKIP, RSN_SELECTOR_LEN) == 0)
		return (WPA_CIPHER_TKIP);
	if (memcmp(s, RSN_CIPHER_SUITE_CCMP, RSN_SELECTOR_LEN) == 0)
		return (WPA_CIPHER_CCMP);
	if (memcmp(s, RSN_CIPHER_SUITE_WEP104, RSN_SELECTOR_LEN) == 0)
		return (WPA_CIPHER_WEP104);
	return (0);
}

static int
rsn_key_mgmt_to_bitfield(uint8_t *s)
{
	if (memcmp(s, RSN_AUTH_KEY_MGMT_UNSPEC_802_1X, RSN_SELECTOR_LEN) == 0)
		return (WPA_KEY_MGMT_IEEE8021X);
	if (memcmp(s, RSN_AUTH_KEY_MGMT_PSK_OVER_802_1X, RSN_SELECTOR_LEN) ==
	    0)
		return (WPA_KEY_MGMT_PSK);
	return (0);
}

static void
pmksa_cache_free_entry(struct wpa_supplicant *wpa_s,
	struct rsn_pmksa_cache *entry)
{
	wpa_s->pmksa_count--;
	if (wpa_s->cur_pmksa == entry) {
		wpa_printf(MSG_DEBUG, "RSN: removed current PMKSA entry");
		wpa_s->cur_pmksa = NULL;
	}
	free(entry);
}

/* ARGSUSED */
static void
pmksa_cache_expire(void *eloop_ctx, void *timeout_ctx)
{
	struct wpa_supplicant *wpa_s = eloop_ctx;
	time_t now;

	(void) time(&now);
	while (wpa_s->pmksa && wpa_s->pmksa->expiration <= now) {
		struct rsn_pmksa_cache *entry = wpa_s->pmksa;
		wpa_s->pmksa = entry->next;
		wpa_printf(MSG_DEBUG, "RSN: expired PMKSA cache entry for "
		    MACSTR, MAC2STR(entry->aa));
		pmksa_cache_free_entry(wpa_s, entry);
	}

	pmksa_cache_set_expiration(wpa_s);
}

static void
pmksa_cache_set_expiration(struct wpa_supplicant *wpa_s)
{
	int sec;
	eloop_cancel_timeout(pmksa_cache_expire, wpa_s, NULL);
	if (wpa_s->pmksa == NULL)
		return;
	sec = wpa_s->pmksa->expiration - time(NULL);
	if (sec < 0)
		sec = 0;
	(void) eloop_register_timeout(sec + 1, 0, pmksa_cache_expire,
	    wpa_s, NULL);
}

void
pmksa_cache_free(struct wpa_supplicant *wpa_s)
{
	struct rsn_pmksa_cache *entry, *prev;

	entry = wpa_s->pmksa;
	wpa_s->pmksa = NULL;
	while (entry) {
		prev = entry;
		entry = entry->next;
		free(prev);
	}
	pmksa_cache_set_expiration(wpa_s);
	wpa_s->cur_pmksa = NULL;
}

struct rsn_pmksa_cache *
pmksa_cache_get(struct wpa_supplicant *wpa_s,
		uint8_t *aa, uint8_t *pmkid)
{
	struct rsn_pmksa_cache *entry = wpa_s->pmksa;
	while (entry) {
		if ((aa == NULL ||
		    memcmp(entry->aa, aa, IEEE80211_ADDR_LEN) == 0) &&
		    (pmkid == NULL ||
		    memcmp(entry->pmkid, pmkid, PMKID_LEN) == 0))
			return (entry);
		entry = entry->next;
	}
	return (NULL);
}

int
pmksa_cache_list(struct wpa_supplicant *wpa_s, char *buf, size_t len)
{
	int i, j;
	char *pos = buf;
	struct rsn_pmksa_cache *entry;
	time_t now;

	(void) time(&now);
	pos += snprintf(pos, buf + len - pos,
	    "Index / AA / PMKID / expiration (in seconds)\n");
	i = 0;
	entry = wpa_s->pmksa;
	while (entry) {
		i++;
		pos += snprintf(pos, buf + len - pos, "%d " MACSTR " ",
		    i, MAC2STR(entry->aa));
		for (j = 0; j < PMKID_LEN; j++)
			pos += snprintf(pos, buf + len - pos, "%02x",
			    entry->pmkid[j]);
		pos += snprintf(pos, buf + len - pos, " %d\n",
		    (int)(entry->expiration - now));
		entry = entry->next;
	}
	return (pos - buf);
}

void
pmksa_candidate_free(struct wpa_supplicant *wpa_s)
{
	struct rsn_pmksa_candidate *entry, *prev;

	entry = wpa_s->pmksa_candidates;
	wpa_s->pmksa_candidates = NULL;
	while (entry) {
		prev = entry;
		entry = entry->next;
		free(prev);
	}
}

/* ARGSUSED */
static int
wpa_parse_wpa_ie_wpa(struct wpa_supplicant *wpa_s, uint8_t *wpa_ie,
    size_t wpa_ie_len, struct wpa_ie_data *data)
{
	struct wpa_ie_hdr *hdr;
	uint8_t *pos;
	int left;
	int i, count;

	data->proto = WPA_PROTO_WPA;
	data->pairwise_cipher = WPA_CIPHER_TKIP;
	data->group_cipher = WPA_CIPHER_TKIP;
	data->key_mgmt = WPA_KEY_MGMT_IEEE8021X;
	data->capabilities = 0;

	if (wpa_ie_len == 0) {
		/* No WPA IE - fail silently */
		return (-1);
	}

	if (wpa_ie_len < sizeof (struct wpa_ie_hdr)) {
		wpa_printf(MSG_DEBUG, "%s: ie len too short %u",
		    "wpa_parse_wpa_ie_wpa", wpa_ie_len);
		return (-1);
	}

	hdr = (struct wpa_ie_hdr *)wpa_ie;

	if (hdr->elem_id != GENERIC_INFO_ELEM ||
	    hdr->len != wpa_ie_len - 2 ||
	    memcmp(&hdr->oui, WPA_OUI_AND_TYPE, WPA_SELECTOR_LEN) != 0 ||
	    LE_16(hdr->version) != WPA_VERSION) {
		wpa_printf(MSG_DEBUG, "%s: malformed ie or unknown version",
		    "wpa_parse_wpa_ie_wpa");
		return (-1);
	}

	pos = (uint8_t *)(hdr + 1);
	left = wpa_ie_len - sizeof (*hdr);

	if (left >= WPA_SELECTOR_LEN) {
		data->group_cipher = wpa_selector_to_bitfield(pos);
		pos += WPA_SELECTOR_LEN;
		left -= WPA_SELECTOR_LEN;
	} else if (left > 0) {
		wpa_printf(MSG_DEBUG, "%s: ie length mismatch, %u too much",
		    "wpa_parse_wpa_ie_wpa", left);
		return (-1);
	}

	if (left >= 2) {
		data->pairwise_cipher = 0;
		count = pos[0] | (pos[1] << 8);
		pos += 2;
		left -= 2;
		if (count == 0 || left < count * WPA_SELECTOR_LEN) {
			wpa_printf(MSG_DEBUG, "%s: ie count botch (pairwise), "
			    "count %u left %u",
			    "wpa_parse_wpa_ie_wpa", count, left);
			return (-1);
		}
		for (i = 0; i < count; i++) {
			data->pairwise_cipher |= wpa_selector_to_bitfield(pos);
			pos += WPA_SELECTOR_LEN;
			left -= WPA_SELECTOR_LEN;
		}
	} else if (left == 1) {
		wpa_printf(MSG_DEBUG, "%s: ie too short (for key mgmt)",
		    "wpa_parse_wpa_ie_wpa");
		return (-1);
	}

	if (left >= 2) {
		data->key_mgmt = 0;
		count = pos[0] | (pos[1] << 8);
		pos += 2;
		left -= 2;
		if (count == 0 || left < count * WPA_SELECTOR_LEN) {
			wpa_printf(MSG_DEBUG, "%s: ie count botch (key mgmt), "
			    "count %u left %u",
			    "wpa_parse_wpa_ie_wpa", count, left);
			return (-1);
		}
		for (i = 0; i < count; i++) {
			data->key_mgmt |= wpa_key_mgmt_to_bitfield(pos);
			pos += WPA_SELECTOR_LEN;
			left -= WPA_SELECTOR_LEN;
		}
	} else if (left == 1) {
		wpa_printf(MSG_DEBUG, "%s: ie too short (for capabilities)",
		    "wpa_parse_wpa_ie_wpa");
		return (-1);
	}

	if (left >= 2) {
		data->capabilities = pos[0] | (pos[1] << 8);
		pos += 2;
		left -= 2;
	}

	if (left > 0) {
		wpa_printf(MSG_DEBUG, "%s: ie has %u trailing bytes",
		    "wpa_parse_wpa_ie_wpa", left);
		return (-1);
	}

	return (0);
}

/* ARGSUSED */
static int
wpa_parse_wpa_ie_rsn(struct wpa_supplicant *wpa_s, uint8_t *rsn_ie,
    size_t rsn_ie_len, struct wpa_ie_data *data)
{
	struct rsn_ie_hdr *hdr;
	uint8_t *pos;
	int left;
	int i, count;

	data->proto = WPA_PROTO_RSN;
	data->pairwise_cipher = WPA_CIPHER_CCMP;
	data->group_cipher = WPA_CIPHER_CCMP;
	data->key_mgmt = WPA_KEY_MGMT_IEEE8021X;
	data->capabilities = 0;

	if (rsn_ie_len == 0) {
		/* No RSN IE - fail silently */
		return (-1);
	}

	if (rsn_ie_len < sizeof (struct rsn_ie_hdr)) {
		wpa_printf(MSG_DEBUG, "%s: ie len too short %u",
		    "wpa_parse_wpa_ie_rsn", rsn_ie_len);
		return (-1);
	}

	hdr = (struct rsn_ie_hdr *)rsn_ie;

	if (hdr->elem_id != RSN_INFO_ELEM ||
	    hdr->len != rsn_ie_len - 2 ||
	    LE_16(hdr->version) != RSN_VERSION) {
		wpa_printf(MSG_DEBUG, "%s: malformed ie or unknown version",
		    "wpa_parse_wpa_ie_rsn");
		return (-1);
	}

	pos = (uint8_t *)(hdr + 1);
	left = rsn_ie_len - sizeof (*hdr);

	if (left >= RSN_SELECTOR_LEN) {
		data->group_cipher = rsn_selector_to_bitfield(pos);
		pos += RSN_SELECTOR_LEN;
		left -= RSN_SELECTOR_LEN;
	} else if (left > 0) {
		wpa_printf(MSG_DEBUG, "%s: ie length mismatch, %u too much",
		    "wpa_parse_wpa_ie_rsn", left);
		return (-1);
	}

	if (left >= 2) {
		data->pairwise_cipher = 0;
		count = pos[0] | (pos[1] << 8);
		pos += 2;
		left -= 2;
		if (count == 0 || left < count * RSN_SELECTOR_LEN) {
			wpa_printf(MSG_DEBUG, "%s: ie count botch (pairwise), "
			    "count %u left %u",
			    "wpa_parse_wpa_ie_rsn", count, left);
			return (-1);
		}
		for (i = 0; i < count; i++) {
			data->pairwise_cipher |= rsn_selector_to_bitfield(pos);
			pos += RSN_SELECTOR_LEN;
			left -= RSN_SELECTOR_LEN;
		}
	} else if (left == 1) {
		wpa_printf(MSG_DEBUG, "%s: ie too short (for key mgmt)",
		    "wpa_parse_wpa_ie_rsn");
		return (-1);
	}

	if (left >= 2) {
		data->key_mgmt = 0;
		count = pos[0] | (pos[1] << 8);
		pos += 2;
		left -= 2;
		if (count == 0 || left < count * RSN_SELECTOR_LEN) {
			wpa_printf(MSG_DEBUG, "%s: ie count botch (key mgmt), "
			    "count %u left %u",
			    "wpa_parse_wpa_ie_rsn", count, left);
			return (-1);
		}
		for (i = 0; i < count; i++) {
			data->key_mgmt |= rsn_key_mgmt_to_bitfield(pos);
			pos += RSN_SELECTOR_LEN;
			left -= RSN_SELECTOR_LEN;
		}
	} else if (left == 1) {
		wpa_printf(MSG_DEBUG, "%s: ie too short (for capabilities)",
		    "wpa_parse_wpa_ie_rsn");
		return (-1);
	}

	if (left >= 2) {
		data->capabilities = pos[0] | (pos[1] << 8);
		pos += 2;
		left -= 2;
	}

	if (left > 0) {
		/*
		 * RSN IE could include PMKID data, but Authenticator should
		 * never include it, so no need to parse it in the Supplicant.
		 */
		wpa_printf(MSG_DEBUG, "%s: ie has %u trailing bytes - ignored",
		    "wpa_parse_wpa_ie_rsn", left);
	}

	return (0);
}

int
wpa_parse_wpa_ie(struct wpa_supplicant *wpa_s, uint8_t *wpa_ie,
    size_t wpa_ie_len, struct wpa_ie_data *data)
{
	if (wpa_ie_len >= 1 && wpa_ie[0] == RSN_INFO_ELEM)
		return (wpa_parse_wpa_ie_rsn(wpa_s, wpa_ie, wpa_ie_len, data));
	else
		return (wpa_parse_wpa_ie_wpa(wpa_s, wpa_ie, wpa_ie_len, data));
}

static int
wpa_gen_wpa_ie_wpa(struct wpa_supplicant *wpa_s, uint8_t *wpa_ie)
{
	uint8_t *pos;
	struct wpa_ie_hdr *hdr;

	hdr = (struct wpa_ie_hdr *)wpa_ie;
	hdr->elem_id = GENERIC_INFO_ELEM;
	(void) memcpy(&hdr->oui, WPA_OUI_AND_TYPE, WPA_SELECTOR_LEN);
	hdr->version = LE_16(WPA_VERSION);
	pos = (uint8_t *)(hdr + 1);

	if (wpa_s->group_cipher == WPA_CIPHER_CCMP) {
		(void) memcpy(pos, WPA_CIPHER_SUITE_CCMP, WPA_SELECTOR_LEN);
	} else if (wpa_s->group_cipher == WPA_CIPHER_TKIP) {
		(void) memcpy(pos, WPA_CIPHER_SUITE_TKIP, WPA_SELECTOR_LEN);
	} else if (wpa_s->group_cipher == WPA_CIPHER_WEP104) {
		(void) memcpy(pos, WPA_CIPHER_SUITE_WEP104, WPA_SELECTOR_LEN);
	} else if (wpa_s->group_cipher == WPA_CIPHER_WEP40) {
		(void) memcpy(pos, WPA_CIPHER_SUITE_WEP40, WPA_SELECTOR_LEN);
	} else {
		wpa_printf(MSG_WARNING, "Invalid group cipher (%d).",
		    wpa_s->group_cipher);
		return (-1);
	}
	pos += WPA_SELECTOR_LEN;

	*pos++ = 1;
	*pos++ = 0;
	if (wpa_s->pairwise_cipher == WPA_CIPHER_CCMP) {
		(void) memcpy(pos, WPA_CIPHER_SUITE_CCMP, WPA_SELECTOR_LEN);
	} else if (wpa_s->pairwise_cipher == WPA_CIPHER_TKIP) {
		(void) memcpy(pos, WPA_CIPHER_SUITE_TKIP, WPA_SELECTOR_LEN);
	} else if (wpa_s->pairwise_cipher == WPA_CIPHER_NONE) {
		(void) memcpy(pos, WPA_CIPHER_SUITE_NONE, WPA_SELECTOR_LEN);
	} else {
		wpa_printf(MSG_WARNING, "Invalid pairwise cipher (%d).",
		    wpa_s->pairwise_cipher);
		return (-1);
	}
	pos += WPA_SELECTOR_LEN;

	*pos++ = 1;
	*pos++ = 0;
	if (wpa_s->key_mgmt == WPA_KEY_MGMT_IEEE8021X) {
		(void) memcpy(pos, WPA_AUTH_KEY_MGMT_UNSPEC_802_1X,
		    WPA_SELECTOR_LEN);
	} else if (wpa_s->key_mgmt == WPA_KEY_MGMT_PSK) {
		(void) memcpy(pos, WPA_AUTH_KEY_MGMT_PSK_OVER_802_1X,
		    WPA_SELECTOR_LEN);
	} else {
		wpa_printf(MSG_WARNING, "Invalid key management type (%d).",
		    wpa_s->key_mgmt);
		return (-1);
	}
	pos += WPA_SELECTOR_LEN;

	/*
	 * WPA Capabilities; use defaults, so no need to include it
	 */
	hdr->len = (pos - wpa_ie) - 2;

	return (pos - wpa_ie);
}

static int
wpa_gen_wpa_ie_rsn(struct wpa_supplicant *wpa_s, uint8_t *rsn_ie)
{
	uint8_t *pos;
	struct rsn_ie_hdr *hdr;

	hdr = (struct rsn_ie_hdr *)rsn_ie;
	hdr->elem_id = RSN_INFO_ELEM;
	hdr->version = LE_16(RSN_VERSION);
	pos = (uint8_t *)(hdr + 1);

	if (wpa_s->group_cipher == WPA_CIPHER_CCMP) {
		(void) memcpy(pos, RSN_CIPHER_SUITE_CCMP, RSN_SELECTOR_LEN);
	} else if (wpa_s->group_cipher == WPA_CIPHER_TKIP) {
		(void) memcpy(pos, RSN_CIPHER_SUITE_TKIP, RSN_SELECTOR_LEN);
	} else if (wpa_s->group_cipher == WPA_CIPHER_WEP104) {
		(void) memcpy(pos, RSN_CIPHER_SUITE_WEP104, RSN_SELECTOR_LEN);
	} else if (wpa_s->group_cipher == WPA_CIPHER_WEP40) {
		(void) memcpy(pos, RSN_CIPHER_SUITE_WEP40, RSN_SELECTOR_LEN);
	} else {
		wpa_printf(MSG_WARNING, "Invalid group cipher (%d).",
		    wpa_s->group_cipher);
		return (-1);
	}
	pos += RSN_SELECTOR_LEN;

	*pos++ = 1;
	*pos++ = 0;
	if (wpa_s->pairwise_cipher == WPA_CIPHER_CCMP) {
		(void) memcpy(pos, RSN_CIPHER_SUITE_CCMP, RSN_SELECTOR_LEN);
	} else if (wpa_s->pairwise_cipher == WPA_CIPHER_TKIP) {
		(void) memcpy(pos, RSN_CIPHER_SUITE_TKIP, RSN_SELECTOR_LEN);
	} else if (wpa_s->pairwise_cipher == WPA_CIPHER_NONE) {
		(void) memcpy(pos, RSN_CIPHER_SUITE_NONE, RSN_SELECTOR_LEN);
	} else {
		wpa_printf(MSG_WARNING, "Invalid pairwise cipher (%d).",
		    wpa_s->pairwise_cipher);
		return (-1);
	}
	pos += RSN_SELECTOR_LEN;

	*pos++ = 1;
	*pos++ = 0;
	if (wpa_s->key_mgmt == WPA_KEY_MGMT_IEEE8021X) {
		(void) memcpy(pos, RSN_AUTH_KEY_MGMT_UNSPEC_802_1X,
		    RSN_SELECTOR_LEN);
	} else if (wpa_s->key_mgmt == WPA_KEY_MGMT_PSK) {
		(void) memcpy(pos, RSN_AUTH_KEY_MGMT_PSK_OVER_802_1X,
		    RSN_SELECTOR_LEN);
	} else {
		wpa_printf(MSG_WARNING, "Invalid key management type (%d).",
		    wpa_s->key_mgmt);
		return (-1);
	}
	pos += RSN_SELECTOR_LEN;

	/* RSN Capabilities */
	*pos++ = 0;
	*pos++ = 0;

	if (wpa_s->cur_pmksa) {
		/* PMKID Count (2 octets, little endian) */
		*pos++ = 1;
		*pos++ = 0;
		/* PMKID */
		(void) memcpy(pos, wpa_s->cur_pmksa->pmkid, PMKID_LEN);
		pos += PMKID_LEN;
	}

	hdr->len = (pos - rsn_ie) - 2;

	return (pos - rsn_ie);
}

int
wpa_gen_wpa_ie(struct wpa_supplicant *wpa_s, uint8_t *wpa_ie)
{
	if (wpa_s->proto == WPA_PROTO_RSN)
		return (wpa_gen_wpa_ie_rsn(wpa_s, wpa_ie));
	else
		return (wpa_gen_wpa_ie_wpa(wpa_s, wpa_ie));
}

static void
wpa_pmk_to_ptk(uint8_t *pmk, uint8_t *addr1, uint8_t *addr2,
    uint8_t *nonce1, uint8_t *nonce2, uint8_t *ptk, size_t ptk_len)
{
	uint8_t data[2 * IEEE80211_ADDR_LEN + 2 * WPA_PMK_LEN];

	/*
	 * PTK = PRF-X(PMK, "Pairwise key expansion",
	 * 	Min(AA, SA) || Max(AA, SA) ||
	 * 	Min(ANonce, SNonce) || Max(ANonce, SNonce))
	 */

	if (memcmp(addr1, addr2, IEEE80211_ADDR_LEN) < 0) {
		(void) memcpy(data, addr1, IEEE80211_ADDR_LEN);
		(void) memcpy(data + IEEE80211_ADDR_LEN, addr2,
		    IEEE80211_ADDR_LEN);
	} else {
		(void) memcpy(data, addr2, IEEE80211_ADDR_LEN);
		(void) memcpy(data + IEEE80211_ADDR_LEN, addr1,
		    IEEE80211_ADDR_LEN);
	}

	if (memcmp(nonce1, nonce2, WPA_PMK_LEN) < 0) {
		(void) memcpy(data + 2 * IEEE80211_ADDR_LEN, nonce1,
		    WPA_PMK_LEN);
		(void) memcpy(data + 2 * IEEE80211_ADDR_LEN + WPA_PMK_LEN,
		    nonce2, WPA_PMK_LEN);
	} else {
		(void) memcpy(data + 2 * IEEE80211_ADDR_LEN, nonce2,
		    WPA_PMK_LEN);
		(void) memcpy(data + 2 * IEEE80211_ADDR_LEN + WPA_PMK_LEN,
		    nonce1, WPA_PMK_LEN);
	}

	sha1_prf(pmk, WPA_PMK_LEN, "Pairwise key expansion", data,
	    sizeof (data), ptk, ptk_len);

	wpa_hexdump(MSG_DEBUG, "WPA: PMK", pmk, WPA_PMK_LEN);
	wpa_hexdump(MSG_DEBUG, "WPA: PTK", ptk, ptk_len);
}

struct wpa_ssid *
wpa_supplicant_get_ssid(struct wpa_supplicant *wpa_s)
{
	struct wpa_ssid *entry;
	uint8_t ssid[MAX_ESSID_LENGTH];
	int ssid_len;
	uint8_t bssid[IEEE80211_ADDR_LEN];

	(void) memset(ssid, 0, MAX_ESSID_LENGTH);
	ssid_len = wpa_s->driver->get_ssid(wpa_s->handle, wpa_s->linkid,
	    (char *)ssid);
	if (ssid_len < 0) {
		wpa_printf(MSG_WARNING, "Could not read SSID from driver.");
		return (NULL);
	}

	if (wpa_s->driver->get_bssid(wpa_s->handle, wpa_s->linkid,
	    (char *)bssid) < 0) {
		wpa_printf(MSG_WARNING, "Could not read BSSID from driver.");
		return (NULL);
	}

	entry = wpa_s->conf->ssid;
	wpa_printf(MSG_DEBUG, "entry len=%d ssid=%s,"
	    " driver len=%d ssid=%s",
	    entry->ssid_len, entry->ssid, ssid_len, ssid);

	if (ssid_len == entry->ssid_len &&
	    memcmp(ssid, entry->ssid, ssid_len) == 0 &&
	    (!entry->bssid_set ||
	    memcmp(bssid, entry->bssid, IEEE80211_ADDR_LEN) == 0))
		return (entry);

	return (NULL);
}

static void
wpa_eapol_key_mic(uint8_t *key, int ver, uint8_t *buf, size_t len, uint8_t *mic)
{
	if (ver == WPA_KEY_INFO_TYPE_HMAC_MD5_RC4) {
		hmac_md5(key, 16, buf, len, mic);
	} else if (ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
		uint8_t hash[SHA1_MAC_LEN];
		hmac_sha1(key, 16, buf, len, hash);
		(void) memcpy(mic, hash, MD5_MAC_LEN);
	}
}

void
wpa_supplicant_key_request(struct wpa_supplicant *wpa_s,
	int error, int pairwise)
{
	int rlen;
	struct ieee802_1x_hdr *hdr;
	struct wpa_eapol_key *reply;
	unsigned char *rbuf;
	struct l2_ethhdr *ethhdr;
	int key_info, ver;
	uint8_t bssid[IEEE80211_ADDR_LEN];

	if (wpa_s->pairwise_cipher == WPA_CIPHER_CCMP)
		ver = WPA_KEY_INFO_TYPE_HMAC_SHA1_AES;
	else
		ver = WPA_KEY_INFO_TYPE_HMAC_MD5_RC4;

	if (wpa_s->driver->get_bssid(wpa_s->handle, wpa_s->linkid,
	    (char *)bssid) < 0) {
		wpa_printf(MSG_WARNING, "Failed to read BSSID for EAPOL-Key "
		    "request");
		return;
	}

	rlen = sizeof (*ethhdr) + sizeof (*hdr) + sizeof (*reply);
	rbuf = malloc(rlen);
	if (rbuf == NULL)
		return;

	(void) memset(rbuf, 0, rlen);
	ethhdr = (struct l2_ethhdr *)rbuf;
	(void) memcpy(ethhdr->h_dest, bssid, IEEE80211_ADDR_LEN);
	(void) memcpy(ethhdr->h_source, wpa_s->own_addr, IEEE80211_ADDR_LEN);
	ethhdr->h_proto = htons(ETHERTYPE_EAPOL);

	hdr = (struct ieee802_1x_hdr *)(ethhdr + 1);
	hdr->version = wpa_s->conf->eapol_version;
	hdr->type = IEEE802_1X_TYPE_EAPOL_KEY;
	hdr->length = htons(sizeof (*reply));

	reply = (struct wpa_eapol_key *)(hdr + 1);
	reply->type = wpa_s->proto == WPA_PROTO_RSN ?
	    EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
	key_info = WPA_KEY_INFO_REQUEST | ver;
	if (wpa_s->ptk_set)
		key_info |= WPA_KEY_INFO_MIC;
	if (error)
		key_info |= WPA_KEY_INFO_ERROR;
	if (pairwise)
		key_info |= WPA_KEY_INFO_KEY_TYPE;
	reply->key_info = BE_16(key_info);
	reply->key_length = 0;
	(void) memcpy(reply->replay_counter, wpa_s->request_counter,
	    WPA_REPLAY_COUNTER_LEN);
	inc_byte_array(wpa_s->request_counter, WPA_REPLAY_COUNTER_LEN);

	reply->key_data_length = BE_16(0);

	if (key_info & WPA_KEY_INFO_MIC) {
		wpa_eapol_key_mic(wpa_s->ptk.mic_key, ver, (uint8_t *)hdr,
		    rlen - sizeof (*ethhdr), reply->key_mic);
	}

	wpa_printf(MSG_INFO, "WPA: Sending EAPOL-Key Request (error=%d "
	    "pairwise=%d ptk_set=%d len=%d)",
	    error, pairwise, wpa_s->ptk_set, rlen);
	wpa_hexdump(MSG_MSGDUMP, "WPA: TX EAPOL-Key Request", rbuf, rlen);
	(void) l2_packet_send(wpa_s->l2, rbuf, rlen);
	free(rbuf);
}

static void
wpa_supplicant_process_1_of_4(struct wpa_supplicant *wpa_s,
    unsigned char *src_addr, struct wpa_eapol_key *key, int ver)
{
	int rlen;
	struct ieee802_1x_hdr *hdr;
	struct wpa_eapol_key *reply;
	unsigned char *rbuf;
	struct l2_ethhdr *ethhdr;
	struct wpa_ssid *ssid;
	struct wpa_ptk *ptk;
	uint8_t buf[8], wpa_ie_buf[80], *wpa_ie, *pmkid = NULL;
	int wpa_ie_len;

	wpa_s->wpa_state = WPA_4WAY_HANDSHAKE;
	wpa_printf(MSG_DEBUG, "WPA: RX message 1 of 4-Way Handshake from "
	    MACSTR " (ver=%d)", MAC2STR(src_addr), ver);

	ssid = wpa_supplicant_get_ssid(wpa_s);
	if (ssid == NULL) {
		wpa_printf(MSG_WARNING,
		    "WPA: No SSID info found (msg 1 of 4).");
		return;
	}

	if (wpa_s->proto == WPA_PROTO_RSN) {
		/* RSN: msg 1/4 should contain PMKID for the selected PMK */
		uint8_t *pos = (uint8_t *)(key + 1);
		uint8_t *end = pos + BE_16(key->key_data_length);

		wpa_hexdump(MSG_DEBUG, "RSN: msg 1/4 key data",
		    pos, BE_16(key->key_data_length));

		while (pos + 1 < end) {
			if (pos + 2 + pos[1] > end) {
				wpa_printf(MSG_DEBUG, "RSN: key data "
				    "underflow (ie=%d len=%d)",
				    pos[0], pos[1]);
				break;
			}
			if (pos[0] == GENERIC_INFO_ELEM &&
			    pos + 1 + RSN_SELECTOR_LEN < end &&
			    pos[1] >= RSN_SELECTOR_LEN + PMKID_LEN &&
			    memcmp(pos + 2, RSN_KEY_DATA_PMKID,
			    RSN_SELECTOR_LEN) == 0) {
				pmkid = pos + 2 + RSN_SELECTOR_LEN;
				wpa_hexdump(MSG_DEBUG, "RSN: PMKID from "
				    "Authenticator", pmkid, PMKID_LEN);
				break;
			} else if (pos[0] == GENERIC_INFO_ELEM && pos[1] == 0)
				break;
			pos += 2 + pos[1];
		}
	}

	wpa_ie = wpa_ie_buf;
	wpa_ie_len = wpa_gen_wpa_ie(wpa_s, wpa_ie);
	if (wpa_ie_len < 0) {
		wpa_printf(MSG_WARNING, "WPA: Failed to generate "
		    "WPA IE (for msg 2 of 4).");
		return;
	}
	wpa_hexdump(MSG_DEBUG, "WPA: WPA IE for msg 2/4", wpa_ie, wpa_ie_len);

	rlen = sizeof (*ethhdr) + sizeof (*hdr) + sizeof (*reply) + wpa_ie_len;
	rbuf = malloc(rlen);
	if (rbuf == NULL)
		return;

	(void) memset(rbuf, 0, rlen);
	ethhdr = (struct l2_ethhdr *)rbuf;
	(void) memcpy(ethhdr->h_dest, src_addr, IEEE80211_ADDR_LEN);
	(void) memcpy(ethhdr->h_source, wpa_s->own_addr, IEEE80211_ADDR_LEN);
	ethhdr->h_proto = htons(ETHERTYPE_EAPOL);

	hdr = (struct ieee802_1x_hdr *)(ethhdr + 1);
	hdr->version = wpa_s->conf->eapol_version;
	hdr->type = IEEE802_1X_TYPE_EAPOL_KEY;
	hdr->length = htons(sizeof (*reply) + wpa_ie_len);

	reply = (struct wpa_eapol_key *)(hdr + 1);
	reply->type = wpa_s->proto == WPA_PROTO_RSN ?
	    EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
	reply->key_info = BE_16(ver | WPA_KEY_INFO_KEY_TYPE | WPA_KEY_INFO_MIC);
	reply->key_length = key->key_length;
	(void) memcpy(reply->replay_counter, key->replay_counter,
	    WPA_REPLAY_COUNTER_LEN);

	reply->key_data_length = BE_16(wpa_ie_len);
	(void) memcpy(reply + 1, wpa_ie, wpa_ie_len);

	if (wpa_s->renew_snonce) {
		if (random_get_pseudo_bytes(wpa_s->snonce, WPA_NONCE_LEN)) {
			wpa_printf(MSG_WARNING, "WPA: Failed to get "
			    "random data for SNonce");
			free(rbuf);
			return;
		}

		wpa_s->renew_snonce = 0;
		wpa_hexdump(MSG_DEBUG, "WPA: Renewed SNonce",
		    wpa_s->snonce, WPA_NONCE_LEN);
	}
	(void) memcpy(reply->key_nonce, wpa_s->snonce, WPA_NONCE_LEN);
	ptk = &wpa_s->tptk;
	(void) memcpy(wpa_s->anonce, key->key_nonce, WPA_NONCE_LEN);

	wpa_pmk_to_ptk(wpa_s->pmk, wpa_s->own_addr, src_addr,
	    wpa_s->snonce, key->key_nonce, (uint8_t *)ptk, sizeof (*ptk));

	/*
	 * Supplicant: swap tx/rx Mic keys
	 */
	(void) memcpy(buf, ptk->u.auth.tx_mic_key, 8);
	(void) memcpy(ptk->u.auth.tx_mic_key, ptk->u.auth.rx_mic_key, 8);
	(void) memcpy(ptk->u.auth.rx_mic_key, buf, 8);
	wpa_s->tptk_set = 1;
	wpa_eapol_key_mic(wpa_s->tptk.mic_key, ver, (uint8_t *)hdr,
	    rlen - sizeof (*ethhdr), reply->key_mic);
	wpa_hexdump(MSG_DEBUG, "WPA: EAPOL-Key MIC", reply->key_mic, 16);

	wpa_printf(MSG_DEBUG, "WPA: Sending EAPOL-Key 2/4");
	wpa_hexdump(MSG_MSGDUMP, "WPA: TX EAPOL-Key 2/4", rbuf, rlen);
	(void) l2_packet_send(wpa_s->l2, rbuf, rlen);

	free(rbuf);
}

static void
wpa_supplicant_process_3_of_4_gtk(struct wpa_supplicant *wpa_s,
    unsigned char *src_addr, struct wpa_eapol_key *key,
    uint8_t *gtk, int gtk_len)
{
	int keyidx, tx, key_rsc_len = 0, alg;

	wpa_hexdump(MSG_DEBUG,
	    "WPA: received GTK in pairwise handshake", gtk, gtk_len);

	keyidx = gtk[0] & 0x3;
	tx = !!(gtk[0] & BIT(2));
	if (tx && wpa_s->pairwise_cipher != WPA_CIPHER_NONE) {
		/*
		 * Ignore Tx bit in GTK IE if a pairwise key is used.
		 * One AP seemed to set this bit (incorrectly, since Tx
		 * is only when doing Group Key only APs) and without
		 * this workaround, the data connection does not work
		 * because wpa_supplicant configured non-zero keyidx to
		 * be used for unicast.
		 */
		wpa_printf(MSG_INFO, "RSN: Tx bit set for GTK IE, but "
		    "pairwise keys are used - ignore Tx bit");
		tx = 0;
	}

	gtk += 2;
	gtk_len -= 2;
	wpa_hexdump(MSG_DEBUG, "WPA: Group Key", gtk, gtk_len);

	switch (wpa_s->group_cipher) {
	case WPA_CIPHER_CCMP:
		if (gtk_len != 16) {
			wpa_printf(MSG_WARNING, "WPA: Unsupported CCMP"
			    " Group Cipher key length %d.", gtk_len);
			return;
		}
		key_rsc_len = 6;
		alg = WPA_ALG_CCMP;
		break;
	case WPA_CIPHER_TKIP:
		if (gtk_len != 32) {
			wpa_printf(MSG_WARNING, "WPA: Unsupported TKIP"
			    " Group Cipher key length %d.", gtk_len);
			return;
		}
		key_rsc_len = 6;
		alg = WPA_ALG_TKIP;
		break;
	case WPA_CIPHER_WEP104:
		if (gtk_len != 13) {
			wpa_printf(MSG_WARNING, "WPA: Unsupported "
			    "WEP104 Group Cipher key length " "%d.", gtk_len);
			return;
		}
		alg = WPA_ALG_WEP;
		break;
	case WPA_CIPHER_WEP40:
		if (gtk_len != 5) {
			wpa_printf(MSG_WARNING, "WPA: Unsupported "
			    "WEP40 Group Cipher key length %d.", gtk_len);
			return;
		}
		alg = WPA_ALG_WEP;
		break;
	default:
		wpa_printf(MSG_WARNING, "WPA: Unsupport Group Cipher "
		    "%d", wpa_s->group_cipher);
		return;
	}

	wpa_printf(MSG_DEBUG, "WPA: Installing GTK to the driver "
	    "(keyidx=%d tx=%d).", keyidx, tx);
	wpa_hexdump(MSG_DEBUG, "WPA: RSC", key->key_rsc, key_rsc_len);
	if (wpa_s->group_cipher == WPA_CIPHER_TKIP) {
		uint8_t tmpbuf[8];
		/*
		 * Swap Tx/Rx keys for Michael MIC
		 */
		(void) memcpy(tmpbuf, gtk + 16, 8);
		(void) memcpy(gtk + 16, gtk + 24, 8);
		(void) memcpy(gtk + 24, tmpbuf, 8);
	}
	if (wpa_s->pairwise_cipher == WPA_CIPHER_NONE) {
		if (wpa_s->driver->set_key(wpa_s->handle, wpa_s->linkid, alg,
		    (uint8_t *)"\xff\xff\xff\xff\xff\xff",
		    keyidx, 1, key->key_rsc,
		    key_rsc_len, gtk, gtk_len) < 0)
			wpa_printf(MSG_WARNING, "WPA: Failed to set "
			    "GTK to the driver (Group only).");
	} else if (wpa_s->driver->set_key(wpa_s->handle, wpa_s->linkid, alg,
	    (uint8_t *)"\xff\xff\xff\xff\xff\xff", keyidx, tx,
	    key->key_rsc, key_rsc_len, gtk, gtk_len) < 0) {
		wpa_printf(MSG_WARNING, "WPA: Failed to set GTK to "
		    "the driver.");
	}

	wpa_printf(MSG_INFO, "WPA: Key negotiation completed with "
	    MACSTR, MAC2STR(src_addr));
	eloop_cancel_timeout(wpa_supplicant_scan, wpa_s, NULL);
	wpa_supplicant_cancel_auth_timeout(wpa_s);
	wpa_s->wpa_state = WPA_COMPLETED;
}

static void
wpa_supplicant_process_3_of_4(struct wpa_supplicant *wpa_s,
    unsigned char *src_addr, struct wpa_eapol_key *key,
    int extra_len, int ver)
{
	int rlen;
	struct ieee802_1x_hdr *hdr;
	struct wpa_eapol_key *reply;
	unsigned char *rbuf;
	struct l2_ethhdr *ethhdr;
	int key_info, ie_len = 0, keylen, gtk_len = 0;
	uint8_t *ie = NULL, *gtk = NULL, *key_rsc;
	uint8_t null_rsc[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };

	wpa_s->wpa_state = WPA_4WAY_HANDSHAKE;
	wpa_printf(MSG_DEBUG, "WPA: RX message 3 of 4-Way Handshake from "
	    MACSTR " (ver=%d)", MAC2STR(src_addr), ver);

	key_info = BE_16(key->key_info);

	if (wpa_s->proto == WPA_PROTO_RSN) {
		uint8_t *pos = (uint8_t *)(key + 1);
		uint8_t *end = pos + BE_16(key->key_data_length);
		while (pos + 1 < end) {
			if (pos + 2 + pos[1] > end) {
				wpa_printf(MSG_DEBUG, "RSN: key data "
				    "underflow (ie=%d len=%d)",
				    pos[0], pos[1]);
				break;
			}
			if (*pos == RSN_INFO_ELEM) {
				ie = pos;
				ie_len = pos[1] + 2;
			} else if (pos[0] == GENERIC_INFO_ELEM &&
			    pos + 1 + RSN_SELECTOR_LEN < end &&
			    pos[1] > RSN_SELECTOR_LEN + 2 &&
			    memcmp(pos + 2, RSN_KEY_DATA_GROUPKEY,
			    RSN_SELECTOR_LEN) == 0) {
				if (!(key_info & WPA_KEY_INFO_ENCR_KEY_DATA)) {
					wpa_printf(MSG_WARNING, "WPA: GTK IE "
					    "in unencrypted key data");
					return;
				}
				gtk = pos + 2 + RSN_SELECTOR_LEN;
				gtk_len = pos[1] - RSN_SELECTOR_LEN;
			} else if (pos[0] == GENERIC_INFO_ELEM && pos[1] == 0)
				break;

			pos += 2 + pos[1];
		}
	} else {
		ie = (uint8_t *)(key + 1);
		ie_len = BE_16(key->key_data_length);
		if (ie_len > extra_len) {
			wpa_printf(MSG_INFO, "WPA: Truncated EAPOL-Key packet:"
			    " ie_len=%d > extra_len=%d",
			    ie_len, extra_len);
			return;
		}
	}

	if (wpa_s->ap_wpa_ie &&
	    (wpa_s->ap_wpa_ie_len != ie_len ||
	    memcmp(wpa_s->ap_wpa_ie, ie, ie_len) != 0)) {
		wpa_printf(MSG_WARNING, "WPA: WPA IE in 3/4 msg does not match"
		    " with WPA IE in Beacon/ProbeResp (src=" MACSTR ")",
		    MAC2STR(src_addr));
		wpa_hexdump(MSG_INFO, "WPA: WPA IE in Beacon/ProbeResp",
		    wpa_s->ap_wpa_ie, wpa_s->ap_wpa_ie_len);
		wpa_hexdump(MSG_INFO, "WPA: WPA IE in 3/4 msg", ie, ie_len);
		wpa_supplicant_disassociate(wpa_s, REASON_IE_IN_4WAY_DIFFERS);
		wpa_supplicant_req_scan(wpa_s, 0, 0);
		return;
	}

	if (memcmp(wpa_s->anonce, key->key_nonce, WPA_NONCE_LEN) != 0) {
		wpa_printf(MSG_WARNING, "WPA: ANonce from message 1 of 4-Way "
		    "Handshake differs from 3 of 4-Way Handshake - drop"
		    " packet (src=" MACSTR ")", MAC2STR(src_addr));
		return;
	}

	keylen = BE_16(key->key_length);
	switch (wpa_s->pairwise_cipher) {
	case WPA_CIPHER_CCMP:
		if (keylen != 16) {
			wpa_printf(MSG_WARNING, "WPA: Invalid CCMP key length "
			    "%d (src=" MACSTR ")",
			    keylen, MAC2STR(src_addr));
			return;
		}
		break;
	case WPA_CIPHER_TKIP:
		if (keylen != 32) {
			wpa_printf(MSG_WARNING, "WPA: Invalid TKIP key length "
			    "%d (src=" MACSTR ")",
			    keylen, MAC2STR(src_addr));
			return;
		}
		break;
	}

	rlen = sizeof (*ethhdr) + sizeof (*hdr) + sizeof (*reply);
	rbuf = malloc(rlen);
	if (rbuf == NULL)
		return;

	(void) memset(rbuf, 0, rlen);
	ethhdr = (struct l2_ethhdr *)rbuf;
	(void) memcpy(ethhdr->h_dest, src_addr, IEEE80211_ADDR_LEN);
	(void) memcpy(ethhdr->h_source, wpa_s->own_addr, IEEE80211_ADDR_LEN);
	ethhdr->h_proto = htons(ETHERTYPE_EAPOL);

	hdr = (struct ieee802_1x_hdr *)(ethhdr + 1);
	hdr->version = wpa_s->conf->eapol_version;
	hdr->type = IEEE802_1X_TYPE_EAPOL_KEY;
	hdr->length = htons(sizeof (*reply));

	reply = (struct wpa_eapol_key *)(hdr + 1);
	reply->type = wpa_s->proto == WPA_PROTO_RSN ?
	    EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
	reply->key_info = BE_16(ver | WPA_KEY_INFO_KEY_TYPE |
	    WPA_KEY_INFO_MIC | (key_info & WPA_KEY_INFO_SECURE));
	reply->key_length = key->key_length;
	(void) memcpy(reply->replay_counter, key->replay_counter,
	    WPA_REPLAY_COUNTER_LEN);

	reply->key_data_length = BE_16(0);

	(void) memcpy(reply->key_nonce, wpa_s->snonce, WPA_NONCE_LEN);
	wpa_eapol_key_mic(wpa_s->ptk.mic_key, ver, (uint8_t *)hdr,
	    rlen - sizeof (*ethhdr), reply->key_mic);

	wpa_printf(MSG_DEBUG, "WPA: Sending EAPOL-Key 4/4");
	wpa_hexdump(MSG_MSGDUMP, "WPA: TX EAPOL-Key 4/4", rbuf, rlen);
	(void) l2_packet_send(wpa_s->l2, rbuf, rlen);

	free(rbuf);

	/*
	 * SNonce was successfully used in msg 3/4, so mark it to be renewed
	 * for the next 4-Way Handshake. If msg 3 is received again, the old
	 * SNonce will still be used to avoid changing PTK.
	 */
	wpa_s->renew_snonce = 1;

	if (key_info & WPA_KEY_INFO_INSTALL) {
		int alg, keylen, rsclen;
		wpa_printf(MSG_DEBUG, "WPA: Installing PTK to the driver.");
		switch (wpa_s->pairwise_cipher) {
		case WPA_CIPHER_CCMP:
			alg = WPA_ALG_CCMP;
			keylen = 16;
			rsclen = 6;
			break;
		case WPA_CIPHER_TKIP:
			alg = WPA_ALG_TKIP;
			keylen = 32;
			rsclen = 6;
			break;
		case WPA_CIPHER_NONE:
			wpa_printf(MSG_DEBUG, "WPA: Pairwise Cipher Suite: "
			    "NONE - do not use pairwise keys");
			return;
		default:
			wpa_printf(MSG_WARNING, "WPA: Unsupported pairwise "
			    "cipher %d", wpa_s->pairwise_cipher);
			return;
		}
		if (wpa_s->proto == WPA_PROTO_RSN) {
			key_rsc = null_rsc;
		} else {
			key_rsc = key->key_rsc;
			wpa_hexdump(MSG_DEBUG, "WPA: RSC", key_rsc, rsclen);
		}

		if (wpa_s->driver->set_key(wpa_s->handle, wpa_s->linkid, alg,
		    src_addr, 0, 1, key_rsc, rsclen,
		    (uint8_t *)&wpa_s->ptk.tk1, keylen) < 0) {
			wpa_printf(MSG_WARNING, "WPA: Failed to set PTK to the"
			    " driver.");
		}
	}

	wpa_printf(MSG_DEBUG, "%s: key_info=%x gtk=%p\n",
	    "wpa_supplicant_process_3_of_4", key_info, gtk);
	wpa_s->wpa_state = WPA_GROUP_HANDSHAKE;

	if (gtk)
		wpa_supplicant_process_3_of_4_gtk(wpa_s,
		    src_addr, key, gtk, gtk_len);
}

static void
wpa_supplicant_process_1_of_2(struct wpa_supplicant *wpa_s,
    unsigned char *src_addr, struct wpa_eapol_key *key,
    int extra_len, int ver)
{
	int rlen;
	struct ieee802_1x_hdr *hdr;
	struct wpa_eapol_key *reply;
	unsigned char *rbuf;
	struct l2_ethhdr *ethhdr;
	int key_info, keylen, keydatalen, maxkeylen, keyidx, key_rsc_len = 0;
	int alg, tx;
	uint8_t ek[32], tmpbuf[8], gtk[32];
	uint8_t *gtk_ie = NULL;
	size_t gtk_ie_len = 0;

	wpa_s->wpa_state = WPA_GROUP_HANDSHAKE;
	wpa_printf(MSG_DEBUG, "WPA: RX message 1 of Group Key Handshake from "
	    MACSTR " (ver=%d)", MAC2STR(src_addr), ver);

	key_info = BE_16(key->key_info);
	keydatalen = BE_16(key->key_data_length);

	if (wpa_s->proto == WPA_PROTO_RSN) {
		uint8_t *pos = (uint8_t *)(key + 1);
		uint8_t *end = pos + keydatalen;
		while (pos + 1 < end) {
			if (pos + 2 + pos[1] > end) {
				wpa_printf(MSG_DEBUG, "RSN: key data "
				    "underflow (ie=%d len=%d)",
				    pos[0], pos[1]);
				break;
			}
			if (pos[0] == GENERIC_INFO_ELEM &&
			    pos + 1 + RSN_SELECTOR_LEN < end &&
			    pos[1] > RSN_SELECTOR_LEN + 2 &&
			    memcmp(pos + 2, RSN_KEY_DATA_GROUPKEY,
			    RSN_SELECTOR_LEN) == 0) {
				if (!(key_info & WPA_KEY_INFO_ENCR_KEY_DATA)) {
					wpa_printf(MSG_WARNING, "WPA: GTK IE "
					    "in unencrypted key data");
					return;
				}
				gtk_ie = pos + 2 + RSN_SELECTOR_LEN;
				gtk_ie_len = pos[1] - RSN_SELECTOR_LEN;
				break;
			} else if (pos[0] == GENERIC_INFO_ELEM && pos[1] == 0) {
				break;
			}

			pos += 2 + pos[1];
		}

		if (gtk_ie == NULL) {
			wpa_printf(MSG_INFO, "WPA: No GTK IE in Group Key "
			    "message 1/2");
			return;
		}
		maxkeylen = keylen = gtk_ie_len - 2;
	} else {
		keylen = BE_16(key->key_length);
		maxkeylen = keydatalen;
		if (keydatalen > extra_len) {
			wpa_printf(MSG_INFO, "WPA: Truncated EAPOL-Key packet:"
			    " key_data_length=%d > extra_len=%d",
			    keydatalen, extra_len);
			return;
		}
		if (ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES)
			maxkeylen -= 8;
	}

	switch (wpa_s->group_cipher) {
	case WPA_CIPHER_CCMP:
		if (keylen != 16 || maxkeylen < 16) {
			wpa_printf(MSG_WARNING, "WPA: Unsupported CCMP Group "
			    "Cipher key length %d (%d).", keylen, maxkeylen);
			return;
		}
		key_rsc_len = 6;
		alg = WPA_ALG_CCMP;
		break;
	case WPA_CIPHER_TKIP:
		if (keylen != 32 || maxkeylen < 32) {
			wpa_printf(MSG_WARNING, "WPA: Unsupported TKIP Group "
			    "Cipher key length %d (%d).", keylen, maxkeylen);
			return;
		}
		key_rsc_len = 6; /* key->key_data; */
		alg = WPA_ALG_TKIP;
		break;
	case WPA_CIPHER_WEP104:
		if (keylen != 13 || maxkeylen < 13) {
			wpa_printf(MSG_WARNING, "WPA: Unsupported WEP104 Group"
			    " Cipher key length %d (%d).", keylen, maxkeylen);
			return;
		}
		alg = WPA_ALG_WEP;
		break;
	case WPA_CIPHER_WEP40:
		if (keylen != 5 || maxkeylen < 5) {
			wpa_printf(MSG_WARNING, "WPA: Unsupported WEP40 Group "
			    "Cipher key length %d (%d).", keylen, maxkeylen);
			return;
		}
		alg = WPA_ALG_WEP;
		break;
	default:
		wpa_printf(MSG_WARNING, "WPA: Unsupport Group Cipher %d",
		    wpa_s->group_cipher);
		return;
	}

	if (wpa_s->proto == WPA_PROTO_RSN) {
		wpa_hexdump(MSG_DEBUG,
		    "WPA: received GTK in group key handshake",
		    gtk_ie, gtk_ie_len);
		keyidx = gtk_ie[0] & 0x3;
		tx = !!(gtk_ie[0] & BIT(2));
		if (gtk_ie_len - 2 > sizeof (gtk)) {
			wpa_printf(MSG_INFO, "WPA: Too long GTK in GTK IE "
			    "(len=%d)", gtk_ie_len - 2);
			return;
		}
		(void) memcpy(gtk, gtk_ie + 2, gtk_ie_len - 2);
	} else {
		keyidx = (key_info & WPA_KEY_INFO_KEY_INDEX_MASK) >>
		    WPA_KEY_INFO_KEY_INDEX_SHIFT;
		if (ver == WPA_KEY_INFO_TYPE_HMAC_MD5_RC4) {
			(void) memcpy(ek, key->key_iv, 16);
			(void) memcpy(ek + 16, wpa_s->ptk.encr_key, 16);
			rc4_skip(ek, 32, 256, (uint8_t *)(key + 1), keydatalen);
			(void) memcpy(gtk, key + 1, keylen);
		} else if (ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
			if (keydatalen % 8) {
				wpa_printf(MSG_WARNING, "WPA: Unsupported "
				    "AES-WRAP len %d", keydatalen);
				return;
			}
			if (aes_unwrap(wpa_s->ptk.encr_key, maxkeylen / 8,
			    (uint8_t *)(key + 1), gtk)) {
				wpa_printf(MSG_WARNING, "WPA: AES unwrap "
				    "failed - could not decrypt GTK");
				return;
			}
		}
		tx = !!(key_info & WPA_KEY_INFO_TXRX);
		if (tx && wpa_s->pairwise_cipher != WPA_CIPHER_NONE) {
			/*
			 * Ignore Tx bit in Group Key message if a pairwise key
			 * is used. Some APs seem to setting this bit
			 * (incorrectly, since Tx is only when doing Group Key
			 * only APs) and without this workaround, the data
			 * connection does not work because wpa_supplicant
			 * configured non-zero keyidx to be used for unicast.
			 */
			wpa_printf(MSG_INFO, "WPA: Tx bit set for GTK, but "
			    "pairwise keys are used - ignore Tx bit");
			tx = 0;
		}
	}
	wpa_hexdump(MSG_DEBUG, "WPA: Group Key", gtk, keylen);
	wpa_printf(MSG_DEBUG, "WPA: Installing GTK to the driver (keyidx=%d "
	    "tx=%d).", keyidx, tx);
	wpa_hexdump(MSG_DEBUG, "WPA: RSC", key->key_rsc, key_rsc_len);
	if (wpa_s->group_cipher == WPA_CIPHER_TKIP) {
		/*
		 * Swap Tx/Rx keys for Michael MIC
		 */
		(void) memcpy(tmpbuf, gtk + 16, 8);
		(void) memcpy(gtk + 16, gtk + 24, 8);
		(void) memcpy(gtk + 24, tmpbuf, 8);
	}
	if (wpa_s->pairwise_cipher == WPA_CIPHER_NONE) {
		if (wpa_s->driver->set_key(wpa_s->handle, wpa_s->linkid, alg,
		    (uint8_t *)"\xff\xff\xff\xff\xff\xff",
		    keyidx, 1, key->key_rsc,
		    key_rsc_len, gtk, keylen) < 0)
			wpa_printf(MSG_WARNING, "WPA: Failed to set GTK to the"
			    " driver (Group only).");
	} else if (wpa_s->driver->set_key(wpa_s->handle, wpa_s->linkid, alg,
	    (uint8_t *)"\xff\xff\xff\xff\xff\xff",
	    keyidx, tx,
	    key->key_rsc, key_rsc_len,
	    gtk, keylen) < 0) {
		wpa_printf(MSG_WARNING, "WPA: Failed to set GTK to the "
		    "driver.");
	}

	rlen = sizeof (*ethhdr) + sizeof (*hdr) + sizeof (*reply);
	rbuf = malloc(rlen);
	if (rbuf == NULL)
		return;

	(void) memset(rbuf, 0, rlen);
	ethhdr = (struct l2_ethhdr *)rbuf;
	(void) memcpy(ethhdr->h_dest, src_addr, IEEE80211_ADDR_LEN);
	(void) memcpy(ethhdr->h_source, wpa_s->own_addr, IEEE80211_ADDR_LEN);
	ethhdr->h_proto = htons(ETHERTYPE_EAPOL);

	hdr = (struct ieee802_1x_hdr *)(ethhdr + 1);
	hdr->version = wpa_s->conf->eapol_version;
	hdr->type = IEEE802_1X_TYPE_EAPOL_KEY;
	hdr->length = htons(sizeof (*reply));

	reply = (struct wpa_eapol_key *)(hdr + 1);
	reply->type = wpa_s->proto == WPA_PROTO_RSN ?
	    EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
	reply->key_info =
	    BE_16(ver | WPA_KEY_INFO_MIC | WPA_KEY_INFO_SECURE |
	    (key_info & WPA_KEY_INFO_KEY_INDEX_MASK));
	reply->key_length = key->key_length;
	(void) memcpy(reply->replay_counter, key->replay_counter,
	    WPA_REPLAY_COUNTER_LEN);

	reply->key_data_length = BE_16(0);

	wpa_eapol_key_mic(wpa_s->ptk.mic_key, ver, (uint8_t *)hdr,
	    rlen - sizeof (*ethhdr), reply->key_mic);

	wpa_printf(MSG_DEBUG, "WPA: Sending EAPOL-Key 2/2");
	wpa_hexdump(MSG_MSGDUMP, "WPA: TX EAPOL-Key 2/2", rbuf, rlen);
	(void) l2_packet_send(wpa_s->l2, rbuf, rlen);
	free(rbuf);

	wpa_printf(MSG_INFO, "WPA: Key negotiation completed with " MACSTR,
	    MAC2STR(src_addr));
	eloop_cancel_timeout(wpa_supplicant_scan, wpa_s, NULL);
	wpa_supplicant_cancel_auth_timeout(wpa_s);
	wpa_s->wpa_state = WPA_COMPLETED;
	wpa_printf(MSG_INFO, "-----------------------------------\n");
}

static int
wpa_supplicant_verify_eapol_key_mic(struct wpa_supplicant *wpa_s,
    struct wpa_eapol_key *key, int ver, uint8_t *buf, size_t len)
{
	uint8_t mic[16];
	int ok = 0;

	(void) memcpy(mic, key->key_mic, 16);
	if (wpa_s->tptk_set) {
		(void) memset(key->key_mic, 0, 16);
		wpa_eapol_key_mic(wpa_s->tptk.mic_key, ver, buf, len,
		    key->key_mic);
		if (memcmp(mic, key->key_mic, 16) != 0) {
			wpa_printf(MSG_WARNING, "WPA: Invalid EAPOL-Key MIC "
			    "when using TPTK - ignoring TPTK");
		} else {
			ok = 1;
			wpa_s->tptk_set = 0;
			wpa_s->ptk_set = 1;
			(void) memcpy(&wpa_s->ptk, &wpa_s->tptk,
			    sizeof (wpa_s->ptk));
		}
	}

	if (!ok && wpa_s->ptk_set) {
		(void) memset(key->key_mic, 0, 16);
		wpa_eapol_key_mic(wpa_s->ptk.mic_key, ver, buf, len,
		    key->key_mic);
		if (memcmp(mic, key->key_mic, 16) != 0) {
			wpa_printf(MSG_WARNING, "WPA: Invalid EAPOL-Key MIC "
			    "- dropping packet");
			return (-1);
		}
		ok = 1;
	}

	if (!ok) {
		wpa_printf(MSG_WARNING, "WPA: Could not verify EAPOL-Key MIC "
		    "- dropping packet");
		return (-1);
	}

	(void) memcpy(wpa_s->rx_replay_counter, key->replay_counter,
	    WPA_REPLAY_COUNTER_LEN);
	wpa_s->rx_replay_counter_set = 1;

	return (0);
}

/* Decrypt RSN EAPOL-Key key data (RC4 or AES-WRAP) */
static int
wpa_supplicant_decrypt_key_data(struct wpa_supplicant *wpa_s,
	struct wpa_eapol_key *key, int ver)
{
	int keydatalen = BE_16(key->key_data_length);

	wpa_hexdump(MSG_DEBUG, "RSN: encrypted key data",
	    (uint8_t *)(key + 1), keydatalen);
	if (!wpa_s->ptk_set) {
		wpa_printf(MSG_WARNING, "WPA: PTK not available, "
		    "cannot decrypt EAPOL-Key key data.");
		return (-1);
	}

	/*
	 * Decrypt key data here so that this operation does not need
	 * to be implemented separately for each message type.
	 */
	if (ver == WPA_KEY_INFO_TYPE_HMAC_MD5_RC4) {
		uint8_t ek[32];
		(void) memcpy(ek, key->key_iv, 16);
		(void) memcpy(ek + 16, wpa_s->ptk.encr_key, 16);
		rc4_skip(ek, 32, 256, (uint8_t *)(key + 1), keydatalen);
	} else if (ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
		uint8_t *buf;
		if (keydatalen % 8) {
			wpa_printf(MSG_WARNING, "WPA: Unsupported "
			    "AES-WRAP len %d", keydatalen);
			return (-1);
		}
		keydatalen -= 8; /* AES-WRAP adds 8 bytes */
		buf = malloc(keydatalen);
		if (buf == NULL) {
			wpa_printf(MSG_WARNING, "WPA: No memory for "
			    "AES-UNWRAP buffer");
			return (-1);
		}
		if (aes_unwrap(wpa_s->ptk.encr_key, keydatalen / 8,
		    (uint8_t *)(key + 1), buf)) {
			free(buf);
			wpa_printf(MSG_WARNING, "WPA: AES unwrap failed - "
			    "could not decrypt EAPOL-Key key data");
			return (-1);
		}
		(void) memcpy(key + 1, buf, keydatalen);
		free(buf);
		key->key_data_length = BE_16(keydatalen);
	}
	wpa_hexdump(MSG_DEBUG, "WPA: decrypted EAPOL-Key key data",
	    (uint8_t *)(key + 1), keydatalen);

	return (0);
}

static void
wpa_sm_rx_eapol(struct wpa_supplicant *wpa_s,
    unsigned char *src_addr, unsigned char *buf, size_t len)
{
	size_t plen, data_len, extra_len;
	struct ieee802_1x_hdr *hdr;
	struct wpa_eapol_key *key;
	int key_info, ver;

	wpa_printf(MSG_DEBUG, "WPA: EAPOL frame len %u\n ", len);

	hdr = (struct ieee802_1x_hdr *)buf;
	key = (struct wpa_eapol_key *)(hdr + 1);
	wpa_printf(MSG_DEBUG, "hdr_len=%u, key_len=%u",
	    sizeof (*hdr), sizeof (*key));
	if (len < sizeof (*hdr) + sizeof (*key)) {
		wpa_printf(MSG_DEBUG, "WPA: EAPOL frame too short, len %u, "
		    "expecting at least %u",
		    len, sizeof (*hdr) + sizeof (*key));
		return;
	}
	plen = ntohs(hdr->length);
	data_len = plen + sizeof (*hdr);
	wpa_printf(MSG_DEBUG, "IEEE 802.1X RX: version=%d type=%d length=%d",
	    hdr->version, hdr->type, plen);

	if (hdr->type != IEEE802_1X_TYPE_EAPOL_KEY) {
		wpa_printf(MSG_DEBUG, "WPA: EAPOL frame (type %u) discarded, "
		    "not a Key frame", hdr->type);
		return;
	}
	if (plen > len - sizeof (*hdr) || plen < sizeof (*key)) {
		wpa_printf(MSG_DEBUG, "WPA: EAPOL frame payload size %u "
		    "invalid (frame size %u)", plen, len);
		return;
	}

	wpa_printf(MSG_DEBUG, "  EAPOL-Key type=%d", key->type);
	if (key->type != EAPOL_KEY_TYPE_WPA && key->type !=
	    EAPOL_KEY_TYPE_RSN) {
		wpa_printf(MSG_DEBUG, "WPA: EAPOL-Key type (%d) unknown, "
		    "discarded", key->type);
		return;
	}

	wpa_hexdump(MSG_MSGDUMP, "WPA: RX EAPOL-Key", buf, len);
	if (data_len < len) {
		wpa_printf(MSG_DEBUG, "WPA: ignoring %d bytes after the IEEE "
		    "802.1X data", len - data_len);
	}
	key_info = BE_16(key->key_info);
	ver = key_info & WPA_KEY_INFO_TYPE_MASK;
	if (ver != WPA_KEY_INFO_TYPE_HMAC_MD5_RC4 &&
	    ver != WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
		wpa_printf(MSG_INFO, "WPA: Unsupported EAPOL-Key descriptor "
		    "version %d.", ver);
		return;
	}

	if (wpa_s->pairwise_cipher == WPA_CIPHER_CCMP &&
	    ver != WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
		wpa_printf(MSG_INFO, "WPA: CCMP is used, but EAPOL-Key "
		    "descriptor version (%d) is not 2.", ver);
		if (wpa_s->group_cipher != WPA_CIPHER_CCMP &&
		    !(key_info & WPA_KEY_INFO_KEY_TYPE)) {
			/*
			 * Earlier versions of IEEE 802.11i did not explicitly
			 * require version 2 descriptor for all EAPOL-Key
			 * packets, so allow group keys to use version 1 if
			 * CCMP is not used for them.
			 */
			wpa_printf(MSG_INFO, "WPA: Backwards compatibility: "
			    "allow invalid version for non-CCMP group keys");
		} else
			return;
	}

	if (wpa_s->rx_replay_counter_set &&
	    memcmp(key->replay_counter, wpa_s->rx_replay_counter,
	    WPA_REPLAY_COUNTER_LEN) <= 0) {
		wpa_printf(MSG_WARNING, "WPA: EAPOL-Key Replay Counter did not"
		    " increase - dropping packet");
		return;
	}

	if (!(key_info & WPA_KEY_INFO_ACK)) {
		wpa_printf(MSG_INFO, "WPA: No Ack bit in key_info");
		return;
	}

	if (key_info & WPA_KEY_INFO_REQUEST) {
		wpa_printf(MSG_INFO, "WPA: EAPOL-Key with Request bit - "
		    "dropped");
		return;
	}

	if ((key_info & WPA_KEY_INFO_MIC) &&
	    wpa_supplicant_verify_eapol_key_mic(wpa_s, key, ver, buf,
	    data_len)) {
		return;
	}

	extra_len = data_len - sizeof (*hdr) - sizeof (*key);

	if (wpa_s->proto == WPA_PROTO_RSN &&
	    (key_info & WPA_KEY_INFO_ENCR_KEY_DATA) &&
	    wpa_supplicant_decrypt_key_data(wpa_s, key, ver))
		return;

	if (key_info & WPA_KEY_INFO_KEY_TYPE) {
		if (key_info & WPA_KEY_INFO_KEY_INDEX_MASK) {
			wpa_printf(MSG_WARNING, "WPA: Ignored EAPOL-Key "
			    "(Pairwise) with non-zero key index");
			return;
		}
		if (key_info & WPA_KEY_INFO_MIC) {
			/* 3/4 4-Way Handshake */
			wpa_supplicant_process_3_of_4(wpa_s, src_addr, key,
			    extra_len, ver);
		} else {
			/* 1/4 4-Way Handshake */
			wpa_supplicant_process_1_of_4(wpa_s, src_addr, key,
			    ver);
		}
	} else {
		if (key_info & WPA_KEY_INFO_MIC) {
			/* 1/2 Group Key Handshake */
			wpa_supplicant_process_1_of_2(wpa_s, src_addr, key,
			    extra_len, ver);
		} else {
			wpa_printf(MSG_WARNING, "WPA: EAPOL-Key (Group) "
			    "without Mic bit - dropped");
		}
	}
}

void
wpa_supplicant_rx_eapol(void *ctx, unsigned char *src_addr,
    unsigned char *buf, size_t len)
{
	struct wpa_supplicant *wpa_s = ctx;

	wpa_printf(MSG_DEBUG, "RX EAPOL from " MACSTR, MAC2STR(src_addr));
	wpa_hexdump(MSG_MSGDUMP, "RX EAPOL", buf, len);

	if (wpa_s->eapol_received == 0) {
		/* Timeout for completing IEEE 802.1X and WPA authentication */
		wpa_supplicant_req_auth_timeout(
		    wpa_s, wpa_s->key_mgmt == WPA_KEY_MGMT_IEEE8021X ?
		    70 : 10, 0);
	}
	wpa_s->eapol_received++;

	/*
	 * Source address of the incoming EAPOL frame could be compared to the
	 * current BSSID. However, it is possible that a centralized
	 * Authenticator could be using another MAC address than the BSSID of
	 * an AP, so just allow any address to be used for now. The replies are
	 * still sent to the current BSSID (if available), though.
	 */
	wpa_sm_rx_eapol(wpa_s, src_addr, buf, len);
}
<?xml version="1.0"?>
<!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1">
<!--
	Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
	Use is subject to license terms.

 CDDL HEADER START

 The contents of this file are subject to the terms of the
 Common Development and Distribution License (the "License").
 You may not use this file except in compliance with the License.

 You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 or http://www.opensolaris.org/os/licensing.
 See the License for the specific language governing permissions
 and limitations under the License.

 When distributing Covered Code, include this CDDL HEADER in each
 file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 If applicable, add the following below this CDDL HEADER, with the
 fields enclosed by brackets "[]" replaced with your own identifying
 information: Portions Copyright [yyyy] [name of copyright owner]

 CDDL HEADER END

	NOTE:  This service manifest is not editable; its contents will
	be overwritten by package or patch operations, including
	operating system upgrade.  Make customizations in a different
	file.
-->

<service_bundle type='manifest' name='SUNWsupr:wpad'>

<service
	name='network/wpa'
	type='service'
	version='1'>

	<!--
	    The wpa service will use the crypto framework of
	    PKCS #11 when we come to the enterprise mode.
	-->
	<dependency
	    name='cryptosvc'
	    grouping='require_all'
	    restart_on='none'
	    type='service'>
		<service_fmri value='svc:/system/cryptosvc' />
	</dependency>

	<exec_method
		type='method'
		name='start'
		exec='/usr/lib/inet/wpad'
		timeout_seconds='60' >
		<method_context working_directory='/'>
			<method_credential
				user='root'
				group='root'
				limit_privileges=':default'
				privileges='basic,sys_net_config,net_rawaccess'
			/>
		</method_context>
	</exec_method>

	<exec_method
		type='method'
		name='stop'
		exec=':kill'
		timeout_seconds='60' />

        <property_group name='general' type='framework'>
                <!-- to start stop wpad -->
                <propval name='action_authorization' type='astring'
                        value='solaris.smf.manage.wpa' />
        </property_group>

	<stability value='Unstable' />

	<template>
		<common_name>
			<loctext xml:lang='C'>
			Wireless WPA Supplicant
			</loctext>
		</common_name>
		<documentation>
			<manpage title='wpad' section='8'
			    manpath='/usr/share/man' />
		</documentation>
	</template>
</service>

</service_bundle>
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
 * Sun elects to license this software under the BSD license.
 * See README for more details.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>

#include <openssl/aes.h>
#include <openssl/hmac.h>
#include <openssl/rc4.h>

#include "wpa_enc.h"

/*
 * @kek: key encryption key (KEK)
 * @n: length of the wrapped key in 64-bit units; e.g., 2 = 128-bit = 16 bytes
 * @plain: plaintext key to be wrapped, n * 64 bit
 * @cipher: wrapped key, (n + 1) * 64 bit
 */
void
aes_wrap(uint8_t *kek, int n, uint8_t *plain, uint8_t *cipher)
{
	uint8_t *a, *r, b[16];
	int i, j;
	AES_KEY key;

	a = cipher;
	r = cipher + 8;

	/* 1) Initialize variables. */
	(void) memset(a, 0xa6, 8);
	(void) memcpy(r, plain, 8 * n);

	(void) AES_set_encrypt_key(kek, 128, &key);

	/*
	 * 2) Calculate intermediate values.
	 * For j = 0 to 5
	 * 	For i=1 to n
	 * 		B = AES(K, A | R[i])
	 * 		A = MSB(64, B) ^ t where t = (n*j)+i
	 * 		R[i] = LSB(64, B)
	 */
	for (j = 0; j <= 5; j++) {
		r = cipher + 8;
		for (i = 1; i <= n; i++) {
			(void) memcpy(b, a, 8);
			(void) memcpy(b + 8, r, 8);
			AES_encrypt(b, b, &key);
			(void) memcpy(a, b, 8);
			a[7] ^= n * j + i;
			(void) memcpy(r, b + 8, 8);
			r += 8;
		}
	}

	/*
	 * 3) Output the results.
	 *
	 * These are already in @cipher due to the location of temporary
	 * variables.
	 */
}

/*
 * @kek: key encryption key (KEK)
 * @n: length of the wrapped key in 64-bit units; e.g., 2 = 128-bit = 16 bytes
 * @cipher: wrapped key to be unwrapped, (n + 1) * 64 bit
 * @plain: plaintext key, n * 64 bit
 */
int
aes_unwrap(uint8_t *kek, int n, uint8_t *cipher, uint8_t *plain)
{
	uint8_t a[8], *r, b[16];
	int i, j;
	AES_KEY key;

	/* 1) Initialize variables. */
	(void) memcpy(a, cipher, 8);
	r = plain;
	(void) memcpy(r, cipher + 8, 8 * n);

	(void) AES_set_decrypt_key(kek, 128, &key);

	/*
	 * 2) Compute intermediate values.
	 * For j = 5 to 0
	 * 	For i = n to 1
	 * 		B = AES-1(K, (A ^ t) | R[i]) where t = n*j+i
	 * 		A = MSB(64, B)
	 * 		R[i] = LSB(64, B)
	 */
	for (j = 5; j >= 0; j--) {
		r = plain + (n - 1) * 8;
		for (i = n; i >= 1; i--) {
			(void) memcpy(b, a, 8);
			b[7] ^= n * j + i;

			(void) memcpy(b + 8, r, 8);
			AES_decrypt(b, b, &key);
			(void) memcpy(a, b, 8);
			(void) memcpy(r, b + 8, 8);
			r -= 8;
		}
	}

	/*
	 * 3) Output results.
	 *
	 * These are already in @plain due to the location of temporary
	 * variables. Just verify that the IV matches with the expected value.
	 */
	for (i = 0; i < 8; i++) {
		if (a[i] != 0xa6) {
			return (-1);
		}
	}

	return (0);
}

/* RFC 2104 */
void
hmac_sha1(unsigned char *key, unsigned int key_len,
    unsigned char *data, unsigned int data_len, unsigned char *mac)
{
	unsigned int mac_len = 0;
	(void) HMAC(EVP_sha1(), key, key_len, data, data_len, mac, &mac_len);
}


void
hmac_sha1_vector(unsigned char *key, unsigned int key_len, size_t num_elem,
    unsigned char *addr[], unsigned int *len, unsigned char *mac)
{
	unsigned char *buf, *ptr;
	int i, buf_len;

	buf_len = 0;
	for (i = 0; i < num_elem; i ++)
		buf_len += len[i];

	buf = malloc(buf_len);
	ptr = buf;

	for (i = 0; i < num_elem; i ++) {
		(void) memcpy(ptr, addr[i], len[i]);
		ptr += len[i];
	}

	hmac_sha1(key, key_len, buf, buf_len, mac);

	free(buf);
}


void
sha1_prf(unsigned char *key, unsigned int key_len,
    char *label, unsigned char *data, unsigned int data_len,
    unsigned char *buf, size_t buf_len)
{
	uint8_t zero = 0, counter = 0;
	size_t pos, plen;
	uint8_t hash[SHA1_MAC_LEN];
	size_t label_len = strlen(label);

	unsigned char *addr[4];
	unsigned int len[4];

	addr[0] = (uint8_t *)label;
	len[0] = label_len;
	addr[1] = &zero;
	len[1] = 1;
	addr[2] = data;
	len[2] = data_len;
	addr[3] = &counter;
	len[3] = 1;

	pos = 0;
	while (pos < buf_len) {
		plen = buf_len - pos;
		if (plen >= SHA1_MAC_LEN) {
			hmac_sha1_vector(key, key_len, 4, addr, len, &buf[pos]);
			pos += SHA1_MAC_LEN;
		} else {
			hmac_sha1_vector(key, key_len, 4, addr, len, hash);
			(void) memcpy(&buf[pos], hash, plen);
			break;
		}
		counter++;
	}
}

void
pbkdf2_sha1(char *passphrase, char *ssid, size_t ssid_len, int iterations,
    unsigned char *buf, size_t buflen)
{
	(void) PKCS5_PBKDF2_HMAC_SHA1(passphrase, -1, (unsigned char *)ssid,
	    ssid_len, iterations, buflen, buf);
}

void
rc4_skip(uint8_t *key, size_t keylen, size_t skip,
    uint8_t *data, size_t data_len)
{
	uint8_t *buf;
	size_t buf_len;

	buf_len = skip + data_len;
	buf = malloc(buf_len);

	bzero(buf, buf_len);
	bcopy(data, buf + skip, data_len);

	rc4(buf, buf_len, key, keylen);

	bcopy(buf + skip, data, data_len);
	free(buf);
}

void
rc4(uint8_t *buf, size_t len, uint8_t *key, size_t key_len)
{
	RC4_KEY k;

	RC4_set_key(&k, key_len, key);
	RC4(&k, len, buf, buf);
}

void
hmac_md5_vector(uint8_t *key, size_t key_len, size_t num_elem,
    uint8_t *addr[], size_t *len, uint8_t *mac)
{
	unsigned char *buf, *ptr;
	int i, buf_len;

	buf_len = 0;
	for (i = 0; i < num_elem; i ++)
		buf_len += len[i];

	buf = malloc(buf_len);
	ptr = buf;

	for (i = 0; i < num_elem; i ++) {
		(void) memcpy(ptr, addr[i], len[i]);
		ptr += len[i];
	}

	hmac_md5(key, key_len, buf, buf_len, mac);
	free(buf);
}

/* RFC 2104 */
void
hmac_md5(uint8_t *key, size_t key_len, uint8_t *data,
    size_t data_len, uint8_t *mac)
{
	unsigned int mac_len = 0;
	(void) HMAC(EVP_md5(), key, key_len, data, data_len, mac, &mac_len);
}
/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
 * Sun elects to license this software under the BSD license.
 * See README for more details.
 */
#ifndef __WPA_ENC_H
#define	__WPA_ENC_H

#include <openssl/sha.h>
#include <openssl/md5.h>

#ifdef	__cplusplus
extern "C" {
#endif

#define	SHA1_MAC_LEN	SHA_DIGEST_LENGTH
#define	MD5_MAC_LEN	MD5_DIGEST_LENGTH

void aes_wrap(uint8_t *, int, uint8_t *, uint8_t *);
int aes_unwrap(uint8_t *, int, uint8_t *, uint8_t *);

void hmac_sha1_vector(unsigned char *, unsigned int,
    size_t, unsigned char *[], unsigned int *, unsigned char *);

void hmac_sha1(unsigned char *, unsigned int,
    unsigned char *, unsigned int, unsigned char *);

void sha1_prf(unsigned char *, unsigned int,
    char *, unsigned char *, unsigned int, unsigned char *, size_t);

void pbkdf2_sha1(char *, char *, size_t, int, unsigned char *, size_t);

void rc4_skip(uint8_t *, size_t, size_t, uint8_t *, size_t);
void rc4(uint8_t *, size_t, uint8_t *, size_t);

void hmac_md5_vector(uint8_t *, size_t, size_t,
    uint8_t *[], size_t *, uint8_t *);
void hmac_md5(uint8_t *, size_t, uint8_t *, size_t, uint8_t *);

#ifdef __cplusplus
}
#endif

#endif /* __WPA_ENC_H */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
 * Sun elects to license this software under the BSD license.
 * See README for more details.
 */
#ifndef __WPA_IMPL_H
#define	__WPA_IMPL_H

#include <net/wpa.h>
#include <libdladm.h>
#include <libdllink.h>

#ifdef	__cplusplus
extern "C" {
#endif

#define	BIT(n)			(1 << (n))

#define	WPA_CIPHER_NONE		BIT(0)
#define	WPA_CIPHER_WEP40	BIT(1)
#define	WPA_CIPHER_WEP104	BIT(2)
#define	WPA_CIPHER_TKIP		BIT(3)
#define	WPA_CIPHER_CCMP		BIT(4)

#define	WPA_KEY_MGMT_IEEE8021X	BIT(0)
#define	WPA_KEY_MGMT_PSK	BIT(1)
#define	WPA_KEY_MGMT_NONE	BIT(2)
#define	WPA_KEY_MGMT_IEEE8021X_NO_WPA	BIT(3)

#define	WPA_PROTO_WPA		BIT(0)
#define	WPA_PROTO_RSN		BIT(1)

#pragma pack(1)
struct ieee802_1x_hdr {
	uint8_t		version;
	uint8_t		type;
	uint16_t	length;
	/* followed by length octets of data */
};
#pragma pack()

#define	EAPOL_VERSION	2

enum {	IEEE802_1X_TYPE_EAP_PACKET	= 0,
	IEEE802_1X_TYPE_EAPOL_START	= 1,
	IEEE802_1X_TYPE_EAPOL_LOGOFF	= 2,
	IEEE802_1X_TYPE_EAPOL_KEY	= 3,
	IEEE802_1X_TYPE_EAPOL_ENCAPSULATED_ASF_ALERT	= 4
};

enum {	EAPOL_KEY_TYPE_RC4 = 1,
	EAPOL_KEY_TYPE_RSN = 2,
	EAPOL_KEY_TYPE_WPA = 254
};

#define	WPA_NONCE_LEN		32
#define	WPA_REPLAY_COUNTER_LEN	8
#define	MAX_PSK_LENGTH		64
#define	WPA_PMK_LEN		32

#pragma pack(1)
struct wpa_eapol_key {
	uint8_t		type;
	uint16_t	key_info;
	uint16_t	key_length;
	uint8_t		replay_counter[WPA_REPLAY_COUNTER_LEN];
	uint8_t		key_nonce[WPA_NONCE_LEN];
	uint8_t		key_iv[16];
	uint8_t		key_rsc[8];
	uint8_t		key_id[8]; /* Reserved in IEEE 802.11i/RSN */
	uint8_t		key_mic[16];
	uint16_t	key_data_length;
	/* followed by key_data_length bytes of key_data */
};
#pragma pack()

#define	WPA_KEY_INFO_TYPE_MASK		(BIT(0) | BIT(1) | BIT(2))
#define	WPA_KEY_INFO_TYPE_HMAC_MD5_RC4	BIT(0)
#define	WPA_KEY_INFO_TYPE_HMAC_SHA1_AES	BIT(1)
#define	WPA_KEY_INFO_KEY_TYPE		BIT(3) /* 1: Pairwise, 0: Group key */
/* bit4..5 is used in WPA, but is reserved in IEEE 802.11i/RSN */
#define	WPA_KEY_INFO_KEY_INDEX_MASK	(BIT(4) | BIT(5))
#define	WPA_KEY_INFO_KEY_INDEX_SHIFT	4
#define	WPA_KEY_INFO_INSTALL		BIT(6) /* pairwise */
#define	WPA_KEY_INFO_TXRX		BIT(6) /* group */
#define	WPA_KEY_INFO_ACK		BIT(7)
#define	WPA_KEY_INFO_MIC		BIT(8)
#define	WPA_KEY_INFO_SECURE		BIT(9)
#define	WPA_KEY_INFO_ERROR		BIT(10)
#define	WPA_KEY_INFO_REQUEST		BIT(11)
#define	WPA_KEY_INFO_ENCR_KEY_DATA	BIT(12) /* IEEE 802.11i/RSN only */

#define	WPA_CAPABILITY_PREAUTH		BIT(0)

#define	GENERIC_INFO_ELEM		0xdd
#define	RSN_INFO_ELEM			0x30

#define	MAX_LOGBUF			4096
#define	MAX_SCANRESULTS			64

enum {
	REASON_UNSPECIFIED			= 1,
	REASON_DEAUTH_LEAVING			= 3,
	REASON_INVALID_IE			= 13,
	REASON_MICHAEL_MIC_FAILURE		= 14,
	REASON_4WAY_HANDSHAKE_TIMEOUT		= 15,
	REASON_GROUP_KEY_UPDATE_TIMEOUT		= 16,
	REASON_IE_IN_4WAY_DIFFERS		= 17,
	REASON_GROUP_CIPHER_NOT_VALID		= 18,
	REASON_PAIRWISE_CIPHER_NOT_VALID	= 19,
	REASON_AKMP_NOT_VALID			= 20,
	REASON_UNSUPPORTED_RSN_IE_VERSION	= 21,
	REASON_INVALID_RSN_IE_CAPAB		= 22,
	REASON_IEEE_802_1X_AUTH_FAILED		= 23,
	REASON_CIPHER_SUITE_REJECTED		= 24
};

/*
 * wpa_supplicant
 */
#define	PMKID_LEN 			16
#define	PMK_LEN				32

#define	MAC2STR(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5]
#define	MACSTR "%02x:%02x:%02x:%02x:%02x:%02x"

struct rsn_pmksa_cache {
	struct rsn_pmksa_cache	*next;
	uint8_t			pmkid[PMKID_LEN];
	uint8_t			pmk[PMK_LEN];
	time_t			expiration;
	int			akmp; /* WPA_KEY_MGMT_* */
	uint8_t			aa[IEEE80211_ADDR_LEN];
};

struct rsn_pmksa_candidate {
	struct rsn_pmksa_candidate *next;
	uint8_t			bssid[IEEE80211_ADDR_LEN];
};


#pragma pack(1)
struct wpa_ptk {
	uint8_t mic_key[16]; /* EAPOL-Key MIC Key (MK) */
	uint8_t encr_key[16]; /* EAPOL-Key Encryption Key (EK) */
	uint8_t tk1[16]; /* Temporal Key 1 (TK1) */
	union {
		uint8_t tk2[16]; /* Temporal Key 2 (TK2) */
		struct {
			uint8_t tx_mic_key[8];
			uint8_t rx_mic_key[8];
		} auth;
	} u;
};
#pragma pack()


struct wpa_supplicant {
	struct l2_packet_data	*l2;
	unsigned char		own_addr[IEEE80211_ADDR_LEN];

	/* The handle required for libdladm calls */
	dladm_handle_t		handle;

	datalink_id_t		linkid;
	char			kname[DLADM_SECOBJ_NAME_MAX];

	uint8_t			pmk[PMK_LEN];

	uint8_t			snonce[WPA_NONCE_LEN];
	uint8_t			anonce[WPA_NONCE_LEN];
	/* ANonce from the last 1/4 msg */

	struct wpa_ptk		ptk, tptk;
	int			ptk_set, tptk_set;
	int			renew_snonce;

	struct wpa_config	*conf;

	uint8_t			request_counter[WPA_REPLAY_COUNTER_LEN];
	uint8_t			rx_replay_counter[WPA_REPLAY_COUNTER_LEN];
	int			rx_replay_counter_set;

	uint8_t			bssid[IEEE80211_ADDR_LEN];
	int			reassociate; /* reassociation requested */

	uint8_t			*ap_wpa_ie;
	size_t			ap_wpa_ie_len;

	/*
	 * Selected configuration
	 * based on Beacon/ProbeResp WPA IE
	 */
	int			proto;
	int 			pairwise_cipher;
	int 			group_cipher;
	int			key_mgmt;

	struct wpa_driver_ops	*driver;

	enum {
		WPA_DISCONNECTED,
		WPA_SCANNING,
		WPA_ASSOCIATING,
		WPA_ASSOCIATED,
		WPA_4WAY_HANDSHAKE,
		WPA_GROUP_HANDSHAKE,
		WPA_COMPLETED
	} wpa_state;

	struct rsn_pmksa_cache	*pmksa; /* PMKSA cache */
	int	pmksa_count; /* number of entries in PMKSA cache */
	struct rsn_pmksa_cache	*cur_pmksa; /* current PMKSA entry */
	struct rsn_pmksa_candidate	*pmksa_candidates;

	/*
	 * number of EAPOL packets received after the
	 * previous association event
	 */
	int			eapol_received;
};

struct wpa_ie_data {
	int	proto;
	int	pairwise_cipher;
	int	group_cipher;
	int	key_mgmt;
	int	capabilities;
};

/* WPA configuration */
struct wpa_ssid {
	uint8_t	*ssid;
	size_t	ssid_len;

	uint8_t	bssid[IEEE80211_ADDR_LEN];
	int	bssid_set;

	uint8_t	psk[PMK_LEN];
	int	psk_set;
	char	*passphrase;

	/* Bitfields of allowed Pairwise/Group Ciphers, WPA_CIPHER_* */
	int	pairwise_cipher;
	int	group_cipher;

	int	key_mgmt;
	int	proto; /* Bitfield of allowed protocols (WPA_PROTO_*) */
};

struct wpa_config {
	struct wpa_ssid *ssid; /* global network list */
	int eapol_version;
	/* int ap_scan; */
};

struct wpa_config *wpa_config_read(void *);
void wpa_config_free(struct wpa_config *);

/*
 * Debugging function - conditional printf and hex dump.
 * Driver wrappers can use these for debugging purposes.
 */
enum { MSG_MSGDUMP, MSG_DEBUG, MSG_INFO, MSG_WARNING, MSG_ERROR };

void wpa_printf(int, char *, ...);
void wpa_hexdump(int, const char *, const uint8_t *, size_t);

void wpa_event_handler(void *, wpa_event_type);
void wpa_supplicant_rx_eapol(void *, unsigned char *, unsigned char *, size_t);

void wpa_supplicant_scan(void *, void *);
void wpa_supplicant_req_scan(struct wpa_supplicant *, int, int);

void wpa_supplicant_req_auth_timeout(struct wpa_supplicant *, int, int);
void wpa_supplicant_cancel_auth_timeout(struct wpa_supplicant *);
void wpa_supplicant_disassociate(struct wpa_supplicant *, int);

void pmksa_cache_free(struct wpa_supplicant *);
void pmksa_candidate_free(struct wpa_supplicant *);
struct rsn_pmksa_cache *pmksa_cache_get(struct wpa_supplicant *,
    uint8_t *, uint8_t *);

int wpa_parse_wpa_ie(struct wpa_supplicant *, uint8_t *,
	size_t, struct wpa_ie_data *);
int wpa_gen_wpa_ie(struct wpa_supplicant *, uint8_t *);

#ifdef __cplusplus
}
#endif

#endif /* __WPA_IMPL_H */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
 * Sun elects to license this software under the BSD license.
 * See README for more details.
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <syslog.h>
#include <sys/stat.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <door.h>
#include <libscf.h>
#include <libdladm.h>
#include <libdllink.h>
#include <sys/ethernet.h>

#include "wpa_impl.h"
#include "wpa_enc.h"
#include "driver.h"
#include "eloop.h"
#include "l2_packet.h"

extern struct wpa_driver_ops wpa_driver_wifi_ops;
int wpa_debug_level = MSG_ERROR;

/*
 * wpa_printf - conditional printf
 * @level: priority level (MSG_*) of the message
 * @fmt: printf format string, followed by optional arguments
 *
 * This function is used to print conditional debugging and error messages. The
 * output may be directed to stdout, stderr, and/or syslog based on
 * configuration.
 */
void
wpa_printf(int level, char *fmt, ...)
{
	va_list ap;
	char buffer[MAX_LOGBUF];

	if (level < wpa_debug_level)
		return;

	va_start(ap, fmt);

	/* LINTED E_SEC_PRINTF_VAR_FMT */
	(void) vsnprintf(buffer, sizeof (buffer), fmt, ap);

	va_end(ap);

	syslog(LOG_NOTICE | LOG_DAEMON, "%s", buffer);
}

/*
 * wpa_hexdump - conditional hex dump
 * @level: priority level (MSG_*) of the message
 * @title: title of for the message
 * @buf: data buffer to be dumped
 * @len: length of the @buf
 *
 * This function is used to print conditional debugging and error messages. The
 * output may be directed to stdout, stderr, and/or syslog based on
 * configuration. The contents of @buf is printed out has hex dump.
 */
void
wpa_hexdump(int level, const char *title, const uint8_t *buf, size_t len)
{
	size_t i;
	char buffer[MAX_LOGBUF], tmp[4];
	int n;

	if (level < wpa_debug_level)
		return;

	(void) snprintf(buffer, sizeof (buffer), "%s - hexdump(len=%d):",
	    title, len);
	n = strlen(buffer);

	for (i = 0; i < len; i++) {
		(void) sprintf(tmp, " %02x", buf[i]);

		n += strlen(tmp);
		if (n >= MAX_LOGBUF) break;

		(void) strlcat(buffer, tmp, sizeof (buffer));
	}

	syslog(LOG_NOTICE | LOG_DAEMON, "%s", buffer);
}

static const char *
wpa_ssid_txt(char *ssid, size_t ssid_len)
{
	static char ssid_txt[MAX_ESSID_LENGTH + 1];
	char *pos;

	if (ssid_len > MAX_ESSID_LENGTH)
		ssid_len = MAX_ESSID_LENGTH;
	(void) memcpy(ssid_txt, ssid, ssid_len);
	ssid_txt[ssid_len] = '\0';
	for (pos = ssid_txt; *pos != '\0'; pos ++) {
		if ((uint8_t)*pos < 32 || (uint8_t)*pos >= 127)
			*pos = '_';
	}
	return (ssid_txt);
}

/* ARGSUSED */
void
wpa_supplicant_scan(void *eloop_ctx, void *timeout_ctx)
{
	struct wpa_supplicant *wpa_s = eloop_ctx;
	struct wpa_ssid *ssid;

	if (wpa_s->conf == NULL)
		return;

	if (wpa_s->wpa_state == WPA_DISCONNECTED)
		wpa_s->wpa_state = WPA_SCANNING;

	ssid = wpa_s->conf->ssid;
	wpa_printf(MSG_DEBUG, "Starting AP scan (%s SSID)",
	    ssid ? "specific": "broadcast");

	if (ssid) {
		wpa_printf(MSG_DEBUG, "Scan SSID: %s", ssid->ssid);
	}

	if (wpa_s->driver->scan(wpa_s->handle, wpa_s->linkid)) {
		wpa_printf(MSG_WARNING, "Failed to initiate AP scan.");
	}
}

void
wpa_supplicant_req_scan(struct wpa_supplicant *wpa_s, int sec, int usec)
{
	wpa_printf(MSG_DEBUG, "Setting scan request: %d sec %d usec",
	    sec, usec);
	(void) eloop_cancel_timeout(wpa_supplicant_scan, wpa_s, NULL);
	(void) eloop_register_timeout(sec, usec, wpa_supplicant_scan,
	    wpa_s, NULL);
}

void
wpa_supplicant_cancel_scan(struct wpa_supplicant *wpa_s)
{
	wpa_printf(MSG_DEBUG, "Cancelling scan request");
	eloop_cancel_timeout(wpa_supplicant_scan, wpa_s, NULL);
}

/* ARGSUSED */
static void
wpa_supplicant_timeout(void *eloop_ctx, void *timeout_ctx)
{
	struct wpa_supplicant *wpa_s = eloop_ctx;

	wpa_printf(MSG_INFO, "Authentication with " MACSTR " timed out.",
	    MAC2STR(wpa_s->bssid));

	wpa_s->reassociate = 1;
	wpa_supplicant_req_scan(wpa_s, 0, 0);
}

void
wpa_supplicant_req_auth_timeout(struct wpa_supplicant *wpa_s,
				int sec, int usec)
{
	wpa_printf(MSG_DEBUG, "Setting authentication timeout: %d sec "
	    "%d usec", sec, usec);
	eloop_cancel_timeout(wpa_supplicant_timeout, wpa_s, NULL);
	(void) eloop_register_timeout(sec, usec, wpa_supplicant_timeout,
	    wpa_s, NULL);
}

void
wpa_supplicant_cancel_auth_timeout(struct wpa_supplicant *wpa_s)
{
	wpa_printf(MSG_DEBUG, "Cancelling authentication timeout");
	eloop_cancel_timeout(wpa_supplicant_timeout, wpa_s, NULL);
}

static void
wpa_supplicant_cleanup(struct wpa_supplicant *wpa_s)
{
	l2_packet_deinit(wpa_s->l2);
	wpa_s->l2 = NULL;

	if (wpa_s->conf != NULL) {
		wpa_config_free(wpa_s->conf);
		wpa_s->conf = NULL;
	}

	dladm_close(wpa_s->handle);
	free(wpa_s->ap_wpa_ie);
	pmksa_candidate_free(wpa_s);
	pmksa_cache_free(wpa_s);
}

static void
wpa_clear_keys(struct wpa_supplicant *wpa_s, uint8_t *addr)
{
	wpa_s->driver->set_key(wpa_s->handle, wpa_s->linkid, WPA_ALG_NONE,
	    (uint8_t *)"\xff\xff\xff\xff\xff\xff", 0, 0, NULL, 0, NULL, 0);
	wpa_s->driver->set_key(wpa_s->handle, wpa_s->linkid, WPA_ALG_NONE,
	    (uint8_t *)"\xff\xff\xff\xff\xff\xff", 1, 0, NULL, 0, NULL, 0);
	wpa_s->driver->set_key(wpa_s->handle, wpa_s->linkid, WPA_ALG_NONE,
	    (uint8_t *)"\xff\xff\xff\xff\xff\xff", 2, 0, NULL, 0, NULL, 0);
	wpa_s->driver->set_key(wpa_s->handle, wpa_s->linkid, WPA_ALG_NONE,
	    (uint8_t *)"\xff\xff\xff\xff\xff\xff", 3, 0, NULL, 0, NULL, 0);
	if (addr) {
		wpa_s->driver->set_key(wpa_s->handle, wpa_s->linkid,
		    WPA_ALG_NONE, addr, 0, 0, NULL, 0, NULL, 0);
	}
}

static void
wpa_supplicant_mark_disassoc(struct wpa_supplicant *wpa_s)
{
	wpa_s->wpa_state = WPA_DISCONNECTED;
	(void) memset(wpa_s->bssid, 0, IEEE80211_ADDR_LEN);
}

static int
wpa_supplicant_set_suites(struct wpa_supplicant *wpa_s,
    dladm_wlan_ess_t *bss, struct wpa_ssid *ssid,
    uint8_t *wpa_ie, int *wpa_ie_len)
{
	struct wpa_ie_data ie;
	int sel, proto;
	uint8_t *ap_ie;
	size_t ap_ie_len;

	/* RSN or WPA */
	if (bss->we_wpa_ie_len && bss->we_wpa_ie[0] == RSN_INFO_ELEM &&
	    (ssid->proto & WPA_PROTO_RSN)) {
		wpa_printf(MSG_DEBUG, "RSN: using IEEE 802.11i/D9.0");
		proto = WPA_PROTO_RSN;
	} else {
		wpa_printf(MSG_DEBUG, "WPA: using IEEE 802.11i/D3.0");
		proto = WPA_PROTO_WPA;
	}

	ap_ie = bss->we_wpa_ie;
	ap_ie_len = bss->we_wpa_ie_len;

	if (wpa_parse_wpa_ie(wpa_s, ap_ie, ap_ie_len, &ie)) {
		wpa_printf(MSG_WARNING, "WPA: Failed to parse WPA IE for "
		    "the selected BSS.");
		return (-1);
	}

	wpa_s->proto = proto;
	free(wpa_s->ap_wpa_ie);
	wpa_s->ap_wpa_ie = malloc(ap_ie_len);
	(void) memcpy(wpa_s->ap_wpa_ie, ap_ie, ap_ie_len);
	wpa_s->ap_wpa_ie_len = ap_ie_len;

	sel = ie.group_cipher & ssid->group_cipher;
	if (sel & WPA_CIPHER_CCMP) {
		wpa_s->group_cipher = WPA_CIPHER_CCMP;
	} else if (sel & WPA_CIPHER_TKIP) {
		wpa_s->group_cipher = WPA_CIPHER_TKIP;
	} else if (sel & WPA_CIPHER_WEP104) {
		wpa_s->group_cipher = WPA_CIPHER_WEP104;
	} else if (sel & WPA_CIPHER_WEP40) {
		wpa_s->group_cipher = WPA_CIPHER_WEP40;
	} else {
		wpa_printf(MSG_WARNING, "WPA: Failed to select group cipher.");
		return (-1);
	}

	sel = ie.pairwise_cipher & ssid->pairwise_cipher;
	if (sel & WPA_CIPHER_CCMP) {
		wpa_s->pairwise_cipher = WPA_CIPHER_CCMP;
	} else if (sel & WPA_CIPHER_TKIP) {
		wpa_s->pairwise_cipher = WPA_CIPHER_TKIP;
	} else if (sel & WPA_CIPHER_NONE) {
		wpa_s->pairwise_cipher = WPA_CIPHER_NONE;
	} else {
		wpa_printf(MSG_WARNING, "WPA: Failed to select pairwise "
		    "cipher.");
		return (-1);
	}

	sel = ie.key_mgmt & ssid->key_mgmt;
	if (sel & WPA_KEY_MGMT_IEEE8021X) {
		wpa_s->key_mgmt = WPA_KEY_MGMT_IEEE8021X;
	} else if (sel & WPA_KEY_MGMT_PSK) {
		wpa_s->key_mgmt = WPA_KEY_MGMT_PSK;
	} else {
		wpa_printf(MSG_WARNING, "WPA: Failed to select authenticated "
		    "key management type.");
		return (-1);
	}

	*wpa_ie_len = wpa_gen_wpa_ie(wpa_s, wpa_ie);
	if (*wpa_ie_len < 0) {
		wpa_printf(MSG_WARNING, "WPA: Failed to generate WPA IE.");
		return (-1);
	}
	wpa_hexdump(MSG_DEBUG, "WPA: Own WPA IE", wpa_ie, *wpa_ie_len);

	if (ssid->key_mgmt & WPA_KEY_MGMT_PSK)
		(void) memcpy(wpa_s->pmk, ssid->psk, PMK_LEN);
	else if (wpa_s->cur_pmksa)
		(void) memcpy(wpa_s->pmk, wpa_s->cur_pmksa->pmk, PMK_LEN);
	else {
		(void) memset(wpa_s->pmk, 0, PMK_LEN);
	}

	return (0);
}

static void wpa_supplicant_associate(struct wpa_supplicant *wpa_s,
    dladm_wlan_ess_t *bss, struct wpa_ssid *ssid)
{
	uint8_t wpa_ie[IEEE80211_MAX_OPT_IE];
	int wpa_ie_len;

	wpa_s->reassociate = 0;
	wpa_printf(MSG_DEBUG, "Trying to associate with " MACSTR
	    " (SSID='%s' freq=%d MHz)", MAC2STR(bss->we_bssid.wb_bytes),
	    wpa_ssid_txt((char *)ssid->ssid, ssid->ssid_len), bss->we_freq);
	wpa_supplicant_cancel_scan(wpa_s);

	if (bss->we_wpa_ie_len &&
	    (ssid->key_mgmt & (WPA_KEY_MGMT_IEEE8021X | WPA_KEY_MGMT_PSK))) {
		wpa_s->cur_pmksa = pmksa_cache_get(wpa_s,
		    bss->we_bssid.wb_bytes, NULL);
		if (wpa_s->cur_pmksa) {
			wpa_hexdump(MSG_DEBUG, "RSN: PMKID",
			    wpa_s->cur_pmksa->pmkid, PMKID_LEN);
		}
		if (wpa_supplicant_set_suites(wpa_s, bss, ssid,
		    wpa_ie, &wpa_ie_len)) {
			wpa_printf(MSG_WARNING, "WPA: Failed to set WPA key "
			    "management and encryption suites");
			return;
		}
	} else {
		wpa_ie_len = 0;
	}

	wpa_clear_keys(wpa_s, bss->we_bssid.wb_bytes);
	wpa_s->wpa_state = WPA_ASSOCIATING;
	wpa_s->driver->associate(wpa_s->handle, wpa_s->linkid,
	    (const char *)bss->we_bssid.wb_bytes, wpa_ie, wpa_ie_len);

	/* Timeout for IEEE 802.11 authentication and association */
	wpa_supplicant_req_auth_timeout(wpa_s, 15, 0);
}

void
wpa_supplicant_disassociate(struct wpa_supplicant *wpa_s, int reason_code)
{
	uint8_t *addr = NULL;
	wpa_s->wpa_state = WPA_DISCONNECTED;
	if (memcmp(wpa_s->bssid, "\x00\x00\x00\x00\x00\x00",
	    IEEE80211_ADDR_LEN) != 0) {
		wpa_s->driver->disassociate(wpa_s->handle, wpa_s->linkid,
		    reason_code);
		addr = wpa_s->bssid;
	}
	wpa_clear_keys(wpa_s, addr);
}

static dladm_wlan_ess_t *
wpa_supplicant_select_bss(struct wpa_supplicant *wpa_s, struct wpa_ssid *group,
    dladm_wlan_ess_t *results, int num, struct wpa_ssid **selected_ssid)
{
	struct wpa_ssid *ssid;
	dladm_wlan_ess_t *bss, *selected = NULL;
	int i;

	struct wpa_ie_data ie;

	wpa_printf(MSG_DEBUG, "Selecting BSS from scan results (%d)", num);

	bss = NULL;
	ssid = NULL;

	/* try to find matched AP */
	for (i = 0; i < num && !selected; i++) {
		bss = &results[i];
		wpa_printf(MSG_DEBUG, "%d: " MACSTR " ssid='%s' "
		    "wpa_ie_len=%d",
		    i, MAC2STR(bss->we_bssid.wb_bytes),
		    wpa_ssid_txt(bss->we_ssid.we_bytes, bss->we_ssid_len),
		    bss->we_wpa_ie_len);
		if (bss->we_wpa_ie_len == 0) {
			wpa_printf(MSG_DEBUG, "   skip - no WPA/RSN IE");
		}

		ssid = group;
		if (bss->we_ssid_len != ssid->ssid_len ||
		    memcmp(bss->we_ssid.we_bytes, ssid->ssid,
		    bss->we_ssid_len) != 0) {
			wpa_printf(MSG_DEBUG, "   skip - SSID mismatch");
			continue;
		}
		if (!((ssid->proto & (WPA_PROTO_RSN | WPA_PROTO_WPA)) &&
		    wpa_parse_wpa_ie(wpa_s, bss->we_wpa_ie,
		    bss->we_wpa_ie_len, &ie) == 0)) {
			wpa_printf(MSG_DEBUG, "   skip - "
			    "could not parse WPA/RSN IE");
			continue;
		}
		if (!(ie.proto & ssid->proto)) {
			wpa_printf(MSG_DEBUG, "   skip - proto mismatch");
			continue;
		}
		if (!(ie.pairwise_cipher & ssid->pairwise_cipher)) {
			wpa_printf(MSG_DEBUG, "   skip - PTK cipher mismatch");
			continue;
		}
		if (!(ie.group_cipher & ssid->group_cipher)) {
			wpa_printf(MSG_DEBUG, "   skip - GTK cipher mismatch");
			continue;
		}
		if (!(ie.key_mgmt & ssid->key_mgmt)) {
			wpa_printf(MSG_DEBUG, "   skip - key mgmt mismatch");
			continue;
		}

		selected = bss;
		*selected_ssid = ssid;
		wpa_printf(MSG_DEBUG, "   selected");
	}

	return (selected);
}


static void
wpa_supplicant_scan_results(struct wpa_supplicant *wpa_s)
{
	dladm_wlan_ess_t results[MAX_SCANRESULTS];
	int num;
	dladm_wlan_ess_t *selected = NULL;
	struct wpa_ssid *ssid;

	(void) memset(results, 0, sizeof (dladm_wlan_ess_t) * MAX_SCANRESULTS);
	num = wpa_s->driver->get_scan_results(wpa_s->handle, wpa_s->linkid,
	    results, MAX_SCANRESULTS);
	wpa_printf(MSG_DEBUG, "Scan results: %d", num);
	if (num < 0)
		return;
	if (num > MAX_SCANRESULTS) {
		wpa_printf(MSG_INFO, "Not enough room for all APs (%d < %d)",
		    num, MAX_SCANRESULTS);
		num = MAX_SCANRESULTS;
	}

	selected = wpa_supplicant_select_bss(wpa_s,
	    wpa_s->conf->ssid, results, num, &ssid);

	if (selected) {
		if (wpa_s->reassociate ||
		    memcmp(selected->we_bssid.wb_bytes, wpa_s->bssid,
		    IEEE80211_ADDR_LEN) != 0) {
			wpa_supplicant_associate(wpa_s, selected, ssid);
		} else {
			wpa_printf(MSG_DEBUG, "Already associated with the "
			    "selected AP.");
		}
	} else {
		wpa_printf(MSG_DEBUG, "No suitable AP found.");
		wpa_supplicant_req_scan(wpa_s, 5, 0);	/* wait 5 seconds */
	}
}

/*
 * wpa_event_handler - report a driver event for wpa_supplicant
 * @wpa_s: pointer to wpa_supplicant data; this is the @ctx variable registered
 *	with wpa_driver_events_init()
 * @event: event type (defined above)
 *
 * Driver wrapper code should call this function whenever an event is received
 * from the driver.
 */
void
wpa_event_handler(void *cookie, wpa_event_type event)
{
	struct wpa_supplicant *wpa_s = cookie;

	switch (event) {
	case EVENT_ASSOC:
		wpa_printf(MSG_DEBUG, "\nAssociation event\n");
		/* async event */
		if (wpa_s->wpa_state < WPA_ASSOCIATED) {
			wpa_s->wpa_state = WPA_ASSOCIATED;
			if (wpa_s->key_mgmt == WPA_KEY_MGMT_NONE) {
				wpa_supplicant_cancel_auth_timeout(wpa_s);
			} else {
				/* Timeout for receiving first EAPOL packet */
				wpa_supplicant_req_auth_timeout(wpa_s, 10, 0);
			}
		}
		break;
	case EVENT_DISASSOC:
		if (wpa_s->wpa_state >= WPA_ASSOCIATED)
			wpa_supplicant_req_scan(wpa_s, 0, 100000);
		wpa_supplicant_mark_disassoc(wpa_s);
		wpa_printf(MSG_DEBUG, "Disconnect event - remove keys");
		if (wpa_s->key_mgmt != WPA_KEY_MGMT_NONE)
			wpa_clear_keys(wpa_s, wpa_s->bssid);
		break;
	case EVENT_SCAN_RESULTS:
		wpa_supplicant_scan_results(wpa_s);
		/* reset vars */
		(void) memset(wpa_s->rx_replay_counter, 0,
		    WPA_REPLAY_COUNTER_LEN);
		wpa_s->rx_replay_counter_set = 0;
		wpa_s->renew_snonce = 1;
		wpa_s->eapol_received = 0;
		break;
	default:
		wpa_printf(MSG_INFO, "Unknown event %d", event);
		break;
	}
}

/* ARGSUSED */
static void
wpa_supplicant_terminate(int sig, void *eloop_ctx, void *signal_ctx)
{
	wpa_printf(MSG_INFO, "Signal %d received - terminating", sig);
	eloop_terminate();
}

static int
wpa_supplicant_driver_init(const char *link, struct wpa_supplicant *wpa_s)
{
	wpa_s->l2 = l2_packet_init(link, ETHERTYPE_EAPOL,
	    wpa_supplicant_rx_eapol, wpa_s);
	if (wpa_s->l2 == NULL)
		return (-1);

	if (l2_packet_get_own_addr(wpa_s->l2, wpa_s->own_addr)) {
		(void) fprintf(stderr, "Failed to get own L2 address\n");
		return (-1);
	}

	if (wpa_s->driver->set_wpa(wpa_s->handle, wpa_s->linkid, 1) < 0) {
		wpa_printf(MSG_ERROR, "Failed to enable WPA in the driver.");
		return (-1);
	}

	wpa_clear_keys(wpa_s, NULL);
	wpa_supplicant_req_scan(wpa_s, 0, 100000);

	return (0);
}

static int door_id = -1;

/* ARGSUSED */
static void
event_handler(void *cookie, char *argp, size_t asize,
    door_desc_t *dp, uint_t n_desc)
{
	wpa_event_type event;

	/* LINTED E_BAD_PTR_CAST_ALIGN */
	event = ((wl_events_t *)argp)->event;
	wpa_event_handler(cookie, event);

	(void) door_return(NULL, 0, NULL, 0);
}

/*
 * Create the driver to wpad door
 */
int
wpa_supplicant_door_setup(void *cookie, char *doorname)
{
	struct stat stbuf;
	int error = 0;

	wpa_printf(MSG_DEBUG, "wpa_supplicant_door_setup(%s)", doorname);
	/*
	 * Create the door
	 */
	door_id = door_create(event_handler, cookie,
	    DOOR_UNREF | DOOR_REFUSE_DESC | DOOR_NO_CANCEL);

	if (door_id < 0) {
		error = -1;
		goto out;
	}

	if (stat(doorname, &stbuf) < 0) {
		int newfd;
		if ((newfd = creat(doorname, 0666)) < 0) {
			(void) door_revoke(door_id);
			door_id = -1;
			error = -1;

			goto out;
		}
		(void) close(newfd);
	}

	if (fattach(door_id, doorname) < 0) {
		if ((errno != EBUSY) || (fdetach(doorname) < 0) ||
		    (fattach(door_id, doorname) < 0)) {
			(void) door_revoke(door_id);
			door_id = -1;
			error = -1;

			goto out;
		}
	}

out:
	return (error);
}

void
wpa_supplicant_door_destroy(char *doorname)
{
	wpa_printf(MSG_DEBUG, "wpa_supplicant_door_destroy(%s)\n", doorname);

	if (door_id == -1)
		return;

	if (door_revoke(door_id) == -1) {
		wpa_printf(MSG_ERROR, "failed to door_revoke(%d) %s, exiting.",
		    door_id, strerror(errno));
	}

	if (fdetach(doorname) == -1) {
		wpa_printf(MSG_ERROR, "failed to fdetach %s: %s, exiting.",
		    doorname, strerror(errno));
	}

	(void) close(door_id);
}

static int
wpa_config_parse_ssid(struct wpa_ssid *ssid, int line, const char *value)
{
	free(ssid->ssid);

	ssid->ssid = (uint8_t *)strdup(value);
	ssid->ssid_len = strlen(value);

	if (ssid->ssid == NULL) {
		wpa_printf(MSG_ERROR, "Invalid SSID '%s'.", line, value);
		return (-1);
	}
	if (ssid->ssid_len > MAX_ESSID_LENGTH) {
		free(ssid->ssid);
		wpa_printf(MSG_ERROR, "Too long SSID '%s'.", line, value);
		return (-1);
	}
	wpa_printf(MSG_MSGDUMP, "SSID: %s", ssid->ssid);
	return (0);
}

static struct wpa_ssid *
wpa_config_read_network(struct wpa_supplicant *wpa_s)
{
	struct wpa_ssid *ssid;
	char buf[MAX_ESSID_LENGTH + 1];
	dladm_secobj_class_t cl;
	uint8_t psk[MAX_PSK_LENGTH + 1];
	uint_t key_len;

	wpa_printf(MSG_MSGDUMP, "Start of a new network configration");

	ssid = (struct wpa_ssid *)malloc(sizeof (*ssid));
	if (ssid == NULL)
		return (NULL);
	(void) memset(ssid, 0, sizeof (*ssid));

	/*
	 * Set default supported values
	 */
	ssid->proto = WPA_PROTO_WPA | WPA_PROTO_RSN;
	ssid->pairwise_cipher = WPA_CIPHER_CCMP | WPA_CIPHER_TKIP;
	ssid->group_cipher = WPA_CIPHER_CCMP | WPA_CIPHER_TKIP |
	    WPA_CIPHER_WEP104 | WPA_CIPHER_WEP40;
	ssid->key_mgmt = WPA_KEY_MGMT_PSK; /* | WPA_KEY_MGMT_IEEE8021X; */

	(void) memset(buf, 0, MAX_ESSID_LENGTH + 1);
	wpa_s->driver->get_ssid(wpa_s->handle, wpa_s->linkid, (char *)buf);

	(void) wpa_config_parse_ssid(ssid, 0, buf);

	key_len = sizeof (psk);
	(void) dladm_get_secobj(wpa_s->handle, (const char *)wpa_s->kname, &cl,
	    psk, &key_len, DLADM_OPT_ACTIVE);
	psk[key_len] = '\0';
	ssid->passphrase = strdup((const char *)psk);

	if (ssid->passphrase) {
		pbkdf2_sha1(ssid->passphrase, (char *)ssid->ssid,
		    ssid->ssid_len, 4096, ssid->psk, PMK_LEN);
		wpa_hexdump(MSG_MSGDUMP, "PSK (from passphrase)",
		    ssid->psk, PMK_LEN);
		ssid->psk_set = 1;
	}

	if ((ssid->key_mgmt & WPA_KEY_MGMT_PSK) && !ssid->psk_set) {
		wpa_printf(MSG_ERROR, "WPA-PSK accepted for key "
		    "management, but no PSK configured.");
		free(ssid);
		ssid = NULL;
	}

	return (ssid);
}

struct wpa_config *
wpa_config_read(void *arg)
{
	struct wpa_ssid *ssid;
	struct wpa_config *config;
	struct wpa_supplicant *wpa_s = arg;

	config = malloc(sizeof (*config));
	if (config == NULL)
		return (NULL);
	(void) memset(config, 0, sizeof (*config));
	config->eapol_version = 1;	/* fixed value */

	wpa_printf(MSG_DEBUG, "Reading configuration parameters from driver\n");

	ssid = wpa_config_read_network(wpa_s);
	if (ssid == NULL) {
		wpa_config_free(config);
		config = NULL;
	} else {
		config->ssid = ssid;
	}

	return (config);
}

void
wpa_config_free(struct wpa_config *config)
{
	struct wpa_ssid *ssid = config->ssid;

	if (ssid != NULL) {
		free(ssid->ssid);
		free(ssid->passphrase);
		free(ssid);
	}
	free(config);
}

/*
 * make sure wpad is running under SMF context.
 */
static boolean_t
is_smf_context(void)
{
	char *fmri;

	return (((fmri = getenv("SMF_FMRI")) != NULL) &&
	    (strstr(fmri, SERVICE_NAME) != NULL));
}

int
main(int argc, char *argv[])
{
	struct wpa_supplicant wpa_s;
	char *link = NULL;
	char *key = NULL;
	dlpi_handle_t dh = NULL;
	datalink_id_t linkid;
	dladm_phys_attr_t dpa;
	int c;
	int exitcode;
	char door_file[MAXPATHLEN];
	dladm_handle_t handle;

	if (!is_smf_context()) {
		(void) fprintf(stderr,
		    "wpad is an smf(7) managed service and cannot be run from "
		    "the command line; please use dladm(8).\n");
		return (SMF_EXIT_ERR_NOSMF);
	}

	for (;;) {
		c = getopt(argc, argv, "i:k:");
		if (c < 0)
			break;
		switch (c) {
		case 'i':
			link = optarg;
			break;
		case 'k':
			key = optarg;
			break;
		default:
			return (SMF_EXIT_ERR_CONFIG);
		}
	}

	/*
	 * key name is required to retrieve PSK value through libwdladm APIs.
	 * key is saved by dladm command by keyname
	 * see dladm.
	 */
	if ((link == NULL) || (key == NULL)) {
		wpa_printf(MSG_ERROR, "\nLink & key is required.");
		return (-1);
	}

	if ((strlen(key) >= sizeof (wpa_s.kname)))  {
		wpa_printf(MSG_ERROR, "Too long key name '%s'.", key);
		return (-1);
	}

	if (daemon(0, 0))
		return (-1);

	/*
	 * Hold this link open to prevent a link renaming operation.
	 */
	if (dlpi_open(link, &dh, 0) != DLPI_SUCCESS) {
		wpa_printf(MSG_ERROR, "Failed to open link '%s'.", link);
		return (-1);
	}

	/* This handle is stored in wpa_s when that struct is filled. */
	if (dladm_open(&handle) != DLADM_STATUS_OK) {
		wpa_printf(MSG_ERROR, "Failed to open dladm handle");
		dlpi_close(dh);
		return (-1);
	}

	if (dladm_name2info(handle, link, &linkid, NULL, NULL, NULL) !=
	    DLADM_STATUS_OK) {
		wpa_printf(MSG_ERROR, "Invalid link name '%s'.", link);
		dladm_close(handle);
		dlpi_close(dh);
		return (-1);
	}

	/*
	 * Get the device name of the link, which will be used as the door
	 * file name used to communicate with the driver. Note that different
	 * links use different doors.
	 */
	if (dladm_phys_info(handle, linkid, &dpa, DLADM_OPT_ACTIVE) !=
	    DLADM_STATUS_OK) {
		wpa_printf(MSG_ERROR,
		    "Failed to get device name of link '%s'.", link);
		dladm_close(handle);
		dlpi_close(dh);
		return (-1);
	}
	(void) snprintf(door_file, MAXPATHLEN, "%s_%s", WPA_DOOR, dpa.dp_dev);

	(void) memset(&wpa_s, 0, sizeof (wpa_s));
	wpa_s.driver = &wpa_driver_wifi_ops;
	wpa_s.handle = handle;
	wpa_s.linkid = linkid;
	(void) strlcpy(wpa_s.kname, key, sizeof (wpa_s.kname));
	eloop_init(&wpa_s);

	/*
	 * Setup default WPA/WPA2 configuration
	 * get ESSID and PSK value
	 */
	wpa_s.conf = wpa_config_read(&wpa_s);
	if (wpa_s.conf == NULL || wpa_s.conf->ssid == NULL) {
		wpa_printf(MSG_ERROR, "\nNo networks (SSID) configured.\n");
		exitcode = -1;
		goto cleanup;
	}

	exitcode = 0;

	/*
	 * Setup door file to communicate with driver
	 */
	if (wpa_supplicant_door_setup(&wpa_s, door_file) != 0) {
		wpa_printf(MSG_ERROR, "Failed to setup door(%s)", door_file);
		exitcode = -1;
		goto cleanup;
	}

	wpa_s.renew_snonce = 1;
	if (wpa_supplicant_driver_init(link, &wpa_s) < 0) {
		exitcode = -1;
		goto cleanup;
	}

	/*
	 * This link is hold again in wpa_supplicant_driver_init(), so that
	 * we release the first reference.
	 */
	dlpi_close(dh);
	dh = NULL;

	wpa_printf(MSG_DEBUG, "=> eloop_run");

	(void) eloop_register_signal(SIGINT, wpa_supplicant_terminate, NULL);
	(void) eloop_register_signal(SIGTERM, wpa_supplicant_terminate, NULL);
	(void) eloop_register_signal(SIGKILL, wpa_supplicant_terminate, NULL);

	eloop_run();

	wpa_printf(MSG_DEBUG, "<= eloop_run()");
	wpa_supplicant_disassociate(&wpa_s, REASON_DEAUTH_LEAVING);

	if (wpa_s.driver->set_wpa(wpa_s.handle, wpa_s.linkid, 0) < 0) {
		wpa_printf(MSG_ERROR, "Failed to disable WPA in the driver.\n");
	}

cleanup:
	wpa_supplicant_door_destroy(door_file);
	/* The libdladm handle is closed in the following method */
	wpa_supplicant_cleanup(&wpa_s);
	eloop_destroy();

	if (dh != NULL)
		dlpi_close(dh);

	return (exitcode);
}