Traversée de répertoire
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Catégorie OWASP : MASVS-STORAGE : stockage
Présentation
Les failles de traversée de répertoire se produisent lorsqu'un pirate informatique peut contrôler une partie du chemin, qui est ensuite transmis aux API du système de fichiers sans validation. Cela peut entraîner des opérations non autorisées dans le système de fichiers. Par exemple, un pirate peut utiliser des caractères spéciaux tels que ../
pour modifier de manière inattendue la cible de la ressource, en se déplaçant en dehors du répertoire ciblé.
Impact
Les conséquences varient en fonction de l'opération et du contenu des fichiers concernés, mais conduisent généralement à l'écrasement de fichiers (par l'écriture de fichiers), à des fuites de données (par la lecture de fichiers) ou à des modifications des autorisations (par la modification des autorisations de fichier/répertoire).
Stratégies d'atténuation
Définissez le chemin d'accès canonique à l'aide de File.getCanonicalPath()
et comparez le préfixe avec le répertoire attendu :
Kotlin
@Throws(IllegalArgumentException::class)
fun saferOpenFile(path: String, expectedDir: String?): File {
val f = File(path)
val canonicalPath = f.canonicalPath
require(canonicalPath.startsWith(expectedDir!!))
return f
}
Java
public File saferOpenFile (String path, String expectedDir) throws IllegalArgumentException {
File f = new File(path);
String canonicalPath = f.getCanonicalPath();
if (!canonicalPath.startsWith(expectedDir)) {
throw new IllegalArgumentException();
}
return f;
}
Une autre bonne pratique consiste à utiliser la validation pour vous assurer que seuls les résultats attendus se produisent. Voici quelques exemples :
- Vérifiez si le fichier existe déjà pour éviter un écrasement accidentel.
- Vérifiez si le fichier ciblé est une cible attendue pour éviter les fuites de données ou la modification incorrecte des autorisations.
- Vérifiez l'exactitude du répertoire actuel de l'opération dans la valeur renvoyée par le chemin canonique.
- Assurez-vous qu'un système d'autorisations est explicitement limité à l'opération, par exemple en vérifiant qu'il n'exécute pas de services en tant que racine, et que les autorisations de répertoires sont limitées au service ou à la commande spécifiés.
Recommandations personnalisées
Le contenu et les exemples de code de cette page sont soumis aux licences décrites dans la Licence de contenu. Java et OpenJDK sont des marques ou des marques déposées d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2023/12/26 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2023/12/26 (UTC)."],[],[],null,["# Path traversal\n\n\u003cbr /\u003e\n\n**OWASP category:** [MASVS-STORAGE: Storage](https://mas.owasp.org/MASVS/05-MASVS-STORAGE)\n\nOverview\n--------\n\nPath traversal vulnerabilities occur when an attacker can control part of the\npath that is then passed to the file system APIs without validation. This can\nlead to unauthorized file system operations. For example, an attacker might use\nspecial characters such as `../` to unexpectedly change the resource target, by\ntraversing outside of the targeted directory.\n\nImpact\n------\n\nThe impact varies depending on the operation and file content, but generally\nleads to a file overwrite (when writing files), data leak (when reading files),\nor permission changes (when changing file or directory permissions).\n\nMitigations\n-----------\n\nCanonicalize the path using [`File.getCanonicalPath()`](/reference/java/io/File#getCanonicalPath()) and compare the\nprefix with the expected directory: \n\n### Kotlin\n\n @Throws(IllegalArgumentException::class)\n fun saferOpenFile(path: String, expectedDir: String?): File {\n val f = File(path)\n val canonicalPath = f.canonicalPath\n require(canonicalPath.startsWith(expectedDir!!))\n return f\n }\n\n### Java\n\n public File saferOpenFile (String path, String expectedDir) throws IllegalArgumentException {\n File f = new File(path);\n String canonicalPath = f.getCanonicalPath();\n if (!canonicalPath.startsWith(expectedDir)) {\n throw new IllegalArgumentException();\n }\n return f;\n }\n\nAn additional best practice is to use validation to ensure only expected\noutcomes occur. Examples include the following:\n\n- Checking if the file already exists to prevent an accidental overwrite.\n- Checking if the targeted file is an expected target to prevent leaking data or incorrectly changing permissions.\n- Checking if the current directory of the operation is exactly as expected in the return value from the canonical path.\n- Ensuring a permissions system is explicitly scoped to the operation, such as checking that it isn't running services as root, and ensuring that the directory permissions are scoped to the service or command specified."]]