summaryrefslogtreecommitdiff
path: root/cpp/src/IceSSL/Certificate.cpp
blob: 511290cc6e7d0f85d6482a3f0512491b93c8fd28 (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
// **********************************************************************
//
// Copyright (c) 2003-2007 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

#include <IceUtil/DisableWarnings.h>
#include <IceUtil/StaticMutex.h>
#include <IceSSL/Plugin.h>
#include <IceSSL/Util.h>
#include <IceSSL/RFC2253.h>

#include <openssl/x509v3.h>
#include <openssl/pem.h>

using namespace std;
using namespace Ice;
using namespace IceSSL;

const char* IceSSL::CertificateReadException::_name = "IceSSL::CertificateReadException";

CertificateReadException::CertificateReadException(const char* file, int line, const string& r) :
    Exception(file, line),
    reason(r)
{
}

CertificateReadException::~CertificateReadException() throw()
{
}

string
CertificateReadException::ice_name() const
{
    return _name;
}

Exception* 
CertificateReadException::ice_clone() const
{
    return new CertificateReadException(*this);
}

void
CertificateReadException::ice_throw() const
{
    throw *this;
}

const char* IceSSL::CertificateEncodingException::_name = "IceSSL::CertificateEncodingException";

CertificateEncodingException::CertificateEncodingException(const char* file, int line, const string& r) :
    Exception(file, line),
    reason(r)
{
}

CertificateEncodingException::~CertificateEncodingException() throw()
{
}

string
CertificateEncodingException::ice_name() const
{
    return _name;
}

Exception* 
CertificateEncodingException::ice_clone() const
{
    return new CertificateEncodingException(*this);
}

void
CertificateEncodingException::ice_throw() const
{
    throw *this;
}

static IceUtil::Time
ASMUtcTimeToIceUtilTime(const ASN1_UTCTIME* s)
{
    struct tm tm;
    int offset;
    
    memset(&tm, '\0', sizeof tm);
    
#define g2(p) (((p)[0]-'0')*10+(p)[1]-'0')
    tm.tm_year = g2(s->data);
    if(tm.tm_year < 50)
        tm.tm_year += 100;
    tm.tm_mon = g2(s->data + 2) - 1;
    tm.tm_mday = g2(s->data + 4);
    tm.tm_hour = g2(s->data + 6);
    tm.tm_min = g2(s->data + 8);
    tm.tm_sec = g2(s->data + 10);
    if(s->data[12] == 'Z')
    {
        offset = 0;
    }
    else
    {
        offset = g2(s->data + 13) * 60 + g2(s->data + 15);
        if(s->data[12] == '-')
        {
            offset = -offset;
        }
    }
#undef g2

    //
    // If timegm was on all systems this code could be
    // return IceUtil::Time::seconds(timegm(&tm) - offset*60);
    //
    // Windows doesn't support the re-entrant _r versions.
    //
    time_t tzone;
    {
        static IceUtil::StaticMutex mutex = ICE_STATIC_MUTEX_INITIALIZER;
        IceUtil::StaticMutex::Lock sync(mutex);
        time_t now = time(0);
        tzone = mktime(localtime(&now)) - mktime(gmtime(&now));
    }
    return IceUtil::Time::seconds(mktime(&tm) - offset*60 + tzone);
}

static string
convertX509NameToString(X509NAME* name)
{
    BIO* out = BIO_new(BIO_s_mem());
    X509_NAME_print_ex(out, name, 0, XN_FLAG_RFC2253);
    BUF_MEM* p;
    BIO_get_mem_ptr(out, &p);
    string result = string(p->data, p->length);
    BIO_free(out);
    return result;
}

static vector<pair<int, string> >
convertGeneralNames(GENERAL_NAMES* gens)
{
    vector<pair<int, string> > alt;
    if(gens == 0)
    {
        return alt;
    }
    for(int i = 0; i < sk_GENERAL_NAME_num(gens); ++i)
    {
        GENERAL_NAME* gen = sk_GENERAL_NAME_value(gens, i);
        pair<int, string> p;
        p.first = gen->type;
        switch(gen->type)
        {
        case GEN_EMAIL:
        {
            ASN1_IA5STRING* str = gen->d.rfc822Name;
            if(str && str->type == V_ASN1_IA5STRING && str->data && str->length > 0)
            {
                p.second = reinterpret_cast<const char*>(str->data);
            }
            break;
        }
        case GEN_DNS:
        {
            ASN1_IA5STRING* str = gen->d.dNSName;
            if(str && str->type == V_ASN1_IA5STRING && str->data && str->length > 0)
            {
                p.second = reinterpret_cast<const char*>(str->data);
            }
            break;
        }
        case GEN_DIRNAME:
        {
            p.second = convertX509NameToString(gen->d.directoryName);
            break;
        }
        case GEN_URI:
        {
            ASN1_IA5STRING* str = gen->d.uniformResourceIdentifier;
            if(str && str->type == V_ASN1_IA5STRING && str->data && str->length > 0)
            {
                p.second = reinterpret_cast<const char*>(str->data);
            }
            break;
        }
        case GEN_IPADD:
        {
            ASN1_OCTET_STRING* addr = gen->d.iPAddress;
            // TODO: Support IPv6 someday.
            if(addr && addr->type == V_ASN1_OCTET_STRING && addr->data && addr->length == 4)
            {
                ostringstream ostr;
                for(int j = 0; j < 4; ++j)
                {
                    if(j > 0)
                    {
                        ostr << '.';
                    }
                    ostr << static_cast<int>(addr->data[j]);
                }
                p.second = ostr.str();
            }
            break;
        }
        case GEN_OTHERNAME:
        case GEN_EDIPARTY:
        case GEN_X400:
        case GEN_RID:
        {
            //
            // TODO: These types are not supported. If the user wants
            // them, they have to get at the certificate data. Another
            // alternative is to DER encode the data (as the Java
            // certificate does).
            //
            break;
        }
        }
        alt.push_back(p);
    }
    sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
    return alt;
}

const char* ParseException::_name = "IceSSL::ParseException";

ParseException::ParseException(const char* file, int line, const string& r) :
    Exception(file, line),
    reason(r)
{
}

ParseException::~ParseException() throw()
{
}

string
ParseException::ice_name() const
{
    return _name;
}

IceUtil::Exception* 
ParseException::ice_clone() const
{
    return new ParseException(*this);
}

void
ParseException::ice_throw() const
{
    throw *this;
}

DistinguishedName::DistinguishedName(X509NAME* name) :
    _rdns(RFC2253::parseStrict(convertX509NameToString(name)))
{
    unescape();
}

DistinguishedName::DistinguishedName(const string& dn) :
    _rdns(RFC2253::parseStrict(dn))
{
    unescape();
}

DistinguishedName::DistinguishedName(const list<pair<string, string> >& rdns) :
    _rdns(rdns)
{
    unescape();
}

bool
DistinguishedName::operator==(const DistinguishedName& other) const
{
    return other._unescaped == _unescaped;
}

bool
DistinguishedName::operator!=(const DistinguishedName& other) const
{
    return other._unescaped != _unescaped;
}

bool
DistinguishedName::operator<(const DistinguishedName& other) const
{
    return other._unescaped < _unescaped;
}

bool
DistinguishedName::match(const DistinguishedName& other) const
{
    for(list< pair<string, string> >::const_iterator p = other._unescaped.begin(); p != other._unescaped.end(); ++p)
    {
        bool found = false;
        for(list< pair<string, string> >::const_iterator q = _unescaped.begin(); q != _unescaped.end(); ++q)
        {
            if(p->first == q->first)
            {
                found = true;
                if(p->second != q->second)
                {
                    return false;
                }
            }
        }
        if(!found)
        {
            return false;
        }
    }
    return true;
}

//
// This always produces the same output as the input DN -- the type of
// escaping is not changed.
//
DistinguishedName::operator string() const
{
    ostringstream os;
    bool first = true;
    for(list< pair<string, string> >::const_iterator p = _rdns.begin(); p != _rdns.end(); ++p)
    {
        if(!first)
        {
            os << ",";
        }
        first = false;
        os << p->first << "=" << p->second;
    }
    return os.str();
}

void
DistinguishedName::unescape()
{
    for(list< pair<string, string> >::const_iterator q = _rdns.begin(); q != _rdns.end(); ++q)
    {
        pair<string, string> rdn = *q;
        rdn.second = RFC2253::unescape(rdn.second);
        _unescaped.push_back(rdn);
    }
}

PublicKey::PublicKey(EVP_PKEY* key) :
    _key(key)
{
}

PublicKey::~PublicKey()
{
    EVP_PKEY_free(_key);
}

EVP_PKEY*
PublicKey::key() const
{
    return _key;
}

//
// The caller is responsible for incrementing the reference count.
//
Certificate::Certificate(X509* cert) :
    _cert(cert)
{
    assert(_cert != 0);
}

Certificate::~Certificate()
{
    X509_free(_cert);
}

CertificatePtr
Certificate::load(const string& file)
{
    BIO *cert = BIO_new(BIO_s_file());
    if(BIO_read_filename(cert, file.c_str()) <= 0)
    {
        BIO_free(cert);
        throw CertificateReadException(__FILE__, __LINE__, "error opening file");
    }
    
    X509* x = PEM_read_bio_X509_AUX(cert, NULL, NULL, NULL);
    if(x == NULL)
    {
        BIO_free(cert);
        throw CertificateReadException(__FILE__, __LINE__, "error reading file:\n" + getSslErrors(false));
    }
    BIO_free(cert);
    return new Certificate(x);
}

CertificatePtr
Certificate::decode(const string& encoding)
{
    BIO *cert = BIO_new_mem_buf(static_cast<void*>(const_cast<char*>(&encoding[0])), static_cast<int>(encoding.size()));
    X509* x = PEM_read_bio_X509_AUX(cert, NULL, NULL, NULL);
    if(x == NULL)
    {
        BIO_free(cert);
        throw CertificateReadException(__FILE__, __LINE__, "error decoding certificate:\n" + getSslErrors(false));
    }
    BIO_free(cert);
    return new Certificate(x);
}

bool
Certificate::operator==(const Certificate& other) const
{
    return X509_cmp(_cert, other._cert) == 0;
}

bool
Certificate::operator!=(const Certificate& other) const
{
    return X509_cmp(_cert, other._cert) != 0;
}

PublicKeyPtr
Certificate::getPublicKey() const
{
    return new PublicKey(X509_get_pubkey(_cert));
}

bool
Certificate::verify(const PublicKeyPtr& key) const
{
    return X509_verify(_cert, key->key()) > 0;
}

string
Certificate::encode() const
{
    BIO* out = BIO_new(BIO_s_mem());
    int i = PEM_write_bio_X509_AUX(out, _cert);
    if(i <= 0)
    {
        BIO_free(out);
        throw CertificateEncodingException(__FILE__, __LINE__, getSslErrors(false));
    }
    BUF_MEM* p;
    BIO_get_mem_ptr(out, &p);
    string result = string(p->data, p->length);
    BIO_free(out);
    return result;
}

bool
Certificate::checkValidity() const
{
    IceUtil::Time now = IceUtil::Time::now();
    return now > getNotBefore() && now <= getNotAfter();
}

bool
Certificate::checkValidity(const IceUtil::Time& now) const
{
    return now > getNotBefore() && now <= getNotAfter();
}

IceUtil::Time
Certificate::getNotAfter() const
{
    return ASMUtcTimeToIceUtilTime(X509_get_notAfter(_cert));
}

IceUtil::Time
Certificate::getNotBefore() const
{
    return ASMUtcTimeToIceUtilTime(X509_get_notBefore(_cert));
}

string
Certificate::getSerialNumber() const
{
    BIGNUM* bn = ASN1_INTEGER_to_BN(X509_get_serialNumber(_cert), 0);
    char* dec = BN_bn2dec(bn);
    string result = dec;
    OPENSSL_free(dec);
    BN_free(bn);

    return result;
}

//string
//Certificate::getSigAlgName() const
//{
//}

//string
//Certificate::getSigAlgOID() const
//{
//}

DistinguishedName
Certificate::getIssuerDN() const
{
    return DistinguishedName(X509_get_issuer_name(_cert));
}

vector<pair<int, string> >
Certificate::getIssuerAlternativeNames()
{
    return convertGeneralNames(reinterpret_cast<GENERAL_NAMES*>(
        X509_get_ext_d2i(_cert, NID_issuer_alt_name, 0, 0)));
}

DistinguishedName
Certificate::getSubjectDN() const
{
    return DistinguishedName(X509_get_subject_name(_cert));
}

vector<pair<int, string> >
Certificate::getSubjectAlternativeNames()
{
    return convertGeneralNames(
        reinterpret_cast<GENERAL_NAMES*>(X509_get_ext_d2i(_cert, NID_subject_alt_name, 0, 0)));
}

int
Certificate::getVersion() const
{
    return static_cast<int>(X509_get_version(_cert));
}

string
Certificate::toString() const
{
    ostringstream os;
    os << "serial: " << getSerialNumber() << "\n";
    os << "issuer: " << string(getIssuerDN()) << "\n";
    os << "subject: " << string(getSubjectDN()) << "\n";
    os << "notBefore: " << getNotBefore().toDateTime() << "\n";
    os << "notAfter: " << getNotAfter().toDateTime();

    return os.str();
}

X509*
Certificate::getCert() const
{
    return _cert;
}