Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk12 min

How to Set Up an SSL Tunnel with stunnel on Ubuntu

A practical Ubuntu guide to installing stunnel4, choosing client or server mode, configuring certificates and identity checks, enabling mutual TLS, validating handshakes, and fixing common startup and verification failures.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Install Ubuntu’s stunnel4 package, decide whether the tunnel will carry local plaintext to a remote TLS server or terminate inbound TLS for a plaintext service, then configure certificates and identity checks for that direction. A secure client tunnel normally needs verifyChain = yes, a trusted CA bundle, and checkHost or checkIP; a server tunnel needs a certificate chain and matching private key. The steps below show both designs, safe validation, systemd operation, mutual TLS, and fixes for the certificate errors that most often cause a tunnel to fail.

What stunnel does

stunnel is a TLS wrapper for an existing TCP or UDP service. It does not replace the application protocol and it does not turn an arbitrary program into a complete HTTPS server. Instead, it accepts a connection on one side, performs TLS where configured, and forwards the resulting application traffic to another endpoint.

As an Amazon Associate I earn from qualifying purchases.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

There are two useful directions:

  • Client mode: a local application speaks plaintext to stunnel; stunnel creates a TLS connection to a remote server. This is useful when an old client cannot negotiate TLS itself.
  • Server mode: a remote client makes a TLS connection to stunnel; stunnel decrypts it and forwards cleartext to an application on the same Ubuntu host or on another trusted endpoint.

The encrypted hop protects traffic only between the two tunnel endpoints. In server mode, the connection from stunnel to the application is plaintext unless that application or a second tunnel provides encryption. In client mode, the local listener receives plaintext, so it should normally be reachable only through loopback.

Choose the tunnel direction before editing files

Decision point Client mode Server mode
Traffic flow Local plaintext application to a remote TLS service Inbound TLS connection to a local or trusted plaintext service
Certificate responsibility Trust and verify the remote server certificate Present a certificate chain and matching private key to connecting clients
Typical listener 127.0.0.1:8080 A reachable address such as 0.0.0.0:8443, if public exposure is intended
Identity checks CA chain plus hostname or IP validation; SNI may also be required Client validation is optional for one-way TLS and required for mutual TLS
Plaintext exposure Local application traffic before encryption Traffic between stunnel and the backend service

Use client mode when the remote endpoint already provides TLS and your local software does not. Use server mode when you need a TLS front end for an existing service. If both sides must authenticate one another, configure mutual TLS rather than relying on encryption alone.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Install stunnel4 on Ubuntu

Ubuntu distributes stunnel in the Universe repository under the package name stunnel4. Update the package index and install it:

sudo apt update
sudo apt install stunnel4

Check the installed build before using a directive in production. The first command reports the stunnel and linked OpenSSL versions; the second lists compile-time options supported by that build.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
stunnel -version
stunnel -options

The package includes the executables /usr/bin/stunnel and /usr/bin/stunnel4, a default file at /etc/default/stunnel4, documentation under /etc/stunnel, and systemd units including stunnel.target and the [email protected] template. Exact service-manager behavior can differ between Ubuntu releases, so inspect the units installed on your system before enabling a long-running instance.

Prepare certificates, names, and permissions

Public certificates for a server tunnel

A publicly reachable server should use a certificate issued by a trusted certificate authority, commonly obtained and renewed through an ACME client. The certificate file configured with cert must contain the leaf certificate followed by any required intermediate certificates. The private key configured with key must match that leaf certificate.

Put certificates and keys in a directory readable by the account that loads them, but do not make the key world-readable. A typical key protection setup is:

sudo chown root:root /etc/stunnel/private/server.key
sudo chmod 600 /etc/stunnel/private/server.key

If your service manager runs stunnel as a dedicated account, that account must be able to read the key at startup. Granting broad permissions is not a substitute for fixing the service account or file ownership.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Self-signed certificates for development

