feat(BRIDGE-424): implement FIDO2 support

This commit is contained in:
Xavier Michelon
2025-09-08 20:22:34 +02:00
committed by Atanas Janeshliev
parent 2fb5b751b6
commit e091e58be1
13 changed files with 448 additions and 74 deletions

View File

@ -51,8 +51,13 @@ endif()
# We rely on vcpkg for to get gRPC / Protobuf
# run build.sh / build.ps1 to get gRPC / Protobuf and dependencies installed.
set(VCPKG_ROOT "${BRIDGE_REPO_ROOT}/extern/vcpkg")
if(WIN32)
set(VCPKG_ROOT "${BRIDGE_REPO_ROOT}/extern/vcpkg-windows")
else()
set(VCPKG_ROOT "${BRIDGE_REPO_ROOT}/extern/vcpkg")
endif()
message(STATUS "VCPKG_ROOT is ${VCPKG_ROOT}")
if (WIN32)
find_program(VCPKG_EXE "${VCPKG_ROOT}/vcpkg.exe")
else()

View File

@ -22,26 +22,6 @@ Write-host "Bridge-gui directory is $scriptDir"
Write-host "Bridge repos root dir $bridgeRepoRootDir"
Push-Location $scriptDir
# There is bug in CI caused by defining the lower case and upper case
# vars for proxy. For pure bash (case sensitive - creating
# two env items) or pure powershell (case insensitive - by default writes any
# changes into first defined env instance) it is transparent. But during bridge gui
# build we are populating case sensitive env vars from bash to powershell which
# then cause error when trying to list env vars. This is causing an error
# during CMake lookup for CXX and build fails. Therefore we need unset the
# lower case version if present.
Write-Host "Checking for duplicate proxy variables..."
@("HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY") | ForEach-Object {
$upper = $_
$lower = $_.ToLower()
if ((Test-Path "Env:$upper") -and (Test-Path "Env:$lower")) {
Write-Host "Removing duplicate lowercase variable: $lower"
Remove-Item "Env:$lower" -ErrorAction SilentlyContinue
}
}
$ErrorActionPreference = "Stop"
$cmakeExe=$(Get-Command cmake).source
@ -78,7 +58,7 @@ if ($null -eq $buildConfig)
}
$buildDir=(Join-Path $scriptDir "cmake-build-$buildConfig".ToLower())
$vcpkgRoot = (Join-Path $bridgeRepoRootDir "extern/vcpkg" -Resolve)
$vcpkgRoot = (Join-Path $bridgeRepoRootDir "extern/vcpkg-windows" -Resolve)
$vcpkgExe = (Join-Path $vcpkgRoot "vcpkg.exe")
$vcpkgBootstrap = (Join-Path $vcpkgRoot "bootstrap-vcpkg.bat")
@ -91,6 +71,10 @@ function check_exit() {
}
}
# Create short path dirs to avoid windows filepath char limit.
New-Item -ItemType Directory -Force -Path "C:\b" | Out-Null
New-Item -ItemType Directory -Force -Path "C:\p" | Out-Null
Write-host "Running build for version $bridgeVersion - $buildConfig in $buildDir"
$REVISION_HASH = git rev-parse --short=10 HEAD
@ -106,7 +90,7 @@ if ($null -eq $bridgeBuildEnv)
git submodule update --init --recursive $vcpkgRoot
. $vcpkgBootstrap -disableMetrics
. $vcpkgExe install sentry-native:x64-windows grpc:x64-windows --clean-after-build
. $vcpkgExe install sentry-native:x64-windows grpc:x64-windows --x-buildtrees-root=C:\b --x-packages-root=C:\p --clean-after-build
. $vcpkgExe upgrade --no-dry-run
. $cmakeExe -G "Visual Studio 17 2022" -DCMAKE_BUILD_TYPE="$buildConfig" `
-DBRIDGE_APP_FULL_NAME="$bridgeFullName" `

View File

