Because the CA charges, you can build your own CA. You can import the CA into your browser to achieve the effect of https. Once you purchased tickets in 12306, you need to import the website certificate yourself.

About https

In 2015, Alibaba enabled HTTPS encryption on its Taobao and Tmall (including mobile clients) sites, and successfully passed the “Double Eleven” test, becoming the world’s largest e-commerce platform full-site HTTPS transformation case.

There are three major issues that need to be addressed with HTTPS for the entire site.

The first is performance, which is mainly divided into three points:

  1. HTTPS requires multiple handshake, so the network takes longer, and it takes some time for users to jump from HTTP to HTTPS;
  2. HTTPS does RSA check, which will affect device performance;
  3. All CDN nodes need to support HTTPS and need extremely complex solutions to face the challenges of DDoS.

Second, compatibility and surroundings:

  1. All embedded resources in the page must be changed to HTTPS. These resources may come from different departments or even different companies, including pictures, videos, forms, etc., otherwise the browser will warn;
  2. The mobile client (APP) also needs to adapt to HTTPS, so it must be adjusted and modified;
  3. Solve the problem that Referer cannot be seen by third-party websites;
  4. All development and test environments need to be upgraded with HTTPS;

Finally, in order to ensure a smooth switch when going online, a large number of plans need to be prepared in advance to deal with various possible situations.

So far, most of the mainstream websites in China have completed the HTTP to HTTPS migration, such as Taobao, JD.com, Baidu, B station, Youku, etc., and still use HTTP for Tencent Video, iQiyi, Dangdang and other sites.

The following first introduces the principle of https and encryption

Introduction to https

HTTPS (full name: Hyper Text Transfer Protocol over SecureSocket Layer) is an HTTP channel whose goal is security. Based on HTTP, the security of the transmission process is ensured through transmission encryption and identity authentication.
SSL (Secure Sockets Layer) and its successor Transport Layer Security (TLS) is a security protocol that provides security and data integrity for network communications.

HTTPS adds an SSL layer on top of HTTP, and uses SSL encryption technology as the security foundation. HTTPS and HTTP have different default ports, and there is an encryption / authentication layer (between HTTP and TCP, that is, between the application layer and the transport layer).

The SSL protocol can be divided into two layers:

  • SSL Record Protocol: It is built on a reliable transmission protocol (such as TCP) and provides support for basic functions such as data encapsulation, compression, and encryption for higher-level protocols.
  • SSL Handshake Protocol (SSL Handshake Protocol): It is based on the SSL record protocol. It is used for identity authentication, negotiation of encryption algorithms, exchange of encryption keys, etc. before the actual data transmission begins.

 

The process of setting up https is mainly related to the SSL handshake protocol.

Why migrate from http to https

The data transmitted by the HTTP protocol is unencrypted, that is, plain text. Therefore, it is very insecure to transmit private information using the HTTP protocol. In order to ensure that these private data can be transmitted encrypted, Netscape has designed the SSL (Secure Sockets Layer) protocol for HTTPS was born to encrypt the data transmitted by the HTTP protocol.
In simple terms, the HTTPS protocol is a network protocol that can be encrypted and authenticated by the SSL + HTTP protocol. It is more secure than the HTTP protocol.
The differences between HTTPS and HTTP are as follows:
1. The https protocol needs to apply for a certificate from a CA (Certificate Authority), which generally has fewer free certificates and therefore requires a certain cost.
2. http is a hypertext transmission protocol, information is transmitted in plain text, and https is a secure ssl encrypted transmission protocol.
3. http and https use completely different connection methods and different ports. The former is 80 and the latter is 443.
4. The http connection is very simple and stateless; the HTTPS protocol is a network protocol constructed by SSL + HTTP that can perform encrypted transmission and identity authentication, which is more secure than HTTP.

Introduction to Communication Encryption

Symmetric encryption

With the encryption method of single key cryptosystem, the same key can be used for information encryption and decryption at the same time, also known as single key encryption.

