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

common.go 30 KiB

Add DTLS timeout and retransmit tests. This extends the packet adaptor protocol to send three commands: type command = | Packet of []byte | Timeout of time.Duration | TimeoutAck When the shim processes a Timeout in BIO_read, it sends TimeoutAck, fails the BIO_read, returns out of the SSL stack, advances the clock, calls DTLSv1_handle_timeout, and continues. If the Go side sends Timeout right between sending handshake flight N and reading flight N+1, the shim won't read the Timeout until it has sent flight N+1 (it only processes packet commands in BIO_read), so the TimeoutAck comes after N+1. Go then drops all packets before the TimeoutAck, thus dropping one transmit of flight N+1 without having to actually process the packets to determine the end of the flight. The shim then sees the updated clock, calls DTLSv1_handle_timeout, and re-sends flight N+1 for Go to process for real. When dropping packets, Go checks the epoch and increments sequence numbers so that we can continue to be strict here. This requires tracking the initial sequence number of the next epoch. The final Finished message takes an additional special-case to test. DTLS triggers retransmits on either a timeout or seeing a stale flight. OpenSSL only implements the former which should be sufficient (and is necessary) EXCEPT for the final Finished message. If the peer's final Finished message is lost, it won't be waiting for a message from us, so it won't time out anything. That retransmit must be triggered on stale message, so we retransmit the Finished message in Go. Change-Id: I3ffbdb1de525beb2ee831b304670a3387877634c Reviewed-on: https://boringssl-review.googlesource.com/3212 Reviewed-by: Adam Langley <agl@google.com>
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  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. extensionNextProtoNeg uint16 = 13172 // not IANA assigned
  76. extensionRenegotiationInfo uint16 = 0xff01
  77. extensionChannelID uint16 = 30032 // not IANA assigned
  78. )
  79. // TLS signaling cipher suite values
  80. const (
  81. scsvRenegotiation uint16 = 0x00ff
  82. )
  83. // CurveID is the type of a TLS identifier for an elliptic curve. See
  84. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
  85. type CurveID uint16
  86. const (
  87. CurveP256 CurveID = 23
  88. CurveP384 CurveID = 24
  89. CurveP521 CurveID = 25
  90. )
  91. // TLS Elliptic Curve Point Formats
  92. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
  93. const (
  94. pointFormatUncompressed uint8 = 0
  95. )
  96. // TLS CertificateStatusType (RFC 3546)
  97. const (
  98. statusTypeOCSP uint8 = 1
  99. )
  100. // Certificate types (for certificateRequestMsg)
  101. const (
  102. CertTypeRSASign = 1 // A certificate containing an RSA key
  103. CertTypeDSSSign = 2 // A certificate containing a DSA key
  104. CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
  105. CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
  106. // See RFC4492 sections 3 and 5.5.
  107. CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
  108. CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
  109. CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
  110. // Rest of these are reserved by the TLS spec
  111. )
  112. // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
  113. const (
  114. hashMD5 uint8 = 1
  115. hashSHA1 uint8 = 2
  116. hashSHA224 uint8 = 3
  117. hashSHA256 uint8 = 4
  118. hashSHA384 uint8 = 5
  119. hashSHA512 uint8 = 6
  120. )
  121. // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
  122. const (
  123. signatureRSA uint8 = 1
  124. signatureECDSA uint8 = 3
  125. )
  126. // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
  127. // RFC 5246, section A.4.1.
  128. type signatureAndHash struct {
  129. signature, hash uint8
  130. }
  131. // supportedSKXSignatureAlgorithms contains the signature and hash algorithms
  132. // that the code advertises as supported in a TLS 1.2 ClientHello.
  133. var supportedSKXSignatureAlgorithms = []signatureAndHash{
  134. {signatureRSA, hashSHA256},
  135. {signatureECDSA, hashSHA256},
  136. {signatureRSA, hashSHA1},
  137. {signatureECDSA, hashSHA1},
  138. }
  139. // supportedClientCertSignatureAlgorithms contains the signature and hash
  140. // algorithms that the code advertises as supported in a TLS 1.2
  141. // CertificateRequest.
  142. var supportedClientCertSignatureAlgorithms = []signatureAndHash{
  143. {signatureRSA, hashSHA256},
  144. {signatureECDSA, hashSHA256},
  145. }
  146. // SRTP protection profiles (See RFC 5764, section 4.1.2)
  147. const (
  148. SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001
  149. SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002
  150. )
  151. // ConnectionState records basic TLS details about the connection.
  152. type ConnectionState struct {
  153. Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
  154. HandshakeComplete bool // TLS handshake is complete
  155. DidResume bool // connection resumes a previous TLS connection
  156. CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
  157. NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
  158. NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
  159. NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
  160. ServerName string // server name requested by client, if any (server side only)
  161. PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
  162. VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
  163. ChannelID *ecdsa.PublicKey // the channel ID for this connection
  164. SRTPProtectionProfile uint16 // the negotiated DTLS-SRTP protection profile
  165. }
  166. // ClientAuthType declares the policy the server will follow for
  167. // TLS Client Authentication.
  168. type ClientAuthType int
  169. const (
  170. NoClientCert ClientAuthType = iota
  171. RequestClientCert
  172. RequireAnyClientCert
  173. VerifyClientCertIfGiven
  174. RequireAndVerifyClientCert
  175. )
  176. // ClientSessionState contains the state needed by clients to resume TLS
  177. // sessions.
  178. type ClientSessionState struct {
  179. sessionId []uint8 // Session ID supplied by the server. nil if the session has a ticket.
  180. sessionTicket []uint8 // Encrypted ticket used for session resumption with server
  181. vers uint16 // SSL/TLS version negotiated for the session
  182. cipherSuite uint16 // Ciphersuite negotiated for the session
  183. masterSecret []byte // MasterSecret generated by client on a full handshake
  184. handshakeHash []byte // Handshake hash for Channel ID purposes.
  185. serverCertificates []*x509.Certificate // Certificate chain presented by the server
  186. extendedMasterSecret bool // Whether an extended master secret was used to generate the session
  187. }
  188. // ClientSessionCache is a cache of ClientSessionState objects that can be used
  189. // by a client to resume a TLS session with a given server. ClientSessionCache
  190. // implementations should expect to be called concurrently from different
  191. // goroutines.
  192. type ClientSessionCache interface {
  193. // Get searches for a ClientSessionState associated with the given key.
  194. // On return, ok is true if one was found.
  195. Get(sessionKey string) (session *ClientSessionState, ok bool)
  196. // Put adds the ClientSessionState to the cache with the given key.
  197. Put(sessionKey string, cs *ClientSessionState)
  198. }
  199. // ServerSessionCache is a cache of sessionState objects that can be used by a
  200. // client to resume a TLS session with a given server. ServerSessionCache
  201. // implementations should expect to be called concurrently from different
  202. // goroutines.
  203. type ServerSessionCache interface {
  204. // Get searches for a sessionState associated with the given session
  205. // ID. On return, ok is true if one was found.
  206. Get(sessionId string) (session *sessionState, ok bool)
  207. // Put adds the sessionState to the cache with the given session ID.
  208. Put(sessionId string, session *sessionState)
  209. }
  210. // A Config structure is used to configure a TLS client or server.
  211. // After one has been passed to a TLS function it must not be
  212. // modified. A Config may be reused; the tls package will also not
  213. // modify it.
  214. type Config struct {
  215. // Rand provides the source of entropy for nonces and RSA blinding.
  216. // If Rand is nil, TLS uses the cryptographic random reader in package
  217. // crypto/rand.
  218. // The Reader must be safe for use by multiple goroutines.
  219. Rand io.Reader
  220. // Time returns the current time as the number of seconds since the epoch.
  221. // If Time is nil, TLS uses time.Now.
  222. Time func() time.Time
  223. // Certificates contains one or more certificate chains
  224. // to present to the other side of the connection.
  225. // Server configurations must include at least one certificate.
  226. Certificates []Certificate
  227. // NameToCertificate maps from a certificate name to an element of
  228. // Certificates. Note that a certificate name can be of the form
  229. // '*.example.com' and so doesn't have to be a domain name as such.
  230. // See Config.BuildNameToCertificate
  231. // The nil value causes the first element of Certificates to be used
  232. // for all connections.
  233. NameToCertificate map[string]*Certificate
  234. // RootCAs defines the set of root certificate authorities
  235. // that clients use when verifying server certificates.
  236. // If RootCAs is nil, TLS uses the host's root CA set.
  237. RootCAs *x509.CertPool
  238. // NextProtos is a list of supported, application level protocols.
  239. NextProtos []string
  240. // ServerName is used to verify the hostname on the returned
  241. // certificates unless InsecureSkipVerify is given. It is also included
  242. // in the client's handshake to support virtual hosting.
  243. ServerName string
  244. // ClientAuth determines the server's policy for
  245. // TLS Client Authentication. The default is NoClientCert.
  246. ClientAuth ClientAuthType
  247. // ClientCAs defines the set of root certificate authorities
  248. // that servers use if required to verify a client certificate
  249. // by the policy in ClientAuth.
  250. ClientCAs *x509.CertPool
  251. // ClientCertificateTypes defines the set of allowed client certificate
  252. // types. The default is CertTypeRSASign and CertTypeECDSASign.
  253. ClientCertificateTypes []byte
  254. // InsecureSkipVerify controls whether a client verifies the
  255. // server's certificate chain and host name.
  256. // If InsecureSkipVerify is true, TLS accepts any certificate
  257. // presented by the server and any host name in that certificate.
  258. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  259. // This should be used only for testing.
  260. InsecureSkipVerify bool
  261. // CipherSuites is a list of supported cipher suites. If CipherSuites
  262. // is nil, TLS uses a list of suites supported by the implementation.
  263. CipherSuites []uint16
  264. // PreferServerCipherSuites controls whether the server selects the
  265. // client's most preferred ciphersuite, or the server's most preferred
  266. // ciphersuite. If true then the server's preference, as expressed in
  267. // the order of elements in CipherSuites, is used.
  268. PreferServerCipherSuites bool
  269. // SessionTicketsDisabled may be set to true to disable session ticket
  270. // (resumption) support.
  271. SessionTicketsDisabled bool
  272. // SessionTicketKey is used by TLS servers to provide session
  273. // resumption. See RFC 5077. If zero, it will be filled with
  274. // random data before the first server handshake.
  275. //
  276. // If multiple servers are terminating connections for the same host
  277. // they should all have the same SessionTicketKey. If the
  278. // SessionTicketKey leaks, previously recorded and future TLS
  279. // connections using that key are compromised.
  280. SessionTicketKey [32]byte
  281. // ClientSessionCache is a cache of ClientSessionState entries
  282. // for TLS session resumption.
  283. ClientSessionCache ClientSessionCache
  284. // ServerSessionCache is a cache of sessionState entries for TLS session
  285. // resumption.
  286. ServerSessionCache ServerSessionCache
  287. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  288. // If zero, then SSLv3 is taken as the minimum.
  289. MinVersion uint16
  290. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  291. // If zero, then the maximum version supported by this package is used,
  292. // which is currently TLS 1.2.
  293. MaxVersion uint16
  294. // CurvePreferences contains the elliptic curves that will be used in
  295. // an ECDHE handshake, in preference order. If empty, the default will
  296. // be used.
  297. CurvePreferences []CurveID
  298. // ChannelID contains the ECDSA key for the client to use as
  299. // its TLS Channel ID.
  300. ChannelID *ecdsa.PrivateKey
  301. // RequestChannelID controls whether the server requests a TLS
  302. // Channel ID. If negotiated, the client's public key is
  303. // returned in the ConnectionState.
  304. RequestChannelID bool
  305. // PreSharedKey, if not nil, is the pre-shared key to use with
  306. // the PSK cipher suites.
  307. PreSharedKey []byte
  308. // PreSharedKeyIdentity, if not empty, is the identity to use
  309. // with the PSK cipher suites.
  310. PreSharedKeyIdentity string
  311. // SRTPProtectionProfiles, if not nil, is the list of SRTP
  312. // protection profiles to offer in DTLS-SRTP.
  313. SRTPProtectionProfiles []uint16
  314. // SignatureAndHashes, if not nil, overrides the default set of
  315. // supported signature and hash algorithms to advertise in
  316. // CertificateRequest.
  317. SignatureAndHashes []signatureAndHash
  318. // Bugs specifies optional misbehaviour to be used for testing other
  319. // implementations.
  320. Bugs ProtocolBugs
  321. serverInitOnce sync.Once // guards calling (*Config).serverInit
  322. }
  323. type BadValue int
  324. const (
  325. BadValueNone BadValue = iota
  326. BadValueNegative
  327. BadValueZero
  328. BadValueLimit
  329. BadValueLarge
  330. NumBadValues
  331. )
  332. type ProtocolBugs struct {
  333. // InvalidSKXSignature specifies that the signature in a
  334. // ServerKeyExchange message should be invalid.
  335. InvalidSKXSignature bool
  336. // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
  337. // to be wrong.
  338. InvalidSKXCurve bool
  339. // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
  340. // can be invalid.
  341. BadECDSAR BadValue
  342. BadECDSAS BadValue
  343. // MaxPadding causes CBC records to have the maximum possible padding.
  344. MaxPadding bool
  345. // PaddingFirstByteBad causes the first byte of the padding to be
  346. // incorrect.
  347. PaddingFirstByteBad bool
  348. // PaddingFirstByteBadIf255 causes the first byte of padding to be
  349. // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
  350. PaddingFirstByteBadIf255 bool
  351. // FailIfNotFallbackSCSV causes a server handshake to fail if the
  352. // client doesn't send the fallback SCSV value.
  353. FailIfNotFallbackSCSV bool
  354. // DuplicateExtension causes an extra empty extension of bogus type to
  355. // be emitted in either the ClientHello or the ServerHello.
  356. DuplicateExtension bool
  357. // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
  358. // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
  359. // Certificate message is sent and no signature is added to
  360. // ServerKeyExchange.
  361. UnauthenticatedECDH bool
  362. // SkipServerKeyExchange causes the server to skip sending
  363. // ServerKeyExchange messages.
  364. SkipServerKeyExchange bool
  365. // SkipChangeCipherSpec causes the implementation to skip
  366. // sending the ChangeCipherSpec message (and adjusting cipher
  367. // state accordingly for the Finished message).
  368. SkipChangeCipherSpec bool
  369. // EarlyChangeCipherSpec causes the client to send an early
  370. // ChangeCipherSpec message before the ClientKeyExchange. A value of
  371. // zero disables this behavior. One and two configure variants for 0.9.8
  372. // and 1.0.1 modes, respectively.
  373. EarlyChangeCipherSpec int
  374. // FragmentAcrossChangeCipherSpec causes the implementation to fragment
  375. // the Finished (or NextProto) message around the ChangeCipherSpec
  376. // messages.
  377. FragmentAcrossChangeCipherSpec bool
  378. // SkipNewSessionTicket causes the server to skip sending the
  379. // NewSessionTicket message despite promising to in ServerHello.
  380. SkipNewSessionTicket bool
  381. // SendV2ClientHello causes the client to send a V2ClientHello
  382. // instead of a normal ClientHello.
  383. SendV2ClientHello bool
  384. // SendFallbackSCSV causes the client to include
  385. // TLS_FALLBACK_SCSV in the ClientHello.
  386. SendFallbackSCSV bool
  387. // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
  388. // handshake record. Handshake messages will be split into multiple
  389. // records at the specified size, except that the client_version will
  390. // never be fragmented.
  391. MaxHandshakeRecordLength int
  392. // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
  393. // the first 6 bytes of the ClientHello.
  394. FragmentClientVersion bool
  395. // FragmentAlert will cause all alerts to be fragmented across
  396. // two records.
  397. FragmentAlert bool
  398. // SendSpuriousAlert will cause an spurious, unwanted alert to be sent.
  399. SendSpuriousAlert bool
  400. // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
  401. // ClientKeyExchange with the specified version rather than the
  402. // client_version when performing the RSA key exchange.
  403. RsaClientKeyExchangeVersion uint16
  404. // RenewTicketOnResume causes the server to renew the session ticket and
  405. // send a NewSessionTicket message during an abbreviated handshake.
  406. RenewTicketOnResume bool
  407. // SendClientVersion, if non-zero, causes the client to send a different
  408. // TLS version in the ClientHello than the maximum supported version.
  409. SendClientVersion uint16
  410. // SkipHelloVerifyRequest causes a DTLS server to skip the
  411. // HelloVerifyRequest message.
  412. SkipHelloVerifyRequest bool
  413. // ExpectFalseStart causes the server to, on full handshakes,
  414. // expect the peer to False Start; the server Finished message
  415. // isn't sent until we receive an application data record
  416. // from the peer.
  417. ExpectFalseStart bool
  418. // SSL3RSAKeyExchange causes the client to always send an RSA
  419. // ClientKeyExchange message without the two-byte length
  420. // prefix, as if it were SSL3.
  421. SSL3RSAKeyExchange bool
  422. // SkipCipherVersionCheck causes the server to negotiate
  423. // TLS 1.2 ciphers in earlier versions of TLS.
  424. SkipCipherVersionCheck bool
  425. // ExpectServerName, if not empty, is the hostname the client
  426. // must specify in the server_name extension.
  427. ExpectServerName string
  428. // SwapNPNAndALPN switches the relative order between NPN and
  429. // ALPN on the server. This is to test that server preference
  430. // of ALPN works regardless of their relative order.
  431. SwapNPNAndALPN bool
  432. // AllowSessionVersionMismatch causes the server to resume sessions
  433. // regardless of the version associated with the session.
  434. AllowSessionVersionMismatch bool
  435. // CorruptTicket causes a client to corrupt a session ticket before
  436. // sending it in a resume handshake.
  437. CorruptTicket bool
  438. // OversizedSessionId causes the session id that is sent with a ticket
  439. // resumption attempt to be too large (33 bytes).
  440. OversizedSessionId bool
  441. // RequireExtendedMasterSecret, if true, requires that the peer support
  442. // the extended master secret option.
  443. RequireExtendedMasterSecret bool
  444. // NoExtendedMasterSecret causes the client and server to behave as if
  445. // they didn't support an extended master secret.
  446. NoExtendedMasterSecret bool
  447. // EmptyRenegotiationInfo causes the renegotiation extension to be
  448. // empty in a renegotiation handshake.
  449. EmptyRenegotiationInfo bool
  450. // BadRenegotiationInfo causes the renegotiation extension value in a
  451. // renegotiation handshake to be incorrect.
  452. BadRenegotiationInfo bool
  453. // NoRenegotiationInfo causes the client to behave as if it
  454. // didn't support the renegotiation info extension.
  455. NoRenegotiationInfo bool
  456. // SequenceNumberIncrement, if non-zero, causes outgoing sequence
  457. // numbers in DTLS to increment by that value rather by 1. This is to
  458. // stress the replay bitmap window by simulating extreme packet loss and
  459. // retransmit at the record layer.
  460. SequenceNumberIncrement uint64
  461. // RSAServerKeyExchange, if true, causes the server to send a
  462. // ServerKeyExchange message in the plain RSA key exchange.
  463. RSAServerKeyExchange bool
  464. // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
  465. // client offers when negotiating SRTP. MKI support is still missing so
  466. // the peer must still send none.
  467. SRTPMasterKeyIdentifer string
  468. // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
  469. // server sends in the ServerHello instead of the negotiated one.
  470. SendSRTPProtectionProfile uint16
  471. // NoSignatureAndHashes, if true, causes the client to omit the
  472. // signature and hashes extension.
  473. //
  474. // For a server, it will cause an empty list to be sent in the
  475. // CertificateRequest message. None the less, the configured set will
  476. // still be enforced.
  477. NoSignatureAndHashes bool
  478. // RequireSameRenegoClientVersion, if true, causes the server
  479. // to require that all ClientHellos match in offered version
  480. // across a renego.
  481. RequireSameRenegoClientVersion bool
  482. // RequireFastradioPadding, if true, requires that ClientHello messages
  483. // be at least 1000 bytes long.
  484. RequireFastradioPadding bool
  485. // ExpectInitialRecordVersion, if non-zero, is the expected
  486. // version of the records before the version is determined.
  487. ExpectInitialRecordVersion uint16
  488. // MaxPacketLength, if non-zero, is the maximum acceptable size for a
  489. // packet.
  490. MaxPacketLength int
  491. // SendCipherSuite, if non-zero, is the cipher suite value that the
  492. // server will send in the ServerHello. This does not affect the cipher
  493. // the server believes it has actually negotiated.
  494. SendCipherSuite uint16
  495. // AppDataAfterChangeCipherSpec, if not null, causes application data to
  496. // be sent immediately after ChangeCipherSpec.
  497. AppDataAfterChangeCipherSpec []byte
  498. // TimeoutSchedule is the schedule of packet drops and simulated
  499. // timeouts for before each handshake leg from the peer.
  500. TimeoutSchedule []time.Duration
  501. // PacketAdaptor is the packetAdaptor to use to simulate timeouts.
  502. PacketAdaptor *packetAdaptor
  503. }
  504. func (c *Config) serverInit() {
  505. if c.SessionTicketsDisabled {
  506. return
  507. }
  508. // If the key has already been set then we have nothing to do.
  509. for _, b := range c.SessionTicketKey {
  510. if b != 0 {
  511. return
  512. }
  513. }
  514. if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  515. c.SessionTicketsDisabled = true
  516. }
  517. }
  518. func (c *Config) rand() io.Reader {
  519. r := c.Rand
  520. if r == nil {
  521. return rand.Reader
  522. }
  523. return r
  524. }
  525. func (c *Config) time() time.Time {
  526. t := c.Time
  527. if t == nil {
  528. t = time.Now
  529. }
  530. return t()
  531. }
  532. func (c *Config) cipherSuites() []uint16 {
  533. s := c.CipherSuites
  534. if s == nil {
  535. s = defaultCipherSuites()
  536. }
  537. return s
  538. }
  539. func (c *Config) minVersion() uint16 {
  540. if c == nil || c.MinVersion == 0 {
  541. return minVersion
  542. }
  543. return c.MinVersion
  544. }
  545. func (c *Config) maxVersion() uint16 {
  546. if c == nil || c.MaxVersion == 0 {
  547. return maxVersion
  548. }
  549. return c.MaxVersion
  550. }
  551. var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
  552. func (c *Config) curvePreferences() []CurveID {
  553. if c == nil || len(c.CurvePreferences) == 0 {
  554. return defaultCurvePreferences
  555. }
  556. return c.CurvePreferences
  557. }
  558. // mutualVersion returns the protocol version to use given the advertised
  559. // version of the peer.
  560. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  561. minVersion := c.minVersion()
  562. maxVersion := c.maxVersion()
  563. if vers < minVersion {
  564. return 0, false
  565. }
  566. if vers > maxVersion {
  567. vers = maxVersion
  568. }
  569. return vers, true
  570. }
  571. // getCertificateForName returns the best certificate for the given name,
  572. // defaulting to the first element of c.Certificates if there are no good
  573. // options.
  574. func (c *Config) getCertificateForName(name string) *Certificate {
  575. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  576. // There's only one choice, so no point doing any work.
  577. return &c.Certificates[0]
  578. }
  579. name = strings.ToLower(name)
  580. for len(name) > 0 && name[len(name)-1] == '.' {
  581. name = name[:len(name)-1]
  582. }
  583. if cert, ok := c.NameToCertificate[name]; ok {
  584. return cert
  585. }
  586. // try replacing labels in the name with wildcards until we get a
  587. // match.
  588. labels := strings.Split(name, ".")
  589. for i := range labels {
  590. labels[i] = "*"
  591. candidate := strings.Join(labels, ".")
  592. if cert, ok := c.NameToCertificate[candidate]; ok {
  593. return cert
  594. }
  595. }
  596. // If nothing matches, return the first certificate.
  597. return &c.Certificates[0]
  598. }
  599. func (c *Config) signatureAndHashesForServer() []signatureAndHash {
  600. if c != nil && c.SignatureAndHashes != nil {
  601. return c.SignatureAndHashes
  602. }
  603. return supportedClientCertSignatureAlgorithms
  604. }
  605. func (c *Config) signatureAndHashesForClient() []signatureAndHash {
  606. if c != nil && c.SignatureAndHashes != nil {
  607. return c.SignatureAndHashes
  608. }
  609. return supportedSKXSignatureAlgorithms
  610. }
  611. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  612. // from the CommonName and SubjectAlternateName fields of each of the leaf
  613. // certificates.
  614. func (c *Config) BuildNameToCertificate() {
  615. c.NameToCertificate = make(map[string]*Certificate)
  616. for i := range c.Certificates {
  617. cert := &c.Certificates[i]
  618. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  619. if err != nil {
  620. continue
  621. }
  622. if len(x509Cert.Subject.CommonName) > 0 {
  623. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  624. }
  625. for _, san := range x509Cert.DNSNames {
  626. c.NameToCertificate[san] = cert
  627. }
  628. }
  629. }
  630. // A Certificate is a chain of one or more certificates, leaf first.
  631. type Certificate struct {
  632. Certificate [][]byte
  633. PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
  634. // OCSPStaple contains an optional OCSP response which will be served
  635. // to clients that request it.
  636. OCSPStaple []byte
  637. // SignedCertificateTimestampList contains an optional encoded
  638. // SignedCertificateTimestampList structure which will be
  639. // served to clients that request it.
  640. SignedCertificateTimestampList []byte
  641. // Leaf is the parsed form of the leaf certificate, which may be
  642. // initialized using x509.ParseCertificate to reduce per-handshake
  643. // processing for TLS clients doing client authentication. If nil, the
  644. // leaf certificate will be parsed as needed.
  645. Leaf *x509.Certificate
  646. }
  647. // A TLS record.
  648. type record struct {
  649. contentType recordType
  650. major, minor uint8
  651. payload []byte
  652. }
  653. type handshakeMessage interface {
  654. marshal() []byte
  655. unmarshal([]byte) bool
  656. }
  657. // lruSessionCache is a client or server session cache implementation
  658. // that uses an LRU caching strategy.
  659. type lruSessionCache struct {
  660. sync.Mutex
  661. m map[string]*list.Element
  662. q *list.List
  663. capacity int
  664. }
  665. type lruSessionCacheEntry struct {
  666. sessionKey string
  667. state interface{}
  668. }
  669. // Put adds the provided (sessionKey, cs) pair to the cache.
  670. func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
  671. c.Lock()
  672. defer c.Unlock()
  673. if elem, ok := c.m[sessionKey]; ok {
  674. entry := elem.Value.(*lruSessionCacheEntry)
  675. entry.state = cs
  676. c.q.MoveToFront(elem)
  677. return
  678. }
  679. if c.q.Len() < c.capacity {
  680. entry := &lruSessionCacheEntry{sessionKey, cs}
  681. c.m[sessionKey] = c.q.PushFront(entry)
  682. return
  683. }
  684. elem := c.q.Back()
  685. entry := elem.Value.(*lruSessionCacheEntry)
  686. delete(c.m, entry.sessionKey)
  687. entry.sessionKey = sessionKey
  688. entry.state = cs
  689. c.q.MoveToFront(elem)
  690. c.m[sessionKey] = elem
  691. }
  692. // Get returns the value associated with a given key. It returns (nil,
  693. // false) if no value is found.
  694. func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
  695. c.Lock()
  696. defer c.Unlock()
  697. if elem, ok := c.m[sessionKey]; ok {
  698. c.q.MoveToFront(elem)
  699. return elem.Value.(*lruSessionCacheEntry).state, true
  700. }
  701. return nil, false
  702. }
  703. // lruClientSessionCache is a ClientSessionCache implementation that
  704. // uses an LRU caching strategy.
  705. type lruClientSessionCache struct {
  706. lruSessionCache
  707. }
  708. func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  709. c.lruSessionCache.Put(sessionKey, cs)
  710. }
  711. func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  712. cs, ok := c.lruSessionCache.Get(sessionKey)
  713. if !ok {
  714. return nil, false
  715. }
  716. return cs.(*ClientSessionState), true
  717. }
  718. // lruServerSessionCache is a ServerSessionCache implementation that
  719. // uses an LRU caching strategy.
  720. type lruServerSessionCache struct {
  721. lruSessionCache
  722. }
  723. func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
  724. c.lruSessionCache.Put(sessionId, session)
  725. }
  726. func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
  727. cs, ok := c.lruSessionCache.Get(sessionId)
  728. if !ok {
  729. return nil, false
  730. }
  731. return cs.(*sessionState), true
  732. }
  733. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  734. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  735. // is used instead.
  736. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  737. const defaultSessionCacheCapacity = 64
  738. if capacity < 1 {
  739. capacity = defaultSessionCacheCapacity
  740. }
  741. return &lruClientSessionCache{
  742. lruSessionCache{
  743. m: make(map[string]*list.Element),
  744. q: list.New(),
  745. capacity: capacity,
  746. },
  747. }
  748. }
  749. // NewLRUServerSessionCache returns a ServerSessionCache with the given
  750. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  751. // is used instead.
  752. func NewLRUServerSessionCache(capacity int) ServerSessionCache {
  753. const defaultSessionCacheCapacity = 64
  754. if capacity < 1 {
  755. capacity = defaultSessionCacheCapacity
  756. }
  757. return &lruServerSessionCache{
  758. lruSessionCache{
  759. m: make(map[string]*list.Element),
  760. q: list.New(),
  761. capacity: capacity,
  762. },
  763. }
  764. }
  765. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  766. type dsaSignature struct {
  767. R, S *big.Int
  768. }
  769. type ecdsaSignature dsaSignature
  770. var emptyConfig Config
  771. func defaultConfig() *Config {
  772. return &emptyConfig
  773. }
  774. var (
  775. once sync.Once
  776. varDefaultCipherSuites []uint16
  777. )
  778. func defaultCipherSuites() []uint16 {
  779. once.Do(initDefaultCipherSuites)
  780. return varDefaultCipherSuites
  781. }
  782. func initDefaultCipherSuites() {
  783. for _, suite := range cipherSuites {
  784. if suite.flags&suitePSK == 0 {
  785. varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  786. }
  787. }
  788. }
  789. func unexpectedMessageError(wanted, got interface{}) error {
  790. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  791. }
  792. func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
  793. for _, s := range sigHashes {
  794. if s == sigHash {
  795. return true
  796. }
  797. }
  798. return false
  799. }