certgen.c 44.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*********************************************************************
######################################################################
##
##  Created by: Denis Filatov
##
##  Copyleft (c) 2015
##  This code is provided under the CeCill-C license agreement.
######################################################################
*********************************************************************/
#define _CRT_SECURE_NO_WARNINGS
11 12
#define _USE_MATH_DEFINES

13
#include <stdio.h>
14 15 16 17
#include "../cxml/cxml.h"
#include "../cshared/copts.h"
#include "../cshared/cserialize.h"
#include "../cshared/cstr.h"
18 19
#include "../cshared/cring.h"
#include "../cshared/cmem.h"
20 21 22 23 24 25 26 27 28 29 30

#include "ecc_api.h"
#include "mkgmtime.h"
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
#include <limits.h>
#include <time.h>
#include <math.h>

31 32 33 34
#if defined(__CYGWIN__)
#define floorl(X) __builtin_floor(X)
#endif

35 36 37 38 39 40 41 42 43 44
//#define DEBUG_BOOKMARKS
//#define DEBUG_DATA
#define MAX_BOOKMARKS 16

typedef struct bookmark_t bookmark_t;
struct bookmark_t {
	bookmark_t * prev;
	char       * ptr;
};

filatov's avatar
filatov committed
45 46 47 48 49 50 51 52 53
typedef enum {
	si_self,
	si_digest,
	si_certificate,
	si_certificate_chain,
	si_digest_with_other_algorithm,
	si_other
} SignerInfoType;

54 55 56 57 58 59
typedef struct cert_cxml_handler_t
{
	cxml_handler_t  h;
	unsigned int    subject_type;
	int             signer_type;
	const char    * signer;
filatov's avatar
filatov committed
60
	const char    * signer_digest;
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
	int             vr_type;
	int             sa_type;
	void          * verificationKey;
	void          * encryptionKey;

	int				pk_alg;
	int				pk_sym_alg;
	int				pk_ptype;
	char          * pk_data;
	int				pk_datasize;

	char   		  * buf;
	char          * ptr;
	const char    * end;

	char          * bookmarks[MAX_BOOKMARKS];
	int             bidx;

	unsigned int    nTmpValue;
	void          * key;
}cert_cxml_handler_t;

static void bookmark_position(cert_cxml_handler_t * const h, const cxml_tag_t * tag)
{
	if (h->bidx >= MAX_BOOKMARKS){
		fprintf(stderr, "FATAL: Profile is tooooooo complicated!!!\n");
		exit(-1);
	}
	h->bookmarks[h->bidx] = h->ptr;
	h->bidx++;
	h->ptr++;
#ifdef DEBUG_BOOKMARKS
	printf("BOOKMARK 0x%08X (%s)\n", (unsigned int)h->ptr, tag->name);
#endif
}

static int apply_bookmark_size(cert_cxml_handler_t * const h, const cxml_tag_t * tag)
{
	int size, bcount;
	char * psize;
	if (h->bidx == 0){
		fprintf(stderr, "FATAL: Inconsistent bookmarks!!!\n");
		exit(-1);
	}
	psize = h->bookmarks[--h->bidx];
	size = h->ptr - psize - 1;
#ifdef DEBUG_BOOKMARKS
	printf("APPLY    0x%08X [%d] (%s)\n", (unsigned int)h->ptr, size, tag->name);
#endif
	bcount = cintx_bytecount(size);
	if (bcount == 1){
		*(unsigned char*)psize = size;
		size = 0;
	}
	else{
		memmove(psize + bcount, psize + 1, h->ptr - psize - 1);
		h->ptr += bcount - 1;
		size = cintx_write(size, &psize, psize + bcount, NULL);
	}
	return size; // size is overridden to be 0 or -1
}

static int attribute_public_key_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int attribute_eccpoint_tag   (cxml_handler_t* const h, cxml_tag_t * const tag);
static int attribute_eccpoint_text  (cxml_handler_t* const h, char * const text, int length);
static int attribute_assurance_tag  (cxml_handler_t* const h, cxml_tag_t * const tag);
static int attribute_aid_tag        (cxml_handler_t* const h, cxml_tag_t * const tag);
static int attribute_ssp_tag        (cxml_handler_t* const h, cxml_tag_t * const tag);
static int attribute_ssp_text       (cxml_handler_t* const h, char * const text, int length);

static const cxml_taghandler_t h_publickey[] = {
	{ "eccpoint",  attribute_eccpoint_tag, attribute_eccpoint_text, NULL },
	{ "ecc-point", attribute_eccpoint_tag, attribute_eccpoint_text, NULL },
	{ "ecc_point", attribute_eccpoint_tag, attribute_eccpoint_text, NULL },
	{ NULL }
};

static const cxml_taghandler_t h_attribute[] = {
	{ "public-key", attribute_public_key_tag, NULL, h_publickey },
	{ "public_key", attribute_public_key_tag, NULL, h_publickey },
	{ "publickey",  attribute_public_key_tag, NULL, h_publickey },
	{ "eccpoint",   attribute_eccpoint_tag, attribute_eccpoint_text, NULL },
	{ "ecc-point",  attribute_eccpoint_tag, attribute_eccpoint_text, NULL },
	{ "ecc_point",  attribute_eccpoint_tag, attribute_eccpoint_text, NULL },
	{ "assurance",  attribute_assurance_tag, NULL, NULL },
146 147 148
	{ "aid", attribute_aid_tag, NULL, NULL },
	{ "ssp", attribute_ssp_tag, attribute_ssp_text, NULL },
	{ NULL }
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
};

static int subject_attribute_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static const cxml_taghandler_t h_subject[] = {
    {"attribute",  subject_attribute_tag,  NULL,  h_attribute},
    {NULL}
};

static int location_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static const cxml_taghandler_t h_location_list [] = {
    {"location",   location_tag,   NULL, NULL },
    {NULL}
};

static int region_none_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int region_circle_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int region_rectangle_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int region_polygon_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
filatov's avatar
filatov committed
167 168 169
static int region_id_tag(cxml_handler_t* const h, cxml_tag_t * const tag);
static int region_region_tag(cxml_handler_t* const h, cxml_tag_t * const tag);
static int region_region_text(cxml_handler_t* const h, char * const text, int length);
170
static const cxml_taghandler_t h_restriction[] = {
filatov's avatar
filatov committed
171 172 173 174 175 176
    {"region",     region_region_tag,    region_region_text, NULL },
    {"none",       region_none_tag,      NULL,               NULL },
    {"circle",     region_circle_tag,    NULL,               NULL },
    {"rectangle",  region_rectangle_tag, NULL,               h_location_list },
    {"polygon",    region_polygon_tag,   NULL,               h_location_list },
    {"id",         region_id_tag,        NULL,               NULL },
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
    {NULL}
};

