| 1 |
|
| 2 |
package pkcs7 |
| 3 |
|
| 4 |
import ( |
| 5 |
x509 "github.com/avast/apkverifier/internal/x509andr" |
| 6 |
"bytes" |
| 7 |
"crypto" |
| 8 |
"crypto/aes" |
| 9 |
"crypto/cipher" |
| 10 |
"crypto/des" |
| 11 |
"crypto/hmac" |
| 12 |
"crypto/rand" |
| 13 |
"crypto/rsa" |
| 14 |
go_x509 "crypto/x509" |
| 15 |
"crypto/x509/pkix" |
| 16 |
"encoding/asn1" |
| 17 |
"errors" |
| 18 |
"fmt" |
| 19 |
"math/big" |
| 20 |
"sort" |
| 21 |
"time" |
| 22 |
"reflect" |
| 23 |
"sync/atomic" |
| 24 |
"os" |
| 25 |
|
| 26 |
_ "crypto/sha1" |
| 27 |
) |
| 28 |
|
| 29 |
|
| 30 |
type PKCS7 struct { |
| 31 |
Content []byte |
| 32 |
Certificates []*go_x509.Certificate |
| 33 |
CRLs []pkix.CertificateList |
| 34 |
Signers []signerInfo |
| 35 |
ContentType asn1.ObjectIdentifier |
| 36 |
raw interface{} |
| 37 |
} |
| 38 |
|
| 39 |
type contentInfo struct { |
| 40 |
ContentType asn1.ObjectIdentifier |
| 41 |
Content asn1.RawValue `asn1:"explicit,optional,tag:0"` |
| 42 |
} |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
var ErrUnsupportedContentType = errors.New("pkcs7: cannot parse data: unimplemented content type") |
| 48 |
|
| 49 |
type unsignedData []byte |
| 50 |
|
| 51 |
var ( |
| 52 |
oidData = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 1} |
| 53 |
oidSignedData = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 2} |
| 54 |
oidEnvelopedData = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 3} |
| 55 |
oidSignedAndEnvelopedData = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 4} |
| 56 |
oidDigestedData = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 5} |
| 57 |
oidEncryptedData = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 6} |
| 58 |
oidAttributeContentType = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 3} |
| 59 |
oidAttributeMessageDigest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 4} |
| 60 |
oidAttributeSigningTime = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 5} |
| 61 |
) |
| 62 |
|
| 63 |
type signedData struct { |
| 64 |
Version int `asn1:"default:1"` |
| 65 |
DigestAlgorithmIdentifiers []pkix.AlgorithmIdentifier `asn1:"set"` |
| 66 |
ContentInfo contentInfo |
| 67 |
Certificates rawCertificates `asn1:"optional,tag:0"` |
| 68 |
CRLs []pkix.CertificateList `asn1:"optional,tag:1"` |
| 69 |
SignerInfos []signerInfo `asn1:"set"` |
| 70 |
} |
| 71 |
|
| 72 |
type rawCertificates struct { |
| 73 |
Raw asn1.RawContent |
| 74 |
} |
| 75 |
|
| 76 |
type envelopedData struct { |
| 77 |
Version int |
| 78 |
RecipientInfos []recipientInfo `asn1:"set"` |
| 79 |
EncryptedContentInfo encryptedContentInfo |
| 80 |
} |
| 81 |
|
| 82 |
type recipientInfo struct { |
| 83 |
Version int |
| 84 |
IssuerAndSerialNumber issuerAndSerial |
| 85 |
KeyEncryptionAlgorithm pkix.AlgorithmIdentifier |
| 86 |
EncryptedKey []byte |
| 87 |
} |
| 88 |
|
| 89 |
type encryptedContentInfo struct { |
| 90 |
ContentType asn1.ObjectIdentifier |
| 91 |
ContentEncryptionAlgorithm pkix.AlgorithmIdentifier |
| 92 |
EncryptedContent asn1.RawValue `asn1:"tag:0,optional,explicit"` |
| 93 |
} |
| 94 |
|
| 95 |
type attribute struct { |
| 96 |
Type asn1.ObjectIdentifier |
| 97 |
Value asn1.RawValue `asn1:"set"` |
| 98 |
} |
| 99 |
|
| 100 |
type SignerAttribute struct { |
| 101 |
Type asn1.ObjectIdentifier |
| 102 |
Value asn1.RawValue `asn1:"set"` |
| 103 |
} |
| 104 |
|
| 105 |
type issuerAndSerial struct { |
| 106 |
IssuerName asn1.RawValue |
| 107 |
SerialNumber *big.Int |
| 108 |
} |
| 109 |
|
| 110 |
type IssuerAndSerial struct { |
| 111 |
IssuerName asn1.RawValue |
| 112 |
SerialNumber *big.Int |
| 113 |
} |
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
type MessageDigestMismatchError struct { |
| 118 |
ExpectedDigest []byte |
| 119 |
ActualDigest []byte |
| 120 |
} |
| 121 |
|
| 122 |
func (err *MessageDigestMismatchError) Error() string { |
| 123 |
return fmt.Sprintf("pkcs7: Message digest mismatch\n\tExpected: %X\n\tActual : %X", err.ExpectedDigest, err.ActualDigest) |
| 124 |
} |
| 125 |
|
| 126 |
type signerInfo struct { |
| 127 |
Version int `asn1:"default:1"` |
| 128 |
IssuerAndSerialNumber issuerAndSerial |
| 129 |
DigestAlgorithm pkix.AlgorithmIdentifier |
| 130 |
AuthenticatedAttributes []attribute `asn1:"optional,tag:0"` |
| 131 |
DigestEncryptionAlgorithm pkix.AlgorithmIdentifier |
| 132 |
EncryptedDigest []byte |
| 133 |
UnauthenticatedAttributes []attribute `asn1:"optional,tag:1"` |
| 134 |
} |
| 135 |
|
| 136 |
type SignerInfo struct { |
| 137 |
Version int `asn1:"default:1"` |
| 138 |
IssuerAndSerialNumber IssuerAndSerial |
| 139 |
DigestAlgorithm pkix.AlgorithmIdentifier |
| 140 |
AuthenticatedAttributes []SignerAttribute `asn1:"optional,tag:0"` |
| 141 |
DigestEncryptionAlgorithm pkix.AlgorithmIdentifier |
| 142 |
EncryptedDigest []byte |
| 143 |
UnauthenticatedAttributes []SignerAttribute `asn1:"optional,tag:1"` |
| 144 |
} |
| 145 |
|
| 146 |
|
| 147 |
func Parse(data []byte) (p7 *PKCS7, err error) { |
| 148 |
if len(data) == 0 { |
| 149 |
return nil, errors.New("pkcs7: input data is empty") |
| 150 |
} |
| 151 |
var info contentInfo |
| 152 |
der, err := ber2der(data) |
| 153 |
if err != nil { |
| 154 |
return nil, err |
| 155 |
} |
| 156 |
rest, err := asn1.Unmarshal(der, &info) |
| 157 |
if len(rest) > 0 { |
| 158 |
err = asn1.SyntaxError{Msg: "trailing data"} |
| 159 |
return |
| 160 |
} |
| 161 |
if err != nil { |
| 162 |
return |
| 163 |
} |
| 164 |
|
| 165 |
|
| 166 |
switch { |
| 167 |
case info.ContentType.Equal(oidSignedData): |
| 168 |
return parseSignedData(info.Content.Bytes) |
| 169 |
case info.ContentType.Equal(oidEnvelopedData): |
| 170 |
return parseEnvelopedData(info.Content.Bytes) |
| 171 |
} |
| 172 |
|
| 173 |
return nil, ErrUnsupportedContentType |
| 174 |
} |
| 175 |
|
| 176 |
var andrCertPanicReported uint32 |
| 177 |
func andrCertConvertVal(out, in reflect.Value) { |
| 178 |
defer func() { |
| 179 |
if p := recover(); p != nil { |
| 180 |
if atomic.CompareAndSwapUint32(&andrCertPanicReported, 0, 1) { |
| 181 |
fmt.Fprintf(os.Stderr, "Conversion in pkcs7 andrCertToGoCert failed: %s\n", p) |
| 182 |
} |
| 183 |
} |
| 184 |
}() |
| 185 |
|
| 186 |
out.Set(in.Convert(out.Type())) |
| 187 |
} |
| 188 |
|
| 189 |
func andrCertToGoCert(certificate *x509.Certificate) *go_x509.Certificate { |
| 190 |
var cert go_x509.Certificate |
| 191 |
goval := reflect.ValueOf(&cert).Elem() |
| 192 |
ourval := reflect.ValueOf(certificate).Elem() |
| 193 |
for i := 0; i < ourval.NumField(); i++ { |
| 194 |
n := ourval.Type().Field(i).Name |
| 195 |
out := goval.FieldByName(n) |
| 196 |
if out.IsValid() { |
| 197 |
andrCertConvertVal(out, ourval.Field(i)) |
| 198 |
} |
| 199 |
} |
| 200 |
return &cert |
| 201 |
} |
| 202 |
|
| 203 |
func parseSignedData(data []byte) (*PKCS7, error) { |
| 204 |
var sd signedData |
| 205 |
asn1.Unmarshal(data, &sd) |
| 206 |
certs, err := sd.Certificates.Parse() |
| 207 |
if err != nil { |
| 208 |
return nil, err |
| 209 |
} |
| 210 |
|
| 211 |
|
| 212 |
var compound asn1.RawValue |
| 213 |
var content unsignedData |
| 214 |
|
| 215 |
|
| 216 |
if len(sd.ContentInfo.Content.Bytes) > 0 { |
| 217 |
if _, err := asn1.Unmarshal(sd.ContentInfo.Content.Bytes, &compound); err != nil { |
| 218 |
return nil, err |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
if compound.IsCompound { |
| 223 |
if _, err = asn1.Unmarshal(compound.Bytes, &content); err != nil { |
| 224 |
return nil, err |
| 225 |
} |
| 226 |
} else { |
| 227 |
|
| 228 |
content = compound.Bytes |
| 229 |
} |
| 230 |
|
| 231 |
goCerts := make([]*go_x509.Certificate, len(certs)) |
| 232 |
for i := range certs { |
| 233 |
goCerts[i] = andrCertToGoCert(certs[i]) |
| 234 |
} |
| 235 |
|
| 236 |
return &PKCS7{ |
| 237 |
Content: content, |
| 238 |
Certificates: goCerts, |
| 239 |
CRLs: sd.CRLs, |
| 240 |
Signers: sd.SignerInfos, |
| 241 |
ContentType: sd.ContentInfo.ContentType, |
| 242 |
raw: sd}, nil |
| 243 |
} |
| 244 |
|
| 245 |
func (raw rawCertificates) Parse() ([]*x509.Certificate, error) { |
| 246 |
if len(raw.Raw) == 0 { |
| 247 |
return nil, nil |
| 248 |
} |
| 249 |
|
| 250 |
var val asn1.RawValue |
| 251 |
if _, err := asn1.Unmarshal(raw.Raw, &val); err != nil { |
| 252 |
return nil, err |
| 253 |
} |
| 254 |
|
| 255 |
return x509.ParseCertificates(val.Bytes) |
| 256 |
} |
| 257 |
|
| 258 |
func parseEnvelopedData(data []byte) (*PKCS7, error) { |
| 259 |
var ed envelopedData |
| 260 |
if _, err := asn1.Unmarshal(data, &ed); err != nil { |
| 261 |
return nil, err |
| 262 |
} |
| 263 |
return &PKCS7{ |
| 264 |
raw: ed, |
| 265 |
}, nil |
| 266 |
} |
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
func (p7 *PKCS7) Verify() (err error) { |
| 272 |
if len(p7.Signers) == 0 { |
| 273 |
return errors.New("pkcs7: Message has no signers") |
| 274 |
} |
| 275 |
for _, signer := range p7.Signers { |
| 276 |
if err := verifySignature(p7, signer); err != nil { |
| 277 |
return err |
| 278 |
} |
| 279 |
} |
| 280 |
return nil |
| 281 |
} |
| 282 |
|
| 283 |
func verifySignature(p7 *PKCS7, signer signerInfo) error { |
| 284 |
signedData := p7.Content |
| 285 |
if len(signer.AuthenticatedAttributes) > 0 { |
| 286 |
|
| 287 |
var digest []byte |
| 288 |
err := unmarshalAttribute(signer.AuthenticatedAttributes, oidAttributeMessageDigest, &digest) |
| 289 |
if err != nil { |
| 290 |
return err |
| 291 |
} |
| 292 |
hash, err := getHashForOID(signer.DigestAlgorithm.Algorithm) |
| 293 |
if err != nil { |
| 294 |
return err |
| 295 |
} |
| 296 |
h := hash.New() |
| 297 |
h.Write(p7.Content) |
| 298 |
computed := h.Sum(nil) |
| 299 |
if !hmac.Equal(digest, computed) { |
| 300 |
return &MessageDigestMismatchError{ |
| 301 |
ExpectedDigest: digest, |
| 302 |
ActualDigest: computed, |
| 303 |
} |
| 304 |
} |
| 305 |
|
| 306 |
|
| 307 |
signedData, err = marshalAttributes(signer.AuthenticatedAttributes) |
| 308 |
if err != nil { |
| 309 |
return err |
| 310 |
} |
| 311 |
} |
| 312 |
cert := getCertFromCertsByIssuerAndSerial(p7.Certificates, signer.IssuerAndSerialNumber) |
| 313 |
if cert == nil { |
| 314 |
return errors.New("pkcs7: No certificate for signer") |
| 315 |
} |
| 316 |
|
| 317 |
algo := go_x509.SHA1WithRSA |
| 318 |
return cert.CheckSignature(algo, signedData, signer.EncryptedDigest) |
| 319 |
} |
| 320 |
|
| 321 |
func marshalAttributes(attrs []attribute) ([]byte, error) { |
| 322 |
encodedAttributes, err := asn1.Marshal(struct { |
| 323 |
A []attribute `asn1:"set"` |
| 324 |
}{A: attrs}) |
| 325 |
if err != nil { |
| 326 |
return nil, err |
| 327 |
} |
| 328 |
|
| 329 |
|
| 330 |
var raw asn1.RawValue |
| 331 |
asn1.Unmarshal(encodedAttributes, &raw) |
| 332 |
return raw.Bytes, nil |
| 333 |
} |
| 334 |
|
| 335 |
var ( |
| 336 |
oidDigestAlgorithmSHA1 = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 26} |
| 337 |
oidEncryptionAlgorithmRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1} |
| 338 |
) |
| 339 |
|
| 340 |
func getCertFromCertsByIssuerAndSerial(certs []*go_x509.Certificate, ias issuerAndSerial) *go_x509.Certificate { |
| 341 |
for _, cert := range certs { |
| 342 |
if isCertMatchForIssuerAndSerial(cert, ias) { |
| 343 |
return cert |
| 344 |
} |
| 345 |
} |
| 346 |
return nil |
| 347 |
} |
| 348 |
|
| 349 |
func getHashForOID(oid asn1.ObjectIdentifier) (crypto.Hash, error) { |
| 350 |
switch { |
| 351 |
case oid.Equal(oidDigestAlgorithmSHA1): |
| 352 |
return crypto.SHA1, nil |
| 353 |
} |
| 354 |
return crypto.Hash(0), ErrUnsupportedAlgorithm |
| 355 |
} |
| 356 |
|
| 357 |
|
| 358 |
|
| 359 |
func (p7 *PKCS7) GetOnlySigner() *go_x509.Certificate { |
| 360 |
if len(p7.Signers) != 1 { |
| 361 |
return nil |
| 362 |
} |
| 363 |
signer := p7.Signers[0] |
| 364 |
return getCertFromCertsByIssuerAndSerial(p7.Certificates, signer.IssuerAndSerialNumber) |
| 365 |
} |
| 366 |
|
| 367 |
|
| 368 |
var ErrUnsupportedAlgorithm = errors.New("pkcs7: cannot decrypt data: only RSA, DES, DES-EDE3, AES-256-CBC and AES-128-GCM supported") |
| 369 |
|
| 370 |
|
| 371 |
var ErrNotEncryptedContent = errors.New("pkcs7: content data is a decryptable data type") |
| 372 |
|
| 373 |
|
| 374 |
func (p7 *PKCS7) Decrypt(cert *go_x509.Certificate, pk crypto.PrivateKey) ([]byte, error) { |
| 375 |
data, ok := p7.raw.(envelopedData) |
| 376 |
if !ok { |
| 377 |
return nil, ErrNotEncryptedContent |
| 378 |
} |
| 379 |
recipient := selectRecipientForCertificate(data.RecipientInfos, cert) |
| 380 |
if recipient.EncryptedKey == nil { |
| 381 |
return nil, errors.New("pkcs7: no enveloped recipient for provided certificate") |
| 382 |
} |
| 383 |
if priv := pk.(*rsa.PrivateKey); priv != nil { |
| 384 |
var contentKey []byte |
| 385 |
contentKey, err := rsa.DecryptPKCS1v15(rand.Reader, priv, recipient.EncryptedKey) |
| 386 |
if err != nil { |
| 387 |
return nil, err |
| 388 |
} |
| 389 |
return data.EncryptedContentInfo.decrypt(contentKey) |
| 390 |
} |
| 391 |
fmt.Printf("Unsupported Private Key: %v\n", pk) |
| 392 |
return nil, ErrUnsupportedAlgorithm |
| 393 |
} |
| 394 |
|
| 395 |
var oidEncryptionAlgorithmDESCBC = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 7} |
| 396 |
var oidEncryptionAlgorithmDESEDE3CBC = asn1.ObjectIdentifier{1, 2, 840, 113549, 3, 7} |
| 397 |
var oidEncryptionAlgorithmAES256CBC = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 42} |
| 398 |
var oidEncryptionAlgorithmAES128GCM = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 6} |
| 399 |
var oidEncryptionAlgorithmAES128CBC = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 2} |
| 400 |
|
| 401 |
func (eci encryptedContentInfo) decrypt(key []byte) ([]byte, error) { |
| 402 |
alg := eci.ContentEncryptionAlgorithm.Algorithm |
| 403 |
if !alg.Equal(oidEncryptionAlgorithmDESCBC) && |
| 404 |
!alg.Equal(oidEncryptionAlgorithmDESEDE3CBC) && |
| 405 |
!alg.Equal(oidEncryptionAlgorithmAES256CBC) && |
| 406 |
!alg.Equal(oidEncryptionAlgorithmAES128CBC) && |
| 407 |
!alg.Equal(oidEncryptionAlgorithmAES128GCM) { |
| 408 |
fmt.Printf("Unsupported Content Encryption Algorithm: %s\n", alg) |
| 409 |
return nil, ErrUnsupportedAlgorithm |
| 410 |
} |
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
var cyphertext []byte |
| 415 |
if eci.EncryptedContent.IsCompound { |
| 416 |
|
| 417 |
var buf bytes.Buffer |
| 418 |
cypherbytes := eci.EncryptedContent.Bytes |
| 419 |
for { |
| 420 |
var part []byte |
| 421 |
cypherbytes, _ = asn1.Unmarshal(cypherbytes, &part) |
| 422 |
buf.Write(part) |
| 423 |
if cypherbytes == nil { |
| 424 |
break |
| 425 |
} |
| 426 |
} |
| 427 |
cyphertext = buf.Bytes() |
| 428 |
} else { |
| 429 |
|
| 430 |
cyphertext = eci.EncryptedContent.Bytes |
| 431 |
} |
| 432 |
|
| 433 |
var block cipher.Block |
| 434 |
var err error |
| 435 |
|
| 436 |
switch { |
| 437 |
case alg.Equal(oidEncryptionAlgorithmDESCBC): |
| 438 |
block, err = des.NewCipher(key) |
| 439 |
case alg.Equal(oidEncryptionAlgorithmDESEDE3CBC): |
| 440 |
block, err = des.NewTripleDESCipher(key) |
| 441 |
case alg.Equal(oidEncryptionAlgorithmAES256CBC): |
| 442 |
fallthrough |
| 443 |
case alg.Equal(oidEncryptionAlgorithmAES128GCM), alg.Equal(oidEncryptionAlgorithmAES128CBC): |
| 444 |
block, err = aes.NewCipher(key) |
| 445 |
} |
| 446 |
|
| 447 |
if err != nil { |
| 448 |
return nil, err |
| 449 |
} |
| 450 |
|
| 451 |
if alg.Equal(oidEncryptionAlgorithmAES128GCM) { |
| 452 |
params := aesGCMParameters{} |
| 453 |
paramBytes := eci.ContentEncryptionAlgorithm.Parameters.Bytes |
| 454 |
|
| 455 |
_, err := asn1.Unmarshal(paramBytes, ¶ms) |
| 456 |
if err != nil { |
| 457 |
return nil, err |
| 458 |
} |
| 459 |
|
| 460 |
gcm, err := cipher.NewGCM(block) |
| 461 |
if err != nil { |
| 462 |
return nil, err |
| 463 |
} |
| 464 |
|
| 465 |
if len(params.Nonce) != gcm.NonceSize() { |
| 466 |
return nil, errors.New("pkcs7: encryption algorithm parameters are incorrect") |
| 467 |
} |
| 468 |
if params.ICVLen != gcm.Overhead() { |
| 469 |
return nil, errors.New("pkcs7: encryption algorithm parameters are incorrect") |
| 470 |
} |
| 471 |
|
| 472 |
plaintext, err := gcm.Open(nil, params.Nonce, cyphertext, nil) |
| 473 |
if err != nil { |
| 474 |
return nil, err |
| 475 |
} |
| 476 |
|
| 477 |
return plaintext, nil |
| 478 |
} |
| 479 |
|
| 480 |
iv := eci.ContentEncryptionAlgorithm.Parameters.Bytes |
| 481 |
if len(iv) != block.BlockSize() { |
| 482 |
return nil, errors.New("pkcs7: encryption algorithm parameters are malformed") |
| 483 |
} |
| 484 |
mode := cipher.NewCBCDecrypter(block, iv) |
| 485 |
plaintext := make([]byte, len(cyphertext)) |
| 486 |
mode.CryptBlocks(plaintext, cyphertext) |
| 487 |
if plaintext, err = unpad(plaintext, mode.BlockSize()); err != nil { |
| 488 |
return nil, err |
| 489 |
} |
| 490 |
return plaintext, nil |
| 491 |
} |
| 492 |
|
| 493 |
func selectRecipientForCertificate(recipients []recipientInfo, cert *go_x509.Certificate) recipientInfo { |
| 494 |
for _, recp := range recipients { |
| 495 |
if isCertMatchForIssuerAndSerial(cert, recp.IssuerAndSerialNumber) { |
| 496 |
return recp |
| 497 |
} |
| 498 |
} |
| 499 |
return recipientInfo{} |
| 500 |
} |
| 501 |
|
| 502 |
func isCertMatchForIssuerAndSerial(cert *go_x509.Certificate, ias issuerAndSerial) bool { |
| 503 |
return cert.SerialNumber.Cmp(ias.SerialNumber) == 0 && bytes.Compare(cert.RawIssuer, ias.IssuerName.FullBytes) == 0 |
| 504 |
} |
| 505 |
|
| 506 |
func pad(data []byte, blocklen int) ([]byte, error) { |
| 507 |
if blocklen < 1 { |
| 508 |
return nil, fmt.Errorf("invalid blocklen %d", blocklen) |
| 509 |
} |
| 510 |
padlen := blocklen - (len(data) % blocklen) |
| 511 |
if padlen == 0 { |
| 512 |
padlen = blocklen |
| 513 |
} |
| 514 |
pad := bytes.Repeat([]byte{byte(padlen)}, padlen) |
| 515 |
return append(data, pad...), nil |
| 516 |
} |
| 517 |
|
| 518 |
func unpad(data []byte, blocklen int) ([]byte, error) { |
| 519 |
if blocklen < 1 { |
| 520 |
return nil, fmt.Errorf("invalid blocklen %d", blocklen) |
| 521 |
} |
| 522 |
if len(data)%blocklen != 0 || len(data) == 0 { |
| 523 |
return nil, fmt.Errorf("invalid data len %d", len(data)) |
| 524 |
} |
| 525 |
|
| 526 |
|
| 527 |
padlen := int(data[len(data)-1]) |
| 528 |
|
| 529 |
|
| 530 |
pad := data[len(data)-padlen:] |
| 531 |
for _, padbyte := range pad { |
| 532 |
if padbyte != byte(padlen) { |
| 533 |
return nil, errors.New("invalid padding") |
| 534 |
} |
| 535 |
} |
| 536 |
|
| 537 |
return data[:len(data)-padlen], nil |
| 538 |
} |
| 539 |
|
| 540 |
func unmarshalAttribute(attrs []attribute, attributeType asn1.ObjectIdentifier, out interface{}) error { |
| 541 |
for _, attr := range attrs { |
| 542 |
if attr.Type.Equal(attributeType) { |
| 543 |
_, err := asn1.Unmarshal(attr.Value.Bytes, out) |
| 544 |
return err |
| 545 |
} |
| 546 |
} |
| 547 |
return errors.New("pkcs7: attribute type not in attributes") |
| 548 |
} |
| 549 |
|
| 550 |
|
| 551 |
func (p7 *PKCS7) UnmarshalSignedAttribute(attributeType asn1.ObjectIdentifier, out interface{}) error { |
| 552 |
sd, ok := p7.raw.(signedData) |
| 553 |
if !ok { |
| 554 |
return errors.New("pkcs7: payload is not signedData content") |
| 555 |
} |
| 556 |
if len(sd.SignerInfos) < 1 { |
| 557 |
return errors.New("pkcs7: payload has no signers") |
| 558 |
} |
| 559 |
attributes := sd.SignerInfos[0].AuthenticatedAttributes |
| 560 |
return unmarshalAttribute(attributes, attributeType, out) |
| 561 |
} |
| 562 |
|
| 563 |
|
| 564 |
type SignedData struct { |
| 565 |
sd signedData |
| 566 |
certs []*x509.Certificate |
| 567 |
messageDigest []byte |
| 568 |
} |
| 569 |
|
| 570 |
|
| 571 |
|
| 572 |
type Attribute struct { |
| 573 |
Type asn1.ObjectIdentifier |
| 574 |
Value interface{} |
| 575 |
} |
| 576 |
|
| 577 |
|
| 578 |
type SignerInfoConfig struct { |
| 579 |
ExtraSignedAttributes []Attribute |
| 580 |
} |
| 581 |
|
| 582 |
|
| 583 |
func NewSignedData(data []byte) (*SignedData, error) { |
| 584 |
content, err := asn1.Marshal(data) |
| 585 |
if err != nil { |
| 586 |
return nil, err |
| 587 |
} |
| 588 |
ci := contentInfo{ |
| 589 |
ContentType: oidData, |
| 590 |
Content: asn1.RawValue{Class: 2, Tag: 0, Bytes: content, IsCompound: true}, |
| 591 |
} |
| 592 |
digAlg := pkix.AlgorithmIdentifier{ |
| 593 |
Algorithm: oidDigestAlgorithmSHA1, |
| 594 |
} |
| 595 |
h := crypto.SHA1.New() |
| 596 |
h.Write(data) |
| 597 |
md := h.Sum(nil) |
| 598 |
sd := signedData{ |
| 599 |
ContentInfo: ci, |
| 600 |
Version: 1, |
| 601 |
DigestAlgorithmIdentifiers: []pkix.AlgorithmIdentifier{digAlg}, |
| 602 |
} |
| 603 |
return &SignedData{sd: sd, messageDigest: md}, nil |
| 604 |
} |
| 605 |
|
| 606 |
type attributes struct { |
| 607 |
types []asn1.ObjectIdentifier |
| 608 |
values []interface{} |
| 609 |
} |
| 610 |
|
| 611 |
|
| 612 |
func (attrs *attributes) Add(attrType asn1.ObjectIdentifier, value interface{}) { |
| 613 |
attrs.types = append(attrs.types, attrType) |
| 614 |
attrs.values = append(attrs.values, value) |
| 615 |
} |
| 616 |
|
| 617 |
type sortableAttribute struct { |
| 618 |
SortKey []byte |
| 619 |
Attribute attribute |
| 620 |
} |
| 621 |
|
| 622 |
type attributeSet []sortableAttribute |
| 623 |
|
| 624 |
func (sa attributeSet) Len() int { |
| 625 |
return len(sa) |
| 626 |
} |
| 627 |
|
| 628 |
func (sa attributeSet) Less(i, j int) bool { |
| 629 |
return bytes.Compare(sa[i].SortKey, sa[j].SortKey) < 0 |
| 630 |
} |
| 631 |
|
| 632 |
func (sa attributeSet) Swap(i, j int) { |
| 633 |
sa[i], sa[j] = sa[j], sa[i] |
| 634 |
} |
| 635 |
|
| 636 |
func (sa attributeSet) Attributes() []attribute { |
| 637 |
attrs := make([]attribute, len(sa)) |
| 638 |
for i, attr := range sa { |
| 639 |
attrs[i] = attr.Attribute |
| 640 |
} |
| 641 |
return attrs |
| 642 |
} |
| 643 |
|
| 644 |
func (attrs *attributes) ForMarshaling() ([]attribute, error) { |
| 645 |
sortables := make(attributeSet, len(attrs.types)) |
| 646 |
for i := range sortables { |
| 647 |
attrType := attrs.types[i] |
| 648 |
attrValue := attrs.values[i] |
| 649 |
asn1Value, err := asn1.Marshal(attrValue) |
| 650 |
if err != nil { |
| 651 |
return nil, err |
| 652 |
} |
| 653 |
attr := attribute{ |
| 654 |
Type: attrType, |
| 655 |
Value: asn1.RawValue{Tag: 17, IsCompound: true, Bytes: asn1Value}, |
| 656 |
} |
| 657 |
encoded, err := asn1.Marshal(attr) |
| 658 |
if err != nil { |
| 659 |
return nil, err |
| 660 |
} |
| 661 |
sortables[i] = sortableAttribute{ |
| 662 |
SortKey: encoded, |
| 663 |
Attribute: attr, |
| 664 |
} |
| 665 |
} |
| 666 |
sort.Sort(sortables) |
| 667 |
return sortables.Attributes(), nil |
| 668 |
} |
| 669 |
|
| 670 |
|
| 671 |
func (sd *SignedData) AddSigner(cert *x509.Certificate, pkey crypto.PrivateKey, config SignerInfoConfig) error { |
| 672 |
attrs := &attributes{} |
| 673 |
attrs.Add(oidAttributeContentType, sd.sd.ContentInfo.ContentType) |
| 674 |
attrs.Add(oidAttributeMessageDigest, sd.messageDigest) |
| 675 |
attrs.Add(oidAttributeSigningTime, time.Now()) |
| 676 |
for _, attr := range config.ExtraSignedAttributes { |
| 677 |
attrs.Add(attr.Type, attr.Value) |
| 678 |
} |
| 679 |
finalAttrs, err := attrs.ForMarshaling() |
| 680 |
if err != nil { |
| 681 |
return err |
| 682 |
} |
| 683 |
signature, err := signAttributes(finalAttrs, pkey, crypto.SHA1) |
| 684 |
if err != nil { |
| 685 |
return err |
| 686 |
} |
| 687 |
|
| 688 |
ias, err := cert2issuerAndSerial(cert) |
| 689 |
if err != nil { |
| 690 |
return err |
| 691 |
} |
| 692 |
|
| 693 |
signer := signerInfo{ |
| 694 |
AuthenticatedAttributes: finalAttrs, |
| 695 |
DigestAlgorithm: pkix.AlgorithmIdentifier{Algorithm: oidDigestAlgorithmSHA1}, |
| 696 |
DigestEncryptionAlgorithm: pkix.AlgorithmIdentifier{Algorithm: oidEncryptionAlgorithmRSA}, |
| 697 |
IssuerAndSerialNumber: ias, |
| 698 |
EncryptedDigest: signature, |
| 699 |
Version: 1, |
| 700 |
} |
| 701 |
|
| 702 |
sd.certs = append(sd.certs, cert) |
| 703 |
sd.sd.SignerInfos = append(sd.sd.SignerInfos, signer) |
| 704 |
return nil |
| 705 |
} |
| 706 |
|
| 707 |
|
| 708 |
func (sd *SignedData) AddCertificate(cert *x509.Certificate) { |
| 709 |
sd.certs = append(sd.certs, cert) |
| 710 |
} |
| 711 |
|
| 712 |
|
| 713 |
|
| 714 |
func (sd *SignedData) Detach() { |
| 715 |
sd.sd.ContentInfo = contentInfo{ContentType: oidSignedData} |
| 716 |
} |
| 717 |
|
| 718 |
|
| 719 |
func (sd *SignedData) Finish() ([]byte, error) { |
| 720 |
sd.sd.Certificates = marshalCertificates(sd.certs) |
| 721 |
inner, err := asn1.Marshal(sd.sd) |
| 722 |
if err != nil { |
| 723 |
return nil, err |
| 724 |
} |
| 725 |
outer := contentInfo{ |
| 726 |
ContentType: oidSignedData, |
| 727 |
Content: asn1.RawValue{Class: 2, Tag: 0, Bytes: inner, IsCompound: true}, |
| 728 |
} |
| 729 |
return asn1.Marshal(outer) |
| 730 |
} |
| 731 |
|
| 732 |
func cert2issuerAndSerial(cert *x509.Certificate) (issuerAndSerial, error) { |
| 733 |
var ias issuerAndSerial |
| 734 |
|
| 735 |
|
| 736 |
ias.IssuerName = asn1.RawValue{FullBytes: cert.RawIssuer} |
| 737 |
ias.SerialNumber = cert.SerialNumber |
| 738 |
|
| 739 |
return ias, nil |
| 740 |
} |
| 741 |
|
| 742 |
|
| 743 |
func signAttributes(attrs []attribute, pkey crypto.PrivateKey, hash crypto.Hash) ([]byte, error) { |
| 744 |
attrBytes, err := marshalAttributes(attrs) |
| 745 |
if err != nil { |
| 746 |
return nil, err |
| 747 |
} |
| 748 |
h := hash.New() |
| 749 |
h.Write(attrBytes) |
| 750 |
hashed := h.Sum(nil) |
| 751 |
switch priv := pkey.(type) { |
| 752 |
case *rsa.PrivateKey: |
| 753 |
return rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA1, hashed) |
| 754 |
} |
| 755 |
return nil, ErrUnsupportedAlgorithm |
| 756 |
} |
| 757 |
|
| 758 |
|
| 759 |
func marshalCertificates(certs []*x509.Certificate) rawCertificates { |
| 760 |
var buf bytes.Buffer |
| 761 |
for _, cert := range certs { |
| 762 |
buf.Write(cert.Raw) |
| 763 |
} |
| 764 |
rawCerts, _ := marshalCertificateBytes(buf.Bytes()) |
| 765 |
return rawCerts |
| 766 |
} |
| 767 |
|
| 768 |
|
| 769 |
|
| 770 |
|
| 771 |
func marshalCertificateBytes(certs []byte) (rawCertificates, error) { |
| 772 |
var val = asn1.RawValue{Bytes: certs, Class: 2, Tag: 0, IsCompound: true} |
| 773 |
b, err := asn1.Marshal(val) |
| 774 |
if err != nil { |
| 775 |
return rawCertificates{}, err |
| 776 |
} |
| 777 |
return rawCertificates{Raw: b}, nil |
| 778 |
} |
| 779 |
|
| 780 |
|
| 781 |
|
| 782 |
func DegenerateCertificate(cert []byte) ([]byte, error) { |
| 783 |
rawCert, err := marshalCertificateBytes(cert) |
| 784 |
if err != nil { |
| 785 |
return nil, err |
| 786 |
} |
| 787 |
emptyContent := contentInfo{ContentType: oidData} |
| 788 |
sd := signedData{ |
| 789 |
Version: 1, |
| 790 |
ContentInfo: emptyContent, |
| 791 |
Certificates: rawCert, |
| 792 |
CRLs: []pkix.CertificateList{}, |
| 793 |
} |
| 794 |
content, err := asn1.Marshal(sd) |
| 795 |
if err != nil { |
| 796 |
return nil, err |
| 797 |
} |
| 798 |
signedContent := contentInfo{ |
| 799 |
ContentType: oidSignedData, |
| 800 |
Content: asn1.RawValue{Class: 2, Tag: 0, Bytes: content, IsCompound: true}, |
| 801 |
} |
| 802 |
return asn1.Marshal(signedContent) |
| 803 |
} |
| 804 |
|
| 805 |
const ( |
| 806 |
EncryptionAlgorithmDESCBC = iota |
| 807 |
EncryptionAlgorithmAES128GCM |
| 808 |
) |
| 809 |
|
| 810 |
|
| 811 |
|
| 812 |
|
| 813 |
var ContentEncryptionAlgorithm = EncryptionAlgorithmDESCBC |
| 814 |
|
| 815 |
|
| 816 |
|
| 817 |
var ErrUnsupportedEncryptionAlgorithm = errors.New("pkcs7: cannot encrypt content: only DES-CBC and AES-128-GCM supported") |
| 818 |
|
| 819 |
const nonceSize = 12 |
| 820 |
|
| 821 |
type aesGCMParameters struct { |
| 822 |
Nonce []byte `asn1:"tag:4"` |
| 823 |
ICVLen int |
| 824 |
} |
| 825 |
|
| 826 |
func encryptAES128GCM(content []byte) ([]byte, *encryptedContentInfo, error) { |
| 827 |
|
| 828 |
key := make([]byte, 16) |
| 829 |
nonce := make([]byte, nonceSize) |
| 830 |
|
| 831 |
_, err := rand.Read(key) |
| 832 |
if err != nil { |
| 833 |
return nil, nil, err |
| 834 |
} |
| 835 |
|
| 836 |
_, err = rand.Read(nonce) |
| 837 |
if err != nil { |
| 838 |
return nil, nil, err |
| 839 |
} |
| 840 |
|
| 841 |
|
| 842 |
block, err := aes.NewCipher(key) |
| 843 |
if err != nil { |
| 844 |
return nil, nil, err |
| 845 |
} |
| 846 |
|
| 847 |
gcm, err := cipher.NewGCM(block) |
| 848 |
if err != nil { |
| 849 |
return nil, nil, err |
| 850 |
} |
| 851 |
|
| 852 |
ciphertext := gcm.Seal(nil, nonce, content, nil) |
| 853 |
|
| 854 |
|
| 855 |
paramSeq := aesGCMParameters{ |
| 856 |
Nonce: nonce, |
| 857 |
ICVLen: gcm.Overhead(), |
| 858 |
} |
| 859 |
|
| 860 |
paramBytes, err := asn1.Marshal(paramSeq) |
| 861 |
if err != nil { |
| 862 |
return nil, nil, err |
| 863 |
} |
| 864 |
|
| 865 |
eci := encryptedContentInfo{ |
| 866 |
ContentType: oidData, |
| 867 |
ContentEncryptionAlgorithm: pkix.AlgorithmIdentifier{ |
| 868 |
Algorithm: oidEncryptionAlgorithmAES128GCM, |
| 869 |
Parameters: asn1.RawValue{ |
| 870 |
Tag: asn1.TagSequence, |
| 871 |
Bytes: paramBytes, |
| 872 |
}, |
| 873 |
}, |
| 874 |
EncryptedContent: marshalEncryptedContent(ciphertext), |
| 875 |
} |
| 876 |
|
| 877 |
return key, &eci, nil |
| 878 |
} |
| 879 |
|
| 880 |
func encryptDESCBC(content []byte) ([]byte, *encryptedContentInfo, error) { |
| 881 |
|
| 882 |
key := make([]byte, 8) |
| 883 |
iv := make([]byte, des.BlockSize) |
| 884 |
_, err := rand.Read(key) |
| 885 |
if err != nil { |
| 886 |
return nil, nil, err |
| 887 |
} |
| 888 |
_, err = rand.Read(iv) |
| 889 |
if err != nil { |
| 890 |
return nil, nil, err |
| 891 |
} |
| 892 |
|
| 893 |
|
| 894 |
block, err := des.NewCipher(key) |
| 895 |
if err != nil { |
| 896 |
return nil, nil, err |
| 897 |
} |
| 898 |
mode := cipher.NewCBCEncrypter(block, iv) |
| 899 |
plaintext, err := pad(content, mode.BlockSize()) |
| 900 |
cyphertext := make([]byte, len(plaintext)) |
| 901 |
mode.CryptBlocks(cyphertext, plaintext) |
| 902 |
|
| 903 |
|
| 904 |
eci := encryptedContentInfo{ |
| 905 |
ContentType: oidData, |
| 906 |
ContentEncryptionAlgorithm: pkix.AlgorithmIdentifier{ |
| 907 |
Algorithm: oidEncryptionAlgorithmDESCBC, |
| 908 |
Parameters: asn1.RawValue{Tag: 4, Bytes: iv}, |
| 909 |
}, |
| 910 |
EncryptedContent: marshalEncryptedContent(cyphertext), |
| 911 |
} |
| 912 |
|
| 913 |
return key, &eci, nil |
| 914 |
} |
| 915 |
|
| 916 |
|
| 917 |
|
| 918 |
|
| 919 |
|
| 920 |
|
| 921 |
|
| 922 |
|
| 923 |
|
| 924 |
|
| 925 |
|
| 926 |
|
| 927 |
func Encrypt(content []byte, recipients []*x509.Certificate) ([]byte, error) { |
| 928 |
var eci *encryptedContentInfo |
| 929 |
var key []byte |
| 930 |
var err error |
| 931 |
|
| 932 |
|
| 933 |
switch ContentEncryptionAlgorithm { |
| 934 |
case EncryptionAlgorithmDESCBC: |
| 935 |
key, eci, err = encryptDESCBC(content) |
| 936 |
|
| 937 |
case EncryptionAlgorithmAES128GCM: |
| 938 |
key, eci, err = encryptAES128GCM(content) |
| 939 |
|
| 940 |
default: |
| 941 |
return nil, ErrUnsupportedEncryptionAlgorithm |
| 942 |
} |
| 943 |
|
| 944 |
if err != nil { |
| 945 |
return nil, err |
| 946 |
} |
| 947 |
|
| 948 |
|
| 949 |
recipientInfos := make([]recipientInfo, len(recipients)) |
| 950 |
for i, recipient := range recipients { |
| 951 |
encrypted, err := encryptKey(key, recipient) |
| 952 |
if err != nil { |
| 953 |
return nil, err |
| 954 |
} |
| 955 |
ias, err := cert2issuerAndSerial(recipient) |
| 956 |
if err != nil { |
| 957 |
return nil, err |
| 958 |
} |
| 959 |
info := recipientInfo{ |
| 960 |
Version: 0, |
| 961 |
IssuerAndSerialNumber: ias, |
| 962 |
KeyEncryptionAlgorithm: pkix.AlgorithmIdentifier{ |
| 963 |
Algorithm: oidEncryptionAlgorithmRSA, |
| 964 |
}, |
| 965 |
EncryptedKey: encrypted, |
| 966 |
} |
| 967 |
recipientInfos[i] = info |
| 968 |
} |
| 969 |
|
| 970 |
|
| 971 |
envelope := envelopedData{ |
| 972 |
EncryptedContentInfo: *eci, |
| 973 |
Version: 0, |
| 974 |
RecipientInfos: recipientInfos, |
| 975 |
} |
| 976 |
innerContent, err := asn1.Marshal(envelope) |
| 977 |
if err != nil { |
| 978 |
return nil, err |
| 979 |
} |
| 980 |
|
| 981 |
|
| 982 |
wrapper := contentInfo{ |
| 983 |
ContentType: oidEnvelopedData, |
| 984 |
Content: asn1.RawValue{Class: 2, Tag: 0, IsCompound: true, Bytes: innerContent}, |
| 985 |
} |
| 986 |
|
| 987 |
return asn1.Marshal(wrapper) |
| 988 |
} |
| 989 |
|
| 990 |
func marshalEncryptedContent(content []byte) asn1.RawValue { |
| 991 |
asn1Content, _ := asn1.Marshal(content) |
| 992 |
return asn1.RawValue{Tag: 0, Class: 2, Bytes: asn1Content, IsCompound: true} |
| 993 |
} |
| 994 |
|
| 995 |
func encryptKey(key []byte, recipient *x509.Certificate) ([]byte, error) { |
| 996 |
if pub := recipient.PublicKey.(*rsa.PublicKey); pub != nil { |
| 997 |
return rsa.EncryptPKCS1v15(rand.Reader, pub, key) |
| 998 |
} |
| 999 |
return nil, ErrUnsupportedAlgorithm |
| 1000 |
} |
| 1001 |
|
| 1002 |
|
| 1003 |
func (p7 *PKCS7) GetSignerInfos() []SignerInfo { |
| 1004 |
res := make([]SignerInfo, len(p7.Signers)) |
| 1005 |
for i := range p7.Signers { |
| 1006 |
s := &p7.Signers[i] |
| 1007 |
|
| 1008 |
AuthenticatedAttributes := make([]SignerAttribute, len(s.AuthenticatedAttributes)) |
| 1009 |
for i := range s.AuthenticatedAttributes { |
| 1010 |
AuthenticatedAttributes[i] = SignerAttribute(s.AuthenticatedAttributes[i]) |
| 1011 |
} |
| 1012 |
|
| 1013 |
UnauthenticatedAttributes := make([]SignerAttribute, len(s.UnauthenticatedAttributes)) |
| 1014 |
for i := range s.UnauthenticatedAttributes { |
| 1015 |
UnauthenticatedAttributes[i] = SignerAttribute(s.UnauthenticatedAttributes[i]) |
| 1016 |
} |
| 1017 |
res[i] = SignerInfo{ |
| 1018 |
s.Version, |
| 1019 |
IssuerAndSerial(s.IssuerAndSerialNumber), |
| 1020 |
s.DigestAlgorithm, |
| 1021 |
AuthenticatedAttributes, |
| 1022 |
s.DigestEncryptionAlgorithm, |
| 1023 |
s.EncryptedDigest, |
| 1024 |
UnauthenticatedAttributes, |
| 1025 |
} |
| 1026 |
} |
| 1027 |
return res |
| 1028 |
} |
| 1029 |
|
| 1030 |
func (si *SignerInfo) UnmarshalSignedAttribute(attributeType asn1.ObjectIdentifier, out interface{}) error { |
| 1031 |
found := false |
| 1032 |
for _, attr := range si.AuthenticatedAttributes { |
| 1033 |
if attr.Type.Equal(attributeType) { |
| 1034 |
if found { |
| 1035 |
return errors.New("pkcs7: attribute type has multiple values") |
| 1036 |
} |
| 1037 |
|
| 1038 |
found = true |
| 1039 |
if _, err := asn1.Unmarshal(attr.Value.Bytes, out); err != nil { |
| 1040 |
return err |
| 1041 |
} |
| 1042 |
} |
| 1043 |
} |
| 1044 |
|
| 1045 |
if !found { |
| 1046 |
return errors.New("pkcs7: attribute type not in attributes") |
| 1047 |
} |
| 1048 |
return nil |
| 1049 |
} |
| 1050 |
|
| 1051 |
func (si *SignerInfo) MarshalAuthenticatedAttributes() ([]byte, error) { |
| 1052 |
encodedAttributes, err := asn1.Marshal(struct { |
| 1053 |
A []SignerAttribute `asn1:"set"` |
| 1054 |
}{A: si.AuthenticatedAttributes}) |
| 1055 |
if err != nil { |
| 1056 |
return nil, err |
| 1057 |
} |
| 1058 |
|
| 1059 |
|
| 1060 |
var raw asn1.RawValue |
| 1061 |
asn1.Unmarshal(encodedAttributes, &raw) |
| 1062 |
return raw.Bytes, nil |
| 1063 |
} |