public static SafeFreeCredentials AcquireDefaultCredential(SSPIInterface SecModule, string package, CredentialUse intent)
        {
            GlobalLog.Print("SSPIWrapper::AcquireDefaultCredential(): using " + package);
            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web,
                                  "AcquireDefaultCredential(" +
                                  "package = " + package + ", " +
                                  "intent  = " + intent + ")");
            }


            SafeFreeCredentials outCredential = null;
            int errorCode = SecModule.AcquireDefaultCredential(package, intent, out outCredential);

            if (errorCode != 0)
            {
#if TRAVE
                GlobalLog.Print("SSPIWrapper::AcquireDefaultCredential(): error " + SecureChannel.MapSecurityStatus((uint)errorCode));
#endif
                if (Logging.On)
                {
                    Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_operation_failed_with_error, "AcquireDefaultCredential()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
                }
                throw new Win32Exception(errorCode);
            }
            return(outCredential);
        }
Ejemplo n.º 2
0
        protected override void Dispose(bool disposing)
        {
            GlobalLog.Print("TlsStream::Dispose()");
            if (Interlocked.Exchange(ref m_ShutDown, 1) == 1)
            {
                return;
            }

            if (disposing)
            {
                m_DestinationHost    = null;
                m_SecureChannel      = null;
                m_ArrivingData       = null;
                m_ClientCertificates = null;

                // This might leak memory but we do clenup through garbage-collection
                if (m_Exception == null)
                {
                    m_Exception = new WebException(
                        NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.ConnectionClosed),
                        WebExceptionStatus.ConnectionClosed);
                }
            }
            //
            // only resource we need to free is the network stream, since this
            // is based on the client socket, closing the stream will cause us
            // to flush the data to the network, close the stream and (in the
            // NetoworkStream code) might close the socket as well if we own it.
            //
            base.Dispose(disposing);
        }
Ejemplo n.º 3
0
        public ServiceProxyResponder(BamConf conf, ILogger logger)
            : base(conf, logger)
        {
            _commonServiceProvider   = new Incubator();
            _appServiceProviders     = new Dictionary <string, Incubator>();
            _appSecureChannels       = new Dictionary <string, SecureChannel>();
            _commonSecureChannel     = new SecureChannel();
            _clientProxyGenerators   = new Dictionary <string, IClientProxyGenerator>();
            RendererFactory          = new RendererFactory(logger);
            ExecutionRequestResolver = new ExecutionRequestResolver();

            AddCommonService(_commonSecureChannel);
            AddClientProxyGenerator(new CsClientProxyGenerator(), "proxies.cs", "csproxies", "csharpproxies");
            AddClientProxyGenerator(new JsClientProxyGenerator(), "proxies.js", "jsproxies", "javascriptproxies");

            CommonServiceAdded += (type, obj) =>
            {
                CommonSecureChannel.ServiceProvider.Set(type, obj);
            };
            CommonServiceRemoved += (type) =>
            {
                CommonSecureChannel.ServiceProvider.Remove(type);
            };
            AppServiceAdded += (appName, type, instance) =>
            {
                if (!AppSecureChannels.ContainsKey(appName))
                {
                    SecureChannel channel = new SecureChannel();
                    channel.ServiceProvider.CopyFrom(CommonServiceProvider, true);
                    AppSecureChannels.Add(appName, channel);
                }

                AppSecureChannels[appName].ServiceProvider.Set(type, instance, false);
            };
        }
 public void RemoteCertUserDeclaredInvalid(SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         RemoteCertUserDeclaredInvalid(GetHashCode(secureChannel));
     }
 }
 public void NoDelegateButClientCert(SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         NoDelegateButClientCert(GetHashCode(secureChannel));
     }
 }
 public void AttemptingRestartUsingCert(X509Certificate?clientCertificate, SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         AttemptingRestartUsingCert(clientCertificate?.ToString(true), GetHashCode(secureChannel));
     }
 }
 public void NoIssuersTryAllCerts(SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         NoIssuersTryAllCerts(GetHashCode(secureChannel));
     }
 }
 public void RemoteCertHasNoErrors(SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         RemoteCertHasNoErrors(GetHashCode(secureChannel));
     }
 }
 public void RemoteCertificateError(SecureChannel secureChannel, string message)
 {
     if (IsEnabled())
     {
         RemoteCertificateError(GetHashCode(secureChannel), message);
     }
 }
 public void UsingCachedCredential(SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         UsingCachedCredential(GetHashCode(secureChannel));
     }
 }
 public void SecureChannelCtor(SecureChannel secureChannel, SslStream sslStream, string hostname, X509CertificateCollection?clientCertificates, EncryptionPolicy encryptionPolicy)
 {
     if (IsEnabled())
     {
         SecureChannelCtor(IdOf(secureChannel), hostname, GetHashCode(secureChannel), clientCertificates?.Count ?? 0, encryptionPolicy);
     }
 }
