* Remove U2F support and JS

* fix final changes

* fix more final stuff
This commit is contained in:
Andrew Camilleri 2021-04-28 09:22:09 +02:00 committed by GitHub
parent 270bd98a10
commit 5fe3c1c61f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
26 changed files with 9 additions and 1646 deletions

View file

@ -9,6 +9,7 @@ namespace BTCPayServer.Data
{
public bool RequiresEmailConfirmation { get; set; }
public List<StoredFile> StoredFiles { get; set; }
[Obsolete("U2F support has been replace with FIDO2")]
public List<U2FDevice> U2FDevices { get; set; }
public List<APIKeyData> APIKeys { get; set; }
public DateTimeOffset? Created { get; set; }

View file

@ -23,11 +23,12 @@ namespace BTCPayServer.Data
internal static void OnModelCreating(ModelBuilder builder)
{
#pragma warning disable CS0618 // Type or member is obsolete
builder.Entity<U2FDevice>()
.HasOne(o => o.ApplicationUser)
.WithMany(i => i.U2FDevices)
.HasForeignKey(i => i.ApplicationUserId).OnDelete(DeleteBehavior.Cascade);
#pragma warning restore CS0618 // Type or member is obsolete
}
}
}

View file

@ -2,7 +2,6 @@
using Microsoft.EntityFrameworkCore.Migrations;
using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace BTCPayServer.Migrations
{

View file

@ -1,133 +0,0 @@
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BTCPayServer.Controllers;
using BTCPayServer.Data;
using BTCPayServer.Models.AccountViewModels;
using BTCPayServer.Tests.Logging;
using BTCPayServer.U2F;
using BTCPayServer.U2F.Models;
using Microsoft.AspNetCore.Mvc;
using NBitcoin;
using U2F.Core.Models;
using U2F.Core.Utils;
using Xunit;
using Xunit.Abstractions;
namespace BTCPayServer.Tests
{
public class U2FTests
{
public const int TestTimeout = 60_000;
public U2FTests(ITestOutputHelper helper)
{
Logs.Tester = new XUnitLog(helper) { Name = "Tests" };
Logs.LogProvider = new XUnitLogProvider(helper);
}
[Fact(Timeout = TestTimeout)]
[Trait("Integration", "Integration")]
public async Task U2ftest()
{
using (var tester = ServerTester.Create())
{
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
user.RegisterDerivationScheme("BTC");
var accountController = tester.PayTester.GetController<AccountController>();
var manageController = user.GetController<ManageController>();
var mock = new MockU2FService(tester.PayTester.GetService<ApplicationDbContextFactory>());
manageController._u2FService = mock;
accountController._u2FService = mock;
Assert
.IsType<RedirectToActionResult>(await accountController.Login(new LoginViewModel()
{
Email = user.RegisterDetails.Email,
Password = user.RegisterDetails.Password
}));
Assert.Empty(Assert.IsType<U2FAuthenticationViewModel>(Assert
.IsType<ViewResult>(await manageController.U2FAuthentication()).Model).Devices);
var addDeviceVM = Assert.IsType<AddU2FDeviceViewModel>(Assert
.IsType<ViewResult>(manageController.AddU2FDevice("testdevice")).Model);
Assert.NotEmpty(addDeviceVM.Challenge);
Assert.Equal("testdevice", addDeviceVM.Name);
Assert.NotEmpty(addDeviceVM.Version);
Assert.Null(addDeviceVM.DeviceResponse);
var devReg = new DeviceRegistration(Guid.NewGuid().ToByteArray(), RandomUtils.GetBytes(65),
Guid.NewGuid().ToByteArray(), 1);
mock.GetDevReg = () => devReg;
mock.StartedAuthentication = () =>
new StartedAuthentication("chocolate", addDeviceVM.AppId,
devReg.KeyHandle.ByteArrayToBase64String());
addDeviceVM.DeviceResponse = new RegisterResponse("ss",
Convert.ToBase64String(Encoding.UTF8.GetBytes("{typ:'x', challenge: 'fff'}"))).ToJson();
Assert
.IsType<RedirectToActionResult>(await manageController.AddU2FDevice(addDeviceVM));
Assert.Single(Assert.IsType<U2FAuthenticationViewModel>(Assert
.IsType<ViewResult>(await manageController.U2FAuthentication()).Model).Devices);
var secondaryLoginViewModel = Assert.IsType<SecondaryLoginViewModel>(Assert
.IsType<ViewResult>(await accountController.Login(new LoginViewModel()
{
Email = user.RegisterDetails.Email,
Password = user.RegisterDetails.Password
})).Model);
Assert.NotNull(secondaryLoginViewModel.LoginWithU2FViewModel);
Assert.Single(secondaryLoginViewModel.LoginWithU2FViewModel.Challenges);
Assert.Equal(secondaryLoginViewModel.LoginWithU2FViewModel.Challenge,
secondaryLoginViewModel.LoginWithU2FViewModel.Challenges.First().challenge);
secondaryLoginViewModel.LoginWithU2FViewModel.DeviceResponse = new AuthenticateResponse(
Convert.ToBase64String(Encoding.UTF8.GetBytes(
"{typ:'x', challenge: '" + secondaryLoginViewModel.LoginWithU2FViewModel.Challenge + "'}")),
"dd", devReg.KeyHandle.ByteArrayToBase64String()).ToJson();
Assert
.IsType<RedirectToActionResult>(
await accountController.LoginWithU2F(secondaryLoginViewModel.LoginWithU2FViewModel));
}
}
public class MockU2FService : U2FService
{
public Func<DeviceRegistration> GetDevReg;
public Func<StartedAuthentication> StartedAuthentication;
public MockU2FService(ApplicationDbContextFactory contextFactory) : base(contextFactory)
{
}
protected override StartedRegistration StartDeviceRegistrationCore(string appId)
{
return global::U2F.Core.Crypto.U2F.StartRegistration(appId);
}
protected override DeviceRegistration FinishRegistrationCore(StartedRegistration startedRegistration,
RegisterResponse registerResponse)
{
return GetDevReg();
}
protected override StartedAuthentication StartAuthenticationCore(string appId, U2FDevice registeredDevice)
{
return StartedAuthentication();
}
protected override void FinishAuthenticationCore(StartedAuthentication authentication,
AuthenticateResponse authenticateResponse, DeviceRegistration registration)
{
}
}
}
}

View file

@ -84,7 +84,6 @@
<PackageReference Include="TwentyTwenty.Storage.Azure" Version="2.12.1" />
<PackageReference Include="TwentyTwenty.Storage.Google" Version="2.12.1" />
<PackageReference Include="TwentyTwenty.Storage.Local" Version="2.12.1" />
<PackageReference Include="U2F.Core" Version="1.0.4" />
<PackageReference Include="YamlDotNet" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.1" Condition="'$(RazorCompileOnBuild)' != 'true'" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.1" />
@ -139,7 +138,6 @@
<Folder Include="wwwroot\vendor\clipboard.js\" />
<Folder Include="wwwroot\vendor\highlightjs\" />
<Folder Include="wwwroot\vendor\summernote" />
<Folder Include="wwwroot\vendor\u2f" />
<Folder Include="wwwroot\vendor\vue-qrcode-reader" />
</ItemGroup>

View file

@ -11,8 +11,6 @@ using BTCPayServer.Fido2.Models;
using BTCPayServer.Logging;
using BTCPayServer.Models.AccountViewModels;
using BTCPayServer.Services;
using BTCPayServer.U2F;
using BTCPayServer.U2F.Models;
using Fido2NetLib;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
@ -21,7 +19,6 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using NicolasDorier.RateLimits;
using U2F.Core.Exceptions;
namespace BTCPayServer.Controllers
{
@ -35,7 +32,6 @@ namespace BTCPayServer.Controllers
readonly SettingsRepository _SettingsRepository;
readonly Configuration.BTCPayServerOptions _Options;
private readonly BTCPayServerEnvironment _btcPayServerEnvironment;
public U2FService _u2FService;
private readonly Fido2Service _fido2Service;
private readonly EventAggregator _eventAggregator;
readonly ILogger _logger;
@ -47,7 +43,6 @@ namespace BTCPayServer.Controllers
SettingsRepository settingsRepository,
Configuration.BTCPayServerOptions options,
BTCPayServerEnvironment btcPayServerEnvironment,
U2FService u2FService,
EventAggregator eventAggregator,
Fido2Service fido2Service)
{
@ -57,7 +52,6 @@ namespace BTCPayServer.Controllers
_SettingsRepository = settingsRepository;
_Options = options;
_btcPayServerEnvironment = btcPayServerEnvironment;
_u2FService = u2FService;
_fido2Service = fido2Service;
_eventAggregator = eventAggregator;
_logger = Logs.PayServer;
@ -126,9 +120,8 @@ namespace BTCPayServer.Controllers
return View(model);
}
var u2fDevices = await _u2FService.HasDevices(user.Id);
var fido2Devices = await _fido2Service.HasCredentials(user.Id);
if (!await _userManager.IsLockedOutAsync(user) && u2fDevices || fido2Devices)
if (!await _userManager.IsLockedOutAsync(user) && fido2Devices)
{
if (await _userManager.CheckPasswordAsync(user, model.Password))
{
@ -147,7 +140,6 @@ namespace BTCPayServer.Controllers
return View("SecondaryLogin", new SecondaryLoginViewModel()
{
LoginWith2FaViewModel = twoFModel,
LoginWithU2FViewModel = u2fDevices? await BuildU2FViewModel(model.RememberMe, user) : null,
LoginWithFido2ViewModel = fido2Devices? await BuildFido2ViewModel(model.RememberMe, user): null,
});
}
@ -193,27 +185,6 @@ namespace BTCPayServer.Controllers
return View(model);
}
private async Task<LoginWithU2FViewModel> BuildU2FViewModel(bool rememberMe, ApplicationUser user)
{
if (_btcPayServerEnvironment.IsSecure)
{
var u2fChallenge = await _u2FService.GenerateDeviceChallenges(user.Id,
Request.GetAbsoluteUriNoPathBase().ToString().TrimEnd('/'));
return new LoginWithU2FViewModel()
{
Version = u2fChallenge[0].version,
Challenge = u2fChallenge[0].challenge,
Challenges = u2fChallenge,
AppId = u2fChallenge[0].appId,
UserId = user.Id,
RememberMe = rememberMe
};
}
return null;
}
private async Task<LoginWithFido2ViewModel> BuildFido2ViewModel(bool rememberMe, ApplicationUser user)
{
if (_btcPayServerEnvironment.IsSecure)
@ -263,7 +234,7 @@ namespace BTCPayServer.Controllers
errorMessage = "Invalid login attempt.";
}
catch (U2fException e)
catch (Fido2VerificationException e)
{
errorMessage = e.Message;
}
@ -273,7 +244,6 @@ namespace BTCPayServer.Controllers
return View("SecondaryLogin", new SecondaryLoginViewModel()
{
LoginWithFido2ViewModel = viewModel,
LoginWithU2FViewModel = (await _u2FService.HasDevices(user.Id)) ? await BuildU2FViewModel(viewModel.RememberMe, user) : null,
LoginWith2FaViewModel = !user.TwoFactorEnabled
? null
: new LoginWith2faViewModel()
@ -282,57 +252,6 @@ namespace BTCPayServer.Controllers
}
});
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginWithU2F(LoginWithU2FViewModel viewModel, string returnUrl = null)
{
if (!CanLoginOrRegister())
{
return RedirectToAction("Login");
}
ViewData["ReturnUrl"] = returnUrl;
var user = await _userManager.FindByIdAsync(viewModel.UserId);
if (user == null)
{
return NotFound();
}
var errorMessage = string.Empty;
try
{
if (await _u2FService.AuthenticateUser(viewModel.UserId, viewModel.DeviceResponse))
{
await _signInManager.SignInAsync(user, viewModel.RememberMe, "U2F");
_logger.LogInformation("User logged in.");
return RedirectToLocal(returnUrl);
}
errorMessage = "Invalid login attempt.";
}
catch (U2fException e)
{
errorMessage = e.Message;
}
ModelState.AddModelError(string.Empty, errorMessage);
return View("SecondaryLogin", new SecondaryLoginViewModel()
{
LoginWithU2FViewModel = viewModel,
LoginWith2FaViewModel = !user.TwoFactorEnabled
? null
: new LoginWith2faViewModel()
{
RememberMe = viewModel.RememberMe
}
});
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> LoginWith2fa(bool rememberMe, string returnUrl = null)
@ -355,7 +274,6 @@ namespace BTCPayServer.Controllers
return View("SecondaryLogin", new SecondaryLoginViewModel()
{
LoginWith2FaViewModel = new LoginWith2faViewModel { RememberMe = rememberMe },
LoginWithU2FViewModel = (await _u2FService.HasDevices(user.Id)) ? await BuildU2FViewModel(rememberMe, user) : null,
LoginWithFido2ViewModel = (await _fido2Service.HasCredentials(user.Id)) ? await BuildFido2ViewModel(rememberMe, user) : null,
});
}
@ -402,7 +320,6 @@ namespace BTCPayServer.Controllers
return View("SecondaryLogin", new SecondaryLoginViewModel()
{
LoginWith2FaViewModel = model,
LoginWithU2FViewModel = (await _u2FService.HasDevices(user.Id)) ? await BuildU2FViewModel(rememberMe, user) : null,
LoginWithFido2ViewModel = (await _fido2Service.HasCredentials(user.Id)) ? await BuildFido2ViewModel(rememberMe, user) : null,
});
}

