forked from PurpleI2P/i2pd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SSU2Session.cpp
3066 lines (2965 loc) · 109 KB
/
SSU2Session.cpp
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
/*
* Copyright (c) 2022-2024, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <string.h>
#include <openssl/rand.h>
#include "Log.h"
#include "Transports.h"
#include "Gzip.h"
#include "NetDb.hpp"
#include "SSU2.h"
namespace i2p
{
namespace transport
{
void SSU2IncompleteMessage::AttachNextFragment (const uint8_t * fragment, size_t fragmentSize)
{
if (msg->len + fragmentSize > msg->maxLen)
{
LogPrint (eLogInfo, "SSU2: I2NP message size ", msg->maxLen, " is not enough");
auto newMsg = NewI2NPMessage (msg->len + fragmentSize);
*newMsg = *msg;
msg = newMsg;
}
if (msg->Concat (fragment, fragmentSize) < fragmentSize)
LogPrint (eLogError, "SSU2: I2NP buffer overflow ", msg->maxLen);
nextFragmentNum++;
}
bool SSU2IncompleteMessage::ConcatOutOfSequenceFragments ()
{
bool isLast = false;
while (outOfSequenceFragments)
{
if (outOfSequenceFragments->fragmentNum == nextFragmentNum)
{
AttachNextFragment (outOfSequenceFragments->buf, outOfSequenceFragments->len);
isLast = outOfSequenceFragments->isLast;
if (isLast)
outOfSequenceFragments = nullptr;
else
outOfSequenceFragments = outOfSequenceFragments->next;
}
else
break;
}
return isLast;
}
void SSU2IncompleteMessage::AddOutOfSequenceFragment (std::shared_ptr<SSU2IncompleteMessage::Fragment> fragment)
{
if (!fragment || !fragment->fragmentNum) return; // fragment 0 not allowed
if (fragment->fragmentNum < nextFragmentNum) return; // already processed
if (!outOfSequenceFragments)
outOfSequenceFragments = fragment;
else
{
auto frag = outOfSequenceFragments;
std::shared_ptr<Fragment> prev;
do
{
if (fragment->fragmentNum < frag->fragmentNum) break; // found
if (fragment->fragmentNum == frag->fragmentNum) return; // duplicate
prev = frag; frag = frag->next;
}
while (frag);
fragment->next = frag;
if (prev)
prev->next = fragment;
else
outOfSequenceFragments = fragment;
}
lastFragmentInsertTime = i2p::util::GetSecondsSinceEpoch ();
}
SSU2Session::SSU2Session (SSU2Server& server, std::shared_ptr<const i2p::data::RouterInfo> in_RemoteRouter,
std::shared_ptr<const i2p::data::RouterInfo::Address> addr):
TransportSession (in_RemoteRouter, SSU2_CONNECT_TIMEOUT),
m_Server (server), m_Address (addr), m_RemoteTransports (0), m_RemotePeerTestTransports (0),
m_DestConnID (0), m_SourceConnID (0), m_State (eSSU2SessionStateUnknown),
m_SendPacketNum (0), m_ReceivePacketNum (0), m_LastDatetimeSentPacketNum (0),
m_IsDataReceived (false), m_RTT (SSU2_UNKNOWN_RTT),
m_MsgLocalExpirationTimeout (I2NP_MESSAGE_LOCAL_EXPIRATION_TIMEOUT_MAX),
m_MsgLocalSemiExpirationTimeout (I2NP_MESSAGE_LOCAL_EXPIRATION_TIMEOUT_MAX / 2),
m_WindowSize (SSU2_MIN_WINDOW_SIZE),
m_RTO (SSU2_INITIAL_RTO), m_RelayTag (0),m_ConnectTimer (server.GetService ()),
m_TerminationReason (eSSU2TerminationReasonNormalClose),
m_MaxPayloadSize (SSU2_MIN_PACKET_SIZE - IPV6_HEADER_SIZE - UDP_HEADER_SIZE - 32) // min size
{
m_NoiseState.reset (new i2p::crypto::NoiseSymmetricState);
if (in_RemoteRouter && m_Address)
{
// outgoing
InitNoiseXKState1 (*m_NoiseState, m_Address->s);
m_RemoteEndpoint = boost::asio::ip::udp::endpoint (m_Address->host, m_Address->port);
m_RemoteTransports = in_RemoteRouter->GetCompatibleTransports (false);
if (in_RemoteRouter->IsSSU2PeerTesting (true)) m_RemotePeerTestTransports |= i2p::data::RouterInfo::eSSU2V4;
if (in_RemoteRouter->IsSSU2PeerTesting (false)) m_RemotePeerTestTransports |= i2p::data::RouterInfo::eSSU2V6;
RAND_bytes ((uint8_t *)&m_DestConnID, 8);
RAND_bytes ((uint8_t *)&m_SourceConnID, 8);
}
else
{
// incoming
InitNoiseXKState1 (*m_NoiseState, i2p::context.GetSSU2StaticPublicKey ());
}
}
SSU2Session::~SSU2Session ()
{
}
void SSU2Session::Connect ()
{
if (m_State == eSSU2SessionStateUnknown || m_State == eSSU2SessionStateTokenReceived)
{
LogPrint(eLogDebug, "SSU2: Connecting to ", GetRemoteEndpoint (),
" (", i2p::data::GetIdentHashAbbreviation (GetRemoteIdentity ()->GetIdentHash ()), ")");
ScheduleConnectTimer ();
auto token = m_Server.FindOutgoingToken (m_RemoteEndpoint);
if (token)
SendSessionRequest (token);
else
{
m_State = eSSU2SessionStateUnknown;
SendTokenRequest ();
}
}
}
void SSU2Session::ScheduleConnectTimer ()
{
m_ConnectTimer.cancel ();
m_ConnectTimer.expires_from_now (boost::posix_time::seconds(SSU2_CONNECT_TIMEOUT));
m_ConnectTimer.async_wait (std::bind (&SSU2Session::HandleConnectTimer,
shared_from_this (), std::placeholders::_1));
}
void SSU2Session::HandleConnectTimer (const boost::system::error_code& ecode)
{
if (!ecode)
{
// timeout expired
if (m_State == eSSU2SessionStateIntroduced) // WaitForIntroducer
LogPrint (eLogWarning, "SSU2: Session was not introduced after ", SSU2_CONNECT_TIMEOUT, " seconds");
else
LogPrint (eLogWarning, "SSU2: Session with ", m_RemoteEndpoint, " was not established after ", SSU2_CONNECT_TIMEOUT, " seconds");
Terminate ();
}
}
bool SSU2Session::Introduce (std::shared_ptr<SSU2Session> session, uint32_t relayTag)
{
// we are Alice
if (!session || !relayTag) return false;
// find local address to introduce
auto localAddress = session->FindLocalAddress ();
if (!localAddress) return false;
// create nonce
uint32_t nonce;
RAND_bytes ((uint8_t *)&nonce, 4);
auto ts = i2p::util::GetSecondsSinceEpoch ();
// payload
uint8_t payload[SSU2_MAX_PACKET_SIZE];
size_t payloadSize = 0;
payload[0] = eSSU2BlkRelayRequest;
payload[3] = 0; // flag
htobe32buf (payload + 4, nonce);
htobe32buf (payload + 8, relayTag);
htobe32buf (payload + 12, ts);
payload[16] = 2; // ver
size_t asz = CreateEndpoint (payload + 18, m_MaxPayloadSize - 18, boost::asio::ip::udp::endpoint (localAddress->host, localAddress->port));
if (!asz) return false;
payload[17] = asz;
payloadSize += asz + 18;
SignedData s;
s.Insert ((const uint8_t *)"RelayRequestData", 16); // prologue
s.Insert (GetRemoteIdentity ()->GetIdentHash (), 32); // bhash
s.Insert (session->GetRemoteIdentity ()->GetIdentHash (), 32); // chash
s.Insert (payload + 4, 14 + asz); // nonce, relay tag, timestamp, ver, asz and Alice's endpoint
s.Sign (i2p::context.GetPrivateKeys (), payload + payloadSize);
payloadSize += i2p::context.GetIdentity ()->GetSignatureLen ();
htobe16buf (payload + 1, payloadSize - 3); // size
payloadSize += CreatePaddingBlock (payload + payloadSize, m_MaxPayloadSize - payloadSize);
// send
m_RelaySessions.emplace (nonce, std::make_pair (session, ts));
session->m_SourceConnID = htobe64 (((uint64_t)nonce << 32) | nonce);
session->m_DestConnID = ~session->m_SourceConnID;
m_Server.AddSession (session);
SendData (payload, payloadSize);
return true;
}
void SSU2Session::WaitForIntroduction ()
{
m_State = eSSU2SessionStateIntroduced;
ScheduleConnectTimer ();
}
void SSU2Session::ConnectAfterIntroduction ()
{
if (m_State == eSSU2SessionStateIntroduced)
{
// create new connID
uint64_t oldConnID = GetConnID ();
RAND_bytes ((uint8_t *)&m_DestConnID, 8);
RAND_bytes ((uint8_t *)&m_SourceConnID, 8);
// connect
m_State = eSSU2SessionStateTokenReceived;
m_Server.AddPendingOutgoingSession (shared_from_this ());
m_Server.RemoveSession (oldConnID);
Connect ();
}
}
void SSU2Session::SendPeerTest ()
{
// we are Alice
uint32_t nonce;
RAND_bytes ((uint8_t *)&nonce, 4);
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
// session for message 5
auto session = std::make_shared<SSU2Session> (m_Server);
session->SetState (eSSU2SessionStatePeerTest);
m_PeerTests.emplace (nonce, std::make_pair (session, ts/1000));
session->m_SourceConnID = htobe64 (((uint64_t)nonce << 32) | nonce);
session->m_DestConnID = ~session->m_SourceConnID;
m_Server.AddSession (session);
// peer test block
auto packet = m_Server.GetSentPacketsPool ().AcquireShared ();
packet->payloadSize = CreatePeerTestBlock (packet->payload, m_MaxPayloadSize, nonce);
if (packet->payloadSize > 0)
{
packet->payloadSize += CreatePaddingBlock (packet->payload + packet->payloadSize, m_MaxPayloadSize - packet->payloadSize);
uint32_t packetNum = SendData (packet->payload, packet->payloadSize, SSU2_FLAG_IMMEDIATE_ACK_REQUESTED);
packet->sendTime = ts;
m_SentPackets.emplace (packetNum, packet);
LogPrint (eLogDebug, "SSU2: PeerTest msg=1 sent to ", i2p::data::GetIdentHashAbbreviation (GetRemoteIdentity ()->GetIdentHash ()));
}
}
void SSU2Session::SendKeepAlive ()
{
if (IsEstablished ())
{
uint8_t payload[20];
size_t payloadSize = CreatePaddingBlock (payload, 20, 8);
SendData (payload, payloadSize);
}
}
void SSU2Session::Terminate ()
{
if (m_State != eSSU2SessionStateTerminated)
{
m_State = eSSU2SessionStateTerminated;
m_ConnectTimer.cancel ();
m_OnEstablished = nullptr;
if (m_RelayTag)
m_Server.RemoveRelay (m_RelayTag);
m_SentHandshakePacket.reset (nullptr);
m_SessionConfirmedFragment.reset (nullptr);
m_PathChallenge.reset (nullptr);
for (auto& it: m_SendQueue)
it->Drop ();
m_SendQueue.clear ();
SetSendQueueSize (0);
m_SentPackets.clear ();
m_IncompleteMessages.clear ();
m_RelaySessions.clear ();
m_PeerTests.clear ();
m_ReceivedI2NPMsgIDs.clear ();
m_Server.RemoveSession (m_SourceConnID);
transports.PeerDisconnected (shared_from_this ());
auto remoteIdentity = GetRemoteIdentity ();
if (remoteIdentity)
{
LogPrint (eLogDebug, "SSU2: Session with ", GetRemoteEndpoint (),
" (", i2p::data::GetIdentHashAbbreviation (remoteIdentity->GetIdentHash ()), ") terminated");
}
else
{
LogPrint (eLogDebug, "SSU2: Session with ", GetRemoteEndpoint (), " terminated");
}
}
}
void SSU2Session::RequestTermination (SSU2TerminationReason reason)
{
if (m_State == eSSU2SessionStateEstablished || m_State == eSSU2SessionStateClosing)
{
m_TerminationReason = reason;
SendTermination ();
m_State = eSSU2SessionStateClosing;
}
else
Done ();
}
void SSU2Session::Established ()
{
m_State = eSSU2SessionStateEstablished;
m_EphemeralKeys = nullptr;
m_NoiseState.reset (nullptr);
m_SessionConfirmedFragment.reset (nullptr);
m_SentHandshakePacket.reset (nullptr);
m_ConnectTimer.cancel ();
SetTerminationTimeout (SSU2_TERMINATION_TIMEOUT);
transports.PeerConnected (shared_from_this ());
if (m_OnEstablished)
{
m_OnEstablished ();
m_OnEstablished = nullptr;
}
LogPrint(eLogDebug, "SSU2: Session with ", GetRemoteEndpoint (),
" (", i2p::data::GetIdentHashAbbreviation (GetRemoteIdentity ()->GetIdentHash ()), ") established");
}
void SSU2Session::Done ()
{
m_Server.GetService ().post (std::bind (&SSU2Session::Terminate, shared_from_this ()));
}
void SSU2Session::SendLocalRouterInfo (bool update)
{
if (update || !IsOutgoing ())
{
auto s = shared_from_this ();
m_Server.GetService ().post ([s]()
{
if (!s->IsEstablished ()) return;
uint8_t payload[SSU2_MAX_PACKET_SIZE];
size_t payloadSize = s->CreateRouterInfoBlock (payload, s->m_MaxPayloadSize - 32, i2p::context.GetSharedRouterInfo ());
if (payloadSize)
{
if (payloadSize < s->m_MaxPayloadSize)
payloadSize += s->CreatePaddingBlock (payload + payloadSize, s->m_MaxPayloadSize - payloadSize);
s->SendData (payload, payloadSize);
}
else
s->SendFragmentedMessage (CreateDatabaseStoreMsg ());
});
}
}
void SSU2Session::SendI2NPMessages (const std::vector<std::shared_ptr<I2NPMessage> >& msgs)
{
m_Server.GetService ().post (std::bind (&SSU2Session::PostI2NPMessages, shared_from_this (), msgs));
}
void SSU2Session::PostI2NPMessages (std::vector<std::shared_ptr<I2NPMessage> > msgs)
{
if (m_State == eSSU2SessionStateTerminated) return;
uint64_t mts = i2p::util::GetMonotonicMicroseconds ();
bool isSemiFull = false;
if (m_SendQueue.size ())
{
int64_t queueLag = (int64_t)mts - (int64_t)m_SendQueue.front ()->GetEnqueueTime ();
isSemiFull = queueLag > m_MsgLocalSemiExpirationTimeout;
if (isSemiFull)
{
LogPrint (eLogWarning, "SSU2: Outgoing messages queue to ",
i2p::data::GetIdentHashAbbreviation (GetRemoteIdentity ()->GetIdentHash ()),
" is semi-full (size = ", m_SendQueue.size (), ", lag = ", queueLag / 1000, ", rtt = ", (int)m_RTT, ")");
}
}
for (auto it: msgs)
{
if (isSemiFull && it->onDrop)
it->Drop (); // drop earlier because we can handle it
else
{
it->SetEnqueueTime (mts);
m_SendQueue.push_back (std::move (it));
}
}
SendQueue ();
if (m_SendQueue.size () > 0) // windows is full
Resend (i2p::util::GetMillisecondsSinceEpoch ());
SetSendQueueSize (m_SendQueue.size ());
}
bool SSU2Session::SendQueue ()
{
if (!m_SendQueue.empty () && m_SentPackets.size () <= m_WindowSize)
{
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
uint64_t mts = i2p::util::GetMonotonicMicroseconds ();
auto packet = m_Server.GetSentPacketsPool ().AcquireShared ();
size_t ackBlockSize = CreateAckBlock (packet->payload, m_MaxPayloadSize);
bool ackBlockSent = false;
packet->payloadSize += ackBlockSize;
while (!m_SendQueue.empty () && m_SentPackets.size () <= m_WindowSize)
{
auto msg = m_SendQueue.front ();
if (!msg || msg->IsExpired (ts) || msg->GetEnqueueTime() + m_MsgLocalExpirationTimeout < mts)
{
// drop null or expired message
if (msg) msg->Drop ();
m_SendQueue.pop_front ();
continue;
}
size_t len = msg->GetNTCP2Length () + 3;
if (len > m_MaxPayloadSize) // message too long
{
m_SendQueue.pop_front ();
if (SendFragmentedMessage (msg))
ackBlockSent = true;
}
else if (packet->payloadSize + len <= m_MaxPayloadSize)
{
m_SendQueue.pop_front ();
packet->payloadSize += CreateI2NPBlock (packet->payload + packet->payloadSize, m_MaxPayloadSize - packet->payloadSize, std::move (msg));
}
else
{
// create new packet and copy ack block
auto newPacket = m_Server.GetSentPacketsPool ().AcquireShared ();
memcpy (newPacket->payload, packet->payload, ackBlockSize);
newPacket->payloadSize = ackBlockSize;
// complete current packet
if (packet->payloadSize > ackBlockSize) // more than just ack block
{
ackBlockSent = true;
// try to add padding
if (packet->payloadSize + 16 < m_MaxPayloadSize)
packet->payloadSize += CreatePaddingBlock (packet->payload + packet->payloadSize, m_MaxPayloadSize - packet->payloadSize);
}
else
{
// reduce ack block
if (len + 8 < m_MaxPayloadSize)
{
// keep Ack block and drop some ranges
ackBlockSent = true;
packet->payloadSize = m_MaxPayloadSize - len;
if (packet->payloadSize & 0x01) packet->payloadSize--; // make it even
htobe16buf (packet->payload + 1, packet->payloadSize - 3); // new block size
}
else // drop Ack block completely
packet->payloadSize = 0;
// msg fits single packet
m_SendQueue.pop_front ();
packet->payloadSize += CreateI2NPBlock (packet->payload + packet->payloadSize, m_MaxPayloadSize - packet->payloadSize, std::move (msg));
}
// send right a way
uint32_t packetNum = SendData (packet->payload, packet->payloadSize);
packet->sendTime = ts;
m_SentPackets.emplace (packetNum, packet);
packet = newPacket; // just ack block
}
};
if (packet->payloadSize > ackBlockSize)
{
// last
ackBlockSent = true;
if (packet->payloadSize + 16 < m_MaxPayloadSize)
packet->payloadSize += CreatePaddingBlock (packet->payload + packet->payloadSize, m_MaxPayloadSize - packet->payloadSize);
uint32_t packetNum = SendData (packet->payload, packet->payloadSize, SSU2_FLAG_IMMEDIATE_ACK_REQUESTED);
packet->sendTime = ts;
m_SentPackets.emplace (packetNum, packet);
}
return ackBlockSent;
}
return false;
}
bool SSU2Session::SendFragmentedMessage (std::shared_ptr<I2NPMessage> msg)
{
if (!msg) return false;
size_t lastFragmentSize = (msg->GetNTCP2Length () + 3 - m_MaxPayloadSize) % (m_MaxPayloadSize - 8);
size_t extraSize = m_MaxPayloadSize - lastFragmentSize;
bool ackBlockSent = false;
uint32_t msgID;
memcpy (&msgID, msg->GetHeader () + I2NP_HEADER_MSGID_OFFSET, 4);
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
auto packet = m_Server.GetSentPacketsPool ().AcquireShared ();
if (extraSize >= 8)
{
packet->payloadSize = CreateAckBlock (packet->payload, extraSize);
ackBlockSent = true;
if (packet->payloadSize + 12 < m_MaxPayloadSize)
{
uint32_t packetNum = SendData (packet->payload, packet->payloadSize);
packet->sendTime = ts;
m_SentPackets.emplace (packetNum, packet);
packet = m_Server.GetSentPacketsPool ().AcquireShared ();
}
else
extraSize -= packet->payloadSize;
}
size_t offset = extraSize > 0 ? (rand () % extraSize) : 0;
if (offset + packet->payloadSize >= m_MaxPayloadSize) offset = 0;
auto size = CreateFirstFragmentBlock (packet->payload + packet->payloadSize, m_MaxPayloadSize - offset - packet->payloadSize, msg);
if (!size) return false;
extraSize -= offset;
packet->payloadSize += size;
uint32_t firstPacketNum = SendData (packet->payload, packet->payloadSize);
packet->sendTime = ts;
m_SentPackets.emplace (firstPacketNum, packet);
uint8_t fragmentNum = 0;
while (msg->offset < msg->len)
{
offset = extraSize > 0 ? (rand () % extraSize) : 0;
packet = m_Server.GetSentPacketsPool ().AcquireShared ();
packet->payloadSize = CreateFollowOnFragmentBlock (packet->payload, m_MaxPayloadSize - offset, msg, fragmentNum, msgID);
extraSize -= offset;
uint8_t flags = 0;
if (msg->offset >= msg->len && packet->payloadSize + 16 < m_MaxPayloadSize) // last fragment
{
packet->payloadSize += CreatePaddingBlock (packet->payload + packet->payloadSize, m_MaxPayloadSize - packet->payloadSize);
if (fragmentNum > 2) // 3 or more fragments
flags |= SSU2_FLAG_IMMEDIATE_ACK_REQUESTED;
}
uint32_t followonPacketNum = SendData (packet->payload, packet->payloadSize, flags);
packet->sendTime = ts;
m_SentPackets.emplace (followonPacketNum, packet);
}
return ackBlockSent;
}
size_t SSU2Session::Resend (uint64_t ts)
{
// resend handshake packet
if (m_SentHandshakePacket && ts >= m_SentHandshakePacket->sendTime + SSU2_HANDSHAKE_RESEND_INTERVAL)
{
LogPrint (eLogDebug, "SSU2: Resending ", (int)m_State);
ResendHandshakePacket ();
m_SentHandshakePacket->sendTime = ts;
return 0;
}
// resend data packets
if (m_SentPackets.empty ()) return 0;
std::map<uint32_t, std::shared_ptr<SSU2SentPacket> > resentPackets;
for (auto it = m_SentPackets.begin (); it != m_SentPackets.end (); )
if (ts >= it->second->sendTime + (it->second->numResends + 1) * m_RTO)
{
if (it->second->numResends > SSU2_MAX_NUM_RESENDS)
{
LogPrint (eLogInfo, "SSU2: Packet was not Acked after ", it->second->numResends, " attempts. Terminate session");
m_SentPackets.clear ();
m_SendQueue.clear ();
SetSendQueueSize (0);
RequestTermination (eSSU2TerminationReasonTimeout);
return resentPackets.size ();
}
else
{
uint32_t packetNum = SendData (it->second->payload, it->second->payloadSize);
it->second->numResends++;
it->second->sendTime = ts;
resentPackets.emplace (packetNum, it->second);
it = m_SentPackets.erase (it);
}
}
else
it++;
if (!resentPackets.empty ())
{
#if (__cplusplus >= 201703L) // C++ 17 or higher
m_SentPackets.merge (resentPackets);
#else
m_SentPackets.insert (resentPackets.begin (), resentPackets.end ());
#endif
m_WindowSize >>= 1; // /2
if (m_WindowSize < SSU2_MIN_WINDOW_SIZE) m_WindowSize = SSU2_MIN_WINDOW_SIZE;
return resentPackets.size ();
}
return 0;
}
void SSU2Session::ResendHandshakePacket ()
{
if (m_SentHandshakePacket)
{
m_Server.Send (m_SentHandshakePacket->header.buf, 16, m_SentHandshakePacket->headerX, 48,
m_SentHandshakePacket->payload, m_SentHandshakePacket->payloadSize, m_RemoteEndpoint);
if (m_SessionConfirmedFragment && m_State == eSSU2SessionStateSessionConfirmedSent)
// resend second fragment of SessionConfirmed
m_Server.Send (m_SessionConfirmedFragment->header.buf, 16,
m_SessionConfirmedFragment->payload, m_SessionConfirmedFragment->payloadSize, m_RemoteEndpoint);
}
}
bool SSU2Session::ProcessFirstIncomingMessage (uint64_t connID, uint8_t * buf, size_t len)
{
// we are Bob
m_SourceConnID = connID;
Header header;
header.h.connID = connID;
memcpy (header.buf + 8, buf + 8, 8);
header.ll[1] ^= CreateHeaderMask (i2p::context.GetSSU2IntroKey (), buf + (len - 12));
switch (header.h.type)
{
case eSSU2SessionRequest:
ProcessSessionRequest (header, buf, len);
break;
case eSSU2TokenRequest:
ProcessTokenRequest (header, buf, len);
break;
case eSSU2PeerTest:
{
// TODO: remove later
if (len < 32)
{
LogPrint (eLogWarning, "SSU2: PeerTest message too short ", len);
break;
}
const uint8_t nonce[12] = {0};
uint64_t headerX[2];
i2p::crypto::ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, (uint8_t *)headerX);
LogPrint (eLogWarning, "SSU2: Unexpected PeerTest message SourceConnID=", connID, " DestConnID=", headerX[0]);
break;
}
case eSSU2HolePunch:
LogPrint (eLogDebug, "SSU2: Late HolePunch for ", connID);
break;
default:
{
LogPrint (eLogWarning, "SSU2: Unexpected message type ", (int)header.h.type, " from ", m_RemoteEndpoint, " of ", len, " bytes");
return false;
}
}
return true;
}
void SSU2Session::SendSessionRequest (uint64_t token)
{
// we are Alice
m_EphemeralKeys = i2p::transport::transports.GetNextX25519KeysPair ();
m_SentHandshakePacket.reset (new HandshakePacket);
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
m_SentHandshakePacket->sendTime = ts;
Header& header = m_SentHandshakePacket->header;
uint8_t * headerX = m_SentHandshakePacket->headerX,
* payload = m_SentHandshakePacket->payload;
// fill packet
header.h.connID = m_DestConnID; // dest id
RAND_bytes (header.buf + 8, 4); // random packet num
header.h.type = eSSU2SessionRequest;
header.h.flags[0] = 2; // ver
header.h.flags[1] = (uint8_t)i2p::context.GetNetID (); // netID
header.h.flags[2] = 0; // flag
memcpy (headerX, &m_SourceConnID, 8); // source id
memcpy (headerX + 8, &token, 8); // token
memcpy (headerX + 16, m_EphemeralKeys->GetPublicKey (), 32); // X
// payload
payload[0] = eSSU2BlkDateTime;
htobe16buf (payload + 1, 4);
htobe32buf (payload + 3, (ts + 500)/1000);
size_t payloadSize = 7;
if (GetRouterStatus () == eRouterStatusFirewalled && m_Address->IsIntroducer ())
{
// relay tag request
payload[payloadSize] = eSSU2BlkRelayTagRequest;
memset (payload + payloadSize + 1, 0, 2); // size = 0
payloadSize += 3;
}
payloadSize += CreatePaddingBlock (payload + payloadSize, 40 - payloadSize, 1);
// KDF for session request
m_NoiseState->MixHash ({ {header.buf, 16}, {headerX, 16} }); // h = SHA256(h || header)
m_NoiseState->MixHash (m_EphemeralKeys->GetPublicKey (), 32); // h = SHA256(h || aepk);
uint8_t sharedSecret[32];
m_EphemeralKeys->Agree (m_Address->s, sharedSecret);
m_NoiseState->MixKey (sharedSecret);
// encrypt
const uint8_t nonce[12] = {0}; // always 0
i2p::crypto::AEADChaCha20Poly1305 (payload, payloadSize, m_NoiseState->m_H, 32, m_NoiseState->m_CK + 32, nonce, payload, payloadSize + 16, true);
payloadSize += 16;
header.ll[0] ^= CreateHeaderMask (m_Address->i, payload + (payloadSize - 24));
header.ll[1] ^= CreateHeaderMask (m_Address->i, payload + (payloadSize - 12));
i2p::crypto::ChaCha20 (headerX, 48, m_Address->i, nonce, headerX);
m_NoiseState->MixHash (payload, payloadSize); // h = SHA256(h || encrypted payload from Session Request) for SessionCreated
m_SentHandshakePacket->payloadSize = payloadSize;
// send
if (m_State == eSSU2SessionStateTokenReceived || m_Server.AddPendingOutgoingSession (shared_from_this ()))
{
m_State = eSSU2SessionStateSessionRequestSent;
m_HandshakeInterval = ts;
m_Server.Send (header.buf, 16, headerX, 48, payload, payloadSize, m_RemoteEndpoint);
}
else
{
LogPrint (eLogWarning, "SSU2: SessionRequest request to ", m_RemoteEndpoint, " already pending");
Terminate ();
}
}
void SSU2Session::ProcessSessionRequest (Header& header, uint8_t * buf, size_t len)
{
// we are Bob
if (len < 88)
{
LogPrint (eLogWarning, "SSU2: SessionRequest message too short ", len);
return;
}
const uint8_t nonce[12] = {0};
uint8_t headerX[48];
i2p::crypto::ChaCha20 (buf + 16, 48, i2p::context.GetSSU2IntroKey (), nonce, headerX);
memcpy (&m_DestConnID, headerX, 8);
uint64_t token;
memcpy (&token, headerX + 8, 8);
if (!token || token != m_Server.GetIncomingToken (m_RemoteEndpoint))
{
LogPrint (eLogDebug, "SSU2: SessionRequest token mismatch. Retry");
SendRetry ();
return;
}
// KDF for session request
m_NoiseState->MixHash ( { {header.buf, 16}, {headerX, 16} } ); // h = SHA256(h || header)
m_NoiseState->MixHash (headerX + 16, 32); // h = SHA256(h || aepk);
uint8_t sharedSecret[32];
i2p::context.GetSSU2StaticKeys ().Agree (headerX + 16, sharedSecret);
m_NoiseState->MixKey (sharedSecret);
// decrypt
uint8_t * payload = buf + 64;
std::vector<uint8_t> decryptedPayload(len - 80);
if (!i2p::crypto::AEADChaCha20Poly1305 (payload, len - 80, m_NoiseState->m_H, 32,
m_NoiseState->m_CK + 32, nonce, decryptedPayload.data (), decryptedPayload.size (), false))
{
LogPrint (eLogWarning, "SSU2: SessionRequest AEAD verification failed ");
return;
}
m_NoiseState->MixHash (payload, len - 64); // h = SHA256(h || encrypted payload from Session Request) for SessionCreated
// payload
m_State = eSSU2SessionStateSessionRequestReceived;
HandlePayload (decryptedPayload.data (), decryptedPayload.size ());
if (m_TerminationReason == eSSU2TerminationReasonNormalClose)
{
m_Server.AddSession (shared_from_this ());
SendSessionCreated (headerX + 16);
}
else
SendRetry ();
}
void SSU2Session::SendSessionCreated (const uint8_t * X)
{
// we are Bob
m_EphemeralKeys = i2p::transport::transports.GetNextX25519KeysPair ();
m_SentHandshakePacket.reset (new HandshakePacket);
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
m_SentHandshakePacket->sendTime = ts;
uint8_t kh2[32];
i2p::crypto::HKDF (m_NoiseState->m_CK, nullptr, 0, "SessCreateHeader", kh2, 32); // k_header_2 = HKDF(chainKey, ZEROLEN, "SessCreateHeader", 32)
// fill packet
Header& header = m_SentHandshakePacket->header;
uint8_t * headerX = m_SentHandshakePacket->headerX,
* payload = m_SentHandshakePacket->payload;
header.h.connID = m_DestConnID; // dest id
RAND_bytes (header.buf + 8, 4); // random packet num
header.h.type = eSSU2SessionCreated;
header.h.flags[0] = 2; // ver
header.h.flags[1] = (uint8_t)i2p::context.GetNetID (); // netID
header.h.flags[2] = 0; // flag
memcpy (headerX, &m_SourceConnID, 8); // source id
memset (headerX + 8, 0, 8); // token = 0
memcpy (headerX + 16, m_EphemeralKeys->GetPublicKey (), 32); // Y
// payload
size_t maxPayloadSize = m_MaxPayloadSize - 48;
payload[0] = eSSU2BlkDateTime;
htobe16buf (payload + 1, 4);
htobe32buf (payload + 3, (ts + 500)/1000);
size_t payloadSize = 7;
payloadSize += CreateAddressBlock (payload + payloadSize, maxPayloadSize - payloadSize, m_RemoteEndpoint);
if (m_RelayTag)
{
payload[payloadSize] = eSSU2BlkRelayTag;
htobe16buf (payload + payloadSize + 1, 4);
htobe32buf (payload + payloadSize + 3, m_RelayTag);
payloadSize += 7;
}
auto token = m_Server.NewIncomingToken (m_RemoteEndpoint);
if (ts + SSU2_TOKEN_EXPIRATION_THRESHOLD > token.second) // not expired?
{
payload[payloadSize] = eSSU2BlkNewToken;
htobe16buf (payload + payloadSize + 1, 12);
htobe32buf (payload + payloadSize + 3, token.second - SSU2_TOKEN_EXPIRATION_THRESHOLD); // expires
memcpy (payload + payloadSize + 7, &token.first, 8); // token
payloadSize += 15;
}
payloadSize += CreatePaddingBlock (payload + payloadSize, maxPayloadSize - payloadSize);
// KDF for SessionCreated
m_NoiseState->MixHash ( { {header.buf, 16}, {headerX, 16} } ); // h = SHA256(h || header)
m_NoiseState->MixHash (headerX + 16, 32); // h = SHA256(h || bepk);
uint8_t sharedSecret[32];
m_EphemeralKeys->Agree (X, sharedSecret);
m_NoiseState->MixKey (sharedSecret);
// encrypt
const uint8_t nonce[12] = {0}; // always zero
i2p::crypto::AEADChaCha20Poly1305 (payload, payloadSize, m_NoiseState->m_H, 32, m_NoiseState->m_CK + 32, nonce, payload, payloadSize + 16, true);
payloadSize += 16;
m_NoiseState->MixHash (payload, payloadSize); // h = SHA256(h || encrypted Noise payload from Session Created)
header.ll[0] ^= CreateHeaderMask (i2p::context.GetSSU2IntroKey (), payload + (payloadSize - 24));
header.ll[1] ^= CreateHeaderMask (kh2, payload + (payloadSize - 12));
i2p::crypto::ChaCha20 (headerX, 48, kh2, nonce, headerX);
m_State = eSSU2SessionStateSessionCreatedSent;
m_SentHandshakePacket->payloadSize = payloadSize;
// send
m_HandshakeInterval = ts;
m_Server.Send (header.buf, 16, headerX, 48, payload, payloadSize, m_RemoteEndpoint);
}
bool SSU2Session::ProcessSessionCreated (uint8_t * buf, size_t len)
{
// we are Alice
Header header;
memcpy (header.buf, buf, 16);
header.ll[0] ^= CreateHeaderMask (m_Address->i, buf + (len - 24));
uint8_t kh2[32];
i2p::crypto::HKDF (m_NoiseState->m_CK, nullptr, 0, "SessCreateHeader", kh2, 32); // k_header_2 = HKDF(chainKey, ZEROLEN, "SessCreateHeader", 32)
header.ll[1] ^= CreateHeaderMask (kh2, buf + (len - 12));
if (header.h.type != eSSU2SessionCreated)
// this situation is valid, because it might be Retry with different encryption
return false;
if (len < 80)
{
LogPrint (eLogWarning, "SSU2: SessionCreated message too short ", len);
return false;
}
m_HandshakeInterval = i2p::util::GetMillisecondsSinceEpoch () - m_HandshakeInterval;
const uint8_t nonce[12] = {0};
uint8_t headerX[48];
i2p::crypto::ChaCha20 (buf + 16, 48, kh2, nonce, headerX);
// KDF for SessionCreated
m_NoiseState->MixHash ( { {header.buf, 16}, {headerX, 16} } ); // h = SHA256(h || header)
m_NoiseState->MixHash (headerX + 16, 32); // h = SHA256(h || bepk);
uint8_t sharedSecret[32];
m_EphemeralKeys->Agree (headerX + 16, sharedSecret);
m_NoiseState->MixKey (sharedSecret);
// decrypt
uint8_t * payload = buf + 64;
std::vector<uint8_t> decryptedPayload(len - 80);
if (!i2p::crypto::AEADChaCha20Poly1305 (payload, len - 80, m_NoiseState->m_H, 32,
m_NoiseState->m_CK + 32, nonce, decryptedPayload.data (), decryptedPayload.size (), false))
{
LogPrint (eLogWarning, "SSU2: SessionCreated AEAD verification failed ");
if (GetRemoteIdentity ())
i2p::data::netdb.SetUnreachable (GetRemoteIdentity ()->GetIdentHash (), true); // assume wrong s key
return false;
}
m_NoiseState->MixHash (payload, len - 64); // h = SHA256(h || encrypted payload from SessionCreated) for SessionConfirmed
// payload
m_State = eSSU2SessionStateSessionCreatedReceived;
HandlePayload (decryptedPayload.data (), decryptedPayload.size ());
m_Server.AddSession (shared_from_this ());
AdjustMaxPayloadSize ();
SendSessionConfirmed (headerX + 16);
KDFDataPhase (m_KeyDataSend, m_KeyDataReceive);
return true;
}
void SSU2Session::SendSessionConfirmed (const uint8_t * Y)
{
// we are Alice
m_SentHandshakePacket.reset (new HandshakePacket);
m_SentHandshakePacket->sendTime = i2p::util::GetMillisecondsSinceEpoch ();
uint8_t kh2[32];
i2p::crypto::HKDF (m_NoiseState->m_CK, nullptr, 0, "SessionConfirmed", kh2, 32); // k_header_2 = HKDF(chainKey, ZEROLEN, "SessionConfirmed", 32)
// fill packet
Header& header = m_SentHandshakePacket->header;
header.h.connID = m_DestConnID; // dest id
header.h.packetNum = 0; // always zero
header.h.type = eSSU2SessionConfirmed;
memset (header.h.flags, 0, 3);
header.h.flags[0] = 1; // frag, total fragments always 1
// payload
size_t maxPayloadSize = m_MaxPayloadSize - 48; // for part 2, 48 is part1
uint8_t * payload = m_SentHandshakePacket->payload;
size_t payloadSize = CreateRouterInfoBlock (payload, maxPayloadSize, i2p::context.GetSharedRouterInfo ());
if (!payloadSize)
{
// split by two fragments
maxPayloadSize += m_MaxPayloadSize;
payloadSize = CreateRouterInfoBlock (payload, maxPayloadSize, i2p::context.GetSharedRouterInfo ());
header.h.flags[0] = 0x02; // frag 0, total fragments 2
// TODO: check if we need more fragments
}
if (payloadSize < maxPayloadSize)
payloadSize += CreatePaddingBlock (payload + payloadSize, maxPayloadSize - payloadSize);
// KDF for Session Confirmed part 1
m_NoiseState->MixHash (header.buf, 16); // h = SHA256(h || header)
// Encrypt part 1
uint8_t * part1 = m_SentHandshakePacket->headerX;
uint8_t nonce[12];
CreateNonce (1, nonce); // always one
i2p::crypto::AEADChaCha20Poly1305 (i2p::context.GetSSU2StaticPublicKey (), 32, m_NoiseState->m_H, 32, m_NoiseState->m_CK + 32, nonce, part1, 48, true);
m_NoiseState->MixHash (part1, 48); // h = SHA256(h || ciphertext);
// KDF for Session Confirmed part 2
uint8_t sharedSecret[32];
i2p::context.GetSSU2StaticKeys ().Agree (Y, sharedSecret);
m_NoiseState->MixKey (sharedSecret);
// Encrypt part2
memset (nonce, 0, 12); // always zero
i2p::crypto::AEADChaCha20Poly1305 (payload, payloadSize, m_NoiseState->m_H, 32, m_NoiseState->m_CK + 32, nonce, payload, payloadSize + 16, true);
payloadSize += 16;
m_NoiseState->MixHash (payload, payloadSize); // h = SHA256(h || ciphertext);
m_SentHandshakePacket->payloadSize = payloadSize;
if (header.h.flags[0] > 1)
{
if (payloadSize > m_MaxPayloadSize - 48)
{
payloadSize = m_MaxPayloadSize - 48 - (rand () % 16);
if (m_SentHandshakePacket->payloadSize - payloadSize < 24)
payloadSize -= 24;
}
else
header.h.flags[0] = 1;
}
// Encrypt header
header.ll[0] ^= CreateHeaderMask (m_Address->i, payload + (payloadSize - 24));
header.ll[1] ^= CreateHeaderMask (kh2, payload + (payloadSize - 12));
m_State = eSSU2SessionStateSessionConfirmedSent;
// send
m_Server.Send (header.buf, 16, part1, 48, payload, payloadSize, m_RemoteEndpoint);
m_SendPacketNum++;
if (m_SentHandshakePacket->payloadSize > payloadSize)
{
// send second fragment
m_SessionConfirmedFragment.reset (new HandshakePacket);
Header& header = m_SessionConfirmedFragment->header;
header.h.connID = m_DestConnID; // dest id
header.h.packetNum = 0;
header.h.type = eSSU2SessionConfirmed;
memset (header.h.flags, 0, 3);
header.h.flags[0] = 0x12; // frag 1, total fragments 2
m_SessionConfirmedFragment->payloadSize = m_SentHandshakePacket->payloadSize - payloadSize;
memcpy (m_SessionConfirmedFragment->payload, m_SentHandshakePacket->payload + payloadSize, m_SessionConfirmedFragment->payloadSize);
m_SentHandshakePacket->payloadSize = payloadSize;
header.ll[0] ^= CreateHeaderMask (m_Address->i, m_SessionConfirmedFragment->payload + (m_SessionConfirmedFragment->payloadSize - 24));
header.ll[1] ^= CreateHeaderMask (kh2, m_SessionConfirmedFragment->payload + (m_SessionConfirmedFragment->payloadSize - 12));
m_Server.Send (header.buf, 16, m_SessionConfirmedFragment->payload, m_SessionConfirmedFragment->payloadSize, m_RemoteEndpoint);
}
}
bool SSU2Session::ProcessSessionConfirmed (uint8_t * buf, size_t len)
{
// we are Bob
Header header;
memcpy (header.buf, buf, 16);
header.ll[0] ^= CreateHeaderMask (i2p::context.GetSSU2IntroKey (), buf + (len - 24));
uint8_t kh2[32];
i2p::crypto::HKDF (m_NoiseState->m_CK, nullptr, 0, "SessionConfirmed", kh2, 32); // k_header_2 = HKDF(chainKey, ZEROLEN, "SessionConfirmed", 32)
header.ll[1] ^= CreateHeaderMask (kh2, buf + (len - 12));
if (header.h.type != eSSU2SessionConfirmed)
{
LogPrint (eLogInfo, "SSU2: Unexpected message type ", (int)header.h.type, " instead ", (int)eSSU2SessionConfirmed);
// TODO: queue up
return true;
}
// packet num must be always zero
if (header.h.packetNum)
{
LogPrint (eLogError, "SSU2: Non zero packet number in SessionConfirmed");
return false;
}
// check if fragmented
uint8_t numFragments = header.h.flags[0] & 0x0F;
if (numFragments > 1)
{
// fragmented
if (numFragments > 2)
{
LogPrint (eLogError, "SSU2: Too many fragments ", (int)numFragments, " in SessionConfirmed from ", m_RemoteEndpoint);
return false;
}
if (len < 32)
{
LogPrint (eLogWarning, "SSU2: SessionConfirmed fragment too short ", len);
if (m_SessionConfirmedFragment) m_SessionConfirmedFragment.reset (nullptr);
return false;
}
if (!(header.h.flags[0] & 0xF0))
{
// first fragment
if (!m_SessionConfirmedFragment)
{
m_SessionConfirmedFragment.reset (new HandshakePacket);
m_SessionConfirmedFragment->header = header;
memcpy (m_SessionConfirmedFragment->payload, buf + 16, len - 16);
m_SessionConfirmedFragment->payloadSize = len - 16;
return true; // wait for second fragment
}
else if (m_SessionConfirmedFragment->isSecondFragment)
{
// we have second fragment