test_radius.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  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. import binascii
  7. import hashlib
  8. import hmac
  9. import logging
  10. logger = logging.getLogger()
  11. import os
  12. import select
  13. import struct
  14. import subprocess
  15. import threading
  16. import time
  17. import hostapd
  18. from utils import HwsimSkip, require_under_vm, skip_with_fips, fail_test
  19. from test_ap_hs20 import build_dhcp_ack
  20. from test_ap_ft import ft_params1
  21. def connect(dev, ssid, wait_connect=True):
  22. dev.connect(ssid, key_mgmt="WPA-EAP", scan_freq="2412",
  23. eap="PSK", identity="psk.user@example.com",
  24. password_hex="0123456789abcdef0123456789abcdef",
  25. wait_connect=wait_connect)
  26. def test_radius_auth_unreachable(dev, apdev):
  27. """RADIUS Authentication server unreachable"""
  28. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  29. params['auth_server_port'] = "18139"
  30. hostapd.add_ap(apdev[0], params)
  31. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  32. connect(dev[0], "radius-auth", wait_connect=False)
  33. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
  34. if ev is None:
  35. raise Exception("Timeout on EAP start")
  36. logger.info("Checking for RADIUS retries")
  37. time.sleep(4)
  38. mib = hapd.get_mib()
  39. if "radiusAuthClientAccessRequests" not in mib:
  40. raise Exception("Missing MIB fields")
  41. if int(mib["radiusAuthClientAccessRetransmissions"]) < 1:
  42. raise Exception("Missing RADIUS Authentication retransmission")
  43. if int(mib["radiusAuthClientPendingRequests"]) < 1:
  44. raise Exception("Missing pending RADIUS Authentication request")
  45. def test_radius_auth_unreachable2(dev, apdev):
  46. """RADIUS Authentication server unreachable (2)"""
  47. subprocess.call(['ip', 'ro', 'replace', '192.168.213.17', 'dev', 'lo'])
  48. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  49. params['auth_server_addr'] = "192.168.213.17"
  50. params['auth_server_port'] = "18139"
  51. hostapd.add_ap(apdev[0], params)
  52. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  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. hostapd.add_ap(apdev[0], params)
  71. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  72. connect(dev[0], "radius-auth", wait_connect=False)
  73. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
  74. if ev is None:
  75. raise Exception("Timeout on EAP start")
  76. subprocess.call(['ip', 'ro', 'del', 'blackhole', '192.168.213.18'])
  77. time.sleep(0.1)
  78. dev[0].request("DISCONNECT")
  79. hapd.set('auth_server_addr_replace', '127.0.0.1')
  80. dev[0].request("RECONNECT")
  81. dev[0].wait_connected()
  82. def test_radius_acct_unreachable(dev, apdev):
  83. """RADIUS Accounting server unreachable"""
  84. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  85. params['acct_server_addr'] = "127.0.0.1"
  86. params['acct_server_port'] = "18139"
  87. params['acct_server_shared_secret'] = "radius"
  88. hostapd.add_ap(apdev[0], params)
  89. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  90. connect(dev[0], "radius-acct")
  91. logger.info("Checking for RADIUS retries")
  92. time.sleep(4)
  93. mib = hapd.get_mib()
  94. if "radiusAccClientRetransmissions" not in mib:
  95. raise Exception("Missing MIB fields")
  96. if int(mib["radiusAccClientRetransmissions"]) < 2:
  97. raise Exception("Missing RADIUS Accounting retransmissions")
  98. if int(mib["radiusAccClientPendingRequests"]) < 2:
  99. raise Exception("Missing pending RADIUS Accounting requests")
  100. def test_radius_acct_unreachable2(dev, apdev):
  101. """RADIUS Accounting server unreachable(2)"""
  102. subprocess.call(['ip', 'ro', 'replace', '192.168.213.17', 'dev', 'lo'])
  103. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  104. params['acct_server_addr'] = "192.168.213.17"
  105. params['acct_server_port'] = "18139"
  106. params['acct_server_shared_secret'] = "radius"
  107. hostapd.add_ap(apdev[0], params)
  108. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  109. subprocess.call(['ip', 'ro', 'del', '192.168.213.17', 'dev', 'lo'])
  110. connect(dev[0], "radius-acct")
  111. logger.info("Checking for RADIUS retries")
  112. time.sleep(4)
  113. mib = hapd.get_mib()
  114. if "radiusAccClientRetransmissions" not in mib:
  115. raise Exception("Missing MIB fields")
  116. if int(mib["radiusAccClientRetransmissions"]) < 1 and int(mib["radiusAccClientPendingRequests"]) < 1:
  117. raise Exception("Missing pending or retransmitted RADIUS Accounting requests")
  118. def test_radius_acct_unreachable3(dev, apdev):
  119. """RADIUS Accounting server initially unreachable, but then available"""
  120. require_under_vm()
  121. subprocess.call(['ip', 'ro', 'replace', 'blackhole', '192.168.213.18'])
  122. as_hapd = hostapd.Hostapd("as")
  123. as_mib_start = as_hapd.get_mib(param="radius_server")
  124. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  125. params['acct_server_addr'] = "192.168.213.18"
  126. params['acct_server_port'] = "1813"
  127. params['acct_server_shared_secret'] = "radius"
  128. hostapd.add_ap(apdev[0], params)
  129. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  130. connect(dev[0], "radius-acct")
  131. subprocess.call(['ip', 'ro', 'del', 'blackhole', '192.168.213.18'])
  132. time.sleep(0.1)
  133. dev[0].request("DISCONNECT")
  134. hapd.set('acct_server_addr_replace', '127.0.0.1')
  135. dev[0].request("RECONNECT")
  136. dev[0].wait_connected()
  137. time.sleep(1)
  138. as_mib_end = as_hapd.get_mib(param="radius_server")
  139. req_s = int(as_mib_start['radiusAccServTotalResponses'])
  140. req_e = int(as_mib_end['radiusAccServTotalResponses'])
  141. if req_e <= req_s:
  142. raise Exception("Unexpected RADIUS server acct MIB value")
  143. def test_radius_acct_unreachable4(dev, apdev):
  144. """RADIUS Accounting server unreachable and multiple STAs"""
  145. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  146. params['acct_server_addr'] = "127.0.0.1"
  147. params['acct_server_port'] = "18139"
  148. params['acct_server_shared_secret'] = "radius"
  149. hostapd.add_ap(apdev[0], params)
  150. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  151. for i in range(20):
  152. connect(dev[0], "radius-acct")
  153. dev[0].request("REMOVE_NETWORK all")
  154. dev[0].wait_disconnected()
  155. def test_radius_acct(dev, apdev):
  156. """RADIUS Accounting"""
  157. as_hapd = hostapd.Hostapd("as")
  158. as_mib_start = as_hapd.get_mib(param="radius_server")
  159. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  160. params['acct_server_addr'] = "127.0.0.1"
  161. params['acct_server_port'] = "1813"
  162. params['acct_server_shared_secret'] = "radius"
  163. params['radius_auth_req_attr'] = [ "126:s:Operator", "77:s:testing" ]
  164. params['radius_acct_req_attr'] = [ "126:s:Operator", "77:s:testing" ]
  165. hostapd.add_ap(apdev[0], params)
  166. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  167. connect(dev[0], "radius-acct")
  168. dev[1].connect("radius-acct", key_mgmt="WPA-EAP", scan_freq="2412",
  169. eap="PAX", identity="test-class",
  170. password_hex="0123456789abcdef0123456789abcdef")
  171. dev[2].connect("radius-acct", key_mgmt="WPA-EAP",
  172. eap="GPSK", identity="gpsk-cui",
  173. password="abcdefghijklmnop0123456789abcdef",
  174. scan_freq="2412")
  175. logger.info("Checking for RADIUS counters")
  176. count = 0
  177. while True:
  178. mib = hapd.get_mib()
  179. if int(mib['radiusAccClientResponses']) >= 3:
  180. break
  181. time.sleep(0.1)
  182. count += 1
  183. if count > 10:
  184. raise Exception("Did not receive Accounting-Response packets")
  185. if int(mib['radiusAccClientRetransmissions']) > 0:
  186. raise Exception("Unexpected Accounting-Request retransmission")
  187. as_mib_end = as_hapd.get_mib(param="radius_server")
  188. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  189. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  190. if req_e < req_s + 2:
  191. raise Exception("Unexpected RADIUS server acct MIB value")
  192. acc_s = int(as_mib_start['radiusAuthServAccessAccepts'])
  193. acc_e = int(as_mib_end['radiusAuthServAccessAccepts'])
  194. if acc_e < acc_s + 1:
  195. raise Exception("Unexpected RADIUS server auth MIB value")
  196. def test_radius_acct_non_ascii_ssid(dev, apdev):
  197. """RADIUS Accounting and non-ASCII SSID"""
  198. params = hostapd.wpa2_eap_params()
  199. params['acct_server_addr'] = "127.0.0.1"
  200. params['acct_server_port'] = "1813"
  201. params['acct_server_shared_secret'] = "radius"
  202. ssid2 = "740665007374"
  203. params['ssid2'] = ssid2
  204. hostapd.add_ap(apdev[0], params)
  205. dev[0].connect(ssid2=ssid2, key_mgmt="WPA-EAP", scan_freq="2412",
  206. eap="PSK", identity="psk.user@example.com",
  207. password_hex="0123456789abcdef0123456789abcdef")
  208. def test_radius_acct_pmksa_caching(dev, apdev):
  209. """RADIUS Accounting with PMKSA caching"""
  210. as_hapd = hostapd.Hostapd("as")
  211. as_mib_start = as_hapd.get_mib(param="radius_server")
  212. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  213. params['acct_server_addr'] = "127.0.0.1"
  214. params['acct_server_port'] = "1813"
  215. params['acct_server_shared_secret'] = "radius"
  216. hapd = hostapd.add_ap(apdev[0], params)
  217. connect(dev[0], "radius-acct")
  218. dev[1].connect("radius-acct", key_mgmt="WPA-EAP", scan_freq="2412",
  219. eap="PAX", identity="test-class",
  220. password_hex="0123456789abcdef0123456789abcdef")
  221. for d in [ dev[0], dev[1] ]:
  222. d.request("REASSOCIATE")
  223. d.wait_connected(timeout=15, error="Reassociation timed out")
  224. count = 0
  225. while True:
  226. mib = hapd.get_mib()
  227. if int(mib['radiusAccClientResponses']) >= 4:
  228. break
  229. time.sleep(0.1)
  230. count += 1
  231. if count > 10:
  232. raise Exception("Did not receive Accounting-Response packets")
  233. if int(mib['radiusAccClientRetransmissions']) > 0:
  234. raise Exception("Unexpected Accounting-Request retransmission")
  235. as_mib_end = as_hapd.get_mib(param="radius_server")
  236. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  237. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  238. if req_e < req_s + 2:
  239. raise Exception("Unexpected RADIUS server acct MIB value")
  240. acc_s = int(as_mib_start['radiusAuthServAccessAccepts'])
  241. acc_e = int(as_mib_end['radiusAuthServAccessAccepts'])
  242. if acc_e < acc_s + 1:
  243. raise Exception("Unexpected RADIUS server auth MIB value")
  244. def test_radius_acct_interim(dev, apdev):
  245. """RADIUS Accounting interim update"""
  246. as_hapd = hostapd.Hostapd("as")
  247. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  248. params['acct_server_addr'] = "127.0.0.1"
  249. params['acct_server_port'] = "1813"
  250. params['acct_server_shared_secret'] = "radius"
  251. params['radius_acct_interim_interval'] = "1"
  252. hostapd.add_ap(apdev[0], params)
  253. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  254. connect(dev[0], "radius-acct")
  255. logger.info("Checking for RADIUS counters")
  256. as_mib_start = as_hapd.get_mib(param="radius_server")
  257. time.sleep(3.1)
  258. as_mib_end = as_hapd.get_mib(param="radius_server")
  259. req_s = int(as_mib_start['radiusAccServTotalRequests'])
  260. req_e = int(as_mib_end['radiusAccServTotalRequests'])
  261. if req_e < req_s + 3:
  262. raise Exception("Unexpected RADIUS server acct MIB value")
  263. def test_radius_acct_interim_unreachable(dev, apdev):
  264. """RADIUS Accounting interim update with unreachable server"""
  265. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  266. params['acct_server_addr'] = "127.0.0.1"
  267. params['acct_server_port'] = "18139"
  268. params['acct_server_shared_secret'] = "radius"
  269. params['radius_acct_interim_interval'] = "1"
  270. hapd = hostapd.add_ap(apdev[0], params)
  271. start = hapd.get_mib()
  272. connect(dev[0], "radius-acct")
  273. logger.info("Waiting for interium accounting updates")
  274. time.sleep(3.1)
  275. end = hapd.get_mib()
  276. req_s = int(start['radiusAccClientTimeouts'])
  277. req_e = int(end['radiusAccClientTimeouts'])
  278. if req_e < req_s + 2:
  279. raise Exception("Unexpected RADIUS server acct MIB value")
  280. def test_radius_acct_interim_unreachable2(dev, apdev):
  281. """RADIUS Accounting interim update with unreachable server (retry)"""
  282. params = hostapd.wpa2_eap_params(ssid="radius-acct")
  283. params['acct_server_addr'] = "127.0.0.1"
  284. params['acct_server_port'] = "18139"
  285. params['acct_server_shared_secret'] = "radius"
  286. # Use long enough interim update interval to allow RADIUS retransmission
  287. # case (3 seconds) to trigger first.
  288. params['radius_acct_interim_interval'] = "4"
  289. hapd = hostapd.add_ap(apdev[0], params)
  290. start = hapd.get_mib()
  291. connect(dev[0], "radius-acct")
  292. logger.info("Waiting for interium accounting updates")
  293. time.sleep(7.5)
  294. end = hapd.get_mib()
  295. req_s = int(start['radiusAccClientTimeouts'])
  296. req_e = int(end['radiusAccClientTimeouts'])
  297. if req_e < req_s + 2:
  298. raise Exception("Unexpected RADIUS server acct MIB value")
  299. def test_radius_acct_ipaddr(dev, apdev):
  300. """RADIUS Accounting and Framed-IP-Address"""
  301. try:
  302. _test_radius_acct_ipaddr(dev, apdev)
  303. finally:
  304. subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
  305. stderr=open('/dev/null', 'w'))
  306. subprocess.call(['brctl', 'delbr', 'ap-br0'],
  307. stderr=open('/dev/null', 'w'))
  308. def _test_radius_acct_ipaddr(dev, apdev):
  309. params = { "ssid": "radius-acct-open",
  310. 'acct_server_addr': "127.0.0.1",
  311. 'acct_server_port': "1813",
  312. 'acct_server_shared_secret': "radius",
  313. 'proxy_arp': '1',
  314. 'ap_isolate': '1',
  315. 'bridge': 'ap-br0' }
  316. hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
  317. try:
  318. hapd.enable()
  319. except:
  320. # For now, do not report failures due to missing kernel support
  321. raise HwsimSkip("Could not start hostapd - assume proxyarp not supported in kernel version")
  322. bssid = apdev[0]['bssid']
  323. subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
  324. subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
  325. dev[0].connect("radius-acct-open", key_mgmt="NONE", scan_freq="2412")
  326. addr0 = dev[0].own_addr()
  327. pkt = build_dhcp_ack(dst_ll="ff:ff:ff:ff:ff:ff", src_ll=bssid,
  328. ip_src="192.168.1.1", ip_dst="255.255.255.255",
  329. yiaddr="192.168.1.123", chaddr=addr0)
  330. if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
  331. raise Exception("DATA_TEST_FRAME failed")
  332. dev[0].request("DISCONNECT")
  333. dev[0].wait_disconnected()
  334. hapd.disable()
  335. def send_and_check_reply(srv, req, code, error_cause=0):
  336. reply = srv.SendPacket(req)
  337. logger.debug("RADIUS response from hostapd")
  338. for i in reply.keys():
  339. logger.debug("%s: %s" % (i, reply[i]))
  340. if reply.code != code:
  341. raise Exception("Unexpected response code")
  342. if error_cause:
  343. if 'Error-Cause' not in reply:
  344. raise Exception("Missing Error-Cause")
  345. if reply['Error-Cause'][0] != error_cause:
  346. raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))
  347. def test_radius_acct_psk(dev, apdev):
  348. """RADIUS Accounting - PSK"""
  349. as_hapd = hostapd.Hostapd("as")
  350. params = hostapd.wpa2_params(ssid="radius-acct", passphrase="12345678")
  351. params['acct_server_addr'] = "127.0.0.1"
  352. params['acct_server_port'] = "1813"
  353. params['acct_server_shared_secret'] = "radius"
  354. hapd = hostapd.add_ap(apdev[0], params)
  355. dev[0].connect("radius-acct", psk="12345678", scan_freq="2412")
  356. def test_radius_acct_psk_sha256(dev, apdev):
  357. """RADIUS Accounting - PSK SHA256"""
  358. as_hapd = hostapd.Hostapd("as")
  359. params = hostapd.wpa2_params(ssid="radius-acct", passphrase="12345678")
  360. params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
  361. params['acct_server_addr'] = "127.0.0.1"
  362. params['acct_server_port'] = "1813"
  363. params['acct_server_shared_secret'] = "radius"
  364. hapd = hostapd.add_ap(apdev[0], params)
  365. dev[0].connect("radius-acct", key_mgmt="WPA-PSK-SHA256",
  366. psk="12345678", scan_freq="2412")
  367. def test_radius_acct_ft_psk(dev, apdev):
  368. """RADIUS Accounting - FT-PSK"""
  369. as_hapd = hostapd.Hostapd("as")
  370. params = ft_params1(ssid="radius-acct", passphrase="12345678")
  371. params['acct_server_addr'] = "127.0.0.1"
  372. params['acct_server_port'] = "1813"
  373. params['acct_server_shared_secret'] = "radius"
  374. hapd = hostapd.add_ap(apdev[0], params)
  375. dev[0].connect("radius-acct", key_mgmt="FT-PSK",
  376. psk="12345678", scan_freq="2412")
  377. def test_radius_acct_ieee8021x(dev, apdev):
  378. """RADIUS Accounting - IEEE 802.1X"""
  379. skip_with_fips(dev[0])
  380. as_hapd = hostapd.Hostapd("as")
  381. params = hostapd.radius_params()
  382. params["ssid"] = "radius-acct-1x"
  383. params["ieee8021x"] = "1"
  384. params["wep_key_len_broadcast"] = "13"
  385. params["wep_key_len_unicast"] = "13"
  386. params['acct_server_addr'] = "127.0.0.1"
  387. params['acct_server_port'] = "1813"
  388. params['acct_server_shared_secret'] = "radius"
  389. hapd = hostapd.add_ap(apdev[0], params)
  390. dev[0].connect("radius-acct-1x", key_mgmt="IEEE8021X", eap="PSK",
  391. identity="psk.user@example.com",
  392. password_hex="0123456789abcdef0123456789abcdef",
  393. scan_freq="2412")
  394. def test_radius_das_disconnect(dev, apdev):
  395. """RADIUS Dynamic Authorization Extensions - Disconnect"""
  396. try:
  397. import pyrad.client
  398. import pyrad.packet
  399. import pyrad.dictionary
  400. import radius_das
  401. except ImportError:
  402. raise HwsimSkip("No pyrad modules available")
  403. params = hostapd.wpa2_eap_params(ssid="radius-das")
  404. params['radius_das_port'] = "3799"
  405. params['radius_das_client'] = "127.0.0.1 secret"
  406. params['radius_das_require_event_timestamp'] = "1"
  407. params['own_ip_addr'] = "127.0.0.1"
  408. params['nas_identifier'] = "nas.example.com"
  409. hapd = hostapd.add_ap(apdev[0], params)
  410. connect(dev[0], "radius-das")
  411. addr = dev[0].p2p_interface_addr()
  412. sta = hapd.get_sta(addr)
  413. id = sta['dot1xAuthSessionId']
  414. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  415. srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
  416. secret="secret", dict=dict)
  417. srv.retries = 1
  418. srv.timeout = 1
  419. logger.info("Disconnect-Request with incorrect secret")
  420. req = radius_das.DisconnectPacket(dict=dict, secret="incorrect",
  421. User_Name="foo",
  422. NAS_Identifier="localhost",
  423. Event_Timestamp=int(time.time()))
  424. logger.debug(req)
  425. try:
  426. reply = srv.SendPacket(req)
  427. raise Exception("Unexpected response to Disconnect-Request")
  428. except pyrad.client.Timeout:
  429. logger.info("Disconnect-Request with incorrect secret properly ignored")
  430. logger.info("Disconnect-Request without Event-Timestamp")
  431. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  432. User_Name="psk.user@example.com")
  433. logger.debug(req)
  434. try:
  435. reply = srv.SendPacket(req)
  436. raise Exception("Unexpected response to Disconnect-Request")
  437. except pyrad.client.Timeout:
  438. logger.info("Disconnect-Request without Event-Timestamp properly ignored")
  439. logger.info("Disconnect-Request with non-matching Event-Timestamp")
  440. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  441. User_Name="psk.user@example.com",
  442. Event_Timestamp=123456789)
  443. logger.debug(req)
  444. try:
  445. reply = srv.SendPacket(req)
  446. raise Exception("Unexpected response to Disconnect-Request")
  447. except pyrad.client.Timeout:
  448. logger.info("Disconnect-Request with non-matching Event-Timestamp properly ignored")
  449. logger.info("Disconnect-Request with unsupported attribute")
  450. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  451. User_Name="foo",
  452. User_Password="foo",
  453. Event_Timestamp=int(time.time()))
  454. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 401)
  455. logger.info("Disconnect-Request with invalid Calling-Station-Id")
  456. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  457. User_Name="foo",
  458. Calling_Station_Id="foo",
  459. Event_Timestamp=int(time.time()))
  460. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 407)
  461. logger.info("Disconnect-Request with mismatching User-Name")
  462. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  463. User_Name="foo",
  464. Event_Timestamp=int(time.time()))
  465. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)
  466. logger.info("Disconnect-Request with mismatching Calling-Station-Id")
  467. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  468. Calling_Station_Id="12:34:56:78:90:aa",
  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")
  472. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  473. Acct_Session_Id="12345678-87654321",
  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-Session-Id (len)")
  477. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  478. Acct_Session_Id="12345678",
  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")
  482. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  483. Acct_Multi_Session_Id="12345678+87654321",
  484. Event_Timestamp=int(time.time()))
  485. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)
  486. logger.info("Disconnect-Request with mismatching Acct-Multi-Session-Id (len)")
  487. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  488. Acct_Multi_Session_Id="12345678",
  489. Event_Timestamp=int(time.time()))
  490. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)
  491. logger.info("Disconnect-Request with no session identification attributes")
  492. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  493. Event_Timestamp=int(time.time()))
  494. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)
  495. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  496. if ev is not None:
  497. raise Exception("Unexpected disconnection")
  498. logger.info("Disconnect-Request with mismatching NAS-IP-Address")
  499. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  500. NAS_IP_Address="192.168.3.4",
  501. Acct_Session_Id=id,
  502. Event_Timestamp=int(time.time()))
  503. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 403)
  504. logger.info("Disconnect-Request with mismatching NAS-Identifier")
  505. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  506. NAS_Identifier="unknown.example.com",
  507. Acct_Session_Id=id,
  508. Event_Timestamp=int(time.time()))
  509. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 403)
  510. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  511. if ev is not None:
  512. raise Exception("Unexpected disconnection")
  513. logger.info("Disconnect-Request with matching Acct-Session-Id")
  514. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  515. NAS_IP_Address="127.0.0.1",
  516. NAS_Identifier="nas.example.com",
  517. Acct_Session_Id=id,
  518. Event_Timestamp=int(time.time()))
  519. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  520. dev[0].wait_disconnected(timeout=10)
  521. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  522. logger.info("Disconnect-Request with matching Acct-Multi-Session-Id")
  523. sta = hapd.get_sta(addr)
  524. multi_sess_id = sta['authMultiSessionId']
  525. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  526. NAS_IP_Address="127.0.0.1",
  527. NAS_Identifier="nas.example.com",
  528. Acct_Multi_Session_Id=multi_sess_id,
  529. Event_Timestamp=int(time.time()))
  530. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  531. dev[0].wait_disconnected(timeout=10)
  532. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  533. logger.info("Disconnect-Request with matching User-Name")
  534. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  535. NAS_Identifier="nas.example.com",
  536. User_Name="psk.user@example.com",
  537. Event_Timestamp=int(time.time()))
  538. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  539. dev[0].wait_disconnected(timeout=10)
  540. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  541. logger.info("Disconnect-Request with matching Calling-Station-Id")
  542. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  543. NAS_IP_Address="127.0.0.1",
  544. Calling_Station_Id=addr,
  545. Event_Timestamp=int(time.time()))
  546. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  547. dev[0].wait_disconnected(timeout=10)
  548. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", "CTRL-EVENT-CONNECTED"])
  549. if ev is None:
  550. raise Exception("Timeout while waiting for re-connection")
  551. if "CTRL-EVENT-EAP-STARTED" not in ev:
  552. raise Exception("Unexpected skipping of EAP authentication in reconnection")
  553. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  554. logger.info("Disconnect-Request with matching Calling-Station-Id and non-matching CUI")
  555. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  556. Calling_Station_Id=addr,
  557. Chargeable_User_Identity="foo@example.com",
  558. Event_Timestamp=int(time.time()))
  559. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, error_cause=503)
  560. logger.info("Disconnect-Request with matching CUI")
  561. dev[1].connect("radius-das", key_mgmt="WPA-EAP",
  562. eap="GPSK", identity="gpsk-cui",
  563. password="abcdefghijklmnop0123456789abcdef",
  564. scan_freq="2412")
  565. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  566. Chargeable_User_Identity="gpsk-chargeable-user-identity",
  567. Event_Timestamp=int(time.time()))
  568. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  569. dev[1].wait_disconnected(timeout=10)
  570. dev[1].wait_connected(timeout=10, error="Re-connection timed out")
  571. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  572. if ev is not None:
  573. raise Exception("Unexpected disconnection")
  574. connect(dev[2], "radius-das")
  575. logger.info("Disconnect-Request with matching User-Name - multiple sessions matching")
  576. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  577. NAS_Identifier="nas.example.com",
  578. User_Name="psk.user@example.com",
  579. Event_Timestamp=int(time.time()))
  580. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, error_cause=508)
  581. logger.info("Disconnect-Request with User-Name matching multiple sessions, Calling-Station-Id only one")
  582. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  583. NAS_Identifier="nas.example.com",
  584. Calling_Station_Id=addr,
  585. User_Name="psk.user@example.com",
  586. Event_Timestamp=int(time.time()))
  587. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  588. dev[0].wait_disconnected(timeout=10)
  589. dev[0].wait_connected(timeout=10, error="Re-connection timed out")
  590. ev = dev[2].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
  591. if ev is not None:
  592. raise Exception("Unexpected disconnection")
  593. logger.info("Disconnect-Request with matching Acct-Multi-Session-Id after disassociation")
  594. sta = hapd.get_sta(addr)
  595. multi_sess_id = sta['authMultiSessionId']
  596. dev[0].request("DISCONNECT")
  597. dev[0].wait_disconnected(timeout=10)
  598. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  599. NAS_IP_Address="127.0.0.1",
  600. NAS_Identifier="nas.example.com",
  601. Acct_Multi_Session_Id=multi_sess_id,
  602. Event_Timestamp=int(time.time()))
  603. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  604. dev[0].request("RECONNECT")
  605. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
  606. if ev is None:
  607. raise Exception("Timeout on EAP start")
  608. dev[0].wait_connected(timeout=15)
  609. logger.info("Disconnect-Request with matching User-Name after disassociation")
  610. dev[0].request("DISCONNECT")
  611. dev[0].wait_disconnected(timeout=10)
  612. dev[2].request("DISCONNECT")
  613. dev[2].wait_disconnected(timeout=10)
  614. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  615. NAS_IP_Address="127.0.0.1",
  616. NAS_Identifier="nas.example.com",
  617. User_Name="psk.user@example.com",
  618. Event_Timestamp=int(time.time()))
  619. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  620. logger.info("Disconnect-Request with matching CUI after disassociation")
  621. dev[1].request("DISCONNECT")
  622. dev[1].wait_disconnected(timeout=10)
  623. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  624. NAS_IP_Address="127.0.0.1",
  625. NAS_Identifier="nas.example.com",
  626. Chargeable_User_Identity="gpsk-chargeable-user-identity",
  627. Event_Timestamp=int(time.time()))
  628. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  629. logger.info("Disconnect-Request with matching Calling-Station-Id after disassociation")
  630. dev[0].request("RECONNECT")
  631. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
  632. if ev is None:
  633. raise Exception("Timeout on EAP start")
  634. dev[0].wait_connected(timeout=15)
  635. dev[0].request("DISCONNECT")
  636. dev[0].wait_disconnected(timeout=10)
  637. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  638. NAS_IP_Address="127.0.0.1",
  639. NAS_Identifier="nas.example.com",
  640. Calling_Station_Id=addr,
  641. Event_Timestamp=int(time.time()))
  642. send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)
  643. logger.info("Disconnect-Request with mismatching Calling-Station-Id after disassociation")
  644. req = radius_das.DisconnectPacket(dict=dict, secret="secret",
  645. NAS_IP_Address="127.0.0.1",
  646. NAS_Identifier="nas.example.com",
  647. Calling_Station_Id=addr,
  648. Event_Timestamp=int(time.time()))
  649. send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, error_cause=503)
  650. def test_radius_das_coa(dev, apdev):
  651. """RADIUS Dynamic Authorization Extensions - CoA"""
  652. try:
  653. import pyrad.client
  654. import pyrad.packet
  655. import pyrad.dictionary
  656. import radius_das
  657. except ImportError:
  658. raise HwsimSkip("No pyrad modules available")
  659. params = hostapd.wpa2_eap_params(ssid="radius-das")
  660. params['radius_das_port'] = "3799"
  661. params['radius_das_client'] = "127.0.0.1 secret"
  662. params['radius_das_require_event_timestamp'] = "1"
  663. hapd = hostapd.add_ap(apdev[0], params)
  664. connect(dev[0], "radius-das")
  665. addr = dev[0].p2p_interface_addr()
  666. sta = hapd.get_sta(addr)
  667. id = sta['dot1xAuthSessionId']
  668. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  669. srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
  670. secret="secret", dict=dict)
  671. srv.retries = 1
  672. srv.timeout = 1
  673. # hostapd does not currently support CoA-Request, so NAK is expected
  674. logger.info("CoA-Request with matching Acct-Session-Id")
  675. req = radius_das.CoAPacket(dict=dict, secret="secret",
  676. Acct_Session_Id=id,
  677. Event_Timestamp=int(time.time()))
  678. send_and_check_reply(srv, req, pyrad.packet.CoANAK, error_cause=405)
  679. def test_radius_ipv6(dev, apdev):
  680. """RADIUS connection over IPv6"""
  681. params = {}
  682. params['ssid'] = 'as'
  683. params['beacon_int'] = '2000'
  684. params['radius_server_clients'] = 'auth_serv/radius_clients_ipv6.conf'
  685. params['radius_server_ipv6'] = '1'
  686. params['radius_server_auth_port'] = '18129'
  687. params['radius_server_acct_port'] = '18139'
  688. params['eap_server'] = '1'
  689. params['eap_user_file'] = 'auth_serv/eap_user.conf'
  690. params['ca_cert'] = 'auth_serv/ca.pem'
  691. params['server_cert'] = 'auth_serv/server.pem'
  692. params['private_key'] = 'auth_serv/server.key'
  693. hostapd.add_ap(apdev[1], params)
  694. params = hostapd.wpa2_eap_params(ssid="radius-ipv6")
  695. params['auth_server_addr'] = "::0"
  696. params['auth_server_port'] = "18129"
  697. params['acct_server_addr'] = "::0"
  698. params['acct_server_port'] = "18139"
  699. params['acct_server_shared_secret'] = "radius"
  700. params['own_ip_addr'] = "::0"
  701. hostapd.add_ap(apdev[0], params)
  702. connect(dev[0], "radius-ipv6")
  703. def test_radius_macacl(dev, apdev):
  704. """RADIUS MAC ACL"""
  705. params = hostapd.radius_params()
  706. params["ssid"] = "radius"
  707. params["macaddr_acl"] = "2"
  708. hostapd.add_ap(apdev[0], params)
  709. dev[0].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. def test_radius_auth_force_invalid_client_addr(dev, apdev):
  1033. """RADIUS client address specified and invalid address"""
  1034. params = hostapd.wpa2_eap_params(ssid="radius-auth")
  1035. #params['radius_client_addr'] = "10.11.12.14"
  1036. params['radius_client_addr'] = "1::2"
  1037. hapd = hostapd.add_ap(apdev[0], params)
  1038. connect(dev[0], "radius-auth", wait_connect=False)
  1039. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
  1040. if ev is None:
  1041. raise Exception("Timeout on EAP start")
  1042. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  1043. if ev is not None:
  1044. raise Exception("Unexpected connection")
  1045. def add_message_auth(req):
  1046. req.authenticator = req.CreateAuthenticator()
  1047. hmac_obj = hmac.new(req.secret)
  1048. hmac_obj.update(struct.pack("B", req.code))
  1049. hmac_obj.update(struct.pack("B", req.id))
  1050. # request attributes
  1051. req.AddAttribute("Message-Authenticator",
  1052. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
  1053. attrs = req._PktEncodeAttributes()
  1054. # Length
  1055. flen = 4 + 16 + len(attrs)
  1056. hmac_obj.update(struct.pack(">H", flen))
  1057. hmac_obj.update(req.authenticator)
  1058. hmac_obj.update(attrs)
  1059. del req[80]
  1060. req.AddAttribute("Message-Authenticator", hmac_obj.digest())
  1061. def test_radius_server_failures(dev, apdev):
  1062. """RADIUS server failure cases"""
  1063. try:
  1064. import pyrad.client
  1065. import pyrad.packet
  1066. import pyrad.dictionary
  1067. except ImportError:
  1068. raise HwsimSkip("No pyrad modules available")
  1069. dict = pyrad.dictionary.Dictionary("dictionary.radius")
  1070. client = pyrad.client.Client(server="127.0.0.1", authport=1812,
  1071. secret="radius", dict=dict)
  1072. client.retries = 1
  1073. client.timeout = 1
  1074. # unexpected State
  1075. req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest,
  1076. User_Name="foo")
  1077. req['State'] = 'foo-state'
  1078. add_message_auth(req)
  1079. reply = client.SendPacket(req)
  1080. if reply.code != pyrad.packet.AccessReject:
  1081. raise Exception("Unexpected RADIUS response code " + str(reply.code))
  1082. # no EAP-Message
  1083. req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest,
  1084. User_Name="foo")
  1085. add_message_auth(req)
  1086. try:
  1087. reply = client.SendPacket(req)
  1088. raise Exception("Unexpected response")
  1089. except pyrad.client.Timeout:
  1090. pass
  1091. def test_ap_vlan_wpa2_psk_radius_required(dev, apdev):
  1092. """AP VLAN with WPA2-PSK and RADIUS attributes required"""
  1093. try:
  1094. import pyrad.server
  1095. import pyrad.packet
  1096. import pyrad.dictionary
  1097. except ImportError:
  1098. raise HwsimSkip("No pyrad modules available")
  1099. class TestServer(pyrad.server.Server):
  1100. def _HandleAuthPacket(self, pkt):
  1101. pyrad.server.Server._HandleAuthPacket(self, pkt)
  1102. logger.info("Received authentication request")
  1103. reply = self.CreateReplyPacket(pkt)
  1104. reply.code = pyrad.packet.AccessAccept
  1105. secret = reply.secret
  1106. if self.t_events['extra'].is_set():
  1107. reply.AddAttribute("Chargeable-User-Identity", "test-cui")
  1108. reply.AddAttribute("User-Name", "test-user")
  1109. if self.t_events['long'].is_set():
  1110. reply.AddAttribute("Tunnel-Type", 13)
  1111. reply.AddAttribute("Tunnel-Medium-Type", 6)
  1112. reply.AddAttribute("Tunnel-Private-Group-ID", "1")
  1113. self.SendReplyPacket(pkt.fd, reply)
  1114. def RunWithStop(self, t_events):
  1115. self._poll = select.poll()
  1116. self._fdmap = {}
  1117. self._PrepareSockets()
  1118. self.t_events = t_events
  1119. while not t_events['stop'].is_set():
  1120. for (fd, event) in self._poll.poll(1000):
  1121. if event == select.POLLIN:
  1122. try:
  1123. fdo = self._fdmap[fd]
  1124. self._ProcessInput(fdo)
  1125. except pyrad.server.ServerPacketError as err:
  1126. logger.info("pyrad server dropping packet: " + str(err))
  1127. except pyrad.packet.PacketError as err:
  1128. logger.info("pyrad server received invalid packet: " + str(err))
  1129. else:
  1130. logger.error("Unexpected event in pyrad server main loop")
  1131. srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
  1132. authport=18138, acctport=18139)
  1133. srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
  1134. "radius",
  1135. "localhost")
  1136. srv.BindToAddress("")
  1137. t_events = {}
  1138. t_events['stop'] = threading.Event()
  1139. t_events['long'] = threading.Event()
  1140. t_events['extra'] = threading.Event()
  1141. t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
  1142. t.start()
  1143. try:
  1144. ssid = "test-wpa2-psk"
  1145. params = hostapd.radius_params()
  1146. params['ssid'] = ssid
  1147. params["wpa"] = "2"
  1148. params["wpa_key_mgmt"] = "WPA-PSK"
  1149. params["rsn_pairwise"] = "CCMP"
  1150. params['macaddr_acl'] = '2'
  1151. params['dynamic_vlan'] = "2"
  1152. params['wpa_passphrase'] = '0123456789abcdefghi'
  1153. params['auth_server_port'] = "18138"
  1154. hapd = hostapd.add_ap(apdev[0], params)
  1155. logger.info("connecting without VLAN")
  1156. dev[0].connect(ssid, psk="0123456789abcdefghi", scan_freq="2412",
  1157. wait_connect=False)
  1158. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
  1159. "CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=20)
  1160. if ev is None:
  1161. raise Exception("Timeout on connection attempt")
  1162. if "CTRL-EVENT-CONNECTED" in ev:
  1163. raise Exception("Unexpected success without vlan parameters")
  1164. logger.info("connecting without VLAN failed as expected")
  1165. logger.info("connecting without VLAN (CUI/User-Name)")
  1166. t_events['extra'].set()
  1167. dev[1].connect(ssid, psk="0123456789abcdefghi", scan_freq="2412",
  1168. wait_connect=False)
  1169. ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED",
  1170. "CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=20)
  1171. if ev is None:
  1172. raise Exception("Timeout on connection attempt")
  1173. if "CTRL-EVENT-CONNECTED" in ev:
  1174. raise Exception("Unexpected success without vlan parameters(2)")
  1175. logger.info("connecting without VLAN failed as expected(2)")
  1176. t_events['extra'].clear()
  1177. t_events['long'].set()
  1178. logger.info("connecting with VLAN")
  1179. dev[2].connect(ssid, psk="0123456789abcdefghi", scan_freq="2412",
  1180. wait_connect=False)
  1181. ev = dev[2].wait_event(["CTRL-EVENT-CONNECTED",
  1182. "CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=20)
  1183. if ev is None:
  1184. raise Exception("Timeout on connection attempt")
  1185. if "CTRL-EVENT-SSID-TEMP-DISABLED" in ev:
  1186. raise Exception("Unexpected failure with vlan parameters")
  1187. logger.info("connecting with VLAN succeeded as expected")
  1188. finally:
  1189. t_events['stop'].set()
  1190. t.join()
  1191. def test_radius_mppe_failure(dev, apdev):
  1192. """RADIUS failure when adding MPPE keys"""
  1193. params = { "ssid": "as", "beacon_int": "2000",
  1194. "radius_server_clients": "auth_serv/radius_clients.conf",
  1195. "radius_server_auth_port": '18127',
  1196. "eap_server": "1",
  1197. "eap_user_file": "auth_serv/eap_user.conf",
  1198. "ca_cert": "auth_serv/ca.pem",
  1199. "server_cert": "auth_serv/server.pem",
  1200. "private_key": "auth_serv/server.key" }
  1201. authsrv = hostapd.add_ap(apdev[1], params)
  1202. params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
  1203. params['auth_server_port'] = "18127"
  1204. hapd = hostapd.add_ap(apdev[0], params)
  1205. with fail_test(authsrv, 1, "os_get_random;radius_msg_add_mppe_keys"):
  1206. dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
  1207. identity="user", anonymous_identity="ttls",
  1208. password="password",
  1209. ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
  1210. wait_connect=False, scan_freq="2412")
  1211. dev[0].wait_disconnected()
  1212. dev[0].request("REMOVE_NETWORK all")