Example: The Caesar Code The
Caesar Code was created by Julius Caesar during the Roman Expansion and is used to encrypt operational orders passed through messengers. It encrypts the letters of the alphabet by moving them a certain position. For example, if you move 2 digits to the right, the letter A will become C, the letter B will become D, …, the letter X will become Z, the letter Y will become A, and the letter Z will become B.

advantage:

open, less calculation, fast and high efficient

Cons:

less security

Asymmetric encryption

Asymmetric encryption algorithms require two keys: a public key (publickey for short) and a private key (privatekey: private key).

The public key and the private key are a pair. If you use the public key to encrypt the data, you can only decrypt it with the corresponding private key. On the contrary, you can also use the private key to encrypt and then use the public key to decrypt. Because encryption and decryption use two different keys, this algorithm is called an asymmetric encryption algorithm.

The basic process of the asymmetric encryption algorithm to realize the exchange of confidential information is:
Party A generates a pair of keys and makes the public key public. Other roles (Party B) who need to send information to Party A use the key (Party’s public key) pair The confidential information is encrypted and then sent to Party A; Party A then uses its private key to decrypt the encrypted information. When Party A wants to reply to Party B, the opposite is true. Party B’s public key is used to encrypt the data. Similarly, Party B uses its own private key to decrypt.

advantage:

safer

Cons:

more calculation, for little data

scenes to be used

Simulate a communication scenario:

user A、B、C、D,A communicates with B、C、D 

If you use symmetric encryption, you need to negotiate a key between AB, AC, and AD.

If asymmetric encryption is used, only A needs to keep the private key and distribute his public key to B, C, and D.
No matter which party B, C, D uses the public key to encrypt the message, only A can decrypt it with the private key.

Security considerations:

confirm key before communication
  • Messages that use symmetric encryption A to negotiate keys with other users will be vulnerable to “man-in-the-middle attacks” if they are intercepted by the captured packets, that is, the communication data is detected or dropped by the attacker.
  • Using asymmetric encryption
    A also needs to negotiate keys with other users. A needs to construct a pair of public and private keys, send the public keys to B, C, and D, and keep the private key.
    At this time, if the message sent by A to B, C, and D is intercepted by hacker E, E can retain A’s public key, and then construct a new pair of public and private keys, retain the private key, and send his public key to B, C, D.

According to asymmetric encryption, E becomes the middleman of communication:
B, C, D use E’s public key to encrypt the data and send it to A. After E hijacks the communication data, E uses his private key to decrypt the data, and then uses A’s public key. The encrypted data is sent to A.
For users A, B, C, and D, they did not know that their communication was exposed to the middleman.

How to make communication secure:

asymmetric encryption confirm IDs, as SSL shakehands。

At this time, a public trust agency F needs to be introduced to prove the identity of the user; otherwise, in the current communication environment, individuals cannot prove their identity for themselves.

This institution is the CA.
The CA has a pair of public and private keys. The public key is public to all users, and the private key is kept by itself.
When A wants to prove himself to B, he only needs to request the CA to encrypt his own message with the CA private key (signature), and then send the message to B. If B can decrypt it with the CA’s public key, explain this message It is certified by CA and has not been tampered with by others.

At this time, the man-in-the-middle attack no longer works, because even if the data sent by A to B is intercepted, the man-in-the-middle can only use the CA’s public key to decrypt the message content-“This is a certificate verified by the CA and sent by A to B data”. However, the intermediary cannot tamper with the content of the message, because B will only use the public key of the CA to verify whether the message has been authenticated by the CA. The data encrypted by the intermediary with his private key cannot be unlocked by the public key of the CA.

The power of security certificate CA is huge. In the event of a CNNIC certificate incident, CNNIC acts as a trusted root CA. If it wants to, it can forge SSL certificates of any site at home and abroad. In conjunction with firewall DNS pollution, it can initiate domestically. Man-in-the-middle attacks on any website, interception of communication data.

