Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   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
/*
 * hostapd / EAP Full Authenticator state machine (RFC 4137)
 * Copyright (c) 2004-2014, Jouni Malinen <j@w1.fi>
 *
 * This software may be distributed under the terms of the BSD license.
 * See README for more details.
 *
 * This state machine is based on the full authenticator state machine defined
 * in RFC 4137. However, to support backend authentication in RADIUS
 * authentication server functionality, parts of backend authenticator (also
 * from RFC 4137) are mixed in. This functionality is enabled by setting
 * backend_auth configuration variable to TRUE.
 */

#include "includes.h"

#include "common.h"
#include "crypto/sha256.h"
#include "eap_i.h"
#include "state_machine.h"
#include "common/wpa_ctrl.h"

#define STATE_MACHINE_DATA struct eap_sm
#define STATE_MACHINE_DEBUG_PREFIX "EAP"

#define EAP_MAX_AUTH_ROUNDS 50

/* EAP state machines are described in RFC 4137 */

static int eap_sm_calculateTimeout(struct eap_sm *sm, int retransCount,
				   int eapSRTT, int eapRTTVAR,
				   int methodTimeout);
static void eap_sm_parseEapResp(struct eap_sm *sm, const struct wpabuf *resp);
static int eap_sm_getId(const struct wpabuf *data);
static struct wpabuf * eap_sm_buildSuccess(struct eap_sm *sm, u8 id);
static struct wpabuf * eap_sm_buildFailure(struct eap_sm *sm, u8 id);
static int eap_sm_nextId(struct eap_sm *sm, int id);
static void eap_sm_Policy_update(struct eap_sm *sm, const u8 *nak_list,
				 size_t len);
static EapType eap_sm_Policy_getNextMethod(struct eap_sm *sm, int *vendor);
static int eap_sm_Policy_getDecision(struct eap_sm *sm);
static Boolean eap_sm_Policy_doPickUp(struct eap_sm *sm, EapType method);


static int eap_get_erp_send_reauth_start(struct eap_sm *sm)
{
	if (sm->eapol_cb->get_erp_send_reauth_start)
		return sm->eapol_cb->get_erp_send_reauth_start(sm->eapol_ctx);
	return 0;
}


static const char * eap_get_erp_domain(struct eap_sm *sm)
{
	if (sm->eapol_cb->get_erp_domain)
		return sm->eapol_cb->get_erp_domain(sm->eapol_ctx);
	return NULL;
}


#ifdef CONFIG_ERP

static struct eap_server_erp_key * eap_erp_get_key(struct eap_sm *sm,
						   const char *keyname)
{
	if (sm->eapol_cb->erp_get_key)
		return sm->eapol_cb->erp_get_key(sm->eapol_ctx, keyname);
	return NULL;
}


static int eap_erp_add_key(struct eap_sm *sm, struct eap_server_erp_key *erp)
{
	if (sm->eapol_cb->erp_add_key)
		return sm->eapol_cb->erp_add_key(sm->eapol_ctx, erp);
	return -1;
}

#endif /* CONFIG_ERP */


static struct wpabuf * eap_sm_buildInitiateReauthStart(struct eap_sm *sm,
						       u8 id)
{
	const char *domain;
	size_t plen = 1;
	struct wpabuf *msg;
	size_t domain_len = 0;

	domain = eap_get_erp_domain(sm);
	if (domain) {
		domain_len = os_strlen(domain);
		plen += 2 + domain_len;
	}

	msg = eap_msg_alloc(EAP_VENDOR_IETF,
			    (EapType) EAP_ERP_TYPE_REAUTH_START, plen,
			    EAP_CODE_INITIATE, id);
	if (msg == NULL)
		return NULL;
	wpabuf_put_u8(msg, 0); /* Reserved */
	if (domain) {
		/* Domain name TLV */
		wpabuf_put_u8(msg, EAP_ERP_TLV_DOMAIN_NAME);
		wpabuf_put_u8(msg, domain_len);
		wpabuf_put_data(msg, domain, domain_len);
	}

	return msg;
}


static int eap_copy_buf(struct wpabuf **dst, const struct wpabuf *src)
{
	if (src == NULL)
		return -1;

	wpabuf_free(*dst);
	*dst = wpabuf_dup(src);
	return *dst ? 0 : -1;
}


static int eap_copy_data(u8 **dst, size_t *dst_len,
			 const u8 *src, size_t src_len)
{
	if (src == NULL)
		return -1;

	os_free(*dst);
	*dst = os_malloc(src_len);
	if (*dst) {
		os_memcpy(*dst, src, src_len);
		*dst_len = src_len;
		return 0;
	} else {
		*dst_len = 0;
		return -1;
	}
}

#define EAP_COPY(dst, src) \
	eap_copy_data((dst), (dst ## Len), (src), (src ## Len))


/**
 * eap_user_get - Fetch user information from the database
 * @sm: Pointer to EAP state machine allocated with eap_server_sm_init()
 * @identity: Identity (User-Name) of the user
 * @identity_len: Length of identity in bytes
 * @phase2: 0 = EAP phase1 user, 1 = EAP phase2 (tunneled) user
 * Returns: 0 on success, or -1 on failure
 *
 * This function is used to fetch user information for EAP. The user will be
 * selected based on the specified identity. sm->user and
 * sm->user_eap_method_index are updated for the new user when a matching user
 * is found. sm->user can be used to get user information (e.g., password).
 */
int eap_user_get(struct eap_sm *sm, const u8 *identity, size_t identity_len,
		 int phase2)
{
	struct eap_user *user;

	if (sm == NULL || sm->eapol_cb == NULL ||
	    sm->eapol_cb->get_eap_user == NULL)
		return -1;

	eap_user_free(sm->user);
	sm->user = NULL;

	user = os_zalloc(sizeof(*user));
	if (user == NULL)
	    return -1;

	if (sm->eapol_cb->get_eap_user(sm->eapol_ctx, identity,
				       identity_len, phase2, user) != 0) {
		eap_user_free(user);
		return -1;
	}

	sm->user = user;
	sm->user_eap_method_index = 0;

	return 0;
}


void eap_log_msg(struct eap_sm *sm, const char *fmt, ...)
{
	va_list ap;
	char *buf;
	int buflen;

	if (sm == NULL || sm->eapol_cb == NULL || sm->eapol_cb->log_msg == NULL)
		return;

	va_start(ap, fmt);
	buflen = vsnprintf(NULL, 0, fmt, ap) + 1;
	va_end(ap);

	buf = os_malloc(buflen);
	if (buf == NULL)
		return;
	va_start(ap, fmt);
	vsnprintf(buf, buflen, fmt, ap);
	va_end(ap);

	sm->eapol_cb->log_msg(sm->eapol_ctx, buf);

	os_free(buf);
}


SM_STATE(EAP, DISABLED)
{
	SM_ENTRY(EAP, DISABLED);
	sm->num_rounds = 0;
}


SM_STATE(EAP, INITIALIZE)
{
	SM_ENTRY(EAP, INITIALIZE);

	if (sm->eap_if.eapRestart && !sm->eap_server && sm->identity) {
		/*
		 * Need to allow internal Identity method to be used instead
		 * of passthrough at the beginning of reauthentication.
		 */
		eap_server_clear_identity(sm);
	}

	sm->try_initiate_reauth = FALSE;
	sm->currentId = -1;
	sm->eap_if.eapSuccess = FALSE;
	sm->eap_if.eapFail = FALSE;
	sm->eap_if.eapTimeout = FALSE;
	bin_clear_free(sm->eap_if.eapKeyData, sm->eap_if.eapKeyDataLen);
	sm->eap_if.eapKeyData = NULL;
	sm->eap_if.eapKeyDataLen = 0;
	os_free(sm->eap_if.eapSessionId);
	sm->eap_if.eapSessionId = NULL;
	sm->eap_if.eapSessionIdLen = 0;
	sm->eap_if.eapKeyAvailable = FALSE;
	sm->eap_if.eapRestart = FALSE;

	/*
	 * This is not defined in RFC 4137, but method state needs to be
	 * reseted here so that it does not remain in success state when
	 * re-authentication starts.
	 */
	if (sm->m && sm->eap_method_priv) {
		sm->m->reset(sm, sm->eap_method_priv);
		sm->eap_method_priv = NULL;
	}
	sm->m = NULL;
	sm->user_eap_method_index = 0;

	if (sm->backend_auth) {
		sm->currentMethod = EAP_TYPE_NONE;
		/* parse rxResp, respId, respMethod */
		eap_sm_parseEapResp(sm, sm->eap_if.eapRespData);
		if (sm->rxResp) {
			sm->currentId = sm->respId;
		}
	}
	sm->num_rounds = 0;
	sm->method_pending = METHOD_PENDING_NONE;

	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_STARTED
		MACSTR, MAC2STR(sm->peer_addr));
}


SM_STATE(EAP, PICK_UP_METHOD)
{
	SM_ENTRY(EAP, PICK_UP_METHOD);

	if (eap_sm_Policy_doPickUp(sm, sm->respMethod)) {
		sm->currentMethod = sm->respMethod;
		if (sm->m && sm->eap_method_priv) {
			sm->m->reset(sm, sm->eap_method_priv);
			sm->eap_method_priv = NULL;
		}
		sm->m = eap_server_get_eap_method(EAP_VENDOR_IETF,
						  sm->currentMethod);
		if (sm->m && sm->m->initPickUp) {
			sm->eap_method_priv = sm->m->initPickUp(sm);
			if (sm->eap_method_priv == NULL) {
				wpa_printf(MSG_DEBUG, "EAP: Failed to "
					   "initialize EAP method %d",
					   sm->currentMethod);
				sm->m = NULL;
				sm->currentMethod = EAP_TYPE_NONE;
			}
		} else {
			sm->m = NULL;
			sm->currentMethod = EAP_TYPE_NONE;
		}
	}

	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_PROPOSED_METHOD
		"method=%u", sm->currentMethod);
}


