Exemplo n.º 1
0
        public void TestSimpleTunnelDataCreation()
        {
            var smalldata = BufUtils.Random(38);

            var srcmsgs = new List <TunnelMessage>();

            srcmsgs.Add(new TunnelMessageLocal((new DeliveryStatusMessage(1234)).Header16));
            var msgfrags = TunnelDataMessage.MakeFragments(srcmsgs, 0x3e5c);

            Assert.IsTrue(msgfrags.Count() == 1);

            var firstmsg   = msgfrags.First();
            var serialized = firstmsg.Header16.HeaderAndPayload;

            var recovered       = I2NPMessage.ReadHeader16(new BufRefLen(serialized));
            var reassembler     = new TunnelDataFragmentReassembly();
            var reassembledmsgs = reassembler.Process(new TunnelDataMessage[] { (TunnelDataMessage)recovered.Message });

            Assert.IsTrue(reassembledmsgs.Count() == 1);

            var firstrecinstr = reassembledmsgs.First();

            Assert.IsTrue(firstrecinstr.Delivery == TunnelMessage.DeliveryTypes.Local);
            Assert.IsTrue(firstrecinstr.Header.Message.MessageType == I2NPMessage.MessageTypes.DeliveryStatus);
            Assert.IsTrue(((DeliveryStatusMessage)firstrecinstr.Header.Message).MessageId == 1234);
        }
Exemplo n.º 2
0
        internal static BufLen Send(DHHandshakeContext context)
        {
            context.TimestampA = (uint)Math.Ceiling((DateTime.UtcNow - I2PDate.RefDate).TotalSeconds);

            var cleartext = new List <byte>();
            var ri        = RouterContext.Inst.MyRouterIdentity.ToByteArray();

            cleartext.AddRange(BufUtils.Flip16B((ushort)ri.Length));
            cleartext.AddRange(ri);

            cleartext.AddRange(BufUtils.Flip32B(context.TimestampA));
#if LOG_ALL_TRANSPORT
            DebugUtils.Log("SessionConfirmA send TimestampA: " + (I2PDate.RefDate.AddSeconds(context.TimestampA).ToString()));
            DebugUtils.Log("SessionConfirmA send TimestampB: " + (I2PDate.RefDate.AddSeconds(context.TimestampB).ToString()));
#endif

            var sign = I2PSignature.DoSign(RouterContext.Inst.PrivateSigningKey,
                                           context.X.Key,
                                           context.Y.Key,
                                           context.RemoteRI.IdentHash.Hash,
                                           BufUtils.Flip32BL(context.TimestampA),
                                           BufUtils.Flip32BL(context.TimestampB));

            var padsize = BufUtils.Get16BytePadding(sign.Length + cleartext.Count);
            cleartext.AddRange(BufUtils.Random(padsize));

            cleartext.AddRange(sign);

            var buf = new BufLen(cleartext.ToArray());
            context.Encryptor.ProcessBytes(buf);

            return(buf);
        }
Exemplo n.º 3
0
 public I2PSigningPrivateKey(I2PCertificate cert)
     : base(new BufLen(BufUtils.Random(cert.SigningPrivateKeyLength)), cert)
 {
     if (cert.SignatureType == SigningKeyTypes.EdDSA_SHA512_Ed25519)
     {
         ExpandedPrivateKey = Chaos.NaCl.Ed25519.ExpandedPrivateKeyFromSeed(ToByteArray());
     }
 }
Exemplo n.º 4
0
        public void Write(List <byte> dest)
        {
            Id.Write(dest);
            LastSeen.Write(dest);
            dest.AddRange(BufUtils.Random(60));     // Reserved space

            var mapping = CreateMapping();

            mapping.Write(dest);
        }
Exemplo n.º 5
0
        public void Write(BufRefStream dest)
        {
            Id.Write(dest);
            LastSeen.Write(dest);
            Created.Write(dest);
            dest.Write(BufUtils.Random(52));     // Reserved space

            var mapping = CreateMapping();

            mapping.Write(dest);
        }
