欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

nginx 双向证书验证_使用Nginx的基于证书的双向TLS身份验证

程序员文章站 2022-06-29 21:56:09
...

nginx 双向证书验证

Additional layer of security for your Flask or FastAPI server

Flask或FastAPI服务器的附加安全层

You will learn to create self-signed server certificates in order to serve your web application as https. Later on, you can easily swap it with certificates from certificates authorities for your server.

您将学习创建自签名服务器证书,以便将Web应用程序用作https。 稍后,您可以轻松地将其与服务器证书颁发机构颁发的证书交换。

In addition, this article will also cover two-way authentication between server and client using certificates. Users are required to install relevant certificates in their browser before they can access your web application. This method provides an alternative to the usual username-password authentication. Have a look at the following image for an overview of mutual TLS authentication

此外,本文还将介绍使用证书的服务器和客户端之间的双向身份验证。 用户必须先在浏览器中安装相关证书,然后才能访问您的Web应用程序。 此方法提供了通常的用户名密码验证的替代方法。 查看下图,以了解相互TLS身份验证的概述

nginx 双向证书验证_使用Nginx的基于证书的双向TLS身份验证
CodeProject CodeProject

It is mostly used in workplace or universities in which users can only access internal websites with the company’s computers that have been installed with the right certificates. One major advantage is no password removal or creation is required in the event where an employee resigned from his/her job or there is an intake of new students to the university. Please bear in mind that such authentication is just another way to secure your application. In fact, you can even combine it with username-password authentication for better security. It largely depends on your use cases.

它主要用于工作场所或大学中,其中用户只能使用已安装了正确证书的公司计算机访问内部网站。 一个主要优点是,如果员工辞职或大学招收新学生,则无需删除或创建密码。 请记住,这种身份验证只是保护您的应用程序的另一种方法。 实际上,您甚至可以将其与用户名密码身份验证结合使用以提高安全性。 这在很大程度上取决于您的用例。

1.设定 (1. Setup)

I am using Ubuntu 18.04.5 LTS (Bionic Beaver) for this tutorial. You can check the os version of your local machine via the following command

我在本教程中使用Ubuntu 18.04.5 LTS(Bionic Beaver)。 您可以通过以下命令检查本地计算机的操作系统版本

cat /etc/os-release

Before you continue, make sure that you have installed both Nginx and OpenSSL in your machine.

在继续之前,请确保已在计算机中安装了Nginx和OpenSSL。

Nginx的 (Nginx)

Run the following command to check if nginx is installed in your machine.

运行以下命令以检查您的计算机中是否安装了nginx。

nginx -v

的OpenSSL (OpenSSL)

As for OpenSSL, you can easily check it as follows:

对于OpenSSL,您可以轻松地按以下步骤进行检查:

openssl version -a

If it is not install, kindly refer to the following link to install it.

如果尚未安装,请参考以下链接进行安装。

Let’s proceed to the next section to generate the required certificates and private keys using OpenSSL.

让我们继续进行下一部分,以使用OpenSSL生成所需的证书和私钥。

2. OpenSSL (2. OpenSSL)

服务器证书和** (Server Certificate and Key)

Change the working directory to the following

将工作目录更改为以下内容

/etc/ssl

You should see the following files and folders:

您应该看到以下文件和文件夹:

  • certs — Contains all the certificates that identify their respective certificate authorities.

    certs包含标识各自证书颁发机构的所有证书。

  • openssl.conf — Configuration file for openssl.

    openssl.conf -openssl的配置文件。

  • private — Empty folder to store your personal certificates.

    private -空文件夹存储您的个人证书。

It is highly recommended to store your certificates here although you can actually store it anywhere you like. In this tutorial, I am going to create a new folder called selfsigned and generate certificates inside it. This allows us to easily clean it up later on.

强烈建议您将证书存储在此处,尽管您实际上可以将其存储在任意位置。 在本教程中,我将创建一个名为selfsigned的新文件夹并在其中生成证书。 这使我们以后可以轻松清理它。

