CA certificate to build self https server

Because the CA charges, so you can self CA, to achieve the effect https by the CA into the browser, once 12306 tickets will need to import the certificate on their own website.

About https

2015, Alibaba's Taobao will, Lynx (including mobile clients) enabled site-wide HTTPS encryption, and passed the "double eleven" test, HTTPS transformation case has become the world's largest electronic business platform full stop.

HTTPS site-wide need to address three major problems.

The first is performance, three main points:

  1. HTTPS require several handshakes, thus consuming network becomes long, the user jumps from HTTP to HTTPS take some time;
  2. RSA HTTPS do check, which can affect device performance;
  3. All CDN nodes to support HTTPS, there are extremely complex and require solutions to face the challenges of DDoS.

Secondly, and peripheral compatibility:

  1. All pages must be changed HTTPS embedded resources, and these resources may come from different departments or even different companies, including images, videos, forms, etc., otherwise the browser will warn;
  2. Mobile client (APP) also need to adapt HTTPS, it is necessary to make adjustments to modify;
  3. Third-party sites can not solve the problem see the Referer;
  4. All development and test environments have to do HTTPS upgrade;

Finally, in order to ensure a smooth changeover at the line, we need to prepare in advance a large number of plans to cope with various situations that may arise.

So far, most of the mainstream sites have already completed the migration of HTTP to HTTPS, such as Taobao, Jingdong, Baidu, B station, Youku, etc., are still in use HTTP Tencent video, love the Fantastic Art, Dangdang and other sites.


The following brief introduction to the principles and encryption https


https Profile

HTTPS (full name: Hyper Text Transfer Protocol over SecureSocket Layer ), is safe for the target HTTP channel, on the basis of HTTP to ensure the security of the transmission through the transmission encryption and authentication.
SSL (Secure Sockets Layer Secure Sockets Layer), and its successor, Transport Layer Security (Transport Layer Security, TLS) to provide security and data integrity of a secure communications protocol for the network.

HTTPS SSL layer was added on the basis of HTTP to SSL encryption based security. Different HTTPS and HTTP default port, and there is an encryption / authentication layer (between the TCP and HTTP, i.e., between the application layer and the transport layer).

SSL protocol can be divided into two layers:

  • SSL Record Protocol (SSL Record Protocol): it is based on a reliable transport protocol (e.g., TCP), to provide high-level protocol data encapsulation, compression, encryption support basic functions.
  • SSL handshake protocol (SSL Handshake Protocol): It is built on top of the SSL Record protocol for data transmission before the actual start of communication between the two sides authentication, negotiate an encryption algorithm, encryption key exchange and so on.

Here Insert Picture Description
Https main building process with the SSL handshake protocol related.

Why migrate from http to https

HTTP data transmission protocol is unencrypted, plain text is therefore transmitted using the HTTP protocol is insecure private information, in order to ensure the privacy of data transmission can be encrypted, so designed Netscape SSL (Secure Sockets Layer) protocol with HTTP protocol for data transmission is encrypted, thus was born HTTPS.
In simple terms, HTTPS protocol is constructed from SSL + HTTP protocol can be encrypted transmission, network authentication protocol than HTTP protocol security.
The main difference between HTTPS and HTTP as follows:
  1, HTTPS protocol requires the CA (Certificate Authority, ie authority digital certificates) to request a certificate, generally less free certificates, thus requiring a fee.
  2, http is the hypertext transfer protocol, information is transmitted in the clear, https is encrypted with a security ssl transfer protocol.
  3, http and https use is completely different connections, with the port are not the same, the former is 80, which is 443.
  4, http connection is very simple, is stateless; is constructed by the HTTPS protocol SSL + HTTP encrypted transmission protocol, authentication of network protocols, security protocols than HTTP.

Communication About Encryption

Symmetric encryption

The method of using a single encryption key cryptography, the same key can be used simultaneously encrypting and decrypting information, also called single-key encryption.