SM_STATE(EAP, IDLE)
{
	SM_ENTRY(EAP, IDLE);

	sm->eap_if.retransWhile = eap_sm_calculateTimeout(
		sm, sm->retransCount, sm->eap_if.eapSRTT, sm->eap_if.eapRTTVAR,
		sm->methodTimeout);
}


SM_STATE(EAP, RETRANSMIT)
{
	SM_ENTRY(EAP, RETRANSMIT);

	sm->retransCount++;
	if (sm->retransCount <= sm->MaxRetrans && sm->lastReqData) {
		if (eap_copy_buf(&sm->eap_if.eapReqData, sm->lastReqData) == 0)
			sm->eap_if.eapReq = TRUE;
	}

	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_RETRANSMIT MACSTR,
		MAC2STR(sm->peer_addr));
}


SM_STATE(EAP, RECEIVED)
{
	SM_ENTRY(EAP, RECEIVED);

	/* parse rxResp, respId, respMethod */
	eap_sm_parseEapResp(sm, sm->eap_if.eapRespData);
	sm->num_rounds++;
}


SM_STATE(EAP, DISCARD)
{
	SM_ENTRY(EAP, DISCARD);
	sm->eap_if.eapResp = FALSE;
	sm->eap_if.eapNoReq = TRUE;
}


SM_STATE(EAP, SEND_REQUEST)
{
	SM_ENTRY(EAP, SEND_REQUEST);

	sm->retransCount = 0;
	if (sm->eap_if.eapReqData) {
		if (eap_copy_buf(&sm->lastReqData, sm->eap_if.eapReqData) == 0)
		{
			sm->eap_if.eapResp = FALSE;
			sm->eap_if.eapReq = TRUE;
		} else {
			sm->eap_if.eapResp = FALSE;
			sm->eap_if.eapReq = FALSE;
		}
	} else {
		wpa_printf(MSG_INFO, "EAP: SEND_REQUEST - no eapReqData");
		sm->eap_if.eapResp = FALSE;
		sm->eap_if.eapReq = FALSE;
		sm->eap_if.eapNoReq = TRUE;
	}
}


SM_STATE(EAP, INTEGRITY_CHECK)
{
	SM_ENTRY(EAP, INTEGRITY_CHECK);

	if (!eap_hdr_len_valid(sm->eap_if.eapRespData, 1)) {
		sm->ignore = TRUE;
		return;
	}

	if (sm->m->check) {
		sm->ignore = sm->m->check(sm, sm->eap_method_priv,
					  sm->eap_if.eapRespData);
	}
}


SM_STATE(EAP, METHOD_REQUEST)
{
	SM_ENTRY(EAP, METHOD_REQUEST);

	if (sm->m == NULL) {
		wpa_printf(MSG_DEBUG, "EAP: method not initialized");
		return;
	}

	sm->currentId = eap_sm_nextId(sm, sm->currentId);
	wpa_printf(MSG_DEBUG, "EAP: building EAP-Request: Identifier %d",
		   sm->currentId);
	sm->lastId = sm->currentId;
	wpabuf_free(sm->eap_if.eapReqData);
	sm->eap_if.eapReqData = sm->m->buildReq(sm, sm->eap_method_priv,
						sm->currentId);
	if (sm->m->getTimeout)
		sm->methodTimeout = sm->m->getTimeout(sm, sm->eap_method_priv);
	else
		sm->methodTimeout = 0;
}


static void eap_server_erp_init(struct eap_sm *sm)
{
#ifdef CONFIG_ERP
	u8 *emsk = NULL;
	size_t emsk_len = 0;
	u8 EMSKname[EAP_EMSK_NAME_LEN];
	u8 len[2], ctx[3];
	const char *domain;
	size_t domain_len, nai_buf_len;
	struct eap_server_erp_key *erp = NULL;
	int pos;

	domain = eap_get_erp_domain(sm);
	if (!domain)
		return;

	domain_len = os_strlen(domain);

	nai_buf_len = 2 * EAP_EMSK_NAME_LEN + 1 + domain_len;
	if (nai_buf_len > 253) {
		/*
		 * keyName-NAI has a maximum length of 253 octet to fit in
		 * RADIUS attributes.
		 */
		wpa_printf(MSG_DEBUG,
			   "EAP: Too long realm for ERP keyName-NAI maximum length");
		return;
	}
	nai_buf_len++; /* null termination */
	erp = os_zalloc(sizeof(*erp) + nai_buf_len);
	if (erp == NULL)
		goto fail;
	erp->recv_seq = (u32) -1;

	emsk = sm->m->get_emsk(sm, sm->eap_method_priv, &emsk_len);
	if (!emsk || emsk_len == 0 || emsk_len > ERP_MAX_KEY_LEN) {
		wpa_printf(MSG_DEBUG,
			   "EAP: No suitable EMSK available for ERP");
		goto fail;
	}

	wpa_hexdump_key(MSG_DEBUG, "EAP: EMSK", emsk, emsk_len);

	WPA_PUT_BE16(len, EAP_EMSK_NAME_LEN);
	if (hmac_sha256_kdf(sm->eap_if.eapSessionId, sm->eap_if.eapSessionIdLen,
			    "EMSK", len, sizeof(len),
			    EMSKname, EAP_EMSK_NAME_LEN) < 0) {
		wpa_printf(MSG_DEBUG, "EAP: Could not derive EMSKname");
		goto fail;
	}
	wpa_hexdump(MSG_DEBUG, "EAP: EMSKname", EMSKname, EAP_EMSK_NAME_LEN);

	pos = wpa_snprintf_hex(erp->keyname_nai, nai_buf_len,
			       EMSKname, EAP_EMSK_NAME_LEN);
	erp->keyname_nai[pos] = '@';
	os_memcpy(&erp->keyname_nai[pos + 1], domain, domain_len);

	WPA_PUT_BE16(len, emsk_len);
	if (hmac_sha256_kdf(emsk, emsk_len,
			    "EAP Re-authentication Root Key@ietf.org",
			    len, sizeof(len), erp->rRK, emsk_len) < 0) {
		wpa_printf(MSG_DEBUG, "EAP: Could not derive rRK for ERP");
		goto fail;
	}
	erp->rRK_len = emsk_len;
	wpa_hexdump_key(MSG_DEBUG, "EAP: ERP rRK", erp->rRK, erp->rRK_len);

	ctx[0] = EAP_ERP_CS_HMAC_SHA256_128;
	WPA_PUT_BE16(&ctx[1], erp->rRK_len);
	if (hmac_sha256_kdf(erp->rRK, erp->rRK_len,
			    "Re-authentication Integrity Key@ietf.org",
			    ctx, sizeof(ctx), erp->rIK, erp->rRK_len) < 0) {
		wpa_printf(MSG_DEBUG, "EAP: Could not derive rIK for ERP");
		goto fail;
	}
	erp->rIK_len = erp->rRK_len;
	wpa_hexdump_key(MSG_DEBUG, "EAP: ERP rIK", erp->rIK, erp->rIK_len);

	if (eap_erp_add_key(sm, erp) == 0) {
		wpa_printf(MSG_DEBUG, "EAP: Stored ERP keys %s",
			   erp->keyname_nai);
		erp = NULL;
	}

fail:
	bin_clear_free(emsk, emsk_len);
	bin_clear_free(erp, sizeof(*erp));
#endif /* CONFIG_ERP */
}


SM_STATE(EAP, METHOD_RESPONSE)
{
	SM_ENTRY(EAP, METHOD_RESPONSE);

	if (!eap_hdr_len_valid(sm->eap_if.eapRespData, 1))
		return;

	sm->m->process(sm, sm->eap_method_priv, sm->eap_if.eapRespData);
	if (sm->m->isDone(sm, sm->eap_method_priv)) {
		eap_sm_Policy_update(sm, NULL, 0);
		bin_clear_free(sm->eap_if.eapKeyData, sm->eap_if.eapKeyDataLen);
		if (sm->m->getKey) {
			sm->eap_if.eapKeyData = sm->m->getKey(
				sm, sm->eap_method_priv,
				&sm->eap_if.eapKeyDataLen);
		} else {
			sm->eap_if.eapKeyData = NULL;
			sm->eap_if.eapKeyDataLen = 0;
		}
		os_free(sm->eap_if.eapSessionId);
		sm->eap_if.eapSessionId = NULL;
		if (sm->m->getSessionId) {
			sm->eap_if.eapSessionId = sm->m->getSessionId(
				sm, sm->eap_method_priv,
				&sm->eap_if.eapSessionIdLen);
			wpa_hexdump(MSG_DEBUG, "EAP: Session-Id",
				    sm->eap_if.eapSessionId,
				    sm->eap_if.eapSessionIdLen);
		}
		if (sm->erp && sm->m->get_emsk && sm->eap_if.eapSessionId)
			eap_server_erp_init(sm);
		sm->methodState = METHOD_END;
	} else {
		sm->methodState = METHOD_CONTINUE;
	}
}


