test_radius.py 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643
  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, alloc_fail, fail_test, wait_fail_trigger
  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(4.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 (req_e=%d req_s=%d)" % (req_e, req_s))
  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 add_message_auth_req(req):
  646. req.authenticator = req.CreateAuthenticator()
  647. hmac_obj = hmac.new(req.secret)
  648. hmac_obj.update(struct.pack("B", req.code))
  649. hmac_obj.update(struct.pack("B", req.id))
  650. # request attributes
  651. req.AddAttribute("Message-Authenticator", 16*"\x00")
  652. attrs = req._PktEncodeAttributes()
  653. # Length
  654. flen = 4 + 16 + len(attrs)
  655. hmac_obj.update(struct.pack(">H", flen))
  656. hmac_obj.update(16*"\x00") # all zeros Authenticator in calculation
  657. hmac_obj.update(attrs)
  658. del req[80]
  659. req.AddAttribute("Message-Authenticator", hmac_obj.digest())
  660. def test_radius_das_disconnect_time_window(dev, apdev):
  661. """RADIUS Dynamic Authorization Extensions - Disconnect - time window"""
  662. try:
  663. import pyrad.client
  664. import pyrad.packet
  665. import pyrad.dictionary
  666. import radius_das
  667. except ImportError:
  668. raise HwsimSkip("No pyrad modules available")
  669. params = hostapd.wpa2_eap_params(ssid="radius-das")
  670. params['radius_das_port'] = "3799"
  671. params['radius_das_client'] = "127.0.0.1 secret"
  672. params['radius_das_require_event_timestamp'] = "1"
  673. params['radius_das_require_message_authenticator'] = "1"
  674. params['radius_das_time_window'] = "10"
  675. params['own_ip_addr'] = "127.0.0.1"
  676. params['nas_identifier'] = "nas.example.com"
  677. hapd = hostapd.add_ap(apdev[0], params)
  678. connect(dev[0], "radius-das")
  679. addr = dev[0].own_addr()
  680. sta = hapd.get_sta(addr)
  681. id = sta['dot1xAuthSessionId']
  682. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  683. srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
  684. secret="secret", dict=dict)
  685. srv.retries = 1
  686. srv.timeout = 1
  687. logger.info("Disconnect-Request with unsupported attribute")
  688. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  689. NAS_IP_Address="127.0.0.1",
  690. NAS_Identifier="nas.example.com",
  691. Calling_Station_Id=addr,
  692. Event_Timestamp=int(time.time()) - 50)
  693. add_message_auth_req(req)
  694. logger.debug(req)
  695. try:
  696. reply = srv.SendPacket(req)
  697. raise Exception("Unexpected response to Disconnect-Request")
  698. except pyrad.client.Timeout:
  699. logger.info("Disconnect-Request with non-matching Event-Timestamp properly ignored")
  700. logger.info("Disconnect-Request with unsupported attribute")
  701. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  702. NAS_IP_Address="127.0.0.1",
  703. NAS_Identifier="nas.example.com",
  704. Calling_Station_Id=addr,
  705. Event_Timestamp=int(time.time()))
  706. add_message_auth_req(req)
  707. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  708. def test_radius_das_coa(dev, apdev):
  709. """RADIUS Dynamic Authorization Extensions - CoA"""
  710. try:
  711. import pyrad.client
  712. import pyrad.packet
  713. import pyrad.dictionary
  714. import radius_das
  715. except ImportError:
  716. raise HwsimSkip("No pyrad modules available")
  717. params = hostapd.wpa2_eap_params(ssid="radius-das")
  718. params['radius_das_port'] = "3799"
  719. params['radius_das_client'] = "127.0.0.1 secret"
  720. params['radius_das_require_event_timestamp'] = "1"
  721. hapd = hostapd.add_ap(apdev[0], params)
  722. connect(dev[0], "radius-das")
  723. addr = dev[0].p2p_interface_addr()
  724. sta = hapd.get_sta(addr)
  725. id = sta['dot1xAuthSessionId']
  726. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  727. srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
  728. secret="secret", dict=dict)
  729. srv.retries = 1
  730. srv.timeout = 1
  731. # hostapd does not currently support CoA-Request, so NAK is expected
  732. logger.info("CoA-Request with matching Acct-Session-Id")
  733. req = radius_das.CoAPacket(dict=dict, secret="secret",
  734. Acct_Session_Id=id,
  735. Event_Timestamp=int(time.time()))
  736. send_and_check_reply(srv, req, pyrad.packet.CoANAK, error_cause=405)
  737. def test_radius_ipv6(dev, apdev):
  738. """RADIUS connection over IPv6"""
  739. params = {}
  740. params['ssid'] = 'as'
  741. params['beacon_int'] = '2000'
  742. params['radius_server_clients'] = 'auth_serv/radius_clients_ipv6.conf'
  743. params['radius_server_ipv6'] = '1'
  744. params['radius_server_auth_port'] = '18129'
  745. params['radius_server_acct_port'] = '18139'
  746. params['eap_server'] = '1'
  747. params['eap_user_file'] = 'auth_serv/eap_user.conf'
  748. params['ca_cert'] = 'auth_serv/ca.pem'
  749. params['server_cert'] = 'auth_serv/server.pem'
  750. params['private_key'] = 'auth_serv/server.key'
  751. hostapd.add_ap(apdev[1], params)
  752. params = hostapd.wpa2_eap_params(ssid="radius-ipv6")
  753. params['auth_server_addr'] = "::0"
  754. params['auth_server_port'] = "18129"
  755. params['acct_server_addr'] = "::0"
  756. params['acct_server_port'] = "18139"
  757. params['acct_server_shared_secret'] = "radius"
  758. params['own_ip_addr'] = "::0"
  759. hostapd.add_ap(apdev[0], params)
  760. connect(dev[0], "radius-ipv6")
  761. def test_radius_macacl(dev, apdev):
  762. """RADIUS MAC ACL"""
  763. params = hostapd.radius_params()
  764. params["ssid"] = "radius"
  765. params["macaddr_acl"] = "2"
  766. hostapd.add_ap(apdev[0], params)
  767. dev[0].connect("radius", key_mgmt="NONE", scan_freq="2412")
  768. # Invalid VLAN ID from RADIUS server
  769. dev[2].connect("radius", key_mgmt="NONE", scan_freq="2412")
  770. dev[2].request("REMOVE_NETWORK all")
  771. dev[2].wait_disconnected()
  772. dev[2].connect("radius", key_mgmt="NONE", scan_freq="2412")
  773. def test_radius_macacl_acct(dev, apdev):
  774. """RADIUS MAC ACL and accounting enabled"""
  775. params = hostapd.radius_params()
  776. params["ssid"] = "radius"
  777. params["macaddr_acl"] = "2"
  778. params['acct_server_addr'] = "127.0.0.1"
  779. params['acct_server_port'] = "1813"
  780. params['acct_server_shared_secret'] = "radius"
  781. hostapd.add_ap(apdev[0], params)
  782. dev[0].connect("radius", key_mgmt="NONE", scan_freq="2412")
  783. dev[1].connect("radius", key_mgmt="NONE", scan_freq="2412")
  784. dev[1].request("DISCONNECT")
  785. dev[1].wait_disconnected()
  786. dev[1].request("RECONNECT")
  787. def test_radius_macacl_oom(dev, apdev):
  788. """RADIUS MAC ACL and OOM"""
  789. params = hostapd.radius_params()
  790. params["ssid"] = "radius"
  791. params["macaddr_acl"] = "2"
  792. hapd = hostapd.add_ap(apdev[0], params)
  793. bssid = hapd.own_addr()
  794. dev[0].scan_for_bss(bssid, freq="2412")
  795. with alloc_fail(hapd, 1, "hostapd_allowed_address"):
  796. dev[0].connect("radius", key_mgmt="NONE", scan_freq="2412")
  797. dev[1].scan_for_bss(bssid, freq="2412")
  798. with alloc_fail(hapd, 2, "hostapd_allowed_address"):
  799. dev[1].connect("radius", key_mgmt="NONE", scan_freq="2412")
  800. dev[2].scan_for_bss(bssid, freq="2412")
  801. with alloc_fail(hapd, 2, "=hostapd_allowed_address"):
  802. dev[2].connect("radius", key_mgmt="NONE", scan_freq="2412")
  803. def test_radius_macacl_unreachable(dev, apdev):
  804. """RADIUS MAC ACL and server unreachable"""
  805. params = hostapd.radius_params()
  806. params['auth_server_port'] = "18139"
  807. params["ssid"] = "radius"
  808. params["macaddr_acl"] = "2"
  809. hapd = hostapd.add_ap(apdev[0], params)
  810. bssid = hapd.own_addr()
  811. dev[0].scan_for_bss(bssid, freq="2412")
  812. dev[0].connect("radius", key_mgmt="NONE", scan_freq="2412",
  813. wait_connect=False)
  814. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=3)
  815. if ev is not None:
  816. raise Exception("Unexpected connection")
  817. logger.info("Fix authentication server port")
  818. hapd.set("auth_server_port", "1812")
  819. hapd.disable()
  820. hapd.enable()
  821. dev[0].wait_connected()
  822. dev[0].request("DISCONNECT")
  823. dev[0].wait_disconnected()
  824. def test_radius_failover(dev, apdev):
  825. """RADIUS Authentication and Accounting server failover"""
  826. subprocess.call(['ip', 'ro', 'replace', '192.168.213.17', 'dev', 'lo'])
  827. as_hapd = hostapd.Hostapd("as")
  828. as_mib_start = as_hapd.get_mib(param="radius_server")
  829. params = hostapd.wpa2_eap_params(ssid="radius-failover")
  830. params["auth_server_addr"] = "192.168.213.17"
  831. params["auth_server_port"] = "1812"
  832. params["auth_server_shared_secret"] = "testing"
  833. params['acct_server_addr'] = "192.168.213.17"
  834. params['acct_server_port'] = "1813"
  835. params['acct_server_shared_secret'] = "testing"
  836. params['radius_retry_primary_interval'] = "20"
  837. hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
  838. hapd.set("auth_server_addr", "127.0.0.1")
  839. hapd.set("auth_server_port", "1812")
  840. hapd.set("auth_server_shared_secret", "radius")
  841. hapd.set('acct_server_addr', "127.0.0.1")
  842. hapd.set('acct_server_port', "1813")
  843. hapd.set('acct_server_shared_secret', "radius")
  844. hapd.enable()
  845. ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=30)
  846. if ev is None:
  847. raise Exception("AP startup timed out")
  848. if "AP-ENABLED" not in ev:
  849. raise Exception("AP startup failed")
  850. start = os.times()[4]
  851. try:
  852. subprocess.call(['ip', 'ro', 'replace', 'prohibit', '192.168.213.17'])
  853. dev[0].request("SET EAPOL::authPeriod 5")
  854. connect(dev[0], "radius-failover", wait_connect=False)
  855. dev[0].wait_connected(timeout=20)
  856. finally:
  857. dev[0].request("SET EAPOL::authPeriod 30")
  858. subprocess.call(['ip', 'ro', 'del', '192.168.213.17'])
  859. as_mib_end = as_hapd.get_mib(param="radius_server")
  860. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  861. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  862. if req_e <= req_s:
  863. raise Exception("Unexpected RADIUS server acct MIB value")
  864. end = os.times()[4]
  865. try:
  866. subprocess.call(['ip', 'ro', 'replace', 'prohibit', '192.168.213.17'])
  867. dev[1].request("SET EAPOL::authPeriod 5")
  868. if end - start < 21:
  869. time.sleep(21 - (end - start))
  870. connect(dev[1], "radius-failover", wait_connect=False)
  871. dev[1].wait_connected(timeout=20)
  872. finally:
  873. dev[1].request("SET EAPOL::authPeriod 30")
  874. subprocess.call(['ip', 'ro', 'del', '192.168.213.17'])
  875. def run_pyrad_server(srv, t_events):
  876. srv.RunWithStop(t_events)
  877. def test_radius_protocol(dev, apdev):
  878. """RADIUS Authentication protocol tests with a fake server"""
  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. if self.t_events['msg_auth'].is_set():
  892. logger.info("Add Message-Authenticator")
  893. if self.t_events['wrong_secret'].is_set():
  894. logger.info("Use incorrect RADIUS shared secret")
  895. pw = "incorrect"
  896. else:
  897. pw = reply.secret
  898. hmac_obj = hmac.new(pw)
  899. hmac_obj.update(struct.pack("B", reply.code))
  900. hmac_obj.update(struct.pack("B", reply.id))
  901. # reply attributes
  902. reply.AddAttribute("Message-Authenticator",
  903. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
  904. attrs = reply._PktEncodeAttributes()
  905. # Length
  906. flen = 4 + 16 + len(attrs)
  907. hmac_obj.update(struct.pack(">H", flen))
  908. hmac_obj.update(pkt.authenticator)
  909. hmac_obj.update(attrs)
  910. if self.t_events['double_msg_auth'].is_set():
  911. logger.info("Include two Message-Authenticator attributes")
  912. else:
  913. del reply[80]
  914. reply.AddAttribute("Message-Authenticator", hmac_obj.digest())
  915. self.SendReplyPacket(pkt.fd, reply)
  916. def RunWithStop(self, t_events):
  917. self._poll = select.poll()
  918. self._fdmap = {}
  919. self._PrepareSockets()
  920. self.t_events = t_events
  921. while not t_events['stop'].is_set():
  922. for (fd, event) in self._poll.poll(1000):
  923. if event == select.POLLIN:
  924. try:
  925. fdo = self._fdmap[fd]
  926. self._ProcessInput(fdo)
  927. except pyrad.server.ServerPacketError as err:
  928. logger.info("pyrad server dropping packet: " + str(err))
  929. except pyrad.packet.PacketError as err:
  930. logger.info("pyrad server received invalid packet: " + str(err))
  931. else:
  932. logger.error("Unexpected event in pyrad server main loop")
  933. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  934. authport=18138, acctport=18139)
  935. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  936. "radius",
  937. "localhost")
  938. srv.BindToAddress("")
  939. t_events = {}
  940. t_events['stop'] = threading.Event()
  941. t_events['msg_auth'] = threading.Event()
  942. t_events['wrong_secret'] = threading.Event()
  943. t_events['double_msg_auth'] = threading.Event()
  944. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  945. t.start()
  946. try:
  947. params = hostapd.wpa2_eap_params(ssid="radius-test")
  948. params['auth_server_port'] = "18138"
  949. hapd = hostapd.add_ap(apdev[0], params)
  950. connect(dev[0], "radius-test", wait_connect=False)
  951. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
  952. if ev is None:
  953. raise Exception("Timeout on EAP start")
  954. time.sleep(1)
  955. dev[0].request("REMOVE_NETWORK all")
  956. time.sleep(0.1)
  957. dev[0].dump_monitor()
  958. t_events['msg_auth'].set()
  959. t_events['wrong_secret'].set()
  960. connect(dev[0], "radius-test", wait_connect=False)
  961. time.sleep(1)
  962. dev[0].request("REMOVE_NETWORK all")
  963. time.sleep(0.1)
  964. dev[0].dump_monitor()
  965. t_events['wrong_secret'].clear()
  966. connect(dev[0], "radius-test", wait_connect=False)
  967. time.sleep(1)
  968. dev[0].request("REMOVE_NETWORK all")
  969. time.sleep(0.1)
  970. dev[0].dump_monitor()
  971. t_events['double_msg_auth'].set()
  972. connect(dev[0], "radius-test", wait_connect=False)
  973. time.sleep(1)
  974. finally:
  975. t_events['stop'].set()
  976. t.join()
  977. def build_tunnel_password(secret, authenticator, psk):
  978. a = "\xab\xcd"
  979. padlen = 16 - (1 + len(psk)) % 16
  980. if padlen == 16:
  981. padlen = 0
  982. p = struct.pack('B', len(psk)) + psk + padlen * b'\x00'
  983. cc_all = bytes()
  984. b = hashlib.md5(secret + authenticator + a).digest()
  985. while len(p) > 0:
  986. pp = bytearray(p[0:16])
  987. p = p[16:]
  988. bb = bytearray(b)
  989. cc = bytearray(pp[i] ^ bb[i] for i in range(len(bb)))
  990. cc_all += cc
  991. b = hashlib.md5(secret + cc).digest()
  992. data = '\x00' + a + bytes(cc_all)
  993. return data
  994. def start_radius_psk_server(psk, invalid_code=False, acct_interim_interval=0,
  995. session_timeout=0, reject=False):
  996. try:
  997. import pyrad.server
  998. import pyrad.packet
  999. import pyrad.dictionary
  1000. except ImportError:
  1001. raise HwsimSkip("No pyrad modules available")
  1002. class TestServer(pyrad.server.Server):
  1003. def _HandleAuthPacket(self, pkt):
  1004. pyrad.server.Server._HandleAuthPacket(self, pkt)
  1005. logger.info("Received authentication request")
  1006. reply = self.CreateReplyPacket(pkt)
  1007. reply.code = pyrad.packet.AccessAccept
  1008. if self.t_events['invalid_code']:
  1009. reply.code = pyrad.packet.AccessRequest
  1010. if self.t_events['reject']:
  1011. reply.code = pyrad.packet.AccessReject
  1012. data = build_tunnel_password(reply.secret, pkt.authenticator,
  1013. self.t_events['psk'])
  1014. reply.AddAttribute("Tunnel-Password", data)
  1015. if self.t_events['acct_interim_interval']:
  1016. reply.AddAttribute("Acct-Interim-Interval",
  1017. self.t_events['acct_interim_interval'])
  1018. if self.t_events['session_timeout']:
  1019. reply.AddAttribute("Session-Timeout",
  1020. self.t_events['session_timeout'])
  1021. self.SendReplyPacket(pkt.fd, reply)
  1022. def RunWithStop(self, t_events):
  1023. self._poll = select.poll()
  1024. self._fdmap = {}
  1025. self._PrepareSockets()
  1026. self.t_events = t_events
  1027. while not t_events['stop'].is_set():
  1028. for (fd, event) in self._poll.poll(1000):
  1029. if event == select.POLLIN:
  1030. try:
  1031. fdo = self._fdmap[fd]
  1032. self._ProcessInput(fdo)
  1033. except pyrad.server.ServerPacketError as err:
  1034. logger.info("pyrad server dropping packet: " + str(err))
  1035. except pyrad.packet.PacketError as err:
  1036. logger.info("pyrad server received invalid packet: " + str(err))
  1037. else:
  1038. logger.error("Unexpected event in pyrad server main loop")
  1039. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  1040. authport=18138, acctport=18139)
  1041. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  1042. "radius",
  1043. "localhost")
  1044. srv.BindToAddress("")
  1045. t_events = {}
  1046. t_events['stop'] = threading.Event()
  1047. t_events['psk'] = psk
  1048. t_events['invalid_code'] = invalid_code
  1049. t_events['acct_interim_interval'] = acct_interim_interval
  1050. t_events['session_timeout'] = session_timeout
  1051. t_events['reject'] = reject
  1052. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  1053. t.start()
  1054. return t, t_events
  1055. def hostapd_radius_psk_test_params():
  1056. params = hostapd.radius_params()
  1057. params['ssid'] = "test-wpa2-psk"
  1058. params["wpa"] = "2"
  1059. params["wpa_key_mgmt"] = "WPA-PSK"
  1060. params["rsn_pairwise"] = "CCMP"
  1061. params['macaddr_acl'] = '2'
  1062. params['wpa_psk_radius'] = '2'
  1063. params['auth_server_port'] = "18138"
  1064. return params
  1065. def test_radius_psk(dev, apdev):
  1066. """WPA2 with PSK from RADIUS"""
  1067. t, t_events = start_radius_psk_server("12345678")
  1068. try:
  1069. params = hostapd_radius_psk_test_params()
  1070. hapd = hostapd.add_ap(apdev[0], params)
  1071. dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412")
  1072. t_events['psk'] = "0123456789abcdef"
  1073. dev[1].connect("test-wpa2-psk", psk="0123456789abcdef",
  1074. scan_freq="2412")
  1075. finally:
  1076. t_events['stop'].set()
  1077. t.join()
  1078. def test_radius_psk_invalid(dev, apdev):
  1079. """WPA2 with invalid PSK from RADIUS"""
  1080. t, t_events = start_radius_psk_server("1234567")
  1081. try:
  1082. params = hostapd_radius_psk_test_params()
  1083. hapd = hostapd.add_ap(apdev[0], params)
  1084. dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412",
  1085. wait_connect=False)
  1086. time.sleep(1)
  1087. finally:
  1088. t_events['stop'].set()
  1089. t.join()
  1090. def test_radius_psk_invalid2(dev, apdev):
  1091. """WPA2 with invalid PSK (hexstring) from RADIUS"""
  1092. t, t_events = start_radius_psk_server(64*'q')
  1093. try:
  1094. params = hostapd_radius_psk_test_params()
  1095. hapd = hostapd.add_ap(apdev[0], params)
  1096. dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412",
  1097. wait_connect=False)
  1098. time.sleep(1)
  1099. finally:
  1100. t_events['stop'].set()
  1101. t.join()
  1102. def test_radius_psk_hex_psk(dev, apdev):
  1103. """WPA2 with PSK hexstring from RADIUS"""
  1104. t, t_events = start_radius_psk_server(64*'2', acct_interim_interval=19,
  1105. session_timeout=123)
  1106. try:
  1107. params = hostapd_radius_psk_test_params()
  1108. hapd = hostapd.add_ap(apdev[0], params)
  1109. dev[0].connect("test-wpa2-psk", raw_psk=64*'2', scan_freq="2412")
  1110. finally:
  1111. t_events['stop'].set()
  1112. t.join()
  1113. def test_radius_psk_unknown_code(dev, apdev):
  1114. """WPA2 with PSK from RADIUS and unknown code"""
  1115. t, t_events = start_radius_psk_server(64*'2', invalid_code=True)
  1116. try:
  1117. params = hostapd_radius_psk_test_params()
  1118. hapd = hostapd.add_ap(apdev[0], params)
  1119. dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412",
  1120. wait_connect=False)
  1121. time.sleep(1)
  1122. finally:
  1123. t_events['stop'].set()
  1124. t.join()
  1125. def test_radius_psk_reject(dev, apdev):
  1126. """WPA2 with PSK from RADIUS and reject"""
  1127. t, t_events = start_radius_psk_server("12345678", reject=True)
  1128. try:
  1129. params = hostapd_radius_psk_test_params()
  1130. hapd = hostapd.add_ap(apdev[0], params)
  1131. dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412",
  1132. wait_connect=False)
  1133. ev = dev[0].wait_event(["CTRL-EVENT-AUTH-REJECT"], timeout=10)
  1134. if ev is None:
  1135. raise Exception("No CTRL-EVENT-AUTH-REJECT event")
  1136. dev[0].request("DISCONNECT")
  1137. finally:
  1138. t_events['stop'].set()
  1139. t.join()
  1140. def test_radius_psk_oom(dev, apdev):
  1141. """WPA2 with PSK from RADIUS and OOM"""
  1142. t, t_events = start_radius_psk_server(64*'2')
  1143. try:
  1144. params = hostapd_radius_psk_test_params()
  1145. hapd = hostapd.add_ap(apdev[0], params)
  1146. bssid = hapd.own_addr()
  1147. dev[0].scan_for_bss(bssid, freq="2412")
  1148. with alloc_fail(hapd, 1, "=hostapd_acl_recv_radius"):
  1149. dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412",
  1150. wait_connect=False)
  1151. wait_fail_trigger(hapd, "GET_ALLOC_FAIL")
  1152. finally:
  1153. t_events['stop'].set()
  1154. t.join()
  1155. def test_radius_psk_default(dev, apdev):
  1156. """WPA2 with default PSK"""
  1157. ssid = "test-wpa2-psk"
  1158. params = hostapd.radius_params()
  1159. params['ssid'] = ssid
  1160. params["wpa"] = "2"
  1161. params["wpa_key_mgmt"] = "WPA-PSK"
  1162. params["rsn_pairwise"] = "CCMP"
  1163. params['macaddr_acl'] = '2'
  1164. params['wpa_psk_radius'] = '1'
  1165. params['wpa_passphrase'] = 'qwertyuiop'
  1166. hapd = hostapd.add_ap(apdev[0], params)
  1167. dev[0].connect(ssid, psk="qwertyuiop", scan_freq="2412")
  1168. dev[0].dump_monitor()
  1169. dev[0].request("REMOVE_NETWORK all")
  1170. dev[0].wait_disconnected()
  1171. dev[0].dump_monitor()
  1172. hapd.disable()
  1173. hapd.set("wpa_psk_radius", "2")
  1174. hapd.enable()
  1175. dev[0].connect(ssid, psk="qwertyuiop", scan_freq="2412", wait_connect=False)
  1176. ev = dev[0].wait_event(["CTRL-EVENT-AUTH-REJECT"], timeout=10)
  1177. if ev is None:
  1178. raise Exception("No CTRL-EVENT-AUTH-REJECT event")
  1179. dev[0].request("DISCONNECT")
  1180. def test_radius_auth_force_client_addr(dev, apdev):
  1181. """RADIUS client address specified"""
  1182. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  1183. params['radius_client_addr'] = "127.0.0.1"
  1184. hapd = hostapd.add_ap(apdev[0], params)
  1185. connect(dev[0], "radius-auth")
  1186. @remote_compatible
  1187. def test_radius_auth_force_invalid_client_addr(dev, apdev):
  1188. """RADIUS client address specified and invalid address"""
  1189. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  1190. #params['radius_client_addr'] = "10.11.12.14"
  1191. params['radius_client_addr'] = "1::2"
  1192. hapd = hostapd.add_ap(apdev[0], params)
  1193. connect(dev[0], "radius-auth", wait_connect=False)
  1194. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
  1195. if ev is None:
  1196. raise Exception("Timeout on EAP start")
  1197. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  1198. if ev is not None:
  1199. raise Exception("Unexpected connection")
  1200. def add_message_auth(req):
  1201. req.authenticator = req.CreateAuthenticator()
  1202. hmac_obj = hmac.new(req.secret)
  1203. hmac_obj.update(struct.pack("B", req.code))
  1204. hmac_obj.update(struct.pack("B", req.id))
  1205. # request attributes
  1206. req.AddAttribute("Message-Authenticator",
  1207. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
  1208. attrs = req._PktEncodeAttributes()
  1209. # Length
  1210. flen = 4 + 16 + len(attrs)
  1211. hmac_obj.update(struct.pack(">H", flen))
  1212. hmac_obj.update(req.authenticator)
  1213. hmac_obj.update(attrs)
  1214. del req[80]
  1215. req.AddAttribute("Message-Authenticator", hmac_obj.digest())
  1216. def test_radius_server_failures(dev, apdev):
  1217. """RADIUS server failure cases"""
  1218. try:
  1219. import pyrad.client
  1220. import pyrad.packet
  1221. import pyrad.dictionary
  1222. except ImportError:
  1223. raise HwsimSkip("No pyrad modules available")
  1224. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  1225. client = pyrad.client.Client(server="127.0.0.1", authport=1812,
  1226. secret="radius", dict=dict)
  1227. client.retries = 1
  1228. client.timeout = 1
  1229. # unexpected State
  1230. req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest,
  1231. User_Name="foo")
  1232. req['State'] = 'foo-state'
  1233. add_message_auth(req)
  1234. reply = client.SendPacket(req)
  1235. if reply.code != pyrad.packet.AccessReject:
  1236. raise Exception("Unexpected RADIUS response code " + str(reply.code))
  1237. # no EAP-Message
  1238. req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest,
  1239. User_Name="foo")
  1240. add_message_auth(req)
  1241. try:
  1242. reply = client.SendPacket(req)
  1243. raise Exception("Unexpected response")
  1244. except pyrad.client.Timeout:
  1245. pass
  1246. def test_ap_vlan_wpa2_psk_radius_required(dev, apdev):
  1247. """AP VLAN with WPA2-PSK and RADIUS attributes required"""
  1248. try:
  1249. import pyrad.server
  1250. import pyrad.packet
  1251. import pyrad.dictionary
  1252. except ImportError:
  1253. raise HwsimSkip("No pyrad modules available")
  1254. class TestServer(pyrad.server.Server):
  1255. def _HandleAuthPacket(self, pkt):
  1256. pyrad.server.Server._HandleAuthPacket(self, pkt)
  1257. logger.info("Received authentication request")
  1258. reply = self.CreateReplyPacket(pkt)
  1259. reply.code = pyrad.packet.AccessAccept
  1260. secret = reply.secret
  1261. if self.t_events['extra'].is_set():
  1262. reply.AddAttribute("Chargeable-User-Identity", "test-cui")
  1263. reply.AddAttribute("User-Name", "test-user")
  1264. if self.t_events['long'].is_set():
  1265. reply.AddAttribute("Tunnel-Type", 13)
  1266. reply.AddAttribute("Tunnel-Medium-Type", 6)
  1267. reply.AddAttribute("Tunnel-Private-Group-ID", "1")
  1268. self.SendReplyPacket(pkt.fd, reply)
  1269. def RunWithStop(self, t_events):
  1270. self._poll = select.poll()
  1271. self._fdmap = {}
  1272. self._PrepareSockets()
  1273. self.t_events = t_events
  1274. while not t_events['stop'].is_set():
  1275. for (fd, event) in self._poll.poll(1000):
  1276. if event == select.POLLIN:
  1277. try:
  1278. fdo = self._fdmap[fd]
  1279. self._ProcessInput(fdo)
  1280. except pyrad.server.ServerPacketError as err:
  1281. logger.info("pyrad server dropping packet: " + str(err))
  1282. except pyrad.packet.PacketError as err:
  1283. logger.info("pyrad server received invalid packet: " + str(err))
  1284. else:
  1285. logger.error("Unexpected event in pyrad server main loop")
  1286. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  1287. authport=18138, acctport=18139)
  1288. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  1289. "radius",
  1290. "localhost")
  1291. srv.BindToAddress("")
  1292. t_events = {}
  1293. t_events['stop'] = threading.Event()
  1294. t_events['long'] = threading.Event()
  1295. t_events['extra'] = threading.Event()
  1296. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  1297. t.start()
  1298. try:
  1299. ssid = "test-wpa2-psk"
  1300. params = hostapd.radius_params()
  1301. params['ssid'] = ssid
  1302. params["wpa"] = "2"
  1303. params["wpa_key_mgmt"] = "WPA-PSK"
  1304. params["rsn_pairwise"] = "CCMP"
  1305. params['macaddr_acl'] = '2'
  1306. params['dynamic_vlan'] = "2"
  1307. params['wpa_passphrase'] = '0123456789abcdefghi'
  1308. params['auth_server_port'] = "18138"
  1309. hapd = hostapd.add_ap(apdev[0], params)
  1310. logger.info("connecting without VLAN")
  1311. dev[0].connect(ssid, psk="0123456789abcdefghi", scan_freq="2412",
  1312. wait_connect=False)
  1313. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
  1314. "CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=20)
  1315. if ev is None:
  1316. raise Exception("Timeout on connection attempt")
  1317. if "CTRL-EVENT-CONNECTED" in ev:
  1318. raise Exception("Unexpected success without vlan parameters")
  1319. logger.info("connecting without VLAN failed as expected")
  1320. logger.info("connecting without VLAN (CUI/User-Name)")
  1321. t_events['extra'].set()
  1322. dev[1].connect(ssid, psk="0123456789abcdefghi", scan_freq="2412",
  1323. wait_connect=False)
  1324. ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED",
  1325. "CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=20)
  1326. if ev is None:
  1327. raise Exception("Timeout on connection attempt")
  1328. if "CTRL-EVENT-CONNECTED" in ev:
  1329. raise Exception("Unexpected success without vlan parameters(2)")
  1330. logger.info("connecting without VLAN failed as expected(2)")
  1331. t_events['extra'].clear()
  1332. t_events['long'].set()
  1333. logger.info("connecting with VLAN")
  1334. dev[2].connect(ssid, psk="0123456789abcdefghi", scan_freq="2412",
  1335. wait_connect=False)
  1336. ev = dev[2].wait_event(["CTRL-EVENT-CONNECTED",
  1337. "CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=20)
  1338. if ev is None:
  1339. raise Exception("Timeout on connection attempt")
  1340. if "CTRL-EVENT-SSID-TEMP-DISABLED" in ev:
  1341. raise Exception("Unexpected failure with vlan parameters")
  1342. logger.info("connecting with VLAN succeeded as expected")
  1343. finally:
  1344. t_events['stop'].set()
  1345. t.join()
  1346. def test_radius_mppe_failure(dev, apdev):
  1347. """RADIUS failure when adding MPPE keys"""
  1348. params = { "ssid": "as", "beacon_int": "2000",
  1349. "radius_server_clients": "auth_serv/radius_clients.conf",
  1350. "radius_server_auth_port": '18127',
  1351. "eap_server": "1",
  1352. "eap_user_file": "auth_serv/eap_user.conf",
  1353. "ca_cert": "auth_serv/ca.pem",
  1354. "server_cert": "auth_serv/server.pem",
  1355. "private_key": "auth_serv/server.key" }
  1356. authsrv = hostapd.add_ap(apdev[1], params)
  1357. params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
  1358. params['auth_server_port'] = "18127"
  1359. hapd = hostapd.add_ap(apdev[0], params)
  1360. with fail_test(authsrv, 1, "os_get_random;radius_msg_add_mppe_keys"):
  1361. dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
  1362. identity="user", anonymous_identity="ttls",
  1363. password="password",
  1364. ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
  1365. wait_connect=False, scan_freq="2412")
  1366. dev[0].wait_disconnected()
  1367. dev[0].request("REMOVE_NETWORK all")
  1368. def test_radius_acct_failure(dev, apdev):
  1369. """RADIUS Accounting and failure to add attributes"""
  1370. # Connection goes through, but Accounting-Request cannot be sent out due to
  1371. # NAS-Identifier being too long to fit into a RADIUS attribute.
  1372. params = { "ssid": "radius-acct-open",
  1373. 'acct_server_addr': "127.0.0.1",
  1374. 'acct_server_port': "1813",
  1375. 'acct_server_shared_secret': "radius",
  1376. 'nas_identifier': 255*'A' }
  1377. hapd = hostapd.add_ap(apdev[0], params)
  1378. dev[0].connect("radius-acct-open", key_mgmt="NONE", scan_freq="2412")
  1379. def test_radius_acct_failure_oom(dev, apdev):
  1380. """RADIUS Accounting and failure to add attributes due to OOM"""
  1381. params = { "ssid": "radius-acct-open",
  1382. 'acct_server_addr': "127.0.0.1",
  1383. 'acct_server_port': "1813",
  1384. 'acct_server_shared_secret': "radius",
  1385. 'radius_acct_interim_interval': "1",
  1386. 'nas_identifier': 250*'A',
  1387. 'radius_acct_req_attr': [ "126:s:" + 250*'B',
  1388. "77:s:" + 250*'C',
  1389. "127:s:" + 250*'D',
  1390. "181:s:" + 250*'E' ] }
  1391. hapd = hostapd.add_ap(apdev[0], params)
  1392. bssid = hapd.own_addr()
  1393. dev[0].scan_for_bss(bssid, freq="2412")
  1394. with alloc_fail(hapd, 1, "radius_msg_add_attr;?radius_msg_add_attr_int32;=accounting_msg"):
  1395. dev[0].connect("radius-acct-open", key_mgmt="NONE", scan_freq="2412")
  1396. wait_fail_trigger(hapd, "GET_ALLOC_FAIL")
  1397. dev[0].request("REMOVE_NETWORK all")
  1398. dev[0].wait_disconnected()
  1399. dev[1].scan_for_bss(bssid, freq="2412")
  1400. with alloc_fail(hapd, 1, "accounting_sta_report"):
  1401. dev[1].connect("radius-acct-open", key_mgmt="NONE", scan_freq="2412")
  1402. wait_fail_trigger(hapd, "GET_ALLOC_FAIL")
  1403. dev[1].request("REMOVE_NETWORK all")
  1404. dev[1].wait_disconnected()
  1405. tests = [ (1, "radius_msg_add_attr;?radius_msg_add_attr_int32;=accounting_msg"),
  1406. (2, "radius_msg_add_attr;accounting_msg"),
  1407. (3, "radius_msg_add_attr;accounting_msg") ]
  1408. for count, func in tests:
  1409. with fail_test(hapd, count, func):
  1410. dev[0].connect("radius-acct-open", key_mgmt="NONE",
  1411. scan_freq="2412")
  1412. wait_fail_trigger(hapd, "GET_FAIL")
  1413. dev[0].request("REMOVE_NETWORK all")
  1414. dev[0].wait_disconnected()
  1415. dev[0].connect("radius-acct-open", key_mgmt="NONE", scan_freq="2412")
  1416. with fail_test(hapd, 8,
  1417. "radius_msg_add_attr;?radius_msg_add_attr_int32;=accounting_sta_report"):
  1418. dev[0].request("REMOVE_NETWORK all")
  1419. dev[0].wait_disconnected()
  1420. wait_fail_trigger(hapd, "GET_FAIL")
  1421. with fail_test(hapd, 1, "radius_msg_add_attr;=accounting_report_state"):
  1422. hapd.disable()
  1423. def test_radius_acct_failure_oom_rsn(dev, apdev):
  1424. """RADIUS Accounting in RSN and failure to add attributes due to OOM"""
  1425. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  1426. params['acct_server_addr'] = "127.0.0.1"
  1427. params['acct_server_port'] = "1813"
  1428. params['acct_server_shared_secret'] = "radius"
  1429. params['radius_acct_interim_interval'] = "1"
  1430. params['nas_identifier'] = 250*'A'
  1431. params['radius_acct_req_attr'] = [ "126:s:" + 250*'B',
  1432. "77:s:" + 250*'C',
  1433. "127:s:" + 250*'D',
  1434. "181:s:" + 250*'E' ]
  1435. hapd = hostapd.add_ap(apdev[0], params)
  1436. bssid = hapd.own_addr()
  1437. dev[0].scan_for_bss(bssid, freq="2412")
  1438. with alloc_fail(hapd, 1, "radius_msg_add_attr;?radius_msg_add_attr_int32;=accounting_msg"):
  1439. connect(dev[0], "radius-acct")
  1440. wait_fail_trigger(hapd, "GET_ALLOC_FAIL")
  1441. dev[1].scan_for_bss(bssid, freq="2412")
  1442. with alloc_fail(hapd, 1, "accounting_sta_report"):
  1443. connect(dev[1], "radius-acct")
  1444. wait_fail_trigger(hapd, "GET_ALLOC_FAIL")
  1445. dev[2].scan_for_bss(bssid, freq="2412")
  1446. connect(dev[2], "radius-acct")
  1447. for i in range(1, 8):
  1448. with alloc_fail(hapd, i, "radius_msg_add_attr;?radius_msg_add_attr_int32;=accounting_msg"):
  1449. wait_fail_trigger(hapd, "GET_ALLOC_FAIL")
  1450. for i in range(1, 15):
  1451. with alloc_fail(hapd, i, "radius_msg_add_attr;?radius_msg_add_attr_int32;=accounting_sta_report"):
  1452. wait_fail_trigger(hapd, "GET_ALLOC_FAIL")
  1453. def test_radius_acct_failure_sta_data(dev, apdev):
  1454. """RADIUS Accounting and failure to get STA data"""
  1455. params = { "ssid": "radius-acct-open",
  1456. 'acct_server_addr': "127.0.0.1",
  1457. 'acct_server_port': "1813",
  1458. 'acct_server_shared_secret': "radius" }
  1459. hapd = hostapd.add_ap(apdev[0], params)
  1460. with fail_test(hapd, 1, "accounting_sta_update_stats"):
  1461. dev[0].connect("radius-acct-open", key_mgmt="NONE", scan_freq="2412")
  1462. dev[0].request("DISCONNECT")
  1463. dev[0].wait_disconnected()
  1464. hapd.wait_event(["AP-STA-DISCONNECTED"], timeout=1)