blob: 35d12706e52ac1bc3ab4a8bc5eeef6add20af6e3 [file] [log] [blame]
Dmitry Shmidtd5e49232012-12-03 15:08:10 -08001#!/usr/bin/python
2#
3# Example nfcpy to wpa_supplicant wrapper for WPS NFC operations
Dmitry Shmidtf8623282013-02-20 14:34:59 -08004# Copyright (c) 2012-2013, Jouni Malinen <j@w1.fi>
Dmitry Shmidtd5e49232012-12-03 15:08:10 -08005#
6# This software may be distributed under the terms of the BSD license.
7# See README for more details.
8
9import os
10import sys
11import time
Dmitry Shmidtf8623282013-02-20 14:34:59 -080012import random
Dmitry Shmidtcf32e602014-01-28 10:57:39 -080013import threading
14import argparse
Dmitry Shmidtd5e49232012-12-03 15:08:10 -080015
16import nfc
17import nfc.ndef
18import nfc.llcp
19import nfc.handover
20
Dmitry Shmidtf8623282013-02-20 14:34:59 -080021import logging
Dmitry Shmidtf8623282013-02-20 14:34:59 -080022
Dmitry Shmidt700a1372013-03-15 14:14:44 -070023import wpaspy
Dmitry Shmidtd5e49232012-12-03 15:08:10 -080024
25wpas_ctrl = '/var/run/wpa_supplicant'
Dmitry Shmidtcf32e602014-01-28 10:57:39 -080026srv = None
27continue_loop = True
28terminate_now = False
Dmitry Shmidtd5e49232012-12-03 15:08:10 -080029
30def wpas_connect():
31 ifaces = []
32 if os.path.isdir(wpas_ctrl):
33 try:
34 ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
35 except OSError, error:
36 print "Could not find wpa_supplicant: ", error
37 return None
38
39 if len(ifaces) < 1:
40 print "No wpa_supplicant control interface found"
41 return None
42
43 for ctrl in ifaces:
44 try:
Dmitry Shmidt700a1372013-03-15 14:14:44 -070045 wpas = wpaspy.Ctrl(ctrl)
Dmitry Shmidtd5e49232012-12-03 15:08:10 -080046 return wpas
Dmitry Shmidt700a1372013-03-15 14:14:44 -070047 except Exception, e:
Dmitry Shmidtd5e49232012-12-03 15:08:10 -080048 pass
49 return None
50
51
52def wpas_tag_read(message):
53 wpas = wpas_connect()
54 if (wpas == None):
Dmitry Shmidt4b060592013-04-29 16:42:49 -070055 return False
Dmitry Shmidtcf32e602014-01-28 10:57:39 -080056 if "FAIL" in wpas.request("WPS_NFC_TAG_READ " + str(message).encode("hex")):
Dmitry Shmidt4b060592013-04-29 16:42:49 -070057 return False
58 return True
Dmitry Shmidtd5e49232012-12-03 15:08:10 -080059
Dmitry Shmidt1e78e762013-04-02 11:05:36 -070060def wpas_get_config_token(id=None):
Dmitry Shmidtf8623282013-02-20 14:34:59 -080061 wpas = wpas_connect()
62 if (wpas == None):
63 return None
Dmitry Shmidt1e78e762013-04-02 11:05:36 -070064 if id:
Dmitry Shmidt4b060592013-04-29 16:42:49 -070065 ret = wpas.request("WPS_NFC_CONFIG_TOKEN NDEF " + id)
66 else:
67 ret = wpas.request("WPS_NFC_CONFIG_TOKEN NDEF")
68 if "FAIL" in ret:
69 return None
70 return ret.rstrip().decode("hex")
Dmitry Shmidtf8623282013-02-20 14:34:59 -080071
72
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -080073def wpas_get_er_config_token(uuid):
74 wpas = wpas_connect()
75 if (wpas == None):
76 return None
Dmitry Shmidtcf32e602014-01-28 10:57:39 -080077 ret = wpas.request("WPS_ER_NFC_CONFIG_TOKEN NDEF " + uuid)
78 if "FAIL" in ret:
79 return None
80 return ret.rstrip().decode("hex")
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -080081
82
Dmitry Shmidtf8623282013-02-20 14:34:59 -080083def wpas_get_password_token():
84 wpas = wpas_connect()
85 if (wpas == None):
86 return None
87 return wpas.request("WPS_NFC_TOKEN NDEF").rstrip().decode("hex")
88
89
Dmitry Shmidtd5e49232012-12-03 15:08:10 -080090def wpas_get_handover_req():
91 wpas = wpas_connect()
92 if (wpas == None):
93 return None
Dmitry Shmidtf8623282013-02-20 14:34:59 -080094 return wpas.request("NFC_GET_HANDOVER_REQ NDEF WPS-CR").rstrip().decode("hex")
Dmitry Shmidtd5e49232012-12-03 15:08:10 -080095
96
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -080097def wpas_get_handover_sel(uuid):
Dmitry Shmidtd5e49232012-12-03 15:08:10 -080098 wpas = wpas_connect()
99 if (wpas == None):
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800100 return None
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800101 if uuid is None:
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800102 res = wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR").rstrip()
103 else:
104 res = wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR " + uuid).rstrip()
105 if "FAIL" in res:
106 return None
107 return res.decode("hex")
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800108
109
110def wpas_report_handover(req, sel, type):
111 wpas = wpas_connect()
112 if (wpas == None):
113 return None
114 return wpas.request("NFC_REPORT_HANDOVER " + type + " WPS " +
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800115 str(req).encode("hex") + " " +
116 str(sel).encode("hex"))
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800117
118
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800119class HandoverServer(nfc.handover.HandoverServer):
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800120 def __init__(self, llc):
121 super(HandoverServer, self).__init__(llc)
122 self.sent_carrier = None
123 self.ho_server_processing = False
124 self.success = False
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800125
126 def process_request(self, request):
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800127 self.ho_server_processing = True
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800128 print "HandoverServer - request received"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800129 try:
130 print "Parsed handover request: " + request.pretty()
131 except Exception, e:
132 print e
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800133
134 sel = nfc.ndef.HandoverSelectMessage(version="1.2")
135
136 for carrier in request.carriers:
137 print "Remote carrier type: " + carrier.type
138 if carrier.type == "application/vnd.wfa.wsc":
139 print "WPS carrier type match - add WPS carrier record"
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800140 data = wpas_get_handover_sel(self.uuid)
141 if data is None:
142 print "Could not get handover select carrier record from wpa_supplicant"
143 continue
144 print "Handover select carrier record from wpa_supplicant:"
145 print data.encode("hex")
146 self.sent_carrier = data
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800147 wpas_report_handover(carrier.record, self.sent_carrier, "RESP")
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800148
149 message = nfc.ndef.Message(data);
150 sel.add_carrier(message[0], "active", message[1:])
151
152 print "Handover select:"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800153 try:
154 print sel.pretty()
155 except Exception, e:
156 print e
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800157 print str(sel).encode("hex")
158
159 print "Sending handover select"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800160 self.success = True
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800161 return sel
162
163
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800164def wps_handover_init(llc):
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800165 print "Trying to initiate WPS handover"
166
167 data = wpas_get_handover_req()
168 if (data == None):
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800169 print "Could not get handover request carrier record from wpa_supplicant"
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800170 return
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800171 print "Handover request carrier record from wpa_supplicant: " + data.encode("hex")
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800172
173 message = nfc.ndef.HandoverRequestMessage(version="1.2")
174 message.nonce = random.randint(0, 0xffff)
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800175 datamsg = nfc.ndef.Message(data)
176 message.add_carrier(datamsg[0], "active", datamsg[1:])
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800177
178 print "Handover request:"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800179 try:
180 print message.pretty()
181 except Exception, e:
182 print e
183 print str(message).encode("hex")
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800184
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800185 client = nfc.handover.HandoverClient(llc)
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800186 try:
187 print "Trying handover";
188 client.connect()
189 print "Connected for handover"
190 except nfc.llcp.ConnectRefused:
191 print "Handover connection refused"
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800192 client.close()
193 return
194
195 print "Sending handover request"
196
197 if not client.send(message):
198 print "Failed to send handover request"
199
200 print "Receiving handover response"
201 message = client._recv()
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800202 if message is None:
203 print "No response received"
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800204 client.close()
205 return
206 if message.type != "urn:nfc:wkt:Hs":
207 print "Response was not Hs - received: " + message.type
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800208 client.close()
209 return
210
211 print "Received message"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800212 try:
213 print message.pretty()
214 except Exception, e:
215 print e
216 print str(message).encode("hex")
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800217 message = nfc.ndef.HandoverSelectMessage(message)
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800218 print "Handover select received"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800219 try:
220 print message.pretty()
221 except Exception, e:
222 print e
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800223
224 for carrier in message.carriers:
225 print "Remote carrier type: " + carrier.type
226 if carrier.type == "application/vnd.wfa.wsc":
227 print "WPS carrier type match - send to wpa_supplicant"
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800228 wpas_report_handover(data, carrier.record, "INIT")
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800229 # nfcpy does not support the new format..
230 #wifi = nfc.ndef.WifiConfigRecord(carrier.record)
231 #print wifi.pretty()
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800232
233 print "Remove peer"
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800234 client.close()
235 print "Done with handover"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800236 global only_one
237 if only_one:
238 global continue_loop
239 continue_loop = False
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800240
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800241 global no_wait
242 if no_wait:
243 print "Trying to exit.."
244 global terminate_now
245 terminate_now = True
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800246
Dmitry Shmidt4b060592013-04-29 16:42:49 -0700247def wps_tag_read(tag, wait_remove=True):
248 success = False
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800249 if len(tag.ndef.message):
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800250 for record in tag.ndef.message:
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800251 print "record type " + record.type
252 if record.type == "application/vnd.wfa.wsc":
253 print "WPS tag - send to wpa_supplicant"
Dmitry Shmidt4b060592013-04-29 16:42:49 -0700254 success = wpas_tag_read(tag.ndef.message)
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800255 break
256 else:
257 print "Empty tag"
258
Dmitry Shmidt4b060592013-04-29 16:42:49 -0700259 if wait_remove:
260 print "Remove tag"
261 while tag.is_present:
262 time.sleep(0.1)
263
264 return success
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800265
266
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800267def rdwr_connected_write(tag):
268 print "Tag found - writing"
269 global write_data
270 tag.ndef.message = str(write_data)
271 print "Done - remove tag"
272 global only_one
273 if only_one:
274 global continue_loop
275 continue_loop = False
276 global write_wait_remove
277 while write_wait_remove and tag.is_present:
278 time.sleep(0.1)
279
Dmitry Shmidt4b060592013-04-29 16:42:49 -0700280def wps_write_config_tag(clf, id=None, wait_remove=True):
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800281 print "Write WPS config token"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800282 global write_data, write_wait_remove
283 write_wait_remove = wait_remove
284 write_data = wpas_get_config_token(id)
285 if write_data == None:
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800286 print "Could not get WPS config token from wpa_supplicant"
Dmitry Shmidt4b060592013-04-29 16:42:49 -0700287 sys.exit(1)
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800288 return
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800289 print "Touch an NFC tag"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800290 clf.connect(rdwr={'on-connect': rdwr_connected_write})
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800291
292
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800293def wps_write_er_config_tag(clf, uuid, wait_remove=True):
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800294 print "Write WPS ER config token"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800295 global write_data, write_wait_remove
296 write_wait_remove = wait_remove
297 write_data = wpas_get_er_config_token(uuid)
298 if write_data == None:
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800299 print "Could not get WPS config token from wpa_supplicant"
300 return
301
302 print "Touch an NFC tag"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800303 clf.connect(rdwr={'on-connect': rdwr_connected_write})
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800304
305
Dmitry Shmidt4b060592013-04-29 16:42:49 -0700306def wps_write_password_tag(clf, wait_remove=True):
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800307 print "Write WPS password token"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800308 global write_data, write_wait_remove
309 write_wait_remove = wait_remove
310 write_data = wpas_get_password_token()
311 if write_data == None:
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800312 print "Could not get WPS password token from wpa_supplicant"
313 return
314
315 print "Touch an NFC tag"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800316 clf.connect(rdwr={'on-connect': rdwr_connected_write})
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800317
318
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800319def rdwr_connected(tag):
320 global only_one, no_wait
321 print "Tag connected: " + str(tag)
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800322
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800323 if tag.ndef:
324 print "NDEF tag: " + tag.type
325 try:
326 print tag.ndef.message.pretty()
327 except Exception, e:
328 print e
329 success = wps_tag_read(tag, not only_one)
330 if only_one and success:
331 global continue_loop
332 continue_loop = False
333 else:
334 print "Not an NDEF tag - remove tag"
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800335
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800336 return not no_wait
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800337
338
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800339def llcp_worker(llc):
340 global arg_uuid
341 if arg_uuid is None:
342 wps_handover_init(llc)
343 print "Exiting llcp_worker thread"
344 return
345
346 global srv
347 global wait_connection
348 while not wait_connection and srv.sent_carrier is None:
349 if srv.ho_server_processing:
350 time.sleep(0.025)
351
352def llcp_startup(clf, llc):
353 global arg_uuid
354 if arg_uuid:
355 print "Start LLCP server"
356 global srv
357 srv = HandoverServer(llc)
358 if arg_uuid is "ap":
359 print "Trying to handle WPS handover"
360 srv.uuid = None
361 else:
362 print "Trying to handle WPS handover with AP " + arg_uuid
363 srv.uuid = arg_uuid
364 return llc
365
366def llcp_connected(llc):
367 print "P2P LLCP connected"
368 global wait_connection
369 wait_connection = False
370 global arg_uuid
371 if arg_uuid:
372 global srv
373 srv.start()
374 else:
375 threading.Thread(target=llcp_worker, args=(llc,)).start()
376 print "llcp_connected returning"
377 return True
378
379
380def terminate_loop():
381 global terminate_now
382 return terminate_now
383
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800384def main():
385 clf = nfc.ContactlessFrontend()
386
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800387 parser = argparse.ArgumentParser(description='nfcpy to wpa_supplicant integration for WPS NFC operations')
388 parser.add_argument('-d', const=logging.DEBUG, default=logging.INFO,
389 action='store_const', dest='loglevel',
390 help='verbose debug output')
391 parser.add_argument('-q', const=logging.WARNING, action='store_const',
392 dest='loglevel', help='be quiet')
393 parser.add_argument('--only-one', '-1', action='store_true',
394 help='run only one operation and exit')
395 parser.add_argument('--no-wait', action='store_true',
396 help='do not wait for tag to be removed before exiting')
397 parser.add_argument('--uuid',
398 help='UUID of an AP (used for WPS ER operations)')
399 parser.add_argument('--id',
400 help='network id (used for WPS ER operations)')
401 parser.add_argument('command', choices=['write-config',
402 'write-er-config',
403 'write-password'],
404 nargs='?')
405 args = parser.parse_args()
406
407 global arg_uuid
408 arg_uuid = args.uuid
409
410 global only_one
411 only_one = args.only_one
412
413 global no_wait
414 no_wait = args.no_wait
415
416 logging.basicConfig(level=args.loglevel)
417
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800418 try:
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800419 if not clf.open("usb"):
420 print "Could not open connection with an NFC device"
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800421 raise SystemExit
422
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800423 if args.command == "write-config":
424 wps_write_config_tag(clf, id=args.id, wait_remove=not args.no_wait)
Dmitry Shmidt4b060592013-04-29 16:42:49 -0700425 raise SystemExit
426
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800427 if args.command == "write-er-config":
428 wps_write_er_config_tag(clf, args.uuid, wait_remove=not args.no_wait)
Dmitry Shmidt1e78e762013-04-02 11:05:36 -0700429 raise SystemExit
430
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800431 if args.command == "write-password":
432 wps_write_password_tag(clf, wait_remove=not args.no_wait)
Dmitry Shmidt33e38bf2013-02-27 12:56:00 -0800433 raise SystemExit
434
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800435 global continue_loop
436 while continue_loop:
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800437 print "Waiting for a tag or peer to be touched"
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800438 wait_connection = True
439 try:
440 if not clf.connect(rdwr={'on-connect': rdwr_connected},
441 llcp={'on-startup': llcp_startup,
442 'on-connect': llcp_connected},
443 terminate=terminate_loop):
Dmitry Shmidt4b060592013-04-29 16:42:49 -0700444 break
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800445 except Exception, e:
446 print "clf.connect failed"
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800447
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800448 global srv
449 if only_one and srv and srv.success:
450 raise SystemExit
Dmitry Shmidtd5e49232012-12-03 15:08:10 -0800451
452 except KeyboardInterrupt:
453 raise SystemExit
454 finally:
455 clf.close()
456
457 raise SystemExit
458
459if __name__ == '__main__':
460 main()