common.go 39 KB

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