웹사이트 검색

Nginx 웹 서버 보안을 위한 팁과 요령


이 페이지에서

  1. 요구 사항\n
  2. Nginx 설치
  3. Nginx 업데이트
  4. 정보 공개 방지
  5. 액세스에서 IP 제한\n
  6. TLS로 Nginx 보호\n
  7. 디렉토리를 암호로 보호\n

Nginx는 전 세계에서 가장 빠르게 성장하는 오픈 소스, 경량, 고성능 웹 서버입니다. Nginx는 Linux, Windows, Mac OS 및 Solaris 운영 체제에서 실행됩니다. NGINX의 인기가 계속 높아지고 있으므로 점점 더 많은 NGINX 배포를 확보해야 합니다.

이 튜토리얼에서는 몇 가지 인기 있는 Nginx 서버 보안 팁과 요령을 설명합니다.

요구 사항

  • Ubuntu 18.04 또는 Debian 9를 실행하는 서버.\n
  • 서버에 루트 암호가 설정되어 있습니다.\n

Nginx 설치

먼저 시스템에 Nginx를 설치해야 합니다. 다음 명령을 실행하여 설치할 수 있습니다.

apt-get install nginx -y

Nginx가 설치되면 다음 명령을 사용하여 Nginx의 상태를 확인할 수 있습니다.

systemctl status nginx

다음 출력이 표시되어야 합니다.

? nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2019-03-10 02:43:14 UTC; 4min 40s ago
     Docs: man:nginx(8)
  Process: 2271 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0/SUCCESS)
  Process: 2281 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 2274 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
 Main PID: 2285 (nginx)
    Tasks: 2 (limit: 1111)
   CGroup: /system.slice/nginx.service
           ??2285 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           ??2290 nginx: worker process

Mar 10 02:43:14 ubuntu1804 systemd[1]: Starting A high performance web server and a reverse proxy server...
Mar 10 02:43:14 ubuntu1804 systemd[1]: nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument
Mar 10 02:43:14 ubuntu1804 systemd[1]: Started A high performance web server and a reverse proxy server.

Nginx 업데이트

많은 성능 향상, 새로운 기능 및 보안 수정 사항이 추가되고 있으므로 Nginx 웹 서버를 업데이트해야 합니다. 대부분의 최신 Linux 배포판은 기본 패키지 목록에 최신 버전의 nginx가 포함되어 있지 않습니다. 따라서 패키지 관리자를 통해 최신 버전의 nginx를 업그레이드해야 합니다. 다음 명령을 사용하여 Nginx 웹 서버를 업데이트할 수 있습니다.

apt-get update -y
apt-get install nginx --reinstall -y

정보 공개 방지

먼저 Nginx가 버전 정보를 공개하지 않도록 해야 합니다.

기본적으로 Nginx는 HTTP 헤더에 이름과 버전을 표시합니다.

다음 명령으로 확인할 수 있습니다.

curl -I http://localhost

다음 출력이 표시되어야 합니다.

HTTP/1.1 200 OK
Server: nginx/1.14.0 (Ubuntu)
Date: Sat, 09 Mar 2019 15:28:01 GMT
Content-Type: text/html
Content-Length: 10918
Last-Modified: Fri, 01 Feb 2019 16:05:17 GMT
Connection: keep-alive
ETag: "5c546e3d-2aa6"
Accept-Ranges: bytes

위 출력에서 Nginx 및 운영 체제 버전이 표시되어야 합니다.

/etc/nginx/nginx.conf 파일을 편집하여 이 정보를 숨길 수 있습니다.

nano /etc/nginx/nginx.conf

http 구성 부분 내에 server_tokens 오프라인을 추가합니다.

