hardware.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. # Copyright 2016 Google Inc. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """This module implements the low level device API.
  15. This module exposes a low level SecurityKey class,
  16. representing the physical security key device.
  17. """
  18. import logging
  19. from pyu2f import apdu
  20. from pyu2f import errors
  21. class SecurityKey(object):
  22. """Low level api for talking to a security key.
  23. This class implements the low level api specified in FIDO
  24. U2F for talking to a security key.
  25. """
  26. def __init__(self, transport):
  27. self.transport = transport
  28. self.use_legacy_format = False
  29. self.logger = logging.getLogger('pyu2f.hardware')
  30. def CmdRegister(self, challenge_param, app_param):
  31. """Register security key.
  32. Ask the security key to register with a particular origin & client.
  33. Args:
  34. challenge_param: Arbitrary 32 byte challenge string.
  35. app_param: Arbitrary 32 byte applciation parameter.
  36. Returns:
  37. A binary structure containing the key handle, attestation, and a
  38. signature over that by the attestation key. The precise format
  39. is dictated by the FIDO U2F specs.
  40. Raises:
  41. TUPRequiredError: A Test of User Precense is required to proceed.
  42. ApduError: Something went wrong on the device.
  43. """
  44. self.logger.debug('CmdRegister')
  45. if len(challenge_param) != 32 or len(app_param) != 32:
  46. raise errors.InvalidRequestError()
  47. body = bytearray(challenge_param + app_param)
  48. response = self.InternalSendApdu(apdu.CommandApdu(
  49. 0,
  50. apdu.CMD_REGISTER,
  51. 0x03, # Per the U2F reference code tests
  52. 0x00,
  53. body))
  54. response.CheckSuccessOrRaise()
  55. return response.body
  56. def CmdAuthenticate(self,
  57. challenge_param,
  58. app_param,
  59. key_handle,
  60. check_only=False):
  61. """Attempt to obtain an authentication signature.
  62. Ask the security key to sign a challenge for a particular key handle
  63. in order to authenticate the user.
  64. Args:
  65. challenge_param: SHA-256 hash of client_data object as a bytes
  66. object.
  67. app_param: SHA-256 hash of the app id as a bytes object.
  68. key_handle: The key handle to use to issue the signature as a bytes
  69. object.
  70. check_only: If true, only check if key_handle is valid.
  71. Returns:
  72. A binary structure containing the key handle, attestation, and a
  73. signature over that by the attestation key. The precise format
  74. is dictated by the FIDO U2F specs.
  75. Raises:
  76. TUPRequiredError: If check_only is False, a Test of User Precense
  77. is required to proceed. If check_only is True, this means
  78. the key_handle is valid.
  79. InvalidKeyHandleError: The key_handle is not valid for this device.
  80. ApduError: Something else went wrong on the device.
  81. """
  82. self.logger.debug('CmdAuthenticate')
  83. if len(challenge_param) != 32 or len(app_param) != 32:
  84. raise errors.InvalidRequestError()
  85. control = 0x07 if check_only else 0x03
  86. body = bytearray(challenge_param + app_param +
  87. bytearray([len(key_handle)]) + key_handle)
  88. response = self.InternalSendApdu(apdu.CommandApdu(
  89. 0, apdu.CMD_AUTH, control, 0x00, body))
  90. response.CheckSuccessOrRaise()
  91. return response.body
  92. def CmdVersion(self):
  93. """Obtain the version of the device and test transport format.
  94. Obtains the version of the device and determines whether to use ISO
  95. 7816-4 or the U2f variant. This function should be called at least once
  96. before CmdAuthenticate or CmdRegister to make sure the object is using the
  97. proper transport for the device.
  98. Returns:
  99. The version of the U2F protocol in use.
  100. """
  101. self.logger.debug('CmdVersion')
  102. response = self.InternalSendApdu(apdu.CommandApdu(
  103. 0, apdu.CMD_VERSION, 0x00, 0x00))
  104. if not response.IsSuccess():
  105. raise errors.ApduError(response.sw1, response.sw2)
  106. return response.body
  107. def CmdBlink(self, time):
  108. self.logger.debug('CmdBlink')
  109. self.transport.SendBlink(time)
  110. def CmdWink(self):
  111. self.logger.debug('CmdWink')
  112. self.transport.SendWink()
  113. def CmdPing(self, data):
  114. self.logger.debug('CmdPing')
  115. return self.transport.SendPing(data)
  116. def InternalSendApdu(self, apdu_to_send):
  117. """Send an APDU to the device.
  118. Sends an APDU to the device, possibly falling back to the legacy
  119. encoding format that is not ISO7816-4 compatible.
  120. Args:
  121. apdu_to_send: The CommandApdu object to send
  122. Returns:
  123. The ResponseApdu object constructed out of the devices reply.
  124. """
  125. response = None
  126. if not self.use_legacy_format:
  127. response = apdu.ResponseApdu(self.transport.SendMsgBytes(
  128. apdu_to_send.ToByteArray()))
  129. if response.sw1 == 0x67 and response.sw2 == 0x00:
  130. # If we failed using the standard format, retry with the
  131. # legacy format.
  132. self.use_legacy_format = True
  133. return self.InternalSendApdu(apdu_to_send)
  134. else:
  135. response = apdu.ResponseApdu(self.transport.SendMsgBytes(
  136. apdu_to_send.ToLegacyU2FByteArray()))
  137. return response