test_radius.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  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. logger.info("Disconnect-Request with mismatching Acct-Session-Id (len)")
  340. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  341. Acct_Session_Id="12345678",
  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.DisconnectNAK:
  348. raise Exception("Unexpected response code")
  349. if 'Error-Cause' not in reply:
  350. raise Exception("Missing Error-Cause")
  351. if reply['Error-Cause'][0] != 503:
  352. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  353. logger.info("Disconnect-Request with mismatching Acct-Multi-Session-Id")
  354. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  355. Acct_Multi_Session_Id="12345678+87654321",
  356. Event_Timestamp=int(time.time()))
  357. reply = srv.SendPacket(req)
  358. logger.debug("RADIUS response from hostapd")
  359. for i in reply.keys():
  360. logger.debug("%s: %s" % (i, reply[i]))
  361. if reply.code != pyrad.packet.DisconnectNAK:
  362. raise Exception("Unexpected response code")
  363. if 'Error-Cause' not in reply:
  364. raise Exception("Missing Error-Cause")
  365. if reply['Error-Cause'][0] != 503:
  366. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  367. logger.info("Disconnect-Request with mismatching Acct-Multi-Session-Id (len)")
  368. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  369. Acct_Multi_Session_Id="12345678",
  370. Event_Timestamp=int(time.time()))
  371. reply = srv.SendPacket(req)
  372. logger.debug("RADIUS response from hostapd")
  373. for i in reply.keys():
  374. logger.debug("%s: %s" % (i, reply[i]))
  375. if reply.code != pyrad.packet.DisconnectNAK:
  376. raise Exception("Unexpected response code")
  377. if 'Error-Cause' not in reply:
  378. raise Exception("Missing Error-Cause")
  379. if reply['Error-Cause'][0] != 503:
  380. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  381. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  382. if ev is not None:
  383. raise Exception("Unexpected disconnection")
  384. logger.info("Disconnect-Request with mismatching NAS-IP-Address")
  385. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  386. NAS_IP_Address="192.168.3.4",
  387. Acct_Session_Id=id,
  388. Event_Timestamp=int(time.time()))
  389. reply = srv.SendPacket(req)
  390. logger.debug("RADIUS response from hostapd")
  391. for i in reply.keys():
  392. logger.debug("%s: %s" % (i, reply[i]))
  393. if reply.code != pyrad.packet.DisconnectNAK:
  394. raise Exception("Unexpected response code")
  395. if 'Error-Cause' not in reply:
  396. raise Exception("Missing Error-Cause")
  397. if reply['Error-Cause'][0] != 403:
  398. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  399. logger.info("Disconnect-Request with mismatching NAS-Identifier")
  400. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  401. NAS_Identifier="unknown.example.com",
  402. Acct_Session_Id=id,
  403. Event_Timestamp=int(time.time()))
  404. reply = srv.SendPacket(req)
  405. logger.debug("RADIUS response from hostapd")
  406. for i in reply.keys():
  407. logger.debug("%s: %s" % (i, reply[i]))
  408. if reply.code != pyrad.packet.DisconnectNAK:
  409. raise Exception("Unexpected response code")
  410. if 'Error-Cause' not in reply:
  411. raise Exception("Missing Error-Cause")
  412. if reply['Error-Cause'][0] != 403:
  413. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  414. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  415. if ev is not None:
  416. raise Exception("Unexpected disconnection")
  417. logger.info("Disconnect-Request with matching Acct-Session-Id")
  418. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  419. NAS_IP_Address="127.0.0.1",
  420. NAS_Identifier="nas.example.com",
  421. Acct_Session_Id=id,
  422. Event_Timestamp=int(time.time()))
  423. reply = srv.SendPacket(req)
  424. logger.debug("RADIUS response from hostapd")
  425. for i in reply.keys():
  426. logger.debug("%s: %s" % (i, reply[i]))
  427. if reply.code != pyrad.packet.DisconnectACK:
  428. raise Exception("Unexpected response code")
  429. dev[0].wait_disconnected(timeout=10)
  430. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  431. logger.info("Disconnect-Request with matching Acct-Multi-Session-Id")
  432. sta = hapd.get_sta(addr)
  433. multi_sess_id = sta['authMultiSessionId']
  434. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  435. NAS_IP_Address="127.0.0.1",
  436. NAS_Identifier="nas.example.com",
  437. Acct_Multi_Session_Id=multi_sess_id,
  438. Event_Timestamp=int(time.time()))
  439. reply = srv.SendPacket(req)
  440. logger.debug("RADIUS response from hostapd")
  441. for i in reply.keys():
  442. logger.debug("%s: %s" % (i, reply[i]))
  443. if reply.code != pyrad.packet.DisconnectACK:
  444. raise Exception("Unexpected response code")
  445. dev[0].wait_disconnected(timeout=10)
  446. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  447. logger.info("Disconnect-Request with matching User-Name")
  448. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  449. NAS_Identifier="nas.example.com",
  450. User_Name="psk.user@example.com",
  451. Event_Timestamp=int(time.time()))
  452. reply = srv.SendPacket(req)
  453. logger.debug("RADIUS response from hostapd")
  454. for i in reply.keys():
  455. logger.debug("%s: %s" % (i, reply[i]))
  456. if reply.code != pyrad.packet.DisconnectACK:
  457. raise Exception("Unexpected response code")
  458. dev[0].wait_disconnected(timeout=10)
  459. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  460. logger.info("Disconnect-Request with matching Calling-Station-Id")
  461. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  462. NAS_IP_Address="127.0.0.1",
  463. Calling_Station_Id=addr,
  464. Event_Timestamp=int(time.time()))
  465. reply = srv.SendPacket(req)
  466. logger.debug("RADIUS response from hostapd")
  467. for i in reply.keys():
  468. logger.debug("%s: %s" % (i, reply[i]))
  469. if reply.code != pyrad.packet.DisconnectACK:
  470. raise Exception("Unexpected response code")
  471. dev[0].wait_disconnected(timeout=10)
  472. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", "CTRL-EVENT-CONNECTED"])
  473. if ev is None:
  474. raise Exception("Timeout while waiting for re-connection")
  475. if "CTRL-EVENT-EAP-STARTED" not in ev:
  476. raise Exception("Unexpected skipping of EAP authentication in reconnection")
  477. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  478. logger.info("Disconnect-Request with matching Calling-Station-Id and non-matching CUI")
  479. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  480. Calling_Station_Id=addr,
  481. Chargeable_User_Identity="foo@example.com",
  482. Event_Timestamp=int(time.time()))
  483. reply = srv.SendPacket(req)
  484. logger.debug("RADIUS response from hostapd")
  485. for i in reply.keys():
  486. logger.debug("%s: %s" % (i, reply[i]))
  487. if reply.code != pyrad.packet.DisconnectNAK:
  488. raise Exception("Unexpected response code")
  489. if 'Error-Cause' not in reply:
  490. raise Exception("Missing Error-Cause")
  491. if reply['Error-Cause'][0] != 503:
  492. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  493. logger.info("Disconnect-Request with matching CUI")
  494. dev[1].connect("radius-das", key_mgmt="WPA-EAP",
  495. eap="GPSK", identity="gpsk-cui",
  496. password="abcdefghijklmnop0123456789abcdef",
  497. scan_freq="2412")
  498. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  499. Chargeable_User_Identity="gpsk-chargeable-user-identity",
  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.DisconnectACK:
  506. raise Exception("Unexpected response code")
  507. dev[1].wait_disconnected(timeout=10)
  508. dev[1].wait_connected(timeout=10, error="Re-connection timed out")
  509. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  510. if ev is not None:
  511. raise Exception("Unexpected disconnection")
  512. connect(dev[2], "radius-das")
  513. logger.info("Disconnect-Request with matching User-Name - multiple sessions matching")
  514. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  515. NAS_Identifier="nas.example.com",
  516. User_Name="psk.user@example.com",
  517. Event_Timestamp=int(time.time()))
  518. reply = srv.SendPacket(req)
  519. logger.debug("RADIUS response from hostapd")
  520. for i in reply.keys():
  521. logger.debug("%s: %s" % (i, reply[i]))
  522. if reply.code != pyrad.packet.DisconnectNAK:
  523. raise Exception("Unexpected response code")
  524. if 'Error-Cause' not in reply:
  525. raise Exception("Missing Error-Cause")
  526. if reply['Error-Cause'][0] != 508:
  527. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  528. logger.info("Disconnect-Request with User-Name matching multiple sessions, Calling-Station-Id only one")
  529. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  530. NAS_Identifier="nas.example.com",
  531. Calling_Station_Id=addr,
  532. User_Name="psk.user@example.com",
  533. Event_Timestamp=int(time.time()))
  534. reply = srv.SendPacket(req)
  535. logger.debug("RADIUS response from hostapd")
  536. for i in reply.keys():
  537. logger.debug("%s: %s" % (i, reply[i]))
  538. if reply.code != pyrad.packet.DisconnectACK:
  539. raise Exception("Unexpected response code")
  540. dev[0].wait_disconnected(timeout=10)
  541. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  542. ev = dev[2].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  543. if ev is not None:
  544. raise Exception("Unexpected disconnection")
  545. def test_radius_das_coa(dev, apdev):
  546. """RADIUS Dynamic Authorization Extensions - CoA"""
  547. try:
  548. import pyrad.client
  549. import pyrad.packet
  550. import pyrad.dictionary
  551. import radius_das
  552. except ImportError:
  553. raise HwsimSkip("No pyrad modules available")
  554. params = hostapd.wpa2_eap_params(ssid="radius-das")
  555. params['radius_das_port'] = "3799"
  556. params['radius_das_client'] = "127.0.0.1 secret"
  557. params['radius_das_require_event_timestamp'] = "1"
  558. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  559. connect(dev[0], "radius-das")
  560. addr = dev[0].p2p_interface_addr()
  561. sta = hapd.get_sta(addr)
  562. id = sta['dot1xAuthSessionId']
  563. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  564. srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
  565. secret="secret", dict=dict)
  566. srv.retries = 1
  567. srv.timeout = 1
  568. # hostapd does not currently support CoA-Request, so NAK is expected
  569. logger.info("CoA-Request with matching Acct-Session-Id")
  570. req = radius_das.CoAPacket(dict=dict, secret="secret",
  571. Acct_Session_Id=id,
  572. Event_Timestamp=int(time.time()))
  573. reply = srv.SendPacket(req)
  574. logger.debug("RADIUS response from hostapd")
  575. for i in reply.keys():
  576. logger.debug("%s: %s" % (i, reply[i]))
  577. if reply.code != pyrad.packet.CoANAK:
  578. raise Exception("Unexpected response code")
  579. if 'Error-Cause' not in reply:
  580. raise Exception("Missing Error-Cause")
  581. if reply['Error-Cause'][0] != 405:
  582. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  583. def test_radius_ipv6(dev, apdev):
  584. """RADIUS connection over IPv6"""
  585. params = {}
  586. params['ssid'] = 'as'
  587. params['beacon_int'] = '2000'
  588. params['radius_server_clients'] = 'auth_serv/radius_clients_ipv6.conf'
  589. params['radius_server_ipv6'] = '1'
  590. params['radius_server_auth_port'] = '18129'
  591. params['radius_server_acct_port'] = '18139'
  592. params['eap_server'] = '1'
  593. params['eap_user_file'] = 'auth_serv/eap_user.conf'
  594. params['ca_cert'] = 'auth_serv/ca.pem'
  595. params['server_cert'] = 'auth_serv/server.pem'
  596. params['private_key'] = 'auth_serv/server.key'
  597. hostapd.add_ap(apdev[1]['ifname'], params)
  598. params = hostapd.wpa2_eap_params(ssid="radius-ipv6")
  599. params['auth_server_addr'] = "::0"
  600. params['auth_server_port'] = "18129"
  601. params['acct_server_addr'] = "::0"
  602. params['acct_server_port'] = "18139"
  603. params['acct_server_shared_secret'] = "radius"
  604. params['own_ip_addr'] = "::0"
  605. hostapd.add_ap(apdev[0]['ifname'], params)
  606. connect(dev[0], "radius-ipv6")
  607. def test_radius_macacl(dev, apdev):
  608. """RADIUS MAC ACL"""
  609. params = hostapd.radius_params()
  610. params["ssid"] = "radius"
  611. params["macaddr_acl"] = "2"
  612. hostapd.add_ap(apdev[0]['ifname'], params)
  613. dev[0].connect("radius", key_mgmt="NONE", scan_freq="2412")
  614. def test_radius_failover(dev, apdev):
  615. """RADIUS Authentication and Accounting server failover"""
  616. subprocess.call(['sudo', 'ip', 'ro', 'replace', '192.168.213.17', 'dev',
  617. 'lo'])
  618. as_hapd = hostapd.Hostapd("as")
  619. as_mib_start = as_hapd.get_mib(param="radius_server")
  620. params = hostapd.wpa2_eap_params(ssid="radius-failover")
  621. params["auth_server_addr"] = "192.168.213.17"
  622. params["auth_server_port"] = "1812"
  623. params["auth_server_shared_secret"] = "testing"
  624. params['acct_server_addr'] = "192.168.213.17"
  625. params['acct_server_port'] = "1813"
  626. params['acct_server_shared_secret'] = "testing"
  627. hapd = hostapd.add_ap(apdev[0]['ifname'], params, no_enable=True)
  628. hapd.set("auth_server_addr", "127.0.0.1")
  629. hapd.set("auth_server_port", "1812")
  630. hapd.set("auth_server_shared_secret", "radius")
  631. hapd.set('acct_server_addr', "127.0.0.1")
  632. hapd.set('acct_server_port', "1813")
  633. hapd.set('acct_server_shared_secret', "radius")
  634. hapd.enable()
  635. ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=30)
  636. if ev is None:
  637. raise Exception("AP startup timed out")
  638. if "AP-ENABLED" not in ev:
  639. raise Exception("AP startup failed")
  640. try:
  641. subprocess.call(['sudo', 'ip', 'ro', 'replace', 'prohibit',
  642. '192.168.213.17'])
  643. dev[0].request("SET EAPOL::authPeriod 5")
  644. connect(dev[0], "radius-failover", wait_connect=False)
  645. dev[0].wait_connected(timeout=60)
  646. finally:
  647. dev[0].request("SET EAPOL::authPeriod 30")
  648. subprocess.call(['sudo', 'ip', 'ro', 'del', '192.168.213.17'])
  649. as_mib_end = as_hapd.get_mib(param="radius_server")
  650. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  651. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  652. if req_e <= req_s:
  653. raise Exception("Unexpected RADIUS server acct MIB value")
  654. def run_pyrad_server(srv, t_events):
  655. srv.RunWithStop(t_events)
  656. def test_radius_protocol(dev, apdev):
  657. """RADIUS Authentication protocol tests with a fake server"""
  658. try:
  659. import pyrad.server
  660. import pyrad.packet
  661. import pyrad.dictionary
  662. except ImportError:
  663. raise HwsimSkip("No pyrad modules available")
  664. class TestServer(pyrad.server.Server):
  665. def _HandleAuthPacket(self, pkt):
  666. pyrad.server.Server._HandleAuthPacket(self, pkt)
  667. logger.info("Received authentication request")
  668. reply = self.CreateReplyPacket(pkt)
  669. reply.code = pyrad.packet.AccessAccept
  670. if self.t_events['msg_auth'].is_set():
  671. logger.info("Add Message-Authenticator")
  672. if self.t_events['wrong_secret'].is_set():
  673. logger.info("Use incorrect RADIUS shared secret")
  674. pw = "incorrect"
  675. else:
  676. pw = reply.secret
  677. hmac_obj = hmac.new(pw)
  678. hmac_obj.update(struct.pack("B", reply.code))
  679. hmac_obj.update(struct.pack("B", reply.id))
  680. # reply attributes
  681. reply.AddAttribute("Message-Authenticator",
  682. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
  683. attrs = reply._PktEncodeAttributes()
  684. # Length
  685. flen = 4 + 16 + len(attrs)
  686. hmac_obj.update(struct.pack(">H", flen))
  687. hmac_obj.update(pkt.authenticator)
  688. hmac_obj.update(attrs)
  689. if self.t_events['double_msg_auth'].is_set():
  690. logger.info("Include two Message-Authenticator attributes")
  691. else:
  692. del reply[80]
  693. reply.AddAttribute("Message-Authenticator", hmac_obj.digest())
  694. self.SendReplyPacket(pkt.fd, reply)
  695. def RunWithStop(self, t_events):
  696. self._poll = select.poll()
  697. self._fdmap = {}
  698. self._PrepareSockets()
  699. self.t_events = t_events
  700. while not t_events['stop'].is_set():
  701. for (fd, event) in self._poll.poll(1000):
  702. if event == select.POLLIN:
  703. try:
  704. fdo = self._fdmap[fd]
  705. self._ProcessInput(fdo)
  706. except ServerPacketError as err:
  707. logger.info("pyrad server dropping packet: " + str(err))
  708. except pyrad.packet.PacketError as err:
  709. logger.info("pyrad server received invalid packet: " + str(err))
  710. else:
  711. logger.error("Unexpected event in pyrad server main loop")
  712. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  713. authport=18138, acctport=18139)
  714. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  715. "radius",
  716. "localhost")
  717. srv.BindToAddress("")
  718. t_events = {}
  719. t_events['stop'] = threading.Event()
  720. t_events['msg_auth'] = threading.Event()
  721. t_events['wrong_secret'] = threading.Event()
  722. t_events['double_msg_auth'] = threading.Event()
  723. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  724. t.start()
  725. try:
  726. params = hostapd.wpa2_eap_params(ssid="radius-test")
  727. params['auth_server_port'] = "18138"
  728. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  729. connect(dev[0], "radius-test", wait_connect=False)
  730. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
  731. if ev is None:
  732. raise Exception("Timeout on EAP start")
  733. time.sleep(1)
  734. dev[0].request("REMOVE_NETWORK all")
  735. time.sleep(0.1)
  736. dev[0].dump_monitor()
  737. t_events['msg_auth'].set()
  738. t_events['wrong_secret'].set()
  739. connect(dev[0], "radius-test", wait_connect=False)
  740. time.sleep(1)
  741. dev[0].request("REMOVE_NETWORK all")
  742. time.sleep(0.1)
  743. dev[0].dump_monitor()
  744. t_events['wrong_secret'].clear()
  745. connect(dev[0], "radius-test", wait_connect=False)
  746. time.sleep(1)
  747. dev[0].request("REMOVE_NETWORK all")
  748. time.sleep(0.1)
  749. dev[0].dump_monitor()
  750. t_events['double_msg_auth'].set()
  751. connect(dev[0], "radius-test", wait_connect=False)
  752. time.sleep(1)
  753. finally:
  754. t_events['stop'].set()
  755. t.join()
  756. def test_radius_psk(dev, apdev):
  757. """WPA2 with PSK from RADIUS"""
  758. try:
  759. import pyrad.server
  760. import pyrad.packet
  761. import pyrad.dictionary
  762. except ImportError:
  763. raise HwsimSkip("No pyrad modules available")
  764. class TestServer(pyrad.server.Server):
  765. def _HandleAuthPacket(self, pkt):
  766. pyrad.server.Server._HandleAuthPacket(self, pkt)
  767. logger.info("Received authentication request")
  768. reply = self.CreateReplyPacket(pkt)
  769. reply.code = pyrad.packet.AccessAccept
  770. a = "\xab\xcd"
  771. secret = reply.secret
  772. if self.t_events['long'].is_set():
  773. p = b'\x10' + "0123456789abcdef" + 15 * b'\x00'
  774. b = hashlib.md5(secret + pkt.authenticator + a).digest()
  775. pp = bytearray(p[0:16])
  776. bb = bytearray(b)
  777. cc = bytearray(pp[i] ^ bb[i] for i in range(len(bb)))
  778. b = hashlib.md5(reply.secret + bytes(cc)).digest()
  779. pp = bytearray(p[16:32])
  780. bb = bytearray(b)
  781. cc += bytearray(pp[i] ^ bb[i] for i in range(len(bb)))
  782. data = '\x00' + a + bytes(cc)
  783. else:
  784. p = b'\x08' + "12345678" + 7 * b'\x00'
  785. b = hashlib.md5(secret + pkt.authenticator + a).digest()
  786. pp = bytearray(p)
  787. bb = bytearray(b)
  788. cc = bytearray(pp[i] ^ bb[i] for i in range(len(bb)))
  789. data = '\x00' + a + bytes(cc)
  790. reply.AddAttribute("Tunnel-Password", data)
  791. self.SendReplyPacket(pkt.fd, reply)
  792. def RunWithStop(self, t_events):
  793. self._poll = select.poll()
  794. self._fdmap = {}
  795. self._PrepareSockets()
  796. self.t_events = t_events
  797. while not t_events['stop'].is_set():
  798. for (fd, event) in self._poll.poll(1000):
  799. if event == select.POLLIN:
  800. try:
  801. fdo = self._fdmap[fd]
  802. self._ProcessInput(fdo)
  803. except ServerPacketError as err:
  804. logger.info("pyrad server dropping packet: " + str(err))
  805. except pyrad.packet.PacketError as err:
  806. logger.info("pyrad server received invalid packet: " + str(err))
  807. else:
  808. logger.error("Unexpected event in pyrad server main loop")
  809. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  810. authport=18138, acctport=18139)
  811. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  812. "radius",
  813. "localhost")
  814. srv.BindToAddress("")
  815. t_events = {}
  816. t_events['stop'] = threading.Event()
  817. t_events['long'] = threading.Event()
  818. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  819. t.start()
  820. try:
  821. ssid = "test-wpa2-psk"
  822. params = hostapd.radius_params()
  823. params['ssid'] = ssid
  824. params["wpa"] = "2"
  825. params["wpa_key_mgmt"] = "WPA-PSK"
  826. params["rsn_pairwise"] = "CCMP"
  827. params['macaddr_acl'] = '2'
  828. params['wpa_psk_radius'] = '2'
  829. params['auth_server_port'] = "18138"
  830. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  831. dev[0].connect(ssid, psk="12345678", scan_freq="2412")
  832. t_events['long'].set()
  833. dev[1].connect(ssid, psk="0123456789abcdef", scan_freq="2412")
  834. finally:
  835. t_events['stop'].set()
  836. t.join()