🔐

パスキーでログイン:自分のシークレットは自分で管理する with Go

に公開

はじめに

apple_passkey_login.jpg
https://developer.apple.com/passkeys のヘッダー画像

最近、私はウェブサービスで認証する時、「パスキーでログイン」 というボタンがあると、思わず微笑みながらすぐにクリックすることが多くなりました。パスキーを使った認証方法がより安全で便利だからです。そこで「パスキーでログイン」ボタンが何を意味するかについて説明します。

WebAuthn (Web Authentication) 概要

W3C(World Wide Web Consortium) は World Wide Web のための国際標準化機構です。

FIDO2 プロジェクトは ウェブで強力な認証を作るために FIDO Alliance と W3C が共に研究するプロジェクトです。

WebAuthnは W3Cで策定されたウェブ標準であり、FIDO2 プロジェクトの中核を成す構成要素です。開発者なら ssh で使う Public-key authentication(公開鍵認証) と近いものだと考えるとイメージしやすいでしょう。WebAuthnはパスワードの代わりに公開鍵・秘密鍵のペアを使用するため、ユーザーは本人の秘密「パスワード」や「秘密鍵」をサーバーに転送しません。

WebAuthnは次のような構成要素を含みます:

  1. ウェブサイト : WebAuthnに準拠する信頼当事者 (Relying Party)
  2. ウェブブラウザー : WebAuthnに準拠するクライアント
  3. 認証器 : WebAuthn クライアントとの互換性を前提とした、FIDO2 認証器

WebAuthnは、ウェブサイトが WebAuthn Credentials(資格情報)でユーザーを認証する APIを定義し、WebAuthn 認証器が実行する動作を定義します。

”パスキーの説明って言ったのに、なんで WebAuthn?”って思われたら、すぐ説明しているので、そちらをご確認いただいても大丈夫です。

WebAuthn 認証器

WebAuthn 認証器は信頼できる認証情報管理器です。WebAuthn 認証器はユーザーの秘密鍵を安全に保管し、サーバーから貰ったチャレンジに署名する役割があります。また認証器は色んな種類があり、次のようになります:

  1. プラットフォーム認証器 : デバイス本体に内蔵された認証器で、主に生体認証を通して認証を要求。
    • ハードウェア TPM
  2. ローミング認証器 : デバイス本体に存在しない移動型認証器で、クロスプラットフォーム認証器とも呼ばれる
    • YubiKey, スマホアラート認証(CaBLE プロトコル) など
  3. ソフトウェア認証器 : 暗号化されたクラウドサービスに同期化する方法で、アプリ・拡張機能の形
    • クラウドに秘密鍵をアップロードするため、特定のハードウェアが破壊・紛失した際にも復元が可能です。
    • ただし、ソフトウェア認証器のマスターパスワードの盗用された場合、保存された全ての認証情報が流出するリスクがあります。
    • Bitwarden, Apple パスワードアプリ

パスキー(Passkey)

パスキー(Passkey)は 「とある WebAuthn 認証器に管理される WebAuthn 資格情報」 を示す非技術的用語です。Google, GitHub など多様なサービスの認証システムでユーザーに WebAuthn 資格情報を Passkeyって呼んでいます。

一般ユーザーの立場で、「WebAuthn(Web Authentication) 資格情報でログイン」ボタンはあまりにも専門的すぎてクリックしない可能性が高そうです。

WebAuthn 動作フロー

WebAuthnの 動作フローは大きく Registration(登録) と Authentication(認証) 二つで分けられます。このフローは一般的サービスの加入・ログインと似たものです。ただし、この過程でサーバーはユーザーのシークレット「秘密鍵」や「パスワード」は絶対に知ることはなく、各鍵の使用所は次のようになります:

  • 秘密鍵 : 署名時、クライアントが使用
  • 公開鍵 : 検証時、サーバーが使用

