SSL Secure socket layer

Secure Socket Layer (SSL) is developed by Netspace to ensure the integrity and confidentiality of data transmission over the Internet. The current version is 3.0. The latest version is TLS1.2 Transport Layer Security. The difference between TLS and SSL is so small that it can be understood as a newer version of SSL.

Communication process

SSL is located at the transport layer between the application layer and the network layer. Application data is encrypted through SSL in the transport layer, and its own SSL header is added to transmit the encrypted data to the network layer.

With OpenSSL, you can issue your own certificate. After you have the certificate and private key, secure SSL communication can be carried out.

The interface flow provided by SSL is shown below:

  1. The browser of the client sends the version number of SSL protocol, encryption algorithm, random number, and other information needed for communication to the server.

  2. Server according to the client transfer the information to choose both sides support SSL protocol version, the information such as the encryption algorithm and its certificate to the client (this step may pose a safety hazard, such as forge the client supports SSL protocol version is too low, may cause the server to SSL version of the security level is too low for communication).

  3. The client uses the information sent from the server to verify the validity of the server, including whether the certificate has expired, whether the certificate issuer is reliable, whether the public key matches, and whether the domain name on the certificate matches the server. If the authentication fails, the communication is disconnected. If the authentication succeeds, the communication continues.

  4. The client randomly generates a symmetric password for communication encryption, encrypts it through the public key, and then sends the encrypted pre-master password to the server.

  5. The server decrypts its private key to obtain the pre-master password used for communication encryption, and then uses a series of algorithms to generate the master communication password (the client will also generate the same master communication password through the same way);

  6. The client sends a message to the server, indicating that the subsequent data communication will use the master password of encryption and decryption as the master communication password generated in the previous stage, and at the same time notifying the server that the handshake process is over.

  7. The server also wants the client to specify the communication password and confirm that the handshake is complete.

  8. The handshake is complete. When SSL secure channel data communication starts, the client and server use the same symmetric key for data communication and verify communication integrity.

After SSL communication is established

As can be seen from the above communication process, after SSL communication is established, the communication process is very secure, which can effectively prevent the problems of man-in-the-middle attack and carrier hijacking, and the confidentiality and integrity of communication data are effectively guaranteed. So for SSL related attack must be based on the session initialization phase, for example, in the middle attack must be implemented in the process of the establishment, the session that attackers forge a certificate in the process of communication, the client claimed that the certificate is to fool the client server certificate, and make its trust the certificate, and use the certificate to communicate, In this way, the information of user communication will be monitored by the third, and the confidentiality and integrity of communication will be destroyed. This attack way also has certain limitation, when use forged certificates to establish communication, generally the attacker will not get through official certification certificate, the client browser will be sent a warning, remind communication is not safe, you can refer to browser prompts when accessing a 12306 (12306 is used for its self-built certificate issued by the ca, The certificate is not authenticated by an official authority, so the browser will assume that the certificate is not secure by default and raise an alarm).

Bypassing browser validation

Although verifying the validity of the certificate through the browser can increase the cost of the attack, in some special cases, the browser verification can be bypassed. For example, when using packet capture tools such as Fiddler and Charles, their certificates can be manually added as trusted certificates, so we don’t receive browser alerts when using these tools to perform a local logical analysis of the relevant system. And browser validation is only for Web applications, mobile and other non-Web applications can only be protected in other ways, one common way to do this is using SSL Pinning, or certificate binding.

There are three protocols in how SSL works

1. Handshake protocol

The handshake protocol is the first subprotocol that clients and servers use to communicate with SSL connections. The handshake protocol consists of a series of messages between the client and the server. The most complex protocol in SSL is the handshake protocol. The protocol allows servers and clients to authenticate with each other, negotiate encryption and MAC algorithms, and secure SSL keys to protect data sent in SSL records. Use the handshake protocol before the application’s data transfer.

2. Recording protocol

After a successful handshake between the client and server, the logging protocol is used, that is, the client and server authenticate each other and determine the algorithm used for the exchange of secure information, and the SSL logging protocol is entered, which provides two service connections for SSL:

  • (1) Confidentiality: use the secret key defined by the handshake protocol
  • (2) Integrity: The handshake protocol defines the MAC to ensure message integrity

3. Alarm protocol

When the client and server discover an error, they send an alert message to each other. If a fatal error occurs, the algorithm immediately closes the SSL connection, and both parties delete the associated session number, secret, and key first. Each alert message has two bytes. The first byte indicates the error type, 1 if it is an alert, and 2 if it is a fatal error. The second byte specifies the actual error type.

