コード例 #1
0
    def init_xmlsec(self): 

        # Init libxml library
        libxml2.initParser()
        libxml2.substituteEntitiesDefault(1)
        
        # Init xmlsec library
        if xmlsec.init() < 0:
            log.error(" xmlsec initialization failed.")
            # XXX This should do something else...
            return sys.exit(-1)
        
        # Check loaded library version
        if xmlsec.checkVersion() != 1:
            log.error(" loaded xmlsec library version is not compatible.\n")
            sys.exit(-1)

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

        self._init_xmlsec = True 
コード例 #2
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
コード例 #3
0
ファイル: pgConnection.py プロジェクト: gislite/mapmint
 def parseConf(self):
     libxml2.initParser()
     doc = libxml2.parseFile(self.conf["main"]["dataPath"] + "/PostGIS/" + self.dbfile + ".xml")
     styledoc = libxml2.parseFile(self.conf["main"]["dataPath"] + "/PostGIS/conn.xsl")
     style = libxslt.parseStylesheetDoc(styledoc)
     res = style.applyStylesheet(doc, None)
     self.db_string = res.content.replace("PG: ", "")
コード例 #4
0
ファイル: service.py プロジェクト: gislite/mapmint
def load(conf,inputs,outputs):
	#print >> sys.stderr, conf
	# To define
	dbParams=['dbname','user','password','host','port']
	values="{"
	try: 
		parse_options = libxml2.XML_PARSE_DTDLOAD + libxml2.XML_PARSE_NOENT
		libxml2.initParser()
		xqf = libxml2.readFile(conf["main"]["dataPath"]+"/"+inputs["type"]["value"]+"/"+inputs["name"]["value"]+".xml", None, parse_options)
		cnt=0
		for j in dbParams:
			print >> sys.stderr,j
			#print >> sys.stderr, j
			try:
				items = xqf.xpathEval("/connection/"+j)
				for i in items:
				#print >> sys.stderr, cnt
					if cnt>0:
						values+=', '
					values+='"'+i.name+'": "'+str(i.children.get_content())+'"'
					cnt+=1
			except:
				values+='"'+j+'": ""'
				cnt+=1
				pass
	except Exception,e:
		print >> sys.stderr,e
		conf["lenv"]["message"]=zoo._("Unable to parse the file")
		return 4
コード例 #5
0
ファイル: service.py プロジェクト: nbozon/mapmint
def test(conf, inputs, outputs):
    libxml2.initParser()
    xcontent = (
        "<connection><dbname>"
        + inputs["dbname"]["value"]
        + "</dbname><user>"
        + inputs["user"]["value"]
        + "</user><password>"
        + inputs["password"]["value"]
        + "</password><host>"
        + inputs["host"]["value"]
        + "</host><port>"
        + inputs["port"]["value"]
        + "</port></connection>"
    )
    doc = libxml2.parseMemory(xcontent, len(xcontent))
    styledoc = libxml2.parseFile(conf["main"]["dataPath"] + "/" + inputs["type"]["value"] + "/conn.xsl")
    # print >> sys.stderr,conf["main"]["dataPath"]+"/"+inputs["type"]["value"]+"/conn.xsl"
    style = libxslt.parseStylesheetDoc(styledoc)
    result = style.applyStylesheet(doc, None)
    # print >> sys.stderr,"("+result.content+")"
    ds = osgeo.ogr.Open(result.content)
    if ds is None:
        conf["lenv"]["message"] = zoo._("Unable to connect to ") + inputs["name"]["value"]
        return 4
    else:
        outputs["Result"]["value"] = zoo._("Connection to ") + inputs["name"]["value"] + zoo._(" successfull")
    ds = None
    return 3
