InfoGrab Docs

셀프 호스팅 PostgreSQL을 사용한 데이터베이스 접근

요약

Teleport can provide secure access to PostgreSQL via the Teleport Database Service. The Teleport Database Service proxies traffic from database clients to self-hosted databases in your infrastructure.

Teleport can provide secure access to PostgreSQL via the Teleport Database Service. This allows for fine-grained access control through the Teleport RBAC system.

The Teleport Database Service proxies traffic from database clients to self-hosted databases in your infrastructure. Teleport maintains a certificate authority (CA) for database clients. You configure your database to trust the Teleport database client CA, and the Teleport Database Service presents certificates signed by this CA when proxying user traffic. With this setup, there is no need to store long-lived credentials for self-hosted databases.

Meanwhile, the Teleport Database Service verifies self-hosted databases by checking their TLS certificates against either the Teleport database CA or a custom CA used with the database.

In this guide, you will:

  1. Configure your PostgreSQL database for Teleport access.
  2. Add the database to your Teleport cluster.
  3. Connect to the database via Teleport.

작동 방식#

The Teleport Database Service authenticates to your self-hosted PostgreSQL database using mutual TLS. PostgreSQL trusts the Teleport certificate authority for database clients, and presents a certificate signed by either the Teleport database CA or a custom CA. When a user initiates a database session, the Teleport Database Service presents a certificate signed by Teleport. The authenticated connection then proxies client traffic from the user.

셀프 호스팅 Teleport 클러스터로 PostgreSQL 등록

클라우드 호스팅 Teleport 클러스터로 PostgreSQL 등록

사전 조건#

  • A running Teleport cluster. If you want to get started with Teleport, sign up for a free trial or set up a demo environment.

  • The tctl and tsh clients.

    Installing `tctl` and `tsh` clients
    1. Determine the version of your Teleport cluster. The tctl and tsh clients must be at most one major version behind your Teleport cluster version. Send a GET request to the Proxy Service at /v1/webapi/find and use a JSON query tool to obtain your cluster version. Replace with the web address of your Teleport Proxy Service:

      $ TELEPORT_DOMAIN=
      $ TELEPORT_VERSION="$(curl -s https://$TELEPORT_DOMAIN/v1/webapi/find | jq -r '.server_version')"
      
    2. Follow the instructions for your platform to install tctl and tsh clients:

  • 셀프 호스팅 PostgreSQL 인스턴스.
  • 커맨드라인 클라이언트 psql이 설치되어 시스템의 PATH 환경 변수에 추가되어 있어야 합니다.
  • Teleport 데이터베이스 서비스를 실행할 호스트(예: Amazon EC2 인스턴스).
  • 선택 사항: 셀프 호스팅 데이터베이스에 대한 인증서를 발급하는 인증 기관.

To check that you can connect to your Teleport cluster, sign in with tsh login, then verify that you can run tctl commands using your current credentials.

For example, run the following command, assigning to the domain name of the Teleport Proxy Service in your cluster and to your Teleport username:

$ tsh login --proxy= --user=
$ tctl status
# Cluster  (=teleport.url=)
# Version  (=teleport.version=)
# CA pin   (=presets.ca_pin=)

If you can connect to the cluster and run the tctl status command, you can use your current credentials to run subsequent tctl commands from your workstation. If you host your own Teleport cluster, you can also run tctl commands on the computer that hosts the Teleport Auth Service for full permissions.

1/5단계. Teleport 토큰 및 사용자 생성#

The Database Service requires a valid join token to join your Teleport cluster. Run the following tctl command and save the token output in /tmp/token on the server that will run the Database Service:

$ tctl tokens add --type=db --format=text
(=presets.tokens.first=)

Teleport 사용자 생성#

Flag Description
--roles List of roles to assign to the user. The builtin access role allows them to connect to any database server registered with Teleport.
--db-users List of database usernames the user will be allowed to use when connecting to the databases. A wildcard allows any user.
--db-names List of logical databases (aka schemas) the user will be allowed to connect to within a database server. A wildcard allows any database.

For more detailed information about database access controls and how to restrict access see RBAC documentation.

2/5단계. 인증서/키 쌍 생성#

Teleport uses mutual TLS authentication with self-hosted databases. These databases must be able to verify certificates presented by the Teleport Database Service. Self-hosted databases also need a certificate/key pair that Teleport can verify.

