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,
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)
64 conn, dialErr := tls.Dial(network, addr, &cfg)
66 if _, ok := dialErr.(ErrRejected); ok {
69 cfg.InsecureSkipVerify = true
70 cfg.VerifyPeerCertificate = func(
72 verifiedChains [][]*x509.Certificate,
74 return verifyCert(host, dialErr, rawCerts, verifiedChains)
77 conn, err = tls.Dial(network, addr, &cfg)
79 sinkErr <- fmt.Sprintf("%s\t%s", addr, dialErr.Error())
83 connState := conn.ConnectionState()
84 sinkTLS <- fmt.Sprintf(
86 strings.TrimSuffix(addr, ":443"),
87 ucspi.TLSVersion(connState.Version),
88 tls.CipherSuiteName(connState.CipherSuite),
89 spkiHash(connState.PeerCertificates[0]),
94 func roundTrip(w http.ResponseWriter, req *http.Request) {
95 if req.Method == http.MethodHead {
96 http.Error(w, "go away", http.StatusMethodNotAllowed)
99 sinkReq <- fmt.Sprintf("%s %s", req.Method, req.URL.String())
100 host := strings.TrimSuffix(req.URL.Host, ":443")
102 for _, spy := range SpyDomains {
103 if strings.HasSuffix(host, spy) {
104 http.NotFound(w, req)
105 sinkOther <- fmt.Sprintf(
106 "%s %s\t%d\tspy one",
115 if strings.HasPrefix(req.URL.Host, "www.reddit.com") {
116 req.URL.Host = "old.reddit.com"
117 http.Redirect(w, req, req.URL.String(), http.StatusMovedPermanently)
121 resp, err := transport.RoundTrip(req)
123 sinkErr <- fmt.Sprintf("%s\t%s", req.URL.Host, err.Error())
124 w.WriteHeader(http.StatusBadGateway)
125 w.Write([]byte(err.Error()))
129 for k, vs := range resp.Header {
130 if k == "Location" || k == "Content-Type" || k == "Content-Length" {
133 for _, v := range vs {
138 switch resp.Header.Get("Content-Type") {
139 case "application/font-woff", "application/font-sfnt":
140 // Those are deprecated types
142 case "font/otf", "font/ttf", "font/woff", "font/woff2":
143 http.NotFound(w, req)
144 sinkOther <- fmt.Sprintf(
145 "%s %s\t%d\tfonts are not allowed",
153 if strings.Contains(req.Header.Get("User-Agent"), "AppleWebKit/538.15") {
157 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.webp")
162 defer os.Remove(tmpFd.Name())
163 defer resp.Body.Close()
164 if _, err = io.Copy(tmpFd, resp.Body); err != nil {
165 log.Printf("Error during %s: %+v\n", req.URL, err)
166 http.Error(w, err.Error(), http.StatusBadGateway)
170 cmd := exec.Command(CmdDWebP, tmpFd.Name(), "-o", "-")
171 data, err := cmd.Output()
173 http.Error(w, err.Error(), http.StatusBadGateway)
176 w.Header().Add("Content-Type", "image/png")
177 w.WriteHeader(http.StatusOK)
179 sinkOther <- fmt.Sprintf(
180 "%s %s\t%d\tWebP transcoded to PNG",
187 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.jxl")
192 defer os.Remove(tmpFd.Name())
193 defer resp.Body.Close()
194 if _, err = io.Copy(tmpFd, resp.Body); err != nil {
195 log.Printf("Error during %s: %+v\n", req.URL, err)
196 http.Error(w, err.Error(), http.StatusBadGateway)
200 dstFn := tmpFd.Name() + ".png"
201 cmd := exec.Command(CmdDJXL, tmpFd.Name(), dstFn)
203 defer os.Remove(dstFn)
205 http.Error(w, err.Error(), http.StatusBadGateway)
208 data, err := ioutil.ReadFile(dstFn)
210 http.Error(w, err.Error(), http.StatusBadGateway)
213 w.Header().Add("Content-Type", "image/png")
214 w.WriteHeader(http.StatusOK)
216 sinkOther <- fmt.Sprintf(
217 "%s %s\t%d\tJPEG XL transcoded to PNG",
225 if req.Method == http.MethodGet {
227 switch resp.StatusCode {
228 case http.StatusMovedPermanently, http.StatusPermanentRedirect:
229 redirType = "permanent"
231 case http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect:
232 if strings.Contains(req.Header.Get("User-Agent"), "newsboat/") {
235 redirType = "temporary"
241 w.Header().Add("Content-Type", "text/html")
242 w.WriteHeader(http.StatusOK)
243 location := resp.Header.Get("Location")
247 <head><title>%d %s: %s redirection</title></head>
248 <body>Redirection to <a href="%s">%s</a>
250 resp.StatusCode, http.StatusText(resp.StatusCode),
251 redirType, location, location,
253 sinkRedir <- fmt.Sprintf(
254 "%s %s\t%s\t%s", req.Method, resp.Status, req.URL.String(), location,
260 for _, h := range []string{"Location", "Content-Type", "Content-Length"} {
261 if v := resp.Header.Get(h); v != "" {
265 w.WriteHeader(resp.StatusCode)
266 n, err := io.Copy(w, resp.Body)
268 log.Printf("Error during %s: %+v\n", req.URL, err)
276 resp.Header.Get("Content-Type"),
277 humanize.IBytes(uint64(n)),
279 if resp.StatusCode == http.StatusOK {
286 type Handler struct{}
288 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
289 if req.Method != http.MethodConnect {
293 hj, ok := w.(http.Hijacker)
295 log.Fatalln("no hijacking")
297 conn, _, err := hj.Hijack()
302 conn.Write([]byte(fmt.Sprintf(
305 http.StatusOK, http.StatusText(http.StatusOK),
307 host := strings.Split(req.Host, ":")[0]
309 keypair, ok := hostCerts[host]
310 if !ok || !keypair.cert.NotAfter.After(time.Now().Add(time.Hour)) {
311 keypair = newKeypair(host, caCert, caPrv)
312 hostCerts[host] = keypair
315 tlsConn := tls.Server(conn, &tls.Config{
316 Certificates: []tls.Certificate{{
317 Certificate: [][]byte{keypair.cert.Raw},
318 PrivateKey: keypair.prv,
321 if err = tlsConn.Handshake(); err != nil {
322 log.Printf("TLS error %s: %+v\n", host, err)
326 Handler: &HTTPSHandler{host: req.Host},
327 TLSNextProto: tlsNextProtoS,
329 err = srv.Serve(&SingleListener{conn: tlsConn})
331 if _, ok := err.(AlreadyAccepted); !ok {
332 log.Printf("TLS serve error %s: %+v\n", host, err)
338 type HTTPSHandler struct {
342 func (h *HTTPSHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
343 req.URL.Scheme = "https"
344 req.URL.Host = h.host
349 crtPath := flag.String("cert", "cert.pem", "Path to server X.509 certificate")
350 prvPath := flag.String("key", "prv.pem", "Path to server PKCS#8 private key")
351 bind := flag.String("bind", "[::1]:8080", "Bind address")
352 certs = flag.String("certs", "certs", "Directory with pinned certificates")
353 dnsSrv = flag.String("dns", "[::1]:53", "DNS server")
354 fifos = flag.String("fifos", "fifos", "Directory with FIFOs")
355 notai = flag.Bool("notai", false, "Do not prepend TAI64N to logs")
357 log.SetFlags(log.Lshortfile)
361 _, caCert, err = ucspi.CertificateFromFile(*crtPath)
365 caPrv, err = ucspi.PrivateKeyFromFile(*prvPath)
370 ln, err := net.Listen("tcp", *bind)
376 TLSNextProto: tlsNextProtoS,
378 log.Println("listening:", *bind)
379 if err := srv.Serve(ln); err != nil {