Esempio n. 1
0
        internal static Enum GetArbitraryValue(Type enumType)
        {
            Array enumValues = GetEnumValues(enumType);
            int   index      = (int)(DateTimeUtilities.CurrentUnixMs() & 0x7FFFFFFF) % enumValues.Length;

            return((Enum)enumValues.GetValue(index));
        }
Esempio n. 2
0
        private void randMult(string curveName)
        {
            X9ECParameters spec = SecNamedCurves.GetByName(curveName);

            BigInteger   n      = spec.N;
            ECPoint      g      = (ECPoint)spec.G;
            SecureRandom random = new SecureRandom();             //SecureRandom.getInstance("SHA1PRNG", "SUN");
            BigInteger   k      = new BigInteger(n.BitLength - 1, random);

            ECPoint qMultiply = null;
            long    startTime = DateTimeUtilities.CurrentUnixMs();

            for (int i = 0; i < NUM_ROUNDS; i++)
            {
                qMultiply = g.Multiply(k);
            }
            long endTime = DateTimeUtilities.CurrentUnixMs();

            double avgDuration = (double)(endTime - startTime) / NUM_ROUNDS;

            Console.WriteLine(curveName);
            Console.Write("Millis   : ");
            Console.WriteLine(avgDuration);
            Console.WriteLine();
        }
Esempio n. 3
0
        private void DumpDatagram(string verb, byte[] buf, int off, int len)
        {
            long          timestamp = DateTimeUtilities.CurrentUnixMs() - launchTimestamp;
            StringBuilder sb        = new StringBuilder("(+" + timestamp + "ms) " + verb + " " + len + " byte datagram:");

            for (int pos = 0; pos < len; ++pos)
            {
                if (pos % 16 == 0)
                {
                    sb.Append(Environment.NewLine);
                    sb.Append("    ");
                }
                else if (pos % 16 == 8)
                {
                    sb.Append('-');
                }
                else
                {
                    sb.Append(' ');
                }
                int val = buf[off + pos] & 0xFF;
                sb.Append(HEX_CHARS[val >> 4]);
                sb.Append(HEX_CHARS[val & 0xF]);
            }
            Dump(sb.ToString());
        }
Esempio n. 4
0
        /// <summary>Return a V3 signature object containing the current signature state.</summary>
        public PgpSignature Generate()
        {
            long creationTime = DateTimeUtilities.CurrentUnixMs() / 1000L;

            byte[] hData = new byte[]
            {
                (byte)signatureType,
                (byte)(creationTime >> 24),
                (byte)(creationTime >> 16),
                (byte)(creationTime >> 8),
                (byte)creationTime
            };

            sig.BlockUpdate(hData, 0, hData.Length);
            dig.BlockUpdate(hData, 0, hData.Length);

            byte[] sigBytes    = sig.GenerateSignature();
            byte[] digest      = DigestUtilities.DoFinal(dig);
            byte[] fingerPrint = new byte[] { digest[0], digest[1] };

            // an RSA signature
            bool isRsa = keyAlgorithm == PublicKeyAlgorithmTag.RsaSign ||
                         keyAlgorithm == PublicKeyAlgorithmTag.RsaGeneral;

            MPInteger[] sigValues = isRsa
                                ?       PgpUtilities.RsaSigToMpi(sigBytes)
                                :       PgpUtilities.DsaSigToMpi(sigBytes);

            return(new PgpSignature(
                       new SignaturePacket(3, signatureType, privKey.KeyId, keyAlgorithm,
                                           hashAlgorithm, creationTime * 1000L, fingerPrint, sigValues)));
        }
Esempio n. 5
0
        internal static global::System.Enum GetArbitraryValue(global::System.Type enumType)
        {
            global::System.Array enumValues = GetEnumValues(enumType);
            int num = (int)(DateTimeUtilities.CurrentUnixMs() & 0x7FFFFFFF) % enumValues.get_Length();

            return((global::System.Enum)enumValues.GetValue(num));
        }
