| // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | package ssh |
| 16 |
| 17 | import ( |
| 18 | "context" |
| 19 | "encoding/binary" |
| 20 | "errors" |
| 21 | "fmt" |
| 22 | "net" |
| 23 | "slices" |
| 24 | "strings" |
| 25 | "sync" |
| 26 | "time" |
| 27 |
| 28 | libio "github.com/fatedier/golib/io" |
| 29 | "github.com/spf13/cobra" |
| 30 | flag "github.com/spf13/pflag" |
| 31 | "golang.org/x/crypto/ssh" |
| 32 |
| 33 | "github.com/fatedier/frp/client/proxy" |
| 34 | "github.com/fatedier/frp/pkg/config" |
| 35 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 36 | "github.com/fatedier/frp/pkg/msg" |
| 37 | "github.com/fatedier/frp/pkg/util/log" |
| 38 | netpkg "github.com/fatedier/frp/pkg/util/net" |
| 39 | "github.com/fatedier/frp/pkg/util/util" |
| 40 | "github.com/fatedier/frp/pkg/util/xlog" |
| 41 | "github.com/fatedier/frp/pkg/virtual" |
| 42 | ) |
| 43 |
| 44 | const ( |
| 45 | // https://datatracker.ietf.org/doc/html/rfc4254#page-16 |
| 46 | ChannelTypeServerOpenChannel = "forwarded-tcpip" |
| 47 | RequestTypeForward = "tcpip-forward" |
| 48 | ) |
| 49 |
| 50 | type tcpipForward struct { |
| 51 | Host string |
| 52 | Port uint32 |
| 53 | } |
| 54 |
| 55 | // https://datatracker.ietf.org/doc/html/rfc4254#page-16 |
| 56 | type forwardedTCPPayload struct { |
| 57 | Addr string |
| 58 | Port uint32 |
| 59 |
| 60 | OriginAddr string |
| 61 | OriginPort uint32 |
| 62 | } |
| 63 |
| 64 | type TunnelServer struct { |
| 65 | underlyingConn net.Conn |
| 66 | sshConn *ssh.ServerConn |
| 67 | sc *ssh.ServerConfig |
| 68 | firstChannel ssh.Channel |
| 69 |
| 70 | vc *virtual.Client |
| 71 | peerServerListener *netpkg.InternalListener |
| 72 | doneCh chan struct{} |
| 73 | closeDoneChOnce sync.Once |
| 74 | } |
| 75 |
| 76 | func NewTunnelServer(conn net.Conn, sc *ssh.ServerConfig, peerServerListener *netpkg.InternalListener) (*TunnelServer, error) { |
| 77 | s := &TunnelServer{ |
| 78 | underlyingConn: conn, |
| 79 | sc: sc, |
| 80 | peerServerListener: peerServerListener, |
| 81 | doneCh: make(chan struct{}), |
| 82 | } |
| 83 | return s, nil |
| 84 | } |
| 85 |
| 86 | func (s *TunnelServer) Run() error { |
| 87 | sshConn, channels, requests, err := ssh.NewServerConn(s.underlyingConn, s.sc) |
| 88 | if err != nil { |
| 89 | return err |
| 90 | } |
| 91 |
| 92 | s.sshConn = sshConn |
| 93 |
| 94 | addr, extraPayload, err := s.waitForwardAddrAndExtraPayload(channels, requests, 3*time.Second) |
| 95 | if err != nil { |
| 96 | return err |
| 97 | } |
| 98 |
| 99 | clientCfg, pc, helpMessage, err := s.parseClientAndProxyConfigurer(addr, extraPayload) |
| 100 | if err != nil { |
| 101 | if errors.Is(err, flag.ErrHelp) { |
| 102 | s.writeToClient(helpMessage) |
| 103 | return nil |
| 104 | } |
| 105 | s.writeToClient(err.Error()) |
| 106 | return fmt.Errorf("parse flags from ssh client error: %v", err) |
| 107 | } |
| 108 | if err := clientCfg.Complete(); err != nil { |
| 109 | s.writeToClient(fmt.Sprintf("failed to complete client config: %v", err)) |
| 110 | return fmt.Errorf("complete client config error: %v", err) |
| 111 | } |
| 112 | if sshConn.Permissions != nil { |
| 113 | clientCfg.User = util.EmptyOr(sshConn.Permissions.Extensions["user"], clientCfg.User) |
| 114 | } |
| 115 | pc.Complete() |
| 116 |
| 117 | vc, err := virtual.NewClient(virtual.ClientOptions{ |
| 118 | Common: clientCfg, |
| 119 | Spec: &msg.ClientSpec{ |
| 120 | Type: "ssh-tunnel", |
| 121 | // If ssh does not require authentication, then the virtual client needs to authenticate through a token. |
| 122 | // Otherwise, once ssh authentication is passed, the virtual client does not need to authenticate again. |
| 123 | AlwaysAuthPass: !s.sc.NoClientAuth, |
| 124 | }, |
| 125 | HandleWorkConnCb: func(base *v1.ProxyBaseConfig, workConn net.Conn, m *msg.StartWorkConn) bool { |
| 126 | // join workConn and ssh channel |
| 127 | c, err := s.openConn(addr) |
| 128 | if err != nil { |
| 129 | log.Tracef("open conn error: %v", err) |
| 130 | workConn.Close() |
| 131 | return false |
| 132 | } |
| 133 | libio.Join(c, workConn) |
| 134 | return false |
| 135 | }, |
| 136 | }) |
| 137 | if err != nil { |
| 138 | return err |
| 139 | } |
| 140 | s.vc = vc |
| 141 |
| 142 | // transfer connection from virtual client to server peer listener |
| 143 | go func() { |
| 144 | l := s.vc.PeerListener() |
| 145 | for { |
| 146 | conn, err := l.Accept() |
| 147 | if err != nil { |
| 148 | return |
| 149 | } |
| 150 | _ = s.peerServerListener.PutConn(conn) |
| 151 | } |
| 152 | }() |
| 153 | xl := xlog.New().AddPrefix(xlog.LogPrefix{Name: "sshVirtualClient", Value: "sshVirtualClient", Priority: 100}) |
| 154 | ctx := xlog.NewContext(context.Background(), xl) |
| 155 | go func() { |
| 156 | vcErr := s.vc.Run(ctx) |
| 157 | if vcErr != nil { |
| 158 | s.writeToClient(vcErr.Error()) |
| 159 | } |
| 160 |
| 161 | // If vc.Run returns, it means that the virtual client has been closed, and the ssh tunnel connection should be closed. |
| 162 | // One scenario is that the virtual client exits due to login failure. |
| 163 | s.closeDoneChOnce.Do(func() { |
| 164 | _ = sshConn.Close() |
| 165 | close(s.doneCh) |
| 166 | }) |
| 167 | }() |
| 168 |
| 169 | s.vc.UpdateProxyConfigurer([]v1.ProxyConfigurer{pc}) |
| 170 |
| 171 | if ps, err := s.waitProxyStatusReady(pc.GetBaseConfig().Name, time.Second); err != nil { |
| 172 | s.writeToClient(err.Error()) |
| 173 | log.Warnf("wait proxy status ready error: %v", err) |
| 174 | } else { |
| 175 | // success |
| 176 | s.writeToClient(createSuccessInfo(clientCfg.User, pc, ps)) |
| 177 | _ = sshConn.Wait() |
| 178 | } |
| 179 |
| 180 | s.vc.Close() |
| 181 | log.Tracef("ssh tunnel connection from %v closed", sshConn.RemoteAddr()) |
| 182 | s.closeDoneChOnce.Do(func() { |
| 183 | _ = sshConn.Close() |
| 184 | close(s.doneCh) |
| 185 | }) |
| 186 | return nil |
| 187 | } |
| 188 |
| 189 | func (s *TunnelServer) writeToClient(data string) { |
| 190 | if s.firstChannel == nil { |
| 191 | return |
| 192 | } |
| 193 | _, _ = s.firstChannel.Write([]byte(data + "\n")) |
| 194 | } |
| 195 |
| 196 | func (s *TunnelServer) waitForwardAddrAndExtraPayload( |
| 197 | channels <-chan ssh.NewChannel, |
| 198 | requests <-chan *ssh.Request, |
| 199 | timeout time.Duration, |
| 200 | ) (*tcpipForward, string, error) { |
| 201 | addrCh := make(chan *tcpipForward, 1) |
| 202 | extraPayloadCh := make(chan string, 1) |
| 203 |
| 204 | // get forward address |
| 205 | go func() { |
| 206 | addrGot := false |
| 207 | for req := range requests { |
| 208 | if req.Type == RequestTypeForward && !addrGot { |
| 209 | payload := tcpipForward{} |
| 210 | if err := ssh.Unmarshal(req.Payload, &payload); err != nil { |
| 211 | return |
| 212 | } |
| 213 | addrGot = true |
| 214 | addrCh <- &payload |
| 215 | } |
| 216 | if req.WantReply { |
| 217 | _ = req.Reply(true, nil) |
| 218 | } |
| 219 | } |
| 220 | }() |
| 221 |
| 222 | // get extra payload |
| 223 | go func() { |
| 224 | for newChannel := range channels { |
| 225 | // extraPayload will send to extraPayloadCh |
| 226 | go s.handleNewChannel(newChannel, extraPayloadCh) |
| 227 | } |
| 228 | }() |
| 229 |
| 230 | var ( |
| 231 | addr *tcpipForward |
| 232 | extraPayload string |
| 233 | ) |
| 234 |
| 235 | timer := time.NewTimer(timeout) |
| 236 | defer timer.Stop() |
| 237 | for { |
| 238 | select { |
| 239 | case v := <-addrCh: |
| 240 | addr = v |
| 241 | case extra := <-extraPayloadCh: |
| 242 | extraPayload = extra |
| 243 | case <-timer.C: |
| 244 | return nil, "", fmt.Errorf("get addr and extra payload timeout") |
| 245 | } |
| 246 | if addr != nil && extraPayload != "" { |
| 247 | break |
| 248 | } |
| 249 | } |
| 250 | return addr, extraPayload, nil |
| 251 | } |
| 252 |
| 253 | func (s *TunnelServer) parseClientAndProxyConfigurer(_ *tcpipForward, extraPayload string) (*v1.ClientCommonConfig, v1.ProxyConfigurer, string, error) { |
| 254 | helpMessage := "" |
| 255 | cmd := &cobra.Command{ |
| 256 | Use: "ssh v0@{address} [command]", |
| 257 | Short: "ssh v0@{address} [command]", |
| 258 | Run: func(*cobra.Command, []string) {}, |
| 259 | } |
| 260 | cmd.SetGlobalNormalizationFunc(config.WordSepNormalizeFunc) |
| 261 |
| 262 | args := strings.Split(extraPayload, " ") |
| 263 | if len(args) < 1 { |
| 264 | return nil, nil, helpMessage, fmt.Errorf("invalid extra payload") |
| 265 | } |
| 266 | proxyType := strings.TrimSpace(args[0]) |
| 267 | supportTypes := []string{"tcp", "http", "https", "tcpmux", "stcp"} |
| 268 | if !slices.Contains(supportTypes, proxyType) { |
| 269 | return nil, nil, helpMessage, fmt.Errorf("invalid proxy type: %s, support types: %v", proxyType, supportTypes) |
| 270 | } |
| 271 | pc := v1.NewProxyConfigurerByType(v1.ProxyType(proxyType)) |
| 272 | if pc == nil { |
| 273 | return nil, nil, helpMessage, fmt.Errorf("new proxy configurer error") |
| 274 | } |
| 275 | config.RegisterProxyFlags(cmd, pc, config.WithSSHMode()) |
| 276 |
| 277 | clientCfg := v1.ClientCommonConfig{} |
| 278 | config.RegisterClientCommonConfigFlags(cmd, &clientCfg, config.WithSSHMode()) |
| 279 |
| 280 | cmd.InitDefaultHelpCmd() |
| 281 | if err := cmd.ParseFlags(args); err != nil { |
| 282 | if errors.Is(err, flag.ErrHelp) { |
| 283 | helpMessage = cmd.UsageString() |
| 284 | } |
| 285 | return nil, nil, helpMessage, err |
| 286 | } |
| 287 | // if name is not set, generate a random one |
| 288 | if pc.GetBaseConfig().Name == "" { |
| 289 | id, err := util.RandIDWithLen(8) |
| 290 | if err != nil { |
| 291 | return nil, nil, helpMessage, fmt.Errorf("generate random id error: %v", err) |
| 292 | } |
| 293 | pc.GetBaseConfig().Name = fmt.Sprintf("sshtunnel-%s-%s", proxyType, id) |
| 294 | } |
| 295 | return &clientCfg, pc, helpMessage, nil |
| 296 | } |
| 297 |
| 298 | func (s *TunnelServer) handleNewChannel(channel ssh.NewChannel, extraPayloadCh chan string) { |
| 299 | ch, reqs, err := channel.Accept() |
| 300 | if err != nil { |
| 301 | return |
| 302 | } |
| 303 | if s.firstChannel == nil { |
| 304 | s.firstChannel = ch |
| 305 | } |
| 306 | go s.keepAlive(ch) |
| 307 |
| 308 | for req := range reqs { |
| 309 | if req.WantReply { |
| 310 | _ = req.Reply(true, nil) |
| 311 | } |
| 312 | if req.Type != "exec" || len(req.Payload) <= 4 { |
| 313 | continue |
| 314 | } |
| 315 | end := 4 + binary.BigEndian.Uint32(req.Payload[:4]) |
| 316 | if len(req.Payload) < int(end) { |
| 317 | continue |
| 318 | } |
| 319 | extraPayload := string(req.Payload[4:end]) |
| 320 | select { |
| 321 | case extraPayloadCh <- extraPayload: |
| 322 | default: |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 |
| 327 | func (s *TunnelServer) keepAlive(ch ssh.Channel) { |
| 328 | tk := time.NewTicker(time.Second * 30) |
| 329 | defer tk.Stop() |
| 330 |
| 331 | for { |
| 332 | select { |
| 333 | case <-tk.C: |
| 334 | _, err := ch.SendRequest("heartbeat", false, nil) |
| 335 | if err != nil { |
| 336 | return |
| 337 | } |
| 338 | case <-s.doneCh: |
| 339 | return |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 |
| 344 | func (s *TunnelServer) openConn(addr *tcpipForward) (net.Conn, error) { |
| 345 | payload := forwardedTCPPayload{ |
| 346 | Addr: addr.Host, |
| 347 | Port: addr.Port, |
| 348 | // Note: Here is just for compatibility, not the real source address. |
| 349 | OriginAddr: addr.Host, |
| 350 | OriginPort: addr.Port, |
| 351 | } |
| 352 | channel, reqs, err := s.sshConn.OpenChannel(ChannelTypeServerOpenChannel, ssh.Marshal(&payload)) |
| 353 | if err != nil { |
| 354 | return nil, fmt.Errorf("open ssh channel error: %v", err) |
| 355 | } |
| 356 | go ssh.DiscardRequests(reqs) |
| 357 |
| 358 | conn := netpkg.WrapReadWriteCloserToConn(channel, s.underlyingConn) |
| 359 | return conn, nil |
| 360 | } |
| 361 |
| 362 | func (s *TunnelServer) waitProxyStatusReady(name string, timeout time.Duration) (*proxy.WorkingStatus, error) { |
| 363 | ticker := time.NewTicker(100 * time.Millisecond) |
| 364 | defer ticker.Stop() |
| 365 |
| 366 | timer := time.NewTimer(timeout) |
| 367 | defer timer.Stop() |
| 368 |
| 369 | statusExporter := s.vc.Service().StatusExporter() |
| 370 |
| 371 | for { |
| 372 | select { |
| 373 | case <-ticker.C: |
| 374 | ps, ok := statusExporter.GetProxyStatus(name) |
| 375 | if !ok { |
| 376 | continue |
| 377 | } |
| 378 | switch ps.Phase { |
| 379 | case proxy.ProxyPhaseRunning: |
| 380 | return ps, nil |
| 381 | case proxy.ProxyPhaseStartErr, proxy.ProxyPhaseClosed: |
| 382 | return ps, errors.New(ps.Err) |
| 383 | } |
| 384 | case <-timer.C: |
| 385 | return nil, fmt.Errorf("wait proxy status ready timeout") |
| 386 | case <-s.doneCh: |
| 387 | return nil, fmt.Errorf("ssh tunnel server closed") |
| 388 | } |
| 389 | } |
| 390 | } |