|
| 1 | +package ssh |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "io/fs" |
| 8 | + "net" |
| 9 | + "os" |
| 10 | + "path/filepath" |
| 11 | + "sync" |
| 12 | + "syscall" |
| 13 | + |
| 14 | + gossh "golang.org/x/crypto/ssh" |
| 15 | +) |
| 16 | + |
| 17 | +const ( |
| 18 | + forwardedUnixChannelType = "[email protected]" |
| 19 | +) |
| 20 | + |
| 21 | +// directStreamLocalChannelData data struct as specified in OpenSSH's protocol |
| 22 | +// extensions document, Section 2.4. |
| 23 | +// https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL?annotate=HEAD |
| 24 | +type directStreamLocalChannelData struct { |
| 25 | + SocketPath string |
| 26 | + |
| 27 | + Reserved1 string |
| 28 | + Reserved2 uint32 |
| 29 | +} |
| 30 | + |
| 31 | +// DirectStreamLocalHandler provides Unix forwarding from client -> server. It |
| 32 | +// can be enabled by adding it to the server's ChannelHandlers under |
| 33 | + |
| 34 | +// |
| 35 | +// Unix socket support on Windows is not widely available, so this handler may |
| 36 | +// not work on all Windows installations and is not tested on Windows. |
| 37 | +func DirectStreamLocalHandler(srv *Server, _ *gossh.ServerConn, newChan gossh.NewChannel, ctx Context) { |
| 38 | + var d directStreamLocalChannelData |
| 39 | + err := gossh.Unmarshal(newChan.ExtraData(), &d) |
| 40 | + if err != nil { |
| 41 | + _ = newChan.Reject(gossh.ConnectionFailed, "error parsing direct-streamlocal data: "+err.Error()) |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + if srv.LocalUnixForwardingCallback == nil { |
| 46 | + _ = newChan.Reject(gossh.Prohibited, "unix forwarding is disabled") |
| 47 | + return |
| 48 | + } |
| 49 | + dconn, err := srv.LocalUnixForwardingCallback(ctx, d.SocketPath) |
| 50 | + if err != nil { |
| 51 | + if errors.Is(err, ErrRejected) { |
| 52 | + _ = newChan.Reject(gossh.Prohibited, "unix forwarding is disabled") |
| 53 | + return |
| 54 | + } |
| 55 | + _ = newChan.Reject(gossh.ConnectionFailed, fmt.Sprintf("dial unix socket %q: %+v", d.SocketPath, err.Error())) |
| 56 | + return |
| 57 | + } |
| 58 | + |
| 59 | + ch, reqs, err := newChan.Accept() |
| 60 | + if err != nil { |
| 61 | + _ = dconn.Close() |
| 62 | + return |
| 63 | + } |
| 64 | + go gossh.DiscardRequests(reqs) |
| 65 | + |
| 66 | + bicopy(ctx, ch, dconn) |
| 67 | +} |
| 68 | + |
| 69 | +// remoteUnixForwardRequest describes the extra data sent in a |
| 70 | +// [email protected] containing the socket path to bind to. |
| 71 | +type remoteUnixForwardRequest struct { |
| 72 | + SocketPath string |
| 73 | +} |
| 74 | + |
| 75 | +// remoteUnixForwardChannelData describes the data sent as the payload in the new |
| 76 | +// channel request when a Unix connection is accepted by the listener. |
| 77 | +type remoteUnixForwardChannelData struct { |
| 78 | + SocketPath string |
| 79 | + Reserved uint32 |
| 80 | +} |
| 81 | + |
| 82 | +// ForwardedUnixHandler can be enabled by creating a ForwardedUnixHandler and |
| 83 | +// adding the HandleSSHRequest callback to the server's RequestHandlers under |
| 84 | + |
| 85 | + |
| 86 | +// |
| 87 | +// Unix socket support on Windows is not widely available, so this handler may |
| 88 | +// not work on all Windows installations and is not tested on Windows. |
| 89 | +type ForwardedUnixHandler struct { |
| 90 | + sync.Mutex |
| 91 | + forwards map[string]net.Listener |
| 92 | +} |
| 93 | + |
| 94 | +func (h *ForwardedUnixHandler) HandleSSHRequest(ctx Context, srv *Server, req *gossh.Request) (bool, []byte) { |
| 95 | + h.Lock() |
| 96 | + if h.forwards == nil { |
| 97 | + h.forwards = make(map[string]net.Listener) |
| 98 | + } |
| 99 | + h.Unlock() |
| 100 | + conn, ok := ctx.Value(ContextKeyConn).(*gossh.ServerConn) |
| 101 | + if !ok { |
| 102 | + // TODO: log cast failure |
| 103 | + return false, nil |
| 104 | + } |
| 105 | + |
| 106 | + switch req.Type { |
| 107 | + |
| 108 | + var reqPayload remoteUnixForwardRequest |
| 109 | + err := gossh.Unmarshal(req.Payload, &reqPayload) |
| 110 | + if err != nil { |
| 111 | + // TODO: log parse failure |
| 112 | + return false, nil |
| 113 | + } |
| 114 | + |
| 115 | + if srv.ReverseUnixForwardingCallback == nil { |
| 116 | + return false, []byte("unix forwarding is disabled") |
| 117 | + } |
| 118 | + |
| 119 | + addr := reqPayload.SocketPath |
| 120 | + h.Lock() |
| 121 | + _, ok := h.forwards[addr] |
| 122 | + h.Unlock() |
| 123 | + if ok { |
| 124 | + // TODO: log failure |
| 125 | + return false, nil |
| 126 | + } |
| 127 | + |
| 128 | + ln, err := srv.ReverseUnixForwardingCallback(ctx, addr) |
| 129 | + if err != nil { |
| 130 | + if errors.Is(err, ErrRejected) { |
| 131 | + return false, []byte("unix forwarding is disabled") |
| 132 | + } |
| 133 | + // TODO: log unix listen failure |
| 134 | + return false, nil |
| 135 | + } |
| 136 | + |
| 137 | + // The listener needs to successfully start before it can be added to |
| 138 | + // the map, so we don't have to worry about checking for an existing |
| 139 | + // listener as you can't listen on the same socket twice. |
| 140 | + // |
| 141 | + // This is also what the TCP version of this code does. |
| 142 | + h.Lock() |
| 143 | + h.forwards[addr] = ln |
| 144 | + h.Unlock() |
| 145 | + |
| 146 | + ctx, cancel := context.WithCancel(ctx) |
| 147 | + go func() { |
| 148 | + <-ctx.Done() |
| 149 | + _ = ln.Close() |
| 150 | + }() |
| 151 | + go func() { |
| 152 | + defer cancel() |
| 153 | + |
| 154 | + for { |
| 155 | + c, err := ln.Accept() |
| 156 | + if err != nil { |
| 157 | + // closed below |
| 158 | + break |
| 159 | + } |
| 160 | + payload := gossh.Marshal(&remoteUnixForwardChannelData{ |
| 161 | + SocketPath: addr, |
| 162 | + }) |
| 163 | + |
| 164 | + go func() { |
| 165 | + ch, reqs, err := conn.OpenChannel(forwardedUnixChannelType, payload) |
| 166 | + if err != nil { |
| 167 | + _ = c.Close() |
| 168 | + return |
| 169 | + } |
| 170 | + go gossh.DiscardRequests(reqs) |
| 171 | + bicopy(ctx, ch, c) |
| 172 | + }() |
| 173 | + } |
| 174 | + |
| 175 | + h.Lock() |
| 176 | + ln2, ok := h.forwards[addr] |
| 177 | + if ok && ln2 == ln { |
| 178 | + delete(h.forwards, addr) |
| 179 | + } |
| 180 | + h.Unlock() |
| 181 | + _ = ln.Close() |
| 182 | + }() |
| 183 | + |
| 184 | + return true, nil |
| 185 | + |
| 186 | + |
| 187 | + var reqPayload remoteUnixForwardRequest |
| 188 | + err := gossh.Unmarshal(req.Payload, &reqPayload) |
| 189 | + if err != nil { |
| 190 | + // TODO: log parse failure |
| 191 | + return false, nil |
| 192 | + } |
| 193 | + h.Lock() |
| 194 | + ln, ok := h.forwards[reqPayload.SocketPath] |
| 195 | + h.Unlock() |
| 196 | + if ok { |
| 197 | + _ = ln.Close() |
| 198 | + } |
| 199 | + return true, nil |
| 200 | + |
| 201 | + default: |
| 202 | + return false, nil |
| 203 | + } |
| 204 | +} |
| 205 | + |
| 206 | +// unlink removes files and unlike os.Remove, directories are kept. |
| 207 | +func unlink(path string) error { |
| 208 | + // Ignore EINTR like os.Remove, see ignoringEINTR in os/file_posix.go |
| 209 | + // for more details. |
| 210 | + for { |
| 211 | + err := syscall.Unlink(path) |
| 212 | + if !errors.Is(err, syscall.EINTR) { |
| 213 | + return err |
| 214 | + } |
| 215 | + } |
| 216 | +} |
| 217 | + |
| 218 | +// SimpleUnixLocalForwardingCallback provides a basic implementation for |
| 219 | +// LocalUnixForwardingCallback. It will simply dial the requested socket using |
| 220 | +// a context-aware dialer. |
| 221 | +func SimpleUnixLocalForwardingCallback(ctx Context, socketPath string) (net.Conn, error) { |
| 222 | + var d net.Dialer |
| 223 | + return d.DialContext(ctx, "unix", socketPath) |
| 224 | +} |
| 225 | + |
| 226 | +// SimpleUnixReverseForwardingCallback provides a basic implementation for |
| 227 | +// ReverseUnixForwardingCallback. The parent directory will be created (with |
| 228 | +// os.MkdirAll), and existing files with the same name will be removed. |
| 229 | +func SimpleUnixReverseForwardingCallback(_ Context, socketPath string) (net.Listener, error) { |
| 230 | + // Create socket parent dir if not exists. |
| 231 | + parentDir := filepath.Dir(socketPath) |
| 232 | + err := os.MkdirAll(parentDir, 0700) |
| 233 | + if err != nil { |
| 234 | + return nil, fmt.Errorf("failed to create parent directory %q for socket %q: %w", parentDir, socketPath, err) |
| 235 | + } |
| 236 | + |
| 237 | + // Remove existing socket if it exists. We do not use os.Remove() here |
| 238 | + // so that directories are kept. Note that it's possible that we will |
| 239 | + // overwrite a regular file here. Both of these behaviors match OpenSSH, |
| 240 | + // however, which is why we unlink. |
| 241 | + err = unlink(socketPath) |
| 242 | + if err != nil && !errors.Is(err, fs.ErrNotExist) { |
| 243 | + return nil, fmt.Errorf("failed to remove existing file in socket path %q: %w", socketPath, err) |
| 244 | + } |
| 245 | + |
| 246 | + ln, err := net.Listen("unix", socketPath) |
| 247 | + if err != nil { |
| 248 | + return nil, fmt.Errorf("failed to listen on unix socket %q: %w", socketPath, err) |
| 249 | + } |
| 250 | + |
| 251 | + return ln, err |
| 252 | +} |
0 commit comments