def checkServiceCall(self, context, service_name): """ if called by a user and service modify configuration then check user have acquired 'ufwi_conf_write' lock. See session.acquire(...). Lock is acquired with ufwi_conf.takeWriteRole(). """ component_ctx = Context.fromComponent(self) if 'ufwi_conf' not in self.core.getComponentList(component_ctx): # Lock must be acquired by calling ufwi_conf.takeWriteRole(). If ufwi_conf # component is missing user will not be able to acquire the lock, # therefore lock checking is disabled if ufwi_conf component is not # loaded self.warning("Could not find ufwi_conf component: " "sessions are able to modify configuration concurrently") return if (service_name in self.roles['ufwi_conf_read']) \ or (service_name not in self.roles['ufwi_conf_write']): # Only check the lock for editing services return # Check if the user has the lock if not self.core.lock_manager.contextHasLock(context, 'ufwi_conf_write'): service = "%s.%s()" % (self.name, service_name) raise LockError( tr("You need ufwi_conf lock to call the %s service: call ufwi_conf.takeWriteRole()"), service)
def init(self, core): AbstractNuConfComponent.init(self, core) self.context = Context.fromComponent(self) self.var_dir = self.core.config.get('CORE', 'vardir') self.ufwi_conf_var_dir = join(self.var_dir, 'ufwi_conf') if self.core.config.getboolean('CORE', 'use_edenwall'): warn_dangerous_files(self) if not check_and_correct_lo(self): self.critical("Networking configuration problem. :-(") self.core = core self.ethtool = Ethtool('/usr/sbin/ethtool', self) if not self.config_loaded: self.autoconf() self.save_config( CONFIG_AUTOCONFIGURATION, "network : auto configuration", self.context ) else: self.info("not autoconfiguring") self.core.notify.connect('ha', 'ImportStart', self.__haImportStart) self.core.notify.connect('ha', 'ImportEnd', self.__haImportEnd)
def service_getStatus(self, context): """ return 2 lists of components which are - remote services - local services [ 'ntp', 'dhcp' ], ['antispam'] """ defer = None filtered_components = [] # allowed services which can be filtered local_components = [] # local services # use status component context to be allowed to call # the getStatus() service of all components context = Context.fromComponent(self) for component_name in self.core.getComponentList(context): component = self.core.getComponent(context, component_name) if issubclass(component.__class__, UnixServiceComponent): if defer is None: #first iteration, we create the deferred and add the first callback defer = self.core.callService(context, component_name, 'getPorts') defer.addCallback(self.addComponent, component_name, filtered_components, local_components, context) else: #next iterations, we append the callService and the handler to the deffered defer.addCallback(lambda unused: self.core.callService(context, component_name, 'getPorts')) defer.addCallback(self.addComponent, component_name, filtered_components, local_components, context) if defer is None: return [], [] defer.addCallback(self.getAllStates) defer.addErrback(self.handleError) return defer
def init_done(self): d = self.loadConfig() if self.NAME != "multisite_master": # arf.. ctx = Context.fromComponent(self) d.addCallback(lambda x: self.core.callService(ctx, "multisite_master", "registerSubComponent", self.NAME)) return d
def loadTransport(self, *args): server_certs_name = MULTISITE_CERT_NAME + '-server' d = self.pki.loadServerCerts(server_certs_name, 'server') d.addCallback(self.startTransport, server_certs_name) d.addCallback(lambda x: self.pki.loadServerCerts(MULTISITE_CERT_NAME, 'client')) d.addCallback(self.startClientTransport, MULTISITE_CERT_NAME) d.addCallback(lambda x: self.core.callService(Context.fromComponent(self), 'multisite_transport', 'start', TRANSPORT_ID)) return d
def ha_time_sync(self): context = Context.fromComponent(self) if not self.core.hasComponent(context, 'ha'): return try: yield self.core.callService(context, 'ha', 'syncTime') except Exception, err: self.writeError(err, "syncTime error")
def _close_and_stop(self): context = Context.fromComponent(self) localfw = LocalFW('ids_ips') try: yield localfw.execute(self.core, context) except Exception, err: self.writeError(err, 'Error while handling firewall rules for the ids-ips') raise
def genConfigFiles(self, responsible): templates_variables = {} for attr in AntispamConf.ATTRS: templates_variables[attr] = getattr(self.config, attr) context = Context.fromComponent(self) fqdn = yield self.core.callService(context, "hosts", "getFqdn") templates_variables["fqdn"] = fqdn templates_variables["use_antispam"] = self.config.use_antispam self.generate_configfile(templates_variables)
def __init__(self, component, core): self.core = core self.ctx = Context.fromComponent(component) self.ca_path = {} self.key_path = {} self.cert_path = {} self.ca = {} self.key = {} self.cert = {}
def _fetchResolv(self): context = Context.fromComponent(self) serialized_resolvcfg = yield self.core.callService( context, 'resolv', 'getResolvConfig' ) resolvcfg = deserializeResolv(serialized_resolvcfg) returnValue(resolvcfg)
def unregister(self): self.info('Unregistering secondary') if self.primary: ret = yield self.primary.unregister() self.primary = None if ret is not None: ctx = Context.fromComponent(self.component) yield self.core.callService(ctx, 'multisite_transport', 'removeRemote', TRANSPORT_ID, '5.0.0.1')
def __init__(self, secondary): self.hello_task_id = None self.component = secondary.component self.core = secondary.core self.ctx = Context.fromComponent(self.component) self.state = self.INIT self.vars = VariablesStore() LoggerChild.__init__(self, self.component)
def applyRules(self, sched_options, template, template_version, ruleset, association): self.template = template self.template_version = template_version self.ruleset = ruleset self.association = association self.last_sent = int(time.time()) self.save() ctx = Context.fromComponent(self.component) task = RuleApplicationTask(self.core, ctx, self, sched_options, self.template, deepcopy(self.generic_links)) self.setTask(task)
def subComponentCall(self, *args): ctx = Context.fromComponent(self) def lambda_x(func, *args): return lambda x: func(*args) d = succeed('done') for component in self.subcomponents: d.addCallback(lambda_x(self.core.callService, ctx, component, *args)) d.addErrback(self.writeError) return d
def apply_config(self, responsible, paths, arg=None): """ start/stop services if needed """ self.generate_configfile({}) # no template variables context = Context.fromComponent(self) defer = self.core.callService(context, self.NAME, 'status') defer.addCallback(self._call_init_script, context) defer.addErrback(self.writeError) return defer
def genConfigFiles(self, responsible): if self.__hascustom(): custom = CUSTOM_DHCP else: custom = False try: context = Context.fromComponent(self) ha_status = yield self.core.callService(context, 'ha', 'getHAMode') except Exception, err: self.error(exceptionAsUnicode(err)) ha_status = ENOHA
def _nupkiCRLUpdated(self, notify_context): config = self._getSSLConfig() if not config['use_nupki']: return pki_name = notify_context.pki_name if config['nupki_pki'] != pki_name: return self.cert_logger.error("Copy updated PKI CRL") context = Context.fromComponent(self) yield self.core.callService(context, 'nupki', 'copyCRL', pki_name, self.CRL_PATH) self._onCRLUpdated()
def init(self, core): self.core = core self.notify = core.notify self.config = RulesetConfig(self) if core.config.getboolean('CORE', 'use_edenwall'): self.input_output_rules = core.conf_get_var_or_default( 'ufwi_ruleset', 'input_output_rules', default=False, type='bool') else: self.input_output_rules = True self.ufwi_ruleset_context = Context.fromComponent(self) events.connect('ufwi_rpcdServerStarted', self._ufwi_rpcdStarted)
def check_and_react(self, manual_purge=False): yield deferToThread(self._check_and_react, manual_purge) try: if self.registered_for_mail.new_alerts: body = self.registered_for_mail.make_body() context = Context.fromComponent(self) yield self.core.callService(context, 'contact', 'sendMailToAdmin', subjects.get(self.config.language, subjects["en"]), body) except Exception, err: self.writeError(err, "Error while sending alert e-mail")
def _stopvpn(self): yield deferToThread(vpnrules, self, False) localfw = LocalFW('vpn_support') # don't create any rule: just clear existing rules context = Context.fromComponent(self) try: yield localfw.execute(self.core, context) except Exception, err: self.writeError(err, 'Error while disabling firewall rules for the VPN support') raise
def _setSSLConfigNuPKI(self, config): pki = config.get('nupki_pki', u'') cert = config.get('nupki_cert', u'') self.cert_logger.error('Copy certificate "%s" of the PKI "%s".' % (cert, pki)) comp_ctx = Context.fromComponent(self) yield self.core.callService(comp_ctx, 'nupki', 'copyPKI', pki, cert, {'ca': self.CA_PATH, 'certificate': self.CERT_PATH, 'key': self.KEY_PATH, 'crl': self.CRL_PATH})
def changeable(self): if self._isChangeForbidden(): returnValue(NOT_CHANGEABLE) context = Context.fromComponent(self) serialized_nuauthcfg = yield self.core.callService( context, "nuauth", "getNuauthConfig" ) nuauthcfg = NuauthCfg.deserialize(serialized_nuauthcfg) changeable = CHANGE_DISCOURAGED if nuauthcfg.hasAD() else CHANGEABLE returnValue(changeable)
def getLicenseInfo(self): ctx = Context.fromComponent(self) info = yield self.core.callService(ctx, 'license', 'getLicenseInfo') model = info.get('model', '') ID = info.get('ID', '') owner = info.get('owner', '') self.values['model'] = model self.values['serial'] = ID self.values['client'] = owner # For compatibility with old EAS. self.values['type'] = model
def sendMailToAdmin(self, subject, body): template_variables = {'body': body, 'subject': subject} context = Context.fromComponent(self) defer = self.core.callService(context, 'resolv', 'getDomain') defer.addCallback(self._addMyDomain, template_variables) defer.addCallback(lambda x: self.core.callService(context, 'hostname', 'getShortHostname')) defer.addCallback(self._addMyHostname, template_variables) defer.addCallback(lambda x: self.core.callService(context, 'license', 'getID')) defer.addCallback(self._addMyID, template_variables) defer.addCallback(self.sendMailToAdmin_cb, template_variables) return defer
def applyRules(self, save=False, already_read=False): if not already_read: self.read_config(None) context = Context.fromComponent(self) self.debug('First loading of configuration') defer = self.update() # FIXME: Check permissions? # defer.addCallback(lambda unused: self.checkPermissions(self.permissions)) defer.addCallback(self._applyGetNetcfg, context) if save: defer.addCallback(self._save_config) return defer
def read_config(self, responsible, *args, **kwargs): if (responsible is not None) \ and (responsible.caller_component == "dhcp"): return try: serialized_dhcpcfg = self.core.config_manager.get(self.NAME) except ConfigError: dhcpcfg = DHCPCfg() self.debug("Could not read a DHCP config. Defaults loaded.") else: context = Context.fromComponent(self) serialized_netcfg = yield self.core.callService(context, 'network', 'getNetconfig') dhcpcfg = self._deserializeDhcpConfig(serialized_netcfg, serialized_dhcpcfg) self._setDhcpConfig(dhcpcfg)
def update_hostname(self): """ add 127.0.1.1 line must not failed, if error don't add line starting with "127.0.1.1" in configuration """ try: context = Context.fromComponent(self) hostname = yield self.core.callService(context, 'hostname', 'getShortHostname') domain = yield self.core.callService(context, 'resolv', 'getDomain') self.change_hostname(hostname, domain) except Exception, err: # eat error self.writeError(err)
def service_callRemote(self, ctx, component, service, *args): """ Call a remote service on primary. @param component component called on primary (str) @param service service called (str) @param args service's arguments (dict) @return service result """ if not self.primary or self.primary.state != self.primary.ONLINE: raise RpcdError("HA isn't enabled. calling %s.%s() : %s" % unicode(component, service, self.primary.state)) ctx_component = Context.fromComponent(self.component) return self.core.callService(ctx_component, 'multisite_transport', 'callRemote', TRANSPORT_ID, 'primary', component, service, *args)
def apply_config(self, responsible, paths, arg=None): # FIXME don't restart all vpn when network is modified context = Context.fromComponent(self) # on secondary if vpn at least one vpn is active, ipsec is an ha ressource # if ipsec is an ha ressource, when starting heartbeat will start ipsec (ha # component depends on site2site component) ipsec_is_ha_ressource = False if EDENWALL: try: ha_type = yield self.core.callService(context, 'ha', 'getHAMode') ipsec_is_ha_ressource = ha_type in [PRIMARY, SECONDARY] except Exception, err: self.debug("can not read high availability status") self.writeError(err)
def setFirewallRules(self, *args): # FIXME: use LocalFW wrapper comp_ctx = Context.fromComponent(self) d = self.core.callService(comp_ctx, 'localfw', 'open', 'multisiterules') d.addCallback(lambda x:self.core.callService(comp_ctx, 'localfw', 'addFilterRule', {'chain': 'INPUT', 'decision': 'ACCEPT', 'protocol': 'udp', 'dport': OPENVPN_PORT})) d.addCallback(lambda x:self.core.callService(comp_ctx, 'localfw', 'addFilterRule', {'chain': 'INPUT', 'input': OPENVPN_IF, 'decision': 'ACCEPT', 'protocol': 'tcp', 'dport': RPCD_PORT})) d.addCallback(lambda x:self.core.callService(comp_ctx, 'localfw', 'addFilterRule', {'chain': 'FORWARD', 'output': OPENVPN_IF, 'decision': 'DROP'})) d.addCallback(lambda x:self.core.callService(comp_ctx, 'localfw', 'apply')) d.addCallback(lambda x:self.core.callService(comp_ctx, 'localfw', 'close')) d.addErrback(self.localfwFailed, comp_ctx) return d