Networking in C · intermediate · ~15 min
Understand TLS structure; integrate via a vetted library.
TLS (Transport Layer Security) sits between TCP and HTTP. It encrypts and protects the data your application sends.
It works in two stages:
The golden rule: never implement TLS yourself. Always integrate a vetted library.
TLS is everywhere:
To read a C program that uses TLS, you need to recognize the common OpenSSL idioms. That is the goal of this lesson.
Record layer. Each record has a 5-byte header (type, version, length) followed by the encrypted payload. The type says what the record carries: handshake, application data, or alert.
Handshake. The opening exchange that sets up the secure channel:
TLS 1.3 collapses this into a single round trip (1-RTT).
Certificate verification. In OpenSSL, verification is OFF by default for clients. Always turn it on. Always validate the hostname too.
SNI (Server Name Indication). The client tells the server which hostname it wants during the handshake. This lets one IP address host many certificates.
Pentester mindset. Misconfigured TLS shows up as mixed content, downgrade attacks, expired certificates, or weak ciphers. Defenders audit for these with tools like testssl.sh, sslyze, and nmap --script ssl-enum-ciphers.
Defensive coding habit. A safe client configuration:
SSL_VERIFY_PEERRefuse anything weaker.
Reference: https://www.openssl.org/docs/man3.0/man7/ssl.html.
Note OpenSSL's unusual convention: most functions return 1 on success.
TLS is the layer between TCP and your application. It provides three things:
You will never write a TLS stack from scratch. Instead, you wrap a vetted library such as OpenSSL, BoringSSL, mbedTLS, or GnuTLS.
This lesson explains the structure of TLS so you can read someone else's TLS code with confidence.
SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
SSL_CTX_load_verify_locations(ctx, NULL, "/etc/ssl/certs");
SSL *ssl = SSL_new(ctx);
SSL_set_fd(ssl, tcp_fd);
SSL_connect(ssl);
SSL_write(ssl, msg, mlen);
See the OpenSSL wiki.openssl.org 'Simple_TLS_Server' / 'Simple_TLS_Client' pages.
openssl s_client -connect example.com:443 -showcerts is the gold-standard troubleshooting tool. It shows the full handshake and certificate chain.tcpdump captures the record layer on the wire for deeper analysis.OpenSSL has its own cleanup rules:
SSL_free and SSL_CTX_free to release objects.curlSimple_TLS_Client example from start to finish.SSL_VERIFY_PEER does.testssl.sh example.com and read through the report.