test_ap_wps.py 192 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787
  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 base64
  7. import os
  8. import time
  9. import stat
  10. import subprocess
  11. import logging
  12. logger = logging.getLogger()
  13. import re
  14. import socket
  15. import httplib
  16. import urlparse
  17. import urllib
  18. import xml.etree.ElementTree as ET
  19. import StringIO
  20. import SocketServer
  21. import hwsim_utils
  22. import hostapd
  23. from wpasupplicant import WpaSupplicant
  24. from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips
  25. def wps_start_ap(apdev, ssid="test-wps-conf"):
  26. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  27. "wpa_passphrase": "12345678", "wpa": "2",
  28. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
  29. return hostapd.add_ap(apdev['ifname'], params)
  30. def test_ap_wps_init(dev, apdev):
  31. """Initial AP configuration with first WPS Enrollee"""
  32. ssid = "test-wps"
  33. hostapd.add_ap(apdev[0]['ifname'],
  34. { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
  35. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  36. logger.info("WPS provisioning step")
  37. hapd.request("WPS_PBC")
  38. if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
  39. raise Exception("PBC status not shown correctly")
  40. id = dev[0].add_network()
  41. dev[0].set_network_quoted(id, "ssid", "home")
  42. dev[0].set_network_quoted(id, "psk", "12345678")
  43. dev[0].request("ENABLE_NETWORK %s no-connect" % id)
  44. id = dev[0].add_network()
  45. dev[0].set_network_quoted(id, "ssid", "home2")
  46. dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
  47. dev[0].set_network(id, "key_mgmt", "NONE")
  48. dev[0].request("ENABLE_NETWORK %s no-connect" % id)
  49. dev[0].request("WPS_PBC")
  50. dev[0].wait_connected(timeout=30)
  51. status = dev[0].get_status()
  52. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  53. raise Exception("Not fully connected")
  54. if status['ssid'] != ssid:
  55. raise Exception("Unexpected SSID")
  56. if status['pairwise_cipher'] != 'CCMP':
  57. raise Exception("Unexpected encryption configuration")
  58. if status['key_mgmt'] != 'WPA2-PSK':
  59. raise Exception("Unexpected key_mgmt")
  60. status = hapd.request("WPS_GET_STATUS")
  61. if "PBC Status: Disabled" not in status:
  62. raise Exception("PBC status not shown correctly")
  63. if "Last WPS result: Success" not in status:
  64. raise Exception("Last WPS result not shown correctly")
  65. if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
  66. raise Exception("Peer address not shown correctly")
  67. conf = hapd.request("GET_CONFIG")
  68. if "wps_state=configured" not in conf:
  69. raise Exception("AP not in WPS configured state")
  70. if "wpa=3" not in conf:
  71. raise Exception("AP not in WPA+WPA2 configuration")
  72. if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
  73. raise Exception("Unexpected rsn_pairwise_cipher")
  74. if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
  75. raise Exception("Unexpected wpa_pairwise_cipher")
  76. if "group_cipher=TKIP" not in conf:
  77. raise Exception("Unexpected group_cipher")
  78. if len(dev[0].list_networks()) != 3:
  79. raise Exception("Unexpected number of network blocks")
  80. def test_ap_wps_init_2ap_pbc(dev, apdev):
  81. """Initial two-radio AP configuration with first WPS PBC Enrollee"""
  82. ssid = "test-wps"
  83. params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
  84. hostapd.add_ap(apdev[0]['ifname'], params)
  85. hostapd.add_ap(apdev[1]['ifname'], params)
  86. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  87. logger.info("WPS provisioning step")
  88. hapd.request("WPS_PBC")
  89. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
  90. dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
  91. bss = dev[0].get_bss(apdev[0]['bssid'])
  92. if "[WPS-PBC]" not in bss['flags']:
  93. raise Exception("WPS-PBC flag missing from AP1")
  94. bss = dev[0].get_bss(apdev[1]['bssid'])
  95. if "[WPS-PBC]" not in bss['flags']:
  96. raise Exception("WPS-PBC flag missing from AP2")
  97. dev[0].dump_monitor()
  98. dev[0].request("SET wps_cred_processing 2")
  99. dev[0].request("WPS_PBC")
  100. ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
  101. dev[0].request("SET wps_cred_processing 0")
  102. if ev is None:
  103. raise Exception("WPS cred event not seen")
  104. if "100e" not in ev:
  105. raise Exception("WPS attributes not included in the cred event")
  106. dev[0].wait_connected(timeout=30)
  107. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
  108. dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
  109. bss = dev[1].get_bss(apdev[0]['bssid'])
  110. if "[WPS-PBC]" in bss['flags']:
  111. raise Exception("WPS-PBC flag not cleared from AP1")
  112. bss = dev[1].get_bss(apdev[1]['bssid'])
  113. if "[WPS-PBC]" in bss['flags']:
  114. raise Exception("WPS-PBC flag not cleared from AP2")
  115. def test_ap_wps_init_2ap_pin(dev, apdev):
  116. """Initial two-radio AP configuration with first WPS PIN Enrollee"""
  117. ssid = "test-wps"
  118. params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
  119. hostapd.add_ap(apdev[0]['ifname'], params)
  120. hostapd.add_ap(apdev[1]['ifname'], params)
  121. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  122. logger.info("WPS provisioning step")
  123. pin = dev[0].wps_read_pin()
  124. hapd.request("WPS_PIN any " + pin)
  125. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
  126. dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
  127. bss = dev[0].get_bss(apdev[0]['bssid'])
  128. if "[WPS-AUTH]" not in bss['flags']:
  129. raise Exception("WPS-AUTH flag missing from AP1")
  130. bss = dev[0].get_bss(apdev[1]['bssid'])
  131. if "[WPS-AUTH]" not in bss['flags']:
  132. raise Exception("WPS-AUTH flag missing from AP2")
  133. dev[0].dump_monitor()
  134. dev[0].request("WPS_PIN any " + pin)
  135. dev[0].wait_connected(timeout=30)
  136. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
  137. dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
  138. bss = dev[1].get_bss(apdev[0]['bssid'])
  139. if "[WPS-AUTH]" in bss['flags']:
  140. raise Exception("WPS-AUTH flag not cleared from AP1")
  141. bss = dev[1].get_bss(apdev[1]['bssid'])
  142. if "[WPS-AUTH]" in bss['flags']:
  143. raise Exception("WPS-AUTH flag not cleared from AP2")
  144. def test_ap_wps_init_through_wps_config(dev, apdev):
  145. """Initial AP configuration using wps_config command"""
  146. ssid = "test-wps-init-config"
  147. hostapd.add_ap(apdev[0]['ifname'],
  148. { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
  149. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  150. if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
  151. raise Exception("WPS_CONFIG command failed")
  152. ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
  153. if ev is None:
  154. raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
  155. # It takes some time for the AP to update Beacon and Probe Response frames,
  156. # so wait here before requesting the scan to be started to avoid adding
  157. # extra five second wait to the test due to fetching obsolete scan results.
  158. hapd.ping()
  159. time.sleep(0.2)
  160. dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
  161. pairwise="CCMP", group="CCMP")
  162. def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
  163. """AP configuration using wps_config command with invalid passphrase"""
  164. ssid = "test-wps-init-config"
  165. hostapd.add_ap(apdev[0]['ifname'],
  166. { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
  167. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  168. if "FAIL" not in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "1234567".encode("hex")):
  169. raise Exception("Invalid WPS_CONFIG command accepted")
  170. def test_ap_wps_conf(dev, apdev):
  171. """WPS PBC provisioning with configured AP"""
  172. ssid = "test-wps-conf"
  173. hostapd.add_ap(apdev[0]['ifname'],
  174. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  175. "wpa_passphrase": "12345678", "wpa": "2",
  176. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  177. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  178. logger.info("WPS provisioning step")
  179. hapd.request("WPS_PBC")
  180. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  181. dev[0].dump_monitor()
  182. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  183. dev[0].wait_connected(timeout=30)
  184. status = dev[0].get_status()
  185. if status['wpa_state'] != 'COMPLETED':
  186. raise Exception("Not fully connected")
  187. if status['bssid'] != apdev[0]['bssid']:
  188. raise Exception("Unexpected BSSID")
  189. if status['ssid'] != ssid:
  190. raise Exception("Unexpected SSID")
  191. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  192. raise Exception("Unexpected encryption configuration")
  193. if status['key_mgmt'] != 'WPA2-PSK':
  194. raise Exception("Unexpected key_mgmt")
  195. sta = hapd.get_sta(dev[0].p2p_interface_addr())
  196. if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
  197. raise Exception("Device name not available in STA command")
  198. def test_ap_wps_conf_5ghz(dev, apdev):
  199. """WPS PBC provisioning with configured AP on 5 GHz band"""
  200. try:
  201. hapd = None
  202. ssid = "test-wps-conf"
  203. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  204. "wpa_passphrase": "12345678", "wpa": "2",
  205. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  206. "country_code": "FI", "hw_mode": "a", "channel": "36" }
  207. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  208. logger.info("WPS provisioning step")
  209. hapd.request("WPS_PBC")
  210. dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
  211. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  212. dev[0].wait_connected(timeout=30)
  213. sta = hapd.get_sta(dev[0].p2p_interface_addr())
  214. if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
  215. raise Exception("Device name not available in STA command")
  216. finally:
  217. dev[0].request("DISCONNECT")
  218. if hapd:
  219. hapd.request("DISABLE")
  220. subprocess.call(['iw', 'reg', 'set', '00'])
  221. dev[0].flush_scan_cache()
  222. def test_ap_wps_conf_chan14(dev, apdev):
  223. """WPS PBC provisioning with configured AP on channel 14"""
  224. try:
  225. hapd = None
  226. ssid = "test-wps-conf"
  227. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  228. "wpa_passphrase": "12345678", "wpa": "2",
  229. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  230. "country_code": "JP", "hw_mode": "b", "channel": "14" }
  231. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  232. logger.info("WPS provisioning step")
  233. hapd.request("WPS_PBC")
  234. dev[0].request("WPS_PBC")
  235. dev[0].wait_connected(timeout=30)
  236. sta = hapd.get_sta(dev[0].p2p_interface_addr())
  237. if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
  238. raise Exception("Device name not available in STA command")
  239. finally:
  240. dev[0].request("DISCONNECT")
  241. if hapd:
  242. hapd.request("DISABLE")
  243. subprocess.call(['iw', 'reg', 'set', '00'])
  244. dev[0].flush_scan_cache()
  245. def test_ap_wps_twice(dev, apdev):
  246. """WPS provisioning with twice to change passphrase"""
  247. ssid = "test-wps-twice"
  248. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  249. "wpa_passphrase": "12345678", "wpa": "2",
  250. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
  251. hostapd.add_ap(apdev[0]['ifname'], params)
  252. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  253. logger.info("WPS provisioning step")
  254. hapd.request("WPS_PBC")
  255. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  256. dev[0].dump_monitor()
  257. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  258. dev[0].wait_connected(timeout=30)
  259. dev[0].request("DISCONNECT")
  260. logger.info("Restart AP with different passphrase and re-run WPS")
  261. hapd_global = hostapd.HostapdGlobal()
  262. hapd_global.remove(apdev[0]['ifname'])
  263. params['wpa_passphrase'] = 'another passphrase'
  264. hostapd.add_ap(apdev[0]['ifname'], params)
  265. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  266. logger.info("WPS provisioning step")
  267. hapd.request("WPS_PBC")
  268. dev[0].dump_monitor()
  269. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  270. dev[0].wait_connected(timeout=30)
  271. networks = dev[0].list_networks()
  272. if len(networks) > 1:
  273. raise Exception("Unexpected duplicated network block present")
  274. def test_ap_wps_incorrect_pin(dev, apdev):
  275. """WPS PIN provisioning with incorrect PIN"""
  276. ssid = "test-wps-incorrect-pin"
  277. hostapd.add_ap(apdev[0]['ifname'],
  278. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  279. "wpa_passphrase": "12345678", "wpa": "2",
  280. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  281. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  282. logger.info("WPS provisioning attempt 1")
  283. hapd.request("WPS_PIN any 12345670")
  284. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  285. dev[0].dump_monitor()
  286. dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
  287. ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
  288. if ev is None:
  289. raise Exception("WPS operation timed out")
  290. if "config_error=18" not in ev:
  291. raise Exception("Incorrect config_error reported")
  292. if "msg=8" not in ev:
  293. raise Exception("PIN error detected on incorrect message")
  294. dev[0].wait_disconnected(timeout=10)
  295. dev[0].request("WPS_CANCEL")
  296. # if a scan was in progress, wait for it to complete before trying WPS again
  297. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
  298. status = hapd.request("WPS_GET_STATUS")
  299. if "Last WPS result: Failed" not in status:
  300. raise Exception("WPS failure result not shown correctly")
  301. logger.info("WPS provisioning attempt 2")
  302. hapd.request("WPS_PIN any 12345670")
  303. dev[0].dump_monitor()
  304. dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
  305. ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
  306. if ev is None:
  307. raise Exception("WPS operation timed out")
  308. if "config_error=18" not in ev:
  309. raise Exception("Incorrect config_error reported")
  310. if "msg=10" not in ev:
  311. raise Exception("PIN error detected on incorrect message")
  312. dev[0].wait_disconnected(timeout=10)
  313. def test_ap_wps_conf_pin(dev, apdev):
  314. """WPS PIN provisioning with configured AP"""
  315. ssid = "test-wps-conf-pin"
  316. hostapd.add_ap(apdev[0]['ifname'],
  317. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  318. "wpa_passphrase": "12345678", "wpa": "2",
  319. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  320. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  321. logger.info("WPS provisioning step")
  322. pin = dev[0].wps_read_pin()
  323. hapd.request("WPS_PIN any " + pin)
  324. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  325. dev[0].dump_monitor()
  326. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  327. dev[0].wait_connected(timeout=30)
  328. status = dev[0].get_status()
  329. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  330. raise Exception("Not fully connected")
  331. if status['ssid'] != ssid:
  332. raise Exception("Unexpected SSID")
  333. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  334. raise Exception("Unexpected encryption configuration")
  335. if status['key_mgmt'] != 'WPA2-PSK':
  336. raise Exception("Unexpected key_mgmt")
  337. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
  338. bss = dev[1].get_bss(apdev[0]['bssid'])
  339. if "[WPS-AUTH]" in bss['flags']:
  340. raise Exception("WPS-AUTH flag not cleared")
  341. logger.info("Try to connect from another station using the same PIN")
  342. pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
  343. ev = dev[1].wait_event(["WPS-M2D","CTRL-EVENT-CONNECTED"], timeout=30)
  344. if ev is None:
  345. raise Exception("Operation timed out")
  346. if "WPS-M2D" not in ev:
  347. raise Exception("Unexpected WPS operation started")
  348. hapd.request("WPS_PIN any " + pin)
  349. dev[1].wait_connected(timeout=30)
  350. def test_ap_wps_conf_pin_v1(dev, apdev):
  351. """WPS PIN provisioning with configured WPS v1.0 AP"""
  352. ssid = "test-wps-conf-pin-v1"
  353. hostapd.add_ap(apdev[0]['ifname'],
  354. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  355. "wpa_passphrase": "12345678", "wpa": "2",
  356. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  357. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  358. logger.info("WPS provisioning step")
  359. pin = dev[0].wps_read_pin()
  360. hapd.request("SET wps_version_number 0x10")
  361. hapd.request("WPS_PIN any " + pin)
  362. found = False
  363. for i in range(0, 10):
  364. dev[0].scan(freq="2412")
  365. if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
  366. found = True
  367. break
  368. if not found:
  369. hapd.request("SET wps_version_number 0x20")
  370. raise Exception("WPS-PIN flag not seen in scan results")
  371. dev[0].dump_monitor()
  372. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  373. dev[0].wait_connected(timeout=30)
  374. hapd.request("SET wps_version_number 0x20")
  375. def test_ap_wps_conf_pin_2sta(dev, apdev):
  376. """Two stations trying to use WPS PIN at the same time"""
  377. ssid = "test-wps-conf-pin2"
  378. hostapd.add_ap(apdev[0]['ifname'],
  379. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  380. "wpa_passphrase": "12345678", "wpa": "2",
  381. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  382. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  383. logger.info("WPS provisioning step")
  384. pin = "12345670"
  385. pin2 = "55554444"
  386. hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
  387. hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
  388. dev[0].dump_monitor()
  389. dev[1].dump_monitor()
  390. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  391. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
  392. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  393. dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  394. dev[0].wait_connected(timeout=30)
  395. dev[1].wait_connected(timeout=30)
  396. def test_ap_wps_conf_pin_timeout(dev, apdev):
  397. """WPS PIN provisioning with configured AP timing out PIN"""
  398. ssid = "test-wps-conf-pin"
  399. hostapd.add_ap(apdev[0]['ifname'],
  400. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  401. "wpa_passphrase": "12345678", "wpa": "2",
  402. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  403. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  404. addr = dev[0].p2p_interface_addr()
  405. pin = dev[0].wps_read_pin()
  406. if "FAIL" not in hapd.request("WPS_PIN "):
  407. raise Exception("Unexpected success on invalid WPS_PIN")
  408. hapd.request("WPS_PIN any " + pin + " 1")
  409. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  410. time.sleep(1.1)
  411. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  412. ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
  413. if ev is None:
  414. raise Exception("WPS-PIN-NEEDED event timed out")
  415. ev = dev[0].wait_event(["WPS-M2D"])
  416. if ev is None:
  417. raise Exception("M2D not reported")
  418. dev[0].request("WPS_CANCEL")
  419. hapd.request("WPS_PIN any " + pin + " 20 " + addr)
  420. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  421. dev[0].wait_connected(timeout=30)
  422. def test_ap_wps_reg_connect(dev, apdev):
  423. """WPS registrar using AP PIN to connect"""
  424. ssid = "test-wps-reg-ap-pin"
  425. appin = "12345670"
  426. hostapd.add_ap(apdev[0]['ifname'],
  427. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  428. "wpa_passphrase": "12345678", "wpa": "2",
  429. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  430. "ap_pin": appin})
  431. logger.info("WPS provisioning step")
  432. dev[0].dump_monitor()
  433. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  434. dev[0].wps_reg(apdev[0]['bssid'], appin)
  435. status = dev[0].get_status()
  436. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  437. raise Exception("Not fully connected")
  438. if status['ssid'] != ssid:
  439. raise Exception("Unexpected SSID")
  440. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  441. raise Exception("Unexpected encryption configuration")
  442. if status['key_mgmt'] != 'WPA2-PSK':
  443. raise Exception("Unexpected key_mgmt")
  444. def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
  445. """WPS registrar using AP PIN to connect (WPA+WPA2)"""
  446. ssid = "test-wps-reg-ap-pin"
  447. appin = "12345670"
  448. hostapd.add_ap(apdev[0]['ifname'],
  449. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  450. "wpa_passphrase": "12345678", "wpa": "3",
  451. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  452. "wpa_pairwise": "TKIP", "ap_pin": appin})
  453. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  454. dev[0].wps_reg(apdev[0]['bssid'], appin)
  455. status = dev[0].get_status()
  456. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  457. raise Exception("Not fully connected")
  458. if status['ssid'] != ssid:
  459. raise Exception("Unexpected SSID")
  460. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
  461. raise Exception("Unexpected encryption configuration")
  462. if status['key_mgmt'] != 'WPA2-PSK':
  463. raise Exception("Unexpected key_mgmt")
  464. def check_wps_reg_failure(dev, ap, appin):
  465. dev.request("WPS_REG " + ap['bssid'] + " " + appin)
  466. ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
  467. if ev is None:
  468. raise Exception("WPS operation timed out")
  469. if "WPS-SUCCESS" in ev:
  470. raise Exception("WPS operation succeeded unexpectedly")
  471. if "config_error=15" not in ev:
  472. raise Exception("WPS setup locked state was not reported correctly")
  473. def test_ap_wps_random_ap_pin(dev, apdev):
  474. """WPS registrar using random AP PIN"""
  475. ssid = "test-wps-reg-random-ap-pin"
  476. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  477. hostapd.add_ap(apdev[0]['ifname'],
  478. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  479. "wpa_passphrase": "12345678", "wpa": "2",
  480. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  481. "device_name": "Wireless AP", "manufacturer": "Company",
  482. "model_name": "WAP", "model_number": "123",
  483. "serial_number": "12345", "device_type": "6-0050F204-1",
  484. "os_version": "01020300",
  485. "config_methods": "label push_button",
  486. "uuid": ap_uuid, "upnp_iface": "lo" })
  487. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  488. appin = hapd.request("WPS_AP_PIN random")
  489. if "FAIL" in appin:
  490. raise Exception("Could not generate random AP PIN")
  491. if appin not in hapd.request("WPS_AP_PIN get"):
  492. raise Exception("Could not fetch current AP PIN")
  493. logger.info("WPS provisioning step")
  494. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  495. dev[0].wps_reg(apdev[0]['bssid'], appin)
  496. hapd.request("WPS_AP_PIN disable")
  497. logger.info("WPS provisioning step with AP PIN disabled")
  498. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  499. check_wps_reg_failure(dev[1], apdev[0], appin)
  500. logger.info("WPS provisioning step with AP PIN reset")
  501. appin = "12345670"
  502. hapd.request("WPS_AP_PIN set " + appin)
  503. dev[1].wps_reg(apdev[0]['bssid'], appin)
  504. dev[0].request("REMOVE_NETWORK all")
  505. dev[1].request("REMOVE_NETWORK all")
  506. dev[0].wait_disconnected(timeout=10)
  507. dev[1].wait_disconnected(timeout=10)
  508. logger.info("WPS provisioning step after AP PIN timeout")
  509. hapd.request("WPS_AP_PIN disable")
  510. appin = hapd.request("WPS_AP_PIN random 1")
  511. time.sleep(1.1)
  512. if "FAIL" not in hapd.request("WPS_AP_PIN get"):
  513. raise Exception("AP PIN unexpectedly still enabled")
  514. check_wps_reg_failure(dev[0], apdev[0], appin)
  515. logger.info("WPS provisioning step after AP PIN timeout(2)")
  516. hapd.request("WPS_AP_PIN disable")
  517. appin = "12345670"
  518. hapd.request("WPS_AP_PIN set " + appin + " 1")
  519. time.sleep(1.1)
  520. if "FAIL" not in hapd.request("WPS_AP_PIN get"):
  521. raise Exception("AP PIN unexpectedly still enabled")
  522. check_wps_reg_failure(dev[1], apdev[0], appin)
  523. with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
  524. if "FAIL" in hapd.request("WPS_AP_PIN random 1"):
  525. raise Exception("Failed to generate PIN during OOM")
  526. hapd.request("WPS_AP_PIN disable")
  527. with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
  528. hapd.request("WPS_AP_PIN set 12345670")
  529. hapd.request("WPS_AP_PIN disable")
  530. def test_ap_wps_reg_config(dev, apdev):
  531. """WPS registrar configuring an AP using AP PIN"""
  532. ssid = "test-wps-init-ap-pin"
  533. appin = "12345670"
  534. hostapd.add_ap(apdev[0]['ifname'],
  535. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  536. "ap_pin": appin})
  537. logger.info("WPS configuration step")
  538. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  539. dev[0].dump_monitor()
  540. new_ssid = "wps-new-ssid"
  541. new_passphrase = "1234567890"
  542. dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
  543. new_passphrase)
  544. status = dev[0].get_status()
  545. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  546. raise Exception("Not fully connected")
  547. if status['ssid'] != new_ssid:
  548. raise Exception("Unexpected SSID")
  549. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  550. raise Exception("Unexpected encryption configuration")
  551. if status['key_mgmt'] != 'WPA2-PSK':
  552. raise Exception("Unexpected key_mgmt")
  553. logger.info("Re-configure back to open")
  554. dev[0].request("REMOVE_NETWORK all")
  555. dev[0].flush_scan_cache()
  556. dev[0].dump_monitor()
  557. dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
  558. status = dev[0].get_status()
  559. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  560. raise Exception("Not fully connected")
  561. if status['ssid'] != "wps-open":
  562. raise Exception("Unexpected SSID")
  563. if status['key_mgmt'] != 'NONE':
  564. raise Exception("Unexpected key_mgmt")
  565. def test_ap_wps_reg_config_ext_processing(dev, apdev):
  566. """WPS registrar configuring an AP with external config processing"""
  567. ssid = "test-wps-init-ap-pin"
  568. appin = "12345670"
  569. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  570. "wps_cred_processing": "1", "ap_pin": appin}
  571. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  572. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  573. new_ssid = "wps-new-ssid"
  574. new_passphrase = "1234567890"
  575. dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
  576. new_passphrase, no_wait=True)
  577. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  578. if ev is None:
  579. raise Exception("WPS registrar operation timed out")
  580. ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
  581. if ev is None:
  582. raise Exception("WPS configuration timed out")
  583. if "1026" not in ev:
  584. raise Exception("AP Settings missing from event")
  585. hapd.request("SET wps_cred_processing 0")
  586. if "FAIL" in hapd.request("WPS_CONFIG " + new_ssid.encode("hex") + " WPA2PSK CCMP " + new_passphrase.encode("hex")):
  587. raise Exception("WPS_CONFIG command failed")
  588. dev[0].wait_connected(timeout=15)
  589. def test_ap_wps_reg_config_tkip(dev, apdev):
  590. """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
  591. skip_with_fips(dev[0])
  592. ssid = "test-wps-init-ap"
  593. appin = "12345670"
  594. hostapd.add_ap(apdev[0]['ifname'],
  595. { "ssid": ssid, "eap_server": "1", "wps_state": "1",
  596. "ap_pin": appin})
  597. logger.info("WPS configuration step")
  598. dev[0].request("SET wps_version_number 0x10")
  599. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  600. dev[0].dump_monitor()
  601. new_ssid = "wps-new-ssid-with-tkip"
  602. new_passphrase = "1234567890"
  603. dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
  604. new_passphrase)
  605. logger.info("Re-connect to verify WPA2 mixed mode")
  606. dev[0].request("DISCONNECT")
  607. id = 0
  608. dev[0].set_network(id, "pairwise", "CCMP")
  609. dev[0].set_network(id, "proto", "RSN")
  610. dev[0].connect_network(id)
  611. status = dev[0].get_status()
  612. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  613. raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
  614. if status['ssid'] != new_ssid:
  615. raise Exception("Unexpected SSID")
  616. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
  617. raise Exception("Unexpected encryption configuration")
  618. if status['key_mgmt'] != 'WPA2-PSK':
  619. raise Exception("Unexpected key_mgmt")
  620. def test_ap_wps_setup_locked(dev, apdev):
  621. """WPS registrar locking up AP setup on AP PIN failures"""
  622. ssid = "test-wps-incorrect-ap-pin"
  623. appin = "12345670"
  624. hostapd.add_ap(apdev[0]['ifname'],
  625. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  626. "wpa_passphrase": "12345678", "wpa": "2",
  627. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  628. "ap_pin": appin})
  629. new_ssid = "wps-new-ssid-test"
  630. new_passphrase = "1234567890"
  631. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  632. ap_setup_locked=False
  633. for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
  634. dev[0].dump_monitor()
  635. logger.info("Try incorrect AP PIN - attempt " + pin)
  636. dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
  637. "CCMP", new_passphrase, no_wait=True)
  638. ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
  639. if ev is None:
  640. raise Exception("Timeout on receiving WPS operation failure event")
  641. if "CTRL-EVENT-CONNECTED" in ev:
  642. raise Exception("Unexpected connection")
  643. if "config_error=15" in ev:
  644. logger.info("AP Setup Locked")
  645. ap_setup_locked=True
  646. elif "config_error=18" not in ev:
  647. raise Exception("config_error=18 not reported")
  648. dev[0].wait_disconnected(timeout=10)
  649. time.sleep(0.1)
  650. if not ap_setup_locked:
  651. raise Exception("AP setup was not locked")
  652. dev[0].request("WPS_CANCEL")
  653. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True,
  654. only_new=True)
  655. bss = dev[0].get_bss(apdev[0]['bssid'])
  656. if 'wps_ap_setup_locked' not in bss or bss['wps_ap_setup_locked'] != '1':
  657. logger.info("BSS: " + str(bss))
  658. raise Exception("AP Setup Locked not indicated in scan results")
  659. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  660. status = hapd.request("WPS_GET_STATUS")
  661. if "Last WPS result: Failed" not in status:
  662. raise Exception("WPS failure result not shown correctly")
  663. if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
  664. raise Exception("Peer address not shown correctly")
  665. time.sleep(0.5)
  666. dev[0].dump_monitor()
  667. logger.info("WPS provisioning step")
  668. pin = dev[0].wps_read_pin()
  669. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  670. hapd.request("WPS_PIN any " + pin)
  671. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  672. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
  673. if ev is None:
  674. raise Exception("WPS success was not reported")
  675. dev[0].wait_connected(timeout=30)
  676. appin = hapd.request("WPS_AP_PIN random")
  677. if "FAIL" in appin:
  678. raise Exception("Could not generate random AP PIN")
  679. ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
  680. if ev is None:
  681. raise Exception("Failed to unlock AP PIN")
  682. def test_ap_wps_setup_locked_timeout(dev, apdev):
  683. """WPS re-enabling AP PIN after timeout"""
  684. ssid = "test-wps-incorrect-ap-pin"
  685. appin = "12345670"
  686. hostapd.add_ap(apdev[0]['ifname'],
  687. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  688. "wpa_passphrase": "12345678", "wpa": "2",
  689. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  690. "ap_pin": appin})
  691. new_ssid = "wps-new-ssid-test"
  692. new_passphrase = "1234567890"
  693. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  694. ap_setup_locked=False
  695. for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
  696. dev[0].dump_monitor()
  697. logger.info("Try incorrect AP PIN - attempt " + pin)
  698. dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
  699. "CCMP", new_passphrase, no_wait=True)
  700. ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
  701. if ev is None:
  702. raise Exception("Timeout on receiving WPS operation failure event")
  703. if "CTRL-EVENT-CONNECTED" in ev:
  704. raise Exception("Unexpected connection")
  705. if "config_error=15" in ev:
  706. logger.info("AP Setup Locked")
  707. ap_setup_locked=True
  708. break
  709. elif "config_error=18" not in ev:
  710. raise Exception("config_error=18 not reported")
  711. dev[0].wait_disconnected(timeout=10)
  712. time.sleep(0.1)
  713. if not ap_setup_locked:
  714. raise Exception("AP setup was not locked")
  715. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  716. ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
  717. if ev is None:
  718. raise Exception("AP PIN did not get unlocked on 60 second timeout")
  719. def test_ap_wps_pbc_overlap_2ap(dev, apdev):
  720. """WPS PBC session overlap with two active APs"""
  721. hostapd.add_ap(apdev[0]['ifname'],
  722. { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
  723. "wpa_passphrase": "12345678", "wpa": "2",
  724. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  725. "wps_independent": "1"})
  726. hostapd.add_ap(apdev[1]['ifname'],
  727. { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
  728. "wpa_passphrase": "123456789", "wpa": "2",
  729. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  730. "wps_independent": "1"})
  731. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  732. hapd.request("WPS_PBC")
  733. hapd2 = hostapd.Hostapd(apdev[1]['ifname'])
  734. hapd2.request("WPS_PBC")
  735. logger.info("WPS provisioning step")
  736. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
  737. dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
  738. dev[0].request("WPS_PBC")
  739. ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
  740. if ev is None:
  741. raise Exception("PBC session overlap not detected")
  742. hapd.request("DISABLE")
  743. hapd2.request("DISABLE")
  744. dev[0].flush_scan_cache()
  745. def test_ap_wps_pbc_overlap_2sta(dev, apdev):
  746. """WPS PBC session overlap with two active STAs"""
  747. ssid = "test-wps-pbc-overlap"
  748. hostapd.add_ap(apdev[0]['ifname'],
  749. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  750. "wpa_passphrase": "12345678", "wpa": "2",
  751. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  752. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  753. logger.info("WPS provisioning step")
  754. hapd.request("WPS_PBC")
  755. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  756. dev[0].dump_monitor()
  757. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
  758. dev[1].dump_monitor()
  759. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  760. dev[1].request("WPS_PBC " + apdev[0]['bssid'])
  761. ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
  762. if ev is None:
  763. raise Exception("PBC session overlap not detected (dev0)")
  764. if "config_error=12" not in ev:
  765. raise Exception("PBC session overlap not correctly reported (dev0)")
  766. dev[0].request("WPS_CANCEL")
  767. dev[0].request("DISCONNECT")
  768. ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
  769. if ev is None:
  770. raise Exception("PBC session overlap not detected (dev1)")
  771. if "config_error=12" not in ev:
  772. raise Exception("PBC session overlap not correctly reported (dev1)")
  773. dev[1].request("WPS_CANCEL")
  774. dev[1].request("DISCONNECT")
  775. hapd.request("WPS_CANCEL")
  776. ret = hapd.request("WPS_PBC")
  777. if "FAIL" not in ret:
  778. raise Exception("PBC mode allowed to be started while PBC overlap still active")
  779. hapd.request("DISABLE")
  780. dev[0].flush_scan_cache()
  781. dev[1].flush_scan_cache()
  782. def test_ap_wps_cancel(dev, apdev):
  783. """WPS AP cancelling enabled config method"""
  784. ssid = "test-wps-ap-cancel"
  785. hostapd.add_ap(apdev[0]['ifname'],
  786. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  787. "wpa_passphrase": "12345678", "wpa": "2",
  788. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
  789. bssid = apdev[0]['bssid']
  790. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  791. logger.info("Verify PBC enable/cancel")
  792. hapd.request("WPS_PBC")
  793. dev[0].scan(freq="2412")
  794. dev[0].scan(freq="2412")
  795. bss = dev[0].get_bss(apdev[0]['bssid'])
  796. if "[WPS-PBC]" not in bss['flags']:
  797. raise Exception("WPS-PBC flag missing")
  798. if "FAIL" in hapd.request("WPS_CANCEL"):
  799. raise Exception("WPS_CANCEL failed")
  800. dev[0].scan(freq="2412")
  801. dev[0].scan(freq="2412")
  802. bss = dev[0].get_bss(apdev[0]['bssid'])
  803. if "[WPS-PBC]" in bss['flags']:
  804. raise Exception("WPS-PBC flag not cleared")
  805. logger.info("Verify PIN enable/cancel")
  806. hapd.request("WPS_PIN any 12345670")
  807. dev[0].scan(freq="2412")
  808. dev[0].scan(freq="2412")
  809. bss = dev[0].get_bss(apdev[0]['bssid'])
  810. if "[WPS-AUTH]" not in bss['flags']:
  811. raise Exception("WPS-AUTH flag missing")
  812. if "FAIL" in hapd.request("WPS_CANCEL"):
  813. raise Exception("WPS_CANCEL failed")
  814. dev[0].scan(freq="2412")
  815. dev[0].scan(freq="2412")
  816. bss = dev[0].get_bss(apdev[0]['bssid'])
  817. if "[WPS-AUTH]" in bss['flags']:
  818. raise Exception("WPS-AUTH flag not cleared")
  819. def test_ap_wps_er_add_enrollee(dev, apdev):
  820. """WPS ER configuring AP and adding a new enrollee using PIN"""
  821. try:
  822. _test_ap_wps_er_add_enrollee(dev, apdev)
  823. finally:
  824. dev[0].request("WPS_ER_STOP")
  825. def _test_ap_wps_er_add_enrollee(dev, apdev):
  826. ssid = "wps-er-add-enrollee"
  827. ap_pin = "12345670"
  828. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  829. hostapd.add_ap(apdev[0]['ifname'],
  830. { "ssid": ssid, "eap_server": "1", "wps_state": "1",
  831. "device_name": "Wireless AP", "manufacturer": "Company",
  832. "model_name": "WAP", "model_number": "123",
  833. "serial_number": "12345", "device_type": "6-0050F204-1",
  834. "os_version": "01020300",
  835. 'friendly_name': "WPS AP - <>&'\" - TEST",
  836. "config_methods": "label push_button",
  837. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  838. logger.info("WPS configuration step")
  839. new_passphrase = "1234567890"
  840. dev[0].dump_monitor()
  841. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  842. dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
  843. new_passphrase)
  844. status = dev[0].get_status()
  845. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  846. raise Exception("Not fully connected")
  847. if status['ssid'] != ssid:
  848. raise Exception("Unexpected SSID")
  849. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  850. raise Exception("Unexpected encryption configuration")
  851. if status['key_mgmt'] != 'WPA2-PSK':
  852. raise Exception("Unexpected key_mgmt")
  853. logger.info("Start ER")
  854. dev[0].request("WPS_ER_START ifname=lo")
  855. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  856. if ev is None:
  857. raise Exception("AP discovery timed out")
  858. if ap_uuid not in ev:
  859. raise Exception("Expected AP UUID not found")
  860. if "|WPS AP - &lt;&gt;&amp;&apos;&quot; - TEST|Company|" not in ev:
  861. raise Exception("Expected friendly name not found")
  862. logger.info("Learn AP configuration through UPnP")
  863. dev[0].dump_monitor()
  864. dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
  865. ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
  866. if ev is None:
  867. raise Exception("AP learn timed out")
  868. if ap_uuid not in ev:
  869. raise Exception("Expected AP UUID not in settings")
  870. if "ssid=" + ssid not in ev:
  871. raise Exception("Expected SSID not in settings")
  872. if "key=" + new_passphrase not in ev:
  873. raise Exception("Expected passphrase not in settings")
  874. ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
  875. if ev is None:
  876. raise Exception("WPS-FAIL after AP learn timed out")
  877. time.sleep(0.1)
  878. logger.info("Add Enrollee using ER")
  879. pin = dev[1].wps_read_pin()
  880. dev[0].dump_monitor()
  881. dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
  882. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  883. dev[1].dump_monitor()
  884. dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  885. ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
  886. if ev is None:
  887. raise Exception("Enrollee did not report success")
  888. dev[1].wait_connected(timeout=15)
  889. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  890. if ev is None:
  891. raise Exception("WPS ER did not report success")
  892. hwsim_utils.test_connectivity_sta(dev[0], dev[1])
  893. logger.info("Add a specific Enrollee using ER")
  894. pin = dev[2].wps_read_pin()
  895. addr2 = dev[2].p2p_interface_addr()
  896. dev[0].dump_monitor()
  897. dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
  898. dev[2].dump_monitor()
  899. dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  900. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
  901. if ev is None:
  902. raise Exception("Enrollee not seen")
  903. if addr2 not in ev:
  904. raise Exception("Unexpected Enrollee MAC address")
  905. dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
  906. dev[2].wait_connected(timeout=30)
  907. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  908. if ev is None:
  909. raise Exception("WPS ER did not report success")
  910. logger.info("Verify registrar selection behavior")
  911. dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
  912. dev[1].request("DISCONNECT")
  913. dev[1].wait_disconnected(timeout=10)
  914. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
  915. dev[1].scan(freq="2412")
  916. bss = dev[1].get_bss(apdev[0]['bssid'])
  917. if "[WPS-AUTH]" not in bss['flags']:
  918. # It is possible for scan to miss an update especially when running
  919. # tests under load with multiple VMs, so allow another attempt.
  920. dev[1].scan(freq="2412")
  921. bss = dev[1].get_bss(apdev[0]['bssid'])
  922. if "[WPS-AUTH]" not in bss['flags']:
  923. raise Exception("WPS-AUTH flag missing")
  924. logger.info("Stop ER")
  925. dev[0].dump_monitor()
  926. dev[0].request("WPS_ER_STOP")
  927. ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
  928. if ev is None:
  929. raise Exception("WPS ER unsubscription timed out")
  930. # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
  931. # a bit before verifying that the scan results have changed.
  932. time.sleep(0.2)
  933. for i in range(0, 10):
  934. dev[1].request("BSS_FLUSH 0")
  935. dev[1].scan(freq="2412", only_new=True)
  936. bss = dev[1].get_bss(apdev[0]['bssid'])
  937. if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
  938. break
  939. logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
  940. time.sleep(0.1)
  941. if "[WPS-AUTH]" in bss['flags']:
  942. raise Exception("WPS-AUTH flag not removed")
  943. def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
  944. """WPS ER adding a new enrollee identified by UUID"""
  945. try:
  946. _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
  947. finally:
  948. dev[0].request("WPS_ER_STOP")
  949. def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
  950. ssid = "wps-er-add-enrollee"
  951. ap_pin = "12345670"
  952. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  953. hostapd.add_ap(apdev[0]['ifname'],
  954. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  955. "wpa_passphrase": "12345678", "wpa": "2",
  956. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  957. "device_name": "Wireless AP", "manufacturer": "Company",
  958. "model_name": "WAP", "model_number": "123",
  959. "serial_number": "12345", "device_type": "6-0050F204-1",
  960. "os_version": "01020300",
  961. "config_methods": "label push_button",
  962. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  963. logger.info("WPS configuration step")
  964. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  965. dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
  966. logger.info("Start ER")
  967. dev[0].request("WPS_ER_START ifname=lo")
  968. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  969. if ev is None:
  970. raise Exception("AP discovery timed out")
  971. if ap_uuid not in ev:
  972. raise Exception("Expected AP UUID not found")
  973. logger.info("Learn AP configuration through UPnP")
  974. dev[0].dump_monitor()
  975. dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
  976. ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
  977. if ev is None:
  978. raise Exception("AP learn timed out")
  979. if ap_uuid not in ev:
  980. raise Exception("Expected AP UUID not in settings")
  981. ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
  982. if ev is None:
  983. raise Exception("WPS-FAIL after AP learn timed out")
  984. time.sleep(0.1)
  985. logger.info("Add a specific Enrollee using ER (PBC/UUID)")
  986. addr1 = dev[1].p2p_interface_addr()
  987. dev[0].dump_monitor()
  988. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  989. dev[1].dump_monitor()
  990. dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
  991. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
  992. if ev is None:
  993. raise Exception("Enrollee not seen")
  994. if addr1 not in ev:
  995. raise Exception("Unexpected Enrollee MAC address")
  996. uuid = ev.split(' ')[1]
  997. dev[0].request("WPS_ER_PBC " + uuid)
  998. dev[1].wait_connected(timeout=30)
  999. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  1000. if ev is None:
  1001. raise Exception("WPS ER did not report success")
  1002. logger.info("Add a specific Enrollee using ER (PIN/UUID)")
  1003. pin = dev[2].wps_read_pin()
  1004. addr2 = dev[2].p2p_interface_addr()
  1005. dev[0].dump_monitor()
  1006. dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1007. dev[2].dump_monitor()
  1008. dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  1009. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
  1010. if ev is None:
  1011. raise Exception("Enrollee not seen")
  1012. if addr2 not in ev:
  1013. raise Exception("Unexpected Enrollee MAC address")
  1014. uuid = ev.split(' ')[1]
  1015. dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
  1016. dev[2].wait_connected(timeout=30)
  1017. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  1018. if ev is None:
  1019. raise Exception("WPS ER did not report success")
  1020. logger.info("Stop ER")
  1021. dev[0].dump_monitor()
  1022. dev[0].request("WPS_ER_STOP")
  1023. def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
  1024. """WPS ER connected to AP and adding a new enrollee using PBC"""
  1025. try:
  1026. _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
  1027. finally:
  1028. dev[0].request("WPS_ER_STOP")
  1029. def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
  1030. ssid = "wps-er-add-enrollee-pbc"
  1031. ap_pin = "12345670"
  1032. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1033. hostapd.add_ap(apdev[0]['ifname'],
  1034. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1035. "wpa_passphrase": "12345678", "wpa": "2",
  1036. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1037. "device_name": "Wireless AP", "manufacturer": "Company",
  1038. "model_name": "WAP", "model_number": "123",
  1039. "serial_number": "12345", "device_type": "6-0050F204-1",
  1040. "os_version": "01020300",
  1041. "config_methods": "label push_button",
  1042. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  1043. logger.info("Learn AP configuration")
  1044. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1045. dev[0].dump_monitor()
  1046. dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
  1047. status = dev[0].get_status()
  1048. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  1049. raise Exception("Not fully connected")
  1050. logger.info("Start ER")
  1051. dev[0].request("WPS_ER_START ifname=lo")
  1052. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  1053. if ev is None:
  1054. raise Exception("AP discovery timed out")
  1055. if ap_uuid not in ev:
  1056. raise Exception("Expected AP UUID not found")
  1057. enrollee = dev[1].p2p_interface_addr()
  1058. if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
  1059. raise Exception("Unknown UUID not reported")
  1060. logger.info("Add Enrollee using ER and PBC")
  1061. dev[0].dump_monitor()
  1062. dev[1].dump_monitor()
  1063. dev[1].request("WPS_PBC")
  1064. for i in range(0, 2):
  1065. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
  1066. if ev is None:
  1067. raise Exception("Enrollee discovery timed out")
  1068. if enrollee in ev:
  1069. break
  1070. if i == 1:
  1071. raise Exception("Expected Enrollee not found")
  1072. if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
  1073. raise Exception("Unknown UUID not reported")
  1074. logger.info("Use learned network configuration on ER")
  1075. dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
  1076. if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
  1077. raise Exception("WPS_ER_PBC failed")
  1078. ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
  1079. if ev is None:
  1080. raise Exception("Enrollee did not report success")
  1081. dev[1].wait_connected(timeout=15)
  1082. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  1083. if ev is None:
  1084. raise Exception("WPS ER did not report success")
  1085. hwsim_utils.test_connectivity_sta(dev[0], dev[1])
  1086. def test_ap_wps_er_pbc_overlap(dev, apdev):
  1087. """WPS ER connected to AP and PBC session overlap"""
  1088. try:
  1089. _test_ap_wps_er_pbc_overlap(dev, apdev)
  1090. finally:
  1091. dev[0].request("WPS_ER_STOP")
  1092. def _test_ap_wps_er_pbc_overlap(dev, apdev):
  1093. ssid = "wps-er-add-enrollee-pbc"
  1094. ap_pin = "12345670"
  1095. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1096. hostapd.add_ap(apdev[0]['ifname'],
  1097. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1098. "wpa_passphrase": "12345678", "wpa": "2",
  1099. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1100. "device_name": "Wireless AP", "manufacturer": "Company",
  1101. "model_name": "WAP", "model_number": "123",
  1102. "serial_number": "12345", "device_type": "6-0050F204-1",
  1103. "os_version": "01020300",
  1104. "config_methods": "label push_button",
  1105. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  1106. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1107. dev[0].dump_monitor()
  1108. dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
  1109. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1110. dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1111. # avoid leaving dev 1 or 2 as the last Probe Request to the AP
  1112. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
  1113. dev[0].dump_monitor()
  1114. dev[0].request("WPS_ER_START ifname=lo")
  1115. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  1116. if ev is None:
  1117. raise Exception("AP discovery timed out")
  1118. if ap_uuid not in ev:
  1119. raise Exception("Expected AP UUID not found")
  1120. # verify BSSID selection of the AP instead of UUID
  1121. if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
  1122. raise Exception("Could not select AP based on BSSID")
  1123. dev[0].dump_monitor()
  1124. dev[1].request("WPS_PBC " + apdev[0]['bssid'])
  1125. dev[2].request("WPS_PBC " + apdev[0]['bssid'])
  1126. ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
  1127. if ev is None:
  1128. raise Exception("PBC scan failed")
  1129. ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
  1130. if ev is None:
  1131. raise Exception("PBC scan failed")
  1132. found1 = False
  1133. found2 = False
  1134. addr1 = dev[1].own_addr()
  1135. addr2 = dev[2].own_addr()
  1136. for i in range(3):
  1137. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
  1138. if ev is None:
  1139. raise Exception("Enrollee discovery timed out")
  1140. if addr1 in ev:
  1141. found1 = True
  1142. if found2:
  1143. break
  1144. if addr2 in ev:
  1145. found2 = True
  1146. if found1:
  1147. break
  1148. if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
  1149. raise Exception("PBC overlap not reported")
  1150. dev[1].request("WPS_CANCEL")
  1151. dev[2].request("WPS_CANCEL")
  1152. if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
  1153. raise Exception("Invalid WPS_ER_PBC accepted")
  1154. def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
  1155. """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
  1156. try:
  1157. _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
  1158. finally:
  1159. dev[0].request("WPS_ER_STOP")
  1160. def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
  1161. ssid = "wps-er-add-enrollee-pbc"
  1162. ap_pin = "12345670"
  1163. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1164. hostapd.add_ap(apdev[0]['ifname'],
  1165. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1166. "wpa_passphrase": "12345678", "wpa": "2",
  1167. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1168. "device_name": "Wireless AP", "manufacturer": "Company",
  1169. "model_name": "WAP", "model_number": "123",
  1170. "serial_number": "12345", "device_type": "6-0050F204-1",
  1171. "os_version": "01020300",
  1172. "config_methods": "label push_button",
  1173. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  1174. logger.info("Learn AP configuration")
  1175. dev[0].request("SET wps_version_number 0x10")
  1176. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1177. dev[0].dump_monitor()
  1178. dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
  1179. status = dev[0].get_status()
  1180. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  1181. raise Exception("Not fully connected")
  1182. logger.info("Start ER")
  1183. dev[0].request("WPS_ER_START ifname=lo")
  1184. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  1185. if ev is None:
  1186. raise Exception("AP discovery timed out")
  1187. if ap_uuid not in ev:
  1188. raise Exception("Expected AP UUID not found")
  1189. logger.info("Use learned network configuration on ER")
  1190. dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
  1191. logger.info("Add Enrollee using ER and PIN")
  1192. enrollee = dev[1].p2p_interface_addr()
  1193. pin = dev[1].wps_read_pin()
  1194. dev[0].dump_monitor()
  1195. dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
  1196. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1197. dev[1].dump_monitor()
  1198. dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  1199. dev[1].wait_connected(timeout=30)
  1200. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  1201. if ev is None:
  1202. raise Exception("WPS ER did not report success")
  1203. def test_ap_wps_er_config_ap(dev, apdev):
  1204. """WPS ER configuring AP over UPnP"""
  1205. try:
  1206. _test_ap_wps_er_config_ap(dev, apdev)
  1207. finally:
  1208. dev[0].request("WPS_ER_STOP")
  1209. def _test_ap_wps_er_config_ap(dev, apdev):
  1210. ssid = "wps-er-ap-config"
  1211. ap_pin = "12345670"
  1212. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1213. hostapd.add_ap(apdev[0]['ifname'],
  1214. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1215. "wpa_passphrase": "12345678", "wpa": "2",
  1216. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1217. "device_name": "Wireless AP", "manufacturer": "Company",
  1218. "model_name": "WAP", "model_number": "123",
  1219. "serial_number": "12345", "device_type": "6-0050F204-1",
  1220. "os_version": "01020300",
  1221. "config_methods": "label push_button",
  1222. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  1223. logger.info("Connect ER to the AP")
  1224. dev[0].connect(ssid, psk="12345678", scan_freq="2412")
  1225. logger.info("WPS configuration step")
  1226. dev[0].request("WPS_ER_START ifname=lo")
  1227. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  1228. if ev is None:
  1229. raise Exception("AP discovery timed out")
  1230. if ap_uuid not in ev:
  1231. raise Exception("Expected AP UUID not found")
  1232. new_passphrase = "1234567890"
  1233. dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
  1234. ssid.encode("hex") + " WPA2PSK CCMP " +
  1235. new_passphrase.encode("hex"))
  1236. ev = dev[0].wait_event(["WPS-SUCCESS"])
  1237. if ev is None:
  1238. raise Exception("WPS ER configuration operation timed out")
  1239. dev[0].wait_disconnected(timeout=10)
  1240. dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
  1241. logger.info("WPS ER restart")
  1242. dev[0].request("WPS_ER_START")
  1243. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  1244. if ev is None:
  1245. raise Exception("AP discovery timed out on ER restart")
  1246. if ap_uuid not in ev:
  1247. raise Exception("Expected AP UUID not found on ER restart")
  1248. if "OK" not in dev[0].request("WPS_ER_STOP"):
  1249. raise Exception("WPS_ER_STOP failed")
  1250. if "OK" not in dev[0].request("WPS_ER_STOP"):
  1251. raise Exception("WPS_ER_STOP failed")
  1252. def test_ap_wps_er_cache_ap_settings(dev, apdev):
  1253. """WPS ER caching AP settings"""
  1254. try:
  1255. _test_ap_wps_er_cache_ap_settings(dev, apdev)
  1256. finally:
  1257. dev[0].request("WPS_ER_STOP")
  1258. def _test_ap_wps_er_cache_ap_settings(dev, apdev):
  1259. ssid = "wps-er-add-enrollee"
  1260. ap_pin = "12345670"
  1261. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1262. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1263. "wpa_passphrase": "12345678", "wpa": "2",
  1264. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1265. "device_name": "Wireless AP", "manufacturer": "Company",
  1266. "model_name": "WAP", "model_number": "123",
  1267. "serial_number": "12345", "device_type": "6-0050F204-1",
  1268. "os_version": "01020300",
  1269. "config_methods": "label push_button",
  1270. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
  1271. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  1272. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1273. dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
  1274. id = int(dev[0].list_networks()[0]['id'])
  1275. dev[0].set_network(id, "scan_freq", "2412")
  1276. dev[0].request("WPS_ER_START ifname=lo")
  1277. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  1278. if ev is None:
  1279. raise Exception("AP discovery timed out")
  1280. if ap_uuid not in ev:
  1281. raise Exception("Expected AP UUID not found")
  1282. dev[0].dump_monitor()
  1283. dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
  1284. ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
  1285. if ev is None:
  1286. raise Exception("AP learn timed out")
  1287. ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
  1288. if ev is None:
  1289. raise Exception("WPS-FAIL after AP learn timed out")
  1290. time.sleep(0.1)
  1291. hapd.disable()
  1292. for i in range(2):
  1293. ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
  1294. "CTRL-EVENT-DISCONNECTED" ],
  1295. timeout=15)
  1296. if ev is None:
  1297. raise Exception("AP removal or disconnection timed out")
  1298. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  1299. for i in range(2):
  1300. ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
  1301. timeout=15)
  1302. if ev is None:
  1303. raise Exception("AP discovery or connection timed out")
  1304. pin = dev[1].wps_read_pin()
  1305. dev[0].dump_monitor()
  1306. dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
  1307. time.sleep(0.2)
  1308. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1309. dev[1].dump_monitor()
  1310. dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  1311. ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
  1312. if ev is None:
  1313. raise Exception("Enrollee did not report success")
  1314. dev[1].wait_connected(timeout=15)
  1315. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  1316. if ev is None:
  1317. raise Exception("WPS ER did not report success")
  1318. dev[0].dump_monitor()
  1319. dev[0].request("WPS_ER_STOP")
  1320. def test_ap_wps_fragmentation(dev, apdev):
  1321. """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
  1322. ssid = "test-wps-fragmentation"
  1323. appin = "12345670"
  1324. hostapd.add_ap(apdev[0]['ifname'],
  1325. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1326. "wpa_passphrase": "12345678", "wpa": "3",
  1327. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1328. "wpa_pairwise": "TKIP", "ap_pin": appin,
  1329. "fragment_size": "50" })
  1330. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1331. logger.info("WPS provisioning step (PBC)")
  1332. hapd.request("WPS_PBC")
  1333. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1334. dev[0].dump_monitor()
  1335. dev[0].request("SET wps_fragment_size 50")
  1336. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1337. dev[0].wait_connected(timeout=30)
  1338. status = dev[0].get_status()
  1339. if status['wpa_state'] != 'COMPLETED':
  1340. raise Exception("Not fully connected")
  1341. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
  1342. raise Exception("Unexpected encryption configuration")
  1343. if status['key_mgmt'] != 'WPA2-PSK':
  1344. raise Exception("Unexpected key_mgmt")
  1345. logger.info("WPS provisioning step (PIN)")
  1346. pin = dev[1].wps_read_pin()
  1347. hapd.request("WPS_PIN any " + pin)
  1348. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1349. dev[1].request("SET wps_fragment_size 50")
  1350. dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  1351. dev[1].wait_connected(timeout=30)
  1352. status = dev[1].get_status()
  1353. if status['wpa_state'] != 'COMPLETED':
  1354. raise Exception("Not fully connected")
  1355. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
  1356. raise Exception("Unexpected encryption configuration")
  1357. if status['key_mgmt'] != 'WPA2-PSK':
  1358. raise Exception("Unexpected key_mgmt")
  1359. logger.info("WPS connection as registrar")
  1360. dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1361. dev[2].request("SET wps_fragment_size 50")
  1362. dev[2].wps_reg(apdev[0]['bssid'], appin)
  1363. status = dev[2].get_status()
  1364. if status['wpa_state'] != 'COMPLETED':
  1365. raise Exception("Not fully connected")
  1366. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
  1367. raise Exception("Unexpected encryption configuration")
  1368. if status['key_mgmt'] != 'WPA2-PSK':
  1369. raise Exception("Unexpected key_mgmt")
  1370. def test_ap_wps_new_version_sta(dev, apdev):
  1371. """WPS compatibility with new version number on the station"""
  1372. ssid = "test-wps-ver"
  1373. hostapd.add_ap(apdev[0]['ifname'],
  1374. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1375. "wpa_passphrase": "12345678", "wpa": "2",
  1376. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
  1377. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1378. logger.info("WPS provisioning step")
  1379. hapd.request("WPS_PBC")
  1380. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1381. dev[0].dump_monitor()
  1382. dev[0].request("SET wps_version_number 0x43")
  1383. dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
  1384. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1385. dev[0].wait_connected(timeout=30)
  1386. def test_ap_wps_new_version_ap(dev, apdev):
  1387. """WPS compatibility with new version number on the AP"""
  1388. ssid = "test-wps-ver"
  1389. hostapd.add_ap(apdev[0]['ifname'],
  1390. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1391. "wpa_passphrase": "12345678", "wpa": "2",
  1392. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
  1393. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1394. logger.info("WPS provisioning step")
  1395. if "FAIL" in hapd.request("SET wps_version_number 0x43"):
  1396. raise Exception("Failed to enable test functionality")
  1397. hapd.request("WPS_PBC")
  1398. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1399. dev[0].dump_monitor()
  1400. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1401. dev[0].wait_connected(timeout=30)
  1402. hapd.request("SET wps_version_number 0x20")
  1403. def test_ap_wps_check_pin(dev, apdev):
  1404. """Verify PIN checking through control interface"""
  1405. hostapd.add_ap(apdev[0]['ifname'],
  1406. { "ssid": "wps", "eap_server": "1", "wps_state": "2",
  1407. "wpa_passphrase": "12345678", "wpa": "2",
  1408. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
  1409. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1410. for t in [ ("12345670", "12345670"),
  1411. ("12345678", "FAIL-CHECKSUM"),
  1412. ("12345", "FAIL"),
  1413. ("123456789", "FAIL"),
  1414. ("1234-5670", "12345670"),
  1415. ("1234 5670", "12345670"),
  1416. ("1-2.3:4 5670", "12345670") ]:
  1417. res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
  1418. res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
  1419. if res != res2:
  1420. raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
  1421. if res != t[1]:
  1422. raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
  1423. if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
  1424. raise Exception("Unexpected WPS_CHECK_PIN success")
  1425. if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
  1426. raise Exception("Unexpected WPS_CHECK_PIN success")
  1427. for i in range(0, 10):
  1428. pin = dev[0].request("WPS_PIN get")
  1429. rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
  1430. if pin != rpin:
  1431. raise Exception("Random PIN validation failed for " + pin)
  1432. def test_ap_wps_wep_config(dev, apdev):
  1433. """WPS 2.0 AP rejecting WEP configuration"""
  1434. ssid = "test-wps-config"
  1435. appin = "12345670"
  1436. hostapd.add_ap(apdev[0]['ifname'],
  1437. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1438. "ap_pin": appin})
  1439. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1440. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1441. dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
  1442. "hello", no_wait=True)
  1443. ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
  1444. if ev is None:
  1445. raise Exception("WPS-FAIL timed out")
  1446. if "reason=2" not in ev:
  1447. raise Exception("Unexpected reason code in WPS-FAIL")
  1448. status = hapd.request("WPS_GET_STATUS")
  1449. if "Last WPS result: Failed" not in status:
  1450. raise Exception("WPS failure result not shown correctly")
  1451. if "Failure Reason: WEP Prohibited" not in status:
  1452. raise Exception("Failure reason not reported correctly")
  1453. if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
  1454. raise Exception("Peer address not shown correctly")
  1455. def test_ap_wps_wep_enroll(dev, apdev):
  1456. """WPS 2.0 STA rejecting WEP configuration"""
  1457. ssid = "test-wps-wep"
  1458. hostapd.add_ap(apdev[0]['ifname'],
  1459. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1460. "skip_cred_build": "1", "extra_cred": "wps-wep-cred" })
  1461. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1462. hapd.request("WPS_PBC")
  1463. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1464. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1465. ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
  1466. if ev is None:
  1467. raise Exception("WPS-FAIL event timed out")
  1468. if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
  1469. raise Exception("Unexpected WPS-FAIL event: " + ev)
  1470. def test_ap_wps_ie_fragmentation(dev, apdev):
  1471. """WPS AP using fragmented WPS IE"""
  1472. ssid = "test-wps-ie-fragmentation"
  1473. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1474. "wpa_passphrase": "12345678", "wpa": "2",
  1475. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1476. "device_name": "1234567890abcdef1234567890abcdef",
  1477. "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
  1478. "model_name": "1234567890abcdef1234567890abcdef",
  1479. "model_number": "1234567890abcdef1234567890abcdef",
  1480. "serial_number": "1234567890abcdef1234567890abcdef" }
  1481. hostapd.add_ap(apdev[0]['ifname'], params)
  1482. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1483. hapd.request("WPS_PBC")
  1484. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1485. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1486. dev[0].wait_connected(timeout=30)
  1487. bss = dev[0].get_bss(apdev[0]['bssid'])
  1488. if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
  1489. logger.info("Device Name not received correctly")
  1490. logger.info(bss)
  1491. # This can fail if Probe Response frame is missed and Beacon frame was
  1492. # used to fill in the BSS entry. This can happen, e.g., during heavy
  1493. # load every now and then and is not really an error, so try to
  1494. # workaround by runnign another scan.
  1495. dev[0].scan(freq="2412", only_new=True)
  1496. bss = dev[0].get_bss(apdev[0]['bssid'])
  1497. if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
  1498. logger.info(bss)
  1499. raise Exception("Device Name not received correctly")
  1500. if len(re.findall("dd..0050f204", bss['ie'])) != 2:
  1501. raise Exception("Unexpected number of WPS IEs")
  1502. def get_psk(pskfile):
  1503. psks = {}
  1504. with open(pskfile, "r") as f:
  1505. lines = f.read().splitlines()
  1506. for l in lines:
  1507. if l == "# WPA PSKs":
  1508. continue
  1509. (addr,psk) = l.split(' ')
  1510. psks[addr] = psk
  1511. return psks
  1512. def test_ap_wps_per_station_psk(dev, apdev):
  1513. """WPS PBC provisioning with per-station PSK"""
  1514. addr0 = dev[0].own_addr()
  1515. addr1 = dev[1].own_addr()
  1516. addr2 = dev[2].own_addr()
  1517. ssid = "wps"
  1518. appin = "12345670"
  1519. pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
  1520. try:
  1521. os.remove(pskfile)
  1522. except:
  1523. pass
  1524. try:
  1525. with open(pskfile, "w") as f:
  1526. f.write("# WPA PSKs\n")
  1527. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1528. "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
  1529. "rsn_pairwise": "CCMP", "ap_pin": appin,
  1530. "wpa_psk_file": pskfile }
  1531. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  1532. logger.info("First enrollee")
  1533. hapd.request("WPS_PBC")
  1534. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1535. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1536. dev[0].wait_connected(timeout=30)
  1537. logger.info("Second enrollee")
  1538. hapd.request("WPS_PBC")
  1539. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1540. dev[1].request("WPS_PBC " + apdev[0]['bssid'])
  1541. dev[1].wait_connected(timeout=30)
  1542. logger.info("External registrar")
  1543. dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1544. dev[2].wps_reg(apdev[0]['bssid'], appin)
  1545. logger.info("Verifying PSK results")
  1546. psks = get_psk(pskfile)
  1547. if addr0 not in psks:
  1548. raise Exception("No PSK recorded for sta0")
  1549. if addr1 not in psks:
  1550. raise Exception("No PSK recorded for sta1")
  1551. if addr2 not in psks:
  1552. raise Exception("No PSK recorded for sta2")
  1553. if psks[addr0] == psks[addr1]:
  1554. raise Exception("Same PSK recorded for sta0 and sta1")
  1555. if psks[addr0] == psks[addr2]:
  1556. raise Exception("Same PSK recorded for sta0 and sta2")
  1557. if psks[addr1] == psks[addr2]:
  1558. raise Exception("Same PSK recorded for sta1 and sta2")
  1559. dev[0].request("REMOVE_NETWORK all")
  1560. logger.info("Second external registrar")
  1561. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1562. dev[0].wps_reg(apdev[0]['bssid'], appin)
  1563. psks2 = get_psk(pskfile)
  1564. if addr0 not in psks2:
  1565. raise Exception("No PSK recorded for sta0(reg)")
  1566. if psks[addr0] == psks2[addr0]:
  1567. raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
  1568. finally:
  1569. os.remove(pskfile)
  1570. def test_ap_wps_per_station_psk_failure(dev, apdev):
  1571. """WPS PBC provisioning with per-station PSK (file not writable)"""
  1572. addr0 = dev[0].p2p_dev_addr()
  1573. addr1 = dev[1].p2p_dev_addr()
  1574. addr2 = dev[2].p2p_dev_addr()
  1575. ssid = "wps"
  1576. appin = "12345670"
  1577. pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
  1578. try:
  1579. os.remove(pskfile)
  1580. except:
  1581. pass
  1582. try:
  1583. with open(pskfile, "w") as f:
  1584. f.write("# WPA PSKs\n")
  1585. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1586. "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
  1587. "rsn_pairwise": "CCMP", "ap_pin": appin,
  1588. "wpa_psk_file": pskfile }
  1589. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  1590. if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
  1591. raise Exception("Failed to set wpa_psk_file")
  1592. logger.info("First enrollee")
  1593. hapd.request("WPS_PBC")
  1594. dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1595. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1596. dev[0].wait_connected(timeout=30)
  1597. logger.info("Second enrollee")
  1598. hapd.request("WPS_PBC")
  1599. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1600. dev[1].request("WPS_PBC " + apdev[0]['bssid'])
  1601. dev[1].wait_connected(timeout=30)
  1602. logger.info("External registrar")
  1603. dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
  1604. dev[2].wps_reg(apdev[0]['bssid'], appin)
  1605. logger.info("Verifying PSK results")
  1606. psks = get_psk(pskfile)
  1607. if len(psks) > 0:
  1608. raise Exception("PSK recorded unexpectedly")
  1609. finally:
  1610. os.remove(pskfile)
  1611. def test_ap_wps_pin_request_file(dev, apdev):
  1612. """WPS PIN provisioning with configured AP"""
  1613. ssid = "wps"
  1614. pinfile = "/tmp/ap_wps_pin_request_file.log"
  1615. if os.path.exists(pinfile):
  1616. os.remove(pinfile)
  1617. hostapd.add_ap(apdev[0]['ifname'],
  1618. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1619. "wps_pin_requests": pinfile,
  1620. "wpa_passphrase": "12345678", "wpa": "2",
  1621. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  1622. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1623. uuid = dev[0].get_status_field("uuid")
  1624. pin = dev[0].wps_read_pin()
  1625. try:
  1626. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1627. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  1628. ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
  1629. if ev is None:
  1630. raise Exception("PIN needed event not shown")
  1631. if uuid not in ev:
  1632. raise Exception("UUID mismatch")
  1633. dev[0].request("WPS_CANCEL")
  1634. success = False
  1635. with open(pinfile, "r") as f:
  1636. lines = f.readlines()
  1637. for l in lines:
  1638. if uuid in l:
  1639. success = True
  1640. break
  1641. if not success:
  1642. raise Exception("PIN request entry not in the log file")
  1643. finally:
  1644. try:
  1645. os.remove(pinfile)
  1646. except:
  1647. pass
  1648. def test_ap_wps_auto_setup_with_config_file(dev, apdev):
  1649. """WPS auto-setup with configuration file"""
  1650. conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
  1651. ifname = apdev[0]['ifname']
  1652. try:
  1653. with open(conffile, "w") as f:
  1654. f.write("driver=nl80211\n")
  1655. f.write("hw_mode=g\n")
  1656. f.write("channel=1\n")
  1657. f.write("ieee80211n=1\n")
  1658. f.write("interface=%s\n" % ifname)
  1659. f.write("ctrl_interface=/var/run/hostapd\n")
  1660. f.write("ssid=wps\n")
  1661. f.write("eap_server=1\n")
  1662. f.write("wps_state=1\n")
  1663. hostapd.add_bss('phy3', ifname, conffile)
  1664. hapd = hostapd.Hostapd(ifname)
  1665. hapd.request("WPS_PBC")
  1666. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  1667. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  1668. dev[0].wait_connected(timeout=30)
  1669. with open(conffile, "r") as f:
  1670. lines = f.read().splitlines()
  1671. vals = dict()
  1672. for l in lines:
  1673. try:
  1674. [name,value] = l.split('=', 1)
  1675. vals[name] = value
  1676. except ValueError, e:
  1677. if "# WPS configuration" in l:
  1678. pass
  1679. else:
  1680. raise Exception("Unexpected configuration line: " + l)
  1681. if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
  1682. raise Exception("Incorrect configuration: " + str(vals))
  1683. finally:
  1684. try:
  1685. os.remove(conffile)
  1686. except:
  1687. pass
  1688. def test_ap_wps_pbc_timeout(dev, apdev, params):
  1689. """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
  1690. if not params['long']:
  1691. raise HwsimSkip("Skip test case with long duration due to --long not specified")
  1692. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1693. hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  1694. location = ssdp_get_location(ap_uuid)
  1695. urls = upnp_get_urls(location)
  1696. eventurl = urlparse.urlparse(urls['event_sub_url'])
  1697. ctrlurl = urlparse.urlparse(urls['control_url'])
  1698. url = urlparse.urlparse(location)
  1699. conn = httplib.HTTPConnection(url.netloc)
  1700. class WPSERHTTPServer(SocketServer.StreamRequestHandler):
  1701. def handle(self):
  1702. data = self.rfile.readline().strip()
  1703. logger.debug(data)
  1704. self.wfile.write(gen_wps_event())
  1705. server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
  1706. server.timeout = 1
  1707. headers = { "callback": '<http://127.0.0.1:12345/event>',
  1708. "NT": "upnp:event",
  1709. "timeout": "Second-1234" }
  1710. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1711. resp = conn.getresponse()
  1712. if resp.status != 200:
  1713. raise Exception("Unexpected HTTP response: %d" % resp.status)
  1714. sid = resp.getheader("sid")
  1715. logger.debug("Subscription SID " + sid)
  1716. msg = '''<?xml version="1.0"?>
  1717. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  1718. <s:Body>
  1719. <u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
  1720. <NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
  1721. VFi5hrLk
  1722. </NewMessage>
  1723. </u:SetSelectedRegistrar>
  1724. </s:Body>
  1725. </s:Envelope>'''
  1726. headers = { "Content-type": 'text/xml; charset="utf-8"' }
  1727. headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
  1728. conn.request("POST", ctrlurl.path, msg, headers)
  1729. resp = conn.getresponse()
  1730. if resp.status != 200:
  1731. raise Exception("Unexpected HTTP response: %d" % resp.status)
  1732. server.handle_request()
  1733. logger.info("Start WPS_PBC and wait for PBC walk time expiration")
  1734. if "OK" not in dev[0].request("WPS_PBC"):
  1735. raise Exception("WPS_PBC failed")
  1736. start = os.times()[4]
  1737. server.handle_request()
  1738. dev[1].request("BSS_FLUSH 0")
  1739. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
  1740. only_new=True)
  1741. bss = dev[1].get_bss(apdev[0]['bssid'])
  1742. logger.debug("BSS: " + str(bss))
  1743. if '[WPS-AUTH]' not in bss['flags']:
  1744. raise Exception("WPS not indicated authorized")
  1745. server.handle_request()
  1746. wps_timeout_seen = False
  1747. while True:
  1748. hapd.dump_monitor()
  1749. dev[1].dump_monitor()
  1750. if not wps_timeout_seen:
  1751. ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
  1752. if ev is not None:
  1753. logger.info("PBC timeout seen")
  1754. wps_timeout_seen = True
  1755. else:
  1756. dev[0].dump_monitor()
  1757. now = os.times()[4]
  1758. if now - start > 130:
  1759. raise Exception("Selected registration information not removed")
  1760. dev[1].request("BSS_FLUSH 0")
  1761. dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
  1762. only_new=True)
  1763. bss = dev[1].get_bss(apdev[0]['bssid'])
  1764. logger.debug("BSS: " + str(bss))
  1765. if '[WPS-AUTH]' not in bss['flags']:
  1766. break
  1767. server.handle_request()
  1768. server.server_close()
  1769. if wps_timeout_seen:
  1770. return
  1771. now = os.times()[4]
  1772. if now < start + 150:
  1773. dur = start + 150 - now
  1774. else:
  1775. dur = 1
  1776. logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
  1777. ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
  1778. if ev is None:
  1779. raise Exception("WPS-TIMEOUT not reported")
  1780. def add_ssdp_ap(ifname, ap_uuid):
  1781. ssid = "wps-ssdp"
  1782. ap_pin = "12345670"
  1783. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1784. "wpa_passphrase": "12345678", "wpa": "2",
  1785. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1786. "device_name": "Wireless AP", "manufacturer": "Company",
  1787. "model_name": "WAP", "model_number": "123",
  1788. "serial_number": "12345", "device_type": "6-0050F204-1",
  1789. "os_version": "01020300",
  1790. "config_methods": "label push_button",
  1791. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
  1792. "friendly_name": "WPS Access Point",
  1793. "manufacturer_url": "http://www.example.com/",
  1794. "model_description": "Wireless Access Point",
  1795. "model_url": "http://www.example.com/model/",
  1796. "upc": "123456789012" }
  1797. return hostapd.add_ap(ifname, params)
  1798. def ssdp_send(msg, no_recv=False):
  1799. socket.setdefaulttimeout(1)
  1800. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  1801. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1802. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  1803. sock.bind(("127.0.0.1", 0))
  1804. sock.sendto(msg, ("239.255.255.250", 1900))
  1805. if no_recv:
  1806. return None
  1807. return sock.recv(1000)
  1808. def ssdp_send_msearch(st):
  1809. msg = '\r\n'.join([
  1810. 'M-SEARCH * HTTP/1.1',
  1811. 'HOST: 239.255.255.250:1900',
  1812. 'MX: 1',
  1813. 'MAN: "ssdp:discover"',
  1814. 'ST: ' + st,
  1815. '', ''])
  1816. return ssdp_send(msg)
  1817. def test_ap_wps_ssdp_msearch(dev, apdev):
  1818. """WPS AP and SSDP M-SEARCH messages"""
  1819. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1820. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  1821. msg = '\r\n'.join([
  1822. 'M-SEARCH * HTTP/1.1',
  1823. 'Host: 239.255.255.250:1900',
  1824. 'Mx: 1',
  1825. 'Man: "ssdp:discover"',
  1826. 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
  1827. '', ''])
  1828. ssdp_send(msg)
  1829. msg = '\r\n'.join([
  1830. 'M-SEARCH * HTTP/1.1',
  1831. 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
  1832. 'mx: \t1\t\t ',
  1833. 'man: \t \t "ssdp:discover" ',
  1834. 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
  1835. '', ''])
  1836. ssdp_send(msg)
  1837. ssdp_send_msearch("ssdp:all")
  1838. ssdp_send_msearch("upnp:rootdevice")
  1839. ssdp_send_msearch("uuid:" + ap_uuid)
  1840. ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
  1841. ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1");
  1842. msg = '\r\n'.join([
  1843. 'M-SEARCH * HTTP/1.1',
  1844. 'HOST:\t239.255.255.250:1900',
  1845. 'MAN: "ssdp:discover"',
  1846. 'MX: 130',
  1847. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1848. '', ''])
  1849. ssdp_send(msg, no_recv=True)
  1850. def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
  1851. """WPS AP and invalid SSDP M-SEARCH messages"""
  1852. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1853. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  1854. socket.setdefaulttimeout(1)
  1855. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  1856. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1857. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  1858. sock.bind(("127.0.0.1", 0))
  1859. logger.debug("Missing MX")
  1860. msg = '\r\n'.join([
  1861. 'M-SEARCH * HTTP/1.1',
  1862. 'HOST: 239.255.255.250:1900',
  1863. 'MAN: "ssdp:discover"',
  1864. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1865. '', ''])
  1866. sock.sendto(msg, ("239.255.255.250", 1900))
  1867. logger.debug("Negative MX")
  1868. msg = '\r\n'.join([
  1869. 'M-SEARCH * HTTP/1.1',
  1870. 'HOST: 239.255.255.250:1900',
  1871. 'MX: -1',
  1872. 'MAN: "ssdp:discover"',
  1873. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1874. '', ''])
  1875. sock.sendto(msg, ("239.255.255.250", 1900))
  1876. logger.debug("Invalid MX")
  1877. msg = '\r\n'.join([
  1878. 'M-SEARCH * HTTP/1.1',
  1879. 'HOST: 239.255.255.250:1900',
  1880. 'MX; 1',
  1881. 'MAN: "ssdp:discover"',
  1882. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1883. '', ''])
  1884. sock.sendto(msg, ("239.255.255.250", 1900))
  1885. logger.debug("Missing MAN")
  1886. msg = '\r\n'.join([
  1887. 'M-SEARCH * HTTP/1.1',
  1888. 'HOST: 239.255.255.250:1900',
  1889. 'MX: 1',
  1890. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1891. '', ''])
  1892. sock.sendto(msg, ("239.255.255.250", 1900))
  1893. logger.debug("Invalid MAN")
  1894. msg = '\r\n'.join([
  1895. 'M-SEARCH * HTTP/1.1',
  1896. 'HOST: 239.255.255.250:1900',
  1897. 'MX: 1',
  1898. 'MAN: foo',
  1899. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1900. '', ''])
  1901. sock.sendto(msg, ("239.255.255.250", 1900))
  1902. msg = '\r\n'.join([
  1903. 'M-SEARCH * HTTP/1.1',
  1904. 'HOST: 239.255.255.250:1900',
  1905. 'MX: 1',
  1906. 'MAN; "ssdp:discover"',
  1907. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1908. '', ''])
  1909. sock.sendto(msg, ("239.255.255.250", 1900))
  1910. logger.debug("Missing HOST")
  1911. msg = '\r\n'.join([
  1912. 'M-SEARCH * HTTP/1.1',
  1913. 'MAN: "ssdp:discover"',
  1914. 'MX: 1',
  1915. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1916. '', ''])
  1917. sock.sendto(msg, ("239.255.255.250", 1900))
  1918. logger.debug("Missing ST")
  1919. msg = '\r\n'.join([
  1920. 'M-SEARCH * HTTP/1.1',
  1921. 'HOST: 239.255.255.250:1900',
  1922. 'MAN: "ssdp:discover"',
  1923. 'MX: 1',
  1924. '', ''])
  1925. sock.sendto(msg, ("239.255.255.250", 1900))
  1926. logger.debug("Mismatching ST")
  1927. msg = '\r\n'.join([
  1928. 'M-SEARCH * HTTP/1.1',
  1929. 'HOST: 239.255.255.250:1900',
  1930. 'MAN: "ssdp:discover"',
  1931. 'MX: 1',
  1932. 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
  1933. '', ''])
  1934. sock.sendto(msg, ("239.255.255.250", 1900))
  1935. msg = '\r\n'.join([
  1936. 'M-SEARCH * HTTP/1.1',
  1937. 'HOST: 239.255.255.250:1900',
  1938. 'MAN: "ssdp:discover"',
  1939. 'MX: 1',
  1940. 'ST: foo:bar',
  1941. '', ''])
  1942. sock.sendto(msg, ("239.255.255.250", 1900))
  1943. msg = '\r\n'.join([
  1944. 'M-SEARCH * HTTP/1.1',
  1945. 'HOST: 239.255.255.250:1900',
  1946. 'MAN: "ssdp:discover"',
  1947. 'MX: 1',
  1948. 'ST: foobar',
  1949. '', ''])
  1950. sock.sendto(msg, ("239.255.255.250", 1900))
  1951. logger.debug("Invalid ST")
  1952. msg = '\r\n'.join([
  1953. 'M-SEARCH * HTTP/1.1',
  1954. 'HOST: 239.255.255.250:1900',
  1955. 'MAN: "ssdp:discover"',
  1956. 'MX: 1',
  1957. 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
  1958. '', ''])
  1959. sock.sendto(msg, ("239.255.255.250", 1900))
  1960. logger.debug("Invalid M-SEARCH")
  1961. msg = '\r\n'.join([
  1962. 'M+SEARCH * HTTP/1.1',
  1963. 'HOST: 239.255.255.250:1900',
  1964. 'MAN: "ssdp:discover"',
  1965. 'MX: 1',
  1966. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1967. '', ''])
  1968. sock.sendto(msg, ("239.255.255.250", 1900))
  1969. msg = '\r\n'.join([
  1970. 'M-SEARCH-* HTTP/1.1',
  1971. 'HOST: 239.255.255.250:1900',
  1972. 'MAN: "ssdp:discover"',
  1973. 'MX: 1',
  1974. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1975. '', ''])
  1976. sock.sendto(msg, ("239.255.255.250", 1900))
  1977. logger.debug("Invalid message format")
  1978. sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
  1979. msg = '\r'.join([
  1980. 'M-SEARCH * HTTP/1.1',
  1981. 'HOST: 239.255.255.250:1900',
  1982. 'MAN: "ssdp:discover"',
  1983. 'MX: 1',
  1984. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1985. '', ''])
  1986. sock.sendto(msg, ("239.255.255.250", 1900))
  1987. try:
  1988. r = sock.recv(1000)
  1989. raise Exception("Unexpected M-SEARCH response: " + r)
  1990. except socket.timeout:
  1991. pass
  1992. logger.debug("Valid M-SEARCH")
  1993. msg = '\r\n'.join([
  1994. 'M-SEARCH * HTTP/1.1',
  1995. 'HOST: 239.255.255.250:1900',
  1996. 'MAN: "ssdp:discover"',
  1997. 'MX: 1',
  1998. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1999. '', ''])
  2000. sock.sendto(msg, ("239.255.255.250", 1900))
  2001. try:
  2002. r = sock.recv(1000)
  2003. pass
  2004. except socket.timeout:
  2005. raise Exception("No SSDP response")
  2006. def test_ap_wps_ssdp_burst(dev, apdev):
  2007. """WPS AP and SSDP burst"""
  2008. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  2009. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  2010. msg = '\r\n'.join([
  2011. 'M-SEARCH * HTTP/1.1',
  2012. 'HOST: 239.255.255.250:1900',
  2013. 'MAN: "ssdp:discover"',
  2014. 'MX: 1',
  2015. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  2016. '', ''])
  2017. socket.setdefaulttimeout(1)
  2018. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  2019. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  2020. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  2021. sock.bind(("127.0.0.1", 0))
  2022. for i in range(0, 25):
  2023. sock.sendto(msg, ("239.255.255.250", 1900))
  2024. resp = 0
  2025. while True:
  2026. try:
  2027. r = sock.recv(1000)
  2028. if not r.startswith("HTTP/1.1 200 OK\r\n"):
  2029. raise Exception("Unexpected message: " + r)
  2030. resp += 1
  2031. except socket.timeout:
  2032. break
  2033. if resp < 20:
  2034. raise Exception("Too few SSDP responses")
  2035. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  2036. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  2037. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  2038. sock.bind(("127.0.0.1", 0))
  2039. for i in range(0, 25):
  2040. sock.sendto(msg, ("239.255.255.250", 1900))
  2041. while True:
  2042. try:
  2043. r = sock.recv(1000)
  2044. if ap_uuid in r:
  2045. break
  2046. except socket.timeout:
  2047. raise Exception("No SSDP response")
  2048. def ssdp_get_location(uuid):
  2049. res = ssdp_send_msearch("uuid:" + uuid)
  2050. location = None
  2051. for l in res.splitlines():
  2052. if l.lower().startswith("location:"):
  2053. location = l.split(':', 1)[1].strip()
  2054. break
  2055. if location is None:
  2056. raise Exception("No UPnP location found")
  2057. return location
  2058. def upnp_get_urls(location):
  2059. conn = urllib.urlopen(location)
  2060. tree = ET.parse(conn)
  2061. root = tree.getroot()
  2062. urn = '{urn:schemas-upnp-org:device-1-0}'
  2063. service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
  2064. res = {}
  2065. res['scpd_url'] = urlparse.urljoin(location, service.find(urn + 'SCPDURL').text)
  2066. res['control_url'] = urlparse.urljoin(location, service.find(urn + 'controlURL').text)
  2067. res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
  2068. return res
  2069. def upnp_soap_action(conn, path, action, include_soap_action=True, soap_action_override=None):
  2070. soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
  2071. wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
  2072. ET.register_namespace('soapenv', soapns)
  2073. ET.register_namespace('wfa', wpsns)
  2074. attrib = {}
  2075. attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
  2076. root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
  2077. body = ET.SubElement(root, "{%s}Body" % soapns)
  2078. act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
  2079. tree = ET.ElementTree(root)
  2080. soap = StringIO.StringIO()
  2081. tree.write(soap, xml_declaration=True, encoding='utf-8')
  2082. headers = { "Content-type": 'text/xml; charset="utf-8"' }
  2083. if include_soap_action:
  2084. headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
  2085. elif soap_action_override:
  2086. headers["SOAPAction"] = soap_action_override
  2087. conn.request("POST", path, soap.getvalue(), headers)
  2088. return conn.getresponse()
  2089. def test_ap_wps_upnp(dev, apdev):
  2090. """WPS AP and UPnP operations"""
  2091. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  2092. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  2093. location = ssdp_get_location(ap_uuid)
  2094. urls = upnp_get_urls(location)
  2095. conn = urllib.urlopen(urls['scpd_url'])
  2096. scpd = conn.read()
  2097. conn = urllib.urlopen(urlparse.urljoin(location, "unknown.html"))
  2098. if conn.getcode() != 404:
  2099. raise Exception("Unexpected HTTP response to GET unknown URL")
  2100. url = urlparse.urlparse(location)
  2101. conn = httplib.HTTPConnection(url.netloc)
  2102. #conn.set_debuglevel(1)
  2103. headers = { "Content-type": 'text/xml; charset="utf-8"',
  2104. "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
  2105. conn.request("POST", "hello", "\r\n\r\n", headers)
  2106. resp = conn.getresponse()
  2107. if resp.status != 404:
  2108. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2109. conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
  2110. resp = conn.getresponse()
  2111. if resp.status != 501:
  2112. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2113. headers = { "Content-type": 'text/xml; charset="utf-8"',
  2114. "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
  2115. ctrlurl = urlparse.urlparse(urls['control_url'])
  2116. conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
  2117. resp = conn.getresponse()
  2118. if resp.status != 401:
  2119. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2120. logger.debug("GetDeviceInfo without SOAPAction header")
  2121. resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
  2122. include_soap_action=False)
  2123. if resp.status != 401:
  2124. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2125. logger.debug("GetDeviceInfo with invalid SOAPAction header")
  2126. for act in [ "foo",
  2127. "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
  2128. '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
  2129. '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
  2130. resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
  2131. include_soap_action=False,
  2132. soap_action_override=act)
  2133. if resp.status != 401:
  2134. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2135. resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
  2136. if resp.status != 200:
  2137. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2138. dev = resp.read()
  2139. if "NewDeviceInfo" not in dev:
  2140. raise Exception("Unexpected GetDeviceInfo response")
  2141. logger.debug("PutMessage without required parameters")
  2142. resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
  2143. if resp.status != 600:
  2144. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2145. logger.debug("PutWLANResponse without required parameters")
  2146. resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
  2147. if resp.status != 600:
  2148. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2149. logger.debug("SetSelectedRegistrar from unregistered ER")
  2150. resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
  2151. if resp.status != 501:
  2152. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2153. logger.debug("Unknown action")
  2154. resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
  2155. if resp.status != 401:
  2156. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2157. def test_ap_wps_upnp_subscribe(dev, apdev):
  2158. """WPS AP and UPnP event subscription"""
  2159. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  2160. hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  2161. location = ssdp_get_location(ap_uuid)
  2162. urls = upnp_get_urls(location)
  2163. eventurl = urlparse.urlparse(urls['event_sub_url'])
  2164. url = urlparse.urlparse(location)
  2165. conn = httplib.HTTPConnection(url.netloc)
  2166. #conn.set_debuglevel(1)
  2167. headers = { "callback": '<http://127.0.0.1:12345/event>',
  2168. "timeout": "Second-1234" }
  2169. conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
  2170. resp = conn.getresponse()
  2171. if resp.status != 412:
  2172. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2173. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2174. resp = conn.getresponse()
  2175. if resp.status != 412:
  2176. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2177. headers = { "NT": "upnp:event",
  2178. "timeout": "Second-1234" }
  2179. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2180. resp = conn.getresponse()
  2181. if resp.status != 412:
  2182. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2183. headers = { "callback": '<http://127.0.0.1:12345/event>',
  2184. "NT": "upnp:foobar",
  2185. "timeout": "Second-1234" }
  2186. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2187. resp = conn.getresponse()
  2188. if resp.status != 400:
  2189. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2190. logger.debug("Valid subscription")
  2191. headers = { "callback": '<http://127.0.0.1:12345/event>',
  2192. "NT": "upnp:event",
  2193. "timeout": "Second-1234" }
  2194. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2195. resp = conn.getresponse()
  2196. if resp.status != 200:
  2197. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2198. sid = resp.getheader("sid")
  2199. logger.debug("Subscription SID " + sid)
  2200. logger.debug("Invalid re-subscription")
  2201. headers = { "NT": "upnp:event",
  2202. "sid": "123456734567854",
  2203. "timeout": "Second-1234" }
  2204. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2205. resp = conn.getresponse()
  2206. if resp.status != 400:
  2207. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2208. logger.debug("Invalid re-subscription")
  2209. headers = { "NT": "upnp:event",
  2210. "sid": "uuid:123456734567854",
  2211. "timeout": "Second-1234" }
  2212. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2213. resp = conn.getresponse()
  2214. if resp.status != 400:
  2215. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2216. logger.debug("Invalid re-subscription")
  2217. headers = { "callback": '<http://127.0.0.1:12345/event>',
  2218. "NT": "upnp:event",
  2219. "sid": sid,
  2220. "timeout": "Second-1234" }
  2221. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2222. resp = conn.getresponse()
  2223. if resp.status != 400:
  2224. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2225. logger.debug("SID mismatch in re-subscription")
  2226. headers = { "NT": "upnp:event",
  2227. "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
  2228. "timeout": "Second-1234" }
  2229. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2230. resp = conn.getresponse()
  2231. if resp.status != 412:
  2232. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2233. logger.debug("Valid re-subscription")
  2234. headers = { "NT": "upnp:event",
  2235. "sid": sid,
  2236. "timeout": "Second-1234" }
  2237. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2238. resp = conn.getresponse()
  2239. if resp.status != 200:
  2240. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2241. sid2 = resp.getheader("sid")
  2242. logger.debug("Subscription SID " + sid2)
  2243. if sid != sid2:
  2244. raise Exception("Unexpected SID change")
  2245. logger.debug("Valid re-subscription")
  2246. headers = { "NT": "upnp:event",
  2247. "sid": "uuid: \t \t" + sid.split(':')[1],
  2248. "timeout": "Second-1234" }
  2249. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2250. resp = conn.getresponse()
  2251. if resp.status != 200:
  2252. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2253. logger.debug("Invalid unsubscription")
  2254. headers = { "sid": sid }
  2255. conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
  2256. resp = conn.getresponse()
  2257. if resp.status != 412:
  2258. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2259. headers = { "foo": "bar" }
  2260. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2261. resp = conn.getresponse()
  2262. if resp.status != 412:
  2263. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2264. logger.debug("Valid unsubscription")
  2265. headers = { "sid": sid }
  2266. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2267. resp = conn.getresponse()
  2268. if resp.status != 200:
  2269. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2270. logger.debug("Unsubscription for not existing SID")
  2271. headers = { "sid": sid }
  2272. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2273. resp = conn.getresponse()
  2274. if resp.status != 412:
  2275. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2276. logger.debug("Invalid unsubscription")
  2277. headers = { "sid": " \t \tfoo" }
  2278. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2279. resp = conn.getresponse()
  2280. if resp.status != 400:
  2281. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2282. logger.debug("Invalid unsubscription")
  2283. headers = { "sid": "uuid:\t \tfoo" }
  2284. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2285. resp = conn.getresponse()
  2286. if resp.status != 400:
  2287. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2288. logger.debug("Invalid unsubscription")
  2289. headers = { "NT": "upnp:event",
  2290. "sid": sid }
  2291. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2292. resp = conn.getresponse()
  2293. if resp.status != 400:
  2294. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2295. headers = { "callback": '<http://127.0.0.1:12345/event>',
  2296. "sid": sid }
  2297. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2298. resp = conn.getresponse()
  2299. if resp.status != 400:
  2300. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2301. logger.debug("Valid subscription with multiple callbacks")
  2302. 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>',
  2303. "NT": "upnp:event",
  2304. "timeout": "Second-1234" }
  2305. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2306. resp = conn.getresponse()
  2307. if resp.status != 200:
  2308. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2309. sid = resp.getheader("sid")
  2310. logger.debug("Subscription SID " + sid)
  2311. # Force subscription to be deleted due to errors
  2312. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  2313. dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
  2314. with alloc_fail(hapd, 1, "event_build_message"):
  2315. for i in range(10):
  2316. dev[1].dump_monitor()
  2317. dev[2].dump_monitor()
  2318. dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
  2319. dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
  2320. dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
  2321. dev[1].request("WPS_CANCEL")
  2322. dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
  2323. dev[2].request("WPS_CANCEL")
  2324. if i % 4 == 1:
  2325. time.sleep(1)
  2326. else:
  2327. time.sleep(0.1)
  2328. time.sleep(0.2)
  2329. headers = { "sid": sid }
  2330. conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
  2331. resp = conn.getresponse()
  2332. if resp.status != 200 and resp.status != 412:
  2333. raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
  2334. headers = { "callback": '<http://127.0.0.1:12345/event>',
  2335. "NT": "upnp:event",
  2336. "timeout": "Second-1234" }
  2337. with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
  2338. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2339. resp = conn.getresponse()
  2340. if resp.status != 200:
  2341. raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
  2342. sid = resp.getheader("sid")
  2343. logger.debug("Subscription SID " + sid)
  2344. headers = { "sid": sid }
  2345. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2346. resp = conn.getresponse()
  2347. if resp.status != 200:
  2348. raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
  2349. headers = { "callback": '<http://127.0.0.1:12345/event>',
  2350. "NT": "upnp:event",
  2351. "timeout": "Second-1234" }
  2352. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2353. resp = conn.getresponse()
  2354. if resp.status != 200:
  2355. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2356. sid = resp.getheader("sid")
  2357. logger.debug("Subscription SID " + sid)
  2358. with alloc_fail(hapd, 1, "=event_add"):
  2359. for i in range(2):
  2360. dev[1].dump_monitor()
  2361. dev[2].dump_monitor()
  2362. dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
  2363. dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
  2364. dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
  2365. dev[1].request("WPS_CANCEL")
  2366. dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
  2367. dev[2].request("WPS_CANCEL")
  2368. if i == 0:
  2369. time.sleep(1)
  2370. else:
  2371. time.sleep(0.1)
  2372. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2373. resp = conn.getresponse()
  2374. if resp.status != 200:
  2375. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2376. with alloc_fail(hapd, 1, "wpabuf_dup;event_add"):
  2377. dev[1].dump_monitor()
  2378. dev[2].dump_monitor()
  2379. dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
  2380. dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
  2381. dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
  2382. dev[1].request("WPS_CANCEL")
  2383. dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
  2384. dev[2].request("WPS_CANCEL")
  2385. time.sleep(0.1)
  2386. with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
  2387. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2388. resp = conn.getresponse()
  2389. if resp.status != 500:
  2390. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2391. with alloc_fail(hapd, 1, "=subscription_start"):
  2392. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2393. resp = conn.getresponse()
  2394. if resp.status != 500:
  2395. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2396. headers = { "callback": '',
  2397. "NT": "upnp:event",
  2398. "timeout": "Second-1234" }
  2399. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2400. resp = conn.getresponse()
  2401. if resp.status != 500:
  2402. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2403. headers = { "callback": ' <',
  2404. "NT": "upnp:event",
  2405. "timeout": "Second-1234" }
  2406. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2407. resp = conn.getresponse()
  2408. if resp.status != 500:
  2409. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2410. headers = { "callback": '<http://127.0.0.1:12345/event>',
  2411. "NT": "upnp:event",
  2412. "timeout": "Second-1234" }
  2413. with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
  2414. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2415. resp = conn.getresponse()
  2416. if resp.status != 500:
  2417. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2418. with alloc_fail(hapd, 1, "event_add;subscription_first_event"):
  2419. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2420. resp = conn.getresponse()
  2421. if resp.status != 500:
  2422. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2423. with alloc_fail(hapd, 1, "subscr_addr_add_url"):
  2424. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2425. resp = conn.getresponse()
  2426. if resp.status != 500:
  2427. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2428. with alloc_fail(hapd, 2, "subscr_addr_add_url"):
  2429. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2430. resp = conn.getresponse()
  2431. if resp.status != 500:
  2432. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2433. for i in range(6):
  2434. headers = { "callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
  2435. "NT": "upnp:event",
  2436. "timeout": "Second-1234" }
  2437. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  2438. resp = conn.getresponse()
  2439. if resp.status != 200:
  2440. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2441. with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
  2442. dev[1].dump_monitor()
  2443. dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
  2444. dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
  2445. dev[1].request("WPS_CANCEL")
  2446. time.sleep(0.1)
  2447. with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
  2448. dev[1].dump_monitor()
  2449. dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
  2450. dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
  2451. dev[1].request("WPS_CANCEL")
  2452. time.sleep(0.1)
  2453. with alloc_fail(hapd, 1, "base64_encode;upnp_wps_device_send_wlan_event"):
  2454. dev[1].dump_monitor()
  2455. dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
  2456. dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
  2457. dev[1].request("WPS_CANCEL")
  2458. time.sleep(0.1)
  2459. hapd.disable()
  2460. with alloc_fail(hapd, 1, "get_netif_info"):
  2461. if "FAIL" not in hapd.request("ENABLE"):
  2462. raise Exception("ENABLE succeeded during OOM")
  2463. def test_ap_wps_upnp_http_proto(dev, apdev):
  2464. """WPS AP and UPnP/HTTP protocol testing"""
  2465. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  2466. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  2467. location = ssdp_get_location(ap_uuid)
  2468. url = urlparse.urlparse(location)
  2469. conn = httplib.HTTPConnection(url.netloc, timeout=0.2)
  2470. #conn.set_debuglevel(1)
  2471. conn.request("HEAD", "hello")
  2472. resp = conn.getresponse()
  2473. if resp.status != 501:
  2474. raise Exception("Unexpected response to HEAD: " + str(resp.status))
  2475. conn.close()
  2476. for cmd in [ "PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST" ]:
  2477. try:
  2478. conn.request(cmd, "hello")
  2479. resp = conn.getresponse()
  2480. except Exception, e:
  2481. pass
  2482. conn.close()
  2483. headers = { "Content-Length": 'abc' }
  2484. conn.request("HEAD", "hello", "\r\n\r\n", headers)
  2485. try:
  2486. resp = conn.getresponse()
  2487. except Exception, e:
  2488. pass
  2489. conn.close()
  2490. headers = { "Content-Length": '-10' }
  2491. conn.request("HEAD", "hello", "\r\n\r\n", headers)
  2492. try:
  2493. resp = conn.getresponse()
  2494. except Exception, e:
  2495. pass
  2496. conn.close()
  2497. headers = { "Content-Length": '10000000000000' }
  2498. conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
  2499. try:
  2500. resp = conn.getresponse()
  2501. except Exception, e:
  2502. pass
  2503. conn.close()
  2504. headers = { "Transfer-Encoding": 'abc' }
  2505. conn.request("HEAD", "hello", "\r\n\r\n", headers)
  2506. resp = conn.getresponse()
  2507. if resp.status != 501:
  2508. raise Exception("Unexpected response to HEAD: " + str(resp.status))
  2509. conn.close()
  2510. headers = { "Transfer-Encoding": 'chunked' }
  2511. conn.request("HEAD", "hello", "\r\n\r\n", headers)
  2512. resp = conn.getresponse()
  2513. if resp.status != 501:
  2514. raise Exception("Unexpected response to HEAD: " + str(resp.status))
  2515. conn.close()
  2516. # Too long a header
  2517. conn.request("HEAD", 5000 * 'A')
  2518. try:
  2519. resp = conn.getresponse()
  2520. except Exception, e:
  2521. pass
  2522. conn.close()
  2523. # Long URL but within header length limits
  2524. conn.request("HEAD", 3000 * 'A')
  2525. resp = conn.getresponse()
  2526. if resp.status != 501:
  2527. raise Exception("Unexpected response to HEAD: " + str(resp.status))
  2528. conn.close()
  2529. headers = { "Content-Length": '20' }
  2530. conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
  2531. try:
  2532. resp = conn.getresponse()
  2533. except Exception, e:
  2534. pass
  2535. conn.close()
  2536. conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
  2537. resp = conn.getresponse()
  2538. if resp.status != 404:
  2539. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2540. conn.close()
  2541. conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
  2542. try:
  2543. resp = conn.getresponse()
  2544. except Exception, e:
  2545. pass
  2546. conn.close()
  2547. def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
  2548. """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
  2549. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  2550. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  2551. location = ssdp_get_location(ap_uuid)
  2552. url = urlparse.urlparse(location)
  2553. conn = httplib.HTTPConnection(url.netloc)
  2554. #conn.set_debuglevel(1)
  2555. headers = { "Transfer-Encoding": 'chunked' }
  2556. conn.request("POST", "hello",
  2557. "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
  2558. headers)
  2559. resp = conn.getresponse()
  2560. if resp.status != 404:
  2561. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2562. conn.close()
  2563. conn.putrequest("POST", "hello")
  2564. conn.putheader('Transfer-Encoding', 'chunked')
  2565. conn.endheaders()
  2566. conn.send("a\r\nabcdefghij\r\n")
  2567. time.sleep(0.1)
  2568. conn.send("2\r\nkl\r\n")
  2569. conn.send("0\r\n\r\n")
  2570. resp = conn.getresponse()
  2571. if resp.status != 404:
  2572. raise Exception("Unexpected HTTP response: %d" % resp.status)
  2573. conn.close()
  2574. conn.putrequest("POST", "hello")
  2575. conn.putheader('Transfer-Encoding', 'chunked')
  2576. conn.endheaders()
  2577. completed = False
  2578. try:
  2579. for i in range(20000):
  2580. conn.send("1\r\nZ\r\n")
  2581. conn.send("0\r\n\r\n")
  2582. resp = conn.getresponse()
  2583. completed = True
  2584. except Exception, e:
  2585. pass
  2586. conn.close()
  2587. if completed:
  2588. raise Exception("Too long chunked request did not result in connection reset")
  2589. headers = { "Transfer-Encoding": 'chunked' }
  2590. conn.request("POST", "hello", "80000000\r\na", headers)
  2591. try:
  2592. resp = conn.getresponse()
  2593. except Exception, e:
  2594. pass
  2595. conn.close()
  2596. conn.request("POST", "hello", "10000000\r\na", headers)
  2597. try:
  2598. resp = conn.getresponse()
  2599. except Exception, e:
  2600. pass
  2601. conn.close()
  2602. def test_ap_wps_disabled(dev, apdev):
  2603. """WPS operations while WPS is disabled"""
  2604. ssid = "test-wps-disabled"
  2605. hostapd.add_ap(apdev[0]['ifname'], { "ssid": ssid })
  2606. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2607. if "FAIL" not in hapd.request("WPS_PBC"):
  2608. raise Exception("WPS_PBC succeeded unexpectedly")
  2609. if "FAIL" not in hapd.request("WPS_CANCEL"):
  2610. raise Exception("WPS_CANCEL succeeded unexpectedly")
  2611. def test_ap_wps_mixed_cred(dev, apdev):
  2612. """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
  2613. ssid = "test-wps-wep"
  2614. hostapd.add_ap(apdev[0]['ifname'],
  2615. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2616. "skip_cred_build": "1", "extra_cred": "wps-mixed-cred" })
  2617. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2618. hapd.request("WPS_PBC")
  2619. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  2620. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  2621. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
  2622. if ev is None:
  2623. raise Exception("WPS-SUCCESS event timed out")
  2624. nets = dev[0].list_networks()
  2625. if len(nets) != 1:
  2626. raise Exception("Unexpected number of network blocks")
  2627. id = nets[0]['id']
  2628. proto = dev[0].get_network(id, "proto")
  2629. if proto != "WPA RSN":
  2630. raise Exception("Unexpected merged proto field value: " + proto)
  2631. pairwise = dev[0].get_network(id, "pairwise")
  2632. if pairwise != "CCMP TKIP" and pairwise != "CCMP GCMP TKIP":
  2633. raise Exception("Unexpected merged pairwise field value: " + pairwise)
  2634. def test_ap_wps_while_connected(dev, apdev):
  2635. """WPS PBC provisioning while connected to another AP"""
  2636. ssid = "test-wps-conf"
  2637. hostapd.add_ap(apdev[0]['ifname'],
  2638. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2639. "wpa_passphrase": "12345678", "wpa": "2",
  2640. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2641. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2642. hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
  2643. dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
  2644. logger.info("WPS provisioning step")
  2645. hapd.request("WPS_PBC")
  2646. dev[0].dump_monitor()
  2647. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  2648. dev[0].wait_connected(timeout=30)
  2649. status = dev[0].get_status()
  2650. if status['bssid'] != apdev[0]['bssid']:
  2651. raise Exception("Unexpected BSSID")
  2652. def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
  2653. """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
  2654. ssid = "test-wps-conf"
  2655. hostapd.add_ap(apdev[0]['ifname'],
  2656. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2657. "wpa_passphrase": "12345678", "wpa": "2",
  2658. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2659. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2660. hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
  2661. try:
  2662. dev[0].request("STA_AUTOCONNECT 0")
  2663. dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
  2664. logger.info("WPS provisioning step")
  2665. hapd.request("WPS_PBC")
  2666. dev[0].dump_monitor()
  2667. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  2668. dev[0].wait_connected(timeout=30)
  2669. status = dev[0].get_status()
  2670. if status['bssid'] != apdev[0]['bssid']:
  2671. raise Exception("Unexpected BSSID")
  2672. finally:
  2673. dev[0].request("STA_AUTOCONNECT 1")
  2674. def test_ap_wps_from_event(dev, apdev):
  2675. """WPS PBC event on AP to enable PBC"""
  2676. ssid = "test-wps-conf"
  2677. hapd = hostapd.add_ap(apdev[0]['ifname'],
  2678. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2679. "wpa_passphrase": "12345678", "wpa": "2",
  2680. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2681. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  2682. dev[0].dump_monitor()
  2683. hapd.dump_monitor()
  2684. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  2685. ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
  2686. if ev is None:
  2687. raise Exception("No WPS-ENROLLEE-SEEN event on AP")
  2688. vals = ev.split(' ')
  2689. if vals[1] != dev[0].p2p_interface_addr():
  2690. raise Exception("Unexpected enrollee address: " + vals[1])
  2691. if vals[5] != '4':
  2692. raise Exception("Unexpected Device Password Id: " + vals[5])
  2693. hapd.request("WPS_PBC")
  2694. dev[0].wait_connected(timeout=30)
  2695. def test_ap_wps_ap_scan_2(dev, apdev):
  2696. """AP_SCAN 2 for WPS"""
  2697. ssid = "test-wps-conf"
  2698. hapd = hostapd.add_ap(apdev[0]['ifname'],
  2699. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2700. "wpa_passphrase": "12345678", "wpa": "2",
  2701. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2702. hapd.request("WPS_PBC")
  2703. wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
  2704. wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
  2705. if "OK" not in wpas.request("AP_SCAN 2"):
  2706. raise Exception("Failed to set AP_SCAN 2")
  2707. wpas.flush_scan_cache()
  2708. wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
  2709. wpas.request("WPS_PBC " + apdev[0]['bssid'])
  2710. ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
  2711. if ev is None:
  2712. raise Exception("WPS-SUCCESS event timed out")
  2713. wpas.wait_connected(timeout=30)
  2714. wpas.request("DISCONNECT")
  2715. wpas.request("BSS_FLUSH 0")
  2716. wpas.dump_monitor()
  2717. wpas.request("REASSOCIATE")
  2718. wpas.wait_connected(timeout=30)
  2719. def test_ap_wps_eapol_workaround(dev, apdev):
  2720. """EAPOL workaround code path for 802.1X header length mismatch"""
  2721. ssid = "test-wps"
  2722. hostapd.add_ap(apdev[0]['ifname'],
  2723. { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
  2724. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2725. bssid = apdev[0]['bssid']
  2726. hapd.request("SET ext_eapol_frame_io 1")
  2727. dev[0].request("SET ext_eapol_frame_io 1")
  2728. hapd.request("WPS_PBC")
  2729. dev[0].request("WPS_PBC")
  2730. ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
  2731. if ev is None:
  2732. raise Exception("Timeout on EAPOL-TX from hostapd")
  2733. res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
  2734. if "OK" not in res:
  2735. raise Exception("EAPOL_RX to wpa_supplicant failed")
  2736. def test_ap_wps_iteration(dev, apdev):
  2737. """WPS PIN and iterate through APs without selected registrar"""
  2738. ssid = "test-wps-conf"
  2739. hapd = hostapd.add_ap(apdev[0]['ifname'],
  2740. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2741. "wpa_passphrase": "12345678", "wpa": "2",
  2742. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2743. ssid2 = "test-wps-conf2"
  2744. hapd2 = hostapd.add_ap(apdev[1]['ifname'],
  2745. { "ssid": ssid2, "eap_server": "1", "wps_state": "2",
  2746. "wpa_passphrase": "12345678", "wpa": "2",
  2747. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2748. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  2749. dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
  2750. dev[0].dump_monitor()
  2751. pin = dev[0].request("WPS_PIN any")
  2752. # Wait for iteration through all WPS APs to happen before enabling any
  2753. # Registrar.
  2754. for i in range(2):
  2755. ev = dev[0].wait_event(["Associated with"], timeout=30)
  2756. if ev is None:
  2757. raise Exception("No association seen")
  2758. ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
  2759. if ev is None:
  2760. raise Exception("No M2D from AP")
  2761. dev[0].wait_disconnected()
  2762. # Verify that each AP requested PIN
  2763. ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
  2764. if ev is None:
  2765. raise Exception("No WPS-PIN-NEEDED event from AP")
  2766. ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
  2767. if ev is None:
  2768. raise Exception("No WPS-PIN-NEEDED event from AP2")
  2769. # Provide PIN to one of the APs and verify that connection gets formed
  2770. hapd.request("WPS_PIN any " + pin)
  2771. dev[0].wait_connected(timeout=30)
  2772. def test_ap_wps_iteration_error(dev, apdev):
  2773. """WPS AP iteration on no Selected Registrar and error case with an AP"""
  2774. ssid = "test-wps-conf-pin"
  2775. hapd = hostapd.add_ap(apdev[0]['ifname'],
  2776. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2777. "wpa_passphrase": "12345678", "wpa": "2",
  2778. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  2779. "wps_independent": "1" })
  2780. hapd.request("SET ext_eapol_frame_io 1")
  2781. bssid = apdev[0]['bssid']
  2782. pin = dev[0].wps_read_pin()
  2783. dev[0].request("WPS_PIN any " + pin)
  2784. ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
  2785. if ev is None:
  2786. raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
  2787. dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
  2788. ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
  2789. if ev is None:
  2790. raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
  2791. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
  2792. if ev is None:
  2793. raise Exception("No CTRL-EVENT-EAP-STARTED")
  2794. # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
  2795. # a case with an incorrectly behaving WPS AP.
  2796. # Start the real target AP and activate registrar on it.
  2797. hapd2 = hostapd.add_ap(apdev[1]['ifname'],
  2798. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2799. "wpa_passphrase": "12345678", "wpa": "2",
  2800. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  2801. "wps_independent": "1" })
  2802. hapd2.request("WPS_PIN any " + pin)
  2803. dev[0].wait_disconnected(timeout=15)
  2804. ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
  2805. if ev is None:
  2806. raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
  2807. ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  2808. if ev is None:
  2809. raise Exception("No WPS-CRED-RECEIVED for the second AP")
  2810. dev[0].wait_connected(timeout=15)
  2811. def test_ap_wps_priority(dev, apdev):
  2812. """WPS PIN provisioning with configured AP and wps_priority"""
  2813. ssid = "test-wps-conf-pin"
  2814. hostapd.add_ap(apdev[0]['ifname'],
  2815. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2816. "wpa_passphrase": "12345678", "wpa": "2",
  2817. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2818. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2819. logger.info("WPS provisioning step")
  2820. pin = dev[0].wps_read_pin()
  2821. hapd.request("WPS_PIN any " + pin)
  2822. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  2823. dev[0].dump_monitor()
  2824. try:
  2825. dev[0].request("SET wps_priority 6")
  2826. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  2827. dev[0].wait_connected(timeout=30)
  2828. netw = dev[0].list_networks()
  2829. prio = dev[0].get_network(netw[0]['id'], 'priority')
  2830. if prio != '6':
  2831. raise Exception("Unexpected network priority: " + prio)
  2832. finally:
  2833. dev[0].request("SET wps_priority 0")
  2834. def test_ap_wps_and_non_wps(dev, apdev):
  2835. """WPS and non-WPS AP in single hostapd process"""
  2836. params = { "ssid": "wps", "eap_server": "1", "wps_state": "1" }
  2837. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  2838. params = { "ssid": "no wps" }
  2839. hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
  2840. appin = hapd.request("WPS_AP_PIN random")
  2841. if "FAIL" in appin:
  2842. raise Exception("Could not generate random AP PIN")
  2843. if appin not in hapd.request("WPS_AP_PIN get"):
  2844. raise Exception("Could not fetch current AP PIN")
  2845. if "FAIL" in hapd.request("WPS_PBC"):
  2846. raise Exception("WPS_PBC failed")
  2847. if "FAIL" in hapd.request("WPS_CANCEL"):
  2848. raise Exception("WPS_CANCEL failed")
  2849. def test_ap_wps_init_oom(dev, apdev):
  2850. """Initial AP configuration and OOM during PSK generation"""
  2851. ssid = "test-wps"
  2852. params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
  2853. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  2854. with alloc_fail(hapd, 1, "base64_encode;wps_build_cred"):
  2855. pin = dev[0].wps_read_pin()
  2856. hapd.request("WPS_PIN any " + pin)
  2857. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  2858. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  2859. dev[0].wait_disconnected()
  2860. hapd.request("WPS_PIN any " + pin)
  2861. dev[0].wait_connected(timeout=30)
  2862. def test_ap_wps_er_oom(dev, apdev):
  2863. """WPS ER OOM in XML processing"""
  2864. try:
  2865. _test_ap_wps_er_oom(dev, apdev)
  2866. finally:
  2867. dev[0].request("WPS_ER_STOP")
  2868. dev[1].request("WPS_CANCEL")
  2869. dev[0].request("DISCONNECT")
  2870. def _test_ap_wps_er_oom(dev, apdev):
  2871. ssid = "wps-er-ap-config"
  2872. ap_pin = "12345670"
  2873. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  2874. hostapd.add_ap(apdev[0]['ifname'],
  2875. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2876. "wpa_passphrase": "12345678", "wpa": "2",
  2877. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  2878. "device_name": "Wireless AP", "manufacturer": "Company",
  2879. "model_name": "WAP", "model_number": "123",
  2880. "serial_number": "12345", "device_type": "6-0050F204-1",
  2881. "os_version": "01020300",
  2882. "config_methods": "label push_button",
  2883. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  2884. dev[0].connect(ssid, psk="12345678", scan_freq="2412")
  2885. with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
  2886. dev[0].request("WPS_ER_START ifname=lo")
  2887. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
  2888. if ev is not None:
  2889. raise Exception("Unexpected AP discovery")
  2890. dev[0].request("WPS_ER_STOP")
  2891. dev[0].request("WPS_ER_START ifname=lo")
  2892. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
  2893. if ev is None:
  2894. raise Exception("AP discovery timed out")
  2895. dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
  2896. with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
  2897. dev[1].request("WPS_PBC " + apdev[0]['bssid'])
  2898. ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
  2899. if ev is None:
  2900. raise Exception("PBC scan failed")
  2901. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
  2902. if ev is None:
  2903. raise Exception("Enrollee discovery timed out")
  2904. def test_ap_wps_er_init_oom(dev, apdev):
  2905. """WPS ER and OOM during init"""
  2906. try:
  2907. _test_ap_wps_er_init_oom(dev, apdev)
  2908. finally:
  2909. dev[0].request("WPS_ER_STOP")
  2910. def _test_ap_wps_er_init_oom(dev, apdev):
  2911. with alloc_fail(dev[0], 1, "wps_er_init"):
  2912. if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
  2913. raise Exception("WPS_ER_START succeeded during OOM")
  2914. with alloc_fail(dev[0], 1, "http_server_init"):
  2915. if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
  2916. raise Exception("WPS_ER_START succeeded during OOM")
  2917. with alloc_fail(dev[0], 2, "http_server_init"):
  2918. if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
  2919. raise Exception("WPS_ER_START succeeded during OOM")
  2920. with alloc_fail(dev[0], 1, "eloop_register_sock;wps_er_ssdp_init"):
  2921. if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
  2922. raise Exception("WPS_ER_START succeeded during OOM")
  2923. with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
  2924. if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
  2925. raise Exception("WPS_ER_START succeeded during os_get_random failure")
  2926. def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
  2927. """WPS events and wpa_cli action script"""
  2928. logdir = os.path.abspath(test_params['logdir'])
  2929. pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
  2930. logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
  2931. actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
  2932. with open(actionfile, 'w') as f:
  2933. f.write('#!/bin/sh\n')
  2934. f.write('echo $* >> %s\n' % logfile)
  2935. # Kill the process and wait some time before returning to allow all the
  2936. # pending events to be processed with some of this happening after the
  2937. # eloop SIGALRM signal has been scheduled.
  2938. f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
  2939. os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
  2940. stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
  2941. ssid = "test-wps-conf"
  2942. hostapd.add_ap(apdev[0]['ifname'],
  2943. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  2944. "wpa_passphrase": "12345678", "wpa": "2",
  2945. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  2946. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  2947. prg = os.path.join(test_params['logdir'],
  2948. 'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
  2949. if not os.path.exists(prg):
  2950. prg = '../../wpa_supplicant/wpa_cli'
  2951. arg = [ prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile ]
  2952. subprocess.call(arg)
  2953. arg = [ 'ps', 'ax' ]
  2954. cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
  2955. out = cmd.communicate()[0]
  2956. cmd.wait()
  2957. logger.debug("Processes:\n" + out)
  2958. if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
  2959. raise Exception("Did not see wpa_cli running")
  2960. hapd.request("WPS_PIN any 12345670")
  2961. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  2962. dev[0].dump_monitor()
  2963. dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
  2964. dev[0].wait_connected(timeout=30)
  2965. for i in range(30):
  2966. if not os.path.exists(pidfile):
  2967. break
  2968. time.sleep(0.1)
  2969. if not os.path.exists(logfile):
  2970. raise Exception("wpa_cli action results file not found")
  2971. with open(logfile, 'r') as f:
  2972. res = f.read()
  2973. if "WPS-SUCCESS" not in res:
  2974. raise Exception("WPS-SUCCESS event not seen in action file")
  2975. arg = [ 'ps', 'ax' ]
  2976. cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
  2977. out = cmd.communicate()[0]
  2978. cmd.wait()
  2979. logger.debug("Remaining processes:\n" + out)
  2980. if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
  2981. raise Exception("wpa_cli still running")
  2982. if os.path.exists(pidfile):
  2983. raise Exception("PID file not removed")
  2984. def test_ap_wps_er_ssdp_proto(dev, apdev):
  2985. """WPS ER SSDP protocol testing"""
  2986. try:
  2987. _test_ap_wps_er_ssdp_proto(dev, apdev)
  2988. finally:
  2989. dev[0].request("WPS_ER_STOP")
  2990. def _test_ap_wps_er_ssdp_proto(dev, apdev):
  2991. socket.setdefaulttimeout(1)
  2992. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  2993. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  2994. sock.bind(("239.255.255.250", 1900))
  2995. if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
  2996. raise Exception("Invalid filter accepted")
  2997. if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
  2998. raise Exception("WPS_ER_START with filter failed")
  2999. (msg,addr) = sock.recvfrom(1000)
  3000. logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
  3001. if "M-SEARCH" not in msg:
  3002. raise Exception("Not an M-SEARCH")
  3003. sock.sendto("FOO", addr)
  3004. time.sleep(0.1)
  3005. dev[0].request("WPS_ER_STOP")
  3006. dev[0].request("WPS_ER_START ifname=lo")
  3007. (msg,addr) = sock.recvfrom(1000)
  3008. logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
  3009. if "M-SEARCH" not in msg:
  3010. raise Exception("Not an M-SEARCH")
  3011. sock.sendto("FOO", addr)
  3012. sock.sendto("HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
  3013. sock.sendto("HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
  3014. sock.sendto("HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
  3015. sock.sendto("HTTP/1.1 200 OK\r\ncache-control: foo=1\r\n\r\n", addr)
  3016. sock.sendto("HTTP/1.1 200 OK\r\ncache-control: max-age=1\r\n\r\n", addr)
  3017. sock.sendto("HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
  3018. sock.sendto("HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
  3019. sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid:\r\n\r\n", addr)
  3020. sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: \r\n\r\n", addr)
  3021. sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: foo\r\n\r\n", addr)
  3022. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
  3023. 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)
  3024. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\n\r\n", addr)
  3025. with alloc_fail(dev[0], 1, "wps_er_ap_add"):
  3026. 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)
  3027. time.sleep(0.1)
  3028. with alloc_fail(dev[0], 2, "wps_er_ap_add"):
  3029. 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)
  3030. time.sleep(0.1)
  3031. # Add an AP with bogus URL
  3032. 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)
  3033. # Update timeout on AP without updating URL
  3034. 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)
  3035. ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
  3036. if ev is None:
  3037. raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
  3038. # Add an AP with a valid URL (but no server listing to it)
  3039. 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)
  3040. ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
  3041. if ev is None:
  3042. raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
  3043. sock.close()
  3044. wps_event_url = None
  3045. def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
  3046. udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
  3047. payload = '''<?xml version="1.0"?>
  3048. <root xmlns="urn:schemas-upnp-org:device-1-0">
  3049. <specVersion>
  3050. <major>1</major>
  3051. <minor>0</minor>
  3052. </specVersion>
  3053. <device>
  3054. <deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
  3055. <friendlyName>WPS Access Point</friendlyName>
  3056. <manufacturer>Company</manufacturer>
  3057. <modelName>WAP</modelName>
  3058. <modelNumber>123</modelNumber>
  3059. <serialNumber>12345</serialNumber>
  3060. '''
  3061. if udn:
  3062. payload += '<UDN>' + udn + '</UDN>'
  3063. payload += '''<serviceList>
  3064. <service>
  3065. <serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
  3066. <serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
  3067. <SCPDURL>wps_scpd.xml</SCPDURL>
  3068. '''
  3069. if controlURL:
  3070. payload += '<controlURL>' + controlURL + '</controlURL>\n'
  3071. if eventSubURL:
  3072. payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
  3073. payload += '''</service>
  3074. </serviceList>
  3075. </device>
  3076. </root>
  3077. '''
  3078. hdr = 'HTTP/1.1 200 OK\r\n' + \
  3079. 'Content-Type: text/xml; charset="utf-8"\r\n' + \
  3080. 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
  3081. 'Connection: close\r\n' + \
  3082. 'Content-Length: ' + str(len(payload)) + '\r\n' + \
  3083. 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
  3084. return hdr + payload
  3085. def gen_wps_control(payload_override=None):
  3086. payload = '''<?xml version="1.0"?>
  3087. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  3088. <s:Body>
  3089. <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
  3090. <NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
  3091. Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
  3092. +FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
  3093. 7zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
  3094. KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
  3095. AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
  3096. AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
  3097. AAYANyoAASA=
  3098. </NewDeviceInfo>
  3099. </u:GetDeviceInfoResponse>
  3100. </s:Body>
  3101. </s:Envelope>
  3102. '''
  3103. if payload_override:
  3104. payload = payload_override
  3105. hdr = 'HTTP/1.1 200 OK\r\n' + \
  3106. 'Content-Type: text/xml; charset="utf-8"\r\n' + \
  3107. 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
  3108. 'Connection: close\r\n' + \
  3109. 'Content-Length: ' + str(len(payload)) + '\r\n' + \
  3110. 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
  3111. return hdr + payload
  3112. def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
  3113. payload = ""
  3114. hdr = 'HTTP/1.1 200 OK\r\n' + \
  3115. 'Content-Type: text/xml; charset="utf-8"\r\n' + \
  3116. 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
  3117. 'Connection: close\r\n' + \
  3118. 'Content-Length: ' + str(len(payload)) + '\r\n'
  3119. if sid:
  3120. hdr += 'SID: ' + sid + '\r\n'
  3121. hdr += 'Timeout: Second-1801\r\n' + \
  3122. 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
  3123. return hdr + payload
  3124. class WPSAPHTTPServer(SocketServer.StreamRequestHandler):
  3125. def handle(self):
  3126. data = self.rfile.readline().strip()
  3127. logger.info("HTTP server received: " + data)
  3128. while True:
  3129. hdr = self.rfile.readline().strip()
  3130. if len(hdr) == 0:
  3131. break
  3132. logger.info("HTTP header: " + hdr)
  3133. if "CALLBACK:" in hdr:
  3134. global wps_event_url
  3135. wps_event_url = hdr.split(' ')[1].strip('<>')
  3136. if "GET /foo.xml" in data:
  3137. self.handle_upnp_info()
  3138. elif "POST /wps_control" in data:
  3139. self.handle_wps_control()
  3140. elif "SUBSCRIBE /wps_event" in data:
  3141. self.handle_wps_event()
  3142. else:
  3143. self.handle_others(data)
  3144. def handle_upnp_info(self):
  3145. self.wfile.write(gen_upnp_info())
  3146. def handle_wps_control(self):
  3147. self.wfile.write(gen_wps_control())
  3148. def handle_wps_event(self):
  3149. self.wfile.write(gen_wps_event())
  3150. def handle_others(self, data):
  3151. logger.info("Ignore HTTP request: " + data)
  3152. class MyTCPServer(SocketServer.TCPServer):
  3153. def __init__(self, addr, handler):
  3154. self.allow_reuse_address = True
  3155. SocketServer.TCPServer.__init__(self, addr, handler)
  3156. def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
  3157. location_url=None):
  3158. socket.setdefaulttimeout(1)
  3159. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  3160. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  3161. sock.bind(("239.255.255.250", 1900))
  3162. dev.request("WPS_ER_START ifname=lo")
  3163. for i in range(100):
  3164. (msg,addr) = sock.recvfrom(1000)
  3165. logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
  3166. if "M-SEARCH" in msg:
  3167. break
  3168. if not wait_m_search:
  3169. raise Exception("Not an M-SEARCH")
  3170. if i == 99:
  3171. raise Exception("No M-SEARCH seen")
  3172. # Add an AP with a valid URL and server listing to it
  3173. server = MyTCPServer(("127.0.0.1", 12345), http_server)
  3174. if not location_url:
  3175. location_url = 'http://127.0.0.1:12345/foo.xml'
  3176. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:%s\r\ncache-control:max-age=%d\r\n\r\n" % (location_url, max_age), addr)
  3177. server.timeout = 1
  3178. return server,sock
  3179. def wps_er_stop(dev, sock, server, on_alloc_fail=False):
  3180. sock.close()
  3181. server.server_close()
  3182. if on_alloc_fail:
  3183. done = False
  3184. for i in range(50):
  3185. res = dev.request("GET_ALLOC_FAIL")
  3186. if res.startswith("0:"):
  3187. done = True
  3188. break
  3189. time.sleep(0.1)
  3190. if not done:
  3191. raise Exception("No allocation failure reported")
  3192. else:
  3193. ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
  3194. if ev is None:
  3195. raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
  3196. dev.request("WPS_ER_STOP")
  3197. def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
  3198. try:
  3199. uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
  3200. server,sock = wps_er_start(dev, handler, location_url=location_url)
  3201. global wps_event_url
  3202. wps_event_url = None
  3203. server.handle_request()
  3204. server.handle_request()
  3205. server.handle_request()
  3206. server.server_close()
  3207. if no_event_url:
  3208. if wps_event_url:
  3209. raise Exception("Received event URL unexpectedly")
  3210. return
  3211. if wps_event_url is None:
  3212. raise Exception("Did not get event URL")
  3213. logger.info("Event URL: " + wps_event_url)
  3214. finally:
  3215. dev.request("WPS_ER_STOP")
  3216. def send_wlanevent(url, uuid, data):
  3217. conn = httplib.HTTPConnection(url.netloc)
  3218. payload = '''<?xml version="1.0" encoding="utf-8"?>
  3219. <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
  3220. <e:property><STAStatus>1</STAStatus></e:property>
  3221. <e:property><APStatus>1</APStatus></e:property>
  3222. <e:property><WLANEvent>'''
  3223. payload += base64.b64encode(data)
  3224. payload += '</WLANEvent></e:property></e:propertyset>'
  3225. headers = { "Content-type": 'text/xml; charset="utf-8"',
  3226. "Server": "Unspecified, UPnP/1.0, Unspecified",
  3227. "HOST": url.netloc,
  3228. "NT": "upnp:event",
  3229. "SID": "uuid:" + uuid,
  3230. "SEQ": "0",
  3231. "Content-Length": str(len(payload)) }
  3232. conn.request("NOTIFY", url.path, payload, headers)
  3233. resp = conn.getresponse()
  3234. if resp.status != 200:
  3235. raise Exception("Unexpected HTTP response: %d" % resp.status)
  3236. def test_ap_wps_er_http_proto(dev, apdev):
  3237. """WPS ER HTTP protocol testing"""
  3238. try:
  3239. _test_ap_wps_er_http_proto(dev, apdev)
  3240. finally:
  3241. dev[0].request("WPS_ER_STOP")
  3242. def _test_ap_wps_er_http_proto(dev, apdev):
  3243. uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
  3244. server,sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
  3245. global wps_event_url
  3246. wps_event_url = None
  3247. server.handle_request()
  3248. server.handle_request()
  3249. server.handle_request()
  3250. server.server_close()
  3251. if wps_event_url is None:
  3252. raise Exception("Did not get event URL")
  3253. logger.info("Event URL: " + wps_event_url)
  3254. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
  3255. if ev is None:
  3256. raise Exception("No WPS-ER-AP-ADD event")
  3257. if uuid not in ev:
  3258. raise Exception("UUID mismatch")
  3259. sock.close()
  3260. logger.info("Valid Probe Request notification")
  3261. url = urlparse.urlparse(wps_event_url)
  3262. conn = httplib.HTTPConnection(url.netloc)
  3263. payload = '''<?xml version="1.0" encoding="utf-8"?>
  3264. <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
  3265. <e:property><STAStatus>1</STAStatus></e:property>
  3266. <e:property><APStatus>1</APStatus></e:property>
  3267. <e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
  3268. EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
  3269. RGV2aWNlIEEQSQAGADcqAAEg
  3270. </WLANEvent></e:property>
  3271. </e:propertyset>
  3272. '''
  3273. headers = { "Content-type": 'text/xml; charset="utf-8"',
  3274. "Server": "Unspecified, UPnP/1.0, Unspecified",
  3275. "HOST": url.netloc,
  3276. "NT": "upnp:event",
  3277. "SID": "uuid:" + uuid,
  3278. "SEQ": "0",
  3279. "Content-Length": str(len(payload)) }
  3280. conn.request("NOTIFY", url.path, payload, headers)
  3281. resp = conn.getresponse()
  3282. if resp.status != 200:
  3283. raise Exception("Unexpected HTTP response: %d" % resp.status)
  3284. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
  3285. if ev is None:
  3286. raise Exception("No WPS-ER-ENROLLEE-ADD event")
  3287. if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
  3288. raise Exception("No Enrollee UUID match")
  3289. logger.info("Incorrect event URL AP id")
  3290. conn = httplib.HTTPConnection(url.netloc)
  3291. conn.request("NOTIFY", url.path + '123', payload, headers)
  3292. resp = conn.getresponse()
  3293. if resp.status != 404:
  3294. raise Exception("Unexpected HTTP response: %d" % resp.status)
  3295. logger.info("Missing AP id")
  3296. conn = httplib.HTTPConnection(url.netloc)
  3297. conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
  3298. payload, headers)
  3299. time.sleep(0.1)
  3300. logger.info("Incorrect event URL event id")
  3301. conn = httplib.HTTPConnection(url.netloc)
  3302. conn.request("NOTIFY", '/event/123456789/123', payload, headers)
  3303. time.sleep(0.1)
  3304. logger.info("Incorrect event URL prefix")
  3305. conn = httplib.HTTPConnection(url.netloc)
  3306. conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
  3307. resp = conn.getresponse()
  3308. if resp.status != 404:
  3309. raise Exception("Unexpected HTTP response: %d" % resp.status)
  3310. logger.info("Unsupported request")
  3311. conn = httplib.HTTPConnection(url.netloc)
  3312. conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
  3313. resp = conn.getresponse()
  3314. if resp.status != 501:
  3315. raise Exception("Unexpected HTTP response: %d" % resp.status)
  3316. logger.info("Unsupported request and OOM")
  3317. with alloc_fail(dev[0], 1, "wps_er_http_req"):
  3318. conn = httplib.HTTPConnection(url.netloc)
  3319. conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
  3320. time.sleep(0.5)
  3321. logger.info("Too short WLANEvent")
  3322. data = '\x00'
  3323. send_wlanevent(url, uuid, data)
  3324. logger.info("Invalid WLANEventMAC")
  3325. data = '\x00qwertyuiopasdfghjklzxcvbnm'
  3326. send_wlanevent(url, uuid, data)
  3327. logger.info("Unknown WLANEventType")
  3328. data = '\xff02:00:00:00:00:00'
  3329. send_wlanevent(url, uuid, data)
  3330. logger.info("Probe Request notification without any attributes")
  3331. data = '\x0102:00:00:00:00:00'
  3332. send_wlanevent(url, uuid, data)
  3333. logger.info("Probe Request notification with invalid attribute")
  3334. data = '\x0102:00:00:00:00:00\xff'
  3335. send_wlanevent(url, uuid, data)
  3336. logger.info("EAP message without any attributes")
  3337. data = '\x0202:00:00:00:00:00'
  3338. send_wlanevent(url, uuid, data)
  3339. logger.info("EAP message with invalid attribute")
  3340. data = '\x0202:00:00:00:00:00\xff'
  3341. send_wlanevent(url, uuid, data)
  3342. logger.info("EAP message from new STA and not M1")
  3343. data = '\x0202:ff:ff:ff:ff:ff' + '\x10\x22\x00\x01\x05'
  3344. send_wlanevent(url, uuid, data)
  3345. logger.info("EAP message: M1")
  3346. data = '\x0202:00:00:00:00:00'
  3347. data += '\x10\x22\x00\x01\x04'
  3348. data += '\x10\x47\x00\x10' + 16*'\x00'
  3349. data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
  3350. data += '\x10\x1a\x00\x10' + 16*'\x00'
  3351. data += '\x10\x32\x00\xc0' + 192*'\x00'
  3352. data += '\x10\x04\x00\x02\x00\x00'
  3353. data += '\x10\x10\x00\x02\x00\x00'
  3354. data += '\x10\x0d\x00\x01\x00'
  3355. data += '\x10\x08\x00\x02\x00\x00'
  3356. data += '\x10\x44\x00\x01\x00'
  3357. data += '\x10\x21\x00\x00'
  3358. data += '\x10\x23\x00\x00'
  3359. data += '\x10\x24\x00\x00'
  3360. data += '\x10\x42\x00\x00'
  3361. data += '\x10\x54\x00\x08' + 8*'\x00'
  3362. data += '\x10\x11\x00\x00'
  3363. data += '\x10\x3c\x00\x01\x00'
  3364. data += '\x10\x02\x00\x02\x00\x00'
  3365. data += '\x10\x12\x00\x02\x00\x00'
  3366. data += '\x10\x09\x00\x02\x00\x00'
  3367. data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
  3368. m1 = data
  3369. send_wlanevent(url, uuid, data)
  3370. logger.info("EAP message: WSC_ACK")
  3371. data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0d'
  3372. send_wlanevent(url, uuid, data)
  3373. logger.info("EAP message: M1")
  3374. send_wlanevent(url, uuid, m1)
  3375. logger.info("EAP message: WSC_NACK")
  3376. data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0e'
  3377. send_wlanevent(url, uuid, data)
  3378. logger.info("EAP message: M1 - Too long attribute values")
  3379. data = '\x0202:00:00:00:00:00'
  3380. data += '\x10\x11\x00\x21' + 33*'\x00'
  3381. data += '\x10\x45\x00\x21' + 33*'\x00'
  3382. data += '\x10\x42\x00\x21' + 33*'\x00'
  3383. data += '\x10\x24\x00\x21' + 33*'\x00'
  3384. data += '\x10\x23\x00\x21' + 33*'\x00'
  3385. data += '\x10\x21\x00\x41' + 65*'\x00'
  3386. data += '\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
  3387. send_wlanevent(url, uuid, data)
  3388. logger.info("EAP message: M1 missing UUID-E")
  3389. data = '\x0202:00:00:00:00:00'
  3390. data += '\x10\x22\x00\x01\x04'
  3391. send_wlanevent(url, uuid, data)
  3392. logger.info("EAP message: M1 missing MAC Address")
  3393. data += '\x10\x47\x00\x10' + 16*'\x00'
  3394. send_wlanevent(url, uuid, data)
  3395. logger.info("EAP message: M1 missing Enrollee Nonce")
  3396. data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
  3397. send_wlanevent(url, uuid, data)
  3398. logger.info("EAP message: M1 missing Public Key")
  3399. data += '\x10\x1a\x00\x10' + 16*'\x00'
  3400. send_wlanevent(url, uuid, data)
  3401. logger.info("EAP message: M1 missing Authentication Type flags")
  3402. data += '\x10\x32\x00\xc0' + 192*'\x00'
  3403. send_wlanevent(url, uuid, data)
  3404. logger.info("EAP message: M1 missing Encryption Type Flags")
  3405. data += '\x10\x04\x00\x02\x00\x00'
  3406. send_wlanevent(url, uuid, data)
  3407. logger.info("EAP message: M1 missing Connection Type flags")
  3408. data += '\x10\x10\x00\x02\x00\x00'
  3409. send_wlanevent(url, uuid, data)
  3410. logger.info("EAP message: M1 missing Config Methods")
  3411. data += '\x10\x0d\x00\x01\x00'
  3412. send_wlanevent(url, uuid, data)
  3413. logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
  3414. data += '\x10\x08\x00\x02\x00\x00'
  3415. send_wlanevent(url, uuid, data)
  3416. logger.info("EAP message: M1 missing Manufacturer")
  3417. data += '\x10\x44\x00\x01\x00'
  3418. send_wlanevent(url, uuid, data)
  3419. logger.info("EAP message: M1 missing Model Name")
  3420. data += '\x10\x21\x00\x00'
  3421. send_wlanevent(url, uuid, data)
  3422. logger.info("EAP message: M1 missing Model Number")
  3423. data += '\x10\x23\x00\x00'
  3424. send_wlanevent(url, uuid, data)
  3425. logger.info("EAP message: M1 missing Serial Number")
  3426. data += '\x10\x24\x00\x00'
  3427. send_wlanevent(url, uuid, data)
  3428. logger.info("EAP message: M1 missing Primary Device Type")
  3429. data += '\x10\x42\x00\x00'
  3430. send_wlanevent(url, uuid, data)
  3431. logger.info("EAP message: M1 missing Device Name")
  3432. data += '\x10\x54\x00\x08' + 8*'\x00'
  3433. send_wlanevent(url, uuid, data)
  3434. logger.info("EAP message: M1 missing RF Bands")
  3435. data += '\x10\x11\x00\x00'
  3436. send_wlanevent(url, uuid, data)
  3437. logger.info("EAP message: M1 missing Association State")
  3438. data += '\x10\x3c\x00\x01\x00'
  3439. send_wlanevent(url, uuid, data)
  3440. logger.info("EAP message: M1 missing Device Password ID")
  3441. data += '\x10\x02\x00\x02\x00\x00'
  3442. send_wlanevent(url, uuid, data)
  3443. logger.info("EAP message: M1 missing Configuration Error")
  3444. data += '\x10\x12\x00\x02\x00\x00'
  3445. send_wlanevent(url, uuid, data)
  3446. logger.info("EAP message: M1 missing OS Version")
  3447. data += '\x10\x09\x00\x02\x00\x00'
  3448. send_wlanevent(url, uuid, data)
  3449. logger.info("Check max concurrent requests")
  3450. addr = (url.hostname, url.port)
  3451. socks = {}
  3452. for i in range(20):
  3453. socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
  3454. socket.IPPROTO_TCP)
  3455. socks[i].connect(addr)
  3456. for i in range(20):
  3457. socks[i].send("GET / HTTP/1.1\r\n\r\n")
  3458. count = 0
  3459. for i in range(20):
  3460. try:
  3461. res = socks[i].recv(100)
  3462. if "HTTP/1" in res:
  3463. count += 1
  3464. except:
  3465. pass
  3466. socks[i].close()
  3467. logger.info("%d concurrent HTTP GET operations returned response" % count)
  3468. if count < 10:
  3469. raise Exception("Too few concurrent HTTP connections accepted")
  3470. logger.info("OOM in HTTP server")
  3471. for func in [ "http_request_init", "httpread_create",
  3472. "eloop_register_timeout;httpread_create",
  3473. "eloop_register_sock;httpread_create",
  3474. "httpread_hdr_analyze" ]:
  3475. with alloc_fail(dev[0], 1, func):
  3476. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
  3477. socket.IPPROTO_TCP)
  3478. sock.connect(addr)
  3479. sock.send("GET / HTTP/1.1\r\n\r\n")
  3480. try:
  3481. sock.recv(100)
  3482. except:
  3483. pass
  3484. sock.close()
  3485. logger.info("Invalid HTTP header")
  3486. for req in [ " GET / HTTP/1.1\r\n\r\n",
  3487. "HTTP/1.1 200 OK\r\n\r\n",
  3488. "HTTP/\r\n\r\n",
  3489. "GET %%a%aa% HTTP/1.1\r\n\r\n",
  3490. "GET / HTTP/1.1\r\n FOO\r\n\r\n",
  3491. "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
  3492. "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
  3493. "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
  3494. "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
  3495. "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
  3496. "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra" ]:
  3497. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
  3498. socket.IPPROTO_TCP)
  3499. sock.settimeout(0.1)
  3500. sock.connect(addr)
  3501. sock.send(req)
  3502. try:
  3503. sock.recv(100)
  3504. except:
  3505. pass
  3506. sock.close()
  3507. with alloc_fail(dev[0], 2, "httpread_read_handler"):
  3508. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
  3509. socket.IPPROTO_TCP)
  3510. sock.connect(addr)
  3511. sock.send("NOTIFY / HTTP/1.1\r\n\r\n" + 4500*'a')
  3512. try:
  3513. sock.recv(100)
  3514. except:
  3515. pass
  3516. sock.close()
  3517. conn = httplib.HTTPConnection(url.netloc)
  3518. payload = '<foo'
  3519. headers = { "Content-type": 'text/xml; charset="utf-8"',
  3520. "Server": "Unspecified, UPnP/1.0, Unspecified",
  3521. "HOST": url.netloc,
  3522. "NT": "upnp:event",
  3523. "SID": "uuid:" + uuid,
  3524. "SEQ": "0",
  3525. "Content-Length": str(len(payload)) }
  3526. conn.request("NOTIFY", url.path, payload, headers)
  3527. resp = conn.getresponse()
  3528. if resp.status != 200:
  3529. raise Exception("Unexpected HTTP response: %d" % resp.status)
  3530. conn = httplib.HTTPConnection(url.netloc)
  3531. payload = '<WLANEvent foo></WLANEvent>'
  3532. headers = { "Content-type": 'text/xml; charset="utf-8"',
  3533. "Server": "Unspecified, UPnP/1.0, Unspecified",
  3534. "HOST": url.netloc,
  3535. "NT": "upnp:event",
  3536. "SID": "uuid:" + uuid,
  3537. "SEQ": "0",
  3538. "Content-Length": str(len(payload)) }
  3539. conn.request("NOTIFY", url.path, payload, headers)
  3540. resp = conn.getresponse()
  3541. if resp.status != 200:
  3542. raise Exception("Unexpected HTTP response: %d" % resp.status)
  3543. with alloc_fail(dev[0], 1, "xml_get_first_item"):
  3544. send_wlanevent(url, uuid, '')
  3545. with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
  3546. send_wlanevent(url, uuid, 'foo')
  3547. for func in [ "wps_init",
  3548. "wps_process_manufacturer",
  3549. "wps_process_model_name",
  3550. "wps_process_model_number",
  3551. "wps_process_serial_number",
  3552. "wps_process_dev_name" ]:
  3553. with alloc_fail(dev[0], 1, func):
  3554. send_wlanevent(url, uuid, m1)
  3555. def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
  3556. """WPS ER HTTP protocol testing - no eventSubURL"""
  3557. class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
  3558. def handle_upnp_info(self):
  3559. self.wfile.write(gen_upnp_info(eventSubURL=None))
  3560. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
  3561. no_event_url=True)
  3562. def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
  3563. """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
  3564. class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
  3565. def handle_upnp_info(self):
  3566. self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
  3567. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
  3568. no_event_url=True)
  3569. def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
  3570. """WPS ER HTTP protocol testing - subscribe OOM"""
  3571. try:
  3572. _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
  3573. finally:
  3574. dev[0].request("WPS_ER_STOP")
  3575. def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
  3576. tests = [ (1, "http_client_url_parse"),
  3577. (1, "wpabuf_alloc;wps_er_subscribe"),
  3578. (1, "http_client_addr"),
  3579. (1, "eloop_register_sock;http_client_addr"),
  3580. (1, "eloop_register_timeout;http_client_addr") ]
  3581. for count,func in tests:
  3582. with alloc_fail(dev[0], count, func):
  3583. server,sock = wps_er_start(dev[0], WPSAPHTTPServer)
  3584. server.handle_request()
  3585. server.handle_request()
  3586. wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
  3587. def test_ap_wps_er_http_proto_no_sid(dev, apdev):
  3588. """WPS ER HTTP protocol testing - no SID"""
  3589. class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
  3590. def handle_wps_event(self):
  3591. self.wfile.write(gen_wps_event(sid=None))
  3592. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
  3593. def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
  3594. """WPS ER HTTP protocol testing - invalid SID - no UUID"""
  3595. class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
  3596. def handle_wps_event(self):
  3597. self.wfile.write(gen_wps_event(sid='FOO'))
  3598. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
  3599. def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
  3600. """WPS ER HTTP protocol testing - invalid SID UUID"""
  3601. class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
  3602. def handle_wps_event(self):
  3603. self.wfile.write(gen_wps_event(sid='uuid:FOO'))
  3604. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
  3605. def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
  3606. """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
  3607. class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
  3608. def handle_wps_event(self):
  3609. payload = ""
  3610. hdr = 'HTTP/1.1 404 Not Found\r\n' + \
  3611. 'Content-Type: text/xml; charset="utf-8"\r\n' + \
  3612. 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
  3613. 'Connection: close\r\n' + \
  3614. 'Content-Length: ' + str(len(payload)) + '\r\n' + \
  3615. 'Timeout: Second-1801\r\n' + \
  3616. 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
  3617. self.wfile.write(hdr + payload)
  3618. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
  3619. def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
  3620. """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
  3621. class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
  3622. def handle_wps_event(self):
  3623. payload = ""
  3624. hdr = 'HTTP/1.1 FOO\r\n' + \
  3625. 'Content-Type: text/xml; charset="utf-8"\r\n' + \
  3626. 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
  3627. 'Connection: close\r\n' + \
  3628. 'Content-Length: ' + str(len(payload)) + '\r\n' + \
  3629. 'Timeout: Second-1801\r\n' + \
  3630. 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
  3631. self.wfile.write(hdr + payload)
  3632. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
  3633. def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
  3634. """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
  3635. class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
  3636. def handle_wps_control(self):
  3637. payload = '''<?xml version="1.0"?>
  3638. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  3639. <s:Body>
  3640. <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
  3641. <NewDeviceInfo>Rk9P</NewDeviceInfo>
  3642. </u:GetDeviceInfoResponse>
  3643. </s:Body>
  3644. </s:Envelope>
  3645. '''
  3646. self.wfile.write(gen_wps_control(payload_override=payload))
  3647. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
  3648. def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
  3649. """WPS ER HTTP protocol testing - No device in UPnP info"""
  3650. class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
  3651. def handle_upnp_info(self):
  3652. payload = '''<?xml version="1.0"?>
  3653. <root xmlns="urn:schemas-upnp-org:device-1-0">
  3654. <specVersion>
  3655. <major>1</major>
  3656. <minor>0</minor>
  3657. </specVersion>
  3658. </root>
  3659. '''
  3660. hdr = 'HTTP/1.1 200 OK\r\n' + \
  3661. 'Content-Type: text/xml; charset="utf-8"\r\n' + \
  3662. 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
  3663. 'Connection: close\r\n' + \
  3664. 'Content-Length: ' + str(len(payload)) + '\r\n' + \
  3665. 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
  3666. self.wfile.write(hdr + payload)
  3667. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
  3668. def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
  3669. """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
  3670. class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
  3671. def handle_upnp_info(self):
  3672. payload = '''<?xml version="1.0"?>
  3673. <root xmlns="urn:schemas-upnp-org:device-1-0">
  3674. <specVersion>
  3675. <major>1</major>
  3676. <minor>0</minor>
  3677. </specVersion>
  3678. <device>
  3679. </device>
  3680. </root>
  3681. '''
  3682. hdr = 'HTTP/1.1 200 OK\r\n' + \
  3683. 'Content-Type: text/xml; charset="utf-8"\r\n' + \
  3684. 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
  3685. 'Connection: close\r\n' + \
  3686. 'Content-Length: ' + str(len(payload)) + '\r\n' + \
  3687. 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
  3688. self.wfile.write(hdr + payload)
  3689. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
  3690. def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
  3691. """WPS ER HTTP protocol testing - Invalid UDN UUID"""
  3692. class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
  3693. def handle_upnp_info(self):
  3694. self.wfile.write(gen_upnp_info(udn='uuid:foo'))
  3695. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
  3696. def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
  3697. """WPS ER HTTP protocol testing - no controlURL"""
  3698. class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
  3699. def handle_upnp_info(self):
  3700. self.wfile.write(gen_upnp_info(controlURL=None))
  3701. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
  3702. no_event_url=True)
  3703. def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
  3704. """WPS ER HTTP protocol testing - DNS name in controlURL"""
  3705. class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
  3706. def handle_upnp_info(self):
  3707. self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
  3708. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
  3709. no_event_url=True)
  3710. def test_ap_wps_http_timeout(dev, apdev):
  3711. """WPS AP/ER and HTTP timeout"""
  3712. try:
  3713. _test_ap_wps_http_timeout(dev, apdev)
  3714. finally:
  3715. dev[0].request("WPS_ER_STOP")
  3716. def _test_ap_wps_http_timeout(dev, apdev):
  3717. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  3718. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  3719. location = ssdp_get_location(ap_uuid)
  3720. url = urlparse.urlparse(location)
  3721. addr = (url.hostname, url.port)
  3722. logger.debug("Open HTTP connection to hostapd, but do not complete request")
  3723. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
  3724. socket.IPPROTO_TCP)
  3725. sock.connect(addr)
  3726. sock.send("G")
  3727. class DummyServer(SocketServer.StreamRequestHandler):
  3728. def handle(self):
  3729. logger.debug("DummyServer - start 31 sec wait")
  3730. time.sleep(31)
  3731. logger.debug("DummyServer - wait done")
  3732. logger.debug("Start WPS ER")
  3733. server,sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
  3734. wait_m_search=True)
  3735. logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
  3736. # This will wait for 31 seconds..
  3737. server.handle_request()
  3738. logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
  3739. try:
  3740. sock.send("ET / HTTP/1.1\r\n\r\n")
  3741. res = sock.recv(100)
  3742. sock.close()
  3743. except:
  3744. pass
  3745. def test_ap_wps_er_url_parse(dev, apdev):
  3746. """WPS ER and URL parsing special cases"""
  3747. try:
  3748. _test_ap_wps_er_url_parse(dev, apdev)
  3749. finally:
  3750. dev[0].request("WPS_ER_STOP")
  3751. def _test_ap_wps_er_url_parse(dev, apdev):
  3752. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  3753. sock.settimeout(1)
  3754. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  3755. sock.bind(("239.255.255.250", 1900))
  3756. dev[0].request("WPS_ER_START ifname=lo")
  3757. (msg,addr) = sock.recvfrom(1000)
  3758. logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
  3759. if "M-SEARCH" not in msg:
  3760. raise Exception("Not an M-SEARCH")
  3761. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1\r\ncache-control:max-age=1\r\n\r\n", addr)
  3762. ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
  3763. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1/:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
  3764. ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
  3765. sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://255.255.255.255:0/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
  3766. ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
  3767. sock.close()
  3768. def test_ap_wps_er_link_update(dev, apdev):
  3769. """WPS ER and link update special cases"""
  3770. class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
  3771. def handle_upnp_info(self):
  3772. self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
  3773. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
  3774. class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
  3775. def handle_others(self, data):
  3776. if "GET / " in data:
  3777. self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
  3778. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
  3779. location_url='http://127.0.0.1:12345')
  3780. def test_ap_wps_er_http_client(dev, apdev):
  3781. """WPS ER and HTTP client special cases"""
  3782. with alloc_fail(dev[0], 1, "http_link_update"):
  3783. run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
  3784. with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
  3785. run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
  3786. with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
  3787. run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
  3788. class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
  3789. def handle_upnp_info(self):
  3790. self.wfile.write("GET / HTTP/1.1\r\n\r\n")
  3791. run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
  3792. no_event_url=True)
  3793. def test_ap_wps_init_oom(dev, apdev):
  3794. """wps_init OOM cases"""
  3795. ssid = "test-wps"
  3796. appin = "12345670"
  3797. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  3798. "ap_pin": appin }
  3799. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  3800. pin = dev[0].wps_read_pin()
  3801. with alloc_fail(hapd, 1, "wps_init"):
  3802. hapd.request("WPS_PIN any " + pin)
  3803. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  3804. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  3805. ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
  3806. if ev is None:
  3807. raise Exception("No EAP failure reported")
  3808. dev[0].request("WPS_CANCEL")
  3809. with alloc_fail(dev[0], 2, "wps_init"):
  3810. hapd.request("WPS_PIN any " + pin)
  3811. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  3812. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  3813. ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
  3814. if ev is None:
  3815. raise Exception("No EAP failure reported")
  3816. dev[0].request("WPS_CANCEL")
  3817. with alloc_fail(dev[0], 2, "wps_init"):
  3818. hapd.request("WPS_PBC")
  3819. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  3820. dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
  3821. ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
  3822. if ev is None:
  3823. raise Exception("No EAP failure reported")
  3824. dev[0].request("WPS_CANCEL")
  3825. dev[0].dump_monitor()
  3826. new_ssid = "wps-new-ssid"
  3827. new_passphrase = "1234567890"
  3828. with alloc_fail(dev[0], 3, "wps_init"):
  3829. dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
  3830. new_passphrase, no_wait=True)
  3831. ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
  3832. if ev is None:
  3833. raise Exception("No EAP failure reported")
  3834. dev[0].flush_scan_cache()
  3835. def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
  3836. """WPS and invalid IE in Association Request frame"""
  3837. ssid = "test-wps"
  3838. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
  3839. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  3840. pin = "12345670"
  3841. hapd.request("WPS_PIN any " + pin)
  3842. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  3843. try:
  3844. dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
  3845. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  3846. for i in range(5):
  3847. ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
  3848. if ev and "vendor=14122" in ev:
  3849. break
  3850. if ev is None or "vendor=14122" not in ev:
  3851. raise Exception("EAP-WSC not started")
  3852. dev[0].request("WPS_CANCEL")
  3853. finally:
  3854. dev[0].request("VENDOR_ELEM_REMOVE 13 *")
  3855. def test_ap_wps_pbc_pin_mismatch(dev, apdev):
  3856. """WPS PBC/PIN mismatch"""
  3857. ssid = "test-wps"
  3858. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
  3859. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  3860. hapd.request("SET wps_version_number 0x10")
  3861. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  3862. hapd.request("WPS_PBC")
  3863. pin = dev[0].wps_read_pin()
  3864. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  3865. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
  3866. if ev is None:
  3867. raise Exception("Scan did not complete")
  3868. dev[0].request("WPS_CANCEL")
  3869. hapd.request("WPS_CANCEL")
  3870. dev[0].flush_scan_cache()
  3871. def test_ap_wps_ie_invalid(dev, apdev):
  3872. """WPS PIN attempt with AP that has invalid WSC IE"""
  3873. ssid = "test-wps"
  3874. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  3875. "vendor_elements": "dd050050f20410" }
  3876. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  3877. params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
  3878. hostapd.add_ap(apdev[1]['ifname'], params)
  3879. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  3880. pin = dev[0].wps_read_pin()
  3881. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  3882. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
  3883. if ev is None:
  3884. raise Exception("Scan did not complete")
  3885. dev[0].request("WPS_CANCEL")
  3886. def test_ap_wps_scan_prio_order(dev, apdev):
  3887. """WPS scan priority ordering"""
  3888. ssid = "test-wps"
  3889. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
  3890. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  3891. params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
  3892. hostapd.add_ap(apdev[1]['ifname'], params)
  3893. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  3894. dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
  3895. pin = dev[0].wps_read_pin()
  3896. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  3897. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
  3898. if ev is None:
  3899. raise Exception("Scan did not complete")
  3900. dev[0].request("WPS_CANCEL")
  3901. def test_ap_wps_probe_req_ie_oom(dev, apdev):
  3902. """WPS ProbeReq IE OOM"""
  3903. ssid = "test-wps"
  3904. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
  3905. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  3906. pin = dev[0].wps_read_pin()
  3907. hapd.request("WPS_PIN any " + pin)
  3908. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  3909. with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
  3910. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  3911. ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
  3912. if ev is None:
  3913. raise Exception("Association not seen")
  3914. dev[0].request("WPS_CANCEL")
  3915. with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
  3916. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  3917. ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
  3918. if ev is None:
  3919. raise Exception("Association not seen")
  3920. dev[0].request("WPS_CANCEL")
  3921. def test_ap_wps_assoc_req_ie_oom(dev, apdev):
  3922. """WPS AssocReq IE OOM"""
  3923. ssid = "test-wps"
  3924. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
  3925. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  3926. pin = dev[0].wps_read_pin()
  3927. hapd.request("WPS_PIN any " + pin)
  3928. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  3929. with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
  3930. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  3931. ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
  3932. if ev is None:
  3933. raise Exception("Association not seen")
  3934. dev[0].request("WPS_CANCEL")
  3935. def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
  3936. """WPS AssocResp IE OOM"""
  3937. ssid = "test-wps"
  3938. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
  3939. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  3940. pin = dev[0].wps_read_pin()
  3941. hapd.request("WPS_PIN any " + pin)
  3942. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  3943. with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
  3944. dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
  3945. ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
  3946. if ev is None:
  3947. raise Exception("Association not seen")
  3948. dev[0].request("WPS_CANCEL")
  3949. def test_ap_wps_bss_info_errors(dev, apdev):
  3950. """WPS BSS info errors"""
  3951. params = { "ssid": "1",
  3952. "vendor_elements": "dd0e0050f20410440001ff101100010a" }
  3953. hostapd.add_ap(apdev[0]['ifname'], params)
  3954. params = { 'ssid': "2", "vendor_elements": "dd050050f20410" }
  3955. hostapd.add_ap(apdev[1]['ifname'], params)
  3956. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  3957. dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
  3958. bss = dev[0].get_bss(apdev[0]['bssid'])
  3959. logger.info("BSS: " + str(bss))
  3960. if "wps_state" in bss:
  3961. raise Exception("Unexpected wps_state in BSS info")
  3962. if 'wps_device_name' not in bss:
  3963. raise Exception("No wps_device_name in BSS info")
  3964. if bss['wps_device_name'] != '_':
  3965. raise Exception("Unexpected wps_device_name value")
  3966. bss = dev[0].get_bss(apdev[1]['bssid'])
  3967. logger.info("BSS: " + str(bss))
  3968. with alloc_fail(dev[0], 1, "=wps_attr_text"):
  3969. bss = dev[0].get_bss(apdev[0]['bssid'])
  3970. logger.info("BSS(OOM): " + str(bss))
  3971. def wps_run_pbc_fail_ap(apdev, dev, hapd):
  3972. hapd.request("WPS_PBC")
  3973. dev.scan_for_bss(apdev['bssid'], freq="2412")
  3974. dev.request("WPS_PBC " + apdev['bssid'])
  3975. ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
  3976. if ev is None:
  3977. raise Exception("No EAP failure reported")
  3978. dev.request("WPS_CANCEL")
  3979. dev.wait_disconnected()
  3980. for i in range(5):
  3981. try:
  3982. dev.flush_scan_cache()
  3983. break
  3984. except Exception, e:
  3985. if str(e).startswith("Failed to trigger scan"):
  3986. # Try again
  3987. time.sleep(1)
  3988. else:
  3989. raise
  3990. def wps_run_pbc_fail(apdev, dev):
  3991. hapd = wps_start_ap(apdev)
  3992. wps_run_pbc_fail_ap(apdev, dev, hapd)
  3993. def test_ap_wps_pk_oom(dev, apdev):
  3994. """WPS and public key OOM"""
  3995. with alloc_fail(dev[0], 1, "wps_build_public_key"):
  3996. wps_run_pbc_fail(apdev[0], dev[0])
  3997. def test_ap_wps_pk_oom_ap(dev, apdev):
  3998. """WPS and public key OOM on AP"""
  3999. hapd = wps_start_ap(apdev[0])
  4000. with alloc_fail(hapd, 1, "wps_build_public_key"):
  4001. wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
  4002. def test_ap_wps_encr_oom_ap(dev, apdev):
  4003. """WPS and encrypted settings decryption OOM on AP"""
  4004. hapd = wps_start_ap(apdev[0])
  4005. pin = dev[0].wps_read_pin()
  4006. hapd.request("WPS_PIN any " + pin)
  4007. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  4008. with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
  4009. dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
  4010. ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
  4011. if ev is None:
  4012. raise Exception("No WPS-FAIL reported")
  4013. dev[0].request("WPS_CANCEL")
  4014. dev[0].wait_disconnected()
  4015. def test_ap_wps_encr_no_random_ap(dev, apdev):
  4016. """WPS and no random data available for encryption on AP"""
  4017. hapd = wps_start_ap(apdev[0])
  4018. with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
  4019. wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
  4020. def test_ap_wps_e_hash_no_random_sta(dev, apdev):
  4021. """WPS and no random data available for e-hash on STA"""
  4022. with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
  4023. wps_run_pbc_fail(apdev[0], dev[0])
  4024. def test_ap_wps_m1_no_random(dev, apdev):
  4025. """WPS and no random for M1 on STA"""
  4026. with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
  4027. wps_run_pbc_fail(apdev[0], dev[0])
  4028. def test_ap_wps_m1_oom(dev, apdev):
  4029. """WPS and OOM for M1 on STA"""
  4030. with alloc_fail(dev[0], 1, "wps_build_m1"):
  4031. wps_run_pbc_fail(apdev[0], dev[0])
  4032. def test_ap_wps_m3_oom(dev, apdev):
  4033. """WPS and OOM for M3 on STA"""
  4034. with alloc_fail(dev[0], 1, "wps_build_m3"):
  4035. wps_run_pbc_fail(apdev[0], dev[0])
  4036. def test_ap_wps_m5_oom(dev, apdev):
  4037. """WPS and OOM for M5 on STA"""
  4038. hapd = wps_start_ap(apdev[0])
  4039. hapd.request("WPS_PBC")
  4040. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  4041. for i in range(1, 3):
  4042. with alloc_fail(dev[0], i, "wps_build_m5"):
  4043. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  4044. ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
  4045. if ev is None:
  4046. raise Exception("No EAP failure reported")
  4047. dev[0].request("WPS_CANCEL")
  4048. dev[0].wait_disconnected()
  4049. dev[0].flush_scan_cache()
  4050. def test_ap_wps_m5_no_random(dev, apdev):
  4051. """WPS and no random for M5 on STA"""
  4052. with fail_test(dev[0], 1,
  4053. "os_get_random;wps_build_encr_settings;wps_build_m5"):
  4054. wps_run_pbc_fail(apdev[0], dev[0])
  4055. def test_ap_wps_m7_oom(dev, apdev):
  4056. """WPS and OOM for M7 on STA"""
  4057. hapd = wps_start_ap(apdev[0])
  4058. hapd.request("WPS_PBC")
  4059. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  4060. for i in range(1, 3):
  4061. with alloc_fail(dev[0], i, "wps_build_m7"):
  4062. dev[0].request("WPS_PBC " + apdev[0]['bssid'])
  4063. ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
  4064. if ev is None:
  4065. raise Exception("No EAP failure reported")
  4066. dev[0].request("WPS_CANCEL")
  4067. dev[0].wait_disconnected()
  4068. dev[0].flush_scan_cache()
  4069. def test_ap_wps_m7_no_random(dev, apdev):
  4070. """WPS and no random for M7 on STA"""
  4071. with fail_test(dev[0], 1,
  4072. "os_get_random;wps_build_encr_settings;wps_build_m7"):
  4073. wps_run_pbc_fail(apdev[0], dev[0])
  4074. def test_ap_wps_wsc_done_oom(dev, apdev):
  4075. """WPS and OOM for WSC_Done on STA"""
  4076. with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
  4077. wps_run_pbc_fail(apdev[0], dev[0])
  4078. def test_ap_wps_random_psk_fail(dev, apdev):
  4079. """WPS and no random for PSK on AP"""
  4080. ssid = "test-wps"
  4081. pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
  4082. appin = "12345670"
  4083. try:
  4084. os.remove(pskfile)
  4085. except:
  4086. pass
  4087. try:
  4088. with open(pskfile, "w") as f:
  4089. f.write("# WPA PSKs\n")
  4090. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  4091. "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
  4092. "rsn_pairwise": "CCMP", "ap_pin": appin,
  4093. "wpa_psk_file": pskfile }
  4094. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  4095. dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
  4096. with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
  4097. dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
  4098. ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
  4099. if ev is None:
  4100. raise Exception("No EAP failure reported")
  4101. dev[0].request("WPS_CANCEL")
  4102. dev[0].wait_disconnected()
  4103. with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
  4104. wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
  4105. with alloc_fail(hapd, 1, "wps_build_cred"):
  4106. wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
  4107. with alloc_fail(hapd, 2, "wps_build_cred"):
  4108. wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
  4109. finally:
  4110. os.remove(pskfile)
  4111. def wps_ext_eap_identity_req(dev, hapd, bssid):
  4112. logger.debug("EAP-Identity/Request")
  4113. ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
  4114. if ev is None:
  4115. raise Exception("Timeout on EAPOL-TX from hostapd")
  4116. res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
  4117. if "OK" not in res:
  4118. raise Exception("EAPOL_RX to wpa_supplicant failed")
  4119. def wps_ext_eap_identity_resp(hapd, dev, addr):
  4120. ev = dev.wait_event(["EAPOL-TX"], timeout=10)
  4121. if ev is None:
  4122. raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
  4123. res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
  4124. if "OK" not in res:
  4125. raise Exception("EAPOL_RX to hostapd failed")
  4126. def wps_ext_eap_wsc(dst, src, src_addr, msg):
  4127. logger.debug(msg)
  4128. ev = src.wait_event(["EAPOL-TX"], timeout=10)
  4129. if ev is None:
  4130. raise Exception("Timeout on EAPOL-TX")
  4131. res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
  4132. if "OK" not in res:
  4133. raise Exception("EAPOL_RX failed")
  4134. def wps_start_ext(apdev, dev):
  4135. addr = dev.own_addr()
  4136. bssid = apdev['bssid']
  4137. ssid = "test-wps-conf"
  4138. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  4139. "wpa_passphrase": "12345678", "wpa": "2",
  4140. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
  4141. hapd = hostapd.add_ap(apdev['ifname'], params)
  4142. pin = dev.wps_read_pin()
  4143. hapd.request("WPS_PIN any " + pin)
  4144. dev.scan_for_bss(bssid, freq="2412")
  4145. hapd.request("SET ext_eapol_frame_io 1")
  4146. dev.request("SET ext_eapol_frame_io 1")
  4147. dev.request("WPS_PIN " + bssid + " " + pin)
  4148. return addr,bssid,hapd
  4149. def wps_auth_corrupt(dst, src, addr):
  4150. ev = src.wait_event(["EAPOL-TX"], timeout=10)
  4151. if ev is None:
  4152. raise Exception("Timeout on EAPOL-TX")
  4153. src.request("SET ext_eapol_frame_io 0")
  4154. dst.request("SET ext_eapol_frame_io 0")
  4155. msg = ev.split(' ')[2]
  4156. if msg[-24:-16] != '10050008':
  4157. raise Exception("Could not find Authenticator attribute")
  4158. # Corrupt Authenticator value
  4159. msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
  4160. res = dst.request("EAPOL_RX " + addr + " " + msg)
  4161. if "OK" not in res:
  4162. raise Exception("EAPOL_RX failed")
  4163. def wps_fail_finish(hapd, dev, fail_str):
  4164. ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
  4165. if ev is None:
  4166. raise Exception("WPS-FAIL not indicated")
  4167. if fail_str not in ev:
  4168. raise Exception("Unexpected WPS-FAIL value: " + ev)
  4169. dev.request("WPS_CANCEL")
  4170. dev.wait_disconnected()
  4171. def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
  4172. wps_auth_corrupt(dev, hapd, bssid)
  4173. wps_fail_finish(hapd, dev, fail_str)
  4174. def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
  4175. wps_auth_corrupt(hapd, dev, addr)
  4176. wps_fail_finish(hapd, dev, fail_str)
  4177. def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
  4178. """WPS and Authenticator attribute mismatch in M2"""
  4179. addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
  4180. wps_ext_eap_identity_req(dev[0], hapd, bssid)
  4181. wps_ext_eap_identity_resp(hapd, dev[0], addr)
  4182. wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
  4183. wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
  4184. logger.debug("M2")
  4185. wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
  4186. def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
  4187. """WPS and Authenticator attribute mismatch in M3"""
  4188. addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
  4189. wps_ext_eap_identity_req(dev[0], hapd, bssid)
  4190. wps_ext_eap_identity_resp(hapd, dev[0], addr)
  4191. wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
  4192. wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
  4193. wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
  4194. logger.debug("M3")
  4195. wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
  4196. def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
  4197. """WPS and Authenticator attribute mismatch in M4"""
  4198. addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
  4199. wps_ext_eap_identity_req(dev[0], hapd, bssid)
  4200. wps_ext_eap_identity_resp(hapd, dev[0], addr)
  4201. wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
  4202. wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
  4203. wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
  4204. wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
  4205. logger.debug("M4")
  4206. wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
  4207. def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
  4208. """WPS and Authenticator attribute mismatch in M5"""
  4209. addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
  4210. wps_ext_eap_identity_req(dev[0], hapd, bssid)
  4211. wps_ext_eap_identity_resp(hapd, dev[0], addr)
  4212. wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
  4213. wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
  4214. wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
  4215. wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
  4216. wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
  4217. logger.debug("M5")
  4218. wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
  4219. def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
  4220. """WPS and Authenticator attribute mismatch in M6"""
  4221. addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
  4222. wps_ext_eap_identity_req(dev[0], hapd, bssid)
  4223. wps_ext_eap_identity_resp(hapd, dev[0], addr)
  4224. wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
  4225. wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
  4226. wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
  4227. wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
  4228. wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
  4229. wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
  4230. logger.debug("M6")
  4231. wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
  4232. def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
  4233. """WPS and Authenticator attribute mismatch in M7"""
  4234. addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
  4235. wps_ext_eap_identity_req(dev[0], hapd, bssid)
  4236. wps_ext_eap_identity_resp(hapd, dev[0], addr)
  4237. wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
  4238. wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
  4239. wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
  4240. wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
  4241. wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
  4242. wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
  4243. wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
  4244. logger.debug("M7")
  4245. wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
  4246. def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
  4247. """WPS and Authenticator attribute mismatch in M8"""
  4248. addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
  4249. wps_ext_eap_identity_req(dev[0], hapd, bssid)
  4250. wps_ext_eap_identity_resp(hapd, dev[0], addr)
  4251. wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
  4252. wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
  4253. wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
  4254. wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
  4255. wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
  4256. wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
  4257. wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
  4258. wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
  4259. logger.debug("M8")
  4260. wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
  4261. def test_ap_wps_authenticator_missing_m2(dev, apdev):
  4262. """WPS and Authenticator attribute missing from M2"""
  4263. addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
  4264. wps_ext_eap_identity_req(dev[0], hapd, bssid)
  4265. wps_ext_eap_identity_resp(hapd, dev[0], addr)
  4266. wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
  4267. wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
  4268. logger.debug("M2")
  4269. ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
  4270. if ev is None:
  4271. raise Exception("Timeout on EAPOL-TX")
  4272. hapd.request("SET ext_eapol_frame_io 0")
  4273. dev[0].request("SET ext_eapol_frame_io 0")
  4274. msg = ev.split(' ')[2]
  4275. if msg[-24:-16] != '10050008':
  4276. raise Exception("Could not find Authenticator attribute")
  4277. # Remove Authenticator value
  4278. msg = msg[:-24]
  4279. mlen = "%04x" % (int(msg[4:8], 16) - 12)
  4280. msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
  4281. res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
  4282. if "OK" not in res:
  4283. raise Exception("EAPOL_RX failed")
  4284. wps_fail_finish(hapd, dev[0], "msg=5")
  4285. def test_ap_wps_config_methods(dev, apdev):
  4286. """WPS configuration method parsing"""
  4287. ssid = "test-wps-conf"
  4288. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  4289. "wpa_passphrase": "12345678", "wpa": "2",
  4290. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  4291. "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button" }
  4292. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  4293. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  4294. "wpa_passphrase": "12345678", "wpa": "2",
  4295. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  4296. "config_methods": "display push_button" }
  4297. hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)