Esempio n. 1
0
        public static int Main(string[] args)
        {
            int exitCode = 0;

            try
            {
                Console.WriteLine("Press on your Yubikey to get the OTP value.  Do NOT add any quotes or other characters to the input.");
                string otp = Console.ReadLine();

                if (string.IsNullOrWhiteSpace(otp) || otp.Length == 0)
                {
                    Console.WriteLine("Unable to read Yubikey input.");
                    exitCode = -1;
                }
                else
                {
                    var client       = new YubicoClient(yubico_api_client_id, yubico_api_secret_key);
                    var yubicoAnswer = client.VerifyAsync(otp).GetAwaiter().GetResult();
                    Console.WriteLine(String.Format(CultureInfo.InvariantCulture, "Validation status is : {0}.", yubicoAnswer.Status.ToString()));
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
                exitCode = -2;
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
            return(exitCode);
        }
Esempio n. 2
0
        public async Task <bool> ValidateAsync(string purpose, string token, UserManager <User> manager, User user)
        {
            var userService = _serviceProvider.GetRequiredService <IUserService>();

            if (!(await userService.CanAccessPremium(user)))
            {
                return(false);
            }

            if (string.IsNullOrWhiteSpace(token) || token.Length != 44)
            {
                return(false);
            }

            var id = token.Substring(0, 12);

            var provider = user.GetTwoFactorProvider(TwoFactorProviderType.YubiKey);

            if (!provider.MetaData.ContainsValue(id))
            {
                return(false);
            }

            var client   = new YubicoClient(_globalSettings.Yubico.ClientId, _globalSettings.Yubico.Key);
            var response = await client.VerifyAsync(token);

            return(response.Status == YubicoResponseStatus.Ok);
        }
Esempio n. 3
0
        public async Task Verify_NotOK()
        {
            var user = Environment.GetEnvironmentVariable("UNITTEST_YUBICO_USERNAME");
            var pass = Environment.GetEnvironmentVariable("UNITTEST_YUBICO_PASSWORD");

            var credential = new NetworkCredential(user, pass);

            using var client = new YubicoClient(credential, this.Logger);

            var res = await client.VerifyAsync("ccscccggkthbfkghciijdkvvldebnevilllbufrrftek", default);

            Assert.IsFalse(res);

            res = await client.VerifyAsync(null, default).ConfigureAwait(false);

            Assert.IsFalse(res);

            res = await client.VerifyAsync(string.Empty, default).ConfigureAwait(false);

            Assert.IsFalse(res);

            res = await client.VerifyAsync("asdf", default).ConfigureAwait(false);

            Assert.IsFalse(res);
        }
        internal IYubicoResponse Validate(string token, int userId = -1)
        {
            var clientId  = ConfigurationManager.AppSettings["YubiKey.ClientId"];
            var secretKey = ConfigurationManager.AppSettings["YubiKey.SecretKey"];
            var client    = new YubicoClient(clientId, secretKey);
            var database  = ApplicationContext.Current.DatabaseContext.Database;

            try
            {
                var response = client.Verify(token);
                if (response.Status == YubicoResponseStatus.Ok)
                {
                    //check that this specific user has registered this YubiKey
                    if (userId == -1)
                    {
                        return(response);
                    }

                    var result = database.Fetch <TwoFactor>(string.Format("WHERE [userId] = {0} AND [key] = '{1}' AND [confirmed] = 1",
                                                                          userId, Constants.YubiKeyProviderName));

                    if (result.Any(x => x.Value == response.PublicId))
                    {
                        return(response);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error <YubiKeyService>("Could not validate the provided one-time-password", ex);
            }

            return(null);
        }
        public IYubicoResponse Verify(string onetimePassword)
        {
            var client = new YubicoClient(this.ClientId);

            client.SetApiKey(this.ApiKey);
            client.SetSync(this.SyncLevel);
            return(client.Verify(onetimePassword));
        }
Esempio n. 6
0
        private async void Submit(object sender, EventArgs e)
        {
            var otp      = OtpInput.Text;
            var clientId = ClientIdInput.Text;
            var apiKey   = ApiKeyInput.Text;
            var sync     = SyncInput.Text;
            var nonce    = NonceInput.Text;

            OutputField.Clear();

            var client = new YubicoClient(clientId);

            if (!string.IsNullOrEmpty(apiKey))
            {
                client.SetApiKey(apiKey);
            }
            if (!string.IsNullOrEmpty(sync))
            {
                client.SetSync(sync);
            }
            if (!string.IsNullOrEmpty(nonce))
            {
                client.SetNonce(nonce);
            }
            try
            {
                var sw       = Stopwatch.StartNew();
                var response = await client.VerifyAsync(otp);

                sw.Stop();
                if (response != null)
                {
                    OutputField.AppendText(string.Format("response in: {0}{1}", sw.ElapsedMilliseconds, Environment.NewLine));
                    OutputField.AppendText(string.Format("Status: {0}{1}", response.Status, Environment.NewLine));
                    OutputField.AppendText(string.Format("Public ID: {0}{1}", response.PublicId, Environment.NewLine));
                    OutputField.AppendText(string.Format("Use/Session Counter: {0} {1}{2}", response.UseCounter, response.SessionCounter, Environment.NewLine));
                    OutputField.AppendText(string.Format("Url: {0}", response.Url));
                }
                else
                {
                    OutputField.Text = "Null result returned, error in call";
                }
            }
            catch (YubicoValidationFailure yvf)
            {
                OutputField.Text = string.Format("Failure in validation: {0}{1}", yvf.Message, Environment.NewLine);
            }
        }
        public async Task <bool> ValidateAsync(string purpose, string token, UserManager <ApplicationUser, string> manager, ApplicationUser user)
        {
            var clientId = ConfigurationManager.AppSettings["YubikeyClientId"];
            var secret   = ConfigurationManager.AppSettings["YubikeyAPIKey"];

            var client   = new YubicoClient(clientId, secret);
            var response = await client.VerifyAsync(token);

            if (response != null)
            {
                if (response.Status == YubicoResponseStatus.Ok)
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 8
0
        private bool ValidateProofDataAsync(IProofData proofData, IAuthenticationContext context, out string response)
        {
            string userPrincipalName  = (string)context.Data[USERUPN];
            string registeredTokenIDs = (string)context.Data[REGISTEREDTOKENIDS];

            if (proofData == null ||
                proofData.Properties == null ||
                !proofData.Properties.ContainsKey("yubikeyotp"))
            {
                throw new ExternalAuthenticationException("Invalid submission - no proof data provided", context);
            }

            string otp = proofData.Properties["yubikeyotp"] as string;

            log.Debug("[{0}] Extracted otp {1} from proof data", context.ActivityId, otp ?? "(null)");

            if (string.IsNullOrEmpty(otp) || otp.Length < 13)
            {
                response = "Invalid One-Time Password received";
                return(false);
            }

            // extract the first 12 characters of the token id and convert to all lowercase
            string tokenID = otp.Substring(0, 12).ToLower();

            if (Array.IndexOf(registeredTokenIDs.Split(','), tokenID) == -1)
            {
                response = string.Format("Token ID ({0}) not associated with {1}", tokenID, userPrincipalName);
                return(false);
            }

            var client       = new YubicoClient(yubico_api_client_id, yubico_api_secret_key);
            var yubicoAnswer = client.VerifyAsync(otp).GetAwaiter().GetResult();

            if (yubicoAnswer == null || yubicoAnswer.Status != YubicoResponseStatus.Ok)
            {
                response = yubicoAnswer.Status.ToString();
                return(false);
            }

            response = "Authenticated completed successfully";
            return(true);
        }
Esempio n. 9
0
        private bool ValidateProofDataAsync(IProofData proofData, IAuthenticationContext context, out string response)
        {
            if (proofData == null ||
                proofData.Properties == null ||
                !proofData.Properties.ContainsKey("yubikeyotp"))
            {
                throw new ExternalAuthenticationException("Invalid submission - no proof data provided", context);
            }

            string otp = proofData.Properties["yubikeyotp"] as string;

            log.Debug("Extracted otp {0} from proof data", otp ?? "(null)");

            if (string.IsNullOrEmpty(otp) || otp.Length < 13)
            {
                response = "Authentication failed: Invalid One-Time Password received";
                return(false);
            }

            string tokenID = otp.Substring(0, 12);

            if (!registeredTokenIDs.Contains(tokenID))
            {
                response = string.Format("Authentication failed: Token ID ({0}) not associated with {1}", tokenID, upn);
                return(false);
            }

            var client       = new YubicoClient(yubico_api_client_id, yubico_api_secret_key);
            var yubicoAnswer = client.VerifyAsync(otp).GetAwaiter().GetResult();

            if (yubicoAnswer == null || yubicoAnswer.Status != YubicoResponseStatus.Ok)
            {
                response = string.Format("Authentication failed: {0}", yubicoAnswer.Status.ToString());
                return(false);
            }

            response = "Authenticated completed successfully";
            return(true);
        }
        public async Task <YubikeyOTPValidationResult> Validate(string token)
        {
            try
            {
                var client = new YubicoClient(ClientId, ApiKey);
                if (!YubicoClient.IsOtpValidFormat(token))
                {
                    return(YubikeyOTPValidationResult.Failure("Invalid OTP format!"));
                }

                var response = await client.VerifyAsync(token);

                if (response.Status != YubicoResponseStatus.Ok)
                {
                    return(YubikeyOTPValidationResult.Failure(response.Status.ToString()));
                }

                return(YubikeyOTPValidationResult.Success(response.PublicId));
            }
            catch (YubicoValidationFailure e)
            {
                return(YubikeyOTPValidationResult.Failure(e.Message));
            }
        }