Exemplo n.º 6
0
        public void TestBufLen()
        {
            BufLen b1null = null;
            var    b1     = new BufLen(BufUtils.Random(70));
            var    b2     = new BufLen(BufUtils.Random(70));

            b1[0] = 2;
            b2[0] = 1;

#pragma warning disable 1718
            Assert.IsTrue(b1null == b1null);
            Assert.IsTrue(b1null == null);
            Assert.IsTrue(b1 != b1null);
            Assert.IsTrue(b1 != null);
            Assert.IsTrue(null != b1);
            Assert.IsTrue(b1 == b1);
            Assert.IsTrue(b1 != b2);
            Assert.IsTrue(b1 == b1.Clone());
            Assert.IsTrue(b1.AsEnumerable().Average(b => b) == b1.Clone().AsEnumerable().Average(b => b));
            Assert.IsTrue(((IComparable <BufLen>)b1).CompareTo(b1.Clone()) == 0);
#pragma warning restore 1718

            var list = new List <byte>(b1);
            Assert.IsTrue(b1 == new BufLen(list.ToArray()));

            var buf = new byte[5];
            b2.Peek(buf, 30);
            Assert.IsTrue((new BufLen(b2, 30, 5)) == new BufLen(buf));

            Assert.IsTrue(b1 != b2);
            Assert.IsTrue(((IComparable <BufLen>)b1).CompareTo(b2) > 0);
            Assert.IsTrue(b1 > b2);
            Assert.IsFalse(b1 < b2);
            Assert.IsTrue(b1 > new BufLen(b1, 0, 20));
            Assert.IsFalse(b1 < new BufLen(b1, 0, 20));
            Assert.IsTrue(new BufLen(b1, 0, 20) < b1);
            Assert.IsFalse(new BufLen(b1, 0, 20) > b1);

            Assert.IsTrue(b1.GetHashCode() == b1.GetHashCode());
            Assert.IsTrue(b1.GetHashCode() == b1.Clone().GetHashCode());

            b1.PokeFlip32(0x326de4f7, 20);
            Assert.IsTrue(b1[20] == 0x32);
            Assert.IsTrue(b1[21] == 0x6d);
            Assert.IsTrue(b1[22] == 0xe4);
            Assert.IsTrue(b1[23] == 0xf7);

            b1.Poke32(0x326de4f7, 21);
            Assert.IsTrue(b1[20] == 0x32);
            Assert.IsTrue(b1[21] == 0xf7);
            Assert.IsTrue(b1[22] == 0xe4);
            Assert.IsTrue(b1[23] == 0x6d);
            Assert.IsTrue(b1[24] == 0x32);
        }
Exemplo n.º 7
0
        public BufLen GenerateData(I2NPMessage msg)
        {
            if (NTCPContext == null)
            {
                throw new Exception("NTCP Session not negotiated!");
            }
            if (NTCPContext.Encryptor == null)
            {
                throw new Exception("NTCP encryptor not available");
            }

            var data = msg != null ? msg.Header16.HeaderAndPayload: null;

            var datalength = msg == null ? 4 : data.Length;
            var buflen     = 2 + datalength + 4;
            var padlength  = BufUtils.Get16BytePadding(buflen);

            buflen += padlength;

            var buf    = new BufLen(new byte[buflen]);
            var writer = new BufRefLen(buf);

            // Length
            if (msg == null)
            {
                // Send timestamp
                writer.Write16(0);
                writer.WriteFlip32((uint)(DateTime.UtcNow - I2PDate.RefDate).TotalSeconds);
            }
            else
            {
                if (data.Length > 16378)
                {
                    throw new ArgumentException("NTCP data can be max 16378 bytes long!");
                }
                writer.WriteFlip16((ushort)data.Length);
                writer.Write(data);
            }

            // Pad
            writer.Write(BufUtils.Random(writer.Length - 4));

            // Checksum
            var checkbuf = new BufLen(buf, 0, writer - buf);
            var checksum = LZUtils.Adler32(1, checkbuf);

            writer.WriteFlip32(checksum);

            // Encrypt
            NTCPContext.Encryptor.ProcessBytes(buf);

            return(buf);
        }
Exemplo n.º 8
0
        public void MakeAndReadFragmentsWithSerialize()
        {
            var origmsgs = new List <TunnelMessage>();

            for (int i = 0; i < 200; ++i)
            {
                switch (BufUtils.RandomInt(3))
                {
                case 0:
                    var adatarec = new DataMessage(new BufLen(BufUtils.Random(2048 + BufUtils.RandomInt(1024))));

                    origmsgs.Add(new TunnelMessageLocal(adatarec.Header16));
                    break;

                case 1:
                    var arec = new DatabaseLookupMessage(
                        new I2PIdentHash(true),
                        new I2PIdentHash(true),
                        DatabaseLookupMessage.LookupTypes.RouterInfo);

                    origmsgs.Add(new TunnelMessageRouter(arec.Header16, new I2PIdentHash(true)));
                    break;

                case 2:
                    var adatarec2 = new DataMessage(new BufLen(BufUtils.Random(2048 + BufUtils.RandomInt(1024))));

                    origmsgs.Add(new TunnelMessageTunnel(adatarec2.Header16,
                                                         new I2PIdentHash(true),
                                                         BufUtils.RandomUint()));
                    break;
                }
            }

            var msgs     = TunnelDataMessage.MakeFragments(origmsgs, BufUtils.RandomUint());
            var recvlist = new List <TunnelDataMessage>();

            foreach (var msg in msgs)
            {
                recvlist.Add((TunnelDataMessage)I2NPMessage.ReadHeader16(new BufRefLen(msg.Header16.HeaderAndPayload)).Message);
            }

            var mkmsg     = new TunnelDataFragmentReassembly();
            var recvtmsgs = mkmsg.Process(recvlist);

            foreach (var rmsg in recvtmsgs)
            {
                Assert.IsTrue(origmsgs.SingleOrDefault(m =>
                                                       m.Delivery == rmsg.Delivery &&
                                                       m.Header.HeaderAndPayload == rmsg.Header.HeaderAndPayload
                                                       ) != null);
            }
        }