Registration(登録)

  1. 登録リクエスト (クライアント -> サーバー)
    - 例)ユーザーがウェブサイトで「パスキー登録」ボタンクリック
  2. チャレンジとオプション生成 (サーバー -> クライアント)
    • サーバーは次のような情報を含めたオプションオブジェクトを生成
      • challenge : 署名と検証時、使うランダム文字列
      • rp : Relying Party 情報(idプロパティで有効なドメイン範囲指定)
      • user : 現在登録するユーザーの情報
      • pubKeyCredParams : 推奨暗号化アルゴリズム
    • クライアント(ブラウザー)にこのオプションオブジェクト送信
  3. 認証器呼び出し (クライアント -> 認証器)
    • ブラウザーは WebAuthn API navigator.credentials.create() 呼び出し
    • 認証器にオプションオブジェクト送信
  4. ユーザー検証と鍵生成 (認証器)
    • 認証器がユーザーに PINまたは生体認証(FaceID など)を要求し、本人確認
    • 確認成功時、認証器がそのウェブサイト専用の新しい公開鍵・秘密鍵ペアを生成
    • 秘密鍵は安全な領域に保存され、それを識別するための Credential IDを生成
  5. 署名と送信 (認証器 -> クライアント -> サーバー)
    • 生成された秘密鍵を使ってサーバーから受け取ったチャレンジに電子署名値生成
    • 公開鍵、電子署名、暗号化アルゴリズム、Credential IDをクライアント(ブラウザー)に送信
    • クライアント(ブラウザー)はこのデータをサーバーに送信
  6. 検証と保存 (サーバー)
    • サーバーは送信された公開鍵を使って電子署名の有効性検証
    • 検証成功時、サーバーは次のような情報を DBに保存
      • ユーザーID -> Credential ID、公開鍵、暗号化アルゴリズム

Authentication(認証)

  1. ログインリクエスト (クライアント -> サーバー)
    • 例)ユーザーがウェブサイトで「パスキーでログイン」ボタンクリック
  2. チャレンジ生成 (サーバー -> クライアント)
    • サーバーはランダム文字列のチャレンジ生成
    • DBに保存している Credential ID リストと共にクライアント「ブラウザー」に送信
  3. 認証器呼び出し (クライアント -> 認証器)
    • ブラウザーは WebAuthn API navigator.credentials.get() 呼び出し
    • 認証器にデータ送信
  4. ユーザー検証と署名 (認証器)
    • 認証器は送信された Credential ID リストに該当する秘密鍵存在確認
    • 認証器がユーザーに PINまたは生体認証(FaceID など)を要求し、本人確認
    • 確認成功時、認証器に保存された秘密鍵を使ってサーバーから受け取ったチャレンジに電子署名値生成
  5. 署名送信 (認証器 -> クライアント -> サーバー)
    • 生成された電子署名値をブラウザーを通してサーバーに送信
  6. 検証と完了 (サーバー)
    • サーバーは DBに保存された公開鍵と暗号化アルゴリズムを使って電子署名検証
    • 検証成功時、ログイン処理

WebAuthn 認証システム実装 with Go

WebAuthn 認証システムを Go + Gin プロジェクトで実装しました。WebAuthn 動作フローの各手順がコード内のコメントで登場します!

gymynnym/learn-webauthn リポジトリでソースコードを確認できます。

$ mkdir learn-webauthn && cd learn-webauthn/
$ go mod init learn-webauthn
$ go get -u github.com/gin-gonic/gin
$ go get -u github.com/go-webauthn/webauthn/webauthn

WebAuthn と Gin ウェブサーバー初期化

// model.go
package main

type RegistrationCache struct {
	SessionData webauthn.SessionData
	PendingUser *User
}

RegistrationCacheは Registration(登録)に使うキャッシュストア構造体です。

  • SessionData : 登録の認証時使用
  • PendingUser : 認証完了時、DBに保存するユーザーオブジェクト
package main

import (
  "github.com/gin-gonic/gin"
  "github.com/go-webauthn/webauthn/webauthn"
)

const ( // Gin サーバー設定
  HOSTNAME = "localhost"
  PORT     = ":8080"
)

