Ejemplo n.º 1
0
    def request_cms(self, message_digest, md_algorithm):
        """
        Format the body of an :rfc:`3161` request as a CMS object.
        Subclasses with more specific needs may want to override this.

        :param message_digest:
            Message digest to which the timestamp will apply.
        :param md_algorithm:
            Message digest algorithm to use.

            .. note::
                As per :rfc:`8933`, ``md_algorithm`` should also be the
                algorithm used to compute ``message_digest``.
        :return:
            An :class:`.asn1crypto.tsp.TimeStampReq` object.
        """
        nonce = get_nonce()
        req = tsp.TimeStampReq({
            'version': 1,
            'message_imprint': tsp.MessageImprint({
                'hash_algorithm': algos.DigestAlgorithm({
                    'algorithm': md_algorithm
                }),
                'hashed_message': message_digest
            }),
            'nonce': cms.Integer(nonce),
            # we want the server to send along its certs
            'cert_req': True
        })
        return nonce, req
Ejemplo n.º 2
0
def test_timestamp(requests_mock, setup):
    setup.illusionist.register(requests_mock)
    hashed_bytes = hashlib.sha256(b'test').digest()
    req = tsp.TimeStampReq({
        'version':
        'v2',
        'message_imprint':
        tsp.MessageImprint({
            'hash_algorithm':
            algos.DigestAlgorithm({'algorithm': 'sha256'}),
            'hashed_message':
            hashed_bytes
        }),
        'nonce':
        core.Integer(0x1337),
        'cert_req':
        True
    })
    response = requests.post("http://test.test/testing-ca/tsa/tsa",
                             data=req.dump())
    resp: tsp.TimeStampResp = tsp.TimeStampResp.load(response.content)
    sd = resp['time_stamp_token']['content']
    tst_info: tsp.TSTInfo = sd['encap_content_info']['content'].parsed
    assert tst_info['nonce'].native == 0x1337
    assert tst_info['gen_time'].native \
           == datetime.now().replace(tzinfo=pytz.utc)
Ejemplo n.º 3
0
def timestamp(unhashed,
              hashalgo,
              url,
              credentials,
              req_options,
              prehashed=None):
    if prehashed:
        hashed_value = prehashed
    else:
        hashed_value = getattr(hashlib, hashalgo)(unhashed).digest()
    tspreq = tsp.TimeStampReq({
        "version":
        1,
        "message_imprint":
        tsp.MessageImprint({
            "hash_algorithm":
            algos.DigestAlgorithm({'algorithm': hashalgo}),
            "hashed_message":
            hashed_value,
        }),
        #'req_policy', ObjectIdentifier, {'optional': True}),
        "nonce":
        int(time.time() * 1000),
        "cert_req":
        True,
        #'extensions': tsp.Extensions()
    })
    tspreq = tspreq.dump()

    tspheaders = {"Content-Type": "application/timestamp-query"}
    if credentials is not None:
        username = credentials.get("username", None)
        password = credentials.get("password", None)
        if username and password:
            auth_header_value = b64encode(
                bytes(username + ':' + password, "utf-8")).decode("ascii")
            tspheaders["Authorization"] = f"Basic {auth_header_value}"
    if req_options is None:
        req_options = {}

    tspresp = requests.post(url,
                            data=tspreq,
                            headers=tspheaders,
                            **req_options)
    if tspresp.headers.get('Content-Type',
                           None) == 'application/timestamp-reply':
        tspresp = tsp.TimeStampResp.load(tspresp.content)

        if tspresp['status']['status'].native == 'granted':
            attrs = [
                cms.CMSAttribute({
                    'type':
                    cms.CMSAttributeType('signature_time_stamp_token'),
                    'values':
                    cms.SetOfContentInfo([
                        cms.ContentInfo({
                            'content_type':
                            cms.ContentType('signed_data'),
                            'content':
                            tspresp["time_stamp_token"]["content"],
                        })
                    ])
                })
            ]
            return attrs
        else:
            raise ValueError("TimeStampResponse status is not granted")
    else:
        raise ValueError("TimeStampResponse has invalid content type")