static int validity_restriction_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static const cxml_taghandler_t h_validity[] = {
    {"restriction",  validity_restriction_tag,    NULL, h_restriction },
    {NULL}
};
	
static int certificate_version_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int certificate_version_text(cxml_handler_t* const h, char * const text, int length);
static int certificate_signer_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int certificate_signer_text(cxml_handler_t* const h, char * const text, int length);
static int certificate_subject_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int certificate_validity_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int certificate_signature_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static const cxml_taghandler_t h_certificate[] = {
    {"version",   certificate_version_tag, certificate_version_text, NULL },
    {"signer",    certificate_signer_tag,  certificate_signer_text,  NULL },
    {"subject",   certificate_subject_tag, NULL,  h_subject },
    {"validity",  certificate_validity_tag, NULL,  h_validity },
    {"signature", certificate_signature_tag, NULL,  h_validity },
    {NULL}
};

static int root_certificate_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static const cxml_taghandler_t h_root[] = {
    {"certificate", root_certificate_tag, NULL, h_certificate },
    {NULL}
};

static int  _Begin_Tag(cxml_handler_t* const h, cxml_tag_t * const tag);
static int  _End_Tag(cxml_handler_t* const h, cxml_tag_t * const tag);
static int  _Text(cxml_handler_t* const h, char * const text, int length);


static cxml_handler_class Class = {
    sizeof(cert_cxml_handler_t),
    NULL, NULL,
    _Begin_Tag, _End_Tag,
    _Text
};

#define STR2ENUM(N,V) _str_2_enum(N, sizeof(N)/sizeof(N[0]), V)

static int _str_2_enum(const char ** values, size_t size, const char * v)
{
224
	while (*v && cisspace(*v))v++;
225 226 227 228 229 230 231
	if (*v){
		size_t i;
		for (i = 0; i<size; i++){
			if (values[i] && 0 == strcmp(values[i], v)) {
				return i;
			}
		}
232
		if (cisdigit(*v)){
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
			return strtoul(v, NULL, 0);
		}
	}
	return -1;
}

#ifdef DEBUG_DATA
static void print_x(FILE * f, const char * ptr, int len)
{
	const unsigned char * e = (const unsigned char *)(ptr + len);
	for (; ptr < e; ptr++){
		unsigned char c = *ptr;
		fprintf(f, "%02X", c);
	}
}
#endif

static unsigned int _convert_time(const char * v);

static const char *_outPath = ".";
static const char *_searchPath = NULL;
static const char *_certName = NULL;
static       char *_profileName = NULL;
static const char *_signerName = NULL;
static unsigned int _defaultTime = 0;
static ecc_format   _outFormat = 0;
static const char * _verificationKey = NULL;
static const char * _decriptionKey   = NULL;
static const char * _keyPath = NULL;
static int          _reuseKeys = 0;
263
static int          _force = 0;
264 265 266 267

static long         _refLat = 0;
static long         _refLon = 0;

268 269
static const long double _latTMDPerMetter = 180.0 / M_PI / 0.6378;
static long double       _lonTMDPerMetter = 180.0 / M_PI / 0.6378;
270 271
static const char * _cfgFile = NULL;

272 273 274 275 276 277 278 279 280 281 282 283
static void _setup_default_time()
{
	time_t t;
	struct tm * ptm;
	struct tm   tm = {0};
	memset(&tm, 0, sizeof(tm));
	time(&t);
	ptm = gmtime(&t);
	tm.tm_mday = 1;
	tm.tm_year = ptm->tm_year;
	_defaultTime = mkitstime32(&tm);
}
284 285 286 287 288 289 290 291 292 293 294 295

static int _time_option(const copt_t * opt, const char * option, const copt_value_t * value)
{
	_defaultTime = _convert_time(value->v_str);
	return (_defaultTime == (unsigned int)-1) ? -1 : 0;
}

static int _refPoint_option(const copt_t * opt, const char * option, const copt_value_t * value)
{
	char * e;
	long double lat, lon;
	lat = strtold(value->v_str, &e);
filatov's avatar
filatov committed
296
	if (*e == ':' || *e == ','){
297 298 299 300 301 302
		lon = strtold(e + 1, &e);
		if (*e == 0){
			if (lat <= 90.0 &&  lat >= -90.0) lat *= 10000000.0; // degree
			_refLat = (int32_t)floorl(lat);
			if (lon <= 180.0 &&  lon >= -180.0) lon *= 10000000.0; // degree
			_refLon = (int32_t)floorl(lon);
303
			_lonTMDPerMetter = 180.0 / M_PI / 0.6378 / cos((lat/10000000.0) * M_PI / 180.0);
304 305 306 307 308 309
			return 0;
		}
	}
	return -1;
}

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
typedef struct macro_item macro_item;
struct macro_item {
	cring_t _ring;
	const char* name;
	const char* value;
};
static macro_item _default_macro[] = {
	{ { NULL, NULL }, "CAM", "36" },
	{ { NULL, NULL }, "DENM", "37" },
	{ { NULL, NULL }, "GENERIC", "38" },
	{ { NULL, NULL }, "TLM", "137" },
	{ { NULL, NULL }, "SPAT", "137" },
	{ { NULL, NULL }, "RLT", "138" },
	{ { NULL, NULL }, "MAP", "138" },
	{ { NULL, NULL }, "MAP", "138" },
	{ { NULL, NULL }, "IVI", "139" },
	{ { NULL, NULL }, "TLC", "140" },
	{ { NULL, NULL }, "GN-MGMT", "141" }
};

static cring_t _macro = { &_macro, &_macro };

static int _addMacro_option(const copt_t * opt, const char * option, const copt_value_t * value)
{
	macro_item * m;
	const char * n = value->v_str;
	char * v = strchr(n, ':');
	if (v){
		*(v++) = 0;
		if (0 == *v) v = NULL;
	}
	for (m = cring_first_cast(_macro, macro_item);
		&m->_ring != &_macro && !cstrequal(m->name, n);
		m = cring_next_cast(m, macro_item));
	if (&m->_ring == &_macro){
		m = cnew(macro_item);
		cring_init(&m->_ring);
		cring_enqueue(&_macro, &m->_ring);
		m->name = n;
	}
	m->value = v;
	return 0;
}

static const char * macro_lookup(const char* n)
{
	macro_item * m;
	for (m = cring_first_cast(_macro, macro_item);
		&m->_ring != &_macro;
		m = cring_next_cast(m, macro_item)) {
		if (cstrequal(m->name, n)){
			return m->value;
		}
	}
	return NULL;
}

367 368 369 370 371 372 373 374 375 376 377
static const char * _o_formats[] = {
	"bin", "hex", "pem", NULL
};