var (
  userDB                 = map[string]*User{}                 // in-memory DB (username -> User)
  registrationCacheStore = map[string]*RegistrationCache{}    // in-memory registration キャッシュストア (username -> RegistrationCache)
  loginSessionStore      = map[string]*webauthn.SessionData{} // in-memory login キャッシュストア (username -> SessionData)
  webAuthn               *webauthn.WebAuthn
)

func initWebAuthn() { // WebAuthn 初期化
  var err error
  webAuthn, err = webauthn.New(&webauthn.Config{
    // Relying Party 情報設定
    RPDisplayName: "Example App",
    RPID:          HOSTNAME,
    RPOrigins:     []string{"http://" + HOSTNAME + PORT},
  })
  if err != nil {
    panic("Failed to initialize WebAuthn: " + err.Error())
  }
}

func main() {
  initWebAuthn()

  r := gin.Default()
  if err := r.Run(PORT); err != nil {
    panic("Failed to start server: " + err.Error())
  }
}
  • userDB : ユーザー専用 in-memory DB
  • registrationCacheStore : 登録で使用するキャッシュストア
  • loginSessionStore : 認証で使用するキャッシュストア
  • webAuthn : WebAuthn オブジェクト
  • main.r : Gin サーバー、ルーター

ユーザーモデル定義

ユーザーモデルを WebAuthnライブラリと一緒に使う場合、webauthn.User インタフェースの実装が必要です。

// webauthn/types.go
type User interface {
  WebAuthnID() []byte                // ユーザー ID (最大 64bytes)
  WebAuthnName() string              // ユーザーアカウント名
  WebAuthnDisplayName() string       // ユーザー表示名 (for-human readable)
  WebAuthnCredentials() []Credential // 資格情報リスト
}

通常、WebAuthnIDは DBに保存されたユーザーIDそのままで使います。しかし、DBに保存された ユーザーIDは、整数型の場合もあれば UUID型の場合もあり、多様なデータ型に対応するため、byte型です。

// model.go
package main

import (
	"encoding/binary"

	"github.com/go-webauthn/webauthn/webauthn"
)

type User struct {
	ID          uint64
	Name        string
	Credentials webauthn.Credentials
}

func (u *User) WebAuthnID() []byte {
	b := make([]byte, 8)
	binary.LittleEndian.PutUint64(b, u.ID)
	return b
}
func (u *User) WebAuthnName() string                       { return u.Name }
func (u *User) WebAuthnDisplayName() string                { return u.Name }
func (u *User) WebAuthnCredentials() []webauthn.Credential { return u.Credentials }

登録(Registration)実装

func beginRegistration(c *gin.Context) {
  username := c.Param("username")

  // ユーザー存在確認
  if _, exists := userDB[username]; exists {
    c.JSON(409, gin.H{"error": "User already exists"})
      return
  }

  // ユーザー生成
  user := User{
    ID:   uint64(len(userDB) + 1),
    Name: username,
  }

  // 登録#2: チャレンジとオプション生成
  options, sessionData, err := webAuthn.BeginRegistration(&user)
  if err != nil {
    c.JSON(500, gin.H{"error": "Failed to begin registration"})
    return
  }

  // キャッシュストアにセッションデータとユーザー情報を保存
  registrationCacheStore[username] = &RegistrationCache{
    SessionData: *sessionData,
    PendingUser: &user,
  }
  c.JSON(200, options)
}

func finishRegistration(c *gin.Context) {
  username := c.Param("username")

  // セッションデータとユーザー情報取得
  cache, exists := registrationCacheStore[username]
  if !exists {
    c.JSON(400, gin.H{"error": "No session data found"})
    return
  }

  // 登録#6: 検証
  credential, err := webAuthn.FinishRegistration(cache.PendingUser, cache.SessionData, c.Request)
  if err != nil {
    c.JSON(400, gin.H{"error": "Failed to finish registration"})
    return
  }

  // 登録#6: 保存
  user := cache.PendingUser
  user.Credentials = append(user.Credentials, *credential) // 新しい資格情報を追加
  userDB[username] = user                                  // ユーザーDBに保存
  delete(registrationCacheStore, username)                 // キャッシュストアから削除

  c.JSON(200, gin.H{"status": "Registration successful"})
}
func main() {
  // ...
  r.GET("/register/begin/:username", beginRegistration)
  r.POST("/register/finish/:username", finishRegistration)
  // ...
}