View file

@ -1,83 +0,0 @@
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Models;
using BTCPayServer.U2F.Models;
using Microsoft.AspNetCore.Mvc;
using U2F.Core.Exceptions;
namespace BTCPayServer.Controllers
{
public partial class ManageController
{
[HttpGet]
public async Task<IActionResult> U2FAuthentication()
{
return View(new U2FAuthenticationViewModel()
{
Devices = await _u2FService.GetDevices(_userManager.GetUserId(User))
});
}
[HttpGet]
public async Task<IActionResult> RemoveU2FDevice(string id)
{
await _u2FService.RemoveDevice(id, _userManager.GetUserId(User));
return RedirectToAction("U2FAuthentication", new
{
StatusMessage = "Device removed"
});
}
[HttpGet]
public IActionResult AddU2FDevice(string name)
{
if (!_btcPayServerEnvironment.IsSecure)
{
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Severity = StatusMessageModel.StatusSeverity.Error,
Message = "Cannot register U2F device while not on https or tor"
});
return RedirectToAction("U2FAuthentication");
}
var serverRegisterResponse = _u2FService.StartDeviceRegistration(_userManager.GetUserId(User),
Request.GetAbsoluteUriNoPathBase().ToString().TrimEnd('/'));
return View(new AddU2FDeviceViewModel()
{
AppId = serverRegisterResponse.AppId,
Challenge = serverRegisterResponse.Challenge,
Version = serverRegisterResponse.Version,
Name = name
});
}
[HttpPost]
public async Task<IActionResult> AddU2FDevice(AddU2FDeviceViewModel viewModel)
{
var errorMessage = string.Empty;
try
{
if (await _u2FService.CompleteRegistration(_userManager.GetUserId(User), viewModel.DeviceResponse,
string.IsNullOrEmpty(viewModel.Name) ? "Unlabelled U2F Device" : viewModel.Name))
{
TempData[WellKnownTempData.SuccessMessage] = "Device added!";
return RedirectToAction("U2FAuthentication");
}
}
catch (U2fException e)
{
errorMessage = e.Message;
}
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Severity = StatusMessageModel.StatusSeverity.Error,
Message = string.IsNullOrEmpty(errorMessage) ? "Could not add device." : errorMessage
});
return RedirectToAction("U2FAuthentication");
}
}
}

View file

@ -4,13 +4,11 @@ using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Data;
using BTCPayServer.Models.ManageViewModels;
using BTCPayServer.Security;
using BTCPayServer.Security.GreenField;
using BTCPayServer.Services;
using BTCPayServer.Services.Mails;
using BTCPayServer.Services.Stores;
using BTCPayServer.Services.Wallets;
using BTCPayServer.U2F;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
@ -29,8 +27,6 @@ namespace BTCPayServer.Controllers
private readonly EmailSenderFactory _EmailSenderFactory;
private readonly ILogger _logger;
private readonly UrlEncoder _urlEncoder;
readonly IWebHostEnvironment _Env;
public U2FService _u2FService;
private readonly BTCPayServerEnvironment _btcPayServerEnvironment;
private readonly APIKeyRepository _apiKeyRepository;
private readonly IAuthorizationService _authorizationService;
@ -48,7 +44,6 @@ namespace BTCPayServer.Controllers
BTCPayWalletProvider walletProvider,
StoreRepository storeRepository,
IWebHostEnvironment env,
U2FService u2FService,
BTCPayServerEnvironment btcPayServerEnvironment,
APIKeyRepository apiKeyRepository,
IAuthorizationService authorizationService,
@ -60,8 +55,6 @@ namespace BTCPayServer.Controllers
_EmailSenderFactory = emailSenderFactory;
_logger = logger;
_urlEncoder = urlEncoder;
_Env = env;
_u2FService = u2FService;
_btcPayServerEnvironment = btcPayServerEnvironment;
_apiKeyRepository = apiKeyRepository;
_authorizationService = authorizationService;

View file

