웹사이트 검색

데비안 9에서 SSL/TLS로 Lets Encrypt 및 Secure Nginx 설치


이 페이지에서

  1. Certbot 클라이언트 유틸리티 설치
  2. Let’s Encrypt 인증서 받기
  3. Lets encrypt SSL 인증서를 얻는 다른 방법
  4. TLS(SSL)용 Nginx 구성
  5. Nginx에 Let’s Encrypt 인증서 설치
  6. 웹 트래픽을 HTTPS로 강제\n
  7. 최종 확인\n
  8. 자동 갱신 Let's Encrypt 인증서

이 튜토리얼에서는 Let’s Encrypt 인증 기관에서 무료로 발급한 TLS 인증서를 사용하여 Debian 9에 Nginx 웹 서버를 설치하고 보호하는 방법을 보여줍니다. 또한 인증서가 만료되기 전에 cron 작업을 사용하여 Lets’ Encrypt TLS 인증서의 자동 갱신을 구성합니다.

전송 계층 보안이라고도 하는 TLS는 SSL 인증서를 사용하여 서버와 클라이언트 간 또는 Nginx 서버와 같은 웹 서버와 브라우저 간에 흐르는 네트워크 트래픽을 암호화하는 네트워크 프로토콜입니다. 이 두 엔터티 간에 교환되는 모든 데이터는 보안이 유지되며 중간자 공격 또는 패킷 스니핑과 같은 기술을 사용하여 가로채더라도 연결을 해독할 수 없습니다. certbot 패키지 소프트웨어는 Let's Encrypt CA에서 제공하는 공식 클라이언트 유틸리티로 데비안에서 무료 Let's Encrypt 인증서를 생성하고 다운로드하는 과정에서 사용할 수 있습니다.

요구 사항

  • Debian 9에 LEMP 스택을 설치합니다.\n
  • 적절한 DNS 레코드가 있는 공개 등록 도메인 이름(하위 도메인의 경우 A 레코드 또는 CNAME 레코드).\n
  • 서버의 콘솔에 직접 액세스하거나 서버에 대한 원격 SSH 액세스.\n
  • 루트 권한이 있거나 루트 계정에 직접 액세스할 수 있는 사용자 계정.\n

Certbot 클라이언트 유틸리티 설치

Debian 공식 리포지토리에서 Debian 9에 Let’s Encrypt cerbot 클라이언트 유틸리티를 설치하려면 터미널을 열고 다음 스크린샷과 같이 루트 권한으로 다음 명령을 실행합니다.

apt-get install certbot

Debian 기본 패키지 관리자의 명령줄 인터페이스인 Debian apt 유틸리티는 몇 가지 사전 확인 후 certbot 패키지 및 모든 필수 종속성을 설치하는 데 동의하는지 여부를 묻습니다. 소프트웨어 설치 프로세스를 수락하려면 서버의 콘솔 프롬프트에서 예(y)로 응답하십시오.

Let’s Encrypt 인증서 받기

도메인에 대한 Let’s Encrypt 인증서를 생성하고 다운로드하려면 먼저 Nginx 웹 서버가 실행 중이고 인터넷에서 포트 80 이상에 액세스할 수 있는지 확인하세요. Nginx가 실행 중인지 확인하려면 루트 권한으로 다음 명령을 실행합니다.

sudo systemctl status nginx

서버가 아직 실행 중이 아니면 아래 명령으로 Nginx 데몬을 시작합니다.

sudo systemctl start nginx

포트 80 및 443에서 들어오는 모든 연결을 차단하는 UFW 방화벽과 같은 Debian에 일반 방화벽이 설치되어 있는 경우 아래 명령을 실행하여 시스템에서 HTTP 및 HTTPS 포트를 엽니다.

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

도메인에 대한 인증서를 얻으려면 아래 설명된 대로 다음 매개변수 및 플래그를 사용하여 콘솔에서 cerbot 명령을 실행하십시오. 루트 권한으로 명령을 실행하고 –d 플래그를 사용하여 인증서를 얻으려는 도메인 이름 및 기타 모든 하위 도메인을 제공합니다. 또한 certbot이 Nginx 구성 파일을 방해하지 않도록 --standalone 옵션을 제공하십시오. 이 옵션을 사용하여 인증서를 발급하는 동안 Nginx 서버를 중지해야 합니다.

cerbot 명령 구문:

sudo certbot certonly --standalone –d yourdomain.com –d www.yourdomain.com

처음 certbot 명령을 실행하고 인증서를 받으면 이메일 주소를 추가하고 Let’s Encrypt 서비스 약관에 동의하라는 메시지가 표시됩니다. Let's Encrypt 파트너와 이메일 주소를 공유하지 않으려면 '아니요' 서비스 약관에 동의하는 'a'를 씁니다. 마지막으로 도메인에 대한 인증서를 얻은 후 바닥글 메모를 읽고 인증서 시스템 경로와 만료 날짜를 찾으십시오.

