Repository navigation
Expand file tree
/
Copy pathasyncvnc2.py
More file actions
4385 lines (3900 loc) · 199 KB
/
Copy pathasyncvnc2.py
File metadata and controls
4385 lines (3900 loc) · 199 KB
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
import hmac
import ssl
from asyncio import (
CancelledError,
IncompleteReadError,
Queue,
QueueFull,
StreamReader,
StreamWriter,
get_running_loop,
open_connection,
sleep,
start_server,
)
from base64 import b64encode
from contextlib import ExitStack, asynccontextmanager, contextmanager
from dataclasses import dataclass, field
from enum import Enum
from fractions import Fraction
from hashlib import sha1, sha256
from itertools import product
from os import urandom
from zlib import compress, decompressobj
from zlib import error as zlib_error
import numpy as np
from cryptography.hazmat.primitives import cmac
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.serialization import load_der_public_key
from keysymdef import keysymdef # type: ignore
from loguru import logger
# Keyboard keys
key_codes: dict[str, int] = {}
key_codes.update((name, code) for name, code, char in keysymdef)
key_codes.update((chr(char), code) for name, code, char in keysymdef if char)
key_codes['Del'] = key_codes['Delete']
key_codes['Esc'] = key_codes['Escape']
key_codes['Cmd'] = key_codes['Super_L']
key_codes['Alt'] = key_codes['Alt_L']
key_codes['Ctrl'] = key_codes['Control_L']
key_codes['Super'] = key_codes['Super_L']
key_codes['Shift'] = key_codes['Shift_L']
key_codes['Backspace'] = key_codes['BackSpace']
# Common screen aspect ratios
screen_ratios: set[Fraction] = {
Fraction(3, 2),
Fraction(4, 3),
Fraction(16, 10),
Fraction(16, 9),
Fraction(32, 9),
Fraction(64, 27),
}
# Colour channel orders
video_modes: dict[bytes, str] = {
b'\x20\x18\x00\x01\x00\xff\x00\xff\x00\xff\x10\x08\x00': 'bgra',
b'\x20\x18\x00\x01\x00\xff\x00\xff\x00\xff\x00\x08\x10': 'rgba',
b'\x20\x18\x01\x01\x00\xff\x00\xff\x00\xff\x10\x08\x00': 'argb',
b'\x20\x18\x01\x01\x00\xff\x00\xff\x00\xff\x00\x08\x10': 'abgr',
}
video_definition: dict[str, bytes] = {v: k for k, v in video_modes.items()}
#: Open H.264 encoding number (0x48323634 = ASCII "H264"). Intentionally NOT an
#: Enc member -- it must never be auto-advertised by EncList.default(), and there
#: is no verified wire format to decode it against. See Video.read() for details.
_H264_ENCODING = 0x48323634
#: Plafond défensif sur toute longueur/taille annoncée par le serveur avant
#: une allocation (Tight, ZlibHex, curseurs). 64 Mo est largement au-dessus
#: de tout besoin légitime -- juste assez pour éviter qu'un serveur hostile
#: ou buggé ne force une allocation démesurée.
_MAX_ALLOC_BYTES = 64 * 1024 * 1024
def _check_alloc_size(n: int, what: str):
if n > _MAX_ALLOC_BYTES:
raise ValueError(f'{what}: taille annoncée ({n} octets) dépasse le plafond de sécurité')
class Enc(Enum):
"""
Supported encodings
Default priority order is TIGHT, TIGHT_PNG, ZRLE, TRLE, ZLIB, HEXTILE, COPY, RAW.
ZYWRLE (17) is a supported member but deliberately NOT in this default
list -- see Enc.ZYWRLE and Enc.default() docstrings.
The remaining members are pseudo-encodings: they never "win" a rectangle
like the ones above, they either shape the framebuffer/cursor state
(CURSOR, X_CURSOR, CURSOR_WITH_ALPHA, DESKTOP_SIZE, EXTENDED_DESKTOP_SIZE,
LAST_RECT) or just advertise a capability with no rectangle payload of
their own (FENCE, CONTINUOUS_UPDATES, XVP, EXTENDED_CLIPBOARD).
"""
#: Tight encoding (BasicCompression/FillCompression/JpegCompression).
TIGHT = 7
#: Tight encoding, PNG variant (reuses the Tight decoder as-is).
TIGHT_PNG = -260
#: ZRLE encoding.
ZRLE = 16
#: ZYWRLE encoding (17). On the wire this is the ZRLE format (message-type
#: 16 sub-stream shape -- 4-byte zlib length then TRLE-style tiles through
#: the same zlib context): the "ZYWRLE" part is a server-side-only lossy
#: wavelet preprocessing step applied to pixel data *before* the ordinary
#: ZRLE/TRLE tile encoder runs (Hitachi's algorithm, see QEMU's
#: `ui/vnc-enc-zywrle-template.c`). The original hypothesis here was that
#: this meant no client-side decode changes were needed at all -- **real
#: testing 2026-09-09 against a real QEMU 8.2.2 server disproves that**:
#: once QEMU's lossy wavelet path actually engages (`-vnc :N,lossy=on`
#: plus a jpeg_quality < 9), it sends tile subencoding byte values in the
#: 17-126 range, which rfbproto.rst/RFC 6143 both reserve as "unused" (no
#: packed-palette bit-width is defined above size 16) -- this fork's
#: TRLE/ZRLE decoder correctly raises ValueError on that range rather
#: than guess at an undocumented tile format. Two candidate guesses at
#: the real format (palette + 1-byte-per-pixel indices; a couple of
#: bit-packing width variants) were tried against the live server and
#: neither produced a coherent image -- see
#: docs/sessions/session-11-2026-09-09.md for the full trace. Net
#: result: Enc.ZYWRLE decodes correctly for any *standard* ZRLE-shaped
#: rectangle (confirmed: subencodings 0/1/2-16/127/128/130-255 all work,
#: same code as Enc.ZRLE -- see Video.read()), but a real QEMU server
#: with its lossy path actually engaged WILL eventually send a rectangle
#: this fork cannot decode. Deliberately excluded from Enc.default() --
#: see Enc.default() -- opt-in only, and only recommended today against
#: a server confirmed to encode ZYWRLE within the documented subencoding
#: range (untested; TigerVNC/Xvnc 1.13.1 doesn't implement ZYWRLE at
#: all, confirmed the same day -- see docs/features-backlog.md).
ZYWRLE = 17
#: TRLE encoding.
TRLE = 15
#: Raw encoding with zlib compession.
ZLIB = 6
#: Hextile encoding.
HEXTILE = 5
#: zlib-compressed Hextile encoding (LibVNCServer/x11vnc).
ZLIBHEX = 8
#: Ultra encoding (9, UltraVNC/LibVNCServer) : en-tête U32 (taille
#: compressée) puis les pixels bruts du rectangle compressés en LZO1X
#: (`lzo1x_1_compress`, voir `src/libvncserver/ultra.c`). Décodé par
#: `_lzo1x_decompress()`, pur Python. Vérifié 2026-10-10 contre un vrai
#: x11vnc 0.9.17 (issue #24) : image 640x480 identique au Raw, 10
#: rectangles Ultra en ~0,2 s. Exclu de Enc.default() (opt-in) : seule
#: LibVNCServer a été testée, pas UltraVNC lui-même (Windows).
ULTRA = 9
#: CoRRE encoding (Compact RRE -- rectangles limités à 255x255).
CORRE = 4
#: RRE encoding (Rise-and-Run-length Encoding).
RRE = 3
#: CopyRect encoding.
COPY = 1
#: Raw encoding.
RAW = 0
#: Rich Cursor pseudo-encoding: client-side cursor rendering.
CURSOR = -239
#: X Cursor pseudo-encoding: older/simpler cousin of CURSOR.
X_CURSOR = -240
#: Cursor With Alpha pseudo-encoding: true per-pixel alpha, no bitmask.
CURSOR_WITH_ALPHA = -314
#: DesktopSize pseudo-encoding: server-initiated framebuffer resize.
DESKTOP_SIZE = -223
#: ExtendedDesktopSize pseudo-encoding: resize + multi-screen layout.
EXTENDED_DESKTOP_SIZE = -308
#: LastRect pseudo-encoding: marks the end of an update of unknown rectangle count.
LAST_RECT = -224
#: Fence pseudo-encoding: enables the ClientFence/ServerFence messages.
FENCE = -312
#: ContinuousUpdates pseudo-encoding: enables streaming without polling.
CONTINUOUS_UPDATES = -313
#: xvp pseudo-encoding: enables the xvp Client/Server Messages (remote
#: shutdown/reboot/reset of the system whose framebuffer we're viewing).
XVP = -309
#: Extended Clipboard pseudo-encoding (0xC0A1E5CE as signed S32): switches
#: ClientCutText/ServerCutText (message-types 6/3) to a signed-length
#: format that, on a negative length, carries a UTF-8-capable
#: Caps/Request/Peek/Notify/Provide envelope instead of plain Latin-1 text
#: (rfbproto.rst "Extended Clipboard Pseudo-Encoding"; see
#: CLIPBOARD_FORMAT_*/CLIPBOARD_ACTION_* below, Client.process_extended_clipboard()
#: and Client.send_clipboard_*()). Safe to advertise by default like
#: Enc.XVP above -- a server that doesn't recognise this pseudo-encoding
#: just ignores it per spec (confirmed 2026-09-13 by reading QEMU's own
#: SetEncodings dispatch, ui/vnc.c: an unrecognised encoding value simply
#: doesn't match any case and is skipped). **2026-09-13 : tested for
#: real** against both a real TigerVNC/Xvnc 1.13.1 (the extension's
#: originating implementation) and a real QEMU 8.2.2 -- see
#: docs/features-backlog.md and docs/sessions/session-14-2026-09-13.md.
#: Only the *text* format (UTF-8) is decoded/encoded by this fork --
#: rtf/html/dib/files are correctly skipped over on receive (so the
#: stream never desyncs) but their content is discarded, not implemented.
EXTENDED_CLIPBOARD = (
-1063131698
) # 0xC0A1E5CE as S32 -- verified against rfbproto.rst + QEMU/TigerVNC sources
@classmethod
def default(cls):
"""
Get a list of supported encodings expect RAW.
Enc.ZYWRLE (17) is deliberately excluded here -- opt-in only via
EncList([...]) + Enc.ZYWRLE or EncList() + Enc.ZYWRLE. See the
Enc.ZYWRLE docstring: real testing (2026-09-09) against a real
QEMU 8.2.2 server found that its ZYWRLE encoder sends tile
subencoding byte values in the 17-126 range that rfbproto.rst/RFC
6143 both explicitly reserve as "unused" -- this fork's TRLE/ZRLE
decoder correctly refuses to decode those (ValueError) rather than
guess at an undocumented format and risk silently corrupting the
image. Advertising ZYWRLE by default would make a plain ZRLE-only
connection to such a server crash the moment the server's lossy
heuristics kick in (quality<9 with lossy=on) -- entirely outside
the caller's control once negotiated.
Enc.ULTRA (9) est exclu aussi, pour une autre raison : seul le
serveur LibVNCServer a été testé, pas UltraVNC (voir Enc.ULTRA).
"""
return filter(lambda x: x.value not in (0, cls.ZYWRLE.value, cls.ULTRA.value), cls)
class EncList(list):
"""
A list of Supported encodings and the simple operations:
"-" -- Exclude from the list
"+" -- Add to list or rise priority
EncList() -- default encoding list
EncList(Enc.ZLIB) -- encoding list with one encoding
EncList([Enc.ZLIB,Enc.TRLE]) -- encoding list with two encodings
EncList() - Enc.ZLIB -- default encoding list except Enc.ZLIB
EncList() + Enc.ZLIB -- default encoding list with hi-priority of Enc.ZLIB
"""
def __init__(self, iterable=None):
if iterable is None:
super().__init__(Enc.default())
return
super().__init__([])
if isinstance(iterable, Enc):
iterable = [iterable]
try:
for x in iterable:
if isinstance(x, Enc):
if x not in self:
self.append(x)
else:
raise TypeError
except TypeError:
raise TypeError('Arg must be one of the None or the Enc or the iterable of Enc')
def __add__(self, other):
if isinstance(other, Enc):
return EncList([other, *self])
return EncList([*other, *self])
def __sub__(self, other):
if isinstance(other, Enc):
other = [other]
a = filter(lambda x: x not in other, self)
return EncList(a)
async def read_int(reader: StreamReader, length: int) -> int:
"""
Reads, unpacks, and returns an integer of *length* bytes.
"""
return int.from_bytes(await reader.readexactly(length), 'big')
async def read_text(reader: StreamReader, encoding: str) -> str:
"""
Reads, unpacks, and returns length-prefixed text.
"""
length = await read_int(reader, 4)
data = await reader.readexactly(length)
return data.decode(encoding)
def pack_ard(data):
encoded = data.encode('utf-8')
if len(encoded) > 63:
raise ValueError(
f'Identifiant/mot de passe Apple ARD trop long : {len(encoded)} '
f'octets UTF-8 (63 maximum, terminateur nul compris dans les 64 '
f'octets du champ protocolaire)'
)
data = encoded + b'\x00'
data += urandom(64 - len(data))
return data
def _pack_mslogonii_field(data: str, field_size: int, what: str) -> bytes:
"""
Encode un champ nom d'utilisateur/mot de passe MSLogonII (security type
113) : UTF-8, terminateur nul, complété par des octets aléatoires
jusqu'à *field_size* -- rfbproto.rst, section "MSLogonII
Authentication" ("Both fields should be encoded using UTF-8, NULL
terminated and padded with random data so the length of each is 256
and 64 bytes respectively"). Même motif que pack_ard() ci-dessus
(Apple ARD), avec des tailles de champ différentes.
"""
encoded = data.encode('utf-8')
if len(encoded) > field_size - 1:
raise ValueError(
f'{what} MSLogonII trop long : {len(encoded)} octets UTF-8 '
f'({field_size - 1} maximum, terminateur nul compris dans les '
f'{field_size} octets du champ protocolaire)'
)
data = encoded + b'\x00'
data += urandom(field_size - len(data))
return data
async def _sasl_negotiate(
reader: StreamReader, writer: StreamWriter, username: str | None, password: str | None
) -> None:
"""
Négocie l'authentification SASL (security type 20, rfbproto.rst section
"SASL") pour les mécanismes ``PLAIN`` (RFC 4616) et ``ANONYMOUS``
(RFC 4505) uniquement.
Contrairement au reste des types de sécurité de ce fichier, SASL n'est
*pas* un format binaire figé mais une correspondance de RFC 2222 dans le
protocole RFB, où la charge utile opaque (*clientout-data*/
*serverout-data*) est en principe produite par un appel à une
bibliothèque tierce (`cyrus-sasl`, via `sasl_client_start`/
`sasl_client_step`). Le tramage sur le fil lui-même (longueurs U32,
séquence mechlist -> client-start -> [server-start ->
client-step -> server-step]* -> SecurityResult) est en revanche
entièrement documenté indépendamment de cette bibliothèque -- voir
`rfbproto.rst`, section "SASL". Seuls PLAIN et ANONYMOUS sont
implémentés ici, en clair, sans aucune dépendance supplémentaire : ce
sont les deux mécanismes SASL les plus simples possibles, chacun
intégralement défini par sa propre RFC autonome (pas de défi du
serveur, un seul aller-retour). Tout autre mécanisme
(`DIGEST-MD5`/`GSSAPI`/`CRAM-MD5`/etc.) nécessiterait une vraie
bibliothèque SASL (et souvent une infrastructure Kerberos pour
`GSSAPI`) -- refusé explicitement ici plutôt que deviné, même principe
que pour ZYWRLE (subencodings 17-126) et le type de sécurité 18 isolé
(voir `docs/features-backlog.md`).
Ni PLAIN ni ANONYMOUS ne négocient de couche de confidentialité/
intégrité (SSF, "security strength factor") au sens de RFC 4422 -- le
SSF de ces deux mécanismes est nul par construction. Il n'y a donc
jamais, pour ces deux mécanismes précisément, de `sasl_encode`/
`sasl_decode` à appliquer aux messages RFB qui suivent le
`SecurityResult` : ce n'est pas une limite de cette implémentation,
c'est une propriété des mécanismes eux-mêmes.
**Testé contre un vrai QEMU 10.2 le 2026-10-10 (issue #32)**, PLAIN
avec une base sasldb, via le sous-type VeNCrypt X509SASL (263) : seul
chemin où QEMU propose PLAIN (voir la ConnectionError ci-dessous et
`test_live_qemu_sasl.py`). Connexion et capture réussies ; mauvais mot de
passe et utilisateur inconnu : connexion fermée par QEMU, remontée en
PermissionError. ANONYMOUS n'est proposé par QEMU dans aucun mode
(SASL_SEC_NOANONYMOUS hors X509SASL ; en X509SASL, dépend de la
configuration Cyrus) : non vérifié contre un serveur réel.
"""
try:
mechlist_length = await read_int(reader, 4)
except IncompleteReadError as exc:
# Vu contre un vrai QEMU 10.2 (2026-10-10, issue #32) : sans aucun
# mécanisme utilisable, il ferme la connexion au lieu d'envoyer une
# liste vide (trace : « no available SASL mechanisms »). Hors
# VeNCrypt X509SASL (et socket Unix), QEMU exige un mécanisme qui
# chiffre lui-même (min_ssf=56, NOPLAINTEXT, NOANONYMOUS) : PLAIN et
# ANONYMOUS sont retirés en SASL seul **et** en TLSSASL (TLS anonyme).
raise ConnectionError(
'SASL: le serveur a fermé la connexion avant la liste des mécanismes '
"(aucun mécanisme commun ? QEMU ne propose PLAIN/ANONYMOUS qu'en "
'VeNCrypt X509SASL : tls-creds-x509 + sasl=on)'
) from exc
mechlist = (await reader.readexactly(mechlist_length)).decode('ascii')
mechanisms = set(mechlist.split(',')) if mechlist else set()
if not mechanisms:
# QEMU 4.2 (vérifié 2026-10-11) envoie une liste vide là où QEMU 10
# ferme la connexion (voir ci-dessus) : même cause, même conseil.
raise ValueError(
'SASL: server offered no mechanisms (QEMU ne propose PLAIN/ANONYMOUS '
"qu'en VeNCrypt X509SASL : tls-creds-x509 + sasl=on)"
)
if 'PLAIN' in mechanisms and username is not None and password is not None:
# RFC 4616 : authzid NUL authcid NUL passwd -- authzid vide (on
# n'autorise pas à agir pour une identité distincte de authcid).
chosen_mechanism = 'PLAIN'
clientout = b'\x00' + username.encode('utf-8') + b'\x00' + password.encode('utf-8')
elif 'ANONYMOUS' in mechanisms:
# RFC 4505 : message optionnel ("trace information", p.ex. une
# adresse mail ou un identifiant informel) -- le nom d'utilisateur
# fourni sert de trace s'il y en a un, sinon message vide (les deux
# sont valides selon la RFC).
chosen_mechanism = 'ANONYMOUS'
clientout = (username or '').encode('utf-8')
else:
raise ValueError(
f'SASL: aucun mécanisme pris en charge parmi {sorted(mechanisms)} '
'(seuls PLAIN et ANONYMOUS sont implémentés ici -- les autres '
'nécessiteraient une vraie bibliothèque SASL)'
)
mechname = chosen_mechanism.encode('ascii')
# "If clientout-data is non-NULL, it should be extended by a single NUL
# byte" -- clientout construit ci-dessus n'est jamais None (toujours au
# moins b'' pour ANONYMOUS sans nom d'utilisateur), donc toujours
# complété d'un octet NUL.
clientout_padded = clientout + b'\x00'
writer.write(
len(mechname).to_bytes(4, 'big')
+ mechname
+ len(clientout_padded).to_bytes(4, 'big')
+ clientout_padded
)
try:
serverout_length = await read_int(reader, 4)
except IncompleteReadError as exc:
# QEMU (vérifié 2026-10-10) refuse un mauvais mot de passe ou un
# utilisateur inconnu en fermant la connexion, sans SecurityResult.
raise PermissionError(
f'SASL {chosen_mechanism}: authentification refusée (connexion fermée par le serveur)'
) from exc
await reader.readexactly(serverout_length) # serverout-data, ignorée (voir docstring)
complete_flag = await read_int(reader, 1)
if complete_flag != 1:
# PLAIN et ANONYMOUS sont tous deux des mécanismes à une seule
# étape (RFC 4616/4505 : aucun défi du serveur) -- un
# complete-flag à 0 ici indiquerait un serveur attendant une étape
# SASL client-step supplémentaire non prévue par ces deux
# mécanismes et non implémentée ici, plutôt que de deviner un
# échange non documenté pour ce cas.
raise ValueError(
f'SASL: échange multi-étapes inattendu pour {chosen_mechanism} '
'(seuls PLAIN/ANONYMOUS en une étape sont pris en charge ici)'
)
# VeNCrypt (security type 19) sub-types, per the only formal spec that was
# ever written for this extension (obtained directly from the original
# VeNCrypt implementation, published on the tigervnc-rfbproto mailing list --
# https://www.mail-archive.com/tigervnc-rfbproto@lists.sourceforge.net/msg00256.html --
# this text never made it into an RFC, but the "Plain subtype" wire format
# below *is* documented in rfbproto.rst itself, section "VeNCrypt", which
# this fork also cross-checked) -- this text never made it into an RFC or
# into rfbproto.rst itself for the None/Vnc families, but it is the same
# document TigerVNC's own CSecurityVeNCrypt.cxx implements against.
#
# Six sub-types are implemented here, in three families, crossed with two
# encryption tiers (TLS.../X509...):
# - TLSNone/TLSVnc ("anonymous" TLS): the server presents a self-signed/
# ephemeral certificate that this client deliberately does not attempt to
# validate (see _vencrypt_negotiate below) -- that lack of validation *is*
# the whole meaning of "anonymous" here, matching the "TLS anonyme" wording
# used for this feature in features.md.
# - X509None/X509Vnc (added 2026-09-05): the server instead presents a real
# CA-signed certificate that this client *does* validate against a trust
# store -- by default the system trust store (`ssl.create_default_context()`,
# the same default a browser or `requests`/`httpx` would use), or an
# explicit CA supplied by the caller via `ssl_context` (e.g. an internal/
# private CA). This is what features.md used to describe as "would need a
# way for the caller to supply a CA certificate, which nothing here
# currently plumbs through" -- that plumbing is `ssl_context` itself
# (already threaded through `connect()`/`listen()`/`Client.create()` for
# TLSNone/TLSVnc) plus the new `server_hostname` parameter below, needed
# because `loop.start_tls()` refuses to check a certificate's hostname
# without being told what hostname to check it against.
# - TLSPlain/X509Plain (added 2026-09-14): a third, orthogonal suffix --
# after the TLS/X509 handshake, the client sends a username and password
# as plain length-prefixed byte strings (rfbproto.rst "Plain subtype";
# cross-checked against TigerVNC's own client, CSecurityPlain.cxx --
# identical field order and U32 lengths). Reuses the existing `username`/
# `password` parameters already accepted by `Client.create()` for Apple
# authentication (type 33) above -- no new parameter needed. Encoded as
# UTF-8: unlike VNC Authentication's DES challenge-response (Latin-1,
# truncated to 8 bytes -- see the dedicated comment on that block), Plain
# has no such cryptographic key-size constraint, so the modern, unambiguous
# choice is used instead, matching how this fork already encodes Extended
# Clipboard text.
#
# In all three families, "None" means no further authentication after the
# TLS handshake (the SecurityResult below concludes the negotiation
# directly), "Vnc" means standard VNC Authentication is layered on top, now
# running over the encrypted stream instead of the underlying algorithm
# changing, and "Plain" means the username/password exchange above instead.
_VENCRYPT_TLS_NONE = 257
_VENCRYPT_TLS_VNC = 258
_VENCRYPT_TLS_PLAIN = 259
_VENCRYPT_X509_NONE = 260
_VENCRYPT_X509_VNC = 261
_VENCRYPT_X509_PLAIN = 262
# Sous-types SASL (2026-10-10, issue #32) : TLS (anonyme) ou X509, puis la
# négociation SASL du type de sécurité 20 (_sasl_negotiate) sur le flux
# chiffré. Numéros d'après QEMU (ui/vnc.h : VNC_AUTH_VENCRYPT_X509SASL = 263,
# VNC_AUTH_VENCRYPT_TLSSASL = 264). C'est la seule façon d'obtenir PLAIN
# d'un vrai QEMU : sans TLS, QEMU exige un mécanisme SASL qui chiffre
# lui-même (SSF >= 56, ex. DIGEST-MD5) et retire PLAIN de sa liste.
_VENCRYPT_X509_SASL = 263
_VENCRYPT_TLS_SASL = 264
async def _start_tls_client(
reader: StreamReader,
writer: StreamWriter,
ssl_context: ssl.SSLContext,
server_hostname: str | None = None,
) -> tuple[StreamReader, StreamWriter]:
"""
Upgrades an already-connected plain-TCP asyncio stream pair to TLS, in
place. Needed for the VeNCrypt security type (see _vencrypt_negotiate),
which multiplexes: ProtocolVersion and the VeNCrypt version/sub-type
negotiation itself happen in clear, then everything from that point on
(including the rest of the security handshake) must go over TLS on the
*same* TCP connection -- there is no separate port or new connection.
asyncio has no public "StreamWriter.start_tls()"; the documented way to
upgrade an existing connection is `loop.start_tls()`, which swaps the
transport under an existing protocol instance in place. The StreamReader
keeps working unmodified afterwards -- `loop.start_tls()` internally
calls `protocol.connection_made(new_transport)`, and
`StreamReaderProtocol.connection_made()` reacts to that by calling
`self._stream_reader.set_transport(new_transport)` on the very same
StreamReader object we already have. Only the StreamWriter needs to be
rebuilt: it binds to a specific transport at construction time and has
no way to swap it out itself, so a fresh StreamWriter is constructed
around the new (TLS) transport instead, reusing the same reader,
protocol and event loop.
*server_hostname* (added for the X509None/X509Vnc VeNCrypt sub-types,
see _vencrypt_negotiate) is forwarded as-is to `loop.start_tls()`, used
to check the hostname/IP on the certificate the server presents --
meaningful whenever `ssl_context.check_hostname` is true, which is the
default for `ssl.create_default_context()` used below for X509None/
X509Vnc. Passing `None` here (as `listen()` does, see its own
docstring) does NOT raise, even with `check_hostname` true: verified by
real execution in this sandbox that asyncio's `loop.start_tls()`
(`SSLContext.wrap_bio()` under the hood) silently skips the hostname
check in that case instead of raising -- unlike the synchronous
`SSLContext.wrap_socket()` API, which does raise
`ValueError("check_hostname requires server_hostname")` in the same
situation (a genuinely different code path; the naive assumption that
asyncio would raise the same error was wrong and corrected in this
session, see CLAUDE.md). Certificate CHAIN verification against the
trust store still applies regardless of `server_hostname` -- only the
hostname-matching step is affected. Harmless to pass a real hostname
for TLSNone/TLSVnc, where the default anonymous context explicitly
disables check_hostname anyway; if a caller supplies their own
ssl_context for those sub-types with check_hostname enabled instead,
forwarding it here is the correct behaviour too, not just a no-op.
"""
loop = get_running_loop()
transport = writer.transport
protocol = transport.get_protocol()
new_transport = await loop.start_tls(
transport, protocol, ssl_context, server_side=False, server_hostname=server_hostname
)
new_writer = StreamWriter(new_transport, protocol, reader, loop)
return reader, new_writer
async def _vencrypt_negotiate(
reader: StreamReader,
writer: StreamWriter,
ssl_context: ssl.SSLContext | None,
server_hostname: str | None = None,
) -> tuple[StreamReader, StreamWriter, int]:
"""
Runs the VeNCrypt (security type 19) version and sub-type negotiation,
then upgrades the connection to TLS and returns the new (reader, writer)
pair together with the sub-type that was selected -- the caller
(Client.create()) still has to finish authentication itself for the
"Vnc" sub-types (by falling through into the existing VNC Authentication
block over the now-encrypted stream) and the "Plain" sub-types (by
sending a username/password directly, see the comment above
_VENCRYPT_TLS_NONE) and, either way, to read the final SecurityResult
the same as for any other RFB 3.7/3.8 security type.
Byte format verified against the only formal VeNCrypt specification that
exists -- see the comment above _VENCRYPT_TLS_NONE for the source -- not
from memory. Only version 0.2 of the extension is implemented (0.1 was
never documented and, per that same spec author, no known VNC
implementation was ever found that supports 0.1 but not 0.2).
*server_hostname* is the hostname/IP the caller believes it is talking
to (typically the same `host` passed to `connect()`) -- only meaningful
for the X509None/X509Vnc/X509Plain sub-types added 2026-09-05/2026-09-14,
see below and the comment above _VENCRYPT_TLS_NONE. Ignored (well,
harmlessly forwarded) for TLSNone/TLSVnc/TLSPlain.
Sub-type preference order when several are offered: X509Vnc, X509Plain,
X509None, TLSVnc, TLSPlain, TLSNone -- real certificate validation
(X509*) is preferred over anonymous TLS (TLS*), and within each family,
requiring further authentication ("Vnc" or "Plain") is preferred over no
further authentication at all ("None"), same reasoning as the
pre-existing outer `for auth_type in (33, 1, 2, 19)` preference a few
lines up in Client.create(). Between "Vnc" and "Plain", "Vnc" is
preferred: VNC Authentication's DES challenge-response never puts the
actual password on the wire (even the now-encrypted one), whereas
"Plain" sends it directly -- safe once TLS/X509 is already established,
but a passive TLS-terminating intermediary (a corporate proxy, say)
would see it in the clear where it would not for "Vnc". A server
offering only a subset of these six behaves exactly as before this
session -- this ordering is a pure addition, not a change to any
previous choice.
TLSNone/TLSVnc: only tested in this sandbox against a hand-written fake
VeNCrypt server over a real loopback TLS socket (see CLAUDE.md) --
**tested for real against TigerVNC/Xvnc on 2026-09-08**, see the
dedicated VeNCrypt row in features-backlog.md.
X509None/X509Vnc (added 2026-09-05): same hand-written-fake-server
loopback methodology, this time with a real two-tier CA/server
certificate chain generated with `openssl` in this sandbox, covering
both a successful connection (client trusts the CA that signed the
server certificate) and a rejected one (client trusts an unrelated CA
instead -- confirms real validation actually happens, unlike TLSNone/
TLSVnc above). **Tested for real against TigerVNC/Xvnc on 2026-09-08**,
see features-backlog.md.
TLSPlain/X509Plain (added 2026-09-14): **tested for real against
TigerVNC/Xvnc 1.13.1 from the start** (a real Linux user + PAM `vnc`
service configured in this sandbox specifically for this test, since
TigerVNC's `SSecurityPlain` delegates password verification to PAM/
Windows and refuses to run at all without one) -- see
docs/sessions/session-16-2026-09-14.md for the full method. Correct
username/password: connection succeeds end-to-end. Wrong password:
a real `rfb::AuthFailureException` from the server, surfaced here as
the existing SecurityResult failure-reason path (unchanged code).
"""
server_major = await read_int(reader, 1)
server_minor = await read_int(reader, 1)
if server_major != 0 or server_minor < 2:
raise ValueError(
f'unsupported VeNCrypt version offered by server: {server_major}.{server_minor}'
)
writer.write(bytes([0, 2]))
if await read_int(reader, 1) != 0:
raise ValueError('server rejected VeNCrypt version 0.2')
n_subtypes = await read_int(reader, 1)
if n_subtypes == 0:
raise ValueError('server advertised no VeNCrypt sub-types')
raw_subtypes = await reader.readexactly(4 * n_subtypes)
subtypes = [
int.from_bytes(raw_subtypes[i : i + 4], 'big') for i in range(0, len(raw_subtypes), 4)
]
for candidate in (
_VENCRYPT_X509_VNC,
_VENCRYPT_X509_PLAIN,
_VENCRYPT_X509_SASL,
_VENCRYPT_X509_NONE,
_VENCRYPT_TLS_VNC,
_VENCRYPT_TLS_PLAIN,
_VENCRYPT_TLS_SASL,
_VENCRYPT_TLS_NONE,
):
if candidate in subtypes:
chosen = candidate
break
else:
raise ValueError(
f'unsupported VeNCrypt sub-types offered by server: {subtypes} (only '
f'TLSNone/TLSVnc/TLSPlain/TLSSASL/X509None/X509Vnc/X509Plain/X509SASL '
f'are implemented)'
)
writer.write(chosen.to_bytes(4, 'big'))
# Point de divergence réel entre sources trouvé et corrigé dans cette
# session : le tout premier brouillon de spec VeNCrypt (mailing-list
# tigervnc-rfbproto, 2010, cité plus haut) décrivait ici un U32 de
# statut (0=OK) suivi, en cas d'échec, d'une chaîne de raison
# longueur-préfixée -- mais ni la spec communautaire actuelle
# (rfbproto.rst, section VeNCrypt/"Subtypes with TLS or X509 prefix")
# ni l'implémentation de référence ne suivent ce format : TigerVNC
# (`CSecurityTLS::processMsg()`, `common/rfb/CSecurityTLS.cxx`) lit un
# unique octet U8 et lève une erreur seulement s'il vaut 0 -- aucune
# chaîne de raison n'est lue. C'est ce format à un octet qui est
# implémenté ci-dessous ; l'ancien format U32+raison aurait
# désynchronisé la lecture d'un octet dès la première connexion à un
# vrai serveur (lu comme les 3 premiers octets de la poignée de main
# TLS elle-même).
if await read_int(reader, 1) == 0:
raise ValueError('server failed to set up VeNCrypt TLS (TLS session initialisation failed)')
if ssl_context is None:
if chosen in (
_VENCRYPT_X509_NONE,
_VENCRYPT_X509_VNC,
_VENCRYPT_X509_PLAIN,
_VENCRYPT_X509_SASL,
):
# X509None/X509Vnc/X509Plain: the server presents a
# real CA-signed certificate, unlike TLSNone/TLSVnc below --
# this is exactly the "X509" prefix's meaning. The safe default
# is therefore to actually verify it, against the system trust
# store, the same default a browser or `requests`/`httpx` would
# use -- not to silently disable verification as done for the
# anonymous sub-types just below.
#
# A caller whose server uses a private/internal CA (the common
# case in practice: publicly-trusted CAs essentially never
# certify VNC endpoints) needs to supply their own ssl_context,
# e.g.:
# ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
# ctx.load_verify_locations(cafile='ma-ca-interne.pem')
# await connect(host, ssl_context=ctx)
# Passing an explicit ssl_context always takes priority over
# this default, exactly as it already did for TLSNone/TLSVnc.
ssl_context = ssl.create_default_context()
else:
# TLSNone/TLSVnc are the "anonymous" VeNCrypt sub-types: the
# server presents a self-signed/ephemeral certificate that
# there is, by construction, no CA to validate it against --
# that lack of validation *is* what "anonymous" means here, as
# opposed to the X509None/X509Vnc sub-types just above, which do
# carry a real, verifiable certificate. Disabling verification
# is therefore the correct default for these two sub-types
# specifically, not a careless bypass -- a caller who wants
# strict verification instead can always pass their own
# ssl_context (which is exactly what selects X509None/X509Vnc's
# verifying behaviour above, if the server also offers one of
# those two).
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
# 2026-09-07, trouve par test reel contre un vrai serveur
# TigerVNC (Xvnc, backend GnuTLS) : le contexte ci-dessus,
# jusque-la, ne suffisait PAS a etablir une session TLSNone/
# TLSVnc contre ce serveur reel -- echec immediat cote serveur
# ("TLS Handshake failed: Insufficient credentials for that
# request."), alors que le meme code fonctionnait contre un
# faux serveur fabrique a la main lors de la verification du
# 2026-09-02. Cause reelle : TigerVNC/GnuTLS implemente ces
# deux sous-types "anonymes" avec de vraies suites Diffie-
# Hellman anonymes (ADH/AECDH, aucun certificat echange du
# tout), alors que le faux serveur de test utilisait un
# certificat auto-signe avec des suites authentifiees
# normales (CERT_NONE cote client desactive juste la
# *verification* du certificat, ce qui est different d'une
# suite reellement anonyme) -- deux implementations
# differentes d'"anonyme" au sens VeNCrypt du terme.
# OpenSSL 1.1.0+ retire les suites anonymes de sa liste de
# suites par defaut (SECLEVEL 1 les exclut deja) ; sans
# reactivation explicite, aucune suite commune n'existe entre
# ce client et un serveur qui n'offre QUE de l'anonyme reel --
# confirme en forcant manuellement `set_ciphers('ADH:AECDH:'
# '@SECLEVEL=0')` + `maximum_version = TLSv1_2` (les suites
# anonymes n'existent pas en TLS 1.3, protocole qui les a
# retirees structurellement) : la connexion contre le meme
# Xvnc reussit alors. Mais reactiver les suites anonymes ne
# suffit pas a lui seul : `'DEFAULT:ADH:AECDH:@SECLEVEL=0'`
# (suites anonymes ajoutees APRES la liste par defaut, pour ne
# pas casser la non-regression contre un serveur qui
# presenterait un certificat auto-signe avec des suites
# authentifiees normales -- exactement le scenario deja
# verifie le 2026-09-02) echoue tout aussi silencieusement que
# l'absence totale de suites anonymes. Diagnostic par
# bissection (`SSLContext.get_ciphers()` sur chaque variante,
# plus repetition apres avoir decouvert que TigerVNC blackliste
# temporairement une IP au bout de 5 echecs d'authentification
# -- `-UseBlacklist=0` cote serveur de test le temps du
# diagnostic, pour ne pas fausser les mesures) : la ou
# `'DEFAULT:ADH:AECDH'` echoue, `'ADH:AECDH:DEFAULT'` (memes
# suites, ordre inverse) reussit. Ce n'est donc pas une
# question de PRESENCE des suites anonymes dans la liste, mais
# de leur RANG : `set_ciphers()` restitue une liste ordonnee
# selon l'ordre d'apparition des tokens dans la chaine, et
# GnuTLS (backend de Xvnc) ne semble considerer qu'un prefixe
# de la liste annoncee par le client avant de conclure "No
# supported cipher suites have been found" -- avec `ADH-AES256
# -GCM-SHA384` en position 3 (`'ADH:AECDH:HIGH'`) la connexion
# reussit, avec la meme suite en position 18 (`'ALL:!eNULL'`,
# ordre par defaut d'OpenSSL) elle echoue, a liste de suites
# quasi identique par ailleurs (140 vs 141 entrees). Chaine
# retenue : `'ADH:AECDH:ALL:!eNULL:@SECLEVEL=0'` -- suites
# anonymes placees EN TETE (prioritaires pour un serveur
# anonyme reel comme TigerVNC/GnuTLS), suivies de l'ensemble
# des suites authentifiees normales pour prendre le relais
# face a un serveur (reel ou fabrique a la main) qui
# presenterait un certificat auto-signe avec des suites
# classiques -- verifie sans regression dans les deux sens
# (voir CLAUDE.md, entree du 2026-09-08). `!eNULL` exclut
# uniquement les suites sans chiffrement (le "e" de eNULL) ;
# les suites sans authentification (le "a" de aNULL, ADH/
# AECDH) restent incluses -- seule l'authentification est
# optionnelle ici, pas le chiffrement lui-meme. Un caller qui
# fournit son propre `ssl_context` continue de
# court-circuiter entierement ce bloc, comme avant.
ssl_context.set_ciphers('ADH:AECDH:ALL:!eNULL:@SECLEVEL=0')
ssl_context.maximum_version = ssl.TLSVersion.TLSv1_2
reader, writer = await _start_tls_client(reader, writer, ssl_context, server_hostname)
return reader, writer, chosen
# RSA-AES security types (5=RA2, 129=RA2_256 -- "RSA-AES-256"; rfbproto.rst
# "RSA-AES Security Type"/"RSA-AES-256 Security Type", added by TigerVNC in
# 2022). Unlike VeNCrypt above, this is not a wrapper around TLS: the RSA
# key exchange and the AES-EAX message framing that follows are both
# implemented from scratch here, since nothing in Python's standard library
# or in `cryptography` does either for us the way `ssl`/`start_tls()` does
# for VeNCrypt. Two sibling security types exist for each -- RA2ne/RA2ne_256
# ("only the handshake is encrypted, SecurityResult and everything after
# stays in the clear") and RA2r/RA2r_256 ("a second round of key derivation
# after the credentials, this time over AES-EAX instead of RSA") -- neither
# is implemented here: RA2ne trades away exactly the property that makes
# RA2 worth having in the first place, and RA2r's extra round buys a
# marginal property (forward secrecy for a hypothetical RSA key compromise
# discovered mid-session) at real extra complexity, for a fork that only
# needs to interoperate as a client, not to hedge against every possible
# server hardening choice. Confirmed real values by reading TigerVNC's own
# client, common/rfb/{CSecurityRSAAES.cxx,CSecurityRSAAES.h} and
# common/rdr/{AESInStream,AESOutStream}.cxx (2026-09-15) -- several details
# below (the AES key size actually being 128/256 rather than matching the
# RSA key size, the exact preimage byte layout for the two SHA1/SHA256
# hashes, the credentials format, and the EAX nonce/associated-data
# construction) are not fully pinned down by rfbproto.rst's prose alone and
# were taken from this reference implementation instead.
RSA_AES_MIN_KEY_LENGTH = 1024 # bits; TigerVNC's own client refuses shorter
RSA_AES_MAX_KEY_LENGTH = 8192 # bits; TigerVNC's own client refuses longer
RSA_AES_SUBTYPE_USERPASS = 1 # server wants both username and password
RSA_AES_SUBTYPE_PASS = 2 # server wants only a password
_EAX_TAG_SIZE = 16 # AES block size -- true for EAX regardless of AES-128 vs AES-256
_EAX_MAX_MESSAGE_SIZE = 8192 # matches TigerVNC's AESOutStream::MaxMessageSize exactly
def _omac(key: bytes, tweak: int, message: bytes) -> bytes:
"""
One building block of AES-EAX: CMAC of a single all-zero 16-byte block
with its last byte set to *tweak*, concatenated with *message* --
OMAC_K^tweak(message) in the notation rfbproto.rst itself uses ("N =
OMAC_K^0(Nonce)", etc.). *key* is the raw AES key (16 or 32 bytes).
"""
mac = cmac.CMAC(algorithms.AES(key))
mac.update(bytes(15) + bytes([tweak]) + message)
return mac.finalize()
def _eax_seal(key: bytes, nonce: bytes, header: bytes, plaintext: bytes) -> tuple[bytes, bytes]:
"""
Encrypts *plaintext* with AES-EAX, returning (ciphertext, 16-byte tag).
*nonce* is the 16-byte message counter (see _EAXWriter below), *header*
is the associated data (the 2-byte big-endian length prefix, for this
fork's one and only use of EAX). `cryptography` has no built-in AESEAX
class (unlike AESGCM/AESCCM/AESSIV/AESOCB3/ChaCha20Poly1305 -- checked
2026-09-15), so this rebuilds the construction from CTR mode + CMAC
exactly as the EAX paper defines it and as TigerVNC's own
common/rdr/AESOutStream.cxx does it (via Nettle's EAX macros) --
N=OMAC^0(nonce), H=OMAC^1(header), C=CTR_N(plaintext), tag=N⊕H⊕OMAC^2(C).
"""
n_tag = _omac(key, 0, nonce)
h_tag = _omac(key, 1, header)
encryptor = Cipher(algorithms.AES(key), modes.CTR(n_tag)).encryptor()
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
c_tag = _omac(key, 2, ciphertext)
tag = bytes(a ^ b ^ c for a, b, c in zip(n_tag, h_tag, c_tag))
return ciphertext, tag
def _eax_open(key: bytes, nonce: bytes, header: bytes, ciphertext: bytes, tag: bytes) -> bytes:
"""
Inverse of _eax_seal(): verifies *tag* (constant-time, via
hmac.compare_digest -- TigerVNC's own AESInStream.cxx uses a plain
memcmp() here, but there is no reason for this fork to copy that
particular shortcut when a safer comparison is one import away) and
raises ValueError on mismatch, otherwise returns the decrypted
plaintext.
"""
n_tag = _omac(key, 0, nonce)
h_tag = _omac(key, 1, header)
c_tag = _omac(key, 2, ciphertext)
expected_tag = bytes(a ^ b ^ c for a, b, c in zip(n_tag, h_tag, c_tag))
if not hmac.compare_digest(expected_tag, tag):
raise ValueError(
"AES-EAX : jeton d'authenticité invalide (message corrompu ou mauvaise clé)"
)
decryptor = Cipher(algorithms.AES(key), modes.CTR(n_tag)).decryptor()
return decryptor.update(ciphertext) + decryptor.finalize()
def _eax_increment_counter(counter: bytearray) -> None:
"""
Increments *counter* in place as a 128-bit little-endian unsigned
integer -- the exact scheme rfbproto.rst specifies for the EAX message
index ("16-byte little-endian message index increments from zero"),
confirmed byte-for-byte against TigerVNC's own AESInStream.cxx/
AESOutStream.cxx (both increment the lowest-address byte first,
carrying into the next byte on overflow, stopping at the first byte
that does *not* wrap to 0).
"""
for i in range(16):
counter[i] = (counter[i] + 1) & 0xFF
if counter[i] != 0:
break
class _EAXReader:
"""
Enveloppe un `StreamReader` TCP brut pour déchiffrer et authentifier
chaque message AES-EAX avant de le rendre disponible à `readexactly()`
-- transparent pour tout le reste de ce fichier, qui ne s'en sert que
via cette unique méthode (voir le commentaire au-dessus de
RSA_AES_MIN_KEY_LENGTH pour le format exact et sa source). Contrairement
à `_ws_wrap_connection()` (WebSockets), pas besoin d'une tâche de fond
ni de `feed_data()` : chaque message EAX porte son propre préfixe de
longueur explicite (2 octets), donc un simple aller-retour
`readexactly()` sur le flux brut suffit à en lire un entier avant de le
déchiffrer.
"""
def __init__(self, raw_reader: StreamReader, key: bytes):
self._raw = raw_reader
self._key = key
self._counter = bytearray(16)
self._buffer = b''
async def readexactly(self, n: int) -> bytes:
while len(self._buffer) < n:
self._buffer += await self._read_one_message()
result, self._buffer = self._buffer[:n], self._buffer[n:]
return result
async def _read_one_message(self) -> bytes:
header = await self._raw.readexactly(2)
length = int.from_bytes(header, 'big')
ciphertext_and_tag = await self._raw.readexactly(length + _EAX_TAG_SIZE)
ciphertext, tag = ciphertext_and_tag[:length], ciphertext_and_tag[length:]
plaintext = _eax_open(self._key, bytes(self._counter), header, ciphertext, tag)
_eax_increment_counter(self._counter)
return plaintext
class _EAXWriter:
"""
Enveloppe un `StreamWriter` TCP brut pour que chaque `write()` soit
automatiquement scindé en messages d'au plus `_EAX_MAX_MESSAGE_SIZE`
octets (comme `AESOutStream::MaxMessageSize` côté TigerVNC), chiffrés
et authentifiés en AES-EAX avant d'être réellement écrits sur le
socket -- même principe et même API minimale que `_WebSocketWriter`
ci-dessus (voir sa docstring), mais pour un chiffrement plutôt qu'un
tunnel WebSocket.
"""
def __init__(self, raw_writer: StreamWriter, key: bytes):
self._raw = raw_writer
self._key = key
self._counter = bytearray(16)
def write(self, data: bytes) -> None:
data = bytes(data)
for offset in range(0, len(data), _EAX_MAX_MESSAGE_SIZE):
chunk = data[offset : offset + _EAX_MAX_MESSAGE_SIZE]
header = len(chunk).to_bytes(2, 'big')
ciphertext, tag = _eax_seal(self._key, bytes(self._counter), header, chunk)
self._raw.write(header + ciphertext + tag)
_eax_increment_counter(self._counter)
async def drain(self) -> None:
await self._raw.drain()
def close(self) -> None:
self._raw.close()
async def wait_closed(self) -> None:
await self._raw.wait_closed()