Exemplo n.º 1
0
        /// <summary>
        /// Notifies clients of the current authentication state.
        /// </summary>
        /// <param name="action">
        /// The authentication command which reflects the current auth state.
        /// </param>
        public void NotifyAuthenticationStatus(AuthenticationAction action, string username = null, AuthenticationResultObject authenticationResult = null)
        {
            // KF - I edited this function to take two arguments instead of one and then refactored all the code that calls it to pass in an AuthenticationResultObject
            switch (m_waitingForAuth)
            {
            case true:
            {
                m_waitingForAuth = action == AuthenticationAction.Authenticated ? false : true;
            }
            break;

            case false:
            {
                m_waitingForAuth = action == AuthenticationAction.Required;
            }
            break;
            }


            var authResult = new AuthenticationResultObject();

            if (authenticationResult != null)
            {
                authResult = authenticationResult;
            }

            var msg = new AuthenticationMessage(action, authResult, username); // KF - Also added a constructor to AuthenticationMessage);

            PushMessage(msg);
        }
        public void TestPasswordMessageCreateMd5()
        {
            var salt = new byte[] { 0x77, 0x16, 0x3e, 0xe3 };

            var authMessage = new AuthenticationMessage {
                AuthenticationMessageType = AuthenticationMessageType.MD5Password,
                DataBuffer = salt
            };

            var state = PostgresClientState.CreateDefault();

            var connectionString = new PostgresConnectionString(
                PostgresServerInformation.FakeConnectionString);

            var passwordMessage = PasswordMessage
                                  .CreateMd5(authMessage, state, connectionString);

            const string expectedHash = "md583ce447ce89d7e4e943205ff8f82f76a";

            try
            {
                var actualHash = Encoding.ASCII.GetString(
                    passwordMessage.Password, 0,
                    passwordMessage.PasswordLength);
                Assert.AreEqual(0x23, passwordMessage.PasswordLength);
                Assert.AreEqual(expectedHash, actualHash);
            }
            finally
            {
                authMessage.TryDispose();
                passwordMessage.TryDispose();
            }
        }
Exemplo n.º 3
0
        //---msg readers

        private void AuthenticationMsgReader(ReceivedMsg receivedMsg, AuthenticationMessage msg)
        {
            UserAuthenticationState autState;

            if (_authenticationStates.TryGetValue((IScsServerClient)receivedMsg.Sender, out autState))
            {
                autState.Step1_MsgReader(receivedMsg, msg);

                if (autState.State == UserAuthenticationState.AuthenticationState.Success)
                {
                    // Удаляем аутентификатор
                    _authenticationStates.Remove(autState.ScsClient);

                    //Сначала добавляем потом удаляем, чтобы не бьыло ни наносекунды, когда никто не слушает клиента
                    //_msgQueue.AddMessenger(autState.ScsClient);
                    //_msgQueueForAutentification.RemoveMessenger(autState.ScsClient);

                    _authenticatedUsers.Add(autState.ScsClient, autState.User);
                    autState.ScsClient.SendMessage(new AuthenticationSuccesMessage());


                    OnUserLogin?.Invoke(this, new UserEventArgs(autState.User));
                }
            }
            else
            {
                Console.WriteLine(GetType().Name + " :AuthenticationMsgReader error login=" + msg.login);
            }
        }
 public Task <StatusMessage> Authenticate(AuthenticationMessage message)
 {
     message.Id = NextId();
     message.Op = REQUEST_AUTHENTICATION;
     return(SendMessage(new RequestResponse((int)message.Id, message,
                                            success => Status = ConnectionStatus.AUTHENTICATED)));
 }
        public static void Test_Returns_False_For_Session_Who_Stole_Others_Token()
        {
            //arrange
            Mock <ISigningService> signingService = new Mock <ISigningService>();

            signingService.Setup(x => x.isSigned(It.IsAny <byte[]>(), It.IsAny <byte[]>()))
            .Returns(true);

            ElevationManager      elevationManager = new ElevationManager(Mock.Of <ILog>(), signingService.Object);
            IElevatableSession    session          = Mock.Of <IElevatableSession>();
            AuthenticationMessage message          = new AuthenticationMessage(new byte[0]);

            session.UniqueAuthToken = elevationManager.RequestSingleUseToken(session);

            //act:Preform a authentication
            elevationManager.TryAuthenticate(session, message);

            //assert
            Assert.True(elevationManager.isElevated(session));

            //Should fail because this session isn't authorized with this token
            IElevatableSession criminalSession = Mock.Of <IElevatableSession>();

            criminalSession.UniqueAuthToken = session.UniqueAuthToken;

            Assert.False(elevationManager.isElevated(criminalSession));
        }
