Esempio n. 1
0
        public async Task IncrementHotp(int position)
        {
            if (Authenticators.ElementAtOrDefault(position) == null)
            {
                return;
            }

            var info = Authenticators[position];
            var auth = GetAuthenticator(info);

            if (auth.Type != OtpType.Hotp)
            {
                return;
            }

            var secret = Base32.Decode(auth.Secret);
            var hotp   = new Hotp(secret, auth.Algorithm);

            auth.Counter++;
            auth.Code      = hotp.ComputeHotp(auth.Counter);
            auth.TimeRenew = DateTime.Now.AddSeconds(10);

            Authenticators[position] = auth;
            await _connection.UpdateAsync(auth);
        }
        public virtual CredentialViewModel DescribeCredential(Credential credential)
        {
            var           kind   = GetCredentialKind(credential.Type);
            Authenticator auther = null;

            if (kind == CredentialKind.External)
            {
                string providerName = credential.Type.Split('.')[1];
                Authenticators.TryGetValue(providerName, out auther);
            }

            var credentialViewModel = new CredentialViewModel
            {
                Key         = credential.Key,
                Type        = credential.Type,
                TypeCaption = FormatCredentialType(credential.Type),
                Identity    = credential.Identity,
                Created     = credential.Created,
                Expires     = credential.Expires,
                Kind        = kind,
                AuthUI      = auther?.GetUI(),
                // Set the description as the value for legacy API keys
                Description        = credential.Description,
                Value              = kind == CredentialKind.Token && credential.Description == null ? credential.Value : null,
                Scopes             = credential.Scopes.Select(s => new ScopeViewModel(s.Subject, NuGetScopes.Describe(s.AllowedAction))).ToList(),
                ExpirationDuration = credential.ExpirationTicks != null ? new TimeSpan?(new TimeSpan(credential.ExpirationTicks.Value)) : null
            };

            credentialViewModel.HasExpired = credential.HasExpired ||
                                             (credentialViewModel.IsNonScopedV1ApiKey &&
                                              !credential.HasBeenUsedInLastDays(_config.ExpirationInDaysForApiKeyV1));

            return(credentialViewModel);
        }
Esempio n. 3
0
        public virtual CredentialViewModel DescribeCredential(Credential credential)
        {
            var           kind   = GetCredentialKind(credential.Type);
            Authenticator auther = null;

            if (kind == CredentialKind.External)
            {
                string providerName = credential.Type.Split('.')[1];
                if (!Authenticators.TryGetValue(providerName, out auther))
                {
                    auther = null;
                }
            }

            return(new CredentialViewModel
            {
                Type = credential.Type,
                TypeCaption = FormatCredentialType(credential.Type),
                Identity = credential.Identity,
                Value = kind == CredentialKind.Token ? credential.Value : String.Empty,
                Created = credential.Created,
                Expires = credential.Expires,
                Kind = kind,
                AuthUI = auther?.GetUI()
            });
        }
        public async Task IncrementCounter(int position)
        {
            var auth = Authenticators.ElementAtOrDefault(position);

            if (auth == null)
            {
                return;
            }

            auth.Counter++;
            await _connection.UpdateAsync(auth);
        }
        public virtual async Task <AuthenticateExternalLoginResult> ReadExternalLoginCredential(IOwinContext context)
        {
            var result = await context.Authentication.AuthenticateAsync(AuthenticationTypes.External);

            if (result == null)
            {
                _trace.Information("No external login found.");
                return(new AuthenticateExternalLoginResult());
            }
            var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);

            if (idClaim == null)
            {
                _trace.Error("External Authentication is missing required claim: " + ClaimTypes.NameIdentifier);
                return(new AuthenticateExternalLoginResult());
            }

            var nameClaim = result.Identity.FindFirst(ClaimTypes.Name);

            if (nameClaim == null)
            {
                _trace.Error("External Authentication is missing required claim: " + ClaimTypes.Name);
                return(new AuthenticateExternalLoginResult());
            }

            var    emailClaim  = result.Identity.FindFirst(ClaimTypes.Email);
            string emailSuffix = emailClaim == null ? String.Empty : (" <" + emailClaim.Value + ">");

            var tenantIdClaim = result.Identity.FindFirst(tenantIdClaimType);

            Authenticator auther;
            string        authenticationType = idClaim.Issuer;

            if (!Authenticators.TryGetValue(idClaim.Issuer, out auther))
            {
                foreach (var authenticator in Authenticators.Values)
                {
                    if (authenticator.TryMapIssuerToAuthenticationType(idClaim.Issuer, out authenticationType))
                    {
                        auther = authenticator;
                        break;
                    }
                }
            }

            return(new AuthenticateExternalLoginResult()
            {
                Authentication = null,
                ExternalIdentity = result.Identity,
                Authenticator = auther,
                Credential = _credentialBuilder.CreateExternalCredential(authenticationType, idClaim.Value, nameClaim.Value + emailSuffix, tenantIdClaim?.Value)
            });
        }
