Example #1
0
        public SslStreamServer(
            Stream stream, 
            bool ownStream,
            X509Certificate serverCertificate,
            bool clientCertificateRequired,
            X509Chain caCerts,
            SslProtocols enabledSslProtocols,
            SslStrength sslStrength,
            bool checkCertificateRevocation,
            RemoteCertificateValidationHandler remote_callback)
            : base(stream, ownStream)
        {
            this.checkCertificateRevocationStatus = checkCertificateRevocation;
            this.remoteCertificateSelectionCallback = remote_callback;

            // Initialize the SslContext object
            InitializeServerContext(serverCertificate, clientCertificateRequired, caCerts, enabledSslProtocols, sslStrength, checkCertificateRevocation);
            
            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 #2
0
    /// <summary>Create a DtlsFilter.</summary>
    /// <param name="key">A CryptoKey initialized by the OpenSSL.NET library.</param>
    /// <param name="cert">The path to the certificate to use.</param>
    /// <param name="ca_cert">The path to the ca certificate to use.</param>
    /// <param name="client">Use client initialization parameters.</param>
    public DtlsAssociation(ISender sender, CertificateHandler ch, PType ptype,
        Ssl ssl, bool client) : base(sender, ch)
    {
      _ip = new IdentifierPair();
      PType = ptype;
      _ssl = ssl;
      _client = client;
      _ssl.SetReadAhead(1);
      // Buggy SSL versions have issue with compression and dtls
      _ssl.SetOptions((int) SslOptions.SSL_OP_NO_COMPRESSION);
      if(client) {
        _ssl.SetConnectState();
      } else {
        _ssl.SetAcceptState();
      }

      // The ssl object will take control
      _read = BIO.MemoryBuffer(false);
      _read.NonBlocking = true;
      _write = BIO.MemoryBuffer(false);
      _write.NonBlocking = true;

      _ssl.SetBIO(_read, _write);
      _ssl.DoHandshake();

      _buffer = new byte[Int16.MaxValue];
      _buffer_sync = new object();
      _fe_lock = 0;
    }
Example #3
0
        public SslStreamServer(
            Stream stream,
            bool ownStream,
            string pskCiphers,
            byte[] pskPsk)
            : base(stream, ownStream)
        {
            this.pskCiphers = pskCiphers;
            this.pskPsk = pskPsk;

            this.internalPskServerCallback = new PskServerCallbackHandler(InternalPskServerCallback);

            // Initialize the SslContext object
            InitializeServerContextUsingPsk(this.pskCiphers);

            // 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();
        }
        private static string ProtocolString(Ssl? sslValue)
        {
            if (!sslValue.HasValue)
                return null;

            return (sslValue == Ssl.Add) ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
        }
        public void ControllerSetForProtocol_ControllerInParameters_ProtocolIsRendered(Ssl option)
        {
            _routeOptions.SetOptionByController(option, "mycontroller");
            _routeCollection.MapRoute("etcroutes", "etc/{controller}/{action}");
            var actual = SslHelpers.UrlHelpers.SslRouteUrl(_urlHelper, "etcroutes", new { controller = "mycontroller", action ="someaction" });

            AssertUriPathMatchesOption(option, actual);
        }
Example #6
0
 private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result)
 {
     Ssl.SslErrorCode retVal = Ssl.SslGetError(context, result);
     if (retVal == Ssl.SslErrorCode.SSL_ERROR_SYSCALL)
     {
         retVal = (Ssl.SslErrorCode)Crypto.ErrGetError();
     }
     return(retVal);
 }
Example #7
0
        private static void BioWrite(SafeBioHandle bio, ReadOnlySpan <byte> buffer)
        {
            int bytes = Ssl.BioWrite(bio, ref MemoryMarshal.GetReference(buffer), buffer.Length);

            if (bytes != buffer.Length)
            {
                throw CreateSslException(SR.net_ssl_write_bio_failed_error);
            }
        }
Example #8
0
        public void TestSerialization()
        {
            var sut = new Ssl();

            JsonHelper.GetSerializedKeys(sut).Should().BeEquivalentTo(new SortedSet <string>
            {
                "status", "method", "type", "cname_target", "cname", "settings"
            });
        }
Example #9
0
        internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, bool isServer, bool remoteCertRequired)
        {
            SafeSslHandle context = null;

            IntPtr method = GetSslMethod(protocols);

            using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(method))
            {
                if (innerContext.IsInvalid)
                {
                    throw CreateSslException(SR.net_allocate_ssl_context_failed);
                }

                // Configure allowed protocols. It's ok to use DangerousGetHandle here without AddRef/Release as we just
                // create the handle, it's rooted by the using, no one else has a reference to it, etc.
                Ssl.SetProtocolOptions(innerContext.DangerousGetHandle(), protocols);

                // The logic in SafeSslHandle.Disconnect is simple because we are doing a quiet
                // shutdown (we aren't negotiating for session close to enable later session
                // restoration).
                //
                // If you find yourself wanting to remove this line to enable bidirectional
                // close-notify, you'll probably need to rewrite SafeSslHandle.Disconnect().
                // https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html
                Ssl.SslCtxSetQuietShutdown(innerContext);

                if (!Ssl.SetEncryptionPolicy(innerContext, policy))
                {
                    throw new PlatformNotSupportedException(SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy));
                }

                if (certHandle != null && certKeyHandle != null)
                {
                    SetSslCertificate(innerContext, certHandle, certKeyHandle);
                }

                if (remoteCertRequired)
                {
                    Debug.Assert(isServer, "isServer flag should be true");
                    Ssl.SslCtxSetVerify(innerContext,
                                        s_verifyClientCertificate);

                    //update the client CA list
                    UpdateCAListFromRootStore(innerContext);
                }

                context = SafeSslHandle.Create(innerContext, isServer);
                Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create");
                if (context.IsInvalid)
                {
                    context.Dispose();
                    throw CreateSslException(SR.net_allocate_ssl_context_failed);
                }
            }

            return(context);
        }
