Exemple #1
0
    def received(self, context):
        self.poruka_odgovor = context.reply

        libxml2.initParser()
        libxml2.substituteEntitiesDefault(1)

        xmlsec.init()
        xmlsec.cryptoAppInit(None)
        xmlsec.cryptoInit()

        mngr = xmlsec.KeysMngr()
        xmlsec.cryptoAppDefaultKeysMngrInit(mngr)
        mngr.certLoad(verifyCertFile, xmlsec.KeyDataFormatPem,
                      xmlsec.KeyDataTypeTrusted)

        doc = libxml2.parseDoc(context.reply)
        xmlsec.addIDs(doc, doc.getRootElement(), ['Id'])
        node = xmlsec.findNode(doc.getRootElement(), xmlsec.NodeSignature,
                               xmlsec.DSigNs)
        dsig_ctx = xmlsec.DSigCtx(mngr)
        dsig_ctx.verify(node)
        if (dsig_ctx.status == xmlsec.DSigStatusSucceeded):
            self.valid_signature = 1

        xmlsec.cryptoShutdown()
        xmlsec.cryptoAppShutdown()
        xmlsec.shutdown()
        libxml2.cleanupParser()
        return context
    def tearDown(self):
        libxml2.cleanupParser()
        if libxml2.debugMemory(1) != 0:
            libxml2.dumpMemory() 
            self.fail("Memory leak %d bytes" % (libxml2.debugMemory(1),))
	else:
	    print "OK"
Exemple #3
0
 def __del__(self):
     if self.doc != None:
         self.doc.freeDoc()
     libxml2.cleanupParser()
     if libxml2.debugMemory(1) != 0:
         print "Memory leak %d bytes" % (libxml2.debugMemory(1))
         libxml2.dumpMemory()
Exemple #4
0
 def tearDown(self):
     libxml2.cleanupParser()
     if libxml2.debugMemory(1) != 0:
         libxml2.dumpMemory()
         self.fail("Memory leak %d bytes" % (libxml2.debugMemory(1), ))
     else:
         print("OK")
Exemple #5
0
    def validate(self, str):
        """
        Validate the given string 
        """
        if not self.schema:
            return False

        file = open(self.schema)
        try:
            schema = file.read()
        finally:
            file.close()

        rngParser = libxml2.relaxNGNewMemParserCtxt(schema, len(schema))
        rngSchema = rngParser.relaxNGParse()
        ctxt = rngSchema.relaxNGNewValidCtxt()
        doc = libxml2.parseDoc(str)
        is_valid = doc.relaxNGValidateDoc(ctxt)

        # Clean up
        doc.freeDoc()
        del rngParser, rngSchema, ctxt
        libxml2.relaxNGCleanupTypes()
        libxml2.cleanupParser()
        return is_valid == 0
Exemple #6
0
def received(self, context):
    self.poruka_odgovor = context.reply
 
    libxml2.initParser()
    libxml2.substituteEntitiesDefault(1)
 
    xmlsec.init()
    xmlsec.cryptoAppInit(None)
    xmlsec.cryptoInit()
 
    mngr = xmlsec.KeysMngr()
    xmlsec.cryptoAppDefaultKeysMngrInit(mngr)
    #mngr.certLoad(verifyCertFile, xmlsec.KeyDataFormatPem, xmlsec.KeyDataTypeTrusted)
    mngr.certLoad(certFile, xmlsec.KeyDataFormatPem, xmlsec.KeyDataTypeTrusted)
  
    doc = libxml2.parseDoc(context.reply)
    xmlsec.addIDs(doc, doc.getRootElement(), ['Id'])
    node = xmlsec.findNode(doc.getRootElement(), xmlsec.NodeSignature, xmlsec.DSigNs)
    dsig_ctx = xmlsec.DSigCtx(mngr)
    dsig_ctx.verify(node)
    if(dsig_ctx.status == xmlsec.DSigStatusSucceeded): self.valid_signature = 1
 
    xmlsec.cryptoShutdown()
    xmlsec.cryptoAppShutdown()
    xmlsec.shutdown()
    libxml2.cleanupParser()
    return context
