Exemple #1
0
 /// <summary>
 /// Conecta-se ao AuthServer
 /// </summary>
 public bool ConnectToAuthServer(ClientAuth client)
 {
     AuthServer = client;
     AuthServer.OnDisconnect     += OnAuthServerDisconnected;
     AuthServer.OnPacketReceived += AuthServer_OnPacketReceived;
     return(AuthServer.Connect());
 }
        public bool CreateClient(ClientAuth clientObj)
        {
            bool retFlag = default(bool);

            using (TransactionScope transScope = new TransactionScope())
            {
                try
                {
                    if (CreateClientBasicDetails(clientObj))
                    {
                        if (CreateClientAuthDetails(clientObj))
                        {
                            transScope.Complete();
                            retFlag = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    transScope.Dispose();
                    throw ex;
                }
                finally
                {
                    transScope.Dispose();
                }
            }

            return(retFlag);
        }
        public async Task Auth_ShouldBe_Success()
        {
            InitClient();

            await HandShake_ShouldBe_Success();

            var data = new ClientAuth()
            {
                Username        = Settings.UserName,
                Password        = ByteString.CopyFromUtf8(Settings.Password),
                NetReadTimeout  = 60 * 60 * 1000,
                NetWriteTimeout = 60 * 60 * 1000
            };

            var packet = new Packet()
            {
                Type = PacketType.Clientauthentication,
                Body = data.ToByteString()
            }.ToByteArray();

            await _client.WritePacketAsync(packet);

            var p = await _client.ReadPacketAsync();

            p.ValidateAck();
        }
Exemple #4
0
        private void HandleTcpClientAccepted(IAsyncResult ar)
        {
            if (IsRunning)
            {
                var _Client = _server.EndAcceptTcpClient(ar);
                if (ClientCount > 10)
                {
                    //TODO
                    _Client.Close();
                    return;
                }


                var _Session = new ClientAuth(_Client, new AuthPacketInfo()
                {
                });

                lock (m_Clients)
                {
                    ClientCount++;
                    m_Clients.Add(_Session.Info.UID, _Session);
                    OnClientConnected(_Session);
                }

                var _Stream = _Session.NetworkStream;

                _Stream.BeginRead(MsgBufferRead, 0, MsgBufferRead.Length, HandleDataReceived, _Session);

                _server.BeginAcceptTcpClient(HandleTcpClientAccepted, ar.AsyncState);
            }
        }
 /// <summary>
 /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
 /// /> and <see cref="ignoreCase" />
 /// </summary>
 /// <param name="sourceValue">the value to convert into an instance of <see cref="ClientAuth" />.</param>
 /// <returns>
 /// an instance of <see cref="ClientAuth" />, or <c>null</c> if there is no suitable conversion.
 /// </returns>
 public static object ConvertFrom(dynamic sourceValue)
 {
     if (null == sourceValue)
     {
         return(null);
     }
     try
     {
         ClientAuth.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());
     }
     catch
     {
         // Unable to use JSON pattern
     }
     try
     {
         return(new ClientAuth
         {
             Name = sourceValue.Name,
             CaChain = sourceValue.CaChain,
             Status = sourceValue.Status,
         });
     }
     catch
     {
     }
     return(null);
 }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldFindPolicyOverrides()
        public virtual void ShouldFindPolicyOverrides()
        {
            // given
            IDictionary <string, string> @params = stringMap();

            string          policyName   = "XYZ";
            SslPolicyConfig policyConfig = new SslPolicyConfig(policyName);

            File homeDir = TestDirectory.directory("home");

            @params[GraphDatabaseSettings.neo4j_home.name()] = homeDir.AbsolutePath;
            @params[policyConfig.BaseDirectory.name()]       = "certificates/XYZ";

            File privateKey        = TestDirectory.directory("/path/to/my.key");
            File publicCertificate = TestDirectory.directory("/path/to/my.crt");
            File trustedDir        = TestDirectory.directory("/some/other/path/to/trusted");
            File revokedDir        = TestDirectory.directory("/some/other/path/to/revoked");

            @params[policyConfig.PrivateKey.name()]        = privateKey.AbsolutePath;
            @params[policyConfig.PublicCertificate.name()] = publicCertificate.AbsolutePath;
            @params[policyConfig.TrustedDir.name()]        = trustedDir.AbsolutePath;
            @params[policyConfig.RevokedDir.name()]        = revokedDir.AbsolutePath;

            @params[policyConfig.AllowKeyGeneration.name()] = "true";
            @params[policyConfig.TrustAll.name()]           = "true";

            @params[policyConfig.PrivateKeyPassword.name()] = "setecastronomy";
            @params[policyConfig.TlsVersions.name()]        = "TLSv1.1,TLSv1.2";
            @params[policyConfig.Ciphers.name()]            = "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384";
            @params[policyConfig.ClientAuth.name()]         = "optional";

            Config config = Config.defaults(@params);

            // when
            File privateKeyFromConfig        = config.Get(policyConfig.PrivateKey);
            File publicCertificateFromConfig = config.Get(policyConfig.PublicCertificate);
            File trustedDirFromConfig        = config.Get(policyConfig.TrustedDir);
            File revokedDirFromConfig        = config.Get(policyConfig.RevokedDir);

            string         privateKeyPassword = config.Get(policyConfig.PrivateKeyPassword);
            bool           allowKeyGeneration = config.Get(policyConfig.AllowKeyGeneration);
            bool           trustAll           = config.Get(policyConfig.TrustAll);
            IList <string> tlsVersions        = config.Get(policyConfig.TlsVersions);
            IList <string> ciphers            = config.Get(policyConfig.Ciphers);
            ClientAuth     clientAuth         = config.Get(policyConfig.ClientAuth);

            // then
            assertEquals(privateKey, privateKeyFromConfig);
            assertEquals(publicCertificate, publicCertificateFromConfig);
            assertEquals(trustedDir, trustedDirFromConfig);
            assertEquals(revokedDir, revokedDirFromConfig);

            assertTrue(allowKeyGeneration);
            assertTrue(trustAll);
            assertEquals("setecastronomy", privateKeyPassword);
            assertEquals(asList("TLSv1.1", "TLSv1.2"), tlsVersions);
            assertEquals(asList("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"), ciphers);
            assertEquals(ClientAuth.OPTIONAL, clientAuth);
        }
Exemple #7
0
        public IPacketWriter HandleAuthChallenge()
        {
            ClientAuth.Clear();
            PacketWriter writer = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_AUTH_CHALLENGE], "SMSG_AUTH_CHALLENGE");

            writer.WriteInt32(0);
            return(writer);
        }
        public static ClientVM ConvertClientToClientVM(ClientAuth clientObj)
        {
            ClientVM clientVMObj = new ClientVM();

            Mapper.CreateMap <ClientAuth, ClientVM>();
            clientVMObj = Mapper.Map <ClientVM>(clientObj);
            return(clientVMObj);
        }
Exemple #9
0
        public void HandleRealmList(Socket socket)
        {
            while (socket.Connected)
            {
                System.Threading.Thread.Sleep(1);
                if (socket.Available > 0)
                {
                    byte[] buffer = new byte[socket.Available];
                    socket.Receive(buffer, buffer.Length, SocketFlags.None);

                    PacketReader packet = new PacketReader(buffer, false);
                    PacketWriter writer = new PacketWriter();

                    var op = (RealmlistOpcodes)packet.ReadByte();
                    switch (op)
                    {
                    case RealmlistOpcodes.LOGON_CHALLENGE:
                        writer.WriteBytes(ClientAuth.LogonChallenge(packet));
                        break;

                    case RealmlistOpcodes.RECONNECT_CHALLENGE:
                        writer.WriteBytes(ClientAuth.Reconnect_Challenge);
                        break;

                    case RealmlistOpcodes.LOGON_PROOF:
                    case RealmlistOpcodes.RECONNECT_PROOF:
                        writer.WriteUInt8((byte)RealmlistOpcodes.RECONNECT_PROOF);
                        writer.WriteUInt8(0);
                        break;

                    case RealmlistOpcodes.REALMLIST_REQUEST:
                        //Send Realm List
                        byte[] realmName = Encoding.UTF8.GetBytes(Sandbox.Instance.RealmName);
                        byte[] redirect  = Encoding.UTF8.GetBytes("127.0.0.1:" + Sandbox.Instance.RedirectPort);

                        writer.WriteUInt8(0x10);
                        writer.WriteUInt16((ushort)(16 + realmName.Length + redirect.Length)); //Packet length
                        writer.WriteUInt32(0);
                        writer.WriteUInt8(1);                                                  //Realm count
                        writer.WriteUInt32(1);                                                 //Icon
                        writer.WriteUInt8(0);                                                  //Colour
                        writer.WriteBytes(realmName);
                        writer.WriteUInt8(0);
                        writer.WriteBytes(redirect);
                        writer.WriteUInt8(0);
                        writer.WriteUInt32(0);
                        break;
                    }

                    if (writer.BaseStream.Length > 0)
                    {
                        socket.SendData(writer, op.ToString());
                    }
                }
            }

            socket.Close();
        }