SM_STATE(EAP, PROPOSE_METHOD)
{
	int vendor;
	EapType type;

	SM_ENTRY(EAP, PROPOSE_METHOD);

	sm->try_initiate_reauth = FALSE;
try_another_method:
	type = eap_sm_Policy_getNextMethod(sm, &vendor);
	if (vendor == EAP_VENDOR_IETF)
		sm->currentMethod = type;
	else
		sm->currentMethod = EAP_TYPE_EXPANDED;
	if (sm->m && sm->eap_method_priv) {
		sm->m->reset(sm, sm->eap_method_priv);
		sm->eap_method_priv = NULL;
	}
	sm->m = eap_server_get_eap_method(vendor, type);
	if (sm->m) {
		sm->eap_method_priv = sm->m->init(sm);
		if (sm->eap_method_priv == NULL) {
			wpa_printf(MSG_DEBUG, "EAP: Failed to initialize EAP "
				   "method %d", sm->currentMethod);
			sm->m = NULL;
			sm->currentMethod = EAP_TYPE_NONE;
			goto try_another_method;
		}
	}
	if (sm->m == NULL) {
		wpa_printf(MSG_DEBUG, "EAP: Could not find suitable EAP method");
		eap_log_msg(sm, "Could not find suitable EAP method");
		sm->decision = DECISION_FAILURE;
		return;
	}
	if (sm->currentMethod == EAP_TYPE_IDENTITY ||
	    sm->currentMethod == EAP_TYPE_NOTIFICATION)
		sm->methodState = METHOD_CONTINUE;
	else
		sm->methodState = METHOD_PROPOSED;

	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_PROPOSED_METHOD
		"vendor=%u method=%u", vendor, sm->currentMethod);
	eap_log_msg(sm, "Propose EAP method vendor=%u method=%u",
		    vendor, sm->currentMethod);
}


SM_STATE(EAP, NAK)
{
	const struct eap_hdr *nak;
	size_t len = 0;
	const u8 *pos;
	const u8 *nak_list = NULL;

	SM_ENTRY(EAP, NAK);

	if (sm->eap_method_priv) {
		sm->m->reset(sm, sm->eap_method_priv);
		sm->eap_method_priv = NULL;
	}
	sm->m = NULL;

	if (!eap_hdr_len_valid(sm->eap_if.eapRespData, 1))
		return;

	nak = wpabuf_head(sm->eap_if.eapRespData);
	if (nak && wpabuf_len(sm->eap_if.eapRespData) > sizeof(*nak)) {
		len = be_to_host16(nak->length);
		if (len > wpabuf_len(sm->eap_if.eapRespData))
			len = wpabuf_len(sm->eap_if.eapRespData);
		pos = (const u8 *) (nak + 1);
		len -= sizeof(*nak);
		if (*pos == EAP_TYPE_NAK) {
			pos++;
			len--;
			nak_list = pos;
		}
	}
	eap_sm_Policy_update(sm, nak_list, len);
}


SM_STATE(EAP, SELECT_ACTION)
{
	SM_ENTRY(EAP, SELECT_ACTION);

	sm->decision = eap_sm_Policy_getDecision(sm);
}


SM_STATE(EAP, TIMEOUT_FAILURE)
{
	SM_ENTRY(EAP, TIMEOUT_FAILURE);

	sm->eap_if.eapTimeout = TRUE;

	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_TIMEOUT_FAILURE MACSTR,
		MAC2STR(sm->peer_addr));
}


SM_STATE(EAP, FAILURE)
{
	SM_ENTRY(EAP, FAILURE);

	wpabuf_free(sm->eap_if.eapReqData);
	sm->eap_if.eapReqData = eap_sm_buildFailure(sm, sm->currentId);
	wpabuf_free(sm->lastReqData);
	sm->lastReqData = NULL;
	sm->eap_if.eapFail = TRUE;

	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_FAILURE
		MACSTR, MAC2STR(sm->peer_addr));
}


SM_STATE(EAP, SUCCESS)
{
	SM_ENTRY(EAP, SUCCESS);

	wpabuf_free(sm->eap_if.eapReqData);
	sm->eap_if.eapReqData = eap_sm_buildSuccess(sm, sm->currentId);
	wpabuf_free(sm->lastReqData);
	sm->lastReqData = NULL;
	if (sm->eap_if.eapKeyData)
		sm->eap_if.eapKeyAvailable = TRUE;
	sm->eap_if.eapSuccess = TRUE;

	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_SUCCESS
		MACSTR, MAC2STR(sm->peer_addr));
}


SM_STATE(EAP, INITIATE_REAUTH_START)
{
	SM_ENTRY(EAP, INITIATE_REAUTH_START);

	sm->initiate_reauth_start_sent = TRUE;
	sm->try_initiate_reauth = TRUE;
	sm->currentId = eap_sm_nextId(sm, sm->currentId);
	wpa_printf(MSG_DEBUG,
		   "EAP: building EAP-Initiate-Re-auth-Start: Identifier %d",
		   sm->currentId);
	sm->lastId = sm->currentId;
	wpabuf_free(sm->eap_if.eapReqData);
	sm->eap_if.eapReqData = eap_sm_buildInitiateReauthStart(sm,
								sm->currentId);
	wpabuf_free(sm->lastReqData);
	sm->lastReqData = NULL;
}


#ifdef CONFIG_ERP

static void erp_send_finish_reauth(struct eap_sm *sm,
				   struct eap_server_erp_key *erp, u8 id,
				   u8 flags, u16 seq, const char *nai)
{
	size_t plen;
	struct wpabuf *msg;
	u8 hash[SHA256_MAC_LEN];
	size_t hash_len;
	u8 seed[4];

	if (erp) {
		switch (erp->cryptosuite) {
		case EAP_ERP_CS_HMAC_SHA256_256:
			hash_len = 32;
			break;
		case EAP_ERP_CS_HMAC_SHA256_128:
			hash_len = 16;
			break;
		default:
			return;
		}
	} else
		hash_len = 0;

	plen = 1 + 2 + 2 + os_strlen(nai);
	if (hash_len)
		plen += 1 + hash_len;
	msg = eap_msg_alloc(EAP_VENDOR_IETF, (EapType) EAP_ERP_TYPE_REAUTH,
			    plen, EAP_CODE_FINISH, id);
	if (msg == NULL)
		return;
	wpabuf_put_u8(msg, flags);
	wpabuf_put_be16(msg, seq);

	wpabuf_put_u8(msg, EAP_ERP_TLV_KEYNAME_NAI);
	wpabuf_put_u8(msg, os_strlen(nai));
	wpabuf_put_str(msg, nai);

	if (erp) {
		wpabuf_put_u8(msg, erp->cryptosuite);
		if (hmac_sha256(erp->rIK, erp->rIK_len,
				wpabuf_head(msg), wpabuf_len(msg), hash) < 0) {
			wpabuf_free(msg);
			return;
		}
		wpabuf_put_data(msg, hash, hash_len);
	}

	wpa_printf(MSG_DEBUG, "EAP: Send EAP-Finish/Re-auth (%s)",
		   flags & 0x80 ? "failure" : "success");

	sm->lastId = sm->currentId;
	sm->currentId = id;
	wpabuf_free(sm->eap_if.eapReqData);
	sm->eap_if.eapReqData = msg;
	wpabuf_free(sm->lastReqData);
	sm->lastReqData = NULL;

	if ((flags & 0x80) || !erp) {
		sm->eap_if.eapFail = TRUE;
		wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_FAILURE
			MACSTR, MAC2STR(sm->peer_addr));
		return;
	}

	bin_clear_free(sm->eap_if.eapKeyData, sm->eap_if.eapKeyDataLen);
	sm->eap_if.eapKeyDataLen = 0;
	sm->eap_if.eapKeyData = os_malloc(erp->rRK_len);
	if (!sm->eap_if.eapKeyData)
		return;

	WPA_PUT_BE16(seed, seq);
	WPA_PUT_BE16(&seed[2], erp->rRK_len);
	if (hmac_sha256_kdf(erp->rRK, erp->rRK_len,
			    "Re-authentication Master Session Key@ietf.org",
			    seed, sizeof(seed),
			    sm->eap_if.eapKeyData, erp->rRK_len) < 0) {
		wpa_printf(MSG_DEBUG, "EAP: Could not derive rMSK for ERP");
		bin_clear_free(sm->eap_if.eapKeyData, erp->rRK_len);
		sm->eap_if.eapKeyData = NULL;
		return;
	}
	sm->eap_if.eapKeyDataLen = erp->rRK_len;
	sm->eap_if.eapKeyAvailable = TRUE;
	wpa_hexdump_key(MSG_DEBUG, "EAP: ERP rMSK",
			sm->eap_if.eapKeyData, sm->eap_if.eapKeyDataLen);
	sm->eap_if.eapSuccess = TRUE;

	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_SUCCESS
		MACSTR, MAC2STR(sm->peer_addr));
}


