Example #1
0
		public void TestCase()
		{
			OpenSSL.Core.Random.Seed(rnd_seed);

			BigNumber.GeneratorHandler cb = new BigNumber.GeneratorHandler(this.OnStatus);
			DH a = new DH(64, DH.Generator5, cb, Console.Out);

			DH.CheckCode check = a.Check();
			if ((check & DH.CheckCode.CheckP_NotPrime) != 0)
				Console.WriteLine("p value is not prime");
			if ((check & DH.CheckCode.CheckP_NotSafePrime) != 0)
				Console.WriteLine("p value is not safe prime");
			if ((check & DH.CheckCode.UnableToCheckGenerator) != 0)
				Console.WriteLine("unable to check the generator value");
			if ((check & DH.CheckCode.NotSuitableGenerator) != 0)
				Console.WriteLine("the g value is not a generator");

			Console.WriteLine();
			Console.WriteLine("p    ={0}", a.P);
			Console.WriteLine("g    ={0}", a.G);

			DH b = new DH(a.P, a.G);

			a.NoExpConstantTime = false;
			b.NoExpConstantTime = true;

			a.GenerateKeys();
			Console.WriteLine("pri 1={0}", a.PrivateKey);
			Console.WriteLine("pub 1={0}", a.PublicKey);

			b.GenerateKeys();
			Console.WriteLine("pri 2={0}", b.PrivateKey);
			Console.WriteLine("pub 2={0}", b.PublicKey);

			byte[] aout = a.ComputeKey(b.PublicKey);
			string astr = BitConverter.ToString(aout);
			Console.WriteLine("key1 ={0}", astr);

			byte[] bout = b.ComputeKey(a.PublicKey);
			string bstr = BitConverter.ToString(bout);
			Console.WriteLine("key2 ={0}", bstr);

			if (aout.Length < 4 || astr != bstr)
				throw new Exception("Error in DH routines");

			a.Dispose();
			b.Dispose();
		}
        public SslAnonStreamServer(
            Stream stream, 
            bool ownStream,
            DH dh,
            SslProtocols enabledSslProtocols,
            SslStrength sslStrength)
            : base(stream, ownStream)
        {
            // Initialize the SslContext object
            InitializeServerContext(dh, enabledSslProtocols, sslStrength);

            // Initalize the Ssl object
            ssl = new Ssl(sslContext);
            // Initialze the read/write bio
            read_bio = BIO.MemoryBuffer(false);
            write_bio = BIO.MemoryBuffer(false);
            // Set the read/write bio's into the the Ssl object
            ssl.SetBIO(read_bio, write_bio);
            read_bio.SetClose(BIO.CloseOption.Close);
            write_bio.SetClose(BIO.CloseOption.Close);
            // Set the Ssl object into server mode
            ssl.SetAcceptState();
        }
Example #3
0
		public void CanCreateFromDH()
		{
			using (DH dh = new DH())
			{
				dh.GenerateKeys();
				using (CryptoKey key = new CryptoKey(dh)) {
					Assert.AreEqual(CryptoKey.KeyType.DH, key.Type);
				}
			}
		}