Example #10
0
        internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount)
        {
            sendBuf   = null;
            sendCount = 0;

            if ((recvBuf != null) && (recvCount > 0))
            {
                if (BioWrite(context.InputBio, recvBuf, recvOffset, recvCount) <= 0)
                {
                    // Make sure we clear out the error that is stored in the queue
                    throw Crypto.CreateOpenSslCryptographicException();
                }
            }

            int retVal = Ssl.SslDoHandshake(context);

            if (retVal != 1)
            {
                Exception        innerError;
                Ssl.SslErrorCode error = GetSslError(context, retVal, out innerError);

                if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ))
                {
                    throw new SslException(SR.Format(SR.net_ssl_handshake_failed_error, error), innerError);
                }
            }

            sendCount = Crypto.BioCtrlPending(context.OutputBio);
            if (sendCount > 0)
            {
                sendBuf = new byte[sendCount];

                try
                {
                    sendCount = BioRead(context.OutputBio, sendBuf, sendCount);
                }
                finally
                {
                    if (sendCount <= 0)
                    {
                        // Make sure we clear out the error that is stored in the queue
                        Crypto.ErrGetError();
                        sendBuf   = null;
                        sendCount = 0;
                    }
                }
            }

            bool stateOk = Ssl.IsSslStateOK(context);

            if (stateOk)
            {
                context.MarkHandshakeCompleted();
            }
            return(stateOk);
        }
Example #11
0
        internal static int Encrypt(SafeSslHandle context, ReadOnlySpan <byte> input, ref byte[] output, out Ssl.SslErrorCode errorCode)
        {
#if DEBUG
            ulong assertNoError = Crypto.ErrPeekError();
            Debug.Assert(assertNoError == 0, "OpenSsl error queue is not empty, run: 'openssl errstr " + assertNoError.ToString("X") + "' for original error.");
#endif
            errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;

            int       retVal;
            Exception innerError = null;

            lock (context)
            {
                retVal = Ssl.SslWrite(context, ref MemoryMarshal.GetReference(input), input.Length);

                if (retVal != input.Length)
                {
                    errorCode = GetSslError(context, retVal, out innerError);
                }
            }

            if (retVal != input.Length)
            {
                retVal = 0;

                switch (errorCode)
                {
                // indicate end-of-file
                case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
                case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
                    break;

                default:
                    throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError);
                }
            }
            else
            {
                int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio);

                if (output == null || output.Length < capacityNeeded)
                {
                    output = new byte[capacityNeeded];
                }

                retVal = BioRead(context.OutputBio, output, capacityNeeded);

                if (retVal <= 0)
                {
                    // Make sure we clear out the error that is stored in the queue
                    Crypto.ErrClearError();
                }
            }

            return(retVal);
        }
Example #12
0
        internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int offset, int count, out Ssl.SslErrorCode errorCode)
        {
#if DEBUG
            ulong assertNoError = Crypto.ErrPeekError();
            Debug.Assert(assertNoError == 0, "OpenSsl error queue is not empty, run: 'openssl errstr " + assertNoError.ToString("X") + "' for original error.");
#endif
            errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;

            int       retVal     = BioWrite(context.InputBio !, outBuffer, offset, count);
            Exception?innerError = null;

            if (retVal == count)
            {
                unsafe
                {
                    fixed(byte *fixedBuffer = outBuffer)
                    {
                        retVal = Ssl.SslRead(context, fixedBuffer + offset, outBuffer.Length);
                    }
                }

                if (retVal > 0)
                {
                    count = retVal;
                }
            }

            if (retVal != count)
            {
                errorCode = GetSslError(context, retVal, out innerError);
            }

            if (retVal != count)
            {
                retVal = 0;

                switch (errorCode)
                {
                // indicate end-of-file
                case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
                    break;

                case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
                    // update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ
                    errorCode = Ssl.IsSslRenegotiatePending(context) ?
                                Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE :
                                Ssl.SslErrorCode.SSL_ERROR_WANT_READ;
                    break;

                default:
                    throw new SslException(SR.Format(SR.net_ssl_decrypt_failed, errorCode), innerError);
                }
            }

            return(retVal);
        }