SM_STATE(EAP, INITIATE_RECEIVED)
{
	const u8 *pos, *end, *start, *tlvs, *hdr;
	const struct eap_hdr *ehdr;
	size_t len;
	u8 flags;
	u16 seq;
	char nai[254];
	struct eap_server_erp_key *erp;
	int max_len;
	u8 hash[SHA256_MAC_LEN];
	size_t hash_len;
	struct erp_tlvs parse;
	u8 resp_flags = 0x80; /* default to failure; cleared on success */

	SM_ENTRY(EAP, INITIATE_RECEIVED);

	sm->rxInitiate = FALSE;

	pos = eap_hdr_validate(EAP_VENDOR_IETF, (EapType) EAP_ERP_TYPE_REAUTH,
			       sm->eap_if.eapRespData, &len);
	if (pos == NULL) {
		wpa_printf(MSG_INFO, "EAP-Initiate: Invalid frame");
		goto fail;
	}
	hdr = wpabuf_head(sm->eap_if.eapRespData);
	ehdr = wpabuf_head(sm->eap_if.eapRespData);

	wpa_hexdump(MSG_DEBUG, "EAP: EAP-Initiate/Re-Auth", pos, len);
	if (len < 4) {
		wpa_printf(MSG_INFO, "EAP: Too short EAP-Initiate/Re-auth");
		goto fail;
	}
	end = pos + len;

	flags = *pos++;
	seq = WPA_GET_BE16(pos);
	pos += 2;
	wpa_printf(MSG_DEBUG, "EAP: Flags=0x%x SEQ=%u", flags, seq);
	tlvs = pos;

	/*
	 * Parse TVs/TLVs. Since we do not yet know the length of the
	 * Authentication Tag, stop parsing if an unknown TV/TLV is seen and
	 * just try to find the keyName-NAI first so that we can check the
	 * Authentication Tag.
	 */
	if (erp_parse_tlvs(tlvs, end, &parse, 1) < 0)
		goto fail;

	if (!parse.keyname) {
		wpa_printf(MSG_DEBUG,
			   "EAP: No keyName-NAI in EAP-Initiate/Re-auth Packet");
		goto fail;
	}

	wpa_hexdump_ascii(MSG_DEBUG, "EAP: EAP-Initiate/Re-auth - keyName-NAI",
			  parse.keyname, parse.keyname_len);
	if (parse.keyname_len > 253) {
		wpa_printf(MSG_DEBUG,
			   "EAP: Too long keyName-NAI in EAP-Initiate/Re-auth");
		goto fail;
	}
	os_memcpy(nai, parse.keyname, parse.keyname_len);
	nai[parse.keyname_len] = '\0';

	if (!sm->eap_server) {
		/*
		 * In passthrough case, EAP-Initiate/Re-auth replaces
		 * EAP Identity exchange. Use keyName-NAI as the user identity
		 * and forward EAP-Initiate/Re-auth to the backend
		 * authentication server.
		 */
		wpa_printf(MSG_DEBUG,
			   "EAP: Use keyName-NAI as user identity for backend authentication");
		eap_server_clear_identity(sm);
		sm->identity = (u8 *) dup_binstr(parse.keyname,
						 parse.keyname_len);
		if (!sm->identity)
			goto fail;
		sm->identity_len = parse.keyname_len;
		return;
	}

	erp = eap_erp_get_key(sm, nai);
	if (!erp) {
		wpa_printf(MSG_DEBUG, "EAP: No matching ERP key found for %s",
			   nai);
		goto report_error;
	}

	if (erp->recv_seq != (u32) -1 && erp->recv_seq >= seq) {
		wpa_printf(MSG_DEBUG,
			   "EAP: SEQ=%u replayed (already received SEQ=%u)",
			   seq, erp->recv_seq);
		goto fail;
	}

	/* Is there enough room for Cryptosuite and Authentication Tag? */
	start = parse.keyname + parse.keyname_len;
	max_len = end - start;
	if (max_len <
	    1 + (erp->cryptosuite == EAP_ERP_CS_HMAC_SHA256_256 ? 32 : 16)) {
		wpa_printf(MSG_DEBUG,
			   "EAP: Not enough room for Authentication Tag");
		goto fail;
	}

	switch (erp->cryptosuite) {
	case EAP_ERP_CS_HMAC_SHA256_256:
		if (end[-33] != erp->cryptosuite) {
			wpa_printf(MSG_DEBUG,
				   "EAP: Different Cryptosuite used");
			goto fail;
		}
		hash_len = 32;
		break;
	case EAP_ERP_CS_HMAC_SHA256_128:
		if (end[-17] != erp->cryptosuite) {
			wpa_printf(MSG_DEBUG,
				   "EAP: Different Cryptosuite used");
			goto fail;
		}
		hash_len = 16;
		break;
	default:
		hash_len = 0;
		break;
	}

	if (hash_len) {
		if (hmac_sha256(erp->rIK, erp->rIK_len, hdr,
				end - hdr - hash_len, hash) < 0)
			goto fail;
		if (os_memcmp(end - hash_len, hash, hash_len) != 0) {
			wpa_printf(MSG_DEBUG,
				   "EAP: Authentication Tag mismatch");
			goto fail;
		}
	}

	/* Check if any supported CS results in matching tag */
	if (!hash_len && max_len >= 1 + 32 &&
	    end[-33] == EAP_ERP_CS_HMAC_SHA256_256) {
		if (hmac_sha256(erp->rIK, erp->rIK_len, hdr,
				end - hdr - 32, hash) < 0)
			goto fail;
		if (os_memcmp(end - 32, hash, 32) == 0) {
			wpa_printf(MSG_DEBUG,
				   "EAP: Authentication Tag match using HMAC-SHA256-256");
			hash_len = 32;
			erp->cryptosuite = EAP_ERP_CS_HMAC_SHA256_256;
		}
	}

	if (!hash_len && end[-17] == EAP_ERP_CS_HMAC_SHA256_128) {
		if (hmac_sha256(erp->rIK, erp->rIK_len, hdr,
				end - hdr - 16, hash) < 0)
			goto fail;
		if (os_memcmp(end - 16, hash, 16) == 0) {
			wpa_printf(MSG_DEBUG,
				   "EAP: Authentication Tag match using HMAC-SHA256-128");
			hash_len = 16;
			erp->cryptosuite = EAP_ERP_CS_HMAC_SHA256_128;
		}
	}

	if (!hash_len) {
		wpa_printf(MSG_DEBUG,
			   "EAP: No supported cryptosuite matched Authentication Tag");
		goto fail;
	}
	end -= 1 + hash_len;

	/*
	 * Parse TVs/TLVs again now that we know the exact part of the buffer
	 * that contains them.
	 */
	wpa_hexdump(MSG_DEBUG, "EAP: EAP-Initiate/Re-Auth TVs/TLVs",
		    tlvs, end - tlvs);
	if (erp_parse_tlvs(tlvs, end, &parse, 0) < 0)
		goto fail;

	wpa_printf(MSG_DEBUG, "EAP: ERP key %s SEQ updated to %u",
		   erp->keyname_nai, seq);
	erp->recv_seq = seq;
	resp_flags &= ~0x80; /* R=0 - success */

report_error:
	erp_send_finish_reauth(sm, erp, ehdr->identifier, resp_flags, seq, nai);
	return;

fail:
	sm->ignore = TRUE;
}

#endif /* CONFIG_ERP */


SM_STATE(EAP, INITIALIZE_PASSTHROUGH)
{
	SM_ENTRY(EAP, INITIALIZE_PASSTHROUGH);

	wpabuf_free(sm->eap_if.aaaEapRespData);
	sm->eap_if.aaaEapRespData = NULL;
	sm->try_initiate_reauth = FALSE;
}


SM_STATE(EAP, IDLE2)
{
	SM_ENTRY(EAP, IDLE2);

	sm->eap_if.retransWhile = eap_sm_calculateTimeout(
		sm, sm->retransCount, sm->eap_if.eapSRTT, sm->eap_if.eapRTTVAR,
		sm->methodTimeout);
}


SM_STATE(EAP, RETRANSMIT2)
{
	SM_ENTRY(EAP, RETRANSMIT2);

	sm->retransCount++;
	if (sm->retransCount <= sm->MaxRetrans && sm->lastReqData) {
		if (eap_copy_buf(&sm->eap_if.eapReqData, sm->lastReqData) == 0)
			sm->eap_if.eapReq = TRUE;
	}

	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_RETRANSMIT2 MACSTR,
		MAC2STR(sm->peer_addr));
}


SM_STATE(EAP, RECEIVED2)
{
	SM_ENTRY(EAP, RECEIVED2);

	/* parse rxResp, respId, respMethod */
	eap_sm_parseEapResp(sm, sm->eap_if.eapRespData);
}


SM_STATE(EAP, DISCARD2)
{
	SM_ENTRY(EAP, DISCARD2);
	sm->eap_if.eapResp = FALSE;
	sm->eap_if.eapNoReq = TRUE;
}


SM_STATE(EAP, SEND_REQUEST2)
{
	SM_ENTRY(EAP, SEND_REQUEST2);

	sm->retransCount = 0;
	if (sm->eap_if.eapReqData) {
		if (eap_copy_buf(&sm->lastReqData, sm->eap_if.eapReqData) == 0)
		{
			sm->eap_if.eapResp = FALSE;
			sm->eap_if.eapReq = TRUE;
		} else {
			sm->eap_if.eapResp = FALSE;
			sm->eap_if.eapReq = FALSE;
		}
	} else {
		wpa_printf(MSG_INFO, "EAP: SEND_REQUEST2 - no eapReqData");
		sm->eap_if.eapResp = FALSE;
		sm->eap_if.eapReq = FALSE;
		sm->eap_if.eapNoReq = TRUE;
	}
}


SM_STATE(EAP, AAA_REQUEST)
{
	SM_ENTRY(EAP, AAA_REQUEST);

	if (sm->eap_if.eapRespData == NULL) {
		wpa_printf(MSG_INFO, "EAP: AAA_REQUEST - no eapRespData");
		return;
	}

	/*
	 * if (respMethod == IDENTITY)
	 *	aaaIdentity = eapRespData
	 * This is already taken care of by the EAP-Identity method which
	 * stores the identity into sm->identity.
	 */

	eap_copy_buf(&sm->eap_if.aaaEapRespData, sm->eap_if.eapRespData);
}


SM_STATE(EAP, AAA_RESPONSE)
{
	SM_ENTRY(EAP, AAA_RESPONSE);

	eap_copy_buf(&sm->eap_if.eapReqData, sm->eap_if.aaaEapReqData);
	sm->currentId = eap_sm_getId(sm->eap_if.eapReqData);
	sm->methodTimeout = sm->eap_if.aaaMethodTimeout;
}