static copt_t options [] = {
	{ "h?", "help", COPT_HELP, NULL,                 "Print this help page" },
	{ "C", "config", COPT_CFGFILE, (void*)&_cfgFile, "Config file path [no cfg file]" },
	{ "o", "out", COPT_STR, (void*)&_outPath, "Output path [current dir by default]" },
	{ "O", "format", COPT_STRENUM, (void*)_o_formats, "Output format (bin|hex|pem)[binary by default]" },
	{ "S", "certs", COPT_STR, (void*)&_searchPath, "Certificates search path [Output path by default]" },
	{ "K", "keys",  COPT_STR,  (void*)&_keyPath,    "Private key storage path [Output path by default]" },
378 379
	{ "R", "reuse", COPT_BOOL, (void*)&_reuseKeys, "Reuse existing key pair [regenerate by default]" },
	{ "f", "force", COPT_BOOL, (void*)&_force, "Force regenerate existing certificate and keys" },
380 381 382 383 384 385
	{ "n", "name", COPT_STR, (void*)&_certName, "Certificate name (take from profile by default)" },
	{ "v", "vkey", COPT_STR, (void*)&_verificationKey, "Verification public key (generate key pair by default)" },
	{ "e", "ekey", COPT_STR, (void*)&_decriptionKey, "Decription public key (generate key pair if neccessary)" },
	{ "s", "signer", COPT_STR, (void*)&_signerName, "Signer certificate name [take from profile by default]" },
	{ "t", "reftime",     COPT_STR | COPT_CALLBACK, (void*)&_time_option, "Reference UTC time point (YYY-DD-MM) [current date]" },
	{ "l", "reflocation", COPT_STR | COPT_CALLBACK, (void*)&_refPoint_option, "Reference location in form <lat>:<lon> [0.0:0.0]" },
386
	{ "m", "macro", COPT_STR | COPT_CALLBACK, (void*)&_addMacro_option, "Add macro in form of name:value to process AID, SSP, etc." },
387 388 389 390 391 392 393 394 395 396 397 398
	{ NULL, NULL,     COPT_END,  NULL, NULL }
};

int main(int argc, char ** argv)
{
	FILE *f;
	int rc;

	cert_cxml_handler_t * h = cxml_st_handler_new(&Class, h_root);
	h->vr_type = -1;
	h->sa_type = -1;
	
399 400
	// set default time to the begining of this year
	_setup_default_time();
401 402 403 404 405 406

	// init default macroses
	for (rc = 0; rc < sizeof(_default_macro) / sizeof(_default_macro[0]); rc++){
		cring_enqueue(&_macro, &_default_macro[rc]._ring);
	}

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
	argc = coptions(argc, argv, COPT_HELP_NOVALUES , options);

    if(argc < 2){
		if(argc<0 && (0-argc)<((sizeof(options)/sizeof(options[0]))-1)){
			printf("Unknown option %s\n", argv[0-argc]);
		}
		const char * a = strrchr(argv[0], '/');
		if (a == NULL) a = argv[0];
		coptions_help(stdout, a, COPT_HELP_NOVALUES, options, "<profile> [signer]");
		return -1;
    }

	if (_searchPath == NULL) _searchPath = _outPath;
	if (_keyPath == NULL)    _keyPath    = _outPath;
	_outFormat = copts_enum_value(options, 3, _o_formats);
	if (_defaultTime == 0){
		//set it to begining of this year
		time_t t = time(NULL);
		struct tm tm;
		struct tm * ptm = gmtime(&t);
		memcpy(&tm, ptm, sizeof(tm));
		tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
		tm.tm_mday = 1; tm.tm_mon = 0;
		_defaultTime = mkitstime32(&tm);
	}

	if(argc > 2){
		// set signer certificate file name
		_signerName = argv[2];
	}

    f = fopen(argv[1], "rb");
	if(f == NULL){
		fprintf(stderr, "%s: Certificate profile not found\n", argv[1]);
		return -1;
	}else{
		
		if(ecc_api_init()){
			return -1;
		}

		_profileName = cstrdup(cstrlastpathelement(argv[1]));
		if(_profileName){
			char * p = strrchr(_profileName, '.');
			if(p) *p = 0;
		}

		rc = cxml_handler_parse_stream(&h->h, f);
		if (rc == -1){
			fprintf(stderr, "%s Profile parsing error\n", argv[1]);
			return -1;
		}
		fclose(f);

		ecc_api_done();
	}
	return 0;
}

static int root_certificate_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		if(_certName == NULL){
			_certName = cxml_tag_attr_value(tag, "name");
			if(_certName == NULL){
				_certName = _profileName;
			}
filatov's avatar
filatov committed
475 476 477
			else if (!cstrequal(_certName, _profileName)){
				fprintf(stderr, "WARNING: %s.xml: profile name differs from certificate name '%s'\n", _profileName, _certName);
			}
478 479 480
		}
		h->ptr = h->buf = malloc(4096);
		h->end = h->buf + 4096;
481
		if (!_force && cxml_tag_attr_boolean(tag, "keep-existing")){
482 483 484 485 486 487 488 489 490 491 492 493
			FILE * f;
			char * path = h->ptr;
			cvstrncpy(path, h->end - path, _outPath, "/", _certName, ".crt", NULL);
			f = fopen(path, "r+b");
			if (f){
				fclose(f);
				free(h->buf);
				return CXML_RETURN_STOP;
			}
		}
	}else{
		FILE * f;
494 495 496
		char * path;
		path = h->ptr;
		cvstrncpy(path, h->end-path, _outPath, "/", _certName, ".crt", NULL);
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
		f = fopen(path, "wb");
		if (!f){
			fprintf(stderr, "ERROR: Certificate write failed to '%s'\n", path);
		}else{
			if (_outFormat == 0){ 
				fwrite(h->buf, 1, h->ptr - h->buf, f);
			}else{ // hex or pem format
				const unsigned char * p = (const unsigned char *)h->buf;
				for (; p < (const unsigned char *)h->ptr; p++){
					fprintf(f, "%02X", *p);
				}
			}
			fclose(f);
		}
		if (h->verificationKey){
			if (_verificationKey == NULL && _reuseKeys == 0){
				cvstrncpy(path, h->end - path, _keyPath, "/", _certName, ".vkey", NULL);
				ecc_api_key_private_save(h->verificationKey, path, _outFormat);
				cvstrncpy(path, h->end - path, _keyPath, "/", _certName, ".vpkey", NULL);
				ecc_api_key_public_save(h->verificationKey, path, _outFormat);
			}
		}
		if (h->encryptionKey){
			if (_decriptionKey == NULL && _reuseKeys == 0){
				cvstrncpy(path, h->end - path, _keyPath, "/", _certName, ".ekey", NULL);
				ecc_api_key_private_save(h->encryptionKey, path, _outFormat);
				cvstrncpy(path, h->end - path, _keyPath, "/", _certName, ".epkey", NULL);
				ecc_api_key_public_save(h->encryptionKey, path, _outFormat);
			}
		}
		free(h->buf);
	}
	return 0;
}