def _signXML(xml):
    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")

        dsigctx = xmlsec.DSigCtx()

        key = xmlsec.cryptoAppKeyLoad(key_file, xmlsec.KeyDataFormatPem,
                                      key_pwd, None, None)

        if not key:
            raise SignatureError('failed to load the private key %s' %
                                 key_file)
        dsigctx.signKey = key

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

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

        # 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
Exemple #8
0
    def collect_figures(self):
        libxml2.cleanupParser()
        gc.collect()

        figures = []
        figures.append(("Objects in gc.garbage", len(gc.garbage), ""))
        figures.append(("libxml2 memory leak", libxml2.debugMemory(1), "bytes"))
        return figures
Exemple #9
0
    def sending(self, context):
        msgtype = "RacunZahtjev"
        if "PoslovniProstorZahtjev" in context.envelope: msgtype = "PoslovniProstorZahtjev"
    
        doc2 = libxml2.parseDoc(context.envelope)

        zahtjev = doc2.xpathEval('//*[local-name()="%s"]' % msgtype)[0]
        doc2.setRootElement(zahtjev)

        x = doc2.getRootElement().newNs('http://www.apis-it.hr/fin/2012/types/f73', 'tns')
 
        for i in doc2.xpathEval('//*'):
            i.setNs(x)

        libxml2.initParser()
        libxml2.substituteEntitiesDefault(1)

        xmlsec.init()
        xmlsec.cryptoAppInit(None)
        xmlsec.cryptoInit()

        doc2.getRootElement().setProp('Id', msgtype)
        xmlsec.addIDs(doc2, doc2.getRootElement(), ['Id'])    

        signNode = xmlsec.TmplSignature(doc2, xmlsec.transformExclC14NId(), xmlsec.transformRsaSha1Id(), None)

        doc2.getRootElement().addChild(signNode)
    
        refNode = signNode.addReference(xmlsec.transformSha1Id(), None, None, None)
        refNode.setProp('URI', '#%s' % msgtype)
        refNode.addTransform(xmlsec.transformEnvelopedId())
        refNode.addTransform(xmlsec.transformExclC14NId())
 
        dsig_ctx = xmlsec.DSigCtx()
        key = xmlsec.cryptoAppKeyLoad(keyFile, xmlsec.KeyDataFormatPem, None, None, None)
        dsig_ctx.signKey = key

        xmlsec.cryptoAppKeyCertLoad(key, certFile, xmlsec.KeyDataFormatPem)
        key.setName(keyFile)

        keyInfoNode = signNode.ensureKeyInfo(None)
        x509DataNode = keyInfoNode.addX509Data()
        xmlsec.addChild(x509DataNode, "X509IssuerSerial")
        xmlsec.addChild(x509DataNode, "X509Certificate")

        dsig_ctx.sign(signNode)
    
        if dsig_ctx is not None: dsig_ctx.destroy()
        context.envelope = """<?xml version="1.0" encoding="UTF-8"?>
        <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
        <soapenv:Body>""" + doc2.serialize().replace('<?xml version="1.0" encoding="UTF-8"?>','') + """</soapenv:Body></soapenv:Envelope>""" # Ugly hack
    
        # Shutdown xmlsec-crypto library, ako ne radi HTTPS onda ovo treba zakomentirati da ga ne ugasi prije reda
        xmlsec.cryptoShutdown()
        xmlsec.shutdown()
        libxml2.cleanupParser()

        return context