Example #13
0
 public void StoreValues(Data data, string path)
 {
     data.SetValue(@"" + path + @"AccountId", Data.EscapeString(AccountId));
     data.SetValue(@"" + path + @"Address", Data.EscapeString(Address));
     data.SetValue(@"" + path + @"Password", _password);
     data.SetValue(@"" + path + @"Port", Port.ToString(System.Globalization.CultureInfo.InvariantCulture));
     data.SetValue(@"" + path + @"Server", Data.EscapeString(Server));
     data.SetValue(@"" + path + @"Ssl", Ssl.ToString());
     data.SetValue(@"" + path + @"UserName", Data.EscapeString(UserName));
 }
Example #14
0
        private static void Disconnect(SafeSslHandle context)
        {
            int retVal = Ssl.SslShutdown(context);

            if (retVal < 0)
            {
                //TODO (Issue #4031) check this error
                Ssl.SslGetError(context, retVal);
            }
        }
        public void ControllerSetForProtocol_ControllerInContext_ProtocolIsRendered(Ssl option)
        {
            //NOTE: "unittest" is the route value from request context, assigned at setup
            _routeOptions.SetOptionByController(option, "unittest");

            _routeCollection.MapRoute("etcroutes", "etc/{controller}/{action}");
            var actual = SslHelpers.UrlHelpers.SslRouteUrl(_urlHelper, "etcroutes", new { action = "someaction" });

            AssertUriPathMatchesOption(option, actual);
        }
Example #16
0
 // Parses environment variables and initializes the values.
 protected internal virtual Configuration ParseEnvironment(IDictionary <string, string> environment)
 {
     Hostname         = GetOrDefault(environment, "HOSTNAME", Hostname);
     Host             = GetOrDefault(environment, "HOST", Host);
     LogLevel         = LogLevel.None;
     Ssl              = bool.Parse(GetOrDefault(environment, "SSL", Ssl.ToString()));
     Port             = int.Parse(GetOrDefault(environment, "PORT", Port.ToString()));
     CustomAppId      = GetOrDefault(environment, "CUSTOM_APP_ID", CustomAppId);
     CustomAppVersion = GetOrDefault(environment, "CUSTOM_APP_VERSION", CustomAppVersion);
     return(this);
 }
Example #17
0
 public Dictionary <string, string> ToDictionary()
 {
     return(new Dictionary <string, string>
     {
         { "Port", Port.ToString() },
         { "HostNames", HostNames },
         { "Ssl", Ssl.ToString() },
         { "ApplicationName", ApplicationName },
         { "LogType", LogType }
     });
 }
        static SslInitializer()
        {
            CryptoInitializer.Initialize();

            //Call ssl specific initializer
            Ssl.EnsureLibSslInitialized();
            if (Interop.Crypto.ErrPeekLastError() != 0)
            {
                // It is going to be wrapped in a type load exception but will have the error information
                throw Interop.Crypto.CreateOpenSslCryptographicException();
            }
        }
Example #19
0
        public void SetUp()
        {
            var       kernel     = new Kernel();
            var       ip         = new Ip("127.0.0.1");
            const int port       = 0;
            Ssl       ssl        = null;
            var       tcpObj     = new SockTcp(new Kernel(), ip, port, 3, ssl);
            var       upperProxy = new UpperProxy(false, "", 0, null, false, "", "");//上位プロキシ未使用
            const int timeout    = 3;

            _proxy = new Proxy(kernel, null, tcpObj, timeout, upperProxy);
        }
Example #20
0
        private static unsafe int AlpnServerSelectCallback(IntPtr ssl, byte **outp, byte *outlen, byte *inp, uint inlen, IntPtr arg)
        {
            *      outp    = null;
            *      outlen  = 0;
            IntPtr sslData = Ssl.SslGetData(ssl);

            // reset application data to avoid dangling pointer.
            Ssl.SslSetData(ssl, IntPtr.Zero);

            GCHandle protocolHandle = GCHandle.FromIntPtr(sslData);

            if (!(protocolHandle.Target is List <SslApplicationProtocol> protocolList))
            {
                return(Ssl.SSL_TLSEXT_ERR_ALERT_FATAL);
            }

            try
            {
                for (int i = 0; i < protocolList.Count; i++)
                {
                    var clientList = new Span <byte>(inp, (int)inlen);
                    while (clientList.Length > 0)
                    {
                        byte        length      = clientList[0];
                        Span <byte> clientProto = clientList.Slice(1, length);
                        if (clientProto.SequenceEqual(protocolList[i].Protocol.Span))
                        {
                            fixed(byte *p = &MemoryMarshal.GetReference(clientProto)) * outp = p;

                            *outlen = length;
                            return(Ssl.SSL_TLSEXT_ERR_OK);
                        }

                        clientList = clientList.Slice(1 + length);
                    }
                }
            }
            catch
            {
                // No common application protocol was negotiated, set the target on the alpnHandle to null.
                // It is ok to clear the handle value here, this results in handshake failure, so the SslStream object is disposed.
                protocolHandle.Target = null;

                return(Ssl.SSL_TLSEXT_ERR_ALERT_FATAL);
            }

            // No common application protocol was negotiated, set the target on the alpnHandle to null.
            // It is ok to clear the handle value here, this results in handshake failure, so the SslStream object is disposed.
            protocolHandle.Target = null;

            return(Ssl.SSL_TLSEXT_ERR_ALERT_FATAL);
        }
