pkcs12.go 9.7 KB

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