Example #1
0
        }         // GetAmlDataCustom

        private bool GetAml(
            AddressCurrency nCurrency,
            out string result,
            out decimal authentication,
            out string description
            )
        {
            AuthenticationResults authenticationResults = this.idHubService.Authenticate(
                this.firstName,
                null,
                this.lastName,
                this.gender,
                this.dateOfBirth,
                this.customerAddress[1, nCurrency],
                this.customerAddress[2, nCurrency],
                this.customerAddress[3, nCurrency],
                this.customerAddress[4, nCurrency],
                null,
                this.customerAddress[6, nCurrency],
                this.customerId
                );

            return(CreateAmlResultFromAuthenticationReuslts(
                       authenticationResults,
                       out result,
                       out authentication,
                       out description
                       ));
        }         // GetAml
Example #2
0
        public void TestParseSimpleWithComment()
        {
            const string          input  = "example.com; foo=pass (2 of 3 tests OK)";
            var                   buffer = Encoding.ASCII.GetBytes(input);
            AuthenticationResults authres;

            Assert.IsTrue(AuthenticationResults.TryParse(buffer, 0, buffer.Length, out authres));
            Assert.AreEqual("example.com", authres.AuthenticationServiceIdentifier, "authserv-id");
            Assert.AreEqual(1, authres.Results.Count, "methods");
            Assert.AreEqual("foo", authres.Results[0].Method);
            Assert.AreEqual("pass", authres.Results[0].Result);
            Assert.AreEqual("2 of 3 tests OK", authres.Results[0].ResultComment);

            Assert.AreEqual(input, authres.ToString());

            const string expected = " example.com; foo=pass (2 of 3 tests OK)\n";
            var          encoded  = new StringBuilder();
            var          options  = FormatOptions.Default.Clone();

            options.NewLineFormat = NewLineFormat.Unix;

            authres.Encode(options, encoded, "Authentication-Results:".Length);

            Assert.AreEqual(expected, encoded.ToString());
        }
