test_ap_wps.py 196 KB

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