Exemple #10
0
    def sending(self, context):
        msgtype = "RacunZahtjev"
        if "PoslovniProstorZahtjev" in context.envelope: msgtype = "PoslovniProstorZahtjev"
    
        doc2 = libxml2.parseDoc(context.envelope)

        zahtjev = doc2.xpathEval('//*[local-name()="%s"]' % msgtype)[0]
        doc2.setRootElement(zahtjev)

        x = doc2.getRootElement().newNs('http://www.apis-it.hr/fin/2012/types/f73', 'tns')
 
        for i in doc2.xpathEval('//*'):
            i.setNs(x)

        libxml2.initParser()
        libxml2.substituteEntitiesDefault(1)

        xmlsec.init()
        xmlsec.cryptoAppInit(None)
        xmlsec.cryptoInit()

        doc2.getRootElement().setProp('Id', msgtype)
        xmlsec.addIDs(doc2, doc2.getRootElement(), ['Id'])    

        signNode = xmlsec.TmplSignature(doc2, xmlsec.transformExclC14NId(), xmlsec.transformRsaSha1Id(), None)

        doc2.getRootElement().addChild(signNode)
    
        refNode = signNode.addReference(xmlsec.transformSha1Id(), None, None, None)
        refNode.setProp('URI', '#%s' % msgtype)
        refNode.addTransform(xmlsec.transformEnvelopedId())
        refNode.addTransform(xmlsec.transformExclC14NId())
 
        dsig_ctx = xmlsec.DSigCtx()
        key = xmlsec.cryptoAppKeyLoad(keyFile, xmlsec.KeyDataFormatPem, None, None, None)
        dsig_ctx.signKey = key

        xmlsec.cryptoAppKeyCertLoad(key, certFile, xmlsec.KeyDataFormatPem)
        key.setName(keyFile)

        keyInfoNode = signNode.ensureKeyInfo(None)
        x509DataNode = keyInfoNode.addX509Data()
        xmlsec.addChild(x509DataNode, "X509IssuerSerial")
        xmlsec.addChild(x509DataNode, "X509Certificate")

        dsig_ctx.sign(signNode)
    
        if dsig_ctx is not None: dsig_ctx.destroy()
        context.envelope = """<?xml version="1.0" encoding="UTF-8"?>
        <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
        <soapenv:Body>""" + doc2.serialize().replace('<?xml version="1.0" encoding="UTF-8"?>','') + """</soapenv:Body></soapenv:Envelope>""" # Ugly hack
    
        # Shutdown xmlsec-crypto library, ako ne radi HTTPS onda ovo treba zakomentirati da ga ne ugasi prije reda
        xmlsec.cryptoShutdown()
        xmlsec.shutdown()
        libxml2.cleanupParser()

        return context
Exemple #11
0
    def _finaliza_funcoes_externas(self):
        ''' Desativa as funções criptográficas e de análise XML
        As funções devem ser chamadas na ordem inversa da ativação
        '''
        #xmlsec.cryptoShutdown()
        #xmlsec.cryptoAppShutdown()
        xmlsec.shutdown()

        libxml2.cleanupParser()
 def cleanup():
     # Shutdown xmlsec-crypto library
     xmlsec.cryptoShutdown()
     # Shutdown crypto library
     xmlsec.cryptoAppShutdown()
     # Shutdown xmlsec library
     xmlsec.shutdown()
     # Shutdown LibXML2
     libxml2.cleanupParser()
Exemple #13
0
    def stop(self):
        sMessage = None
        # Memory debug specific

        libxml2.cleanupParser()
        if libxml2.debugMemory(1) != 0:
            sMessage = _("LIBXML2 Memory leak %d bytes") %\
                       (libxml2.debugMemory(1))
        libxml2.dumpMemory()
        return sMessage
Exemple #14
0
 def cleanup():
   if usexml:
     # Shutdown xmlsec-crypto library
     xmlsec.cryptoShutdown()
     # Shutdown crypto library
     xmlsec.cryptoAppShutdown()
     # Shutdown xmlsec library
     xmlsec.shutdown()
     # Shutdown LibXML2
     libxml2.cleanupParser()
Exemple #15
0
def destroy():
    """Destroys the modules loaded by this module. Should be called after
    everything is done, but we won't kill you if you don't.
    """
    # The following commands are commented because this is bugged with
    # urllib2 (see https://github.com/dnet/pyxmlsec/issues/1)
    #xmlsec.cryptoShutdown()
    #xmlsec.cryptoAppShutdown()
        
    xmlsec.shutdown()
    libxml2.cleanupParser()
