Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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/rand"
  7. "crypto/rsa"
  8. "crypto/x509"
  9. "io"
  10. "io/ioutil"
  11. "strings"
  12. "sync"
  13. "time"
  14. )
  15. const (
  16. maxPlaintext = 16384 // maximum plaintext payload length
  17. maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
  18. recordHeaderLen = 5 // record header length
  19. maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
  20. versionSSL30 = 0x0300
  21. versionTLS10 = 0x0301
  22. minVersion = versionSSL30
  23. maxVersion = versionTLS10
  24. )
  25. // TLS record types.
  26. type recordType uint8
  27. const (
  28. recordTypeChangeCipherSpec recordType = 20
  29. recordTypeAlert recordType = 21
  30. recordTypeHandshake recordType = 22
  31. recordTypeApplicationData recordType = 23
  32. )
  33. // TLS handshake message types.
  34. const (
  35. typeClientHello uint8 = 1
  36. typeServerHello uint8 = 2
  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. extensionNextProtoNeg uint16 = 13172 // not IANA assigned
  58. )
  59. // TLS Elliptic Curves
  60. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
  61. var (
  62. curveP256 uint16 = 23
  63. curveP384 uint16 = 24
  64. curveP521 uint16 = 25
  65. )
  66. // TLS Elliptic Curve Point Formats
  67. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
  68. var (
  69. pointFormatUncompressed uint8 = 0
  70. )
  71. // TLS CertificateStatusType (RFC 3546)
  72. const (
  73. statusTypeOCSP uint8 = 1
  74. )
  75. // Certificate types (for certificateRequestMsg)
  76. const (
  77. certTypeRSASign = 1 // A certificate containing an RSA key
  78. certTypeDSSSign = 2 // A certificate containing a DSA key
  79. certTypeRSAFixedDH = 3 // A certificate containing a static DH key
  80. certTypeDSSFixedDH = 4 // A certificate containing a static DH key
  81. // Rest of these are reserved by the TLS spec
  82. )
  83. // ConnectionState records basic TLS details about the connection.
  84. type ConnectionState struct {
  85. HandshakeComplete bool
  86. CipherSuite uint16
  87. NegotiatedProtocol string
  88. NegotiatedProtocolIsMutual bool
  89. // ServerName contains the server name indicated by the client, if any.
  90. // (Only valid for server connections.)
  91. ServerName string
  92. // the certificate chain that was presented by the other side
  93. PeerCertificates []*x509.Certificate
  94. // the verified certificate chains built from PeerCertificates.
  95. VerifiedChains [][]*x509.Certificate
  96. }
  97. // A Config structure is used to configure a TLS client or server. After one
  98. // has been passed to a TLS function it must not be modified.
  99. type Config struct {
  100. // Rand provides the source of entropy for nonces and RSA blinding.
  101. // If Rand is nil, TLS uses the cryptographic random reader in package
  102. // crypto/rand.
  103. Rand io.Reader
  104. // Time returns the current time as the number of seconds since the epoch.
  105. // If Time is nil, TLS uses the system time.Seconds.
  106. Time func() int64
  107. // Certificates contains one or more certificate chains
  108. // to present to the other side of the connection.
  109. // Server configurations must include at least one certificate.
  110. Certificates []Certificate
  111. // NameToCertificate maps from a certificate name to an element of
  112. // Certificates. Note that a certificate name can be of the form
  113. // '*.example.com' and so doesn't have to be a domain name as such.
  114. // See Config.BuildNameToCertificate
  115. // The nil value causes the first element of Certificates to be used
  116. // for all connections.
  117. NameToCertificate map[string]*Certificate
  118. // RootCAs defines the set of root certificate authorities
  119. // that clients use when verifying server certificates.
  120. // If RootCAs is nil, TLS uses the host's root CA set.
  121. RootCAs *x509.CertPool
  122. // NextProtos is a list of supported, application level protocols.
  123. NextProtos []string
  124. // ServerName is included in the client's handshake to support virtual
  125. // hosting.
  126. ServerName string
  127. // AuthenticateClient controls whether a server will request a certificate
  128. // from the client. It does not require that the client send a
  129. // certificate nor does it require that the certificate sent be
  130. // anything more than self-signed.
  131. AuthenticateClient bool
  132. // CipherSuites is a list of supported cipher suites. If CipherSuites
  133. // is nil, TLS uses a list of suites supported by the implementation.
  134. CipherSuites []uint16
  135. }
  136. func (c *Config) rand() io.Reader {
  137. r := c.Rand
  138. if r == nil {
  139. return rand.Reader
  140. }
  141. return r
  142. }
  143. func (c *Config) time() int64 {
  144. t := c.Time
  145. if t == nil {
  146. t = time.Seconds
  147. }
  148. return t()
  149. }
  150. func (c *Config) rootCAs() *x509.CertPool {
  151. s := c.RootCAs
  152. if s == nil {
  153. s = defaultRoots()
  154. }
  155. return s
  156. }
  157. func (c *Config) cipherSuites() []uint16 {
  158. s := c.CipherSuites
  159. if s == nil {
  160. s = defaultCipherSuites()
  161. }
  162. return s
  163. }
  164. // getCertificateForName returns the best certificate for the given name,
  165. // defaulting to the first element of c.Certificates if there are no good
  166. // options.
  167. func (c *Config) getCertificateForName(name string) *Certificate {
  168. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  169. // There's only one choice, so no point doing any work.
  170. return &c.Certificates[0]
  171. }
  172. name = strings.ToLower(name)
  173. for len(name) > 0 && name[len(name)-1] == '.' {
  174. name = name[:len(name)-1]
  175. }
  176. if cert, ok := c.NameToCertificate[name]; ok {
  177. return cert
  178. }
  179. // try replacing labels in the name with wildcards until we get a
  180. // match.
  181. labels := strings.Split(name, ".")
  182. for i := range labels {
  183. labels[i] = "*"
  184. candidate := strings.Join(labels, ".")
  185. if cert, ok := c.NameToCertificate[candidate]; ok {
  186. return cert
  187. }
  188. }
  189. // If nothing matches, return the first certificate.
  190. return &c.Certificates[0]
  191. }
  192. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  193. // from the CommonName and SubjectAlternateName fields of each of the leaf
  194. // certificates.
  195. func (c *Config) BuildNameToCertificate() {
  196. c.NameToCertificate = make(map[string]*Certificate)
  197. for i := range c.Certificates {
  198. cert := &c.Certificates[i]
  199. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  200. if err != nil {
  201. continue
  202. }
  203. if len(x509Cert.Subject.CommonName) > 0 {
  204. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  205. }
  206. for _, san := range x509Cert.DNSNames {
  207. c.NameToCertificate[san] = cert
  208. }
  209. }
  210. }
  211. // A Certificate is a chain of one or more certificates, leaf first.
  212. type Certificate struct {
  213. Certificate [][]byte
  214. PrivateKey *rsa.PrivateKey
  215. // OCSPStaple contains an optional OCSP response which will be served
  216. // to clients that request it.
  217. OCSPStaple []byte
  218. }
  219. // A TLS record.
  220. type record struct {
  221. contentType recordType
  222. major, minor uint8
  223. payload []byte
  224. }
  225. type handshakeMessage interface {
  226. marshal() []byte
  227. unmarshal([]byte) bool
  228. }
  229. // mutualVersion returns the protocol version to use given the advertised
  230. // version of the peer.
  231. func mutualVersion(vers uint16) (uint16, bool) {
  232. if vers < minVersion {
  233. return 0, false
  234. }
  235. if vers > maxVersion {
  236. vers = maxVersion
  237. }
  238. return vers, true
  239. }
  240. var emptyConfig Config
  241. func defaultConfig() *Config {
  242. return &emptyConfig
  243. }
  244. // Possible certificate files; stop after finding one.
  245. // On OS X we should really be using the Directory Services keychain
  246. // but that requires a lot of Mach goo to get at. Instead we use
  247. // the same root set that curl uses.
  248. var certFiles = []string{
  249. "/etc/ssl/certs/ca-certificates.crt", // Linux etc
  250. "/usr/share/curl/curl-ca-bundle.crt", // OS X
  251. }
  252. var once sync.Once
  253. func defaultRoots() *x509.CertPool {
  254. once.Do(initDefaults)
  255. return varDefaultRoots
  256. }
  257. func defaultCipherSuites() []uint16 {
  258. once.Do(initDefaults)
  259. return varDefaultCipherSuites
  260. }
  261. func initDefaults() {
  262. initDefaultRoots()
  263. initDefaultCipherSuites()
  264. }
  265. var varDefaultRoots *x509.CertPool
  266. func initDefaultRoots() {
  267. roots := x509.NewCertPool()
  268. for _, file := range certFiles {
  269. data, err := ioutil.ReadFile(file)
  270. if err == nil {
  271. roots.AppendCertsFromPEM(data)
  272. break
  273. }
  274. }
  275. varDefaultRoots = roots
  276. }
  277. var varDefaultCipherSuites []uint16
  278. func initDefaultCipherSuites() {
  279. varDefaultCipherSuites = make([]uint16, len(cipherSuites))
  280. i := 0
  281. for id := range cipherSuites {
  282. varDefaultCipherSuites[i] = id
  283. i++
  284. }
  285. }