Esempio n. 6
0
        internal static Enum GetArbitraryValue(System.Type enumType)
        {
            Array values = GetEnumValues(enumType);
            int   pos    = (int)(DateTimeUtilities.CurrentUnixMs() & int.MaxValue) % values.Length;

            return((Enum)values.GetValue(pos));
        }
        internal Message ReceiveMessage()
        {
            long currentTimeMillis = DateTimeUtilities.CurrentUnixMs();

            if (mResendTimeout == null)
            {
                mResendMillis  = InitialResendMillis;
                mResendTimeout = new Timeout(mResendMillis, currentTimeMillis);

                PrepareInboundFlight(Platform.CreateHashtable());
            }

            byte[] buf = null;

            for (;;)
            {
                if (mRecordLayer.IsClosed)
                {
                    throw new TlsFatalAlert(AlertDescription.user_canceled);
                }

                Message pending = GetPendingMessage();
                if (pending != null)
                {
                    return(pending);
                }

                int handshakeMillis = Timeout.GetWaitMillis(mHandshakeTimeout, currentTimeMillis);
                if (handshakeMillis < 0)
                {
                    throw new TlsFatalAlert(AlertDescription.handshake_failure);
                }

                int waitMillis = System.Math.Max(1, Timeout.GetWaitMillis(mResendTimeout, currentTimeMillis));
                if (handshakeMillis > 0)
                {
                    waitMillis = System.Math.Min(waitMillis, handshakeMillis);
                }

                int receiveLimit = mRecordLayer.GetReceiveLimit();
                if (buf == null || buf.Length < receiveLimit)
                {
                    buf = new byte[receiveLimit];
                }

                int received = mRecordLayer.Receive(buf, 0, receiveLimit, waitMillis);
                if (received < 0)
                {
                    ResendOutboundFlight();
                }
                else
                {
                    ProcessRecord(MaxReceiveAhead, mRecordLayer.ReadEpoch, buf, 0, received);
                }

                currentTimeMillis = DateTimeUtilities.CurrentUnixMs();
            }
        }
        private double RandMult(SecureRandom random, ECPoint g, BigInteger n)
        {
            BigInteger[] ks = new BigInteger[128];
            for (int i = 0; i < ks.Length; ++i)
            {
                ks[i] = new BigInteger(n.BitLength - 1, random);
            }

            int     ki = 0;
            ECPoint p  = g;

            for (int i = 1; i <= PRE_ROUNDS; i++)
            {
                for (int j = 0; j < MULTS_PER_ROUND; ++j)
                {
                    BigInteger k = ks[ki];
                    p = g.Multiply(k);
                    if ((ki & 1) != 0)
                    {
                        g = p;
                    }
                    if (++ki == ks.Length)
                    {
                        ki = 0;
                    }
                }
            }

            double minElapsed = Double.MaxValue, maxElapsed = Double.MinValue, totalElapsed = 0.0;

            for (int i = 1; i <= NUM_ROUNDS; i++)
            {
                long startTime = DateTimeUtilities.CurrentUnixMs();

                for (int j = 0; j < MULTS_PER_ROUND; ++j)
                {
                    BigInteger k = ks[ki];
                    p = g.Multiply(k);
                    if ((ki & 1) != 0)
                    {
                        g = p;
                    }
                    if (++ki == ks.Length)
                    {
                        ki = 0;
                    }
                }

                long endTime = DateTimeUtilities.CurrentUnixMs();

                double roundElapsed = (double)(endTime - startTime);
                minElapsed    = System.Math.Min(minElapsed, roundElapsed);
                maxElapsed    = System.Math.Max(maxElapsed, roundElapsed);
                totalElapsed += roundElapsed;
            }

            return((totalElapsed - minElapsed - maxElapsed) / (NUM_ROUNDS - 2) / MULTS_PER_ROUND);
        }
Esempio n. 9
0
        internal static void WriteGmtUnixTime(byte[] buf, int offset)
        {
            int t = (int)(DateTimeUtilities.CurrentUnixMs() / 1000L);

            buf[offset]     = (byte)(t >> 24);
            buf[offset + 1] = (byte)(t >> 16);
            buf[offset + 2] = (byte)(t >> 8);
            buf[offset + 3] = (byte)t;
        }
Esempio n. 10
0
        private void RandomTests()
        {
            SecureRandom srng = new SecureRandom();

            srng.SetSeed(DateTimeUtilities.CurrentUnixMs());
            for (int i = 0; i < 10; ++i)
            {
                RandomTest(srng);
            }
        }
Esempio n. 11
0
 public X931SecureRandom Build(IBlockCipher engine, KeyParameter key, bool predictionResistant)
 {
     if (mDateTimeVector == null)
     {
         mDateTimeVector = new byte[engine.GetBlockSize()];
         Pack.UInt64_To_BE((ulong)DateTimeUtilities.CurrentUnixMs(), mDateTimeVector, 0);
     }
     engine.Init(forEncryption: true, key);
     return(new X931SecureRandom(mRandom, new X931Rng(engine, mDateTimeVector, mEntropySourceProvider.Get(engine.GetBlockSize() * 8)), predictionResistant));
 }
