8000 Fix SSL deadlock risk in libpq · sqlparser/postgres@d6dc44a · GitHub
[go: up one dir, main page]

Skip to content

Commit d6dc44a

Browse files
committed
Fix SSL deadlock risk in libpq
In libpq, we set up and pass to OpenSSL callback routines to handle locking. When we run out of SSL connections, we try to clean things up by de-registering the hooks. Unfortunately, we had a few calls into the OpenSSL library after these hooks were de-registered during SSL cleanup which lead to deadlocking. This moves the thread callback cleanup to be after all SSL-cleanup related OpenSSL library calls. I've been unable to reproduce the deadlock with this fix. In passing, also move the close_SSL call to be after unlocking our ssl_config mutex when in a failure state. While it looks pretty unlikely to be an issue, it could have resulted in deadlocks if we ended up in this code path due to something other than SSL_new failing. Thanks to Heikki for pointing this out. Back-patch to all supported versions; note that the close_SSL issue only goes back to 9.0, so that hunk isn't included in the 8.4 patch. Initially found and reported by Vesa-Matti J Kari; many thanks to both Heikki and Andres for their help running down the specific issue and reviewing the patch.
1 parent 312116e commit d6dc44a

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

src/interfaces/libpq/fe-secure.c

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1430,13 +1430,22 @@ open_client_SSL(PGconn *conn)
14301430
static void
14311431
close_SSL(PGconn *conn)
14321432
{
1433+
bool destroy_needed = false;
1434+
14331435
if (conn->ssl)
14341436
{
14351437
DISABLE_SIGPIPE((void) 0);
1438+
1439+
/*
1440+
* We can't destroy everything SSL-related here due to the possible
1441+
* later calls to OpenSSL routines which may need our thread
1442+
* callbacks, so set a flag here and check at the end.
1443+
*/
1444+
destroy_needed = true;
1445+
14361446
SSL_shutdown(conn->ssl);
14371447
SSL_free(conn->ssl);
14381448
conn->ssl = NULL;
1439-
pqsecure_destroy();
14401449
/* We have to assume we got EPIPE */
14411450
REMEMBER_EPIPE(true);
14421451
RESTORE_SIGPIPE();
@@ -1456,6 +1465,17 @@ close_SSL(PGconn *conn)
14561465
conn->engine = NULL;
14571466
}
14581467
#endif
1468+
1469+
/*
1470+
* This will remove our SSL locking hooks, if this is the last SSL
1471+
* connection, which means we must wait to call it until after all
1472+
* SSL calls have been made, otherwise we can end up with a race
1473+
* condition and possible deadlocks.
1474+
*
1475+
* See comments above destroy_ssl_system().
1476+
*/
1477+
if (destroy_needed)
1478+
pqsecure_destroy();
14591479
}
14601480

14611481
/*

0 commit comments

Comments
 (0)
0