示例#1
0
def SignAlert(xml_tree, username):
  """Sign XML with user key/certificate.

  Args:
    xml_tree: (string) Alert XML tree.
    username: (string) Username of the alert author.

  Returns:
    String.
    Signed alert XML tree if your has key/certificate pair
    Unchanged XML tree otherwise.
  """

  if not XMLSEC_DEFINED:
    return xml_tree

  key_path = os.path.join(settings.CREDENTIALS_DIR, username + ".key")
  cert_path = os.path.join(settings.CREDENTIALS_DIR, username + ".cert")

  try:
    signed_xml_tree = copy.deepcopy(xml_tree)
    xmlsec.add_enveloped_signature(signed_xml_tree, pos=-1)
    xmlsec.sign(signed_xml_tree, key_path, cert_path)
    return signed_xml_tree
  except (IOError, xmlsec.exceptions.XMLSigException):
    return xml_tree
示例#2
0
def SignAlert(xml_tree, username):
    """Sign XML with user key/certificate.

  Args:
    xml_tree: (string) Alert XML tree.
    username: (string) Username of the alert author.

  Returns:
    String.
    Signed alert XML tree if your has key/certificate pair
    Unchanged XML tree otherwise.
  """

    if not XMLSEC_DEFINED:
        return xml_tree

    key_path = os.path.join(settings.CREDENTIALS_DIR, username + ".key")
    cert_path = os.path.join(settings.CREDENTIALS_DIR, username + ".cert")

    try:
        signed_xml_tree = copy.deepcopy(xml_tree)
        xmlsec.add_enveloped_signature(signed_xml_tree, pos=-1)
        xmlsec.sign(signed_xml_tree, key_path, cert_path)
        return signed_xml_tree
    except (IOError, xmlsec.exceptions.XMLSigException):
        return xml_tree
示例#3
0
 def signCAP(self, xml_tree):
     try:
         signed_xml_tree = copy.deepcopy(xml_tree)
         xmlsec.add_enveloped_signature(signed_xml_tree, pos=-1)
         xmlsec.sign(signed_xml_tree, self.key_path, self.cert_path)
         return signed_xml_tree
     except:
         return xml_tree
示例#4
0
    def test_mm_with_java_alt(self):
        case = self.cases['mm5']
        t = case.as_etree('in.xml')
        xmlsec.add_enveloped_signature(t,
                                       pos=-1,
                                       c14n_method=constants.TRANSFORM_C14N_EXCLUSIVE,
                                       transforms=[constants.TRANSFORM_ENVELOPED_SIGNATURE])
        signed = xmlsec.sign(t,
                             key_spec=self.private_keyspec,
                             cert_spec=self.public_keyspec)

        expected = case.as_etree('out.xml')

        print " --- Expected"
        print etree.tostring(expected)
        print " --- Actual"
        print etree.tostring(signed)

        # extract 'SignatureValue's
        expected_sv = _get_all_signatures(expected)
        signed_sv = _get_all_signatures(signed)

        print "Signed   SignatureValue: %s" % (repr(signed_sv))
        print "Expected SignatureValue: %s" % (repr(expected_sv))

        self.assertEqual(signed_sv, expected_sv)
示例#5
0
 def test_wrapping_attack(self):
     """
     Test resistance to attempted wrapping attack
     """
     case = self.cases['SAML_assertion1']
     print("XML input :\n{}\n\n".format(case.as_buf('in.xml')))
     tbs = case.as_etree('in.xml')
     signed = xmlsec.sign(tbs,
                          key_spec=self.private_keyspec,
                          cert_spec=self.public_keyspec)
     attack = case.as_etree('evil.xml')
     attack.append(signed)
     refs = xmlsec.verified(attack, self.public_keyspec)
     self.assertTrue(len(refs) == 1)
     print("verified XML: %s" % etree.tostring(refs[0]))
     seen_foo = False
     seen_bar = False
     for av in refs[0].findall(".//{%s}AttributeValue" % 'urn:oasis:names:tc:SAML:2.0:assertion'):
         print(etree.tostring(av))
         print(av.text)
         if av.text == 'Foo':
             seen_foo = True
         elif av.text == 'Bar':
             seen_bar = True
         self.assertTrue(av.text != 'admin')
     self.assertTrue(seen_foo and seen_bar)
