如何在NGINX+DJANGO平台設置SSL連線

於Django應用程式裡採用HTTPS對於保護用戶數據非常重要。 如果網頁應用程序具有用戶身份驗證,就是使用HTTPS的最好的理由。 否則,用戶名和密碼將通過HTTP以純文本格式傳播。 這意味著如果用戶使用公共互聯網連接,並且他登錄您的應用程序,他很容易受到駭客偷襲。

重要的是不僅安全的登錄,密碼更改和支付頁面與HTTPS,以及整個應用程序。 以下說明,將指導完成所有必要的步驟,以正確保護您的Django應用程式。

建立一個SSL證書

第一步是為您的Django應用程式獲取SSL證書。 有幾個選項:您可以生成自己的證書,您可以從Let’s Encrypt獲得一個免費的證書,或者您可以從互聯網上的許多公司購買一個證書。

在本教程中,我將使用從Namecheap註冊的Positive SSL的簡單商業SSL證書。

產生一個CSR代碼

CSR代表證書簽名請求,它是一個通常在服務器端生成的base64編碼數據。因為我們將使用Nginx作為web服務器,我們將使用openssl。

通常CSR openssl配置默認包含如下內容:

公共名稱(應頒發域名證書)
國家
州(或省)
地點(或城市)
組織
組織單位(部)
電子郵件地址

請在ssh的terminal上執行下列指令來產生CSR代碼:

openssl req -new -newkey rsa:2048 -nodes -keyout simpleacademy.key -out simpleacademy.csr

請注意,simpleacademy可以改為自己網域的名字
接著輸入相關訊息:

Country Name (2 letter code) [AU]:TW
State or Province Name (full name) [Some-State]:Taiwan
Locality Name (eg, city) []:Taipei
Organization Name (eg, company) [Internet Widgits Pty Ltd]:The Solar Systems Limited
Organizational Unit Name (eg, section) []:IT
Common Name (e.g. server FQDN or YOUR name) []:simple.academy
Email Address []:[email protected]

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:Simple is Better Than Complex

完成後就會產生兩個檔案,CSR跟KEY兩個檔案。
然後可以到NameCheap的Positive SSL來啟動有效的SSL認證金鑰。其他內容不再多做說明

安裝有效SSL金鑰

將驗證過的CSR與KEY放置到ㄧ個目錄,例如:/etc/nginx/ssl。

接著修改virtualhost的設定。

upstream simple_academy_server {
  server unix:/opt/simple_academy/run/gunicorn.sock fail_timeout=0;
}

# Redirect all non-encrypted to encrypted
server {
    server_name simple.academy;
    listen 80;
    return 301 https://simple.academy$request_uri;
}

server {
    server_name simple.academy;

    listen 443;  # <-

    ssl on;  # <-
    ssl_certificate /etc/nginx/ssl/simpleacademy_cert_chain.crt;  # <-crt所在位置
    ssl_certificate_key /etc/nginx/ssl/simpleacademy.key;  # <-key所在位置

    client_max_body_size 4G;

    access_log /opt/simple_academy/logs/nginx-access.log;
    error_log /opt/simple_academy/logs/nginx-error.log;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;  # <-這個很重要,記得加入
        proxy_set_header Host $http_host;
        proxy_redirect off;

        if (!-f $request_filename) {
            proxy_pass http://simple_academy_server;
            break;
        }
    }
}

這樣基本上就完成了!!

在CentOS上,如何設定SSL給HTTPS,或其他應用。

採用OPENSSL指令來設定SSL,以下的動作需要root/su的權限才行。

參考網址:
http://wiki.centos.org/HowTos/Https
http://www.sslshopper.com/article-most-common-openssl-commands.html

 

1. 首先下載OpenSSL, openssl官網:http://www.openssl.org/

 yum install mod_ssl openssl

2. 產生ㄧ個self-signed certificate

 # 產生私有鑰匙 private key 
openssl genrsa -out ca.key 1024 

