SELINA.ai
Sign in

How Does SFTP Work: The Protocol Demystified for Developers

SFTP gets treated like a checkbox. You need to move files, someone says "use SFTP," and you do. But if you've ever wondered how does SFTP work at the protocol level, or why it exists alongside FTP and FTPS as a seemingly redundant option, this is the piece that answers those questions with actual specifics. No vendor positioning. No glossy diagrams. Just the protocol, its mechanics, and the operational details that matter when you're building systems that move sensitive data.

Key Takeaways

What Is SFTP, and Why Isn't It Just FTP with Encryption?

SFTP stands for SSH File Transfer Protocol. The name is misleading because it implies a relationship to FTP. There is none. SFTP is a file-transfer subsystem built directly into SSH, sharing no code, no architecture, and no lineage with the original File Transfer Protocol. FTP dates to 1971. SFTP was designed by Tatu Ylönen in 1997 and later standardized as an open protocol under the IETF.

The distinction matters for one structural reason: FTP uses two channels. A control channel (port 21) carries commands. A separate data channel (port 20, or a negotiated ephemeral port in passive mode) carries file contents. Neither channel is encrypted by default. FTPS bolts TLS onto this dual-channel architecture, which means you now have two encrypted channels, multiple ports to open in your firewall, and the general headache of negotiating passive-mode port ranges through NAT.

SFTP consolidates everything into one port. Commands, file data, directory listings, permission changes: all of it flows through a single SSH connection on port 22. One port. One encrypted tunnel. One set of firewall rules. This is why SFTP won.

How Does the SSH Handshake Establish an SFTP Session?

The SFTP session begins before any file operation happens, with the SSH transport layer doing its work. Here is the sequence, stripped to essentials:

  1. TCP connection. The client opens a TCP socket to port 22 (or whatever port the SSH daemon is configured on) on the server.
  2. Protocol version exchange. Both sides announce their SSH protocol version. This is plaintext, and it is the last plaintext you will see in the session.
  3. Key exchange. Client and server negotiate a key-exchange algorithm (historically Diffie-Hellman or ECDH, and now increasingly hybrid post-quantum methods). They derive a shared session key without ever transmitting it. This session key encrypts everything that follows.
  4. Server authentication. The server presents its host key. The client checks this against its known_hosts file or trust store. If it does not match, you get the "REMOTE HOST IDENTIFICATION HAS CHANGED" warning that most people have dismissed at least once. Do not dismiss it.
  5. Client authentication. The client proves its identity. This is typically a password or, preferably, a public-key challenge-response. More on this below.
  6. Channel request. Once authenticated, the client requests an SSH subsystem channel specifically for SFTP. The server spawns its SFTP subsystem process (usually sftp-server or internal-sftp in OpenSSH configurations).
  7. SFTP protocol negotiation. Inside the encrypted channel, client and server exchange SFTP version numbers and agree on capabilities.

After step 7, you have a working SFTP session. Every subsequent operation (directory listing, file upload, permission change) is a binary message sent inside the encrypted SSH channel.

How Does SFTP Authentication Actually Work?

SFTP inherits SSH's authentication mechanisms directly. The two you will encounter in practice are password authentication and public-key authentication.

Password authentication is straightforward. The client sends a username and password inside the already-encrypted SSH channel. The server checks them against its user database (local accounts, LDAP, PAM, whatever). The password is never transmitted in the clear because the SSH tunnel is already established before authentication begins. But the password still exists as a string that a human chose, reused, or wrote on a sticky note. This is the weak link.

Public-key authentication eliminates the password entirely. You generate a keypair: a private key that stays on the client machine, and a public key that gets installed on the server (typically in ~/.ssh/authorized_keys). During authentication, the server sends a challenge, the client signs it with the private key, and the server verifies the signature against the stored public key. The private key never leaves the client machine. There is no shared secret to intercept, phish, or brute-force.

For automated systems (CI/CD pipelines, backup scripts, data ingestion jobs), public-key auth is the only defensible choice. Passwords in scripts are credentials waiting to be leaked.

What About Certificate-Based and Multi-Factor Auth?

OpenSSH also supports certificate-based authentication, where a certificate authority signs user keys and the server trusts the CA rather than individual public keys. This scales better in large organizations because you revoke at the CA level instead of editing authorized_keys files on every server. Keyboard-interactive authentication can layer in TOTP or other second factors, though this is less common in automated SFTP workflows for obvious reasons.

What Happens During an SFTP File Transfer?

Once the session is established, the SFTP protocol operates as a request-response binary protocol. This is different from FTP's text-based command model. Each operation is a numbered message type with a request ID, and the server responds with a corresponding status or data message.

A file upload (put) works like this:

  1. The client sends an SSH_FXP_OPEN request with the remote filename and flags indicating write/create/truncate.
  2. The server responds with an SSH_FXP_HANDLE containing a file handle (an opaque byte string).
  3. The client sends one or more SSH_FXP_WRITE requests, each containing the handle, an offset, and a chunk of data.
  4. The server acknowledges each write with an SSH_FXP_STATUS.
  5. The client sends SSH_FXP_CLOSE to finalize the file.

Downloads (get) reverse the flow: SSH_FXP_OPEN with read flags, then repeated SSH_FXP_READ requests at successive offsets, until the server returns SSH_FXP_STATUS with an EOF indicator.

The offset-based read/write model is what gives SFTP native resume support for interrupted transfers. If a transfer dies midway, the client can reopen the file and start writing at the last confirmed offset. FTP has a REST command for this, but its behavior is less consistent across implementations.

What Other Operations Does the Protocol Support?

SFTP is not just put and get. The protocol supports full remote file management: creating and removing directories (SSH_FXP_MKDIR, SSH_FXP_RMDIR), renaming files (SSH_FXP_RENAME), reading and setting file attributes like permissions and timestamps (SSH_FXP_STAT, SSH_FXP_SETSTAT), and listing directory contents (SSH_FXP_READDIR). The command-line sftp client exposes these as familiar commands: ls, cd, rm, chmod, mkdir. The familiarity is cosmetic. Underneath, every command is a binary message inside an encrypted channel.

How Does SFTP Encryption Protect Data in Transit?

SFTP does not implement its own encryption. It delegates entirely to the SSH transport layer, which provides three protections simultaneously:

Confidentiality. The session key derived during key exchange encrypts all traffic with a symmetric cipher. Modern OpenSSH defaults to chacha20-poly1305@openssh.com or AES-256 in GCM mode. Every packet, whether it carries a directory listing or a gigabyte file chunk, is encrypted before it hits the wire.

Integrity. Each packet includes a MAC (message authentication code) or, in AEAD cipher modes, an authentication tag. If any bit is altered in transit, the receiving side detects it and drops the connection. There is no silent corruption.

Authentication. The server's host key and the client's credentials establish mutual trust. A man-in-the-middle cannot impersonate either side without possessing the correct private key.

Compare this to plain FTP, which moves data over two unencrypted channels. Credentials, filenames, and file contents are all visible to anyone with a packet capture on the network path. FTPS adds TLS, but the dual-channel architecture means you need to negotiate encryption separately for the control and data connections, and passive-mode data connections can be especially finicky behind firewalls.

Why Do SFTP Breaches Still Happen If the Protocol Is Encrypted?

Because the protocol's cryptography is not the failure point. Every significant SFTP-related breach in recent memory traces back to operational failures around the protocol, not weaknesses in the encryption itself.

In late 2025, a ransomware group compromised a corporate SFTP server run by a healthcare vendor, exfiltrating names, Social Security numbers, and medical record images. The roughly 3.39 GB of stolen data ended up on the dark web. The protocol did its job. The access controls around the protocol did not.

In May 2026, a bank's third-party document vendor had its SFTP server accessed without authorization, exposing customer tax forms and account numbers. Again: not a cipher break. An access management failure.

The pattern is consistent. Attackers actively scan for misconfigured file-transfer servers, looking for weak credentials, unrotated SSH keys, overly permissive access, or forgotten service accounts. The encryption is doing its job. The humans managing keys, credentials, and third-party access are not.

For context on the plaintext side: roughly 2.45 million FTP hosts observed in a recent Censys scan still lack encryption entirely. If you are reading this article, you probably are not running unencrypted FTP. But someone in your supply chain might be.