Esempio n. 6
0
        private string FormatExternalCredentialType(string externalType)
        {
            Authenticator authenticator;

            if (!Authenticators.TryGetValue(externalType, out authenticator))
            {
                return(externalType);
            }
            var ui = authenticator.GetUI();

            return(ui == null ? authenticator.Name : ui.AccountNoun);
        }
        public async Task Rename(int position, string issuer, string username)
        {
            var auth = Authenticators.ElementAtOrDefault(position);

            if (auth == null)
            {
                return;
            }

            auth.Issuer   = issuer;
            auth.Username = username;

            await _connection.UpdateAsync(auth);
        }
Esempio n. 8
0
        public virtual CredentialViewModel DescribeCredential(Credential credential)
        {
            var           kind          = GetCredentialKind(credential.Type);
            Authenticator authenticator = null;

            if (kind == CredentialKind.External)
            {
                if (string.IsNullOrEmpty(credential.TenantId))
                {
                    string providerName = credential.Type.Split('.')[1];
                    Authenticators.TryGetValue(providerName, out authenticator);
                }
                else
                {
                    authenticator = Authenticators
                                    .Values
                                    .FirstOrDefault(provider => provider.Name.Equals(AzureActiveDirectoryV2Authenticator.DefaultAuthenticationType, StringComparison.OrdinalIgnoreCase));
                }
            }

            var credentialViewModel = new CredentialViewModel
            {
                Key         = credential.Key,
                Type        = credential.Type,
                TypeCaption = FormatCredentialType(credential.Type),
                Identity    = credential.Identity,
                Created     = credential.Created,
                Expires     = credential.Expires,
                Kind        = kind,
                AuthUI      = authenticator?.GetUI(),
                // Set the description as the value for legacy API keys
                Description = credential.Description,
                Value       = kind == CredentialKind.Token && credential.Description == null ? credential.Value : null,
                Scopes      = credential.Scopes.Select(s => new ScopeViewModel(
                                                           s.Owner?.Username ?? credential.User.Username,
                                                           s.Subject,
                                                           NuGetScopes.Describe(s.AllowedAction)))
                              .ToList(),
                ExpirationDuration = credential.ExpirationTicks != null ? new TimeSpan?(new TimeSpan(credential.ExpirationTicks.Value)) : null
            };

            credentialViewModel.HasExpired = credential.HasExpired ||
                                             (credentialViewModel.IsNonScopedApiKey &&
                                              !credential.HasBeenUsedInLastDays(_config.ExpirationInDaysForApiKeyV1));

            credentialViewModel.Description = credentialViewModel.IsNonScopedApiKey
                ? Strings.NonScopedApiKeyDescription : credentialViewModel.Description;

            return(credentialViewModel);
        }
Esempio n. 9
0
        public async Task Rename(int position, string issuer, string username)
        {
            if (Authenticators.ElementAtOrDefault(position) == null)
            {
                return;
            }

            var info = Authenticators[position];
            var auth = GetAuthenticator(info);

            auth.Issuer   = issuer.Trim().Truncate(32);
            auth.Username = username.Trim().Truncate(32);

            await _connection.UpdateAsync(auth);
        }
