summaryrefslogtreecommitdiff
path: root/src/vcore/SignatureValidator.cpp
blob: a130bee9ed3bfc9c92555dfc0cfe5172b2473a0f (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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
/*
 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *    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.
 */
/*
 * @file        SignatureValidator.cpp
 * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
 * @author      Sangwan Kwon (sangwan.kwon@samsung.com)
 * @version     1.0
 * @brief       Implementatin of tizen signature validation protocol.
 */

#include <memory>
#include <string>
#include <utility>

#include <dpl/log/log.h>

#include <vcore/CertificateCollection.h>
#include <vcore/Certificate.h>
#include <vcore/ReferenceValidator.h>
#include <vcore/ValidatorFactories.h>
#include <vcore/XmlsecAdapter.h>
#include <vcore/SignatureReader.h>
#include <vcore/SignatureFinder.h>
#include <vcore/Ocsp.h>
#include <vcore/PluginHandler.h>

#include <vcore/SignatureValidator.h>

#ifdef TIZEN_PROFILE_MOBILE
#include <cchecker/ocsp.h>
#endif

using namespace ValidationCore::CertStoreId;

namespace {

const std::string TOKEN_PREFIX          = "http://www.w3.org/ns/widgets-digsig#";
const std::string TOKEN_ROLE_AUTHOR_URI = TOKEN_PREFIX + "role-author";
const std::string TOKEN_ROLE_DIST_URI   = TOKEN_PREFIX + "role-distributor";
const std::string TOKEN_PROFILE_URI     = TOKEN_PREFIX + "profile";

enum class CertTimeStatus : int {
	VALID,
	NOT_YET,
	EXPIRED
};

inline time_t _getMidTime(time_t lower, time_t upper)
{
	return (lower >> 1) + (upper >> 1);
}

inline CertTimeStatus _timeValidation(time_t lower, time_t upper, time_t current)
{
	if (current < lower)
		return CertTimeStatus::NOT_YET;
	else if (current > upper)
		return CertTimeStatus::EXPIRED;
	else
		return CertTimeStatus::VALID;
}

inline bool _isTimeStrict(const Set &stores)
{
	return (stores.contains(TIZEN_TEST) || stores.contains(TIZEN_VERIFY))
		   ? true : false;
}

} // namespace anonymous


namespace ValidationCore {

class SignatureValidator::Impl {
public:
	Impl(const SignatureFileInfo &info);
	virtual ~Impl() {};

	VCerr check(
		const std::string &contentPath,
		bool checkOcsp,
		bool checkReferences,
		SignatureData &outData);

	VCerr checkList(
		bool checkOcsp,
		const UriList &uriList,
		SignatureData &outData);

	VCerr makeChainBySignature(
		bool completeWithSystemCert,
		CertificateList &certList);

	std::string errorToString(VCerr code);

private:
	VCerr baseCheck(
		const std::string &contentPath,
		bool checkOcsp,
		bool checkReferences);

	VCerr baseCheckList(
		bool checkOcsp,
		const UriList &uriList);

	VCerr makeDataBySignature(bool completeWithSystemCert);
	VCerr additionalCheck(VCerr result);

	VCerr parseSignature(void);
	VCerr preStep(void);
	bool checkRoleURI(void);
	bool checkProfileURI(void);
	bool checkObjectReferences(void);

	PluginHandler m_pluginHandler;
	SignatureFileInfo m_fileInfo;
	XmlSec::XmlSecContext m_context;
	SignatureData m_data;
	bool m_disregarded;
};


SignatureValidator::Impl::Impl(const SignatureFileInfo &info) :
	m_fileInfo(info),
	m_disregarded(false)
{
}

bool SignatureValidator::Impl::checkRoleURI(void)
{
	std::string roleURI = m_data.getRoleURI();

	if (roleURI.empty()) {
		LogWarning("URI attribute in Role tag couldn't be empty.");
		return false;
	}

	if (roleURI != TOKEN_ROLE_AUTHOR_URI && m_data.isAuthorSignature()) {
		LogWarning("URI attribute in Role tag does not "
				   "match with signature filename.");
		return false;
	}

	if (roleURI != TOKEN_ROLE_DIST_URI && !m_data.isAuthorSignature()) {
		LogWarning("URI attribute in Role tag does not "
				   "match with signature filename.");
		return false;
	}

	return true;
}


bool SignatureValidator::Impl::checkProfileURI(void)
{
	if (TOKEN_PROFILE_URI != m_data.getProfileURI()) {
		LogWarning("Profile tag contains unsupported value "
				   "in URI attribute " << m_data.getProfileURI());
		return false;
	}

	return true;
}

bool SignatureValidator::Impl::checkObjectReferences(void)
{
	for (const auto &object : m_data.getObjectList()) {
		if (!m_data.containObjectReference(object)) {
			LogWarning("Signature does not contain reference for object " << object);
			return false;
		}
	}

	return true;
}

VCerr SignatureValidator::Impl::additionalCheck(VCerr result)
{
	try {
		if (m_pluginHandler.fail()) {
			LogInfo("No validator plugin found. Skip additional check.");
			return result;
		}

		return m_pluginHandler.step(result, m_data);
	} catch (...) {
		LogError("Exception in additional check by plugin.");
		return E_SIG_PLUGIN;
	}
}

VCerr SignatureValidator::Impl::parseSignature(void)
{
	try {
		SignatureReader xml;
		xml.initialize(m_data, SIGNATURE_SCHEMA_PATH);
		xml.read(m_data);
	} catch (ParserSchemaException::CertificateLoaderError &e) {
		LogError("Certificate loader error: " << e.DumpToString());
		return E_SIG_INVALID_CERT;
	} catch (...) {
		LogError("Failed to parse signature file by signature reader.");
		return E_SIG_INVALID_FORMAT;
	}

	return E_SIG_NONE;
}

/*
 *  Make SignatureData by parsing signature file.
 *  and get certificate chain with attached certificate in signature
 */
VCerr SignatureValidator::Impl::makeDataBySignature(bool completeWithSystemCert)
{
	LogDebug("Start to make chain.");
	m_data = SignatureData(m_fileInfo.getFileName(), m_fileInfo.getFileNumber());

	if (parseSignature()) {
		LogError("Failed to parse signature.");
		return E_SIG_INVALID_FORMAT;
	}

	if (!checkRoleURI() || !checkProfileURI())
		return E_SIG_INVALID_FORMAT;

	try {
		CertificateCollection collection;
		// Load Certificates and make chain.
		collection.load(m_data.getCertList());

		if (!collection.sort() || collection.empty()) {
			LogError("Certificates do not form valid chain.");
			return E_SIG_INVALID_CHAIN;
		}

		// Add root certificate to chain.
		if (completeWithSystemCert && !collection.completeCertificateChain()) {
			if (m_data.isAuthorSignature() || m_data.getSignatureNumber() == 1) {
				LogError("Failed to complete cert chain with system cert");
				return E_SIG_INVALID_CHAIN;
			} else {
				LogDebug("Distributor N's certificate has got "
						 "unrecognized root CA certificate.");
				m_disregarded = true;
			}
		}

		m_data.setSortedCertificateList(collection.getChain());
		LogDebug("Finish making chain successfully.");
	} catch (const CertificateCollection::Exception::Base &e) {
		LogError("CertificateCollection exception : " << e.DumpToString());
		return E_SIG_INVALID_CHAIN;
	} catch (const std::exception &e) {
		LogError("std exception occured : " << e.what());
		return E_SIG_UNKNOWN;
	} catch (...) {
		LogError("Unknown exception in SignatureValidator::makeChainBySignature");
		return E_SIG_UNKNOWN;
	}

	return E_SIG_NONE;
}

VCerr SignatureValidator::Impl::preStep(void)
{
	// Make chain process.
	VCerr result = makeDataBySignature(true);

	if (result != E_SIG_NONE)
		return result;

	for (const auto &certptr : m_data.getCertList()) {
		auto storeIdSet = createCertificateIdentifier().find(certptr);
		if (!storeIdSet.contains(TIZEN_REVOKED))
			continue;

		LogInfo("Revoked certificate: " << certptr->getOneLine());
		return E_SIG_REVOKED;
	}

	// Get Identifier from fingerprint original, extention file.
	LogDebug("Start to check certificate domain.");
	auto certificatePtr = m_data.getCertList().back();
	auto storeIdSet = createCertificateIdentifier().find(certificatePtr);

	// Check root CA certificate has proper domain.
	LogDebug("root certificate from " << storeIdSet.typeToString() << " domain");
	if (m_data.isAuthorSignature()) {
		if (!storeIdSet.contains(TIZEN_DEVELOPER)) {
			LogError("author-signature.xml's root certificate "
					 "isn't in tizen developer domain.");
			return E_SIG_INVALID_CHAIN;
		}
	} else {
		if (storeIdSet.contains(TIZEN_DEVELOPER)) {
			LogError("distributor signautre root certificate "
					 "shouldn't be in tizen developer domain.");
			return E_SIG_INVALID_CHAIN;
		}

		if (m_data.getSignatureNumber() == 1 && !storeIdSet.isContainsVis()) {
			LogError("signature1.xml has got unrecognized root CA certificate.");
			return E_SIG_INVALID_CHAIN;
		} else if (!storeIdSet.isContainsVis()) {
			LogDebug("signatureN.xml has got unrecognized root CA certificate.");
			m_disregarded = true;
		}
	}

	m_data.setStorageType(storeIdSet);
	LogDebug("Finish checking certificate domain.");
	/*
	 * We add only Root CA certificate because the rest
	 * of certificates are present in signature files ;-)
	 */
	m_context.signatureFile = m_data.getSignatureFileName();
	m_context.certificatePtr = m_data.getCertList().back();
	/* certificate time check */
	time_t lower = m_data.getEndEntityCertificatePtr()->getNotBefore();
	time_t upper = m_data.getEndEntityCertificatePtr()->getNotAfter();
	time_t current = time(NULL);
	CertTimeStatus status = _timeValidation(lower, upper, current);

	if (status != CertTimeStatus::VALID) {
		LogDebug("Certificate's time is invalid.");

		if (_isTimeStrict(storeIdSet))
			return status == CertTimeStatus::EXPIRED
				   ? E_SIG_CERT_EXPIRED : E_SIG_CERT_NOT_YET;

		time_t mid = _getMidTime(lower, upper);
		LogInfo("Use middle notBeforeTime and notAfterTime."
				" lower: " << lower
				<< " upper: " << upper
				<< " mid: " << mid
				<< " current: " << current);
		m_context.validationTime = mid;
	}

	return E_SIG_NONE;
}

VCerr SignatureValidator::Impl::baseCheck(
	const std::string &contentPath,
	bool checkOcsp,
	bool checkReferences)
{
	try {
		// Make certificate chain, check certificate info
		VCerr result = preStep();

		if (result != E_SIG_NONE)
			return result;

		// Since disregard case, uncheck root certs in signatureN.xml
		if (!m_data.isAuthorSignature() && m_data.getSignatureNumber() != 1)
			m_context.allowBrokenChain = true;

		// XmlSec validate
		XmlSecSingleton::Instance().validate(m_context);
		// Check reference of 'Object' tag - OID
		m_data.setReference(m_context.referenceSet);

		if (!checkObjectReferences()) {
			LogWarning("Failed to check Object References");
			return E_SIG_INVALID_REF;
		}

		// Check reference's existence
		if (checkReferences) {
			ReferenceValidator fileValidator(contentPath);

			if (ReferenceValidator::NO_ERROR != fileValidator.checkReferences(m_data)) {
				LogWarning("Invalid package - file references broken");
				return E_SIG_INVALID_REF;
			}
		}

		// Check OCSP
		if (checkOcsp && Ocsp::check(m_data) == Ocsp::Result::REVOKED) {
			LogError("Certificate is Revoked by OCSP server.");
			return E_SIG_REVOKED;
		}

		LogDebug("Signature validation check done successfully ");
	} catch (const CertificateCollection::Exception::Base &e) {
		LogError("CertificateCollection exception : " << e.DumpToString());
		return E_SIG_INVALID_CHAIN;
	} catch (const XmlSec::Exception::InternalError &e) {
		LogError("XmlSec internal error : " << e.DumpToString());
		return E_SIG_INVALID_FORMAT;
	} catch (const XmlSec::Exception::InvalidFormat &e) {
		LogError("XmlSec invalid format : " << e.DumpToString());
		return E_SIG_INVALID_FORMAT;
	} catch (const XmlSec::Exception::InvalidSig &e) {
		LogError("XmlSec invalid signature : " << e.DumpToString());
		return E_SIG_INVALID_SIG;
	} catch (const XmlSec::Exception::OutOfMemory &e) {
		LogError("XmlSec out of memory : " << e.DumpToString());
		return E_SIG_OUT_OF_MEM;
	} catch (const XmlSec::Exception::Base &e) {
		LogError("XmlSec unknown exception : " << e.DumpToString());
		return E_SIG_INVALID_FORMAT;
	} catch (const Ocsp::Exception::OcspUnsupported &e) {
		LogInfo("Ocsp unsupported : " << e.DumpToString());
	} catch (const Ocsp::Exception::Base &e) {
		LogInfo("Ocsp check throw exeption : " << e.DumpToString());
#ifdef TIZEN_PROFILE_MOBILE
		LogInfo("Launch cert-checker.");
		try {
			if (cchecker_ocsp_request() != 0)
				LogError("Load cert-checker failed.");
		} catch (const std::exception &e) {
			LogError("std exception occured while cchecker running : " << e.what());
		} catch (...) {
			LogError("Unknown exception occuured while cchecker running. ");
		}
#endif
	} catch (const std::exception &e) {
		LogError("std exception occured : " << e.what());
		return E_SIG_UNKNOWN;
	} catch (...) {
		LogError("Unknown exception in SignatureValidator::check");
		return E_SIG_UNKNOWN;
	}

	return m_disregarded ? E_SIG_DISREGARDED : E_SIG_NONE;
}

VCerr SignatureValidator::Impl::baseCheckList(
	bool checkOcsp,
	const UriList &uriList)
{
	try {
		// Make certificate chain, check certificate info
		VCerr result = preStep();

		if (result != E_SIG_NONE)
			return result;

		// XmlSec validate
		if (uriList.size() == 0)
			XmlSecSingleton::Instance().validateNoHash(m_context);
		else
			XmlSecSingleton::Instance().validatePartialHash(m_context, uriList);

		if (checkOcsp && Ocsp::check(m_data) == Ocsp::Result::REVOKED) {
			LogError("Certificate is Revoked by OCSP server.");
			return E_SIG_REVOKED;
		}

		LogDebug("Signature validation of check list done successfully ");
	} catch (const CertificateCollection::Exception::Base &e) {
		LogError("CertificateCollection exception : " << e.DumpToString());
		return E_SIG_INVALID_CHAIN;
	} catch (const XmlSec::Exception::InternalError &e) {
		LogError("XmlSec internal error : " << e.DumpToString());
		return E_SIG_INVALID_FORMAT;
	} catch (const XmlSec::Exception::InvalidFormat &e) {
		LogError("XmlSec invalid format : " << e.DumpToString());
		return E_SIG_INVALID_FORMAT;
	} catch (const XmlSec::Exception::InvalidSig &e) {
		LogError("XmlSec invalid signature : " << e.DumpToString());
		return E_SIG_INVALID_SIG;
	} catch (const XmlSec::Exception::OutOfMemory &e) {
		LogError("XmlSec out of memory : " << e.DumpToString());
		return E_SIG_OUT_OF_MEM;
	} catch (const XmlSec::Exception::Base &e) {
		LogError("XmlSec unknown exception : " << e.DumpToString());
		return E_SIG_INVALID_FORMAT;
	} catch (const Ocsp::Exception::OcspUnsupported &e) {
		LogInfo("Ocsp unsupported : " << e.DumpToString());
	} catch (const Ocsp::Exception::Base &e) {
		LogInfo("Ocsp check throw exeption : " << e.DumpToString());
#ifdef TIZEN_PROFILE_MOBILE
		LogInfo("Launch cert-checker.");
		try {
			if (cchecker_ocsp_request() != 0)
				LogError("Load cert-checker failed.");
		} catch (const std::exception &e) {
			LogError("std exception occured while cchecker running : " << e.what());
		} catch (...) {
			LogError("Unknown exception occuured while cchecker running. ");
		}
#endif
	} catch (...) {
		LogError("Unknown exception in SignatureValidator::checkList");
		return E_SIG_UNKNOWN;
	}

	return m_disregarded ? E_SIG_DISREGARDED : E_SIG_NONE;
}

VCerr SignatureValidator::Impl::check(
	const std::string &contentPath,
	bool checkOcsp,
	bool checkReferences,
	SignatureData &outData)
{
	VCerr result;
	result = baseCheck(contentPath, checkOcsp, checkReferences);
	result = additionalCheck(result);
	outData = m_data;
	return result;
}

VCerr SignatureValidator::Impl::checkList(
	bool checkOcsp,
	const UriList &uriList,
	SignatureData &outData)
{
	VCerr result;
	result = baseCheckList(checkOcsp, uriList);
	result = additionalCheck(result);
	outData = m_data;
	return result;
}

VCerr SignatureValidator::Impl::makeChainBySignature(
	bool completeWithSystemCert,
	CertificateList &certList)
{
	VCerr result = makeDataBySignature(completeWithSystemCert);

	if (result != E_SIG_NONE)
		return result;

	certList = m_data.getCertList();
	return E_SIG_NONE;
}

std::string SignatureValidator::Impl::errorToString(VCerr code)
{
	switch (code) {
	case E_SIG_NONE:
		return "Success.";

	case E_SIG_INVALID_FORMAT:
		return "Invalid format of signature file.";

	case E_SIG_INVALID_CERT:
		return "Invalid format of certificate in signature.";

	case E_SIG_INVALID_CHAIN:
		return "Invalid certificate chain with certificate in signature.";

	case E_SIG_INVALID_SIG:
		return "Invalid signature. Signed with wrong key, changed signature file or changed package file.";

	case E_SIG_INVALID_REF:
		return "Invalid file reference. An unsinged file was found.";

	case E_SIG_CERT_EXPIRED:
		return "Certificate in signature was expired.";

	case E_SIG_CERT_NOT_YET:
		return "Certificate in signature is not valid yet.";

	case E_SIG_DISREGARDED:
		return "Signature validation can be disregarded in some cases.";

	case E_SIG_REVOKED:
		return "One of certificate was revoked in certificate chain.";

	case E_SIG_PLUGIN:
		return "Failed to load plugin for additional validation check.";

	case E_SIG_OUT_OF_MEM:
		return "Out of memory.";

	case E_SIG_UNKNOWN:
		return "Unknown error.";

	default:
		return m_pluginHandler.errorToString(code);
	}
}


SignatureValidator::SignatureValidator(const SignatureFileInfo &info)
{
	std::unique_ptr<SignatureValidator::Impl> impl(new(std::nothrow) SignatureValidator::Impl(info));
	m_pImpl = std::move(impl);
}
SignatureValidator::~SignatureValidator() {}

std::string SignatureValidator::errorToString(VCerr code)
{
	if (!m_pImpl)
		return "out of memory. error.";

	return m_pImpl->errorToString(code);
}

VCerr SignatureValidator::check(
	const std::string &contentPath,
	bool checkOcsp,
	bool checkReferences,
	SignatureData &outData)
{
	if (!m_pImpl)
		return E_SIG_OUT_OF_MEM;

	return m_pImpl->check(
			   contentPath,
			   checkOcsp,
			   checkReferences,
			   outData);
}

VCerr SignatureValidator::checkList(
	bool checkOcsp,
	const UriList &uriList,
	SignatureData &outData)
{
	if (!m_pImpl)
		return E_SIG_OUT_OF_MEM;

	return m_pImpl->checkList(
			   checkOcsp,
			   uriList,
			   outData);
}

VCerr SignatureValidator::makeChainBySignature(
	bool completeWithSystemCert,
	CertificateList &certList)
{
	if (!m_pImpl)
		return E_SIG_OUT_OF_MEM;

	return m_pImpl->makeChainBySignature(completeWithSystemCert, certList);
}

} // namespace ValidationCore