wps-nfc.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #!/usr/bin/python
  2. #
  3. # Example nfcpy to wpa_supplicant wrapper for WPS NFC operations
  4. # Copyright (c) 2012, 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 nfc
  12. import nfc.ndef
  13. import wpactrl
  14. wpas_ctrl = '/var/run/wpa_supplicant'
  15. def wpas_connect():
  16. ifaces = []
  17. if os.path.isdir(wpas_ctrl):
  18. try:
  19. ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
  20. except OSError, error:
  21. print "Could not find wpa_supplicant: ", error
  22. return None
  23. if len(ifaces) < 1:
  24. print "No wpa_supplicant control interface found"
  25. return None
  26. for ctrl in ifaces:
  27. try:
  28. wpas = wpactrl.WPACtrl(ctrl)
  29. return wpas
  30. except wpactrl.error, error:
  31. print "Error: ", error
  32. pass
  33. return None
  34. def wpas_tag_read(message):
  35. wpas = wpas_connect()
  36. if (wpas == None):
  37. return
  38. print wpas.request("WPS_NFC_TAG_READ " + message.encode("hex"))
  39. def wps_tag_read(tag):
  40. if len(tag.ndef.message):
  41. message = nfc.ndef.Message(tag.ndef.message)
  42. print "message type " + message.type
  43. for record in message:
  44. print "record type " + record.type
  45. if record.type == "application/vnd.wfa.wsc":
  46. print "WPS tag - send to wpa_supplicant"
  47. wpas_tag_read(tag.ndef.message)
  48. break
  49. else:
  50. print "Empty tag"
  51. print "Remove tag"
  52. while tag.is_present:
  53. time.sleep(0.1)
  54. def main():
  55. clf = nfc.ContactlessFrontend()
  56. try:
  57. while True:
  58. print "Waiting for a tag to be touched"
  59. while True:
  60. tag = clf.poll()
  61. if tag == None:
  62. continue
  63. if tag.ndef:
  64. wps_tag_read(tag)
  65. break
  66. if tag:
  67. print "Not an NDEF tag - remove tag"
  68. while tag.is_present:
  69. time.sleep(0.1)
  70. break
  71. except KeyboardInterrupt:
  72. raise SystemExit
  73. finally:
  74. clf.close()
  75. raise SystemExit
  76. if __name__ == '__main__':
  77. main()