Standard library · Network

sshd

An SSH server with password and public key login, commands, a shell and SFTP, written in Salam.

import sshd

This package is an SSH server written in Salam. Make a configuration, add the users who may log in, call Listen and then Serve, and an ordinary client such as OpenSSH, or the ssh package, can connect, log in with a password or a public key, run a command, open an interactive shell, and move files with SFTP. It needs no OpenSSH on the machine.

The package holds the settings and the lifecycle of the server: what to listen on, who may log in, and what a logged-in user may do. The protocol itself, the key exchange, the encryption and the channels, is done by the same ssh package that the client uses.

What to know before you use it:

  • Set a host key. A client trusts the server by its host key. With host_key_file the server reads an OpenSSH private key and keeps the same identity on every start. Without it the key is made from host_seed, and when that is empty from a seed built into the library, which everyone can read, so never leave both empty on a real server.
  • Public keys are listed in authorized_keys_file, one OpenSSH public key per line. Unlike sshd the list is shared: a key in it can log in as any user in users, so give each service its own server and file. Turn off allow_password when keys are enough.
  • Each user has a name, a password and a home. The home is a directory below root, and it is where that user's SFTP session starts. All users share the same root.
  • Switches for what is allowed: allow_exec for single commands, allow_shell for an interactive shell and allow_sftp for file transfer. allow_shell alone does not stop a user from running commands, because a command is run through /bin/sh -c with the rights of the server process; switch allow_exec off too for a server that only moves files.
  • Connections are served one after another, and the first read of a connection has no time limit, so a client that connects and stays silent, or a long session, holds up everyone behind it. Put the server behind something that limits idle connections if strangers can reach it.
  • Listen is false when host_key_file names a file that is not there, so a typo does not quietly give you the built-in key. A file that exists but cannot be parsed still falls back to the seed.

Users, defaults and a free port

NewConfig listens on all interfaces on port 22 and allows passwords, public keys, commands, a shell and SFTP. AddUser appends a user; when the home is left out it is /. Binding to port 0 on the loopback address lets the system pick a port and Port tells you which, so this program runs without a network and without clashing with a real SSH server.

sshd-users.salam
import sshd

func main:
    mut cfg := sshd.NewConfig()
    println cfg.port, cfg.allow_password, cfg.allow_publickey, cfg.allow_shell
    cfg.host = "127.0.0.1"
    cfg.port = 0
    cfg.root = "/srv/files"
    cfg.allow_shell = false
    cfg.banner = "authorized use only"
    sshd.AddUser(cfg, "alice", "s3cret", "/home/alice")
    sshd.AddUser(cfg, "bob", "hunter2")
    each u in cfg.users:
        println u.name, u.home
    end
    mut srv := sshd.New(cfg)
    println sshd.Listen(srv)
    println sshd.Port(srv) > 0
    sshd.Close(srv)
    println sshd.DefaultVersion
end
Output22 true true true alice /home/alice bob / true true SSH-2.0-SalamServer_1.0

Listen returns false when the port cannot be bound, and Close frees it again. The banner is shown to a client before it logs in.

Serve files with public keys only

A server that exists to receive deployments should not accept passwords and should not hand out a shell. The example reads its identity from a host key file, lets in only the keys listed in authorized_keys_file, and does not give out a shell. Commands stay allowed there; switch allow_exec off as well for a server that only moves files.

sshd-serve.salam
import sshd

func main:
    mut cfg := sshd.NewConfig()
    cfg.port = 2222
    cfg.root = "/srv/files"
    cfg.host_key_file = "/etc/deploy/host_key"
    cfg.authorized_keys_file = "/etc/deploy/authorized_keys"
    cfg.allow_password = false
    cfg.allow_shell = false
    sshd.AddUser(cfg, "deploy", "", "/")
    mut srv := sshd.New(cfg)
    if not sshd.Listen(srv):
        println "cannot listen on port", cfg.port
        ret 1
    end
    println "ssh server on port", sshd.Port(srv)
    sshd.Serve(srv)
    ret 0
end

This runs until it is stopped, so it is only checked here. Connect to it with ssh -p 2222 deploy@host or with ssh.Connect and a key.

Which function for which job

JobUse
Start from the defaultsNewConfig, then set the fields of Config
Allow a user to log inAddUser
Create the serverNew
Open the portListen, then Port to read it
Serve clients until stoppedServe
Serve exactly one connectionServeOnce
Stop and free the portClose

Types

User

struct User
A user who may log in to the server.
NameTypeDescription
namestr = ""The login name.
passwordstr = ""The password for a password login.
homestr = "/"The directory below the root where the user starts; / by default.
sshd-Config.salam
import sshd

