Enable security keys with OS Login

Preview

This product or feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms. Pre-GA products and features are available "as is" and might have limited support. For more information, see thelaunch stage descriptions.

This document describes how to use the physical security keys registered in yourGoogle account to connect to virtual machine (VM) instances that use OS Login.

Physical security keys are used to generate private SSH key files for connectingto VMs. When you use the Google Cloud console SSH-in-browser tool or theGoogle Cloud CLI to connect to VMs using security keys, OS Loginretrieves the private SSH key file associated with your security key andconfigures the SSH key file for you. When you usethird-party tools toconnect, you must use the OS Login API to retrieve the SSH key informationand configure the SSH key file yourself.

Before you begin

Limitations

  • VMs that have security keys enabled only accept connections fromSSH keys that are attached to the physical security keys registered in yourGoogle Account.
  • You can't use Cloud Shell to connect to VMs that have security keysenabled.
  • Both the VM you're connecting to and the workstation you're connecting frommust use a version of OpenSSH 8.2 or later that supports security key SSHtypes. The following Compute Engine VM operating systems support securitykeys:

    • Debian 11 (or later)
    • SUSE Linux Enterprise Server (SLES) 15 (or later)
    • Ubuntu 20.04 LTS (or later)
    • Container-Optimized OS 93 LTS (or later)
    • Rocky Linux 9 (or later)

    To check if your environment supports security keys, run the following command:

    ssh -Q key | grep ^sk-

    If the command doesn't return any output, your environment doesn't supportsecurity keys.

  • The SSH client on the workstation you're connecting from must support securitykeys and include the required libraries, such aslibfido2.

Note: Service accounts continue to connect to VMs without using security keys.If you are connecting from a service or application that doesn't supportsecurity keys,connect to the VM as a service account.

Enable security keys with OS Login

You can enable use of security keys for all VMs that use OS Login in yourproject, or for single VMs.

Enable security keys for all OS Login-enabled VMs in a project

To enable security keys on all VMs that use OS Login in your project, use theGoogle Cloud console or the gcloud CLI.

Console

To enable security keys for all OS Login-enabled VMs, use theGoogle Cloud console to setenable-oslogin andenable-oslogin-sk toTRUE in project metadata:

  1. Go to theMetadata page.

    Go to Metadata

  2. ClickEdit.

  3. ClickAdd item.

    1. In theKey field, enterenable-oslogin.
    2. In theValue field, enterTRUE.
  4. ClickAdd item.

    1. In theKey field, enterenable-oslogin-sk.
    2. In theValue field, enterTRUE.
  5. ClickSave.

gcloud

To enable security keys for all OS Login-enabled VMs, use thegcloud compute project-info add-metadata commandto setenable-oslogin=TRUE andenable-oslogin-sk=TRUE in projectmetadata:

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

Enable security keys on a single OS Login-enabled VM

To enable security keys on a VM that uses OS Login, use theGoogle Cloud console or the gcloud CLI.

Console

To enable security keys on a single VM, use the Google Cloud console tosetenable-oslogin andenable-oslogin-sk toTRUE in instance metadata:

  1. Go to theVM instances page.

    Go to VM instances

  2. Click the name of the VM you want to enable security keys for.

  3. ClickEdit.

  4. In theMetadata section, clickAdd item.

    1. In theKey field, enterenable-oslogin.
    2. In theValue field, enterTRUE.
  5. ClickAdd item.

    1. In theKey field, enterenable-oslogin-sk.
    2. In theValue field, enterTRUE.
  6. ClickSave.

gcloud

To enable security keys on a single VM, use thegcloud compute instances add-metadata commandto setenable-oslogin=TRUE andenable-oslogin-sk=TRUE in instancemetadata:

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

ReplaceVM_NAME with the name of your VM.

Connect to a VM using a security key

You can connect to a VM that uses security keys using the Google Cloud console,the gcloud CLI, or third-party tools. If you connect to VMs usingthe Google Cloud console or the gcloud CLI, Compute Engineconfigures your SSH key for you. If you connect to VMs using third-party tools,you must perform the configuration yourself.

Note: VMs that have security keys enabled don't support gcloud CLIconnections from Windows workstations. Connect using the Google Cloud consoleor third-party tools instead.

Console

When you connect to VMs using the Google Cloud consoleSSH-in-browser tool, SSH-in-browser retrievesthe private keys associated with your security keys.

Note: The private key file can't be used to access your VM without physicalaccess to your security key device.

To connect to a VM that has security keys enabled, do the following:

  1. In the Google Cloud console, go to theVM instances page.

  2. In the list of VMs, clickSSH in the row of the VM that you want toconnect to.

  3. When prompted, touch your security key.

gcloud

When you connect to VMs using the gcloud CLI, thegcloud CLI retrieves the private keys associated with yoursecurity keys and configures the private key files. This configuration ispersistent and applies to all VMs that use security keys.

Note: The private key file can't be used to access your VM without physicalaccess to your security key device.

Use thegcloud beta compute ssh commandto connect to a VM that has security keys enabled:

gcloud beta compute sshVM_NAME

Third-party tools

Before you connect to a VM that has security keys enabled, youmust retrieve the private keys associated with your security keys andconfigure the private key files. This example uses the Python client libraryto perform the configuration.

Note: The private key file can't be used to access your VM without physicalaccess to your security key device.

You only need to perform this configuration the first time youconnect to a VM. The configuration is persistent and applies to allVMs that use security keys in your project.

From a terminal on your workstation, do the following:

  1. Install the Google client library for Python, if you haven't already, byrunning the following command:

    pip3 install google-api-python-client
  2. Save the following sample Python script, which retrieves the private keysassociated with your security keys, configures the private key files, andconnects to the VM.

    importargparseimportosimportsubprocessfromtypingimportOptionalimportgoogleapiclient.discoverydefwrite_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=[]forindex,keyinenumerate(security_keys):key_file=os.path.join(directory,f"google_sk_{index}")withopen(key_file,"w")asf:f.write(key.get("privateKey"))os.chmod(key_file,0o600)key_files.append(key_file)returnkey_filesdefssh_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"]forkey_fileinkey_files:command.extend(["-i",key_file])command.append(f"{username}@{ip_address}")returncommanddefmain(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=directoryoros.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"notinprofile:print("You don't have a POSIX account configured.")print("Please make sure that you have enabled OS Login for your VM.")returnusername=profile.get("posixAccounts")[0].get("username")# Write the SSH private key files.security_keys=profile.get("securityKeys")ifsecurity_keysisNone: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")returnkey_files=write_ssh_key_files(security_keys,directory)# Compose the SSH command.command=ssh_command(key_files,username,ip_address)ifdryrun:# 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. Run the script to configure your keys and optionally connect to the VM.

    python3SCRIPT_NAME.py --user_key=USER_KEY --ip_address=IP_ADDRESS[--dryrun]

    Replace the following:

    • SCRIPT_NAME: the name of your configurationscript.
    • USER_KEY: your primary email address.
    • IP_ADDRESS: the external IP address of the VMyou're connecting to.
    • [--dryrun]: (Optional) add the--dryrun flag toprint the connection command without connecting to the VM. If you don'tspecify this flag, the script runs the connection command.

What's next?

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.