http {

        ##
        # Basic Settings
        ##
        server_tokens off;

완료되면 파일을 저장하고 닫습니다. 그런 다음 Nginx 웹 서버를 다시 시작하여 변경 사항을 적용합니다.

systemctl restart nginx

이제 curl 명령을 다시 실행합니다.

curl -I http://localhost

다음 출력이 표시되어야 합니다.

HTTP/1.1 200 OK
Server: nginx
Date: Sat, 09 Mar 2019 15:33:31 GMT
Content-Type: text/html
Content-Length: 10918
Last-Modified: Fri, 01 Feb 2019 16:05:17 GMT
Connection: keep-alive
ETag: "5c546e3d-2aa6"
Accept-Ranges: bytes

액세스에서 IP 제한

Nginx는 특정 IP 주소를 허용하거나 거부하는 ngx_http_access_module이라는 간단한 모듈과 함께 제공됩니다.

Nginx 형식 172.16.0.0/16을 허용하고 다른 서브넷에서 거부하려는 경우. 그런 다음 /etc/nginx/sites-enabled/default 파일을 엽니다.

nano /etc/nginx/sites-enabled/default

서버 블록 내에서 다음과 같이 변경합니다.

server {
        listen 80 default_server;
        listen [::]:80 default_server;

	allow 172.16.0.0/16;
    	deny  all;

완료되면 파일을 저장하고 닫습니다. 그런 다음 Nginx를 다시 시작하여 다음 변경 사항을 적용합니다.

systemctl restart nginx

이제 192.168.0.102와 같은 다른 IP 주소 범위에서 Nginx 서버에 액세스해 보십시오.

그런 다음 다음 명령을 사용하여 Nginx 로그를 확인합니다.

tail -f /var/log/nginx/error.log

다음 출력에서 액세스가 금지되어야 합니다.

2019/03/09 16:13:01 [error] 11589#11589: *1 access forbidden by rule, client: 192.168.0.102, server: _, request: "GET /test/ HTTP/1.1", host: "172.16.0.122"

TLS로 Nginx 보호

TLS(Transport Layer Security)는 SSL(Secure Socket Layer)의 후속 제품입니다. 보다 강력하고 효율적인 HTTPS를 제공하며 Forward Secrecy, 최신 OpenSSL 암호화 제품군과의 호환성 및 HSTS와 같은 향상된 기능을 포함합니다. 이 자습서에서는 Nginx에서 자체 서명된 SSL 인증서를 활성화하는 방법을 보여줍니다. 대신 lets Encrypt 인증서를 사용하려면 여기를 살펴보세요. https://linux-console.net/tutorial/nginx-with-letsencrypt-ciphersuite/

먼저 다음 명령을 사용하여 SSL용 디렉터리를 만듭니다.

mkdir /etc/nginx/ssl/

그런 다음 다음 명령을 사용하여 키와 인증서를 생성합니다.

cd /etc/nginx/ssl/

먼저 다음 명령을 사용하여 키를 생성합니다.

openssl genrsa -aes256 -out nginx.key 1024

다음 출력이 표시되어야 합니다.

Generating RSA private key, 1024 bit long modulus
...++++++
.............................++++++
e is 65537 (0x010001)
Enter pass phrase for nginx.key:
Verifying - Enter pass phrase for nginx.key:

다음으로 다음 명령을 사용하여 csr을 생성합니다.

openssl req -new -key nginx.key -out nginx.csr

아래와 같이 모든 정보를 제공하십시오.

Generating RSA private key, 1024 bit long modulus
...++++++
.............................++++++
e is 65537 (0x010001)
Enter pass phrase for nginx.key:
Verifying - Enter pass phrase for nginx.key:
:~# openssl req -new -key nginx.key -out nginx.csr
Enter pass phrase for nginx.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:IN
State or Province Name (full name) [Some-State]:Gujarat
Locality Name (eg, city) []:Junagadh
Organization Name (eg, company) [Internet Widgits Pty Ltd]:IT
Organizational Unit Name (eg, section) []:IT
Common Name (e.g. server FQDN or YOUR name) []:HITESH
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:admin
An optional company name []:IT

그런 다음 다음 명령을 사용하여 인증서에 서명합니다.

openssl x509 -req -days 365 -in nginx.csr -signkey nginx.key -out nginx.crt

다음 출력이 표시되어야 합니다.

Signature ok
subject=C = IN, ST = Gujarat, L = Junagadh, O = IT, OU = IT, CN = HITESH, emailAddress = 
Getting Private key
Enter pass phrase for nginx.key:

다음으로 Nginx 기본 가상 호스트 파일을 열고 인증서를 정의합니다.

nano /etc/nginx/sites-enabled/default

다음과 같이 변경합니다.

server {
        listen 192.168.0.100:443 ssl;
        root /var/www/html;
        index index.html index.htm index.nginx-debian.html;
        server_name _;
        ssl_certificate /etc/nginx/ssl/nginx.crt;
        ssl_certificate_key /etc/nginx/ssl/nginx.key;
        ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;

완료되면 파일을 저장하고 닫습니다. 그런 다음 Nginx 서버를 다시 시작하여 이러한 변경 사항을 적용합니다.

systemctl restart nginx

비밀번호로 디렉토리 보호

Nginx 웹 서버를 설정할 때 특정 디렉토리를 비밀번호로 보호할 수도 있습니다. .htpasswd 파일을 사용하여 이 작업을 수행할 수 있습니다.

이렇게 하려면 passwd 파일을 만들고 다음 명령을 사용하여 사용자를 추가합니다.

mkdir /etc/nginx/.htpasswd
htpasswd -c /etc/nginx/.htpasswd/passwd admin

다음 출력이 표시되어야 합니다.

New password: 
Re-type new password: 
Adding password for user admin

다음으로 다음 명령을 사용하여 Nginx 웹 루트 내에 테스트 디렉토리를 만듭니다.

mkdir /var/www/html/test

다음으로 다음 명령을 사용하여 www-data 사용자에게 소유권을 부여합니다.

chown -R www-data:www-data /var/www/html/test

그런 다음 다음 명령을 사용하여 Nginx 기본 가상 호스트 파일을 엽니다.

nano /etc/nginx/sites-enabled/default

다음으로 아래와 같이 테스트 디렉토리를 보호합니다.

        location /test {

	auth_basic  "Restricted";
	auth_basic_user_file   /etc/nginx/.htpasswd/passwd;

완료되면 파일을 저장하고 닫습니다. 그런 다음 Nginx 서비스를 다시 시작하여 이러한 변경 사항을 적용합니다.

systemctl restart nginx

그런 다음 웹 브라우저를 열고 URL http://your-server-ip/test를 입력합니다. 다음 페이지와 같이 테스트 디렉토리에 액세스하기 위해 사용자 이름과 비밀번호를 입력하라는 메시지가 표시됩니다.

축하합니다! Ubuntu 18.04 서버에서 Nginx 서버를 성공적으로 보호했습니다. 이것이 Nginx 웹 서버에서 호스팅되는 애플리케이션을 보호하는 데 도움이 되기를 바랍니다. 궁금한 점이 있으면 언제든지 문의해 주세요. 자세한 내용은 Nginx 보안 문서를 참조하세요.