Example #3
0
        public void TestArgumentExceptions()
        {
            AuthenticationResults authres;
            var buffer = new byte[16];

            Assert.Throws <ArgumentNullException> (() => new AuthenticationResults(null));

            Assert.Throws <ArgumentNullException> (() => new AuthenticationMethodResult(null));
            Assert.Throws <ArgumentNullException> (() => new AuthenticationMethodResult(null, "result"));
            Assert.Throws <ArgumentNullException> (() => new AuthenticationMethodResult("method", null));

            Assert.Throws <ArgumentNullException> (() => new AuthenticationMethodProperty(null, "property", "value"));
            Assert.Throws <ArgumentNullException> (() => new AuthenticationMethodProperty("ptype", null, "value"));
            Assert.Throws <ArgumentNullException> (() => new AuthenticationMethodProperty("ptype", "Property", null));

            Assert.Throws <ArgumentNullException> (() => AuthenticationResults.Parse(null));
            Assert.Throws <ArgumentNullException> (() => AuthenticationResults.Parse(null, 0, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => AuthenticationResults.Parse(buffer, -1, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => AuthenticationResults.Parse(buffer, 0, -1));

            Assert.Throws <ArgumentNullException> (() => AuthenticationResults.TryParse(null, out authres));
            Assert.Throws <ArgumentNullException> (() => AuthenticationResults.TryParse(null, 0, 0, out authres));
            Assert.Throws <ArgumentOutOfRangeException> (() => AuthenticationResults.TryParse(buffer, -1, 0, out authres));
            Assert.Throws <ArgumentOutOfRangeException> (() => AuthenticationResults.TryParse(buffer, 0, -1, out authres));
        }
Example #4
0
        }         // GetAml

        private bool CreateAmlResultFromAuthenticationReuslts(
            AuthenticationResults results,
            out string result,
            out decimal authentication,
            out string description
            )
        {
            description    = results.AuthIndexText;
            authentication = results.AuthenticationIndex;

            if (results.HasError)
            {
                Log.Info("Error getting AML data: {0}", results.Error);
                result = string.Empty;
                return(true);
            }             // if

            result = "Passed";

            if (results.ReturnedHRP.Any(returnedHrp => this.warningRules.Contains(returnedHrp.HighRiskPolRuleID)))
            {
                result = "Warning";
            }

            return(false);
        }         // CreateAmlResultFromAuthenticationReuslts
Example #5
0
        public void TestParseMethodWithMultipleProperties()
        {
            const string          input  = "example.com; spf=pass ptype1.prop1=value1 ptype2.prop2=value2";
            var                   buffer = Encoding.ASCII.GetBytes(input);
            AuthenticationResults authres;

            Assert.IsTrue(AuthenticationResults.TryParse(buffer, 0, buffer.Length, out authres));
            Assert.AreEqual("example.com", authres.AuthenticationServiceIdentifier, "authserv-id");
            Assert.AreEqual(1, authres.Results.Count, "methods");
            Assert.AreEqual("spf", authres.Results[0].Method);
            Assert.AreEqual("pass", authres.Results[0].Result);
            Assert.AreEqual(2, authres.Results[0].Properties.Count, "properties");
            Assert.AreEqual("ptype1", authres.Results[0].Properties[0].PropertyType);
            Assert.AreEqual("prop1", authres.Results[0].Properties[0].Property);
            Assert.AreEqual("value1", authres.Results[0].Properties[0].Value);
            Assert.AreEqual("ptype2", authres.Results[0].Properties[1].PropertyType);
            Assert.AreEqual("prop2", authres.Results[0].Properties[1].Property);
            Assert.AreEqual("value2", authres.Results[0].Properties[1].Value);

            Assert.AreEqual(input, authres.ToString());

            const string expected = " example.com;\n\tspf=pass ptype1.prop1=value1 ptype2.prop2=value2\n";
            var          encoded  = new StringBuilder();
            var          options  = FormatOptions.Default.Clone();

            options.NewLineFormat = NewLineFormat.Unix;

            authres.Encode(options, encoded, "Authentication-Results:".Length);

            Assert.AreEqual(expected, encoded.ToString());
        }
Example #6
0
        public void TestParseHeavilyCommentedExample()
        {
            var buffer = Encoding.ASCII.GetBytes("foo.example.net (foobar) 1 (baz); dkim (Because I like it) / 1 (One yay) = (wait for it) fail policy (A dot can go here) . (like that) expired (this surprised me) = (as I wasn't expecting it) 1362471462");
            AuthenticationResults authres;

            Assert.IsTrue(AuthenticationResults.TryParse(buffer, 0, buffer.Length, out authres));
            Assert.AreEqual("foo.example.net", authres.AuthenticationServiceIdentifier, "authserv-id");
            Assert.AreEqual(1, authres.Version.Value, "authres-version");
            Assert.AreEqual(1, authres.Results.Count, "methods");
            Assert.AreEqual("dkim", authres.Results[0].Method);
            Assert.AreEqual(1, authres.Results[0].Version.Value, "method-version");
            Assert.AreEqual("fail", authres.Results[0].Result);
            Assert.AreEqual(1, authres.Results[0].Properties.Count, "dkim properties");
            Assert.AreEqual("policy", authres.Results[0].Properties[0].PropertyType);
            Assert.AreEqual("expired", authres.Results[0].Properties[0].Property);
            Assert.AreEqual("1362471462", authres.Results[0].Properties[0].Value);

            Assert.AreEqual("foo.example.net 1; dkim/1=fail policy.expired=1362471462", authres.ToString());

            const string expected = " foo.example.net 1;\n\tdkim/1=fail policy.expired=1362471462\n";
            var          encoded  = new StringBuilder();
            var          options  = FormatOptions.Default.Clone();

            options.NewLineFormat = NewLineFormat.Unix;

            authres.Encode(options, encoded, "Authentication-Results:".Length);

            Assert.AreEqual(expected, encoded.ToString());
        }
        /// <summary>
        /// Generate the ARC-Authentication-Results header.
        /// </summary>
        /// <remarks>
        /// The ARC-Authentication-Results header contains information detailing the results of
        /// authenticating/verifying the message via ARC, DKIM, SPF, etc.
        ///
        /// In the following implementation, we assume that all of these authentication results
        /// have already been determined by other mail software that has added some Authentication-Results
        /// headers containing this information.
        ///
        /// Note: This method is used when ArcSigner.Sign() is called instead of ArcSigner.SignAsync().
        /// </remarks>
        protected override AuthenticationResults GenerateArcAuthenticationResults(FormatOptions options, MimeMessage message, CancellationToken cancellationToken)
        {
            var results = new AuthenticationResults(AuthenticationServiceIdentifier);

            for (int i = 0; i < message.Headers.Count; i++)
            {
                var header = message.Headers[i];

                if (header.Id != HeaderId.AuthenticationResults)
                {
                    continue;
                }

                if (!AuthenticationResults.TryParse(header.RawValue, out AuthenticationResults authres))
                {
                    continue;
                }

                if (authres.AuthenticationServiceIdentifier != AuthenticationServiceIdentifier)
                {
                    continue;
                }

                foreach (var result in authres.Results)
                {
                    if (!results.Results.Any(r => r.Method == result.Method))
                    {
                        results.Results.Add(result);
                    }
                }
            }

            return(results);
        }
Example #8
0
        public void TestParseSimpleWithQuotedReasonSemiColon()
        {
            const string          input  = "example.com; spf=pass reason=\"good stuff\"";
            var                   buffer = Encoding.ASCII.GetBytes(input + "; ");
            AuthenticationResults authres;

            Assert.IsTrue(AuthenticationResults.TryParse(buffer, 0, buffer.Length, out authres));
            Assert.AreEqual("example.com", authres.AuthenticationServiceIdentifier, "authserv-id");
            Assert.AreEqual(1, authres.Results.Count, "methods");
            Assert.AreEqual("spf", authres.Results[0].Method);
            Assert.AreEqual("pass", authres.Results[0].Result);
            Assert.AreEqual("good stuff", authres.Results[0].Reason);
            Assert.AreEqual(0, authres.Results[0].Properties.Count, "properties");

            Assert.AreEqual(input, authres.ToString());

            const string expected = " example.com; spf=pass reason=\"good stuff\"\n";
            var          encoded  = new StringBuilder();
            var          options  = FormatOptions.Default.Clone();

            options.NewLineFormat = NewLineFormat.Unix;

            authres.Encode(options, encoded, "Authentication-Results:".Length);

            Assert.AreEqual(expected, encoded.ToString());
        }
Example #9
0
        public void TestParseSimpleWithProperty3()
        {
            const string          input  = "example.com; spf=pass [email protected]";
            var                   buffer = Encoding.ASCII.GetBytes(input);
            AuthenticationResults authres;

            Assert.IsTrue(AuthenticationResults.TryParse(buffer, 0, buffer.Length, out authres));
            Assert.AreEqual("example.com", authres.AuthenticationServiceIdentifier, "authserv-id");
            Assert.AreEqual(1, authres.Results.Count, "methods");
            Assert.AreEqual("spf", authres.Results[0].Method);
            Assert.AreEqual("pass", authres.Results[0].Result);
            Assert.AreEqual(1, authres.Results[0].Properties.Count, "properties");
            Assert.AreEqual("smtp", authres.Results[0].Properties[0].PropertyType);
            Assert.AreEqual("mailfrom", authres.Results[0].Properties[0].Property);
            Assert.AreEqual("*****@*****.**", authres.Results[0].Properties[0].Value);

            Assert.AreEqual(input, authres.ToString());

            const string expected = " example.com;\n\tspf=pass [email protected]\n";
            var          encoded  = new StringBuilder();
            var          options  = FormatOptions.Default.Clone();

            options.NewLineFormat = NewLineFormat.Unix;

            authres.Encode(options, encoded, "Authentication-Results:".Length);

            Assert.AreEqual(expected, encoded.ToString());
        }
        protected virtual async void ConnectionApproval(NetIncomingMessage msg)
        {
            var connection = msg.SenderConnection;
            var user       = "";
            var password   = "";

            try
            {
                var token = msg.ReadString();
                var tripleDesInformation = await Authenticator.GetKeyFromToken(token);

                ((ServerTripleDesNetEncryptor)NetEncryptor).ImportKeyForConnection(msg.SenderConnection, tripleDesInformation.Key, tripleDesInformation.Iv);
                ((ServerTripleDesNetEncryptor)NetEncryptor).Decrypt(msg);

                user     = msg.ReadString().ToLower();
                password = msg.ReadString();
            }
            catch (Exception e)
            {
                Log(e);
                connection.Deny(NetConnectionResult.Unknown);
                NetConnector.Recycle(msg);
                return;
            }

            if (PendingAndLoggedInUsers.Values.Any(c => c.UserName == user))
            {
                AuthenticationResults.Add(new Tuple <AuthenticationResult, string>(
                                              new AuthenticationResult()
                {
                    Connection   = connection,
                    Success      = false,
                    RequestState = RequestState.UserAlreadyLoggedIn
                }, user));
                return;
            }
            PendingAndLoggedInUsers.Add(connection, new CommunicationUser <TAuthenticationUser>()
            {
                UserName = user
            });
            var authTask = Authenticator.Authenticate(user, password)
                           .ContinueWith(async approval =>
            {
                var authentication        = await approval;
                authentication.Connection = connection;

                ConnectionApprovalExtras(authentication);
                if (authentication.Success && !string.IsNullOrEmpty(authentication.UserId))
                {
                    var userData = await GetUser(authentication.UserId);
                    PendingAndLoggedInUsers[connection].UserData     = userData;
                    PendingAndLoggedInUsers[connection].LoggedInTime = DateTime.UtcNow;
                }
                AuthenticationResults.Add(new Tuple <AuthenticationResult, string>(authentication, user));
                NetConnector.Recycle(msg);
            });

            AddRunningTask(authTask);
        }
Example #11
0
        public override void Execute()
        {
            DB.ForEachRowSafe((entriesSafeReader, bRowsetStart) => {
                int customerId    = entriesSafeReader["CustomerId"];
                long serviceLogId = entriesSafeReader["Id"];

                try {
                    SafeReader dataSafeReader = DB.GetFirst("GetDataForAmlBackfill",
                                                            CommandSpecies.StoredProcedure,
                                                            new QueryParameter("CustomerId", customerId),
                                                            new QueryParameter("ServiceLogId", serviceLogId));

                    if (!dataSafeReader.IsEmpty)
                    {
                        Log.Debug("Backfilling aml for service log: {0} customer {1}", serviceLogId, customerId);

                        DateTime insertDate         = dataSafeReader["InsertDate"];
                        string xml                  = dataSafeReader["ResponseData"];
                        string firstName            = dataSafeReader["FirstName"];
                        string middleName           = dataSafeReader["MiddleName"];
                        string surname              = dataSafeReader["Surname"];
                        string postcode             = dataSafeReader["Postcode"];
                        string existingAmlResult    = dataSafeReader["ExistingAmlResult"];
                        bool isLastEntryForCustomer = dataSafeReader["IsLastEntryForCustomer"];

                        string key = string.Format("{0}_{1}_{2}_{3}", firstName, middleName, surname, postcode);
                        AuthenticationResults result = idHubService.ParseAndSave_ForBackfill(xml, serviceLogId, insertDate, key);

                        int authentication = result.AuthenticationIndex;
                        string description = result.AuthIndexText;

                        if (isLastEntryForCustomer)
                        {
                            // Update customer table
                            DB.ExecuteNonQuery("UpdateAmlResult", CommandSpecies.StoredProcedure,
                                               new QueryParameter("CustomerId", customerId),
                                               new QueryParameter("AmlResult", existingAmlResult),
                                               new QueryParameter("AmlScore", authentication),
                                               new QueryParameter("AmlDescription", description)
                                               );
                        }
                        else
                        {
                            // Update IsActive to 0 (The save always saves it as active)
                            DB.ExecuteNonQuery("SetAmlResultInactive", CommandSpecies.StoredProcedure,
                                               new QueryParameter("LookupKey", key),
                                               new QueryParameter("ServiceLogId", serviceLogId)
                                               );
                        }
                    }
                }
                catch (Exception ex) {
                    Log.Error("The backfill for customer:{0} failed with exception:{1}", customerId, ex);
                }

                return(ActionResult.Continue);
            }, "GetEntriesForAmlBackfill", CommandSpecies.StoredProcedure);
        }
Example #12
0
 /// <summary> The constructor for afailed result of an authentication method.</summary>
 /// <param name="errorReason"> The reason why the method did not return succesful</param>
 public AuthenticationResult(AuthenticationResults errorReason)
 {
     TokenString = default;
     if (errorReason == AuthenticationResults.Succes)
     {
         throw new ArgumentException("errorReason cannot be Succes");
     }
     Result = errorReason;
 }
Example #13
0
        public async Task <AuthenticationResult> AuthenticateUser(AuthenticationTypesContext context)
        {
            IDictionary <string, ClaimsIdentity> identity = new Dictionary <string, ClaimsIdentity>();
            AuthenticationResults authenticationResult    = AuthenticationResults.FailInvalidCredentials;
            var user = await this._manager.FindAsync(context.UserName, context.Password);

            if (user != null)
            {
                authenticationResult = AuthenticationResults.Success;
                identity             = await this._claimsProvider.GenerateUserIdentitiesAsync(user, context.AuthenticationTypes);
            }
            return(new AuthenticationResult(authenticationResult, identity));
        }
Example #14
0
 public void TestInitialize()
 {
     jsonService = new JsonService();
     initiateAuthenticationResponse = new InitiateAuthenticationResponse(REFERENCE);
     authenticationResult           = new AuthenticationResult(REFERENCE, TransactionStatus.STARTED, null, null);
     authenticationResultWithRequestedAttributes = new AuthenticationResult(REFERENCE, TransactionStatus.APPROVED, DETAILS, REQUESTED_ATTRIBUTES);
     authenticationResults = new AuthenticationResults(new List <AuthenticationResult> {
         authenticationResult
     });
     authenticationClient = AuthenticationClient.Create(SslSettings.Create(TestKeystoreUtil.GetKeystorePath(TestKeystoreUtil.KEYSTORE_PATH_PKCS12), TestKeystoreUtil.KEYSTORE_PASSWORD, TestKeystoreUtil.GetKeystorePath(TestKeystoreUtil.CERTIFICATE_PATH)), FrejaEnvironment.TEST)
                            .SetTestModeCustomUrl(CUSTOM_URL).SetTransactionContext(TransactionContext.PERSONAL).Build <AuthenticationClient>();
     StopServer();
 }
Example #15
0
        public void TestEncodeLongResultMethod()
        {
            const string expected = "Authentication-Results: lists.example.com 1;\n\treally-long-method-name=really-long-value\n";
            var          encoded  = new StringBuilder("Authentication-Results:");
            var          authres  = new AuthenticationResults("lists.example.com");
            var          options  = FormatOptions.Default.Clone();

            authres.Results.Add(new AuthenticationMethodResult("really-long-method-name", "really-long-value"));
            authres.Version = 1;

            options.NewLineFormat = NewLineFormat.Unix;

            authres.Encode(options, encoded, encoded.Length);

            Assert.AreEqual(expected, encoded.ToString());
        }
Example #16
0
        public void TestEncodeLongAuthServId()
        {
            const string authservid = "this-is-a-really-really-really-long-authserv-identifier-that-is-78-octets-long";
            const string expected   = "Authentication-Results:\n\t" + authservid + ";\n\tdkim=pass; spf=pass\n";
            var          encoded    = new StringBuilder("Authentication-Results:");
            var          authres    = new AuthenticationResults(authservid);
            var          options    = FormatOptions.Default.Clone();

            authres.Results.Add(new AuthenticationMethodResult("dkim", "pass"));
            authres.Results.Add(new AuthenticationMethodResult("spf", "pass"));

            options.NewLineFormat = NewLineFormat.Unix;

            authres.Encode(options, encoded, encoded.Length);

            Assert.AreEqual(expected, encoded.ToString());
        }
Example #17
0
        }         // GetAmlData

        private bool GetAmlDataCustom(out string result, out decimal authentication, out string description)
        {
            Log.Info(
                "Starting custom AML check with parameters: " +
                "FirstName={0} Surname={1} Gender={2} DateOfBirth={3} " +
                "idhubHouseNumber={4} idhubHouseName={5} idhubStreet={6} " +
                "idhubDistrict={7} idhubTown={8} idhubCounty={9} idhubPostCode={10}",
                this.firstName,
                this.lastName,
                this.gender,
                this.dateOfBirth,
                this.idhubHouseNumber,
                this.idhubHouseName,
                this.idhubStreet,
                this.idhubDistrict,
                this.idhubTown,
                this.idhubCounty,
                this.idhubPostCode
                );

            AuthenticationResults authenticationResults = this.idHubService.AuthenticateForcedWithCustomAddress(
                this.firstName,
                null,
                this.lastName,
                this.gender,
                this.dateOfBirth,
                this.idhubHouseNumber,
                this.idhubHouseName,
                this.idhubStreet,
                this.idhubDistrict,
                this.idhubTown,
                this.idhubCounty,
                this.idhubPostCode,
                this.customerId
                );

            return(CreateAmlResultFromAuthenticationReuslts(
                       authenticationResults,
                       out result,
                       out authentication,
                       out description
                       ));
        }         // GetAmlDataCustom
