broker.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /*
  2. Broker acts as the HTTP signaling channel.
  3. It matches clients and snowflake proxies by passing corresponding
  4. SessionDescriptions in order to negotiate a WebRTC connection.
  5. */
  6. package main
  7. import (
  8. "bytes"
  9. "container/heap"
  10. "context"
  11. "crypto/tls"
  12. "flag"
  13. "io"
  14. "log"
  15. "net/http"
  16. "os"
  17. "os/signal"
  18. "strings"
  19. "sync"
  20. "syscall"
  21. "time"
  22. "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/bridgefingerprint"
  23. "github.com/aws/aws-sdk-go-v2/config"
  24. "github.com/aws/aws-sdk-go-v2/service/sqs"
  25. "github.com/prometheus/client_golang/prometheus"
  26. "github.com/prometheus/client_golang/prometheus/promhttp"
  27. "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/ptutil/safelog"
  28. "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/namematcher"
  29. "golang.org/x/crypto/acme/autocert"
  30. )
  31. type BrokerContext struct {
  32. snowflakes *SnowflakeHeap
  33. restrictedSnowflakes *SnowflakeHeap
  34. // Maps keeping track of snowflakeIDs required to match SDP answers from
  35. // the second http POST. Restricted snowflakes can only be matched up with
  36. // clients behind an unrestricted NAT.
  37. idToSnowflake map[string]*Snowflake
  38. // Synchronization for the snowflake map and heap
  39. snowflakeLock sync.Mutex
  40. proxyPolls chan *ProxyPoll
  41. metrics *Metrics
  42. bridgeList BridgeListHolderFileBased
  43. allowedRelayPattern string
  44. presumedPatternForLegacyClient string
  45. }
  46. func (ctx *BrokerContext) GetBridgeInfo(fingerprint bridgefingerprint.Fingerprint) (BridgeInfo, error) {
  47. return ctx.bridgeList.GetBridgeInfo(fingerprint)
  48. }
  49. func NewBrokerContext(
  50. metricsLogger *log.Logger,
  51. allowedRelayPattern,
  52. presumedPatternForLegacyClient string,
  53. ) *BrokerContext {
  54. snowflakes := new(SnowflakeHeap)
  55. heap.Init(snowflakes)
  56. rSnowflakes := new(SnowflakeHeap)
  57. heap.Init(rSnowflakes)
  58. metrics, err := NewMetrics(metricsLogger)
  59. if err != nil {
  60. panic(err.Error())
  61. }
  62. if metrics == nil {
  63. panic("Failed to create metrics")
  64. }
  65. bridgeListHolder := NewBridgeListHolder()
  66. const DefaultBridges = `{"displayName":"default", "webSocketAddress":"wss://snowflake.torproject.net/", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80A72"}
  67. `
  68. bridgeListHolder.LoadBridgeInfo(bytes.NewReader([]byte(DefaultBridges)))
  69. return &BrokerContext{
  70. snowflakes: snowflakes,
  71. restrictedSnowflakes: rSnowflakes,
  72. idToSnowflake: make(map[string]*Snowflake),
  73. proxyPolls: make(chan *ProxyPoll),
  74. metrics: metrics,
  75. bridgeList: bridgeListHolder,
  76. allowedRelayPattern: allowedRelayPattern,
  77. presumedPatternForLegacyClient: presumedPatternForLegacyClient,
  78. }
  79. }
  80. // Proxies may poll for client offers concurrently.
  81. type ProxyPoll struct {
  82. id string
  83. proxyType string
  84. natType string
  85. clients int
  86. offerChannel chan *ClientOffer
  87. }
  88. // Registers a Snowflake and waits for some Client to send an offer,
  89. // as part of the polling logic of the proxy handler.
  90. func (ctx *BrokerContext) RequestOffer(id string, proxyType string, natType string, clients int) *ClientOffer {
  91. request := new(ProxyPoll)
  92. request.id = id
  93. request.proxyType = proxyType
  94. request.natType = natType
  95. request.clients = clients
  96. request.offerChannel = make(chan *ClientOffer)
  97. ctx.proxyPolls <- request
  98. // Block until an offer is available, or timeout which sends a nil offer.
  99. offer := <-request.offerChannel
  100. return offer
  101. }
  102. // goroutine which matches clients to proxies and sends SDP offers along.
  103. // Safely processes proxy requests, responding to them with either an available
  104. // client offer or nil on timeout / none are available.
  105. func (ctx *BrokerContext) Broker() {
  106. for request := range ctx.proxyPolls {
  107. snowflake := ctx.AddSnowflake(request.id, request.proxyType, request.natType, request.clients)
  108. // Wait for a client to avail an offer to the snowflake.
  109. go func(request *ProxyPoll) {
  110. select {
  111. case offer := <-snowflake.offerChannel:
  112. request.offerChannel <- offer
  113. case <-time.After(time.Second * ProxyTimeout):
  114. // This snowflake is no longer available to serve clients.
  115. ctx.snowflakeLock.Lock()
  116. defer ctx.snowflakeLock.Unlock()
  117. if snowflake.index != -1 {
  118. if request.natType == NATUnrestricted {
  119. heap.Remove(ctx.snowflakes, snowflake.index)
  120. } else {
  121. heap.Remove(ctx.restrictedSnowflakes, snowflake.index)
  122. }
  123. ctx.metrics.promMetrics.AvailableProxies.With(prometheus.Labels{"nat": request.natType, "type": request.proxyType}).Dec()
  124. delete(ctx.idToSnowflake, snowflake.id)
  125. close(request.offerChannel)
  126. }
  127. }
  128. }(request)
  129. }
  130. }
  131. // Create and add a Snowflake to the heap.
  132. // Required to keep track of proxies between providing them
  133. // with an offer and awaiting their second POST with an answer.
  134. func (ctx *BrokerContext) AddSnowflake(id string, proxyType string, natType string, clients int) *Snowflake {
  135. snowflake := new(Snowflake)
  136. snowflake.id = id
  137. snowflake.clients = clients
  138. snowflake.proxyType = proxyType
  139. snowflake.natType = natType
  140. snowflake.offerChannel = make(chan *ClientOffer)
  141. snowflake.answerChannel = make(chan string)
  142. ctx.snowflakeLock.Lock()
  143. if natType == NATUnrestricted {
  144. heap.Push(ctx.snowflakes, snowflake)
  145. } else {
  146. heap.Push(ctx.restrictedSnowflakes, snowflake)
  147. }
  148. ctx.metrics.promMetrics.AvailableProxies.With(prometheus.Labels{"nat": natType, "type": proxyType}).Inc()
  149. ctx.idToSnowflake[id] = snowflake
  150. ctx.snowflakeLock.Unlock()
  151. return snowflake
  152. }
  153. func (ctx *BrokerContext) InstallBridgeListProfile(reader io.Reader) error {
  154. if err := ctx.bridgeList.LoadBridgeInfo(reader); err != nil {
  155. return err
  156. }
  157. return nil
  158. }
  159. func (ctx *BrokerContext) CheckProxyRelayPattern(pattern string, nonSupported bool) bool {
  160. if nonSupported {
  161. pattern = ctx.presumedPatternForLegacyClient
  162. }
  163. proxyPattern := namematcher.NewNameMatcher(pattern)
  164. brokerPattern := namematcher.NewNameMatcher(ctx.allowedRelayPattern)
  165. return proxyPattern.IsSupersetOf(brokerPattern)
  166. }
  167. // Client offer contains an SDP, bridge fingerprint and the NAT type of the client
  168. type ClientOffer struct {
  169. natType string
  170. sdp []byte
  171. fingerprint []byte
  172. }
  173. func main() {
  174. var acmeEmail string
  175. var acmeHostnamesCommas string
  176. var acmeCertCacheDir string
  177. var addr string
  178. var geoipDatabase string
  179. var geoip6Database string
  180. var bridgeListFilePath, allowedRelayPattern, presumedPatternForLegacyClient string
  181. var brokerSQSQueueName, brokerSQSQueueRegion string
  182. var disableTLS bool
  183. var certFilename, keyFilename string
  184. var disableGeoip bool
  185. var metricsFilename string
  186. var unsafeLogging bool
  187. flag.StringVar(&acmeEmail, "acme-email", "", "optional contact email for Let's Encrypt notifications")
  188. flag.StringVar(&acmeHostnamesCommas, "acme-hostnames", "", "comma-separated hostnames for TLS certificate")
  189. flag.StringVar(&certFilename, "cert", "", "TLS certificate file")
  190. flag.StringVar(&keyFilename, "key", "", "TLS private key file")
  191. flag.StringVar(&acmeCertCacheDir, "acme-cert-cache", "acme-cert-cache", "directory in which certificates should be cached")
  192. flag.StringVar(&addr, "addr", ":443", "address to listen on")
  193. flag.StringVar(&geoipDatabase, "geoipdb", "/usr/share/tor/geoip", "path to correctly formatted geoip database mapping IPv4 address ranges to country codes")
  194. flag.StringVar(&geoip6Database, "geoip6db", "/usr/share/tor/geoip6", "path to correctly formatted geoip database mapping IPv6 address ranges to country codes")
  195. flag.StringVar(&bridgeListFilePath, "bridge-list-path", "", "file path for bridgeListFile")
  196. flag.StringVar(&allowedRelayPattern, "allowed-relay-pattern", "", "allowed pattern for relay host name. The broker will reject proxies whose AcceptedRelayPattern is more restrictive than this")
  197. flag.StringVar(&presumedPatternForLegacyClient, "default-relay-pattern", "", "presumed pattern for legacy client")
  198. flag.StringVar(&brokerSQSQueueName, "broker-sqs-name", "", "name of broker SQS queue to listen for incoming messages on")
  199. flag.StringVar(&brokerSQSQueueRegion, "broker-sqs-region", "", "name of AWS region of broker SQS queue")
  200. flag.BoolVar(&disableTLS, "disable-tls", false, "don't use HTTPS")
  201. flag.BoolVar(&disableGeoip, "disable-geoip", false, "don't use geoip for stats collection")
  202. flag.StringVar(&metricsFilename, "metrics-log", "", "path to metrics logging output")
  203. flag.BoolVar(&unsafeLogging, "unsafe-logging", false, "prevent logs from being scrubbed")
  204. flag.Parse()
  205. var err error
  206. var metricsFile io.Writer
  207. var logOutput io.Writer = os.Stderr
  208. if unsafeLogging {
  209. log.SetOutput(logOutput)
  210. } else {
  211. // We want to send the log output through our scrubber first
  212. log.SetOutput(&safelog.LogScrubber{Output: logOutput})
  213. }
  214. log.SetFlags(log.LstdFlags | log.LUTC)
  215. if metricsFilename != "" {
  216. metricsFile, err = os.OpenFile(metricsFilename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  217. if err != nil {
  218. log.Fatal(err.Error())
  219. }
  220. } else {
  221. metricsFile = os.Stdout
  222. }
  223. metricsLogger := log.New(metricsFile, "", 0)
  224. ctx := NewBrokerContext(metricsLogger, allowedRelayPattern, presumedPatternForLegacyClient)
  225. if bridgeListFilePath != "" {
  226. bridgeListFile, err := os.Open(bridgeListFilePath)
  227. if err != nil {
  228. log.Fatal(err.Error())
  229. }
  230. err = ctx.InstallBridgeListProfile(bridgeListFile)
  231. if err != nil {
  232. log.Fatal(err.Error())
  233. }
  234. }
  235. if !disableGeoip {
  236. err = ctx.metrics.LoadGeoipDatabases(geoipDatabase, geoip6Database)
  237. if err != nil {
  238. log.Fatal(err.Error())
  239. }
  240. }
  241. go ctx.Broker()
  242. i := &IPC{ctx}
  243. http.HandleFunc("/robots.txt", robotsTxtHandler)
  244. http.Handle("/proxy", SnowflakeHandler{i, proxyPolls})
  245. http.Handle("/client", SnowflakeHandler{i, clientOffers})
  246. http.Handle("/answer", SnowflakeHandler{i, proxyAnswers})
  247. http.Handle("/debug", SnowflakeHandler{i, debugHandler})
  248. http.Handle("/metrics", MetricsHandler{metricsFilename, metricsHandler})
  249. http.Handle("/prometheus", promhttp.HandlerFor(ctx.metrics.promMetrics.registry, promhttp.HandlerOpts{}))
  250. http.Handle("/amp/client/", SnowflakeHandler{i, ampClientOffers})
  251. server := http.Server{
  252. Addr: addr,
  253. }
  254. // Run SQS Handler to continuously poll and process messages from SQS
  255. if brokerSQSQueueName != "" && brokerSQSQueueRegion != "" {
  256. log.Printf("Loading SQSHandler using SQS Queue %s in region %s\n", brokerSQSQueueName, brokerSQSQueueRegion)
  257. sqsHandlerContext := context.Background()
  258. cfg, err := config.LoadDefaultConfig(sqsHandlerContext, config.WithRegion(brokerSQSQueueRegion))
  259. if err != nil {
  260. log.Fatal(err)
  261. }
  262. client := sqs.NewFromConfig(cfg)
  263. sqsHandler, err := newSQSHandler(sqsHandlerContext, client, brokerSQSQueueName, brokerSQSQueueRegion, i)
  264. if err != nil {
  265. log.Fatal(err)
  266. }
  267. go sqsHandler.PollAndHandleMessages(sqsHandlerContext)
  268. }
  269. sigChan := make(chan os.Signal, 1)
  270. signal.Notify(sigChan, syscall.SIGHUP)
  271. // go routine to handle a SIGHUP signal to allow the broker operator to send
  272. // a SIGHUP signal when the geoip database files are updated, without requiring
  273. // a restart of the broker
  274. go func() {
  275. for {
  276. signal := <-sigChan
  277. log.Printf("Received signal: %s. Reloading geoip databases.", signal)
  278. if err = ctx.metrics.LoadGeoipDatabases(geoipDatabase, geoip6Database); err != nil {
  279. log.Fatalf("reload of Geo IP databases on signal %s returned error: %v", signal, err)
  280. }
  281. }
  282. }()
  283. // Handle the various ways of setting up TLS. The legal configurations
  284. // are:
  285. // --acme-hostnames (with optional --acme-email and/or --acme-cert-cache)
  286. // --cert and --key together
  287. // --disable-tls
  288. // The outputs of this block of code are the disableTLS,
  289. // needHTTP01Listener, certManager, and getCertificate variables.
  290. if acmeHostnamesCommas != "" {
  291. acmeHostnames := strings.Split(acmeHostnamesCommas, ",")
  292. log.Printf("ACME hostnames: %q", acmeHostnames)
  293. var cache autocert.Cache
  294. if err = os.MkdirAll(acmeCertCacheDir, 0700); err != nil {
  295. log.Printf("Warning: Couldn't create cache directory %q (reason: %s) so we're *not* using our certificate cache.", acmeCertCacheDir, err)
  296. } else {
  297. cache = autocert.DirCache(acmeCertCacheDir)
  298. }
  299. certManager := autocert.Manager{
  300. Cache: cache,
  301. Prompt: autocert.AcceptTOS,
  302. HostPolicy: autocert.HostWhitelist(acmeHostnames...),
  303. Email: acmeEmail,
  304. }
  305. go func() {
  306. log.Printf("Starting HTTP-01 listener")
  307. log.Fatal(http.ListenAndServe(":80", certManager.HTTPHandler(nil)))
  308. }()
  309. server.TLSConfig = &tls.Config{GetCertificate: certManager.GetCertificate}
  310. err = server.ListenAndServeTLS("", "")
  311. } else if certFilename != "" && keyFilename != "" {
  312. if acmeEmail != "" || acmeHostnamesCommas != "" {
  313. log.Fatalf("The --cert and --key options are not allowed with --acme-email or --acme-hostnames.")
  314. }
  315. err = server.ListenAndServeTLS(certFilename, keyFilename)
  316. } else if disableTLS {
  317. err = server.ListenAndServe()
  318. } else {
  319. log.Fatal("the --acme-hostnames, --cert and --key, or --disable-tls option is required")
  320. }
  321. if err != nil {
  322. log.Fatal(err)
  323. }
  324. }