Esempio n. 12
0
        private void RandomTests()
        {
            SecureRandom srng = new SecureRandom();

            srng.SetSeed(DateTimeUtilities.CurrentUnixMs());
            RandomTests(srng, null);
            RandomTests(srng, new BasicGcmMultiplier());
            RandomTests(srng, new Tables8kGcmMultiplier());
            RandomTests(srng, new Tables64kGcmMultiplier());
        }
Esempio n. 13
0
        private void RandomTests()
        {
            SecureRandom random = new SecureRandom();

            random.SetSeed(DateTimeUtilities.CurrentUnixMs());

            for (int i = 0; i < 100; ++i)
            {
                RandomTest(random);
            }
        }
Esempio n. 14
0
        internal static Enum GetArbitraryValue(System.Type enumType)
        {
            Array values = GetEnumValues(enumType);
            int   pos    = (int)(DateTimeUtilities.CurrentUnixMs() & int.MaxValue) % values.Length;

#if WINDOWS_PHONE
            var strVal = values.GetValue(pos).ToString();
            return((Enum)Enum.Parse(enumType, strVal, true));
#else
            return((Enum)values.GetValue(pos));
#endif
        }
        private void RandMult(string label, X9ECParameters spec)
        {
            ECCurve    C = spec.Curve;
            ECPoint    G = (ECPoint)spec.G;
            BigInteger n = spec.N;

            SecureRandom random = new SecureRandom();

            random.SetSeed(DateTimeUtilities.CurrentUnixMs());

            Console.WriteLine(label);

            int[] coords = ECCurve.GetAllCoordinateSystems();
            for (int i = 0; i < coords.Length; ++i)
            {
                int coord = coords[i];
                if (C.SupportsCoordinateSystem(coord))
                {
                    ECCurve c = C;
                    ECPoint g = G;

                    bool defaultCoord = (c.CoordinateSystem == coord);
                    if (!defaultCoord)
                    {
                        c = C.Configure().SetCoordinateSystem(coord).Create();
                        g = c.ImportPoint(G);
                    }

                    double        avgRate   = RandMult(random, g, n);
                    string        coordName = COORD_NAMES[coord];
                    StringBuilder sb        = new StringBuilder();
                    sb.Append("   ");
                    sb.Append(defaultCoord ? '*' : ' ');
                    sb.Append(coordName);
                    for (int j = sb.Length; j < 30; ++j)
                    {
                        sb.Append(' ');
                    }
                    sb.Append(": ");
                    sb.Append(avgRate);
                    sb.Append(" mults/sec");
                    for (int j = sb.Length; j < 64; ++j)
                    {
                        sb.Append(' ');
                    }
                    sb.Append('(');
                    sb.Append(1000.0 / avgRate);
                    sb.Append(" millis/mult)");
                    Console.WriteLine(sb.ToString());
                }
            }
        }
Esempio n. 16
0
 internal virtual void HandshakeSuccessful(DtlsHandshakeRetransmit retransmit)
 {
     if (this.mReadEpoch == this.mCurrentEpoch || this.mWriteEpoch == this.mCurrentEpoch)
     {
         throw new InvalidOperationException();
     }
     if (retransmit != null)
     {
         this.mRetransmit       = retransmit;
         this.mRetransmitEpoch  = this.mCurrentEpoch;
         this.mRetransmitExpiry = DateTimeUtilities.CurrentUnixMs() + 240000L;
     }
     this.mInHandshake  = false;
     this.mCurrentEpoch = this.mPendingEpoch;
     this.mPendingEpoch = null;
 }
Esempio n. 17
0
 internal virtual void HandshakeSuccessful(DtlsHandshakeRetransmit retransmit)
 {
     //IL_001c: Unknown result type (might be due to invalid IL or missing references)
     if (mReadEpoch == mCurrentEpoch || mWriteEpoch == mCurrentEpoch)
     {
         throw new InvalidOperationException();
     }
     if (retransmit != null)
     {
         mRetransmit       = retransmit;
         mRetransmitEpoch  = mCurrentEpoch;
         mRetransmitExpiry = DateTimeUtilities.CurrentUnixMs() + 240000;
     }
     mInHandshake  = false;
     mCurrentEpoch = mPendingEpoch;
     mPendingEpoch = null;
 }
Esempio n. 18
0
        protected static byte[] CreateRandomBlock(bool useGMTUnixTime, SecureRandom random, string asciiLabel)
        {
            /*
             * We use the TLS 1.0 PRF on the SecureRandom output, to guard against RNGs where the raw
             * output could be used to recover the internal state.
             */
            byte[] secret = new byte[32];
            random.NextBytes(secret);

            byte[] seed = new byte[8];
            // TODO Use high-resolution timer
            TlsUtilities.WriteUint64(DateTimeUtilities.CurrentUnixMs(), seed, 0);

            byte[] result = TlsUtilities.PRF(secret, asciiLabel, seed, 32);

            if (useGMTUnixTime)
            {
                TlsUtilities.WriteGmtUnixTime(result, 0);
            }

            return(result);
        }
