Ejemplo n.º 1
0
 public AuthorizationException(string message, Type entityType, AccessType accessType, bool isRecordLevel, 
     UserRecordPermission grantedPermissions, SecureSession session = null)
     : base(message)
 {
     EntityType = entityType;
       AccessType = accessType;
       IsRecordLevel = isRecordLevel;
       GrantedPermissions = grantedPermissions;
       if (session != null) {
     RequireReadMode = session.DemandReadAccessLevel;
     CurrentDenyReadMode = session.DenyReadAction;
     var ctx = session.Context;
     UserName = ctx.User.UserName;
     UserContextValues = string.Join(string.Empty, ctx.Values.Select(kv => StringHelper.SafeFormat("      [{0}]={1}\r\n", kv.Key, kv.Value)));
     var user = ctx.User;
     if (user.Authority == null) {
       UserRoles = "(UserContext.Authority is not set)";
     } else {
       UserRoles = user.Authority.GetRoleNames();
       PermissionSummary = user.Authority.GetPermissionsSummary(EntityType);
       var enDynGrants = user.Authority.DynamicGrants.Where(g => g.IsEnabled(session.Context));
       EnabledDynamicGrants = string.Join(",", enDynGrants.Select(g => g.Activity.Name));
     }
       }
 }
Ejemplo n.º 2
0
        private async ValueTask <TlsStream> EstablishSslConnection(string host, HttpRequestMessage request, Stream stream, CancellationToken cancellationToken)
        {
            logger.Trace("HTTP connection handler: Establish TLS connection");

            var secParams = new SecurityParameters();

            secParams.CipherSuiteIDs.Add(CipherSuiteId.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256);
            secParams.CipherSuiteIDs.Add(CipherSuiteId.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384);
            secParams.CipherSuiteIDs.Add(CipherSuiteId.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256);
            secParams.CipherSuiteIDs.Add(CipherSuiteId.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384);
            secParams.MinimumVersion = ProtocolVersion.TLS1_2;
            secParams.MaximumVersion = ProtocolVersion.TLS1_2;

            if (this._settings._clientCertificate != null)
            {
                var pluginManager = new IVU.Common.Tls.Plugin.CipherSuitePluginInterface.CipherSuitePluginManager();
                var privateKey    = pluginManager.GetPrivateKey(this._settings._clientCertificate.Key);
                secParams.AddCertificate(new X509CertificateCollection {
                    this._settings._clientCertificate.Certificate
                }, privateKey);
            }

            secParams.ClientCertificateSelectionCallback += (client, server) =>
            {
                return(0);
            };

            secParams.ServerCertificateValidationCallback = certificates =>
            {
                if (this._settings?._serverCertificateCustomValidationCallback == null)
                {
                    logger.Error("No server certificate validation callback provided!");
                    return(false);
                }

                return(this._settings?._serverCertificateCustomValidationCallback(
                           request,
                           new X509Certificate2(certificates[0]),
                           null,
                           SslPolicyErrors.None) == true);
            };

            var tlsSession = new SecureSession(stream, secParams);

            try
            {
                await tlsSession.PerformClientHandshake(cancellationToken);

                logger.Trace("HTTP connection handler: TLS connection successfull establish");
            }
            catch (Exception ex)
            {
                tlsSession.Close();
                logger.ErrorException("Failed to establish TLS connection: {0}", ex, ex.Message);
                throw new TlsConnectFailed("Failed to establish TLS connection", ex);
            }

            return(new TlsStream(tlsSession));
        }
Ejemplo n.º 3
0
        public void Validation_ShouldBeAbleToCreateToken()
        {
            Prepare();

            IHttpContext  context    = CreateFakeContext(MethodBase.GetCurrentMethod().Name);
            SecureSession session    = SecureSession.Get(context);
            string        postString = ApiParameters.ParametersToJsonParamsObjectString("random information");

            EncryptedValidationToken token = ApiEncryptionValidation.CreateEncryptedValidationToken(postString, session);
        }
Ejemplo n.º 4
0
        public void should_login_token()
        {
            var secureSession = new SecureSession<Token>(null, new MemoryTokenStore<Token>());
            var token = new Token(Guid.Empty, null, false);

            secureSession.Login(token);

            secureSession.IsLoggedIn().ShouldBeTrue();
            secureSession.GetCurrentToken().ShouldEqual(token);
        }