static int certificate_version_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		h->nTmpValue = 2;
		const char * v = cxml_tag_attr_value(tag, "version");
		if(v == NULL)v = cxml_tag_attr_value(tag, "value");
		if(v){
541
			while(cisspace(*v))v++;
542 543 544 545 546 547 548 549 550 551 552 553 554
			h->nTmpValue = strtoul(v, NULL, 0);
		}
	}else{
		cint8_write(h->nTmpValue, &h->ptr, h->end, &rc);
	}
	return rc;
}

static int certificate_version_text(cxml_handler_t* const _h, char * const text, int length)
{
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if(text){
		const char * p = text;
555
		while(*p && cisspace(*p))p++;
556 557 558 559 560 561 562 563 564
		if(*p) h->nTmpValue = strtoul(p, NULL, 0);
	}
	return 0;
}

static const char * _signer_types [] = {
	"self",
	"digest",
	"certificate",
filatov's avatar
filatov committed
565 566
	"certificate_chain",
	"other_digest",
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
	"other",
};

static size_t load_certificate(const char * path, char * ptr, const char * e)
{
	FILE *f;
	size_t size;
	char * cert = ptr;

	f = fopen(path, "rb");
	if (f == NULL){
		perror(path);
		return -1;
	}
	fseek(f, 0, SEEK_END);
	size = ftell(f);
	fseek(f, 0, SEEK_SET);
	if (size < 67){
		fprintf(stderr, "%s: File too small\n", path);
		return -1;
	}
588
	if (size > (size_t)(e - cert)){
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
		fprintf(stderr, "%s: no enough space\n", path);
		return -1;
	}
	if (size != fread(cert, 1, size, f)){
		perror(path);
		return -1;
	}
	fclose(f);
	if (cert[0] != 2) {
		char * c = cstr_hex2bin(cert, size, cert, size);
		if (c){
			size = c - cert;
		}
	}
	return size;
}

filatov's avatar
filatov committed
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
static const char * _pk_algorithms[] = {
	[0] = "ecdsa_nistp256_with_sha256",
	[1] = "ecies_nistp256",
};

static const char * _sym_algorithms[] = {
	[0] = "aes_128_ccm",
};
static const char * _point_types[] = {
	[0] = "x_coordinate_only",
	[1] = "compressed",
	[2] = "compressed_y0",
	[3] = "compressed_y1",
	[4] = "uncompressed"
};

622 623 624
static int certificate_signer_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
filatov's avatar
filatov committed
625
	const char * v;
626 627 628
	// write signer info
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
filatov's avatar
filatov committed
629 630
		h->signer_type = si_digest; // digest by default
		v = cxml_tag_attr_value(tag, "type");
631 632
		if(v){
			h->signer_type = STR2ENUM(_signer_types, v);
filatov's avatar
filatov committed
633
			if (h->signer_type <0){
634 635 636 637 638 639
				fprintf(stderr, "%s: Unknown signer type\n", v);
				return -1;
			}
		}
		cint8_write(h->signer_type, &h->ptr, h->end, &rc);

filatov's avatar
filatov committed
640
		if (h->signer_type > si_self){
641 642 643 644
			if (_signerName){
				h->signer = _signerName;
			}
			else{
filatov's avatar
filatov committed
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
				if (h->signer_type == si_digest || h->signer_type == si_digest_with_other_algorithm){
					h->signer_digest = cxml_tag_attr_value(tag, "digest");
					if (h->signer_type == si_digest_with_other_algorithm){
						int alg;
						v = cxml_tag_attr_value(tag, "algorithm");
						if (v == NULL) {
							fprintf(stderr, "Signing algorithm shall be provided\n");
							return -1;
						}
						alg = STR2ENUM(_pk_algorithms, v);
						if (alg < 0){
							fprintf(stderr, "%s: Unknown public key algorithm\n", v);
							return -1;
						}
						cint8_write(alg, &h->ptr, h->end, &rc);
					}
				}
				if (h->signer_digest == NULL){
					v = cxml_tag_attr_value(tag, "name");
					if (v == NULL){
						fprintf(stderr, "%s: Signer name or digest shall be provided\n", v);
						return -1;
					}
					h->signer = v;
669
				}
filatov's avatar
filatov committed
670 671 672 673
			}
			if (h->signer_type == si_certificate_chain ||
				h->signer_type >= si_other){
				bookmark_position(h, tag);
674 675 676 677
			}
		}
	}else{
		// write signer info
filatov's avatar
filatov committed
678 679 680 681 682 683 684 685 686
		if (h->signer_type > si_self){
			if (h->signer_type < si_other) {
				if (h->signer_digest){
					int len = strlen(h->signer_digest);
					v = cstr_hex2bin(h->ptr, h->end - h->ptr, h->signer_digest, len);
					if (v == NULL){
						fprintf(stderr, "%s: no more space to write digest of size %d bytes\n", v, len);
						return -1;
					}
687 688
				}
				else{
filatov's avatar
filatov committed
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
					char * path, *cname;
					int plen;
					cname = (char*)h->signer;
					while (*cname){
						char * se = strchr(cname, ' ');
						if (se){
							*se = 0;
							while (cisspace(*se))se++;
						}
						else se = cstrend(cname);
						h->signer = cname;

						// load signer certificate
						plen = strlen(_searchPath) + (se - cname);
						path = malloc(plen + 16);
						cvstrncpy(path, plen + 16, _searchPath, "/", cname, ".crt", NULL);
						size_t size = load_certificate(path, h->ptr, h->end);
						if (size < 0){
							fprintf(stderr, "%s: signer certificate not found or error\n", h->signer);
							rc = -1;
						}
						else{
							// digests
							if (h->signer_type == si_digest || h->signer_type == si_digest_with_other_algorithm){
								char hash[sha256_hash_size];
								// change eccpoint type of the signature to x_coordinate_only(0) 
								// to follow canonical encoding
								h->ptr[size - 65] = 0;
								sha256_calculate(hash, h->ptr, size);
718
#ifdef DEBUG_DATA
filatov's avatar
filatov committed
719 720 721 722 723 724
								fprintf(stderr, "HASH (%s): ", h->signer);
								print_x(stderr, hash, sha256_hash_size);
								fprintf(stderr, "\n");
								fprintf(stderr, "DIGEST (%s): ", h->signer);
								print_x(stderr, &hash[sha256_hash_size - 8], 8);
								fprintf(stderr, "\n");
725
#endif
filatov's avatar
filatov committed
726 727 728 729 730 731 732 733 734 735 736 737
								cbuf_write(hash + sha256_hash_size - 8, 8, &h->ptr, h->end, &rc);
							}
							else {// certificate or chain
								h->ptr += size;
								if (h->signer_type == si_certificate_chain){
									cname = se;
									continue;
								}
							}
						}
						// continue only if certificate chain
						break;
738
					}
filatov's avatar
filatov committed
739
					free(path);
740
				}
filatov's avatar
filatov committed
741 742 743
			}
			if (h->signer_type == si_certificate_chain || h->signer_type >= si_other) {
				apply_bookmark_size(h, tag);
744 745 746 747 748 749
			}
		}
	}
	return rc;
}