Exemple #16
0
def destroy():
    """Destroys the modules loaded by this module. Should be called after
    everything is done, but we won't kill you if you don't.
    """
    # The following commands are commented because this is bugged with
    # urllib2 (see https://github.com/dnet/pyxmlsec/issues/1)
    #xmlsec.cryptoShutdown()
    #xmlsec.cryptoAppShutdown()

    xmlsec.shutdown()
    libxml2.cleanupParser()
Exemple #17
0
def publish(base_dir, pub_repo, pub_msg):
    """
    Run the publish application.
    """ 
    libxml2.debugMemory(1)
    
    app = publishApplication(base_dir, 'vcjb.cfg', pub_repo, pub_msg)
    
    app.run()
    
    libxml2.cleanupParser()
Exemple #18
0
def main():
    assert (sys.argv)
    if len(sys.argv) < 3:
        print "Error: wrong number of arguments."
        print "Usage: %s <xml-file> <key-file1> [<key-file2> [...]]" % sys.argv[
            0]
        return sys.exit(1)

    # Init libxml library
    libxml2.initParser()
    libxml2.substituteEntitiesDefault(1)

    # Init xmlsec library
    if xmlsec.init() < 0:
        print "Error: xmlsec initialization failed."
        return sys.exit(-1)

    # Check loaded library version
    if xmlsec.checkVersion() != 1:
        print "Error: loaded xmlsec library version is not compatible.\n"
        sys.exit(-1)

    # Init crypto library
    if xmlsec.cryptoAppInit(None) < 0:
        print "Error: crypto initialization failed."

    # Init xmlsec-crypto library
    if xmlsec.cryptoInit() < 0:
        print "Error: xmlsec-crypto initialization failed."

    # Create keys manager and load keys
    mngr = load_keys(sys.argv[2:], len(sys.argv) - 2)

    res = 0
    # Verify file
    if mngr is not None:
        res = verify_file(mngr, sys.argv[1])
        # Destroy keys manager
        mngr.destroy()

    # Shutdown xmlsec-crypto library
    xmlsec.cryptoShutdown()

    # Shutdown crypto library
    xmlsec.cryptoAppShutdown()

    # Shutdown xmlsec library
    xmlsec.shutdown()

    # Shutdown LibXML2
    libxml2.cleanupParser()

    sys.exit(res)
Exemple #19
0
def lib_shutdown():
    # Shutdown xmlsec-crypto library
    #xmlsec.cryptoShutdown()

    # Shutdown crypto library
    #xmlsec.cryptoAppShutdown()

    # Shutdown xmlsec library
    #xmlsec.shutdown()

    # Shutdown LibXML2
    libxml2.cleanupParser()
Exemple #20
0
def main():
    assert(sys.argv)
    if len(sys.argv) < 3:
        print "Error: wrong number of arguments."
        print "Usage: %s <xml-file> <key-file1> [<key-file2> [...]]" % sys.argv[0]
        return sys.exit(1)
    
    # Init libxml library
    libxml2.initParser()
    libxml2.substituteEntitiesDefault(1)

    # Init xmlsec library
    if xmlsec.init() < 0:
        print "Error: xmlsec initialization failed."
        return sys.exit(-1)
    
    # Check loaded library version
    if xmlsec.checkVersion() != 1:
	print "Error: loaded xmlsec library version is not compatible.\n"
	sys.exit(-1)

    # Init crypto library
    if xmlsec.cryptoAppInit(None) < 0:
        print "Error: crypto initialization failed."
    
    # Init xmlsec-crypto library
    if xmlsec.cryptoInit() < 0:
        print "Error: xmlsec-crypto initialization failed."

    # Create keys manager and load keys
    mngr = load_keys(sys.argv[2:], len(sys.argv) - 2)

    res = 0
    # Verify file
    if mngr is not None:
        res = verify_file(mngr, sys.argv[1])
        # Destroy keys manager
        mngr.destroy()
    
    # Shutdown xmlsec-crypto library
    xmlsec.cryptoShutdown()

    # Shutdown crypto library
    xmlsec.cryptoAppShutdown()

    # Shutdown xmlsec library
    xmlsec.shutdown()

    # Shutdown LibXML2
    libxml2.cleanupParser()

    sys.exit(res)