Example #21
0
        internal static int Encrypt(SafeSslHandle context, byte[] input, int offset, int count, ref byte[] output, out Ssl.SslErrorCode errorCode)
        {
            Debug.Assert(input != null);
            Debug.Assert(offset >= 0);
            Debug.Assert(count >= 0);
            Debug.Assert(offset <= input.Length);
            Debug.Assert(input.Length - offset >= count);

            errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;

            int retVal;

            unsafe
            {
                fixed(byte *fixedBuffer = input)
                {
                    retVal = Ssl.SslWrite(context, fixedBuffer + offset, count);
                }
            }

            if (retVal != count)
            {
                Exception innerError;
                errorCode = GetSslError(context, retVal, out innerError);
                retVal    = 0;

                switch (errorCode)
                {
                // indicate end-of-file
                case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
                case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
                    break;

                default:
                    throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError);
                }
            }
            else
            {
                int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio);

                if (output == null || output.Length < capacityNeeded)
                {
                    output = new byte[capacityNeeded];
                }

                retVal = BioRead(context.OutputBio, output, capacityNeeded);
            }

            return(retVal);
        }
Example #22
0
        private static void QueryUniqueChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle)
        {
            bool sessionReused  = Ssl.SslSessionReused(context);
            int  certHashLength = context.IsServer ^ sessionReused?
                                  Ssl.SslGetPeerFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length) :
                                      Ssl.SslGetFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length);

            if (0 == certHashLength)
            {
                throw CreateSslException(SR.net_ssl_get_channel_binding_token_failed);
            }

            bindingHandle.SetCertHashLength(certHashLength);
        }
 protected bool Equals(RedisEndpoint other)
 {
     return(string.Equals(Host, other.Host) &&
            Port == other.Port &&
            Ssl.Equals(other.Ssl) &&
            ConnectTimeout == other.ConnectTimeout &&
            SendTimeout == other.SendTimeout &&
            ReceiveTimeout == other.ReceiveTimeout &&
            IdleTimeOutSecs == other.IdleTimeOutSecs &&
            Db == other.Db &&
            string.Equals(Client, other.Client) &&
            string.Equals(Password, other.Password) &&
            string.Equals(NamespacePrefix, other.NamespacePrefix));
 }
Example #24
0
        private static unsafe int AlpnServerSelectCallback(IntPtr ssl, out IntPtr outp, out byte outlen, IntPtr inp, uint inlen, IntPtr arg)
        {
            outp   = IntPtr.Zero;
            outlen = 0;

            GCHandle protocols = GCHandle.FromIntPtr(arg);

            Debug.Assert(protocols.IsAllocated && protocols.Target != null);

            byte[] server = (byte[])protocols.Target;

            return(Ssl.SslSelectNextProto(out outp, out outlen, protocols.AddrOfPinnedObject(), (uint)server.Length, inp, inlen) == Ssl.OPENSSL_NPN_NEGOTIATED ?
                   Ssl.SSL_TLSEXT_ERR_OK : Ssl.SSL_TLSEXT_ERR_NOACK);
        }
Example #25
0
        internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount)
        {
            sendBuf   = null;
            sendCount = 0;
            if ((recvBuf != null) && (recvCount > 0))
            {
                BioWrite(context.InputBio, recvBuf, recvOffset, recvCount);
            }

            Ssl.SslErrorCode error;
            int retVal = Ssl.SslDoHandshake(context);

            if (retVal != 1)
            {
                error = GetSslError(context, retVal);

                if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ))
                {
                    throw CreateSslException(context, SR.net_ssl_handshake_failed_error, retVal);
                }
            }

            sendCount = Crypto.BioCtrlPending(context.OutputBio);

            if (sendCount > 0)
            {
                sendBuf = new byte[sendCount];

                try
                {
                    sendCount = BioRead(context.OutputBio, sendBuf, sendCount);
                }
                finally
                {
                    if (sendCount <= 0)
                    {
                        sendBuf   = null;
                        sendCount = 0;
                    }
                }
            }

            bool stateOk = Ssl.IsSslStateOK(context);

            if (stateOk)
            {
                context.MarkHandshakeCompleted();
            }
            return(stateOk);
        }
Example #26
0
        static OpenSsl()
        {
            if (!AppContext.TryGetSwitch("System.Net.Security.SslStream.ForceClearOpenSslErrorQueue", out bool forceErrorQueueCleanup))
            {
                // AppContext wasn't used, try the environment variable.
                string envVar = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_NET_SECURITY_SSLSTREAM_FORCECLEAROPENSSLERRORQUEUE");
                forceErrorQueueCleanup = envVar != null && (envVar.Equals("true", StringComparison.OrdinalIgnoreCase) || envVar.Equals("1"));
            }

            if (forceErrorQueueCleanup)
            {
                Ssl.ForceErrorQueueCleanupBeforeWriteRead();
            }
        }
Example #27
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("AccountId=" + AccountId.ToString());
            sb.AppendLine("Address=" + Address.ToString());
            sb.AppendLine("Password="******"Port=" + Port.ToString());
            sb.AppendLine("Server=" + Server.ToString());
            sb.AppendLine("Ssl=" + Ssl.ToString());
            sb.AppendLine("UserName=" + UserName.ToString());

            return(sb.ToString());
        }
