test_ap_wps.py 221 KB

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