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