summaryrefslogtreecommitdiffstats
path: root/contrib/wpa/src/radius/radius_server.c
blob: 744283c7dc9d739535e7f1c948205ec6adfee225 (plain)
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
/*
 * RADIUS authentication server
 * Copyright (c) 2005-2009, 2011-2014, Jouni Malinen <j@w1.fi>
 *
 * This software may be distributed under the terms of the BSD license.
 * See README for more details.
 */

#include "includes.h"
#include <net/if.h>
#ifdef CONFIG_SQLITE
#include <sqlite3.h>
#endif /* CONFIG_SQLITE */

#include "common.h"
#include "radius.h"
#include "eloop.h"
#include "eap_server/eap.h"
#include "ap/ap_config.h"
#include "crypto/tls.h"
#include "radius_server.h"

/**
 * RADIUS_SESSION_TIMEOUT - Session timeout in seconds
 */
#define RADIUS_SESSION_TIMEOUT 60

/**
 * RADIUS_MAX_SESSION - Maximum number of active sessions
 */
#define RADIUS_MAX_SESSION 100

/**
 * RADIUS_MAX_MSG_LEN - Maximum message length for incoming RADIUS messages
 */
#define RADIUS_MAX_MSG_LEN 3000

static const struct eapol_callbacks radius_server_eapol_cb;

struct radius_client;
struct radius_server_data;

/**
 * struct radius_server_counters - RADIUS server statistics counters
 */
struct radius_server_counters {
	u32 access_requests;
	u32 invalid_requests;
	u32 dup_access_requests;
	u32 access_accepts;
	u32 access_rejects;
	u32 access_challenges;
	u32 malformed_access_requests;
	u32 bad_authenticators;
	u32 packets_dropped;
	u32 unknown_types;

	u32 acct_requests;
	u32 invalid_acct_requests;
	u32 acct_responses;
	u32 malformed_acct_requests;
	u32 acct_bad_authenticators;
	u32 unknown_acct_types;
};

/**
 * struct radius_session - Internal RADIUS server data for a session
 */
struct radius_session {
	struct radius_session *next;
	struct radius_client *client;
	struct radius_server_data *server;
	unsigned int sess_id;
	struct eap_sm *eap;
	struct eap_eapol_interface *eap_if;
	char *username; /* from User-Name attribute */
	char *nas_ip;

	struct radius_msg *last_msg;
	char *last_from_addr;
	int last_from_port;
	struct sockaddr_storage last_from;
	socklen_t last_fromlen;
	u8 last_identifier;
	struct radius_msg *last_reply;
	u8 last_authenticator[16];

	unsigned int remediation:1;
	unsigned int macacl:1;

	struct hostapd_radius_attr *accept_attr;
};

/**
 * struct radius_client - Internal RADIUS server data for a client
 */
struct radius_client {
	struct radius_client *next;
	struct in_addr addr;
	struct in_addr mask;
#ifdef CONFIG_IPV6
	struct in6_addr addr6;
	struct in6_addr mask6;
#endif /* CONFIG_IPV6 */
	char *shared_secret;
	int shared_secret_len;
	struct radius_session *sessions;
	struct radius_server_counters counters;
};

/**
 * struct radius_server_data - Internal RADIUS server data
 */
struct radius_server_data {
	/**
	 * auth_sock - Socket for RADIUS authentication messages
	 */
	int auth_sock;

	/**
	 * acct_sock - Socket for RADIUS accounting messages
	 */
	int acct_sock;

	/**
	 * clients - List of authorized RADIUS clients
	 */
	struct radius_client *clients;

	/**
	 * next_sess_id - Next session identifier
	 */
	unsigned int next_sess_id;

	/**
	 * conf_ctx - Context pointer for callbacks
	 *
	 * This is used as the ctx argument in get_eap_user() calls.
	 */
	void *conf_ctx;

	/**
	 * num_sess - Number of active sessions
	 */
	int num_sess;

	/**
	 * eap_sim_db_priv - EAP-SIM/AKA database context
	 *
	 * This is passed to the EAP-SIM/AKA server implementation as a
	 * callback context.
	 */
	void *eap_sim_db_priv;

	/**
	 * ssl_ctx - TLS context
	 *
	 * This is passed to the EAP server implementation as a callback
	 * context for TLS operations.
	 */
	void *ssl_ctx;

	/**
	 * pac_opaque_encr_key - PAC-Opaque encryption key for EAP-FAST
	 *
	 * This parameter is used to set a key for EAP-FAST to encrypt the
	 * PAC-Opaque data. It can be set to %NULL if EAP-FAST is not used. If
	 * set, must point to a 16-octet key.
	 */
	u8 *pac_opaque_encr_key;

	/**
	 * eap_fast_a_id - EAP-FAST authority identity (A-ID)
	 *
	 * If EAP-FAST is not used, this can be set to %NULL. In theory, this
	 * is a variable length field, but due to some existing implementations
	 * requiring A-ID to be 16 octets in length, it is recommended to use
	 * that length for the field to provide interoperability with deployed
	 * peer implementations.
	 */
	u8 *eap_fast_a_id;

	/**
	 * eap_fast_a_id_len - Length of eap_fast_a_id buffer in octets
	 */
	size_t eap_fast_a_id_len;

	/**
	 * eap_fast_a_id_info - EAP-FAST authority identifier information
	 *
	 * This A-ID-Info contains a user-friendly name for the A-ID. For
	 * example, this could be the enterprise and server names in
	 * human-readable format. This field is encoded as UTF-8. If EAP-FAST
	 * is not used, this can be set to %NULL.
	 */
	char *eap_fast_a_id_info;

	/**
	 * eap_fast_prov - EAP-FAST provisioning modes
	 *
	 * 0 = provisioning disabled, 1 = only anonymous provisioning allowed,
	 * 2 = only authenticated provisioning allowed, 3 = both provisioning
	 * modes allowed.
	 */
	int eap_fast_prov;

	/**
	 * pac_key_lifetime - EAP-FAST PAC-Key lifetime in seconds
	 *
	 * This is the hard limit on how long a provisioned PAC-Key can be
	 * used.
	 */
	int pac_key_lifetime;

	/**
	 * pac_key_refresh_time - EAP-FAST PAC-Key refresh time in seconds
	 *
	 * This is a soft limit on the PAC-Key. The server will automatically
	 * generate a new PAC-Key when this number of seconds (or fewer) of the
	 * lifetime remains.
	 */
	int pac_key_refresh_time;

	/**
	 * eap_sim_aka_result_ind - EAP-SIM/AKA protected success indication
	 *
	 * This controls whether the protected success/failure indication
	 * (AT_RESULT_IND) is used with EAP-SIM and EAP-AKA.
	 */
	int eap_sim_aka_result_ind;

	/**
	 * tnc - Trusted Network Connect (TNC)
	 *
	 * This controls whether TNC is enabled and will be required before the
	 * peer is allowed to connect. Note: This is only used with EAP-TTLS
	 * and EAP-FAST. If any other EAP method is enabled, the peer will be
	 * allowed to connect without TNC.
	 */
	int tnc;

	/**
	 * pwd_group - The D-H group assigned for EAP-pwd
	 *
	 * If EAP-pwd is not used it can be set to zero.
	 */
	u16 pwd_group;

	/**
	 * server_id - Server identity
	 */
	const char *server_id;

	/**
	 * erp - Whether EAP Re-authentication Protocol (ERP) is enabled
	 *
	 * This controls whether the authentication server derives ERP key
	 * hierarchy (rRK and rIK) from full EAP authentication and allows
	 * these keys to be used to perform ERP to derive rMSK instead of full
	 * EAP authentication to derive MSK.
	 */
	int erp;

	const char *erp_domain;

	struct dl_list erp_keys; /* struct eap_server_erp_key */

	unsigned int tls_session_lifetime;

	/**
	 * wps - Wi-Fi Protected Setup context
	 *
	 * If WPS is used with an external RADIUS server (which is quite
	 * unlikely configuration), this is used to provide a pointer to WPS
	 * context data. Normally, this can be set to %NULL.
	 */
	struct wps_context *wps;

	/**
	 * ipv6 - Whether to enable IPv6 support in the RADIUS server
	 */
	int ipv6;

	/**
	 * start_time - Timestamp of server start
	 */
	struct os_reltime start_time;

	/**
	 * counters - Statistics counters for server operations
	 *
	 * These counters are the sum over all clients.
	 */
	struct radius_server_counters counters;

	/**
	 * get_eap_user - Callback for fetching EAP user information
	 * @ctx: Context data from conf_ctx
	 * @identity: User identity
	 * @identity_len: identity buffer length in octets
	 * @phase2: Whether this is for Phase 2 identity
	 * @user: Data structure for filling in the user information
	 * Returns: 0 on success, -1 on failure
	 *
	 * This is used to fetch information from user database. The callback
	 * will fill in information about allowed EAP methods and the user
	 * password. The password field will be an allocated copy of the
	 * password data and RADIUS server will free it after use.
	 */
	int (*get_eap_user)(void *ctx, const u8 *identity, size_t identity_len,
			    int phase2, struct eap_user *user);

