test_radius.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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_interim(dev, apdev):
  139. """RADIUS Accounting interim update"""
  140. as_hapd = hostapd.Hostapd("as")
  141. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  142. params['acct_server_addr'] = "127.0.0.1"
  143. params['acct_server_port'] = "1813"
  144. params['acct_server_shared_secret'] = "radius"
  145. params['radius_acct_interim_interval'] = "1"
  146. hostapd.add_ap(apdev[0]['ifname'], params)
  147. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  148. connect(dev[0], "radius-acct")
  149. logger.info("Checking for RADIUS counters")
  150. as_mib_start = as_hapd.get_mib(param="radius_server")
  151. time.sleep(3.1)
  152. as_mib_end = as_hapd.get_mib(param="radius_server")
  153. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  154. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  155. if req_e < req_s + 3:
  156. raise Exception("Unexpected RADIUS server acct MIB value")
  157. def test_radius_acct_interim_unreachable(dev, apdev):
  158. """RADIUS Accounting interim update with unreachable server"""
  159. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  160. params['acct_server_addr'] = "127.0.0.1"
  161. params['acct_server_port'] = "18139"
  162. params['acct_server_shared_secret'] = "radius"
  163. params['radius_acct_interim_interval'] = "1"
  164. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  165. start = hapd.get_mib()
  166. connect(dev[0], "radius-acct")
  167. logger.info("Waiting for interium accounting updates")
  168. time.sleep(3.1)
  169. end = hapd.get_mib()
  170. req_s = int(start['radiusAccClientTimeouts'])
  171. req_e = int(end['radiusAccClientTimeouts'])
  172. if req_e < req_s + 2:
  173. raise Exception("Unexpected RADIUS server acct MIB value")
  174. def test_radius_das_disconnect(dev, apdev):
  175. """RADIUS Dynamic Authorization Extensions - Disconnect"""
  176. try:
  177. import pyrad.client
  178. import pyrad.packet
  179. import pyrad.dictionary
  180. import radius_das
  181. except ImportError:
  182. return "skip"
  183. params = hostapd.wpa2_eap_params(ssid="radius-das")
  184. params['radius_das_port'] = "3799"
  185. params['radius_das_client'] = "127.0.0.1 secret"
  186. params['radius_das_require_event_timestamp'] = "1"
  187. params['own_ip_addr'] = "127.0.0.1"
  188. params['nas_identifier'] = "nas.example.com"
  189. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  190. connect(dev[0], "radius-das")
  191. addr = dev[0].p2p_interface_addr()
  192. sta = hapd.get_sta(addr)
  193. id = sta['dot1xAuthSessionId']
  194. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  195. srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
  196. secret="secret", dict=dict)
  197. srv.retries = 1
  198. srv.timeout = 1
  199. logger.info("Disconnect-Request with incorrect secret")
  200. req = radius_das.DisconnectPacket(dict=dict, secret="incorrect",
  201. User_Name="foo",
  202. NAS_Identifier="localhost",
  203. Event_Timestamp=int(time.time()))
  204. logger.debug(req)
  205. try:
  206. reply = srv.SendPacket(req)
  207. raise Exception("Unexpected response to Disconnect-Request")
  208. except pyrad.client.Timeout:
  209. logger.info("Disconnect-Request with incorrect secret properly ignored")
  210. logger.info("Disconnect-Request without Event-Timestamp")
  211. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  212. User_Name="psk.user@example.com")
  213. logger.debug(req)
  214. try:
  215. reply = srv.SendPacket(req)
  216. raise Exception("Unexpected response to Disconnect-Request")
  217. except pyrad.client.Timeout:
  218. logger.info("Disconnect-Request without Event-Timestamp properly ignored")
  219. logger.info("Disconnect-Request with non-matching Event-Timestamp")
  220. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  221. User_Name="psk.user@example.com",
  222. Event_Timestamp=123456789)
  223. logger.debug(req)
  224. try:
  225. reply = srv.SendPacket(req)
  226. raise Exception("Unexpected response to Disconnect-Request")
  227. except pyrad.client.Timeout:
  228. logger.info("Disconnect-Request with non-matching Event-Timestamp properly ignored")
  229. logger.info("Disconnect-Request with unsupported attribute")
  230. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  231. User_Name="foo",
  232. User_Password="foo",
  233. Event_Timestamp=int(time.time()))
  234. reply = srv.SendPacket(req)
  235. logger.debug("RADIUS response from hostapd")
  236. for i in reply.keys():
  237. logger.debug("%s: %s" % (i, reply[i]))
  238. if reply.code != pyrad.packet.DisconnectNAK:
  239. raise Exception("Unexpected response code")
  240. if 'Error-Cause' not in reply:
  241. raise Exception("Missing Error-Cause")
  242. if reply['Error-Cause'][0] != 401:
  243. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  244. logger.info("Disconnect-Request with invalid Calling-Station-Id")
  245. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  246. User_Name="foo",
  247. Calling_Station_Id="foo",
  248. Event_Timestamp=int(time.time()))
  249. reply = srv.SendPacket(req)
  250. logger.debug("RADIUS response from hostapd")
  251. for i in reply.keys():
  252. logger.debug("%s: %s" % (i, reply[i]))
  253. if reply.code != pyrad.packet.DisconnectNAK:
  254. raise Exception("Unexpected response code")
  255. if 'Error-Cause' not in reply:
  256. raise Exception("Missing Error-Cause")
  257. if reply['Error-Cause'][0] != 407:
  258. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  259. logger.info("Disconnect-Request with mismatching User-Name")
  260. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  261. User_Name="foo",
  262. Event_Timestamp=int(time.time()))
  263. reply = srv.SendPacket(req)
  264. logger.debug("RADIUS response from hostapd")
  265. for i in reply.keys():
  266. logger.debug("%s: %s" % (i, reply[i]))
  267. if reply.code != pyrad.packet.DisconnectNAK:
  268. raise Exception("Unexpected response code")
  269. if 'Error-Cause' not in reply:
  270. raise Exception("Missing Error-Cause")
  271. if reply['Error-Cause'][0] != 503:
  272. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  273. logger.info("Disconnect-Request with mismatching Calling-Station-Id")
  274. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  275. Calling_Station_Id="12:34:56:78:90:aa",
  276. Event_Timestamp=int(time.time()))
  277. reply = srv.SendPacket(req)
  278. logger.debug("RADIUS response from hostapd")
  279. for i in reply.keys():
  280. logger.debug("%s: %s" % (i, reply[i]))
  281. if reply.code != pyrad.packet.DisconnectNAK:
  282. raise Exception("Unexpected response code")
  283. if 'Error-Cause' not in reply:
  284. raise Exception("Missing Error-Cause")
  285. if reply['Error-Cause'][0] != 503:
  286. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  287. logger.info("Disconnect-Request with mismatching Acct-Session-Id")
  288. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  289. Acct_Session_Id="12345678-87654321",
  290. Event_Timestamp=int(time.time()))
  291. reply = srv.SendPacket(req)
  292. logger.debug("RADIUS response from hostapd")
  293. for i in reply.keys():
  294. logger.debug("%s: %s" % (i, reply[i]))
  295. if reply.code != pyrad.packet.DisconnectNAK:
  296. raise Exception("Unexpected response code")
  297. if 'Error-Cause' not in reply:
  298. raise Exception("Missing Error-Cause")
  299. if reply['Error-Cause'][0] != 503:
  300. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  301. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  302. if ev is not None:
  303. raise Exception("Unexpected disconnection")
  304. logger.info("Disconnect-Request with mismatching NAS-IP-Address")
  305. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  306. NAS_IP_Address="192.168.3.4",
  307. Acct_Session_Id=id,
  308. Event_Timestamp=int(time.time()))
  309. reply = srv.SendPacket(req)
  310. logger.debug("RADIUS response from hostapd")
  311. for i in reply.keys():
  312. logger.debug("%s: %s" % (i, reply[i]))
  313. if reply.code != pyrad.packet.DisconnectNAK:
  314. raise Exception("Unexpected response code")
  315. if 'Error-Cause' not in reply:
  316. raise Exception("Missing Error-Cause")
  317. if reply['Error-Cause'][0] != 403:
  318. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  319. logger.info("Disconnect-Request with mismatching NAS-Identifier")
  320. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  321. NAS_Identifier="unknown.example.com",
  322. Acct_Session_Id=id,
  323. Event_Timestamp=int(time.time()))
  324. reply = srv.SendPacket(req)
  325. logger.debug("RADIUS response from hostapd")
  326. for i in reply.keys():
  327. logger.debug("%s: %s" % (i, reply[i]))
  328. if reply.code != pyrad.packet.DisconnectNAK:
  329. raise Exception("Unexpected response code")
  330. if 'Error-Cause' not in reply:
  331. raise Exception("Missing Error-Cause")
  332. if reply['Error-Cause'][0] != 403:
  333. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  334. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  335. if ev is not None:
  336. raise Exception("Unexpected disconnection")
  337. logger.info("Disconnect-Request with matching Acct-Session-Id")
  338. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  339. NAS_IP_Address="127.0.0.1",
  340. NAS_Identifier="nas.example.com",
  341. Acct_Session_Id=id,
  342. Event_Timestamp=int(time.time()))
  343. reply = srv.SendPacket(req)
  344. logger.debug("RADIUS response from hostapd")
  345. for i in reply.keys():
  346. logger.debug("%s: %s" % (i, reply[i]))
  347. if reply.code != pyrad.packet.DisconnectACK:
  348. raise Exception("Unexpected response code")
  349. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
  350. if ev is None:
  351. raise Exception("Timeout while waiting for disconnection")
  352. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"])
  353. if ev is None:
  354. raise Exception("Timeout while waiting for re-connection")
  355. logger.info("Disconnect-Request with matching User-Name")
  356. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  357. NAS_Identifier="nas.example.com",
  358. User_Name="psk.user@example.com",
  359. Event_Timestamp=int(time.time()))
  360. reply = srv.SendPacket(req)
  361. logger.debug("RADIUS response from hostapd")
  362. for i in reply.keys():
  363. logger.debug("%s: %s" % (i, reply[i]))
  364. if reply.code != pyrad.packet.DisconnectACK:
  365. raise Exception("Unexpected response code")
  366. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
  367. if ev is None:
  368. raise Exception("Timeout while waiting for disconnection")
  369. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"])
  370. if ev is None:
  371. raise Exception("Timeout while waiting for re-connection")
  372. logger.info("Disconnect-Request with matching Calling-Station-Id")
  373. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  374. NAS_IP_Address="127.0.0.1",
  375. Calling_Station_Id=addr,
  376. Event_Timestamp=int(time.time()))
  377. reply = srv.SendPacket(req)
  378. logger.debug("RADIUS response from hostapd")
  379. for i in reply.keys():
  380. logger.debug("%s: %s" % (i, reply[i]))
  381. if reply.code != pyrad.packet.DisconnectACK:
  382. raise Exception("Unexpected response code")
  383. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
  384. if ev is None:
  385. raise Exception("Timeout while waiting for disconnection")
  386. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", "CTRL-EVENT-CONNECTED"])
  387. if ev is None:
  388. raise Exception("Timeout while waiting for re-connection")
  389. if "CTRL-EVENT-EAP-STARTED" not in ev:
  390. raise Exception("Unexpected skipping of EAP authentication in reconnection")
  391. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"])
  392. if ev is None:
  393. raise Exception("Timeout while waiting for re-connection to complete")
  394. logger.info("Disconnect-Request with matching Calling-Station-Id and non-matching CUI")
  395. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  396. Calling_Station_Id=addr,
  397. Chargeable_User_Identity="foo@example.com",
  398. Event_Timestamp=int(time.time()))
  399. reply = srv.SendPacket(req)
  400. logger.debug("RADIUS response from hostapd")
  401. for i in reply.keys():
  402. logger.debug("%s: %s" % (i, reply[i]))
  403. if reply.code != pyrad.packet.DisconnectACK:
  404. raise Exception("Unexpected response code")
  405. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
  406. if ev is None:
  407. raise Exception("Timeout while waiting for disconnection")
  408. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"])
  409. if ev is None:
  410. raise Exception("Timeout while waiting for re-connection")
  411. logger.info("Disconnect-Request with matching CUI")
  412. dev[1].connect("radius-das", key_mgmt="WPA-EAP",
  413. eap="GPSK", identity="gpsk-cui",
  414. password="abcdefghijklmnop0123456789abcdef",
  415. scan_freq="2412")
  416. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  417. Chargeable_User_Identity="gpsk-chargeable-user-identity",
  418. Event_Timestamp=int(time.time()))
  419. reply = srv.SendPacket(req)
  420. logger.debug("RADIUS response from hostapd")
  421. for i in reply.keys():
  422. logger.debug("%s: %s" % (i, reply[i]))
  423. if reply.code != pyrad.packet.DisconnectACK:
  424. raise Exception("Unexpected response code")
  425. ev = dev[1].wait_event(["CTRL-EVENT-DISCONNECTED"])
  426. if ev is None:
  427. raise Exception("Timeout while waiting for disconnection")
  428. ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"])
  429. if ev is None:
  430. raise Exception("Timeout while waiting for re-connection")
  431. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  432. if ev is not None:
  433. raise Exception("Unexpected disconnection")
  434. def test_radius_das_coa(dev, apdev):
  435. """RADIUS Dynamic Authorization Extensions - CoA"""
  436. try:
  437. import pyrad.client
  438. import pyrad.packet
  439. import pyrad.dictionary
  440. import radius_das
  441. except ImportError:
  442. return "skip"
  443. params = hostapd.wpa2_eap_params(ssid="radius-das")
  444. params['radius_das_port'] = "3799"
  445. params['radius_das_client'] = "127.0.0.1 secret"
  446. params['radius_das_require_event_timestamp'] = "1"
  447. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  448. connect(dev[0], "radius-das")
  449. addr = dev[0].p2p_interface_addr()
  450. sta = hapd.get_sta(addr)
  451. id = sta['dot1xAuthSessionId']
  452. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  453. srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
  454. secret="secret", dict=dict)
  455. srv.retries = 1
  456. srv.timeout = 1
  457. # hostapd does not currently support CoA-Request, so NAK is expected
  458. logger.info("CoA-Request with matching Acct-Session-Id")
  459. req = radius_das.CoAPacket(dict=dict, secret="secret",
  460. Acct_Session_Id=id,
  461. Event_Timestamp=int(time.time()))
  462. reply = srv.SendPacket(req)
  463. logger.debug("RADIUS response from hostapd")
  464. for i in reply.keys():
  465. logger.debug("%s: %s" % (i, reply[i]))
  466. if reply.code != pyrad.packet.CoANAK:
  467. raise Exception("Unexpected response code")
  468. if 'Error-Cause' not in reply:
  469. raise Exception("Missing Error-Cause")
  470. if reply['Error-Cause'][0] != 405:
  471. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  472. def test_radius_ipv6(dev, apdev):
  473. """RADIUS connection over IPv6"""
  474. params = {}
  475. params['ssid'] = 'as'
  476. params['beacon_int'] = '2000'
  477. params['radius_server_clients'] = 'auth_serv/radius_clients_ipv6.conf'
  478. params['radius_server_ipv6'] = '1'
  479. params['radius_server_auth_port'] = '18129'
  480. params['radius_server_acct_port'] = '18139'
  481. params['eap_server'] = '1'
  482. params['eap_user_file'] = 'auth_serv/eap_user.conf'
  483. params['ca_cert'] = 'auth_serv/ca.pem'
  484. params['server_cert'] = 'auth_serv/server.pem'
  485. params['private_key'] = 'auth_serv/server.key'
  486. hostapd.add_ap(apdev[1]['ifname'], params)
  487. params = hostapd.wpa2_eap_params(ssid="radius-ipv6")
  488. params['auth_server_addr'] = "::0"
  489. params['auth_server_port'] = "18129"
  490. params['acct_server_addr'] = "::0"
  491. params['acct_server_port'] = "18139"
  492. params['acct_server_shared_secret'] = "radius"
  493. params['own_ip_addr'] = "::0"
  494. hostapd.add_ap(apdev[0]['ifname'], params)
  495. connect(dev[0], "radius-ipv6")
  496. def test_radius_macacl(dev, apdev):
  497. """RADIUS MAC ACL"""
  498. params = hostapd.radius_params()
  499. params["ssid"] = "radius"
  500. params["macaddr_acl"] = "2"
  501. hostapd.add_ap(apdev[0]['ifname'], params)
  502. dev[0].connect("radius", key_mgmt="NONE", scan_freq="2412")
  503. def test_radius_failover(dev, apdev):
  504. """RADIUS Authentication and Accounting server failover"""
  505. subprocess.call(['sudo', 'ip', 'ro', 'replace', '192.168.213.17', 'dev',
  506. 'lo'])
  507. as_hapd = hostapd.Hostapd("as")
  508. as_mib_start = as_hapd.get_mib(param="radius_server")
  509. params = hostapd.wpa2_eap_params(ssid="radius-failover")
  510. params["auth_server_addr"] = "192.168.213.17"
  511. params["auth_server_port"] = "1812"
  512. params["auth_server_shared_secret"] = "testing"
  513. params['acct_server_addr'] = "192.168.213.17"
  514. params['acct_server_port'] = "1813"
  515. params['acct_server_shared_secret'] = "testing"
  516. hapd = hostapd.add_ap(apdev[0]['ifname'], params, no_enable=True)
  517. hapd.set("auth_server_addr", "127.0.0.1")
  518. hapd.set("auth_server_port", "1812")
  519. hapd.set("auth_server_shared_secret", "radius")
  520. hapd.set('acct_server_addr', "127.0.0.1")
  521. hapd.set('acct_server_port', "1813")
  522. hapd.set('acct_server_shared_secret', "radius")
  523. hapd.enable()
  524. ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=30)
  525. if ev is None:
  526. raise Exception("AP startup timed out")
  527. if "AP-ENABLED" not in ev:
  528. raise Exception("AP startup failed")
  529. try:
  530. subprocess.call(['sudo', 'ip', 'ro', 'replace', 'prohibit',
  531. '192.168.213.17'])
  532. dev[0].request("SET EAPOL::authPeriod 5")
  533. connect(dev[0], "radius-failover", wait_connect=False)
  534. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=60)
  535. if ev is None:
  536. raise Exception("Connection with the AP timed out")
  537. finally:
  538. dev[0].request("SET EAPOL::authPeriod 30")
  539. subprocess.call(['sudo', 'ip', 'ro', 'del', '192.168.213.17'])
  540. as_mib_end = as_hapd.get_mib(param="radius_server")
  541. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  542. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  543. if req_e <= req_s:
  544. raise Exception("Unexpected RADIUS server acct MIB value")
  545. def run_pyrad_server(srv, t_events):
  546. srv.RunWithStop(t_events)
  547. def test_radius_protocol(dev, apdev):
  548. """RADIUS Authentication protocol tests with a fake server"""
  549. try:
  550. import pyrad.server
  551. import pyrad.packet
  552. import pyrad.dictionary
  553. except ImportError:
  554. return "skip"
  555. class TestServer(pyrad.server.Server):
  556. def _HandleAuthPacket(self, pkt):
  557. pyrad.server.Server._HandleAuthPacket(self, pkt)
  558. logger.info("Received authentication request")
  559. reply = self.CreateReplyPacket(pkt)
  560. reply.code = pyrad.packet.AccessAccept
  561. if self.t_events['msg_auth'].is_set():
  562. logger.info("Add Message-Authenticator")
  563. if self.t_events['wrong_secret'].is_set():
  564. logger.info("Use incorrect RADIUS shared secret")
  565. pw = "incorrect"
  566. else:
  567. pw = reply.secret
  568. hmac_obj = hmac.new(pw)
  569. hmac_obj.update(struct.pack("B", reply.code))
  570. hmac_obj.update(struct.pack("B", reply.id))
  571. # reply attributes
  572. reply.AddAttribute("Message-Authenticator",
  573. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
  574. attrs = reply._PktEncodeAttributes()
  575. # Length
  576. flen = 4 + 16 + len(attrs)
  577. hmac_obj.update(struct.pack(">H", flen))
  578. hmac_obj.update(pkt.authenticator)
  579. hmac_obj.update(attrs)
  580. if self.t_events['double_msg_auth'].is_set():
  581. logger.info("Include two Message-Authenticator attributes")
  582. else:
  583. del reply[80]
  584. reply.AddAttribute("Message-Authenticator", hmac_obj.digest())
  585. self.SendReplyPacket(pkt.fd, reply)
  586. def RunWithStop(self, t_events):
  587. self._poll = select.poll()
  588. self._fdmap = {}
  589. self._PrepareSockets()
  590. self.t_events = t_events
  591. while not t_events['stop'].is_set():
  592. for (fd, event) in self._poll.poll(1000):
  593. if event == select.POLLIN:
  594. try:
  595. fdo = self._fdmap[fd]
  596. self._ProcessInput(fdo)
  597. except ServerPacketError as err:
  598. logger.info("pyrad server dropping packet: " + str(err))
  599. except pyrad.packet.PacketError as err:
  600. logger.info("pyrad server received invalid packet: " + str(err))
  601. else:
  602. logger.error("Unexpected event in pyrad server main loop")
  603. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  604. authport=18138, acctport=18139)
  605. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  606. "radius",
  607. "localhost")
  608. srv.BindToAddress("")
  609. t_events = {}
  610. t_events['stop'] = threading.Event()
  611. t_events['msg_auth'] = threading.Event()
  612. t_events['wrong_secret'] = threading.Event()
  613. t_events['double_msg_auth'] = threading.Event()
  614. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  615. t.start()
  616. try:
  617. params = hostapd.wpa2_eap_params(ssid="radius-test")
  618. params['auth_server_port'] = "18138"
  619. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  620. connect(dev[0], "radius-test", wait_connect=False)
  621. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
  622. if ev is None:
  623. raise Exception("Timeout on EAP start")
  624. time.sleep(1)
  625. dev[0].request("REMOVE_NETWORK all")
  626. time.sleep(0.1)
  627. dev[0].dump_monitor()
  628. t_events['msg_auth'].set()
  629. t_events['wrong_secret'].set()
  630. connect(dev[0], "radius-test", wait_connect=False)
  631. time.sleep(1)
  632. dev[0].request("REMOVE_NETWORK all")
  633. time.sleep(0.1)
  634. dev[0].dump_monitor()
  635. t_events['wrong_secret'].clear()
  636. connect(dev[0], "radius-test", wait_connect=False)
  637. time.sleep(1)
  638. dev[0].request("REMOVE_NETWORK all")
  639. time.sleep(0.1)
  640. dev[0].dump_monitor()
  641. t_events['double_msg_auth'].set()
  642. connect(dev[0], "radius-test", wait_connect=False)
  643. time.sleep(1)
  644. finally:
  645. t_events['stop'].set()
  646. t.join()