Esempio n. 10
0
        public virtual CredentialViewModel DescribeCredential(Credential credential)
        {
            var           kind          = GetCredentialKind(credential.Type);
            Authenticator authenticator = null;

            if (kind == CredentialKind.External)
            {
                if (string.IsNullOrEmpty(credential.TenantId))
                {
                    string providerName = credential.Type.Split('.')[1];
                    Authenticators.TryGetValue(providerName, out authenticator);
                }
                else
                {
                    authenticator = Authenticators
                                    .Values
                                    .FirstOrDefault(provider => provider.Name.Equals(AzureActiveDirectoryV2Authenticator.DefaultAuthenticationType, StringComparison.OrdinalIgnoreCase));
                }
            }

            var credentialViewModel = new CredentialViewModel
            {
                Key         = credential.Key,
                Type        = credential.Type,
                TypeCaption = FormatCredentialType(credential.Type),
                Identity    = credential.Identity,
                Created     = credential.Created,
                Expires     = credential.Expires,
                Kind        = kind,
                AuthUI      = authenticator?.GetUI(),
                Description = credential.Description,
                Scopes      = credential.Scopes.Select(s => new ScopeViewModel(
                                                           s.Owner?.Username ?? credential.User.Username,
                                                           s.Subject,
                                                           NuGetScopes.Describe(s.AllowedAction)))
                              .ToList(),
                ExpirationDuration = credential.ExpirationTicks != null ? new TimeSpan?(new TimeSpan(credential.ExpirationTicks.Value)) : null,
                RevocationSource   = credential.RevocationSourceKey != null?Enum.GetName(typeof(CredentialRevocationSource), credential.RevocationSourceKey) : null,
            };

            credentialViewModel.HasExpired = IsCredentialExpiredOrNonScopedApiKeyNotUsedInLastDays(credential);

            credentialViewModel.Description = credentialViewModel.IsNonScopedApiKey
                ? ServicesStrings.NonScopedApiKeyDescription : credentialViewModel.Description;

            return(credentialViewModel);
        }
        public async Task Delete(int position)
        {
            var auth = Authenticators.ElementAtOrDefault(position);

            if (auth == null)
            {
                return;
            }

            await _connection.DeleteAsync <Authenticator>(auth.Secret);

            Authenticators.Remove(auth);
            _all.Remove(auth);

            const string sql = "DELETE FROM authenticatorcategory WHERE authenticatorSecret = ?";
            await _connection.ExecuteAsync(sql, auth.Secret);
        }
Esempio n. 12
0
        public async virtual Task <AuthenticateExternalLoginResult> ReadExternalLoginCredential(IOwinContext context)
        {
            var result = await context.Authentication.AuthenticateAsync(AuthenticationTypes.External);

            if (result == null)
            {
                Trace.Information("No external login found.");
                return(new AuthenticateExternalLoginResult());
            }
            var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);

            if (idClaim == null)
            {
                Trace.Error("External Authentication is missing required claim: " + ClaimTypes.NameIdentifier);
                return(new AuthenticateExternalLoginResult());
            }

            var nameClaim = result.Identity.FindFirst(ClaimTypes.Name);

            if (nameClaim == null)
            {
                Trace.Error("External Authentication is missing required claim: " + ClaimTypes.Name);
                return(new AuthenticateExternalLoginResult());
            }

            var    emailClaim  = result.Identity.FindFirst(ClaimTypes.Email);
            string emailSuffix = emailClaim == null ? String.Empty : (" <" + emailClaim.Value + ">");

            Authenticator auther;

            if (!Authenticators.TryGetValue(idClaim.Issuer, out auther))
            {
                auther = null;
            }

            return(new AuthenticateExternalLoginResult()
            {
                Authentication = null,
                ExternalIdentity = result.Identity,
                Authenticator = auther,
                Credential = CredentialBuilder.CreateExternalCredential(idClaim.Issuer, idClaim.Value, nameClaim.Value + emailSuffix)
            });
        }
Esempio n. 13
0
        public Authenticator Get(int position)
        {
            if (Authenticators.ElementAtOrDefault(position) == null)
            {
                return(null);
            }

            var info = Authenticators[position];
            var auth = GetAuthenticator(info);

            if (auth.Type == OtpType.Totp && auth.TimeRenew <= DateTime.Now)
            {
                var secret = Base32.Decode(auth.Secret);
                var totp   = new Totp(secret, auth.Period, auth.Algorithm, auth.Digits);
                auth.Code      = totp.ComputeTotp();
                auth.TimeRenew = DateTime.Now.AddSeconds(totp.RemainingSeconds());
            }

            return(auth);
        }
Esempio n. 14
0
        public async Task Delete(int position)
        {
            if (Authenticators.ElementAtOrDefault(position) == null)
            {
                return;
            }

            var info = Authenticators[position];
            var auth = GetAuthenticator(info);

            await _connection.DeleteAsync <Authenticator>(auth.Secret);

            Authenticators.Remove(info);
            _all.Remove(auth);

            var sql = "DELETE FROM authenticatorcategory WHERE authenticatorSecret = ?";

            object[] args = { auth.Secret };
            await _connection.ExecuteAsync(sql, args);
        }
        public virtual ActionResult Challenge(string providerName, string redirectUrl)
        {
            Authenticator provider;

            if (!Authenticators.TryGetValue(providerName, out provider))
            {
                throw new InvalidOperationException(String.Format(
                                                        CultureInfo.CurrentCulture,
                                                        Strings.UnknownAuthenticationProvider,
                                                        providerName));
            }
            if (!provider.BaseConfig.Enabled)
            {
                throw new InvalidOperationException(String.Format(
                                                        CultureInfo.CurrentCulture,
                                                        Strings.AuthenticationProviderDisabled,
                                                        providerName));
            }

            return(provider.Challenge(redirectUrl));
        }
