forked from open-eid/libdigidocpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
X509Crypto.cpp
278 lines (252 loc) · 9.03 KB
/
X509Crypto.cpp
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
/*
* libdigidocpp
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "X509Crypto.h"
#include "log.h"
#include "crypto/Digest.h"
#include "crypto/OpenSSLHelpers.h"
#include "util/File.h"
#include <openssl/asn1t.h>
#include <openssl/err.h>
#include <openssl/ts.h>
#include <openssl/x509v3.h>
#include <cstring>
#include <iterator>
#include <set>
using namespace digidoc;
using namespace std;
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
/*-
* IssuerSerial ::= SEQUENCE {
* issuer GeneralNames,
* serialNumber CertificateSerialNumber
* }
*/
using ESS_ISSUER_SERIAL = struct ESS_issuer_serial {
STACK_OF(GENERAL_NAME) *issuer;
ASN1_INTEGER *serial;
};
#if OPENSSL_VERSION_NUMBER < 0x10101000L
ASN1_SEQUENCE(ESS_ISSUER_SERIAL) = {
ASN1_SEQUENCE_OF(ESS_ISSUER_SERIAL, issuer, GENERAL_NAME),
ASN1_SIMPLE(ESS_ISSUER_SERIAL, serial, ASN1_INTEGER)
} static_ASN1_SEQUENCE_END(ESS_ISSUER_SERIAL)
IMPLEMENT_ASN1_FUNCTIONS_const(ESS_ISSUER_SERIAL)
#endif
#else
static int ECDSA_SIG_set0(ECDSA_SIG *sig, BIGNUM *r, BIGNUM *s)
{
if(!r || !s) return 0;
BN_clear_free(sig->r);
BN_clear_free(sig->s);
sig->r = r;
sig->s = s;
return 1;
}
#endif
/**
* Initialize RSA crypter.
*
* @param cert X.509 certificate.
*/
X509Crypto::X509Crypto(X509Cert cert)
: cert(std::move(cert))
{
}
bool X509Crypto::compareIssuerToDer(const vector<unsigned char> &data) const
{
// DER-encoded instance of type IssuerSerial type defined in IETF RFC 5035 [17].
const unsigned char *p = data.data();
SCOPE(ESS_ISSUER_SERIAL, is, d2i_ESS_ISSUER_SERIAL(nullptr, &p, long(data.size())));
if(!is || sk_GENERAL_NAME_num(is->issuer) != 1)
return false;
GENERAL_NAME *issuer = sk_GENERAL_NAME_value(is->issuer, 0);
return issuer->type == GEN_DIRNAME &&
X509_NAME_cmp(issuer->d.dirn, X509_get_issuer_name(cert.handle())) == 0 &&
ASN1_INTEGER_cmp(is->serial, X509_get_serialNumber(cert.handle())) == 0;
}
/**
* Check if X509Cert issuer is same as provided issuer name by
* http:https://www.w3.org/TR/xmldsig-core/#dname-encrules which refers to
* http:https://www.ietf.org/rfc/rfc4514.txt
*
* String X.500 AttributeType
* CN commonName (2.5.4.3)
* L localityName (2.5.4.7)
* ST stateOrProvinceName (2.5.4.8)
* O organizationName (2.5.4.10)
* OU organizationalUnitName (2.5.4.11)
* C countryName (2.5.4.6)
* STREET streetAddress (2.5.4.9)
* DC domainComponent (0.9.2342.19200300.100.1.25)
* UID userId (0.9.2342.19200300.100.1.1)
*
* These attribute types are described in [RFC4519].
* Implementations MAY recognize other DN string representations.
* However, as there is no requirement that alternative DN string
* representations be recognized (and, if so, how), implementations
* SHOULD only generate DN strings in accordance with Section 2 of this document.
*
* @param issuer name
* @return 0 if equal, otherwise a number different from 0 is returned
* @throw IOException if error
*/
int X509Crypto::compareIssuerToString(const string &name) const
{
static const std::set<std::string> list{
"CN", "commonName",
"L", "localityName",
"ST", "stateOrProvinceName",
"O", "organizationName",
"OU", "organizationalUnitName",
"C", "countryName",
"STREET", "streetAddress",
"DC", "domainComponent",
"UID", "userId"
};
for(size_t old = 0, pos = 0; ; )
{
pos = name.find(',', old);
if(pos == string::npos)
{
pos = name.size();
if(pos < old)
break;
}
else
{
if(name[pos-1] == '\\')
{
old = pos;
continue;
}
}
string nameitem = name.substr(old, pos - old);
old = pos + 1;
if((pos = nameitem.find('=')) == string::npos ||
nameitem.compare(pos-1, 1, "\\") == 0)
continue;
string obj = nameitem.substr(0, pos);
if(list.find(obj) == list.end())
continue;
ASN1_OBJECT *obja = OBJ_txt2obj(obj.c_str(), 0);
string tmp = nameitem.substr(pos+1, pos-old);
string value;
char data[] = "00";
for(string::const_iterator i = tmp.cbegin(); i != tmp.cend(); ++i)
{
if(*i == '\\' && distance(i, tmp.cend()) > 2 && isxdigit(*(i+1)) && isxdigit(*(i+2)))
{
data[0] = *(++i);
data[1] = *(++i);
value += static_cast<char>(strtoul(data, nullptr, 16));
}
else
value += *i;
}
bool found = false;
X509_NAME *issuer = X509_get_issuer_name(cert.handle());
for(int i = 0; i < X509_NAME_entry_count(issuer); ++i)
{
X509_NAME_ENTRY *entb = X509_NAME_get_entry(issuer, i);
if(OBJ_cmp(obja, X509_NAME_ENTRY_get_object(entb)) != 0)
continue;
char *data = nullptr;
int size = ASN1_STRING_to_UTF8((unsigned char**)&data, X509_NAME_ENTRY_get_data(entb));
found = value.compare(0, size_t(size), data, value.size()) == 0;
OPENSSL_free(data);
if(found)
break;
}
if(!found)
return -1;
}
return 0;
}
bool X509Crypto::isRSAKey() const
{
SCOPE(EVP_PKEY, key, X509_get_pubkey(cert.handle()));
return key.get() && EVP_PKEY_base_id(key.get()) == EVP_PKEY_RSA;
}
/**
* Verify signature with RSA public key from X.509 certificate.
*
* @param digestMethod digest method (e.g NID_sha1 for SHA1, see openssl/obj_mac.h).
* @param digest digest value, this value is compared with the digest value decrypted from the <code>signature</code>.
* @param signature signature value, this value is decrypted to get the digest and compared with
* the digest value provided in <code>digest</code>.
* @return returns <code>true</code> if the signature value matches with the digest, otherwise <code>false</code>
* is returned.
* @throws IOException throws exception if X.509 certificate is not missing or does not have a RSA public key.
*/
bool X509Crypto::verify(const string &method, const vector<unsigned char> &digest, const vector<unsigned char> &signature)
{
if(!cert)
THROW("X.509 certificate parameter is not set in RSACrypt, can not verify signature.");
if(signature.empty())
THROW("Signature value is empty.");
SCOPE(EVP_PKEY, key, X509_get_pubkey(cert.handle()));
if(!key)
THROW("Certificate does not have a public key, can not verify signature.");
int result = 0;
switch(EVP_PKEY_base_id(key.get()))
{
case EVP_PKEY_RSA:
{
SCOPE(RSA, rsa, EVP_PKEY_get1_RSA(key.get()));
#if OPENSSL_VERSION_NUMBER < 0x10010000L
result = RSA_verify(Digest::toMethod(method), digest.data(), (unsigned int)digest.size(),
const_cast<unsigned char*>(signature.data()), (unsigned int)signature.size(), rsa.get());
#else
vector<unsigned char> out(size_t(RSA_size(rsa.get())));
int size = RSA_public_decrypt(int(signature.size()), signature.data(), out.data(), rsa.get(), RSA_PKCS1_PADDING);
if(size <= 0)
break;
out.resize(size_t(size));
const unsigned char *p = out.data();
SCOPE(X509_SIG, sig, d2i_X509_SIG(nullptr, &p, long(out.size())));
if(!sig)
break;
const X509_ALGOR *algor = nullptr;
const ASN1_OCTET_STRING *value = nullptr;
X509_SIG_get0(sig.get(), &algor, &value);
if(algor->parameter && ASN1_TYPE_get(algor->parameter) != V_ASN1_NULL)
break;
if(Digest::toMethod(method) == OBJ_obj2nid(algor->algorithm) &&
size_t(value->length) == digest.size() &&
memcmp(value->data, digest.data(), digest.size()) == 0)
result = 1;
#endif
break;
}
#ifndef OPENSSL_NO_ECDSA
case EVP_PKEY_EC:
{
SCOPE(EC_KEY, ec, EVP_PKEY_get1_EC_KEY(key.get()));
SCOPE(ECDSA_SIG, sig, ECDSA_SIG_new());
ECDSA_SIG_set0(sig.get(),
BN_bin2bn(signature.data(), int(signature.size()/2), nullptr),
BN_bin2bn(&signature[signature.size()/2], int(signature.size()/2), nullptr));
result = ECDSA_do_verify(digest.data(), int(digest.size()), sig.get(), ec.get());
break;
}
#endif
default: THROW("Unsupported public key");
}
return result == 1;
}