	/**
	 * eap_req_id_text - Optional data for EAP-Request/Identity
	 *
	 * This can be used to configure an optional, displayable message that
	 * will be sent in EAP-Request/Identity. This string can contain an
	 * ASCII-0 character (nul) to separate network infromation per RFC
	 * 4284. The actual string length is explicit provided in
	 * eap_req_id_text_len since nul character will not be used as a string
	 * terminator.
	 */
	char *eap_req_id_text;

	/**
	 * eap_req_id_text_len - Length of eap_req_id_text buffer in octets
	 */
	size_t eap_req_id_text_len;

	/*
	 * msg_ctx - Context data for wpa_msg() calls
	 */
	void *msg_ctx;

#ifdef CONFIG_RADIUS_TEST
	char *dump_msk_file;
#endif /* CONFIG_RADIUS_TEST */

	char *subscr_remediation_url;
	u8 subscr_remediation_method;

#ifdef CONFIG_SQLITE
	sqlite3 *db;
#endif /* CONFIG_SQLITE */
};


#define RADIUS_DEBUG(args...) \
wpa_printf(MSG_DEBUG, "RADIUS SRV: " args)
#define RADIUS_ERROR(args...) \
wpa_printf(MSG_ERROR, "RADIUS SRV: " args)
#define RADIUS_DUMP(args...) \
wpa_hexdump(MSG_MSGDUMP, "RADIUS SRV: " args)
#define RADIUS_DUMP_ASCII(args...) \
wpa_hexdump_ascii(MSG_MSGDUMP, "RADIUS SRV: " args)


static void radius_server_session_timeout(void *eloop_ctx, void *timeout_ctx);
static void radius_server_session_remove_timeout(void *eloop_ctx,
						 void *timeout_ctx);

void srv_log(struct radius_session *sess, const char *fmt, ...)
PRINTF_FORMAT(2, 3);

void srv_log(struct radius_session *sess, const char *fmt, ...)
{
	va_list ap;
	char *buf;
	int buflen;

	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);

	RADIUS_DEBUG("[0x%x %s] %s", sess->sess_id, sess->nas_ip, buf);

#ifdef CONFIG_SQLITE
	if (sess->server->db) {
		char *sql;
		sql = sqlite3_mprintf("INSERT INTO authlog"
				      "(timestamp,session,nas_ip,username,note)"
				      " VALUES ("
				      "strftime('%%Y-%%m-%%d %%H:%%M:%%f',"
				      "'now'),%u,%Q,%Q,%Q)",
				      sess->sess_id, sess->nas_ip,
				      sess->username, buf);
		if (sql) {
			if (sqlite3_exec(sess->server->db, sql, NULL, NULL,
					 NULL) != SQLITE_OK) {
				RADIUS_ERROR("Failed to add authlog entry into sqlite database: %s",
					     sqlite3_errmsg(sess->server->db));
			}
			sqlite3_free(sql);
		}
	}
#endif /* CONFIG_SQLITE */

	os_free(buf);
}


static struct radius_client *
radius_server_get_client(struct radius_server_data *data, struct in_addr *addr,
			 int ipv6)
{
	struct radius_client *client = data->clients;

	while (client) {
#ifdef CONFIG_IPV6
		if (ipv6) {
			struct in6_addr *addr6;
			int i;

			addr6 = (struct in6_addr *) addr;
			for (i = 0; i < 16; i++) {
				if ((addr6->s6_addr[i] &
				     client->mask6.s6_addr[i]) !=
				    (client->addr6.s6_addr[i] &
				     client->mask6.s6_addr[i])) {
					i = 17;
					break;
				}
			}
			if (i == 16) {
				break;
			}
		}
#endif /* CONFIG_IPV6 */
		if (!ipv6 && (client->addr.s_addr & client->mask.s_addr) ==
		    (addr->s_addr & client->mask.s_addr)) {
			break;
		}

		client = client->next;
	}

	return client;
}


static struct radius_session *
radius_server_get_session(struct radius_client *client, unsigned int sess_id)
{
	struct radius_session *sess = client->sessions;

	while (sess) {
		if (sess->sess_id == sess_id) {
			break;
		}
		sess = sess->next;
	}

	return sess;
}


static void radius_server_session_free(struct radius_server_data *data,
				       struct radius_session *sess)
{
	eloop_cancel_timeout(radius_server_session_timeout, data, sess);
	eloop_cancel_timeout(radius_server_session_remove_timeout, data, sess);
	eap_server_sm_deinit(sess->eap);
	radius_msg_free(sess->last_msg);
	os_free(sess->last_from_addr);
	radius_msg_free(sess->last_reply);
	os_free(sess->username);
	os_free(sess->nas_ip);
	os_free(sess);
	data->num_sess--;
}


static void radius_server_session_remove(struct radius_server_data *data,
					 struct radius_session *sess)
{
	struct radius_client *client = sess->client;
	struct radius_session *session, *prev;

	eloop_cancel_timeout(radius_server_session_remove_timeout, data, sess);

	prev = NULL;
	session = client->sessions;
	while (session) {
		if (session == sess) {
			if (prev == NULL) {
				client->sessions = sess->next;
			} else {
				prev->next = sess->next;
			}
			radius_server_session_free(data, sess);
			break;
		}
		prev = session;
		session = session->next;
	}
}


static void radius_server_session_remove_timeout(void *eloop_ctx,
						 void *timeout_ctx)
{
	struct radius_server_data *data = eloop_ctx;
	struct radius_session *sess = timeout_ctx;
	RADIUS_DEBUG("Removing completed session 0x%x", sess->sess_id);
	radius_server_session_remove(data, sess);
}


static void radius_server_session_timeout(void *eloop_ctx, void *timeout_ctx)
{
	struct radius_server_data *data = eloop_ctx;
	struct radius_session *sess = timeout_ctx;

	RADIUS_DEBUG("Timing out authentication session 0x%x", sess->sess_id);
	radius_server_session_remove(data, sess);
}


static struct radius_session *
radius_server_new_session(struct radius_server_data *data,
			  struct radius_client *client)
{
	struct radius_session *sess;

	if (data->num_sess >= RADIUS_MAX_SESSION) {
		RADIUS_DEBUG("Maximum number of existing session - no room "
			     "for a new session");
		return NULL;
	}

	sess = os_zalloc(sizeof(*sess));
	if (sess == NULL)
		return NULL;

	sess->server = data;
	sess->client = client;
	sess->sess_id = data->next_sess_id++;
	sess->next = client->sessions;
	client->sessions = sess;
	eloop_register_timeout(RADIUS_SESSION_TIMEOUT, 0,
			       radius_server_session_timeout, data, sess);
	data->num_sess++;
	return sess;
}


#ifdef CONFIG_TESTING_OPTIONS
static void radius_server_testing_options_tls(struct radius_session *sess,
					      const char *tls,
					      struct eap_config *eap_conf)
{
	int test = atoi(tls);

	switch (test) {
	case 1:
		srv_log(sess, "TLS test - break VerifyData");
		eap_conf->tls_test_flags = TLS_BREAK_VERIFY_DATA;
		break;
	case 2:
		srv_log(sess, "TLS test - break ServerKeyExchange ServerParams hash");
		eap_conf->tls_test_flags = TLS_BREAK_SRV_KEY_X_HASH;
		break;
	case 3:
		srv_log(sess, "TLS test - break ServerKeyExchange ServerParams Signature");
		eap_conf->tls_test_flags = TLS_BREAK_SRV_KEY_X_SIGNATURE;
		break;
	case 4:
		srv_log(sess, "TLS test - RSA-DHE using a short 511-bit prime");
		eap_conf->tls_test_flags = TLS_DHE_PRIME_511B;
		break;
	case 5:
		srv_log(sess, "TLS test - RSA-DHE using a short 767-bit prime");
		eap_conf->tls_test_flags = TLS_DHE_PRIME_767B;
		break;
	case 6:
		srv_log(sess, "TLS test - RSA-DHE using a bogus 15 \"prime\"");
		eap_conf->tls_test_flags = TLS_DHE_PRIME_15;
		break;
	case 7:
		srv_log(sess, "TLS test - RSA-DHE using a short 58-bit prime in long container");
		eap_conf->tls_test_flags = TLS_DHE_PRIME_58B;
		break;
	case 8:
		srv_log(sess, "TLS test - RSA-DHE using a non-prime");
		eap_conf->tls_test_flags = TLS_DHE_NON_PRIME;
		break;
	default:
		srv_log(sess, "Unrecognized TLS test");
		break;
	}
}
#endif /* CONFIG_TESTING_OPTIONS */

