OS Login でセキュリティ キーを有効にする


このドキュメントでは、Google アカウントに登録されている物理的なセキュリティ キーを使用して、OS Login を使用する仮想マシン(VM)インスタンスに接続する方法について説明します。

物理的なセキュリティ キーを使用して、VM に接続するための SSH 秘密鍵ファイルを生成します。Google Cloud コンソールのブラウザでの SSH ツールまたは Google Cloud CLI を使用している場合、セキュリティ キーを使用して VM に接続すると、OS Login はセキュリティ キーに関連付けられている秘密 SSH 認証鍵ファイルを取得し、SSH 認証鍵ファイルを構成します。サードパーティ ツールを使用して接続する場合は、OS Login API を使用して SSH 認証鍵情報を取得し、SSH 認証鍵ファイルをご自身で構成する必要があります。

準備

  • Google アカウントにセキュリティ キーを追加します。
  • OS Login を設定します。
  • まだ設定していない場合は、認証を設定します。認証とは、Google Cloud サービスと API にアクセスするために ID を確認するプロセスです。ローカル開発環境からコードまたはサンプルを実行するには、次のように Compute Engine に対する認証を行います。

    このページのサンプルをどのように使うかに応じて、タブを選択してください。

    コンソール

    Google Cloud コンソールを使用して Google Cloud サービスと API にアクセスする場合、認証を設定する必要はありません。

    gcloud

    1. Google Cloud CLI をインストールし、次のコマンドを実行して初期化します。

      gcloud init
    2. デフォルトのリージョンとゾーンを設定します

    REST

    このページの REST API サンプルをローカル開発環境で使用するには、gcloud CLI に指定した認証情報を使用します。

      Google Cloud CLI をインストールし、次のコマンドを実行して初期化します。

      gcloud init

制限事項

  • セキュリティ キーが有効にされている VM は、Google アカウントに登録されている物理的なセキュリティ キーにアタッチされている SSH 認証鍵からの接続のみを受け入れます。
  • 接続先の VM と接続元のワークステーションの両方で、セキュリティ キーの SSH タイプをサポートする OpenSSH 8.2 以降のバージョンを使用する必要があります。次の Compute Engine VM オペレーティング システムはセキュリティ キーをサポートしています。

    • Debian 11(またはそれ以降)
    • SUSE Linux Enterprise Server(SLES)15(またはそれ以降)
    • Ubuntu 20.04 LTS(またはそれ以降)
    • Container-Optimized OS 93 LTS(またはそれ以降)
    • Rocky Linux 9(またはそれ以降)

    ご使用の環境がセキュリティ キーをサポートしているかどうかを確認するには、次のコマンドを実行します。

    ssh -Q key | grep ^sk-
    

    コマンドから出力が返されない場合、ご使用の環境はセキュリティ キーをサポートしていません。

OS Login でセキュリティ キーを有効にする

プロジェクトで OS Login を使用するすべての VM または単一の VM に対してセキュリティ キーの使用を有効にできます。

OS Login が有効になっているプロジェクト内のすべての VM のセキュリティ キーを有効にする

プロジェクト内の OS Login を使用するすべての VM でセキュリティ キーを有効にするには、Google Cloud コンソールまたは gcloud CLI を使用します。

コンソール

OS Login が有効になっているすべての VM のセキュリティ キーを有効にするには、Google Cloud コンソールを使用して、プロジェクトのメタデータで enable-osloginenable-oslogin-skTRUE に設定します。

  1. [メタデータ] ページに移動します。

    [メタデータ] に移動

  2. [編集] をクリックします。

  3. [項目を追加] をクリックします。

    1. [キー] フィールドに「enable-oslogin」と入力します。
    2. [] に「TRUE」と入力します。
  4. [項目を追加] をクリックします。

    1. [キー] フィールドに「enable-oslogin-sk」と入力します。
    2. [] に「TRUE」と入力します。
  5. [保存] をクリックします。

gcloud

OS Login が有効になっているすべての VM のセキュリティ キーを有効にするには、gcloud compute project-info add-metadata コマンドを使用してプロジェクトのメタデータで enable-oslogin=TRUEenable-oslogin-sk=TRUE を設定します。

