C语言实现一个简单的TLS server和client

2023-06-16  本文已影响0人  CodingCode

参考:https://wiki.openssl.org/index.php/Simple_TLS_Server

  1. sslserver.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

int create_socket(int port) {
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        perror("Unable to create socket");
        return -1;
    }

    if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("Unable to bind");
        close(sock);
        return -1;
    }

    if (listen(sock, 1) < 0) {
        perror("Unable to listen");
        close(sock);
        return -1;
    }

    return sock;
}

SSL_CTX *create_context()
{
    const SSL_METHOD *method;
    SSL_CTX *ctx;

    SSL_library_init();
    OpenSSL_add_all_algorithms();  /* Load cryptos, et.al. */
    SSL_load_error_strings();   /* Bring in and register error messages */

    method = TLSv1_2_server_method();
    ctx = SSL_CTX_new(method);
    if (ctx == NULL) {
        perror("Unable to create SSL context");
        ERR_print_errors_fp(stderr);
        return NULL;
    }

    /* Set the key and cert */
    if (SSL_CTX_use_certificate_file(ctx, "/path/to/cert.pem", SSL_FILETYPE_PEM) <= 0) {
        ERR_print_errors_fp(stderr);
        SSL_CTX_free(ctx);
        return NULL;
    }

    if (SSL_CTX_use_PrivateKey_file(ctx, "/path/to/key.pem", SSL_FILETYPE_PEM) <= 0 ) {
        ERR_print_errors_fp(stderr);
        SSL_CTX_free(ctx);
        return NULL;
    }

    return ctx;
}

int main(int argc, char **argv)
{
    SSL_CTX *ctx = create_context();
    if (ctx == NULL) {
        ERR_print_errors_fp(stderr);
        return 1;
    }

    int sock = create_socket(8888);
    if (sock < 0 ) {
        return 1;
    }

    printf("Start to accept client request\n");
    while(1) {
        struct sockaddr_in addr;
        unsigned int len = sizeof(addr);
        SSL *ssl;

        int fd = accept(sock, (struct sockaddr*)&addr, &len);
        if (fd < 0) {
            perror("Unable to accept");
            return 1;
        }

        printf("A client was accept\n");
        ssl = SSL_new(ctx);
        SSL_set_fd(ssl, fd);

        if (SSL_accept(ssl) <= 0) {
            ERR_print_errors_fp(stderr);
            SSL_shutdown(ssl);
            SSL_free(ssl);                  /* release connection state */
            close(fd);                      /* close socket */
            SSL_CTX_free(ctx);              /* release context */
            return 1;
        }

        SSL_write(ssl, "rely", strlen("reply"));

        SSL_shutdown(ssl);
        SSL_free(ssl);
        close(fd);
    }

    close(sock);
    SSL_CTX_free(ctx);
}
  1. sslclient.c
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <resolv.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

int create_socket(const char *hostname, int port) {
    struct sockaddr_in server;
    server.sin_addr.s_addr = inet_addr(hostname);
    server.sin_family = AF_INET;
    server.sin_port = htons(port);

    int sock= socket(AF_INET, SOCK_STREAM , 0);
    if (sock < 0) {
        perror("Unable to create socket");
        return -1;
    }

    if (connect(sock, (struct sockaddr *)&server , sizeof(server)) < 0) {
        perror("Unable to connect to");
        close(sock);
        return -1;
    }

    return sock;
}

int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
{
    char    buf[256];
    X509   *err_cert;
    int     err_num, err_depth;
    SSL    *ssl;

    err_num   = X509_STORE_CTX_get_error(ctx);
    err_depth = X509_STORE_CTX_get_error_depth(ctx);
    err_cert  = X509_STORE_CTX_get_current_cert(ctx);

    ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
    if (!preverify_ok) {
        X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);

        if (err_num == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) {
            X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
            printf("self-signed certificates in chain (%s)\n", buf);
            preverify_ok = 1;   // ignore this error
        } else if (err_num == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT) {
            X509_NAME_oneline(X509_get_issuer_name(err_cert), buf, 256);
            printf("cannnot get issuer name (%s)\n", buf);
        } else {
            printf("error=%d, depth=%d, content=(%s)(%s)\n", err_num, err_depth, X509_verify_cert_error_string(err_num), buf);
        }
    }

    return preverify_ok;
}

SSL_CTX *create_context(void)
{
    const SSL_METHOD *method;
    SSL_CTX *ctx;

    SSL_library_init();
    OpenSSL_add_all_algorithms();  /* Load cryptos, et.al. */
    SSL_load_error_strings();   /* Bring in and register error messages */

    method = TLSv1_2_client_method();  /* Create new client-method instance */
    ctx = SSL_CTX_new(method);   /* Create new context */
    if (ctx == NULL)
    {
        perror("Unable to create SSL context");
        ERR_print_errors_fp(stderr);
        return NULL;
    }

    /* Set the key and cert */
    if (SSL_CTX_load_verify_locations(ctx, "certs/ca-1.pem", NULL) <= 0) {
        ERR_print_errors_fp(stderr);
        SSL_CTX_free(ctx);
        return NULL;
    }

    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback);

    return ctx;
}

void ShowCerts(SSL* ssl)
{
    X509 *cert;
    char *line;
    cert = SSL_get_peer_certificate(ssl); /* get the server's certificate */
    if ( cert != NULL )
    {
        printf("Server certificates:\n");
        line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
        printf("Subject: %s\n", line);
        free(line);       /* free the malloc'ed string */
        line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
        printf("Issuer: %s\n", line);
        free(line);       /* free the malloc'ed string */
        X509_free(cert);     /* free the malloc'ed certificate copy */
    }
    else
        printf("Info: No client certificates configured.\n");
}

int main(int count, char *strings[])
{

    SSL_CTX *ctx = create_context();
    if (ctx == NULL) {
        ERR_print_errors_fp(stderr);
        return 1;
    }

    int sock = create_socket("<hostname>", 8888);
    if (sock < 0 ) {
        return 1;
    }

    SSL *ssl = SSL_new(ctx);            /* create new SSL connection state */
    SSL_set_fd(ssl, sock);              /* attach the socket descriptor */

    if (SSL_connect(ssl) == -1) {       /* perform the connection */
        ERR_print_errors_fp(stderr);
        close(sock);                        /* close socket */
        SSL_free(ssl);                  /* release connection state */
        SSL_CTX_free(ctx);              /* release context */
        return 1;
    }

    printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
    ShowCerts(ssl);                                 /* get any certs */

    SSL_write(ssl, "msg", strlen("msg"));                   /* encrypt & send message */

    char buffer[1024]={'\0'};
    int size = SSL_read(ssl, buffer, sizeof(buffer));       /* get reply & decrypt */
    printf("Received: len=%d:[%s]\n", size, buffer);

    SSL_shutdown(ssl);
    SSL_free(ssl);          /* release connection state */
    close(sock);                /* close socket */
    SSL_CTX_free(ctx);      /* release context */
    return 0;
}
  1. 编译
gcc -Wall -o sslclient sslclient.c -L/usr/lib64 -lssl -lcrypto
gcc -Wall -o sslserver sslserver.c -L/usr/lib64 -lssl -lcrypto
上一篇下一篇

猜你喜欢

热点阅读