forked from S4tvara/Sietch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.go
More file actions
1145 lines (975 loc) · 33.2 KB
/
sync.go
File metadata and controls
1145 lines (975 loc) · 33.2 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
package p2p
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"slices"
"time"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/protocol"
"github.com/substantialcattle5/sietch/internal/config"
"github.com/substantialcattle5/sietch/internal/manifest" //golangci-lint error
)
const (
// Protocol IDs for different sync operations
ManifestProtocolID = "/sietch/manifest/1.0.0"
ManifestProtocolIDv0 = "/sietch/manifest/0.9.0" // Fallback version
ChunkProtocolID = "/sietch/chunk/1.0.0"
KeyExchangeProtocol = "/sietch/key-exchange/1.0.0"
AuthProtocol = "/sietch/auth/1.0.0"
// RSA encryption chunk size (must be smaller than key size to account for padding)
RSAChunkSize = 256 // For 2048-bit keys
)
// SyncService handles vault synchronization
type SyncService struct {
host host.Host
vaultMgr *config.Manager
privateKey *rsa.PrivateKey
publicKey *rsa.PublicKey
rsaConfig *config.RSAConfig
trustedPeers map[peer.ID]*PeerInfo
vaultConfig *config.VaultConfig
trustAllPeers bool // New flag to automatically trust all peers
}
// PeerInfo contains information about a trusted peer
type PeerInfo struct {
ID peer.ID
PublicKey *rsa.PublicKey
Fingerprint string
Name string
TrustedSince time.Time
}
// SyncResult contains statistics about a sync operation
type SyncResult struct {
FileCount int
ChunksTransferred int
ChunksDeduplicated int
BytesTransferred int64
Duration time.Duration
}
// NewSyncService creates a new sync service
func NewSyncService(h host.Host, vm *config.Manager) (*SyncService, error) {
// Basic initialization without RSA security
s := &SyncService{
host: h,
vaultMgr: vm,
trustedPeers: make(map[peer.ID]*PeerInfo),
trustAllPeers: true, // Trust all peers by default
}
// Register basic protocol handlers
h.SetStreamHandler(protocol.ID(ManifestProtocolID), s.handleManifestRequest)
h.SetStreamHandler(protocol.ID(ManifestProtocolIDv0), s.handleManifestRequest) // Support fallback version
h.SetStreamHandler(protocol.ID(ChunkProtocolID), s.handleChunkRequest)
return s, nil
}
// NewSecureSyncService creates a new secure sync service with RSA key support
func NewSecureSyncService(
h host.Host,
vm *config.Manager,
privateKey *rsa.PrivateKey,
publicKey *rsa.PublicKey,
rsaConfig *config.RSAConfig,
) (*SyncService, error) {
// Load vault configuration
vaultConfig, err := vm.GetConfig()
if err != nil {
return nil, fmt.Errorf("failed to load vault configuration: %w", err)
}
s := &SyncService{
host: h,
vaultMgr: vm,
privateKey: privateKey,
publicKey: publicKey,
rsaConfig: rsaConfig,
trustedPeers: make(map[peer.ID]*PeerInfo),
vaultConfig: vaultConfig,
trustAllPeers: true, // Trust all peers by default
}
// Load trusted peers from config
if rsaConfig != nil && rsaConfig.TrustedPeers != nil {
for _, trustedPeer := range rsaConfig.TrustedPeers {
// Parse the peer ID
peerID, err := peer.Decode(trustedPeer.ID)
if err != nil {
fmt.Printf("Warning: Failed to decode peer ID %s: %v\n", trustedPeer.ID, err)
continue
}
// Parse the public key
block, _ := pem.Decode([]byte(trustedPeer.PublicKey))
if block == nil {
fmt.Printf("Warning: Failed to decode public key for peer %s\n", trustedPeer.ID)
continue
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
fmt.Printf("Warning: Failed to parse public key for peer %s: %v\n", trustedPeer.ID, err)
continue
}
rsaPublicKey, ok := pub.(*rsa.PublicKey)
if !ok {
fmt.Printf("Warning: Public key for peer %s is not an RSA key\n", trustedPeer.ID)
continue
}
// Add to trusted peers map
s.trustedPeers[peerID] = &PeerInfo{
ID: peerID,
PublicKey: rsaPublicKey,
Fingerprint: trustedPeer.Fingerprint,
Name: trustedPeer.Name,
TrustedSince: trustedPeer.TrustedSince,
}
}
}
// Register all protocol handlers including secure ones
s.RegisterProtocols(context.Background())
return s, nil
}
// RegisterProtocols sets up all protocol handlers
func (s *SyncService) RegisterProtocols(ctx context.Context) {
// Register basic protocol handlers
s.host.SetStreamHandler(protocol.ID(ManifestProtocolID), s.handleManifestRequest)
s.host.SetStreamHandler(protocol.ID(ManifestProtocolIDv0), s.handleManifestRequest) // Support fallback version
s.host.SetStreamHandler(protocol.ID(ChunkProtocolID), s.handleChunkRequest)
// Register secure protocol handlers
if s.privateKey != nil {
s.host.SetStreamHandler(protocol.ID(KeyExchangeProtocol), s.handleKeyExchange)
s.host.SetStreamHandler(protocol.ID(AuthProtocol), s.handleAuthentication)
}
}
// SetTrustAllPeers sets whether to automatically trust all peers
func (s *SyncService) SetTrustAllPeers(trustAll bool) {
s.trustAllPeers = trustAll
fmt.Printf("Trust all peers set to: %v\n", trustAll)
}
// handleKeyExchange handles key exchange requests from peers
// handleKeyExchange handles key exchange requests from peers
func (s *SyncService) handleKeyExchange(stream network.Stream) {
defer stream.Close()
if s.publicKey == nil {
fmt.Println("Cannot perform key exchange: no public key available")
return
}
// Use connection deadline instead of separate read/write deadlines
_ = stream.SetReadDeadline(time.Now().Add(30 * time.Second))
_ = stream.SetWriteDeadline(time.Now().Add(30 * time.Second))
// Read peer's public key in chunks
var pemData []byte
buffer := make([]byte, 1024)
for {
n, err := stream.Read(buffer)
if err == io.EOF {
break
}
if err != nil {
fmt.Printf("Error reading peer's public key: %v\n", err)
return
}
pemData = append(pemData, buffer[:n]...)
// Check if we have a complete PEM block
if block, _ := pem.Decode(pemData); block != nil {
// If we got a complete block, we can stop reading
break
}
}
// Parse peer's public key
block, _ := pem.Decode(pemData)
if block == nil {
fmt.Println("Failed to decode peer's public key: empty block")
return
}
// Support different key formats
var peerPubKey *rsa.PublicKey
var err error
switch block.Type {
case "RSA PUBLIC KEY":
// Try PKCS1 format
directKey, err := x509.ParsePKCS1PublicKey(block.Bytes)
if err != nil {
fmt.Printf("Failed to parse as PKCS1: %v\n", err)
} else {
peerPubKey = directKey
}
case "PUBLIC KEY":
// Try PKIX format
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
fmt.Printf("Failed to parse peer's public key: %v\n", err)
return
}
var ok bool
peerPubKey, ok = pub.(*rsa.PublicKey)
if !ok {
fmt.Println("Peer's key is not an RSA public key")
return
}
default:
fmt.Printf("Unknown key format: %s\n", block.Type)
return
}
// Calculate fingerprint
publicKeyDER, err := x509.MarshalPKIXPublicKey(peerPubKey)
if err != nil {
fmt.Printf("Failed to marshal peer's public key: %v\n", err)
return
}
hash := sha256.Sum256(publicKeyDER)
fingerprint := base64.StdEncoding.EncodeToString(hash[:])
// Send our public key in response
ourPublicKeyDER, err := x509.MarshalPKIXPublicKey(s.publicKey)
if err != nil {
fmt.Printf("Failed to marshal our public key: %v\n", err)
return
}
ourPublicKeyBlock := &pem.Block{
Type: "PUBLIC KEY",
Bytes: ourPublicKeyDER,
}
ourPubKeyPEM := pem.EncodeToMemory(ourPublicKeyBlock)
_, err = stream.Write(ourPubKeyPEM)
if err != nil {
fmt.Printf("Failed to send our public key: %v\n", err)
return
}
// Store peer info automatically
peerID := stream.Conn().RemotePeer()
s.trustedPeers[peerID] = &PeerInfo{
ID: peerID,
PublicKey: peerPubKey,
Fingerprint: fingerprint,
TrustedSince: time.Now(),
}
fmt.Printf("Key exchange completed with peer %s (fingerprint: %s)\n", peerID.String(), fingerprint)
}
// handleAuthentication handles authentication requests from peers
func (s *SyncService) handleAuthentication(stream network.Stream) {
defer stream.Close()
// Read challenge with timeout
_ = stream.SetReadDeadline(time.Now().Add(30 * time.Second))
var challenge struct {
Challenge []byte `json:"challenge"`
Sender string `json:"sender"`
}
if err := json.NewDecoder(stream).Decode(&challenge); err != nil {
fmt.Printf("Error reading authentication challenge: %v\n", err)
return
}
// Sign the challenge with our private key
challengeHash := sha256.Sum256(challenge.Challenge)
signature, err := rsa.SignPKCS1v15(rand.Reader, s.privateKey, crypto.SHA256, challengeHash[:])
if err != nil {
fmt.Printf("Error signing challenge: %v\n", err)
return
}
// Send response with timeout
_ = stream.SetWriteDeadline(time.Now().Add(30 * time.Second))
response := struct {
Signature []byte `json:"signature"`
VaultID string `json:"vault_id"`
Name string `json:"name"`
}{
Signature: signature,
VaultID: s.vaultConfig.VaultID,
Name: s.vaultConfig.Name,
}
if err := json.NewEncoder(stream).Encode(response); err != nil {
fmt.Printf("Error sending authentication response: %v\n", err)
}
}
// handleManifestRequest processes requests for vault manifests
func (s *SyncService) handleManifestRequest(stream network.Stream) {
defer stream.Close()
peerID := stream.Conn().RemotePeer()
// If we have RSA keys and not trusting all peers, verify the peer is trusted
if s.privateKey != nil && !s.trustAllPeers {
if _, ok := s.trustedPeers[peerID]; !ok {
fmt.Printf("Rejecting manifest request from untrusted peer: %s\n", peerID.String())
// Send error response
errorResponse := struct {
Error string `json:"error"`
}{
Error: "Unauthorized: Peer not trusted",
}
_ = json.NewEncoder(stream).Encode(errorResponse)
return
}
}
// Get our vault manifest
manifest, err := s.vaultMgr.GetManifest()
if err != nil {
fmt.Printf("Error getting manifest: %v\n", err)
// Send error response
errorResponse := struct {
Error string `json:"error"`
}{
Error: "Internal error getting manifest",
}
_ = json.NewEncoder(stream).Encode(errorResponse)
return
}
// Prepare response with correct structure
response := struct {
Files []*config.FileManifest `json:"files"`
Error string `json:"error,omitempty"`
}{
Files: make([]*config.FileManifest, len(manifest.Files)),
}
// Convert from value to pointer slices
for i := range manifest.Files {
fileCopy := manifest.Files[i] // Create a copy to avoid aliasing issues
response.Files[i] = &fileCopy
}
// Encode and send the manifest with timeout
_ = stream.SetWriteDeadline(time.Now().Add(30 * time.Second))
if err := json.NewEncoder(stream).Encode(response); err != nil {
fmt.Printf("Error sending manifest: %v\n", err)
}
}
// handleChunkRequest processes requests for chunks
func (s *SyncService) handleChunkRequest(stream network.Stream) {
defer stream.Close()
peerID := stream.Conn().RemotePeer()
// If we have RSA keys and not trusting all peers, verify the peer is trusted
var peerInfo *PeerInfo
if s.privateKey != nil && !s.trustAllPeers {
var ok bool
peerInfo, ok = s.trustedPeers[peerID]
if !ok {
fmt.Printf("Rejecting chunk request from untrusted peer: %s\n", peerID.String())
// Send error response
errorResponse := struct {
Error string `json:"error"`
}{
Error: "Unauthorized: Peer not trusted",
}
_ = json.NewEncoder(stream).Encode(errorResponse)
return
}
}
// Read the chunk hash with timeout
_ = stream.SetReadDeadline(time.Now().Add(30 * time.Second))
var chunkRequest struct {
Hash string `json:"hash"`
EncryptedHash string `json:"encrypted_hash,omitempty"`
IsEncrypted bool `json:"is_encrypted"`
}
if err := json.NewDecoder(stream).Decode(&chunkRequest); err != nil {
fmt.Printf("Error reading chunk request: %v\n", err)
return
}
// First try using the primary hash
chunkHash := chunkRequest.Hash
fmt.Printf("Looking for chunk with hash: %s\n", chunkHash)
chunkData, err := s.vaultMgr.GetChunk(chunkHash)
// If that fails and we have an encrypted hash, try that
if err != nil && chunkRequest.EncryptedHash != "" {
fmt.Printf("Chunk not found, trying encrypted hash: %s\n", chunkRequest.EncryptedHash)
chunkData, err = s.vaultMgr.GetChunk(chunkRequest.EncryptedHash)
if err == nil {
fmt.Printf("Found chunk using encrypted hash\n")
}
}
// If still not found, return error
if err != nil {
fmt.Printf("Chunk not found with either hash\n")
response := struct {
Error string `json:"error"`
}{
Error: "Chunk not found",
}
_ = json.NewEncoder(stream).Encode(response)
return
}
// If using RSA encryption, encrypt the chunk for the recipient
var encryptedData []byte
if s.privateKey != nil && peerInfo != nil && peerInfo.PublicKey != nil {
encryptedData = s.encryptLargeData(chunkData, peerInfo.PublicKey)
} else {
encryptedData = chunkData
}
// Send the chunk data with timeout
_ = stream.SetWriteDeadline(time.Now().Add(30 * time.Second))
response := struct {
Size int `json:"size"`
Data []byte `json:"data"`
Encrypted bool `json:"encrypted"`
}{
Size: len(chunkData),
Data: encryptedData,
Encrypted: (s.privateKey != nil && peerInfo != nil),
}
if err := json.NewEncoder(stream).Encode(response); err != nil {
fmt.Printf("Error sending chunk: %v\n", err)
}
}
// encryptLargeData encrypts data that may be larger than RSA can handle in one block
func (s *SyncService) encryptLargeData(data []byte, publicKey *rsa.PublicKey) []byte {
result := []byte{}
// Calculate max chunk size based on key size (with overhead for PKCS#1v15 padding)
maxChunkSize := (publicKey.Size() - 11)
// Process data in chunks
for i := 0; i < len(data); i += maxChunkSize {
end := i + maxChunkSize
if end > len(data) {
end = len(data)
}
chunk := data[i:end]
encryptedChunk, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, chunk)
if err != nil {
fmt.Printf("Error encrypting chunk: %v\n", err)
continue
}
// Add encrypted chunk to result
result = append(result, encryptedChunk...)
}
return result
}
// decryptLargeData decrypts data that was encrypted in chunks
func (s *SyncService) decryptLargeData(data []byte) []byte {
result := []byte{}
// Process data in chunks based on key size
chunkSize := s.privateKey.Size()
for i := 0; i < len(data); i += chunkSize {
end := min(i+chunkSize, len(data))
chunk := data[i:end]
if len(chunk) < chunkSize {
fmt.Printf("Warning: Incomplete chunk size %d vs %d\n", len(chunk), chunkSize)
continue
}
decryptedChunk, err := rsa.DecryptPKCS1v15(rand.Reader, s.privateKey, chunk)
if err != nil {
fmt.Printf("Error decrypting chunk: %v\n", err)
continue
}
// Add decrypted chunk to result
result = append(result, decryptedChunk...)
}
return result
}
// VerifyAndExchangeKeys performs key exchange with a peer
func (s *SyncService) VerifyAndExchangeKeys(ctx context.Context, peerID peer.ID) (bool, error) {
// Don't return early with trustAllPeers, just mark for later
needsKeyExchange := true
autoTrust := s.trustAllPeers
// Check if already trusted
if _, ok := s.trustedPeers[peerID]; ok {
autoTrust = true
// We might still need to exchange keys if fingerprint is missing
if s.trustedPeers[peerID].Fingerprint != "" && s.trustedPeers[peerID].PublicKey != nil {
needsKeyExchange = false
}
}
// If no RSA keys, return true (no verification needed)
if s.privateKey == nil {
return true, nil
}
// Do key exchange if needed
if needsKeyExchange {
// Create stream and exchange keys as in original code
timeoutCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
stream, err := s.host.NewStream(timeoutCtx, peerID, protocol.ID(KeyExchangeProtocol))
if err != nil {
// Check if we already have peer info from reverse connection
if peerInfo, ok := s.trustedPeers[peerID]; ok && peerInfo.Fingerprint != "" {
fmt.Printf("Failed to open stream, but have fingerprint from reverse connection: %s\n", peerInfo.Fingerprint)
return true, nil
}
return false, fmt.Errorf("failed to open key exchange stream: %w", err)
}
defer stream.Close()
// Use connection deadline instead of separate read/write deadlines
_ = stream.SetReadDeadline(time.Now().Add(30 * time.Second))
_ = stream.SetWriteDeadline(time.Now().Add(30 * time.Second))
// Send our public key
publicKeyDER, err := x509.MarshalPKIXPublicKey(s.publicKey)
if err != nil {
return false, fmt.Errorf("failed to marshal public key: %w", err)
}
publicKeyBlock := &pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyDER,
}
publicKeyPEM := pem.EncodeToMemory(publicKeyBlock)
_, err = stream.Write(publicKeyPEM)
if err != nil {
return false, fmt.Errorf("failed to send public key: %w", err)
}
// Read peer's public key in chunks
var pemData []byte
buffer := make([]byte, 1024)
for {
n, err := stream.Read(buffer)
if err == io.EOF {
break
}
if err != nil {
// Check if we already have peer info from reverse connection
if peerInfo, ok := s.trustedPeers[peerID]; ok && peerInfo.Fingerprint != "" {
fmt.Printf("Read error, but have fingerprint from reverse connection: %s\n", peerInfo.Fingerprint)
return true, nil
}
return false, fmt.Errorf("failed reading key data: %w", err)
}
pemData = append(pemData, buffer[:n]...)
// Check if we have a complete PEM block
if block, _ := pem.Decode(pemData); block != nil {
// If we got a complete block, we can stop reading
break
}
}
// Parse peer's public key
block, _ := pem.Decode(pemData)
if block == nil {
// Check if we already have peer info from reverse connection
if peerInfo, ok := s.trustedPeers[peerID]; ok && peerInfo.Fingerprint != "" {
fmt.Printf("Failed to decode PEM block, but have fingerprint from reverse connection: %s\n", peerInfo.Fingerprint)
return true, nil
}
return false, fmt.Errorf("failed to decode peer's public key: empty block")
}
// Support different key formats
var peerPubKey *rsa.PublicKey
var pub interface{}
switch block.Type {
case "RSA PUBLIC KEY":
// Try PKCS1 format
directKey, err := x509.ParsePKCS1PublicKey(block.Bytes)
if err != nil {
fmt.Printf("Failed to parse as PKCS1: %v\n", err)
} else {
peerPubKey = directKey
}
case "PUBLIC KEY":
// Try PKIX format
pub, err = x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return false, fmt.Errorf("failed to parse PKIX public key: %w", err)
}
var ok bool
peerPubKey, ok = pub.(*rsa.PublicKey)
if !ok {
return false, fmt.Errorf("peer's key is not an RSA public key")
}
default:
return false, fmt.Errorf("unknown key format: %s", block.Type)
}
// Calculate fingerprint
peerKeyDER, err := x509.MarshalPKIXPublicKey(peerPubKey)
if err != nil {
return false, fmt.Errorf("failed to marshal peer's public key: %w", err)
}
hash := sha256.Sum256(peerKeyDER)
fingerprint := base64.StdEncoding.EncodeToString(hash[:])
// Store peer info
s.trustedPeers[peerID] = &PeerInfo{
ID: peerID,
PublicKey: peerPubKey,
Fingerprint: fingerprint,
TrustedSince: time.Now(),
}
}
// Auto-trust if configured to do so
if autoTrust {
return true, nil
}
// Perform authentication challenge
if err := s.authenticatePeer(ctx, peerID); err != nil {
delete(s.trustedPeers, peerID)
return false, fmt.Errorf("authentication failed: %w", err)
}
return true, nil
}
// authenticatePeer sends an authentication challenge to verify peer identity
func (s *SyncService) authenticatePeer(ctx context.Context, peerID peer.ID) error {
// Create a context with timeout
timeoutCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
stream, err := s.host.NewStream(timeoutCtx, peerID, protocol.ID(AuthProtocol))
if err != nil {
return fmt.Errorf("failed to open authentication stream: %w", err)
}
defer stream.Close()
// Generate random challenge
challenge := make([]byte, 32)
_, err = rand.Read(challenge)
if err != nil {
return fmt.Errorf("failed to generate challenge: %w", err)
}
// Send challenge with timeout
_ = stream.SetWriteDeadline(time.Now().Add(30 * time.Second))
request := struct {
Challenge []byte `json:"challenge"`
Sender string `json:"sender"`
}{
Challenge: challenge,
Sender: s.vaultConfig.VaultID,
}
if err := json.NewEncoder(stream).Encode(request); err != nil {
return fmt.Errorf("failed to send challenge: %w", err)
}
// Read response with timeout
_ = stream.SetReadDeadline(time.Now().Add(30 * time.Second))
var response struct {
Signature []byte `json:"signature"`
VaultID string `json:"vault_id"`
Name string `json:"name"`
}
if err := json.NewDecoder(stream).Decode(&response); err != nil {
return fmt.Errorf("failed to read auth response: %w", err)
}
// Get peer's public key
peerInfo, ok := s.trustedPeers[peerID]
if !ok {
return fmt.Errorf("peer not found in trusted list")
}
// Verify signature
challengeHash := sha256.Sum256(challenge)
err = rsa.VerifyPKCS1v15(peerInfo.PublicKey, crypto.SHA256, challengeHash[:], response.Signature)
if err != nil {
return fmt.Errorf("signature verification failed: %w", err)
}
// Update peer info with vault details
peerInfo.Name = response.Name
return nil
}
// GetPeerFingerprint returns the fingerprint of a peer's public key
func (s *SyncService) GetPeerFingerprint(peerID peer.ID) (string, error) {
peerInfo, ok := s.trustedPeers[peerID]
if !ok {
return "", fmt.Errorf("peer not found in trusted list")
}
return peerInfo.Fingerprint, nil
}
// AddTrustedPeer adds a peer to the trusted peers list and saves to config
func (s *SyncService) AddTrustedPeer(ctx context.Context, peerID peer.ID) error {
peerInfo, ok := s.trustedPeers[peerID]
if !ok {
return fmt.Errorf("peer not found in temporary trusted list")
}
// Add to permanent trusted peers in config
if s.rsaConfig != nil && peerInfo.PublicKey != nil {
// First, check if this peer already exists in the trusted peers list
if s.rsaConfig.TrustedPeers == nil {
s.rsaConfig.TrustedPeers = []config.TrustedPeer{}
}
// Check for existing peer by ID or fingerprint
existingPeer := false
for _, peer := range s.rsaConfig.TrustedPeers {
if peer.ID == peerID.String() || peer.Fingerprint == peerInfo.Fingerprint {
existingPeer = true
fmt.Printf("Peer already in trusted list (ID: %s, Fingerprint: %s)\n",
peer.ID, peer.Fingerprint)
break
}
}
if existingPeer {
// Peer already exists, no need to add again
return nil
}
// Convert public key to PEM
publicKeyDER, err := x509.MarshalPKIXPublicKey(peerInfo.PublicKey)
if err != nil {
return fmt.Errorf("failed to marshal public key: %w", err)
}
publicKeyBlock := &pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyDER,
}
publicKeyPEM := string(pem.EncodeToMemory(publicKeyBlock))
// Create trusted peer entry
trustedPeer := config.TrustedPeer{
ID: peerID.String(),
Name: peerInfo.Name,
PublicKey: publicKeyPEM,
Fingerprint: peerInfo.Fingerprint,
TrustedSince: time.Now(),
}
// Add to config
s.rsaConfig.TrustedPeers = append(s.rsaConfig.TrustedPeers, trustedPeer)
// Make sure vaultConfig is updated with the latest rsaConfig
if s.vaultConfig != nil {
s.vaultConfig.Sync.RSA = s.rsaConfig
}
// Save updated config
if err := s.vaultMgr.SaveConfig(s.vaultConfig); err != nil {
return fmt.Errorf("failed to save updated config: %w", err)
}
// // Pretty print newly trusted peer
// data, err := yaml.Marshal(trustedPeer)
// if err != nil {
// fmt.Printf("ERROR: Failed to marshal trusted peer: %v\n", err)
// } else {
// fmt.Println("=========== NEW TRUSTED PEER ===========")
// fmt.Println(string(data))
// fmt.Println("=========== END TRUSTED PEER ===========")
// }
}
return nil
}
// SyncWithPeer performs a sync operation with a specific peer
func (s *SyncService) SyncWithPeer(ctx context.Context, peerID peer.ID) (*SyncResult, error) {
// Create a context with timeout for the entire operation
timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
startTime := time.Now()
result := &SyncResult{}
// First verify and exchange keys with peer (will auto-trust if trustAllPeers is true)
fmt.Printf("Starting key verification with peer %s...\n", peerID.String())
trusted, err := s.VerifyAndExchangeKeys(timeoutCtx, peerID)
if err != nil {
return nil, fmt.Errorf("key exchange failed: %w", err)
}
if !trusted {
return nil, fmt.Errorf("peer %s is not trusted", peerID.String())
}
fmt.Printf("Peer %s is trusted, proceeding with sync\n", peerID.String())
// Step 1: Get remote manifest
fmt.Printf("Retrieving manifest from peer %s...\n", peerID.String())
remoteManifest, err := s.getRemoteManifest(timeoutCtx, peerID)
if err != nil {
return nil, fmt.Errorf("failed to get remote manifest: %v", err)
}
fmt.Printf("Retrieved manifest from peer with %d files\n", len(remoteManifest.Files))
// Step 2: Get local manifest
localManifest, err := s.vaultMgr.GetManifest()
if err != nil {
return nil, fmt.Errorf("failed to get local manifest: %v", err)
}
// Step 3: Find missing chunks
missingChunks := s.findMissingChunks(localManifest, remoteManifest)
fmt.Printf("Found %d missing chunks to fetch\n", len(missingChunks))
// Step 4: Fetch missing chunks
for i, chunkHash := range missingChunks {
if i%10 == 0 {
fmt.Printf("Fetching chunk %d of %d...\n", i+1, len(missingChunks))
}
exists, _ := s.vaultMgr.ChunkExists(chunkHash)
if exists {
result.ChunksDeduplicated++
continue
}
// Find associated encrypted hash if any
var encryptedHash string
for _, file := range remoteManifest.Files {
for _, chunk := range file.Chunks {
if chunk.Hash == chunkHash && chunk.EncryptedHash != "" {
encryptedHash = chunk.EncryptedHash
break
}
}
if encryptedHash != "" {
break
}
}
// Pass the encrypted hash directly to fetchChunk
chunkData, size, err := s.fetchChunk(timeoutCtx, peerID, chunkHash, encryptedHash)
if err != nil {
return nil, fmt.Errorf("failed to fetch chunk %s: %v", chunkHash, err)
}
// Store the chunk with both hashes if needed
if err := s.StoreChunk(chunkHash, chunkData, encryptedHash); err != nil {
return nil, fmt.Errorf("failed to store chunk %s: %v", chunkHash, err)
}
result.ChunksTransferred++
result.BytesTransferred += int64(size)
}
// Step 5: Save file manifests for synced files
fmt.Println("Saving file manifests...")
savedCount := 0
for _, remoteFile := range remoteManifest.Files {
// Check if this file already exists locally
exists := false
for _, localFile := range localManifest.Files {
if localFile.FilePath == remoteFile.FilePath {
exists = true
break
}
}
if !exists {
// Create a copy of the file manifest to avoid pointer issues
fileManifest := remoteFile
err := manifest.StoreFileManifest(
s.vaultMgr.VaultRoot(),
fileManifest.FilePath,
&fileManifest,
)
if err != nil {
return nil, fmt.Errorf("failed to save manifest for %s: %v",
fileManifest.FilePath, err)
}
fmt.Printf("Saved manifest for: %s\n", fileManifest.FilePath)
savedCount++
}
}
fmt.Printf("Saved %d file manifests\n", savedCount)
result.FileCount = savedCount
// Step 6: Rebuild references
if err := s.vaultMgr.RebuildReferences(); err != nil {
return nil, fmt.Errorf("failed to rebuild references: %v", err)
}
result.Duration = time.Since(startTime)
fmt.Printf("Sync completed in %v: %d files, %d chunks transferred, %d chunks reused\n",
result.Duration, result.FileCount, result.ChunksTransferred, result.ChunksDeduplicated)
return result, nil
}
// getRemoteManifest fetches the manifest from a remote peer
func (s *SyncService) getRemoteManifest(ctx context.Context, peerID peer.ID) (*config.Manifest, error) {
// Create a context with timeout
timeoutCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// Try current protocol version first
stream, err := s.host.NewStream(timeoutCtx, peerID, protocol.ID(ManifestProtocolID))
// If current version fails, try fallback
if err != nil {
stream, err = s.host.NewStream(timeoutCtx, peerID, protocol.ID(ManifestProtocolIDv0))
if err != nil {
return nil, fmt.Errorf("failed to connect with any protocol version: %w", err)
}
}
defer stream.Close()
// Set read deadline
_ = stream.SetReadDeadline(time.Now().Add(30 * time.Second))
// Read the manifest
var response struct {
Error string `json:"error,omitempty"`
Files []*config.FileManifest `json:"files,omitempty"`
}
if err := json.NewDecoder(stream).Decode(&response); err != nil {
return nil, fmt.Errorf("failed to decode manifest: %w", err)
}
if response.Error != "" {
return nil, fmt.Errorf("remote error: %s", response.Error)
}
valueFiles := make([]config.FileManifest, len(response.Files))
for i, filePtr := range response.Files {