-
Notifications
You must be signed in to change notification settings - Fork 0
/
vouch
executable file
·1247 lines (1027 loc) · 45.9 KB
/
vouch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import argparse
import base64
import json
import math
import os
import re
import socket
import ssl
import struct
import sys
import time
from enum import Enum, auto
from subprocess import check_output, run
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from uuid import uuid4
__version__='UNRELEASED'
__signer__=''
_verbose=False
def eprint(*args, **kwargs):
return print(*args, file=sys.stderr, **kwargs)
stderr_isatty = os.isatty(sys.stderr.fileno())
no_color = True if os.getenv('NO_COLOR', '') else False
_KILL_LINE = '\r\033[K'
_BRIGHT = '' if no_color else '\033[1m'
_RED = '' if no_color else '\033[31m'
_GREEN = '' if no_color else '\033[32m'
_YELLOW = '' if no_color else '\033[33m'
_BLUE = '' if no_color else '\033[34m'
_NORMAL = '' if no_color else '\033[39m' # normal colour, unchanged brightness
_RESET = '' if no_color else '\033[0m'
class APIError(Exception):
def __init__(self, response):
self.error = response.get('error')
if self.error and 'message' in self.error:
super().__init__(f'API error: {self.error["message"]}')
else:
super().__init__(f'API error: {json.dumps(response)}')
self.response = response
class Client:
def __init__(self, keyFile, serviceUrl, insecure=False):
self.keyFile = keyFile
self.serviceUrl = serviceUrl
self.insecure = insecure
def call(self, method, params=None):
requestId = str(uuid4())
req = {
'jsonrpc': '2.0',
'id': requestId,
'method': method,
}
if params is not None:
req['params'] = params
req = json.dumps(req).encode('utf-8')
headers = {
'Content-Type': 'application/json',
}
if self.keyFile:
prefix = f'SSH {requestId} {math.floor(time.time())} '.encode('utf-8')
signedMessage = prefix + req
check_output(['ssh-add', '-q', os.path.expanduser(self.keyFile)])
signature = check_output(['ssh-keygen',
'-q',
'-Y', 'sign',
'-f', os.path.expanduser(self.keyFile),
'-n', '[email protected]',
'-'],
input=signedMessage).replace(b'\n', b'')
auth_header = prefix + signature
headers['Authorization'] = auth_header
context = ssl.create_default_context()
if self.insecure:
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
res = urlopen(Request(self.serviceUrl, data=req, headers=headers, method='POST'),
context=context)
if res.status == 200:
res = json.loads(res.read().decode('utf-8'))
if 'result' in res:
return res['result']
else:
raise APIError(res)
elif res.status >= 200 and res.status <= 299:
return None
else:
eprint(json.dumps({
'http': res.status,
'reason': res.reason,
}))
sys.exit(1)
def script(args, method, keyFile, params):
return Client(keyFile, args.serviceUrl, insecure=args.insecure).call(method, params)
def _add_help_to(p, sp):
h = sp.add_parser('help', help='Print help')
h.set_defaults(handler=lambda args: p.print_help())
VOUCH_ID_PRINCIPAL = os.getenv('VOUCH_ID_PRINCIPAL', None)
def _ensure_principal(namespace, dest):
existing = getattr(namespace, dest, None)
if existing is None:
setattr(namespace, dest, { 'id': VOUCH_ID_PRINCIPAL, 'epoch': False })
elif isinstance(existing, str):
setattr(namespace, dest, { 'id': existing, 'epoch': False })
return getattr(namespace, dest)
class SetPrincipalIdAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
p = _ensure_principal(namespace, self.dest)
if isinstance(values, str):
p['id'] = values
if isinstance(values, list):
p['id'] = ''.join(values)
class SetEpochAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if option_string in self.option_strings:
_ensure_principal(namespace, self.dest)['epoch'] = values
class SetAnyEpochAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if option_string in self.option_strings:
_ensure_principal(namespace, self.dest)['epoch'] = False
def _add_principal_argument(p):
p.add_argument('principal', action=SetPrincipalIdAction,
nargs=(1 if VOUCH_ID_PRINCIPAL is None else '?'),
default=VOUCH_ID_PRINCIPAL,
help='Set the principal name to use (often an email address)')
p.add_argument('--any-epoch', dest='principal', nargs=0, action=SetAnyEpochAction,
default='any epoch',
help='Apply the operation to any epoch of the named principal')
p.add_argument('--epoch', dest='principal', metavar='EPOCH', action=SetEpochAction,
default='any epoch',
help='Apply the operation only to a specific epoch of the named principal')
def defaultComment():
import socket
return socket.gethostname()
def progress_message(s):
if stderr_isatty:
eprint(f'{_KILL_LINE+_BRIGHT+_YELLOW}⋯{_NORMAL} {s}{_RESET}', end='')
def progress_detail(s):
if stderr_isatty:
eprint(s, end='')
def progress_ok():
if stderr_isatty:
if _verbose:
eprint(f'\r{_BRIGHT+_GREEN}✔{_RESET}')
else:
eprint(f'{_KILL_LINE+_RESET}', end='')
def progress_fail(and_exit=True, exit_status=1):
if and_exit:
if stderr_isatty:
eprint(f'\r{_BRIGHT+_RED}❌{_RESET}')
sys.exit(exit_status)
else:
if stderr_isatty:
if _verbose:
eprint(f'\r{_BRIGHT+_RED}❌{_RESET}')
else:
eprint(f'{_KILL_LINE+_RESET}', end='')
def progress_warning(s):
if stderr_isatty:
eprint(f'{_KILL_LINE+_BRIGHT+_RED}⚠{_YELLOW} {s}{_RESET}')
def progress_info(s):
if stderr_isatty:
eprint(f'{_KILL_LINE+_BRIGHT+_BLUE}🛈{_NORMAL} {s}{_RESET}')
def progress_check(result, and_exit=True, exit_status=1):
if result:
progress_ok()
else:
progress_fail(and_exit, exit_status)
## SSH wire formatting
def parse_chunk(length, bs):
if len(bs) < length: raise ValueError('Packet too short')
return (bs[:length], bs[length:])
def parse_expected(expected, bs, msg=None):
if not bs.startswith(expected):
raise ValueError(msg or ('Missing expected text ' + repr(expected)))
return bs[len(expected):]
def parse_int(bs):
if len(bs) < 4: raise ValueError('Packet too short')
(val,) = struct.unpack('>I', bs[:4])
return (val, bs[4:])
def parse_long(bs):
if len(bs) < 8: raise ValueError('Packet too short')
(val,) = struct.unpack('>Q', bs[:8])
return (val, bs[8:])
def parse_byte(bs):
if len(bs) < 1: raise ValueError('Packet too short')
(val,) = struct.unpack('>B', bs[:1])
return (val, bs[1:])
def parse_str(bs):
(length, bs) = parse_int(bs)
if len(bs) < length: raise ValueError('Packet too short')
return (bs[:length], bs[length:])
def parse_expected_str(expected, bs, msg=None):
(actual, bs) = parse_str(bs)
if actual != expected: raise ValueError(msg or ('Missing expected text ' + repr(expected)))
return bs
def parse_end(bs):
if bs != b'': raise ValueError('Unexpected bytes at end of packet')
def format_int(i): return struct.pack('>I', i)
def format_byte(b): return struct.pack('>B', b)
def format_str(bs): return format_int(len(bs)) + bs
class SshAgent:
def __init__(self, socket_path=None):
if socket_path is None:
socket_path = os.environ.get('SSH_AUTH_SOCK', None)
self.socket_path = socket_path
if socket_path:
try:
self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self._socket.connect(socket_path)
except socket.error:
if self._socket:
self._socket.close()
self._socket = None
else:
self._socket = None
def __del__(self):
if self._socket:
self._socket.close()
self._socket = None
def _send(self, packet):
self._socket.sendall(format_str(packet))
def _readbytes(self, count):
bs = b''
while count > 0:
chunk = self._socket.recv(count)
count = count - len(chunk)
bs = bs + chunk
return memoryview(bs)
def _recv(self):
(length,) = struct.unpack('>I', self._readbytes(4))
bs = self._readbytes(length)
return bs
def _readreply(self):
return parse_byte(self._recv())
def list_identities(self):
if not self._socket:
return []
self._send(bytes([11])) # SSH_AGENTC_REQUEST_IDENTITIES
(packet_type, blob) = self._readreply()
assert packet_type == 12 # SSH_AGENT_IDENTITIES_ANSWER
(nkeys, blob) = parse_int(blob)
result = []
for i in range(nkeys):
(keyblob, blob) = parse_str(blob)
(comment, blob) = parse_str(blob)
keytype = bytes(parse_str(keyblob)[0])
result.append((keytype, bytes(keyblob), bytes(comment).decode('utf-8')))
parse_end(blob)
return result
def _readsuccess(self):
(packet_type, blob) = self._readreply()
assert packet_type == 6 # SSH_AGENT_SUCCESS
parse_end(blob)
def add_identity(self, key_type, contents, comment):
self._send(bytes([17]) + format_str(key_type) + contents + format_str(comment))
self._readsuccess()
def remove_identity(self, key_blob):
self._send(bytes([18]) + format_str(key_blob))
self._readsuccess()
class Ed25519PublicKey:
MAGIC = b'ssh-ed25519'
def __init__(self):
self.blob = None
self.public_key_bytes = None
def load(self, blob):
self.blob = blob
blob = parse_expected_str(Ed25519PublicKey.MAGIC, blob, 'Non-ED25519 keys not yet supported')
(self.public_key_bytes, blob) = parse_str(blob)
parse_end(blob)
return self
def load_from_bytes(self, bs):
self.blob = None
self.public_key_bytes = bs
return self
def __eq__(self, other):
return self.public_key_bytes == other.public_key_bytes
class Ed25519SecretKey:
MAGIC = b'ssh-ed25519'
def __init__(self):
self.blob = None
self.public_key = None
self.secret_key_seed = None
def load(self, blob):
orig_blob = blob
(check1, blob) = parse_int(blob)
(check2, blob) = parse_int(blob)
if check1 != check2:
raise ValueError('Private key decryption failed')
blob = parse_expected_str(Ed25519SecretKey.MAGIC, blob, 'Non-ED25519 keys not yet supported')
(public_key_bytes, blob) = parse_str(blob)
self.public_key = Ed25519PublicKey().load_from_bytes(public_key_bytes)
(sk, blob) = parse_str(blob)
self.secret_key_seed = sk[:32]
(_comment, blob) = parse_str(blob)
self.blob = orig_blob[:-len(blob)]
# Padding
if len(blob) >= 16:
raise ValueError('Invalid private key file')
for (idx, b) in enumerate(blob, 1):
if idx != b:
raise ValueError('Invalid private key file')
return self
def __eq__(self, other):
return self.secret_key_seed == other.secret_key_seed
class Ed25519Certificate:
MAGIC = b'[email protected]'
def __init__(self):
self.blob = None
self.nonce = None
def load(self, blob):
self.blob = blob
blob = parse_expected_str(Ed25519Certificate.MAGIC, blob)
(self.nonce, blob) = parse_str(blob)
(signed_public_key_bytes, blob) = parse_str(blob)
self.signed_public_key = Ed25519PublicKey().load_from_bytes(signed_public_key_bytes)
(self.serial, blob) = parse_long(blob)
(self.cert_type, blob) = parse_int(blob)
(self.key_id, blob) = parse_str(blob)
(principals, blob) = parse_str(blob)
self.valid_principals = []
while principals:
(p, principals) = parse_str(principals)
self.valid_principals.append(p)
(self.valid_after, blob) = parse_long(blob)
(self.valid_before, blob) = parse_long(blob)
(self.critical_options_blob, blob) = parse_str(blob)
(self.extensions_blob, blob) = parse_str(blob)
(self.reserved, blob) = parse_str(blob)
(issuer_public_key_bytes, blob) = parse_str(blob)
self.issuer_public_key = Ed25519PublicKey().load(issuer_public_key_bytes)
(self.signature_blob, blob) = parse_str(blob)
return self
def validity_errors(self, now=None):
if now is None:
now = time.time()
errors = []
if now < self.valid_after:
t = time.localtime(self.valid_after)
errors.append(f'it is not valid until {time.strftime("%Y-%m-%d %H:%M:%S", t)}')
if now >= self.valid_before:
t = time.localtime(self.valid_before)
errors.append(f'it expired at {time.strftime("%Y-%m-%d %H:%M:%S", t)}')
return errors
def decode_secret_key(text):
PREFIX = '-----BEGIN OPENSSH PRIVATE KEY-----'
SUFFIX = '-----END OPENSSH PRIVATE KEY-----'
text = text.replace('\n', '')
if not text.startswith(PREFIX) or not text.endswith(SUFFIX):
raise ValueError('Invalid private key file')
text = text[len(PREFIX):-len(SUFFIX)]
blob = base64.b64decode(text)
blob = parse_expected(b'openssh-key-v1\0', blob, 'Invalid private key file')
blob = parse_expected_str(b'none', blob, 'Passphrases not yet supported') # cipher
blob = parse_expected_str(b'none', blob, 'Passphrases not yet supported') # kd
blob = parse_expected_str(b'', blob, 'Invalid private key file') # salt
(nkeys, blob) = parse_int(blob)
if nkeys != 1:
raise ValueError('Private key file with more than one keypair not yet supported')
(pubkey_blob, blob) = parse_str(blob)
public_key = Ed25519PublicKey().load(pubkey_blob)
(seckey_blob, blob) = parse_str(blob)
secret_key = Ed25519SecretKey().load(seckey_blob)
if secret_key.public_key != public_key:
raise ValueError('Private key does not match public key')
return secret_key
def mksshdir():
sshdir = os.path.expanduser('~/.ssh')
if not os.path.exists(sshdir):
progress_info(f'Creating directory {sshdir}')
os.makedirs(sshdir, mode=0o700, exist_ok=True)
def _add_munge_arguments(p):
p.add_argument('--dry-run', '-n', action='store_true',
help='Dry run: modifies no files, shows what would happen')
p.add_argument('--show-details', action='store_true',
help='Print out details of the changes being made')
p.add_argument('--remove', action='store_true',
help='Remove configuration stanzas inserted by an earlier run')
def munge(filename, comment_leader, specifier, comment_trailer, replacement_lines,
dry_run=False,
show_details=False,
at_top_if_missing=True):
opener = f"{comment_leader}--- {specifier} BEGIN ---{comment_trailer}"
closer = f"{comment_leader}--- {specifier} END ---{comment_trailer}"
position = 'head'
head_lines = []
body_lines = []
body_found = False
tail_lines = []
if os.path.exists(filename):
with open(filename, 'rt') as f:
for l in f:
if position == 'head':
if l.strip() == opener:
position = 'body'
body_found = True
else:
head_lines.append(l)
elif position == 'body':
if l.strip() == closer:
position = 'tail'
else:
body_lines.append(l)
elif position == 'tail':
tail_lines.append(l)
else:
pass
if replacement_lines:
chunk = [opener + '\n'] + replacement_lines + [closer + '\n']
if body_found:
lines = head_lines + chunk + tail_lines
elif at_top_if_missing:
lines = chunk + head_lines + tail_lines
else:
lines = head_lines + tail_lines + chunk
else:
lines = head_lines + tail_lines
if dry_run:
print(filename + ':\n\t' + '\t'.join(lines), end='')
else:
progress_info(f'Updating {filename}')
if show_details:
eprint('\t' + '\t'.join(lines), end='')
with open(filename, 'wt') as f:
f.write(''.join(lines))
def main(argv=sys.argv):
app_name = os.path.basename(argv[0])
argv = argv[1:]
synopsis='''Interface to the vouch.id API.'''
VOUCH_ID_KEYFILE = os.getenv('VOUCH_ID_KEYFILE', '~/.ssh/id_ed25519')
VOUCH_ID_API = os.getenv('VOUCH_ID_API', 'https://vouch.id/')
SP_ARGS = { 'formatter_class': argparse.ArgumentDefaultsHelpFormatter }
parser = argparse.ArgumentParser(prog=app_name,
description=synopsis,
**SP_ARGS)
parser.add_argument('-v', '--version', action='version', version=__version__)
parser.add_argument('--verbose', action='store_true',
help='Enable verbose output')
parser.add_argument('--insecure', action='store_true',
help=argparse.SUPPRESS)
parser.add_argument('-s', '--service-url', dest='serviceUrl', default=VOUCH_ID_API,
help=argparse.SUPPRESS)
parser.set_defaults(handler=lambda args: parser.print_help())
sp = parser.add_subparsers()
_add_help_to(parser, sp)
def add_login_args(p, include_dry_run=True):
p.add_argument('-k', '--key', dest='keyFile', default=VOUCH_ID_KEYFILE)
p.add_argument('--comment', default=defaultComment(), help='Comment to identify this machine and its key')
p.add_argument('--no-check-issuer', dest='checkIssuer', action='store_false')
p.add_argument('--save-certificate', dest='saveCertificate', action='store_true')
if include_dry_run:
p.add_argument('-n', '--dry-run', dest='dryRun', action='store_true',
help='Report on certificate status without doing anything')
_add_principal_argument(p)
#---------------------------------------------------------------------------
p = sp.add_parser('admin', help='Service administration', **SP_ARGS)
admin_p = p
p.set_defaults(handler=lambda args: admin_p.print_help())
ssp = p.add_subparsers()
_add_help_to(p, ssp)
def deleteInvitation(args):
print(json.dumps(script(args, 'deleteInvitation', args.keyFile, {
'principal_id': args.principalId,
})['deleted']))
p = ssp.add_parser('uninvite', help='Delete invitation', **SP_ARGS)
p.add_argument('keyFile', metavar='adminKeyFile')
p.add_argument('principalId')
p.set_defaults(handler=deleteInvitation)
def invitePrincipal(args):
res = script(args, 'invitePrincipal', args.keyFile, {
'principal_id': args.principalId,
'expiry_seconds': args.expiry,
'replace_existing_ok': args.allow_replacement,
})
if args.invitation_code_only:
print(res['invite_secret'])
else:
print(res['web_url'])
print(res['app_url'])
print(f"Invitation will expire in {res['remaining_lifetime']} seconds.")
p = ssp.add_parser('invite', help='Invite principal', **SP_ARGS)
p.add_argument('keyFile', metavar='adminKeyFile')
p.add_argument('principalId')
p.add_argument('--expiry', metavar='SECONDS', type=int, default=86400,
help='Number of seconds the invitation should remain valid for')
p.add_argument('--allow-replacement', action='store_true',
help='Whether to allow the invitation to replace an existing registration')
p.add_argument('--invitation-code-only', action='store_true',
help='Whether to print out only the invitation code or full URL details')
p.set_defaults(handler=invitePrincipal)
def deletePrincipal(args):
print(json.dumps(script(args, 'deletePrincipal', args.keyFile, {
'principal': args.principal,
})['deleted']))
p = ssp.add_parser('delete', help='Delete principal', **SP_ARGS)
p.add_argument('keyFile', metavar='adminKeyFile')
_add_principal_argument(p)
p.set_defaults(handler=deletePrincipal)
def listPrincipals(args):
for p in script(args, 'listPrincipals', args.keyFile, {})['principals']:
print(f"{p['epoch']}\t{p['id']}")
p = ssp.add_parser('list', help='List principals', **SP_ARGS)
p.add_argument('keyFile', metavar='adminKeyFile')
p.set_defaults(handler=listPrincipals)
#---------------------------------------------------------------------------
p = sp.add_parser('machine', help='Tools for managing an SSH client machine', **SP_ARGS)
machine_p = p
p.set_defaults(handler=lambda args: machine_p.print_help())
ssp = p.add_subparsers()
_add_help_to(p, ssp)
def registerMachine(args):
req = {
'principal': args.principal,
'comment': args.comment,
}
if args.timeout is not None:
req['timeout'] = args.timeout
res = script(args, 'registerMachine', args.keyFile, req)
if res['state'] == 'registration-pending':
print(f"pending\t{res['rendezvous_code']}")
elif res['state'] == 'registered':
print(f"registered")
p = ssp.add_parser('register', help='Register client machine', **SP_ARGS)
p.add_argument('-k', '--key', dest='keyFile', default=VOUCH_ID_KEYFILE)
p.add_argument('--comment', default=defaultComment(), help='Comment to identify this machine and its key')
p.add_argument('--timeout', metavar='SECONDS', type=int, default=None,
help='Number of seconds to wait for success before returning "pending"')
_add_principal_argument(p)
p.set_defaults(handler=registerMachine)
def getCertificate(args):
req = {
'principal': args.principal,
}
if args.timeout is not None:
req['timeout'] = args.timeout
res = script(args, 'getCertificate', args.keyFile, req)
if res['state'] == 'certificate-pending':
return
elif res['state'] == 'not-registered':
sys.exit(1)
elif res['state'] == 'certificate-issued':
if args.output is not None:
with open(args.output, 'w') as f:
print(res['certificate'], file=f)
else:
print(res['certificate'])
p = ssp.add_parser('certificate', help='Retrieve machine certificate', **SP_ARGS)
p.add_argument('-k', '--key', dest='keyFile', default=VOUCH_ID_KEYFILE)
p.add_argument('-o', '--output', metavar='FILENAME')
p.add_argument('--timeout', metavar='SECONDS', type=int, default=None,
help='Number of seconds to wait for success before returning "pending"')
_add_principal_argument(p)
p.set_defaults(handler=getCertificate)
def clearCertificate(args):
script(args, 'clearCertificate', args.keyFile, {
'principal': args.principal,
})
p = ssp.add_parser('clear-certificate', help='Remove cached machine certificate', **SP_ARGS)
p.add_argument('-k', '--key', dest='keyFile', default=VOUCH_ID_KEYFILE)
_add_principal_argument(p)
p.set_defaults(handler=clearCertificate)
def machine_setup(args):
specifier = f"{args.serviceUrl} {args.principal['id']}"
lines = []
if not args.remove:
commandline = ['ProxyCommand', 'vouch', 'magic']
params = {
'api': args.serviceUrl,
'principal': args.principal,
}
if args.insecure:
params['insecure'] = True
def esc(s):
return "'" + s.replace("'", "'\"'\"'") + "'"
if args.comment != defaultComment():
params['comment'] = args.comment
commandline.extend(['--comment', esc(args.comment)])
if args.keyFile != VOUCH_ID_KEYFILE:
params['key'] = args.keyFile
commandline.extend(['--key', esc(args.keyFile)])
if args.checkIssuer is False:
params['check-issuer'] = False
commandline.extend(['--no-check-issuer'])
if args.saveCertificate:
params['save-certificate'] = True
commandline.extend(['--save-certificate'])
if args.principal['epoch'] is not False:
commandline.extend(['--epoch', esc(args.principal['epoch'])])
else:
commandline.extend(['--any-epoch'])
commandline.extend(['%h', '%p', esc(args.principal['id'])])
lines.append('# vouch machine setup: ' + json.dumps(params) + '\n')
lines.append(' '.join(commandline) + '\n')
mksshdir()
munge(os.path.expanduser('~/.ssh/config'),
'# ', specifier, '',
lines,
show_details=args.show_details,
dry_run=args.dry_run)
p = ssp.add_parser('setup', help='Set up SSH client configuration', **SP_ARGS)
_add_munge_arguments(p)
add_login_args(p, include_dry_run=False)
p.set_defaults(handler=machine_setup)
#---------------------------------------------------------------------------
def login(args):
keyFile = os.path.expanduser(args.keyFile)
certFile = keyFile + '-cert.pub'
agent = SshAgent()
if not agent.socket_path:
progress_warning('ssh-agent not running or not configured')
if args.saveCertificate:
progress_info('Will only save certificate to disk')
else:
progress_message('no ssh-agent, cannot load certificates')
progress_fail()
progress_message('Checking key pair')
if os.path.exists(keyFile):
progress_ok()
else:
if args.dryRun:
progress_detail(' — key pair not present')
progress_fail()
progress_message('Generating key pair')
check_output(['ssh-keygen',
'-q',
'-t', 'ed25519',
'-C', args.comment,
'-N', '',
'-f', keyFile])
progress_check(os.path.exists(keyFile))
check_output(['ssh-add', '-q', keyFile])
with open(keyFile, 'rt') as f:
secret_key = decode_secret_key(f.read())
issuerKey = None
if args.checkIssuer:
progress_detail(' — fetching CA key')
issuerKeyStr = script(args, 'registerServer', None, {
'principal': args.principal,
})['principal_key']
issuerKey = Ed25519PublicKey().load(base64.b64decode(issuerKeyStr.split(' ')[1]))
progress_message('Checking ssh-agent for usable existing certificates')
to_remove = []
chosen = None
for (keytype, keybytes, keycomment) in agent.list_identities():
if keytype != Ed25519Certificate.MAGIC:
continue
candidate = Ed25519Certificate().load(keybytes)
if candidate.signed_public_key != secret_key.public_key:
continue
if args.checkIssuer:
if candidate.issuer_public_key != issuerKey:
to_remove.append((candidate, 'it was issued by a different CA'))
continue
errors = candidate.validity_errors()
if errors:
to_remove.append((candidate, ' and '.join(errors)))
continue
if chosen is None:
chosen = candidate
else:
if candidate.valid_before > chosen.valid_before:
to_remove.append((chosen, 'it is not longest-lived'))
chosen = candidate
else:
to_remove.append((candidate, 'it is not longest-lived'))
if chosen is None:
progress_detail(' — no usable certificate present')
progress_ok()
for (cert, reason) in to_remove:
if _verbose:
progress_info('Removing an existing certificate because ' + reason)
if not args.dryRun:
agent.remove_identity(cert.blob)
if chosen is None:
if args.dryRun:
progress_info('Dry run, not requesting a certificate')
return
progress_message('Fetching certificate')
def get_rendezvous_code(timeout):
res = script(args, 'registerMachine', args.keyFile, {
'principal': args.principal,
'comment': args.comment,
'timeout': timeout,
})
if res['state'] == 'registration-pending':
return res['rendezvous_code']
elif res['state'] == 'registered':
return None
def get_certificate(timeout):
res = script(args, 'getCertificate', args.keyFile, {
'principal': args.principal,
'timeout': timeout,
})
if res['state'] == 'certificate-issued':
return res['certificate']
elif res['state'] == 'certificate-pending':
return None
elif res['state'] == 'not-registered':
return False
old_rendezvous_code = None
new_rendezvous_code = None
class State(Enum):
REGISTRATION_UNKNOWN = auto()
REGISTRATION_PENDING = auto()
CERTIFICATE_UNKNOWN = auto()
CERTIFICATE_PENDING = auto()
state = State.REGISTRATION_UNKNOWN
TIMEOUT_SECONDS = 30
while True:
if state in [State.REGISTRATION_UNKNOWN, State.REGISTRATION_PENDING]:
timeout = 0 if state is State.REGISTRATION_UNKNOWN else TIMEOUT_SECONDS
new_rendezvous_code = get_rendezvous_code(timeout)
if new_rendezvous_code is None:
state = State.CERTIFICATE_UNKNOWN
else:
if old_rendezvous_code != new_rendezvous_code:
progress_message('Authorize machine in app. Registration code: ' + new_rendezvous_code)
old_rendezvous_code = new_rendezvous_code
state = State.REGISTRATION_PENDING
elif state in [State.CERTIFICATE_UNKNOWN, State.CERTIFICATE_PENDING]:
timeout = 0 if state is State.CERTIFICATE_UNKNOWN else TIMEOUT_SECONDS
cert_str = get_certificate(timeout)
if cert_str == False:
state = State.REGISTRATION_UNKNOWN
elif cert_str is None:
state = State.CERTIFICATE_PENDING
progress_message('Waiting for certificate to issue')
else:
chosen = Ed25519Certificate().load(base64.b64decode(cert_str.split(' ')[1]))
break
progress_ok()
if args.saveCertificate:
progress_message('Writing certificate to disk')
with open(certFile, 'wt') as f:
f.write(cert_str)
progress_ok()
progress_message('Adding certificate to ssh-agent')
agent.add_identity(Ed25519Certificate.MAGIC,
(format_str(chosen.blob) +
format_str(secret_key.public_key.public_key_bytes) +
format_str(secret_key.secret_key_seed +
secret_key.public_key.public_key_bytes)),
b'')
progress_ok()
p = sp.add_parser('login', help='Run through all the steps to ensure a certificate is available', **SP_ARGS)
add_login_args(p)
p.set_defaults(handler=login)
def logout(args):
if not args.local_only:
progress_message('Clearing cached certificate at server')
script(args, 'clearCertificate', args.keyFile, {
'principal': args.principal,
})
progress_ok()
keyFile = os.path.expanduser(args.keyFile)
agent = SshAgent()
if not agent.socket_path:
progress_warning('ssh-agent not running or not configured')
return
if not os.path.exists(keyFile):
return
with open(keyFile, 'rt') as f:
secret_key = decode_secret_key(f.read())
progress_message('Checking ssh-agent for certificates to remove')
for (keytype, keybytes, keycomment) in agent.list_identities():
if keytype != Ed25519Certificate.MAGIC:
continue
candidate = Ed25519Certificate().load(keybytes)
if candidate.signed_public_key == secret_key.public_key:
agent.remove_identity(candidate.blob)
progress_ok()
p = sp.add_parser('logout', help='Delete certificates from SSH agent and optionally from server', **SP_ARGS)
p.add_argument('-k', '--key', dest='keyFile', default=VOUCH_ID_KEYFILE)
p.add_argument('--local-only', action='store_true',
help='Remove certificates from SSH agent only, leave certificates on server')
_add_principal_argument(p)
p.set_defaults(handler=logout)
#---------------------------------------------------------------------------
p = sp.add_parser('principal', help='Tools for managing a principal account', **SP_ARGS)
principal_p = p
p.set_defaults(handler=lambda args: principal_p.print_help())
ssp = p.add_subparsers()
_add_help_to(p, ssp)
p = ssp.add_parser('machine', help='Manage registered machines', **SP_ARGS)
principal_machine_p = p
p.set_defaults(handler=lambda args: principal_machine_p.print_help())
sssp = p.add_subparsers()
_add_help_to(p, sssp)
def deregisterMachine(args):
print(json.dumps(script(args, 'deregisterMachine', args.keyFile, {
'machine': args.machineKey,
})['deleted']))
p = sssp.add_parser('deregister', help='Deregister a machine', **SP_ARGS)
p.add_argument('keyFile', metavar='principalKeyFile')
p.add_argument('machineKey')
p.set_defaults(handler=deregisterMachine)
def setMachine(args):
script(args, 'setMachine', args.keyFile, {
'machine': args.machineKey,
'comment': args.comment,
})
p = sssp.add_parser('update', help='Update a registered machine', **SP_ARGS)
p.add_argument('keyFile', metavar='principalKeyFile')
p.add_argument('machineKey')
p.add_argument('comment')
p.set_defaults(handler=setMachine)
def setCertificate(args):
script(args, 'setCertificate', args.keyFile, {
'machine': args.machineKey,
'certificate': None if args.certificate == '' else args.certificate,
})
p = sssp.add_parser('set', help='Set or clear a machine\'s certificate', **SP_ARGS)
p.add_argument('keyFile', metavar='principalKeyFile')
p.add_argument('machineKey')
p.add_argument('certificate', default='', nargs='?')
p.set_defaults(handler=setCertificate)
def listMachines(args):
if not args.json:
print('comment\tcert_present\tregistration_time\trequest_time\tpub')
for u in script(args, 'listMachines', args.keyFile, {})['machines']:
if args.json:
print(json.dumps(u))
else:
print(f'{u["comment"]}\t{"Y" if u["certificate"] else "N"}\t{u["registration_time"] or ""}\t{u["request_time"] or ""}\t{u["machine"]}')
p = sssp.add_parser('list', help='List registered machines', **SP_ARGS)
p.add_argument('keyFile', metavar='principalKeyFile')
p.add_argument('-j', '--json', action='store_true')
p.set_defaults(handler=listMachines)
def lookupRegistration(args):