test_ap_wps.py 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941
  1. # WPS tests
  2. # Copyright (c) 2013-2014, 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 os
  7. import time
  8. import subprocess
  9. import logging
  10. logger = logging.getLogger()
  11. import re
  12. import socket
  13. import httplib
  14. import urlparse
  15. import urllib
  16. import xml.etree.ElementTree as ET
  17. import StringIO
  18. import hwsim_utils
  19. import hostapd
  20. def test_ap_wps_init(dev, apdev):
  21. """Initial AP configuration with first WPS Enrollee"""
  22. ssid = "test-wps"
  23. hostapd.add_ap(apdev[0]['ifname'],
  24. { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
  25. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  26. logger.info("WPS provisioning step")
  27. hapd.request("WPS_PBC")
  28. if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
  29. raise Exception("PBC status not shown correctly")
  30. id = dev[0].add_network()
  31. dev[0].set_network_quoted(id, "ssid", "home")
  32. dev[0].set_network_quoted(id, "psk", "12345678")
  33. dev[0].request("ENABLE_NETWORK %s no-connect" % id)
  34. id = dev[0].add_network()
  35. dev[0].set_network_quoted(id, "ssid", "home2")
  36. dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
  37. dev[0].set_network(id, "key_mgmt", "NONE")
  38. dev[0].request("ENABLE_NETWORK %s no-connect" % id)
  39. dev[0].request("WPS_PBC")
  40. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  41. if ev is None:
  42. raise Exception("Association with the AP timed out")
  43. status = dev[0].get_status()
  44. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  45. raise Exception("Not fully connected")
  46. if status['ssid'] != ssid:
  47. raise Exception("Unexpected SSID")
  48. if status['pairwise_cipher'] != 'CCMP':
  49. raise Exception("Unexpected encryption configuration")
  50. if status['key_mgmt'] != 'WPA2-PSK':
  51. raise Exception("Unexpected key_mgmt")
  52. status = hapd.request("WPS_GET_STATUS")
  53. if "PBC Status: Disabled" not in status:
  54. raise Exception("PBC status not shown correctly")
  55. if "Last WPS result: Success" not in status:
  56. raise Exception("Last WPS result not shown correctly")
  57. if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
  58. raise Exception("Peer address not shown correctly")
  59. conf = hapd.request("GET_CONFIG")
  60. if "wps_state=configured" not in conf:
  61. raise Exception("AP not in WPS configured state")
  62. if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
  63. raise Exception("Unexpected rsn_pairwise_cipher")
  64. if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
  65. raise Exception("Unexpected wpa_pairwise_cipher")
  66. if "group_cipher=TKIP" not in conf:
  67. raise Exception("Unexpected group_cipher")
  68. if len(dev[0].list_networks()) != 3:
  69. raise Exception("Unexpected number of network blocks")
  70. def test_ap_wps_init_2ap_pbc(dev, apdev):
  71. """Initial two-radio AP configuration with first WPS PBC Enrollee"""
  72. ssid = "test-wps"
  73. params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
  74. hostapd.add_ap(apdev[0]['ifname'], params)
  75. hostapd.add_ap(apdev[1]['ifname'], params)
  76. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  77. logger.info("WPS provisioning step")
  78. hapd.request("WPS_PBC")
  79. dev[0].scan(freq="2412")
  80. bss = dev[0].get_bss(apdev[0]['bssid'])
  81. if "[WPS-PBC]" not in bss['flags']:
  82. raise Exception("WPS-PBC flag missing from AP1")
  83. bss = dev[0].get_bss(apdev[1]['bssid'])
  84. if "[WPS-PBC]" not in bss['flags']:
  85. raise Exception("WPS-PBC flag missing from AP2")
  86. dev[0].dump_monitor()
  87. dev[0].request("SET wps_cred_processing 2")
  88. dev[0].request("WPS_PBC")
  89. ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
  90. dev[0].request("SET wps_cred_processing 0")
  91. if ev is None:
  92. raise Exception("WPS cred event not seen")
  93. if "100e" not in ev:
  94. raise Exception("WPS attributes not included in the cred event")
  95. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  96. if ev is None:
  97. raise Exception("Association with the AP timed out")
  98. dev[1].scan(freq="2412")
  99. bss = dev[1].get_bss(apdev[0]['bssid'])
  100. if "[WPS-PBC]" in bss['flags']:
  101. raise Exception("WPS-PBC flag not cleared from AP1")
  102. bss = dev[1].get_bss(apdev[1]['bssid'])
  103. if "[WPS-PBC]" in bss['flags']:
  104. raise Exception("WPS-PBC flag bit ckeared from AP2")
  105. def test_ap_wps_init_2ap_pin(dev, apdev):
  106. """Initial two-radio AP configuration with first WPS PIN Enrollee"""
  107. ssid = "test-wps"
  108. params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
  109. hostapd.add_ap(apdev[0]['ifname'], params)
  110. hostapd.add_ap(apdev[1]['ifname'], params)
  111. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  112. logger.info("WPS provisioning step")
  113. pin = dev[0].wps_read_pin()
  114. hapd.request("WPS_PIN any " + pin)
  115. dev[0].scan(freq="2412")
  116. bss = dev[0].get_bss(apdev[0]['bssid'])
  117. if "[WPS-AUTH]" not in bss['flags']:
  118. raise Exception("WPS-AUTH flag missing from AP1")
  119. bss = dev[0].get_bss(apdev[1]['bssid'])
  120. if "[WPS-AUTH]" not in bss['flags']:
  121. raise Exception("WPS-AUTH flag missing from AP2")
  122. dev[0].dump_monitor()
  123. dev[0].request("WPS_PIN any " + pin)
  124. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  125. if ev is None:
  126. raise Exception("Association with the AP timed out")
  127. dev[1].scan(freq="2412")
  128. bss = dev[1].get_bss(apdev[0]['bssid'])
  129. if "[WPS-AUTH]" in bss['flags']:
  130. raise Exception("WPS-AUTH flag not cleared from AP1")
  131. bss = dev[1].get_bss(apdev[1]['bssid'])
  132. if "[WPS-AUTH]" in bss['flags']:
  133. raise Exception("WPS-AUTH flag bit ckeared from AP2")
  134. def test_ap_wps_init_through_wps_config(dev, apdev):
  135. """Initial AP configuration using wps_config command"""
  136. ssid = "test-wps-init-config"
  137. hostapd.add_ap(apdev[0]['ifname'],
  138. { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
  139. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  140. if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
  141. raise Exception("WPS_CONFIG command failed")
  142. ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
  143. if ev is None:
  144. raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
  145. # It takes some time for the AP to update Beacon and Probe Response frames,
  146. # so wait here before requesting the scan to be started to avoid adding
  147. # extra five second wait to the test due to fetching obsolete scan results.
  148. hapd.ping()
  149. time.sleep(0.2)
  150. dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
  151. pairwise="CCMP", group="CCMP")
  152. def test_ap_wps_conf(dev, apdev):
  153. """WPS PBC provisioning with configured AP"""
  154. ssid = "test-wps-conf"
  155. hostapd.add_ap(apdev[0]['ifname'],
  156. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  157. "wpa_passphrase": "12345678", "wpa": "2",
  158. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  159. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  160. logger.info("WPS provisioning step")
  161. hapd.request("WPS_PBC")
  162. dev[0].dump_monitor()
  163. dev[0].request("WPS_PBC")
  164. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  165. if ev is None:
  166. raise Exception("Association with the AP timed out")
  167. status = dev[0].get_status()
  168. if status['wpa_state'] != 'COMPLETED':
  169. raise Exception("Not fully connected")
  170. if status['bssid'] != apdev[0]['bssid']:
  171. raise Exception("Unexpected BSSID")
  172. if status['ssid'] != ssid:
  173. raise Exception("Unexpected SSID")
  174. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  175. raise Exception("Unexpected encryption configuration")
  176. if status['key_mgmt'] != 'WPA2-PSK':
  177. raise Exception("Unexpected key_mgmt")
  178. sta = hapd.get_sta(dev[0].p2p_interface_addr())
  179. if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
  180. raise Exception("Device name not available in STA command")
  181. def test_ap_wps_twice(dev, apdev):
  182. """WPS provisioning with twice to change passphrase"""
  183. ssid = "test-wps-twice"
  184. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  185. "wpa_passphrase": "12345678", "wpa": "2",
  186. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
  187. hostapd.add_ap(apdev[0]['ifname'], params)
  188. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  189. logger.info("WPS provisioning step")
  190. hapd.request("WPS_PBC")
  191. dev[0].dump_monitor()
  192. dev[0].request("WPS_PBC")
  193. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  194. if ev is None:
  195. raise Exception("Association with the AP timed out")
  196. dev[0].request("DISCONNECT")
  197. logger.info("Restart AP with different passphrase and re-run WPS")
  198. hapd_global = hostapd.HostapdGlobal()
  199. hapd_global.remove(apdev[0]['ifname'])
  200. params['wpa_passphrase'] = 'another passphrase'
  201. hostapd.add_ap(apdev[0]['ifname'], params)
  202. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  203. logger.info("WPS provisioning step")
  204. hapd.request("WPS_PBC")
  205. dev[0].dump_monitor()
  206. dev[0].request("WPS_PBC")
  207. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  208. if ev is None:
  209. raise Exception("Association with the AP timed out")
  210. networks = dev[0].list_networks()
  211. if len(networks) > 1:
  212. raise Exception("Unexpected duplicated network block present")
  213. def test_ap_wps_incorrect_pin(dev, apdev):
  214. """WPS PIN provisioning with incorrect PIN"""
  215. ssid = "test-wps-incorrect-pin"
  216. hostapd.add_ap(apdev[0]['ifname'],
  217. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  218. "wpa_passphrase": "12345678", "wpa": "2",
  219. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  220. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  221. logger.info("WPS provisioning attempt 1")
  222. hapd.request("WPS_PIN any 12345670")
  223. dev[0].dump_monitor()
  224. dev[0].request("WPS_PIN any 55554444")
  225. ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
  226. if ev is None:
  227. raise Exception("WPS operation timed out")
  228. if "config_error=18" not in ev:
  229. raise Exception("Incorrect config_error reported")
  230. if "msg=8" not in ev:
  231. raise Exception("PIN error detected on incorrect message")
  232. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
  233. if ev is None:
  234. raise Exception("Timeout on disconnection event")
  235. dev[0].request("WPS_CANCEL")
  236. # if a scan was in progress, wait for it to complete before trying WPS again
  237. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
  238. status = hapd.request("WPS_GET_STATUS")
  239. if "Last WPS result: Failed" not in status:
  240. raise Exception("WPS failure result not shown correctly")
  241. logger.info("WPS provisioning attempt 2")
  242. hapd.request("WPS_PIN any 12345670")
  243. dev[0].dump_monitor()
  244. dev[0].request("WPS_PIN any 12344444")
  245. ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
  246. if ev is None:
  247. raise Exception("WPS operation timed out")
  248. if "config_error=18" not in ev:
  249. raise Exception("Incorrect config_error reported")
  250. if "msg=10" not in ev:
  251. raise Exception("PIN error detected on incorrect message")
  252. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
  253. if ev is None:
  254. raise Exception("Timeout on disconnection event")
  255. def test_ap_wps_conf_pin(dev, apdev):
  256. """WPS PIN provisioning with configured AP"""
  257. ssid = "test-wps-conf-pin"
  258. hostapd.add_ap(apdev[0]['ifname'],
  259. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  260. "wpa_passphrase": "12345678", "wpa": "2",
  261. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  262. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  263. logger.info("WPS provisioning step")
  264. pin = dev[0].wps_read_pin()
  265. hapd.request("WPS_PIN any " + pin)
  266. dev[0].dump_monitor()
  267. dev[0].request("WPS_PIN any " + pin)
  268. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  269. if ev is None:
  270. raise Exception("Association with the AP timed out")
  271. status = dev[0].get_status()
  272. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  273. raise Exception("Not fully connected")
  274. if status['ssid'] != ssid:
  275. raise Exception("Unexpected SSID")
  276. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  277. raise Exception("Unexpected encryption configuration")
  278. if status['key_mgmt'] != 'WPA2-PSK':
  279. raise Exception("Unexpected key_mgmt")
  280. dev[1].scan(freq="2412")
  281. bss = dev[1].get_bss(apdev[0]['bssid'])
  282. if "[WPS-AUTH]" in bss['flags']:
  283. raise Exception("WPS-AUTH flag not cleared")
  284. logger.info("Try to connect from another station using the same PIN")
  285. dev[1].request("WPS_PIN any " + pin)
  286. ev = dev[1].wait_event(["WPS-M2D","CTRL-EVENT-CONNECTED"], timeout=30)
  287. if ev is None:
  288. raise Exception("Operation timed out")
  289. if "WPS-M2D" not in ev:
  290. raise Exception("Unexpected WPS operation started")
  291. def test_ap_wps_conf_pin_2sta(dev, apdev):
  292. """Two stations trying to use WPS PIN at the same time"""
  293. ssid = "test-wps-conf-pin2"
  294. hostapd.add_ap(apdev[0]['ifname'],
  295. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  296. "wpa_passphrase": "12345678", "wpa": "2",
  297. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  298. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  299. logger.info("WPS provisioning step")
  300. pin = "12345670"
  301. pin2 = "55554444"
  302. hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
  303. hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
  304. dev[0].dump_monitor()
  305. dev[1].dump_monitor()
  306. dev[0].request("WPS_PIN any " + pin)
  307. dev[1].request("WPS_PIN any " + pin)
  308. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  309. if ev is None:
  310. raise Exception("Association with the AP timed out")
  311. ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  312. if ev is None:
  313. raise Exception("Association with the AP timed out")
  314. def test_ap_wps_conf_pin_timeout(dev, apdev):
  315. """WPS PIN provisioning with configured AP timing out PIN"""
  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. addr = dev[0].p2p_interface_addr()
  323. pin = dev[0].wps_read_pin()
  324. if "FAIL" not in hapd.request("WPS_PIN "):
  325. raise Exception("Unexpected success on invalid WPS_PIN")
  326. hapd.request("WPS_PIN any " + pin + " 1")
  327. time.sleep(1.1)
  328. dev[0].request("WPS_PIN any " + pin)
  329. ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
  330. if ev is None:
  331. raise Exception("WPS-PIN-NEEDED event timed out")
  332. ev = dev[0].wait_event(["WPS-M2D"])
  333. if ev is None:
  334. raise Exception("M2D not reported")
  335. dev[0].request("WPS_CANCEL")
  336. hapd.request("WPS_PIN any " + pin + " 20 " + addr)
  337. dev[0].request("WPS_PIN any " + pin)
  338. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  339. if ev is None:
  340. raise Exception("Association with the AP timed out")
  341. def test_ap_wps_reg_connect(dev, apdev):
  342. """WPS registrar using AP PIN to connect"""
  343. ssid = "test-wps-reg-ap-pin"
  344. appin = "12345670"
  345. hostapd.add_ap(apdev[0]['ifname'],
  346. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  347. "wpa_passphrase": "12345678", "wpa": "2",
  348. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  349. "ap_pin": appin})
  350. logger.info("WPS provisioning step")
  351. dev[0].dump_monitor()
  352. dev[0].wps_reg(apdev[0]['bssid'], appin)
  353. status = dev[0].get_status()
  354. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  355. raise Exception("Not fully connected")
  356. if status['ssid'] != ssid:
  357. raise Exception("Unexpected SSID")
  358. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  359. raise Exception("Unexpected encryption configuration")
  360. if status['key_mgmt'] != 'WPA2-PSK':
  361. raise Exception("Unexpected key_mgmt")
  362. def check_wps_reg_failure(dev, ap, appin):
  363. dev.request("WPS_REG " + ap['bssid'] + " " + appin)
  364. ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
  365. if ev is None:
  366. raise Exception("WPS operation timed out")
  367. if "WPS-SUCCESS" in ev:
  368. raise Exception("WPS operation succeeded unexpectedly")
  369. if "config_error=15" not in ev:
  370. raise Exception("WPS setup locked state was not reported correctly")
  371. def test_ap_wps_random_ap_pin(dev, apdev):
  372. """WPS registrar using random AP PIN"""
  373. ssid = "test-wps-reg-random-ap-pin"
  374. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  375. hostapd.add_ap(apdev[0]['ifname'],
  376. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  377. "wpa_passphrase": "12345678", "wpa": "2",
  378. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  379. "device_name": "Wireless AP", "manufacturer": "Company",
  380. "model_name": "WAP", "model_number": "123",
  381. "serial_number": "12345", "device_type": "6-0050F204-1",
  382. "os_version": "01020300",
  383. "config_methods": "label push_button",
  384. "uuid": ap_uuid, "upnp_iface": "lo" })
  385. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  386. appin = hapd.request("WPS_AP_PIN random")
  387. if "FAIL" in appin:
  388. raise Exception("Could not generate random AP PIN")
  389. if appin not in hapd.request("WPS_AP_PIN get"):
  390. raise Exception("Could not fetch current AP PIN")
  391. logger.info("WPS provisioning step")
  392. dev[0].wps_reg(apdev[0]['bssid'], appin)
  393. hapd.request("WPS_AP_PIN disable")
  394. logger.info("WPS provisioning step with AP PIN disabled")
  395. check_wps_reg_failure(dev[1], apdev[0], appin)
  396. logger.info("WPS provisioning step with AP PIN reset")
  397. appin = "12345670"
  398. hapd.request("WPS_AP_PIN set " + appin)
  399. dev[1].wps_reg(apdev[0]['bssid'], appin)
  400. dev[0].request("REMOVE_NETWORK all")
  401. dev[1].request("REMOVE_NETWORK all")
  402. dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
  403. dev[1].wait_event(["CTRL-EVENT-DISCONNECTED"])
  404. logger.info("WPS provisioning step after AP PIN timeout")
  405. hapd.request("WPS_AP_PIN disable")
  406. appin = hapd.request("WPS_AP_PIN random 1")
  407. time.sleep(1.1)
  408. if "FAIL" not in hapd.request("WPS_AP_PIN get"):
  409. raise Exception("AP PIN unexpectedly still enabled")
  410. check_wps_reg_failure(dev[0], apdev[0], appin)
  411. logger.info("WPS provisioning step after AP PIN timeout(2)")
  412. hapd.request("WPS_AP_PIN disable")
  413. appin = "12345670"
  414. hapd.request("WPS_AP_PIN set " + appin + " 1")
  415. time.sleep(1.1)
  416. if "FAIL" not in hapd.request("WPS_AP_PIN get"):
  417. raise Exception("AP PIN unexpectedly still enabled")
  418. check_wps_reg_failure(dev[1], apdev[0], appin)
  419. def test_ap_wps_reg_config(dev, apdev):
  420. """WPS registrar configuring an AP using AP PIN"""
  421. ssid = "test-wps-init-ap-pin"
  422. appin = "12345670"
  423. hostapd.add_ap(apdev[0]['ifname'],
  424. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  425. "ap_pin": appin})
  426. logger.info("WPS configuration step")
  427. dev[0].dump_monitor()
  428. new_ssid = "wps-new-ssid"
  429. new_passphrase = "1234567890"
  430. dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
  431. new_passphrase)
  432. status = dev[0].get_status()
  433. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  434. raise Exception("Not fully connected")
  435. if status['ssid'] != new_ssid:
  436. raise Exception("Unexpected SSID")
  437. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  438. raise Exception("Unexpected encryption configuration")
  439. if status['key_mgmt'] != 'WPA2-PSK':
  440. raise Exception("Unexpected key_mgmt")
  441. logger.info("Re-configure back to open")
  442. dev[0].request("REMOVE_NETWORK all")
  443. dev[0].request("BSS_FLUSH 0")
  444. dev[0].request("SCAN freq=2412 only_new=1")
  445. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  446. if ev is None:
  447. raise Exception("Scan timed out")
  448. dev[0].dump_monitor()
  449. dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
  450. status = dev[0].get_status()
  451. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  452. raise Exception("Not fully connected")
  453. if status['ssid'] != "wps-open":
  454. raise Exception("Unexpected SSID")
  455. if status['key_mgmt'] != 'NONE':
  456. raise Exception("Unexpected key_mgmt")
  457. def test_ap_wps_reg_config_ext_processing(dev, apdev):
  458. """WPS registrar configuring an AP with external config processing"""
  459. ssid = "test-wps-init-ap-pin"
  460. appin = "12345670"
  461. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  462. "wps_cred_processing": "1", "ap_pin": appin}
  463. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  464. new_ssid = "wps-new-ssid"
  465. new_passphrase = "1234567890"
  466. dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
  467. new_passphrase, no_wait=True)
  468. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  469. if ev is None:
  470. raise Exception("WPS registrar operation timed out")
  471. ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
  472. if ev is None:
  473. raise Exception("WPS configuration timed out")
  474. if "1026" not in ev:
  475. raise Exception("AP Settings missing from event")
  476. hapd.request("SET wps_cred_processing 0")
  477. if "FAIL" in hapd.request("WPS_CONFIG " + new_ssid.encode("hex") + " WPA2PSK CCMP " + new_passphrase.encode("hex")):
  478. raise Exception("WPS_CONFIG command failed")
  479. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  480. if ev is None:
  481. raise Exception("Association with the AP timed out")
  482. def test_ap_wps_reg_config_tkip(dev, apdev):
  483. """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
  484. ssid = "test-wps-init-ap"
  485. appin = "12345670"
  486. hostapd.add_ap(apdev[0]['ifname'],
  487. { "ssid": ssid, "eap_server": "1", "wps_state": "1",
  488. "ap_pin": appin})
  489. logger.info("WPS configuration step")
  490. dev[0].request("SET wps_version_number 0x10")
  491. dev[0].dump_monitor()
  492. new_ssid = "wps-new-ssid-with-tkip"
  493. new_passphrase = "1234567890"
  494. dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
  495. new_passphrase)
  496. logger.info("Re-connect to verify WPA2 mixed mode")
  497. dev[0].request("DISCONNECT")
  498. id = 0
  499. dev[0].set_network(id, "pairwise", "CCMP")
  500. dev[0].set_network(id, "proto", "RSN")
  501. dev[0].connect_network(id)
  502. status = dev[0].get_status()
  503. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  504. raise Exception("Not fully connected")
  505. if status['ssid'] != new_ssid:
  506. raise Exception("Unexpected SSID")
  507. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
  508. raise Exception("Unexpected encryption configuration")
  509. if status['key_mgmt'] != 'WPA2-PSK':
  510. raise Exception("Unexpected key_mgmt")
  511. def test_ap_wps_setup_locked(dev, apdev):
  512. """WPS registrar locking up AP setup on AP PIN failures"""
  513. ssid = "test-wps-incorrect-ap-pin"
  514. appin = "12345670"
  515. hostapd.add_ap(apdev[0]['ifname'],
  516. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  517. "wpa_passphrase": "12345678", "wpa": "2",
  518. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  519. "ap_pin": appin})
  520. new_ssid = "wps-new-ssid-test"
  521. new_passphrase = "1234567890"
  522. ap_setup_locked=False
  523. for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
  524. dev[0].dump_monitor()
  525. logger.info("Try incorrect AP PIN - attempt " + pin)
  526. dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
  527. "CCMP", new_passphrase, no_wait=True)
  528. ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
  529. if ev is None:
  530. raise Exception("Timeout on receiving WPS operation failure event")
  531. if "CTRL-EVENT-CONNECTED" in ev:
  532. raise Exception("Unexpected connection")
  533. if "config_error=15" in ev:
  534. logger.info("AP Setup Locked")
  535. ap_setup_locked=True
  536. elif "config_error=18" not in ev:
  537. raise Exception("config_error=18 not reported")
  538. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
  539. if ev is None:
  540. raise Exception("Timeout on disconnection event")
  541. time.sleep(0.1)
  542. if not ap_setup_locked:
  543. raise Exception("AP setup was not locked")
  544. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  545. status = hapd.request("WPS_GET_STATUS")
  546. if "Last WPS result: Failed" not in status:
  547. raise Exception("WPS failure result not shown correctly")
  548. if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
  549. raise Exception("Peer address not shown correctly")
  550. time.sleep(0.5)
  551. dev[0].dump_monitor()
  552. logger.info("WPS provisioning step")
  553. pin = dev[0].wps_read_pin()
  554. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  555. hapd.request("WPS_PIN any " + pin)
  556. dev[0].request("WPS_PIN any " + pin)
  557. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
  558. if ev is None:
  559. raise Exception("WPS success was not reported")
  560. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  561. if ev is None:
  562. raise Exception("Association with the AP timed out")
  563. appin = hapd.request("WPS_AP_PIN random")
  564. if "FAIL" in appin:
  565. raise Exception("Could not generate random AP PIN")
  566. ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
  567. if ev is None:
  568. raise Exception("Failed to unlock AP PIN")
  569. def test_ap_wps_setup_locked_timeout(dev, apdev):
  570. """WPS re-enabling AP PIN after timeout"""
  571. ssid = "test-wps-incorrect-ap-pin"
  572. appin = "12345670"
  573. hostapd.add_ap(apdev[0]['ifname'],
  574. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  575. "wpa_passphrase": "12345678", "wpa": "2",
  576. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  577. "ap_pin": appin})
  578. new_ssid = "wps-new-ssid-test"
  579. new_passphrase = "1234567890"
  580. ap_setup_locked=False
  581. for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
  582. dev[0].dump_monitor()
  583. logger.info("Try incorrect AP PIN - attempt " + pin)
  584. dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
  585. "CCMP", new_passphrase, no_wait=True)
  586. ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
  587. if ev is None:
  588. raise Exception("Timeout on receiving WPS operation failure event")
  589. if "CTRL-EVENT-CONNECTED" in ev:
  590. raise Exception("Unexpected connection")
  591. if "config_error=15" in ev:
  592. logger.info("AP Setup Locked")
  593. ap_setup_locked=True
  594. break
  595. elif "config_error=18" not in ev:
  596. raise Exception("config_error=18 not reported")
  597. ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
  598. if ev is None:
  599. raise Exception("Timeout on disconnection event")
  600. time.sleep(0.1)
  601. if not ap_setup_locked:
  602. raise Exception("AP setup was not locked")
  603. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  604. ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
  605. if ev is None:
  606. raise Exception("AP PIN did not get unlocked on 60 second timeout")
  607. def test_ap_wps_pbc_overlap_2ap(dev, apdev):
  608. """WPS PBC session overlap with two active APs"""
  609. hostapd.add_ap(apdev[0]['ifname'],
  610. { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
  611. "wpa_passphrase": "12345678", "wpa": "2",
  612. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  613. "wps_independent": "1"})
  614. hostapd.add_ap(apdev[1]['ifname'],
  615. { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
  616. "wpa_passphrase": "123456789", "wpa": "2",
  617. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  618. "wps_independent": "1"})
  619. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  620. hapd.request("WPS_PBC")
  621. hapd2 = hostapd.Hostapd(apdev[1]['ifname'])
  622. hapd2.request("WPS_PBC")
  623. logger.info("WPS provisioning step")
  624. dev[0].dump_monitor()
  625. dev[0].request("WPS_PBC")
  626. ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
  627. if ev is None:
  628. raise Exception("PBC session overlap not detected")
  629. def test_ap_wps_pbc_overlap_2sta(dev, apdev):
  630. """WPS PBC session overlap with two active STAs"""
  631. ssid = "test-wps-pbc-overlap"
  632. hostapd.add_ap(apdev[0]['ifname'],
  633. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  634. "wpa_passphrase": "12345678", "wpa": "2",
  635. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  636. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  637. logger.info("WPS provisioning step")
  638. hapd.request("WPS_PBC")
  639. dev[0].dump_monitor()
  640. dev[1].dump_monitor()
  641. dev[0].request("WPS_PBC")
  642. dev[1].request("WPS_PBC")
  643. ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
  644. if ev is None:
  645. raise Exception("PBC session overlap not detected (dev0)")
  646. if "config_error=12" not in ev:
  647. raise Exception("PBC session overlap not correctly reported (dev0)")
  648. ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
  649. if ev is None:
  650. raise Exception("PBC session overlap not detected (dev1)")
  651. if "config_error=12" not in ev:
  652. raise Exception("PBC session overlap not correctly reported (dev1)")
  653. hapd.request("WPS_CANCEL")
  654. ret = hapd.request("WPS_PBC")
  655. if "FAIL" not in ret:
  656. raise Exception("PBC mode allowed to be started while PBC overlap still active")
  657. def test_ap_wps_cancel(dev, apdev):
  658. """WPS AP cancelling enabled config method"""
  659. ssid = "test-wps-ap-cancel"
  660. hostapd.add_ap(apdev[0]['ifname'],
  661. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  662. "wpa_passphrase": "12345678", "wpa": "2",
  663. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
  664. bssid = apdev[0]['bssid']
  665. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  666. logger.info("Verify PBC enable/cancel")
  667. hapd.request("WPS_PBC")
  668. dev[0].scan(freq="2412")
  669. bss = dev[0].get_bss(apdev[0]['bssid'])
  670. if "[WPS-PBC]" not in bss['flags']:
  671. raise Exception("WPS-PBC flag missing")
  672. if "FAIL" in hapd.request("WPS_CANCEL"):
  673. raise Exception("WPS_CANCEL failed")
  674. dev[0].scan(freq="2412")
  675. bss = dev[0].get_bss(apdev[0]['bssid'])
  676. if "[WPS-PBC]" in bss['flags']:
  677. raise Exception("WPS-PBC flag not cleared")
  678. logger.info("Verify PIN enable/cancel")
  679. hapd.request("WPS_PIN any 12345670")
  680. dev[0].scan(freq="2412")
  681. bss = dev[0].get_bss(apdev[0]['bssid'])
  682. if "[WPS-AUTH]" not in bss['flags']:
  683. raise Exception("WPS-AUTH flag missing")
  684. if "FAIL" in hapd.request("WPS_CANCEL"):
  685. raise Exception("WPS_CANCEL failed")
  686. dev[0].scan(freq="2412")
  687. bss = dev[0].get_bss(apdev[0]['bssid'])
  688. if "[WPS-AUTH]" in bss['flags']:
  689. raise Exception("WPS-AUTH flag not cleared")
  690. def test_ap_wps_er_add_enrollee(dev, apdev):
  691. """WPS ER configuring AP and adding a new enrollee using PIN"""
  692. ssid = "wps-er-add-enrollee"
  693. ap_pin = "12345670"
  694. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  695. hostapd.add_ap(apdev[0]['ifname'],
  696. { "ssid": ssid, "eap_server": "1", "wps_state": "1",
  697. "device_name": "Wireless AP", "manufacturer": "Company",
  698. "model_name": "WAP", "model_number": "123",
  699. "serial_number": "12345", "device_type": "6-0050F204-1",
  700. "os_version": "01020300",
  701. "config_methods": "label push_button",
  702. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  703. logger.info("WPS configuration step")
  704. new_passphrase = "1234567890"
  705. dev[0].dump_monitor()
  706. dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
  707. new_passphrase)
  708. status = dev[0].get_status()
  709. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  710. raise Exception("Not fully connected")
  711. if status['ssid'] != ssid:
  712. raise Exception("Unexpected SSID")
  713. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
  714. raise Exception("Unexpected encryption configuration")
  715. if status['key_mgmt'] != 'WPA2-PSK':
  716. raise Exception("Unexpected key_mgmt")
  717. logger.info("Start ER")
  718. dev[0].request("WPS_ER_START ifname=lo")
  719. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  720. if ev is None:
  721. raise Exception("AP discovery timed out")
  722. if ap_uuid not in ev:
  723. raise Exception("Expected AP UUID not found")
  724. logger.info("Learn AP configuration through UPnP")
  725. dev[0].dump_monitor()
  726. dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
  727. ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
  728. if ev is None:
  729. raise Exception("AP learn timed out")
  730. if ap_uuid not in ev:
  731. raise Exception("Expected AP UUID not in settings")
  732. if "ssid=" + ssid not in ev:
  733. raise Exception("Expected SSID not in settings")
  734. if "key=" + new_passphrase not in ev:
  735. raise Exception("Expected passphrase not in settings")
  736. logger.info("Add Enrollee using ER")
  737. pin = dev[1].wps_read_pin()
  738. dev[0].dump_monitor()
  739. dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
  740. dev[1].dump_monitor()
  741. dev[1].request("WPS_PIN any " + pin)
  742. ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
  743. if ev is None:
  744. raise Exception("Enrollee did not report success")
  745. ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  746. if ev is None:
  747. raise Exception("Association with the AP timed out")
  748. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  749. if ev is None:
  750. raise Exception("WPS ER did not report success")
  751. hwsim_utils.test_connectivity_sta(dev[0], dev[1])
  752. logger.info("Add a specific Enrollee using ER")
  753. pin = dev[2].wps_read_pin()
  754. addr2 = dev[2].p2p_interface_addr()
  755. dev[0].dump_monitor()
  756. dev[2].dump_monitor()
  757. dev[2].request("WPS_PIN any " + pin)
  758. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
  759. if ev is None:
  760. raise Exception("Enrollee not seen")
  761. if addr2 not in ev:
  762. raise Exception("Unexpected Enrollee MAC address")
  763. dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
  764. ev = dev[2].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  765. if ev is None:
  766. raise Exception("Association with the AP timed out")
  767. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  768. if ev is None:
  769. raise Exception("WPS ER did not report success")
  770. logger.info("Verify registrar selection behavior")
  771. dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
  772. dev[1].request("DISCONNECT")
  773. dev[1].wait_event(["CTRL-EVENT-DISCONNECTED"])
  774. dev[1].scan(freq="2412")
  775. bss = dev[1].get_bss(apdev[0]['bssid'])
  776. if "[WPS-AUTH]" not in bss['flags']:
  777. raise Exception("WPS-AUTH flag missing")
  778. logger.info("Stop ER")
  779. dev[0].dump_monitor()
  780. dev[0].request("WPS_ER_STOP")
  781. ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
  782. if ev is None:
  783. raise Exception("WPS ER unsubscription timed out")
  784. # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
  785. # a bit before verifying that the scan results have change.
  786. time.sleep(0.2)
  787. dev[1].scan(freq="2412")
  788. bss = dev[1].get_bss(apdev[0]['bssid'])
  789. if "[WPS-AUTH]" in bss['flags']:
  790. raise Exception("WPS-AUTH flag not removed")
  791. def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
  792. """WPS ER connected to AP and adding a new enrollee using PBC"""
  793. ssid = "wps-er-add-enrollee-pbc"
  794. ap_pin = "12345670"
  795. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  796. hostapd.add_ap(apdev[0]['ifname'],
  797. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  798. "wpa_passphrase": "12345678", "wpa": "2",
  799. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  800. "device_name": "Wireless AP", "manufacturer": "Company",
  801. "model_name": "WAP", "model_number": "123",
  802. "serial_number": "12345", "device_type": "6-0050F204-1",
  803. "os_version": "01020300",
  804. "config_methods": "label push_button",
  805. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  806. logger.info("Learn AP configuration")
  807. dev[0].dump_monitor()
  808. dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
  809. status = dev[0].get_status()
  810. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  811. raise Exception("Not fully connected")
  812. logger.info("Start ER")
  813. dev[0].request("WPS_ER_START ifname=lo")
  814. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  815. if ev is None:
  816. raise Exception("AP discovery timed out")
  817. if ap_uuid not in ev:
  818. raise Exception("Expected AP UUID not found")
  819. logger.info("Use learned network configuration on ER")
  820. dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
  821. logger.info("Add Enrollee using ER and PBC")
  822. dev[0].dump_monitor()
  823. enrollee = dev[1].p2p_interface_addr()
  824. dev[1].dump_monitor()
  825. dev[1].request("WPS_PBC")
  826. for i in range(0, 2):
  827. ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
  828. if ev is None:
  829. raise Exception("Enrollee discovery timed out")
  830. if enrollee in ev:
  831. break
  832. if i == 1:
  833. raise Exception("Expected Enrollee not found")
  834. dev[0].request("WPS_ER_PBC " + enrollee)
  835. ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
  836. if ev is None:
  837. raise Exception("Enrollee did not report success")
  838. ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  839. if ev is None:
  840. raise Exception("Association with the AP timed out")
  841. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  842. if ev is None:
  843. raise Exception("WPS ER did not report success")
  844. hwsim_utils.test_connectivity_sta(dev[0], dev[1])
  845. # verify BSSID selection of the AP instead of UUID
  846. if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
  847. raise Exception("Could not select AP based on BSSID")
  848. def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
  849. """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
  850. ssid = "wps-er-add-enrollee-pbc"
  851. ap_pin = "12345670"
  852. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  853. hostapd.add_ap(apdev[0]['ifname'],
  854. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  855. "wpa_passphrase": "12345678", "wpa": "2",
  856. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  857. "device_name": "Wireless AP", "manufacturer": "Company",
  858. "model_name": "WAP", "model_number": "123",
  859. "serial_number": "12345", "device_type": "6-0050F204-1",
  860. "os_version": "01020300",
  861. "config_methods": "label push_button",
  862. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  863. logger.info("Learn AP configuration")
  864. dev[0].request("SET wps_version_number 0x10")
  865. dev[0].dump_monitor()
  866. dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
  867. status = dev[0].get_status()
  868. if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
  869. raise Exception("Not fully connected")
  870. logger.info("Start ER")
  871. dev[0].request("WPS_ER_START ifname=lo")
  872. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  873. if ev is None:
  874. raise Exception("AP discovery timed out")
  875. if ap_uuid not in ev:
  876. raise Exception("Expected AP UUID not found")
  877. logger.info("Use learned network configuration on ER")
  878. dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
  879. logger.info("Add Enrollee using ER and PIN")
  880. enrollee = dev[1].p2p_interface_addr()
  881. pin = dev[1].wps_read_pin()
  882. dev[0].dump_monitor()
  883. dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
  884. dev[1].dump_monitor()
  885. dev[1].request("WPS_PIN any " + pin)
  886. ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  887. if ev is None:
  888. raise Exception("Association with the AP timed out")
  889. ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
  890. if ev is None:
  891. raise Exception("WPS ER did not report success")
  892. def test_ap_wps_er_config_ap(dev, apdev):
  893. """WPS ER configuring AP over UPnP"""
  894. ssid = "wps-er-ap-config"
  895. ap_pin = "12345670"
  896. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  897. hostapd.add_ap(apdev[0]['ifname'],
  898. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  899. "wpa_passphrase": "12345678", "wpa": "2",
  900. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  901. "device_name": "Wireless AP", "manufacturer": "Company",
  902. "model_name": "WAP", "model_number": "123",
  903. "serial_number": "12345", "device_type": "6-0050F204-1",
  904. "os_version": "01020300",
  905. "config_methods": "label push_button",
  906. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
  907. logger.info("Connect ER to the AP")
  908. dev[0].connect(ssid, psk="12345678", scan_freq="2412")
  909. logger.info("WPS configuration step")
  910. dev[0].request("WPS_ER_START ifname=lo")
  911. ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
  912. if ev is None:
  913. raise Exception("AP discovery timed out")
  914. if ap_uuid not in ev:
  915. raise Exception("Expected AP UUID not found")
  916. new_passphrase = "1234567890"
  917. dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
  918. ssid.encode("hex") + " WPA2PSK CCMP " +
  919. new_passphrase.encode("hex"))
  920. ev = dev[0].wait_event(["WPS-SUCCESS"])
  921. if ev is None:
  922. raise Exception("WPS ER configuration operation timed out")
  923. dev[1].wait_event(["CTRL-EVENT-DISCONNECTED"])
  924. dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
  925. def test_ap_wps_fragmentation(dev, apdev):
  926. """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
  927. ssid = "test-wps-fragmentation"
  928. hostapd.add_ap(apdev[0]['ifname'],
  929. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  930. "wpa_passphrase": "12345678", "wpa": "3",
  931. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  932. "wpa_pairwise": "TKIP",
  933. "fragment_size": "50" })
  934. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  935. logger.info("WPS provisioning step")
  936. hapd.request("WPS_PBC")
  937. dev[0].dump_monitor()
  938. dev[0].request("SET wps_fragment_size 50")
  939. dev[0].request("WPS_PBC")
  940. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  941. if ev is None:
  942. raise Exception("Association with the AP timed out")
  943. status = dev[0].get_status()
  944. if status['wpa_state'] != 'COMPLETED':
  945. raise Exception("Not fully connected")
  946. if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
  947. raise Exception("Unexpected encryption configuration")
  948. if status['key_mgmt'] != 'WPA2-PSK':
  949. raise Exception("Unexpected key_mgmt")
  950. def test_ap_wps_new_version_sta(dev, apdev):
  951. """WPS compatibility with new version number on the station"""
  952. ssid = "test-wps-ver"
  953. hostapd.add_ap(apdev[0]['ifname'],
  954. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  955. "wpa_passphrase": "12345678", "wpa": "2",
  956. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
  957. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  958. logger.info("WPS provisioning step")
  959. hapd.request("WPS_PBC")
  960. dev[0].dump_monitor()
  961. dev[0].request("SET wps_version_number 0x43")
  962. dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
  963. dev[0].request("WPS_PBC")
  964. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  965. if ev is None:
  966. raise Exception("Association with the AP timed out")
  967. def test_ap_wps_new_version_ap(dev, apdev):
  968. """WPS compatibility with new version number on the AP"""
  969. ssid = "test-wps-ver"
  970. hostapd.add_ap(apdev[0]['ifname'],
  971. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  972. "wpa_passphrase": "12345678", "wpa": "2",
  973. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
  974. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  975. logger.info("WPS provisioning step")
  976. if "FAIL" in hapd.request("SET wps_version_number 0x43"):
  977. raise Exception("Failed to enable test functionality")
  978. hapd.request("WPS_PBC")
  979. dev[0].dump_monitor()
  980. dev[0].request("WPS_PBC")
  981. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  982. hapd.request("SET wps_version_number 0x20")
  983. if ev is None:
  984. raise Exception("Association with the AP timed out")
  985. def test_ap_wps_check_pin(dev, apdev):
  986. """Verify PIN checking through control interface"""
  987. hostapd.add_ap(apdev[0]['ifname'],
  988. { "ssid": "wps", "eap_server": "1", "wps_state": "2",
  989. "wpa_passphrase": "12345678", "wpa": "2",
  990. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
  991. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  992. for t in [ ("12345670", "12345670"),
  993. ("12345678", "FAIL-CHECKSUM"),
  994. ("1234-5670", "12345670"),
  995. ("1234 5670", "12345670"),
  996. ("1-2.3:4 5670", "12345670") ]:
  997. res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
  998. res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
  999. if res != res2:
  1000. raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
  1001. if res != t[1]:
  1002. raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
  1003. if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
  1004. raise Exception("Unexpected WPS_CHECK_PIN success")
  1005. if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
  1006. raise Exception("Unexpected WPS_CHECK_PIN success")
  1007. def test_ap_wps_wep_config(dev, apdev):
  1008. """WPS 2.0 AP rejecting WEP configuration"""
  1009. ssid = "test-wps-config"
  1010. appin = "12345670"
  1011. hostapd.add_ap(apdev[0]['ifname'],
  1012. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1013. "ap_pin": appin})
  1014. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1015. dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
  1016. "hello", no_wait=True)
  1017. ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
  1018. if ev is None:
  1019. raise Exception("WPS-FAIL timed out")
  1020. if "reason=2" not in ev:
  1021. raise Exception("Unexpected reason code in WPS-FAIL")
  1022. status = hapd.request("WPS_GET_STATUS")
  1023. if "Last WPS result: Failed" not in status:
  1024. raise Exception("WPS failure result not shown correctly")
  1025. if "Failure Reason: WEP Prohibited" not in status:
  1026. raise Exception("Failure reason not reported correctly")
  1027. if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
  1028. raise Exception("Peer address not shown correctly")
  1029. def test_ap_wps_wep_enroll(dev, apdev):
  1030. """WPS 2.0 STA rejecting WEP configuration"""
  1031. ssid = "test-wps-wep"
  1032. hostapd.add_ap(apdev[0]['ifname'],
  1033. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1034. "skip_cred_build": "1", "extra_cred": "wps-wep-cred" })
  1035. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1036. hapd.request("WPS_PBC")
  1037. dev[0].request("WPS_PBC")
  1038. ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
  1039. if ev is None:
  1040. raise Exception("WPS-FAIL event timed out")
  1041. if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
  1042. raise Exception("Unexpected WPS-FAIL event: " + ev)
  1043. def test_ap_wps_ie_fragmentation(dev, apdev):
  1044. """WPS AP using fragmented WPS IE"""
  1045. ssid = "test-wps-ie-fragmentation"
  1046. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1047. "wpa_passphrase": "12345678", "wpa": "2",
  1048. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1049. "device_name": "1234567890abcdef1234567890abcdef",
  1050. "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
  1051. "model_name": "1234567890abcdef1234567890abcdef",
  1052. "model_number": "1234567890abcdef1234567890abcdef",
  1053. "serial_number": "1234567890abcdef1234567890abcdef" }
  1054. hostapd.add_ap(apdev[0]['ifname'], params)
  1055. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1056. hapd.request("WPS_PBC")
  1057. dev[0].request("WPS_PBC")
  1058. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  1059. if ev is None:
  1060. raise Exception("Association with the AP timed out")
  1061. bss = dev[0].get_bss(apdev[0]['bssid'])
  1062. if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
  1063. logger.info(bss)
  1064. raise Exception("Device Name not received correctly")
  1065. if len(re.findall("dd..0050f204", bss['ie'])) != 2:
  1066. raise Exception("Unexpected number of WPS IEs")
  1067. def get_psk(pskfile):
  1068. psks = {}
  1069. with open(pskfile, "r") as f:
  1070. lines = f.read().splitlines()
  1071. for l in lines:
  1072. if l == "# WPA PSKs":
  1073. continue
  1074. (addr,psk) = l.split(' ')
  1075. psks[addr] = psk
  1076. return psks
  1077. def test_ap_wps_per_station_psk(dev, apdev):
  1078. """WPS PBC provisioning with per-station PSK"""
  1079. addr0 = dev[0].p2p_dev_addr()
  1080. addr1 = dev[1].p2p_dev_addr()
  1081. addr2 = dev[2].p2p_dev_addr()
  1082. ssid = "wps"
  1083. appin = "12345670"
  1084. pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
  1085. try:
  1086. os.remove(pskfile)
  1087. except:
  1088. pass
  1089. try:
  1090. with open(pskfile, "w") as f:
  1091. f.write("# WPA PSKs\n")
  1092. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1093. "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
  1094. "rsn_pairwise": "CCMP", "ap_pin": appin,
  1095. "wpa_psk_file": pskfile }
  1096. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  1097. logger.info("First enrollee")
  1098. hapd.request("WPS_PBC")
  1099. dev[0].request("WPS_PBC")
  1100. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"])
  1101. if ev is None:
  1102. raise Exception("Association with the AP timed out (1)")
  1103. logger.info("Second enrollee")
  1104. hapd.request("WPS_PBC")
  1105. dev[1].request("WPS_PBC")
  1106. ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"])
  1107. if ev is None:
  1108. raise Exception("Association with the AP timed out (2)")
  1109. logger.info("External registrar")
  1110. dev[2].wps_reg(apdev[0]['bssid'], appin)
  1111. logger.info("Verifying PSK results")
  1112. psks = get_psk(pskfile)
  1113. if addr0 not in psks:
  1114. raise Exception("No PSK recorded for sta0")
  1115. if addr1 not in psks:
  1116. raise Exception("No PSK recorded for sta1")
  1117. if addr2 not in psks:
  1118. raise Exception("No PSK recorded for sta2")
  1119. if psks[addr0] == psks[addr1]:
  1120. raise Exception("Same PSK recorded for sta0 and sta1")
  1121. if psks[addr0] == psks[addr2]:
  1122. raise Exception("Same PSK recorded for sta0 and sta2")
  1123. if psks[addr1] == psks[addr2]:
  1124. raise Exception("Same PSK recorded for sta1 and sta2")
  1125. dev[0].request("REMOVE_NETWORK all")
  1126. logger.info("Second external registrar")
  1127. dev[0].wps_reg(apdev[0]['bssid'], appin)
  1128. psks2 = get_psk(pskfile)
  1129. if addr0 not in psks2:
  1130. raise Exception("No PSK recorded for sta0(reg)")
  1131. if psks[addr0] == psks2[addr0]:
  1132. raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
  1133. finally:
  1134. os.remove(pskfile)
  1135. def test_ap_wps_per_station_psk_failure(dev, apdev):
  1136. """WPS PBC provisioning with per-station PSK (file not writable)"""
  1137. addr0 = dev[0].p2p_dev_addr()
  1138. addr1 = dev[1].p2p_dev_addr()
  1139. addr2 = dev[2].p2p_dev_addr()
  1140. ssid = "wps"
  1141. appin = "12345670"
  1142. pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
  1143. try:
  1144. os.remove(pskfile)
  1145. except:
  1146. pass
  1147. try:
  1148. with open(pskfile, "w") as f:
  1149. f.write("# WPA PSKs\n")
  1150. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1151. "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
  1152. "rsn_pairwise": "CCMP", "ap_pin": appin,
  1153. "wpa_psk_file": pskfile }
  1154. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  1155. if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
  1156. raise Exception("Failed to set wpa_psk_file")
  1157. logger.info("First enrollee")
  1158. hapd.request("WPS_PBC")
  1159. dev[0].request("WPS_PBC")
  1160. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"])
  1161. if ev is None:
  1162. raise Exception("Association with the AP timed out (1)")
  1163. logger.info("Second enrollee")
  1164. hapd.request("WPS_PBC")
  1165. dev[1].request("WPS_PBC")
  1166. ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"])
  1167. if ev is None:
  1168. raise Exception("Association with the AP timed out (2)")
  1169. logger.info("External registrar")
  1170. dev[2].wps_reg(apdev[0]['bssid'], appin)
  1171. logger.info("Verifying PSK results")
  1172. psks = get_psk(pskfile)
  1173. if len(psks) > 0:
  1174. raise Exception("PSK recorded unexpectedly")
  1175. finally:
  1176. os.remove(pskfile)
  1177. def test_ap_wps_pin_request_file(dev, apdev):
  1178. """WPS PIN provisioning with configured AP"""
  1179. ssid = "wps"
  1180. pinfile = "/tmp/ap_wps_pin_request_file.log"
  1181. if os.path.exists(pinfile):
  1182. subprocess.call(['sudo', 'rm', pinfile])
  1183. hostapd.add_ap(apdev[0]['ifname'],
  1184. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1185. "wps_pin_requests": pinfile,
  1186. "wpa_passphrase": "12345678", "wpa": "2",
  1187. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
  1188. hapd = hostapd.Hostapd(apdev[0]['ifname'])
  1189. uuid = dev[0].get_status_field("uuid")
  1190. pin = dev[0].wps_read_pin()
  1191. try:
  1192. dev[0].request("WPS_PIN any " + pin)
  1193. ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
  1194. if ev is None:
  1195. raise Exception("PIN needed event not shown")
  1196. if uuid not in ev:
  1197. raise Exception("UUID mismatch")
  1198. dev[0].request("WPS_CANCEL")
  1199. success = False
  1200. with open(pinfile, "r") as f:
  1201. lines = f.readlines()
  1202. for l in lines:
  1203. if uuid in l:
  1204. success = True
  1205. break
  1206. if not success:
  1207. raise Exception("PIN request entry not in the log file")
  1208. finally:
  1209. subprocess.call(['sudo', 'rm', pinfile])
  1210. def test_ap_wps_auto_setup_with_config_file(dev, apdev):
  1211. """WPS auto-setup with configuration file"""
  1212. conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
  1213. ifname = apdev[0]['ifname']
  1214. try:
  1215. with open(conffile, "w") as f:
  1216. f.write("driver=nl80211\n")
  1217. f.write("hw_mode=g\n")
  1218. f.write("channel=1\n")
  1219. f.write("ieee80211n=1\n")
  1220. f.write("interface=%s\n" % ifname)
  1221. f.write("ctrl_interface=/var/run/hostapd\n")
  1222. f.write("ssid=wps\n")
  1223. f.write("eap_server=1\n")
  1224. f.write("wps_state=1\n")
  1225. hostapd.add_bss('phy3', ifname, conffile)
  1226. hapd = hostapd.Hostapd(ifname)
  1227. hapd.request("WPS_PBC")
  1228. dev[0].request("WPS_PBC")
  1229. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
  1230. if ev is None:
  1231. raise Exception("Association with the AP timed out")
  1232. with open(conffile, "r") as f:
  1233. lines = f.read().splitlines()
  1234. vals = dict()
  1235. for l in lines:
  1236. try:
  1237. [name,value] = l.split('=', 1)
  1238. vals[name] = value
  1239. except ValueError, e:
  1240. if "# WPS configuration" in l:
  1241. pass
  1242. else:
  1243. raise Exception("Unexpected configuration line: " + l)
  1244. if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
  1245. raise Exception("Incorrect configuration: " + str(vals))
  1246. finally:
  1247. subprocess.call(['sudo', 'rm', conffile])
  1248. def add_ssdp_ap(ifname, ap_uuid):
  1249. ssid = "wps-ssdp"
  1250. ap_pin = "12345670"
  1251. hostapd.add_ap(ifname,
  1252. { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  1253. "wpa_passphrase": "12345678", "wpa": "2",
  1254. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  1255. "device_name": "Wireless AP", "manufacturer": "Company",
  1256. "model_name": "WAP", "model_number": "123",
  1257. "serial_number": "12345", "device_type": "6-0050F204-1",
  1258. "os_version": "01020300",
  1259. "config_methods": "label push_button",
  1260. "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
  1261. "friendly_name": "WPS Access Point",
  1262. "manufacturer_url": "http://www.example.com/",
  1263. "model_description": "Wireless Access Point",
  1264. "model_url": "http://www.example.com/model/",
  1265. "upc": "123456789012" })
  1266. def ssdp_send(msg, no_recv=False):
  1267. socket.setdefaulttimeout(1)
  1268. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  1269. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1270. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  1271. sock.bind(("127.0.0.1", 0))
  1272. sock.sendto(msg, ("239.255.255.250", 1900))
  1273. if no_recv:
  1274. return None
  1275. return sock.recv(1000)
  1276. def ssdp_send_msearch(st):
  1277. msg = '\r\n'.join([
  1278. 'M-SEARCH * HTTP/1.1',
  1279. 'HOST: 239.255.255.250:1900',
  1280. 'MX: 1',
  1281. 'MAN: "ssdp:discover"',
  1282. 'ST: ' + st,
  1283. '', ''])
  1284. return ssdp_send(msg)
  1285. def test_ap_wps_ssdp_msearch(dev, apdev):
  1286. """WPS AP and SSDP M-SEARCH messages"""
  1287. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1288. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  1289. msg = '\r\n'.join([
  1290. 'M-SEARCH * HTTP/1.1',
  1291. 'Host: 239.255.255.250:1900',
  1292. 'Mx: 1',
  1293. 'Man: "ssdp:discover"',
  1294. 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
  1295. '', ''])
  1296. ssdp_send(msg)
  1297. msg = '\r\n'.join([
  1298. 'M-SEARCH * HTTP/1.1',
  1299. 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
  1300. 'mx: \t1\t\t ',
  1301. 'man: \t \t "ssdp:discover" ',
  1302. 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
  1303. '', ''])
  1304. ssdp_send(msg)
  1305. ssdp_send_msearch("ssdp:all")
  1306. ssdp_send_msearch("upnp:rootdevice")
  1307. ssdp_send_msearch("uuid:" + ap_uuid)
  1308. ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
  1309. ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1");
  1310. msg = '\r\n'.join([
  1311. 'M-SEARCH * HTTP/1.1',
  1312. 'HOST:\t239.255.255.250:1900',
  1313. 'MAN: "ssdp:discover"',
  1314. 'MX: 130',
  1315. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1316. '', ''])
  1317. ssdp_send(msg, no_recv=True)
  1318. def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
  1319. """WPS AP and invalid SSDP M-SEARCH messages"""
  1320. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1321. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  1322. socket.setdefaulttimeout(1)
  1323. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  1324. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1325. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  1326. sock.bind(("127.0.0.1", 0))
  1327. logger.debug("Missing MX")
  1328. msg = '\r\n'.join([
  1329. 'M-SEARCH * HTTP/1.1',
  1330. 'HOST: 239.255.255.250:1900',
  1331. 'MAN: "ssdp:discover"',
  1332. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1333. '', ''])
  1334. sock.sendto(msg, ("239.255.255.250", 1900))
  1335. logger.debug("Negative MX")
  1336. msg = '\r\n'.join([
  1337. 'M-SEARCH * HTTP/1.1',
  1338. 'HOST: 239.255.255.250:1900',
  1339. 'MX: -1',
  1340. 'MAN: "ssdp:discover"',
  1341. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1342. '', ''])
  1343. sock.sendto(msg, ("239.255.255.250", 1900))
  1344. logger.debug("Invalid MX")
  1345. msg = '\r\n'.join([
  1346. 'M-SEARCH * HTTP/1.1',
  1347. 'HOST: 239.255.255.250:1900',
  1348. 'MX; 1',
  1349. 'MAN: "ssdp:discover"',
  1350. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1351. '', ''])
  1352. sock.sendto(msg, ("239.255.255.250", 1900))
  1353. logger.debug("Missing MAN")
  1354. msg = '\r\n'.join([
  1355. 'M-SEARCH * HTTP/1.1',
  1356. 'HOST: 239.255.255.250:1900',
  1357. 'MX: 1',
  1358. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1359. '', ''])
  1360. sock.sendto(msg, ("239.255.255.250", 1900))
  1361. logger.debug("Invalid MAN")
  1362. msg = '\r\n'.join([
  1363. 'M-SEARCH * HTTP/1.1',
  1364. 'HOST: 239.255.255.250:1900',
  1365. 'MX: 1',
  1366. 'MAN: foo',
  1367. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1368. '', ''])
  1369. sock.sendto(msg, ("239.255.255.250", 1900))
  1370. msg = '\r\n'.join([
  1371. 'M-SEARCH * HTTP/1.1',
  1372. 'HOST: 239.255.255.250:1900',
  1373. 'MX: 1',
  1374. 'MAN; "ssdp:discover"',
  1375. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1376. '', ''])
  1377. sock.sendto(msg, ("239.255.255.250", 1900))
  1378. logger.debug("Missing HOST")
  1379. msg = '\r\n'.join([
  1380. 'M-SEARCH * HTTP/1.1',
  1381. 'MAN: "ssdp:discover"',
  1382. 'MX: 1',
  1383. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1384. '', ''])
  1385. sock.sendto(msg, ("239.255.255.250", 1900))
  1386. logger.debug("Missing ST")
  1387. msg = '\r\n'.join([
  1388. 'M-SEARCH * HTTP/1.1',
  1389. 'HOST: 239.255.255.250:1900',
  1390. 'MAN: "ssdp:discover"',
  1391. 'MX: 1',
  1392. '', ''])
  1393. sock.sendto(msg, ("239.255.255.250", 1900))
  1394. logger.debug("Mismatching ST")
  1395. msg = '\r\n'.join([
  1396. 'M-SEARCH * HTTP/1.1',
  1397. 'HOST: 239.255.255.250:1900',
  1398. 'MAN: "ssdp:discover"',
  1399. 'MX: 1',
  1400. 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
  1401. '', ''])
  1402. sock.sendto(msg, ("239.255.255.250", 1900))
  1403. msg = '\r\n'.join([
  1404. 'M-SEARCH * HTTP/1.1',
  1405. 'HOST: 239.255.255.250:1900',
  1406. 'MAN: "ssdp:discover"',
  1407. 'MX: 1',
  1408. 'ST: foo:bar',
  1409. '', ''])
  1410. sock.sendto(msg, ("239.255.255.250", 1900))
  1411. msg = '\r\n'.join([
  1412. 'M-SEARCH * HTTP/1.1',
  1413. 'HOST: 239.255.255.250:1900',
  1414. 'MAN: "ssdp:discover"',
  1415. 'MX: 1',
  1416. 'ST: foobar',
  1417. '', ''])
  1418. sock.sendto(msg, ("239.255.255.250", 1900))
  1419. logger.debug("Invalid ST")
  1420. msg = '\r\n'.join([
  1421. 'M-SEARCH * HTTP/1.1',
  1422. 'HOST: 239.255.255.250:1900',
  1423. 'MAN: "ssdp:discover"',
  1424. 'MX: 1',
  1425. 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
  1426. '', ''])
  1427. sock.sendto(msg, ("239.255.255.250", 1900))
  1428. logger.debug("Invalid M-SEARCH")
  1429. msg = '\r\n'.join([
  1430. 'M+SEARCH * HTTP/1.1',
  1431. 'HOST: 239.255.255.250:1900',
  1432. 'MAN: "ssdp:discover"',
  1433. 'MX: 1',
  1434. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1435. '', ''])
  1436. sock.sendto(msg, ("239.255.255.250", 1900))
  1437. msg = '\r\n'.join([
  1438. 'M-SEARCH-* HTTP/1.1',
  1439. 'HOST: 239.255.255.250:1900',
  1440. 'MAN: "ssdp:discover"',
  1441. 'MX: 1',
  1442. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1443. '', ''])
  1444. sock.sendto(msg, ("239.255.255.250", 1900))
  1445. logger.debug("Invalid message format")
  1446. sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
  1447. msg = '\r'.join([
  1448. 'M-SEARCH * HTTP/1.1',
  1449. 'HOST: 239.255.255.250:1900',
  1450. 'MAN: "ssdp:discover"',
  1451. 'MX: 1',
  1452. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1453. '', ''])
  1454. sock.sendto(msg, ("239.255.255.250", 1900))
  1455. try:
  1456. r = sock.recv(1000)
  1457. raise Exception("Unexpected M-SEARCH response: " + r)
  1458. except socket.timeout:
  1459. pass
  1460. logger.debug("Valid M-SEARCH")
  1461. msg = '\r\n'.join([
  1462. 'M-SEARCH * HTTP/1.1',
  1463. 'HOST: 239.255.255.250:1900',
  1464. 'MAN: "ssdp:discover"',
  1465. 'MX: 1',
  1466. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1467. '', ''])
  1468. sock.sendto(msg, ("239.255.255.250", 1900))
  1469. try:
  1470. r = sock.recv(1000)
  1471. pass
  1472. except socket.timeout:
  1473. raise Exception("No SSDP response")
  1474. def test_ap_wps_ssdp_burst(dev, apdev):
  1475. """WPS AP and SSDP burst"""
  1476. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1477. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  1478. msg = '\r\n'.join([
  1479. 'M-SEARCH * HTTP/1.1',
  1480. 'HOST: 239.255.255.250:1900',
  1481. 'MAN: "ssdp:discover"',
  1482. 'MX: 1',
  1483. 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
  1484. '', ''])
  1485. socket.setdefaulttimeout(1)
  1486. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  1487. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1488. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  1489. sock.bind(("127.0.0.1", 0))
  1490. for i in range(0, 25):
  1491. sock.sendto(msg, ("239.255.255.250", 1900))
  1492. resp = 0
  1493. while True:
  1494. try:
  1495. r = sock.recv(1000)
  1496. if not r.startswith("HTTP/1.1 200 OK\r\n"):
  1497. raise Exception("Unexpected message: " + r)
  1498. resp += 1
  1499. except socket.timeout:
  1500. break
  1501. if resp < 20:
  1502. raise Exception("Too few SSDP responses")
  1503. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  1504. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1505. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  1506. sock.bind(("127.0.0.1", 0))
  1507. for i in range(0, 25):
  1508. sock.sendto(msg, ("239.255.255.250", 1900))
  1509. while True:
  1510. try:
  1511. r = sock.recv(1000)
  1512. if ap_uuid in r:
  1513. break
  1514. except socket.timeout:
  1515. raise Exception("No SSDP response")
  1516. def ssdp_get_location(uuid):
  1517. res = ssdp_send_msearch("uuid:" + uuid)
  1518. location = None
  1519. for l in res.splitlines():
  1520. if l.lower().startswith("location:"):
  1521. location = l.split(':', 1)[1].strip()
  1522. break
  1523. if location is None:
  1524. raise Exception("No UPnP location found")
  1525. return location
  1526. def upnp_get_urls(location):
  1527. conn = urllib.urlopen(location)
  1528. tree = ET.parse(conn)
  1529. root = tree.getroot()
  1530. urn = '{urn:schemas-upnp-org:device-1-0}'
  1531. service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
  1532. res = {}
  1533. res['scpd_url'] = urlparse.urljoin(location, service.find(urn + 'SCPDURL').text)
  1534. res['control_url'] = urlparse.urljoin(location, service.find(urn + 'controlURL').text)
  1535. res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
  1536. return res
  1537. def upnp_soap_action(conn, path, action, include_soap_action=True, soap_action_override=None):
  1538. soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
  1539. wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
  1540. ET.register_namespace('soapenv', soapns)
  1541. ET.register_namespace('wfa', wpsns)
  1542. attrib = {}
  1543. attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
  1544. root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
  1545. body = ET.SubElement(root, "{%s}Body" % soapns)
  1546. act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
  1547. tree = ET.ElementTree(root)
  1548. soap = StringIO.StringIO()
  1549. tree.write(soap, xml_declaration=True, encoding='utf-8')
  1550. headers = { "Content-type": 'text/xml; charset="utf-8"' }
  1551. if include_soap_action:
  1552. headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
  1553. elif soap_action_override:
  1554. headers["SOAPAction"] = soap_action_override
  1555. conn.request("POST", path, soap.getvalue(), headers)
  1556. return conn.getresponse()
  1557. def test_ap_wps_upnp(dev, apdev):
  1558. """WPS AP and UPnP operations"""
  1559. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1560. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  1561. location = ssdp_get_location(ap_uuid)
  1562. urls = upnp_get_urls(location)
  1563. conn = urllib.urlopen(urls['scpd_url'])
  1564. scpd = conn.read()
  1565. conn = urllib.urlopen(urlparse.urljoin(location, "unknown.html"))
  1566. if conn.getcode() != 404:
  1567. raise Exception("Unexpected HTTP response to GET unknown URL")
  1568. url = urlparse.urlparse(location)
  1569. conn = httplib.HTTPConnection(url.netloc)
  1570. #conn.set_debuglevel(1)
  1571. headers = { "Content-type": 'text/xml; charset="utf-8"',
  1572. "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
  1573. conn.request("POST", "hello", "\r\n\r\n", headers)
  1574. resp = conn.getresponse()
  1575. if resp.status != 404:
  1576. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1577. conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
  1578. resp = conn.getresponse()
  1579. if resp.status != 501:
  1580. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1581. headers = { "Content-type": 'text/xml; charset="utf-8"',
  1582. "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
  1583. ctrlurl = urlparse.urlparse(urls['control_url'])
  1584. conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
  1585. resp = conn.getresponse()
  1586. if resp.status != 401:
  1587. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1588. logger.debug("GetDeviceInfo without SOAPAction header")
  1589. resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
  1590. include_soap_action=False)
  1591. if resp.status != 401:
  1592. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1593. logger.debug("GetDeviceInfo with invalid SOAPAction header")
  1594. for act in [ "foo",
  1595. "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
  1596. '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
  1597. '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
  1598. resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
  1599. include_soap_action=False,
  1600. soap_action_override=act)
  1601. if resp.status != 401:
  1602. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1603. resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
  1604. if resp.status != 200:
  1605. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1606. dev = resp.read()
  1607. if "NewDeviceInfo" not in dev:
  1608. raise Exception("Unexpected GetDeviceInfo response")
  1609. logger.debug("PutMessage without required parameters")
  1610. resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
  1611. if resp.status != 600:
  1612. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1613. logger.debug("PutWLANResponse without required parameters")
  1614. resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
  1615. if resp.status != 600:
  1616. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1617. logger.debug("SetSelectedRegistrar from unregistered ER")
  1618. resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
  1619. if resp.status != 501:
  1620. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1621. logger.debug("Unknown action")
  1622. resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
  1623. if resp.status != 401:
  1624. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1625. def test_ap_wps_upnp_subscribe(dev, apdev):
  1626. """WPS AP and UPnP event subscription"""
  1627. ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
  1628. add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
  1629. location = ssdp_get_location(ap_uuid)
  1630. urls = upnp_get_urls(location)
  1631. eventurl = urlparse.urlparse(urls['event_sub_url'])
  1632. url = urlparse.urlparse(location)
  1633. conn = httplib.HTTPConnection(url.netloc)
  1634. #conn.set_debuglevel(1)
  1635. headers = { "callback": '<http://127.0.0.1:12345/event>',
  1636. "timeout": "Second-1234" }
  1637. conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
  1638. resp = conn.getresponse()
  1639. if resp.status != 412:
  1640. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1641. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1642. resp = conn.getresponse()
  1643. if resp.status != 412:
  1644. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1645. headers = { "NT": "upnp:event",
  1646. "timeout": "Second-1234" }
  1647. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1648. resp = conn.getresponse()
  1649. if resp.status != 412:
  1650. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1651. headers = { "callback": '<http://127.0.0.1:12345/event>',
  1652. "NT": "upnp:foobar",
  1653. "timeout": "Second-1234" }
  1654. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1655. resp = conn.getresponse()
  1656. if resp.status != 400:
  1657. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1658. logger.debug("Valid subscription")
  1659. headers = { "callback": '<http://127.0.0.1:12345/event>',
  1660. "NT": "upnp:event",
  1661. "timeout": "Second-1234" }
  1662. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1663. resp = conn.getresponse()
  1664. if resp.status != 200:
  1665. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1666. sid = resp.getheader("sid")
  1667. logger.debug("Subscription SID " + sid)
  1668. logger.debug("Invalid re-subscription")
  1669. headers = { "NT": "upnp:event",
  1670. "sid": "123456734567854",
  1671. "timeout": "Second-1234" }
  1672. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1673. resp = conn.getresponse()
  1674. if resp.status != 400:
  1675. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1676. logger.debug("Invalid re-subscription")
  1677. headers = { "NT": "upnp:event",
  1678. "sid": "uuid:123456734567854",
  1679. "timeout": "Second-1234" }
  1680. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1681. resp = conn.getresponse()
  1682. if resp.status != 400:
  1683. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1684. logger.debug("Invalid re-subscription")
  1685. headers = { "callback": '<http://127.0.0.1:12345/event>',
  1686. "NT": "upnp:event",
  1687. "sid": sid,
  1688. "timeout": "Second-1234" }
  1689. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1690. resp = conn.getresponse()
  1691. if resp.status != 400:
  1692. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1693. logger.debug("SID mismatch in re-subscription")
  1694. headers = { "NT": "upnp:event",
  1695. "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
  1696. "timeout": "Second-1234" }
  1697. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1698. resp = conn.getresponse()
  1699. if resp.status != 412:
  1700. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1701. logger.debug("Valid re-subscription")
  1702. headers = { "NT": "upnp:event",
  1703. "sid": sid,
  1704. "timeout": "Second-1234" }
  1705. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1706. resp = conn.getresponse()
  1707. if resp.status != 200:
  1708. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1709. sid2 = resp.getheader("sid")
  1710. logger.debug("Subscription SID " + sid2)
  1711. if sid != sid2:
  1712. raise Exception("Unexpected SID change")
  1713. logger.debug("Valid re-subscription")
  1714. headers = { "NT": "upnp:event",
  1715. "sid": "uuid: \t \t" + sid.split(':')[1],
  1716. "timeout": "Second-1234" }
  1717. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1718. resp = conn.getresponse()
  1719. if resp.status != 200:
  1720. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1721. logger.debug("Invalid unsubscription")
  1722. headers = { "sid": sid }
  1723. conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
  1724. resp = conn.getresponse()
  1725. if resp.status != 412:
  1726. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1727. headers = { "foo": "bar" }
  1728. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1729. resp = conn.getresponse()
  1730. if resp.status != 412:
  1731. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1732. logger.debug("Valid unsubscription")
  1733. headers = { "sid": sid }
  1734. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1735. resp = conn.getresponse()
  1736. if resp.status != 200:
  1737. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1738. logger.debug("Unsubscription for not existing SID")
  1739. headers = { "sid": sid }
  1740. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1741. resp = conn.getresponse()
  1742. if resp.status != 412:
  1743. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1744. logger.debug("Invalid unsubscription")
  1745. headers = { "sid": " \t \tfoo" }
  1746. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1747. resp = conn.getresponse()
  1748. if resp.status != 400:
  1749. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1750. logger.debug("Invalid unsubscription")
  1751. headers = { "sid": "uuid:\t \tfoo" }
  1752. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1753. resp = conn.getresponse()
  1754. if resp.status != 400:
  1755. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1756. logger.debug("Invalid unsubscription")
  1757. headers = { "NT": "upnp:event",
  1758. "sid": sid }
  1759. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1760. resp = conn.getresponse()
  1761. if resp.status != 400:
  1762. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1763. headers = { "callback": '<http://127.0.0.1:12345/event>',
  1764. "sid": sid }
  1765. conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1766. resp = conn.getresponse()
  1767. if resp.status != 400:
  1768. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1769. logger.debug("Valid subscription with multiple callbacks")
  1770. 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>',
  1771. "NT": "upnp:event",
  1772. "timeout": "Second-1234" }
  1773. conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
  1774. resp = conn.getresponse()
  1775. if resp.status != 200:
  1776. raise Exception("Unexpected HTTP response: %s" % resp.status)
  1777. sid = resp.getheader("sid")
  1778. logger.debug("Subscription SID " + sid)