Ejemplo n.º 4
0
def sign(datau,
         key,
         cert,
         othercerts,
         hashalgo,
         attrs=True,
         signed_value=None,
         hsm=None,
         pss=False,
         timestampurl=None,
         timestampcredentials=None):
    if signed_value is None:
        signed_value = getattr(hashlib, hashalgo)(datau).digest()
    signed_time = datetime.now(tz=util.timezone.utc)

    if hsm is not None:
        keyid, cert = hsm.certificate()
        cert = cert2asn(cert, False)
    else:
        cert = cert2asn(cert)

    certificates = []
    certificates.append(cert)
    for i in range(len(othercerts)):
        certificates.append(cert2asn(othercerts[i]))

    hashalgo = unicode(hashalgo) if sys.version[0] < '3' else hashalgo

    signer = {
        'version':
        'v1',
        'sid':
        cms.SignerIdentifier({
            'issuer_and_serial_number':
            cms.IssuerAndSerialNumber({
                'issuer': cert.issuer,
                'serial_number': cert.serial_number,
            }),
        }),
        'digest_algorithm':
        algos.DigestAlgorithm({'algorithm': hashalgo}),
        'signature':
        signed_value,
    }
    if not pss:
        signer['signature_algorithm'] = algos.SignedDigestAlgorithm(
            {'algorithm': 'rsassa_pkcs1v15'})
    else:
        if isinstance(key, keys.PrivateKeyInfo):
            salt_length = key.byte_size - hashes.SHA512.digest_size - 2
            salt_length = hashes.SHA512.digest_size
        else:
            salt_length = padding.calculate_max_pss_salt_length(
                key, hashes.SHA512)
        signer['signature_algorithm'] = algos.SignedDigestAlgorithm({
            'algorithm':
            'rsassa_pss',
            'parameters':
            algos.RSASSAPSSParams({
                'hash_algorithm':
                algos.DigestAlgorithm({'algorithm': 'sha512'}),
                'mask_gen_algorithm':
                algos.MaskGenAlgorithm({
                    'algorithm':
                    algos.MaskGenAlgorithmId('mgf1'),
                    'parameters': {
                        'algorithm': algos.DigestAlgorithmId('sha512'),
                    }
                }),
                'salt_length':
                algos.Integer(salt_length),
                'trailer_field':
                algos.TrailerField(1)
            })
        })

    if attrs:
        if attrs is True:
            signer['signed_attrs'] = [
                cms.CMSAttribute({
                    'type': cms.CMSAttributeType('content_type'),
                    'values': ('data', ),
                }),
                cms.CMSAttribute({
                    'type': cms.CMSAttributeType('message_digest'),
                    'values': (signed_value, ),
                }),
                cms.CMSAttribute({
                    'type':
                    cms.CMSAttributeType('signing_time'),
                    'values':
                    (cms.Time({'utc_time': core.UTCTime(signed_time)}), )
                }),
            ]
        else:
            signer['signed_attrs'] = attrs

    config = {
        'version':
        'v1',
        'digest_algorithms':
        cms.DigestAlgorithms((algos.DigestAlgorithm({'algorithm':
                                                     hashalgo}), )),
        'encap_content_info': {
            'content_type': 'data',
        },
        'certificates':
        certificates,
        # 'crls': [],
        'signer_infos': [
            signer,
        ],
    }
    datas = cms.ContentInfo({
        'content_type': cms.ContentType('signed_data'),
        'content': cms.SignedData(config),
    })
    if attrs:
        tosign = datas['content']['signer_infos'][0]['signed_attrs'].dump()
        tosign = b'\x31' + tosign[1:]
    else:
        tosign = datau
    if hsm is not None:
        signed_value_signature = hsm.sign(keyid, tosign, hashalgo)
    elif isinstance(key, keys.PrivateKeyInfo):
        key = asymmetric.load_private_key(key)
        if pss:
            signed_value_signature = asymmetric.rsa_pss_sign(
                key, tosign, 'sha512')
        else:
            signed_value_signature = asymmetric.rsa_pkcs1v15_sign(
                key, tosign, hashalgo.lower())
    else:
        if pss:
            hasher = hashes.Hash(hashes.SHA512(),
                                 backend=backends.default_backend())
            hasher.update(tosign)
            digest = hasher.finalize()
            signed_value_signature = key.sign(
                digest,
                padding.PSS(mgf=padding.MGF1(hashes.SHA512()),
                            salt_length=salt_length),
                utils.Prehashed(hashes.SHA512()))
        else:
            signed_value_signature = key.sign(
                tosign, padding.PKCS1v15(),
                getattr(hashes, hashalgo.upper())())

    if timestampurl is not None:
        signed_value = getattr(hashlib,
                               hashalgo)(signed_value_signature).digest()
        tspreq = tsp.TimeStampReq({
            "version":
            1,
            "message_imprint":
            tsp.MessageImprint({
                "hash_algorithm":
                algos.DigestAlgorithm({'algorithm': hashalgo}),
                "hashed_message":
                signed_value,
            }),
            #'req_policy', ObjectIdentifier, {'optional': True}),
            "nonce":
            int(time.time() * 1000),
            "cert_req":
            True,
            #'extensions': tsp.Extensions()
        })
        tspreq = tspreq.dump()

        tspheaders = {"Content-Type": "application/timestamp-query"}
        if timestampcredentials is not None:
            username = timestampcredentials.get("username", None)
            password = timestampcredentials.get("password", None)
            if username and password:
                auth_header_value = b64encode(
                    bytes(username + ':' + password, "utf-8")).decode("ascii")
                tspheaders["Authorization"] = f"Basic {auth_header_value}"
        tspresp = requests.post(timestampurl, data=tspreq, headers=tspheaders)
        if tspresp.headers.get('Content-Type',
                               None) == 'application/timestamp-reply':
            tspresp = tsp.TimeStampResp.load(tspresp.content)

            if tspresp['status']['status'].native == 'granted':
                attrs = [
                    cms.CMSAttribute({
                        'type':
                        cms.CMSAttributeType('signature_time_stamp_token'),
                        'values':
                        cms.SetOfContentInfo([
                            cms.ContentInfo({
                                'content_type':
                                cms.ContentType('signed_data'),
                                'content':
                                tspresp["time_stamp_token"]["content"],
                            })
                        ])
                    })
                ]
                datas['content']['signer_infos'][0]['unsigned_attrs'] = attrs

            else:
                raise ValueError("TimeStampResponse status is not granted")

        else:
            raise ValueError("TimeStampResponse has invalid content type")

    # signed_value_signature = core.OctetString(signed_value_signature)
    datas['content']['signer_infos'][0]['signature'] = signed_value_signature

    #open('signed-content-info', 'wb').write(datas.dump())
    return datas.dump()
