test_radius.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. # RADIUS tests
  2. # Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi>
  3. #
  4. # This software may be distributed under the terms of the BSD license.
  5. # See README for more details.
  6. import hmac
  7. import logging
  8. logger = logging.getLogger()
  9. import select
  10. import struct
  11. import subprocess
  12. import threading
  13. import time
  14. import hostapd
  15. def connect(dev, ssid, wait_connect=True):
  16. dev.connect(ssid, key_mgmt="WPA-EAP", scan_freq="2412",
  17. eap="PSK", identity="psk.user@example.com",
  18. password_hex="0123456789abcdef0123456789abcdef",
  19. wait_connect=wait_connect)
  20. def test_radius_auth_unreachable(dev, apdev):
  21. """RADIUS Authentication server unreachable"""
  22. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  23. params['auth_server_port'] = "18139"
  24. hostapd.add_ap(apdev[0]['ifname'], params)
  25. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  26. connect(dev[0], "radius-auth", wait_connect=False)
  27. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
  28. if ev is None:
  29. raise Exception("Timeout on EAP start")
  30. logger.info("Checking for RADIUS retries")
  31. time.sleep(4)
  32. mib = hapd.get_mib()
  33. if "radiusAuthClientAccessRequests" not in mib:
  34. raise Exception("Missing MIB fields")
  35. if int(mib["radiusAuthClientAccessRetransmissions"]) < 1:
  36. raise Exception("Missing RADIUS Authentication retransmission")
  37. if int(mib["radiusAuthClientPendingRequests"]) < 1:
  38. raise Exception("Missing pending RADIUS Authentication request")
  39. def test_radius_auth_unreachable2(dev, apdev):
  40. """RADIUS Authentication server unreachable (2)"""
  41. subprocess.call(['sudo', 'ip', 'ro', 'replace', '192.168.213.17', 'dev',
  42. 'lo'])
  43. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  44. params['auth_server_addr'] = "192.168.213.17"
  45. params['auth_server_port'] = "18139"
  46. hostapd.add_ap(apdev[0]['ifname'], params)
  47. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  48. subprocess.call(['sudo', 'ip', 'ro', 'del', '192.168.213.17', 'dev', 'lo'])
  49. connect(dev[0], "radius-auth", wait_connect=False)
  50. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
  51. if ev is None:
  52. raise Exception("Timeout on EAP start")
  53. logger.info("Checking for RADIUS retries")
  54. time.sleep(4)
  55. mib = hapd.get_mib()
  56. if "radiusAuthClientAccessRequests" not in mib:
  57. raise Exception("Missing MIB fields")
  58. if int(mib["radiusAuthClientAccessRetransmissions"]) < 1:
  59. raise Exception("Missing RADIUS Authentication retransmission")
  60. def test_radius_acct_unreachable(dev, apdev):
  61. """RADIUS Accounting server unreachable"""
  62. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  63. params['acct_server_addr'] = "127.0.0.1"
  64. params['acct_server_port'] = "18139"
  65. params['acct_server_shared_secret'] = "radius"
  66. hostapd.add_ap(apdev[0]['ifname'], params)
  67. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  68. connect(dev[0], "radius-acct")
  69. logger.info("Checking for RADIUS retries")
  70. time.sleep(4)
  71. mib = hapd.get_mib()
  72. if "radiusAccClientRetransmissions" not in mib:
  73. raise Exception("Missing MIB fields")
  74. if int(mib["radiusAccClientRetransmissions"]) < 2:
  75. raise Exception("Missing RADIUS Accounting retransmissions")
  76. if int(mib["radiusAccClientPendingRequests"]) < 2:
  77. raise Exception("Missing pending RADIUS Accounting requests")
  78. def test_radius_acct_unreachable2(dev, apdev):
  79. """RADIUS Accounting server unreachable(2)"""
  80. subprocess.call(['sudo', 'ip', 'ro', 'replace', '192.168.213.17', 'dev',
  81. 'lo'])
  82. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  83. params['acct_server_addr'] = "192.168.213.17"
  84. params['acct_server_port'] = "18139"
  85. params['acct_server_shared_secret'] = "radius"
  86. hostapd.add_ap(apdev[0]['ifname'], params)
  87. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  88. subprocess.call(['sudo', 'ip', 'ro', 'del', '192.168.213.17', 'dev', 'lo'])
  89. connect(dev[0], "radius-acct")
  90. logger.info("Checking for RADIUS retries")
  91. time.sleep(4)
  92. mib = hapd.get_mib()
  93. if "radiusAccClientRetransmissions" not in mib:
  94. raise Exception("Missing MIB fields")
  95. if int(mib["radiusAccClientRetransmissions"]) < 1 and int(mib["radiusAccClientPendingRequests"]) < 1:
  96. raise Exception("Missing pending or retransmitted RADIUS Accounting requests")
  97. def test_radius_acct(dev, apdev):
  98. """RADIUS Accounting"""
  99. as_hapd = hostapd.Hostapd("as")
  100. as_mib_start = as_hapd.get_mib(param="radius_server")
  101. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  102. params['acct_server_addr'] = "127.0.0.1"
  103. params['acct_server_port'] = "1813"
  104. params['acct_server_shared_secret'] = "radius"
  105. params['radius_auth_req_attr'] = [ "126:s:Operator", "77:s:testing" ]
  106. params['radius_acct_req_attr'] = [ "126:s:Operator", "77:s:testing" ]
  107. hostapd.add_ap(apdev[0]['ifname'], params)
  108. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  109. connect(dev[0], "radius-acct")
  110. dev[1].connect("radius-acct", key_mgmt="WPA-EAP", scan_freq="2412",
  111. eap="PAX", identity="test-class",
  112. password_hex="0123456789abcdef0123456789abcdef")
  113. dev[2].connect("radius-acct", key_mgmt="WPA-EAP",
  114. eap="GPSK", identity="gpsk-cui",
  115. password="abcdefghijklmnop0123456789abcdef",
  116. scan_freq="2412")
  117. logger.info("Checking for RADIUS counters")
  118. count = 0
  119. while True:
  120. mib = hapd.get_mib()
  121. if int(mib['radiusAccClientResponses']) >= 3:
  122. break
  123. time.sleep(0.1)
  124. count += 1
  125. if count > 10:
  126. raise Exception("Did not receive Accounting-Response packets")
  127. if int(mib['radiusAccClientRetransmissions']) > 0:
  128. raise Exception("Unexpected Accounting-Request retransmission")
  129. as_mib_end = as_hapd.get_mib(param="radius_server")
  130. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  131. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  132. if req_e < req_s + 2:
  133. raise Exception("Unexpected RADIUS server acct MIB value")
  134. acc_s = int(as_mib_start['radiusAuthServAccessAccepts'])
  135. acc_e = int(as_mib_end['radiusAuthServAccessAccepts'])
  136. if acc_e < acc_s + 1:
  137. raise Exception("Unexpected RADIUS server auth MIB value")
  138. def test_radius_acct_pmksa_caching(dev, apdev):
  139. """RADIUS Accounting with PMKSA caching"""
  140. as_hapd = hostapd.Hostapd("as")
  141. as_mib_start = as_hapd.get_mib(param="radius_server")
  142. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  143. params['acct_server_addr'] = "127.0.0.1"
  144. params['acct_server_port'] = "1813"
  145. params['acct_server_shared_secret'] = "radius"
  146. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  147. connect(dev[0], "radius-acct")
  148. dev[1].connect("radius-acct", key_mgmt="WPA-EAP", scan_freq="2412",
  149. eap="PAX", identity="test-class",
  150. password_hex="0123456789abcdef0123456789abcdef")
  151. for d in [ dev[0], dev[1] ]:
  152. d.request("REASSOCIATE")
  153. ev = d.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  154. if ev is None:
  155. raise Exception("Reassociation timed out")
  156. count = 0
  157. while True:
  158. mib = hapd.get_mib()
  159. if int(mib['radiusAccClientResponses']) >= 4:
  160. break
  161. time.sleep(0.1)
  162. count += 1
  163. if count > 10:
  164. raise Exception("Did not receive Accounting-Response packets")
  165. if int(mib['radiusAccClientRetransmissions']) > 0:
  166. raise Exception("Unexpected Accounting-Request retransmission")
  167. as_mib_end = as_hapd.get_mib(param="radius_server")
  168. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  169. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  170. if req_e < req_s + 2:
  171. raise Exception("Unexpected RADIUS server acct MIB value")
  172. acc_s = int(as_mib_start['radiusAuthServAccessAccepts'])
  173. acc_e = int(as_mib_end['radiusAuthServAccessAccepts'])
  174. if acc_e < acc_s + 1:
  175. raise Exception("Unexpected RADIUS server auth MIB value")
  176. def test_radius_acct_interim(dev, apdev):
  177. """RADIUS Accounting interim update"""
  178. as_hapd = hostapd.Hostapd("as")
  179. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  180. params['acct_server_addr'] = "127.0.0.1"
  181. params['acct_server_port'] = "1813"
  182. params['acct_server_shared_secret'] = "radius"
  183. params['radius_acct_interim_interval'] = "1"
  184. hostapd.add_ap(apdev[0]['ifname'], params)
  185. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  186. connect(dev[0], "radius-acct")
  187. logger.info("Checking for RADIUS counters")
  188. as_mib_start = as_hapd.get_mib(param="radius_server")
  189. time.sleep(3.1)
  190. as_mib_end = as_hapd.get_mib(param="radius_server")
  191. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  192. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  193. if req_e < req_s + 3:
  194. raise Exception("Unexpected RADIUS server acct MIB value")
  195. def test_radius_acct_interim_unreachable(dev, apdev):
  196. """RADIUS Accounting interim update with unreachable server"""
  197. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  198. params['acct_server_addr'] = "127.0.0.1"
  199. params['acct_server_port'] = "18139"
  200. params['acct_server_shared_secret'] = "radius"
  201. params['radius_acct_interim_interval'] = "1"
  202. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  203. start = hapd.get_mib()
  204. connect(dev[0], "radius-acct")
  205. logger.info("Waiting for interium accounting updates")
  206. time.sleep(3.1)
  207. end = hapd.get_mib()
  208. req_s = int(start['radiusAccClientTimeouts'])
  209. req_e = int(end['radiusAccClientTimeouts'])
  210. if req_e < req_s + 2:
  211. raise Exception("Unexpected RADIUS server acct MIB value")
  212. def test_radius_das_disconnect(dev, apdev):
  213. """RADIUS Dynamic Authorization Extensions - Disconnect"""
  214. try:
  215. import pyrad.client
  216. import pyrad.packet
  217. import pyrad.dictionary
  218. import radius_das
  219. except ImportError:
  220. return "skip"
  221. params = hostapd.wpa2_eap_params(ssid="radius-das")
  222. params['radius_das_port'] = "3799"
  223. params['radius_das_client'] = "127.0.0.1 secret"
  224. params['radius_das_require_event_timestamp'] = "1"
  225. params['own_ip_addr'] = "127.0.0.1"
  226. params['nas_identifier'] = "nas.example.com"
  227. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  228. connect(dev[0], "radius-das")
  229. addr = dev[0].p2p_interface_addr()
  230. sta = hapd.get_sta(addr)
  231. id = sta['dot1xAuthSessionId']
  232. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  233. srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
  234. secret="secret", dict=dict)
  235. srv.retries = 1
  236. srv.timeout = 1
  237. logger.info("Disconnect-Request with incorrect secret")
  238. req = radius_das.DisconnectPacket(dict=dict, secret="incorrect",
  239. User_Name="foo",
  240. NAS_Identifier="localhost",
  241. Event_Timestamp=int(time.time()))
  242. logger.debug(req)
  243. try:
  244. reply = srv.SendPacket(req)
  245. raise Exception("Unexpected response to Disconnect-Request")
  246. except pyrad.client.Timeout:
  247. logger.info("Disconnect-Request with incorrect secret properly ignored")
  248. logger.info("Disconnect-Request without Event-Timestamp")
  249. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  250. User_Name="psk.user@example.com")
  251. logger.debug(req)
  252. try:
  253. reply = srv.SendPacket(req)
  254. raise Exception("Unexpected response to Disconnect-Request")
  255. except pyrad.client.Timeout:
  256. logger.info("Disconnect-Request without Event-Timestamp properly ignored")
  257. logger.info("Disconnect-Request with non-matching Event-Timestamp")
  258. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  259. User_Name="psk.user@example.com",
  260. Event_Timestamp=123456789)
  261. logger.debug(req)
  262. try:
  263. reply = srv.SendPacket(req)
  264. raise Exception("Unexpected response to Disconnect-Request")
  265. except pyrad.client.Timeout:
  266. logger.info("Disconnect-Request with non-matching Event-Timestamp properly ignored")
  267. logger.info("Disconnect-Request with unsupported attribute")
  268. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  269. User_Name="foo",
  270. User_Password="foo",
  271. Event_Timestamp=int(time.time()))
  272. reply = srv.SendPacket(req)
  273. logger.debug("RADIUS response from hostapd")
  274. for i in reply.keys():
  275. logger.debug("%s: %s" % (i, reply[i]))
  276. if reply.code != pyrad.packet.DisconnectNAK:
  277. raise Exception("Unexpected response code")
  278. if 'Error-Cause' not in reply:
  279. raise Exception("Missing Error-Cause")
  280. if reply['Error-Cause'][0] != 401:
  281. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  282. logger.info("Disconnect-Request with invalid Calling-Station-Id")
  283. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  284. User_Name="foo",
  285. Calling_Station_Id="foo",
  286. Event_Timestamp=int(time.time()))
  287. reply = srv.SendPacket(req)
  288. logger.debug("RADIUS response from hostapd")
  289. for i in reply.keys():
  290. logger.debug("%s: %s" % (i, reply[i]))
  291. if reply.code != pyrad.packet.DisconnectNAK:
  292. raise Exception("Unexpected response code")
  293. if 'Error-Cause' not in reply:
  294. raise Exception("Missing Error-Cause")
  295. if reply['Error-Cause'][0] != 407:
  296. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  297. logger.info("Disconnect-Request with mismatching User-Name")
  298. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  299. User_Name="foo",
  300. Event_Timestamp=int(time.time()))
  301. reply = srv.SendPacket(req)
  302. logger.debug("RADIUS response from hostapd")
  303. for i in reply.keys():
  304. logger.debug("%s: %s" % (i, reply[i]))
  305. if reply.code != pyrad.packet.DisconnectNAK:
  306. raise Exception("Unexpected response code")
  307. if 'Error-Cause' not in reply:
  308. raise Exception("Missing Error-Cause")
  309. if reply['Error-Cause'][0] != 503:
  310. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  311. logger.info("Disconnect-Request with mismatching Calling-Station-Id")
  312. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  313. Calling_Station_Id="12:34:56:78:90:aa",
  314. Event_Timestamp=int(time.time()))
  315. reply = srv.SendPacket(req)
  316. logger.debug("RADIUS response from hostapd")
  317. for i in reply.keys():
  318. logger.debug("%s: %s" % (i, reply[i]))
  319. if reply.code != pyrad.packet.DisconnectNAK:
  320. raise Exception("Unexpected response code")
  321. if 'Error-Cause' not in reply:
  322. raise Exception("Missing Error-Cause")
  323. if reply['Error-Cause'][0] != 503:
  324. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  325. logger.info("Disconnect-Request with mismatching Acct-Session-Id")
  326. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  327. Acct_Session_Id="12345678-87654321",
  328. Event_Timestamp=int(time.time()))
  329. reply = srv.SendPacket(req)
  330. logger.debug("RADIUS response from hostapd")
  331. for i in reply.keys():
  332. logger.debug("%s: %s" % (i, reply[i]))
  333. if reply.code != pyrad.packet.DisconnectNAK:
  334. raise Exception("Unexpected response code")
  335. if 'Error-Cause' not in reply:
  336. raise Exception("Missing Error-Cause")
  337. if reply['Error-Cause'][0] != 503:
  338. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  339. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  340. if ev is not None:
  341. raise Exception("Unexpected disconnection")
  342. logger.info("Disconnect-Request with mismatching NAS-IP-Address")
  343. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  344. NAS_IP_Address="192.168.3.4",
  345. Acct_Session_Id=id,
  346. Event_Timestamp=int(time.time()))
  347. reply = srv.SendPacket(req)
  348. logger.debug("RADIUS response from hostapd")
  349. for i in reply.keys():
  350. logger.debug("%s: %s" % (i, reply[i]))
  351. if reply.code != pyrad.packet.DisconnectNAK:
  352. raise Exception("Unexpected response code")
  353. if 'Error-Cause' not in reply:
  354. raise Exception("Missing Error-Cause")
  355. if reply['Error-Cause'][0] != 403:
  356. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  357. logger.info("Disconnect-Request with mismatching NAS-Identifier")
  358. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  359. NAS_Identifier="unknown.example.com",
  360. Acct_Session_Id=id,
  361. Event_Timestamp=int(time.time()))
  362. reply = srv.SendPacket(req)
  363. logger.debug("RADIUS response from hostapd")
  364. for i in reply.keys():
  365. logger.debug("%s: %s" % (i, reply[i]))
  366. if reply.code != pyrad.packet.DisconnectNAK:
  367. raise Exception("Unexpected response code")
  368. if 'Error-Cause' not in reply:
  369. raise Exception("Missing Error-Cause")
  370. if reply['Error-Cause'][0] != 403:
  371. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  372. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  373. if ev is not None:
  374. raise Exception("Unexpected disconnection")
  375. logger.info("Disconnect-Request with matching Acct-Session-Id")
  376. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  377. NAS_IP_Address="127.0.0.1",
  378. NAS_Identifier="nas.example.com",
  379. Acct_Session_Id=id,
  380. Event_Timestamp=int(time.time()))
  381. reply = srv.SendPacket(req)
  382. logger.debug("RADIUS response from hostapd")
  383. for i in reply.keys():
  384. logger.debug("%s: %s" % (i, reply[i]))
  385. if reply.code != pyrad.packet.DisconnectACK:
  386. raise Exception("Unexpected response code")
  387. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
  388. if ev is None:
  389. raise Exception("Timeout while waiting for disconnection")
  390. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"])
  391. if ev is None:
  392. raise Exception("Timeout while waiting for re-connection")
  393. logger.info("Disconnect-Request with matching User-Name")
  394. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  395. NAS_Identifier="nas.example.com",
  396. User_Name="psk.user@example.com",
  397. Event_Timestamp=int(time.time()))
  398. reply = srv.SendPacket(req)
  399. logger.debug("RADIUS response from hostapd")
  400. for i in reply.keys():
  401. logger.debug("%s: %s" % (i, reply[i]))
  402. if reply.code != pyrad.packet.DisconnectACK:
  403. raise Exception("Unexpected response code")
  404. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
  405. if ev is None:
  406. raise Exception("Timeout while waiting for disconnection")
  407. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"])
  408. if ev is None:
  409. raise Exception("Timeout while waiting for re-connection")
  410. logger.info("Disconnect-Request with matching Calling-Station-Id")
  411. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  412. NAS_IP_Address="127.0.0.1",
  413. Calling_Station_Id=addr,
  414. Event_Timestamp=int(time.time()))
  415. reply = srv.SendPacket(req)
  416. logger.debug("RADIUS response from hostapd")
  417. for i in reply.keys():
  418. logger.debug("%s: %s" % (i, reply[i]))
  419. if reply.code != pyrad.packet.DisconnectACK:
  420. raise Exception("Unexpected response code")
  421. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
  422. if ev is None:
  423. raise Exception("Timeout while waiting for disconnection")
  424. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", "CTRL-EVENT-CONNECTED"])
  425. if ev is None:
  426. raise Exception("Timeout while waiting for re-connection")
  427. if "CTRL-EVENT-EAP-STARTED" not in ev:
  428. raise Exception("Unexpected skipping of EAP authentication in reconnection")
  429. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"])
  430. if ev is None:
  431. raise Exception("Timeout while waiting for re-connection to complete")
  432. logger.info("Disconnect-Request with matching Calling-Station-Id and non-matching CUI")
  433. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  434. Calling_Station_Id=addr,
  435. Chargeable_User_Identity="foo@example.com",
  436. Event_Timestamp=int(time.time()))
  437. reply = srv.SendPacket(req)
  438. logger.debug("RADIUS response from hostapd")
  439. for i in reply.keys():
  440. logger.debug("%s: %s" % (i, reply[i]))
  441. if reply.code != pyrad.packet.DisconnectACK:
  442. raise Exception("Unexpected response code")
  443. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
  444. if ev is None:
  445. raise Exception("Timeout while waiting for disconnection")
  446. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"])
  447. if ev is None:
  448. raise Exception("Timeout while waiting for re-connection")
  449. logger.info("Disconnect-Request with matching CUI")
  450. dev[1].connect("radius-das", key_mgmt="WPA-EAP",
  451. eap="GPSK", identity="gpsk-cui",
  452. password="abcdefghijklmnop0123456789abcdef",
  453. scan_freq="2412")
  454. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  455. Chargeable_User_Identity="gpsk-chargeable-user-identity",
  456. Event_Timestamp=int(time.time()))
  457. reply = srv.SendPacket(req)
  458. logger.debug("RADIUS response from hostapd")
  459. for i in reply.keys():
  460. logger.debug("%s: %s" % (i, reply[i]))
  461. if reply.code != pyrad.packet.DisconnectACK:
  462. raise Exception("Unexpected response code")
  463. ev = dev[1].wait_event(["CTRL-EVENT-DISCONNECTED"])
  464. if ev is None:
  465. raise Exception("Timeout while waiting for disconnection")
  466. ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"])
  467. if ev is None:
  468. raise Exception("Timeout while waiting for re-connection")
  469. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  470. if ev is not None:
  471. raise Exception("Unexpected disconnection")
  472. def test_radius_das_coa(dev, apdev):
  473. """RADIUS Dynamic Authorization Extensions - CoA"""
  474. try:
  475. import pyrad.client
  476. import pyrad.packet
  477. import pyrad.dictionary
  478. import radius_das
  479. except ImportError:
  480. return "skip"
  481. params = hostapd.wpa2_eap_params(ssid="radius-das")
  482. params['radius_das_port'] = "3799"
  483. params['radius_das_client'] = "127.0.0.1 secret"
  484. params['radius_das_require_event_timestamp'] = "1"
  485. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  486. connect(dev[0], "radius-das")
  487. addr = dev[0].p2p_interface_addr()
  488. sta = hapd.get_sta(addr)
  489. id = sta['dot1xAuthSessionId']
  490. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  491. srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
  492. secret="secret", dict=dict)
  493. srv.retries = 1
  494. srv.timeout = 1
  495. # hostapd does not currently support CoA-Request, so NAK is expected
  496. logger.info("CoA-Request with matching Acct-Session-Id")
  497. req = radius_das.CoAPacket(dict=dict, secret="secret",
  498. Acct_Session_Id=id,
  499. Event_Timestamp=int(time.time()))
  500. reply = srv.SendPacket(req)
  501. logger.debug("RADIUS response from hostapd")
  502. for i in reply.keys():
  503. logger.debug("%s: %s" % (i, reply[i]))
  504. if reply.code != pyrad.packet.CoANAK:
  505. raise Exception("Unexpected response code")
  506. if 'Error-Cause' not in reply:
  507. raise Exception("Missing Error-Cause")
  508. if reply['Error-Cause'][0] != 405:
  509. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  510. def test_radius_ipv6(dev, apdev):
  511. """RADIUS connection over IPv6"""
  512. params = {}
  513. params['ssid'] = 'as'
  514. params['beacon_int'] = '2000'
  515. params['radius_server_clients'] = 'auth_serv/radius_clients_ipv6.conf'
  516. params['radius_server_ipv6'] = '1'
  517. params['radius_server_auth_port'] = '18129'
  518. params['radius_server_acct_port'] = '18139'
  519. params['eap_server'] = '1'
  520. params['eap_user_file'] = 'auth_serv/eap_user.conf'
  521. params['ca_cert'] = 'auth_serv/ca.pem'
  522. params['server_cert'] = 'auth_serv/server.pem'
  523. params['private_key'] = 'auth_serv/server.key'
  524. hostapd.add_ap(apdev[1]['ifname'], params)
  525. params = hostapd.wpa2_eap_params(ssid="radius-ipv6")
  526. params['auth_server_addr'] = "::0"
  527. params['auth_server_port'] = "18129"
  528. params['acct_server_addr'] = "::0"
  529. params['acct_server_port'] = "18139"
  530. params['acct_server_shared_secret'] = "radius"
  531. params['own_ip_addr'] = "::0"
  532. hostapd.add_ap(apdev[0]['ifname'], params)
  533. connect(dev[0], "radius-ipv6")
  534. def test_radius_macacl(dev, apdev):
  535. """RADIUS MAC ACL"""
  536. params = hostapd.radius_params()
  537. params["ssid"] = "radius"
  538. params["macaddr_acl"] = "2"
  539. hostapd.add_ap(apdev[0]['ifname'], params)
  540. dev[0].connect("radius", key_mgmt="NONE", scan_freq="2412")
  541. def test_radius_failover(dev, apdev):
  542. """RADIUS Authentication and Accounting server failover"""
  543. subprocess.call(['sudo', 'ip', 'ro', 'replace', '192.168.213.17', 'dev',
  544. 'lo'])
  545. as_hapd = hostapd.Hostapd("as")
  546. as_mib_start = as_hapd.get_mib(param="radius_server")
  547. params = hostapd.wpa2_eap_params(ssid="radius-failover")
  548. params["auth_server_addr"] = "192.168.213.17"
  549. params["auth_server_port"] = "1812"
  550. params["auth_server_shared_secret"] = "testing"
  551. params['acct_server_addr'] = "192.168.213.17"
  552. params['acct_server_port'] = "1813"
  553. params['acct_server_shared_secret'] = "testing"
  554. hapd = hostapd.add_ap(apdev[0]['ifname'], params, no_enable=True)
  555. hapd.set("auth_server_addr", "127.0.0.1")
  556. hapd.set("auth_server_port", "1812")
  557. hapd.set("auth_server_shared_secret", "radius")
  558. hapd.set('acct_server_addr', "127.0.0.1")
  559. hapd.set('acct_server_port', "1813")
  560. hapd.set('acct_server_shared_secret', "radius")
  561. hapd.enable()
  562. ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=30)
  563. if ev is None:
  564. raise Exception("AP startup timed out")
  565. if "AP-ENABLED" not in ev:
  566. raise Exception("AP startup failed")
  567. try:
  568. subprocess.call(['sudo', 'ip', 'ro', 'replace', 'prohibit',
  569. '192.168.213.17'])
  570. dev[0].request("SET EAPOL::authPeriod 5")
  571. connect(dev[0], "radius-failover", wait_connect=False)
  572. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=60)
  573. if ev is None:
  574. raise Exception("Connection with the AP timed out")
  575. finally:
  576. dev[0].request("SET EAPOL::authPeriod 30")
  577. subprocess.call(['sudo', 'ip', 'ro', 'del', '192.168.213.17'])
  578. as_mib_end = as_hapd.get_mib(param="radius_server")
  579. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  580. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  581. if req_e <= req_s:
  582. raise Exception("Unexpected RADIUS server acct MIB value")
  583. def run_pyrad_server(srv, t_events):
  584. srv.RunWithStop(t_events)
  585. def test_radius_protocol(dev, apdev):
  586. """RADIUS Authentication protocol tests with a fake server"""
  587. try:
  588. import pyrad.server
  589. import pyrad.packet
  590. import pyrad.dictionary
  591. except ImportError:
  592. return "skip"
  593. class TestServer(pyrad.server.Server):
  594. def _HandleAuthPacket(self, pkt):
  595. pyrad.server.Server._HandleAuthPacket(self, pkt)
  596. logger.info("Received authentication request")
  597. reply = self.CreateReplyPacket(pkt)
  598. reply.code = pyrad.packet.AccessAccept
  599. if self.t_events['msg_auth'].is_set():
  600. logger.info("Add Message-Authenticator")
  601. if self.t_events['wrong_secret'].is_set():
  602. logger.info("Use incorrect RADIUS shared secret")
  603. pw = "incorrect"
  604. else:
  605. pw = reply.secret
  606. hmac_obj = hmac.new(pw)
  607. hmac_obj.update(struct.pack("B", reply.code))
  608. hmac_obj.update(struct.pack("B", reply.id))
  609. # reply attributes
  610. reply.AddAttribute("Message-Authenticator",
  611. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
  612. attrs = reply._PktEncodeAttributes()
  613. # Length
  614. flen = 4 + 16 + len(attrs)
  615. hmac_obj.update(struct.pack(">H", flen))
  616. hmac_obj.update(pkt.authenticator)
  617. hmac_obj.update(attrs)
  618. if self.t_events['double_msg_auth'].is_set():
  619. logger.info("Include two Message-Authenticator attributes")
  620. else:
  621. del reply[80]
  622. reply.AddAttribute("Message-Authenticator", hmac_obj.digest())
  623. self.SendReplyPacket(pkt.fd, reply)
  624. def RunWithStop(self, t_events):
  625. self._poll = select.poll()
  626. self._fdmap = {}
  627. self._PrepareSockets()
  628. self.t_events = t_events
  629. while not t_events['stop'].is_set():
  630. for (fd, event) in self._poll.poll(1000):
  631. if event == select.POLLIN:
  632. try:
  633. fdo = self._fdmap[fd]
  634. self._ProcessInput(fdo)
  635. except ServerPacketError as err:
  636. logger.info("pyrad server dropping packet: " + str(err))
  637. except pyrad.packet.PacketError as err:
  638. logger.info("pyrad server received invalid packet: " + str(err))
  639. else:
  640. logger.error("Unexpected event in pyrad server main loop")
  641. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  642. authport=18138, acctport=18139)
  643. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  644. "radius",
  645. "localhost")
  646. srv.BindToAddress("")
  647. t_events = {}
  648. t_events['stop'] = threading.Event()
  649. t_events['msg_auth'] = threading.Event()
  650. t_events['wrong_secret'] = threading.Event()
  651. t_events['double_msg_auth'] = threading.Event()
  652. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  653. t.start()
  654. try:
  655. params = hostapd.wpa2_eap_params(ssid="radius-test")
  656. params['auth_server_port'] = "18138"
  657. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  658. connect(dev[0], "radius-test", wait_connect=False)
  659. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
  660. if ev is None:
  661. raise Exception("Timeout on EAP start")
  662. time.sleep(1)
  663. dev[0].request("REMOVE_NETWORK all")
  664. time.sleep(0.1)
  665. dev[0].dump_monitor()
  666. t_events['msg_auth'].set()
  667. t_events['wrong_secret'].set()
  668. connect(dev[0], "radius-test", wait_connect=False)
  669. time.sleep(1)
  670. dev[0].request("REMOVE_NETWORK all")
  671. time.sleep(0.1)
  672. dev[0].dump_monitor()
  673. t_events['wrong_secret'].clear()
  674. connect(dev[0], "radius-test", wait_connect=False)
  675. time.sleep(1)
  676. dev[0].request("REMOVE_NETWORK all")
  677. time.sleep(0.1)
  678. dev[0].dump_monitor()
  679. t_events['double_msg_auth'].set()
  680. connect(dev[0], "radius-test", wait_connect=False)
  681. time.sleep(1)
  682. finally:
  683. t_events['stop'].set()
  684. t.join()