filatov's avatar
filatov committed
750 751 752 753 754 755 756 757 758
static int certificate_signer_text(cxml_handler_t* const _h, char * const text, int length)
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (h->signer_type >= si_other) {
		cbuf_write(text, length, &h->ptr, h->end, &rc);
	}
	return rc;
}
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018

static const char * _subject_type [] = {
	"EC",	"AT",	"AA",	"EA",	"ROOT",	"CRL"
};

typedef struct list_pointer_t
{
	unsigned char * ptr;
	unsigned char cnt;
}list_pointer_t;

static int certificate_subject_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	// write signer info
	if (cxml_tag_is_open(tag)){
		int len;
		const char * v = cxml_tag_attr_value(tag, "type");
		if(v == NULL){
			fprintf(stderr, "Subject type must be set in Certificate profile\n");
			return -1;
		}
		h->subject_type = STR2ENUM(_subject_type, v);
		if(h->subject_type < 0) {
			fprintf(stderr, "%s: Unknown subject type\n", v);
			return -1;
		}
		cint8_write(h->subject_type, &h->ptr, h->end, &rc);
		v  = cxml_tag_attr_value(tag, "name");
		len = cstrlen(v);
		if(0 == cintx_write(len, &h->ptr, h->end, &rc) && len > 0){
			cbuf_write(v, len, &h->ptr, h->end, &rc);
		}
		bookmark_position(h, tag);
	}else{
		apply_bookmark_size(h, tag);
	}
	return rc;
}

static const char * _subject_attribute_types[] = {
	[0]  = "verification_key",
	[1]  = "encryption_key",
	[2]  = "assurance_level",
	[3]  = "reconstruction_value",
	[32] = "its_aid_list",
	[33] = "its_aid_ssp_list"
};

static int subject_attribute_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		const char * v = cxml_tag_attr_value(tag, "type");
		int atype;
		if(v == NULL){
			fprintf(stderr, "Attribute type must be set\n");
			return -1;
		}
		atype = STR2ENUM(_subject_attribute_types, v);
		if(atype < 0) {
			fprintf(stderr, "%s: Unknown attribute type\n", v);
			return -1;
		}
		cint8_write(atype, &h->ptr, h->end, &rc);
		h->sa_type = atype;

		const char * keyPath = _verificationKey;
		switch (h->sa_type){
		case  1: // encryption_key
			keyPath = _decriptionKey;
		case  0: //verificationKey
			if (keyPath){
				h->key = ecc_api_key_public_load(keyPath, 0);
				if (h->key == NULL){
					fprintf(stderr, "%s: Can't load public key\n", keyPath);
					return -1;
				}
			}
			else if (_reuseKeys){
				cvstrncpy(h->ptr, h->end - h->ptr, _keyPath, "/", _certName,
					".", h->sa_type ? "e" : "v", "key", NULL);
				h->key = ecc_api_key_private_load(h->ptr, 0);
				if (h->key == NULL){
					_reuseKeys = 0;
				}
			}
			break;
		case 32: //its_aid_list
		case 33: //its_aid_ssp_list
			bookmark_position(h, tag);
			break;
		};
	}else{
		switch(h->sa_type){
		case  0: // verification_key
			h->verificationKey = h->key;
			h->key = NULL;
			break;
		case  1: // encryption_key
			h->encryptionKey = h->key;
			h->key = NULL;
			break;
		case 32: //its_aid_list
		case 33: //its_aid_ssp_list
			apply_bookmark_size(h, tag);
			break;
		}
		if(h->key){
			ecc_api_key_free(h->key);
		}
		h->sa_type = -1;
	}
	return rc;
}

static int attribute_public_key_tag(cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		int alg = 0, sym_alg = 0;
		const char * v = cxml_tag_attr_value(tag, "algorithm");
		if (v) {
			alg = STR2ENUM(_pk_algorithms, v);
			if (alg < 0){
				fprintf(stderr, "%s: Unknown public key algorithm\n", v);
				return -1;
			}
		}
		cint8_write(alg, &h->ptr, h->end, &rc);

		v = cxml_tag_attr_value(tag, "point-type");
		if (v){
			h->pk_ptype = STR2ENUM(_point_types, v);
			if (h->pk_ptype < 0){
				fprintf(stderr, "%s: Unknown point type\n", v);
				return -1;
			}
			if (h->pk_ptype == 1) h->pk_ptype = 2;
		}

		switch (alg){
		case 0:
			break;
		case 1:
			v = cxml_tag_attr_value(tag, "sym_alg");
			if (v){
				sym_alg = STR2ENUM(_sym_algorithms, v);
				if (sym_alg < 0){
					fprintf(stderr, "%s: Unknown symmetric algorithm\n", v);
					return -1;
				}
			}
			cint8_write(sym_alg, &h->ptr, h->end, &rc);
			break;
		default:
			bookmark_position(h, tag);
			break;
		}
		h->pk_alg = alg;
		h->pk_sym_alg = sym_alg;
	}
	else{
		if (h->pk_alg > 1){
			apply_bookmark_size(h, tag);
		}
		h->pk_alg = -1;
		h->pk_sym_alg = -1;
	}
	return rc;
}

