github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/crypto/tls/common.go (about)

     1  // TINYGO: The following is copied and modified from Go 1.19.3 official implementation.
     2  
     3  // Copyright 2009 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  package tls
     8  
     9  import (
    10  	"context"
    11  	"crypto"
    12  	"crypto/x509"
    13  	"io"
    14  	"net"
    15  	"sync"
    16  	"time"
    17  )
    18  
    19  // CurveID is the type of a TLS identifier for an elliptic curve. See
    20  // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
    21  //
    22  // In TLS 1.3, this type is called NamedGroup, but at this time this library
    23  // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
    24  type CurveID uint16
    25  
    26  // ConnectionState records basic TLS details about the connection.
    27  type ConnectionState struct {
    28  	// TINYGO: empty; TLS connection offloaded to device
    29  }
    30  
    31  // ClientAuthType declares the policy the server will follow for
    32  // TLS Client Authentication.
    33  type ClientAuthType int
    34  
    35  // ClientSessionCache is a cache of ClientSessionState objects that can be used
    36  // by a client to resume a TLS session with a given server. ClientSessionCache
    37  // implementations should expect to be called concurrently from different
    38  // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
    39  // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
    40  // are supported via this interface.
    41  type ClientSessionCache interface {
    42  	// Get searches for a ClientSessionState associated with the given key.
    43  	// On return, ok is true if one was found.
    44  	Get(sessionKey string) (session *ClientSessionState, ok bool)
    45  
    46  	// Put adds the ClientSessionState to the cache with the given key. It might
    47  	// get called multiple times in a connection if a TLS 1.3 server provides
    48  	// more than one session ticket. If called with a nil *ClientSessionState,
    49  	// it should remove the cache entry.
    50  	Put(sessionKey string, cs *ClientSessionState)
    51  }
    52  
    53  //go:generate stringer -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go
    54  
    55  // SignatureScheme identifies a signature algorithm supported by TLS. See
    56  // RFC 8446, Section 4.2.3.
    57  type SignatureScheme uint16
    58  
    59  // ClientHelloInfo contains information from a ClientHello message in order to
    60  // guide application logic in the GetCertificate and GetConfigForClient callbacks.
    61  type ClientHelloInfo struct {
    62  	// CipherSuites lists the CipherSuites supported by the client (e.g.
    63  	// TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
    64  	CipherSuites []uint16
    65  
    66  	// ServerName indicates the name of the server requested by the client
    67  	// in order to support virtual hosting. ServerName is only set if the
    68  	// client is using SNI (see RFC 4366, Section 3.1).
    69  	ServerName string
    70  
    71  	// SupportedCurves lists the elliptic curves supported by the client.
    72  	// SupportedCurves is set only if the Supported Elliptic Curves
    73  	// Extension is being used (see RFC 4492, Section 5.1.1).
    74  	SupportedCurves []CurveID
    75  
    76  	// SupportedPoints lists the point formats supported by the client.
    77  	// SupportedPoints is set only if the Supported Point Formats Extension
    78  	// is being used (see RFC 4492, Section 5.1.2).
    79  	SupportedPoints []uint8
    80  
    81  	// SignatureSchemes lists the signature and hash schemes that the client
    82  	// is willing to verify. SignatureSchemes is set only if the Signature
    83  	// Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
    84  	SignatureSchemes []SignatureScheme
    85  
    86  	// SupportedProtos lists the application protocols supported by the client.
    87  	// SupportedProtos is set only if the Application-Layer Protocol
    88  	// Negotiation Extension is being used (see RFC 7301, Section 3.1).
    89  	//
    90  	// Servers can select a protocol by setting Config.NextProtos in a
    91  	// GetConfigForClient return value.
    92  	SupportedProtos []string
    93  
    94  	// SupportedVersions lists the TLS versions supported by the client.
    95  	// For TLS versions less than 1.3, this is extrapolated from the max
    96  	// version advertised by the client, so values other than the greatest
    97  	// might be rejected if used.
    98  	SupportedVersions []uint16
    99  
   100  	// Conn is the underlying net.Conn for the connection. Do not read
   101  	// from, or write to, this connection; that will cause the TLS
   102  	// connection to fail.
   103  	Conn net.Conn
   104  
   105  	// config is embedded by the GetCertificate or GetConfigForClient caller,
   106  	// for use with SupportsCertificate.
   107  	config *Config
   108  
   109  	// ctx is the context of the handshake that is in progress.
   110  	ctx context.Context
   111  }
   112  
   113  // CertificateRequestInfo contains information from a server's
   114  // CertificateRequest message, which is used to demand a certificate and proof
   115  // of control from a client.
   116  type CertificateRequestInfo struct {
   117  	// AcceptableCAs contains zero or more, DER-encoded, X.501
   118  	// Distinguished Names. These are the names of root or intermediate CAs
   119  	// that the server wishes the returned certificate to be signed by. An
   120  	// empty slice indicates that the server has no preference.
   121  	AcceptableCAs [][]byte
   122  
   123  	// SignatureSchemes lists the signature schemes that the server is
   124  	// willing to verify.
   125  	SignatureSchemes []SignatureScheme
   126  
   127  	// Version is the TLS version that was negotiated for this connection.
   128  	Version uint16
   129  
   130  	// ctx is the context of the handshake that is in progress.
   131  	ctx context.Context
   132  }
   133  
   134  // RenegotiationSupport enumerates the different levels of support for TLS
   135  // renegotiation. TLS renegotiation is the act of performing subsequent
   136  // handshakes on a connection after the first. This significantly complicates
   137  // the state machine and has been the source of numerous, subtle security
   138  // issues. Initiating a renegotiation is not supported, but support for
   139  // accepting renegotiation requests may be enabled.
   140  //
   141  // Even when enabled, the server may not change its identity between handshakes
   142  // (i.e. the leaf certificate must be the same). Additionally, concurrent
   143  // handshake and application data flow is not permitted so renegotiation can
   144  // only be used with protocols that synchronise with the renegotiation, such as
   145  // HTTPS.
   146  //
   147  // Renegotiation is not defined in TLS 1.3.
   148  type RenegotiationSupport int
   149  
   150  // A Config structure is used to configure a TLS client or server.
   151  // After one has been passed to a TLS function it must not be
   152  // modified. A Config may be reused; the tls package will also not
   153  // modify it.
   154  type Config struct {
   155  	// Rand provides the source of entropy for nonces and RSA blinding.
   156  	// If Rand is nil, TLS uses the cryptographic random reader in package
   157  	// crypto/rand.
   158  	// The Reader must be safe for use by multiple goroutines.
   159  	Rand io.Reader
   160  
   161  	// Time returns the current time as the number of seconds since the epoch.
   162  	// If Time is nil, TLS uses time.Now.
   163  	Time func() time.Time
   164  
   165  	// Certificates contains one or more certificate chains to present to the
   166  	// other side of the connection. The first certificate compatible with the
   167  	// peer's requirements is selected automatically.
   168  	//
   169  	// Server configurations must set one of Certificates, GetCertificate or
   170  	// GetConfigForClient. Clients doing client-authentication may set either
   171  	// Certificates or GetClientCertificate.
   172  	//
   173  	// Note: if there are multiple Certificates, and they don't have the
   174  	// optional field Leaf set, certificate selection will incur a significant
   175  	// per-handshake performance cost.
   176  	Certificates []Certificate
   177  
   178  	// NameToCertificate maps from a certificate name to an element of
   179  	// Certificates. Note that a certificate name can be of the form
   180  	// '*.example.com' and so doesn't have to be a domain name as such.
   181  	//
   182  	// Deprecated: NameToCertificate only allows associating a single
   183  	// certificate with a given name. Leave this field nil to let the library
   184  	// select the first compatible chain from Certificates.
   185  	NameToCertificate map[string]*Certificate
   186  
   187  	// GetCertificate returns a Certificate based on the given
   188  	// ClientHelloInfo. It will only be called if the client supplies SNI
   189  	// information or if Certificates is empty.
   190  	//
   191  	// If GetCertificate is nil or returns nil, then the certificate is
   192  	// retrieved from NameToCertificate. If NameToCertificate is nil, the
   193  	// best element of Certificates will be used.
   194  	//
   195  	// Once a Certificate is returned it should not be modified.
   196  	GetCertificate func(*ClientHelloInfo) (*Certificate, error)
   197  
   198  	// GetClientCertificate, if not nil, is called when a server requests a
   199  	// certificate from a client. If set, the contents of Certificates will
   200  	// be ignored.
   201  	//
   202  	// If GetClientCertificate returns an error, the handshake will be
   203  	// aborted and that error will be returned. Otherwise
   204  	// GetClientCertificate must return a non-nil Certificate. If
   205  	// Certificate.Certificate is empty then no certificate will be sent to
   206  	// the server. If this is unacceptable to the server then it may abort
   207  	// the handshake.
   208  	//
   209  	// GetClientCertificate may be called multiple times for the same
   210  	// connection if renegotiation occurs or if TLS 1.3 is in use.
   211  	//
   212  	// Once a Certificate is returned it should not be modified.
   213  	GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
   214  
   215  	// GetConfigForClient, if not nil, is called after a ClientHello is
   216  	// received from a client. It may return a non-nil Config in order to
   217  	// change the Config that will be used to handle this connection. If
   218  	// the returned Config is nil, the original Config will be used. The
   219  	// Config returned by this callback may not be subsequently modified.
   220  	//
   221  	// If GetConfigForClient is nil, the Config passed to Server() will be
   222  	// used for all connections.
   223  	//
   224  	// If SessionTicketKey was explicitly set on the returned Config, or if
   225  	// SetSessionTicketKeys was called on the returned Config, those keys will
   226  	// be used. Otherwise, the original Config keys will be used (and possibly
   227  	// rotated if they are automatically managed).
   228  	GetConfigForClient func(*ClientHelloInfo) (*Config, error)
   229  
   230  	// VerifyPeerCertificate, if not nil, is called after normal
   231  	// certificate verification by either a TLS client or server. It
   232  	// receives the raw ASN.1 certificates provided by the peer and also
   233  	// any verified chains that normal processing found. If it returns a
   234  	// non-nil error, the handshake is aborted and that error results.
   235  	//
   236  	// If normal verification fails then the handshake will abort before
   237  	// considering this callback. If normal verification is disabled (on the
   238  	// client when InsecureSkipVerify is set, or on a server when ClientAuth is
   239  	// RequestClientCert or RequireAnyClientCert), then this callback will be
   240  	// considered but the verifiedChains argument will always be nil. When
   241  	// ClientAuth is NoClientCert, this callback is not called on the server.
   242  	// rawCerts may be empty on the server if ClientAuth is RequestClientCert or
   243  	// VerifyClientCertIfGiven.
   244  	//
   245  	// This callback is not invoked on resumed connections, as certificates are
   246  	// not re-verified on resumption.
   247  	//
   248  	// verifiedChains and its contents should not be modified.
   249  	VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
   250  
   251  	// VerifyConnection, if not nil, is called after normal certificate
   252  	// verification and after VerifyPeerCertificate by either a TLS client
   253  	// or server. If it returns a non-nil error, the handshake is aborted
   254  	// and that error results.
   255  	//
   256  	// If normal verification fails then the handshake will abort before
   257  	// considering this callback. This callback will run for all connections,
   258  	// including resumptions, regardless of InsecureSkipVerify or ClientAuth
   259  	// settings.
   260  	VerifyConnection func(ConnectionState) error
   261  
   262  	// RootCAs defines the set of root certificate authorities
   263  	// that clients use when verifying server certificates.
   264  	// If RootCAs is nil, TLS uses the host's root CA set.
   265  	RootCAs *x509.CertPool
   266  
   267  	// NextProtos is a list of supported application level protocols, in
   268  	// order of preference. If both peers support ALPN, the selected
   269  	// protocol will be one from this list, and the connection will fail
   270  	// if there is no mutually supported protocol. If NextProtos is empty
   271  	// or the peer doesn't support ALPN, the connection will succeed and
   272  	// ConnectionState.NegotiatedProtocol will be empty.
   273  	NextProtos []string
   274  
   275  	// ServerName is used to verify the hostname on the returned
   276  	// certificates unless InsecureSkipVerify is given. It is also included
   277  	// in the client's handshake to support virtual hosting unless it is
   278  	// an IP address.
   279  	ServerName string
   280  
   281  	// ClientAuth determines the server's policy for
   282  	// TLS Client Authentication. The default is NoClientCert.
   283  	ClientAuth ClientAuthType
   284  
   285  	// ClientCAs defines the set of root certificate authorities
   286  	// that servers use if required to verify a client certificate
   287  	// by the policy in ClientAuth.
   288  	ClientCAs *x509.CertPool
   289  
   290  	// InsecureSkipVerify controls whether a client verifies the server's
   291  	// certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
   292  	// accepts any certificate presented by the server and any host name in that
   293  	// certificate. In this mode, TLS is susceptible to machine-in-the-middle
   294  	// attacks unless custom verification is used. This should be used only for
   295  	// testing or in combination with VerifyConnection or VerifyPeerCertificate.
   296  	InsecureSkipVerify bool
   297  
   298  	// CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
   299  	// the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
   300  	//
   301  	// If CipherSuites is nil, a safe default list is used. The default cipher
   302  	// suites might change over time.
   303  	CipherSuites []uint16
   304  
   305  	// PreferServerCipherSuites is a legacy field and has no effect.
   306  	//
   307  	// It used to control whether the server would follow the client's or the
   308  	// server's preference. Servers now select the best mutually supported
   309  	// cipher suite based on logic that takes into account inferred client
   310  	// hardware, server hardware, and security.
   311  	//
   312  	// Deprecated: PreferServerCipherSuites is ignored.
   313  	PreferServerCipherSuites bool
   314  
   315  	// SessionTicketsDisabled may be set to true to disable session ticket and
   316  	// PSK (resumption) support. Note that on clients, session ticket support is
   317  	// also disabled if ClientSessionCache is nil.
   318  	SessionTicketsDisabled bool
   319  
   320  	// SessionTicketKey is used by TLS servers to provide session resumption.
   321  	// See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
   322  	// with random data before the first server handshake.
   323  	//
   324  	// Deprecated: if this field is left at zero, session ticket keys will be
   325  	// automatically rotated every day and dropped after seven days. For
   326  	// customizing the rotation schedule or synchronizing servers that are
   327  	// terminating connections for the same host, use SetSessionTicketKeys.
   328  	SessionTicketKey [32]byte
   329  
   330  	// ClientSessionCache is a cache of ClientSessionState entries for TLS
   331  	// session resumption. It is only used by clients.
   332  	ClientSessionCache ClientSessionCache
   333  
   334  	// UnwrapSession is called on the server to turn a ticket/identity
   335  	// previously produced by [WrapSession] into a usable session.
   336  	//
   337  	// UnwrapSession will usually either decrypt a session state in the ticket
   338  	// (for example with [Config.EncryptTicket]), or use the ticket as a handle
   339  	// to recover a previously stored state. It must use [ParseSessionState] to
   340  	// deserialize the session state.
   341  	//
   342  	// If UnwrapSession returns an error, the connection is terminated. If it
   343  	// returns (nil, nil), the session is ignored. crypto/tls may still choose
   344  	// not to resume the returned session.
   345  	UnwrapSession func(identity []byte, cs ConnectionState) (*SessionState, error)
   346  
   347  	// WrapSession is called on the server to produce a session ticket/identity.
   348  	//
   349  	// WrapSession must serialize the session state with [SessionState.Bytes].
   350  	// It may then encrypt the serialized state (for example with
   351  	// [Config.DecryptTicket]) and use it as the ticket, or store the state and
   352  	// return a handle for it.
   353  	//
   354  	// If WrapSession returns an error, the connection is terminated.
   355  	//
   356  	// Warning: the return value will be exposed on the wire and to clients in
   357  	// plaintext. The application is in charge of encrypting and authenticating
   358  	// it (and rotating keys) or returning high-entropy identifiers. Failing to
   359  	// do so correctly can compromise current, previous, and future connections
   360  	// depending on the protocol version.
   361  	WrapSession func(ConnectionState, *SessionState) ([]byte, error)
   362  
   363  	// MinVersion contains the minimum TLS version that is acceptable.
   364  	//
   365  	// By default, TLS 1.2 is currently used as the minimum when acting as a
   366  	// client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum
   367  	// supported by this package, both as a client and as a server.
   368  	//
   369  	// The client-side default can temporarily be reverted to TLS 1.0 by
   370  	// including the value "x509sha1=1" in the GODEBUG environment variable.
   371  	// Note that this option will be removed in Go 1.19 (but it will still be
   372  	// possible to set this field to VersionTLS10 explicitly).
   373  	MinVersion uint16
   374  
   375  	// MaxVersion contains the maximum TLS version that is acceptable.
   376  	//
   377  	// By default, the maximum version supported by this package is used,
   378  	// which is currently TLS 1.3.
   379  	MaxVersion uint16
   380  
   381  	// CurvePreferences contains the elliptic curves that will be used in
   382  	// an ECDHE handshake, in preference order. If empty, the default will
   383  	// be used. The client will use the first preference as the type for
   384  	// its key share in TLS 1.3. This may change in the future.
   385  	CurvePreferences []CurveID
   386  
   387  	// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
   388  	// When true, the largest possible TLS record size is always used. When
   389  	// false, the size of TLS records may be adjusted in an attempt to
   390  	// improve latency.
   391  	DynamicRecordSizingDisabled bool
   392  
   393  	// Renegotiation controls what types of renegotiation are supported.
   394  	// The default, none, is correct for the vast majority of applications.
   395  	Renegotiation RenegotiationSupport
   396  
   397  	// KeyLogWriter optionally specifies a destination for TLS master secrets
   398  	// in NSS key log format that can be used to allow external programs
   399  	// such as Wireshark to decrypt TLS connections.
   400  	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
   401  	// Use of KeyLogWriter compromises security and should only be
   402  	// used for debugging.
   403  	KeyLogWriter io.Writer
   404  
   405  	// mutex protects sessionTicketKeys and autoSessionTicketKeys.
   406  	mutex sync.RWMutex
   407  	// sessionTicketKeys contains zero or more ticket keys. If set, it means
   408  	// the keys were set with SessionTicketKey or SetSessionTicketKeys. The
   409  	// first key is used for new tickets and any subsequent keys can be used to
   410  	// decrypt old tickets. The slice contents are not protected by the mutex
   411  	// and are immutable.
   412  	sessionTicketKeys []ticketKey
   413  	// autoSessionTicketKeys is like sessionTicketKeys but is owned by the
   414  	// auto-rotation logic. See Config.ticketKeys.
   415  	autoSessionTicketKeys []ticketKey
   416  }
   417  
   418  // ticketKey is the internal representation of a session ticket key.
   419  type ticketKey struct {
   420  	aesKey  [16]byte
   421  	hmacKey [16]byte
   422  	// created is the time at which this ticket key was created. See Config.ticketKeys.
   423  	created time.Time
   424  }
   425  
   426  // A Certificate is a chain of one or more certificates, leaf first.
   427  type Certificate struct {
   428  	Certificate [][]byte
   429  	// PrivateKey contains the private key corresponding to the public key in
   430  	// Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
   431  	// For a server up to TLS 1.2, it can also implement crypto.Decrypter with
   432  	// an RSA PublicKey.
   433  	PrivateKey crypto.PrivateKey
   434  	// SupportedSignatureAlgorithms is an optional list restricting what
   435  	// signature algorithms the PrivateKey can be used for.
   436  	SupportedSignatureAlgorithms []SignatureScheme
   437  	// OCSPStaple contains an optional OCSP response which will be served
   438  	// to clients that request it.
   439  	OCSPStaple []byte
   440  	// SignedCertificateTimestamps contains an optional list of Signed
   441  	// Certificate Timestamps which will be served to clients that request it.
   442  	SignedCertificateTimestamps [][]byte
   443  	// Leaf is the parsed form of the leaf certificate, which may be initialized
   444  	// using x509.ParseCertificate to reduce per-handshake processing. If nil,
   445  	// the leaf certificate will be parsed as needed.
   446  	Leaf *x509.Certificate
   447  }