Exemplo n.º 1
0
        public override SSUState HandleMessage(SSUHeader header, BufRefLen reader)
        {
            if (header.MessageType == SSUHeader.MessageTypes.RelayResponse)
            {
                var response = new RelayResponse(reader);
                return(HandleRelayResponse(response));
            }

            return(this);
        }
Exemplo n.º 2
0
 internal void ReportRelayResponse(SSUHeader header, RelayResponse response, IPEndPoint ep)
 {
     if (RelayResponseReceived != null)
     {
         lock ( RelayResponseReceivedLock )
         {
             RelayResponseReceived(header, response, ep);
         }
     }
 }
Exemplo n.º 3
0
        public override SSUState HandleMessage(SSUHeader header, BufRefLen reader)
        {
            switch (header.MessageType)
            {
            case SSUHeader.MessageTypes.SessionRequest:
                var req = new SessionRequest(reader, I2PKeyType.DefaultAsymetricKeyCert);
                Logging.LogTransport($"SSU SessionCreatedState {Session.DebugId}: OK SessionRequest received.");

                BufUtils.DHI2PToSessionAndMAC(out var sessionkey, out var mackey,
                                              req.XKey.ModPow(PrivateKey.ToBigInteger(), I2PConstants.ElGamalP));

                Session.MACKey    = mackey;
                Session.SharedKey = sessionkey;

                Session.Host.ReportedAddress(new IPAddress(req.Address.ToByteArray()));

                // TODO: Remove comment when relaying is implemented

                /*
                 * if ( header.ExtendedOptions != null )
                 * {
                 *  if ( header.ExtendedOptions.Length == 2 && ( ( header.ExtendedOptions[0] & 0x01 ) != 0 ) )
                 *  {
                 *      RelayTag = BufUtils.RandomUint();
                 *  }
                 * }*/

                Request = req;
                SendSessionCreated();

                return(this);

            case SSUHeader.MessageTypes.RelayResponse:
                Logging.LogTransport(string.Format("SSU SessionCreatedState {0}: RelayResponse received from {1}.",
                                                   Session.DebugId, (Session.RemoteEP == null ? "<null>" : Session.RemoteEP.ToString())));
                var response = new RelayResponse(reader);
                Session.Host.ReportRelayResponse(header, response, Session.RemoteEP);
                break;

            case SSUHeader.MessageTypes.SessionConfirmed:
                return(ParseSessionConfirmed(header, reader));

            case SSUHeader.MessageTypes.PeerTest:
                HandleIncomingPeerTestPackage(reader);
                break;

            default:
                Logging.LogTransport($"SSU SessionCreatedState: Session {Session.DebugId} Unexpected Message: {header.MessageType}");
                break;
            }

            return(this);
        }
Exemplo n.º 4
0
        private SSUState ParseSessionConfirmed(SSUHeader header, BufRefLen reader)
        {
            var info    = reader.Read8();
            var cursize = reader.ReadFlip16();

            if (Fragments is null)
            {
                Fragments = new BufLen[info & 0x0f];
            }

            return(AssembleFragments(header, reader, info, cursize));
        }
Exemplo n.º 5
0
        public override SSUState HandleMessage(SSUHeader header, BufRefLen reader)
        {
            if (header.MessageType == SSUHeader.MessageTypes.SessionCreated)
            {
                Logging.LogTransport($"SSU SessionConfirmedState {Session.DebugId}: Unexpected message received: {header.MessageType}");
                return(this);
            }

            Logging.LogTransport($"SSU SessionConfirmedState: Session {Session.DebugId} established. " +
                                 $"{header.MessageType} received. Moving to Established state.");

            var next = new EstablishedState(Session);

            Session.ReportConnectionEstablished();

            return(next.HandleMessage(header, reader));
        }
