pkcs12.go 9.3 KB

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