libdigidocpp
MACX509CertStore.cpp
Go to the documentation of this file.
1 /*
2  * libdigidocpp
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  *
18  */
19 
20 #include "MACX509CertStore.h"
21 #include "X509CertStore_p.h"
22 
23 #include "../../log.h"
24 
25 #include <openssl/err.h>
26 
27 #include <Security/SecCertificate.h>
28 #include <Security/SecTrustSettings.h>
29 
30 using namespace digidoc;
31 
38 {
39  loadCerts(kSecTrustSettingsDomainSystem);
40  loadCerts(kSecTrustSettingsDomainAdmin);
41  INFO("Loaded %d certificates into certificate store.", sk_X509_num(d->stack));
42 }
43 
50 void MACX509CertStore::loadCerts(unsigned int trustSettings) throw(IOException)
51 {
52  CFArrayRef certs;
53  if(SecTrustSettingsCopyCertificates(trustSettings, &certs))
54  THROW_IOEXCEPTION("Failed to open KeyStore.");
55 
56  CFIndex size = CFArrayGetCount(certs);
57  for(CFIndex i = 0; i < size; ++i)
58  {
59  SecCertificateRef cert = SecCertificateRef(CFArrayGetValueAtIndex(certs, i));
60  CSSM_DATA data;
61  if(SecCertificateGetData(cert, &data))
62  {
63  WARN("Error retrieving a CA certificate from the KeyStore");
64  continue;
65  }
66 
67  const unsigned char *pBytes = (const unsigned char*)data.Data;
68  X509 *c = d2i_X509(0, &pBytes, data.Length);
69  if(!c)
70  {
71  WARN("Cant add cert %ld to X509_STORE, %s", ASN1_INTEGER_get(X509_get_serialNumber(c)), ERR_reason_error_string(ERR_get_error()));
72  continue;
73  }
74 
75  sk_X509_push(d->stack, c);
76  if(!X509_STORE_add_cert(d->store, c))
77  WARN("Cant add cert %ld to X509_STORE, %s", ASN1_INTEGER_get(X509_get_serialNumber(c)), ERR_reason_error_string(ERR_get_error()));
78  }
79  CFRelease(certs);
80 }