示例#6
0
    def test_mm2(self):
        case = self.cases['mm2']
        t = case.as_etree('in.xml')
        xmlsec.add_enveloped_signature(t,
                                       pos=-1,
                                       c14n_method=constants.TRANSFORM_C14N_EXCLUSIVE,
                                       digest_alg=constants.ALGORITHM_DIGEST_SHA1,
                                       signature_alg=constants.ALGORITHM_SIGNATURE_RSA_SHA1,
                                       transforms=[constants.TRANSFORM_ENVELOPED_SIGNATURE])
        signed = xmlsec.sign(t,
                             key_spec=self.private_keyspec,
                             cert_spec=self.public_keyspec)

        expected = case.as_etree('out.xml')

        print(" --- Expected")
        print(etree.tostring(expected))
        print(" --- Actual")
        print(etree.tostring(signed))

        # extract 'SignatureValue's
        expected_sv = _get_all_signatures(expected)
        signed_sv = _get_all_signatures(signed)

        print("Signed   SignatureValue: %s" % (repr(signed_sv)))
        print("Expected SignatureValue: %s" % (repr(expected_sv)))

        self.assertEqual(signed_sv, expected_sv)
示例#7
0
 def test_wrapping_attack(self):
     """
     Test resistance to attempted wrapping attack
     """
     case = self.cases['SAML_assertion1']
     print("XML input :\n{}\n\n".format(case.as_buf('in.xml')))
     tbs = case.as_etree('in.xml')
     signed = xmlsec.sign(tbs,
                          key_spec=self.private_keyspec,
                          cert_spec=self.public_keyspec)
     attack = case.as_etree('evil.xml')
     attack.append(signed)
     refs = xmlsec.verified(attack, self.public_keyspec)
     self.assertTrue(len(refs) == 1)
     print("verified XML: %s" % etree.tostring(refs[0]))
     seen_foo = False
     seen_bar = False
     for av in refs[0].findall(".//{%s}AttributeValue" %
                               'urn:oasis:names:tc:SAML:2.0:assertion'):
         print(etree.tostring(av))
         print(av.text)
         if av.text == 'Foo':
             seen_foo = True
         elif av.text == 'Bar':
             seen_bar = True
         self.assertTrue(av.text != 'admin')
     self.assertTrue(seen_foo and seen_bar)
示例#8
0
    def test_sign_verify_SAML_assertion_sha256(self):
        """
        Test signing a SAML assertion using sha256, and making sure we can verify it.
        """
        case = self.cases['SAML_assertion_sha256']
        print("XML input :\n{}\n\n".format(case.as_buf('in.xml')))

        signed = xmlsec.sign(case.as_etree('in.xml'),
                             key_spec=self.private_keyspec,
                             cert_spec=self.public_keyspec)
        res = xmlsec.verify(signed, self.public_keyspec)
        self.assertTrue(res)
示例#9
0
    def secure_message_sign(self, root):
        """
        Sign the SignedDelivery message.
        """
        del root.attrib['xmlns']
        unsigned_xml = apply_xslt(root, 'secure_message_drop_ns.xsl')
        unsigned_xml.attrib['xmlns'] = 'http://minameddelanden.gov.se/schema/Message'
        xmlsec.add_enveloped_signature(unsigned_xml, pos=-1, c14n_method=constants.TRANSFORM_C14N_EXCLUSIVE,
                                       transforms=[constants.TRANSFORM_ENVELOPED_SIGNATURE])
        xml_signed = xmlsec.sign(unsigned_xml, self.key_file, self.cert)

        return xml_signed
示例#10
0
    def test_sign_xades(self):
        """
        Test that we can sign an already signed document without breaking the first signature
        """

        case = self.cases['dont_break_xades']
        t = case.as_etree('in.xml')

        signed = xmlsec.sign(t, self.private_keyspec)
        self.assertIsNotNone(signed)
        digests = [dv.text for dv in signed.findall('.//{%s}DigestValue' % xmlsec.NS['ds'])]
        assert 'JvmW5vKjaTEVHzOdiC/H3HSGNocGamY9sDeU86ld6TA=' in digests
        res = xmlsec.verify(signed, self.public_keyspec)
        self.assertTrue(res)