Esempio n. 19
0
        public virtual int Receive(byte[] buf, int off, int len, int waitMillis)
        {
            long endMillis = DateTimeUtilities.CurrentUnixMs() + waitMillis;

            for (;;)
            {
                int length = transport.Receive(buf, off, len, waitMillis);
                if (length < 0 || !LostPacket(percentPacketLossReceiving))
                {
                    return(length);
                }

                Console.WriteLine("PACKET LOSS (" + length + " byte packet not received)");

                long now = DateTimeUtilities.CurrentUnixMs();
                if (now >= endMillis)
                {
                    return(-1);
                }

                waitMillis = (int)(endMillis - now);
            }
        }
        private double RandMult(SecureRandom random, ECPoint g, BigInteger n)
        {
            BigInteger[] ks = new BigInteger[128];
            for (int i = 0; i < ks.Length; ++i)
            {
                ks[i] = new BigInteger(n.BitLength - 1, random);
            }

            int     ki = 0;
            ECPoint p  = g;

            for (int i = 1; i <= PRE_ROUNDS; i++)
            {
                BigInteger k = ks[ki];
                p = g.Multiply(k);
                if (++ki == ks.Length)
                {
                    ki = 0;
                    g  = p;
                }
            }
            long startTime = DateTimeUtilities.CurrentUnixMs();

            for (int i = 1; i <= NUM_ROUNDS; i++)
            {
                BigInteger k = ks[ki];
                p = g.Multiply(k);
                if (++ki == ks.Length)
                {
                    ki = 0;
                    g  = p;
                }
            }
            long endTime = DateTimeUtilities.CurrentUnixMs();

            return((double)(endTime - startTime) / NUM_ROUNDS);
        }
Esempio n. 21
0
        public virtual int Receive(byte[] buf, int off, int len, int waitMillis)
        {
            long currentTimeMillis = DateTimeUtilities.CurrentUnixMs();

            Timeout timeout = Timeout.ForWaitMillis(waitMillis, currentTimeMillis);

            byte[] record = null;

            while (waitMillis >= 0)
            {
                if (mRetransmitTimeout != null && mRetransmitTimeout.RemainingMillis(currentTimeMillis) < 1)
                {
                    mRetransmit        = null;
                    mRetransmitEpoch   = null;
                    mRetransmitTimeout = null;
                }

                int receiveLimit = mTransport.GetReceiveLimit();
                if (record == null || record.Length < receiveLimit)
                {
                    record = new byte[receiveLimit];
                }

                int received  = ReceiveRecord(record, 0, receiveLimit, waitMillis);
                int processed = ProcessRecord(received, record, buf, off);
                if (processed >= 0)
                {
                    return(processed);
                }

                currentTimeMillis = DateTimeUtilities.CurrentUnixMs();
                waitMillis        = Timeout.GetWaitMillis(timeout, currentTimeMillis);
            }

            return(-1);
        }
        public PgpSignature Generate()
        {
            long num = DateTimeUtilities.CurrentUnixMs() / 1000;

            byte[] array = new byte[5]
            {
                (byte)signatureType,
                (byte)(num >> 24),
                (byte)(num >> 16),
                (byte)(num >> 8),
                (byte)num
            };
            sig.BlockUpdate(array, 0, array.Length);
            dig.BlockUpdate(array, 0, array.Length);
            byte[] encoding    = sig.GenerateSignature();
            byte[] array2      = DigestUtilities.DoFinal(dig);
            byte[] fingerprint = new byte[2]
            {
                array2[0],
                array2[1]
            };
            MPInteger[] signature = ((keyAlgorithm == PublicKeyAlgorithmTag.RsaSign || keyAlgorithm == PublicKeyAlgorithmTag.RsaGeneral) ? PgpUtilities.RsaSigToMpi(encoding) : PgpUtilities.DsaSigToMpi(encoding));
            return(new PgpSignature(new SignaturePacket(3, signatureType, privKey.KeyId, keyAlgorithm, hashAlgorithm, num * 1000, fingerprint, signature)));
        }
Esempio n. 23
0
 internal static Timeout ForWaitMillis(int waitMillis)
 {
     return(ForWaitMillis(waitMillis, DateTimeUtilities.CurrentUnixMs()));
 }
