3 # Example nfcpy to hostapd 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.
23 wpas_ctrl = '/var/run/hostapd'
31 with open(summary_file, 'a') as f:
34 def success_report(txt):
37 with open(success_file, 'a') as f:
42 if os.path.isdir(wpas_ctrl):
44 ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
45 except OSError, error:
46 print "Could not find hostapd: ", error
50 print "No hostapd control interface found"
55 wpas = wpaspy.Ctrl(ctrl)
62 def wpas_tag_read(message):
66 if "FAIL" in wpas.request("WPS_NFC_TAG_READ " + str(message).encode("hex")):
71 def wpas_get_config_token():
75 ret = wpas.request("WPS_NFC_CONFIG_TOKEN NDEF")
78 return ret.rstrip().decode("hex")
81 def wpas_get_password_token():
85 ret = wpas.request("WPS_NFC_TOKEN NDEF")
88 return ret.rstrip().decode("hex")
91 def wpas_get_handover_sel():
95 ret = wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR")
98 return ret.rstrip().decode("hex")
101 def wpas_report_handover(req, sel):
102 wpas = wpas_connect()
105 return wpas.request("NFC_REPORT_HANDOVER RESP WPS " +
106 str(req).encode("hex") + " " +
107 str(sel).encode("hex"))
110 class HandoverServer(nfc.handover.HandoverServer):
111 def __init__(self, llc):
112 super(HandoverServer, self).__init__(llc)
113 self.ho_server_processing = False
116 # 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")
125 request = nfc.ndef.HandoverRequestMessage(request)
126 except nfc.ndef.DecodeError as e:
127 summary("error decoding 'Hr' message: {}".format(e))
129 response = self.process_request(request)
130 summary("send handover response {}".format(response.type))
133 def process_request(self, request):
134 summary("HandoverServer - request received")
136 print "Parsed handover request: " + request.pretty()
139 print str(request).encode("hex")
141 sel = nfc.ndef.HandoverSelectMessage(version="1.2")
143 for carrier in request.carriers:
144 print "Remote carrier type: " + carrier.type
145 if carrier.type == "application/vnd.wfa.wsc":
146 summary("WPS carrier type match - add WPS carrier record")
147 data = wpas_get_handover_sel()
149 summary("Could not get handover select carrier record from hostapd")
151 print "Handover select carrier record from hostapd:"
152 print data.encode("hex")
153 if "OK" in wpas_report_handover(carrier.record, data):
154 success_report("Handover reported successfully")
156 summary("Handover report rejected")
158 message = nfc.ndef.Message(data);
159 sel.add_carrier(message[0], "active", message[1:])
161 print "Handover select:"
166 print str(sel).encode("hex")
168 summary("Sending handover select")
173 def wps_tag_read(tag):
175 if len(tag.ndef.message):
176 for record in tag.ndef.message:
177 print "record type " + record.type
178 if record.type == "application/vnd.wfa.wsc":
179 summary("WPS tag - send to hostapd")
180 success = wpas_tag_read(tag.ndef.message)
186 success_report("Tag read succeeded")
191 def rdwr_connected_write(tag):
192 summary("Tag found - writing - " + str(tag))
194 tag.ndef.message = str(write_data)
195 success_report("Tag write succeeded")
196 print "Done - remove tag"
200 continue_loop = False
201 global write_wait_remove
202 while write_wait_remove and tag.is_present:
205 def wps_write_config_tag(clf, wait_remove=True):
206 summary("Write WPS config token")
207 global write_data, write_wait_remove
208 write_wait_remove = wait_remove
209 write_data = wpas_get_config_token()
210 if write_data == None:
211 summary("Could not get WPS config token from hostapd")
214 print "Touch an NFC tag"
215 clf.connect(rdwr={'on-connect': rdwr_connected_write})
218 def wps_write_password_tag(clf, wait_remove=True):
219 summary("Write WPS password token")
220 global write_data, write_wait_remove
221 write_wait_remove = wait_remove
222 write_data = wpas_get_password_token()
223 if write_data == None:
224 summary("Could not get WPS password token from hostapd")
227 print "Touch an NFC tag"
228 clf.connect(rdwr={'on-connect': rdwr_connected_write})
231 def rdwr_connected(tag):
232 global only_one, no_wait
233 summary("Tag connected: " + str(tag))
236 print "NDEF tag: " + tag.type
238 print tag.ndef.message.pretty()
241 success = wps_tag_read(tag)
242 if only_one and success:
244 continue_loop = False
246 summary("Not an NDEF tag - remove tag")
252 def llcp_startup(clf, llc):
253 print "Start LLCP server"
255 srv = HandoverServer(llc)
258 def llcp_connected(llc):
259 print "P2P LLCP connected"
260 global wait_connection
261 wait_connection = False
268 clf = nfc.ContactlessFrontend()
270 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')
280 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')
284 parser.add_argument('command', choices=['write-config',
287 args = parser.parse_args()
290 only_one = args.only_one
293 no_wait = args.no_wait
297 summary_file = args.summary
301 success_file = args.success
303 logging.basicConfig(level=args.loglevel)
306 if not clf.open("usb"):
307 print "Could not open connection with an NFC device"
310 if args.command == "write-config":
311 wps_write_config_tag(clf, wait_remove=not args.no_wait)
314 if args.command == "write-password":
315 wps_write_password_tag(clf, wait_remove=not args.no_wait)
320 print "Waiting for a tag or peer to be touched"
321 wait_connection = True
323 if not clf.connect(rdwr={'on-connect': rdwr_connected},
324 llcp={'on-startup': llcp_startup,
325 'on-connect': llcp_connected}):
328 print "clf.connect failed"
331 if only_one and srv and srv.success:
334 except KeyboardInterrupt:
341 if __name__ == '__main__':