Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

623 řádky
19 KiB

  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tls
  5. import (
  6. "container/list"
  7. "crypto"
  8. "crypto/rand"
  9. "crypto/x509"
  10. "fmt"
  11. "io"
  12. "math/big"
  13. "strings"
  14. "sync"
  15. "time"
  16. )
  17. const (
  18. VersionSSL30 = 0x0300
  19. VersionTLS10 = 0x0301
  20. VersionTLS11 = 0x0302
  21. VersionTLS12 = 0x0303
  22. )
  23. const (
  24. maxPlaintext = 16384 // maximum plaintext payload length
  25. maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
  26. recordHeaderLen = 5 // record header length
  27. maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
  28. minVersion = VersionTLS10
  29. maxVersion = VersionTLS12
  30. )
  31. // TLS record types.
  32. type recordType uint8
  33. const (
  34. recordTypeChangeCipherSpec recordType = 20
  35. recordTypeAlert recordType = 21
  36. recordTypeHandshake recordType = 22
  37. recordTypeApplicationData recordType = 23
  38. )
  39. // TLS handshake message types.
  40. const (
  41. typeClientHello uint8 = 1
  42. typeServerHello uint8 = 2
  43. typeNewSessionTicket uint8 = 4
  44. typeCertificate uint8 = 11
  45. typeServerKeyExchange uint8 = 12
  46. typeCertificateRequest uint8 = 13
  47. typeServerHelloDone uint8 = 14
  48. typeCertificateVerify uint8 = 15
  49. typeClientKeyExchange uint8 = 16
  50. typeFinished uint8 = 20
  51. typeCertificateStatus uint8 = 22
  52. typeNextProtocol uint8 = 67 // Not IANA assigned
  53. )
  54. // TLS compression types.
  55. const (
  56. compressionNone uint8 = 0
  57. )
  58. // TLS extension numbers
  59. const (
  60. extensionServerName uint16 = 0
  61. extensionStatusRequest uint16 = 5
  62. extensionSupportedCurves uint16 = 10
  63. extensionSupportedPoints uint16 = 11
  64. extensionSignatureAlgorithms uint16 = 13
  65. extensionALPN uint16 = 16
  66. extensionSessionTicket uint16 = 35
  67. extensionNextProtoNeg uint16 = 13172 // not IANA assigned
  68. extensionRenegotiationInfo uint16 = 0xff01
  69. )
  70. // TLS signaling cipher suite values
  71. const (
  72. scsvRenegotiation uint16 = 0x00ff
  73. )
  74. // CurveID is the type of a TLS identifier for an elliptic curve. See
  75. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
  76. type CurveID uint16
  77. const (
  78. CurveP256 CurveID = 23
  79. CurveP384 CurveID = 24
  80. CurveP521 CurveID = 25
  81. )
  82. // TLS Elliptic Curve Point Formats
  83. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
  84. const (
  85. pointFormatUncompressed uint8 = 0
  86. )
  87. // TLS CertificateStatusType (RFC 3546)
  88. const (
  89. statusTypeOCSP uint8 = 1
  90. )
  91. // Certificate types (for certificateRequestMsg)
  92. const (
  93. certTypeRSASign = 1 // A certificate containing an RSA key
  94. certTypeDSSSign = 2 // A certificate containing a DSA key
  95. certTypeRSAFixedDH = 3 // A certificate containing a static DH key
  96. certTypeDSSFixedDH = 4 // A certificate containing a static DH key
  97. // See RFC4492 sections 3 and 5.5.
  98. certTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
  99. certTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
  100. certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
  101. // Rest of these are reserved by the TLS spec
  102. )
  103. // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
  104. const (
  105. hashSHA1 uint8 = 2
  106. hashSHA256 uint8 = 4
  107. hashSHA384 uint8 = 5
  108. )
  109. // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
  110. const (
  111. signatureRSA uint8 = 1
  112. signatureECDSA uint8 = 3
  113. )
  114. // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
  115. // RFC 5246, section A.4.1.
  116. type signatureAndHash struct {
  117. hash, signature uint8
  118. }
  119. // supportedSKXSignatureAlgorithms contains the signature and hash algorithms
  120. // that the code advertises as supported in a TLS 1.2 ClientHello.
  121. var supportedSKXSignatureAlgorithms = []signatureAndHash{
  122. {hashSHA256, signatureRSA},
  123. {hashSHA256, signatureECDSA},
  124. {hashSHA1, signatureRSA},
  125. {hashSHA1, signatureECDSA},
  126. }
  127. // supportedClientCertSignatureAlgorithms contains the signature and hash
  128. // algorithms that the code advertises as supported in a TLS 1.2
  129. // CertificateRequest.
  130. var supportedClientCertSignatureAlgorithms = []signatureAndHash{
  131. {hashSHA256, signatureRSA},
  132. {hashSHA256, signatureECDSA},
  133. }
  134. // ConnectionState records basic TLS details about the connection.
  135. type ConnectionState struct {
  136. Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
  137. HandshakeComplete bool // TLS handshake is complete
  138. DidResume bool // connection resumes a previous TLS connection
  139. CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
  140. NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
  141. NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
  142. ServerName string // server name requested by client, if any (server side only)
  143. PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
  144. VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
  145. // TLSUnique contains the "tls-unique" channel binding value (see RFC
  146. // 5929, section 3). For resumed sessions this value will be nil
  147. // because resumption does not include enough context (see
  148. // https://secure-resumption.com/#channelbindings). This will change in
  149. // future versions of Go once the TLS master-secret fix has been
  150. // standardized and implemented.
  151. TLSUnique []byte
  152. }
  153. // ClientAuthType declares the policy the server will follow for
  154. // TLS Client Authentication.
  155. type ClientAuthType int
  156. const (
  157. NoClientCert ClientAuthType = iota
  158. RequestClientCert
  159. RequireAnyClientCert
  160. VerifyClientCertIfGiven
  161. RequireAndVerifyClientCert
  162. )
  163. // ClientSessionState contains the state needed by clients to resume TLS
  164. // sessions.
  165. type ClientSessionState struct {
  166. sessionTicket []uint8 // Encrypted ticket used for session resumption with server
  167. vers uint16 // SSL/TLS version negotiated for the session
  168. cipherSuite uint16 // Ciphersuite negotiated for the session
  169. masterSecret []byte // MasterSecret generated by client on a full handshake
  170. serverCertificates []*x509.Certificate // Certificate chain presented by the server
  171. }
  172. // ClientSessionCache is a cache of ClientSessionState objects that can be used
  173. // by a client to resume a TLS session with a given server. ClientSessionCache
  174. // implementations should expect to be called concurrently from different
  175. // goroutines.
  176. type ClientSessionCache interface {
  177. // Get searches for a ClientSessionState associated with the given key.
  178. // On return, ok is true if one was found.
  179. Get(sessionKey string) (session *ClientSessionState, ok bool)
  180. // Put adds the ClientSessionState to the cache with the given key.
  181. Put(sessionKey string, cs *ClientSessionState)
  182. }
  183. // ClientHelloInfo contains information from a ClientHello message in order to
  184. // guide certificate selection in the GetCertificate callback.
  185. type ClientHelloInfo struct {
  186. // CipherSuites lists the CipherSuites supported by the client (e.g.
  187. // TLS_RSA_WITH_RC4_128_SHA).
  188. CipherSuites []uint16
  189. // ServerName indicates the name of the server requested by the client
  190. // in order to support virtual hosting. ServerName is only set if the
  191. // client is using SNI (see
  192. // http://tools.ietf.org/html/rfc4366#section-3.1).
  193. ServerName string
  194. // SupportedCurves lists the elliptic curves supported by the client.
  195. // SupportedCurves is set only if the Supported Elliptic Curves
  196. // Extension is being used (see
  197. // http://tools.ietf.org/html/rfc4492#section-5.1.1).
  198. SupportedCurves []CurveID
  199. // SupportedPoints lists the point formats supported by the client.
  200. // SupportedPoints is set only if the Supported Point Formats Extension
  201. // is being used (see
  202. // http://tools.ietf.org/html/rfc4492#section-5.1.2).
  203. SupportedPoints []uint8
  204. }
  205. // A Config structure is used to configure a TLS client or server.
  206. // After one has been passed to a TLS function it must not be
  207. // modified. A Config may be reused; the tls package will also not
  208. // modify it.
  209. type Config struct {
  210. // Rand provides the source of entropy for nonces and RSA blinding.
  211. // If Rand is nil, TLS uses the cryptographic random reader in package
  212. // crypto/rand.
  213. // The Reader must be safe for use by multiple goroutines.
  214. Rand io.Reader
  215. // Time returns the current time as the number of seconds since the epoch.
  216. // If Time is nil, TLS uses time.Now.
  217. Time func() time.Time
  218. // Certificates contains one or more certificate chains
  219. // to present to the other side of the connection.
  220. // Server configurations must include at least one certificate.
  221. Certificates []Certificate
  222. // NameToCertificate maps from a certificate name to an element of
  223. // Certificates. Note that a certificate name can be of the form
  224. // '*.example.com' and so doesn't have to be a domain name as such.
  225. // See Config.BuildNameToCertificate
  226. // The nil value causes the first element of Certificates to be used
  227. // for all connections.
  228. NameToCertificate map[string]*Certificate
  229. // GetCertificate returns a Certificate based on the given
  230. // ClientHelloInfo. If GetCertificate is nil or returns nil, then the
  231. // certificate is retrieved from NameToCertificate. If
  232. // NameToCertificate is nil, the first element of Certificates will be
  233. // used.
  234. GetCertificate func(clientHello *ClientHelloInfo) (*Certificate, error)
  235. // RootCAs defines the set of root certificate authorities
  236. // that clients use when verifying server certificates.
  237. // If RootCAs is nil, TLS uses the host's root CA set.
  238. RootCAs *x509.CertPool
  239. // NextProtos is a list of supported, application level protocols.
  240. NextProtos []string
  241. // ServerName is used to verify the hostname on the returned
  242. // certificates unless InsecureSkipVerify is given. It is also included
  243. // in the client's handshake to support virtual hosting.
  244. ServerName string
  245. // ClientAuth determines the server's policy for
  246. // TLS Client Authentication. The default is NoClientCert.
  247. ClientAuth ClientAuthType
  248. // ClientCAs defines the set of root certificate authorities
  249. // that servers use if required to verify a client certificate
  250. // by the policy in ClientAuth.
  251. ClientCAs *x509.CertPool
  252. // InsecureSkipVerify controls whether a client verifies the
  253. // server's certificate chain and host name.
  254. // If InsecureSkipVerify is true, TLS accepts any certificate
  255. // presented by the server and any host name in that certificate.
  256. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  257. // This should be used only for testing.
  258. InsecureSkipVerify bool
  259. // CipherSuites is a list of supported cipher suites. If CipherSuites
  260. // is nil, TLS uses a list of suites supported by the implementation.
  261. CipherSuites []uint16
  262. // PreferServerCipherSuites controls whether the server selects the
  263. // client's most preferred ciphersuite, or the server's most preferred
  264. // ciphersuite. If true then the server's preference, as expressed in
  265. // the order of elements in CipherSuites, is used.
  266. PreferServerCipherSuites bool
  267. // SessionTicketsDisabled may be set to true to disable session ticket
  268. // (resumption) support.
  269. SessionTicketsDisabled bool
  270. // SessionTicketKey is used by TLS servers to provide session
  271. // resumption. See RFC 5077. If zero, it will be filled with
  272. // random data before the first server handshake.
  273. //
  274. // If multiple servers are terminating connections for the same host
  275. // they should all have the same SessionTicketKey. If the
  276. // SessionTicketKey leaks, previously recorded and future TLS
  277. // connections using that key are compromised.
  278. SessionTicketKey [32]byte
  279. // SessionCache is a cache of ClientSessionState entries for TLS session
  280. // resumption.
  281. ClientSessionCache ClientSessionCache
  282. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  283. // If zero, then SSLv3 is taken as the minimum.
  284. MinVersion uint16
  285. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  286. // If zero, then the maximum version supported by this package is used,
  287. // which is currently TLS 1.2.
  288. MaxVersion uint16
  289. // CurvePreferences contains the elliptic curves that will be used in
  290. // an ECDHE handshake, in preference order. If empty, the default will
  291. // be used.
  292. CurvePreferences []CurveID
  293. serverInitOnce sync.Once // guards calling (*Config).serverInit
  294. }
  295. func (c *Config) serverInit() {
  296. if c.SessionTicketsDisabled {
  297. return
  298. }
  299. // If the key has already been set then we have nothing to do.
  300. for _, b := range c.SessionTicketKey {
  301. if b != 0 {
  302. return
  303. }
  304. }
  305. if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  306. c.SessionTicketsDisabled = true
  307. }
  308. }
  309. func (c *Config) rand() io.Reader {
  310. r := c.Rand
  311. if r == nil {
  312. return rand.Reader
  313. }
  314. return r
  315. }
  316. func (c *Config) time() time.Time {
  317. t := c.Time
  318. if t == nil {
  319. t = time.Now
  320. }
  321. return t()
  322. }
  323. func (c *Config) cipherSuites() []uint16 {
  324. s := c.CipherSuites
  325. if s == nil {
  326. s = defaultCipherSuites()
  327. }
  328. return s
  329. }
  330. func (c *Config) minVersion() uint16 {
  331. if c == nil || c.MinVersion == 0 {
  332. return minVersion
  333. }
  334. return c.MinVersion
  335. }
  336. func (c *Config) maxVersion() uint16 {
  337. if c == nil || c.MaxVersion == 0 {
  338. return maxVersion
  339. }
  340. return c.MaxVersion
  341. }
  342. var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
  343. func (c *Config) curvePreferences() []CurveID {
  344. if c == nil || len(c.CurvePreferences) == 0 {
  345. return defaultCurvePreferences
  346. }
  347. return c.CurvePreferences
  348. }
  349. // mutualVersion returns the protocol version to use given the advertised
  350. // version of the peer.
  351. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  352. minVersion := c.minVersion()
  353. maxVersion := c.maxVersion()
  354. if vers < minVersion {
  355. return 0, false
  356. }
  357. if vers > maxVersion {
  358. vers = maxVersion
  359. }
  360. return vers, true
  361. }
  362. // getCertificate returns the best certificate for the given ClientHelloInfo,
  363. // defaulting to the first element of c.Certificates.
  364. func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  365. if c.GetCertificate != nil {
  366. cert, err := c.GetCertificate(clientHello)
  367. if cert != nil || err != nil {
  368. return cert, err
  369. }
  370. }
  371. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  372. // There's only one choice, so no point doing any work.
  373. return &c.Certificates[0], nil
  374. }
  375. name := strings.ToLower(clientHello.ServerName)
  376. for len(name) > 0 && name[len(name)-1] == '.' {
  377. name = name[:len(name)-1]
  378. }
  379. if cert, ok := c.NameToCertificate[name]; ok {
  380. return cert, nil
  381. }
  382. // try replacing labels in the name with wildcards until we get a
  383. // match.
  384. labels := strings.Split(name, ".")
  385. for i := range labels {
  386. labels[i] = "*"
  387. candidate := strings.Join(labels, ".")
  388. if cert, ok := c.NameToCertificate[candidate]; ok {
  389. return cert, nil
  390. }
  391. }
  392. // If nothing matches, return the first certificate.
  393. return &c.Certificates[0], nil
  394. }
  395. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  396. // from the CommonName and SubjectAlternateName fields of each of the leaf
  397. // certificates.
  398. func (c *Config) BuildNameToCertificate() {
  399. c.NameToCertificate = make(map[string]*Certificate)
  400. for i := range c.Certificates {
  401. cert := &c.Certificates[i]
  402. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  403. if err != nil {
  404. continue
  405. }
  406. if len(x509Cert.Subject.CommonName) > 0 {
  407. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  408. }
  409. for _, san := range x509Cert.DNSNames {
  410. c.NameToCertificate[san] = cert
  411. }
  412. }
  413. }
  414. // A Certificate is a chain of one or more certificates, leaf first.
  415. type Certificate struct {
  416. Certificate [][]byte
  417. // PrivateKey contains the private key corresponding to the public key
  418. // in Leaf. For a server, this must be a *rsa.PrivateKey or
  419. // *ecdsa.PrivateKey. For a client doing client authentication, this
  420. // can be any type that implements crypto.Signer (which includes RSA
  421. // and ECDSA private keys).
  422. PrivateKey crypto.PrivateKey
  423. // OCSPStaple contains an optional OCSP response which will be served
  424. // to clients that request it.
  425. OCSPStaple []byte
  426. // Leaf is the parsed form of the leaf certificate, which may be
  427. // initialized using x509.ParseCertificate to reduce per-handshake
  428. // processing for TLS clients doing client authentication. If nil, the
  429. // leaf certificate will be parsed as needed.
  430. Leaf *x509.Certificate
  431. }
  432. // A TLS record.
  433. type record struct {
  434. contentType recordType
  435. major, minor uint8
  436. payload []byte
  437. }
  438. type handshakeMessage interface {
  439. marshal() []byte
  440. unmarshal([]byte) bool
  441. }
  442. // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  443. // caching strategy.
  444. type lruSessionCache struct {
  445. sync.Mutex
  446. m map[string]*list.Element
  447. q *list.List
  448. capacity int
  449. }
  450. type lruSessionCacheEntry struct {
  451. sessionKey string
  452. state *ClientSessionState
  453. }
  454. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  455. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  456. // is used instead.
  457. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  458. const defaultSessionCacheCapacity = 64
  459. if capacity < 1 {
  460. capacity = defaultSessionCacheCapacity
  461. }
  462. return &lruSessionCache{
  463. m: make(map[string]*list.Element),
  464. q: list.New(),
  465. capacity: capacity,
  466. }
  467. }
  468. // Put adds the provided (sessionKey, cs) pair to the cache.
  469. func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  470. c.Lock()
  471. defer c.Unlock()
  472. if elem, ok := c.m[sessionKey]; ok {
  473. entry := elem.Value.(*lruSessionCacheEntry)
  474. entry.state = cs
  475. c.q.MoveToFront(elem)
  476. return
  477. }
  478. if c.q.Len() < c.capacity {
  479. entry := &lruSessionCacheEntry{sessionKey, cs}
  480. c.m[sessionKey] = c.q.PushFront(entry)
  481. return
  482. }
  483. elem := c.q.Back()
  484. entry := elem.Value.(*lruSessionCacheEntry)
  485. delete(c.m, entry.sessionKey)
  486. entry.sessionKey = sessionKey
  487. entry.state = cs
  488. c.q.MoveToFront(elem)
  489. c.m[sessionKey] = elem
  490. }
  491. // Get returns the ClientSessionState value associated with a given key. It
  492. // returns (nil, false) if no value is found.
  493. func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  494. c.Lock()
  495. defer c.Unlock()
  496. if elem, ok := c.m[sessionKey]; ok {
  497. c.q.MoveToFront(elem)
  498. return elem.Value.(*lruSessionCacheEntry).state, true
  499. }
  500. return nil, false
  501. }
  502. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  503. type dsaSignature struct {
  504. R, S *big.Int
  505. }
  506. type ecdsaSignature dsaSignature
  507. var emptyConfig Config
  508. func defaultConfig() *Config {
  509. return &emptyConfig
  510. }
  511. var (
  512. once sync.Once
  513. varDefaultCipherSuites []uint16
  514. )
  515. func defaultCipherSuites() []uint16 {
  516. once.Do(initDefaultCipherSuites)
  517. return varDefaultCipherSuites
  518. }
  519. func initDefaultCipherSuites() {
  520. varDefaultCipherSuites = make([]uint16, len(cipherSuites))
  521. for i, suite := range cipherSuites {
  522. varDefaultCipherSuites[i] = suite.id
  523. }
  524. }
  525. func unexpectedMessageError(wanted, got interface{}) error {
  526. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  527. }