コード例 #1
0
ファイル: decrypt2.py プロジェクト: DeltaOS/pyxmlsec
def load_des_keys(files, files_size):
    assert(files)
    assert(files_size > 0)

    # Create and initialize keys manager, we use a simple list based
    # keys manager, implement your own KeysStore klass if you need
    # something more sophisticated
    mngr = xmlsec.KeysMngr()
    if mngr is None:
        print "Error: failed to create keys manager."
        return None
    if xmlsec.cryptoAppDefaultKeysMngrInit(mngr) < 0:
        print "Error: failed to initialize keys manager."
        mngr.destroy()
        return None
    for file in files:
        if not check_filename(file):
            mngr.destroy()
            return None
        # Load DES key
        key = xmlsec.keyReadBinaryFile(xmlsec.keyDataDesId(), file)
        if key is None:
    	    print "Error: failed to load des key from binary file \"%s\"" % file
	    mngr.destroy()
            return None
        # Add key to keys manager, from now on keys manager is responsible
	# for destroying key
        if xmlsec.cryptoAppDefaultKeysMngrAdoptKey(mngr, key) < 0:
    	    print "Error: failed to add key from \"%s\" to keys manager" % file
            key.destroy()
	    mngr.destroy()
            return None
    return mngr
コード例 #2
0
ファイル: decrypt2.py プロジェクト: quinox/pyxmlsec
def load_des_keys(files, files_size):
    assert (files)
    assert (files_size > 0)

    # Create and initialize keys manager, we use a simple list based
    # keys manager, implement your own KeysStore klass if you need
    # something more sophisticated
    mngr = xmlsec.KeysMngr()
    if mngr is None:
        print "Error: failed to create keys manager."
        return None
    if xmlsec.cryptoAppDefaultKeysMngrInit(mngr) < 0:
        print "Error: failed to initialize keys manager."
        mngr.destroy()
        return None
    for file in files:
        if not check_filename(file):
            mngr.destroy()
            return None
        # Load DES key
        key = xmlsec.keyReadBinaryFile(xmlsec.keyDataDesId(), file)
        if key is None:
            print "Error: failed to load des key from binary file \"%s\"" % file
            mngr.destroy()
            return None
        # Add key to keys manager, from now on keys manager is responsible
# for destroying key
        if xmlsec.cryptoAppDefaultKeysMngrAdoptKey(mngr, key) < 0:
            print "Error: failed to add key from \"%s\" to keys manager" % file
            key.destroy()
            mngr.destroy()
            return None
    return mngr
コード例 #3
0
ファイル: xmldsig.py プロジェクト: alyanwarr/Xigner
    def load_key(self,
                 path,
                 password=None,
                 name=None,
                 cert_path=None,
                 key_format='pem',
                 cert_format='pem'):
        """Loads a key into the key store of the class.
        
        path       -- The path to a keyfile used to sign the XML.
        password   -- The key password, or None if no password is set.
        name       -- The name to be set for the key, or None if none should be set
        cert_path  -- The path to the certificate belonging to this key, or None
        key_format -- The format of the key as string. Defaults to pem
        cert_format-- The format of the certificate as string. Defaults to pem
        """

        key_format = XMLDSIG._determine_key_format(key_format)
        cert_format = XMLDSIG._determine_key_format(cert_format)

        try:
            # Load key
            key = xmlsec.cryptoAppKeyLoad(path, key_format, password, None,
                                          None)
            if key is None:
                raise XMLDSIGError('Failed loading private key %s' % path)

            # Set key name
            if name and key.setName(name) < 0:
                raise XMLDSIGError('Failed setting key name of %s to %s' %
                                   (path, name))

            # Link certificate to key
            if cert_path and xmlsec.cryptoAppKeyCertLoad(
                    key, cert_path, cert_format) < 0:
                raise XMLDSIGError('Failed loading certificate %s' % cert_path)

            # Load certificate into store
            if xmlsec.cryptoAppDefaultKeysMngrAdoptKey(self.key_manager,
                                                       key) < 0:
                raise XMLDSIGError("Failed loading key %s into key manager." %
                                   path)

        except XMLDSIGError:
            raise
        except Exception as e:
            raise XMLDSIGError('Something went wrong loading key %s: %s' %
                               (path, e))
