[Fix] Correzione controllo sicurezza query SQL: uso regex con word boundary per evitare falsi positivi su nomi colonna (es. UpdateDate, CreateDate) e gestione corretta dei prefissi sp_/xp_

This commit is contained in:
Alessio Dal Santo
2026-03-30 16:40:39 +02:00
parent f1f75d59ac
commit e43b7dc869
+23 -6
View File
@@ -2894,25 +2894,42 @@ public partial class DataCoupler : ComponentBase
if (!trimmedQuery.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
return false;
// Lista di parole chiave vietate per sicurezza
var forbiddenKeywords = new[]
// Parole chiave complete: devono essere token SQL isolati (\bKEYWORD\b)
// Evita falsi positivi su nomi di colonne come UpdateDate, CreateDate, DeletedAt, ecc.
var forbiddenFullKeywords = new[]
{
"INSERT", "UPDATE", "DELETE", "DROP", "CREATE", "ALTER", "TRUNCATE",
"EXEC", "EXECUTE", "sp_", "xp_", "BULK", "OPENROWSET", "OPENDATASOURCE"
"EXEC", "EXECUTE", "BULK", "OPENROWSET", "OPENDATASOURCE"
};
// Prefissi pericolosi: devono iniziare la parola (sp_anything, xp_anything)
// Non si usa \bprefix\b perché _ è un word-char e mancherebbe sp_executesql, xp_cmdshell, ecc.
var forbiddenPrefixes = new[] { "SP_", "XP_" };
var upperQuery = trimmedQuery.ToUpperInvariant();
// Verifica che non contenga parole chiave vietate
foreach (var keyword in forbiddenKeywords)
// Verifica parole chiave complete con word boundary
foreach (var keyword in forbiddenFullKeywords)
{
if (upperQuery.Contains(keyword))
var pattern = $@"\b{System.Text.RegularExpressions.Regex.Escape(keyword)}\b";
if (System.Text.RegularExpressions.Regex.IsMatch(upperQuery, pattern))
{
Logger.LogWarning("Query rifiutata: contiene parola chiave vietata '{Keyword}'", keyword);
return false;
}
}
// Verifica prefissi stored procedure: \bSP_ cattura sp_anything, xp_anything
foreach (var prefix in forbiddenPrefixes)
{
var pattern = $@"\b{System.Text.RegularExpressions.Regex.Escape(prefix)}";
if (System.Text.RegularExpressions.Regex.IsMatch(upperQuery, pattern))
{
Logger.LogWarning("Query rifiutata: contiene prefisso stored procedure vietato '{Prefix}'", prefix);
return false;
}
}
return true;
}