1 /**
2  * XML Security Library example: Signing a file with a dynamicaly created template and an X509 certificate.
3  *
4  * Signs a file using a dynamicaly created template, key from PEM file and
5  * an X509 certificate. The signature has one reference with one enveloped
6  * transform to sign the whole document except the <dsig:Signature/> node
7  * itself. The key certificate is written in the <dsig:X509Data/> node.
8  *
9  * This example was developed and tested with OpenSSL crypto library. The
10  * certificates management policies for another crypto library may break it.
11  *
12  * Usage:
13  *      sign3 <xml-doc> <pem-key>
14  *
15  * Example:
16  *      ./sign3 sign3-doc.xml rsakey.pem rsacert.pem > sign3-res.xml
17  *
18  * The result signature could be validated using verify3 example:
19  *      ./verify3 sign3-res.xml ca2cert.pem cacert.pem
20  *
21  * This is free software; see Copyright file in the source
22  * distribution for preciese wording.
23  *
24  * Copyright (C) 2002-2016 Aleksey Sanin <aleksey@aleksey.com>. All Rights Reserved.
25  */
26 #include <stdlib.h>
27 #include <string.h>
28 #include <assert.h>
29 
30 #include <libxml/tree.h>
31 #include <libxml/xmlmemory.h>
32 #include <libxml/parser.h>
33 
34 #ifndef XMLSEC_NO_XSLT
35 #include <libxslt/xslt.h>
36 #include <libxslt/security.h>
37 #endif /* XMLSEC_NO_XSLT */
38 
39 #include <xmlsec/xmlsec.h>
40 #include <xmlsec/xmltree.h>
41 #include <xmlsec/xmldsig.h>
42 #include <xmlsec/templates.h>
43 #include <xmlsec/crypto.h>
44 
45 int sign_file(const char* xml_file, const char* key_file, const char* cert_file);
46 
47 int
main(int argc,char ** argv)48 main(int argc, char **argv) {
49 #ifndef XMLSEC_NO_XSLT
50     xsltSecurityPrefsPtr xsltSecPrefs = NULL;
51 #endif /* XMLSEC_NO_XSLT */
52 
53     assert(argv);
54 
55     if(argc != 4) {
56         fprintf(stderr, "Error: wrong number of arguments.\n");
57         fprintf(stderr, "Usage: %s <xml-file> <key-file> <cert-file>\n", argv[0]);
58         return(1);
59     }
60 
61     /* Init libxml and libxslt libraries */
62     xmlInitParser();
63     LIBXML_TEST_VERSION
64     xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
65     xmlSubstituteEntitiesDefault(1);
66 #ifndef XMLSEC_NO_XSLT
67     xmlIndentTreeOutput = 1;
68 #endif /* XMLSEC_NO_XSLT */
69 
70     /* Init libxslt */
71 #ifndef XMLSEC_NO_XSLT
72     /* disable everything */
73     xsltSecPrefs = xsltNewSecurityPrefs();
74     xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_READ_FILE,        xsltSecurityForbid);
75     xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_WRITE_FILE,       xsltSecurityForbid);
76     xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_CREATE_DIRECTORY, xsltSecurityForbid);
77     xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_READ_NETWORK,     xsltSecurityForbid);
78     xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_WRITE_NETWORK,    xsltSecurityForbid);
79     xsltSetDefaultSecurityPrefs(xsltSecPrefs);
80 #endif /* XMLSEC_NO_XSLT */
81 
82     /* Init xmlsec library */
83     if(xmlSecInit() < 0) {
84         fprintf(stderr, "Error: xmlsec initialization failed.\n");
85         return(-1);
86     }
87 
88     /* Check loaded library version */
89     if(xmlSecCheckVersion() != 1) {
90         fprintf(stderr, "Error: loaded xmlsec library version is not compatible.\n");
91         return(-1);
92     }
93 
94     /* Load default crypto engine if we are supporting dynamic
95      * loading for xmlsec-crypto libraries. Use the crypto library
96      * name ("openssl", "nss", etc.) to load corresponding
97      * xmlsec-crypto library.
98      */
99 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
100     if(xmlSecCryptoDLLoadLibrary(NULL) < 0) {
101         fprintf(stderr, "Error: unable to load default xmlsec-crypto library. Make sure\n"
102                         "that you have it installed and check shared libraries path\n"
103                         "(LD_LIBRARY_PATH and/or LTDL_LIBRARY_PATH) environment variables.\n");
104         return(-1);
105     }
106 #endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */
107 
108     /* Init crypto library */
109     if(xmlSecCryptoAppInit(NULL) < 0) {
110         fprintf(stderr, "Error: crypto initialization failed.\n");
111         return(-1);
112     }
113 
114     /* Init xmlsec-crypto library */
115     if(xmlSecCryptoInit() < 0) {
116         fprintf(stderr, "Error: xmlsec-crypto initialization failed.\n");
117         return(-1);
118     }
119 
120     if(sign_file(argv[1], argv[2], argv[3]) < 0) {
121         return(-1);
122     }
123 
124     /* Shutdown xmlsec-crypto library */
125     xmlSecCryptoShutdown();
126 
127     /* Shutdown crypto library */
128     xmlSecCryptoAppShutdown();
129 
130     /* Shutdown xmlsec library */
131     xmlSecShutdown();
132 
133     /* Shutdown libxslt/libxml */
134 #ifndef XMLSEC_NO_XSLT
135     xsltFreeSecurityPrefs(xsltSecPrefs);
136     xsltCleanupGlobals();
137 #endif /* XMLSEC_NO_XSLT */
138     xmlCleanupParser();
139 
140     return(0);
141 }
142 
143 /**
144  * sign_file:
145  * @xml_file:           the XML file name.
146  * @key_file:           the PEM private key file name.
147  * @cert_file:          the x509 certificate PEM file.
148  *
149  * Signs the @xml_file using private key from @key_file and dynamicaly
150  * created enveloped signature template. The certificate from @cert_file
151  * is placed in the <dsig:X509Data/> node.
152  *
153  * Returns 0 on success or a negative value if an error occurs.
154  */
155 int
sign_file(const char * xml_file,const char * key_file,const char * cert_file)156 sign_file(const char* xml_file, const char* key_file, const char* cert_file) {
157     xmlDocPtr doc = NULL;
158     xmlNodePtr signNode = NULL;
159     xmlNodePtr refNode = NULL;
160     xmlNodePtr keyInfoNode = NULL;
161     xmlNodePtr x509DataNode = NULL;
162     xmlSecDSigCtxPtr dsigCtx = NULL;
163     int res = -1;
164 
165     assert(xml_file);
166     assert(key_file);
167     assert(cert_file);
168 
169     /* load doc file */
170     doc = xmlParseFile(xml_file);
171     if ((doc == NULL) || (xmlDocGetRootElement(doc) == NULL)){
172         fprintf(stderr, "Error: unable to parse file \"%s\"\n", xml_file);
173         goto done;
174     }
175 
176     /* create signature template for RSA-SHA1 enveloped signature */
177     signNode = xmlSecTmplSignatureCreate(doc, xmlSecTransformExclC14NId,
178                                          xmlSecTransformRsaSha1Id, NULL);
179     if(signNode == NULL) {
180         fprintf(stderr, "Error: failed to create signature template\n");
181         goto done;
182     }
183 
184     /* add <dsig:Signature/> node to the doc */
185     xmlAddChild(xmlDocGetRootElement(doc), signNode);
186 
187     /* add reference */
188     refNode = xmlSecTmplSignatureAddReference(signNode, xmlSecTransformSha1Id,
189                                         NULL, NULL, NULL);
190     if(refNode == NULL) {
191         fprintf(stderr, "Error: failed to add reference to signature template\n");
192         goto done;
193     }
194 
195     /* add enveloped transform */
196     if(xmlSecTmplReferenceAddTransform(refNode, xmlSecTransformEnvelopedId) == NULL) {
197         fprintf(stderr, "Error: failed to add enveloped transform to reference\n");
198         goto done;
199     }
200 
201     /* add <dsig:KeyInfo/> and <dsig:X509Data/> */
202     keyInfoNode = xmlSecTmplSignatureEnsureKeyInfo(signNode, NULL);
203     if(keyInfoNode == NULL) {
204         fprintf(stderr, "Error: failed to add key info\n");
205         goto done;
206     }
207 
208     x509DataNode = xmlSecTmplKeyInfoAddX509Data(keyInfoNode);
209     if(x509DataNode == NULL) {
210         fprintf(stderr, "Error: failed to add X509Data node\n");
211         goto done;
212     }
213 
214     if(xmlSecTmplX509DataAddSubjectName(x509DataNode) == NULL) {
215         fprintf(stderr, "Error: failed to add X509SubjectName node\n");
216         goto done;
217     }
218 
219     if(xmlSecTmplX509DataAddCertificate(x509DataNode) == NULL) {
220         fprintf(stderr, "Error: failed to add X509Certificate node\n");
221         goto done;
222     }
223 
224     /* create signature context, we don't need keys manager in this example */
225     dsigCtx = xmlSecDSigCtxCreate(NULL);
226     if(dsigCtx == NULL) {
227         fprintf(stderr,"Error: failed to create signature context\n");
228         goto done;
229     }
230 
231     /* load private key, assuming that there is not password */
232     dsigCtx->signKey = xmlSecCryptoAppKeyLoad(key_file, xmlSecKeyDataFormatPem, NULL, NULL, NULL);
233     if(dsigCtx->signKey == NULL) {
234         fprintf(stderr,"Error: failed to load private pem key from \"%s\"\n", key_file);
235         goto done;
236     }
237 
238     /* load certificate and add to the key */
239     if(xmlSecCryptoAppKeyCertLoad(dsigCtx->signKey, cert_file, xmlSecKeyDataFormatPem) < 0) {
240         fprintf(stderr,"Error: failed to load pem certificate \"%s\"\n", cert_file);
241         goto done;
242     }
243 
244     /* set key name to the file name, this is just an example! */
245     if(xmlSecKeySetName(dsigCtx->signKey, key_file) < 0) {
246         fprintf(stderr,"Error: failed to set key name for key from \"%s\"\n", key_file);
247         goto done;
248     }
249 
250     /* sign the template */
251     if(xmlSecDSigCtxSign(dsigCtx, signNode) < 0) {
252         fprintf(stderr,"Error: signature failed\n");
253         goto done;
254     }
255 
256     /* print signed document to stdout */
257     xmlDocDump(stdout, doc);
258 
259     /* success */
260     res = 0;
261 
262 done:
263     /* cleanup */
264     if(dsigCtx != NULL) {
265         xmlSecDSigCtxDestroy(dsigCtx);
266     }
267 
268     if(doc != NULL) {
269         xmlFreeDoc(doc);
270     }
271     return(res);
272 }
273 
274