Ejemplo n.º 12
0
 public void FoundCertInStore(bool serverMode, SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         FoundCertInStore(serverMode ? "LocalMachine" : "CurrentUser", GetHashCode(secureChannel));
     }
 }
 public void CertsAfterFiltering(int filteredCertsCount, SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         CertsAfterFiltering(filteredCertsCount, GetHashCode(secureChannel));
     }
 }
Ejemplo n.º 14
0
 public void LocatingPrivateKey(X509Certificate x509Certificate, SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         LocatingPrivateKey(x509Certificate.ToString(true), GetHashCode(secureChannel));
     }
 }
Ejemplo n.º 15
0
 public void CertIsType2(SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         CertIsType2(GetHashCode(secureChannel));
     }
 }
Ejemplo n.º 16
0
 public void UsingCachedCredential(SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         WriteEvent(UsingCachedCredentialId, GetHashCode(secureChannel));
     }
 }
Ejemplo n.º 17
0
 public void NotFoundCertInStore(SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         NotFoundCertInStore(GetHashCode(secureChannel));
     }
 }
Ejemplo n.º 18
0
        public ServiceProxyResponder(BamConf conf, ILogger logger)
            : base(conf, logger)
        {
            _commonServiceProvider = new Incubator();
            _appServiceProviders   = new Dictionary <string, Incubator>();
            _appSecureChannels     = new Dictionary <string, SecureChannel>();
            _commonSecureChannel   = new SecureChannel();
            RendererFactory        = new RendererFactory(logger);

            AddCommonService(_commonSecureChannel);

            CommonServiceAdded += (type, obj) =>
            {
                CommonSecureChannel.ServiceProvider.Set(type, obj);
            };
            CommonServiceRemoved += (type) =>
            {
                CommonSecureChannel.ServiceProvider.Remove(type);
            };
            AppServiceAdded += (appName, type, instance) =>
            {
                if (!AppSecureChannels.ContainsKey(appName))
                {
                    SecureChannel channel = new SecureChannel();
                    channel.ServiceProvider.CopyFrom(CommonServiceProvider, true);
                    AppSecureChannels.Add(appName, channel);
                }

                AppSecureChannels[appName].ServiceProvider.Set(type, instance, false);
            };
        }
 public void LookForMatchingCerts(int issuersCount, SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         LookForMatchingCerts(issuersCount, GetHashCode(secureChannel));
     }
 }
        /// <inheritdoc/>
        public void OnAccept(HttpContext context, WebSocket webSocket)
        {
            SecureChannel channel = null;

            // check if the accept socket has been created.
            if (webSocket != null)
            {
                try {
                    channel = new SecureChannel(_listenerId, this,
                                                _bufferManager, _quotas, _controller.Certificate,
                                                _controller.CertificateChain, GetEndpoints());
                    channel.SetRequestReceivedCallback(OnRequestReceived);

                    // Wrap socket in channel to read and write.
                    var socket = new WebSocketMessageSocket(channel, webSocket,
                                                            _bufferManager, _quotas.MaxBufferSize);
                    var channelId = (uint)Interlocked.Increment(ref _lastChannelId);
                    channel.Attach(channelId, socket);

                    _channels.TryAdd(channelId, channel);
                    _logger.Debug("Started channel {channelId} on {socket.Handle}...",
                                  channelId, socket.Handle);
                }
                catch (Exception ex) {
                    _logger.Error(ex, "Unexpected error accepting a new connection.");
                }
            }
        }
 public void SelectedCert(X509Certificate clientCertificate, SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         SelectedCert(clientCertificate?.ToString(true), GetHashCode(secureChannel));
     }
 }
Ejemplo n.º 22
0
        public void ConstructorEnsureSecurity2()
        {
            IChannel ch = new SecureChannel();

            ChannelServices.RegisterChannel(ch, true);
            ChannelServices.UnregisterChannel(ch);
        }
 public void FindingMatchingCerts(SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         FindingMatchingCerts(GetHashCode(secureChannel));
     }
 }
 public void CertificateFromDelegate(SecureChannel secureChannel)
 {
     if (IsEnabled())
     {
         CertificateFromDelegate(GetHashCode(secureChannel));
     }
 }