@ -35,7 +35,6 @@ using BTCPayServer.Services.PaymentRequests;
using BTCPayServer.Services.Rates;
using BTCPayServer.Services.Stores;
using BTCPayServer.Services.Wallets;
using BTCPayServer.U2F;
using BundlerMinifier.TagHelpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
@ -113,7 +112,6 @@ namespace BTCPayServer.Hosting
services.TryAddSingleton<WalletRepository>();
services.TryAddSingleton<EventAggregator>();
services.TryAddSingleton<PaymentRequestService>();
services.TryAddSingleton<U2FService>();
services.AddSingleton<ApplicationDbContextFactory>();
services.AddOptions<BTCPayServerOptions>().Configure(
(options) =>

View file

@ -1,9 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Contracts;
@ -17,17 +14,13 @@ using BTCPayServer.Payments;
using BTCPayServer.Payments.Lightning;
using BTCPayServer.Services;
using BTCPayServer.Services.Stores;
using Fido2NetLib;
using Fido2NetLib.Objects;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NBitcoin.DataEncoders;
using NBXplorer;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Org.BouncyCastle.Math.EC;
using PeterO.Cbor;
namespace BTCPayServer.Hosting

View file

@ -1,5 +1,4 @@
using BTCPayServer.Fido2.Models;
using BTCPayServer.U2F.Models;
namespace BTCPayServer.Models.AccountViewModels
{
@ -7,6 +6,5 @@ namespace BTCPayServer.Models.AccountViewModels
{
public LoginWithFido2ViewModel LoginWithFido2ViewModel { get; set; }
public LoginWith2faViewModel LoginWith2FaViewModel { get; set; }
public LoginWithU2FViewModel LoginWithU2FViewModel { get; set; }
}
}

View file

@ -63,12 +63,11 @@ namespace BTCPayServer.Security.GreenField
return AuthenticateResult.Fail(result.ToString());
var user = await _userManager.Users
.Include(applicationUser => applicationUser.U2FDevices)
.Include(applicationUser => applicationUser.Fido2Credentials)
.FirstOrDefaultAsync(applicationUser =>
applicationUser.NormalizedUserName == _userManager.NormalizeName(username));
if (user.U2FDevices.Any() || user.Fido2Credentials.Any())
if (user.Fido2Credentials.Any())
{
return AuthenticateResult.Fail("Cannot use Basic authentication with multi-factor is enabled.");
}

View file

@ -1,12 +0,0 @@
namespace BTCPayServer.U2F.Models
{
public class AddU2FDeviceViewModel
{
public string AppId { get; set; }
public string Challenge { get; set; }
public string Version { get; set; }
public string DeviceResponse { get; set; }
public string Name { get; set; }
}
}

View file

@ -1,29 +0,0 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace BTCPayServer.U2F.Models
{
public class LoginWithU2FViewModel
{
public string UserId { get; set; }
[Required]
[Display(Name = "App id")]
public string AppId { get; set; }
[Required]
[Display(Name = "Version")]
public string Version { get; set; }
[Required]
[Display(Name = "Device Response")]
public string DeviceResponse { get; set; }
[Display(Name = "Challenges")]
public List<ServerChallenge> Challenges { get; set; }
[Display(Name = "Challenge")]
public string Challenge { get; set; }
public bool RememberMe { get; set; }
}
}

View file

@ -1,10 +0,0 @@
namespace BTCPayServer.U2F.Models
{
public class ServerChallenge
{
public string challenge { get; set; }
public string version { get; set; }
public string appId { get; set; }
public string keyHandle { get; set; }
}
}

View file

@ -1,9 +0,0 @@
namespace BTCPayServer.U2F.Models
{
public class ServerRegisterResponse
{
public string AppId { get; set; }
public string Challenge { get; set; }
public string Version { get; set; }
}
}

View file

@ -1,10 +0,0 @@
using System.Collections.Generic;
using BTCPayServer.Data;
namespace BTCPayServer.U2F.Models
{
public class U2FAuthenticationViewModel
{
public List<U2FDevice> Devices { get; set; }
}
}

View file

@ -1,15 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace BTCPayServer.U2F.Models
{
public class U2FDeviceAuthenticationRequest
{
public string KeyHandle { get; set; }
[Required] public string Challenge { get; set; }
[Required] [StringLength(200)] public string AppId { get; set; }
[Required] [StringLength(50)] public string Version { get; set; }
}
}

View file

@ -1,248 +0,0 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Data;
using BTCPayServer.U2F.Models;
using Microsoft.EntityFrameworkCore;
using NBitcoin;
using U2F.Core.Exceptions;
using U2F.Core.Models;
using U2F.Core.Utils;
namespace BTCPayServer.U2F
{
public class U2FService
{
private readonly ApplicationDbContextFactory _contextFactory;
private ConcurrentDictionary<string, List<U2FDeviceAuthenticationRequest>> UserAuthenticationRequests
{
get;
set;
}
= new ConcurrentDictionary<string, List<U2FDeviceAuthenticationRequest>>();
public U2FService(ApplicationDbContextFactory contextFactory)
{
_contextFactory = contextFactory;
}
public async Task<List<U2FDevice>> GetDevices(string userId)
{
using (var context = _contextFactory.CreateContext())
{
return await context.U2FDevices
.Where(device => device.ApplicationUserId == userId)
.ToListAsync();
}
}
public async Task RemoveDevice(string id, string userId)
{
using (var context = _contextFactory.CreateContext())
{
var device = await context.U2FDevices.FindAsync(id);
if (device == null || !device.ApplicationUserId.Equals(userId, StringComparison.InvariantCulture))
{
return;
}
context.U2FDevices.Remove(device);
await context.SaveChangesAsync();
}
}
public async Task<bool> HasDevices(string userId)
{
using (var context = _contextFactory.CreateContext())
{
return await context.U2FDevices.Where(fDevice => fDevice.ApplicationUserId == userId).AnyAsync();
}
}
public ServerRegisterResponse StartDeviceRegistration(string userId, string appId)
{
var startedRegistration = StartDeviceRegistrationCore(appId);
UserAuthenticationRequests.AddOrReplace(userId, new List<U2FDeviceAuthenticationRequest>()
{
new U2FDeviceAuthenticationRequest()
{
AppId = startedRegistration.AppId,
Challenge = startedRegistration.Challenge,
Version = global::U2F.Core.Crypto.U2F.U2FVersion,
}
});
return new ServerRegisterResponse
{
AppId = startedRegistration.AppId,
Challenge = startedRegistration.Challenge,
Version = startedRegistration.Version
};
}
public async Task<bool> CompleteRegistration(string userId, string deviceResponse, string name)
{
if (string.IsNullOrWhiteSpace(deviceResponse))
return false;
if (!UserAuthenticationRequests.ContainsKey(userId) || !UserAuthenticationRequests[userId].Any())
{
return false;
}
var registerResponse = RegisterResponse.FromJson<RegisterResponse>(deviceResponse);
//There is only 1 request when registering device
var authenticationRequest = UserAuthenticationRequests[userId].First();
var startedRegistration =
new StartedRegistration(authenticationRequest.Challenge, authenticationRequest.AppId);
var registration = FinishRegistrationCore(startedRegistration, registerResponse);
UserAuthenticationRequests.AddOrReplace(userId, new List<U2FDeviceAuthenticationRequest>());
using (var context = _contextFactory.CreateContext())
{
var duplicate = context.U2FDevices.Any(device =>
device.ApplicationUserId == userId &&
device.KeyHandle.Equals(registration.KeyHandle) &&
device.PublicKey.Equals(registration.PublicKey));
if (duplicate)
{
throw new U2fException("The U2F Device has already been registered with this user");
}
await context.U2FDevices.AddAsync(new U2FDevice()
{
Id = Guid.NewGuid().ToString(),
AttestationCert = registration.AttestationCert,
Counter = Convert.ToInt32(registration.Counter),
Name = name,
KeyHandle = registration.KeyHandle,
PublicKey = registration.PublicKey,
ApplicationUserId = userId
});
await context.SaveChangesAsync();
}
return true;
}
public async Task<bool> AuthenticateUser(string userId, string deviceResponse)
{
if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(deviceResponse))
return false;
var authenticateResponse =
AuthenticateResponse.FromJson<AuthenticateResponse>(deviceResponse);
using (var context = _contextFactory.CreateContext())
{
var keyHandle = authenticateResponse.KeyHandle.Base64StringToByteArray();
var device = await context.U2FDevices.Where(fDevice =>
fDevice.ApplicationUserId == userId &&
fDevice.KeyHandle == keyHandle).SingleOrDefaultAsync();
if (device == null)
return false;
// User will have a authentication request for each device they have registered so get the one that matches the device key handle
var authenticationRequest =
UserAuthenticationRequests[userId].First(f =>
f.KeyHandle.Equals(authenticateResponse.KeyHandle, StringComparison.InvariantCulture));
var registration = new DeviceRegistration(device.KeyHandle, device.PublicKey,
device.AttestationCert, Convert.ToUInt32(device.Counter));
var authentication = new StartedAuthentication(authenticationRequest.Challenge,
authenticationRequest.AppId, authenticationRequest.KeyHandle);
var challengeAuthenticationRequestMatch = UserAuthenticationRequests[userId].First(f =>
f.Challenge.Equals(authenticateResponse.GetClientData().Challenge, StringComparison.InvariantCulture));
if (authentication.Challenge != challengeAuthenticationRequestMatch.Challenge)
{
authentication = new StartedAuthentication(challengeAuthenticationRequestMatch.Challenge, authenticationRequest.AppId, authenticationRequest.KeyHandle);
}
FinishAuthenticationCore(authentication, authenticateResponse, registration);
UserAuthenticationRequests.AddOrReplace(userId, new List<U2FDeviceAuthenticationRequest>());
device.Counter = Convert.ToInt32(registration.Counter);
await context.SaveChangesAsync();
}
return true;
}
public async Task<List<ServerChallenge>> GenerateDeviceChallenges(string userId, string appId)
{
using (var context = _contextFactory.CreateContext())
{
var devices = await context.U2FDevices.Where(fDevice => fDevice.ApplicationUserId == userId).ToListAsync();
if (devices.Count == 0)
return null;
var requests = new List<U2FDeviceAuthenticationRequest>();
var serverChallenges = new List<ServerChallenge>();
foreach (var registeredDevice in devices)
{
var challenge = StartAuthenticationCore(appId, registeredDevice);
serverChallenges.Add(new ServerChallenge()
{
challenge = challenge.Challenge,
appId = challenge.AppId,
version = challenge.Version,
keyHandle = challenge.KeyHandle
});
requests.Add(
new U2FDeviceAuthenticationRequest()
{
AppId = appId,
Challenge = challenge.Challenge,
KeyHandle = registeredDevice.KeyHandle.ByteArrayToBase64String(),
Version = global::U2F.Core.Crypto.U2F.U2FVersion
});
}
UserAuthenticationRequests.AddOrReplace(userId, requests);
return serverChallenges;
}
}
protected virtual StartedRegistration StartDeviceRegistrationCore(string appId)
{
return global::U2F.Core.Crypto.U2F.StartRegistration(appId);
}
protected virtual DeviceRegistration FinishRegistrationCore(StartedRegistration startedRegistration, RegisterResponse registerResponse)
{
return global::U2F.Core.Crypto.U2F.FinishRegistration(startedRegistration, registerResponse);
}
protected virtual StartedAuthentication StartAuthenticationCore(string appId, U2FDevice registeredDevice)
{
return global::U2F.Core.Crypto.U2F.StartAuthentication(appId,
new DeviceRegistration(registeredDevice.KeyHandle, registeredDevice.PublicKey,
registeredDevice.AttestationCert, (uint)registeredDevice.Counter));
}
protected virtual void FinishAuthenticationCore(StartedAuthentication authentication,
AuthenticateResponse authenticateResponse, DeviceRegistration registration)
{
global::U2F.Core.Crypto.U2F.FinishAuthentication(authentication, authenticateResponse, registration);
}
}
}

View file

@ -1,52 +0,0 @@
@model BTCPayServer.U2F.Models.LoginWithU2FViewModel
<form id="u2fForm" asp-action="LoginWithU2F" method="post" asp-route-returnUrl="@ViewData["ReturnUrl"]">
<input type="hidden" asp-for="Version" />
<input type="hidden" asp-for="Challenge" />
<input type="hidden" asp-for="AppId" />
<input type="hidden" asp-for="DeviceResponse" />
@for (int i = 0; i < Model.Challenges.Count; i++)
{
@Html.HiddenFor(m => m.Challenges[i])
}
<input type="hidden" asp-for="UserId" />
<input type="hidden" asp-for="RememberMe" />
</form>
<section class="pt-5">
<div>
<div class="row">
<div class="col-lg-12 section-heading">
<h2>U2F Authentication</h2>
<hr class="primary">
<div>
<span id="spinner" class="fa fa-spinner fa-spin float-right ml-3 mr-5 mt-1" style="font-size:2.5em"></span>
<p>Insert your U2F device or hardware wallet into your computer's USB port. If it has a button, tap on it.</p>
</div>
<p id="error-message" class="d-none alert alert-danger"></p>
<a id="btn-retry" class="btn btn-secondary d-none" href="javascript:window.location.reload()">Retry</a>
</div>
</div>
</div>
</section>
<script src="~/vendor/u2f/u2f-api-1.1.1.js" asp-append-version="true"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", () => {
window.u2fApi.sign(
@Safe.Json(Model.Challenges)
)
.then(data => {
document.getElementById("DeviceResponse").value = JSON.stringify(data);
document.getElementById("u2fForm").submit();
})
.catch(error => {
document.getElementById("error-message").innerText = error.message;
document.getElementById("error-message").classList.remove("d-none");
document.getElementById("spinner").classList.add("d-none");
if (!error.message.endsWith("not supported")) {
document.getElementById("btn-retry").classList.remove("d-none");
}
});
});
</script>

