Search code examples
c#sqlitesandbox

Run SQLite in sandboxed environment


My goal is to allow SQLite access from a sandboxed Lua environment. But in the example below, it is still possible to use attach database (and probably more unwanted actions). Is there a way to run SQLite queries in a sandboxed environment on a predefined SQLite file

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");

m_dbConnection.Flags = SQLiteConnectionFlags.Default | SQLiteConnectionFlags.NoBindFunctions |
                        SQLiteConnectionFlags.NoConnectionPool | SQLiteConnectionFlags.NoCreateModule |
                        SQLiteConnectionFlags.NoLoadExtension | SQLiteConnectionFlags.NoExtensionFunctions;

m_dbConnection.Open();

string sql = "attach database 'contacts.db' as contacts;";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);

command.ExecuteNonQuery();

m_dbConnection.Close();

Solution

  • If you create the connection, SQLiteConnection has an Authorize event, which you can use to prevent databases from being attached:

    SQLiteConnection conn = new SQLiteConnection("Data Source=:memory:");
    conn.Authorize += Conn_Authorize;
    
    ...
    
    private static void Conn_Authorize(object sender, AuthorizerEventArgs e)
    {
        if (e.ActionCode == SQLiteAuthorizerActionCode.Attach)
        {
            e.ReturnCode = SQLiteAuthorizerReturnCode.Deny;
        }
        else
        {
            e.ReturnCode = SQLiteAuthorizerReturnCode.Ok;
        }
    }