コード例 #6
0
ファイル: service.py プロジェクト: wslerry/mapmint
def load(conf, inputs, outputs):
    #print >> sys.stderr, conf
    # To define
    dbParams = ['dbname', 'user', 'password', 'host', 'port']
    values = "{"
    try:
        parse_options = libxml2.XML_PARSE_DTDLOAD + libxml2.XML_PARSE_NOENT
        libxml2.initParser()
        xqf = libxml2.readFile(
            conf["main"]["dataPath"] + "/" + inputs["type"]["value"] + "/" +
            inputs["name"]["value"] + ".xml", None, parse_options)
        cnt = 0
        for j in dbParams:
            print >> sys.stderr, j
            #print >> sys.stderr, j
            try:
                items = xqf.xpathEval("/connection/" + j)
                for i in items:
                    #print >> sys.stderr, cnt
                    if cnt > 0:
                        values += ', '
                    values += '"' + i.name + '": "' + str(
                        i.children.get_content()) + '"'
                    cnt += 1
            except:
                values += '"' + j + '": ""'
                cnt += 1
                pass
    except Exception, e:
        print >> sys.stderr, e
        conf["lenv"]["message"] = zoo._("Unable to parse the file")
        return 4
コード例 #7
0
    def _inicializar_cripto(self):
        libxml2.initParser()
        libxml2.substituteEntitiesDefault(1)

        xmlsec.init()
        xmlsec.cryptoAppInit(None)
        xmlsec.cryptoInit()
コード例 #8
0
ファイル: assinatura.py プロジェクト: Defendi/PyTrustNFe
    def _inicializar_cripto(self):
        libxml2.initParser()
        libxml2.substituteEntitiesDefault(1)

        xmlsec.init()
        xmlsec.cryptoAppInit(None)
        xmlsec.cryptoInit()
コード例 #9
0
ファイル: __init__.py プロジェクト: driedtoast/identitycert
def init():
    global secinit
    if secinit:
        return
    # 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."
    secinit = True
コード例 #10
0
    def parseConf(self):
	libxml2.initParser()
        doc = libxml2.parseFile(self.conf["main"]["dataPath"]+"/PostGIS/"+self.dbfile+".xml")
        styledoc = libxml2.parseFile(self.conf["main"]["dataPath"]+"/PostGIS/conn.xsl")
        style = libxslt.parseStylesheetDoc(styledoc)
        res=style.applyStylesheet(doc, None)
        self.db_string=res.content.replace("PG: ","")
コード例 #11
0
ファイル: fiskal.py プロジェクト: jerko/fiskal_v70
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
コード例 #12
0
    def __init__(self, logging):

        self.logging = logging

        self.logging.debug("Starting crypto engine")
        
        # 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:
            self.logging.error("loaded xmlsec library version is not compatible.")
            sys.exit(-1)
            
        # Init crypto library
        if xmlsec.cryptoAppInit(None) < 0:
            self.logging.error("crypto initialization failed.")
                
        # Init xmlsec-crypto library
        if xmlsec.cryptoInit() < 0:
            self.logging.error("xmlsec-crypto initialization failed.")
コード例 #13
0
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
コード例 #14
0
ファイル: xstc.py プロジェクト: 3dfreeman/OpenCOLLADA
	def setUp(self):
		#
		# Set up Libxml2.
		#
		self.initialMemUsed = libxml2.debugMemory(1)
		libxml2.initParser()
		libxml2.lineNumbersDefault(1)
		libxml2.registerErrorHandler(handleError, self)
コード例 #15
0
 def setUp(self):
     #
     # Set up Libxml2.
     #
     self.initialMemUsed = libxml2.debugMemory(1)
     libxml2.initParser()
     libxml2.lineNumbersDefault(1)
     libxml2.registerErrorHandler(handleError, self)
コード例 #16
0
ファイル: fiskal.py プロジェクト: jerko/fiskal_v70
    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
コード例 #17
0
ファイル: fiskal.py プロジェクト: badbole/fiskal_v70
    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
コード例 #18
0
ファイル: certificado.py プロジェクト: wcreis/PySPED
    def _inicia_funcoes_externas(self):
        # Ativa as funções de análise de arquivos XML
        libxml2.initParser()
        libxml2.substituteEntitiesDefault(1)

        # Ativa as funções da API de criptografia
        xmlsec.init()
        xmlsec.cryptoAppInit(None)
        xmlsec.cryptoInit()
コード例 #19
0
ファイル: assinatura.py プロジェクト: danielgoncalves/PyNFe
    def _ativar_funcoes_criptograficas(self):
        # FIXME: descobrir forma de evitar o uso do libxml2 neste processo

        # Ativa as funções de análise de arquivos XML FIXME
        libxml2.initParser()
        libxml2.substituteEntitiesDefault(1)
        
        # Ativa as funções da API de criptografia
        xmlsec.init()
        xmlsec.cryptoAppInit(None)
        xmlsec.cryptoInit()
