test_ap_wps.py 215 KB

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