def main_view(request): try: context = helpers.get_baseapp_context(request) except Exception: helpers.view_exception(Exception) raise Http404("HTTP 404 Error") return render(request, "srxpolsrch/main.html", context)
def get_local_repo(request): """ Return the Git repository which resides within the workspace directory of the requesting user as a git object. """ try: workspace = WORKSPACEDIR + request.user.username local_repo = git.Repo(workspace) return local_repo except Exception: helpers.view_exception(Exception)
def clone_repo(request): """ Clone a Git repository from given remote address into a local workspace directory. Git user configuration is set from user information within request. """ try: username = request.user.username useremail = request.user.email workspace = WORKSPACEDIR + username if os.path.isdir(workspace): shutil.rmtree(workspace) logger.info("Cloning git repository...") address = get_git_auth_address(request) git.Repo.clone_from(address, workspace, config="http.sslVerify=false") local_repo = get_local_repo(request) with local_repo.config_writer() as cw: cw.set_value("user", "name", username).release() cw.set_value("user", "email", useremail).release() response = "success" except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def commit_config(request): """ Commit the file provided within the request and push to the remote repository. """ try: file_to_commit = request.POST.get("host_var_file_path", None) username = request.user.username local_repo = get_local_repo(request) local_repo.git.pull() local_repo.git.add(file_to_commit) logger.info("Committing config") local_repo.git.commit(m="SRX YAMLr firewall policy change") address = get_git_auth_address(request) logger.info("Pushing config to {}...".format(REMOTE_REPO_URL)) if username != "unittest_user": local_repo.git.push(address) else: local_repo.git.push("-n", address) request.session["configdict"] = {} response = "success" except Exception as exc_instance: error = str(exc_instance) if "HTTP 401" in error: logger.info("Invalid token: {}".format(helpers.get_token(request))) response = "unauthorized" else: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def commithash(request): """ Retrieve the latest commit hash value from a given file or repository. If a file path is provided, the value from that file is returned. Otherwise, the value from the current repository is returned. Provide "file_path" in request data as a relative path within the current repo: { "file_path": "relative/path/to/file" } """ try: file_path = request.GET.get("file_path", None) local_repo = get_local_repo(request) if file_path: commit_hash = local_repo.git.log("-n 1", "--pretty=format:%H", "--", file_path) else: commit_hash = local_repo.git.rev_parse("--verify HEAD") response = commit_hash except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def reset_config_session(request): try: request.session["configdict"] = None response = 0 except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def search(request): try: inp_src = request.GET.get("input_from", None) inp_dest = request.GET.get("input_to", None) wd = request.session["workingdict"] def find_objects(inp): objects = [] for obj in wd["addresses"]: if inp in obj["name"].upper() or inp in obj["val"].upper(): objects.append(obj) for obj in wd["addrsets"]: if inp in obj["name"].upper(): objects.append(obj) else: for val in obj["val"]: if inp in val.upper(): objects.append(obj) break return objects objects_src = find_objects(inp_src) if inp_src else None objects_dest = find_objects(inp_dest) if inp_dest else None def object_in_policy(pol, direction): objlist = objects_src if direction == "source" else objects_dest zonedir = "fromzone" if direction == "source" else "tozone" for obj in objlist: if isinstance(pol[direction], str): if obj["name"] == pol[direction] and obj["zone"] == pol[ zonedir]: return True else: for obj_single in pol[direction]: if obj["name"] == obj_single and obj["zone"] == pol[ zonedir]: return True return False policies = [] for pol in wd["policies"]: if objects_src and not objects_dest: if object_in_policy(pol, "source"): policies.append(pol) elif objects_dest and not objects_src: if object_in_policy(pol, "destination"): policies.append(pol) elif objects_src and objects_dest: if object_in_policy(pol, "source") and object_in_policy( pol, "destination"): policies.append(pol) response = policies except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def object_create_appset(request): try: srxobject = srxconfig.srxObject(request) result = srxobject.create_appset() request.session["configdict"] = result response = helpers.convert_dict_to_yaml(result) except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def policy_rename(request): try: srxpolicy = srxconfig.srxPolicy(request) result = srxpolicy.update_policyname() request.session["configdict"] = result response = helpers.convert_dict_to_yaml(result) except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def write_config(request): try: src = srxsource.sourceData(request) src.set_configdict() src.update_source_file() response = "success" except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def get_diff(request): """ Return the Git diff output from the repository within the workspace directory of the requesting user. """ try: local_repo = get_local_repo(request) response = local_repo.git.diff() except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def get_git_auth_address(request): """ Assemble the Git push address from user token, server url and repository. """ try: token = helpers.get_token(request) git_type = os.environ.get("GITSERVER_TYPE") if git_type == "gogs": prfx = "https://" if REMOTE_REPO_URL.startswith( "https") else "http://" repo = REMOTE_REPO_URL.replace(prfx, "") # Put colon behind token to prevent gogs from opening a stdin # prompt asking for a password in case of invalid token. return prfx + token + ":" + "@" + repo elif git_type == "github": # Support for the Github API has not been implemented yet. return REMOTE_REPO_URL except Exception: helpers.view_exception(Exception)
def set_host_var_file_path(request): try: file_path = request.POST.get("host_var_file_path") obj, created = models.HostVarFilePath.objects.update_or_create( id=0, defaults={"path": file_path}, ) response = 0 except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def policy_add_address(request): try: srxpolicy = srxconfig.srxPolicy(request) result = srxpolicy.add_address() if "p_exists" not in result: request.session["configdict"] = result response = helpers.convert_dict_to_yaml(result) else: request.session["configdict"] = result["p_existing"] request.session["pe_detail"] = result["pe_detail"] response = "p_exists" except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def create_config_session(request): try: configdict = request.session.get("configdict") if not configdict: request.session["configdict"] = {} request.session["pe_detail"] = {} response = "cache_loaded" if load_workingdict( request) else "cache_empty" else: response = "config_session_exists" except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def validate_cache(request): try: srcfile_commithash = request.GET.get("srcfile_commithash") try: wd_cache = models.Cache.objects.get(name="workingdict") cached_commithash = wd_cache.srcfile_commithash except models.Cache.DoesNotExist: cached_commithash = None if srcfile_commithash == cached_commithash: response = "cache_valid" load_workingdict(request) else: response = "cache_invalid" except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def import_objects(request): try: src = srxsource.sourceData(request) src.read_source_file() src.import_zones() src.import_addresses() src.import_addrsets() src.import_applications() src.import_appsets() src.import_policies() src.save_import_to_cache() wd_cache = models.Cache.objects.get(name="workingdict") workingdict_origin = json.loads(wd_cache.workingdict_origin) request.session["workingdict"] = workingdict_origin response = "success" except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def loadpolicy(request): try: policyhash = request.GET.get("policyhash") wd = request.session["workingdict"] for pol in wd["policies"]: if policyhash == pol["policyhash"]: p_existing = deepcopy(pol) srxpolicy = srxconfig.srxPolicy(request) pe_detail = srxpolicy.get_existing_policy_subvalues(p_existing) pe_fmt = srxpolicy.format_existing_policy(p_existing) request.session["configdict"] = pe_fmt request.session["pe_detail"] = pe_detail response = "load_existing" except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def get_policy_yaml(request): try: policyhash = request.GET.get("policyhash", None) wd = request.session["workingdict"] response = None for policy in wd["policies"]: if policyhash == policy["policyhash"]: pol = deepcopy(policy) pol.pop("name") pol.pop("policyhash") temp_in_memory_out = StringIO() sys.stdout = temp_in_memory_out yaml = YAML() yaml.indent(mapping=2, sequence=4, offset=2) yaml.dump(pol, sys.stdout) response = temp_in_memory_out.getvalue() sys.stdout = sys.__stdout__ break except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)
def search_object(request): try: response = helpers.search_object_in_workingdict(request) except Exception: response = helpers.view_exception(Exception) return JsonResponse(response, safe=False)