Example #28
0
        internal static int Encrypt(SafeSslHandle context, ReadOnlyMemory <byte> input, ref byte[] output, out Ssl.SslErrorCode errorCode)
        {
            errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;

            int retVal;

            unsafe
            {
                using (MemoryHandle handle = input.Pin())
                {
                    retVal = Ssl.SslWrite(context, (byte *)handle.Pointer, input.Length);
                }
            }

            if (retVal != input.Length)
            {
                errorCode = GetSslError(context, retVal, out Exception innerError);
                retVal    = 0;

                switch (errorCode)
                {
                // indicate end-of-file
                case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
                case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
                    break;

                default:
                    throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError);
                }
            }
            else
            {
                int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio);

                if (output == null || output.Length < capacityNeeded)
                {
                    output = new byte[capacityNeeded];
                }

                retVal = BioRead(context.OutputBio, output, capacityNeeded);
                if (retVal <= 0)
                {
                    // Make sure we clear out the error that is stored in the queue
                    Crypto.ErrGetError();
                }
            }

            return(retVal);
        }
Example #29
0
 public void StoreValues(Data data, string path)
 {
     data.SetValue(@"" + path + @"AddSignature", AddSignature.ToString());
     data.SetValue(@"" + path + @"Address", Data.EscapeString(Address));
     data.SetValue(@"" + path + @"Content", Data.EscapeString(Content));
     data.SetValue(@"" + path + @"Enabled", Enabled.ToString());
     data.SetValue(@"" + path + @"Password", _password);
     data.SetValue(@"" + path + @"Port", Port.ToString(CultureInfo.InvariantCulture));
     data.SetValue(@"" + path + @"Recipients", Data.EscapeString(Recipients));
     data.SetValue(@"" + path + @"SameTextAsClientMail", SameTextAsClientMail.ToString());
     data.SetValue(@"" + path + @"Server", Data.EscapeString(Server));
     data.SetValue(@"" + path + @"Ssl", Ssl.ToString());
     data.SetValue(@"" + path + @"Subject", Data.EscapeString(Subject));
     data.SetValue(@"" + path + @"UserName", Data.EscapeString(UserName));
 }
Example #30
0
        internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int offset, int count, out Ssl.SslErrorCode errorCode)
        {
            errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;

            int retVal = BioWrite(context.InputBio, outBuffer, offset, count);

            if (retVal == count)
            {
                unsafe
                {
                    fixed(byte *fixedBuffer = outBuffer)
                    {
                        retVal = Ssl.SslRead(context, fixedBuffer + offset, outBuffer.Length);
                    }
                }

                if (retVal > 0)
                {
                    count = retVal;
                }
            }

            if (retVal != count)
            {
                Exception innerError;
                errorCode = GetSslError(context, retVal, out innerError);
                retVal    = 0;

                switch (errorCode)
                {
                // indicate end-of-file
                case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
                    break;

                case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
                    // update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ
                    errorCode = Ssl.IsSslRenegotiatePending(context) ?
                                Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE :
                                Ssl.SslErrorCode.SSL_ERROR_WANT_READ;
                    break;

                default:
                    throw new SslException(SR.Format(SR.net_ssl_decrypt_failed, errorCode), innerError);
                }
            }

            return(retVal);
        }
Example #31
0
        internal static int Encrypt(SafeSslHandle context, byte[] buffer, int offset, int count, out Ssl.SslErrorCode errorCode)
        {
            Debug.Assert(buffer != null);
            Debug.Assert(offset >= 0);
            Debug.Assert(count >= 0);
            Debug.Assert(buffer.Length >= offset + count);

            errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;

            int retVal;

            unsafe
            {
                fixed(byte *fixedBuffer = buffer)
                {
                    retVal = Ssl.SslWrite(context, fixedBuffer + offset, count);
                }
            }

            if (retVal != count)
            {
                Exception innerError;
                errorCode = GetSslError(context, retVal, out innerError);
                retVal    = 0;

                switch (errorCode)
                {
                // indicate end-of-file
                case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
                case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
                    break;

                default:
                    throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError);
                }
            }
            else
            {
                int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio);

                Debug.Assert(buffer.Length >= capacityNeeded, "Input buffer of size " + buffer.Length +
                             " bytes is insufficient since encryption needs " + capacityNeeded + " bytes.");

                retVal = BioRead(context.OutputBio, buffer, capacityNeeded);
            }

            return(retVal);
        }
Example #32
0
        //CLIENT
        public SockUdp(Kernel kernel, Ip ip, int port, Ssl ssl, byte[] buf) : base(kernel)
        {
            //SSL通信を使用する場合は、このオブジェクトがセットされる 通常の場合は、null
            _ssl = ssl;

            _sockKind = SockKind.CLIENT;

            _socket = new Socket((ip.InetKind == InetKind.V4) ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);

            Set(SockState.Connect, null, new IPEndPoint(ip.IPAddress, port));

            //************************************************
            //送信処理
            //************************************************
            Send(buf);
        }
Example #33
0
        protected int VerifyCookie(Ssl ssl, byte[] cookie)
        {
            MemBlock from_cookie = MemBlock.Reference(cookie);

            byte[]   lcookie      = CalculateCookie(ssl.Handle.GetHashCode());
            MemBlock local_cookie = MemBlock.Reference(lcookie);

            if (local_cookie.Equals(from_cookie))
            {
                return(1);
            }
            else
            {
                return(-1);
            }
        }
