Пример #1
0
		public static HandshakeMessage ReadMessage (TlsContext context, HandshakeType handshakeType, TlsBuffer incoming)
		{
			HandshakeMessage message;
			switch (handshakeType) {
			case HandshakeType.HelloRequest:
				message = new TlsHelloRequest ();
				break;
			case HandshakeType.ServerHello:
				return new TlsServerHello (context, incoming);
			case HandshakeType.Certificate:
				return new TlsCertificate (incoming);
			case HandshakeType.ServerHelloDone:
				message = new TlsServerHelloDone ();
				break;
			case HandshakeType.Finished:
				return new TlsFinished (incoming);
			case HandshakeType.ClientHello:
				return new TlsClientHello (context, incoming);
			case HandshakeType.ClientKeyExchange:
				return new TlsClientKeyExchange (context, incoming);
			case HandshakeType.CertificateRequest:
				return new TlsCertificateRequest (context.NegotiatedProtocol, incoming);
			case HandshakeType.CertificateVerify:
				return new TlsCertificateVerify (context.NegotiatedProtocol, incoming);
			case HandshakeType.ServerKeyExchange:
				return new TlsServerKeyExchange (context, incoming);
			default:
				throw new TlsException (AlertDescription.UnexpectedMessage, "Unknown server handshake message received: {0}", handshakeType);
			}

			message.Read (incoming);
			return message;
		}
Пример #2
0
		public TlsClientHello (TlsContext context, TlsBuffer incoming)
			: base (HandshakeType.ClientHello)
		{
			ClientProtocol = (TlsProtocolCode)incoming.ReadInt16 ();

			Read (incoming);
		}
Пример #3
0
		public override void GenerateClient (TlsContext ctx)
		{
			// Compute pre master secret
			using (var preMasterSecret = ctx.Session.GetSecureRandomBytes (48)) {
				preMasterSecret.Buffer [0] = (byte)((short)ctx.Configuration.RequestedProtocol >> 8);
				preMasterSecret.Buffer [1] = (byte)ctx.Configuration.RequestedProtocol;

				RSA rsa = null;
				// Create a new RSA key
				var serverCertificates = ctx.Session.PendingCrypto.ServerCertificates;
				if (serverCertificates == null || serverCertificates.Count == 0) {
					// FIXME: Should have received ServerKeyExchange message.
					throw new TlsException (AlertDescription.IlegalParameter);
				} else {
					rsa = new RSAManaged (serverCertificates [0].RSA.KeySize);
					rsa.ImportParameters (serverCertificates [0].RSA.ExportParameters (false));
				}

				ComputeMasterSecret (ctx, preMasterSecret);

				// Encrypt premaster_sercret
				var formatter = new RSAPKCS1KeyExchangeFormatter (rsa);
				encryptedPreMasterSecret = formatter.CreateKeyExchange (preMasterSecret.Buffer);
				rsa.Clear ();
			}
		}
        /// <exception cref="IOException"></exception>
        public Chacha20Poly1305(TlsContext context)
        {
            if (!TlsUtilities.IsTlsV12(context))
                throw new TlsFatalAlert(AlertDescription.internal_error);

            this.context = context;

            byte[] key_block = TlsUtilities.CalculateKeyBlock(context, 64);

            KeyParameter client_write_key = new KeyParameter(key_block, 0, 32);
            KeyParameter server_write_key = new KeyParameter(key_block, 32, 32);

            this.encryptCipher = new ChaChaEngine(20);
            this.decryptCipher = new ChaChaEngine(20);

            KeyParameter encryptKey, decryptKey;
            if (context.IsServer)
            {
                encryptKey = server_write_key;
                decryptKey = client_write_key;
            }
            else
            {
                encryptKey = client_write_key;
                decryptKey = server_write_key;
            }

            byte[] dummyNonce = new byte[8];

            this.encryptCipher.Init(true, new ParametersWithIV(encryptKey, dummyNonce));
            this.decryptCipher.Init(false, new ParametersWithIV(decryptKey, dummyNonce));
        }
		public DiffieHellmanKeyExchange (TlsContext ctx)
		{
			this.protocol = ctx.NegotiatedProtocol;

			switch (protocol) {
			case TlsProtocolCode.Tls12:
				Signature = new SignatureTls12 (ctx.Session.ServerSignatureAlgorithm);
				break;
			case TlsProtocolCode.Tls10:
				Signature = new SignatureTls10 ();
				break;
			case TlsProtocolCode.Tls11:
				Signature = new SignatureTls11 ();
				break;
			default:
				throw new NotSupportedException ();
			}

			dh = new DiffieHellmanManaged ();
			Y = dh.CreateKeyExchange ();
			var dhparams = dh.ExportParameters (true);
			P = dhparams.P;
			G = dhparams.G;

			using (var buffer = CreateParameterBuffer (ctx.HandshakeParameters))
				Signature.Create (buffer, ctx.Configuration.PrivateKey);
		}
Пример #6
0
		public TlsServerHello (TlsContext context, TlsBuffer incoming)
			: base (HandshakeType.ServerHello)
		{
			ServerProtocol = (TlsProtocolCode)incoming.ReadInt16 ();

			Read (incoming);
		}
		internal static RenegotiationExtension CreateClient (TlsContext context)
		{
			if (!context.Session.SecureRenegotiation && (context.Configuration.RenegotiationFlags & RenegotiationFlags.SendClientHelloExtension) == 0)
				return null;

			context.HandshakeParameters.RequestedSecureNegotiation = true;
			return new RenegotiationExtension (context.Session.ClientVerifyData);
		}
Пример #8
0
        internal static TlsEncryptionCredentials LoadEncryptionCredentials(TlsContext context,
            string[] certResources, string keyResource)
        {
            Certificate certificate = LoadCertificateChain(certResources);
            AsymmetricKeyParameter privateKey = LoadPrivateKeyResource(keyResource);

            return new DefaultTlsEncryptionCredentials(context, certificate, privateKey);
        }
Пример #9
0
        internal static TlsSignerCredentials LoadSignerCredentials(TlsContext context, string[] certResources,
            string keyResource, SignatureAndHashAlgorithm signatureAndHashAlgorithm)
        {
            Certificate certificate = LoadCertificateChain(certResources);
            AsymmetricKeyParameter privateKey = LoadPrivateKeyResource(keyResource);

            return new DefaultTlsSignerCredentials(context, certificate, privateKey, signatureAndHashAlgorithm);
        }