Example #4
0
        private void ProcessTCPPacket(TCPPacket pTCPPacket, ref uint pSequence, SortedDictionary<uint, byte[]> pBuffer, RiftStream pStream)
        {
            if (pTCPPacket.SequenceNumber > pSequence) pBuffer[(uint)pTCPPacket.SequenceNumber] = pTCPPacket.TCPData;
            if (pTCPPacket.SequenceNumber < pSequence)
            {
                int difference = (int)(pSequence - pTCPPacket.SequenceNumber);
                byte[] data = pTCPPacket.TCPData;
                if (data.Length > difference)
                {
                    pStream.Append(data, difference, data.Length - difference);
                    pSequence += (uint)(data.Length - difference);
                }
            }
            else if (pTCPPacket.SequenceNumber == pSequence)
            {
                byte[] data = pTCPPacket.TCPData;
                pStream.Append(data);
                pSequence += (uint)data.Length;

                bool found;
                do
                {
                    SortedDictionary<uint, byte[]>.Enumerator enumerator = pBuffer.GetEnumerator();
                    if ((found = (enumerator.MoveNext() && enumerator.Current.Key <= pSequence)))
                    {
                        int difference = (int)(pSequence - enumerator.Current.Key);
                        if (enumerator.Current.Value.Length > difference)
                        {
                            pStream.Append(enumerator.Current.Value, difference, enumerator.Current.Value.Length - difference);
                            pSequence += (uint)(enumerator.Current.Value.Length - difference);
                        }
                        pBuffer.Remove(enumerator.Current.Key);
                    }
                }
                while (found);
            }

            RiftPacket packet;
            while ((packet = pStream.Read(pTCPPacket.Timeval.Date)) != null)
            {
                AddPacket(packet);
                if (packet.Opcode == 0x01B7)
                {
                    mIsCharacterSession = true;
                }
                else if (packet.Opcode == 0x040B)
                {
                    RiftPacketField fieldServerPublicKey;
                    if (packet.GetFieldByIndex(out fieldServerPublicKey, 1) &&
                        fieldServerPublicKey.Type == ERiftPacketFieldType.ByteArray &&
                        fieldServerPublicKey.Value.Bytes.Length == 128)
                    {
                        if (mClientPrivateKeys == null)
                        {
                            DateTime started = DateTime.Now;
                            while (!Program.LiveKeys.ContainsKey(mIsCharacterSession) && DateTime.Now.Subtract(started).TotalSeconds < 10) Thread.Sleep(1);
                            if (Program.LiveKeys.ContainsKey(mIsCharacterSession)) mClientPrivateKeys = Program.LiveKeys;
                            else
                            {
                                MessageBox.Show(this, "The required key was unable to be found for some reason, let the developers know this happened.", "Key Grab Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                mTerminated = true;
                                return;
                            }
                        }
                        mClientPrivateKey = BigNumber.FromArray(mClientPrivateKeys[mIsCharacterSession]);
                        mServerPublicKey = BigNumber.FromArray(fieldServerPublicKey.Value.Bytes);
                        DH dh = new DH(mModulus, mGenerator, BigNumber.One, mClientPrivateKey);
                        mSharedSecretKey = dh.ComputeKey(mServerPublicKey);
                    }
                }
                else if (packet.Opcode == 0x19)
                {
                    pStream.EnableInflater();
                    if (packet.Outbound)
                    {
                        mInboundStream.EnableEncryption(mSharedSecretKey);
                        mOutboundStream.EnableEncryption(mSharedSecretKey);
                    }
                }
            }
        }
		public void CanCompareDH()
		{
			using (var dh = new DH())
			{
				dh.GenerateKeys();

				using (var lhs = new CryptoKey(dh))
				{
					Assert.AreEqual(lhs, lhs);
					using (var rhs = new CryptoKey(dh))
					{
						Assert.AreEqual(lhs, rhs);
					}

					using (var dh2 = new DH(1, 5))
					{
						dh2.GenerateKeys();
						using (var other = new CryptoKey(dh2))
						{
							Assert.AreNotEqual(lhs, other);
						}
					}
				}
			}
		}
		public void CanCreateFromDH()
		{
			using (var dh = new DH())
			{
				dh.GenerateKeys();

				using (var key = new CryptoKey(dh))
				{
					Assert.AreEqual(CryptoKey.KeyType.DH, key.Type);
					Assert.AreEqual(dh.Handle, key.GetDH().Handle);
				}

				using (var key = new CryptoKey())
				{
					key.Assign(dh);
					Assert.AreEqual(dh.Handle, key.GetDH().Handle);
				}
			}
		}
Example #7
0
		public void Execute(string[] args)
		{
			try
			{
				options.ParseArguments(args);
			}
			catch (Exception)
			{
				Usage();
				return;
			}

			int g = DH.Generator2;
			if (this.options.IsSet("2"))
				g = DH.Generator2;

			if (this.options.IsSet("5"))
				g = DH.Generator5;

			int bits = 512;
			if (this.options.Arguments.Count == 1)
				bits = Convert.ToInt32(this.options.Arguments[0]);

			Console.Error.WriteLine("Generating DH parameters, {0} bit long safe prime, generator {1}", bits, g);
			Console.Error.WriteLine("This is going to take a long time");

			DH dh = new DH(bits, g, Program.OnGenerator, null);

			string outfile = this.options["out"] as string;
			if (string.IsNullOrEmpty(outfile))
			{
				Console.WriteLine(dh.PEM);
			}
			else
			{
				File.WriteAllText(outfile, dh.PEM);
			}
		}
Example #8
0
		/// <summary>
		/// Calls EVP_PKEY_assign()
		/// </summary>
		/// <param name="key">Key.</param>
		public void Assign(DH key)
		{
			key.AddRef();
			Native.ExpectSuccess(Native.EVP_PKEY_assign(ptr, (int)KeyType.DH, key.Handle));
		}
Example #9
0
 /// <summary>
 /// Calls EVP_PKEY_set1_DH()
 /// </summary>
 /// <param name="dh"></param>
 public CryptoKey(DH dh)
     : this()
 {
     Native.ExpectSuccess(Native.EVP_PKEY_set1_DH(this.ptr, dh.Handle));
 }
Example #10
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dh"></param>
        /// <param name="asyncCallback"></param>
        /// <param name="asyncState"></param>
        /// <returns></returns>
        public virtual IAsyncResult BeginAuthenticateAsServer(
            DH dh,
			AsyncCallback asyncCallback,
			Object asyncState)
        {
            return BeginAuthenticateAsServer(dh, SslProtocols.Default, SslStrength.Medium, asyncCallback, asyncState);
        }
Example #11
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dh"></param>
        /// <param name="enabledSslProtocols"></param>
        /// <param name="sslStrength"></param>
        /// <param name="asyncCallback"></param>
        /// <param name="asyncState"></param>
        /// <returns></returns>
        public virtual IAsyncResult BeginAuthenticateAsServer(
            DH dh,
			SslProtocols enabledSslProtocols,
			SslStrength sslStrength,
			AsyncCallback asyncCallback,
			Object asyncState)
        {
            if (IsAuthenticated)
            {
                throw new InvalidOperationException("SslStream is already authenticated");
            }
            // Initialize the server stream
            SslAnonStreamServer server_stream = new SslAnonStreamServer(InnerStream, false, dh, enabledSslProtocols, sslStrength);
            // Set the internal sslStream
            sslStream = server_stream;
            // Start the read operation
            return BeginRead(new byte[0], 0, 0, asyncCallback, asyncState);
        }
Example #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dh"></param>
        /// <param name="enabledSslProtocols"></param>
        /// <param name="sslStrength"></param>
        public virtual void AuthenticateAsServer(
            DH dh,
			SslProtocols enabledSslProtocols,
			SslStrength sslStrength)
        {
            EndAuthenticateAsServer(BeginAuthenticateAsServer(dh, enabledSslProtocols, sslStrength, null, null));
        }
Example #13
0
		/// <summary>
		/// Factory method that calls XXX() to deserialize
		/// a DH object from a DER-formatted buffer using the BIO interface.
		/// </summary>
		/// <param name="bio"></param>
		/// <returns></returns>
		public static DH FromParametersDER(BIO bio)
		{
			var dh_new = new DH_new_delegate(Managed_DH_new);
			var d2i_DHparams = new d2i_DHparams_delegate(Managed_d2i_DHparams);
			var dh_new_ptr = Marshal.GetFunctionPointerForDelegate(dh_new);
			var d2i_DHparams_ptr = Marshal.GetFunctionPointerForDelegate(d2i_DHparams);
			var ptr = Native.ExpectNonNull(Native.ASN1_d2i_bio(dh_new_ptr, d2i_DHparams_ptr, bio.Handle, IntPtr.Zero));
			var dh = new DH(ptr, true);
			
			return dh;
		}
Example #14
0
 /// <summary>
 /// Calls EVP_PKEY_assign()
 /// </summary>
 /// <param name="key">Key.</param>
 public void Assign(DH key)
 {
     key.AddRef();
     Native.ExpectSuccess(Native.EVP_PKEY_assign(ptr, (int)KeyType.DH, key.Handle));
 }
Example #15
0
        private void ProcessTCPPacket(TCPPacket pTCPPacket, ref uint pSequence, SortedDictionary<uint, byte[]> pBuffer, RiftStream pStream)
        {
            if (pTCPPacket.SequenceNumber > pSequence) pBuffer[(uint)pTCPPacket.SequenceNumber] = pTCPPacket.TCPData;
            if (pTCPPacket.SequenceNumber < pSequence)
            {
                int difference = (int)(pSequence - pTCPPacket.SequenceNumber);
                byte[] data = pTCPPacket.TCPData;
                if (data.Length > difference)
                {
                    pStream.Append(data, difference, data.Length - difference);
                    pSequence += (uint)(data.Length - difference);
                }
            }
            else if (pTCPPacket.SequenceNumber == pSequence)
            {
                byte[] data = pTCPPacket.TCPData;
                pStream.Append(data);
                pSequence += (uint)data.Length;

                bool found;
                do
                {
                    SortedDictionary<uint, byte[]>.Enumerator enumerator = pBuffer.GetEnumerator();
                    if ((found = (enumerator.MoveNext() && enumerator.Current.Key <= pSequence)))
                    {
                        int difference = (int)(pSequence - enumerator.Current.Key);
                        if (enumerator.Current.Value.Length > difference)
                        {
                            pStream.Append(enumerator.Current.Value, difference, enumerator.Current.Value.Length - difference);
                            pSequence += (uint)(enumerator.Current.Value.Length - difference);
                        }
                        pBuffer.Remove(enumerator.Current.Key);
                    }
                }
                while (found);
            }

            RiftPacket packet;
            while ((packet = pStream.Read(pTCPPacket.Timeval.Date)) != null)
            {
                AddPacket(packet);
                if (packet.Opcode == 0x01B7) mIsCharacterSession = true;
                else if (packet.Opcode == 0x040B)
                {
                    RiftPacketField fieldServerPublicKey;
                    if (packet.GetFieldByIndex(out fieldServerPublicKey, 1) &&
                        fieldServerPublicKey.Type == ERiftPacketFieldType.ByteArray &&
                        fieldServerPublicKey.Value.Bytes.Length == 128)
                    {
                        if (mClientPrivateKeys != null && mClientPrivateKeys.ContainsKey(mIsCharacterSession)) mClientPrivateKey = BigNumber.FromArray(mClientPrivateKeys[mIsCharacterSession]);
                        if (mClientPrivateKey == null)
                        {
                            // Scan for rift.exe, read memory to pointers, get client private key
                        }
                        mServerPublicKey = BigNumber.FromArray(fieldServerPublicKey.Value.Bytes);
                        DH dh = new DH(mModulus, mGenerator, BigNumber.One, mClientPrivateKey);
                        mSharedSecretKey = dh.ComputeKey(mServerPublicKey);
                    }
                }
                else if (packet.Opcode == 0x19)
                {
                    pStream.EnableInflater();
                    if (packet.Outbound)
                    {
                        mInboundStream.EnableEncryption(mSharedSecretKey);
                        mOutboundStream.EnableEncryption(mSharedSecretKey);
                    }
                }
            }
        }
        private void InitializeServerContext(
            DH dh,
            SslProtocols enabledSslProtocols,
            SslStrength sslStrength)
        {
            // Initialize the context
            sslContext = new SslContext(SslMethod.SSLv23_server_method);

            // Remove support for protocols not specified in the enabledSslProtocols
            if ((enabledSslProtocols & SslProtocols.Ssl2) != SslProtocols.Ssl2)
            {
                sslContext.Options |= SslOptions.SSL_OP_NO_SSLv2;
            }
            if ((enabledSslProtocols & SslProtocols.Ssl3) != SslProtocols.Ssl3 &&
                ((enabledSslProtocols & SslProtocols.Default) != SslProtocols.Default))
            {
                // no SSLv3 support
                sslContext.Options |= SslOptions.SSL_OP_NO_SSLv3;
            }
            if ((enabledSslProtocols & SslProtocols.Tls) != SslProtocols.Tls &&
                (enabledSslProtocols & SslProtocols.Default) != SslProtocols.Default)
            {
                sslContext.Options |= SslOptions.SSL_OP_NO_TLSv1;
            }

            // Set the context mode
            sslContext.Mode = SslMode.SSL_MODE_AUTO_RETRY;

            sslContext.SetVerify(VerifyMode.SSL_VERIFY_NONE, null);

            // Set the cipher string
            sslContext.SetCipherList("ADH");

            sslContext.SetTmpDhCallback(dh);
        }
Example #17
0
 public void SetTmpDhCallback(DH dh)
 {
     DHCallBack_delegate = new Native.DHCallBack(() => { return dh.Handle; });
     Native.SSL_CTX_set_tmp_dh_callback(this.ptr, DHCallBack_delegate);
 }
Example #18
0
		/// <summary>
		/// Calls EVP_PKEY_set1_DH()
		/// </summary>
		/// <param name="dh"></param>
		public CryptoKey(DH dh)
			: this()
		{
			Native.ExpectSuccess(Native.EVP_PKEY_set1_DH(ptr, dh.Handle));
		}