4 * (c) 2007 Martin Mares <mj@ucw.cz>
11 #include "lib/getopt.h"
18 #include <sys/types.h>
19 #include <sys/socket.h>
21 #include <arpa/inet.h>
22 #include <netinet/in.h>
26 /*** CONFIGURATION ***/
28 static uns port = 8888;
29 static uns dh_bits = 1024;
30 static uns max_conn = 10;
31 static uns session_timeout;
32 static byte *ca_cert_name = "?";
33 static byte *server_cert_name = "?";
34 static byte *server_key_name = "?";
35 static clist access_rules;
38 uns max_attachment_size;
41 static struct cf_section access_conf = {
42 CF_TYPE(struct access_rule),
44 CF_USER("IP", PTR_TO(struct access_rule, addrmask), &ip_addrmask_type),
45 CF_UNS("Admin", PTR_TO(struct access_rule, allow_admin)),
46 CF_UNS("PlainText", PTR_TO(struct access_rule, plain_text)),
47 CF_UNS("MaxConn", PTR_TO(struct access_rule, max_conn)),
52 static struct cf_section submitd_conf = {
54 CF_UNS("Port", &port),
55 CF_UNS("DHBits", &dh_bits),
56 CF_UNS("MaxConn", &max_conn),
57 CF_UNS("SessionTimeout", &session_timeout),
58 CF_UNS("MaxRequestSize", &max_request_size),
59 CF_UNS("MaxAttachSize", &max_attachment_size),
60 CF_STRING("CACert", &ca_cert_name),
61 CF_STRING("ServerCert", &server_cert_name),
62 CF_STRING("ServerKey", &server_key_name),
63 CF_LIST("Access", &access_rules, &access_conf),
64 CF_UNS("TraceTLS", &trace_tls),
65 CF_UNS("TraceCommands", &trace_commands),
72 static clist connections;
73 static uns last_conn_id;
79 clist_init(&connections);
85 struct conn *c = xmalloc_zero(sizeof(*c));
86 c->id = ++last_conn_id;
87 clist_add_tail(&connections, &c->n);
93 conn_free(struct conn *c)
102 static struct access_rule *
105 CLIST_FOR_EACH(struct access_rule *, r, access_rules)
106 if (ip_addrmask_match(&r->addrmask, ip))
115 CLIST_FOR_EACH(struct conn *, c, connections)
123 static gnutls_certificate_credentials_t cert_cred;
124 static gnutls_dh_params_t dh_params;
126 #define TLS_CHECK(name) if (err < 0) die(#name " failed: %s", gnutls_strerror(err))
133 gnutls_global_init();
134 err = gnutls_certificate_allocate_credentials(&cert_cred);
135 TLS_CHECK(gnutls_certificate_allocate_credentials);
136 err = gnutls_certificate_set_x509_trust_file(cert_cred, ca_cert_name, GNUTLS_X509_FMT_PEM);
138 die("No CA certificate found");
140 die("Unable to load X509 trust file: %s", gnutls_strerror(err));
141 err = gnutls_certificate_set_x509_key_file(cert_cred, server_cert_name, server_key_name, GNUTLS_X509_FMT_PEM);
143 die("Unable to load X509 key file: %s", gnutls_strerror(err));
145 err = gnutls_dh_params_init(&dh_params); TLS_CHECK(gnutls_dh_params_init);
146 err = gnutls_dh_params_generate2(dh_params, dh_bits); TLS_CHECK(gnutls_dh_params_generate2);
147 gnutls_certificate_set_dh_params(cert_cred, dh_params);
150 static gnutls_session_t
151 tls_new_session(int sk)
156 err = gnutls_init(&s, GNUTLS_SERVER); TLS_CHECK(gnutls_init);
157 err = gnutls_set_default_priority(s); TLS_CHECK(gnutls_set_default_priority); // FIXME
158 gnutls_credentials_set(s, GNUTLS_CRD_CERTIFICATE, cert_cred);
159 gnutls_certificate_server_set_request(s, GNUTLS_CERT_REQUEST);
160 gnutls_dh_set_prime_bits(s, dh_bits);
161 gnutls_transport_set_ptr(s, (gnutls_transport_ptr_t) sk);
166 tls_verify_cert(struct conn *c)
168 gnutls_session_t s = c->tls;
169 uns status, num_certs;
171 gnutls_x509_crt_t cert;
172 const gnutls_datum_t *certs;
174 DBG("Verifying peer certificates");
175 err = gnutls_certificate_verify_peers2(s, &status);
177 return gnutls_strerror(err);
178 DBG("Verify status: %04x", status);
179 if (status & GNUTLS_CERT_INVALID)
180 return "Certificate is invalid";
181 /* XXX: We do not handle revokation. */
182 if (gnutls_certificate_type_get(s) != GNUTLS_CRT_X509)
183 return "Certificate is not X509";
185 err = gnutls_x509_crt_init(&cert);
187 return "gnutls_x509_crt_init() failed";
188 certs = gnutls_certificate_get_peers(s, &num_certs);
190 return "No peer certificate found";
191 DBG("Got certificate list with %d peers", num_certs);
193 err = gnutls_x509_crt_import(cert, &certs[0], GNUTLS_X509_FMT_DER);
195 return "Cannot import certificate";
196 /* XXX: We do not check expiration and activation since the keys are generated for a single contest only anyway. */
199 size_t dn_len = sizeof(dn);
200 err = gnutls_x509_crt_get_dn_by_oid(cert, GNUTLS_OID_X520_COMMON_NAME, 0, 0, dn, &dn_len);
202 return "Cannot retrieve common name";
204 log(L_INFO, "Cert CN: %s", dn);
205 c->cert_name = xstrdup(dn);
207 /* Check certificate purpose */
212 size_t purp_len = sizeof(purp);
214 err = gnutls_x509_crt_get_key_purpose_oid(cert, purpi++, purp, &purp_len, &crit);
215 if (err == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
216 return "Not a client certificate";
217 TLS_CHECK(gnutls_x509_crt_get_key_purpose_oid);
219 while (strcmp(purp, GNUTLS_KP_TLS_WWW_CLIENT));
226 tls_log_params(struct conn *c)
230 gnutls_session_t s = c->tls;
231 const char *proto = gnutls_protocol_get_name(gnutls_protocol_get_version(s));
232 const char *kx = gnutls_kx_get_name(gnutls_kx_get(s));
233 const char *cert = gnutls_certificate_type_get_name(gnutls_certificate_type_get(s));
234 const char *comp = gnutls_compression_get_name(gnutls_compression_get(s));
235 const char *cipher = gnutls_cipher_get_name(gnutls_cipher_get(s));
236 const char *mac = gnutls_mac_get_name(gnutls_mac_get(s));
237 log(L_DEBUG, "TLS params: proto=%s kx=%s cert=%s comp=%s cipher=%s mac=%s",
238 proto, kx, cert, comp, cipher, mac);
241 /*** FASTBUFS OVER SOCKETS AND TLS ***/
243 void NONRET // Fatal protocol violation
244 client_error(char *msg, ...)
248 vlog_msg(L_ERROR_R, msg, args);
253 sk_fb_refill(struct fastbuf *f)
255 struct conn *c = SKIP_BACK(struct conn, rx_fb, f);
256 int cnt = read(c->sk, f->buffer, f->bufend - f->buffer);
258 client_error("Read error: %m");
260 f->bstop = f->buffer + cnt;
265 sk_fb_spout(struct fastbuf *f)
267 struct conn *c = SKIP_BACK(struct conn, tx_fb, f);
268 int len = f->bptr - f->buffer;
271 int cnt = careful_write(c->sk, f->buffer, len);
273 client_error("Write error");
278 init_sk_fastbufs(struct conn *c)
280 struct fastbuf *rf = &c->rx_fb, *tf = &c->tx_fb;
282 rf->buffer = xmalloc(1024);
283 rf->bufend = rf->buffer + 1024;
284 rf->bptr = rf->bstop = rf->buffer;
286 rf->refill = sk_fb_refill;
288 tf->buffer = xmalloc(1024);
289 tf->bufend = tf->buffer + 1024;
290 tf->bptr = tf->bstop = tf->buffer;
292 tf->spout = sk_fb_spout;
296 tls_fb_refill(struct fastbuf *f)
298 struct conn *c = SKIP_BACK(struct conn, rx_fb, f);
300 int cnt = gnutls_record_recv(c->tls, f->buffer, f->bufend - f->buffer);
301 DBG("TLS: Received %d bytes", cnt);
303 client_error("TLS read error: %s", gnutls_strerror(cnt));
305 f->bstop = f->buffer + cnt;
310 tls_fb_spout(struct fastbuf *f)
312 struct conn *c = SKIP_BACK(struct conn, tx_fb, f);
313 int len = f->bptr - f->buffer;
316 int cnt = gnutls_record_send(c->tls, f->buffer, len);
317 DBG("TLS: Sent %d bytes", cnt);
319 client_error("TLS write error: %s", gnutls_strerror(cnt));
324 init_tls_fastbufs(struct conn *c)
326 struct fastbuf *rf = &c->rx_fb, *tf = &c->tx_fb;
328 ASSERT(rf->buffer && tf->buffer); // Already set up for the plaintext connection
329 rf->refill = tls_fb_refill;
330 tf->spout = tls_fb_spout;
333 /*** CLIENT LOOP (runs in a child process) ***/
336 sigalrm_handler(int sig UNUSED)
338 // We do not try to do any gracious shutdown to avoid races
339 client_error("Timed out");
343 client_loop(struct conn *c)
345 setproctitle("submitd: client %s", c->ip_string);
349 signal(SIGPIPE, SIG_IGN);
350 struct sigaction sa = {
351 .sa_handler = sigalrm_handler
353 if (sigaction(SIGALRM, &sa, NULL) < 0)
354 die("Cannot setup SIGALRM handler: %m");
356 if (c->rule->plain_text)
358 bputsn(&c->tx_fb, "+OK");
363 bputsn(&c->tx_fb, "+TLS");
365 c->tls = tls_new_session(c->sk);
366 int err = gnutls_handshake(c->tls);
368 client_error("TLS handshake failed: %s", gnutls_strerror(err));
370 const char *cert_err = tls_verify_cert(c);
372 client_error("TLS certificate failure: %s", cert_err);
373 init_tls_fastbufs(c);
376 alarm(session_timeout);
377 if (!process_init(c))
378 log(L_ERROR, "Protocol handshake failed");
381 setproctitle("submitd: client %s (%s)", c->ip_string, c->user);
384 alarm(session_timeout);
385 if (!process_command(c))
391 gnutls_bye(c->tls, GNUTLS_SHUT_WR);
394 gnutls_deinit(c->tls);
400 sigchld_handler(int sig UNUSED)
402 /* We do not need to do anything, just interrupt the accept syscall */
406 reap_child(pid_t pid, int status)
408 byte msg[EXIT_STATUS_MSG_SIZE];
409 if (format_exit_status(msg, status))
410 log(L_ERROR, "Child %d %s", (int)pid, msg);
412 CLIST_FOR_EACH(struct conn *, c, connections)
415 log(L_INFO, "Connection %d closed", c->id);
419 log(L_ERROR, "Cannot find connection for child process %d", (int)pid);
422 static int listen_sk;
427 listen_sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
431 if (setsockopt(listen_sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
432 die("setsockopt(SO_REUSEADDR): %m");
434 struct sockaddr_in sa;
435 bzero(&sa, sizeof(sa));
436 sa.sin_family = AF_INET;
437 sa.sin_addr.s_addr = INADDR_ANY;
438 sa.sin_port = htons(port);
439 if (bind(listen_sk, (struct sockaddr *) &sa, sizeof(sa)) < 0)
440 die("Cannot bind to port %d: %m", port);
441 if (listen(listen_sk, 1024) < 0)
442 die("Cannot listen on port %d: %m", port);
448 struct sockaddr_in sa;
449 int salen = sizeof(sa);
450 int sk = accept(listen_sk, (struct sockaddr *) &sa, &salen);
458 byte ipbuf[INET_ADDRSTRLEN];
459 inet_ntop(AF_INET, &sa.sin_addr, ipbuf, sizeof(ipbuf));
460 u32 addr = ntohl(sa.sin_addr.s_addr);
461 uns port = ntohs(sa.sin_port);
464 struct access_rule *rule = lookup_rule(addr);
467 err = "Unauthorized";
471 if (num_conn >= max_conn)
473 err = "Too many connections";
477 if (conn_count(addr) >= rule->max_conn)
479 err = "Too many connections from this address";
483 struct conn *c = conn_new();
484 log(L_INFO, "Connection from %s:%d (id %d, %s, %s)",
486 (rule->plain_text ? "plain-text" : "TLS"),
487 (rule->allow_admin ? "admin" : "user"));
489 c->ip_string = xstrdup(ipbuf);
497 err = "Server overloaded";
498 log(L_ERROR, "Fork failed: %m");
511 log(L_ERROR_R, "Connection from %s:%d rejected (%s)", ipbuf, port, err);
513 // Write an error message to the socket, but do not allow it to slow us down
514 struct linger ling = { .l_onoff=0 };
515 if (setsockopt(sk, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) < 0)
516 log(L_ERROR, "Cannot set SO_LINGER: %m");
518 write(sk, err, strlen(err));
523 int main(int argc, char **argv)
525 setproctitle_init(argc, argv);
526 cf_def_file = "config";
527 cf_declare_section("SubmitD", &submitd_conf, 0);
528 cf_declare_section("Tasks", &tasks_conf, 0);
531 if ((opt = cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL)) >= 0)
532 die("This program has no options");
534 log(L_INFO, "Initializing TLS");
539 log(L_INFO, "Listening on port %d", port);
541 struct sigaction sa = {
542 .sa_handler = sigchld_handler
544 if (sigaction(SIGCHLD, &sa, NULL) < 0)
545 die("Cannot setup SIGCHLD handler: %m");
549 setproctitle("submitd: %d connections", num_conn);
551 pid_t pid = waitpid(-1, &status, WNOHANG);
553 reap_child(pid, status);