def exec_request(self, kwargs): try: if 'id' not in kwargs or 'endpoint' not in kwargs: return jsonbak.dumps({'error': 'Missing ID or endpoint.'}) if 'method' not in kwargs: method = 'GET' elif kwargs['method'] == 'GET': del kwargs['method'] method = 'GET' else: if str(self.getSelfAdminStanza()['admin']) != 'true': self.logger.error('Admin mode is disabled.') return jsonbak.dumps({'error': 'Forbidden. Enable admin mode.'}) method = kwargs['method'] del kwargs['method'] the_id = kwargs['id'] url, auth, verify, cluster_enabled = self.get_credentials(the_id) opt_endpoint = kwargs["endpoint"] del kwargs['id'] del kwargs['endpoint'] daemons_ready = self.check_daemons(url, auth, verify, cluster_enabled) if not daemons_ready: return jsonbak.dumps({"status": "200", "error": 3099, "message": "Wazuh not ready yet."}) request = self.make_request(method, url, opt_endpoint, kwargs, auth, verify) result = jsonbak.dumps(request) except Exception as e: self.logger.error("Error making API request: %s" % (e)) return jsonbak.dumps({'error': str(e)}) return result
def wazuh_ready(self, **kwargs): """Endpoint to check daemons status. Parameters ---------- kwargs : dict Request parameters """ try: self.logger.debug("api: Checking if Wazuh is ready.") if 'apiId' not in kwargs: return jsonbak.dumps({'error': 'Missing API ID.'}) the_id = kwargs['apiId'] url, auth, verify, cluster_enabled = self.get_credentials(the_id) daemons_ready = self.check_daemons(url, auth, verify, cluster_enabled) msg = "Wazuh is now ready." if daemons_ready else "Wazuh not ready yet." self.logger.debug("api: %s" % msg) return jsonbak.dumps({ "status": "200", "ready": daemons_ready, "message": msg }) except Exception as e: self.logger.error("api: Error checking daemons: %s" % (e)) return jsonbak.dumps({ "status": "200", "ready": False, "message": "Error getting the Wazuh daemons status." })
def update_api(self, **kwargs): """Update Wazuh API. Parameters ---------- kwargs : dict The request's parameters """ try: self.logger.debug("manager: Updating API information.") entry = kwargs if '_user' in kwargs: del kwargs['_user'] if not "passapi" in entry: opt_id = entry["_key"] data_temp = self.db.get(opt_id) current_api = jsonbak.loads(data_temp) current_api = current_api["data"] entry["passapi"] = current_api["passapi"] keys_list = ['_key', 'url', 'portapi', 'userapi', 'passapi', 'filterName', 'filterType', 'managerName'] if set(entry.keys()) == set(keys_list): self.db.update(entry) parsed_data = jsonbak.dumps({'data': 'success'}) else: missing_params = diff_keys_dic_update_api(entry) raise Exception( "Invalid arguments, missing params : %s" % str(missing_params)) except Exception as e: self.logger.error("manager: Error in update_api endpoint: %s" % (e)) return jsonbak.dumps({"error": str(e)}) return parsed_data
def add_job(self, **kwargs): """Add job to the queue. Parameters ---------- kwargs : dict Request parameters """ try: self.logger.debug("queue: Adding job to the jobs queue.") now = time.time() exec_time = now + float(kwargs['delay']) del kwargs['delay'] job = { "job": kwargs, "added": now, "exec_time": exec_time, "done": 0 } self.queue.insert_job(job) return jsonbak.dumps({ "data": "Job added to the queue.", "error": 0 }) except Exception as e: self.logger.error("queue: Error adding job: %s" % (e)) return jsonbak.dumps({'error': str(e)})
def update(self, obj): """Update an already inserted API. Parameters ---------- obj : dict The API to edit. """ try: self.logger.debug("bin.db: Updating API.") if not '_key' in obj: raise Exception('Missing Key') id = obj['_key'] del obj['_key'] obj = jsonbak.dumps(obj) kvstoreUri = self.kvstoreUri + '/' + id + '?output_mode=json' result = self.session.post(kvstoreUri, data=obj, headers={ "Authorization": "Splunk %s" % splunk.getSessionKey(), "Content-Type": "application/json" }, verify=False).json() parsed_result = jsonbak.dumps({'data': result}) return parsed_result except Exception as e: self.logger.error("Error updating in DB module: %s" % (e)) raise e
def add_api(self, **kwargs): """Add a Wazuh API. Parameters ---------- kwargs : dict The request's parameters """ try: self.logger.debug("manager: Adding a new API.") record = kwargs keys_list = [ 'url', 'portapi', 'userapi', 'passapi', 'managerName', 'filterType', 'filterName' ] if set(record.keys()) == set(keys_list): key = self.db.insert(jsonbak.dumps(record)) parsed_data = jsonbak.dumps({'result': key}) return parsed_data else: raise Exception('Invalid number of arguments') except Exception as e: self.logger.error({'manager - add_api': str(e)}) return jsonbak.dumps({'error': str(e)})
def autocomplete(self, **kwargs): """Provisional method for returning the full list of Wazuh API endpoints.""" try: self.logger.debug("Returning autocomplet for devtools.") parsed_json = jsonbak.dumps([{"method":'PUT',"endpoints":[{"name":'/active-response/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/group/:group_id',"args":[{"name":':agent_id'},{"name":':group_id'}]},{"name":'/agents/:agent_id/restart',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/upgrade',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/upgrade_custom',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_name',"args":[{"name":':agent_name'}]},{"name":'/agents/groups/:group_id',"args":[{"name":':group_id'}]},{"name":'/agents/restart',"args":[]},{"name":'/cluster/:node_id/restart',"args":[{"name":':node_id'}]},{"name":'/cluster/restart',"args":[]},{"name":'/manager/restart',"args":[]},{"name":'/rootcheck',"args":[]},{"name":'/rootcheck/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/syscheck',"args":[]},{"name":'/syscheck/:agent_id',"args":[{"name":':agent_id'}]}]},{"method":'DELETE',"endpoints":[{"name":'/agents',"args":[]},{"name":'/agents/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/group',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/group/:group_id',"args":[{"name":':agent_id'},{"name":':group_id'}]},{"name":'/agents/group/:group_id',"args":[{"name":':group_id'}]},{"name":'/agents/groups',"args":[]},{"name":'/agents/groups/:group_id',"args":[{"name":':group_id'}]},{"name":'/cache',"args":[]},{"name":'/cache',"args":[]},{"name":'/rootcheck',"args":[]},{"name":'/rootcheck/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/syscheck/:agent_id',"args":[{"name":':agent_id'}]}]},{"method":'GET',"endpoints":[{"name":'/agents',"args":[]},{"name":'/agents/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/config/:component/:configuration',"args":[{"name":':agent_id'},{"name":':component'},{"name":':configuration'}]},{"name":'/agents/:agent_id/group/is_sync',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/key',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/upgrade_result',"args":[{"name":':agent_id'}]},{"name":'/agents/groups',"args":[]},{"name":'/agents/groups/:group_id',"args":[{"name":':group_id'}]},{"name":'/agents/groups/:group_id/configuration',"args":[{"name":':group_id'}]},{"name":'/agents/groups/:group_id/files',"args":[{"name":':group_id'}]},{"name":'/agents/groups/:group_id/files/:filename',"args":[{"name":':group_id'},{"name":':filename'}]},{"name":'/agents/name/:agent_name',"args":[{"name":':agent_name'}]},{"name":'/agents/no_group',"args":[]},{"name":'/agents/outdated',"args":[]},{"name":'/agents/stats/distinct',"args":[]},{"name":'/agents/summary',"args":[]},{"name":'/agents/summary/os',"args":[]},{"name":'/cache',"args":[]},{"name":'/cache/config',"args":[]},{"name":'/ciscat/:agent_id/results',"args":[{"name":':agent_id'}]},{"name":'/cluster/:node_id/configuration',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/configuration/validation',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/files',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/info',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/logs',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/logs/summary',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/stats',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/stats/analysisd',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/stats/hourly',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/stats/remoted',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/stats/weekly',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/status',"args":[{"name":':node_id'}]},{"name":'/cluster/config',"args":[]},{"name":'/cluster/configuration/validation',"args":[]},{"name":'/cluster/healthcheck',"args":[]},{"name":'/cluster/node',"args":[]},{"name":'/cluster/nodes',"args":[]},{"name":'/cluster/nodes/:node_name',"args":[{"name":':node_name'}]},{"name":'/cluster/status',"args":[]},{"name":'/manager/stats/remoted',"args":[]},{"name":'/sca/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/sca/:agent_id/checks/:id',"args":[{"name":':agent_id'},{"name":':id'}]},{"name":'/decoders',"args":[]},{"name":'/decoders/:decoder_name',"args":[{"name":':decoder_name'}]},{"name":'/decoders/files',"args":[]},{"name":'/decoders/parents',"args":[]},{"name":'/lists',"args":[]},{"name":'/lists/files',"args":[]},{"name":'/manager/configuration',"args":[]},{"name":'/manager/configuration/validation',"args":[]},{"name":'/manager/files',"args":[]},{"name":'/manager/info',"args":[]},{"name":'/manager/logs',"args":[]},{"name":'/manager/logs/summary',"args":[]},{"name":'/manager/stats',"args":[]},{"name":'/manager/stats/analysisd',"args":[]},{"name":'/manager/stats/hourly',"args":[]},{"name":'/manager/stats/remoted',"args":[]},{"name":'/manager/stats/weekly',"args":[]},{"name":'/manager/status',"args":[]},{"name":'/rootcheck/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/rootcheck/:agent_id/cis',"args":[{"name":':agent_id'}]},{"name":'/rootcheck/:agent_id/last_scan',"args":[{"name":':agent_id'}]},{"name":'/rootcheck/:agent_id/pci',"args":[{"name":':agent_id'}]},{"name":'/rules',"args":[]},{"name":'/rules/:rule_id',"args":[{"name":':rule_id'}]},{"name":'/rules/files',"args":[]},{"name":'/rules/gdpr',"args":[]},{"name":'/rules/nist-800-53',"args":[]},{"name":'/rules/hipaa',"args":[]},{"name":'/rules/groups',"args":[]},{"name":'/rules/pci',"args":[]},{"name":'/syscheck/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/syscheck/:agent_id/last_scan',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/hardware',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/netaddr',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/netiface',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/netproto',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/os',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/packages',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/ports',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/processes',"args":[{"name":':agent_id'}]}]},{"method":'POST',"endpoints":[{"name":'/agents',"args":[]},{"name":'/agents/group/:group_id',"args":[{"name":':group_id'}]},{"name":'/agents/groups/:group_id/configuration',"args":[{"name":':group_id'}]},{"name":'/agents/groups/:group_id/files/:file_name',"args":[{"name":':group_id'},{"name":':file_name'}]},{"name":'/agents/insert',"args":[]},{"name":'/agents/restart',"args":[]},{"name":'/cluster/:node_id/files',"args":[{"name":':node_id'}]},{"name":'/manager/files',"args":[]}]}]) except Exception as e: return jsonbak.dumps({'error': str(e)}) return parsed_json
def check_connection(self, **kwargs): """Check API connection. Parameters ---------- kwargs : dict The request's parameters """ try: self.logger.debug("manager: Checking API connection.") opt_username = kwargs["user"] opt_password = kwargs["pass"] opt_base_url = kwargs["ip"] opt_base_port = kwargs["port"] opt_cluster = kwargs["cluster"] == "true" url = opt_base_url + ":" + opt_base_port auth = requestsbak.auth.HTTPBasicAuth(opt_username, opt_password) verify = False try: self.check_wazuh_version(kwargs) except Exception as e: error = {"status": 400, "error": str(e)} return jsonbak.dumps(error) daemons_ready = self.check_daemons(url, auth, verify, opt_cluster, kwargs) # Pass the cluster status instead of always False if not daemons_ready: raise Exception("DAEMONS-NOT-READY") output = self.get_cluster_info(opt_username, opt_password, opt_base_url, opt_base_port, opt_cluster) result = jsonbak.dumps(output) except Exception as e: if e == "DAEMONS-NOT-READY": self.logger.error( "manager: Cannot connect to API; Wazuh not ready yet.") return jsonbak.dumps({ "status": "200", "error": 3099, "message": "Wazuh not ready yet." }) else: self.logger.error("manager: Cannot connect to API : %s" % (e)) return jsonbak.dumps({ "status": 400, "error": "Cannot connect to the API" }) return result
def get_config(self): """Gets the configuration. Parameters ---------- kwargs : dict Request parameters """ try: self.logger.debug("config: Reading the config.conf file.") config = self.config.get_config() return jsonbak.dumps({"data": config, "error": 0}) except Exception as e: self.logger.error("config: Error getting the configuration: %s" % (e)) return jsonbak.dumps({'error': str(e)})
def autocomplete(self, **kwargs): """Provisional method for returning the full list of Wazuh API endpoints.""" try: self.logger.debug("Returning autocomplete for devtools.") return api_info.get_api_endpoints() except Exception as e: return jsonbak.dumps({'error': str(e)})
def update_config(self, **kwargs): """Updates a parameter of the configuration. Parameters ---------- kwargs : dict Request parameters """ try: self.logger.debug("config: Updating configuration.") result = self.config.update_config(kwargs) return jsonbak.dumps({"data": result, "error": 0}) except Exception as e: self.logger.error("config: Error updating the configuration: %s" % (e)) return jsonbak.dumps({'error': str(e)})
def format_output(self, arr): """Format the data for the CSV file generation. Parameters ---------- arr : list A list of dicts """ try: self.logger.debug("api: Formatting data to generate CSV file.") if isinstance(arr, list): for item in arr: if isinstance(item, dict): for key, value in item.items(): if isinstance(value, dict): item[key] = jsonbak.dumps(value) elif isinstance(value, list): i = 0 while i < len(value): value[i] = str(value[i]) i += 1 else: item[key] = str(value) elif isinstance(item, list): for each in item: each = str(each) else: item = str(item) return arr except Exception as e: raise e
def update_job(self, job, session_key=False): """Update an already inserted API. Parameters ---------- obj : dict The API to edit. """ try: self.logger.debug("bin.jobs_queue: Updating job.") if not '_key' in job: raise Exception('Missing Key') id = job['_key'] del job['_key'] job = jsonbak.dumps(job) kvstoreUri = self.kvstoreUri+'/'+id+'?output_mode=json' auth_key = session_key if session_key else splunk.getSessionKey() result = self.session.post(kvstoreUri, data=job, headers={ "Authorization": "Splunk %s" % auth_key, "Content-Type": "application/json"}, verify=False).json() if '_key' in result.keys() and result['_key'] == id: return 'Job updated.' else: raise Exception('Job cannot be updated.') except Exception as e: self.logger.error("bin.jobs_queu: Error updating in JobsQueue module: %s" % (e)) raise e
def remove(self, _key): """Remove an API. Parameters ---------- obj : dict The API to be removed. """ try: self.logger.debug("bin.db: Removing API.") if not _key: raise Exception('Missing ID in remove DB module') kvstoreUri = self.kvstoreUri + '/' + str( _key) + '?output_mode=json' result = self.session.delete(kvstoreUri, headers={ "Authorization": "Splunk %s" % splunk.getSessionKey(), "Content-Type": "application/json" }, verify=False) if result.status_code == 200: parsed_result = jsonbak.dumps({'data': 'API removed.'}) else: msg = jsonbak.loads(result.text) text = msg['messages'][0]['text'] raise Exception(text) return parsed_result except Exception as e: self.logger.error("Error removing an API in DB module: %s" % (e)) raise e
def all(self, session_key=False): try: self.logger.debug("bin.db: Getting all APIs .") kvstoreUri = self.kvstoreUri + '?output_mode=json' auth_key = session_key if session_key else splunk.getSessionKey() result = self.session.get(kvstoreUri, headers={ "Authorization": "Splunk %s" % auth_key, "Content-Type": "application/json" }, verify=False).json() return jsonbak.dumps(result) except Exception as e: self.logger.error( 'Error returning all API rows in DB module: %s ' % (e)) return jsonbak.dumps({"error": str(e)})
def check_connection_by_id(self, **kwargs): """Given an API id we check the connection. Parameters ---------- kwargs : dict The request's parameters """ try: self.logger.debug("manager: Checking API connection by id.") opt_id = kwargs["apiId"] current_api = self.get_api(apiId=opt_id) current_api_json = jsonbak.loads(jsonbak.loads(current_api)) if not "data" in current_api_json: return jsonbak.dumps({"status": "400", "error": "Error when checking API connection."}) opt_username = str(current_api_json["data"]["userapi"]) opt_password = str(current_api_json["data"]["passapi"]) opt_base_url = str(current_api_json["data"]["url"]) opt_base_port = str(current_api_json["data"]["portapi"]) opt_cluster = False if "cluster" in current_api_json["data"]: opt_cluster = current_api_json["data"]["cluster"] == "true" url = opt_base_url + ":" + opt_base_port auth = requestsbak.auth.HTTPBasicAuth(opt_username, opt_password) verify = False try: manager_info = self.session.get( url + '/manager/info', auth=auth, timeout=20, verify=verify) manager_info = manager_info.json() except ConnectionError as e: self.logger.error("manager: Cannot connect to API : %s" % (e)) return jsonbak.dumps({"status": "400", "error": "Unreachable API, please check the URL and port."}) output = {} if "error" in manager_info and manager_info["error"] != 0: #Checks if daemons are up and running return jsonbak.dumps({"status": "400", "error": manager_info["message"]}) output['managerName'] = { 'name' : manager_info['data']['name'] } output['clusterMode'] = { "enabled" : manager_info['data']['cluster']['enabled'], "running" : manager_info['data']['cluster']['running'] } output['clusterName'] = { "type" : manager_info['data']['cluster']['node_type'], "cluster" : manager_info['data']['cluster']['name'], "node" : manager_info['data']['cluster']['node_name'] } del current_api_json["data"]["passapi"] output['api'] = current_api_json result = jsonbak.dumps(output) except Exception as e: self.logger.error("Error when checking API connection: %s" % (e)) raise e return result
def get_log_lines(self, **kwargs): """Get last log lines. Parameters ---------- kwargs : dict The request's parameters """ try: self.logger.debug("manager: Getting last log lines.") lines = self.logger.get_last_log_lines(20) parsed_data = jsonbak.dumps({'logs': lines}) except Exception as e: self.logger.error("manager: Get_log_lines endpoint: %s" % (e)) return jsonbak.dumps({"error": str(e)}) return parsed_data
def get_config_on_memory(self): try: self.logger.debug("api: Getting configuration on memory.") config = cli.getConfStanza("config", "configuration") return config except Exception as e: self.logger.error("api: Error getting the configuration on memory: %s" % (e)) return jsonbak.dumps({"error": str(e)})
def get_apis(): """Obtain the list of APIs.""" try: logger.debug("bin.get_agents_status: Getting APIs.") session_key = getSplunkSessionKey() data_temp = db.all(session_key) except Exception as e: return jsonbak.dumps({'error': str(e)}) return data_temp
def request(self, **kwargs): """Make requests to the Wazuh API as a proxy backend. Parameters ---------- kwargs : dict Request parameters """ try: self.logger.debug("api: Preparing request.") if 'apiId' not in kwargs or 'endpoint' not in kwargs: return jsonbak.dumps({'error': 'Missing ID or endpoint.'}) if 'method' not in kwargs: method = 'GET' elif kwargs['method'] == 'GET': del kwargs['method'] method = 'GET' else: if str(self.getSelfAdminStanza()['admin']) != 'true': self.logger.error('api: Admin mode is disabled.') return jsonbak.dumps( {'error': 'Forbidden. Enable admin mode.'}) method = kwargs['method'] del kwargs['method'] the_id = kwargs['apiId'] url, auth, verify, cluster_enabled = self.get_credentials(the_id) opt_endpoint = kwargs["endpoint"] del kwargs['apiId'] del kwargs['endpoint'] daemons_ready = self.check_daemons(url, auth, verify, cluster_enabled) if not daemons_ready: return jsonbak.dumps({ "status": "200", "error": 3099, "message": "Wazuh not ready yet." }) request = self.make_request(method, url, opt_endpoint, kwargs, auth, verify) result = jsonbak.dumps(request) except Exception as e: self.logger.error("api: Error making API request: %s" % (e)) return jsonbak.dumps({'error': str(e)}) return result
def app_info(self, **kwargs): """Obtain app information from file. Parameters ---------- kwargs : dict The request's parameters """ try: self.logger.debug("manager: Getting app info.") stanza = cli.getConfStanza('package', 'app') data_temp = stanza stanza = cli.getConfStanza('package', 'splunk') data_temp['splunk_version'] = stanza['version'] parsed_data = jsonbak.dumps(data_temp) except Exception as e: return jsonbak.dumps({'error': str(e)}) return parsed_data
def remove_api(self, **kwargs): """Delete Wazuh API from DB. Parameters ---------- kwargs : dict The request's parameters """ try: self.logger.debug("manager: Removing API.") api_id = kwargs if '_key' not in api_id: return jsonbak.dumps({'error': 'Missing ID'}) self.db.remove(api_id['_key']) parsed_data = jsonbak.dumps({'data': 'success'}) except Exception as e: self.logger.error("manager: Error in remove_api endpoint: %s" % (e)) return jsonbak.dumps({'error': str(e)}) return parsed_data
def get_api(self, **kwargs): """Obtain Wazuh API from DB. Parameters ---------- kwargs : dict The request's parameters """ try: self.logger.debug("manager: Getting API info from _key.") if 'apiId' not in kwargs: return jsonbak.dumps({'error': 'Missing ID.'}) id = kwargs['apiId'] data_temp = self.db.get(id) parsed_data = jsonbak.dumps(data_temp) except Exception as e: self.logger.error("manager: Error in get_apis endpoint: %s" % (e)) return jsonbak.dumps({'error': str(e)}) return parsed_data
def nist(self, **kwargs): try: self.logger.debug("api: Getting NIST 800-53 data.") if not 'requirement' in kwargs: raise Exception('Missing requirement.') nist_description = '' requirement = kwargs['requirement'] if requirement == 'all': if not 'apiId' in kwargs: return jsonbak.dumps(nist_requirements.nist) the_id = kwargs['apiId'] url,auth,verify = self.get_credentials(the_id) opt_endpoint = '/rules/nist-800-53' request = self.session.get( url + opt_endpoint, params=kwargs, auth=auth, verify=verify).json() if request['error'] != 0: return jsonbak.dumps({'error':request['error']}) data = request['data']['items'] result = {} for item in data: result[item] = nist_requirements.nist[item] return jsonbak.dumps(result) else: if not requirement in nist_requirements.nist: return jsonbak.dumps({'error':'Requirement not found.'}) nist_description = nist_requirements.nist[requirement] result = {} result['nist'] = {} result['nist']['requirement'] = requirement result['nist']['description'] = nist_description return jsonbak.dumps(result) except Exception as e: self.logger.error("api: Error getting NIST 800-53 requirements: %s" % (str(e))) return jsonbak.dumps({"error": str(e)})
def gdpr(self, **kwargs): try: self.logger.debug("api: Getting GDPR data.") if not 'requirement' in kwargs: raise Exception('Missing requirement.') pci_description = '' requirement = kwargs['requirement'] if requirement == 'all': if not 'apiId' in kwargs: return jsonbak.dumps(gdpr_requirements.gdpr) the_id = kwargs['apiId'] url,auth,verify,cluster_enabled = self.get_credentials(the_id) opt_endpoint = '/rules/gdpr' request = self.session.get( url + opt_endpoint, params=kwargs, auth=auth, verify=verify).json() if request['error'] != 0: return jsonbak.dumps({'error':request['error']}) data = request['data']['items'] result = {} for item in data: result[item] = gdpr_requirements.gdpr[item] return jsonbak.dumps(result) else: if not requirement in gdpr_requirements.gdpr: return jsonbak.dumps({'error':'Requirement not found.'}) pci_description = gdpr_requirements.gdpr[requirement] result = {} result['gdpr'] = {} result['gdpr']['requirement'] = requirement result['gdpr']['description'] = pci_description return jsonbak.dumps(result) except Exception as e: self.logger.error("api: Error getting PCI-DSS requirements: %s" % (str(e))) return jsonbak.dumps({"error": str(e)})
def get_apis(self, **kwargs): """Obtain all Wazuh APIs from DB. Parameters ---------- kwargs : dict The request's parameters """ try: self.logger.debug("manager: Getting API list.") apis = self.db.all() parsed_apis = jsonbak.loads(apis) # Remove the password from the list of apis for api in parsed_apis: if "passapi" in api: del api["passapi"] result = jsonbak.dumps(parsed_apis) except Exception as e: self.logger.error(jsonbak.dumps({"error": str(e)})) return jsonbak.dumps({"error": str(e)}) return result
def insert_job(self, job, session_key=False): """Insert a job. Parameters ---------- dic : job The job information str : session_key The authorized session key """ try: self.logger.debug("bin.jobs_queu: Inserting job.") kvstoreUri = self.kvstoreUri+'?output_mode=json' auth_key = session_key if session_key else splunk.getSessionKey() job = jsonbak.dumps(job) result = self.session.post(kvstoreUri, data=job, headers={ "Authorization": "Splunk %s" % auth_key, "Content-Type": "application/json"}, verify=False).json() return jsonbak.dumps(result) except Exception as e: self.logger.error('bin.jobs_queu: Error inserting a job in JobsQueue module: %s ' % (e)) return jsonbak.dumps({"error": str(e)})
def polling_state(self, **kwargs): """Check agent monitoring status. Parameters ---------- kwargs : dict The request's parameters """ try: self.logger.debug("manager: Getting agents polling state.") app = cli.getConfStanza( 'inputs', 'script:///opt/splunk/etc/apps/SplunkAppForWazuh/bin/get_agents_status.py') disabled = app.get('disabled') polling_dict = {} polling_dict['disabled'] = disabled data_temp = jsonbak.dumps(polling_dict) except Exception as e: return jsonbak.dumps({'error': str(e)}) return data_temp
def check_connection_by_id(self, **kwargs): """Given an API id we check the connection. Parameters ---------- kwargs : dict The request's parameters """ try: self.logger.debug("manager: Checking API connection by id.") opt_id = kwargs["apiId"] current_api = self.get_api(apiId=opt_id) current_api_json = jsonbak.loads(jsonbak.loads(current_api)) if not "data" in current_api_json: return jsonbak.dumps({ "status": "400", "error": "Error when checking API connection." }) opt_username = str(current_api_json["data"]["userapi"]) opt_password = str(current_api_json["data"]["passapi"]) opt_base_url = str(current_api_json["data"]["url"]) opt_base_port = str(current_api_json["data"]["portapi"]) opt_cluster = False if "cluster" in current_api_json["data"]: opt_cluster = current_api_json["data"]["cluster"] == "true" output = self.get_cluster_info(opt_username, opt_password, opt_base_url, opt_base_port, opt_cluster) del current_api_json["data"]["passapi"] output['api'] = current_api_json result = jsonbak.dumps(output) except Exception as e: self.logger.error("Error when checking API connection: %s" % (e)) raise e return result
def get_log_lines(self, **kwargs): """Get last log lines. Parameters ---------- kwargs : dict The request's parameters """ try: self.logger.debug("manager: Getting last log lines.") lines = self.logger.get_last_log_lines(20) parsed_data = jsonbak.dumps({ 'logs': lines, 'logs_path': make_splunkhome_path( ['var', 'log', 'splunk', 'SplunkAppForWazuh.log']) }) except Exception as e: self.logger.error("manager: Get_log_lines endpoint: %s" % (e)) return jsonbak.dumps({"error": str(e)}) return parsed_data