SM_STATE(EAP, AAA_IDLE)
{
	SM_ENTRY(EAP, AAA_IDLE);

	sm->eap_if.aaaFail = FALSE;
	sm->eap_if.aaaSuccess = FALSE;
	sm->eap_if.aaaEapReq = FALSE;
	sm->eap_if.aaaEapNoReq = FALSE;
	sm->eap_if.aaaEapResp = TRUE;
}


SM_STATE(EAP, TIMEOUT_FAILURE2)
{
	SM_ENTRY(EAP, TIMEOUT_FAILURE2);

	sm->eap_if.eapTimeout = TRUE;

	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_TIMEOUT_FAILURE2 MACSTR,
		MAC2STR(sm->peer_addr));
}


SM_STATE(EAP, FAILURE2)
{
	SM_ENTRY(EAP, FAILURE2);

	eap_copy_buf(&sm->eap_if.eapReqData, sm->eap_if.aaaEapReqData);
	sm->eap_if.eapFail = TRUE;

	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_FAILURE2 MACSTR,
		MAC2STR(sm->peer_addr));
}


SM_STATE(EAP, SUCCESS2)
{
	SM_ENTRY(EAP, SUCCESS2);

	eap_copy_buf(&sm->eap_if.eapReqData, sm->eap_if.aaaEapReqData);

	sm->eap_if.eapKeyAvailable = sm->eap_if.aaaEapKeyAvailable;
	if (sm->eap_if.aaaEapKeyAvailable) {
		EAP_COPY(&sm->eap_if.eapKeyData, sm->eap_if.aaaEapKeyData);
	} else {
		bin_clear_free(sm->eap_if.eapKeyData, sm->eap_if.eapKeyDataLen);
		sm->eap_if.eapKeyData = NULL;
		sm->eap_if.eapKeyDataLen = 0;
	}

	sm->eap_if.eapSuccess = TRUE;

	/*
	 * Start reauthentication with identity request even though we know the
	 * previously used identity. This is needed to get reauthentication
	 * started properly.
	 */
	sm->start_reauth = TRUE;

	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_SUCCESS2 MACSTR,
		MAC2STR(sm->peer_addr));
}


SM_STEP(EAP)
{
	if (sm->eap_if.eapRestart && sm->eap_if.portEnabled)
		SM_ENTER_GLOBAL(EAP, INITIALIZE);
	else if (!sm->eap_if.portEnabled)
		SM_ENTER_GLOBAL(EAP, DISABLED);
	else if (sm->num_rounds > EAP_MAX_AUTH_ROUNDS) {
		if (sm->num_rounds == EAP_MAX_AUTH_ROUNDS + 1) {
			wpa_printf(MSG_DEBUG, "EAP: more than %d "
				   "authentication rounds - abort",
				   EAP_MAX_AUTH_ROUNDS);
			sm->num_rounds++;
			SM_ENTER_GLOBAL(EAP, FAILURE);
		}
	} else switch (sm->EAP_state) {
	case EAP_INITIALIZE:
		if (sm->backend_auth) {
			if (!sm->rxResp)
				SM_ENTER(EAP, SELECT_ACTION);
			else if (sm->rxResp &&
				 (sm->respMethod == EAP_TYPE_NAK ||
				  (sm->respMethod == EAP_TYPE_EXPANDED &&
				   sm->respVendor == EAP_VENDOR_IETF &&
				   sm->respVendorMethod == EAP_TYPE_NAK)))
				SM_ENTER(EAP, NAK);
			else
				SM_ENTER(EAP, PICK_UP_METHOD);
		} else {
			SM_ENTER(EAP, SELECT_ACTION);
		}
		break;
	case EAP_PICK_UP_METHOD:
		if (sm->currentMethod == EAP_TYPE_NONE) {
			SM_ENTER(EAP, SELECT_ACTION);
		} else {
			SM_ENTER(EAP, METHOD_RESPONSE);
		}
		break;
	case EAP_DISABLED:
		if (sm->eap_if.portEnabled)
			SM_ENTER(EAP, INITIALIZE);
		break;
	case EAP_IDLE:
		if (sm->eap_if.retransWhile == 0) {
			if (sm->try_initiate_reauth) {
				sm->try_initiate_reauth = FALSE;
				SM_ENTER(EAP, SELECT_ACTION);
			} else {
				SM_ENTER(EAP, RETRANSMIT);
			}
		} else if (sm->eap_if.eapResp)
			SM_ENTER(EAP, RECEIVED);
		break;
	case EAP_RETRANSMIT:
		if (sm->retransCount > sm->MaxRetrans)
			SM_ENTER(EAP, TIMEOUT_FAILURE);
		else
			SM_ENTER(EAP, IDLE);
		break;
	case EAP_RECEIVED:
		if (sm->rxResp && (sm->respId == sm->currentId) &&
		    (sm->respMethod == EAP_TYPE_NAK ||
		     (sm->respMethod == EAP_TYPE_EXPANDED &&
		      sm->respVendor == EAP_VENDOR_IETF &&
		      sm->respVendorMethod == EAP_TYPE_NAK))
		    && (sm->methodState == METHOD_PROPOSED))
			SM_ENTER(EAP, NAK);
		else if (sm->rxResp && (sm->respId == sm->currentId) &&
			 ((sm->respMethod == sm->currentMethod) ||
			  (sm->respMethod == EAP_TYPE_EXPANDED &&
			   sm->respVendor == EAP_VENDOR_IETF &&
			   sm->respVendorMethod == sm->currentMethod)))
			SM_ENTER(EAP, INTEGRITY_CHECK);
#ifdef CONFIG_ERP
		else if (sm->rxInitiate)
			SM_ENTER(EAP, INITIATE_RECEIVED);
#endif /* CONFIG_ERP */
		else {
			wpa_printf(MSG_DEBUG, "EAP: RECEIVED->DISCARD: "
				   "rxResp=%d respId=%d currentId=%d "
				   "respMethod=%d currentMethod=%d",
				   sm->rxResp, sm->respId, sm->currentId,
				   sm->respMethod, sm->currentMethod);
			eap_log_msg(sm, "Discard received EAP message");
			SM_ENTER(EAP, DISCARD);
		}
		break;
	case EAP_DISCARD:
		SM_ENTER(EAP, IDLE);
		break;
	case EAP_SEND_REQUEST:
		SM_ENTER(EAP, IDLE);
		break;
	case EAP_INTEGRITY_CHECK:
		if (sm->ignore)
			SM_ENTER(EAP, DISCARD);
		else
			SM_ENTER(EAP, METHOD_RESPONSE);
		break;
	case EAP_METHOD_REQUEST:
		if (sm->m == NULL) {
			/*
			 * This transition is not mentioned in RFC 4137, but it
			 * is needed to handle cleanly a case where EAP method
			 * initialization fails.
			 */
			SM_ENTER(EAP, FAILURE);
			break;
		}
		SM_ENTER(EAP, SEND_REQUEST);
		if (sm->eap_if.eapNoReq && !sm->eap_if.eapReq) {
			/*
			 * This transition is not mentioned in RFC 4137, but it
			 * is needed to handle cleanly a case where EAP method
			 * buildReq fails.
			 */
			wpa_printf(MSG_DEBUG,
				   "EAP: Method did not return a request");
			SM_ENTER(EAP, FAILURE);
			break;
		}
		break;
	case EAP_METHOD_RESPONSE:
		/*
		 * Note: Mechanism to allow EAP methods to wait while going
		 * through pending processing is an extension to RFC 4137
		 * which only defines the transits to SELECT_ACTION and
		 * METHOD_REQUEST from this METHOD_RESPONSE state.
		 */
		if (sm->methodState == METHOD_END)
			SM_ENTER(EAP, SELECT_ACTION);
		else if (sm->method_pending == METHOD_PENDING_WAIT) {
			wpa_printf(MSG_DEBUG, "EAP: Method has pending "
				   "processing - wait before proceeding to "
				   "METHOD_REQUEST state");
		} else if (sm->method_pending == METHOD_PENDING_CONT) {
			wpa_printf(MSG_DEBUG, "EAP: Method has completed "
				   "pending processing - reprocess pending "
				   "EAP message");
			sm->method_pending = METHOD_PENDING_NONE;
			SM_ENTER(EAP, METHOD_RESPONSE);
		} else
			SM_ENTER(EAP, METHOD_REQUEST);
		break;
	case EAP_PROPOSE_METHOD:
		/*
		 * Note: Mechanism to allow EAP methods to wait while going
		 * through pending processing is an extension to RFC 4137
		 * which only defines the transit to METHOD_REQUEST from this
		 * PROPOSE_METHOD state.
		 */
		if (sm->method_pending == METHOD_PENDING_WAIT) {
			wpa_printf(MSG_DEBUG, "EAP: Method has pending "
				   "processing - wait before proceeding to "
				   "METHOD_REQUEST state");
			if (sm->user_eap_method_index > 0)
				sm->user_eap_method_index--;
		} else if (sm->method_pending == METHOD_PENDING_CONT) {
			wpa_printf(MSG_DEBUG, "EAP: Method has completed "
				   "pending processing - reprocess pending "
				   "EAP message");
			sm->method_pending = METHOD_PENDING_NONE;
			SM_ENTER(EAP, PROPOSE_METHOD);
		} else
			SM_ENTER(EAP, METHOD_REQUEST);
		break;
	case EAP_NAK:
		SM_ENTER(EAP, SELECT_ACTION);
		break;
	case EAP_SELECT_ACTION:
		if (sm->decision == DECISION_FAILURE)
			SM_ENTER(EAP, FAILURE);
		else if (sm->decision == DECISION_SUCCESS)
			SM_ENTER(EAP, SUCCESS);
		else if (sm->decision == DECISION_PASSTHROUGH)
			SM_ENTER(EAP, INITIALIZE_PASSTHROUGH);
		else if (sm->decision == DECISION_INITIATE_REAUTH_START)
			SM_ENTER(EAP, INITIATE_REAUTH_START);
#ifdef CONFIG_ERP
		else if (sm->eap_server && sm->erp && sm->rxInitiate)
			SM_ENTER(EAP, INITIATE_RECEIVED);
#endif /* CONFIG_ERP */
		else
			SM_ENTER(EAP, PROPOSE_METHOD);
		break;
	case EAP_INITIATE_REAUTH_START:
		SM_ENTER(EAP, SEND_REQUEST);
		break;
	case EAP_INITIATE_RECEIVED:
		if (!sm->eap_server)
			SM_ENTER(EAP, SELECT_ACTION);
		break;
	case EAP_TIMEOUT_FAILURE:
		break;
	case EAP_FAILURE:
		break;
	case EAP_SUCCESS:
		break;

	case EAP_INITIALIZE_PASSTHROUGH:
		if (sm->currentId == -1)
			SM_ENTER(EAP, AAA_IDLE);
		else
			SM_ENTER(EAP, AAA_REQUEST);
		break;
	case EAP_IDLE2:
		if (sm->eap_if.eapResp)
			SM_ENTER(EAP, RECEIVED2);
		else if (sm->eap_if.retransWhile == 0)
			SM_ENTER(EAP, RETRANSMIT2);
		break;
	case EAP_RETRANSMIT2:
		if (sm->retransCount > sm->MaxRetrans)
			SM_ENTER(EAP, TIMEOUT_FAILURE2);
		else
			SM_ENTER(EAP, IDLE2);
		break;
	case EAP_RECEIVED2:
		if (sm->rxResp && (sm->respId == sm->currentId))
			SM_ENTER(EAP, AAA_REQUEST);
		else
			SM_ENTER(EAP, DISCARD2);
		break;
	case EAP_DISCARD2:
		SM_ENTER(EAP, IDLE2);
		break;
	case EAP_SEND_REQUEST2:
		SM_ENTER(EAP, IDLE2);
		break;
	case EAP_AAA_REQUEST:
		SM_ENTER(EAP, AAA_IDLE);
		break;
	case EAP_AAA_RESPONSE:
		SM_ENTER(EAP, SEND_REQUEST2);
		break;
	case EAP_AAA_IDLE:
		if (sm->eap_if.aaaFail)
			SM_ENTER(EAP, FAILURE2);
		else if (sm->eap_if.aaaSuccess)
			SM_ENTER(EAP, SUCCESS2);
		else if (sm->eap_if.aaaEapReq)
			SM_ENTER(EAP, AAA_RESPONSE);
		else if (sm->eap_if.aaaTimeout)
			SM_ENTER(EAP, TIMEOUT_FAILURE2);
		break;
	case EAP_TIMEOUT_FAILURE2:
		break;
	case EAP_FAILURE2:
		break;
	case EAP_SUCCESS2:
		break;
	}
}