Exemplo n.º 6
0
        public virtual SSUState DatagramReceived(BufRefLen recv, IPEndPoint RemoteEP)
        {
            // Verify the MAC
            var reader   = new BufRefLen(recv);
            var header   = new SSUHeader(reader);
            var recvencr = header.EncryptedBuf;

            var macstate = VerifyMAC(header, CurrentMACKey);

            switch (macstate)
            {
            case MACHealth.AbandonSession:
                Logging.LogTransport($"SSU {this}: Abandoning session. MAC check failed.");

                SendSessionDestroyed();
                Session.Host.ReportEPProblem(RemoteEP);
                return(null);

            case MACHealth.Missmatch:
                return(this);
            }

            // Decrypt
            Cipher.Init(false, CurrentPayloadKey.ToParametersWithIV(header.IV));
            Cipher.ProcessBytes(recvencr);

            header.SkipExtendedHeaders(reader);

            if (header.MessageType == SSUHeader.MessageTypes.SessionDestroyed &&
                CurrentPayloadKey != Session.RemoteIntroKey &&
                CurrentPayloadKey != Session.MyRouterContext.IntroKey)
            {
                Logging.LogTransport($"SSU {this}: Received SessionDestroyed.");
                SendSessionDestroyed();
                return(null);
            }

            Logging.LogDebugData($"SSU {this}: Received message: {header.MessageType}" +
                                 $": {SSUHost.SSUDateTime( header.TimeStamp )}");

            DataReceived();

            return(HandleMessage(header, reader));
        }
Exemplo n.º 7
0
        protected MACHealth VerifyMAC(SSUHeader header, BufLen key)
        {
            var macdata = new BufLen[] {
                header.MACDataBuf,
                header.IV,
                BufUtils.Flip16BL((ushort)((ushort)header.MACDataBuf.Length ^ I2PConstants.SSU_PROTOCOL_VERSION))
            };

            var recvhash = I2PHMACMD5Digest.Generate(macdata, key, MACBuf);
            var ok       = header.MAC.Equals(recvhash);
            var result   = ok ? MACHealth.Match : MACHealth.Missmatch;

            if (!ok)
            {
                if (++ConsecutiveMACCheckFailures > 3)
                {
                    result = MACHealth.AbandonSession;
                }
            }
            else
            {
                ConsecutiveMACCheckFailures = 0;
            }

#if DEBUG
            if (result != MACHealth.Match)
            {
                Logging.LogTransport($"SSU {this}: VerifyMAC {result} [{ConsecutiveMACCheckFailures}] {key}");
            }
            else
            {
                Logging.LogDebugData($"SSU {this}: VerifyMAC {result} [{ConsecutiveMACCheckFailures}] {key}");
            }
#endif

#if DEBUG && SSU_TRACK_OLD_MAC_KEYS
            if (result != MACHealth.Match)
            {
                result = CheckOldKeys(header, macdata, MACBuf, result);
            }
#endif
            return(result);
        }
Exemplo n.º 8
0
        void Host_RelayResponseReceived(SSUHeader header, RelayResponse response, IPEndPoint ep)
        {
            Logging.LogTransport(
                $"SSU RelayRequestState: {Session.DebugId} RelayResponse from {ep} received.");

            if (header.MessageType == SSUHeader.MessageTypes.RelayResponse)
            {
                if (Introducers.Any(i => i.Value.RemoteEP == ep))
                {
                    HandleRelayResponse(response);
                }
                else
                {
                    Logging.LogTransport(
                        $"SSU RelayRequestState: {Session.DebugId} RelayResponse from {ep} received. " +
                        $"Ignored as not in wait set [{string.Join( ", ", Introducers.Select( i => i.Value.RemoteEP ) )}].");
                }
            }
        }
Exemplo n.º 9
0
        private MACHealth CheckOldKeys(
            SSUHeader header,
            BufLen[] macdata,
            BufLen mACBuf,
            MACHealth result)
        {
            if (!SSUSession.OldKeys.TryGetValue(Session.RemoteEP, out var oldkeys))
            {
                return(result);
            }

            foreach (var keyinfo in oldkeys.ToArray())
            {
                var recvhashi = I2PHMACMD5Digest.Generate(macdata, keyinfo.Key, MACBuf);
                var oki       = header.MAC.Equals(recvhashi);

                Logging.LogTransport($"SSU {this}: " +
                                     $"Old key from {keyinfo.Created} {keyinfo.CreatedDelta, -20} {keyinfo.Type, -10} match: {oki, -6} {keyinfo.Key}");
            }

            return(result);
        }