示例#11
0
    def test_duo_vuln_attack(self):
        """
        Test https://duo.com/blog/duo-finds-saml-vulnerabilities-affecting-multiple-implementations
        """
        case = self.cases['SAML_assertion_sha256']
        print("XML input :\n{}\n\n".format(case.as_buf('in.xml')))

        signed = xmlsec.sign(case.as_etree('in.xml'),
                             key_spec=self.private_keyspec,
                             cert_spec=self.public_keyspec)
        refs = xmlsec.verified(signed, self.public_keyspec)
        self.assertTrue(len(refs) == 1)
        print("verified XML: %s" % etree.tostring(refs[0]))
        assert('evil' not in [x.text for x in refs[0].findall(".//{%s}AttributeValue" % 'urn:oasis:names:tc:SAML:2.0:assertion')])
    def test_sign_xades(self):
        """
        Test that we can sign an already signed document without breaking the first signature
        """

        case = self.cases['dont_break_xades']
        t = case.as_etree('in.xml')

        signed = xmlsec.sign(t, self.private_keyspec)
        self.assertIsNotNone(signed)
        digests = [dv.text for dv in signed.findall('.//{%s}DigestValue' % xmlsec.NS['ds'])]
        assert 'JvmW5vKjaTEVHzOdiC/H3HSGNocGamY9sDeU86ld6TA=' in digests
        res = xmlsec.verify(signed, self.public_keyspec)
        self.assertTrue(res)
示例#13
0
    def test_SAML_sign_with_pkcs11(self):
        """
        Test signing a SAML assertion using PKCS#11 and then verifying it using plain file.
        """
        case = self.cases['SAML_assertion1']
        print("XML input :\n{}\n\n".format(case.as_buf('in.xml')))

        os.environ['SOFTHSM_CONF'] = softhsm_conf

        signed = xmlsec.sign(case.as_etree('in.xml'),
                             key_spec="pkcs11://%s:0/test?pin=secret1" % P11_MODULE)

        # verify signature using the public key
        res = xmlsec.verify(signed, signer_cert_pem)
        self.assertTrue(res)
示例#14
0
    def secure_message_sign(self, root):
        """
        Sign the the SignedDelivery message.
        """
        # Root element must be renamed before signing and then renamed back to the old value
        root.tag = 'SignedDelivery'
        unsigned_xml = apply_xslt(root, 'secure_message_drop_ns.xsl')
        unsigned_xml.attrib['xmlns'] = 'http://minameddelanden.gov.se/schema/Message'
        xmlsec.add_enveloped_signature(unsigned_xml, pos=-1, c14n_method=constants.TRANSFORM_C14N_EXCLUSIVE,
                                       transforms=[constants.TRANSFORM_ENVELOPED_SIGNATURE])
        xml_signed = xmlsec.sign(unsigned_xml, self.key_file, self.cert)
        xml_signed.tag = 'arg0'
        del xml_signed.attrib['xmlns']

        return xml_signed
示例#15
0
def sign_xml(xml_stream, key_fname, cert_fname):
    template = etree.XML(xml_stream)

    opts = dict()
    if hasattr(template, 'getroot') and \
       hasattr(template.getroot, '__call__'):
        root = template.getroot()
    else:
        root = template
    idattr = root.get('ID') or root.get('id')
    if idattr:
        opts['reference_uri'] = "#{}".format(idattr)

    signed_xml = xmlsec.sign(root, key_fname, cert_fname, **opts)
    return etree.tostring(signed_xml)
示例#16
0
 def seal_delivery_sign(self, root):
     """
     Sign the SealedDelivery message.
     """
     root.tag = 'SealedDelivery'
     root.attrib['xmlns'] = 'http://minameddelanden.gov.se/schema/Message'
     xmlsec.add_enveloped_signature(root, pos=-1, c14n_method=constants.TRANSFORM_C14N_EXCLUSIVE,
                                    transforms=[constants.TRANSFORM_ENVELOPED_SIGNATURE,
                                                constants.TRANSFORM_C14N_EXCLUSIVE])
     xml_signed = xmlsec.sign(root,
                              self.key_file,
                              self.cert,
                              sig_path="./{http://www.w3.org/2000/09/xmldsig#}Signature")
     xml_signed.tag = 'arg0'
     del xml_signed.attrib['xmlns']
     return xml_signed