What Does Key Hygiene Look Like in Practice?

If encryption is not the weak point, key management is where you should focus. Here are the specific practices that matter:

Rotate SSH keys on a schedule. This sounds obvious, but in practice, most organizations have SSH keys that are older than some of their employees. Set a rotation cadence (90 days is reasonable for automated service keys) and enforce it.

Scope keys to minimum privilege. OpenSSH's authorized_keys file supports forced commands and restrictions. A key used by a backup script should be locked to a specific command (command="internal-sftp") and, ideally, chrooted to a specific directory. A key that can do anything on the server is a key that will eventually do something you did not intend.

Revoke immediately on personnel or vendor changes. When a contractor leaves or a vendor relationship ends, their SSH keys need to be removed from every server they had access to. Not next sprint. Now. Certificate-based SSH auth helps here because you revoke at the CA, but most shops are still managing individual authorized_keys files.

Audit what keys exist. This is the unglamorous part. Most organizations cannot tell you how many SSH keys are deployed across their infrastructure, who generated them, or what they grant access to. You cannot manage what you have not inventoried.

How Is Post-Quantum Cryptography Changing SFTP?

It is already in the stack. OpenSSH 10.4, released July 6, 2026, shipped experimental support for ML-DSA 44 and Ed25519 composite signatures. This builds on earlier work integrating a hybrid post-quantum key-exchange algorithm designed to protect session keys from future quantum decryption.

The threat model here is specific and worth understanding: "harvest now, decrypt later" attacks. A well-resourced adversary (read: nation-state) captures encrypted SSH traffic today and stores it. The data is gibberish now. But if a sufficiently capable quantum computer arrives in 10 or 15 years, those stored sessions could be decrypted retroactively. Every file you transferred, every command you ran.

For most developers moving application logs or deployment artifacts, this risk is abstract. For organizations transferring medical records, financial data, trade secrets, or (relevantly for us) AI training data over SFTP, the calculus is different. Data that is sensitive today will still be sensitive in 2040. The key exchange protecting it needs to survive that long.

The practical step: if you control your SSH infrastructure, track OpenSSH releases and plan to enable hybrid post-quantum key exchange as it stabilizes. The performance overhead is measurable but small. The risk it mitigates is not hypothetical; it is a known intelligence-collection pattern.

What Are the Recent SFTP-Specific Vulnerabilities Worth Knowing?

OpenSSH 10.4 fixed eight security weaknesses across the SSH client, server, and file-transfer utilities. Two are particularly relevant to SFTP users:

CVE-2026-59995 (SFTP) and CVE-2026-59996 (SCP) are path-manipulation bugs. A malicious server could redirect a downloaded file to an unintended location on the client's filesystem during a command like sftp server:/path .. Medium severity. Low likelihood in typical interactive use. But in CI/CD pipelines where an automated script fetches files from a remote endpoint and processes them, this class of bug can lead to arbitrary file overwrites.

Separately, CVE-2026-0968 was an out-of-bounds heap read in libssh, triggered when an SFTP client processed a malformed directory-listing response from a malicious server. The fix shipped with libssh 0.12.0 in February 2026. The severity is limited (it is a read, not a write, and requires connecting to a malicious server), but it is a useful reminder that SFTP client libraries, not just servers, are part of your attack surface.

The Automation Blind Spot

The 2026 OpenSSH patches also addressed a subtler issue: security-relevant flags placed late in sftp or scp command-line arguments could be silently dropped. If your deployment script constructs a long sftp command and appends security flags at the end, those flags might not take effect.

This is the kind of bug that never surfaces in interactive use. You type sftp with a few flags and it works. But when a CI/CD system builds the command string programmatically, concatenating paths and options, the argument ordering can silently degrade security posture. Teams treat SFTP as "solved" once the connection is encrypted. The automated invocation of the protocol is where subtle regressions hide.

When Should You Use SFTP vs. Other Transfer Methods?

SFTP is a strong default for file transfer between systems you control or semi-control. It is the right choice when:

SFTP is not the best choice when you need high-throughput parallel transfers of many small files (the request-response overhead per file adds up), when you are transferring to end users who need a browser-based experience, or when you are building an API-driven data pipeline where a REST endpoint or object-storage presigned URL would be more natural.

FTPS still exists and is still used, primarily in industries with regulatory requirements that specifically mention TLS (some PCI DSS interpretations, certain EDI trading-partner agreements). It is not wrong, but it is more complex to operate due to the multi-port architecture and certificate management overhead.

Plain FTP should not be used for anything. At all. If you encounter it in a vendor integration, push back.

How Do You Set Up SFTP Correctly on an OpenSSH Server?

The minimal secure configuration in sshd_config looks something like this:

Subsystem sftp internal-sftp

Match Group sftponly
 ChrootDirectory /data/%u
 ForceCommand internal-sftp
 AllowTcpForwarding no
 X11Forwarding no
 PasswordAuthentication no

Key decisions in this config:

internal-sftp instead of the external sftp-server binary. The internal subsystem runs in-process, which is required for chroot to work and reduces the attack surface slightly.

ChrootDirectory locks each user into their own directory tree. They cannot traverse upward to /etc/passwd or /var/log. The chroot directory must be owned by root and not writable by the user, which is a common source of "broken chroot" debugging sessions.

ForceCommand internal-sftp ensures that users in the sftponly group can only use SFTP. They cannot get a shell, run arbitrary commands, or use SSH tunneling. This is least-privilege applied at the protocol level.

PasswordAuthentication no for the matched group forces public-key auth. No passwords. No brute-force surface.

What Does This Mean for Moving Sensitive Data in AI Workflows?

If you are moving training data, model weights, evaluation datasets, or inference logs between systems, SFTP is a reasonable transport. The encryption is strong. The tooling is mature. The protocol is well understood.

But the protocol is the easy part. The hard part is managing the SSH keys that automated pipelines use, ensuring that vendor access to SFTP endpoints is scoped and revocable, and keeping your OpenSSH versions current so you pick up fixes like the path-manipulation bugs and the emerging post-quantum protections.

For file transfers where you want end-to-end encryption and do not want to manage SSH infrastructure yourself, we built SelinaSEND as a zero-knowledge alternative. Different tool, different use case. SFTP remains the right answer for server-to-server file movement where you control both endpoints.

The protocol is not the risk. The operations around it are.

If you want to see how we think about secure data handling more broadly: start a free 7-day trial, no card required.

Frequently Asked Questions

Is SFTP just FTP with encryption added?

No. SFTP is a completely separate protocol built as a subsystem of SSH, sharing no code or architecture with FTP. It runs everything over a single encrypted channel on port 22, unlike FTP's unencrypted dual-channel design.

How is an SFTP session established?

The client opens a TCP connection to port 22, and the SSH transport layer performs a protocol version exchange, key exchange to derive a shared session key, and server authentication via host key verification. After the client authenticates, it requests an SFTP subsystem channel and negotiates SFTP protocol versions, all inside the now-encrypted session.

What authentication methods does SFTP support?

SFTP inherits SSH's authentication methods, mainly passwords and public-key cryptography, with public-key preferred since the private key never leaves the client and there's no shared secret to intercept. OpenSSH also supports certificate-based authentication for easier revocation at scale, and keyboard-interactive methods can add multi-factor authentication.

How does an SFTP file transfer actually work under the hood?

SFTP uses a binary request-response protocol where operations like open, write, read, and close are numbered messages exchanged with the server, unlike FTP's text-based commands. This offset-based read/write model also enables native resume support for interrupted transfers.

Does SFTP's encryption make it immune to breaches?

No. The article notes that SFTP's cryptography itself is not what typically fails; credential mismanagement, poor key hygiene, and third-party access sprawl are the consistent root causes of real-world incidents.

Sources & References

Michael C.

Michael C.

Founder & Principal Engineer, Selina Labs

Michael builds Selina, a privacy-first AI that remembers you across conversations. He ships security-sensitive AI in production — real attacks, real fixes, measured in minutes and dollars — and writes about privacy, security, and LLMs from that seat. Top Rated Plus and expert-verified on Upwork.

Learn more about Selina.ai