summaryrefslogtreecommitdiffstats
path: root/eurephiadm/parse_certificate_files.c
blob: b824b8a2f782418a68c6b20c3b929820dd171314 (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
/* parse_certificate_files.c  --  Parses PEM or PKCS12 formatted cert. files
 *
 *  GPLv2 only - Copyright (C) 2008 - 2012
 *               David Sommerseth <dazo@users.sourceforge.net>
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; version 2
 *  of the License.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

/**
 * @file   parse_certificate_files.c
 * @author David Sommerseth <dazo@users.sourceforge.net>
 * @date   2008-12-21
 *
 * @brief  Parses PEM/DER or PKCS#12 certificate files to retrieve information
 *         needed by eurephia.  This feature requires OpenSSL to be available.
 *
 */

#ifdef HAVE_OPENSSL
#include <stdio.h>
#include <string.h>
#include <assert.h>

#include <openssl/ssl.h>
#include <openssl/pkcs12.h>
#include <openssl/evp.h>
#include <openssl/err.h>

#include <eurephia_nullsafe.h>
#include <certinfo.h>

#include "get_console_input.h"
#define _PARSE_CERTFICIATE_FILES_C
#include "parse_certificate_files.h"


/**
 * Extracts a specific X.509 field from an X509 struct pointer.
 *
 * @param module     String containing a module name, only used in error situations
 * @param cert       Pointer to an X509 struct with the certificate information
 * @param fieldname  X.509 field name to extract
 *
 * @return Returns a string (char *) to the field value if found, otherwise NULL.
 */
char *ExtractCertInfo(const char *module, X509 *cert, const char *fieldname) {
        unsigned char *buf = (unsigned char *)1;  // Needs to be 1 to avoid OpenSSL 0.9.6b bug
        char resbuf[2050];
        X509_NAME *name = NULL;
        X509_NAME_ENTRY *namentry = NULL;
        ASN1_STRING *asn1 = NULL;
        int nid, tmp = -1, pos = -1;

        //
        // Extract subject information
        //

        memset(resbuf, 0, 2050);

        nid = OBJ_txt2nid(fieldname);
        name = X509_get_subject_name(cert);

        do {
                pos = tmp;
                tmp = X509_NAME_get_index_by_NID(name, nid, pos);
        } while ( tmp > -1 );

        if( pos == -1 ) {
                fprintf(stderr, "%s: Field '%s' not found\n", module, fieldname);
                return 0;
        }

        if( !(namentry = X509_NAME_get_entry(name, pos)) ) {
                fprintf(stderr, "%s: Failed to extract name entry from field '%s'\n", module, fieldname);
                return 0;
        }

        if( !(asn1 = X509_NAME_ENTRY_get_data(namentry)) ) {
                fprintf(stderr, "%s: Failed to extract data from name entry field '%s'\n", module, fieldname);
                return 0;
        }

        if( ASN1_STRING_to_UTF8(&buf, asn1) <= 0 ) {
                fprintf(stderr, "%s: Failed to convert ASN1 string to UTF-8 for '%s'\n", module, fieldname);
                return 0;
        }

        snprintf(resbuf, 2048, "%s%c", buf, '\0');
        OPENSSL_free(buf);

        return strdup_nullsafe(resbuf);
}


/**
 * Internal function, usually called via the Cert_ParseFile(...) macro.  Parses a certificate
 * file of a given format.
 *
 * @param module          String containing a module name, only used in error situations
 * @param certfile        File name of the input file
 * @param certfile_format Certificate format of the file
 *
 * @return Returns a certinfo struct pointer with the parsed result on success, otherwise NULL.
 */
certinfo *_Cert_ParseFile(const char *module, const char *certfile, int certfile_format) {
        BIO *bio_err = NULL;
        PKCS12 *p12 = NULL;
        EVP_PKEY *pkey = NULL;
        X509 *cert = NULL;
        FILE *fp;
        certinfo *ret = NULL;

        /* Needed to convert X509 digest into hex string */
        unsigned char md_sha1[EVP_MAX_MD_SIZE];
        unsigned int mdlen;

        if( !bio_err ) {
                SSL_library_init();
                SSL_load_error_strings();
                bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
        }

        // Open file - according to defined format
        switch( certfile_format ) {
        case CERTFILE_PEM: // PEM/DER format
                fp = fopen(certfile, "r");
                if( !(cert = PEM_read_X509(fp, NULL, NULL, NULL)) ) {
                        fprintf(stderr, "%s: Failed to open certificate file\n", module);
                        return NULL;
                }
                fclose(fp);
                break;

        case CERTFILE_PKCS12: // PKCS#12 format
                fp = fopen(certfile, "r");
                p12 = d2i_PKCS12_fp(fp, NULL);
                fclose(fp);
                if( p12 == NULL ) {
                        fprintf(stderr, "%s: Could not open PKCS#12 file\n", module);
                        return NULL;
                }
                OpenSSL_add_all_ciphers();

                // First, try without password
                if( !PKCS12_parse(p12, "", &pkey, &cert, NULL) ) {
                        char pwd[130];

                        // If empty password failed, get password and try again
                        memset(&pwd, 0, 130);
                        if( get_console_input(pwd, 128, "PKCS12 password:", 1) < 0 ) {
                                fprintf(stderr, "Could not retrieve password\n");
                        }
                        if( !PKCS12_parse(p12, pwd, &pkey, &cert, NULL) ) {
                                PKCS12_free(p12); p12 = NULL;
                                fprintf(stderr,
                                        "%s: Could not open PKCS#12 file - wrong password\n", module);
                                fprintf(stderr,
                                        "%s: %s\n", module, ERR_error_string(ERR_get_error(), NULL));
                                BIO_free(bio_err);
                                return NULL;
                        }
                }
                EVP_PKEY_free(pkey); pkey = NULL;
                PKCS12_free(p12); p12 = NULL;
                break;

        default: // Unknown
                fprintf(stderr, "%s: Unknown certificate file format\n", module);
                return NULL;
        }

        ret = (certinfo *) malloc_nullsafe(NULL, sizeof(certinfo)+2);
        assert( ret != NULL );

        ret->digest = (char *) malloc_nullsafe(NULL, 66);
        assert(ret != NULL);


        // extract SHA1 digest from certificate
        if (X509_digest(cert, EVP_sha1(), md_sha1, &mdlen) && mdlen > 0) {
                static const char hexcodes[] = "0123456789ABCDEF";
                int j;

                for (j = 0; j < (int) mdlen; j++) {
                        ret->digest[j * 3] = hexcodes[(md_sha1[j] & 0xf0) >> 4U];
                        ret->digest[(j * 3) + 1] = hexcodes[(md_sha1[j] & 0x0f)];
                        if (j + 1 != (int) mdlen) {
                                ret->digest[(j * 3) + 2] = ':';
                        } else {
                                ret->digest[(j * 3) + 2] = '\0';
                        }
                }
        }

        // Extract the subject information we want
        ret->common_name = ExtractCertInfo(module, cert, "CN");
        ret->org         = ExtractCertInfo(module, cert, "O");
        ret->email       = ExtractCertInfo(module, cert, "emailAddress");

        X509_free(cert);
        BIO_free(bio_err);

        return ret;
}
#endif