# 產生 CSR 
openssl req -new -key ca.key -out ca.csr

# 產生 Self Signed Key
openssl x509 -req -days 365 -in ca.csr -signkey ca.key -out ca.crt

# 將上述的檔案復制到正確的目錄
cp ca.crt /etc/pki/tls/certs
cp ca.key /etc/pki/tls/private/ca.key
cp ca.csr /etc/pki/tls/private/ca.csr

3. 修改/etc/httpd/conf.d/ssl.conf

....
SSLCertificateFile /etc/pki/tls/certs/ca.crt
SSLCertificateKeyFile /etc/pki/tls/private/ca.key   
...

4. 重新啓動httpd

service httpd restart

5. 設定虛擬主機(Virtual Hosting)

<VirtualHost *:443>
        SSLEngine on
        SSLCertificateFile /etc/pki/tls/certs/ca.crt
        SSLCertificateKeyFile /etc/pki/tls/private/ca.key
        <Directory /var/www/vhosts/yoursite.com/httpsdocs>
        AllowOverride All
        </Directory>
        DocumentRoot /var/www/vhosts/yoursite.com/httpsdocs
        ServerName yoursite.com
</VirtualHost>

6. 重新啓動httpd

service httpd restart

7. 設定防火牆

iptables -A INPUT -p tcp --dport 443 -j ACCEPT
/sbin/service iptables save
iptables -L -v

8 其他openssl主要指令集:
These commands allow you to generate CSRs, Certificates, Private Keys and do other miscellaneous tasks.
Generate a new private key and Certificate Signing Request

openssl req -out CSR.csr -new -newkey rsa:2048 -nodes -keyout privateKey.key

Generate a self-signed certificate (see How to Create and Install an Apache Self Signed Certificate for more info)

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privateKey.key -out certificate.crt

Generate a certificate signing request (CSR) for an existing private key

openssl req -out CSR.csr -key privateKey.key -new

Generate a certificate signing request based on an existing certificate

openssl x509 -x509toreq -in certificate.crt -out CSR.csr -signkey privateKey.key

Remove a passphrase from a private key

openssl rsa -in privateKey.pem -out newPrivateKey.pem

Checking Using OpenSSL
If you need to check the information within a Certificate, CSR or Private Key, use these commands. You can also check CSRs and check certificates using our online tools.

Check a Certificate Signing Request (CSR)

openssl req -text -noout -verify -in CSR.csr

Check a private key

openssl rsa -in privateKey.key -check

Check a certificate

openssl x509 -in certificate.crt -text -noout

Check a PKCS#12 file (.pfx or .p12)

openssl pkcs12 -info -in keyStore.p12

Debugging Using OpenSSL

If you are receiving an error that the private doesn’t match the certificate or that a certificate that you installed to a site is not trusted, try one of these commands. If you are trying to verify that an SSL certificate is installed correctly, be sure to check out the SSL Checker.

Check an MD5 hash of the public key to ensure that it matches with what is in a CSR or private key

openssl x509 -noout -modulus -in certificate.crt | openssl md5
openssl rsa -noout -modulus -in privateKey.key | openssl md5
openssl req -noout -modulus -in CSR.csr | openssl md5

Check an SSL connection. All the certificates (including Intermediates) should be displayed

openssl s_client -connect www.paypal.com:443

Converting Using OpenSSL

These commands allow you to convert certificates and keys to different formats to make them compatible with specific types of servers or software. For example, you can convert a normal PEM file that would work with Apache to a PFX (PKCS#12) file and use it with Tomcat or IIS. Use our SSL Converter to convert certificates without messing with OpenSSL.

Convert a DER file (.crt .cer .der) to PEM

openssl x509 -inform der -in certificate.cer -out certificate.pem

Convert a PEM file to DER

openssl x509 -outform der -in certificate.pem -out certificate.der

Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM

openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes

You can add -nocerts to only output the private key or add -nokeys to only output the certificates.

Convert a PEM certificate file and a private key to PKCS#12 (.pfx .p12)

openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt