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 tlsNextProtoC = make(map[string]func(string, *tls.Conn) http.RoundTripper)
43 caCert *x509.Certificate
44 caPrv crypto.PrivateKey
47 transport = http.Transport{
48 ForceAttemptHTTP2: false,
49 DisableKeepAlives: true,
50 MaxIdleConnsPerHost: 2,
51 TLSNextProto: tlsNextProtoC,
52 DialTLSContext: dialTLS,
55 accepted = make(map[string]string)
56 acceptedM sync.RWMutex
57 rejected = make(map[string]string)
58 rejectedM sync.RWMutex
61 func spkiHash(cert *x509.Certificate) string {
62 hsh := sha256.Sum256(cert.RawSubjectPublicKeyInfo)
63 return hex.EncodeToString(hsh[:])
66 func acceptedAdd(addr, h string) {
72 func rejectedAdd(addr, h string) {
78 type ErrRejected struct {
82 func (err ErrRejected) Error() string { return err.addr + " was rejected" }
84 func dialTLS(ctx context.Context, network, addr string) (net.Conn, error) {
85 host := strings.TrimSuffix(addr, ":443")
87 VerifyPeerCertificate: func(
89 verifiedChains [][]*x509.Certificate,
91 return verifyCert(host, nil, rawCerts, verifiedChains)
94 conn, dialErr := tls.Dial(network, addr, &cfg)
96 if _, ok := dialErr.(ErrRejected); ok {
99 cfg.InsecureSkipVerify = true
100 cfg.VerifyPeerCertificate = func(
102 verifiedChains [][]*x509.Certificate,
104 return verifyCert(host, dialErr, rawCerts, verifiedChains)
107 conn, err = tls.Dial(network, addr, &cfg)
109 sinkErr <- fmt.Sprintf("%s\t%s", addr, dialErr.Error())
113 connState := conn.ConnectionState()
114 sinkTLS <- fmt.Sprintf(
116 strings.TrimSuffix(addr, ":443"),
117 ucspi.TLSVersion(connState.Version),
118 tls.CipherSuiteName(connState.CipherSuite),
119 spkiHash(connState.PeerCertificates[0]),
124 func roundTrip(w http.ResponseWriter, req *http.Request) {
125 if req.Method == http.MethodHead {
126 http.Error(w, "go away", http.StatusMethodNotAllowed)
129 sinkReq <- fmt.Sprintf("%s %s", req.Method, req.URL.String())
130 host := strings.TrimSuffix(req.URL.Host, ":443")
131 for _, spy := range SpyDomains {
132 if strings.HasSuffix(host, spy) {
133 http.NotFound(w, req)
134 sinkOther <- fmt.Sprintf(
135 "%s %s\t%d\tspy one",
143 if strings.HasPrefix(req.URL.Host, "www.reddit.com") {
144 req.URL.Host = "old.reddit.com"
145 http.Redirect(w, req, req.URL.String(), http.StatusMovedPermanently)
148 resp, err := transport.RoundTrip(req)
150 sinkErr <- fmt.Sprintf("%s\t%s", req.URL.Host, err.Error())
151 w.WriteHeader(http.StatusBadGateway)
152 w.Write([]byte(err.Error()))
155 contentType := resp.Header.Get("Content-Type")
157 case "application/font-woff", "application/font-sfnt":
158 // Those are deprecated types
160 case "font/otf", "font/ttf", "font/woff", "font/woff2":
161 http.NotFound(w, req)
162 sinkOther <- fmt.Sprintf(
163 "%s %s\t%d\tfonts are not allowed",
171 for k, vs := range resp.Header {
172 if k == "Location" || k == "Content-Type" || k == "Content-Length" {
175 for _, v := range vs {
179 if req.Method == http.MethodGet {
181 switch resp.StatusCode {
182 case http.StatusMovedPermanently, http.StatusPermanentRedirect:
183 redirType = "permanent"
185 case http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect:
186 if strings.Contains(req.Header.Get("User-Agent"), "newsboat/") {
189 redirType = "temporary"
195 w.Header().Add("Content-Type", "text/html")
196 w.WriteHeader(http.StatusOK)
197 location := resp.Header.Get("Location")
201 <head><title>%d %s: %s redirection</title></head>
202 <body>Redirection to <a href="%s">%s</a>
204 resp.StatusCode, http.StatusText(resp.StatusCode),
205 redirType, location, location,
207 sinkRedir <- fmt.Sprintf(
208 "%s %s\t%s\t%s", req.Method, resp.Status, req.URL.String(), location,
213 for _, h := range []string{"Location", "Content-Type", "Content-Length"} {
214 if v := resp.Header.Get(h); v != "" {
218 w.WriteHeader(resp.StatusCode)
219 n, err := io.Copy(w, resp.Body)
221 log.Printf("Error during %s: %+v\n", req.URL, err)
229 resp.Header.Get("Content-Type"),
230 humanize.IBytes(uint64(n)),
232 if resp.StatusCode == http.StatusOK {
239 type Handler struct{}
241 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
242 if req.Method != http.MethodConnect {
246 hj, ok := w.(http.Hijacker)
248 log.Fatalln("no hijacking")
250 conn, _, err := hj.Hijack()
255 conn.Write([]byte(fmt.Sprintf(
258 http.StatusOK, http.StatusText(http.StatusOK),
260 host := strings.Split(req.Host, ":")[0]
262 keypair, ok := hostCerts[host]
263 if !ok || !keypair.cert.NotAfter.After(time.Now().Add(time.Hour)) {
264 keypair = newKeypair(host, caCert, caPrv)
265 hostCerts[host] = keypair
268 tlsConn := tls.Server(conn, &tls.Config{
269 Certificates: []tls.Certificate{{
270 Certificate: [][]byte{keypair.cert.Raw},
271 PrivateKey: keypair.prv,
274 if err = tlsConn.Handshake(); err != nil {
275 log.Printf("TLS error %s: %+v\n", host, err)
279 Handler: &HTTPSHandler{host: req.Host},
280 TLSNextProto: tlsNextProtoS,
282 err = srv.Serve(&SingleListener{conn: tlsConn})
284 if _, ok := err.(AlreadyAccepted); !ok {
285 log.Printf("TLS serve error %s: %+v\n", host, err)
291 type HTTPSHandler struct {
295 func (h *HTTPSHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
296 req.URL.Scheme = "https"
297 req.URL.Host = h.host
302 crtPath := flag.String("cert", "cert.pem", "Path to server X.509 certificate")
303 prvPath := flag.String("key", "prv.pem", "Path to server PKCS#8 private key")
304 bind := flag.String("bind", "[::1]:8080", "Bind address")
305 certs = flag.String("certs", "certs", "Directory with pinned certificates")
306 dnsSrv = flag.String("dns", "[::1]:53", "DNS server")
307 fifos = flag.String("fifos", "fifos", "Directory with FIFOs")
308 notai = flag.Bool("notai", false, "Do not prepend TAI64N to logs")
310 log.SetFlags(log.Lshortfile)
314 _, caCert, err = ucspi.CertificateFromFile(*crtPath)
318 caPrv, err = ucspi.PrivateKeyFromFile(*prvPath)
323 ln, err := net.Listen("tcp", *bind)
329 TLSNextProto: tlsNextProtoS,
331 srv.SetKeepAlivesEnabled(false)
332 log.Println("listening:", *bind)
333 if err := srv.Serve(ln); err != nil {