test_ap_wps.py 217 KB

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