Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

622 rindas
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 = VersionSSL30
  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. )
  108. // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
  109. const (
  110. signatureRSA uint8 = 1
  111. signatureECDSA uint8 = 3
  112. )
  113. // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
  114. // RFC 5246, section A.4.1.
  115. type signatureAndHash struct {
  116. hash, signature uint8
  117. }
  118. // supportedSKXSignatureAlgorithms contains the signature and hash algorithms
  119. // that the code advertises as supported in a TLS 1.2 ClientHello.
  120. var supportedSKXSignatureAlgorithms = []signatureAndHash{
  121. {hashSHA256, signatureRSA},
  122. {hashSHA256, signatureECDSA},
  123. {hashSHA1, signatureRSA},
  124. {hashSHA1, signatureECDSA},
  125. }
  126. // supportedClientCertSignatureAlgorithms contains the signature and hash
  127. // algorithms that the code advertises as supported in a TLS 1.2
  128. // CertificateRequest.
  129. var supportedClientCertSignatureAlgorithms = []signatureAndHash{
  130. {hashSHA256, signatureRSA},
  131. {hashSHA256, signatureECDSA},
  132. }
  133. // ConnectionState records basic TLS details about the connection.
  134. type ConnectionState struct {
  135. Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
  136. HandshakeComplete bool // TLS handshake is complete
  137. DidResume bool // connection resumes a previous TLS connection
  138. CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
  139. NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
  140. NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
  141. ServerName string // server name requested by client, if any (server side only)
  142. PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
  143. VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
  144. // TLSUnique contains the "tls-unique" channel binding value (see RFC
  145. // 5929, section 3). For resumed sessions this value will be nil
  146. // because resumption does not include enough context (see
  147. // https://secure-resumption.com/#channelbindings). This will change in
  148. // future versions of Go once the TLS master-secret fix has been
  149. // standardized and implemented.
  150. TLSUnique []byte
  151. }
  152. // ClientAuthType declares the policy the server will follow for
  153. // TLS Client Authentication.
  154. type ClientAuthType int
  155. const (
  156. NoClientCert ClientAuthType = iota
  157. RequestClientCert
  158. RequireAnyClientCert
  159. VerifyClientCertIfGiven
  160. RequireAndVerifyClientCert
  161. )
  162. // ClientSessionState contains the state needed by clients to resume TLS
  163. // sessions.
  164. type ClientSessionState struct {
  165. sessionTicket []uint8 // Encrypted ticket used for session resumption with server
  166. vers uint16 // SSL/TLS version negotiated for the session
  167. cipherSuite uint16 // Ciphersuite negotiated for the session
  168. masterSecret []byte // MasterSecret generated by client on a full handshake
  169. serverCertificates []*x509.Certificate // Certificate chain presented by the server
  170. }
  171. // ClientSessionCache is a cache of ClientSessionState objects that can be used
  172. // by a client to resume a TLS session with a given server. ClientSessionCache
  173. // implementations should expect to be called concurrently from different
  174. // goroutines.
  175. type ClientSessionCache interface {
  176. // Get searches for a ClientSessionState associated with the given key.
  177. // On return, ok is true if one was found.
  178. Get(sessionKey string) (session *ClientSessionState, ok bool)
  179. // Put adds the ClientSessionState to the cache with the given key.
  180. Put(sessionKey string, cs *ClientSessionState)
  181. }
  182. // ClientHelloInfo contains information from a ClientHello message in order to
  183. // guide certificate selection in the GetCertificate callback.
  184. type ClientHelloInfo struct {
  185. // CipherSuites lists the CipherSuites supported by the client (e.g.
  186. // TLS_RSA_WITH_RC4_128_SHA).
  187. CipherSuites []uint16
  188. // ServerName indicates the name of the server requested by the client
  189. // in order to support virtual hosting. ServerName is only set if the
  190. // client is using SNI (see
  191. // http://tools.ietf.org/html/rfc4366#section-3.1).
  192. ServerName string
  193. // SupportedCurves lists the elliptic curves supported by the client.
  194. // SupportedCurves is set only if the Supported Elliptic Curves
  195. // Extension is being used (see
  196. // http://tools.ietf.org/html/rfc4492#section-5.1.1).
  197. SupportedCurves []CurveID
  198. // SupportedPoints lists the point formats supported by the client.
  199. // SupportedPoints is set only if the Supported Point Formats Extension
  200. // is being used (see
  201. // http://tools.ietf.org/html/rfc4492#section-5.1.2).
  202. SupportedPoints []uint8
  203. }
  204. // A Config structure is used to configure a TLS client or server.
  205. // After one has been passed to a TLS function it must not be
  206. // modified. A Config may be reused; the tls package will also not
  207. // modify it.
  208. type Config struct {
  209. // Rand provides the source of entropy for nonces and RSA blinding.
  210. // If Rand is nil, TLS uses the cryptographic random reader in package
  211. // crypto/rand.
  212. // The Reader must be safe for use by multiple goroutines.
  213. Rand io.Reader
  214. // Time returns the current time as the number of seconds since the epoch.
  215. // If Time is nil, TLS uses time.Now.
  216. Time func() time.Time
  217. // Certificates contains one or more certificate chains
  218. // to present to the other side of the connection.
  219. // Server configurations must include at least one certificate.
  220. Certificates []Certificate
  221. // NameToCertificate maps from a certificate name to an element of
  222. // Certificates. Note that a certificate name can be of the form
  223. // '*.example.com' and so doesn't have to be a domain name as such.
  224. // See Config.BuildNameToCertificate
  225. // The nil value causes the first element of Certificates to be used
  226. // for all connections.
  227. NameToCertificate map[string]*Certificate
  228. // GetCertificate returns a Certificate based on the given
  229. // ClientHelloInfo. If GetCertificate is nil or returns nil, then the
  230. // certificate is retrieved from NameToCertificate. If
  231. // NameToCertificate is nil, the first element of Certificates will be
  232. // used.
  233. GetCertificate func(clientHello *ClientHelloInfo) (*Certificate, error)
  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. // InsecureSkipVerify controls whether a client verifies the
  252. // server's certificate chain and host name.
  253. // If InsecureSkipVerify is true, TLS accepts any certificate
  254. // presented by the server and any host name in that certificate.
  255. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  256. // This should be used only for testing.
  257. InsecureSkipVerify bool
  258. // CipherSuites is a list of supported cipher suites. If CipherSuites
  259. // is nil, TLS uses a list of suites supported by the implementation.
  260. CipherSuites []uint16
  261. // PreferServerCipherSuites controls whether the server selects the
  262. // client's most preferred ciphersuite, or the server's most preferred
  263. // ciphersuite. If true then the server's preference, as expressed in
  264. // the order of elements in CipherSuites, is used.
  265. PreferServerCipherSuites bool
  266. // SessionTicketsDisabled may be set to true to disable session ticket
  267. // (resumption) support.
  268. SessionTicketsDisabled bool
  269. // SessionTicketKey is used by TLS servers to provide session
  270. // resumption. See RFC 5077. If zero, it will be filled with
  271. // random data before the first server handshake.
  272. //
  273. // If multiple servers are terminating connections for the same host
  274. // they should all have the same SessionTicketKey. If the
  275. // SessionTicketKey leaks, previously recorded and future TLS
  276. // connections using that key are compromised.
  277. SessionTicketKey [32]byte
  278. // SessionCache is a cache of ClientSessionState entries for TLS session
  279. // resumption.
  280. ClientSessionCache ClientSessionCache
  281. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  282. // If zero, then SSLv3 is taken as the minimum.
  283. MinVersion uint16
  284. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  285. // If zero, then the maximum version supported by this package is used,
  286. // which is currently TLS 1.2.
  287. MaxVersion uint16
  288. // CurvePreferences contains the elliptic curves that will be used in
  289. // an ECDHE handshake, in preference order. If empty, the default will
  290. // be used.
  291. CurvePreferences []CurveID
  292. serverInitOnce sync.Once // guards calling (*Config).serverInit
  293. }
  294. func (c *Config) serverInit() {
  295. if c.SessionTicketsDisabled {
  296. return
  297. }
  298. // If the key has already been set then we have nothing to do.
  299. for _, b := range c.SessionTicketKey {
  300. if b != 0 {
  301. return
  302. }
  303. }
  304. if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  305. c.SessionTicketsDisabled = true
  306. }
  307. }
  308. func (c *Config) rand() io.Reader {
  309. r := c.Rand
  310. if r == nil {
  311. return rand.Reader
  312. }
  313. return r
  314. }
  315. func (c *Config) time() time.Time {
  316. t := c.Time
  317. if t == nil {
  318. t = time.Now
  319. }
  320. return t()
  321. }
  322. func (c *Config) cipherSuites() []uint16 {
  323. s := c.CipherSuites
  324. if s == nil {
  325. s = defaultCipherSuites()
  326. }
  327. return s
  328. }
  329. func (c *Config) minVersion() uint16 {
  330. if c == nil || c.MinVersion == 0 {
  331. return minVersion
  332. }
  333. return c.MinVersion
  334. }
  335. func (c *Config) maxVersion() uint16 {
  336. if c == nil || c.MaxVersion == 0 {
  337. return maxVersion
  338. }
  339. return c.MaxVersion
  340. }
  341. var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
  342. func (c *Config) curvePreferences() []CurveID {
  343. if c == nil || len(c.CurvePreferences) == 0 {
  344. return defaultCurvePreferences
  345. }
  346. return c.CurvePreferences
  347. }
  348. // mutualVersion returns the protocol version to use given the advertised
  349. // version of the peer.
  350. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  351. minVersion := c.minVersion()
  352. maxVersion := c.maxVersion()
  353. if vers < minVersion {
  354. return 0, false
  355. }
  356. if vers > maxVersion {
  357. vers = maxVersion
  358. }
  359. return vers, true
  360. }
  361. // getCertificate returns the best certificate for the given ClientHelloInfo,
  362. // defaulting to the first element of c.Certificates.
  363. func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  364. if c.GetCertificate != nil {
  365. cert, err := c.GetCertificate(clientHello)
  366. if cert != nil || err != nil {
  367. return cert, err
  368. }
  369. }
  370. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  371. // There's only one choice, so no point doing any work.
  372. return &c.Certificates[0], nil
  373. }
  374. name := strings.ToLower(clientHello.ServerName)
  375. for len(name) > 0 && name[len(name)-1] == '.' {
  376. name = name[:len(name)-1]
  377. }
  378. if cert, ok := c.NameToCertificate[name]; ok {
  379. return cert, nil
  380. }
  381. // try replacing labels in the name with wildcards until we get a
  382. // match.
  383. labels := strings.Split(name, ".")
  384. for i := range labels {
  385. labels[i] = "*"
  386. candidate := strings.Join(labels, ".")
  387. if cert, ok := c.NameToCertificate[candidate]; ok {
  388. return cert, nil
  389. }
  390. }
  391. // If nothing matches, return the first certificate.
  392. return &c.Certificates[0], nil
  393. }
  394. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  395. // from the CommonName and SubjectAlternateName fields of each of the leaf
  396. // certificates.
  397. func (c *Config) BuildNameToCertificate() {
  398. c.NameToCertificate = make(map[string]*Certificate)
  399. for i := range c.Certificates {
  400. cert := &c.Certificates[i]
  401. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  402. if err != nil {
  403. continue
  404. }
  405. if len(x509Cert.Subject.CommonName) > 0 {
  406. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  407. }
  408. for _, san := range x509Cert.DNSNames {
  409. c.NameToCertificate[san] = cert
  410. }
  411. }
  412. }
  413. // A Certificate is a chain of one or more certificates, leaf first.
  414. type Certificate struct {
  415. Certificate [][]byte
  416. // PrivateKey contains the private key corresponding to the public key
  417. // in Leaf. For a server, this must be a *rsa.PrivateKey or
  418. // *ecdsa.PrivateKey. For a client doing client authentication, this
  419. // can be any type that implements crypto.Signer (which includes RSA
  420. // and ECDSA private keys).
  421. PrivateKey crypto.PrivateKey
  422. // OCSPStaple contains an optional OCSP response which will be served
  423. // to clients that request it.
  424. OCSPStaple []byte
  425. // Leaf is the parsed form of the leaf certificate, which may be
  426. // initialized using x509.ParseCertificate to reduce per-handshake
  427. // processing for TLS clients doing client authentication. If nil, the
  428. // leaf certificate will be parsed as needed.
  429. Leaf *x509.Certificate
  430. }
  431. // A TLS record.
  432. type record struct {
  433. contentType recordType
  434. major, minor uint8
  435. payload []byte
  436. }
  437. type handshakeMessage interface {
  438. marshal() []byte
  439. unmarshal([]byte) bool
  440. }
  441. // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  442. // caching strategy.
  443. type lruSessionCache struct {
  444. sync.Mutex
  445. m map[string]*list.Element
  446. q *list.List
  447. capacity int
  448. }
  449. type lruSessionCacheEntry struct {
  450. sessionKey string
  451. state *ClientSessionState
  452. }
  453. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  454. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  455. // is used instead.
  456. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  457. const defaultSessionCacheCapacity = 64
  458. if capacity < 1 {
  459. capacity = defaultSessionCacheCapacity
  460. }
  461. return &lruSessionCache{
  462. m: make(map[string]*list.Element),
  463. q: list.New(),
  464. capacity: capacity,
  465. }
  466. }
  467. // Put adds the provided (sessionKey, cs) pair to the cache.
  468. func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  469. c.Lock()
  470. defer c.Unlock()
  471. if elem, ok := c.m[sessionKey]; ok {
  472. entry := elem.Value.(*lruSessionCacheEntry)
  473. entry.state = cs
  474. c.q.MoveToFront(elem)
  475. return
  476. }
  477. if c.q.Len() < c.capacity {
  478. entry := &lruSessionCacheEntry{sessionKey, cs}
  479. c.m[sessionKey] = c.q.PushFront(entry)
  480. return
  481. }
  482. elem := c.q.Back()
  483. entry := elem.Value.(*lruSessionCacheEntry)
  484. delete(c.m, entry.sessionKey)
  485. entry.sessionKey = sessionKey
  486. entry.state = cs
  487. c.q.MoveToFront(elem)
  488. c.m[sessionKey] = elem
  489. }
  490. // Get returns the ClientSessionState value associated with a given key. It
  491. // returns (nil, false) if no value is found.
  492. func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  493. c.Lock()
  494. defer c.Unlock()
  495. if elem, ok := c.m[sessionKey]; ok {
  496. c.q.MoveToFront(elem)
  497. return elem.Value.(*lruSessionCacheEntry).state, true
  498. }
  499. return nil, false
  500. }
  501. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  502. type dsaSignature struct {
  503. R, S *big.Int
  504. }
  505. type ecdsaSignature dsaSignature
  506. var emptyConfig Config
  507. func defaultConfig() *Config {
  508. return &emptyConfig
  509. }
  510. var (
  511. once sync.Once
  512. varDefaultCipherSuites []uint16
  513. )
  514. func defaultCipherSuites() []uint16 {
  515. once.Do(initDefaultCipherSuites)
  516. return varDefaultCipherSuites
  517. }
  518. func initDefaultCipherSuites() {
  519. varDefaultCipherSuites = make([]uint16, len(cipherSuites))
  520. for i, suite := range cipherSuites {
  521. varDefaultCipherSuites[i] = suite.id
  522. }
  523. }
  524. func unexpectedMessageError(wanted, got interface{}) error {
  525. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  526. }