Esempio n. 24
0
 internal Timeout(long durationMillis)
     : this(durationMillis, DateTimeUtilities.CurrentUnixMs())
 {
 }
        private double RandMult(SecureRandom random, ECPoint g, BigInteger n)
        {
            BigInteger[] ks = new BigInteger[128];
            for (int i = 0; i < ks.Length; ++i)
            {
                ks[i] = new BigInteger(n.BitLength - 1, random);
            }

            int     ki = 0;
            ECPoint p  = g;

            {
                long startTime = DateTimeUtilities.CurrentUnixMs();
                long goalTime  = startTime + MILLIS_WARMUP;

                do
                {
                    BigInteger k = ks[ki];
                    p = g.Multiply(k);
                    if ((ki & 1) != 0)
                    {
                        g = p;
                    }
                    if (++ki == ks.Length)
                    {
                        ki = 0;
                    }
                }while (DateTimeUtilities.CurrentUnixMs() < goalTime);
            }

            double minRate = Double.MaxValue, maxRate = Double.MinValue, totalRate = 0.0;

            for (int i = 1; i <= NUM_ROUNDS; i++)
            {
                long startTime = DateTimeUtilities.CurrentUnixMs();
                long goalTime = startTime + MILLIS_PER_ROUND;
                long count = 0, endTime;

                do
                {
                    ++count;

                    for (int j = 0; j < MULTS_PER_CHECK; ++j)
                    {
                        BigInteger k = ks[ki];
                        p = g.Multiply(k);
                        if ((ki & 1) != 0)
                        {
                            g = p;
                        }
                        if (++ki == ks.Length)
                        {
                            ki = 0;
                        }
                    }

                    endTime = DateTimeUtilities.CurrentUnixMs();
                }while (endTime < goalTime);

                double roundElapsed = (double)(endTime - startTime);
                double roundRate    = count * MULTS_PER_CHECK * 1000L / roundElapsed;

                minRate    = System.Math.Min(minRate, roundRate);
                maxRate    = System.Math.Max(maxRate, roundRate);
                totalRate += roundRate;
            }

            return((totalRate - minRate - maxRate) / (NUM_ROUNDS - 2));
        }
Esempio n. 26
0
        public virtual int Receive(byte[] buf, int off, int len, int waitMillis)
        {
            byte[] array = null;
            int    result;

            while (true)
            {
                int num = Math.Min(len, this.GetReceiveLimit()) + 13;
                if (array == null || array.Length < num)
                {
                    array = new byte[num];
                }
                try
                {
                    if (this.mRetransmit != null && DateTimeUtilities.CurrentUnixMs() > this.mRetransmitExpiry)
                    {
                        this.mRetransmit      = null;
                        this.mRetransmitEpoch = null;
                    }
                    int num2 = this.ReceiveRecord(array, 0, num, waitMillis);
                    if (num2 < 0)
                    {
                        result = num2;
                    }
                    else
                    {
                        if (num2 < 13)
                        {
                            continue;
                        }
                        int num3 = TlsUtilities.ReadUint16(array, 11);
                        if (num2 != num3 + 13)
                        {
                            continue;
                        }
                        byte b = TlsUtilities.ReadUint8(array, 0);
                        switch (b)
                        {
                        case 20:
                        case 21:
                        case 22:
                        case 23:
                        case 24:
                        {
                            int       num4      = TlsUtilities.ReadUint16(array, 3);
                            DtlsEpoch dtlsEpoch = null;
                            if (num4 == this.mReadEpoch.Epoch)
                            {
                                dtlsEpoch = this.mReadEpoch;
                            }
                            else if (b == 22 && this.mRetransmitEpoch != null && num4 == this.mRetransmitEpoch.Epoch)
                            {
                                dtlsEpoch = this.mRetransmitEpoch;
                            }
                            if (dtlsEpoch == null)
                            {
                                continue;
                            }
                            long num5 = TlsUtilities.ReadUint48(array, 5);
                            if (dtlsEpoch.ReplayWindow.ShouldDiscard(num5))
                            {
                                continue;
                            }
                            ProtocolVersion other = TlsUtilities.ReadVersion(array, 1);
                            if (this.mDiscoveredPeerVersion != null && !this.mDiscoveredPeerVersion.Equals(other))
                            {
                                continue;
                            }
                            byte[] array2 = dtlsEpoch.Cipher.DecodeCiphertext(DtlsRecordLayer.GetMacSequenceNumber(dtlsEpoch.Epoch, num5), b, array, 13, num2 - 13);
                            dtlsEpoch.ReplayWindow.ReportAuthenticated(num5);
                            if (array2.Length > this.mPlaintextLimit)
                            {
                                continue;
                            }
                            if (this.mDiscoveredPeerVersion == null)
                            {
                                this.mDiscoveredPeerVersion = other;
                            }
                            switch (b)
                            {
                            case 20:
                                for (int i = 0; i < array2.Length; i++)
                                {
                                    byte b2 = TlsUtilities.ReadUint8(array2, i);
                                    if (b2 == 1 && this.mPendingEpoch != null)
                                    {
                                        this.mReadEpoch = this.mPendingEpoch;
                                    }
                                }
                                continue;

                            case 21:
                                if (array2.Length == 2)
                                {
                                    byte b3 = array2[0];
                                    byte b4 = array2[1];
                                    this.mPeer.NotifyAlertReceived(b3, b4);
                                    if (b3 == 2)
                                    {
                                        this.Fail(b4);
                                        throw new TlsFatalAlert(b4);
                                    }
                                    if (b4 == 0)
                                    {
                                        this.CloseTransport();
                                    }
                                }
                                continue;

                            case 22:
                                if (!this.mInHandshake)
                                {
                                    if (this.mRetransmit != null)
                                    {
                                        this.mRetransmit.ReceivedHandshakeRecord(num4, array2, 0, array2.Length);
                                    }
                                    continue;
                                }
                                break;

                            case 23:
                                if (this.mInHandshake)
                                {
                                    continue;
                                }
                                break;

                            case 24:
                                continue;
                            }
                            if (!this.mInHandshake && this.mRetransmit != null)
                            {
                                this.mRetransmit      = null;
                                this.mRetransmitEpoch = null;
                            }
                            Array.Copy(array2, 0, buf, off, array2.Length);
                            result = array2.Length;
                            break;
                        }

                        default:
                            continue;
                        }
                    }
                }
                catch (IOException ex)
                {
                    throw ex;
                }
                break;
            }
            return(result);
        }
