Debian Codegraph @

yubiotp/otp.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """
2 Implementation of the Yubico OTP algorithm. This can generate and parse OTP
3 structures.
4
5 >>> from binascii import unhexlify
6 >>> key = b'0123456789abcdef'
7 >>> otp = OTP(unhexlify(b'0123456789ab'), 5, 0x0153f8, 0, 0x1234)
8 >>> _ = repr(otp) # coverage
9 >>> _ = str(otp) # coverage
10 >>> token = encode_otp(otp, key, b'cclngiuv')
11 >>> token == b'cclngiuvttkhthcilurtkerbjnnkljfkjccklkhl'
12 True
13 >>> public_id, otp2 = decode_otp(token, key)
14 >>> public_id == b'cclngiuv'
15 True
16 >>> otp2 == otp
17 True
18 """
19 from binascii import hexlify
20 from datetime import datetime
21 from random import randrange
22 from struct import pack, unpack
23
24 from Crypto.Cipher import AES
25
26 from .crc import crc16, verify_crc16
27 from .modhex import is_modhex, modhex, unmodhex
28
29
30 __all__ = ['decode_otp', 'encode_otp', 'OTP', 'YubiKey', 'CRCError']
31
32
33 class CRCError(ValueError):
34 """
35 Raised when a decrypted token has an invalid checksum.
36 """
37 pass
38
39
40 def decode_otp(token, key):
41 """
42 Decodes a modhex-encoded Yubico OTP token and returns the public ID and the
43 unpacked :class:`OTP` object.
44
45 :param bytes token: A modhex-encoded buffer, as generated by a YubiKey
46 device. Decoded, this should consist of 0-16 bytes of public ID
47 followed by 16 bytes of encrypted OTP data.
48 :param bytes key: A 16-byte AES key as a binary string.
49
50 :returns: The public ID in its modhex-encoded form and the OTP structure.
51 :rtype: (bytes, :class:`OTP`)
52
53 :raises: ``ValueError`` if the string can not be decoded.
54 :raises: :exc:`CRCError` if the checksum on the decrypted data is
55 incorrect.
56 """
57 if len(key) != 16:
58 raise ValueError('Key must be exactly 16 bytes')
59
60 public_id, token = token[:-32], token[-32:]
61
62 buf = unmodhex(token)
63 buf = AES.new(key, AES.MODE_ECB).decrypt(buf)
64 otp = OTP.unpack(buf)
65
66 return (public_id, otp)
67
68
69 def encode_otp(otp, key, public_id=b''):
70 """
71 Encodes an :class:`OTP` structure, encrypts it with the given key and
72 returns the modhex-encoded token.
73
74 :param otp: The OTP structure.
75 :type otp: :class:`OTP`
76
77 :param bytes key: A 16-byte AES key as a binary string.
78 :param bytes public_id: An optional public id, modhex-encoded. This can be
79 at most 32 bytes.
80
81 :raises: ValueError if any parameters are out of range.
82 """
83 if len(key) != 16:
84 raise ValueError('Key must be exactly 16 bytes')
85
86 if not is_modhex(public_id):
87 raise ValueError('public_id must be a valid modhex string')
88
89 if len(public_id) > 32:
90 raise ValueError('public_id may be no longer than 32 modhex characters')
91
92 buf = otp.pack()
93 buf = AES.new(key, AES.MODE_ECB).encrypt(buf)
94 token = modhex(buf)
95
96 return public_id + token
97
98
99 class OTP(object):
100 """
101 A single YubiKey OTP. This is typically instantiated by parsing an encoded
102 OTP.
103
104 :param bytes uid: The private ID as a 6-byte binary string.
105 :param int session: The non-volatile usage counter.
106 :param int timestamp: An integer in [0..2^24].
107 :param int counter: The volatile usage counter.
108 :param int rand: An arbitrary number in [0..2^16].
109 """
110 def __init__(self, uid, session, timestamp, counter, rand):
111 self.uid = uid
112 self.session = session
113 self.timestamp = timestamp
114 self.counter = counter
115 self.rand = rand
116
117 def __repr__(self):
118 return 'OTP({self.uid!r}, {self.session!r}, {self.timestamp!r}, {self.counter!r}, {self.rand!r})'.format(self=self)
119
120 def __str__(self):
121 return 'OTP: {0} {1}/{2} (0x{3:x}/0x{4:x})'.format(hexlify(self.uid), self.session, self.counter, self.timestamp, self.rand)
122
123 def __eq__(self, other):
124 if self.__class__ is not other.__class__:
125 return False
126
127 self_props = (self.uid, self.session, self.timestamp, self.counter, self.rand)
128 other_props = (other.uid, other.session, other.timestamp, other.counter, other.rand)
129
130 return (self_props == other_props)
131
132 def pack(self):
133 """
134 Returns the OTP packed into a binary string, ready to be encrypted and
135 encoded.
136 """
137 fields = (
138 self.uid,
139 self.session,
140 self.timestamp & 0xff, (self.timestamp >> 8) & 0xffff,
141 self.counter,
142 self.rand,
143 )
144
145 buf = pack('<6s H BH B H', *fields)
146
147 crc = ~crc16(buf) & 0xffff
148 buf += pack('<H', crc)
149
150 return buf
151
152 @classmethod
153 def unpack(cls, buf):
154 """
155 Parse a packed OTP. This is the complement to :meth:`pack` so the
156 buffer should be a decoded, decrypted OTP buffer.
157
158 :param bytes buf: A packed OTP structure.
159 :raises: :exc:`CRCError` if the buffer does not pass crc validation.
160 """
161 if not verify_crc16(buf):
162 raise CRCError('OTP checksum is invalid')
163
164 uid, session, t1, t2, counter, rand, crc = unpack('<6s H BH B H H', buf)
165
166 timestamp = (t2 << 8) | t1
167
168 return cls(uid, session, timestamp, counter, rand)
169
170
171 class YubiKey(object):
172 """
173 A simulated YubiKey device. This can be used to generate a sequence of
174 Yubico OTP tokens.
175
176 :param bytes uid: The private ID as a 6-byte binary string.
177 :param int session: The non-volatile usage counter. It is the caller's
178 responsibility to persist this. Note that this may increment if the
179 volatile counter wraps, so you should only increment and persist this
180 after you have finished generating tokens.
181 :param int counter: The volatile session counter. This defaults to 0 at
182 init time, but the caller can override this.
183 """
184 def __init__(self, uid, session, counter=0):
185 self.uid = uid
186 self.session = min(session, 0x7fff)
187 self.counter = min(counter, 0xff)
188
189 self._init_timestamp()
190
191 def generate(self):
192 """
193 Return a new OTP object, as if the user had pressed the YubiKey button.
194
195 :rtype: :class:`OTP`
196 """
197 otp = OTP(self.uid, self.session, self._timestamp(), self.counter, randrange(0xffff))
198 self._increment_counter()
199
200 return otp
201
202 def _init_timestamp(self):
203 self._timestamp_base = randrange(0x00ffff)
204 self._timestamp_start = datetime.now()
205
206 def _timestamp(self):
207 """
208 Returns the current timestamp value, based on the number of seconds
209 since the object was created.
210 """
211 delta = datetime.now() - self._timestamp_start
212 delta = delta.days * 86400 + delta.seconds
213
214 return (self._timestamp_base + (delta * 8)) % 0xffffff
215
216 def _increment_counter(self):
217 if self.counter >= 0xff:
218 self._increment_session()
219 self.counter = 0
220 else:
221 self.counter += 1
222
223 def _increment_session(self):
224 self.session = min(self.session + 1, 0x7fff)