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 func (c *Conn) DialSSH(user, host string) error {
37 return fmt.Errorf("cannot reuse Conn")
42 remote = user + "@" + host
44 c.debugf("DialSSH: connecting to %q", remote)
48 // Help debugging by showing executed shell commands
51 c.cmd = exec.Command("ssh", remote, "/bin/sh", opts)
54 stdin, err := c.cmd.StdinPipe()
58 stdout, err := c.cmd.StdoutPipe()
62 err = c.handleStderrAsEvents(c.cmd)
72 err = c.dialSSH(stdin, stdout)
77 c.conn = safcm.NewGobConn(stdout, stdin)
82 func (c *Conn) dialSSH(stdin io.Writer, stdout_ io.Reader) error {
83 stdout := bufio.NewReader(stdout_)
85 goos, err := connGetGoos(stdin, stdout)
89 goarch, err := connGetGoarch(stdin, stdout)
93 uid, err := connGetUID(stdin, stdout)
98 path := fmt.Sprintf("/tmp/safcm-remote-%d", uid)
100 c.debugf("DialSSH: probing remote at %q", path)
102 // Compatibility for different operating systems
107 dir_stat='drwxrwxrwt 0 0'
108 file_stat="-rwx------ $(id -u) $(id -g)"
110 stat -c '%A %u %g' "$1"
117 return fmt.Errorf("internal error: no support for %q", goos)
120 // Use a function so the shell cannot execute the input line-wise.
121 // This is important because we're also using stdin to send data to
122 // the script. If the shell executes the input line-wise then our
123 // script is interpreted as input for `read`.
125 // The target directory must no permit other users to delete our files
126 // or symlink attacks and arbitrary code execution is possible. For
127 // /tmp this is guaranteed by the sticky bit. Make sure it has the
128 // proper permissions.
130 // We cannot use `test -f && test -O` because this is open to TOCTOU
131 // attacks. `stat` gives use the full file state. If the file is owned
132 // by us and not a symlink then it's safe to use (assuming sticky or
133 // directory not writable by others).
135 // `test -e` is only used to prevent error messages if the file
136 // doesn't exist. It does not guard against any races.
137 _, err = fmt.Fprintf(stdin, `
142 dir="$(dirname "$x")"
143 if ! test "$(compat_stat "$dir")" = "$dir_stat"; then
144 echo "unsafe permissions on $dir, aborting" >&2
148 if test -e "$x" && test "$(compat_stat "$x")" = "$file_stat"; then
150 compat_sha512sum "$x"
152 # Empty checksum to request upload
156 # Wait for signal to continue
159 if test -n "$upload"; then
160 tmp="$(mktemp "$x.XXXXXX")"
161 # Report filename for upload
164 # Wait for upload to complete
167 # Safely create new file (ln does not follow symlinks)
171 # Make file executable
182 remoteSum, err := stdout.ReadString('\n')
187 // Get embedded helper binary
188 helper, err := remote.Helpers.ReadFile(
189 fmt.Sprintf("helpers/%s-%s", goos, goarch))
191 return fmt.Errorf("remote not built for GOOS/GOARCH %s/%s",
196 if remoteSum == "\n" {
198 c.debugf("DialSSH: remote not present or invalid permissions")
201 x := strings.Fields(remoteSum)
203 return fmt.Errorf("got unexpected checksum line %q",
206 sha := sha512.Sum512(helper)
207 hex := hex.EncodeToString(sha[:])
209 c.debugf("DialSSH: remote checksum matches")
212 c.debugf("DialSSH: remote checksum does not match")
217 // Notify user that an upload is going to take place.
218 c.events <- ConnEvent{
219 Type: ConnEventUpload,
222 // Tell script we want to upload a new file.
223 _, err = fmt.Fprintln(stdin, "upload")
227 // Get path to temporary file for upload.
229 // Write to the temporary file instead of the final path so
230 // that a concurrent run of this function won't use a
231 // partially written file. The rm in the script could still
232 // cause a missing file but at least no file with unknown
233 // content is executed.
234 path, err := stdout.ReadString('\n')
238 path = strings.TrimSuffix(path, "\n")
240 c.debugf("DialSSH: uploading new remote to %q at %q",
243 cmd := exec.Command("ssh", c.remote,
244 fmt.Sprintf("cat > %q", path))
245 cmd.Stdin = bytes.NewReader(helper)
246 err = c.handleStderrAsEvents(cmd)
256 // Tell script to continue and execute the remote helper
257 _, err = fmt.Fprintln(stdin, "")
265 func connGetGoos(stdin io.Writer, stdout *bufio.Reader) (string, error) {
266 _, err := fmt.Fprintln(stdin, "uname -o")
270 x, err := stdout.ReadString('\n')
274 x = strings.TrimSpace(x)
276 // NOTE: Adapt helper uploading in dialSSH() when adding new systems
282 return "", fmt.Errorf("unsupported OS %q (`uname -o`)", x)
287 func connGetGoarch(stdin io.Writer, stdout *bufio.Reader) (string, error) {
288 _, err := fmt.Fprintln(stdin, "uname -m")
292 x, err := stdout.ReadString('\n')
296 x = strings.TrimSpace(x)
298 // NOTE: Adapt cmd/safcm-remote/build.sh when adding new architectures
306 return "", fmt.Errorf("unsupported arch %q (`uname -m`)", x)
311 func connGetUID(stdin io.Writer, stdout *bufio.Reader) (int, error) {
312 _, err := fmt.Fprintln(stdin, "id -u")
316 x, err := stdout.ReadString('\n')
320 x = strings.TrimSpace(x)
322 uid, err := strconv.Atoi(x)
324 return -1, fmt.Errorf("invalid UID %q (`id -u`)", x)