Ejemplo n.º 5
0
    def _sign(self,
              datau,
              key,
              cert,
              othercerts,
              hashalgo,
              attrs=True,
              signed_value=None,
              hsm=None,
              pss=False,
              timestampurl=None):
        if signed_value is None:
            signed_value = getattr(hashlib, hashalgo)(datau).digest()
        signed_time = datetime.now(tz=util.timezone.utc)

        if hsm is not None:
            keyid, cert = hsm.certificate()
            cert = cert2asn(cert, False)
            othercerts = []
        else:
            cert = cert2asn(cert)

        certificates = []
        certificates.append(cert)
        for i in range(len(othercerts)):
            certificates.append(cert2asn(othercerts[i]))

        signer = {
            'version':
            'v1',
            'sid':
            cms.SignerIdentifier({
                'issuer_and_serial_number':
                cms.IssuerAndSerialNumber({
                    'issuer': cert.issuer,
                    'serial_number': cert.serial_number,
                }),
            }),
            'digest_algorithm':
            algos.DigestAlgorithm({'algorithm': hashalgo}),
            'signature':
            signed_value,
        }
        if not pss:
            signer['signature_algorithm'] = algos.SignedDigestAlgorithm(
                {'algorithm': 'rsassa_pkcs1v15'})
        else:
            salt_length = padding.calculate_max_pss_salt_length(
                key, hashes.SHA512)
            signer['signature_algorithm'] = algos.SignedDigestAlgorithm({
                'algorithm':
                'rsassa_pss',
                'parameters':
                algos.RSASSAPSSParams({
                    'hash_algorithm':
                    algos.DigestAlgorithm({'algorithm': 'sha512'}),
                    'mask_gen_algorithm':
                    algos.MaskGenAlgorithm({
                        'algorithm':
                        algos.MaskGenAlgorithmId('mgf1'),
                        'parameters': {
                            'algorithm': algos.DigestAlgorithmId('sha512'),
                        }
                    }),
                    'salt_length':
                    algos.Integer(salt_length),
                    'trailer_field':
                    algos.TrailerField(1)
                })
            })

        if attrs:
            if attrs is True:
                signer['signed_attrs'] = [
                    cms.CMSAttribute({
                        'type':
                        cms.CMSAttributeType('content_type'),
                        'values': ('data', ),
                    }),
                    cms.CMSAttribute({
                        'type':
                        cms.CMSAttributeType('message_digest'),
                        'values': (signed_value, ),
                    }),
                    cms.CMSAttribute({
                        'type':
                        cms.CMSAttributeType('signing_time'),
                        'values':
                        (cms.Time({'utc_time': core.UTCTime(signed_time)}), )
                    }),
                ]
            else:
                signer['signed_attrs'] = attrs

        config = {
            'version':
            'v1',
            'digest_algorithms':
            cms.DigestAlgorithms(
                (algos.DigestAlgorithm({'algorithm': hashalgo}), )),
            'encap_content_info': {
                'content_type': 'data',
            },
            'certificates':
            certificates,
            # 'crls': [],
            'signer_infos': [
                signer,
            ],
        }
        datas = cms.ContentInfo({
            'content_type': cms.ContentType('signed_data'),
            'content': cms.SignedData(config),
        })
        if attrs:
            tosign = datas['content']['signer_infos'][0]['signed_attrs'].dump()
            tosign = b'\x31' + tosign[1:]
        else:
            tosign = datau
        if hsm is not None:
            signed_value_signature = hsm.sign(keyid, tosign, hashalgo)
        else:
            if pss:
                hasher = hashes.Hash(hashes.SHA512(),
                                     backend=backends.default_backend())
                hasher.update(tosign)
                digest = hasher.finalize()
                signed_value_signature = key.sign(
                    digest,
                    padding.PSS(mgf=padding.MGF1(hashes.SHA512()),
                                salt_length=salt_length),
                    utils.Prehashed(hashes.SHA512()))
            else:
                signed_value_signature = key.sign(
                    tosign, padding.PKCS1v15(),
                    getattr(hashes, hashalgo.upper())())

        if timestampurl is not None:
            signed_value = getattr(hashlib,
                                   hashalgo)(signed_value_signature).digest()
            tspreq = tsp.TimeStampReq({
                "version":
                1,
                "message_imprint":
                tsp.MessageImprint({
                    "hash_algorithm":
                    algos.DigestAlgorithm({'algorithm': hashalgo}),
                    "hashed_message":
                    signed_value,
                }),
                "nonce":
                int(time.time() * 1000),
                "cert_req":
                True,
            })
            tspreq = tspreq.dump()

            tspheaders = {"Content-Type": "application/timestamp-query"}
            tspresp = requests.post(timestampurl,
                                    data=tspreq,
                                    headers=tspheaders)
            if tspresp.headers.get('Content-Type',
                                   None) == 'application/timestamp-reply':
                tspresp = tsp.TimeStampResp.load(tspresp.content)

                if tspresp['status']['status'].native == 'granted':
                    attrs = [
                        cms.CMSAttribute({
                            'type':
                            cms.CMSAttributeType('signature_time_stamp_token'),
                            'values':
                            cms.SetOfContentInfo([
                                cms.ContentInfo({
                                    'content_type':
                                    cms.ContentType('signed_data'),
                                    'content':
                                    tspresp["time_stamp_token"]["content"],
                                })
                            ])
                        })
                    ]
                    datas['content']['signer_infos'][0][
                        'unsigned_attrs'] = attrs

        # signed_value_signature = core.OctetString(signed_value_signature)
        datas['content']['signer_infos'][0][
            'signature'] = signed_value_signature

        return datas.dump()
