test_ap_wps.py 220 KB

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