Exemplo n.º 9
0
        private void SendUnfragmentedSessionConfirmed()
        {
            var ri = new BufLen(Session.MyRouterContext.MyRouterInfo.ToByteArray());

            SendMessage(
                SSUHeader.MessageTypes.SessionConfirmed,
                Session.MACKey,
                Session.SharedKey,
                (start, writer) =>
            {
                writer.Write8((byte)((0 << 4) + 1));
                writer.WriteFlip16((ushort)ri.Length);
                writer.Write(ri);

                Session.SignOnTimeA = BufUtils.Flip32(SSUHost.SSUTime(DateTime.UtcNow));
                writer.Write32(Session.SignOnTimeA);
                var padding = BufUtils.Get16BytePadding(Session.MyRouterContext.Certificate.SignatureLength + (writer - start));
                writer.Write(BufUtils.Random(padding));

                var baddr = new BufLen(Session.RemoteEP.Address.GetAddressBytes());
                var bport = BufUtils.Flip16BL((ushort)Session.RemoteEP.Port);
#if LOG_ALL_TRANSPORT
                Logging.LogTransport(string.Format("SSU SessionConfirmedState {0}: X for signature {1}.",
                                                   Session.DebugId, Request.X.Key));
                Logging.LogTransport(string.Format("SSU SessionConfirmedState {0}: Y for signature {1}.",
                                                   Session.DebugId, Request.Y.Key));
                Logging.LogTransport(string.Format("SSU SessionConfirmedState {0}: Alice address for signature {1}. Port {2}.",
                                                   Session.DebugId, Request.SCMessage.Address, Request.SCMessage.Port));
                Logging.LogTransport(string.Format("SSU SessionConfirmedState {0}: Bob address for signature {1}. Port {2}.",
                                                   Session.DebugId, baddr, bport));
                Logging.LogTransport(string.Format("SSU SessionConfirmedState {0}: Relay tag {1}. Signon time {2}.",
                                                   Session.DebugId, Request.SCMessage.RelayTag, (BufLen)Session.SignOnTimeA));
#endif

                var sign = I2PSignature.DoSign(Session.MyRouterContext.PrivateSigningKey,
                                               Request.X.Key, Request.Y.Key,
                                               Request.SCMessage.Address, Request.SCMessage.Port,
                                               baddr, bport,
                                               Request.SCMessage.RelayTag, (BufLen)Session.SignOnTimeA
                                               );
                writer.Write(sign);

#if LOG_ALL_TRANSPORT
                Logging.LogTransport(string.Format("SessionConfirmedState {0}: sending unfragmented SessionConfirmed. {1} bytes [0x{1:X}].",
                                                   Session.DebugId,
                                                   writer - start - SSUHeader.FIXED_HEADER_SIZE));
#endif

                return(true);
            });
        }
Exemplo n.º 10
0
        public void TestRoulette()
        {
            var l = BufUtils.Random(10000).AsEnumerable();
            var r = new I2PCore.Utils.RouletteSelection <byte, byte>(l, v => v, k => k == 42 ? 30f : 1f, float.MaxValue);

            int is42    = 0;
            int samples = 10000;

            for (int i = 0; i < samples; ++i)
            {
                if (r.GetWeightedRandom() == 42)
                {
                    ++is42;
                }
            }

            Assert.IsTrue(is42 > (20 * samples) / 256);
        }
Exemplo n.º 11
0
        public void TestSingleLargeTunnelDataCreation()
        {
            var sourcedata = new BufLen(BufUtils.Random(9000));

            var srcmsgs = new List <TunnelMessage>();

            srcmsgs.Add(new TunnelMessageTunnel((new DataMessage(sourcedata)).Header16, new I2PIdentHash(true), 4242));
            var msgfrags = TunnelDataMessage.MakeFragments(srcmsgs, 0x3e5c);

            Assert.IsTrue(msgfrags.Count() == 10);

            var serbuf = new List <byte>();

            foreach (var frag in msgfrags)
            {
                serbuf.AddRange(frag.Header16.HeaderAndPayload);
            }
            var serbufarray = serbuf.ToArray();

            var reassembler = new TunnelDataFragmentReassembly();
            var reader      = new BufRefLen(serbufarray);
            var readmsgs    = new List <TunnelDataMessage>();

            while (reader.Length > 0)
            {
                readmsgs.Add((TunnelDataMessage)(I2NPMessage.ReadHeader16(reader)).Message);
            }

            var reassembledmsgs = reassembler.Process(readmsgs);

            Assert.IsTrue(reassembledmsgs.Count() == 1);
            Assert.IsTrue(reassembler.BufferedFragmentCount == 0);

            var firstrecinstr = reassembledmsgs.First();

            Assert.IsTrue(firstrecinstr.Delivery == TunnelMessage.DeliveryTypes.Tunnel);
            Assert.IsTrue(((TunnelMessageTunnel)firstrecinstr).Tunnel == 4242);
            Assert.IsTrue(firstrecinstr.Header.Message.MessageType == I2NPMessage.MessageTypes.Data);

            var datamsg = (DataMessage)firstrecinstr.Header.Message;

            Assert.IsTrue(datamsg.DataMessagePayloadLength == sourcedata.Length);
            Assert.IsTrue(datamsg.DataMessagePayload == sourcedata);
        }
