USE [master]GO/****** Object: StoredProcedure [dbo].[usp_who] Script Date: 03/14/2013 14:57:25 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO-- =============================-- Author: -- Created: 03/14/13-- Desc: sp_who for users-- =============================CREATE PROCEDURE [usp_who] @who INT = @@spidwith execute as selfASBEGINSET NOCOUNT ON;exec sp_who @who;END
-- Script by Vedran Kesegic, 20.3.2013.-- We will create a database and a procedure which calls sp_who2.-- We will also create a low-privileged login and give him exec permission on that procedure.create database TestCertcreate login LowPriv with password='Str0ngPWD!'GOuse TestCertcreate user LowPriv for login LowPrivGOcreate procedure dbo.show_processes --with execute as 'dbo' -- even this wont help, because dbo is db user and can receive only privileges at db level, not server levelasbegin select * from sys.login_token -- who am i select * from sys.fn_my_permissions(null,'server') -- what server rights do i have exec sys.sp_who2endGOgrant exec on dbo.show_processes to LowPrivGOexecute as login='LowPriv'exec sys.sp_who2 -- shows only my session, not goodexec dbo.show_processes -- shows only my session, not goodrevertGO-- Create login to which we will grant view server state. Login will be mapped to certificate.-- Sign procedure with that certificate - meaning procedure will execute under that high-priv login.-- certificate must be in master database in order to be mapped to loginuse master -- create certificate in master databasecreate certificate HighPrivCert ENCRYPTION BY PASSWORD = 'Str0ngPWD!'WITH SUBJECT = 'Certificate for signing stored procedures'select * from sys.certificatesGOcreate login HighPrivCertLogin from certificate HighPrivCert -- create high priv logingrant view server state to HighPrivCertLoginGO-- in order to grant db user rights, we must transfer to that db the same certificatebackup certificate HighPrivCert to file='C:\temp\HighPrivCert.CER'WITH PRIVATE KEY( FILE = 'C:\temp\HighPrivCert.PVK', DECRYPTION BY PASSWORD = 'Str0ngPWD!', -- pwd to open the key ENCRYPTION BY PASSWORD = 'FilePWD!1' -- must protect the file)GOuse TestCertcreate certificate HighPrivCert from file='C:\temp\HighPrivCert.CER'WITH PRIVATE KEY( FILE = 'C:\temp\HighPrivCert.PVK', DECRYPTION BY PASSWORD = 'FilePWD!1', -- to read the file ENCRYPTION BY PASSWORD = 'Str0ngPWD!' -- pwd to protect the key)select * from sys.certificates-- Manually delete cert files NOW!GO-- by signing procedure, it will run under login associated with that certificateADD SIGNATURE TO OBJECT::dbo.show_processesBY CERTIFICATE HighPrivCertWITH PASSWORD='Str0ngPWD!'GOexecute as login='LowPriv'exec sys.sp_who2 -- shows only my sessionexec dbo.show_processes -- shows all sessions! We are running under HighPrivCertLogin which have VIEW SERVER STATE permission.revertGO-- CLEANUP/*use masterdrop database TestCertdrop login HighPrivCertLogindrop certificate HighPrivCertdrop login LowPriv*/