コード例 #4
0
    def load(self, key_file=None, cert_file=None, password='', key_name=None):
        """
        load a private key and/or a public certificate for signature and verification

        - key_file: str, filename of PEM file containing the private key.
                    (the file should NOT be password-protected)
        - cert_file: str, filename of PEM file containing the X509 certificate.
                     (optional: can be None)
        - password: str, password to open key file, or None if no password.
        """
        #TODO: try except block to destroy key if error
        if key_file is not None:
            # Load private key, with optional password
            #print 'PASSWORD: %s' % password
            key = xmlsec.cryptoAppKeyLoad(filename=key_file,
                                          format=xmlsec.KeyDataFormatPem,
                                          pwd=password,
                                          pwdCallback=None,
                                          pwdCallbackCtx=None)
            # API references:
            # http://pyxmlsec.labs.libre-entreprise.org/docs/html/xmlsec-module.html#cryptoAppKeyLoad
            # http://www.aleksey.com/xmlsec/api/xmlsec-app.html#XMLSECCRYPTOAPPKEYLOAD
            # http://www.aleksey.com/xmlsec/api/xmlsec-keysdata.html#XMLSECKEYDATAFORMAT
            if key is None:
                raise RuntimeError, "Error: failed to load private PEM key from \"%s\"" % key_file
            if key_name is not None:
                # Set key name
                if key.setName(key_name) < 0:
                    raise RuntimeError, "Error: failed to set key name to \"%s\"" % key_name
            if cert_file is not None:
                # Load certificate and add to the key
                if xmlsec.cryptoAppKeyCertLoad(key, cert_file,
                                               xmlsec.KeyDataFormatPem) < 0:
                    raise RuntimeError, "Error: failed to load PEM certificate \"%s\"" % cert_file
            # load key into manager:
            if xmlsec.cryptoAppDefaultKeysMngrAdoptKey(self.keysmngr, key) < 0:
                raise RuntimeError, "Error: failed to load key into keys manager"

        elif cert_file is not None:
            # case when we only want to load a cert without private key
            if self.keysmngr.certLoad(cert_file, xmlsec.KeyDataFormatPem,
                                      xmlsec.KeyDataTypeTrusted) < 0:
                # is it better to keep the keys manager if an error occurs?
                #self.keysmngr.destroy()
                raise RuntimeError, "Error: failed to load PEM certificate from \"%s\"" % cert_file
コード例 #5
0
ファイル: verify2.py プロジェクト: artur-kacen/pyxmlsec
def load_keys(files, files_size):
    assert(files)
    assert(files_size > 0)

    # Create and initialize keys manager, we use a simple list based
    # keys manager, implement your own KeysStore klass if you need
    # something more sophisticated
    mngr = xmlsec.KeysMngr()
    if mngr is None:
        print "Error: failed to create keys manager."
        return None
    if xmlsec.cryptoAppDefaultKeysMngrInit(mngr) < 0:
        print "Error: failed to initialize keys manager."
        mngr.destroy()
        return None
    for file in files:
        # Load key
        if not check_filename(file):
            mngr.destroy()
            return None
        key = xmlsec.cryptoAppKeyLoad(file, xmlsec.KeyDataFormatPem,
                                      None, None, None)
        if key == None:
            print "Error: failed to load pem key from " + file
            mngr.destroy()        
            return None
        # Set key name to the file name, this is just an example!
        if key.setName(file) < 0:
            print "Error: failed to set key name for key from " + file
            key.destroy()
            mngr.destroy()
            return None
        # Add key to keys manager, from now on keys manager is responsible 
	# for destroying key
        if xmlsec.cryptoAppDefaultKeysMngrAdoptKey(mngr, key) < 0:
            print "Error: failed to add key from \"%s\" to keys manager" % file
            key.destroy()
            mngr.destroy()
            return None
    return mngr
