charon-cmd: load certificates and RSA private keys
[strongswan.git] / src / charon-cmd / cmd / cmd_creds.c
1 /*
2 * Copyright (C) 2013 Martin Willi
3 * Copyright (C) 2013 revosec AG
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include "cmd_creds.h"
17
18 #include <utils/debug.h>
19 #include <credentials/sets/mem_cred.h>
20
21 typedef struct private_cmd_creds_t private_cmd_creds_t;
22
23 /**
24 * Private data of an cmd_creds_t object.
25 */
26 struct private_cmd_creds_t {
27
28 /**
29 * Public cmd_creds_t interface.
30 */
31 cmd_creds_t public;
32
33 /**
34 * Reused in-memory credential set
35 */
36 mem_cred_t *creds;
37 };
38
39 /**
40 * Load a trusted certificate from path
41 */
42 static void load_cert(private_cmd_creds_t *this, char *path)
43 {
44 certificate_t *cert;
45
46 cert = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
47 BUILD_FROM_FILE, path, BUILD_END);
48 if (!cert)
49 {
50 DBG1(DBG_CFG, "loading certificate from '%s' failed", path);
51 exit(1);
52 }
53 this->creds->add_cert(this->creds, TRUE, cert);
54 }
55
56 /**
57 * Load a private key of given kind from path
58 */
59 static void load_key(private_cmd_creds_t *this, key_type_t type, char *path)
60 {
61 private_key_t *privkey;
62
63 privkey = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, type,
64 BUILD_FROM_FILE, path, BUILD_END);
65 if (!privkey)
66 {
67 DBG1(DBG_CFG, "loading %N private key from '%s' failed",
68 key_type_names, type, path);
69 exit(1);
70 }
71 this->creds->add_key(this->creds, privkey);
72 }
73
74 METHOD(cmd_creds_t, handle, bool,
75 private_cmd_creds_t *this, cmd_option_type_t opt, char *arg)
76 {
77 switch (opt)
78 {
79 case CMD_OPT_CERT:
80 load_cert(this, arg);
81 break;
82 case CMD_OPT_RSA:
83 load_key(this, KEY_RSA, arg);
84 break;
85 default:
86 return FALSE;
87 }
88 return TRUE;
89 }
90
91 METHOD(cmd_creds_t, destroy, void,
92 private_cmd_creds_t *this)
93 {
94 lib->credmgr->remove_set(lib->credmgr, &this->creds->set);
95 this->creds->destroy(this->creds);
96 free(this);
97 }
98
99 /**
100 * See header
101 */
102 cmd_creds_t *cmd_creds_create()
103 {
104 private_cmd_creds_t *this;
105
106 INIT(this,
107 .public = {
108 .handle = _handle,
109 .destroy = _destroy,
110 },
111 .creds = mem_cred_create(),
112 );
113
114 lib->credmgr->add_set(lib->credmgr, &this->creds->set);
115
116 return &this->public;
117 }