1
0
mirror of https://github.com/bitwarden/server.git synced 2025-06-30 15:42:48 -05:00

[PM-8107] Remove Duo v2 from server (#4934)

refactor(TwoFactorAuthentication): Remove references to old Duo SDK version 2 code and replace them with the Duo SDK version 4 supported library DuoUniversal code.

Increased unit test coverage in the Two Factor Authentication code space. We opted to use DI instead of Inheritance for the Duo and OrganizaitonDuo two factor tokens to increase testability, since creating a testing mock of the Duo.Client was non-trivial.

Reviewed-by: @JaredSnider-Bitwarden
This commit is contained in:
Ike
2024-11-18 15:58:05 -08:00
committed by GitHub
parent e16cad50b1
commit ab5d4738d6
36 changed files with 1412 additions and 1369 deletions

View File

@ -4,15 +4,14 @@ using Bit.Api.Auth.Models.Response.TwoFactor;
using Bit.Api.Models.Request;
using Bit.Api.Models.Response;
using Bit.Core.Auth.Enums;
using Bit.Core.Auth.Identity.TokenProviders;
using Bit.Core.Auth.LoginFeatures.PasswordlessLogin.Interfaces;
using Bit.Core.Auth.Models.Business.Tokenables;
using Bit.Core.Auth.Utilities;
using Bit.Core.Context;
using Bit.Core.Entities;
using Bit.Core.Exceptions;
using Bit.Core.Repositories;
using Bit.Core.Services;
using Bit.Core.Settings;
using Bit.Core.Tokens;
using Bit.Core.Utilities;
using Fido2NetLib;
@ -29,11 +28,10 @@ public class TwoFactorController : Controller
private readonly IUserService _userService;
private readonly IOrganizationRepository _organizationRepository;
private readonly IOrganizationService _organizationService;
private readonly GlobalSettings _globalSettings;
private readonly UserManager<User> _userManager;
private readonly ICurrentContext _currentContext;
private readonly IVerifyAuthRequestCommand _verifyAuthRequestCommand;
private readonly IFeatureService _featureService;
private readonly IDuoUniversalTokenService _duoUniversalTokenService;
private readonly IDataProtectorTokenFactory<TwoFactorAuthenticatorUserVerificationTokenable> _twoFactorAuthenticatorDataProtector;
private readonly IDataProtectorTokenFactory<SsoEmail2faSessionTokenable> _ssoEmailTwoFactorSessionDataProtector;
@ -41,22 +39,20 @@ public class TwoFactorController : Controller
IUserService userService,
IOrganizationRepository organizationRepository,
IOrganizationService organizationService,
GlobalSettings globalSettings,
UserManager<User> userManager,
ICurrentContext currentContext,
IVerifyAuthRequestCommand verifyAuthRequestCommand,
IFeatureService featureService,
IDuoUniversalTokenService duoUniversalConfigService,
IDataProtectorTokenFactory<TwoFactorAuthenticatorUserVerificationTokenable> twoFactorAuthenticatorDataProtector,
IDataProtectorTokenFactory<SsoEmail2faSessionTokenable> ssoEmailTwoFactorSessionDataProtector)
{
_userService = userService;
_organizationRepository = organizationRepository;
_organizationService = organizationService;
_globalSettings = globalSettings;
_userManager = userManager;
_currentContext = currentContext;
_verifyAuthRequestCommand = verifyAuthRequestCommand;
_featureService = featureService;
_duoUniversalTokenService = duoUniversalConfigService;
_twoFactorAuthenticatorDataProtector = twoFactorAuthenticatorDataProtector;
_ssoEmailTwoFactorSessionDataProtector = ssoEmailTwoFactorSessionDataProtector;
}
@ -184,21 +180,7 @@ public class TwoFactorController : Controller
public async Task<TwoFactorDuoResponseModel> PutDuo([FromBody] UpdateTwoFactorDuoRequestModel model)
{
var user = await CheckAsync(model, true);
try
{
// for backwards compatibility - will be removed with PM-8107
DuoApi duoApi = null;
if (model.ClientId != null && model.ClientSecret != null)
{
duoApi = new DuoApi(model.ClientId, model.ClientSecret, model.Host);
}
else
{
duoApi = new DuoApi(model.IntegrationKey, model.SecretKey, model.Host);
}
await duoApi.JSONApiCall("GET", "/auth/v2/check");
}
catch (DuoException)
if (!await _duoUniversalTokenService.ValidateDuoConfiguration(model.ClientSecret, model.ClientId, model.Host))
{
throw new BadRequestException(
"Duo configuration settings are not valid. Please re-check the Duo Admin panel.");
@ -241,21 +223,7 @@ public class TwoFactorController : Controller
}
var organization = await _organizationRepository.GetByIdAsync(orgIdGuid) ?? throw new NotFoundException();
try
{
// for backwards compatibility - will be removed with PM-8107
DuoApi duoApi = null;
if (model.ClientId != null && model.ClientSecret != null)
{
duoApi = new DuoApi(model.ClientId, model.ClientSecret, model.Host);
}
else
{
duoApi = new DuoApi(model.IntegrationKey, model.SecretKey, model.Host);
}
await duoApi.JSONApiCall("GET", "/auth/v2/check");
}
catch (DuoException)
if (!await _duoUniversalTokenService.ValidateDuoConfiguration(model.ClientId, model.ClientSecret, model.Host))
{
throw new BadRequestException(
"Duo configuration settings are not valid. Please re-check the Duo Admin panel.");

View File

@ -2,8 +2,8 @@
using Bit.Api.Auth.Models.Request.Accounts;
using Bit.Core.AdminConsole.Entities;
using Bit.Core.Auth.Enums;
using Bit.Core.Auth.Identity.TokenProviders;
using Bit.Core.Auth.Models;
using Bit.Core.Auth.Utilities;
using Bit.Core.Entities;
using Fido2NetLib;
@ -43,21 +43,16 @@ public class UpdateTwoFactorAuthenticatorRequestModel : SecretVerificationReques
public class UpdateTwoFactorDuoRequestModel : SecretVerificationRequestModel, IValidatableObject
{
/*
To support both v2 and v4 we need to remove the required annotation from the properties.
todo - the required annotation will be added back in PM-8107.
String lengths based on Duo's documentation
https://github.com/duosecurity/duo_universal_csharp/blob/main/DuoUniversal/Client.cs
*/
[StringLength(50)]
public string ClientId { get; set; }
[StringLength(50)]
public string ClientSecret { get; set; }
//todo - will remove SKey and IKey with PM-8107
[StringLength(50)]
public string IntegrationKey { get; set; }
//todo - will remove SKey and IKey with PM-8107
[StringLength(50)]
public string SecretKey { get; set; }
[Required]
[StringLength(50)]
[StringLength(20, MinimumLength = 20, ErrorMessage = "Client Id must be exactly 20 characters.")]
public string ClientId { get; set; }
[Required]
[StringLength(40, MinimumLength = 40, ErrorMessage = "Client Secret must be exactly 40 characters.")]
public string ClientSecret { get; set; }
[Required]
public string Host { get; set; }
public User ToUser(User existingUser)
@ -65,22 +60,17 @@ public class UpdateTwoFactorDuoRequestModel : SecretVerificationRequestModel, IV
var providers = existingUser.GetTwoFactorProviders();
if (providers == null)
{
providers = new Dictionary<TwoFactorProviderType, TwoFactorProvider>();
providers = [];
}
else if (providers.ContainsKey(TwoFactorProviderType.Duo))
{
providers.Remove(TwoFactorProviderType.Duo);
}
Temporary_SyncDuoParams();
providers.Add(TwoFactorProviderType.Duo, new TwoFactorProvider
{
MetaData = new Dictionary<string, object>
{
//todo - will remove SKey and IKey with PM-8107
["SKey"] = SecretKey,
["IKey"] = IntegrationKey,
["ClientSecret"] = ClientSecret,
["ClientId"] = ClientId,
["Host"] = Host
@ -96,22 +86,17 @@ public class UpdateTwoFactorDuoRequestModel : SecretVerificationRequestModel, IV
var providers = existingOrg.GetTwoFactorProviders();
if (providers == null)
{
providers = new Dictionary<TwoFactorProviderType, TwoFactorProvider>();
providers = [];
}
else if (providers.ContainsKey(TwoFactorProviderType.OrganizationDuo))
{
providers.Remove(TwoFactorProviderType.OrganizationDuo);
}
Temporary_SyncDuoParams();
providers.Add(TwoFactorProviderType.OrganizationDuo, new TwoFactorProvider
{
MetaData = new Dictionary<string, object>
{
//todo - will remove SKey and IKey with PM-8107
["SKey"] = SecretKey,
["IKey"] = IntegrationKey,
["ClientSecret"] = ClientSecret,
["ClientId"] = ClientId,
["Host"] = Host
@ -124,34 +109,22 @@ public class UpdateTwoFactorDuoRequestModel : SecretVerificationRequestModel, IV
public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!DuoApi.ValidHost(Host))
var results = new List<ValidationResult>();
if (string.IsNullOrWhiteSpace(ClientId))
{
yield return new ValidationResult("Host is invalid.", [nameof(Host)]);
results.Add(new ValidationResult("ClientId is required.", [nameof(ClientId)]));
}
if (string.IsNullOrWhiteSpace(ClientSecret) && string.IsNullOrWhiteSpace(ClientId) &&
string.IsNullOrWhiteSpace(SecretKey) && string.IsNullOrWhiteSpace(IntegrationKey))
{
yield return new ValidationResult("Neither v2 or v4 values are valid.", [nameof(IntegrationKey), nameof(SecretKey), nameof(ClientSecret), nameof(ClientId)]);
}
}
/*
use this method to ensure that both v2 params and v4 params are in sync
todo will be removed in pm-8107
*/
private void Temporary_SyncDuoParams()
{
// Even if IKey and SKey exist prioritize v4 params ClientId and ClientSecret
if (!string.IsNullOrWhiteSpace(ClientSecret) && !string.IsNullOrWhiteSpace(ClientId))
if (string.IsNullOrWhiteSpace(ClientSecret))
{
SecretKey = ClientSecret;
IntegrationKey = ClientId;
results.Add(new ValidationResult("ClientSecret is required.", [nameof(ClientSecret)]));
}
else if (!string.IsNullOrWhiteSpace(SecretKey) && !string.IsNullOrWhiteSpace(IntegrationKey))
if (string.IsNullOrWhiteSpace(Host) || !DuoUniversalTokenService.ValidDuoHost(Host))
{
ClientSecret = SecretKey;
ClientId = IntegrationKey;
results.Add(new ValidationResult("Host is invalid.", [nameof(Host)]));
}
return results;
}
}

View File

@ -13,37 +13,26 @@ public class TwoFactorDuoResponseModel : ResponseModel
public TwoFactorDuoResponseModel(User user)
: base(ResponseObj)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
ArgumentNullException.ThrowIfNull(user);
var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Duo);
Build(provider);
}
public TwoFactorDuoResponseModel(Organization org)
public TwoFactorDuoResponseModel(Organization organization)
: base(ResponseObj)
{
if (org == null)
{
throw new ArgumentNullException(nameof(org));
}
ArgumentNullException.ThrowIfNull(organization);
var provider = org.GetTwoFactorProvider(TwoFactorProviderType.OrganizationDuo);
var provider = organization.GetTwoFactorProvider(TwoFactorProviderType.OrganizationDuo);
Build(provider);
}
public bool Enabled { get; set; }
public string Host { get; set; }
//TODO - will remove SecretKey with PM-8107
public string SecretKey { get; set; }
//TODO - will remove IntegrationKey with PM-8107
public string IntegrationKey { get; set; }
public string ClientSecret { get; set; }
public string ClientId { get; set; }
// updated build to assist in the EDD migration for the Duo 2FA provider
private void Build(TwoFactorProvider provider)
{
if (provider?.MetaData != null && provider.MetaData.Count > 0)
@ -54,36 +43,13 @@ public class TwoFactorDuoResponseModel : ResponseModel
{
Host = (string)host;
}
//todo - will remove SKey and IKey with PM-8107
// check Skey and IKey first if they exist
if (provider.MetaData.TryGetValue("SKey", out var sKey))
{
ClientSecret = MaskKey((string)sKey);
SecretKey = MaskKey((string)sKey);
}
if (provider.MetaData.TryGetValue("IKey", out var iKey))
{
IntegrationKey = (string)iKey;
ClientId = (string)iKey;
}
// Even if IKey and SKey exist prioritize v4 params ClientId and ClientSecret
if (provider.MetaData.TryGetValue("ClientSecret", out var clientSecret))
{
if (!string.IsNullOrWhiteSpace((string)clientSecret))
{
ClientSecret = MaskKey((string)clientSecret);
SecretKey = MaskKey((string)clientSecret);
}
ClientSecret = MaskSecret((string)clientSecret);
}
if (provider.MetaData.TryGetValue("ClientId", out var clientId))
{
if (!string.IsNullOrWhiteSpace((string)clientId))
{
ClientId = (string)clientId;
IntegrationKey = (string)clientId;
}
ClientId = (string)clientId;
}
}
else
@ -92,30 +58,7 @@ public class TwoFactorDuoResponseModel : ResponseModel
}
}
/*
use this method to ensure that both v2 params and v4 params are in sync
todo will be removed in pm-8107
*/
private void Temporary_SyncDuoParams()
{
// Even if IKey and SKey exist prioritize v4 params ClientId and ClientSecret
if (!string.IsNullOrWhiteSpace(ClientSecret) && !string.IsNullOrWhiteSpace(ClientId))
{
SecretKey = ClientSecret;
IntegrationKey = ClientId;
}
else if (!string.IsNullOrWhiteSpace(SecretKey) && !string.IsNullOrWhiteSpace(IntegrationKey))
{
ClientSecret = SecretKey;
ClientId = IntegrationKey;
}
else
{
throw new InvalidDataException("Invalid Duo parameters.");
}
}
private static string MaskKey(string key)
private static string MaskSecret(string key)
{
if (string.IsNullOrWhiteSpace(key) || key.Length <= 6)
{

View File

@ -23,7 +23,6 @@ using Microsoft.OpenApi.Models;
using Bit.SharedWeb.Utilities;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Bit.Core.Auth.Identity;
using Bit.Core.Auth.UserFeatures;
using Bit.Core.Entities;
using Bit.Core.Billing.Extensions;
@ -32,10 +31,10 @@ using Bit.Core.Tools.Entities;
using Bit.Core.Vault.Entities;
using Bit.Api.Auth.Models.Request.WebAuthn;
using Bit.Core.Auth.Models.Data;
using Bit.Core.Auth.Identity.TokenProviders;
using Bit.Core.Tools.ReportFeatures;
#if !OSS
using Bit.Commercial.Core.SecretsManager;
using Bit.Commercial.Core.Utilities;

View File

@ -1,86 +0,0 @@
using Bit.Core.Auth.Enums;
using Bit.Core.Auth.Models;
using Bit.Core.Auth.Utilities.Duo;
using Bit.Core.Entities;
using Bit.Core.Services;
using Bit.Core.Settings;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
namespace Bit.Core.Auth.Identity;
public class DuoWebTokenProvider : IUserTwoFactorTokenProvider<User>
{
private readonly IServiceProvider _serviceProvider;
private readonly GlobalSettings _globalSettings;
public DuoWebTokenProvider(
IServiceProvider serviceProvider,
GlobalSettings globalSettings)
{
_serviceProvider = serviceProvider;
_globalSettings = globalSettings;
}
public async Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<User> manager, User user)
{
var userService = _serviceProvider.GetRequiredService<IUserService>();
if (!(await userService.CanAccessPremium(user)))
{
return false;
}
var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Duo);
if (!HasProperMetaData(provider))
{
return false;
}
return await userService.TwoFactorProviderIsEnabledAsync(TwoFactorProviderType.Duo, user);
}
public async Task<string> GenerateAsync(string purpose, UserManager<User> manager, User user)
{
var userService = _serviceProvider.GetRequiredService<IUserService>();
if (!(await userService.CanAccessPremium(user)))
{
return null;
}
var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Duo);
if (!HasProperMetaData(provider))
{
return null;
}
var signatureRequest = DuoWeb.SignRequest((string)provider.MetaData["IKey"],
(string)provider.MetaData["SKey"], _globalSettings.Duo.AKey, user.Email);
return signatureRequest;
}
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;
}
var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Duo);
if (!HasProperMetaData(provider))
{
return false;
}
var response = DuoWeb.VerifyResponse((string)provider.MetaData["IKey"], (string)provider.MetaData["SKey"],
_globalSettings.Duo.AKey, token);
return response == user.Email;
}
private bool HasProperMetaData(TwoFactorProvider provider)
{
return provider?.MetaData != null && provider.MetaData.ContainsKey("IKey") &&
provider.MetaData.ContainsKey("SKey") && provider.MetaData.ContainsKey("Host");
}
}