Exemple #21
0
def shutdown():
    """
    Shutdown all libraries cleanly.
    Should only be called at the end of all xmlsec actions.
    """
    # Shutdown xmlsec-crypto library
    xmlsec.cryptoShutdown()
    # Shutdown crypto library
    xmlsec.cryptoAppShutdown()
    # Shutdown xmlsec library
    xmlsec.shutdown()
    # Shutdown LibXML2
    libxml2.cleanupParser()
    def test_CheckListCreateMemoryTest(self):
        '''Create a checklist with no memory leaks

        libxml2 requires special memory handling.  Check that we can create a
        CheckList and destory it without any memory leaks from the libxml2
        library.
        '''
        self.checklist = checklist.CheckList(os.path.join(self.dataDir,
            'fedoraus.xml'))
        libxml2.cleanupParser()
        self.assert_(libxml2.debugMemory(1) == 0,
                'FAIL: %d bytes leaked' % (libxml2.debugMemory(1)))
        del self.checklist
Exemple #23
0
 def close(self):
     self.logging.debug("Shuttind crypto engine down")
     # Shutdown xmlsec-crypto library
     xmlsec.cryptoShutdown()
     
     # Shutdown crypto library
     xmlsec.cryptoAppShutdown()
     
     # Shutdown xmlsec library
     xmlsec.shutdown()
     
     # Shutdown LibXML2
     libxml2.cleanupParser()
Exemple #24
0
def main():
    assert(sys.argv)
    if len(sys.argv) != 2:
        print "Error: wrong number of arguments."
        print "Usage: %s <enc-file>" % sys.argv[0]
        return sys.exit(1)
    
    res = 0
    # Init libxml library
    libxml2.initParser()
    libxml2.substituteEntitiesDefault(1)

    # Init xmlsec library
    if xmlsec.init() < 0:
        print "Error: xmlsec initialization failed."
        return sys.exit(-1)
    
    # Check loaded library version
    if xmlsec.checkVersion() != 1:
	print "Error: loaded xmlsec library version is not compatible."
	sys.exit(-1)

    # Init crypto library
    if xmlsec.cryptoAppInit(None) < 0:
        print "Error: crypto initialization failed."
    
    # Init xmlsec-crypto library
    if xmlsec.cryptoInit() < 0:
        print "Error: xmlsec-crypto initialization failed."

    # Create keys manager and load keys */
    mngr = create_files_keys_mngr()

    if mngr is not None:
        res = decrypt_file(mngr, sys.argv[1])

    # Shutdown xmlsec-crypto library
    xmlsec.cryptoShutdown()

    # Shutdown crypto library
    xmlsec.cryptoAppShutdown()

    # Shutdown xmlsec library
    xmlsec.shutdown()

    # Shutdown LibXML2
    libxml2.cleanupParser()

    sys.exit(res)