static int eap_sm_calculateTimeout(struct eap_sm *sm, int retransCount,
				   int eapSRTT, int eapRTTVAR,
				   int methodTimeout)
{
	int rto, i;

	if (sm->try_initiate_reauth) {
		wpa_printf(MSG_DEBUG,
			   "EAP: retransmit timeout 1 second for EAP-Initiate-Re-auth-Start");
		return 1;
	}

	if (methodTimeout) {
		/*
		 * EAP method (either internal or through AAA server, provided
		 * timeout hint. Use that as-is as a timeout for retransmitting
		 * the EAP request if no response is received.
		 */
		wpa_printf(MSG_DEBUG, "EAP: retransmit timeout %d seconds "
			   "(from EAP method hint)", methodTimeout);
		return methodTimeout;
	}

	/*
	 * RFC 3748 recommends algorithms described in RFC 2988 for estimation
	 * of the retransmission timeout. This should be implemented once
	 * round-trip time measurements are available. For nowm a simple
	 * backoff mechanism is used instead if there are no EAP method
	 * specific hints.
	 *
	 * SRTT = smoothed round-trip time
	 * RTTVAR = round-trip time variation
	 * RTO = retransmission timeout
	 */

	/*
	 * RFC 2988, 2.1: before RTT measurement, set RTO to 3 seconds for
	 * initial retransmission and then double the RTO to provide back off
	 * per 5.5. Limit the maximum RTO to 20 seconds per RFC 3748, 4.3
	 * modified RTOmax.
	 */
	rto = 3;
	for (i = 0; i < retransCount; i++) {
		rto *= 2;
		if (rto >= 20) {
			rto = 20;
			break;
		}
	}

	wpa_printf(MSG_DEBUG, "EAP: retransmit timeout %d seconds "
		   "(from dynamic back off; retransCount=%d)",
		   rto, retransCount);

	return rto;
}


static void eap_sm_parseEapResp(struct eap_sm *sm, const struct wpabuf *resp)
{
	const struct eap_hdr *hdr;
	size_t plen;

	/* parse rxResp, respId, respMethod */
	sm->rxResp = FALSE;
	sm->rxInitiate = FALSE;
	sm->respId = -1;
	sm->respMethod = EAP_TYPE_NONE;
	sm->respVendor = EAP_VENDOR_IETF;
	sm->respVendorMethod = EAP_TYPE_NONE;

	if (resp == NULL || wpabuf_len(resp) < sizeof(*hdr)) {
		wpa_printf(MSG_DEBUG, "EAP: parseEapResp: invalid resp=%p "
			   "len=%lu", resp,
			   resp ? (unsigned long) wpabuf_len(resp) : 0);
		return;
	}

	hdr = wpabuf_head(resp);
	plen = be_to_host16(hdr->length);
	if (plen > wpabuf_len(resp)) {
		wpa_printf(MSG_DEBUG, "EAP: Ignored truncated EAP-Packet "
			   "(len=%lu plen=%lu)",
			   (unsigned long) wpabuf_len(resp),
			   (unsigned long) plen);
		return;
	}

	sm->respId = hdr->identifier;

	if (hdr->code == EAP_CODE_RESPONSE)
		sm->rxResp = TRUE;
	else if (hdr->code == EAP_CODE_INITIATE)
		sm->rxInitiate = TRUE;

	if (plen > sizeof(*hdr)) {
		u8 *pos = (u8 *) (hdr + 1);
		sm->respMethod = *pos++;
		if (sm->respMethod == EAP_TYPE_EXPANDED) {
			if (plen < sizeof(*hdr) + 8) {
				wpa_printf(MSG_DEBUG, "EAP: Ignored truncated "
					   "expanded EAP-Packet (plen=%lu)",
					   (unsigned long) plen);
				return;
			}
			sm->respVendor = WPA_GET_BE24(pos);
			pos += 3;
			sm->respVendorMethod = WPA_GET_BE32(pos);
		}
	}

	wpa_printf(MSG_DEBUG,
		   "EAP: parseEapResp: rxResp=%d rxInitiate=%d respId=%d respMethod=%u respVendor=%u respVendorMethod=%u",
		   sm->rxResp, sm->rxInitiate, sm->respId, sm->respMethod,
		   sm->respVendor, sm->respVendorMethod);
}


static int eap_sm_getId(const struct wpabuf *data)
{
	const struct eap_hdr *hdr;

	if (data == NULL || wpabuf_len(data) < sizeof(*hdr))
		return -1;

	hdr = wpabuf_head(data);
	wpa_printf(MSG_DEBUG, "EAP: getId: id=%d", hdr->identifier);
	return hdr->identifier;
}


static struct wpabuf * eap_sm_buildSuccess(struct eap_sm *sm, u8 id)
{
	struct wpabuf *msg;
	struct eap_hdr *resp;
	wpa_printf(MSG_DEBUG, "EAP: Building EAP-Success (id=%d)", id);

	msg = wpabuf_alloc(sizeof(*resp));
	if (msg == NULL)
		return NULL;
	resp = wpabuf_put(msg, sizeof(*resp));
	resp->code = EAP_CODE_SUCCESS;
	resp->identifier = id;
	resp->length = host_to_be16(sizeof(*resp));

	return msg;
}


static struct wpabuf * eap_sm_buildFailure(struct eap_sm *sm, u8 id)
{
	struct wpabuf *msg;
	struct eap_hdr *resp;
	wpa_printf(MSG_DEBUG, "EAP: Building EAP-Failure (id=%d)", id);

	msg = wpabuf_alloc(sizeof(*resp));
	if (msg == NULL)
		return NULL;
	resp = wpabuf_put(msg, sizeof(*resp));
	resp->code = EAP_CODE_FAILURE;
	resp->identifier = id;
	resp->length = host_to_be16(sizeof(*resp));

	return msg;
}


static int eap_sm_nextId(struct eap_sm *sm, int id)
{
	if (id < 0) {
		/* RFC 3748 Ch 4.1: recommended to initialize Identifier with a
		 * random number */
		id = rand() & 0xff;
		if (id != sm->lastId)
			return id;
	}
	return (id + 1) & 0xff;
}


/**
 * eap_sm_process_nak - Process EAP-Response/Nak
 * @sm: Pointer to EAP state machine allocated with eap_server_sm_init()
 * @nak_list: Nak list (allowed methods) from the supplicant
 * @len: Length of nak_list in bytes
 *
 * This function is called when EAP-Response/Nak is received from the
 * supplicant. This can happen for both phase 1 and phase 2 authentications.
 */