Consider symmetric encryption again:

The above is a big difference between symmetric encryption and asymmetric encryption. Symmetric encryption can only be used in pairs. Asymmetric encryption can use its own private key to encrypt data. Tell people who have the public key that this message was sent by me. Yes, you can also send data with confidence to those who have the public key, because only those who have the private key can decrypt the data.

Consider communication efficiency:

Symmetric encryption and asymmetric encryption have their own advantages, and the combination of the two can play a better role.
In actual use, the connection is established using asymmetric encryption, and a key for symmetric encryption is negotiated through the asymmetric encrypted secure connection.
Because the process of negotiating a key is secure, the negotiated key will not be tampered with, and you can then use the key for fast communications with subsequent symmetric encryption.

https establishment process

The following describes the actual process of https:
How_to_Self-built_CA_certificate_and_build_https_server_1.png

  1. The CA gives its own certificate (public trust certificate) to each browser vendor, and the vendor configures the certificate to their respective browsers.
  2. The website gives its own certificate (identity certificate) to the CA, and the CA uses the private key to sign the certificate, and the CA signs it and sends it back to the website. In this process, the CA needs to verify the authenticity of the website. The certificate issued by the website to the CA is not just a certificate. The website certificate (including the website URL) and the website public key are necessary. It also contains some other information to be signed together.
  3. The browser user requests a secure connection from the website. The website sends the CA-signed certificate to the user. The browser checks which CA made the signature based on the certificate information and finds the corresponding public key verification from the CA certificate that comes with the browser.
  4. If the verification is passed, the reliability of the website identity is proved. The user can make a secure connection through the public key provided by the website, and negotiate with the website for the subsequent symmetric encryption key.

Self-built CA certificate

lab environment:

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

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

First create a myCA directory to store relevant information about the self-built CA:

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

myCA is used to store the CA root certificate, certificate database, and certificates, keys, and requests generated by subsequent servers.
signedcerts holds a copy of the signed certificate, and private contains the private key.

Then configure myCA related parameters in the myCA directory:

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

Then create the caconfig.cnf file (the configuration file of the self-built CA):

vim ~/myCA/caconfig.cnf

The content of the caconfig.cnf file is as follows:

# 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 
stateOrProvinceName     = JS                               
countryName             = CN                               
emailAddress            = XXXX@XXX.com                     
organizationName        = XXX                               
organizationalUnitName  = XXX                            
#       
[ root_ca_extensions ]
basicConstraints        = CA:true

The path of dir and default_keyfile needs to be changed to your own username

Generate CA root certificate and key:

export OPENSSL_CONF=~/myCA/caconfig.cnf      
openssl req -x509 -newkey rsa:2048 -out cacert.pem -outform PEM -days 1825            

This step requires the user to set a password, so keep in mind.

The above steps generate a CA self-signed root certificate and an RSA public / private key pair. The format of the certificate is PEM and the validity period is 1825 days.

/myCA/cacert.pem: CA root certificate /
myCA / private / cakey.pem: CA private key

Generate the server configuration file exampleserver.cnf:

vim ~/myCA/exampleserver.cnf

The content of the exampleserver.cnf file is as follows:

#
# exampleserver.cnf
#

[ req ]
prompt             = no
distinguished_name = server_distinguished_name

[ server_distinguished_name ]
commonName              = localhost          
stateOrProvinceName     = JS                 
countryName             = CN                 
emailAddress            = XXXX@XXX.com       
organizationName        = XXX                 
organizationalUnitName  = XXX                 

Generate server certificate and key:

export OPENSSL_CONF=~/myCA/exampleserver.cnf  
openssl req -newkey rsa:1024 -keyout tempkey.pem -keyform PEM -out tempreq.pem -outform PEM

Similarly, a password needs to be set.

After that, there are 2 kinds of operations on the temporary key, choose one of them:
1. Convert the temporary private key to an unencrypted key, that is, the key is not encrypted:

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