Esempio n. 16
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            foreach (var application in Applications)
            {
                var name = application.IdentityProviderBinding.Name;
                if (!IdentityProviders.Any(i => i.Name == name))
                {
                    yield return(new ValidationResult($"No identity provider with name '{name}' configured.", new string[] { nameof(Applications) }));
                }

                if (application.AuthenticatorBindings != null)
                {
                    foreach (var authBinding in application.AuthenticatorBindings)
                    {
                        var authName = authBinding.Name;
                        if (Authenticators is null || !Authenticators.Any(a => a.Name == authName))
                        {
                            yield return(new ValidationResult($"No authenticator with name '{authName}' configured.", new string[] { nameof(Applications) }));
                        }
                    }
                }
            }
        }
Esempio n. 17
0
 public AuthManOptions AddAuth <T>() where T : IAuthenticate
 {
     Authenticators.Add(typeof(T));
     return(this);
 }
Esempio n. 18
0
 public AuthManOptions AddAuth(IEnumerable <Type> types)
 {
     // TODO: add validation for IAuthenticate interface
     Authenticators.AddRange(types);
     return(this);
 }
Esempio n. 19
0
 public AuthManOptions AddUserAuth <TUserMan, TUser>() where TUserMan : IUserMan <TUser>
 {
     Authenticators.Add(typeof(TUserMan));
     return(this);
 }
 public int GetPosition(string secret)
 {
     return(Authenticators.FindIndex(a => a.Secret == secret));
 }
Esempio n. 21
0
        public static void Load()
        {
            InitializeDefaults();

            if (!File.Exists(SettingsFile))
            {
                return;
            }

            using (BinaryReader binReader = new BinaryReader(File.OpenRead(SettingsFile)))
            {
                string fileHeader = "";

                for (int i = 0; i < 9; i++)
                {
                    fileHeader += binReader.ReadChar();
                }

                if (fileHeader != "WINBMACFG")
                {
                    return;
                }

                int fileVersion = binReader.ReadInt32();

                if (fileVersion > 4)
                {
                    System.Windows.MessageBox.Show("The settings database was created with a newer version of WinBMA. We were unable to load your settings.", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                    return;
                }

                int numOfAuths = binReader.ReadInt32();

                for (int i = 0; i < numOfAuths; i++)
                {
                    string name         = binReader.ReadString();
                    string serial       = binReader.ReadString();
                    bool?  isRestorable = null;
                    AuthAPI.Security.EncryptionProvider.EncryptionType encType = AuthAPI.Security.EncryptionProvider.EncryptionType.None;
                    int tokenLen = 20;

                    if (fileVersion > 2)
                    {
                        isRestorable = binReader.ReadBoolean();
                        encType      = (AuthAPI.Security.EncryptionProvider.EncryptionType)binReader.ReadByte();
                        tokenLen     = binReader.ReadInt32();
                    }

                    byte[] token = binReader.ReadBytes(tokenLen);

                    Authenticators.Add(new AuthAPI.Authenticator(name, serial, token, isRestorable, encType));
                }

                if (fileVersion < 3)
                {
                    for (int i = 0; i < 2; i++)
                    {
                        DateTime storedLastSync = DateTime.FromBinary(binReader.ReadInt64());
                        Int64    storedOffset   = binReader.ReadInt64();

                        if (storedLastSync > _lastSyncTime)
                        {
                            _lastSyncTime = storedLastSync;
                            _timeOffset   = storedOffset;
                        }
                    }
                }
                else
                {
                    _lastSyncTime = DateTime.FromBinary(binReader.ReadInt64());
                    _timeOffset   = binReader.ReadInt64();
                }

                if (fileVersion == 1)
                {
                    return;
                }

                SelectedAuthenticatorIndex = binReader.ReadInt32();

                if (fileVersion == 2)
                {
                    return;
                }

                _autoSync = binReader.ReadBoolean();

                _alwaysOnTop         = binReader.ReadBoolean();
                _autoCopyToClipboard = binReader.ReadBoolean();
                _theme = binReader.ReadString();

                _checkForUpdates = binReader.ReadBoolean();
                _lastUpdateCheck = DateTime.FromBinary(binReader.ReadInt64());

                if (fileVersion == 3)
                {
                    return;
                }

                _hotkeyEnabled   = binReader.ReadBoolean();
                _hotkeyModifiers = (Utilities.SystemHotKey.ModifierKeys)binReader.ReadByte();
                _hotkey          = (Utilities.Keys)binReader.ReadInt32();
            }
        }