|
| 1 | +#!/usr/bin/env python |
| 2 | +# |
| 3 | +# Glances - An eye on your system |
| 4 | +# |
| 5 | +# SPDX-FileCopyrightText: 2025 Nicolas Hennion <nicolas@nicolargo.com> |
| 6 | +# |
| 7 | +# SPDX-License-Identifier: LGPL-3.0-only |
| 8 | +# |
| 9 | + |
| 10 | +"""Glances unit tests for DuckDB export SQL injection prevention. |
| 11 | +
|
| 12 | +Tests cover: |
| 13 | +- _quote_identifier properly escapes SQL identifiers |
| 14 | +- CREATE TABLE and INSERT INTO use quoted identifiers |
| 15 | +- SQL injection via crafted column names is prevented |
| 16 | +- SQL injection via crafted table names is prevented |
| 17 | +- Normal export workflow still works with quoting |
| 18 | +""" |
| 19 | + |
| 20 | +import pytest |
| 21 | + |
| 22 | +try: |
| 23 | + import duckdb |
| 24 | +except ImportError: |
| 25 | + pytest.skip("duckdb not installed", allow_module_level=True) |
| 26 | + |
| 27 | +from glances.exports.glances_duckdb import _quote_identifier |
| 28 | + |
| 29 | +# --------------------------------------------------------------------------- |
| 30 | +# Tests – _quote_identifier |
| 31 | +# --------------------------------------------------------------------------- |
| 32 | + |
| 33 | + |
| 34 | +class TestQuoteIdentifier: |
| 35 | + """Unit tests for the _quote_identifier helper.""" |
| 36 | + |
| 37 | + def test_simple_name(self): |
| 38 | + assert _quote_identifier('cpu_percent') == '"cpu_percent"' |
| 39 | + |
| 40 | + def test_name_with_spaces(self): |
| 41 | + assert _quote_identifier('my column') == '"my column"' |
| 42 | + |
| 43 | + def test_name_with_double_quote(self): |
| 44 | + """Embedded double quotes must be doubled.""" |
| 45 | + assert _quote_identifier('col"name') == '"col""name"' |
| 46 | + |
| 47 | + def test_name_with_multiple_double_quotes(self): |
| 48 | + assert _quote_identifier('a"b"c') == '"a""b""c"' |
| 49 | + |
| 50 | + def test_sql_injection_attempt(self): |
| 51 | + """SQL metacharacters must be safely quoted.""" |
| 52 | + malicious = 'cpu); DROP TABLE secrets; --' |
| 53 | + quoted = _quote_identifier(malicious) |
| 54 | + assert quoted == '"cpu); DROP TABLE secrets; --"' |
| 55 | + |
| 56 | + def test_empty_string(self): |
| 57 | + assert _quote_identifier('') == '""' |
| 58 | + |
| 59 | + def test_non_string_input(self): |
| 60 | + """Non-string input should be converted to string.""" |
| 61 | + assert _quote_identifier(42) == '"42"' |
| 62 | + |
| 63 | + def test_name_with_semicolon(self): |
| 64 | + assert _quote_identifier('col;name') == '"col;name"' |
| 65 | + |
| 66 | + def test_name_with_parentheses(self): |
| 67 | + assert _quote_identifier('col(name)') == '"col(name)"' |
| 68 | + |
| 69 | + |
| 70 | +# --------------------------------------------------------------------------- |
| 71 | +# Tests – SQL injection prevention with real DuckDB |
| 72 | +# --------------------------------------------------------------------------- |
| 73 | + |
| 74 | + |
| 75 | +class TestDuckDBInjectionPrevention: |
| 76 | + """Verify that quoted identifiers prevent SQL injection in real DuckDB.""" |
| 77 | + |
| 78 | + @pytest.fixture |
| 79 | + def db(self): |
| 80 | + """Create an in-memory DuckDB connection.""" |
| 81 | + conn = duckdb.connect(':memory:') |
| 82 | + yield conn |
| 83 | + conn.close() |
| 84 | + |
| 85 | + def test_create_table_with_safe_names(self, db): |
| 86 | + """Normal table and column creation works with quoting.""" |
| 87 | + table = _quote_identifier('cpu') |
| 88 | + col1 = _quote_identifier('time') |
| 89 | + col2 = _quote_identifier('cpu_percent') |
| 90 | + db.execute(f'CREATE TABLE {table} ({col1} VARCHAR, {col2} DOUBLE);') |
| 91 | + db.execute(f'INSERT INTO {table} VALUES (?, ?);', ['2024-01-01', 95.5]) |
| 92 | + result = db.execute(f'SELECT * FROM {table}').fetchall() |
| 93 | + assert len(result) == 1 |
| 94 | + assert result[0] == ('2024-01-01', 95.5) |
| 95 | + |
| 96 | + def test_create_table_with_special_column_names(self, db): |
| 97 | + """Column names with special characters are properly handled.""" |
| 98 | + table = _quote_identifier('test_plugin') |
| 99 | + col_special = _quote_identifier('my column with spaces') |
| 100 | + db.execute(f'CREATE TABLE {table} ({col_special} VARCHAR);') |
| 101 | + db.execute(f'INSERT INTO {table} VALUES (?);', ['value']) |
| 102 | + result = db.execute(f'SELECT * FROM {table}').fetchall() |
| 103 | + assert result[0] == ('value',) |
| 104 | + |
| 105 | + def test_injection_in_column_name_is_neutralized(self, db): |
| 106 | + """A malicious column name must not execute injected SQL.""" |
| 107 | + # Create a target table that the injection would try to drop |
| 108 | + db.execute('CREATE TABLE secrets (data VARCHAR);') |
| 109 | + db.execute("INSERT INTO secrets VALUES ('sensitive');") |
| 110 | + |
| 111 | + # Attempt injection via column name |
| 112 | + malicious_col = 'cpu BIGINT); DROP TABLE secrets; --' |
| 113 | + safe_col = _quote_identifier(malicious_col) |
| 114 | + table = _quote_identifier('test_inject') |
| 115 | + |
| 116 | + # This should create a table with a weird column name, NOT drop secrets |
| 117 | + db.execute(f'CREATE TABLE {table} ({safe_col} VARCHAR);') |
| 118 | + |
| 119 | + # Verify secrets table still exists and has data |
| 120 | + result = db.execute('SELECT * FROM secrets').fetchall() |
| 121 | + assert result == [('sensitive',)] |
| 122 | + |
| 123 | + def test_injection_in_table_name_is_neutralized(self, db): |
| 124 | + """A malicious table name must not execute injected SQL.""" |
| 125 | + db.execute('CREATE TABLE important (data VARCHAR);') |
| 126 | + db.execute("INSERT INTO important VALUES ('keep');") |
| 127 | + |
| 128 | + malicious_table = 'x (a INT); DROP TABLE important; --' |
| 129 | + safe_table = _quote_identifier(malicious_table) |
| 130 | + db.execute(f'CREATE TABLE {safe_table} (col1 VARCHAR);') |
| 131 | + |
| 132 | + # important table must still exist |
| 133 | + result = db.execute('SELECT * FROM important').fetchall() |
| 134 | + assert result == [('keep',)] |
| 135 | + |
| 136 | + def test_insert_with_quoted_table(self, db): |
| 137 | + """INSERT INTO with quoted table name works correctly.""" |
| 138 | + table = _quote_identifier('my-plugin') |
| 139 | + db.execute(f'CREATE TABLE {table} ({_quote_identifier("val")} BIGINT);') |
| 140 | + db.execute(f'INSERT INTO {table} VALUES (?);', [42]) |
| 141 | + result = db.execute(f'SELECT * FROM {table}').fetchall() |
| 142 | + assert result == [(42,)] |
| 143 | + |
| 144 | + def test_full_export_simulation(self, db): |
| 145 | + """Simulate a full Glances DuckDB export cycle with quoting.""" |
| 146 | + plugin = 'cpu' |
| 147 | + stats = { |
| 148 | + 'total': 85.5, |
| 149 | + 'user': 60.0, |
| 150 | + 'system': 25.5, |
| 151 | + 'idle': 14.5, |
| 152 | + } |
| 153 | + convert_types = { |
| 154 | + 'float': 'DOUBLE', |
| 155 | + 'int': 'BIGINT', |
| 156 | + 'str': 'VARCHAR', |
| 157 | + } |
| 158 | + |
| 159 | + # Build creation_list as the real code does |
| 160 | + creation_list = [ |
| 161 | + f'{_quote_identifier("time")} VARCHAR', |
| 162 | + f'{_quote_identifier("hostname_id")} VARCHAR', |
| 163 | + ] |
| 164 | + for key, value in stats.items(): |
| 165 | + creation_list.append(f'{_quote_identifier(key)} {convert_types[type(value).__name__]}') |
| 166 | + |
| 167 | + # CREATE TABLE |
| 168 | + quoted_plugin = _quote_identifier(plugin) |
| 169 | + create_query = f'CREATE TABLE {quoted_plugin} ({", ".join(creation_list)});' |
| 170 | + db.execute(create_query) |
| 171 | + |
| 172 | + # INSERT |
| 173 | + values = ['2024-01-01T00:00:00', 'myhost'] + list(stats.values()) |
| 174 | + placeholders = ', '.join(['?' for _ in values]) |
| 175 | + insert_query = f'INSERT INTO {quoted_plugin} VALUES ({placeholders});' |
| 176 | + db.execute(insert_query, values) |
| 177 | + |
| 178 | + # Verify |
| 179 | + result = db.execute(f'SELECT * FROM {quoted_plugin}').fetchall() |
| 180 | + assert len(result) == 1 |
| 181 | + assert result[0][0] == '2024-01-01T00:00:00' |
| 182 | + assert result[0][1] == 'myhost' |
| 183 | + assert result[0][2] == 85.5 |
| 184 | + |
| 185 | + def test_column_with_double_quote_in_name(self, db): |
| 186 | + """Column name containing double quotes is properly escaped.""" |
| 187 | + table = _quote_identifier('test') |
| 188 | + col = _quote_identifier('col"with"quotes') |
| 189 | + db.execute(f'CREATE TABLE {table} ({col} VARCHAR);') |
| 190 | + db.execute(f'INSERT INTO {table} VALUES (?);', ['value']) |
| 191 | + result = db.execute(f'SELECT * FROM {table}').fetchall() |
| 192 | + assert result == [('value',)] |
0 commit comments