コード例 #20
0
ファイル: xmlsec_wrapper.py プロジェクト: GoodRx/SudsSigner
def init_xmlsec():
    libxml2.initParser()
    libxml2.substituteEntitiesDefault(1)
    if xmlsec.init() < 0:
        raise RuntimeError('xmlsec initialization failed')
    if xmlsec.checkVersion() != 1:
        raise RuntimeError('loaded xmlsec library version is not compatible')
    if xmlsec.cryptoAppInit(None) < 0:
        raise RuntimeError('crypto initialization failed')
    if xmlsec.cryptoInit() < 0:
        raise RuntimeError('xmlsec-crypto initialization failed')
コード例 #21
0
ファイル: xmlsec_wrapper.py プロジェクト: Se7ge/SudsSigner
def init_xmlsec():
    libxml2.initParser()
    libxml2.substituteEntitiesDefault(1)
    if xmlsec.init() < 0:
        raise RuntimeError('xmlsec initialization failed')
    if xmlsec.checkVersion() != 1:
        raise RuntimeError('loaded xmlsec library version is not compatible')
    if xmlsec.cryptoAppInit(None) < 0:
        raise RuntimeError('crypto initialization failed')
    if xmlsec.cryptoInit() < 0:
        raise RuntimeError('xmlsec-crypto initialization failed')
コード例 #22
0
    def _ativar_funcoes_criptograficas(self):
        # FIXME: descobrir forma de evitar o uso do libxml2 neste processo

        # Ativa as funções de análise de arquivos XML FIXME
        libxml2.initParser()
        libxml2.substituteEntitiesDefault(1)

        # Ativa as funções da API de criptografia
        xmlsec.init()
        xmlsec.cryptoAppInit(None)
        xmlsec.cryptoInit()
コード例 #23
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)
コード例 #24
0
 def init():
     # Init libxml library
     libxml2.initParser()
     libxml2.substituteEntitiesDefault(1)
     # Init xmlsec library
     assert xmlsec.init() >= 0, "Error: xmlsec initialization failed."
     # Check loaded library version
     assert xmlsec.checkVersion() == 1, "Error: loaded xmlsec library version is not compatible."
     # Init crypto library
     assert xmlsec.cryptoAppInit(None) >= 0, "Error: crypto initialization failed."
     # Init xmlsec-crypto library
     assert xmlsec.cryptoInit() >= 0, "Error: xmlsec-crypto initialization failed."
コード例 #25
0
ファイル: verify2.py プロジェクト: artur-kacen/pyxmlsec
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)
コード例 #26
0
ファイル: decrypt3.py プロジェクト: dnet/pyxmlsec
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)
コード例 #27
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)
コード例 #28
0
ファイル: xmldsig.py プロジェクト: alyanwarr/Xigner
def _init():
    """Initializes the libxml2 parser and XMLSEC library. Is called
    automatically upon loading this module.
    """
    # Initiate the libxml2 parser
    libxml2.initParser()
    libxml2.substituteEntitiesDefault(1)

    # Initialize xmlsec
    if xmlsec.init() < 0:
        raise XMLDSIGError("Failed initializing xmlsec library")
    if xmlsec.cryptoAppInit(None) < 0:
        raise XMLDSIGError("Failed initializing crypto library")
    if xmlsec.cryptoInit() < 0:
        raise XMLDSIGError("Failed initializing xmlsec-crypto library")
コード例 #29
0
ファイル: xmldsig.py プロジェクト: AntagonistHQ/xmldsig
def _init():
    """Initializes the libxml2 parser and XMLSEC library. Is called
    automatically upon loading this module.
    """
    # Initiate the libxml2 parser
    libxml2.initParser()
    libxml2.substituteEntitiesDefault(1)
            
    # Initialize xmlsec
    if xmlsec.init() < 0:
        raise XMLDSIGError("Failed initializing xmlsec library")
    if xmlsec.cryptoAppInit(None) < 0:
        raise XMLDSIGError("Failed initializing crypto library")
    if xmlsec.cryptoInit() < 0:
        raise XMLDSIGError("Failed initializing xmlsec-crypto library")