Run the following command to generate the a server certificate and its corresponding private key. We are are going to use X.509 Certificate Data Management which is the standard format for public key certificates which contain the cryptographic key pairs with identities and information related to websites or organizations.

运行以下命令以生成服务器证书及其对应的私钥。 我们将使用X.509证书数据管理,这是公共**证书的标准格式,其中包含带有与网站或组织相关的身份和信息的加***对。

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout server.key -out server.crt
  • req — Represent the certificate request and certificate generating utility. It will use the configuration from openssl.conf.

    req —代表证书申请和证书生成实用程序。 它将使用openssl.conf的配置。

  • nodes — Represent no DES (cryptography term) instead of nodes (programming term). It means that it will create an unencrypted private key. If omitted, it will prompt for a passphrase.

    nodes -不代表no DES (加密术语),而nodes (编程术语)。 这意味着它将创建一个未加密的私钥。 如果省略,它将提示输入密码。

  • days 365— Determine the number of days for validity of the certificate. The default value is 30 days. In this case, I have specified a 365 days validity.

    days 365 —确定证书有效期的天数。 默认值为30天。 在这种情况下,我指定了365天有效期。

  • newkey rsa:2048 — Create a new certificate request and a new private key. Accepts an input parameter in the form of rsa:nbits, alg:file, param:file, algname:file, etc. For this tutorial, I am using rsa with 2048 bits.

    newkey rsa:2048 —创建一个新的证书请求和一个新的私钥。 接受rsa:nbitsalg:fileparam:filealgname:file等形式的输入参数。对于本教程,我使用的2048位rsa。

  • keyout — Name of the private key.

    keyout —私钥名称。

  • out — Name of the certificate.

    out —证书名称。

It will prompt for some details, simply hit enter all the way till the end. It will generate the following files:

它将提示您一些详细信息,只需完全按Enter键即可。 它将生成以下文件:

  • server.crt — Certificate for your server.

    server.crt —服务器的证书。

  • server.key — Private key for your server.

    server.key服务器的私钥。

In fact, you can now use this self-signed certificate to run your server as https. You should not use self-signed certificate for production server.

实际上,您现在可以使用此自签名证书以https身份运行服务器。 您不应将自签名证书用于生产服务器。

客户证书和** (Client Certificate and Key)

For mutual TLS authentication, you will need a certificate and private key for client. Run the following command to generate them.

对于双向TLS身份验证,您将需要客户端的证书和私钥。 运行以下命令以生成它们。

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

Likewise, you should get the following certificates and private key

同样,您应该获得以下证书和私钥

  • client.crt

    client.crt
  • client.key

    客户**

The next step is to combine both of them together as PKCS12 file so that you can import them into the client’s browser for mutual TLS authentication. It will prompt you for password. Simply click enter to create a PKCS12 file without a password.

下一步是将它们作为PKCS12文件组合在一起,以便可以将它们导入客户端的浏览器中以进行相互TLS身份验证。 它将提示您输入密码。 只需单击Enter即可创建没有密码的PKCS12文件。

openssl pkcs12 -export -out client.pfx -inkey client.key -in client.crt

用于检查和验证的其他OpenSSL命令 (Extra OpenSSL Commands for Checking and Verification)

You can use the following command to check a private key

您可以使用以下命令来检查私钥

openssl rsa -in server.key -check

As for certificates, you can check it as follows:

至于证书,您可以按以下方式检查它:

openssl x509 -in server.crt -text -noout

If you have created PKCS12 file which usually ends with .pfx or .p12, you can check the content via the following command

如果创建了通常以.pfx或.p12结尾的PKCS12文件,则可以通过以下命令检查内容

openssl pkcs12 -info -in client.pfx

3. Nginx (3. Nginx)

In this section, we are going to modify the configurations in nginx to support https and mutual TLS authentication. Once you have nginx installed in your, head over to the following directory.

在本节中,我们将修改nginx中的配置以支持https和双向TLS身份验证。 一旦您安装了nginx,请转到以下目录。

/etc/nginx

