Skip to content

Commit

Permalink
Fix: Avoid deadlocks while refreshing authentication
Browse files Browse the repository at this point in the history
use a transaction and FOR UPDATE during selection to lock the row
being updated to reduce likelihood of a deadlock.
  • Loading branch information
a-h-abdelsalam committed Apr 25, 2024
1 parent a396997 commit 4574c9e
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions src/manage_sql.c
Original file line number Diff line number Diff line change
Expand Up @@ -17436,7 +17436,8 @@ auth_cache_find (const char *username, const char *password, int method)

quoted_username = sql_quote (username);
hash = sql_string ("SELECT hash FROM auth_cache WHERE username = '%s'"
" AND method = %i AND creation_time >= m_now () - %d;",
" AND method = %i AND creation_time >= m_now () - %d"
" FOR UPDATE;",
quoted_username, method, get_auth_timeout()*60);
g_free (quoted_username);
if (!hash)
Expand Down Expand Up @@ -17526,6 +17527,7 @@ authenticate_any_method (const gchar *username, const gchar *password,
int ret;
gchar *hash;

sql_begin_immediate ();
if (gvm_auth_ldap_enabled ()
&& ldap_auth_enabled ()
&& user_exists_method (username, AUTHENTICATION_METHOD_LDAP_CONNECT))
Expand All @@ -17539,6 +17541,7 @@ authenticate_any_method (const gchar *username, const gchar *password,
if (auth_cache_find (username, password, 0) == 0)
{
auth_cache_refresh (username);
sql_commit ();
return 0;
}

Expand All @@ -17552,7 +17555,14 @@ authenticate_any_method (const gchar *username, const gchar *password,
free (cacert);

if (ret == 0)
auth_cache_insert (username, password, 0);
{
auth_cache_insert (username, password, 0);
sql_commit ();
}
else
{
sql_rollback ();
}
return ret;
}
if (gvm_auth_radius_enabled ()
Expand All @@ -17565,6 +17575,7 @@ authenticate_any_method (const gchar *username, const gchar *password,
if (auth_cache_find (username, password, 1) == 0)
{
auth_cache_refresh (username);
sql_commit ();
return 0;
}

Expand All @@ -17573,13 +17584,21 @@ authenticate_any_method (const gchar *username, const gchar *password,
g_free (host);
g_free (key);
if (ret == 0)
auth_cache_insert (username, password, 1);
{
auth_cache_insert (username, password, 1);
sql_commit ();
}
else
{
sql_rollback ();
}
return ret;
}
*auth_method = AUTHENTICATION_METHOD_FILE;
if (auth_cache_find (username, password, 2) == 0)
{
auth_cache_refresh (username);
sql_commit ();
return 0;
}
hash = manage_user_hash (username);
Expand All @@ -17605,6 +17624,10 @@ authenticate_any_method (const gchar *username, const gchar *password,
break;
}

if (ret)
sql_rollback ();
else
sql_commit ();

g_free (hash);
return ret;
Expand Down

0 comments on commit 4574c9e

Please sign in to comment.