コード例 #30
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)
コード例 #31
0
 def init():
     global usexml
     if not usexml:
         return
     try:
       # Init libxml library
       libxml2.initParser()
       libxml2.substituteEntitiesDefault(1)
       # Init xmlsec library
       assert xmlsec.init() >= 0, "Error: xmlsec initialization failed."
       # Check loaded library version
       assert xmlsec.checkVersion() == 1, "Error: loaded xmlsec library version is not compatible."
       # Init crypto library
       assert xmlsec.cryptoAppInit(None) >= 0, "Error: crypto initialization failed."
       # Init xmlsec-crypto library
       assert xmlsec.cryptoInit() >= 0, "Error: xmlsec-crypto initialization failed."
     except:
       usexml=False
コード例 #32
0
def _init():
    """
    Initialize necessary libraries (libxml2 and xmlsec).
    Should be called once only: this is automatic when this module is imported.
    Raises an exception if an error occurs.
    """
    # Init libxml library
    libxml2.initParser()
    libxml2.substituteEntitiesDefault(1)
    # Init xmlsec library
    assert xmlsec.init() >= 0, "Error: xmlsec initialization failed."
    # Check loaded library version
    assert xmlsec.checkVersion(
    ) == 1, "Error: loaded xmlsec library version is not compatible."
    # Init crypto library
    assert xmlsec.cryptoAppInit(
        None) >= 0, "Error: crypto initialization failed."
    # Init xmlsec-crypto library
    assert xmlsec.cryptoInit(
    ) >= 0, "Error: xmlsec-crypto initialization failed."
コード例 #33
0
ファイル: utils.py プロジェクト: imraneyim/python-saml2
def lib_init():
  # Init libxml library
  libxml2.initParser()
  libxml2.substituteEntitiesDefault(1)

  # Init xmlsec library
  if xmlsec.init() < 0:
    raise(saml2.Error("Error: xmlsec initialization failed."))

  # Check loaded library version
  if xmlsec.checkVersion() != 1:
    raise(saml2.Error(
      "Error: loaded xmlsec library version is not compatible.\n"))

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

  # Init xmlsec-crypto library
  if xmlsec.cryptoInit() < 0:
    raise(saml2.Error("Error: xmlsec-crypto initialization failed."))  
コード例 #34
0
ファイル: service.py プロジェクト: mapmint/mapmint
def details(conf,inputs,outputs):
	dbParams=['dbname','user','password','host','port']
	res={}
	values="{"
	try: 
		parse_options = libxml2.XML_PARSE_DTDLOAD + libxml2.XML_PARSE_NOENT
		libxml2.initParser()
		xqf = libxml2.readFile(conf["main"]["dataPath"]+"/"+inputs["type"]["value"]+"/"+inputs["name"]["value"]+".xml", None, parse_options)
		cnt=0
		for j in dbParams:
			print >> sys.stderr,j
			#print >> sys.stderr, j
			try:
				items = xqf.xpathEval("/connection/"+j)
				for i in items:
				    res[i.name]=str(i.children.get_content())
			except:
				res[j]=""
				pass
	except Exception,e:
		conf["lenv"]["message"]=zoo._("Unable to parse the file: ")+str(e)
		return zoo.SERVICE_FAILED
コード例 #35
0
ファイル: service.py プロジェクト: wslerry/mapmint
def test(conf, inputs, outputs):
    libxml2.initParser()
    xcontent = '<connection><dbname>' + inputs["dbname"][
        "value"] + '</dbname><user>' + inputs["user"][
            "value"] + '</user><password>' + inputs["password"][
                "value"] + '</password><host>' + inputs["host"][
                    "value"] + '</host><port>' + inputs["port"][
                        "value"] + '</port></connection>'
    doc = libxml2.parseMemory(xcontent, len(xcontent))
    styledoc = libxml2.parseFile(conf["main"]["dataPath"] + "/" +
                                 inputs["type"]["value"] + "/conn.xsl")
    style = libxslt.parseStylesheetDoc(styledoc)
    result = style.applyStylesheet(doc, None)
    ds = osgeo.ogr.Open(result.content)
    if ds is None:
        conf["lenv"]["message"] = zoo._(
            "Unable to connect to ") + inputs["name"]["value"]
        return 4
    else:
        print >> sys.stderr, "OK 6'"
        outputs["Result"]["value"] = zoo._("Connection to ") + str(
            inputs["name"]["value"]).encode('utf-8') + zoo._(" successfull")
    ds = None
    return 3