For short-lived testing, you can create a self-signed certificate with a Subject Alternative Name for the DNS name or IP address used by clients. Every client must explicitly trust that certificate or its issuing test CA. Turning off verification is not a safe replacement: it allows an attacker who can intercept the connection to impersonate the server.

Names, addresses, and SNI

Decide which name clients will verify. A DNS name should be present in the certificate’s Subject Alternative Name field. If the remote service hosts several TLS sites on one address, send the expected name with sni = server.example.com. SNI selects a certificate; it does not prove that the selected certificate belongs to the intended host. Keep the separate identity check with checkHost or checkIP.

Configure client mode: local plaintext to remote TLS

Client mode is appropriate when a local program connects to a simple TCP port but the destination requires TLS. Create a configuration such as /etc/stunnel/client.conf:

foreground = yes

[remote-service]
client = yes
accept = 127.0.0.1:8080
connect = server.example.com:8443
verifyChain = yes
CAfile = /etc/ssl/certs/ca-certificates.crt
checkHost = server.example.com
sni = server.example.com
sslVersionMin = TLSv1.2

Understand each client directive

  • client = yes tells stunnel that the local side is plaintext and the outbound side is TLS.
  • accept = 127.0.0.1:8080 creates the local listener. Binding to loopback prevents other machines from injecting plaintext unless you deliberately choose a broader address.
  • connect = server.example.com:8443 identifies the remote TLS endpoint. Use the port actually published by that service.
  • verifyChain = yes requires a certificate chain that leads to a trusted authority.
  • CAfile = /etc/ssl/certs/ca-certificates.crt points at Ubuntu’s system CA bundle. Use another CA file when the service uses a private certificate authority.
  • checkHost = server.example.com verifies that the certificate identity matches the DNS name. Use checkIP when the service is intentionally addressed by an IP and the certificate contains that IP.
  • sni = server.example.com sends the TLS server-name indication needed by many name-based services.
  • sslVersionMin = TLSv1.2 prevents negotiation of older protocol versions when the installed build supports this option.
  • foreground = yes keeps the process attached to the terminal, which is useful for the first test and for seeing immediate errors.

Point the application at stunnel

Change the local application’s destination from the remote host and port to 127.0.0.1:8080. The application now sends its normal plaintext protocol to stunnel; stunnel creates the protected connection to server.example.com:8443. Do not configure the application to perform a second TLS handshake on this listener unless you intentionally need nested TLS.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test the client configuration

Start the configuration directly while diagnosing it:

sudo stunnel /etc/stunnel/client.conf

In another terminal, confirm that the listener exists:

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
ss -ltnp | grep 8080

Then exercise the local application or a protocol-appropriate test client against port 8080. A successful TCP listener proves only that stunnel opened the local socket; the first real request is what tests DNS resolution, the remote handshake, certificate validation, and application compatibility.

Configure server mode: inbound TLS to a plaintext service

Use server mode when clients should connect securely to Ubuntu while the backend service remains unchanged. The backend must already be listening on its cleartext address, for example 127.0.0.1:8080. Create a file such as /etc/stunnel/server.conf:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
foreground = yes

[web]
accept = 0.0.0.0:8443
connect = 127.0.0.1:8080
cert = /etc/stunnel/fullchain.pem
key = /etc/stunnel/private/server.key
sslVersionMin = TLSv1.2

How the server settings work

  • accept = 0.0.0.0:8443 listens on every IPv4 interface. Replace it with a specific address when the service must not be reachable on all interfaces; open the firewall only for the intended TLS port.
  • connect = 127.0.0.1:8080 forwards decrypted traffic to the backend. Use a remote trusted address only when that network path is controlled and its exposure is understood.
  • cert points to the certificate chain presented to clients. Include the leaf first and the required intermediates after it.
  • key points to the corresponding private key. The key must be readable by the account that starts stunnel and should remain mode 600 where possible.
  • sslVersionMin = TLSv1.2 sets a minimum protocol version on builds that support the directive.

