| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | package remotelink |
| 6 | |
| 7 | import ( |
| 8 | "context" |
| 9 | "crypto" |
| 10 | "crypto/ecdsa" |
| 11 | "crypto/ed25519" |
| 12 | "crypto/elliptic" |
| 13 | "crypto/rand" |
| 14 | "crypto/sha256" |
| 15 | "crypto/subtle" |
| 16 | "crypto/tls" |
| 17 | "crypto/x509" |
| 18 | "crypto/x509/pkix" |
| 19 | "encoding/base64" |
| 20 | "errors" |
| 21 | "fmt" |
| 22 | "math/big" |
| 23 | "strings" |
| 24 | "time" |
| 25 | |
| 26 | "github.com/gorilla/websocket" |
| 27 | ) |
| 28 | |
| 29 | const ( |
| 30 | |
| 31 | Protocol = "cage-remote/1" |
| 32 | |
| 33 | |
| 34 | MaxMessageSize = 64 << 10 |
| 35 | handshakeTimeout = 15 * time.Second |
| 36 | ) |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | type Identity struct { |
| 42 | Certificate tls.Certificate |
| 43 | Pin string |
| 44 | } |
| 45 | |
| 46 | |
| 47 | |
| 48 | func NewIdentity() (*Identity, error) { |
| 49 | _, private, err := ed25519.GenerateKey(rand.Reader) |
| 50 | if err != nil { |
| 51 | return nil, fmt.Errorf("generate identity key: %w", err) |
| 52 | } |
| 53 | return IdentityFromKey(private) |
| 54 | } |
| 55 | |
| 56 | |
| 57 | |
| 58 | func IdentityFromKey(key ed25519.PrivateKey) (*Identity, error) { |
| 59 | if len(key) != ed25519.PrivateKeySize { |
| 60 | return nil, errors.New("invalid Ed25519 identity key") |
| 61 | } |
| 62 | return IdentityFromSigner(key) |
| 63 | } |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | func IdentityFromSigner(signer crypto.Signer) (*Identity, error) { |
| 69 | if signer == nil { |
| 70 | return nil, errors.New("device identity signer is required") |
| 71 | } |
| 72 | public := signer.Public() |
| 73 | switch key := public.(type) { |
| 74 | case ed25519.PublicKey: |
| 75 | if len(key) != ed25519.PublicKeySize { |
| 76 | return nil, errors.New("invalid Ed25519 identity public key") |
| 77 | } |
| 78 | case *ecdsa.PublicKey: |
| 79 | if key == nil || key.Curve != elliptic.P256() { |
| 80 | return nil, errors.New("device ECDSA signer must use P-256") |
| 81 | } |
| 82 | default: |
| 83 | return nil, errors.New("device identity signer must use Ed25519 or P-256") |
| 84 | } |
| 85 | serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) |
| 86 | if err != nil { |
| 87 | return nil, fmt.Errorf("generate certificate serial: %w", err) |
| 88 | } |
| 89 | now := time.Now() |
| 90 | template := &x509.Certificate{ |
| 91 | SerialNumber: serial, |
| 92 | Subject: pkix.Name{CommonName: "Cage temporary remote identity"}, |
| 93 | NotBefore: now.Add(-time.Minute), NotAfter: now.Add(24 * time.Hour), |
| 94 | KeyUsage: x509.KeyUsageDigitalSignature, |
| 95 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, |
| 96 | } |
| 97 | der, err := x509.CreateCertificate(rand.Reader, template, template, public, signer) |
| 98 | if err != nil { |
| 99 | return nil, fmt.Errorf("create identity certificate: %w", err) |
| 100 | } |
| 101 | leaf, err := x509.ParseCertificate(der) |
| 102 | if err != nil { |
| 103 | return nil, fmt.Errorf("parse identity certificate: %w", err) |
| 104 | } |
| 105 | digest := sha256.Sum256(leaf.RawSubjectPublicKeyInfo) |
| 106 | return &Identity{ |
| 107 | Certificate: tls.Certificate{Certificate: [][]byte{der}, PrivateKey: signer, Leaf: leaf}, |
| 108 | Pin: "sha256:" + base64.StdEncoding.EncodeToString(digest[:]), |
| 109 | }, nil |
| 110 | } |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | func Client(ctx context.Context, ws *websocket.Conn, identity *Identity, expectedPin string) (*tls.Conn, error) { |
| 117 | return handshake(ctx, ws, identity, expectedPin, false, false) |
| 118 | } |
| 119 | |
| 120 | |
| 121 | |
| 122 | func Server(ctx context.Context, ws *websocket.Conn, identity *Identity, expectedPin string) (*tls.Conn, error) { |
| 123 | return handshake(ctx, ws, identity, expectedPin, true, false) |
| 124 | } |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | func ServerAfterJoin(ctx context.Context, ws *websocket.Conn, identity *Identity, expectedPin string) (*tls.Conn, error) { |
| 130 | return handshake(ctx, ws, identity, expectedPin, true, true) |
| 131 | } |
| 132 | |
| 133 | func peerVerifier(pin string) (func(tls.ConnectionState) error, error) { |
| 134 | encoded, ok := strings.CutPrefix(pin, "sha256:") |
| 135 | digest, err := base64.StdEncoding.DecodeString(encoded) |
| 136 | if !ok || err != nil || len(digest) != sha256.Size || base64.StdEncoding.EncodeToString(digest) != encoded { |
| 137 | return nil, errors.New("peer pin must be sha256: followed by padded Base64 of a SHA-256 SPKI digest") |
| 138 | } |
| 139 | return func(state tls.ConnectionState) error { |
| 140 | if state.Version != tls.VersionTLS13 || state.NegotiatedProtocol != Protocol { |
| 141 | return errors.New("peer did not negotiate the required TLS version and application protocol") |
| 142 | } |
| 143 | if len(state.PeerCertificates) == 0 { |
| 144 | return errors.New("peer did not provide an identity certificate") |
| 145 | } |
| 146 | certificate := state.PeerCertificates[0] |
| 147 | now := time.Now() |
| 148 | if now.Before(certificate.NotBefore) || !now.Before(certificate.NotAfter) { |
| 149 | return errors.New("peer identity certificate is outside its validity period") |
| 150 | } |
| 151 | actual := sha256.Sum256(certificate.RawSubjectPublicKeyInfo) |
| 152 | if subtle.ConstantTimeCompare(actual[:], digest) != 1 { |
| 153 | return errors.New("peer identity does not match the paired public key") |
| 154 | } |
| 155 | return nil |
| 156 | }, nil |
| 157 | } |
| 158 | |
| 159 | func handshake(ctx context.Context, ws *websocket.Conn, identity *Identity, expectedPin string, server, waitForJoin bool) (_ *tls.Conn, err error) { |
| 160 | if ws == nil { |
| 161 | return nil, errors.New("WebSocket connection is required") |
| 162 | } |
| 163 | defer func() { |
| 164 | if err != nil { |
| 165 | _ = ws.Close() |
| 166 | } |
| 167 | }() |
| 168 | verify, err := peerVerifier(expectedPin) |
| 169 | if err != nil { |
| 170 | return nil, err |
| 171 | } |
| 172 | if identity == nil || len(identity.Certificate.Certificate) == 0 || identity.Certificate.PrivateKey == nil { |
| 173 | return nil, errors.New("local identity certificate and private key are required") |
| 174 | } |
| 175 | config := &tls.Config{ |
| 176 | MinVersion: tls.VersionTLS13, MaxVersion: tls.VersionTLS13, |
| 177 | NextProtos: []string{Protocol}, |
| 178 | Certificates: []tls.Certificate{identity.Certificate}, |
| 179 | VerifyConnection: verify, |
| 180 | SessionTicketsDisabled: true, |
| 181 | } |
| 182 | stream := newWebSocketConn(ws) |
| 183 | if waitForJoin { |
| 184 | wait, cancel := context.WithTimeout(ctx, 2*time.Minute) |
| 185 | stop := context.AfterFunc(wait, func() { _ = stream.Close() }) |
| 186 | kind, first, readErr := ws.NextReader() |
| 187 | stop() |
| 188 | waitErr := wait.Err() |
| 189 | cancel() |
| 190 | if waitErr != nil { |
| 191 | return nil, fmt.Errorf("waiting for paired device: %w", waitErr) |
| 192 | } |
| 193 | if readErr != nil || kind != websocket.BinaryMessage { |
| 194 | return nil, errors.New("peer did not send a binary TLS handshake") |
| 195 | } |
| 196 | |
| 197 | |
| 198 | stream.reader = first |
| 199 | } |
| 200 | var connection *tls.Conn |
| 201 | if server { |
| 202 | config.ClientAuth = tls.RequireAnyClientCert |
| 203 | connection = tls.Server(stream, config) |
| 204 | } else { |
| 205 | |
| 206 | |
| 207 | config.InsecureSkipVerify = true |
| 208 | connection = tls.Client(stream, config) |
| 209 | } |
| 210 | ctx, cancel := context.WithTimeout(ctx, handshakeTimeout) |
| 211 | defer cancel() |
| 212 | deadline, _ := ctx.Deadline() |
| 213 | if err := stream.SetDeadline(deadline); err != nil { |
| 214 | return nil, fmt.Errorf("set handshake deadline: %w", err) |
| 215 | } |
| 216 | stop := context.AfterFunc(ctx, func() { _ = stream.Close() }) |
| 217 | err = connection.HandshakeContext(ctx) |
| 218 | stop() |
| 219 | if ctx.Err() != nil { |
| 220 | return nil, fmt.Errorf("remote TLS handshake: %w", ctx.Err()) |
| 221 | } |
| 222 | if err != nil { |
| 223 | return nil, fmt.Errorf("remote TLS handshake: %w", err) |
| 224 | } |
| 225 | if err := stream.SetDeadline(time.Time{}); err != nil { |
| 226 | return nil, fmt.Errorf("clear handshake deadline: %w", err) |
| 227 | } |
| 228 | return connection, nil |
| 229 | } |