View file

@ -5,11 +5,11 @@
<section>
<div class="container">
@if (Model.LoginWith2FaViewModel != null && Model.LoginWithU2FViewModel != null && Model.LoginWithFido2ViewModel != null)
@if (Model.LoginWith2FaViewModel != null && Model.LoginWithFido2ViewModel != null)
{
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
}
else if (Model.LoginWith2FaViewModel == null && Model.LoginWithU2FViewModel == null && Model.LoginWithFido2ViewModel == null)
else if (Model.LoginWith2FaViewModel == null && Model.LoginWithFido2ViewModel == null)
{
<div class="row">
<div class="col-lg-12 section-heading">
@ -27,12 +27,6 @@
<partial name="Loginwith2fa" model="@Model.LoginWith2FaViewModel"/>
</div>
}
@if (Model.LoginWithU2FViewModel != null)
{
<div class="col-sm-12 col-md-6">
<partial name="LoginWithU2F" model="@Model.LoginWithU2FViewModel"/>
</div>
}
@if (Model.LoginWithFido2ViewModel != null)
{
<div class="col-sm-12 col-md-6">

View file

@ -1,53 +0,0 @@
@model BTCPayServer.U2F.Models.AddU2FDeviceViewModel
@{
ViewData.SetActivePageAndTitle(ManageNavPages.U2F, "Add U2F device");
}
<form asp-action="AddU2FDevice" method="post" id="registerForm" class="hidden">
<input type="hidden" asp-for="AppId"/>
<input type="hidden" asp-for="Version"/>
<input type="hidden" asp-for="Challenge"/>
<input type="hidden" asp-for="Name"/>
<input type="hidden" asp-for="DeviceResponse"/>
</form>
<div class="card">
<div class="card-header">
<h4 class="mb-0">
Registering U2F Device
</h4>
</div>
<div class="card-body">
<span id="spinner" class="fa fa-spinner fa-spin float-right" style="font-size:2.5em"></span>
<p class="mb-0 mr-5">Insert your U2F device or a hardware wallet into your computer's USB port. If it has a button, tap on it.</p>
<p id="error-message" class="d-none text-danger mt-3 mb-0"></p>
</div>
<div class="card-footer">
<a class="btn btn-secondary" asp-action="U2FAuthentication" id="btn-back">Abort</a>
</div>
</div>
@section Scripts {
<script src="~/vendor/u2f/u2f-api-1.1.1.js" asp-append-version="true"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", () => {
window.u2fApi.register([{
appId: @Safe.Json(Model.AppId),
version: @Safe.Json(Model.Version),
challenge: @Safe.Json(Model.Challenge)
}])
.then(data => {
document.getElementById("DeviceResponse").value = JSON.stringify(data);
document.getElementById("registerForm").submit();
})
.catch(message => {
document.getElementById("error-message").classList.remove("d-none");
document.getElementById("error-message").innerText = message;
document.getElementById("btn-back").innerText = "Retry";
document.getElementById("spinner").classList.add("d-none");
});
});
</script>
}

View file

@ -2,6 +2,6 @@ namespace BTCPayServer.Views.Manage
{
public enum ManageNavPages
{
Index, ChangePassword, TwoFactorAuthentication, U2F, APIKeys, Notifications, Fido2
Index, ChangePassword, TwoFactorAuthentication, APIKeys, Notifications, Fido2
}
}

View file

@ -1,44 +0,0 @@
@model BTCPayServer.U2F.Models.U2FAuthenticationViewModel
@{
ViewData.SetActivePageAndTitle(ManageNavPages.U2F, "Registered U2F devices");
}
<form asp-action="AddU2FDevice" method="get">
<table class="table table-lg mb-4">
<thead>
<tr>
<th>Name</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
@foreach (var device in Model.Devices)
{
<tr>
<td>@device.Name</td>
<td class="text-right" >
<a asp-action="RemoveU2FDevice" asp-route-id="@device.Id">Remove</a>
</td>
</tr>
}
@if (!Model.Devices.Any())
{
<tr>
<td colspan="2" class="text-center h5 py-2">
No registered devices
</td>
</tr>
}
</tbody>
</table>
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" name="Name" placeholder="New Device Name"/>
<button type="submit" class="btn btn-primary ml-2">
<span class="fa fa-plus"></span>
Add New Device
</button>
</div>
</div>
</form>

View file

@ -3,7 +3,6 @@
<a id="@ManageNavPages.Index.ToString()" class="nav-link @ViewData.IsActivePage(ManageNavPages.Index)" asp-controller="Manage" asp-action="Index">Profile</a>
<a id="@ManageNavPages.ChangePassword.ToString()" class="nav-link @ViewData.IsActivePage(ManageNavPages.ChangePassword)" asp-controller="Manage" asp-action="ChangePassword">Password</a>
<a id="@ManageNavPages.TwoFactorAuthentication.ToString()" class="nav-link @ViewData.IsActivePage(ManageNavPages.TwoFactorAuthentication)" asp-controller="Manage" asp-action="TwoFactorAuthentication">Two-factor authentication</a>
<a id="@ManageNavPages.U2F.ToString()" class="nav-link @ViewData.IsActivePage(ManageNavPages.U2F)" asp-controller="Manage" asp-action="U2FAuthentication">U2F Authentication</a>
<a id="@ManageNavPages.Fido2.ToString()" class="nav-link @ViewData.IsActivePage(ManageNavPages.Fido2)" asp-action="List" asp-controller="Fido2">FIDO2 Authentication</a>
<a id="@ManageNavPages.APIKeys.ToString()" class="nav-link @ViewData.IsActivePage(ManageNavPages.APIKeys)" asp-controller="Manage" asp-action="APIKeys">API Keys</a>
<a id="@ManageNavPages.Notifications.ToString()" class="nav-link @ViewData.IsActivePage(ManageNavPages.Notifications)" asp-controller="Manage" asp-action="NotificationSettings">Notifications</a>

View file