static int attribute_eccpoint_tag   (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	int pointtype;
	if (cxml_tag_is_open(tag)){
		const char * v;
		pointtype = 0;
		v = cxml_tag_attr_value(tag, "type");
		if (v){
			pointtype = STR2ENUM(_point_types, v);
			if (pointtype < 0){
				fprintf(stderr, "%s: Unknown point type\n", v);
				return -1;
			}
			if (pointtype == 1) pointtype = 2;
		}
		h->pk_ptype = pointtype;
		h->pk_data = NULL;
		h->pk_datasize = 0;

	}
	else{
		void * key = h->key;
		pointtype = h->pk_ptype;
		// generate private and public key pair
		char x[32], y[32];
		if (key == NULL){
			if (h->pk_data){
				if (h->pk_datasize < 32 || (h->pk_datasize < 64 && pointtype == 4)){
					fprintf(stderr, "Insufficient size of public key\n");
					return -1;
				}
				key = ecc_api_key_public_set(h->pk_alg, pointtype, h->pk_data, h->pk_data + 32);
			}
			else{
				// generate PK
				if (h->pk_alg < 0 || h->pk_sym_alg < 0){
					fprintf(stderr, "Public key algorythm must be specified\n");
					return -1;
				}
				key = ecc_api_key_gen(h->pk_alg, h->pk_sym_alg);
			}
		}
		if (key){
			h->key = key;
			rc = ecc_api_key_public(key, &x[0], &y[0]);
			if (rc >= 0){
				if (pointtype == 2) pointtype |= (y[31] & 1);
				cint8_write(pointtype, &h->ptr, h->end, &rc);
				if (rc == 0)cbuf_write(&x[0], 32, &h->ptr, h->end, &rc);
				if (rc == 0 && pointtype == 4){
					cbuf_write(&y[0], 32, &h->ptr, h->end, &rc);
				}
			}
		}
		if (h->pk_data){
			free(h->pk_data);
			h->pk_data = NULL;
		}
	}
	return rc;
}

static int attribute_eccpoint_text(cxml_handler_t* const _h, char * const text, int length)
{
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (h->pk_data == NULL){
		h->pk_data = malloc(64);
		h->pk_datasize = 0;
	}
	char * e = cstr_hex2bin(h->pk_data + h->pk_datasize, 64 - h->pk_datasize, text, length);
	h->pk_datasize = e - h->pk_data;
	return 0;
}


static int attribute_assurance_tag  (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		uint8_t assurance = 0;
		const char * v = cxml_tag_attr_value(tag, "level");
		if(v){
1019
			while(*v && cisspace(*v))v++;
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
			if(*v){
				long n = strtol(v, NULL, 0); 
				if(n<0 || n > 7){
					fprintf(stderr, "%s: Invalid assurance level\n", v);
					return -1;
				}
				assurance |= n<<5;
			}
		}
		v = cxml_tag_attr_value(tag, "confidence");
		if(v){
1031
			while(*v && cisspace(*v))v++;
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
			if(*v){
				long n = strtol(v, NULL, 0); 
				if(n<0 || n > 3){
					fprintf(stderr, "%s: Invalid assurance confidence\n", v);
					return -1;
				}
				assurance |= n;
			}
		}
		cint8_write(assurance, &h->ptr, h->end, &rc);
	}
	return rc;
}

1046
static int attribute_aid_tag(cxml_handler_t* const _h, cxml_tag_t * const tag)
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if(0 == (tag->type & CXML_TAG_OPEN)){
		const char * v = cxml_tag_attr_value(tag, "value");
		if(NULL == v)v = cxml_tag_attr_value(tag, "aid");
		if(NULL == v){
			fprintf(stderr, "WARNING: Value required for AID tag. Item was skiped.\n");
		}else{
			uint32_t n;
1057
			while(cisspace(*v))v++;
1058 1059 1060 1061 1062 1063 1064 1065
			if (!cisdigit(*v)){
				// look in the aid map
				const char * v1 = macro_lookup(v);
				if (!v1){
					fprintf(stderr, "ERROR: Invalid AID '%s'\n", v);
					return -1;
				}
				v = v1;
1066
			}
1067 1068
			n = strtoul(v, NULL, 0);
			cintx_write(n, &h->ptr, h->end, &rc);
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
		}
	}
	return rc;
}

static int attribute_ssp_tag        (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		uint32_t n;
		const char * v = cxml_tag_attr_value(tag, "aid");
		if(NULL == v){
			fprintf(stderr, "ERROR: AID shall be supplied for SSP.\n");
			return -1;
		}
1085
		while(cisspace(*v))v++;
1086 1087 1088 1089 1090 1091 1092 1093
		if (!cisdigit(*v)){
			// look in the aid map
			const char * v1 = macro_lookup(v);
			if (!v1){
				fprintf(stderr, "ERROR: Invalid AID '%s' in SSP\n", v);
				return -1;
			}
			v = v1;
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
		}
		n = strtoul(v, NULL, 0);
		cintx_write(n, &h->ptr, h->end, &rc);
		bookmark_position(h, tag);
	}else{
		apply_bookmark_size(h, tag);
	}
	return rc;
}

static int attribute_ssp_text(cxml_handler_t* const _h, char * const text, int length)
{
	int rc=0;
1107
	if (text && length){
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
		cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
		rc = cbuf_write(text, length, &h->ptr, h->end, NULL);
	}
	return rc;
}

static int certificate_validity_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		bookmark_position(h, tag);
		rc = 0;
	}else{
		rc = apply_bookmark_size(h, tag);
	}
	return rc;
}

filatov's avatar
filatov committed
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
static unsigned int _convert_diff_time(const char * v)
{
	unsigned int ret = 0;
	const char * p = v;
	char * e;
	int mult = 1;
	switch (*p){
	case '-':
		mult = -1;
	case '+':
		p++;
	}

	for (;;){
		unsigned int n;
		n = strtoul(p, &e, 10);
		if (n == ULONG_MAX) break;
		if (cisalnum(*e)){
			switch (*e){
			case 'd': n *= 24;
			case 'h': n *= 60;
			case 'm': n *= 60;
			case 's': e++; break;
			default:
				fprintf(stderr, "%s: Unknown time modificator: '%c'\n", p, *e);
				return INT32_MIN;
			}
		}
		else{
			// consider n as days
			n *= 24 * 3600;
		}
		ret += n;
		if (cisdigit(*e)){
			p = e;
			continue;
		}
		break;
	}
	return ret * mult;
}

static unsigned int _convert_time2(const char * v, unsigned int baseTime)
1170 1171 1172 1173 1174
{
	unsigned int ret;
	char * e;
	struct tm tm;
	
1175
	// can be a difference from the base time point
filatov's avatar
filatov committed
1176 1177
	if (*v == '-' || *v == '+'){
		if (baseTime == 0){
1178 1179 1180
			fprintf(stderr, "Default time must be set\n");
			return 0;
		}
filatov's avatar
filatov committed
1181 1182 1183 1184
		ret = _convert_diff_time(v);
		if (ret == INT32_MIN)
			return 0;
		ret = baseTime + ret;
1185 1186 1187 1188 1189 1190 1191
	}
	else{
		// next try load as integer seconds since epoch
		ret = strtoul(v, &e, 0);
		if (ret == ULONG_MAX || *e){
			ret = 0;
			memset(&tm, 0, sizeof(tm));
filatov's avatar
filatov committed
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
			// check predefined values
			if ((e = cstrisprefix(v, "today"))){
				time_t t;
				struct tm * ptm;
				time(&t); ptm = gmtime(&t);
				tm.tm_year = ptm->tm_year; tm.tm_mon = ptm->tm_mon; tm.tm_mday = ptm->tm_mday;
			}
			else if ((e = cstrisprefix(v, "ybegin"))){
				time_t t;
				struct tm * ptm;
				time(&t); ptm = gmtime(&t);
				tm.tm_year = ptm->tm_year; tm.tm_mon = 0; tm.tm_mday = 1;
			}
			else if ((e = cstrisprefix(v, "yend"))){
				time_t t;
				struct tm * ptm;
				time(&t); ptm = gmtime(&t);
				tm.tm_year = ptm->tm_year+1; tm.tm_mon = 0; tm.tm_mday = 1;
			}
			//next try to convert ISO text representation
			else if (3 == sscanf(v, "%d-%d-%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday)){
1213
				tm.tm_mon--; // STARTED FROM 0
filatov's avatar
filatov committed
1214
				if (tm.tm_year > 500)
1215
					tm.tm_year -= 1900;
filatov's avatar
filatov committed
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
				e = (char*)v; // to prevent next check for '-/+'
			}
			else{
				fprintf(stderr, "%s: Date format specification error. Use YYY-MM-DD or today+/-NNNd\n", v);
				return 0;
			}
			ret = mkitstime32(&tm);
			if (ret == (time_t)-1) {
				fprintf(stderr, "%s: Date format specification error. Use YYY-MM-DD or today+/-NNNd\n", v);
				ret = 0;
			}
			if (*e == '-' || *e == '+'){
				ret = _convert_time2(e, ret);
1229 1230 1231 1232 1233 1234
			}
		}
	}
	return ret;
}

filatov's avatar
filatov committed
1235 1236 1237 1238 1239
static unsigned int _convert_time(const char * v)
{
	return _convert_time2(v, _defaultTime);
}

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
static int validity_restriction_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		int vr_type = -1;
		int nTime;
		const char * v = cxml_tag_attr_value(tag, "type");
		const char *start, *end, *duration;
		if(NULL == v){
			fprintf(stderr, "ERROR: Restriction shall have a type.\n");
			return -1;
		}
		
1254
		while(cisspace(*v))v++;
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
		if(0 == strcmp("time", v)){
			start    = cxml_tag_attr_value(tag, "start");
			end      = cxml_tag_attr_value(tag, "end");
			duration = cxml_tag_attr_value(tag, "duration");
			if(end && *end){
				vr_type = (start && *start) ? 1 : 0;
			}else if(start && *start && duration && *duration){
				vr_type = 2;
			}else{
				fprintf(stderr, "ERROR: Either end or start and duration shall be specified for time restriction.\n");
				return -1;
			}
		}else if(0 == strcmp("region", v)){
			vr_type = 3;
1269
		}else if(cisdigit(*v)){
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
			vr_type=strtoul(v, NULL,0);
		}else{
			fprintf(stderr, "%s: Unknown validity restriction type.\n", v);
			return -1;
		}
		h->vr_type = vr_type;
		cint8_write(vr_type, &h->ptr, h->end, &rc);
		
		// save time restrictions
		switch(vr_type){
		case 1: /* time_start_and_end */
			nTime = _convert_time(start);
			cint32_write(nTime, &h->ptr, h->end, &rc);
		case 0: /* time_end */
			nTime = _convert_time(end);
			cint32_write(nTime, &h->ptr, h->end, &rc);
			break;
		case 2: /* time_start_and_duration */
			nTime = _convert_time(start);
			cint32_write(nTime, &h->ptr, h->end, &rc);
filatov's avatar
filatov committed
1290
			nTime = _convert_diff_time(duration);
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
			cint32_write(nTime, &h->ptr, h->end, &rc);
			break;
		case 3: /* region */
			break;
		default: // opaque
			bookmark_position(h, tag); // for opaque data
		}
	}else{
		if(h->vr_type > 3){
			apply_bookmark_size(h, tag);
		}
		h->vr_type = -1;
	}
	return 0;
}
static int region_none_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	if (cxml_tag_is_open(tag)){
		cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
		return cint8_write(0, &h->ptr, h->end, NULL);
	}
	return 0;
}

static int region_circle_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		//region type
		if(0 == cint8_write(1, &h->ptr, h->end, NULL)){
			//latitude and longitude
			rc = location_tag (_h, tag);
			if(0 == rc){
				//radius
				uint32_t n;
1327
				char * e;
1328 1329 1330 1331 1332
				const char * v    = cxml_tag_attr_value(tag, "radius");
				if(NULL == v){
					fprintf(stderr, "ERROR: radius shall be specified for circle.\n");
					return -1;
				}
1333 1334 1335
				n = strtoul(v, &e, 0);
				if( (e[0] == 'k' || e[0] == 'K') && (e[1] == 'm' || e[1] == 'M') )
					n *= 1000;
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
				if(n > 0xFFFF){
					fprintf(stderr, "ERROR: %ul: radius is too big.\n", n);
					return -1;
				}
				cint16_write(n, &h->ptr, h->end, &rc);
			}
		}
	}
	return rc;
}

static int region_rectangle_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		// region type
		rc = cint8_write(2, &h->ptr, h->end, NULL);
		if(0 == rc){
			bookmark_position(h, tag);
		}
	}else{
		rc = apply_bookmark_size(h, tag);
	}
	return rc;
}

static int region_polygon_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		// region type
		rc = cint8_write(3, &h->ptr, h->end, NULL);
		if(0 == rc){
			bookmark_position(h, tag);
		}
	}else{
		rc = apply_bookmark_size(h, tag);
	}
	return rc;
}

static int location_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
	if (cxml_tag_is_open(tag)){
filatov's avatar
filatov committed
1383
		int32_t lat, lon, absolute = 0;
1384
		long double d;
1385
		char * e;
1386
		cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
filatov's avatar
filatov committed
1387 1388 1389 1390 1391 1392

		const char * v = cxml_tag_attr_value(tag, "mode");
		absolute = cstrequal(v, "absolute");
			
		v = cxml_tag_attr_value(tag, "latitude");
		int relative = 1;
1393
		if(v == NULL){
filatov's avatar
filatov committed
1394
			fprintf(stderr, "ERROR: Latitude must be specified for location.\n");
1395 1396
			return -1;
		}
1397 1398 1399 1400 1401 1402 1403
		e = NULL; d = strtold(v, &e);
		if(e[0] == 'm' || (e[0] == 'k' && e[1] == 'm')){
			if(e[0] == 'k') d*=1000.0;
			d = d * _latTMDPerMetter;
		}else{
			if (d <= 90.0 &&  d >= -90.0) d *= 10000000.0; // degree
		}
filatov's avatar
filatov committed
1404 1405
		if (!absolute) d += _refLat;
		lat = (int32_t)floorl(d);
1406 1407 1408 1409 1410 1411

		v    = cxml_tag_attr_value(tag, "longitude");
		if(v == NULL){
			fprintf(stderr, "ERROR: Longitude shall be specified for location.\n");
			return -1;
		}
1412 1413 1414 1415 1416 1417 1418 1419
		e = NULL; d = strtold(v, &e);
		if(e[0] == 'm' || (e[0] == 'k' && e[1] == 'm')){
			if(e[0] == 'k') d*=1000.0;
			// convert metters to degree
			d = d * _lonTMDPerMetter;
		}else{
			if (d <= 180.0 &&  d >= -180.0) d *= 10000000.0; // degree
		}
filatov's avatar
filatov committed
1420 1421
		if (!absolute) d += _refLon;
		lon = (int32_t)floorl(d);
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464

		cint32_write(lat, &h->ptr, h->end, &rc);
		cint32_write(lon, &h->ptr, h->end, &rc);
	}
	return rc;
}

static const char * _id_dictionaries[] = {
	"iso_3166_1",
	"un_stats",
};

static int region_id_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		int value = 0;
		unsigned int uvalue = 0;
		const char * v;

		// region type
		rc = cint8_write(4, &h->ptr, h->end, NULL);

		// region dictionary. use 0 by default
		v = cxml_tag_attr_value(tag, "dictionary");
		if(v == NULL)v = cxml_tag_attr_value(tag, "dict");
		if(v){
			value = STR2ENUM(_id_dictionaries, v);
			if(value<0){
				fprintf(stderr, "%s: Unknown dictionary type\n", v);
				return -1;
			}
		}
		if(cint8_write(value, &h->ptr, h->end, NULL)){
			return -1;
		}
			
		v = cxml_tag_attr_value(tag, "id");
		if(v == NULL){
			fprintf(stderr, "ERROR: Region identifier must be set\n");
			return -1;
		}
1465
		while(cisspace(*v))v++;
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
		uvalue = strtoul(v, NULL, 0);
		if(uvalue > 0xFFFF){
			fprintf(stderr, "%s: Invalid region identifier\n", v);
			return -1;
		}
		if(cint16_write(uvalue, &h->ptr, h->end, NULL)){
			return -1;
		}
			
		uvalue = 0;
		v = cxml_tag_attr_value(tag, "local");
		if(v){
1478
			while(cisspace(*v))v++;
1479
			uvalue = strtoul(v, NULL, 0);
1480
			if(!cisdigit(*v) || uvalue > 0xFFFF){
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
				fprintf(stderr, "%s: Invalid region identifier\n", v);
				return -1;
			}
		}
		cintx_write(uvalue, &h->ptr, h->end, &rc);
		if(rc) return -1;
	}
	return rc;
}

filatov's avatar
filatov committed
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
static const char * _region_types[] = {
	[0] = "none",
	[1] = "circle",
	[2] = "rectangle",
	[3] = "polygon",
	[4] = "id"
};
static cxml_tag_f* _region_type_handlers[] = {
	[0] = region_none_tag,
	[1] = region_circle_tag,
	[2] = region_rectangle_tag,
	[3] = region_polygon_tag,
	[4] = region_id_tag
};

static int region_region_tag(cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		const char * v;
		v = cxml_tag_attr_value(tag, "type");
		h->nTmpValue = STR2ENUM(_region_types, v);
		if (h->nTmpValue < 0){
			fprintf(stderr, "ERROR: unknown region type: %s\n", v);
			return -1;
		}
	}
	if (h->nTmpValue < sizeof(_region_type_handlers) / sizeof(_region_type_handlers[0])){
		return _region_type_handlers[h->nTmpValue](_h, tag);
	}

	if (cxml_tag_is_open(tag)){
		// region type
		rc = cint8_write(h->nTmpValue, &h->ptr, h->end, NULL);
		bookmark_position(h, tag);
	} else{
		apply_bookmark_size(h, tag);
	}
	return rc;
}

static int region_region_text(cxml_handler_t* const _h, char * const text, int length)
{
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	char * end;
	// try to treat it as hex
	end = cstr_hex2bin(h->ptr, h->end - h->ptr, text, length);
	if (end){
		h->ptr = end;
	}
	else{
		if (length > (h->end - h->ptr)){
			fprintf(stderr, "ERROR: region definition is tooooo big: %d bytes\n", length);
			return -1;
		}
		h->ptr = cmemcpy(h->ptr, text, length);
	}
	return 0;
}

1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
static const char * _signature_algorithms[] = {
	"ecdsa_nistp256_with_sha256",
};

static int certificate_signature_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
	int rc = 0;
	cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
	if (cxml_tag_is_open(tag)){
		void * key;
		int alg = 0;
		if(h->signer_type == 0){
			// self signed certificate
			key = h->verificationKey;
			if(!key){
				fprintf(stderr, "ERROR: Verification key attribute was not provided for self-signed certificate\n");
				return -1;
			}
		}else{
			const char * v = cxml_tag_attr_value(tag, "algorithm");
			if (v){
				alg = STR2ENUM(_signature_algorithms, v);
				if (alg < 0){
					fprintf(stderr, "%s: Unknown signature algorithm\n", v);
					return -1;
				}
			}

1580 1581 1582 1583 1584
			v = cxml_tag_attr_value(tag, "signer");
			if (v){
				h->signer = v;
			}

1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
			if (h->signer == NULL){
				fprintf(stderr, "ERROR: Signer certificate name shall be provided\n");
				return -1;
			}

			// load signer certificate
			int plen = strlen(_searchPath) + strlen(h->signer);
			char * path = malloc(plen + 16);

			cvstrncpy(path, plen + 16, _searchPath, "/", h->signer, ".vkey", NULL);
			key = ecc_api_key_private_load(path, alg);
			if (key == NULL){
				fprintf(stderr, "%s: Could not load issuing private key\n", path);
				free(path);
				return -1;
			}
		}
		cint8_write(alg, &h->ptr, h->end, &rc);
		rc = ecc_sign(key, h->buf, h->ptr - h->buf - 1, &h->ptr, h->end - h->ptr);
	}
	return rc;
}

static int  _Begin_Tag(cxml_handler_t* const h, cxml_tag_t * const tag)
{
	fprintf(stderr, "WARNING: %s: Unknown tag", tag->name);
	return 0;
}

static int  _End_Tag(cxml_handler_t* const h, cxml_tag_t * const tag)
{
	return 0;
}
static int  _Text(cxml_handler_t* const h, char * const text, int length)
{return 0;}