OS 로그인으로 보안 키 사용 설정


이 문서에서는 Google 계정에 등록된 물리적 보안 키를 사용하여 OS 로그인을 사용하는 가상 머신(VM) 인스턴스에 연결하는 방법을 설명합니다.

물리적 보안 키는 VM에 연결할 수 있도록 비공개 SSH 키 파일을 생성하는 데 사용됩니다. Google Cloud 콘솔의 브라우저에서 SSH를 통해 연결 도구 또는 Google Cloud CLI를 통해 보안 키를 사용하여 VM에 연결하면 OS 로그인에서 보안 키와 연결된 비공개 SSH 키 파일을 가져와 SSH 키 파일을 자동으로 구성합니다. 서드파티 도구를 사용하여 연결할 때는 OS 로그인 API를 사용하여 SSH 키 정보를 검색하고 SSH 키 파일을 직접 구성해야 합니다.

시작하기 전에

  • Google 계정에 보안 키 추가
  • OS 로그인 설정
  • 아직 인증을 설정하지 않았다면 설정합니다. 인증은 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 로그인으로 보안 키 사용 설정

프로젝트에서 OS 로그인을 사용하는 모든 VM 또는 단일 VM에 보안 키 사용을 사용 설정할 수 있습니다.

프로젝트의 모든 OS 로그인 사용 VM에 보안 키 사용 설정

프로젝트에서 OS 로그인을 사용하는 모든 VM에 보안 키를 사용 설정하려면 Google Cloud 콘솔 또는 gcloud CLI를 사용하세요.

콘솔

모든 OS 로그인 사용 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 로그인 사용 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 로그인 사용 VM에서 보안 키 사용 설정

OS 로그인 사용 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

단일 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에 연결

Google Cloud 콘솔, gcloud CLI 또는 타사 도구를 사용하여 보안 키를 사용하는 VM에 연결할 수 있습니다. 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에 연결하지 않고 연결 명령어를 출력합니다. 이 플래그를 지정하지 않으면 스크립트에서 연결 명령어를 실행합니다.

다음 단계