source: TI12-security/trunk/python/Tests/xmlsec/verify2.py @ 1415

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/Tests/xmlsec/verify2.py@1415
Revision 1415, 5.2 KB checked in by pjkersha, 13 years ago (diff)

Include XML Security test programs.

Line 
1#!/usr/bin/env python
2#
3# $Id: verify2.py,v 1.1 2005/04/27 08:39:36 pjkersha Exp $
4#
5# PyXMLSec example: Verifying a file using keys manager.
6#
7# Verifies a file using keys manager
8#
9# Usage:
10#       verify2.py <signed-file> <public-pem-key1> [<public-pem-key2> [...]]
11#
12# Example:
13#       ./verify2.py sign1-res.xml rsapub.pem
14#       ./verify2.py sign2-res.xml rsapub.pem
15#
16# This is free software; see COPYING file in the source
17# distribution for preciese wording.
18#
19# Copyright (C) 2003-2004 Valery Febvre <vfebvre@easter-eggs.com>
20#
21
22import sys, os
23sys.path.insert(0, '../')
24
25import libxml2
26import xmlsec
27
28def main():
29    assert(sys.argv)
30    if len(sys.argv) < 3:
31        print "Error: wrong number of arguments."
32        print "Usage: %s <xml-file> <key-file1> [<key-file2> [...]]" % sys.argv[0]
33        return sys.exit(1)
34   
35    # Init libxml library
36    libxml2.initParser()
37    libxml2.substituteEntitiesDefault(1)
38
39    # Init xmlsec library
40    if xmlsec.init() < 0:
41        print "Error: xmlsec initialization failed."
42        return sys.exit(-1)
43   
44    # Check loaded library version
45    if xmlsec.checkVersion() != 1:
46        print "Error: loaded xmlsec library version is not compatible.\n"
47        sys.exit(-1)
48
49    # Init crypto library
50    if xmlsec.cryptoAppInit(None) < 0:
51        print "Error: crypto initialization failed."
52   
53    # Init xmlsec-crypto library
54    if xmlsec.cryptoInit() < 0:
55        print "Error: xmlsec-crypto initialization failed."
56
57    # Create keys manager and load keys
58    mngr = load_keys(sys.argv[2:], len(sys.argv) - 2)
59
60    res = 0
61    # Verify file
62    if mngr is not None:
63        res = verify_file(mngr, sys.argv[1])
64        # Destroy keys manager
65        mngr.destroy()
66   
67    # Shutdown xmlsec-crypto library
68    xmlsec.cryptoShutdown()
69
70    # Shutdown crypto library
71    xmlsec.cryptoAppShutdown()
72
73    # Shutdown xmlsec library
74    xmlsec.shutdown()
75
76    # Shutdown LibXML2
77    libxml2.cleanupParser()
78
79    sys.exit(res)
80
81
82# Creates simple keys manager and load PEM keys from files in it.
83# The caller is responsible for destroing returned keys manager using destroy.
84# Returns the newly created keys manager or None if an error occurs.
85def load_keys(files, files_size):
86    assert(files)
87    assert(files_size > 0)
88
89    # Create and initialize keys manager, we use a simple list based
90    # keys manager, implement your own KeysStore klass if you need
91    # something more sophisticated
92    mngr = xmlsec.KeysMngr()
93    if mngr is None:
94        print "Error: failed to create keys manager."
95        return None
96    if xmlsec.cryptoAppDefaultKeysMngrInit(mngr) < 0:
97        print "Error: failed to initialize keys manager."
98        mngr.destroy()
99        return None
100    for file in files:
101        # Load key
102        if not check_filename(file):
103            mngr.destroy()
104            return None
105        key = xmlsec.cryptoAppKeyLoad(file, xmlsec.KeyDataFormatPem,
106                                      None, None, None)
107        if key == None:
108            print "Error: failed to load pem key from " + file
109            mngr.destroy()       
110            return None
111        # Set key name to the file name, this is just an example!
112        if key.setName(file) < 0:
113            print "Error: failed to set key name for key from " + file
114            key.destroy()
115            mngr.destroy()
116            return None
117        # Add key to keys manager, from now on keys manager is responsible
118        # for destroying key
119        if xmlsec.cryptoAppDefaultKeysMngrAdoptKey(mngr, key) < 0:
120            print "Error: failed to add key from \"%s\" to keys manager" % file
121            key.destroy()
122            mngr.destroy()
123            return None
124    return mngr
125
126
127# Verifies XML signature in xml_file.
128# Returns 0 on success or a negative value if an error occurs.
129def verify_file(mngr, xml_file):
130    assert(mngr)
131    assert(xml_file)
132
133    # Load XML file
134    if not check_filename(xml_file):
135        return -1
136    doc = libxml2.parseFile(xml_file)
137    if doc is None or doc.getRootElement() is None:
138        print "Error: unable to parse file \"%s\"" % tmpl_file
139        return cleanup(doc)
140
141    # Find start node
142    node = xmlsec.findNode(doc.getRootElement(),
143                           xmlsec.NodeSignature, xmlsec.DSigNs)
144    if node is None:
145        print "Error: start node not found in \"%s\"", xml_file
146
147    # Create signature context
148    dsig_ctx = xmlsec.DSigCtx(mngr)
149    if dsig_ctx is None:
150        print "Error: failed to create signature context"
151        return cleanup(doc)
152
153    # Verify signature
154    if dsig_ctx.verify(node) < 0:
155        print "Error: signature verify"
156        return cleanup(doc, dsig_ctx)
157
158    # Print verification result to stdout
159    if dsig_ctx.status == xmlsec.DSigStatusSucceeded:
160        print "Signature is OK"
161    else:
162        print "Signature is INVALID"
163
164    # Success
165    return cleanup(doc, dsig_ctx, 1)
166
167
168def cleanup(doc=None, dsig_ctx=None, res=-1):
169    if dsig_ctx is not None:
170        dsig_ctx.destroy()
171    if doc is not None:
172        doc.freeDoc()
173    return res
174
175
176def check_filename(filename):
177    if os.access(filename, os.R_OK):
178        return 1
179    else:
180        print "Error: XML file \"%s\" not found OR no read access" % filename
181        return 0
182
183
184if __name__ == "__main__":
185    main()
Note: See TracBrowser for help on using the repository browser.