Пример #10
0
        /// <exception cref="IOException"></exception>
        public TlsAeadCipher(TlsContext context, IAeadBlockCipher clientWriteCipher, IAeadBlockCipher serverWriteCipher,
            int cipherKeySize, int macSize)
        {
            if (!TlsUtilities.IsTlsV12(context))
                throw new TlsFatalAlert(AlertDescription.internal_error);

            this.context = context;
            this.macSize = macSize;

            // NOTE: Valid for RFC 5288/6655 ciphers but may need review for other AEAD ciphers
            this.nonce_explicit_length = 8;

            // TODO SecurityParameters.fixed_iv_length
            int fixed_iv_length = 4;

            int key_block_size = (2 * cipherKeySize) + (2 * fixed_iv_length);

            byte[] key_block = TlsUtilities.CalculateKeyBlock(context, key_block_size);

            int offset = 0;

            KeyParameter client_write_key = new KeyParameter(key_block, offset, cipherKeySize);
            offset += cipherKeySize;
            KeyParameter server_write_key = new KeyParameter(key_block, offset, cipherKeySize);
            offset += cipherKeySize;
            byte[] client_write_IV = Arrays.CopyOfRange(key_block, offset, offset + fixed_iv_length);
            offset += fixed_iv_length;
            byte[] server_write_IV = Arrays.CopyOfRange(key_block, offset, offset + fixed_iv_length);
            offset += fixed_iv_length;

            if (offset != key_block_size)
                throw new TlsFatalAlert(AlertDescription.internal_error);

            KeyParameter encryptKey, decryptKey;
            if (context.IsServer)
            {
                this.encryptCipher = serverWriteCipher;
                this.decryptCipher = clientWriteCipher;
                this.encryptImplicitNonce = server_write_IV;
                this.decryptImplicitNonce = client_write_IV;
                encryptKey = server_write_key;
                decryptKey = client_write_key;
            }
            else
            {
                this.encryptCipher = clientWriteCipher;
                this.decryptCipher = serverWriteCipher;
                this.encryptImplicitNonce = client_write_IV;
                this.decryptImplicitNonce = server_write_IV;
                encryptKey = client_write_key;
                decryptKey = server_write_key;
            }

            byte[] dummyNonce = new byte[fixed_iv_length + nonce_explicit_length];

            this.encryptCipher.Init(true, new AeadParameters(encryptKey, 8 * macSize, dummyNonce));
            this.decryptCipher.Init(false, new AeadParameters(decryptKey, 8 * macSize, dummyNonce));
        }
        public override void Init(TlsContext context)
        {
            base.Init(context);

            if (this.mTlsSigner != null)
            {
                this.mTlsSigner.Init(context);
            }
        }
		public override void GenerateClient (TlsContext ctx)
		{
			using (var dh = new DiffieHellmanManaged (P, G, 0)) {
				using (var X = new SecureBuffer (dh.DecryptKeyExchange (Y))) {
					Y = dh.CreateKeyExchange ();
					ComputeMasterSecret (ctx, X);
				}
			}
		}
		public override void GenerateClient (TlsContext context)
		{
			GenerateKeyPair (context, domainParameters, out clientQ, out clientD);
			clientKey = ExternalizeKey (clientQ);

			var agreement = CalculateAgreement (serverQ, clientD);
			using (var preMaster = new SecureBuffer (agreement.ToByteArrayUnsigned ()))
				ComputeMasterSecret (context, preMaster);
		}
Пример #14
0
        internal virtual void Init(TlsContext context)
        {
            this.mReadCipher = new TlsNullCipher(context);
            this.mWriteCipher = this.mReadCipher;
            this.mHandshakeHash = new DeferredHash();
            this.mHandshakeHash.Init(context);

            SetPlaintextLimit(DEFAULT_PLAINTEXT_LIMIT);
        }
Пример #15
0
 /// <exception cref="IOException"></exception>
 public override TlsCipher CreateCipher(TlsContext context, int encryptionAlgorithm, int macAlgorithm)
 {
     switch (encryptionAlgorithm)
     {
     case EncryptionAlgorithm.cls_3DES_EDE_CBC:
         return CreateDesEdeCipher(context, macAlgorithm);
     case EncryptionAlgorithm.AES_128_CBC:
         return CreateAESCipher(context, 16, macAlgorithm);
     case EncryptionAlgorithm.AES_128_CCM:
         // NOTE: Ignores macAlgorithm
         return CreateCipher_Aes_Ccm(context, 16, 16);
     case EncryptionAlgorithm.AES_128_CCM_8:
         // NOTE: Ignores macAlgorithm
         return CreateCipher_Aes_Ccm(context, 16, 8);
     case EncryptionAlgorithm.AES_128_GCM:
         // NOTE: Ignores macAlgorithm
         return CreateCipher_Aes_Gcm(context, 16, 16);
     case EncryptionAlgorithm.AES_128_OCB_TAGLEN96:
         // NOTE: Ignores macAlgorithm
         return CreateCipher_Aes_Ocb(context, 16, 12);
     case EncryptionAlgorithm.AES_256_CBC:
         return CreateAESCipher(context, 32, macAlgorithm);
     case EncryptionAlgorithm.AES_256_CCM:
         // NOTE: Ignores macAlgorithm
         return CreateCipher_Aes_Ccm(context, 32, 16);
     case EncryptionAlgorithm.AES_256_CCM_8:
         // NOTE: Ignores macAlgorithm
         return CreateCipher_Aes_Ccm(context, 32, 8);
     case EncryptionAlgorithm.AES_256_GCM:
         // NOTE: Ignores macAlgorithm
         return CreateCipher_Aes_Gcm(context, 32, 16);
     case EncryptionAlgorithm.AES_256_OCB_TAGLEN96:
         // NOTE: Ignores macAlgorithm
         return CreateCipher_Aes_Ocb(context, 32, 12);
     case EncryptionAlgorithm.CAMELLIA_128_CBC:
         return CreateCamelliaCipher(context, 16, macAlgorithm);
     case EncryptionAlgorithm.CAMELLIA_128_GCM:
         // NOTE: Ignores macAlgorithm
         return CreateCipher_Camellia_Gcm(context, 16, 16);
     case EncryptionAlgorithm.CAMELLIA_256_CBC:
         return CreateCamelliaCipher(context, 32, macAlgorithm);
     case EncryptionAlgorithm.CAMELLIA_256_GCM:
         // NOTE: Ignores macAlgorithm
         return CreateCipher_Camellia_Gcm(context, 32, 16);
     case EncryptionAlgorithm.CHACHA20_POLY1305:
         // NOTE: Ignores macAlgorithm
         return CreateChaCha20Poly1305(context);
     case EncryptionAlgorithm.NULL:
         return CreateNullCipher(context, macAlgorithm);
     case EncryptionAlgorithm.RC4_128:
         return CreateRC4Cipher(context, 16, macAlgorithm);
     case EncryptionAlgorithm.SEED_CBC:
         return CreateSeedCipher(context, macAlgorithm);
     default:
         throw new TlsFatalAlert(AlertDescription.internal_error);
     }
 }
		public override void HandleClient (TlsContext context, KeyExchange clientExchange)
		{
			var clientKey = ((EllipticCurveKeyExchange)clientExchange).clientKey;

			clientQ = domainParameters.Curve.DecodePoint (clientKey);

			var agreement = CalculateAgreement (clientQ, serverD);
			using (var preMaster = new SecureBuffer (agreement.ToByteArrayUnsigned ()))
				ComputeMasterSecret (context, preMaster);
		}
 /**
  * Parse a {@link DigitallySigned} from a {@link Stream}.
  * 
  * @param context
  *            the {@link TlsContext} of the current connection.
  * @param input
  *            the {@link Stream} to parse from.
  * @return a {@link DigitallySigned} object.
  * @throws IOException
  */
 public static DigitallySigned Parse(TlsContext context, Stream input)
 {
     SignatureAndHashAlgorithm algorithm = null;
     if (TlsUtilities.IsTlsV12(context))
     {
         algorithm = SignatureAndHashAlgorithm.Parse(input);
     }
     byte[] signature = TlsUtilities.ReadOpaque16(input);
     return new DigitallySigned(algorithm, signature);
 }
Пример #18
0
		void ComputeMasterSecret (DisposeContext d, TlsContext ctx, SecureBuffer preMasterSecret)
		{
			// Compute ClientRandom + ServerRandom
			int clen = ctx.HandshakeParameters.ClientRandom.Size;
			int slen = ctx.HandshakeParameters.ServerRandom.Size;
			int rlen = clen + slen;
			var cs = d.CreateBuffer (rlen);
			Buffer.BlockCopy (ctx.HandshakeParameters.ClientRandom.Buffer, 0, cs.Buffer, 0, clen);
			Buffer.BlockCopy (ctx.HandshakeParameters.ServerRandom.Buffer, 0, cs.Buffer, clen, slen);

			// Server Random + Client Random
			var sc = d.CreateBuffer (rlen);
			Buffer.BlockCopy (ctx.HandshakeParameters.ServerRandom.Buffer, 0, sc.Buffer, 0, slen);
			Buffer.BlockCopy (ctx.HandshakeParameters.ClientRandom.Buffer, 0, sc.Buffer, slen, clen);

			// Create master secret
			var crypto = ctx.Session.PendingCrypto;
			crypto.MasterSecret = crypto.Cipher.PRF.ComputeMasterSecret (preMasterSecret, cs);

			#if DEBUG_FULL
			if (ctx.EnableDebugging) {
				DebugHelper.WriteLine ("CS", cs);
				DebugHelper.WriteLine ("SC", sc);
				DebugHelper.WriteLine ("PRE-MASTER", preMasterSecret);
				DebugHelper.WriteLine ("MASTER SECRET", crypto.MasterSecret.Buffer);
			}
			#endif

			var keyBlock = crypto.Cipher.PRF.ComputeKeyExpansion (d, crypto.MasterSecret, sc, crypto.Cipher.KeyBlockSize);

			#if DEBUG_FULL
			if (ctx.EnableDebugging) {
				DebugHelper.WriteLine ("KEY BLOCK SIZE: {0}", crypto.Cipher.KeyBlockSize);
				DebugHelper.WriteLine ("KEY BLOCK", keyBlock.Buffer);
			}
			#endif

			crypto.ClientWriteMac = keyBlock.ReadSecureBuffer (crypto.Cipher.HashSize);
			crypto.ServerWriteMac = keyBlock.ReadSecureBuffer (crypto.Cipher.HashSize);
			crypto.ClientWriteKey = keyBlock.ReadSecureBuffer (crypto.Cipher.KeyMaterialSize);
			crypto.ServerWriteKey = keyBlock.ReadSecureBuffer (crypto.Cipher.KeyMaterialSize);

			if (crypto.Cipher.HasFixedIV) {
				crypto.ClientWriteIV = keyBlock.ReadSecureBuffer (crypto.Cipher.FixedIvSize);
				crypto.ServerWriteIV = keyBlock.ReadSecureBuffer (crypto.Cipher.FixedIvSize);

				#if DEBUG_FULL
				if (ctx.EnableDebugging) {
					DebugHelper.WriteLine ("CLIENT IV", crypto.ClientWriteIV.Buffer);
					DebugHelper.WriteLine ("SERVER IV", crypto.ServerWriteIV.Buffer);
				}
				#endif
			}
		}
Пример #19
0
        /**
         * Encode this {@link HeartbeatMessage} to a {@link Stream}.
         * 
         * @param output
         *            the {@link Stream} to encode to.
         * @throws IOException
         */
        public virtual void Encode(TlsContext context, Stream output)
        {
            TlsUtilities.WriteUint8(mType, output);

            TlsUtilities.CheckUint16(mPayload.Length);
            TlsUtilities.WriteUint16(mPayload.Length, output);
            output.Write(mPayload, 0, mPayload.Length);

            byte[] padding = new byte[mPaddingLength];
            context.NonceRandomGenerator.NextBytes(padding);
            output.Write(padding, 0, padding.Length);
        }
Пример #20
0
        /// <exception cref="IOException"></exception>
        public Chacha20Poly1305(TlsContext context)
        {
            if (!TlsUtilities.IsTlsV12(context))
                throw new TlsFatalAlert(AlertDescription.internal_error);

            this.context = context;

            int cipherKeySize = 32;
            // TODO SecurityParameters.fixed_iv_length
            int fixed_iv_length = 12;
            // TODO SecurityParameters.record_iv_length = 0

            int key_block_size = (2 * cipherKeySize) + (2 * fixed_iv_length);

            byte[] key_block = TlsUtilities.CalculateKeyBlock(context, key_block_size);

            int offset = 0;

            KeyParameter client_write_key = new KeyParameter(key_block, offset, cipherKeySize);
            offset += cipherKeySize;
            KeyParameter server_write_key = new KeyParameter(key_block, offset, cipherKeySize);
            offset += cipherKeySize;
            byte[] client_write_IV = Arrays.CopyOfRange(key_block, offset, offset + fixed_iv_length);
            offset += fixed_iv_length;
            byte[] server_write_IV = Arrays.CopyOfRange(key_block, offset, offset + fixed_iv_length);
            offset += fixed_iv_length;

            if (offset != key_block_size)
                throw new TlsFatalAlert(AlertDescription.internal_error);

            this.encryptCipher = new ChaCha7539Engine();
            this.decryptCipher = new ChaCha7539Engine();

            KeyParameter encryptKey, decryptKey;
            if (context.IsServer)
            {
                encryptKey = server_write_key;
                decryptKey = client_write_key;
                this.encryptIV = server_write_IV;
                this.decryptIV = client_write_IV;
            }
            else
            {
                encryptKey = client_write_key;
                decryptKey = server_write_key;
                this.encryptIV = client_write_IV;
                this.decryptIV = server_write_IV;
            }

            this.encryptCipher.Init(true, new ParametersWithIV(encryptKey, encryptIV));
            this.decryptCipher.Init(false, new ParametersWithIV(decryptKey, decryptIV));
        }
		public EllipticCurveKeyExchange (TlsContext context)
		{
			curveType = ECCurveType.named_curve;
			namedCurve = context.Configuration.UserSettings.NamedCurve ?? NamedCurve.secp256k1;
			domainParameters = NamedCurveHelper.GetECParameters (namedCurve);

			GenerateKeyPair (context, domainParameters, out serverQ, out serverD);
			publicBytes = ExternalizeKey (serverQ);

			Signature = new SignatureTls12 (context.Session.ServerSignatureAlgorithm);
			using (var buffer = CreateParameterBuffer (context.HandshakeParameters))
				Signature.Create (buffer, context.Configuration.PrivateKey);
		}
