Commit 87685481 authored by Ondřej Borýsek's avatar Ondřej Borýsek
Browse files

Add automatic login and auth reresh

parent 333afbf3
Loading
Loading
Loading
Loading
+1 −4
Original line number Diff line number Diff line
@@ -15,7 +15,7 @@ import pwndoc_db_init
from helpers.file_utils import zip_multiple_folders_non_recursive_to_virtual, relative_path
from template_manager import PwndocTemplateManager
import template_pwndoc
from pwndoc_api import login, refresh_examples, delete_all_templates_in_pwndoc, load_audit_file, \
from pwndoc_api import refresh_examples, delete_all_templates_in_pwndoc, load_audit_file, \
    get_findings_from_audit, download_and_return_finding, delete_finding, get_audits
from helpers.db_models import DbTemplate
from template_pwndoc import TNSTemplatePwndoc, get_fid_from_raw_finding
@@ -33,7 +33,6 @@ def show_debug_actions_list():

@bp.route("/download_api", methods=["GET"])
def download_api_examples():
    login()
    refresh_examples()
    return basic_msg("API examples downloaded")

@@ -46,7 +45,6 @@ def force_upload_init_data():

@bp.route("/refresh_api_examples", methods=["GET"])
def debug_refresh_api_examples():
    login()
    refresh_examples()
    return basic_msg(f"OK")

@@ -182,7 +180,6 @@ def test_flash_msg():


def _list_newly_grouped_or_aliased_findings(audit_id: str) -> List[Tuple[str, str, str]]:
    login()
    refresh_examples(audit_id)
    TemplateAliasing.refresh()
    TemplateGrouping.refresh()
+1 −2
Original line number Diff line number Diff line
@@ -27,7 +27,7 @@ from template_manager import PwndocTemplateManager
from helpers.flask_multifile_upload import save_multiple_uploaded_files
from scan2report import scan2report
from api_templates import download_templates_from_pwndoc_to_scan2report
from pwndoc_api import login, get_findings_from_audit, upsert_raw_finding, get_audits, does_audit_exist
from pwndoc_api import get_findings_from_audit, upsert_raw_finding, get_audits, does_audit_exist
from template_scan2report import TemplateScan2Report, str_bool_to_bool
from template_pwndoc import get_fid_from_raw_finding
from template_converters import Scan2ReportConvert
@@ -531,7 +531,6 @@ def upload_scan_findings_to_pwndoc(folder_name: str) -> bool:
        else:
            findings.append(finding_parsed)

    login()
    new_raw_findings = []
    for single_finding in tqdm(findings, desc="Converting findings to PwnDoc format"):
        single_finding_pwndoc = Scan2ReportConvert.convert_single_finding_to_tns_pwndoc(single_finding, locale)  # todo: should this do the HTML conversion?
+23 −9
Original line number Diff line number Diff line
@@ -2,18 +2,41 @@ import random
import string
import time

import jwt
import requests
from requests.auth import AuthBase
import urllib3
from tqdm import tqdm
from loguru import logger
from flask import abort
from typing import List, Tuple

from helpers.time_helper import current_timestamp
from template_pwndoc import TemplatePwndoc, MultilocaleTemplateWrapperPwndoc, TNSTemplatePwndoc
import config
from helpers.file_utils import *


class PwnDocAuth(AuthBase):
    def __call__(self, r):
        if r.path_url.startswith('/api/users'):
            return r

        if session.cookies.get('token') is None:
            login()
            return r

        jwt_token = session.cookies.get('token', "").replace("JWT%20", "")
        jwt_data = jwt.decode(jwt_token, algorithms=["HS256"], options={"verify_signature": False})  # todo: why is the signature invalid?
        exp_timestamp = jwt_data.get("exp")
        if current_timestamp() >= exp_timestamp:
            login()  # todo: maybe refresh token?

        return r


session = requests.Session()
session.auth = PwnDocAuth()
session.verify = not config.PWNDOC_DISABLE_HTTPS_VERIFICATION
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)  # I'm writing one custom warning on config load, the default setting of urllib3 prints it on every request.

@@ -102,18 +125,15 @@ def get_and_save(url_path: str, filename: Optional[str] = None) -> dict:

def pwndoc_download_json_of_vulnerabilities_and_custom_fields():
    """ Don't use this directly, use PwndocTemplateManager.update_template_db_from_pwndoc instead. """
    login()
    get_and_save("/api/vulnerabilities")
    get_and_save("/api/data/custom-fields")


def pwndoc_download_json_of_custom_fields():
    login()
    get_and_save("/api/data/custom-fields")


def _download_audits():
    login()
    get_and_save("/api/audits")


@@ -148,7 +168,6 @@ def load_audit_file(audit_id: str) -> Optional[dict]:


def delete_all_templates_in_pwndoc():
    login()
    url = f"{config.PWNDOC_URL}/api/vulnerabilities"
    resp = session.delete(url)
    assert resp.status_code == 200, f"Template removal failed: {resp.text}"
@@ -165,7 +184,6 @@ def download_audit(audit_id: str):


def download_and_return_audit(audit_id: str) -> dict:
    login()
    download_audit(audit_id)
    answer = load_audit_file(audit_id)
    if answer is None:
@@ -189,20 +207,17 @@ def get_findings_from_audit(audit_id: str) -> List[dict]:


def download_and_return_finding(audit_id: str, finding_id: str):
    # login()
    url_path = f"/api/audits/{audit_id}/findings/{finding_id}"
    return get_and_save(url_path).get("datas", {})


def delete_finding(audit_id: str, finding_id: str):
    login()
    url_path = f"/api/audits/{audit_id}/findings/{finding_id}"
    resp = session.delete(f"{config.PWNDOC_URL}{url_path}")
    assert resp.status_code == 200, f"Template removal failed: {resp.text}"


def update_scope(audit_id: str, scope_raw: dict):
    login()
    url_path = f"/api/audits/{audit_id}/network"
    resp = session.put(f"{config.PWNDOC_URL}{url_path}", json=scope_raw)

@@ -245,7 +260,6 @@ def download_report(audit_id: str, report_filename: str):
    # note: pass filename, not filepath - filepath can be different between flask and background worker
    report_filepath = get_docx_filepath(report_filename)

    login()
    url = f"{config.PWNDOC_URL}/api/audits/{audit_id}/generate"
    resp = session.get(url, timeout=config.RQ_JOB_TIMEOUT)
    assert resp.status_code == 200, f"Report download failed"
+1 −1
Original line number Diff line number Diff line
@@ -32,7 +32,7 @@ class InitialData:
            return

        self._add_pwndoc_user(first_user=True)
        login()
        # login()  # login happens automatically

        # no dependencies
        self._upload_universal('_api_templates.json')
+1 −0
Original line number Diff line number Diff line
@@ -6,6 +6,7 @@
loguru==0.6.0
tqdm==4.64.1
requests==2.28.1
pyjwt~=2.6.0
dataclasses_json==0.5.7
python-dotenv==0.21.0
flask==2.2.2 # >= 2.2.0