static void radius_server_testing_options(struct radius_session *sess,
					  struct eap_config *eap_conf)
{
#ifdef CONFIG_TESTING_OPTIONS
	const char *pos;

	pos = os_strstr(sess->username, "@test-");
	if (pos == NULL)
		return;
	pos += 6;
	if (os_strncmp(pos, "tls-", 4) == 0)
		radius_server_testing_options_tls(sess, pos + 4, eap_conf);
	else
		srv_log(sess, "Unrecognized test: %s", pos);
#endif /* CONFIG_TESTING_OPTIONS */
}


static struct radius_session *
radius_server_get_new_session(struct radius_server_data *data,
			      struct radius_client *client,
			      struct radius_msg *msg, const char *from_addr)
{
	u8 *user;
	size_t user_len;
	int res;
	struct radius_session *sess;
	struct eap_config eap_conf;
	struct eap_user tmp;

	RADIUS_DEBUG("Creating a new session");

	if (radius_msg_get_attr_ptr(msg, RADIUS_ATTR_USER_NAME, &user,
				    &user_len, NULL) < 0) {
		RADIUS_DEBUG("Could not get User-Name");
		return NULL;
	}
	RADIUS_DUMP_ASCII("User-Name", user, user_len);

	os_memset(&tmp, 0, sizeof(tmp));
	res = data->get_eap_user(data->conf_ctx, user, user_len, 0, &tmp);
	bin_clear_free(tmp.password, tmp.password_len);

	if (res != 0) {
		RADIUS_DEBUG("User-Name not found from user database");
		return NULL;
	}

	RADIUS_DEBUG("Matching user entry found");
	sess = radius_server_new_session(data, client);
	if (sess == NULL) {
		RADIUS_DEBUG("Failed to create a new session");
		return NULL;
	}
	sess->accept_attr = tmp.accept_attr;
	sess->macacl = tmp.macacl;

	sess->username = os_malloc(user_len * 4 + 1);
	if (sess->username == NULL) {
		radius_server_session_free(data, sess);
		return NULL;
	}
	printf_encode(sess->username, user_len * 4 + 1, user, user_len);

	sess->nas_ip = os_strdup(from_addr);
	if (sess->nas_ip == NULL) {
		radius_server_session_free(data, sess);
		return NULL;
	}

	srv_log(sess, "New session created");

	os_memset(&eap_conf, 0, sizeof(eap_conf));
	eap_conf.ssl_ctx = data->ssl_ctx;
	eap_conf.msg_ctx = data->msg_ctx;
	eap_conf.eap_sim_db_priv = data->eap_sim_db_priv;
	eap_conf.backend_auth = TRUE;
	eap_conf.eap_server = 1;
	eap_conf.pac_opaque_encr_key = data->pac_opaque_encr_key;
	eap_conf.eap_fast_a_id = data->eap_fast_a_id;
	eap_conf.eap_fast_a_id_len = data->eap_fast_a_id_len;
	eap_conf.eap_fast_a_id_info = data->eap_fast_a_id_info;
	eap_conf.eap_fast_prov = data->eap_fast_prov;
	eap_conf.pac_key_lifetime = data->pac_key_lifetime;
	eap_conf.pac_key_refresh_time = data->pac_key_refresh_time;
	eap_conf.eap_sim_aka_result_ind = data->eap_sim_aka_result_ind;
	eap_conf.tnc = data->tnc;
	eap_conf.wps = data->wps;
	eap_conf.pwd_group = data->pwd_group;
	eap_conf.server_id = (const u8 *) data->server_id;
	eap_conf.server_id_len = os_strlen(data->server_id);
	eap_conf.erp = data->erp;
	eap_conf.tls_session_lifetime = data->tls_session_lifetime;
	radius_server_testing_options(sess, &eap_conf);
	sess->eap = eap_server_sm_init(sess, &radius_server_eapol_cb,
				       &eap_conf);
	if (sess->eap == NULL) {
		RADIUS_DEBUG("Failed to initialize EAP state machine for the "
			     "new session");
		radius_server_session_free(data, sess);
		return NULL;
	}
	sess->eap_if = eap_get_interface(sess->eap);
	sess->eap_if->eapRestart = TRUE;
	sess->eap_if->portEnabled = TRUE;

	RADIUS_DEBUG("New session 0x%x initialized", sess->sess_id);

	return sess;
}


static struct radius_msg *
radius_server_encapsulate_eap(struct radius_server_data *data,
			      struct radius_client *client,
			      struct radius_session *sess,
			      struct radius_msg *request)
{
	struct radius_msg *msg;
	int code;
	unsigned int sess_id;
	struct radius_hdr *hdr = radius_msg_get_hdr(request);

	if (sess->eap_if->eapFail) {
		sess->eap_if->eapFail = FALSE;
		code = RADIUS_CODE_ACCESS_REJECT;
	} else if (sess->eap_if->eapSuccess) {
		sess->eap_if->eapSuccess = FALSE;
		code = RADIUS_CODE_ACCESS_ACCEPT;
	} else {
		sess->eap_if->eapReq = FALSE;
		code = RADIUS_CODE_ACCESS_CHALLENGE;
	}

	msg = radius_msg_new(code, hdr->identifier);
	if (msg == NULL) {
		RADIUS_DEBUG("Failed to allocate reply message");
		return NULL;
	}

	sess_id = htonl(sess->sess_id);
	if (code == RADIUS_CODE_ACCESS_CHALLENGE &&
	    !radius_msg_add_attr(msg, RADIUS_ATTR_STATE,
				 (u8 *) &sess_id, sizeof(sess_id))) {
		RADIUS_DEBUG("Failed to add State attribute");
	}

	if (sess->eap_if->eapReqData &&
	    !radius_msg_add_eap(msg, wpabuf_head(sess->eap_if->eapReqData),
				wpabuf_len(sess->eap_if->eapReqData))) {
		RADIUS_DEBUG("Failed to add EAP-Message attribute");
	}

	if (code == RADIUS_CODE_ACCESS_ACCEPT && sess->eap_if->eapKeyData) {
		int len;
#ifdef CONFIG_RADIUS_TEST
		if (data->dump_msk_file) {
			FILE *f;
			char buf[2 * 64 + 1];
			f = fopen(data->dump_msk_file, "a");
			if (f) {
				len = sess->eap_if->eapKeyDataLen;
				if (len > 64)
					len = 64;
				len = wpa_snprintf_hex(
					buf, sizeof(buf),
					sess->eap_if->eapKeyData, len);
				buf[len] = '\0';
				fprintf(f, "%s\n", buf);
				fclose(f);
			}
		}
#endif /* CONFIG_RADIUS_TEST */
		if (sess->eap_if->eapKeyDataLen > 64) {
			len = 32;
		} else {
			len = sess->eap_if->eapKeyDataLen / 2;
		}
		if (!radius_msg_add_mppe_keys(msg, hdr->authenticator,
					      (u8 *) client->shared_secret,
					      client->shared_secret_len,
					      sess->eap_if->eapKeyData + len,
					      len, sess->eap_if->eapKeyData,
					      len)) {
			RADIUS_DEBUG("Failed to add MPPE key attributes");
		}
	}

#ifdef CONFIG_HS20
	if (code == RADIUS_CODE_ACCESS_ACCEPT && sess->remediation &&
	    data->subscr_remediation_url) {
		u8 *buf;
		size_t url_len = os_strlen(data->subscr_remediation_url);
		buf = os_malloc(1 + url_len);
		if (buf == NULL) {
			radius_msg_free(msg);
			return NULL;
		}
		buf[0] = data->subscr_remediation_method;
		os_memcpy(&buf[1], data->subscr_remediation_url, url_len);
		if (!radius_msg_add_wfa(
			    msg, RADIUS_VENDOR_ATTR_WFA_HS20_SUBSCR_REMEDIATION,
			    buf, 1 + url_len)) {
			RADIUS_DEBUG("Failed to add WFA-HS20-SubscrRem");
		}
		os_free(buf);
	} else if (code == RADIUS_CODE_ACCESS_ACCEPT && sess->remediation) {
		u8 buf[1];
		if (!radius_msg_add_wfa(
			    msg, RADIUS_VENDOR_ATTR_WFA_HS20_SUBSCR_REMEDIATION,
			    buf, 0)) {
			RADIUS_DEBUG("Failed to add WFA-HS20-SubscrRem");
		}
	}
#endif /* CONFIG_HS20 */

	if (radius_msg_copy_attr(msg, request, RADIUS_ATTR_PROXY_STATE) < 0) {
		RADIUS_DEBUG("Failed to copy Proxy-State attribute(s)");
		radius_msg_free(msg);
		return NULL;
	}