View File

@ -1,76 +0,0 @@
using Bit.Core.AdminConsole.Entities;
using Bit.Core.Auth.Enums;
using Bit.Core.Auth.Models;
using Bit.Core.Auth.Utilities.Duo;
using Bit.Core.Entities;
using Bit.Core.Settings;
namespace Bit.Core.Auth.Identity;
public interface IOrganizationDuoWebTokenProvider : IOrganizationTwoFactorTokenProvider { }
public class OrganizationDuoWebTokenProvider : IOrganizationDuoWebTokenProvider
{
private readonly GlobalSettings _globalSettings;
public OrganizationDuoWebTokenProvider(GlobalSettings globalSettings)
{
_globalSettings = globalSettings;
}
public Task<bool> CanGenerateTwoFactorTokenAsync(Organization organization)
{
if (organization == null || !organization.Enabled || !organization.Use2fa)
{
return Task.FromResult(false);
}
var provider = organization.GetTwoFactorProvider(TwoFactorProviderType.OrganizationDuo);
var canGenerate = organization.TwoFactorProviderIsEnabled(TwoFactorProviderType.OrganizationDuo)
&& HasProperMetaData(provider);
return Task.FromResult(canGenerate);
}
public Task<string> GenerateAsync(Organization organization, User user)
{
if (organization == null || !organization.Enabled || !organization.Use2fa)
{
return Task.FromResult<string>(null);
}
var provider = organization.GetTwoFactorProvider(TwoFactorProviderType.OrganizationDuo);
if (!HasProperMetaData(provider))
{
return Task.FromResult<string>(null);
}
var signatureRequest = DuoWeb.SignRequest(provider.MetaData["IKey"].ToString(),
provider.MetaData["SKey"].ToString(), _globalSettings.Duo.AKey, user.Email);
return Task.FromResult(signatureRequest);
}
public Task<bool> ValidateAsync(string token, Organization organization, User user)
{
if (organization == null || !organization.Enabled || !organization.Use2fa)
{
return Task.FromResult(false);
}
var provider = organization.GetTwoFactorProvider(TwoFactorProviderType.OrganizationDuo);
if (!HasProperMetaData(provider))
{
return Task.FromResult(false);
}
var response = DuoWeb.VerifyResponse(provider.MetaData["IKey"].ToString(),
provider.MetaData["SKey"].ToString(), _globalSettings.Duo.AKey, token);
return Task.FromResult(response == user.Email);
}
private bool HasProperMetaData(TwoFactorProvider provider)
{
return provider?.MetaData != null && provider.MetaData.ContainsKey("IKey") &&
provider.MetaData.ContainsKey("SKey") && provider.MetaData.ContainsKey("Host");
}
}