Example #18
0
        public void TestParseAuthServIdSemicolon()
        {
            var buffer = Encoding.ASCII.GetBytes("example.org;");
            AuthenticationResults authres;

            Assert.IsTrue(AuthenticationResults.TryParse(buffer, 0, buffer.Length, out authres));
            Assert.AreEqual("example.org", authres.AuthenticationServiceIdentifier, "authserv-id");

            Assert.AreEqual("example.org; none", authres.ToString());

            const string expected = " example.org; none\n";
            var          encoded  = new StringBuilder();
            var          options  = FormatOptions.Default.Clone();

            options.NewLineFormat = NewLineFormat.Unix;

            authres.Encode(options, encoded, "Authentication-Results:".Length);

            Assert.AreEqual(expected, encoded.ToString());
        }
Example #19
0
        public void TestParseNoAuthServId()
        {
            var buffer = Encoding.ASCII.GetBytes("spf=fail (sender IP is 1.1.1.1) smtp.mailfrom=eu-west-1.amazonses.com; recevingdomain.com; dkim=pass (signature was verified) header.d=domain.com;domain1.com; dmarc=bestguesspass action=none header.from=domain.com;");
            AuthenticationResults authres;

            Assert.IsTrue(AuthenticationResults.TryParse(buffer, 0, buffer.Length, out authres));
            Assert.IsNull(authres.AuthenticationServiceIdentifier, "authserv-id");

            Assert.AreEqual("spf=fail (sender IP is 1.1.1.1) smtp.mailfrom=eu-west-1.amazonses.com; recevingdomain.com; dkim=pass (signature was verified) header.d=domain.com;domain1.com; dmarc=bestguesspass action=\"none\" header.from=domain.com", authres.ToString());

            const string expected = " spf=fail (sender IP is 1.1.1.1)\n\tsmtp.mailfrom=eu-west-1.amazonses.com; recevingdomain.com;\n\tdkim=pass (signature was verified) header.d=domain.com;domain1.com;\n\tdmarc=bestguesspass action=\"none\" header.from=domain.com\n";
            var          encoded  = new StringBuilder();
            var          options  = FormatOptions.Default.Clone();

            options.NewLineFormat = NewLineFormat.Unix;

            authres.Encode(options, encoded, "Authentication-Results:".Length);

            Assert.AreEqual(expected, encoded.ToString());
        }