	if (code == RADIUS_CODE_ACCESS_ACCEPT) {
		struct hostapd_radius_attr *attr;
		for (attr = sess->accept_attr; attr; attr = attr->next) {
			if (!radius_msg_add_attr(msg, attr->type,
						 wpabuf_head(attr->val),
						 wpabuf_len(attr->val))) {
				wpa_printf(MSG_ERROR, "Could not add RADIUS attribute");
				radius_msg_free(msg);
				return NULL;
			}
		}
	}

	if (radius_msg_finish_srv(msg, (u8 *) client->shared_secret,
				  client->shared_secret_len,
				  hdr->authenticator) < 0) {
		RADIUS_DEBUG("Failed to add Message-Authenticator attribute");
	}

	return msg;
}


static struct radius_msg *
radius_server_macacl(struct radius_server_data *data,
		     struct radius_client *client,
		     struct radius_session *sess,
		     struct radius_msg *request)
{
	struct radius_msg *msg;
	int code;
	struct radius_hdr *hdr = radius_msg_get_hdr(request);
	u8 *pw;
	size_t pw_len;

	code = RADIUS_CODE_ACCESS_ACCEPT;

	if (radius_msg_get_attr_ptr(request, RADIUS_ATTR_USER_PASSWORD, &pw,
				    &pw_len, NULL) < 0) {
		RADIUS_DEBUG("Could not get User-Password");
		code = RADIUS_CODE_ACCESS_REJECT;
	} else {
		int res;
		struct eap_user tmp;

		os_memset(&tmp, 0, sizeof(tmp));
		res = data->get_eap_user(data->conf_ctx, (u8 *) sess->username,
					 os_strlen(sess->username), 0, &tmp);
		if (res || !tmp.macacl || tmp.password == NULL) {
			RADIUS_DEBUG("No MAC ACL user entry");
			bin_clear_free(tmp.password, tmp.password_len);
			code = RADIUS_CODE_ACCESS_REJECT;
		} else {
			u8 buf[128];
			res = radius_user_password_hide(
				request, tmp.password, tmp.password_len,
				(u8 *) client->shared_secret,
				client->shared_secret_len,
				buf, sizeof(buf));
			bin_clear_free(tmp.password, tmp.password_len);

			if (res < 0 || pw_len != (size_t) res ||
			    os_memcmp_const(pw, buf, res) != 0) {
				RADIUS_DEBUG("Incorrect User-Password");
				code = RADIUS_CODE_ACCESS_REJECT;
			}
		}
	}

	msg = radius_msg_new(code, hdr->identifier);
	if (msg == NULL) {
		RADIUS_DEBUG("Failed to allocate reply message");
		return NULL;
	}

	if (radius_msg_copy_attr(msg, request, RADIUS_ATTR_PROXY_STATE) < 0) {
		RADIUS_DEBUG("Failed to copy Proxy-State attribute(s)");
		radius_msg_free(msg);
		return NULL;
	}

	if (code == RADIUS_CODE_ACCESS_ACCEPT) {
		struct hostapd_radius_attr *attr;
		for (attr = sess->accept_attr; attr; attr = attr->next) {
			if (!radius_msg_add_attr(msg, attr->type,
						 wpabuf_head(attr->val),
						 wpabuf_len(attr->val))) {
				wpa_printf(MSG_ERROR, "Could not add RADIUS attribute");
				radius_msg_free(msg);
				return NULL;
			}
		}
	}

	if (radius_msg_finish_srv(msg, (u8 *) client->shared_secret,
				  client->shared_secret_len,
				  hdr->authenticator) < 0) {
		RADIUS_DEBUG("Failed to add Message-Authenticator attribute");
	}

	return msg;
}


static int radius_server_reject(struct radius_server_data *data,
				struct radius_client *client,
				struct radius_msg *request,
				struct sockaddr *from, socklen_t fromlen,
				const char *from_addr, int from_port)
{
	struct radius_msg *msg;
	int ret = 0;
	struct eap_hdr eapfail;
	struct wpabuf *buf;
	struct radius_hdr *hdr = radius_msg_get_hdr(request);

	RADIUS_DEBUG("Reject invalid request from %s:%d",
		     from_addr, from_port);

	msg = radius_msg_new(RADIUS_CODE_ACCESS_REJECT, hdr->identifier);
	if (msg == NULL) {
		return -1;
	}

	os_memset(&eapfail, 0, sizeof(eapfail));
	eapfail.code = EAP_CODE_FAILURE;
	eapfail.identifier = 0;
	eapfail.length = host_to_be16(sizeof(eapfail));

	if (!radius_msg_add_eap(msg, (u8 *) &eapfail, sizeof(eapfail))) {
		RADIUS_DEBUG("Failed to add EAP-Message attribute");
	}

	if (radius_msg_copy_attr(msg, request, RADIUS_ATTR_PROXY_STATE) < 0) {
		RADIUS_DEBUG("Failed to copy Proxy-State attribute(s)");
		radius_msg_free(msg);
		return -1;
	}

	if (radius_msg_finish_srv(msg, (u8 *) client->shared_secret,
				  client->shared_secret_len,
				  hdr->authenticator) <
	    0) {
		RADIUS_DEBUG("Failed to add Message-Authenticator attribute");
	}

	if (wpa_debug_level <= MSG_MSGDUMP) {
		radius_msg_dump(msg);
	}

	data->counters.access_rejects++;
	client->counters.access_rejects++;
	buf = radius_msg_get_buf(msg);
	if (sendto(data->auth_sock, wpabuf_head(buf), wpabuf_len(buf), 0,
		   (struct sockaddr *) from, sizeof(*from)) < 0) {
		wpa_printf(MSG_INFO, "sendto[RADIUS SRV]: %s", strerror(errno));
		ret = -1;
	}

	radius_msg_free(msg);

	return ret;
}


static int radius_server_request(struct radius_server_data *data,
				 struct radius_msg *msg,
				 struct sockaddr *from, socklen_t fromlen,
				 struct radius_client *client,
				 const char *from_addr, int from_port,
				 struct radius_session *force_sess)
{
	struct wpabuf *eap = NULL;
	int res, state_included = 0;
	u8 statebuf[4];
	unsigned int state;
	struct radius_session *sess;
	struct radius_msg *reply;
	int is_complete = 0;

	if (force_sess)
		sess = force_sess;
	else {
		res = radius_msg_get_attr(msg, RADIUS_ATTR_STATE, statebuf,
					  sizeof(statebuf));
		state_included = res >= 0;
		if (res == sizeof(statebuf)) {
			state = WPA_GET_BE32(statebuf);
			sess = radius_server_get_session(client, state);
		} else {
			sess = NULL;
		}
	}

	if (sess) {
		RADIUS_DEBUG("Request for session 0x%x", sess->sess_id);
	} else if (state_included) {
		RADIUS_DEBUG("State attribute included but no session found");
		radius_server_reject(data, client, msg, from, fromlen,
				     from_addr, from_port);
		return -1;
	} else {
		sess = radius_server_get_new_session(data, client, msg,
						     from_addr);
		if (sess == NULL) {
			RADIUS_DEBUG("Could not create a new session");
			radius_server_reject(data, client, msg, from, fromlen,
					     from_addr, from_port);
			return -1;
		}
	}

	if (sess->last_from_port == from_port &&
	    sess->last_identifier == radius_msg_get_hdr(msg)->identifier &&
	    os_memcmp(sess->last_authenticator,
		      radius_msg_get_hdr(msg)->authenticator, 16) == 0) {
		RADIUS_DEBUG("Duplicate message from %s", from_addr);
		data->counters.dup_access_requests++;
		client->counters.dup_access_requests++;

		if (sess->last_reply) {
			struct wpabuf *buf;
			buf = radius_msg_get_buf(sess->last_reply);
			res = sendto(data->auth_sock, wpabuf_head(buf),
				     wpabuf_len(buf), 0,
				     (struct sockaddr *) from, fromlen);
			if (res < 0) {
				wpa_printf(MSG_INFO, "sendto[RADIUS SRV]: %s",
					   strerror(errno));
			}
			return 0;
		}

		RADIUS_DEBUG("No previous reply available for duplicate "
			     "message");
		return -1;
	}
		      
	eap = radius_msg_get_eap(msg);
	if (eap == NULL && sess->macacl) {
		reply = radius_server_macacl(data, client, sess, msg);
		if (reply == NULL)
			return -1;
		goto send_reply;
	}
	if (eap == NULL) {
		RADIUS_DEBUG("No EAP-Message in RADIUS packet from %s",
			     from_addr);
		data->counters.packets_dropped++;
		client->counters.packets_dropped++;
		return -1;
	}

	RADIUS_DUMP("Received EAP data", wpabuf_head(eap), wpabuf_len(eap));

	/* FIX: if Code is Request, Success, or Failure, send Access-Reject;
	 * RFC3579 Sect. 2.6.2.
	 * Include EAP-Response/Nak with no preferred method if
	 * code == request.
	 * If code is not 1-4, discard the packet silently.
	 * Or is this already done by the EAP state machine? */