You should see the following files and directories when you run ls command.

运行ls命令时,应该看到以下文件和目录。

nginx 双向证书验证_使用Nginx的基于证书的双向TLS身份验证

Instead of modifying the nginx.conf file directly, we are going to change the configuration file in sites-available folder. Change the working directory to the folder

而不是直接修改nginx.conf文件,我们将更改sites-available文件夹中的配置文件。 将工作目录更改为文件夹

cd sites-available

You should see a file called default. Before you continue, let’s duplicate it and keep the new copy as backup file in case anything goes wrong.

您应该看到一个名为default的文件。 在继续之前,让我们复制它,并将新副本保留为备份文件,以防万一出问题。

cp default backup.conf

https (https)

You should see the following lines of code inside default when you open it.

打开default代码后,您应该在default代码中看到以下代码行。

nginx 双向证书验证_使用Nginx的基于证书的双向TLS身份验证

To enable https for your server, simply un-comment the following lines

要为您的服务器启用https,只需取消注释以下行

listen 443 ssl default_server;
listen [::]:443 ssl default_server;

and append the following configuration below it (modify the path accordingly)

并在其下面附加以下配置(相应地修改路径)

ssl_certificate         /etc/ssl/selfsigned/server.crt;
ssl_certificate_key /etc/ssl/selfsigned/server.key;

You should modify the root setting as well if you are serving any static files. For example, my Flask server is located at the following location

如果要提供任何静态文件,还应该修改根设置。 例如,我的Flask服务器位于以下位置

root /home/tester/wfng;

Let’s say your Flask server is accessible at the following URL,

假设您可以通过以下网址访问Flask服务器,

http://localhost:5000/

you can easily create a reverse proxy for it via nginx by adding the following lines of code

您可以通过添加以下代码行来通过nginx轻松为其创建反向代理

location / {
proxy_pass http://localhost:5000/;
}

相互TLS身份验证 (Mutual TLS Authentication)

Add the following lines to enable mutual TLS authentication with nginx

添加以下行以使用nginx启用相互TLS身份验证

ssl_client_certificate  /etc/ssl/selfsigned/client.crt;
ssl_verify_client yes;

If you have multiple client certificates, simply concatenate them into one single file as follows:

如果您有多个客户端证书,只需将它们串联到一个文件中,如下所示:

cat cert1.crt cert2.crt > certs.pem

There might arise a situation in which you wanted to enable mutual TLS authentication only for specific routes. In this case, simply change the ssl_verify_client to optional and add the following conditional check.

可能会出现您只想为特定路由启用双向TLS身份验证的情况。 在这种情况下,只需将ssl_verify_client更改为optional并添加以下条件检查。

location /user {
if ($ssl_client_verify != "SUCCESS") { return 403; } proxy_pass http://localhost:5000/user;
}

$ssl_client_verify returns the following results:

$ssl_client_verify返回以下结果:

  • SUCCESS — Successfully verified the certificate.

    SUCCESS —成功验证证书。

  • FAILED:reason — Verification failed and the reason for the failure.

    FAILED:reason -验证失败以及失败的原因。

  • NONE — If a certificate was not present.

    NONE -如果不存在证书。

Check the following gist for an example the default file.

请检查以下要点,以获取default文件示例。

server {
  listen 443 ssl default_server;
  listen [::]:443 ssl default_server;


  ssl_certificate         /etc/ssl/selfsigned/server.crt;
  ssl_certificate_key     /etc/ssl/selfsigned/server.key;
  ssl_client_certificate  /etc/ssl/selfsigned/client.crt;
  ssl_verify_client       optional;


  root /home/tester/wfng;


  server_name _;


  location /user {
    if ($ssl_client_verify != "SUCCESS") { return 403; }


    proxy_pass http://localhost:5000/user;
  }


  location / {
    proxy_pass http://localhost:5000/;
  }
}

Once you are done, the next step is to verify your configuration file via the following command to make sure that there is no error.

完成后,下一步就是通过以下命令验证您的配置文件,以确保没有错误。

