]> Sergey Matveev's repositories - tofuproxy.git/blob - main.go
More reliable Habr hack
[tofuproxy.git] / main.go
1 /*
2 Copyright (C) 2021 Sergey Matveev <stargrave@stargrave.org>
3
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.
7
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.
12
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/>.
15 */
16
17 package main
18
19 import (
20         "context"
21         "crypto"
22         "crypto/tls"
23         "crypto/x509"
24         "flag"
25         "fmt"
26         "io"
27         "io/ioutil"
28         "log"
29         "net"
30         "net/http"
31         "os"
32         "os/exec"
33         "path/filepath"
34         "strings"
35         "time"
36
37         "github.com/dustin/go-humanize"
38         "go.cypherpunks.ru/ucspi"
39 )
40
41 var (
42         tlsNextProtoS = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
43         caCert        *x509.Certificate
44         caPrv         crypto.PrivateKey
45         transport     = http.Transport{
46                 DialTLSContext:    dialTLS,
47                 ForceAttemptHTTP2: true,
48         }
49         sessionCache = tls.NewLRUClientSessionCache(1024)
50
51         CmdDWebP = "dwebp"
52         CmdDJXL  = "djxl"
53
54         imageExts = map[string]struct{}{
55                 ".apng": {},
56                 ".avif": {},
57                 ".gif":  {},
58                 ".heic": {},
59                 ".jp2":  {},
60                 ".jpeg": {},
61                 ".jpg":  {},
62                 ".jxl":  {},
63                 ".mng":  {},
64                 ".png":  {},
65                 ".svg":  {},
66                 ".tif":  {},
67                 ".tiff": {},
68                 ".webp": {},
69         }
70 )
71
72 func dialTLS(ctx context.Context, network, addr string) (net.Conn, error) {
73         host := strings.TrimSuffix(addr, ":443")
74         cfg := tls.Config{
75                 VerifyPeerCertificate: func(
76                         rawCerts [][]byte,
77                         verifiedChains [][]*x509.Certificate,
78                 ) error {
79                         return verifyCert(host, nil, rawCerts, verifiedChains)
80                 },
81                 ClientSessionCache: sessionCache,
82                 NextProtos:         []string{"h2", "http/1.1"},
83         }
84         conn, dialErr := tls.Dial(network, addr, &cfg)
85         if dialErr != nil {
86                 if _, ok := dialErr.(ErrRejected); ok {
87                         return nil, dialErr
88                 }
89                 cfg.InsecureSkipVerify = true
90                 cfg.VerifyPeerCertificate = func(
91                         rawCerts [][]byte,
92                         verifiedChains [][]*x509.Certificate,
93                 ) error {
94                         return verifyCert(host, dialErr, rawCerts, verifiedChains)
95                 }
96                 var err error
97                 conn, err = tls.Dial(network, addr, &cfg)
98                 if err != nil {
99                         sinkErr <- fmt.Sprintf("%s\t%s", addr, dialErr.Error())
100                         return nil, err
101                 }
102         }
103         connState := conn.ConnectionState()
104         if connState.DidResume {
105                 sinkTLS <- fmt.Sprintf(
106                         "%s\t%s %s\t%s\t%s",
107                         strings.TrimSuffix(addr, ":443"),
108                         ucspi.TLSVersion(connState.Version),
109                         tls.CipherSuiteName(connState.CipherSuite),
110                         spkiHash(connState.PeerCertificates[0]),
111                         connState.NegotiatedProtocol,
112                 )
113         }
114         return conn, nil
115 }
116
117 func roundTrip(w http.ResponseWriter, req *http.Request) {
118         if req.Method == http.MethodHead {
119                 http.Error(w, "go away", http.StatusMethodNotAllowed)
120                 return
121         }
122         sinkReq <- fmt.Sprintf("%s %s", req.Method, req.URL.String())
123         host := strings.TrimSuffix(req.URL.Host, ":443")
124
125         for _, spy := range SpyDomains {
126                 if strings.HasSuffix(host, spy) {
127                         http.NotFound(w, req)
128                         sinkOther <- fmt.Sprintf(
129                                 "%s %s\t%d\tspy one",
130                                 req.Method,
131                                 req.URL.String(),
132                                 http.StatusNotFound,
133                         )
134                         return
135                 }
136         }
137
138         if host == "www.reddit.com" {
139                 req.URL.Host = "old.reddit.com"
140                 http.Redirect(w, req, req.URL.String(), http.StatusMovedPermanently)
141                 return
142         }
143
144         if host == "habrastorage.org" && strings.Contains(req.URL.Path, "r/w780q1") {
145                 req.URL.Path = strings.Replace(req.URL.Path, "r/w780q1/", "", 1)
146                 http.Redirect(w, req, req.URL.String(), http.StatusFound)
147                 return
148         }
149
150         resp, err := transport.RoundTrip(req)
151         if err != nil {
152                 sinkErr <- fmt.Sprintf("%s\t%s", req.URL.Host, err.Error())
153                 w.WriteHeader(http.StatusBadGateway)
154                 w.Write([]byte(err.Error()))
155                 return
156         }
157
158         for k, vs := range resp.Header {
159                 if k == "Location" || k == "Content-Type" || k == "Content-Length" {
160                         continue
161                 }
162                 for _, v := range vs {
163                         w.Header().Add(k, v)
164                 }
165         }
166
167         switch resp.Header.Get("Content-Type") {
168         case "application/font-woff", "application/font-sfnt":
169                 // Those are deprecated types
170                 fallthrough
171         case "font/otf", "font/ttf", "font/woff", "font/woff2":
172                 http.NotFound(w, req)
173                 sinkOther <- fmt.Sprintf(
174                         "%s %s\t%d\tfonts are not allowed",
175                         req.Method,
176                         req.URL.String(),
177                         http.StatusNotFound,
178                 )
179                 resp.Body.Close()
180                 return
181         case "image/webp":
182                 if strings.Contains(req.Header.Get("User-Agent"), "AppleWebKit/538.15") {
183                         // My Xombrero
184                         break
185                 }
186                 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.webp")
187                 if err != nil {
188                         log.Fatalln(err)
189                 }
190                 defer tmpFd.Close()
191                 defer os.Remove(tmpFd.Name())
192                 defer resp.Body.Close()
193                 if _, err = io.Copy(tmpFd, resp.Body); err != nil {
194                         log.Printf("Error during %s: %+v\n", req.URL, err)
195                         http.Error(w, err.Error(), http.StatusBadGateway)
196                         return
197                 }
198                 tmpFd.Close()
199                 cmd := exec.Command(CmdDWebP, tmpFd.Name(), "-o", "-")
200                 data, err := cmd.Output()
201                 if err != nil {
202                         http.Error(w, err.Error(), http.StatusBadGateway)
203                         return
204                 }
205                 w.Header().Add("Content-Type", "image/png")
206                 w.WriteHeader(http.StatusOK)
207                 w.Write(data)
208                 sinkOther <- fmt.Sprintf(
209                         "%s %s\t%d\tWebP transcoded to PNG",
210                         req.Method,
211                         req.URL.String(),
212                         http.StatusOK,
213                 )
214                 return
215         case "image/jxl":
216                 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.jxl")
217                 if err != nil {
218                         log.Fatalln(err)
219                 }
220                 defer tmpFd.Close()
221                 defer os.Remove(tmpFd.Name())
222                 defer resp.Body.Close()
223                 if _, err = io.Copy(tmpFd, resp.Body); err != nil {
224                         log.Printf("Error during %s: %+v\n", req.URL, err)
225                         http.Error(w, err.Error(), http.StatusBadGateway)
226                         return
227                 }
228                 tmpFd.Close()
229                 dstFn := tmpFd.Name() + ".png"
230                 cmd := exec.Command(CmdDJXL, tmpFd.Name(), dstFn)
231                 err = cmd.Run()
232                 defer os.Remove(dstFn)
233                 if err != nil {
234                         http.Error(w, err.Error(), http.StatusBadGateway)
235                         return
236                 }
237                 data, err := ioutil.ReadFile(dstFn)
238                 if err != nil {
239                         http.Error(w, err.Error(), http.StatusBadGateway)
240                         return
241                 }
242                 w.Header().Add("Content-Type", "image/png")
243                 w.WriteHeader(http.StatusOK)
244                 w.Write(data)
245                 sinkOther <- fmt.Sprintf(
246                         "%s %s\t%d\tJPEG XL transcoded to PNG",
247                         req.Method,
248                         req.URL.String(),
249                         http.StatusOK,
250                 )
251                 return
252         }
253
254         if req.Method == http.MethodGet {
255                 var redirType string
256                 switch resp.StatusCode {
257                 case http.StatusMovedPermanently, http.StatusPermanentRedirect:
258                         redirType = "permanent"
259                         goto Redir
260                 case http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect:
261                         if strings.Contains(req.Header.Get("User-Agent"), "newsboat/") {
262                                 goto NoRedir
263                         }
264                         if _, ok := imageExts[filepath.Ext(req.URL.Path)]; ok {
265                                 goto NoRedir
266                         }
267                         redirType = "temporary"
268                 default:
269                         goto NoRedir
270                 }
271         Redir:
272                 resp.Body.Close()
273                 w.Header().Add("Content-Type", "text/html")
274                 w.WriteHeader(http.StatusOK)
275                 location := resp.Header.Get("Location")
276                 w.Write([]byte(
277                         fmt.Sprintf(
278                                 `<html><head><title>%d %s: %s redirection</title></head>
279 <body>Redirection to <a href="%s">%s</a></body></html>`,
280                                 resp.StatusCode, http.StatusText(resp.StatusCode),
281                                 redirType, location, location,
282                         )))
283                 sinkRedir <- fmt.Sprintf(
284                         "%s %s\t%s\t%s", req.Method, resp.Status, req.URL.String(), location,
285                 )
286                 return
287         }
288
289 NoRedir:
290         for _, h := range []string{"Location", "Content-Type", "Content-Length"} {
291                 if v := resp.Header.Get(h); v != "" {
292                         w.Header().Add(h, v)
293                 }
294         }
295         w.WriteHeader(resp.StatusCode)
296         n, err := io.Copy(w, resp.Body)
297         if err != nil {
298                 log.Printf("Error during %s: %+v\n", req.URL, err)
299         }
300         resp.Body.Close()
301         msg := fmt.Sprintf(
302                 "%s %s\t%s\t%s\t%s",
303                 req.Method,
304                 req.URL.String(),
305                 resp.Status,
306                 resp.Header.Get("Content-Type"),
307                 humanize.IBytes(uint64(n)),
308         )
309         if resp.StatusCode == http.StatusOK {
310                 sinkOK <- msg
311         } else {
312                 sinkOther <- msg
313         }
314 }
315
316 type Handler struct{}
317
318 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
319         if req.Method != http.MethodConnect {
320                 roundTrip(w, req)
321                 return
322         }
323         hj, ok := w.(http.Hijacker)
324         if !ok {
325                 log.Fatalln("no hijacking")
326         }
327         conn, _, err := hj.Hijack()
328         if err != nil {
329                 log.Fatalln(err)
330         }
331         defer conn.Close()
332         conn.Write([]byte(fmt.Sprintf(
333                 "%s %d %s\r\n\r\n",
334                 req.Proto,
335                 http.StatusOK, http.StatusText(http.StatusOK),
336         )))
337         host := strings.Split(req.Host, ":")[0]
338         hostCertsM.Lock()
339         keypair, ok := hostCerts[host]
340         if !ok || !keypair.cert.NotAfter.After(time.Now().Add(time.Hour)) {
341                 keypair = newKeypair(host, caCert, caPrv)
342                 hostCerts[host] = keypair
343         }
344         hostCertsM.Unlock()
345         tlsConn := tls.Server(conn, &tls.Config{
346                 Certificates: []tls.Certificate{{
347                         Certificate: [][]byte{keypair.cert.Raw},
348                         PrivateKey:  keypair.prv,
349                 }},
350         })
351         if err = tlsConn.Handshake(); err != nil {
352                 log.Printf("TLS error %s: %+v\n", host, err)
353                 return
354         }
355         srv := http.Server{
356                 Handler:      &HTTPSHandler{host: req.Host},
357                 TLSNextProto: tlsNextProtoS,
358         }
359         err = srv.Serve(&SingleListener{conn: tlsConn})
360         if err != nil {
361                 if _, ok := err.(AlreadyAccepted); !ok {
362                         log.Printf("TLS serve error %s: %+v\n", host, err)
363                         return
364                 }
365         }
366 }
367
368 type HTTPSHandler struct {
369         host string
370 }
371
372 func (h *HTTPSHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
373         req.URL.Scheme = "https"
374         req.URL.Host = h.host
375         roundTrip(w, req)
376 }
377
378 func main() {
379         crtPath := flag.String("cert", "cert.pem", "Path to server X.509 certificate")
380         prvPath := flag.String("key", "prv.pem", "Path to server PKCS#8 private key")
381         bind := flag.String("bind", "[::1]:8080", "Bind address")
382         certs = flag.String("certs", "certs", "Directory with pinned certificates")
383         dnsSrv = flag.String("dns", "[::1]:53", "DNS server")
384         fifos = flag.String("fifos", "fifos", "Directory with FIFOs")
385         notai = flag.Bool("notai", false, "Do not prepend TAI64N to logs")
386         flag.Parse()
387         log.SetFlags(log.Lshortfile)
388         fifoInit()
389
390         var err error
391         _, caCert, err = ucspi.CertificateFromFile(*crtPath)
392         if err != nil {
393                 log.Fatalln(err)
394         }
395         caPrv, err = ucspi.PrivateKeyFromFile(*prvPath)
396         if err != nil {
397                 log.Fatalln(err)
398         }
399
400         ln, err := net.Listen("tcp", *bind)
401         if err != nil {
402                 log.Fatalln(err)
403         }
404         srv := http.Server{
405                 Handler:      &Handler{},
406                 TLSNextProto: tlsNextProtoS,
407         }
408         log.Println("listening:", *bind)
409         if err := srv.Serve(ln); err != nil {
410                 log.Fatalln(err)
411         }
412 }