1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
29 maxPlaintext = 16384 // maximum plaintext payload length
30 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
31 tlsRecordHeaderLen = 5 // record header length
32 dtlsRecordHeaderLen = 13
33 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
35 minVersion = VersionSSL30
36 maxVersion = VersionTLS12
43 recordTypeChangeCipherSpec recordType = 20
44 recordTypeAlert recordType = 21
45 recordTypeHandshake recordType = 22
46 recordTypeApplicationData recordType = 23
49 // TLS handshake message types.
51 typeHelloRequest uint8 = 0
52 typeClientHello uint8 = 1
53 typeServerHello uint8 = 2
54 typeHelloVerifyRequest uint8 = 3
55 typeNewSessionTicket uint8 = 4
56 typeCertificate uint8 = 11
57 typeServerKeyExchange uint8 = 12
58 typeCertificateRequest uint8 = 13
59 typeServerHelloDone uint8 = 14
60 typeCertificateVerify uint8 = 15
61 typeClientKeyExchange uint8 = 16
62 typeFinished uint8 = 20
63 typeCertificateStatus uint8 = 22
64 typeNextProtocol uint8 = 67 // Not IANA assigned
65 typeEncryptedExtensions uint8 = 203 // Not IANA assigned
68 // TLS compression types.
70 compressionNone uint8 = 0
73 // TLS extension numbers
75 extensionServerName uint16 = 0
76 extensionStatusRequest uint16 = 5
77 extensionSupportedCurves uint16 = 10
78 extensionSupportedPoints uint16 = 11
79 extensionSignatureAlgorithms uint16 = 13
80 extensionALPN uint16 = 16
81 extensionExtendedMasterSecret uint16 = 23
82 extensionSessionTicket uint16 = 35
83 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
84 extensionRenegotiationInfo uint16 = 0xff01
85 extensionChannelID uint16 = 30032 // not IANA assigned
88 // TLS signaling cipher suite values
90 scsvRenegotiation uint16 = 0x00ff
93 // CurveID is the type of a TLS identifier for an elliptic curve. See
94 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
98 CurveP256 CurveID = 23
99 CurveP384 CurveID = 24
100 CurveP521 CurveID = 25
103 // TLS Elliptic Curve Point Formats
104 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
106 pointFormatUncompressed uint8 = 0
109 // TLS CertificateStatusType (RFC 3546)
111 statusTypeOCSP uint8 = 1
114 // Certificate types (for certificateRequestMsg)
116 CertTypeRSASign = 1 // A certificate containing an RSA key
117 CertTypeDSSSign = 2 // A certificate containing a DSA key
118 CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
119 CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
121 // See RFC4492 sections 3 and 5.5.
122 CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
123 CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
124 CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
126 // Rest of these are reserved by the TLS spec
129 // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
135 // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
137 signatureRSA uint8 = 1
138 signatureECDSA uint8 = 3
141 // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
142 // RFC 5246, section A.4.1.
143 type signatureAndHash struct {
144 signature, hash uint8
147 // supportedSKXSignatureAlgorithms contains the signature and hash algorithms
148 // that the code advertises as supported in a TLS 1.2 ClientHello.
149 var supportedSKXSignatureAlgorithms = []signatureAndHash{
150 {signatureRSA, hashSHA256},
151 {signatureECDSA, hashSHA256},
152 {signatureRSA, hashSHA1},
153 {signatureECDSA, hashSHA1},
156 // supportedClientCertSignatureAlgorithms contains the signature and hash
157 // algorithms that the code advertises as supported in a TLS 1.2
158 // CertificateRequest.
159 var supportedClientCertSignatureAlgorithms = []signatureAndHash{
160 {signatureRSA, hashSHA256},
161 {signatureECDSA, hashSHA256},
164 // ConnectionState records basic TLS details about the connection.
165 type ConnectionState struct {
166 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
167 HandshakeComplete bool // TLS handshake is complete
168 DidResume bool // connection resumes a previous TLS connection
169 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
170 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
171 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
172 NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
173 ServerName string // server name requested by client, if any (server side only)
174 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
175 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
176 ChannelID *ecdsa.PublicKey // the channel ID for this connection
179 // ClientAuthType declares the policy the server will follow for
180 // TLS Client Authentication.
181 type ClientAuthType int
184 NoClientCert ClientAuthType = iota
187 VerifyClientCertIfGiven
188 RequireAndVerifyClientCert
191 // ClientSessionState contains the state needed by clients to resume TLS
193 type ClientSessionState struct {
194 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
195 vers uint16 // SSL/TLS version negotiated for the session
196 cipherSuite uint16 // Ciphersuite negotiated for the session
197 masterSecret []byte // MasterSecret generated by client on a full handshake
198 handshakeHash []byte // Handshake hash for Channel ID purposes.
199 serverCertificates []*x509.Certificate // Certificate chain presented by the server
200 extendedMasterSecret bool // Whether an extended master secret was used to generate the session
203 // ClientSessionCache is a cache of ClientSessionState objects that can be used
204 // by a client to resume a TLS session with a given server. ClientSessionCache
205 // implementations should expect to be called concurrently from different
207 type ClientSessionCache interface {
208 // Get searches for a ClientSessionState associated with the given key.
209 // On return, ok is true if one was found.
210 Get(sessionKey string) (session *ClientSessionState, ok bool)
212 // Put adds the ClientSessionState to the cache with the given key.
213 Put(sessionKey string, cs *ClientSessionState)
216 // A Config structure is used to configure a TLS client or server.
217 // After one has been passed to a TLS function it must not be
218 // modified. A Config may be reused; the tls package will also not
221 // Rand provides the source of entropy for nonces and RSA blinding.
222 // If Rand is nil, TLS uses the cryptographic random reader in package
224 // The Reader must be safe for use by multiple goroutines.
227 // Time returns the current time as the number of seconds since the epoch.
228 // If Time is nil, TLS uses time.Now.
229 Time func() time.Time
231 // Certificates contains one or more certificate chains
232 // to present to the other side of the connection.
233 // Server configurations must include at least one certificate.
234 Certificates []Certificate
236 // NameToCertificate maps from a certificate name to an element of
237 // Certificates. Note that a certificate name can be of the form
238 // '*.example.com' and so doesn't have to be a domain name as such.
239 // See Config.BuildNameToCertificate
240 // The nil value causes the first element of Certificates to be used
241 // for all connections.
242 NameToCertificate map[string]*Certificate
244 // RootCAs defines the set of root certificate authorities
245 // that clients use when verifying server certificates.
246 // If RootCAs is nil, TLS uses the host's root CA set.
247 RootCAs *x509.CertPool
249 // NextProtos is a list of supported, application level protocols.
252 // ServerName is used to verify the hostname on the returned
253 // certificates unless InsecureSkipVerify is given. It is also included
254 // in the client's handshake to support virtual hosting.
257 // ClientAuth determines the server's policy for
258 // TLS Client Authentication. The default is NoClientCert.
259 ClientAuth ClientAuthType
261 // ClientCAs defines the set of root certificate authorities
262 // that servers use if required to verify a client certificate
263 // by the policy in ClientAuth.
264 ClientCAs *x509.CertPool
266 // ClientCertificateTypes defines the set of allowed client certificate
267 // types. The default is CertTypeRSASign and CertTypeECDSASign.
268 ClientCertificateTypes []byte
270 // InsecureSkipVerify controls whether a client verifies the
271 // server's certificate chain and host name.
272 // If InsecureSkipVerify is true, TLS accepts any certificate
273 // presented by the server and any host name in that certificate.
274 // In this mode, TLS is susceptible to man-in-the-middle attacks.
275 // This should be used only for testing.
276 InsecureSkipVerify bool
278 // CipherSuites is a list of supported cipher suites. If CipherSuites
279 // is nil, TLS uses a list of suites supported by the implementation.
280 CipherSuites []uint16
282 // PreferServerCipherSuites controls whether the server selects the
283 // client's most preferred ciphersuite, or the server's most preferred
284 // ciphersuite. If true then the server's preference, as expressed in
285 // the order of elements in CipherSuites, is used.
286 PreferServerCipherSuites bool
288 // SessionTicketsDisabled may be set to true to disable session ticket
289 // (resumption) support.
290 SessionTicketsDisabled bool
292 // SessionTicketKey is used by TLS servers to provide session
293 // resumption. See RFC 5077. If zero, it will be filled with
294 // random data before the first server handshake.
296 // If multiple servers are terminating connections for the same host
297 // they should all have the same SessionTicketKey. If the
298 // SessionTicketKey leaks, previously recorded and future TLS
299 // connections using that key are compromised.
300 SessionTicketKey [32]byte
302 // SessionCache is a cache of ClientSessionState entries for TLS session
304 ClientSessionCache ClientSessionCache
306 // MinVersion contains the minimum SSL/TLS version that is acceptable.
307 // If zero, then SSLv3 is taken as the minimum.
310 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
311 // If zero, then the maximum version supported by this package is used,
312 // which is currently TLS 1.2.
315 // CurvePreferences contains the elliptic curves that will be used in
316 // an ECDHE handshake, in preference order. If empty, the default will
318 CurvePreferences []CurveID
320 // ChannelID contains the ECDSA key for the client to use as
321 // its TLS Channel ID.
322 ChannelID *ecdsa.PrivateKey
324 // RequestChannelID controls whether the server requests a TLS
325 // Channel ID. If negotiated, the client's public key is
326 // returned in the ConnectionState.
327 RequestChannelID bool
329 // PreSharedKey, if not nil, is the pre-shared key to use with
330 // the PSK cipher suites.
333 // PreSharedKeyIdentity, if not empty, is the identity to use
334 // with the PSK cipher suites.
335 PreSharedKeyIdentity string
337 // Bugs specifies optional misbehaviour to be used for testing other
341 serverInitOnce sync.Once // guards calling (*Config).serverInit
347 BadValueNone BadValue = iota
355 type ProtocolBugs struct {
356 // InvalidSKXSignature specifies that the signature in a
357 // ServerKeyExchange message should be invalid.
358 InvalidSKXSignature bool
360 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
364 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
369 // MaxPadding causes CBC records to have the maximum possible padding.
371 // PaddingFirstByteBad causes the first byte of the padding to be
373 PaddingFirstByteBad bool
374 // PaddingFirstByteBadIf255 causes the first byte of padding to be
375 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
376 PaddingFirstByteBadIf255 bool
378 // FailIfNotFallbackSCSV causes a server handshake to fail if the
379 // client doesn't send the fallback SCSV value.
380 FailIfNotFallbackSCSV bool
382 // DuplicateExtension causes an extra empty extension of bogus type to
383 // be emitted in either the ClientHello or the ServerHello.
384 DuplicateExtension bool
386 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
387 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
388 // Certificate message is sent and no signature is added to
389 // ServerKeyExchange.
390 UnauthenticatedECDH bool
392 // SkipServerKeyExchange causes the server to skip sending
393 // ServerKeyExchange messages.
394 SkipServerKeyExchange bool
396 // SkipChangeCipherSpec causes the implementation to skip
397 // sending the ChangeCipherSpec message (and adjusting cipher
398 // state accordingly for the Finished message).
399 SkipChangeCipherSpec bool
401 // EarlyChangeCipherSpec causes the client to send an early
402 // ChangeCipherSpec message before the ClientKeyExchange. A value of
403 // zero disables this behavior. One and two configure variants for 0.9.8
404 // and 1.0.1 modes, respectively.
405 EarlyChangeCipherSpec int
407 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
408 // the Finished (or NextProto) message around the ChangeCipherSpec
410 FragmentAcrossChangeCipherSpec bool
412 // SkipNewSessionTicket causes the server to skip sending the
413 // NewSessionTicket message despite promising to in ServerHello.
414 SkipNewSessionTicket bool
416 // SendV2ClientHello causes the client to send a V2ClientHello
417 // instead of a normal ClientHello.
418 SendV2ClientHello bool
420 // SendFallbackSCSV causes the client to include
421 // TLS_FALLBACK_SCSV in the ClientHello.
422 SendFallbackSCSV bool
424 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
425 // handshake record. Handshake messages will be split into multiple
426 // records at the specified size, except that the client_version will
427 // never be fragmented.
428 MaxHandshakeRecordLength int
430 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
431 // the first 6 bytes of the ClientHello.
432 FragmentClientVersion bool
434 // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
435 // ClientKeyExchange with the specified version rather than the
436 // client_version when performing the RSA key exchange.
437 RsaClientKeyExchangeVersion uint16
439 // RenewTicketOnResume causes the server to renew the session ticket and
440 // send a NewSessionTicket message during an abbreviated handshake.
441 RenewTicketOnResume bool
443 // SendClientVersion, if non-zero, causes the client to send a different
444 // TLS version in the ClientHello than the maximum supported version.
445 SendClientVersion uint16
447 // SkipHelloVerifyRequest causes a DTLS server to skip the
448 // HelloVerifyRequest message.
449 SkipHelloVerifyRequest bool
451 // ExpectFalseStart causes the server to, on full handshakes,
452 // expect the peer to False Start; the server Finished message
453 // isn't sent until we receive an application data record
455 ExpectFalseStart bool
457 // SSL3RSAKeyExchange causes the client to always send an RSA
458 // ClientKeyExchange message without the two-byte length
459 // prefix, as if it were SSL3.
460 SSL3RSAKeyExchange bool
462 // SkipCipherVersionCheck causes the server to negotiate
463 // TLS 1.2 ciphers in earlier versions of TLS.
464 SkipCipherVersionCheck bool
466 // ExpectServerName, if not empty, is the hostname the client
467 // must specify in the server_name extension.
468 ExpectServerName string
470 // SwapNPNAndALPN switches the relative order between NPN and
471 // ALPN on the server. This is to test that server preference
472 // of ALPN works regardless of their relative order.
475 // AllowSessionVersionMismatch causes the server to resume sessions
476 // regardless of the version associated with the session.
477 AllowSessionVersionMismatch bool
479 // CorruptTicket causes a client to corrupt a session ticket before
480 // sending it in a resume handshake.
483 // OversizedSessionId causes the session id that is sent with a ticket
484 // resumption attempt to be too large (33 bytes).
485 OversizedSessionId bool
487 // RequireExtendedMasterSecret, if true, requires that the peer support
488 // the extended master secret option.
489 RequireExtendedMasterSecret bool
491 // NoExtendedMasterSecret causes the client and server to behave is if
492 // they didn't support an extended master secret.
493 NoExtendedMasterSecret bool
495 // EmptyRenegotiationInfo causes the renegotiation extension to be
496 // empty in a renegotiation handshake.
497 EmptyRenegotiationInfo bool
499 // BadRenegotiationInfo causes the renegotiation extension value in a
500 // renegotiation handshake to be incorrect.
501 BadRenegotiationInfo bool
504 func (c *Config) serverInit() {
505 if c.SessionTicketsDisabled {
509 // If the key has already been set then we have nothing to do.
510 for _, b := range c.SessionTicketKey {
516 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
517 c.SessionTicketsDisabled = true
521 func (c *Config) rand() io.Reader {
529 func (c *Config) time() time.Time {
537 func (c *Config) cipherSuites() []uint16 {
540 s = defaultCipherSuites()
545 func (c *Config) minVersion() uint16 {
546 if c == nil || c.MinVersion == 0 {
552 func (c *Config) maxVersion() uint16 {
553 if c == nil || c.MaxVersion == 0 {
559 var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
561 func (c *Config) curvePreferences() []CurveID {
562 if c == nil || len(c.CurvePreferences) == 0 {
563 return defaultCurvePreferences
565 return c.CurvePreferences
568 // mutualVersion returns the protocol version to use given the advertised
569 // version of the peer.
570 func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
571 minVersion := c.minVersion()
572 maxVersion := c.maxVersion()
574 if vers < minVersion {
577 if vers > maxVersion {
583 // getCertificateForName returns the best certificate for the given name,
584 // defaulting to the first element of c.Certificates if there are no good
586 func (c *Config) getCertificateForName(name string) *Certificate {
587 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
588 // There's only one choice, so no point doing any work.
589 return &c.Certificates[0]
592 name = strings.ToLower(name)
593 for len(name) > 0 && name[len(name)-1] == '.' {
594 name = name[:len(name)-1]
597 if cert, ok := c.NameToCertificate[name]; ok {
601 // try replacing labels in the name with wildcards until we get a
603 labels := strings.Split(name, ".")
604 for i := range labels {
606 candidate := strings.Join(labels, ".")
607 if cert, ok := c.NameToCertificate[candidate]; ok {
612 // If nothing matches, return the first certificate.
613 return &c.Certificates[0]
616 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
617 // from the CommonName and SubjectAlternateName fields of each of the leaf
619 func (c *Config) BuildNameToCertificate() {
620 c.NameToCertificate = make(map[string]*Certificate)
621 for i := range c.Certificates {
622 cert := &c.Certificates[i]
623 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
627 if len(x509Cert.Subject.CommonName) > 0 {
628 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
630 for _, san := range x509Cert.DNSNames {
631 c.NameToCertificate[san] = cert
636 // A Certificate is a chain of one or more certificates, leaf first.
637 type Certificate struct {
639 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
640 // OCSPStaple contains an optional OCSP response which will be served
641 // to clients that request it.
643 // Leaf is the parsed form of the leaf certificate, which may be
644 // initialized using x509.ParseCertificate to reduce per-handshake
645 // processing for TLS clients doing client authentication. If nil, the
646 // leaf certificate will be parsed as needed.
647 Leaf *x509.Certificate
652 contentType recordType
657 type handshakeMessage interface {
659 unmarshal([]byte) bool
662 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
664 type lruSessionCache struct {
667 m map[string]*list.Element
672 type lruSessionCacheEntry struct {
674 state *ClientSessionState
677 // NewLRUClientSessionCache returns a ClientSessionCache with the given
678 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
680 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
681 const defaultSessionCacheCapacity = 64
684 capacity = defaultSessionCacheCapacity
686 return &lruSessionCache{
687 m: make(map[string]*list.Element),
693 // Put adds the provided (sessionKey, cs) pair to the cache.
694 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
698 if elem, ok := c.m[sessionKey]; ok {
699 entry := elem.Value.(*lruSessionCacheEntry)
701 c.q.MoveToFront(elem)
705 if c.q.Len() < c.capacity {
706 entry := &lruSessionCacheEntry{sessionKey, cs}
707 c.m[sessionKey] = c.q.PushFront(entry)
712 entry := elem.Value.(*lruSessionCacheEntry)
713 delete(c.m, entry.sessionKey)
714 entry.sessionKey = sessionKey
716 c.q.MoveToFront(elem)
717 c.m[sessionKey] = elem
720 // Get returns the ClientSessionState value associated with a given key. It
721 // returns (nil, false) if no value is found.
722 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
726 if elem, ok := c.m[sessionKey]; ok {
727 c.q.MoveToFront(elem)
728 return elem.Value.(*lruSessionCacheEntry).state, true
733 // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
734 type dsaSignature struct {
738 type ecdsaSignature dsaSignature
740 var emptyConfig Config
742 func defaultConfig() *Config {
748 varDefaultCipherSuites []uint16
751 func defaultCipherSuites() []uint16 {
752 once.Do(initDefaultCipherSuites)
753 return varDefaultCipherSuites
756 func initDefaultCipherSuites() {
757 for _, suite := range cipherSuites {
758 if suite.flags&suitePSK == 0 {
759 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
764 func unexpectedMessageError(wanted, got interface{}) error {
765 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)