Exemplo n.º 12
0
        public void TestGZip()
        {
            var smalldata = BufUtils.Random(200);
            var bigdata   = BufUtils.Random(2 * 1024 * 1024);

            var smalldata_zero = new byte[200];
            var bigdata_zero   = new byte[2 * 1024 * 1024];

            var b1 = LZUtils.BCGZipCompressNew(new BufLen(smalldata));
            var b2 = LZUtils.BCGZipDecompressNew(b1);

            Assert.IsTrue(b2 == new BufLen(smalldata));

            b1 = LZUtils.BCGZipCompressNew(new BufLen(bigdata));
            b2 = LZUtils.BCGZipDecompressNew(b1);
            Assert.IsTrue(b2 == new BufLen(bigdata));

            b1 = LZUtils.BCGZipCompressNew(new BufLen(smalldata_zero));
            b2 = LZUtils.BCGZipDecompressNew(b1);
            Assert.IsTrue(b2 == new BufLen(smalldata_zero));

            b1 = LZUtils.BCGZipCompressNew(new BufLen(bigdata_zero));
            b2 = LZUtils.BCGZipDecompressNew(b1);
            Assert.IsTrue(b2 == new BufLen(bigdata_zero));

            var ba1 = LZUtils.BCGZipCompress(bigdata);

            b2 = LZUtils.BCGZipDecompressNew(new BufLen(ba1));
            Assert.IsTrue(b2 == new BufLen(bigdata));

            b1 = LZUtils.BCGZipCompressNew(new BufLen(bigdata_zero));
            var ba2 = LZUtils.BCGZipDecompress(b1);

            Assert.IsTrue(new BufLen(ba2) == new BufLen(bigdata_zero));

            for (int i = bigdata.Length / 10; i < bigdata.Length - bigdata.Length / 10; ++i)
            {
                bigdata[i] = 42;
            }
            b1 = LZUtils.BCGZipCompressNew(new BufLen(bigdata));
            b2 = LZUtils.BCGZipDecompressNew(b1);
            Assert.IsTrue(b2 == new BufLen(bigdata));
        }
Exemplo n.º 13
0
        public void TestRoulette2()
        {
            var l = BufUtils.Random(10000).AsEnumerable();

            l = l.Concat(BufUtils.Populate <byte>(42, 10000));
            var r = new I2PCore.Utils.RouletteSelection <byte, byte>(l, v => v, k => 1f, float.MaxValue);

            int is42    = 0;
            int samples = 10000;

            for (int i = 0; i < samples; ++i)
            {
                if (r.GetWeightedRandom() == 42)
                {
                    ++is42;
                }
            }

            Assert.IsTrue(is42 > samples / 2 - samples / 30);
        }
Exemplo n.º 14
0
        internal static byte[] Send(DHHandshakeContext context)
        {
            var clear  = new byte[304];
            var writer = new BufRefLen(clear);

            var keys = I2PPrivateKey.GetNewKeyPair();

            context.PrivateKey = keys.PrivateKey;
            context.Y          = keys.PublicKey;
            context.YBuf       = new BufLen(context.Y.Key);

            var sharedkey = BufUtils.DHI2PToByteArray(context.X.ToBigInteger().ModPow(context.PrivateKey.ToBigInteger(), I2PConstants.ElGamalP));

            context.SessionKey = new I2PSessionKey(sharedkey);

            writer.Write(context.YBuf);

            context.TimestampB = (uint)(DateTime.UtcNow - I2PDate.RefDate).TotalSeconds;

            writer.Write(I2PHashSHA256.GetHash(context.XBuf, context.YBuf));
            writer.WriteFlip32(context.TimestampB);
            writer.Write(BufUtils.Random(12));

            var key = new KeyParameter(context.SessionKey.Key.ToByteArray());

            var iv = context.YBuf.PeekB(context.YBuf.Length - 16, 16);

            context.Encryptor = new CbcBlockCipher(new AesEngine());
            context.Encryptor.Init(true, new ParametersWithIV(key, iv, 0, 16));

            iv = context.HXxorHI.PeekB(context.HXxorHI.Length - 16, 16);

            context.Dectryptor = new CbcBlockCipher(new AesEngine());
            context.Dectryptor.Init(false, new ParametersWithIV(key, iv, 0, 16));

            context.Encryptor.ProcessBytes(new BufLen(clear, 256, 48));

            return(clear);
        }