Exemple #10
0
        public int AddClientAuthDetails(ClientAuth clientObj, string insertQuery)
        {
            try
            {
                int ClientAuthID = default(int);

                using (SqlConnection con = new SqlConnection(ConnectionStr))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand(insertQuery, con);

                    List <SqlParameter> sParamList = new List <SqlParameter>()
                    {
                        new SqlParameter()
                        {
                            ParameterName = "@ClientId", SqlDbType = SqlDbType.Int, Value = clientObj.ClientId
                        },
                        new SqlParameter()
                        {
                            ParameterName = "@ClientUserName", SqlDbType = SqlDbType.VarChar, Value = clientObj.UserName, Size = 300
                        },
                        new SqlParameter()
                        {
                            ParameterName = "@ClientPassword", SqlDbType = SqlDbType.VarChar, Value = clientObj.Password, Size = 300
                        },
                        new SqlParameter()
                        {
                            ParameterName = "@IsActive", SqlDbType = SqlDbType.Bit, Value = clientObj.IsActive
                        },
                        new SqlParameter()
                        {
                            ParameterName = "@DateOfRegistration", SqlDbType = SqlDbType.DateTime, Value = clientObj.CreatedDate
                        },
                        // Adding 1 year for expiry
                        new SqlParameter()
                        {
                            ParameterName = "@DateOfExpire", SqlDbType = SqlDbType.DateTime, Value = DBHelper.DefaultForDBNullValues(clientObj.CreatedDate.AddYears(1))
                        },
                        // Last login time must be null
                        new SqlParameter()
                        {
                            ParameterName = "@LastLoginTime", SqlDbType = SqlDbType.DateTime, Value = DBNull.Value
                        }
                    };

                    cmd.Parameters.AddRange(sParamList.ToArray());

                    ClientAuthID = (int)cmd.ExecuteScalar();
                }

                return(ClientAuthID);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #11
0
        protected override void OnAuthServerPacketReceive(ClientAuth client, AuthPacketInfo packet)
        {
            switch (packet.ID)
            {
            case AuthPacketEnum.SERVER_KEEPALIVE:
                break;

            case AuthPacketEnum.SERVER_CONNECT:
                break;

            case AuthPacketEnum.SERVER_COMMAND:
                break;

            case AuthPacketEnum.SERVER_UPDATE:
                break;

            case AuthPacketEnum.RECEIVES_USER_UID:
                break;

            case AuthPacketEnum.DISCONNECT_PLAYER_ALL_ON_SERVERS:
                break;

            case AuthPacketEnum.SERVER_RELEASE_CHAT:
                break;

            case AuthPacketEnum.SERVER_RELEASE_NOTICE_GM:
                break;

            case AuthPacketEnum.SERVER_RELEASE_TICKET:
                break;

            case AuthPacketEnum.SERVER_RELEASE_BOXRANDOM:
                break;

            case AuthPacketEnum.SERVER_RELEASE_NOTICE:
                break;

            case AuthPacketEnum.CHECK_PLAYER_DUPLICATE:
                break;

            case AuthPacketEnum.RESULT_PLAYER_DUPLICATE:
                break;

            case AuthPacketEnum.SEND_DISCONNECT_PLAYER:
                break;

            case AuthPacketEnum.LOGIN_RESULT:
                break;

            case AuthPacketEnum.PLAYER_LOGIN_RESULT:
                break;

            default:
                break;
            }
        }
Exemple #12
0
        public static bool CompareHash(string Password, ClientAuth Client)
        {
            string hash = Convert.ToBase64String(KeyDerivation.Pbkdf2(
                                                     password: Password,
                                                     salt: Convert.FromBase64String(Client.SALT),
                                                     prf: KeyDerivationPrf.HMACSHA1,
                                                     iterationCount: 10000,
                                                     numBytesRequested: 256 / 8));

            return(hash == Client.HASH);
        }
Exemple #13
0
        private void DoConnect()
        {
            _tcpClient            = new TcpClient(Address, Port);
            _channelNetworkStream = _tcpClient.GetStream();
            var p = Packet.Parser.ParseFrom(ReadNextPacket());

            if (p != null)
            {
                if (p.Version != 1)
                {
                    throw new CanalClientException("unsupported version at this client.");
                }

                if (p.Type != PacketType.Handshake)
                {
                    throw new CanalClientException("expect handshake but found other type.");
                }

                var handshake = Handshake.Parser.ParseFrom(p.Body);
                _supportedCompressions.Add(handshake.SupportedCompressions);

                var ca = new ClientAuth()
                {
                    Username        = Username ?? "",
                    Password        = ByteString.CopyFromUtf8(Password ?? ""),
                    NetReadTimeout  = IdleTimeout,
                    NetWriteTimeout = IdleTimeout
                };

                var packArray = new Packet()
                {
                    Type = PacketType.Clientauthentication,
                    Body = ca.ToByteString()
                }.ToByteArray();

                WriteWithHeader(packArray);

                var packet = Packet.Parser.ParseFrom(ReadNextPacket());
                if (packet.Type != PacketType.Ack)
                {
                    throw new CanalClientException("unexpected packet type when ack is expected");
                }

                var ackBody = Com.Alibaba.Otter.Canal.Protocol.Ack.Parser.ParseFrom(p.Body);
                if (ackBody.ErrorCode > 0)
                {
                    throw new CanalClientException("something goes wrong when doing authentication:" +
                                                   ackBody.ErrorMessage);
                }

                _connected = _tcpClient.Connected;
                _logger.LogDebug($"Canal connect success. IP: {Address}, Port: {Port}");
            }
        }
Exemple #14
0
 public void Close(ClientAuth pSession, bool pRemove = true)
 {
     if (pSession != null)
     {
         pSession.Close();
         if (pRemove)
         {
             m_Clients.Remove(pSession.Info.UID);
         }
         OnClientDisconnected(pSession);
     }
 }
        public bool CreateClientAuthDetails(ClientAuth clientAuthObj)
        {
            bool retFlag = default(bool);

            StringBuilder insertQuery = new StringBuilder("INSERT INTO [dbo].[ClientAuthentication] (ClientId, ClientUserName, ClientPassword, IsActive, DateOfRegistration, DateOfExpire, LastLoginTime) ");

            insertQuery.Append("VALUES (@ClientId, @ClientUserName, @ClientPassword, @IsActive, @DateOfRegistration, @DateOfExpire, @LastLoginTime);SELECT CAST(scope_identity() AS int);");

            retFlag = (ClientDA.AddClientAuthDetails(clientAuthObj, insertQuery.ToString()) > 0) ? true : false;

            return(retFlag);
        }
Exemple #16
0
 public SslPolicy(PrivateKey privateKey, X509Certificate[] keyCertChain, IList <string> tlsVersions, IList <string> ciphers, ClientAuth clientAuth, TrustManagerFactory trustManagerFactory, SslProvider sslProvider, bool verifyHostname, LogProvider logProvider)
 {
     this._privateKey          = privateKey;
     this._keyCertChain        = keyCertChain;
     this._tlsVersions         = tlsVersions == null ? null : tlsVersions.ToArray();
     this._ciphers             = ciphers;
     this._clientAuth          = clientAuth;
     this._trustManagerFactory = trustManagerFactory;
     this._sslProvider         = sslProvider;
     this._verifyHostname      = verifyHostname;
     this._log = logProvider.GetLog(typeof(SslPolicy));
 }
Exemple #17
0
        /// <summary>
        /// Connect to canal server.
        /// </summary>
        /// <returns></returns>
        public async Task ConnectAsync()
        {
            ValidateState(ConnectionState.Closed, nameof(ConnectAsync));

            _client = SocketFactory.CreateClient <TcpClient>(_options.Host, _options.Port);
            var p = await _client.ReadPacketAsync();

            // _client.Socket.ReceiveTimeout = _options.SoTimeout;
            //Handshake
            ValidatePackageType(p, PacketType.Handshake, 1);
            var handshake = Handshake.Parser.ParseFrom(p.Body);
            var seed      = handshake.Seeds;

            var newPassword = _options.Password;

            if (_options.Password != null)
            {
                // encode password
                newPassword = SecurityUtil.ByteArrayToHexString(SecurityUtil.Scramble411(Encoding.UTF8.GetBytes(_options.Password), seed.ToByteArray()));
            }

            //Auth
            var data = new ClientAuth()
            {
                Username        = _options.UserName,
                Password        = ByteString.CopyFromUtf8(newPassword ?? ""),
                NetReadTimeout  = _options.IdleTimeout,
                NetWriteTimeout = _options.IdleTimeout
            };

            var packet = new Packet()
            {
                Type = PacketType.Clientauthentication,
                Body = data.ToByteString()
            }.ToByteArray();

            //Send auth data
            await _client.WritePacketAsync(packet);

            p = await _client.ReadPacketAsync();

            //Validate auth ack packet
            p.ValidateAck();

            //Set state
            SetConnectionState(ConnectionState.Connected);

            _logger.LogInformation($"Connect to canal server [{_options.Host}:{_options.Port}] success.");
        }
        public ClientAuth GetClientDetails(int clientId)
        {
            ClientAuth clientObj = new ClientAuth();

            StringBuilder sb = new StringBuilder("SELECT CL.*,CLAU.* FROM CLIENT CL JOIN CLIENTAUTHENTICATION CLAU ON CL.CLIENTID=CLAU.CLIENTID WHERE CL.CLIENTID = @ClientId");

            if (ClientDA.GetClientDetails(clientId, sb.ToString(), clientObj))
            {
                return(clientObj);
            }
            else
            {
                return(null);
            }
        }
Exemple #19
0
        private io.netty.handler.ssl.ClientAuth ForNetty(ClientAuth clientAuth)
        {
            switch (clientAuth)
            {
            case Org.Neo4j.Ssl.ClientAuth.None:
                return(io.netty.handler.ssl.ClientAuth.NONE);

            case Org.Neo4j.Ssl.ClientAuth.Optional:
                return(io.netty.handler.ssl.ClientAuth.OPTIONAL);

            case Org.Neo4j.Ssl.ClientAuth.Require:
                return(io.netty.handler.ssl.ClientAuth.REQUIRE);

            default:
                throw new System.ArgumentException("Cannot translate to netty equivalent: " + clientAuth);
            }
        }
Exemple #20
0
        public bool GetClientDetails(int clientId, string selectQuery, ClientAuth obj)
        {
            if (obj == null)
            {
                obj = new ClientAuth();
            }
            try
            {
                using (SqlConnection con = new SqlConnection(ConnectionStr))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand(selectQuery, con);
                    cmd.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@ClientId", SqlDbType = SqlDbType.Int, Value = clientId
                    });

                    SqlDataReader dr = cmd.ExecuteReader();

                    if (dr.HasRows)
                    {
                        while (dr.Read())
                        {
                            obj.ClientId        = Convert.ToInt32(dr["ClientId"]);
                            obj.FirstName       = Convert.ToString(dr["ClientFirstName"]);
                            obj.LastName        = Convert.ToString(dr["ClientLastName"]);
                            obj.BusinessName    = Convert.ToString(dr["BusinessName"]);
                            obj.PrimaryAddress  = Convert.ToString(dr["ClientPrimaryAddress"]);
                            obj.PrimaryPhoneNum = Convert.ToInt64(dr["PrimaryContactNumber"]);
                            obj.AltPhoneNum     = Convert.ToInt64(dr["AlternateContactNumber"]);
                            obj.PrimaryMail     = Convert.ToString(dr["PrimaryMailId"]);
                            obj.FacebookId      = Convert.ToString(dr["FacebookId"]);
                            obj.CreatedDate     = Convert.ToDateTime(dr["CreatedDate"]);
                            obj.IsActive        = Convert.ToBoolean(dr["IsActive"]);
                            obj.UserName        = Convert.ToString(dr["ClientUserName"]);
                        }
                    }

                    return(true);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldFindPolicyDefaults()
        public virtual void ShouldFindPolicyDefaults()
        {
            // given
            IDictionary <string, string> @params = stringMap();

            string          policyName   = "XYZ";
            SslPolicyConfig policyConfig = new SslPolicyConfig(policyName);

            File homeDir = TestDirectory.directory("home");

            @params[GraphDatabaseSettings.neo4j_home.name()] = homeDir.AbsolutePath;
            @params[policyConfig.BaseDirectory.name()]       = "certificates/XYZ";
            Config config = Config.defaults(@params);

            // derived defaults
            File privateKey        = new File(homeDir, "certificates/XYZ/private.key");
            File publicCertificate = new File(homeDir, "certificates/XYZ/public.crt");
            File trustedDir        = new File(homeDir, "certificates/XYZ/trusted");
            File revokedDir        = new File(homeDir, "certificates/XYZ/revoked");

            // when
            File           privateKeyFromConfig        = config.Get(policyConfig.PrivateKey);
            File           publicCertificateFromConfig = config.Get(policyConfig.PublicCertificate);
            File           trustedDirFromConfig        = config.Get(policyConfig.TrustedDir);
            File           revokedDirFromConfig        = config.Get(policyConfig.RevokedDir);
            string         privateKeyPassword          = config.Get(policyConfig.PrivateKeyPassword);
            bool           allowKeyGeneration          = config.Get(policyConfig.AllowKeyGeneration);
            bool           trustAll    = config.Get(policyConfig.TrustAll);
            IList <string> tlsVersions = config.Get(policyConfig.TlsVersions);
            IList <string> ciphers     = config.Get(policyConfig.Ciphers);
            ClientAuth     clientAuth  = config.Get(policyConfig.ClientAuth);

            // then
            assertEquals(privateKey, privateKeyFromConfig);
            assertEquals(publicCertificate, publicCertificateFromConfig);
            assertEquals(trustedDir, trustedDirFromConfig);
            assertEquals(revokedDir, revokedDirFromConfig);
            assertNull(privateKeyPassword);
            assertFalse(allowKeyGeneration);
            assertFalse(trustAll);
            assertEquals(singletonList("TLSv1.2"), tlsVersions);
            assertNull(ciphers);
            assertEquals(ClientAuth.REQUIRE, clientAuth);
        }
Exemple #22
0
        private void Load(Config config, Log log)
        {
            ISet <string> policyNames = config.IdentifiersFromGroup(typeof(SslPolicyConfig));

            foreach (string policyName in policyNames)
            {
                if (policyName.Equals(LEGACY_POLICY_NAME))
                {
                    // the legacy policy name is reserved for the legacy policy which derives its configuration from legacy settings
                    throw new System.ArgumentException("Legacy policy cannot be configured. Please migrate to new SSL policy system.");
                }

                SslPolicyConfig policyConfig           = new SslPolicyConfig(policyName);
                File            baseDirectory          = config.Get(policyConfig.BaseDirectory);
                File            trustedCertificatesDir = config.Get(policyConfig.TrustedDir);
                File            revokedCertificatesDir = config.Get(policyConfig.RevokedDir);

                if (!baseDirectory.exists())
                {
                    throw new System.ArgumentException(format("Base directory '%s' for SSL policy with name '%s' does not exist.", baseDirectory, policyName));
                }

                bool allowKeyGeneration = config.Get(policyConfig.AllowKeyGeneration);

                File       privateKeyFile     = config.Get(policyConfig.PrivateKey);
                string     privateKeyPassword = config.Get(policyConfig.PrivateKeyPassword);
                PrivateKey privateKey;

                X509Certificate[] keyCertChain;
                File keyCertChainFile = config.Get(policyConfig.PublicCertificate);

                if (allowKeyGeneration && !privateKeyFile.exists() && !keyCertChainFile.exists())
                {
                    GeneratePrivateKeyAndCertificate(log, policyName, keyCertChainFile, privateKeyFile, trustedCertificatesDir, revokedCertificatesDir);
                }

                privateKey   = LoadPrivateKey(privateKeyFile, privateKeyPassword);
                keyCertChain = LoadCertificateChain(keyCertChainFile);

                ClientAuth          clientAuth     = config.Get(policyConfig.ClientAuth);
                bool                trustAll       = config.Get(policyConfig.TrustAll);
                bool                verifyHostname = config.Get(policyConfig.VerifyHostname);
                TrustManagerFactory trustManagerFactory;

                ICollection <X509CRL> crls = GetCRLs(revokedCertificatesDir);

                try
                {
                    trustManagerFactory = CreateTrustManagerFactory(trustAll, trustedCertificatesDir, crls, clientAuth);
                }
                catch (Exception e)
                {
                    throw new Exception("Failed to create trust manager based on: " + trustedCertificatesDir, e);
                }

                IList <string> tlsVersions = config.Get(policyConfig.TlsVersions);
                IList <string> ciphers     = config.Get(policyConfig.Ciphers);

                SslPolicy sslPolicy = new SslPolicy(privateKey, keyCertChain, tlsVersions, ciphers, clientAuth, trustManagerFactory, _sslProvider, verifyHostname, _logProvider);
                log.Info(format("Loaded SSL policy '%s' = %s", policyName, sslPolicy));
                _policies[policyName] = sslPolicy;
            }
        }
Exemple #23
0
 private void OnClientDisconnected(ClientAuth session)
 {
     ClientCount--;
     ClientDisconnected?.Invoke(session);
 }
Exemple #24
0
 protected void ClientRequestPacket(ClientAuth session, AuthPacketInfo packet)
 {
     OnPacketReceived?.Invoke(session, packet);
 }
Exemple #25
0
        // Creates a new thread per connection from this function
        // This function is the actual communication with the specific connection
        private void StartSlave()
        {
            CryptoTool crypto = new CryptoTool();
            //---Slave master list creation and assignment---\\
            Slave client = new Slave();

            client.AssignedKeys  = false;
            client.ConnectionKey = ClientConfig.connectionKey;
            if (clientConnection.Connected)
            {
                client.OnlineStatus = OnlineInfo.Online; // Assign online
            }
            else
            {
                client.OnlineStatus = OnlineInfo.Offline; // Assign offline
            }
            client.Authorized = false;

            //---Local variable creation---\\
            bool   Authing          = true;
            bool   Authed           = false;
            bool   KeepAlive        = true;
            int    AuthStep         = 1;
            int    clientListNumber = 0;                           // make it 0 so we can handle things better
            int    bytesRead        = 0;                           // Byte count from stream read
            string dataReceived;                                   // string of byte data recieved

            byte[]        dataSent;                                // Byte data to send to client - probly wont be used
            NetworkStream nwStream = clientConnection.GetStream(); // Start connection stream

            byte[] buffer = new byte[clientConnection.ReceiveBufferSize];
            // SslStream slStream = new SslStream(nwStream); // Iniate stream for future use

            // Mess with secure encrypted stream stuff later
            // SslStream sStream = new SslStream(nwStream);

            try
            {
                while (KeepAlive) // keep looping while we tell it to
                {
                    if (!Authed & Authing)
                    {
                        //---read incoming stream---\\
                        bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize);
                        //---convert the data received into a string---\\
                        dataReceived = crypto.DefaultDecrypt(Encoding.ASCII.GetString(buffer, 0, bytesRead)); // Decrypt data to string
                        WorkQueue.AddBytes(buffer.Length);
                        if (ClientConfig.Debug)
                        {
                            Logger.SaveDebug("==================START OF NEW CLIENT VERIFICATION================");
                        }
                        if (ClientConfig.Debug)
                        {
                            Logger.SaveDebug($"NEW CLIENT! | ID: {dataReceived} - AUTH SEQUENCE STARTED!");
                        }
                        Debug.WriteLine("Step 0 - Received : " + dataReceived);
                        client.ClientID = dataReceived;
                        ClientHandler.AddClient(client);
                        client.SlaveListAssignment = ClientHandler.AssignClientListCount(client.ClientID);
                        clientListNumber           = client.SlaveListAssignment;
                        if (clientListNumber == 0)
                        {
                            // Issue handling the list number assignment code
                            //TODO: What/how do we handle this?
                        }
                        //---Sending acknowledge---\\
                        dataSent = null;
                        dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt("VALID")); // encrypt to send
                        WorkQueue.AddBytes(dataSent.Length);
                        nwStream.Write(dataSent, 0, dataSent.Length);
                        Debug.WriteLine("Telling client step 0 valid...");
                        dataSent  = null;
                        bytesRead = 0;


                        //---Auth sequence loop handling until pass or failure---\\
                        while (Authing & AuthStep != 0)
                        {
                            ClientAuth auth = new ClientAuth();
                            if (String.IsNullOrWhiteSpace(ClientHandler.Slaves[clientListNumber].IP))
                            {
                                ClientHandler.Slaves[clientListNumber].IP = auth.GetIP(dataReceived);
                            }

                            //using (AuthSteps step = new AuthSteps())
                            //{

                            switch (AuthStep)
                            {
                            case 1:
                                // Read response
                                bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize);
                                WorkQueue.AddBytes(buffer.Length);
                                dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                                Debug.WriteLine("Step 1 - Received : " + dataReceived);
                                if (ClientConfig.Debug)
                                {
                                    Logger.SaveDebug($"Step 1 started for client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                }
                                if (auth.CheckAuth(crypto.DefaultDecrypt(dataReceived), 1))
                                {
                                    AuthStep = 2;
                                    //---sending back valid step 1---\\
                                    dataSent = null;
                                    dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt("VALID"));
                                    nwStream.Write(dataSent, 0, dataSent.Length);
                                    WorkQueue.AddBytes(dataSent.Length);
                                    Debug.WriteLine("Telling client step 1 valid...");
                                    dataSent = null;
                                    ClientHandler.Slaves[clientListNumber].AuthStatus.Step1Done = true;
                                    if (ClientConfig.Debug)
                                    {
                                        Logger.SaveDebug($"Step 1 verified | client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                    }
                                }
                                else
                                {
                                    Logger.SaveDebug($"Step 1 FAILED! for client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                    AuthStep = 0;         // Deny
                                    Authing  = false;
                                    Authed   = false;
                                    clientConnection.Close();
                                    if (ClientConfig.Debug)
                                    {
                                        Logger.SaveDebug($"Client disconnected and slave list updated for client!");
                                    }
                                    ClientHandler.Slaves[clientListNumber].Authorized   = false;
                                    ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.BadLogin;
                                }
                                break;

                            case 2:
                                // Read response
                                bytesRead    = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize);
                                dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                                WorkQueue.AddBytes(buffer.Length);
                                Debug.WriteLine("Step 2 - Received : " + dataReceived);
                                if (ClientConfig.Debug)
                                {
                                    Logger.SaveDebug($"Step 2 started for client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                }

                                // Process response
                                if (auth.CheckAuth(crypto.DefaultDecrypt(dataReceived), 2))
                                {
                                    dataSent = null;
                                    AuthStep = 3;
                                    dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt("VALID"));
                                    nwStream.Write(dataSent, 0, dataSent.Length);
                                    WorkQueue.AddBytes(dataSent.Length);
                                    Debug.WriteLine("Telling client step 2 valid...");
                                    dataSent = null;
                                    ClientHandler.Slaves[clientListNumber].AuthStatus.Step2Done = true;
                                    if (ClientConfig.Debug)
                                    {
                                        Logger.SaveDebug($"Step 2 VALID for client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                    }
                                }
                                else
                                {
                                    AuthStep = 0;         // Deny
                                    Authing  = false;
                                    Authed   = false;
                                    clientConnection.Close();
                                    ClientHandler.Slaves[clientListNumber].Authorized   = false;
                                    ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.BadLogin;
                                    if (ClientConfig.Debug)
                                    {
                                        Logger.SaveDebug($"Step 2 FAILED | closed connection and updated slave list.");
                                    }
                                }
                                break;

                            case 3:
                                // Read response
                                //bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize);
                                //dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                                //Debug.WriteLine("Step 3 - Received : " + dataReceived);

                                if (ClientConfig.Debug)
                                {
                                    Logger.SaveDebug($"Step 3 started for client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                }

                                // Process response
                                if (ClientConfig.AssignNewKeys)
                                {
                                    dataSent = null;
                                    EncryptionKeys newKeys = ClientConfig.EncryptionKeys[Rando.GetNumber(ClientConfig.EncryptionKeys.Count)];
                                    ClientHandler.Slaves[clientListNumber].key = newKeys;
                                    dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt($"KEYS:{newKeys.Password}:{newKeys.Salt}:{newKeys.XorKey}:{newKeys.VlKey}"));
                                    nwStream.Write(dataSent, 0, dataSent.Length);
                                    WorkQueue.AddBytes(dataSent.Length);
                                    ClientHandler.Slaves[clientListNumber].AuthStatus.Step3Done = true;
                                    ClientHandler.Slaves[clientListNumber].Authorized           = true;
                                    if (ClientConfig.Debug)
                                    {
                                        Logger.SaveDebug($"Step 3 COMPLETED for client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                    }
                                    bytesRead    = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize);
                                    dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                                    WorkQueue.AddBytes(buffer.Length);
                                    if (dataReceived.Contains("UPDATED"))
                                    {
                                        Authed  = true;
                                        Authing = false;
                                    }
                                    else
                                    {
                                        // Bad sequence sent, close connection
                                        AuthStep = 0;         // Deny
                                        Authing  = false;
                                        Authed   = false;
                                        clientConnection.Close();
                                        ClientHandler.Slaves[clientListNumber].Authorized   = false;
                                        ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.Unknown;
                                        if (ClientConfig.Debug)
                                        {
                                            Logger.SaveDebug($"Step 3 FAILED | Connection closed and list updated | ERROR UPDATING KEYS!");
                                        }
                                    }
                                }
                                else
                                {
                                    // Bad sequence sent, close connection
                                    AuthStep = 0;         // Deny
                                    Authing  = false;
                                    Authed   = false;
                                    clientConnection.Close();
                                    ClientHandler.Slaves[clientListNumber].Authorized   = false;
                                    ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.VMDenied;
                                    if (ClientConfig.Debug)
                                    {
                                        Logger.SaveDebug($"Step 3 FAILED | Connection closed and list updated");
                                    }
                                }
                                break;

                            default:
                                // Bad sequence sent, close connection
                                AuthStep = 0;         // Deny
                                Authing  = false;
                                Authed   = false;
                                clientConnection.Close();
                                ClientHandler.Slaves[clientListNumber].Authorized   = false;
                                ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.Error;
                                if (ClientConfig.Debug)
                                {
                                    Logger.SaveDebug($"Default auth switch hit, ERROR occured!");
                                }
                                break;
                            }

                            //}
                        } // Authing loop

                        Debug.WriteLine($"Auth Status processed: {Authed} | Auth sequence processing is complete");
                    }
                    else if (Authed & !Authing) // Process this after client has been authorized
                    {
                        // read response
                        //bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize);
                        //dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                        // Send response
                        //dataSent = null;
                        //dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt("VALID"));
                        //nwStream.Write(dataSent, 0, dataSent.Length);
                        for (var x = 0; x < WorkQueue.JobQueue.Count; x++)
                        {
                            if (WorkQueue.JobQueue[x] != null)                                                                                       // Validate we haven't grabbed a junk list item
                            {
                                if (WorkQueue.JobQueue[x].ClientID == ClientHandler.Slaves[clientListNumber].ClientID & !WorkQueue.JobQueue[x].Sent) // Client has work in queue that isn't sent yet
                                {                                                                                                                    // Pending work, let's send it
                                    switch (WorkQueue.JobQueue[x].WorkType)
                                    {
                                    case WorkType.Kill:
                                    default:
                                        if (ClientConfig.Debug)
                                        {
                                            Logger.SaveDebug($"JobQueue item {x} could not be handled for client {WorkQueue.JobQueue[x].ClientID}({ClientHandler.Slaves[clientListNumber].ClientID})");
                                        }
                                        Debug.WriteLine($"JobQueue item {x} could not be handled for client {WorkQueue.JobQueue[x].ClientID}({ClientHandler.Slaves[clientListNumber].ClientID})");
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        // Unknown not authed or not failed to auth either
                        KeepAlive = false;
                    }
                }// end of keepalive loop

                ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.Offline;
                Debug.WriteLine("KEEP ALIVE OFF AND SLAVE THREAD ENDING!");
                Logger.SaveDebug("KEEP ALIVE OFF AND SLAVE THREAD ENDING!");
            }
            catch (Exception ex)
            {
                ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.Offline;
                Debug.WriteLine("ERROR! >> " + ex);
            }
        }
Exemple #26
0
 protected abstract void OnAuthServerPacketReceive(ClientAuth client, AuthPacketInfo packet);
Exemple #27
0
 /// <summary>
 /// É Disparado quando um packet é recebido do AuthServer
 /// </summary>
 private void AuthServer_OnPacketReceived(ClientAuth authClient, AuthPacketInfo packet)
 {
     OnAuthServerPacketReceive(authClient, packet);
 }
Exemple #28
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private javax.net.ssl.TrustManagerFactory createTrustManagerFactory(boolean trustAll, java.io.File trustedCertificatesDir, java.util.Collection<java.security.cert.X509CRL> crls, org.neo4j.ssl.ClientAuth clientAuth) throws Exception
        private TrustManagerFactory CreateTrustManagerFactory(bool trustAll, File trustedCertificatesDir, ICollection <X509CRL> crls, ClientAuth clientAuth)
        {
            if (trustAll)
            {
                return(InsecureTrustManagerFactory.INSTANCE);
            }

            KeyStore trustStore = KeyStore.getInstance(KeyStore.DefaultType);

            trustStore.load(null, null);

            File[] trustedCertFiles = trustedCertificatesDir.listFiles();

            if (trustedCertFiles == null)
            {
                throw new Exception(format("Could not find or list files in trusted directory: %s", trustedCertificatesDir));
            }
            else if (clientAuth == ClientAuth.REQUIRE && trustedCertFiles.Length == 0)
            {
                throw new Exception(format("Client auth is required but no trust anchors found in: %s", trustedCertificatesDir));
            }

            int i = 0;

            foreach (File trustedCertFile in trustedCertFiles)
            {
                CertificateFactory certificateFactory = CertificateFactory.getInstance(PkiUtils.CERTIFICATE_TYPE);
                using (Stream input = Files.newInputStream(trustedCertFile.toPath()))
                {
                    while (input.available() > 0)
                    {
                        try
                        {
                            X509Certificate cert = ( X509Certificate )certificateFactory.generateCertificate(input);
                            trustStore.setCertificateEntry(Convert.ToString(i++), cert);
                        }
                        catch (Exception e)
                        {
                            throw new CertificateException("Error loading certificate file: " + trustedCertFile, e);
                        }
                    }
                }
            }

            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.DefaultAlgorithm);

            if (crls.Count > 0)
            {
                PKIXBuilderParameters pkixParamsBuilder = new PKIXBuilderParameters(trustStore, new X509CertSelector());
                pkixParamsBuilder.RevocationEnabled = true;

                pkixParamsBuilder.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crls)));

                trustManagerFactory.init(new CertPathTrustManagerParameters(pkixParamsBuilder));
            }
            else
            {
                trustManagerFactory.init(trustStore);
            }

            return(trustManagerFactory);
        }
Exemple #29
0
 private void OnClientConnected(ClientAuth session)
 {
     ClientConnected?.Invoke(session);
 }