コード例 #6
0
def load_keys(files, files_size):
    assert (files)
    assert (files_size > 0)

    # Create and initialize keys manager, we use a simple list based
    # keys manager, implement your own KeysStore klass if you need
    # something more sophisticated
    mngr = xmlsec.KeysMngr()
    if mngr is None:
        print "Error: failed to create keys manager."
        return None
    if xmlsec.cryptoAppDefaultKeysMngrInit(mngr) < 0:
        print "Error: failed to initialize keys manager."
        mngr.destroy()
        return None
    for file in files:
        # Load key
        if not check_filename(file):
            mngr.destroy()
            return None
        key = xmlsec.cryptoAppKeyLoad(file, xmlsec.KeyDataFormatPem, None,
                                      None, None)
        if key == None:
            print "Error: failed to load pem key from " + file
            mngr.destroy()
            return None
        # Set key name to the file name, this is just an example!
        if key.setName(file) < 0:
            print "Error: failed to set key name for key from " + file
            key.destroy()
            mngr.destroy()
            return None
        # Add key to keys manager, from now on keys manager is responsible
# for destroying key
        if xmlsec.cryptoAppDefaultKeysMngrAdoptKey(mngr, key) < 0:
            print "Error: failed to add key from \"%s\" to keys manager" % file
            key.destroy()
            mngr.destroy()
            return None
    return mngr
コード例 #7
0
ファイル: xmldsig.py プロジェクト: lweberk/xmldsig
    def load_key(self, path, password=None, name=None,
                       cert_path=None, key_format='pem', cert_format='pem'):
        """Loads a key into the key store of the class.

        path       -- The path to a keyfile used to sign the XML.
        password   -- The key password, or None if no password is set.
        name       -- The name to be set for the key, or None if none should be set
        cert_path  -- The path to the certificate belonging to this key, or None
        key_format -- The format of the key as string. Defaults to pem
        cert_format-- The format of the certificate as string. Defaults to pem
        """

        key_format = XMLDSIG._determine_key_format(key_format)
        cert_format = XMLDSIG._determine_key_format(cert_format)

        try:
            # Load key
            key = xmlsec.cryptoAppKeyLoad(path, key_format, password, None, None)
            if key is None:
                raise XMLDSIGError('Failed loading private key %s' % path)

            # Set key name
            if name and key.setName(name) < 0:
                raise XMLDSIGError('Failed setting key name of %s to %s' % (path, name))

            # Link certificate to key
            if cert_path and xmlsec.cryptoAppKeyCertLoad(key, cert_path, cert_format) < 0:
                raise XMLDSIGError('Failed loading certificate %s' % cert_path)

            # Load certificate into store
            if xmlsec.cryptoAppDefaultKeysMngrAdoptKey(self.key_manager, key) < 0:
                raise XMLDSIGError("Failed loading key %s into key manager." % path)

        except XMLDSIGError:
            raise
        except Exception as e:
            raise XMLDSIGError('Something went wrong loading key %s: %s' % (path, e))
コード例 #8
0
    def signRequest(file, request):
        keysmngr = xmlsec.KeysMngr()
        if keysmngr is None:
            raise RuntimeError, "Error: failed to create keys manager."
        if xmlsec.cryptoAppDefaultKeysMngrInit(keysmngr) < 0:
            keysmngr.destroy()
            raise RuntimeError, "Error: failed to initialize keys manager."

        key = xmlsec.cryptoAppKeyLoad(filename = file, pwd = None,
           format = xmlsec.KeyDataFormatPem, pwdCallback = None,
           pwdCallbackCtx = None)
        if xmlsec.cryptoAppDefaultKeysMngrAdoptKey(keysmngr, key) < 0:
            keysmngr.destroy()
            raise RuntimeError, "Error: failed to load key into keys manager" 

        dsig_ctx = xmlsec.DSigCtx(keysmngr)

        # Match the dtd and replace it.

        pat = re.compile("(^.*<!DOCTYPE.*distributionRequest[^>]*SYSTEM[ \t]*\")([^\"]*)(\"[^>]*>.*$)", re.DOTALL)
        m = pat.match(request)

        request = m.group(1)+"http://dmswww.stsci.edu/dtd/sso/distribution.dtd"+m.group(3)

        ctxt = libxml2.createMemoryParserCtxt(request, len(request))
        ctxt.validate(1)
        ctxt.parseDocument()
        doc = ctxt.doc()

        if doc is None or doc.getRootElement() is None:
            keysmngr.destroy()
            raise RuntimeError, "Error: unable to parse XML data"

        # find the XML-DSig start node
        node = xmlsec.findNode(doc.getRootElement(), xmlsec.NodeSignature,
                       xmlsec.DSigNs)
        if node is None:
            fragment = libxml2.parseDoc("""<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
  <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
  <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
  <Reference URI="#distributionRequest">
    <Transforms>
      <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
      <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#WithComments" />
    </Transforms>
    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
    <DigestValue></DigestValue>
  </Reference>
</SignedInfo>
<SignatureValue></SignatureValue>
<KeyInfo>
 <KeyValue><RSAKeyValue>
  <Modulus></Modulus>
  <Exponent></Exponent>
 </RSAKeyValue></KeyValue> 
</KeyInfo>
</Signature>
""")
            # remove the xml header on the front of the document fragment
            fragment = fragment.getRootElement()
            # getElementsByTagName doesn't exist here for some reason, have to use xpath
            ctxt = doc.xpathNewContext()
            nodeList = ctxt.xpathEval("/distributionRequest")
            for child in nodeList:
                child.addChild(fragment)
                if child.prop('Id') == None:
                    child.setProp('Id', 'distributionRequest')
            node = xmlsec.findNode(doc.getRootElement(), xmlsec.NodeSignature,
                       xmlsec.DSigNs)
        

        # Remove passwords

        ctxt = doc.xpathNewContext()
        nodeList = ctxt.xpathEval('//requester')
        for child in nodeList:
            child.unsetProp('archivePassword')

        nodeList = ctxt.xpathEval('//ftp')
        for child in nodeList:
            if child.hasProp('loginPassword'):
                child.unsetProp('loginPassword')
                warnings.warn('ftp password is not allowed in user requests.')

        # Sign the template, or resign existing block
        status = dsig_ctx.sign(node)
        output = str(doc)
        doc.freeDoc()
        keysmngr.destroy()
        if status < 0:
            raise RuntimeError, "Error: signature failed"
        return output
