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 byte *log_name;
29 static uns port = 8888;
30 static uns dh_bits = 1024;
31 static uns max_conn = 10;
32 static uns session_timeout;
33 static byte *ca_cert_name = "?";
34 static byte *server_cert_name = "?";
35 static byte *server_key_name = "?";
36 static clist access_rules;
39 uns max_attachment_size;
42 static struct cf_section access_conf = {
43 CF_TYPE(struct access_rule),
45 CF_USER("IP", PTR_TO(struct access_rule, addrmask), &ip_addrmask_type),
46 CF_UNS("Admin", PTR_TO(struct access_rule, allow_admin)),
47 CF_UNS("PlainText", PTR_TO(struct access_rule, plain_text)),
48 CF_UNS("MaxConn", PTR_TO(struct access_rule, max_conn)),
53 static struct cf_section submitd_conf = {
55 CF_STRING("LogFile", &log_name),
56 CF_UNS("Port", &port),
57 CF_UNS("DHBits", &dh_bits),
58 CF_UNS("MaxConn", &max_conn),
59 CF_UNS("SessionTimeout", &session_timeout),
60 CF_UNS("MaxRequestSize", &max_request_size),
61 CF_UNS("MaxAttachSize", &max_attachment_size),
62 CF_STRING("CACert", &ca_cert_name),
63 CF_STRING("ServerCert", &server_cert_name),
64 CF_STRING("ServerKey", &server_key_name),
65 CF_LIST("Access", &access_rules, &access_conf),
66 CF_UNS("TraceTLS", &trace_tls),
67 CF_UNS("TraceCommands", &trace_commands),
74 static clist connections;
75 static uns last_conn_id;
81 clist_init(&connections);
87 struct conn *c = xmalloc_zero(sizeof(*c));
88 c->id = ++last_conn_id;
89 clist_add_tail(&connections, &c->n);
95 conn_free(struct conn *c)
104 static struct access_rule *
107 CLIST_FOR_EACH(struct access_rule *, r, access_rules)
108 if (ip_addrmask_match(&r->addrmask, ip))
117 CLIST_FOR_EACH(struct conn *, c, connections)
125 static gnutls_certificate_credentials_t cert_cred;
126 static gnutls_dh_params_t dh_params;
128 #define TLS_CHECK(name) if (err < 0) die(#name " failed: %s", gnutls_strerror(err))
135 gnutls_global_init();
136 err = gnutls_certificate_allocate_credentials(&cert_cred);
137 TLS_CHECK(gnutls_certificate_allocate_credentials);
138 err = gnutls_certificate_set_x509_trust_file(cert_cred, ca_cert_name, GNUTLS_X509_FMT_PEM);
140 die("No CA certificate found");
142 die("Unable to load X509 trust file: %s", gnutls_strerror(err));
143 err = gnutls_certificate_set_x509_key_file(cert_cred, server_cert_name, server_key_name, GNUTLS_X509_FMT_PEM);
145 die("Unable to load X509 key file: %s", gnutls_strerror(err));
147 err = gnutls_dh_params_init(&dh_params); TLS_CHECK(gnutls_dh_params_init);
148 err = gnutls_dh_params_generate2(dh_params, dh_bits); TLS_CHECK(gnutls_dh_params_generate2);
149 gnutls_certificate_set_dh_params(cert_cred, dh_params);
152 static gnutls_session_t
153 tls_new_session(int sk)
158 err = gnutls_init(&s, GNUTLS_SERVER); TLS_CHECK(gnutls_init);
159 err = gnutls_set_default_priority(s); TLS_CHECK(gnutls_set_default_priority); // FIXME
160 gnutls_credentials_set(s, GNUTLS_CRD_CERTIFICATE, cert_cred);
161 gnutls_certificate_server_set_request(s, GNUTLS_CERT_REQUEST);
162 gnutls_dh_set_prime_bits(s, dh_bits);
163 gnutls_transport_set_ptr(s, (gnutls_transport_ptr_t) sk);
168 tls_verify_cert(struct conn *c)
170 gnutls_session_t s = c->tls;
171 uns status, num_certs;
173 gnutls_x509_crt_t cert;
174 const gnutls_datum_t *certs;
176 DBG("Verifying peer certificates");
177 err = gnutls_certificate_verify_peers2(s, &status);
179 return gnutls_strerror(err);
180 DBG("Verify status: %04x", status);
181 if (status & GNUTLS_CERT_INVALID)
182 return "Certificate is invalid";
183 /* XXX: We do not handle revokation. */
184 if (gnutls_certificate_type_get(s) != GNUTLS_CRT_X509)
185 return "Certificate is not X509";
187 err = gnutls_x509_crt_init(&cert);
189 return "gnutls_x509_crt_init() failed";
190 certs = gnutls_certificate_get_peers(s, &num_certs);
192 return "No peer certificate found";
193 DBG("Got certificate list with %d peers", num_certs);
195 err = gnutls_x509_crt_import(cert, &certs[0], GNUTLS_X509_FMT_DER);
197 return "Cannot import certificate";
198 /* XXX: We do not check expiration and activation since the keys are generated for a single contest only anyway. */
201 size_t dn_len = sizeof(dn);
202 err = gnutls_x509_crt_get_dn_by_oid(cert, GNUTLS_OID_X520_COMMON_NAME, 0, 0, dn, &dn_len);
204 return "Cannot retrieve common name";
206 msg(L_INFO, "Cert CN: %s", dn);
207 c->cert_name = xstrdup(dn);
209 /* Check certificate purpose */
214 size_t purp_len = sizeof(purp);
216 err = gnutls_x509_crt_get_key_purpose_oid(cert, purpi++, purp, &purp_len, &crit);
217 if (err == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
218 return "Not a client certificate";
219 TLS_CHECK(gnutls_x509_crt_get_key_purpose_oid);
221 while (strcmp(purp, GNUTLS_KP_TLS_WWW_CLIENT));
228 tls_log_params(struct conn *c)
232 gnutls_session_t s = c->tls;
233 const char *proto = gnutls_protocol_get_name(gnutls_protocol_get_version(s));
234 const char *kx = gnutls_kx_get_name(gnutls_kx_get(s));
235 const char *cert = gnutls_certificate_type_get_name(gnutls_certificate_type_get(s));
236 const char *comp = gnutls_compression_get_name(gnutls_compression_get(s));
237 const char *cipher = gnutls_cipher_get_name(gnutls_cipher_get(s));
238 const char *mac = gnutls_mac_get_name(gnutls_mac_get(s));
239 msg(L_DEBUG, "TLS params: proto=%s kx=%s cert=%s comp=%s cipher=%s mac=%s",
240 proto, kx, cert, comp, cipher, mac);
243 /*** FASTBUFS OVER SOCKETS AND TLS ***/
245 void NONRET // Fatal protocol violation
246 client_error(char *msg, ...)
250 vmsg(L_ERROR_R, msg, args);
255 sk_fb_refill(struct fastbuf *f)
257 struct conn *c = SKIP_BACK(struct conn, rx_fb, f);
258 int cnt = read(c->sk, f->buffer, f->bufend - f->buffer);
260 client_error("Read error: %m");
262 f->bstop = f->buffer + cnt;
267 sk_fb_spout(struct fastbuf *f)
269 struct conn *c = SKIP_BACK(struct conn, tx_fb, f);
270 int len = f->bptr - f->buffer;
273 int cnt = careful_write(c->sk, f->buffer, len);
275 client_error("Write error");
280 init_sk_fastbufs(struct conn *c)
282 struct fastbuf *rf = &c->rx_fb, *tf = &c->tx_fb;
284 rf->buffer = xmalloc(1024);
285 rf->bufend = rf->buffer + 1024;
286 rf->bptr = rf->bstop = rf->buffer;
288 rf->refill = sk_fb_refill;
290 tf->buffer = xmalloc(1024);
291 tf->bufend = tf->buffer + 1024;
292 tf->bptr = tf->bstop = tf->buffer;
294 tf->spout = sk_fb_spout;
298 tls_fb_refill(struct fastbuf *f)
300 struct conn *c = SKIP_BACK(struct conn, rx_fb, f);
302 int cnt = gnutls_record_recv(c->tls, f->buffer, f->bufend - f->buffer);
303 DBG("TLS: Received %d bytes", cnt);
305 client_error("TLS read error: %s", gnutls_strerror(cnt));
307 f->bstop = f->buffer + cnt;
312 tls_fb_spout(struct fastbuf *f)
314 struct conn *c = SKIP_BACK(struct conn, tx_fb, f);
315 int len = f->bptr - f->buffer;
318 int cnt = gnutls_record_send(c->tls, f->buffer, len);
319 DBG("TLS: Sent %d bytes", cnt);
321 client_error("TLS write error: %s", gnutls_strerror(cnt));
326 init_tls_fastbufs(struct conn *c)
328 struct fastbuf *rf = &c->rx_fb, *tf = &c->tx_fb;
330 ASSERT(rf->buffer && tf->buffer); // Already set up for the plaintext connection
331 rf->refill = tls_fb_refill;
332 tf->spout = tls_fb_spout;
335 /*** CLIENT LOOP (runs in a child process) ***/
338 sigalrm_handler(int sig UNUSED)
340 // We do not try to do any gracious shutdown to avoid races
341 client_error("Timed out");
345 client_loop(struct conn *c)
347 setproctitle("submitd: client %s", c->ip_string);
351 signal(SIGPIPE, SIG_IGN);
352 struct sigaction sa = {
353 .sa_handler = sigalrm_handler
355 if (sigaction(SIGALRM, &sa, NULL) < 0)
356 die("Cannot setup SIGALRM handler: %m");
358 if (c->rule->plain_text)
360 bputsn(&c->tx_fb, "+OK");
365 bputsn(&c->tx_fb, "+TLS");
367 c->tls = tls_new_session(c->sk);
368 int err = gnutls_handshake(c->tls);
370 client_error("TLS handshake failed: %s", gnutls_strerror(err));
372 const char *cert_err = tls_verify_cert(c);
374 client_error("TLS certificate failure: %s", cert_err);
375 init_tls_fastbufs(c);
378 alarm(session_timeout);
379 if (!process_init(c))
380 msg(L_ERROR, "Protocol handshake failed");
383 setproctitle("submitd: client %s (%s)", c->ip_string, c->user);
386 alarm(session_timeout);
387 if (!process_command(c))
393 gnutls_bye(c->tls, GNUTLS_SHUT_WR);
396 gnutls_deinit(c->tls);
402 sigchld_handler(int sig UNUSED)
404 /* We do not need to do anything, just interrupt the accept syscall */
408 reap_child(pid_t pid, int status)
410 byte buf[EXIT_STATUS_MSG_SIZE];
411 if (format_exit_status(buf, status))
412 msg(L_ERROR, "Child %d %s", (int)pid, buf);
414 CLIST_FOR_EACH(struct conn *, c, connections)
417 msg(L_INFO, "Connection %d closed", c->id);
421 msg(L_ERROR, "Cannot find connection for child process %d", (int)pid);
424 static int listen_sk;
429 listen_sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
433 if (setsockopt(listen_sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
434 die("setsockopt(SO_REUSEADDR): %m");
436 struct sockaddr_in sa;
437 bzero(&sa, sizeof(sa));
438 sa.sin_family = AF_INET;
439 sa.sin_addr.s_addr = INADDR_ANY;
440 sa.sin_port = htons(port);
441 if (bind(listen_sk, (struct sockaddr *) &sa, sizeof(sa)) < 0)
442 die("Cannot bind to port %d: %m", port);
443 if (listen(listen_sk, 1024) < 0)
444 die("Cannot listen on port %d: %m", port);
450 struct sockaddr_in sa;
451 int salen = sizeof(sa);
452 int sk = accept(listen_sk, (struct sockaddr *) &sa, &salen);
460 byte ipbuf[INET_ADDRSTRLEN];
461 inet_ntop(AF_INET, &sa.sin_addr, ipbuf, sizeof(ipbuf));
462 u32 addr = ntohl(sa.sin_addr.s_addr);
463 uns port = ntohs(sa.sin_port);
466 struct access_rule *rule = lookup_rule(addr);
469 err = "Unauthorized";
473 if (num_conn >= max_conn)
475 err = "Too many connections";
479 if (conn_count(addr) >= rule->max_conn)
481 err = "Too many connections from this address";
485 struct conn *c = conn_new();
486 msg(L_INFO, "Connection from %s:%d (id %d, %s, %s)",
488 (rule->plain_text ? "plain-text" : "TLS"),
489 (rule->allow_admin ? "admin" : "user"));
491 c->ip_string = xstrdup(ipbuf);
499 err = "Server overloaded";
500 msg(L_ERROR, "Fork failed: %m");
513 msg(L_ERROR_R, "Connection from %s:%d rejected (%s)", ipbuf, port, err);
515 // Write an error message to the socket, but do not allow it to slow us down
516 struct linger ling = { .l_onoff=0 };
517 if (setsockopt(sk, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) < 0)
518 msg(L_ERROR, "Cannot set SO_LINGER: %m");
520 write(sk, err, strlen(err));
525 int main(int argc, char **argv)
527 setproctitle_init(argc, argv);
528 cf_def_file = "submit/config";
529 cf_declare_section("SubmitD", &submitd_conf, 0);
530 cf_declare_section("Tasks", &tasks_conf, 0);
533 if ((opt = cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL)) >= 0)
534 die("This program has no options");
538 msg(L_INFO, "Initializing TLS");
543 msg(L_INFO, "Listening on port %d", port);
545 struct sigaction sa = {
546 .sa_handler = sigchld_handler
548 if (sigaction(SIGCHLD, &sa, NULL) < 0)
549 die("Cannot setup SIGCHLD handler: %m");
553 setproctitle("submitd: %d connections", num_conn);
555 pid_t pid = waitpid(-1, &status, WNOHANG);
557 reap_child(pid, status);