示例#17
0
    def test_sign_verify_SAML_assertion_unwrap2(self):
        """
        Test signing a SAML assertion, and return verified data.
        """
        case = self.cases['SAML_assertion1']
        print("XML input :\n{}\n\n".format(case.as_buf('in.xml')))

        tbs = case.as_etree('in.xml')
        signed = xmlsec.sign(tbs,
                             key_spec=self.private_keyspec,
                             cert_spec=self.public_keyspec)
        refs = xmlsec.verified(signed, self.public_keyspec)
        self.assertTrue(len(refs) == 1)
        print("verified XML: %s" % etree.tostring(refs[0]))
        self.assertTrue(tbs.tag == refs[0].tag)
        set1 = set(etree.tostring(i, method='c14n') for i in root(tbs))
        set2 = set(etree.tostring(i, method='c14n') for i in root(refs[0]))
        self.assertTrue(set1 == set2)
示例#18
0
    def test_sign_verify_SAML_assertion_unwrap2(self):
        """
        Test signing a SAML assertion, and return verified data.
        """
        case = self.cases['SAML_assertion1']
        print("XML input :\n{}\n\n".format(case.as_buf('in.xml')))

        tbs = case.as_etree('in.xml')
        signed = xmlsec.sign(tbs,
                             key_spec=self.private_keyspec,
                             cert_spec=self.public_keyspec)
        refs = xmlsec.verified(signed, self.public_keyspec)
        self.assertTrue(len(refs) == 1)
        print("verified XML: %s" % etree.tostring(refs[0]))
        self.assertTrue(tbs.tag == refs[0].tag)
        set1 = set(etree.tostring(i, method='c14n') for i in root(tbs))
        set2 = set(etree.tostring(i, method='c14n') for i in root(refs[0]))
        self.assertTrue(set1 == set2)
示例#19
0
文件: sigver.py 项目: gbel/pysaml2
    def sign_statement(self, statement, _class_name, key_file, node_id,
                       _id_attr):
        """
        Sign an XML statement.

        The parameters actually used in this CryptoBackend
        implementation are :

        :param statement: XML as string
        :param key_file: xmlsec key_spec string(), filename,
            "pkcs11://" URI or PEM data
        :returns: Signed XML as string
        """
        import xmlsec
        import lxml.etree

        xml = xmlsec.parse_xml(statement)
        signed = xmlsec.sign(xml, key_file)
        return lxml.etree.tostring(signed, xml_declaration=True)
示例#20
0
    def sign_statement(self, statement, _class_name, key_file, node_id,
                       _id_attr):
        """
        Sign an XML statement.

        The parameters actually used in this CryptoBackend
        implementation are :

        :param statement: XML as string
        :param key_file: xmlsec key_spec string(), filename,
            "pkcs11://" URI or PEM data
        :returns: Signed XML as string
        """
        import xmlsec
        import lxml.etree

        xml = xmlsec.parse_xml(statement)
        signed = xmlsec.sign(xml, key_file)
        return lxml.etree.tostring(signed, xml_declaration=True)
示例#21
0
    def test_mm_with_inner_signature(self):
        expected_digest = 'd62qF9gk1F1/JcdUrtJUqPtoMHc='
        case = self.cases['mm6']
        t = case.as_etree('in.xml')

        xmlsec.add_enveloped_signature(
            t,
            pos=-1,
            c14n_method=constants.TRANSFORM_C14N_EXCLUSIVE,
            digest_alg=constants.ALGORITHM_DIGEST_SHA1,
            signature_alg=constants.ALGORITHM_SIGNATURE_RSA_SHA1,
            transforms=[constants.TRANSFORM_ENVELOPED_SIGNATURE])
        signed = xmlsec.sign(
            t,
            key_spec=self.private_keyspec,
            cert_spec=self.public_keyspec,
            sig_path="./{http://www.w3.org/2000/09/xmldsig#}Signature")

        expected = case.as_etree('out.xml')

        sig = t.find("./{%s}Signature" % xmlsec.NS['ds'])
        digest = sig.findtext('.//{%s}DigestValue' % xmlsec.NS['ds'])

        print " --- Expected digest value"
        print expected_digest
        print " --- Actual digest value"
        print digest

        print " --- Expected"
        print etree.tostring(expected)
        print " --- Actual"
        print etree.tostring(signed)

        # extract 'SignatureValue's
        expected_sv = _get_all_signatures(expected)
        signed_sv = _get_all_signatures(signed)

        print "Signed   SignatureValue: %s" % (repr(signed_sv))
        print "Expected SignatureValue: %s" % (repr(expected_sv))

        self.assertEquals(digest, expected_digest)
        self.assertEqual(signed_sv, expected_sv)