コード例 #36
0
ファイル: service.py プロジェクト: wslerry/mapmint
def details(conf, inputs, outputs):
    dbParams = ['dbname', 'user', 'password', 'host', 'port']
    res = {}
    values = "{"
    try:
        parse_options = libxml2.XML_PARSE_DTDLOAD + libxml2.XML_PARSE_NOENT
        libxml2.initParser()
        xqf = libxml2.readFile(
            conf["main"]["dataPath"] + "/" + inputs["type"]["value"] + "/" +
            inputs["name"]["value"] + ".xml", None, parse_options)
        cnt = 0
        for j in dbParams:
            print >> sys.stderr, j
            #print >> sys.stderr, j
            try:
                items = xqf.xpathEval("/connection/" + j)
                for i in items:
                    res[i.name] = str(i.children.get_content())
            except:
                res[j] = ""
                pass
    except Exception, e:
        conf["lenv"]["message"] = zoo._("Unable to parse the file: ") + str(e)
        return zoo.SERVICE_FAILED
コード例 #37
0
ファイル: saml_sp.py プロジェクト: salrashid123/googlapps-sso
  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
コード例 #38
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
コード例 #39
0
ファイル: utils.py プロジェクト: driedtoast/identitycert
def lib_init():
    # Init libxml library
    libxml2.initParser()
    libxml2.substituteEntitiesDefault(1)
コード例 #40
0
ファイル: utils.py プロジェクト: driedtoast/identitycert
def lib_init():
  # Init libxml library
  libxml2.initParser()
  libxml2.substituteEntitiesDefault(1)
コード例 #41
0
ファイル: simple.py プロジェクト: CGTIC/Plone_SP
import os
import thread
from types import ListType, TupleType
from xml.dom import minidom
from cStringIO import StringIO
from DateTime import DateTime
from Products.CMFCore.utils import getToolByName
from Products.Archetypes.Marshall import Marshaller
from Products.Archetypes.Field import ReferenceField
from Products.Archetypes.config import REFERENCE_CATALOG, UUID_ATTR
from Products.Archetypes.debug import log
from Products.Marshall.config import AT_NS, CMF_NS, ATXML_SCHEMA
from Products.Marshall.exceptions import MarshallingException

import libxml2
libxml2.initParser()


class SimpleXMLMarshaller(Marshaller):

    __name__ = 'Simple XML Marshaller'

    def demarshall(self, instance, data, **kwargs):
        doc = libxml2.parseDoc(data)
        p = instance.getPrimaryField()
        pname = p and p.getName() or None
        try:
            fields = [f for f in instance.Schema().fields()
                      if f.getName() != pname]
            for f in fields:
                items = doc.xpathEval('/*/%s' % f.getName())
コード例 #42
0
import thread
from types import ListType, TupleType
from xml.dom import minidom
from cStringIO import StringIO
from DateTime import DateTime
from Products.CMFCore.utils import getToolByName
from Products.Archetypes.Marshall import Marshaller
from Products.Archetypes.Field import ReferenceField
from Products.Archetypes.config import REFERENCE_CATALOG, UUID_ATTR
from Products.Archetypes.debug import log
from Products.Marshall.config import AT_NS, CMF_NS, ATXML_SCHEMA
from Products.Marshall.exceptions import MarshallingException

import libxml2

libxml2.initParser()


class SimpleXMLMarshaller(Marshaller):

    __name__ = 'Simple XML Marshaller'

    def demarshall(self, instance, data, **kwargs):
        doc = libxml2.parseDoc(data)
        p = instance.getPrimaryField()
        pname = p and p.getName() or None
        try:
            fields = [
                f for f in instance.Schema().fields() if f.getName() != pname
            ]
            for f in fields: