Repository navigation
Expand file tree
/
Copy pathasyncvnc2.py.orig
More file actions
3018 lines (2629 loc) · 134 KB
/
Copy pathasyncvnc2.py.orig
File metadata and controls
3018 lines (2629 loc) · 134 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 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
from itertools import product
from os import urandom
from typing import Dict, List, Optional, Set, Tuple
from zlib import decompressobj
import numpy as np
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).
"""
#: 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
#: 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
@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.
"""
return filter(lambda x: x.value not in (0, cls.ZYWRLE.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
# 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 or into rfbproto.rst itself, but it is
# the same document TigerVNC's own CSecurityVeNCrypt.cxx implements against).
#
# Four sub-types are implemented here, in two families:
# - 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.
#
# In both families, "None" means no further authentication after the TLS
# handshake (the SecurityResult below concludes the negotiation directly),
# and "Vnc" means standard VNC Authentication is layered on top, now running
# over the encrypted stream instead of the underlying algorithm changing.
_VENCRYPT_TLS_NONE = 257
_VENCRYPT_TLS_VNC = 258
_VENCRYPT_X509_NONE = 260
_VENCRYPT_X509_VNC = 261
async def _start_tls_client(reader: StreamReader, writer: StreamWriter,
ssl_context: ssl.SSLContext,
server_hostname: Optional[str] = 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: Optional[ssl.SSLContext],
server_hostname: Optional[str] = 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, 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 sub-types added 2026-09-05, see below and the
comment above _VENCRYPT_TLS_NONE. Ignored (well, harmlessly forwarded)
for TLSNone/TLSVnc.
Sub-type preference order when several are offered: X509Vnc, X509None,
TLSVnc, TLSNone -- real certificate validation (X509*) is preferred over
anonymous TLS (TLS*), and within each family, requiring VNC
Authentication on top ("Vnc") 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(). A server offering only TLSNone/TLSVnc (no X509
sub-type at all) behaves exactly as before this session -- this
ordering is a pure addition, not a change to the previous two-way
choice.
TLSNone/TLSVnc: only tested in this sandbox against a hand-written fake
VeNCrypt server over a real loopback TLS socket (see CLAUDE.md) -- never
against a real server that actually requires VeNCrypt (TigerVNC/RealVNC
Enterprise are the obvious candidates, none available here).
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). Also never tested against a real server.
"""
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_NONE, _VENCRYPT_TLS_VNC, _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/X509None/X509Vnc 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):
# X509None/X509Vnc (added 2026-09-05): 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
@dataclass
class Clipboard:
"""
Shared clipboard.
"""
writer: StreamWriter = field(repr=False)
#: The clipboard text.
text: str = ''
def write(self, text: str):
"""
Sends clipboard text to the server.
"""
data = text.encode('latin-1')
self.writer.write(b'\x06\x00\x00\x00' + len(data).to_bytes(4, 'big') + data)
@dataclass
class Keyboard:
"""
Virtual keyboard.
"""
writer: StreamWriter = field(repr=False)
@contextmanager
def _write(self, key: str):
data = key_codes[key].to_bytes(4, 'big')
self.writer.write(b'\x04\x01\x00\x00' + data)
try:
yield
finally:
self.writer.write(b'\x04\x00\x00\x00' + data)
@contextmanager
def hold(self, *keys: str):
"""
Context manager that pushes the given keys on enter, and releases them (in reverse order) on exit.
"""
with ExitStack() as stack:
for key in keys:
stack.enter_context(self._write(key))
yield
def press(self, *keys: str):
"""
Pushes all the given keys, and then releases them in reverse order.
"""
with self.hold(*keys):
pass
def write(self, text: str):
"""
Pushes and releases each of the given keys, one after the other.
"""
for key in text:
with self.hold(key):
pass
@dataclass
class Mouse:
"""
Virtual mouse.
"""
writer: StreamWriter = field(repr=False)
buttons: int = 0
x: int = 0
y: int = 0
def _write(self):
self.writer.write(
b'\x05' +
self.buttons.to_bytes(1, 'big') +
self.x.to_bytes(2, 'big') +
self.y.to_bytes(2, 'big'))
@contextmanager
def hold(self, button: int = 0):
"""
Context manager that presses a mouse button on enter, and releases it on exit.
"""
mask = 1 << button
self.buttons |= mask
self._write()
try:
yield
finally:
self.buttons &= ~mask
self._write()
def click(self, button: int = 0):
"""
Presses and releases a mouse button.
"""
with self.hold(button):
pass
def middle_click(self):
"""
Presses and releases the middle mouse button.
"""
self.click(1)
def right_click(self):
"""
Presses and releases the right mouse button.
"""
self.click(2)
def scroll_up(self, repeat=1):
"""
Scrolls the mouse wheel upwards.
"""
for _ in range(repeat):
self.click(3)
def scroll_down(self, repeat=1):
"""
Scrolls the mouse wheel downwards.
"""
for _ in range(repeat):
self.click(4)
def move(self, x: int, y: int):
"""
Moves the mouse cursor to the given co-ordinates.
"""
self.x = x
self.y = y
self._write()
@dataclass
class Screen:
"""
Computer screen.
"""
#: Horizontal position in pixels.
x: int
#: Vertical position in pixels.
y: int
#: Width in pixels.
width: int
#: Height in pixels.
height: int
#: Arbitrary server/client-assigned identifier (ExtendedDesktopSize only).
id: int = 0
#: Reserved flags (ExtendedDesktopSize only, currently always 0).
flags: int = 0
@property
def slices(self) -> Tuple[slice, slice]:
"""
Object that can be used to crop the video buffer to this screen.
"""
return slice(self.y, self.y + self.height), slice(self.x, self.x + self.width)
@property
def score(self) -> float:
"""
A measure of our confidence that this represents a real screen. For screens with standard aspect ratios, this
is proportional to its pixel area. For non-standard aspect ratios, the score is further multiplied by the ratio
or its reciprocal, whichever is smaller.
"""
value = float(self.width * self.height)
ratios = {Fraction(self.width, self.height).limit_denominator(64),
Fraction(self.height, self.width).limit_denominator(64)}
if not ratios & screen_ratios:
value *= min(ratios) * 0.5
return value
@dataclass
class Cursor:
"""
Mouse cursor shape received from the server (Rich Cursor / X Cursor / Cursor With Alpha pseudo-encodings).
"""
#: Horizontal hotspot position, relative to the cursor image.
x: int
#: Vertical hotspot position, relative to the cursor image.
y: int
#: Width in pixels.
width: int
#: Height in pixels.
height: int
#: RGBA image data (alpha is real per-pixel alpha, or derived from the server's transparency bitmask).
data: np.ndarray
@dataclass
class StreamZReader:
"""
aio StreamReader wrapper for zlib
"""
reader: StreamReader = field(repr=False)
decompress: object = field(repr=False)
length: int
_head: int = 0
_buffer: bytes = b''
_zbuffer: bytes = b''
async def read(self, n: int =-1) -> bytes:
"""
Read up to a maximum of n bytes.
If n is not provided, or set to -1, read until EOF and return all read bytes.
When n is provided, data will be returned as soon as it is available.
"""
if n == -1:
try:
self._zbuffer += await self.reader.readexactly(self.length)
except IncompleteReadError as e:
self._zbuffer += e.partial
self.length = 0
rdata = self._buffer[self._head:] + self.decompress.decompress(self._zbuffer)
self._buffer = b''
self._head = 0
self._zbuffer = self.decompress.unconsumed_tail
return rdata
if (n <= 0) or ((len(self._buffer) <= self._head) and (self.length <= 0)):
return b''
while (len(self._buffer) == self._head) and (self.length > 0):
ndata = await self.reader.readexactly(self.length)
self.length -= len(ndata)
self._zbuffer += ndata
self._buffer = self.decompress.decompress(self._zbuffer)
self._head = 0
self._zbuffer = self.decompress.unconsumed_tail
rdata = self._buffer[self._head:self._head + n]
self._head += len(rdata)
return rdata
async def readexactly(self, n: int) -> bytes:
"""
Read exactly n bytes.
Raise an asyncio.IncompleteReadError if the end of the stream is reached before n can be read.
"""
data = b''
_n = n
while _n > 0:
ndata = await self.read(_n)
if len(ndata) == 0:
raise IncompleteReadError(data, n)
data += ndata
_n = n - len(data)
return data
def _tile_1d_gen(tw: int, x: int, w: int):
for cx in range(x, x + w - tw + 1, tw):
yield (cx, tw)
mod = w % tw
if mod:
yield (x + w - mod, mod)
def _tile_gen(tw: int, th: int, x: int, y: int, w: int, h: int):
for (cy, ch) in _tile_1d_gen(th, y, h):
for (cx, cw) in _tile_1d_gen(tw, x, w):
yield (cx, cy, cw, ch)
class _BytesReader:
"""
Minimal async-readexactly wrapper over an in-memory buffer, so decompressed
ZlibHex tile data (already fully available) can be fed through the same
tile-body decoder used for plain Hextile (which reads from a live StreamReader).
"""
def __init__(self, data: bytes):
self._data = data
self._pos = 0
async def readexactly(self, n: int) -> bytes:
chunk = self._data[self._pos:self._pos + n]
if len(chunk) < n:
raise IncompleteReadError(chunk, n)
self._pos += n
return chunk
async def _hextile_tile_body(reader, mask: int, bg, fg: bytes, cw: int, ch: int):
"""
Reads a Hextile tile's background/foreground/subrects (everything except the
Raw case, which the caller handles separately since it short-circuits
everything else) and returns (tile_array, new_bg, new_fg).
Shared between process_hextile (reading live from the network) and
process_zlibhex's Zlib-compressed tiles (reading from an already-decompressed
in-memory buffer via _BytesReader) -- both follow identical Hextile rules
once the subencoding byte and a byte source are in hand.
"""
if mask & 2:
bg = await reader.readexactly(4)
if bg is None:
raise ValueError("Hextile: first tile of the rectangle did not specify a background colour")
if mask & 4:
fg = await reader.readexactly(4)
tile = np.ndarray((ch, cw, 4), 'B', bg * (cw * ch)).copy()
if mask & 8:
n = await read_int(reader, 1)
coloured = bool(mask & 16)
for _ in range(n):
colour = (await reader.readexactly(4)) if coloured else fg
pos = await read_int(reader, 1)
size = await read_int(reader, 1)
sx = (pos >> 4) & 0x0F
sy = pos & 0x0F
sw = ((size >> 4) & 0x0F) + 1
sh = (size & 0x0F) + 1
tile[sy:sy + sh, sx:sx + sw, :] = np.ndarray((sh, sw, 4), 'B', colour * (sw * sh))
return tile, bg, fg
async def _rle_len(reader: StreamReader):
_pixels = 0
while True:
n = await read_int(reader, 1)
_pixels += n
if n != 255:
break
return _pixels + 1
async def _update_palette(reader: StreamReader, n: int, palette: Optional[list] = None):
pal_bytes = await reader.readexactly(3*n)
pal_list = [pal_bytes[i:i+3] for i in range(0, 3*n, 3)]
palette.clear()
palette.extend(pal_list)
async def _rle_packedbits(reader: StreamReader, cw: int, ch: int, subencoding: int, palette: list) -> bytes:
frame = b''
if subencoding <= 16:
# subencoding == 2 .. 16
await _update_palette(reader, subencoding, palette)
else:
# subencoding == 127
subencoding = len(palette)
if subencoding == 2:
bits = 1
elif subencoding <= 4:
bits = 2
else:
bits = 4
rowlen = (bits * cw + 7) // 8
mask = (1 << bits) - 1
for _ in range(ch):
row = await reader.readexactly(rowlen)
offset = 0
rowit = iter(row)
for _ in range(cw):
if offset == 0:
offset = 8
packcol = next(rowit)
offset -= bits
frame += palette[(packcol >> offset) & mask]
return frame
async def _rle_rle(reader: StreamReader, cw: int, ch: int, subencoding: int, palette: list) -> bytes:
frame = b''
subencoding -= 128
if subencoding > 1:
await _update_palette(reader, subencoding, palette)
elif subencoding == 1:
subencoding = len(palette)
tile_pixels = ch * cw
pixels = 0
while pixels < tile_pixels:
if subencoding:
pal_index = await read_int(reader, 1)
if pal_index < 128:
frame += palette[pal_index]
pixels += 1
continue
else:
pal_index -= 128
color = palette[pal_index]
else:
color = await reader.readexactly(3)
p = await _rle_len(reader)
frame += color * p
pixels += p
if pixels > tile_pixels:
raise ValueError("Too many pixels")
return frame
async def _tight_read_length(reader: StreamReader) -> int:
"""
Reads a Tight "compact" length (1-3 bytes) and returns it.
"""
b0 = await read_int(reader, 1)
length = b0 & 0x7F
if b0 & 0x80:
b1 = await read_int(reader, 1)
length |= (b1 & 0x7F) << 7
if b1 & 0x80:
b2 = await read_int(reader, 1)