コード例 #9
0
    def assina_xml(self, xml):
        self._inicia_funcoes_externas()
        xml = self._prepara_doc_xml(xml)

        #
        # Colocamos o texto no avaliador XML
        #
        doc_xml = libxml2.parseMemory(xml.encode('utf-8'),
                                      len(xml.encode('utf-8')))

        #
        # Separa o nó da assinatura
        #
        noh_assinatura = xmlsec.findNode(doc_xml.getRootElement(),
                                         xmlsec.NodeSignature, xmlsec.DSigNs)

        #
        # Arquivos temporários são criados com o certificado no formato PEM
        #
        temp_chave = tempfile.NamedTemporaryFile('w')
        temp_chave.write(self.chave)
        temp_chave.flush()

        temp_certificado = tempfile.NamedTemporaryFile('w')
        temp_certificado.write(self.certificado)
        temp_certificado.flush()

        #
        # Buscamos chave e certificado no arquivo temporário e inserimos no "chaveiro"
        #
        chaveiro = xmlsec.KeysMngr()
        xmlsec.cryptoAppDefaultKeysMngrInit(chaveiro)

        chave = xmlsec.cryptoAppKeyLoad(filename=temp_chave.name,
                                        format=xmlsec.KeyDataFormatPem,
                                        pwd=None,
                                        pwdCallback=None,
                                        pwdCallbackCtx=None)
        certificado = xmlsec.cryptoAppKeyCertLoad(
            chave,
            filename=temp_certificado.name,
            format=xmlsec.KeyDataFormatPem)
        xmlsec.cryptoAppDefaultKeysMngrAdoptKey(chaveiro, chave)

        #
        # Cria a variável de chamada (callable) da função de assinatura, usando o "chaveiro"
        #
        assinador = xmlsec.DSigCtx(chaveiro)

        #
        # Atribui a chave ao assinador
        #
        assinador.signKey = chave

        #
        # Realiza a assinatura
        #
        assinador.sign(noh_assinatura)

        #
        # Guarda o status
        #
        status = assinador.status

        #
        # Libera a memória ocupada pelo assinador manualmente
        #
        assinador.destroy()

        #
        # Arquivos temporários são deletados do disco
        #
        temp_chave.close()
        temp_certificado.close()

        if status != xmlsec.DSigStatusSucceeded:
            #
            # Libera a memória ocupada pelo documento xml manualmente
            #
            doc_xml.freeDoc()
            self._finaliza_funcoes_externas()
            raise RuntimeError(
                'Erro ao realizar a assinatura do arquivo; status: "' +
                str(status) + '"')

        #
        # Elimina do xml assinado a cadeia certificadora, deixando somente
        # o certificado que assinou o documento
        #
        xpath = doc_xml.xpathNewContext()
        xpath.xpathRegisterNs(u'sig', NAMESPACE_SIG)
        certificados = xpath.xpathEval(u'//sig:X509Data/sig:X509Certificate')
        for i in range(len(certificados) - 1):
            certificados[i].unlinkNode()
            certificados[i].freeNode()

        #
        # Retransforma o documento xml em texto
        #
        xml = doc_xml.serialize()

        #
        # Libera a memória ocupada pelo documento xml manualmente
        #
        doc_xml.freeDoc()
        self._finaliza_funcoes_externas()

        xml = self._finaliza_xml(xml)

        return xml