Exemplo n.º 6
0
        public static void SendAuthenticationRequest(AuthenticationMessage authMessage, UserAuthenticatedCallback callback)
        {
            byte [] data = authMessage.GetMessageBytes();

            authenticatedCallback = callback;

            ChatService.SendData(data);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Authenticate the client on the server.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public void SendAuthentication(string username, string password)
        {
            var authMessage = new AuthenticationMessage()
            {
                Username = username, Password = password
            };

            Send(authMessage);
        }
Exemplo n.º 8
0
    public bool Verify()
    {
        using var bytesPipe = new BytesPipe();
        var target = new AuthenticationMessage(this.CreationTime, this.Hash, null);

        target.Export(bytesPipe.Writer, BytesPool.Shared);

        return(this.Certificate?.Verify(bytesPipe.Reader.GetSequence()) ?? false);
    }
Exemplo n.º 9
0
    void SendAuthentication(NetworkConnection conn)
    {
        Debug.LogWarning("Dev: Started SendAuthentication");
        AuthenticationMessage message = new AuthenticationMessage()
        {
            username = AuthenticationParameters.UserName,
            password = AuthenticationParameters.Password
        };

        conn.Send(CustomMeesageTypes.AuthenticationMsgType, message);
        Debug.LogWarning("Dev: Finished SendAuthentication");
    }
Exemplo n.º 10
0
        public void Callback(AuthenticationMessage authenticationFailureResult)
        {
            this.logger.Info("Authentication result {0}, {1}", authenticationFailureResult.Action, authenticationFailureResult.AuthenticationResult.AuthenticationResult);
            switch (authenticationFailureResult.Action)
            {
            case AuthenticationAction.Denied:
            case AuthenticationAction.Required:
            case AuthenticationAction.InvalidInput:
            {
                // User needs to log in.
                //BringAppToFocus();

                Device.BeginInvokeOnMainThread(async() =>
                    {
                        if (!(app.NavPage.CurrentPage is LoginPage))
                        {
                            await app.NavPage.PushAsync(new LoginPage());
                        }
                    });

                /*m_mainWindow.Dispatcher.InvokeAsync(() =>
                 * {
                 *  ((MainWindowViewModel)m_mainWindow.DataContext).IsUserLoggedIn = false;
                 * });*/
            }
            break;

            case AuthenticationAction.Authenticated:
            case AuthenticationAction.ErrorNoInternet:
            case AuthenticationAction.ErrorUnknown:
            {
                Device.BeginInvokeOnMainThread(async() =>
                    {
                        if (app.NavPage.CurrentPage is LoginPage)
                        {
                            await app.NavPage.PopToRootAsync();
                        }
                    });

                /*m_logger.Info($"The logged in user is {authenticationFailureResult.Username}");
                 *
                 * m_mainWindow.Dispatcher.InvokeAsync(() =>
                 * {
                 *  ((MainWindowViewModel)m_mainWindow.DataContext).LoggedInUser = authenticationFailureResult.Username;
                 *  ((MainWindowViewModel)m_mainWindow.DataContext).IsUserLoggedIn = true;
                 * });
                 *
                 * OnViewChangeRequest(typeof(DashboardView));*/
            }
            break;
            }
        }
Exemplo n.º 11
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            AuthenticationMessage data = new AuthenticationMessage {
                Username    = UsernameTextbox.Text,
                Password    = PasswordTextbox.Password,
                MessageType = MessageType.Authentication
            };

            if (!attemptingLogin)
            {
                CommunicationManager.SendAuthenticationRequest(data, (args) => NavigateToChat(args));
                attemptingLogin = true;
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Sends credentials to the server to attempt authentication.
        /// </summary>
        /// <param name="username">
        /// Username to authorize with.
        /// </param>
        /// <param name="password">
        /// Password to authorize with.
        /// </param>
        public void AttemptAuthentication(string username, SecureString password)
        {
            var msg = new AuthenticationMessage(AuthenticationAction.Requested, username, password);

            var logger = LoggerUtil.GetAppWideLogger();

            try
            {
                PushMessage(msg);
            }
            catch (Exception e)
            {
                LoggerUtil.RecursivelyLogException(logger, e);
            }
        }
Exemplo n.º 13
0
 private void NavigateToChat(AuthenticationMessage authData)
 {
     attemptingLogin = false;
     if (authData.Success)
     {
         Dispatcher.Invoke(DispatcherPriority.Normal,
                           new Action(async() => {
             await AnimateOut();
             (Application.Current.MainWindow as MainWindow).MainFrame.NavigationService.Navigate(new ChatPage(new Models.User()
             {
                 Name = UsernameTextbox.Text
             }));
         }));
     }
 }
Exemplo n.º 14
0
    public static AuthenticationMessage Create(DateTime creationTime, ReadOnlyMemory <byte> hash, OmniDigitalSignature?digitalSignature)
    {
        if (digitalSignature is null)
        {
            return(new AuthenticationMessage(Timestamp.FromDateTime(creationTime), hash, null));
        }

        using var bytesPipe = new BytesPipe();
        var target = new AuthenticationMessage(Timestamp.FromDateTime(creationTime), hash, null);

        target.Export(bytesPipe.Writer, BytesPool.Shared);

        var certificate = OmniDigitalSignature.CreateOmniCertificate(digitalSignature, bytesPipe.Reader.GetSequence());

        return(new AuthenticationMessage(Timestamp.FromDateTime(creationTime), hash, certificate));
    }
        public void Step1_MsgReader(ReceivedMsg receivedMsg, AuthenticationMessage authenticationMessage)
        {
            if (receivedMsg.Sender == ScsClient)
            {
                Console.WriteLine(GetType().Name + " :Get AuthenticationMessage " + authenticationMessage.login);
                if (State == AuthenticationState.Processing)
                {
                    User  = new User(authenticationMessage.login, ScsClient);
                    State = AuthenticationState.Success;

                    //Console.WriteLine("Authentication Success login=" + authenticationMessage.login);
                }

                Stop();
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Constructs a new AuthenticationRequestArgs instance from the given client message.
        /// </summary>
        /// <param name="msg">
        /// The client authentication message.
        /// </param>
        public AuthenticationRequestArgs(AuthenticationMessage msg)
        {
            Username = msg.Username;
            Password = new SecureString();

            try
            {
                foreach (var c in msg.Password)
                {
                    Password.AppendChar((char)c);
                }
            }
            finally
            {
                Array.Clear(msg.Password, 00, msg.Password.Length);
            }
        }
Exemplo n.º 17
0
        public static void ReceivedMessage(NetworkMessage networkMessage)
        {
            Debug.WriteLine("Message received");

            // Read the message type
            MessageType msgType = (MessageType)networkMessage.GetMessageType();
            string      json    = networkMessage.GetJSONFromBuffer();

            switch (msgType)
            {
            case MessageType.Authentication:
                AuthenticationMessage auth = JsonConvert.DeserializeObject <AuthenticationMessage>(json);
                if (authenticatedCallback != null)
                {
                    authenticatedCallback?.Invoke(auth);
                }

                break;

            case MessageType.ChatMessage:
                ChatMessage chat = JsonConvert.DeserializeObject <ChatMessage>(json);
                OnMessageReceived?.Invoke(null, chat);
                break;

            case MessageType.UserState:
                UserStateMessage userState = JsonConvert.DeserializeObject <UserStateMessage>(json);
                OnMessageReceived?.Invoke(null, new ChatMessage()
                {
                    Sender = new User()
                    {
                        Name = "SYSTEM"
                    },
                    Content = userState.User.Name + " has " + (userState.IsOnline ? "come online" : "gone offline"),
                    Date    = userState.Date
                });

                break;

            default:
                break;
            }
        }
        public static void Test_Returns_True_After_Sucessful_Authentication()
        {
            //arrange
            Mock <ISigningService> signingService = new Mock <ISigningService>();

            signingService.Setup(x => x.isSigned(It.IsAny <byte[]>(), It.IsAny <byte[]>()))
            .Returns(true);

            ElevationManager      elevationManager = new ElevationManager(Mock.Of <ILog>(), signingService.Object);
            IElevatableSession    session          = Mock.Of <IElevatableSession>();
            AuthenticationMessage message          = new AuthenticationMessage(new byte[0]);

            session.UniqueAuthToken = elevationManager.RequestSingleUseToken(session);

            //act:Preform a authentication
            elevationManager.TryAuthenticate(session, message);

            //assrt
            Assert.True(elevationManager.isElevated(session));
        }
Exemplo n.º 19
0
        public static void HandleAuthentication(IMessage message, IConnection connection)
        {
            AuthenticationMessage authMessage = message as AuthenticationMessage;
            string passHash = "";

            try
            {
                passHash = Conn.GetPersonPassHash(authMessage.Login);
            }
            catch (Exception e)
            {
                connection.Send(MessageFactory.MakeAuthenticationResposeMessage("", Status.Error, e.Message));
                return;
            }
            if (passHash == Hash(authMessage.Password))
            {
                SendToken(authMessage.Login, connection);
                return;
            }
            connection.Send(MessageFactory.MakeAuthenticationResposeMessage("", Status.Error, "Пароли не совпадают."));
        }
Exemplo n.º 20
0
        public async Task <AuthenticationMessage> SendAuthenticationMessageAsync(string deviceId, Guid customerId, string phoneNumber, string messageText, bool isSms)
        {
            if (isSms)
            {
                // TODO : this should not be here !!!!!
                var config = new ConfigurationBuilder()
                             .AddJsonFile("appconfig.json")
                             .Build();

                //TODO: refactor
                var accountSid = config["accountId"];
                var authToken  = config["authToken"];
                var sendFrom   = config["phonenumber"];

                TwilioClient.Init(accountSid, authToken);

                var message = await MessageResource.CreateAsync(
                    body : messageText,
                    from : new Twilio.Types.PhoneNumber(sendFrom),
                    to : new Twilio.Types.PhoneNumber(phoneNumber));

                var m = new AuthenticationMessage
                {
                    Customer    = await _dbContext.Customers.FirstOrDefaultAsync(x => x.Id == customerId),
                    Data        = messageText,
                    Device      = await _dbContext.Devices.FirstOrDefaultAsync(x => x.DeviceId == deviceId),
                    DateCreated = DateTime.Now,
                    IsUsed      = false
                };

                _dbContext.AuthenticationMessages.Add(m);

                await _dbContext.SaveChangesAsync();

                return(m);
            }

            return(null);
        }
        private void Authenticate(AuthenticationMessage authenticationMessage)
        {
            PasswordMessage passwordMessage;

            switch (authenticationMessage.AuthenticationMessageType)
            {
            case AuthenticationMessageType.MD5Password:
                passwordMessage = PasswordMessage.CreateMd5(
                    authenticationMessage, ClientState,
                    PostgresConnectionString);
                break;

            default:
                throw new ArgumentOutOfRangeException(
                          nameof(authenticationMessage.AuthenticationMessageType),
                          authenticationMessage.AuthenticationMessageType,
                          "Authentication method not supported.");
            }

            using (passwordMessage)
            {
                WriteMessage(passwordMessage);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// This method is the implementation of IConferenceServer.
        /// This methos is called from client side to connect to a particular meeting.
        /// This methods do the following things:
        /// -Search Conference from running conferences on this server--if found return conference room object
        /// otherwise search db  & make new object of conferenceroom and return that
        /// -Create new AuthenticationMessage with profile.ClientId that is passed to JoinConference method.
        /// -Check conf==null then throw exception that specified conference id not found.
        /// -check conference capacity by executing query to mysql and throw exception in the case when capacity is full
        /// -sleep thread 1 seconds.
        /// -validate password of the meeting....its just empty function return true in all casees
        /// -Always else condition of if(!ValidateAuthentication(Password,"" + conferenceID)) statement run
        ///  --check ctool_guest if IsGuest=true, if IsGuest=false then check ctool_company_member table
        ///  --Assign Msg object different values like ftp_ip,username & password etc
        ///  --check query result that is run again IsGuest true/false, assign different values to profile & msg object
        /// -check duplicate profile name..if found throw exception of duplicate user
        /// -this condition will not run because on previous statement we throw exception on same name
        ///  if(cp.ClientRegistrationId == profile.ClientRegistrationId) // client exist in this meeting 
        /// -conf.AttachClient(profile.Name,profile,Msg); will add the profile uri to dispatcher list so that 
        ///  user can get the message when some message is broadcast.
        ///  -Add message join messages
        ///  -insert profile.cleintid in the ctool_billing with billing_mtype=1 with quest and billing_mtype=0 for non-guest.
        ///  -Select billing id against insertion and asssign it into the profile.billingid which further used in the billing consumer function named 
        ///  public void UpdateBillingInformation()
        ///  -return conferenceroom object.
        /// </summary>
        /// <param name="conferenceID"></param>
        /// <param name="profile"></param>
        /// <param name="Msg"></param>
        /// <param name="Password"></param>
        /// <param name="IsGuest"></param>
        /// <returns></returns>
        public IConferenceRoom JoinConference(int conferenceID,ref WebMeeting.Common.ClientProfile profile,out AuthenticationMessage Msg, string Password,bool IsGuest)
        {
            Console.WriteLine(" On Join Called \n Going inside Search Conference");
                ConferenceRoom      conf;

                //
                // Find the conference
                //
                conf = SearchConference(conferenceID.ToString());
                Msg = new AuthenticationMessage(profile.ClientId,true);
                //try
                //{

                //
                // If conf not found, raise an error
                //
                if(conf == null)
                {
                    throw (new System.ArgumentException("No conference with specified Id found hosted on this server", conferenceID.ToString()));
                }
                string sql = "select meeting_capacity from ctool_meeting where meeting_id = " + conf.ConferenceId;
                ArrayList Recordset = dbCon.Execute(sql);
                //Console.WriteLine(sql + "\n Execute. Recordset Count = " + Recordset.Count.ToString());
                if(Recordset.Count < 1)
                {
                    throw (new System.ArgumentException("No conference with specified Id found hosted on this server", conferenceID.ToString() ));
                }
                ArrayList Record = (ArrayList)Recordset[0];
                int nTotal = Convert.ToInt32(Record[0]);
                if((conf.ClientList.Count + 1) > (nTotal+1))
                {
                    throw (new System.ArgumentException("No More users can join this conference. Conference Capacity reached", "Max" + conferenceID.ToString()));
                }
                //this sleep code should be removed as it slow the connection speed of the application.
                System.Threading.Thread.Sleep(1000);
                //ValidateAuthentication(Password,"" + conferenceID)--this method does nothing,its always send
                //true
                /*
                if(!ValidateAuthentication(Password,"" + conferenceID))
                {
                    Console.WriteLine("\nUser not validated ");
                    throw (new System.ArgumentException("Invalid Meeting Password", Password));
                }
                else
                */
                {
                    string sql2= "Select company_member_fname,company_member_email,company_acc_name From ctool_company_member,ctool_company_acc where company_acc_id = company_member_cid AND company_member_id = " + profile.ClientRegistrationId;
                    if(IsGuest)
                    {
                        sql2 = "Select * from ctool_guest where guest_id = " +  profile.ClientRegistrationId;
                    }
                    profile.IsGuest = IsGuest;
                    ArrayList recordSet = dbCon.Execute(sql2);
                    if(recordSet.Count < 1)
                    {
                        throw (new System.ArgumentException("No user exists with specified username","ClientRegistrationId"));

                    }
                    else
                    {

                        Msg.ConferenceName = conf.conferenceName;
                        Msg.FTPPassoword = this.FTP_Password;
                        Msg.FTPUsername = this.FTP_Username;
                        Msg.FTPPort = this.FTP_PORT;
                        Msg.FTP_IP = this.FTP_IP;
                        Msg.ImageURL = GetImage("" + conferenceID);
                        Msg.SenderID=-1;
                        Msg.VoiceIP = voiceServerIP;
                        Msg.VoicePort = voiceServerPort;
                        Msg.voiceConferenceId = conf.conferenceVoiceSessionID;
                        if(recordSet.Count > 0)
                        {
                            if(IsGuest)
                            {
                                ArrayList record = (ArrayList)recordSet[0];
                                string strFName =record[3].ToString();
                                profile.Name = strFName;
                                profile.EMailAddress = record[4].ToString().ToLower();
                                Msg.companyName = "Guest Account";
                                Msg.ClientName = strFName;
                                Msg.ClientEmail = profile.EMailAddress;//record[1].ToString().ToLower();
                                Msg.SenderID=-1;
                            }
                            else
                            {
                                ArrayList record = (ArrayList)recordSet[0];
                                string strFName =record[0].ToString();
                                profile.Name = strFName;
                                profile.EMailAddress = record[1].ToString().ToLower();
                                profile.Name = strFName;
                                Msg.companyName =record[2].ToString();
                                Msg.ClientName = strFName;
                                Msg.ClientEmail = record[1].ToString().ToLower();
                                Msg.SenderID=-1;
                            }
                        }
                    }
                }
                Console.WriteLine("profile name :::"+profile.Name);

                foreach(ClientProfile cp in conf.ClientList.Values)
                {
                    Console.WriteLine("client List name :::"+cp.Name.Trim());
                    // To avoid the duplicate name
                    if(cp.Name.Trim()==profile.Name.Trim())
                    {
                        Console.WriteLine("Exception fired of login duplicate");
                        throw (new System.ArgumentException("A user is already login with name.", profile.Name.Trim()));
                    }
                    //
                    if(cp.ClientRegistrationId == profile.ClientRegistrationId) // client exist in this meeting
                    {

                        // zaeem Vierw thios condition doesnt seem to be working ok
                        // Wil see that later
                        conf.checkConnectionUrgent(cp.ClientId );
                        //break;
                    }
                }
                Console.WriteLine("Meeting Name " + Msg.ConferenceName);

                Console.WriteLine("\n Calling AttachClient");
                conf.AttachClient(profile.Name,profile,Msg);
                Console.WriteLine("\n Attach Client Called");

                GenuineUtility.CurrentSession["Profile"] = profile;

                //******************** Logging
                ST_flowMsg FlowMsgObj = new  ST_flowMsg ();
                FlowMsgObj.meetID = conf.ConferenceId ;
                FlowMsgObj.curDate= DateTime.Now.Year + "-" + DateTime.Now.Month +"-" + DateTime.Now.Day + " " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second;
                FlowMsgObj.curMsg = profile.Name + " has joined the "+ conf.conferenceName +" conference ." ;
                FlowMsgObj.MsgCategory = "Attendee Joins and Leaves";
                //Zaeem Removed logging
                //flowMsgs.Add(FlowMsgObj);

                FlowMsgObj = null;
                return conf;
            /*
            }

            catch(Exception exp)
            {

                Console.WriteLine("******** Exception in Join conference **********");
                Console.WriteLine(exp.Message.ToString());
                Console.WriteLine(exp.StackTrace.ToString());
                Console.WriteLine("********End Exception in Join conference **********");
                return conf;

            }
            */
        }
Exemplo n.º 23
0
        public async ValueTask <AuthenticatedResult> AuthenticateAsync(CancellationToken cancellationToken = default)
        {
            var myProfileMessage = new ProfileMessage(
                GenSessionId(),
                (_digitalSignature is null) ? AuthenticationType.None : AuthenticationType.Signature,
                new[] { KeyExchangeAlgorithmType.EcDh_P521_Sha2_256 },
                new[] { KeyDerivationAlgorithmType.Pbkdf2 },
                new[] { CryptoAlgorithmType.Aes_Gcm_256 },
                new[] { HashAlgorithmType.Sha2_256 });
            var otherProfileMessage = await this.ExchangeProfileMessageAsync(myProfileMessage, cancellationToken);

            ParseAlgorithmTypes(myProfileMessage, otherProfileMessage, out var keyExchangeAlgorithmType, out var keyDerivationAlgorithmType, out var cryptoAlgorithmType, out var hashAlgorithmType);

            OmniSignature?signature;

            byte[] secret;

            if (keyExchangeAlgorithmType.HasFlag(KeyExchangeAlgorithmType.EcDh_P521_Sha2_256))
            {
                var myAgreement             = OmniAgreement.Create(OmniAgreementAlgorithmType.EcDh_P521_Sha2_256);
                var otherAgreementPublicKey = await this.ExchangeAgreementPublicKeyAsync(myAgreement.GetOmniAgreementPublicKey(), cancellationToken);

                var myHash    = this.ComputeHash(myProfileMessage, myAgreement.GetOmniAgreementPublicKey(), hashAlgorithmType);
                var otherHash = this.ComputeHash(otherProfileMessage, otherAgreementPublicKey, hashAlgorithmType);

                var myAuthenticationMessage    = AuthenticationMessage.Create(DateTime.UtcNow, myHash, _digitalSignature);
                var otherAuthenticationMessage = await this.ExchangeAuthenticationMessageAsync(myAuthenticationMessage, cancellationToken);

                if ((DateTime.UtcNow - otherAuthenticationMessage.CreationTime.ToDateTime()) > TimeSpan.FromMinutes(30))
                {
                    throw new NotSupportedException();
                }
                if (!BytesOperations.Equals(otherAuthenticationMessage.Hash.Span, otherHash))
                {
                    throw new NotSupportedException();
                }

                signature = otherAuthenticationMessage.Certificate?.GetOmniSignature();
                secret    = OmniAgreement.GetSecret(otherAgreementPublicKey, myAgreement.GetOmniAgreementPrivateKey());
            }
            else
            {
                throw new NotSupportedException();
            }

            byte[] encryptKey;
            byte[] decryptKey;
            byte[] encryptNonce;
            byte[] decryptNonce;

            if (keyDerivationAlgorithmType.HasFlag(KeyDerivationAlgorithmType.Pbkdf2))
            {
                byte[] xorSessionId = new byte[Math.Max(myProfileMessage.SessionId.Length, otherProfileMessage.SessionId.Length)];
                BytesOperations.Xor(myProfileMessage.SessionId.Span, otherProfileMessage.SessionId.Span, xorSessionId);

                int cryptoKeyLength = 0;
                int nonceLength     = 0;

                if (cryptoAlgorithmType.HasFlag(CryptoAlgorithmType.Aes_Gcm_256))
                {
                    cryptoKeyLength = 32;
                    nonceLength     = 12;
                }

                encryptKey   = new byte[cryptoKeyLength];
                decryptKey   = new byte[cryptoKeyLength];
                encryptNonce = new byte[nonceLength];
                decryptNonce = new byte[nonceLength];

                var kdfResult = new byte[(cryptoKeyLength + nonceLength) * 2];

                if (hashAlgorithmType.HasFlag(HashAlgorithmType.Sha2_256))
                {
                    Pbkdf2_Sha2_256.TryComputeHash(secret.AsSpan(), xorSessionId, 1024, kdfResult);
                }

                using (var stream = new MemoryStream(kdfResult))
                {
                    if (_type == OmniSecureConnectionType.Connected)
                    {
                        stream.Read(encryptKey, 0, encryptKey.Length);
                        stream.Read(decryptKey, 0, decryptKey.Length);
                        stream.Read(encryptNonce, 0, encryptNonce.Length);
                        stream.Read(decryptNonce, 0, decryptNonce.Length);
                    }
                    else if (_type == OmniSecureConnectionType.Accepted)
                    {
                        stream.Read(decryptKey, 0, decryptKey.Length);
                        stream.Read(encryptKey, 0, encryptKey.Length);
                        stream.Read(decryptNonce, 0, decryptNonce.Length);
                        stream.Read(encryptNonce, 0, encryptNonce.Length);
                    }
                }

                return(new AuthenticatedResult()
                {
                    Signature = signature,
                    CryptoAlgorithmType = cryptoAlgorithmType,
                    EncryptKey = encryptKey,
                    DecryptKey = decryptKey,
                    EncryptNonce = encryptNonce,
                    DecryptNonce = decryptNonce,
                });
            }
            else
            {
                throw new NotSupportedException(nameof(keyDerivationAlgorithmType));
            }
        }
Exemplo n.º 24
0
        private async ValueTask <AuthenticationMessage> ExchangeAuthenticationMessageAsync(AuthenticationMessage myAuthenticationMessage, CancellationToken cancellationToken = default)
        {
            var enqueueTask = _connection.Sender.SendAsync(myAuthenticationMessage, cancellationToken).AsTask();
            var dequeueTask = _connection.Receiver.ReceiveAsync <AuthenticationMessage>(cancellationToken).AsTask();

            await Task.WhenAll(enqueueTask, dequeueTask);

            var otherAuthenticationMessage = dequeueTask.Result;

            if (otherAuthenticationMessage is null)
            {
                throw new NullReferenceException();
            }

            return(otherAuthenticationMessage);
        }
Exemplo n.º 25
0
        private void OnServerMessage(NamedPipeConnection <BaseMessage, BaseMessage> connection, BaseMessage message)
        {
            // This is so gross, but unfortuantely we can't just switch on a type.
            // We can come up with a nice mapping system so we can do a switch,
            // but this can wait.

            if (Default.m_ipcQueue.HandleMessage(message))
            {
                return;
            }

            if (m_ipcQueue.HandleMessage(message))
            {
                return;
            }

            m_logger.Debug("Got IPC message from server.");

            var msgRealType = message.GetType();

            if (msgRealType == typeof(AuthenticationMessage))
            {
                AuthMessage = (AuthenticationMessage)message;
                m_logger.Debug("Server message is {0}", nameof(AuthenticationMessage));
                var cast = (AuthenticationMessage)message;
                if (cast != null)
                {
                    AuthenticationResultReceived?.Invoke(cast);
                }
            }
            else if (msgRealType == typeof(Messages.DeactivationMessage))
            {
                m_logger.Debug("Server message is {0}", nameof(Messages.DeactivationMessage));
                var cast = (Messages.DeactivationMessage)message;
                if (cast != null)
                {
                    DeactivationResultReceived?.Invoke(cast.Command);
                }
            }
            else if (msgRealType == typeof(Messages.FilterStatusMessage))
            {
                m_logger.Debug("Server message is {0}", nameof(Messages.FilterStatusMessage));
                var cast = (Messages.FilterStatusMessage)message;
                if (cast != null)
                {
                    StateChanged?.Invoke(new StateChangeEventArgs(cast));
                }
            }
            else if (msgRealType == typeof(Messages.NotifyBlockActionMessage))
            {
                m_logger.Debug("Server message is {0}", nameof(Messages.NotifyBlockActionMessage));
                var cast = (Messages.NotifyBlockActionMessage)message;
                if (cast != null)
                {
                    BlockActionReceived?.Invoke(cast);
                }
            }
            else if (msgRealType == typeof(Messages.RelaxedPolicyMessage))
            {
                m_logger.Debug("Server message is {0}", nameof(Messages.RelaxedPolicyMessage));
                var cast = (Messages.RelaxedPolicyMessage)message;
                if (cast != null)
                {
                    switch (cast.Command)
                    {
                    case RelaxedPolicyCommand.Info:
                    {
                        RelaxedPolicyInfoReceived?.Invoke(cast);
                    }
                    break;

                    case RelaxedPolicyCommand.Expired:
                    {
                        RelaxedPolicyExpired?.Invoke();
                    }
                    break;
                    }
                }
            }
            else if (msgRealType == typeof(Messages.ClientToClientMessage))
            {
                m_logger.Debug("Server message is {0}", nameof(Messages.ClientToClientMessage));
                var cast = (Messages.ClientToClientMessage)message;
                if (cast != null)
                {
                    ClientToClientCommandReceived?.Invoke(cast);
                }
            }
            else if (msgRealType == typeof(Messages.ServerUpdateQueryMessage))
            {
                m_logger.Debug("Server message is {0}", nameof(Messages.ServerUpdateQueryMessage));
                var cast = (Messages.ServerUpdateQueryMessage)message;
                if (cast != null)
                {
                    ServerAppUpdateRequestReceived?.Invoke(cast);
                }
            }
            else if (msgRealType == typeof(Messages.ServerUpdateNotificationMessage))
            {
                m_logger.Debug("Server message is {0}", nameof(Messages.ServerUpdateNotificationMessage));
                var cast = (Messages.ServerUpdateNotificationMessage)message;
                if (cast != null)
                {
                    ServerUpdateStarting?.Invoke();
                }
            }
            else if (msgRealType == typeof(Messages.CaptivePortalDetectionMessage))
            {
                m_logger.Debug("Server message is {0}", nameof(Messages.CaptivePortalDetectionMessage));
                var cast = (Messages.CaptivePortalDetectionMessage)message;
                if (cast != null)
                {
                    CaptivePortalDetectionReceived?.Invoke(cast);
                }
            }
            else
            {
                // Unknown type.
            }
        }
Exemplo n.º 26
0
        public async ValueTask Handshake(CancellationToken cancellationToken = default)
        {
            ProfileMessage myProfileMessage;
            ProfileMessage?otherProfileMessage = null;
            {
                {
                    var sessionId = new byte[32];
                    using (var randomNumberGenerator = RandomNumberGenerator.Create())
                    {
                        randomNumberGenerator.GetBytes(sessionId);
                    }

                    myProfileMessage = new ProfileMessage(
                        sessionId,
                        (_passwords.Count == 0) ? AuthenticationType.None : AuthenticationType.Password,
                        new[] { KeyExchangeAlgorithm.EcDh_P521_Sha2_256 },
                        new[] { KeyDerivationAlgorithm.Pbkdf2 },
                        new[] { CryptoAlgorithm.Aes_Gcm_256 },
                        new[] { HashAlgorithm.Sha2_256 });
                }

                var enqueueTask = _connection.EnqueueAsync((bufferWriter) => myProfileMessage.Export(bufferWriter, _bytesPool), cancellationToken);
                var dequeueTask = _connection.DequeueAsync((sequence) => otherProfileMessage = ProfileMessage.Import(sequence, _bytesPool), cancellationToken);

                await ValueTaskHelper.WhenAll(enqueueTask, dequeueTask);

                if (otherProfileMessage is null)
                {
                    throw new NullReferenceException();
                }
                if (myProfileMessage.AuthenticationType != otherProfileMessage.AuthenticationType)
                {
                    throw new OmniSecureConnectionException("AuthenticationType does not match.");
                }
            }

            var keyExchangeAlgorithm   = GetOverlapMaxEnum(myProfileMessage.KeyExchangeAlgorithms, otherProfileMessage.KeyExchangeAlgorithms);
            var keyDerivationAlgorithm = GetOverlapMaxEnum(myProfileMessage.KeyDerivationAlgorithms, otherProfileMessage.KeyDerivationAlgorithms);
            var cryptoAlgorithm        = GetOverlapMaxEnum(myProfileMessage.CryptoAlgorithms, otherProfileMessage.CryptoAlgorithms);
            var hashAlgorithm          = GetOverlapMaxEnum(myProfileMessage.HashAlgorithms, otherProfileMessage.HashAlgorithms);

            if (!EnumHelper.IsValid(keyExchangeAlgorithm))
            {
                throw new OmniSecureConnectionException("key exchange algorithm does not match.");
            }
            if (!EnumHelper.IsValid(keyDerivationAlgorithm))
            {
                throw new OmniSecureConnectionException("key derivation algorithm does not match.");
            }
            if (!EnumHelper.IsValid(cryptoAlgorithm))
            {
                throw new OmniSecureConnectionException("Crypto algorithm does not match.");
            }
            if (!EnumHelper.IsValid(hashAlgorithm))
            {
                throw new OmniSecureConnectionException("Hash algorithm does not match.");
            }

            ReadOnlyMemory <byte> secret = null;

            if (keyExchangeAlgorithm.HasFlag(KeyExchangeAlgorithm.EcDh_P521_Sha2_256))
            {
                var myAgreement = OmniAgreement.Create(OmniAgreementAlgorithmType.EcDh_P521_Sha2_256);

                OmniAgreementPrivateKey myAgreementPrivateKey;
                OmniAgreementPublicKey? otherAgreementPublicKey = null;
                {
                    {
                        myAgreementPrivateKey = myAgreement.GetOmniAgreementPrivateKey();

                        var enqueueTask = _connection.EnqueueAsync((bufferWriter) => myAgreement.GetOmniAgreementPublicKey().Export(bufferWriter, _bytesPool), cancellationToken);
                        var dequeueTask = _connection.DequeueAsync((sequence) => otherAgreementPublicKey = OmniAgreementPublicKey.Import(sequence, _bytesPool), cancellationToken);

                        await ValueTaskHelper.WhenAll(enqueueTask, dequeueTask);

                        if (otherAgreementPublicKey is null)
                        {
                            throw new NullReferenceException();
                        }
                        if ((DateTime.UtcNow - otherAgreementPublicKey.CreationTime.ToDateTime()).TotalMinutes > 30)
                        {
                            throw new OmniSecureConnectionException("Agreement public key has Expired.");
                        }
                    }

                    if (_passwords.Count > 0)
                    {
                        AuthenticationMessage myAuthenticationMessage;
                        AuthenticationMessage?otherAuthenticationMessage = null;
                        {
                            {
                                var myHashAndPasswordList = this.GetHashes(myProfileMessage, myAgreement.GetOmniAgreementPublicKey(), hashAlgorithm).ToList();

                                _random.Shuffle(myHashAndPasswordList);
                                myAuthenticationMessage = new AuthenticationMessage(myHashAndPasswordList.Select(n => n.Item1).ToArray());
                            }

                            var enqueueTask = _connection.EnqueueAsync((bufferWriter) => myAuthenticationMessage.Export(bufferWriter, _bytesPool), cancellationToken);
                            var dequeueTask = _connection.DequeueAsync((sequence) => otherAuthenticationMessage = AuthenticationMessage.Import(sequence, _bytesPool), cancellationToken);

                            await ValueTaskHelper.WhenAll(enqueueTask, dequeueTask);

                            if (otherAuthenticationMessage is null)
                            {
                                throw new NullReferenceException();
                            }

                            var matchedPasswords = new List <string>();
                            {
                                var equalityComparer = new CustomEqualityComparer <ReadOnlyMemory <byte> >((x, y) => BytesOperations.Equals(x.Span, y.Span), (x) => Fnv1_32.ComputeHash(x.Span));
                                var receiveHashes    = new HashSet <ReadOnlyMemory <byte> >(otherAuthenticationMessage.Hashes, equalityComparer);

                                foreach (var(hash, password) in this.GetHashes(otherProfileMessage, otherAgreementPublicKey, hashAlgorithm))
                                {
                                    if (receiveHashes.Contains(hash))
                                    {
                                        matchedPasswords.Add(password);
                                    }
                                }
                            }

                            if (matchedPasswords.Count == 0)
                            {
                                throw new OmniSecureConnectionException("Password does not match.");
                            }

                            _matchedPasswords = matchedPasswords.ToArray();
                        }
                    }
                }

                if (hashAlgorithm.HasFlag(HashAlgorithm.Sha2_256))
                {
                    secret = OmniAgreement.GetSecret(otherAgreementPublicKey, myAgreementPrivateKey);
                }
            }

            byte[] myCryptoKey;
            byte[] otherCryptoKey;
            byte[] myNonce;
            byte[] otherNonce;

            if (keyDerivationAlgorithm.HasFlag(KeyDerivationAlgorithm.Pbkdf2))
            {
                byte[] xorSessionId = new byte[Math.Max(myProfileMessage.SessionId.Length, otherProfileMessage.SessionId.Length)];
                BytesOperations.Xor(myProfileMessage.SessionId.Span, otherProfileMessage.SessionId.Span, xorSessionId);

                int cryptoKeyLength = 0;
                int nonceLength     = 0;

                if (cryptoAlgorithm.HasFlag(CryptoAlgorithm.Aes_Gcm_256))
                {
                    cryptoKeyLength = 32;
                    nonceLength     = 12;
                }

                myCryptoKey    = new byte[cryptoKeyLength];
                otherCryptoKey = new byte[cryptoKeyLength];
                myNonce        = new byte[nonceLength];
                otherNonce     = new byte[nonceLength];

                var kdfResult = new byte[(cryptoKeyLength + nonceLength) * 2];

                if (hashAlgorithm.HasFlag(HashAlgorithm.Sha2_256))
                {
                    Pbkdf2_Sha2_256.TryComputeHash(secret.Span, xorSessionId, 1024, kdfResult);
                }

                using (var stream = new MemoryStream(kdfResult))
                {
                    if (_type == OmniSecureConnectionType.Connected)
                    {
                        stream.Read(myCryptoKey, 0, myCryptoKey.Length);
                        stream.Read(otherCryptoKey, 0, otherCryptoKey.Length);
                        stream.Read(myNonce, 0, myNonce.Length);
                        stream.Read(otherNonce, 0, otherNonce.Length);
                    }
                    else if (_type == OmniSecureConnectionType.Accepted)
                    {
                        stream.Read(otherCryptoKey, 0, otherCryptoKey.Length);
                        stream.Read(myCryptoKey, 0, myCryptoKey.Length);
                        stream.Read(otherNonce, 0, otherNonce.Length);
                        stream.Read(myNonce, 0, myNonce.Length);
                    }
                }
            }
            else
            {
                throw new NotSupportedException(nameof(keyDerivationAlgorithm));
            }

            _state = new State(cryptoAlgorithm, hashAlgorithm, myCryptoKey, otherCryptoKey, myNonce, otherNonce);
        }
Exemplo n.º 27
0
        protected void OnServerMessage(BaseMessage message)
        {
            // This is so gross, but unfortuantely we can't just switch on a type.
            // We can come up with a nice mapping system so we can do a switch,
            // but this can wait.

            if (Default.ipcQueue.HandleMessage(message))
            {
                return;
            }

            if (ipcQueue.HandleMessage(message))
            {
                return;
            }

            logger.Debug("Got IPC message from server.");

            var msgRealType = message.GetType();

            Action <BaseMessage> callback = null;

            if (m_callbacks.TryGetValue(msgRealType, out callback))
            {
                logger.Debug("Server message is {0}", msgRealType.Name);
                callback?.Invoke(message);
            }
            else if (msgRealType == typeof(AuthenticationMessage))
            {
                AuthMessage = (AuthenticationMessage)message;
                logger.Debug("Server message is {0}", nameof(AuthenticationMessage));
                var cast = (AuthenticationMessage)message;
                if (cast != null)
                {
                    AuthenticationResultReceived?.Invoke(cast);
                }
            }
            else if (msgRealType == typeof(Messages.DeactivationMessage))
            {
                logger.Debug("Server message is {0}", nameof(Messages.DeactivationMessage));
                var cast = (Messages.DeactivationMessage)message;
                if (cast != null)
                {
                    DeactivationResultReceived?.Invoke(cast.Command);
                }
            }
            else if (msgRealType == typeof(Messages.FilterStatusMessage))
            {
                logger.Debug("Server message is {0}", nameof(Messages.FilterStatusMessage));
                var cast = (Messages.FilterStatusMessage)message;
                if (cast != null)
                {
                    StateChanged?.Invoke(new StateChangeEventArgs(cast));
                }
            }
            else if (msgRealType == typeof(Messages.NotifyBlockActionMessage))
            {
                logger.Debug("Server message is {0}", nameof(Messages.NotifyBlockActionMessage));
                var cast = (Messages.NotifyBlockActionMessage)message;
                if (cast != null)
                {
                    BlockActionReceived?.Invoke(cast);
                }
            }
            else if (msgRealType == typeof(Messages.RelaxedPolicyMessage))
            {
                logger.Debug("Server message is {0}", nameof(Messages.RelaxedPolicyMessage));
                var cast = (Messages.RelaxedPolicyMessage)message;
                if (cast != null)
                {
                    switch (cast.Command)
                    {
                    case RelaxedPolicyCommand.Info:
                    {
                        RelaxedPolicyInfoReceived?.Invoke(cast);
                    }
                    break;

                    case RelaxedPolicyCommand.Expired:
                    {
                        RelaxedPolicyExpired?.Invoke();
                    }
                    break;
                    }
                }
            }
            else if (msgRealType == typeof(Messages.ClientToClientMessage))
            {
                logger.Debug("Server message is {0}", nameof(Messages.ClientToClientMessage));
                var cast = (Messages.ClientToClientMessage)message;
                if (cast != null)
                {
                    ClientToClientCommandReceived?.Invoke(cast);
                }
            }
            else if (msgRealType == typeof(Messages.ServerUpdateQueryMessage))
            {
                logger.Debug("Server message is {0}", nameof(Messages.ServerUpdateQueryMessage));
                var cast = (Messages.ServerUpdateQueryMessage)message;
                if (cast != null)
                {
                    ServerAppUpdateRequestReceived?.Invoke(cast);
                }
            }
            else if (msgRealType == typeof(Messages.CaptivePortalDetectionMessage))
            {
                logger.Debug("Server message is {0}", nameof(Messages.CaptivePortalDetectionMessage));
                var cast = (Messages.CaptivePortalDetectionMessage)message;
                if (cast != null)
                {
                    CaptivePortalDetectionReceived?.Invoke(cast);
                }
            }
            else if (msgRealType == typeof(Messages.CertificateExemptionMessage))
            {
                logger.Debug("Server message is {0}", nameof(Messages.CertificateExemptionMessage));
                var cast = (Messages.CertificateExemptionMessage)message;
                if (cast != null)
                {
                    AddCertificateExemptionRequest?.Invoke(cast);
                }
            }
            else if (msgRealType == typeof(Messages.DiagnosticsInfoMessage))
            {
                logger.Debug("Server message is {0}", nameof(Messages.DiagnosticsInfoMessage));
                var cast = (Messages.DiagnosticsInfoMessage)message;
                if (cast != null)
                {
                    OnDiagnosticsInfo?.Invoke(cast);
                }
            }
            else
            {
                // Unknown type.
                logger.Info("Unknown type is {0}", msgRealType.Name);
            }
        }