plain.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. package tlsmode
  2. import (
  3. "bufio"
  4. "crypto/tls"
  5. "errors"
  6. "net"
  7. "net/http"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/gnacho/netpulse/server-go/internal/auth"
  12. )
  13. // PlainHandler wraps the handler served on the plain HTTP port with what the
  14. // current mode allows there. Requests that arrived over TLS - on that port,
  15. // through the sniffing listener - are not restricted.
  16. func (m *Manager) PlainHandler(next http.Handler) http.Handler {
  17. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  18. // Secure is a TLS connection, or one a trusted TLS-terminating proxy
  19. // forwarded as https - the same rule the session cookie follows. A
  20. // client that fakes the proxy's header only sends its own
  21. // credentials in clear.
  22. if auth.IsSecureRequest(r) || !m.Enabled() {
  23. next.ServeHTTP(w, r)
  24. return
  25. }
  26. switch m.Mode() {
  27. case Migrate:
  28. if auth.IsAgentRequest(r) || isPublicPath(r.URL.Path) {
  29. next.ServeHTTP(w, r)
  30. return
  31. }
  32. dropPlainSession(w)
  33. if m.redirectBrowser(w, r) {
  34. return
  35. }
  36. // Refused, not redirected: a redirect cannot protect a password
  37. // or token that has already been sent in clear.
  38. auth.WriteError(w, http.StatusForbidden, "use_https",
  39. "this server only accepts sign-ins and API calls over HTTPS")
  40. case Redirect:
  41. if isPublicPath(r.URL.Path) && r.URL.Path != "/api/health" && r.URL.Path != "/health" ||
  42. isHealthPath(r.URL.Path) && fromLoopback(r) {
  43. next.ServeHTTP(w, r)
  44. return
  45. }
  46. dropPlainSession(w)
  47. if m.redirectBrowser(w, r) {
  48. return
  49. }
  50. w.Header().Set("Upgrade", "TLS/1.2, HTTP/1.1")
  51. w.Header().Set("Connection", "Upgrade")
  52. auth.WriteError(w, http.StatusUpgradeRequired, "use_https",
  53. "this server only answers over HTTPS")
  54. default:
  55. next.ServeHTTP(w, r)
  56. }
  57. })
  58. }
  59. // dropPlainSession deletes the session cookie of a sign-in made over plain
  60. // HTTP. A browser sends it with every http:// request - an old bookmark,
  61. // access by address, which HSTS never covers - in clear, until it expires;
  62. // once plain HTTP is no longer for people, it is only a liability.
  63. func dropPlainSession(w http.ResponseWriter) {
  64. w.Header().Add("Set-Cookie", auth.ClearSessionCookie)
  65. }
  66. // redirectBrowser sends a page load to the HTTPS address. API calls are not
  67. // redirected: a client that would follow one has usually sent its
  68. // credentials already.
  69. func (m *Manager) redirectBrowser(w http.ResponseWriter, r *http.Request) bool {
  70. if (r.Method != http.MethodGet && r.Method != http.MethodHead) || strings.HasPrefix(r.URL.Path, "/api/") {
  71. return false
  72. }
  73. target, ok := m.RedirectTarget(r)
  74. if !ok {
  75. return false
  76. }
  77. http.Redirect(w, r, target, http.StatusPermanentRedirect)
  78. return true
  79. }
  80. // isPublicPath is what carries no credential and is safe over plain HTTP: the
  81. // health checks, and the root certificate and fingerprint a device needs
  82. // before it can trust HTTPS at all.
  83. func isPublicPath(p string) bool {
  84. return isHealthPath(p) || p == "/fingerprint" || p == "/netpulse-ca.crt" || p == "/netpulse-ca.pem"
  85. }
  86. func isHealthPath(p string) bool { return p == "/api/health" || p == "/health" }
  87. // fromLoopback looks at the connection, never at forwarded headers.
  88. func fromLoopback(r *http.Request) bool {
  89. host, _, err := net.SplitHostPort(r.RemoteAddr)
  90. if err != nil {
  91. return false
  92. }
  93. ip := net.ParseIP(host)
  94. return ip != nil && ip.IsLoopback()
  95. }
  96. // --- one port, both protocols ---
  97. // peekTimeout bounds how long a new connection may take to send its first
  98. // byte before it is dropped, so a client that sends nothing cannot hold a
  99. // goroutine forever.
  100. const peekTimeout = 10 * time.Second
  101. // SniffListener wraps the plain port's listener. Once the CA exists, a
  102. // connection that opens with a TLS handshake is served as HTTPS on the same
  103. // port: a browser holding an HSTS policy for the server's name upgrades
  104. // http://name:PORT to https://name:PORT, which would otherwise fail against
  105. // a plain listener and never see the redirect. Before HTTPS was ever turned
  106. // on, connections are passed through untouched, as before.
  107. func (m *Manager) SniffListener(ln net.Listener) net.Listener {
  108. l := &sniffListener{
  109. Listener: ln,
  110. m: m,
  111. plain: make(chan net.Conn),
  112. errc: make(chan error, 1),
  113. done: make(chan struct{}),
  114. }
  115. go l.acceptLoop()
  116. return l
  117. }
  118. type sniffListener struct {
  119. net.Listener
  120. m *Manager
  121. plain chan net.Conn
  122. errc chan error
  123. done chan struct{}
  124. once sync.Once
  125. }
  126. func (l *sniffListener) Accept() (net.Conn, error) {
  127. select {
  128. case c := <-l.plain:
  129. return c, nil
  130. case err := <-l.errc:
  131. return nil, err
  132. case <-l.done:
  133. return nil, net.ErrClosed
  134. }
  135. }
  136. func (l *sniffListener) Close() error {
  137. l.once.Do(func() { close(l.done) })
  138. return l.Listener.Close()
  139. }
  140. func (l *sniffListener) acceptLoop() {
  141. var delay time.Duration
  142. for {
  143. c, err := l.Listener.Accept()
  144. if err != nil {
  145. // Only a closed listener ends the loop. Anything else - running
  146. // out of file descriptors under a burst of connections, say - is
  147. // waited out: handing it to http.Server would make it stop
  148. // serving for good while the process, and the port, stay up.
  149. if errors.Is(err, net.ErrClosed) {
  150. select {
  151. case l.errc <- err:
  152. case <-l.done:
  153. }
  154. return
  155. }
  156. if delay == 0 {
  157. delay = 5 * time.Millisecond
  158. } else if delay *= 2; delay > time.Second {
  159. delay = time.Second
  160. }
  161. select {
  162. case <-time.After(delay):
  163. case <-l.done:
  164. return
  165. }
  166. continue
  167. }
  168. delay = 0
  169. go l.route(c)
  170. }
  171. }
  172. func (l *sniffListener) route(c net.Conn) {
  173. // Once the CA exists the port answers TLS in every mode, and with HTTPS
  174. // off: a browser that got an HSTS policy for the name while a stricter
  175. // mode was on keeps rewriting http://name:PORT to https://name:PORT for
  176. // as long as the policy lasts. Served here, it gets max-age=0 and the
  177. // page; refused, the name would be unreachable from it until then.
  178. if l.m.CA() == nil {
  179. l.deliver(c)
  180. return
  181. }
  182. _ = c.SetReadDeadline(time.Now().Add(peekTimeout))
  183. br := bufio.NewReader(c)
  184. first, err := br.Peek(1)
  185. _ = c.SetReadDeadline(time.Time{})
  186. if err != nil {
  187. c.Close()
  188. return
  189. }
  190. pc := &peekedConn{Conn: c, r: br}
  191. if first[0] == 0x16 { // a TLS handshake record
  192. l.m.sniff.serve(pc)
  193. return
  194. }
  195. l.deliver(pc)
  196. }
  197. func (l *sniffListener) deliver(c net.Conn) {
  198. select {
  199. case l.plain <- c:
  200. case <-l.done:
  201. c.Close()
  202. }
  203. }
  204. // peekedConn gives back the byte read to tell the protocols apart.
  205. type peekedConn struct {
  206. net.Conn
  207. r *bufio.Reader
  208. }
  209. func (c *peekedConn) Read(p []byte) (int, error) { return c.r.Read(p) }
  210. // sniffServer serves the TLS connections found on the plain port.
  211. type sniffServer struct {
  212. m *Manager
  213. conns chan net.Conn
  214. done chan struct{}
  215. once sync.Once
  216. }
  217. func newSniffServer(m *Manager) *sniffServer {
  218. s := &sniffServer{m: m, conns: make(chan net.Conn), done: make(chan struct{})}
  219. srv := m.opts.NewServer("", m.handler)
  220. go func() { _ = srv.Serve(chanListener{s}) }()
  221. go func() {
  222. <-s.done
  223. _ = srv.Close()
  224. }()
  225. return s
  226. }
  227. func (s *sniffServer) serve(c net.Conn) {
  228. ca := s.m.CA()
  229. if ca == nil {
  230. c.Close()
  231. return
  232. }
  233. select {
  234. case s.conns <- tls.Server(c, ca.TLSConfig()):
  235. case <-s.done:
  236. c.Close()
  237. }
  238. }
  239. func (s *sniffServer) close() { s.once.Do(func() { close(s.done) }) }
  240. // chanListener hands the sniffing server its connections.
  241. type chanListener struct{ s *sniffServer }
  242. func (l chanListener) Accept() (net.Conn, error) {
  243. select {
  244. case c := <-l.s.conns:
  245. return c, nil
  246. case <-l.s.done:
  247. return nil, net.ErrClosed
  248. }
  249. }
  250. func (chanListener) Close() error { return nil }
  251. func (chanListener) Addr() net.Addr { return &net.TCPAddr{} }