gateway.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. // Copyright 2023 The frp Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  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. package ssh
  15. import (
  16. "fmt"
  17. "net"
  18. "os"
  19. "strconv"
  20. "strings"
  21. "golang.org/x/crypto/ssh"
  22. v1 "github.com/fatedier/frp/pkg/config/v1"
  23. "github.com/fatedier/frp/pkg/transport"
  24. "github.com/fatedier/frp/pkg/util/log"
  25. netpkg "github.com/fatedier/frp/pkg/util/net"
  26. )
  27. type Gateway struct {
  28. bindPort int
  29. ln net.Listener
  30. peerServerListener *netpkg.InternalListener
  31. sshConfig *ssh.ServerConfig
  32. }
  33. func NewGateway(
  34. cfg v1.SSHTunnelGateway, bindAddr string,
  35. peerServerListener *netpkg.InternalListener,
  36. ) (*Gateway, error) {
  37. sshConfig := &ssh.ServerConfig{}
  38. // privateKey
  39. var (
  40. privateKeyBytes []byte
  41. err error
  42. )
  43. if cfg.PrivateKeyFile != "" {
  44. privateKeyBytes, err = os.ReadFile(cfg.PrivateKeyFile)
  45. } else {
  46. if cfg.AutoGenPrivateKeyPath != "" {
  47. privateKeyBytes, _ = os.ReadFile(cfg.AutoGenPrivateKeyPath)
  48. }
  49. if len(privateKeyBytes) == 0 {
  50. privateKeyBytes, err = transport.NewRandomPrivateKey()
  51. if err == nil && cfg.AutoGenPrivateKeyPath != "" {
  52. err = os.WriteFile(cfg.AutoGenPrivateKeyPath, privateKeyBytes, 0o600)
  53. }
  54. }
  55. }
  56. if err != nil {
  57. return nil, err
  58. }
  59. privateKey, err := ssh.ParsePrivateKey(privateKeyBytes)
  60. if err != nil {
  61. return nil, err
  62. }
  63. sshConfig.AddHostKey(privateKey)
  64. sshConfig.NoClientAuth = cfg.AuthorizedKeysFile == ""
  65. sshConfig.PublicKeyCallback = func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  66. authorizedKeysMap, err := loadAuthorizedKeysFromFile(cfg.AuthorizedKeysFile)
  67. if err != nil {
  68. log.Errorf("load authorized keys file error: %v", err)
  69. return nil, fmt.Errorf("internal error")
  70. }
  71. user, ok := authorizedKeysMap[string(key.Marshal())]
  72. if !ok {
  73. return nil, fmt.Errorf("unknown public key for remoteAddr %q", conn.RemoteAddr())
  74. }
  75. return &ssh.Permissions{
  76. Extensions: map[string]string{
  77. "user": user,
  78. },
  79. }, nil
  80. }
  81. ln, err := net.Listen("tcp", net.JoinHostPort(bindAddr, strconv.Itoa(cfg.BindPort)))
  82. if err != nil {
  83. return nil, err
  84. }
  85. return &Gateway{
  86. bindPort: cfg.BindPort,
  87. ln: ln,
  88. peerServerListener: peerServerListener,
  89. sshConfig: sshConfig,
  90. }, nil
  91. }
  92. func (g *Gateway) Run() {
  93. for {
  94. conn, err := g.ln.Accept()
  95. if err != nil {
  96. return
  97. }
  98. go g.handleConn(conn)
  99. }
  100. }
  101. func (g *Gateway) handleConn(conn net.Conn) {
  102. defer conn.Close()
  103. ts, err := NewTunnelServer(conn, g.sshConfig, g.peerServerListener)
  104. if err != nil {
  105. return
  106. }
  107. if err := ts.Run(); err != nil {
  108. log.Errorf("ssh tunnel server run error: %v", err)
  109. }
  110. }
  111. func loadAuthorizedKeysFromFile(path string) (map[string]string, error) {
  112. authorizedKeysMap := make(map[string]string) // value is username
  113. authorizedKeysBytes, err := os.ReadFile(path)
  114. if err != nil {
  115. return nil, err
  116. }
  117. for len(authorizedKeysBytes) > 0 {
  118. pubKey, comment, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes)
  119. if err != nil {
  120. return nil, err
  121. }
  122. authorizedKeysMap[string(pubKey.Marshal())] = strings.TrimSpace(comment)
  123. authorizedKeysBytes = rest
  124. }
  125. return authorizedKeysMap, nil
  126. }