pkcs12.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. blocks := make([]*pem.Block, 0, len(bags))
  93. for _, bag := range bags {
  94. block, err := convertBag(&bag, encodedPassword)
  95. if err != nil {
  96. return nil, err
  97. }
  98. blocks = append(blocks, block)
  99. }
  100. return blocks, nil
  101. }
  102. func convertBag(bag *safeBag, password []byte) (*pem.Block, error) {
  103. block := &pem.Block{
  104. Headers: make(map[string]string),
  105. }
  106. for _, attribute := range bag.Attributes {
  107. k, v, err := convertAttribute(&attribute)
  108. if err != nil {
  109. return nil, err
  110. }
  111. block.Headers[k] = v
  112. }
  113. switch {
  114. case bag.Id.Equal(oidCertBag):
  115. block.Type = certificateType
  116. certsData, err := decodeCertBag(bag.Value.Bytes)
  117. if err != nil {
  118. return nil, err
  119. }
  120. block.Bytes = certsData
  121. case bag.Id.Equal(oidPKCS8ShroundedKeyBag):
  122. block.Type = privateKeyType
  123. key, err := decodePkcs8ShroudedKeyBag(bag.Value.Bytes, password)
  124. if err != nil {
  125. return nil, err
  126. }
  127. switch key := key.(type) {
  128. case *rsa.PrivateKey:
  129. block.Bytes = x509.MarshalPKCS1PrivateKey(key)
  130. case *ecdsa.PrivateKey:
  131. block.Bytes, err = x509.MarshalECPrivateKey(key)
  132. if err != nil {
  133. return nil, err
  134. }
  135. default:
  136. return nil, errors.New("found unknown private key type in PKCS#8 wrapping")
  137. }
  138. default:
  139. return nil, errors.New("don't know how to convert a safe bag of type " + bag.Id.String())
  140. }
  141. return block, nil
  142. }
  143. func convertAttribute(attribute *pkcs12Attribute) (key, value string, err error) {
  144. isString := false
  145. switch {
  146. case attribute.Id.Equal(oidFriendlyName):
  147. key = "friendlyName"
  148. isString = true
  149. case attribute.Id.Equal(oidLocalKeyID):
  150. key = "localKeyId"
  151. case attribute.Id.Equal(oidMicrosoftCSPName):
  152. // This key is chosen to match OpenSSL.
  153. key = "Microsoft CSP Name"
  154. isString = true
  155. default:
  156. return "", "", errors.New("pkcs12: unknown attribute with OID " + attribute.Id.String())
  157. }
  158. if isString {
  159. if err := unmarshal(attribute.Value.Bytes, &attribute.Value); err != nil {
  160. return "", "", err
  161. }
  162. if value, err = decodeBMPString(attribute.Value.Bytes); err != nil {
  163. return "", "", err
  164. }
  165. } else {
  166. var id []byte
  167. if err := unmarshal(attribute.Value.Bytes, &id); err != nil {
  168. return "", "", err
  169. }
  170. value = hex.EncodeToString(id)
  171. }
  172. return key, value, nil
  173. }
  174. // Decode extracts a certificate and private key from pfxData. This function
  175. // assumes that there is only one certificate and only one private key in the
  176. // pfxData.
  177. func Decode(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, err error) {
  178. encodedPassword, err := bmpString(password)
  179. if err != nil {
  180. return nil, nil, err
  181. }
  182. bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword)
  183. if err != nil {
  184. return nil, nil, err
  185. }
  186. if len(bags) != 2 {
  187. err = errors.New("pkcs12: expected exactly two safe bags in the PFX PDU")
  188. return
  189. }
  190. for _, bag := range bags {
  191. switch {
  192. case bag.Id.Equal(oidCertBag):
  193. if certificate != nil {
  194. err = errors.New("pkcs12: expected exactly one certificate bag")
  195. }
  196. certsData, err := decodeCertBag(bag.Value.Bytes)
  197. if err != nil {
  198. return nil, nil, err
  199. }
  200. certs, err := x509.ParseCertificates(certsData)
  201. if err != nil {
  202. return nil, nil, err
  203. }
  204. if len(certs) != 1 {
  205. err = errors.New("pkcs12: expected exactly one certificate in the certBag")
  206. return nil, nil, err
  207. }
  208. certificate = certs[0]
  209. case bag.Id.Equal(oidPKCS8ShroundedKeyBag):
  210. if privateKey != nil {
  211. err = errors.New("pkcs12: expected exactly one key bag")
  212. }
  213. if privateKey, err = decodePkcs8ShroudedKeyBag(bag.Value.Bytes, encodedPassword); err != nil {
  214. return nil, nil, err
  215. }
  216. }
  217. }
  218. if certificate == nil {
  219. return nil, nil, errors.New("pkcs12: certificate missing")
  220. }
  221. if privateKey == nil {
  222. return nil, nil, errors.New("pkcs12: private key missing")
  223. }
  224. return
  225. }
  226. func getSafeContents(p12Data, password []byte) (bags []safeBag, updatedPassword []byte, err error) {
  227. pfx := new(pfxPdu)
  228. if err := unmarshal(p12Data, pfx); err != nil {
  229. return nil, nil, errors.New("pkcs12: error reading P12 data: " + err.Error())
  230. }
  231. if pfx.Version != 3 {
  232. return nil, nil, NotImplementedError("can only decode v3 PFX PDU's")
  233. }
  234. if !pfx.AuthSafe.ContentType.Equal(oidDataContentType) {
  235. return nil, nil, NotImplementedError("only password-protected PFX is implemented")
  236. }
  237. // unmarshal the explicit bytes in the content for type 'data'
  238. if err := unmarshal(pfx.AuthSafe.Content.Bytes, &pfx.AuthSafe.Content); err != nil {
  239. return nil, nil, err
  240. }
  241. if len(pfx.MacData.Mac.Algorithm.Algorithm) == 0 {
  242. return nil, nil, errors.New("pkcs12: no MAC in data")
  243. }
  244. if err := verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password); err != nil {
  245. if err == ErrIncorrectPassword && len(password) == 2 && password[0] == 0 && password[1] == 0 {
  246. // some implementations use an empty byte array
  247. // for the empty string password try one more
  248. // time with empty-empty password
  249. password = nil
  250. err = verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password)
  251. }
  252. if err != nil {
  253. return nil, nil, err
  254. }
  255. }
  256. var authenticatedSafe []contentInfo
  257. if err := unmarshal(pfx.AuthSafe.Content.Bytes, &authenticatedSafe); err != nil {
  258. return nil, nil, err
  259. }
  260. if len(authenticatedSafe) != 2 {
  261. return nil, nil, NotImplementedError("expected exactly two items in the authenticated safe")
  262. }
  263. for _, ci := range authenticatedSafe {
  264. var data []byte
  265. switch {
  266. case ci.ContentType.Equal(oidDataContentType):
  267. if err := unmarshal(ci.Content.Bytes, &data); err != nil {
  268. return nil, nil, err
  269. }
  270. case ci.ContentType.Equal(oidEncryptedDataContentType):
  271. var encryptedData encryptedData
  272. if err := unmarshal(ci.Content.Bytes, &encryptedData); err != nil {
  273. return nil, nil, err
  274. }
  275. if encryptedData.Version != 0 {
  276. return nil, nil, NotImplementedError("only version 0 of EncryptedData is supported")
  277. }
  278. if data, err = pbDecrypt(encryptedData.EncryptedContentInfo, password); err != nil {
  279. return nil, nil, err
  280. }
  281. default:
  282. return nil, nil, NotImplementedError("only data and encryptedData content types are supported in authenticated safe")
  283. }
  284. var safeContents []safeBag
  285. if err := unmarshal(data, &safeContents); err != nil {
  286. return nil, nil, err
  287. }
  288. bags = append(bags, safeContents...)
  289. }
  290. return bags, password, nil
  291. }