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/>.
36 "github.com/dustin/go-humanize"
37 "go.cypherpunks.ru/ucspi"
41 tlsNextProtoS = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
42 caCert *x509.Certificate
43 caPrv crypto.PrivateKey
44 transport = http.Transport{
45 DialTLSContext: dialTLS,
46 ForceAttemptHTTP2: true,
48 sessionCache = tls.NewLRUClientSessionCache(1024)
54 func dialTLS(ctx context.Context, network, addr string) (net.Conn, error) {
55 host := strings.TrimSuffix(addr, ":443")
57 VerifyPeerCertificate: func(
59 verifiedChains [][]*x509.Certificate,
61 return verifyCert(host, nil, rawCerts, verifiedChains)
63 ClientSessionCache: sessionCache,
64 NextProtos: []string{"h2", "http/1.1"},
66 conn, dialErr := tls.Dial(network, addr, &cfg)
68 if _, ok := dialErr.(ErrRejected); ok {
71 cfg.InsecureSkipVerify = true
72 cfg.VerifyPeerCertificate = func(
74 verifiedChains [][]*x509.Certificate,
76 return verifyCert(host, dialErr, rawCerts, verifiedChains)
79 conn, err = tls.Dial(network, addr, &cfg)
81 sinkErr <- fmt.Sprintf("%s\t%s", addr, dialErr.Error())
85 connState := conn.ConnectionState()
86 if connState.DidResume {
87 sinkTLS <- fmt.Sprintf(
89 strings.TrimSuffix(addr, ":443"),
90 ucspi.TLSVersion(connState.Version),
91 tls.CipherSuiteName(connState.CipherSuite),
92 spkiHash(connState.PeerCertificates[0]),
93 connState.NegotiatedProtocol,
99 func roundTrip(w http.ResponseWriter, req *http.Request) {
100 if req.Method == http.MethodHead {
101 http.Error(w, "go away", http.StatusMethodNotAllowed)
104 sinkReq <- fmt.Sprintf("%s %s", req.Method, req.URL.String())
105 host := strings.TrimSuffix(req.URL.Host, ":443")
107 for _, spy := range SpyDomains {
108 if strings.HasSuffix(host, spy) {
109 http.NotFound(w, req)
110 sinkOther <- fmt.Sprintf(
111 "%s %s\t%d\tspy one",
120 if strings.HasPrefix(req.URL.Host, "www.reddit.com") {
121 req.URL.Host = "old.reddit.com"
122 http.Redirect(w, req, req.URL.String(), http.StatusMovedPermanently)
126 resp, err := transport.RoundTrip(req)
128 sinkErr <- fmt.Sprintf("%s\t%s", req.URL.Host, err.Error())
129 w.WriteHeader(http.StatusBadGateway)
130 w.Write([]byte(err.Error()))
134 for k, vs := range resp.Header {
135 if k == "Location" || k == "Content-Type" || k == "Content-Length" {
138 for _, v := range vs {
143 switch resp.Header.Get("Content-Type") {
144 case "application/font-woff", "application/font-sfnt":
145 // Those are deprecated types
147 case "font/otf", "font/ttf", "font/woff", "font/woff2":
148 http.NotFound(w, req)
149 sinkOther <- fmt.Sprintf(
150 "%s %s\t%d\tfonts are not allowed",
158 if strings.Contains(req.Header.Get("User-Agent"), "AppleWebKit/538.15") {
162 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.webp")
167 defer os.Remove(tmpFd.Name())
168 defer resp.Body.Close()
169 if _, err = io.Copy(tmpFd, resp.Body); err != nil {
170 log.Printf("Error during %s: %+v\n", req.URL, err)
171 http.Error(w, err.Error(), http.StatusBadGateway)
175 cmd := exec.Command(CmdDWebP, tmpFd.Name(), "-o", "-")
176 data, err := cmd.Output()
178 http.Error(w, err.Error(), http.StatusBadGateway)
181 w.Header().Add("Content-Type", "image/png")
182 w.WriteHeader(http.StatusOK)
184 sinkOther <- fmt.Sprintf(
185 "%s %s\t%d\tWebP transcoded to PNG",
192 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.jxl")
197 defer os.Remove(tmpFd.Name())
198 defer resp.Body.Close()
199 if _, err = io.Copy(tmpFd, resp.Body); err != nil {
200 log.Printf("Error during %s: %+v\n", req.URL, err)
201 http.Error(w, err.Error(), http.StatusBadGateway)
205 dstFn := tmpFd.Name() + ".png"
206 cmd := exec.Command(CmdDJXL, tmpFd.Name(), dstFn)
208 defer os.Remove(dstFn)
210 http.Error(w, err.Error(), http.StatusBadGateway)
213 data, err := ioutil.ReadFile(dstFn)
215 http.Error(w, err.Error(), http.StatusBadGateway)
218 w.Header().Add("Content-Type", "image/png")
219 w.WriteHeader(http.StatusOK)
221 sinkOther <- fmt.Sprintf(
222 "%s %s\t%d\tJPEG XL transcoded to PNG",
230 if req.Method == http.MethodGet {
232 switch resp.StatusCode {
233 case http.StatusMovedPermanently, http.StatusPermanentRedirect:
234 redirType = "permanent"
236 case http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect:
237 if strings.Contains(req.Header.Get("User-Agent"), "newsboat/") {
240 redirType = "temporary"
246 w.Header().Add("Content-Type", "text/html")
247 w.WriteHeader(http.StatusOK)
248 location := resp.Header.Get("Location")
252 <head><title>%d %s: %s redirection</title></head>
253 <body>Redirection to <a href="%s">%s</a>
255 resp.StatusCode, http.StatusText(resp.StatusCode),
256 redirType, location, location,
258 sinkRedir <- fmt.Sprintf(
259 "%s %s\t%s\t%s", req.Method, resp.Status, req.URL.String(), location,
265 for _, h := range []string{"Location", "Content-Type", "Content-Length"} {
266 if v := resp.Header.Get(h); v != "" {
270 w.WriteHeader(resp.StatusCode)
271 n, err := io.Copy(w, resp.Body)
273 log.Printf("Error during %s: %+v\n", req.URL, err)
281 resp.Header.Get("Content-Type"),
282 humanize.IBytes(uint64(n)),
284 if resp.StatusCode == http.StatusOK {
291 type Handler struct{}
293 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
294 if req.Method != http.MethodConnect {
298 hj, ok := w.(http.Hijacker)
300 log.Fatalln("no hijacking")
302 conn, _, err := hj.Hijack()
307 conn.Write([]byte(fmt.Sprintf(
310 http.StatusOK, http.StatusText(http.StatusOK),
312 host := strings.Split(req.Host, ":")[0]
314 keypair, ok := hostCerts[host]
315 if !ok || !keypair.cert.NotAfter.After(time.Now().Add(time.Hour)) {
316 keypair = newKeypair(host, caCert, caPrv)
317 hostCerts[host] = keypair
320 tlsConn := tls.Server(conn, &tls.Config{
321 Certificates: []tls.Certificate{{
322 Certificate: [][]byte{keypair.cert.Raw},
323 PrivateKey: keypair.prv,
326 if err = tlsConn.Handshake(); err != nil {
327 log.Printf("TLS error %s: %+v\n", host, err)
331 Handler: &HTTPSHandler{host: req.Host},
332 TLSNextProto: tlsNextProtoS,
334 err = srv.Serve(&SingleListener{conn: tlsConn})
336 if _, ok := err.(AlreadyAccepted); !ok {
337 log.Printf("TLS serve error %s: %+v\n", host, err)
343 type HTTPSHandler struct {
347 func (h *HTTPSHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
348 req.URL.Scheme = "https"
349 req.URL.Host = h.host
354 crtPath := flag.String("cert", "cert.pem", "Path to server X.509 certificate")
355 prvPath := flag.String("key", "prv.pem", "Path to server PKCS#8 private key")
356 bind := flag.String("bind", "[::1]:8080", "Bind address")
357 certs = flag.String("certs", "certs", "Directory with pinned certificates")
358 dnsSrv = flag.String("dns", "[::1]:53", "DNS server")
359 fifos = flag.String("fifos", "fifos", "Directory with FIFOs")
360 notai = flag.Bool("notai", false, "Do not prepend TAI64N to logs")
362 log.SetFlags(log.Lshortfile)
366 _, caCert, err = ucspi.CertificateFromFile(*crtPath)
370 caPrv, err = ucspi.PrivateKeyFromFile(*prvPath)
375 ln, err := net.Listen("tcp", *bind)
381 TLSNextProto: tlsNextProtoS,
383 log.Println("listening:", *bind)
384 if err := srv.Serve(ln); err != nil {