nginx -t

If the test is successful, you will see the following output on your terminal.

如果测试成功,您将在终端上看到以下输出。

nginx 双向证书验证_使用Nginx的基于证书的双向TLS身份验证

After that, you need to reload the configuration for it to take effect.

之后,您需要重新加载配置以使其生效。

nginx -s reload

Alternatively, you can restart nginx as well instead of reloading the configuration.

另外,您也可以重新启动nginx而不是重新加载配置。

sudo systemctl restart nginx

4.浏览器 (4. Browser)

https(https)

You can now access your server in your browser via its corresponding domain or IP. Let’s say you are accessing an URL that does not required client authentication, it should prompt the following warning when you are accessing it for the first time (differs based on the browser that you used).

现在,您可以通过其相应的域或IP在浏览器中访问服务器。 假设您正在访问不需要客户端身份验证的URL,那么当您首次访问该URL时(它会根据您使用的浏览器而有所不同)时会提示以下警告。

nginx 双向证书验证_使用Nginx的基于证书的双向TLS身份验证

Simply click Advance and Accept the Risk and Continue. You should reached the homepage of your server.

只需单击“ AdvanceAccept the Risk and Continue 。 您应该访问服务器的主页。

相互TLS身份验证 (Mutual TLS Authentication)

As for mutual TLS authentication, you need to import the PKCS12 that we have created earlier. Head over to Option or Setting based on your browser and search for Certificate. The following is the user interface for Firefox

对于双向TLS身份验证,您需要导入我们之前创建的PKCS12。 根据您的浏览器转到“选项”或“设置”,然后搜索“证书”。 以下是Firefox的用户界面

nginx 双向证书验证_使用Nginx的基于证书的双向TLS身份验证

Google Chrome users should see the following interface instead

Google Chrome用户应该改用以下界面

nginx 双向证书验证_使用Nginx的基于证书的双向TLS身份验证

Click on View Certificate and and then the Import button

单击View Certificate ,然后单击Import按钮

nginx 双向证书验证_使用Nginx的基于证书的双向TLS身份验证

It will prompt for the password that is tied to the certificate. Once you have imported the certificate, simply relaunched the browser. When you access the URL again, your browser will prompt you for User Identification Request. Accept it and you should be able to access your server.

它将提示输入与证书绑定的密码。 导入证书后,只需重新启动浏览器即可。 再次访问URL时,浏览器将提示您输入User Identification Request 。 接受它,您应该可以访问服务器。

结论 (Conclusion)

Let’s recap what we have learned today.

让我们回顾一下我们今天学到的东西。

We started off with a brief introduction and the advantages of mutual TLS authentication. Next, we moved on to install the necessary modules namely nginx and openssl.

我们从简要介绍和相互TLS身份验证的优点开始。 接下来,我们继续安装必要的模块,即nginx和openssl。

We have also generated a certificate and private key for the client in order to serve it as https. Besides, we created another set of certificate and private key for mutual TLS authentication. We combined it later on to create a PKCS12 file to be imported to our browser later on.

我们还为客户端生成了证书和私钥,以便将其用作https。 此外,我们还创建了另一组用于相互TLS身份验证的证书和私钥。 稍后我们将其组合在一起,以创建PKCS12文件,稍后将其导入到我们的浏览器中。

Later on, we continued with modifying the configuration file in nginx based on our use case. Once we are done with it, we restarted nginx and imported the appropriate certificate to our browser. By now, you should be able to access your server directly from your browser.

后来,我们继续根据用例在nginx中修改配置文件。 完成操作后,我们重新启动了nginx并将相应的证书导入到我们的浏览器中。 到现在为止,您应该能够直接从浏览器访问服务器。

Thanks for reading this piece. Hope to see you again in the next tutorial!

感谢您阅读本文。 希望在下一个教程中再见!

翻译自: https://levelup.gitconnected.com/certificate-based-mutual-tls-authentication-with-nginx-57c7e693759d

nginx 双向证书验证

相关标签: nginx https ssl