pgproxy.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // The pgproxy server is a proxy for the Postgres wire protocol.
  4. package main
  5. import (
  6. "context"
  7. "crypto/ecdsa"
  8. "crypto/elliptic"
  9. crand "crypto/rand"
  10. "crypto/tls"
  11. "crypto/x509"
  12. "crypto/x509/pkix"
  13. "expvar"
  14. "flag"
  15. "fmt"
  16. "io"
  17. "log"
  18. "math/big"
  19. "net"
  20. "net/http"
  21. "os"
  22. "strings"
  23. "time"
  24. "tailscale.com/client/local"
  25. "tailscale.com/metrics"
  26. "tailscale.com/tsnet"
  27. "tailscale.com/tsweb"
  28. )
  29. var (
  30. hostname = flag.String("hostname", "", "Tailscale hostname to serve on")
  31. port = flag.Int("port", 5432, "Listening port for client connections")
  32. debugPort = flag.Int("debug-port", 80, "Listening port for debug/metrics endpoint")
  33. upstreamAddr = flag.String("upstream-addr", "", "Address of the upstream Postgres server, in host:port format")
  34. upstreamCA = flag.String("upstream-ca-file", "", "File containing the PEM-encoded CA certificate for the upstream server")
  35. tailscaleDir = flag.String("state-dir", "", "Directory in which to store the Tailscale auth state")
  36. )
  37. func main() {
  38. flag.Parse()
  39. if *hostname == "" {
  40. log.Fatal("missing --hostname")
  41. }
  42. if *upstreamAddr == "" {
  43. log.Fatal("missing --upstream-addr")
  44. }
  45. if *upstreamCA == "" {
  46. log.Fatal("missing --upstream-ca-file")
  47. }
  48. if *tailscaleDir == "" {
  49. log.Fatal("missing --state-dir")
  50. }
  51. ts := &tsnet.Server{
  52. Dir: *tailscaleDir,
  53. Hostname: *hostname,
  54. }
  55. if os.Getenv("TS_AUTHKEY") == "" {
  56. log.Print("Note: you need to run this with TS_AUTHKEY=... the first time, to join your tailnet of choice.")
  57. }
  58. tsclient, err := ts.LocalClient()
  59. if err != nil {
  60. log.Fatalf("getting tsnet API client: %v", err)
  61. }
  62. p, err := newProxy(*upstreamAddr, *upstreamCA, tsclient)
  63. if err != nil {
  64. log.Fatal(err)
  65. }
  66. expvar.Publish("pgproxy", p.Expvar())
  67. if *debugPort != 0 {
  68. mux := http.NewServeMux()
  69. tsweb.Debugger(mux)
  70. srv := &http.Server{
  71. Handler: mux,
  72. }
  73. dln, err := ts.Listen("tcp", fmt.Sprintf(":%d", *debugPort))
  74. if err != nil {
  75. log.Fatal(err)
  76. }
  77. go func() {
  78. log.Fatal(srv.Serve(dln))
  79. }()
  80. }
  81. ln, err := ts.Listen("tcp", fmt.Sprintf(":%d", *port))
  82. if err != nil {
  83. log.Fatal(err)
  84. }
  85. log.Printf("serving access to %s on port %d", *upstreamAddr, *port)
  86. log.Fatal(p.Serve(ln))
  87. }
  88. // proxy is a postgres wire protocol proxy, which strictly enforces
  89. // the security of the TLS connection to its upstream regardless of
  90. // what the client's TLS configuration is.
  91. type proxy struct {
  92. upstreamAddr string // "my.database.com:5432"
  93. upstreamHost string // "my.database.com"
  94. upstreamCertPool *x509.CertPool
  95. downstreamCert []tls.Certificate
  96. client *local.Client
  97. activeSessions expvar.Int
  98. startedSessions expvar.Int
  99. errors metrics.LabelMap
  100. }
  101. // newProxy returns a proxy that forwards connections to
  102. // upstreamAddr. The upstream's TLS session is verified using the CA
  103. // cert(s) in upstreamCAPath.
  104. func newProxy(upstreamAddr, upstreamCAPath string, client *local.Client) (*proxy, error) {
  105. bs, err := os.ReadFile(upstreamCAPath)
  106. if err != nil {
  107. return nil, err
  108. }
  109. upstreamCertPool := x509.NewCertPool()
  110. if !upstreamCertPool.AppendCertsFromPEM(bs) {
  111. return nil, fmt.Errorf("invalid CA cert in %q", upstreamCAPath)
  112. }
  113. h, _, err := net.SplitHostPort(upstreamAddr)
  114. if err != nil {
  115. return nil, err
  116. }
  117. downstreamCert, err := mkSelfSigned(h)
  118. if err != nil {
  119. return nil, err
  120. }
  121. return &proxy{
  122. upstreamAddr: upstreamAddr,
  123. upstreamHost: h,
  124. upstreamCertPool: upstreamCertPool,
  125. downstreamCert: []tls.Certificate{downstreamCert},
  126. client: client,
  127. errors: metrics.LabelMap{Label: "kind"},
  128. }, nil
  129. }
  130. // Expvar returns p's monitoring metrics.
  131. func (p *proxy) Expvar() expvar.Var {
  132. ret := &metrics.Set{}
  133. ret.Set("sessions_active", &p.activeSessions)
  134. ret.Set("sessions_started", &p.startedSessions)
  135. ret.Set("session_errors", &p.errors)
  136. return ret
  137. }
  138. // Serve accepts postgres client connections on ln and proxies them to
  139. // the configured upstream. ln can be any net.Listener, but all client
  140. // connections must originate from tailscale IPs that can be verified
  141. // with WhoIs.
  142. func (p *proxy) Serve(ln net.Listener) error {
  143. var lastSessionID int64
  144. for {
  145. c, err := ln.Accept()
  146. if err != nil {
  147. return err
  148. }
  149. id := time.Now().UnixNano()
  150. if id == lastSessionID {
  151. // Bluntly enforce SID uniqueness, even if collisions are
  152. // fantastically unlikely (but OSes vary in how much timer
  153. // precision they expose to the OS, so id might be rounded
  154. // e.g. to the same millisecond)
  155. id++
  156. }
  157. lastSessionID = id
  158. go func(sessionID int64) {
  159. if err := p.serve(sessionID, c); err != nil {
  160. log.Printf("%d: session ended with error: %v", sessionID, err)
  161. }
  162. }(id)
  163. }
  164. }
  165. var (
  166. // sslStart is the magic bytes that postgres clients use to indicate
  167. // that they want to do a TLS handshake. Servers should respond with
  168. // the single byte "S" before starting a normal TLS handshake.
  169. sslStart = [8]byte{0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f}
  170. // plaintextStart is the magic bytes that postgres clients use to
  171. // indicate that they're starting a plaintext authentication
  172. // handshake.
  173. plaintextStart = [8]byte{0, 0, 0, 86, 0, 3, 0, 0}
  174. )
  175. // serve proxies the postgres client on c to the proxy's upstream,
  176. // enforcing strict TLS to the upstream.
  177. func (p *proxy) serve(sessionID int64, c net.Conn) error {
  178. defer c.Close()
  179. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  180. defer cancel()
  181. whois, err := p.client.WhoIs(ctx, c.RemoteAddr().String())
  182. if err != nil {
  183. p.errors.Add("whois-failed", 1)
  184. return fmt.Errorf("getting client identity: %v", err)
  185. }
  186. // Before anything else, log the connection attempt.
  187. user, machine := "", ""
  188. if whois.Node != nil {
  189. if whois.Node.Hostinfo.ShareeNode() {
  190. machine = "external-device"
  191. } else {
  192. machine = strings.TrimSuffix(whois.Node.Name, ".")
  193. }
  194. }
  195. if whois.UserProfile != nil {
  196. user = whois.UserProfile.LoginName
  197. if user == "tagged-devices" && whois.Node != nil {
  198. user = strings.Join(whois.Node.Tags, ",")
  199. }
  200. }
  201. if user == "" || machine == "" {
  202. p.errors.Add("no-ts-identity", 1)
  203. return fmt.Errorf("couldn't identify source user and machine (user %q, machine %q)", user, machine)
  204. }
  205. log.Printf("%d: session start, from %s (machine %s, user %s)", sessionID, c.RemoteAddr(), machine, user)
  206. start := time.Now()
  207. defer func() {
  208. elapsed := time.Since(start)
  209. log.Printf("%d: session end, from %s (machine %s, user %s), lasted %s", sessionID, c.RemoteAddr(), machine, user, elapsed.Round(time.Millisecond))
  210. }()
  211. // Read the client's opening message, to figure out if it's trying
  212. // to TLS or not.
  213. var buf [8]byte
  214. if _, err := io.ReadFull(c, buf[:len(sslStart)]); err != nil {
  215. p.errors.Add("network-error", 1)
  216. return fmt.Errorf("initial magic read: %v", err)
  217. }
  218. var clientIsTLS bool
  219. switch {
  220. case buf == sslStart:
  221. clientIsTLS = true
  222. case buf == plaintextStart:
  223. clientIsTLS = false
  224. default:
  225. p.errors.Add("client-bad-protocol", 1)
  226. return fmt.Errorf("unrecognized initial packet = % 02x", buf)
  227. }
  228. // Dial & verify upstream connection.
  229. var d net.Dialer
  230. d.Timeout = 10 * time.Second
  231. upc, err := d.Dial("tcp", p.upstreamAddr)
  232. if err != nil {
  233. p.errors.Add("network-error", 1)
  234. return fmt.Errorf("upstream dial: %v", err)
  235. }
  236. defer upc.Close()
  237. if _, err := upc.Write(sslStart[:]); err != nil {
  238. p.errors.Add("network-error", 1)
  239. return fmt.Errorf("upstream write of start-ssl magic: %v", err)
  240. }
  241. if _, err := io.ReadFull(upc, buf[:1]); err != nil {
  242. p.errors.Add("network-error", 1)
  243. return fmt.Errorf("reading upstream start-ssl response: %v", err)
  244. }
  245. if buf[0] != 'S' {
  246. p.errors.Add("upstream-bad-protocol", 1)
  247. return fmt.Errorf("upstream didn't acknowledge start-ssl, said %q", buf[0])
  248. }
  249. tlsConf := &tls.Config{
  250. ServerName: p.upstreamHost,
  251. RootCAs: p.upstreamCertPool,
  252. MinVersion: tls.VersionTLS12,
  253. }
  254. uptc := tls.Client(upc, tlsConf)
  255. if err = uptc.HandshakeContext(ctx); err != nil {
  256. p.errors.Add("upstream-tls", 1)
  257. return fmt.Errorf("upstream TLS handshake: %v", err)
  258. }
  259. // Accept the client conn and set it up the way the client wants.
  260. var clientConn net.Conn
  261. if clientIsTLS {
  262. io.WriteString(c, "S") // yeah, we're good to speak TLS
  263. s := tls.Server(c, &tls.Config{
  264. ServerName: p.upstreamHost,
  265. Certificates: p.downstreamCert,
  266. MinVersion: tls.VersionTLS12,
  267. })
  268. if err = uptc.HandshakeContext(ctx); err != nil {
  269. p.errors.Add("client-tls", 1)
  270. return fmt.Errorf("client TLS handshake: %v", err)
  271. }
  272. clientConn = s
  273. } else {
  274. // Repeat the header we read earlier up to the server.
  275. if _, err := uptc.Write(plaintextStart[:]); err != nil {
  276. p.errors.Add("network-error", 1)
  277. return fmt.Errorf("sending initial client bytes to upstream: %v", err)
  278. }
  279. clientConn = c
  280. }
  281. // Finally, proxy the client to the upstream.
  282. errc := make(chan error, 1)
  283. go func() {
  284. _, err := io.Copy(uptc, clientConn)
  285. errc <- err
  286. }()
  287. go func() {
  288. _, err := io.Copy(clientConn, uptc)
  289. errc <- err
  290. }()
  291. if err := <-errc; err != nil {
  292. // Don't increment error counts here, because the most common
  293. // cause of termination is client or server closing the
  294. // connection normally, and it'll obscure "interesting"
  295. // handshake errors.
  296. return fmt.Errorf("session terminated with error: %v", err)
  297. }
  298. return nil
  299. }
  300. // mkSelfSigned creates and returns a self-signed TLS certificate for
  301. // hostname.
  302. func mkSelfSigned(hostname string) (tls.Certificate, error) {
  303. priv, err := ecdsa.GenerateKey(elliptic.P256(), crand.Reader)
  304. if err != nil {
  305. return tls.Certificate{}, err
  306. }
  307. pub := priv.Public()
  308. template := x509.Certificate{
  309. SerialNumber: big.NewInt(1),
  310. Subject: pkix.Name{
  311. Organization: []string{"pgproxy"},
  312. },
  313. DNSNames: []string{hostname},
  314. NotBefore: time.Now(),
  315. NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour),
  316. KeyUsage: x509.KeyUsageDigitalSignature,
  317. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  318. BasicConstraintsValid: true,
  319. }
  320. derBytes, err := x509.CreateCertificate(crand.Reader, &template, &template, pub, priv)
  321. if err != nil {
  322. return tls.Certificate{}, err
  323. }
  324. cert, err := x509.ParseCertificate(derBytes)
  325. if err != nil {
  326. return tls.Certificate{}, err
  327. }
  328. return tls.Certificate{
  329. Certificate: [][]byte{derBytes},
  330. PrivateKey: priv,
  331. Leaf: cert,
  332. }, nil
  333. }