gcloud compute project-info add-metadata \
    --metadata enable-oslogin=TRUE,enable-oslogin-sk=TRUE

OS Login が有効になっている単一の VM でセキュリティ キーを有効にする

OS Login を使用する 1 つの VM でセキュリティ キーを有効にするには、Google Cloud コンソールまたは gcloud CLI を使用します。

コンソール

単一の VM でセキュリティ キーを有効にするには、Google Cloud コンソールを使用して、インスタンスのメタデータで enable-osloginenable-oslogin-skTRUE に設定します。

  1. [VM インスタンス] ページに移動します。

    [VM インスタンス] に移動

  2. セキュリティ キーを有効にする VM の名前をクリックします。

  3. [編集] をクリックします。

  4. [カスタム メタデータ] セクションで [項目を追加] をクリックします。

    1. [キー] フィールドに「enable-oslogin」と入力します。
    2. [] に「TRUE」と入力します。
  5. [項目を追加] をクリックします。

    1. [キー] フィールドに「enable-oslogin-sk」と入力します。
    2. [] に「TRUE」と入力します。
  6. [保存] をクリックします。

gcloud

1 つの VM でセキュリティ キーを有効にするには、gcloud compute instances add-metadata コマンドを使用して、インスタンス メタデータに enable-oslogin=TRUEenable-oslogin-sk=TRUE を設定します。

gcloud compute instances add-metadata VM_NAME \
    --metadata enable-oslogin=TRUE,enable-oslogin-sk=TRUE

VM_NAME は実際の VM 名に置き換えます。

セキュリティ キーを使用して VM に接続する

セキュリティ キーを使用する VM に接続するには、Google Cloud コンソール、gcloud CLI、またはサードパーティ ツールを使用します。Google Cloud コンソールまたは gcloud CLI を使用して VM に接続すると、Compute Engine によって SSH 認証鍵が自動的に構成されます。サードパーティのツールを使用して VM に接続する場合は、構成を自分で行う必要があります。

コンソール

Google Cloud コンソールのブラウザでの SSH ツールを使用して VM に接続すると、ブラウザでの SSH がセキュリティ キーに関連付けられた秘密鍵を取得します。

セキュリティ キーが有効になっている VM に接続するには、次の操作を行います。

  1. Google Cloud コンソールで [VM インスタンス] ページに移動します。

  2. VM のリストで、接続する VM の行にある [SSH] をクリックします。

  3. メッセージが表示されたら、セキュリティ キーをタッチします。

gcloud

gcloud CLI を使用して VM に接続すると、gcloud CLI によってセキュリティ キーに関連付けられた秘密鍵が取得され、秘密鍵ファイルが構成されます。この構成は永続的なもので、セキュリティ キーを使用するすべての VM に適用されます。

gcloud beta compute ssh コマンドを使用して、セキュリティ キーが有効化されている VM に接続します。

gcloud beta compute ssh VM_NAME

サードパーティ製ツール

セキュリティ キーが有効になっている VM に接続する前に、セキュリティ キーに関連付けられている秘密鍵を取得し、秘密鍵ファイルを構成する必要があります。この例では、Python クライアント ライブラリを使用して構成を行います。

この構成は、VM に初めて接続するときだけ行う必要があります。この構成は永続的なもので、プロジェクトのセキュリティ キーを使用するすべての VM に適用されます。

