/* * ***** BEGIN LICENSE BLOCK ***** Copyright (C) 2009-2016 Olof Hagsand and Benny Holmgren Copyright (C) 2017-2019 Olof Hagsand Copyright (C) 2020-2021 Olof Hagsand and Rubicon Communications, LLC(Netgate) This file is part of CLIXON. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 3 or later (the "GPL"), in which case the provisions of the GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL, and not to allow others to use your version of this file under the terms of Apache License version 2, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the Apache License version 2 or the GPL. ***** END LICENSE BLOCK ***** */ #ifdef HAVE_CONFIG_H #include "clixon_config.h" /* generated by config & autoconf */ #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* cligen */ #include /* clicon */ #include #include "clixon_backend_transaction.h" #include "backend_socket.h" #include "backend_client.h" #include "backend_plugin.h" #include "backend_commit.h" #include "backend_handle.h" #include "backend_startup.h" /* Command line options to be passed to getopt(3) */ #define BACKEND_OPTS "hD:f:E:l:d:p:b:Fza:u:P:1qs:c:U:g:y:o:" #define BACKEND_LOGFILE "/usr/local/var/clixon_backend.log" /*! Clean and close all state of backend (but dont exit). * Cannot use h after this * @param[in] h Clixon handle */ static int backend_terminate(clicon_handle h) { yang_stmt *yspec; char *pidfile = clicon_backend_pidfile(h); int sockfamily = clicon_sock_family(h); char *sockpath = clicon_sock_str(h); cxobj *x; struct stat st; int ss; cvec *nsctx; clicon_debug(1, "%s", __FUNCTION__); if ((ss = clicon_socket_get(h)) != -1) close(ss); /* Disconnect datastore */ xmldb_disconnect(h); /* Clear module state caches */ if ((x = clicon_modst_cache_get(h, 0)) != NULL) xml_free(x); if ((x = clicon_modst_cache_get(h, 1)) != NULL) xml_free(x); /* Free changelog */ if ((x = clicon_xml_changelog_get(h)) != NULL) xml_free(x); if ((yspec = clicon_dbspec_yang(h)) != NULL) yspec_free(yspec); if ((yspec = clicon_config_yang(h)) != NULL) yspec_free(yspec); if ((yspec = clicon_nacm_ext_yang(h)) != NULL) yspec_free(yspec); if ((nsctx = clicon_nsctx_global_get(h)) != NULL) cvec_free(nsctx); if ((x = clicon_nacm_ext(h)) != NULL) xml_free(x); if ((x = clicon_conf_xml(h)) != NULL) xml_free(x); stream_publish_exit(); clixon_plugin_exit_all(h); /* Delete all backend plugin RPC callbacks */ rpc_callback_delete_all(h); /* Delete all backend plugin upgrade callbacks */ upgrade_callback_delete_all(h); /* Delete all process-control entries */ clixon_process_delete_all(h); xpath_optimize_exit(); if (pidfile) unlink(pidfile); if (sockfamily==AF_UNIX && lstat(sockpath, &st) == 0) unlink(sockpath); backend_handle_exit(h); /* Also deletes streams. Cannot use h after this. */ clixon_event_exit(); clicon_debug(1, "%s done", __FUNCTION__); clicon_log_exit(); return 0; } /*! Unlink pidfile and quit */ static void backend_sig_term(int arg) { static int i=0; if (i++ == 0) clicon_log(LOG_NOTICE, "%s: %s: pid: %u Signal %d", __PROGRAM__, __FUNCTION__, getpid(), arg); clicon_exit_set(); /* checked in clixon_event_loop() */ } /*! Create backend server socket and register callback * @param[in] h Clicon handle * @retval s Server socket file descriptor (see socket(2)) * @retval -1 Error */ static int backend_server_socket(clicon_handle h) { int ss; /* Open control socket */ if ((ss = backend_socket_init(h)) < 0) return -1; /* ss is a server socket that the clients connect to. The callback therefore accepts clients on ss */ if (clixon_event_reg_fd(ss, backend_accept_client, h, "server socket") < 0) { close(ss); return -1; } return ss; } /*! Load external NACM file */ static int nacm_load_external(clicon_handle h) { int retval = -1; char *filename; /* NACM config file */ yang_stmt *yspec = NULL; cxobj *xt = NULL; struct stat st; FILE *f = NULL; filename = clicon_option_str(h, "CLICON_NACM_FILE"); if (filename == NULL || strlen(filename)==0){ clicon_err(OE_UNIX, errno, "CLICON_NACM_FILE not set in NACM external mode"); goto done; } if (stat(filename, &st) < 0){ clicon_err(OE_UNIX, errno, "%s", filename); goto done; } if (!S_ISREG(st.st_mode)){ clicon_err(OE_UNIX, 0, "%s is not a regular file", filename); goto done; } if ((f = fopen(filename, "r")) == NULL) { clicon_err(OE_UNIX, errno, "configure file: %s", filename); return -1; } if ((yspec = yspec_new()) == NULL) goto done; if (yang_spec_parse_module(h, "ietf-netconf-acm", NULL, yspec) < 0) goto done; /* Read configfile */ if (clixon_xml_parse_file(f, YB_MODULE, yspec, NULL, &xt, NULL) < 0) goto done; if (xt == NULL){ clicon_err(OE_XML, 0, "No xml tree in %s", filename); goto done; } if (clicon_nacm_ext_yang_set(h, yspec) < 0) goto done; if (clicon_nacm_ext_set(h, xt) < 0) goto done; retval = 0; done: if (f) fclose(f); return retval; } static int xmldb_drop_priv(clicon_handle h, const char *db, uid_t uid, gid_t gid) { int retval = -1; char *filename = NULL; if (xmldb_db2file(h, db, &filename) < 0) goto done; if (chown(filename, uid, gid) < 0){ clicon_err(OE_UNIX, errno, "chown"); goto done; } retval = 0; done: if (filename) free(filename); return retval; } /*! Drop root privileges uid and gid to Clixon user/group and * * If config options are right, drop process uid/guid privileges and change some * file ownerships. * "Right" means: * - uid is currently 0 (started as root) * - CLICON_BACKEND_USER is set * - CLICON_BACKEND_PRIVILEGES is not "none" * @param[in] h Clicon handle * @param[in] gid Group id (assume already known) * @retval 0 OK * @retval -1 Error */ static int check_drop_priv(clicon_handle h, gid_t gid) { int retval = -1; uid_t uid; uid_t newuid = -1; enum priv_mode_t priv_mode = PM_NONE; char *backend_user = NULL; /* Get privileges mode (for dropping privileges) */ priv_mode = clicon_backend_privileges_mode(h); if (priv_mode == PM_NONE) goto ok; /* From here, drop privileges */ /* Check backend user exists */ if ((backend_user = clicon_backend_user(h)) == NULL){ clicon_err(OE_DAEMON, EPERM, "Privileges cannot be dropped without specifying CLICON_BACKEND_USER\n"); goto done; } /* Get (wanted) new backend user id */ if (name2uid(backend_user, &newuid) < 0){ clicon_err(OE_DAEMON, errno, "'%s' is not a valid user .\n", backend_user); goto done; } /* get current backend userid, if already at this level OK */ if ((uid = getuid()) == newuid) goto ok; if (uid != 0){ clicon_err(OE_DAEMON, EPERM, "Privileges can only be dropped from root user (uid is %u)\n", uid); goto done; } /* When dropping privileges, datastores are created if they do not exist. * But when drops are not made, datastores are created on demand. * XXX: move the creation to top-level so they are always created at init? */ if (xmldb_exists(h, "running") != 1) if (xmldb_create(h, "running") < 0) goto done; if (xmldb_drop_priv(h, "running", newuid, gid) < 0) goto done; if (xmldb_exists(h, "candidate") != 1) if (xmldb_create(h, "candidate") < 0) goto done; if (xmldb_drop_priv(h, "candidate", newuid, gid) < 0) goto done; if (xmldb_exists(h, "startup") != 1) if (xmldb_create(h, "startup") < 0) goto done; if (xmldb_drop_priv(h, "startup", newuid, gid) < 0) goto done; if (setgid(gid) == -1) { clicon_err(OE_DAEMON, errno, "setgid %d", gid); goto done; } switch (priv_mode){ case PM_DROP_PERM: if (drop_priv_perm(newuid) < 0) goto done; /* Verify you cannot regain root privileges */ if (setuid(0) != -1){ clicon_err(OE_DAEMON, EPERM, "Could regain root privilieges"); goto done; } break; case PM_DROP_TEMP: if (drop_priv_temp(newuid) < 0) goto done; break; case PM_NONE: break; /* catched above */ } ok: retval = 0; done: return retval; } /*! Given a retval, transform to status or fatal error * * @param[in] ret Return value from xml validation function * @param[out] status Transform status according to rules below * @retval 0 OK, status set * @retval -1 Fatal error outside scope of startup_status * Transformation rules: * 1) retval -1 assume clicon_errno/suberrno set. Special case from xml parser * is clicon_suberrno = XMLPARSE_ERRNO which assumes an XML (non-fatal) parse * error which translates to -> STARTUP_ERR * All other error cases translates to fatal error * 2) retval 0 is xml validation fails -> STARTUP_INVALID * 3) retval 1 is OK -> STARTUP_OK * 4) any other retval translates to fatal error */ static int ret2status(int ret, enum startup_status *status) { int retval = -1; switch (ret){ case -1: if (clicon_suberrno != XMLPARSE_ERRNO) goto done; clicon_err_reset(); *status = STARTUP_ERR; break; case 0: *status = STARTUP_INVALID; break; case 1: *status = STARTUP_OK; break; default: clicon_err(OE_CFG, EINVAL, "No such retval %d", retval); } /* switch */ retval = 0; done: return retval; } /*--------------------------------------------------------------------- * Restconf process pseudo plugin */ #define RESTCONF_PROCESS "restconf" /*! Process rpc callback function * - if RPC op is start, if enable is true, start the service, if false, error or ignore it * - if RPC op is stop, stop the service * These rules give that if RPC op is start and enable is false -> change op to none */ int restconf_rpc_wrapper(clicon_handle h, process_entry_t *pe, char **operation) { int retval = -1; cxobj *xt = NULL; clicon_debug(1, "%s", __FUNCTION__); if (strcmp(*operation, "stop") == 0){ /* if RPC op is stop, stop the service */ } else if (strcmp(*operation, "start") == 0){ /* RPC op is start & enable is true, then start the service, & enable is false, error or ignore it */ if (xmldb_get(h, "running", NULL, "/restconf", &xt) < 0) goto done; if (xt != NULL && xpath_first(xt, NULL, "/restconf[enable='false']") != NULL) { *operation = "none"; } } retval = 0; done: if (xt) xml_free(xt); return retval; } /*! Enable process-control of restconf daemon, ie start/stop restconf by registering restconf process * @param[in] h Clicon handle * @note Could also look in clixon-restconf and start process if enable is true, but that needs to * be in start callback using a pseudo plugin. */ static int restconf_pseudo_process_control(clicon_handle h) { int retval = -1; char **argv = NULL; int i; int nr; char dbgstr[8]; char wwwstr[64]; nr = 4; if (clicon_debug_get() != 0) nr += 2; if ((argv = calloc(nr, sizeof(char *))) == NULL){ clicon_err(OE_UNIX, errno, "calloc"); goto done; } i = 0; snprintf(wwwstr, sizeof(wwwstr)-1, "%s/clixon_restconf", clicon_option_str(h, "CLICON_WWWDIR")); argv[i++] = wwwstr; argv[i++] = "-f"; argv[i++] = clicon_option_str(h, "CLICON_CONFIGFILE"); if (clicon_debug_get() != 0){ argv[i++] = "-D"; snprintf(dbgstr, sizeof(dbgstr)-1, "%d", clicon_debug_get()); argv[i++] = dbgstr; } argv[i++] = NULL; assert(i==nr); if (clixon_process_register(h, RESTCONF_PROCESS, NULL /* XXX network namespace */, restconf_rpc_wrapper, argv, nr) < 0) goto done; if (argv != NULL) free(argv); retval = 0; done: return retval; } /*! Restconf pseduo-plugin process validate */ static int restconf_pseudo_process_validate(clicon_handle h, transaction_data td) { int retval = -1; cxobj *xtarget; clicon_debug(1, "%s", __FUNCTION__); xtarget = transaction_target(td); /* If ssl-enable is true and (at least a) socket has ssl, * then server-cert-path and server-key-path must exist */ if (xpath_first(xtarget, NULL, "restconf/enable[.='true']") && xpath_first(xtarget, NULL, "restconf/socket[ssl='true']")){ /* Should filepath be checked? One could claim this is a runtime system,... */ if (xpath_first(xtarget, 0, "restconf/server-cert-path") == NULL){ clicon_err(OE_CFG, 0, "SSL enabled but server-cert-path not set"); return -1; /* induce fail */ } if (xpath_first(xtarget, 0, "restconf/server-key-path") == NULL){ clicon_err(OE_CFG, 0, "SSL enabled but server-key-path not set"); return -1; /* induce fail */ } } retval = 0; return retval; } /*! Restconf pseduo-plugin process commit */ static int restconf_pseudo_process_commit(clicon_handle h, transaction_data td) { int retval = -1; cxobj *xtarget; cxobj *cx; int enabled = 0; clicon_debug(1, "%s", __FUNCTION__); xtarget = transaction_target(td); if (xpath_first(xtarget, NULL, "/restconf[enable='true']") != NULL) enabled++; if ((cx = xpath_first(xtarget, NULL, "/restconf/enable")) != NULL && xml_flag(cx, XML_FLAG_CHANGE|XML_FLAG_ADD)){ if (clixon_process_operation(h, RESTCONF_PROCESS, enabled?"start":"stop", 0, NULL) < 0) goto done; } retval = 0; done: return retval; } static int restconf_pseudo_reset(clicon_handle h, const char *db) { int retval = -1; cxobj *xt = NULL; /* Get data as xml from db1 */ if (xmldb_get(h, (char*)db, NULL, "/restconf[enable='true']", &xt) < 0) goto done; if (xt && xml_child_nr(xt)) if (clixon_process_operation(h, RESTCONF_PROCESS, "start", 0, NULL) < 0) goto done; retval = 0; done: return retval; } /*! Register start/stop restconf RPC and create pseudo-plugin to monitor enable flag * @param[in] h Clixon handle */ static int restconf_pseudo_process_reg(clicon_handle h, yang_stmt *yspec) { int retval = -1; clixon_plugin *cp = NULL; if (clixon_pseudo_plugin(h, "restconf pseudo plugin", &cp) < 0) goto done; cp->cp_api.ca_reset = restconf_pseudo_reset; cp->cp_api.ca_trans_commit = restconf_pseudo_process_commit; cp->cp_api.ca_trans_validate = restconf_pseudo_process_validate; /* Register generic process-control of restconf daemon, ie start/stop restconf */ if (restconf_pseudo_process_control(h) < 0) goto done; retval = 0; done: return retval; } /* Debug timer */ int backend_timer_setup(int fd, void *arg) { int retval = -1; clicon_handle h = (clicon_handle)arg; struct timeval now; struct timeval t; struct timeval t1 = {10, 0}; clicon_debug(1, "%s", __FUNCTION__); gettimeofday(&now, NULL); backend_client_print(h, stderr); xmldb_print(h, stderr); fprintf(stderr, "\n"); /* Initiate new timer */ timeradd(&now, &t1, &t); if (clixon_event_reg_timeout(t, backend_timer_setup, /* this function */ h, /* clicon handle */ "backend timer setup") < 0) goto done; retval = 0; done: return retval; } /*! usage */ static void usage(clicon_handle h, char *argv0) { char *plgdir = clicon_backend_dir(h); char *confsock = clicon_sock_str(h); char *confpid = clicon_backend_pidfile(h); char *group = clicon_sock_group(h); fprintf(stderr, "usage:%s *\n" "where options are\n" "\t-h\t\tHelp\n" "\t-D \tDebug level\n" "\t-f \tCLICON config file\n" "\t-E \tExtra configuration file directory\n" "\t-l (s|e|o|f) Log on (s)yslog, std(e)rr or std(o)ut (stderr is default) Only valid if -F, if background syslog is on syslog.\n" "\t-d \tSpecify backend plugin directory (default: %s)\n" "\t-p \tYang directory path (see CLICON_YANG_DIR)\n" "\t-b \tSpecify XMLDB database directory\n" "\t-F\t\tRun in foreground, do not run as daemon\n" "\t-z\t\tKill other config daemon and exit\n" "\t-a UNIX|IPv4|IPv6 Internal backend socket family\n" "\t-u \tInternal socket domain path or IP addr (see -a)(default: %s)\n" "\t-P \tPid filename (default: %s)\n" "\t-1\t\tRun once and then quit (dont wait for events)\n" "\t-s \tSpecify backend startup mode: none|startup|running|init)\n" "\t-c \tLoad extra xml configuration, but don't commit.\n" "\t-q \t\tQuit startup directly after upgrading and print result on stdout\n" "\t-U \tRun backend daemon as this user AND drop privileges permanently\n" "\t-g \tClient membership required to this group (default: %s)\n" "\t-y \tLoad yang spec file (override yang main module)\n" "\t-o \"