test_radius.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  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. from utils import HwsimSkip
  17. def connect(dev, ssid, wait_connect=True):
  18. dev.connect(ssid, key_mgmt="WPA-EAP", scan_freq="2412",
  19. eap="PSK", identity="psk.user@example.com",
  20. password_hex="0123456789abcdef0123456789abcdef",
  21. wait_connect=wait_connect)
  22. def test_radius_auth_unreachable(dev, apdev):
  23. """RADIUS Authentication server unreachable"""
  24. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  25. params['auth_server_port'] = "18139"
  26. hostapd.add_ap(apdev[0]['ifname'], params)
  27. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  28. connect(dev[0], "radius-auth", wait_connect=False)
  29. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
  30. if ev is None:
  31. raise Exception("Timeout on EAP start")
  32. logger.info("Checking for RADIUS retries")
  33. time.sleep(4)
  34. mib = hapd.get_mib()
  35. if "radiusAuthClientAccessRequests" not in mib:
  36. raise Exception("Missing MIB fields")
  37. if int(mib["radiusAuthClientAccessRetransmissions"]) < 1:
  38. raise Exception("Missing RADIUS Authentication retransmission")
  39. if int(mib["radiusAuthClientPendingRequests"]) < 1:
  40. raise Exception("Missing pending RADIUS Authentication request")
  41. def test_radius_auth_unreachable2(dev, apdev):
  42. """RADIUS Authentication server unreachable (2)"""
  43. subprocess.call(['sudo', 'ip', 'ro', 'replace', '192.168.213.17', 'dev',
  44. 'lo'])
  45. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  46. params['auth_server_addr'] = "192.168.213.17"
  47. params['auth_server_port'] = "18139"
  48. hostapd.add_ap(apdev[0]['ifname'], params)
  49. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  50. subprocess.call(['sudo', 'ip', 'ro', 'del', '192.168.213.17', 'dev', 'lo'])
  51. connect(dev[0], "radius-auth", wait_connect=False)
  52. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
  53. if ev is None:
  54. raise Exception("Timeout on EAP start")
  55. logger.info("Checking for RADIUS retries")
  56. time.sleep(4)
  57. mib = hapd.get_mib()
  58. if "radiusAuthClientAccessRequests" not in mib:
  59. raise Exception("Missing MIB fields")
  60. if int(mib["radiusAuthClientAccessRetransmissions"]) < 1:
  61. raise Exception("Missing RADIUS Authentication retransmission")
  62. def test_radius_acct_unreachable(dev, apdev):
  63. """RADIUS Accounting server unreachable"""
  64. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  65. params['acct_server_addr'] = "127.0.0.1"
  66. params['acct_server_port'] = "18139"
  67. params['acct_server_shared_secret'] = "radius"
  68. hostapd.add_ap(apdev[0]['ifname'], params)
  69. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  70. connect(dev[0], "radius-acct")
  71. logger.info("Checking for RADIUS retries")
  72. time.sleep(4)
  73. mib = hapd.get_mib()
  74. if "radiusAccClientRetransmissions" not in mib:
  75. raise Exception("Missing MIB fields")
  76. if int(mib["radiusAccClientRetransmissions"]) < 2:
  77. raise Exception("Missing RADIUS Accounting retransmissions")
  78. if int(mib["radiusAccClientPendingRequests"]) < 2:
  79. raise Exception("Missing pending RADIUS Accounting requests")
  80. def test_radius_acct_unreachable2(dev, apdev):
  81. """RADIUS Accounting server unreachable(2)"""
  82. subprocess.call(['sudo', 'ip', 'ro', 'replace', '192.168.213.17', 'dev',
  83. 'lo'])
  84. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  85. params['acct_server_addr'] = "192.168.213.17"
  86. params['acct_server_port'] = "18139"
  87. params['acct_server_shared_secret'] = "radius"
  88. hostapd.add_ap(apdev[0]['ifname'], params)
  89. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  90. subprocess.call(['sudo', 'ip', 'ro', 'del', '192.168.213.17', 'dev', 'lo'])
  91. connect(dev[0], "radius-acct")
  92. logger.info("Checking for RADIUS retries")
  93. time.sleep(4)
  94. mib = hapd.get_mib()
  95. if "radiusAccClientRetransmissions" not in mib:
  96. raise Exception("Missing MIB fields")
  97. if int(mib["radiusAccClientRetransmissions"]) < 1 and int(mib["radiusAccClientPendingRequests"]) < 1:
  98. raise Exception("Missing pending or retransmitted RADIUS Accounting requests")
  99. def test_radius_acct(dev, apdev):
  100. """RADIUS Accounting"""
  101. as_hapd = hostapd.Hostapd("as")
  102. as_mib_start = as_hapd.get_mib(param="radius_server")
  103. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  104. params['acct_server_addr'] = "127.0.0.1"
  105. params['acct_server_port'] = "1813"
  106. params['acct_server_shared_secret'] = "radius"
  107. params['radius_auth_req_attr'] = [ "126:s:Operator", "77:s:testing" ]
  108. params['radius_acct_req_attr'] = [ "126:s:Operator", "77:s:testing" ]
  109. hostapd.add_ap(apdev[0]['ifname'], params)
  110. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  111. connect(dev[0], "radius-acct")
  112. dev[1].connect("radius-acct", key_mgmt="WPA-EAP", scan_freq="2412",
  113. eap="PAX", identity="test-class",
  114. password_hex="0123456789abcdef0123456789abcdef")
  115. dev[2].connect("radius-acct", key_mgmt="WPA-EAP",
  116. eap="GPSK", identity="gpsk-cui",
  117. password="abcdefghijklmnop0123456789abcdef",
  118. scan_freq="2412")
  119. logger.info("Checking for RADIUS counters")
  120. count = 0
  121. while True:
  122. mib = hapd.get_mib()
  123. if int(mib['radiusAccClientResponses']) >= 3:
  124. break
  125. time.sleep(0.1)
  126. count += 1
  127. if count > 10:
  128. raise Exception("Did not receive Accounting-Response packets")
  129. if int(mib['radiusAccClientRetransmissions']) > 0:
  130. raise Exception("Unexpected Accounting-Request retransmission")
  131. as_mib_end = as_hapd.get_mib(param="radius_server")
  132. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  133. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  134. if req_e < req_s + 2:
  135. raise Exception("Unexpected RADIUS server acct MIB value")
  136. acc_s = int(as_mib_start['radiusAuthServAccessAccepts'])
  137. acc_e = int(as_mib_end['radiusAuthServAccessAccepts'])
  138. if acc_e < acc_s + 1:
  139. raise Exception("Unexpected RADIUS server auth MIB value")
  140. def test_radius_acct_pmksa_caching(dev, apdev):
  141. """RADIUS Accounting with PMKSA caching"""
  142. as_hapd = hostapd.Hostapd("as")
  143. as_mib_start = as_hapd.get_mib(param="radius_server")
  144. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  145. params['acct_server_addr'] = "127.0.0.1"
  146. params['acct_server_port'] = "1813"
  147. params['acct_server_shared_secret'] = "radius"
  148. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  149. connect(dev[0], "radius-acct")
  150. dev[1].connect("radius-acct", key_mgmt="WPA-EAP", scan_freq="2412",
  151. eap="PAX", identity="test-class",
  152. password_hex="0123456789abcdef0123456789abcdef")
  153. for d in [ dev[0], dev[1] ]:
  154. d.request("REASSOCIATE")
  155. d.wait_connected(timeout=15, error="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. raise HwsimSkip("No pyrad modules available")
  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. dev[0].wait_disconnected(timeout=10)
  388. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  389. logger.info("Disconnect-Request with matching User-Name")
  390. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  391. NAS_Identifier="nas.example.com",
  392. User_Name="psk.user@example.com",
  393. Event_Timestamp=int(time.time()))
  394. reply = srv.SendPacket(req)
  395. logger.debug("RADIUS response from hostapd")
  396. for i in reply.keys():
  397. logger.debug("%s: %s" % (i, reply[i]))
  398. if reply.code != pyrad.packet.DisconnectACK:
  399. raise Exception("Unexpected response code")
  400. dev[0].wait_disconnected(timeout=10)
  401. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  402. logger.info("Disconnect-Request with matching Calling-Station-Id")
  403. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  404. NAS_IP_Address="127.0.0.1",
  405. Calling_Station_Id=addr,
  406. Event_Timestamp=int(time.time()))
  407. reply = srv.SendPacket(req)
  408. logger.debug("RADIUS response from hostapd")
  409. for i in reply.keys():
  410. logger.debug("%s: %s" % (i, reply[i]))
  411. if reply.code != pyrad.packet.DisconnectACK:
  412. raise Exception("Unexpected response code")
  413. dev[0].wait_disconnected(timeout=10)
  414. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", "CTRL-EVENT-CONNECTED"])
  415. if ev is None:
  416. raise Exception("Timeout while waiting for re-connection")
  417. if "CTRL-EVENT-EAP-STARTED" not in ev:
  418. raise Exception("Unexpected skipping of EAP authentication in reconnection")
  419. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  420. logger.info("Disconnect-Request with matching Calling-Station-Id and non-matching CUI")
  421. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  422. Calling_Station_Id=addr,
  423. Chargeable_User_Identity="foo@example.com",
  424. Event_Timestamp=int(time.time()))
  425. reply = srv.SendPacket(req)
  426. logger.debug("RADIUS response from hostapd")
  427. for i in reply.keys():
  428. logger.debug("%s: %s" % (i, reply[i]))
  429. if reply.code != pyrad.packet.DisconnectNAK:
  430. raise Exception("Unexpected response code")
  431. if 'Error-Cause' not in reply:
  432. raise Exception("Missing Error-Cause")
  433. if reply['Error-Cause'][0] != 503:
  434. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  435. logger.info("Disconnect-Request with matching CUI")
  436. dev[1].connect("radius-das", key_mgmt="WPA-EAP",
  437. eap="GPSK", identity="gpsk-cui",
  438. password="abcdefghijklmnop0123456789abcdef",
  439. scan_freq="2412")
  440. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  441. Chargeable_User_Identity="gpsk-chargeable-user-identity",
  442. Event_Timestamp=int(time.time()))
  443. reply = srv.SendPacket(req)
  444. logger.debug("RADIUS response from hostapd")
  445. for i in reply.keys():
  446. logger.debug("%s: %s" % (i, reply[i]))
  447. if reply.code != pyrad.packet.DisconnectACK:
  448. raise Exception("Unexpected response code")
  449. dev[1].wait_disconnected(timeout=10)
  450. dev[1].wait_connected(timeout=10, error="Re-connection timed out")
  451. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  452. if ev is not None:
  453. raise Exception("Unexpected disconnection")
  454. def test_radius_das_coa(dev, apdev):
  455. """RADIUS Dynamic Authorization Extensions - CoA"""
  456. try:
  457. import pyrad.client
  458. import pyrad.packet
  459. import pyrad.dictionary
  460. import radius_das
  461. except ImportError:
  462. raise HwsimSkip("No pyrad modules available")
  463. params = hostapd.wpa2_eap_params(ssid="radius-das")
  464. params['radius_das_port'] = "3799"
  465. params['radius_das_client'] = "127.0.0.1 secret"
  466. params['radius_das_require_event_timestamp'] = "1"
  467. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  468. connect(dev[0], "radius-das")
  469. addr = dev[0].p2p_interface_addr()
  470. sta = hapd.get_sta(addr)
  471. id = sta['dot1xAuthSessionId']
  472. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  473. srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
  474. secret="secret", dict=dict)
  475. srv.retries = 1
  476. srv.timeout = 1
  477. # hostapd does not currently support CoA-Request, so NAK is expected
  478. logger.info("CoA-Request with matching Acct-Session-Id")
  479. req = radius_das.CoAPacket(dict=dict, secret="secret",
  480. Acct_Session_Id=id,
  481. Event_Timestamp=int(time.time()))
  482. reply = srv.SendPacket(req)
  483. logger.debug("RADIUS response from hostapd")
  484. for i in reply.keys():
  485. logger.debug("%s: %s" % (i, reply[i]))
  486. if reply.code != pyrad.packet.CoANAK:
  487. raise Exception("Unexpected response code")
  488. if 'Error-Cause' not in reply:
  489. raise Exception("Missing Error-Cause")
  490. if reply['Error-Cause'][0] != 405:
  491. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  492. def test_radius_ipv6(dev, apdev):
  493. """RADIUS connection over IPv6"""
  494. params = {}
  495. params['ssid'] = 'as'
  496. params['beacon_int'] = '2000'
  497. params['radius_server_clients'] = 'auth_serv/radius_clients_ipv6.conf'
  498. params['radius_server_ipv6'] = '1'
  499. params['radius_server_auth_port'] = '18129'
  500. params['radius_server_acct_port'] = '18139'
  501. params['eap_server'] = '1'
  502. params['eap_user_file'] = 'auth_serv/eap_user.conf'
  503. params['ca_cert'] = 'auth_serv/ca.pem'
  504. params['server_cert'] = 'auth_serv/server.pem'
  505. params['private_key'] = 'auth_serv/server.key'
  506. hostapd.add_ap(apdev[1]['ifname'], params)
  507. params = hostapd.wpa2_eap_params(ssid="radius-ipv6")
  508. params['auth_server_addr'] = "::0"
  509. params['auth_server_port'] = "18129"
  510. params['acct_server_addr'] = "::0"
  511. params['acct_server_port'] = "18139"
  512. params['acct_server_shared_secret'] = "radius"
  513. params['own_ip_addr'] = "::0"
  514. hostapd.add_ap(apdev[0]['ifname'], params)
  515. connect(dev[0], "radius-ipv6")
  516. def test_radius_macacl(dev, apdev):
  517. """RADIUS MAC ACL"""
  518. params = hostapd.radius_params()
  519. params["ssid"] = "radius"
  520. params["macaddr_acl"] = "2"
  521. hostapd.add_ap(apdev[0]['ifname'], params)
  522. dev[0].connect("radius", key_mgmt="NONE", scan_freq="2412")
  523. def test_radius_failover(dev, apdev):
  524. """RADIUS Authentication and Accounting server failover"""
  525. subprocess.call(['sudo', 'ip', 'ro', 'replace', '192.168.213.17', 'dev',
  526. 'lo'])
  527. as_hapd = hostapd.Hostapd("as")
  528. as_mib_start = as_hapd.get_mib(param="radius_server")
  529. params = hostapd.wpa2_eap_params(ssid="radius-failover")
  530. params["auth_server_addr"] = "192.168.213.17"
  531. params["auth_server_port"] = "1812"
  532. params["auth_server_shared_secret"] = "testing"
  533. params['acct_server_addr'] = "192.168.213.17"
  534. params['acct_server_port'] = "1813"
  535. params['acct_server_shared_secret'] = "testing"
  536. hapd = hostapd.add_ap(apdev[0]['ifname'], params, no_enable=True)
  537. hapd.set("auth_server_addr", "127.0.0.1")
  538. hapd.set("auth_server_port", "1812")
  539. hapd.set("auth_server_shared_secret", "radius")
  540. hapd.set('acct_server_addr', "127.0.0.1")
  541. hapd.set('acct_server_port', "1813")
  542. hapd.set('acct_server_shared_secret', "radius")
  543. hapd.enable()
  544. ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=30)
  545. if ev is None:
  546. raise Exception("AP startup timed out")
  547. if "AP-ENABLED" not in ev:
  548. raise Exception("AP startup failed")
  549. try:
  550. subprocess.call(['sudo', 'ip', 'ro', 'replace', 'prohibit',
  551. '192.168.213.17'])
  552. dev[0].request("SET EAPOL::authPeriod 5")
  553. connect(dev[0], "radius-failover", wait_connect=False)
  554. dev[0].wait_connected(timeout=60)
  555. finally:
  556. dev[0].request("SET EAPOL::authPeriod 30")
  557. subprocess.call(['sudo', 'ip', 'ro', 'del', '192.168.213.17'])
  558. as_mib_end = as_hapd.get_mib(param="radius_server")
  559. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  560. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  561. if req_e <= req_s:
  562. raise Exception("Unexpected RADIUS server acct MIB value")
  563. def run_pyrad_server(srv, t_events):
  564. srv.RunWithStop(t_events)
  565. def test_radius_protocol(dev, apdev):
  566. """RADIUS Authentication protocol tests with a fake server"""
  567. try:
  568. import pyrad.server
  569. import pyrad.packet
  570. import pyrad.dictionary
  571. except ImportError:
  572. raise HwsimSkip("No pyrad modules available")
  573. class TestServer(pyrad.server.Server):
  574. def _HandleAuthPacket(self, pkt):
  575. pyrad.server.Server._HandleAuthPacket(self, pkt)
  576. logger.info("Received authentication request")
  577. reply = self.CreateReplyPacket(pkt)
  578. reply.code = pyrad.packet.AccessAccept
  579. if self.t_events['msg_auth'].is_set():
  580. logger.info("Add Message-Authenticator")
  581. if self.t_events['wrong_secret'].is_set():
  582. logger.info("Use incorrect RADIUS shared secret")
  583. pw = "incorrect"
  584. else:
  585. pw = reply.secret
  586. hmac_obj = hmac.new(pw)
  587. hmac_obj.update(struct.pack("B", reply.code))
  588. hmac_obj.update(struct.pack("B", reply.id))
  589. # reply attributes
  590. reply.AddAttribute("Message-Authenticator",
  591. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
  592. attrs = reply._PktEncodeAttributes()
  593. # Length
  594. flen = 4 + 16 + len(attrs)
  595. hmac_obj.update(struct.pack(">H", flen))
  596. hmac_obj.update(pkt.authenticator)
  597. hmac_obj.update(attrs)
  598. if self.t_events['double_msg_auth'].is_set():
  599. logger.info("Include two Message-Authenticator attributes")
  600. else:
  601. del reply[80]
  602. reply.AddAttribute("Message-Authenticator", hmac_obj.digest())
  603. self.SendReplyPacket(pkt.fd, reply)
  604. def RunWithStop(self, t_events):
  605. self._poll = select.poll()
  606. self._fdmap = {}
  607. self._PrepareSockets()
  608. self.t_events = t_events
  609. while not t_events['stop'].is_set():
  610. for (fd, event) in self._poll.poll(1000):
  611. if event == select.POLLIN:
  612. try:
  613. fdo = self._fdmap[fd]
  614. self._ProcessInput(fdo)
  615. except ServerPacketError as err:
  616. logger.info("pyrad server dropping packet: " + str(err))
  617. except pyrad.packet.PacketError as err:
  618. logger.info("pyrad server received invalid packet: " + str(err))
  619. else:
  620. logger.error("Unexpected event in pyrad server main loop")
  621. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  622. authport=18138, acctport=18139)
  623. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  624. "radius",
  625. "localhost")
  626. srv.BindToAddress("")
  627. t_events = {}
  628. t_events['stop'] = threading.Event()
  629. t_events['msg_auth'] = threading.Event()
  630. t_events['wrong_secret'] = threading.Event()
  631. t_events['double_msg_auth'] = threading.Event()
  632. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  633. t.start()
  634. try:
  635. params = hostapd.wpa2_eap_params(ssid="radius-test")
  636. params['auth_server_port'] = "18138"
  637. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  638. connect(dev[0], "radius-test", wait_connect=False)
  639. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
  640. if ev is None:
  641. raise Exception("Timeout on EAP start")
  642. time.sleep(1)
  643. dev[0].request("REMOVE_NETWORK all")
  644. time.sleep(0.1)
  645. dev[0].dump_monitor()
  646. t_events['msg_auth'].set()
  647. t_events['wrong_secret'].set()
  648. connect(dev[0], "radius-test", wait_connect=False)
  649. time.sleep(1)
  650. dev[0].request("REMOVE_NETWORK all")
  651. time.sleep(0.1)
  652. dev[0].dump_monitor()
  653. t_events['wrong_secret'].clear()
  654. connect(dev[0], "radius-test", wait_connect=False)
  655. time.sleep(1)
  656. dev[0].request("REMOVE_NETWORK all")
  657. time.sleep(0.1)
  658. dev[0].dump_monitor()
  659. t_events['double_msg_auth'].set()
  660. connect(dev[0], "radius-test", wait_connect=False)
  661. time.sleep(1)
  662. finally:
  663. t_events['stop'].set()
  664. t.join()
  665. def test_radius_psk(dev, apdev):
  666. """WPA2 with PSK from RADIUS"""
  667. try:
  668. import pyrad.server
  669. import pyrad.packet
  670. import pyrad.dictionary
  671. except ImportError:
  672. raise HwsimSkip("No pyrad modules available")
  673. class TestServer(pyrad.server.Server):
  674. def _HandleAuthPacket(self, pkt):
  675. pyrad.server.Server._HandleAuthPacket(self, pkt)
  676. logger.info("Received authentication request")
  677. reply = self.CreateReplyPacket(pkt)
  678. reply.code = pyrad.packet.AccessAccept
  679. a = "\xab\xcd"
  680. secret = reply.secret
  681. if self.t_events['long'].is_set():
  682. p = b'\x10' + "0123456789abcdef" + 15 * b'\x00'
  683. b = hashlib.md5(secret + pkt.authenticator + a).digest()
  684. pp = bytearray(p[0:16])
  685. bb = bytearray(b)
  686. cc = bytearray(pp[i] ^ bb[i] for i in range(len(bb)))
  687. b = hashlib.md5(reply.secret + bytes(cc)).digest()
  688. pp = bytearray(p[16:32])
  689. bb = bytearray(b)
  690. cc += bytearray(pp[i] ^ bb[i] for i in range(len(bb)))
  691. data = '\x00' + a + bytes(cc)
  692. else:
  693. p = b'\x08' + "12345678" + 7 * b'\x00'
  694. b = hashlib.md5(secret + pkt.authenticator + a).digest()
  695. pp = bytearray(p)
  696. bb = bytearray(b)
  697. cc = bytearray(pp[i] ^ bb[i] for i in range(len(bb)))
  698. data = '\x00' + a + bytes(cc)
  699. reply.AddAttribute("Tunnel-Password", data)
  700. self.SendReplyPacket(pkt.fd, reply)
  701. def RunWithStop(self, t_events):
  702. self._poll = select.poll()
  703. self._fdmap = {}
  704. self._PrepareSockets()
  705. self.t_events = t_events
  706. while not t_events['stop'].is_set():
  707. for (fd, event) in self._poll.poll(1000):
  708. if event == select.POLLIN:
  709. try:
  710. fdo = self._fdmap[fd]
  711. self._ProcessInput(fdo)
  712. except ServerPacketError as err:
  713. logger.info("pyrad server dropping packet: " + str(err))
  714. except pyrad.packet.PacketError as err:
  715. logger.info("pyrad server received invalid packet: " + str(err))
  716. else:
  717. logger.error("Unexpected event in pyrad server main loop")
  718. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  719. authport=18138, acctport=18139)
  720. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  721. "radius",
  722. "localhost")
  723. srv.BindToAddress("")
  724. t_events = {}
  725. t_events['stop'] = threading.Event()
  726. t_events['long'] = threading.Event()
  727. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  728. t.start()
  729. try:
  730. ssid = "test-wpa2-psk"
  731. params = hostapd.radius_params()
  732. params['ssid'] = ssid
  733. params["wpa"] = "2"
  734. params["wpa_key_mgmt"] = "WPA-PSK"
  735. params["rsn_pairwise"] = "CCMP"
  736. params['macaddr_acl'] = '2'
  737. params['wpa_psk_radius'] = '2'
  738. params['auth_server_port'] = "18138"
  739. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  740. dev[0].connect(ssid, psk="12345678", scan_freq="2412")
  741. t_events['long'].set()
  742. dev[1].connect(ssid, psk="0123456789abcdef", scan_freq="2412")
  743. finally:
  744. t_events['stop'].set()
  745. t.join()