-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpyroughtime.py
executable file
·1504 lines (1316 loc) · 53.3 KB
/
pyroughtime.py
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
# -*- coding: utf-8 -*-
# pyroughtime
# Copyright (C) 2019-2025 Marcus Dansarie <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
import argparse
import datetime
import json
import secrets
import socket
import struct
import sys
import threading
import time
from base64 import b64decode, b64encode
from typing import Literal, Optional
from Cryptodome.Hash import SHA512
from Cryptodome.Signature import eddsa
class RoughtimeError(Exception):
'Represents an error that has occured in the Roughtime client.'
def __init__(self, message: str) -> None:
super(RoughtimeError, self).__init__(message)
class RoughtimeResult:
'''
Represents the result of a Roughtime time request. Use the various methods
to access information about the request.
Args:
publ (str): the public key used to verify the server's
response, as a base-64 encoded string.
nonce (str): the nonce sent in the request, as a
base64-encoded nonce string.
blind (str): the blind used to generate the nonce for the
request from a previous response, as a base64-encoded
string.
request_data (bytes): the request packet sent to the server.
response_data (bytes): the response packet received from the
server.
midp (int): the midpoint timestamp returned by the server, in
seconds.
radi (int): the radius returned by the server, in seconds.
request_time (int): the time at which the request was sent, in
nanoseconds. The time must be on the monotonic timescale
used by time.monotonic_ns.
response_time (int): the time at which the response was
received, in nanoseconds. The time must be on the monotonic
timescale used by time.monotonic_ns.
mint (int): the minimum midpoint time at which the provided
certificate may be used to sign responses.
maxt (int): the maximum midpoint time at which the provided
certificate may be used to sign responses.
pathlen (int): the length of the Merkle three path sent in the
server's reply.
ver (int): the server's reported version.
'''
def __init__(self,
publ: str,
nonce: str,
blind: str,
request_data: bytes,
response_data: bytes,
midp: int,
radi: int,
request_time: int,
response_time: int,
mint: int,
maxt: int,
pathlen: int,
ver: int,
vers: list[int]) -> None:
self._publ = publ
self._nonce = nonce
self._blind = blind
self._reqdata = request_data
self._resdata = response_data
self._midp = midp
self._radi = radi
self._request_time = request_time
self._response_time = response_time
self._mint = mint
self._maxt = maxt
self._pathlen = pathlen
self._ver = ver
self._vers = vers
def __str__(self) -> str:
'''
Returns:
A string representation of the returned time and radius that can be
shown to a user. Currently, this method returns the output of the
prettytime method.
'''
return self.prettytime()
def public_key(self) -> str:
'''
Returns:
The public key used to validate the query result, as a
base64-encoded string.
'''
return self._publ
def nonce(self) -> str:
'''
Returns:
The nonce sent in the request, as a base64-encoded string.
'''
return self._nonce
def blind(self) -> str:
'''
Returns:
The blind used to generate the nonce for this request from a
previous response, as a base64-encoded string.
'''
return self._blind
def request_packet(self) -> bytes:
'''
Returns:
The request packet sent to the server in this request.
'''
return self._reqdata
def result_packet(self) -> bytes:
'''
Returns:
The result packet sent from the server in reply the request.
'''
return self._resdata
def prettytime(self) -> str:
'''
Returns:
A nice-looking string representation of the time and radius
returned by the server in the response. The format is of the form
2000-01-01 12:34:56 UTC (+/- 1 s).
'''
timestr = self.datetime().strftime('%Y-%m-%d %H:%M:%S')
return '%s UTC (+/- % 2d s)' % (timestr, self.radi())
def midp(self) -> int:
'''
Returns:
The midpoint timestamp in seconds since the Posix epoch at 00:00:00
on 1 January 1970, representing the best estimate of time of
processing of the response in the server.
'''
return self._midp
def radi(self) -> int:
'''
Returns:
The radius returned by the server, indicating guaranteed accuracy
of the midpoint, in seconds.
'''
return self._radi
def datetime(self) -> datetime.datetime:
'''
Returns:
A datetime object representing the midpoint returned by the server.
'''
return RoughtimeClient.timestamp_to_datetime(self.midp())
def rtt(self) -> float:
'''
Returns:
The round trip time, i.e. the time elapsed between the request was
sent and the response was received, in seconds.
'''
return (self._response_time - self._request_time) * 1E-9
def mint(self):
'''
Returns:
The minimum timestamp for the delegated key used to sign the
response, indicating the minimum midpoint time for which the
certificate may be used to sign responses.
'''
return RoughtimeClient.timestamp_to_datetime(self._mint)
def maxt(self):
'''
Returns:
The maximum timestamp for the delegated key used to sign the
response, indicating the maximum midpoint time for which the
certificate may be used to sign responses.
'''
return RoughtimeClient.timestamp_to_datetime(self._maxt)
def pathlen(self) -> int:
'''
Returns:
The length of the Merkle tree path sent in the server's reply.
Equivalent to the height of the Merkle tree.
'''
return self._pathlen
def ver(self: RoughtimeResult) -> str:
'''
Returns:
A string representing the reply version.
'''
return RoughtimeResult._ver_to_str(self._ver)
def vers(self: RoughtimeResult) -> str:
'''
Returns:
A string representing the server's supported versions.
'''
ret = ''
for v in self._vers:
if len(ret) != 0:
ret += ' '
ret += RoughtimeResult._ver_to_str(v)
return ret
@staticmethod
def _ver_to_str(ver: int) -> str:
if ver & 0x80000000 != 0:
return 'draft-%02d' % (ver & 0x7fffffff)
return str(ver)
class RoughtimeServer:
'''
Implements a Roughtime server that provides authenticated time. Instances
are started with the start method and stopped with the stop method.
Args:
publ (str): The server's base64-encoded Ed25519 public key.
cert (str): A base64-encoded Roughtime CERT packet containing a
delegated certificate signed with a long-term key. The
certificate signature must have been made using publ.
dpriv (str): A base64-encoded Ed25519 private key for the delegated
certificate.
radi (int): The time accuracy (RADI) that the server should report.
Raises:
RoughtimeError: If cert was not signed with publ or if cert and dpriv
do not represent a valid Ed25519 certificate pair.
'''
CERTIFICATE_CONTEXT = b'RoughTime v1 delegation signature\x00'
SIGNED_RESPONSE_CONTEXT = b'RoughTime v1 response signature\x00'
ROUGHTIME_HEADER = 0x4d49544847554f52
ROUGHTIME_VERSION = 0x8000000c
def __init__(self, publ: str, cert: str, dpriv: str, radi: int = 3) \
-> None:
self._sock = None # type: Optional[socket.socket]
self._run = False
self._thread = None # type: Optional[threading.Thread]
cert_bytes = b64decode(cert)
if len(cert_bytes) != 152:
raise RoughtimeError('Wrong CERT length.')
self._cert = RoughtimePacket('CERT', cert_bytes)
self._dpriv = eddsa.import_private_key(b64decode(dpriv))
if radi < 1:
radi = 1
self._radi = int(radi)
# Ensure that CERT was signed with publ.
dele = self._cert.get_tag('DELE')
sig = self._cert.get_tag('SIG')
publ_bytes = b64decode(publ)
pubkey = eddsa.import_public_key(publ_bytes)
try:
ver = eddsa.new(pubkey, 'rfc8032')
ver.verify(RoughtimeServer.CERTIFICATE_CONTEXT
+ dele.get_value_bytes(),
sig.get_value_bytes())
except Exception:
raise RoughtimeError('CERT was not signed with publ.')
# Calculate SRV tag value.
ha = SHA512.new()
ha.update(b'\xff')
ha.update(publ_bytes)
self._srvval = ha.digest()[:32]
# Ensure that the CERT and private key are a valid pair.
assert isinstance(dele, RoughtimePacket)
dele_pubkey = eddsa.import_public_key(
dele.get_tag('PUBK').get_value_bytes())
self._sign = eddsa.new(self._dpriv, 'rfc8032')
testsign = self._sign.sign(RoughtimeServer.SIGNED_RESPONSE_CONTEXT)
try:
ver = eddsa.new(dele_pubkey, 'rfc8032')
ver.verify(RoughtimeServer.SIGNED_RESPONSE_CONTEXT, testsign)
except Exception:
raise RoughtimeError('CERT and dpriv arguments are not a valid '
+ 'certificate pair.')
def start(self, ip: str, port: int) -> None:
'''
Starts the Roughtime server.
Args:
ip (str): The IP address the server should bind to.
port (int): The UDP port the server should bind to.
'''
if self._run:
raise RoughtimeError('Server already running.')
try:
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._sock.bind((ip, port))
self._sock.settimeout(0.001)
self._run = True
self._thread = threading.Thread(
target=RoughtimeServer._recv_thread,
args=(self,))
self._thread.start()
except Exception as ex:
self._run = False
if self._thread is not None:
self._thread.join()
self._thread = None
if self._sock is not None:
self._sock.close()
self._sock = None
raise ex
def stop(self) -> None:
'Stops the Roughtime server.'
if not self._run:
return
self._run = False
assert self._thread is not None
assert self._sock is not None
self._thread.join()
self._sock.close()
self._thread = None
self._sock = None
@staticmethod
def _ctz(v):
'Count trailing zeros.'
return (v & -v).bit_length() - 1
@staticmethod
def _clp2(x: int) -> int:
'Returns the next power of two.'
x -= 1
x |= x >> 1
x |= x >> 2
x |= x >> 4
x |= x >> 8
x |= x >> 16
return x + 1
@staticmethod
def _construct_merkle(msgs: list[bytes],
prev: Optional[list[list[bytes]]] = None,
height: Optional[int] = None) -> list[list[bytes]]:
'''
Recursively builds a Merkle tree from a list of request messages.
Args:
msgs (list[bytes]): List of messages to include in the Merkle tree.
prev (list[bytes] | None): The partially built tree. Set to None on
first call.
height (int | None): Remaining height of the Merkle tree. Set to
None on first call.
Returns:
merkle (list[list[bytes]]): A Merkle tree.
'''
# If this is the initial call to the method.
if prev is None:
# Hash messages.
hashes = []
for m in msgs:
ha = SHA512.new()
ha.update(b'\x00' + m)
hashes.append(ha.digest()[:32])
# Calculate next power of two and height of tree.
size = RoughtimeServer._clp2(len(hashes))
height = RoughtimeServer._ctz(size)
# Extend nonce list to the next power of two.
hashes += [secrets.token_bytes(32)
for x in range(size - len(hashes))]
return RoughtimeServer._construct_merkle(hashes, [hashes], height)
assert height is not None
if height == 0:
return prev
out = []
for i in range(1 << (height - 1)):
ha = SHA512.new()
ha.update(b'\x01' + msgs[i * 2] + msgs[i * 2 + 1])
out.append(ha.digest()[:32])
prev.append(out)
return RoughtimeServer._construct_merkle(out, prev, height - 1)
@staticmethod
def _construct_merkle_path(merkle: list[list[bytes]], index: int) -> bytes:
'Returns the Merkle tree path for a nonce index.'
out = b''
while len(merkle) > 1:
out += merkle[0][index ^ 1]
merkle = merkle[1:]
index >>= 1
return out
@staticmethod
def _datetime_to_timestamp(dt: datetime.datetime) -> int:
'Converts a datetime object into a Posix timestamp.'
return int(dt.timestamp())
@staticmethod
def _recv_thread(ref: RoughtimeServer) -> None:
'''
Request packet receive thread for the server.
Args:
ref (RoughtimeServer): reference to the owning server instance.
'''
assert ref._sock is not None
while ref._run:
try:
data, addr = ref._sock.recvfrom(1500)
except socket.timeout:
continue
# Ignore requests shorter than 1024 bytes.
if len(data) < 1024:
print('Bad length.')
continue
try:
request = RoughtimePacket(packet=data, expect_header=True)
except Exception as ex:
print(ex)
print('Bad packet: %s' % str(ex))
continue
# Ensure request contains a proper VER tag.
if not request.contains_tag('VER'):
print('Request missing VER tag.')
continue
if not request.contains_tag('NONC'):
print('Request missing NONC tag.')
continue
ver = request.get_tag('VER')
if ver.get_value_len() % 4 != 0:
print('Wrong VER value length: %d' % ver.get_value_len())
continue
version_ok = False
ver_bytes = ver.get_value_bytes()
prev = 0
for n in range(ver.get_value_len() // 4):
vernum = RoughtimePacket.unpack_uint32(ver_bytes, n * 4)
if n != 0 and vernum <= prev:
print('Version numbers not sorted')
break
if vernum == RoughtimeServer.ROUGHTIME_VERSION:
version_ok = True
break
prev = vernum
if not version_ok:
print('No matching version in request')
continue
# Ensure request contains a proper NONC tag.
nonc = request.get_tag('NONC').get_value_bytes()
if len(nonc) != 32:
print('Wrong NONC value length: %d' % len(nonc))
continue
# Check SRV tag, if present.
if request.contains_tag('SRV'):
request_srv = request.get_tag('SRV').get_value_bytes()
if len(request_srv) != 32:
print('Bad SRV tag value length: %d' % len(request_srv))
continue
if request_srv != ref._srvval:
print('Unknown SRV tag value: %s, expected %s'
% (request_srv.hex(), ref._srvval.hex()))
continue
noncelist = [data]
merkle = RoughtimeServer._construct_merkle(noncelist)
path_bytes = RoughtimeServer._construct_merkle_path(merkle, 0)
# Construct reply.
reply = RoughtimePacket()
reply.add_tag(ref._cert)
reply.add_tag(request.get_tag('NONC'))
# Single nonce Merkle tree.
indx = RoughtimeTag('INDX')
indx.set_value_uint32(0)
reply.add_tag(indx)
path = RoughtimeTag('PATH')
path.set_value_bytes(path_bytes)
reply.add_tag(path)
srep = RoughtimePacket('SREP')
verbytes = RoughtimeTag.uint32_to_bytes(
RoughtimeServer.ROUGHTIME_VERSION)
srep.add_tag(RoughtimeTag('VER', verbytes))
srep.add_tag(RoughtimeTag('VERS', verbytes))
root = RoughtimeTag('ROOT', merkle[-1][0])
srep.add_tag(root)
midp = RoughtimeTag('MIDP')
midp.set_value_uint64(RoughtimeServer._datetime_to_timestamp(
datetime.datetime.now()))
srep.add_tag(midp)
radi = RoughtimeTag('RADI')
radival = ref._radi
if radival < 1:
radival = 1
radi.set_value_uint32(radival)
srep.add_tag(radi)
reply.add_tag(srep)
sig = RoughtimeTag('SIG', ref._sign.sign(
RoughtimeServer.SIGNED_RESPONSE_CONTEXT
+ srep.get_value_bytes()))
reply.add_tag(sig)
ref._sock.sendto(reply.get_value_bytes(packet_header=True), addr)
@staticmethod
def create_key() -> tuple[str, str]:
'''
Generates a long-term Ed25519 key pair.
Returns:
priv (str): A base64-encoded Ed25519 private key.
publ (str): A base64-encoded Ed25519 public key.
'''
priv = secrets.token_bytes(32)
publ = eddsa.import_private_key(priv).public_key() \
.export_key(format='raw')
return (b64encode(priv).decode('ascii'),
b64encode(publ).decode('ascii'))
@staticmethod
def create_delegated_key(priv: str,
mint: Optional[int] = None,
maxt: Optional[int] = None) -> tuple[str, str]:
'''
Generates a Roughtime delegated key signed by a long-term key.
Args:
priv (str): A base64-encoded Ed25519 private key.
mint (int): Start of the delegated key's validity time in seconds
since the epoch.
maxt (int): End of the delegated key's validity time in seconds
since the epoch.
Returns:
cert (str): A base64 encoded Roughtime CERT packet.
dpriv (str): A base64 encoded Ed25519 private key.
'''
if mint is None:
mint = RoughtimeServer._datetime_to_timestamp(
datetime.datetime.now())
if maxt is None or maxt <= mint:
maxt = RoughtimeServer._datetime_to_timestamp(
datetime.datetime.now() + datetime.timedelta(days=30))
privkey = eddsa.new(eddsa.import_private_key(b64decode(priv)),
'rfc8032')
dpriv = secrets.token_bytes(32)
dpubl = eddsa.import_private_key(dpriv).public_key() \
.export_key(format='raw')
mint_tag = RoughtimeTag('MINT')
maxt_tag = RoughtimeTag('MAXT')
mint_tag.set_value_uint64(mint)
maxt_tag.set_value_uint64(maxt)
pubk = RoughtimeTag('PUBK')
pubk.set_value_bytes(dpubl)
dele = RoughtimePacket(key='DELE')
dele.add_tag(mint_tag)
dele.add_tag(maxt_tag)
dele.add_tag(pubk)
delesig = privkey.sign(RoughtimeServer.CERTIFICATE_CONTEXT
+ dele.get_value_bytes())
sig = RoughtimeTag('SIG', delesig)
cert = RoughtimePacket('CERT')
cert.add_tag(dele)
cert.add_tag(sig)
return (b64encode(cert.get_value_bytes()).decode('ascii'),
b64encode(dpriv).decode('ascii'))
@staticmethod
def test_server() -> tuple[RoughtimeServer, str]:
'''
Starts a Roughtime server listening on 127.0.0.1, port 2002 for
testing.
Returns:
serv (RoughtimeServer): The server instance.
publ (str): The server's public long-term key.
'''
priv, publ = RoughtimeServer.create_key()
cert, dpriv = RoughtimeServer.create_delegated_key(priv)
serv = RoughtimeServer(publ, cert, dpriv)
serv.start('127.0.0.1', 2002)
return serv, publ
class RoughtimeClient:
'''
Queries Roughtime servers for the current time and authenticates the
replies.
Args:
max_history_len (int): The number of previous replies to keep.
'''
def __init__(self, max_history_len: int = 100):
self._prev_replies = [] # type: list[RoughtimeResult]
self._max_history_len = max_history_len
@staticmethod
def timestamp_to_datetime(ts: int) -> datetime.datetime:
'''
Converts a Posix timestamp to a datetime instance. The underlying
implementation supports is limited to 32-bit integers, resulting in
dates and times after 2106-02-07 06:28:15 being represented
incorrectly. The behavior for negative timestamps is unspecified.
Args:
ts (int): A Posix timestamp in seconds since the epoch at 00:00:00
on 1 January 1970.
Returns:
A datetime representation of the timestamp.
'''
# Underlying implementation is limited to 32 bits.
if ts > 0xffffffff:
ts = 0xffffffff
return datetime.datetime.fromtimestamp(ts, datetime.UTC)
@staticmethod
def _udp_query(address: str,
port: int,
packet: bytes,
timeout: int | float) \
-> tuple[RoughtimePacket, int, int, bytes]:
'''
Performs a Roughtime query using the UDP transport protocol.
Args:
address (str): the IP address or DNS name of the server to query.
port (str): UDP port number for the request.
packet (bytes): the Roughtime request packet to send.
timeout (int | float): time to wait for response packet before
failing, in seconds.
Returns:
packet (RoughtimePacket): a RoughtimePacket instance, representing
the parsed response packet.
request_time (int): request transmit time in nanoseconds, as
reported by time.monotonic_ns().
response_time (int): response receive time in nanoseconds, as
reported by time.monotonic_ns().
data (bytes): the complete response packet.
'''
timeout *= 1000000000
for family, type_, proto, canonname, sockaddr in \
socket.getaddrinfo(address, port, type=socket.SOCK_DGRAM):
sock = socket.socket(family, socket.SOCK_DGRAM)
try:
sock.sendto(packet, (sockaddr[0], sockaddr[1]))
request_time = time.monotonic_ns()
except Exception:
# Try next IP on failure.
sock.close()
continue
# Wait for reply
while time.monotonic_ns() - request_time < timeout:
remtime = timeout - (time.monotonic_ns() - request_time)
sock.settimeout(remtime * 1E-9)
try:
data, repl = sock.recvfrom(1500)
receive_time = time.monotonic_ns()
repl_addr = repl[0]
repl_port = repl[1]
except socket.timeout:
continue
if repl_addr == sockaddr[0] and repl_port == sockaddr[1]:
break
sock.close()
if receive_time - request_time >= timeout:
# Try next IP on timeout.
continue
# Break out of loop if successful.
break
if receive_time - request_time >= timeout:
raise RoughtimeError('Timeout while waiting for reply.')
reply = RoughtimePacket(packet=data, expect_header=True)
return reply, request_time, receive_time, data
@staticmethod
def _tcp_query(address: str,
port: int,
packet: bytes,
timeout: int | float) \
-> tuple[RoughtimePacket, int, int, bytes]:
'''
Performs a Roughtime query using the TCP transport protocol. TCP
queries are an experimental feature.
Args:
address (str): the IP address or DNS name of the server to query.
port (str): TCP port number for the request.
packet (bytes): the Roughtime request packet to send.
timeout (int | float): time to wait for response packet before
failing, in seconds.
Returns:
packet (RoughtimePacket): a RoughtimePacket instance, representing
the parsed response packet.
request_time (int): request transmit time in nanoseconds, as
reported by time.monotonic_ns().
response_time (int): response receive time in nanoseconds, as
reported by time.monotonic_ns().
data (bytes): the complete response packet.
'''
for family, type_, proto, canonname, sockaddr in \
socket.getaddrinfo(address, port, type=socket.SOCK_STREAM):
sock = socket.socket(family, socket.SOCK_STREAM)
sock.settimeout(timeout)
try:
sock.connect((sockaddr[0], sockaddr[1]))
sock.sendall(packet)
request_time = time.monotonic_ns()
except Exception:
# Try next IP on failure.
sock.close()
continue
# Wait for reply
buf = bytes()
response_time = None
while time.monotonic_ns() - request_time < timeout * 1000000000:
remtime = timeout - (time.monotonic_ns() - request_time) * 1E-9
sock.settimeout(remtime)
try:
buf += sock.recv(4096)
if response_time is None:
response_time = time.monotonic_ns()
except socket.timeout:
continue
if len(buf) < 12:
continue
(magic, repl_len) = struct.unpack('<QI', buf[:12])
if magic != RoughtimeServer.ROUGHTIME_HEADER:
sock.close()
raise RoughtimeError('Bad packet header.')
if repl_len > 1500:
sock.close()
raise RoughtimeError('Response packet too large')
if repl_len + 12 > len(buf):
continue
data = buf[:repl_len + 12]
break
sock.close()
if time.monotonic_ns() - request_time >= timeout * 1000000000:
# Try next IP on timeout.
continue
# Break out of loop if successful.
break
if time.monotonic_ns() - request_time >= timeout * 1000000000:
raise RoughtimeError('Timeout while waiting for reply.')
reply = RoughtimePacket(packet=data, expect_header=True)
assert response_time is not None
return reply, request_time, response_time, data
def query(self,
address: str,
port: int,
publ: str,
timeout: float | int = 2,
protocol: Literal['udp', 'tcp'] = 'udp') -> RoughtimeResult:
'''
Sends a time query to the server, waits for a reply, and then verifies
it.
Args:
address (str): The server address.
port (int): The server port.
publ (str): The server's public key in base64 format. This is used
to indicate to request a particular signing key from the server
and to authenticate the received response.
timeout (float | int): Maximum time to wait for a reply from the
server, in seconds.
protocol ('udp' | 'tcp'): The transport layer protocol to use for
the request.
Raises:
RoughtimeError: On any error. The message will describe the
specific error that occurred.
Returns:
A RoughtimeResult instance, describing the query result.
'''
if protocol != 'udp' and protocol != 'tcp':
raise RoughtimeError('Illegal protocol type.')
publ_bytes = b64decode(publ)
pubkey = eddsa.new(eddsa.import_public_key(publ_bytes), 'rfc8032')
# Generate nonce.
blind = secrets.token_bytes(32)
ha = SHA512.new()
if len(self._prev_replies) > 0:
ha.update(self._prev_replies[-1].result_packet())
ha.update(blind)
nonce = ha.digest()[:32]
# Create query packet.
packet = RoughtimePacket()
ha = SHA512.new()
ha.update(b'\xff')
ha.update(publ_bytes)
srvhash = ha.digest()[:32]
packet.add_tag(RoughtimeTag('SRV', srvhash))
packet.add_tag(RoughtimeTag('VER', RoughtimeTag.uint32_to_bytes(
RoughtimeServer.ROUGHTIME_VERSION)))
packet.add_tag(RoughtimeTag('NONC', nonce))
if protocol == 'udp':
packet.add_padding()
request_packet_bytes = packet.get_value_bytes(True)
if protocol == 'udp':
query_fun = self._udp_query
elif protocol == 'tcp':
query_fun = self._tcp_query
else:
raise ValueError('Bad protocol string.')
reply, request_time, response_time, result_packet_bytes = \
query_fun(address, port, request_packet_bytes, timeout)
# Get reply tags.
try:
srep = reply.get_tag('SREP')
cert = reply.get_tag('CERT')
if not isinstance(srep, RoughtimePacket) or \
not isinstance(cert, RoughtimePacket):
raise Exception()
dele = cert.get_tag('DELE')
if not isinstance(dele, RoughtimePacket):
raise Exception()
nonc = reply.get_tag('NONC')
dsig = cert.get_tag('SIG').get_value_bytes()
midp = srep.get_tag('MIDP').to_int()
radi = srep.get_tag('RADI').to_int()
root = srep.get_tag('ROOT').get_value_bytes()
sig = reply.get_tag('SIG').get_value_bytes()
indx = reply.get_tag('INDX').to_int()
path = reply.get_tag('PATH').get_value_bytes()
pubk = dele.get_tag('PUBK').get_value_bytes()
mint = dele.get_tag('MINT').to_int()
maxt = dele.get_tag('MAXT').to_int()
ver = srep.get_tag('VER')
vers = srep.get_tag('VERS')
except Exception:
raise RoughtimeError('Missing tag in server reply or parse error.')
if nonc.get_value_bytes() != nonce:
raise RoughtimeError('Bad NONC in server reply.')
ver_num = ver.to_int()
ver_list = vers.to_int32_list()
# Verify signature of DELE with long term certificate.
try:
recvpacket = dele.get_received()
assert recvpacket is not None
pubkey.verify(RoughtimeServer.CERTIFICATE_CONTEXT + recvpacket,
dsig)
except Exception:
raise RoughtimeError('Verification of long term certificate '
+ 'signature failed.')
# Verify that DELE timestamps are consistent with MIDP value.
if mint > midp or maxt < midp:
raise RoughtimeError('MIDP outside delegated key validity time.')
node_size = 32
ha = SHA512.new()
# Ensure that Merkle tree is correct and includes request packet.
ha.update(b'\x00' + request_packet_bytes)
curr_hash = ha.digest()[:node_size]
if len(path) % node_size != 0:
raise RoughtimeError('PATH length not a multiple of %d.'
% node_size)
pathlen = len(path) // node_size
if pathlen > 32:
raise RoughtimeError('Too long path in Merkle tree.')
while len(path) > 0:
ha = ha.new()
if indx & 1 == 0:
ha.update(b'\x01' + curr_hash + path[:node_size])
else:
ha.update(b'\x01' + path[:node_size] + curr_hash)
curr_hash = ha.digest()[:node_size]
path = path[node_size:]
indx >>= 1
if indx != 0:
raise RoughtimeError('INDX not zero after traversing PATH.')
if curr_hash != root:
raise RoughtimeError('Final Merkle tree value not equal to ROOT.')
# Verify that DELE signature of SREP is valid.
delekey = eddsa.new(eddsa.import_public_key(pubk), 'rfc8032')
try:
recvpacket = srep.get_received()
assert recvpacket is not None
delekey.verify(RoughtimeServer.SIGNED_RESPONSE_CONTEXT
+ recvpacket, sig)
except Exception:
raise RoughtimeError('Bad DELE key signature.')
result = RoughtimeResult(
publ, b64encode(nonce).decode('ascii'),
b64encode(blind).decode('ascii'), request_packet_bytes,
result_packet_bytes, midp, radi, request_time, response_time, mint,
maxt, pathlen, ver_num, ver_list)
self._prev_replies.append(result)
while len(self._prev_replies) > self._max_history_len:
self._prev_replies = self._prev_replies[1:]
return result
def get_previous_replies(self) -> list[RoughtimeResult]:
'''
Returns a list of previous replies recieved by the instance.
Returns:
prev_replies (list[RoughtimeResult]): A list of RoughtimeResult
instances. The list is in chronological order.
'''
return self._prev_replies
def get_inconsistent_replies(self) \
-> list[tuple[RoughtimeResult, RoughtimeResult]]:
'''
Goes through the list of replies that have been received by the
instance so far and verifies that there are no contradicting
timestamps.
Returns:
A list of pairs of RoughtimeResult instances with inconsistent
times. An empty list indicates that no replies appear to violate
causality.
'''
invalid_pairs = []
for i in range(len(self._prev_replies)):
reply_i = self._prev_replies[i]
packet_i = RoughtimePacket(packet=reply_i.result_packet())
srep_i = packet_i.get_tag('SREP')
assert isinstance(srep_i, RoughtimePacket)
midp_i = RoughtimeClient.timestamp_to_datetime(
srep_i.get_tag('MIDP').to_int())