Example #34
0
        private static void UpdateCAListFromRootStore(SafeSslContextHandle context)
        {
            using (SafeX509NameStackHandle nameStack = Crypto.NewX509NameStack())
            {
                //maintaining the HashSet of Certificate's issuer name to keep track of duplicates
                HashSet <string> issuerNameHashSet = new HashSet <string>();

                //Enumerate Certificates from LocalMachine and CurrentUser root store
                AddX509Names(nameStack, StoreLocation.LocalMachine, issuerNameHashSet);
                AddX509Names(nameStack, StoreLocation.CurrentUser, issuerNameHashSet);

                Ssl.SslCtxSetClientCAList(context, nameStack);

                // The handle ownership has been transferred into the CTX.
                nameStack.SetHandleAsInvalid();
            }
        }
Example #35
0
            public void getLocalAddress(String title, ProtocolKind protocolKind)
            {
                var       bindIp    = new Ip(IpKind.V4Localhost);
                const int port      = 9991;
                const int listenMax = 10;
                Ssl       ssl       = null;

                var sockServer = new SockServer(new Kernel(), protocolKind, ssl);

                ThreadStart action = () => {
                    if (protocolKind == ProtocolKind.Tcp)
                    {
                        sockServer.Bind(bindIp, port, listenMax);
                    }
                    else
                    {
                        sockServer.Bind(bindIp, port);
                    }
                };


                var _t = new Thread(action)
                {
                    IsBackground = true
                };

                _t.Start();

                while (sockServer.SockState == SockState.Idle)
                {
                    Thread.Sleep(200);
                }

                var localAddress = sockServer.LocalAddress;

                Assert.That(localAddress.ToString(), Is.EqualTo("127.0.0.1:9991"));
                //bind()後 localAddressの取得が可能になる

                var remoteAddress = sockServer.RemoteAddress;

                Assert.IsNull(remoteAddress);
                //SockServerでは、remoteAddressは常にnullになる

                sockServer.Close();
            }
Example #36
0
        internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, bool isServer, bool remoteCertRequired)
        {
            SafeSslHandle context = null;

            IntPtr method = GetSslMethod(protocols);

            using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(method))
            {
                if (innerContext.IsInvalid)
                {
                    throw CreateSslException(SR.net_allocate_ssl_context_failed);
                }

                Ssl.SetProtocolOptions(innerContext, protocols);

                Ssl.SslCtxSetQuietShutdown(innerContext);

                Ssl.SetEncryptionPolicy(innerContext, policy);

                if (certHandle != null && certKeyHandle != null)
                {
                    SetSslCertificate(innerContext, certHandle, certKeyHandle);
                }

                if (remoteCertRequired)
                {
                    Debug.Assert(isServer, "isServer flag should be true");
                    Ssl.SslCtxSetVerify(innerContext,
                                        s_verifyClientCertificate);

                    //update the client CA list
                    UpdateCAListFromRootStore(innerContext);
                }

                context = SafeSslHandle.Create(innerContext, isServer);
                Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create");
                if (context.IsInvalid)
                {
                    context.Dispose();
                    throw CreateSslException(SR.net_allocate_ssl_context_failed);
                }
            }

            return(context);
        }
Example #37
0
        protected void InitializeClientContextUsingPsk(string pskCiphers)
        {
            // Initialize the context with the specified ssl version
            //sslContext = new SslContext(SslMethod.SSLv23_client_method);
            sslContext = new SslContext(SslMethod.TLSv1_client_method);
            //sslContext = new SslContext(SslMethod.SSLv3_client_method);

            // Remove support for protocols that should not be supported
            sslContext.Options |= SslOptions.SSL_OP_NO_SSLv2;
            sslContext.Options |= SslOptions.SSL_OP_NO_SSLv3;

            // Set the enabled cipher list
            // WARNING: Using PSK ciphers requires that the PSK callback be set and initialize the identity and psk value.
            // Failure to do this will cause the PSK ciphers to be skipped when picking a shared cipher.
            // The result will be an error because of "no shared ciphers".
//            sslContext.SetCipherList("PSK-AES256-CBC-SHA:PSK-3DES-EDE-CBC-SHA:PSK-AES128-CBC-SHA:PSK-RC4-SHA");
            sslContext.SetCipherList(pskCiphers);

            // Set the PSK callbacks
            sslContext.SetPskClientCallback(this.internalPskClientCallback);

            // Set up the read/write bio's
            read_bio = BIO.MemoryBuffer(false);
            write_bio = BIO.MemoryBuffer(false);
            ssl = new Ssl(sslContext);
            ssl.SetBIO(read_bio, write_bio);
            read_bio.SetClose(BIO.CloseOption.Close);
            write_bio.SetClose(BIO.CloseOption.Close);
			ssl.SetConnectState();
		}
Example #38
0
 public SslException(string inputMessage, Ssl.SslErrorCode error)
     : this(inputMessage, (int)error)
 {
 }
        private void AssertUriPathMatchesOption(Ssl? ssl, string path)
        {
            if (path == null)
            {
                Assert.Fail("Uri path was null");
            }

            if (ssl.HasValue)
            {
                var expectedScheme = (ssl==Ssl.Add) ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
                Assert.That(path.StartsWith(expectedScheme + ":"), path);
            }
            else
            {
                Assert.That(path.StartsWith("/"), path);
            }
        }
