File
Blob: tun/client/lightweight.go
| 1 | package client |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/ed25519" |
| 6 | "crypto/rand" |
| 7 | "crypto/tls" |
| 8 | "crypto/x509" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "net" |
| 12 | "net/http" |
| 13 | "strings" |
| 14 | "time" |
| 15 | |
| 16 | pkiImpl "go.miragespace.co/specter/pki" |
| 17 | "go.miragespace.co/specter/spec/pki" |
| 18 | "go.miragespace.co/specter/spec/protocol" |
| 19 | "go.miragespace.co/specter/spec/transport" |
| 20 | "go.miragespace.co/specter/tun/client/dialer" |
| 21 | "go.miragespace.co/specter/util" |
| 22 | |
| 23 | "go.uber.org/zap" |
| 24 | ) |
| 25 | |
| 26 | type LightweightConfig struct { |
| 27 | Logger *zap.Logger |
| 28 | Transport transport.ClientTransport |
| 29 | PKIClient protocol.PKIService |
| 30 | Apex *dialer.ParsedApex |
| 31 | Target string |
| 32 | Token string |
| 33 | Output io.Writer |
| 34 | } |
| 35 | |
| 36 | type LightweightClient struct { |
| 37 | LightweightConfig |
| 38 | fwd *forwarder |
| 39 | target Tunnel |
| 40 | // The first Open response preserves the URL and home across disconnections. |
| 41 | initialSession *protocol.OpenSessionResponse |
| 42 | } |
| 43 | |
| 44 | // attachmentError marks a local failure that another connection cannot fix. |
| 45 | type attachmentError struct { |
| 46 | error |
| 47 | } |
| 48 | |
| 49 | func (e *attachmentError) Unwrap() error { return e.error } |
| 50 | |
| 51 | func NewLightweightClient(cfg LightweightConfig) (*LightweightClient, error) { |
| 52 | target, err := parseTarget(cfg.Target) |
| 53 | if err != nil { |
| 54 | return nil, err |
| 55 | } |
| 56 | if cfg.Apex == nil || cfg.Transport == nil || cfg.PKIClient == nil { |
| 57 | return nil, fmt.Errorf("apex, transport, and PKI client are required") |
| 58 | } |
| 59 | if cfg.Apex.Host == "" || cfg.Apex.Port < 1 || cfg.Apex.Port > 65535 { |
| 60 | return nil, fmt.Errorf("invalid apex address") |
| 61 | } |
| 62 | if cfg.Logger == nil { |
| 63 | cfg.Logger = zap.NewNop() |
| 64 | } |
| 65 | if cfg.Output == nil { |
| 66 | cfg.Output = io.Discard |
| 67 | } |
| 68 | return &LightweightClient{ |
| 69 | LightweightConfig: cfg, |
| 70 | fwd: newForwarder(cfg.Logger), |
| 71 | target: Tunnel{Target: cfg.Target, parsed: target}, |
| 72 | }, nil |
| 73 | } |
| 74 | |
| 75 | func (l *LightweightClient) Run(ctx context.Context) error { |
| 76 | parent := ctx |
| 77 | _, key, err := ed25519.GenerateKey(rand.Reader) |
| 78 | if err != nil { |
| 79 | return err |
| 80 | } |
| 81 | req, err := pkiImpl.CreateRequest(key) |
| 82 | if err != nil { |
| 83 | return err |
| 84 | } |
| 85 | issueCtx, cancel := context.WithTimeout(ctx, 15*time.Second) |
| 86 | certResp, err := l.PKIClient.RequestCertificate(issueCtx, req) |
| 87 | cancel() |
| 88 | if ctx.Err() != nil { |
| 89 | return nil |
| 90 | } |
| 91 | if err != nil { |
| 92 | return fmt.Errorf("obtaining attachment certificate: %w", err) |
| 93 | } |
| 94 | cert, err := x509.ParseCertificate(certResp.GetCertDer()) |
| 95 | if err != nil { |
| 96 | return err |
| 97 | } |
| 98 | identity, err := pki.ExtractCertificateIdentity(cert) |
| 99 | if err != nil { |
| 100 | return err |
| 101 | } |
| 102 | notAfter := cert.NotAfter |
| 103 | l.Logger.Info("Attachment certificate obtained", zap.Object("identity", identity), zap.Time("notAfter", notAfter)) |
| 104 | if err := l.Transport.WithClientCertificate(tls.Certificate{ |
| 105 | Certificate: [][]byte{cert.Raw}, |
| 106 | PrivateKey: key, |
| 107 | }); err != nil { |
| 108 | return err |
| 109 | } |
| 110 | ctx, cancel = context.WithDeadline(ctx, notAfter) |
| 111 | defer cancel() |
| 112 | // Traffic can arrive before Open replies with the assigned hostname. |
| 113 | r := l.fwd.newRoute("", l.target) |
| 114 | defer r.proxy.close() |
| 115 | router := transport.NewStreamRouter(l.Logger, nil, l.Transport) |
| 116 | router.HandleTunnel(protocol.Stream_DIRECT, func(d *transport.StreamDelegate) { |
| 117 | link, ok := receiveLink(l.Logger, d) |
| 118 | if ok { |
| 119 | l.fwd.handleLink(ctx, link, d, r) |
| 120 | } |
| 121 | }) |
| 122 | go router.Accept(ctx) |
| 123 | if l.Token == "" { |
| 124 | err = l.runEphemeral(ctx) |
| 125 | } else { |
| 126 | err = l.runToken(ctx) |
| 127 | } |
| 128 | if parent.Err() != nil { |
| 129 | return nil |
| 130 | } |
| 131 | if ctx.Err() != nil { |
| 132 | return fmt.Errorf("attachment certificate expired at %s", notAfter.Format(time.RFC3339)) |
| 133 | } |
| 134 | return err |
| 135 | } |
| 136 | |
| 137 | func (l *LightweightClient) runEphemeral(ctx context.Context) error { |
| 138 | backoff := time.Second |
| 139 | for ctx.Err() == nil { |
| 140 | node := l.initialSession.GetNode() |
| 141 | if node == nil { |
| 142 | node = &protocol.Node{Address: l.Apex.String()} |
| 143 | } |
| 144 | activated, err := l.attach(ctx, node) |
| 145 | if ctx.Err() != nil { |
| 146 | break |
| 147 | } |
| 148 | if definite(err) { |
| 149 | return err |
| 150 | } |
| 151 | if unsupported(err) { |
| 152 | return fmt.Errorf("server %s does not support lightweight tunnels", node.GetAddress()) |
| 153 | } |
| 154 | if activated { |
| 155 | backoff = time.Second |
| 156 | } |
| 157 | l.Logger.Warn("Retrying tunnel attachment", zap.Error(err), zap.Duration("backoff", backoff)) |
| 158 | timer := time.NewTimer(util.RandomTimeRange(backoff)) |
| 159 | select { |
| 160 | case <-ctx.Done(): |
| 161 | timer.Stop() |
| 162 | case <-timer.C: |
| 163 | } |
| 164 | backoff = min(backoff*2, 30*time.Second) |
| 165 | } |
| 166 | return ctx.Err() |
| 167 | } |
| 168 | |
| 169 | func (l *LightweightClient) dialAttachment(ctx context.Context, node *protocol.Node) (net.Conn, transport.PhysicalConn, error) { |
| 170 | // Overlay retains this context for the physical connection. Only RPC requests |
| 171 | // get attempt deadlines; ending a successful unary request must not end traffic. |
| 172 | conn, err := l.Transport.DialStream(ctx, node, protocol.Stream_RPC) |
| 173 | if err != nil { |
| 174 | return nil, nil, err |
| 175 | } |
| 176 | provider, ok := conn.(transport.PhysicalConnProvider) |
| 177 | if !ok || provider.PhysicalConn() == nil { |
| 178 | conn.Close() |
| 179 | return nil, nil, &attachmentError{fmt.Errorf("transport does not expose a physical connection")} |
| 180 | } |
| 181 | return conn, provider.PhysicalConn(), nil |
| 182 | } |
| 183 | |
| 184 | // Each client makes one request on the supplied stream; its caller owns the |
| 185 | // physical connection. Closing the RPC stream must not end other tunnel streams. |
| 186 | func tunnelClientOnStream(conn net.Conn) protocol.TunnelService { |
| 187 | tp := http.DefaultTransport.(*http.Transport).Clone() |
| 188 | tp.DisableKeepAlives = true |
| 189 | tp.DialTLSContext = func(context.Context, string, string) (net.Conn, error) { |
| 190 | return conn, nil |
| 191 | } |
| 192 | return protocol.NewTunnelServiceProtobufClient("https://tunnel", &http.Client{Transport: tp}) |
| 193 | } |
| 194 | |
| 195 | func (l *LightweightClient) attach(ctx context.Context, node *protocol.Node) (bool, error) { |
| 196 | conn, pc, err := l.dialAttachment(ctx, node) |
| 197 | if err != nil { |
| 198 | return false, err |
| 199 | } |
| 200 | defer pc.Close("attachment ended") |
| 201 | defer conn.Close() |
| 202 | openCtx, cancel := context.WithTimeout(ctx, 15*time.Second) |
| 203 | resp, err := tunnelClientOnStream(conn).OpenEphemeralSession(openCtx, &protocol.OpenEphemeralSessionRequest{}) |
| 204 | cancel() |
| 205 | if err != nil { |
| 206 | return false, err |
| 207 | } |
| 208 | first := l.initialSession == nil |
| 209 | if err := l.acceptSession(resp); err != nil { |
| 210 | return false, &attachmentError{err} |
| 211 | } |
| 212 | if !first { |
| 213 | l.Logger.Info("Tunnel recovered", zap.String("url", l.URL()), zap.String("server", resp.GetNode().GetAddress())) |
| 214 | } |
| 215 | select { |
| 216 | case <-ctx.Done(): |
| 217 | case <-pc.Done(): |
| 218 | } |
| 219 | l.Logger.Info("Tunnel disconnected", zap.Error(pc.Err())) |
| 220 | return true, pc.Err() |
| 221 | } |
| 222 | |
| 223 | func (l *LightweightClient) acceptSession(resp *protocol.OpenSessionResponse) error { |
| 224 | if resp.GetHostname() == "" || resp.GetNode().GetAddress() == "" || resp.GetApex() == "" { |
| 225 | return fmt.Errorf("server returned an empty hostname, identity, or apex") |
| 226 | } |
| 227 | if l.initialSession != nil { |
| 228 | if l.initialSession.GetHostname() != resp.GetHostname() { |
| 229 | return fmt.Errorf("recovered tunnel hostname changed") |
| 230 | } |
| 231 | return nil |
| 232 | } |
| 233 | l.initialSession = resp |
| 234 | l.fwd.rootDomain.Store(resp.GetApex()) |
| 235 | if _, err := fmt.Fprintln(l.Output, l.URL()); err != nil { |
| 236 | return &attachmentError{fmt.Errorf("printing tunnel URL: %w", err)} |
| 237 | } |
| 238 | l.Logger.Info("Tunnel ready", zap.String("url", l.URL()), zap.String("hostname", resp.GetHostname()), zap.String("server", resp.GetNode().GetAddress())) |
| 239 | return nil |
| 240 | } |
| 241 | |
| 242 | func (l *LightweightClient) URL() string { |
| 243 | hostname := l.initialSession.GetHostname() |
| 244 | if strings.Contains(hostname, ".") { |
| 245 | return "https://" + hostname |
| 246 | } |
| 247 | authority := hostname + "." + l.initialSession.GetApex() |
| 248 | if l.Apex.Port != 443 { |
| 249 | authority = net.JoinHostPort(authority, fmt.Sprint(l.Apex.Port)) |
| 250 | } |
| 251 | return "https://" + authority |
| 252 | } |