View File

@ -1,172 +0,0 @@
using Bit.Core.Auth.Models;
using Bit.Core.Auth.Models.Business.Tokenables;
using Bit.Core.Context;
using Bit.Core.Entities;
using Bit.Core.Settings;
using Bit.Core.Tokens;
using Microsoft.Extensions.Logging;
using Duo = DuoUniversal;
namespace Bit.Core.Auth.Identity;
/*
PM-5156 addresses tech debt
Interface to allow for DI, will end up being removed as part of the removal of the old Duo SDK v2 flows.
This service is to support SDK v4 flows for Duo. At some time in the future we will need
to combine this service with the DuoWebTokenProvider and OrganizationDuoWebTokenProvider to support SDK v4.
*/
public interface ITemporaryDuoWebV4SDKService
{
Task<string> GenerateAsync(TwoFactorProvider provider, User user);
Task<bool> ValidateAsync(string token, TwoFactorProvider provider, User user);
}
public class TemporaryDuoWebV4SDKService : ITemporaryDuoWebV4SDKService
{
private readonly ICurrentContext _currentContext;
private readonly GlobalSettings _globalSettings;
private readonly IDataProtectorTokenFactory<DuoUserStateTokenable> _tokenDataFactory;
private readonly ILogger<TemporaryDuoWebV4SDKService> _logger;
/// <summary>
/// Constructor for the DuoUniversalPromptService. Used to supplement v2 implementation of Duo with v4 SDK
/// </summary>
/// <param name="currentContext">used to fetch initiating Client</param>
/// <param name="globalSettings">used to fetch vault URL for Redirect URL</param>
public TemporaryDuoWebV4SDKService(
ICurrentContext currentContext,
GlobalSettings globalSettings,
IDataProtectorTokenFactory<DuoUserStateTokenable> tokenDataFactory,
ILogger<TemporaryDuoWebV4SDKService> logger)
{
_currentContext = currentContext;
_globalSettings = globalSettings;
_tokenDataFactory = tokenDataFactory;
_logger = logger;
}
/// <summary>
/// Provider agnostic (either Duo or OrganizationDuo) method to generate a Duo Auth URL
/// </summary>
/// <param name="provider">Either Duo or OrganizationDuo</param>
/// <param name="user">self</param>
/// <returns>AuthUrl for DUO SDK v4</returns>
public async Task<string> GenerateAsync(TwoFactorProvider provider, User user)
{
if (!HasProperMetaData(provider))
{
if (!HasProperMetaData_SDKV2(provider))
{
return null;
}
}
var duoClient = await BuildDuoClientAsync(provider);
if (duoClient == null)
{
return null;
}
var state = _tokenDataFactory.Protect(new DuoUserStateTokenable(user));
var authUrl = duoClient.GenerateAuthUri(user.Email, state);
return authUrl;
}
/// <summary>
/// Validates Duo SDK v4 response
/// </summary>
/// <param name="token">response form Duo</param>
/// <param name="provider">TwoFactorProviderType Duo or OrganizationDuo</param>
/// <param name="user">self</param>
/// <returns>true or false depending on result of verification</returns>
public async Task<bool> ValidateAsync(string token, TwoFactorProvider provider, User user)
{
if (!HasProperMetaData(provider))
{
if (!HasProperMetaData_SDKV2(provider))
{
return false;
}
}
var duoClient = await BuildDuoClientAsync(provider);
if (duoClient == null)
{
return false;
}
var parts = token.Split("|");
var authCode = parts[0];
var state = parts[1];
_tokenDataFactory.TryUnprotect(state, out var tokenable);
if (!tokenable.Valid || !tokenable.TokenIsValid(user))
{
return false;
}
// duoClient compares the email from the received IdToken with user.Email to verify a bad actor hasn't used
// their authCode with a victims credentials
var res = await duoClient.ExchangeAuthorizationCodeFor2faResult(authCode, user.Email);
// If the result of the exchange doesn't throw an exception and it's not null, then it's valid
return res.AuthResult.Result == "allow";
}
private bool HasProperMetaData(TwoFactorProvider provider)
{
return provider?.MetaData != null && provider.MetaData.ContainsKey("ClientId") &&
provider.MetaData.ContainsKey("ClientSecret") && provider.MetaData.ContainsKey("Host");
}
/// <summary>
/// Checks if the metadata for SDK V2 is present.
/// Transitional method to support Duo during v4 database rename
/// </summary>
/// <param name="provider">The TwoFactorProvider object to check.</param>
/// <returns>True if the provider has the proper metadata; otherwise, false.</returns>
private bool HasProperMetaData_SDKV2(TwoFactorProvider provider)
{
if (provider?.MetaData != null &&
provider.MetaData.TryGetValue("IKey", out var iKey) &&
provider.MetaData.TryGetValue("SKey", out var sKey) &&
provider.MetaData.ContainsKey("Host"))
{
provider.MetaData.Add("ClientId", iKey);
provider.MetaData.Add("ClientSecret", sKey);
return true;
}
else
{
return false;
}
}
/// <summary>
/// Generates a Duo.Client object for use with Duo SDK v4. This combines the health check and the client generation
/// </summary>
/// <param name="provider">TwoFactorProvider Duo or OrganizationDuo</param>
/// <returns>Duo.Client object or null</returns>
private async Task<Duo.Client> BuildDuoClientAsync(TwoFactorProvider provider)
{
// Fetch Client name from header value since duo auth can be initiated from multiple clients and we want
// to redirect back to the initiating client
_currentContext.HttpContext.Request.Headers.TryGetValue("Bitwarden-Client-Name", out var bitwardenClientName);
var redirectUri = string.Format("{0}/duo-redirect-connector.html?client={1}",
_globalSettings.BaseServiceUri.Vault, bitwardenClientName.FirstOrDefault() ?? "web");
var client = new Duo.ClientBuilder(
(string)provider.MetaData["ClientId"],
(string)provider.MetaData["ClientSecret"],
(string)provider.MetaData["Host"],
redirectUri).Build();
if (!await client.DoHealthCheck(true))
{
_logger.LogError("Unable to connect to Duo. Health check failed.");
return null;
}
return client;
}
}

