wps-nfc.py 12 KB

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