-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrdmon.v
More file actions
902 lines (783 loc) · 25.3 KB
/
rdmon.v
File metadata and controls
902 lines (783 loc) · 25.3 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
module main
import os
import net
import time
import crypto.rand
#include <sodium.h>
#flag -lsodium
const default_server = 'rs-ny.rustdesk.com'
const rendezvous_port = 21116
const online_query_port = 21115 // rendezvous_port - 1
const poll_interval_secs = 60
struct Config {
mut:
server string = default_server
ids []string
with_ip bool
interval int = poll_interval_secs
verbose bool
}
struct PeerState {
mut:
id string
online bool
ip string
last_seen time.Time
}
fn main() {
mut config := parse_args() or {
eprintln(err)
print_usage()
exit(1)
}
if config.ids.len == 0 {
eprintln('Error: No peer IDs specified')
print_usage()
exit(1)
}
println('RustDesk Monitor (rdmon)')
println('========================')
println('Server: ${config.server}:${online_query_port}')
println('Monitoring ${config.ids.len} peer(s): ${config.ids.join(", ")}')
println('IP tracking: ${if config.with_ip { "enabled" } else { "disabled" }}')
println('Poll interval: ${config.interval}s')
if config.verbose {
println('Verbose: enabled')
}
println('------------------------')
println('')
os.flush()
mut states := map[string]PeerState{}
for id in config.ids {
states[id] = PeerState{
id: id
online: false
ip: ''
last_seen: time.Time{}
}
}
// Initial check - report current status
println('Checking initial status...')
os.flush()
check_peers(mut config, mut states, true)
// Main monitoring loop
for {
time.sleep(config.interval * time.second)
check_peers(mut config, mut states, false)
}
}
fn parse_args() !Config {
mut config := Config{}
args := os.args[1..]
mut i := 0
for i < args.len {
arg := args[i]
match arg {
'-h', '--help' {
print_usage()
exit(0)
}
'-s', '--server' {
i++
if i >= args.len {
return error('--server requires an argument')
}
config.server = args[i]
}
'-f', '--file' {
i++
if i >= args.len {
return error('--file requires an argument')
}
ids := load_ids_from_file(args[i])!
config.ids << ids
}
'-i', '--interval' {
i++
if i >= args.len {
return error('--interval requires an argument')
}
config.interval = args[i].int()
if config.interval < 1 {
config.interval = 1
}
}
'--with-ip' {
config.with_ip = true
}
'-v', '--verbose' {
config.verbose = true
}
else {
// Assume it's a peer ID
if !arg.starts_with('-') {
config.ids << arg
} else {
return error('Unknown option: ${arg}')
}
}
}
i++
}
return config
}
fn load_ids_from_file(path string) ![]string {
content := os.read_file(path) or { return error('Cannot read file: ${path}') }
mut ids := []string{}
for line in content.split_into_lines() {
trimmed := line.trim_space()
// Skip empty lines and comments
if trimmed.len > 0 && !trimmed.starts_with('#') {
ids << trimmed
}
}
return ids
}
fn print_usage() {
println('Usage: rdmon [OPTIONS] <peer_id> [peer_id...]')
println('')
println('Options:')
println(' -h, --help Show this help message')
println(' -s, --server HOST RustDesk server (default: ${default_server})')
println(' -f, --file FILE Load peer IDs from file (one per line)')
println(' -i, --interval SEC Poll interval in seconds (default: ${poll_interval_secs})')
println(' --with-ip Enable IP address tracking (may be detectable)')
println(' -v, --verbose Enable verbose/debug output')
println('')
println('Examples:')
println(' rdmon 111111111')
println(' rdmon -f peers.txt --with-ip')
println(' rdmon -s myserver.com 111111111 222222222')
}
fn check_peers(mut config Config, mut states map[string]PeerState, report_all bool) {
// Query online status
online_states := query_online_status(config.server, config.ids) or {
eprintln('[${format_time(time.now())}] Error querying status: ${err}')
os.flush()
return
}
now := time.now()
for id in config.ids {
is_online := online_states[id] or { false }
mut state := states[id] or { continue }
state_changed := is_online != state.online
// Report if state changed or if reporting all (initial check)
if state_changed || report_all {
state.online = is_online
state.last_seen = now
mut ip_info := ''
if config.with_ip && is_online {
ip := get_peer_ip(config.server, id, config.verbose) or { '' }
if ip.len > 0 {
state.ip = ip
ip_info = ' (IP: ${ip})'
}
}
status := if is_online { 'ONLINE' } else { 'OFFLINE' }
println('[${format_time(now)}] ${id}: ${status}${ip_info}')
}
states[id] = state
}
os.flush()
}
fn format_time(t time.Time) string {
return t.format_ss()
}
fn debug(verbose bool, msg string) {
if verbose {
eprintln('[DEBUG] ${msg}')
}
}
// Query online status for multiple peers
fn query_online_status(server string, ids []string) !map[string]bool {
mut sock := net.dial_tcp('${server}:${online_query_port}') or {
return error('Failed to connect to ${server}:${online_query_port}: ${err}')
}
defer {
sock.close() or {}
}
sock.set_read_timeout(10 * time.second)
sock.set_write_timeout(10 * time.second)
// Build and send OnlineRequest
msg := build_online_request('rdmon', ids)
sock.write(msg) or { return error('Failed to send request: ${err}') }
// Read response
response := read_protobuf_message(mut sock) or { return error('Failed to read response: ${err}') }
// Parse OnlineResponse
return parse_online_response(response, ids)
}
// Build protobuf OnlineRequest message
fn build_online_request(my_id string, peer_ids []string) []u8 {
// Build OnlineRequest (field 1 = id, field 2 = peers)
mut online_req := []u8{}
// Field 1: id (string)
online_req << encode_protobuf_string(1, my_id)
// Field 2: peers (repeated string)
for peer_id in peer_ids {
online_req << encode_protobuf_string(2, peer_id)
}
// Wrap in RendezvousMessage (field 23 = online_request)
mut msg := []u8{}
msg << encode_protobuf_bytes(23, online_req)
// RustDesk uses variable-length framing (see bytes_codec.rs)
// Lower 2 bits indicate length encoding: 0=1byte, 1=2bytes, 2=3bytes, 3=4bytes
return encode_frame(msg)
}
// Encode frame with RustDesk's variable-length prefix
fn encode_frame(data []u8) []u8 {
length := u32(data.len)
mut framed := []u8{}
if length <= 0x3F {
// 1 byte: (len << 2) | 0x0
framed << u8(length << 2)
} else if length <= 0x3FFF {
// 2 bytes little-endian: (len << 2) | 0x1
val := u16(length << 2) | 0x1
framed << u8(val & 0xFF)
framed << u8(val >> 8)
} else if length <= 0x3FFFFF {
// 3 bytes: (len << 2) | 0x2
val := u32(length << 2) | 0x2
framed << u8(val & 0xFF)
framed << u8((val >> 8) & 0xFF)
framed << u8((val >> 16) & 0xFF)
} else {
// 4 bytes little-endian: (len << 2) | 0x3
val := u32(length << 2) | 0x3
framed << u8(val & 0xFF)
framed << u8((val >> 8) & 0xFF)
framed << u8((val >> 16) & 0xFF)
framed << u8((val >> 24) & 0xFF)
}
framed << data
return framed
}
// Encode a protobuf string field
fn encode_protobuf_string(field_num int, value string) []u8 {
mut result := []u8{}
// Wire type 2 (length-delimited) = (field_num << 3) | 2
result << encode_varint(u64(u32(field_num) << 3 | 2))
result << encode_varint(u64(value.len))
result << value.bytes()
return result
}
// Encode a protobuf bytes field (for nested message)
fn encode_protobuf_bytes(field_num int, value []u8) []u8 {
mut result := []u8{}
// Wire type 2 (length-delimited) = (field_num << 3) | 2
result << encode_varint(u64(u32(field_num) << 3 | 2))
result << encode_varint(u64(value.len))
result << value
return result
}
// Encode a varint
fn encode_varint(value u64) []u8 {
mut v := value
mut result := []u8{}
for {
mut b := u8(v & 0x7F)
v >>= 7
if v != 0 {
b |= 0x80
}
result << b
if v == 0 {
break
}
}
return result
}
// Read a length-prefixed protobuf message from TCP (RustDesk variable-length framing)
fn read_protobuf_message(mut sock net.TcpConn) ![]u8 {
// Read first byte to determine length encoding
mut first_byte := []u8{len: 1}
sock.read(mut first_byte) or { return error('Failed to read length: ${err}') }
encoding_type := first_byte[0] & 0x03
mut msg_len := u32(0)
match encoding_type {
0 {
// 1 byte length
msg_len = u32(first_byte[0]) >> 2
}
1 {
// 2 bytes little-endian
mut second_byte := []u8{len: 1}
sock.read(mut second_byte) or { return error('Failed to read length: ${err}') }
msg_len = (u32(first_byte[0]) | (u32(second_byte[0]) << 8)) >> 2
}
2 {
// 3 bytes
mut extra_bytes := []u8{len: 2}
sock.read(mut extra_bytes) or { return error('Failed to read length: ${err}') }
msg_len = (u32(first_byte[0]) | (u32(extra_bytes[0]) << 8) | (u32(extra_bytes[1]) << 16)) >> 2
}
else {
// 4 bytes little-endian (encoding_type == 3)
mut extra_bytes := []u8{len: 3}
sock.read(mut extra_bytes) or { return error('Failed to read length: ${err}') }
msg_len = (u32(first_byte[0]) | (u32(extra_bytes[0]) << 8) | (u32(extra_bytes[1]) << 16) | (u32(extra_bytes[2]) << 24)) >> 2
}
}
if msg_len > 65536 {
return error('Message too large: ${msg_len}')
}
if msg_len == 0 {
return []u8{}
}
// Read message body
mut msg_buf := []u8{len: int(msg_len)}
mut total_read := 0
for total_read < int(msg_len) {
n := sock.read(mut msg_buf[total_read..]) or { return error('Failed to read message: ${err}') }
if n == 0 {
return error('Connection closed')
}
total_read += n
}
return msg_buf
}
// Parser state wrapper
struct Parser {
mut:
pos int
}
// Parse OnlineResponse and extract peer states
fn parse_online_response(data []u8, ids []string) !map[string]bool {
mut result := map[string]bool{}
// Find field 24 (online_response) in RendezvousMessage
mut p := Parser{}
for p.pos < data.len {
tag_and_type := decode_varint(data, mut p) or { break }
field_num := int(tag_and_type >> 3)
wire_type := int(tag_and_type & 0x07)
if field_num == 24 && wire_type == 2 {
// Found online_response
length := decode_varint(data, mut p) or { break }
online_resp := data[p.pos..p.pos + int(length)]
// Parse OnlineResponse - find field 1 (states)
mut rp := Parser{}
for rp.pos < online_resp.len {
resp_tag := decode_varint(online_resp, mut rp) or { break }
resp_field := int(resp_tag >> 3)
resp_wire := int(resp_tag & 0x07)
if resp_field == 1 && resp_wire == 2 {
// Found states bytes
states_len := decode_varint(online_resp, mut rp) or { break }
states := online_resp[rp.pos..rp.pos + int(states_len)]
// Decode bitfield
for i, id in ids {
byte_idx := i / 8
if byte_idx < states.len {
bit_value := u8(0x01) << (7 - (i % 8))
is_online := (states[byte_idx] & bit_value) == bit_value
result[id] = is_online
} else {
result[id] = false
}
}
return result
} else {
// Skip this field
skip_field(online_resp, resp_wire, mut rp) or { break }
}
}
break
} else {
// Skip this field
skip_field(data, wire_type, mut p) or { break }
}
}
// If we didn't find the response, assume all offline
for id in ids {
result[id] = false
}
return result
}
// Decode a varint from data at position
fn decode_varint(data []u8, mut p Parser) !u64 {
mut result := u64(0)
mut shift := 0
for {
if p.pos >= data.len {
return error('Unexpected end of data')
}
b := data[p.pos]
p.pos++
result |= u64(b & 0x7F) << shift
if (b & 0x80) == 0 {
break
}
shift += 7
if shift >= 64 {
return error('Varint too long')
}
}
return result
}
// Skip a protobuf field based on wire type
fn skip_field(data []u8, wire_type int, mut p Parser) ! {
match wire_type {
0 {
// Varint
decode_varint(data, mut p)!
}
1 {
// 64-bit
p.pos += 8
}
2 {
// Length-delimited
length := decode_varint(data, mut p)!
p.pos += int(length)
}
5 {
// 32-bit
p.pos += 4
}
else {
return error('Unknown wire type: ${wire_type}')
}
}
}
// Session holds the symmetric key for encrypted communication
struct Session {
symmetric_key []u8
}
// Get peer IP address via PunchHoleRequest (optional, may be detectable)
fn get_peer_ip(server string, peer_id string, verbose bool) !string {
mut sock := net.dial_tcp('${server}:${rendezvous_port}') or {
return error('Failed to connect: ${err}')
}
defer {
sock.close() or {}
}
sock.set_read_timeout(5 * time.second)
sock.set_write_timeout(5 * time.second)
// First check what the server sends on connect
debug(verbose, 'Reading initial message...')
initial := read_protobuf_message(mut sock) or { []u8{} }
if initial.len > 0 {
debug(verbose, 'Initial message: ${initial.len} bytes')
// Check if it looks like a KeyExchange (field 25)
if initial.len > 2 && initial[0] == 0xca && initial[1] == 0x01 {
debug(verbose, 'Server sent KeyExchange, trying encrypted mode...')
return get_peer_ip_encrypted(mut sock, initial, peer_id, verbose)
}
}
// Try sending unencrypted PunchHoleRequest
debug(verbose, 'Trying unencrypted PunchHoleRequest...')
msg := build_punch_hole_request(peer_id)
debug(verbose, 'Sending: ${msg.len} bytes: ${msg.hex()}')
sock.write(msg) or { return error('Failed to send: ${err}') }
// Read response
debug(verbose, 'Reading response...')
response := read_protobuf_message(mut sock) or {
debug(verbose, 'Read error: ${err}')
return error('Failed to read response: ${err}')
}
debug(verbose, 'Got response: ${response.len} bytes: ${response.hex()}')
return parse_punch_hole_response(response, verbose)
}
// Handle encrypted mode for IP retrieval
// Note: IP tracking requires encrypted communication with the rendezvous server.
// This is experimental and may not work with all RustDesk servers.
fn get_peer_ip_encrypted(mut sock net.TcpConn, key_exchange_msg []u8, peer_id string, verbose bool) !string {
debug(verbose, 'Received KeyExchange: ${key_exchange_msg.len} bytes')
// Parse KeyExchange and perform handshake
their_pk := parse_key_exchange(key_exchange_msg) or { return error('Key exchange failed: ${err}') }
debug(verbose, 'Server PK: ${their_pk.hex()}')
// Generate our keypair and create response, get the session key
key_response, session := create_key_exchange_response(their_pk, verbose) or { return error('Failed to create key response: ${err}') }
debug(verbose, 'Sending KeyExchange response: ${key_response.len} bytes')
sock.write(key_response) or { return error('Failed to send key exchange: ${err}') }
// Send encrypted PunchHoleRequest
plaintext := build_punch_hole_request_inner(peer_id)
encrypted_msg := encrypt_message(plaintext, session.symmetric_key)
debug(verbose, 'Sending encrypted PunchHoleRequest: ${encrypted_msg.len} bytes')
sock.write(encrypted_msg) or { return error('Failed to send: ${err}') }
// Read responses - server may send multiple messages
sock.set_read_timeout(3 * time.second)
mut nonce_counter := u64(1)
for _ in 0 .. 3 {
encrypted_response := read_protobuf_message(mut sock) or {
debug(verbose, 'No more responses: ${err}')
break
}
if encrypted_response.len == 0 {
debug(verbose, 'Empty response from server')
break
}
debug(verbose, 'Got encrypted response: ${encrypted_response.len} bytes')
// Decrypt the response with current nonce
decrypted := decrypt_message_with_nonce(encrypted_response, session.symmetric_key, nonce_counter) or {
debug(verbose, 'Failed to decrypt response: ${err}')
nonce_counter++
continue
}
nonce_counter++
debug(verbose, 'Decrypted response: ${decrypted.len} bytes')
// Try to parse - return if we get an IP
ip := parse_punch_hole_response(decrypted, verbose) or {
debug(verbose, 'No IP: ${err}')
continue
}
return ip
}
return error('No IP address available (peer may require relay)')
}
// Parse KeyExchange message and extract their public key
fn parse_key_exchange(data []u8) ![]u8 {
mut p := Parser{}
for p.pos < data.len {
tag := decode_varint(data, mut p) or { break }
field_num := int(tag >> 3)
wire_type := int(tag & 0x07)
if field_num == 25 && wire_type == 2 {
// Found KeyExchange (field 25)
length := decode_varint(data, mut p) or { break }
key_ex := data[p.pos..p.pos + int(length)]
// Parse KeyExchange - field 1 is repeated bytes keys
mut kp := Parser{}
for kp.pos < key_ex.len {
ktag := decode_varint(key_ex, mut kp) or { break }
kfield := int(ktag >> 3)
kwire := int(ktag & 0x07)
if kfield == 1 && kwire == 2 {
// Found keys field
klen := decode_varint(key_ex, mut kp) or { break }
signed_key := key_ex[kp.pos..kp.pos + int(klen)]
// The signed key is: 64-byte ed25519 signature + 32-byte Curve25519 public key
// The signature is Ed25519, but the signed content is already Curve25519
// Skip signature verification, just extract the Curve25519 public key
if signed_key.len >= 96 {
return signed_key[64..96].clone()
} else if signed_key.len >= 32 {
return signed_key[0..32].clone()
}
return error('Invalid key length: ${signed_key.len}')
} else {
skip_field(key_ex, kwire, mut kp) or { break }
}
}
break
} else {
skip_field(data, wire_type, mut p) or { break }
}
}
return error('No KeyExchange found in response')
}
// Create KeyExchange response with our public key and encrypted symmetric key
// Returns the framed message and the session with the symmetric key
fn create_key_exchange_response(their_pk []u8, verbose bool) !([]u8, Session) {
// Generate our keypair using libsodium
mut our_pk := []u8{len: 32}
mut our_sk := []u8{len: 32}
C.crypto_box_keypair(our_pk.data, our_sk.data)
debug(verbose, 'Generated keypair, PK: ${our_pk.hex()}')
// Generate symmetric key (32 bytes)
symmetric_key := rand.bytes(32) or { return error('Failed to generate symmetric key') }
// Encrypt symmetric key using crypto_box (NOT crypto_box_seal!)
// crypto_box_easy: ciphertext = MAC (16 bytes) + encrypted data
// Nonce is 24 bytes of zeros for key exchange
mut nonce := [24]u8{}
ciphertext_len := 16 + symmetric_key.len // MAC + data = 48 bytes
mut ciphertext := []u8{len: ciphertext_len}
result := C.crypto_box_easy(ciphertext.data, symmetric_key.data, u64(symmetric_key.len),
&nonce[0], their_pk.data, our_sk.data)
if result != 0 {
return error('crypto_box_easy failed with result ${result}')
}
debug(verbose, 'Encrypted symmetric key: ${ciphertext.len} bytes')
// Build KeyExchange response message
// keys[0] = our public key, keys[1] = encrypted symmetric key
mut key_ex := []u8{}
key_ex << encode_protobuf_bytes(1, our_pk)
key_ex << encode_protobuf_bytes(1, ciphertext)
// Wrap in RendezvousMessage (field 25 = key_exchange)
mut msg := []u8{}
msg << encode_protobuf_bytes(25, key_ex)
return encode_frame(msg), Session{
symmetric_key: symmetric_key
}
}
// Build PunchHoleRequest message (framed, unencrypted - for port 21115)
fn build_punch_hole_request(peer_id string) []u8 {
msg := build_punch_hole_request_inner(peer_id)
return encode_frame(msg)
}
// Build PunchHoleRequest inner protobuf (no framing)
fn build_punch_hole_request_inner(peer_id string) []u8 {
// Build PunchHoleRequest (field 1 = id)
mut punch_req := []u8{}
punch_req << encode_protobuf_string(1, peer_id)
// Wrap in RendezvousMessage (field 8 = punch_hole_request)
mut msg := []u8{}
msg << encode_protobuf_bytes(8, punch_req)
return msg
}
// C function declarations for crypto
fn C.crypto_secretbox_easy(&u8, &u8, u64, &u8, &u8) int
fn C.crypto_secretbox_open_easy(&u8, &u8, u64, &u8, &u8) int
fn C.crypto_box_keypair(&u8, &u8) int
fn C.crypto_box_easy(&u8, &u8, u64, &u8, &u8, &u8) int
// Create a 24-byte nonce from a counter value (little-endian)
fn create_nonce(nonce_val u64) [24]u8 {
mut nonce := [24]u8{}
nonce[0] = u8(nonce_val & 0xFF)
nonce[1] = u8((nonce_val >> 8) & 0xFF)
nonce[2] = u8((nonce_val >> 16) & 0xFF)
nonce[3] = u8((nonce_val >> 24) & 0xFF)
nonce[4] = u8((nonce_val >> 32) & 0xFF)
nonce[5] = u8((nonce_val >> 40) & 0xFF)
nonce[6] = u8((nonce_val >> 48) & 0xFF)
nonce[7] = u8((nonce_val >> 56) & 0xFF)
return nonce
}
// Prepare a 32-byte secretbox key from a byte slice
fn prepare_sbox_key(key []u8) [32]u8 {
mut sbox_key := [32]u8{}
for i in 0 .. 32 {
if i < key.len {
sbox_key[i] = key[i]
}
}
return sbox_key
}
// Encrypt a message with the symmetric key using secretbox (XSalsa20-Poly1305)
// RustDesk uses nonce counter that increments BEFORE use, so first message uses nonce 1
fn encrypt_message(plaintext []u8, key []u8) []u8 {
return encrypt_message_with_nonce(plaintext, key, 1)
}
// Encrypt with specific nonce value (for counter-based nonces)
fn encrypt_message_with_nonce(plaintext []u8, key []u8, nonce_val u64) []u8 {
nonce := create_nonce(nonce_val)
sbox_key := prepare_sbox_key(key)
// Encrypt: ciphertext = MAC (16 bytes) + encrypted data
mut ciphertext := []u8{len: 16 + plaintext.len}
C.crypto_secretbox_easy(ciphertext.data, plaintext.data, u64(plaintext.len), &nonce[0], &sbox_key[0])
// Apply framing (NO nonce prepending - RustDesk uses synchronized counters)
return encode_frame(ciphertext)
}
// Decrypt a message with the symmetric key using secretbox (XSalsa20-Poly1305)
// RustDesk uses nonce counter that increments BEFORE use, so first message uses nonce 1
fn decrypt_message_with_nonce(data []u8, key []u8, nonce_val u64) ![]u8 {
if data.len < 16 {
return error('Message too short')
}
nonce := create_nonce(nonce_val)
sbox_key := prepare_sbox_key(key)
// Decrypt
plaintext_len := data.len - 16
mut plaintext := []u8{len: plaintext_len}
result := C.crypto_secretbox_open_easy(plaintext.data, data.data, u64(data.len), &nonce[0], &sbox_key[0])
if result != 0 {
return error('Decryption failed - authentication error')
}
return plaintext
}
// Parse PunchHoleResponse or RelayResponse for IP address
fn parse_punch_hole_response(data []u8, verbose bool) !string {
// Look for field 9/10/11/19 (punch_hole, punch_hole_sent, punch_hole_response, relay_response)
mut p := Parser{}
for p.pos < data.len {
tag_and_type := decode_varint(data, mut p) or { break }
field_num := int(tag_and_type >> 3)
wire_type := int(tag_and_type & 0x07)
if (field_num == 9 || field_num == 10 || field_num == 11 || field_num == 19) && wire_type == 2 {
// All have socket_addr as field 1
length := decode_varint(data, mut p) or { break }
resp := data[p.pos..p.pos + int(length)]
// Parse response - find field 1 (socket_addr) or field 10 (socket_addr_v6)
mut rp := Parser{}
mut found_addr := []u8{}
for rp.pos < resp.len {
resp_tag := decode_varint(resp, mut rp) or { break }
resp_field := int(resp_tag >> 3)
resp_wire := int(resp_tag & 0x07)
if resp_field == 1 && resp_wire == 2 {
// Found socket_addr (IPv4)
addr_len := decode_varint(resp, mut rp) or { break }
found_addr = resp[rp.pos..rp.pos + int(addr_len)].clone()
debug(verbose, 'Found socket_addr: ${found_addr.len} bytes')
rp.pos += int(addr_len)
} else if resp_field == 10 && resp_wire == 2 {
// Found socket_addr_v6 - prefer this if no IPv4
addr_len := decode_varint(resp, mut rp) or { break }
if found_addr.len == 0 {
found_addr = resp[rp.pos..rp.pos + int(addr_len)].clone()
debug(verbose, 'Found socket_addr_v6: ${found_addr.len} bytes')
}
rp.pos += int(addr_len)
} else if resp_field == 3 && field_num == 11 {
// Field 3 in PunchHoleResponse is failure enum
return error('Peer offline or not found')
} else {
skip_field(resp, resp_wire, mut rp) or { break }
}
}
if found_addr.len > 0 {
return decode_addr_mangle(found_addr)
}
// RelayResponse without socket_addr means peer is behind NAT
if field_num == 19 {
return error('Peer is behind NAT (relay required)')
}
break
} else {
skip_field(data, wire_type, mut p) or { break }
}
}
return error('No IP address in response')
}
// Decode RustDesk's AddrMangle format
fn decode_addr_mangle(data []u8) !string {
if data.len == 0 {
return error('Empty address data')
}
// IPv6 addresses are stored with a 0x00 prefix and 18 bytes total (16 + 2 for port)
if data.len >= 18 && data[0] == 0x00 {
// IPv6 format: [0x00][16 bytes ipv6][2 bytes port BE]
mut ip_parts := []string{}
for i := 0; i < 8; i++ {
val := u16(data[1 + i * 2]) << 8 | u16(data[2 + i * 2])
ip_parts << '${val:x}'
}
port := u16(data[17]) << 8 | u16(data[18])
return '[${ip_parts.join(":")}]:${port}'
}
// IPv4 mangled format - decode the obfuscation
if data.len < 4 {
return error('Address data too short')
}
// RustDesk uses 128-bit encoding but V doesn't have u128
// We work with two u64 values: low (bytes 0-7) and high (bytes 8-15)
mut low := u64(0)
mut high := u64(0)
for i := 0; i < data.len && i < 8; i++ {
low |= u64(data[i]) << (i * 8)
}
for i := 8; i < data.len && i < 16; i++ {
high |= u64(data[i]) << ((i - 8) * 8)
}
// Extract components using RustDesk's mangle algorithm
// v = ((ip + tm) << 49) | (tm << 17) | (port + (tm & 0xFFFF))
// tm is in bits 17-48 (32 bits)
tm := (low >> 17) & 0xFFFFFFFF
// port is in bits 0-16, minus tm's lower 16 bits
port := u16((low & 0x1FFFF) - (tm & 0xFFFF))
// ip + tm is in bits 49+
// bits 49-63 are in 'low' (15 bits), rest in 'high'
ip_plus_tm_low := low >> 49 // 15 bits from low
ip_plus_tm_high := high << 15 // remaining bits shifted
ip_plus_tm := ip_plus_tm_low | ip_plus_tm_high
// Subtract tm to get ip
ip_encoded := ip_plus_tm - tm
// Convert IP to bytes (little endian as stored)
ip_bytes := [
u8(ip_encoded & 0xFF),
u8((ip_encoded >> 8) & 0xFF),
u8((ip_encoded >> 16) & 0xFF),
u8((ip_encoded >> 24) & 0xFF),
]
return '${ip_bytes[0]}.${ip_bytes[1]}.${ip_bytes[2]}.${ip_bytes[3]}:${port}'
}