	wpabuf_free(sess->eap_if->eapRespData);
	sess->eap_if->eapRespData = eap;
	sess->eap_if->eapResp = TRUE;
	eap_server_sm_step(sess->eap);

	if ((sess->eap_if->eapReq || sess->eap_if->eapSuccess ||
	     sess->eap_if->eapFail) && sess->eap_if->eapReqData) {
		RADIUS_DUMP("EAP data from the state machine",
			    wpabuf_head(sess->eap_if->eapReqData),
			    wpabuf_len(sess->eap_if->eapReqData));
	} else if (sess->eap_if->eapFail) {
		RADIUS_DEBUG("No EAP data from the state machine, but eapFail "
			     "set");
	} else if (eap_sm_method_pending(sess->eap)) {
		radius_msg_free(sess->last_msg);
		sess->last_msg = msg;
		sess->last_from_port = from_port;
		os_free(sess->last_from_addr);
		sess->last_from_addr = os_strdup(from_addr);
		sess->last_fromlen = fromlen;
		os_memcpy(&sess->last_from, from, fromlen);
		return -2;
	} else {
		RADIUS_DEBUG("No EAP data from the state machine - ignore this"
			     " Access-Request silently (assuming it was a "
			     "duplicate)");
		data->counters.packets_dropped++;
		client->counters.packets_dropped++;
		return -1;
	}

	if (sess->eap_if->eapSuccess || sess->eap_if->eapFail)
		is_complete = 1;
	if (sess->eap_if->eapFail)
		srv_log(sess, "EAP authentication failed");
	else if (sess->eap_if->eapSuccess)
		srv_log(sess, "EAP authentication succeeded");

	reply = radius_server_encapsulate_eap(data, client, sess, msg);

send_reply:
	if (reply) {
		struct wpabuf *buf;
		struct radius_hdr *hdr;

		RADIUS_DEBUG("Reply to %s:%d", from_addr, from_port);
		if (wpa_debug_level <= MSG_MSGDUMP) {
			radius_msg_dump(reply);
		}

		switch (radius_msg_get_hdr(reply)->code) {
		case RADIUS_CODE_ACCESS_ACCEPT:
			srv_log(sess, "Sending Access-Accept");
			data->counters.access_accepts++;
			client->counters.access_accepts++;
			break;
		case RADIUS_CODE_ACCESS_REJECT:
			srv_log(sess, "Sending Access-Reject");
			data->counters.access_rejects++;
			client->counters.access_rejects++;
			break;
		case RADIUS_CODE_ACCESS_CHALLENGE:
			data->counters.access_challenges++;
			client->counters.access_challenges++;
			break;
		}
		buf = radius_msg_get_buf(reply);
		res = sendto(data->auth_sock, wpabuf_head(buf),
			     wpabuf_len(buf), 0,
			     (struct sockaddr *) from, fromlen);
		if (res < 0) {
			wpa_printf(MSG_INFO, "sendto[RADIUS SRV]: %s",
				   strerror(errno));
		}
		radius_msg_free(sess->last_reply);
		sess->last_reply = reply;
		sess->last_from_port = from_port;
		hdr = radius_msg_get_hdr(msg);
		sess->last_identifier = hdr->identifier;
		os_memcpy(sess->last_authenticator, hdr->authenticator, 16);
	} else {
		data->counters.packets_dropped++;
		client->counters.packets_dropped++;
	}

	if (is_complete) {
		RADIUS_DEBUG("Removing completed session 0x%x after timeout",
			     sess->sess_id);
		eloop_cancel_timeout(radius_server_session_remove_timeout,
				     data, sess);
		eloop_register_timeout(10, 0,
				       radius_server_session_remove_timeout,
				       data, sess);
	}

	return 0;
}


static void radius_server_receive_auth(int sock, void *eloop_ctx,
				       void *sock_ctx)
{
	struct radius_server_data *data = eloop_ctx;
	u8 *buf = NULL;
	union {
		struct sockaddr_storage ss;
		struct sockaddr_in sin;
#ifdef CONFIG_IPV6
		struct sockaddr_in6 sin6;
#endif /* CONFIG_IPV6 */
	} from;
	socklen_t fromlen;
	int len;
	struct radius_client *client = NULL;
	struct radius_msg *msg = NULL;
	char abuf[50];
	int from_port = 0;

	buf = os_malloc(RADIUS_MAX_MSG_LEN);
	if (buf == NULL) {
		goto fail;
	}

	fromlen = sizeof(from);
	len = recvfrom(sock, buf, RADIUS_MAX_MSG_LEN, 0,
		       (struct sockaddr *) &from.ss, &fromlen);
	if (len < 0) {
		wpa_printf(MSG_INFO, "recvfrom[radius_server]: %s",
			   strerror(errno));
		goto fail;
	}

#ifdef CONFIG_IPV6
	if (data->ipv6) {
		if (inet_ntop(AF_INET6, &from.sin6.sin6_addr, abuf,
			      sizeof(abuf)) == NULL)
			abuf[0] = '\0';
		from_port = ntohs(from.sin6.sin6_port);
		RADIUS_DEBUG("Received %d bytes from %s:%d",
			     len, abuf, from_port);

		client = radius_server_get_client(data,
						  (struct in_addr *)
						  &from.sin6.sin6_addr, 1);
	}
#endif /* CONFIG_IPV6 */

	if (!data->ipv6) {
		os_strlcpy(abuf, inet_ntoa(from.sin.sin_addr), sizeof(abuf));
		from_port = ntohs(from.sin.sin_port);
		RADIUS_DEBUG("Received %d bytes from %s:%d",
			     len, abuf, from_port);

		client = radius_server_get_client(data, &from.sin.sin_addr, 0);
	}

	RADIUS_DUMP("Received data", buf, len);

	if (client == NULL) {
		RADIUS_DEBUG("Unknown client %s - packet ignored", abuf);
		data->counters.invalid_requests++;
		goto fail;
	}

	msg = radius_msg_parse(buf, len);
	if (msg == NULL) {
		RADIUS_DEBUG("Parsing incoming RADIUS frame failed");
		data->counters.malformed_access_requests++;
		client->counters.malformed_access_requests++;
		goto fail;
	}

	os_free(buf);
	buf = NULL;

	if (wpa_debug_level <= MSG_MSGDUMP) {
		radius_msg_dump(msg);
	}

	if (radius_msg_get_hdr(msg)->code != RADIUS_CODE_ACCESS_REQUEST) {
		RADIUS_DEBUG("Unexpected RADIUS code %d",
			     radius_msg_get_hdr(msg)->code);
		data->counters.unknown_types++;
		client->counters.unknown_types++;
		goto fail;
	}

	data->counters.access_requests++;
	client->counters.access_requests++;

	if (radius_msg_verify_msg_auth(msg, (u8 *) client->shared_secret,
				       client->shared_secret_len, NULL)) {
		RADIUS_DEBUG("Invalid Message-Authenticator from %s", abuf);
		data->counters.bad_authenticators++;
		client->counters.bad_authenticators++;
		goto fail;
	}

	if (radius_server_request(data, msg, (struct sockaddr *) &from,
				  fromlen, client, abuf, from_port, NULL) ==
	    -2)
		return; /* msg was stored with the session */

fail:
	radius_msg_free(msg);
	os_free(buf);
}


