telebit/telebit.go

384 lines
9.5 KiB
Go
Raw Normal View History

2020-05-22 10:41:24 +00:00
package telebit
2020-05-21 05:30:24 +00:00
2020-05-21 10:29:05 +00:00
import (
2020-06-01 07:38:18 +00:00
"bytes"
2020-05-22 10:07:35 +00:00
"crypto/tls"
"encoding/json"
2020-05-21 10:29:05 +00:00
"errors"
"fmt"
"io"
2020-06-01 07:38:18 +00:00
"io/ioutil"
2020-05-21 10:29:05 +00:00
"net"
2020-06-01 07:38:18 +00:00
"net/http"
2020-05-22 10:07:35 +00:00
"os"
"strings"
2020-05-21 10:29:05 +00:00
"time"
2020-05-22 10:07:35 +00:00
"github.com/caddyserver/certmagic"
"github.com/go-acme/lego/v3/challenge"
2020-07-06 09:56:29 +00:00
"github.com/go-acme/lego/v3/challenge/dns01"
2020-05-21 10:29:05 +00:00
)
2020-05-21 05:30:24 +00:00
// Note: 64k is the TCP max, but 1460b is the 100mbit Ethernet max (1500 MTU - overhead),
// but 1Gbit Ethernet (Jumbo frame) has an 9000b MTU
// Nerds posting benchmarks on SO show that 8k seems about right,
// but even 1024b could work well.
var defaultBufferSize = 8192
2020-06-06 09:43:56 +00:00
var defaultPeekerSize = 1024
2020-05-21 05:30:24 +00:00
// ErrBadGateway means that the target did not accept the connection
var ErrBadGateway = errors.New("EBADGATEWAY")
2020-05-21 10:29:05 +00:00
// The proper handling of this error
// is still being debated as of Jun 9, 2020
// https://github.com/golang/go/issues/4373
var errNetClosing = "use of closed network connection"
2020-05-21 10:29:05 +00:00
// A Handler routes, proxies, terminates, or responds to a net.Conn.
type Handler interface {
2020-06-22 06:34:42 +00:00
// TODO ServeTCP
2020-05-22 10:07:35 +00:00
Serve(net.Conn) error
2020-05-21 10:29:05 +00:00
}
2020-05-22 10:07:35 +00:00
// HandlerFunc should handle, proxy, or terminate the connection
type HandlerFunc func(net.Conn) error
2020-05-21 10:29:05 +00:00
2020-06-22 06:34:42 +00:00
// Authorizer is called when a new client connects and we need to know something about it
type Authorizer func(*http.Request) (*Grants, error)
2020-05-21 10:29:05 +00:00
// Serve calls f(conn).
2020-05-22 10:07:35 +00:00
func (f HandlerFunc) Serve(conn net.Conn) error {
2020-05-21 10:29:05 +00:00
return f(conn)
}
// NewForwarder creates a handler that port-forwards to a target
func NewForwarder(target string, timeout time.Duration) HandlerFunc {
2020-05-22 10:07:35 +00:00
return func(client net.Conn) error {
2020-05-21 10:29:05 +00:00
tconn, err := net.Dial("tcp", target)
if nil != err {
return err
}
return Forward(client, tconn, timeout)
}
}
// Forward port-forwards a relay (websocket) client to a target (local) server
2020-05-22 10:07:35 +00:00
func Forward(client net.Conn, target net.Conn, timeout time.Duration) error {
2020-05-21 10:29:05 +00:00
// Something like ReadAhead(size) should signal
// to read and send up to `size` bytes without waiting
// for a response - since we can't signal 'non-read' as
// is the normal operation of tcp... or can we?
// And how do we distinguish idle from dropped?
// Maybe this should have been a udp protocol???
defer client.Close()
defer target.Close()
srcCh := make(chan []byte)
dstCh := make(chan []byte)
srcErrCh := make(chan error)
dstErrCh := make(chan error)
// Source (Relay) Read Channel
go func() {
for {
b := make([]byte, defaultBufferSize)
n, err := client.Read(b)
if n > 0 {
srcCh <- b[:n]
}
if nil != err {
// TODO let client log this server-side error (unless EOF)
// (nil here because we probably can't send the error to the relay)
srcErrCh <- err
break
}
}
}()
// Target (Local) Read Channel
go func() {
for {
b := make([]byte, defaultBufferSize)
n, err := target.Read(b)
if n > 0 {
dstCh <- b[:n]
}
if nil != err {
if io.EOF == err {
err = nil
}
dstErrCh <- err
break
}
}
}()
fmt.Println(
"[debug] forwarding tcp connection",
client.LocalAddr(),
client.RemoteAddr(),
target.LocalAddr(),
target.RemoteAddr(),
)
2020-05-21 10:29:05 +00:00
var err error = nil
2020-06-03 06:17:30 +00:00
ForwardData:
2020-05-21 10:29:05 +00:00
for {
select {
// TODO do we need a context here?
//case <-ctx.Done():
// break
case b := <-srcCh:
client.SetDeadline(time.Now().Add(timeout))
_, err = target.Write(b)
if nil != err {
fmt.Printf("write to target failed: %q\n", err.Error())
2020-06-03 06:17:30 +00:00
break ForwardData
2020-05-21 10:29:05 +00:00
}
case b := <-dstCh:
target.SetDeadline(time.Now().Add(timeout))
_, err = client.Write(b)
if nil != err {
fmt.Printf("write to remote failed: %q\n", err.Error())
2020-06-03 06:17:30 +00:00
break ForwardData
2020-05-21 10:29:05 +00:00
}
case err = <-srcErrCh:
if nil == err {
2020-06-03 06:17:30 +00:00
break ForwardData
}
if io.EOF != err && io.ErrClosedPipe != err && !strings.Contains(err.Error(), errNetClosing) {
2020-07-15 09:33:23 +00:00
fmt.Printf("error: data source (websocket client) read failed: %q\n", err.Error())
} else {
fmt.Printf("Connection closed (possibly by remote client)\n")
2020-05-21 10:29:05 +00:00
}
2020-06-03 06:17:30 +00:00
break ForwardData
2020-05-21 10:29:05 +00:00
case err = <-dstErrCh:
if nil == err {
2020-06-03 06:17:30 +00:00
break ForwardData
}
if io.EOF != err && io.ErrClosedPipe != err && !strings.Contains(err.Error(), errNetClosing) {
2020-07-15 09:33:23 +00:00
fmt.Printf("error: data sink (local target) read failed: %q\n", err.Error())
} else {
fmt.Printf("Connection closed (possibly by local target)\n")
2020-05-21 10:29:05 +00:00
}
2020-06-03 06:17:30 +00:00
break ForwardData
2020-05-21 10:29:05 +00:00
}
}
client.Close()
return err
}
2020-05-22 10:07:35 +00:00
type ACME struct {
Agree bool
Email string
Directory string
DNSProvider challenge.Provider
2020-07-06 09:56:29 +00:00
DNSChallengeOption dns01.ChallengeOption
2020-05-22 10:07:35 +00:00
Storage certmagic.Storage
StoragePath string
EnableHTTPChallenge bool
EnableTLSALPNChallenge bool
}
var acmecert *certmagic.Config = nil
2020-06-09 10:41:38 +00:00
/*
func NewTerminator(servername string, acme *ACME, handler Handler) HandlerFunc {
2020-05-22 10:07:35 +00:00
return func(client net.Conn) error {
2020-06-09 10:41:38 +00:00
return handler.Serve(TerminateTLS("", client, acme))
2020-05-22 10:07:35 +00:00
}
}
2020-06-09 10:41:38 +00:00
*/
//func TerminateTLS(client *ConnWrap, acme *ACME) net.Conn
2020-05-22 10:07:35 +00:00
func TerminateTLS(client net.Conn, acme *ACME) net.Conn {
var magic *certmagic.Config = nil
2020-05-22 10:07:35 +00:00
if nil == acmecert {
acme.Storage = &certmagic.FileStorage{Path: acme.StoragePath}
if "" == acme.Directory {
acme.Directory = certmagic.LetsEncryptProductionCA
}
var err error
2020-07-06 09:56:29 +00:00
magic, err = NewCertMagic(acme)
if nil != err {
fmt.Fprintf(
os.Stderr,
"failed to initialize certificate management (discovery url? local folder perms?): %s\n",
err,
)
os.Exit(1)
}
acmecert = magic
2020-05-22 10:07:35 +00:00
}
tlsConfig := &tls.Config{
GetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
return acmecert.GetCertificate(hello)
2020-05-22 10:07:35 +00:00
/*
if false {
_, _ = magic.GetCertificate(hello)
}
// TODO
// 1. call out to greenlock for validation
// 2. push challenges through http channel
// 3. receive certificates (or don't)
certbundleT, err := tls.LoadX509KeyPair("certs/fullchain.pem", "certs/privkey.pem")
certbundle := &certbundleT
if err != nil {
return nil, err
}
return certbundle, nil
*/
},
}
2020-06-09 10:41:38 +00:00
var servername string
var scheme string
// I think this must always be ConnWrap, but I'm not sure
switch conn := client.(type) {
case *ConnWrap:
servername = conn.Servername()
scheme = conn.Scheme()
client = conn
default:
wconn := &ConnWrap{
Conn: client,
}
2020-07-08 10:28:32 +00:00
_ = wconn.isEncrypted()
2020-06-09 10:41:38 +00:00
servername = wconn.Servername()
scheme = wconn.Scheme()
client = wconn
}
/*
// TODO ?
if "" == scheme {
scheme = "tls"
}
if "http" == scheme {
scheme = "https"
}
*/
2020-05-22 10:07:35 +00:00
tlsconn := tls.Server(client, tlsConfig)
return &ConnWrap{
2020-06-09 10:41:38 +00:00
Conn: tlsconn,
Plain: client,
servername: servername,
scheme: scheme,
2020-05-22 10:07:35 +00:00
}
}
2020-07-06 09:56:29 +00:00
func NewCertMagic(acme *ACME) (*certmagic.Config, error) {
2020-05-22 10:07:35 +00:00
if !acme.Agree {
fmt.Fprintf(
os.Stderr,
"\n\nError: must --acme-agree to terms to use Let's Encrypt / ACME issued certificates\n\n",
)
os.Exit(1)
}
cache := certmagic.NewCache(certmagic.CacheOptions{
GetConfigForCert: func(cert certmagic.Certificate) (*certmagic.Config, error) {
// do whatever you need to do to get the right
// configuration for this certificate; keep in
// mind that this config value is used as a
// template, and will be completed with any
// defaults that are set in the Default config
return &certmagic.Config{}, nil
},
})
magic := certmagic.New(cache, certmagic.Config{
Storage: acme.Storage,
OnDemand: &certmagic.OnDemandConfig{
DecisionFunc: func(name string) error {
return nil
},
},
})
// yes, a circular reference, passing `magic` to its own Issuer
2020-07-06 09:56:29 +00:00
fmt.Printf("[debug] ACME Email: %q\n", acme.Email)
2020-05-22 10:07:35 +00:00
magic.Issuer = certmagic.NewACMEManager(magic, certmagic.ACMEManager{
DNSProvider: acme.DNSProvider,
2020-07-06 09:56:29 +00:00
DNSChallengeOption: acme.DNSChallengeOption,
2020-05-22 10:07:35 +00:00
CA: acme.Directory,
Email: acme.Email,
Agreed: acme.Agree,
DisableHTTPChallenge: !acme.EnableHTTPChallenge,
DisableTLSALPNChallenge: !acme.EnableTLSALPNChallenge,
// plus any other customizations you need
})
return magic, nil
}
2020-06-01 07:38:18 +00:00
type Grants struct {
2020-06-22 06:34:42 +00:00
Subject string `json:"sub"`
Domains []string `json:"domains"`
2020-06-22 06:34:42 +00:00
Ports []int `json:"ports"`
}
func Inspect(authURL, token string) (*Grants, error) {
2020-07-15 09:33:23 +00:00
inspectURL := authURL + "/inspect"
//fmt.Fprintf(os.Stderr, "[debug] telebit.Inspect(\n\tinspectURL = %s,\n\ttoken = %s,\n)", inspectURL, token)
msg, err := Request("GET", inspectURL, token, nil)
if nil != err {
return nil, err
}
if nil == msg {
return nil, fmt.Errorf("invalid response")
}
grants := &Grants{}
err = json.NewDecoder(msg).Decode(grants)
if err != nil {
return nil, err
}
if "" == grants.Subject {
fmt.Fprintf(os.Stderr, "TODO update mgmt server to show Subject: %q", msg)
grants.Subject = strings.Split(grants.Domains[0], ".")[0]
}
return grants, nil
}
2020-06-01 07:38:18 +00:00
func Request(method, fullurl, token string, payload io.Reader) (io.Reader, error) {
HTTPClient := &http.Client{
Timeout: 15 * time.Second,
}
req, err := http.NewRequest(method, fullurl, payload)
if err != nil {
return nil, err
}
if len(token) > 0 {
req.Header.Set("Authorization", "Bearer "+token)
}
if nil != payload {
req.Header.Set("Content-Type", "application/json")
}
resp, err := HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("%d: failed to read response body: %w", resp.StatusCode, err)
}
if resp.StatusCode >= http.StatusBadRequest {
return nil, fmt.Errorf("%d: request failed: %v", resp.StatusCode, string(body))
}
return bytes.NewBuffer(body), nil
}