コード例 #10
0
    def assina_xml(self, xml):
        self._inicia_funcoes_externas()
        xml = self._prepara_doc_xml(xml)

        #
        # Colocamos o texto no avaliador XML
        #
        doc_xml = libxml2.parseMemory(xml.encode("utf-8"), len(xml.encode("utf-8")))

        #
        # Separa o nó da assinatura
        #
        noh_assinatura = xmlsec.findNode(doc_xml.getRootElement(), xmlsec.NodeSignature, xmlsec.DSigNs)

        #
        # Arquivos temporários são criados com o certificado no formato PEM
        #
        temp_chave = tempfile.NamedTemporaryFile("w")
        temp_chave.write(self.chave)
        temp_chave.flush()

        temp_certificado = tempfile.NamedTemporaryFile("w")
        temp_certificado.write(self.certificado)
        temp_certificado.flush()

        #
        # Buscamos chave e certificado no arquivo temporário e inserimos no "chaveiro"
        #
        chaveiro = xmlsec.KeysMngr()
        xmlsec.cryptoAppDefaultKeysMngrInit(chaveiro)

        chave = xmlsec.cryptoAppKeyLoad(
            filename=temp_chave.name, format=xmlsec.KeyDataFormatPem, pwd=None, pwdCallback=None, pwdCallbackCtx=None
        )
        certificado = xmlsec.cryptoAppKeyCertLoad(chave, filename=temp_certificado.name, format=xmlsec.KeyDataFormatPem)
        xmlsec.cryptoAppDefaultKeysMngrAdoptKey(chaveiro, chave)

        #
        # Cria a variável de chamada (callable) da função de assinatura, usando o "chaveiro"
        #
        assinador = xmlsec.DSigCtx(chaveiro)

        #
        # Atribui a chave ao assinador
        #
        assinador.signKey = chave

        #
        # Realiza a assinatura
        #
        assinador.sign(noh_assinatura)

        #
        # Guarda o status
        #
        status = assinador.status

        #
        # Libera a memória ocupada pelo assinador manualmente
        #
        assinador.destroy()

        #
        # Arquivos temporários são deletados do disco
        #
        temp_chave.close()
        temp_certificado.close()

        if status != xmlsec.DSigStatusSucceeded:
            #
            # Libera a memória ocupada pelo documento xml manualmente
            #
            doc_xml.freeDoc()
            self._finaliza_funcoes_externas()
            raise RuntimeError('Erro ao realizar a assinatura do arquivo; status: "' + str(status) + '"')

        #
        # Elimina do xml assinado a cadeia certificadora, deixando somente
        # o certificado que assinou o documento
        #
        xpath = doc_xml.xpathNewContext()
        xpath.xpathRegisterNs(u"sig", NAMESPACE_SIG)
        certificados = xpath.xpathEval(u"//sig:X509Data/sig:X509Certificate")
        for i in range(len(certificados) - 1):
            certificados[i].unlinkNode()
            certificados[i].freeNode()

        #
        # Retransforma o documento xml em texto
        #
        xml = doc_xml.serialize()

        #
        # Libera a memória ocupada pelo documento xml manualmente
        #
        doc_xml.freeDoc()
        self._finaliza_funcoes_externas()

        xml = self._finaliza_xml(xml)

        return xml
