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