Run as a user of its own: ports bound as root, then root given up

[general] user (and group): started as root, bbs serve reads the
configuration, binds every socket it listens on (the listeners, TCP and
unix; the HTTP API and metrics, FTP, NNTP, IRC, finger, gopher, binkp),
gives up root (setgroups to the user's groups, setgid, setuid) and
executes itself again, the same process (its PID, for systemd and
reload), the sockets handed down; each server's listen takes the one for
its address (internal/sockets).  Nothing is written as root: database,
logs, host keys, backups and a unix socket without socket_group are the
user's.

Other commands as root give root up first, so the database stays the
user's (but check and config; backup restore puts things back as root
and gives them, but the configuration, to the user).  System
configuration has Run as user and group.

TestRunAs (as root) serves a port under 1024 and a unix socket as
nobody, the same process through a reload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr
This commit is contained in:
Claude committed 2026-10-14 21:28:57 +00:00
1 parent 856e31f86f
commit e9fc5ed156
25 files changed
+714 -20

No files matched your search

+7
View File
@@ -17,6 +17,13 @@ sysop = Sysop
;postal_address = "1 Main St, Springfield"
;phone = "+1 555 0100 (300-33600), +1 555 0101 (V.92)"
;addresses = "telnet bbs.example.org, ssh bbs.example.org:2222, https://bbs.example.org/"
;; started as root, serve binds its ports (23, 79 ...) and sockets, then
; runs as this user (and its group, or group; with the user's other groups,
; for socket_group and docker): what it makes is that user's. Other bbs
; commands run as root become it too (but check, config, backup restore).
; Under systemd: no User= then. See docs/wiki/Running.md
;user = bbs
;group = bbs
; the database: SQLite's file, or a PostgreSQL, MySQL or MariaDB server (whose
; password then lives here: keep this file 0640). bbs db copy moves one
; into another. See docs/wiki/Databases.md
+4
View File
@@ -9,6 +9,10 @@ ExecStart=/usr/local/bin/bbs -config /etc/bbs/bbs.conf serve
ExecReload=/bin/kill -HUP $MAINPID
User=bbs
Group=bbs
# or: started as root, the BBS binds its ports and becomes [general] user
# itself (docs/wiki/Running.md): then no User= and Group= here, nor
# AmbientCapabilities, and RuntimeDirectory's directory is root's (put
# unix sockets where the user may write, or give them a socket_group)
# for [listen menu]'s socket_group = asterisk
SupplementaryGroups=asterisk
# for DOS doors in Docker (README, "Doors"): the docker group is as good as
+3
View File
@@ -40,6 +40,9 @@ func backupCmd(cfg *server.Config, path string, args []string) {
fatal(err)
}
to := backup.Targets{Config: path, Database: cfg.Database, Dirs: map[string]string{}}
if a := cfg.RunAs; a != nil && os.Geteuid() == 0 {
to.Owner, to.UID, to.GID = true, a.UID, a.GID
}
sources := append(server.Sources(cfg), server.Keys(cfg)...)
for _, s := range sources {
to.Dirs[s.Name] = s.Path
+8 -1
View File
@@ -6,6 +6,7 @@ import (
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
@@ -155,7 +156,13 @@ func configScreens(path string) {
if err != nil {
return nil, err
}
return server.NewBackups(ocfg, path, b).Run()
a, err := server.NewBackups(ocfg, path, b).Run()
if u := ocfg.RunAs; err == nil && u != nil && os.Geteuid() == 0 {
// made as root for a BBS that runs as its own user: its
os.Chown(filepath.Dir(a.Path), u.UID, u.GID)
os.Chown(a.Path, u.UID, u.GID)
}
return a, err
},
Backups: func() ([]backup.Archive, error) {
cfg, err := server.Load(path)
+45
View File
@@ -74,6 +74,7 @@ import (
"github.com/Neo-Desktop/bbs-sec/internal/qwknet"
"github.com/Neo-Desktop/bbs-sec/internal/script"
"github.com/Neo-Desktop/bbs-sec/internal/server"
"github.com/Neo-Desktop/bbs-sec/internal/sockets"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
@@ -166,6 +167,18 @@ func main() {
if len(args) > 0 {
cmd, args = args[0], args[1:]
}
if cfg.RunAs != nil && os.Geteuid() == 0 {
// what the BBS makes (the database, backups, keys) is its user's,
// not root's: serve gives up root itself, after binding its ports;
// check reads; a restore puts things back as root and gives them
// to the user
restore := cmd == "backup" && len(args) > 0 && args[0] == "restore"
if cmd != "serve" && cmd != "check" && !restore {
if err := sockets.Drop(cfg.RunAs); err != nil {
fatal(err)
}
}
}
switch cmd {
case "serve":
os.Exit(serve(cfg, *configPath))
@@ -339,6 +352,27 @@ func logger(spec string) (*log.Logger, error) {
}
func serve(cfg *server.Config, path string) int {
if a := cfg.RunAs; a != nil {
switch {
case os.Geteuid() == 0:
// the ports bound as root, then this program again as the user
socks, err := server.Bind(cfg)
if err != nil {
fmt.Fprintln(os.Stderr, "bbs:", err)
return 1
}
err = sockets.Become(a, socks)
fmt.Fprintf(os.Stderr, "bbs: becoming %s: %v\n", a.User, err)
return 1
case os.Geteuid() != a.UID:
fmt.Fprintf(os.Stderr, "bbs: user = %s, but started as uid %d (start it as root, or as %s)\n", a.User, os.Geteuid(), a.User)
return 1
}
}
if err := sockets.Inherit(); err != nil {
fmt.Fprintln(os.Stderr, "bbs:", err)
return 1
}
lg, err := logger(cfg.Log)
if err != nil {
fmt.Fprintln(os.Stderr, "bbs: log:", err)
@@ -528,6 +562,17 @@ func serve(cfg *server.Config, path string) int {
}
}()
}
go func() {
// sockets bound as root that no server took (the file changed
// between): closed, and said
time.Sleep(10 * time.Second)
for _, k := range sockets.Left() {
lg.Printf("a socket bound for %s was not taken: closed", k)
}
}()
if a := cfg.RunAs; a != nil {
lg.Printf("running as %s (uid %d, gid %d)", a.User, os.Getuid(), os.Getgid())
}
if err := srv.Run(ctx); err != nil {
lg.Printf("%v", err)
return 1
+155
View File
@@ -0,0 +1,155 @@
package main
import (
"bufio"
"fmt"
"net"
"os"
"os/exec"
"os/user"
"path/filepath"
"strings"
"sync"
"syscall"
"testing"
"time"
)
// TestRunAs: started as root with [general] user, serve binds its ports
// (one under 1024) and unix socket as root, then runs as the user, the
// same process; what it makes is the user's. Root only.
func TestRunAs(t *testing.T) {
if os.Geteuid() != 0 {
t.Skip("not root")
}
nobody, err := user.Lookup("nobody")
if err != nil {
t.Skip("no nobody")
}
port := 0
for p := 1000; p > 600; p-- {
if ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p)); err == nil {
ln.Close()
port = p
break
}
}
if port == 0 {
t.Skip("no free port under 1024")
}
// a directory nobody can reach (t.TempDir's parent may not be)
dir, err := os.MkdirTemp("/tmp", "bbs-runas-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
os.Chmod(dir, 0o755)
data := filepath.Join(dir, "data")
os.Mkdir(data, 0o700)
var uid, gid int
fmt.Sscan(nobody.Uid, &uid)
fmt.Sscan(nobody.Gid, &gid)
os.Chown(data, uid, gid)
exe := filepath.Join(dir, "bbs")
if out, err := exec.Command("go", "build", "-o", exe, ".").CombinedOutput(); err != nil {
t.Fatalf("build: %v\n%s", err, out)
}
conf := filepath.Join(dir, "bbs.conf")
sock := filepath.Join(data, "menu.sock")
os.WriteFile(conf, []byte(fmt.Sprintf(`[general]
name = RunAs BBS
user = nobody
database = %s
files_dir = %s
log = stderr
attempts = 1
[listen low]
type = raw
address = 127.0.0.1:%d
ansi = no
[listen menu]
type = raw
address = %s
ansi = no
`, filepath.Join(data, "bbs.db"), filepath.Join(data, "files"), port, sock)), 0o644)
// a command as root makes the database as the user
if out, err := exec.Command(exe, "-config", conf, "init").CombinedOutput(); err != nil {
t.Fatalf("init: %v\n%s", err, out)
}
if fi, err := os.Stat(filepath.Join(data, "bbs.db")); err != nil || fi.Sys().(*syscall.Stat_t).Uid != uint32(uid) {
t.Fatalf("the database is not nobody's: %v", err)
}
cmd := exec.Command(exe, "-config", conf, "serve")
log := &syncBuf{}
cmd.Stderr = log
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
defer func() {
cmd.Process.Signal(syscall.SIGTERM)
cmd.Wait()
if t.Failed() {
t.Log(log.String())
}
}()
var c net.Conn
for i := 0; i < 100; i++ {
if c, err = net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port)); err == nil {
break
}
time.Sleep(50 * time.Millisecond)
}
if err != nil {
t.Fatalf("port %d: %v", port, err)
}
c.SetDeadline(time.Now().Add(5 * time.Second))
r := bufio.NewReader(c)
var got string
for i := 0; i < 5 && !strings.Contains(got, "RunAs BBS"); i++ {
l, _ := r.ReadString('\n')
got += l
}
if !strings.Contains(got, "RunAs BBS") {
t.Errorf("banner %q", got)
}
c.Close()
u, err := net.Dial("unix", sock)
if err != nil {
t.Fatalf("socket: %v", err)
}
u.Close()
status, _ := os.ReadFile(fmt.Sprintf("/proc/%d/status", cmd.Process.Pid))
if !strings.Contains(string(status), fmt.Sprintf("Uid:\t%d\t%d\t%d\t%d", uid, uid, uid, uid)) {
t.Errorf("not nobody:\n%s", status)
}
if fi, err := os.Stat(sock); err != nil || fi.Sys().(*syscall.Stat_t).Uid != uint32(uid) {
t.Errorf("the socket is not nobody's")
}
// a reload, the same process
cmd.Process.Signal(syscall.SIGHUP)
time.Sleep(300 * time.Millisecond)
if !strings.Contains(log.String(), "reload: ") {
t.Errorf("no reload")
}
}
// syncBuf is a buffer written by one goroutine (the command's output) and
// read by another.
type syncBuf struct {
mu sync.Mutex
b strings.Builder
}
func (s *syncBuf) Write(p []byte) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.b.Write(p)
}
func (s *syncBuf) String() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.b.String()
}
+4 -3
View File
@@ -56,14 +56,15 @@ terminal with neither.
| menu | what is in it |
|---|---|
| Board configuration | the BBS's name, the sysop's, the location, postal address, dial-in numbers and internet addresses; the banner, message of the day, goodbye, logo; menus and prompts |
| System configuration | the database and log; where files are kept and how large they may be; deny lists, the hack log, bans; scheduled events; every section of the file as it is |
| System configuration | the user and group it runs as; the database and log; where files are kept and how large they may be; deny lists, the hack log, bans; scheduled events; every section of the file as it is |
| Connections and modems | modem lines and every listener; callers at once, logins, time-outs, lock-outs; the caller ID country and GeoIP |
| Services | telnet, TN3270, SSH and RLogin listeners; finger, gopher, FTP, IRC, news, the web (API, forum, image boards); MRC, FidoNet, QWK networks, doors |
| Users and groups | the accounts (level, flags, sysop, locked, a new password; new ones; deleted ones) and the access levels |
| Maintenance | disk space; what message areas keep, old messages taken out; the image boards' archive; backups: one now, those made, `[backup]` ([Backups](Backups)) |
Running as another user and group, and PAM and LDAP logins, are shown as
not available yet: they are to come.
PAM and LDAP logins are shown as not available yet: they are to come.
Running as a user of its own (System configuration's Run as user) is in
[Running](Running#running-as-a-user-of-its-own).
| key | |
|---|---|
+1
View File
@@ -6,6 +6,7 @@
| `internal/server` | listeners, session headers, rlogin, SSH, telling 3270s from the rest |
| `internal/telnet` | the server side of telnet: options, terminal type, window size, the handoff to go3270 |
| `internal/confedit` | bbs.conf edited as a sysop would by hand, comments kept; the catalog of keys read from bbs.conf.sample (embedded by the root package), and which take effect at a reload |
| `internal/sockets` | ports bound as root and handed down: the BBS becomes its user, the same process |
| `internal/backup` | backups: the configuration, a database snapshot and the files in one tar.gz; listing, pruning, restoring |
| `internal/confui` | the configuration menus (sheets of internal/view), for `bbs config` and the sysop's tools: changes held until saved |
| `internal/view` | what the screens show, described once: menus, tables, messages, forms, panels, drafts |
+34
View File
@@ -11,6 +11,40 @@ user, with the database in `/var/lib/bbs` and sockets in `/run/bbs`;
`systemctl reload bbs` puts what may change while callers are on in force
([Configuration](Configuration#changing-it-while-callers-are-on)).
## Running as a user of its own
Ports under 1024 (telnet's 23, finger's 79, gopher's 70) need root, or
`CAP_NET_BIND_SERVICE`. Either systemd starts the BBS as its user with
that capability (bbs.service.sample's `User=bbs` and
`AmbientCapabilities=`), or the BBS is started as root and gives root up
itself:
```
[general]
user = bbs
; group = bbs (the user's own by default)
```
Started as root, `bbs serve` reads the configuration, binds every port and
unix socket it listens on (the listeners, the HTTP API and metrics, FTP,
NNTP, IRC, finger, gopher, binkp), gives up root (its supplementary groups
become the user's: `socket_group`'s and docker's, say) and runs itself
again as the user, the same process (its PID, for systemd and `systemctl
reload`), the sockets handed down. Nothing is written as root: the
database, logs, host keys and backups are the user's. A unix socket
without `socket_group` is the user's too.
Other commands started as root (`bbs user add`, `bbs init`, `bbs backup`)
give root up first as well, so that the database stays the user's; `bbs
check` and `bbs config` stay root (the configuration file is root's to
write), and `bbs backup restore` puts things back as root and gives them
(but the configuration) to the user.
The user must be able to read the configuration (`chown root:bbs
/etc/bbs/bbs.conf; chmod 0640`), write where the database and files are,
and run the program. Under systemd, leave `User=` out (bbs.service.sample
says how).
Without `-config` it runs with the defaults: telnet and TN3270 on port
2300, modem callers raw on 127.0.0.1:2323, the database `bbs.db` here. The database can as well
be PostgreSQL, MySQL or MariaDB: see [Databases](Databases).
+2 -1
View File
@@ -25,6 +25,7 @@ import (
"github.com/Neo-Desktop/bbs-sec/internal/imageboard"
"github.com/Neo-Desktop/bbs-sec/internal/nntp"
"github.com/Neo-Desktop/bbs-sec/internal/qwknet"
"github.com/Neo-Desktop/bbs-sec/internal/sockets"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
@@ -439,7 +440,7 @@ func (c *limitConn) Close() error {
// Run serves until ctx is done.
func (s *Server) Run(ctx context.Context) error {
ln, err := net.Listen("tcp", s.S.Address)
ln, err := sockets.Listen("tcp", s.S.Address)
if err != nil {
return fmt.Errorf("http: %w", err)
}
+3 -2
View File
@@ -3,11 +3,12 @@ package api
import (
"context"
"fmt"
"net"
"net/http"
"sort"
"strings"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/sockets"
)
// metrics writes the Prometheus text format.
@@ -77,7 +78,7 @@ func (s *Server) metrics(w http.ResponseWriter, r *http.Request) {
func (s *Server) serveMetrics(ctx context.Context) {
mux := http.NewServeMux()
mux.HandleFunc("GET /metrics", s.metrics)
ln, err := net.Listen("tcp", s.S.Metrics)
ln, err := sockets.Listen("tcp", s.S.Metrics)
if err != nil {
s.B.Log.Printf("http: metrics: %v", err)
return
+27
View File
@@ -21,6 +21,23 @@ type Targets struct {
Config string // the configuration file ("": not restored)
Database string // the database's address ("": not restored)
Dirs map[string]string // each directory's (or key file's) place, by its name (one not here: not restored)
// Owner: what is restored (but the configuration) is given to this
// user and group (a restore as root for a BBS that runs as its own)
Owner bool
UID, GID int
}
// own gives p (and all under it) to the owner, if there is one.
func (to Targets) own(p string) error {
if !to.Owner {
return nil
}
return filepath.WalkDir(p, func(q string, d os.DirEntry, err error) error {
if err != nil {
return err
}
return os.Lchown(q, to.UID, to.GID)
})
}
// Restore puts an archive back, the BBS stopped. Each file or directory
@@ -125,6 +142,11 @@ func Restore(archive string, to Targets, now time.Time, say func(string)) error
if err := restoreDB(s, to.Database, stamp, say); err != nil {
return fmt.Errorf("the database: %w", err)
}
if store.IsFile(to.Database) {
if err := to.own(strings.TrimPrefix(to.Database, "sqlite:")); err != nil {
return err
}
}
}
for top, s := range staged {
if top == "database.db" {
@@ -140,6 +162,11 @@ func Restore(archive string, to Targets, now time.Time, say func(string)) error
if err := os.Rename(s, dst); err != nil {
return err
}
if top != "bbs.conf" {
if err := to.own(dst); err != nil {
return err
}
}
say(fmt.Sprintf("%s restored to %s", top, dst))
}
return nil
+1
View File
@@ -74,6 +74,7 @@ var labels = map[string]string{
"security.deny_file": "Addresses refused (file)", "security.name_deny_file": "Names refused (file)",
"security.hack_log": "Hack log", "security.ban_minutes": "Ban after a lock-out (min)",
"chan.dir": "Image boards' files", "fido.dir": "FidoNet's packets",
"general.user": "Run as user", "general.group": "and group",
"backup.dir": "Backup directory", "backup.at": "Daily at (HH:MM)", "backup.keep": "Backups kept",
"backup.files": "With the files",
}
+3 -2
View File
@@ -86,8 +86,9 @@ func (e *Editor) systemMenu() page {
out = append(out, e.field(sec("chan"), "dir"), e.field(sec("fido"), "dir"))
out = append(out, heading("Security"))
out = append(out, e.fields(sec("security"), "deny_file", "name_deny_file", "hack_log", "ban_minutes")...)
out = append(out, heading("The process and logins"),
notYet("Run as user and group", "Binding the ports as root, then running as another user and group: to come. Today systemd's User= and Group= do it (bbs.service.sample)."),
out = append(out, heading("The process and logins"))
out = append(out, e.fields(g, "user", "group")...)
out = append(out,
notYet("PAM", "Passwords checked by PAM: to come."),
notYet("LDAP", "Passwords (and accounts) checked by an LDAP server: to come."),
heading("More"),
+2 -1
View File
@@ -22,6 +22,7 @@ import (
"time"
"github.com/Neo-Desktop/bbs-sec/internal/ftn"
"github.com/Neo-Desktop/bbs-sec/internal/sockets"
)
// binkp (FTS-1026) commands.
@@ -302,7 +303,7 @@ type Server struct {
// Run listens until ctx is done.
func (sv *Server) Run(ctx context.Context) error {
ln, err := net.Listen("tcp", sv.Address)
ln, err := sockets.Listen("tcp", sv.Address)
if err != nil {
return fmt.Errorf("binkp: %w", err)
}
+2 -1
View File
@@ -11,6 +11,7 @@ import (
"unicode/utf8"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/sockets"
"github.com/Neo-Desktop/bbs-sec/internal/tcpserv"
)
@@ -31,7 +32,7 @@ type Server struct {
// Run listens until ctx is done.
func (s *Server) Run(ctx context.Context) error {
ln, err := net.Listen("tcp", s.S.Address)
ln, err := sockets.Listen("tcp", s.S.Address)
if err != nil {
return fmt.Errorf("finger: %w", err)
}
+7
View File
@@ -25,6 +25,7 @@ import (
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/files"
"github.com/Neo-Desktop/bbs-sec/internal/sockets"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
@@ -58,6 +59,7 @@ type Server struct {
Set Settings
tlsConfig *tls.Config
inherited net.Listener // the socket handed down for Address, if any
mu sync.Mutex
clients int
perIP map[string]int
@@ -81,6 +83,10 @@ func New(b *bbs.BBS, set Settings) (*Server, error) {
// Run serves until ctx is done.
func (s *Server) Run(ctx context.Context) error {
s.inherited = sockets.Take("tcp", s.Set.Address)
if s.inherited != nil && s.Set.TLS == TLSImplicit {
s.inherited = tls.NewListener(s.inherited, s.tlsConfig)
}
srv := ftpserver.NewFtpServer(s)
srv.Logger = slog.New(slog.NewTextHandler(s.B.Log.Writer(), &slog.HandlerOptions{Level: slog.LevelError}))
if err := srv.Listen(); err != nil {
@@ -105,6 +111,7 @@ func (s *Server) Run(ctx context.Context) error {
func (s *Server) GetSettings() (*ftpserver.Settings, error) {
set := &ftpserver.Settings{
ListenAddr: s.Set.Address,
Listener: s.inherited, // bound before the BBS gave up root (nil: none)
PublicHost: s.Set.PublicHost,
Banner: s.Set.Banner,
IdleTimeout: int(s.Set.IdleTimeout / time.Second),
+2 -1
View File
@@ -15,6 +15,7 @@ import (
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/news"
"github.com/Neo-Desktop/bbs-sec/internal/sockets"
"github.com/Neo-Desktop/bbs-sec/internal/store"
"github.com/Neo-Desktop/bbs-sec/internal/tcpserv"
)
@@ -41,7 +42,7 @@ const PerPage = 50
// Run listens until ctx is done.
func (s *Server) Run(ctx context.Context) error {
ln, err := net.Listen("tcp", s.S.Address)
ln, err := sockets.Listen("tcp", s.S.Address)
if err != nil {
return fmt.Errorf("gopher: %w", err)
}
+6 -3
View File
@@ -22,6 +22,7 @@ import (
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/ircd/isupport"
"github.com/Neo-Desktop/bbs-sec/internal/sockets"
"github.com/Neo-Desktop/bbs-sec/internal/tcpserv"
)
@@ -116,7 +117,7 @@ func (s *Server) Run(ctx context.Context) error {
Refuse: func(c net.Conn) bool { return s.B.Refuse("irc", c.RemoteAddr()) }}
var lns []net.Listener
if s.S.Address != "" {
ln, err := net.Listen("tcp", s.S.Address)
ln, err := sockets.Listen("tcp", s.S.Address)
if err != nil {
return fmt.Errorf("irc: %w", err)
}
@@ -127,8 +128,10 @@ func (s *Server) Run(ctx context.Context) error {
if err != nil {
return fmt.Errorf("irc: certificate: %w", err)
}
ln, err := tls.Listen("tcp", s.S.TLSAddress, &tls.Config{Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12})
ln, err := sockets.Listen("tcp", s.S.TLSAddress)
if err == nil {
ln = tls.NewListener(ln, &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12})
}
if err != nil {
for _, l := range lns {
l.Close()
+2 -1
View File
@@ -15,6 +15,7 @@ import (
"time"
"github.com/Neo-Desktop/bbs-sec/internal/news"
"github.com/Neo-Desktop/bbs-sec/internal/sockets"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
@@ -67,7 +68,7 @@ func NewServer(svc *Service, set ServerSettings, peers []*Peer) (*Server, error)
// Run serves until ctx is done.
func (s *Server) Run(ctx context.Context) error {
ln, err := net.Listen("tcp", s.Set.Address)
ln, err := sockets.Listen("tcp", s.Set.Address)
if err != nil {
return fmt.Errorf("nntp: %w", err)
}
+101
View File
@@ -0,0 +1,101 @@
package server
import (
"fmt"
"net"
"os"
"github.com/Neo-Desktop/bbs-sec/internal/sockets"
)
// Bind binds every socket the configuration listens on (as root, before
// the BBS becomes [general]'s user): the listeners, TCP and unix, and the
// servers' ports. They are handed down, each server taking its own.
func Bind(cfg *Config) ([]sockets.Socket, error) {
var out []sockets.Socket
fail := func(err error) ([]sockets.Socket, error) {
for _, s := range out {
s.File.Close()
}
return nil, err
}
tcp := func(addr string) error {
if addr == "" {
return nil
}
for _, s := range out {
if s.Network == "tcp" && s.Address == addr {
return nil
}
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return fmt.Errorf("%s: %w", addr, err)
}
defer ln.Close()
f, err := ln.(*net.TCPListener).File()
if err != nil {
return err
}
out = append(out, sockets.Socket{Network: "tcp", Address: addr, File: f})
return nil
}
for _, l := range cfg.Listeners {
if !l.Unix() {
if err := tcp(l.Address); err != nil {
return fail(fmt.Errorf("[listen %s] %w", l.Name, err))
}
continue
}
u, err := ListenUnix(l)
if err != nil {
return fail(fmt.Errorf("[listen %s] %w", l.Name, err))
}
if a := cfg.RunAs; a != nil {
// the user's, as it would be had the BBS made it (its group
// socket_group's, if said)
gid := a.GID
if l.SocketGroup != "" {
gid = -1
}
if err := os.Lchown(l.path(), a.UID, gid); err != nil {
u.Close()
return fail(err)
}
}
f, err := u.UnixListener.File()
u.UnixListener.Close() // not u.Close: the socket stays where it is
if err != nil {
return fail(err)
}
out = append(out, sockets.Socket{Network: "unix", Address: l.path(), File: f})
}
var addrs []string
if h := cfg.HTTP; h != nil {
addrs = append(addrs, h.Address, h.Metrics)
}
if cfg.FTP != nil {
addrs = append(addrs, cfg.FTP.Address)
}
if cfg.NNTP != nil {
addrs = append(addrs, cfg.NNTP.Address)
}
if i := cfg.IRC; i != nil {
addrs = append(addrs, i.Address, i.TLSAddress)
}
if cfg.Finger != nil {
addrs = append(addrs, cfg.Finger.Address)
}
if cfg.Gopher != nil {
addrs = append(addrs, cfg.Gopher.Address)
}
if cfg.Binkp != nil {
addrs = append(addrs, cfg.Binkp.Address)
}
for _, a := range addrs {
if err := tcp(a); err != nil {
return fail(err)
}
}
return out, nil
}
+10 -1
View File
@@ -32,6 +32,7 @@ import (
"github.com/Neo-Desktop/bbs-sec/internal/qwk"
"github.com/Neo-Desktop/bbs-sec/internal/qwknet"
"github.com/Neo-Desktop/bbs-sec/internal/screens"
"github.com/Neo-Desktop/bbs-sec/internal/sockets"
"github.com/Neo-Desktop/bbs-sec/internal/store"
"github.com/Neo-Desktop/bbs-sec/internal/ui3270"
)
@@ -70,7 +71,8 @@ type Config struct {
Log string // syslog, stderr, none, or a file
Listeners []*Listener
Warnings []string
Guard *guard.Guard // [security]
Guard *guard.Guard // [security]
RunAs *sockets.Account // [general] user and group: who serve becomes, its ports bound (nil: as it is started)
Events []*events.Event
}
@@ -248,6 +250,13 @@ func (c *Config) general(g *config.Section) error {
if s.PhoneCountry = strings.ToUpper(g.String("phone_country", "")); s.PhoneCountry != "" && !phone.Known(s.PhoneCountry) {
return fmt.Errorf("phone_country: %q is not a country with a calling code (an ISO 3166 code: US, GB, DE)", s.PhoneCountry)
}
if u := g.String("user", ""); u != "" {
if c.RunAs, err = sockets.Lookup(u, g.String("group", "")); err != nil {
return err
}
} else if g.Has("group") {
return errors.New("group: with user only")
}
s.QWKID = strings.ToUpper(g.String("qwk_id", s.QWKID))
if s.QWKID != "" && !qwk.ValidID(s.QWKID) {
return errors.New("qwk_id: 1 to 8 letters and digits")
+17 -3
View File
@@ -40,6 +40,7 @@ import (
"golang.org/x/crypto/ssh"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/sockets"
"github.com/Neo-Desktop/bbs-sec/internal/telnet"
"github.com/Neo-Desktop/bbs-sec/internal/textui"
"github.com/Neo-Desktop/bbs-sec/internal/ui3270"
@@ -156,7 +157,7 @@ func (s *Server) listen(l *Listener) (net.Listener, error) {
if err != nil {
return nil, fmt.Errorf("tls: %w", err)
}
ln, err := net.Listen("tcp", l.Address)
ln, err := sockets.Listen("tcp", l.Address)
if err != nil {
return nil, err
}
@@ -164,8 +165,21 @@ func (s *Server) listen(l *Listener) (net.Listener, error) {
MinVersion: tls.VersionTLS12}), nil
}
if !l.Unix() {
return net.Listen("tcp", l.Address)
return sockets.Listen("tcp", l.Address)
}
if ln, ok := sockets.Take("unix", l.path()).(*net.UnixListener); ok {
return &unixListener{ln, l.path()}, nil // made before the BBS gave up root
}
u, err := ListenUnix(l)
if err != nil {
return nil, err // not a nil *unixListener in an interface
}
return u, nil
}
// ListenUnix makes a listener's unix socket, its mode and group as the
// listener says.
func ListenUnix(l *Listener) (*unixListener, error) {
path := l.path()
if _, err := os.Lstat(path); err == nil {
// a live server keeps its socket; a dead one's is replaced
@@ -193,7 +207,7 @@ func (s *Server) listen(l *Listener) (net.Listener, error) {
}
ul := ln.(*net.UnixListener)
ul.SetUnlinkOnClose(false) // the name it was made under is gone
fail := func(err error) (net.Listener, error) {
fail := func(err error) (*unixListener, error) {
ul.Close()
return nil, err
}
+199
View File
@@ -0,0 +1,199 @@
// Package sockets lets the BBS bind its ports as root and then run as a
// user of its own: the root process binds every listening socket, gives
// up root (groups, group, user) and executes itself again, the same
// process, the sockets handed down; there each server's Listen takes the
// socket for its address instead of binding one.
package sockets
import (
"errors"
"fmt"
"net"
"os"
"os/user"
"strconv"
"strings"
"sync"
"syscall"
)
// env is how sockets are handed down: "3 tcp :23\n4 unix /run/bbs/x.sock".
const env = "BBS_SOCKETS"
var (
mu sync.Mutex
inherited = map[string]net.Listener{} // by key: "tcp :23"
)
func key(network, address string) string { return network + " " + address }
// Inherit takes the sockets handed down, if any (once, at the start).
func Inherit() error {
v := os.Getenv(env)
if v == "" {
return nil
}
os.Unsetenv(env)
mu.Lock()
defer mu.Unlock()
for _, line := range strings.Split(v, "\n") {
fdText, k, ok := strings.Cut(line, " ")
fd, err := strconv.Atoi(fdText)
if !ok || err != nil || fd < 3 {
return fmt.Errorf("%s: %q", env, line)
}
syscall.CloseOnExec(fd)
f := os.NewFile(uintptr(fd), k)
ln, err := net.FileListener(f)
f.Close() // FileListener has its own
if err != nil {
return fmt.Errorf("the socket for %s: %w", k, err)
}
inherited[k] = ln
}
return nil
}
// Take is the socket handed down for an address (nil: none).
func Take(network, address string) net.Listener {
mu.Lock()
defer mu.Unlock()
k := key(network, address)
ln := inherited[k]
delete(inherited, k)
return ln
}
// Listen is net.Listen, but for an address whose socket was handed down.
func Listen(network, address string) (net.Listener, error) {
if ln := Take(network, address); ln != nil {
return ln, nil
}
return net.Listen(network, address)
}
// Left are the sockets handed down that nothing took (the configuration
// changed between the two: they are closed).
func Left() []string {
mu.Lock()
defer mu.Unlock()
var out []string
for k, ln := range inherited {
out = append(out, k)
ln.Close()
delete(inherited, k)
}
return out
}
// Account is who the BBS runs as.
type Account struct {
User string // as configured
UID int
GID int
Groups []int // supplementary: the user's groups
}
// Lookup finds a user (a name or a number), and its group: group, or the
// user's own ("": its own).
func Lookup(name, group string) (*Account, error) {
u, err := user.Lookup(name)
if err != nil {
if u, err = user.LookupId(name); err != nil {
return nil, fmt.Errorf("user %q: no such user", name)
}
}
a := &Account{User: name}
a.UID, _ = strconv.Atoi(u.Uid)
a.GID, _ = strconv.Atoi(u.Gid)
if group != "" {
g, err := user.LookupGroup(group)
if err != nil {
if g, err = user.LookupGroupId(group); err != nil {
return nil, fmt.Errorf("group %q: no such group", group)
}
}
a.GID, _ = strconv.Atoi(g.Gid)
}
ids, _ := u.GroupIds()
for _, id := range ids {
if n, err := strconv.Atoi(id); err == nil {
a.Groups = append(a.Groups, n)
}
}
if a.UID == 0 {
return nil, errors.New("user: root is who it runs as already: name another")
}
return a, nil
}
// Drop gives up root for the account, in this process: its groups, its
// group, its user.
func Drop(a *Account) error {
if err := syscall.Setgroups(a.Groups); err != nil {
return fmt.Errorf("setgroups: %w", err)
}
if err := syscall.Setgid(a.GID); err != nil {
return fmt.Errorf("setgid %d: %w", a.GID, err)
}
if err := syscall.Setuid(a.UID); err != nil {
return fmt.Errorf("setuid %d: %w", a.UID, err)
}
if os.Geteuid() == 0 || os.Getuid() == 0 {
return errors.New("still root after setuid")
}
return nil
}
// Socket is a socket bound as root, to hand down.
type Socket struct {
Network, Address string
File *os.File
}
// Become gives up root for the account and executes this program again
// with the same arguments, the sockets handed down; it returns only if it
// could not.
func Become(a *Account, socks []Socket) error {
exe, err := os.Executable()
if err != nil {
return err
}
envv := os.Environ()
if h, err := user.LookupId(strconv.Itoa(a.UID)); err == nil {
envv = setEnv(setEnv(setEnv(envv, "HOME", h.HomeDir), "USER", h.Username), "LOGNAME", h.Username)
}
// each socket left at its own descriptor, open across the exec (not
// moved to 3, 4 ...: the runtime's own are among those); the new
// program's are made after them, in what is free
var lines []string
for _, s := range socks {
fd := s.File.Fd()
if _, _, e := syscall.Syscall(syscall.SYS_FCNTL, fd, syscall.F_SETFD, 0); e != 0 {
return fmt.Errorf("the socket for %s: %w", s.Address, e)
}
lines = append(lines, fmt.Sprintf("%d %s", fd, key(s.Network, s.Address)))
}
if len(lines) > 0 {
envv = setEnv(envv, env, strings.Join(lines, "\n"))
}
if err := Drop(a); err != nil {
return err
}
err = syscall.Exec(exe, os.Args, envv)
if errors.Is(err, syscall.EACCES) {
return fmt.Errorf("%s cannot run %s: %w", a.User, exe, err)
}
return err
}
// setEnv is env with k's value v (in its place, or added).
func setEnv(env []string, k, v string) []string {
for i, e := range env {
if strings.HasPrefix(e, k+"=") {
env[i] = k + "=" + v
return env
}
}
return append(env, k+"="+v)
}
+69
View File
@@ -0,0 +1,69 @@
package sockets
import (
"fmt"
"net"
"os"
"strings"
"testing"
)
// TestInherit: sockets named in the environment are taken by Listen for
// their addresses; what nothing takes is closed by Left.
func TestInherit(t *testing.T) {
a, _ := net.Listen("tcp", "127.0.0.1:0")
b, _ := net.Listen("tcp", "127.0.0.1:0")
fa, _ := a.(*net.TCPListener).File()
fb, _ := b.(*net.TCPListener).File()
addrA, addrB := a.Addr().String(), b.Addr().String()
a.Close()
b.Close()
os.Setenv(env, fmt.Sprintf("%d tcp %s\n%d tcp %s", fa.Fd(), addrA, fb.Fd(), addrB))
if err := Inherit(); err != nil {
t.Fatal(err)
}
if os.Getenv(env) != "" {
t.Error("the environment keeps it")
}
ln, err := Listen("tcp", addrA)
if err != nil || ln.Addr().String() != addrA {
t.Fatalf("%v %v", ln, err)
}
defer ln.Close()
go func() {
if c, err := net.Dial("tcp", addrA); err == nil {
c.Write([]byte("hi"))
c.Close()
}
}()
c, err := ln.Accept()
if err != nil {
t.Fatal(err)
}
c.Close()
if Take("tcp", addrA) != nil {
t.Error("taken twice")
}
if left := Left(); len(left) != 1 || left[0] != "tcp "+addrB {
t.Errorf("left %q", left)
}
os.Setenv(env, "x tcp :1")
if err := Inherit(); err == nil {
t.Error("a bad descriptor taken")
}
}
func TestLookup(t *testing.T) {
if _, err := Lookup("no-such-user-here", ""); err == nil || !strings.Contains(err.Error(), "no such user") {
t.Errorf("%v", err)
}
if _, err := Lookup("root", ""); err == nil {
t.Error("root taken")
}
if a, err := Lookup("nobody", ""); err == nil && (a.UID == 0 || a.User != "nobody") {
t.Errorf("%+v", a)
}
if _, err := Lookup("nobody", "no-such-group-here"); err == nil {
t.Error("a group that is not there")
}
}