webService.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "crypto/subtle"
  22. "crypto/tls"
  23. "encoding/json"
  24. "fmt"
  25. "io/ioutil"
  26. golanglog "log"
  27. "net"
  28. "net/http"
  29. "sync"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  31. )
  32. type webServer struct {
  33. serveMux *http.ServeMux
  34. config *Config
  35. }
  36. // RunWebServer runs a web server which responds to the following Psiphon API
  37. // web requests: handshake, connected, and status. At this time, this web
  38. // server is a stub for stand-alone testing. It provides the minimal response
  39. // required by the tunnel-core client. It doesn't return read landing pages,
  40. // serer discovery results, or other handshake response values. It also does
  41. // not log stats in the standard way.
  42. func RunWebServer(config *Config, shutdownBroadcast <-chan struct{}) error {
  43. webServer := &webServer{
  44. config: config,
  45. }
  46. serveMux := http.NewServeMux()
  47. serveMux.HandleFunc("/handshake", webServer.handshakeHandler)
  48. serveMux.HandleFunc("/connected", webServer.connectedHandler)
  49. serveMux.HandleFunc("/status", webServer.statusHandler)
  50. certificate, err := tls.X509KeyPair(
  51. []byte(config.WebServerCertificate),
  52. []byte(config.WebServerPrivateKey))
  53. if err != nil {
  54. return psiphon.ContextError(err)
  55. }
  56. tlsConfig := &tls.Config{
  57. Certificates: []tls.Certificate{certificate},
  58. }
  59. // TODO: inherits global log config?
  60. logWriter := NewLogWriter()
  61. defer logWriter.Close()
  62. server := &psiphon.HTTPSServer{
  63. http.Server{
  64. Handler: serveMux,
  65. TLSConfig: tlsConfig,
  66. ReadTimeout: WEB_SERVER_READ_TIMEOUT,
  67. WriteTimeout: WEB_SERVER_WRITE_TIMEOUT,
  68. ErrorLog: golanglog.New(logWriter, "", 0),
  69. },
  70. }
  71. listener, err := net.Listen(
  72. "tcp", fmt.Sprintf("%s:%d", config.ServerIPAddress, config.WebServerPort))
  73. if err != nil {
  74. return psiphon.ContextError(err)
  75. }
  76. log.WithContext().Info("starting")
  77. err = nil
  78. errors := make(chan error)
  79. waitGroup := new(sync.WaitGroup)
  80. waitGroup.Add(1)
  81. go func() {
  82. defer waitGroup.Done()
  83. // Note: will be interrupted by listener.Close()
  84. err := server.ServeTLS(listener)
  85. // Can't check for the exact error that Close() will cause in Accept(),
  86. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  87. // explicit stop signal to stop gracefully.
  88. select {
  89. case <-shutdownBroadcast:
  90. default:
  91. if err != nil {
  92. select {
  93. case errors <- psiphon.ContextError(err):
  94. default:
  95. }
  96. }
  97. }
  98. log.WithContext().Info("stopped")
  99. }()
  100. select {
  101. case <-shutdownBroadcast:
  102. case err = <-errors:
  103. }
  104. listener.Close()
  105. waitGroup.Wait()
  106. log.WithContext().Info("exiting")
  107. return err
  108. }
  109. func (webServer *webServer) checkWebServerSecret(r *http.Request) bool {
  110. return subtle.ConstantTimeCompare(
  111. []byte(r.URL.Query().Get("server_secret")),
  112. []byte(webServer.config.WebServerSecret)) == 1
  113. }
  114. func (webServer *webServer) handshakeHandler(w http.ResponseWriter, r *http.Request) {
  115. if !webServer.checkWebServerSecret(r) {
  116. // TODO: log more details?
  117. log.WithContext().Warning("checkWebServerSecret failed")
  118. // TODO: psi_web returns NotFound in this case
  119. w.WriteHeader(http.StatusForbidden)
  120. return
  121. }
  122. // TODO: validate; proper log
  123. log.WithContextFields(LogFields{"queryParams": r.URL.Query()}).Info("handshake")
  124. // TODO: necessary, in case client sends bogus request body?
  125. _, err := ioutil.ReadAll(r.Body)
  126. if err != nil {
  127. w.WriteHeader(http.StatusInternalServerError)
  128. return
  129. }
  130. // TODO: backwards compatibility cases (only sending the new JSON format response line)
  131. // TODO: share struct definition with psiphon/serverApi.go?
  132. // TODO: populate more response data
  133. var handshakeConfig struct {
  134. Homepages []string `json:"homepages"`
  135. UpgradeClientVersion string `json:"upgrade_client_version"`
  136. PageViewRegexes []map[string]string `json:"page_view_regexes"`
  137. HttpsRequestRegexes []map[string]string `json:"https_request_regexes"`
  138. EncodedServerList []string `json:"encoded_server_list"`
  139. ClientRegion string `json:"client_region"`
  140. ServerTimestamp string `json:"server_timestamp"`
  141. }
  142. handshakeConfig.ServerTimestamp = psiphon.GetCurrentTimestamp()
  143. jsonPayload, err := json.Marshal(handshakeConfig)
  144. if err != nil {
  145. w.WriteHeader(http.StatusInternalServerError)
  146. return
  147. }
  148. responseBody := append([]byte("Config: "), jsonPayload...)
  149. w.WriteHeader(http.StatusOK)
  150. w.Write(responseBody)
  151. }
  152. func (webServer *webServer) connectedHandler(w http.ResponseWriter, r *http.Request) {
  153. if !webServer.checkWebServerSecret(r) {
  154. // TODO: log more details?
  155. log.WithContext().Warning("checkWebServerSecret failed")
  156. // TODO: psi_web does NotFound in this case
  157. w.WriteHeader(http.StatusForbidden)
  158. return
  159. }
  160. // TODO: validate; proper log
  161. log.WithContextFields(LogFields{"queryParams": r.URL.Query()}).Info("connected")
  162. // TODO: necessary, in case client sends bogus request body?
  163. _, err := ioutil.ReadAll(r.Body)
  164. if err != nil {
  165. w.WriteHeader(http.StatusInternalServerError)
  166. return
  167. }
  168. var connectedResponse struct {
  169. ConnectedTimestamp string `json:"connected_timestamp"`
  170. }
  171. connectedResponse.ConnectedTimestamp =
  172. psiphon.TruncateTimestampToHour(psiphon.GetCurrentTimestamp())
  173. responseBody, err := json.Marshal(connectedResponse)
  174. if err != nil {
  175. w.WriteHeader(http.StatusInternalServerError)
  176. return
  177. }
  178. w.WriteHeader(http.StatusOK)
  179. w.Write(responseBody)
  180. }
  181. func (webServer *webServer) statusHandler(w http.ResponseWriter, r *http.Request) {
  182. if !webServer.checkWebServerSecret(r) {
  183. // TODO: log more details?
  184. log.WithContext().Warning("checkWebServerSecret failed")
  185. // TODO: psi_web does NotFound in this case
  186. w.WriteHeader(http.StatusForbidden)
  187. return
  188. }
  189. // TODO: validate; proper log
  190. log.WithContextFields(LogFields{"queryParams": r.URL.Query()}).Info("status")
  191. // TODO: use json.NewDecoder(r.Body)? But will that handle bogus extra data in request body?
  192. requestBody, err := ioutil.ReadAll(r.Body)
  193. if err != nil {
  194. w.WriteHeader(http.StatusInternalServerError)
  195. return
  196. }
  197. // TODO: parse payload; validate; proper logs
  198. log.WithContextFields(LogFields{"payload": string(requestBody)}).Info("status payload")
  199. w.WriteHeader(http.StatusOK)
  200. }