void eap_sm_process_nak(struct eap_sm *sm, const u8 *nak_list, size_t len)
{
	int i;
	size_t j;

	if (sm->user == NULL)
		return;

	wpa_printf(MSG_MSGDUMP, "EAP: processing NAK (current EAP method "
		   "index %d)", sm->user_eap_method_index);

	wpa_hexdump(MSG_MSGDUMP, "EAP: configured methods",
		    (u8 *) sm->user->methods,
		    EAP_MAX_METHODS * sizeof(sm->user->methods[0]));
	wpa_hexdump(MSG_MSGDUMP, "EAP: list of methods supported by the peer",
		    nak_list, len);

	i = sm->user_eap_method_index;
	while (i < EAP_MAX_METHODS &&
	       (sm->user->methods[i].vendor != EAP_VENDOR_IETF ||
		sm->user->methods[i].method != EAP_TYPE_NONE)) {
		if (sm->user->methods[i].vendor != EAP_VENDOR_IETF)
			goto not_found;
		for (j = 0; j < len; j++) {
			if (nak_list[j] == sm->user->methods[i].method) {
				break;
			}
		}

		if (j < len) {
			/* found */
			i++;
			continue;
		}

	not_found:
		/* not found - remove from the list */
		if (i + 1 < EAP_MAX_METHODS) {
			os_memmove(&sm->user->methods[i],
				   &sm->user->methods[i + 1],
				   (EAP_MAX_METHODS - i - 1) *
				   sizeof(sm->user->methods[0]));
		}
		sm->user->methods[EAP_MAX_METHODS - 1].vendor =
			EAP_VENDOR_IETF;
		sm->user->methods[EAP_MAX_METHODS - 1].method = EAP_TYPE_NONE;
	}

	wpa_hexdump(MSG_MSGDUMP, "EAP: new list of configured methods",
		    (u8 *) sm->user->methods, EAP_MAX_METHODS *
		    sizeof(sm->user->methods[0]));
}


static void eap_sm_Policy_update(struct eap_sm *sm, const u8 *nak_list,
				 size_t len)
{
	if (nak_list == NULL || sm == NULL || sm->user == NULL)
		return;

	if (sm->user->phase2) {
		wpa_printf(MSG_DEBUG, "EAP: EAP-Nak received after Phase2 user"
			   " info was selected - reject");
		sm->decision = DECISION_FAILURE;
		return;
	}

	eap_sm_process_nak(sm, nak_list, len);
}


static EapType eap_sm_Policy_getNextMethod(struct eap_sm *sm, int *vendor)
{
	EapType next;
	int idx = sm->user_eap_method_index;

	/* In theory, there should be no problems with starting
	 * re-authentication with something else than EAP-Request/Identity and
	 * this does indeed work with wpa_supplicant. However, at least Funk
	 * Supplicant seemed to ignore re-auth if it skipped
	 * EAP-Request/Identity.
	 * Re-auth sets currentId == -1, so that can be used here to select
	 * whether Identity needs to be requested again. */
	if (sm->identity == NULL || sm->currentId == -1) {
		*vendor = EAP_VENDOR_IETF;
		next = EAP_TYPE_IDENTITY;
		sm->update_user = TRUE;
	} else if (sm->user && idx < EAP_MAX_METHODS &&
		   (sm->user->methods[idx].vendor != EAP_VENDOR_IETF ||
		    sm->user->methods[idx].method != EAP_TYPE_NONE)) {
		*vendor = sm->user->methods[idx].vendor;
		next = sm->user->methods[idx].method;
		sm->user_eap_method_index++;
	} else {
		*vendor = EAP_VENDOR_IETF;
		next = EAP_TYPE_NONE;
	}
	wpa_printf(MSG_DEBUG, "EAP: getNextMethod: vendor %d type %d",
		   *vendor, next);
	return next;
}


static int eap_sm_Policy_getDecision(struct eap_sm *sm)
{
	if (!sm->eap_server && sm->identity && !sm->start_reauth) {
		wpa_printf(MSG_DEBUG, "EAP: getDecision: -> PASSTHROUGH");
		return DECISION_PASSTHROUGH;
	}

	if (sm->m && sm->currentMethod != EAP_TYPE_IDENTITY &&
	    sm->m->isSuccess(sm, sm->eap_method_priv)) {
		wpa_printf(MSG_DEBUG, "EAP: getDecision: method succeeded -> "
			   "SUCCESS");
		sm->update_user = TRUE;
		return DECISION_SUCCESS;
	}

	if (sm->m && sm->m->isDone(sm, sm->eap_method_priv) &&
	    !sm->m->isSuccess(sm, sm->eap_method_priv)) {
		wpa_printf(MSG_DEBUG, "EAP: getDecision: method failed -> "
			   "FAILURE");
		sm->update_user = TRUE;
		return DECISION_FAILURE;
	}

	if ((sm->user == NULL || sm->update_user) && sm->identity &&
	    !sm->start_reauth) {
		/*
		 * Allow Identity method to be started once to allow identity
		 * selection hint to be sent from the authentication server,
		 * but prevent a loop of Identity requests by only allowing
		 * this to happen once.
		 */
		int id_req = 0;
		if (sm->user && sm->currentMethod == EAP_TYPE_IDENTITY &&
		    sm->user->methods[0].vendor == EAP_VENDOR_IETF &&
		    sm->user->methods[0].method == EAP_TYPE_IDENTITY)
			id_req = 1;
		if (eap_user_get(sm, sm->identity, sm->identity_len, 0) != 0) {
			wpa_printf(MSG_DEBUG, "EAP: getDecision: user not "
				   "found from database -> FAILURE");
			return DECISION_FAILURE;
		}
		if (id_req && sm->user &&
		    sm->user->methods[0].vendor == EAP_VENDOR_IETF &&
		    sm->user->methods[0].method == EAP_TYPE_IDENTITY) {
			wpa_printf(MSG_DEBUG, "EAP: getDecision: stop "
				   "identity request loop -> FAILURE");
			sm->update_user = TRUE;
			return DECISION_FAILURE;
		}
		sm->update_user = FALSE;
	}
	sm->start_reauth = FALSE;

	if (sm->user && sm->user_eap_method_index < EAP_MAX_METHODS &&
	    (sm->user->methods[sm->user_eap_method_index].vendor !=
	     EAP_VENDOR_IETF ||
	     sm->user->methods[sm->user_eap_method_index].method !=
	     EAP_TYPE_NONE)) {
		wpa_printf(MSG_DEBUG, "EAP: getDecision: another method "
			   "available -> CONTINUE");
		return DECISION_CONTINUE;
	}

	if (!sm->identity && eap_get_erp_send_reauth_start(sm) &&
	    !sm->initiate_reauth_start_sent) {
		wpa_printf(MSG_DEBUG,
			   "EAP: getDecision: send EAP-Initiate/Re-auth-Start");
		return DECISION_INITIATE_REAUTH_START;
	}

	if (sm->identity == NULL || sm->currentId == -1) {
		wpa_printf(MSG_DEBUG, "EAP: getDecision: no identity known "
			   "yet -> CONTINUE");
		return DECISION_CONTINUE;
	}

	wpa_printf(MSG_DEBUG, "EAP: getDecision: no more methods available -> "
		   "FAILURE");
	return DECISION_FAILURE;
}


static Boolean eap_sm_Policy_doPickUp(struct eap_sm *sm, EapType method)
{
	return method == EAP_TYPE_IDENTITY ? TRUE : FALSE;
}


/**
 * eap_server_sm_step - Step EAP server state machine
 * @sm: Pointer to EAP state machine allocated with eap_server_sm_init()
 * Returns: 1 if EAP state was changed or 0 if not
 *
 * This function advances EAP state machine to a new state to match with the
 * current variables. This should be called whenever variables used by the EAP
 * state machine have changed.
 */
int eap_server_sm_step(struct eap_sm *sm)
{
	int res = 0;
	do {
		sm->changed = FALSE;
		SM_STEP_RUN(EAP);
		if (sm->changed)
			res = 1;
	} while (sm->changed);
	return res;
}


void eap_user_free(struct eap_user *user)
{
	if (user == NULL)
		return;
	bin_clear_free(user->password, user->password_len);
	user->password = NULL;
	bin_clear_free(user->salt, user->salt_len);
	user->salt = NULL;
	os_free(user);
}


/**
 * eap_server_sm_init - Allocate and initialize EAP server state machine
 * @eapol_ctx: Context data to be used with eapol_cb calls
 * @eapol_cb: Pointer to EAPOL callback functions
 * @conf: EAP configuration
 * Returns: Pointer to the allocated EAP state machine or %NULL on failure
 *
 * This function allocates and initializes an EAP state machine.
 */
struct eap_sm * eap_server_sm_init(void *eapol_ctx,
				   const struct eapol_callbacks *eapol_cb,
				   struct eap_config *conf)
{
	struct eap_sm *sm;