View File

@ -6,7 +6,7 @@ using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using OtpNet;
namespace Bit.Core.Auth.Identity;
namespace Bit.Core.Auth.Identity.TokenProviders;
public class AuthenticatorTokenProvider : IUserTwoFactorTokenProvider<User>
{

View File

@ -0,0 +1,102 @@
using Bit.Core.Auth.Enums;
using Bit.Core.Auth.Models;
using Bit.Core.Auth.Models.Business.Tokenables;
using Bit.Core.Entities;
using Bit.Core.Services;
using Bit.Core.Tokens;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Duo = DuoUniversal;
namespace Bit.Core.Auth.Identity.TokenProviders;
public class DuoUniversalTokenProvider(
IServiceProvider serviceProvider,
IDataProtectorTokenFactory<DuoUserStateTokenable> tokenDataFactory,
IDuoUniversalTokenService duoUniversalTokenService) : IUserTwoFactorTokenProvider<User>
{
/// <summary>
/// We need the IServiceProvider to resolve the IUserService. There is a complex dependency dance
/// occurring between IUserService, which extends the UserManager<User>, and the usage of the
/// UserManager<User> within this class. Trying to resolve the IUserService using the DI pipeline
/// will not allow the server to start and it will hang and give no helpful indication as to the problem.
/// </summary>
private readonly IServiceProvider _serviceProvider = serviceProvider;
private readonly IDataProtectorTokenFactory<DuoUserStateTokenable> _tokenDataFactory = tokenDataFactory;
private readonly IDuoUniversalTokenService _duoUniversalTokenService = duoUniversalTokenService;
public async Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<User> manager, User user)
{
var userService = _serviceProvider.GetRequiredService<IUserService>();
var provider = await GetDuoTwoFactorProvider(user, userService);
if (provider == null)
{
return false;
}
return await userService.TwoFactorProviderIsEnabledAsync(TwoFactorProviderType.Duo, user);
}
public async Task<string> GenerateAsync(string purpose, UserManager<User> manager, User user)
{
var duoClient = await GetDuoClientAsync(user);
if (duoClient == null)
{
return null;
}
return _duoUniversalTokenService.GenerateAuthUrl(duoClient, _tokenDataFactory, user);
}
public async Task<bool> ValidateAsync(string purpose, string token, UserManager<User> manager, User user)
{
var duoClient = await GetDuoClientAsync(user);
if (duoClient == null)
{
return false;
}
return await _duoUniversalTokenService.RequestDuoValidationAsync(duoClient, _tokenDataFactory, user, token);
}
/// <summary>
/// Get the Duo Two Factor Provider for the user if they have access to Duo
/// </summary>
/// <param name="user">Active User</param>
/// <returns>null or Duo TwoFactorProvider</returns>
private async Task<TwoFactorProvider> GetDuoTwoFactorProvider(User user, IUserService userService)
{
if (!await userService.CanAccessPremium(user))
{
return null;
}
var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Duo);
if (!_duoUniversalTokenService.HasProperDuoMetadata(provider))
{
return null;
}
return provider;
}
/// <summary>
/// Uses the User to fetch a valid TwoFactorProvider and use it to create a Duo.Client
/// </summary>
/// <param name="user">active user</param>
/// <returns>null or Duo TwoFactorProvider</returns>
private async Task<Duo.Client> GetDuoClientAsync(User user)
{
var userService = _serviceProvider.GetRequiredService<IUserService>();
var provider = await GetDuoTwoFactorProvider(user, userService);
if (provider == null)
{
return null;
}
var duoClient = await _duoUniversalTokenService.BuildDuoTwoFactorClientAsync(provider);
if (duoClient == null)
{
return null;
}
return duoClient;
}
}

View File

