1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stddef.h>
4 #include <stdio.h>
5
6 #if HAVE_GNUTLS
7 #include <gnutls/gnutls.h>
8 #include <gnutls/x509.h>
9 #endif
10
11 #include "alloc-util.h"
12 #include "log.h"
13 #include "macro.h"
14 #include "microhttpd-util.h"
15 #include "string-util.h"
16 #include "strv.h"
17 #include "util.h"
18
microhttpd_logger(void * arg,const char * fmt,va_list ap)19 void microhttpd_logger(void *arg, const char *fmt, va_list ap) {
20 char *f;
21
22 f = strjoina("microhttpd: ", fmt);
23
24 DISABLE_WARNING_FORMAT_NONLITERAL;
25 log_internalv(LOG_INFO, 0, NULL, 0, NULL, f, ap);
26 REENABLE_WARNING;
27 }
28
mhd_respond_internal(struct MHD_Connection * connection,enum MHD_RequestTerminationCode code,const char * buffer,size_t size,enum MHD_ResponseMemoryMode mode)29 static int mhd_respond_internal(struct MHD_Connection *connection,
30 enum MHD_RequestTerminationCode code,
31 const char *buffer,
32 size_t size,
33 enum MHD_ResponseMemoryMode mode) {
34 assert(connection);
35
36 _cleanup_(MHD_destroy_responsep) struct MHD_Response *response
37 = MHD_create_response_from_buffer(size, (char*) buffer, mode);
38 if (!response)
39 return MHD_NO;
40
41 log_debug("Queueing response %u: %s", code, buffer);
42 if (MHD_add_response_header(response, "Content-Type", "text/plain") == MHD_NO)
43 return MHD_NO;
44 return MHD_queue_response(connection, code, response);
45 }
46
mhd_respond(struct MHD_Connection * connection,enum MHD_RequestTerminationCode code,const char * message)47 int mhd_respond(struct MHD_Connection *connection,
48 enum MHD_RequestTerminationCode code,
49 const char *message) {
50
51 const char *fmt;
52
53 fmt = strjoina(message, "\n");
54
55 return mhd_respond_internal(connection, code,
56 fmt, strlen(message) + 1,
57 MHD_RESPMEM_PERSISTENT);
58 }
59
mhd_respond_oom(struct MHD_Connection * connection)60 int mhd_respond_oom(struct MHD_Connection *connection) {
61 return mhd_respond(connection, MHD_HTTP_SERVICE_UNAVAILABLE, "Out of memory.");
62 }
63
mhd_respondf(struct MHD_Connection * connection,int error,enum MHD_RequestTerminationCode code,const char * format,...)64 int mhd_respondf(struct MHD_Connection *connection,
65 int error,
66 enum MHD_RequestTerminationCode code,
67 const char *format, ...) {
68
69 const char *fmt;
70 char *m;
71 int r;
72 va_list ap;
73
74 assert(connection);
75 assert(format);
76
77 if (error < 0)
78 error = -error;
79 errno = -error;
80 fmt = strjoina(format, "\n");
81 va_start(ap, format);
82 DISABLE_WARNING_FORMAT_NONLITERAL;
83 r = vasprintf(&m, fmt, ap);
84 REENABLE_WARNING;
85 va_end(ap);
86
87 if (r < 0)
88 return respond_oom(connection);
89
90 return mhd_respond_internal(connection, code, m, r, MHD_RESPMEM_MUST_FREE);
91 }
92
93 #if HAVE_GNUTLS
94
95 static struct {
96 const char *const names[4];
97 int level;
98 bool enabled;
99 } gnutls_log_map[] = {
100 { {"0"}, LOG_DEBUG },
101 { {"1", "audit"}, LOG_WARNING, true}, /* gnutls session audit */
102 { {"2", "assert"}, LOG_DEBUG }, /* gnutls assert log */
103 { {"3", "hsk", "ext"}, LOG_DEBUG }, /* gnutls handshake log */
104 { {"4", "rec"}, LOG_DEBUG }, /* gnutls record log */
105 { {"5", "dtls"}, LOG_DEBUG }, /* gnutls DTLS log */
106 { {"6", "buf"}, LOG_DEBUG },
107 { {"7", "write", "read"}, LOG_DEBUG },
108 { {"8"}, LOG_DEBUG },
109 { {"9", "enc", "int"}, LOG_DEBUG },
110 };
111
log_func_gnutls(int level,const char * message)112 static void log_func_gnutls(int level, const char *message) {
113 assert_se(message);
114
115 if (0 <= level && level < (int) ELEMENTSOF(gnutls_log_map)) {
116 if (gnutls_log_map[level].enabled)
117 log_internal(gnutls_log_map[level].level, 0, NULL, 0, NULL, "gnutls %d/%s: %s", level, gnutls_log_map[level].names[1], message);
118 } else {
119 log_debug("Received GNUTLS message with unknown level %d.", level);
120 log_internal(LOG_DEBUG, 0, NULL, 0, NULL, "gnutls: %s", message);
121 }
122 }
123
log_reset_gnutls_level(void)124 static void log_reset_gnutls_level(void) {
125 int i;
126
127 for (i = ELEMENTSOF(gnutls_log_map) - 1; i >= 0; i--)
128 if (gnutls_log_map[i].enabled) {
129 log_debug("Setting gnutls log level to %d", i);
130 gnutls_global_set_log_level(i);
131 break;
132 }
133 }
134
log_enable_gnutls_category(const char * cat)135 static int log_enable_gnutls_category(const char *cat) {
136 unsigned i;
137
138 if (streq(cat, "all")) {
139 for (i = 0; i < ELEMENTSOF(gnutls_log_map); i++)
140 gnutls_log_map[i].enabled = true;
141 log_reset_gnutls_level();
142 return 0;
143 } else
144 for (i = 0; i < ELEMENTSOF(gnutls_log_map); i++)
145 if (strv_contains((char**)gnutls_log_map[i].names, cat)) {
146 gnutls_log_map[i].enabled = true;
147 log_reset_gnutls_level();
148 return 0;
149 }
150 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No such log category: %s", cat);
151 }
152
setup_gnutls_logger(char ** categories)153 int setup_gnutls_logger(char **categories) {
154 int r;
155
156 gnutls_global_set_log_function(log_func_gnutls);
157
158 if (categories)
159 STRV_FOREACH(cat, categories) {
160 r = log_enable_gnutls_category(*cat);
161 if (r < 0)
162 return r;
163 }
164 else
165 log_reset_gnutls_level();
166
167 return 0;
168 }
169
verify_cert_authorized(gnutls_session_t session)170 static int verify_cert_authorized(gnutls_session_t session) {
171 unsigned status;
172 gnutls_certificate_type_t type;
173 gnutls_datum_t out;
174 int r;
175
176 r = gnutls_certificate_verify_peers2(session, &status);
177 if (r < 0)
178 return log_error_errno(r, "gnutls_certificate_verify_peers2 failed: %m");
179
180 type = gnutls_certificate_type_get(session);
181 r = gnutls_certificate_verification_status_print(status, type, &out, 0);
182 if (r < 0)
183 return log_error_errno(r, "gnutls_certificate_verification_status_print failed: %m");
184
185 log_debug("Certificate status: %s", out.data);
186 gnutls_free(out.data);
187
188 return status == 0 ? 0 : -EPERM;
189 }
190
get_client_cert(gnutls_session_t session,gnutls_x509_crt_t * client_cert)191 static int get_client_cert(gnutls_session_t session, gnutls_x509_crt_t *client_cert) {
192 const gnutls_datum_t *pcert;
193 unsigned listsize;
194 gnutls_x509_crt_t cert;
195 int r;
196
197 assert(session);
198 assert(client_cert);
199
200 pcert = gnutls_certificate_get_peers(session, &listsize);
201 if (!pcert || !listsize)
202 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
203 "Failed to retrieve certificate chain");
204
205 r = gnutls_x509_crt_init(&cert);
206 if (r < 0) {
207 log_error("Failed to initialize client certificate");
208 return r;
209 }
210
211 /* Note that by passing values between 0 and listsize here, you
212 can get access to the CA's certs */
213 r = gnutls_x509_crt_import(cert, &pcert[0], GNUTLS_X509_FMT_DER);
214 if (r < 0) {
215 log_error("Failed to import client certificate");
216 gnutls_x509_crt_deinit(cert);
217 return r;
218 }
219
220 *client_cert = cert;
221 return 0;
222 }
223
get_auth_dn(gnutls_x509_crt_t client_cert,char ** buf)224 static int get_auth_dn(gnutls_x509_crt_t client_cert, char **buf) {
225 size_t len = 0;
226 int r;
227
228 assert(buf);
229 assert(*buf == NULL);
230
231 r = gnutls_x509_crt_get_dn(client_cert, NULL, &len);
232 if (r != GNUTLS_E_SHORT_MEMORY_BUFFER) {
233 log_error("gnutls_x509_crt_get_dn failed");
234 return r;
235 }
236
237 *buf = malloc(len);
238 if (!*buf)
239 return log_oom();
240
241 gnutls_x509_crt_get_dn(client_cert, *buf, &len);
242 return 0;
243 }
244
gnutls_x509_crt_deinitp(gnutls_x509_crt_t * p)245 static void gnutls_x509_crt_deinitp(gnutls_x509_crt_t *p) {
246 gnutls_x509_crt_deinit(*p);
247 }
248
check_permissions(struct MHD_Connection * connection,int * code,char ** hostname)249 int check_permissions(struct MHD_Connection *connection, int *code, char **hostname) {
250 const union MHD_ConnectionInfo *ci;
251 gnutls_session_t session;
252 _cleanup_(gnutls_x509_crt_deinitp) gnutls_x509_crt_t client_cert = NULL;
253 _cleanup_free_ char *buf = NULL;
254 int r;
255
256 assert(connection);
257 assert(code);
258
259 *code = 0;
260
261 ci = MHD_get_connection_info(connection,
262 MHD_CONNECTION_INFO_GNUTLS_SESSION);
263 if (!ci) {
264 log_error("MHD_get_connection_info failed: session is unencrypted");
265 *code = mhd_respond(connection, MHD_HTTP_FORBIDDEN,
266 "Encrypted connection is required");
267 return -EPERM;
268 }
269 session = ci->tls_session;
270 assert(session);
271
272 r = get_client_cert(session, &client_cert);
273 if (r < 0) {
274 *code = mhd_respond(connection, MHD_HTTP_UNAUTHORIZED,
275 "Authorization through certificate is required");
276 return -EPERM;
277 }
278
279 r = get_auth_dn(client_cert, &buf);
280 if (r < 0) {
281 *code = mhd_respond(connection, MHD_HTTP_UNAUTHORIZED,
282 "Failed to determine distinguished name from certificate");
283 return -EPERM;
284 }
285
286 log_debug("Connection from %s", buf);
287
288 if (hostname)
289 *hostname = TAKE_PTR(buf);
290
291 r = verify_cert_authorized(session);
292 if (r < 0) {
293 log_warning("Client is not authorized");
294 *code = mhd_respond(connection, MHD_HTTP_UNAUTHORIZED,
295 "Client certificate not signed by recognized authority");
296 }
297 return r;
298 }
299
300 #else
check_permissions(struct MHD_Connection * connection,int * code,char ** hostname)301 int check_permissions(struct MHD_Connection *connection, int *code, char **hostname) {
302 assert_not_reached();
303 }
304
setup_gnutls_logger(char ** categories)305 int setup_gnutls_logger(char **categories) {
306 if (categories)
307 log_notice("Ignoring specified gnutls logging categories — gnutls not available.");
308 return 0;
309 }
310 #endif
311