Clients must use the DNS name or IP address covered by the certificate. If the certificate is for service.example.com, connecting by an unrelated name will correctly fail identity validation even when the server is reachable.

Check the server handshake independently

From a client that can reach the listener, inspect the certificate and negotiated protocol with:

openssl s_client -connect server.example.com:8443 -servername server.example.com

The -servername value should match the name clients are expected to use. This command is useful for spotting a missing intermediate, an unexpected certificate, or a listener that is not actually speaking TLS. It does not replace application-level testing.

Add mutual TLS when clients must authenticate

One-way TLS authenticates the server to the client. Mutual TLS adds a client certificate, allowing the server to reject clients that do not possess a certificate issued by a trusted client CA.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

On the server service, add the CA that issues client certificates:

verifyChain = yes
CAfile = /etc/stunnel/client-ca.pem

In stunnel’s authentication model, verifyChain = yes implies requireCert = yes; a connecting client must therefore present a certificate that chains to the configured CA. Keep the server certificate and key settings as shown in the server example.

The client needs its own certificate and private key while continuing to validate the server:

cert = /etc/stunnel/client.pem
key = /etc/stunnel/private/client.key
verifyChain = yes
CAfile = /etc/ssl/certs/ca-certificates.crt
checkHost = server.example.com
sni = server.example.com

Use separate client certificates when you need to revoke one device or service without replacing every credential. Protect client keys with the same restrictive permissions used for server keys. Mutual TLS authenticates the certificate holder; authorization decisions such as which account may use which application still belong in the backend service or an access-control layer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Run stunnel under systemd and reload safely

Use foreground mode for first-run diagnostics

Keep foreground = yes while checking syntax, permissions, name resolution, and the first handshake. Start the file directly, watch the terminal for errors, and stop it with the normal interrupt signal after testing. This avoids hiding an immediate startup failure inside a service manager.

Identify the installed units

Inspect the units supplied by your Ubuntu release:

systemctl list-unit-files 'stunnel*'
systemctl cat stunnel.target
systemctl cat [email protected]

The package provides a target and a template unit, but the exact enablement workflow and configuration directory are release-specific. Place configuration files in the location documented by the installed package and use the unit name shown on your host. A template instance commonly maps a name such as client to a corresponding configuration file, but confirm that mapping with systemctl cat before relying on it.

Inspect status and logs after starting

Start the package-provided instance or target using the service-manager interface documented on your system, then inspect its status and journal immediately:

sudo systemctl status [email protected]
sudo journalctl -u [email protected] -b

Substitute the actual instance name if your configuration uses another one. If your release exposes a different unit, query that unit instead of forcing the example name. The official package units may provide their own reload action; use that action for configuration changes so the manager can preserve the expected process and privilege model.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Harden the tunnel before exposing it

  • Limit plaintext listeners: keep client-mode accept on 127.0.0.1 unless remote plaintext access is a deliberate requirement. A listener on all interfaces can expose credentials and application data before encryption.
  • Enforce modern TLS: set sslVersionMin = TLSv1.2 where the installed build supports it, and verify the option with stunnel -options.
  • Validate identity, not only encryption: client mode should combine verifyChain, a trusted CAfile, and checkHost or checkIP. SNI by itself is not authentication.
  • Protect private keys: restrict ownership and mode, and ensure backups do not become more widely readable than the live key.
  • Drop privileges after binding: where appropriate, bind listening sockets first and then use setuid and setgid, or the isolation controls supplied by the service manager. Test that the reduced account can still read certificates, CA files, logs, and any required runtime files.
  • Treat chroot as a complete filesystem: if you configure a chroot, copy or mount every required item inside it, including the configuration, certificate and key files, CA bundle, resolver files, logs, PID files, and other runtime dependencies. A chroot that omits DNS or trust files can look like a TLS failure even though the files exist outside the jail.
  • Restrict network access: allow the public TLS port only from intended networks and keep the backend port inaccessible from untrusted interfaces.
  • Plan certificate renewal: renew the certificate before expiry, preserve the full chain order, and perform a controlled reload followed by a fresh handshake test.

