# Improper Handling of Exceptional Conditions (CWE-755) The product does not handle or incorrectly handles an exceptional condition. - Prevalence: Moyenne 3 langages couverts - Impact: Élevé 1 règles de sévérité élevée - Prevention: Documentée 4 exemples de correctifs **OWASP:** Insecure Design (A04:2021-Insecure Design) - #4 ## Description When exceptional conditions are not properly handled, the product may enter an undefined state, crash, or expose sensitive information. This can lead to denial of service, information disclosure, or unexpected behavior. ## Prevention Stratégies de prévention pour Improper Handling of Exceptional Conditions basées sur 4 règles de détection Shoulder. ### Go Always check error return values before using other results ### JavaScript Use finally blocks to release resources (connections, file handles) on all code paths ### Python Return error responses when security checks fail instead of continuing execution Wrap database, file, network, and API operations in try/except with proper logging ## Warning Signs - [HIGH] security checks (authentication, authorization, validation) inside try/except blocks that return suc - [MEDIUM] Resource at ... may not be released when exceptions occur - [MEDIUM] code that allocates resources (files, connections, memory) within try blocks but fails to release th - [MEDIUM] critical operations (database, file I/O, network calls, external APIs) that lack proper exception ha ## Consequences - DoS - Lecture des données de l'application - Exécuter du code non autorisé ## Mitigations - Anticipez toutes les conditions exceptionnelles potentielles et gérez-les correctement - Utilisez des blocs try-catch et des mécanismes appropriés de gestion d'erreurs - Échouez de manière sécurisée lorsqu'une exception se produit ## Detection - Total rules: 4 - Languages: go, javascript, typescript, python ## Rules by Language ### Python (2 rules) - **Security Check Failing Open** [HIGH]: Detects security checks (authentication, authorization, validation) inside try/except blocks that return success on exception. This causes the system to "fail open" - granting access when security checks fail. - Remediation: Return an error response when security checks fail instead of continuing execution. ```python from flask import request, abort @app.route('/api/admin') def admin_endpoint(): try: user = authenticate(request.headers.get('Authorization')) check_admin_permission(user) except (AuthenticationError, PermissionError): abort(403) # Fail closed - deny access return {'data': get_admin_data()} ``` Learn more: https://shoulder.dev/learn/python/cwe-755/failing-open - **Missing Exception Handling in Critical Operations** [MEDIUM]: Detects critical operations (database, file I/O, network calls, external APIs) that lack proper exception handling. Uncaught exceptions can crash the application, leak sensitive information, or leave the system in an inconsistent state. - Remediation: Wrap database, file, network, and API operations in try/except blocks. ```python import logging import requests logger = logging.getLogger(__name__) def fetch_data(url): try: response = requests.get(url, timeout=5) response.raise_for_status() return response.json() except requests.RequestException as e: logger.error(f"Request failed: {e}") return None ``` Learn more: https://shoulder.dev/learn/python/cwe-755/uncaught-exception ### Go (1 rules) - **Incomplete Error Handling** [MEDIUM]: Function returns error but caller does not check err != nil. - Remediation: Check error return values before using other returned values. ```go result, err := process() if err != nil { return err } // Now safe to use result ``` Learn more: https://shoulder.dev/learn/go/cwe-755/incomplete-error-handling ### Javascript (1 rules) - **Resource Exhaustion via Exception Handling** [MEDIUM]: Detects code that allocates resources (files, connections, memory) within try blocks but fails to release them in finally blocks or error paths. When exceptions occur, resources may not be properly cleaned up, leading to resource exhaustion, memory leaks, and denial of service. - Remediation: Use finally blocks or try-with-resources pattern: ```javascript // ✅ SAFE - Cleanup in finally let connection; try { connection = await db.getConnection(); await connection.query(sql); } catch (error) { logger.error('Query failed:', error); throw error; } finally { if (connection) { await connection.release(); } } ``` ### Typescript (1 rules) - **Resource Exhaustion via Exception Handling** [MEDIUM]: Detects code that allocates resources (files, connections, memory) within try blocks but fails to release them in finally blocks or error paths. When exceptions occur, resources may not be properly cleaned up, leading to resource exhaustion, memory leaks, and denial of service. - Remediation: Use finally blocks or try-with-resources pattern: ```javascript // ✅ SAFE - Cleanup in finally let connection; try { connection = await db.getConnection(); await connection.query(sql); } catch (error) { logger.error('Query failed:', error); throw error; } finally { if (connection) { await connection.release(); } } ```