@ -1,829 +0,0 @@
(function () {
'use strict';
//Copyright 2014-2015 Google Inc. All rights reserved.
//Use of this source code is governed by a BSD-style
//license that can be found in the LICENSE file or at
//https://developers.google.com/open-source/licenses/bsd
/**
* @fileoverview The U2F api.
*/
// 'use strict';
/**
* Namespace for the U2F api.
* @type {Object}
*/
var u2f = u2f || {};
const chromeApi = u2f; // Adaptation for u2f-api package
/**
* FIDO U2F Javascript API Version
* @number
*/
var js_api_version;
/**
* The U2F extension id
* @const {string}
*/
// The Chrome packaged app extension ID.
// Uncomment this if you want to deploy a server instance that uses
// the package Chrome app and does not require installing the U2F Chrome extension.
u2f.EXTENSION_ID = 'kmendfapggjehodndflmmgagdbamhnfd';
// The U2F Chrome extension ID.
// Uncomment this if you want to deploy a server instance that uses
// the U2F Chrome extension to authenticate.
// u2f.EXTENSION_ID = 'pfboblefjcgdjicmnffhdgionmgcdmne';
/**
* Message types for messsages to/from the extension
* @const
* @enum {string}
*/
u2f.MessageTypes = {
'U2F_REGISTER_REQUEST': 'u2f_register_request',
'U2F_REGISTER_RESPONSE': 'u2f_register_response',
'U2F_SIGN_REQUEST': 'u2f_sign_request',
'U2F_SIGN_RESPONSE': 'u2f_sign_response',
'U2F_GET_API_VERSION_REQUEST': 'u2f_get_api_version_request',
'U2F_GET_API_VERSION_RESPONSE': 'u2f_get_api_version_response'
};
/**
* Response status codes
* @const
* @enum {number}
*/
u2f.ErrorCodes = {
'OK': 0,
'OTHER_ERROR': 1,
'BAD_REQUEST': 2,
'CONFIGURATION_UNSUPPORTED': 3,
'DEVICE_INELIGIBLE': 4,
'TIMEOUT': 5
};
//Low level MessagePort API support
/**
* Sets up a MessagePort to the U2F extension using the
* available mechanisms.
* @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback
*/
u2f.getMessagePort = function(callback) {
if (typeof chrome != 'undefined' && chrome.runtime) {
// The actual message here does not matter, but we need to get a reply
// for the callback to run. Thus, send an empty signature request
// in order to get a failure response.
var msg = {
type: u2f.MessageTypes.U2F_SIGN_REQUEST,
signRequests: []
};
chrome.runtime.sendMessage(u2f.EXTENSION_ID, msg, function() {
if (!chrome.runtime.lastError) {
// We are on a whitelisted origin and can talk directly
// with the extension.
u2f.getChromeRuntimePort_(callback);
} else {
// chrome.runtime was available, but we couldn't message
// the extension directly, use iframe
u2f.getIframePort_(callback);
}
});
} else if (u2f.isAndroidChrome_()) {
u2f.getAuthenticatorPort_(callback);
} else if (u2f.isIosChrome_()) {
u2f.getIosPort_(callback);
} else {
// chrome.runtime was not available at all, which is normal
// when this origin doesn't have access to any extensions.
u2f.getIframePort_(callback);
}
};
/**
* Detect chrome running on android based on the browser's useragent.
* @private
*/
u2f.isAndroidChrome_ = function() {
var userAgent = navigator.userAgent;
return userAgent.indexOf('Chrome') != -1 &&
userAgent.indexOf('Android') != -1;
};
/**
* Detect chrome running on iOS based on the browser's platform.
* @private
*/
u2f.isIosChrome_ = function() {
return ["iPhone", "iPad", "iPod"].indexOf(navigator.platform) > -1;
};
/**
* Connects directly to the extension via chrome.runtime.connect.
* @param {function(u2f.WrappedChromeRuntimePort_)} callback
* @private
*/
u2f.getChromeRuntimePort_ = function(callback) {
var port = chrome.runtime.connect(u2f.EXTENSION_ID,
{'includeTlsChannelId': true});
setTimeout(function() {
callback(new u2f.WrappedChromeRuntimePort_(port));
}, 0);
};
/**
* Return a 'port' abstraction to the Authenticator app.
* @param {function(u2f.WrappedAuthenticatorPort_)} callback
* @private
*/
u2f.getAuthenticatorPort_ = function(callback) {
setTimeout(function() {
callback(new u2f.WrappedAuthenticatorPort_());
}, 0);
};
/**
* Return a 'port' abstraction to the iOS client app.
* @param {function(u2f.WrappedIosPort_)} callback
* @private
*/
u2f.getIosPort_ = function(callback) {
setTimeout(function() {
callback(new u2f.WrappedIosPort_());
}, 0);
};
/**
* A wrapper for chrome.runtime.Port that is compatible with MessagePort.
* @param {Port} port
* @constructor
* @private
*/
u2f.WrappedChromeRuntimePort_ = function(port) {
this.port_ = port;
};
/**
* Format and return a sign request compliant with the JS API version supported by the extension.
* @param {Array<u2f.SignRequest>} signRequests
* @param {number} timeoutSeconds
* @param {number} reqId
* @return {Object}
*/
u2f.formatSignRequest_ =
function(appId, challenge, registeredKeys, timeoutSeconds, reqId) {
if (js_api_version === undefined || js_api_version < 1.1) {
// Adapt request to the 1.0 JS API
var signRequests = [];
for (var i = 0; i < registeredKeys.length; i++) {
signRequests[i] = {
version: registeredKeys[i].version,
challenge: challenge,
keyHandle: registeredKeys[i].keyHandle,
appId: appId
};
}
return {
type: u2f.MessageTypes.U2F_SIGN_REQUEST,
signRequests: signRequests,
timeoutSeconds: timeoutSeconds,
requestId: reqId
};
}
// JS 1.1 API
return {
type: u2f.MessageTypes.U2F_SIGN_REQUEST,
appId: appId,
challenge: challenge,
registeredKeys: registeredKeys,
timeoutSeconds: timeoutSeconds,
requestId: reqId
};
};
/**
* Format and return a register request compliant with the JS API version supported by the extension..
* @param {Array<u2f.SignRequest>} signRequests
* @param {Array<u2f.RegisterRequest>} signRequests
* @param {number} timeoutSeconds
* @param {number} reqId
* @return {Object}
*/
u2f.formatRegisterRequest_ =
function(appId, registeredKeys, registerRequests, timeoutSeconds, reqId) {
if (js_api_version === undefined || js_api_version < 1.1) {
// Adapt request to the 1.0 JS API
for (var i = 0; i < registerRequests.length; i++) {
registerRequests[i].appId = appId;
}
var signRequests = [];
for (var i = 0; i < registeredKeys.length; i++) {
signRequests[i] = {
version: registeredKeys[i].version,
challenge: registerRequests[0],
keyHandle: registeredKeys[i].keyHandle,
appId: appId
};
}
return {
type: u2f.MessageTypes.U2F_REGISTER_REQUEST,
signRequests: signRequests,
registerRequests: registerRequests,
timeoutSeconds: timeoutSeconds,
requestId: reqId
};
}
// JS 1.1 API
return {
type: u2f.MessageTypes.U2F_REGISTER_REQUEST,
appId: appId,
registerRequests: registerRequests,
registeredKeys: registeredKeys,
timeoutSeconds: timeoutSeconds,
requestId: reqId
};
};
/**
* Posts a message on the underlying channel.
* @param {Object} message
*/
u2f.WrappedChromeRuntimePort_.prototype.postMessage = function(message) {
this.port_.postMessage(message);
};
/**
* Emulates the HTML 5 addEventListener interface. Works only for the
* onmessage event, which is hooked up to the chrome.runtime.Port.onMessage.
* @param {string} eventName
* @param {function({data: Object})} handler
*/
u2f.WrappedChromeRuntimePort_.prototype.addEventListener =
function(eventName, handler) {
var name = eventName.toLowerCase();
if (name == 'message' || name == 'onmessage') {
this.port_.onMessage.addListener(function(message) {
// Emulate a minimal MessageEvent object
handler({'data': message});
});
} else {
console.error('WrappedChromeRuntimePort only supports onMessage');
}
};
/**
* Wrap the Authenticator app with a MessagePort interface.
* @constructor
* @private
*/
u2f.WrappedAuthenticatorPort_ = function() {
this.requestId_ = -1;
this.requestObject_ = null;
};
/**
* Launch the Authenticator intent.
* @param {Object} message
*/
u2f.WrappedAuthenticatorPort_.prototype.postMessage = function(message) {
var intentUrl =
u2f.WrappedAuthenticatorPort_.INTENT_URL_BASE_ +
';S.request=' + encodeURIComponent(JSON.stringify(message)) +
';end';
document.location = intentUrl;
};
/**
* Tells what type of port this is.
* @return {String} port type
*/
u2f.WrappedAuthenticatorPort_.prototype.getPortType = function() {
return "WrappedAuthenticatorPort_";
};
/**
* Emulates the HTML 5 addEventListener interface.
* @param {string} eventName
* @param {function({data: Object})} handler
*/
u2f.WrappedAuthenticatorPort_.prototype.addEventListener = function(eventName, handler) {
var name = eventName.toLowerCase();
if (name == 'message') {
var self = this;
/* Register a callback to that executes when
* chrome injects the response. */
window.addEventListener(
'message', self.onRequestUpdate_.bind(self, handler), false);
} else {
console.error('WrappedAuthenticatorPort only supports message');
}
};
/**
* Callback invoked when a response is received from the Authenticator.
* @param function({data: Object}) callback
* @param {Object} message message Object
*/
u2f.WrappedAuthenticatorPort_.prototype.onRequestUpdate_ =
function(callback, message) {
var messageObject = JSON.parse(message.data);
var intentUrl = messageObject['intentURL'];
var errorCode = messageObject['errorCode'];
var responseObject = null;
if (messageObject.hasOwnProperty('data')) {
responseObject = /** @type {Object} */ (
JSON.parse(messageObject['data']));
}
callback({'data': responseObject});
};
/**
* Base URL for intents to Authenticator.
* @const
* @private
*/
u2f.WrappedAuthenticatorPort_.INTENT_URL_BASE_ =
'intent:#Intent;action=com.google.android.apps.authenticator.AUTHENTICATE';
/**
* Wrap the iOS client app with a MessagePort interface.
* @constructor
* @private
*/
u2f.WrappedIosPort_ = function() {};
/**
* Launch the iOS client app request
* @param {Object} message
*/
u2f.WrappedIosPort_.prototype.postMessage = function(message) {
var str = JSON.stringify(message);
var url = "u2f://auth?" + encodeURI(str);
location.replace(url);
};
/**
* Tells what type of port this is.
* @return {String} port type
*/
u2f.WrappedIosPort_.prototype.getPortType = function() {
return "WrappedIosPort_";
};
/**
* Emulates the HTML 5 addEventListener interface.
* @param {string} eventName
* @param {function({data: Object})} handler
*/
u2f.WrappedIosPort_.prototype.addEventListener = function(eventName, handler) {
var name = eventName.toLowerCase();
if (name !== 'message') {
console.error('WrappedIosPort only supports message');
}
};
/**
* Sets up an embedded trampoline iframe, sourced from the extension.
* @param {function(MessagePort)} callback
* @private
*/
u2f.getIframePort_ = function(callback) {
// Create the iframe
var iframeOrigin = 'chrome-extension://' + u2f.EXTENSION_ID;
var iframe = document.createElement('iframe');
iframe.src = iframeOrigin + '/u2f-comms.html';
iframe.setAttribute('style', 'display:none');
document.body.appendChild(iframe);
var channel = new MessageChannel();
var ready = function(message) {
if (message.data == 'ready') {
channel.port1.removeEventListener('message', ready);
callback(channel.port1);
} else {
console.error('First event on iframe port was not "ready"');
}
};
channel.port1.addEventListener('message', ready);
channel.port1.start();
iframe.addEventListener('load', function() {
// Deliver the port to the iframe and initialize
iframe.contentWindow.postMessage('init', iframeOrigin, [channel.port2]);
});
};
//High-level JS API
/**
* Default extension response timeout in seconds.
* @const
*/
u2f.EXTENSION_TIMEOUT_SEC = 30;
/**
* A singleton instance for a MessagePort to the extension.
* @type {MessagePort|u2f.WrappedChromeRuntimePort_}
* @private
*/
u2f.port_ = null;
/**
* Callbacks waiting for a port
* @type {Array<function((MessagePort|u2f.WrappedChromeRuntimePort_))>}
* @private
*/
u2f.waitingForPort_ = [];
/**
* A counter for requestIds.
* @type {number}
* @private
*/
u2f.reqCounter_ = 0;
/**
* A map from requestIds to client callbacks
* @type {Object.<number,(function((u2f.Error|u2f.RegisterResponse))
* |function((u2f.Error|u2f.SignResponse)))>}
* @private
*/
u2f.callbackMap_ = {};
/**
* Creates or retrieves the MessagePort singleton to use.
* @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback
* @private
*/
u2f.getPortSingleton_ = function(callback) {
if (u2f.port_) {
callback(u2f.port_);
} else {
if (u2f.waitingForPort_.length == 0) {
u2f.getMessagePort(function(port) {
u2f.port_ = port;
u2f.port_.addEventListener('message',
/** @type {function(Event)} */ (u2f.responseHandler_));
// Careful, here be async callbacks. Maybe.
while (u2f.waitingForPort_.length)
u2f.waitingForPort_.shift()(u2f.port_);
});
}
u2f.waitingForPort_.push(callback);
}
};
/**
* Handles response messages from the extension.
* @param {MessageEvent.<u2f.Response>} message
* @private
*/
u2f.responseHandler_ = function(message) {
var response = message.data;
var reqId = response['requestId'];
if (!reqId || !u2f.callbackMap_[reqId]) {
console.error('Unknown or missing requestId in response.');
return;
}
var cb = u2f.callbackMap_[reqId];
delete u2f.callbackMap_[reqId];
cb(response['responseData']);
};
/**
* Calls the callback with true or false as first and only argument
* @param {Function} callback
*/
u2f.isSupported = function(callback) {
var hasCalledBack = false;
function reply(value) {
if (hasCalledBack)
return;
hasCalledBack = true;
callback(value);
}
u2f.getApiVersion(
function (response) {
js_api_version = response['js_api_version'] === undefined ? 0 : response['js_api_version'];
reply(true);
}
);
// No response from extension within 1500ms -> no support
setTimeout(reply.bind(null, false), 1500);
};
/**
* Dispatches an array of sign requests to available U2F tokens.
* If the JS API version supported by the extension is unknown, it first sends a
* message to the extension to find out the supported API version and then it sends
* the sign request.
* @param {string=} appId
* @param {string=} challenge
* @param {Array<u2f.RegisteredKey>} registeredKeys
* @param {function((u2f.Error|u2f.SignResponse))} callback
* @param {number=} opt_timeoutSeconds
*/
u2f.sign = function(appId, challenge, registeredKeys, callback, opt_timeoutSeconds) {
if (js_api_version === undefined) {
// Send a message to get the extension to JS API version, then send the actual sign request.
u2f.getApiVersion(
function (response) {
js_api_version = response['js_api_version'] === undefined ? 0 : response['js_api_version'];
console.log("Extension JS API Version: ", js_api_version);
u2f.sendSignRequest(appId, challenge, registeredKeys, callback, opt_timeoutSeconds);
});
} else {
// We know the JS API version. Send the actual sign request in the supported API version.
u2f.sendSignRequest(appId, challenge, registeredKeys, callback, opt_timeoutSeconds);
}
};
/**
* Dispatches an array of sign requests to available U2F tokens.
* @param {string=} appId
* @param {string=} challenge
* @param {Array<u2f.RegisteredKey>} registeredKeys
* @param {function((u2f.Error|u2f.SignResponse))} callback
* @param {number=} opt_timeoutSeconds
*/
u2f.sendSignRequest = function(appId, challenge, registeredKeys, callback, opt_timeoutSeconds) {
u2f.getPortSingleton_(function(port) {
var reqId = ++u2f.reqCounter_;
u2f.callbackMap_[reqId] = callback;
var timeoutSeconds = (typeof opt_timeoutSeconds !== 'undefined' ?
opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC);
var req = u2f.formatSignRequest_(appId, challenge, registeredKeys, timeoutSeconds, reqId);
port.postMessage(req);
});
};
/**
* Dispatches register requests to available U2F tokens. An array of sign
* requests identifies already registered tokens.
* If the JS API version supported by the extension is unknown, it first sends a
* message to the extension to find out the supported API version and then it sends
* the register request.
* @param {string=} appId
* @param {Array<u2f.RegisterRequest>} registerRequests
* @param {Array<u2f.RegisteredKey>} registeredKeys
* @param {function((u2f.Error|u2f.RegisterResponse))} callback
* @param {number=} opt_timeoutSeconds
*/
u2f.register = function(appId, registerRequests, registeredKeys, callback, opt_timeoutSeconds) {
if (js_api_version === undefined) {
// Send a message to get the extension to JS API version, then send the actual register request.
u2f.getApiVersion(
function (response) {
js_api_version = response['js_api_version'] === undefined ? 0: response['js_api_version'];
console.log("Extension JS API Version: ", js_api_version);
u2f.sendRegisterRequest(appId, registerRequests, registeredKeys,
callback, opt_timeoutSeconds);
});
} else {
// We know the JS API version. Send the actual register request in the supported API version.
u2f.sendRegisterRequest(appId, registerRequests, registeredKeys,
callback, opt_timeoutSeconds);
}
};
/**
* Dispatches register requests to available U2F tokens. An array of sign
* requests identifies already registered tokens.
* @param {string=} appId
* @param {Array<u2f.RegisterRequest>} registerRequests
* @param {Array<u2f.RegisteredKey>} registeredKeys
* @param {function((u2f.Error|u2f.RegisterResponse))} callback
* @param {number=} opt_timeoutSeconds
*/
u2f.sendRegisterRequest = function(appId, registerRequests, registeredKeys, callback, opt_timeoutSeconds) {
u2f.getPortSingleton_(function(port) {
var reqId = ++u2f.reqCounter_;
u2f.callbackMap_[reqId] = callback;
var timeoutSeconds = (typeof opt_timeoutSeconds !== 'undefined' ?
opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC);
var req = u2f.formatRegisterRequest_(
appId, registeredKeys, registerRequests, timeoutSeconds, reqId);
port.postMessage(req);
});
};
/**
* Dispatches a message to the extension to find out the supported
* JS API version.
* If the user is on a mobile phone and is thus using Google Authenticator instead
* of the Chrome extension, don't send the request and simply return 0.
* @param {function((u2f.Error|u2f.GetJsApiVersionResponse))} callback
* @param {number=} opt_timeoutSeconds
*/
u2f.getApiVersion = function(callback, opt_timeoutSeconds) {
u2f.getPortSingleton_(function(port) {
// If we are using Android Google Authenticator or iOS client app,
// do not fire an intent to ask which JS API version to use.
if (port.getPortType) {
var apiVersion;
switch (port.getPortType()) {
case 'WrappedIosPort_':
case 'WrappedAuthenticatorPort_':
apiVersion = 1.1;
break;
default:
apiVersion = 0;
break;
}
callback({ 'js_api_version': apiVersion });
return;
}
var reqId = ++u2f.reqCounter_;
u2f.callbackMap_[reqId] = callback;
var req = {
type: u2f.MessageTypes.U2F_GET_API_VERSION_REQUEST,
timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ?
opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC),
requestId: reqId
};
port.postMessage(req);
});
};
// Feature detection (yes really)
// For IE and Edge detection, see https://stackoverflow.com/questions/31757852#31757969
// and https://stackoverflow.com/questions/56360225#56361977
var isBrowser = (typeof navigator !== 'undefined') && !!navigator.userAgent;
var isSafari = isBrowser && navigator.userAgent.match(/Safari\//)
&& !navigator.userAgent.match(/Chrome\//);
var isEDGE = isBrowser && /(Edge\/)|(edg\/)/i.test(navigator.userAgent);
var isIE = isBrowser && /(MSIE 9|MSIE 10|rv:11.0)/i.test(navigator.userAgent);
var _backend = null;
function getBackend() {
if (_backend)
return _backend;
var supportChecker = new Promise(function (resolve, reject) {
function notSupported() {
resolve({ u2f: null });
}
if (!isBrowser)
return notSupported();
if (isSafari)
// Safari doesn't support U2F, and the Safari-FIDO-U2F
// extension lacks full support (Multi-facet apps), so we
// block it until proper support.
return notSupported();
var hasNativeSupport = (typeof window.u2f !== 'undefined') &&
(typeof window.u2f.sign === 'function');
if (hasNativeSupport)
return resolve({ u2f: window.u2f });
if (isEDGE || isIE)
// We don't want to check for Google's extension hack on EDGE & IE
// as it'll cause trouble (popups, etc)
return notSupported();
if (location.protocol === 'http:')
// U2F isn't supported over http, only https
return notSupported();
if (typeof MessageChannel === 'undefined')
// Unsupported browser, the chrome hack would throw
return notSupported();
// Test for google extension support
chromeApi.isSupported(function (ok) {
if (ok)
resolve({ u2f: chromeApi });
else
notSupported();
});
})
.then(function (response) {
_backend = response.u2f ? supportChecker : null;
return response;
});
return supportChecker;
}
var ErrorCodes = {
OK: 0,
OTHER_ERROR: 1,
BAD_REQUEST: 2,
CONFIGURATION_UNSUPPORTED: 3,
DEVICE_INELIGIBLE: 4,
TIMEOUT: 5
};
var ErrorNames = {
"0": "OK",
"1": "OTHER_ERROR",
"2": "BAD_REQUEST",
"3": "CONFIGURATION_UNSUPPORTED",
"4": "DEVICE_INELIGIBLE",
"5": "TIMEOUT"
};
function makeError(msg, err) {
var code = err != null ? err.errorCode : 1; // Default to OTHER_ERROR
var type = ErrorNames[('' + code)];
var error = new Error(msg);
error.metaData = { type: type, code: code };
return error;
}
function isSupported() {
return getBackend()
.then(function (backend) { return !!backend.u2f; });
}
function _ensureSupport(backend) {
if (!backend.u2f) {
if (location.protocol === 'http:')
throw new Error("U2F isn't supported over http, only https");
throw new Error("U2F not supported");
}
}
function ensureSupport() {
return getBackend()
.then(_ensureSupport);
}
function arrayify(value) {
if (value != null && Array.isArray(value))
return value;
return value == null
? []
: Array.isArray(value)
? value.slice() : [value];
}
function register(registerRequests, signRequests, timeout) {
var _registerRequests = arrayify(registerRequests);
if (typeof signRequests === 'number' && typeof timeout === 'undefined') {
timeout = signRequests;
signRequests = [];
}
var _signRequests = arrayify(signRequests);
return getBackend()
.then(function (backend) {
_ensureSupport(backend);
var u2f = backend.u2f;
return new Promise(function (resolve, reject) {
function callback(response) {
if (response.errorCode)
reject(makeError("Registration failed", response));
else {
delete response.errorCode;
resolve(response);
}
}
var appId = _registerRequests[0].appId;
u2f.register(appId, _registerRequests, _signRequests, callback, timeout);
});
});
}
function sign(signRequests, timeout) {
var _signRequests = arrayify(signRequests);
return getBackend()
.then(function (backend) {
_ensureSupport(backend);
var u2f = backend.u2f;
return new Promise(function (resolve, reject) {
var _a;
function callback(response) {
if (response.errorCode)
reject(makeError("Sign failed", response));
else {
delete response.errorCode;
resolve(response);
}
}
var appId = _signRequests[0].appId;
var challenge = _signRequests[0].challenge;
var registeredKeys = (_a = []).concat.apply(_a, _signRequests
.map(function (_a) {
var version = _a.version, keyHandle = _a.keyHandle, appId = _a.appId;
return arrayify(keyHandle)
.map(function (keyHandle) {
return ({ version: version, keyHandle: keyHandle, appId: appId });
});
}));
u2f.sign(appId, challenge, registeredKeys, callback, timeout);
});
});
}
var u2fApi = /*#__PURE__*/Object.freeze({
ErrorCodes: ErrorCodes,
ErrorNames: ErrorNames,
isSupported: isSupported,
ensureSupport: ensureSupport,
register: register,
sign: sign
});
window.u2fApi = u2fApi;
}());