Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

1100 Zeilen
36 KiB

  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "container/list"
  7. "crypto"
  8. "crypto/ecdsa"
  9. "crypto/rand"
  10. "crypto/x509"
  11. "fmt"
  12. "io"
  13. "math/big"
  14. "strings"
  15. "sync"
  16. "time"
  17. )
  18. const (
  19. VersionSSL30 = 0x0300
  20. VersionTLS10 = 0x0301
  21. VersionTLS11 = 0x0302
  22. VersionTLS12 = 0x0303
  23. )
  24. const (
  25. maxPlaintext = 16384 // maximum plaintext payload length
  26. maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
  27. tlsRecordHeaderLen = 5 // record header length
  28. dtlsRecordHeaderLen = 13
  29. maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
  30. minVersion = VersionSSL30
  31. maxVersion = VersionTLS12
  32. )
  33. // TLS record types.
  34. type recordType uint8
  35. const (
  36. recordTypeChangeCipherSpec recordType = 20
  37. recordTypeAlert recordType = 21
  38. recordTypeHandshake recordType = 22
  39. recordTypeApplicationData recordType = 23
  40. )
  41. // TLS handshake message types.
  42. const (
  43. typeHelloRequest uint8 = 0
  44. typeClientHello uint8 = 1
  45. typeServerHello uint8 = 2
  46. typeHelloVerifyRequest uint8 = 3
  47. typeNewSessionTicket uint8 = 4
  48. typeCertificate uint8 = 11
  49. typeServerKeyExchange uint8 = 12
  50. typeCertificateRequest uint8 = 13
  51. typeServerHelloDone uint8 = 14
  52. typeCertificateVerify uint8 = 15
  53. typeClientKeyExchange uint8 = 16
  54. typeFinished uint8 = 20
  55. typeCertificateStatus uint8 = 22
  56. typeNextProtocol uint8 = 67 // Not IANA assigned
  57. typeEncryptedExtensions uint8 = 203 // Not IANA assigned
  58. )
  59. // TLS compression types.
  60. const (
  61. compressionNone uint8 = 0
  62. )
  63. // TLS extension numbers
  64. const (
  65. extensionServerName uint16 = 0
  66. extensionStatusRequest uint16 = 5
  67. extensionSupportedCurves uint16 = 10
  68. extensionSupportedPoints uint16 = 11
  69. extensionSignatureAlgorithms uint16 = 13
  70. extensionUseSRTP uint16 = 14
  71. extensionALPN uint16 = 16
  72. extensionSignedCertificateTimestamp uint16 = 18
  73. extensionExtendedMasterSecret uint16 = 23
  74. extensionSessionTicket uint16 = 35
  75. extensionCustom uint16 = 1234 // not IANA assigned
  76. extensionNextProtoNeg uint16 = 13172 // not IANA assigned
  77. extensionRenegotiationInfo uint16 = 0xff01
  78. extensionChannelID uint16 = 30032 // not IANA assigned
  79. )
  80. // TLS signaling cipher suite values
  81. const (
  82. scsvRenegotiation uint16 = 0x00ff
  83. )
  84. // CurveID is the type of a TLS identifier for an elliptic curve. See
  85. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
  86. type CurveID uint16
  87. const (
  88. CurveP224 CurveID = 21
  89. CurveP256 CurveID = 23
  90. CurveP384 CurveID = 24
  91. CurveP521 CurveID = 25
  92. )
  93. // TLS Elliptic Curve Point Formats
  94. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
  95. const (
  96. pointFormatUncompressed uint8 = 0
  97. )
  98. // TLS CertificateStatusType (RFC 3546)
  99. const (
  100. statusTypeOCSP uint8 = 1
  101. )
  102. // Certificate types (for certificateRequestMsg)
  103. const (
  104. CertTypeRSASign = 1 // A certificate containing an RSA key
  105. CertTypeDSSSign = 2 // A certificate containing a DSA key
  106. CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
  107. CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
  108. // See RFC4492 sections 3 and 5.5.
  109. CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
  110. CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
  111. CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
  112. // Rest of these are reserved by the TLS spec
  113. )
  114. // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
  115. const (
  116. hashMD5 uint8 = 1
  117. hashSHA1 uint8 = 2
  118. hashSHA224 uint8 = 3
  119. hashSHA256 uint8 = 4
  120. hashSHA384 uint8 = 5
  121. hashSHA512 uint8 = 6
  122. )
  123. // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
  124. const (
  125. signatureRSA uint8 = 1
  126. signatureECDSA uint8 = 3
  127. )
  128. // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
  129. // RFC 5246, section A.4.1.
  130. type signatureAndHash struct {
  131. signature, hash uint8
  132. }
  133. // supportedSKXSignatureAlgorithms contains the signature and hash algorithms
  134. // that the code advertises as supported in a TLS 1.2 ClientHello.
  135. var supportedSKXSignatureAlgorithms = []signatureAndHash{
  136. {signatureRSA, hashSHA256},
  137. {signatureECDSA, hashSHA256},
  138. {signatureRSA, hashSHA1},
  139. {signatureECDSA, hashSHA1},
  140. }
  141. // supportedClientCertSignatureAlgorithms contains the signature and hash
  142. // algorithms that the code advertises as supported in a TLS 1.2
  143. // CertificateRequest.
  144. var supportedClientCertSignatureAlgorithms = []signatureAndHash{
  145. {signatureRSA, hashSHA256},
  146. {signatureECDSA, hashSHA256},
  147. }
  148. // SRTP protection profiles (See RFC 5764, section 4.1.2)
  149. const (
  150. SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001
  151. SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002
  152. )
  153. // ConnectionState records basic TLS details about the connection.
  154. type ConnectionState struct {
  155. Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
  156. HandshakeComplete bool // TLS handshake is complete
  157. DidResume bool // connection resumes a previous TLS connection
  158. CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
  159. NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
  160. NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
  161. NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
  162. ServerName string // server name requested by client, if any (server side only)
  163. PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
  164. VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
  165. ChannelID *ecdsa.PublicKey // the channel ID for this connection
  166. SRTPProtectionProfile uint16 // the negotiated DTLS-SRTP protection profile
  167. TLSUnique []byte
  168. }
  169. // ClientAuthType declares the policy the server will follow for
  170. // TLS Client Authentication.
  171. type ClientAuthType int
  172. const (
  173. NoClientCert ClientAuthType = iota
  174. RequestClientCert
  175. RequireAnyClientCert
  176. VerifyClientCertIfGiven
  177. RequireAndVerifyClientCert
  178. )
  179. // ClientSessionState contains the state needed by clients to resume TLS
  180. // sessions.
  181. type ClientSessionState struct {
  182. sessionId []uint8 // Session ID supplied by the server. nil if the session has a ticket.
  183. sessionTicket []uint8 // Encrypted ticket used for session resumption with server
  184. vers uint16 // SSL/TLS version negotiated for the session
  185. cipherSuite uint16 // Ciphersuite negotiated for the session
  186. masterSecret []byte // MasterSecret generated by client on a full handshake
  187. handshakeHash []byte // Handshake hash for Channel ID purposes.
  188. serverCertificates []*x509.Certificate // Certificate chain presented by the server
  189. extendedMasterSecret bool // Whether an extended master secret was used to generate the session
  190. }
  191. // ClientSessionCache is a cache of ClientSessionState objects that can be used
  192. // by a client to resume a TLS session with a given server. ClientSessionCache
  193. // implementations should expect to be called concurrently from different
  194. // goroutines.
  195. type ClientSessionCache interface {
  196. // Get searches for a ClientSessionState associated with the given key.
  197. // On return, ok is true if one was found.
  198. Get(sessionKey string) (session *ClientSessionState, ok bool)
  199. // Put adds the ClientSessionState to the cache with the given key.
  200. Put(sessionKey string, cs *ClientSessionState)
  201. }
  202. // ServerSessionCache is a cache of sessionState objects that can be used by a
  203. // client to resume a TLS session with a given server. ServerSessionCache
  204. // implementations should expect to be called concurrently from different
  205. // goroutines.
  206. type ServerSessionCache interface {
  207. // Get searches for a sessionState associated with the given session
  208. // ID. On return, ok is true if one was found.
  209. Get(sessionId string) (session *sessionState, ok bool)
  210. // Put adds the sessionState to the cache with the given session ID.
  211. Put(sessionId string, session *sessionState)
  212. }
  213. // A Config structure is used to configure a TLS client or server.
  214. // After one has been passed to a TLS function it must not be
  215. // modified. A Config may be reused; the tls package will also not
  216. // modify it.
  217. type Config struct {
  218. // Rand provides the source of entropy for nonces and RSA blinding.
  219. // If Rand is nil, TLS uses the cryptographic random reader in package
  220. // crypto/rand.
  221. // The Reader must be safe for use by multiple goroutines.
  222. Rand io.Reader
  223. // Time returns the current time as the number of seconds since the epoch.
  224. // If Time is nil, TLS uses time.Now.
  225. Time func() time.Time
  226. // Certificates contains one or more certificate chains
  227. // to present to the other side of the connection.
  228. // Server configurations must include at least one certificate.
  229. Certificates []Certificate
  230. // NameToCertificate maps from a certificate name to an element of
  231. // Certificates. Note that a certificate name can be of the form
  232. // '*.example.com' and so doesn't have to be a domain name as such.
  233. // See Config.BuildNameToCertificate
  234. // The nil value causes the first element of Certificates to be used
  235. // for all connections.
  236. NameToCertificate map[string]*Certificate
  237. // RootCAs defines the set of root certificate authorities
  238. // that clients use when verifying server certificates.
  239. // If RootCAs is nil, TLS uses the host's root CA set.
  240. RootCAs *x509.CertPool
  241. // NextProtos is a list of supported, application level protocols.
  242. NextProtos []string
  243. // ServerName is used to verify the hostname on the returned
  244. // certificates unless InsecureSkipVerify is given. It is also included
  245. // in the client's handshake to support virtual hosting.
  246. ServerName string
  247. // ClientAuth determines the server's policy for
  248. // TLS Client Authentication. The default is NoClientCert.
  249. ClientAuth ClientAuthType
  250. // ClientCAs defines the set of root certificate authorities
  251. // that servers use if required to verify a client certificate
  252. // by the policy in ClientAuth.
  253. ClientCAs *x509.CertPool
  254. // ClientCertificateTypes defines the set of allowed client certificate
  255. // types. The default is CertTypeRSASign and CertTypeECDSASign.
  256. ClientCertificateTypes []byte
  257. // InsecureSkipVerify controls whether a client verifies the
  258. // server's certificate chain and host name.
  259. // If InsecureSkipVerify is true, TLS accepts any certificate
  260. // presented by the server and any host name in that certificate.
  261. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  262. // This should be used only for testing.
  263. InsecureSkipVerify bool
  264. // CipherSuites is a list of supported cipher suites. If CipherSuites
  265. // is nil, TLS uses a list of suites supported by the implementation.
  266. CipherSuites []uint16
  267. // PreferServerCipherSuites controls whether the server selects the
  268. // client's most preferred ciphersuite, or the server's most preferred
  269. // ciphersuite. If true then the server's preference, as expressed in
  270. // the order of elements in CipherSuites, is used.
  271. PreferServerCipherSuites bool
  272. // SessionTicketsDisabled may be set to true to disable session ticket
  273. // (resumption) support.
  274. SessionTicketsDisabled bool
  275. // SessionTicketKey is used by TLS servers to provide session
  276. // resumption. See RFC 5077. If zero, it will be filled with
  277. // random data before the first server handshake.
  278. //
  279. // If multiple servers are terminating connections for the same host
  280. // they should all have the same SessionTicketKey. If the
  281. // SessionTicketKey leaks, previously recorded and future TLS
  282. // connections using that key are compromised.
  283. SessionTicketKey [32]byte
  284. // ClientSessionCache is a cache of ClientSessionState entries
  285. // for TLS session resumption.
  286. ClientSessionCache ClientSessionCache
  287. // ServerSessionCache is a cache of sessionState entries for TLS session
  288. // resumption.
  289. ServerSessionCache ServerSessionCache
  290. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  291. // If zero, then SSLv3 is taken as the minimum.
  292. MinVersion uint16
  293. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  294. // If zero, then the maximum version supported by this package is used,
  295. // which is currently TLS 1.2.
  296. MaxVersion uint16
  297. // CurvePreferences contains the elliptic curves that will be used in
  298. // an ECDHE handshake, in preference order. If empty, the default will
  299. // be used.
  300. CurvePreferences []CurveID
  301. // ChannelID contains the ECDSA key for the client to use as
  302. // its TLS Channel ID.
  303. ChannelID *ecdsa.PrivateKey
  304. // RequestChannelID controls whether the server requests a TLS
  305. // Channel ID. If negotiated, the client's public key is
  306. // returned in the ConnectionState.
  307. RequestChannelID bool
  308. // PreSharedKey, if not nil, is the pre-shared key to use with
  309. // the PSK cipher suites.
  310. PreSharedKey []byte
  311. // PreSharedKeyIdentity, if not empty, is the identity to use
  312. // with the PSK cipher suites.
  313. PreSharedKeyIdentity string
  314. // SRTPProtectionProfiles, if not nil, is the list of SRTP
  315. // protection profiles to offer in DTLS-SRTP.
  316. SRTPProtectionProfiles []uint16
  317. // SignatureAndHashes, if not nil, overrides the default set of
  318. // supported signature and hash algorithms to advertise in
  319. // CertificateRequest.
  320. SignatureAndHashes []signatureAndHash
  321. // Bugs specifies optional misbehaviour to be used for testing other
  322. // implementations.
  323. Bugs ProtocolBugs
  324. serverInitOnce sync.Once // guards calling (*Config).serverInit
  325. }
  326. type BadValue int
  327. const (
  328. BadValueNone BadValue = iota
  329. BadValueNegative
  330. BadValueZero
  331. BadValueLimit
  332. BadValueLarge
  333. NumBadValues
  334. )
  335. type ProtocolBugs struct {
  336. // InvalidSKXSignature specifies that the signature in a
  337. // ServerKeyExchange message should be invalid.
  338. InvalidSKXSignature bool
  339. // InvalidCertVerifySignature specifies that the signature in a
  340. // CertificateVerify message should be invalid.
  341. InvalidCertVerifySignature bool
  342. // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
  343. // to be wrong.
  344. InvalidSKXCurve bool
  345. // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
  346. // can be invalid.
  347. BadECDSAR BadValue
  348. BadECDSAS BadValue
  349. // MaxPadding causes CBC records to have the maximum possible padding.
  350. MaxPadding bool
  351. // PaddingFirstByteBad causes the first byte of the padding to be
  352. // incorrect.
  353. PaddingFirstByteBad bool
  354. // PaddingFirstByteBadIf255 causes the first byte of padding to be
  355. // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
  356. PaddingFirstByteBadIf255 bool
  357. // FailIfNotFallbackSCSV causes a server handshake to fail if the
  358. // client doesn't send the fallback SCSV value.
  359. FailIfNotFallbackSCSV bool
  360. // DuplicateExtension causes an extra empty extension of bogus type to
  361. // be emitted in either the ClientHello or the ServerHello.
  362. DuplicateExtension bool
  363. // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
  364. // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
  365. // Certificate message is sent and no signature is added to
  366. // ServerKeyExchange.
  367. UnauthenticatedECDH bool
  368. // SkipHelloVerifyRequest causes a DTLS server to skip the
  369. // HelloVerifyRequest message.
  370. SkipHelloVerifyRequest bool
  371. // SkipCertificateStatus, if true, causes the server to skip the
  372. // CertificateStatus message. This is legal because CertificateStatus is
  373. // optional, even with a status_request in ServerHello.
  374. SkipCertificateStatus bool
  375. // SkipServerKeyExchange causes the server to skip sending
  376. // ServerKeyExchange messages.
  377. SkipServerKeyExchange bool
  378. // SkipNewSessionTicket causes the server to skip sending the
  379. // NewSessionTicket message despite promising to in ServerHello.
  380. SkipNewSessionTicket bool
  381. // SkipChangeCipherSpec causes the implementation to skip
  382. // sending the ChangeCipherSpec message (and adjusting cipher
  383. // state accordingly for the Finished message).
  384. SkipChangeCipherSpec bool
  385. // SkipFinished causes the implementation to skip sending the Finished
  386. // message.
  387. SkipFinished bool
  388. // EarlyChangeCipherSpec causes the client to send an early
  389. // ChangeCipherSpec message before the ClientKeyExchange. A value of
  390. // zero disables this behavior. One and two configure variants for 0.9.8
  391. // and 1.0.1 modes, respectively.
  392. EarlyChangeCipherSpec int
  393. // FragmentAcrossChangeCipherSpec causes the implementation to fragment
  394. // the Finished (or NextProto) message around the ChangeCipherSpec
  395. // messages.
  396. FragmentAcrossChangeCipherSpec bool
  397. // SendV2ClientHello causes the client to send a V2ClientHello
  398. // instead of a normal ClientHello.
  399. SendV2ClientHello bool
  400. // SendFallbackSCSV causes the client to include
  401. // TLS_FALLBACK_SCSV in the ClientHello.
  402. SendFallbackSCSV bool
  403. // SendRenegotiationSCSV causes the client to include the renegotiation
  404. // SCSV in the ClientHello.
  405. SendRenegotiationSCSV bool
  406. // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
  407. // handshake record. Handshake messages will be split into multiple
  408. // records at the specified size, except that the client_version will
  409. // never be fragmented. For DTLS, it is the maximum handshake fragment
  410. // size, not record size; DTLS allows multiple handshake fragments in a
  411. // single handshake record. See |PackHandshakeFragments|.
  412. MaxHandshakeRecordLength int
  413. // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
  414. // the first 6 bytes of the ClientHello.
  415. FragmentClientVersion bool
  416. // FragmentAlert will cause all alerts to be fragmented across
  417. // two records.
  418. FragmentAlert bool
  419. // SendSpuriousAlert, if non-zero, will cause an spurious, unwanted
  420. // alert to be sent.
  421. SendSpuriousAlert alert
  422. // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
  423. // ClientKeyExchange with the specified version rather than the
  424. // client_version when performing the RSA key exchange.
  425. RsaClientKeyExchangeVersion uint16
  426. // RenewTicketOnResume causes the server to renew the session ticket and
  427. // send a NewSessionTicket message during an abbreviated handshake.
  428. RenewTicketOnResume bool
  429. // SendClientVersion, if non-zero, causes the client to send a different
  430. // TLS version in the ClientHello than the maximum supported version.
  431. SendClientVersion uint16
  432. // ExpectFalseStart causes the server to, on full handshakes,
  433. // expect the peer to False Start; the server Finished message
  434. // isn't sent until we receive an application data record
  435. // from the peer.
  436. ExpectFalseStart bool
  437. // AlertBeforeFalseStartTest, if non-zero, causes the server to, on full
  438. // handshakes, send an alert just before reading the application data
  439. // record to test False Start. This can be used in a negative False
  440. // Start test to determine whether the peer processed the alert (and
  441. // closed the connection) before or after sending app data.
  442. AlertBeforeFalseStartTest alert
  443. // SSL3RSAKeyExchange causes the client to always send an RSA
  444. // ClientKeyExchange message without the two-byte length
  445. // prefix, as if it were SSL3.
  446. SSL3RSAKeyExchange bool
  447. // SkipCipherVersionCheck causes the server to negotiate
  448. // TLS 1.2 ciphers in earlier versions of TLS.
  449. SkipCipherVersionCheck bool
  450. // ExpectServerName, if not empty, is the hostname the client
  451. // must specify in the server_name extension.
  452. ExpectServerName string
  453. // SwapNPNAndALPN switches the relative order between NPN and
  454. // ALPN on the server. This is to test that server preference
  455. // of ALPN works regardless of their relative order.
  456. SwapNPNAndALPN bool
  457. // ALPNProtocol, if not nil, sets the ALPN protocol that a server will
  458. // return.
  459. ALPNProtocol *string
  460. // AllowSessionVersionMismatch causes the server to resume sessions
  461. // regardless of the version associated with the session.
  462. AllowSessionVersionMismatch bool
  463. // CorruptTicket causes a client to corrupt a session ticket before
  464. // sending it in a resume handshake.
  465. CorruptTicket bool
  466. // OversizedSessionId causes the session id that is sent with a ticket
  467. // resumption attempt to be too large (33 bytes).
  468. OversizedSessionId bool
  469. // RequireExtendedMasterSecret, if true, requires that the peer support
  470. // the extended master secret option.
  471. RequireExtendedMasterSecret bool
  472. // NoExtendedMasterSecret causes the client and server to behave as if
  473. // they didn't support an extended master secret.
  474. NoExtendedMasterSecret bool
  475. // EmptyRenegotiationInfo causes the renegotiation extension to be
  476. // empty in a renegotiation handshake.
  477. EmptyRenegotiationInfo bool
  478. // BadRenegotiationInfo causes the renegotiation extension value in a
  479. // renegotiation handshake to be incorrect.
  480. BadRenegotiationInfo bool
  481. // NoRenegotiationInfo causes the client to behave as if it
  482. // didn't support the renegotiation info extension.
  483. NoRenegotiationInfo bool
  484. // RequireRenegotiationInfo, if true, causes the client to return an
  485. // error if the server doesn't reply with the renegotiation extension.
  486. RequireRenegotiationInfo bool
  487. // SequenceNumberMapping, if non-nil, is the mapping function to apply
  488. // to the sequence number of outgoing packets. For both TLS and DTLS,
  489. // the two most-significant bytes in the resulting sequence number are
  490. // ignored so that the DTLS epoch cannot be changed.
  491. SequenceNumberMapping func(uint64) uint64
  492. // RSAEphemeralKey, if true, causes the server to send a
  493. // ServerKeyExchange message containing an ephemeral key (as in
  494. // RSA_EXPORT) in the plain RSA key exchange.
  495. RSAEphemeralKey bool
  496. // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
  497. // client offers when negotiating SRTP. MKI support is still missing so
  498. // the peer must still send none.
  499. SRTPMasterKeyIdentifer string
  500. // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
  501. // server sends in the ServerHello instead of the negotiated one.
  502. SendSRTPProtectionProfile uint16
  503. // NoSignatureAndHashes, if true, causes the client to omit the
  504. // signature and hashes extension.
  505. //
  506. // For a server, it will cause an empty list to be sent in the
  507. // CertificateRequest message. None the less, the configured set will
  508. // still be enforced.
  509. NoSignatureAndHashes bool
  510. // NoSupportedCurves, if true, causes the client to omit the
  511. // supported_curves extension.
  512. NoSupportedCurves bool
  513. // RequireSameRenegoClientVersion, if true, causes the server
  514. // to require that all ClientHellos match in offered version
  515. // across a renego.
  516. RequireSameRenegoClientVersion bool
  517. // ExpectInitialRecordVersion, if non-zero, is the expected
  518. // version of the records before the version is determined.
  519. ExpectInitialRecordVersion uint16
  520. // MaxPacketLength, if non-zero, is the maximum acceptable size for a
  521. // packet.
  522. MaxPacketLength int
  523. // SendCipherSuite, if non-zero, is the cipher suite value that the
  524. // server will send in the ServerHello. This does not affect the cipher
  525. // the server believes it has actually negotiated.
  526. SendCipherSuite uint16
  527. // AppDataAfterChangeCipherSpec, if not null, causes application data to
  528. // be sent immediately after ChangeCipherSpec.
  529. AppDataAfterChangeCipherSpec []byte
  530. // AlertAfterChangeCipherSpec, if non-zero, causes an alert to be sent
  531. // immediately after ChangeCipherSpec.
  532. AlertAfterChangeCipherSpec alert
  533. // TimeoutSchedule is the schedule of packet drops and simulated
  534. // timeouts for before each handshake leg from the peer.
  535. TimeoutSchedule []time.Duration
  536. // PacketAdaptor is the packetAdaptor to use to simulate timeouts.
  537. PacketAdaptor *packetAdaptor
  538. // ReorderHandshakeFragments, if true, causes handshake fragments in
  539. // DTLS to overlap and be sent in the wrong order. It also causes
  540. // pre-CCS flights to be sent twice. (Post-CCS flights consist of
  541. // Finished and will trigger a spurious retransmit.)
  542. ReorderHandshakeFragments bool
  543. // MixCompleteMessageWithFragments, if true, causes handshake
  544. // messages in DTLS to redundantly both fragment the message
  545. // and include a copy of the full one.
  546. MixCompleteMessageWithFragments bool
  547. // SendInvalidRecordType, if true, causes a record with an invalid
  548. // content type to be sent immediately following the handshake.
  549. SendInvalidRecordType bool
  550. // WrongCertificateMessageType, if true, causes Certificate message to
  551. // be sent with the wrong message type.
  552. WrongCertificateMessageType bool
  553. // FragmentMessageTypeMismatch, if true, causes all non-initial
  554. // handshake fragments in DTLS to have the wrong message type.
  555. FragmentMessageTypeMismatch bool
  556. // FragmentMessageLengthMismatch, if true, causes all non-initial
  557. // handshake fragments in DTLS to have the wrong message length.
  558. FragmentMessageLengthMismatch bool
  559. // SplitFragments, if non-zero, causes the handshake fragments in DTLS
  560. // to be split across two records. The value of |SplitFragments| is the
  561. // number of bytes in the first fragment.
  562. SplitFragments int
  563. // SendEmptyFragments, if true, causes handshakes to include empty
  564. // fragments in DTLS.
  565. SendEmptyFragments bool
  566. // SendSplitAlert, if true, causes an alert to be sent with the header
  567. // and record body split across multiple packets. The peer should
  568. // discard these packets rather than process it.
  569. SendSplitAlert bool
  570. // FailIfResumeOnRenego, if true, causes renegotiations to fail if the
  571. // client offers a resumption or the server accepts one.
  572. FailIfResumeOnRenego bool
  573. // IgnorePeerCipherPreferences, if true, causes the peer's cipher
  574. // preferences to be ignored.
  575. IgnorePeerCipherPreferences bool
  576. // IgnorePeerSignatureAlgorithmPreferences, if true, causes the peer's
  577. // signature algorithm preferences to be ignored.
  578. IgnorePeerSignatureAlgorithmPreferences bool
  579. // IgnorePeerCurvePreferences, if true, causes the peer's curve
  580. // preferences to be ignored.
  581. IgnorePeerCurvePreferences bool
  582. // BadFinished, if true, causes the Finished hash to be broken.
  583. BadFinished bool
  584. // DHGroupPrime, if not nil, is used to define the (finite field)
  585. // Diffie-Hellman group. The generator used is always two.
  586. DHGroupPrime *big.Int
  587. // PackHandshakeFragments, if true, causes handshake fragments to be
  588. // packed into individual handshake records, up to the specified record
  589. // size.
  590. PackHandshakeFragments int
  591. // PackHandshakeRecords, if true, causes handshake records to be packed
  592. // into individual packets, up to the specified packet size.
  593. PackHandshakeRecords int
  594. // EnableAllCiphersInDTLS, if true, causes RC4 to be enabled in DTLS.
  595. EnableAllCiphersInDTLS bool
  596. // EmptyCertificateList, if true, causes the server to send an empty
  597. // certificate list in the Certificate message.
  598. EmptyCertificateList bool
  599. // ExpectNewTicket, if true, causes the client to abort if it does not
  600. // receive a new ticket.
  601. ExpectNewTicket bool
  602. // RequireClientHelloSize, if not zero, is the required length in bytes
  603. // of the ClientHello /record/. This is checked by the server.
  604. RequireClientHelloSize int
  605. // CustomExtension, if not empty, contains the contents of an extension
  606. // that will be added to client/server hellos.
  607. CustomExtension string
  608. // ExpectedCustomExtension, if not nil, contains the expected contents
  609. // of a custom extension.
  610. ExpectedCustomExtension *string
  611. }
  612. func (c *Config) serverInit() {
  613. if c.SessionTicketsDisabled {
  614. return
  615. }
  616. // If the key has already been set then we have nothing to do.
  617. for _, b := range c.SessionTicketKey {
  618. if b != 0 {
  619. return
  620. }
  621. }
  622. if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  623. c.SessionTicketsDisabled = true
  624. }
  625. }
  626. func (c *Config) rand() io.Reader {
  627. r := c.Rand
  628. if r == nil {
  629. return rand.Reader
  630. }
  631. return r
  632. }
  633. func (c *Config) time() time.Time {
  634. t := c.Time
  635. if t == nil {
  636. t = time.Now
  637. }
  638. return t()
  639. }
  640. func (c *Config) cipherSuites() []uint16 {
  641. s := c.CipherSuites
  642. if s == nil {
  643. s = defaultCipherSuites()
  644. }
  645. return s
  646. }
  647. func (c *Config) minVersion() uint16 {
  648. if c == nil || c.MinVersion == 0 {
  649. return minVersion
  650. }
  651. return c.MinVersion
  652. }
  653. func (c *Config) maxVersion() uint16 {
  654. if c == nil || c.MaxVersion == 0 {
  655. return maxVersion
  656. }
  657. return c.MaxVersion
  658. }
  659. var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
  660. func (c *Config) curvePreferences() []CurveID {
  661. if c == nil || len(c.CurvePreferences) == 0 {
  662. return defaultCurvePreferences
  663. }
  664. return c.CurvePreferences
  665. }
  666. // mutualVersion returns the protocol version to use given the advertised
  667. // version of the peer.
  668. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  669. minVersion := c.minVersion()
  670. maxVersion := c.maxVersion()
  671. if vers < minVersion {
  672. return 0, false
  673. }
  674. if vers > maxVersion {
  675. vers = maxVersion
  676. }
  677. return vers, true
  678. }
  679. // getCertificateForName returns the best certificate for the given name,
  680. // defaulting to the first element of c.Certificates if there are no good
  681. // options.
  682. func (c *Config) getCertificateForName(name string) *Certificate {
  683. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  684. // There's only one choice, so no point doing any work.
  685. return &c.Certificates[0]
  686. }
  687. name = strings.ToLower(name)
  688. for len(name) > 0 && name[len(name)-1] == '.' {
  689. name = name[:len(name)-1]
  690. }
  691. if cert, ok := c.NameToCertificate[name]; ok {
  692. return cert
  693. }
  694. // try replacing labels in the name with wildcards until we get a
  695. // match.
  696. labels := strings.Split(name, ".")
  697. for i := range labels {
  698. labels[i] = "*"
  699. candidate := strings.Join(labels, ".")
  700. if cert, ok := c.NameToCertificate[candidate]; ok {
  701. return cert
  702. }
  703. }
  704. // If nothing matches, return the first certificate.
  705. return &c.Certificates[0]
  706. }
  707. func (c *Config) signatureAndHashesForServer() []signatureAndHash {
  708. if c != nil && c.SignatureAndHashes != nil {
  709. return c.SignatureAndHashes
  710. }
  711. return supportedClientCertSignatureAlgorithms
  712. }
  713. func (c *Config) signatureAndHashesForClient() []signatureAndHash {
  714. if c != nil && c.SignatureAndHashes != nil {
  715. return c.SignatureAndHashes
  716. }
  717. return supportedSKXSignatureAlgorithms
  718. }
  719. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  720. // from the CommonName and SubjectAlternateName fields of each of the leaf
  721. // certificates.
  722. func (c *Config) BuildNameToCertificate() {
  723. c.NameToCertificate = make(map[string]*Certificate)
  724. for i := range c.Certificates {
  725. cert := &c.Certificates[i]
  726. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  727. if err != nil {
  728. continue
  729. }
  730. if len(x509Cert.Subject.CommonName) > 0 {
  731. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  732. }
  733. for _, san := range x509Cert.DNSNames {
  734. c.NameToCertificate[san] = cert
  735. }
  736. }
  737. }
  738. // A Certificate is a chain of one or more certificates, leaf first.
  739. type Certificate struct {
  740. Certificate [][]byte
  741. PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
  742. // OCSPStaple contains an optional OCSP response which will be served
  743. // to clients that request it.
  744. OCSPStaple []byte
  745. // SignedCertificateTimestampList contains an optional encoded
  746. // SignedCertificateTimestampList structure which will be
  747. // served to clients that request it.
  748. SignedCertificateTimestampList []byte
  749. // Leaf is the parsed form of the leaf certificate, which may be
  750. // initialized using x509.ParseCertificate to reduce per-handshake
  751. // processing for TLS clients doing client authentication. If nil, the
  752. // leaf certificate will be parsed as needed.
  753. Leaf *x509.Certificate
  754. }
  755. // A TLS record.
  756. type record struct {
  757. contentType recordType
  758. major, minor uint8
  759. payload []byte
  760. }
  761. type handshakeMessage interface {
  762. marshal() []byte
  763. unmarshal([]byte) bool
  764. }
  765. // lruSessionCache is a client or server session cache implementation
  766. // that uses an LRU caching strategy.
  767. type lruSessionCache struct {
  768. sync.Mutex
  769. m map[string]*list.Element
  770. q *list.List
  771. capacity int
  772. }
  773. type lruSessionCacheEntry struct {
  774. sessionKey string
  775. state interface{}
  776. }
  777. // Put adds the provided (sessionKey, cs) pair to the cache.
  778. func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
  779. c.Lock()
  780. defer c.Unlock()
  781. if elem, ok := c.m[sessionKey]; ok {
  782. entry := elem.Value.(*lruSessionCacheEntry)
  783. entry.state = cs
  784. c.q.MoveToFront(elem)
  785. return
  786. }
  787. if c.q.Len() < c.capacity {
  788. entry := &lruSessionCacheEntry{sessionKey, cs}
  789. c.m[sessionKey] = c.q.PushFront(entry)
  790. return
  791. }
  792. elem := c.q.Back()
  793. entry := elem.Value.(*lruSessionCacheEntry)
  794. delete(c.m, entry.sessionKey)
  795. entry.sessionKey = sessionKey
  796. entry.state = cs
  797. c.q.MoveToFront(elem)
  798. c.m[sessionKey] = elem
  799. }
  800. // Get returns the value associated with a given key. It returns (nil,
  801. // false) if no value is found.
  802. func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
  803. c.Lock()
  804. defer c.Unlock()
  805. if elem, ok := c.m[sessionKey]; ok {
  806. c.q.MoveToFront(elem)
  807. return elem.Value.(*lruSessionCacheEntry).state, true
  808. }
  809. return nil, false
  810. }
  811. // lruClientSessionCache is a ClientSessionCache implementation that
  812. // uses an LRU caching strategy.
  813. type lruClientSessionCache struct {
  814. lruSessionCache
  815. }
  816. func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  817. c.lruSessionCache.Put(sessionKey, cs)
  818. }
  819. func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  820. cs, ok := c.lruSessionCache.Get(sessionKey)
  821. if !ok {
  822. return nil, false
  823. }
  824. return cs.(*ClientSessionState), true
  825. }
  826. // lruServerSessionCache is a ServerSessionCache implementation that
  827. // uses an LRU caching strategy.
  828. type lruServerSessionCache struct {
  829. lruSessionCache
  830. }
  831. func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
  832. c.lruSessionCache.Put(sessionId, session)
  833. }
  834. func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
  835. cs, ok := c.lruSessionCache.Get(sessionId)
  836. if !ok {
  837. return nil, false
  838. }
  839. return cs.(*sessionState), true
  840. }
  841. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  842. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  843. // is used instead.
  844. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  845. const defaultSessionCacheCapacity = 64
  846. if capacity < 1 {
  847. capacity = defaultSessionCacheCapacity
  848. }
  849. return &lruClientSessionCache{
  850. lruSessionCache{
  851. m: make(map[string]*list.Element),
  852. q: list.New(),
  853. capacity: capacity,
  854. },
  855. }
  856. }
  857. // NewLRUServerSessionCache returns a ServerSessionCache with the given
  858. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  859. // is used instead.
  860. func NewLRUServerSessionCache(capacity int) ServerSessionCache {
  861. const defaultSessionCacheCapacity = 64
  862. if capacity < 1 {
  863. capacity = defaultSessionCacheCapacity
  864. }
  865. return &lruServerSessionCache{
  866. lruSessionCache{
  867. m: make(map[string]*list.Element),
  868. q: list.New(),
  869. capacity: capacity,
  870. },
  871. }
  872. }
  873. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  874. type dsaSignature struct {
  875. R, S *big.Int
  876. }
  877. type ecdsaSignature dsaSignature
  878. var emptyConfig Config
  879. func defaultConfig() *Config {
  880. return &emptyConfig
  881. }
  882. var (
  883. once sync.Once
  884. varDefaultCipherSuites []uint16
  885. )
  886. func defaultCipherSuites() []uint16 {
  887. once.Do(initDefaultCipherSuites)
  888. return varDefaultCipherSuites
  889. }
  890. func initDefaultCipherSuites() {
  891. for _, suite := range cipherSuites {
  892. if suite.flags&suitePSK == 0 {
  893. varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  894. }
  895. }
  896. }
  897. func unexpectedMessageError(wanted, got interface{}) error {
  898. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  899. }
  900. func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
  901. for _, s := range sigHashes {
  902. if s == sigHash {
  903. return true
  904. }
  905. }
  906. return false
  907. }