sshprox.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. package sshprox
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "net/url"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "runtime"
  12. "strconv"
  13. "strings"
  14. "github.com/google/uuid"
  15. "imuslab.com/zoraxy/mod/reverseproxy"
  16. "imuslab.com/zoraxy/mod/utils"
  17. "imuslab.com/zoraxy/mod/websocketproxy"
  18. )
  19. /*
  20. SSH Proxy
  21. This is a tool to bind gotty into Zoraxy
  22. so that you can do something similar to
  23. online ssh terminal
  24. */
  25. type Manager struct {
  26. StartingPort int
  27. Instances []*Instance
  28. }
  29. type Instance struct {
  30. UUID string
  31. ExecPath string
  32. RemoteAddr string
  33. RemotePort int
  34. AssignedPort int
  35. conn *reverseproxy.ReverseProxy //HTTP proxy
  36. tty *exec.Cmd //SSH connection ported to web interface
  37. Parent *Manager
  38. }
  39. func NewSSHProxyManager() *Manager {
  40. return &Manager{
  41. StartingPort: 14810,
  42. Instances: []*Instance{},
  43. }
  44. }
  45. // Get the next free port in the list
  46. func (m *Manager) GetNextPort() int {
  47. nextPort := m.StartingPort
  48. occupiedPort := make(map[int]bool)
  49. for _, instance := range m.Instances {
  50. occupiedPort[instance.AssignedPort] = true
  51. }
  52. for {
  53. if !occupiedPort[nextPort] {
  54. return nextPort
  55. }
  56. nextPort++
  57. }
  58. }
  59. func (m *Manager) HandleHttpByInstanceId(instanceId string, w http.ResponseWriter, r *http.Request) {
  60. targetInstance, err := m.GetInstanceById(instanceId)
  61. if err != nil {
  62. http.Error(w, err.Error(), http.StatusNotFound)
  63. return
  64. }
  65. if targetInstance.tty == nil {
  66. //Server side already closed
  67. http.Error(w, "Connection already closed", http.StatusInternalServerError)
  68. return
  69. }
  70. r.Header.Set("X-Forwarded-Host", r.Host)
  71. requestURL := r.URL.String()
  72. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  73. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  74. r.Header.Set("Zr-Origin-Upgrade", "websocket")
  75. requestURL = strings.TrimPrefix(requestURL, "/")
  76. u, _ := url.Parse("ws://127.0.0.1:" + strconv.Itoa(targetInstance.AssignedPort) + "/" + requestURL)
  77. wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
  78. SkipTLSValidation: false,
  79. SkipOriginCheck: false,
  80. Logger: nil,
  81. })
  82. wspHandler.ServeHTTP(w, r)
  83. return
  84. }
  85. targetInstance.conn.ProxyHTTP(w, r)
  86. }
  87. func (m *Manager) GetInstanceById(instanceId string) (*Instance, error) {
  88. for _, instance := range m.Instances {
  89. if instance.UUID == instanceId {
  90. return instance, nil
  91. }
  92. }
  93. return nil, fmt.Errorf("instance not found: %s", instanceId)
  94. }
  95. func (m *Manager) NewSSHProxy(binaryRoot string) (*Instance, error) {
  96. //Check if the binary exists in system/gotty/
  97. binary := "gotty_" + runtime.GOOS + "_" + runtime.GOARCH
  98. if runtime.GOOS == "windows" {
  99. binary = binary + ".exe"
  100. }
  101. //Extract it from embedfs if not exists locally
  102. execPath := filepath.Join(binaryRoot, binary)
  103. //Create the storage folder structure
  104. os.MkdirAll(filepath.Dir(execPath), 0775)
  105. //Create config file if not exists
  106. if !utils.FileExists(filepath.Join(filepath.Dir(execPath), ".gotty")) {
  107. configFile, _ := gotty.ReadFile("gotty/.gotty")
  108. os.WriteFile(filepath.Join(filepath.Dir(execPath), ".gotty"), configFile, 0775)
  109. }
  110. //Create web.ssh binary if not exists
  111. if !utils.FileExists(execPath) {
  112. //Try to extract it from embedded fs
  113. executable, err := gotty.ReadFile("gotty/" + binary)
  114. if err != nil {
  115. //Binary not found in embedded
  116. return nil, errors.New("platform not supported")
  117. }
  118. //Extract to target location
  119. err = os.WriteFile(execPath, executable, 0777)
  120. if err != nil {
  121. //Binary not found in embedded
  122. log.Println("Extract web.ssh failed: " + err.Error())
  123. return nil, errors.New("web.ssh sub-program extract failed")
  124. }
  125. }
  126. //Convert the binary path to realpath
  127. realpath, err := filepath.Abs(execPath)
  128. if err != nil {
  129. return nil, err
  130. }
  131. thisInstance := Instance{
  132. UUID: uuid.New().String(),
  133. ExecPath: realpath,
  134. AssignedPort: -1,
  135. Parent: m,
  136. }
  137. m.Instances = append(m.Instances, &thisInstance)
  138. return &thisInstance, nil
  139. }
  140. // Create a new Connection to target address
  141. func (i *Instance) CreateNewConnection(listenPort int, username string, remoteIpAddr string, remotePort int) error {
  142. //Create a gotty instance
  143. connAddr := remoteIpAddr
  144. if username != "" {
  145. connAddr = username + "@" + remoteIpAddr
  146. }
  147. configPath := filepath.Join(filepath.Dir(i.ExecPath), ".gotty")
  148. title := username + "@" + remoteIpAddr
  149. if remotePort != 22 {
  150. title = title + ":" + strconv.Itoa(remotePort)
  151. }
  152. sshCommand := []string{"ssh", "-t", connAddr, "-p", strconv.Itoa(remotePort)}
  153. cmd := exec.Command(i.ExecPath, "-w", "-p", strconv.Itoa(listenPort), "--once", "--config", configPath, "--title-format", title, "bash", "-c", strings.Join(sshCommand, " "))
  154. cmd.Dir = filepath.Dir(i.ExecPath)
  155. cmd.Env = append(os.Environ(), "TERM=xterm")
  156. cmd.Stdout = os.Stdout
  157. cmd.Stderr = os.Stderr
  158. go func() {
  159. cmd.Run()
  160. i.Destroy()
  161. }()
  162. i.tty = cmd
  163. i.AssignedPort = listenPort
  164. i.RemoteAddr = remoteIpAddr
  165. i.RemotePort = remotePort
  166. //Create a new proxy agent for this root
  167. path, err := url.Parse("http://127.0.0.1:" + strconv.Itoa(listenPort))
  168. if err != nil {
  169. return err
  170. }
  171. //Create new proxy objects to the proxy
  172. proxy := reverseproxy.NewReverseProxy(path)
  173. i.conn = proxy
  174. return nil
  175. }
  176. func (i *Instance) Destroy() {
  177. // Remove the instance from the Manager's Instances list
  178. for idx, inst := range i.Parent.Instances {
  179. if inst == i {
  180. // Remove the instance from the slice by swapping it with the last instance and slicing the slice
  181. i.Parent.Instances[len(i.Parent.Instances)-1], i.Parent.Instances[idx] = i.Parent.Instances[idx], i.Parent.Instances[len(i.Parent.Instances)-1]
  182. i.Parent.Instances = i.Parent.Instances[:len(i.Parent.Instances)-1]
  183. break
  184. }
  185. }
  186. }