test_radius.py 35 KB

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