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 ForceAttemptHTTP2: false,
46 TLSNextProto: make(map[string]func(string, *tls.Conn) http.RoundTripper),
47 DialTLSContext: dialTLS,
49 sessionCache = tls.NewLRUClientSessionCache(1024)
55 func dialTLS(ctx context.Context, network, addr string) (net.Conn, error) {
56 host := strings.TrimSuffix(addr, ":443")
58 VerifyPeerCertificate: func(
60 verifiedChains [][]*x509.Certificate,
62 return verifyCert(host, nil, rawCerts, verifiedChains)
64 ClientSessionCache: sessionCache,
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()
88 strings.TrimSuffix(addr, ":443"),
89 ucspi.TLSVersion(connState.Version),
90 tls.CipherSuiteName(connState.CipherSuite),
91 spkiHash(connState.PeerCertificates[0]),
93 if connState.DidResume {
100 func roundTrip(w http.ResponseWriter, req *http.Request) {
101 if req.Method == http.MethodHead {
102 http.Error(w, "go away", http.StatusMethodNotAllowed)
105 sinkReq <- fmt.Sprintf("%s %s", req.Method, req.URL.String())
106 host := strings.TrimSuffix(req.URL.Host, ":443")
108 for _, spy := range SpyDomains {
109 if strings.HasSuffix(host, spy) {
110 http.NotFound(w, req)
111 sinkOther <- fmt.Sprintf(
112 "%s %s\t%d\tspy one",
121 if strings.HasPrefix(req.URL.Host, "www.reddit.com") {
122 req.URL.Host = "old.reddit.com"
123 http.Redirect(w, req, req.URL.String(), http.StatusMovedPermanently)
127 resp, err := transport.RoundTrip(req)
129 sinkErr <- fmt.Sprintf("%s\t%s", req.URL.Host, err.Error())
130 w.WriteHeader(http.StatusBadGateway)
131 w.Write([]byte(err.Error()))
135 for k, vs := range resp.Header {
136 if k == "Location" || k == "Content-Type" || k == "Content-Length" {
139 for _, v := range vs {
144 switch resp.Header.Get("Content-Type") {
145 case "application/font-woff", "application/font-sfnt":
146 // Those are deprecated types
148 case "font/otf", "font/ttf", "font/woff", "font/woff2":
149 http.NotFound(w, req)
150 sinkOther <- fmt.Sprintf(
151 "%s %s\t%d\tfonts are not allowed",
159 if strings.Contains(req.Header.Get("User-Agent"), "AppleWebKit/538.15") {
163 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.webp")
168 defer os.Remove(tmpFd.Name())
169 defer resp.Body.Close()
170 if _, err = io.Copy(tmpFd, resp.Body); err != nil {
171 log.Printf("Error during %s: %+v\n", req.URL, err)
172 http.Error(w, err.Error(), http.StatusBadGateway)
176 cmd := exec.Command(CmdDWebP, tmpFd.Name(), "-o", "-")
177 data, err := cmd.Output()
179 http.Error(w, err.Error(), http.StatusBadGateway)
182 w.Header().Add("Content-Type", "image/png")
183 w.WriteHeader(http.StatusOK)
185 sinkOther <- fmt.Sprintf(
186 "%s %s\t%d\tWebP transcoded to PNG",
193 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.jxl")
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 dstFn := tmpFd.Name() + ".png"
207 cmd := exec.Command(CmdDJXL, tmpFd.Name(), dstFn)
209 defer os.Remove(dstFn)
211 http.Error(w, err.Error(), http.StatusBadGateway)
214 data, err := ioutil.ReadFile(dstFn)
216 http.Error(w, err.Error(), http.StatusBadGateway)
219 w.Header().Add("Content-Type", "image/png")
220 w.WriteHeader(http.StatusOK)
222 sinkOther <- fmt.Sprintf(
223 "%s %s\t%d\tJPEG XL transcoded to PNG",
231 if req.Method == http.MethodGet {
233 switch resp.StatusCode {
234 case http.StatusMovedPermanently, http.StatusPermanentRedirect:
235 redirType = "permanent"
237 case http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect:
238 if strings.Contains(req.Header.Get("User-Agent"), "newsboat/") {
241 redirType = "temporary"
247 w.Header().Add("Content-Type", "text/html")
248 w.WriteHeader(http.StatusOK)
249 location := resp.Header.Get("Location")
253 <head><title>%d %s: %s redirection</title></head>
254 <body>Redirection to <a href="%s">%s</a>
256 resp.StatusCode, http.StatusText(resp.StatusCode),
257 redirType, location, location,
259 sinkRedir <- fmt.Sprintf(
260 "%s %s\t%s\t%s", req.Method, resp.Status, req.URL.String(), location,
266 for _, h := range []string{"Location", "Content-Type", "Content-Length"} {
267 if v := resp.Header.Get(h); v != "" {
271 w.WriteHeader(resp.StatusCode)
272 n, err := io.Copy(w, resp.Body)
274 log.Printf("Error during %s: %+v\n", req.URL, err)
282 resp.Header.Get("Content-Type"),
283 humanize.IBytes(uint64(n)),
285 if resp.StatusCode == http.StatusOK {
292 type Handler struct{}
294 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
295 if req.Method != http.MethodConnect {
299 hj, ok := w.(http.Hijacker)
301 log.Fatalln("no hijacking")
303 conn, _, err := hj.Hijack()
308 conn.Write([]byte(fmt.Sprintf(
311 http.StatusOK, http.StatusText(http.StatusOK),
313 host := strings.Split(req.Host, ":")[0]
315 keypair, ok := hostCerts[host]
316 if !ok || !keypair.cert.NotAfter.After(time.Now().Add(time.Hour)) {
317 keypair = newKeypair(host, caCert, caPrv)
318 hostCerts[host] = keypair
321 tlsConn := tls.Server(conn, &tls.Config{
322 Certificates: []tls.Certificate{{
323 Certificate: [][]byte{keypair.cert.Raw},
324 PrivateKey: keypair.prv,
327 if err = tlsConn.Handshake(); err != nil {
328 log.Printf("TLS error %s: %+v\n", host, err)
332 Handler: &HTTPSHandler{host: req.Host},
333 TLSNextProto: tlsNextProtoS,
335 err = srv.Serve(&SingleListener{conn: tlsConn})
337 if _, ok := err.(AlreadyAccepted); !ok {
338 log.Printf("TLS serve error %s: %+v\n", host, err)
344 type HTTPSHandler struct {
348 func (h *HTTPSHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
349 req.URL.Scheme = "https"
350 req.URL.Host = h.host
355 crtPath := flag.String("cert", "cert.pem", "Path to server X.509 certificate")
356 prvPath := flag.String("key", "prv.pem", "Path to server PKCS#8 private key")
357 bind := flag.String("bind", "[::1]:8080", "Bind address")
358 certs = flag.String("certs", "certs", "Directory with pinned certificates")
359 dnsSrv = flag.String("dns", "[::1]:53", "DNS server")
360 fifos = flag.String("fifos", "fifos", "Directory with FIFOs")
361 notai = flag.Bool("notai", false, "Do not prepend TAI64N to logs")
363 log.SetFlags(log.Lshortfile)
367 _, caCert, err = ucspi.CertificateFromFile(*crtPath)
371 caPrv, err = ucspi.PrivateKeyFromFile(*prvPath)
376 ln, err := net.Listen("tcp", *bind)
382 TLSNextProto: tlsNextProtoS,
384 log.Println("listening:", *bind)
385 if err := srv.Serve(ln); err != nil {