Troubleshoot common failures

The connection works only when verification is disabled

This almost always means the trust or identity configuration is incomplete. Check the failure in this order:

  1. Confirm that CAfile exists and is readable by the account running stunnel. Ubuntu’s usual public CA bundle is /etc/ssl/certs/ca-certificates.crt.
  2. Compare the hostname in checkHost with the name in the certificate’s Subject Alternative Name. Do not use a convenient alias unless that alias is actually listed.
  3. Check that the server sends its leaf certificate plus every required intermediate. A server can appear valid in a browser that has cached intermediates while failing for stunnel.
  4. Verify the SNI value. A wrong or missing sni can cause a name-based service to return a different certificate.
  5. Use openssl s_client against the same host, port, and SNI name to inspect the chain and negotiated certificate.

Do not solve these errors by setting verification off. That removes the protection against an impersonated endpoint.

stunnel cannot start

Check the installed build and logs first:

stunnel -version
stunnel -options
sudo systemctl status [email protected]
sudo journalctl -u [email protected] -b

Typical causes are an unreadable private key, a certificate file without the required chain, an address already in use, or a directive unsupported by the installed build. Confirm the paths, ownership, and modes; test whether another process already owns the configured accept port; and remove or replace options that do not appear in stunnel -options.

The listener opens but requests fail

  • In client mode, verify that the local application is connecting to the stunnel accept address rather than directly to the remote TLS port.
  • Confirm that the remote connect name resolves from the stunnel host and that firewalls permit the outbound port.
  • Ensure the backend in server mode is actually listening on the configured connect address and speaks the expected plaintext protocol.
  • Check for protocol mismatches. A TLS client sent to a plaintext backend, or plaintext sent to a service expecting TLS, will produce an apparently connected but unusable session.

The port is already in use

Find the owning process before changing the configuration:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ss -ltnp | grep 8443

Stop the conflicting service or choose an unused listener port, then update clients and firewall rules consistently. Do not run two stunnel instances against the same address and port.

Clients reject a server certificate

Check that the client uses the certificate’s actual DNS name or IP, that the server presents the complete chain, and that the private key matches the leaf certificate. A self-signed development certificate must be installed in the client’s trust store explicitly. Replacing it with a public certificate authority certificate is usually simpler for a service accessed by unrelated clients.

Deployment choices at a glance

Scenario Recommended arrangement Important controls
Legacy local client, remote provider requires TLS Client mode with loopback accept and remote connect verifyChain, CA bundle, checkHost or checkIP, and SNI when required
Existing Ubuntu service needs an encrypted public entry point Server mode terminating TLS and forwarding to a protected backend address Trusted full certificate chain, matching key, TLS 1.2 minimum, firewall restrictions
Only approved machines may connect Server mode with mutual TLS Client-issuing CA, verifyChain = yes, client certificates and protected keys
Short-lived lab test Self-signed certificate with a correct SAN and explicit client trust Limit exposure, keep verification enabled, replace the test certificate before production

Final validation checklist

  1. Install stunnel4 and record the output of stunnel -version and stunnel -options.
  2. Choose client or server mode based on which side is plaintext.
  3. Bind client listeners to loopback unless broader access is intentional.
  4. Use a complete server certificate chain and a matching, tightly protected private key.
  5. In client mode, configure chain validation and hostname or IP identity checks; add SNI only when the remote service needs it.
  6. If using mutual TLS, configure the client CA on the server and a client certificate and key on each client.
  7. Run the configuration in the foreground, confirm the listener with ss, and inspect a handshake with openssl s_client.
  8. Move to the installed systemd unit, inspect its journal, and use its documented reload mechanism for renewals or configuration changes.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.