Lets encrypt SSL 인증서를 얻는 다른 방법

"webroot" 플러그인을 통해 Let’s Encrypt 인증서를 얻으려면 아래 구문을 사용하십시오. --webroot 및 –w 플래그와 함께 certbot 명령을 실행하는 동안 기본적으로 /var/www/html/ 시스템 경로에 있는 Nginx 웹 루트 디렉터리를 추가합니다. 또한 /.well-known 디렉터리를 생성하려면 Nginx에 웹 루트 디렉터리에 대한 전체 쓰기 권한이 있는지 확인하세요.

cerbot에 대한 --webrot 옵션은 인증서 갱신 및 보안 알림을 위해 이메일 주소를 추가하도록 요청합니다. Certbot 클라이언트에는 가짜 이메일 주소를 감지할 수 있는 내장 코드가 있습니다. 계속해서 인증서를 받으려면 공개적으로 액세스할 수 있는 전자 메일 주소를 제공해야 합니다.

certbot certonly --webroot –w /var/www/html/ -d yourdomain.com –d www.yourdomain.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel):  #A fake email address will be detected
There seem to be problems with that address. Enter email address (used for
urgent renewal and security notices)  If you really want to skip this, you can
run the client with --register-unsafely-without-email but make sure you then
backup your account key from /etc/letsencrypt/accounts   (Enter 'c' to cancel):
 
-------------------------------------------------------------------------------
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf. You must agree
in order to register with the ACME server at
https://acme-v01.api.letsencrypt.org/directory
-------------------------------------------------------------------------------
(A)gree/(C)ancel: a
 
-------------------------------------------------------------------------------
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about EFF and
our work to encrypt the web, protect its users and defend digital rights.
-------------------------------------------------------------------------------
(Y)es/(N)o: n
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for www.domain.com
Using the webroot path /var/www/html/  for all unmatched domains.
Waiting for verification...
Cleaning up challenges
 
IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at
    /etc/letsencrypt/live/www.yourdomain.com/fullchain.pem. Your
   cert will expire on 2017-12-28. To obtain a new or tweaked version
   of this certificate in the future, simply run certbot again. To
   non-interactively renew *all* of your certificates, run "certbot
   renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should
   make a secure backup of this folder now. This configuration
   directory will also contain certificates and private keys obtained
   by Certbot so making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:
 
   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

TLS(SSL)용 Nginx 구성

도메인에 대한 Nginx 전체 기본 TLS 구성 파일은 아래 발췌 파일과 같아야 합니다.

/etc/nginx/sites-enabled/default-ssl 파일 샘플:

    server {
                    listen 443 ssl default_server;
                    listen [::]:443 ssl default_server;
      
                server_name  www.yourdomain.com yourdomain.com;
                #server_name _;
                               
                root /var/www/html;
                               
                access_log /var/log/nginx/access.log;
                error_log /var/log/nginx/error.log;
              
               #SSL Certificates
                ssl_certificate "/etc/letsencrypt/live/www.yourdomain.com/cert.pem";
                ssl_certificate_key "/etc/letsencrypt/live/www. yourdomain.com/privkey.pem";
                ssl_dhparam /etc/nginx/dhparam.pem;
               
                ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
                #ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
 
                ssl_session_cache shared:SSL:1m;
               ssl_session_timeout 10m;
                ssl_ciphers HIGH:!aNULL:!MD5;
                ssl_prefer_server_ciphers  on;
               
                add_header Strict-Transport-Security "max-age=31536000;
    #includeSubDomains" always;
 
                location / {
        index index.php index.html index.htm;
                    try_files $uri $uri/ /index.php?$args $uri/ =404;
                }
 
               
                set $cache_uri $request_uri;
               
                location ~ /.well-known {
                allow all;
                                }
              
                #
                #             # With php-fpm (or other unix sockets):
                                fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
                #             # With php-cgi (or other tcp sockets):
                #             fastcgi_pass 127.0.0.1:9000;
                }

               # deny access to .htaccess files, if Apache's document root
                # concurs with nginx's one
                #
                #location ~ /\.ht {
                #             deny all;
                #}
               
    }

FastCGI Process Manager를 통해 PHP 스크립트를 처리하기 위한 코드 행도 이 발췌문에서 찾을 수 있으며 다음 행으로 표시됩니다.

location ~ \.php$ {
                                include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
                }

Nginx에 Let’s Encrypt 인증서 설치

