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.
 
 
 

347 lines
9.2 KiB

  1. // Copyright 2015 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 pkcs12 implements some of PKCS#12.
  5. //
  6. // This implementation is distilled from https://tools.ietf.org/html/rfc7292
  7. // and referenced documents. It is intended for decoding P12/PFX-stored
  8. // certificates and keys for use with the crypto/tls package.
  9. package pkcs12
  10. import (
  11. "crypto/ecdsa"
  12. "crypto/rsa"
  13. "crypto/x509"
  14. "crypto/x509/pkix"
  15. "encoding/asn1"
  16. "encoding/hex"
  17. "encoding/pem"
  18. "errors"
  19. )
  20. var (
  21. oidDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 1})
  22. oidEncryptedDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 6})
  23. oidFriendlyName = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 20})
  24. oidLocalKeyID = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 21})
  25. oidMicrosoftCSPName = asn1.ObjectIdentifier([]int{1, 3, 6, 1, 4, 1, 311, 17, 1})
  26. )
  27. type pfxPdu struct {
  28. Version int
  29. AuthSafe contentInfo
  30. MacData macData `asn1:"optional"`
  31. }
  32. type contentInfo struct {
  33. ContentType asn1.ObjectIdentifier
  34. Content asn1.RawValue `asn1:"tag:0,explicit,optional"`
  35. }
  36. type encryptedData struct {
  37. Version int
  38. EncryptedContentInfo encryptedContentInfo
  39. }
  40. type encryptedContentInfo struct {
  41. ContentType asn1.ObjectIdentifier
  42. ContentEncryptionAlgorithm pkix.AlgorithmIdentifier
  43. EncryptedContent []byte `asn1:"tag:0,optional"`
  44. }
  45. func (i encryptedContentInfo) Algorithm() pkix.AlgorithmIdentifier {
  46. return i.ContentEncryptionAlgorithm
  47. }
  48. func (i encryptedContentInfo) Data() []byte { return i.EncryptedContent }
  49. type safeBag struct {
  50. Id asn1.ObjectIdentifier
  51. Value asn1.RawValue `asn1:"tag:0,explicit"`
  52. Attributes []pkcs12Attribute `asn1:"set,optional"`
  53. }
  54. type pkcs12Attribute struct {
  55. Id asn1.ObjectIdentifier
  56. Value asn1.RawValue `asn1:"set"`
  57. }
  58. type encryptedPrivateKeyInfo struct {
  59. AlgorithmIdentifier pkix.AlgorithmIdentifier
  60. EncryptedData []byte
  61. }
  62. func (i encryptedPrivateKeyInfo) Algorithm() pkix.AlgorithmIdentifier {
  63. return i.AlgorithmIdentifier
  64. }
  65. func (i encryptedPrivateKeyInfo) Data() []byte {
  66. return i.EncryptedData
  67. }
  68. // PEM block types
  69. const (
  70. certificateType = "CERTIFICATE"
  71. privateKeyType = "PRIVATE KEY"
  72. )
  73. // unmarshal calls asn1.Unmarshal, but also returns an error if there is any
  74. // trailing data after unmarshaling.
  75. func unmarshal(in []byte, out interface{}) error {
  76. trailing, err := asn1.Unmarshal(in, out)
  77. if err != nil {
  78. return err
  79. }
  80. if len(trailing) != 0 {
  81. return errors.New("pkcs12: trailing data found")
  82. }
  83. return nil
  84. }
  85. // ConvertToPEM converts all "safe bags" contained in pfxData to PEM blocks.
  86. func ToPEM(pfxData []byte, password string) ([]*pem.Block, error) {
  87. encodedPassword, err := bmpString(password)
  88. if err != nil {
  89. return nil, ErrIncorrectPassword
  90. }
  91. bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword)
  92. if err != nil {
  93. return nil, err
  94. }
  95. blocks := make([]*pem.Block, 0, len(bags))
  96. for _, bag := range bags {
  97. block, err := convertBag(&bag, encodedPassword)
  98. if err != nil {
  99. return nil, err
  100. }
  101. blocks = append(blocks, block)
  102. }
  103. return blocks, nil
  104. }
  105. func convertBag(bag *safeBag, password []byte) (*pem.Block, error) {
  106. block := &pem.Block{
  107. Headers: make(map[string]string),
  108. }
  109. for _, attribute := range bag.Attributes {
  110. k, v, err := convertAttribute(&attribute)
  111. if err != nil {
  112. return nil, err
  113. }
  114. block.Headers[k] = v
  115. }
  116. switch {
  117. case bag.Id.Equal(oidCertBag):
  118. block.Type = certificateType
  119. certsData, err := decodeCertBag(bag.Value.Bytes)
  120. if err != nil {
  121. return nil, err
  122. }
  123. block.Bytes = certsData
  124. case bag.Id.Equal(oidPKCS8ShroundedKeyBag):
  125. block.Type = privateKeyType
  126. key, err := decodePkcs8ShroudedKeyBag(bag.Value.Bytes, password)
  127. if err != nil {
  128. return nil, err
  129. }
  130. switch key := key.(type) {
  131. case *rsa.PrivateKey:
  132. block.Bytes = x509.MarshalPKCS1PrivateKey(key)
  133. case *ecdsa.PrivateKey:
  134. block.Bytes, err = x509.MarshalECPrivateKey(key)
  135. if err != nil {
  136. return nil, err
  137. }
  138. default:
  139. return nil, errors.New("found unknown private key type in PKCS#8 wrapping")
  140. }
  141. default:
  142. return nil, errors.New("don't know how to convert a safe bag of type " + bag.Id.String())
  143. }
  144. return block, nil
  145. }
  146. func convertAttribute(attribute *pkcs12Attribute) (key, value string, err error) {
  147. isString := false
  148. switch {
  149. case attribute.Id.Equal(oidFriendlyName):
  150. key = "friendlyName"
  151. isString = true
  152. case attribute.Id.Equal(oidLocalKeyID):
  153. key = "localKeyId"
  154. case attribute.Id.Equal(oidMicrosoftCSPName):
  155. // This key is chosen to match OpenSSL.
  156. key = "Microsoft CSP Name"
  157. isString = true
  158. default:
  159. return "", "", errors.New("pkcs12: unknown attribute with OID " + attribute.Id.String())
  160. }
  161. if isString {
  162. if err := unmarshal(attribute.Value.Bytes, &attribute.Value); err != nil {
  163. return "", "", err
  164. }
  165. if value, err = decodeBMPString(attribute.Value.Bytes); err != nil {
  166. return "", "", err
  167. }
  168. } else {
  169. var id []byte
  170. if err := unmarshal(attribute.Value.Bytes, &id); err != nil {
  171. return "", "", err
  172. }
  173. value = hex.EncodeToString(id)
  174. }
  175. return key, value, nil
  176. }
  177. // Decode extracts a certificate and private key from pfxData. This function
  178. // assumes that there is only one certificate and only one private key in the
  179. // pfxData.
  180. func Decode(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, err error) {
  181. encodedPassword, err := bmpString(password)
  182. if err != nil {
  183. return nil, nil, err
  184. }
  185. bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword)
  186. if err != nil {
  187. return nil, nil, err
  188. }
  189. if len(bags) != 2 {
  190. err = errors.New("pkcs12: expected exactly two safe bags in the PFX PDU")
  191. return
  192. }
  193. for _, bag := range bags {
  194. switch {
  195. case bag.Id.Equal(oidCertBag):
  196. if certificate != nil {
  197. err = errors.New("pkcs12: expected exactly one certificate bag")
  198. }
  199. certsData, err := decodeCertBag(bag.Value.Bytes)
  200. if err != nil {
  201. return nil, nil, err
  202. }
  203. certs, err := x509.ParseCertificates(certsData)
  204. if err != nil {
  205. return nil, nil, err
  206. }
  207. if len(certs) != 1 {
  208. err = errors.New("pkcs12: expected exactly one certificate in the certBag")
  209. return nil, nil, err
  210. }
  211. certificate = certs[0]
  212. case bag.Id.Equal(oidPKCS8ShroundedKeyBag):
  213. if privateKey != nil {
  214. err = errors.New("pkcs12: expected exactly one key bag")
  215. }
  216. if privateKey, err = decodePkcs8ShroudedKeyBag(bag.Value.Bytes, encodedPassword); err != nil {
  217. return nil, nil, err
  218. }
  219. }
  220. }
  221. if certificate == nil {
  222. return nil, nil, errors.New("pkcs12: certificate missing")
  223. }
  224. if privateKey == nil {
  225. return nil, nil, errors.New("pkcs12: private key missing")
  226. }
  227. return
  228. }
  229. func getSafeContents(p12Data, password []byte) (bags []safeBag, updatedPassword []byte, err error) {
  230. pfx := new(pfxPdu)
  231. if err := unmarshal(p12Data, pfx); err != nil {
  232. return nil, nil, errors.New("pkcs12: error reading P12 data: " + err.Error())
  233. }
  234. if pfx.Version != 3 {
  235. return nil, nil, NotImplementedError("can only decode v3 PFX PDU's")
  236. }
  237. if !pfx.AuthSafe.ContentType.Equal(oidDataContentType) {
  238. return nil, nil, NotImplementedError("only password-protected PFX is implemented")
  239. }
  240. // unmarshal the explicit bytes in the content for type 'data'
  241. if err := unmarshal(pfx.AuthSafe.Content.Bytes, &pfx.AuthSafe.Content); err != nil {
  242. return nil, nil, err
  243. }
  244. if len(pfx.MacData.Mac.Algorithm.Algorithm) == 0 {
  245. return nil, nil, errors.New("pkcs12: no MAC in data")
  246. }
  247. if err := verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password); err != nil {
  248. if err == ErrIncorrectPassword && len(password) == 2 && password[0] == 0 && password[1] == 0 {
  249. // some implementations use an empty byte array
  250. // for the empty string password try one more
  251. // time with empty-empty password
  252. password = nil
  253. err = verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password)
  254. }
  255. if err != nil {
  256. return nil, nil, err
  257. }
  258. }
  259. var authenticatedSafe []contentInfo
  260. if err := unmarshal(pfx.AuthSafe.Content.Bytes, &authenticatedSafe); err != nil {
  261. return nil, nil, err
  262. }
  263. if len(authenticatedSafe) != 2 {
  264. return nil, nil, NotImplementedError("expected exactly two items in the authenticated safe")
  265. }
  266. for _, ci := range authenticatedSafe {
  267. var data []byte
  268. switch {
  269. case ci.ContentType.Equal(oidDataContentType):
  270. if err := unmarshal(ci.Content.Bytes, &data); err != nil {
  271. return nil, nil, err
  272. }
  273. case ci.ContentType.Equal(oidEncryptedDataContentType):
  274. var encryptedData encryptedData
  275. if err := unmarshal(ci.Content.Bytes, &encryptedData); err != nil {
  276. return nil, nil, err
  277. }
  278. if encryptedData.Version != 0 {
  279. return nil, nil, NotImplementedError("only version 0 of EncryptedData is supported")
  280. }
  281. if data, err = pbDecrypt(encryptedData.EncryptedContentInfo, password); err != nil {
  282. return nil, nil, err
  283. }
  284. default:
  285. return nil, nil, NotImplementedError("only data and encryptedData content types are supported in authenticated safe")
  286. }
  287. var safeContents []safeBag
  288. if err := unmarshal(data, &safeContents); err != nil {
  289. return nil, nil, err
  290. }
  291. bags = append(bags, safeContents...)
  292. }
  293. return bags, password, nil
  294. }