Example #40
0
		public override void Close()
		{
			//base.Close();
			if (ssl != null)
			{
				ssl.Dispose();
				ssl = null;
			}
			if (sslContext != null)
			{
				sslContext.Dispose();
				sslContext = null;
			}
		}
Example #41
0
			internal int OnClientCertThunk(IntPtr ssl_ptr, out IntPtr cert_ptr, out IntPtr key_ptr)
			{
				X509Certificate cert = null;
				CryptoKey key = null;
				Ssl ssl = new Ssl(ssl_ptr, false);
				cert_ptr = IntPtr.Zero;
				key_ptr = IntPtr.Zero;

				int nRet = OnClientCertCallback(ssl, out cert, out key);
				if (nRet != 0)
				{
					if (cert != null)
					{
						cert_ptr = cert.Handle;
					}
					if (key != null)
					{
						key_ptr = key.Handle;
					}
				}
				return nRet;
			}
Example #42
0
        // PSK client callback
        public int InternalPskClientCallback(Ssl ssl, String hint, out String identity, uint max_identity_len, out byte[] psk, uint max_psk_len)
        {
            identity = this.pskIdentity;
            psk = this.pskPsk;

            return 1; // success
        }
Example #43
0
        internal static int Encrypt(SafeSslHandle context, byte[] buffer, int offset, int count, out Ssl.SslErrorCode errorCode)
        {
            Debug.Assert(buffer != null);
            Debug.Assert(offset >= 0);
            Debug.Assert(count >= 0);
            Debug.Assert(buffer.Length >= offset + count);

            errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;

            int retVal;
            unsafe
            {
                fixed (byte* fixedBuffer = buffer)
                {
                    retVal = Ssl.SslWrite(context, fixedBuffer + offset, count);
                }
            }

            if (retVal != count)
            {
                Exception innerError;
                errorCode = GetSslError(context, retVal, out innerError);
                retVal = 0;

                switch (errorCode)
                {
                    // indicate end-of-file
                    case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
                    case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
                        break;

                    default:
                        throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError);
                }
            }
            else
            {
                int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio);

                Debug.Assert(buffer.Length >= capacityNeeded, "Input buffer of size " + buffer.Length +
                                                              " bytes is insufficient since encryption needs " + capacityNeeded + " bytes.");

                retVal = BioRead(context.OutputBio, buffer, capacityNeeded);
            }

            return retVal;
        }
        public void NamedRouteSetForSsl_UrlProtocolIsHttps(Ssl ssl)
        {
            _routeCollection.MapRoute(ssl, "Route1", "anything");
            var sslRouteByName = SslHelpers.UrlHelpers.SslRouteUrl(_urlHelper, "Route1");

            AssertUriPathMatchesOption(ssl, sslRouteByName);
        }
Example #45
0
		public int InternalClientCertificateSelectionCallback(Ssl ssl, out X509Certificate x509_cert, out CryptoKey key)
		{
			int nRet = 0;
			x509_cert = null;
			key = null;

			Core.Stack<X509Name> name_stack = ssl.CAList;
			string[] strIssuers = new string[name_stack.Count];
			int count = 0;

			foreach (X509Name name in name_stack)
			{
				strIssuers[count++] = name.OneLine;
			}

			if (localCertificateSelectionCallback != null)
			{
				X509Certificate cert = localCertificateSelectionCallback(this, targetHost, clientCertificates, ssl.GetPeerCertificate(), strIssuers);
				if (cert != null && cert.HasPrivateKey)
				{
					x509_cert = cert;
					key = cert.PrivateKey;
					// Addref the cert and private key
					x509_cert.AddRef();
					key.AddRef();
					// return success
					nRet = 1;
				}
			}

			return nRet;
		}
 public static Route MapRoute(this RouteCollection routes, Ssl ssl, string name, string url)
 {
     RouteOptions.Current.SetOptionForNamedRoute(ssl, name);
     return routes.MapRoute(name, url);
 }