Exemplo n.º 10
0
        private SSUState AssembleFragments(SSUHeader header, BufRefLen reader, byte info, ushort cursize)
        {
            var fragnr    = info >> 4;
            var fragcount = info & 0x0f;

            Logging.LogTransport($"AssembleFragments: frag {fragnr} / {fragcount}, len {cursize}.");

            if (fragnr != fragcount - 1)
            {
                Fragments[fragnr] = reader.ReadBufLen(cursize);
            }
            else
            {
                ASignonTime       = reader.Peek32(cursize);
                Fragments[fragnr] = reader.ReadBufLen(reader.Length);
            }

            if (Fragments.Any(f => f is null))
            {
                return(this);
            }

            var buf       = new BufLen(new byte[Fragments.Sum(f => f.Length)]);
            var bufwriter = new BufRefLen(buf);

            for (int i = 0; i < Fragments.Length; ++i)
            {
                bufwriter.Write(Fragments[i]);
            }
            Session.RemoteRouter = new I2PRouterIdentity((BufRefLen)buf);

            var signbuf = new BufRefLen(buf,
                                        buf.Length - Session.RemoteRouter.Certificate.SignatureLength);

            ASign = new I2PSignature(signbuf, Session.RemoteRouter.Certificate);

            return(VerifyRemoteSignature());
        }