Exemple #25
0
def main():
    assert (sys.argv)
    if len(sys.argv) != 2:
        print "Error: wrong number of arguments."
        print "Usage: %s <enc-file>" % sys.argv[0]
        return sys.exit(1)

    res = 0
    # Init libxml library
    libxml2.initParser()
    libxml2.substituteEntitiesDefault(1)

    # Init xmlsec library
    if xmlsec.init() < 0:
        print "Error: xmlsec initialization failed."
        return sys.exit(-1)

    # Check loaded library version
    if xmlsec.checkVersion() != 1:
        print "Error: loaded xmlsec library version is not compatible."
        sys.exit(-1)

    # Init crypto library
    if xmlsec.cryptoAppInit(None) < 0:
        print "Error: crypto initialization failed."

    # Init xmlsec-crypto library
    if xmlsec.cryptoInit() < 0:
        print "Error: xmlsec-crypto initialization failed."

    # Create keys manager and load keys */
    mngr = create_files_keys_mngr()

    if mngr is not None:
        res = decrypt_file(mngr, sys.argv[1])

    # Shutdown xmlsec-crypto library
    xmlsec.cryptoShutdown()

    # Shutdown crypto library
    xmlsec.cryptoAppShutdown()

    # Shutdown xmlsec library
    xmlsec.shutdown()

    # Shutdown LibXML2
    libxml2.cleanupParser()

    sys.exit(res)
Exemple #26
0
    def _desativar_funcoes_criptograficas(self):
        ''' Desativa as funções criptográficas e de análise XML
        As funções devem ser chamadas aproximadamente na ordem inversa da ativação
        '''

        # Shutdown xmlsec-crypto library
        xmlsec.cryptoShutdown()

        # Shutdown crypto library
        xmlsec.cryptoAppShutdown()

        # Shutdown xmlsec library
        xmlsec.shutdown()

        # Shutdown LibXML2 FIXME: descobrir forma de evitar o uso do libxml2 neste processo
        libxml2.cleanupParser()
    def shutdown_xmlsec(self):
        
        if not self._init_xmlsec:
            return 

        # Shutdown xmlsec-crypto library
        xmlsec.cryptoShutdown()

        # Shutdown crypto library
        xmlsec.cryptoAppShutdown()

        # Shutdown xmlsec library
        xmlsec.shutdown()

        # Shutdown LibXML2
        libxml2.cleanupParser()
Exemple #28
0
 def _desativar_funcoes_criptograficas(self):
     ''' Desativa as funções criptográficas e de análise XML
     As funções devem ser chamadas aproximadamente na ordem inversa da ativação
     '''
     
     # Shutdown xmlsec-crypto library
     xmlsec.cryptoShutdown()
     
     # Shutdown crypto library
     xmlsec.cryptoAppShutdown()
     
     # Shutdown xmlsec library
     xmlsec.shutdown()
     
     # Shutdown LibXML2 FIXME: descobrir forma de evitar o uso do libxml2 neste processo
     libxml2.cleanupParser()
    def validateXML(self, xmlToProcess):

        ctxtParser = libxml2.schemaNewParserCtxt(XSD)
        ctxtSchema = ctxtParser.schemaParse()
        ctxtValid = ctxtSchema.schemaNewValidCtxt()

        doc = libxml2.parseDoc(xmlToProcess)
        retVal = doc.schemaValidateDoc(ctxtValid)
        if( retVal != 0):
            self.logger.error("Error validating against XML Schema - "+XSD)
            sys.exit(RET_CRITICAL)
        doc.freeDoc()
        del ctxtParser
        del ctxtSchema
        del ctxtValid
        libxml2.schemaCleanupTypes()
        libxml2.cleanupParser() 
Exemple #30
0
    def validateXML(self, xmlToProcess):

        ctxtParser = libxml2.schemaNewParserCtxt(XSD)
        ctxtSchema = ctxtParser.schemaParse()
        ctxtValid = ctxtSchema.schemaNewValidCtxt()

        doc = libxml2.parseDoc(xmlToProcess)
        retVal = doc.schemaValidateDoc(ctxtValid)
        if (retVal != 0):
            self.logger.error("Error validating against XML Schema - " + XSD)
            sys.exit(RET_CRITICAL)
        doc.freeDoc()
        del ctxtParser
        del ctxtSchema
        del ctxtValid
        libxml2.schemaCleanupTypes()
        libxml2.cleanupParser()