Пример #22
0
        /**
         * Generate a new instance of an TlsMac.
         *
         * @param context the TLS client context
         * @param digest  The digest to use.
         * @param key     A byte-array where the key for this MAC is located.
         * @param keyOff  The number of bytes to skip, before the key starts in the buffer.
         * @param keyLen  The length of the key.
         */
        public TlsMac(TlsContext context, IDigest digest, byte[] key, int keyOff, int keyLen)
        {
            this.context = context;

            KeyParameter keyParameter = new KeyParameter(key, keyOff, keyLen);

            this.secret = Arrays.Clone(keyParameter.GetKey());

            // TODO This should check the actual algorithm, not rely on the engine type
            if (digest is LongDigest)
            {
                this.digestBlockSize = 128;
                this.digestOverhead = 16;
            }
            else
            {
                this.digestBlockSize = 64;
                this.digestOverhead = 8;
            }

            if (TlsUtilities.IsSsl(context))
            {
                this.mac = new Ssl3Mac(digest);

                // TODO This should check the actual algorithm, not assume based on the digest size
                if (digest.GetDigestSize() == 20)
                {
                    /*
                     * NOTE: When SHA-1 is used with the SSL 3.0 MAC, the secret + input pad is not
                     * digest block-aligned.
                     */
                    this.digestOverhead = 4;
                }
            }
            else
            {
                this.mac = new HMac(digest);

                // NOTE: The input pad for HMAC is always a full digest block
            }

            this.mac.Init(keyParameter);

            this.macLength = mac.GetMacSize();
            if (context.SecurityParameters.truncatedHMac)
            {
                this.macLength = System.Math.Min(this.macLength, 10);
            }
        }
Пример #23
0
        internal DtlsRecordLayer(DatagramTransport transport, TlsContext context, TlsPeer peer, byte contentType)
        {
            this.mTransport = transport;
            this.mContext = context;
            this.mPeer = peer;

            this.mInHandshake = true;

            this.mCurrentEpoch = new DtlsEpoch(0, new TlsNullCipher(context));
            this.mPendingEpoch = null;
            this.mReadEpoch = mCurrentEpoch;
            this.mWriteEpoch = mCurrentEpoch;

            SetPlaintextLimit(MAX_FRAGMENT_LENGTH);
        }
Пример #24
0
		public override void HandleClient (TlsContext ctx, KeyExchange clientExchange)
		{
			// Read client premaster secret
			var encryptedPreMaster = ((RSAKeyExchange)clientExchange).encryptedPreMasterSecret;

			if (!ctx.Configuration.HasCredentials)
				throw new TlsException (AlertDescription.BadCertificate, "Server certificate Private Key unavailable.");

			// Decrypt premaster secret
			var deformatter = new RSAPKCS1KeyExchangeDeformatter (ctx.Configuration.PrivateKey);

			using (var preMasterSecret = new SecureBuffer (deformatter.DecryptKeyExchange (encryptedPreMaster))) {
				// Create master secret
				ComputeMasterSecret (ctx, preMasterSecret);
			}
		}
Пример #25
0
        /// <exception cref="IOException"></exception>
        public TlsNullCipher(TlsContext context, IDigest clientWriteDigest, IDigest serverWriteDigest)
        {
            if ((clientWriteDigest == null) != (serverWriteDigest == null))
                throw new TlsFatalAlert(AlertDescription.internal_error);

            this.context = context;

            TlsMac clientWriteMac = null, serverWriteMac = null;

            if (clientWriteDigest != null)
            {
                int key_block_size = clientWriteDigest.GetDigestSize()
                    + serverWriteDigest.GetDigestSize();
                byte[] key_block = TlsUtilities.CalculateKeyBlock(context, key_block_size);

                int offset = 0;

                clientWriteMac = new TlsMac(context, clientWriteDigest, key_block, offset,
                    clientWriteDigest.GetDigestSize());
                offset += clientWriteDigest.GetDigestSize();

                serverWriteMac = new TlsMac(context, serverWriteDigest, key_block, offset,
                    serverWriteDigest.GetDigestSize());
                offset += serverWriteDigest.GetDigestSize();

                if (offset != key_block_size)
                {
                    throw new TlsFatalAlert(AlertDescription.internal_error);
                }
            }

            if (context.IsServer)
            {
                writeMac = serverWriteMac;
                readMac = clientWriteMac;
            }
            else
            {
                writeMac = clientWriteMac;
                readMac = serverWriteMac;
            }
        }
        public DefaultTlsSignerCredentials(TlsContext context, Certificate certificate, AsymmetricKeyParameter privateKey,
            SignatureAndHashAlgorithm signatureAndHashAlgorithm)
        {
            if (certificate == null)
                throw new ArgumentNullException("certificate");
            if (certificate.IsEmpty)
                throw new ArgumentException("cannot be empty", "clientCertificate");
            if (privateKey == null)
                throw new ArgumentNullException("privateKey");
            if (!privateKey.IsPrivate)
                throw new ArgumentException("must be private", "privateKey");
            if (TlsUtilities.IsTlsV12(context) && signatureAndHashAlgorithm == null)
                throw new ArgumentException("cannot be null for (D)TLS 1.2+", "signatureAndHashAlgorithm");

            if (privateKey is RsaKeyParameters)
            {
                mSigner = new TlsRsaSigner();
            }
            else if (privateKey is DsaPrivateKeyParameters)
            {
                mSigner = new TlsDssSigner();
            }
            else if (privateKey is ECPrivateKeyParameters)
            {
                mSigner = new TlsECDsaSigner();
            }
            else
            {
                throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey");
            }

            this.mSigner.Init(context);

            this.mContext = context;
            this.mCertificate = certificate;
            this.mPrivateKey = privateKey;
            this.mSignatureAndHashAlgorithm = signatureAndHashAlgorithm;
        }
Пример #27
0
        /**
         * Parse a {@link CertificateUrl} from a {@link Stream}.
         * 
         * @param context
         *            the {@link TlsContext} of the current connection.
         * @param input
         *            the {@link Stream} to parse from.
         * @return a {@link CertificateUrl} object.
         * @throws IOException
         */
        public static CertificateUrl parse(TlsContext context, Stream input)
        {
            byte type = TlsUtilities.ReadUint8(input);
            if (!CertChainType.IsValid(type))
                throw new TlsFatalAlert(AlertDescription.decode_error);

            int totalLength = TlsUtilities.ReadUint16(input);
            if (totalLength < 1)
                throw new TlsFatalAlert(AlertDescription.decode_error);

            byte[] urlAndHashListData = TlsUtilities.ReadFully(totalLength, input);

            MemoryStream buf = new MemoryStream(urlAndHashListData, false);

            IList url_and_hash_list = Platform.CreateArrayList();
            while (buf.Position < buf.Length)
            {
                UrlAndHash url_and_hash = UrlAndHash.Parse(context, buf);
                url_and_hash_list.Add(url_and_hash);
            }

            return new CertificateUrl(type, url_and_hash_list);
        }
Пример #28
0
        /// <exception cref="IOException"></exception>
        public static byte[] GenerateEncryptedPreMasterSecret(TlsContext context, RsaKeyParameters rsaServerPublicKey,
            Stream output)
        {
            /*
             * Choose a PremasterSecret and send it encrypted to the server
             */
            byte[] premasterSecret = new byte[48];
            context.SecureRandom.NextBytes(premasterSecret);
            TlsUtilities.WriteVersion(context.ClientVersion, premasterSecret, 0);

            Pkcs1Encoding encoding = new Pkcs1Encoding(new RsaBlindedEngine());
            encoding.Init(true, new ParametersWithRandom(rsaServerPublicKey, context.SecureRandom));

            try
            {
                byte[] encryptedPreMasterSecret = encoding.ProcessBlock(premasterSecret, 0, premasterSecret.Length);

                if (TlsUtilities.IsSsl(context))
                {
                    // TODO Do any SSLv3 servers actually expect the length?
                    output.Write(encryptedPreMasterSecret, 0, encryptedPreMasterSecret.Length);
                }
                else
                {
                    TlsUtilities.WriteOpaque16(encryptedPreMasterSecret, output);
                }
            }
            catch (InvalidCipherTextException e)
            {
                /*
                 * This should never happen, only during decryption.
                 */
                throw new TlsFatalAlert(AlertDescription.internal_error, e);
            }

            return premasterSecret;
        }
Пример #29
0
		public override bool ProcessClient (TlsContext context)
		{
			if (context.IsServer)
				throw new InvalidOperationException ();

			if (!context.HandshakeParameters.RequestedSecureNegotiation)
				throw new TlsException (AlertDescription.HandshakeFailure);

			if (!context.Session.SecureRenegotiation) {
				// Initial handshake
				if (Data != null && Data.Size > 0)
					throw new TlsException (AlertDescription.HandshakeFailure);
				context.HandshakeParameters.SecureNegotiationSupported = true;
				return true;
			}

			var clientData = context.Session.ClientVerifyData;
			var serverData =  context.Session.ServerVerifyData;
			#if DEBUG_FULL
			if (context.EnableDebugging) {
				DebugHelper.WriteLine ("CHECKING CLIENT DATA", clientData);
				DebugHelper.WriteLine ("CHECKING SERVER DATA", serverData);
				DebugHelper.WriteLine ("CHECKING WHAT WE GOT", Data);
			}
			#endif
			var expectedLength = clientData.Size + serverData.Size;
			if (Data.Size != expectedLength)
				throw new TlsException (AlertDescription.DecodeError);

			if (!TlsBuffer.Compare (clientData.Buffer, 0, clientData.Size, Data.Buffer, 0, clientData.Size))
				throw new TlsException (AlertDescription.HandshakeFailure);
			if (!TlsBuffer.Compare (serverData.Buffer, 0, serverData.Size, Data.Buffer, clientData.Size, serverData.Size))
				throw new TlsException (AlertDescription.HandshakeFailure);

			context.HandshakeParameters.SecureNegotiationSupported = true;
			return true;
		}
        public DefaultTlsEncryptionCredentials(TlsContext context, Certificate certificate,
            AsymmetricKeyParameter privateKey)
        {
            if (certificate == null)
                throw new ArgumentNullException("certificate");
            if (certificate.IsEmpty)
                throw new ArgumentException("cannot be empty", "certificate");
            if (privateKey == null)
                throw new ArgumentNullException("'privateKey' cannot be null");
            if (!privateKey.IsPrivate)
                throw new ArgumentException("must be private", "privateKey");

            if (privateKey is RsaKeyParameters)
            {
            }
            else
            {
                throw new ArgumentException("type not supported: " + Platform.GetTypeName(privateKey), "privateKey");
            }

            this.mContext = context;
            this.mCertificate = certificate;
            this.mPrivateKey = privateKey;
        }
 protected virtual TlsBlockCipher CreateAESCipher(TlsContext context, int cipherKeySize, int macAlgorithm)
 {
     return(new TlsBlockCipher(context, CreateAesBlockCipher(), CreateAesBlockCipher(), CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm), cipherKeySize));
 }
Пример #32
0
        /// <exception cref="IOException"></exception>
        public override TlsCipher CreateCipher(TlsContext context, int encryptionAlgorithm, int macAlgorithm)
        {
            switch (encryptionAlgorithm)
            {
            case EncryptionAlgorithm.cls_3DES_EDE_CBC:
                return(CreateDesEdeCipher(context, macAlgorithm));

            case EncryptionAlgorithm.AEAD_CHACHA20_POLY1305:
                // NOTE: Ignores macAlgorithm
                return(CreateChaCha20Poly1305(context));

            case EncryptionAlgorithm.AES_128_CBC:
                return(CreateAESCipher(context, 16, macAlgorithm));

            case EncryptionAlgorithm.AES_128_CCM:
                // NOTE: Ignores macAlgorithm
                return(CreateCipher_Aes_Ccm(context, 16, 16));

            case EncryptionAlgorithm.AES_128_CCM_8:
                // NOTE: Ignores macAlgorithm
                return(CreateCipher_Aes_Ccm(context, 16, 8));

            case EncryptionAlgorithm.AES_256_CCM:
                // NOTE: Ignores macAlgorithm
                return(CreateCipher_Aes_Ccm(context, 32, 16));

            case EncryptionAlgorithm.AES_256_CCM_8:
                // NOTE: Ignores macAlgorithm
                return(CreateCipher_Aes_Ccm(context, 32, 8));

            case EncryptionAlgorithm.AES_128_GCM:
                // NOTE: Ignores macAlgorithm
                return(CreateCipher_Aes_Gcm(context, 16, 16));

            case EncryptionAlgorithm.AES_256_CBC:
                return(CreateAESCipher(context, 32, macAlgorithm));

            case EncryptionAlgorithm.AES_256_GCM:
                // NOTE: Ignores macAlgorithm
                return(CreateCipher_Aes_Gcm(context, 32, 16));

            case EncryptionAlgorithm.CAMELLIA_128_CBC:
                return(CreateCamelliaCipher(context, 16, macAlgorithm));

            case EncryptionAlgorithm.CAMELLIA_128_GCM:
                // NOTE: Ignores macAlgorithm
                return(CreateCipher_Camellia_Gcm(context, 16, 16));

            case EncryptionAlgorithm.CAMELLIA_256_CBC:
                return(CreateCamelliaCipher(context, 32, macAlgorithm));

            case EncryptionAlgorithm.CAMELLIA_256_GCM:
                // NOTE: Ignores macAlgorithm
                return(CreateCipher_Camellia_Gcm(context, 32, 16));

            case EncryptionAlgorithm.ESTREAM_SALSA20:
                return(CreateSalsa20Cipher(context, 12, 32, macAlgorithm));

            case EncryptionAlgorithm.NULL:
                return(CreateNullCipher(context, macAlgorithm));

            case EncryptionAlgorithm.RC4_128:
                return(CreateRC4Cipher(context, 16, macAlgorithm));

            case EncryptionAlgorithm.SALSA20:
                return(CreateSalsa20Cipher(context, 20, 32, macAlgorithm));

            case EncryptionAlgorithm.SEED_CBC:
                return(CreateSeedCipher(context, macAlgorithm));

            default:
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }
        }
 protected virtual TlsCipher CreateChaCha20Poly1305(TlsContext context)
 {
     return(new Chacha20Poly1305(context));
 }
 protected virtual TlsAeadCipher CreateCipher_Aes_Ccm(TlsContext context, int cipherKeySize, int macSize)
 {
     return(new TlsAeadCipher(context, this.CreateAeadBlockCipher_Aes_Ccm(), this.CreateAeadBlockCipher_Aes_Ccm(), cipherKeySize, macSize));
 }
 protected virtual TlsNullCipher CreateNullCipher(TlsContext context, int macAlgorithm)
 {
     return(new TlsNullCipher(context, this.CreateHMacDigest(macAlgorithm), this.CreateHMacDigest(macAlgorithm)));
 }
        public override TlsCipher CreateCipher(TlsContext context, int encryptionAlgorithm, int macAlgorithm)
        {
            switch (encryptionAlgorithm)
            {
            case 0:
                return(this.CreateNullCipher(context, macAlgorithm));

            case 1:
            case 3:
            case 4:
            case 5:
            case 6:
                break;

            case 2:
                return(this.CreateRC4Cipher(context, 16, macAlgorithm));

            case 7:
                return(this.CreateDesEdeCipher(context, macAlgorithm));

            case 8:
                return(this.CreateAESCipher(context, 16, macAlgorithm));

            case 9:
                return(this.CreateAESCipher(context, 32, macAlgorithm));

            case 10:
                return(this.CreateCipher_Aes_Gcm(context, 16, 16));

            case 11:
                return(this.CreateCipher_Aes_Gcm(context, 32, 16));

            case 12:
                return(this.CreateCamelliaCipher(context, 16, macAlgorithm));

            case 13:
                return(this.CreateCamelliaCipher(context, 32, macAlgorithm));

            case 14:
                return(this.CreateSeedCipher(context, macAlgorithm));

            case 15:
                return(this.CreateCipher_Aes_Ccm(context, 16, 16));

            case 16:
                return(this.CreateCipher_Aes_Ccm(context, 16, 8));

            case 17:
                return(this.CreateCipher_Aes_Ccm(context, 32, 16));

            case 18:
                return(this.CreateCipher_Aes_Ccm(context, 32, 8));

            case 19:
                return(this.CreateCipher_Camellia_Gcm(context, 16, 16));

            case 20:
                return(this.CreateCipher_Camellia_Gcm(context, 32, 16));

            default:
                switch (encryptionAlgorithm)
                {
                case 100:
                    return(this.CreateSalsa20Cipher(context, 12, 32, macAlgorithm));

                case 101:
                    return(this.CreateSalsa20Cipher(context, 20, 32, macAlgorithm));

                case 102:
                    return(this.CreateChaCha20Poly1305(context));
                }
                break;
            }
            throw new TlsFatalAlert(80);
        }
Пример #37
0
 public ClientKeyExchange(TlsContext context)
     : base(context, NegotiationState.ClientKeyExchange)
 {
 }
Пример #38
0
 public override TlsExtension ProcessServer(TlsContext context)
 {
     return(null);
 }
    public TlsBlockCipher(TlsContext context, IBlockCipher clientWriteCipher, IBlockCipher serverWriteCipher, IDigest clientWriteDigest, IDigest serverWriteDigest, int cipherKeySize)
    {
        this.context = context;
        randomData   = new byte[256];
        context.NonceRandomGenerator.NextBytes(randomData);
        useExplicitIV  = TlsUtilities.IsTlsV11(context);
        encryptThenMac = context.SecurityParameters.encryptThenMac;
        int num = 2 * cipherKeySize + clientWriteDigest.GetDigestSize() + serverWriteDigest.GetDigestSize();

        if (!useExplicitIV)
        {
            num += clientWriteCipher.GetBlockSize() + serverWriteCipher.GetBlockSize();
        }
        byte[] array  = TlsUtilities.CalculateKeyBlock(context, num);
        int    num2   = 0;
        TlsMac tlsMac = new TlsMac(context, clientWriteDigest, array, num2, clientWriteDigest.GetDigestSize());

        num2 += clientWriteDigest.GetDigestSize();
        TlsMac tlsMac2 = new TlsMac(context, serverWriteDigest, array, num2, serverWriteDigest.GetDigestSize());

        num2 += serverWriteDigest.GetDigestSize();
        KeyParameter parameters = new KeyParameter(array, num2, cipherKeySize);

        num2 += cipherKeySize;
        KeyParameter parameters2 = new KeyParameter(array, num2, cipherKeySize);

        num2 += cipherKeySize;
        byte[] iv;
        byte[] iv2;
        if (useExplicitIV)
        {
            iv  = new byte[clientWriteCipher.GetBlockSize()];
            iv2 = new byte[serverWriteCipher.GetBlockSize()];
        }
        else
        {
            iv    = Arrays.CopyOfRange(array, num2, num2 + clientWriteCipher.GetBlockSize());
            num2 += clientWriteCipher.GetBlockSize();
            iv2   = Arrays.CopyOfRange(array, num2, num2 + serverWriteCipher.GetBlockSize());
            num2 += serverWriteCipher.GetBlockSize();
        }
        if (num2 != num)
        {
            throw new TlsFatalAlert(80);
        }
        ICipherParameters parameters3;
        ICipherParameters parameters4;

        if (context.IsServer)
        {
            mWriteMac     = tlsMac2;
            mReadMac      = tlsMac;
            encryptCipher = serverWriteCipher;
            decryptCipher = clientWriteCipher;
            parameters3   = new ParametersWithIV(parameters2, iv2);
            parameters4   = new ParametersWithIV(parameters, iv);
        }
        else
        {
            mWriteMac     = tlsMac;
            mReadMac      = tlsMac2;
            encryptCipher = clientWriteCipher;
            decryptCipher = serverWriteCipher;
            parameters3   = new ParametersWithIV(parameters, iv);
            parameters4   = new ParametersWithIV(parameters2, iv2);
        }
        encryptCipher.Init(forEncryption: true, parameters3);
        decryptCipher.Init(forEncryption: false, parameters4);
    }
Пример #40
0
 internal HueTlsAuthentication(TlsContext context)
 {
     _context = context;
 }
 protected virtual TlsBlockCipher CreateSeedCipher(TlsContext context, int macAlgorithm)
 {
     return(new TlsBlockCipher(context, this.CreateSeedBlockCipher(), this.CreateSeedBlockCipher(), this.CreateHMacDigest(macAlgorithm), this.CreateHMacDigest(macAlgorithm), 16));
 }
