-
Notifications
You must be signed in to change notification settings - Fork 0
/
GPGMECryptoSignBackend.cc
403 lines (367 loc) · 12.4 KB
/
GPGMECryptoSignBackend.cc
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
//========================================================================
//
// GPGMECryptoSignBackend.cc
//
// This file is licensed under the GPLv2 or later
//
// Copyright 2023 g10 Code GmbH, Author: Sune Stolborg Vuorela <sune@vuorela.dk>
//========================================================================
#include "config.h"
#include "GPGMECryptoSignBackend.h"
#include "DistinguishedNameParser.h"
#include <gpgme.h>
#include <gpgme++/key.h>
#include <gpgme++/gpgmepp_version.h>
#include <gpgme++/signingresult.h>
#include <gpgme++/engineinfo.h>
bool GpgSignatureBackend::hasSufficientVersion()
{
// gpg 2.4.0 does not support padded signatures.
// Most gpg signatures are padded. This is fixed for 2.4.1
// gpg 2.4.0 does not support generating signatures
// with definite lengths. This is also fixed for 2.4.1.
// this has also been fixed in 2.2.42 in the 2.2 branch
auto version = GpgME::engineInfo(GpgME::GpgSMEngine).engineVersion();
if (version > "2.4.0") {
return true;
}
if (version >= "2.3.0") { // development branch for 2.4 releases; no more releases here
return false;
}
return version >= "2.2.42";
}
/// GPGME helper methods
// gpgme++'s string-like functions returns char pointers that can be nullptr
// Creating std::string from nullptr is, depending on c++ standards versions
// either undefined behavior or illegal, so we need a helper.
static std::string fromCharPtr(const char *data)
{
if (data) {
return std::string { data };
}
return {};
}
static bool isSuccess(const GpgME::Error &err)
{
if (err) {
return false;
}
if (err.isCanceled()) {
return false;
}
return true;
}
template<typename Result>
static bool isValidResult(const Result &result)
{
return isSuccess(result.error());
}
template<typename Result>
static bool hasValidResult(const std::optional<Result> &result)
{
if (!result) {
return false;
}
return isValidResult(result.value());
}
static std::optional<GpgME::Signature> getSignature(const GpgME::VerificationResult &result, size_t signatureNumber)
{
if (result.numSignatures() > signatureNumber) {
return result.signature(signatureNumber);
}
return std::nullopt;
}
static X509CertificateInfo::Validity getValidityFromSubkey(const GpgME::Subkey &key)
{
X509CertificateInfo::Validity validity;
validity.notBefore = key.creationTime();
validity.notAfter = key.expirationTime();
return validity;
}
static X509CertificateInfo::EntityInfo getEntityInfoFromKey(std::string_view dnString)
{
const auto dn = DN::parseString(dnString);
X509CertificateInfo::EntityInfo info;
info.commonName = DN::FindFirstValue(dn, "CN").value_or(std::string {});
info.organization = DN::FindFirstValue(dn, "O").value_or(std::string {});
info.email = DN::FindFirstValue(dn, "EMAIL").value_or(std::string {});
info.distinguishedName = std::string { dnString };
return info;
}
static std::unique_ptr<X509CertificateInfo> getCertificateInfoFromKey(const GpgME::Key &key)
{
auto certificateInfo = std::make_unique<X509CertificateInfo>();
certificateInfo->setIssuerInfo(getEntityInfoFromKey(fromCharPtr(key.issuerName())));
certificateInfo->setSerialNumber(GooString { DN::detail::parseHexString(fromCharPtr(key.issuerSerial())).value_or("") });
auto subjectInfo = getEntityInfoFromKey(fromCharPtr(key.userID(0).id()));
if (subjectInfo.email.empty()) {
subjectInfo.email = fromCharPtr(key.userID(1).email());
}
certificateInfo->setSubjectInfo(std::move(subjectInfo));
certificateInfo->setValidity(getValidityFromSubkey(key.subkey(0)));
certificateInfo->setNickName(GooString(fromCharPtr(key.primaryFingerprint())));
X509CertificateInfo::PublicKeyInfo pkInfo;
pkInfo.publicKeyStrength = key.subkey(0).length();
switch (key.subkey(0).publicKeyAlgorithm()) {
case GpgME::Subkey::AlgoDSA:
pkInfo.publicKeyType = DSAKEY;
break;
case GpgME::Subkey::AlgoECC:
case GpgME::Subkey::AlgoECDH:
case GpgME::Subkey::AlgoECDSA:
case GpgME::Subkey::AlgoEDDSA:
pkInfo.publicKeyType = ECKEY;
break;
case GpgME::Subkey::AlgoRSA:
case GpgME::Subkey::AlgoRSA_E:
case GpgME::Subkey::AlgoRSA_S:
pkInfo.publicKeyType = RSAKEY;
break;
case GpgME::Subkey::AlgoELG:
case GpgME::Subkey::AlgoELG_E:
case GpgME::Subkey::AlgoMax:
case GpgME::Subkey::AlgoUnknown:
pkInfo.publicKeyType = OTHERKEY;
}
{
auto ctx = GpgME::Context::create(GpgME::CMS);
GpgME::Data pubkeydata;
const auto err = ctx->exportPublicKeys(key.primaryFingerprint(), pubkeydata);
if (isSuccess(err)) {
certificateInfo->setCertificateDER(GooString(pubkeydata.toString()));
}
}
certificateInfo->setPublicKeyInfo(std::move(pkInfo));
int kue = 0;
// this block is kind of a hack. GPGSM collapses multiple
// into one bit, so trying to match it back can never be good
if (key.canSign()) {
kue |= KU_NON_REPUDIATION;
kue |= KU_DIGITAL_SIGNATURE;
}
if (key.canEncrypt()) {
kue |= KU_KEY_ENCIPHERMENT;
kue |= KU_DATA_ENCIPHERMENT;
}
if (key.canCertify()) {
kue |= KU_KEY_CERT_SIGN;
}
certificateInfo->setKeyUsageExtensions(kue);
auto subkey = key.subkey(0);
if (subkey.isCardKey()) {
certificateInfo->setKeyLocation(KeyLocation::HardwareToken);
} else if (subkey.isSecret()) {
certificateInfo->setKeyLocation(KeyLocation::Computer);
}
return certificateInfo;
}
/// implementation of header file
GpgSignatureBackend::GpgSignatureBackend()
{
GpgME::initializeLibrary();
}
std::unique_ptr<CryptoSign::SigningInterface> GpgSignatureBackend::createSigningHandler(const std::string &certID, HashAlgorithm /*digestAlgTag*/)
{
return std::make_unique<GpgSignatureCreation>(certID);
}
std::unique_ptr<CryptoSign::VerificationInterface> GpgSignatureBackend::createVerificationHandler(std::vector<unsigned char> &&pkcs7)
{
return std::make_unique<GpgSignatureVerification>(std::move(pkcs7));
}
std::vector<std::unique_ptr<X509CertificateInfo>> GpgSignatureBackend::getAvailableSigningCertificates()
{
std::vector<std::unique_ptr<X509CertificateInfo>> certificates;
const auto context = GpgME::Context::create(GpgME::CMS);
auto err = context->startKeyListing(static_cast<const char *>(nullptr), true /*secretOnly*/);
while (isSuccess(err)) {
const auto key = context->nextKey(err);
if (!key.isNull() && isSuccess(err)) {
if (key.isBad()) {
continue;
}
if (!key.canSign()) {
continue;
}
certificates.push_back(getCertificateInfoFromKey(key));
} else {
break;
}
}
return certificates;
}
GpgSignatureCreation::GpgSignatureCreation(const std::string &certId) : gpgContext { GpgME::Context::create(GpgME::CMS) }
{
GpgME::Error error;
const auto signingKey = gpgContext->key(certId.c_str(), error, true);
if (isSuccess(error)) {
gpgContext->addSigningKey(signingKey);
key = signingKey;
}
}
void GpgSignatureCreation::addData(unsigned char *dataBlock, int dataLen)
{
gpgData.write(dataBlock, dataLen);
}
std::optional<GooString> GpgSignatureCreation::signDetached(const std::string &password)
{
if (!key) {
return {};
}
gpgData.rewind();
GpgME::Data signatureData;
const auto signingResult = gpgContext->sign(gpgData, signatureData, GpgME::SignatureMode::Detached);
if (!isValidResult(signingResult)) {
return {};
}
const auto signatureString = signatureData.toString();
return GooString(std::move(signatureString));
}
std::unique_ptr<X509CertificateInfo> GpgSignatureCreation::getCertificateInfo() const
{
if (!key) {
return nullptr;
}
return getCertificateInfoFromKey(*key);
}
GpgSignatureVerification::GpgSignatureVerification(const std::vector<unsigned char> &p7data) : gpgContext { GpgME::Context::create(GpgME::CMS) }, signatureData(reinterpret_cast<const char *>(p7data.data()), p7data.size())
{
gpgContext->setOffline(true);
signatureData.setEncoding(GpgME::Data::BinaryEncoding);
}
void GpgSignatureVerification::addData(unsigned char *dataBlock, int dataLen)
{
signedData.write(dataBlock, dataLen);
}
std::unique_ptr<X509CertificateInfo> GpgSignatureVerification::getCertificateInfo() const
{
if (!hasValidResult(gpgResult)) {
return nullptr;
}
auto signature = getSignature(gpgResult.value(), 0);
if (!signature) {
return nullptr;
}
auto gpgInfo = getCertificateInfoFromKey(signature->key(true, false));
return gpgInfo;
}
HashAlgorithm GpgSignatureVerification::getHashAlgorithm() const
{
if (gpgResult) {
const auto signature = getSignature(gpgResult.value(), 0);
if (!signature) {
return HashAlgorithm::Unknown;
}
switch (signature->hashAlgorithm()) {
case GPGME_MD_MD5:
return HashAlgorithm::Md5;
case GPGME_MD_SHA1:
return HashAlgorithm::Sha1;
case GPGME_MD_MD2:
return HashAlgorithm::Md2;
case GPGME_MD_SHA256:
return HashAlgorithm::Sha256;
case GPGME_MD_SHA384:
return HashAlgorithm::Sha384;
case GPGME_MD_SHA512:
return HashAlgorithm::Sha512;
case GPGME_MD_SHA224:
return HashAlgorithm::Sha224;
case GPGME_MD_NONE:
case GPGME_MD_RMD160:
case GPGME_MD_TIGER:
case GPGME_MD_HAVAL:
case GPGME_MD_MD4:
case GPGME_MD_CRC32:
case GPGME_MD_CRC32_RFC1510:
case GPGME_MD_CRC24_RFC2440:
default:
return HashAlgorithm::Unknown;
}
}
return HashAlgorithm::Unknown;
}
std::string GpgSignatureVerification::getSignerName() const
{
if (!hasValidResult(gpgResult)) {
return {};
}
const auto signature = getSignature(gpgResult.value(), 0);
if (!signature) {
return {};
}
const auto dn = DN::parseString(fromCharPtr(signature->key(true, false).userID(0).id()));
return DN::FindFirstValue(dn, "CN").value_or("");
}
std::string GpgSignatureVerification::getSignerSubjectDN() const
{
if (!hasValidResult(gpgResult)) {
return {};
}
const auto signature = getSignature(gpgResult.value(), 0);
if (!signature) {
return {};
}
return fromCharPtr(signature->key(true, false).userID(0).id());
}
std::chrono::system_clock::time_point GpgSignatureVerification::getSigningTime() const
{
if (!hasValidResult(gpgResult)) {
return {};
}
const auto signature = getSignature(gpgResult.value(), 0);
if (!signature) {
return {};
}
return std::chrono::system_clock::from_time_t(signature->creationTime());
}
CertificateValidationStatus GpgSignatureVerification::validateCertificate(std::chrono::system_clock::time_point validation_time, bool ocspRevocationCheck, bool useAIACertFetch)
{
if (!gpgResult) {
return CERTIFICATE_NOT_VERIFIED;
}
if (gpgResult->error()) {
return CERTIFICATE_GENERIC_ERROR;
}
const auto signature = getSignature(gpgResult.value(), 0);
if (!signature) {
return CERTIFICATE_GENERIC_ERROR;
}
const auto offline = gpgContext->offline();
gpgContext->setOffline((!ocspRevocationCheck) || useAIACertFetch);
const auto key = signature->key(true, true);
gpgContext->setOffline(offline);
if (key.isExpired()) {
return CERTIFICATE_EXPIRED;
}
if (key.isRevoked()) {
return CERTIFICATE_REVOKED;
}
if (key.isBad()) {
return CERTIFICATE_NOT_VERIFIED;
}
return CERTIFICATE_TRUSTED;
}
SignatureValidationStatus GpgSignatureVerification::validateSignature()
{
signedData.rewind();
const auto result = gpgContext->verifyDetachedSignature(signatureData, signedData);
gpgResult = result;
if (!isValidResult(result)) {
return SIGNATURE_DECODING_ERROR;
}
const auto signature = getSignature(result, 0);
if (!signature) {
return SIGNATURE_DECODING_ERROR;
}
// Ensure key is actually available
signature->key(true, true);
const auto summary = signature->summary();
using Summary = GpgME::Signature::Summary;
if (summary & Summary::Red) {
return SIGNATURE_INVALID;
}
if (summary & Summary::Green || summary & Summary::Valid) {
return SIGNATURE_VALID;
}
return SIGNATURE_GENERIC_ERROR;
}