You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1233 line
42 KiB

  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.
  4. package tls
  5. import (
  6. "container/list"
  7. "crypto"
  8. "crypto/internal/cipherhw"
  9. "crypto/rand"
  10. "crypto/sha512"
  11. "crypto/x509"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "math/big"
  16. "net"
  17. "strings"
  18. "sync"
  19. "time"
  20. )
  21. const (
  22. VersionSSL30 = 0x0300
  23. VersionTLS10 = 0x0301
  24. VersionTLS11 = 0x0302
  25. VersionTLS12 = 0x0303
  26. VersionTLS13 = 0x0304
  27. VersionTLS13Draft18 = 0x7f00 | 18
  28. VersionTLS13Draft21 = 0x7f00 | 21
  29. VersionTLS13Draft22 = 0x7f00 | 22
  30. VersionTLS13Draft23 = 0x7f00 | 23
  31. VersionTLS13Draft28 = 0x7f00 | 28
  32. )
  33. const (
  34. maxPlaintext = 16384 // maximum plaintext payload length
  35. maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
  36. recordHeaderLen = 5 // record header length
  37. maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
  38. maxWarnAlertCount = 5 // maximum number of consecutive warning alerts
  39. minVersion = VersionTLS12
  40. maxVersion = VersionTLS13Draft28
  41. )
  42. // TLS record types.
  43. type recordType uint8
  44. const (
  45. recordTypeChangeCipherSpec recordType = 20
  46. recordTypeAlert recordType = 21
  47. recordTypeHandshake recordType = 22
  48. recordTypeApplicationData recordType = 23
  49. )
  50. // TLS handshake message types.
  51. const (
  52. typeHelloRequest uint8 = 0
  53. typeClientHello uint8 = 1
  54. typeServerHello uint8 = 2
  55. typeNewSessionTicket uint8 = 4
  56. typeEndOfEarlyData uint8 = 5
  57. typeEncryptedExtensions uint8 = 8
  58. typeCertificate uint8 = 11
  59. typeServerKeyExchange uint8 = 12
  60. typeCertificateRequest uint8 = 13
  61. typeServerHelloDone uint8 = 14
  62. typeCertificateVerify uint8 = 15
  63. typeClientKeyExchange uint8 = 16
  64. typeFinished uint8 = 20
  65. typeCertificateStatus uint8 = 22
  66. typeNextProtocol uint8 = 67 // Not IANA assigned
  67. )
  68. // TLS compression types.
  69. const (
  70. compressionNone uint8 = 0
  71. )
  72. // TLS extension numbers
  73. const (
  74. extensionServerName uint16 = 0
  75. extensionStatusRequest uint16 = 5
  76. extensionSupportedCurves uint16 = 10 // Supported Groups in 1.3 nomenclature
  77. extensionSupportedPoints uint16 = 11
  78. extensionSignatureAlgorithms uint16 = 13
  79. extensionALPN uint16 = 16
  80. extensionSCT uint16 = 18 // https://tools.ietf.org/html/rfc6962#section-6
  81. extensionSessionTicket uint16 = 35
  82. extensionPreSharedKey uint16 = 41
  83. extensionEarlyData uint16 = 42
  84. extensionSupportedVersions uint16 = 43
  85. extensionPSKKeyExchangeModes uint16 = 45
  86. extensionCAs uint16 = 47
  87. extensionSignatureAlgorithmsCert uint16 = 50
  88. extensionKeyShare uint16 = 51
  89. extensionNextProtoNeg uint16 = 13172 // not IANA assigned
  90. extensionRenegotiationInfo uint16 = 0xff01
  91. extensionDelegatedCredential uint16 = 0xff02 // TODO(any) Get IANA assignment
  92. )
  93. // TLS signaling cipher suite values
  94. const (
  95. scsvRenegotiation uint16 = 0x00ff
  96. )
  97. // PSK Key Exchange Modes
  98. // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.7
  99. const (
  100. pskDHEKeyExchange uint8 = 1
  101. )
  102. // CurveID is the type of a TLS identifier for an elliptic curve. See
  103. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
  104. //
  105. // TLS 1.3 refers to these as Groups, but this library implements only
  106. // curve-based ones anyway. See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.4.
  107. type CurveID uint16
  108. const (
  109. CurveP256 CurveID = 23
  110. CurveP384 CurveID = 24
  111. CurveP521 CurveID = 25
  112. X25519 CurveID = 29
  113. )
  114. // TLS 1.3 Key Share
  115. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.5
  116. type keyShare struct {
  117. group CurveID
  118. data []byte
  119. }
  120. // TLS 1.3 PSK Identity and Binder, as sent by the client
  121. // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.6
  122. type psk struct {
  123. identity []byte
  124. obfTicketAge uint32
  125. binder []byte
  126. }
  127. // TLS Elliptic Curve Point Formats
  128. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
  129. const (
  130. pointFormatUncompressed uint8 = 0
  131. )
  132. // TLS CertificateStatusType (RFC 3546)
  133. const (
  134. statusTypeOCSP uint8 = 1
  135. )
  136. // Certificate types (for certificateRequestMsg)
  137. const (
  138. certTypeRSASign = 1 // A certificate containing an RSA key
  139. certTypeDSSSign = 2 // A certificate containing a DSA key
  140. certTypeRSAFixedDH = 3 // A certificate containing a static DH key
  141. certTypeDSSFixedDH = 4 // A certificate containing a static DH key
  142. // See RFC 4492 sections 3 and 5.5.
  143. certTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
  144. certTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
  145. certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
  146. // Rest of these are reserved by the TLS spec
  147. )
  148. // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
  149. const (
  150. signaturePKCS1v15 uint8 = iota + 1
  151. signatureECDSA
  152. signatureRSAPSS
  153. )
  154. // supportedSignatureAlgorithms contains the signature and hash algorithms that
  155. // the code advertises as supported in a TLS 1.2 ClientHello and in a TLS 1.2
  156. // CertificateRequest. The two fields are merged to match with TLS 1.3.
  157. // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
  158. var supportedSignatureAlgorithms = []SignatureScheme{
  159. PKCS1WithSHA256,
  160. ECDSAWithP256AndSHA256,
  161. PKCS1WithSHA384,
  162. ECDSAWithP384AndSHA384,
  163. PKCS1WithSHA512,
  164. ECDSAWithP521AndSHA512,
  165. PKCS1WithSHA1,
  166. ECDSAWithSHA1,
  167. }
  168. // supportedSignatureAlgorithms13 lists the advertised signature algorithms
  169. // allowed for digital signatures. It includes TLS 1.2 + PSS.
  170. var supportedSignatureAlgorithms13 = []SignatureScheme{
  171. PSSWithSHA256,
  172. PKCS1WithSHA256,
  173. ECDSAWithP256AndSHA256,
  174. PSSWithSHA384,
  175. PKCS1WithSHA384,
  176. ECDSAWithP384AndSHA384,
  177. PSSWithSHA512,
  178. PKCS1WithSHA512,
  179. ECDSAWithP521AndSHA512,
  180. PKCS1WithSHA1,
  181. ECDSAWithSHA1,
  182. }
  183. // ConnectionState records basic TLS details about the connection.
  184. type ConnectionState struct {
  185. ConnectionID []byte // Random unique connection id
  186. Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
  187. HandshakeComplete bool // TLS handshake is complete
  188. DidResume bool // connection resumes a previous TLS connection
  189. CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
  190. NegotiatedProtocol string // negotiated next protocol (not guaranteed to be from Config.NextProtos)
  191. NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server (client side only)
  192. ServerName string // server name requested by client, if any (server side only)
  193. PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
  194. VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
  195. SignedCertificateTimestamps [][]byte // SCTs from the server, if any
  196. OCSPResponse []byte // stapled OCSP response from server, if any
  197. DelegatedCredential []byte // Delegated credential sent by the server, if any
  198. // TLSUnique contains the "tls-unique" channel binding value (see RFC
  199. // 5929, section 3). For resumed sessions this value will be nil
  200. // because resumption does not include enough context (see
  201. // https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will
  202. // change in future versions of Go once the TLS master-secret fix has
  203. // been standardized and implemented.
  204. TLSUnique []byte
  205. // HandshakeConfirmed is true once all data returned by Read
  206. // (past and future) is guaranteed not to be replayed.
  207. HandshakeConfirmed bool
  208. // Unique0RTTToken is a value that never repeats, and can be used
  209. // to detect replay attacks against 0-RTT connections.
  210. // Unique0RTTToken is only present if HandshakeConfirmed is false.
  211. Unique0RTTToken []byte
  212. ClientHello []byte // ClientHello packet
  213. }
  214. // ClientAuthType declares the policy the server will follow for
  215. // TLS Client Authentication.
  216. type ClientAuthType int
  217. const (
  218. NoClientCert ClientAuthType = iota
  219. RequestClientCert
  220. RequireAnyClientCert
  221. VerifyClientCertIfGiven
  222. RequireAndVerifyClientCert
  223. )
  224. // ClientSessionState contains the state needed by clients to resume TLS
  225. // sessions.
  226. type ClientSessionState struct {
  227. sessionTicket []uint8 // Encrypted ticket used for session resumption with server
  228. vers uint16 // SSL/TLS version negotiated for the session
  229. cipherSuite uint16 // Ciphersuite negotiated for the session
  230. masterSecret []byte // MasterSecret generated by client on a full handshake
  231. serverCertificates []*x509.Certificate // Certificate chain presented by the server
  232. verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
  233. }
  234. // ClientSessionCache is a cache of ClientSessionState objects that can be used
  235. // by a client to resume a TLS session with a given server. ClientSessionCache
  236. // implementations should expect to be called concurrently from different
  237. // goroutines. Only ticket-based resumption is supported, not SessionID-based
  238. // resumption.
  239. type ClientSessionCache interface {
  240. // Get searches for a ClientSessionState associated with the given key.
  241. // On return, ok is true if one was found.
  242. Get(sessionKey string) (session *ClientSessionState, ok bool)
  243. // Put adds the ClientSessionState to the cache with the given key.
  244. Put(sessionKey string, cs *ClientSessionState)
  245. }
  246. // SignatureScheme identifies a signature algorithm supported by TLS. See
  247. // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.3.
  248. type SignatureScheme uint16
  249. const (
  250. PKCS1WithSHA1 SignatureScheme = 0x0201
  251. PKCS1WithSHA256 SignatureScheme = 0x0401
  252. PKCS1WithSHA384 SignatureScheme = 0x0501
  253. PKCS1WithSHA512 SignatureScheme = 0x0601
  254. PSSWithSHA256 SignatureScheme = 0x0804
  255. PSSWithSHA384 SignatureScheme = 0x0805
  256. PSSWithSHA512 SignatureScheme = 0x0806
  257. ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
  258. ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
  259. ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
  260. // Legacy signature and hash algorithms for TLS 1.2.
  261. ECDSAWithSHA1 SignatureScheme = 0x0203
  262. )
  263. // ClientHelloInfo contains information from a ClientHello message in order to
  264. // guide certificate selection in the GetCertificate callback.
  265. type ClientHelloInfo struct {
  266. // CipherSuites lists the CipherSuites supported by the client (e.g.
  267. // TLS_RSA_WITH_RC4_128_SHA).
  268. CipherSuites []uint16
  269. // ServerName indicates the name of the server requested by the client
  270. // in order to support virtual hosting. ServerName is only set if the
  271. // client is using SNI (see
  272. // http://tools.ietf.org/html/rfc4366#section-3.1).
  273. ServerName string
  274. // SupportedCurves lists the elliptic curves supported by the client.
  275. // SupportedCurves is set only if the Supported Elliptic Curves
  276. // Extension is being used (see
  277. // http://tools.ietf.org/html/rfc4492#section-5.1.1).
  278. SupportedCurves []CurveID
  279. // SupportedPoints lists the point formats supported by the client.
  280. // SupportedPoints is set only if the Supported Point Formats Extension
  281. // is being used (see
  282. // http://tools.ietf.org/html/rfc4492#section-5.1.2).
  283. SupportedPoints []uint8
  284. // SignatureSchemes lists the signature and hash schemes that the client
  285. // is willing to verify. SignatureSchemes is set only if the Signature
  286. // Algorithms Extension is being used (see
  287. // https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1).
  288. SignatureSchemes []SignatureScheme
  289. // SupportedProtos lists the application protocols supported by the client.
  290. // SupportedProtos is set only if the Application-Layer Protocol
  291. // Negotiation Extension is being used (see
  292. // https://tools.ietf.org/html/rfc7301#section-3.1).
  293. //
  294. // Servers can select a protocol by setting Config.NextProtos in a
  295. // GetConfigForClient return value.
  296. SupportedProtos []string
  297. // SupportedVersions lists the TLS versions supported by the client.
  298. // For TLS versions less than 1.3, this is extrapolated from the max
  299. // version advertised by the client, so values other than the greatest
  300. // might be rejected if used.
  301. SupportedVersions []uint16
  302. // Conn is the underlying net.Conn for the connection. Do not read
  303. // from, or write to, this connection; that will cause the TLS
  304. // connection to fail.
  305. Conn net.Conn
  306. // Offered0RTTData is true if the client announced that it will send
  307. // 0-RTT data. If the server Config.Accept0RTTData is true, and the
  308. // client offered a session ticket valid for that purpose, it will
  309. // be notified that the 0-RTT data is accepted and it will be made
  310. // immediately available for Read.
  311. Offered0RTTData bool
  312. // AcceptsDelegatedCredential is true if the client indicated willingness
  313. // to negotiate the delegated credential extension.
  314. AcceptsDelegatedCredential bool
  315. // The Fingerprint is an sequence of bytes unique to this Client Hello.
  316. // It can be used to prevent or mitigate 0-RTT data replays as it's
  317. // guaranteed that a replayed connection will have the same Fingerprint.
  318. Fingerprint []byte
  319. }
  320. // CertificateRequestInfo contains information from a server's
  321. // CertificateRequest message, which is used to demand a certificate and proof
  322. // of control from a client.
  323. type CertificateRequestInfo struct {
  324. // AcceptableCAs contains zero or more, DER-encoded, X.501
  325. // Distinguished Names. These are the names of root or intermediate CAs
  326. // that the server wishes the returned certificate to be signed by. An
  327. // empty slice indicates that the server has no preference.
  328. AcceptableCAs [][]byte
  329. // SignatureSchemes lists the signature schemes that the server is
  330. // willing to verify.
  331. SignatureSchemes []SignatureScheme
  332. }
  333. // RenegotiationSupport enumerates the different levels of support for TLS
  334. // renegotiation. TLS renegotiation is the act of performing subsequent
  335. // handshakes on a connection after the first. This significantly complicates
  336. // the state machine and has been the source of numerous, subtle security
  337. // issues. Initiating a renegotiation is not supported, but support for
  338. // accepting renegotiation requests may be enabled.
  339. //
  340. // Even when enabled, the server may not change its identity between handshakes
  341. // (i.e. the leaf certificate must be the same). Additionally, concurrent
  342. // handshake and application data flow is not permitted so renegotiation can
  343. // only be used with protocols that synchronise with the renegotiation, such as
  344. // HTTPS.
  345. type RenegotiationSupport int
  346. const (
  347. // RenegotiateNever disables renegotiation.
  348. RenegotiateNever RenegotiationSupport = iota
  349. // RenegotiateOnceAsClient allows a remote server to request
  350. // renegotiation once per connection.
  351. RenegotiateOnceAsClient
  352. // RenegotiateFreelyAsClient allows a remote server to repeatedly
  353. // request renegotiation.
  354. RenegotiateFreelyAsClient
  355. )
  356. // A Config structure is used to configure a TLS client or server.
  357. // After one has been passed to a TLS function it must not be
  358. // modified. A Config may be reused; the tls package will also not
  359. // modify it.
  360. type Config struct {
  361. // Rand provides the source of entropy for nonces and RSA blinding.
  362. // If Rand is nil, TLS uses the cryptographic random reader in package
  363. // crypto/rand.
  364. // The Reader must be safe for use by multiple goroutines.
  365. Rand io.Reader
  366. // Time returns the current time as the number of seconds since the epoch.
  367. // If Time is nil, TLS uses time.Now.
  368. Time func() time.Time
  369. // Certificates contains one or more certificate chains to present to
  370. // the other side of the connection. Server configurations must include
  371. // at least one certificate or else set GetCertificate. Clients doing
  372. // client-authentication may set either Certificates or
  373. // GetClientCertificate.
  374. Certificates []Certificate
  375. // NameToCertificate maps from a certificate name to an element of
  376. // Certificates. Note that a certificate name can be of the form
  377. // '*.example.com' and so doesn't have to be a domain name as such.
  378. // See Config.BuildNameToCertificate
  379. // The nil value causes the first element of Certificates to be used
  380. // for all connections.
  381. NameToCertificate map[string]*Certificate
  382. // GetCertificate returns a Certificate based on the given
  383. // ClientHelloInfo. It will only be called if the client supplies SNI
  384. // information or if Certificates is empty.
  385. //
  386. // If GetCertificate is nil or returns nil, then the certificate is
  387. // retrieved from NameToCertificate. If NameToCertificate is nil, the
  388. // first element of Certificates will be used.
  389. GetCertificate func(*ClientHelloInfo) (*Certificate, error)
  390. // GetClientCertificate, if not nil, is called when a server requests a
  391. // certificate from a client. If set, the contents of Certificates will
  392. // be ignored.
  393. //
  394. // If GetClientCertificate returns an error, the handshake will be
  395. // aborted and that error will be returned. Otherwise
  396. // GetClientCertificate must return a non-nil Certificate. If
  397. // Certificate.Certificate is empty then no certificate will be sent to
  398. // the server. If this is unacceptable to the server then it may abort
  399. // the handshake.
  400. //
  401. // GetClientCertificate may be called multiple times for the same
  402. // connection if renegotiation occurs or if TLS 1.3 is in use.
  403. GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
  404. // GetConfigForClient, if not nil, is called after a ClientHello is
  405. // received from a client. It may return a non-nil Config in order to
  406. // change the Config that will be used to handle this connection. If
  407. // the returned Config is nil, the original Config will be used. The
  408. // Config returned by this callback may not be subsequently modified.
  409. //
  410. // If GetConfigForClient is nil, the Config passed to Server() will be
  411. // used for all connections.
  412. //
  413. // Uniquely for the fields in the returned Config, session ticket keys
  414. // will be duplicated from the original Config if not set.
  415. // Specifically, if SetSessionTicketKeys was called on the original
  416. // config but not on the returned config then the ticket keys from the
  417. // original config will be copied into the new config before use.
  418. // Otherwise, if SessionTicketKey was set in the original config but
  419. // not in the returned config then it will be copied into the returned
  420. // config before use. If neither of those cases applies then the key
  421. // material from the returned config will be used for session tickets.
  422. GetConfigForClient func(*ClientHelloInfo) (*Config, error)
  423. // VerifyPeerCertificate, if not nil, is called after normal
  424. // certificate verification by either a TLS client or server. It
  425. // receives the raw ASN.1 certificates provided by the peer and also
  426. // any verified chains that normal processing found. If it returns a
  427. // non-nil error, the handshake is aborted and that error results.
  428. //
  429. // If normal verification fails then the handshake will abort before
  430. // considering this callback. If normal verification is disabled by
  431. // setting InsecureSkipVerify, or (for a server) when ClientAuth is
  432. // RequestClientCert or RequireAnyClientCert, then this callback will
  433. // be considered but the verifiedChains argument will always be nil.
  434. VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
  435. // RootCAs defines the set of root certificate authorities
  436. // that clients use when verifying server certificates.
  437. // If RootCAs is nil, TLS uses the host's root CA set.
  438. RootCAs *x509.CertPool
  439. // NextProtos is a list of supported, application level protocols.
  440. NextProtos []string
  441. // ServerName is used to verify the hostname on the returned
  442. // certificates unless InsecureSkipVerify is given. It is also included
  443. // in the client's handshake to support virtual hosting unless it is
  444. // an IP address.
  445. ServerName string
  446. // ClientAuth determines the server's policy for
  447. // TLS Client Authentication. The default is NoClientCert.
  448. ClientAuth ClientAuthType
  449. // ClientCAs defines the set of root certificate authorities
  450. // that servers use if required to verify a client certificate
  451. // by the policy in ClientAuth.
  452. ClientCAs *x509.CertPool
  453. // InsecureSkipVerify controls whether a client verifies the
  454. // server's certificate chain and host name.
  455. // If InsecureSkipVerify is true, TLS accepts any certificate
  456. // presented by the server and any host name in that certificate.
  457. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  458. // This should be used only for testing.
  459. InsecureSkipVerify bool
  460. // CipherSuites is a list of supported cipher suites to be used in
  461. // TLS 1.0-1.2. If CipherSuites is nil, TLS uses a list of suites
  462. // supported by the implementation.
  463. CipherSuites []uint16
  464. // PreferServerCipherSuites controls whether the server selects the
  465. // client's most preferred ciphersuite, or the server's most preferred
  466. // ciphersuite. If true then the server's preference, as expressed in
  467. // the order of elements in CipherSuites, is used.
  468. PreferServerCipherSuites bool
  469. // SessionTicketsDisabled may be set to true to disable session ticket
  470. // (resumption) support.
  471. SessionTicketsDisabled bool
  472. // SessionTicketKey is used by TLS servers to provide session
  473. // resumption. See RFC 5077. If zero, it will be filled with
  474. // random data before the first server handshake.
  475. //
  476. // If multiple servers are terminating connections for the same host
  477. // they should all have the same SessionTicketKey. If the
  478. // SessionTicketKey leaks, previously recorded and future TLS
  479. // connections using that key are compromised.
  480. SessionTicketKey [32]byte
  481. // ClientSessionCache is a cache of ClientSessionState entries for TLS
  482. // session resumption.
  483. ClientSessionCache ClientSessionCache
  484. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  485. // If zero, then TLS 1.0 is taken as the minimum.
  486. MinVersion uint16
  487. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  488. // If zero, then the maximum version supported by this package is used,
  489. // which is currently TLS 1.2.
  490. MaxVersion uint16
  491. // CurvePreferences contains the elliptic curves that will be used in
  492. // an ECDHE handshake, in preference order. If empty, the default will
  493. // be used.
  494. CurvePreferences []CurveID
  495. // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
  496. // When true, the largest possible TLS record size is always used. When
  497. // false, the size of TLS records may be adjusted in an attempt to
  498. // improve latency.
  499. DynamicRecordSizingDisabled bool
  500. // Renegotiation controls what types of renegotiation are supported.
  501. // The default, none, is correct for the vast majority of applications.
  502. Renegotiation RenegotiationSupport
  503. // KeyLogWriter optionally specifies a destination for TLS master secrets
  504. // in NSS key log format that can be used to allow external programs
  505. // such as Wireshark to decrypt TLS connections.
  506. // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
  507. // Use of KeyLogWriter compromises security and should only be
  508. // used for debugging.
  509. KeyLogWriter io.Writer
  510. // If Max0RTTDataSize is not zero, the client will be allowed to use
  511. // session tickets to send at most this number of bytes of 0-RTT data.
  512. // 0-RTT data is subject to replay and has memory DoS implications.
  513. // The server will later be able to refuse the 0-RTT data with
  514. // Accept0RTTData, or wait for the client to prove that it's not
  515. // replayed with Conn.ConfirmHandshake.
  516. //
  517. // It has no meaning on the client.
  518. //
  519. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-2.3.
  520. Max0RTTDataSize uint32
  521. // Accept0RTTData makes the 0-RTT data received from the client
  522. // immediately available to Read. 0-RTT data is subject to replay.
  523. // Use Conn.ConfirmHandshake to wait until the data is known not
  524. // to be replayed after reading it.
  525. //
  526. // It has no meaning on the client.
  527. //
  528. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-2.3.
  529. Accept0RTTData bool
  530. // SessionTicketSealer, if not nil, is used to wrap and unwrap
  531. // session tickets, instead of SessionTicketKey.
  532. SessionTicketSealer SessionTicketSealer
  533. // AcceptDelegatedCredential is true if the client is willing to negotiate
  534. // the delegated credential extension.
  535. //
  536. // This value has no meaning for the server.
  537. //
  538. // See https://tools.ietf.org/html/draft-ietf-tls-subcerts-02.
  539. AcceptDelegatedCredential bool
  540. // GetDelegatedCredential returns a DC and its private key for use in the
  541. // delegated credential extension. The inputs to the callback are some
  542. // information parsed from the ClientHello, as well as the protocol version
  543. // selected by the server. This is necessary because the DC is bound to the
  544. // protocol version in which it's used. The return value is the raw DC
  545. // encoded in the wire format specified in
  546. // https://tools.ietf.org/html/draft-ietf-tls-subcerts-02. If the return
  547. // value is nil, then the server will not offer negotiate the extension.
  548. //
  549. // This value has no meaning for the client.
  550. GetDelegatedCredential func(*ClientHelloInfo, uint16) ([]byte, crypto.PrivateKey, error)
  551. serverInitOnce sync.Once // guards calling (*Config).serverInit
  552. // mutex protects sessionTicketKeys.
  553. mutex sync.RWMutex
  554. // sessionTicketKeys contains zero or more ticket keys. If the length
  555. // is zero, SessionTicketsDisabled must be true. The first key is used
  556. // for new tickets and any subsequent keys can be used to decrypt old
  557. // tickets.
  558. sessionTicketKeys []ticketKey
  559. }
  560. // ticketKeyNameLen is the number of bytes of identifier that is prepended to
  561. // an encrypted session ticket in order to identify the key used to encrypt it.
  562. const ticketKeyNameLen = 16
  563. // ticketKey is the internal representation of a session ticket key.
  564. type ticketKey struct {
  565. // keyName is an opaque byte string that serves to identify the session
  566. // ticket key. It's exposed as plaintext in every session ticket.
  567. keyName [ticketKeyNameLen]byte
  568. aesKey [16]byte
  569. hmacKey [16]byte
  570. }
  571. // ticketKeyFromBytes converts from the external representation of a session
  572. // ticket key to a ticketKey. Externally, session ticket keys are 32 random
  573. // bytes and this function expands that into sufficient name and key material.
  574. func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
  575. hashed := sha512.Sum512(b[:])
  576. copy(key.keyName[:], hashed[:ticketKeyNameLen])
  577. copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
  578. copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
  579. return key
  580. }
  581. // Clone returns a shallow clone of c. It is safe to clone a Config that is
  582. // being used concurrently by a TLS client or server.
  583. func (c *Config) Clone() *Config {
  584. // Running serverInit ensures that it's safe to read
  585. // SessionTicketsDisabled.
  586. c.serverInitOnce.Do(func() { c.serverInit(nil) })
  587. var sessionTicketKeys []ticketKey
  588. c.mutex.RLock()
  589. sessionTicketKeys = c.sessionTicketKeys
  590. c.mutex.RUnlock()
  591. return &Config{
  592. Rand: c.Rand,
  593. Time: c.Time,
  594. Certificates: c.Certificates,
  595. NameToCertificate: c.NameToCertificate,
  596. GetCertificate: c.GetCertificate,
  597. GetClientCertificate: c.GetClientCertificate,
  598. GetConfigForClient: c.GetConfigForClient,
  599. VerifyPeerCertificate: c.VerifyPeerCertificate,
  600. RootCAs: c.RootCAs,
  601. NextProtos: c.NextProtos,
  602. ServerName: c.ServerName,
  603. ClientAuth: c.ClientAuth,
  604. ClientCAs: c.ClientCAs,
  605. InsecureSkipVerify: c.InsecureSkipVerify,
  606. CipherSuites: c.CipherSuites,
  607. PreferServerCipherSuites: c.PreferServerCipherSuites,
  608. SessionTicketsDisabled: c.SessionTicketsDisabled,
  609. SessionTicketKey: c.SessionTicketKey,
  610. ClientSessionCache: c.ClientSessionCache,
  611. MinVersion: c.MinVersion,
  612. MaxVersion: c.MaxVersion,
  613. CurvePreferences: c.CurvePreferences,
  614. DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
  615. Renegotiation: c.Renegotiation,
  616. KeyLogWriter: c.KeyLogWriter,
  617. Accept0RTTData: c.Accept0RTTData,
  618. Max0RTTDataSize: c.Max0RTTDataSize,
  619. SessionTicketSealer: c.SessionTicketSealer,
  620. AcceptDelegatedCredential: c.AcceptDelegatedCredential,
  621. GetDelegatedCredential: c.GetDelegatedCredential,
  622. sessionTicketKeys: sessionTicketKeys,
  623. }
  624. }
  625. // serverInit is run under c.serverInitOnce to do initialization of c. If c was
  626. // returned by a GetConfigForClient callback then the argument should be the
  627. // Config that was passed to Server, otherwise it should be nil.
  628. func (c *Config) serverInit(originalConfig *Config) {
  629. if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 || c.SessionTicketSealer != nil {
  630. return
  631. }
  632. alreadySet := false
  633. for _, b := range c.SessionTicketKey {
  634. if b != 0 {
  635. alreadySet = true
  636. break
  637. }
  638. }
  639. if !alreadySet {
  640. if originalConfig != nil {
  641. copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
  642. } else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  643. c.SessionTicketsDisabled = true
  644. return
  645. }
  646. }
  647. if originalConfig != nil {
  648. originalConfig.mutex.RLock()
  649. c.sessionTicketKeys = originalConfig.sessionTicketKeys
  650. originalConfig.mutex.RUnlock()
  651. } else {
  652. c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
  653. }
  654. }
  655. func (c *Config) ticketKeys() []ticketKey {
  656. c.mutex.RLock()
  657. // c.sessionTicketKeys is constant once created. SetSessionTicketKeys
  658. // will only update it by replacing it with a new value.
  659. ret := c.sessionTicketKeys
  660. c.mutex.RUnlock()
  661. return ret
  662. }
  663. // SetSessionTicketKeys updates the session ticket keys for a server. The first
  664. // key will be used when creating new tickets, while all keys can be used for
  665. // decrypting tickets. It is safe to call this function while the server is
  666. // running in order to rotate the session ticket keys. The function will panic
  667. // if keys is empty.
  668. func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
  669. if len(keys) == 0 {
  670. panic("tls: keys must have at least one key")
  671. }
  672. newKeys := make([]ticketKey, len(keys))
  673. for i, bytes := range keys {
  674. newKeys[i] = ticketKeyFromBytes(bytes)
  675. }
  676. c.mutex.Lock()
  677. c.sessionTicketKeys = newKeys
  678. c.mutex.Unlock()
  679. }
  680. func (c *Config) rand() io.Reader {
  681. r := c.Rand
  682. if r == nil {
  683. return rand.Reader
  684. }
  685. return r
  686. }
  687. func (c *Config) time() time.Time {
  688. t := c.Time
  689. if t == nil {
  690. t = time.Now
  691. }
  692. return t()
  693. }
  694. func hasOverlappingCipherSuites(cs1, cs2 []uint16) bool {
  695. for _, c1 := range cs1 {
  696. for _, c2 := range cs2 {
  697. if c1 == c2 {
  698. return true
  699. }
  700. }
  701. }
  702. return false
  703. }
  704. func (c *Config) cipherSuites() []uint16 {
  705. s := c.CipherSuites
  706. if s == nil {
  707. s = defaultCipherSuites()
  708. } else if c.maxVersion() >= VersionTLS13 {
  709. // Ensure that TLS 1.3 suites are always present, but respect
  710. // the application cipher suite preferences.
  711. s13 := defaultTLS13CipherSuites()
  712. if !hasOverlappingCipherSuites(s, s13) {
  713. allSuites := make([]uint16, len(s13)+len(s))
  714. allSuites = append(allSuites, s13...)
  715. s = append(allSuites, s...)
  716. }
  717. }
  718. return s
  719. }
  720. func (c *Config) minVersion() uint16 {
  721. if c == nil || c.MinVersion == 0 {
  722. return minVersion
  723. }
  724. return c.MinVersion
  725. }
  726. func (c *Config) maxVersion() uint16 {
  727. if c == nil || c.MaxVersion == 0 {
  728. return maxVersion
  729. }
  730. return c.MaxVersion
  731. }
  732. var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  733. func (c *Config) curvePreferences() []CurveID {
  734. if c == nil || len(c.CurvePreferences) == 0 {
  735. return defaultCurvePreferences
  736. }
  737. return c.CurvePreferences
  738. }
  739. // mutualVersion returns the protocol version to use given the advertised
  740. // version of the peer using the legacy non-extension methods.
  741. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  742. minVersion := c.minVersion()
  743. maxVersion := c.maxVersion()
  744. // Version 1.3 and higher are not negotiated via this mechanism.
  745. if maxVersion > VersionTLS12 {
  746. maxVersion = VersionTLS12
  747. }
  748. if vers < minVersion {
  749. return 0, false
  750. }
  751. if vers > maxVersion {
  752. vers = maxVersion
  753. }
  754. return vers, true
  755. }
  756. // pickVersion returns the protocol version to use given the advertised
  757. // versions of the peer using the Supported Versions extension.
  758. func (c *Config) pickVersion(peerSupportedVersions []uint16) (uint16, bool) {
  759. supportedVersions := c.getSupportedVersions()
  760. for _, supportedVersion := range supportedVersions {
  761. for _, version := range peerSupportedVersions {
  762. if version == supportedVersion {
  763. return version, true
  764. }
  765. }
  766. }
  767. return 0, false
  768. }
  769. // configSuppVersArray is the backing array of Config.getSupportedVersions
  770. var configSuppVersArray = [...]uint16{VersionTLS13, VersionTLS12, VersionTLS11, VersionTLS10, VersionSSL30}
  771. // tls13DraftSuppVersArray is the backing array of Config.getSupportedVersions
  772. // with TLS 1.3 draft versions included.
  773. //
  774. // TODO: remove once TLS 1.3 is finalised.
  775. var tls13DraftSuppVersArray = [...]uint16{VersionTLS13Draft28, VersionTLS12, VersionTLS11, VersionTLS10, VersionSSL30}
  776. // getSupportedVersions returns the protocol versions that are supported by the
  777. // current configuration.
  778. func (c *Config) getSupportedVersions() []uint16 {
  779. minVersion := c.minVersion()
  780. maxVersion := c.maxVersion()
  781. // Sanity check to avoid advertising unsupported versions.
  782. if minVersion < VersionSSL30 {
  783. minVersion = VersionSSL30
  784. }
  785. if maxVersion > VersionTLS13 {
  786. maxVersion = VersionTLS13
  787. }
  788. if maxVersion < minVersion {
  789. return nil
  790. }
  791. // TODO: remove once TLS 1.3 is finalised.
  792. if maxVersion == VersionTLS13 {
  793. return tls13DraftSuppVersArray[:len(tls13DraftSuppVersArray)-int(minVersion-VersionSSL30)]
  794. }
  795. return configSuppVersArray[VersionTLS13-maxVersion : VersionTLS13-minVersion+1]
  796. }
  797. // getCertificate returns the best certificate for the given ClientHelloInfo,
  798. // defaulting to the first element of c.Certificates.
  799. func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  800. if c.GetCertificate != nil &&
  801. (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  802. cert, err := c.GetCertificate(clientHello)
  803. if cert != nil || err != nil {
  804. return cert, err
  805. }
  806. }
  807. if len(c.Certificates) == 0 {
  808. return nil, errors.New("tls: no certificates configured")
  809. }
  810. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  811. // There's only one choice, so no point doing any work.
  812. return &c.Certificates[0], nil
  813. }
  814. name := strings.ToLower(clientHello.ServerName)
  815. for len(name) > 0 && name[len(name)-1] == '.' {
  816. name = name[:len(name)-1]
  817. }
  818. if cert, ok := c.NameToCertificate[name]; ok {
  819. return cert, nil
  820. }
  821. // try replacing labels in the name with wildcards until we get a
  822. // match.
  823. labels := strings.Split(name, ".")
  824. for i := range labels {
  825. labels[i] = "*"
  826. candidate := strings.Join(labels, ".")
  827. if cert, ok := c.NameToCertificate[candidate]; ok {
  828. return cert, nil
  829. }
  830. }
  831. // If nothing matches, return the first certificate.
  832. return &c.Certificates[0], nil
  833. }
  834. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  835. // from the CommonName and SubjectAlternateName fields of each of the leaf
  836. // certificates.
  837. func (c *Config) BuildNameToCertificate() {
  838. c.NameToCertificate = make(map[string]*Certificate)
  839. for i := range c.Certificates {
  840. cert := &c.Certificates[i]
  841. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  842. if err != nil {
  843. continue
  844. }
  845. if len(x509Cert.Subject.CommonName) > 0 {
  846. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  847. }
  848. for _, san := range x509Cert.DNSNames {
  849. c.NameToCertificate[san] = cert
  850. }
  851. }
  852. }
  853. // writeKeyLog logs client random and master secret if logging was enabled by
  854. // setting c.KeyLogWriter.
  855. func (c *Config) writeKeyLog(what string, clientRandom, masterSecret []byte) error {
  856. if c.KeyLogWriter == nil {
  857. return nil
  858. }
  859. logLine := []byte(fmt.Sprintf("%s %x %x\n", what, clientRandom, masterSecret))
  860. writerMutex.Lock()
  861. _, err := c.KeyLogWriter.Write(logLine)
  862. writerMutex.Unlock()
  863. return err
  864. }
  865. // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
  866. // and is only for debugging, so a global mutex saves space.
  867. var writerMutex sync.Mutex
  868. // A Certificate is a chain of one or more certificates, leaf first.
  869. type Certificate struct {
  870. Certificate [][]byte
  871. // PrivateKey contains the private key corresponding to the public key
  872. // in Leaf. For a server, this must implement crypto.Signer and/or
  873. // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
  874. // (performing client authentication), this must be a crypto.Signer
  875. // with an RSA or ECDSA PublicKey.
  876. PrivateKey crypto.PrivateKey
  877. // OCSPStaple contains an optional OCSP response which will be served
  878. // to clients that request it.
  879. OCSPStaple []byte
  880. // SignedCertificateTimestamps contains an optional list of Signed
  881. // Certificate Timestamps which will be served to clients that request it.
  882. SignedCertificateTimestamps [][]byte
  883. // Leaf is the parsed form of the leaf certificate, which may be
  884. // initialized using x509.ParseCertificate to reduce per-handshake
  885. // processing for TLS clients doing client authentication. If nil, the
  886. // leaf certificate will be parsed as needed.
  887. Leaf *x509.Certificate
  888. }
  889. type handshakeMessage interface {
  890. marshal() []byte
  891. unmarshal([]byte) alert
  892. }
  893. // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  894. // caching strategy.
  895. type lruSessionCache struct {
  896. sync.Mutex
  897. m map[string]*list.Element
  898. q *list.List
  899. capacity int
  900. }
  901. type lruSessionCacheEntry struct {
  902. sessionKey string
  903. state *ClientSessionState
  904. }
  905. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  906. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  907. // is used instead.
  908. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  909. const defaultSessionCacheCapacity = 64
  910. if capacity < 1 {
  911. capacity = defaultSessionCacheCapacity
  912. }
  913. return &lruSessionCache{
  914. m: make(map[string]*list.Element),
  915. q: list.New(),
  916. capacity: capacity,
  917. }
  918. }
  919. // Put adds the provided (sessionKey, cs) pair to the cache.
  920. func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  921. c.Lock()
  922. defer c.Unlock()
  923. if elem, ok := c.m[sessionKey]; ok {
  924. entry := elem.Value.(*lruSessionCacheEntry)
  925. entry.state = cs
  926. c.q.MoveToFront(elem)
  927. return
  928. }
  929. if c.q.Len() < c.capacity {
  930. entry := &lruSessionCacheEntry{sessionKey, cs}
  931. c.m[sessionKey] = c.q.PushFront(entry)
  932. return
  933. }
  934. elem := c.q.Back()
  935. entry := elem.Value.(*lruSessionCacheEntry)
  936. delete(c.m, entry.sessionKey)
  937. entry.sessionKey = sessionKey
  938. entry.state = cs
  939. c.q.MoveToFront(elem)
  940. c.m[sessionKey] = elem
  941. }
  942. // Get returns the ClientSessionState value associated with a given key. It
  943. // returns (nil, false) if no value is found.
  944. func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  945. c.Lock()
  946. defer c.Unlock()
  947. if elem, ok := c.m[sessionKey]; ok {
  948. c.q.MoveToFront(elem)
  949. return elem.Value.(*lruSessionCacheEntry).state, true
  950. }
  951. return nil, false
  952. }
  953. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  954. type dsaSignature struct {
  955. R, S *big.Int
  956. }
  957. type ecdsaSignature dsaSignature
  958. var emptyConfig Config
  959. func defaultConfig() *Config {
  960. return &emptyConfig
  961. }
  962. var (
  963. once sync.Once
  964. varDefaultCipherSuites []uint16
  965. varDefaultTLS13CipherSuites []uint16
  966. )
  967. func defaultCipherSuites() []uint16 {
  968. once.Do(initDefaultCipherSuites)
  969. return varDefaultCipherSuites
  970. }
  971. func defaultTLS13CipherSuites() []uint16 {
  972. once.Do(initDefaultCipherSuites)
  973. return varDefaultTLS13CipherSuites
  974. }
  975. func initDefaultCipherSuites() {
  976. var topCipherSuites, topTLS13CipherSuites []uint16
  977. if cipherhw.AESGCMSupport() {
  978. // If AES-GCM hardware is provided then prioritise AES-GCM
  979. // cipher suites.
  980. topTLS13CipherSuites = []uint16{
  981. TLS_AES_128_GCM_SHA256,
  982. TLS_AES_256_GCM_SHA384,
  983. TLS_CHACHA20_POLY1305_SHA256,
  984. }
  985. topCipherSuites = []uint16{
  986. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  987. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  988. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  989. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  990. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  991. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  992. }
  993. } else {
  994. // Without AES-GCM hardware, we put the ChaCha20-Poly1305
  995. // cipher suites first.
  996. topTLS13CipherSuites = []uint16{
  997. TLS_CHACHA20_POLY1305_SHA256,
  998. TLS_AES_128_GCM_SHA256,
  999. TLS_AES_256_GCM_SHA384,
  1000. }
  1001. topCipherSuites = []uint16{
  1002. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  1003. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  1004. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1005. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1006. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1007. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  1008. }
  1009. }
  1010. varDefaultTLS13CipherSuites = make([]uint16, 0, len(cipherSuites))
  1011. varDefaultTLS13CipherSuites = append(varDefaultTLS13CipherSuites, topTLS13CipherSuites...)
  1012. varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
  1013. varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
  1014. NextCipherSuite:
  1015. for _, suite := range cipherSuites {
  1016. if suite.flags&suiteDefaultOff != 0 {
  1017. continue
  1018. }
  1019. if suite.flags&suiteTLS13 != 0 {
  1020. for _, existing := range varDefaultTLS13CipherSuites {
  1021. if existing == suite.id {
  1022. continue NextCipherSuite
  1023. }
  1024. }
  1025. varDefaultTLS13CipherSuites = append(varDefaultTLS13CipherSuites, suite.id)
  1026. } else {
  1027. for _, existing := range varDefaultCipherSuites {
  1028. if existing == suite.id {
  1029. continue NextCipherSuite
  1030. }
  1031. }
  1032. varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  1033. }
  1034. }
  1035. varDefaultCipherSuites = append(varDefaultTLS13CipherSuites, varDefaultCipherSuites...)
  1036. }
  1037. func unexpectedMessageError(wanted, got interface{}) error {
  1038. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  1039. }
  1040. func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
  1041. for _, s := range supportedSignatureAlgorithms {
  1042. if s == sigAlg {
  1043. return true
  1044. }
  1045. }
  1046. return false
  1047. }
  1048. // signatureFromSignatureScheme maps a signature algorithm to the underlying
  1049. // signature method (without hash function).
  1050. func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 {
  1051. switch signatureAlgorithm {
  1052. case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
  1053. return signaturePKCS1v15
  1054. case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
  1055. return signatureRSAPSS
  1056. case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
  1057. return signatureECDSA
  1058. default:
  1059. return 0
  1060. }
  1061. }
  1062. // TODO(kk): Use variable length encoding?
  1063. func getUint24(b []byte) int {
  1064. n := int(b[2])
  1065. n += int(b[1] << 8)
  1066. n += int(b[0] << 16)
  1067. return n
  1068. }
  1069. func putUint24(b []byte, n int) {
  1070. b[0] = byte(n >> 16)
  1071. b[1] = byte(n >> 8)
  1072. b[2] = byte(n & 0xff)
  1073. }