test_radius.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. # RADIUS tests
  2. # Copyright (c) 2013-2016, 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. from remotehost import remote_compatible
  7. import binascii
  8. import hashlib
  9. import hmac
  10. import logging
  11. logger = logging.getLogger()
  12. import os
  13. import select
  14. import struct
  15. import subprocess
  16. import threading
  17. import time
  18. import hostapd
  19. from utils import HwsimSkip, require_under_vm, skip_with_fips, fail_test
  20. from test_ap_hs20 import build_dhcp_ack
  21. from test_ap_ft import ft_params1
  22. def connect(dev, ssid, wait_connect=True):
  23. dev.connect(ssid, key_mgmt="WPA-EAP", scan_freq="2412",
  24. eap="PSK", identity="psk.user@example.com",
  25. password_hex="0123456789abcdef0123456789abcdef",
  26. wait_connect=wait_connect)
  27. @remote_compatible
  28. def test_radius_auth_unreachable(dev, apdev):
  29. """RADIUS Authentication server unreachable"""
  30. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  31. params['auth_server_port'] = "18139"
  32. hapd = hostapd.add_ap(apdev[0], params)
  33. connect(dev[0], "radius-auth", wait_connect=False)
  34. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
  35. if ev is None:
  36. raise Exception("Timeout on EAP start")
  37. logger.info("Checking for RADIUS retries")
  38. time.sleep(4)
  39. mib = hapd.get_mib()
  40. if "radiusAuthClientAccessRequests" not in mib:
  41. raise Exception("Missing MIB fields")
  42. if int(mib["radiusAuthClientAccessRetransmissions"]) < 1:
  43. raise Exception("Missing RADIUS Authentication retransmission")
  44. if int(mib["radiusAuthClientPendingRequests"]) < 1:
  45. raise Exception("Missing pending RADIUS Authentication request")
  46. def test_radius_auth_unreachable2(dev, apdev):
  47. """RADIUS Authentication server unreachable (2)"""
  48. subprocess.call(['ip', 'ro', 'replace', '192.168.213.17', 'dev', 'lo'])
  49. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  50. params['auth_server_addr'] = "192.168.213.17"
  51. params['auth_server_port'] = "18139"
  52. hapd = hostapd.add_ap(apdev[0], params)
  53. subprocess.call(['ip', 'ro', 'del', '192.168.213.17', 'dev', 'lo'])
  54. connect(dev[0], "radius-auth", wait_connect=False)
  55. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
  56. if ev is None:
  57. raise Exception("Timeout on EAP start")
  58. logger.info("Checking for RADIUS retries")
  59. time.sleep(4)
  60. mib = hapd.get_mib()
  61. if "radiusAuthClientAccessRequests" not in mib:
  62. raise Exception("Missing MIB fields")
  63. if int(mib["radiusAuthClientAccessRetransmissions"]) < 1:
  64. raise Exception("Missing RADIUS Authentication retransmission")
  65. def test_radius_auth_unreachable3(dev, apdev):
  66. """RADIUS Authentication server initially unreachable, but then available"""
  67. subprocess.call(['ip', 'ro', 'replace', 'blackhole', '192.168.213.18'])
  68. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  69. params['auth_server_addr'] = "192.168.213.18"
  70. hapd = hostapd.add_ap(apdev[0], params)
  71. connect(dev[0], "radius-auth", wait_connect=False)
  72. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
  73. if ev is None:
  74. raise Exception("Timeout on EAP start")
  75. subprocess.call(['ip', 'ro', 'del', 'blackhole', '192.168.213.18'])
  76. time.sleep(0.1)
  77. dev[0].request("DISCONNECT")
  78. hapd.set('auth_server_addr_replace', '127.0.0.1')
  79. dev[0].request("RECONNECT")
  80. dev[0].wait_connected()
  81. def test_radius_acct_unreachable(dev, apdev):
  82. """RADIUS Accounting server unreachable"""
  83. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  84. params['acct_server_addr'] = "127.0.0.1"
  85. params['acct_server_port'] = "18139"
  86. params['acct_server_shared_secret'] = "radius"
  87. hapd = hostapd.add_ap(apdev[0], params)
  88. connect(dev[0], "radius-acct")
  89. logger.info("Checking for RADIUS retries")
  90. time.sleep(4)
  91. mib = hapd.get_mib()
  92. if "radiusAccClientRetransmissions" not in mib:
  93. raise Exception("Missing MIB fields")
  94. if int(mib["radiusAccClientRetransmissions"]) < 2:
  95. raise Exception("Missing RADIUS Accounting retransmissions")
  96. if int(mib["radiusAccClientPendingRequests"]) < 2:
  97. raise Exception("Missing pending RADIUS Accounting requests")
  98. def test_radius_acct_unreachable2(dev, apdev):
  99. """RADIUS Accounting server unreachable(2)"""
  100. subprocess.call(['ip', 'ro', 'replace', '192.168.213.17', 'dev', 'lo'])
  101. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  102. params['acct_server_addr'] = "192.168.213.17"
  103. params['acct_server_port'] = "18139"
  104. params['acct_server_shared_secret'] = "radius"
  105. hapd = hostapd.add_ap(apdev[0], params)
  106. subprocess.call(['ip', 'ro', 'del', '192.168.213.17', 'dev', 'lo'])
  107. connect(dev[0], "radius-acct")
  108. logger.info("Checking for RADIUS retries")
  109. time.sleep(4)
  110. mib = hapd.get_mib()
  111. if "radiusAccClientRetransmissions" not in mib:
  112. raise Exception("Missing MIB fields")
  113. if int(mib["radiusAccClientRetransmissions"]) < 1 and int(mib["radiusAccClientPendingRequests"]) < 1:
  114. raise Exception("Missing pending or retransmitted RADIUS Accounting requests")
  115. def test_radius_acct_unreachable3(dev, apdev):
  116. """RADIUS Accounting server initially unreachable, but then available"""
  117. require_under_vm()
  118. subprocess.call(['ip', 'ro', 'replace', 'blackhole', '192.168.213.18'])
  119. as_hapd = hostapd.Hostapd("as")
  120. as_mib_start = as_hapd.get_mib(param="radius_server")
  121. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  122. params['acct_server_addr'] = "192.168.213.18"
  123. params['acct_server_port'] = "1813"
  124. params['acct_server_shared_secret'] = "radius"
  125. hapd = hostapd.add_ap(apdev[0], params)
  126. connect(dev[0], "radius-acct")
  127. subprocess.call(['ip', 'ro', 'del', 'blackhole', '192.168.213.18'])
  128. time.sleep(0.1)
  129. dev[0].request("DISCONNECT")
  130. hapd.set('acct_server_addr_replace', '127.0.0.1')
  131. dev[0].request("RECONNECT")
  132. dev[0].wait_connected()
  133. time.sleep(1)
  134. as_mib_end = as_hapd.get_mib(param="radius_server")
  135. req_s = int(as_mib_start['radiusAccServTotalResponses'])
  136. req_e = int(as_mib_end['radiusAccServTotalResponses'])
  137. if req_e <= req_s:
  138. raise Exception("Unexpected RADIUS server acct MIB value")
  139. def test_radius_acct_unreachable4(dev, apdev):
  140. """RADIUS Accounting server unreachable and multiple STAs"""
  141. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  142. params['acct_server_addr'] = "127.0.0.1"
  143. params['acct_server_port'] = "18139"
  144. params['acct_server_shared_secret'] = "radius"
  145. hapd = hostapd.add_ap(apdev[0], params)
  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. "62:d:1" ]
  160. params['radius_acct_req_attr'] = [ "126:s:Operator", "62:d:1",
  161. "77:s:testing" ]
  162. hapd = hostapd.add_ap(apdev[0], params)
  163. connect(dev[0], "radius-acct")
  164. dev[1].connect("radius-acct", key_mgmt="WPA-EAP", scan_freq="2412",
  165. eap="PAX", identity="test-class",
  166. password_hex="0123456789abcdef0123456789abcdef")
  167. dev[2].connect("radius-acct", key_mgmt="WPA-EAP",
  168. eap="GPSK", identity="gpsk-cui",
  169. password="abcdefghijklmnop0123456789abcdef",
  170. scan_freq="2412")
  171. logger.info("Checking for RADIUS counters")
  172. count = 0
  173. while True:
  174. mib = hapd.get_mib()
  175. if int(mib['radiusAccClientResponses']) >= 3:
  176. break
  177. time.sleep(0.1)
  178. count += 1
  179. if count > 10:
  180. raise Exception("Did not receive Accounting-Response packets")
  181. if int(mib['radiusAccClientRetransmissions']) > 0:
  182. raise Exception("Unexpected Accounting-Request retransmission")
  183. as_mib_end = as_hapd.get_mib(param="radius_server")
  184. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  185. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  186. if req_e < req_s + 2:
  187. raise Exception("Unexpected RADIUS server acct MIB value")
  188. acc_s = int(as_mib_start['radiusAuthServAccessAccepts'])
  189. acc_e = int(as_mib_end['radiusAuthServAccessAccepts'])
  190. if acc_e < acc_s + 1:
  191. raise Exception("Unexpected RADIUS server auth MIB value")
  192. def test_radius_acct_non_ascii_ssid(dev, apdev):
  193. """RADIUS Accounting and non-ASCII SSID"""
  194. params = hostapd.wpa2_eap_params()
  195. params['acct_server_addr'] = "127.0.0.1"
  196. params['acct_server_port'] = "1813"
  197. params['acct_server_shared_secret'] = "radius"
  198. ssid2 = "740665007374"
  199. params['ssid2'] = ssid2
  200. hostapd.add_ap(apdev[0], params)
  201. dev[0].connect(ssid2=ssid2, key_mgmt="WPA-EAP", scan_freq="2412",
  202. eap="PSK", identity="psk.user@example.com",
  203. password_hex="0123456789abcdef0123456789abcdef")
  204. def test_radius_acct_pmksa_caching(dev, apdev):
  205. """RADIUS Accounting with PMKSA caching"""
  206. as_hapd = hostapd.Hostapd("as")
  207. as_mib_start = as_hapd.get_mib(param="radius_server")
  208. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  209. params['acct_server_addr'] = "127.0.0.1"
  210. params['acct_server_port'] = "1813"
  211. params['acct_server_shared_secret'] = "radius"
  212. hapd = hostapd.add_ap(apdev[0], params)
  213. connect(dev[0], "radius-acct")
  214. dev[1].connect("radius-acct", key_mgmt="WPA-EAP", scan_freq="2412",
  215. eap="PAX", identity="test-class",
  216. password_hex="0123456789abcdef0123456789abcdef")
  217. for d in [ dev[0], dev[1] ]:
  218. d.request("REASSOCIATE")
  219. d.wait_connected(timeout=15, error="Reassociation timed out")
  220. count = 0
  221. while True:
  222. mib = hapd.get_mib()
  223. if int(mib['radiusAccClientResponses']) >= 4:
  224. break
  225. time.sleep(0.1)
  226. count += 1
  227. if count > 10:
  228. raise Exception("Did not receive Accounting-Response packets")
  229. if int(mib['radiusAccClientRetransmissions']) > 0:
  230. raise Exception("Unexpected Accounting-Request retransmission")
  231. as_mib_end = as_hapd.get_mib(param="radius_server")
  232. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  233. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  234. if req_e < req_s + 2:
  235. raise Exception("Unexpected RADIUS server acct MIB value")
  236. acc_s = int(as_mib_start['radiusAuthServAccessAccepts'])
  237. acc_e = int(as_mib_end['radiusAuthServAccessAccepts'])
  238. if acc_e < acc_s + 1:
  239. raise Exception("Unexpected RADIUS server auth MIB value")
  240. def test_radius_acct_interim(dev, apdev):
  241. """RADIUS Accounting interim update"""
  242. as_hapd = hostapd.Hostapd("as")
  243. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  244. params['acct_server_addr'] = "127.0.0.1"
  245. params['acct_server_port'] = "1813"
  246. params['acct_server_shared_secret'] = "radius"
  247. params['radius_acct_interim_interval'] = "1"
  248. hapd = hostapd.add_ap(apdev[0], params)
  249. connect(dev[0], "radius-acct")
  250. logger.info("Checking for RADIUS counters")
  251. as_mib_start = as_hapd.get_mib(param="radius_server")
  252. time.sleep(3.1)
  253. as_mib_end = as_hapd.get_mib(param="radius_server")
  254. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  255. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  256. if req_e < req_s + 3:
  257. raise Exception("Unexpected RADIUS server acct MIB value")
  258. def test_radius_acct_interim_unreachable(dev, apdev):
  259. """RADIUS Accounting interim update with unreachable server"""
  260. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  261. params['acct_server_addr'] = "127.0.0.1"
  262. params['acct_server_port'] = "18139"
  263. params['acct_server_shared_secret'] = "radius"
  264. params['radius_acct_interim_interval'] = "1"
  265. hapd = hostapd.add_ap(apdev[0], params)
  266. start = hapd.get_mib()
  267. connect(dev[0], "radius-acct")
  268. logger.info("Waiting for interium accounting updates")
  269. time.sleep(3.1)
  270. end = hapd.get_mib()
  271. req_s = int(start['radiusAccClientTimeouts'])
  272. req_e = int(end['radiusAccClientTimeouts'])
  273. if req_e < req_s + 2:
  274. raise Exception("Unexpected RADIUS server acct MIB value")
  275. def test_radius_acct_interim_unreachable2(dev, apdev):
  276. """RADIUS Accounting interim update with unreachable server (retry)"""
  277. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  278. params['acct_server_addr'] = "127.0.0.1"
  279. params['acct_server_port'] = "18139"
  280. params['acct_server_shared_secret'] = "radius"
  281. # Use long enough interim update interval to allow RADIUS retransmission
  282. # case (3 seconds) to trigger first.
  283. params['radius_acct_interim_interval'] = "4"
  284. hapd = hostapd.add_ap(apdev[0], params)
  285. start = hapd.get_mib()
  286. connect(dev[0], "radius-acct")
  287. logger.info("Waiting for interium accounting updates")
  288. time.sleep(7.5)
  289. end = hapd.get_mib()
  290. req_s = int(start['radiusAccClientTimeouts'])
  291. req_e = int(end['radiusAccClientTimeouts'])
  292. if req_e < req_s + 2:
  293. raise Exception("Unexpected RADIUS server acct MIB value")
  294. def test_radius_acct_ipaddr(dev, apdev):
  295. """RADIUS Accounting and Framed-IP-Address"""
  296. try:
  297. _test_radius_acct_ipaddr(dev, apdev)
  298. finally:
  299. subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
  300. stderr=open('/dev/null', 'w'))
  301. subprocess.call(['brctl', 'delbr', 'ap-br0'],
  302. stderr=open('/dev/null', 'w'))
  303. def _test_radius_acct_ipaddr(dev, apdev):
  304. params = { "ssid": "radius-acct-open",
  305. 'acct_server_addr': "127.0.0.1",
  306. 'acct_server_port': "1813",
  307. 'acct_server_shared_secret': "radius",
  308. 'proxy_arp': '1',
  309. 'ap_isolate': '1',
  310. 'bridge': 'ap-br0' }
  311. hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
  312. try:
  313. hapd.enable()
  314. except:
  315. # For now, do not report failures due to missing kernel support
  316. raise HwsimSkip("Could not start hostapd - assume proxyarp not supported in kernel version")
  317. bssid = apdev[0]['bssid']
  318. subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
  319. subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
  320. dev[0].connect("radius-acct-open", key_mgmt="NONE", scan_freq="2412")
  321. addr0 = dev[0].own_addr()
  322. pkt = build_dhcp_ack(dst_ll="ff:ff:ff:ff:ff:ff", src_ll=bssid,
  323. ip_src="192.168.1.1", ip_dst="255.255.255.255",
  324. yiaddr="192.168.1.123", chaddr=addr0)
  325. if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
  326. raise Exception("DATA_TEST_FRAME failed")
  327. dev[0].request("DISCONNECT")
  328. dev[0].wait_disconnected()
  329. hapd.disable()
  330. def send_and_check_reply(srv, req, code, error_cause=0):
  331. reply = srv.SendPacket(req)
  332. logger.debug("RADIUS response from hostapd")
  333. for i in reply.keys():
  334. logger.debug("%s: %s" % (i, reply[i]))
  335. if reply.code != code:
  336. raise Exception("Unexpected response code")
  337. if error_cause:
  338. if 'Error-Cause' not in reply:
  339. raise Exception("Missing Error-Cause")
  340. if reply['Error-Cause'][0] != error_cause:
  341. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  342. def test_radius_acct_psk(dev, apdev):
  343. """RADIUS Accounting - PSK"""
  344. as_hapd = hostapd.Hostapd("as")
  345. params = hostapd.wpa2_params(ssid="radius-acct", passphrase="12345678")
  346. params['acct_server_addr'] = "127.0.0.1"
  347. params['acct_server_port'] = "1813"
  348. params['acct_server_shared_secret'] = "radius"
  349. hapd = hostapd.add_ap(apdev[0], params)
  350. dev[0].connect("radius-acct", psk="12345678", scan_freq="2412")
  351. def test_radius_acct_psk_sha256(dev, apdev):
  352. """RADIUS Accounting - PSK SHA256"""
  353. as_hapd = hostapd.Hostapd("as")
  354. params = hostapd.wpa2_params(ssid="radius-acct", passphrase="12345678")
  355. params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
  356. params['acct_server_addr'] = "127.0.0.1"
  357. params['acct_server_port'] = "1813"
  358. params['acct_server_shared_secret'] = "radius"
  359. hapd = hostapd.add_ap(apdev[0], params)
  360. dev[0].connect("radius-acct", key_mgmt="WPA-PSK-SHA256",
  361. psk="12345678", scan_freq="2412")
  362. def test_radius_acct_ft_psk(dev, apdev):
  363. """RADIUS Accounting - FT-PSK"""
  364. as_hapd = hostapd.Hostapd("as")
  365. params = ft_params1(ssid="radius-acct", passphrase="12345678")
  366. params['acct_server_addr'] = "127.0.0.1"
  367. params['acct_server_port'] = "1813"
  368. params['acct_server_shared_secret'] = "radius"
  369. hapd = hostapd.add_ap(apdev[0], params)
  370. dev[0].connect("radius-acct", key_mgmt="FT-PSK",
  371. psk="12345678", scan_freq="2412")
  372. def test_radius_acct_ieee8021x(dev, apdev):
  373. """RADIUS Accounting - IEEE 802.1X"""
  374. skip_with_fips(dev[0])
  375. as_hapd = hostapd.Hostapd("as")
  376. params = hostapd.radius_params()
  377. params["ssid"] = "radius-acct-1x"
  378. params["ieee8021x"] = "1"
  379. params["wep_key_len_broadcast"] = "13"
  380. params["wep_key_len_unicast"] = "13"
  381. params['acct_server_addr'] = "127.0.0.1"
  382. params['acct_server_port'] = "1813"
  383. params['acct_server_shared_secret'] = "radius"
  384. hapd = hostapd.add_ap(apdev[0], params)
  385. dev[0].connect("radius-acct-1x", key_mgmt="IEEE8021X", eap="PSK",
  386. identity="psk.user@example.com",
  387. password_hex="0123456789abcdef0123456789abcdef",
  388. scan_freq="2412")
  389. def test_radius_das_disconnect(dev, apdev):
  390. """RADIUS Dynamic Authorization Extensions - Disconnect"""
  391. try:
  392. import pyrad.client
  393. import pyrad.packet
  394. import pyrad.dictionary
  395. import radius_das
  396. except ImportError:
  397. raise HwsimSkip("No pyrad modules available")
  398. params = hostapd.wpa2_eap_params(ssid="radius-das")
  399. params['radius_das_port'] = "3799"
  400. params['radius_das_client'] = "127.0.0.1 secret"
  401. params['radius_das_require_event_timestamp'] = "1"
  402. params['own_ip_addr'] = "127.0.0.1"
  403. params['nas_identifier'] = "nas.example.com"
  404. hapd = hostapd.add_ap(apdev[0], params)
  405. connect(dev[0], "radius-das")
  406. addr = dev[0].p2p_interface_addr()
  407. sta = hapd.get_sta(addr)
  408. id = sta['dot1xAuthSessionId']
  409. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  410. srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
  411. secret="secret", dict=dict)
  412. srv.retries = 1
  413. srv.timeout = 1
  414. logger.info("Disconnect-Request with incorrect secret")
  415. req = radius_das.DisconnectPacket(dict=dict, secret="incorrect",
  416. User_Name="foo",
  417. NAS_Identifier="localhost",
  418. Event_Timestamp=int(time.time()))
  419. logger.debug(req)
  420. try:
  421. reply = srv.SendPacket(req)
  422. raise Exception("Unexpected response to Disconnect-Request")
  423. except pyrad.client.Timeout:
  424. logger.info("Disconnect-Request with incorrect secret properly ignored")
  425. logger.info("Disconnect-Request without Event-Timestamp")
  426. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  427. User_Name="psk.user@example.com")
  428. logger.debug(req)
  429. try:
  430. reply = srv.SendPacket(req)
  431. raise Exception("Unexpected response to Disconnect-Request")
  432. except pyrad.client.Timeout:
  433. logger.info("Disconnect-Request without Event-Timestamp properly ignored")
  434. logger.info("Disconnect-Request with non-matching Event-Timestamp")
  435. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  436. User_Name="psk.user@example.com",
  437. Event_Timestamp=123456789)
  438. logger.debug(req)
  439. try:
  440. reply = srv.SendPacket(req)
  441. raise Exception("Unexpected response to Disconnect-Request")
  442. except pyrad.client.Timeout:
  443. logger.info("Disconnect-Request with non-matching Event-Timestamp properly ignored")
  444. logger.info("Disconnect-Request with unsupported attribute")
  445. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  446. User_Name="foo",
  447. User_Password="foo",
  448. Event_Timestamp=int(time.time()))
  449. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 401)
  450. logger.info("Disconnect-Request with invalid Calling-Station-Id")
  451. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  452. User_Name="foo",
  453. Calling_Station_Id="foo",
  454. Event_Timestamp=int(time.time()))
  455. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 407)
  456. logger.info("Disconnect-Request with mismatching User-Name")
  457. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  458. User_Name="foo",
  459. Event_Timestamp=int(time.time()))
  460. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)
  461. logger.info("Disconnect-Request with mismatching Calling-Station-Id")
  462. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  463. Calling_Station_Id="12:34:56:78:90:aa",
  464. Event_Timestamp=int(time.time()))
  465. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)
  466. logger.info("Disconnect-Request with mismatching Acct-Session-Id")
  467. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  468. Acct_Session_Id="12345678-87654321",
  469. Event_Timestamp=int(time.time()))
  470. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)
  471. logger.info("Disconnect-Request with mismatching Acct-Session-Id (len)")
  472. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  473. Acct_Session_Id="12345678",
  474. Event_Timestamp=int(time.time()))
  475. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)
  476. logger.info("Disconnect-Request with mismatching Acct-Multi-Session-Id")
  477. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  478. Acct_Multi_Session_Id="12345678+87654321",
  479. Event_Timestamp=int(time.time()))
  480. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)
  481. logger.info("Disconnect-Request with mismatching Acct-Multi-Session-Id (len)")
  482. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  483. Acct_Multi_Session_Id="12345678",
  484. Event_Timestamp=int(time.time()))
  485. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)
  486. logger.info("Disconnect-Request with no session identification attributes")
  487. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  488. Event_Timestamp=int(time.time()))
  489. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)
  490. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  491. if ev is not None:
  492. raise Exception("Unexpected disconnection")
  493. logger.info("Disconnect-Request with mismatching NAS-IP-Address")
  494. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  495. NAS_IP_Address="192.168.3.4",
  496. Acct_Session_Id=id,
  497. Event_Timestamp=int(time.time()))
  498. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 403)
  499. logger.info("Disconnect-Request with mismatching NAS-Identifier")
  500. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  501. NAS_Identifier="unknown.example.com",
  502. Acct_Session_Id=id,
  503. Event_Timestamp=int(time.time()))
  504. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 403)
  505. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  506. if ev is not None:
  507. raise Exception("Unexpected disconnection")
  508. logger.info("Disconnect-Request with matching Acct-Session-Id")
  509. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  510. NAS_IP_Address="127.0.0.1",
  511. NAS_Identifier="nas.example.com",
  512. Acct_Session_Id=id,
  513. Event_Timestamp=int(time.time()))
  514. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  515. dev[0].wait_disconnected(timeout=10)
  516. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  517. logger.info("Disconnect-Request with matching Acct-Multi-Session-Id")
  518. sta = hapd.get_sta(addr)
  519. multi_sess_id = sta['authMultiSessionId']
  520. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  521. NAS_IP_Address="127.0.0.1",
  522. NAS_Identifier="nas.example.com",
  523. Acct_Multi_Session_Id=multi_sess_id,
  524. Event_Timestamp=int(time.time()))
  525. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  526. dev[0].wait_disconnected(timeout=10)
  527. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  528. logger.info("Disconnect-Request with matching User-Name")
  529. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  530. NAS_Identifier="nas.example.com",
  531. User_Name="psk.user@example.com",
  532. Event_Timestamp=int(time.time()))
  533. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  534. dev[0].wait_disconnected(timeout=10)
  535. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  536. logger.info("Disconnect-Request with matching Calling-Station-Id")
  537. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  538. NAS_IP_Address="127.0.0.1",
  539. Calling_Station_Id=addr,
  540. Event_Timestamp=int(time.time()))
  541. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  542. dev[0].wait_disconnected(timeout=10)
  543. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", "CTRL-EVENT-CONNECTED"])
  544. if ev is None:
  545. raise Exception("Timeout while waiting for re-connection")
  546. if "CTRL-EVENT-EAP-STARTED" not in ev:
  547. raise Exception("Unexpected skipping of EAP authentication in reconnection")
  548. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  549. logger.info("Disconnect-Request with matching Calling-Station-Id and non-matching CUI")
  550. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  551. Calling_Station_Id=addr,
  552. Chargeable_User_Identity="foo@example.com",
  553. Event_Timestamp=int(time.time()))
  554. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, error_cause=503)
  555. logger.info("Disconnect-Request with matching CUI")
  556. dev[1].connect("radius-das", key_mgmt="WPA-EAP",
  557. eap="GPSK", identity="gpsk-cui",
  558. password="abcdefghijklmnop0123456789abcdef",
  559. scan_freq="2412")
  560. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  561. Chargeable_User_Identity="gpsk-chargeable-user-identity",
  562. Event_Timestamp=int(time.time()))
  563. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  564. dev[1].wait_disconnected(timeout=10)
  565. dev[1].wait_connected(timeout=10, error="Re-connection timed out")
  566. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  567. if ev is not None:
  568. raise Exception("Unexpected disconnection")
  569. connect(dev[2], "radius-das")
  570. logger.info("Disconnect-Request with matching User-Name - multiple sessions matching")
  571. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  572. NAS_Identifier="nas.example.com",
  573. User_Name="psk.user@example.com",
  574. Event_Timestamp=int(time.time()))
  575. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, error_cause=508)
  576. logger.info("Disconnect-Request with User-Name matching multiple sessions, Calling-Station-Id only one")
  577. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  578. NAS_Identifier="nas.example.com",
  579. Calling_Station_Id=addr,
  580. User_Name="psk.user@example.com",
  581. Event_Timestamp=int(time.time()))
  582. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  583. dev[0].wait_disconnected(timeout=10)
  584. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  585. ev = dev[2].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  586. if ev is not None:
  587. raise Exception("Unexpected disconnection")
  588. logger.info("Disconnect-Request with matching Acct-Multi-Session-Id after disassociation")
  589. sta = hapd.get_sta(addr)
  590. multi_sess_id = sta['authMultiSessionId']
  591. dev[0].request("DISCONNECT")
  592. dev[0].wait_disconnected(timeout=10)
  593. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  594. NAS_IP_Address="127.0.0.1",
  595. NAS_Identifier="nas.example.com",
  596. Acct_Multi_Session_Id=multi_sess_id,
  597. Event_Timestamp=int(time.time()))
  598. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  599. dev[0].request("RECONNECT")
  600. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
  601. if ev is None:
  602. raise Exception("Timeout on EAP start")
  603. dev[0].wait_connected(timeout=15)
  604. logger.info("Disconnect-Request with matching User-Name after disassociation")
  605. dev[0].request("DISCONNECT")
  606. dev[0].wait_disconnected(timeout=10)
  607. dev[2].request("DISCONNECT")
  608. dev[2].wait_disconnected(timeout=10)
  609. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  610. NAS_IP_Address="127.0.0.1",
  611. NAS_Identifier="nas.example.com",
  612. User_Name="psk.user@example.com",
  613. Event_Timestamp=int(time.time()))
  614. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  615. logger.info("Disconnect-Request with matching CUI after disassociation")
  616. dev[1].request("DISCONNECT")
  617. dev[1].wait_disconnected(timeout=10)
  618. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  619. NAS_IP_Address="127.0.0.1",
  620. NAS_Identifier="nas.example.com",
  621. Chargeable_User_Identity="gpsk-chargeable-user-identity",
  622. Event_Timestamp=int(time.time()))
  623. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  624. logger.info("Disconnect-Request with matching Calling-Station-Id after disassociation")
  625. dev[0].request("RECONNECT")
  626. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
  627. if ev is None:
  628. raise Exception("Timeout on EAP start")
  629. dev[0].wait_connected(timeout=15)
  630. dev[0].request("DISCONNECT")
  631. dev[0].wait_disconnected(timeout=10)
  632. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  633. NAS_IP_Address="127.0.0.1",
  634. NAS_Identifier="nas.example.com",
  635. Calling_Station_Id=addr,
  636. Event_Timestamp=int(time.time()))
  637. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  638. logger.info("Disconnect-Request with mismatching Calling-Station-Id after disassociation")
  639. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  640. NAS_IP_Address="127.0.0.1",
  641. NAS_Identifier="nas.example.com",
  642. Calling_Station_Id=addr,
  643. Event_Timestamp=int(time.time()))
  644. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, error_cause=503)
  645. def test_radius_das_coa(dev, apdev):
  646. """RADIUS Dynamic Authorization Extensions - CoA"""
  647. try:
  648. import pyrad.client
  649. import pyrad.packet
  650. import pyrad.dictionary
  651. import radius_das
  652. except ImportError:
  653. raise HwsimSkip("No pyrad modules available")
  654. params = hostapd.wpa2_eap_params(ssid="radius-das")
  655. params['radius_das_port'] = "3799"
  656. params['radius_das_client'] = "127.0.0.1 secret"
  657. params['radius_das_require_event_timestamp'] = "1"
  658. hapd = hostapd.add_ap(apdev[0], params)
  659. connect(dev[0], "radius-das")
  660. addr = dev[0].p2p_interface_addr()
  661. sta = hapd.get_sta(addr)
  662. id = sta['dot1xAuthSessionId']
  663. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  664. srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
  665. secret="secret", dict=dict)
  666. srv.retries = 1
  667. srv.timeout = 1
  668. # hostapd does not currently support CoA-Request, so NAK is expected
  669. logger.info("CoA-Request with matching Acct-Session-Id")
  670. req = radius_das.CoAPacket(dict=dict, secret="secret",
  671. Acct_Session_Id=id,
  672. Event_Timestamp=int(time.time()))
  673. send_and_check_reply(srv, req, pyrad.packet.CoANAK, error_cause=405)
  674. def test_radius_ipv6(dev, apdev):
  675. """RADIUS connection over IPv6"""
  676. params = {}
  677. params['ssid'] = 'as'
  678. params['beacon_int'] = '2000'
  679. params['radius_server_clients'] = 'auth_serv/radius_clients_ipv6.conf'
  680. params['radius_server_ipv6'] = '1'
  681. params['radius_server_auth_port'] = '18129'
  682. params['radius_server_acct_port'] = '18139'
  683. params['eap_server'] = '1'
  684. params['eap_user_file'] = 'auth_serv/eap_user.conf'
  685. params['ca_cert'] = 'auth_serv/ca.pem'
  686. params['server_cert'] = 'auth_serv/server.pem'
  687. params['private_key'] = 'auth_serv/server.key'
  688. hostapd.add_ap(apdev[1], params)
  689. params = hostapd.wpa2_eap_params(ssid="radius-ipv6")
  690. params['auth_server_addr'] = "::0"
  691. params['auth_server_port'] = "18129"
  692. params['acct_server_addr'] = "::0"
  693. params['acct_server_port'] = "18139"
  694. params['acct_server_shared_secret'] = "radius"
  695. params['own_ip_addr'] = "::0"
  696. hostapd.add_ap(apdev[0], params)
  697. connect(dev[0], "radius-ipv6")
  698. def test_radius_macacl(dev, apdev):
  699. """RADIUS MAC ACL"""
  700. params = hostapd.radius_params()
  701. params["ssid"] = "radius"
  702. params["macaddr_acl"] = "2"
  703. hostapd.add_ap(apdev[0], params)
  704. dev[0].connect("radius", key_mgmt="NONE", scan_freq="2412")
  705. # Invalid VLAN ID from RADIUS server
  706. dev[2].connect("radius", key_mgmt="NONE", scan_freq="2412")
  707. dev[2].request("REMOVE_NETWORK all")
  708. dev[2].wait_disconnected()
  709. dev[2].connect("radius", key_mgmt="NONE", scan_freq="2412")
  710. def test_radius_macacl_acct(dev, apdev):
  711. """RADIUS MAC ACL and accounting enabled"""
  712. params = hostapd.radius_params()
  713. params["ssid"] = "radius"
  714. params["macaddr_acl"] = "2"
  715. params['acct_server_addr'] = "127.0.0.1"
  716. params['acct_server_port'] = "1813"
  717. params['acct_server_shared_secret'] = "radius"
  718. hostapd.add_ap(apdev[0], params)
  719. dev[0].connect("radius", key_mgmt="NONE", scan_freq="2412")
  720. dev[1].connect("radius", key_mgmt="NONE", scan_freq="2412")
  721. dev[1].request("DISCONNECT")
  722. dev[1].wait_disconnected()
  723. dev[1].request("RECONNECT")
  724. def test_radius_failover(dev, apdev):
  725. """RADIUS Authentication and Accounting server failover"""
  726. subprocess.call(['ip', 'ro', 'replace', '192.168.213.17', 'dev', 'lo'])
  727. as_hapd = hostapd.Hostapd("as")
  728. as_mib_start = as_hapd.get_mib(param="radius_server")
  729. params = hostapd.wpa2_eap_params(ssid="radius-failover")
  730. params["auth_server_addr"] = "192.168.213.17"
  731. params["auth_server_port"] = "1812"
  732. params["auth_server_shared_secret"] = "testing"
  733. params['acct_server_addr'] = "192.168.213.17"
  734. params['acct_server_port'] = "1813"
  735. params['acct_server_shared_secret'] = "testing"
  736. params['radius_retry_primary_interval'] = "20"
  737. hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
  738. hapd.set("auth_server_addr", "127.0.0.1")
  739. hapd.set("auth_server_port", "1812")
  740. hapd.set("auth_server_shared_secret", "radius")
  741. hapd.set('acct_server_addr', "127.0.0.1")
  742. hapd.set('acct_server_port', "1813")
  743. hapd.set('acct_server_shared_secret', "radius")
  744. hapd.enable()
  745. ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=30)
  746. if ev is None:
  747. raise Exception("AP startup timed out")
  748. if "AP-ENABLED" not in ev:
  749. raise Exception("AP startup failed")
  750. start = os.times()[4]
  751. try:
  752. subprocess.call(['ip', 'ro', 'replace', 'prohibit', '192.168.213.17'])
  753. dev[0].request("SET EAPOL::authPeriod 5")
  754. connect(dev[0], "radius-failover", wait_connect=False)
  755. dev[0].wait_connected(timeout=20)
  756. finally:
  757. dev[0].request("SET EAPOL::authPeriod 30")
  758. subprocess.call(['ip', 'ro', 'del', '192.168.213.17'])
  759. as_mib_end = as_hapd.get_mib(param="radius_server")
  760. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  761. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  762. if req_e <= req_s:
  763. raise Exception("Unexpected RADIUS server acct MIB value")
  764. end = os.times()[4]
  765. try:
  766. subprocess.call(['ip', 'ro', 'replace', 'prohibit', '192.168.213.17'])
  767. dev[1].request("SET EAPOL::authPeriod 5")
  768. if end - start < 21:
  769. time.sleep(21 - (end - start))
  770. connect(dev[1], "radius-failover", wait_connect=False)
  771. dev[1].wait_connected(timeout=20)
  772. finally:
  773. dev[1].request("SET EAPOL::authPeriod 30")
  774. subprocess.call(['ip', 'ro', 'del', '192.168.213.17'])
  775. def run_pyrad_server(srv, t_events):
  776. srv.RunWithStop(t_events)
  777. def test_radius_protocol(dev, apdev):
  778. """RADIUS Authentication protocol tests with a fake server"""
  779. try:
  780. import pyrad.server
  781. import pyrad.packet
  782. import pyrad.dictionary
  783. except ImportError:
  784. raise HwsimSkip("No pyrad modules available")
  785. class TestServer(pyrad.server.Server):
  786. def _HandleAuthPacket(self, pkt):
  787. pyrad.server.Server._HandleAuthPacket(self, pkt)
  788. logger.info("Received authentication request")
  789. reply = self.CreateReplyPacket(pkt)
  790. reply.code = pyrad.packet.AccessAccept
  791. if self.t_events['msg_auth'].is_set():
  792. logger.info("Add Message-Authenticator")
  793. if self.t_events['wrong_secret'].is_set():
  794. logger.info("Use incorrect RADIUS shared secret")
  795. pw = "incorrect"
  796. else:
  797. pw = reply.secret
  798. hmac_obj = hmac.new(pw)
  799. hmac_obj.update(struct.pack("B", reply.code))
  800. hmac_obj.update(struct.pack("B", reply.id))
  801. # reply attributes
  802. reply.AddAttribute("Message-Authenticator",
  803. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
  804. attrs = reply._PktEncodeAttributes()
  805. # Length
  806. flen = 4 + 16 + len(attrs)
  807. hmac_obj.update(struct.pack(">H", flen))
  808. hmac_obj.update(pkt.authenticator)
  809. hmac_obj.update(attrs)
  810. if self.t_events['double_msg_auth'].is_set():
  811. logger.info("Include two Message-Authenticator attributes")
  812. else:
  813. del reply[80]
  814. reply.AddAttribute("Message-Authenticator", hmac_obj.digest())
  815. self.SendReplyPacket(pkt.fd, reply)
  816. def RunWithStop(self, t_events):
  817. self._poll = select.poll()
  818. self._fdmap = {}
  819. self._PrepareSockets()
  820. self.t_events = t_events
  821. while not t_events['stop'].is_set():
  822. for (fd, event) in self._poll.poll(1000):
  823. if event == select.POLLIN:
  824. try:
  825. fdo = self._fdmap[fd]
  826. self._ProcessInput(fdo)
  827. except pyrad.server.ServerPacketError as err:
  828. logger.info("pyrad server dropping packet: " + str(err))
  829. except pyrad.packet.PacketError as err:
  830. logger.info("pyrad server received invalid packet: " + str(err))
  831. else:
  832. logger.error("Unexpected event in pyrad server main loop")
  833. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  834. authport=18138, acctport=18139)
  835. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  836. "radius",
  837. "localhost")
  838. srv.BindToAddress("")
  839. t_events = {}
  840. t_events['stop'] = threading.Event()
  841. t_events['msg_auth'] = threading.Event()
  842. t_events['wrong_secret'] = threading.Event()
  843. t_events['double_msg_auth'] = threading.Event()
  844. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  845. t.start()
  846. try:
  847. params = hostapd.wpa2_eap_params(ssid="radius-test")
  848. params['auth_server_port'] = "18138"
  849. hapd = hostapd.add_ap(apdev[0], params)
  850. connect(dev[0], "radius-test", wait_connect=False)
  851. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
  852. if ev is None:
  853. raise Exception("Timeout on EAP start")
  854. time.sleep(1)
  855. dev[0].request("REMOVE_NETWORK all")
  856. time.sleep(0.1)
  857. dev[0].dump_monitor()
  858. t_events['msg_auth'].set()
  859. t_events['wrong_secret'].set()
  860. connect(dev[0], "radius-test", wait_connect=False)
  861. time.sleep(1)
  862. dev[0].request("REMOVE_NETWORK all")
  863. time.sleep(0.1)
  864. dev[0].dump_monitor()
  865. t_events['wrong_secret'].clear()
  866. connect(dev[0], "radius-test", wait_connect=False)
  867. time.sleep(1)
  868. dev[0].request("REMOVE_NETWORK all")
  869. time.sleep(0.1)
  870. dev[0].dump_monitor()
  871. t_events['double_msg_auth'].set()
  872. connect(dev[0], "radius-test", wait_connect=False)
  873. time.sleep(1)
  874. finally:
  875. t_events['stop'].set()
  876. t.join()
  877. def test_radius_psk(dev, apdev):
  878. """WPA2 with PSK from RADIUS"""
  879. try:
  880. import pyrad.server
  881. import pyrad.packet
  882. import pyrad.dictionary
  883. except ImportError:
  884. raise HwsimSkip("No pyrad modules available")
  885. class TestServer(pyrad.server.Server):
  886. def _HandleAuthPacket(self, pkt):
  887. pyrad.server.Server._HandleAuthPacket(self, pkt)
  888. logger.info("Received authentication request")
  889. reply = self.CreateReplyPacket(pkt)
  890. reply.code = pyrad.packet.AccessAccept
  891. a = "\xab\xcd"
  892. secret = reply.secret
  893. if self.t_events['long'].is_set():
  894. p = b'\x10' + "0123456789abcdef" + 15 * b'\x00'
  895. b = hashlib.md5(secret + pkt.authenticator + a).digest()
  896. pp = bytearray(p[0:16])
  897. bb = bytearray(b)
  898. cc = bytearray(pp[i] ^ bb[i] for i in range(len(bb)))
  899. b = hashlib.md5(reply.secret + bytes(cc)).digest()
  900. pp = bytearray(p[16:32])
  901. bb = bytearray(b)
  902. cc += bytearray(pp[i] ^ bb[i] for i in range(len(bb)))
  903. data = '\x00' + a + bytes(cc)
  904. else:
  905. p = b'\x08' + "12345678" + 7 * b'\x00'
  906. b = hashlib.md5(secret + pkt.authenticator + a).digest()
  907. pp = bytearray(p)
  908. bb = bytearray(b)
  909. cc = bytearray(pp[i] ^ bb[i] for i in range(len(bb)))
  910. data = '\x00' + a + bytes(cc)
  911. reply.AddAttribute("Tunnel-Password", data)
  912. self.SendReplyPacket(pkt.fd, reply)
  913. def RunWithStop(self, t_events):
  914. self._poll = select.poll()
  915. self._fdmap = {}
  916. self._PrepareSockets()
  917. self.t_events = t_events
  918. while not t_events['stop'].is_set():
  919. for (fd, event) in self._poll.poll(1000):
  920. if event == select.POLLIN:
  921. try:
  922. fdo = self._fdmap[fd]
  923. self._ProcessInput(fdo)
  924. except pyrad.server.ServerPacketError as err:
  925. logger.info("pyrad server dropping packet: " + str(err))
  926. except pyrad.packet.PacketError as err:
  927. logger.info("pyrad server received invalid packet: " + str(err))
  928. else:
  929. logger.error("Unexpected event in pyrad server main loop")
  930. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  931. authport=18138, acctport=18139)
  932. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  933. "radius",
  934. "localhost")
  935. srv.BindToAddress("")
  936. t_events = {}
  937. t_events['stop'] = threading.Event()
  938. t_events['long'] = threading.Event()
  939. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  940. t.start()
  941. try:
  942. ssid = "test-wpa2-psk"
  943. params = hostapd.radius_params()
  944. params['ssid'] = ssid
  945. params["wpa"] = "2"
  946. params["wpa_key_mgmt"] = "WPA-PSK"
  947. params["rsn_pairwise"] = "CCMP"
  948. params['macaddr_acl'] = '2'
  949. params['wpa_psk_radius'] = '2'
  950. params['auth_server_port'] = "18138"
  951. hapd = hostapd.add_ap(apdev[0], params)
  952. dev[0].connect(ssid, psk="12345678", scan_freq="2412")
  953. t_events['long'].set()
  954. dev[1].connect(ssid, psk="0123456789abcdef", scan_freq="2412")
  955. finally:
  956. t_events['stop'].set()
  957. t.join()
  958. def test_radius_psk_invalid(dev, apdev):
  959. """WPA2 with invalid PSK from RADIUS"""
  960. try:
  961. import pyrad.server
  962. import pyrad.packet
  963. import pyrad.dictionary
  964. except ImportError:
  965. raise HwsimSkip("No pyrad modules available")
  966. class TestServer(pyrad.server.Server):
  967. def _HandleAuthPacket(self, pkt):
  968. pyrad.server.Server._HandleAuthPacket(self, pkt)
  969. logger.info("Received authentication request")
  970. reply = self.CreateReplyPacket(pkt)
  971. reply.code = pyrad.packet.AccessAccept
  972. a = "\xab\xcd"
  973. secret = reply.secret
  974. p = b'\x07' + "1234567" + 8 * b'\x00'
  975. b = hashlib.md5(secret + pkt.authenticator + a).digest()
  976. pp = bytearray(p)
  977. bb = bytearray(b)
  978. cc = bytearray(pp[i] ^ bb[i] for i in range(len(bb)))
  979. data = '\x00' + a + bytes(cc)
  980. reply.AddAttribute("Tunnel-Password", data)
  981. self.SendReplyPacket(pkt.fd, reply)
  982. def RunWithStop(self, t_events):
  983. self._poll = select.poll()
  984. self._fdmap = {}
  985. self._PrepareSockets()
  986. self.t_events = t_events
  987. while not t_events['stop'].is_set():
  988. for (fd, event) in self._poll.poll(1000):
  989. if event == select.POLLIN:
  990. try:
  991. fdo = self._fdmap[fd]
  992. self._ProcessInput(fdo)
  993. except pyrad.server.ServerPacketError as err:
  994. logger.info("pyrad server dropping packet: " + str(err))
  995. except pyrad.packet.PacketError as err:
  996. logger.info("pyrad server received invalid packet: " + str(err))
  997. else:
  998. logger.error("Unexpected event in pyrad server main loop")
  999. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  1000. authport=18138, acctport=18139)
  1001. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  1002. "radius",
  1003. "localhost")
  1004. srv.BindToAddress("")
  1005. t_events = {}
  1006. t_events['stop'] = threading.Event()
  1007. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  1008. t.start()
  1009. try:
  1010. ssid = "test-wpa2-psk"
  1011. params = hostapd.radius_params()
  1012. params['ssid'] = ssid
  1013. params["wpa"] = "2"
  1014. params["wpa_key_mgmt"] = "WPA-PSK"
  1015. params["rsn_pairwise"] = "CCMP"
  1016. params['macaddr_acl'] = '2'
  1017. params['wpa_psk_radius'] = '2'
  1018. params['auth_server_port'] = "18138"
  1019. hapd = hostapd.add_ap(apdev[0], params)
  1020. dev[0].connect(ssid, psk="12345678", scan_freq="2412",
  1021. wait_connect=False)
  1022. time.sleep(1)
  1023. finally:
  1024. t_events['stop'].set()
  1025. t.join()
  1026. def test_radius_auth_force_client_addr(dev, apdev):
  1027. """RADIUS client address specified"""
  1028. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  1029. params['radius_client_addr'] = "127.0.0.1"
  1030. hapd = hostapd.add_ap(apdev[0], params)
  1031. connect(dev[0], "radius-auth")
  1032. @remote_compatible
  1033. def test_radius_auth_force_invalid_client_addr(dev, apdev):
  1034. """RADIUS client address specified and invalid address"""
  1035. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  1036. #params['radius_client_addr'] = "10.11.12.14"
  1037. params['radius_client_addr'] = "1::2"
  1038. hapd = hostapd.add_ap(apdev[0], params)
  1039. connect(dev[0], "radius-auth", wait_connect=False)
  1040. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
  1041. if ev is None:
  1042. raise Exception("Timeout on EAP start")
  1043. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  1044. if ev is not None:
  1045. raise Exception("Unexpected connection")
  1046. def add_message_auth(req):
  1047. req.authenticator = req.CreateAuthenticator()
  1048. hmac_obj = hmac.new(req.secret)
  1049. hmac_obj.update(struct.pack("B", req.code))
  1050. hmac_obj.update(struct.pack("B", req.id))
  1051. # request attributes
  1052. req.AddAttribute("Message-Authenticator",
  1053. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
  1054. attrs = req._PktEncodeAttributes()
  1055. # Length
  1056. flen = 4 + 16 + len(attrs)
  1057. hmac_obj.update(struct.pack(">H", flen))
  1058. hmac_obj.update(req.authenticator)
  1059. hmac_obj.update(attrs)
  1060. del req[80]
  1061. req.AddAttribute("Message-Authenticator", hmac_obj.digest())
  1062. def test_radius_server_failures(dev, apdev):
  1063. """RADIUS server failure cases"""
  1064. try:
  1065. import pyrad.client
  1066. import pyrad.packet
  1067. import pyrad.dictionary
  1068. except ImportError:
  1069. raise HwsimSkip("No pyrad modules available")
  1070. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  1071. client = pyrad.client.Client(server="127.0.0.1", authport=1812,
  1072. secret="radius", dict=dict)
  1073. client.retries = 1
  1074. client.timeout = 1
  1075. # unexpected State
  1076. req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest,
  1077. User_Name="foo")
  1078. req['State'] = 'foo-state'
  1079. add_message_auth(req)
  1080. reply = client.SendPacket(req)
  1081. if reply.code != pyrad.packet.AccessReject:
  1082. raise Exception("Unexpected RADIUS response code " + str(reply.code))
  1083. # no EAP-Message
  1084. req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest,
  1085. User_Name="foo")
  1086. add_message_auth(req)
  1087. try:
  1088. reply = client.SendPacket(req)
  1089. raise Exception("Unexpected response")
  1090. except pyrad.client.Timeout:
  1091. pass
  1092. def test_ap_vlan_wpa2_psk_radius_required(dev, apdev):
  1093. """AP VLAN with WPA2-PSK and RADIUS attributes required"""
  1094. try:
  1095. import pyrad.server
  1096. import pyrad.packet
  1097. import pyrad.dictionary
  1098. except ImportError:
  1099. raise HwsimSkip("No pyrad modules available")
  1100. class TestServer(pyrad.server.Server):
  1101. def _HandleAuthPacket(self, pkt):
  1102. pyrad.server.Server._HandleAuthPacket(self, pkt)
  1103. logger.info("Received authentication request")
  1104. reply = self.CreateReplyPacket(pkt)
  1105. reply.code = pyrad.packet.AccessAccept
  1106. secret = reply.secret
  1107. if self.t_events['extra'].is_set():
  1108. reply.AddAttribute("Chargeable-User-Identity", "test-cui")
  1109. reply.AddAttribute("User-Name", "test-user")
  1110. if self.t_events['long'].is_set():
  1111. reply.AddAttribute("Tunnel-Type", 13)
  1112. reply.AddAttribute("Tunnel-Medium-Type", 6)
  1113. reply.AddAttribute("Tunnel-Private-Group-ID", "1")
  1114. self.SendReplyPacket(pkt.fd, reply)
  1115. def RunWithStop(self, t_events):
  1116. self._poll = select.poll()
  1117. self._fdmap = {}
  1118. self._PrepareSockets()
  1119. self.t_events = t_events
  1120. while not t_events['stop'].is_set():
  1121. for (fd, event) in self._poll.poll(1000):
  1122. if event == select.POLLIN:
  1123. try:
  1124. fdo = self._fdmap[fd]
  1125. self._ProcessInput(fdo)
  1126. except pyrad.server.ServerPacketError as err:
  1127. logger.info("pyrad server dropping packet: " + str(err))
  1128. except pyrad.packet.PacketError as err:
  1129. logger.info("pyrad server received invalid packet: " + str(err))
  1130. else:
  1131. logger.error("Unexpected event in pyrad server main loop")
  1132. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  1133. authport=18138, acctport=18139)
  1134. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  1135. "radius",
  1136. "localhost")
  1137. srv.BindToAddress("")
  1138. t_events = {}
  1139. t_events['stop'] = threading.Event()
  1140. t_events['long'] = threading.Event()
  1141. t_events['extra'] = threading.Event()
  1142. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  1143. t.start()
  1144. try:
  1145. ssid = "test-wpa2-psk"
  1146. params = hostapd.radius_params()
  1147. params['ssid'] = ssid
  1148. params["wpa"] = "2"
  1149. params["wpa_key_mgmt"] = "WPA-PSK"
  1150. params["rsn_pairwise"] = "CCMP"
  1151. params['macaddr_acl'] = '2'
  1152. params['dynamic_vlan'] = "2"
  1153. params['wpa_passphrase'] = '0123456789abcdefghi'
  1154. params['auth_server_port'] = "18138"
  1155. hapd = hostapd.add_ap(apdev[0], params)
  1156. logger.info("connecting without VLAN")
  1157. dev[0].connect(ssid, psk="0123456789abcdefghi", scan_freq="2412",
  1158. wait_connect=False)
  1159. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
  1160. "CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=20)
  1161. if ev is None:
  1162. raise Exception("Timeout on connection attempt")
  1163. if "CTRL-EVENT-CONNECTED" in ev:
  1164. raise Exception("Unexpected success without vlan parameters")
  1165. logger.info("connecting without VLAN failed as expected")
  1166. logger.info("connecting without VLAN (CUI/User-Name)")
  1167. t_events['extra'].set()
  1168. dev[1].connect(ssid, psk="0123456789abcdefghi", scan_freq="2412",
  1169. wait_connect=False)
  1170. ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED",
  1171. "CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=20)
  1172. if ev is None:
  1173. raise Exception("Timeout on connection attempt")
  1174. if "CTRL-EVENT-CONNECTED" in ev:
  1175. raise Exception("Unexpected success without vlan parameters(2)")
  1176. logger.info("connecting without VLAN failed as expected(2)")
  1177. t_events['extra'].clear()
  1178. t_events['long'].set()
  1179. logger.info("connecting with VLAN")
  1180. dev[2].connect(ssid, psk="0123456789abcdefghi", scan_freq="2412",
  1181. wait_connect=False)
  1182. ev = dev[2].wait_event(["CTRL-EVENT-CONNECTED",
  1183. "CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=20)
  1184. if ev is None:
  1185. raise Exception("Timeout on connection attempt")
  1186. if "CTRL-EVENT-SSID-TEMP-DISABLED" in ev:
  1187. raise Exception("Unexpected failure with vlan parameters")
  1188. logger.info("connecting with VLAN succeeded as expected")
  1189. finally:
  1190. t_events['stop'].set()
  1191. t.join()
  1192. def test_radius_mppe_failure(dev, apdev):
  1193. """RADIUS failure when adding MPPE keys"""
  1194. params = { "ssid": "as", "beacon_int": "2000",
  1195. "radius_server_clients": "auth_serv/radius_clients.conf",
  1196. "radius_server_auth_port": '18127',
  1197. "eap_server": "1",
  1198. "eap_user_file": "auth_serv/eap_user.conf",
  1199. "ca_cert": "auth_serv/ca.pem",
  1200. "server_cert": "auth_serv/server.pem",
  1201. "private_key": "auth_serv/server.key" }
  1202. authsrv = hostapd.add_ap(apdev[1], params)
  1203. params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
  1204. params['auth_server_port'] = "18127"
  1205. hapd = hostapd.add_ap(apdev[0], params)
  1206. with fail_test(authsrv, 1, "os_get_random;radius_msg_add_mppe_keys"):
  1207. dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
  1208. identity="user", anonymous_identity="ttls",
  1209. password="password",
  1210. ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
  1211. wait_connect=False, scan_freq="2412")
  1212. dev[0].wait_disconnected()
  1213. dev[0].request("REMOVE_NETWORK all")