aboutsummaryrefslogtreecommitdiffstats
path: root/src/wgtpkg-xmlsec.c
blob: daa0cff2198f91ec5f056f17e699efd6e7be7855 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*
 Copyright (C) 2015-2018 IoT.bzh

 author: José Bollo <jose.bollo@iot.bzh>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/


#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>

#include <libxml/tree.h>
#include <xmlsec/xmlsec.h>
#include <xmlsec/xmltree.h>
#include <xmlsec/xmldsig.h>
#include <xmlsec/crypto.h>
#include <xmlsec/templates.h>
#include <xmlsec/errors.h>
#include <xmlsec/io.h>


#include "verbose.h"
#include "wgtpkg-files.h"
#include "wgtpkg-workdir.h"
#include "wgtpkg-xmlsec.h"

static int initstatus;
static int initdone;
static xmlSecKeysMngrPtr keymgr;

static const char trusted_certificates_directory[] = WGTPKG_TRUSTED_CERT_DIR;

/* checks if a file match  uri (should not be a distributor signature) */
static int file_match_cb(const char *uri)
{
	struct filedesc *fdesc = file_of_name(uri);
	return fdesc != NULL && fdesc->type == type_file && (fdesc->flags & flag_distributor_signature) == 0;
}

/* open the file of uri */
static void *file_open_cb(const char *file)
{
	struct filedesc *fdesc;
	int fd;
	FILE *f;

	fdesc = file_of_name(file);
	if (fdesc == NULL) {
		ERROR("shouldn't open uri %s", file);
		return NULL;
	}

	fd = openat(workdirfd, file, O_RDONLY);
	f = fd < 0 ? NULL : fdopen(fd, "r");
	if (f == NULL) {
		ERROR("can't open file %s for reading", file);
		if (fd >= 0)
			close(fd);
	} else
		fdesc->flags |= flag_opened;

	return f;
}

/* read the opened file */
static int file_read_cb(void *context, char *buffer, int len)
{
	size_t r = fread(buffer, 1, (unsigned)len, (FILE*)context);
	return r ? (int)r : feof((FILE*)context) ? 0 : - 1;
}

/* close the opened file */
static int file_close_cb(void *context)
{
	return (int)fclose((FILE*)context);
}

/* echo an error message */
static void errors_cb(const char *file, int line, const char *func, const char *errorObject, const char *errorSubject, int reason, const char *msg)
{
	ERROR("xmlSec error %3d: %s (subject=\"%s\", object=\"%s\")", reason, msg, errorSubject ? errorSubject : "?", errorObject ? errorObject : "?");
}

/* fills database with trusted keys */
static int fill_trusted_keys_file(const char *file)
{
	int err = xmlSecCryptoAppKeysMngrCertLoad(keymgr, file, xmlSecKeyDataFormatPem, xmlSecKeyDataTypeTrusted);
	if (err < 0) {
		ERROR("xmlSecCryptoAppKeysMngrCertLoadMemory failed for %s", file);
		return -1;
	}
	return 0;
}

/* fills database with trusted keys */
static int fill_trusted_keys_dir(const char *directory)
{
	int err;
	DIR *dir;
	struct dirent *ent;
	char path[PATH_MAX], *e;

	e = stpcpy(path, directory);
	dir = opendir(path);
	if (!dir) {
		ERROR("opendir %s failed in fill_trusted_keys_dir", path);
		return -1;
	}

	*e++ = '/';
	ent = readdir(dir);
	while (ent != NULL) {
		if (ent->d_type == DT_REG) {
			strcpy(e, ent->d_name);
			err = fill_trusted_keys_file(path);
			if (err < 0) {
				closedir(dir);
				return -1;
			}
		}
		ent = readdir(dir);
	}

	closedir(dir);
	return 0;
	
}

