diff --git a/docs/Secure-Coding-Guide-for-Python/CWE-703/CWE-230/README.md b/docs/Secure-Coding-Guide-for-Python/CWE-703/CWE-230/README.md new file mode 100644 index 00000000..864af80d --- /dev/null +++ b/docs/Secure-Coding-Guide-for-Python/CWE-703/CWE-230/README.md @@ -0,0 +1,153 @@ +# CWE-230: Improper Handling of Missing Values + +The `NaN` value should be stripped before as they can cause surprising or undefined behaviours in the statistics functions that sort or count occurrences [[2024 doc.python.org]](https://docs.python.org/3/library/statistics.html). +In python, some datasets use `NaN` (not-a-number) to represent the missing data. This can be problematic as the `NaN` values are unordered. Any ordered comparison of a number to a not-a-number value are `False`. A counter-intuitive implication is that `not-a-number` values are not equal to themselves. + +This behavior is compliant with IEEE 754[[2024 Wikipedia]](https://en.wikipedia.org/wiki/IEEE_754) a hardware induced compromise. +The [example01.py](example01.py) code demonstrates various comparisons of `float('NaN')` all resulting in `False`. + +```python +# SPDX-FileCopyrightText: OpenSSF project contributors +# SPDX-License-Identifier: MIT +""" Code Example """ + +foo = float('NaN') +print(f"foo={foo} type = {type(foo)}") + + +print(foo == float("NaN") or + foo is float("NaN") or + foo < 3 or + foo == foo or + foo is None + ) + +``` + +## Non-Compliant Code Example + +This noncompliant code example [[2024 docs.python.org]](https://docs.python.org/3/reference/expressions.html#value-comparisons) attempts a direct comparison with `NaN` in `_value == float("NaN")`. + +*[noncompliant01.py](noncompliant01.py):* + +```python +# SPDX-FileCopyrightText: OpenSSF project contributors +# SPDX-License-Identifier: MIT +""" Non-compliant Code Example """ + + +def balance_is_positive(value: str) -> bool: + """Returns True if there is still enough value for a transaction""" + _value = float(value) + if _value == float("NaN") or _value is float("NaN") or _value is None: + raise ValueError("Expected a float") + if _value <= 0: + return False + else: + return True + + +##################### +# attempting to exploit above code example +##################### +print(balance_is_positive("0.01")) +print(balance_is_positive("0.001")) +print(balance_is_positive("NaN")) + +``` + +The `balance_is_positive` method returns `True` for all 3 cases instead of throwing an `ValureError` exception for `balance_is_positive("NaN")`. + +## Compliant Solution + +In the `compliant01.py` code example, the method `Decimal.quantize` is used to gain control over known rounding errors in floating point values. + +The decision by the balance_is_positive method is to `ROUND_DOWN` instead of the default `ROUND_HALF_EVEN`. + +*[compliant01.py](compliant01.py):* + +```python +# SPDX-FileCopyrightText: OpenSSF project contributors +# SPDX-License-Identifier: MIT +""" Compliant Code Example """ + +from decimal import ROUND_DOWN, Decimal + + +def balance_is_positive(value: str) -> bool: + """Returns True if there is still enough value for a transaction""" + # TODO: additional input sanitation for expected type + _value = Decimal(value) + # TODO: exception handling + return _value.quantize(Decimal(".01"), rounding=ROUND_DOWN) > Decimal("0.00") + + +##################### +# attempting to exploit above code example +##################### +print(balance_is_positive("0.01")) +print(balance_is_positive("0.001")) +print(balance_is_positive("NaN")) + +``` + +`Decimal` throws a `decimal.InvalidOperation` for `NaN` values, the controlled rounding causes only `"0.01"` to return `True`. + +In `compliant02.py` we use the math.isnan to very if the value passed is a valid `float` value. + +*[compliant02.py](compliant02.py):* + +```python +# SPDX-FileCopyrightText: OpenSSF project contributors +# SPDX-License-Identifier: MIT +""" Compliant Code Example """ + +import math + + +def balance_is_positive(value: str) -> bool: + """Returns True if there is still enough value for a transaction""" + _value = float(value) + if math.isnan(_value) or _value is None: + raise ValueError("Expected a float") + if _value < 0.01: + return False + else: + return True + + +##################### +# attempting to exploit above code example +##################### +print(balance_is_positive("0.01")) +print(balance_is_positive("0.001")) +print(balance_is_positive("NaN")) + +``` + +The `balance_is_poitive` method will raise an `ValueError` for `NaN` values. + +## Automated Detection + +|Tool|Version|Checker|Description| +|:----|:----|:----|:----| +|Bandit|1.7.4 on Python 3.10.4|Not Available|| +|flake8|flake8-4.0.1 on python 3.10.4||Not Available| + +## Related Guidelines + +||| +|:---|:---| +|[SEI CERT Coding Standard for Java](https://wiki.sei.cmu.edu/confluence/display/java/SEI+CERT+Oracle+Coding+Standard+for+Java)|[NUM07-J. Do not attempt comparisons with NaN](https://wiki.sei.cmu.edu/confluence/display/java/NUM07-J.+Do+not+attempt+comparisons+with+NaN)| +|[ISO/IEC TR 24772:2013](https://wiki.sei.cmu.edu/confluence/display/java/Rule+AA.+References#RuleAA.References-ISO/IECTR24772-2013)|Injection RST| +|[MITRE CWE Pillar](http://cwe.mitre.org/)|[CWE-703: Improper Check or Handling of Exceptional Conditions (mitre.org)](https://cwe.mitre.org/data/definitions/703.html)| +|[MITRE CWE Pillar](http://cwe.mitre.org/)|[CWE-230: Improper Handling of Missing Values](https://cwe.mitre.org/data/definitions/230.html)| + +## Bibliography + +||| +|:---|:---| +|[[Python 3.10.4 docs]](https://docs.python.org/3/library/string.html#formatstrings)|Format String Syntax. Available from: \[Accessed 22 July 2025]| +|[Python docs](https://docs.python.org/3/)| \[Accessed 22 July 2025]| +|[Python docs](https://docs.python.org/3/)|Python Value comparisons \[Accessed 22 July 2025]| +|[[Wikipedia 2024]](https://realpython.com/python-string-formatting/)|IEEE 754: \[Accessed 22 July 2025]| diff --git a/docs/Secure-Coding-Guide-for-Python/CWE-703/CWE-230/compliant01.py b/docs/Secure-Coding-Guide-for-Python/CWE-703/CWE-230/compliant01.py index b718a9d8..d1d081da 100644 --- a/docs/Secure-Coding-Guide-for-Python/CWE-703/CWE-230/compliant01.py +++ b/docs/Secure-Coding-Guide-for-Python/CWE-703/CWE-230/compliant01.py @@ -1,6 +1,6 @@ # SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT -""" Non-compliant Code Example """ +""" Compliant Code Example """ from decimal import ROUND_DOWN, Decimal diff --git a/docs/Secure-Coding-Guide-for-Python/CWE-703/CWE-230/compliant02.py b/docs/Secure-Coding-Guide-for-Python/CWE-703/CWE-230/compliant02.py new file mode 100644 index 00000000..d82a1b45 --- /dev/null +++ b/docs/Secure-Coding-Guide-for-Python/CWE-703/CWE-230/compliant02.py @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: OpenSSF project contributors +# SPDX-License-Identifier: MIT +""" Compliant Code Example """ + +import math + + +def balance_is_positive(value: str) -> bool: + """Returns True if there is still enough value for a transaction""" + _value = float(value) + if math.isnan(_value) or _value is None: + raise ValueError("Expected a float") + if _value < 0.01: + return False + else: + return True + + +##################### +# attempting to exploit above code example +##################### +print(balance_is_positive("0.01")) +print(balance_is_positive("0.001")) +print(balance_is_positive("NaN")) diff --git a/docs/Secure-Coding-Guide-for-Python/CWE-710/CWE-1095/README.md b/docs/Secure-Coding-Guide-for-Python/CWE-710/CWE-1095/README.md index 9ae565bd..79a19efb 100644 --- a/docs/Secure-Coding-Guide-for-Python/CWE-710/CWE-1095/README.md +++ b/docs/Secure-Coding-Guide-for-Python/CWE-710/CWE-1095/README.md @@ -6,22 +6,29 @@ In-place modification of mutable types such as `list`, `dict`, or `set` that are ## Non-Compliant Code Example (List) -This `noncompliant01.py` example will successfully remove the Bob from `userlist` but this modifies the original list `userlist` and is not recommended. +This `noncompliant01.py` example will remove only one name that starts with `B` despite trying to remove them all without any exception raised: [*noncompliant01.py:*](noncompliant01.py) ```py """ Non-compliant Code Example """ -userlist = ['Alice', 'Bob', 'Charlie'] +userlist = ['Alice', 'Bob', 'Bill', 'Charlie'] print(f'Unmodified list: {userlist}') for user in userlist: - if user == 'Bob': + if user.startswith('B'): userlist.remove(user) print(f'Modified list: {userlist}') ``` +Output from above noncompliant01.py: + +```bash +Unmodified list: ['Alice', 'Bob', 'Bill', 'Charlie'] +Modified list: ['Alice', 'Bill', 'Charlie'] +``` + ## Non-Compliant Code Example (Dict) This `noncompliant02.py` example attempts to delete a dictionary entry, which will result in a `RuntimeError: Dictionary changed size during iteration error` being thrown. @@ -63,12 +70,12 @@ The `compliant01.py` solution demonstrates both strategies. The first example cr ```py """ Compliant Code Example """ -userlist = ['Alice', 'Bob', 'Charlie'] +userlist = ['Alice', 'Bob', 'Bill', 'Charlie'] print(f'Unmodified list: {userlist}') # Create a copy for user in userlist.copy(): - if user == 'Bob': + if user.startswith('B'): userlist.remove(user) print(f'Modified list: {userlist}') @@ -80,7 +87,7 @@ print(f'Unmodified list: {userlist2}') # Create new list activeusers = [] for user in userlist2: - if user != 'Bob': + if user.startswith('B'): activeusers.append(user) print(f'New list: {activeusers}') ``` diff --git a/docs/Secure-Coding-Guide-for-Python/CWE-710/CWE-1095/compliant01.py b/docs/Secure-Coding-Guide-for-Python/CWE-710/CWE-1095/compliant01.py index 53432c9b..2f9741e5 100644 --- a/docs/Secure-Coding-Guide-for-Python/CWE-710/CWE-1095/compliant01.py +++ b/docs/Secure-Coding-Guide-for-Python/CWE-710/CWE-1095/compliant01.py @@ -1,12 +1,12 @@ # SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Compliant Code Example """ -userlist = ['Alice', 'Bob', 'Charlie'] +userlist = ['Alice', 'Bob', 'Bill', 'Charlie'] print(f'Unmodified list: {userlist}') # Create a copy for user in userlist.copy(): - if user == 'Bob': + if user.startswith('B'): userlist.remove(user) print(f'Modified list: {userlist}') @@ -18,6 +18,6 @@ # Create new list activeusers = [] for user in userlist2: - if user != 'Bob': + if not user.startswith('B'): activeusers.append(user) print(f'New list: {activeusers}') diff --git a/docs/Secure-Coding-Guide-for-Python/CWE-710/CWE-1095/noncompliant01.py b/docs/Secure-Coding-Guide-for-Python/CWE-710/CWE-1095/noncompliant01.py index c3da6b3d..93c647fa 100644 --- a/docs/Secure-Coding-Guide-for-Python/CWE-710/CWE-1095/noncompliant01.py +++ b/docs/Secure-Coding-Guide-for-Python/CWE-710/CWE-1095/noncompliant01.py @@ -1,11 +1,11 @@ # SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Non-compliant Code Example """ -userlist = ['Alice', 'Bob', 'Charlie'] +userlist = ['Alice', 'Bob', 'Bill', 'Charlie'] print(f'Unmodified list: {userlist}') for user in userlist: - if user == 'Bob': + if user.startswith('B'): userlist.remove(user) print(f'Modified list: {userlist}') diff --git a/docs/Secure-Coding-Guide-for-Python/readme.md b/docs/Secure-Coding-Guide-for-Python/readme.md index c398eddd..3686130e 100644 --- a/docs/Secure-Coding-Guide-for-Python/readme.md +++ b/docs/Secure-Coding-Guide-for-Python/readme.md @@ -92,7 +92,7 @@ It is __not production code__ and requires code-style or python best practices t |[CWE-703: Improper Check or Handling of Exceptional Conditions](https://cwe.mitre.org/data/definitions/703.html)|Prominent CVE| |:----------------------------------------------------------------|:----| -|[CWE-230: Improper Handling of Missing Values](CWE-703/CWE-230/.)|| +|[CWE-230: Improper Handling of Missing Values](CWE-703/CWE-230/README.md)|| |[CWE-252: Unchecked Return Value](CWE-703/CWE-252/README.md)|| |[CWE-390: Detection of Error Condition without Action](CWE-703/CWE-390/README.md)|| |[CWE-392: Missing Report of Error Condition](CWE-703/CWE-392/README.md)|| diff --git a/docs/Security-Focused-Guide-for-AI-Code-Assistant-Instructions.md b/docs/Security-Focused-Guide-for-AI-Code-Assistant-Instructions.md new file mode 100644 index 00000000..dc788854 --- /dev/null +++ b/docs/Security-Focused-Guide-for-AI-Code-Assistant-Instructions.md @@ -0,0 +1,64 @@ +# **Security-Focused Guide for AI Code Assistant Instructions** + +AI code assistants can significantly speed up development, but they need guidance to produce **secure** and robust code. This guide explains how to create custom instructions (e.g. [GitHub Copilot instructions file](https://docs.github.com/en/copilot/how-tos/custom-instructions/adding-repository-custom-instructions-for-github-copilot), [Cline instructions file](https://docs.cline.bot/enterprise-solutions/custom-instructions), [Cursor rules](https://docs.cursor.com/context/rules), [Claude markdown](https://docs.anthropic.com/en/docs/claude-code/common-workflows#create-an-effective-claude-md-file), etc.) that ensure the AI assistant accounts for application code security, supply chain safety, and platform or language-specific considerations and to embed a “security conscience” into the tool. In practice, this means fewer vulnerabilities making it into your codebase. Remember that these instructions should be kept concise, specific, and actionable – the goal is to influence the AI’s behaviour without overwhelming it. + +--- + +## **Secure Coding Principles in AI Instructions** + +One of the first sections in your instructions should reinforce general secure coding best practices. These principles apply to all languages and frameworks, and you want the AI to **always** keep them in mind when generating code: + +* **Input Validation & Output Encoding:** Instruct the AI to treat all external inputs as untrusted and to validate them. *Example*: “user inputs should be checked for expected format and length”. Any output should be properly encoded to prevent injection attacks such as SQL injection or cross-site scripting (XSS). *Example:* “Always validate function arguments and use parameterized queries for database access” and "Escape special characters in user-generated content before rendering it in HTML”. Similarly, specify that when generating output contexts such as HTML or SQL, the assistant should use safe frameworks or encoding functions to avoid vulnerabilities. +* **Authentication, Authorization & Secrets Management:** Emphasize that **credentials and sensitive tokens must never be hard-coded** or exposed. Your instructions can say: *“Never include API keys, passwords, or secrets in code output, and use environment variables or secure vault references instead”*. Also instruct the AI to use secure authentication flows (for instance, using industry-standard libraries for handling passwords or tokens) and to enforce role-based access checks where appropriate. +* **Error Handling & Logging:** Guide the AI to implement errors securely. That means **catching exceptions and failures without revealing sensitive info** (stack traces, server paths, etc.) to the end-user. In your instructions, you might include: *“When generating code, handle errors gracefully and log them, but do not expose internal details or secrets in error messages.”* This ensures the assistant’s suggestions include secure error-handling patterns (like generic user-facing messages and detailed logs only on the server side). Additionally, instruct the AI to use logging frameworks that can be configured for security (e.g. avoiding logging of personal data or secrets). +* **Secure Defaults & Configurations:** Include guidance such as: *“Prefer safe defaults in configurations – for example, use HTTPS by default, require strong encryption algorithms, and disable insecure protocols or options.”* By specifying this, the AI will be more likely to generate code that opts-in to security features. Always instruct the AI to follow the principle of least privilege (e.g. minimal file system permissions, least-privileged user accounts for services, etc.) in any configuration or code it proposes. +* **Testing for Security:** Encourage the AI to produce or suggest tests for critical code paths. In your instructions, add: *“When applicable, generate unit tests for security-critical functions (including negative tests to ensure the code fails safely).”* Automated testing is a recognized best practice – guides recommend including negative tests to verify that what *shouldn’t* happen, doesn’t happen. +* **Call out and review stubbed code:** If the AI generates code that is stubbed or incomplete, instruct it to flag these areas for review. For example: *“If you generate placeholder code (e.g., `TODO` comments), ensure it is marked for security review before deployment.”* This will help ensure that any incomplete code does not inadvertently introduce vulnerabilities. + +--- + +## **Addressing Software Supply Chain Security** + +Modern software heavily relies on third-party libraries and dependencies. It’s crucial that your AI assistant’s instructions cover supply chain security, ensuring that suggested dependencies and build processes are secure: + +* **Safe Dependency Selection:** Instruct the AI to **prefer well-vetted, reputable libraries** when suggesting code that pulls in external packages. For example, *“Use popular, community-trusted libraries for common tasks (and avoid adding obscure dependencies if a standard library or well-known package can do the same job).”* Emphasize evaluating packages before use – as a developer would manually. +* **Use Package Managers & Lock Versions:** Your instructions should tell the AI to use proper package management. For instance: *“Always use the official package manager for the given language (npm, pip, Maven, etc.) to install libraries, rather than copying code snippets.”* Also, instruct it to specify version ranges or exact versions that are known to be secure. By doing so, the AI will generate code that, for example, uses a `requirements.txt` or `package.json` entry, which aids in maintaining supply chain integrity. +* **Stay Updated & Monitor Vulnerabilities:** Include guidance for keeping dependencies up-to-date. For example: *"When suggesting dependency versions, prefer the latest stable release and mention updating dependencies regularly to patch vulnerabilities"*. +* **Generate Software Bill of Materials (SBOM):** Instruct the AI to create and maintaining SBOMs for better visibility into your software supply chain. For example: *"Generate a Software Bill of Materials (SBOM) by using tools that support standard formats like SPDX or CycloneDX."* You can also mention provenance tracking: *"Where applicable, use in-toto attestations or similar frameworks to create verifiable records of your build and deployment processes."* This ensures comprehensive tracking of what goes into your software and provides the foundation for ongoing vulnerability monitoring and incident response. +* **Integrity Verification:** To further secure the supply chain, you can instruct the assistant to show how to verify what it uses. For instance: *"When adding important external resources (scripts, containers, etc.), include steps to verify integrity (like checksum verification or signature validation) if applicable."* + +--- + +## **Platform and Runtime Security Considerations** + +Every software runs somewhere – be it a web browser, a cloud platform, an IoT device, or an OS. Your guide for the AI assistant should have a section addressing platform-specific and runtime security concerns: + +* **Operating System and Environment:** If your code will run on a server or user machine, instruct the AI on safe system interactions. *“When writing file or OS-level operations, use safe functions and check for errors (e.g., use secure file modes, avoid temp files without proper randomness, etc.). If running as a service, drop privileges when possible.”* This ensures the AI’s output respects security at the OS level (for example, not recommending running as root unless absolutely necessary). Emphasize least privilege: for instance, code for a service should use the minimal privileges needed. The assistant could then suggest using system APIs that limit permissions or show how to configure a Linux capability instead of full root access. +* **Web and Cloud Platforms:** For web applications, direct the AI to include web security best practices. *“Always include appropriate security headers (Content Security Policy, X-Frame-Options, etc.) in web responses, and use frameworks’ built-in protections for cookies and sessions.”* You can also mention using HTTPS for any client-server communication. On cloud platforms, instruct it on secure use of cloud services: *“When generating code for cloud services (AWS/Azure/GCP), follow the provider’s security guidelines (e.g., use parameterized queries for cloud databases, encrypt data at rest and in transit, handle keys via cloud KMS).”* +* **Container and Deployment Considerations:** If your project uses containers or orchestrators (like Docker, Kubernetes), include guidance like: *"Use minimal base images and avoid running containers with the root user. Use official images from trusted sources, and pin image versions using immutable digests (e.g., SHA256 hashes) instead of mutable tags like latest".* This will cause the AI to generate Dockerfiles or deployment scripts that adhere to container security best practices and ties into supply chain concerns as well – using only trusted images and specific versions that ensure consistency and prevent supply chain attacks. Additionally, instruct the AI on container signature verification: *"When working with container images, verify both the integrity and authenticity of images using container signing tools like cosign or notation. Include steps to verify signatures from trusted publishers and implement admission controllers in Kubernetes to enforce signature verification policies."* Instruct the AI to further control deployment artifacts. For instance, by ensuring production websites only load resources from trusted domains to avoid subversion: *"When generating HTML/JS, do not include direct links to untrusted third-party hosts for critical libraries; use our locally hosted or CDN with integrity checks."* +* **Mobile and Desktop App Security:** If relevant, instruct on platform-specific secure coding. For mobile apps, you might say: *“Do not suggest storing sensitive data in plaintext on the device; use the platform’s secure storage APIs.”* For desktop apps, *“Prefer high-level libraries for cryptography rather than rolling your own.”* These platform notes ensure the AI isn’t blind to the context in which code runs. It will include, for example, usage of Android’s `SharedPreferences` with encryption or Apple’s Keychain for iOS if dealing with credentials, reflecting platform best practices. + +--- + +## **Programming Language-Specific Security Examples** + +It’s valuable to dedicate individual paragraphs to language-specific security considerations that are relevant to your project. The following section serves as examples, or special cases the AI should handle to highlight unique vulnerabilities or features of that language and how the AI should approach them: + +* **C/C++ (Memory-Unsafe Languages):** For languages without automatic memory safety, instruct the AI to be extra cautious with memory management. *“In C or C++ code, always use bounds-checked functions (e.g., `strncpy` over `strcpy`), avoid dangerous functions like `gets`, and include buffer size constants to prevent overflow. Enable compiler defenses (stack canaries, fortify source, DEP/NX) in any build configurations you suggest”*. By giving such instructions, the assistant might prefer safer standard library calls or even suggest modern C++ classes (`std::vector` instead of raw arrays) to reduce manual memory handling. It will also acknowledge when an operation is risky, possibly inserting comments like “// ensure no buffer overflow”. +* **Rust, Go, and Memory-Safe Languages:** If the project involves memory-safe languages (Rust, Go, Java, C\#, etc.), you can note that the AI should leverage their safety features. *“In Rust code, avoid using `unsafe` blocks unless absolutely necessary and document any `unsafe` usage with justification.”* Memory-safe-by-default languages enforce a lot at compile time, but you should still have the AI follow best practices of those ecosystems. For example, instruct: *“In any memory-safe language, prefer using safe library functions and types; don’t circumvent their safety without cause.”* If a language offers any tools to verify memory access, direct the AI assistant to use them while building or testing your code. For Example “*In go code, use the data race detector when building the application*”. +* **Python and Dynamic Languages:** Python, JavaScript, and other high-level languages manage memory for you, but come with their own security pitfalls. In your instructions, emphasize things like avoiding exec/eval with untrusted input in Python and being careful with command execution. *“For Python, do not use `exec`/`eval` on user input and prefer safe APIs (e.g., use the `subprocess` module with `shell=False` to avoid shell injection).”* Additionally, mention type checking or the use of linters: *“Follow PEP 8 and use type hints, as this can catch misuse early.”* For JavaScript/TypeScript, you might add: *“When generating Node.js code, use prepared statements for database queries (just like any other language) and encode any data that goes into HTML to prevent XSS”.* These instructions incorporate known best practices (like those from OWASP cheat sheets) directly into the AI’s behavior. +* **Java/C\# and Enterprise Languages:** In languages often used for large applications, you might focus on frameworks and configurations. *“For Java, when suggesting web code (e.g., using Spring), ensure to use built-in security annotations and avoid old, vulnerable libraries (e.g., use `BCryptPasswordEncoder` rather than writing a custom password hash).”* For C\#, similarly: *“Use .NET’s cryptography and identity libraries instead of custom solutions.”* Also instruct about managing object deserialization (both Java and C\# have had vulnerabilities in this area): *“Never suggest turning off security features like XML entity security or type checking during deserialization.”* These language-specific notes guide the AI to incorporate the well-known secure patterns of each ecosystem. + +--- + +## **Referencing Security Standards and Frameworks** + +To strengthen your AI assistant’s guidance, you should point it toward established security standards and frameworks. By referencing these in the instructions, the AI will be biased toward solutions that comply with widely accepted practices: + +* **Use Industry Standards as Keywords:** Mention standards like **OWASP Top 10**, **OWASP ASVS**, **CWE/SANS Top 25**, or language-specific guidelines (Java’s SEI CERT secure coding standards, for instance). For example: *“Code suggestions should adhere to OWASP Top 10 principles (e.g., avoid injection, enforce access control) and follow the OWASP ASVS requirements where applicable”.* +* **Reference SAFECode and Other Guides:** SAFECode (Software Assurance Forum for Excellence in Code) publishes **Fundamental Practices for Secure Software Development**, and including a note about it can be beneficial. *“Our project follows SAFECode’s secure development practices – the AI should prioritize those (e.g., proper validation, authentication, cryptography usage per SAFECode guidance).”* This ties the assistant’s suggestions to a comprehensive set of secure development principles. Similarly, you can reference the **Secure Software Development Lifecycle (SSDLC)** or standards like **ISO 27034** if your organization uses them, to align AI outputs with those processes. +* **Compliance and Regulatory Security:** If you operate in an industry with specific regulations (like healthcare or finance), instruct the AI with those in mind. For instance: *“When generating code, consider compliance requirements (e.g., HIPAA privacy rules for medical data, PCI-DSS for credit card info) – do not output code that logs or transmits sensitive data in insecure ways.”* This ensures the AI’s suggestions are compliant with external standards, for example, it might suggest encryption for personal data fields by default. +* **Continuous Improvement Hooks:** Encourage practices that integrate with ongoing security processes. For example: *“Include comments or TODOs in code suggesting security reviews for complex logic, and note if any third-party component might need a future update or audit.”* This way, the AI not only writes code but also flags areas for human scrutiny or future action. If the AI outputs a piece of cryptography code, for instance, it might add a comment “// TODO: security review for cryptographic implementation” because you instructed it that critical code should not go un-reviewed. +* **Integrate and Act on Automated Security Tooling:** Instruct the AI to proactively run automated security tools (e.g., SAST, DAST, SCA) during code generation and refinement. Example: “When writing or reviewing code, run or simulate the use of tools like CodeQL, Bandit, Semgrep, or OWASP Dependency-Check. Identify any flagged vulnerabilities or outdated dependencies and revise the code accordingly. Repeat this process until the code passes all simulated scans.” This positions the AI not just as a code generator but as a security-aware assistant capable of iterating based on tool feedback. + +---