HEX
Server: LiteSpeed
System: Linux php-prod-1.spaceapp.ru 5.15.0-157-generic #167-Ubuntu SMP Wed Sep 17 21:35:53 UTC 2025 x86_64
User: xnsbb3110 (1041)
PHP: 8.1.33
Disabled: NONE
Upload Files
File: //usr/local/CyberCP/aiScanner/__pycache__/api.cpython-310.pyc
o

��h�j�@s�ddlZddlZddlZddlZddlZddlmZddlmZddl	m
Z
ddlmZddl
mZddlmZmZdd	lmZGd
d�de�Zdd
�Zdd�Zee
dg�dd���Zee
dg�dd���Zee
dg�dd���Zee
dg�dd���ZdS)�N)�JsonResponse)�csrf_exempt)�require_http_methods��Websites)�
Administrator�)�FileAccessToken�ScanHistory)�CyberCPLogFileWriterc@seZdZdZdS)�
SecurityErrorz(Custom exception for security violationsN)�__name__�
__module__�__qualname__�__doc__�rr�#/usr/local/CyberCP/aiScanner/api.pyrsrc
Cs�zW|r|�d�st�d|r|dd�nd�d��WdSz'tjj||dd	�}|��r6t�d
|���WWdSt�d|���|dfWWStjyWt�d
|���YWdSwtyt}zt�dt	|����WYd}~dSd}~ww)z�
    Implement proper token validation
    - Check token format
    - Verify token hasn't expired
    - Confirm token is for the correct scan
    - Log access attempts
    �cp_z[API] Invalid token format: N��Nonez...)NzInvalid token formatT)�token�scan_history__scan_id�	is_activez[API] Token expired for scan )Nz
Token expiredz,[API] Token validated successfully for scan z[API] Token not found for scan )Nz
Invalid tokenz[API] Token validation error: )NzToken validation failed)
�
startswith�logging�writeToFiler	�objects�get�
is_expired�DoesNotExist�	Exception�str)r�scan_id�
file_token�errr�validate_access_tokens0"����r%c
Cszz'|rtj�||�d��}n|}tj�|�}tj�|�}|�|�s%td��|WSty<}z	tdt|�����d}~ww)zc
    Ensure requested path is within allowed directory
    Prevent directory traversal attacks
    �/zPath outside allowed directoryzPath security check failed: N)	�os�path�join�strip�abspathrrr r!)�	base_path�requested_path�	full_pathr$rrr�secure_path_check9s
��r/�POSTc
Cs��z2t�|j�}|�d�}|�d�}|�dd�}t�d|�d|���|r'|s0tddid	d
�WSt||�\}}|rBtd|idd
�WSz�tj	j|j
d�}|j}d
}	d
}
tj
�|dd�}zKddlm}d|�d�}
|j|
|jdd�}|dr�|d}ddl}|�d|�}|r�|�d�}	t�d|	���nt�dt|�dkr�|dnd���Wnty�}zt�dt|����WYd}~nd}~wwz(ddl}|jddgdddd �}|jdkr�ddl}|�d!|j�}|r�|�d�}
Wn	ty�Ynwd|j
||
|	|d"�d#d$g|j�d%�d&�}t�d'|j
���t|�WWStj�y3t�d(|j
���tdd)id*d
�YWSwtj �yFtdd+id	d
�YSt�yj}zt�d,t|����tdd-id.d
�WYd}~Sd}~ww)/aH
    POST /api/ai-scanner/authenticate
    
    Request Body:
    {
        "access_token": "cp_access_abc123...",
        "scan_id": "550e8400-e29b-41d4-a716-446655440000",
        "worker_id": "scanner-1.domain.com"
    }
    
    Response:
    {
        "success": true,
        "site_info": {
            "domain": "client-domain.com",
            "wp_path": "/home/client/public_html",
            "php_version": "8.1",
            "wp_version": "6.3.1"
        },
        "permissions": ["read_files", "list_directories"],
        "expires_at": "2024-12-25T11:00:00Z"
    }
    �access_tokenr"�	worker_id�unknownz)[API] Authentication request from worker �
 for scan �errorzMissing access_token or scan_id���status���domain�Unknownzwp-includeszversion.phpr��ProcessUtilities�cat "�"T��user�retRequiredrNz&\$wp_version\s*=\s*[\'"]([^\'"]+)[\'"]z"[API] Detected WordPress version: z&[API] Could not read WP version file: �No content returnedz [API] Error reading WP version: �phpz-v�)�capture_output�text�timeoutzPHP (\d+\.\d+))r;�wp_path�php_version�
wp_versionr"�
read_files�list_directoriesz%Y-%m-%dT%H:%M:%SZ)�success�	site_info�permissions�
expires_atz$[API] Authentication successful for z[API] Website not found: �Website not found�zInvalid JSONz[API] Authentication error: zAuthentication failed��)!�json�loads�bodyrrrrr%rrr;rJr'r(r)�plogical.processUtilitiesr>�outputExecutioner�externalApp�re�search�group�lenr r!�
subprocess�run�
returncode�stdoutrR�strftimer�JSONDecodeError)�request�datar1r"r2r#r5�websiterJrLrK�version_filer>�command�result�contentr\�matchr$r`�
response_datarrr�authenticate_workerOs�


�$� ��

���
�
���ro�GETc
Cs��z�|j�dd�}|�d�stddidd�WS|�dd�}|j�dd�}|s/tdd	id
d�WSt||�\}}|rAtd|idd�WS|j�dd��d�}�zZt|j	|�}g}�zd
dl
m}	d
dlm
}
z
|
jj|jd�}|j}Wn|
jy�tddidd�YWWWSwd|�d�}
|	j|
|dd�}|d�r>|d���d�}|dd�D]�}|��s�q�|��}t|�dkr�q�|d
}|d��r�|dnd
}d�|dd��}|�d�s�|dvs�|d vr�q�||�d!�r�d"nd#t|�dkr�|dd�nd$d%�}|�d&��r#zt|�|d'<Wnt�yd
|d'<Ynw|�d(��r"|�|�q�|�d!��r3d
|d'<|�|�q�d
|d'<|�|�q�nt�d)t|�dk�rL|dnd*���tdd+id,d�WWWSWn't�y�}zt�d-t|����tdd+id,d�WYd}~WWSd}~wwt�d.t|��d/|�p�d0�d1|���t|t|d2d3�d4�d5��WWSt �y�}zt�d6t|����tdd7id,d�WYd}~WSd}~wwt�y�}zt�d8t|����tdd9id:d�WYd}~Sd}~ww);a�
    GET /api/ai-scanner/files/list?path=wp-content/plugins
    
    Headers:
    Authorization: Bearer cp_access_abc123...
    X-Scan-ID: 550e8400-e29b-41d4-a716-446655440000
    
    Response:
    {
        "path": "wp-content/plugins",
        "items": [
            {
                "name": "akismet",
                "type": "directory",
                "modified": "2024-12-20T10:30:00Z"
            },
            {
                "name": "suspicious-plugin.php",
                "type": "file",
                "size": 15420,
                "modified": "2024-12-24T15:20:00Z",
                "permissions": "644"
            }
        ]
    }
    �HTTP_AUTHORIZATION��Bearer r5�'Missing or invalid Authorization headerr9r7�HTTP_X_SCAN_ID�X-Scan-ID header requiredr6r(r&rr=rr:rSrTzls -la "r@TrAr�
N�	�� ��.)r|z..)�__pycache__�node_modules�d�	directory�file�644)�name�typerQ�-�size)�.php�.js�.html�.htm�.css�.txt�.md�.json�.xml�.sql�.log�.conf�.ini�.yml�.yamlz [API] Directory listing failed: rDzDirectory access failed�z[API] Directory listing error: z
[API] Listed z
 items in �rootr4cSs|ddk|d��fS)Nr�r�r�)�lower)�xrrr�<lambda><szlist_files.<locals>.<lambda>)�key)r(�items�[API] Security violation: �Path not allowedz[API] List files error: �Internal server errorrU)!�METArrr�replacer%rpr*r/rJrYr>�websiteFunctions.modelsrrr;r[rrZ�splitr_�isdigitr)�int�
ValueError�endswith�appendrrr r!�sortedr)rf�auth_headerr1r"r#r5r(r.r�r>rrhrB�
ls_commandrk�lines�line�partsrQr�r��	item_datar$rrr�
list_files�s�

�
��
��&(�+ ��&�����r�c
CsX�z|j�dd�}|�d�stddidd�WS|�dd�}|j�dd�}|s/tdd	id
d�WS|j�dd��d�}|sDtdd
id
d�WSt||�\}}|rVtd|idd�WS�z�t|j	|�}hd�}t
j�|�d�
�}	|	|vr}tdd|	��idd�WWSz�ddlm}
ddlm}z
|jj|jd�}|j}
Wn|jy�tddidd�YWWWSwd|�d�}|
j||
dd�}|dr�zt|d���}|dkr�tddid
d�WWWWSWn2ty�t�d|d���d}Ynwt�dt|�dkr�|dnd ���tdd!idd�WWWSd"|�d�}|
j||
dd�}t|�dk�r1|dd#u�r,|dnd}d$}nt�d%�tdd&id
d�WWWSWn't�yi}zt�d't|����tdd&id
d�WYd#}~WWSd#}~wwt�|�\}}|�s�|	d(k�r|d)}n
|	d*k�r�d+}nd,}z
t �!|�"d$���#d$�}Wn3t$�y�zt �!|�"d-���#d$�}d-}Wnt�d.|���tdd/id
d�YYWWSYnwt�d0|�d1|�d2|���t|||||d3��WWSt%�y}zt�d4t|����tdd5idd�WYd#}~WSd#}~wwt�y+}zt�d6t|����tdd7id8d�WYd#}~Sd#}~ww)9a�
    GET /api/ai-scanner/files/content?path=wp-content/plugins/plugin.php
    
    Headers:
    Authorization: Bearer cp_access_abc123...
    X-Scan-ID: 550e8400-e29b-41d4-a716-446655440000
    
    Response:
    {
        "path": "wp-content/plugins/plugin.php",
        "content": "<?php
// Plugin code here...",
        "size": 15420,
        "encoding": "utf-8",
        "mime_type": "text/x-php"
    }
    rqrrrsr5rtr9r7rurvr6r(r&zFile path required>r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rzFile type not allowed: r�rr=rr:rSrTzstat -c %s "r@TrAi�zFile too large (max 10MB)z![API] Could not parse file size: z[API] Could not get file size: rDzFile not found or inaccessibler?Nzutf-8z*[API] File read failed: No result returnedzUnable to read filez[API] File read error: r�z
text/x-phpr�zapplication/javascriptz
text/plainzlatin-1z([API] Failed to encode file content for zFile encoding not supportedz[API] File content retrieved: z (z bytes) for scan )r(rlr��encoding�	mime_typer�r�z[API] Get file content error: r�rU)&r�rrrr�rpr*r%r/rJr'r(�splitextr�rYr>r�rrr;r[rrZr�r�rrr_r r!�	mimetypes�
guess_type�base64�	b64encode�encode�decode�UnicodeEncodeErrorr)rfr�r1r"r(r#r5r.�allowed_extensions�file_extr>rrhrB�stat_command�stat_result�	file_size�cat_commandrkrlr�r$r��_�content_base64rrr�get_file_contentHs�

���$
� ��

��	�����r�c
Csj�zut�|j�}|�d�}|�d�}|�di�}|�dg�}|�dd�}|�d�}t�d|�d	|����z�d
dlm}dd
lm	}	ddl
}
|jj|d�}||_|�dd�|_
|�dd�|_|�dd�}zt|�dd��dd��}
|
|_Wnttfy�d|_Ynw|�|�|�dd�|�dd�|�dd�|d�}|�|�|r�z|
j
�|�dd��}||_Wnty�|	��|_Ynw|	��|_|��zpd
dlm}|jj|d�\}}d|_d|_|�dd�|_|�dd�|_d|_ |�dd�|_!d}d}|D]}|�dd��"�}|d k�r|d
7}q�|d!k�r|d
7}q�||_#||_$d"|�dd��d#�|_%|��t�d$|���Wnt&�yW}zt�d%t'|����WYd}~nd}~ww|jdk�r�z5|j(j)}|j*|jk�r�t|j*�t|j�|_*|��t�d&|j�d'|j(j+�d(��n	t�d)|j���Wnt&�y�}zt�d*t'|����WYd}~nd}~wwzd
d+lm,}|jj-|d,�j.d-d.�t�d/|���Wnt&�y�}zt�d0t'|����WYd}~nd}~wwt�d1|�d2��t�d3|���t�d4|�d����t�d5|�d����t�d6|�d����t�d7|�d����WnE|j/�yFt�d8|���t0d9d:|d;�d<d=�YWSt&�ym}zt�d>t'|����t0d9d?|d;�d@d=�WYd}~WSd}~wwt0dAdB|d;��WStj1�y�t�dC�t0d9dDdE�dFd=�YSt&�y�}zt�dGt'|����t0d9dHdE�d@d=�WYd}~Sd}~ww)Ia,
    Receive scan completion callbacks from AI Scanner platform
    
    POST /api/ai-scanner/callback
    Content-Type: application/json
    
    Expected payload:
    {
        "scan_id": "uuid",
        "status": "completed",
        "summary": {
            "threat_level": "HIGH|MEDIUM|LOW",
            "total_findings": 3,
            "files_scanned": 25,
            "cost": "$0.0456"
        },
        "findings": [
            {
                "file_path": "wp-content/plugins/file.php",
                "severity": "CRITICAL|HIGH|MEDIUM|LOW", 
                "title": "Issue title",
                "description": "Detailed description",
                "ai_confidence": 95
            }
        ],
        "ai_analysis": "AI summary text",
        "completed_at": "2025-06-23T11:40:12Z"
    }
    r"r8�summary�findings�ai_analysisrr�completed_atz![API] Received callback for scan z: r)r
r)�timezoneN)r"�total_findings�
files_scanned�costz$0.00�$�,g�threat_level�UNKNOWN)r�r�r�r��Zz+00:00)�ScanStatusUpdate�	completed�d�severity�critical�highzScan completed - z threats foundz2[API] Updated ScanStatusUpdate for completed scan z'[API] Error updating ScanStatusUpdate: z[API] Deducted $z from z balancez+[API] Insufficient balance for scan cost: $z[API] Error updating balance: )r	)�scan_historyF)rz.[API] Deactivated file access tokens for scan z![API] Error deactivating tokens: z[API] Scan z completed successfully:z[API]   Status: z[API]   Threat Level: z[API]   Findings: z[API]   Files Scanned: z[API]   Cost: z[API] Scan record not found: r5zScan record not found)r8�messager"rTr7z$[API] Failed to update scan record: zFailed to update scan recordrUrOzCallback received successfullyz&[API] Invalid JSON in callback requestzInvalid JSON payload)r8r�r6z![API] Callback processing error: r�)2rVrWrXrrr�modelsr
�django.utilsr��datetimerr8�issues_foundr��floatr��cost_usdr��AttributeError�set_findings�set_summary�
fromisoformatr��now�save�
status_modelsr��
get_or_create�phase�progress�files_discovered�files_remaining�
threats_foundr��critical_threats�high_threats�activity_descriptionr r!�admin�ai_scanner_settings�balance�userNamer	�filter�updaterrre)rfrgr"r8r�r�r�r�r
r�r��scan_record�cost_str�
cost_value�summary_dict�completed_datetimer��
status_updater��critical_count�
high_count�findingr�r$�scanner_settingsr	rrr�
scan_callback�s 




�



�

�



� �� � �� ��������	
�
�
�����r�)rVr'�timer�r��django.httpr�django.views.decorators.csrfr�django.views.decorators.httprr�r�loginSystem.modelsrr�r	r
�plogical.CyberCPLogFileWriterrrr rr%r/ror�r�r�rrrr�<module>s:%n