webServer.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. serveMux.HandleFunc("/client_verification", webServer.clientVerificationHandler)
  51. certificate, err := tls.X509KeyPair(
  52. []byte(config.WebServerCertificate),
  53. []byte(config.WebServerPrivateKey))
  54. if err != nil {
  55. return psiphon.ContextError(err)
  56. }
  57. tlsConfig := &tls.Config{
  58. Certificates: []tls.Certificate{certificate},
  59. }
  60. // TODO: inherits global log config?
  61. logWriter := NewLogWriter()
  62. defer logWriter.Close()
  63. server := &psiphon.HTTPSServer{
  64. http.Server{
  65. Handler: serveMux,
  66. TLSConfig: tlsConfig,
  67. ReadTimeout: WEB_SERVER_READ_TIMEOUT,
  68. WriteTimeout: WEB_SERVER_WRITE_TIMEOUT,
  69. ErrorLog: golanglog.New(logWriter, "", 0),
  70. },
  71. }
  72. listener, err := net.Listen(
  73. "tcp", fmt.Sprintf("%s:%d", config.ServerIPAddress, config.WebServerPort))
  74. if err != nil {
  75. return psiphon.ContextError(err)
  76. }
  77. log.WithContext().Info("starting")
  78. err = nil
  79. errors := make(chan error)
  80. waitGroup := new(sync.WaitGroup)
  81. waitGroup.Add(1)
  82. go func() {
  83. defer waitGroup.Done()
  84. // Note: will be interrupted by listener.Close()
  85. err := server.ServeTLS(listener)
  86. // Can't check for the exact error that Close() will cause in Accept(),
  87. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  88. // explicit stop signal to stop gracefully.
  89. select {
  90. case <-shutdownBroadcast:
  91. default:
  92. if err != nil {
  93. select {
  94. case errors <- psiphon.ContextError(err):
  95. default:
  96. }
  97. }
  98. }
  99. log.WithContext().Info("stopped")
  100. }()
  101. select {
  102. case <-shutdownBroadcast:
  103. case err = <-errors:
  104. }
  105. listener.Close()
  106. waitGroup.Wait()
  107. log.WithContext().Info("exiting")
  108. return err
  109. }
  110. func (webServer *webServer) checkWebServerSecret(r *http.Request) bool {
  111. return subtle.ConstantTimeCompare(
  112. []byte(r.URL.Query().Get("server_secret")),
  113. []byte(webServer.config.WebServerSecret)) == 1
  114. }
  115. func (webServer *webServer) handshakeHandler(w http.ResponseWriter, r *http.Request) {
  116. if !webServer.checkWebServerSecret(r) {
  117. // TODO: log more details?
  118. log.WithContext().Warning("checkWebServerSecret failed")
  119. // TODO: psi_web returns NotFound in this case
  120. w.WriteHeader(http.StatusForbidden)
  121. return
  122. }
  123. // TODO: validate; proper log
  124. log.WithContextFields(LogFields{"queryParams": r.URL.Query()}).Info("handshake")
  125. // TODO: necessary, in case client sends bogus request body?
  126. _, err := ioutil.ReadAll(r.Body)
  127. if err != nil {
  128. w.WriteHeader(http.StatusInternalServerError)
  129. return
  130. }
  131. // TODO: backwards compatibility cases (only sending the new JSON format response line)
  132. // TODO: share struct definition with psiphon/serverApi.go?
  133. // TODO: populate more response data
  134. var handshakeConfig struct {
  135. Homepages []string `json:"homepages"`
  136. UpgradeClientVersion string `json:"upgrade_client_version"`
  137. PageViewRegexes []map[string]string `json:"page_view_regexes"`
  138. HttpsRequestRegexes []map[string]string `json:"https_request_regexes"`
  139. EncodedServerList []string `json:"encoded_server_list"`
  140. ClientRegion string `json:"client_region"`
  141. ServerTimestamp string `json:"server_timestamp"`
  142. }
  143. handshakeConfig.ServerTimestamp = psiphon.GetCurrentTimestamp()
  144. jsonPayload, err := json.Marshal(handshakeConfig)
  145. if err != nil {
  146. w.WriteHeader(http.StatusInternalServerError)
  147. return
  148. }
  149. responseBody := append([]byte("Config: "), jsonPayload...)
  150. w.WriteHeader(http.StatusOK)
  151. w.Write(responseBody)
  152. }
  153. func (webServer *webServer) connectedHandler(w http.ResponseWriter, r *http.Request) {
  154. if !webServer.checkWebServerSecret(r) {
  155. // TODO: log more details?
  156. log.WithContext().Warning("checkWebServerSecret failed")
  157. // TODO: psi_web does NotFound in this case
  158. w.WriteHeader(http.StatusForbidden)
  159. return
  160. }
  161. // TODO: validate; proper log
  162. log.WithContextFields(LogFields{"queryParams": r.URL.Query()}).Info("connected")
  163. // TODO: necessary, in case client sends bogus request body?
  164. _, err := ioutil.ReadAll(r.Body)
  165. if err != nil {
  166. w.WriteHeader(http.StatusInternalServerError)
  167. return
  168. }
  169. var connectedResponse struct {
  170. ConnectedTimestamp string `json:"connected_timestamp"`
  171. }
  172. connectedResponse.ConnectedTimestamp =
  173. psiphon.TruncateTimestampToHour(psiphon.GetCurrentTimestamp())
  174. responseBody, err := json.Marshal(connectedResponse)
  175. if err != nil {
  176. w.WriteHeader(http.StatusInternalServerError)
  177. return
  178. }
  179. w.WriteHeader(http.StatusOK)
  180. w.Write(responseBody)
  181. }
  182. func (webServer *webServer) statusHandler(w http.ResponseWriter, r *http.Request) {
  183. if !webServer.checkWebServerSecret(r) {
  184. // TODO: log more details?
  185. log.WithContext().Warning("checkWebServerSecret failed")
  186. // TODO: psi_web does NotFound in this case
  187. w.WriteHeader(http.StatusForbidden)
  188. return
  189. }
  190. // TODO: validate; proper log
  191. log.WithContextFields(LogFields{"queryParams": r.URL.Query()}).Info("status")
  192. // TODO: use json.NewDecoder(r.Body)? But will that handle bogus extra data in request body?
  193. requestBody, err := ioutil.ReadAll(r.Body)
  194. if err != nil {
  195. w.WriteHeader(http.StatusInternalServerError)
  196. return
  197. }
  198. // TODO: parse payload; validate; proper logs
  199. log.WithContextFields(LogFields{"payload": string(requestBody)}).Info("status payload")
  200. w.WriteHeader(http.StatusOK)
  201. }
  202. func (webServer *webServer) clientVerificationHandler(w http.ResponseWriter, r *http.Request) {
  203. if !webServer.checkWebServerSecret(r) {
  204. // TODO: log more details?
  205. log.WithContext().Warning("checkWebServerSecret failed")
  206. // TODO: psi_web does NotFound in this case
  207. w.WriteHeader(http.StatusForbidden)
  208. return
  209. }
  210. // TODO: validate; proper log
  211. log.WithContextFields(LogFields{"queryParams": r.URL.Query()}).Info("client_verification")
  212. // TODO: use json.NewDecoder(r.Body)? But will that handle bogus extra data in request body?
  213. requestBody, err := ioutil.ReadAll(r.Body)
  214. if err != nil {
  215. w.WriteHeader(http.StatusInternalServerError)
  216. return
  217. }
  218. // TODO: parse payload; validate; proper logs
  219. log.WithContextFields(LogFields{"payload": string(requestBody)}).Info("client_verification payload")
  220. w.WriteHeader(http.StatusOK)
  221. }