Esempio n. 27
0
        public virtual int Receive(byte[] buf, int off, int len, int waitMillis)
        {
            byte[] record = null;

            for (;;)
            {
                int receiveLimit = System.Math.Min(len, GetReceiveLimit()) + RECORD_HEADER_LENGTH;
                if (record == null || record.Length < receiveLimit)
                {
                    record = new byte[receiveLimit];
                }

                try
                {
                    if (mRetransmit != null && DateTimeUtilities.CurrentUnixMs() > mRetransmitExpiry)
                    {
                        mRetransmit      = null;
                        mRetransmitEpoch = null;
                    }

                    int received = ReceiveRecord(record, 0, receiveLimit, waitMillis);
                    if (received < 0)
                    {
                        return(received);
                    }
                    if (received < RECORD_HEADER_LENGTH)
                    {
                        continue;
                    }
                    int length = TlsUtilities.ReadUint16(record, 11);
                    if (received != (length + RECORD_HEADER_LENGTH))
                    {
                        continue;
                    }

                    byte type = TlsUtilities.ReadUint8(record, 0);

                    // TODO Support user-specified custom protocols?
                    switch (type)
                    {
                    case ContentType.alert:
                    case ContentType.application_data:
                    case ContentType.change_cipher_spec:
                    case ContentType.handshake:
                    case ContentType.heartbeat:
                        break;

                    default:
                        // TODO Exception?
                        continue;
                    }

                    int epoch = TlsUtilities.ReadUint16(record, 3);

                    DtlsEpoch recordEpoch = null;
                    if (epoch == mReadEpoch.Epoch)
                    {
                        recordEpoch = mReadEpoch;
                    }
                    else if (type == ContentType.handshake && mRetransmitEpoch != null &&
                             epoch == mRetransmitEpoch.Epoch)
                    {
                        recordEpoch = mRetransmitEpoch;
                    }

                    if (recordEpoch == null)
                    {
                        continue;
                    }

                    long seq = TlsUtilities.ReadUint48(record, 5);
                    if (recordEpoch.ReplayWindow.ShouldDiscard(seq))
                    {
                        continue;
                    }

                    ProtocolVersion version = TlsUtilities.ReadVersion(record, 1);
                    if (!version.IsDtls)
                    {
                        continue;
                    }

                    if (mReadVersion != null && !mReadVersion.Equals(version))
                    {
                        continue;
                    }

                    byte[] plaintext = recordEpoch.Cipher.DecodeCiphertext(
                        GetMacSequenceNumber(recordEpoch.Epoch, seq), type, record, RECORD_HEADER_LENGTH,
                        received - RECORD_HEADER_LENGTH);

                    recordEpoch.ReplayWindow.ReportAuthenticated(seq);

                    if (plaintext.Length > this.mPlaintextLimit)
                    {
                        continue;
                    }

                    if (mReadVersion == null)
                    {
                        mReadVersion = version;
                    }

                    switch (type)
                    {
                    case ContentType.alert:
                    {
                        if (plaintext.Length == 2)
                        {
                            byte alertLevel       = plaintext[0];
                            byte alertDescription = plaintext[1];

                            mPeer.NotifyAlertReceived(alertLevel, alertDescription);

                            if (alertLevel == AlertLevel.fatal)
                            {
                                Failed();
                                throw new TlsFatalAlert(alertDescription);
                            }

                            // TODO Can close_notify be a fatal alert?
                            if (alertDescription == AlertDescription.close_notify)
                            {
                                CloseTransport();
                            }
                        }

                        continue;
                    }

                    case ContentType.application_data:
                    {
                        if (mInHandshake)
                        {
                            // TODO Consider buffering application data for new epoch that arrives
                            // out-of-order with the Finished message
                            continue;
                        }
                        break;
                    }

                    case ContentType.change_cipher_spec:
                    {
                        // Implicitly receive change_cipher_spec and change to pending cipher state

                        for (int i = 0; i < plaintext.Length; ++i)
                        {
                            byte message = TlsUtilities.ReadUint8(plaintext, i);
                            if (message != ChangeCipherSpec.change_cipher_spec)
                            {
                                continue;
                            }

                            if (mPendingEpoch != null)
                            {
                                mReadEpoch = mPendingEpoch;
                            }
                        }

                        continue;
                    }

                    case ContentType.handshake:
                    {
                        if (!mInHandshake)
                        {
                            if (mRetransmit != null)
                            {
                                mRetransmit.ReceivedHandshakeRecord(epoch, plaintext, 0, plaintext.Length);
                            }

                            // TODO Consider support for HelloRequest
                            continue;
                        }
                        break;
                    }

                    case ContentType.heartbeat:
                    {
                        // TODO[RFC 6520]
                        continue;
                    }
                    }

                    /*
                     * NOTE: If we receive any non-handshake data in the new epoch implies the peer has
                     * received our final flight.
                     */
                    if (!mInHandshake && mRetransmit != null)
                    {
                        this.mRetransmit      = null;
                        this.mRetransmitEpoch = null;
                    }

                    Array.Copy(plaintext, 0, buf, off, plaintext.Length);
                    return(plaintext.Length);
                }
                catch (IOException e)
                {
                    // NOTE: Assume this is a timeout for the moment
                    throw e;
                }
            }
        }