Пример #42
0
 public static TlsSignerCredentials LoadSignerCredentials(TlsContext context,
                                                          Certificate certificate, AsymmetricKeyParameter privateKey)
 {
     return(new DefaultTlsSignerCredentials(context, certificate, privateKey));
 }
 public virtual void Init(TlsContext context)
 {
     this.mContext = context;
 }
        /// <exception cref="IOException"></exception>
        public TlsAeadCipher(TlsContext context, IAeadBlockCipher clientWriteCipher, IAeadBlockCipher serverWriteCipher,
                             int cipherKeySize, int macSize)
        {
            if (!TlsUtilities.IsTlsV12(context))
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            this.context = context;
            this.macSize = macSize;

            // NOTE: Valid for RFC 5288/6655 ciphers but may need review for other AEAD ciphers
            this.nonce_explicit_length = 8;

            // TODO SecurityParameters.fixed_iv_length
            int fixed_iv_length = 4;

            int key_block_size = (2 * cipherKeySize) + (2 * fixed_iv_length);

            byte[] key_block = TlsUtilities.CalculateKeyBlock(context, key_block_size);

            int offset = 0;

            KeyParameter client_write_key = new KeyParameter(key_block, offset, cipherKeySize);

            offset += cipherKeySize;
            KeyParameter server_write_key = new KeyParameter(key_block, offset, cipherKeySize);

            offset += cipherKeySize;
            byte[] client_write_IV = Arrays.CopyOfRange(key_block, offset, offset + fixed_iv_length);
            offset += fixed_iv_length;
            byte[] server_write_IV = Arrays.CopyOfRange(key_block, offset, offset + fixed_iv_length);
            offset += fixed_iv_length;

            if (offset != key_block_size)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            KeyParameter encryptKey, decryptKey;

            if (context.IsServer)
            {
                this.encryptCipher        = serverWriteCipher;
                this.decryptCipher        = clientWriteCipher;
                this.encryptImplicitNonce = server_write_IV;
                this.decryptImplicitNonce = client_write_IV;
                encryptKey = server_write_key;
                decryptKey = client_write_key;
            }
            else
            {
                this.encryptCipher        = clientWriteCipher;
                this.decryptCipher        = serverWriteCipher;
                this.encryptImplicitNonce = client_write_IV;
                this.decryptImplicitNonce = server_write_IV;
                encryptKey = client_write_key;
                decryptKey = server_write_key;
            }

            byte[] dummyNonce = new byte[fixed_iv_length + nonce_explicit_length];

            this.encryptCipher.Init(true, new AeadParameters(encryptKey, 8 * macSize, dummyNonce));
            this.decryptCipher.Init(false, new AeadParameters(decryptKey, 8 * macSize, dummyNonce));
        }
 /// <exception cref="IOException"></exception>
 public virtual TlsCipher CreateCipher(TlsContext context, int encryptionAlgorithm, int macAlgorithm)
 {
     throw new TlsFatalAlert(AlertDescription.internal_error);
 }
Пример #46
0
 public TlsClientKeyExchange(TlsContext context, TlsBuffer incoming)
     : base(HandshakeType.ClientKeyExchange)
 {
     KeyExchange = KeyExchange.Create(context.NegotiatedProtocol, context.Session.PendingCrypto.Cipher.ExchangeAlgorithmType);
     Read(incoming);
 }
 protected virtual TlsBlockCipher CreateCamelliaCipher(TlsContext context, int cipherKeySize, int macAlgorithm)
 {
     return(new TlsBlockCipher(context, this.CreateCamelliaBlockCipher(), this.CreateCamelliaBlockCipher(), this.CreateHMacDigest(macAlgorithm), this.CreateHMacDigest(macAlgorithm), cipherKeySize));
 }
Пример #48
0
        /// <exception cref="IOException"></exception>
        public TlsStreamCipher(TlsContext context, IStreamCipher clientWriteCipher,
                               IStreamCipher serverWriteCipher, IDigest clientWriteDigest, IDigest serverWriteDigest,
                               int cipherKeySize, bool usesNonce)
        {
            bool isServer = context.IsServer;

            this.context   = context;
            this.usesNonce = usesNonce;

            this.encryptCipher = clientWriteCipher;
            this.decryptCipher = serverWriteCipher;

            int key_block_size = (2 * cipherKeySize) + clientWriteDigest.GetDigestSize()
                                 + serverWriteDigest.GetDigestSize();

            byte[] key_block = TlsUtilities.CalculateKeyBlock(context, key_block_size);

            int offset = 0;

            // Init MACs
            TlsMac clientWriteMac = new TlsMac(context, clientWriteDigest, key_block, offset,
                                               clientWriteDigest.GetDigestSize());

            offset += clientWriteDigest.GetDigestSize();
            TlsMac serverWriteMac = new TlsMac(context, serverWriteDigest, key_block, offset,
                                               serverWriteDigest.GetDigestSize());

            offset += serverWriteDigest.GetDigestSize();

            // Build keys
            KeyParameter clientWriteKey = new KeyParameter(key_block, offset, cipherKeySize);

            offset += cipherKeySize;
            KeyParameter serverWriteKey = new KeyParameter(key_block, offset, cipherKeySize);

            offset += cipherKeySize;

            if (offset != key_block_size)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            ICipherParameters encryptParams, decryptParams;

            if (isServer)
            {
                this.writeMac      = serverWriteMac;
                this.readMac       = clientWriteMac;
                this.encryptCipher = serverWriteCipher;
                this.decryptCipher = clientWriteCipher;
                encryptParams      = serverWriteKey;
                decryptParams      = clientWriteKey;
            }
            else
            {
                this.writeMac      = clientWriteMac;
                this.readMac       = serverWriteMac;
                this.encryptCipher = clientWriteCipher;
                this.decryptCipher = serverWriteCipher;
                encryptParams      = clientWriteKey;
                decryptParams      = serverWriteKey;
            }

            if (usesNonce)
            {
                byte[] dummyNonce = new byte[8];
                encryptParams = new ParametersWithIV(encryptParams, dummyNonce);
                decryptParams = new ParametersWithIV(decryptParams, dummyNonce);
            }

            this.encryptCipher.Init(true, encryptParams);
            this.decryptCipher.Init(false, decryptParams);
        }
 public DefaultTlsSignerCredentials(TlsContext context, Certificate certificate, AsymmetricKeyParameter privateKey) : this(context, certificate, privateKey, null)
 {
 }
 protected virtual TlsStreamCipher CreateRC4Cipher(TlsContext context, int cipherKeySize, int macAlgorithm)
 {
     return(new TlsStreamCipher(context, this.CreateRC4StreamCipher(), this.CreateRC4StreamCipher(), this.CreateHMacDigest(macAlgorithm), this.CreateHMacDigest(macAlgorithm), cipherKeySize, false));
 }
 protected virtual TlsBlockCipher CreateDesEdeCipher(TlsContext context, int macAlgorithm)
 {
     return(new TlsBlockCipher(context, CreateDesEdeBlockCipher(), CreateDesEdeBlockCipher(), CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm), 24));
 }
