test_ap_wps.py 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317
  1. # WPS tests
  2. # Copyright (c) 2013-2015, 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 os
  7. import time
  8. import stat
  9. import subprocess
  10. import logging
  11. logger = logging.getLogger()
  12. import re
  13. import socket
  14. import httplib
  15. import urlparse
  16. import urllib
  17. import xml.etree.ElementTree as ET
  18. import StringIO
  19. import SocketServer
  20. import hwsim_utils
  21. import hostapd
  22. from wpasupplicant import WpaSupplicant
  23. from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips
  24. def test_ap_wps_init(dev, apdev):
  25. """Initial AP configuration with first WPS Enrollee"""
  26. ssid = "test-wps"
  27. hostapd.add_ap(apdev[0]['ifname'],
  28. { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
  29. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  30. logger.info("WPS provisioning step")
  31. hapd.request("WPS_PBC")
  32. if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
  33. raise Exception("PBC status not shown correctly")
  34. id = dev[0].add_network()
  35. dev[0].set_network_quoted(id, "ssid", "home")
  36. dev[0].set_network_quoted(id, "psk", "12345678")
  37. dev[0].request("ENABLE_NETWORK %s no-connect" % id)
  38. id = dev[0].add_network()
  39. dev[0].set_network_quoted(id, "ssid", "home2")
  40. dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
  41. dev[0].set_network(id, "key_mgmt", "NONE")
  42. dev[0].request("ENABLE_NETWORK %s no-connect" % id)
  43. dev[0].request("WPS_PBC")
  44. dev[0].wait_connected(timeout=30)
  45. status = dev[0].get_status()
  46. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  47. raise Exception("Not fully connected")
  48. if status['ssid'] != ssid:
  49. raise Exception("Unexpected SSID")
  50. if status['pairwise_cipher'] != 'CCMP':
  51. raise Exception("Unexpected encryption configuration")
  52. if status['key_mgmt'] != 'WPA2-PSK':
  53. raise Exception("Unexpected key_mgmt")
  54. status = hapd.request("WPS_GET_STATUS")
  55. if "PBC Status: Disabled" not in status:
  56. raise Exception("PBC status not shown correctly")
  57. if "Last WPS result: Success" not in status:
  58. raise Exception("Last WPS result not shown correctly")
  59. if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
  60. raise Exception("Peer address not shown correctly")
  61. conf = hapd.request("GET_CONFIG")
  62. if "wps_state=configured" not in conf:
  63. raise Exception("AP not in WPS configured state")
  64. if "wpa=3" not in conf:
  65. raise Exception("AP not in WPA+WPA2 configuration")
  66. if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
  67. raise Exception("Unexpected rsn_pairwise_cipher")
  68. if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
  69. raise Exception("Unexpected wpa_pairwise_cipher")
  70. if "group_cipher=TKIP" not in conf:
  71. raise Exception("Unexpected group_cipher")
  72. if len(dev[0].list_networks()) != 3:
  73. raise Exception("Unexpected number of network blocks")
  74. def test_ap_wps_init_2ap_pbc(dev, apdev):
  75. """Initial two-radio AP configuration with first WPS PBC Enrollee"""
  76. ssid = "test-wps"
  77. params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
  78. hostapd.add_ap(apdev[0]['ifname'], params)
  79. hostapd.add_ap(apdev[1]['ifname'], params)
  80. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  81. logger.info("WPS provisioning step")
  82. hapd.request("WPS_PBC")
  83. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
  84. dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
  85. bss = dev[0].get_bss(apdev[0]['bssid'])
  86. if "[WPS-PBC]" not in bss['flags']:
  87. raise Exception("WPS-PBC flag missing from AP1")
  88. bss = dev[0].get_bss(apdev[1]['bssid'])
  89. if "[WPS-PBC]" not in bss['flags']:
  90. raise Exception("WPS-PBC flag missing from AP2")
  91. dev[0].dump_monitor()
  92. dev[0].request("SET wps_cred_processing 2")
  93. dev[0].request("WPS_PBC")
  94. ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
  95. dev[0].request("SET wps_cred_processing 0")
  96. if ev is None:
  97. raise Exception("WPS cred event not seen")
  98. if "100e" not in ev:
  99. raise Exception("WPS attributes not included in the cred event")
  100. dev[0].wait_connected(timeout=30)
  101. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
  102. dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
  103. bss = dev[1].get_bss(apdev[0]['bssid'])
  104. if "[WPS-PBC]" in bss['flags']:
  105. raise Exception("WPS-PBC flag not cleared from AP1")
  106. bss = dev[1].get_bss(apdev[1]['bssid'])
  107. if "[WPS-PBC]" in bss['flags']:
  108. raise Exception("WPS-PBC flag not cleared from AP2")
  109. def test_ap_wps_init_2ap_pin(dev, apdev):
  110. """Initial two-radio AP configuration with first WPS PIN Enrollee"""
  111. ssid = "test-wps"
  112. params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
  113. hostapd.add_ap(apdev[0]['ifname'], params)
  114. hostapd.add_ap(apdev[1]['ifname'], params)
  115. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  116. logger.info("WPS provisioning step")
  117. pin = dev[0].wps_read_pin()
  118. hapd.request("WPS_PIN any " + pin)
  119. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
  120. dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
  121. bss = dev[0].get_bss(apdev[0]['bssid'])
  122. if "[WPS-AUTH]" not in bss['flags']:
  123. raise Exception("WPS-AUTH flag missing from AP1")
  124. bss = dev[0].get_bss(apdev[1]['bssid'])
  125. if "[WPS-AUTH]" not in bss['flags']:
  126. raise Exception("WPS-AUTH flag missing from AP2")
  127. dev[0].dump_monitor()
  128. dev[0].request("WPS_PIN any " + pin)
  129. dev[0].wait_connected(timeout=30)
  130. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
  131. dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
  132. bss = dev[1].get_bss(apdev[0]['bssid'])
  133. if "[WPS-AUTH]" in bss['flags']:
  134. raise Exception("WPS-AUTH flag not cleared from AP1")
  135. bss = dev[1].get_bss(apdev[1]['bssid'])
  136. if "[WPS-AUTH]" in bss['flags']:
  137. raise Exception("WPS-AUTH flag not cleared from AP2")
  138. def test_ap_wps_init_through_wps_config(dev, apdev):
  139. """Initial AP configuration using wps_config command"""
  140. ssid = "test-wps-init-config"
  141. hostapd.add_ap(apdev[0]['ifname'],
  142. { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
  143. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  144. if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
  145. raise Exception("WPS_CONFIG command failed")
  146. ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
  147. if ev is None:
  148. raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
  149. # It takes some time for the AP to update Beacon and Probe Response frames,
  150. # so wait here before requesting the scan to be started to avoid adding
  151. # extra five second wait to the test due to fetching obsolete scan results.
  152. hapd.ping()
  153. time.sleep(0.2)
  154. dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
  155. pairwise="CCMP", group="CCMP")
  156. def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
  157. """AP configuration using wps_config command with invalid passphrase"""
  158. ssid = "test-wps-init-config"
  159. hostapd.add_ap(apdev[0]['ifname'],
  160. { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
  161. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  162. if "FAIL" not in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "1234567".encode("hex")):
  163. raise Exception("Invalid WPS_CONFIG command accepted")
  164. def test_ap_wps_conf(dev, apdev):
  165. """WPS PBC provisioning with configured AP"""
  166. ssid = "test-wps-conf"
  167. hostapd.add_ap(apdev[0]['ifname'],
  168. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  169. "wpa_passphrase": "12345678", "wpa": "2",
  170. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  171. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  172. logger.info("WPS provisioning step")
  173. hapd.request("WPS_PBC")
  174. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  175. dev[0].dump_monitor()
  176. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  177. dev[0].wait_connected(timeout=30)
  178. status = dev[0].get_status()
  179. if status['wpa_state'] != 'COMPLETED':
  180. raise Exception("Not fully connected")
  181. if status['bssid'] != apdev[0]['bssid']:
  182. raise Exception("Unexpected BSSID")
  183. if status['ssid'] != ssid:
  184. raise Exception("Unexpected SSID")
  185. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  186. raise Exception("Unexpected encryption configuration")
  187. if status['key_mgmt'] != 'WPA2-PSK':
  188. raise Exception("Unexpected key_mgmt")
  189. sta = hapd.get_sta(dev[0].p2p_interface_addr())
  190. if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
  191. raise Exception("Device name not available in STA command")
  192. def test_ap_wps_conf_5ghz(dev, apdev):
  193. """WPS PBC provisioning with configured AP on 5 GHz band"""
  194. try:
  195. hapd = None
  196. ssid = "test-wps-conf"
  197. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  198. "wpa_passphrase": "12345678", "wpa": "2",
  199. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  200. "country_code": "FI", "hw_mode": "a", "channel": "36" }
  201. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  202. logger.info("WPS provisioning step")
  203. hapd.request("WPS_PBC")
  204. dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
  205. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  206. dev[0].wait_connected(timeout=30)
  207. sta = hapd.get_sta(dev[0].p2p_interface_addr())
  208. if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
  209. raise Exception("Device name not available in STA command")
  210. finally:
  211. dev[0].request("DISCONNECT")
  212. if hapd:
  213. hapd.request("DISABLE")
  214. subprocess.call(['iw', 'reg', 'set', '00'])
  215. dev[0].flush_scan_cache()
  216. def test_ap_wps_conf_chan14(dev, apdev):
  217. """WPS PBC provisioning with configured AP on channel 14"""
  218. try:
  219. hapd = None
  220. ssid = "test-wps-conf"
  221. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  222. "wpa_passphrase": "12345678", "wpa": "2",
  223. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  224. "country_code": "JP", "hw_mode": "b", "channel": "14" }
  225. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  226. logger.info("WPS provisioning step")
  227. hapd.request("WPS_PBC")
  228. dev[0].request("WPS_PBC")
  229. dev[0].wait_connected(timeout=30)
  230. sta = hapd.get_sta(dev[0].p2p_interface_addr())
  231. if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
  232. raise Exception("Device name not available in STA command")
  233. finally:
  234. dev[0].request("DISCONNECT")
  235. if hapd:
  236. hapd.request("DISABLE")
  237. subprocess.call(['iw', 'reg', 'set', '00'])
  238. dev[0].flush_scan_cache()
  239. def test_ap_wps_twice(dev, apdev):
  240. """WPS provisioning with twice to change passphrase"""
  241. ssid = "test-wps-twice"
  242. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  243. "wpa_passphrase": "12345678", "wpa": "2",
  244. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
  245. hostapd.add_ap(apdev[0]['ifname'], params)
  246. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  247. logger.info("WPS provisioning step")
  248. hapd.request("WPS_PBC")
  249. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  250. dev[0].dump_monitor()
  251. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  252. dev[0].wait_connected(timeout=30)
  253. dev[0].request("DISCONNECT")
  254. logger.info("Restart AP with different passphrase and re-run WPS")
  255. hapd_global = hostapd.HostapdGlobal()
  256. hapd_global.remove(apdev[0]['ifname'])
  257. params['wpa_passphrase'] = 'another passphrase'
  258. hostapd.add_ap(apdev[0]['ifname'], params)
  259. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  260. logger.info("WPS provisioning step")
  261. hapd.request("WPS_PBC")
  262. dev[0].dump_monitor()
  263. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  264. dev[0].wait_connected(timeout=30)
  265. networks = dev[0].list_networks()
  266. if len(networks) > 1:
  267. raise Exception("Unexpected duplicated network block present")
  268. def test_ap_wps_incorrect_pin(dev, apdev):
  269. """WPS PIN provisioning with incorrect PIN"""
  270. ssid = "test-wps-incorrect-pin"
  271. hostapd.add_ap(apdev[0]['ifname'],
  272. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  273. "wpa_passphrase": "12345678", "wpa": "2",
  274. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  275. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  276. logger.info("WPS provisioning attempt 1")
  277. hapd.request("WPS_PIN any 12345670")
  278. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  279. dev[0].dump_monitor()
  280. dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
  281. ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
  282. if ev is None:
  283. raise Exception("WPS operation timed out")
  284. if "config_error=18" not in ev:
  285. raise Exception("Incorrect config_error reported")
  286. if "msg=8" not in ev:
  287. raise Exception("PIN error detected on incorrect message")
  288. dev[0].wait_disconnected(timeout=10)
  289. dev[0].request("WPS_CANCEL")
  290. # if a scan was in progress, wait for it to complete before trying WPS again
  291. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
  292. status = hapd.request("WPS_GET_STATUS")
  293. if "Last WPS result: Failed" not in status:
  294. raise Exception("WPS failure result not shown correctly")
  295. logger.info("WPS provisioning attempt 2")
  296. hapd.request("WPS_PIN any 12345670")
  297. dev[0].dump_monitor()
  298. dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
  299. ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
  300. if ev is None:
  301. raise Exception("WPS operation timed out")
  302. if "config_error=18" not in ev:
  303. raise Exception("Incorrect config_error reported")
  304. if "msg=10" not in ev:
  305. raise Exception("PIN error detected on incorrect message")
  306. dev[0].wait_disconnected(timeout=10)
  307. def test_ap_wps_conf_pin(dev, apdev):
  308. """WPS PIN provisioning with configured AP"""
  309. ssid = "test-wps-conf-pin"
  310. hostapd.add_ap(apdev[0]['ifname'],
  311. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  312. "wpa_passphrase": "12345678", "wpa": "2",
  313. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  314. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  315. logger.info("WPS provisioning step")
  316. pin = dev[0].wps_read_pin()
  317. hapd.request("WPS_PIN any " + pin)
  318. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  319. dev[0].dump_monitor()
  320. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  321. dev[0].wait_connected(timeout=30)
  322. status = dev[0].get_status()
  323. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  324. raise Exception("Not fully connected")
  325. if status['ssid'] != ssid:
  326. raise Exception("Unexpected SSID")
  327. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  328. raise Exception("Unexpected encryption configuration")
  329. if status['key_mgmt'] != 'WPA2-PSK':
  330. raise Exception("Unexpected key_mgmt")
  331. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
  332. bss = dev[1].get_bss(apdev[0]['bssid'])
  333. if "[WPS-AUTH]" in bss['flags']:
  334. raise Exception("WPS-AUTH flag not cleared")
  335. logger.info("Try to connect from another station using the same PIN")
  336. pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
  337. ev = dev[1].wait_event(["WPS-M2D","CTRL-EVENT-CONNECTED"], timeout=30)
  338. if ev is None:
  339. raise Exception("Operation timed out")
  340. if "WPS-M2D" not in ev:
  341. raise Exception("Unexpected WPS operation started")
  342. hapd.request("WPS_PIN any " + pin)
  343. dev[1].wait_connected(timeout=30)
  344. def test_ap_wps_conf_pin_v1(dev, apdev):
  345. """WPS PIN provisioning with configured WPS v1.0 AP"""
  346. ssid = "test-wps-conf-pin-v1"
  347. hostapd.add_ap(apdev[0]['ifname'],
  348. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  349. "wpa_passphrase": "12345678", "wpa": "2",
  350. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  351. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  352. logger.info("WPS provisioning step")
  353. pin = dev[0].wps_read_pin()
  354. hapd.request("SET wps_version_number 0x10")
  355. hapd.request("WPS_PIN any " + pin)
  356. found = False
  357. for i in range(0, 10):
  358. dev[0].scan(freq="2412")
  359. if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
  360. found = True
  361. break
  362. if not found:
  363. hapd.request("SET wps_version_number 0x20")
  364. raise Exception("WPS-PIN flag not seen in scan results")
  365. dev[0].dump_monitor()
  366. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  367. dev[0].wait_connected(timeout=30)
  368. hapd.request("SET wps_version_number 0x20")
  369. def test_ap_wps_conf_pin_2sta(dev, apdev):
  370. """Two stations trying to use WPS PIN at the same time"""
  371. ssid = "test-wps-conf-pin2"
  372. hostapd.add_ap(apdev[0]['ifname'],
  373. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  374. "wpa_passphrase": "12345678", "wpa": "2",
  375. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  376. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  377. logger.info("WPS provisioning step")
  378. pin = "12345670"
  379. pin2 = "55554444"
  380. hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
  381. hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
  382. dev[0].dump_monitor()
  383. dev[1].dump_monitor()
  384. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  385. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
  386. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  387. dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  388. dev[0].wait_connected(timeout=30)
  389. dev[1].wait_connected(timeout=30)
  390. def test_ap_wps_conf_pin_timeout(dev, apdev):
  391. """WPS PIN provisioning with configured AP timing out PIN"""
  392. ssid = "test-wps-conf-pin"
  393. hostapd.add_ap(apdev[0]['ifname'],
  394. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  395. "wpa_passphrase": "12345678", "wpa": "2",
  396. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  397. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  398. addr = dev[0].p2p_interface_addr()
  399. pin = dev[0].wps_read_pin()
  400. if "FAIL" not in hapd.request("WPS_PIN "):
  401. raise Exception("Unexpected success on invalid WPS_PIN")
  402. hapd.request("WPS_PIN any " + pin + " 1")
  403. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  404. time.sleep(1.1)
  405. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  406. ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
  407. if ev is None:
  408. raise Exception("WPS-PIN-NEEDED event timed out")
  409. ev = dev[0].wait_event(["WPS-M2D"])
  410. if ev is None:
  411. raise Exception("M2D not reported")
  412. dev[0].request("WPS_CANCEL")
  413. hapd.request("WPS_PIN any " + pin + " 20 " + addr)
  414. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  415. dev[0].wait_connected(timeout=30)
  416. def test_ap_wps_reg_connect(dev, apdev):
  417. """WPS registrar using AP PIN to connect"""
  418. ssid = "test-wps-reg-ap-pin"
  419. appin = "12345670"
  420. hostapd.add_ap(apdev[0]['ifname'],
  421. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  422. "wpa_passphrase": "12345678", "wpa": "2",
  423. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  424. "ap_pin": appin})
  425. logger.info("WPS provisioning step")
  426. dev[0].dump_monitor()
  427. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  428. dev[0].wps_reg(apdev[0]['bssid'], appin)
  429. status = dev[0].get_status()
  430. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  431. raise Exception("Not fully connected")
  432. if status['ssid'] != ssid:
  433. raise Exception("Unexpected SSID")
  434. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  435. raise Exception("Unexpected encryption configuration")
  436. if status['key_mgmt'] != 'WPA2-PSK':
  437. raise Exception("Unexpected key_mgmt")
  438. def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
  439. """WPS registrar using AP PIN to connect (WPA+WPA2)"""
  440. ssid = "test-wps-reg-ap-pin"
  441. appin = "12345670"
  442. hostapd.add_ap(apdev[0]['ifname'],
  443. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  444. "wpa_passphrase": "12345678", "wpa": "3",
  445. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  446. "wpa_pairwise": "TKIP", "ap_pin": appin})
  447. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  448. dev[0].wps_reg(apdev[0]['bssid'], appin)
  449. status = dev[0].get_status()
  450. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  451. raise Exception("Not fully connected")
  452. if status['ssid'] != ssid:
  453. raise Exception("Unexpected SSID")
  454. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
  455. raise Exception("Unexpected encryption configuration")
  456. if status['key_mgmt'] != 'WPA2-PSK':
  457. raise Exception("Unexpected key_mgmt")
  458. def check_wps_reg_failure(dev, ap, appin):
  459. dev.request("WPS_REG " + ap['bssid'] + " " + appin)
  460. ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
  461. if ev is None:
  462. raise Exception("WPS operation timed out")
  463. if "WPS-SUCCESS" in ev:
  464. raise Exception("WPS operation succeeded unexpectedly")
  465. if "config_error=15" not in ev:
  466. raise Exception("WPS setup locked state was not reported correctly")
  467. def test_ap_wps_random_ap_pin(dev, apdev):
  468. """WPS registrar using random AP PIN"""
  469. ssid = "test-wps-reg-random-ap-pin"
  470. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  471. hostapd.add_ap(apdev[0]['ifname'],
  472. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  473. "wpa_passphrase": "12345678", "wpa": "2",
  474. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  475. "device_name": "Wireless AP", "manufacturer": "Company",
  476. "model_name": "WAP", "model_number": "123",
  477. "serial_number": "12345", "device_type": "6-0050F204-1",
  478. "os_version": "01020300",
  479. "config_methods": "label push_button",
  480. "uuid": ap_uuid, "upnp_iface": "lo" })
  481. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  482. appin = hapd.request("WPS_AP_PIN random")
  483. if "FAIL" in appin:
  484. raise Exception("Could not generate random AP PIN")
  485. if appin not in hapd.request("WPS_AP_PIN get"):
  486. raise Exception("Could not fetch current AP PIN")
  487. logger.info("WPS provisioning step")
  488. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  489. dev[0].wps_reg(apdev[0]['bssid'], appin)
  490. hapd.request("WPS_AP_PIN disable")
  491. logger.info("WPS provisioning step with AP PIN disabled")
  492. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  493. check_wps_reg_failure(dev[1], apdev[0], appin)
  494. logger.info("WPS provisioning step with AP PIN reset")
  495. appin = "12345670"
  496. hapd.request("WPS_AP_PIN set " + appin)
  497. dev[1].wps_reg(apdev[0]['bssid'], appin)
  498. dev[0].request("REMOVE_NETWORK all")
  499. dev[1].request("REMOVE_NETWORK all")
  500. dev[0].wait_disconnected(timeout=10)
  501. dev[1].wait_disconnected(timeout=10)
  502. logger.info("WPS provisioning step after AP PIN timeout")
  503. hapd.request("WPS_AP_PIN disable")
  504. appin = hapd.request("WPS_AP_PIN random 1")
  505. time.sleep(1.1)
  506. if "FAIL" not in hapd.request("WPS_AP_PIN get"):
  507. raise Exception("AP PIN unexpectedly still enabled")
  508. check_wps_reg_failure(dev[0], apdev[0], appin)
  509. logger.info("WPS provisioning step after AP PIN timeout(2)")
  510. hapd.request("WPS_AP_PIN disable")
  511. appin = "12345670"
  512. hapd.request("WPS_AP_PIN set " + appin + " 1")
  513. time.sleep(1.1)
  514. if "FAIL" not in hapd.request("WPS_AP_PIN get"):
  515. raise Exception("AP PIN unexpectedly still enabled")
  516. check_wps_reg_failure(dev[1], apdev[0], appin)
  517. def test_ap_wps_reg_config(dev, apdev):
  518. """WPS registrar configuring an AP using AP PIN"""
  519. ssid = "test-wps-init-ap-pin"
  520. appin = "12345670"
  521. hostapd.add_ap(apdev[0]['ifname'],
  522. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  523. "ap_pin": appin})
  524. logger.info("WPS configuration step")
  525. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  526. dev[0].dump_monitor()
  527. new_ssid = "wps-new-ssid"
  528. new_passphrase = "1234567890"
  529. dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
  530. new_passphrase)
  531. status = dev[0].get_status()
  532. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  533. raise Exception("Not fully connected")
  534. if status['ssid'] != new_ssid:
  535. raise Exception("Unexpected SSID")
  536. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  537. raise Exception("Unexpected encryption configuration")
  538. if status['key_mgmt'] != 'WPA2-PSK':
  539. raise Exception("Unexpected key_mgmt")
  540. logger.info("Re-configure back to open")
  541. dev[0].request("REMOVE_NETWORK all")
  542. dev[0].flush_scan_cache()
  543. dev[0].dump_monitor()
  544. dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
  545. status = dev[0].get_status()
  546. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  547. raise Exception("Not fully connected")
  548. if status['ssid'] != "wps-open":
  549. raise Exception("Unexpected SSID")
  550. if status['key_mgmt'] != 'NONE':
  551. raise Exception("Unexpected key_mgmt")
  552. def test_ap_wps_reg_config_ext_processing(dev, apdev):
  553. """WPS registrar configuring an AP with external config processing"""
  554. ssid = "test-wps-init-ap-pin"
  555. appin = "12345670"
  556. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  557. "wps_cred_processing": "1", "ap_pin": appin}
  558. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  559. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  560. new_ssid = "wps-new-ssid"
  561. new_passphrase = "1234567890"
  562. dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
  563. new_passphrase, no_wait=True)
  564. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  565. if ev is None:
  566. raise Exception("WPS registrar operation timed out")
  567. ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
  568. if ev is None:
  569. raise Exception("WPS configuration timed out")
  570. if "1026" not in ev:
  571. raise Exception("AP Settings missing from event")
  572. hapd.request("SET wps_cred_processing 0")
  573. if "FAIL" in hapd.request("WPS_CONFIG " + new_ssid.encode("hex") + " WPA2PSK CCMP " + new_passphrase.encode("hex")):
  574. raise Exception("WPS_CONFIG command failed")
  575. dev[0].wait_connected(timeout=15)
  576. def test_ap_wps_reg_config_tkip(dev, apdev):
  577. """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
  578. skip_with_fips(dev[0])
  579. ssid = "test-wps-init-ap"
  580. appin = "12345670"
  581. hostapd.add_ap(apdev[0]['ifname'],
  582. { "ssid": ssid, "eap_server": "1", "wps_state": "1",
  583. "ap_pin": appin})
  584. logger.info("WPS configuration step")
  585. dev[0].request("SET wps_version_number 0x10")
  586. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  587. dev[0].dump_monitor()
  588. new_ssid = "wps-new-ssid-with-tkip"
  589. new_passphrase = "1234567890"
  590. dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
  591. new_passphrase)
  592. logger.info("Re-connect to verify WPA2 mixed mode")
  593. dev[0].request("DISCONNECT")
  594. id = 0
  595. dev[0].set_network(id, "pairwise", "CCMP")
  596. dev[0].set_network(id, "proto", "RSN")
  597. dev[0].connect_network(id)
  598. status = dev[0].get_status()
  599. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  600. raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
  601. if status['ssid'] != new_ssid:
  602. raise Exception("Unexpected SSID")
  603. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
  604. raise Exception("Unexpected encryption configuration")
  605. if status['key_mgmt'] != 'WPA2-PSK':
  606. raise Exception("Unexpected key_mgmt")
  607. def test_ap_wps_setup_locked(dev, apdev):
  608. """WPS registrar locking up AP setup on AP PIN failures"""
  609. ssid = "test-wps-incorrect-ap-pin"
  610. appin = "12345670"
  611. hostapd.add_ap(apdev[0]['ifname'],
  612. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  613. "wpa_passphrase": "12345678", "wpa": "2",
  614. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  615. "ap_pin": appin})
  616. new_ssid = "wps-new-ssid-test"
  617. new_passphrase = "1234567890"
  618. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  619. ap_setup_locked=False
  620. for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
  621. dev[0].dump_monitor()
  622. logger.info("Try incorrect AP PIN - attempt " + pin)
  623. dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
  624. "CCMP", new_passphrase, no_wait=True)
  625. ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
  626. if ev is None:
  627. raise Exception("Timeout on receiving WPS operation failure event")
  628. if "CTRL-EVENT-CONNECTED" in ev:
  629. raise Exception("Unexpected connection")
  630. if "config_error=15" in ev:
  631. logger.info("AP Setup Locked")
  632. ap_setup_locked=True
  633. elif "config_error=18" not in ev:
  634. raise Exception("config_error=18 not reported")
  635. dev[0].wait_disconnected(timeout=10)
  636. time.sleep(0.1)
  637. if not ap_setup_locked:
  638. raise Exception("AP setup was not locked")
  639. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  640. status = hapd.request("WPS_GET_STATUS")
  641. if "Last WPS result: Failed" not in status:
  642. raise Exception("WPS failure result not shown correctly")
  643. if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
  644. raise Exception("Peer address not shown correctly")
  645. time.sleep(0.5)
  646. dev[0].dump_monitor()
  647. logger.info("WPS provisioning step")
  648. pin = dev[0].wps_read_pin()
  649. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  650. hapd.request("WPS_PIN any " + pin)
  651. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  652. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
  653. if ev is None:
  654. raise Exception("WPS success was not reported")
  655. dev[0].wait_connected(timeout=30)
  656. appin = hapd.request("WPS_AP_PIN random")
  657. if "FAIL" in appin:
  658. raise Exception("Could not generate random AP PIN")
  659. ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
  660. if ev is None:
  661. raise Exception("Failed to unlock AP PIN")
  662. def test_ap_wps_setup_locked_timeout(dev, apdev):
  663. """WPS re-enabling AP PIN after timeout"""
  664. ssid = "test-wps-incorrect-ap-pin"
  665. appin = "12345670"
  666. hostapd.add_ap(apdev[0]['ifname'],
  667. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  668. "wpa_passphrase": "12345678", "wpa": "2",
  669. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  670. "ap_pin": appin})
  671. new_ssid = "wps-new-ssid-test"
  672. new_passphrase = "1234567890"
  673. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  674. ap_setup_locked=False
  675. for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
  676. dev[0].dump_monitor()
  677. logger.info("Try incorrect AP PIN - attempt " + pin)
  678. dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
  679. "CCMP", new_passphrase, no_wait=True)
  680. ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
  681. if ev is None:
  682. raise Exception("Timeout on receiving WPS operation failure event")
  683. if "CTRL-EVENT-CONNECTED" in ev:
  684. raise Exception("Unexpected connection")
  685. if "config_error=15" in ev:
  686. logger.info("AP Setup Locked")
  687. ap_setup_locked=True
  688. break
  689. elif "config_error=18" not in ev:
  690. raise Exception("config_error=18 not reported")
  691. dev[0].wait_disconnected(timeout=10)
  692. time.sleep(0.1)
  693. if not ap_setup_locked:
  694. raise Exception("AP setup was not locked")
  695. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  696. ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
  697. if ev is None:
  698. raise Exception("AP PIN did not get unlocked on 60 second timeout")
  699. def test_ap_wps_pbc_overlap_2ap(dev, apdev):
  700. """WPS PBC session overlap with two active APs"""
  701. hostapd.add_ap(apdev[0]['ifname'],
  702. { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
  703. "wpa_passphrase": "12345678", "wpa": "2",
  704. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  705. "wps_independent": "1"})
  706. hostapd.add_ap(apdev[1]['ifname'],
  707. { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
  708. "wpa_passphrase": "123456789", "wpa": "2",
  709. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  710. "wps_independent": "1"})
  711. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  712. hapd.request("WPS_PBC")
  713. hapd2 = hostapd.Hostapd(apdev[1]['ifname'])
  714. hapd2.request("WPS_PBC")
  715. logger.info("WPS provisioning step")
  716. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
  717. dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
  718. dev[0].request("WPS_PBC")
  719. ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
  720. if ev is None:
  721. raise Exception("PBC session overlap not detected")
  722. hapd.request("DISABLE")
  723. hapd2.request("DISABLE")
  724. dev[0].flush_scan_cache()
  725. def test_ap_wps_pbc_overlap_2sta(dev, apdev):
  726. """WPS PBC session overlap with two active STAs"""
  727. ssid = "test-wps-pbc-overlap"
  728. hostapd.add_ap(apdev[0]['ifname'],
  729. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  730. "wpa_passphrase": "12345678", "wpa": "2",
  731. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  732. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  733. logger.info("WPS provisioning step")
  734. hapd.request("WPS_PBC")
  735. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  736. dev[0].dump_monitor()
  737. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
  738. dev[1].dump_monitor()
  739. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  740. dev[1].request("WPS_PBC " + apdev[0]['bssid'])
  741. ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
  742. if ev is None:
  743. raise Exception("PBC session overlap not detected (dev0)")
  744. if "config_error=12" not in ev:
  745. raise Exception("PBC session overlap not correctly reported (dev0)")
  746. dev[0].request("WPS_CANCEL")
  747. dev[0].request("DISCONNECT")
  748. ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
  749. if ev is None:
  750. raise Exception("PBC session overlap not detected (dev1)")
  751. if "config_error=12" not in ev:
  752. raise Exception("PBC session overlap not correctly reported (dev1)")
  753. dev[1].request("WPS_CANCEL")
  754. dev[1].request("DISCONNECT")
  755. hapd.request("WPS_CANCEL")
  756. ret = hapd.request("WPS_PBC")
  757. if "FAIL" not in ret:
  758. raise Exception("PBC mode allowed to be started while PBC overlap still active")
  759. hapd.request("DISABLE")
  760. dev[0].flush_scan_cache()
  761. dev[1].flush_scan_cache()
  762. def test_ap_wps_cancel(dev, apdev):
  763. """WPS AP cancelling enabled config method"""
  764. ssid = "test-wps-ap-cancel"
  765. hostapd.add_ap(apdev[0]['ifname'],
  766. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  767. "wpa_passphrase": "12345678", "wpa": "2",
  768. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
  769. bssid = apdev[0]['bssid']
  770. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  771. logger.info("Verify PBC enable/cancel")
  772. hapd.request("WPS_PBC")
  773. dev[0].scan(freq="2412")
  774. dev[0].scan(freq="2412")
  775. bss = dev[0].get_bss(apdev[0]['bssid'])
  776. if "[WPS-PBC]" not in bss['flags']:
  777. raise Exception("WPS-PBC flag missing")
  778. if "FAIL" in hapd.request("WPS_CANCEL"):
  779. raise Exception("WPS_CANCEL failed")
  780. dev[0].scan(freq="2412")
  781. dev[0].scan(freq="2412")
  782. bss = dev[0].get_bss(apdev[0]['bssid'])
  783. if "[WPS-PBC]" in bss['flags']:
  784. raise Exception("WPS-PBC flag not cleared")
  785. logger.info("Verify PIN enable/cancel")
  786. hapd.request("WPS_PIN any 12345670")
  787. dev[0].scan(freq="2412")
  788. dev[0].scan(freq="2412")
  789. bss = dev[0].get_bss(apdev[0]['bssid'])
  790. if "[WPS-AUTH]" not in bss['flags']:
  791. raise Exception("WPS-AUTH flag missing")
  792. if "FAIL" in hapd.request("WPS_CANCEL"):
  793. raise Exception("WPS_CANCEL failed")
  794. dev[0].scan(freq="2412")
  795. dev[0].scan(freq="2412")
  796. bss = dev[0].get_bss(apdev[0]['bssid'])
  797. if "[WPS-AUTH]" in bss['flags']:
  798. raise Exception("WPS-AUTH flag not cleared")
  799. def test_ap_wps_er_add_enrollee(dev, apdev):
  800. """WPS ER configuring AP and adding a new enrollee using PIN"""
  801. try:
  802. _test_ap_wps_er_add_enrollee(dev, apdev)
  803. finally:
  804. dev[0].request("WPS_ER_STOP")
  805. def _test_ap_wps_er_add_enrollee(dev, apdev):
  806. ssid = "wps-er-add-enrollee"
  807. ap_pin = "12345670"
  808. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  809. hostapd.add_ap(apdev[0]['ifname'],
  810. { "ssid": ssid, "eap_server": "1", "wps_state": "1",
  811. "device_name": "Wireless AP", "manufacturer": "Company",
  812. "model_name": "WAP", "model_number": "123",
  813. "serial_number": "12345", "device_type": "6-0050F204-1",
  814. "os_version": "01020300",
  815. "config_methods": "label push_button",
  816. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  817. logger.info("WPS configuration step")
  818. new_passphrase = "1234567890"
  819. dev[0].dump_monitor()
  820. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  821. dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
  822. new_passphrase)
  823. status = dev[0].get_status()
  824. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  825. raise Exception("Not fully connected")
  826. if status['ssid'] != ssid:
  827. raise Exception("Unexpected SSID")
  828. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  829. raise Exception("Unexpected encryption configuration")
  830. if status['key_mgmt'] != 'WPA2-PSK':
  831. raise Exception("Unexpected key_mgmt")
  832. logger.info("Start ER")
  833. dev[0].request("WPS_ER_START ifname=lo")
  834. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  835. if ev is None:
  836. raise Exception("AP discovery timed out")
  837. if ap_uuid not in ev:
  838. raise Exception("Expected AP UUID not found")
  839. logger.info("Learn AP configuration through UPnP")
  840. dev[0].dump_monitor()
  841. dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
  842. ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
  843. if ev is None:
  844. raise Exception("AP learn timed out")
  845. if ap_uuid not in ev:
  846. raise Exception("Expected AP UUID not in settings")
  847. if "ssid=" + ssid not in ev:
  848. raise Exception("Expected SSID not in settings")
  849. if "key=" + new_passphrase not in ev:
  850. raise Exception("Expected passphrase not in settings")
  851. ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
  852. if ev is None:
  853. raise Exception("WPS-FAIL after AP learn timed out")
  854. time.sleep(0.1)
  855. logger.info("Add Enrollee using ER")
  856. pin = dev[1].wps_read_pin()
  857. dev[0].dump_monitor()
  858. dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
  859. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  860. dev[1].dump_monitor()
  861. dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  862. ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
  863. if ev is None:
  864. raise Exception("Enrollee did not report success")
  865. dev[1].wait_connected(timeout=15)
  866. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  867. if ev is None:
  868. raise Exception("WPS ER did not report success")
  869. hwsim_utils.test_connectivity_sta(dev[0], dev[1])
  870. logger.info("Add a specific Enrollee using ER")
  871. pin = dev[2].wps_read_pin()
  872. addr2 = dev[2].p2p_interface_addr()
  873. dev[0].dump_monitor()
  874. dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
  875. dev[2].dump_monitor()
  876. dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  877. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
  878. if ev is None:
  879. raise Exception("Enrollee not seen")
  880. if addr2 not in ev:
  881. raise Exception("Unexpected Enrollee MAC address")
  882. dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
  883. dev[2].wait_connected(timeout=30)
  884. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  885. if ev is None:
  886. raise Exception("WPS ER did not report success")
  887. logger.info("Verify registrar selection behavior")
  888. dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
  889. dev[1].request("DISCONNECT")
  890. dev[1].wait_disconnected(timeout=10)
  891. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
  892. dev[1].scan(freq="2412")
  893. bss = dev[1].get_bss(apdev[0]['bssid'])
  894. if "[WPS-AUTH]" not in bss['flags']:
  895. # It is possible for scan to miss an update especially when running
  896. # tests under load with multiple VMs, so allow another attempt.
  897. dev[1].scan(freq="2412")
  898. bss = dev[1].get_bss(apdev[0]['bssid'])
  899. if "[WPS-AUTH]" not in bss['flags']:
  900. raise Exception("WPS-AUTH flag missing")
  901. logger.info("Stop ER")
  902. dev[0].dump_monitor()
  903. dev[0].request("WPS_ER_STOP")
  904. ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
  905. if ev is None:
  906. raise Exception("WPS ER unsubscription timed out")
  907. # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
  908. # a bit before verifying that the scan results have changed.
  909. time.sleep(0.2)
  910. for i in range(0, 10):
  911. dev[1].request("BSS_FLUSH 0")
  912. dev[1].scan(freq="2412", only_new=True)
  913. bss = dev[1].get_bss(apdev[0]['bssid'])
  914. if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
  915. break
  916. logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
  917. time.sleep(0.1)
  918. if "[WPS-AUTH]" in bss['flags']:
  919. raise Exception("WPS-AUTH flag not removed")
  920. def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
  921. """WPS ER adding a new enrollee identified by UUID"""
  922. try:
  923. _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
  924. finally:
  925. dev[0].request("WPS_ER_STOP")
  926. def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
  927. ssid = "wps-er-add-enrollee"
  928. ap_pin = "12345670"
  929. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  930. hostapd.add_ap(apdev[0]['ifname'],
  931. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  932. "wpa_passphrase": "12345678", "wpa": "2",
  933. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  934. "device_name": "Wireless AP", "manufacturer": "Company",
  935. "model_name": "WAP", "model_number": "123",
  936. "serial_number": "12345", "device_type": "6-0050F204-1",
  937. "os_version": "01020300",
  938. "config_methods": "label push_button",
  939. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  940. logger.info("WPS configuration step")
  941. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  942. dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
  943. logger.info("Start ER")
  944. dev[0].request("WPS_ER_START ifname=lo")
  945. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  946. if ev is None:
  947. raise Exception("AP discovery timed out")
  948. if ap_uuid not in ev:
  949. raise Exception("Expected AP UUID not found")
  950. logger.info("Learn AP configuration through UPnP")
  951. dev[0].dump_monitor()
  952. dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
  953. ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
  954. if ev is None:
  955. raise Exception("AP learn timed out")
  956. if ap_uuid not in ev:
  957. raise Exception("Expected AP UUID not in settings")
  958. ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
  959. if ev is None:
  960. raise Exception("WPS-FAIL after AP learn timed out")
  961. time.sleep(0.1)
  962. logger.info("Add a specific Enrollee using ER (PBC/UUID)")
  963. addr1 = dev[1].p2p_interface_addr()
  964. dev[0].dump_monitor()
  965. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  966. dev[1].dump_monitor()
  967. dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
  968. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
  969. if ev is None:
  970. raise Exception("Enrollee not seen")
  971. if addr1 not in ev:
  972. raise Exception("Unexpected Enrollee MAC address")
  973. uuid = ev.split(' ')[1]
  974. dev[0].request("WPS_ER_PBC " + uuid)
  975. dev[1].wait_connected(timeout=30)
  976. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  977. if ev is None:
  978. raise Exception("WPS ER did not report success")
  979. logger.info("Add a specific Enrollee using ER (PIN/UUID)")
  980. pin = dev[2].wps_read_pin()
  981. addr2 = dev[2].p2p_interface_addr()
  982. dev[0].dump_monitor()
  983. dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
  984. dev[2].dump_monitor()
  985. dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  986. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
  987. if ev is None:
  988. raise Exception("Enrollee not seen")
  989. if addr2 not in ev:
  990. raise Exception("Unexpected Enrollee MAC address")
  991. uuid = ev.split(' ')[1]
  992. dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
  993. dev[2].wait_connected(timeout=30)
  994. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  995. if ev is None:
  996. raise Exception("WPS ER did not report success")
  997. logger.info("Stop ER")
  998. dev[0].dump_monitor()
  999. dev[0].request("WPS_ER_STOP")
  1000. def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
  1001. """WPS ER connected to AP and adding a new enrollee using PBC"""
  1002. try:
  1003. _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
  1004. finally:
  1005. dev[0].request("WPS_ER_STOP")
  1006. def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
  1007. ssid = "wps-er-add-enrollee-pbc"
  1008. ap_pin = "12345670"
  1009. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1010. hostapd.add_ap(apdev[0]['ifname'],
  1011. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1012. "wpa_passphrase": "12345678", "wpa": "2",
  1013. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1014. "device_name": "Wireless AP", "manufacturer": "Company",
  1015. "model_name": "WAP", "model_number": "123",
  1016. "serial_number": "12345", "device_type": "6-0050F204-1",
  1017. "os_version": "01020300",
  1018. "config_methods": "label push_button",
  1019. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  1020. logger.info("Learn AP configuration")
  1021. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1022. dev[0].dump_monitor()
  1023. dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
  1024. status = dev[0].get_status()
  1025. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  1026. raise Exception("Not fully connected")
  1027. logger.info("Start ER")
  1028. dev[0].request("WPS_ER_START ifname=lo")
  1029. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  1030. if ev is None:
  1031. raise Exception("AP discovery timed out")
  1032. if ap_uuid not in ev:
  1033. raise Exception("Expected AP UUID not found")
  1034. enrollee = dev[1].p2p_interface_addr()
  1035. if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
  1036. raise Exception("Unknown UUID not reported")
  1037. logger.info("Add Enrollee using ER and PBC")
  1038. dev[0].dump_monitor()
  1039. dev[1].dump_monitor()
  1040. dev[1].request("WPS_PBC")
  1041. for i in range(0, 2):
  1042. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
  1043. if ev is None:
  1044. raise Exception("Enrollee discovery timed out")
  1045. if enrollee in ev:
  1046. break
  1047. if i == 1:
  1048. raise Exception("Expected Enrollee not found")
  1049. if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
  1050. raise Exception("Unknown UUID not reported")
  1051. logger.info("Use learned network configuration on ER")
  1052. dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
  1053. if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
  1054. raise Exception("WPS_ER_PBC failed")
  1055. ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
  1056. if ev is None:
  1057. raise Exception("Enrollee did not report success")
  1058. dev[1].wait_connected(timeout=15)
  1059. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  1060. if ev is None:
  1061. raise Exception("WPS ER did not report success")
  1062. hwsim_utils.test_connectivity_sta(dev[0], dev[1])
  1063. def test_ap_wps_er_pbc_overlap(dev, apdev):
  1064. """WPS ER connected to AP and PBC session overlap"""
  1065. try:
  1066. _test_ap_wps_er_pbc_overlap(dev, apdev)
  1067. finally:
  1068. dev[0].request("WPS_ER_STOP")
  1069. def _test_ap_wps_er_pbc_overlap(dev, apdev):
  1070. ssid = "wps-er-add-enrollee-pbc"
  1071. ap_pin = "12345670"
  1072. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1073. hostapd.add_ap(apdev[0]['ifname'],
  1074. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1075. "wpa_passphrase": "12345678", "wpa": "2",
  1076. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1077. "device_name": "Wireless AP", "manufacturer": "Company",
  1078. "model_name": "WAP", "model_number": "123",
  1079. "serial_number": "12345", "device_type": "6-0050F204-1",
  1080. "os_version": "01020300",
  1081. "config_methods": "label push_button",
  1082. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  1083. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1084. dev[0].dump_monitor()
  1085. dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
  1086. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1087. dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1088. # avoid leaving dev 1 or 2 as the last Probe Request to the AP
  1089. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
  1090. dev[0].dump_monitor()
  1091. dev[0].request("WPS_ER_START ifname=lo")
  1092. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  1093. if ev is None:
  1094. raise Exception("AP discovery timed out")
  1095. if ap_uuid not in ev:
  1096. raise Exception("Expected AP UUID not found")
  1097. # verify BSSID selection of the AP instead of UUID
  1098. if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
  1099. raise Exception("Could not select AP based on BSSID")
  1100. dev[0].dump_monitor()
  1101. dev[1].request("WPS_PBC " + apdev[0]['bssid'])
  1102. dev[2].request("WPS_PBC " + apdev[0]['bssid'])
  1103. ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
  1104. if ev is None:
  1105. raise Exception("PBC scan failed")
  1106. ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
  1107. if ev is None:
  1108. raise Exception("PBC scan failed")
  1109. found1 = False
  1110. found2 = False
  1111. addr1 = dev[1].own_addr()
  1112. addr2 = dev[2].own_addr()
  1113. for i in range(3):
  1114. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
  1115. if ev is None:
  1116. raise Exception("Enrollee discovery timed out")
  1117. if addr1 in ev:
  1118. found1 = True
  1119. if found2:
  1120. break
  1121. if addr2 in ev:
  1122. found2 = True
  1123. if found1:
  1124. break
  1125. if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
  1126. raise Exception("PBC overlap not reported")
  1127. dev[1].request("WPS_CANCEL")
  1128. dev[2].request("WPS_CANCEL")
  1129. if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
  1130. raise Exception("Invalid WPS_ER_PBC accepted")
  1131. def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
  1132. """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
  1133. try:
  1134. _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
  1135. finally:
  1136. dev[0].request("WPS_ER_STOP")
  1137. def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
  1138. ssid = "wps-er-add-enrollee-pbc"
  1139. ap_pin = "12345670"
  1140. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1141. hostapd.add_ap(apdev[0]['ifname'],
  1142. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1143. "wpa_passphrase": "12345678", "wpa": "2",
  1144. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1145. "device_name": "Wireless AP", "manufacturer": "Company",
  1146. "model_name": "WAP", "model_number": "123",
  1147. "serial_number": "12345", "device_type": "6-0050F204-1",
  1148. "os_version": "01020300",
  1149. "config_methods": "label push_button",
  1150. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  1151. logger.info("Learn AP configuration")
  1152. dev[0].request("SET wps_version_number 0x10")
  1153. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1154. dev[0].dump_monitor()
  1155. dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
  1156. status = dev[0].get_status()
  1157. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  1158. raise Exception("Not fully connected")
  1159. logger.info("Start ER")
  1160. dev[0].request("WPS_ER_START ifname=lo")
  1161. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  1162. if ev is None:
  1163. raise Exception("AP discovery timed out")
  1164. if ap_uuid not in ev:
  1165. raise Exception("Expected AP UUID not found")
  1166. logger.info("Use learned network configuration on ER")
  1167. dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
  1168. logger.info("Add Enrollee using ER and PIN")
  1169. enrollee = dev[1].p2p_interface_addr()
  1170. pin = dev[1].wps_read_pin()
  1171. dev[0].dump_monitor()
  1172. dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
  1173. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1174. dev[1].dump_monitor()
  1175. dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  1176. dev[1].wait_connected(timeout=30)
  1177. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  1178. if ev is None:
  1179. raise Exception("WPS ER did not report success")
  1180. def test_ap_wps_er_config_ap(dev, apdev):
  1181. """WPS ER configuring AP over UPnP"""
  1182. try:
  1183. _test_ap_wps_er_config_ap(dev, apdev)
  1184. finally:
  1185. dev[0].request("WPS_ER_STOP")
  1186. def _test_ap_wps_er_config_ap(dev, apdev):
  1187. ssid = "wps-er-ap-config"
  1188. ap_pin = "12345670"
  1189. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1190. hostapd.add_ap(apdev[0]['ifname'],
  1191. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1192. "wpa_passphrase": "12345678", "wpa": "2",
  1193. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1194. "device_name": "Wireless AP", "manufacturer": "Company",
  1195. "model_name": "WAP", "model_number": "123",
  1196. "serial_number": "12345", "device_type": "6-0050F204-1",
  1197. "os_version": "01020300",
  1198. "config_methods": "label push_button",
  1199. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  1200. logger.info("Connect ER to the AP")
  1201. dev[0].connect(ssid, psk="12345678", scan_freq="2412")
  1202. logger.info("WPS configuration step")
  1203. dev[0].request("WPS_ER_START ifname=lo")
  1204. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  1205. if ev is None:
  1206. raise Exception("AP discovery timed out")
  1207. if ap_uuid not in ev:
  1208. raise Exception("Expected AP UUID not found")
  1209. new_passphrase = "1234567890"
  1210. dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
  1211. ssid.encode("hex") + " WPA2PSK CCMP " +
  1212. new_passphrase.encode("hex"))
  1213. ev = dev[0].wait_event(["WPS-SUCCESS"])
  1214. if ev is None:
  1215. raise Exception("WPS ER configuration operation timed out")
  1216. dev[0].wait_disconnected(timeout=10)
  1217. dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
  1218. logger.info("WPS ER restart")
  1219. dev[0].request("WPS_ER_START")
  1220. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  1221. if ev is None:
  1222. raise Exception("AP discovery timed out on ER restart")
  1223. if ap_uuid not in ev:
  1224. raise Exception("Expected AP UUID not found on ER restart")
  1225. if "OK" not in dev[0].request("WPS_ER_STOP"):
  1226. raise Exception("WPS_ER_STOP failed")
  1227. if "OK" not in dev[0].request("WPS_ER_STOP"):
  1228. raise Exception("WPS_ER_STOP failed")
  1229. def test_ap_wps_fragmentation(dev, apdev):
  1230. """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
  1231. ssid = "test-wps-fragmentation"
  1232. appin = "12345670"
  1233. hostapd.add_ap(apdev[0]['ifname'],
  1234. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1235. "wpa_passphrase": "12345678", "wpa": "3",
  1236. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1237. "wpa_pairwise": "TKIP", "ap_pin": appin,
  1238. "fragment_size": "50" })
  1239. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1240. logger.info("WPS provisioning step (PBC)")
  1241. hapd.request("WPS_PBC")
  1242. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1243. dev[0].dump_monitor()
  1244. dev[0].request("SET wps_fragment_size 50")
  1245. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1246. dev[0].wait_connected(timeout=30)
  1247. status = dev[0].get_status()
  1248. if status['wpa_state'] != 'COMPLETED':
  1249. raise Exception("Not fully connected")
  1250. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
  1251. raise Exception("Unexpected encryption configuration")
  1252. if status['key_mgmt'] != 'WPA2-PSK':
  1253. raise Exception("Unexpected key_mgmt")
  1254. logger.info("WPS provisioning step (PIN)")
  1255. pin = dev[1].wps_read_pin()
  1256. hapd.request("WPS_PIN any " + pin)
  1257. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1258. dev[1].request("SET wps_fragment_size 50")
  1259. dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  1260. dev[1].wait_connected(timeout=30)
  1261. status = dev[1].get_status()
  1262. if status['wpa_state'] != 'COMPLETED':
  1263. raise Exception("Not fully connected")
  1264. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
  1265. raise Exception("Unexpected encryption configuration")
  1266. if status['key_mgmt'] != 'WPA2-PSK':
  1267. raise Exception("Unexpected key_mgmt")
  1268. logger.info("WPS connection as registrar")
  1269. dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1270. dev[2].request("SET wps_fragment_size 50")
  1271. dev[2].wps_reg(apdev[0]['bssid'], appin)
  1272. status = dev[2].get_status()
  1273. if status['wpa_state'] != 'COMPLETED':
  1274. raise Exception("Not fully connected")
  1275. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
  1276. raise Exception("Unexpected encryption configuration")
  1277. if status['key_mgmt'] != 'WPA2-PSK':
  1278. raise Exception("Unexpected key_mgmt")
  1279. def test_ap_wps_new_version_sta(dev, apdev):
  1280. """WPS compatibility with new version number on the station"""
  1281. ssid = "test-wps-ver"
  1282. hostapd.add_ap(apdev[0]['ifname'],
  1283. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1284. "wpa_passphrase": "12345678", "wpa": "2",
  1285. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
  1286. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1287. logger.info("WPS provisioning step")
  1288. hapd.request("WPS_PBC")
  1289. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1290. dev[0].dump_monitor()
  1291. dev[0].request("SET wps_version_number 0x43")
  1292. dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
  1293. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1294. dev[0].wait_connected(timeout=30)
  1295. def test_ap_wps_new_version_ap(dev, apdev):
  1296. """WPS compatibility with new version number on the AP"""
  1297. ssid = "test-wps-ver"
  1298. hostapd.add_ap(apdev[0]['ifname'],
  1299. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1300. "wpa_passphrase": "12345678", "wpa": "2",
  1301. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
  1302. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1303. logger.info("WPS provisioning step")
  1304. if "FAIL" in hapd.request("SET wps_version_number 0x43"):
  1305. raise Exception("Failed to enable test functionality")
  1306. hapd.request("WPS_PBC")
  1307. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1308. dev[0].dump_monitor()
  1309. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1310. dev[0].wait_connected(timeout=30)
  1311. hapd.request("SET wps_version_number 0x20")
  1312. def test_ap_wps_check_pin(dev, apdev):
  1313. """Verify PIN checking through control interface"""
  1314. hostapd.add_ap(apdev[0]['ifname'],
  1315. { "ssid": "wps", "eap_server": "1", "wps_state": "2",
  1316. "wpa_passphrase": "12345678", "wpa": "2",
  1317. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
  1318. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1319. for t in [ ("12345670", "12345670"),
  1320. ("12345678", "FAIL-CHECKSUM"),
  1321. ("12345", "FAIL"),
  1322. ("123456789", "FAIL"),
  1323. ("1234-5670", "12345670"),
  1324. ("1234 5670", "12345670"),
  1325. ("1-2.3:4 5670", "12345670") ]:
  1326. res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
  1327. res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
  1328. if res != res2:
  1329. raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
  1330. if res != t[1]:
  1331. raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
  1332. if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
  1333. raise Exception("Unexpected WPS_CHECK_PIN success")
  1334. if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
  1335. raise Exception("Unexpected WPS_CHECK_PIN success")
  1336. for i in range(0, 10):
  1337. pin = dev[0].request("WPS_PIN get")
  1338. rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
  1339. if pin != rpin:
  1340. raise Exception("Random PIN validation failed for " + pin)
  1341. def test_ap_wps_wep_config(dev, apdev):
  1342. """WPS 2.0 AP rejecting WEP configuration"""
  1343. ssid = "test-wps-config"
  1344. appin = "12345670"
  1345. hostapd.add_ap(apdev[0]['ifname'],
  1346. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1347. "ap_pin": appin})
  1348. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1349. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1350. dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
  1351. "hello", no_wait=True)
  1352. ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
  1353. if ev is None:
  1354. raise Exception("WPS-FAIL timed out")
  1355. if "reason=2" not in ev:
  1356. raise Exception("Unexpected reason code in WPS-FAIL")
  1357. status = hapd.request("WPS_GET_STATUS")
  1358. if "Last WPS result: Failed" not in status:
  1359. raise Exception("WPS failure result not shown correctly")
  1360. if "Failure Reason: WEP Prohibited" not in status:
  1361. raise Exception("Failure reason not reported correctly")
  1362. if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
  1363. raise Exception("Peer address not shown correctly")
  1364. def test_ap_wps_wep_enroll(dev, apdev):
  1365. """WPS 2.0 STA rejecting WEP configuration"""
  1366. ssid = "test-wps-wep"
  1367. hostapd.add_ap(apdev[0]['ifname'],
  1368. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1369. "skip_cred_build": "1", "extra_cred": "wps-wep-cred" })
  1370. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1371. hapd.request("WPS_PBC")
  1372. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1373. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1374. ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
  1375. if ev is None:
  1376. raise Exception("WPS-FAIL event timed out")
  1377. if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
  1378. raise Exception("Unexpected WPS-FAIL event: " + ev)
  1379. def test_ap_wps_ie_fragmentation(dev, apdev):
  1380. """WPS AP using fragmented WPS IE"""
  1381. ssid = "test-wps-ie-fragmentation"
  1382. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1383. "wpa_passphrase": "12345678", "wpa": "2",
  1384. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1385. "device_name": "1234567890abcdef1234567890abcdef",
  1386. "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
  1387. "model_name": "1234567890abcdef1234567890abcdef",
  1388. "model_number": "1234567890abcdef1234567890abcdef",
  1389. "serial_number": "1234567890abcdef1234567890abcdef" }
  1390. hostapd.add_ap(apdev[0]['ifname'], params)
  1391. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1392. hapd.request("WPS_PBC")
  1393. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1394. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1395. dev[0].wait_connected(timeout=30)
  1396. bss = dev[0].get_bss(apdev[0]['bssid'])
  1397. if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
  1398. logger.info("Device Name not received correctly")
  1399. logger.info(bss)
  1400. # This can fail if Probe Response frame is missed and Beacon frame was
  1401. # used to fill in the BSS entry. This can happen, e.g., during heavy
  1402. # load every now and then and is not really an error, so try to
  1403. # workaround by runnign another scan.
  1404. dev[0].scan(freq="2412", only_new=True)
  1405. bss = dev[0].get_bss(apdev[0]['bssid'])
  1406. if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
  1407. logger.info(bss)
  1408. raise Exception("Device Name not received correctly")
  1409. if len(re.findall("dd..0050f204", bss['ie'])) != 2:
  1410. raise Exception("Unexpected number of WPS IEs")
  1411. def get_psk(pskfile):
  1412. psks = {}
  1413. with open(pskfile, "r") as f:
  1414. lines = f.read().splitlines()
  1415. for l in lines:
  1416. if l == "# WPA PSKs":
  1417. continue
  1418. (addr,psk) = l.split(' ')
  1419. psks[addr] = psk
  1420. return psks
  1421. def test_ap_wps_per_station_psk(dev, apdev):
  1422. """WPS PBC provisioning with per-station PSK"""
  1423. addr0 = dev[0].own_addr()
  1424. addr1 = dev[1].own_addr()
  1425. addr2 = dev[2].own_addr()
  1426. ssid = "wps"
  1427. appin = "12345670"
  1428. pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
  1429. try:
  1430. os.remove(pskfile)
  1431. except:
  1432. pass
  1433. try:
  1434. with open(pskfile, "w") as f:
  1435. f.write("# WPA PSKs\n")
  1436. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1437. "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
  1438. "rsn_pairwise": "CCMP", "ap_pin": appin,
  1439. "wpa_psk_file": pskfile }
  1440. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  1441. logger.info("First enrollee")
  1442. hapd.request("WPS_PBC")
  1443. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1444. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1445. dev[0].wait_connected(timeout=30)
  1446. logger.info("Second enrollee")
  1447. hapd.request("WPS_PBC")
  1448. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1449. dev[1].request("WPS_PBC " + apdev[0]['bssid'])
  1450. dev[1].wait_connected(timeout=30)
  1451. logger.info("External registrar")
  1452. dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1453. dev[2].wps_reg(apdev[0]['bssid'], appin)
  1454. logger.info("Verifying PSK results")
  1455. psks = get_psk(pskfile)
  1456. if addr0 not in psks:
  1457. raise Exception("No PSK recorded for sta0")
  1458. if addr1 not in psks:
  1459. raise Exception("No PSK recorded for sta1")
  1460. if addr2 not in psks:
  1461. raise Exception("No PSK recorded for sta2")
  1462. if psks[addr0] == psks[addr1]:
  1463. raise Exception("Same PSK recorded for sta0 and sta1")
  1464. if psks[addr0] == psks[addr2]:
  1465. raise Exception("Same PSK recorded for sta0 and sta2")
  1466. if psks[addr1] == psks[addr2]:
  1467. raise Exception("Same PSK recorded for sta1 and sta2")
  1468. dev[0].request("REMOVE_NETWORK all")
  1469. logger.info("Second external registrar")
  1470. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1471. dev[0].wps_reg(apdev[0]['bssid'], appin)
  1472. psks2 = get_psk(pskfile)
  1473. if addr0 not in psks2:
  1474. raise Exception("No PSK recorded for sta0(reg)")
  1475. if psks[addr0] == psks2[addr0]:
  1476. raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
  1477. finally:
  1478. os.remove(pskfile)
  1479. def test_ap_wps_per_station_psk_failure(dev, apdev):
  1480. """WPS PBC provisioning with per-station PSK (file not writable)"""
  1481. addr0 = dev[0].p2p_dev_addr()
  1482. addr1 = dev[1].p2p_dev_addr()
  1483. addr2 = dev[2].p2p_dev_addr()
  1484. ssid = "wps"
  1485. appin = "12345670"
  1486. pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
  1487. try:
  1488. os.remove(pskfile)
  1489. except:
  1490. pass
  1491. try:
  1492. with open(pskfile, "w") as f:
  1493. f.write("# WPA PSKs\n")
  1494. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1495. "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
  1496. "rsn_pairwise": "CCMP", "ap_pin": appin,
  1497. "wpa_psk_file": pskfile }
  1498. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  1499. if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
  1500. raise Exception("Failed to set wpa_psk_file")
  1501. logger.info("First enrollee")
  1502. hapd.request("WPS_PBC")
  1503. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1504. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1505. dev[0].wait_connected(timeout=30)
  1506. logger.info("Second enrollee")
  1507. hapd.request("WPS_PBC")
  1508. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1509. dev[1].request("WPS_PBC " + apdev[0]['bssid'])
  1510. dev[1].wait_connected(timeout=30)
  1511. logger.info("External registrar")
  1512. dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1513. dev[2].wps_reg(apdev[0]['bssid'], appin)
  1514. logger.info("Verifying PSK results")
  1515. psks = get_psk(pskfile)
  1516. if len(psks) > 0:
  1517. raise Exception("PSK recorded unexpectedly")
  1518. finally:
  1519. os.remove(pskfile)
  1520. def test_ap_wps_pin_request_file(dev, apdev):
  1521. """WPS PIN provisioning with configured AP"""
  1522. ssid = "wps"
  1523. pinfile = "/tmp/ap_wps_pin_request_file.log"
  1524. if os.path.exists(pinfile):
  1525. os.remove(pinfile)
  1526. hostapd.add_ap(apdev[0]['ifname'],
  1527. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1528. "wps_pin_requests": pinfile,
  1529. "wpa_passphrase": "12345678", "wpa": "2",
  1530. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  1531. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1532. uuid = dev[0].get_status_field("uuid")
  1533. pin = dev[0].wps_read_pin()
  1534. try:
  1535. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1536. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  1537. ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
  1538. if ev is None:
  1539. raise Exception("PIN needed event not shown")
  1540. if uuid not in ev:
  1541. raise Exception("UUID mismatch")
  1542. dev[0].request("WPS_CANCEL")
  1543. success = False
  1544. with open(pinfile, "r") as f:
  1545. lines = f.readlines()
  1546. for l in lines:
  1547. if uuid in l:
  1548. success = True
  1549. break
  1550. if not success:
  1551. raise Exception("PIN request entry not in the log file")
  1552. finally:
  1553. try:
  1554. os.remove(pinfile)
  1555. except:
  1556. pass
  1557. def test_ap_wps_auto_setup_with_config_file(dev, apdev):
  1558. """WPS auto-setup with configuration file"""
  1559. conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
  1560. ifname = apdev[0]['ifname']
  1561. try:
  1562. with open(conffile, "w") as f:
  1563. f.write("driver=nl80211\n")
  1564. f.write("hw_mode=g\n")
  1565. f.write("channel=1\n")
  1566. f.write("ieee80211n=1\n")
  1567. f.write("interface=%s\n" % ifname)
  1568. f.write("ctrl_interface=/var/run/hostapd\n")
  1569. f.write("ssid=wps\n")
  1570. f.write("eap_server=1\n")
  1571. f.write("wps_state=1\n")
  1572. hostapd.add_bss('phy3', ifname, conffile)
  1573. hapd = hostapd.Hostapd(ifname)
  1574. hapd.request("WPS_PBC")
  1575. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1576. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1577. dev[0].wait_connected(timeout=30)
  1578. with open(conffile, "r") as f:
  1579. lines = f.read().splitlines()
  1580. vals = dict()
  1581. for l in lines:
  1582. try:
  1583. [name,value] = l.split('=', 1)
  1584. vals[name] = value
  1585. except ValueError, e:
  1586. if "# WPS configuration" in l:
  1587. pass
  1588. else:
  1589. raise Exception("Unexpected configuration line: " + l)
  1590. if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
  1591. raise Exception("Incorrect configuration: " + str(vals))
  1592. finally:
  1593. try:
  1594. os.remove(conffile)
  1595. except:
  1596. pass
  1597. def test_ap_wps_pbc_timeout(dev, apdev, params):
  1598. """wpa_supplicant PBC walk time [long]"""
  1599. if not params['long']:
  1600. raise HwsimSkip("Skip test case with long duration due to --long not specified")
  1601. ssid = "test-wps"
  1602. hostapd.add_ap(apdev[0]['ifname'],
  1603. { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
  1604. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1605. logger.info("Start WPS_PBC and wait for PBC walk time expiration")
  1606. if "OK" not in dev[0].request("WPS_PBC"):
  1607. raise Exception("WPS_PBC failed")
  1608. ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=150)
  1609. if ev is None:
  1610. raise Exception("WPS-TIMEOUT not reported")
  1611. def add_ssdp_ap(ifname, ap_uuid):
  1612. ssid = "wps-ssdp"
  1613. ap_pin = "12345670"
  1614. hostapd.add_ap(ifname,
  1615. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1616. "wpa_passphrase": "12345678", "wpa": "2",
  1617. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1618. "device_name": "Wireless AP", "manufacturer": "Company",
  1619. "model_name": "WAP", "model_number": "123",
  1620. "serial_number": "12345", "device_type": "6-0050F204-1",
  1621. "os_version": "01020300",
  1622. "config_methods": "label push_button",
  1623. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
  1624. "friendly_name": "WPS Access Point",
  1625. "manufacturer_url": "http://www.example.com/",
  1626. "model_description": "Wireless Access Point",
  1627. "model_url": "http://www.example.com/model/",
  1628. "upc": "123456789012" })
  1629. def ssdp_send(msg, no_recv=False):
  1630. socket.setdefaulttimeout(1)
  1631. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  1632. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1633. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  1634. sock.bind(("127.0.0.1", 0))
  1635. sock.sendto(msg, ("239.255.255.250", 1900))
  1636. if no_recv:
  1637. return None
  1638. return sock.recv(1000)
  1639. def ssdp_send_msearch(st):
  1640. msg = '\r\n'.join([
  1641. 'M-SEARCH * HTTP/1.1',
  1642. 'HOST: 239.255.255.250:1900',
  1643. 'MX: 1',
  1644. 'MAN: "ssdp:discover"',
  1645. 'ST: ' + st,
  1646. '', ''])
  1647. return ssdp_send(msg)
  1648. def test_ap_wps_ssdp_msearch(dev, apdev):
  1649. """WPS AP and SSDP M-SEARCH messages"""
  1650. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1651. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  1652. msg = '\r\n'.join([
  1653. 'M-SEARCH * HTTP/1.1',
  1654. 'Host: 239.255.255.250:1900',
  1655. 'Mx: 1',
  1656. 'Man: "ssdp:discover"',
  1657. 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
  1658. '', ''])
  1659. ssdp_send(msg)
  1660. msg = '\r\n'.join([
  1661. 'M-SEARCH * HTTP/1.1',
  1662. 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
  1663. 'mx: \t1\t\t ',
  1664. 'man: \t \t "ssdp:discover" ',
  1665. 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
  1666. '', ''])
  1667. ssdp_send(msg)
  1668. ssdp_send_msearch("ssdp:all")
  1669. ssdp_send_msearch("upnp:rootdevice")
  1670. ssdp_send_msearch("uuid:" + ap_uuid)
  1671. ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
  1672. ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1");
  1673. msg = '\r\n'.join([
  1674. 'M-SEARCH * HTTP/1.1',
  1675. 'HOST:\t239.255.255.250:1900',
  1676. 'MAN: "ssdp:discover"',
  1677. 'MX: 130',
  1678. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1679. '', ''])
  1680. ssdp_send(msg, no_recv=True)
  1681. def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
  1682. """WPS AP and invalid SSDP M-SEARCH messages"""
  1683. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1684. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  1685. socket.setdefaulttimeout(1)
  1686. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  1687. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1688. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  1689. sock.bind(("127.0.0.1", 0))
  1690. logger.debug("Missing MX")
  1691. msg = '\r\n'.join([
  1692. 'M-SEARCH * HTTP/1.1',
  1693. 'HOST: 239.255.255.250:1900',
  1694. 'MAN: "ssdp:discover"',
  1695. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1696. '', ''])
  1697. sock.sendto(msg, ("239.255.255.250", 1900))
  1698. logger.debug("Negative MX")
  1699. msg = '\r\n'.join([
  1700. 'M-SEARCH * HTTP/1.1',
  1701. 'HOST: 239.255.255.250:1900',
  1702. 'MX: -1',
  1703. 'MAN: "ssdp:discover"',
  1704. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1705. '', ''])
  1706. sock.sendto(msg, ("239.255.255.250", 1900))
  1707. logger.debug("Invalid MX")
  1708. msg = '\r\n'.join([
  1709. 'M-SEARCH * HTTP/1.1',
  1710. 'HOST: 239.255.255.250:1900',
  1711. 'MX; 1',
  1712. 'MAN: "ssdp:discover"',
  1713. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1714. '', ''])
  1715. sock.sendto(msg, ("239.255.255.250", 1900))
  1716. logger.debug("Missing MAN")
  1717. msg = '\r\n'.join([
  1718. 'M-SEARCH * HTTP/1.1',
  1719. 'HOST: 239.255.255.250:1900',
  1720. 'MX: 1',
  1721. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1722. '', ''])
  1723. sock.sendto(msg, ("239.255.255.250", 1900))
  1724. logger.debug("Invalid MAN")
  1725. msg = '\r\n'.join([
  1726. 'M-SEARCH * HTTP/1.1',
  1727. 'HOST: 239.255.255.250:1900',
  1728. 'MX: 1',
  1729. 'MAN: foo',
  1730. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1731. '', ''])
  1732. sock.sendto(msg, ("239.255.255.250", 1900))
  1733. msg = '\r\n'.join([
  1734. 'M-SEARCH * HTTP/1.1',
  1735. 'HOST: 239.255.255.250:1900',
  1736. 'MX: 1',
  1737. 'MAN; "ssdp:discover"',
  1738. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1739. '', ''])
  1740. sock.sendto(msg, ("239.255.255.250", 1900))
  1741. logger.debug("Missing HOST")
  1742. msg = '\r\n'.join([
  1743. 'M-SEARCH * HTTP/1.1',
  1744. 'MAN: "ssdp:discover"',
  1745. 'MX: 1',
  1746. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1747. '', ''])
  1748. sock.sendto(msg, ("239.255.255.250", 1900))
  1749. logger.debug("Missing ST")
  1750. msg = '\r\n'.join([
  1751. 'M-SEARCH * HTTP/1.1',
  1752. 'HOST: 239.255.255.250:1900',
  1753. 'MAN: "ssdp:discover"',
  1754. 'MX: 1',
  1755. '', ''])
  1756. sock.sendto(msg, ("239.255.255.250", 1900))
  1757. logger.debug("Mismatching ST")
  1758. msg = '\r\n'.join([
  1759. 'M-SEARCH * HTTP/1.1',
  1760. 'HOST: 239.255.255.250:1900',
  1761. 'MAN: "ssdp:discover"',
  1762. 'MX: 1',
  1763. 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
  1764. '', ''])
  1765. sock.sendto(msg, ("239.255.255.250", 1900))
  1766. msg = '\r\n'.join([
  1767. 'M-SEARCH * HTTP/1.1',
  1768. 'HOST: 239.255.255.250:1900',
  1769. 'MAN: "ssdp:discover"',
  1770. 'MX: 1',
  1771. 'ST: foo:bar',
  1772. '', ''])
  1773. sock.sendto(msg, ("239.255.255.250", 1900))
  1774. msg = '\r\n'.join([
  1775. 'M-SEARCH * HTTP/1.1',
  1776. 'HOST: 239.255.255.250:1900',
  1777. 'MAN: "ssdp:discover"',
  1778. 'MX: 1',
  1779. 'ST: foobar',
  1780. '', ''])
  1781. sock.sendto(msg, ("239.255.255.250", 1900))
  1782. logger.debug("Invalid ST")
  1783. msg = '\r\n'.join([
  1784. 'M-SEARCH * HTTP/1.1',
  1785. 'HOST: 239.255.255.250:1900',
  1786. 'MAN: "ssdp:discover"',
  1787. 'MX: 1',
  1788. 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
  1789. '', ''])
  1790. sock.sendto(msg, ("239.255.255.250", 1900))
  1791. logger.debug("Invalid M-SEARCH")
  1792. msg = '\r\n'.join([
  1793. 'M+SEARCH * HTTP/1.1',
  1794. 'HOST: 239.255.255.250:1900',
  1795. 'MAN: "ssdp:discover"',
  1796. 'MX: 1',
  1797. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1798. '', ''])
  1799. sock.sendto(msg, ("239.255.255.250", 1900))
  1800. msg = '\r\n'.join([
  1801. 'M-SEARCH-* HTTP/1.1',
  1802. 'HOST: 239.255.255.250:1900',
  1803. 'MAN: "ssdp:discover"',
  1804. 'MX: 1',
  1805. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1806. '', ''])
  1807. sock.sendto(msg, ("239.255.255.250", 1900))
  1808. logger.debug("Invalid message format")
  1809. sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
  1810. msg = '\r'.join([
  1811. 'M-SEARCH * HTTP/1.1',
  1812. 'HOST: 239.255.255.250:1900',
  1813. 'MAN: "ssdp:discover"',
  1814. 'MX: 1',
  1815. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1816. '', ''])
  1817. sock.sendto(msg, ("239.255.255.250", 1900))
  1818. try:
  1819. r = sock.recv(1000)
  1820. raise Exception("Unexpected M-SEARCH response: " + r)
  1821. except socket.timeout:
  1822. pass
  1823. logger.debug("Valid M-SEARCH")
  1824. msg = '\r\n'.join([
  1825. 'M-SEARCH * HTTP/1.1',
  1826. 'HOST: 239.255.255.250:1900',
  1827. 'MAN: "ssdp:discover"',
  1828. 'MX: 1',
  1829. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1830. '', ''])
  1831. sock.sendto(msg, ("239.255.255.250", 1900))
  1832. try:
  1833. r = sock.recv(1000)
  1834. pass
  1835. except socket.timeout:
  1836. raise Exception("No SSDP response")
  1837. def test_ap_wps_ssdp_burst(dev, apdev):
  1838. """WPS AP and SSDP burst"""
  1839. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1840. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  1841. msg = '\r\n'.join([
  1842. 'M-SEARCH * HTTP/1.1',
  1843. 'HOST: 239.255.255.250:1900',
  1844. 'MAN: "ssdp:discover"',
  1845. 'MX: 1',
  1846. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1847. '', ''])
  1848. socket.setdefaulttimeout(1)
  1849. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  1850. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1851. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  1852. sock.bind(("127.0.0.1", 0))
  1853. for i in range(0, 25):
  1854. sock.sendto(msg, ("239.255.255.250", 1900))
  1855. resp = 0
  1856. while True:
  1857. try:
  1858. r = sock.recv(1000)
  1859. if not r.startswith("HTTP/1.1 200 OK\r\n"):
  1860. raise Exception("Unexpected message: " + r)
  1861. resp += 1
  1862. except socket.timeout:
  1863. break
  1864. if resp < 20:
  1865. raise Exception("Too few SSDP responses")
  1866. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  1867. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1868. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  1869. sock.bind(("127.0.0.1", 0))
  1870. for i in range(0, 25):
  1871. sock.sendto(msg, ("239.255.255.250", 1900))
  1872. while True:
  1873. try:
  1874. r = sock.recv(1000)
  1875. if ap_uuid in r:
  1876. break
  1877. except socket.timeout:
  1878. raise Exception("No SSDP response")
  1879. def ssdp_get_location(uuid):
  1880. res = ssdp_send_msearch("uuid:" + uuid)
  1881. location = None
  1882. for l in res.splitlines():
  1883. if l.lower().startswith("location:"):
  1884. location = l.split(':', 1)[1].strip()
  1885. break
  1886. if location is None:
  1887. raise Exception("No UPnP location found")
  1888. return location
  1889. def upnp_get_urls(location):
  1890. conn = urllib.urlopen(location)
  1891. tree = ET.parse(conn)
  1892. root = tree.getroot()
  1893. urn = '{urn:schemas-upnp-org:device-1-0}'
  1894. service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
  1895. res = {}
  1896. res['scpd_url'] = urlparse.urljoin(location, service.find(urn + 'SCPDURL').text)
  1897. res['control_url'] = urlparse.urljoin(location, service.find(urn + 'controlURL').text)
  1898. res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
  1899. return res
  1900. def upnp_soap_action(conn, path, action, include_soap_action=True, soap_action_override=None):
  1901. soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
  1902. wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
  1903. ET.register_namespace('soapenv', soapns)
  1904. ET.register_namespace('wfa', wpsns)
  1905. attrib = {}
  1906. attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
  1907. root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
  1908. body = ET.SubElement(root, "{%s}Body" % soapns)
  1909. act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
  1910. tree = ET.ElementTree(root)
  1911. soap = StringIO.StringIO()
  1912. tree.write(soap, xml_declaration=True, encoding='utf-8')
  1913. headers = { "Content-type": 'text/xml; charset="utf-8"' }
  1914. if include_soap_action:
  1915. headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
  1916. elif soap_action_override:
  1917. headers["SOAPAction"] = soap_action_override
  1918. conn.request("POST", path, soap.getvalue(), headers)
  1919. return conn.getresponse()
  1920. def test_ap_wps_upnp(dev, apdev):
  1921. """WPS AP and UPnP operations"""
  1922. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1923. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  1924. location = ssdp_get_location(ap_uuid)
  1925. urls = upnp_get_urls(location)
  1926. conn = urllib.urlopen(urls['scpd_url'])
  1927. scpd = conn.read()
  1928. conn = urllib.urlopen(urlparse.urljoin(location, "unknown.html"))
  1929. if conn.getcode() != 404:
  1930. raise Exception("Unexpected HTTP response to GET unknown URL")
  1931. url = urlparse.urlparse(location)
  1932. conn = httplib.HTTPConnection(url.netloc)
  1933. #conn.set_debuglevel(1)
  1934. headers = { "Content-type": 'text/xml; charset="utf-8"',
  1935. "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
  1936. conn.request("POST", "hello", "\r\n\r\n", headers)
  1937. resp = conn.getresponse()
  1938. if resp.status != 404:
  1939. raise Exception("Unexpected HTTP response: %d" % resp.status)
  1940. conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
  1941. resp = conn.getresponse()
  1942. if resp.status != 501:
  1943. raise Exception("Unexpected HTTP response: %d" % resp.status)
  1944. headers = { "Content-type": 'text/xml; charset="utf-8"',
  1945. "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
  1946. ctrlurl = urlparse.urlparse(urls['control_url'])
  1947. conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
  1948. resp = conn.getresponse()
  1949. if resp.status != 401:
  1950. raise Exception("Unexpected HTTP response: %d" % resp.status)
  1951. logger.debug("GetDeviceInfo without SOAPAction header")
  1952. resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
  1953. include_soap_action=False)
  1954. if resp.status != 401:
  1955. raise Exception("Unexpected HTTP response: %d" % resp.status)
  1956. logger.debug("GetDeviceInfo with invalid SOAPAction header")
  1957. for act in [ "foo",
  1958. "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
  1959. '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
  1960. '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
  1961. resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
  1962. include_soap_action=False,
  1963. soap_action_override=act)
  1964. if resp.status != 401:
  1965. raise Exception("Unexpected HTTP response: %d" % resp.status)
  1966. resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
  1967. if resp.status != 200:
  1968. raise Exception("Unexpected HTTP response: %d" % resp.status)
  1969. dev = resp.read()
  1970. if "NewDeviceInfo" not in dev:
  1971. raise Exception("Unexpected GetDeviceInfo response")
  1972. logger.debug("PutMessage without required parameters")
  1973. resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
  1974. if resp.status != 600:
  1975. raise Exception("Unexpected HTTP response: %d" % resp.status)
  1976. logger.debug("PutWLANResponse without required parameters")
  1977. resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
  1978. if resp.status != 600:
  1979. raise Exception("Unexpected HTTP response: %d" % resp.status)
  1980. logger.debug("SetSelectedRegistrar from unregistered ER")
  1981. resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
  1982. if resp.status != 501:
  1983. raise Exception("Unexpected HTTP response: %d" % resp.status)
  1984. logger.debug("Unknown action")
  1985. resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
  1986. if resp.status != 401:
  1987. raise Exception("Unexpected HTTP response: %d" % resp.status)
  1988. def test_ap_wps_upnp_subscribe(dev, apdev):
  1989. """WPS AP and UPnP event subscription"""
  1990. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1991. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  1992. location = ssdp_get_location(ap_uuid)
  1993. urls = upnp_get_urls(location)
  1994. eventurl = urlparse.urlparse(urls['event_sub_url'])
  1995. url = urlparse.urlparse(location)
  1996. conn = httplib.HTTPConnection(url.netloc)
  1997. #conn.set_debuglevel(1)
  1998. headers = { "callback": '<http://127.0.0.1:12345/event>',
  1999. "timeout": "Second-1234" }
  2000. conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
  2001. resp = conn.getresponse()
  2002. if resp.status != 412:
  2003. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2004. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2005. resp = conn.getresponse()
  2006. if resp.status != 412:
  2007. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2008. headers = { "NT": "upnp:event",
  2009. "timeout": "Second-1234" }
  2010. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2011. resp = conn.getresponse()
  2012. if resp.status != 412:
  2013. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2014. headers = { "callback": '<http://127.0.0.1:12345/event>',
  2015. "NT": "upnp:foobar",
  2016. "timeout": "Second-1234" }
  2017. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2018. resp = conn.getresponse()
  2019. if resp.status != 400:
  2020. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2021. logger.debug("Valid subscription")
  2022. headers = { "callback": '<http://127.0.0.1:12345/event>',
  2023. "NT": "upnp:event",
  2024. "timeout": "Second-1234" }
  2025. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2026. resp = conn.getresponse()
  2027. if resp.status != 200:
  2028. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2029. sid = resp.getheader("sid")
  2030. logger.debug("Subscription SID " + sid)
  2031. logger.debug("Invalid re-subscription")
  2032. headers = { "NT": "upnp:event",
  2033. "sid": "123456734567854",
  2034. "timeout": "Second-1234" }
  2035. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2036. resp = conn.getresponse()
  2037. if resp.status != 400:
  2038. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2039. logger.debug("Invalid re-subscription")
  2040. headers = { "NT": "upnp:event",
  2041. "sid": "uuid:123456734567854",
  2042. "timeout": "Second-1234" }
  2043. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2044. resp = conn.getresponse()
  2045. if resp.status != 400:
  2046. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2047. logger.debug("Invalid re-subscription")
  2048. headers = { "callback": '<http://127.0.0.1:12345/event>',
  2049. "NT": "upnp:event",
  2050. "sid": sid,
  2051. "timeout": "Second-1234" }
  2052. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2053. resp = conn.getresponse()
  2054. if resp.status != 400:
  2055. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2056. logger.debug("SID mismatch in re-subscription")
  2057. headers = { "NT": "upnp:event",
  2058. "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
  2059. "timeout": "Second-1234" }
  2060. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2061. resp = conn.getresponse()
  2062. if resp.status != 412:
  2063. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2064. logger.debug("Valid re-subscription")
  2065. headers = { "NT": "upnp:event",
  2066. "sid": sid,
  2067. "timeout": "Second-1234" }
  2068. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2069. resp = conn.getresponse()
  2070. if resp.status != 200:
  2071. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2072. sid2 = resp.getheader("sid")
  2073. logger.debug("Subscription SID " + sid2)
  2074. if sid != sid2:
  2075. raise Exception("Unexpected SID change")
  2076. logger.debug("Valid re-subscription")
  2077. headers = { "NT": "upnp:event",
  2078. "sid": "uuid: \t \t" + sid.split(':')[1],
  2079. "timeout": "Second-1234" }
  2080. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2081. resp = conn.getresponse()
  2082. if resp.status != 200:
  2083. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2084. logger.debug("Invalid unsubscription")
  2085. headers = { "sid": sid }
  2086. conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
  2087. resp = conn.getresponse()
  2088. if resp.status != 412:
  2089. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2090. headers = { "foo": "bar" }
  2091. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2092. resp = conn.getresponse()
  2093. if resp.status != 412:
  2094. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2095. logger.debug("Valid unsubscription")
  2096. headers = { "sid": sid }
  2097. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2098. resp = conn.getresponse()
  2099. if resp.status != 200:
  2100. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2101. logger.debug("Unsubscription for not existing SID")
  2102. headers = { "sid": sid }
  2103. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2104. resp = conn.getresponse()
  2105. if resp.status != 412:
  2106. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2107. logger.debug("Invalid unsubscription")
  2108. headers = { "sid": " \t \tfoo" }
  2109. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2110. resp = conn.getresponse()
  2111. if resp.status != 400:
  2112. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2113. logger.debug("Invalid unsubscription")
  2114. headers = { "sid": "uuid:\t \tfoo" }
  2115. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2116. resp = conn.getresponse()
  2117. if resp.status != 400:
  2118. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2119. logger.debug("Invalid unsubscription")
  2120. headers = { "NT": "upnp:event",
  2121. "sid": sid }
  2122. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2123. resp = conn.getresponse()
  2124. if resp.status != 400:
  2125. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2126. headers = { "callback": '<http://127.0.0.1:12345/event>',
  2127. "sid": sid }
  2128. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2129. resp = conn.getresponse()
  2130. if resp.status != 400:
  2131. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2132. logger.debug("Valid subscription with multiple callbacks")
  2133. headers = { "callback": '<http://127.0.0.1:12345/event> <http://127.0.0.1:12345/event>\t<http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event>',
  2134. "NT": "upnp:event",
  2135. "timeout": "Second-1234" }
  2136. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2137. resp = conn.getresponse()
  2138. if resp.status != 200:
  2139. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2140. sid = resp.getheader("sid")
  2141. logger.debug("Subscription SID " + sid)
  2142. def test_ap_wps_upnp_http_proto(dev, apdev):
  2143. """WPS AP and UPnP/HTTP protocol testing"""
  2144. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  2145. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  2146. location = ssdp_get_location(ap_uuid)
  2147. url = urlparse.urlparse(location)
  2148. conn = httplib.HTTPConnection(url.netloc, timeout=0.2)
  2149. #conn.set_debuglevel(1)
  2150. conn.request("HEAD", "hello")
  2151. resp = conn.getresponse()
  2152. if resp.status != 501:
  2153. raise Exception("Unexpected response to HEAD: " + str(resp.status))
  2154. conn.close()
  2155. for cmd in [ "PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST" ]:
  2156. try:
  2157. conn.request(cmd, "hello")
  2158. resp = conn.getresponse()
  2159. except Exception, e:
  2160. pass
  2161. conn.close()
  2162. headers = { "Content-Length": 'abc' }
  2163. conn.request("HEAD", "hello", "\r\n\r\n", headers)
  2164. try:
  2165. resp = conn.getresponse()
  2166. except Exception, e:
  2167. pass
  2168. conn.close()
  2169. headers = { "Content-Length": '-10' }
  2170. conn.request("HEAD", "hello", "\r\n\r\n", headers)
  2171. try:
  2172. resp = conn.getresponse()
  2173. except Exception, e:
  2174. pass
  2175. conn.close()
  2176. headers = { "Content-Length": '10000000000000' }
  2177. conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
  2178. try:
  2179. resp = conn.getresponse()
  2180. except Exception, e:
  2181. pass
  2182. conn.close()
  2183. headers = { "Transfer-Encoding": 'abc' }
  2184. conn.request("HEAD", "hello", "\r\n\r\n", headers)
  2185. resp = conn.getresponse()
  2186. if resp.status != 501:
  2187. raise Exception("Unexpected response to HEAD: " + str(resp.status))
  2188. conn.close()
  2189. headers = { "Transfer-Encoding": 'chunked' }
  2190. conn.request("HEAD", "hello", "\r\n\r\n", headers)
  2191. resp = conn.getresponse()
  2192. if resp.status != 501:
  2193. raise Exception("Unexpected response to HEAD: " + str(resp.status))
  2194. conn.close()
  2195. # Too long a header
  2196. conn.request("HEAD", 5000 * 'A')
  2197. try:
  2198. resp = conn.getresponse()
  2199. except Exception, e:
  2200. pass
  2201. conn.close()
  2202. # Long URL but within header length limits
  2203. conn.request("HEAD", 3000 * 'A')
  2204. resp = conn.getresponse()
  2205. if resp.status != 501:
  2206. raise Exception("Unexpected response to HEAD: " + str(resp.status))
  2207. conn.close()
  2208. headers = { "Content-Length": '20' }
  2209. conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
  2210. try:
  2211. resp = conn.getresponse()
  2212. except Exception, e:
  2213. pass
  2214. conn.close()
  2215. conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
  2216. resp = conn.getresponse()
  2217. if resp.status != 404:
  2218. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2219. conn.close()
  2220. conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
  2221. try:
  2222. resp = conn.getresponse()
  2223. except Exception, e:
  2224. pass
  2225. conn.close()
  2226. def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
  2227. """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
  2228. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  2229. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  2230. location = ssdp_get_location(ap_uuid)
  2231. url = urlparse.urlparse(location)
  2232. conn = httplib.HTTPConnection(url.netloc)
  2233. #conn.set_debuglevel(1)
  2234. headers = { "Transfer-Encoding": 'chunked' }
  2235. conn.request("POST", "hello",
  2236. "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
  2237. headers)
  2238. resp = conn.getresponse()
  2239. if resp.status != 404:
  2240. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2241. conn.close()
  2242. conn.putrequest("POST", "hello")
  2243. conn.putheader('Transfer-Encoding', 'chunked')
  2244. conn.endheaders()
  2245. conn.send("a\r\nabcdefghij\r\n")
  2246. time.sleep(0.1)
  2247. conn.send("2\r\nkl\r\n")
  2248. conn.send("0\r\n\r\n")
  2249. resp = conn.getresponse()
  2250. if resp.status != 404:
  2251. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2252. conn.close()
  2253. conn.putrequest("POST", "hello")
  2254. conn.putheader('Transfer-Encoding', 'chunked')
  2255. conn.endheaders()
  2256. completed = False
  2257. try:
  2258. for i in range(20000):
  2259. conn.send("1\r\nZ\r\n")
  2260. conn.send("0\r\n\r\n")
  2261. resp = conn.getresponse()
  2262. completed = True
  2263. except Exception, e:
  2264. pass
  2265. conn.close()
  2266. if completed:
  2267. raise Exception("Too long chunked request did not result in connection reset")
  2268. headers = { "Transfer-Encoding": 'chunked' }
  2269. conn.request("POST", "hello", "80000000\r\na", headers)
  2270. try:
  2271. resp = conn.getresponse()
  2272. except Exception, e:
  2273. pass
  2274. conn.close()
  2275. conn.request("POST", "hello", "10000000\r\na", headers)
  2276. try:
  2277. resp = conn.getresponse()
  2278. except Exception, e:
  2279. pass
  2280. conn.close()
  2281. def test_ap_wps_disabled(dev, apdev):
  2282. """WPS operations while WPS is disabled"""
  2283. ssid = "test-wps-disabled"
  2284. hostapd.add_ap(apdev[0]['ifname'], { "ssid": ssid })
  2285. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2286. if "FAIL" not in hapd.request("WPS_PBC"):
  2287. raise Exception("WPS_PBC succeeded unexpectedly")
  2288. if "FAIL" not in hapd.request("WPS_CANCEL"):
  2289. raise Exception("WPS_CANCEL succeeded unexpectedly")
  2290. def test_ap_wps_mixed_cred(dev, apdev):
  2291. """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
  2292. ssid = "test-wps-wep"
  2293. hostapd.add_ap(apdev[0]['ifname'],
  2294. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2295. "skip_cred_build": "1", "extra_cred": "wps-mixed-cred" })
  2296. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2297. hapd.request("WPS_PBC")
  2298. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  2299. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  2300. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
  2301. if ev is None:
  2302. raise Exception("WPS-SUCCESS event timed out")
  2303. nets = dev[0].list_networks()
  2304. if len(nets) != 1:
  2305. raise Exception("Unexpected number of network blocks")
  2306. id = nets[0]['id']
  2307. proto = dev[0].get_network(id, "proto")
  2308. if proto != "WPA RSN":
  2309. raise Exception("Unexpected merged proto field value: " + proto)
  2310. pairwise = dev[0].get_network(id, "pairwise")
  2311. if pairwise != "CCMP TKIP" and pairwise != "CCMP GCMP TKIP":
  2312. raise Exception("Unexpected merged pairwise field value: " + pairwise)
  2313. def test_ap_wps_while_connected(dev, apdev):
  2314. """WPS PBC provisioning while connected to another AP"""
  2315. ssid = "test-wps-conf"
  2316. hostapd.add_ap(apdev[0]['ifname'],
  2317. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2318. "wpa_passphrase": "12345678", "wpa": "2",
  2319. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2320. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2321. hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
  2322. dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
  2323. logger.info("WPS provisioning step")
  2324. hapd.request("WPS_PBC")
  2325. dev[0].dump_monitor()
  2326. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  2327. dev[0].wait_connected(timeout=30)
  2328. status = dev[0].get_status()
  2329. if status['bssid'] != apdev[0]['bssid']:
  2330. raise Exception("Unexpected BSSID")
  2331. def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
  2332. """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
  2333. ssid = "test-wps-conf"
  2334. hostapd.add_ap(apdev[0]['ifname'],
  2335. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2336. "wpa_passphrase": "12345678", "wpa": "2",
  2337. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2338. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2339. hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
  2340. try:
  2341. dev[0].request("STA_AUTOCONNECT 0")
  2342. dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
  2343. logger.info("WPS provisioning step")
  2344. hapd.request("WPS_PBC")
  2345. dev[0].dump_monitor()
  2346. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  2347. dev[0].wait_connected(timeout=30)
  2348. status = dev[0].get_status()
  2349. if status['bssid'] != apdev[0]['bssid']:
  2350. raise Exception("Unexpected BSSID")
  2351. finally:
  2352. dev[0].request("STA_AUTOCONNECT 1")
  2353. def test_ap_wps_from_event(dev, apdev):
  2354. """WPS PBC event on AP to enable PBC"""
  2355. ssid = "test-wps-conf"
  2356. hapd = hostapd.add_ap(apdev[0]['ifname'],
  2357. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2358. "wpa_passphrase": "12345678", "wpa": "2",
  2359. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2360. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  2361. dev[0].dump_monitor()
  2362. hapd.dump_monitor()
  2363. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  2364. ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
  2365. if ev is None:
  2366. raise Exception("No WPS-ENROLLEE-SEEN event on AP")
  2367. vals = ev.split(' ')
  2368. if vals[1] != dev[0].p2p_interface_addr():
  2369. raise Exception("Unexpected enrollee address: " + vals[1])
  2370. if vals[5] != '4':
  2371. raise Exception("Unexpected Device Password Id: " + vals[5])
  2372. hapd.request("WPS_PBC")
  2373. dev[0].wait_connected(timeout=30)
  2374. def test_ap_wps_ap_scan_2(dev, apdev):
  2375. """AP_SCAN 2 for WPS"""
  2376. ssid = "test-wps-conf"
  2377. hapd = hostapd.add_ap(apdev[0]['ifname'],
  2378. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2379. "wpa_passphrase": "12345678", "wpa": "2",
  2380. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2381. hapd.request("WPS_PBC")
  2382. wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
  2383. wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
  2384. if "OK" not in wpas.request("AP_SCAN 2"):
  2385. raise Exception("Failed to set AP_SCAN 2")
  2386. wpas.flush_scan_cache()
  2387. wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
  2388. wpas.request("WPS_PBC " + apdev[0]['bssid'])
  2389. ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
  2390. if ev is None:
  2391. raise Exception("WPS-SUCCESS event timed out")
  2392. wpas.wait_connected(timeout=30)
  2393. wpas.request("DISCONNECT")
  2394. wpas.request("BSS_FLUSH 0")
  2395. wpas.dump_monitor()
  2396. wpas.request("REASSOCIATE")
  2397. wpas.wait_connected(timeout=30)
  2398. def test_ap_wps_eapol_workaround(dev, apdev):
  2399. """EAPOL workaround code path for 802.1X header length mismatch"""
  2400. ssid = "test-wps"
  2401. hostapd.add_ap(apdev[0]['ifname'],
  2402. { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
  2403. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2404. bssid = apdev[0]['bssid']
  2405. hapd.request("SET ext_eapol_frame_io 1")
  2406. dev[0].request("SET ext_eapol_frame_io 1")
  2407. hapd.request("WPS_PBC")
  2408. dev[0].request("WPS_PBC")
  2409. ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
  2410. if ev is None:
  2411. raise Exception("Timeout on EAPOL-TX from hostapd")
  2412. res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
  2413. if "OK" not in res:
  2414. raise Exception("EAPOL_RX to wpa_supplicant failed")
  2415. def test_ap_wps_iteration(dev, apdev):
  2416. """WPS PIN and iterate through APs without selected registrar"""
  2417. ssid = "test-wps-conf"
  2418. hapd = hostapd.add_ap(apdev[0]['ifname'],
  2419. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2420. "wpa_passphrase": "12345678", "wpa": "2",
  2421. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2422. ssid2 = "test-wps-conf2"
  2423. hapd2 = hostapd.add_ap(apdev[1]['ifname'],
  2424. { "ssid": ssid2, "eap_server": "1", "wps_state": "2",
  2425. "wpa_passphrase": "12345678", "wpa": "2",
  2426. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2427. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  2428. dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
  2429. dev[0].dump_monitor()
  2430. pin = dev[0].request("WPS_PIN any")
  2431. # Wait for iteration through all WPS APs to happen before enabling any
  2432. # Registrar.
  2433. for i in range(2):
  2434. ev = dev[0].wait_event(["Associated with"], timeout=30)
  2435. if ev is None:
  2436. raise Exception("No association seen")
  2437. ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
  2438. if ev is None:
  2439. raise Exception("No M2D from AP")
  2440. dev[0].wait_disconnected()
  2441. # Verify that each AP requested PIN
  2442. ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
  2443. if ev is None:
  2444. raise Exception("No WPS-PIN-NEEDED event from AP")
  2445. ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
  2446. if ev is None:
  2447. raise Exception("No WPS-PIN-NEEDED event from AP2")
  2448. # Provide PIN to one of the APs and verify that connection gets formed
  2449. hapd.request("WPS_PIN any " + pin)
  2450. dev[0].wait_connected(timeout=30)
  2451. def test_ap_wps_iteration_error(dev, apdev):
  2452. """WPS AP iteration on no Selected Registrar and error case with an AP"""
  2453. ssid = "test-wps-conf-pin"
  2454. hapd = hostapd.add_ap(apdev[0]['ifname'],
  2455. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2456. "wpa_passphrase": "12345678", "wpa": "2",
  2457. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  2458. "wps_independent": "1" })
  2459. hapd.request("SET ext_eapol_frame_io 1")
  2460. bssid = apdev[0]['bssid']
  2461. pin = dev[0].wps_read_pin()
  2462. dev[0].request("WPS_PIN any " + pin)
  2463. ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
  2464. if ev is None:
  2465. raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
  2466. dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
  2467. ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
  2468. if ev is None:
  2469. raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
  2470. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
  2471. if ev is None:
  2472. raise Exception("No CTRL-EVENT-EAP-STARTED")
  2473. # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
  2474. # a case with an incorrectly behaving WPS AP.
  2475. # Start the real target AP and activate registrar on it.
  2476. hapd2 = hostapd.add_ap(apdev[1]['ifname'],
  2477. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2478. "wpa_passphrase": "12345678", "wpa": "2",
  2479. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  2480. "wps_independent": "1" })
  2481. hapd2.request("WPS_PIN any " + pin)
  2482. dev[0].wait_disconnected(timeout=15)
  2483. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
  2484. if ev is None:
  2485. raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
  2486. ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  2487. if ev is None:
  2488. raise Exception("No WPS-CRED-RECEIVED for the second AP")
  2489. dev[0].wait_connected(timeout=15)
  2490. def test_ap_wps_priority(dev, apdev):
  2491. """WPS PIN provisioning with configured AP and wps_priority"""
  2492. ssid = "test-wps-conf-pin"
  2493. hostapd.add_ap(apdev[0]['ifname'],
  2494. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2495. "wpa_passphrase": "12345678", "wpa": "2",
  2496. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2497. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2498. logger.info("WPS provisioning step")
  2499. pin = dev[0].wps_read_pin()
  2500. hapd.request("WPS_PIN any " + pin)
  2501. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  2502. dev[0].dump_monitor()
  2503. try:
  2504. dev[0].request("SET wps_priority 6")
  2505. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  2506. dev[0].wait_connected(timeout=30)
  2507. netw = dev[0].list_networks()
  2508. prio = dev[0].get_network(netw[0]['id'], 'priority')
  2509. if prio != '6':
  2510. raise Exception("Unexpected network priority: " + prio)
  2511. finally:
  2512. dev[0].request("SET wps_priority 0")
  2513. def test_ap_wps_and_non_wps(dev, apdev):
  2514. """WPS and non-WPS AP in single hostapd process"""
  2515. params = { "ssid": "wps", "eap_server": "1", "wps_state": "1" }
  2516. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  2517. params = { "ssid": "no wps" }
  2518. hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
  2519. appin = hapd.request("WPS_AP_PIN random")
  2520. if "FAIL" in appin:
  2521. raise Exception("Could not generate random AP PIN")
  2522. if appin not in hapd.request("WPS_AP_PIN get"):
  2523. raise Exception("Could not fetch current AP PIN")
  2524. if "FAIL" in hapd.request("WPS_PBC"):
  2525. raise Exception("WPS_PBC failed")
  2526. if "FAIL" in hapd.request("WPS_CANCEL"):
  2527. raise Exception("WPS_CANCEL failed")
  2528. def test_ap_wps_init_oom(dev, apdev):
  2529. """Initial AP configuration and OOM during PSK generation"""
  2530. ssid = "test-wps"
  2531. params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
  2532. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  2533. with alloc_fail(hapd, 1, "base64_encode;wps_build_cred"):
  2534. pin = dev[0].wps_read_pin()
  2535. hapd.request("WPS_PIN any " + pin)
  2536. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  2537. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  2538. dev[0].wait_disconnected()
  2539. hapd.request("WPS_PIN any " + pin)
  2540. dev[0].wait_connected(timeout=30)
  2541. def test_ap_wps_er_oom(dev, apdev):
  2542. """WPS ER OOM in XML processing"""
  2543. try:
  2544. _test_ap_wps_er_oom(dev, apdev)
  2545. finally:
  2546. dev[0].request("WPS_ER_STOP")
  2547. dev[1].request("WPS_CANCEL")
  2548. dev[0].request("DISCONNECT")
  2549. def _test_ap_wps_er_oom(dev, apdev):
  2550. ssid = "wps-er-ap-config"
  2551. ap_pin = "12345670"
  2552. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  2553. hostapd.add_ap(apdev[0]['ifname'],
  2554. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2555. "wpa_passphrase": "12345678", "wpa": "2",
  2556. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  2557. "device_name": "Wireless AP", "manufacturer": "Company",
  2558. "model_name": "WAP", "model_number": "123",
  2559. "serial_number": "12345", "device_type": "6-0050F204-1",
  2560. "os_version": "01020300",
  2561. "config_methods": "label push_button",
  2562. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  2563. dev[0].connect(ssid, psk="12345678", scan_freq="2412")
  2564. with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
  2565. dev[0].request("WPS_ER_START ifname=lo")
  2566. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
  2567. if ev is not None:
  2568. raise Exception("Unexpected AP discovery")
  2569. dev[0].request("WPS_ER_STOP")
  2570. dev[0].request("WPS_ER_START ifname=lo")
  2571. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
  2572. if ev is None:
  2573. raise Exception("AP discovery timed out")
  2574. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  2575. with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
  2576. dev[1].request("WPS_PBC " + apdev[0]['bssid'])
  2577. ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
  2578. if ev is None:
  2579. raise Exception("PBC scan failed")
  2580. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
  2581. if ev is None:
  2582. raise Exception("Enrollee discovery timed out")
  2583. def test_ap_wps_er_init_oom(dev, apdev):
  2584. """WPS ER and OOM during init"""
  2585. try:
  2586. _test_ap_wps_er_init_oom(dev, apdev)
  2587. finally:
  2588. dev[0].request("WPS_ER_STOP")
  2589. def _test_ap_wps_er_init_oom(dev, apdev):
  2590. with alloc_fail(dev[0], 1, "wps_er_init"):
  2591. if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
  2592. raise Exception("WPS_ER_START succeeded during OOM")
  2593. with alloc_fail(dev[0], 1, "http_server_init"):
  2594. if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
  2595. raise Exception("WPS_ER_START succeeded during OOM")
  2596. with alloc_fail(dev[0], 2, "http_server_init"):
  2597. if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
  2598. raise Exception("WPS_ER_START succeeded during OOM")
  2599. with alloc_fail(dev[0], 1, "eloop_register_sock;wps_er_ssdp_init"):
  2600. if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
  2601. raise Exception("WPS_ER_START succeeded during OOM")
  2602. with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
  2603. if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
  2604. raise Exception("WPS_ER_START succeeded during os_get_random failure")
  2605. def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
  2606. """WPS events and wpa_cli action script"""
  2607. logdir = os.path.abspath(test_params['logdir'])
  2608. pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
  2609. logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
  2610. actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
  2611. with open(actionfile, 'w') as f:
  2612. f.write('#!/bin/sh\n')
  2613. f.write('echo $* >> %s\n' % logfile)
  2614. # Kill the process and wait some time before returning to allow all the
  2615. # pending events to be processed with some of this happening after the
  2616. # eloop SIGALRM signal has been scheduled.
  2617. f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
  2618. os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
  2619. stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
  2620. ssid = "test-wps-conf"
  2621. hostapd.add_ap(apdev[0]['ifname'],
  2622. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2623. "wpa_passphrase": "12345678", "wpa": "2",
  2624. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2625. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2626. prg = os.path.join(test_params['logdir'],
  2627. 'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
  2628. if not os.path.exists(prg):
  2629. prg = '../../wpa_supplicant/wpa_cli'
  2630. arg = [ prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile ]
  2631. subprocess.call(arg)
  2632. arg = [ 'ps', 'ax' ]
  2633. cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
  2634. out = cmd.communicate()[0]
  2635. cmd.wait()
  2636. logger.debug("Processes:\n" + out)
  2637. if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
  2638. raise Exception("Did not see wpa_cli running")
  2639. hapd.request("WPS_PIN any 12345670")
  2640. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  2641. dev[0].dump_monitor()
  2642. dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
  2643. dev[0].wait_connected(timeout=30)
  2644. for i in range(30):
  2645. if not os.path.exists(pidfile):
  2646. break
  2647. time.sleep(0.1)
  2648. if not os.path.exists(logfile):
  2649. raise Exception("wpa_cli action results file not found")
  2650. with open(logfile, 'r') as f:
  2651. res = f.read()
  2652. if "WPS-SUCCESS" not in res:
  2653. raise Exception("WPS-SUCCESS event not seen in action file")
  2654. arg = [ 'ps', 'ax' ]
  2655. cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
  2656. out = cmd.communicate()[0]
  2657. cmd.wait()
  2658. logger.debug("Remaining processes:\n" + out)
  2659. if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
  2660. raise Exception("wpa_cli still running")
  2661. if os.path.exists(pidfile):
  2662. raise Exception("PID file not removed")
  2663. def test_ap_wps_er_ssdp_proto(dev, apdev):
  2664. """WPS ER SSDP protocol testing"""
  2665. try:
  2666. _test_ap_wps_er_ssdp_proto(dev, apdev)
  2667. finally:
  2668. dev[0].request("WPS_ER_STOP")
  2669. def _test_ap_wps_er_ssdp_proto(dev, apdev):
  2670. socket.setdefaulttimeout(1)
  2671. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  2672. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  2673. sock.bind(("239.255.255.250", 1900))
  2674. if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
  2675. raise Exception("Invalid filter accepted")
  2676. if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
  2677. raise Exception("WPS_ER_START with filter failed")
  2678. (msg,addr) = sock.recvfrom(1000)
  2679. logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
  2680. if "M-SEARCH" not in msg:
  2681. raise Exception("Not an M-SEARCH")
  2682. sock.sendto("FOO", addr)
  2683. time.sleep(0.1)
  2684. dev[0].request("WPS_ER_STOP")
  2685. dev[0].request("WPS_ER_START ifname=lo")
  2686. (msg,addr) = sock.recvfrom(1000)
  2687. logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
  2688. if "M-SEARCH" not in msg:
  2689. raise Exception("Not an M-SEARCH")
  2690. sock.sendto("FOO", addr)
  2691. sock.sendto("HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
  2692. sock.sendto("HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
  2693. sock.sendto("HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
  2694. sock.sendto("HTTP/1.1 200 OK\r\ncache-control: foo=1\r\n\r\n", addr)
  2695. sock.sendto("HTTP/1.1 200 OK\r\ncache-control: max-age=1\r\n\r\n", addr)
  2696. sock.sendto("HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
  2697. sock.sendto("HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
  2698. sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid:\r\n\r\n", addr)
  2699. sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: \r\n\r\n", addr)
  2700. sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: foo\r\n\r\n", addr)
  2701. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
  2702. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nNTS:ssdp:byebye\r\n\r\n", addr)
  2703. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\n\r\n", addr)
  2704. with alloc_fail(dev[0], 1, "wps_er_ap_add"):
  2705. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
  2706. time.sleep(0.1)
  2707. with alloc_fail(dev[0], 2, "wps_er_ap_add"):
  2708. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
  2709. time.sleep(0.1)
  2710. # Add an AP with bogus URL
  2711. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
  2712. # Update timeout on AP without updating URL
  2713. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1:12345/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
  2714. ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
  2715. if ev is None:
  2716. raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
  2717. # Add an AP with a valid URL (but no server listing to it)
  2718. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1:12345/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
  2719. ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
  2720. if ev is None:
  2721. raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
  2722. sock.close()
  2723. wps_event_url = None
  2724. def gen_upnp_info(eventSubURL='wps_event'):
  2725. payload = '''<?xml version="1.0"?>
  2726. <root xmlns="urn:schemas-upnp-org:device-1-0">
  2727. <specVersion>
  2728. <major>1</major>
  2729. <minor>0</minor>
  2730. </specVersion>
  2731. <device>
  2732. <deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
  2733. <friendlyName>WPS Access Point</friendlyName>
  2734. <manufacturer>Company</manufacturer>
  2735. <modelName>WAP</modelName>
  2736. <modelNumber>123</modelNumber>
  2737. <serialNumber>12345</serialNumber>
  2738. <UDN>uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e</UDN>
  2739. <serviceList>
  2740. <service>
  2741. <serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
  2742. <serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
  2743. <SCPDURL>wps_scpd.xml</SCPDURL>
  2744. <controlURL>wps_control</controlURL>
  2745. '''
  2746. if eventSubURL:
  2747. payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>'
  2748. payload += '''</service>
  2749. </serviceList>
  2750. </device>
  2751. </root>
  2752. '''
  2753. hdr = 'HTTP/1.1 200 OK\r\n' + \
  2754. 'Content-Type: text/xml; charset="utf-8"\r\n' + \
  2755. 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
  2756. 'Connection: close\r\n' + \
  2757. 'Content-Length: ' + str(len(payload)) + '\r\n' + \
  2758. 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
  2759. return hdr + payload
  2760. def gen_wps_control():
  2761. payload = '''<?xml version="1.0"?>
  2762. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  2763. <s:Body>
  2764. <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
  2765. <NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
  2766. Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
  2767. +FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
  2768. 7zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
  2769. KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
  2770. AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
  2771. AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
  2772. AAYANyoAASA=
  2773. </NewDeviceInfo>
  2774. </u:GetDeviceInfoResponse>
  2775. </s:Body>
  2776. </s:Envelope>
  2777. '''
  2778. hdr = 'HTTP/1.1 200 OK\r\n' + \
  2779. 'Content-Type: text/xml; charset="utf-8"\r\n' + \
  2780. 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
  2781. 'Connection: close\r\n' + \
  2782. 'Content-Length: ' + str(len(payload)) + '\r\n' + \
  2783. 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
  2784. return hdr + payload
  2785. def gen_wps_event():
  2786. payload = ""
  2787. hdr = 'HTTP/1.1 200 OK\r\n' + \
  2788. 'Content-Type: text/xml; charset="utf-8"\r\n' + \
  2789. 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
  2790. 'Connection: close\r\n' + \
  2791. 'Content-Length: ' + str(len(payload)) + '\r\n' + \
  2792. 'SID: uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a\r\n' + \
  2793. 'Timeout: Second-1801\r\n' + \
  2794. 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
  2795. return hdr + payload
  2796. class WPSAPHTTPServer(SocketServer.StreamRequestHandler):
  2797. def handle(self):
  2798. data = self.rfile.readline().strip()
  2799. logger.info("HTTP server received: " + data)
  2800. while True:
  2801. hdr = self.rfile.readline().strip()
  2802. if len(hdr) == 0:
  2803. break
  2804. logger.info("HTTP header: " + hdr)
  2805. if "CALLBACK:" in hdr:
  2806. global wps_event_url
  2807. wps_event_url = hdr.split(' ')[1].strip('<>')
  2808. if "GET /foo.xml" in data:
  2809. self.wfile.write(gen_upnp_info())
  2810. if "POST /wps_control" in data:
  2811. self.wfile.write(gen_wps_control())
  2812. if "SUBSCRIBE /wps_event" in data:
  2813. self.wfile.write(gen_wps_event())
  2814. class MyTCPServer(SocketServer.TCPServer):
  2815. def __init__(self, addr, handler):
  2816. self.allow_reuse_address = True
  2817. SocketServer.TCPServer.__init__(self, addr, handler)
  2818. def wps_er_start(dev, http_server):
  2819. socket.setdefaulttimeout(1)
  2820. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  2821. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  2822. sock.bind(("239.255.255.250", 1900))
  2823. dev.request("WPS_ER_START ifname=lo")
  2824. (msg,addr) = sock.recvfrom(1000)
  2825. logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
  2826. if "M-SEARCH" not in msg:
  2827. raise Exception("Not an M-SEARCH")
  2828. # Add an AP with a valid URL and server listing to it
  2829. server = MyTCPServer(("127.0.0.1", 12345), http_server)
  2830. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1:12345/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
  2831. server.timeout = 1
  2832. return server,sock
  2833. def wps_er_stop(dev, sock, server, on_alloc_fail=False):
  2834. sock.close()
  2835. server.server_close()
  2836. if on_alloc_fail:
  2837. done = False
  2838. for i in range(50):
  2839. res = dev.request("GET_ALLOC_FAIL")
  2840. if res.startswith("0:"):
  2841. done = True
  2842. break
  2843. time.sleep(0.1)
  2844. if not done:
  2845. raise Exception("No allocation failure reported")
  2846. else:
  2847. ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
  2848. if ev is None:
  2849. raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
  2850. dev.request("WPS_ER_STOP")
  2851. def test_ap_wps_er_http_proto(dev, apdev):
  2852. """WPS ER HTTP protocol testing"""
  2853. try:
  2854. _test_ap_wps_er_http_proto(dev, apdev)
  2855. finally:
  2856. dev[0].request("WPS_ER_STOP")
  2857. def _test_ap_wps_er_http_proto(dev, apdev):
  2858. uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
  2859. server,sock = wps_er_start(dev[0], WPSAPHTTPServer)
  2860. global wps_event_url
  2861. wps_event_url = None
  2862. server.handle_request()
  2863. server.handle_request()
  2864. server.handle_request()
  2865. server.server_close()
  2866. if wps_event_url is None:
  2867. raise Exception("Did not get event URL")
  2868. logger.info("Event URL: " + wps_event_url)
  2869. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
  2870. if ev is None:
  2871. raise Exception("No WPS-ER-AP-ADD event")
  2872. if uuid not in ev:
  2873. raise Exception("UUID mismatch")
  2874. sock.close()
  2875. logger.info("Valid Probe Request notification")
  2876. url = urlparse.urlparse(wps_event_url)
  2877. conn = httplib.HTTPConnection(url.netloc)
  2878. payload = '''<?xml version="1.0" encoding="utf-8"?>
  2879. <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
  2880. <e:property><STAStatus>1</STAStatus></e:property>
  2881. <e:property><APStatus>1</APStatus></e:property>
  2882. <e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
  2883. EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
  2884. RGV2aWNlIEEQSQAGADcqAAEg
  2885. </WLANEvent></e:property>
  2886. </e:propertyset>
  2887. '''
  2888. headers = { "Content-type": 'text/xml; charset="utf-8"',
  2889. "Server": "Unspecified, UPnP/1.0, Unspecified",
  2890. "HOST": url.netloc,
  2891. "NT": "upnp:event",
  2892. "SID": "uuid:" + uuid,
  2893. "SEQ": "0",
  2894. "Content-Length": str(len(payload)) }
  2895. conn.request("NOTIFY", url.path, payload, headers)
  2896. resp = conn.getresponse()
  2897. if resp.status != 200:
  2898. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2899. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
  2900. if ev is None:
  2901. raise Exception("No WPS-ER-ENROLLEE-ADD event")
  2902. if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
  2903. raise Exception("No Enrollee UUID match")
  2904. logger.info("Incorrect event URL AP id")
  2905. conn = httplib.HTTPConnection(url.netloc)
  2906. conn.request("NOTIFY", url.path + '123', payload, headers)
  2907. resp = conn.getresponse()
  2908. if resp.status != 404:
  2909. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2910. logger.info("Missing AP id")
  2911. conn = httplib.HTTPConnection(url.netloc)
  2912. conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
  2913. payload, headers)
  2914. time.sleep(0.1)
  2915. logger.info("Incorrect event URL event id")
  2916. conn = httplib.HTTPConnection(url.netloc)
  2917. conn.request("NOTIFY", '/event/123456789/123', payload, headers)
  2918. time.sleep(0.1)
  2919. logger.info("Incorrect event URL prefix")
  2920. conn = httplib.HTTPConnection(url.netloc)
  2921. conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
  2922. resp = conn.getresponse()
  2923. if resp.status != 404:
  2924. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2925. logger.info("Unsupported request")
  2926. conn = httplib.HTTPConnection(url.netloc)
  2927. conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
  2928. resp = conn.getresponse()
  2929. if resp.status != 501:
  2930. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2931. logger.info("Unsupported request and OOM")
  2932. with alloc_fail(dev[0], 1, "wps_er_http_req"):
  2933. conn = httplib.HTTPConnection(url.netloc)
  2934. conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
  2935. time.sleep(0.5)
  2936. class WPSAPHTTPServer2(SocketServer.StreamRequestHandler):
  2937. def handle(self):
  2938. data = self.rfile.readline().strip()
  2939. logger.info("HTTP server received: " + data)
  2940. while True:
  2941. hdr = self.rfile.readline().strip()
  2942. if len(hdr) == 0:
  2943. break
  2944. logger.info("HTTP header: " + hdr)
  2945. if "GET /foo.xml" in data:
  2946. self.wfile.write(gen_upnp_info(eventSubURL=None))
  2947. if "POST /wps_control" in data:
  2948. self.wfile.write(gen_wps_control())
  2949. def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
  2950. """WPS ER HTTP protocol testing - no eventSubURL"""
  2951. try:
  2952. _test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev)
  2953. finally:
  2954. dev[0].request("WPS_ER_STOP")
  2955. def _test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
  2956. server,sock = wps_er_start(dev[0], WPSAPHTTPServer2)
  2957. server.handle_request()
  2958. server.handle_request()
  2959. wps_er_stop(dev[0], sock, server)
  2960. class WPSAPHTTPServer3(SocketServer.StreamRequestHandler):
  2961. def handle(self):
  2962. data = self.rfile.readline().strip()
  2963. logger.info("HTTP server received: " + data)
  2964. while True:
  2965. hdr = self.rfile.readline().strip()
  2966. if len(hdr) == 0:
  2967. break
  2968. logger.info("HTTP header: " + hdr)
  2969. if "GET /foo.xml" in data:
  2970. self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
  2971. if "POST /wps_control" in data:
  2972. self.wfile.write(gen_wps_control())
  2973. def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
  2974. """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
  2975. try:
  2976. _test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev)
  2977. finally:
  2978. dev[0].request("WPS_ER_STOP")
  2979. def _test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
  2980. server,sock = wps_er_start(dev[0], WPSAPHTTPServer3)
  2981. server.handle_request()
  2982. server.handle_request()
  2983. wps_er_stop(dev[0], sock, server)
  2984. def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
  2985. """WPS ER HTTP protocol testing - subscribe OOM"""
  2986. try:
  2987. _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
  2988. finally:
  2989. dev[0].request("WPS_ER_STOP")
  2990. def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
  2991. tests = [ (1, "http_client_url_parse"),
  2992. (1, "wpabuf_alloc;wps_er_subscribe"),
  2993. (1, "http_client_addr"),
  2994. (1, "eloop_register_sock;http_client_addr"),
  2995. (1, "eloop_register_timeout;http_client_addr") ]
  2996. for count,func in tests:
  2997. with alloc_fail(dev[0], count, func):
  2998. server,sock = wps_er_start(dev[0], WPSAPHTTPServer)
  2999. server.handle_request()
  3000. server.handle_request()
  3001. wps_er_stop(dev[0], sock, server, on_alloc_fail=True)