wps-nfc.py 13 KB

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