GET /register/begin/:username エンドポイントは 登録(Registration)を始めるためのAPIで、次のような役割を果たします:

  1. クライアントから受け取った、usernameで DBに存在するか確認
  2. もしない場合、User オブジェクト生成
  3. その User オブジェクトに対するチャレンジとオプションを生成し、クライアントにレスポンス
    • この場合、registrationCacheStoreに SessionData と User オブジェクト保存

POST /register/finish/:username エンドポイントは 登録(Registration)を完了させるためのAPIで、次のような役割を果たします:

  1. クライアントから受け取った、usernameで キャッシュストアにキャッシュが存在するか確認
  2. もしある場合、クライアントから受け取った電子署名検証
  3. 検証成功時、キャッシュストアから User オブジェクトを取得し、Credentialと一緒に DBに保存
  4. キャッシュストアのクリアと完了

認証(Authentication)実装

func beginLogin(c *gin.Context) {
  username := c.Param("username")

  // ユーザー取得と存在確認
  user, exists := userDB[username]
  if !exists {
    c.JSON(404, gin.H{"error": "User not found"})
    return
  }

  // 認証#2: チャレンジとオプション生成
  options, sessionData, err := webAuthn.BeginLogin(user)
  if err != nil {
    c.JSON(500, gin.H{"error": "Failed to begin login"})
    return
  }

  loginSessionStore[username] = sessionData
  c.JSON(200, options)
}

func finishLogin(c *gin.Context) {
  username := c.Param("username")

  // ユーザー取得と存在確認
  user, exists := userDB[username]
  if !exists {
    c.JSON(404, gin.H{"error": "User not found"})
    return
  }

  // キャッシュストアからセッションデータ取得
  sessionData, exists := loginSessionStore[username]
  if !exists {
    c.JSON(400, gin.H{"error": "No session data found"})
    return
  }

  // #認証#6: 検証
  credential, err := webAuthn.FinishLogin(user, *sessionData, c.Request)
  if err != nil {
    c.JSON(400, gin.H{"error": "Failed to finish login"})
    return
  }
  _ = credential // TODO: Credentialを使ったセッションまたはトークン生成

  delete(loginSessionStore, username) // キャッシュストアから削除

  c.JSON(200, gin.H{"status": "Login successful"})
}

GET /login/begin/:username エンドポイントは 認証(Authentication)を始めるためのAPIで、次のような役割を果たします:

  1. クライアントから受け取った、usernameで DBに存在するか確認
  2. もしある場合、チャレンジ生成とレスポンス
    • この場合、loginSessionStoreに SessionData オブジェクト 保存

POST /login/finish/:username エンドポイントは 認証(Authentication)を完了させるためのAPIで、次のような役割を果たします:

  1. クライアントから受け取った、usernameで DBに存在するか確認
  2. loginSessionStoreで SessionData 取得
  3. もしある場合、検証
  4. 検証成功時、セッションまたはトークン生成(ログイン情報生成)
  5. キャッシュストアのクリアと完了

クライアント実装

<div>
  <h1>Passkey Demo (Go + Gin)</h1>
</div>
<div>
  <label>Username: <input type="text" id="username" value="foo"></label>
  <br/>
  <button onclick="register()">パスキー登録</button>
  <button onclick="login()">パスキーでログイン</button>
</div>
<div id="logs" />
// Log utilities
const logEl = document.getElementById('logs');
function log(msg) {
  logEl.innerText = `${logEl.innerText}\n${msg}`;
}

// Base64 URL-safe Endcode/Decode utilities
function bufferDecode(value) {
  return Uint8Array.from(atob(value.replace(/-/g, "+")
    .replace(/_/g, "/")), c => c.charCodeAt(0));
}
function bufferEncode(value) {
  return btoa(String.fromCharCode.apply(null, new Uint8Array(value)))
    .replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}

