Alternative TLS implementation in Go
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.

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