1 // Simple RPC-like protocol: establish new connection and upload helper
3 // Copyright (C) 2021 Simon Ruderich
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.
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.
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/>.
31 "ruderich.org/simon/safcm"
32 "ruderich.org/simon/safcm/remote"
35 type SSHConfig struct {
37 User string // optional
38 SshConfig string // optional
41 func (c *Conn) DialSSH(cfg SSHConfig) error {
43 return fmt.Errorf("cannot reuse Conn")
48 remote = cfg.User + "@" + cfg.Host
50 c.debugf("DialSSH: connecting to %q", remote)
54 // Help debugging by showing executed shell commands
59 if cfg.SshConfig != "" {
60 c.sshOpts = []string{"-F", cfg.SshConfig}
62 c.cmd = exec.Command("ssh",
63 append(append([]string{}, c.sshOpts...),
64 c.sshRemote, "/bin/sh", opts)...)
66 stdin, err := c.cmd.StdinPipe()
70 stdout, err := c.cmd.StdoutPipe()
74 err = c.handleStderrAsEvents(c.cmd)
84 err = c.dialSSH(stdin, stdout)
89 c.conn = safcm.NewGobConn(stdout, stdin)
94 func (c *Conn) dialSSH(stdin io.Writer, stdout_ io.Reader) error {
95 stdout := bufio.NewReader(stdout_)
97 goos, err := connGetGoos(stdin, stdout)
101 goarch, err := connGetGoarch(stdin, stdout)
105 uid, err := connGetUID(stdin, stdout)
110 path := fmt.Sprintf("/tmp/safcm-remote-%d", uid)
112 c.debugf("DialSSH: probing remote at %q", path)
114 // Compatibility for different operating systems
119 dir_stat='drwxrwxrwt 0 0'
120 file_stat="-rwx------ $(id -u) $(id -g)"
122 stat -c '%A %u %g' "$1"
128 case "freebsd", "openbsd":
131 file_stat="100700 $(id -u) $(id -g)"
133 stat -f '%p %u %g' "$1"
140 return fmt.Errorf("internal error: no support for %q", goos)
143 // Use a function so the shell cannot execute the input line-wise.
144 // This is important because we're also using stdin to send data to
145 // the script. If the shell executes the input line-wise then our
146 // script is interpreted as input for `read`.
148 // The target directory must no permit other users to delete our files
149 // or symlink attacks and arbitrary code execution is possible. For
150 // /tmp this is guaranteed by the sticky bit. The code verifies the
151 // directory has the proper permissions.
153 // We cannot use `test -f && test -O` because this is open to TOCTOU
154 // attacks. `stat` gives use the full file state. If the file is owned
155 // by us and not a symlink then it's safe to use (assuming sticky
156 // directory or directory not writable by others).
158 // `test -e` is only used to prevent error messages if the file
159 // doesn't exist. It does not guard against any races.
160 _, err = fmt.Fprintf(stdin, `
165 dir="$(dirname "$x")"
166 if ! test "$(compat_stat "$dir")" = "$dir_stat"; then
167 echo "unsafe permissions on $dir, aborting" >&2
171 if test -e "$x" && test "$(compat_stat "$x")" = "$file_stat"; then
173 compat_sha512sum "$x"
175 # Empty checksum to request upload
179 # Wait for signal to continue
182 if test -n "$upload"; then
183 tmp="$(mktemp "$x.XXXXXX")"
184 # Report filename for upload
186 # Wait for upload to complete
189 # Safely create new file (ln does not follow symlinks)
193 # Make file executable
195 # Some BSD create files with group wheel in /tmp
196 chgrp "$(id -g)" "$x"
206 remoteSum, err := stdout.ReadString('\n')
211 // Get embedded helper binary
212 helper, err := remote.Helpers.ReadFile(
213 fmt.Sprintf("helpers/%s-%s", goos, goarch))
215 return fmt.Errorf("remote not built for GOOS/GOARCH %s/%s",
220 if remoteSum == "\n" {
222 c.debugf("DialSSH: remote not present or invalid permissions")
225 x := strings.Fields(remoteSum)
227 return fmt.Errorf("got unexpected checksum line %q",
230 sha := sha512.Sum512(helper)
231 hex := hex.EncodeToString(sha[:])
233 c.debugf("DialSSH: remote checksum matches")
236 c.debugf("DialSSH: remote checksum does not match")
241 // Notify user that an upload is going to take place.
242 c.events <- ConnEvent{
243 Type: ConnEventUpload,
246 // Tell script we want to upload a new file.
247 _, err = fmt.Fprintln(stdin, "upload")
251 // Get path to temporary file for upload.
253 // Write to the temporary file instead of the final path so
254 // that a concurrent run of this function won't use a
255 // partially written file. The rm in the script could still
256 // cause a missing file but at least no file with unknown
257 // content is executed.
258 path, err := stdout.ReadString('\n')
262 path = strings.TrimSuffix(path, "\n")
264 c.debugf("DialSSH: uploading new remote to %q at %q",
267 cmd := exec.Command("ssh",
268 append(append([]string{}, c.sshOpts...),
270 fmt.Sprintf("cat > %q", path))...)
271 cmd.Stdin = bytes.NewReader(helper)
272 err = c.handleStderrAsEvents(cmd) // cmd.Stderr
282 // Tell script to continue and execute the remote helper
283 _, err = fmt.Fprintln(stdin, "")
291 func connGetGoos(stdin io.Writer, stdout *bufio.Reader) (string, error) {
292 _, err := fmt.Fprintln(stdin, "uname")
296 x, err := stdout.ReadString('\n')
300 x = strings.TrimSpace(x)
302 // NOTE: Adapt helper uploading in dialSSH() when adding new systems
312 return "", fmt.Errorf("unsupported OS %q (`uname`)", x)
317 func connGetGoarch(stdin io.Writer, stdout *bufio.Reader) (string, error) {
318 _, err := fmt.Fprintln(stdin, "uname -m")
322 x, err := stdout.ReadString('\n')
326 x = strings.TrimSpace(x)
328 // NOTE: Adapt cmd/safcm-remote/build.sh when adding new architectures
331 case "x86_64", "amd64":
336 return "", fmt.Errorf("unsupported arch %q (`uname -m`)", x)
341 func connGetUID(stdin io.Writer, stdout *bufio.Reader) (int, error) {
342 _, err := fmt.Fprintln(stdin, "id -u")
346 x, err := stdout.ReadString('\n')
350 x = strings.TrimSpace(x)
352 uid, err := strconv.Atoi(x)
354 return -1, fmt.Errorf("invalid UID %q (`id -u`)", x)