示例#22
0
    def test_edugain_with_xmlsec1(self):
        case = self.cases['edugain']
        t = case.as_etree('xmlsec1_in.xml')
        signed = xmlsec.sign(t,
                             key_spec=self.private_keyspec,
                             cert_spec=self.public_keyspec)

        expected = case.as_etree('xmlsec1_out.xml')

        print " --- Expected"
        print etree.tostring(expected)
        print " --- Actual"
        print etree.tostring(signed)

        # extract 'SignatureValue's
        expected_sv = _get_all_signatures(expected)
        signed_sv = _get_all_signatures(signed)

        print "Signed   SignatureValue: %s" % (repr(signed_sv))
        print "Expected SignatureValue: %s" % (repr(expected_sv))
示例#23
0
    def test_sign_SAML_assertion_sha256(self):
        """
        Test signing a SAML assertion using sha256, and compare resulting signature with that of another implementation (xmlsec1).
        """
        case = self.cases['SAML_assertion_sha256']
        print("XML input :\n{}\n\n".format(case.as_buf('in.xml')))

        signed = xmlsec.sign(case.as_etree('in.xml'),
                             key_spec=self.private_keyspec,
                             cert_spec=self.public_keyspec)
        expected = case.as_etree('out.xml')

        # extract 'SignatureValue's
        expected_sv = _get_all_signatures(expected)
        signed_sv = _get_all_signatures(signed)

        print "Signed   SignatureValue: %s" % (repr(signed_sv))
        print "Expected SignatureValue: %s" % (repr(expected_sv))

        self.assertEqual(signed_sv, expected_sv)
示例#24
0
    def test_mm_with_inner_signature(self):
        expected_digest = 'd62qF9gk1F1/JcdUrtJUqPtoMHc='
        case = self.cases['mm6']
        t = case.as_etree('in.xml')

        xmlsec.add_enveloped_signature(t,
                                       pos=-1,
                                       c14n_method=constants.TRANSFORM_C14N_EXCLUSIVE,
                                       digest_alg=constants.ALGORITHM_DIGEST_SHA1,
                                       signature_alg=constants.ALGORITHM_SIGNATURE_RSA_SHA1,
                                       transforms=[constants.TRANSFORM_ENVELOPED_SIGNATURE])
        signed = xmlsec.sign(t,
                             key_spec=self.private_keyspec,
                             cert_spec=self.public_keyspec,
                             sig_path="./{http://www.w3.org/2000/09/xmldsig#}Signature")

        expected = case.as_etree('out.xml')

        sig = t.find("./{%s}Signature" % xmlsec.NS['ds'])
        digest = sig.findtext('.//{%s}DigestValue' % xmlsec.NS['ds'])

        print(" --- Expected digest value")
        print(expected_digest)
        print(" --- Actual digest value")
        print(digest)

        print(" --- Expected")
        print(etree.tostring(expected))
        print(" --- Actual")
        print(etree.tostring(signed))

        # extract 'SignatureValue's
        expected_sv = _get_all_signatures(expected)
        signed_sv = _get_all_signatures(signed)

        print("Signed   SignatureValue: %s" % (repr(signed_sv)))
        print("Expected SignatureValue: %s" % (repr(expected_sv)))

        self.assertEquals(digest, expected_digest)
        self.assertEqual(signed_sv, expected_sv)
示例#25
0
    def test_mm_with_java(self):
        case = self.cases['mm4']
        t = case.as_etree('in.xml')
        signed = xmlsec.sign(t,
                             key_spec=self.private_keyspec,
                             cert_spec=self.public_keyspec)

        expected = case.as_etree('out.xml')

        print " --- Expected"
        print etree.tostring(expected)
        print " --- Actual"
        print etree.tostring(signed)

        # extract 'SignatureValue's
        expected_sv = _get_all_signatures(expected)
        signed_sv = _get_all_signatures(signed)

        print "Signed   SignatureValue: %s" % (repr(signed_sv))
        print "Expected SignatureValue: %s" % (repr(expected_sv))

        self.assertEqual(signed_sv, expected_sv)
