summaryrefslogtreecommitdiffstats
path: root/database/sqlite/administration/usercerts.c
blob: c6f368e63ca66860d3b3fbf276db77067e1c2a3f (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
/* usercerts.c  --  Admin functions - user-certificate table
 *
 *  GPLv2 only - Copyright (C) 2008 - 2010
 *               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   sqlite/administration/usercerts.c
 * @author David Sommerseth <dazo@users.sourceforge.net>
 * @date   2009-08-29
 *
 * @brief  Functions for working with the openvpn_usercerts table
 *
 */

#include <string.h>
#include <unistd.h>
#include <assert.h>

#include <libxml/tree.h>

#include <sqlite3.h>

#include <eurephia_nullsafe.h>
#include <eurephia_context.h>
#include <eurephia_log.h>
#include <eurephia_xml.h>
#include <eurephia_values.h>
#include <eurephiadb_session_struct.h>
#include <eurephiadb_mapping.h>

#include "../sqlite.h"

#define FMAP_USERCERTS
#include "../fieldmapping.h"


/**
 * Internal function.  Queries the database for a list of user-certificate links
 *
 * @param ctx      eurephiaCTX
 * @param where_m  eDBfieldMap containing the search criteria
 * @param sortkeys String containing the sort order of the data
 *
 * @return Returns a valid eurephia XML document on success, otherwise NULL
 */
xmlDoc *usercerts_search(eurephiaCTX *ctx, eDBfieldMap *where_m, const char *sortkeys) {
        xmlDoc *list_xml = NULL;
        xmlNode *link_root_n = NULL, *link_n = NULL, *tmp_n = NULL;
        dbresult *res = NULL;
        xmlChar tmp[2050];
        const char *dbsort = NULL;
        int i;

        DEBUG(ctx, 21, "Function call: usercerts_search(ctx, eDBfieldMap, '%s')", sortkeys);
        assert( ctx != NULL );

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return NULL;
        }

        if( sortkeys != NULL ) {
                dbsort = eDBmkSortKeyString(where_m, sortkeys);
        }

        res = sqlite_query_mapped(ctx, SQL_SELECT,
                                  "SELECT uicid, ucs.uid AS uid, certid, locdt(ucs.registered) AS registered,"
                                  "       ucs.accessprofile AS accessprofile, access_descr,"
                                  "       username, "
                                  "       common_name, organisation, email, lower(digest), depth "
                                  "  FROM openvpn_usercerts ucs"
                                  "  LEFT JOIN openvpn_certificates USING(certid)"
                                  "  LEFT JOIN openvpn_accesses acc ON(ucs.accessprofile = acc.accessprofile)"
                                  "  LEFT JOIN openvpn_users u ON(u.uid = ucs.uid)",
                                  NULL, // values (not used for SELECT)
                                  where_m, // fields and values for the WHERE clause
                                  dbsort);
        if( sqlite_query_status(res) != dbSUCCESS ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not query the usercerts table");
                sqlite_log_error(ctx, res);
                sqlite_free_results(res);
                return NULL;
        }

        memset(&tmp, 0, 2050);
        eurephiaXML_CreateDoc(ctx, 1, "usercerts", &list_xml, &link_root_n);
        xmlStrPrintf(tmp, 64, (xmlChar *) "%i", sqlite_get_numtuples(res));
        xmlNewProp(link_root_n, (xmlChar *) "link_count", (xmlChar *) tmp);

        for( i = 0; i < sqlite_get_numtuples(res); i++ ) {
                link_n = xmlNewChild(link_root_n, NULL, (xmlChar *) "usercert_link", NULL);

                sqlite_xml_value(link_n, XML_ATTR, "uicid", res, i, 0);
                sqlite_xml_value(link_n, XML_ATTR, "registered", res, i, 3);

                tmp_n = sqlite_xml_value(link_n, XML_NODE, "username", res, i, 6);
                sqlite_xml_value(tmp_n, XML_ATTR, "uid", res, i, 1);

                tmp_n = xmlNewChild(link_n, NULL, (xmlChar *) "certificate", NULL);
                sqlite_xml_value(tmp_n, XML_ATTR, "certid", res, i, 2);
                sqlite_xml_value(tmp_n, XML_ATTR, "depth", res, i, 11);

                xmlStrPrintf(tmp, 2048, (xmlChar *) "%.2048s", sqlite_get_value(res, i, 7));
                xmlReplaceChars(tmp, '_', ' ');
                xmlNewChild(tmp_n, NULL, (xmlChar *) "common_name", tmp);

                xmlStrPrintf(tmp, 2048, (xmlChar *) "%.2048s", sqlite_get_value(res, i, 8));
                xmlReplaceChars(tmp, '_', ' ');
                xmlNewChild(tmp_n, NULL, (xmlChar *) "organisation", tmp);

                sqlite_xml_value(tmp_n, XML_NODE, "email", res, i, 9);
                sqlite_xml_value(tmp_n, XML_NODE, "digest", res, i, 10);

                tmp_n = sqlite_xml_value(link_n, XML_NODE, "access_profile", res, i, 5);
                sqlite_xml_value(tmp_n, XML_ATTR, "accessprofile", res, i, 4);
        }
        sqlite_free_results(res);

        return list_xml;
}