Exemplo n.º 15
0
        internal static byte[] Send(DHHandshakeContext context)
        {
            var msglen = RouterContext.Inst.MyRouterIdentity.Certificate.SignatureLength;

            msglen += BufUtils.Get16BytePadding(msglen);

            var writer = new BufRefLen(new byte[msglen]);

            var SigBuf = I2PSignature.DoSign(RouterContext.Inst.PrivateSigningKey,
                                             context.XBuf,
                                             context.YBuf,
                                             context.RemoteRI.IdentHash.Hash,
                                             (BufLen)BufUtils.Flip32(context.TimestampA),
                                             (BufLen)BufUtils.Flip32(context.TimestampB));

            writer.Write(SigBuf);
            writer.Write(BufUtils.Random(writer.Length));

            writer.Reset();
            context.Encryptor.ProcessBytes((BufLen)writer);

            return(writer.ToByteArray());
        }
Exemplo n.º 16
0
        private void SendSessionCreated()
        {
            SendMessage(
                SSUHeader.MessageTypes.SessionCreated,
                Session.MyRouterContext.IntroKey,
                Session.MyRouterContext.IntroKey,
                (start, writer) =>
            {
                writer.Write(Y.Key);
                AAddr = Session.RemoteEP.Address.GetAddressBytes();
                writer.Write8((byte)AAddr.Length);
                writer.Write(AAddr);
                APort = BufUtils.Flip16((ushort)Session.RemoteEP.Port);
                writer.Write16(APort);
                writer.WriteFlip32(RelayTag);
                Session.SignOnTimeB = BufUtils.Flip32(SSUHost.SSUTime(DateTime.UtcNow));
                writer.Write32(Session.SignOnTimeB);

                var sign = I2PSignature.DoSign(Session.MyRouterContext.PrivateSigningKey,
                                               Request.X, Y.Key,
                                               new BufLen(AAddr), (BufLen)APort,
                                               Request.Address, (BufLen)BufUtils.Flip16((ushort)Session.MyRouterContext.UDPPort),
                                               (BufLen)RelayTag, (BufLen)Session.SignOnTimeB);

                var signstart = new BufLen(writer);
                writer.Write(sign);
                var padding = BufUtils.Get16BytePadding(writer - signstart);
                writer.Write(BufUtils.Random(padding));

                var cipher       = new CbcBlockCipher(new AesEngine());
                var signcryptbuf = new BufLen(signstart, 0, writer - signstart);
                cipher.Init(true, Session.SharedKey.ToParametersWithIV(new BufLen(start, 16, 16)));
                cipher.ProcessBytes(signcryptbuf);
                return(true);
            });
        }