@ -175,15 +175,21 @@ func (f *frontendCLI) loginAccount(c *ishell.Context) {
}
if auth.TwoFA.Enabled&proton.HasTOTP != 0 {
code := f.readStringInAttempts("Two factor code", c.ReadLine, isNotEmpty)
if code == "" {
f.printAndLogError("Cannot login: need two factor code")
return
}
if len(auth.TwoFA.FIDO2.RegisteredKeys) > 0 && f.yesNoQuestion("Do you want to use a security key for Two-factor authentication") {
if err := f.authWithHardwareKey(client, auth); err != nil {
f.printAndLogError("Cannot login: ", err)
return
}
} else {
code := f.readStringInAttempts("Two factor code", c.ReadLine, isNotEmpty)
if code == "" {
f.printAndLogError("Cannot login: need two factor code")
}
if err := client.Auth2FA(context.Background(), proton.Auth2FAReq{TwoFactorCode: code}); err != nil {
f.printAndLogError("Cannot login: ", err)
return
if err := client.Auth2FA(context.Background(), proton.Auth2FAReq{TwoFactorCode: code}); err != nil {
f.printAndLogError("Cannot login: ", err)
return
}
}
}

View File

@ -0,0 +1,171 @@
//go:build linux || darwin
package cli
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/ProtonMail/go-proton-api"
"github.com/fxamacker/cbor/v2"
"github.com/keys-pub/go-libfido2"
)
func (f *frontendCLI) authWithHardwareKey(client *proton.Client, auth proton.Auth) error {
var fido2Device *libfido2.DeviceLocation
retryCount := 0
for {
locs, err := libfido2.DeviceLocations()
if err != nil {
f.printAndLogError("Cannot retrieve security key list: ", err)
}
if len(locs) == 0 {
fmt.Print("Please insert your security key and press enter to continue.")
f.ReadLine()
} else {
fido2Device = locs[0]
break
}
retryCount++
if retryCount >= 3 {
break
}
}
if fido2Device == nil {
return errors.New("no device found")
}
dev, err := libfido2.NewDevice(fido2Device.Path)
if err != nil {
return fmt.Errorf("cannot open security key: %w", err)
}
// Check if the key has a PIN set first
var pin string
info, err := dev.Info()
if err != nil {
return fmt.Errorf("cannot get device info: %w", err)
}
// Check if clientPin option is available and set
pinSupported := false
for _, option := range info.Options {
if option.Name == "clientPin" && option.Value == libfido2.True {
pinSupported = true
break
}
}
if pinSupported {
pin = f.readStringInAttempts("Security key PIN", f.ReadPassword, isNotEmpty)
if pin == "" {
return errors.New("PIN is required for this security key")
}
}
fmt.Println("Please touch your security key...")
authOptions, ok := auth.TwoFA.FIDO2.AuthenticationOptions.(map[string]interface{})
if !ok {
return errors.New("invalid authentication options format")
}
publicKey, ok := authOptions["publicKey"].(map[string]interface{})
if !ok {
return errors.New("no publicKey found in authentication options")
}
allowCredentials, ok := publicKey["allowCredentials"].([]interface{})
if !ok || len(allowCredentials) == 0 {
return errors.New("no allowed credentials found in authentication options")
}
var credentialIDs [][]byte //nolint:prealloc
for _, cred := range allowCredentials {
credMap, ok := cred.(map[string]interface{})
if !ok {
continue
}
idArray, ok := credMap["id"].([]interface{})
if !ok {
continue
}
credID := sliceAnyToByteArray(idArray)
credentialIDs = append(credentialIDs, credID)
}
if len(credentialIDs) == 0 {
return errors.New("no valid credential IDs found")
}
challengeArray, ok := publicKey["challenge"].([]interface{})
if !ok {
return errors.New("no challenge found in authentication options")
}
challenge := sliceAnyToByteArray(challengeArray)
rpID, ok := publicKey["rpId"].(string)
if !ok {
return errors.New("could not find rpId in authentication options")
}
clientDataJSON := map[string]interface{}{
"type": "webauthn.get",
"challenge": base64.URLEncoding.EncodeToString(challenge),
"origin": "https://" + rpID,
}
clientDataJSONBytes, err := json.Marshal(clientDataJSON)
if err != nil {
return fmt.Errorf("cannot marshal client data: %w", err)
}
clientDataHash := sha256.Sum256(clientDataJSONBytes)
assertion, err := dev.Assertion(
rpID,
clientDataHash[:],
credentialIDs,
pin,
&libfido2.AssertionOpts{UP: libfido2.True},
)
if err != nil {
return fmt.Errorf("FIDO2 assertion failed: %w", err)
}
// Decode CBOR to get raw authenticator data
var authData []byte
err = cbor.Unmarshal(assertion.AuthDataCBOR, &authData)
if err != nil {
return fmt.Errorf("failed to decode CBOR authenticator data: %w", err)
}
// Convert CredentialID bytes to array of integers
credentialIDInts := make([]int, len(assertion.CredentialID))
for i, b := range assertion.CredentialID {
credentialIDInts[i] = int(b)
}
fido2Req := proton.FIDO2Req{
AuthenticationOptions: auth.TwoFA.FIDO2.AuthenticationOptions,
ClientData: base64.StdEncoding.EncodeToString(clientDataJSONBytes),
AuthenticatorData: base64.StdEncoding.EncodeToString(authData),
Signature: base64.StdEncoding.EncodeToString(assertion.Sig),
CredentialID: credentialIDInts,
}
fmt.Println("Submitting FIDO2 authentication request.")
if err := client.Auth2FA(context.Background(), proton.Auth2FAReq{FIDO2: fido2Req}); err != nil {
return fmt.Errorf("FIDO2 authentication failed: %w", err)
}
fmt.Println("FIDO2 authentication succeeded")
return nil
}