Example #20
0
        public void TestParseMultipleMethods()
        {
            const string          input  = "example.com; auth=pass (cram-md5) [email protected]; spf=pass smtp.mailfrom=example.net; sender-id=pass header.from=example.net";
            var                   buffer = Encoding.ASCII.GetBytes(input);
            AuthenticationResults authres;

            Assert.IsTrue(AuthenticationResults.TryParse(buffer, 0, buffer.Length, out authres));
            Assert.AreEqual("example.com", authres.AuthenticationServiceIdentifier, "authserv-id");
            Assert.AreEqual(3, authres.Results.Count, "methods");
            Assert.AreEqual("auth", authres.Results[0].Method);
            Assert.AreEqual("pass", authres.Results[0].Result);
            Assert.AreEqual("cram-md5", authres.Results[0].ResultComment);
            Assert.AreEqual(1, authres.Results[0].Properties.Count, "auth properties");
            Assert.AreEqual("smtp", authres.Results[0].Properties[0].PropertyType);
            Assert.AreEqual("auth", authres.Results[0].Properties[0].Property);
            Assert.AreEqual("*****@*****.**", authres.Results[0].Properties[0].Value);
            Assert.AreEqual("spf", authres.Results[1].Method);
            Assert.AreEqual("pass", authres.Results[1].Result);
            Assert.AreEqual(1, authres.Results[1].Properties.Count, "spf properties");
            Assert.AreEqual("smtp", authres.Results[1].Properties[0].PropertyType);
            Assert.AreEqual("mailfrom", authres.Results[1].Properties[0].Property);
            Assert.AreEqual("example.net", authres.Results[1].Properties[0].Value);
            Assert.AreEqual("sender-id", authres.Results[2].Method);
            Assert.AreEqual("pass", authres.Results[2].Result);
            Assert.AreEqual(1, authres.Results[2].Properties.Count, "sender-id properties");
            Assert.AreEqual("header", authres.Results[2].Properties[0].PropertyType);
            Assert.AreEqual("from", authres.Results[2].Properties[0].Property);
            Assert.AreEqual("example.net", authres.Results[2].Properties[0].Value);

            Assert.AreEqual(input, authres.ToString());

            const string expected = " example.com;\n\tauth=pass (cram-md5) [email protected];\n\tspf=pass smtp.mailfrom=example.net; sender-id=pass header.from=example.net\n";
            var          encoded  = new StringBuilder();
            var          options  = FormatOptions.Default.Clone();

            options.NewLineFormat = NewLineFormat.Unix;

            authres.Encode(options, encoded, "Authentication-Results:".Length);

            Assert.AreEqual(expected, encoded.ToString());
        }