@ -0,0 +1,177 @@
using Bit.Core.Auth.Models;
using Bit.Core.Auth.Models.Business.Tokenables;
using Bit.Core.Context;
using Bit.Core.Entities;
using Bit.Core.Settings;
using Bit.Core.Tokens;
using Duo = DuoUniversal;
namespace Bit.Core.Auth.Identity.TokenProviders;
/// <summary>
/// OrganizationDuo and Duo TwoFactorProviderTypes both use the same flows so both of those Token Providers will
/// have this class injected to utilize these methods
/// </summary>
public interface IDuoUniversalTokenService
{
/// <summary>
/// Generates the Duo Auth URL for the user to be redirected to Duo for 2FA. This
/// Auth URL also lets the Duo Service know where to redirect the user back to after
/// the 2FA process is complete.
/// </summary>
/// <param name="duoClient">A not null valid Duo.Client</param>
/// <param name="tokenDataFactory">This service creates the state token for added security</param>
/// <param name="user">currently active user</param>
/// <returns>a URL in string format</returns>
string GenerateAuthUrl(
Duo.Client duoClient,
IDataProtectorTokenFactory<DuoUserStateTokenable> tokenDataFactory,
User user);
/// <summary>
/// Makes the request to Duo to validate the authCode and state token
/// </summary>
/// <param name="duoClient">A not null valid Duo.Client</param>
/// <param name="tokenDataFactory">Factory for decrypting the state</param>
/// <param name="user">self</param>
/// <param name="token">token received from the client</param>
/// <returns>boolean based on result from Duo</returns>
Task<bool> RequestDuoValidationAsync(
Duo.Client duoClient,
IDataProtectorTokenFactory<DuoUserStateTokenable> tokenDataFactory,
User user,
string token);
/// <summary>
/// Generates a Duo.Client object for use with Duo SDK v4. This method is to validate a Duo configuration
/// when adding or updating the configuration. This method makes a web request to Duo to verify the configuration.
/// Throws exception if configuration is invalid.
/// </summary>
/// <param name="clientSecret">Duo client Secret</param>
/// <param name="clientId">Duo client Id</param>
/// <param name="host">Duo host</param>
/// <returns>Boolean</returns>
Task<bool> ValidateDuoConfiguration(string clientSecret, string clientId, string host);
/// <summary>
/// Checks provider for the correct Duo metadata: ClientId, ClientSecret, and Host. Does no validation on the data.
/// it is assumed to be correct. The only way to have the data written to the Database is after verification
/// occurs.
/// </summary>
/// <param name="provider">Host being checked for proper data</param>
/// <returns>true if all three are present; false if one is missing or the host is incorrect</returns>
bool HasProperDuoMetadata(TwoFactorProvider provider);
/// <summary>
/// Generates a Duo.Client object for use with Duo SDK v4. This combines the health check and the client generation.
/// This method is made public so that it is easier to test. If the method was private then there would not be an
/// easy way to mock the response. Since this makes a web request it is difficult to mock.
/// </summary>
/// <param name="provider">TwoFactorProvider Duo or OrganizationDuo</param>
/// <returns>Duo.Client object or null</returns>
Task<Duo.Client> BuildDuoTwoFactorClientAsync(TwoFactorProvider provider);
}
public class DuoUniversalTokenService(
ICurrentContext currentContext,
GlobalSettings globalSettings) : IDuoUniversalTokenService
{
private readonly ICurrentContext _currentContext = currentContext;
private readonly GlobalSettings _globalSettings = globalSettings;
public string GenerateAuthUrl(
Duo.Client duoClient,
IDataProtectorTokenFactory<DuoUserStateTokenable> tokenDataFactory,
User user)
{
var state = tokenDataFactory.Protect(new DuoUserStateTokenable(user));
var authUrl = duoClient.GenerateAuthUri(user.Email, state);
return authUrl;
}
public async Task<bool> RequestDuoValidationAsync(
Duo.Client duoClient,
IDataProtectorTokenFactory<DuoUserStateTokenable> tokenDataFactory,
User user,
string token)
{
var parts = token.Split("|");
var authCode = parts[0];
var state = parts[1];
tokenDataFactory.TryUnprotect(state, out var tokenable);
if (!tokenable.Valid || !tokenable.TokenIsValid(user))
{
return false;
}
// duoClient compares the email from the received IdToken with user.Email to verify a bad actor hasn't used
// their authCode with a victims credentials
var res = await duoClient.ExchangeAuthorizationCodeFor2faResult(authCode, user.Email);
// If the result of the exchange doesn't throw an exception and it's not null, then it's valid
return res.AuthResult.Result == "allow";
}
public async Task<bool> ValidateDuoConfiguration(string clientSecret, string clientId, string host)
{
// Do some simple checks to ensure data integrity
if (!ValidDuoHost(host) ||
string.IsNullOrWhiteSpace(clientSecret) ||
string.IsNullOrWhiteSpace(clientId))
{
return false;
}
// The AuthURI is not important for this health check so we pass in a non-empty string
var client = new Duo.ClientBuilder(clientId, clientSecret, host, "non-empty").Build();
// This could throw an exception, the false flag will allow the exception to bubble up
return await client.DoHealthCheck(false);
}
public bool HasProperDuoMetadata(TwoFactorProvider provider)
{
return provider?.MetaData != null &&
provider.MetaData.ContainsKey("ClientId") &&
provider.MetaData.ContainsKey("ClientSecret") &&
provider.MetaData.ContainsKey("Host") &&
ValidDuoHost((string)provider.MetaData["Host"]);
}
/// <summary>
/// Checks the host string to make sure it meets Duo's Guidelines before attempting to create a Duo.Client.
/// </summary>
/// <param name="host">string representing the Duo Host</param>
/// <returns>true if the host is valid false otherwise</returns>
public static bool ValidDuoHost(string host)
{
if (Uri.TryCreate($"https://{host}", UriKind.Absolute, out var uri))
{
return (string.IsNullOrWhiteSpace(uri.PathAndQuery) || uri.PathAndQuery == "/") &&
uri.Host.StartsWith("api-") &&
(uri.Host.EndsWith(".duosecurity.com") || uri.Host.EndsWith(".duofederal.com"));
}
return false;
}
public async Task<Duo.Client> BuildDuoTwoFactorClientAsync(TwoFactorProvider provider)
{
// Fetch Client name from header value since duo auth can be initiated from multiple clients and we want
// to redirect back to the initiating client
_currentContext.HttpContext.Request.Headers.TryGetValue("Bitwarden-Client-Name", out var bitwardenClientName);
var redirectUri = string.Format("{0}/duo-redirect-connector.html?client={1}",
_globalSettings.BaseServiceUri.Vault, bitwardenClientName.FirstOrDefault() ?? "web");
var client = new Duo.ClientBuilder(
(string)provider.MetaData["ClientId"],
(string)provider.MetaData["ClientSecret"],
(string)provider.MetaData["Host"],
redirectUri).Build();
if (!await client.DoHealthCheck(false))
{
return null;
}
return client;
}
}

View File