func main:
    mut cfg := sshd.NewConfig()
    println cfg.host, cfg.port, cfg.server_version == sshd.DefaultVersion
    println cfg.allow_password, cfg.allow_publickey
    println cfg.allow_exec, cfg.allow_shell, cfg.allow_sftp
    println cfg.root, cfg.banner == "", cfg.users.len()
    sshd.AddUser(cfg, "alice", "s3cret", "/home/alice")
    sshd.AddUser(cfg, "bob", "hunter2")
    each u in cfg.users:
        println u.name, u.password.len(), u.home
    end
end
Output0.0.0.0 22 true true true true true true . true 0 alice 6 /home/alice bob 7 /

Config

struct Config
The configuration of an SSH server.
NameTypeDescription
hoststr = "0.0.0.0"The address to listen on; 0.0.0.0 means every interface.
portint = 22The port to listen on; 22 by default, and 0 lets the system choose one.
server_versionstrThe version string sent to clients; DefaultVersion by default.
host_key_filestr = ""The path of the OpenSSH private key that is the identity of the server.
authorized_keys_filestr = ""The path of the file with the public keys that may log in.
allow_passwordbool = trueLets users log in with a password; on by default.
allow_publickeybool = trueLets users log in with a public key; on by default.
rootstr = "."The directory that clients see as / in SFTP and as the working directory of commands.
allow_execbool = trueLets users run a single command.
allow_shellbool = trueLets users open an interactive shell.
allow_sftpbool = trueLets users transfer files with SFTP.
bannerstr = ""A message shown to the client before it logs in; empty means none.
host_seedstr = ""The text the host key is made from when there is no host_key_file; the same text gives the same key.
usersVectorThe users who may log in.

The example for this item is shown with the ones above: sshd-Config.salam

Server

struct Server
A running SSH server.
NameTypeDescription
configConfigThe configuration the server was made with; after Listen its port is the real one.
listenertcp.ServerThe listening socket.
runningbool = falseTrue after Listen worked and until Close is called.
sshd-Server.salam
import sshd

func main:
    mut cfg := sshd.NewConfig()
    cfg.host = "127.0.0.1"
    cfg.port = 0
    mut srv := sshd.New(cfg)
    println srv.running
    println sshd.Listen(srv), srv.running
    println sshd.Port(srv) > 0
    sshd.Close(srv)
    println srv.running
end
Outputfalse true true true false

Constants and variables

DefaultVersion

const DefaultVersion: str = "SSH-2.0-SalamServer_1.0"
The version string the server announces to clients, SSH-2.0-SalamServer_1.0.

The example for this item is shown with the ones above: sshd-Config.salam

Functions

NewConfig

func NewConfig(): Config
A configuration with the defaults: port 22, passwords and keys allowed, commands, shell and SFTP allowed, no users.

The example for this item is shown with the ones above: sshd-Config.salam

New

func New(cfg: Config): Server
Makes a server from a configuration. It does not listen yet.

The example for this item is shown with the ones above: sshd-Server.salam

Listen

func Listen(srv &: Server): bool
Opens the port; false when it could not be bound.

The example for this item is shown with the ones above: sshd-Server.salam

Close

func Close(srv &: Server)
Stops the server and frees the port.

The example for this item is shown with the ones above: sshd-Server.salam

Port

func Port(srv: Server): int
The port the server listens on; the real one after Listen when the configuration said 0.

The example for this item is shown with the ones above: sshd-Server.salam

AddUser

func AddUser(cfg &: Config, name: str, password: str, home: str = "/")
Adds a user with a name, a password and a home directory.

The example for this item is shown with the ones above: sshd-Config.salam

ServeOnce

func ServeOnce(srv &: Server): bool
Waits for one connection and serves it until the client leaves; false when the port is not open or the accept failed.
sshd-Serve.salam
import sshd
import env

func main:
    mut cfg := sshd.NewConfig()
    cfg.port = 2222
    cfg.root = "/srv/files"
    cfg.host = "127.0.0.1"
    cfg.allow_shell = false
    cfg.allow_exec = false
    sshd.AddUser(cfg, "alice", env.Get("SSH_PASSWORD"))
    mut srv := sshd.New(cfg)
    if not sshd.Listen(srv):
        ret 1
    end
    handled := sshd.ServeOnce(srv)
    println "one connection served:", handled
    sshd.Serve(srv)
    sshd.Close(srv)
    ret 0
end

Serve

func Serve(srv &: Server)
Serves connections one after another until running becomes false or the listener fails.

The example for this item is shown with the ones above: sshd-Serve.salam