示例#26
0
    def test_sign_verify_all(self):
        """
        Run through all testcases, sign and verify using xmlsec1
        """
        for case in self.cases.values():
            if case.has_data('in.xml'):
                signed = xmlsec.sign(case.as_etree('in.xml'),
                                     key_spec=self.private_keyspec,
                                     cert_spec=self.public_keyspec)
                res = xmlsec.verify(signed, self.public_keyspec)
                self.assertTrue(res)
                with open(self.tmpf.name, "w") as fd:
                    fd.write(etree.tostring(signed))

                run_cmd([XMLSEC1,
                         '--verify',
                         '--store-references',
                         '--id-attr:ID', 'urn:oasis:names:tc:SAML:2.0:metadata:EntityDescriptor',
                         '--id-attr:ID', 'urn:oasis:names:tc:SAML:2.0:metadata:EntitiesDescriptor',
                         '--id-attr:ID', 'urn:oasis:names:tc:SAML:2.0:assertion:Assertion',
                         '--verification-time', '2009-11-01 12:00:00',
                         '--trusted-pem', self.public_keyspec,
                         self.tmpf.name])
示例#27
0
 def test_mm1(self):
     case = self.cases['mm1']
     signed = xmlsec.sign(case.as_etree('in.xml'),
                          key_spec=self.private_keyspec,
                          cert_spec=self.public_keyspec)
     print etree.tostring(signed)
示例#28
0
                             key_spec=self.private_keyspec,
                             cert_spec=self.public_keyspec)
        print etree.tostring(signed)

    def test_mm2(self):
        case = self.cases['mm2']
        t = case.as_etree('in.xml')
        xmlsec.add_enveloped_signature(
            t,
            pos=-1,
            c14n_method=constants.TRANSFORM_C14N_EXCLUSIVE,
            digest_alg=constants.ALGORITHM_DIGEST_SHA1,
            signature_alg=constants.ALGORITHM_SIGNATURE_RSA_SHA1,
            transforms=[constants.TRANSFORM_ENVELOPED_SIGNATURE])
        signed = xmlsec.sign(t,
                             key_spec=self.private_keyspec,
                             cert_spec=self.public_keyspec)

        expected = case.as_etree('out.xml')

        print " --- Expected"
        print etree.tostring(expected)
        print " --- Actual"
        print etree.tostring(signed)

        # extract 'SignatureValue's
        expected_sv = _get_all_signatures(expected)
        signed_sv = _get_all_signatures(signed)

        print "Signed   SignatureValue: %s" % (repr(signed_sv))
        print "Expected SignatureValue: %s" % (repr(expected_sv))
示例#29
0
文件: builtins.py 项目: Renater/pyFF
def sign(req, *opts):
    """

    Sign the working document.

    :param req: The request
    :param opts: Options (unused)
    :return: returns the signed working document

    Sign expects a single dict with at least a 'key' key and optionally a 'cert' key. The 'key' argument references
    either a PKCS#11 uri or the filename containing a PEM-encoded non-password protected private RSA key.
    The 'cert' argument may be empty in which case the cert is looked up using the PKCS#11 token, or may point
    to a file containing a PEM-encoded X.509 certificate.

    **PKCS11 URIs**

    A pkcs11 URI has the form

    .. code-block:: xml

        pkcs11://<absolute path to SO/DLL>[:slot]/<object label>[?pin=<pin>]

    The pin parameter can be used to point to an environment variable containing the pin: "env:<ENV variable>".
    By default pin is "env:PYKCS11PIN" which tells sign to use the pin found in the PYKCS11PIN environment
    variable. This is also the default for PyKCS11 which is used to communicate with the PKCS#11 module.

    **Examples**

    .. code-block:: yaml

        - sign:
            key: pkcs11:///usr/lib/libsofthsm.so/signer

    This would sign the document using the key with label 'signer' in slot 0 of the /usr/lib/libsofthsm.so module.
    Note that you may need to run pyff with env PYKCS11PIN=<pin> .... for this to work. Consult the documentation
    of your PKCS#11 module to find out about any other configuration you may need.

    .. code-block:: yaml

        - sign:
            key: signer.key
            cert: signer.crt

    This example signs the document using the plain key and cert found in the signer.key and signer.crt files.

    """
    if req.t is None:
        raise PipeException("Your pipeline is missing a select statement.")

    if not type(req.args) is dict:
        raise PipeException("Missing key and cert arguments to sign pipe")

    key_file = req.args.get('key', None)
    cert_file = req.args.get('cert', None)

    if key_file is None:
        raise PipeException("Missing key argument for sign pipe")

    if cert_file is None:
        log.info("Attempting to extract certificate from token...")

    opts = dict()
    relt = root(req.t)
    idattr = relt.get('ID')
    if idattr:
        opts['reference_uri'] = "#%s" % idattr
    xmlsec.sign(req.t, key_file, cert_file, **opts)

    return req.t