/* initialisation of access to xmlsec */
int xmlsec_init()
{

	if (initdone)
		goto end;

	initdone = 1;
	initstatus = -1;

	if(xmlSecInit() < 0) {
		ERROR("xmlSecInit failed.");
		goto end;
	}

#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
	if(xmlSecCryptoDLLoadLibrary(XMLSEC_CRYPTO) < 0) {
		ERROR("xmlSecCryptoDLLoadLibrary %s failed.", XMLSEC_CRYPTO);
		goto end;
	}
#endif

	if(xmlSecCryptoAppInit(NULL) < 0) {
		ERROR("xmlSecCryptoAppInit failed.");
		goto end;
	}

	if(xmlSecCryptoInit() < 0) {
		ERROR("xmlSecCryptoInit failed.");
		goto end;
	}

	xmlSecErrorsSetCallback(errors_cb);

	xmlSecIOCleanupCallbacks();
	if (xmlSecIORegisterCallbacks(file_match_cb,
					file_open_cb, file_read_cb, file_close_cb)) {
		ERROR("xmlSecIORegisterCallbacks failed.");
		goto end;
	}

	keymgr = xmlSecKeysMngrCreate();
	if (keymgr == NULL) {
		ERROR("xmlSecKeysMngrCreate failed.");
		goto end;
	}

	if(xmlSecCryptoAppDefaultKeysMngrInit(keymgr) < 0) {
		ERROR("xmlSecCryptoAppDefaultKeysMngrInit failed.");
		goto end;
	}
	fill_trusted_keys_dir(trusted_certificates_directory);

	initstatus = 0;
end:
	return initstatus;
}

/* shuting down accesses to xmlsec */
void xmlsec_shutdown()
{
	xmlSecKeysMngrDestroy(keymgr);

	xmlSecCryptoShutdown();
	
	xmlSecCryptoAppShutdown();
	
	xmlSecShutdown();
}

/* verify a signature */
int xmlsec_verify(xmlNodePtr node)
{
	int rc;
	xmlSecDSigCtxPtr dsigctx;

	assert(initdone && !initstatus);

	dsigctx = xmlSecDSigCtxCreate(keymgr);
	if (dsigctx == NULL) {
		ERROR("xmlSecDSigCtxCreate failed.");
		rc = -1;
	} else {
		rc = xmlSecDSigCtxVerify(dsigctx, node);
		if (rc)
			ERROR("xmlSecDSigCtxVerify failed.");
		else if (dsigctx->status != xmlSecDSigStatusSucceeded) {
			ERROR("invalid signature.");
			rc = -1;
		}
		xmlSecDSigCtxDestroy(dsigctx);
	}

	return rc;
}

/* templates for properties of signature files */
static const struct { const char *id; const char *xml; } properties[2] = {
	{
		.id = "AuthorSignature", /* template of properties for author signature */
		.xml =
			"<SignatureProperties xmlns:dsp=\"http://www.w3.org/2009/xmldsig-properties\">"
			 "<SignatureProperty Id=\"profile\" Target=\"#AuthorSignature\">"
			  "<dsp:Profile URI=\"http://www.w3.org/ns/widgets-digsig#profile\"></dsp:Profile>"
			 "</SignatureProperty>"
			 "<SignatureProperty Id=\"role\" Target=\"#AuthorSignature\">"
			   "<dsp:Role URI=\"http://www.w3.org/ns/widgets-digsig#role-author\"></dsp:Role>"
			 "</SignatureProperty>"
			 "<SignatureProperty Id=\"identifier\" Target=\"#AuthorSignature\">"
			   "<dsp:Identifier></dsp:Identifier>"
			 "</SignatureProperty>"
			"</SignatureProperties>"
	},
	{
		.id = "DistributorSignature", /* template of properties for distributor signature */
		.xml = 
			"<SignatureProperties xmlns:dsp=\"http://www.w3.org/2009/xmldsig-properties\">"
			 "<SignatureProperty Id=\"profile\" Target=\"#DistributorSignature\">"
			  "<dsp:Profile URI=\"http://www.w3.org/ns/widgets-digsig#profile\"></dsp:Profile>"
			 "</SignatureProperty>"
			 "<SignatureProperty Id=\"role\" Target=\"#DistributorSignature\">"
			   "<dsp:Role URI=\"http://www.w3.org/ns/widgets-digsig#role-distributor\"></dsp:Role>"
			 "</SignatureProperty>"
			 "<SignatureProperty Id=\"identifier\" Target=\"#DistributorSignature\">"
			   "<dsp:Identifier></dsp:Identifier>"
			 "</SignatureProperty>"
			"</SignatureProperties>"
	}
};

/* create a signature of 'index' (0 for author, other values for distributors)
using the private 'key' (filename) and the certificates 'certs' (filenames)
as trusted chain */
xmlDocPtr xmlsec_create(unsigned int index, const char *key, const char **certs)
{
	unsigned int i, fc, mask;
	struct filedesc *fdesc;
	xmlNodePtr sign, obj, ref, kinfo, props;
	xmlDocPtr doc;
	int rc;
	xmlSecDSigCtxPtr dsigctx;

	assert(initdone && !initstatus);

	/* create the document */
	doc = xmlNewDoc("1.0");
	if (doc == NULL) {
		ERROR("xmlNewDoc failed");
		goto error;
	}

	/* create the root signature node */
	sign = xmlSecTmplSignatureCreate(doc, xmlSecTransformInclC14N11Id, xmlSecTransformRsaSha256Id, properties[!!index].id);
	if (sign == NULL) {
		ERROR("xmlSecTmplSignatureCreate failed");
		goto error2;
	}
	xmlDocSetRootElement(doc, sign);

	/* create the object and its reference */
	obj = xmlSecTmplSignatureAddObject(sign, "prop", NULL, NULL);
	if (obj == NULL) {
		ERROR("xmlSecTmplSignatureAddObject failed");
		goto error2;
	}
	rc = xmlParseBalancedChunkMemory(doc, NULL, NULL, 0, properties[!!index].xml, &props);
	if (rc) {
		ERROR("xmlParseBalancedChunkMemory failed");
		goto error2;
	}
	if (NULL == xmlAddChild(obj, props)) {
		ERROR("filling object node failed");
		xmlFreeNode(obj);
		goto error2;
	}

	/* create references to files */
	mask = index ? flag_distributor_signature : flag_signature;
	fc = file_count();
	for (i = 0 ; i < fc ; i++) {
		fdesc = file_of_index(i);
		if (fdesc->type == type_file && (fdesc->flags & mask) == 0) {
			ref = xmlSecTmplSignatureAddReference(sign, xmlSecTransformSha256Id, NULL, fdesc->name, NULL);
			if (ref == NULL) {
				ERROR("creation of reference to %s failed", fdesc->name);
				goto error2;
			}
		}
	}

	/* create reference to object having properties */
	ref =  xmlSecTmplSignatureAddReference(sign, xmlSecTransformSha256Id, NULL, "#prop", NULL);
	if (ref == NULL) {
		ERROR("creation of reference to #prop failed");
		goto error2;
	}
	if (NULL == xmlSecTmplReferenceAddTransform(ref, xmlSecTransformInclC14N11Id)) {
		ERROR("setting transform reference to #prop failed");
		goto error2;
	}

	/* adds the X509 data */
	kinfo = xmlSecTmplSignatureEnsureKeyInfo(sign, NULL);
	if (kinfo == NULL) {
		ERROR("xmlSecTmplSignatureEnsureKeyInfo failed");
		goto error2;
	}
	if (NULL == xmlSecTmplKeyInfoAddX509Data(kinfo)) {
		ERROR("xmlSecTmplKeyInfoAddX509Data failed");
		goto error2;
	}

	/* sign now */
	dsigctx = xmlSecDSigCtxCreate(keymgr);
	if (dsigctx == NULL) {
		ERROR("xmlSecDSigCtxCreate failed.");
		goto error3;
	}
	dsigctx->signKey = xmlSecCryptoAppKeyLoad(key, xmlSecKeyDataFormatPem, NULL, NULL, NULL);
	if (dsigctx->signKey == NULL) {
		ERROR("loading key %s failed.", key);
		goto error3;
	}
	while (*certs) {
		if(xmlSecCryptoAppKeyCertLoad(dsigctx->signKey, *certs, xmlSecKeyDataFormatPem) < 0) {
			ERROR("loading certificate %s failed.", *certs);
			goto error3;
		}
		certs++;
	}
	if(xmlSecDSigCtxSign(dsigctx, sign) < 0) {
		ERROR("signing the document failed.");
		goto error3;
	}
	xmlSecDSigCtxDestroy(dsigctx);
	return doc;

error3:
	xmlSecDSigCtxDestroy(dsigctx);
error2:
	xmlFreeDoc(doc);
error:
	return NULL;
}