SSL Discovery 01

Source: Internet
Author: User
Tags ssl connection htons

1. About OpenSSL

The OpenSSL project is a collaborative development of a robust, commercial-grade, full-featured, open-source toolkit that implements Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols as well as a fully-powerful universal cryptographic library.

2. Using SSL for Secure IO

Using SSL for Secure IO is not very different from the original Socketio communication, but only adds the SSL portion.

The basic procedures for SSL Io are described below:

Client process

①//SSL Initialization
②//socket,connect,
③//ssl, establishing an SSL connection, Ssl_connect (SSL)
④//ssl_write,ssl_read
⑤//Close Operation Ssl_shutdown,ssl_free,close,ssl_ctx_free

Service-side process

①//SSL Initialization
②//socket,bind,listen,accept
③//ssl, establishing an SSL connection, ssl_accept (SSL)
④//ssl_write,ssl_read
⑤//Close Operation Ssl_shutdown,ssl_free,close,ssl_ctx_free

3. Using bio for Secure IO

Bio is an abstract package of OpenSSL for IO types, including: memory, files, logs, standard input and output,sockets(tcp/udp), encryption and decryption, Abstract and SSL channels, and so on. Openssl BIO hides the underlying implementation details for the user through a callback function . The use of bio makes the code much simpler.

The basic process of using bio for secure IO

①//SSL initialization
②//Loading the Trusted authentication library (note: If the certificate is not loaded or failed, the certificates are invalid but can continue to connect (the client controls whether to continue communicating))
Ssl_ctx_load_verify_locations (CTX, "Truststore.pem", NULL)
③//Establishing a connection
Bio = Bio_new_ssl_connect (CTX);
/* Set the SSL_MODE_AUTO_RETRY flag */
Bio_get_ssl (bio, &SSL);
Ssl_set_mode (SSL, ssl_mode_auto_retry);
/* Create and setup the connection * *
Bio_set_conn_hostname (bio, "Www.baidu.com:https");
④//bio_write,bio_read
⑤//Close Operation Bio_free_all,ssl_ctx_free

Comparing the use of SSL for IO with the use of bio for communication, it is found that using bio is more concise and convenient, it is recommended to use bio more.

4. Error detection during operation of SSL

OpenSSL throws some kind of error. First, you need to get the error code itself; Err_get_error can accomplish this task;

then, you need to convert the error code to an error string, which is a pointer to a permanent string loaded into memory by ssl_load_error_strings or err_load_bio_strings. Method: Err_reason_error_string,err_lib_error_string,err_func_error_string.

You can also dump the error: ERR_PRINT_ERRORS_FP (FILE *); Err_print_errors (BIO *);


The code is as follows:

A.client_ssl.cpp

int main (int argc, char * *argv) {int sockfd, len;struct sockaddr_in Dest;char buffer[maxbuf + 1]; Ssl_ctx * CTX; SSL * ssl;/* SSL Library initialization */ssl_library_init ();/* Load all SSL algorithms */openssl_add_all_algorithms ();/* Load all SSL error messages */ssl_load_error_  Strings ()/* Generates a SSL_CTX in SSL V2 and V3 standard compatibility mode, i.e. SSL Content Text */ctx = ssl_ctx_new (Sslv23_client_method ()); if (CTX = = NULL) {ERR_PRINT_ERRORS_FP (stdout); exit (1);} /* Create a socket for TCP communication */if ((SOCKFD = socket (af_inet, sock_stream, 0)) < 0) {perror ("socket"); exit (errno);} printf ("Socket created\n");/* Initializes the server-side (offset) address and port information */bzero (&dest, sizeof (dest));d est.sin_family = af_inet;// Set the port for the connection Dest.sin_port = Htons (12345);//Set the IP address of the connection char *addr = "127.0.0.1";//115.239.210.27 baidu//char *addr2 = " 115.239.210.27 "; if (Inet_aton (addr, (struct in_addr *) &dest.sin_addr.s_addr) = = 0) {perror (argv[0]); exit (errno);} printf ("Address created\n");/* Connect Server */if (Connect (SOCKFD, (struct sockaddr *) &dest, sizeof (dest))! = 0) {perror ("Con Nect "); exit (errno);} printf ("Server ConnectEd\n ");/* Generates a new SSL */ssl = Ssl_new (CTX) based on CTX;/* joins the newly connected socket to SSL */SSL_SET_FD (SSL, SOCKFD);//---------------------- ------------------------------------///* Load The Trust store *///if (! Ssl_ctx_load_verify_locations (CTX, "Truststore.pem", NULL)) {//fprintf (stderr, "Error Loading Trust store\n");//err_ PRINT_ERRORS_FP (stderr);//ssl_ctx_free (CTX);//return 0;//}//--------------------------------------------------- -------/* Establish SSL Connection */if (Ssl_connect (SSL) = =-1) {ERR_PRINT_ERRORS_FP (stderr);} else {printf ("Connected with%s encryption \ n ", Ssl_get_cipher (SSL)); Showcerts (SSL);} /* Receive messages from each other, receive up to maxbuf bytes */bzero (buffer, maxbuf + 1);/* Receive server Messages */len = Ssl_read (SSL, buffer, maxbuf); if (len > 0) {printf ("received message succeeded: '%s ',%d bytes of data \ n", buffer, Len);} else {printf ("Message received failed! The error code is%d and the error message is '%s ' \ n ', errno, Strerror (errno)); goto finish;} Bzero (buffer, maxbuf + 1); strcpy (buffer, "from Client->server");/* Send message to server */len = Ssl_write (SSL, buffer, strlen ( buffer); if (Len < 0) {printf ("message '%s ' send failed! Error code is%d, the error message is '%s ' \ n ', buffer, Errno,strerror (errno));} else {printf ("message '%s ' was sent successfully with%d bytes sent!") \ n ", buffer, Len);} finish:/* Close Connection */ssl_shutdown (SSL); Ssl_free (SSL); close (SOCKFD); Ssl_ctx_free (CTX); return 0;}

