feat(BRIDGE-424): FIDO2 GUI support.

This commit is contained in:
Atanas Janeshliev
2025-09-16 13:07:45 +02:00
parent e091e58be1
commit edf903fd21
42 changed files with 3567 additions and 3510 deletions

View File

@ -19,6 +19,7 @@ package cli
import (
"context"
"errors"
"fmt"
"strings"
@ -26,7 +27,9 @@ import (
"github.com/ProtonMail/proton-bridge/v3/internal/bridge"
"github.com/ProtonMail/proton-bridge/v3/internal/certs"
"github.com/ProtonMail/proton-bridge/v3/internal/constants"
"github.com/ProtonMail/proton-bridge/v3/internal/fido"
"github.com/ProtonMail/proton-bridge/v3/internal/hv"
"github.com/ProtonMail/proton-bridge/v3/internal/unleash"
"github.com/ProtonMail/proton-bridge/v3/internal/vault"
"github.com/abiosoft/ishell"
)
@ -174,22 +177,39 @@ func (f *frontendCLI) loginAccount(c *ishell.Context) {
return
}
if auth.TwoFA.Enabled&proton.HasTOTP != 0 {
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")
}
u2fLoginEnabled := f.bridge.GetFeatureFlagValue(unleash.InboxBridgeU2FLoginEnabled)
if err := client.Auth2FA(context.Background(), proton.Auth2FAReq{TwoFactorCode: code}); err != nil {
switch auth.TwoFA.Enabled {
case proton.HasTOTP:
if err := f.loginTOTP(c, client); err != nil {
f.printAndLogError("Cannot login: ", err)
return
}
case proton.HasFIDO2:
if !u2fLoginEnabled {
// This case may only occur for internal users.
f.printAndLogError("Cannot login: Security key authentication required but not enabled in server configuration.")
return
}
if len(auth.TwoFA.FIDO2.RegisteredKeys) == 0 {
f.printAndLogError("Cannot login: Security key login is required, but no registered keys were provided.")
}
if err := fido.AuthWithHardwareKeyCLI(f, client, auth); err != nil {
f.printAndLogError("Cannot login: ", err)
return
}
case proton.HasFIDO2AndTOTP:
if u2fLoginEnabled && len(auth.TwoFA.FIDO2.RegisteredKeys) > 0 && f.yesNoQuestion("Do you want to use a security key for Two-factor authentication") {
if err := fido.AuthWithHardwareKeyCLI(f, client, auth); err != nil {
f.printAndLogError("Cannot login: ", err)
return
}
} else if err := f.loginTOTP(c, client); err != nil {
f.printAndLogError("Cannot login: ", err)
return
}
}
@ -230,6 +250,15 @@ func (f *frontendCLI) loginAccount(c *ishell.Context) {
f.Printf("Account %s was added successfully.\n", bold(user.Username))
}
func (f *frontendCLI) loginTOTP(c *ishell.Context, client *proton.Client) error {
code := f.readStringInAttempts("Two factor code", c.ReadLine, isNotEmpty)
if code == "" {
return errors.New("need two factor code")
}
return client.Auth2FA(context.Background(), proton.Auth2FAReq{TwoFactorCode: code})
}
func (f *frontendCLI) loginAccountHv(c *ishell.Context, loginName string, password string, keyPass []byte, hvDetails *proton.APIHVDetails) {
f.promptHvURL(hvDetails)
client, auth, err := f.bridge.LoginAuth(context.Background(), loginName, []byte(password), hvDetails)

View File

@ -1,171 +0,0 @@
//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

@ -1,126 +0,0 @@
//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

@ -45,6 +45,11 @@ func (f *frontendCLI) yesNoQuestion(question string) bool {
return len(answer) > 0 // Empty is false.
}
func (f *frontendCLI) PromptAndWaitReturn(prompt string) {
f.Print(prompt, ". Press Enter/Return to continue: ")
f.ReadLine()
}
func (f *frontendCLI) readStringInAttempts(title string, readFunc func() string, isOK func(string) bool) (value string) {
f.Printf("%s: ", title)
value = readFunc()
@ -60,6 +65,10 @@ func (f *frontendCLI) readStringInAttempts(title string, readFunc func() string,
return
}
func (f *frontendCLI) ReadSecurityKeyPin() string {
return f.readStringInAttempts("Security key PIN", f.ReadPassword, isNotEmpty)
}
func (f *frontendCLI) printAndLogError(args ...interface{}) {
log.Error(args...)
f.Println(args...)
@ -110,15 +119,3 @@ 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
}