def apply_standalone_template(request): logger.info("__ input_forms apply_standalone_template __") if "input_form_id" not in request.POST: logger.error("Did no find all required fields in request") return render(request, "error.html", {"error": "Invalid Parameters in POST"}) input_form_id = request.POST["input_form_id"] input_form = InputForm.objects.get(pk=input_form_id) json_object = json.loads(input_form.json) context = Context() for j in json_object: if '.' in j["name"]: # this is a fancy variable name j_dict = aframe_utils.generate_dict(j["name"], str(request.POST[j["name"]])) context.update(j_dict) else: logger.debug("setting context %s" % j["name"]) context[j["name"]] = str(request.POST[j["name"]]) config_template = input_form.script try: compiled_template = engines['django'].from_string(config_template.template) except TemplateSyntaxError as e: logger.error("Caught a template syntax error!") logger.error(str(e)) return render(request, "error.html", {"error": "Invalid Template Syntax: %s" % str(e)}) completed_template = str(compiled_template.render(context)) logger.info(completed_template) action_name = config_template.action_provider logger.info(action_name) action_options = json.loads(config_template.action_provider_options) logger.info(action_options) for ao in action_options: if "action_options_" + str(ao) in request.POST: logger.debug("Found a customized action option!") new_val = request.POST["action_options_" + str(ao)] current_value = action_options[ao]["value"] action_options[ao]["value"] = re.sub("{{ .* }}", new_val, current_value) logger.debug(action_options[ao]["value"]) action = action_provider.get_provider_instance(action_name, action_options) results = action.execute_template(completed_template) context = {"results": results} return render(request, "input_forms/results.html", context)
def apply_standalone_template(request): if "input_form_id" not in request.POST: return render(request, "error.html", {"error": "Invalid Parameters in POST"}) input_form_id = request.POST["input_form_id"] input_form = InputForm.objects.get(pk=input_form_id) json_object = json.loads(input_form.json) context = Context() for j in json_object: print "setting context %s" % j["name"] context[j["name"]] = str(request.POST[j["name"]]) config_template = input_form.script try: compiled_template = engines['django'].from_string(config_template.template) except TemplateSyntaxError as e: print "Caught a template syntax error!" return render(request, "error.html", {"error": "Invalid Template Syntax: %s" % str(e)}) completed_template = str(compiled_template.render(context)) print completed_template action_name = config_template.action_provider print action_name action_options = json.loads(config_template.action_provider_options) print action_options for ao in action_options: if "action_options_" + str(ao) in request.POST: print "Found a customized action option!" new_val = request.POST["action_options_" + str(ao)] current_value = action_options[ao]["value"] action_options[ao]["value"] = re.sub("{{ .* }}", new_val, current_value) print action_options[ao]["value"] action = action_provider.get_provider_instance(action_name, action_options) results = action.execute_template(completed_template) context = {"results": results} return render(request, "input_forms/results.html", context)
def apply_template_to_queue(request): if "input_form_id" not in request.POST: return render(request, "error.html", {"error": "Invalid Parameters in POST"}) input_form_id = request.POST["input_form_id"] endpoints = request.session["endpoint_queue"] input_form = InputForm.objects.get(pk=input_form_id) print input_form.json json_object = json.loads(input_form.json) context = Context() for j in json_object: if '.' in j["name"]: # this is a json capable variable name j_dict = aframe_utils.generate_dict(j["name"], str(request.POST[j["name"]])) context.update(j_dict) else: print "setting context %s" % j["name"] context[j["name"]] = str(request.POST[j["name"]]) print context config_template = input_form.script try: compiled_template = engines['django'].from_string(config_template.template) except TemplateSyntaxError as e: print "Caught a template syntax error!" return render(request, "error.html", {"error": "Invalid Template Syntax: %s" % str(e)}) action_name = config_template.action_provider action_options = json.loads(config_template.action_provider_options) print "action name is: " + action_name print "action options are: " + str(action_options) action = action_provider.get_provider_instance(action_name, action_options) results = "" for endpoint in endpoints: if "username" not in endpoint or endpoint["username"] == "": if "global_username" in request.POST: endpoint["username"] = request.POST["global_username"] else: raise Exception("Authentication is required!") if "password" not in endpoint or endpoint["password"] == "": if "global_password" in request.POST: endpoint["password"] = request.POST["global_password"] else: raise Exception("Authentication is required!") context["af_endpoint_ip"] = endpoint["ip"] context["af_endpoint_username"] = endpoint["username"] context["af_endpoint_password"] = endpoint["password"] context["af_endpoint_type"] = endpoint["type"] completed_template = str(compiled_template.render(context)) results += "================ %s ================\n" % endpoint["name"] action.set_endpoint(endpoint) result = action.execute_template(completed_template) if result == None: result='' results += result results += "\n" context = {"results": results} return render(request, "input_forms/results.html", context)
def apply_template(request): """ :param request: HTTPRequest from the input form :return: results of the template execution """ required_fields = set(["input_form_id", "endpoint_id", "group_id"]) if not required_fields.issubset(request.POST): return render(request, "error.html", {"error": "Invalid Parameters in POST"}) input_form_id = request.POST["input_form_id"] endpoint_id = request.POST["endpoint_id"] group_id = request.POST["group_id"] provider_instance = endpoint_provider.get_provider_instance_from_group(group_id) endpoint = provider_instance.get_endpoint_by_id(endpoint_id) if "username" not in endpoint or endpoint["username"] == "": if "global_username" in request.POST: endpoint["username"] = request.POST["global_username"] else: raise Exception("Authentication is required!") if "password" not in endpoint or endpoint["password"] == "": if "global_password" in request.POST: endpoint["password"] = request.POST["global_password"] else: raise Exception("Authentication is required!") input_form = InputForm.objects.get(pk=input_form_id) print input_form.json json_object = json.loads(input_form.json) context = Context() for j in json_object: if '.' in j["name"]: # this is a json capable variable name j_dict = aframe_utils.generate_dict(j["name"], str(request.POST[j["name"]])) context.update(j_dict) else: print "setting context %s" % j["name"] context[j["name"]] = str(request.POST[j["name"]]) context["af_endpoint_ip"] = endpoint["ip"] context["af_endpoint_username"] = endpoint["username"] context["af_endpoint_password"] = endpoint["password"] context["af_endpoint_type"] = endpoint["type"] print context config_template = input_form.script try: compiled_template = engines['django'].from_string(config_template.template) completed_template = str(compiled_template.render(context)) except TemplateSyntaxError as e: print "Caught a template syntax error!" return render(request, "error.html", {"error": "Invalid Template Syntax: %s" % str(e)}) print "TEMPLATE IS:" print completed_template action_name = config_template.action_provider action_options = json.loads(config_template.action_provider_options) print "action name is: " + action_name action = action_provider.get_provider_instance(action_name, action_options) action.set_endpoint(endpoint) results = action.execute_template(completed_template) context = {"results": results} return render(request, "input_forms/results.html", context)
def apply_template_to_queue(request): if "input_form_id" not in request.POST: return render(request, "error.html", {"error": "Invalid Parameters in POST"}) input_form_id = request.POST["input_form_id"] endpoints = request.session["endpoint_queue"] input_form = InputForm.objects.get(pk=input_form_id) print input_form.json json_object = json.loads(input_form.json) context = Context() for j in json_object: print "setting context %s" % j["name"] context[j["name"]] = str(request.POST[j["name"]]) print context config_template = input_form.script try: compiled_template = engines['django'].from_string(config_template.template) except TemplateSyntaxError as e: print "Caught a template syntax error!" return render(request, "error.html", {"error": "Invalid Template Syntax: %s" % str(e)}) action_name = config_template.action_provider action_options = json.loads(config_template.action_provider_options) print "action name is: " + action_name print "action options are: " + str(action_options) action = action_provider.get_provider_instance(action_name, action_options) results = "" for endpoint in endpoints: if "username" not in endpoint or endpoint["username"] == "": if "global_username" in request.POST: endpoint["username"] = request.POST["global_username"] else: raise Exception("Authentication is required!") if "password" not in endpoint or endpoint["password"] == "": if "global_password" in request.POST: endpoint["password"] = request.POST["global_password"] else: raise Exception("Authentication is required!") context["af_endpoint_ip"] = endpoint["ip"] context["af_endpoint_username"] = endpoint["username"] context["af_endpoint_password"] = endpoint["password"] context["af_endpoint_type"] = endpoint["type"] completed_template = str(compiled_template.render(context)) results += "================ %s ================\n" % endpoint["name"] action.set_endpoint(endpoint) result = action.execute_template(completed_template) results += result results += "\n" context = {"results": results} return render(request, "input_forms/results.html", context)
def apply_template(request): """ :param request: HTTPRequest from the input form :return: results of the template execution """ print "APPLY TEMPLATE" required_fields = set(["input_form_id", "endpoint_id", "group_id"]) if not required_fields.issubset(request.POST): return render(request, "error.html", {"error": "Invalid Parameters in POST"}) input_form_id = request.POST["input_form_id"] endpoint_id = request.POST["endpoint_id"] group_id = request.POST["group_id"] provider_instance = endpoint_provider.get_provider_instance_from_group(group_id) endpoint = provider_instance.get_endpoint_by_id(endpoint_id) if "username" not in endpoint or endpoint["username"] == "": if "global_username" in request.POST: endpoint["username"] = request.POST["global_username"] else: raise Exception("Authentication is required!") if "password" not in endpoint or endpoint["password"] == "": if "global_password" in request.POST: endpoint["password"] = request.POST["global_password"] else: raise Exception("Authentication is required!") input_form = InputForm.objects.get(pk=input_form_id) print input_form.json json_object = json.loads(input_form.json) context = Context() for j in json_object: print "setting context %s" % j["name"] context[j["name"]] = str(request.POST[j["name"]]) context["af_endpoint_ip"] = endpoint["ip"] context["af_endpoint_username"] = endpoint["username"] context["af_endpoint_password"] = endpoint["password"] context["af_endpoint_type"] = endpoint["type"] print context config_template = input_form.script try: compiled_template = engines['django'].from_string(config_template.template) completed_template = str(compiled_template.render(context)) except TemplateSyntaxError as e: print "Caught a template syntax error!" return render(request, "error.html", {"error": "Invalid Template Syntax: %s" % str(e)}) print "TEMPLATE IS:" print completed_template action_name = config_template.action_provider action_options = json.loads(config_template.action_provider_options) print "action name is: " + action_name action = action_provider.get_provider_instance(action_name, action_options) action.set_endpoint(endpoint) results = action.execute_template(completed_template) context = {"results": results} return render(request, "input_forms/results.html", context)
def chain_template(request): """ Populates the input_variables of one template from POSTed form data or json encoded http request body This allows you to chain the output of one template to another one if the input_variable of a template is in the form 'some.variable.with.periods' then the input json object will be searched for that value :param request: HTTPRequest either x-www-form-urlencoded or application/json :return: the output of the template specified by the template_id parameter """ print(request.META["CONTENT_TYPE"]) if request.META["CONTENT_TYPE"] == "application/json": try: data = json.loads(request.body) template_id = data["template_id"] except ValueError: error = { "output": "missing required template_id parameter", "status": 1 } return HttpResponse(json.dumps(error), content_type="application/json") try: config_template = ConfigTemplate.objects.get(pk=template_id) context = dict() # iterate over all the keys in the json object and set on the context # the template engine is smart enough to figure out what goes where for k in data: context[k] = data[k] except ObjectDoesNotExist: error = {"output": "Could not get config template", "status": 1} return HttpResponse(json.dumps(error), content_type="application/json") else: # this must be a x-www-form-urlencoded request required_fields = set(["template_id"]) if not required_fields.issubset(request.POST): error = { "output": "missing required template_id parameter", "status": 1 } return HttpResponse(json.dumps(error), content_type="application/json") template_id = request.POST["template_id"] config_template = ConfigTemplate.objects.get(pk=template_id) template_api = get_input_parameters_for_template(config_template) template_api['a_frame_url'] = '{}://{}/tools/execute_template'.format( request.scheme, request.get_host()) context = dict() try: print(str(template_api["input_parameters"])) input_parameters = template_api["input_parameters"] for j in input_parameters: print("setting context %s" % j) context[j] = str(request.POST[j]) except Exception as ex: print(str(ex)) error = {"output": "missing required parameters", "status": 1} return HttpResponse(json.dumps(error), content_type="application/json") compiled_template = engines['django'].from_string(config_template.template) # compiled_template = get_template_from_string(config_template.template) completed_template = str(compiled_template.render(context)) print(completed_template) action_name = config_template.action_provider action_options = json.loads(config_template.action_provider_options) print("action name is: " + action_name) action = action_provider.get_provider_instance(action_name, action_options) if config_template.type == "per-endpoint": required_fields = ("af_endpoint_ip", "af_endpoint_username", "af_endpoint_password", "af_endpoint_password") if not required_fields.issubset(request.POST): error = { "output": "missing required authentication parameters", "status": 1 } return HttpResponse(json.dumps(error), content_type="application/json") endpoint = dict() endpoint["ip"] = request.POST["af_endpoint_ip"] endpoint["username"] = request.POST["af_endpoint_username"] endpoint["password"] = request.POST["af_endpoint_password"] endpoint["type"] = request.POST["af_endpoint_type"] action.set_endpoint(endpoint) try: results = action.execute_template(completed_template.strip().replace( '\r\n', '\n')) response = {"output": results, "status": 0} except Exception as ex: print(str(ex)) response = {"output": "Error executing template", "status": 1} return HttpResponse(json.dumps(response), content_type="application/json")
def _configure_widget_options(j): ''' Configures widget specific options if necessary :param j: input_form configuration object :return: configured input_form json object ''' if "widget_config" in j: logger.debug("jsonifying widget config") j["widget_config_json"] = json.dumps(j["widget_config"]) if j["widget"] == "preload_list" and "widget_config" in j: try: widget_config = j["widget_config"] template_name = widget_config["template_name"] key = widget_config["key_name"] value = widget_config["value_name"] config_template = ConfigTemplate.objects.get(name=template_name) except (ObjectDoesNotExist, KeyError): logger.error('Could not load preloaded_list template name!') return j action_name = config_template.action_provider try: action_options = json.loads( config_template.action_provider_options) except (ValueError, TypeError): logger.error( 'Could not load action_provider_options from config_template!') return j # let's load any secrets if necessary provider_options = action_provider.get_options_for_provider( action_name) for opt in provider_options: if opt['type'] == 'secret': opt_name = opt['name'] pw_lookup_key = action_options[opt_name]['value'] pw_lookup_value = aframe_utils.lookup_secret(pw_lookup_key) action_options[opt_name]['value'] = pw_lookup_value action = action_provider.get_provider_instance(action_name, action_options) try: results = action.execute_template( config_template.template.strip().replace('\r\n', '\n')) print results results_object = json.loads(results) print key print value d = aframe_utils.get_list_from_json(key, value, results_object, list(), 0) print d j["widget_data"] = d except Exception as ex: print str(ex) return j
def apply_standalone_template(request): logger.info("__ input_forms apply_standalone_template __") if "input_form_id" not in request.POST: logger.error("Did no find all required fields in request") return render(request, "error.html", {"error": "Invalid Parameters in POST"}) input_form_id = request.POST["input_form_id"] input_form = InputForm.objects.get(pk=input_form_id) json_object = json.loads(input_form.json) context = dict() for j in json_object: if '.' in j["name"]: # this is a fancy variable name j_dict = aframe_utils.generate_dict(j["name"], str(request.POST[j["name"]])) context.update(j_dict) else: logger.debug("setting context %s" % j["name"]) print 'setting context %s' % j['name'] context[j["name"]] = str(request.POST[j["name"]]) config_template = input_form.script try: compiled_template = engines['django'].from_string( config_template.template) except TemplateSyntaxError as e: logger.error("Caught a template syntax error!") logger.error(str(e)) return render(request, "error.html", {"error": "Invalid Template Syntax: %s" % str(e)}) completed_template = str(compiled_template.render(context)) if "preview" in request.POST: if request.POST["preview"] == "yes_please": logger.info("Returning template Preview") pre_tags = "<html><body><pre>" post_tags = "</pre></body</html>" return HttpResponse(pre_tags + completed_template + post_tags) logger.info(completed_template) action_name = config_template.action_provider logger.info(action_name) action_options = json.loads(config_template.action_provider_options) logger.info(action_options) for ao in action_options: if "action_options_" + str(ao) in request.POST: logger.debug("Found a customized action option!") new_val = request.POST["action_options_" + str(ao)] print new_val current_value = action_options[ao]["value"] print current_value action_options[ao]["value"] = re.sub("{{ .* }}", new_val, current_value) logger.debug(action_options[ao]["value"]) # let's load any secrets if necessary provider_options = action_provider.get_options_for_provider(action_name) for opt in provider_options: print opt if opt['type'] == 'secret': opt_name = opt['name'] pw_lookup_key = action_options[opt_name]['value'] pw_lookup_value = aframe_utils.lookup_secret(pw_lookup_key) action_options[opt_name]['value'] = pw_lookup_value print "action name is: " + action_name action = action_provider.get_provider_instance(action_name, action_options) results = action.execute_template(completed_template) print type(results) # the action is passing back extra information about the type of response if type(results) is dict: if 'display_inline' in results and results['display_inline'] is False: if 'cache_key' in results: # set extra data on the context so we can use it to build a download link downstream context = { 'results': 'Binary data', 'cache_key': results['cache_key'], 'scheme': request.scheme, 'host': request.get_host() } else: # fixme to ensure contents is always present in results when display_inline is true # results['content'] is currently unimplemented! context = {'results': results['contents']} else: # results is just a string object, so send it through context = {"results": results} if "inline" in request.POST and request.POST["inline"] == 'yes_please': print "returning INLINE" context["input_form_name"] = input_form.name context["input_form_id"] = input_form_id return render(request, "overlay_results.html", context) else: print "returning full results" return render(request, "input_forms/results.html", context)
def apply_per_endpoint_template(request): """ :param request: HTTPRequest from the input form :return: results of the template execution """ logger.info("__ input_forms apply_per_endpoint_template __") required_fields = set(["input_form_id", "endpoint_id", "group_id"]) if not required_fields.issubset(request.POST): logger.error("Did no find all required fields in request") return render(request, "error.html", {"error": "Invalid Parameters in POST"}) input_form_id = request.POST["input_form_id"] endpoint_id = request.POST["endpoint_id"] group_id = request.POST["group_id"] provider_instance = endpoint_provider.get_provider_instance_from_group( group_id) endpoint = provider_instance.get_endpoint_by_id(endpoint_id) if "username" not in endpoint or endpoint["username"] == "": if "global_username" in request.POST: endpoint["username"] = request.POST["global_username"] else: raise Exception("Authentication is required!") if "password" not in endpoint or endpoint["password"] == "": if "global_password" in request.POST: endpoint["password"] = request.POST["global_password"] else: raise Exception("Authentication is required!") input_form = InputForm.objects.get(pk=input_form_id) logger.debug(input_form.json) json_object = json.loads(input_form.json) context = dict() for j in json_object: if '.' in j["name"]: # this is a json capable variable name j_dict = aframe_utils.generate_dict( j["name"], str(request.POST.get(j["name"], ''))) context.update(j_dict) else: logger.debug("setting context %s" % j["name"]) # don't worry about null values here context[j["name"]] = str(request.POST.get(j['name'], '')) context["af_endpoint_ip"] = endpoint["ip"] context["af_endpoint_id"] = endpoint["id"] context["af_endpoint_name"] = endpoint["name"] context["af_endpoint_username"] = endpoint["username"] context["af_endpoint_password"] = endpoint["password"] context["af_endpoint_type"] = endpoint["type"] logger.debug(context) config_template = input_form.script try: compiled_template = engines['django'].from_string( config_template.template) completed_template = str(compiled_template.render(context)) except TemplateSyntaxError as e: logger.error("Caught a template syntax error!") return render(request, "error.html", {"error": "Invalid Template Syntax: %s" % str(e)}) logger.debug(completed_template) action_name = config_template.action_provider action_options = json.loads(config_template.action_provider_options) logger.debug(action_options) for ao in action_options: if "action_options_" + str(ao) in request.POST: logger.debug("Found a customized action option!") new_val = request.POST["action_options_" + str(ao)] current_value = action_options[ao]["value"] action_options[ao]["value"] = re.sub("{{.*}}", new_val, current_value) logger.debug(action_options[ao]["value"]) logger.debug("action name is: " + action_name) # let's load any secrets if necessary provider_options = action_provider.get_options_for_provider(action_name) for opt in provider_options: print opt if opt['type'] == 'secret': opt_name = opt['name'] pw_lookup_key = action_options[opt_name]['value'] pw_lookup_value = aframe_utils.lookup_secret(pw_lookup_key) action_options[opt_name]['value'] = pw_lookup_value action = action_provider.get_provider_instance(action_name, action_options) action.set_endpoint(endpoint) results = action.execute_template(completed_template) context = {"results": results} if "inline" in request.POST and request.POST["inline"] == 'yes_please': print "returning INLINE" context["input_form_name"] = input_form.name context["input_form_id"] = input_form_id return render(request, "overlay_results.html", context) return render(request, "input_forms/results.html", context)
def execute_template(post_vars): """ Refactored out of tools/views.py as this is used in a couple of different places (tools/views and screens/views) :param post_vars: copy of all variables passed in via the operation :return: response object of form {'output': whatever, 'status': 1 } """ if 'template_id' not in post_vars and 'template_name' not in post_vars: error = { 'output': 'missing required template_id or template_name parameter', 'status': 1 } return error if 'template_id' in post_vars: template_id = int(post_vars['template_id']) config_template = ConfigTemplate.objects.get(pk=template_id) else: template_name = str(post_vars['template_name']) print("GETTING %s" % template_name) config_template = ConfigTemplate.objects.get(name=template_name) template_api = get_input_parameters_for_template(config_template) context = dict() try: print(str(template_api["input_parameters"])) input_parameters = template_api["input_parameters"] for j in input_parameters: print("setting context %s" % j) context[j] = str(post_vars[j]) except Exception as ex: print(str(ex)) error = {"output": "missing required parameters", "status": 1} return error compiled_template = engines['django'].from_string(config_template.template) # compiled_template = get_template_from_string(config_template.template) completed_template = str(compiled_template.render(context)) print(completed_template) action_name = config_template.action_provider action_options = json.loads(config_template.action_provider_options) print(post_vars) for ao in action_options: print('checking ' + str(ao)) if "action_options_" + str(ao) in post_vars: print("found a match!") new_val = post_vars["action_options_" + str(ao)] print(new_val) current_value = action_options[ao]["value"] print(current_value) action_options[ao]["value"] = re.sub("{{ .* }}", new_val, current_value) print(action_options[ao]["value"]) # let's load any secrets if necessary provider_options = action_provider.get_options_for_provider(action_name) for opt in provider_options: if opt['type'] == 'secret': opt_name = opt['name'] pw_lookup_key = action_options[opt_name]['value'] pw_lookup_value = lookup_secret(pw_lookup_key) action_options[opt_name]['value'] = pw_lookup_value print("action name is: " + action_name) action = action_provider.get_provider_instance(action_name, action_options) if config_template.type == "per-endpoint": if "af_endpoint_ip" not in post_vars or "af_endpoint_id" not in post_vars: error = { "output": "missing required authentication parameters", "status": 1 } return error endpoint = dict() endpoint["id"] = post_vars.get("af_endpoint_id", "") endpoint["name"] = post_vars.get("af_endpoint_name", "") endpoint["ip"] = post_vars.get("af_endpoint_ip", "") endpoint["username"] = post_vars.get("af_endpoint_username", "") endpoint["password"] = post_vars.get("af_endpoint_password", "") endpoint["type"] = post_vars.get("af_endpoint_type", "") action.set_endpoint(endpoint) try: results = action.execute_template(completed_template.strip().replace( '\r\n', '\n')) response = {"output": results.strip(), "status": 0} except Exception as ex: print(str(ex)) response = {"output": "Error executing template", "status": 1} return response
def apply_template_to_queue(request): logger.info("__ input_forms apply_template_to_queue __") if "input_form_id" not in request.POST: logger.error("Did no find all required fields in request") return render(request, "error.html", {"error": "Invalid Parameters in POST"}) input_form_id = request.POST["input_form_id"] endpoints = request.session["endpoint_queue"] input_form = InputForm.objects.get(pk=input_form_id) logger.debug(input_form.json) json_object = json.loads(input_form.json) context = Context() for j in json_object: if '.' in j["name"]: # this is a json capable variable name j_dict = aframe_utils.generate_dict(j["name"], str(request.POST[j["name"]])) context.update(j_dict) else: logger.debug("setting context %s" % j["name"]) context[j["name"]] = str(request.POST[j["name"]]) logger.debug(context) config_template = input_form.script try: compiled_template = engines['django'].from_string(config_template.template) except TemplateSyntaxError as e: logger.error("Caught a template syntax error!") logger.error(str(e)) return render(request, "error.html", {"error": "Invalid Template Syntax: %s" % str(e)}) action_name = config_template.action_provider action_options = json.loads(config_template.action_provider_options) logger.debug("action name is: %s" % action_name) logger.debug("action options are: %s" % action_options) action = action_provider.get_provider_instance(action_name, action_options) results = "" for endpoint in endpoints: if "username" not in endpoint or endpoint["username"] == "": if "global_username" in request.POST: endpoint["username"] = request.POST["global_username"] else: raise Exception("Authentication is required!") if "password" not in endpoint or endpoint["password"] == "": if "global_password" in request.POST: endpoint["password"] = request.POST["global_password"] else: raise Exception("Authentication is required!") context["af_endpoint_ip"] = endpoint["ip"] context["af_endpoint_username"] = endpoint["username"] context["af_endpoint_password"] = endpoint["password"] context["af_endpoint_type"] = endpoint["type"] completed_template = str(compiled_template.render(context)) results += "================ %s ================\n" % endpoint["name"] action.set_endpoint(endpoint) result = action.execute_template(completed_template) results += result results += "\n" context = {"results": results} return render(request, "input_forms/results.html", context)
def apply_template(request): """ :param request: HTTPRequest from the input form :return: results of the template execution """ logger.info("__ input_forms apply_template __") required_fields = set(["input_form_id", "endpoint_id", "group_id"]) if not required_fields.issubset(request.POST): logger.error("Did no find all required fields in request") return render(request, "error.html", {"error": "Invalid Parameters in POST"}) input_form_id = request.POST["input_form_id"] endpoint_id = request.POST["endpoint_id"] group_id = request.POST["group_id"] provider_instance = endpoint_provider.get_provider_instance_from_group(group_id) endpoint = provider_instance.get_endpoint_by_id(endpoint_id) if "username" not in endpoint or endpoint["username"] == "": if "global_username" in request.POST: endpoint["username"] = request.POST["global_username"] else: raise Exception("Authentication is required!") if "password" not in endpoint or endpoint["password"] == "": if "global_password" in request.POST: endpoint["password"] = request.POST["global_password"] else: raise Exception("Authentication is required!") input_form = InputForm.objects.get(pk=input_form_id) logger.debug(input_form.json) json_object = json.loads(input_form.json) context = Context() for j in json_object: if '.' in j["name"]: # this is a json capable variable name j_dict = aframe_utils.generate_dict(j["name"], str(request.POST[j["name"]])) context.update(j_dict) else: logger.debug("setting context %s" % j["name"]) context[j["name"]] = str(request.POST[j["name"]]) context["af_endpoint_ip"] = endpoint["ip"] context["af_endpoint_username"] = endpoint["username"] context["af_endpoint_password"] = endpoint["password"] context["af_endpoint_type"] = endpoint["type"] logger.debug(context) config_template = input_form.script try: compiled_template = engines['django'].from_string(config_template.template) completed_template = str(compiled_template.render(context)) except TemplateSyntaxError as e: logger.error("Caught a template syntax error!") return render(request, "error.html", {"error": "Invalid Template Syntax: %s" % str(e)}) logger.debug(completed_template) action_name = config_template.action_provider action_options = json.loads(config_template.action_provider_options) logger.debug(action_options) for ao in action_options: if "action_options_" + str(ao) in request.POST: logger.debug("Found a customized action option!") new_val = request.POST["action_options_" + str(ao)] current_value = action_options[ao]["value"] action_options[ao]["value"] = re.sub("{{ .* }}", new_val, current_value) logger.debug(action_options[ao]["value"]) logger.debug("action name is: " + action_name) action = action_provider.get_provider_instance(action_name, action_options) action.set_endpoint(endpoint) results = action.execute_template(completed_template) context = {"results": results} return render(request, "input_forms/results.html", context)
def execute_template(request): required_fields = set(["template_id"]) if not required_fields.issubset(request.POST): error = { "output": "missing required template_id parameter", "status": 1 } return HttpResponse(json.dumps(error), content_type="application/json") template_id = request.POST["template_id"] config_template = ConfigTemplate.objects.get(pk=template_id) template_api = get_input_parameters_for_template(config_template) context = Context() try: print str(template_api["input_parameters"]) input_parameters = template_api["input_parameters"] for j in input_parameters: print "setting context %s" % j context[j] = str(request.POST[j]) except Exception as ex: print str(ex) error = {"output": "missing required parameters", "status": 1} return HttpResponse(json.dumps(error), content_type="application/json") compiled_template = engines['django'].from_string(config_template.template) # compiled_template = get_template_from_string(config_template.template) completed_template = str(compiled_template.render(context)) print completed_template action_name = config_template.action_provider action_options = json.loads(config_template.action_provider_options) print "action name is: " + action_name action = action_provider.get_provider_instance(action_name, action_options) if config_template.type == "per-endpoint": required_fields = set([ "af_endpoint_ip", "af_endpoint_username", "af_endpoint_password", "af_endpoint_password" ]) if not required_fields.issubset(request.POST): error = { "output": "missing required authentication parameters", "status": 1 } return HttpResponse(json.dumps(error), content_type="application/json") endpoint = dict() endpoint["ip"] = request.POST["af_endpoint_ip"] endpoint["username"] = request.POST["af_endpoint_username"] endpoint["password"] = request.POST["af_endpoint_password"] endpoint["type"] = request.POST["af_endpoint_type"] action.set_endpoint(endpoint) try: results = action.execute_template(completed_template.strip().replace( '\r\n', '\n')) response = {"output": results, "status": 0} except Exception as ex: print str(ex) response = {"output": "Error executing template", "status": 1} return HttpResponse(json.dumps(response), content_type="application/json")
def execute_template(request): required_fields = set(["template_id"]) if not required_fields.issubset(request.POST): error = {"output": "missing required template_id parameter", "status": 1} return HttpResponse(json.dumps(error), content_type="application/json") template_id = request.POST["template_id"] config_template = ConfigTemplate.objects.get(pk=template_id) template_api = get_input_parameters_for_template(config_template) context = Context() try: print str(template_api["input_parameters"]) input_parameters = template_api["input_parameters"] for j in input_parameters: print "setting context %s" % j context[j] = str(request.POST[j]) except Exception as ex: print str(ex) error = {"output": "missing required parameters", "status": 1} return HttpResponse(json.dumps(error), content_type="application/json") compiled_template = get_template_from_string(config_template.template) completed_template = str(compiled_template.render(context)) print completed_template action_name = config_template.action_provider action_options = json.loads(config_template.action_provider_options) print "action name is: " + action_name action = action_provider.get_provider_instance(action_name, action_options) if config_template.type == "per-endpoint": required_fields = set(["af_endpoint_ip", "af_endpoint_username", "af_endpoint_password", "af_endpoint_password"] ) if not required_fields.issubset(request.POST): error = {"output": "missing required authentication parameters", "status": 1} return HttpResponse(json.dumps(error), content_type="application/json") endpoint = dict() endpoint["ip"] = request.POST["af_endpoint_ip"] endpoint["username"] = request.POST["af_endpoint_username"] endpoint["password"] = request.POST["af_endpoint_password"] endpoint["type"] = request.POST["af_endpoint_type"] action.set_endpoint(endpoint) try: results = action.execute_template(completed_template.strip().replace('\r\n', '\n')) response = {"output": results, "status": 0} except Exception as ex: print str(ex) response = {"output": "Error executing template", "status": 1} return HttpResponse(json.dumps(response), content_type="application/json")
def chain_template(request): """ Populates the input_variables of one template from POSTed form data or json encoded http request body This allows you to chain the output of one template to another one if the input_variable of a template is in the form 'some.variable.with.periods' then the input json object will be searched for that value :param request: HTTPRequest either x-www-form-urlencoded or application/json :return: the output of the template specified by the template_id parameter """ print request.META["CONTENT_TYPE"] if request.META["CONTENT_TYPE"] == "application/json": try: data = json.loads(request.body) template_id = data["template_id"] except ValueError: error = {"output": "missing required template_id parameter", "status": 1} return HttpResponse(json.dumps(error), content_type="application/json") try: config_template = ConfigTemplate.objects.get(pk=template_id) context = Context() # iterate over all the keys in the json object and set on the context # the template engine is smart enough to figure out what goes where for k in data: context[k] = data[k] except ObjectDoesNotExist: error = {"output": "Could not get config template", "status": 1} return HttpResponse(json.dumps(error), content_type="application/json") else: # this must be a x-www-form-urlencoded request required_fields = set(["template_id"]) if not required_fields.issubset(request.POST): error = {"output": "missing required template_id parameter", "status": 1} return HttpResponse(json.dumps(error), content_type="application/json") template_id = request.POST["template_id"] config_template = ConfigTemplate.objects.get(pk=template_id) template_api = get_input_parameters_for_template(config_template) context = Context() try: print str(template_api["input_parameters"]) input_parameters = template_api["input_parameters"] for j in input_parameters: print "setting context %s" % j context[j] = str(request.POST[j]) except Exception as ex: print str(ex) error = {"output": "missing required parameters", "status": 1} return HttpResponse(json.dumps(error), content_type="application/json") compiled_template = engines['django'].from_string(config_template.template) # compiled_template = get_template_from_string(config_template.template) completed_template = str(compiled_template.render(context)) print completed_template action_name = config_template.action_provider action_options = json.loads(config_template.action_provider_options) print "action name is: " + action_name action = action_provider.get_provider_instance(action_name, action_options) if config_template.type == "per-endpoint": required_fields = set(["af_endpoint_ip", "af_endpoint_username", "af_endpoint_password", "af_endpoint_password"] ) if not required_fields.issubset(request.POST): error = {"output": "missing required authentication parameters", "status": 1} return HttpResponse(json.dumps(error), content_type="application/json") endpoint = dict() endpoint["ip"] = request.POST["af_endpoint_ip"] endpoint["username"] = request.POST["af_endpoint_username"] endpoint["password"] = request.POST["af_endpoint_password"] endpoint["type"] = request.POST["af_endpoint_type"] action.set_endpoint(endpoint) try: results = action.execute_template(completed_template.strip().replace('\r\n', '\n')) response = {"output": results, "status": 0} except Exception as ex: print str(ex) response = {"output": "Error executing template", "status": 1} return HttpResponse(json.dumps(response), content_type="application/json")