test_ap_wps.py 196 KB

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