wps-nfc.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. #!/usr/bin/python
  2. #
  3. # Example nfcpy to wpa_supplicant wrapper for WPS NFC operations
  4. # Copyright (c) 2012-2013, Jouni Malinen <j@w1.fi>
  5. #
  6. # This software may be distributed under the terms of the BSD license.
  7. # See README for more details.
  8. import os
  9. import sys
  10. import time
  11. import random
  12. import StringIO
  13. import threading
  14. import nfc
  15. import nfc.ndef
  16. import nfc.llcp
  17. import nfc.handover
  18. import logging
  19. logging.basicConfig()
  20. import wpaspy
  21. wpas_ctrl = '/var/run/wpa_supplicant'
  22. srv = None
  23. continue_loop = True
  24. def wpas_connect():
  25. ifaces = []
  26. if os.path.isdir(wpas_ctrl):
  27. try:
  28. ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
  29. except OSError, error:
  30. print "Could not find wpa_supplicant: ", error
  31. return None
  32. if len(ifaces) < 1:
  33. print "No wpa_supplicant control interface found"
  34. return None
  35. for ctrl in ifaces:
  36. try:
  37. wpas = wpaspy.Ctrl(ctrl)
  38. return wpas
  39. except Exception, e:
  40. pass
  41. return None
  42. def wpas_tag_read(message):
  43. wpas = wpas_connect()
  44. if (wpas == None):
  45. return False
  46. if "FAIL" in wpas.request("WPS_NFC_TAG_READ " + str(message).encode("hex")):
  47. return False
  48. return True
  49. def wpas_get_config_token(id=None):
  50. wpas = wpas_connect()
  51. if (wpas == None):
  52. return None
  53. if id:
  54. ret = wpas.request("WPS_NFC_CONFIG_TOKEN NDEF " + id)
  55. else:
  56. ret = wpas.request("WPS_NFC_CONFIG_TOKEN NDEF")
  57. if "FAIL" in ret:
  58. return None
  59. return ret.rstrip().decode("hex")
  60. def wpas_get_er_config_token(uuid):
  61. wpas = wpas_connect()
  62. if (wpas == None):
  63. return None
  64. return wpas.request("WPS_ER_NFC_CONFIG_TOKEN NDEF " + uuid).rstrip().decode("hex")
  65. def wpas_get_password_token():
  66. wpas = wpas_connect()
  67. if (wpas == None):
  68. return None
  69. return wpas.request("WPS_NFC_TOKEN NDEF").rstrip().decode("hex")
  70. def wpas_get_handover_req():
  71. wpas = wpas_connect()
  72. if (wpas == None):
  73. return None
  74. return wpas.request("NFC_GET_HANDOVER_REQ NDEF WPS-CR").rstrip().decode("hex")
  75. def wpas_get_handover_sel(uuid):
  76. wpas = wpas_connect()
  77. if (wpas == None):
  78. return None
  79. if uuid is None:
  80. return wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR").rstrip().decode("hex")
  81. return wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR " + uuid).rstrip().decode("hex")
  82. def wpas_report_handover(req, sel, type):
  83. wpas = wpas_connect()
  84. if (wpas == None):
  85. return None
  86. return wpas.request("NFC_REPORT_HANDOVER " + type + " WPS " +
  87. str(req).encode("hex") + " " +
  88. str(sel).encode("hex"))
  89. class HandoverServer(nfc.handover.HandoverServer):
  90. def __init__(self, llc):
  91. super(HandoverServer, self).__init__(llc)
  92. self.sent_carrier = None
  93. self.ho_server_processing = False
  94. self.success = False
  95. def process_request(self, request):
  96. self.ho_server_processing = True
  97. print "HandoverServer - request received"
  98. print "Parsed handover request: " + request.pretty()
  99. sel = nfc.ndef.HandoverSelectMessage(version="1.2")
  100. for carrier in request.carriers:
  101. print "Remote carrier type: " + carrier.type
  102. if carrier.type == "application/vnd.wfa.wsc":
  103. print "WPS carrier type match - add WPS carrier record"
  104. data = wpas_get_handover_sel(self.uuid)
  105. if data is None:
  106. print "Could not get handover select carrier record from wpa_supplicant"
  107. continue
  108. print "Handover select carrier record from wpa_supplicant:"
  109. print data.encode("hex")
  110. self.sent_carrier = data
  111. wpas_report_handover(carrier.record, self.sent_carrier, "RESP")
  112. message = nfc.ndef.Message(data);
  113. sel.add_carrier(message[0], "active", message[1:])
  114. print "Handover select:"
  115. print sel.pretty()
  116. print str(sel).encode("hex")
  117. print "Sending handover select"
  118. self.success = True
  119. return sel
  120. def wps_handover_init(llc):
  121. print "Trying to initiate WPS handover"
  122. data = wpas_get_handover_req()
  123. if (data == None):
  124. print "Could not get handover request carrier record from wpa_supplicant"
  125. return
  126. print "Handover request carrier record from wpa_supplicant: " + data.encode("hex")
  127. record = nfc.ndef.Record()
  128. f = StringIO.StringIO(data)
  129. record._read(f)
  130. record = nfc.ndef.HandoverCarrierRecord(record)
  131. print "Parsed handover request carrier record:"
  132. print record.pretty()
  133. message = nfc.ndef.HandoverRequestMessage(version="1.2")
  134. message.nonce = random.randint(0, 0xffff)
  135. message.add_carrier(record, "active")
  136. print "Handover request:"
  137. print message.pretty()
  138. client = nfc.handover.HandoverClient(llc)
  139. try:
  140. print "Trying handover";
  141. client.connect()
  142. print "Connected for handover"
  143. except nfc.llcp.ConnectRefused:
  144. print "Handover connection refused"
  145. client.close()
  146. return
  147. print "Sending handover request"
  148. if not client.send(message):
  149. print "Failed to send handover request"
  150. print "Receiving handover response"
  151. message = client._recv()
  152. if message is None:
  153. print "No response received"
  154. client.close()
  155. return
  156. if message.type != "urn:nfc:wkt:Hs":
  157. print "Response was not Hs - received: " + message.type
  158. client.close()
  159. return
  160. print "Received message"
  161. print message.pretty()
  162. message = nfc.ndef.HandoverSelectMessage(message)
  163. print "Handover select received"
  164. print message.pretty()
  165. for carrier in message.carriers:
  166. print "Remote carrier type: " + carrier.type
  167. if carrier.type == "application/vnd.wfa.wsc":
  168. print "WPS carrier type match - send to wpa_supplicant"
  169. wpas_report_handover(data, carrier.record, "INIT")
  170. wifi = nfc.ndef.WifiConfigRecord(carrier.record)
  171. print wifi.pretty()
  172. print "Remove peer"
  173. client.close()
  174. print "Done with handover"
  175. global only_one
  176. if only_one:
  177. global continue_loop
  178. continue_loop = False
  179. def wps_tag_read(tag, wait_remove=True):
  180. success = False
  181. if len(tag.ndef.message):
  182. for record in tag.ndef.message:
  183. print "record type " + record.type
  184. if record.type == "application/vnd.wfa.wsc":
  185. print "WPS tag - send to wpa_supplicant"
  186. success = wpas_tag_read(tag.ndef.message)
  187. break
  188. else:
  189. print "Empty tag"
  190. if wait_remove:
  191. print "Remove tag"
  192. while tag.is_present:
  193. time.sleep(0.1)
  194. return success
  195. def rdwr_connected_write(tag):
  196. print "Tag found - writing"
  197. global write_data
  198. tag.ndef.message = str(write_data)
  199. print "Done - remove tag"
  200. global only_one
  201. if only_one:
  202. global continue_loop
  203. continue_loop = False
  204. global write_wait_remove
  205. while write_wait_remove and tag.is_present:
  206. time.sleep(0.1)
  207. def wps_write_config_tag(clf, id=None, wait_remove=True):
  208. print "Write WPS config token"
  209. global write_data, write_wait_remove
  210. write_wait_remove = wait_remove
  211. write_data = wpas_get_config_token(id)
  212. if write_data == None:
  213. print "Could not get WPS config token from wpa_supplicant"
  214. sys.exit(1)
  215. return
  216. print "Touch an NFC tag"
  217. clf.connect(rdwr={'on-connect': rdwr_connected_write})
  218. def wps_write_er_config_tag(clf, uuid):
  219. print "Write WPS ER config token"
  220. global write_data, write_wait_remove
  221. write_wait_remove = True
  222. write_data = wpas_get_er_config_token(uuid)
  223. if write_data == None:
  224. print "Could not get WPS config token from wpa_supplicant"
  225. return
  226. print "Touch an NFC tag"
  227. clf.connect(rdwr={'on-connect': rdwr_connected_write})
  228. def wps_write_password_tag(clf, wait_remove=True):
  229. print "Write WPS password token"
  230. global write_data, write_wait_remove
  231. write_wait_remove = wait_remove
  232. write_data = wpas_get_password_token()
  233. if write_data == None:
  234. print "Could not get WPS password token from wpa_supplicant"
  235. return
  236. print "Touch an NFC tag"
  237. clf.connect(rdwr={'on-connect': rdwr_connected_write})
  238. def rdwr_connected(tag):
  239. global only_one
  240. print "Tag connected: " + str(tag)
  241. if tag.ndef:
  242. print "NDEF tag: " + tag.type
  243. try:
  244. print tag.ndef.message.pretty()
  245. except Exception, e:
  246. print e
  247. success = wps_tag_read(tag, not only_one)
  248. if only_one and success:
  249. global continue_loop
  250. continue_loop = False
  251. else:
  252. print "Not an NDEF tag - remove tag"
  253. while tag.is_present:
  254. time.sleep(0.1)
  255. return True
  256. def llcp_worker(llc):
  257. global arg_uuid
  258. if arg_uuid is None:
  259. wps_handover_init(llc)
  260. return
  261. global srv
  262. global wait_connection
  263. while not wait_connection and srv.sent_carrier is None:
  264. if srv.ho_server_processing:
  265. time.sleep(0.025)
  266. def llcp_startup(clf, llc):
  267. global arg_uuid
  268. if arg_uuid:
  269. print "Start LLCP server"
  270. global srv
  271. srv = HandoverServer(llc)
  272. if arg_uuid is "ap":
  273. print "Trying to handle WPS handover"
  274. srv.uuid = None
  275. else:
  276. print "Trying to handle WPS handover with AP " + arg_uuid
  277. srv.uuid = arg_uuid
  278. return llc
  279. def llcp_connected(llc):
  280. print "P2P LLCP connected"
  281. global wait_connection
  282. wait_connection = False
  283. global arg_uuid
  284. if arg_uuid:
  285. global srv
  286. srv.start()
  287. else:
  288. threading.Thread(target=llcp_worker, args=(llc,)).start()
  289. return True
  290. def main():
  291. clf = nfc.ContactlessFrontend()
  292. try:
  293. global arg_uuid
  294. arg_uuid = None
  295. if len(sys.argv) > 1 and sys.argv[1] != '-1':
  296. arg_uuid = sys.argv[1]
  297. global only_one
  298. if len(sys.argv) > 1 and sys.argv[1] == '-1':
  299. only_one = True
  300. else:
  301. only_one = False
  302. if not clf.open("usb"):
  303. print "Could not open connection with an NFC device"
  304. raise SystemExit
  305. if len(sys.argv) > 1 and sys.argv[1] == "write-config":
  306. wps_write_config_tag(clf)
  307. raise SystemExit
  308. if len(sys.argv) > 1 and sys.argv[1] == "write-config-no-wait":
  309. wps_write_config_tag(clf, wait_remove=False)
  310. raise SystemExit
  311. if len(sys.argv) > 2 and sys.argv[1] == "write-config-id":
  312. wps_write_config_tag(clf, sys.argv[2])
  313. raise SystemExit
  314. if len(sys.argv) > 2 and sys.argv[1] == "write-er-config":
  315. wps_write_er_config_tag(clf, sys.argv[2])
  316. raise SystemExit
  317. if len(sys.argv) > 1 and sys.argv[1] == "write-password":
  318. wps_write_password_tag(clf)
  319. raise SystemExit
  320. if len(sys.argv) > 1 and sys.argv[1] == "write-password-no-wait":
  321. wps_write_password_tag(clf, wait_remove=False)
  322. raise SystemExit
  323. global continue_loop
  324. while continue_loop:
  325. print "Waiting for a tag or peer to be touched"
  326. wait_connection = True
  327. try:
  328. if not clf.connect(rdwr={'on-connect': rdwr_connected},
  329. llcp={'on-startup': llcp_startup,
  330. 'on-connect': llcp_connected}):
  331. break
  332. except Exception, e:
  333. print "clf.connect failed"
  334. global srv
  335. if only_one and srv and srv.success:
  336. raise SystemExit
  337. except KeyboardInterrupt:
  338. raise SystemExit
  339. finally:
  340. clf.close()
  341. raise SystemExit
  342. if __name__ == '__main__':
  343. main()