25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

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