コード例 #11
0
ファイル: authn.py プロジェクト: joesoc/gsa-admin-toolkit
  def _signXML(self, xml):
    import libxml2
    import xmlsec
    dsigctx = None
    doc = None
    try:
      # initialization
      libxml2.initParser()
      libxml2.substituteEntitiesDefault(1)
      if xmlsec.init() < 0:
        raise SignatureError('xmlsec init failed')
      if xmlsec.checkVersion() != 1:
        raise SignatureError('incompatible xmlsec library version %s' %
                             str(xmlsec.checkVersion()))
      if xmlsec.cryptoAppInit(None) < 0:
        raise SignatureError('crypto initialization failed')
      if xmlsec.cryptoInit() < 0:
        raise SignatureError('xmlsec-crypto initialization failed')

      # load the input
      doc = libxml2.parseDoc(xml)
      if not doc or not doc.getRootElement():
        raise SignatureError('error parsing input xml')
      node = xmlsec.findNode(doc.getRootElement(), xmlsec.NodeSignature,
                             xmlsec.DSigNs)
      if not node:
        raise SignatureError("couldn't find root node")

      # load the private key
      key = xmlsec.cryptoAppKeyLoad(self.key_file, xmlsec.KeyDataFormatPem,
                                    self.key_pwd, None, None)
      if not key:
        raise SignatureError('failed to load the private key %s' % self.key_file)

      if xmlsec.cryptoAppKeyCertLoad(key, self.cert_file, xmlsec.KeyDataFormatPem) < 0:
        print "Error: failed to load pem certificate \"%s\"" % self.cert_file
        return self.cleanup(doc, dsigctx)

      keymngr = xmlsec.KeysMngr()
      xmlsec.cryptoAppDefaultKeysMngrInit(keymngr)
      xmlsec.cryptoAppDefaultKeysMngrAdoptKey(keymngr, key)
      dsigctx = xmlsec.DSigCtx(keymngr)

      if key.setName(self.key_file) < 0:
        raise SignatureError('failed to set key name')

      # sign
      if dsigctx.sign(node) < 0:
        raise SignatureError('signing failed')
      signed_xml = doc.serialize()

    finally:
      if dsigctx:
        dsigctx.destroy()
      if doc:
        doc.freeDoc()
      xmlsec.cryptoShutdown()
      xmlsec.shutdown()
      libxml2.cleanupParser()

    return signed_xml
コード例 #12
0
ファイル: authn.py プロジェクト: pkeesey/gsa-admin-toolkit
    def _signXML(self, xml):
        import libxml2
        import xmlsec
        dsigctx = None
        doc = None
        try:
            # initialization
            libxml2.initParser()
            libxml2.substituteEntitiesDefault(1)
            if xmlsec.init() < 0:
                raise SignatureError('xmlsec init failed')
            if xmlsec.checkVersion() != 1:
                raise SignatureError('incompatible xmlsec library version %s' %
                                     str(xmlsec.checkVersion()))
            if xmlsec.cryptoAppInit(None) < 0:
                raise SignatureError('crypto initialization failed')
            if xmlsec.cryptoInit() < 0:
                raise SignatureError('xmlsec-crypto initialization failed')

            # load the input
            doc = libxml2.parseDoc(xml)
            if not doc or not doc.getRootElement():
                raise SignatureError('error parsing input xml')
            node = xmlsec.findNode(doc.getRootElement(), xmlsec.NodeSignature,
                                   xmlsec.DSigNs)
            if not node:
                raise SignatureError("couldn't find root node")

            # load the private key
            key = xmlsec.cryptoAppKeyLoad(self.key_file,
                                          xmlsec.KeyDataFormatPem,
                                          self.key_pwd, None, None)
            if not key:
                raise SignatureError('failed to load the private key %s' %
                                     self.key_file)

            if xmlsec.cryptoAppKeyCertLoad(key, self.cert_file,
                                           xmlsec.KeyDataFormatPem) < 0:
                print "Error: failed to load pem certificate \"%s\"" % self.cert_file
                return self.cleanup(doc, dsigctx)

            keymngr = xmlsec.KeysMngr()
            xmlsec.cryptoAppDefaultKeysMngrInit(keymngr)
            xmlsec.cryptoAppDefaultKeysMngrAdoptKey(keymngr, key)
            dsigctx = xmlsec.DSigCtx(keymngr)

            if key.setName(self.key_file) < 0:
                raise SignatureError('failed to set key name')

            # sign
            if dsigctx.sign(node) < 0:
                raise SignatureError('signing failed')
            signed_xml = doc.serialize()

        finally:
            if dsigctx:
                dsigctx.destroy()
            if doc:
                doc.freeDoc()
            xmlsec.cryptoShutdown()
            xmlsec.shutdown()
            libxml2.cleanupParser()

        return signed_xml