	sm = os_zalloc(sizeof(*sm));
	if (sm == NULL)
		return NULL;
	sm->eapol_ctx = eapol_ctx;
	sm->eapol_cb = eapol_cb;
	sm->MaxRetrans = 5; /* RFC 3748: max 3-5 retransmissions suggested */
	sm->ssl_ctx = conf->ssl_ctx;
	sm->msg_ctx = conf->msg_ctx;
	sm->eap_sim_db_priv = conf->eap_sim_db_priv;
	sm->backend_auth = conf->backend_auth;
	sm->eap_server = conf->eap_server;
	if (conf->pac_opaque_encr_key) {
		sm->pac_opaque_encr_key = os_malloc(16);
		if (sm->pac_opaque_encr_key) {
			os_memcpy(sm->pac_opaque_encr_key,
				  conf->pac_opaque_encr_key, 16);
		}
	}
	if (conf->eap_fast_a_id) {
		sm->eap_fast_a_id = os_malloc(conf->eap_fast_a_id_len);
		if (sm->eap_fast_a_id) {
			os_memcpy(sm->eap_fast_a_id, conf->eap_fast_a_id,
				  conf->eap_fast_a_id_len);
			sm->eap_fast_a_id_len = conf->eap_fast_a_id_len;
		}
	}
	if (conf->eap_fast_a_id_info)
		sm->eap_fast_a_id_info = os_strdup(conf->eap_fast_a_id_info);
	sm->eap_fast_prov = conf->eap_fast_prov;
	sm->pac_key_lifetime = conf->pac_key_lifetime;
	sm->pac_key_refresh_time = conf->pac_key_refresh_time;
	sm->eap_teap_auth = conf->eap_teap_auth;
	sm->eap_teap_pac_no_inner = conf->eap_teap_pac_no_inner;
	sm->eap_sim_aka_result_ind = conf->eap_sim_aka_result_ind;
	sm->eap_sim_id = conf->eap_sim_id;
	sm->tnc = conf->tnc;
	sm->wps = conf->wps;
	if (conf->assoc_wps_ie)
		sm->assoc_wps_ie = wpabuf_dup(conf->assoc_wps_ie);
	if (conf->assoc_p2p_ie)
		sm->assoc_p2p_ie = wpabuf_dup(conf->assoc_p2p_ie);
	if (conf->peer_addr)
		os_memcpy(sm->peer_addr, conf->peer_addr, ETH_ALEN);
	sm->fragment_size = conf->fragment_size;
	sm->pwd_group = conf->pwd_group;
	sm->pbc_in_m1 = conf->pbc_in_m1;
	sm->server_id = conf->server_id;
	sm->server_id_len = conf->server_id_len;
	sm->erp = conf->erp;
	sm->tls_session_lifetime = conf->tls_session_lifetime;
	sm->tls_flags = conf->tls_flags;

#ifdef CONFIG_TESTING_OPTIONS
	sm->tls_test_flags = conf->tls_test_flags;
#endif /* CONFIG_TESTING_OPTIONS */

	wpa_printf(MSG_DEBUG, "EAP: Server state machine created");

	return sm;
}


/**
 * eap_server_sm_deinit - Deinitialize and free an EAP server state machine
 * @sm: Pointer to EAP state machine allocated with eap_server_sm_init()
 *
 * This function deinitializes EAP state machine and frees all allocated
 * resources.
 */
void eap_server_sm_deinit(struct eap_sm *sm)
{
	if (sm == NULL)
		return;
	wpa_printf(MSG_DEBUG, "EAP: Server state machine removed");
	if (sm->m && sm->eap_method_priv)
		sm->m->reset(sm, sm->eap_method_priv);
	wpabuf_free(sm->eap_if.eapReqData);
	bin_clear_free(sm->eap_if.eapKeyData, sm->eap_if.eapKeyDataLen);
	os_free(sm->eap_if.eapSessionId);
	wpabuf_free(sm->lastReqData);
	wpabuf_free(sm->eap_if.eapRespData);
	os_free(sm->identity);
	os_free(sm->serial_num);
	os_free(sm->pac_opaque_encr_key);
	os_free(sm->eap_fast_a_id);
	os_free(sm->eap_fast_a_id_info);
	wpabuf_free(sm->eap_if.aaaEapReqData);
	wpabuf_free(sm->eap_if.aaaEapRespData);
	bin_clear_free(sm->eap_if.aaaEapKeyData, sm->eap_if.aaaEapKeyDataLen);
	eap_user_free(sm->user);
	wpabuf_free(sm->assoc_wps_ie);
	wpabuf_free(sm->assoc_p2p_ie);
	os_free(sm);
}


/**
 * eap_sm_notify_cached - Notify EAP state machine of cached PMK
 * @sm: Pointer to EAP state machine allocated with eap_server_sm_init()
 *
 * This function is called when PMKSA caching is used to skip EAP
 * authentication.
 */
void eap_sm_notify_cached(struct eap_sm *sm)
{
	if (sm == NULL)
		return;

	sm->EAP_state = EAP_SUCCESS;
}


/**
 * eap_sm_pending_cb - EAP state machine callback for a pending EAP request
 * @sm: Pointer to EAP state machine allocated with eap_server_sm_init()
 *
 * This function is called when data for a pending EAP-Request is received.
 */
void eap_sm_pending_cb(struct eap_sm *sm)
{
	if (sm == NULL)
		return;
	wpa_printf(MSG_DEBUG, "EAP: Callback for pending request received");
	if (sm->method_pending == METHOD_PENDING_WAIT)
		sm->method_pending = METHOD_PENDING_CONT;
}


/**
 * eap_sm_method_pending - Query whether EAP method is waiting for pending data
 * @sm: Pointer to EAP state machine allocated with eap_server_sm_init()
 * Returns: 1 if method is waiting for pending data or 0 if not
 */
int eap_sm_method_pending(struct eap_sm *sm)
{
	if (sm == NULL)
		return 0;
	return sm->method_pending == METHOD_PENDING_WAIT;
}


/**
 * eap_get_identity - Get the user identity (from EAP-Response/Identity)
 * @sm: Pointer to EAP state machine allocated with eap_server_sm_init()
 * @len: Buffer for returning identity length
 * Returns: Pointer to the user identity or %NULL if not available
 */
const u8 * eap_get_identity(struct eap_sm *sm, size_t *len)
{
	*len = sm->identity_len;
	return sm->identity;
}


/**
 * eap_get_serial_num - Get the serial number of user certificate
 * @sm: Pointer to EAP state machine allocated with eap_server_sm_init()
 * Returns: Pointer to the serial number or %NULL if not available
 */
const char * eap_get_serial_num(struct eap_sm *sm)
{
	return sm->serial_num;
}


/**
 * eap_get_method - Get the used EAP method
 * @sm: Pointer to EAP state machine allocated with eap_server_sm_init()
 * Returns: Pointer to the method name or %NULL if not available
 */
const char * eap_get_method(struct eap_sm *sm)
{
	if (!sm || !sm->m)
		return NULL;
	return sm->m->name;
}


/**
 * eap_get_imsi - Get IMSI of the user
 * @sm: Pointer to EAP state machine allocated with eap_server_sm_init()
 * Returns: Pointer to IMSI or %NULL if not available
 */
const char * eap_get_imsi(struct eap_sm *sm)
{
	if (!sm || sm->imsi[0] == '\0')
		return NULL;
	return sm->imsi;
}


void eap_erp_update_identity(struct eap_sm *sm, const u8 *eap, size_t len)
{
#ifdef CONFIG_ERP
	const struct eap_hdr *hdr;
	const u8 *pos, *end;
	struct erp_tlvs parse;

	if (len < sizeof(*hdr) + 1)
		return;
	hdr = (const struct eap_hdr *) eap;
	end = eap + len;
	pos = (const u8 *) (hdr + 1);
	if (hdr->code != EAP_CODE_INITIATE || *pos != EAP_ERP_TYPE_REAUTH)
		return;
	pos++;
	if (pos + 3 > end)
		return;

	/* Skip Flags and SEQ */
	pos += 3;

	if (erp_parse_tlvs(pos, end, &parse, 1) < 0 || !parse.keyname)
		return;
	wpa_hexdump_ascii(MSG_DEBUG,
			  "EAP: Update identity based on EAP-Initiate/Re-auth keyName-NAI",
			  parse.keyname, parse.keyname_len);
	os_free(sm->identity);
	sm->identity = os_malloc(parse.keyname_len);
	if (sm->identity) {
		os_memcpy(sm->identity, parse.keyname, parse.keyname_len);
		sm->identity_len = parse.keyname_len;
	} else {
		sm->identity_len = 0;
	}
#endif /* CONFIG_ERP */
}


/**
 * eap_get_interface - Get pointer to EAP-EAPOL interface data
 * @sm: Pointer to EAP state machine allocated with eap_server_sm_init()
 * Returns: Pointer to the EAP-EAPOL interface data
 */
struct eap_eapol_interface * eap_get_interface(struct eap_sm *sm)
{
	return &sm->eap_if;
}


/**
 * eap_server_clear_identity - Clear EAP identity information
 * @sm: Pointer to EAP state machine allocated with eap_server_sm_init()
 *
 * This function can be used to clear the EAP identity information in the EAP
 * server context. This allows the EAP/Identity method to be used again after
 * EAPOL-Start or EAPOL-Logoff.
 */
void eap_server_clear_identity(struct eap_sm *sm)
{
	os_free(sm->identity);
	sm->identity = NULL;
}


#ifdef CONFIG_TESTING_OPTIONS
void eap_server_mschap_rx_callback(struct eap_sm *sm, const char *source,
				   const u8 *username, size_t username_len,
				   const u8 *challenge, const u8 *response)
{
	char hex_challenge[30], hex_response[90], user[100];

	/* Print out Challenge and Response in format supported by asleap. */
	if (username)
		printf_encode(user, sizeof(user), username, username_len);
	else
		user[0] = '\0';
	wpa_snprintf_hex_sep(hex_challenge, sizeof(hex_challenge),
			     challenge, sizeof(challenge), ':');
	wpa_snprintf_hex_sep(hex_response, sizeof(hex_response), response, 24,
			     ':');
	wpa_printf(MSG_DEBUG, "[%s/user=%s] asleap -C %s -R %s",
		   source, user, hex_challenge, hex_response);
}
#endif /* CONFIG_TESTING_OPTIONS */