Require passphrase.

2. If you want to keep the key encrypted, rename it directly:

mv tempkey.pem server_key.pem

The difference between the two is that the second type needs to enter the password of the private key when the server starts, otherwise the server will fail to start, but the second type is more secure than the first type and can better protect the key.

Sign the server certificate with a CA key:

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

Delete temporary certificates and keys:

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

The self-signed server certificate and key pair are now generated:

  • server_crt.pem: server certificate file
  • server_key.pem: server key file

The following uses LAMP to build a website for verification

Configure httpd (Apache)

Step 1: Install the Apache service program (the package name of the Apache service is called httpd)

yum install httpd -y

Step two: Add Apache service to boot

systemctl start httpd
systemctl enable httpd

Step 3: Open the browser and test 127.0.0.1, you can see the default home page

httpd main directory:

  • Service directory: / etc / httpd
  • Main configuration directory: /etc/httpd/conf/httpd.conf
  • Website data directory: / var / www / html
  • Access log: / var / log / httpd / access_log
  • Error log: / var / log / httpd / error_log

Configure php7

1.Installation source

Installing php72w needs to configure additional yum source, otherwise it will give an error and cannot find related packages.

The yum source address of the higher version of PHP has two parts, one of which is epel-release and the other from webtatic. If you skip the epel-release and install webtatic, there will be errors.

The commands required for installation are:

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

You can also choose the following command, which has the same effect:

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

2.Clear historical version

In order to prevent PHP conflicts on CentOS, it is better to execute this command first:

yum -y remove php*

3.Install the expansion pack

In fact, there are many corresponding extension libraries in it. Be sure to pay attention to the two packages of cli and fpm. Other related packages need to be seen:

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

Since MySQL will be used later, the mysql package is also needed.

More full version:

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

Configure MySQL

MariaDB is installed by default in CentOS, which is a branch of MySQL. However, you still need to install MySQL in the system for your needs, and you can directly overwrite MariaDB after installation.
Install directly if the network environment allows:

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 is large If the download is slow, you can download it from the domestic mirror source:
http://mirrors.ustc.edu.cn/mysql-ftp/Downloads/
After downloading, decompress it to the file directory in the figure:

pay attention to the file permissions And then install:

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

mysql has an initial default password, use the following command to find it:

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

Enter the initial password, and you cannot do anything at this time, because MySQL must change the password by default to operate the database.
change Password:

mysql -uroot -p
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new passwords';

If the setting of the new password is too simple, an error will be reported. The reason is that MySQL has a password setting specification, which is specifically related to the value of validate_password_policy. You can try a long password with a case and an underscore first.

MySQL full initial password rules view

SHOW VARIABLES LIKE 'validate_password%';

Can be modified by the following command:

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

You can reset the simple password later.

Configure SSL

ssl requires the following modules:

modify ssl.conf:

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

 

Modify DocumentRoot to your own web directory and change the certificate key source to self-built CA:
How_to_Self-built_CA_certificate_and_build_https_server_5.png

Web configuration

Copy the required website folder to the / var / www / html / directory
Modify the website file name in the /etc/httpd/conf/httpd.conf file:

the database required to create your own website:

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 to view the current web page:

setenforce  0
sudo systemctl restart httpd

Close selinux first, otherwise an error will be reported, and the certificate password (the one on the website, not the CA) will be verified before the service starts.

Currently it is an ordinary http connection because the self-built CA is not imported into the browser.

Browser import certificate

Because the website’s certificate is signed by a self-built CA, the browser does not trust it, so you need to manually import the CA certificate.

Take chrome as an example: Settings-> Advanced-> Privacy Settings and Security-> Manage Certificates

You can view the certificate details and import the self-built CA certificate.

Because the domain name set when the website certificate was previously configured is localhost, you need to use the localhost domain name for https Connected, cannot use 127.0.0.1.

A green lock appears in the access status of the address bar, and https is successfully established.