gateway.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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. return nil, fmt.Errorf("internal error")
  69. }
  70. user, ok := authorizedKeysMap[string(key.Marshal())]
  71. if !ok {
  72. return nil, fmt.Errorf("unknown public key for remoteAddr %q", conn.RemoteAddr())
  73. }
  74. return &ssh.Permissions{
  75. Extensions: map[string]string{
  76. "user": user,
  77. },
  78. }, nil
  79. }
  80. ln, err := net.Listen("tcp", net.JoinHostPort(bindAddr, strconv.Itoa(cfg.BindPort)))
  81. if err != nil {
  82. return nil, err
  83. }
  84. return &Gateway{
  85. bindPort: cfg.BindPort,
  86. ln: ln,
  87. peerServerListener: peerServerListener,
  88. sshConfig: sshConfig,
  89. }, nil
  90. }
  91. func (g *Gateway) Run() {
  92. for {
  93. conn, err := g.ln.Accept()
  94. if err != nil {
  95. return
  96. }
  97. go g.handleConn(conn)
  98. }
  99. }
  100. func (g *Gateway) handleConn(conn net.Conn) {
  101. defer conn.Close()
  102. ts, err := NewTunnelServer(conn, g.sshConfig, g.peerServerListener)
  103. if err != nil {
  104. return
  105. }
  106. if err := ts.Run(); err != nil {
  107. log.Error("ssh tunnel server run error: %v", err)
  108. }
  109. }
  110. func loadAuthorizedKeysFromFile(path string) (map[string]string, error) {
  111. authorizedKeysMap := make(map[string]string) // value is username
  112. authorizedKeysBytes, err := os.ReadFile(path)
  113. if err != nil {
  114. return nil, err
  115. }
  116. for len(authorizedKeysBytes) > 0 {
  117. pubKey, comment, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes)
  118. if err != nil {
  119. return nil, err
  120. }
  121. authorizedKeysMap[string(pubKey.Marshal())] = strings.TrimSpace(comment)
  122. authorizedKeysBytes = rest
  123. }
  124. return authorizedKeysMap, nil
  125. }