Esempio n. 28
0
        /// <summary>Connects to the remote system.</summary>
        /// <param name="verifyer">Will be used when a certificate is received to verify
        /// that this certificate is accepted by the client.</param>
        /// <exception cref="IOException">If handshake was not successful</exception>
        public virtual void Connect(
            ICertificateVerifyer verifyer)
        {
            this.verifyer = verifyer;

            /*
             * Send Client hello
             *
             * First, generate some random data.
             */
            this.clientRandom = new byte[32];

            /*
             * TLS 1.0 requires a unix-timestamp in the first 4 bytes
             */
            int t = (int)(DateTimeUtilities.CurrentUnixMs() / 1000L);

            this.clientRandom[0] = (byte)(t >> 24);
            this.clientRandom[1] = (byte)(t >> 16);
            this.clientRandom[2] = (byte)(t >> 8);
            this.clientRandom[3] = (byte)t;

            random.NextBytes(this.clientRandom, 4, 28);


            MemoryStream outStr = new MemoryStream();

            TlsUtilities.WriteVersion(outStr);
            outStr.Write(this.clientRandom, 0, this.clientRandom.Length);

            /*
             * Length of Session id
             */
            TlsUtilities.WriteUint8((short)0, outStr);

            /*
             * Cipher suites
             */
            TlsCipherSuiteManager.WriteCipherSuites(outStr);

            /*
             * Compression methods, just the null method.
             */
            byte[] compressionMethods = new byte[] { 0x00 };
            TlsUtilities.WriteUint8((short)compressionMethods.Length, outStr);
            outStr.Write(compressionMethods, 0, compressionMethods.Length);


            MemoryStream bos = new MemoryStream();

            TlsUtilities.WriteUint8(HP_CLIENT_HELLO, bos);
            TlsUtilities.WriteUint24((int)outStr.Length, bos);
            byte[] outBytes = outStr.ToArray();
            bos.Write(outBytes, 0, outBytes.Length);
            byte[] message = bos.ToArray();
            rs.WriteMessage(RL_HANDSHAKE, message, 0, message.Length);
            connection_state = CS_CLIENT_HELLO_SEND;

            /*
             * We will now read data, until we have completed the handshake.
             */
            while (connection_state != CS_DONE)
            {
                rs.ReadData();
            }

            this.tlsInputStream  = new TlsInputStream(this);
            this.tlsOutputStream = new TlsOuputStream(this);
        }
