2 *****************************************************************************
6 * Author: Damien S. Stuart
8 * Purpose: An implementation of an fwknop server.
10 * Copyright 2010 Damien Stuart (dstuart@dstuart.org)
12 * License (GNU Public License):
14 * This program is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU General Public License
16 * as published by the Free Software Foundation; either version 2
17 * of the License, or (at your option) any later version.
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with this program; if not, write to the Free Software
26 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
29 *****************************************************************************
33 #include "config_init.h"
34 #include "process_packet.h"
35 #include "pcap_capture.h"
39 #include "sig_handler.h"
40 #include "replay_cache.h"
41 #include "tcp_server.h"
45 static void check_dir_path(const char *path, const char *path_name, const unsigned char use_basename);
46 static int make_dir_path(const char *path);
47 static void daemonize_process(fko_srv_options_t *opts);
48 static int write_pid_file(fko_srv_options_t *opts);
49 static pid_t get_running_pid(const fko_srv_options_t *opts);
52 main(int argc, char **argv)
54 int res, last_sig, rp_cache_count;
58 fko_srv_options_t opts;
62 /* Handle command line
64 config_init(&opts, argc, argv);
66 /* Process any options that do their thing and exit.
69 /* Kill the currently running fwknopd?
73 old_pid = get_running_pid(&opts);
77 res = kill(old_pid, SIGTERM);
80 fprintf(stdout, "Killed fwknopd (pid=%i)\n", old_pid);
81 clean_exit(&opts, NO_FW_CLEANUP, EXIT_SUCCESS);
85 perror("Unable to kill fwknop: ");
86 clean_exit(&opts, NO_FW_CLEANUP, EXIT_FAILURE);
91 fprintf(stderr, "No running fwknopd detected.\n");
92 clean_exit(&opts, NO_FW_CLEANUP, EXIT_FAILURE);
96 /* Status of the currently running fwknopd?
100 old_pid = write_pid_file(&opts);
103 fprintf(stdout, "Detected fwknopd is running (pid=%i).\n", old_pid);
105 fprintf(stdout, "No running fwknopd detected.\n");
107 clean_exit(&opts, NO_FW_CLEANUP, EXIT_SUCCESS);
110 /* Restart the currently running fwknopd?
112 if(opts.restart == 1 || opts.status == 1)
114 old_pid = get_running_pid(&opts);
118 res = kill(old_pid, SIGHUP);
121 fprintf(stdout, "Sent restart signal to fwknopd (pid=%i)\n", old_pid);
122 clean_exit(&opts, NO_FW_CLEANUP, EXIT_SUCCESS);
126 perror("Unable to send signal to fwknop: ");
127 clean_exit(&opts, NO_FW_CLEANUP, EXIT_FAILURE);
132 fprintf(stdout, "No running fwknopd detected.\n");
133 clean_exit(&opts, NO_FW_CLEANUP, EXIT_FAILURE);
137 /* Initialize logging.
142 /* Set the locale if specified.
144 if(opts.config[CONF_LOCALE] != NULL
145 && strncasecmp(opts.config[CONF_LOCALE], "NONE", 4) != 0)
147 locale = setlocale(LC_ALL, opts.config[CONF_LOCALE]);
152 "WARNING: Unable to set locale to '%s'.",
153 opts.config[CONF_LOCALE]
160 "Locale set to '%s'.", opts.config[CONF_LOCALE]
166 /* Make sure we have a valid run dir and path leading to digest file
167 * in case it configured to be somewhere other than the run dir.
169 check_dir_path((const char *)opts.config[CONF_FWKNOP_RUN_DIR], "Run", 0);
171 /* Initialize the firewall rules handler based on the fwknopd.conf
172 * file, but (for iptables firewalls) don't flush any rules or create
173 * any chains yet. This allows us to dump the current firewall rules
174 * via fw_rules_dump() in --fw-list mode before changing around any rules
175 * of an existing fwknopd process.
177 fw_config_init(&opts);
179 if(opts.fw_list == 1 || opts.fw_list_all == 1)
181 fw_dump_rules(&opts);
182 clean_exit(&opts, NO_FW_CLEANUP, EXIT_SUCCESS);
185 if(opts.fw_flush == 1)
187 fprintf(stdout, "Deleting any existing firewall rules...\n");
188 clean_exit(&opts, FW_CLEANUP, EXIT_SUCCESS);
191 /* Process the access.conf file.
193 parse_access_file(&opts);
195 /* Show config (including access.conf vars) and exit dump config was
198 if(opts.dump_config == 1)
201 dump_access_list(&opts);
202 clean_exit(&opts, NO_FW_CLEANUP, EXIT_SUCCESS);
205 /* If we are a new process (just being started), proceed with normal
206 * start-up. Otherwise, we are here as a result of a signal sent to an
207 * existing process and we want to restart.
209 if(get_running_pid(&opts) != getpid())
211 /* If foreground mode is not set, the fork off and become a daemon.
212 * Otherwise, attempt to get the pid file lock and go on.
214 if(opts.foreground == 0)
216 daemonize_process(&opts);
220 old_pid = write_pid_file(&opts);
224 "* An instance of fwknopd is already running: (PID=%i).\n", old_pid
227 clean_exit(&opts, NO_FW_CLEANUP, EXIT_FAILURE);
231 fprintf(stderr, "* PID file error. The lock may not be effective.\n");
235 log_msg(LOG_INFO, "Starting %s", MY_NAME);
239 log_msg(LOG_INFO, "Re-starting %s", MY_NAME);
242 if(opts.verbose > 1 && opts.foreground)
245 dump_access_list(&opts);
248 /* Initialize the digest cache for replay attack detection (either
249 * with dbm support or with the default simple cache file strategy)
252 if(strncasecmp(opts.config[CONF_ENABLE_DIGEST_PERSISTENCE], "Y", 1) == 0)
254 rp_cache_count = replay_cache_init(&opts);
256 if(rp_cache_count < 0)
259 "Error opening digest cache file. Incoming digests will not be remembered."
261 strlcpy(opts.config[CONF_ENABLE_DIGEST_PERSISTENCE], "N", 2);
266 "Using Digest Cache: '%s' (entry count = %i)",
268 opts.config[CONF_DIGEST_FILE], rp_cache_count
270 opts.config[CONF_DIGEST_DB_FILE], rp_cache_count
275 /* Prepare the firewall - i.e. flush any old rules and (for iptables)
276 * create fwknop chains.
278 fw_initialize(&opts);
280 /* If the TCP server option was set, fire it up here.
282 if(strncasecmp(opts.config[CONF_ENABLE_TCP_SERVER], "Y", 1) == 0)
284 if(atoi(opts.config[CONF_TCPSERV_PORT]) <= 0
285 || atoi(opts.config[CONF_TCPSERV_PORT]) > MAX_PORT)
288 "WARNING: ENABLE_TCP_SERVER is set, but TCPSERV_PORT is not valid. TCP server not started!"
293 run_tcp_server(&opts);
297 /* Intiate pcap capture mode...
302 last_sig = got_signal;
307 log_msg(LOG_WARNING, "Got SIGHUP. Re-reading configs.");
309 kill(opts.tcp_server_pid, SIGTERM);
315 log_msg(LOG_WARNING, "Got SIGINT. Exiting...");
321 log_msg(LOG_WARNING, "Got SIGTERM. Exiting...");
328 "Got signal %i. No defined action but to exit.", last_sig);
332 else if (opts.packet_ctr_limit > 0
333 && opts.packet_ctr >= opts.packet_ctr_limit)
336 "Packet count limit (%d) reached. Exiting...",
337 opts.packet_ctr_limit);
340 else /* got_signal was not set (should be if we are here) */
343 "Capture ended without signal. Exiting...");
348 log_msg(LOG_INFO, "Shutting Down fwknopd.");
350 /* Kill the TCP server (if we have one running).
352 if(opts.tcp_server_pid > 0)
354 log_msg(LOG_INFO, "Killing the TCP server (pid=%i)",
355 opts.tcp_server_pid);
357 kill(opts.tcp_server_pid, SIGTERM);
359 /* --DSS XXX: This seems to be necessary if the tcp server
360 * was restarted by this program. We need to
361 * investigate and fix this. For now, this works
362 * (it is kludgy, but does no harm afaik).
364 kill(opts.tcp_server_pid, SIGKILL);
373 free_replay_list(&opts);
381 /* Ensure the specified directory exists. If not, create it or die.
384 check_dir_path(const char *filepath, const char *fp_desc, const unsigned char use_basename)
388 char tmp_path[MAX_PATH_LEN];
392 * FIXME: We shouldn't use a hard-coded dir-separator here.
394 /* But first make sure we are using an absolute path.
396 if(*filepath != PATH_SEP)
399 "Path '%s' is not absolute.", filepath
404 /* If this is a file path that we want to use only the basename, strip
405 * the trailing filename here.
407 if(use_basename && ((ndx = strrchr(filepath, PATH_SEP)) != NULL))
408 strlcpy(tmp_path, filepath, (ndx-filepath)+1);
410 strlcpy(tmp_path, filepath, MAX_PATH_LEN);
412 /* At this point, we should make the path is more than just the
413 * PATH_SEP. If it is not, silently return.
415 if(strlen(tmp_path) < 2)
418 /* Make sure we have a valid directory.
420 res = stat(tmp_path, &st);
426 "%s directory: %s does not exist. Attempting to create it.",
430 /* Directory does not exist, so attempt to create it.
432 res = make_dir_path(tmp_path);
436 "Unable to create %s directory: %s (error: %i)",
437 fp_desc, tmp_path, errno
443 "Successfully created %s directory: %s", fp_desc, tmp_path
449 "Stat of %s returned error %i", tmp_path, errno
456 /* It is a file, but is it a directory?
458 if(! S_ISDIR(st.st_mode))
461 "Specified %s directory: %s is NOT a directory\n\n", fp_desc, tmp_path
469 make_dir_path(const char *run_dir)
472 int res = 0, len = 0;
473 char tmp_path[MAX_PATH_LEN];
476 strlcpy(tmp_path, run_dir, MAX_PATH_LEN);
478 len = strlen(tmp_path);
480 /* Strip any trailing dir sep char.
482 if(tmp_path[len-1] == PATH_SEP)
483 tmp_path[len-1] = '\0';
485 for(ndx = tmp_path+1; *ndx; ndx++)
491 /* Stat this part of the path to see if it is a valid directory.
492 * If it does not exist, attempt to create it. If it does, and
493 * it is a directory, go on. Otherwise, any other error cause it
496 if(stat(tmp_path, &st) != 0)
499 res = mkdir(tmp_path, S_IRWXU);
505 if(! S_ISDIR(st.st_mode))
508 "Component: %s of %s is NOT a directory\n\n", tmp_path, run_dir
517 res = mkdir(tmp_path, S_IRWXU);
522 /* Become a daemon: fork(), start a new session, chdir "/",
523 * and close unneeded standard filehandles.
526 daemonize_process(fko_srv_options_t *opts)
530 /* Reset the our umask
534 if ((pid = fork()) < 0)
536 perror("Unable to fork: ");
539 else if (pid != 0) /* parent */
544 /* Child process from here on out */
546 /* Start a new session
550 /* Create the PID file (or be blocked by an existing one).
552 old_pid = write_pid_file(opts);
556 "* An instance of fwknopd is already running: (PID=%i).\n", old_pid
563 fprintf(stderr, "* PID file error. The lock may not be effective.\n");
566 /* Chdir to the root of the filesystem
568 if ((chdir("/")) < 0) {
569 perror("Could not chdir() to /: ");
573 /* Close un-needed file handles
576 close(STDOUT_FILENO);
577 close(STDERR_FILENO);
583 write_pid_file(fko_srv_options_t *opts)
585 pid_t old_pid, my_pid;
586 int op_fd, lck_res, num_bytes;
587 char buf[PID_BUFLEN] = {0};
589 /* Reset errno (just in case)
596 opts->config[CONF_FWKNOP_PID_FILE], O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR
601 perror("Error trying to open PID file: ");
605 fcntl(op_fd, F_SETFD, FD_CLOEXEC);
607 /* Attempt to lock the PID file. If we get an EWOULDBLOCK
608 * error, another instance already has the lock. So we grab
609 * the pid from the existing lock file, complain and bail.
611 lck_res = lockf(op_fd, F_TLOCK, 0);
616 perror("Unexpected error from lockf: ");
622 /* Look for an existing lock holder. If we get a pid return it.
624 old_pid = get_running_pid(opts);
628 /* Otherwise, consider it an error.
630 perror("Unable read existing PID file: ");
634 /* Write our PID to the file
637 snprintf(buf, PID_BUFLEN, "%i\n", my_pid);
639 if(opts->verbose > 1)
640 log_msg(LOG_INFO, "[+] Writing my PID (%i) to the lock file: %s\n",
641 my_pid, opts->config[CONF_FWKNOP_PID_FILE]);
643 num_bytes = write(op_fd, buf, strlen(buf));
645 if(errno || num_bytes != strlen(buf))
646 perror("Lock may not be valid. PID file write error: ");
648 /* Sync/flush regardless...
652 /* Put the lock file discriptor in out options struct so any
653 * child processes we my spawn can close and release it.
655 opts->lock_fd = op_fd;
661 get_running_pid(const fko_srv_options_t *opts)
664 char buf[PID_BUFLEN] = {0};
667 verify_file_perms_ownership(opts->config[CONF_FWKNOP_PID_FILE]);
669 op_fd = open(opts->config[CONF_FWKNOP_PID_FILE], O_RDONLY);
673 if (read(op_fd, buf, PID_BUFLEN) > 0)
675 buf[PID_BUFLEN-1] = '\0';
676 rpid = (pid_t)atoi(buf);
686 clean_exit(fko_srv_options_t *opts, unsigned int fw_cleanup_flag, unsigned int exit_status)
688 if(fw_cleanup_flag == FW_CLEANUP)
692 free_replay_list(opts);