【问题标题】:How to prevent an impersonated principal from resetting the connection?如何防止模拟主体重置连接?
【发布时间】:2021-11-10 00:50:14
【问题描述】:

我正在构建一个应用程序来连接到使用行级安全性的数据库。

我正在使用 EF Core 进行连接,通过研究我发现,只要在服务器上运行应用程序的用户有权模拟用户,它就可以使用 Execute as login = [user login] 执行查询。

我有一个方法,在我的数据库上下文工厂启动新上下文后调用。

public static void ChangeUser(String sUser, DbContext dbContext)
{
    System.Data.Common.DbConnection dbCon = dbContext.Database.GetDbConnection();
    if (dbCon.State != ConnectionState.Open)
        dbCon.Open();
    string userInDb;
    using (var cmd = dbCon.CreateCommand())
    {
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.Add(new SqlParameter("user", sUser));
        cmd.CommandText = "SELECT SUSER_NAME()";
        userInDb = (string) cmd.ExecuteScalar();
    }
    if (userInDb.ToLower() == sUser.ToLower()) return;
    using (var cmd = dbCon.CreateCommand())
    {
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.Add(new SqlParameter("user", sUser));
        cmd.CommandText = "EXECUTE AS LOGIN = @user;";
        cmd.ExecuteNonQuery();
    }
}

这适用于最初的几次调用,但最终我得到错误:ERROR|Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost|Unhandled exception in circuit 'n1Y3qPEm60j0xxOFc6O83IrFu3jHD7EQI0_zPnO_2RQ'. Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot continue the execution because the session is in the kill state. A severe error occurred on the current command. The results, if any, should be discarded. 并查看 SQL 服务器上的日志,我通过日志获得更多信息:The connection has been dropped because the principal that opened it subsequently assumed a new security context, and then tried to reset the connection under its impersonated security context. This scenario is not supported. See "Impersonation Overview" in Books Online.

在不会导致连接“终止状态”的情况下,如何正确模拟使用 EF 核心的用户?

我认为这是因为 Execute as 被调用了两次,所以我尝试在尝试冒充用户之前添加检查。

【问题讨论】:

  • 您不能在 SQL 服务器上禁止用户模拟吗?
  • SQL server 有行级限制。我正在尝试对其进行设置,以便我的中间件用户(运行应用程序池的用户)可以使用中间件(Intranet web api)模拟经过身份验证的用户

标签: c# entity-framework-core impersonation


【解决方案1】:

EXECUTE AS 的WITH COOKIE INTO ... 形式可以用来避免“Cannot continue the execution because the session is in the kill state”错误,建议通过REVERTing来防止用户打开安全漏洞。

Official EXECUTE AS docs

更进一步,这里是我用来简化和可预测的实用程序,以及一些使用示例。

这里有龙:对让用户跨越安全边界的代码要格外小心和深思熟虑。请特别注意 user 参数的来源,您传递到这些 ExecuteAs... 扩展方法中。如果用户或对手能够操纵该字符串,他们可以通过两种方式滥用这些 ExecuteAs 扩展方法:

  1. 显然,他们可以提供不同的、提升的用户,然后执行的任何 SQL 都将在比您预期的更强大的用户的权限下。
  2. 他们可以注入任意 SQL,因为这种形式的 EXECUTE AS 只能在临时上下文中运行。用户名不能参数化。

最后,您可以EXECUTE AS LOGIN ... 或EXECUTE AS USER ...。这些扩展方法是后者。

// Usage examples

async void Main()
{
    // These two will work because the user from the connection string can SELECT anything.
    Groups.ToList();
    PaymentRecords.ToList();

    //using (var executeAsScope = await (DbContext.Database.GetDbConnection() as SqlConnection).ExecuteAsUserAsync("morePrivilegedUser'; PRINT 'do something malicious'; REVERT; EXECUTE AS USER = 'lessPrivilegedUser"))
    //using (var executeAsScope = await (DbContext.Database.GetDbConnection() as SqlConnection).ExecuteAsUserAsync("morePrivilegedUser"))
    using (var executeAsScope = await (DbContext.Database.GetDbConnection() as SqlConnection).ExecuteAsUserAsync("lessPrivilegedUser"))
    {
        // This will succeed because "lessPrivilegedUser" can SELECT the Groups table.
        Groups.ToList();
        // This will throw an exception because "lessPrivilegedUser" does not have permission to SELECT the PaymentRecords table.
        PaymentRecords.ToList();
        // This will fail because @cookie does not exist.
        Database.ExecuteSqlRaw("REVERT WITH COOKIE = @cookie;");
    }

    // This would succeed because we've exited the "lessPrivilegedUser" execute as scope and we are back to the user determined by the connection string.
    PaymentRecords.ToList();

    // Similarly you can work with transactions using the other extension method
    using (var sqlTransaction = await DbContext.Database.GetDbConnection().BeginTransactionAsync() as SqlTransaction)
    using (var dbContextTransaction = await DbContext.Database.UseTransactionAsync(sqlTransaction))
    using (var executeAsScope = await sqlTransaction.ExecuteAsUserAsync("lessPrivilegedUser"))
    {
        // This will succeed because "lessPrivilegedUser" can SELECT the Groups table.
        Groups.ToList();
        // This will fail because "lessPrivilegedUser" does not have permission to SELECT the PaymentRecords table.
        PaymentRecords.ToList();
        // This will fail because @cookie does not exist.
        Database.ExecuteSqlRaw("REVERT WITH COOKIE = @cookie;");
    }
}

// Utilities

public static class ExecuteAsExtensions
{
    public static async Task<IDisposable> ExecuteAsUserAsync(this SqlConnection connection, string user)
    {
        byte[] cookie;
        using (var cmd = connection.CreateCommand())
        {
            cmd.CommandText = $@"DECLARE @cookie VARBINARY(100); EXECUTE AS USER = '{user}' WITH COOKIE INTO @cookie; SELECT @cookie; SET @cookie = 0;";
            await connection.OpenAsync();
            cookie = (byte[])await cmd.ExecuteScalarAsync();
        }

        return new ExecuteAsScope(cookie, connection, transaction: null);
    }

    public static async Task<IDisposable> ExecuteAsUserAsync(this SqlTransaction transaction, string user)
    {
        byte[] cookie;
        using (var cmd = transaction.Connection.CreateCommand())
        {
            cmd.Transaction = transaction;
            cmd.CommandText = $@"DECLARE @cookie VARBINARY(100); EXECUTE AS USER = '{user}'  WITH COOKIE INTO @cookie; SELECT @cookie; SET @cookie = 0;";
            cookie = (byte[])await cmd.ExecuteScalarAsync();
        }

        return new ExecuteAsScope(cookie, transaction.Connection, transaction);
    }
}

public class ExecuteAsScope : IDisposable
{

    private byte[] cookie;
    private SqlConnection connection;
    private SqlTransaction transaction;

    public ExecuteAsScope(byte[] cookie, SqlConnection connection, SqlTransaction transaction)
    {
        this.cookie = cookie;
        this.connection = connection;
        this.transaction = transaction;
    }

    #region IDisposable Support
    private bool disposedValue = false;
    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                using (var cmd = connection.CreateCommand())
                {
                    cmd.Transaction = transaction;
                    cmd.CommandText = $@"REVERT WITH COOKIE = @cookie";
                    cmd.Parameters.AddWithValue("@cookie", cookie);
                    cmd.ExecuteNonQuery();
                }
                transaction = null;
                connection = null;
            }

            disposedValue = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
    }
    #endregion
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-06
    • 2013-01-26
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 2014-02-28
    相关资源
    最近更新 更多