Example #21
0
        static void AssertParseFailure(string input, int tokenIndex, int errorIndex)
        {
            var buffer = Encoding.ASCII.GetBytes(input);

            Assert.IsFalse(AuthenticationResults.TryParse(buffer, out AuthenticationResults authres));

            try {
                AuthenticationResults.Parse(buffer);
                Assert.Fail("Expected parse error.");
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "TokenIndex");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "ErrorIndex");
            }

            try {
                AuthenticationResults.Parse(buffer, 0, buffer.Length);
                Assert.Fail("Expected parse error.");
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "TokenIndex");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "ErrorIndex");
            }
        }
Example #22
0
        public void TestEncodeLongResultMethodWithVersionAndCommentAndReason()
        {
            const string expected = "Authentication-Results: lists.example.com 1;\n\treally-really-really-long-method-name/214748367=\n\treally-really-really-long-value (this is a really really long result comment)\n\treason=\"this is a really really really long reason\"\n\tthis-is-a-really-really-long-ptype.this-is-a-really-really-long-property=\n\tthis-is-a-really-really-long-value\n";
            var          encoded  = new StringBuilder("Authentication-Results:");
            var          authres  = new AuthenticationResults("lists.example.com");
            var          options  = FormatOptions.Default.Clone();

            authres.Results.Add(new AuthenticationMethodResult("really-really-really-long-method-name", "really-really-really-long-value")
            {
                ResultComment = "this is a really really long result comment",
                Reason        = "this is a really really really long reason",
                Version       = 214748367
            });
            authres.Results[0].Properties.Add(new AuthenticationMethodProperty("this-is-a-really-really-long-ptype", "this-is-a-really-really-long-property", "this-is-a-really-really-long-value"));
            authres.Version = 1;

            options.NewLineFormat = NewLineFormat.Unix;

            authres.Encode(options, encoded, encoded.Length);

            Assert.AreEqual(expected, encoded.ToString());
        }