Example #47
0
		protected void InitializeClientContext(X509List certificates, SslProtocols enabledSslProtocols, SslStrength sslStrength, bool checkCertificateRevocation)
		{
			// Initialize the context with the specified ssl version
			// Initialize the context
			sslContext = new SslContext(SslMethod.SSLv23_client_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 Local certificate selection callback
			sslContext.SetClientCertCallback(this.internalCertificateSelectionCallback);
			// Set the enabled cipher list
			sslContext.SetCipherList(GetCipherString(false, enabledSslProtocols, sslStrength));
			// Set the callbacks for remote cert verification and local cert selection
			if (remoteCertificateSelectionCallback != null)
			{
				sslContext.SetVerify(VerifyMode.SSL_VERIFY_PEER | VerifyMode.SSL_VERIFY_FAIL_IF_NO_PEER_CERT, remoteCertificateSelectionCallback);
			}
			// Set the CA list into the store
			if (caCertificates != null)
			{
				X509Store store = new X509Store(caCertificates);
				sslContext.SetCertificateStore(store);
			}
			// Set up the read/write bio's
			read_bio = BIO.MemoryBuffer(false);
			write_bio = BIO.MemoryBuffer(false);
			ssl = new Ssl(sslContext);
			ssl.SetBIO(read_bio, write_bio);
			read_bio.SetClose(BIO.CloseOption.Close);
			write_bio.SetClose(BIO.CloseOption.Close);
			// Set the Ssl object into Client mode
			ssl.SetConnectState();
		}
Example #48
0
      private int OnCallback(IntPtr ssl_ptr, IntPtr cookie_ptr, ref int cookie_len)
      {
        Ssl ssl = new Ssl(ssl_ptr, false);
        byte[] cookie;
        int result = _local_callback(ssl, out cookie);

        Marshal.Copy(cookie, 0, cookie_ptr, cookie.Length);
        cookie_len = cookie.Length;
        return result;
      }
Example #49
0
 private int OnCallback(IntPtr ssl_ptr, IntPtr cookie_ptr, int cookie_len)
 {
   Ssl ssl = new Ssl(ssl_ptr, false);
   byte[] cookie = new byte[cookie_len];
   Marshal.Copy(cookie_ptr, cookie, 0, cookie_len);
   return _local_callback(ssl, cookie);
 }
        public void ControllerSetForProtocol_DefaultExists_ControllerOverridesDefault(Ssl controllerSetting, Ssl @default)
        {
            _routeOptions.SetOptionByController(controllerSetting, "armada");
            _routeCollection.MapRoute("etcroutes", "etc/{controller}/{action}");
            _routeOptions.Default = @default;

            var actual = SslHelpers.UrlHelpers.SslRouteUrl(_urlHelper, "etcroutes", new { controller = "armada", action = "someaction" });
            AssertUriPathMatchesOption(controllerSetting, actual);
        }
 public void SetOptionByController(Ssl ssl, string controller)
 {
     _CurrentOptions.SetOptionForValues(ssl, controller);
 }
        public void UnconfiguredNamedRoute_UrlProtocolMatchesGivenDefault(Ssl? defaultValue)
        {
            _routeOptions.Default = defaultValue;

            _routeCollection.MapRoute("Route1", "anything");

            var sslRouteByName = SslHelpers.UrlHelpers.SslRouteUrl(_urlHelper, "Route1");

            AssertUriPathMatchesOption(defaultValue, sslRouteByName);
        }
Example #53
0
        internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int count, out Ssl.SslErrorCode errorCode)
        {
            errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;

            int retVal = BioWrite(context.InputBio, outBuffer, 0, count);

            if (retVal == count)
            {
                retVal = Ssl.SslRead(context, outBuffer, outBuffer.Length);

                if (retVal > 0)
                {
                    count = retVal;
                }
            }

            if (retVal != count)
            {
                Exception innerError;
                errorCode = GetSslError(context, retVal, out innerError);
                retVal = 0;

                switch (errorCode)
                {
                    // indicate end-of-file
                    case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
                        break;

                    case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
                        // update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ
                        errorCode = Ssl.IsSslRenegotiatePending(context) ?
                                    Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE :
                                    Ssl.SslErrorCode.SSL_ERROR_WANT_READ;
                        break;

                    default:
                        throw new SslException(SR.Format(SR.net_ssl_decrypt_failed, errorCode), innerError);
                }
            }

            return retVal;
        }
Example #54
0
        internal static int Encrypt(SafeSslHandle context, byte[] input, int offset, int count, ref byte[] output, out Ssl.SslErrorCode errorCode)
        {
            Debug.Assert(input != null);
            Debug.Assert(offset >= 0);
            Debug.Assert(count > 0);
            Debug.Assert(offset <= input.Length);
            Debug.Assert(input.Length - offset >= count);

            errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;

            int retVal;
            unsafe
            {
                fixed (byte* fixedBuffer = input)
                {
                    retVal = Ssl.SslWrite(context, fixedBuffer + offset, count);
                }
            }

            if (retVal != count)
            {
                Exception innerError;
                errorCode = GetSslError(context, retVal, out innerError);
                retVal = 0;

                switch (errorCode)
                {
                    // indicate end-of-file
                    case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
                    case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
                        break;

                    default:
                        throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError);
                }
            }
            else
            {
                int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio);

                if (output == null || output.Length < capacityNeeded)
                {
                    output = new byte[capacityNeeded];
                }

                retVal = BioRead(context.OutputBio, output, capacityNeeded);
            }

            return retVal;
        }
Example #55
0
        private static SslException CreateSslException(string message, Ssl.SslErrorCode error)
        {
            string msg = SR.Format(message, error);
            switch (error)
            {
                case Ssl.SslErrorCode.SSL_ERROR_SYSCALL:
                    return CreateSslException(msg);

                case Ssl.SslErrorCode.SSL_ERROR_SSL:
                    Exception innerEx = Interop.Crypto.CreateOpenSslCryptographicException();
                    return new SslException(innerEx.Message, innerEx);

                default:
                    return new SslException(msg, error);
            }
        }
Example #56
0
        // PSK client callback
        public int InternalPskServerCallback(Ssl ssl, String identity, out byte[] psk, uint max_psk_len)
        {
            psk = this.pskPsk;

            return 1; // success
        }