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