Networking in C · intermediate · ~15 min

TLS — read about it; never write it

Understand TLS structure; integrate via a vetted library.

Overview

TLS layers between TCP and HTTP. Handshake establishes a shared secret via asymmetric crypto; record layer encrypts and MACs each chunk of payload. Never implement; always integrate.

Why it matters

Every HTTPS connection. Every modern protocol assumes TLS. Reading a TLS-using C program means knowing the OpenSSL idioms.

Core concepts

Record layer. 5-byte header (type, version, length) + encrypted payload. Type identifies handshake / application data / alert.

Handshake. ClientHello → ServerHello → certificate + key-exchange → Finished. TLS 1.3 collapses to 1-RTT.

Certificate verification. The default in OpenSSL is OFF for clients. Always turn it on. Always validate the hostname.

SNI. Server Name Indication — client tells the server which hostname it wants, so one IP can host many certs.

Pentester mindset. Misconfigured TLS = mixed-content, downgrade, expired certs, weak ciphers. Defenders use testssl.sh, sslyze, nmap --script ssl-enum-ciphers to audit.

Defensive coding habit. SSL_VERIFY_PEER + a real CA bundle + hostname validation + minimum TLS 1.2. Refuse anything below.

Syntax notes

See https://www.openssl.org/docs/man3.0/man7/ssl.html. Each function returns 1 on success in OpenSSL's quirky convention.

Lesson

TLS is the protocol between TCP and your application that gives you encryption, authentication, and integrity. You will never write a TLS stack from scratch. You'll wrap a vetted library (OpenSSL, BoringSSL, mbedTLS, GnuTLS). This lesson explains the structure so you can read someone else's TLS code.

Code examples

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);

Line by line

See the OpenSSL wiki.openssl.org 'Simple_TLS_Server' / 'Simple_TLS_Client' pages.

Common mistakes

  • Skipping certificate verification ('I'll add it later').

Debugging tips

openssl s_client -connect example.com:443 -showcerts is the gold-standard troubleshooter. tcpdump captures the record layer for analysis.

Memory safety

OpenSSL has its own memory hygiene rules. Always SSL_free and SSL_CTX_free. Always check return values for the 1/0/-1 contract.

Real-world uses

curl, every HTTPS client / server, every modern TCP protocol that needs auth + encryption.

Practice tasks

  1. Read the OpenSSL Simple_TLS_Client example end-to-end. 2. Explain what SSL_VERIFY_PEER does. 3. Run testssl.sh example.com and read the report.

Summary

Don't implement TLS. Integrate a vetted library. Verify certs. Validate hostname. Refuse weak protocols.

Practice with these exercises