wps-nfc.py 12 KB

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