Skip to content

Commit 1747ded

Browse files
committed
Fix UAF for statement_cache self->connection->statement_cache in
`sqllite` This protects against a UAF from an execute and clear in two thrads in a FT build and closing on `execute` which can execute arbituary python code before the execution (impacting GIL build too).
1 parent 441c010 commit 1747ded

5 files changed

Lines changed: 86 additions & 5 deletions

File tree

‎Lib/test/test_free_threading/test_sqlite3.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import threading
12
import unittest
23

34
from test import support
@@ -49,6 +50,55 @@ def mutator():
4950
with support.swap_item(sqlite3.converters, NAME, Converter(0)):
5051
run_concurrently([reader] * 8 + [mutator] * 2)
5152

53+
def test_close_during_statement_cache_lookup(self):
54+
# execute() must load the statement cache under the connection lock,
55+
# since close() on another thread clears it. Params.__iter__ runs
56+
# after execute() has checked the connection and before it loads the
57+
# cache, so the handshake orders only the checks before close().
58+
class Stop(Exception):
59+
pass
60+
61+
class SQL(str):
62+
# Raise at the cache lookup, before SQLite is used.
63+
def __hash__(self):
64+
raise Stop
65+
66+
def run():
67+
cx = sqlite3.connect(":memory:", check_same_thread=False)
68+
cu = cx.cursor()
69+
close = cx.close
70+
ready = threading.Lock()
71+
ready.acquire()
72+
raised = []
73+
74+
class Params:
75+
def __iter__(self):
76+
ready.release()
77+
return iter(())
78+
79+
def reader():
80+
try:
81+
cu.executemany(SQL("select 1"), Params())
82+
except Exception as exc:
83+
raised.append(exc)
84+
85+
t = threading.Thread(target=reader)
86+
t.start()
87+
try:
88+
# Ensure we don't close too early before other thread
89+
# has got past check_cursor()
90+
self.assertTrue(ready.acquire(timeout=support.SHORT_TIMEOUT))
91+
close()
92+
finally:
93+
t.join()
94+
self.assertEqual(len(raised), 1)
95+
self.assertIsInstance(raised[0], (Stop, sqlite3.ProgrammingError))
96+
97+
# A GC pause between the two threads would also order them.
98+
with support.disable_gc():
99+
for _ in range(5):
100+
run()
101+
52102

53103
if __name__ == "__main__":
54104
unittest.main()

‎Lib/test/test_sqlite3/test_regression.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,18 @@ def foo():
277277
cur.executemany("insert into b (baz) values (?)",
278278
((i,) for i in foo()))
279279

280+
def test_close_during_statement_cache_lookup(self):
281+
# The statement cache hashes the SQL string, which can run Python
282+
# code. Closing the connection there must not crash.
283+
with memory_database() as con:
284+
class SQL(str):
285+
def __hash__(self):
286+
con.close()
287+
return super().__hash__()
288+
289+
with self.assertRaises(sqlite.ProgrammingError):
290+
con.execute(SQL("select 1"))
291+
280292
def test_convert_timestamp_microsecond_padding(self):
281293
"""
282294
http://bugs.python.org/issue14720
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Fix a crash in :mod:`sqlite3` when the connection is closed while
2+
:meth:`~sqlite3.Cursor.execute` or :meth:`~sqlite3.Cursor.executemany` is
3+
looking up the prepared statement, for example from the
4+
:meth:`~object.__hash__` of a :class:`str` subclass or from another thread.
5+
A :exc:`~sqlite3.ProgrammingError` is now raised instead.

‎Modules/_sqlite/connection.c‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,8 @@ pysqlite_connection_init_impl(pysqlite_Connection *self, PyObject *database,
303303
self->autocommit = autocommit;
304304
self->check_same_thread = check_same_thread;
305305
self->thread_ident = PyThread_get_thread_ident();
306-
self->statement_cache = statement_cache;
306+
pysqlite_set_ref((PyObject *)self, &self->statement_cache,
307+
statement_cache);
307308
self->blobs = blobs;
308309
pysqlite_set_ref((PyObject *)self, &self->row_factory, Py_NewRef(Py_None));
309310
pysqlite_set_ref((PyObject *)self, &self->text_factory,
@@ -410,7 +411,7 @@ static int
410411
connection_clear(PyObject *op)
411412
{
412413
pysqlite_Connection *self = _pysqlite_Connection_CAST(op);
413-
Py_CLEAR(self->statement_cache);
414+
pysqlite_set_ref(op, &self->statement_cache, NULL);
414415
Py_CLEAR(self->blobs);
415416
pysqlite_set_ref(op, &self->row_factory, NULL);
416417
pysqlite_set_ref(op, &self->text_factory, NULL);
@@ -709,7 +710,7 @@ pysqlite_connection_close_impl(pysqlite_Connection *self)
709710
}
710711

711712
pysqlite_close_all_blobs(self);
712-
Py_CLEAR(self->statement_cache);
713+
pysqlite_set_ref((PyObject *)self, &self->statement_cache, NULL);
713714
if (connection_close(self) < 0) {
714715
return NULL;
715716
}

‎Modules/_sqlite/cursor.c‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -536,9 +536,22 @@ static PyObject *
536536
get_statement_from_cache(pysqlite_Cursor *self, PyObject *operation)
537537
{
538538
PyObject *args[] = { NULL, operation, }; // Borrowed ref.
539-
PyObject *cache = self->connection->statement_cache;
539+
// Hold a strong reference: the call may run Python code (e.g. a str
540+
// subclass __hash__) or let another thread run, and either may close
541+
// the connection and clear the cache.
542+
PyObject *cache;
543+
Py_BEGIN_CRITICAL_SECTION(self->connection);
544+
cache = Py_XNewRef(self->connection->statement_cache);
545+
Py_END_CRITICAL_SECTION();
546+
if (cache == NULL) {
547+
PyErr_SetString(self->connection->state->ProgrammingError,
548+
"Cannot operate on a closed database.");
549+
return NULL;
550+
}
540551
size_t nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
541-
return PyObject_Vectorcall(cache, args + 1, nargsf, NULL);
552+
PyObject *stmt = PyObject_Vectorcall(cache, args + 1, nargsf, NULL);
553+
Py_DECREF(cache);
554+
return stmt;
542555
}
543556

544557
static inline int

0 commit comments

Comments
 (0)