stunnel

stunnel is a tool that allows you to encrypt arbitrary TCP connections inside SSL/TLS. It’s often used to add SSL encryption to services that don’t natively support it.

Usage

Usage: stunnel <config_file>

Configuration

KeyDescription
pidPath to store the PID file for the stunnel process
foregroundRun stunnel in the foreground (yes or no)
debugDebug level (0–7), higher means more verbose logging
outputPath to log file for stunnel output
certPath to SSL certificate file (usually .pem)
keyPath to SSL private key file (if separate from cert)
CAfilePath to trusted CA certificates for client certificate verification
verifyVerification level of the peer certificate (0 to 3)
clientyes if stunnel runs in client mode, otherwise server mode
delayDelay SSL handshake until the first byte is sent (yes/no)
socketLow-level socket options (e.g., linger = yes)
setuidDrop privileges to this user after startup
setgidDrop privileges to this group after startup

Service-level (per-tunnel) keys:

KeyDescription
acceptLocal port or IP:port where stunnel listens for connections
connectRemote host:port where stunnel forwards connections
delayDelay SSL handshake on this service
verifyPeer certificate verification level for this service
protocolProtocol name (e.g., smtp, pop3) for logging and detection
clientClient mode for this service (overrides global client if set)
TIMEOUTcloseTimeout in seconds for SSL connection closing

Examples

Simple SSL Tunnel

Suppose you have a local IMAP server running on port 143 (unencrypted). You want to expose it securely on port 993 (IMAPS).

stunnel.conf:

; Service-level configuration
[imaps]
accept = 993
connect = 143

Client Mode: Tunnel a Client Connection Over SSL

Imagine you have a client program that only supports plaintext connections, but the server requires SSL.

You can run stunnel in client mode to wrap your connection.

Example: Connect to a secure SMTP server on port 465

stunnel.conf:

client = yes
 
[smtp-tls-wrapper]
accept = 127.0.0.1:2525
connect = smtp.example.com:465

Run stunnel, then configure your mail client to connect to localhost:2525. stunnel will encrypt the traffic and send it securely to smtp.example.com:465.

Redirect HTTP Traffic to HTTPS Locally

If you want to secure an HTTP service without native HTTPS support:

[https]
accept = 8443
connect = 8080
cert = /etc/stunnel/stunnel.pem
  • The service runs unencrypted on port 8080.
  • Clients connect securely on port 8443.

Extended Example

pid = /var/run/stunnel.pid
foreground = yes
debug = 7
output = /var/log/stunnel.log
 
[secure_service]
accept = 443
connect = 80
cert = /etc/stunnel/stunnel.pem
key = /etc/stunnel/stunnel.key