ワークステーションのターミナルから、次のようにします。

  1. まだ Python 用の Google クライアント ライブラリをインストールしていない場合は、次のコマンドを実行してインストールします。

    pip3 install google-api-python-client
    
  2. 次のサンプル Python スクリプトを保存します。このスクリプトでは、セキュリティ キーに関連付けられた秘密鍵を取得し、秘密鍵ファイルを構成して VM に接続します。

    import argparse
    import os
    import subprocess
    from typing import Optional
    
    import googleapiclient.discovery
    
    
    def write_ssh_key_files(security_keys: list[dict], directory: str) -> list[str]:
        """
        Store the SSH key files.
    
        Saves the SSH keys into files inside specified directory. Using the naming
        template of `google_sk_{i}`.
    
        Args:
            security_keys: list of dictionaries representing security keys retrieved
                from the OSLogin API.
            directory: path to directory in which the security keys will be stored.
    
        Returns:
            List of paths to the saved keys.
        """
        key_files = []
        for index, key in enumerate(security_keys):
            key_file = os.path.join(directory, f"google_sk_{index}")
            with open(key_file, "w") as f:
                f.write(key.get("privateKey"))
                os.chmod(key_file, 0o600)
                key_files.append(key_file)
        return key_files
    
    
    def ssh_command(key_files: list[str], username: str, ip_address: str) -> list[str]:
        """
        Construct the SSH command for a given IP address and key files.
    
        Args:
            key_files: SSH keys to be used for authentication.
            username: username used to authenticate.
            ip_address: the IP address or hostname of the remote system.
    
        Returns:
            SSH command as a list of strings.
        """
        command = ["ssh"]
        for key_file in key_files:
            command.extend(["-i", key_file])
        command.append(f"{username}@{ip_address}")
        return command
    
    
    def main(
        user_key: str, ip_address: str, dryrun: bool, directory: Optional[str] = None
    ) -> None:
        """
        Configure SSH key files and print SSH command.
    
        Args:
            user_key: name of the user you want to authenticate as. Usually an email address.
            ip_address: the IP address of the machine you want to connect to.
            dryrun: bool flag to do dry run, without connecting to the remote machine.
            directory: the directory to store SSH private keys.
        """
        directory = directory or os.path.join(os.path.expanduser("~"), ".ssh")
    
        # Create the OS Login API object.
        oslogin = googleapiclient.discovery.build("oslogin", "v1beta")
    
        # Retrieve security keys and OS Login username from a user's Google account.
        profile = (
            oslogin.users()
            .getLoginProfile(name=f"users/{user_key}", view="SECURITY_KEY")
            .execute()
        )
    
        if "posixAccounts" not in profile:
            print("You don't have a POSIX account configured.")
            print("Please make sure that you have enabled OS Login for your VM.")
            return
    
        username = profile.get("posixAccounts")[0].get("username")
    
        # Write the SSH private key files.
        security_keys = profile.get("securityKeys")
    
        if security_keys is None:
            print(
                "The account you are using to authenticate does not have any security keys assigned to it."
            )
            print(
                "Please check your Application Default Credentials "
                "(https://cloud.google.com/docs/authentication/application-default-credentials)."
            )
            print(
                "More info about using security keys: https://cloud.google.com/compute/docs/oslogin/security-keys"
            )
            return
    
        key_files = write_ssh_key_files(security_keys, directory)
    
        # Compose the SSH command.
        command = ssh_command(key_files, username, ip_address)
    
        if dryrun:
            # Print the SSH command.
            print(" ".join(command))
        else:
            # Connect to the IP address over SSH.
            subprocess.call(command)
    
    
    if __name__ == "__main__":
        parser = argparse.ArgumentParser(
            description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
        )
        parser.add_argument("--user_key", help="Your primary email address.")
        parser.add_argument(
            "--ip_address", help="The external IP address of the VM you want to connect to."
        )
        parser.add_argument("--directory", help="The directory to store SSH private keys.")
        parser.add_argument(
            "--dryrun",
            dest="dryrun",
            default=False,
            action="store_true",
            help="Turn off dryrun mode to execute the SSH command",
        )
        args = parser.parse_args()
    
        main(args.user_key, args.ip_address, args.dryrun, args.directory)
  3. スクリプトを実行して鍵を構成し、必要に応じて VM に接続します。

    python3 SCRIPT_NAME.py --user_key=USER_KEY --ip_address=IP_ADDRESS [--dryrun]
    

    次のように置き換えます。

    • SCRIPT_NAME: 構成スクリプトの名前。
    • USER_KEY: メインのメールアドレス。
    • IP_ADDRESS: 接続先の VM の外部 IP アドレス。
    • [--dryrun]: (省略可)--dryrun フラグを追加して、VM に接続せずに接続コマンドを出力します。このフラグを指定しない場合は、スクリプトは接続コマンドを実行します。

次のステップ