File size: 3,155 Bytes
de5bde0
f1c6807
 
de5bde0
f1c6807
 
 
de5bde0
f1c6807
 
de5bde0
 
 
 
 
8f4e72d
 
 
f1c6807
de5bde0
f1c6807
 
de5bde0
 
 
 
 
 
 
f1c6807
de5bde0
 
 
 
f1c6807
ef3c08e
f1c6807
f8b38e6
 
f1c6807
ef3c08e
8f4e72d
de5bde0
ef3c08e
8f4e72d
de5bde0
ef3c08e
 
 
 
 
de5bde0
ef3c08e
 
 
de5bde0
 
ef3c08e
 
8f4e72d
de5bde0
 
f1c6807
 
de5bde0
 
 
ef3c08e
de5bde0
 
 
f1c6807
ef3c08e
 
 
 
de5bde0
ef3c08e
f1c6807
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from huggingface_hub import InferenceClient
import logging
from typing import Dict, List
import os


class ReportGenerator:

    def __init__(self):
        try:
            hf_token = os.getenv("HF_API_TOKEN")

            if not hf_token:
                raise ValueError("Hugging Face API token is required")

            self.client = InferenceClient(
                model="mistralai/Mistral-7B-Instruct-v0.3", token=hf_token
            )
        except Exception as e:
            logging.error(f"Failed to initialize Inference client: {str(e)}")
            raise

    def _truncate_list(self, items: List[str], max_items: int = 15) -> List[str]:
        """Truncate a list to a maximum number of items."""
        if len(items) > max_items:
            return items[:max_items] + [f"... and {len(items) - max_items} more"]
        return items

    def generate_report(self, basic_info: Dict, security_issues: List[str]) -> str:
        try:
            truncated_permissions = self._truncate_list(
                basic_info.get("permissions", [])
            )
            truncated_issues = self._truncate_list(security_issues)

            prompt = f"""<s>[INST] As a security expert and Android developer, analyze this Android app and provide specific code-level recommendations:

App: {basic_info.get('app_name', 'Unknown')} ({basic_info.get('package', 'Unknown')})
Version: {basic_info.get('version', 'Unknown')}

Security Issues Found:
{chr(10).join([f"- {issue}" for issue in truncated_issues])}

Requested Permissions:
{chr(10).join([f"- {perm}" for perm in truncated_permissions])}

Please provide:
1. A brief security risk assessment
2. Specific code-level fixes for each issue, including example code snippets where applicable
3. Best practices that should be implemented
4. Recommended security configurations

Format your response with clear sections and include Android/Java code examples for fixes. [/INST]</s>"""

            # Call the Inference API with adjusted parameters for more detailed output
            response = self.client.text_generation(
                prompt,
                max_new_tokens=1024,  # Increased token limit for more detailed response
                temperature=0.2,  # Slightly increased for more creative suggestions
                repetition_penalty=1.2,
                do_sample=True,
                return_full_text=False,
            )

            if not response:
                return "Error: Could not generate a meaningful report"

            # Format the final report with clear sections
            return f"""## Security Analysis Report

{response}

### Additional Resources
- [Android Security Best Practices](https://developer.android.com/topic/security/best-practices)
- [OWASP Mobile Security Testing Guide](https://owasp.org/www-project-mobile-security-testing-guide/)

---
*Note: This analysis is based on static analysis and may not cover all runtime behaviors. Implement these suggestions after thorough testing.*"""

        except Exception as e:
            logging.error(f"Error generating report: {str(e)}")
            return f"Error generating report: {str(e)}"