diff --git a/main.go b/main.go index 02ac820..6ce91ad 100644 --- a/main.go +++ b/main.go @@ -23,6 +23,7 @@ import ( "context" "errors" "fmt" + "io/fs" "log" "os" "os/exec" @@ -353,24 +354,30 @@ transport.tcpMuxKeepaliveInterval = 5 return "", fmt.Errorf("invalid port mapping: %q", entry) } name := strings.TrimSpace(parts[0]) - localPort := strings.TrimSpace(parts[1]) - remotePort := strings.TrimSpace(parts[2]) protocol := strings.ToLower(strings.TrimSpace(parts[3])) if protocol != "tcp" && protocol != "udp" { return "", fmt.Errorf("invalid port mapping protocol: %q", entry) } + localPort, err := parsePortNumber(parts[1]) + if err != nil { + return "", fmt.Errorf("invalid port mapping port: %q", entry) + } + remotePort, err := parsePortNumber(parts[2]) + if err != nil { + return "", fmt.Errorf("invalid port mapping port: %q", entry) + } config += fmt.Sprintf(` [[proxies]] name = "%s" type = "%s" localIP = "%s" -localPort = %s -remotePort = %s -`, escapeTomlString(name), protocol, cfg.BackingServiceDNS, localPort, remotePort) +localPort = %d +remotePort = %d +`, escapeTomlString(name), protocol, escapeTomlString(cfg.BackingServiceDNS), localPort, remotePort) } - if err := os.WriteFile(frpConfigPath, []byte(config), 0o600); err != nil { + if err := writePrivateFile(frpConfigPath, []byte(config)); err != nil { return "", fmt.Errorf("write frpc config: %w", err) } @@ -444,22 +451,77 @@ func parseTailscaleTags(tagsStr string) ([]string, error) { // so the secret never appears in the process's argv, which is readable by // anything that can see /proc//cmdline in the pod. func renderPlayitConfig(secretKey string) (string, error) { - if err := os.WriteFile(playitAuthPath, []byte(secretKey), 0o600); err != nil { + if err := writePrivateFile(playitAuthPath, []byte(secretKey)); err != nil { return "", fmt.Errorf("write playit secret: %w", err) } return playitAuthPath, nil } +// parsePortNumber parses a TCP/UDP port from a BACKING_SERVICE_PORT entry and +// rejects anything that is not a decimal integer in 1..65535. Rejecting +// non-numeric input here keeps raw text out of the rendered TOML. +func parsePortNumber(s string) (int, error) { + port, err := strconv.Atoi(strings.TrimSpace(s)) + if err != nil { + return 0, fmt.Errorf("parse port %q: %w", s, err) + } + if port < 1 || port > 65535 { + return 0, fmt.Errorf("port %d out of range 1-65535", port) + } + return port, nil +} + +// writePrivateFile replaces path with a regular file holding data, mode 0600. +// The existing path is removed first (a symlink is removed itself, not +// followed), and the file is then created with O_EXCL. Removing first and +// opening with O_EXCL means a pre-planted file or symlink at the fixed /tmp +// path can neither redirect the write nor keep a wider mode. +func writePrivateFile(path string, data []byte) error { + if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("remove %s: %w", path, err) + } + f, err := os.OpenFile(filepath.Clean(path), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return fmt.Errorf("create %s: %w", path, err) + } + if _, err := f.Write(data); err != nil { + _ = f.Close() + return fmt.Errorf("write %s: %w", path, err) + } + if err := f.Close(); err != nil { + return fmt.Errorf("close %s: %w", path, err) + } + return nil +} + // escapeTomlString escapes special characters in a TOML string value. +// Backslash, quote, newline, carriage return and tab get their short escapes; +// any other control byte (< 0x20 or 0x7f) becomes a \uXXXX escape. Bytes are +// handled one at a time, so multi-byte UTF-8 passes through unchanged. func escapeTomlString(s string) string { - return strings.NewReplacer( - "\\", "\\\\", - "\"", "\\\"", - "\n", "\\n", - "\r", "\\r", - "\t", "\\t", - ).Replace(s) + var b strings.Builder + b.Grow(len(s)) + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case c == '\\': + b.WriteString("\\\\") + case c == '"': + b.WriteString("\\\"") + case c == '\n': + b.WriteString("\\n") + case c == '\r': + b.WriteString("\\r") + case c == '\t': + b.WriteString("\\t") + case c < 0x20 || c == 0x7f: + fmt.Fprintf(&b, "\\u%04X", c) + default: + b.WriteByte(c) + } + } + return b.String() } // buildCommand constructs the command to run the relay process for diff --git a/main_test.go b/main_test.go index bfcf652..d514e41 100644 --- a/main_test.go +++ b/main_test.go @@ -1104,3 +1104,77 @@ func TestRunCommandContextCancellation(t *testing.T) { t.Errorf("runCommand() took %v after cancellation, want well under the sleep's 5s duration", elapsed) } } + +func TestRenderFrpConfigRejectsNonNumericPort(t *testing.T) { + cfg := Config{ + FrpServerAddr: "frp.example.com", + FrpServerPort: 7000, + BackingServiceDNS: "my-server.games.svc", + BackingServicePort: "game:25565\n[[proxies]]:30000:tcp", + } + + cfg.GameServerUID = "fixture-uid" + _, err := renderFrpConfig(cfg, "token") + if err == nil || !strings.Contains(err.Error(), "invalid port mapping port") { + t.Errorf("renderFrpConfig() error = %v, want invalid port mapping port error", err) + } +} + +func TestRenderFrpConfigRejectsOutOfRangePort(t *testing.T) { + for _, mapping := range []string{"game:0:30000:tcp", "game:25565:70000:tcp"} { + cfg := Config{ + FrpServerAddr: "frp.example.com", + FrpServerPort: 7000, + BackingServiceDNS: "my-server.games.svc", + BackingServicePort: mapping, + } + + cfg.GameServerUID = "fixture-uid" + _, err := renderFrpConfig(cfg, "token") + if err == nil || !strings.Contains(err.Error(), "invalid port mapping port") { + t.Errorf("renderFrpConfig(%q) error = %v, want invalid port mapping port error", mapping, err) + } + } +} + +func TestEscapeTomlStringControlChars(t *testing.T) { + if got, want := escapeTomlString("a\x00b\x1b"), "a\\u0000b\\u001B"; got != want { + t.Errorf("escapeTomlString() = %q, want %q", got, want) + } +} + +func TestWritePrivateFileReplacesSymlink(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "target") + path := filepath.Join(dir, "secret") + + if err := os.WriteFile(target, []byte("original"), 0o644); err != nil { + t.Fatalf("write target: %v", err) + } + if err := os.Symlink(target, path); err != nil { + t.Fatalf("symlink: %v", err) + } + + if err := writePrivateFile(path, []byte("x")); err != nil { + t.Fatalf("writePrivateFile() error = %v", err) + } + + got, err := os.ReadFile(target) + if err != nil { + t.Fatalf("read target: %v", err) + } + if string(got) != "original" { + t.Errorf("symlink target was modified: %q", got) + } + + info, err := os.Lstat(path) + if err != nil { + t.Fatalf("lstat path: %v", err) + } + if !info.Mode().IsRegular() { + t.Errorf("path mode = %v, want regular file", info.Mode()) + } + if perm := info.Mode().Perm(); perm != 0o600 { + t.Errorf("path permissions = %o, want 600", perm) + } +} diff --git a/specs.md b/specs.md index 6204ff2..4f5c72d 100644 --- a/specs.md +++ b/specs.md @@ -97,7 +97,7 @@ Whitespace (leading/trailing newlines, spaces) is trimmed from credential values | frp | `/tmp/gameplane-tunnel-frpc.toml` | TOML | Rendered by `renderFrpConfig`; read by frpc process | | playit | `/tmp/gameplane-tunnel-playit-auth` | Raw text (secret key) | Rendered by `renderPlayitConfig`; read by playitd via `--secret-path` flag | -frp/playit rendered files use mode 0600 and are removed when `run` returns. Tailscale uses the state volume described below; no daemon config or CLI auth file is produced. +frp ports are validated as integers in 1–65535 before rendering; anything else is rejected and never written into the TOML. frp TOML strings (including `localIP`) are escaped, and control characters become `\uXXXX`. frp/playit config and secret files are recreated on each render: any existing path (including a symlink) is removed, then the file is created with `O_EXCL` at mode 0600, so a planted file cannot redirect the write or keep a wider mode. frp/playit rendered files use mode 0600 and are removed when `run` returns. Tailscale uses the state volume described below; no daemon config or CLI auth file is produced. ### Relay Binaries and Command-Line Arguments