示例#30
0
# Dados da NFe para assinar
chave = '35190107400225000184550020000067271182139170'
# nfe = '/tmp/%s-nfe.xml' % chave  # caminho para a NFe da chave acima
reference_uri = '#NFe' + chave
# xml = lxml.etree.parse(nfe)
xml_str = """<NFe xmlns="http://www.portalfiscal.inf.br/nfe"><infNFe versao="4.00" Id="NFe35190107400225000184550020000067271182139170"><ide><cUF>35</cUF><cNF>18213917</cNF><natOp>VENDA DE MERCADORIA</natOp><mod>55</mod><serie>2</serie><nNF>6727</nNF><dhEmi>2019-01-10T09:18:00-04:00</dhEmi><dhSaiEnt>2019-01-10T09:18:00-04:00</dhSaiEnt><tpNF>1</tpNF><idDest>1</idDest><cMunFG>3509502</cMunFG><tpImp>1</tpImp><tpEmis>1</tpEmis><cDV>0</cDV><tpAmb>1</tpAmb><finNFe>1</finNFe><indFinal>1</indFinal><indPres>0</indPres><procEmi>0</procEmi><verProc>LinxERP8111836</verProc></ide><emit><CNPJ>07400225000184</CNPJ><xNome>RAFAEL COUTINHO DE MELO SERRANO EIRELI</xNome><xFant>ECOMMERCE</xFant><enderEmit><xLgr>R SANTOS DUMONT</xLgr><nro>845</nro><xBairro>CAMBUI</xBairro><cMun>3509502</cMun><xMun>CAMPINAS</xMun><UF>SP</UF><CEP>13024021</CEP><cPais>1058</cPais><xPais>BRASIL</xPais></enderEmit><IE>795989794119</IE><CRT>3</CRT></emit><dest><CPF>25884285841</CPF><xNome>ROSELI AMORIM</xNome><enderDest><xLgr>RUA SANTOS DUMONT</xLgr><nro>845</nro><xCpl>LOJA</xCpl><xBairro>CAMBUI</xBairro><cMun>3509502</cMun><xMun>CAMPINAS</xMun><UF>SP</UF><CEP>13024021</CEP><cPais>1058</cPais><xPais>BRASIL</xPais><fone>19983983440</fone></enderDest><indIEDest>9</indIEDest><email>[email protected]</email></dest><det nItem="1"><prod><cProd>28.01.0052</cProd><cEAN>SEM GTIN</cEAN><xProd>CHEMISIE FRANZIDO BRENTWOOD</xProd><NCM>61044400</NCM><CFOP>5102</CFOP><uCom>PC</uCom><qCom>1.0000</qCom><vUnCom>74.9900000000</vUnCom><vProd>74.99</vProd><cEANTrib>SEM GTIN</cEANTrib><uTrib>PC</uTrib><qTrib>1.0000</qTrib><vUnTrib>74.9900000000</vUnTrib><indTot>1</indTot></prod><imposto><vTotTrib>10.09</vTotTrib><ICMS><ICMS00><orig>0</orig><CST>00</CST><modBC>3</modBC><vBC>74.99</vBC><pICMS>18.0000</pICMS><vICMS>13.49</vICMS></ICMS00></ICMS><IPI><cEnq>999</cEnq><IPINT><CST>53</CST></IPINT></IPI><PIS><PISAliq><CST>01</CST><vBC>74.99</vBC><pPIS>0.6500</pPIS><vPIS>0.49</vPIS></PISAliq></PIS><COFINS><COFINSAliq><CST>01</CST><vBC>74.99</vBC><pCOFINS>3.0000</pCOFINS><vCOFINS>2.25</vCOFINS></COFINSAliq></COFINS></imposto><infAdProd>.   Trib. Aprox. R$: 10.09 Federal e 13.50 Estadual FONTE: IBPT/empresometro.com.br  D529CB</infAdProd></det><total><ICMSTot><vBC>74.99</vBC><vICMS>13.49</vICMS><vICMSDeson>0.00</vICMSDeson><vICMSUFDest>0.00</vICMSUFDest><vICMSUFRemet>0.00</vICMSUFRemet><vFCP>0.00</vFCP><vBCST>0.00</vBCST><vST>0.00</vST><vFCPST>0.00</vFCPST><vFCPSTRet>0.00</vFCPSTRet><vProd>74.99</vProd><vFrete>0.00</vFrete><vSeg>0.00</vSeg><vDesc>0.00</vDesc><vII>0.00</vII><vIPI>0.00</vIPI><vIPIDevol>0.00</vIPIDevol><vPIS>0.49</vPIS><vCOFINS>2.25</vCOFINS><vOutro>0.00</vOutro><vNF>74.99</vNF><vTotTrib>10.09</vTotTrib></ICMSTot></total><transp><modFrete>1</modFrete><transporta><CNPJ>34028316003129</CNPJ><xNome>NORMAL (16ED1F7)</xNome><xMun>CAMPINAS</xMun><UF>SP</UF></transporta><vol><qVol>1</qVol><esp>CAIXA DE PAPELAO</esp></vol></transp><pag><detPag><indPag>1</indPag><tPag>99</tPag><vPag>74.99</vPag></detPag></pag><infAdic><infCpl>TRIB. APROX. R$: 10.09 FEDERAL E 13.50 ESTADUAL FONTE: IBPT/EMPRESOMETRO.COM.BR    D529CB</infCpl></infAdic></infNFe></NFe>"""
xml = etree.fromstring(xml_str)
# Tags XML da assinatura conforme padrão da NFe
transforms = (xmlsec.constants.TRANSFORM_ENVELOPED_SIGNATURE,
              xmlsec.constants.TRANSFORM_C14N_INCLUSIVE)