@ -5,7 +5,7 @@ using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
namespace Bit.Core.Auth.Identity;
namespace Bit.Core.Auth.Identity.TokenProviders;
public class EmailTokenProvider : IUserTwoFactorTokenProvider<User>
{

View File

@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
namespace Bit.Core.Auth.Identity;
namespace Bit.Core.Auth.Identity.TokenProviders;
public class EmailTwoFactorTokenProvider : EmailTokenProvider
{

View File

@ -1,7 +1,7 @@
using Bit.Core.AdminConsole.Entities;
using Bit.Core.Entities;
namespace Bit.Core.Auth.Identity;
namespace Bit.Core.Auth.Identity.TokenProviders;
public interface IOrganizationTwoFactorTokenProvider
{

View File

@ -0,0 +1,81 @@
using Bit.Core.AdminConsole.Entities;
using Bit.Core.Auth.Enums;
using Bit.Core.Auth.Models;
using Bit.Core.Auth.Models.Business.Tokenables;
using Bit.Core.Entities;
using Bit.Core.Tokens;
using Duo = DuoUniversal;
namespace Bit.Core.Auth.Identity.TokenProviders;
public interface IOrganizationDuoUniversalTokenProvider : IOrganizationTwoFactorTokenProvider { }
public class OrganizationDuoUniversalTokenProvider(
IDataProtectorTokenFactory<DuoUserStateTokenable> tokenDataFactory,
IDuoUniversalTokenService duoUniversalTokenService) : IOrganizationDuoUniversalTokenProvider
{
private readonly IDataProtectorTokenFactory<DuoUserStateTokenable> _tokenDataFactory = tokenDataFactory;
private readonly IDuoUniversalTokenService _duoUniversalTokenService = duoUniversalTokenService;
public Task<bool> CanGenerateTwoFactorTokenAsync(Organization organization)
{
var provider = GetDuoTwoFactorProvider(organization);
if (provider != null && provider.Enabled)
{
return Task.FromResult(true);
}
return Task.FromResult(false);
}
public async Task<string> GenerateAsync(Organization organization, User user)
{
var duoClient = await GetDuoClientAsync(organization);
if (duoClient == null)
{
return null;
}
return _duoUniversalTokenService.GenerateAuthUrl(duoClient, _tokenDataFactory, user);
}
public async Task<bool> ValidateAsync(string token, Organization organization, User user)
{
var duoClient = await GetDuoClientAsync(organization);
if (duoClient == null)
{
return false;
}
return await _duoUniversalTokenService.RequestDuoValidationAsync(duoClient, _tokenDataFactory, user, token);
}
private TwoFactorProvider GetDuoTwoFactorProvider(Organization organization)
{
if (organization == null || !organization.Enabled || !organization.Use2fa)
{
return null;
}
var provider = organization.GetTwoFactorProvider(TwoFactorProviderType.OrganizationDuo);
if (!_duoUniversalTokenService.HasProperDuoMetadata(provider))
{
return null;
}
return provider;
}
private async Task<Duo.Client> GetDuoClientAsync(Organization organization)
{
var provider = GetDuoTwoFactorProvider(organization);
if (provider == null)
{
return null;
}
var duoClient = await _duoUniversalTokenService.BuildDuoTwoFactorClientAsync(provider);
if (duoClient == null)
{
return null;
}
return duoClient;
}
}

View File

@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Bit.Core.Auth.Identity;
namespace Bit.Core.Auth.Identity.TokenProviders;
public class TwoFactorRememberTokenProvider : DataProtectorTokenProvider<User>
{

View File

@ -10,7 +10,7 @@ using Fido2NetLib.Objects;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
namespace Bit.Core.Auth.Identity;
namespace Bit.Core.Auth.Identity.TokenProviders;
public class WebAuthnTokenProvider : IUserTwoFactorTokenProvider<User>
{

View File

@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using YubicoDotNetClient;
namespace Bit.Core.Auth.Identity;
namespace Bit.Core.Auth.Identity.TokenProviders;
public class YubicoOtpTokenProvider : IUserTwoFactorTokenProvider<User>
{
@ -24,7 +24,7 @@ public class YubicoOtpTokenProvider : IUserTwoFactorTokenProvider<User>
public async Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<User> manager, User user)
{
var userService = _serviceProvider.GetRequiredService<IUserService>();
if (!(await userService.CanAccessPremium(user)))
if (!await userService.CanAccessPremium(user))
{
return false;
}
@ -46,7 +46,7 @@ public class YubicoOtpTokenProvider : IUserTwoFactorTokenProvider<User>
public async Task<bool> ValidateAsync(string purpose, string token, UserManager<User> manager, User user)
{
var userService = _serviceProvider.GetRequiredService<IUserService>();
if (!(await userService.CanAccessPremium(user)))
if (!await userService.CanAccessPremium(user))
{
return false;
}

View File

@ -1,277 +0,0 @@
/*
Original source modified from https://github.com/duosecurity/duo_api_csharp
=============================================================================
=============================================================================
Copyright (c) 2018 Duo Security
All rights reserved
*/
using System.Globalization;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Web;
using Bit.Core.Models.Api.Response.Duo;
namespace Bit.Core.Auth.Utilities;
public class DuoApi
{
private const string UrlScheme = "https";
private const string UserAgent = "Bitwarden_DuoAPICSharp/1.0 (.NET Core)";
private readonly string _host;
private readonly string _ikey;
private readonly string _skey;
private readonly HttpClient _httpClient = new();
public DuoApi(string ikey, string skey, string host)
{
_ikey = ikey;
_skey = skey;
_host = host;
if (!ValidHost(host))
{
throw new DuoException("Invalid Duo host configured.", new ArgumentException(nameof(host)));
}
}
public static bool ValidHost(string host)
{
if (Uri.TryCreate($"https://{host}", UriKind.Absolute, out var uri))
{
return (string.IsNullOrWhiteSpace(uri.PathAndQuery) || uri.PathAndQuery == "/") &&
uri.Host.StartsWith("api-") &&
(uri.Host.EndsWith(".duosecurity.com") || uri.Host.EndsWith(".duofederal.com"));
}
return false;
}
public static string CanonicalizeParams(Dictionary<string, string> parameters)
{
var ret = new List<string>();
foreach (var pair in parameters)
{
var p = string.Format("{0}={1}", HttpUtility.UrlEncode(pair.Key), HttpUtility.UrlEncode(pair.Value));
// Signatures require upper-case hex digits.
p = Regex.Replace(p, "(%[0-9A-Fa-f][0-9A-Fa-f])", c => c.Value.ToUpperInvariant());
// Escape only the expected characters.
p = Regex.Replace(p, "([!'()*])", c => "%" + Convert.ToByte(c.Value[0]).ToString("X"));
p = p.Replace("%7E", "~");
// UrlEncode converts space (" ") to "+". The
// signature algorithm requires "%20" instead. Actual
// + has already been replaced with %2B.
p = p.Replace("+", "%20");
ret.Add(p);
}
ret.Sort(StringComparer.Ordinal);
return string.Join("&", ret.ToArray());
}
protected string CanonicalizeRequest(string method, string path, string canonParams, string date)
{
string[] lines = {
date,
method.ToUpperInvariant(),
_host.ToLower(),
path,
canonParams,
};
return string.Join("\n", lines);
}
public string Sign(string method, string path, string canonParams, string date)
{
var canon = CanonicalizeRequest(method, path, canonParams, date);
var sig = HmacSign(canon);
var auth = string.Concat(_ikey, ':', sig);
return string.Concat("Basic ", Encode64(auth));
}
/// <param name="timeout">The request timeout, in milliseconds.
/// Specify 0 to use the system-default timeout. Use caution if
/// you choose to specify a custom timeout - some API
/// calls (particularly in the Auth APIs) will not
/// return a response until an out-of-band authentication process
/// has completed. In some cases, this may take as much as a
/// small number of minutes.</param>
private async Task<(string result, HttpStatusCode statusCode)> ApiCall(string method, string path, Dictionary<string, string> parameters, int timeout)
{
if (parameters == null)
{
parameters = new Dictionary<string, string>();
}
var canonParams = CanonicalizeParams(parameters);
var query = string.Empty;
if (!method.Equals("POST") && !method.Equals("PUT"))
{
if (parameters.Count > 0)
{
query = "?" + canonParams;
}
}
var url = $"{UrlScheme}://{_host}{path}{query}";
var dateString = RFC822UtcNow();
var auth = Sign(method, path, canonParams, dateString);
var request = new HttpRequestMessage
{
Method = new HttpMethod(method),
RequestUri = new Uri(url),
};
request.Headers.Add("Authorization", auth);
request.Headers.Add("X-Duo-Date", dateString);
request.Headers.UserAgent.ParseAdd(UserAgent);
if (timeout > 0)
{
_httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
}
if (method.Equals("POST") || method.Equals("PUT"))
{
request.Content = new StringContent(canonParams, Encoding.UTF8, "application/x-www-form-urlencoded");
}
var response = await _httpClient.SendAsync(request);
var result = await response.Content.ReadAsStringAsync();
var statusCode = response.StatusCode;
return (result, statusCode);
}
public async Task<Response> JSONApiCall(string method, string path, Dictionary<string, string> parameters = null)
{
return await JSONApiCall(method, path, parameters, 0);
}
/// <param name="timeout">The request timeout, in milliseconds.
/// Specify 0 to use the system-default timeout. Use caution if
/// you choose to specify a custom timeout - some API
/// calls (particularly in the Auth APIs) will not
/// return a response until an out-of-band authentication process
/// has completed. In some cases, this may take as much as a
/// small number of minutes.</param>
private async Task<Response> JSONApiCall(string method, string path, Dictionary<string, string> parameters, int timeout)
{
var (res, statusCode) = await ApiCall(method, path, parameters, timeout);
try
{
var obj = JsonSerializer.Deserialize<DuoResponseModel>(res);
if (obj.Stat == "OK")
{
return obj.Response;
}
throw new ApiException(obj.Code ?? 0, (int)statusCode, obj.Message, obj.MessageDetail);
}
catch (ApiException)
{
throw;
}
catch (Exception e)
{
throw new BadResponseException((int)statusCode, e);
}
}
private int? ToNullableInt(string s)
{
int i;
if (int.TryParse(s, out i))
{
return i;
}
return null;
}
private string HmacSign(string data)
{
var keyBytes = Encoding.ASCII.GetBytes(_skey);
var dataBytes = Encoding.ASCII.GetBytes(data);
using (var hmac = new HMACSHA1(keyBytes))
{
var hash = hmac.ComputeHash(dataBytes);
var hex = BitConverter.ToString(hash);
return hex.Replace("-", string.Empty).ToLower();
}
}
private static string Encode64(string plaintext)
{
var plaintextBytes = Encoding.ASCII.GetBytes(plaintext);
return Convert.ToBase64String(plaintextBytes);
}
private static string RFC822UtcNow()
{
// Can't use the "zzzz" format because it adds a ":"
// between the offset's hours and minutes.
var dateString = DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture);
var offset = 0;
var zone = "+" + offset.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0');
dateString += " " + zone.PadRight(5, '0');
return dateString;
}
}
public class DuoException : Exception
{
public int HttpStatus { get; private set; }
public DuoException(string message, Exception inner)
: base(message, inner)
{ }
public DuoException(int httpStatus, string message, Exception inner)
: base(message, inner)
{
HttpStatus = httpStatus;
}
}
public class ApiException : DuoException
{
public int Code { get; private set; }
public string ApiMessage { get; private set; }
public string ApiMessageDetail { get; private set; }
public ApiException(int code, int httpStatus, string apiMessage, string apiMessageDetail)
: base(httpStatus, FormatMessage(code, apiMessage, apiMessageDetail), null)
{
Code = code;
ApiMessage = apiMessage;
ApiMessageDetail = apiMessageDetail;
}
private static string FormatMessage(int code, string apiMessage, string apiMessageDetail)
{
return string.Format("Duo API Error {0}: '{1}' ('{2}')", code, apiMessage, apiMessageDetail);
}
}
public class BadResponseException : DuoException
{
public BadResponseException(int httpStatus, Exception inner)
: base(httpStatus, FormatMessage(httpStatus, inner), inner)
{ }
private static string FormatMessage(int httpStatus, Exception inner)
{
var innerMessage = "(null)";
if (inner != null)
{
innerMessage = string.Format("'{0}'", inner.Message);
}
return string.Format("Got error {0} with HTTP Status {1}", innerMessage, httpStatus);
}
}

View File

@ -1,240 +0,0 @@
/*
Original source modified from https://github.com/duosecurity/duo_dotnet
=============================================================================
=============================================================================
ref: https://github.com/duosecurity/duo_dotnet/blob/master/LICENSE
Copyright (c) 2011, Duo Security, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Security.Cryptography;
using System.Text;
namespace Bit.Core.Auth.Utilities.Duo;
public static class DuoWeb
{
private const string DuoProfix = "TX";
private const string AppPrefix = "APP";
private const string AuthPrefix = "AUTH";
private const int DuoExpire = 300;
private const int AppExpire = 3600;
private const int IKeyLength = 20;
private const int SKeyLength = 40;
private const int AKeyLength = 40;
public static string ErrorUser = "ERR|The username passed to sign_request() is invalid.";
public static string ErrorIKey = "ERR|The Duo integration key passed to sign_request() is invalid.";
public static string ErrorSKey = "ERR|The Duo secret key passed to sign_request() is invalid.";
public static string ErrorAKey = "ERR|The application secret key passed to sign_request() must be at least " +
"40 characters.";
public static string ErrorUnknown = "ERR|An unknown error has occurred.";
// throw on invalid bytes
private static Encoding _encoding = new UTF8Encoding(false, true);
private static DateTime _epoc = new DateTime(1970, 1, 1);
/// <summary>
/// Generate a signed request for Duo authentication.
/// The returned value should be passed into the Duo.init() call
/// in the rendered web page used for Duo authentication.
/// </summary>
/// <param name="ikey">Duo integration key</param>
/// <param name="skey">Duo secret key</param>
/// <param name="akey">Application secret key</param>
/// <param name="username">Primary-authenticated username</param>
/// <param name="currentTime">(optional) The current UTC time</param>
/// <returns>signed request</returns>
public static string SignRequest(string ikey, string skey, string akey, string username,
DateTime? currentTime = null)
{
string duoSig;
string appSig;
var currentTimeValue = currentTime ?? DateTime.UtcNow;
if (username == string.Empty)
{
return ErrorUser;
}
if (username.Contains("|"))
{
return ErrorUser;
}
if (ikey.Length != IKeyLength)
{
return ErrorIKey;
}
if (skey.Length != SKeyLength)
{
return ErrorSKey;
}
if (akey.Length < AKeyLength)
{
return ErrorAKey;
}
try
{
duoSig = SignVals(skey, username, ikey, DuoProfix, DuoExpire, currentTimeValue);
appSig = SignVals(akey, username, ikey, AppPrefix, AppExpire, currentTimeValue);
}
catch
{
return ErrorUnknown;
}
return $"{duoSig}:{appSig}";
}
/// <summary>
/// Validate the signed response returned from Duo.
/// Returns the username of the authenticated user, or null.
/// </summary>
/// <param name="ikey">Duo integration key</param>
/// <param name="skey">Duo secret key</param>
/// <param name="akey">Application secret key</param>
/// <param name="sigResponse">The signed response POST'ed to the server</param>
/// <param name="currentTime">(optional) The current UTC time</param>
/// <returns>authenticated username, or null</returns>
public static string VerifyResponse(string ikey, string skey, string akey, string sigResponse,
DateTime? currentTime = null)
{
string authUser = null;
string appUser = null;
var currentTimeValue = currentTime ?? DateTime.UtcNow;
try
{
var sigs = sigResponse.Split(':');
var authSig = sigs[0];
var appSig = sigs[1];
authUser = ParseVals(skey, authSig, AuthPrefix, ikey, currentTimeValue);
appUser = ParseVals(akey, appSig, AppPrefix, ikey, currentTimeValue);
}
catch
{
return null;
}
if (authUser != appUser)
{
return null;
}
return authUser;
}
private static string SignVals(string key, string username, string ikey, string prefix, long expire,
DateTime currentTime)
{
var ts = (long)(currentTime - _epoc).TotalSeconds;
expire = ts + expire;
var val = $"{username}|{ikey}|{expire.ToString()}";
var cookie = $"{prefix}|{Encode64(val)}";
var sig = Sign(key, cookie);
return $"{cookie}|{sig}";
}
private static string ParseVals(string key, string val, string prefix, string ikey, DateTime currentTime)
{
var ts = (long)(currentTime - _epoc).TotalSeconds;
var parts = val.Split('|');
if (parts.Length != 3)
{
return null;
}
var uPrefix = parts[0];
var uB64 = parts[1];
var uSig = parts[2];
var sig = Sign(key, $"{uPrefix}|{uB64}");
if (Sign(key, sig) != Sign(key, uSig))
{
return null;
}
if (uPrefix != prefix)
{
return null;
}
var cookie = Decode64(uB64);
var cookieParts = cookie.Split('|');
if (cookieParts.Length != 3)
{
return null;
}
var username = cookieParts[0];
var uIKey = cookieParts[1];
var expire = cookieParts[2];
if (uIKey != ikey)
{
return null;
}
var expireTs = Convert.ToInt32(expire);
if (ts >= expireTs)
{
return null;
}
return username;
}
private static string Sign(string skey, string data)
{
var keyBytes = Encoding.ASCII.GetBytes(skey);
var dataBytes = Encoding.ASCII.GetBytes(data);
using (var hmac = new HMACSHA1(keyBytes))
{
var hash = hmac.ComputeHash(dataBytes);
var hex = BitConverter.ToString(hash);
return hex.Replace("-", "").ToLower();
}
}
private static string Encode64(string plaintext)
{
var plaintextBytes = _encoding.GetBytes(plaintext);
return Convert.ToBase64String(plaintextBytes);
}
private static string Decode64(string encoded)
{
var plaintextBytes = Convert.FromBase64String(encoded);
return _encoding.GetString(plaintextBytes);
}
}

View File

@ -1,9 +1,7 @@

using System.Text.Json;
using Bit.Core;
using System.Text.Json;
using Bit.Core.AdminConsole.Entities;
using Bit.Core.Auth.Enums;
using Bit.Core.Auth.Identity;
using Bit.Core.Auth.Identity.TokenProviders;
using Bit.Core.Auth.Models;
using Bit.Core.Auth.Models.Business.Tokenables;
using Bit.Core.Context;
@ -52,8 +50,7 @@ public interface ITwoFactorAuthenticationValidator
public class TwoFactorAuthenticationValidator(
IUserService userService,
UserManager<User> userManager,
IOrganizationDuoWebTokenProvider organizationDuoWebTokenProvider,
ITemporaryDuoWebV4SDKService duoWebV4SDKService,
IOrganizationDuoUniversalTokenProvider organizationDuoWebTokenProvider,
IFeatureService featureService,
IApplicationCacheService applicationCacheService,
IOrganizationUserRepository organizationUserRepository,
@ -63,8 +60,7 @@ public class TwoFactorAuthenticationValidator(
{
private readonly IUserService _userService = userService;
private readonly UserManager<User> _userManager = userManager;
private readonly IOrganizationDuoWebTokenProvider _organizationDuoWebTokenProvider = organizationDuoWebTokenProvider;
private readonly ITemporaryDuoWebV4SDKService _duoWebV4SDKService = duoWebV4SDKService;
private readonly IOrganizationDuoUniversalTokenProvider _organizationDuoUniversalTokenProvider = organizationDuoWebTokenProvider;
private readonly IFeatureService _featureService = featureService;
private readonly IApplicationCacheService _applicationCacheService = applicationCacheService;
private readonly IOrganizationUserRepository _organizationUserRepository = organizationUserRepository;
@ -153,17 +149,7 @@ public class TwoFactorAuthenticationValidator(
{
if (organization.TwoFactorProviderIsEnabled(type))
{
// DUO SDK v4 Update: try to validate the token - PM-5156 addresses tech debt
if (_featureService.IsEnabled(FeatureFlagKeys.DuoRedirect))
{
if (!token.Contains(':'))
{
// We have to send the provider to the DuoWebV4SDKService to create the DuoClient
var provider = organization.GetTwoFactorProvider(TwoFactorProviderType.OrganizationDuo);
return await _duoWebV4SDKService.ValidateAsync(token, provider, user);
}
}
return await _organizationDuoWebTokenProvider.ValidateAsync(token, organization, user);
return await _organizationDuoUniversalTokenProvider.ValidateAsync(token, organization, user);
}
return false;
}
@ -181,19 +167,6 @@ public class TwoFactorAuthenticationValidator(
{
return false;
}
// DUO SDK v4 Update: try to validate the token - PM-5156 addresses tech debt
if (_featureService.IsEnabled(FeatureFlagKeys.DuoRedirect))
{
if (type == TwoFactorProviderType.Duo)
{
if (!token.Contains(':'))
{
// We have to send the provider to the DuoWebV4SDKService to create the DuoClient
var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Duo);
return await _duoWebV4SDKService.ValidateAsync(token, provider, user);
}
}
}
return await _userManager.VerifyTwoFactorTokenAsync(user,
CoreHelpers.CustomProviderName(type), token);
default:
@ -248,10 +221,11 @@ public class TwoFactorAuthenticationValidator(
in the future the `AuthUrl` will be the generated "token" - PM-8107
*/
if (type == TwoFactorProviderType.OrganizationDuo &&
await _organizationDuoWebTokenProvider.CanGenerateTwoFactorTokenAsync(organization))
await _organizationDuoUniversalTokenProvider.CanGenerateTwoFactorTokenAsync(organization))
{
twoFactorParams.Add("Host", provider.MetaData["Host"]);
twoFactorParams.Add("AuthUrl", await _duoWebV4SDKService.GenerateAsync(provider, user));
twoFactorParams.Add("AuthUrl",
await _organizationDuoUniversalTokenProvider.GenerateAsync(organization, user));
return twoFactorParams;
}
@ -261,13 +235,9 @@ public class TwoFactorAuthenticationValidator(
CoreHelpers.CustomProviderName(type));
switch (type)
{
/*
Note: Duo is in the midst of being updated to use the UserManager built-in TwoFactor class
in the future the `AuthUrl` will be the generated "token" - PM-8107
*/
case TwoFactorProviderType.Duo:
twoFactorParams.Add("Host", provider.MetaData["Host"]);
twoFactorParams.Add("AuthUrl", await _duoWebV4SDKService.GenerateAsync(provider, user));
twoFactorParams.Add("AuthUrl", token);
break;
case TwoFactorProviderType.WebAuthn:
if (token != null)

View File

@ -10,6 +10,7 @@ using Bit.Core.AdminConsole.Services.Implementations;
using Bit.Core.AdminConsole.Services.NoopImplementations;
using Bit.Core.Auth.Enums;
using Bit.Core.Auth.Identity;
using Bit.Core.Auth.Identity.TokenProviders;
using Bit.Core.Auth.IdentityServer;
using Bit.Core.Auth.LoginFeatures;
using Bit.Core.Auth.Models.Business.Tokenables;
@ -113,6 +114,7 @@ public static class ServiceCollectionExtensions
services.AddSingleton<IDeviceService, DeviceService>();
services.AddScoped<ISsoConfigService, SsoConfigService>();
services.AddScoped<IAuthRequestService, AuthRequestService>();
services.AddScoped<IDuoUniversalTokenService, DuoUniversalTokenService>();
services.AddScoped<ISendService, SendService>();
services.AddLoginServices();
services.AddScoped<IOrganizationDomainService, OrganizationDomainService>();
@ -388,8 +390,7 @@ public static class ServiceCollectionExtensions
public static IdentityBuilder AddCustomIdentityServices(
this IServiceCollection services, GlobalSettings globalSettings)
{
services.AddScoped<IOrganizationDuoWebTokenProvider, OrganizationDuoWebTokenProvider>();
services.AddScoped<ITemporaryDuoWebV4SDKService, TemporaryDuoWebV4SDKService>();
services.AddScoped<IOrganizationDuoUniversalTokenProvider, OrganizationDuoUniversalTokenProvider>();
services.Configure<PasswordHasherOptions>(options => options.IterationCount = 100000);
services.Configure<TwoFactorRememberTokenProviderOptions>(options =>
{
@ -430,7 +431,7 @@ public static class ServiceCollectionExtensions
CoreHelpers.CustomProviderName(TwoFactorProviderType.Email))
.AddTokenProvider<YubicoOtpTokenProvider>(
CoreHelpers.CustomProviderName(TwoFactorProviderType.YubiKey))
.AddTokenProvider<DuoWebTokenProvider>(
.AddTokenProvider<DuoUniversalTokenProvider>(
CoreHelpers.CustomProviderName(TwoFactorProviderType.Duo))
.AddTokenProvider<TwoFactorRememberTokenProvider>(
CoreHelpers.CustomProviderName(TwoFactorProviderType.Remember))