-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebrtc.rs
More file actions
1618 lines (1421 loc) · 73.8 KB
/
Copy pathwebrtc.rs
File metadata and controls
1618 lines (1421 loc) · 73.8 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
// WebRTC handlers: offer, answer, join, parse, connection handling
use crate::session::{OfferContext, SessionKeys};
use crate::error::CoreError;
use std::sync::{Arc, Mutex};
use rand::Rng;
use p384::{ecdsa::{SigningKey, Signature, signature::Verifier}, PublicKey as P384Pub, pkcs8::{EncodePublicKey, DecodePublicKey}};
use ecdsa::signature::hazmat::{PrehashSigner, PrehashVerifier};
use sha2::{Digest, Sha256, Sha384};
use flate2::{Compression, write::ZlibEncoder, read::{ZlibDecoder, GzDecoder, DeflateDecoder}};
use base64::{engine::general_purpose, Engine};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use std::io::Read;
use std::io::Write;
use hkdf::Hkdf;
pub fn create_secure_offer(offer_state: Arc<Mutex<OfferContext>>, offer_sdp: Option<String>) -> Result<String, CoreError> {
// Generate P-384 keys for compatibility. A reusable SecretKey (not
// EphemeralSecret): the Double Ratchet derives from the handshake keys.
let ecdh_secret = p384::SecretKey::random(&mut rand::thread_rng());
let ecdh_public: P384Pub = ecdh_secret.public_key();
let ecdsa_signing = SigningKey::random(&mut rand::thread_rng());
let ecdsa_public = ecdsa_signing.verifying_key();
// Generate session salt (64 bytes for v4.0 compatibility)
let mut session_salt = [0u8; 64];
rand::thread_rng().fill(&mut session_salt);
// Generate session ID (32 hex chars = 16 bytes)
let session_id: String = (0..16)
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
// Generate connection ID (16 hex chars = 8 bytes)
let connection_id: String = (0..8)
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
// Generate ICE credentials (WebRTC requires ice-pwd length >= 22)
let ice_ufrag: String = (0..8) // 16 hex chars
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
let ice_pwd: String = (0..16) // 32 hex chars
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
// Generate verification code
let verification_code = format!("{:06}", rand::thread_rng().gen_range(100000..999999));
// Generate auth challenge
let auth_challenge: String = (0..32)
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
// Generate DTLS fingerprint (SHA-256) and format as colon-separated uppercase hex
let timestamp = chrono::Utc::now().timestamp();
let mut hasher = Sha256::new();
hasher.update(session_id.as_bytes());
hasher.update(connection_id.as_bytes());
let fp_hex = hex::encode(hasher.finalize()).to_uppercase();
let fp_colon = fp_hex.as_bytes()
.chunks(2)
.map(|c| std::str::from_utf8(c).map_err(|_| CoreError::internal_error("Invalid UTF-8 in fingerprint")))
.collect::<Result<Vec<_>, _>>()?
.join(":");
// NOTE: `fp_hex` above is only the synthetic fingerprint used to fill the
// minimal fallback SDP. The fingerprint used for SAS is taken from the SDP we
// actually advertise (see `local_dtls_fp_hex` below) so it matches what the
// peer derives from that same SDP.
// Use provided real SDP if available; otherwise fall back to minimal SDP
let minimal_sdp = format!(
"v=0\r\n\
o=- {} {} IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\
c=IN IP4 127.0.0.1\r\n\
a=ice-ufrag:{}\r\n\
a=ice-pwd:{}\r\n\
a=fingerprint:sha-256 {}\r\n\
a=setup:actpass\r\n\
a=mid:0\r\n\
a=sctp-port:5000\r\n\
a=max-message-size:262144\r\n",
timestamp,
timestamp,
ice_ufrag,
ice_pwd,
fp_colon
);
// The SDP we will actually advertise in the offer ("s"). Extract the REAL DTLS
// fingerprint from it for SAS, so both peers derive the SAS from the same
// fingerprint. Fall back to the synthetic one only if the SDP carries none.
let effective_offer_sdp = offer_sdp.unwrap_or_else(|| minimal_sdp.clone());
let local_dtls_fp_hex = extract_dtls_fingerprint_from_sdp(&effective_offer_sdp)
.unwrap_or_else(|| fp_hex.to_lowercase());
// Export SPKI for both keys
let ecdh_spki_der = ecdh_public.to_public_key_der().map_err(|e| CoreError::crypto_failure(format!("ECDH key export failed: {}", e)))?;
let ecdsa_spki_der = ecdsa_public.to_public_key_der().map_err(|e| CoreError::crypto_failure(format!("ECDSA key export failed: {}", e)))?;
// Create verifier for self-test
let ecdsa_verifying = p384::ecdsa::VerifyingKey::from(&ecdsa_signing);
// Build signed ECDH package matching web expectations
let e_ts = chrono::Utc::now().timestamp_millis();
// Create JSON string manually to ensure correct field order (keyType first, like web version)
// Format keyData array without spaces to match web version
let key_data_str = format!("[{}]", ecdh_spki_der.as_bytes().iter()
.map(|b| b.to_string())
.collect::<Vec<_>>()
.join(","));
let e_core_str = format!(
r#"{{"keyType":"ECDH","keyData":{},"timestamp":{},"version":"4.0"}}"#,
key_data_str,
e_ts
);
// Use SHA-384 for signing (same as web version)
let mut hasher = Sha384::new();
hasher.update(e_core_str.as_bytes());
let digest = hasher.finalize();
let e_sig_bin: Signature = ecdsa_signing.sign_prehash(&digest).map_err(|e| CoreError::crypto_failure(format!("ECDH signing failed: {}", e)))?;
let e_sig_raw = e_sig_bin.to_bytes();
// Also verify our own signature to make sure it's valid
ecdsa_verifying.verify(e_core_str.as_bytes(), &e_sig_bin)
.map_err(|e| CoreError::crypto_failure(format!("Self-verification failed: {}", e)))?;
let offer_package = serde_json::json!({
// Core information (minimal)
"t": "offer", // type
"s": effective_offer_sdp, // actual SDP from WebRTC offer (real DTLS fingerprint)
"v": "4.1", // protocol version (web PROTOCOL_VERSION); key-package version stays 4.0
"ts": chrono::Utc::now().timestamp_millis(), // timestamp
// Cryptographic keys (essential)
// The web verifier reconstructs the signed string from ALL fields except
// "signature" (in insertion order), so this object must contain exactly
// {keyType, keyData, timestamp, version, signature} — no extra "ps" field.
"e": { // signed ECDH public key package
"keyType": "ECDH",
"keyData": ecdh_spki_der.as_bytes(),
"timestamp": e_ts,
"version": "4.0",
"signature": e_sig_raw.as_ref()
},
"d": { // ECDSA public key (raw SPKI)
"keyData": ecdsa_spki_der.as_bytes()
},
// Session data (essential)
"sl": session_salt.to_vec(), // salt
"si": session_id, // sessionId
"ci": connection_id, // connectionId
// Authentication (essential)
"vc": verification_code, // verificationCode
"ac": auth_challenge, // authChallenge
// Security metadata (simplified)
"slv": "MAX", // securityLevel
// Double Ratchet support (web RATCHET_VERSION). Advertised rather than
// assumed so a peer on an earlier release keeps working on the
// static-key path instead of failing to decrypt anything. Absent = not
// supported.
"dr": crate::ratchet::RATCHET_VERSION,
// Key fingerprints (shortened)
"kf": {
"e": hex::encode(&sha2::Sha256::digest(ecdh_spki_der.as_bytes()))[0..12].to_string(),
"d": hex::encode(&sha2::Sha256::digest(ecdsa_spki_der.as_bytes()))[0..12].to_string()
}
});
// Persist ephemeral state for later answer validation
{
let mut st = offer_state.lock().map_err(|_| CoreError::state_error("Failed to acquire offer_state lock"))?;
st.ecdh_secret = Some(ecdh_secret);
st.session_salt = Some(session_salt.to_vec());
// Store local DTLS fingerprint (hex without colons) for SAS computation
st.local_dtls_fingerprint = Some(local_dtls_fp_hex);
}
// Compress and encode the offer in SB1:gz: format like web version
let json_str = serde_json::to_string(&offer_package).map_err(|e| CoreError::internal_error(format!("JSON serialization failed: {}", e)))?;
// Use gzip compression (same as web version)
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
encoder.write_all(json_str.as_bytes()).map_err(|e| CoreError::internal_error(format!("Compression write failed: {}", e)))?;
let compressed = encoder.finish().map_err(|e| CoreError::internal_error(format!("Compression finish failed: {}", e)))?;
// Use base64 encoding (same as web version)
let encoded = general_purpose::STANDARD.encode(&compressed);
Ok(format!("SB1:gz:{}", encoded))
}
pub fn create_secure_answer(
offer_state: Arc<Mutex<OfferContext>>,
offer_data: String,
answer_sdp: Option<String>
) -> Result<String, CoreError> {
// Decode SB1:gz or SB1:bin if needed
let decoded_offer = if offer_data.starts_with("SB1:gz:") {
let b64 = &offer_data[7..];
let compressed = general_purpose::STANDARD
.decode(b64)
.map_err(|e| CoreError::invalid_input(format!("Base64 decode failed: {}", e)))?;
let mut d = ZlibDecoder::new(&compressed[..]);
let mut s = String::new();
d.read_to_string(&mut s).map_err(|e| CoreError::invalid_input(format!("Zlib decode failed: {}", e)))?;
s
} else if offer_data.starts_with("SB1:bin:") {
let b64url = &offer_data[8..];
let compressed = URL_SAFE_NO_PAD
.decode(b64url)
.map_err(|e| CoreError::invalid_input(format!("Base64URL decode failed: {}", e)))?;
// Try deflate, then gzip
let mut s = String::new();
if DeflateDecoder::new(&compressed[..]).read_to_string(&mut s).is_ok() {
s
} else {
s.clear();
let _ = GzDecoder::new(&compressed[..]).read_to_string(&mut s);
s
}
} else {
offer_data
};
// Parse offer data
let offer: serde_json::Value = serde_json::from_str(&decoded_offer)
.map_err(|e| CoreError::invalid_input(format!("Invalid offer data: {}", e)))?;
// Validate offer structure
if offer["t"].as_str() != Some("offer") {
return Err(CoreError::protocol_violation("Invalid offer type"));
}
if offer["v"].as_str() != Some("4.1") {
return Err(CoreError::protocol_violation("Unsupported protocol version"));
}
// Generate P-384 keys for answer
let ecdh_secret = p384::SecretKey::random(&mut rand::thread_rng());
let ecdh_public: P384Pub = ecdh_secret.public_key();
let ecdsa_signing = SigningKey::random(&mut rand::thread_rng());
let ecdsa_public = ecdsa_signing.verifying_key();
// Generate our session salt
let mut our_session_salt = [0u8; 64];
rand::thread_rng().fill(&mut our_session_salt);
// Generate our session ID
let our_session_id: String = (0..16)
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
// Generate our connection ID
let our_connection_id: String = (0..8)
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
// Generate our verification code
let our_verification_code = format!("{:06}", rand::thread_rng().gen_range(100000..999999));
// Generate our auth challenge
let our_auth_challenge: String = (0..32)
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
// Generate DTLS fingerprint for answer
let timestamp = chrono::Utc::now().timestamp();
let mut hasher_ans = Sha256::new();
hasher_ans.update(our_session_id.as_bytes());
hasher_ans.update(our_connection_id.as_bytes());
let fp_hex_ans = hex::encode(hasher_ans.finalize()).to_uppercase();
let fp_colon_ans = fp_hex_ans.as_bytes()
.chunks(2)
.map(|c| std::str::from_utf8(c).map_err(|_| CoreError::internal_error("Invalid UTF-8 in fingerprint")))
.collect::<Result<Vec<_>, _>>()?
.join(":");
// ⭐ КРИТИЧЕСКИ ВАЖНОЕ ИСПРАВЛЕНИЕ: Сохраняем local DTLS fingerprint
// Это необходимо для вычисления SAS кода, когда answerer получит подтверждение
let local_dtls_fp_hex = fp_hex_ans.clone();
// Generate ICE credentials for answer
let ans_ice_ufrag: String = (0..8)
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
let ans_ice_pwd: String = (0..16)
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
// Generate minimal valid SDP for answer compatibility (fallback)
let minimal_answer_sdp = format!(
"v=0\r\n\
o=- {} {} IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\
c=IN IP4 127.0.0.1\r\n\
a=ice-ufrag:{}\r\n\
a=ice-pwd:{}\r\n\
a=fingerprint:sha-256 {}\r\n\
a=setup:active\r\n\
a=mid:0\r\n\
a=sctp-port:5000\r\n\
a=max-message-size:262144\r\n",
timestamp,
timestamp,
ans_ice_ufrag,
ans_ice_pwd,
fp_colon_ans
);
// Export SPKI
let ecdh_spki_der = ecdh_public.to_public_key_der().map_err(|e| CoreError::crypto_failure(format!("ECDH key export failed: {}", e)))?;
let ecdsa_spki_der = ecdsa_public.to_public_key_der().map_err(|e| CoreError::crypto_failure(format!("ECDSA key export failed: {}", e)))?;
// Build signed ECDH package for answer
let e_ts = chrono::Utc::now().timestamp_millis();
// Create JSON string manually to ensure correct field order (keyType first, like web version)
// Format keyData array without spaces to match web version
let key_data_str = format!("[{}]", ecdh_spki_der.as_bytes().iter()
.map(|b| b.to_string())
.collect::<Vec<_>>()
.join(","));
let e_core_str = format!(
r#"{{"keyType":"ECDH","keyData":{},"timestamp":{},"version":"4.0"}}"#,
key_data_str,
e_ts
);
// Use SHA-384 for signing (same as web version)
let mut hasher = Sha384::new();
hasher.update(e_core_str.as_bytes());
let digest = hasher.finalize();
let e_sig_bin: Signature = ecdsa_signing.sign_prehash(&digest).map_err(|e| CoreError::crypto_failure(format!("ECDH signing failed: {}", e)))?;
let e_sig_raw = e_sig_bin.to_bytes();
// Create answer package compatible with web version
let answer_package = serde_json::json!({
// Core information (minimal)
"t": "answer", // type
"s": answer_sdp.unwrap_or(minimal_answer_sdp), // actual WebRTC answer SDP (fallback to minimal)
"v": "4.1", // protocol version (web PROTOCOL_VERSION); key-package version stays 4.0
"ts": chrono::Utc::now().timestamp_millis(), // timestamp
// Reference to original offer
"oi": offer["si"], // original sessionId
"oc": offer["ci"], // original connectionId
// Our cryptographic keys (essential)
"e": { // signed ECDH public key package
"keyType": "ECDH",
"keyData": ecdh_spki_der.as_bytes(),
"timestamp": e_ts,
"version": "4.0",
"signature": e_sig_raw.as_ref(),
"ps": e_core_str
},
"d": { // ECDSA public key (raw SPKI)
"keyData": ecdsa_spki_der.as_bytes()
},
// Our session data (essential)
"sl": our_session_salt.to_vec(), // salt
"si": our_session_id, // sessionId
"ci": our_connection_id, // connectionId
// Authentication (essential)
"vc": our_verification_code, // verificationCode
"ac": our_auth_challenge, // authChallenge
// Security metadata (simplified)
"slv": "MAX", // securityLevel
// Key fingerprints (shortened)
"kf": {
"e": hex::encode(&sha2::Sha256::digest(ecdh_spki_der.as_bytes()))[0..12].to_string(),
"d": hex::encode(&sha2::Sha256::digest(ecdsa_spki_der.as_bytes()))[0..12].to_string()
}
});
// ⭐ КРИТИЧЕСКИ ВАЖНОЕ ИСПРАВЛЕНИЕ: Сохраняем состояние для последующего вычисления SAS
// Когда answerer получит подтверждение от offerer, он должен вычислить SAS код
// Для этого нужны: local_dtls_fingerprint
{
let mut st = offer_state.lock().map_err(|_| CoreError::state_error("Failed to acquire offer_state lock"))?;
st.local_dtls_fingerprint = Some(local_dtls_fp_hex);
}
// Return SB1:gz encoded answer
let json_str = serde_json::to_string(&answer_package).map_err(|e| CoreError::internal_error(format!("JSON serialization failed: {}", e)))?;
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
encoder.write_all(json_str.as_bytes()).map_err(|e| CoreError::internal_error(format!("Compression write failed: {}", e)))?;
let compressed = encoder.finish().map_err(|e| CoreError::internal_error(format!("Compression finish failed: {}", e)))?;
let encoded = general_purpose::STANDARD.encode(&compressed);
Ok(format!("SB1:gz:{}", encoded))
}
// Helper function to convert CBOR to JSON, converting binary data to arrays of numbers
fn cbor_to_json_with_bytes(cbor_val: &serde_cbor::Value) -> serde_json::Value {
match cbor_val {
serde_cbor::Value::Null => serde_json::Value::Null,
serde_cbor::Value::Bool(b) => serde_json::Value::Bool(*b),
serde_cbor::Value::Integer(i) => {
// Try to fit into i64, otherwise u64
if let Ok(n) = i64::try_from(*i) {
serde_json::Value::Number(n.into())
} else if let Ok(n) = u64::try_from(*i) {
serde_json::Value::Number(n.into())
} else {
serde_json::Value::String(i.to_string())
}
},
serde_cbor::Value::Float(f) => {
serde_json::Number::from_f64(*f)
.map(serde_json::Value::Number)
.unwrap_or(serde_json::Value::Null)
},
serde_cbor::Value::Bytes(b) => {
// Convert bytes to array of numbers for JSON compatibility
serde_json::Value::Array(b.iter().map(|&byte| serde_json::Value::Number(byte.into())).collect())
},
serde_cbor::Value::Text(s) => serde_json::Value::String(s.clone()),
serde_cbor::Value::Array(arr) => {
serde_json::Value::Array(arr.iter().map(cbor_to_json_with_bytes).collect())
},
serde_cbor::Value::Map(map) => {
let mut json_map = serde_json::Map::new();
for (key, val) in map.iter() {
let key_str = match key {
serde_cbor::Value::Text(s) => s.clone(),
serde_cbor::Value::Integer(i) => i.to_string(),
_ => format!("{:?}", key),
};
json_map.insert(key_str, cbor_to_json_with_bytes(val));
}
serde_json::Value::Object(json_map)
},
serde_cbor::Value::Tag(_, val) => cbor_to_json_with_bytes(val),
// Handle any other CBOR value types (Simple, etc.)
_ => serde_json::Value::Null,
}
}
pub fn parse_secure_offer(offer_data: String) -> Result<String, CoreError> {
if offer_data.is_empty() {
return Err(CoreError::invalid_input("Offer data is empty"));
}
// Reuse decoding logic from create_secure_answer
let decoded_offer = if offer_data.starts_with("SB1:gz:") {
let b64 = &offer_data[7..];
let compressed = general_purpose::STANDARD
.decode(b64)
.map_err(|e| CoreError::invalid_input(format!("Base64 decode failed: {}", e)))?;
let mut d = ZlibDecoder::new(&compressed[..]);
let mut s = String::new();
d.read_to_string(&mut s).map_err(|e| CoreError::invalid_input(format!("Zlib decode failed: {}", e)))?;
s
} else if offer_data.starts_with("SB1:bin:") {
let b64url = &offer_data[8..];
let compressed = URL_SAFE_NO_PAD
.decode(b64url)
.map_err(|e| CoreError::invalid_input(format!("Base64URL decode failed: {}", e)))?;
// Try zlib first (most common for eJy... prefix), then deflate, then gzip
let mut s = String::new();
if ZlibDecoder::new(&compressed[..]).read_to_string(&mut s).is_ok() {
s
} else {
s.clear();
if DeflateDecoder::new(&compressed[..]).read_to_string(&mut s).is_ok() {
s
} else {
// Try reading as bytes for CBOR decoding (like handle_secure_answer does)
let mut buf = Vec::new();
if ZlibDecoder::new(&compressed[..]).read_to_end(&mut buf).is_ok() {
// OK
} else if DeflateDecoder::new(&compressed[..]).read_to_end(&mut buf).is_ok() {
// OK
} else {
buf.clear();
if GzDecoder::new(&compressed[..]).read_to_end(&mut buf).is_ok() {
// OK
} else {
return Err(CoreError::invalid_input("Failed to decode SB1:bin with zlib/deflate/gzip"));
}
}
// Try CBOR decode (like handle_secure_answer does)
match serde_cbor::from_slice::<serde_cbor::Value>(&buf) {
Ok(cbor_val) => {
let json_val = cbor_to_json_with_bytes(&cbor_val);
let json_str = serde_json::to_string(&json_val).map_err(|e| CoreError::internal_error(format!("CBOR to JSON conversion failed: {}", e)))?;
json_str
}
Err(_) => {
// If CBOR decode fails, try to interpret as raw string
String::from_utf8(buf).map_err(|e| CoreError::invalid_input(format!("Failed to decode as UTF-8 string: {}", e)))?
}
}
}
}
} else {
// Try to parse as JSON directly
if offer_data.trim().starts_with('{') || offer_data.trim().starts_with('[') {
offer_data.clone()
} else {
return Err(CoreError::invalid_input(format!("Unknown offer format. Expected SB1:gz:, SB1:bin:, or JSON")));
}
};
if decoded_offer.is_empty() {
return Err(CoreError::invalid_input("Decoded offer is empty"));
}
// Validate it's JSON
let offer_json: serde_json::Value = serde_json::from_str(&decoded_offer)
.map_err(|e| CoreError::invalid_input(format!("Invalid offer data (JSON parse error): {}", e)))?;
// Return compact JSON string (so frontend can parse)
serde_json::to_string(&offer_json).map_err(|e| CoreError::internal_error(format!("JSON serialization failed: {}", e)))
}
// Extract DTLS fingerprint from SDP string
fn extract_dtls_fingerprint_from_sdp(sdp: &str) -> Option<String> {
// Look for a=fingerprint:sha-256 ... pattern
let fingerprint_regex = regex::Regex::new(r"a=fingerprint:sha-256\s+([A-Fa-f0-9:]+)").ok()?;
if let Some(caps) = fingerprint_regex.captures(sdp) {
if let Some(fp_match) = caps.get(1) {
// Keep colons, lowercase only — this MUST match the web's _computeSAS
// normalization (`fingerprint.trim().toLowerCase()`), which preserves
// the colon-separated form. Stripping colons would change the SAS salt
// and make the codes disagree across implementations.
let fp = fp_match.as_str().trim().to_lowercase();
return Some(fp);
}
}
None
}
// Compute SAS (Short Authentication String) code using HKDF
// Similar to web version's _computeSAS function
fn compute_sas_code(key_fingerprint_bytes: &[u8], local_fp: &str, remote_fp: &str) -> Result<String, CoreError> {
// Use key fingerprint bytes directly (already decoded)
let key_bytes = key_fingerprint_bytes;
// Create salt: 'webrtc-sas|' + sorted fingerprints joined by '|'
let mut fps = vec![local_fp.to_string(), remote_fp.to_string()];
fps.sort();
let salt_str = format!("webrtc-sas|{}", fps.join("|"));
let salt = salt_str.as_bytes();
// Use HKDF(SHA-256) to derive 64 bits (8 bytes) for SAS code
let hk = Hkdf::<Sha256>::new(Some(salt), &key_bytes);
let mut sas_bytes = [0u8; 8];
hk.expand(b"p2p-sas-v1", &mut sas_bytes)
.map_err(|_| CoreError::crypto_failure("HKDF expand failed for SAS"))?;
// Combine first 4 bytes and last 4 bytes with XOR
let n1 = u32::from_be_bytes([sas_bytes[0], sas_bytes[1], sas_bytes[2], sas_bytes[3]]);
let n2 = u32::from_be_bytes([sas_bytes[4], sas_bytes[5], sas_bytes[6], sas_bytes[7]]);
let combined = (n1 ^ n2) as u64;
// Generate 7-digit code (0000000-9999999)
// Use rejection sampling to avoid bias
let sas_value = (combined % 10_000_000) as u32;
let sas_code = format!("{:07}", sas_value);
Ok(sas_code)
}
// Helper: extract bytes from JSON value (array of numbers, base64/base64url string, or Buffer-like)
fn extract_bytes(val: &serde_json::Value) -> Result<Vec<u8>, CoreError> {
// Try array of numbers first (common in JSON)
if let Some(arr) = val.as_array() {
let mut bytes = Vec::new();
for v in arr {
if let Some(n) = v.as_u64() {
if n > 255 {
return Err(CoreError::invalid_input(format!("Number {} out of byte range", n)));
}
bytes.push(n as u8);
} else if let Some(n) = v.as_i64() {
if n < 0 || n > 255 {
return Err(CoreError::invalid_input(format!("Number {} out of byte range", n)));
}
bytes.push(n as u8);
} else {
return Err(CoreError::invalid_input("Array contains non-numeric values".to_string()));
}
}
return Ok(bytes);
}
// Try base64/base64url string
if let Some(s) = val.as_str() {
// Try standard base64
if let Ok(b) = base64::engine::general_purpose::STANDARD.decode(s) {
return Ok(b);
}
// Try URL-safe base64
if let Ok(b) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(s) {
return Ok(b);
}
// Try URL-safe base64 with padding
if let Ok(b) = base64::engine::general_purpose::URL_SAFE.decode(s) {
return Ok(b);
}
return Err(CoreError::invalid_input("Invalid base64 string".to_string()));
}
// Try object with data field
if let Some(obj) = val.as_object() {
if let Some(data) = obj.get("data") {
return extract_bytes(data);
}
// Try _bytes field (CBOR binary representation)
if let Some(bytes_val) = obj.get("_bytes") {
return extract_bytes(bytes_val);
}
}
Err(CoreError::invalid_input(format!("Unsupported binary format")))
}
pub fn join_secure_connection(
offer_state: Arc<Mutex<OfferContext>>,
session_keys: Arc<Mutex<SessionKeys>>,
offer_data: String,
answer_sdp: Option<String>
) -> Result<String, CoreError> {
if offer_data.is_empty() {
return Err(CoreError::invalid_input("Offer data is empty"));
}
// Decode offer data
let decoded_offer = if offer_data.starts_with("SB1:gz:") {
let b64 = &offer_data[7..];
let compressed = general_purpose::STANDARD
.decode(b64)
.map_err(|e| CoreError::invalid_input(format!("Base64 decode failed: {}", e)))?;
let mut d = ZlibDecoder::new(&compressed[..]);
let mut s = String::new();
d.read_to_string(&mut s).map_err(|e| CoreError::invalid_input(format!("Zlib decode failed: {}", e)))?;
s
} else if offer_data.starts_with("SB1:bin:") {
let b64url = &offer_data[8..];
let compressed = URL_SAFE_NO_PAD
.decode(b64url)
.map_err(|e| CoreError::invalid_input(format!("Base64URL decode failed: {}", e)))?;
// Try zlib first (most common for eJy... prefix), then deflate, then gzip
let mut s = String::new();
if ZlibDecoder::new(&compressed[..]).read_to_string(&mut s).is_ok() {
s
} else {
s.clear();
if DeflateDecoder::new(&compressed[..]).read_to_string(&mut s).is_ok() {
s
} else {
// Try reading as bytes for CBOR decoding (like handle_secure_answer does)
let mut buf = Vec::new();
if ZlibDecoder::new(&compressed[..]).read_to_end(&mut buf).is_ok() {
// OK
} else if DeflateDecoder::new(&compressed[..]).read_to_end(&mut buf).is_ok() {
// OK
} else {
buf.clear();
if GzDecoder::new(&compressed[..]).read_to_end(&mut buf).is_ok() {
// OK
} else {
return Err(CoreError::invalid_input("Failed to decode SB1:bin with zlib/deflate/gzip"));
}
}
// Try CBOR decode (like handle_secure_answer does)
match serde_cbor::from_slice::<serde_cbor::Value>(&buf) {
Ok(cbor_val) => {
let json_val = cbor_to_json_with_bytes(&cbor_val);
let json_str = serde_json::to_string(&json_val).map_err(|e| CoreError::internal_error(format!("CBOR to JSON conversion failed: {}", e)))?;
json_str
}
Err(_) => {
// If CBOR decode fails, try to interpret as raw string
String::from_utf8(buf).map_err(|e| CoreError::invalid_input(format!("Failed to decode as UTF-8 string: {}", e)))?
}
}
}
}
} else {
if offer_data.trim().starts_with('{') || offer_data.trim().starts_with('[') {
offer_data.clone()
} else {
return Err(CoreError::invalid_input("Unknown offer format. Expected SB1:gz:, SB1:bin:, or JSON"));
}
};
if decoded_offer.is_empty() {
return Err(CoreError::invalid_input("Decoded offer is empty"));
}
// Parse offer data
let offer: serde_json::Value = serde_json::from_str(&decoded_offer)
.map_err(|e| CoreError::invalid_input(format!("Invalid offer data: {}", e)))?;
// Validate offer structure
let offer_type = offer.get("t").or_else(|| offer.get("type"));
if offer_type.and_then(|v| v.as_str()) != Some("offer") {
return Err(CoreError::protocol_violation("Invalid offer type"));
}
let offer_version = offer.get("v").or_else(|| offer.get("version"));
if offer_version.and_then(|v| v.as_str()) != Some("4.1") {
return Err(CoreError::protocol_violation("Unsupported protocol version"));
}
// Extract salt from offer (essential for key derivation)
// Try both compact format (sl) and full format (salt)
let offer_salt = offer.get("sl").or_else(|| offer.get("salt"));
let offer_salt = offer_salt
.and_then(|v| v.as_array())
.map(|arr| {
let mut bytes = Vec::new();
for v in arr {
if let Some(n) = v.as_u64() {
if n <= 255 {
bytes.push(n as u8);
}
} else if let Some(n) = v.as_i64() {
if n >= 0 && n <= 255 {
bytes.push(n as u8);
}
}
}
bytes
})
.ok_or_else(|| CoreError::protocol_violation("Missing salt in offer"))?;
if offer_salt.len() != 64 {
return Err(CoreError::protocol_violation(format!("Invalid salt length: {} (expected 64)", offer_salt.len())));
}
// Extract peer ECDH public key from offer
let ecdh_pkg = offer.get("e")
.ok_or_else(|| CoreError::protocol_violation("Missing ECDH package in offer"))?;
let peer_ecdh_key_data = ecdh_pkg.get("keyData")
.ok_or_else(|| CoreError::protocol_violation("Missing keyData in ECDH package"))?;
let peer_ecdh_spki = extract_bytes(peer_ecdh_key_data)
.map_err(|e| CoreError::invalid_input(format!("Invalid ECDH keyData: {}", e)))?;
let peer_ecdh_public = p384::PublicKey::from_public_key_der(&peer_ecdh_spki)
.map_err(|e| CoreError::crypto_failure(format!("Failed to import peer ECDH key: {}", e)))?;
// Did the initiator advertise the Double Ratchet? Absent means an older
// build, which is a downgrade to the static-key scheme rather than a
// failure — with no server there is no way to roll both ends at once.
let peer_supports_ratchet =
offer.get("dr").and_then(|v| v.as_u64()) == Some(crate::ratchet::RATCHET_VERSION);
// Generate our P-384 keys for answer. A reusable SecretKey: as the joining
// (responder) side, this exact key pair becomes the ratchet's first key
// pair — the initiator's first DH deliberately lands on it.
let ecdh_secret = p384::SecretKey::random(&mut rand::thread_rng());
let ecdh_public: P384Pub = ecdh_secret.public_key();
let ecdsa_signing = SigningKey::random(&mut rand::thread_rng());
let ecdsa_public = ecdsa_signing.verifying_key();
// Generate DTLS fingerprint for answer
let our_session_id: String = (0..16)
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
let our_connection_id: String = (0..8)
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
let timestamp = chrono::Utc::now().timestamp();
let mut hasher_ans = Sha256::new();
hasher_ans.update(our_session_id.as_bytes());
hasher_ans.update(our_connection_id.as_bytes());
let fp_hex_ans = hex::encode(hasher_ans.finalize()).to_uppercase();
let fp_colon_ans = fp_hex_ans.as_bytes()
.chunks(2)
.map(|c| std::str::from_utf8(c).map_err(|_| CoreError::internal_error("Invalid UTF-8 in fingerprint")))
.collect::<Result<Vec<_>, _>>()?
.join(":");
// Store local DTLS fingerprint (hex without colons) for SAS computation
// This is needed for handle_secure_answer to compute the SAS code
let local_dtls_fp_hex = fp_hex_ans.clone();
let ans_ice_ufrag: String = (0..8)
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
let ans_ice_pwd: String = (0..16)
.map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>()))
.collect();
let minimal_answer_sdp = format!(
"v=0\r\n\
o=- {} {} IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\
c=IN IP4 127.0.0.1\r\n\
a=ice-ufrag:{}\r\n\
a=ice-pwd:{}\r\n\
a=fingerprint:sha-256 {}\r\n\
a=setup:active\r\n\
a=mid:0\r\n\
a=sctp-port:5000\r\n\
a=max-message-size:262144\r\n",
timestamp, timestamp, ans_ice_ufrag, ans_ice_pwd, fp_colon_ans
);
// Export SPKI
let ecdh_spki_der = ecdh_public.to_public_key_der().map_err(|e| CoreError::crypto_failure(format!("ECDH key export failed: {}", e)))?;
let ecdsa_spki_der = ecdsa_public.to_public_key_der().map_err(|e| CoreError::crypto_failure(format!("ECDSA key export failed: {}", e)))?;
// Build signed ECDH package - EXACTLY like web version
// Web version: const keyPackage = { keyType, keyData, timestamp, version };
// Then: const packageString = JSON.stringify(keyPackage);
let e_ts = chrono::Utc::now().timestamp_millis();
// Build the signed key-package string MANUALLY in keyType-first order, exactly
// like create_secure_offer and the web's JSON.stringify({keyType,keyData,timestamp,version}).
// serde_json::Map serializes keys alphabetically, which would NOT match the web
// verifier, so the signed string must not be derived from the map.
let e_key_data_str = format!("[{}]", ecdh_spki_der.as_bytes().iter()
.map(|b| b.to_string()).collect::<Vec<_>>().join(","));
let e_core_str = format!(
r#"{{"keyType":"ECDH","keyData":{},"timestamp":{},"version":"4.0"}}"#,
e_key_data_str, e_ts
);
// Field map used only to assemble the answer "e" object. We also embed the
// signed "ps" string so the peer can verify against the exact bytes we signed.
let mut ecdh_key_package = serde_json::Map::new();
ecdh_key_package.insert("keyType".to_string(), serde_json::Value::String("ECDH".to_string()));
ecdh_key_package.insert("keyData".to_string(), serde_json::Value::Array(
ecdh_spki_der.as_bytes().iter().map(|&b| serde_json::Value::Number(b.into())).collect()
));
ecdh_key_package.insert("timestamp".to_string(), serde_json::Value::Number(e_ts.into()));
ecdh_key_package.insert("version".to_string(), serde_json::Value::String("4.0".to_string()));
// No "ps" field: the web verifier includes every non-signature field in the
// signed string, so the package must be exactly {keyType,keyData,timestamp,version,signature}.
let mut ecdh_hasher = Sha384::new();
ecdh_hasher.update(e_core_str.as_bytes());
let ecdh_digest = ecdh_hasher.finalize();
let e_sig_bin: Signature = ecdsa_signing.sign_prehash(&ecdh_digest).map_err(|e| CoreError::crypto_failure(format!("ECDH signing failed: {}", e)))?;
let e_sig_raw = e_sig_bin.to_bytes();
if e_sig_raw.len() != 96 {
return Err(CoreError::crypto_failure("ECDH signature must be 96 bytes for P-384"));
}
// Build signed ECDSA package - EXACTLY like web version
// Web version: const keyPackage = { keyType, keyData, timestamp, version };
// Then: const packageString = JSON.stringify(keyPackage);
let d_ts = chrono::Utc::now().timestamp_millis();
// Create object in the exact same order as web version
let mut ecdsa_key_package = serde_json::Map::new();
ecdsa_key_package.insert("keyType".to_string(), serde_json::Value::String("ECDSA".to_string()));
ecdsa_key_package.insert("keyData".to_string(), serde_json::Value::Array(
ecdsa_spki_der.as_bytes().iter().map(|&b| serde_json::Value::Number(b.into())).collect()
));
ecdsa_key_package.insert("timestamp".to_string(), serde_json::Value::Number(d_ts.into()));
ecdsa_key_package.insert("version".to_string(), serde_json::Value::String("4.0".to_string()));
// Serialize to JSON string exactly like web version's JSON.stringify
let d_core_str = serde_json::to_string(&serde_json::Value::Object(ecdsa_key_package.clone()))
.map_err(|e| CoreError::internal_error(format!("Failed to serialize ECDSA package: {}", e)))?;
let mut ecdsa_hasher = Sha384::new();
ecdsa_hasher.update(d_core_str.as_bytes());
let ecdsa_digest = ecdsa_hasher.finalize();
let d_sig_bin: Signature = ecdsa_signing.sign_prehash(&ecdsa_digest).map_err(|e| CoreError::crypto_failure(format!("ECDSA signing failed: {}", e)))?;
let d_sig_raw = d_sig_bin.to_bytes();
if d_sig_raw.len() != 96 {
return Err(CoreError::crypto_failure("ECDSA signature must be 96 bytes for P-384"));
}
// Create answer package - EXACTLY like web version
// Web version: const signedPackage = { ...keyPackage, signature };
// So order is: keyType, keyData, timestamp, version, signature
let mut ecdh_package = ecdh_key_package.clone();
ecdh_package.insert("signature".to_string(), serde_json::Value::Array(
e_sig_raw.as_ref().iter().map(|&b| serde_json::Value::Number(b.into())).collect()
));
let mut ecdsa_package = ecdsa_key_package.clone();
ecdsa_package.insert("signature".to_string(), serde_json::Value::Array(
d_sig_raw.as_ref().iter().map(|&b| serde_json::Value::Number(b.into())).collect()
));
// The SDP that actually goes on the wire — the browser's real answer when the
// frontend supplied one, otherwise our minimal stand-in. The SAS must be
// computed over the SAME fingerprint the peer will see, so hoist it here
// instead of consuming it inside the json! macro.
let effective_answer_sdp = answer_sdp.unwrap_or(minimal_answer_sdp);
let answer_package = serde_json::json!({
"t": "answer",
"s": effective_answer_sdp.clone(),
"v": "4.1",
"version": "4.1", // protocol version (full field alias); key-package version stays 4.0
"ts": chrono::Utc::now().timestamp_millis(),
"oi": offer["si"],
"oc": offer["ci"],
"e": ecdh_package,
"d": ecdsa_package,
"sl": offer_salt.clone(), // Use salt from offer
"si": our_session_id,
"ci": our_connection_id,
"vc": format!("{:06}", rand::thread_rng().gen_range(100000..999999)),
"ac": (0..32).map(|_| format!("{:02x}", rand::thread_rng().gen::<u8>())).collect::<String>(),
"slv": "MAX",
// Double Ratchet support (see the note on the offer package).
"dr": crate::ratchet::RATCHET_VERSION,
"kf": {
"e": hex::encode(&sha2::Sha256::digest(ecdh_spki_der.as_bytes()))[0..12].to_string(),
"d": hex::encode(&sha2::Sha256::digest(ecdsa_spki_der.as_bytes()))[0..12].to_string()
}
});
// Derive keys immediately (like web version does)
let shared = p384::ecdh::diffie_hellman(ecdh_secret.to_nonzero_scalar(), peer_ecdh_public.as_affine());
let shared_bytes_full = shared.raw_secret_bytes();
// Truncate to 32 bytes (matching Web Crypto API)
let shared_bytes: &[u8] = if shared_bytes_full.len() >= 32 {
&shared_bytes_full[..32]
} else {
&shared_bytes_full
};
// Derive keys using HKDF
let hk = Hkdf::<Sha256>::new(Some(&offer_salt), shared_bytes);
let mut enc_okm = [0u8; 32];
hk.expand(b"message-encryption-v4", &mut enc_okm)
.map_err(|e| CoreError::crypto_failure(format!("HKDF expand enc failed: {:?}", e)))?;
let mut mac_okm = [0u8; 64];
hk.expand(b"message-authentication-v4", &mut mac_okm)
.map_err(|e| CoreError::crypto_failure(format!("HKDF expand mac failed: {:?}", e)))?;
let mut meta_okm = [0u8; 32];
hk.expand(b"metadata-protection-v4", &mut meta_okm)
.map_err(|e| CoreError::crypto_failure(format!("HKDF expand meta failed: {:?}", e)))?;
// Derive the SAS ourselves, exactly as handle_secure_answer does on the other
// side and as the web client does in deriveSharedKeys + _computeSAS: the
// dedicated 'fingerprint-generation-v4' key, SHA-384, first 12 bytes, then
// HKDF over the two DTLS fingerprints (compute_sas_code sorts them, so both
// peers reach the same value regardless of orientation).
//
// Without this the joining side had NO code of its own and simply displayed
// whatever the offerer announced over the wire — which an attacker in the
// middle can choose, making the out-of-band comparison meaningless.
let mut fp_okm = [0u8; 32];
hk.expand(b"fingerprint-generation-v4", &mut fp_okm)
.map_err(|e| CoreError::crypto_failure(format!("HKDF expand fingerprint failed: {:?}", e)))?;
// Root for the Double Ratchet: its own domain-separated branch of the key
// schedule (web deriveSharedKeys, info 'double-ratchet-root-v1'), so
// learning a session key tells an attacker nothing about the ratchet.
let mut dr_root_okm = [0u8; 32];
hk.expand(b"double-ratchet-root-v1", &mut dr_root_okm)
.map_err(|e| CoreError::crypto_failure(format!("HKDF expand ratchet root failed: {:?}", e)))?;
let mut fp_h = Sha384::new();
fp_h.update(&fp_okm);
let fp = fp_h.finalize();
let key_fingerprint_bytes: [u8; 12] = {
let mut bytes = [0u8; 12];
bytes.copy_from_slice(&fp[..12]);
bytes
};
// Local = our answer's fingerprint, remote = the offerer's.
let local_sas_fp = extract_dtls_fingerprint_from_sdp(&effective_answer_sdp).unwrap_or_default();
let remote_sas_fp = offer
.get("s")