Let's Encrypt 인증서와 키는 데비안의 /etc/letsencrypt/live/www.yourdomain.com/ 디렉토리에 저장됩니다. 위 디렉토리에 대한 ls 명령은 체인 파일, 전체 체인 파일, 개인 키 및 인증서 파일과 같은 모든 인증서 구성 요소를 표시합니다.

ls /etc/letsencrypt/live/www.yourdomain.com/

Nginx 웹 서버 TLS 구성 파일에 Let’s Encrypt 인증서를 설치하려면 Nginx default-ssl 파일을 열고 아래 발췌문과 같이 도메인의 Let’s Encrypt 인증서 파일 경로를 반영하도록 아래 행을 업데이트합니다.

nano /etc/nginx/sites-enabled/default-ssl

다음 줄을 아래와 같이 변경합니다.

                ssl_certificate "/etc/letsencrypt/live/www.yourdomain.com/cert.pem ";
                ssl_certificate_key "/etc/letsencrypt/live/www.yourdomain.com /privkey.pem";

또한 ssl_dhparam 문이 Nginx SSL 구성에 있는 경우 다음 명령을 실행하여 새 2048비트 Diffie–Hellman 키를 생성해야 합니다. Diffie-Hellman 키 매개변수 생성은 시스템 임의성 또는 엔트로피에 따라 다소 시간이 걸립니다.

openssl dhparam –out /etc/nginx/dhparam.pem 2048

마지막으로 변경 사항을 반영하기 위해 Nginx 데몬을 다시 시작하여 Nginx TLS 구성을 활성화하기 전에 먼저 잠재적인 구문 오류가 있는지 Nginx 구성을 확인하십시오. 이후 Nginx 구성 파일 테스트가 성공하면 Nginx 데몬을 다시 시작하여 아래 명령을 실행하여 Let’s Encrypt 인증서와 함께 새 구성을 로드합니다.

nginx -t
service nginx restart

nginx 서비스가 포트 443에서 청취 상태에서 열린 소켓을 소유하고 있는지 확인하려면 아래 발췌문과 같이 netstat 명령을 실행하십시오.

netstat –tulpn | grep -e 443 -e LISTEN

또한 브라우저를 열고 HTTPS 프로토콜을 통해 도메인 이름으로 이동해야 합니다. Let’s Encrypt 인증서가 Nginx에 성공적으로 적용되면 SSL 핸드셰이크가 오류 없이 원활하게 작동해야 합니다.

웹 트래픽을 HTTPS로 강제

도메인 방문자가 HTTPS 프로토콜을 통해서만 웹사이트를 탐색하도록 강제하려면 Nginx 사이트 지원 기본 구성 파일을 열고 다음 줄을 추가합니다. 그러면 포트 80에 도달하는 모든 요청이 301 상태 코드(영구적으로 이동됨)와 함께 포트로 리디렉션됩니다. 443.

nano /etc/nginx/sites-enabled/default

리디렉션 문은 아래 발췌문에 제시된 것과 같아야 합니다.

server_name www.yourdomain.com yourdomain.com;
return         301 https://$server_name$request_uri;

그런 다음 아래 명령을 실행하여 Nginx 데몬을 다시 시작하여 변경 사항을 적용하십시오.

service nginx restart

최종 확인

Let’s Encrypt CA에서 생성된 인증서를 자세히 조사하려면 Chrome과 같은 최신 웹 브라우저를 사용할 수 있습니다. Chrome 브라우저에서 도메인을 방문하고 F12 기능 키를 눌러 개발자 도구를 엽니다. 다음 스크린샷과 같이 보안 탭으로 이동하고 인증서 보기 버튼을 눌러 인증서를 엽니다.

SSL 인증서 조사에 유용한 또 다른 유틸리티는 openssl 명령줄 유틸리티입니다. Let’s Encrypt CA 인증서에 대한 추가 정보를 표시하려면 Linux 콘솔에서 아래 명령을 실행하십시오.

openssl s_client –connect www.yourdomain.com:443

자동 갱신 Let's Encrypt 인증서

만료일 이전에 Let’s Encrypt CA에서 발급한 인증서를 자동으로 갱신하려면 다음 명령을 실행하여 crontab 작업이 하루에 한 번 오전 2시에 실행되도록 예약합니다. 실행된 cron 작업의 출력은 /var/log/letsencrypt.log에 저장된 로그 파일로 전달됩니다.

crontab –e

인증서를 갱신하기 위한 Cron 작업입니다.

0 2 * * * certbot renew >> /var/log/letsencrypt.log

그게 다야! Let’s Encrypt 인증서 및 유틸리티에 관한 기타 고급 구성은 다음 인터넷 주소 https://certbot.eff.org/docs/의 공식 문서를 참조하십시오.