Example #23
0
        private void GetAuthenticationResults(AuthenticationResultsRequest getAuthenticationResultsRequest, TransactionContext transactionContext, string relyingPartyId)
        {
            AuthenticationResults expectedResponse     = PrepareAuthenticationResultsResponse();
            IAuthenticationClient authenticationClient = AuthenticationClient.Create(SslSettings.Create(TestKeystoreUtil.GetKeystorePath(TestKeystoreUtil.KEYSTORE_PATH_PKCS12), TestKeystoreUtil.KEYSTORE_PASSWORD, TestKeystoreUtil.GetKeystorePath(TestKeystoreUtil.CERTIFICATE_PATH)), FrejaEnvironment.TEST)
                                                         .SetHttpService(CommonTestData.HttpServiceMock.Object)
                                                         .SetTransactionContext(transactionContext).Build <AuthenticationClient>();

            CommonTestData.HttpServiceMock.Setup(x => x.Send <AuthenticationResults>(It.IsAny <Uri>(), It.IsAny <string>(), It.IsAny <AuthenticationResultsRequest>(), It.IsAny <string>())).Returns(expectedResponse);
            List <AuthenticationResult> response = authenticationClient.GetResults(getAuthenticationResultsRequest);

            if (transactionContext.Equals(TransactionContext.PERSONAL))
            {
                CommonTestData.HttpServiceMock.Verify(x => x.Send <AuthenticationResults>(new Uri(FrejaEnvironment.TEST + MethodUrl.AUTHENTICATION_GET_RESULTS), RequestTemplate.AUTHENTICATION_RESULTS_TEMPLATE, getAuthenticationResultsRequest, relyingPartyId));
            }
            else
            {
                CommonTestData.HttpServiceMock.Verify(x => x.Send <AuthenticationResults>(new Uri(FrejaEnvironment.TEST + MethodUrl.ORGANISATION_AUTHENTICATION_GET_RESULTS), RequestTemplate.AUTHENTICATION_RESULTS_TEMPLATE, getAuthenticationResultsRequest, relyingPartyId));
            }
            AuthenticationResult first = response[0];

            Assert.AreEqual(CommonTestData.REFERENCE, first.AuthRef);
            Assert.AreEqual(TransactionStatus.STARTED, first.Status);
            Assert.AreEqual(CommonTestData.DETAILS, first.Details);
            Assert.AreEqual(CommonTestData.REQUESTED_ATTRIBUTES.BasicUserInfo.Name, first.RequestedAttributes.BasicUserInfo.Name);
            Assert.AreEqual(CommonTestData.REQUESTED_ATTRIBUTES.BasicUserInfo.Surname, first.RequestedAttributes.BasicUserInfo.Surname);
            Assert.AreEqual(CommonTestData.REQUESTED_ATTRIBUTES.DateOfBirth, first.RequestedAttributes.DateOfBirth);
            Assert.AreEqual(CommonTestData.REQUESTED_ATTRIBUTES.EmailAddress, first.RequestedAttributes.EmailAddress);
            Assert.AreEqual(CommonTestData.REQUESTED_ATTRIBUTES.CustomIdentifier, first.RequestedAttributes.CustomIdentifier);
            Assert.AreEqual(CommonTestData.REQUESTED_ATTRIBUTES.Ssn.Country, first.RequestedAttributes.Ssn.Country);
            Assert.AreEqual(CommonTestData.REQUESTED_ATTRIBUTES.Ssn.Ssn, first.RequestedAttributes.Ssn.Ssn);
            Assert.AreEqual(CommonTestData.REQUESTED_ATTRIBUTES.OrganisationIdIdentifier, first.RequestedAttributes.OrganisationIdIdentifier);
            AuthenticationResult second = response[1];

            Assert.AreEqual(CommonTestData.REFERENCE, second.AuthRef);
            Assert.AreEqual(TransactionStatus.DELIVERED_TO_MOBILE, second.Status);
            Assert.AreEqual(CommonTestData.DETAILS, second.Details);
            Assert.AreEqual(CommonTestData.CUSTOM_IDENTIFIER, second.RequestedAttributes.CustomIdentifier);
        }
Example #24
0
        public void TestParseMultipleMethodsWithReasons()
        {
            const string          input  = "example.com; dkim=pass reason=\"good signature\" [email protected]; dkim=fail reason=\"bad signature\" [email protected]";
            var                   buffer = Encoding.ASCII.GetBytes(input);
            AuthenticationResults authres;

            Assert.IsTrue(AuthenticationResults.TryParse(buffer, 0, buffer.Length, out authres));
            Assert.AreEqual("example.com", authres.AuthenticationServiceIdentifier, "authserv-id");
            Assert.AreEqual(2, authres.Results.Count, "methods");
            Assert.AreEqual("dkim", authres.Results[0].Method);
            Assert.AreEqual("pass", authres.Results[0].Result);
            Assert.AreEqual("good signature", authres.Results[0].Reason);
            Assert.AreEqual(1, authres.Results[0].Properties.Count, "dkim properties");
            Assert.AreEqual("header", authres.Results[0].Properties[0].PropertyType);
            Assert.AreEqual("i", authres.Results[0].Properties[0].Property);
            Assert.AreEqual("@mail-router.example.net", authres.Results[0].Properties[0].Value);
            Assert.AreEqual("dkim", authres.Results[1].Method);
            Assert.AreEqual("fail", authres.Results[1].Result);
            Assert.AreEqual("bad signature", authres.Results[1].Reason);
            Assert.AreEqual(1, authres.Results[1].Properties.Count, "dkim properties");
            Assert.AreEqual("header", authres.Results[1].Properties[0].PropertyType);
            Assert.AreEqual("i", authres.Results[1].Properties[0].Property);
            Assert.AreEqual("@newyork.example.com", authres.Results[1].Properties[0].Value);

            Assert.AreEqual(input, authres.ToString());

            const string expected = " example.com;\n\tdkim=pass reason=\"good signature\" [email protected];\n\tdkim=fail reason=\"bad signature\" [email protected]\n";
            var          encoded  = new StringBuilder();
            var          options  = FormatOptions.Default.Clone();

            options.NewLineFormat = NewLineFormat.Unix;

            authres.Encode(options, encoded, "Authentication-Results:".Length);

            Assert.AreEqual(expected, encoded.ToString());
        }
