sshprox.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. })
  81. wspHandler.ServeHTTP(w, r)
  82. return
  83. }
  84. targetInstance.conn.ProxyHTTP(w, r)
  85. }
  86. func (m *Manager) GetInstanceById(instanceId string) (*Instance, error) {
  87. for _, instance := range m.Instances {
  88. if instance.UUID == instanceId {
  89. return instance, nil
  90. }
  91. }
  92. return nil, fmt.Errorf("instance not found: %s", instanceId)
  93. }
  94. func (m *Manager) NewSSHProxy(binaryRoot string) (*Instance, error) {
  95. //Check if the binary exists in system/gotty/
  96. binary := "gotty_" + runtime.GOOS + "_" + runtime.GOARCH
  97. if runtime.GOOS == "windows" {
  98. binary = binary + ".exe"
  99. }
  100. //Extract it from embedfs if not exists locally
  101. execPath := filepath.Join(binaryRoot, binary)
  102. //Create the storage folder structure
  103. os.MkdirAll(filepath.Dir(execPath), 0775)
  104. //Create config file if not exists
  105. if !utils.FileExists(filepath.Join(filepath.Dir(execPath), ".gotty")) {
  106. configFile, _ := gotty.ReadFile("gotty/.gotty")
  107. os.WriteFile(filepath.Join(filepath.Dir(execPath), ".gotty"), configFile, 0775)
  108. }
  109. //Create web.ssh binary if not exists
  110. if !utils.FileExists(execPath) {
  111. //Try to extract it from embedded fs
  112. executable, err := gotty.ReadFile("gotty/" + binary)
  113. if err != nil {
  114. //Binary not found in embedded
  115. return nil, errors.New("platform not supported")
  116. }
  117. //Extract to target location
  118. err = os.WriteFile(execPath, executable, 0777)
  119. if err != nil {
  120. //Binary not found in embedded
  121. log.Println("Extract web.ssh failed: " + err.Error())
  122. return nil, errors.New("web.ssh sub-program extract failed")
  123. }
  124. }
  125. //Convert the binary path to realpath
  126. realpath, err := filepath.Abs(execPath)
  127. if err != nil {
  128. return nil, err
  129. }
  130. thisInstance := Instance{
  131. UUID: uuid.New().String(),
  132. ExecPath: realpath,
  133. AssignedPort: -1,
  134. Parent: m,
  135. }
  136. m.Instances = append(m.Instances, &thisInstance)
  137. return &thisInstance, nil
  138. }
  139. // Create a new Connection to target address
  140. func (i *Instance) CreateNewConnection(listenPort int, username string, remoteIpAddr string, remotePort int) error {
  141. //Create a gotty instance
  142. connAddr := remoteIpAddr
  143. if username != "" {
  144. connAddr = username + "@" + remoteIpAddr
  145. }
  146. configPath := filepath.Join(filepath.Dir(i.ExecPath), ".gotty")
  147. title := username + "@" + remoteIpAddr
  148. if remotePort != 22 {
  149. title = title + ":" + strconv.Itoa(remotePort)
  150. }
  151. sshCommand := []string{"ssh", "-t", connAddr, "-p", strconv.Itoa(remotePort)}
  152. cmd := exec.Command(i.ExecPath, "-w", "-p", strconv.Itoa(listenPort), "--once", "--config", configPath, "--title-format", title, "bash", "-c", strings.Join(sshCommand, " "))
  153. cmd.Dir = filepath.Dir(i.ExecPath)
  154. cmd.Env = append(os.Environ(), "TERM=xterm")
  155. cmd.Stdout = os.Stdout
  156. cmd.Stderr = os.Stderr
  157. go func() {
  158. cmd.Run()
  159. i.Destroy()
  160. }()
  161. i.tty = cmd
  162. i.AssignedPort = listenPort
  163. i.RemoteAddr = remoteIpAddr
  164. i.RemotePort = remotePort
  165. //Create a new proxy agent for this root
  166. path, err := url.Parse("http://127.0.0.1:" + strconv.Itoa(listenPort))
  167. if err != nil {
  168. return err
  169. }
  170. //Create new proxy objects to the proxy
  171. proxy := reverseproxy.NewReverseProxy(path)
  172. i.conn = proxy
  173. return nil
  174. }
  175. func (i *Instance) Destroy() {
  176. // Remove the instance from the Manager's Instances list
  177. for idx, inst := range i.Parent.Instances {
  178. if inst == i {
  179. // Remove the instance from the slice by swapping it with the last instance and slicing the slice
  180. i.Parent.Instances[len(i.Parent.Instances)-1], i.Parent.Instances[idx] = i.Parent.Instances[idx], i.Parent.Instances[len(i.Parent.Instances)-1]
  181. i.Parent.Instances = i.Parent.Instances[:len(i.Parent.Instances)-1]
  182. break
  183. }
  184. }
  185. }