2 Copyright (C) 2021 Sergey Matveev <stargrave@stargrave.org>
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, version 3 of the License.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program. If not, see <http://www.gnu.org/licenses/>.
39 "github.com/dustin/go-humanize"
40 "go.cypherpunks.ru/ucspi"
44 tlsNextProtoS = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
45 tlsNextProtoC = make(map[string]func(string, *tls.Conn) http.RoundTripper)
46 caCert *x509.Certificate
47 caPrv crypto.PrivateKey
50 transport = http.Transport{
51 ForceAttemptHTTP2: false,
52 DisableKeepAlives: true,
53 MaxIdleConnsPerHost: 2,
54 TLSNextProto: tlsNextProtoC,
55 DialTLSContext: dialTLS,
58 accepted = make(map[string]string)
59 acceptedM sync.RWMutex
60 rejected = make(map[string]string)
61 rejectedM sync.RWMutex
67 func spkiHash(cert *x509.Certificate) string {
68 hsh := sha256.Sum256(cert.RawSubjectPublicKeyInfo)
69 return hex.EncodeToString(hsh[:])
72 func acceptedAdd(addr, h string) {
78 func rejectedAdd(addr, h string) {
84 type ErrRejected struct {
88 func (err ErrRejected) Error() string { return err.addr + " was rejected" }
90 func dialTLS(ctx context.Context, network, addr string) (net.Conn, error) {
91 host := strings.TrimSuffix(addr, ":443")
93 VerifyPeerCertificate: func(
95 verifiedChains [][]*x509.Certificate,
97 return verifyCert(host, nil, rawCerts, verifiedChains)
100 conn, dialErr := tls.Dial(network, addr, &cfg)
102 if _, ok := dialErr.(ErrRejected); ok {
105 cfg.InsecureSkipVerify = true
106 cfg.VerifyPeerCertificate = func(
108 verifiedChains [][]*x509.Certificate,
110 return verifyCert(host, dialErr, rawCerts, verifiedChains)
113 conn, err = tls.Dial(network, addr, &cfg)
115 sinkErr <- fmt.Sprintf("%s\t%s", addr, dialErr.Error())
119 connState := conn.ConnectionState()
120 sinkTLS <- fmt.Sprintf(
122 strings.TrimSuffix(addr, ":443"),
123 ucspi.TLSVersion(connState.Version),
124 tls.CipherSuiteName(connState.CipherSuite),
125 spkiHash(connState.PeerCertificates[0]),
130 func roundTrip(w http.ResponseWriter, req *http.Request) {
131 if req.Method == http.MethodHead {
132 http.Error(w, "go away", http.StatusMethodNotAllowed)
135 sinkReq <- fmt.Sprintf("%s %s", req.Method, req.URL.String())
136 host := strings.TrimSuffix(req.URL.Host, ":443")
138 for _, spy := range SpyDomains {
139 if strings.HasSuffix(host, spy) {
140 http.NotFound(w, req)
141 sinkOther <- fmt.Sprintf(
142 "%s %s\t%d\tspy one",
151 if strings.HasPrefix(req.URL.Host, "www.reddit.com") {
152 req.URL.Host = "old.reddit.com"
153 http.Redirect(w, req, req.URL.String(), http.StatusMovedPermanently)
157 resp, err := transport.RoundTrip(req)
159 sinkErr <- fmt.Sprintf("%s\t%s", req.URL.Host, err.Error())
160 w.WriteHeader(http.StatusBadGateway)
161 w.Write([]byte(err.Error()))
165 for k, vs := range resp.Header {
166 if k == "Location" || k == "Content-Type" || k == "Content-Length" {
169 for _, v := range vs {
174 switch resp.Header.Get("Content-Type") {
175 case "application/font-woff", "application/font-sfnt":
176 // Those are deprecated types
178 case "font/otf", "font/ttf", "font/woff", "font/woff2":
179 http.NotFound(w, req)
180 sinkOther <- fmt.Sprintf(
181 "%s %s\t%d\tfonts are not allowed",
189 if strings.Contains(req.Header.Get("User-Agent"), "AppleWebKit/538.15") {
193 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.webp")
198 defer os.Remove(tmpFd.Name())
199 defer resp.Body.Close()
200 if _, err = io.Copy(tmpFd, resp.Body); err != nil {
201 log.Printf("Error during %s: %+v\n", req.URL, err)
202 http.Error(w, err.Error(), http.StatusBadGateway)
206 cmd := exec.Command(CmdDWebP, tmpFd.Name(), "-o", "-")
207 data, err := cmd.Output()
209 http.Error(w, err.Error(), http.StatusBadGateway)
212 w.Header().Add("Content-Type", "image/png")
213 w.WriteHeader(http.StatusOK)
215 sinkOther <- fmt.Sprintf(
216 "%s %s\t%d\tWebP transcoded to PNG",
223 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.jxl")
228 defer os.Remove(tmpFd.Name())
229 defer resp.Body.Close()
230 if _, err = io.Copy(tmpFd, resp.Body); err != nil {
231 log.Printf("Error during %s: %+v\n", req.URL, err)
232 http.Error(w, err.Error(), http.StatusBadGateway)
236 dstFn := tmpFd.Name() + ".png"
237 cmd := exec.Command(CmdDJXL, tmpFd.Name(), dstFn)
239 defer os.Remove(dstFn)
241 http.Error(w, err.Error(), http.StatusBadGateway)
244 data, err := ioutil.ReadFile(dstFn)
246 http.Error(w, err.Error(), http.StatusBadGateway)
249 w.Header().Add("Content-Type", "image/png")
250 w.WriteHeader(http.StatusOK)
252 sinkOther <- fmt.Sprintf(
253 "%s %s\t%d\tJPEG XL transcoded to PNG",
261 if req.Method == http.MethodGet {
263 switch resp.StatusCode {
264 case http.StatusMovedPermanently, http.StatusPermanentRedirect:
265 redirType = "permanent"
267 case http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect:
268 if strings.Contains(req.Header.Get("User-Agent"), "newsboat/") {
271 redirType = "temporary"
277 w.Header().Add("Content-Type", "text/html")
278 w.WriteHeader(http.StatusOK)
279 location := resp.Header.Get("Location")
283 <head><title>%d %s: %s redirection</title></head>
284 <body>Redirection to <a href="%s">%s</a>
286 resp.StatusCode, http.StatusText(resp.StatusCode),
287 redirType, location, location,
289 sinkRedir <- fmt.Sprintf(
290 "%s %s\t%s\t%s", req.Method, resp.Status, req.URL.String(), location,
296 for _, h := range []string{"Location", "Content-Type", "Content-Length"} {
297 if v := resp.Header.Get(h); v != "" {
301 w.WriteHeader(resp.StatusCode)
302 n, err := io.Copy(w, resp.Body)
304 log.Printf("Error during %s: %+v\n", req.URL, err)
312 resp.Header.Get("Content-Type"),
313 humanize.IBytes(uint64(n)),
315 if resp.StatusCode == http.StatusOK {
322 type Handler struct{}
324 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
325 if req.Method != http.MethodConnect {
329 hj, ok := w.(http.Hijacker)
331 log.Fatalln("no hijacking")
333 conn, _, err := hj.Hijack()
338 conn.Write([]byte(fmt.Sprintf(
341 http.StatusOK, http.StatusText(http.StatusOK),
343 host := strings.Split(req.Host, ":")[0]
345 keypair, ok := hostCerts[host]
346 if !ok || !keypair.cert.NotAfter.After(time.Now().Add(time.Hour)) {
347 keypair = newKeypair(host, caCert, caPrv)
348 hostCerts[host] = keypair
351 tlsConn := tls.Server(conn, &tls.Config{
352 Certificates: []tls.Certificate{{
353 Certificate: [][]byte{keypair.cert.Raw},
354 PrivateKey: keypair.prv,
357 if err = tlsConn.Handshake(); err != nil {
358 log.Printf("TLS error %s: %+v\n", host, err)
362 Handler: &HTTPSHandler{host: req.Host},
363 TLSNextProto: tlsNextProtoS,
365 err = srv.Serve(&SingleListener{conn: tlsConn})
367 if _, ok := err.(AlreadyAccepted); !ok {
368 log.Printf("TLS serve error %s: %+v\n", host, err)
374 type HTTPSHandler struct {
378 func (h *HTTPSHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
379 req.URL.Scheme = "https"
380 req.URL.Host = h.host
385 crtPath := flag.String("cert", "cert.pem", "Path to server X.509 certificate")
386 prvPath := flag.String("key", "prv.pem", "Path to server PKCS#8 private key")
387 bind := flag.String("bind", "[::1]:8080", "Bind address")
388 certs = flag.String("certs", "certs", "Directory with pinned certificates")
389 dnsSrv = flag.String("dns", "[::1]:53", "DNS server")
390 fifos = flag.String("fifos", "fifos", "Directory with FIFOs")
391 notai = flag.Bool("notai", false, "Do not prepend TAI64N to logs")
393 log.SetFlags(log.Lshortfile)
397 _, caCert, err = ucspi.CertificateFromFile(*crtPath)
401 caPrv, err = ucspi.PrivateKeyFromFile(*prvPath)
406 ln, err := net.Listen("tcp", *bind)
412 TLSNextProto: tlsNextProtoS,
414 srv.SetKeepAlivesEnabled(false)
415 log.Println("listening:", *bind)
416 if err := srv.Serve(ln); err != nil {