wps-nfc.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. import wpaspy
  21. wpas_ctrl = '/var/run/wpa_supplicant'
  22. srv = None
  23. continue_loop = True
  24. terminate_now = False
  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. global no_wait
  188. if no_wait:
  189. print "Trying to exit.."
  190. global terminate_now
  191. terminate_now = True
  192. def wps_tag_read(tag, wait_remove=True):
  193. success = False
  194. if len(tag.ndef.message):
  195. for record in tag.ndef.message:
  196. print "record type " + record.type
  197. if record.type == "application/vnd.wfa.wsc":
  198. print "WPS tag - send to wpa_supplicant"
  199. success = wpas_tag_read(tag.ndef.message)
  200. break
  201. else:
  202. print "Empty tag"
  203. if wait_remove:
  204. print "Remove tag"
  205. while tag.is_present:
  206. time.sleep(0.1)
  207. return success
  208. def rdwr_connected_write(tag):
  209. print "Tag found - writing"
  210. global write_data
  211. tag.ndef.message = str(write_data)
  212. print "Done - remove tag"
  213. global only_one
  214. if only_one:
  215. global continue_loop
  216. continue_loop = False
  217. global write_wait_remove
  218. while write_wait_remove and tag.is_present:
  219. time.sleep(0.1)
  220. def wps_write_config_tag(clf, id=None, wait_remove=True):
  221. print "Write WPS config token"
  222. global write_data, write_wait_remove
  223. write_wait_remove = wait_remove
  224. write_data = wpas_get_config_token(id)
  225. if write_data == None:
  226. print "Could not get WPS config token from wpa_supplicant"
  227. sys.exit(1)
  228. return
  229. print "Touch an NFC tag"
  230. clf.connect(rdwr={'on-connect': rdwr_connected_write})
  231. def wps_write_er_config_tag(clf, uuid, wait_remove=True):
  232. print "Write WPS ER config token"
  233. global write_data, write_wait_remove
  234. write_wait_remove = wait_remove
  235. write_data = wpas_get_er_config_token(uuid)
  236. if write_data == None:
  237. print "Could not get WPS config token from wpa_supplicant"
  238. return
  239. print "Touch an NFC tag"
  240. clf.connect(rdwr={'on-connect': rdwr_connected_write})
  241. def wps_write_password_tag(clf, wait_remove=True):
  242. print "Write WPS password token"
  243. global write_data, write_wait_remove
  244. write_wait_remove = wait_remove
  245. write_data = wpas_get_password_token()
  246. if write_data == None:
  247. print "Could not get WPS password token from wpa_supplicant"
  248. return
  249. print "Touch an NFC tag"
  250. clf.connect(rdwr={'on-connect': rdwr_connected_write})
  251. def rdwr_connected(tag):
  252. global only_one, no_wait
  253. print "Tag connected: " + str(tag)
  254. if tag.ndef:
  255. print "NDEF tag: " + tag.type
  256. try:
  257. print tag.ndef.message.pretty()
  258. except Exception, e:
  259. print e
  260. success = wps_tag_read(tag, not only_one)
  261. if only_one and success:
  262. global continue_loop
  263. continue_loop = False
  264. else:
  265. print "Not an NDEF tag - remove tag"
  266. return not no_wait
  267. def llcp_worker(llc):
  268. global arg_uuid
  269. if arg_uuid is None:
  270. wps_handover_init(llc)
  271. print "Exiting llcp_worker thread"
  272. return
  273. global srv
  274. global wait_connection
  275. while not wait_connection and srv.sent_carrier is None:
  276. if srv.ho_server_processing:
  277. time.sleep(0.025)
  278. def llcp_startup(clf, llc):
  279. global arg_uuid
  280. if arg_uuid:
  281. print "Start LLCP server"
  282. global srv
  283. srv = HandoverServer(llc)
  284. if arg_uuid is "ap":
  285. print "Trying to handle WPS handover"
  286. srv.uuid = None
  287. else:
  288. print "Trying to handle WPS handover with AP " + arg_uuid
  289. srv.uuid = arg_uuid
  290. return llc
  291. def llcp_connected(llc):
  292. print "P2P LLCP connected"
  293. global wait_connection
  294. wait_connection = False
  295. global arg_uuid
  296. if arg_uuid:
  297. global srv
  298. srv.start()
  299. else:
  300. threading.Thread(target=llcp_worker, args=(llc,)).start()
  301. print "llcp_connected returning"
  302. return True
  303. def terminate_loop():
  304. global terminate_now
  305. return terminate_now
  306. def main():
  307. clf = nfc.ContactlessFrontend()
  308. parser = argparse.ArgumentParser(description='nfcpy to wpa_supplicant integration for WPS NFC operations')
  309. parser.add_argument('-d', const=logging.DEBUG, default=logging.INFO,
  310. action='store_const', dest='loglevel',
  311. help='verbose debug output')
  312. parser.add_argument('-q', const=logging.WARNING, action='store_const',
  313. dest='loglevel', help='be quiet')
  314. parser.add_argument('--only-one', '-1', action='store_true',
  315. help='run only one operation and exit')
  316. parser.add_argument('--no-wait', action='store_true',
  317. help='do not wait for tag to be removed before exiting')
  318. parser.add_argument('--uuid',
  319. help='UUID of an AP (used for WPS ER operations)')
  320. parser.add_argument('--id',
  321. help='network id (used for WPS ER operations)')
  322. parser.add_argument('command', choices=['write-config',
  323. 'write-er-config',
  324. 'write-password'],
  325. nargs='?')
  326. args = parser.parse_args()
  327. global arg_uuid
  328. arg_uuid = args.uuid
  329. global only_one
  330. only_one = args.only_one
  331. global no_wait
  332. no_wait = args.no_wait
  333. logging.basicConfig(level=args.loglevel)
  334. try:
  335. if not clf.open("usb"):
  336. print "Could not open connection with an NFC device"
  337. raise SystemExit
  338. if args.command == "write-config":
  339. wps_write_config_tag(clf, id=args.id, wait_remove=not args.no_wait)
  340. raise SystemExit
  341. if args.command == "write-er-config":
  342. wps_write_er_config_tag(clf, args.uuid, wait_remove=not args.no_wait)
  343. raise SystemExit
  344. if args.command == "write-password":
  345. wps_write_password_tag(clf, wait_remove=not args.no_wait)
  346. raise SystemExit
  347. global continue_loop
  348. while continue_loop:
  349. print "Waiting for a tag or peer to be touched"
  350. wait_connection = True
  351. try:
  352. if not clf.connect(rdwr={'on-connect': rdwr_connected},
  353. llcp={'on-startup': llcp_startup,
  354. 'on-connect': llcp_connected},
  355. terminate=terminate_loop):
  356. break
  357. except Exception, e:
  358. print "clf.connect failed"
  359. global srv
  360. if only_one and srv and srv.success:
  361. raise SystemExit
  362. except KeyboardInterrupt:
  363. raise SystemExit
  364. finally:
  365. clf.close()
  366. raise SystemExit
  367. if __name__ == '__main__':
  368. main()