For example: the Caesar cipher
Caesar cipher is • Julius Caesar (Julius Caesar) created by the expansion of the Roman period, operational command for encryption by courier delivery. Alphabet predetermined position and movement of encryption. For example, if two mobile right, the letter A will be changed to C, D becomes the letter B, ..., Z becomes the letter X, Y is changed to letter A, letter Z becomes B.

advantage:

算法公开、计算量小、加密速度快、加密效率高。

Disadvantages:

如果一方的密钥被泄露,加密信息也就不安全了。

Asymmetric encryption

Asymmetric encryption algorithm requires two keys: a public key (the publickey: referred to as a public key) and a private key (PrivateKey: referred to as a private key).

Public and private key are a pair, if the data is encrypted with the public key, only the corresponding private key can decrypt, on the contrary, can also be encrypted with the private key first, then use the public key to decrypt. Because the encryption and decryption using two different keys, so this algorithm is called asymmetric encryption algorithm.

Asymmetric encryption algorithm basic process is the exchange of confidential information:
Party generate a pair of public key and disclosed, needs to send information to other roles (B) using the key to the party (Party A's public key) of confidential information is encrypted and then sent to the Party; Party then his private key to decrypt the encrypted information. Just the opposite Party B wants to reply, use B's public key to encrypt data, empathy, party uses its own private key to decrypt it.

advantage:

一方密钥的丢失不会导致通信被破解,相对更安全。

Disadvantages:

加密和解密花费时间长、速度慢,只适合对少量数据进行加密。

scenes to be used

Simulation of a communication scenario:

有A、B、C、D四个用户,A想让B、C、D与自己进行私密通信。

If symmetric encryption, AB, respectively, need to negotiate a key between AC, AD.

If asymmetric encryption, only need to retain the private key A, his public key to B, C, D.
Whether B, C, D which party using public key cryptography message have only A can decrypt with the private key.

Security considerations:

通信前需要提前协商密钥。
  • Symmetric encryption
    message A key negotiation with other users, if capture is intercepted, it is vulnerable to "man in the middle attack", i.e., the communication data is detected or substitution attacker.

  • Asymmetric encryption
    A key with the same need to consult other users, need to construct a pair of male A private key, public key to send to B, C, D, retention own private key.
    At this time, when the message A to B, C, D are intercepted by hackers E, E A's public key can be reserved, then construct a new pair of public and private key, the private key is kept, his public key to B, C, D.

According to asymmetric encryption, E intermediary communications become:
B, C, D using public key encryption and sends the data E A, E hijacking the communication data, uses its own private key to decrypt the data, then use the public key of A encrypted data sent to A.
For user A, B, C, D, they do not know their intermediary for communication purposes is exposed.

How can the Communications Security:

利用非对称加密来确认双方身份建立连接,即SSL握手。

At this point need to introduce a public trust institution F, used to prove the identity of the user, or in the current communication environment, the individual is unable to prove identity for themselves.

The agency is CA.
CA has a pair of their own public and private key, the public key is open to all users, private own reservations.
When A wants to prove himself to B, just give his first request CA CA private key to encrypt a message with it (the signature), then the message is sent to B, if B can be decrypted by the CA's public key, indicating that this message is certified CA had not been tampered with others.

At this point man in the middle attack is no longer effective because even if intercepted data A to B, the broker can only use the CA's public key to decrypt the content of the message - "This is a CA certificate had been sent from A to B, data". But middlemen can not tamper with the contents of the message, because B only with CA's public key to verify whether the message is authenticated CA, middlemen with their own private key to encrypt data, B with CA's public key can not be untied.

CA's security certificate authority is enormous, CNNIC certificate incidents have occurred, CNNIC as a trusted root CA, if it is willing, it can easily falsify any site SSL certificates at home and abroad, with the firewall DNS poisoning, which can be initiated in the country middleman for any website attack, interception of communications data.

Symmetric encryption consider:

就对称加密而言,公信机构无法达到认证效果。
因为对称加密只有一个密钥,一旦公开任何人都可以对加密信息进行篡改。

These are symmetric encryption and asymmetric encryption uses a relatively large difference, between two symmetric encryption only two, rather than symmetric encryption can either use their private key to encrypt data, public key people have told this news is me , or you can let people have assured the public key to send the data, because only with the private key can decrypt the data.

Consider the communication efficiency:

如果需要频繁通信,每次通信都使用非对称加密需要花费较多的时间。

Symmetric encryption and asymmetric encryption each have advantages, a combination of both in order to better play the role.
In actual use, asymmetric encryption is used to establish a connection, via a secure connection negotiation for asymmetrically encrypted symmetric encryption key.
Since the key negotiation process is safe, it will not be negotiated key tampered with, then we can use the symmetric encryption key for subsequent fast communication.

https setup process

The following describes the actual process of https:
Here Insert Picture Description

  1. CA will own certificate (public trust certificates) to each browser vendors, manufacturers will configure the certificate to the respective browser.
  2. Site own credentials (credentials) to CA, let the CA private key is used to sign the certificate, sent back to the site after the CA signature. In this process, CA needs to verify the authenticity of the site, the site is also not just send a CA-signed certificate, the certificate which sites (including the site URL) and public key sites is necessary, but also contains some additional information along with the signature.
  3. Browser user requests a secure connection to the site, the site of the CA-signed certificate issued to the user after the browser based certificate information, do check which CA's signature, to find the corresponding public key authentication from the browser's own CA certificate.
  4. If verified, it proved the reliability, the user can provide through public Web site identities for secure connections, and follow-up consultation website symmetric encryption keys.

Self CA certificate

lab environment:

  • Operating System: CentOS 7
  • Apache version: httpd
  • php version: php7

Check the OpenSSL, if the version is lower than 1.0.1f recommended to upgrade, because under the OpenSSL 1.0.1f version has a Heartbleed vulnerability.
View version: $openssl version
Version update:$sudo yum update openssl

Firstly myCA directory used to store information about CA's self:

cd && mkdir -p myCA/signedcerts && mkdir myCA/private && cd myCA

myCA用于存放 CA 根证书,证书数据库,以及后续服务器生成的证书,密钥以及请求。
signedcerts保存签名证书的 copy,private包含私钥。

之后配置myCA相关参数,在myCA目录下进行:

echo '01'>serial && touch index.txt

然后创建 caconfig.cnf 文件(自建CA的配置文件):

vim ~/myCA/caconfig.cnf

caconfig.cnf文件内容如下:

# My sample caconfig.cnf file.
#
# Default configuration to use when one is not provided on the command line.
#
[ ca ]
default_ca      = local_ca
#
#
# Default location of directories and files needed to generate certificates.
#
[ local_ca ]
dir             = /home/<username>/myCA

certificate     = $dir/cacert.pem
database        = $dir/index.txt
new_certs_dir   = $dir/signedcerts
private_key     = $dir/private/cakey.pem
serial          = $dir/serial
#       
#
# Default expiration and encryption policies for certificates.
#
default_crl_days        = 365
default_days            = 1825
default_md              = SHA256
#       
policy          = local_ca_policy
x509_extensions = local_ca_extensions
#       
#
# Default policy to use when generating server certificates.  The following
# fields must be defined in the server certificate.
#
[ local_ca_policy ]
commonName              = supplied
stateOrProvinceName     = supplied
countryName             = supplied
emailAddress            = supplied
organizationName        = supplied
organizationalUnitName  = supplied
#       
#
# x509 extensions to use when generating server certificates.
#
[ local_ca_extensions ]
subjectAltName          = DNS:localhost
basicConstraints        = CA:false
nsCertType              = server
#       
#
# The default root certificate generation policy.
#
[ req ]
default_bits    = 2048
default_keyfile = /home/<username>/myCA/private/cakey.pem

default_md      = SHA256
#       
prompt                  = no
distinguished_name      = root_ca_distinguished_name
x509_extensions         = root_ca_extensions
#
#
# Root Certificate Authority distinguished name.  Change these fields to match
# your local environment!
#
[ root_ca_distinguished_name ]
commonName              = MyOwn Root Certificate Authority # CA机构名
stateOrProvinceName     = JS                               # CA所在省份
countryName             = CN                               # CA所在国家(仅限2个字符)
emailAddress            = [email protected]                     # 邮箱
organizationName        = XXX                              # 
organizationalUnitName  = XXX                              # 
#       
[ root_ca_extensions ]
basicConstraints        = CA:true

其中dir和default_keyfile的路径需要改成自己的username

生成 CA 根证书和密钥:

export OPENSSL_CONF=~/myCA/caconfig.cnf       #该命令用于给环境变量 OPENSSL_CONF 赋值为caconfig.cnf。
openssl req -x509 -newkey rsa:2048 -out cacert.pem -outform PEM -days 1825             # 生成 CA 根证书和密钥

该步骤需要用户设置一个密码,请牢记。

以上步骤生成了 CA 自签名根证书,和 RSA 公/私密钥对,证书的格式是 PEM,有效期是1825天。

/myCA/cacert.pem: CA 根证书
/myCA/private/cakey.pem: CA 私钥

生成服务器配置文件exampleserver.cnf:

vim ~/myCA/exampleserver.cnf

exampleserver.cnf文件内容如下:

#
# exampleserver.cnf
#

[ req ]
prompt             = no
distinguished_name = server_distinguished_name

[ server_distinguished_name ]
commonName              = localhost          # 服务器域名
stateOrProvinceName     = JS                 # 服务器所在省份
countryName             = CN                 # 服务器所在国家(仅限2个字符)
emailAddress            = [email protected]       # 邮箱
organizationName        = XXX                # 
organizationalUnitName  = XXX                # 

生成服务器证书和密钥:

export OPENSSL_CONF=~/myCA/exampleserver.cnf   # 该命令设置环境变量 OPENSSL_CONF,使得 openssl 更换配置文件。
openssl req -newkey rsa:1024 -keyout tempkey.pem -keyform PEM -out tempreq.pem -outform PEM

同样的,需要设置密码。

之后,有2种对临时密钥的操作,选择其一即可:
1.将临时私钥转换为 unencrypted key,即密钥不加密状态:

penssl rsa -in tempkey.pem -out server_key.pem

需要输入密码短语。

2.如果希望将 key 保持为加密状态,直接改名:

mv tempkey.pem server_key.pem

两者的区别是,第二种需要在服务器启动时输入私钥的密码,否则会导致服务器启动失败,但第二种安全性高于第一种,可以更好的保护密钥。

使用 CA key 对服务器证书签名:

export OPENSSL_CONF=~/myCA/caconfig.cnf
openssl ca -in tempreq.pem -out server_crt.pem

删除临时证书和密钥:

rm -f tempkey.pem && rm -f tempreq.pem

现在,自签名的服务器证书和密钥对便产生了:

  • server_crt.pem : 服务器证书文件
  • server_key.pem : 服务器密钥文件

以下通过LAMP搭建一个网站进行验证


配置httpd(Apache)

第一步:安装Apache服务程序(apache服务的软件包名称叫做httpd)

yum install httpd -y

第二步: 将Apache服务添加到开机自启中

systemctl start httpd
systemctl enable httpd

第三步:打开浏览器 测试 127.0.0.1,可以看到默认主页

httpd主要目录:

  • 服务目录:/etc/httpd
  • 主配置目录:/etc/httpd/conf/httpd.conf
  • 网站数据目录:/var/www/html
  • 访问日志:/var/log/httpd/access_log
  • 错误日志:/var/log/httpd/error_log

配置php7

1、安装源

安装php72w需要配置额外的yum源,否则会报错不能找到相关软件包。

php高版本的yum源地址,有两部分,其中一部分是epel-release,另外一部分来自webtatic,如果跳过epel-release安装webtatic的时候会有错误。

安装需要的命令是:

rpm -Uvh https://dl.Fedoraproject.org/pub/epel/7/x86_64/Packages/e/epel-release-7-11.noarch.rpm
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm

也可以选择下面的这个命令,是一样的效果:

yum install epel-release -y
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm

2、清除历史版本

为了防止CentOS上面发生php冲突,所以,这个命令还是先执行一下更好些:

yum -y remove php*

3、安装扩展包

事实上,这里面的对应扩展库很多,一定要注意的有cli和fpm这两个包,其它的相关包看需要:

yum -y install php72w php72w-cli php72w-fpm php72w-common php72w-devel php72w-mysql

由于后面要用MySQL,所以mysql包也是需要的。

比较全的版本:

yum -y install php72w php72w-cli php72w-fpm php72w-common php72w-devel php72w-embedded php72w-gd php72w-mbstring php72w-mysqlnd php72w-opcache php72w-pdo php72w-xml

配置MySQL

在CentOS中默认安装有MariaDB,这个是MySQL的分支,但为了需要,还是要在系统中安装MySQL,而且安装完成之后可以直接覆盖掉MariaDB。
网络环境允许的话直接安装:

wget -i -c http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm
yum -y install mysql57-community-release-el7-10.noarch.rpm
yum -y install mysql-community-server

mysql-community-server较大如果下载很慢,可以到国内镜像源下载:
http://mirrors.ustc.edu.cn/mysql-ftp/Downloads/
下载后解压到图中文件目录下:
Here Insert Picture Description
注意文件权限,再安装:

yum -y install mysql57-community-release-el7-10.noarch.rpm
yum -y install mysql-community-server

mysql有初始默认密码,使用以下命令查找:

grep "password" /var/log/mysqld.log

输入初始密码,此时不能做任何事情,因为MySQL默认必须修改密码之后才能操作数据库。
修改密码:

mysql -uroot -p
ALTER USER 'root'@'localhost' IDENTIFIED BY '新密码';

When the new password settings if set too simple will complain, the reason is because there are norms MySQL password settings, specifically related to the value validate_password_policy, you can try a longer password is case-sensitive underlined.

MySQL complete initial password rules View

SHOW VARIABLES LIKE 'validate_password%';

You can be modified by the following command:

mysql> set global validate_password.policy=0;
mysql> set global validate_password.length=1;

After a simple password can be reset.

Configuring SSL

ssl need the following modules:
Here Insert Picture Description
modify ssl.conf:

cd /etc/httpd/conf.d
sudo vim ssl.conf

Here Insert Picture Description
DocumentRoot to modify their pages directory, and change the certificate key source of self CA:
Here Insert Picture Description

Web Configuration

The site will need to be copied to a folder under / var / www / html / directory
to modify the file name website /etc/httpd/conf/httpd.conf file:
Here Insert Picture Description
Create a database of your site's needs:

create database myzoo;
use myzoo; 
create table Person(PersonID int primary key auto_increment, Password varchar(100),Salt varchar(100),Username varchar(100),Token varchar(100),Zoobars int default 10, Profile varchar(5000));

Restart httpd view the current page:

setenforce  0
sudo systemctl restart httpd

Turn off selinux, or will be error, the certificate password (that is not the site of CA) verifies previous settings before service starts.
Here Insert Picture Description
Currently an ordinary http connection, because there is no self-built CA into the browser.

Browser Import Certificate

Since the website's certificate is self-signed CA, the browser does not trust, so the need to manually import the CA certificate.

With chrome as an example: Settings -> Advanced -> Privacy and Security -> Manage Certificates
Here Insert Picture Description
can view certificate details and self import CA certificate
Here Insert Picture Description
because the domain name set when the certificate before configuring the site is localhost, so the need for https domain by localhost connection, you can not use 127.0.0.1.
Here Insert Picture Description
Address bar to access a green lock condition occurs, successfully built https.

Guess you like

Origin www.cnblogs.com/ustca/p/12060580.html