Ejemplo n.º 6
0
    def unsignedpropertied(self,
                           signed_value,
                           tspurl,
                           tspcred,
                           hashalgo="sha256"):
        if tspurl is None:
            unsignedproperties = UnsignedProperties(
                Id="UnsignedProperties_" + self.guid + self.mapa["_5d"])
        else:
            tspreq = tsp.TimeStampReq({
                "version":
                1,
                "message_imprint":
                tsp.MessageImprint({
                    "hash_algorithm":
                    algos.DigestAlgorithm({"algorithm": hashalgo}),
                    "hashed_message":
                    signed_value.encode(),
                }),
                #'req_policy', ObjectIdentifier, {'optional': True}),
                "nonce":
                int(time.time() * 1000),
                "cert_req":
                True,
                #'extensions': tsp.Extensions()
            })
            tspreq = tspreq.dump()

            tspheaders = {"Content-Type": "application/timestamp-query"}
            if tspcred is not None:
                username = tspcred.get("username", None)
                password = tspcred.get("password", None)
                if username and password:
                    auth_header_value = base64.b64encode(
                        bytes(username + ":" + password,
                              "utf-8")).decode("ascii")
                    tspheaders["Authorization"] = f"Basic {auth_header_value}"
            tspresp = requests.post(tspurl, data=tspreq, headers=tspheaders)
            if (tspresp.headers.get("Content-Type",
                                    None) == "application/timestamp-reply"):
                tspresp = tsp.TimeStampResp.load(tspresp.content)

                if tspresp["status"]["status"].native == "granted":
                    attr = self.base64(tspresp["time_stamp_token"].dump())
                else:
                    raise ValueError("TimeStampResponse status is not granted")
            else:
                raise ValueError("TimeStampResponse has invalid content type")

            unsignedproperties = UnsignedProperties(
                UnsignedSignatureProperties(
                    SignatureTimeStamp(
                        CanonicalizationMethod(
                            Algorithm=
                            "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"),
                        EncapsulatedTimeStamp(
                            attr,
                            Encoding="http://uri.etsi.org/01903/v1.2.2#DER"),
                        Id="SignatureTimeStamp_" + self.guid,
                    )),
                Id="UnsignedProperties_" + self.guid + self.mapa["_5d"],
            )
        return unsignedproperties