| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
This is a command-line interface to the yubiotp package. Its primary function |
| 5 |
is to simulate a YubiKey device for testing purposes. It also includes some |
| 6 |
utilities for things like converting to and from modhex. |
| 7 |
""" |
| 8 |
from __future__ import print_function |
| 9 |
|
| 10 |
import sys |
| 11 |
from os.path import expanduser |
| 12 |
from optparse import OptionParser, OptionGroup, Option, OptionValueError |
| 13 |
from random import choice |
| 14 |
from binascii import hexlify, unhexlify |
| 15 |
|
| 16 |
from six.moves import configparser |
| 17 |
|
| 18 |
from yubiotp.modhex import modhex, unmodhex, modhex_to_hex, hex_to_modhex |
| 19 |
from yubiotp.otp import YubiKey, decode_otp, encode_otp |
| 20 |
|
| 21 |
|
| 22 |
def main(): |
| 23 |
parser = Handler.global_option_parser() |
| 24 |
parser.disable_interspersed_args() |
| 25 |
|
| 26 |
opts, args = parser.parse_args() |
| 27 |
|
| 28 |
if len(args) == 0: |
| 29 |
usage('You must choose an action', parser) |
| 30 |
|
| 31 |
handlers = { |
| 32 |
'list': ListHandler(), |
| 33 |
'init': InitHandler(), |
| 34 |
'delete': DeleteHandler(), |
| 35 |
'gen': GenHandler(), |
| 36 |
'parse': ParseHandler(), |
| 37 |
|
| 38 |
'modhex': ModhexHandler(), |
| 39 |
} |
| 40 |
|
| 41 |
handler = handlers.get(args[0]) |
| 42 |
|
| 43 |
if handler is None: |
| 44 |
usage('Unknown action: {0}'.format(args[0]), parser) |
| 45 |
else: |
| 46 |
handler.run() |
| 47 |
|
| 48 |
|
| 49 |
def check_hex_value(option, opt, value): |
| 50 |
try: |
| 51 |
unhexlify(value.encode()) |
| 52 |
except TypeError as e: |
| 53 |
raise OptionValueError(str(e)) |
| 54 |
|
| 55 |
return value |
| 56 |
|
| 57 |
|
| 58 |
def check_modhex_value(option, opt, value): |
| 59 |
try: |
| 60 |
unmodhex(value.encode()) |
| 61 |
except ValueError as e: |
| 62 |
raise OptionValueError(str(e)) |
| 63 |
|
| 64 |
return value |
| 65 |
|
| 66 |
|
| 67 |
class YubiKeyOption(Option): |
| 68 |
""" |
| 69 |
Custom optparse Option class that adds the 'hex' value type. Values of this |
| 70 |
type are expected to be strings of hex digits, which will be decoded into |
| 71 |
binary strings before being stored. |
| 72 |
""" |
| 73 |
TYPES = Option.TYPES + ('hex', 'modhex') |
| 74 |
TYPE_CHECKER = dict(Option.TYPE_CHECKER, |
| 75 |
hex=check_hex_value, |
| 76 |
modhex=check_modhex_value) |
| 77 |
|
| 78 |
|
| 79 |
make_option = YubiKeyOption |
| 80 |
|
| 81 |
|
| 82 |
class Handler(object): |
| 83 |
name = '' |
| 84 |
options = [ |
| 85 |
make_option('-f', '--config', dest='config', default='~/.yubikey', metavar='PATH', help='A config file to store device state. [%default]'), |
| 86 |
make_option('-n', '--name', dest='device_name', default='0', metavar='NAME', help='The device number or name to operate on. [%default]'), |
| 87 |
] |
| 88 |
args = '' |
| 89 |
description = 'Simulates one or more YubiKey devices from which you can generate tokens. Also parses tokens for verification. Choose an action for more information.' |
| 90 |
|
| 91 |
def run(self): |
| 92 |
parser = self.make_option_parser() |
| 93 |
|
| 94 |
opts, args = parser.parse_args() |
| 95 |
|
| 96 |
self.handle(opts, args) |
| 97 |
|
| 98 |
def make_option_parser(self): |
| 99 |
usage = '%prog [global opts] {0} [any opts]'.format(self.name) |
| 100 |
if self.args: |
| 101 |
usage = usage + ' ' + self.args |
| 102 |
|
| 103 |
parser = OptionParser(usage=usage, description=self.description) |
| 104 |
|
| 105 |
for option in Handler.options: |
| 106 |
parser.add_option(option) |
| 107 |
|
| 108 |
if len(self.options) > 0: |
| 109 |
group = OptionGroup(parser, self.name) |
| 110 |
for option in self.options: |
| 111 |
group.add_option(option) |
| 112 |
|
| 113 |
parser.add_option_group(group) |
| 114 |
|
| 115 |
return parser |
| 116 |
|
| 117 |
def handle(self, opts, args): |
| 118 |
raise NotImplementedError() |
| 119 |
|
| 120 |
@classmethod |
| 121 |
def global_option_parser(cls): |
| 122 |
parser = OptionParser( |
| 123 |
usage='%prog [global opts] <list|init|delete|gen|parse|modhex> [any opts] [args]', |
| 124 |
description=cls.description, |
| 125 |
) |
| 126 |
|
| 127 |
for option in cls.options: |
| 128 |
parser.add_option(option) |
| 129 |
|
| 130 |
return parser |
| 131 |
|
| 132 |
@staticmethod |
| 133 |
def random_hex(count): |
| 134 |
return ''.join(choice('0123456789abcdef') for i in range(count * 2)) |
| 135 |
|
| 136 |
|
| 137 |
class ListHandler(Handler): |
| 138 |
name = 'list' |
| 139 |
options = [] |
| 140 |
args = '' |
| 141 |
description = 'List all virtual YubiKey devices.' |
| 142 |
|
| 143 |
def handle(self, opts, args): |
| 144 |
config = configparser.SafeConfigParser() |
| 145 |
config.read([expanduser(opts.config)]) |
| 146 |
config.write(sys.stdout) |
| 147 |
|
| 148 |
|
| 149 |
class InitHandler(Handler): |
| 150 |
name = 'init' |
| 151 |
options = [ |
| 152 |
make_option('-p', '--public', dest='public_id', type='modhex', default='', help='A modhex-encoded public ID (up to 16 bytes)'), |
| 153 |
make_option('-k', '--key', dest='key', type='hex', help='A hex-encoded 16-byte AES key. If omitted, one will be generated.'), |
| 154 |
make_option('-u', '--uid', dest='uid', type='hex', help='A hex-encoded 6-byte private ID. If omitted, one will be generated.'), |
| 155 |
make_option('-s', '--session', dest='session', type='int', default=0, help='The initial session counter. [%default]'), |
| 156 |
] |
| 157 |
description = 'Initialize a new virtual YubiKey.' |
| 158 |
|
| 159 |
def handle(self, opts, args): |
| 160 |
if opts.key is None: |
| 161 |
opts.key = self.random_hex(16) |
| 162 |
|
| 163 |
if opts.uid is None: |
| 164 |
opts.uid = self.random_hex(6) |
| 165 |
|
| 166 |
device = Device(opts.config, opts.device_name) |
| 167 |
device.create(opts.public_id, opts.key, opts.uid, opts.session) |
| 168 |
device.save() |
| 169 |
|
| 170 |
|
| 171 |
class DeleteHandler(Handler): |
| 172 |
name = 'delete' |
| 173 |
options = [] |
| 174 |
args = '' |
| 175 |
description = 'Remove a virtual YubiKey device.' |
| 176 |
|
| 177 |
def handle(self, opts, args): |
| 178 |
device = Device(opts.config, opts.device_name) |
| 179 |
device.delete() |
| 180 |
device.save() |
| 181 |
|
| 182 |
|
| 183 |
class GenHandler(Handler): |
| 184 |
name = 'gen' |
| 185 |
options = [ |
| 186 |
make_option('-c', '--count', dest='count', type='int', default=1, help='Generate multiple tokens. [%default]'), |
| 187 |
make_option('-i', '--interactive', action='store_true', dest='interactive', help='Generate a token for every line read from stdin until interrupted.'), |
| 188 |
] |
| 189 |
args = '' |
| 190 |
description = 'Generate one or more tokens from the virtual device. This simulates pressing the YubiKey\'s button.' |
| 191 |
|
| 192 |
def handle(self, opts, args): |
| 193 |
device = Device(opts.config, opts.device_name) |
| 194 |
|
| 195 |
for i in range(opts.count): |
| 196 |
print(device.gen_token().decode()) |
| 197 |
|
| 198 |
if opts.interactive: |
| 199 |
try: |
| 200 |
while True: |
| 201 |
sys.stdin.readline() |
| 202 |
print(device.gen_token().decode()) |
| 203 |
except KeyboardInterrupt: |
| 204 |
pass |
| 205 |
|
| 206 |
device.save() |
| 207 |
|
| 208 |
|
| 209 |
class ParseHandler(Handler): |
| 210 |
name = 'parse' |
| 211 |
options = [] |
| 212 |
args = 'token ...' |
| 213 |
description = 'Parse tokens generated by the selected virtual device and display its fields.' |
| 214 |
|
| 215 |
def handle(self, opts, args): |
| 216 |
device = Device(opts.config, opts.device_name) |
| 217 |
key = device.get_config('key', unhex=True) |
| 218 |
|
| 219 |
for token in args[1:]: |
| 220 |
try: |
| 221 |
public_id, otp = decode_otp(token.encode(), key) |
| 222 |
except ValueError as e: |
| 223 |
print(e) |
| 224 |
else: |
| 225 |
print('public_id: {0}'.format(public_id.decode())) |
| 226 |
print('uid: {0}'.format(hexlify(otp.uid).decode())) |
| 227 |
print('session: {0}'.format(otp.session)) |
| 228 |
print('timestamp: 0x{0:x}'.format(otp.timestamp)) |
| 229 |
print('counter: {0}'.format(otp.counter)) |
| 230 |
print('random: 0x{0:x}'.format(otp.rand)) |
| 231 |
print() |
| 232 |
|
| 233 |
|
| 234 |
class ModhexHandler(Handler): |
| 235 |
name = 'modhex' |
| 236 |
options = [ |
| 237 |
make_option('-d', '--decode', action='store_true', dest='decode', help='Decode from modhex. Default is to encode to modhex.'), |
| 238 |
make_option('-H', '--hex', action='store_true', dest='hex', help='Encode to or decode from a string of hex digits. Default is a raw string.'), |
| 239 |
] |
| 240 |
args = 'input ...' |
| 241 |
description = 'Encode (default) or decode a modhex string.' |
| 242 |
|
| 243 |
def handle(self, opts, args): |
| 244 |
for arg in args[1:]: |
| 245 |
try: |
| 246 |
if opts.decode: |
| 247 |
if opts.hex: |
| 248 |
print(modhex_to_hex(arg.encode()).decode()) |
| 249 |
else: |
| 250 |
print(unmodhex(arg.encode()).decode()) |
| 251 |
else: |
| 252 |
if opts.hex: |
| 253 |
print(hex_to_modhex(arg.encode()).decode()) |
| 254 |
else: |
| 255 |
print(modhex(arg.encode()).decode()) |
| 256 |
except ValueError as e: |
| 257 |
print(e, file=sys.stderr) |
| 258 |
|
| 259 |
|
| 260 |
def usage(message, parser=None): |
| 261 |
print(message) |
| 262 |
print() |
| 263 |
|
| 264 |
if parser is not None: |
| 265 |
parser.print_help() |
| 266 |
|
| 267 |
sys.exit(1) |
| 268 |
|
| 269 |
|
| 270 |
class Device(object): |
| 271 |
def __init__(self, config_path, name): |
| 272 |
self.config_path = expanduser(config_path) |
| 273 |
self.name = name |
| 274 |
self.section_name = 'device_{0}'.format(name) |
| 275 |
|
| 276 |
self.config = self._load_config() |
| 277 |
self.yubikey = None |
| 278 |
|
| 279 |
def _load_config(self): |
| 280 |
config = configparser.SafeConfigParser() |
| 281 |
config.read([self.config_path]) |
| 282 |
|
| 283 |
return config |
| 284 |
|
| 285 |
def create(self, public_id, key, uid, session): |
| 286 |
if len(key) != 32: |
| 287 |
raise ValueError('AES keys must be exactly 16 bytes') |
| 288 |
|
| 289 |
try: |
| 290 |
self.config.add_section(self.section_name) |
| 291 |
except configparser.DuplicateSectionError: |
| 292 |
usage('A device named "{0}" already exists.'.format(self.name)) |
| 293 |
else: |
| 294 |
self.set_config('public_id', public_id) |
| 295 |
self.set_config('key', key) |
| 296 |
self.set_config('uid', uid) |
| 297 |
self.set_config('session', session) |
| 298 |
|
| 299 |
def delete(self): |
| 300 |
try: |
| 301 |
self.config.remove_section(self.section_name) |
| 302 |
except configparser.NoSectionError: |
| 303 |
usage('The device named "{0}" does not exist.'.format(self.name)) |
| 304 |
|
| 305 |
def gen_token(self): |
| 306 |
self.ensure_yubikey() |
| 307 |
|
| 308 |
otp = self.yubikey.generate() |
| 309 |
key = self.get_config('key', unhex=True) |
| 310 |
public_id = self.get_config('public_id').encode() |
| 311 |
|
| 312 |
token = encode_otp(otp, key, public_id=public_id) |
| 313 |
|
| 314 |
return token |
| 315 |
|
| 316 |
def ensure_yubikey(self): |
| 317 |
if self.yubikey is None: |
| 318 |
try: |
| 319 |
uid = self.get_config('uid', unhex=True) |
| 320 |
session = int(self.get_config('session')) |
| 321 |
|
| 322 |
self.get_config('key') |
| 323 |
except Exception as e: |
| 324 |
usage('The device named "{0}" does not exist or is corrupt. ({1})'.format(self.name, e)) |
| 325 |
else: |
| 326 |
self.yubikey = YubiKey(uid=uid, session=session) |
| 327 |
|
| 328 |
return self.yubikey |
| 329 |
|
| 330 |
def save(self): |
| 331 |
if self.yubikey is not None: |
| 332 |
self.set_config('session', self.yubikey.session + 1) |
| 333 |
|
| 334 |
with open(self.config_path, 'w') as f: |
| 335 |
self.config.write(f) |
| 336 |
|
| 337 |
def get_config(self, key, unhex=False): |
| 338 |
value = self.config.get(self.section_name, key) |
| 339 |
if unhex: |
| 340 |
value = unhexlify(value.encode()) |
| 341 |
|
| 342 |
return value |
| 343 |
|
| 344 |
def set_config(self, key, value): |
| 345 |
self.config.set(self.section_name, key, str(value)) |
| 346 |
|
| 347 |
|
| 348 |
if __name__ == '__main__': |
| 349 |
main() |