test_ap_wps.py 189 KB

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