-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRLS-Auto-Enable.sql
More file actions
374 lines (325 loc) · 11.3 KB
/
RLS-Auto-Enable.sql
File metadata and controls
374 lines (325 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
-- Apply Row-Level Security to all tables
-- --------------------------------------
-- This stored procedure automatically generates a security policy that adds a filter predicate
-- on all tables with a specified column name and type. For details and usage examples, see
-- http://blogs.msdn.com/b/sqlsecurity/archive/2015/03/31/apply-row-level-security-to-all-tables-helper-script.aspx
CREATE PROCEDURE dbo.sp_enable_rls_auto (
/* The type for the tenant ID column. It could be short, int or bigint. */
@rlsColType sysname,
/* The name for the tenant ID column. All tables that match the column name & type will be affected. */
@rlsColName sysname,
/* The schema name where the policy will be applied.
If null (default), the policy will be applied to tables in all schemas in the database. */
@applyToSchema sysname = null,
/* Set to 1 to disable all existing policies that affect the identified target tables.
If set to 0 (default), this function will fail if there is an existing policy on any of these tables. */
@deactivateExistingPolicies bit = 0,
/* Schema name for new RLS objects. If it does not exist, it will be created. */
@rlsSchemaName sysname = N'rls',
/* The name of an existing function in the RLS schema that will be used as the predicate.
If null (default), a new function will be created with a simple CONTEXT_INFO = tenant ID filter. */
@rlsPredicateFunctionName sysname = null,
/* Set to 1 to allow CONTEXT_INFO = null to have access to all rows. Default is 0.
Not applicable if @rlsPredicateFunctionName is set with a custom predicate function.
Note that on Azure SQL Database, CONTEXT_INFO is pre-populated with a unique connection GUID (not null),
so you must execute SET CONTEXT_INFO 0x to reset it to null for this 'admin' mode to work. */
@isNullAdmin bit = 0,
/* If @isNullAdmin = 1, set to 1 to optimize the CONTEXT_INFO = null disjunction into a range query.
Not applicable if @rlsPredicateFunctionName is set with a custom predicate function. */
@isNullAdminOptimized bit = 1,
/* If set, the predicate function will allow only this user to access rows.
Use only for middle-tier scenarios, where this is the shared application user name.
Not applicable if @rlsPredicateFunctionName is set with a custom predicate function. */
@restrictedToAppUserName sysname = null,
/* Set to 1 to print the commands (on by default). */
@printCommands bit = 1,
/* Set to 1 to execute the commands (off by default). */
@runCommands bit = 0
)
AS
DECLARE @typeId int
DECLARE @typeLen int
DECLARE @typeMin bigint
DECLARE @typeMax bigint
DECLARE @cmd nvarchar(max)
DECLARE @fnmin sysname
DECLARE @fnmax sysname
DECLARE @rlsPredicateName sysname
IF( @runCommands = 0 AND @printCommands = 0 )
BEGIN
raiserror( 'Invalid arguments. @runCommands = 0 can only be used if @printCommands = 1', 16, 1 )
return
END
SELECT @typeId = system_type_id, @typeLen = max_length FROM sys.types
WHERE name = @rlsColType AND system_type_id in (48, 52, 56, 127)
IF( @typeId is null OR @typeLen is null)
BEGIN
raiserror( 'Error on type. Only integer types are supported', 16, 1 )
return
END
IF( schema_id(@rlsSchemaName) is null )
BEGIN
SET @cmd = N'CREATE SCHEMA ' + quotename(@rlsSchemaName)
IF( @printCommands = 1 )
BEGIN
PRINT @cmd + N'
go';
END
IF( @runCommands = 1 )
EXEC (@cmd)
END
-- #REGION Predicate function defintion
IF( @rlsPredicateFunctionName is null )
BEGIN
-- #REGION Predicate function creation
--------------------------------------------------------
-- The following 2 UDFs are only used for a particular disjunction case (null=admin)
--
IF( @isNullAdminOptimized = 1 AND @isNullAdmin = 1 )
BEGIN
SELECT @typeMax = (convert(bigint, POWER(2.0, (8*@typeLen)-1))-1)
SELECT @typeMin = (convert(bigint, POWER(2.0, (8*@typeLen)-1))*-1)
SET @fnmin = @rlsColType + N'_lo_' + convert(nvarchar(100), getdate(), 127)
SET @cmd = N'CREATE FUNCTION ' + quotename(@rlsSchemaName) + N'.' + quotename(@fnmin) + N'() RETURNS ' + quotename(@rlsColType) + N'
WITH SCHEMABINDING
AS BEGIN
RETURN CASE WHEN context_info() is null THEN
' + convert(nvarchar(256), @typeMin) + N' ELSE
convert(' + quotename(@rlsColType) + N', convert(varbinary(' + convert(nvarchar(256), @typeLen) + N'), context_info())) END
END'
IF( @printCommands = 1 )
BEGIN
PRINT @cmd + N'
go';
END
IF( @runCommands = 1 )
EXEC (@cmd)
SET @fnmax = @rlsColType + N'_hi_' + convert(nvarchar(100), getdate(), 127)
SET @cmd = N'CREATE FUNCTION ' + quotename(@rlsSchemaName) + N'.' + quotename(@fnmax) + N'() RETURNS ' + quotename(@rlsColType) + N'
WITH SCHEMABINDING
AS BEGIN
RETURN CASE WHEN context_info() is null THEN
' + convert(nvarchar(256), @typeMax) + N' ELSE
convert(' + quotename(@rlsColType) + N', convert(varbinary(' + convert(nvarchar(256), @typeLen) + N'), context_info())) END
END'
IF( @printCommands = 1 )
BEGIN
PRINT @cmd + N'
go';
END
IF( @runCommands = 1 )
EXEC (@cmd)
END
-- ENDOF IF( @isNullAdminOptimized = 1 AND @isNullAdmin = 1 )
SET @rlsPredicateName = 'fn_predicate_' + @rlsColName + '_' + convert(nvarchar(100), getdate(), 127)
SET @cmd = N'CREATE FUNCTION ' + quotename(@rlsSchemaName) + N'.' + quotename(@rlsPredicateName)
+ N'(@TenantId ' + quotename(@rlsColType) + N' )
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN SELECT 1 AS fn_accessResult
WHERE ';
IF( @restrictedToAppUserName is not null )
BEGIN
SET @cmd = @cmd + N'
DATABASE_PRINCIPAL_ID() = DATABASE_PRINCIPAL_ID (''' + replace(@restrictedToAppUserName, '''', '''''') + N''') AND (';
END
SET @cmd = @cmd + N'
'
IF( @isNullAdmin = 1 )
BEGIN
IF( @isNullAdminOptimized = 1 )
BEGIN
SET @cmd = @cmd + N'@TenantId BETWEEN ' + quotename(@rlsSchemaName) + N'.' + quotename(@fnmin) + N'() AND ' + quotename(@rlsSchemaName) + N'.' + quotename(@fnmax) + N'()'
END
ELSE
BEGIN
SET @cmd = @cmd + N'CONTEXT_INFO() is null OR'
SET @cmd = @cmd + N'
'
END
END
IF( @isNullAdmin = 0 OR @isNullAdminOptimized = 0 )
BEGIN
SET @cmd = @cmd + N'CONVERT(' + quotename(@rlsColType) + N', CONVERT(varbinary(' + convert(nvarchar(10), @typeLen )+ '), CONTEXT_INFO())) = @TenantId'
END
SET @cmd = @cmd + N'
'
IF( @restrictedToAppUserName is not null )
BEGIN
SET @cmd = @cmd + N')'
END
SET @cmd = @cmd + N'
';
IF( @printCommands = 1 )
BEGIN
PRINT @cmd + N'
go';
END
IF( @runCommands = 1 )
EXEC (@cmd)
-- #ENDREGION Predicate function creation
END
ELSE
BEGIN
IF( (SELECT count(*) FROM sys.objects
WHERE name = @rlsPredicateFunctionName
AND schema_id = schema_id( @rlsSchemaName )
AND type = 'IF') = 0 )
BEGIN
raiserror( 'Error on User Defined function. Could not find a matching predicate function.', 16, 1 )
return
END
SET @rlsPredicateName = @rlsPredicateFunctionName
END
-- #ENDREGION Predicate function defintion
DECLARE @schemaName sysname;
DECLARE @tableName sysname;
DECLARE @columnName sysname;
DECLARE @tableId sysname;
DECLARE cur_columns CURSOR FOR
SELECT objs.object_id, schema_name(objs.schema_id), objs.name, cols.name FROM sys.columns cols, sys.objects objs
WHERE cols.name = @rlsColName AND @typeId = system_type_id
AND cols.object_id = objs.object_id
AND ( @applyToSchema is NULL OR objs.schema_id = schema_id(@applyToSchema) )
ORDER BY objs.schema_id, objs.object_id;
OPEN cur_columns
FETCH NEXT FROM cur_columns INTO @tableId, @schemaName, @tableName, @columnName
DECLARE @rlsPolicyName sysname
SET @rlsPolicyName = N'secpol_' + @rlsColName + '_' + convert(nvarchar(100), getdate(), 127)
SET @cmd = N'CREATE SECURITY POLICY ' + quotename(@rlsSchemaName) + N'.' + quotename(@rlsPolicyName);
DECLARE @AddPredicateTemplate nvarchar(max);
SET @AddPredicateTemplate = N'ADD FILTER PREDICATE ' + quotename(@rlsSchemaName) + N'.'+ quotename(@rlsPredicateName)
DECLARE @errMessage nvarchar(max)
DECLARE @firstTableHit int
DECLARE @errorHit bit
SET @firstTableHit = 0
SET @errorHit = 0
WHILE @errorHit = 0 AND @@FETCH_STATUS = 0
BEGIN
DECLARE @existingPolicy sysname
SET @existingPolicy = null
DECLARE @existingPolicySchema sysname
select @existingPolicy = pols.name, @existingPolicySchema = schema_name(pols.schema_id)
FROM sys.security_policies pols, sys.security_predicates preds
WHERE
preds.target_object_id = @tableId
AND pols.is_enabled = 1
AND preds.object_id = pols.object_id
IF( @existingPolicy is not null )
BEGIN
DECLARE @innerCmd nvarchar(max)
if( @deactivateExistingPolicies = 1 )
BEGIN
SET @innerCmd = 'ALTER SECURITY POLICY ' + quotename(@existingPolicySchema) + N'.' + quotename(@existingPolicy) + N' WITH ( STATE = OFF )'
BEGIN TRY
IF( @printCommands = 1 )
BEGIN
PRINT @innerCmd + N'
go';
END
IF( @runCommands = 1 )
EXEC (@innerCmd)
END TRY
BEGIN CATCH
IF( @printCommands = 1 )
PRINT '---------- LAST COMMAND FAILED -----------'
SET @errMessage = 'Error while altering the existing policy. Error number: ' + convert(nvarchar(100), error_number()) + N' Error Message: ' + error_message()
raiserror( @innerCmd, 16, 1 )
SET @errorHit = 1
SET @errorHit = 1
END CATCH
END
ELSE
BEGIN
SET @innerCmd = 'Error. No table ' + quotename(@schemaName) + '.' + quotename(@tableName)
+ N' has an active policy defined: ' + quotename(@existingPolicySchema) + '.' + quotename(@existingPolicy)
raiserror( @innerCmd, 16, 1 )
SET @errorHit = 1
END
END
IF( @firstTableHit = 0 )
BEGIN
SET @firstTableHit = 1
END
ELSE
BEGIN
SET @cmd = @cmd + N','
END
SET @cmd = @cmd + N'
' + @AddPredicateTemplate + N'(' + quotename(@ColumnName) + ') ON '
+ quotename(@schemaName) + '.' + quotename(@tableName)
FETCH NEXT FROM cur_columns INTO @tableId, @schemaName, @tableName, @columnName
END
CLOSE cur_columns;
DEALLOCATE cur_columns;
SET @cmd = @cmd + N'
';
IF( @errorHit = 0 AND @firstTableHit > 0 )
BEGIN
BEGIN TRY
IF( @printCommands = 1 )
BEGIN
PRINT @cmd + N'
go'
END
IF( @runCommands = 1 )
EXEC (@cmd)
END TRY
BEGIN CATCH
IF( @printCommands = 1 )
PRINT '---------- LAST COMMAND FAILED -----------'
SET @errMessage = 'Error while creating the policy. Error number: ' + convert(nvarchar(100), error_number()) + N' Error Message: ' + error_message()
raiserror( @errMessage, 16, 1 )
SET @errorHit = 1
END CATCH
END
ELSE
BEGIN
raiserror( 'Error. No tables match the criteria', 16, 1 )
return
END
IF( @errorHit != 0 )
BEGIN
-- Roll back
DECLARE @cleanupCmd nvarchar(max)
IF( @rlsPredicateFunctionName is not null )
BEGIN
SET @cleanupCmd = N'BEGIN TRY
DROP FUNCTION ' + quotename(@rlsSchemaName) + N'.' + quotename(@rlsPredicateName) + N';
';
IF( @isNullAdminOptimized = 1 AND @isNullAdmin = 1 )
BEGIN
SET @cleanupCmd = @cleanupCmd + N' DROP FUNCTION ' + quotename(@rlsSchemaName) + N'.' + quotename(@fnmin) + N'
DROP FUNCTION ' + quotename(@rlsSchemaName) + N'.' + quotename(@fnmax) + N'
'
END
SET @cleanupCmd = @cleanupCmd + N'END TRY
BEGIN CATCH
END CATCH;'
IF( @printCommands = 1 )
BEGIN
PRINT '---------- CLEANUP -----------'
PRINT @cleanupCmd + N'
go'
END
IF( @runCommands = 1 )
EXEC (@cleanupCmd)
END
RETURN
END
go
-- example
EXEC sp_enable_rls_auto
@rlsColType = 'int',
@rlsColName = 'TenantId',
@applyToSchema = null,
@deactivateExistingPolicies = 1,
@rlsSchemaName = N'rls',
@rlsPredicateFunctionName = null,
@isNullAdmin = 0,
@isNullAdminOptimized = 0,
@restrictedToAppUserName = 'AppUser',
@printCommands = 1,
@runCommands = 0 -- set to 1 to execute output
go