static void radius_server_receive_acct(int sock, void *eloop_ctx,
				       void *sock_ctx)
{
	struct radius_server_data *data = eloop_ctx;
	u8 *buf = NULL;
	union {
		struct sockaddr_storage ss;
		struct sockaddr_in sin;
#ifdef CONFIG_IPV6
		struct sockaddr_in6 sin6;
#endif /* CONFIG_IPV6 */
	} from;
	socklen_t fromlen;
	int len, res;
	struct radius_client *client = NULL;
	struct radius_msg *msg = NULL, *resp = NULL;
	char abuf[50];
	int from_port = 0;
	struct radius_hdr *hdr;
	struct wpabuf *rbuf;

	buf = os_malloc(RADIUS_MAX_MSG_LEN);
	if (buf == NULL) {
		goto fail;
	}

	fromlen = sizeof(from);
	len = recvfrom(sock, buf, RADIUS_MAX_MSG_LEN, 0,
		       (struct sockaddr *) &from.ss, &fromlen);
	if (len < 0) {
		wpa_printf(MSG_INFO, "recvfrom[radius_server]: %s",
			   strerror(errno));
		goto fail;
	}

#ifdef CONFIG_IPV6
	if (data->ipv6) {
		if (inet_ntop(AF_INET6, &from.sin6.sin6_addr, abuf,
			      sizeof(abuf)) == NULL)
			abuf[0] = '\0';
		from_port = ntohs(from.sin6.sin6_port);
		RADIUS_DEBUG("Received %d bytes from %s:%d",
			     len, abuf, from_port);

		client = radius_server_get_client(data,
						  (struct in_addr *)
						  &from.sin6.sin6_addr, 1);
	}
#endif /* CONFIG_IPV6 */

	if (!data->ipv6) {
		os_strlcpy(abuf, inet_ntoa(from.sin.sin_addr), sizeof(abuf));
		from_port = ntohs(from.sin.sin_port);
		RADIUS_DEBUG("Received %d bytes from %s:%d",
			     len, abuf, from_port);

		client = radius_server_get_client(data, &from.sin.sin_addr, 0);
	}

	RADIUS_DUMP("Received data", buf, len);

	if (client == NULL) {
		RADIUS_DEBUG("Unknown client %s - packet ignored", abuf);
		data->counters.invalid_acct_requests++;
		goto fail;
	}

	msg = radius_msg_parse(buf, len);
	if (msg == NULL) {
		RADIUS_DEBUG("Parsing incoming RADIUS frame failed");
		data->counters.malformed_acct_requests++;
		client->counters.malformed_acct_requests++;
		goto fail;
	}

	os_free(buf);
	buf = NULL;

	if (wpa_debug_level <= MSG_MSGDUMP) {
		radius_msg_dump(msg);
	}

	if (radius_msg_get_hdr(msg)->code != RADIUS_CODE_ACCOUNTING_REQUEST) {
		RADIUS_DEBUG("Unexpected RADIUS code %d",
			     radius_msg_get_hdr(msg)->code);
		data->counters.unknown_acct_types++;
		client->counters.unknown_acct_types++;
		goto fail;
	}

	data->counters.acct_requests++;
	client->counters.acct_requests++;

	if (radius_msg_verify_acct_req(msg, (u8 *) client->shared_secret,
				       client->shared_secret_len)) {
		RADIUS_DEBUG("Invalid Authenticator from %s", abuf);
		data->counters.acct_bad_authenticators++;
		client->counters.acct_bad_authenticators++;
		goto fail;
	}

	/* TODO: Write accounting information to a file or database */

	hdr = radius_msg_get_hdr(msg);

	resp = radius_msg_new(RADIUS_CODE_ACCOUNTING_RESPONSE, hdr->identifier);
	if (resp == NULL)
		goto fail;

	radius_msg_finish_acct_resp(resp, (u8 *) client->shared_secret,
				    client->shared_secret_len,
				    hdr->authenticator);

	RADIUS_DEBUG("Reply to %s:%d", abuf, from_port);
	if (wpa_debug_level <= MSG_MSGDUMP) {
		radius_msg_dump(resp);
	}
	rbuf = radius_msg_get_buf(resp);
	data->counters.acct_responses++;
	client->counters.acct_responses++;
	res = sendto(data->acct_sock, wpabuf_head(rbuf), wpabuf_len(rbuf), 0,
		     (struct sockaddr *) &from.ss, fromlen);
	if (res < 0) {
		wpa_printf(MSG_INFO, "sendto[RADIUS SRV]: %s",
			   strerror(errno));
	}

fail:
	radius_msg_free(resp);
	radius_msg_free(msg);
	os_free(buf);
}


static int radius_server_disable_pmtu_discovery(int s)
{
	int r = -1;
#if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
	/* Turn off Path MTU discovery on IPv4/UDP sockets. */
	int action = IP_PMTUDISC_DONT;
	r = setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER, &action,
		       sizeof(action));
	if (r == -1)
		wpa_printf(MSG_ERROR, "Failed to set IP_MTU_DISCOVER: "
			   "%s", strerror(errno));
#endif
	return r;
}


static int radius_server_open_socket(int port)
{
	int s;
	struct sockaddr_in addr;

	s = socket(PF_INET, SOCK_DGRAM, 0);
	if (s < 0) {
		wpa_printf(MSG_INFO, "RADIUS: socket: %s", strerror(errno));
		return -1;
	}

	radius_server_disable_pmtu_discovery(s);

	os_memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
		wpa_printf(MSG_INFO, "RADIUS: bind: %s", strerror(errno));
		close(s);
		return -1;
	}

	return s;
}


#ifdef CONFIG_IPV6
static int radius_server_open_socket6(int port)
{
	int s;
	struct sockaddr_in6 addr;

	s = socket(PF_INET6, SOCK_DGRAM, 0);
	if (s < 0) {
		wpa_printf(MSG_INFO, "RADIUS: socket[IPv6]: %s",
			   strerror(errno));
		return -1;
	}

	os_memset(&addr, 0, sizeof(addr));
	addr.sin6_family = AF_INET6;
	os_memcpy(&addr.sin6_addr, &in6addr_any, sizeof(in6addr_any));
	addr.sin6_port = htons(port);
	if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
		wpa_printf(MSG_INFO, "RADIUS: bind: %s", strerror(errno));
		close(s);
		return -1;
	}

	return s;
}
#endif /* CONFIG_IPV6 */


static void radius_server_free_sessions(struct radius_server_data *data,
					struct radius_session *sessions)
{
	struct radius_session *session, *prev;

	session = sessions;
	while (session) {
		prev = session;
		session = session->next;
		radius_server_session_free(data, prev);
	}
}


static void radius_server_free_clients(struct radius_server_data *data,
				       struct radius_client *clients)
{
	struct radius_client *client, *prev;

	client = clients;
	while (client) {
		prev = client;
		client = client->next;

		radius_server_free_sessions(data, prev->sessions);
		os_free(prev->shared_secret);
		os_free(prev);
	}
}


static struct radius_client *
radius_server_read_clients(const char *client_file, int ipv6)
{
	FILE *f;
	const int buf_size = 1024;
	char *buf, *pos;
	struct radius_client *clients, *tail, *entry;
	int line = 0, mask, failed = 0, i;
	struct in_addr addr;
#ifdef CONFIG_IPV6
	struct in6_addr addr6;
#endif /* CONFIG_IPV6 */
	unsigned int val;

	f = fopen(client_file, "r");
	if (f == NULL) {
		RADIUS_ERROR("Could not open client file '%s'", client_file);
		return NULL;
	}

	buf = os_malloc(buf_size);
	if (buf == NULL) {
		fclose(f);
		return NULL;
	}

	clients = tail = NULL;
	while (fgets(buf, buf_size, f)) {
		/* Configuration file format:
		 * 192.168.1.0/24 secret
		 * 192.168.1.2 secret
		 * fe80::211:22ff:fe33:4455/64 secretipv6
		 */
		line++;
		buf[buf_size - 1] = '\0';
		pos = buf;
		while (*pos != '\0' && *pos != '\n')
			pos++;
		if (*pos == '\n')
			*pos = '\0';
		if (*buf == '\0' || *buf == '#')
			continue;

		pos = buf;
		while ((*pos >= '0' && *pos <= '9') || *pos == '.' ||
		       (*pos >= 'a' && *pos <= 'f') || *pos == ':' ||
		       (*pos >= 'A' && *pos <= 'F')) {
			pos++;
		}

		if (*pos == '\0') {
			failed = 1;
			break;
		}

		if (*pos == '/') {
			char *end;
			*pos++ = '\0';
			mask = strtol(pos, &end, 10);
			if ((pos == end) ||
			    (mask < 0 || mask > (ipv6 ? 128 : 32))) {
				failed = 1;
				break;
			}
			pos = end;
		} else {
			mask = ipv6 ? 128 : 32;
			*pos++ = '\0';
		}

		if (!ipv6 && inet_aton(buf, &addr) == 0) {
			failed = 1;
			break;
		}
#ifdef CONFIG_IPV6
		if (ipv6 && inet_pton(AF_INET6, buf, &addr6) <= 0) {
			if (inet_pton(AF_INET, buf, &addr) <= 0) {
				failed = 1;
				break;
			}
			/* Convert IPv4 address to IPv6 */
			if (mask <= 32)
				mask += (128 - 32);
			os_memset(addr6.s6_addr, 0, 10);
			addr6.s6_addr[10] = 0xff;
			addr6.s6_addr[11] = 0xff;
			os_memcpy(addr6.s6_addr + 12, (char *) &addr.s_addr,
				  4);
		}
#endif /* CONFIG_IPV6 */

		while (*pos == ' ' || *pos == '\t') {
			pos++;
		}

		if (*pos == '\0') {
			failed = 1;
			break;
		}

		entry = os_zalloc(sizeof(*entry));
		if (entry == NULL) {
			failed = 1;
			break;
		}
		entry->shared_secret = os_strdup(pos);
		if (entry->shared_secret == NULL) {
			failed = 1;
			os_free(entry);
			break;
		}
		entry->shared_secret_len = os_strlen(entry->shared_secret);
		if (!ipv6) {
			entry->addr.s_addr = addr.s_addr;
			val = 0;
			for (i = 0; i < mask; i++)
				val |= 1 << (31 - i);
			entry->mask.s_addr = htonl(val);
		}
#ifdef CONFIG_IPV6
		if (ipv6) {
			int offset = mask / 8;

			os_memcpy(entry->addr6.s6_addr, addr6.s6_addr, 16);
			os_memset(entry->mask6.s6_addr, 0xff, offset);
			val = 0;
			for (i = 0; i < (mask % 8); i++)
				val |= 1 << (7 - i);
			if (offset < 16)
				entry->mask6.s6_addr[offset] = val;
		}
#endif /* CONFIG_IPV6 */

		if (tail == NULL) {
			clients = tail = entry;
		} else {
			tail->next = entry;
			tail = entry;
		}
	}

	if (failed) {
		RADIUS_ERROR("Invalid line %d in '%s'", line, client_file);
		radius_server_free_clients(NULL, clients);
		clients = NULL;
	}

	os_free(buf);
	fclose(f);

	return clients;
}