Exemplo n.º 11
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.RandomBytes(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_MUCH_TRANSPORT
            Logging.LogTransport(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();
            Send(dest, data);
        }
Exemplo n.º 12
0
 // MAC verified and packet dectrypted
 public abstract SSUState HandleMessage(SSUHeader header, BufRefLen reader);
Exemplo n.º 13
0
        public override SSUState HandleMessage(SSUHeader header, BufRefLen reader)
        {
            switch (header.MessageType)
            {
            case SSUHeader.MessageTypes.Data:
                try
                {
                    var datamsg = new SSUDataMessage(reader, Session.Defragmenter);
                    if (datamsg.ExplicitAcks != null)
                    {
                        Session.Fragmenter.GotAck(datamsg.ExplicitAcks);
                    }
                    if (datamsg.AckBitfields != null)
                    {
                        Session.Fragmenter.GotAck(datamsg.AckBitfields);
                    }
                    if (datamsg.NewMessages != null)
                    {
                        foreach (var msg in datamsg.NewMessages)
                        {
                            var i2npmsg = I2NPMessage.ReadHeader16((BufRefLen)msg.GetPayload());

#if LOG_MUCH_TRANSPORT
                            Logging.LogDebugData($"SSU {this} complete message " +
                                                 $"{msg.MessageId}: {i2npmsg.Expiration}");
#endif

                            if (i2npmsg.MessageType == I2NPMessage.MessageTypes.DeliveryStatus)
                            {
                                if (((DeliveryStatusMessage)i2npmsg.Message).IsNetworkId((ulong)I2PConstants.I2P_NETWORK_ID))
                                {
                                    continue;
                                }
                            }

                            Session.MessageReceived(i2npmsg);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging.Log("EstablishedState: SSUHost.SSUMessageTypes.Data", ex);
                }
                break;

            case SSUHeader.MessageTypes.PeerTest:
                HandleIncomingPeerTestPackage(reader);
                break;

            case SSUHeader.MessageTypes.RelayResponse:
                Logging.LogTransport($"SSU EstablishedState {Session.DebugId}: RelayResponse received from {Session.RemoteEP}.");
                var response = new RelayResponse(reader);
                Session.Host.ReportRelayResponse(header, response, Session.RemoteEP);
                break;

            case SSUHeader.MessageTypes.RelayIntro:
                var intro = new RelayIntro(reader);
                Logging.LogTransport($"SSU EstablishedState {Session.DebugId}: RelayIntro received from {Session.RemoteEP} for {intro.AliceEndpoint}.");

                var data = new BufLen(new byte[12]);
                data.Randomize();
                Send(intro.AliceEndpoint, data);

                ++Session.Host.EPStatisitcs[Session.RemoteEP].RelayIntrosReceived;
                ++Session.RelayIntroductionsReceived;
                break;

            case SSUHeader.MessageTypes.RelayRequest:
                // TODO: Implement
                // if ( !SSUHost.IntroductionSupported ) throw new Exception( "SSU relay introduction not supported" );
                Logging.LogTransport(string.Format("SSU EstablishedState {0}: Relay introduction not supported.", Session.DebugId));
                break;

            case SSUHeader.MessageTypes.SessionRequest:
                Logging.LogTransport(string.Format("SSU EstablishedState {0}: SessionRequest received. Ending session.", Session.DebugId));
                SendSessionDestroyed();
                return(null);

            default:
                Logging.LogTransport(string.Format("SSU EstablishedState {0}: Unexpected message received: {1}.",
                                                   Session.DebugId, header.MessageType));
                break;
            }

            return(this);
        }
Exemplo n.º 14
0
        public override SSUState HandleMessage(SSUHeader header, BufRefLen reader)
        {
            var tstime = SSUHost.SSUDateTime(header.TimeStamp);

            if (header.MessageType != SSUHeader.MessageTypes.SessionCreated)
            {
                Logging.LogTransport($"SSU SessionRequestState: Received unexpected message {tstime} : {header.Flag}");
                return(this);
            }

            SCMessage = new SessionCreated(reader, Session.RemoteRouter.Certificate);

            Session.RelayTag = SCMessage.RelayTag;

            Y = new I2PPublicKey((BufRefLen)SCMessage.Y, Session.RemoteRouter.Certificate);
            BufUtils.DHI2PToSessionAndMAC(out var sessionkey, out var mackey,
                                          Y.ToBigInteger().ModPow(PrivateKey.ToBigInteger(), I2PConstants.ElGamalP));

            Session.SharedKey = sessionkey;
            Session.MACKey    = mackey;

            var    ipaddr = new IPAddress(SCMessage.Address.ToByteArray());
            ushort port   = SCMessage.Port.PeekFlip16(0);

            Session.SignOnTimeB = SCMessage.SignOnTime.Peek32(0);
            var btime = SSUHost.SSUDateTime(BufUtils.Flip32(Session.SignOnTimeB));

            Logging.LogTransport($"SSU SessionRequestState {Session.DebugId} : Received SessionCreated. {tstime.ToString()} : {btime}");
            Session.Host.ReportedAddress(ipaddr);

            if (!I2PSignature.SupportedSignatureType(Session.RemoteRouter.Certificate.SignatureType))
            {
                throw new SignatureCheckFailureException($"SSU SessionRequestState {Session.DebugId} : " +
                                                         $"Received non supported signature type: " +
                                                         $"{Session.RemoteRouter.Certificate.SignatureType}");
            }

            var cipher = new CbcBlockCipher(new AesEngine());

            cipher.Init(false, Session.SharedKey.ToParametersWithIV(header.IV));
            cipher.ProcessBytes(SCMessage.SignatureEncrBuf);

            var baddr = new BufLen(Session.RemoteEP.Address.GetAddressBytes());
            var sign  = new I2PSignature((BufRefLen)SCMessage.Signature, Session.RemoteRouter.Certificate);

            var sok = I2PSignature.DoVerify(
                Session.RemoteRouter.SigningPublicKey, sign,
                X.Key, Y.Key,
                SCMessage.Address, SCMessage.Port,
                baddr, BufUtils.Flip16BL((ushort)Session.RemoteEP.Port),
                SCMessage.RelayTag, SCMessage.SignOnTime);

            Logging.LogTransport($"SSU SessionRequestState: Signature check: {sok}. {Session.RemoteRouter.Certificate.SignatureType}");

            if (!sok)
            {
                throw new SignatureCheckFailureException($"SSU SessionRequestState {Session.DebugId}: Received SessionCreated signature check failed." +
                                                         Session.RemoteRouter.Certificate.ToString());
            }

            if (!RemoteIsFirewalled)
            {
                var relaytag = SCMessage.RelayTag.PeekFlip32(0);
                if (relaytag != 0)
                {
                    Session.RemoteIntroducerInfo = new IntroducerInfo(
                        Session.RemoteEP.Address,
                        (ushort)Session.RemoteEP.Port,
                        Session.RemoteIntroKey, relaytag);

                    Session.Host.IntroductionRelayOffered(Session.RemoteIntroducerInfo);
                }
            }

            Logging.LogTransport($"SSU {this}: SessionCreated received " +
                                 $"from {Session.RemoteEP} created. Moving to SessionConfirmedState.");

            Session.ReportConnectionEstablished();

            return(new SessionConfirmedState(Session, this));
        }