View File

@ -0,0 +1,126 @@
//go:build windows
package cli
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log/slog"
"github.com/ProtonMail/go-proton-api"
"github.com/go-ctap/ctaphid/pkg/webauthntypes"
"github.com/go-ctap/winhello"
"github.com/go-ctap/winhello/hiddenwindow"
)
func (f *frontendCLI) authWithHardwareKey(client *proton.Client, auth proton.Auth) error {
// Windows Hello requires a window handle to work, as indicated by the docs of the lib.
wnd, err := hiddenwindow.New(slog.New(slog.DiscardHandler), "Proton Bridge Auth")
if err != nil {
return fmt.Errorf("failed to create window for Windows Hello: %w", err)
}
defer wnd.Close()
authOptions, ok := auth.TwoFA.FIDO2.AuthenticationOptions.(map[string]interface{})
if !ok {
return fmt.Errorf("invalid authentication options format")
}
publicKey, ok := authOptions["publicKey"].(map[string]interface{})
if !ok {
return fmt.Errorf("no publicKey found in authentication options")
}
rpId, ok := publicKey["rpId"].(string)
if !ok {
return fmt.Errorf("could not find rpId in authentication options")
}
challengeArray, ok := publicKey["challenge"].([]interface{})
if !ok {
return fmt.Errorf("no challenge found in authentication options")
}
challenge := sliceAnyToByteArray(challengeArray)
allowCredentials, ok := publicKey["allowCredentials"].([]interface{})
if !ok || len(allowCredentials) == 0 {
return fmt.Errorf("no allowed credentials found in authentication options")
}
var credentialDescriptors []webauthntypes.PublicKeyCredentialDescriptor
for _, cred := range allowCredentials {
credMap, ok := cred.(map[string]interface{})
if !ok {
continue
}
idArray, ok := credMap["id"].([]interface{})
if !ok {
continue
}
credID := sliceAnyToByteArray(idArray)
credentialDescriptors = append(credentialDescriptors, webauthntypes.PublicKeyCredentialDescriptor{
ID: credID,
Type: webauthntypes.PublicKeyCredentialTypePublicKey,
})
}
if len(credentialDescriptors) == 0 {
return fmt.Errorf("no valid credential descriptors found")
}
clientDataJSON := map[string]interface{}{
"type": "webauthn.get",
"challenge": base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(challenge),
"origin": "https://" + rpId,
}
clientDataJSONBytes, err := json.Marshal(clientDataJSON)
if err != nil {
return fmt.Errorf("failed to marshal client data JSON: %w", err)
}
fmt.Println("Please use Windows Hello to authenticate.")
assertion, err := winhello.GetAssertion(
wnd.WindowHandle(),
rpId,
clientDataJSONBytes,
credentialDescriptors,
nil,
&winhello.AuthenticatorGetAssertionOptions{
AuthenticatorAttachment: winhello.WinHelloAuthenticatorAttachmentCrossPlatform,
UserVerificationRequirement: winhello.WinHelloUserVerificationRequirementDiscouraged,
CredentialHints: []webauthntypes.PublicKeyCredentialHint{
webauthntypes.PublicKeyCredentialHintSecurityKey,
},
},
)
if err != nil {
return fmt.Errorf("windows Hello assertion failed: %w", err)
}
authData := assertion.AuthDataRaw
credentialIDInts := make([]int, len(assertion.Credential.ID))
for i, b := range assertion.Credential.ID {
credentialIDInts[i] = int(b)
}
fido2Req := proton.FIDO2Req{
AuthenticationOptions: auth.TwoFA.FIDO2.AuthenticationOptions,
ClientData: base64.StdEncoding.EncodeToString(clientDataJSONBytes),
AuthenticatorData: base64.StdEncoding.EncodeToString(authData),
Signature: base64.StdEncoding.EncodeToString(assertion.Signature),
CredentialID: credentialIDInts,
}
fmt.Println("Submitting FIDO2 authentication request.")
if err := client.Auth2FA(context.Background(), proton.Auth2FAReq{FIDO2: fido2Req}); err != nil {
return fmt.Errorf("FIDO2 authentication failed: %w", err)
} else {
fmt.Println("FIDO2 authentication succeeded")
}
return nil
}

View File

@ -110,3 +110,15 @@ Recommendation:
a different network to access Proton Mail.
`)
}
func sliceAnyToByteArray(s []any) []byte {
result := make([]byte, len(s))
for i, val := range s {
if intVal, ok := val.(float64); ok {
result[i] = byte(intVal)
} else {
panic("boom")
}
}
return result
}