B.server_ssl.cpp

int main (int argc, char * *argv) {int sockfd, new_fd;socklen_t len;struct sockaddr_in my_addr, their_addr;unsigned int MYP ORT, Lisnum;char Buf[maxbuf + 1]; SSL_CTX * ctx;//Specifies the listening port MyPort = 12345;//Maximum client connections Lisnum = 10;/* SSL Library initialization */ssl_library_init ();/* Load all SSL algorithms */openssl_add_ All_algorithms ();/* Loads all SSL error messages */ssl_load_error_strings ();/* generates a SSL_CTX in SSL V2 and V3 standard compatibility, i.e. SSL Content Text */CTX = SSL _ctx_new (Sslv23_server_method ());/* You can also use Sslv2_server_method () or Sslv3_server_method () to represent V2 or V3 standard */if (CTX = = NULL) { ERR_PRINT_ERRORS_FP (stdout); exit (1);} /* Load the user's digital certificate, which is used to send to the client. The certificate contains a public key */if (Ssl_ctx_use_certificate_file (CTX, "/home/shuyan/workspace/openssl_server/files/cacert.pem", SSL_ FILETYPE_PEM) <= 0) {ERR_PRINT_ERRORS_FP (stdout); exit (1);} /* Load User private key */if (Ssl_ctx_use_privatekey_file (CTX, "/home/shuyan/workspace/openssl_server/files/privkey.pem", SSL_ FILETYPE_PEM) <= 0) {ERR_PRINT_ERRORS_FP (stdout); exit (1);} /* Check that the user's private key is correct */if (! Ssl_ctx_check_private_key (CTX)) {ERR_PRINT_ERRORS_FP (stdout); exit(1);} /* Open a Socket monitor */if ((SOCKFD = socket (pf_inet, sock_stream, 0)) = =-1) {perror ("socket"); exit (1);} else {printf ("Socket C Reated\n ");} Bzero (&my_addr, sizeof (MY_ADDR)); my_addr.sin_family = Pf_inet;my_addr.sin_port = Htons (myport); my_addr.sin_ ADDR.S_ADDR = Inaddr_any;if (Bind (SOCKFD, (struct sockaddr *) &my_addr, sizeof (struct sockaddr)) = =-1) {perror ("bind" ); exit (1);} else {printf ("binded\n");} if (Listen (SOCKFD, lisnum) = =-1) {perror ("listen"); exit (1);} else {printf ("Begin listen\n");} while (1) {SSL * Ssl;len = sizeof (struct sockaddr);/* Wait for client to connect */if ((new_fd = accept (SOCKFD, struct sockaddr *) &thei R_ADDR, &len)) = =-1) {perror ("accept"); exit (errno);} else {printf ("Server:got connection from%s, port%d, socket%d\ N ", Inet_ntoa (THEIR_ADDR.SIN_ADDR), Ntohs (Their_addr.sin_port), NEW_FD);} /* Generate a new SSL */ssl = Ssl_new (CTX) based on CTX;/* Connect the user's socket to SSL */SSL_SET_FD (SSL, NEW_FD);/* Establish SSL connection */if (Ssl_accept (SSL) = =-1) {perror ("accept"); Close (new_fd); break;} /* Start processing on each new connectionData Transceiver */bzero (BUF, Maxbuf + 1), strcpy (buf, "server->client");/* Send message to client */len = Ssl_write (SSL, buf, strlen (BUF)); if (len <= 0) {printf ("message '%s ' send failed! The error code is%d and the error message is '%s ' \ n ', buf, Errno,strerror (errno)); goto finish;} else {printf ("message '%s ' was sent successfully with%d bytes sent!") \ n ", buf, Len);} Bzero (buf, maxbuf + 1);/* Receive client messages */len = Ssl_read (SSL, buf, Maxbuf), if (Len > 0) {printf ("Receive Message succeeded: '%s ',%d bytes of data \ n", b UF, Len);} else {printf ("Message received failed! The error code is%d and the error message is '%s ' \ n ', errno, Strerror (errno)); Err_reason_error_string (Err_get_error ());} /* Handle the end of data transmission on each new connection */finish:/* close SSL connection */ssl_shutdown (SSL);/* Release SSL */ssl_free (SSL);/* Close Socket */close (NEW_FD);} /* Turn off the listening socket */close (SOCKFD);/* Release CTX */ssl_ctx_free (CTX); return 0;}

C.client_bio.cpp

int main () {bio * BIO; SSL * SSL; SSL_CTX * Ctx;int P;char * request = "get/http/1.1\x0d\x0ahost:www.baidu.com\x0d\x0a\x43onnection:close\x0d\x0a\x0d\ x0a "; Char r[1024];/* SSL Library initialization */ssl_library_init ();/* load All SSL algorithm */openssl_add_all_algorithms ();/* Load all SSL error messages */ssl_ Load_error_strings ();/* Set up the library */err_load_bio_strings ();/* Set up the SSL context */ctx = Ssl_ctx_new (sslv23_c Lient_method ());/* Load the Trust store */if (! Ssl_ctx_load_verify_locations (CTX, "Truststore.pem", NULL)) {fprintf (stderr, "Error Loading Trust store\n"); ERR_PRINT_ERRORS_FP (stderr); Ssl_ctx_free (CTX); return 0;}  /* Setup the connection */bio = Bio_new_ssl_connect (CTX); bio = Bio_new (Bio_s_socket ());/* Set the SSL_MODE_AUTO_RETRY flag */bio_get_ssl (BIO, &AMP;SSL); Ssl_set_mode (SSL, ssl_mode_auto_retry);/* Create and setup the connection */bio_set_conn_hostname (BIO, "www.baidu.com: HTTPS "), if (Bio_do_connect (BIO) <= 0) {fprintf (stderr," Error attempting to connect\n "); ERR_PRINT_ERRORS_FP (stderr); Bio_free_all(bio); Ssl_ctx_free (CTX); return 0;}  /* Check the Certificate */if (Ssl_get_verify_result (SSL)! = X509_V_OK) {fprintf (stderr, "Certificate Verification Error: %i\n ", Ssl_get_verify_result (SSL)); Bio_free_all (bio); Ssl_ctx_free (CTX); return 0;} Showcerts (SSL);/* Send the request */bio_write (BIO, request, strlen (request));/* Read in the response */for (;;) {p = bio_read (BIO, R, 1023), if (P <= 0) Break;r[p] = 0;printf ("%s", r);} /* Close the connection and free the context */bio_free_all (BIO); Ssl_ctx_free (CTX); return 0;}





SSL Discovery 01

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.