Certificate workflow

  1. A user connects to your Web site, which is protected by a server certificate. (This can be done by checking to see if the URL begins with “HTTPS :” or if the browser will provide you with relevant information.)

  2. Your server responds and automatically sends your site’s digital certificate to the user to authenticate your site.

  3. The user’s web browser program generates a unique “session key code” that encrypts all communication with the site.

  4. The user’s browser encrypts the chat key with the site’s public key so that only your site can read the chat key.

Server-side code implementation

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define CERT_FILE  "./cert/server.crt"
#define KEY_FILE   "./cert/server.key"

int main(int argc, char *argv[]) {
    SSL_CTX *ctx;
    int listenfd, newfd;
    struct sockaddr_in ser.cli;

    SSL_library_init(a);OpenSSL_add_all_algorithms(a);SSL_load_error_strings(a);if (NULL == (ctx = SSL_CTX_new(SSLv23_server_method()))) {
        ERR_print_errors_fp(stderr);
        exit(- 1);
    }
    if (SSL_CTX_use_certificate_file(ctx, CERT_FILE, SSL_FILETYPE_PEM) ! =1) {
        ERR_print_errors_fp(stderr);
        exit(- 1);
    }
    if (SSL_CTX_use_PrivateKey_file(ctx, KEY_FILE, SSL_FILETYPE_PEM) ! =1) {
        ERR_print_errors_fp(stderr);
        exit(- 1);
    }
    if (1! =SSL_CTX_check_private_key(ctx)) {
        ERR_print_errors_fp(stderr);
        exit(- 1);
    }

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&ser, 0.sizeof(ser));
    ser.sin_family = AF_INET;
    ser.sin_addr.s_addr = htonl(INADDR_ANY);
    ser.sin_port = htons(atoi(argv[1]));

    if (- 1= =bind(listenfd, (struct sockaddr*)&ser, sizeof(struct sockaddr))) {
        perror("bind");
        exit(- 1);
    }
    if (- 1= =listen(listenfd, 5)) {
        perror("listen");
        exit(- 1);
    }

    for (;;) {
        socklen_t size = sizeof(struct sockaddr);
        if (- 1 == (newfd = accept(listenfd, (struct sockaddr*)&cli, &size))) {
            perror("accept");
            break;
        }
        SSL *ssl = SSL_new(ctx);
        SSL_set_fd(ssl, newfd);
        if (- 1= =SSL_accept(ssl)) {
            ERR_print_errors_fp(stderr);
            close(newfd);
            break;
        }
        {
            char buf[256]; int len;
            while ((len = SSL_read(ssl, buf, sizeof(buf))) > 0) {
                buf[len] = 0;
                printf("%s", buf);
                SSL_write(ssl, buf, len);
            }
            SSL_shutdown(ssl);
            SSL_free(ssl);
            close(newfd); }}SSL_CTX_free(ctx);
    close(listenfd);
    return 0;
}
Copy the code

Customer service code implementation

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
int main(int argc, char *argv[]) {
    SSL_CTX *ctx;
    int sockfd;
    struct sockaddr_in ser;

    SSL_library_init(a);OpenSSL_add_all_algorithms(a);SSL_load_error_strings(a);if (NULL == (ctx = SSL_CTX_new(SSLv23_client_method()))) {
        ERR_print_errors_fp(stderr);
        exit(- 1);
    }

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&ser, 0.sizeof(ser));
    ser.sin_family = AF_INET;
    ser.sin_addr.s_addr = inet_addr(argv[1]);
    ser.sin_port = htons(atoi(argv[2]));
    if (- 1= =connect(sockfd, (struct sockaddr*)&ser, sizeof(ser))) {
        perror("connect");
        exit(- 1);
    }
    SSL *ssl = SSL_new(ctx);
    SSL_set_fd(ssl, sockfd);
    if (- 1= =SSL_connect(ssl)) {
        ERR_print_errors_fp(stderr);
        exit(- 1);
    }
    {
        char buf[256]; int len;
        freopen("/etc/passwd"."r", stdin);
        while (fgets(buf, sizeof(buf), stdin)) {
            len = strlen(buf);
            if (SSL_write(ssl, buf, len) > 0) {
                buf[0] = 0;
                len = SSL_read(ssl, buf, sizeof(buf));
                if (len > 0) {
                    buf[len] = 0;
                    printf("%s", buf); }}}SSL_shutdown(ssl);
        SSL_free(ssl);
    }
    close(sockfd);
    SSL_CTX_free(ctx);
    return 0;
}
Copy the code

Resource portal

  • L Focus on [be a gentle program ape] public account
  • In [do a tender program ape] public account background reply [Python information] [2020 autumn recruit] can get the corresponding surprise oh!
  • Build their own blog address: nightmare back to life blog

“❤️ thank you.”

  • Click “like” to support it, so that more people can see this content.
  • Share your thoughts with me in the comments section, and record your thought process in the comments section