summaryrefslogtreecommitdiffstats
path: root/eurephiadm/commands/certificates.c
blob: a3ae77c6ff3777329f96abc635feee93aa3ce605 (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
/* certificates.c  --  eurephiadm command: certs 
 *                     Certificate management
 *
 *  GPLv2 - Copyright (C) 2008  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.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>

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

#ifdef HAVE_LIBXML2
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#endif

#define MODULE "eurephia::Certificates"
#include <eurephia_nullsafe.h>
#include <eurephia_context.h>
#include <eurephia_log.h>
#include <eurephia_xml.h>
#include <eurephia_values_struct.h>
#include <eurephiadb_session_struct.h>
#include <eurephia_admin_struct.h>
#include <eurephiadb_mapping.h>
#include <eurephiadb_driver.h>

#include "../argparser.h"
#include "../get_console_input.h"

void display_certs_help(int page) {
        printf("Help page not implemented yet\n");
}

void help_Certificates() {
        display_certs_help(0);
}

int help_Certificates2(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        e_options helpargs[] = {
                {"--list", "-l", 0},
                {"--show", "-s", 0},
                {"--activate", "-a", 0},
                {"--deactivate", "-d", 0},
                {"--add", "-A", 0},
                {"--delete", "-D", 0},
                {"--password", "-p", 0},
                {NULL, NULL, 0}
        };

        int i = 1;
        display_certs_help(eurephia_getopt(&i, argc, argv, helpargs));
        return 0;
}

#ifdef HAVE_OPENSSL
char *ExtractCertInfo(X509 *cert, const char *fieldname) {
        unsigned char *buf = (unsigned char *)1;  // Needs to be 1 to avoid OpenSSL 0.9.6b bug
        char resbuf[2048];
        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, 2048);

        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 NULL;
        }

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

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

        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 NULL;
        }

        snprintf(resbuf, 2046, "%s", buf);
        OPENSSL_free(buf);

        return strdup_nullsafe(resbuf);
}
#endif

void replace_char(char *str, char s, char r) {
        if( str != NULL ) {
                char *ptr = str;

                while( *ptr != '\0' ) {
                        if( *ptr == s ) {
                                *ptr = r;
                        }
                        ptr++;
                }
        }
}

int register_certificate(eurephiaCTX *ctx, int depth, const char *digest,
                  const char *cname, const char *org, const char *email)
{
        xmlDoc *cert_xml = NULL;
        xmlNode *cert_n = NULL;
        char tmp[66], *cname_cp = NULL, *org_cp = NULL;
        int rc = 0;

        assert( ctx != NULL );

        eurephiaXML_CreateDoc(ctx, 1, "register_certificate", &cert_xml, &cert_n);
        assert( (cert_xml != NULL) || (cert_n != NULL) );

        cert_n = xmlNewChild(cert_n, NULL, (xmlChar *) "fieldMapping", NULL);
        xmlNewProp(cert_n, (xmlChar *) "table", (xmlChar *) "certificates");

        memset(&tmp, 0, 66);
        snprintf(tmp, 64, "%i", depth);

        cname_cp = strdup_nullsafe(cname);
        replace_char(cname_cp, ' ', '_');
        org_cp   = strdup_nullsafe(org);
        replace_char(org_cp, ' ', '_');

        xmlNewChild(cert_n, NULL, (xmlChar *) "depth", (xmlChar *) tmp);
        xmlNewChild(cert_n, NULL, (xmlChar *) "digest", (xmlChar *) digest);
        xmlNewChild(cert_n, NULL, (xmlChar *) "common_name", (xmlChar *) cname_cp);
        xmlNewChild(cert_n, NULL, (xmlChar *) "organisation", (xmlChar *) org_cp);
        xmlNewChild(cert_n, NULL, (xmlChar *) "email", (xmlChar *) email);

        // Register the certificate
        rc = eDBadminAddCertificate(ctx, cert_xml);
        fprintf(stdout, "%s: %s\n", MODULE,
                (rc == 1 ? "Certificate registered successfully" : "Failed to register certificate"));
        xmlFreeDoc(cert_xml);
        free_nullsafe(cname_cp);
        free_nullsafe(org_cp);

        return (rc != 1);
}

int add_cert(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        char *digest = NULL, *cname = NULL, *org = NULL, *email = NULL, *certfile = NULL;
        int depth = -1, i = 0, j = 0, chk = 0, certfile_format = 0, rc = 0;
#ifdef HAVE_OPENSSL
        struct stat cert_stat;
#endif

        e_options addcertargs[] = {
                {"--depth",           "-d", 1},
                {"--digest",          "-D", 1},
                {"--common-name",     "-C", 1},
                {"--organisation",    "-O", 1},
                {"--email",           "-E", 1},
#ifdef HAVE_OPENSSL
                {"--certfile",        "-f", 1},
                {"--pkcs12",          "-p", 0},
#endif
                {"--help",            "-h", 0},
                {NULL, NULL, 0}
        };

        certfile = NULL;
        certfile_format = 0;
        for( i = 1; i < argc ; i++ ) {
                switch( eurephia_getopt(&i, argc, argv, addcertargs) ) {
                case 'd': // Certificate depth

                        // Check if argument is a number
                        chk = 1;
                        for( j = 0; j < strlen_nullsafe(optargs[0]); j++ ) {
                                if( !isdigit(optargs[0][j]) ) {
                                        chk = 0;
                                        break;
                                }
                        }
                        if( chk == 0 )  {
                                fprintf(stderr, "%s: Certificate depth must be a number\n", MODULE);
                                return 1;
                        }

                        depth = atoi_nullsafe(optargs[0]);
                        if( (depth < 0) || (depth > 99) ) {
                                fprintf(stderr, "%s: Certificate depth must be between 0-99\n", MODULE);
                                return 1;
                        }
                        break;

                case 'D': // Certificate digest
                        if( strlen_nullsafe(optargs[0]) < 59 ) {
                                fprintf(stderr, "%s: Certificate digest is too short\n", MODULE);
                                return 1;
                        }
                        digest = strdup_nullsafe(optargs[0]);
                        break;
                case 'C': // Certificate - common_name / CN
                        cname = strdup_nullsafe(optargs[0]);
                        break;
                case 'O': // Certificate - organisation / O
                        org = strdup_nullsafe(optargs[0]);
                        break;
                case 'E': // Certificate - e-mail / emailAddr
                        email = strdup_nullsafe(optargs[0]);
                        break;

#ifdef HAVE_OPENSSL
                case 'p': // Certfile is in PKCS#12 format
                        certfile_format = 1;
                        break;

                case 'f': // Load certificate info from a certificate file
                        if( strlen_nullsafe(optargs[0]) < 1 ) {
                                fprintf(stderr, "%s: certfile is too short\n", MODULE);
                                return 1;
                        }
                        certfile = optargs[0];

                        if( stat(certfile, &cert_stat) == -1 ) {
                                fprintf(stderr, "%s: Could not access certfile: %s (%s)\n", MODULE,
                                        certfile, strerror(errno));
                                return 1;
                        }

                        if( cert_stat.st_size == 0 ) {
                                fprintf(stderr, "%s: certfile '%s' is empty\n", MODULE, certfile);
                                return 1;
                        }
                        break;
#endif
                case 'h':
                        display_certs_help('A');
                        break;
                default:
                        return 2;
                }
        }

        // Sanity check of input parameters
        if( depth < 0 ) {
                fprintf(stderr, "%s: You must set certificate depth (possibly, it needs to be 0)\n", MODULE);
                return 1;
        }

        if( (certfile != NULL) && ((digest != NULL) || (cname != NULL) || (org != NULL) || (email != NULL)) ){
                fprintf(stderr,
                        "%s: You cannot combine --certfile with --depth, --common-name,\n"
                        "--organisation or --email\n", MODULE);
                return 1;
        }

        if( (certfile == NULL) && ((digest == NULL) || (cname == NULL) || (org == NULL) || (email == NULL)) ) {
                fprintf(stderr,
                        "%s: You must use either --certfile or --depth, --common-name,\n"
                        "--organisation and --email\n", MODULE);
                return 1;
        }

#ifdef HAVE_OPENSSL
        // If we have a certfile - open it and fetch the info we want
        if( certfile != NULL ) {
                BIO *bio_err = NULL;
                PKCS12 *p12 = NULL;
                EVP_PKEY *pkey = NULL;
                X509 *cert = NULL;
                FILE *fp;

                /* 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 0: // 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 3;
                        }
                        fclose(fp);
                        break;

                case 1: // 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 3;
                        }
                        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 3;
                                }
                        }
                        EVP_PKEY_free(pkey); pkey = NULL;
                        PKCS12_free(p12); p12 = NULL;
                        break;

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


                // extract SHA1 digest from certificate
                digest = (char *) malloc(66);
                memset(digest, 0, 66);
                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++) {
                                digest[j * 3] = hexcodes[(md_sha1[j] & 0xf0) >> 4U];
                                digest[(j * 3) + 1] = hexcodes[(md_sha1[j] & 0x0f)];
                                if (j + 1 != (int) mdlen) {
                                        digest[(j * 3) + 2] = ':';
                                } else {
                                        digest[(j * 3) + 2] = '\0';
                                }
                        }
                }

                // Extract the subject information we want
                cname = ExtractCertInfo(cert, "CN");
                org   = ExtractCertInfo(cert, "O");
                email = ExtractCertInfo(cert, "emailAddress");

                X509_free(cert);
                BIO_free(bio_err);
        }
#endif
        rc = register_certificate(ctx, depth, digest, cname, org, email);
        free_nullsafe(digest);
        free_nullsafe(cname);
        free_nullsafe(org);
        free_nullsafe(email);
        return rc;
}


int cmd_Certificates(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        char **mode_argv;
        int i, mode_argc = 0, rc = 0;
        int (*mode_fnc) (eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv);

        e_options modeargs[] = {
                {"--list", "-l", 0},
                {"--show", "-s", 0},
                {"--add", "-A", 0},
                {"--delete", "-D", 0},
                {"--help", "-h", 0},
                {NULL, NULL, 0}
        };

        assert((ctx != NULL) && (ctx->dbc != NULL) && (ctx->dbc->config != NULL));
        mode_fnc = NULL;
        for( i = 1; i < argc; i++ ) {
                switch( eurephia_getopt(&i, argc, argv, modeargs) ) {
                case 'l':
                        // mode_fnc = list_certs;
                        break;

                case 's':
                        // mode_fnc = show_certs;
                        break;

                case 'h':
                        mode_fnc = help_Certificates2;
                        break;

                case 'A':
                        mode_fnc = add_cert;
                        break;

                case 'D':
                        // mode_fnc = delete_cert;
                        break;

                default:
                        break;
                }
                if( mode_fnc != NULL ) {
                        break;
                }
        }

        // If we do not have any known mode defined, exit with error
        if( mode_fnc == NULL )  {
                fprintf(stderr, "%s: Unknown argument.  No mode given\n", MODULE);
                return 1;
        }

        // Allocate memory for our arguments being sent to the mode function
        mode_argv = (char **) calloc(sizeof(char *), (argc - i)+2);
        assert(mode_argv != NULL);

        // Copy over only the arguments needed for the mode
        mode_argc = eurephia_arraycp(i, argc, argv, mode_argv, (argc - i));

        // Call the mode function
        rc = mode_fnc(ctx, sess, cfg, mode_argc, mode_argv);
        free_nullsafe(mode_argv);

        return rc;
}