/**
 * Internal function.  Adds or deletes a user-certificate link
 *
 * @param ctx       eurephiaCTX
 * @param mode      String containing the operation mode.  Must be "register" or "remove"
 * @param usrcrt_m  eDBfieldMap containing information about the link to add or remove
 *
 * @return Returns an eurephia ResultMsg XML document, with success message or an error message
 */
xmlDoc *usercerts_add_del(eurephiaCTX *ctx, const char *mode, eDBfieldMap *usrcrt_m) {
        xmlDoc *res = NULL;
        dbresult *dbres = NULL;

        DEBUG(ctx, 21, "Function call: usercerts_add_del(ctx, xmlDoc)");
        assert( (ctx != NULL) && (usrcrt_m != NULL) );

        if( strcmp(mode, "register") == 0 ) {
                dbres = sqlite_query_mapped(ctx, SQL_INSERT,
                                            "INSERT INTO openvpn_usercerts", usrcrt_m, NULL, NULL);
                if( sqlite_query_status(dbres) == dbSUCCESS ) {
                        res = eurephiaXML_ResultMsg(ctx, exmlRESULT, NULL,
                                                    "Registered new user-cert link with id %i",
                                                    dbres->last_insert_id);
                }
        } else if( strcmp(mode, "remove") == 0 ) {
                dbres = sqlite_query_mapped(ctx, SQL_DELETE,
                                            "DELETE FROM openvpn_usercerts", NULL, usrcrt_m, NULL);
                if( sqlite_query_status(dbres) == dbSUCCESS ) {
                        int num_rows = sqlite_get_affected_rows(dbres);
                        if( num_rows > 0 ) {
                                res = eurephiaXML_ResultMsg(ctx, exmlRESULT, NULL,
                                                            "Removed %i user-cert %s successfully",
                                                            num_rows, (num_rows == 1 ? "link" : "links"));
                        } else {
                                res = eurephiaXML_ResultMsg(ctx, exmlERROR, NULL,
                                                            "No user-cert links where removed");
                        }
                }
        }

        if( sqlite_query_status(dbres) != dbSUCCESS ) {
                xmlNode *tmp_n = NULL;

                eurephia_log(ctx, LOG_ERROR, 0, "Failed to %s user-cert link.", mode);
                tmp_n = sqlite_log_error_xml(ctx, dbres);
                res = eurephiaXML_ResultMsg(ctx, exmlERROR, tmp_n, "Failed to %s user-cert link", mode);
                xmlFreeNode(tmp_n);
        }
        sqlite_free_results(dbres);

        return res;
}


/**
 * Internal function.  Updates a user-certs link in the database
 *
 * @param ctx      eurephiaCTX
 * @param uicid    String containing the numeric record ID (uicid field) of the record to be updated
 * @param usrcrt_m eDBfieldMap containing the new information for the record.  Only the fields being
 *                 changed needs to be set.
 *
 * @return Returns an eurephia ResultMsg XML document, with success message or an error message
 */
