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.
 
 
 
 
 
 

335 line
9.6 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/rsa"
  8. "crypto/subtle"
  9. "crypto/x509"
  10. "io"
  11. "os"
  12. )
  13. func (c *Conn) clientHandshake() os.Error {
  14. finishedHash := newFinishedHash()
  15. if c.config == nil {
  16. c.config = defaultConfig()
  17. }
  18. hello := &clientHelloMsg{
  19. vers: maxVersion,
  20. cipherSuites: c.config.cipherSuites(),
  21. compressionMethods: []uint8{compressionNone},
  22. random: make([]byte, 32),
  23. ocspStapling: true,
  24. serverName: c.config.ServerName,
  25. supportedCurves: []uint16{curveP256, curveP384, curveP521},
  26. supportedPoints: []uint8{pointFormatUncompressed},
  27. nextProtoNeg: len(c.config.NextProtos) > 0,
  28. }
  29. t := uint32(c.config.time())
  30. hello.random[0] = byte(t >> 24)
  31. hello.random[1] = byte(t >> 16)
  32. hello.random[2] = byte(t >> 8)
  33. hello.random[3] = byte(t)
  34. _, err := io.ReadFull(c.config.rand(), hello.random[4:])
  35. if err != nil {
  36. c.sendAlert(alertInternalError)
  37. return os.ErrorString("short read from Rand")
  38. }
  39. finishedHash.Write(hello.marshal())
  40. c.writeRecord(recordTypeHandshake, hello.marshal())
  41. msg, err := c.readHandshake()
  42. if err != nil {
  43. return err
  44. }
  45. serverHello, ok := msg.(*serverHelloMsg)
  46. if !ok {
  47. return c.sendAlert(alertUnexpectedMessage)
  48. }
  49. finishedHash.Write(serverHello.marshal())
  50. vers, ok := mutualVersion(serverHello.vers)
  51. if !ok {
  52. return c.sendAlert(alertProtocolVersion)
  53. }
  54. c.vers = vers
  55. c.haveVers = true
  56. if serverHello.compressionMethod != compressionNone {
  57. return c.sendAlert(alertUnexpectedMessage)
  58. }
  59. if !hello.nextProtoNeg && serverHello.nextProtoNeg {
  60. c.sendAlert(alertHandshakeFailure)
  61. return os.ErrorString("server advertised unrequested NPN")
  62. }
  63. suite, suiteId := mutualCipherSuite(c.config.cipherSuites(), serverHello.cipherSuite)
  64. if suite == nil {
  65. return c.sendAlert(alertHandshakeFailure)
  66. }
  67. msg, err = c.readHandshake()
  68. if err != nil {
  69. return err
  70. }
  71. certMsg, ok := msg.(*certificateMsg)
  72. if !ok || len(certMsg.certificates) == 0 {
  73. return c.sendAlert(alertUnexpectedMessage)
  74. }
  75. finishedHash.Write(certMsg.marshal())
  76. certs := make([]*x509.Certificate, len(certMsg.certificates))
  77. chain := NewCASet()
  78. for i, asn1Data := range certMsg.certificates {
  79. cert, err := x509.ParseCertificate(asn1Data)
  80. if err != nil {
  81. c.sendAlert(alertBadCertificate)
  82. return os.ErrorString("failed to parse certificate from server: " + err.String())
  83. }
  84. certs[i] = cert
  85. chain.AddCert(cert)
  86. }
  87. // If we don't have a root CA set configured then anything is accepted.
  88. // TODO(rsc): Find certificates for OS X 10.6.
  89. for cur := certs[0]; c.config.RootCAs != nil; {
  90. parent := c.config.RootCAs.FindVerifiedParent(cur)
  91. if parent != nil {
  92. break
  93. }
  94. parent = chain.FindVerifiedParent(cur)
  95. if parent == nil {
  96. c.sendAlert(alertBadCertificate)
  97. return os.ErrorString("could not find root certificate for chain")
  98. }
  99. if !parent.BasicConstraintsValid || !parent.IsCA {
  100. c.sendAlert(alertBadCertificate)
  101. return os.ErrorString("intermediate certificate does not have CA bit set")
  102. }
  103. // KeyUsage status flags are ignored. From Engineering
  104. // Security, Peter Gutmann: A European government CA marked its
  105. // signing certificates as being valid for encryption only, but
  106. // no-one noticed. Another European CA marked its signature
  107. // keys as not being valid for signatures. A different CA
  108. // marked its own trusted root certificate as being invalid for
  109. // certificate signing. Another national CA distributed a
  110. // certificate to be used to encrypt data for the country’s tax
  111. // authority that was marked as only being usable for digital
  112. // signatures but not for encryption. Yet another CA reversed
  113. // the order of the bit flags in the keyUsage due to confusion
  114. // over encoding endianness, essentially setting a random
  115. // keyUsage in certificates that it issued. Another CA created
  116. // a self-invalidating certificate by adding a certificate
  117. // policy statement stipulating that the certificate had to be
  118. // used strictly as specified in the keyUsage, and a keyUsage
  119. // containing a flag indicating that the RSA encryption key
  120. // could only be used for Diffie-Hellman key agreement.
  121. cur = parent
  122. }
  123. if _, ok := certs[0].PublicKey.(*rsa.PublicKey); !ok {
  124. return c.sendAlert(alertUnsupportedCertificate)
  125. }
  126. c.peerCertificates = certs
  127. if serverHello.certStatus {
  128. msg, err = c.readHandshake()
  129. if err != nil {
  130. return err
  131. }
  132. cs, ok := msg.(*certificateStatusMsg)
  133. if !ok {
  134. return c.sendAlert(alertUnexpectedMessage)
  135. }
  136. finishedHash.Write(cs.marshal())
  137. if cs.statusType == statusTypeOCSP {
  138. c.ocspResponse = cs.response
  139. }
  140. }
  141. msg, err = c.readHandshake()
  142. if err != nil {
  143. return err
  144. }
  145. keyAgreement := suite.ka()
  146. skx, ok := msg.(*serverKeyExchangeMsg)
  147. if ok {
  148. finishedHash.Write(skx.marshal())
  149. err = keyAgreement.processServerKeyExchange(c.config, hello, serverHello, certs[0], skx)
  150. if err != nil {
  151. c.sendAlert(alertUnexpectedMessage)
  152. return err
  153. }
  154. msg, err = c.readHandshake()
  155. if err != nil {
  156. return err
  157. }
  158. }
  159. transmitCert := false
  160. certReq, ok := msg.(*certificateRequestMsg)
  161. if ok {
  162. // We only accept certificates with RSA keys.
  163. rsaAvail := false
  164. for _, certType := range certReq.certificateTypes {
  165. if certType == certTypeRSASign {
  166. rsaAvail = true
  167. break
  168. }
  169. }
  170. // For now, only send a certificate back if the server gives us an
  171. // empty list of certificateAuthorities.
  172. //
  173. // RFC 4346 on the certificateAuthorities field:
  174. // A list of the distinguished names of acceptable certificate
  175. // authorities. These distinguished names may specify a desired
  176. // distinguished name for a root CA or for a subordinate CA; thus,
  177. // this message can be used to describe both known roots and a
  178. // desired authorization space. If the certificate_authorities
  179. // list is empty then the client MAY send any certificate of the
  180. // appropriate ClientCertificateType, unless there is some
  181. // external arrangement to the contrary.
  182. if rsaAvail && len(certReq.certificateAuthorities) == 0 {
  183. transmitCert = true
  184. }
  185. finishedHash.Write(certReq.marshal())
  186. msg, err = c.readHandshake()
  187. if err != nil {
  188. return err
  189. }
  190. }
  191. shd, ok := msg.(*serverHelloDoneMsg)
  192. if !ok {
  193. return c.sendAlert(alertUnexpectedMessage)
  194. }
  195. finishedHash.Write(shd.marshal())
  196. var cert *x509.Certificate
  197. if transmitCert {
  198. certMsg = new(certificateMsg)
  199. if len(c.config.Certificates) > 0 {
  200. cert, err = x509.ParseCertificate(c.config.Certificates[0].Certificate[0])
  201. if err == nil && cert.PublicKeyAlgorithm == x509.RSA {
  202. certMsg.certificates = c.config.Certificates[0].Certificate
  203. } else {
  204. cert = nil
  205. }
  206. }
  207. finishedHash.Write(certMsg.marshal())
  208. c.writeRecord(recordTypeHandshake, certMsg.marshal())
  209. }
  210. preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hello, certs[0])
  211. if err != nil {
  212. c.sendAlert(alertInternalError)
  213. return err
  214. }
  215. if ckx != nil {
  216. finishedHash.Write(ckx.marshal())
  217. c.writeRecord(recordTypeHandshake, ckx.marshal())
  218. }
  219. if cert != nil {
  220. certVerify := new(certificateVerifyMsg)
  221. var digest [36]byte
  222. copy(digest[0:16], finishedHash.serverMD5.Sum())
  223. copy(digest[16:36], finishedHash.serverSHA1.Sum())
  224. signed, err := rsa.SignPKCS1v15(c.config.rand(), c.config.Certificates[0].PrivateKey, crypto.MD5SHA1, digest[0:])
  225. if err != nil {
  226. return c.sendAlert(alertInternalError)
  227. }
  228. certVerify.signature = signed
  229. finishedHash.Write(certVerify.marshal())
  230. c.writeRecord(recordTypeHandshake, certVerify.marshal())
  231. }
  232. masterSecret, clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  233. keysFromPreMasterSecret10(preMasterSecret, hello.random, serverHello.random, suite.macLen, suite.keyLen, suite.ivLen)
  234. clientCipher := suite.cipher(clientKey, clientIV, false /* not for reading */ )
  235. clientHash := suite.mac(clientMAC)
  236. c.out.prepareCipherSpec(clientCipher, clientHash)
  237. c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
  238. if serverHello.nextProtoNeg {
  239. nextProto := new(nextProtoMsg)
  240. proto, fallback := mutualProtocol(c.config.NextProtos, serverHello.nextProtos)
  241. nextProto.proto = proto
  242. c.clientProtocol = proto
  243. c.clientProtocolFallback = fallback
  244. finishedHash.Write(nextProto.marshal())
  245. c.writeRecord(recordTypeHandshake, nextProto.marshal())
  246. }
  247. finished := new(finishedMsg)
  248. finished.verifyData = finishedHash.clientSum(masterSecret)
  249. finishedHash.Write(finished.marshal())
  250. c.writeRecord(recordTypeHandshake, finished.marshal())
  251. serverCipher := suite.cipher(serverKey, serverIV, true /* for reading */ )
  252. serverHash := suite.mac(serverMAC)
  253. c.in.prepareCipherSpec(serverCipher, serverHash)
  254. c.readRecord(recordTypeChangeCipherSpec)
  255. if c.err != nil {
  256. return c.err
  257. }
  258. msg, err = c.readHandshake()
  259. if err != nil {
  260. return err
  261. }
  262. serverFinished, ok := msg.(*finishedMsg)
  263. if !ok {
  264. return c.sendAlert(alertUnexpectedMessage)
  265. }
  266. verify := finishedHash.serverSum(masterSecret)
  267. if len(verify) != len(serverFinished.verifyData) ||
  268. subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
  269. return c.sendAlert(alertHandshakeFailure)
  270. }
  271. c.handshakeComplete = true
  272. c.cipherSuite = suiteId
  273. return nil
  274. }
  275. // mutualProtocol finds the mutual Next Protocol Negotiation protocol given the
  276. // set of client and server supported protocols. The set of client supported
  277. // protocols must not be empty. It returns the resulting protocol and flag
  278. // indicating if the fallback case was reached.
  279. func mutualProtocol(clientProtos, serverProtos []string) (string, bool) {
  280. for _, s := range serverProtos {
  281. for _, c := range clientProtos {
  282. if s == c {
  283. return s, false
  284. }
  285. }
  286. }
  287. return clientProtos[0], true
  288. }