Ejemplo n.º 5
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.secureSession?.Close();
                this.secureSession = null;
            }

            base.Dispose(disposing);
        }
Ejemplo n.º 6
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.º 7
0
        private static IRequest CreateFakeRequest()
        {
            IRequest request = A.Fake <IRequest>();

            A.CallTo(() => request.Headers).Returns(new NameValueCollection());
            A.CallTo(() => request.Cookies).Returns(new CookieCollection());
            Cookie sessionCookie = new Cookie(SecureSession.CookieName, SecureSession.GenerateId());

            request.Cookies.Add(sessionCookie);
            return(request);
        }
Ejemplo n.º 8
0
        public void ShouldBeAbleToEncryptAndDecryptWithSecureSession()
        {
            InitializeSecureChannelSchema();

            SecureSession testObject = SecureSession.Get(new ServiceProxyTestHelpers.FormUrlEncodedTestRequest(), A.Fake <IResponse>());
            string        data       = "Monkey";
            string        cipher     = testObject.EncryptWithPublicKey(data);
            string        decrypted  = testObject.DecryptWithPrivateKey(cipher);

            Expect.AreEqual(data, decrypted);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Decrypt the input string of the specified ExecutionRequest
 /// if it is intended for the SecureChannel
 /// </summary>
 /// <param name="execRequest"></param>
 public static void DecryptSecureChannelInvoke(ExecutionRequest execRequest)
 {
     if (execRequest.Instance != null &&
         execRequest.Instance.GetType() == typeof(SecureChannel) &&
         execRequest.MethodName.Equals(nameof(SecureChannel.Invoke)))
     {
         execRequest.InputString = SecureSession.Get(execRequest.Context).Decrypt(execRequest.InputString);
         HttpArgs args = new HttpArgs();
         args.ParseJson(execRequest.InputString);
         execRequest.JsonParams = args["jsonParams"];
     }
 }
Ejemplo n.º 10
0
        public void should_not_log_in_an_invalid_user()
        {
            var authenticationService = Substitute.For<IAuthenticationService<Token>>();
            var secureSession = new SecureSession<Token>(authenticationService, new MemoryTokenStore<Token>());

            authenticationService.Authenticate(Arg.Any<string>(), Arg.Any<string>()).
                                  ReturnsForAnyArgs(x => { throw new AuthenticationService.AccessDeniedException(); });

            Assert.Throws<AuthenticationService.AccessDeniedException>(() => secureSession.Login("username", "password"));

            secureSession.IsLoggedIn().ShouldBeFalse();
            secureSession.GetCurrentToken().ShouldBeNull();
        }
Ejemplo n.º 11
0
        public void should_logout_user()
        {
            var authenticationService = Substitute.For<IAuthenticationService<Token>>();
            var secureSession = new SecureSession<Token>(authenticationService, new MemoryTokenStore<Token>());

            authenticationService.Authenticate(Arg.Any<string>(), Arg.Any<string>()).
                                  ReturnsForAnyArgs(new Token(Guid.Empty, null, false));

            secureSession.Login("username", "password");
            secureSession.Logout();

            secureSession.IsLoggedIn().ShouldBeFalse();
            secureSession.GetCurrentToken().ShouldBeNull();
        }
Ejemplo n.º 12
0
        public void Securesession_ShouldBeAbleToSetValidationToken()
        {
            ConsoleLogger logger = new ConsoleLogger();

            SecureChannel.InitializeDatabase(logger);

            IRequest      request = CreateFakeRequest();
            SecureSession session = SecureSession.Get(request);

            ApiEncryptionValidation.SetEncryptedValidationToken(request.Headers, "Some random data", session.PublicKey);

            Expect.IsNotNull(request.Headers[CustomHeaders.ValidationToken]);

            OutLine(request.Headers[CustomHeaders.ValidationToken]);
        }
Ejemplo n.º 13
0
        public void Securesession_ShouldBeAbleToEncryptAndDecryptWithSecureSession()
        {
            SecureChannelConfig config = new SecureChannelConfig();
            Exception           ex;

            config.SchemaInitializer.Initialize(new ConsoleLogger(), out ex);
            Expect.IsNull(ex);

            SecureSession testObject = SecureSession.Get(new ServiceProxyTestHelpers.FormUrlEncodedTestRequest(), A.Fake <IResponse>());
            string        data       = "Monkey";
            string        cipher     = testObject.EncryptWithPublicKey(data);
            string        decrypted  = testObject.DecryptWithPrivateKey(cipher);

            Expect.AreEqual(data, decrypted);
        }
Ejemplo n.º 14
0
        public static void Main(string[] args)
        {
            SecurityParameters securityParameters = new SecurityParameters();

            securityParameters.CipherSuiteIDs.Add(0x000a);
            securityParameters.ServerCertificateValidationCallback = new ServerCertificateValidationCallback(CertificateValidationCallback);
            securityParameters.ClientCertificateSelectionCallback  = new ClientCertificateSelectionCallback(CertificateSelectionCallback);

            if (args.Length >= 2)
            {
                X509CertificateCollection certs = new X509CertificateCollection();
                for (int i = 0; i < args.Length - 1; i++)
                {
                    certs.Add(new X509Certificate(args[i]));
                }

                // Get plugin manager for importing the private key
                string path      = System.Reflection.Assembly.GetAssembly(typeof(AaltoTLS.HandshakeLayer.HandshakeSession)).Location;
                string directory = Path.GetDirectoryName(path);
                CipherSuitePluginManager pluginManager = new CipherSuitePluginManager(directory);

                // Import the private key into asymmetric algorithm
                byte[] privateKeyData            = File.ReadAllBytes(args[args.Length - 1]);
                CertificatePrivateKey privateKey = pluginManager.GetPrivateKey(privateKeyData);

                securityParameters.AddCertificate(certs, privateKey);
            }

            string host = "www.mikestoolbox.net";
            int    port = 443;

            string request = "GET / HTTP/1.1\r\nHost: " + host + "\r\n\r\n";

            try {
                TcpClient     tcpClient = new TcpClient(host, port);
                NetworkStream ns        = tcpClient.GetStream();
                SecureSession session   = new SecureSession(ns, securityParameters);
                session.PerformClientHandshake(host);
                session.Send(Encoding.UTF8.GetBytes(request));
                byte[] received = session.Receive();
                Console.WriteLine("Received data: " + Encoding.UTF8.GetString(received));
                session.Close();
            } catch (SocketException) {
                Console.WriteLine("Unable to connect to server");
                return;
            }
        }
Ejemplo n.º 15
0
        public void Securesession_StartSessionShouldCreateSecureSessionEntry()
        {
            SecureChannel server = new SecureChannel();

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

            SecureChannelMessage <ClientSessionInfo> message = server.InitSession(new Instant());
            ClientSessionInfo sessionInfo = message.Data;

            SecureSession created = SecureSession.OneWhere(c => c.Id == sessionInfo.SessionId);

            Expect.IsNotNull(created);
            Expect.IsNotNullOrEmpty(created.Identifier, "Identifier was null or empty");
            Expect.AreEqual(created.Identifier, sessionInfo.ClientIdentifier, "ClientIdentifiers didn't match");
            Expect.AreEqual(sessionInfo.PublicKey, created.PublicKey);
        }
Ejemplo n.º 16
0
        public void should_login_valid_user()
        {
            var authenticationService = Substitute.For<IAuthenticationService<Token>>();
            var secureSession = new SecureSession<Token>(authenticationService, new MemoryTokenStore<Token>());
            var userId = Guid.NewGuid();

            authenticationService.Authenticate(Arg.Any<string>(), Arg.Any<string>()).
                                  ReturnsForAnyArgs(new Token(userId, "username", true));

            secureSession.Login("username", "password");

            secureSession.IsLoggedIn().ShouldBeTrue();
            var token = secureSession.GetCurrentToken();
            token.ShouldNotBeNull();
            token.UserId.ShouldEqual(userId);
            token.Username.ToString().ShouldEqual("username");
            token.IsAdministrator.ShouldBeTrue();
        }
Ejemplo n.º 17
0
        private void IVRButton_Click(object sender, EventArgs e)
        {
            try
            {
                var api = new ConversationsApi();

                string conversationId    = conversationIdTextBox.Text;
                string participantId     = participantIdTextbox.Text;
                CreateSecureSession body = new CreateSecureSession();
                body.FlowId              = "";
                body.UserData            = "<OrderID>|1000|" + conversationId + "|<Entity>";
                body.Disconnect          = false;
                body.SourceParticipantId = userIdTextbox.Text; // agentId

                SecureSession result = api.PostConversationParticipantSecureivrsessions(conversationId, participantId, body);
                IVRResultTextbox.Text = result.ToJson();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 18
0
        public static void CleanUp()
        {
            FilesToDelete.Each(file =>
            {
                if (File.Exists(file))
                {
                    File.Delete(file);
                }
            });

            Prepare();
            ApiKeyCollection keys = ApiKey.LoadAll();

            keys.Delete();
            SecureSessionCollection sessions = SecureSession.LoadAll();

            sessions.Delete();

            ApplicationCollection all = Application.LoadAll();

            all.Delete();
            ClearAppsAndStopServers();
        }
Ejemplo n.º 19
0
        public void Validation_ShouldBeAbleToSetAndValidateValidationToken()
        {
            Prepare();

            SecureSession session = SecureSession.Get(SecureSession.GenerateId());

            string postString = ApiParameters.ParametersToJsonParamsObjectString("random info");
            SecureServiceProxyClient <Echo> client = new SecureServiceProxyClient <Echo>("http://blah.com");

            HttpWebRequest request = client.GetServiceProxyRequest("Send");

            ApiEncryptionValidation.SetEncryptedValidationToken(request.Headers, postString, session.PublicKey);

            Cookie cookie = new Cookie(SecureSession.CookieName, session.Identifier, "", "blah.cxm");

            request.CookieContainer.Add(cookie);
            request.Headers[Headers.SecureSession] = session.Identifier;

            Expect.IsNotNull(request.Headers);
            Expect.IsNotNull(request.Headers[Headers.Nonce]);
            Expect.IsNotNull(request.Headers[Headers.ValidationToken]);

            Expect.AreEqual(EncryptedTokenValidationStatus.Success, ApiEncryptionValidation.ValidateEncryptedToken(request.Headers, postString));
        }
Ejemplo n.º 20
0
 public override void Close()
 {
     this.secureSession?.Close();
     this.secureSession = null;
 }
Ejemplo n.º 21
0
        public static ISecureSession OpenSecureSession(this OperationContext context)
        {
            var session = new SecureSession(context);

            return(session);
        }
        public void Handle()
        {
            NetworkStream networkStream  = null;

            try
            {
                bool loop = true;

                IPEndPoint ipep = (IPEndPoint)Socket.RemoteEndPoint;
                IPAddress = ipep.Address;

                networkStream = new NetworkStream(Socket);

                try
                {
                    Session = new SecureSession(networkStream, Certificates.SecurityParameters);
                    Session.PerformServerHandshake(Certificates.Certificate);
                }
                catch
                {
                    loop = false;
                }


                while (loop)
                {
                    HydraRequest request = null;
                    try
                    {
                        request = new HydraRequest(this);
                    }
                    catch
                    {
                        break;
                    }

                    Modules.IModule module = null;

                    switch (request.Module)
                    {
                        case "feed":
                            {
                                module = new Modules.FeedModule(this);
                                break;
                            }
                        case "profile":
                            {
                                module = new Modules.ProfileModule(this);
                                break;
                            }
                        case "onesite_proxy":
                            {
                                module = new Modules.OnesiteProxyModule(this);
                                break;
                            }
                        case "ugc":
                            {
                                module = new Modules.UgcModule(this);
                                break;
                            }

                        default:
                            {
                                HydraResponse response = new HydraResponse(this);
                                response.StatusCode = 404;
                                response.Status = "File Not Found";
                                response.Payload = new byte[0];
                                response.Send();
                                break;
                            }
                    }

                    if (module != null)
                        module.HandleRequest(request);
                }
            }
            catch (Exception ex)
            {
            }

            try
            {
                Session.Close();
                networkStream.Flush();
                networkStream.Close();
                Socket.Disconnect(false);
                Socket.Dispose();
            }
            catch
            {
            }
        }
Ejemplo n.º 23
0
 public TlsStream(SecureSession secureSession)
 {
     this.secureSession = secureSession;
 }
Ejemplo n.º 24
0
        public override bool TryRespond(IHttpContext context)
        {
            if (!IsInitialized)
            {
                Initialize();
            }

            IRequest  request  = context.Request;
            IResponse response = context.Response;

            Session.Init(context);
            SecureSession.Init(context);

            bool   handled    = false;
            string path       = request.Url.AbsolutePath;
            string commonPath = Path.Combine("/common", path.TruncateFront(1));

            byte[] content = new byte[] { };
            string appName = AppConf.AppNameFromUri(request.Url, BamConf.AppConfigs);

            string[] checkedPaths = new string[] { };
            if (AppContentResponders.ContainsKey(appName))
            {
                handled = AppContentResponders[appName].TryRespond(context, out checkedPaths);
            }

            if (!handled && !ShouldIgnore(path))
            {
                string readFileFromPath;
                bool   exists;
                exists = ServerRoot.FileExists(path, out readFileFromPath);
                if (!exists)
                {
                    exists = ServerRoot.FileExists(commonPath, out readFileFromPath);
                }

                if (exists)
                {
                    string ext = Path.GetExtension(readFileFromPath);
                    if (FileCachesByExtension.ContainsKey(ext))
                    {
                        FileCache cache = FileCachesByExtension[ext];
                        if (ShouldZip(request))
                        {
                            SetGzipContentEncodingHeader(response);
                            content = cache.GetZippedContent(readFileFromPath);
                        }
                        else
                        {
                            content = cache.GetContent(readFileFromPath);
                        }
                        handled = true;
                    }
                }

                if (handled)
                {
                    SetContentType(response, path);
                    SendResponse(response, content);
                    OnResponded(context);
                }
                else
                {
                    LogContentNotFound(path, appName, checkedPaths);
                    OnNotResponded(context);
                }
            }

            return(handled);
        }
Ejemplo n.º 25
0
        public bool TryRespond(IHttpContext context, bool endResponse = false)
        {
            try
            {
                if (Etags.CheckEtags(context))
                {
                    return(true);
                }

                if (!IsInitialized)
                {
                    Initialize();
                }

                IRequest  request  = context.Request;
                IResponse response = context.Response;
                Session.Init(context);
                SecureSession.Init(context);

                bool   handled    = false;
                string path       = request.Url.AbsolutePath;
                string commonPath = Path.Combine("/common", path.TruncateFront(1));

                byte[]   content      = new byte[] { };
                string   appName      = ResolveApplicationName(context);
                string[] checkedPaths = new string[] { };
                if (AppContentResponders.ContainsKey(appName))
                {
                    handled = AppContentResponders[appName].TryRespond(context, out checkedPaths);
                }

                if (!handled && !ShouldIgnore(path))
                {
                    bool exists;
                    exists = ServerRoot.FileExists(path, out string absoluteFileSystemPath);
                    if (!exists)
                    {
                        exists = ServerRoot.FileExists(commonPath, out absoluteFileSystemPath);
                    }

                    if (exists)
                    {
                        string ext = Path.GetExtension(absoluteFileSystemPath);
                        if (FileCachesByExtension.ContainsKey(ext))
                        {
                            FileCache cache = FileCachesByExtension[ext];
                            if (ShouldZip(request))
                            {
                                SetGzipContentEncodingHeader(response);
                                content = cache.GetZippedContent(absoluteFileSystemPath);
                            }
                            else
                            {
                                content = cache.GetContent(absoluteFileSystemPath);
                            }
                            handled = true;
                            Etags.SetLastModified(response, request.Url.ToString(), new FileInfo(absoluteFileSystemPath).LastWriteTime);
                        }
                    }

                    if (handled)
                    {
                        SetContentType(response, path);
                        Etags.Set(response, request.Url.ToString(), content);
                        SendResponse(response, content);
                        OnResponded(context);
                    }
                    else
                    {
                        LogContentNotFound(path, appName, checkedPaths);
                        OnNotResponded(context);
                    }
                }

                if (!handled && endResponse)
                {
                    SendResponse(response, "Not Found", 404);
                }
                return(handled);
            }
            catch (Exception ex)
            {
                Logger.AddEntry("An error occurred in {0}.{1}: {2}", ex, this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message);
                OnNotResponded(context);
                return(false);
            }
        }