xmlDoc *usercerts_update(eurephiaCTX *ctx, const char *uicid, eDBfieldMap *usrcrt_m) {
        xmlNode *where_n = NULL;
        eDBfieldMap *where_m = NULL;
        dbresult *dbres = NULL;
        xmlDoc *where_d = NULL, *res = NULL;

        DEBUG(ctx, 21, "Function call: usercerts_update(ctx, '%s', eDBfieldMap)", uicid);
        assert( ctx != NULL && uicid != NULL && usrcrt_m != NULL );

        // Create a eDBfieldMap which will contain the uicid value
        eurephiaXML_CreateDoc(ctx, 1, "usercerts", &where_d, &where_n);
        assert( (where_d != NULL) && (where_n != NULL) );

        where_n = xmlNewChild(where_n, NULL, (xmlChar *) "fieldMapping", NULL);
        xmlNewProp(where_n, (xmlChar *) "table", (xmlChar *) "usercerts");
        xmlNewChild(where_n, NULL, (xmlChar *) "uicid", (xmlChar *) uicid);

        // Convert xmlNode with fieldMapping into a eDBfieldMap
        where_m = eDBxmlMapping(ctx, tbl_sqlite_usercerts, NULL, where_n);
        assert( where_m != NULL );

        // Send update query to the database
        dbres = sqlite_query_mapped(ctx, SQL_UPDATE, "UPDATE openvpn_usercerts",
                                    usrcrt_m, where_m, NULL);
        if( sqlite_query_status(dbres) == dbSUCCESS ) {
                int num_rows = sqlite_get_affected_rows(dbres);
                if( num_rows > 0 ) {
                        res = eurephiaXML_ResultMsg(ctx, exmlRESULT, NULL,
                                                    "Updated firewall access profile on %i user-cert %s.",
                                                    num_rows, (num_rows == 1 ? "link" : "links"));
                } else {
                        res = eurephiaXML_ResultMsg(ctx, exmlERROR, NULL,
                                                    "No user-cert links where updated");
                }
        } else {
                xmlNode *err_n = NULL;

                eurephia_log(ctx, LOG_ERROR, 0, "Failed to update user-cert link.(uicid: %s)", uicid);
                err_n = sqlite_log_error_xml(ctx, dbres);
                res = eurephiaXML_ResultMsg(ctx, exmlERROR, err_n,
                                            "Failed to update user-cert link for uicid %s", uicid);
                xmlFreeNode(err_n);
        }
        sqlite_free_results(dbres);
        eDBfreeMapping(where_m);
        xmlFreeDoc(where_d);

        return res;
}


/**
 * @copydoc eDBadminUserCertsLink()
 */
xmlDoc *eDBadminUserCertsLink(eurephiaCTX *ctx, xmlDoc *usrcrt_xml) {
        xmlNode *usrcrt_n = NULL, *tmp_n = NULL;
        xmlDoc *resxml = NULL;
        eDBfieldMap *usrcrt_m = NULL;
        const char *mode = NULL, *sortfields = NULL, *uicid = NULL;

        DEBUG(ctx, 20, "Function call: eDBadminUserCertsLink(ctx, xmlDoc)");
        assert( (ctx != NULL) && (usrcrt_xml != NULL) );

        if( (ctx->context_type != ECTX_ADMIN_CONSOLE) && (ctx->context_type != ECTX_ADMIN_WEB) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0,
                             "eurephia admin function call attempted with wrong context type");
                return 0;
        }

        usrcrt_n = eurephiaXML_getRoot(ctx, usrcrt_xml, "usercerts", 1);
        if( usrcrt_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Could not find a valid XML for the user-certs link request");
                return 0;
        }
        mode = xmlGetAttrValue(usrcrt_n->properties, "mode");
        if( mode == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Invalid user-cert link request (1).");
                return 0;
        }

        tmp_n = xmlFindNode(usrcrt_n, "sortfields");
        if( tmp_n ) {
                sortfields = xmlExtractContent(tmp_n);
        }

        tmp_n = xmlFindNode(usrcrt_n, "fieldMapping");
        if( tmp_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "Invalid user-cert link request (2).");
                return 0;
        }
        usrcrt_m = eDBxmlMapping(ctx, tbl_sqlite_usercerts, NULL, tmp_n);
        assert(usrcrt_m != NULL);


        if( strcmp(mode, "search") == 0 ) {
                resxml = usercerts_search(ctx, usrcrt_m, sortfields);
        } else if( strcmp(mode, "register") == 0 ) {
                resxml = usercerts_add_del(ctx, mode, usrcrt_m);
        } else if( strcmp(mode, "remove") == 0 ) {
                resxml = usercerts_add_del(ctx, mode, usrcrt_m);
        } else if( strcmp(mode, "update") == 0 ) {
                uicid = xmlGetAttrValue(usrcrt_n->properties, "uicid");
                if( uicid == NULL ) {
                        eurephia_log(ctx, LOG_ERROR, 0, "Missing required attribute, uicid, for updates");
                        resxml = eurephiaXML_ResultMsg(ctx, exmlERROR, NULL,
                                                       "Can not set firewall access profile without uicid");
                        goto exit;
                }
                resxml = usercerts_update(ctx, uicid, usrcrt_m);
        }

 exit:
        eDBfreeMapping(usrcrt_m);
        return resxml;
}