0

我正在使用SQL Server 2005/2008,我有一個存儲過程不使用字符串連接來生成EXEC語句,但它確實使用存儲過程的動態名稱。沒有字符串連接的存儲過程SQL注入漏洞

我認爲@stored_procedure_name和潛在的@object_name參數都是脆弱的。但是,我所讀到的所有動態SQL鏈接都假設你在一個字符串內連接了你的SQL語句 - 所以我想知道它是否真的可以。

請注意,只是爲了發表這個,我已經通過調用表對象使代碼泛化 - 所以它可能不一定合乎邏輯。

下面是代碼:

CREATE PROCEDURE [dbo].[my_dodgy_sp] 
    @object_name varchar(50) = 'All' 
AS 
BEGIN 
    DECLARE @stored_procedure_name varchar(100); 

    DECLARE object_cursor CURSOR FOR 
     SELECT stored_procedure_name 
     FROM [dbo].[objects] 
     WHERE [stored_procedure_name] <> '' 
     AND ([name] = @object_name) 

    OPEN object_cursor 

    FETCH NEXT FROM object_cursor 
     INTO @stored_procedure_name 

    WHILE @@FETCH_STATUS = 0 
     BEGIN 

      EXEC @stored_procedure_name @object_id OUTPUT; 

      FETCH NEXT FROM object_cursor 
       INTO @stored_procedure_name 
     END 

    CLOSE object_cursor; 
    DEALLOCATE object_cursor; 
END 

回答

1

試試這個:

CREATE PROCEDURE [dbo].[my_dodgy_sp] 
    @object_name varchar(50) = 'All' 
AS 
BEGIN 
    DECLARE @stored_procedure_name sysname, @oID INT, @sql NVARCHAR(MAX), @object_id int; 

    DECLARE object_cursor CURSOR FOR 
     SELECT object_id, name 
     FROM sys.procedures 
     WHERE [name] = @object_name 

    OPEN object_cursor 

    FETCH NEXT FROM object_cursor 
     INTO @oID, @stored_procedure_name 

    WHILE @@FETCH_STATUS = 0 
     BEGIN 
      SET @sql = N'EXEC ['+OBJECT_SCHEMA_NAME(@oid)+N'].['[email protected]_procedure_name+N'] @Object_id OUTPUT' 
      EXEC sp_executesql @sql, N'@object_id int OUTPUT', @ObjectId [email protected]_id OUTPUT 

      PRINT @object_id -- we need to do smth with it? 

      FETCH NEXT FROM object_cursor 
       INTO @oID, @stored_procedure_name 
     END 

    CLOSE object_cursor; 
    DEALLOCATE object_cursor; 
END 

,而不是使用這種複雜的方式,可能是你只需要調用參數化的過程?