test_radius.py 40 KB

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