コード例 #13
0
    def signRequest(file, request, dtd="http://dmswww.stsci.edu/dtd/sso/distribution.dtd", cgi="https://archive.stsci.edu/cgi-bin/dads.cgi", mission='HST'):
     global usexml
     if usexml:
      try:
        keysmngr = xmlsec.KeysMngr()
        if keysmngr is None:
            raise RuntimeError("Error: failed to create keys manager.")
        if xmlsec.cryptoAppDefaultKeysMngrInit(keysmngr) < 0:
            keysmngr.destroy()
            raise RuntimeError("Error: failed to initialize keys manager.")

        key = xmlsec.cryptoAppKeyLoad(filename = file, pwd = None,
           format = xmlsec.KeyDataFormatPem, pwdCallback = None,
           pwdCallbackCtx = None)
        if xmlsec.cryptoAppDefaultKeysMngrAdoptKey(keysmngr, key) < 0:
            keysmngr.destroy()
            raise RuntimeError("Error: failed to load key into keys manager")

        dsig_ctx = xmlsec.DSigCtx(keysmngr)

        # Match the dtd and replace it.

        pat = re.compile("(^.*<!DOCTYPE.*distributionRequest[^>]*SYSTEM[ \t]*\")([^\"]*)(\"[^>]*>.*$)", re.DOTALL)
        m = pat.match(request)

        request = m.group(1)+dtd+m.group(3)

        ctxt = libxml2.createMemoryParserCtxt(request, len(request))
        ctxt.validate(1)
        ctxt.parseDocument()
        doc = ctxt.doc()

        if doc is None or doc.getRootElement() is None:
            keysmngr.destroy()
            raise RuntimeError("Error: unable to parse XML data")

        # find the XML-DSig start node
        node = xmlsec.findNode(doc.getRootElement(), xmlsec.NodeSignature,
                       xmlsec.DSigNs)
        if node is None:
            fragment = libxml2.parseDoc("""<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
  <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
  <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
  <Reference URI="#distributionRequest">
    <Transforms>
      <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
      <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#WithComments" />
    </Transforms>
    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
    <DigestValue></DigestValue>
  </Reference>
</SignedInfo>
<SignatureValue></SignatureValue>
<KeyInfo>
 <KeyValue><RSAKeyValue>
  <Modulus></Modulus>
  <Exponent></Exponent>
 </RSAKeyValue></KeyValue>
</KeyInfo>
</Signature>
""")
            # remove the xml header on the front of the document fragment
            fragment = fragment.getRootElement()
            # getElementsByTagName doesn't exist here for some reason, have to use xpath
            ctxt = doc.xpathNewContext()
            nodeList = ctxt.xpathEval("/distributionRequest")
            for child in nodeList:
                child.addChild(fragment)
                if child.prop('Id') == None:
                    child.setProp('Id', 'distributionRequest')
            node = xmlsec.findNode(doc.getRootElement(), xmlsec.NodeSignature,
                       xmlsec.DSigNs)


        # Remove passwords

        ctxt = doc.xpathNewContext()
        nodeList = ctxt.xpathEval('//requester')
        for child in nodeList:
            child.unsetProp('archivePassword')

        nodeList = ctxt.xpathEval('//ftp')
        for child in nodeList:
            if child.hasProp('loginPassword'):
                child.unsetProp('loginPassword')
                warnings.warn('ftp password is not allowed in user requests.')

        # Sign the template, or resign existing block
        status = dsig_ctx.sign(node)
        output = str(doc)
        doc.freeDoc()
        keysmngr.destroy()
        if status < 0:
            raise RuntimeError("Error: signature failed")
        return output
      except:
        usexml=False
        return signRequest(file, request, dtd, cgi)
     else:
        values = {'request' : request, 'privatekey' : open(file).read(), 'mission' : mission }
        data = urlencode(values).encode("utf-8")
        req = Request(url=cgi, data=data)
        f = urlopen(req)
        return f.read()