Exemplo n.º 17
0
        public void TestSSU()
        {
            DebugUtils.LogToFile("TestSSU.log");

            RouterContext testcontext = new RouterContext(new I2PCertificate(I2PSigningKey.SigningKeyTypes.DSA_SHA1));

            testcontext.DefaultTCPPort = 2048 + BufUtils.RandomInt(5000);
            testcontext.DefaultUDPPort = 2048 + BufUtils.RandomInt(5000);

            var host = new SSUHost_Accessor(testcontext, new FixedMTU());

            host.AllowConnectToSelf = true;

            host.add_ConnectionCreated(new Action <I2PCore.Transport.ITransport>(host_ConnectionCreated));

            // Remote
            var dnsa = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(a => a.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault();
            var addr = new I2PRouterAddress(dnsa, testcontext.UDPPort, 6, "SSU");

            addr.Options["key"] = FreenetBase64.Encode(testcontext.IntroKey);

            RouterContext remotetestcontext = new RouterContext(new I2PCertificate(I2PSigningKey.SigningKeyTypes.DSA_SHA1));

            remotetestcontext.DefaultTCPPort = testcontext.DefaultTCPPort + 5;
            remotetestcontext.DefaultUDPPort = testcontext.DefaultUDPPort + 5;

            var remotehost = new SSUHost_Accessor(remotetestcontext, new FixedMTU());

            remotehost.AllowConnectToSelf = true;
            var client = remotehost.AddSession(addr, testcontext.MyRouterIdentity);

            client.Connect();

            var data = new BufLen(BufUtils.Random(30000));

            var messagecount = 900; // If the out queue is larger than 1000 msgs we start discarding them

            for (int i = 0; i < messagecount; ++i)
            {
                client.Send(new DataMessage(data));
            }

            System.Threading.Thread.Sleep(10000);

            for (int i = 0; i < messagecount; ++i)
            {
                if (i % 10 == 0)
                {
                    System.Threading.Thread.Sleep(100);
                }
                client.Send(new DataMessage(data));
            }

            var start = new TickCounter();

            while (DataReceived.Count < 2 * messagecount)
            {
                if (start.DeltaToNow.ToMinutes >= 1)
                {
                    Assert.Fail("Failed to receive sent data due to a timeout");
                    break;
                }

                System.Threading.Thread.Sleep(500);
            }

            for (int i = 0; i < 100; ++i)
            {
                Assert.IsTrue(((I2PCore.Tunnel.I2NP.Messages.DataMessage)DataReceived.Random().Message).DataMessagePayload ==
                              new BufLen(data));
            }

            System.Threading.Thread.Sleep(500);

            client.Terminate();

            System.Threading.Thread.Sleep(500);

            host.Terminate();

            System.Threading.Thread.Sleep(500);
        }
Exemplo n.º 18
0
        private void SendFragmentedSessionConfirmed()
        {
            var ri       = new BufLen(Session.MyRouterContext.MyRouterInfo.ToByteArray());
            var rireader = new BufRefLen(ri);

            var datafragments = new List <BufLen>();

            while (rireader.Length > 0)
            {
                datafragments.Add(rireader.ReadBufLen(Math.Min(rireader.Length, 472)));
            }

            for (int i = 0; i < datafragments.Count; ++i)
            {
#if LOG_ALL_TRANSPORT
                Logging.LogTransport(string.Format("SessionConfirmedState {0}: sending fragment {1} of {2}, {3} bytes [0x{3:X}].",
                                                   Session.DebugId,
                                                   i + 1,
                                                   datafragments.Count + 1,
                                                   datafragments[i].Length));
#endif
                SendMessage(
                    SSUHeader.MessageTypes.SessionConfirmed,
                    Session.MACKey,
                    Session.SharedKey,
                    (start, writer) =>
                {
                    writer.Write8((byte)((i << 4) + datafragments.Count + 1));
                    writer.WriteFlip16((ushort)datafragments[i].Length);
                    writer.Write(datafragments[i]);

                    return(true);
                });
            }

            SendMessage(
                SSUHeader.MessageTypes.SessionConfirmed,
                Session.MACKey,
                Session.SharedKey,
                (start, writer) =>
            {
                var frag = datafragments.Count;
                writer.Write8((byte)((frag << 4) + frag + 1));
                writer.WriteFlip16(0);

                Session.SignOnTimeA = BufUtils.Flip32(SSUHost.SSUTime(DateTime.UtcNow));
                writer.Write32(Session.SignOnTimeA);
                var padding = BufUtils.Get16BytePadding(Session.MyRouterContext.Certificate.SignatureLength + (writer - start));
                writer.Write(BufUtils.Random(padding));

                var baddr = new BufLen(Session.RemoteEP.Address.GetAddressBytes());

                var sign = I2PSignature.DoSign(Session.MyRouterContext.PrivateSigningKey,
                                               Request.X.Key, Request.Y.Key,
                                               Request.SCMessage.Address, Request.SCMessage.Port,
                                               baddr, BufUtils.Flip16BL((ushort)Session.RemoteEP.Port),
                                               Request.SCMessage.RelayTag, (BufLen)Session.SignOnTimeA
                                               );
                writer.Write(sign);

#if LOG_ALL_TRANSPORT
                Logging.LogTransport(string.Format("SessionConfirmedState {0}: sending fragment {1} of {2}, {3} bytes [0x{3:X}].",
                                                   Session.DebugId,
                                                   frag + 1,
                                                   datafragments.Count + 1,
                                                   writer - start - SSUHeader.FIXED_HEADER_SIZE));
#endif

                return(true);
            });
        }
Exemplo n.º 19
0
        public void TestBiggerEncodeDecode()
        {
            var recv    = new ReceivedSessions(Private);
            var session = new DestinationSessions((d, h, inf) => { }, () => null);

            var origdsmessage = new DeliveryStatusMessage(0x425c);
            var datamessage   = new DataMessage(new BufLen(BufUtils.Random(16000)));
            var origmessage1  = CreateDatabaseStoreMessage();
            var origmessage2  = CreateDatabaseStoreMessage();
            var origmessage3  = CreateDatabaseStoreMessage();
            var origmessage4  = CreateDatabaseStoreMessage();

            /*
             * var msg1eg = session.CreateMessage(
             *  Me,
             *  new GarlicCloveDeliveryTunnel(
             *      origmessage1,
             *      Destination.IdentHash,
             *      1234 ),
             *  new GarlicCloveDeliveryLocal(
             *      origmessage2 ),
             *  new GarlicCloveDeliveryRouter(
             *      origmessage3,
             *      Destination.IdentHash )
             *  );
             *
             * var msg2aes = session.CreateMessage(
             *  Me,
             *  new GarlicCloveDeliveryTunnel(
             *      origdsmessage,
             *      Destination.IdentHash,
             *      1234 ),
             *  new GarlicCloveDeliveryRouter(
             *      origmessage1,
             *      Destination.IdentHash ),
             *  new GarlicCloveDeliveryLocal(
             *      datamessage ),
             *  new GarlicCloveDeliveryTunnel(
             *      origmessage4,
             *      Destination.IdentHash,
             *      1234 ) );
             *
             * var dmsg1eg = recv.DecryptMessage( msg1eg.Garlic );
             * var dmsg2aes = recv.DecryptMessage( msg2aes.Garlic );
             *
             * Assert.IsTrue( dmsg1eg.Cloves.Count() == 3 );
             * Assert.IsTrue( dmsg2aes.Cloves.Count() == 4 );
             *
             * Assert.IsTrue( dmsg2aes.Cloves[0].Delivery.Delivery == GarlicCloveDelivery.DeliveryMethod.Tunnel );
             * Assert.IsTrue( dmsg2aes.Cloves[1].Delivery.Delivery == GarlicCloveDelivery.DeliveryMethod.Router );
             * Assert.IsTrue( dmsg2aes.Cloves[2].Delivery.Delivery == GarlicCloveDelivery.DeliveryMethod.Local );
             * Assert.IsTrue( dmsg2aes.Cloves[3].Delivery.Delivery == GarlicCloveDelivery.DeliveryMethod.Tunnel );
             *
             * Assert.IsTrue( dmsg1eg.Cloves.All( m => m.Message.MessageType == I2NPMessage.MessageTypes.DatabaseStore ) );
             * Assert.IsTrue( !dmsg2aes.Cloves.All( m => m.Message.MessageType == I2NPMessage.MessageTypes.DatabaseStore ) );
             *
             * Assert.IsTrue( dmsg2aes.Cloves.Where( m => m.Message.MessageType == I2NPMessage.MessageTypes.DeliveryStatus ).
             *  All( m => ( (DeliveryStatusMessage)m.Message ).MessageId == 0x425c ) );
             *
             * Assert.IsTrue( dmsg1eg.Cloves.Where( m => m.Message.MessageType == I2NPMessage.MessageTypes.DatabaseStore ).
             *  All( m => ( (DatabaseStoreMessage)m.Message ).RouterInfo.VerifySignature() ) );
             * Assert.IsTrue( dmsg2aes.Cloves.Where( m => m.Message.MessageType == I2NPMessage.MessageTypes.DatabaseStore ).
             *  All( m => ( (DatabaseStoreMessage)m.Message ).RouterInfo.VerifySignature() ) );
             * Assert.IsTrue( dmsg2aes.Cloves.Where( m => m.Message.MessageType == I2NPMessage.MessageTypes.Data ).
             *  All( m => ( (DataMessage)m.Message ).Payload == datamessage.Payload ) );
             */
        }
Exemplo n.º 20
0
 public I2PSessionTag()
 {
     Value = new BufLen(BufUtils.Random(TagLength));
 }
Exemplo n.º 21
0
 bool RandomExtraPadding(BufLen start, BufRefLen writer)
 {
     writer.Write(BufUtils.Random(BufUtils.RandomInt(16)));
     return(true);
 }
Exemplo n.º 22
0
        /**
         * From PacketBuilder.java
         * -----8<-----
         * @param packet prepared packet with the first 32 bytes empty and a length
         *               whose size is mod 16.
         *               As of 0.9.7, length non-mod-16 is allowed; the
         *               last 1-15 bytes are included in the MAC calculation but are not encrypted.
         * -----8<-----
         */

        protected void SendMessage(
            IPEndPoint dest,
            SSUHeader.MessageTypes message,
            BufLen mackey,
            BufLen cryptokey,
            SendMessageGenerator gen,
            SendMessageGenerator genextrapadding)
        {
            var start = Session.Host.SendBuffers.Pop();

            var writer = new BufRefLen(start);
            var header = new SSUHeader(writer, message);

            if (!gen(start, writer))
            {
                return;
            }

            // Do not cut to datalen & ~0xf as that might make data at the end unencrypted
            var datapadding = BufUtils.Get16BytePadding(writer - start);

            writer.Write(BufUtils.Random(datapadding));
            var datalen = writer - start;

            var encryptedbuf = new BufLen(start, 32, datalen - 32);

            // TODO: Adding extra padding does not seem to work
            if (genextrapadding != null)
            {
                if (!genextrapadding(start, writer))
                {
                    return;
                }
            }

            var packetlen = writer - start;
            var data      = new BufLen(start, 0, packetlen);
            var hmac      = new BufLen(data, 32);

            SendMessageCipher.Init(true, cryptokey.ToParametersWithIV(header.IV));
            SendMessageCipher.ProcessBytes(encryptedbuf);

            I2PHMACMD5Digest.Generate(new BufLen[] {
                hmac,
                header.IV,
                BufUtils.Flip16BL((ushort)((ushort)hmac.Length ^ I2PConstants.SSU_PROTOCOL_VERSION))
            }, mackey, header.MAC);

#if LOG_ALL_TRANSPORT
            DebugUtils.Log(string.Format("SSUState SendMessage {0}: encrlen {1} bytes [0x{1:X}] (padding {2} bytes [0x{2:X}]), " +
                                         "hmac {3} bytes [0x{3:X}], sendlen {4} bytes [0x{4:X}]",
                                         Session.DebugId,
                                         encryptedbuf.Length,
                                         datapadding,
                                         hmac.Length,
                                         data.Length));
#endif

            DataSent();
            Session.Host.Send(dest, data);
        }
Exemplo n.º 23
0
 public I2PRawData(int bytes, bool random)
 {
     Data = random ? BufUtils.Random(bytes): new byte[bytes];
 }
Exemplo n.º 24
0
 public I2PPrivateKey(I2PCertificate cert) : base(cert)
 {
     Key = new BufLen(BufUtils.Random(KeySizeBytes));
 }
Exemplo n.º 25
0
        public void TestSSUOutOfOrderFragmentation()
        {
            var fragmenter = new DataFragmenter();

            var smalldata        = new BufLen(BufUtils.Random(4 + BufUtils.RandomInt(4)));
            var smalldatamessage = new I2PCore.Tunnel.I2NP.Messages.DataMessage(smalldata);

            var smalldata1        = new BufLen(BufUtils.Random(40 + BufUtils.RandomInt(14)));
            var smalldatamessage1 = new I2PCore.Tunnel.I2NP.Messages.DataMessage(smalldata1);

            var smalldata2        = new BufLen(BufUtils.Random(130 + BufUtils.RandomInt(39)));
            var smalldatamessage2 = new I2PCore.Tunnel.I2NP.Messages.DataMessage(smalldata2);

            var smalldata3        = new BufLen(BufUtils.Random(770 + BufUtils.RandomInt(220)));
            var smalldatamessage3 = new I2PCore.Tunnel.I2NP.Messages.DataMessage(smalldata3);

            var data        = new BufLen(BufUtils.Random(30000 + BufUtils.RandomInt(30)));
            var datamessage = new I2PCore.Tunnel.I2NP.Messages.DataMessage(data);

            var data2        = new BufLen(BufUtils.Random(20000 + BufUtils.RandomInt(1040)));
            var datamessage2 = new I2PCore.Tunnel.I2NP.Messages.DataMessage(data2);

            var dest   = new byte[MTUConfig.BufferSize];
            var start  = new BufLen(dest);
            var writer = new BufRefLen(dest);

            var tosend = new LinkedList <II2NPHeader5>();

            tosend.AddLast(smalldatamessage.Header5);
            tosend.AddLast(datamessage.Header5);
            tosend.AddLast(smalldatamessage1.Header5);
            tosend.AddLast(smalldatamessage2.Header5);
            tosend.AddLast(smalldatamessage3.Header5);
            tosend.AddLast(datamessage2.Header5);

            var tosendshuffle  = tosend.Shuffle();
            var tosendshuffled = new LinkedList <II2NPHeader5>(tosendshuffle);

            var sent = new LinkedList <II2NPHeader5>();

            foreach (var one in tosend)
            {
                sent.AddLast(one);
            }

            var sentdata = new LinkedList <BufLen>();

            while (true)
            {
                var flagbuf      = writer.ReadBufLen(1);
                var fragcountbuf = writer.ReadBufLen(1);

                var fragments = fragmenter.Send(writer, tosendshuffled);
                if (fragments == 0)
                {
                    break;
                }

                flagbuf[0] |= (byte)I2PCore.Transport.SSU.SSUDataMessage.DataMessageFlags.WantReply;
                // no ACKs
                fragcountbuf[0] = (byte)fragments;

                sentdata.AddLast(new BufLen(start, 0, writer - start));
                dest   = new byte[MTUConfig.BufferSize];
                start  = new BufLen(dest);
                writer = new BufRefLen(dest);
            }

            var shuffled = sentdata.Shuffle();

            var receivedmessages = new LinkedList <II2NPHeader5>();

            var defragmenter = new DataDefragmenter();

            foreach (var frag in shuffled)
            {
                var datamsg = new I2PCore.Transport.SSU.SSUDataMessage(new BufRefLen(frag), defragmenter);
                if (datamsg.NewMessages != null)
                {
                    foreach (var msg in datamsg.NewMessages)
                    {
                        var i2npmsg = I2NPMessage.ReadHeader5((BufRefLen)msg.GetPayload());
                        receivedmessages.AddLast(i2npmsg);
                    }
                }
            }

            Assert.IsTrue(receivedmessages.Count == sent.Count);

            foreach (var sentmsg in sent)
            {
                Assert.IsTrue(receivedmessages.SingleOrDefault(m => ((I2PCore.Tunnel.I2NP.Messages.DataMessage)m.Message).Payload ==
                                                               ((I2PCore.Tunnel.I2NP.Messages.DataMessage)sentmsg.Message).Payload) != null);
            }
        }
Exemplo n.º 26
0
 public I2PSessionKey()
 {
     Key = new BufLen(BufUtils.Random(32));
 }