Ejemplo n.º 25
0
        public static void Prepare()
        {
            ConsoleLogger logger = new ConsoleLogger();

            SecureChannel.InitializeDatabase(logger);
            RegisterDb();
            ClearApps();
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Handles a new connection.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnAccept(object sender, SocketAsyncEventArgs e)
        {
            SecureChannel channel = null;

            while (true)
            {
                var error = e.SocketError;
                var token = e.UserToken;

                // check if the accept socket has been created.
                if (e.AcceptSocket != null && e.SocketError == SocketError.Success)
                {
                    try {
                        // Wrap socket in channel to read and write.
                        channel = new SecureChannel(_listenerId, this,
                                                    _bufferManager, _quotas,
                                                    _serverCertificate ?? _controller.Certificate,
                                                    _serverCertificateChain ?? _controller.CertificateChain,
                                                    GetEndpoints());
                        channel.SetRequestReceivedCallback(new TcpChannelRequestEventHandler(OnRequestReceived));

                        var channelId = (uint)Interlocked.Increment(ref _lastChannelId);
#pragma warning disable IDE0068 // Use recommended dispose pattern
                        var socket = new TcpMessageSocket(channel, e.AcceptSocket,
                                                          _bufferManager, _quotas.MaxBufferSize);
#pragma warning restore IDE0068 // Use recommended dispose pattern
                        channel.Attach(channelId, socket);

                        _channels.TryAdd(channelId, channel);
                        _logger.Debug("Started channel {channelId} on {socket}...",
                                      channelId, socket.Handle);
                    }
                    catch (Exception ex) {
                        _logger.Error(ex, "Unexpected error accepting a new connection.");
                    }
                }

                e.Dispose();
                if (error != SocketError.OperationAborted && token is Socket listeningSocket)
                {
                    // Schedule new accept
                    try {
                        e            = new SocketAsyncEventArgs(); // Should cache it
                        e.Completed += OnAccept;
                        e.UserToken  = listeningSocket;
                        if (!listeningSocket.AcceptAsync(e))
                        {
                            continue; // Handle synchronously
                        }
                    }
                    catch (Exception ex) {
                        _logger.Error(ex, "Unexpected error listening for a connections.");
                        // Stop listening
                    }
                }
                break;
            }
        }
Ejemplo n.º 27
0
        public static void Prepare()
        {
            RegisterDb();
            Db.For <UserAccounts.Data.Account>(UserAccounts.UserAccountsDatabase.Default);
            ConsoleLogger logger = new ConsoleLogger();

            SecureChannel.InitializeDatabase(logger);
            ClearApps();
        }
Ejemplo n.º 28
0
        public void Securesession_ShouldBeAbleToGetSecureSession()
        {
            ConsoleLogger logger = new ConsoleLogger();

            SecureChannel.InitializeDatabase(logger);
            Cookie        cookie  = new Cookie(SecureSession.CookieName, "TestSecureSessionId");
            SecureSession session = SecureSession.Get(cookie);

            Expect.IsNotNull(session);
        }
Ejemplo n.º 29
0
        public void Do()
        {
            // we are using dealer here, but we can use router as well, we just have to manager
            // SecureChannel for each identity
            using (var socket = new DealerSocket())
            {
                socket.Bind("tcp://*:9696");

                using (SecureChannel secureChannel = SecureChannel.CreateServerSecureChannel(m_configuration))
                {
                    // we need to set X509Certificate with a private key for the server
                    X509Certificate2 certificate = new X509Certificate2(
                        System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "server.pfx"), "1234");
                    secureChannel.Certificate = certificate;

                    List <NetMQMessage> outgoingMessages = new List <NetMQMessage>();

                    // waiting for message from client
                    NetMQMessage incomingMessage = socket.ReceiveMultipartMessage();
                    //SplitInMessage

                    // calling ProcessMessage until ProcessMessage return true
                    // and the SecureChannel is ready to encrypt and decrypt messages
                    while (!secureChannel.ProcessMessage(incomingMessage, outgoingMessages))
                    {
                        //SendMessages(socket,outgoingMessages);
                        foreach (NetMQMessage message in outgoingMessages)
                        {
                            socket.SendMultipartMessage(message);
                        }
                        outgoingMessages.Clear();
                        incomingMessage = socket.ReceiveMultipartMessage();
                    }
                    //SendMessages(socket, outgoingMessages);
                    foreach (NetMQMessage message in outgoingMessages)
                    {
                        socket.SendMultipartMessage(message);
                    }
                    outgoingMessages.Clear();

                    // this message is now encrypted
                    NetMQMessage cipherMessage = socket.ReceiveMultipartMessage();

                    // decrypting the message
                    NetMQMessage plainMessage = secureChannel.DecryptApplicationMessage(cipherMessage);
                    System.Console.WriteLine(plainMessage.First.ConvertToString());
                    plainMessage = new NetMQMessage();
                    plainMessage.Append("Worldddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd");

                    // encrypting the message and sending it over the socket
                    socket.SendMultipartMessage(secureChannel.EncryptApplicationMessage(plainMessage));
                }
            }
        }
Ejemplo n.º 30
0
        public void Securesession_ShouldGetTheSameSession()
        {
            SecureChannel server = new SecureChannel();

            server.HttpContext         = A.Fake <IHttpContext>();
            server.HttpContext.Request = new ServiceProxyTestHelpers.FormUrlEncodedTestRequest();

            SecureChannelMessage <ClientSessionInfo> one = server.InitSession(new Instant());
            SecureChannelMessage <ClientSessionInfo> two = server.InitSession(new Instant());

            Expect.AreEqual(one.Data.SessionId, two.Data.SessionId, "Session Ids didn't match");
        }
Ejemplo n.º 31
0
		public void ConstructorEnsureSecurity2 ()
		{
			IChannel ch = new SecureChannel ();
			ChannelServices.RegisterChannel (ch, true);
			ChannelServices.UnregisterChannel (ch);
		}