|
| 1 | +/** |
| 2 | + * @name Find work with the file without setting permissions. |
| 3 | + * @description Lack of restriction on file access rights can be unsafe. |
| 4 | + * @kind problem |
| 5 | + * @id cpp/work-with-file-without-permissions-rights |
| 6 | + * @problem.severity warning |
| 7 | + * @precision medium |
| 8 | + * @tags correctness |
| 9 | + * maintainability |
| 10 | + * security |
| 11 | + * external/cwe/cwe-200 |
| 12 | + * external/cwe/cwe-264 |
| 13 | + */ |
| 14 | + |
| 15 | +import cpp |
| 16 | +import semmle.code.cpp.valuenumbering.GlobalValueNumbering |
| 17 | + |
| 18 | +/** Holds for a function `f` that has an argument at index `apos` used to read the file. */ |
| 19 | +predicate numberArgumentRead(Function f, int apos) { |
| 20 | + f.hasGlobalOrStdName("fgets") and apos = 2 |
| 21 | + or |
| 22 | + f.hasGlobalOrStdName("fread") and apos = 3 |
| 23 | + or |
| 24 | + f.hasGlobalOrStdName("read") and apos = 0 |
| 25 | + or |
| 26 | + f.hasGlobalOrStdName("fscanf") and apos = 0 |
| 27 | +} |
| 28 | + |
| 29 | +/** Holds for a function `f` that has an argument at index `apos` used to write to file */ |
| 30 | +predicate numberArgumentWrite(Function f, int apos) { |
| 31 | + f.hasGlobalOrStdName("fprintf") and apos = 0 |
| 32 | + or |
| 33 | + f.hasGlobalOrStdName("fputs") and apos = 1 |
| 34 | + or |
| 35 | + f.hasGlobalOrStdName("write") and apos = 0 |
| 36 | + or |
| 37 | + f.hasGlobalOrStdName("fwrite") and apos = 3 |
| 38 | + or |
| 39 | + f.hasGlobalOrStdName("fflush") and apos = 0 |
| 40 | +} |
| 41 | + |
| 42 | +from FunctionCall fc |
| 43 | +where |
| 44 | + ( |
| 45 | + fc.getTarget().hasGlobalOrStdName("fopen") or |
| 46 | + fc.getTarget().hasGlobalOrStdName("open") |
| 47 | + ) and |
| 48 | + fc.getNumberOfArguments() = 2 and |
| 49 | + exists(FunctionCall fctmp, int i | |
| 50 | + numberArgumentWrite(fctmp.getTarget(), i) and |
| 51 | + globalValueNumber(fc) = globalValueNumber(fctmp.getArgument(i)) |
| 52 | + ) and |
| 53 | + not exists(FunctionCall fctmp, int i | |
| 54 | + numberArgumentRead(fctmp.getTarget(), i) and |
| 55 | + globalValueNumber(fc) = globalValueNumber(fctmp.getArgument(i)) |
| 56 | + ) and |
| 57 | + not exists(FunctionCall fctmp | |
| 58 | + fctmp.getTarget().hasGlobalOrStdName("umask") or |
| 59 | + fctmp.getTarget().hasGlobalOrStdName("fchmod") or |
| 60 | + fctmp.getTarget().hasGlobalOrStdName("chmod") |
| 61 | + ) and |
| 62 | + not exists(FunctionCall fctmp | |
| 63 | + fctmp.getTarget().hasGlobalOrStdName("fdopen") and |
| 64 | + fctmp.getNumberOfArguments() = 3 and |
| 65 | + globalValueNumber(fctmp) = globalValueNumber(fc.getArgument(0)) |
| 66 | + ) |
| 67 | +select fc, "You may have forgotten to restrict access rights when working with a file." |
0 commit comments