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.
 
 
 
 
 
 

435 lines
12 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. // supportedSignatureAlgorithms contains the signature and hash algorithms that
  110. // the code can advertise as supported both in a TLS 1.2 ClientHello and
  111. // CertificateRequest.
  112. var supportedSignatureAlgorithms = []signatureAndHash{
  113. {hashSHA256, signatureRSA},
  114. {hashSHA256, signatureECDSA},
  115. }
  116. // ConnectionState records basic TLS details about the connection.
  117. type ConnectionState struct {
  118. HandshakeComplete bool
  119. DidResume bool
  120. CipherSuite uint16
  121. NegotiatedProtocol string
  122. NegotiatedProtocolIsMutual bool
  123. // ServerName contains the server name indicated by the client, if any.
  124. // (Only valid for server connections.)
  125. ServerName string
  126. // the certificate chain that was presented by the other side
  127. PeerCertificates []*x509.Certificate
  128. // the verified certificate chains built from PeerCertificates.
  129. VerifiedChains [][]*x509.Certificate
  130. }
  131. // ClientAuthType declares the policy the server will follow for
  132. // TLS Client Authentication.
  133. type ClientAuthType int
  134. const (
  135. NoClientCert ClientAuthType = iota
  136. RequestClientCert
  137. RequireAnyClientCert
  138. VerifyClientCertIfGiven
  139. RequireAndVerifyClientCert
  140. )
  141. // A Config structure is used to configure a TLS client or server. After one
  142. // has been passed to a TLS function it must not be modified.
  143. type Config struct {
  144. // Rand provides the source of entropy for nonces and RSA blinding.
  145. // If Rand is nil, TLS uses the cryptographic random reader in package
  146. // crypto/rand.
  147. Rand io.Reader
  148. // Time returns the current time as the number of seconds since the epoch.
  149. // If Time is nil, TLS uses time.Now.
  150. Time func() time.Time
  151. // Certificates contains one or more certificate chains
  152. // to present to the other side of the connection.
  153. // Server configurations must include at least one certificate.
  154. Certificates []Certificate
  155. // NameToCertificate maps from a certificate name to an element of
  156. // Certificates. Note that a certificate name can be of the form
  157. // '*.example.com' and so doesn't have to be a domain name as such.
  158. // See Config.BuildNameToCertificate
  159. // The nil value causes the first element of Certificates to be used
  160. // for all connections.
  161. NameToCertificate map[string]*Certificate
  162. // RootCAs defines the set of root certificate authorities
  163. // that clients use when verifying server certificates.
  164. // If RootCAs is nil, TLS uses the host's root CA set.
  165. RootCAs *x509.CertPool
  166. // NextProtos is a list of supported, application level protocols.
  167. NextProtos []string
  168. // ServerName is included in the client's handshake to support virtual
  169. // hosting.
  170. ServerName string
  171. // ClientAuth determines the server's policy for
  172. // TLS Client Authentication. The default is NoClientCert.
  173. ClientAuth ClientAuthType
  174. // ClientCAs defines the set of root certificate authorities
  175. // that servers use if required to verify a client certificate
  176. // by the policy in ClientAuth.
  177. ClientCAs *x509.CertPool
  178. // InsecureSkipVerify controls whether a client verifies the
  179. // server's certificate chain and host name.
  180. // If InsecureSkipVerify is true, TLS accepts any certificate
  181. // presented by the server and any host name in that certificate.
  182. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  183. // This should be used only for testing.
  184. InsecureSkipVerify bool
  185. // CipherSuites is a list of supported cipher suites. If CipherSuites
  186. // is nil, TLS uses a list of suites supported by the implementation.
  187. CipherSuites []uint16
  188. // PreferServerCipherSuites controls whether the server selects the
  189. // client's most preferred ciphersuite, or the server's most preferred
  190. // ciphersuite. If true then the server's preference, as expressed in
  191. // the order of elements in CipherSuites, is used.
  192. PreferServerCipherSuites bool
  193. // SessionTicketsDisabled may be set to true to disable session ticket
  194. // (resumption) support.
  195. SessionTicketsDisabled bool
  196. // SessionTicketKey is used by TLS servers to provide session
  197. // resumption. See RFC 5077. If zero, it will be filled with
  198. // random data before the first server handshake.
  199. //
  200. // If multiple servers are terminating connections for the same host
  201. // they should all have the same SessionTicketKey. If the
  202. // SessionTicketKey leaks, previously recorded and future TLS
  203. // connections using that key are compromised.
  204. SessionTicketKey [32]byte
  205. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  206. // If zero, then SSLv3 is taken as the minimum.
  207. MinVersion uint16
  208. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  209. // If zero, then the maximum version supported by this package is used,
  210. // which is currently TLS 1.2.
  211. MaxVersion uint16
  212. serverInitOnce sync.Once // guards calling (*Config).serverInit
  213. }
  214. func (c *Config) serverInit() {
  215. if c.SessionTicketsDisabled {
  216. return
  217. }
  218. // If the key has already been set then we have nothing to do.
  219. for _, b := range c.SessionTicketKey {
  220. if b != 0 {
  221. return
  222. }
  223. }
  224. if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  225. c.SessionTicketsDisabled = true
  226. }
  227. }
  228. func (c *Config) rand() io.Reader {
  229. r := c.Rand
  230. if r == nil {
  231. return rand.Reader
  232. }
  233. return r
  234. }
  235. func (c *Config) time() time.Time {
  236. t := c.Time
  237. if t == nil {
  238. t = time.Now
  239. }
  240. return t()
  241. }
  242. func (c *Config) cipherSuites() []uint16 {
  243. s := c.CipherSuites
  244. if s == nil {
  245. s = defaultCipherSuites()
  246. }
  247. return s
  248. }
  249. func (c *Config) minVersion() uint16 {
  250. if c == nil || c.MinVersion == 0 {
  251. return minVersion
  252. }
  253. return c.MinVersion
  254. }
  255. func (c *Config) maxVersion() uint16 {
  256. if c == nil || c.MaxVersion == 0 {
  257. return maxVersion
  258. }
  259. return c.MaxVersion
  260. }
  261. // mutualVersion returns the protocol version to use given the advertised
  262. // version of the peer.
  263. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  264. minVersion := c.minVersion()
  265. maxVersion := c.maxVersion()
  266. if vers < minVersion {
  267. return 0, false
  268. }
  269. if vers > maxVersion {
  270. vers = maxVersion
  271. }
  272. return vers, true
  273. }
  274. // getCertificateForName returns the best certificate for the given name,
  275. // defaulting to the first element of c.Certificates if there are no good
  276. // options.
  277. func (c *Config) getCertificateForName(name string) *Certificate {
  278. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  279. // There's only one choice, so no point doing any work.
  280. return &c.Certificates[0]
  281. }
  282. name = strings.ToLower(name)
  283. for len(name) > 0 && name[len(name)-1] == '.' {
  284. name = name[:len(name)-1]
  285. }
  286. if cert, ok := c.NameToCertificate[name]; ok {
  287. return cert
  288. }
  289. // try replacing labels in the name with wildcards until we get a
  290. // match.
  291. labels := strings.Split(name, ".")
  292. for i := range labels {
  293. labels[i] = "*"
  294. candidate := strings.Join(labels, ".")
  295. if cert, ok := c.NameToCertificate[candidate]; ok {
  296. return cert
  297. }
  298. }
  299. // If nothing matches, return the first certificate.
  300. return &c.Certificates[0]
  301. }
  302. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  303. // from the CommonName and SubjectAlternateName fields of each of the leaf
  304. // certificates.
  305. func (c *Config) BuildNameToCertificate() {
  306. c.NameToCertificate = make(map[string]*Certificate)
  307. for i := range c.Certificates {
  308. cert := &c.Certificates[i]
  309. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  310. if err != nil {
  311. continue
  312. }
  313. if len(x509Cert.Subject.CommonName) > 0 {
  314. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  315. }
  316. for _, san := range x509Cert.DNSNames {
  317. c.NameToCertificate[san] = cert
  318. }
  319. }
  320. }
  321. // A Certificate is a chain of one or more certificates, leaf first.
  322. type Certificate struct {
  323. Certificate [][]byte
  324. PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
  325. // OCSPStaple contains an optional OCSP response which will be served
  326. // to clients that request it.
  327. OCSPStaple []byte
  328. // Leaf is the parsed form of the leaf certificate, which may be
  329. // initialized using x509.ParseCertificate to reduce per-handshake
  330. // processing for TLS clients doing client authentication. If nil, the
  331. // leaf certificate will be parsed as needed.
  332. Leaf *x509.Certificate
  333. }
  334. // A TLS record.
  335. type record struct {
  336. contentType recordType
  337. major, minor uint8
  338. payload []byte
  339. }
  340. type handshakeMessage interface {
  341. marshal() []byte
  342. unmarshal([]byte) bool
  343. }
  344. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  345. type dsaSignature struct {
  346. R, S *big.Int
  347. }
  348. type ecdsaSignature dsaSignature
  349. var emptyConfig Config
  350. func defaultConfig() *Config {
  351. return &emptyConfig
  352. }
  353. var (
  354. once sync.Once
  355. varDefaultCipherSuites []uint16
  356. )
  357. func defaultCipherSuites() []uint16 {
  358. once.Do(initDefaultCipherSuites)
  359. return varDefaultCipherSuites
  360. }
  361. func initDefaultCipherSuites() {
  362. varDefaultCipherSuites = make([]uint16, len(cipherSuites))
  363. for i, suite := range cipherSuites {
  364. varDefaultCipherSuites[i] = suite.id
  365. }
  366. }