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ů.
 
 
 
 
 
 

438 řádky
13 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. "crypto"
  7. "crypto/rand"
  8. "crypto/x509"
  9. "io"
  10. "math/big"
  11. "strings"
  12. "sync"
  13. "time"
  14. )
  15. const (
  16. VersionSSL30 = 0x0300
  17. VersionTLS10 = 0x0301
  18. VersionTLS11 = 0x0302
  19. VersionTLS12 = 0x0303
  20. )
  21. const (
  22. maxPlaintext = 16384 // maximum plaintext payload length
  23. maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
  24. recordHeaderLen = 5 // record header length
  25. maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
  26. minVersion = VersionSSL30
  27. maxVersion = VersionTLS12
  28. )
  29. // TLS record types.
  30. type recordType uint8
  31. const (
  32. recordTypeChangeCipherSpec recordType = 20
  33. recordTypeAlert recordType = 21
  34. recordTypeHandshake recordType = 22
  35. recordTypeApplicationData recordType = 23
  36. )
  37. // TLS handshake message types.
  38. const (
  39. typeClientHello uint8 = 1
  40. typeServerHello uint8 = 2
  41. typeNewSessionTicket uint8 = 4
  42. typeCertificate uint8 = 11
  43. typeServerKeyExchange uint8 = 12
  44. typeCertificateRequest uint8 = 13
  45. typeServerHelloDone uint8 = 14
  46. typeCertificateVerify uint8 = 15
  47. typeClientKeyExchange uint8 = 16
  48. typeFinished uint8 = 20
  49. typeCertificateStatus uint8 = 22
  50. typeNextProtocol uint8 = 67 // Not IANA assigned
  51. )
  52. // TLS compression types.
  53. const (
  54. compressionNone uint8 = 0
  55. )
  56. // TLS extension numbers
  57. var (
  58. extensionServerName uint16 = 0
  59. extensionStatusRequest uint16 = 5
  60. extensionSupportedCurves uint16 = 10
  61. extensionSupportedPoints uint16 = 11
  62. extensionSignatureAlgorithms uint16 = 13
  63. extensionSessionTicket uint16 = 35
  64. extensionNextProtoNeg uint16 = 13172 // not IANA assigned
  65. )
  66. // TLS Elliptic Curves
  67. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
  68. var (
  69. curveP256 uint16 = 23
  70. curveP384 uint16 = 24
  71. curveP521 uint16 = 25
  72. )
  73. // TLS Elliptic Curve Point Formats
  74. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
  75. var (
  76. pointFormatUncompressed uint8 = 0
  77. )
  78. // TLS CertificateStatusType (RFC 3546)
  79. const (
  80. statusTypeOCSP uint8 = 1
  81. )
  82. // Certificate types (for certificateRequestMsg)
  83. const (
  84. certTypeRSASign = 1 // A certificate containing an RSA key
  85. certTypeDSSSign = 2 // A certificate containing a DSA key
  86. certTypeRSAFixedDH = 3 // A certificate containing a static DH key
  87. certTypeDSSFixedDH = 4 // A certificate containing a static DH key
  88. // See RFC4492 sections 3 and 5.5.
  89. certTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
  90. certTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
  91. certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
  92. // Rest of these are reserved by the TLS spec
  93. )
  94. // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
  95. const (
  96. hashSHA1 uint8 = 2
  97. hashSHA256 uint8 = 4
  98. )
  99. // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
  100. const (
  101. signatureRSA uint8 = 1
  102. signatureECDSA uint8 = 3
  103. )
  104. // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
  105. // RFC 5246, section A.4.1.
  106. type signatureAndHash struct {
  107. hash, signature uint8
  108. }
  109. // supportedSKXSignatureAlgorithms contains the signature and hash algorithms
  110. // that the code advertises as supported in a TLS 1.2 ClientHello.
  111. var supportedSKXSignatureAlgorithms = []signatureAndHash{
  112. {hashSHA256, signatureRSA},
  113. {hashSHA256, signatureECDSA},
  114. {hashSHA1, signatureRSA},
  115. {hashSHA1, signatureECDSA},
  116. }
  117. // supportedClientCertSignatureAlgorithms contains the signature and hash
  118. // algorithms that the code advertises as supported in a TLS 1.2
  119. // CertificateRequest.
  120. var supportedClientCertSignatureAlgorithms = []signatureAndHash{
  121. {hashSHA256, signatureRSA},
  122. {hashSHA256, signatureECDSA},
  123. }
  124. // ConnectionState records basic TLS details about the connection.
  125. type ConnectionState struct {
  126. HandshakeComplete bool // TLS handshake is complete
  127. DidResume bool // connection resumes a previous TLS connection
  128. CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
  129. NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
  130. NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
  131. ServerName string // server name requested by client, if any (server side only)
  132. PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
  133. VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
  134. }
  135. // ClientAuthType declares the policy the server will follow for
  136. // TLS Client Authentication.
  137. type ClientAuthType int
  138. const (
  139. NoClientCert ClientAuthType = iota
  140. RequestClientCert
  141. RequireAnyClientCert
  142. VerifyClientCertIfGiven
  143. RequireAndVerifyClientCert
  144. )
  145. // A Config structure is used to configure a TLS client or server. After one
  146. // has been passed to a TLS function it must not be modified.
  147. type Config struct {
  148. // Rand provides the source of entropy for nonces and RSA blinding.
  149. // If Rand is nil, TLS uses the cryptographic random reader in package
  150. // crypto/rand.
  151. Rand io.Reader
  152. // Time returns the current time as the number of seconds since the epoch.
  153. // If Time is nil, TLS uses time.Now.
  154. Time func() time.Time
  155. // Certificates contains one or more certificate chains
  156. // to present to the other side of the connection.
  157. // Server configurations must include at least one certificate.
  158. Certificates []Certificate
  159. // NameToCertificate maps from a certificate name to an element of
  160. // Certificates. Note that a certificate name can be of the form
  161. // '*.example.com' and so doesn't have to be a domain name as such.
  162. // See Config.BuildNameToCertificate
  163. // The nil value causes the first element of Certificates to be used
  164. // for all connections.
  165. NameToCertificate map[string]*Certificate
  166. // RootCAs defines the set of root certificate authorities
  167. // that clients use when verifying server certificates.
  168. // If RootCAs is nil, TLS uses the host's root CA set.
  169. RootCAs *x509.CertPool
  170. // NextProtos is a list of supported, application level protocols.
  171. NextProtos []string
  172. // ServerName is included in the client's handshake to support virtual
  173. // hosting.
  174. ServerName string
  175. // ClientAuth determines the server's policy for
  176. // TLS Client Authentication. The default is NoClientCert.
  177. ClientAuth ClientAuthType
  178. // ClientCAs defines the set of root certificate authorities
  179. // that servers use if required to verify a client certificate
  180. // by the policy in ClientAuth.
  181. ClientCAs *x509.CertPool
  182. // InsecureSkipVerify controls whether a client verifies the
  183. // server's certificate chain and host name.
  184. // If InsecureSkipVerify is true, TLS accepts any certificate
  185. // presented by the server and any host name in that certificate.
  186. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  187. // This should be used only for testing.
  188. InsecureSkipVerify bool
  189. // CipherSuites is a list of supported cipher suites. If CipherSuites
  190. // is nil, TLS uses a list of suites supported by the implementation.
  191. CipherSuites []uint16
  192. // PreferServerCipherSuites controls whether the server selects the
  193. // client's most preferred ciphersuite, or the server's most preferred
  194. // ciphersuite. If true then the server's preference, as expressed in
  195. // the order of elements in CipherSuites, is used.
  196. PreferServerCipherSuites bool
  197. // SessionTicketsDisabled may be set to true to disable session ticket
  198. // (resumption) support.
  199. SessionTicketsDisabled bool
  200. // SessionTicketKey is used by TLS servers to provide session
  201. // resumption. See RFC 5077. If zero, it will be filled with
  202. // random data before the first server handshake.
  203. //
  204. // If multiple servers are terminating connections for the same host
  205. // they should all have the same SessionTicketKey. If the
  206. // SessionTicketKey leaks, previously recorded and future TLS
  207. // connections using that key are compromised.
  208. SessionTicketKey [32]byte
  209. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  210. // If zero, then SSLv3 is taken as the minimum.
  211. MinVersion uint16
  212. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  213. // If zero, then the maximum version supported by this package is used,
  214. // which is currently TLS 1.2.
  215. MaxVersion uint16
  216. serverInitOnce sync.Once // guards calling (*Config).serverInit
  217. }
  218. func (c *Config) serverInit() {
  219. if c.SessionTicketsDisabled {
  220. return
  221. }
  222. // If the key has already been set then we have nothing to do.
  223. for _, b := range c.SessionTicketKey {
  224. if b != 0 {
  225. return
  226. }
  227. }
  228. if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  229. c.SessionTicketsDisabled = true
  230. }
  231. }
  232. func (c *Config) rand() io.Reader {
  233. r := c.Rand
  234. if r == nil {
  235. return rand.Reader
  236. }
  237. return r
  238. }
  239. func (c *Config) time() time.Time {
  240. t := c.Time
  241. if t == nil {
  242. t = time.Now
  243. }
  244. return t()
  245. }
  246. func (c *Config) cipherSuites() []uint16 {
  247. s := c.CipherSuites
  248. if s == nil {
  249. s = defaultCipherSuites()
  250. }
  251. return s
  252. }
  253. func (c *Config) minVersion() uint16 {
  254. if c == nil || c.MinVersion == 0 {
  255. return minVersion
  256. }
  257. return c.MinVersion
  258. }
  259. func (c *Config) maxVersion() uint16 {
  260. if c == nil || c.MaxVersion == 0 {
  261. return maxVersion
  262. }
  263. return c.MaxVersion
  264. }
  265. // mutualVersion returns the protocol version to use given the advertised
  266. // version of the peer.
  267. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  268. minVersion := c.minVersion()
  269. maxVersion := c.maxVersion()
  270. if vers < minVersion {
  271. return 0, false
  272. }
  273. if vers > maxVersion {
  274. vers = maxVersion
  275. }
  276. return vers, true
  277. }
  278. // getCertificateForName returns the best certificate for the given name,
  279. // defaulting to the first element of c.Certificates if there are no good
  280. // options.
  281. func (c *Config) getCertificateForName(name string) *Certificate {
  282. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  283. // There's only one choice, so no point doing any work.
  284. return &c.Certificates[0]
  285. }
  286. name = strings.ToLower(name)
  287. for len(name) > 0 && name[len(name)-1] == '.' {
  288. name = name[:len(name)-1]
  289. }
  290. if cert, ok := c.NameToCertificate[name]; ok {
  291. return cert
  292. }
  293. // try replacing labels in the name with wildcards until we get a
  294. // match.
  295. labels := strings.Split(name, ".")
  296. for i := range labels {
  297. labels[i] = "*"
  298. candidate := strings.Join(labels, ".")
  299. if cert, ok := c.NameToCertificate[candidate]; ok {
  300. return cert
  301. }
  302. }
  303. // If nothing matches, return the first certificate.
  304. return &c.Certificates[0]
  305. }
  306. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  307. // from the CommonName and SubjectAlternateName fields of each of the leaf
  308. // certificates.
  309. func (c *Config) BuildNameToCertificate() {
  310. c.NameToCertificate = make(map[string]*Certificate)
  311. for i := range c.Certificates {
  312. cert := &c.Certificates[i]
  313. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  314. if err != nil {
  315. continue
  316. }
  317. if len(x509Cert.Subject.CommonName) > 0 {
  318. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  319. }
  320. for _, san := range x509Cert.DNSNames {
  321. c.NameToCertificate[san] = cert
  322. }
  323. }
  324. }
  325. // A Certificate is a chain of one or more certificates, leaf first.
  326. type Certificate struct {
  327. Certificate [][]byte
  328. PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
  329. // OCSPStaple contains an optional OCSP response which will be served
  330. // to clients that request it.
  331. OCSPStaple []byte
  332. // Leaf is the parsed form of the leaf certificate, which may be
  333. // initialized using x509.ParseCertificate to reduce per-handshake
  334. // processing for TLS clients doing client authentication. If nil, the
  335. // leaf certificate will be parsed as needed.
  336. Leaf *x509.Certificate
  337. }
  338. // A TLS record.
  339. type record struct {
  340. contentType recordType
  341. major, minor uint8
  342. payload []byte
  343. }
  344. type handshakeMessage interface {
  345. marshal() []byte
  346. unmarshal([]byte) bool
  347. }
  348. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  349. type dsaSignature struct {
  350. R, S *big.Int
  351. }
  352. type ecdsaSignature dsaSignature
  353. var emptyConfig Config
  354. func defaultConfig() *Config {
  355. return &emptyConfig
  356. }
  357. var (
  358. once sync.Once
  359. varDefaultCipherSuites []uint16
  360. )
  361. func defaultCipherSuites() []uint16 {
  362. once.Do(initDefaultCipherSuites)
  363. return varDefaultCipherSuites
  364. }
  365. func initDefaultCipherSuites() {
  366. varDefaultCipherSuites = make([]uint16, len(cipherSuites))
  367. for i, suite := range cipherSuites {
  368. varDefaultCipherSuites[i] = suite.id
  369. }
  370. }