Exemple #31
0
def main():
    secret_data = "Big secret"

    assert(sys.argv)
    if len(sys.argv) < 3:
        print "Error: wrong number of arguments."
        print "Usage: %s <xml-tmpl> <des-key-file>" % sys.argv[0]
        return sys.exit(1)
    
    # Init libxml library
    libxml2.initParser()
    libxml2.substituteEntitiesDefault(1)

    # Init xmlsec library
    if xmlsec.init() < 0:
        print "Error: xmlsec initialization failed."
        return sys.exit(-1)
    
    # Check loaded library version
    if xmlsec.checkVersion() != 1:
	print "Error: loaded xmlsec library version is not compatible.\n"
	sys.exit(-1)

    # Init crypto library
    if xmlsec.cryptoAppInit(None) < 0:
        print "Error: crypto initialization failed."
    
    # Init xmlsec-crypto library
    if xmlsec.cryptoInit() < 0:
        print "Error: xmlsec-crypto initialization failed."

    res = encrypt_file(sys.argv[1], sys.argv[2], secret_data, len(secret_data))

    # Shutdown xmlsec-crypto library
    xmlsec.cryptoShutdown()

    # Shutdown crypto library
    xmlsec.cryptoAppShutdown()

    # Shutdown xmlsec library
    xmlsec.shutdown()

    # Shutdown LibXML2
    libxml2.cleanupParser()

    sys.exit(res)
Exemple #32
0
def cleanup():
    """Cleanup all libxslt and libxml2 memory allocated"""
    libxsltmod.xsltPythonCleanup()
    libxml2.cleanupParser()
Exemple #33
0
	def tearDown(self):
		libxml2.schemaCleanupTypes()
		libxml2.cleanupParser()
		self.memLeak = libxml2.debugMemory(1) - self.initialMemUsed
Exemple #34
0
  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
Exemple #35
0
def deinit_xmlsec():
    ## Do never shut down because of cleanup bug
    #xmlsec.cryptoShutdown()
    #xmlsec.cryptoAppShutdown()  # never shut this down
    #xmlsec.shutdown()
    libxml2.cleanupParser()
Exemple #36
0
 def __del__(self):
     if self.doc != None:
         self.doc.freeDoc()
     libxml2.cleanupParser()
    def _finalizar_cripto(self):
        xmlsec.cryptoShutdown()
        xmlsec.cryptoAppShutdown()
        xmlsec.shutdown()

        libxml2.cleanupParser()
Exemple #38
0
 def tearDown(self):
     libxml2.schemaCleanupTypes()
     libxml2.cleanupParser()
     self.memLeak = libxml2.debugMemory(1) - self.initialMemUsed
Exemple #39
0
def deinit_xmlsec():
    xmlsec.cryptoShutdown()
    xmlsec.cryptoAppShutdown()
    xmlsec.shutdown()
    libxml2.cleanupParser()
Exemple #40
0
    return None

libxml2.setEntityLoader(myResolver)

input = libxml2.inputBuffer(str_io(s))
reader = input.newTextReader("test3")
reader.SetParserProp(libxml2.PARSER_SUBST_ENTITIES,1)
while reader.Read() == 1:
    res = res + "%s %s %d %d\n" % (reader.NodeType(),reader.Name(),
                                   reader.Depth(),reader.IsEmptyElement())

if res != expect:
    print("test3 failed: unexpected output")
    print(res)
    sys.exit(1)

#
# cleanup
#
del f
del input
del reader

# Memory debug specific
libxml2.cleanupParser()
if libxml2.debugMemory(1) == 0:
    print("OK")
else:
    print("Memory leak %d bytes" % (libxml2.debugMemory(1)))
    libxml2.dumpMemory()