Esempio n. 29
0
 public LoggingDatagramTransport(DatagramTransport transport, TextWriter output)
 {
     this.transport       = transport;
     this.output          = output;
     this.launchTimestamp = DateTimeUtilities.CurrentUnixMs();
 }
Esempio n. 30
0
        public virtual int Receive(byte[] buf, int off, int len, int waitMillis)
        {
            //IL_02c8: Expected O, but got Unknown
            byte[] array = null;
            while (true)
            {
                int num = Math.Min(len, GetReceiveLimit()) + 13;
                if (array == null || array.Length < num)
                {
                    array = new byte[num];
                }
                try
                {
                    if (mRetransmit != null && DateTimeUtilities.CurrentUnixMs() > mRetransmitExpiry)
                    {
                        mRetransmit      = null;
                        mRetransmitEpoch = null;
                    }
                    int num2 = ReceiveRecord(array, 0, num, waitMillis);
                    if (num2 < 0)
                    {
                        return(num2);
                    }
                    if (num2 < 13)
                    {
                        continue;
                    }
                    int num3 = TlsUtilities.ReadUint16(array, 11);
                    if (num2 != num3 + 13)
                    {
                        continue;
                    }
                    byte b = TlsUtilities.ReadUint8(array, 0);
                    switch (b)
                    {
                    case 20:
                    case 21:
                    case 22:
                    case 23:
                    case 24:
                    {
                        int       num4      = TlsUtilities.ReadUint16(array, 3);
                        DtlsEpoch dtlsEpoch = null;
                        if (num4 == mReadEpoch.Epoch)
                        {
                            dtlsEpoch = mReadEpoch;
                        }
                        else if (b == 22 && mRetransmitEpoch != null && num4 == mRetransmitEpoch.Epoch)
                        {
                            dtlsEpoch = mRetransmitEpoch;
                        }
                        if (dtlsEpoch == null)
                        {
                            break;
                        }
                        long num5 = TlsUtilities.ReadUint48(array, 5);
                        if (dtlsEpoch.ReplayWindow.ShouldDiscard(num5))
                        {
                            break;
                        }
                        ProtocolVersion protocolVersion = TlsUtilities.ReadVersion(array, 1);
                        if (!protocolVersion.IsDtls || (mReadVersion != null && !mReadVersion.Equals(protocolVersion)))
                        {
                            break;
                        }
                        byte[] array2 = dtlsEpoch.Cipher.DecodeCiphertext(GetMacSequenceNumber(dtlsEpoch.Epoch, num5), b, array, 13, num2 - 13);
                        dtlsEpoch.ReplayWindow.ReportAuthenticated(num5);
                        if (array2.Length > mPlaintextLimit)
                        {
                            break;
                        }
                        if (mReadVersion == null)
                        {
                            mReadVersion = protocolVersion;
                        }
                        switch (b)
                        {
                        case 21:
                            if (array2.Length == 2)
                            {
                                byte b2 = array2[0];
                                byte b3 = array2[1];
                                mPeer.NotifyAlertReceived(b2, b3);
                                if (b2 == 2)
                                {
                                    Fail(b3);
                                    throw new TlsFatalAlert(b3);
                                }
                                if (b3 == 0)
                                {
                                    CloseTransport();
                                }
                            }
                            goto end_IL_0022;

                        case 23:
                            if (!mInHandshake)
                            {
                                break;
                            }
                            goto end_IL_0022;

                        case 20:
                        {
                            for (int i = 0; i < array2.Length; i++)
                            {
                                byte b4 = TlsUtilities.ReadUint8(array2, i);
                                if (b4 == 1 && mPendingEpoch != null)
                                {
                                    mReadEpoch = mPendingEpoch;
                                }
                            }
                            goto end_IL_0022;
                        }

                        case 22:
                            if (mInHandshake)
                            {
                                break;
                            }
                            if (mRetransmit != null)
                            {
                                mRetransmit.ReceivedHandshakeRecord(num4, array2, 0, array2.Length);
                            }
                            goto end_IL_0022;

                        case 24:
                            goto end_IL_0022;
                        }
                        if (!mInHandshake && mRetransmit != null)
                        {
                            mRetransmit      = null;
                            mRetransmitEpoch = null;
                        }
                        global::System.Array.Copy((global::System.Array)array2, 0, (global::System.Array)buf, off, array2.Length);
                        return(array2.Length);
                    }
                    }
                    end_IL_0022 :;
                }
                catch (IOException val)
                {
                    IOException val2 = val;
                    throw val2;
                }
            }
        }