Пример #52
0
 internal MyTlsAuthentication(TlsTestClientImpl outer, TlsContext context)
 {
     this.mOuter   = outer;
     this.mContext = context;
 }
 protected virtual TlsAeadCipher CreateCipher_Camellia_Gcm(TlsContext context, int cipherKeySize, int macSize)
 {
     return(new TlsAeadCipher(context, CreateAeadBlockCipher_Camellia_Gcm(), CreateAeadBlockCipher_Camellia_Gcm(), cipherKeySize, macSize));
 }
 protected virtual TlsStreamCipher CreateSalsa20Cipher(TlsContext context, int rounds, int cipherKeySize, int macAlgorithm)
 {
     return(new TlsStreamCipher(context, this.CreateSalsa20StreamCipher(rounds), this.CreateSalsa20StreamCipher(rounds), this.CreateHMacDigest(macAlgorithm), this.CreateHMacDigest(macAlgorithm), cipherKeySize, true));
 }
Пример #55
0
 public override bool ProcessClient(TlsContext context)
 {
     return(false);
 }
Пример #56
0
 public virtual TlsCredentials GetClientCredentials(TlsContext context, CertificateRequest certificateRequest)
 {
     return(credProvider == null ? null : credProvider.GetClientCredentials(context, certificateRequest));
 }
Пример #57
0
        public static byte[] SafeDecryptPreMasterSecret(TlsContext context, RsaKeyParameters rsaServerPrivateKey,
                                                        byte[] encryptedPreMasterSecret)
        {
            /*
             * RFC 5246 7.4.7.1.
             */
            ProtocolVersion clientVersion = context.ClientVersion;

            // TODO Provide as configuration option?
            bool versionNumberCheckDisabled = false;

            /*
             * Generate 48 random bytes we can use as a Pre-Master-Secret, if the
             * PKCS1 padding check should fail.
             */
            byte[] fallback = new byte[48];
            context.SecureRandom.NextBytes(fallback);

            byte[] M = Arrays.Clone(fallback);
            try
            {
                Pkcs1Encoding encoding = new Pkcs1Encoding(new RsaBlindedEngine(), fallback);
                encoding.Init(false,
                              new ParametersWithRandom(rsaServerPrivateKey, context.SecureRandom));

                M = encoding.ProcessBlock(encryptedPreMasterSecret, 0, encryptedPreMasterSecret.Length);
            }
            catch (Exception)
            {
                /*
                 * This should never happen since the decryption should never throw an exception
                 * and return a random value instead.
                 *
                 * In any case, a TLS server MUST NOT generate an alert if processing an
                 * RSA-encrypted premaster secret message fails, or the version number is not as
                 * expected. Instead, it MUST continue the handshake with a randomly generated
                 * premaster secret.
                 */
            }

            /*
             * If ClientHello.client_version is TLS 1.1 or higher, server implementations MUST
             * check the version number [..].
             */
            if (versionNumberCheckDisabled && clientVersion.IsEqualOrEarlierVersionOf(ProtocolVersion.TLSv10))
            {
                /*
                 * If the version number is TLS 1.0 or earlier, server
                 * implementations SHOULD check the version number, but MAY have a
                 * configuration option to disable the check.
                 *
                 * So there is nothing to do here.
                 */
            }
            else
            {
                /*
                 * OK, we need to compare the version number in the decrypted Pre-Master-Secret with the
                 * clientVersion received during the handshake. If they don't match, we replace the
                 * decrypted Pre-Master-Secret with a random one.
                 */
                int correct = (clientVersion.MajorVersion ^ (M[0] & 0xff))
                              | (clientVersion.MinorVersion ^ (M[1] & 0xff));
                correct |= correct >> 1;
                correct |= correct >> 2;
                correct |= correct >> 4;
                int mask = ~((correct & 1) - 1);

                /*
                 * mask will be all bits set to 0xff if the version number differed.
                 */
                for (int i = 0; i < 48; i++)
                {
                    M[i] = (byte)((M[i] & (~mask)) | (fallback[i] & mask));
                }
            }
            return(M);
        }
Пример #58
0
 internal MyTlsAuthentication(TlsContext context)
 {
     this._mContext = context;
 }
Пример #59
0
 public TlsNullCipher(TlsContext context)
 {
     this.context  = context;
     this.writeMac = null;
     this.readMac  = null;
 }
Пример #60
0
        protected internal static int GetPrfAlgorithm(TlsContext context, int ciphersuite)
        {
            bool isTLSv12 = TlsUtilities.IsTlsV12(context);

            switch (ciphersuite)
            {
            case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256:
            case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256:
            case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256:
            case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256:
            case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256:
            case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256:
            case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256:
            case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256:
            case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256:
            case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256:
            case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256:
            case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256:
            case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
            case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
            case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256:
            case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
            case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
            case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
            case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256:
            case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256:
            case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256:
            case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM:
            case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256:
            case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM:
            case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256:
            case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
            case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM:
            case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8:
            case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
            case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
            case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM:
            case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8:
            case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
            case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
            case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
            case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
            case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
            case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
            case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
            case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
            case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
            case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
            case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
            case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
            case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
            case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
            case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
            case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
            case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM:
            case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
            case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
            case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
            case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
            case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
            case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
            case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
            case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
            case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
            case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8:
            case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8:
            case CipherSuite.TLS_PSK_WITH_AES_128_CCM:
            case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8:
            case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256:
            case CipherSuite.TLS_PSK_WITH_AES_256_CCM:
            case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8:
            case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256:
            case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256:
            case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256:
            case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256:
            case CipherSuite.TLS_RSA_WITH_AES_128_CCM:
            case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8:
            case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256:
            case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256:
            case CipherSuite.TLS_RSA_WITH_AES_256_CCM:
            case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8:
            case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
            case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256:
            case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
            case CipherSuite.TLS_RSA_WITH_NULL_SHA256:
            {
                if (isTLSv12)
                {
                    return(PrfAlgorithm.tls_prf_sha256);
                }
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384:
            case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384:
            case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384:
            case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384:
            case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
            case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
            case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384:
            case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384:
            case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384:
            case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
            case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
            case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
            case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
            case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
            case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
            case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
            case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
            case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384:
            case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
            case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
            case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
            case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
            case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
            case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
            case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
            case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384:
            case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
            case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384:
            case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384:
            case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384:
            case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384:
            case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384:
            case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384:
            {
                if (isTLSv12)
                {
                    return(PrfAlgorithm.tls_prf_sha384);
                }
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384:
            case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
            case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384:
            case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384:
            case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
            case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384:
            case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384:
            case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384:
            case CipherSuite.TLS_PSK_WITH_NULL_SHA384:
            case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384:
            case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384:
            case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384:
            {
                if (isTLSv12)
                {
                    return(PrfAlgorithm.tls_prf_sha384);
                }
                return(PrfAlgorithm.tls_prf_legacy);
            }

            default:
            {
                if (isTLSv12)
                {
                    return(PrfAlgorithm.tls_prf_sha256);
                }
                return(PrfAlgorithm.tls_prf_legacy);
            }
            }
        }