/**
 * radius_server_init - Initialize RADIUS server
 * @conf: Configuration for the RADIUS server
 * Returns: Pointer to private RADIUS server context or %NULL on failure
 *
 * This initializes a RADIUS server instance and returns a context pointer that
 * will be used in other calls to the RADIUS server module. The server can be
 * deinitialize by calling radius_server_deinit().
 */
struct radius_server_data *
radius_server_init(struct radius_server_conf *conf)
{
	struct radius_server_data *data;

#ifndef CONFIG_IPV6
	if (conf->ipv6) {
		wpa_printf(MSG_ERROR, "RADIUS server compiled without IPv6 support");
		return NULL;
	}
#endif /* CONFIG_IPV6 */

	data = os_zalloc(sizeof(*data));
	if (data == NULL)
		return NULL;

	dl_list_init(&data->erp_keys);
	os_get_reltime(&data->start_time);
	data->conf_ctx = conf->conf_ctx;
	data->eap_sim_db_priv = conf->eap_sim_db_priv;
	data->ssl_ctx = conf->ssl_ctx;
	data->msg_ctx = conf->msg_ctx;
	data->ipv6 = conf->ipv6;
	if (conf->pac_opaque_encr_key) {
		data->pac_opaque_encr_key = os_malloc(16);
		if (data->pac_opaque_encr_key) {
			os_memcpy(data->pac_opaque_encr_key,
				  conf->pac_opaque_encr_key, 16);
		}
	}
	if (conf->eap_fast_a_id) {
		data->eap_fast_a_id = os_malloc(conf->eap_fast_a_id_len);
		if (data->eap_fast_a_id) {
			os_memcpy(data->eap_fast_a_id, conf->eap_fast_a_id,
				  conf->eap_fast_a_id_len);
			data->eap_fast_a_id_len = conf->eap_fast_a_id_len;
		}
	}
	if (conf->eap_fast_a_id_info)
		data->eap_fast_a_id_info = os_strdup(conf->eap_fast_a_id_info);
	data->eap_fast_prov = conf->eap_fast_prov;
	data->pac_key_lifetime = conf->pac_key_lifetime;
	data->pac_key_refresh_time = conf->pac_key_refresh_time;
	data->get_eap_user = conf->get_eap_user;
	data->eap_sim_aka_result_ind = conf->eap_sim_aka_result_ind;
	data->tnc = conf->tnc;
	data->wps = conf->wps;
	data->pwd_group = conf->pwd_group;
	data->server_id = conf->server_id;
	if (conf->eap_req_id_text) {
		data->eap_req_id_text = os_malloc(conf->eap_req_id_text_len);
		if (data->eap_req_id_text) {
			os_memcpy(data->eap_req_id_text, conf->eap_req_id_text,
				  conf->eap_req_id_text_len);
			data->eap_req_id_text_len = conf->eap_req_id_text_len;
		}
	}
	data->erp = conf->erp;
	data->erp_domain = conf->erp_domain;
	data->tls_session_lifetime = conf->tls_session_lifetime;

	if (conf->subscr_remediation_url) {
		data->subscr_remediation_url =
			os_strdup(conf->subscr_remediation_url);
	}
	data->subscr_remediation_method = conf->subscr_remediation_method;

#ifdef CONFIG_SQLITE
	if (conf->sqlite_file) {
		if (sqlite3_open(conf->sqlite_file, &data->db)) {
			RADIUS_ERROR("Could not open SQLite file '%s'",
				     conf->sqlite_file);
			radius_server_deinit(data);
			return NULL;
		}
	}
#endif /* CONFIG_SQLITE */

#ifdef CONFIG_RADIUS_TEST
	if (conf->dump_msk_file)
		data->dump_msk_file = os_strdup(conf->dump_msk_file);
#endif /* CONFIG_RADIUS_TEST */

	data->clients = radius_server_read_clients(conf->client_file,
						   conf->ipv6);
	if (data->clients == NULL) {
		wpa_printf(MSG_ERROR, "No RADIUS clients configured");
		radius_server_deinit(data);
		return NULL;
	}

#ifdef CONFIG_IPV6
	if (conf->ipv6)
		data->auth_sock = radius_server_open_socket6(conf->auth_port);
	else
#endif /* CONFIG_IPV6 */
	data->auth_sock = radius_server_open_socket(conf->auth_port);
	if (data->auth_sock < 0) {
		wpa_printf(MSG_ERROR, "Failed to open UDP socket for RADIUS authentication server");
		radius_server_deinit(data);
		return NULL;
	}
	if (eloop_register_read_sock(data->auth_sock,
				     radius_server_receive_auth,
				     data, NULL)) {
		radius_server_deinit(data);
		return NULL;
	}

	if (conf->acct_port) {
#ifdef CONFIG_IPV6
		if (conf->ipv6)
			data->acct_sock = radius_server_open_socket6(
				conf->acct_port);
		else
#endif /* CONFIG_IPV6 */
		data->acct_sock = radius_server_open_socket(conf->acct_port);
		if (data->acct_sock < 0) {
			wpa_printf(MSG_ERROR, "Failed to open UDP socket for RADIUS accounting server");
			radius_server_deinit(data);
			return NULL;
		}
		if (eloop_register_read_sock(data->acct_sock,
					     radius_server_receive_acct,
					     data, NULL)) {
			radius_server_deinit(data);
			return NULL;
		}
	} else {
		data->acct_sock = -1;
	}

	return data;
}


/**
 * radius_server_erp_flush - Flush all ERP keys
 * @data: RADIUS server context from radius_server_init()
 */
void radius_server_erp_flush(struct radius_server_data *data)
{
	struct eap_server_erp_key *erp;

	if (data == NULL)
		return;
	while ((erp = dl_list_first(&data->erp_keys, struct eap_server_erp_key,
				    list)) != NULL) {
		dl_list_del(&erp->list);
		bin_clear_free(erp, sizeof(*erp));
	}
}


/**
 * radius_server_deinit - Deinitialize RADIUS server
 * @data: RADIUS server context from radius_server_init()
 */
void radius_server_deinit(struct radius_server_data *data)
{
	if (data == NULL)
		return;

	if (data->auth_sock >= 0) {
		eloop_unregister_read_sock(data->auth_sock);
		close(data->auth_sock);
	}

	if (data->acct_sock >= 0) {
		eloop_unregister_read_sock(data->acct_sock);
		close(data->acct_sock);
	}

	radius_server_free_clients(data, data->clients);

	os_free(data->pac_opaque_encr_key);
	os_free(data->eap_fast_a_id);
	os_free(data->eap_fast_a_id_info);
	os_free(data->eap_req_id_text);
#ifdef CONFIG_RADIUS_TEST
	os_free(data->dump_msk_file);
#endif /* CONFIG_RADIUS_TEST */
	os_free(data->subscr_remediation_url);

#ifdef CONFIG_SQLITE
	if (data->db)
		sqlite3_close(data->db);
#endif /* CONFIG_SQLITE */

	radius_server_erp_flush(data);

	os_free(data);
}


/**
 * radius_server_get_mib - Get RADIUS server MIB information
 * @data: RADIUS server context from radius_server_init()
 * @buf: Buffer for returning the MIB data in text format
 * @buflen: buf length in octets
 * Returns: Number of octets written into buf
 */
