blob: 258d84148fe1c7e0690669adacf6f243541a1325 [file] [log] [blame]
Dmitry Shmidtf8623282013-02-20 14:34:59 -08001#!/usr/bin/python
2#
3# Example nfcpy to hostapd 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
9import os
10import sys
11import time
Dmitry Shmidtcf32e602014-01-28 10:57:39 -080012import argparse
Dmitry Shmidtf8623282013-02-20 14:34:59 -080013
14import nfc
15import nfc.ndef
16import nfc.llcp
17import nfc.handover
18
19import logging
Dmitry Shmidtf8623282013-02-20 14:34:59 -080020
Dmitry Shmidt700a1372013-03-15 14:14:44 -070021import wpaspy
Dmitry Shmidtf8623282013-02-20 14:34:59 -080022
23wpas_ctrl = '/var/run/hostapd'
Dmitry Shmidtcf32e602014-01-28 10:57:39 -080024continue_loop = True
Dmitry Shmidt96be6222014-02-13 10:16:51 -080025summary_file = None
26success_file = None
27
28def summary(txt):
Hai Shalom74f70d42019-02-11 14:42:39 -080029 print(txt)
Dmitry Shmidt96be6222014-02-13 10:16:51 -080030 if summary_file:
31 with open(summary_file, 'a') as f:
32 f.write(txt + "\n")
33
34def success_report(txt):
35 summary(txt)
36 if success_file:
37 with open(success_file, 'a') as f:
38 f.write(txt + "\n")
Dmitry Shmidtf8623282013-02-20 14:34:59 -080039
40def wpas_connect():
41 ifaces = []
42 if os.path.isdir(wpas_ctrl):
43 try:
44 ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
Hai Shalom74f70d42019-02-11 14:42:39 -080045 except OSError as error:
46 print("Could not find hostapd: ", error)
Dmitry Shmidtf8623282013-02-20 14:34:59 -080047 return None
48
49 if len(ifaces) < 1:
Hai Shalom74f70d42019-02-11 14:42:39 -080050 print("No hostapd control interface found")
Dmitry Shmidtf8623282013-02-20 14:34:59 -080051 return None
52
53 for ctrl in ifaces:
54 try:
Dmitry Shmidt700a1372013-03-15 14:14:44 -070055 wpas = wpaspy.Ctrl(ctrl)
Dmitry Shmidtf8623282013-02-20 14:34:59 -080056 return wpas
Hai Shalom74f70d42019-02-11 14:42:39 -080057 except Exception as e:
Dmitry Shmidtf8623282013-02-20 14:34:59 -080058 pass
59 return None
60
61
62def wpas_tag_read(message):
63 wpas = wpas_connect()
64 if (wpas == None):
Dmitry Shmidt96be6222014-02-13 10:16:51 -080065 return False
Dmitry Shmidtcf32e602014-01-28 10:57:39 -080066 if "FAIL" in wpas.request("WPS_NFC_TAG_READ " + str(message).encode("hex")):
67 return False
68 return True
Dmitry Shmidtf8623282013-02-20 14:34:59 -080069
70
71def wpas_get_config_token():
72 wpas = wpas_connect()
73 if (wpas == None):
74 return None
Dmitry Shmidt96be6222014-02-13 10:16:51 -080075 ret = wpas.request("WPS_NFC_CONFIG_TOKEN NDEF")
76 if "FAIL" in ret:
77 return None
78 return ret.rstrip().decode("hex")
Dmitry Shmidtf8623282013-02-20 14:34:59 -080079
80
81def wpas_get_password_token():
82 wpas = wpas_connect()
83 if (wpas == None):
84 return None
Dmitry Shmidt96be6222014-02-13 10:16:51 -080085 ret = wpas.request("WPS_NFC_TOKEN NDEF")
86 if "FAIL" in ret:
87 return None
88 return ret.rstrip().decode("hex")
Dmitry Shmidtf8623282013-02-20 14:34:59 -080089
90
91def wpas_get_handover_sel():
92 wpas = wpas_connect()
93 if (wpas == None):
94 return None
Dmitry Shmidt96be6222014-02-13 10:16:51 -080095 ret = wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR")
96 if "FAIL" in ret:
97 return None
98 return ret.rstrip().decode("hex")
Dmitry Shmidtf8623282013-02-20 14:34:59 -080099
100
101def wpas_report_handover(req, sel):
102 wpas = wpas_connect()
103 if (wpas == None):
104 return None
105 return wpas.request("NFC_REPORT_HANDOVER RESP WPS " +
106 str(req).encode("hex") + " " +
107 str(sel).encode("hex"))
108
109
110class HandoverServer(nfc.handover.HandoverServer):
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800111 def __init__(self, llc):
112 super(HandoverServer, self).__init__(llc)
113 self.ho_server_processing = False
114 self.success = False
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800115
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800116 # override to avoid parser error in request/response.pretty() in nfcpy
117 # due to new WSC handover format
118 def _process_request(self, request):
119 summary("received handover request {}".format(request.type))
120 response = nfc.ndef.Message("\xd1\x02\x01Hs\x12")
121 if not request.type == 'urn:nfc:wkt:Hr':
122 summary("not a handover request")
123 else:
124 try:
125 request = nfc.ndef.HandoverRequestMessage(request)
126 except nfc.ndef.DecodeError as e:
127 summary("error decoding 'Hr' message: {}".format(e))
128 else:
129 response = self.process_request(request)
130 summary("send handover response {}".format(response.type))
131 return response
132
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800133 def process_request(self, request):
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800134 summary("HandoverServer - request received")
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800135 try:
Hai Shalom74f70d42019-02-11 14:42:39 -0800136 print("Parsed handover request: " + request.pretty())
137 except Exception as e:
138 print(e)
139 print(str(request).encode("hex"))
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800140
141 sel = nfc.ndef.HandoverSelectMessage(version="1.2")
142
143 for carrier in request.carriers:
Hai Shalom74f70d42019-02-11 14:42:39 -0800144 print("Remote carrier type: " + carrier.type)
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800145 if carrier.type == "application/vnd.wfa.wsc":
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800146 summary("WPS carrier type match - add WPS carrier record")
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800147 data = wpas_get_handover_sel()
148 if data is None:
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800149 summary("Could not get handover select carrier record from hostapd")
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800150 continue
Hai Shalom74f70d42019-02-11 14:42:39 -0800151 print("Handover select carrier record from hostapd:")
152 print(data.encode("hex"))
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800153 if "OK" in wpas_report_handover(carrier.record, data):
154 success_report("Handover reported successfully")
155 else:
156 summary("Handover report rejected")
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800157
158 message = nfc.ndef.Message(data);
159 sel.add_carrier(message[0], "active", message[1:])
160
Hai Shalom74f70d42019-02-11 14:42:39 -0800161 print("Handover select:")
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800162 try:
Hai Shalom74f70d42019-02-11 14:42:39 -0800163 print(sel.pretty())
164 except Exception as e:
165 print(e)
166 print(str(sel).encode("hex"))
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800167
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800168 summary("Sending handover select")
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800169 self.success = True
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800170 return sel
171
172
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800173def wps_tag_read(tag):
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800174 success = False
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800175 if len(tag.ndef.message):
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800176 for record in tag.ndef.message:
Hai Shalom74f70d42019-02-11 14:42:39 -0800177 print("record type " + record.type)
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800178 if record.type == "application/vnd.wfa.wsc":
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800179 summary("WPS tag - send to hostapd")
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800180 success = wpas_tag_read(tag.ndef.message)
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800181 break
182 else:
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800183 summary("Empty tag")
184
185 if success:
186 success_report("Tag read succeeded")
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800187
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800188 return success
189
190
191def rdwr_connected_write(tag):
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800192 summary("Tag found - writing - " + str(tag))
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800193 global write_data
194 tag.ndef.message = str(write_data)
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800195 success_report("Tag write succeeded")
Hai Shalom74f70d42019-02-11 14:42:39 -0800196 print("Done - remove tag")
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800197 global only_one
198 if only_one:
199 global continue_loop
200 continue_loop = False
201 global write_wait_remove
202 while write_wait_remove and tag.is_present:
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800203 time.sleep(0.1)
204
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800205def wps_write_config_tag(clf, wait_remove=True):
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800206 summary("Write WPS config token")
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800207 global write_data, write_wait_remove
208 write_wait_remove = wait_remove
209 write_data = wpas_get_config_token()
210 if write_data == None:
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800211 summary("Could not get WPS config token from hostapd")
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800212 return
213
Hai Shalom74f70d42019-02-11 14:42:39 -0800214 print("Touch an NFC tag")
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800215 clf.connect(rdwr={'on-connect': rdwr_connected_write})
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800216
217
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800218def wps_write_password_tag(clf, wait_remove=True):
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800219 summary("Write WPS password token")
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800220 global write_data, write_wait_remove
221 write_wait_remove = wait_remove
222 write_data = wpas_get_password_token()
223 if write_data == None:
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800224 summary("Could not get WPS password token from hostapd")
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800225 return
226
Hai Shalom74f70d42019-02-11 14:42:39 -0800227 print("Touch an NFC tag")
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800228 clf.connect(rdwr={'on-connect': rdwr_connected_write})
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800229
230
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800231def rdwr_connected(tag):
232 global only_one, no_wait
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800233 summary("Tag connected: " + str(tag))
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800234
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800235 if tag.ndef:
Hai Shalom74f70d42019-02-11 14:42:39 -0800236 print("NDEF tag: " + tag.type)
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800237 try:
Hai Shalom74f70d42019-02-11 14:42:39 -0800238 print(tag.ndef.message.pretty())
239 except Exception as e:
240 print(e)
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800241 success = wps_tag_read(tag)
242 if only_one and success:
243 global continue_loop
244 continue_loop = False
245 else:
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800246 summary("Not an NDEF tag - remove tag")
247 return True
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800248
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800249 return not no_wait
250
251
252def llcp_startup(clf, llc):
Hai Shalom74f70d42019-02-11 14:42:39 -0800253 print("Start LLCP server")
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800254 global srv
255 srv = HandoverServer(llc)
256 return llc
257
258def llcp_connected(llc):
Hai Shalom74f70d42019-02-11 14:42:39 -0800259 print("P2P LLCP connected")
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800260 global wait_connection
261 wait_connection = False
262 global srv
263 srv.start()
264 return True
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800265
266
267def main():
268 clf = nfc.ContactlessFrontend()
269
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800270 parser = argparse.ArgumentParser(description='nfcpy to hostapd integration for WPS NFC operations')
271 parser.add_argument('-d', const=logging.DEBUG, default=logging.INFO,
272 action='store_const', dest='loglevel',
273 help='verbose debug output')
274 parser.add_argument('-q', const=logging.WARNING, action='store_const',
275 dest='loglevel', help='be quiet')
276 parser.add_argument('--only-one', '-1', action='store_true',
277 help='run only one operation and exit')
278 parser.add_argument('--no-wait', action='store_true',
279 help='do not wait for tag to be removed before exiting')
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800280 parser.add_argument('--summary',
281 help='summary file for writing status updates')
282 parser.add_argument('--success',
283 help='success file for writing success update')
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800284 parser.add_argument('command', choices=['write-config',
285 'write-password'],
286 nargs='?')
287 args = parser.parse_args()
288
289 global only_one
290 only_one = args.only_one
291
292 global no_wait
293 no_wait = args.no_wait
294
Dmitry Shmidt96be6222014-02-13 10:16:51 -0800295 if args.summary:
296 global summary_file
297 summary_file = args.summary
298
299 if args.success:
300 global success_file
301 success_file = args.success
302
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800303 logging.basicConfig(level=args.loglevel)
304
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800305 try:
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800306 if not clf.open("usb"):
Hai Shalom74f70d42019-02-11 14:42:39 -0800307 print("Could not open connection with an NFC device")
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800308 raise SystemExit
309
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800310 if args.command == "write-config":
311 wps_write_config_tag(clf, wait_remove=not args.no_wait)
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800312 raise SystemExit
313
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800314 if args.command == "write-password":
315 wps_write_password_tag(clf, wait_remove=not args.no_wait)
316 raise SystemExit
317
318 global continue_loop
319 while continue_loop:
Hai Shalom74f70d42019-02-11 14:42:39 -0800320 print("Waiting for a tag or peer to be touched")
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800321 wait_connection = True
322 try:
323 if not clf.connect(rdwr={'on-connect': rdwr_connected},
324 llcp={'on-startup': llcp_startup,
325 'on-connect': llcp_connected}):
326 break
Hai Shalom74f70d42019-02-11 14:42:39 -0800327 except Exception as e:
328 print("clf.connect failed")
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800329
Dmitry Shmidtcf32e602014-01-28 10:57:39 -0800330 global srv
331 if only_one and srv and srv.success:
332 raise SystemExit
Dmitry Shmidtf8623282013-02-20 14:34:59 -0800333
334 except KeyboardInterrupt:
335 raise SystemExit
336 finally:
337 clf.close()
338
339 raise SystemExit
340
341if __name__ == '__main__':
342 main()