]> ruderich.org/simon Gitweb - safcm/safcm.git/blob - rpc/dial.go
Use SPDX license identifiers
[safcm/safcm.git] / rpc / dial.go
1 // Simple RPC-like protocol: establish new connection and upload helper
2
3 // SPDX-License-Identifier: GPL-3.0-or-later
4 // Copyright (C) 2021-2024  Simon Ruderich
5
6 package rpc
7
8 import (
9         "bufio"
10         "bytes"
11         "crypto/sha512"
12         "encoding/hex"
13         "fmt"
14         "io"
15         "io/fs"
16         "os/exec"
17         "strconv"
18         "strings"
19
20         "ruderich.org/simon/safcm"
21 )
22
23 type SSHConfig struct {
24         Host      string
25         User      string // optional
26         SshConfig string // optional
27
28         RemoteHelpers fs.FS
29 }
30
31 func (c *Conn) DialSSH(cfg SSHConfig) error {
32         if c.events == nil {
33                 return fmt.Errorf("cannot reuse Conn")
34         }
35
36         if cfg.RemoteHelpers == nil {
37                 return fmt.Errorf("SSHConfig.RemoteHelpers not set")
38         }
39         c.remoteHelpers = cfg.RemoteHelpers
40
41         remote := cfg.Host
42         if cfg.User != "" {
43                 remote = cfg.User + "@" + cfg.Host
44         }
45         c.debugf("DialSSH: connecting to %q", remote)
46
47         opts := "-eu"
48         if c.debug {
49                 // Help debugging by showing executed shell commands
50                 opts += "x"
51         }
52
53         c.sshRemote = remote
54         if cfg.SshConfig != "" {
55                 c.sshOpts = []string{"-F", cfg.SshConfig}
56         }
57         c.cmd = exec.Command("ssh",
58                 append(append([]string{}, c.sshOpts...),
59                         c.sshRemote, "/bin/sh", opts)...)
60
61         stdin, err := c.cmd.StdinPipe()
62         if err != nil {
63                 return err
64         }
65         stdout, err := c.cmd.StdoutPipe()
66         if err != nil {
67                 return err
68         }
69         err = c.handleStderrAsEvents(c.cmd)
70         if err != nil {
71                 return err
72         }
73
74         err = c.cmd.Start()
75         if err != nil {
76                 return err
77         }
78
79         err = c.dialSSH(stdin, stdout)
80         if err != nil {
81                 c.Kill() //nolint:errcheck
82                 return err
83         }
84         c.conn = safcm.NewGobConn(stdout, stdin)
85
86         return nil
87 }
88
89 func (c *Conn) dialSSH(stdin io.Writer, stdout_ io.Reader) error {
90         stdout := bufio.NewReader(stdout_)
91
92         goos, err := connGetGoos(stdin, stdout)
93         if err != nil {
94                 return err
95         }
96         goarch, err := connGetGoarch(stdin, stdout)
97         if err != nil {
98                 return err
99         }
100         uid, err := connGetUID(stdin, stdout)
101         if err != nil {
102                 return err
103         }
104
105         path := fmt.Sprintf("/tmp/safcm-remote-%d", uid)
106
107         c.debugf("DialSSH: probing remote at %q", path)
108
109         // Compatibility for different operating systems
110         var compat string
111         switch goos {
112         case "linux":
113                 compat = `
114 dir_stat='drwxrwxrwt 0 0'
115 file_stat="-rwx------ $(id -u) $(id -g)"
116 compat_stat() {
117         stat -c '%A %u %g' "$1"
118 }
119 compat_sha512sum() {
120         sha512sum "$1"
121 }
122 `
123         case "freebsd", "openbsd":
124                 compat = `
125 dir_stat='41777 0 0'
126 file_stat="100700 $(id -u) $(id -g)"
127 compat_stat() {
128         stat -f '%p %u %g' "$1"
129 }
130 compat_sha512sum() {
131         sha512 -q "$1"
132 }
133 `
134         default:
135                 return fmt.Errorf("internal error: no support for %q", goos)
136         }
137
138         // Use a function so the shell cannot execute the input line-wise.
139         // This is important because we're also using stdin to send data to
140         // the script. If the shell executes the input line-wise then our
141         // script is interpreted as input for `read`.
142         //
143         // The target directory must no permit other users to delete our files
144         // or symlink attacks and arbitrary code execution is possible. For
145         // /tmp this is guaranteed by the sticky bit. The code verifies the
146         // directory has the proper permissions.
147         //
148         // We cannot use `test -f && test -O` because this is open to TOCTOU
149         // attacks. `stat` gives use the full file state. If the file is owned
150         // by us and not a symlink then it's safe to use (assuming sticky
151         // directory or directory not writable by others).
152         //
153         // `test -e` is only used to prevent error messages if the file
154         // doesn't exist. It does not guard against any races.
155         _, err = fmt.Fprintf(stdin, `
156 %s
157 f() {
158         x=%q
159
160         dir="$(dirname "$x")"
161         if ! test "$(compat_stat "$dir")" = "$dir_stat"; then
162                 echo "unsafe permissions on $dir, aborting" >&2
163                 exit 1
164         fi
165
166         if test -e "$x" && test "$(compat_stat "$x")" = "$file_stat"; then
167                 # Report checksum
168                 compat_sha512sum "$x"
169         else
170                 # Empty checksum to request upload
171                 echo
172         fi
173
174         # Wait for signal to continue
175         read upload
176
177         if test -n "$upload"; then
178                 tmp="$(mktemp "$x.XXXXXX")"
179                 # Report filename for upload
180                 echo "$tmp"
181                 # Wait for upload to complete
182                 read unused
183
184                 # Safely create new file (ln does not follow symlinks)
185                 rm -f "$x"
186                 ln "$tmp" "$x"
187                 rm "$tmp"
188                 # Make file executable
189                 chmod 0700 "$x"
190                 # Some BSD create files with group wheel in /tmp
191                 chgrp "$(id -g)" "$x"
192         fi
193
194         exec "$x" sync
195 }
196 f
197 `, compat, path)
198         if err != nil {
199                 return err
200         }
201         remoteSum, err := stdout.ReadString('\n')
202         if err != nil {
203                 return err
204         }
205
206         // Get remote helper binary
207         helper, err := fs.ReadFile(c.remoteHelpers,
208                 fmt.Sprintf("%s-%s", goos, goarch))
209         if err != nil {
210                 return fmt.Errorf("remote not built for GOOS/GOARCH %s/%s",
211                         goos, goarch)
212         }
213
214         var upload bool
215         if remoteSum == "\n" {
216                 upload = true
217                 c.debugf("DialSSH: remote not present or invalid permissions")
218
219         } else {
220                 x := strings.Fields(remoteSum)
221                 if len(x) < 1 {
222                         return fmt.Errorf("got unexpected checksum line %q",
223                                 remoteSum)
224                 }
225                 sha := sha512.Sum512(helper)
226                 hex := hex.EncodeToString(sha[:])
227                 if hex == x[0] {
228                         c.debugf("DialSSH: remote checksum matches")
229                 } else {
230                         upload = true
231                         c.debugf("DialSSH: remote checksum does not match")
232                 }
233         }
234
235         if upload {
236                 // Notify user that an upload is going to take place.
237                 c.events <- ConnEvent{
238                         Type: ConnEventUpload,
239                 }
240
241                 // Tell script we want to upload a new file.
242                 _, err = fmt.Fprintln(stdin, "upload")
243                 if err != nil {
244                         return err
245                 }
246                 // Get path to temporary file for upload.
247                 //
248                 // Write to the temporary file instead of the final path so
249                 // that a concurrent run of this function won't use a
250                 // partially written file. The rm in the script could still
251                 // cause a missing file but at least no file with unknown
252                 // content is executed.
253                 path, err := stdout.ReadString('\n')
254                 if err != nil {
255                         return err
256                 }
257                 path = strings.TrimSuffix(path, "\n")
258
259                 c.debugf("DialSSH: uploading new remote to %q at %q",
260                         c.sshRemote, path)
261
262                 cmd := exec.Command("ssh",
263                         append(append([]string{}, c.sshOpts...),
264                                 c.sshRemote,
265                                 fmt.Sprintf("cat > %q", path))...)
266                 cmd.Stdin = bytes.NewReader(helper)
267                 err = c.handleStderrAsEvents(cmd) // cmd.Stderr
268                 if err != nil {
269                         return err
270                 }
271                 err = cmd.Run()
272                 if err != nil {
273                         return err
274                 }
275         }
276
277         // Tell script to continue and execute the remote helper
278         _, err = fmt.Fprintln(stdin, "")
279         if err != nil {
280                 return err
281         }
282
283         return nil
284 }
285
286 func connGetGoos(stdin io.Writer, stdout *bufio.Reader) (string, error) {
287         _, err := fmt.Fprintln(stdin, "uname")
288         if err != nil {
289                 return "", err
290         }
291         x, err := stdout.ReadString('\n')
292         if err != nil {
293                 return "", err
294         }
295         x = strings.TrimSpace(x)
296
297         // NOTE: Adapt helper uploading in dialSSH() when adding new systems
298         var goos string
299         switch x {
300         case "Linux":
301                 goos = "linux"
302         case "FreeBSD":
303                 goos = "freebsd"
304         case "OpenBSD":
305                 goos = "openbsd"
306         default:
307                 return "", fmt.Errorf("unsupported OS %q (`uname`)", x)
308         }
309         return goos, nil
310 }
311
312 func connGetGoarch(stdin io.Writer, stdout *bufio.Reader) (string, error) {
313         _, err := fmt.Fprintln(stdin, "uname -m")
314         if err != nil {
315                 return "", err
316         }
317         x, err := stdout.ReadString('\n')
318         if err != nil {
319                 return "", err
320         }
321         x = strings.TrimSpace(x)
322
323         // NOTE: Adapt cmd/safcm-remote/build.sh when adding new architectures
324         var goarch string
325         switch x {
326         case "x86_64", "amd64":
327                 goarch = "amd64"
328         case "armv7l":
329                 goarch = "armv7l"
330         default:
331                 return "", fmt.Errorf("unsupported arch %q (`uname -m`)", x)
332         }
333         return goarch, nil
334 }
335
336 func connGetUID(stdin io.Writer, stdout *bufio.Reader) (int, error) {
337         _, err := fmt.Fprintln(stdin, "id -u")
338         if err != nil {
339                 return -1, err
340         }
341         x, err := stdout.ReadString('\n')
342         if err != nil {
343                 return -1, err
344         }
345         x = strings.TrimSpace(x)
346
347         uid, err := strconv.Atoi(x)
348         if err != nil {
349                 return -1, fmt.Errorf("invalid UID %q (`id -u`)", x)
350         }
351         return uid, nil
352 }