3 # Example nfcpy to wpa_supplicant wrapper for WPS NFC operations
4 # Copyright (c) 2012-2013, Jouni Malinen <j@w1.fi>
6 # This software may be distributed under the terms of the BSD license.
7 # See README for more details.
27 wpas_ctrl = '/var/run/wpa_supplicant'
34 if os.path.isdir(wpas_ctrl):
36 ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
37 except OSError, error:
38 print "Could not find wpa_supplicant: ", error
42 print "No wpa_supplicant control interface found"
47 wpas = wpaspy.Ctrl(ctrl)
54 def wpas_tag_read(message):
58 if "FAIL" in wpas.request("WPS_NFC_TAG_READ " + str(message).encode("hex")):
62 def wpas_get_config_token(id=None):
67 ret = wpas.request("WPS_NFC_CONFIG_TOKEN NDEF " + id)
69 ret = wpas.request("WPS_NFC_CONFIG_TOKEN NDEF")
72 return ret.rstrip().decode("hex")
75 def wpas_get_er_config_token(uuid):
79 ret = wpas.request("WPS_ER_NFC_CONFIG_TOKEN NDEF " + uuid)
82 return ret.rstrip().decode("hex")
85 def wpas_get_password_token():
89 return wpas.request("WPS_NFC_TOKEN NDEF").rstrip().decode("hex")
92 def wpas_get_handover_req():
96 return wpas.request("NFC_GET_HANDOVER_REQ NDEF WPS-CR").rstrip().decode("hex")
99 def wpas_get_handover_sel(uuid):
100 wpas = wpas_connect()
104 res = wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR").rstrip()
106 res = wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR " + uuid).rstrip()
109 return res.decode("hex")
112 def wpas_report_handover(req, sel, type):
113 wpas = wpas_connect()
116 return wpas.request("NFC_REPORT_HANDOVER " + type + " WPS " +
117 str(req).encode("hex") + " " +
118 str(sel).encode("hex"))
121 class HandoverServer(nfc.handover.HandoverServer):
122 def __init__(self, llc):
123 super(HandoverServer, self).__init__(llc)
124 self.sent_carrier = None
125 self.ho_server_processing = False
128 def process_request(self, request):
129 self.ho_server_processing = True
130 print "HandoverServer - request received"
131 print "Parsed handover request: " + request.pretty()
133 sel = nfc.ndef.HandoverSelectMessage(version="1.2")
135 for carrier in request.carriers:
136 print "Remote carrier type: " + carrier.type
137 if carrier.type == "application/vnd.wfa.wsc":
138 print "WPS carrier type match - add WPS carrier record"
139 data = wpas_get_handover_sel(self.uuid)
141 print "Could not get handover select carrier record from wpa_supplicant"
143 print "Handover select carrier record from wpa_supplicant:"
144 print data.encode("hex")
145 self.sent_carrier = data
146 wpas_report_handover(carrier.record, self.sent_carrier, "RESP")
148 message = nfc.ndef.Message(data);
149 sel.add_carrier(message[0], "active", message[1:])
151 print "Handover select:"
153 print str(sel).encode("hex")
155 print "Sending handover select"
160 def wps_handover_init(llc):
161 print "Trying to initiate WPS handover"
163 data = wpas_get_handover_req()
165 print "Could not get handover request carrier record from wpa_supplicant"
167 print "Handover request carrier record from wpa_supplicant: " + data.encode("hex")
168 record = nfc.ndef.Record()
169 f = StringIO.StringIO(data)
171 record = nfc.ndef.HandoverCarrierRecord(record)
172 print "Parsed handover request carrier record:"
173 print record.pretty()
175 message = nfc.ndef.HandoverRequestMessage(version="1.2")
176 message.nonce = random.randint(0, 0xffff)
177 message.add_carrier(record, "active")
179 print "Handover request:"
180 print message.pretty()
182 client = nfc.handover.HandoverClient(llc)
184 print "Trying handover";
186 print "Connected for handover"
187 except nfc.llcp.ConnectRefused:
188 print "Handover connection refused"
192 print "Sending handover request"
194 if not client.send(message):
195 print "Failed to send handover request"
197 print "Receiving handover response"
198 message = client._recv()
200 print "No response received"
203 if message.type != "urn:nfc:wkt:Hs":
204 print "Response was not Hs - received: " + message.type
208 print "Received message"
209 print message.pretty()
210 message = nfc.ndef.HandoverSelectMessage(message)
211 print "Handover select received"
212 print message.pretty()
214 for carrier in message.carriers:
215 print "Remote carrier type: " + carrier.type
216 if carrier.type == "application/vnd.wfa.wsc":
217 print "WPS carrier type match - send to wpa_supplicant"
218 wpas_report_handover(data, carrier.record, "INIT")
219 wifi = nfc.ndef.WifiConfigRecord(carrier.record)
224 print "Done with handover"
228 continue_loop = False
232 print "Trying to exit.."
236 def wps_tag_read(tag, wait_remove=True):
238 if len(tag.ndef.message):
239 for record in tag.ndef.message:
240 print "record type " + record.type
241 if record.type == "application/vnd.wfa.wsc":
242 print "WPS tag - send to wpa_supplicant"
243 success = wpas_tag_read(tag.ndef.message)
250 while tag.is_present:
256 def rdwr_connected_write(tag):
257 print "Tag found - writing"
259 tag.ndef.message = str(write_data)
260 print "Done - remove tag"
264 continue_loop = False
265 global write_wait_remove
266 while write_wait_remove and tag.is_present:
269 def wps_write_config_tag(clf, id=None, wait_remove=True):
270 print "Write WPS config token"
271 global write_data, write_wait_remove
272 write_wait_remove = wait_remove
273 write_data = wpas_get_config_token(id)
274 if write_data == None:
275 print "Could not get WPS config token from wpa_supplicant"
278 print "Touch an NFC tag"
279 clf.connect(rdwr={'on-connect': rdwr_connected_write})
282 def wps_write_er_config_tag(clf, uuid, wait_remove=True):
283 print "Write WPS ER config token"
284 global write_data, write_wait_remove
285 write_wait_remove = wait_remove
286 write_data = wpas_get_er_config_token(uuid)
287 if write_data == None:
288 print "Could not get WPS config token from wpa_supplicant"
291 print "Touch an NFC tag"
292 clf.connect(rdwr={'on-connect': rdwr_connected_write})
295 def wps_write_password_tag(clf, wait_remove=True):
296 print "Write WPS password token"
297 global write_data, write_wait_remove
298 write_wait_remove = wait_remove
299 write_data = wpas_get_password_token()
300 if write_data == None:
301 print "Could not get WPS password token from wpa_supplicant"
304 print "Touch an NFC tag"
305 clf.connect(rdwr={'on-connect': rdwr_connected_write})
308 def rdwr_connected(tag):
309 global only_one, no_wait
310 print "Tag connected: " + str(tag)
313 print "NDEF tag: " + tag.type
315 print tag.ndef.message.pretty()
318 success = wps_tag_read(tag, not only_one)
319 if only_one and success:
321 continue_loop = False
323 print "Not an NDEF tag - remove tag"
328 def llcp_worker(llc):
331 wps_handover_init(llc)
332 print "Exiting llcp_worker thread"
336 global wait_connection
337 while not wait_connection and srv.sent_carrier is None:
338 if srv.ho_server_processing:
341 def llcp_startup(clf, llc):
344 print "Start LLCP server"
346 srv = HandoverServer(llc)
348 print "Trying to handle WPS handover"
351 print "Trying to handle WPS handover with AP " + arg_uuid
355 def llcp_connected(llc):
356 print "P2P LLCP connected"
357 global wait_connection
358 wait_connection = False
364 threading.Thread(target=llcp_worker, args=(llc,)).start()
365 print "llcp_connected returning"
369 def terminate_loop():
374 clf = nfc.ContactlessFrontend()
376 parser = argparse.ArgumentParser(description='nfcpy to wpa_supplicant integration for WPS NFC operations')
377 parser.add_argument('--only-one', '-1', action='store_true',
378 help='run only one operation and exit')
379 parser.add_argument('--no-wait', action='store_true',
380 help='do not wait for tag to be removed before exiting')
381 parser.add_argument('--uuid',
382 help='UUID of an AP (used for WPS ER operations)')
383 parser.add_argument('--id',
384 help='network id (used for WPS ER operations)')
385 parser.add_argument('command', choices=['write-config',
389 args = parser.parse_args()
395 only_one = args.only_one
398 no_wait = args.no_wait
401 if not clf.open("usb"):
402 print "Could not open connection with an NFC device"
405 if args.command == "write-config":
406 wps_write_config_tag(clf, id=args.id, wait_remove=not args.no_wait)
409 if args.command == "write-er-config":
410 wps_write_er_config_tag(clf, args.uuid, wait_remove=not args.no_wait)
413 if args.command == "write-password":
414 wps_write_password_tag(clf, wait_remove=not args.no_wait)
419 print "Waiting for a tag or peer to be touched"
420 wait_connection = True
422 if not clf.connect(rdwr={'on-connect': rdwr_connected},
423 llcp={'on-startup': llcp_startup,
424 'on-connect': llcp_connected},
425 terminate=terminate_loop):
428 print "clf.connect failed"
431 if only_one and srv and srv.success:
434 except KeyboardInterrupt:
441 if __name__ == '__main__':