Exemple #41
0
def importfile(dbh, filename, batch=False):
    module_logger.info("Importing %s Batch %s", filename, batch)

    status = 1
    message = 'OK'

    if os.path.isfile(filename) and os.path.getsize(filename) > 0:
        try:
            module_logger.debug("Parsing")

            xml = libxml2.newTextReaderFilename(filename)
            libxml2.registerErrorHandler(_xmlerror, "")

            while xml.Read():
                module_logger.debug('X %s %s', xml.NodeType(), xml.Name())

                if xml.NodeType(
                ) == libxml2.XML_READER_TYPE_ELEMENT and xml.Name(
                ) == 'FIMSSR':
                    module_logger.debug("Found FIMSSR %s %s", xml.NodeType(),
                                        xml.Name())
                    status, message = _process_file(dbh, xml)

                    if status != 1:
                        module_logger.debug("Status %s bailing", status)
                        break
        except:
            module_logger.exception("Parse error %s", filename)
            status = -2
            message = "XML Parser Error on file " + filename
        finally:
            module_logger.debug("Cleanup")
            libxml2.cleanupParser()
    else:
        module_logger.error("Zero size file %s", filename)
        status = -2
        message = "Zero size or truncated file " + filename

    if status == 1:
        try:
            csr = dbh.cursor()

            module_logger.debug("Store filename %s",
                                os.path.basename(filename))

            csr.execute(_sql['file_update'],
                        {'filename': os.path.basename(filename)})

            csr.close()

            module_logger.debug("Commit")

            dbh.commit()

        except:
            module_logger.warning("Rollback")

            csr.close()

            dbh.rollback()

            status = -1
            message = "DB error"

    # if not in batch the SCHD update after file
    if status == 1 and not batch:
        module_logger.debug("Not Batch mode, updating schd after file %s",
                            filename)
        status, message = _schdupdate(dbh)

    return status, message
Exemple #42
0
    def _finalizar_cripto(self):
        xmlsec.cryptoShutdown()
        xmlsec.cryptoAppShutdown()
        xmlsec.shutdown()

        libxml2.cleanupParser()
Exemple #43
0
def deinit_xmlsec():
    xmlsec.cryptoShutdown()
    xmlsec.cryptoAppShutdown()
    xmlsec.shutdown()
    libxml2.cleanupParser()
Exemple #44
0
def cleanup():
    """Cleanup all libxslt and libxml2 memory allocated"""
    libxsltmod.xsltPythonCleanup()
    libxml2.cleanupParser()
Exemple #45
0
 def __del__(self):
     if self.doc != None:
         self.doc.freeDoc()
     libxml2.cleanupParser()
Exemple #46
0
 def newfunc(*args, **kwargs):
     libxml2.debugMemory(1)
     testfunction(*args, **kwargs)
     libxml2.cleanupParser()
     leaked_bytes = libxml2.debugMemory(0) 
     assert leaked_bytes == 0, "libxml2 memory leak detected: %d bytes" % leaked_bytes
Exemple #47
0
ctxt_valid.setValidityErrorHandler(e.handler, e.handler, ARG)

# Test valid document
doc = libxml2.parseDoc(valid)
ret = doc.schemaValidateDoc(ctxt_valid)
if ret != 0 or e.errors:
    print("error doing schema validation")
    sys.exit(1)
doc.freeDoc()

# Test invalid document
doc = libxml2.parseDoc(invalid)
ret = doc.schemaValidateDoc(ctxt_valid)
if ret == 0 or not e.errors:
    print("Error: document supposer to be schema invalid")
    sys.exit(1)
doc.freeDoc()

del ctxt_parser
del ctxt_schema
del ctxt_valid
libxml2.schemaCleanupTypes()

# Memory debug specific
libxml2.cleanupParser()
if libxml2.debugMemory(1) == 0:
    print("OK")
else:
    print("Memory leak %d bytes" % (libxml2.debugMemory(1)))
    libxml2.dumpMemory()
Exemple #48
0
  def _verifyXML(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")

      dsigctx = xmlsec.DSigCtx()
         
      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)
      dsigctx.signKey = key

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

      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)

      # verify
      if dsigctx.verify(node) < 0:
        raise SignatureError('verification failed')
      if dsigctx.status == xmlsec.DSigStatusSucceeded:
          self.log("Signature is OK")
          is_valid = True
      else:
          self.log("*****************  Signature is INVALID ********************")
          is_valid = False

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

    return is_valid