int radius_server_get_mib(struct radius_server_data *data, char *buf,
			  size_t buflen)
{
	int ret, uptime;
	unsigned int idx;
	char *end, *pos;
	struct os_reltime now;
	struct radius_client *cli;

	/* RFC 2619 - RADIUS Authentication Server MIB */

	if (data == NULL || buflen == 0)
		return 0;

	pos = buf;
	end = buf + buflen;

	os_get_reltime(&now);
	uptime = (now.sec - data->start_time.sec) * 100 +
		((now.usec - data->start_time.usec) / 10000) % 100;
	ret = os_snprintf(pos, end - pos,
			  "RADIUS-AUTH-SERVER-MIB\n"
			  "radiusAuthServIdent=hostapd\n"
			  "radiusAuthServUpTime=%d\n"
			  "radiusAuthServResetTime=0\n"
			  "radiusAuthServConfigReset=4\n",
			  uptime);
	if (os_snprintf_error(end - pos, ret)) {
		*pos = '\0';
		return pos - buf;
	}
	pos += ret;

	ret = os_snprintf(pos, end - pos,
			  "radiusAuthServTotalAccessRequests=%u\n"
			  "radiusAuthServTotalInvalidRequests=%u\n"
			  "radiusAuthServTotalDupAccessRequests=%u\n"
			  "radiusAuthServTotalAccessAccepts=%u\n"
			  "radiusAuthServTotalAccessRejects=%u\n"
			  "radiusAuthServTotalAccessChallenges=%u\n"
			  "radiusAuthServTotalMalformedAccessRequests=%u\n"
			  "radiusAuthServTotalBadAuthenticators=%u\n"
			  "radiusAuthServTotalPacketsDropped=%u\n"
			  "radiusAuthServTotalUnknownTypes=%u\n"
			  "radiusAccServTotalRequests=%u\n"
			  "radiusAccServTotalInvalidRequests=%u\n"
			  "radiusAccServTotalResponses=%u\n"
			  "radiusAccServTotalMalformedRequests=%u\n"
			  "radiusAccServTotalBadAuthenticators=%u\n"
			  "radiusAccServTotalUnknownTypes=%u\n",
			  data->counters.access_requests,
			  data->counters.invalid_requests,
			  data->counters.dup_access_requests,
			  data->counters.access_accepts,
			  data->counters.access_rejects,
			  data->counters.access_challenges,
			  data->counters.malformed_access_requests,
			  data->counters.bad_authenticators,
			  data->counters.packets_dropped,
			  data->counters.unknown_types,
			  data->counters.acct_requests,
			  data->counters.invalid_acct_requests,
			  data->counters.acct_responses,
			  data->counters.malformed_acct_requests,
			  data->counters.acct_bad_authenticators,
			  data->counters.unknown_acct_types);
	if (os_snprintf_error(end - pos, ret)) {
		*pos = '\0';
		return pos - buf;
	}
	pos += ret;

	for (cli = data->clients, idx = 0; cli; cli = cli->next, idx++) {
		char abuf[50], mbuf[50];
#ifdef CONFIG_IPV6
		if (data->ipv6) {
			if (inet_ntop(AF_INET6, &cli->addr6, abuf,
				      sizeof(abuf)) == NULL)
				abuf[0] = '\0';
			if (inet_ntop(AF_INET6, &cli->mask6, mbuf,
				      sizeof(mbuf)) == NULL)
				mbuf[0] = '\0';
		}
#endif /* CONFIG_IPV6 */
		if (!data->ipv6) {
			os_strlcpy(abuf, inet_ntoa(cli->addr), sizeof(abuf));
			os_strlcpy(mbuf, inet_ntoa(cli->mask), sizeof(mbuf));
		}

		ret = os_snprintf(pos, end - pos,
				  "radiusAuthClientIndex=%u\n"
				  "radiusAuthClientAddress=%s/%s\n"
				  "radiusAuthServAccessRequests=%u\n"
				  "radiusAuthServDupAccessRequests=%u\n"
				  "radiusAuthServAccessAccepts=%u\n"
				  "radiusAuthServAccessRejects=%u\n"
				  "radiusAuthServAccessChallenges=%u\n"
				  "radiusAuthServMalformedAccessRequests=%u\n"
				  "radiusAuthServBadAuthenticators=%u\n"
				  "radiusAuthServPacketsDropped=%u\n"
				  "radiusAuthServUnknownTypes=%u\n"
				  "radiusAccServTotalRequests=%u\n"
				  "radiusAccServTotalInvalidRequests=%u\n"
				  "radiusAccServTotalResponses=%u\n"
				  "radiusAccServTotalMalformedRequests=%u\n"
				  "radiusAccServTotalBadAuthenticators=%u\n"
				  "radiusAccServTotalUnknownTypes=%u\n",
				  idx,
				  abuf, mbuf,
				  cli->counters.access_requests,
				  cli->counters.dup_access_requests,
				  cli->counters.access_accepts,
				  cli->counters.access_rejects,
				  cli->counters.access_challenges,
				  cli->counters.malformed_access_requests,
				  cli->counters.bad_authenticators,
				  cli->counters.packets_dropped,
				  cli->counters.unknown_types,
				  cli->counters.acct_requests,
				  cli->counters.invalid_acct_requests,
				  cli->counters.acct_responses,
				  cli->counters.malformed_acct_requests,
				  cli->counters.acct_bad_authenticators,
				  cli->counters.unknown_acct_types);
		if (os_snprintf_error(end - pos, ret)) {
			*pos = '\0';
			return pos - buf;
		}
		pos += ret;
	}

	return pos - buf;
}


static int radius_server_get_eap_user(void *ctx, const u8 *identity,
				      size_t identity_len, int phase2,
				      struct eap_user *user)
{
	struct radius_session *sess = ctx;
	struct radius_server_data *data = sess->server;
	int ret;

	ret = data->get_eap_user(data->conf_ctx, identity, identity_len,
				 phase2, user);
	if (ret == 0 && user) {
		sess->accept_attr = user->accept_attr;
		sess->remediation = user->remediation;
		sess->macacl = user->macacl;
	}

	if (ret) {
		RADIUS_DEBUG("%s: User-Name not found from user database",
			     __func__);
	}

	return ret;
}


static const char * radius_server_get_eap_req_id_text(void *ctx, size_t *len)
{
	struct radius_session *sess = ctx;
	struct radius_server_data *data = sess->server;
	*len = data->eap_req_id_text_len;
	return data->eap_req_id_text;
}


static void radius_server_log_msg(void *ctx, const char *msg)
{
	struct radius_session *sess = ctx;
	srv_log(sess, "EAP: %s", msg);
}


#ifdef CONFIG_ERP

static const char * radius_server_get_erp_domain(void *ctx)
{
	struct radius_session *sess = ctx;
	struct radius_server_data *data = sess->server;

	return data->erp_domain;
}


static struct eap_server_erp_key *
radius_server_erp_get_key(void *ctx, const char *keyname)
{
	struct radius_session *sess = ctx;
	struct radius_server_data *data = sess->server;
	struct eap_server_erp_key *erp;

	dl_list_for_each(erp, &data->erp_keys, struct eap_server_erp_key,
			 list) {
		if (os_strcmp(erp->keyname_nai, keyname) == 0)
			return erp;
	}

	return NULL;
}


static int radius_server_erp_add_key(void *ctx, struct eap_server_erp_key *erp)
{
	struct radius_session *sess = ctx;
	struct radius_server_data *data = sess->server;

	dl_list_add(&data->erp_keys, &erp->list);
	return 0;
}

#endif /* CONFIG_ERP */


static const struct eapol_callbacks radius_server_eapol_cb =
{
	.get_eap_user = radius_server_get_eap_user,
	.get_eap_req_id_text = radius_server_get_eap_req_id_text,
	.log_msg = radius_server_log_msg,
#ifdef CONFIG_ERP
	.get_erp_send_reauth_start = NULL,
	.get_erp_domain = radius_server_get_erp_domain,
	.erp_get_key = radius_server_erp_get_key,
	.erp_add_key = radius_server_erp_add_key,
#endif /* CONFIG_ERP */
};


/**
 * radius_server_eap_pending_cb - Pending EAP data notification
 * @data: RADIUS server context from radius_server_init()
 * @ctx: Pending EAP context pointer
 *
 * This function is used to notify EAP server module that a pending operation
 * has been completed and processing of the EAP session can proceed.
 */
void radius_server_eap_pending_cb(struct radius_server_data *data, void *ctx)
{
	struct radius_client *cli;
	struct radius_session *s, *sess = NULL;
	struct radius_msg *msg;

	if (data == NULL)
		return;

	for (cli = data->clients; cli; cli = cli->next) {
		for (s = cli->sessions; s; s = s->next) {
			if (s->eap == ctx && s->last_msg) {
				sess = s;
				break;
			}
		}
		if (sess)
			break;
	}

	if (sess == NULL) {
		RADIUS_DEBUG("No session matched callback ctx");
		return;
	}

	msg = sess->last_msg;
	sess->last_msg = NULL;
	eap_sm_pending_cb(sess->eap);
	if (radius_server_request(data, msg,
				  (struct sockaddr *) &sess->last_from,
				  sess->last_fromlen, cli,
				  sess->last_from_addr,
				  sess->last_from_port, sess) == -2)
		return; /* msg was stored with the session */

	radius_msg_free(msg);
}
OpenPOWER on IntegriCloud