Example #25
0
 public AuthenticationResult(AuthenticationResults authenticationResult, IDictionary <string, ClaimsIdentity> identities)
 {
     this.Result     = authenticationResult;
     this.Identities = identities;
 }
Example #26
0
 /// <summary>
 /// Logs the user out locally
 /// </summary>
 public void Logout()
 {
     authResults = null;
     FirePropertyChanged(nameof(IsAuthenticated));
 }
Example #27
0
        /// <summary>
        /// Logs into ParticleCloud with the given username and password
        /// </summary>
        /// <param name="username">The Particle account username</param>
        /// <param name="password">The Particle account password</param>
        /// <param name="expiresIn">How many seconds the token will be valid for. 0 means forever. Short lived tokens are better for security.</param>
        /// <returns>Result if Result.Success == true the user is logged in if its false the user is not logged in and ErrorMessage will contain the error from the server</returns>
        public async Task <Result> LoginWithUserAsync(String username, String password, int expiresIn = 3600)
        {
            if (String.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException(nameof(username));
            }
            if (String.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException(nameof(password));
            }

            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("particle:particle")));

            var data = new Dictionary <String, String>();

            data["grant_type"] = "password";
            data["username"]   = username;
            data["password"]   = password;
            data["expires_in"] = expiresIn.ToString();
            // BaseAddress did not seam to work on Linux so changed to use UriBuilder
            UriBuilder b = new UriBuilder(baseUri);

            b.Path = "/oauth/token";
            try
            {
                var postResults = await client.PostAsync(b.Uri, new FormUrlEncodedContent(data));

                if (postResults.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var results = await postResults.Content.ReadAsStringAsync();

                    var ret = await Task.Run(() => JsonConvert.DeserializeObject <AuthenticationResults>(results));

                    if (ret != null)
                    {
                        if (!String.IsNullOrWhiteSpace(ret.AccessToken))
                        {
                            authResults          = ret;
                            authResults.Username = username;
                            authResults.Password = password;
                            FirePropertyChanged(nameof(IsAuthenticated));
                            return(new Result
                            {
                                Success = true
                            });
                        }
                    }
                }
                else if (postResults.StatusCode == System.Net.HttpStatusCode.BadRequest)
                {
                    var results = await postResults.Content.ReadAsStringAsync();

                    var ret = await Task.Run(() => JsonConvert.DeserializeObject <Result>(results));

                    if (ret != null)
                    {
                        ret.Success = false;
                        return(ret);
                    }
                }

                return(new Result
                {
                    Success = false,
                    Error = postResults.StatusCode.ToString()
                });
            }
            catch (HttpRequestException re)
            {
                return(new Result
                {
                    Success = false,
                    Error = re.Message,
                    Exception = re
                });
            }
        }
Example #28
0
 /// <summary> THe constructor for a succesful result of an authentication method</summary>
 /// <param name="user"> The id of the user.</param>
 /// <param name="has2FaEnabled"> Signal that the current user has 2fa enabled, defaults to false.</param>
 public UserResult(long user, bool has2FaEnabled = false)
 {
     User          = user;
     Has2FaEnabled = has2FaEnabled;
     Result        = AuthenticationResults.Succes;
 }
Example #29
0
 /// <summary> The constructor for a failed result.</summary>
 /// <param name="errorReason"> THe reason why the method failed.</param>
 public UserResult(AuthenticationResults errorReason)
 {
     User          = default;
     Has2FaEnabled = default;
     Result        = errorReason;
 }
Example #30
0
 /// <summary> The constructor for a succesful result for the authentication method.</summary>
 /// <param name="tokenString"> The token to be attached to the result body.</param>
 public AuthenticationResult(string tokenString)
 {
     TokenString = tokenString;
     Result      = AuthenticationResults.Succes;
 }