xmlsec.add_enveloped_signature(xml,
                               transforms=transforms,
                               reference_uri=reference_uri,
                               pos=-1)

# Especificação para usar o A3

keyname = urllib2.quote(keyname, '')
pk11_uri = 'pkcs11://%s/%s?pin=%s' % (module, keyname, pin)

# Assinando a NFe com A3
a, cert, chave = xmlsec.sign(xml, pk11_uri)
print(chave)
# Salvando a NFe assinada
import pdb
pdb.set_trace()
xml.write(nfe[:-3] + '-assinada.xml',
          encoding=xml.docinfo.encoding,
          xml_declaration=True)

# print(xml)
示例#31
0
文件: builtins.py 项目: pmeulen/pyFF
def sign(req, *opts):
    """
Sign the working document.

:param req: The request
:param opts: Options (unused)
:return: returns the signed working document

Sign expects a single dict with at least a 'key' key and optionally a 'cert' key. The 'key' argument references
either a PKCS#11 uri or the filename containing a PEM-encoded non-password protected private RSA key.
The 'cert' argument may be empty in which case the cert is looked up using the PKCS#11 token, or may point
to a file containing a PEM-encoded X.509 certificate.

**PKCS11 URIs**

A pkcs11 URI has the form

.. code-block:: xml

    pkcs11://<absolute path to SO/DLL>[:slot]/<object label>[?pin=<pin>]

The pin parameter can be used to point to an environment variable containing the pin: "env:<ENV variable>".
By default pin is "env:PYKCS11PIN" which tells sign to use the pin found in the PYKCS11PIN environment
variable. This is also the default for PyKCS11 which is used to communicate with the PKCS#11 module.

**Examples**

.. code-block:: yaml

    - sign:
        key: pkcs11:///usr/lib/libsofthsm.so/signer

This would sign the document using the key with label 'signer' in slot 0 of the /usr/lib/libsofthsm.so module.
Note that you may need to run pyff with env PYKCS11PIN=<pin> .... for this to work. Consult the documentation
of your PKCS#11 module to find out about any other configuration you may need.

.. code-block:: yaml

    - sign:
        key: signer.key
        cert: signer.crt

This example signs the document using the plain key and cert found in the signer.key and signer.crt files.
    """
    if req.t is None:
        raise PipeException("Your pipeline is missing a select statement.")

    if not type(req.args) is dict:
        raise PipeException("Missing key and cert arguments to sign pipe")

    key_file = req.args.get('key', None)
    cert_file = req.args.get('cert', None)

    if key_file is None:
        raise PipeException("Missing key argument for sign pipe")

    if cert_file is None:
        log.info("Attempting to extract certificate from token...")

    opts = dict()
    relt = root(req.t)
    idattr = relt.get('ID')
    if idattr:
        opts['reference_uri'] = "#%s" % idattr
    xmlsec.sign(req.t, key_file, cert_file, **opts)

    return req.t