By default, the Teleport Database Service trusts certificates issued by a certificate authority managed by the Teleport Auth Service. You can either:

  • Configure your self-hosted database to trust this CA, and instruct Teleport to issue a certificate for the database to present to the Teleport Database Service.
  • Configure the Database Service to trust a custom CA.

3/5단계. PostgreSQL 서버 구성#

PostgreSQL 서버가 TLS 연결을 수락하도록 구성하려면 앞서 생성한 server.crt, server.key, server.cas 파일을 배치한 경로를 사용하여 PostgreSQL 구성 파일 postgresql.conf에 다음을 추가합니다:

ssl = on
ssl_cert_file = '/path/to/server.crt'
ssl_key_file = '/path/to/server.key'
ssl_ca_file = '/path/to/server.cas'

이 구성을 활성화하려면 PostgreSQL 인스턴스를 재시작합니다.

자세한 내용은 PostgreSQL 문서의 SSL을 사용한 안전한 TCP/IP 연결을 참조하세요.

TLS로 연결하는 클라이언트에 대해 클라이언트 인증서 인증을 요구하도록 PostgreSQL을 구성합니다. 이는 PostgreSQL의 호스트 기반 인증 파일 pg_hba.conf에 다음 항목을 추가하여 수행할 수 있습니다:

hostssl all             all             ::/0                    cert
hostssl all             all             0.0.0.0/0               cert

또한 일치하는 더 높은 우선순위의 인증 규칙이 없는지 확인해야 합니다. 그렇지 않으면 PostgreSQL이 먼저 그 규칙을 제시하고 인증서 기반 Teleport 로그인이 실패합니다.

자세한 내용은 PostgreSQL 문서의 pg_hba.conf 파일을 참조하세요.

4/5단계. 데이터베이스 서비스 구성 및 시작#

Teleport 데이터베이스 서비스를 실행할 위치에 Teleport를 설치하고 구성합니다:

To install a Teleport Agent on your Linux server:

The recommended installation method is the cluster install script. It will select the correct version, edition, and installation mode for your cluster.

  1. Assign to your Teleport cluster hostname and port, but not the scheme (https://).

  2. Run your cluster's install script:

    $ curl "https:///scripts/install.sh" | sudo bash
    

On the host where you will run the Teleport Database Service, start Teleport with the appropriate configuration.

Note that a single Teleport process can run multiple different services, for example multiple Database Service agents as well as the SSH Service or Application Service. The step below will overwrite an existing configuration file, so if you're running multiple services add --output=stdout to print the config in your terminal, and manually adjust /etc/teleport.yaml.

Run the following command to generate a configuration file at /etc/teleport.yaml for the Database Service. Update to use the host and port of the Teleport Proxy Service:

$ sudo teleport db configure create \
   -o file \
   --token=/tmp/token \
   --proxy=:443 \
   --name=example-postgres \
   --protocol=postgres \
   --uri=postgres.example.com:5432 \
   --labels=env=dev 

To configure the Teleport Database Service to trust a custom CA:

  1. Export a CA certificate for the custom CA and make it available at /var/lib/teleport/db.ca on the Teleport Database Service host.

  2. Run a variation of the command above that uses the --ca-cert-file flag. This configures the Teleport Database Service to use the CA certificate at db.ca to verify traffic from the database:

    $ sudo teleport db configure create \
       -o file \
       --token=/tmp/token \
       --proxy=:443 \
       --name=example-postgres \
       --protocol=postgres \
       --uri=postgres.example.com:5432 \
       --ca-cert-file="/var/lib/teleport/db.ca" \
       --labels=env=dev
    

If your database servers use certificates that are signed by a public CA such as ComodoCA or DigiCert, you can use the trust-system-cert-pool option without exporting the CA:

$ sudo teleport db configure create \
   -o file \
   --token=/tmp/token \
   --proxy=:443 \
   --name=example-postgres \
   --protocol=postgres \
   --uri=postgres.example.com:5432 \
   --trust-system-cert-pool \
   --labels=env=dev

(!docs/pages/includes/start-teleport.mdx service="the Teleport Database Service"!)

Teleport는 Kubernetes 클러스터에 Teleport 데이터베이스 서비스를 설치하기 위한 Helm 차트를 제공합니다.

Configure Helm to fetch Teleport charts from the Teleport Helm repository:

$ helm repo add teleport (=teleport.helm_repo_url=)

Refresh the local Helm cache by fetching the latest charts:

$ helm repo update

Install a Teleport Agent into your Kubernetes Cluster with the Teleport Database Service configuration.

Create a file called values.yaml with the following content. Update

데이터베이스에서 로그아웃하고 자격 증명을 제거하려면:

# 특정 데이터베이스 인스턴스의 자격 증명 제거.
$ tsh db logout example-postgres
# 모든 데이터베이스 인스턴스의 자격 증명 제거.
$ tsh db logout

문제 해결#

Unable to cancel a query#

If you use a PostgreSQL cli client like psql, and you try to cancel a query with Ctrl+C, but it doesn't cancel the query, then you need to connect using a tsh local proxy instead. When psql cancels a query, it establishes a new connection without TLS certificates, however Teleport requires TLS certificates not only for authentication, but also to route database connections.

If you enable TLS Routing in Teleport then tsh db connect will automatically start a local proxy for every connection. Alternatively, you can connect via Teleport Connect which also uses a local proxy. Otherwise, you need to start a tsh local proxy manually using tsh proxy db and connect via the local proxy.

If you have already started a long-running query in a psql session that you cannot cancel with Ctrl+C, you can start a new client session to cancel that query manually:

First, find the query's process identifier (PID):

SELECT pid,usename,backend_start,query FROM pg_stat_activity WHERE state = 'active';

Next, gracefully cancel the query using its PID. This will send a SIGINT signal to the postgres backend process for that query:

SELECT pg_cancel_backend(<PID>);

You should always try to gracefully terminate a query first, but if graceful cancellation is taking too long, then you can forcefully terminate the query instead. This will send a SIGTERM signal to the postgres backend process for that query:

SELECT pg_terminate_backend(<PID>);

See the PostgreSQL documentation on admin functions for more information about the pg_cancel_backend and pg_terminate_backend functions.

SSL SYSCALL error#

You may encounter the following error when your local psql is not compatible with newer versions of OpenSSL:

$ tsh db connect --db-user postgres --db-name postgres postgres
psql: error: connection to server at "localhost" (::1), port 12345 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 12345 failed: SSL SYSCALL error: Undefined error: 0

Please upgrade your local psql to the latest version.

다음 단계#

셀프 호스팅 PostgreSQL을 사용한 데이터베이스 접근

원문 보기
요약

Teleport can provide secure access to PostgreSQL via the Teleport Database Service. The Teleport Database Service proxies traffic from database clients to self-hosted databases in your infrastructure.

Teleport can provide secure access to PostgreSQL via the Teleport Database Service. This allows for fine-grained access control through the Teleport RBAC system.

The Teleport Database Service proxies traffic from database clients to self-hosted databases in your infrastructure. Teleport maintains a certificate authority (CA) for database clients. You configure your database to trust the Teleport database client CA, and the Teleport Database Service presents certificates signed by this CA when proxying user traffic. With this setup, there is no need to store long-lived credentials for self-hosted databases.

Meanwhile, the Teleport Database Service verifies self-hosted databases by checking their TLS certificates against either the Teleport database CA or a custom CA used with the database.

In this guide, you will:

  1. Configure your PostgreSQL database for Teleport access.
  2. Add the database to your Teleport cluster.
  3. Connect to the database via Teleport.

작동 방식#

The Teleport Database Service authenticates to your self-hosted PostgreSQL database using mutual TLS. PostgreSQL trusts the Teleport certificate authority for database clients, and presents a certificate signed by either the Teleport database CA or a custom CA. When a user initiates a database session, the Teleport Database Service presents a certificate signed by Teleport. The authenticated connection then proxies client traffic from the user.

셀프 호스팅 Teleport 클러스터로 PostgreSQL 등록

클라우드 호스팅 Teleport 클러스터로 PostgreSQL 등록

사전 조건#

  • A running Teleport cluster. If you want to get started with Teleport, sign up for a free trial or set up a demo environment.

  • The tctl and tsh clients.

    Installing `tctl` and `tsh` clients
    1. Determine the version of your Teleport cluster. The tctl and tsh clients must be at most one major version behind your Teleport cluster version. Send a GET request to the Proxy Service at /v1/webapi/find and use a JSON query tool to obtain your cluster version. Replace with the web address of your Teleport Proxy Service:

      $ TELEPORT_DOMAIN=
      $ TELEPORT_VERSION="$(curl -s https://$TELEPORT_DOMAIN/v1/webapi/find | jq -r '.server_version')"
      
    2. Follow the instructions for your platform to install tctl and tsh clients:

  • 셀프 호스팅 PostgreSQL 인스턴스.
  • 커맨드라인 클라이언트 psql이 설치되어 시스템의 PATH 환경 변수에 추가되어 있어야 합니다.
  • Teleport 데이터베이스 서비스를 실행할 호스트(예: Amazon EC2 인스턴스).
  • 선택 사항: 셀프 호스팅 데이터베이스에 대한 인증서를 발급하는 인증 기관.

To check that you can connect to your Teleport cluster, sign in with tsh login, then verify that you can run tctl commands using your current credentials.

For example, run the following command, assigning to the domain name of the Teleport Proxy Service in your cluster and to your Teleport username:

$ tsh login --proxy= --user=
$ tctl status
# Cluster  (=teleport.url=)
# Version  (=teleport.version=)
# CA pin   (=presets.ca_pin=)

If you can connect to the cluster and run the tctl status command, you can use your current credentials to run subsequent tctl commands from your workstation. If you host your own Teleport cluster, you can also run tctl commands on the computer that hosts the Teleport Auth Service for full permissions.

1/5단계. Teleport 토큰 및 사용자 생성#

The Database Service requires a valid join token to join your Teleport cluster. Run the following tctl command and save the token output in /tmp/token on the server that will run the Database Service:

$ tctl tokens add --type=db --format=text
(=presets.tokens.first=)

Teleport 사용자 생성#

Flag Description
--roles List of roles to assign to the user. The builtin access role allows them to connect to any database server registered with Teleport.
--db-users List of database usernames the user will be allowed to use when connecting to the databases. A wildcard allows any user.
--db-names List of logical databases (aka schemas) the user will be allowed to connect to within a database server. A wildcard allows any database.

For more detailed information about database access controls and how to restrict access see RBAC documentation.

2/5단계. 인증서/키 쌍 생성#

Teleport uses mutual TLS authentication with self-hosted databases. These databases must be able to verify certificates presented by the Teleport Database Service. Self-hosted databases also need a certificate/key pair that Teleport can verify.

By default, the Teleport Database Service trusts certificates issued by a certificate authority managed by the Teleport Auth Service. You can either:

  • Configure your self-hosted database to trust this CA, and instruct Teleport to issue a certificate for the database to present to the Teleport Database Service.
  • Configure the Database Service to trust a custom CA.

3/5단계. PostgreSQL 서버 구성#

PostgreSQL 서버가 TLS 연결을 수락하도록 구성하려면 앞서 생성한 server.crt, server.key, server.cas 파일을 배치한 경로를 사용하여 PostgreSQL 구성 파일 postgresql.conf에 다음을 추가합니다:

ssl = on
ssl_cert_file = '/path/to/server.crt'
ssl_key_file = '/path/to/server.key'
ssl_ca_file = '/path/to/server.cas'

이 구성을 활성화하려면 PostgreSQL 인스턴스를 재시작합니다.

자세한 내용은 PostgreSQL 문서의 SSL을 사용한 안전한 TCP/IP 연결을 참조하세요.

TLS로 연결하는 클라이언트에 대해 클라이언트 인증서 인증을 요구하도록 PostgreSQL을 구성합니다. 이는 PostgreSQL의 호스트 기반 인증 파일 pg_hba.conf에 다음 항목을 추가하여 수행할 수 있습니다:

hostssl all             all             ::/0                    cert
hostssl all             all             0.0.0.0/0               cert

또한 일치하는 더 높은 우선순위의 인증 규칙이 없는지 확인해야 합니다. 그렇지 않으면 PostgreSQL이 먼저 그 규칙을 제시하고 인증서 기반 Teleport 로그인이 실패합니다.

자세한 내용은 PostgreSQL 문서의 pg_hba.conf 파일을 참조하세요.

4/5단계. 데이터베이스 서비스 구성 및 시작#

Teleport 데이터베이스 서비스를 실행할 위치에 Teleport를 설치하고 구성합니다:

To install a Teleport Agent on your Linux server:

The recommended installation method is the cluster install script. It will select the correct version, edition, and installation mode for your cluster.

  1. Assign to your Teleport cluster hostname and port, but not the scheme (https://).

  2. Run your cluster's install script:

    $ curl "https:///scripts/install.sh" | sudo bash
    

On the host where you will run the Teleport Database Service, start Teleport with the appropriate configuration.

Note that a single Teleport process can run multiple different services, for example multiple Database Service agents as well as the SSH Service or Application Service. The step below will overwrite an existing configuration file, so if you're running multiple services add --output=stdout to print the config in your terminal, and manually adjust /etc/teleport.yaml.

Run the following command to generate a configuration file at /etc/teleport.yaml for the Database Service. Update to use the host and port of the Teleport Proxy Service:

$ sudo teleport db configure create \
   -o file \
   --token=/tmp/token \
   --proxy=:443 \
   --name=example-postgres \
   --protocol=postgres \
   --uri=postgres.example.com:5432 \
   --labels=env=dev 

To configure the Teleport Database Service to trust a custom CA:

  1. Export a CA certificate for the custom CA and make it available at /var/lib/teleport/db.ca on the Teleport Database Service host.

  2. Run a variation of the command above that uses the --ca-cert-file flag. This configures the Teleport Database Service to use the CA certificate at db.ca to verify traffic from the database:

    $ sudo teleport db configure create \
       -o file \
       --token=/tmp/token \
       --proxy=:443 \
       --name=example-postgres \
       --protocol=postgres \
       --uri=postgres.example.com:5432 \
       --ca-cert-file="/var/lib/teleport/db.ca" \
       --labels=env=dev
    

If your database servers use certificates that are signed by a public CA such as ComodoCA or DigiCert, you can use the trust-system-cert-pool option without exporting the CA:

$ sudo teleport db configure create \
   -o file \
   --token=/tmp/token \
   --proxy=:443 \
   --name=example-postgres \
   --protocol=postgres \
   --uri=postgres.example.com:5432 \
   --trust-system-cert-pool \
   --labels=env=dev

(!docs/pages/includes/start-teleport.mdx service="the Teleport Database Service"!)

Teleport는 Kubernetes 클러스터에 Teleport 데이터베이스 서비스를 설치하기 위한 Helm 차트를 제공합니다.

Configure Helm to fetch Teleport charts from the Teleport Helm repository:

$ helm repo add teleport (=teleport.helm_repo_url=)

Refresh the local Helm cache by fetching the latest charts:

$ helm repo update

Install a Teleport Agent into your Kubernetes Cluster with the Teleport Database Service configuration.

Create a file called values.yaml with the following content. Update

데이터베이스에서 로그아웃하고 자격 증명을 제거하려면:

# 특정 데이터베이스 인스턴스의 자격 증명 제거.
$ tsh db logout example-postgres
# 모든 데이터베이스 인스턴스의 자격 증명 제거.
$ tsh db logout

문제 해결#

Unable to cancel a query#

If you use a PostgreSQL cli client like psql, and you try to cancel a query with Ctrl+C, but it doesn't cancel the query, then you need to connect using a tsh local proxy instead. When psql cancels a query, it establishes a new connection without TLS certificates, however Teleport requires TLS certificates not only for authentication, but also to route database connections.

If you enable TLS Routing in Teleport then tsh db connect will automatically start a local proxy for every connection. Alternatively, you can connect via Teleport Connect which also uses a local proxy. Otherwise, you need to start a tsh local proxy manually using tsh proxy db and connect via the local proxy.

If you have already started a long-running query in a psql session that you cannot cancel with Ctrl+C, you can start a new client session to cancel that query manually:

First, find the query's process identifier (PID):

SELECT pid,usename,backend_start,query FROM pg_stat_activity WHERE state = 'active';

Next, gracefully cancel the query using its PID. This will send a SIGINT signal to the postgres backend process for that query:

SELECT pg_cancel_backend(<PID>);

You should always try to gracefully terminate a query first, but if graceful cancellation is taking too long, then you can forcefully terminate the query instead. This will send a SIGTERM signal to the postgres backend process for that query:

SELECT pg_terminate_backend(<PID>);

See the PostgreSQL documentation on admin functions for more information about the pg_cancel_backend and pg_terminate_backend functions.

SSL SYSCALL error#

You may encounter the following error when your local psql is not compatible with newer versions of OpenSSL:

$ tsh db connect --db-user postgres --db-name postgres postgres
psql: error: connection to server at "localhost" (::1), port 12345 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 12345 failed: SSL SYSCALL error: Undefined error: 0

Please upgrade your local psql to the latest version.

다음 단계#