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