async function register() {
  const username = document.getElementById('username').value;

  try {
    // 登録#1: 登録リクエスト
    const beginRes = await fetch(`/register/begin/${username}`);
    const options = await beginRes.json();

    // 登録#3: 認証器呼び出し
    log("[Register] call authenticator");
    options.publicKey.challenge = bufferDecode(options.publicKey.challenge);
    options.publicKey.user.id = bufferDecode(options.publicKey.user.id);
    const credential = await navigator.credentials.create({ publicKey: options.publicKey });

    // 登録#5: 署名と送信
    const credentialJSON = {
      id: credential.id,
      rawId: bufferEncode(credential.rawId),
      type: credential.type,
      response: {
        attestationObject: bufferEncode(credential.response.attestationObject),
        clientDataJSON: bufferEncode(credential.response.clientDataJSON),
      },
    };
    const finishRes = await fetch(`/register/finish/${username}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(credentialJSON)
    });

    const finishJSON = await finishRes.json();
    log("[Register] finished: " + JSON.stringify(finishJSON));
  } catch (e) {
    log("Error: " + e);
    console.error(e);
  }
}

async function login() {
  const username = document.getElementById('username').value;
  try {
    // 認証#1: ログインリクエスト
    const beginRes = await fetch(`/login/begin/${username}`);
    const options = await beginRes.json();

    // 認証#3: 認証器呼び出し
    log("[Login] call authenticator");
    options.publicKey.challenge = bufferDecode(options.publicKey.challenge);
    options.publicKey.allowCredentials.forEach(c => {
      c.id = bufferDecode(c.id);
    });
    const assertion = await navigator.credentials.get({ publicKey: options.publicKey });

    // 認証#5: 署名と送信
    const assertionJSON = {
      id: assertion.id,
      rawId: bufferEncode(assertion.rawId),
      type: assertion.type,
      response: {
        authenticatorData: bufferEncode(assertion.response.authenticatorData),
        clientDataJSON: bufferEncode(assertion.response.clientDataJSON),
        signature: bufferEncode(assertion.response.signature),
        userHandle: assertion.response.userHandle ? bufferEncode(assertion.response.userHandle) : null,
      },
    };
    const finishRes = await fetch(`/login/finish/${username}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(assertionJSON)
    });

    const finishJSON = await finishRes.json();
    log("[Login] finished: " + JSON.stringify(finishJSON));
  } catch (e) {
    log("Error: " + e);
    console.error(e);
  }
}

register 関数は「パスキー登録」ボタンをクリックしたら実行され、次のような役割を果たします:

  1. input#usernameの値取得
  2. 登録開始リクエスト後、PublicKeyCredentialCreationOptions オブジェクト受け取る
  3. データデコード後、認証器呼び出し
  4. 認証器で署名
  5. 署名結果エンコード後、登録完了リクエスト
  6. 完了レスポンス受け取って、ログ表示

結果

結果
パスキー登録・ログイン後画面

WebAuthn API navigator.credentialsは httpsが必須ですが、ローカル開発の場合例外的に許可されます!

まとめ

WebAuthn(Passkey)を使う認証方法はユーザー個人がシークレットを管理し、サーバーには保存しません。従って、万が一サーバーがハックされてもユーザーのシークレットは流出しない魅力的な認証方法ですが、全てのユーザーが WebAuthn 認証の利用環境を持ってはいません。例として、パスワードマネジャーを使っていなかったり、ハードウェアによっては TPM モジュールがない場合もたくさんあります。そこで WebAuthn 認証をサポートするサービスも補助認証手段として使われているだけ、WebAuthn-only(password-less)の場合はあまり見つかりません。ユーザー設定で ”「Passkeyで優先ログイン」チェックボックスが追加される”などの動きはありますが、まだ過渡期のようです。もしかすると、パスワードログインは便利すぎて、消えないかも知れません。

Discussion