Nielsen c50.tex V4 - 07/21/2009 3:26pm Page 1192 Part VII Security Object security and Management Studio Object permissions, because they involve users, roles, and objects, can be set from numerous places within Management Studio. It’s almost a maze. From the object list Follow these steps to modify an object’s permissions: 1. From an object node (tables, views, stored procedures, or user-defined functions) in the Object Browser, select Properties from the context menu to open the Properties dialog for that object type. 2. Click the Permissions page to open the Object Properties dialog. The top portion of the form is for selecting a user or role to assign or check permissions. The user must have access to the database to be selected. As with setting statement permissions in the Database Properties Security tab, you can select grant, with grant, or deny. The object list at the top of the dialog lists all the objects in the database. This list can be used to quickly switch to other objects without backing out of the form to the console and selecting a different object. If the user or role has permission to the table, the Columns button opens the Column Permissions dialog. Select the user and then click the button to set the columns permission for that user. Only select and update permissions can be set at the column level, because inserts and deletes affect the entire row. From the user list From the list of database users in Management Studio, select a user and double-click, or select Prop- erties from the right-click context menu. The Database User Properties dialog is used to assign users to roles. Clicking the Properties button will open the properties of the selected role. In the Database User Properties dialog, the Securables page is used to assign or check object permis- sions. This dialog is similar to the Permissions tab of the Database Object Properties dialog. From the role list The third way to control object permissions is from the database role. To open the Database Role Properties dialog, double-click a role in the list of roles, or select Properties from the right-click context menu. The Database Role Properties dialog can be used to assign users or other roles to the role, and to remove them from the role. The Permissions button opens the permissions dialog for the role. This form operates like the other per- mission forms except that it is organized from the role’s perspective. 1192 www.getcoolebook.com Nielsen c50.tex V4 - 07/21/2009 3:26pm Page 1193 Authorizing Securables 50 Ownership chains In SQL Server databases, users often access data by going through one or several objects. Ownership chains apply to views, stored procedures, and user-defined functions. For example: ■ A program might call a stored procedure that then selects data from a table. ■ A report might select from a view, which then selects from a table. ■ A complex stored procedure might call several other stored procedures. In these cases, the user must have permission to execute the stored procedure or select from the view. Whether the user also needs permission to select from the underlying tables depends on the ownership chain from the object the user called to the underlying tables. If the ownership chain is unbroken from the stored procedure to the underlying tables, the stored pro- cedure can execute using the permission of its owner. The user only needs permission to execute the stored procedure. The stored procedure can use its owner’s permission to access the underlying tables. The user doesn’t require permission to the underlying tables. Ownership chains are great for developing tight security where users execute stored procedures but aren’t granted direct permission to any tables. If the ownership chain is broken, meaning there’s a different owner between an object and the next lower object, then SQL Server checks the user’s permission for every object accessed. It’s important to note that if dynamic SQL is used, then the EXECUTE AS clause for CREATE PROCEDURE was added to SQL Server 2005. Since it executes as a separate batch, it breaks ownership chaining. When the chain is broken: ■ The ownership chain from dbo.A to dbo.B to dbo.Person is unbroken, so dbo.A can call dbo.B and access dbo.Person as dbo. ■ The ownership chain from dbo.A to Sue.C to Joe.Purchase is broken because different own- ers are present. Therefore, dbo.A calls Sue.C using Joe’s permissions, and Sue.C accesses Joe.Purchase using Joe’s permissions. ■ The ownership chain from dbo.A through dbo.B to Joe.Person is also broken, so dbo.A calls dbo.B using dbo’s permissions, but dbo.B must access Joe.Purchase using Joe’s permissions. ■ It is possible for dbo, Sue, and Joe to all have the same owner. In that case, the ownership chain will work. Stored procedure execute as When developing stored procedures, the effective security access of the code within the stored pro- cedures can be explicitly determined. This is far better than just guessing that the security, or the ownership chain, will be correct. The execute as stored procedure option defines how the ownership is determined. Although execute as is typically associated with stored procedures, it also applies to scalar user-defined functions, multi-line table-valued user-defined functions, and DML and DDL triggers. 1193 www.getcoolebook.com Nielsen c50.tex V4 - 07/21/2009 3:26pm Page 1194 Part VII Security The following example creates a stored procedure that will execute with the permissions of the user with created the stored procedures: CREATE PROCEDURE AddNewCustomer ( LastName VARCHAR(50), FirstName VARCHAR(50) ) WITH EXECUTE AS SELF AS SET NO COUNT ON The options for execute as are: ■ Caller — execute with the owner permissions of the user executing the stored procedure. ■ Self — execute with the permission of the user who created or altered the stored procedure. ■ Owner — execute with the permissions of the owner of the stored procedure. ■ ’hard-coded user name’ — execute with the permission of the specific named user. A Sample Security Model Example For a few examples of permissions using the OBXKites database, Table 50-1 lists the permission settings of the standard database roles. Table 50-2 lists a few of the users and their roles. TABLE 50-1 OBXKites Fixed Roles Standard Role Hierarchical Role Structures Primary Filegroup Tables Static Filegroup Tables Other Permissions IT sysadmin server role ––– Clerk – – – Execute permissions for several stored procedures that read from and update required day-to-day tables Admin db_owner database fixed role ––– Customer – Select permissions – – 1194 www.getcoolebook.com Nielsen c50.tex V4 - 07/21/2009 3:26pm Page 1195 Authorizing Securables 50 TABLE 50-2 OBXKites Users User Database Standard Roles Sammy Admin Joe Public LRN IT DBA Clerk Windows group (Betty, Tom, Martha, and Mary) Clerk Using this security model, the following users can perform the following tasks: ■ Betty, as a member of the Clerk role, can execute the application that executes stored pro- cedures to retrieve and update data. Betty can run select queries as a member of the Public role. ■ LRN, as the IT DBA, can perform any task in the database as a member of the sysadmin server role. ■ Joe can run select queries as a member of the public role. ■ As a member of the admin role, Sammy can execute all stored procedures. He can also manually modify any table using queries. As a member of the admin role that includes the db_owner role, Joe can perform any database administrative task and select or modify data in any table. ■ Only LRN can restore from the backups. Views and Security A popular, but controversial, method of designing security is to create a view that projects only certain columns, or that restricts the rows with a WHERE clause and a WITH CHECK option, and then grants permission to the view to allow users limited access to data. Some IT shops require that all access go through such a view. This technique is even assumed in the Microsoft certification tests. Chapter 14, ‘‘Projecting Data Through Views,’’ explains how to create a view and use the WITH CHECK option. Those opposed to using views for a point of security have several good reasons: ■ Views are not compiled or optimized. ■ Column-level security can be applied with standard SQL Server security. ■ Using views for row-level security means that the WITH CHECK option must be manually created with each view. As the number of row-level categories grows, the system requires manual maintenance. 1195 www.getcoolebook.com Nielsen c50.tex V4 - 07/21/2009 3:26pm Page 1196 Part VII Security Summary It’s essential to secure the database objects. This is an integral part of the SQL Server security model. This chapter covered such securables, and you should now be able to handle the design and mainte- nance of this part of the database. The next chapter continues with another security-related topic, data encryption, which keeps data confidential. 1196 www.getcoolebook.com Nielsen c51.tex V4 - 07/21/2009 3:41pm Page 1197 Data Cryptography IN THIS CHAPTER Introduction to cryptography Using the SQL Server data encryption tools W hen I was a kid, I remember playing with the secret decoder ring from a cereal box. How cool was that?! Now I’m all grown up and still playing with secret decoder rings. Hmmm. Usually, securing access to the table is sufficient; if not, securing the column will suffice. However, for some information, such as credit card numbers or secret government data, the information’s sensitivity warrants further security by encrypting the data stored in the database. SQL Server 2008 can encrypt data inside SQL Server with passwords, keys, or certificates. All editions of SQL Server support data encryption. Introduction to Cryptography Data encryption is basically a scrambling of the data with a secret key to produce an encoded copy of the data called the cipher data. Without the key, the data is impossible to unscramble. Types of encryption Symmetric encryption uses the same key to both encrypt and decrypt the data. While this method is simpler to administer and faster than asymmetric encryp- tion, it’s considered riskier because the encryption algorithm is weaker, and more tasks (people) need copies of the key. This may not be a problem when encrypting and decrypting data inside SQL Server. 1197 www.getcoolebook.com Nielsen c51.tex V4 - 07/21/2009 3:41pm Page 1198 Part VII Security What’s new with data cryptography? S QL Server 2005 introduced data encryption with master keys and certificates. Although it’s complex, it was well received. Not to rest on their laurels, for SQL Server 2008 Microsoft adds transparent data encryption that encrypts the whole database file for theft protection. Also new is extensible key management, which lets SQL Server use third-party enterprise key management software and hardware-based encryption key. Asymmetric encryption is considered stronger than symmetric encryption because one key, a private key, is paired with a second public key. If the data is encrypted with one of those two keys, then it can be decrypted with the other. In other words, if I encrypt some data using my private key and you already have my public key, then you can decrypt the data. If I’ve had to share my public key with several part- ners and I want to ensure that only you can decrypt the data, then we can double the encryption using both our private and public keys. I encrypt using my private key and encrypt it again using your public key. You reverse the order, decrypting with your private key and then my public key. Data can also be encrypted and decrypted using .NET at the middle tier or at the front end. This offers the advantage that the database server never sees readable data. A number of years ago, I used this method for a SQL Server 2000 project storing credit card data. It required that I write a C# .NET class that employed the System.Security.Cryptography class to use a Rinjdael (explained later in this chapter) encryption algorithm. It worked well, and the data was encrypted from the time it was initially received until the authorized user viewed the report. Certificates are similar to keys but are generally issued by an organization, such as VeriSign, to certify that the organization associated with the certificate is legitimate. It’s possible, and recommended, to generate local certificates within SQL. The hierarchy of keys SQL Server encryption is based on a hierarchy of keys. At the top of the hierarchy is a unique service master key generated by SQL Server for encryption the first time it’s needed. At the next level is the database master key, which is a symmetric key SQL Server uses to encrypt private certificates and asymmetric keys. You create a database master key using the CREATE MASTER KEY DDL command. SQL Server then encrypts the database master using the service master key and stores it in both the user database and the master database: CREATE MASTER KEY ENCRYPTION BY PASSWORD = ‘P@$rw0rD’; The password must meet Windows’ strong password requirements. To view information about the master keys, use the syssymmetric_keys and the sysdatabases.is_master_key_encrypted_by_server catalog views. Within the database, and below the database master key in SQL Server’s cryptographic hierarchy, are certificates and private keys. 1198 www.getcoolebook.com Nielsen c51.tex V4 - 07/21/2009 3:41pm Page 1199 Data Cryptography 51 Encrypting Data When it comes to actually encrypting data, SQL Server provides four methods: ■ Passphrase ■ Symmetric key ■ Asymmetric key ■ Certificate Encrypting with a passphrase The first method of encrypting data is to use a passphrase, similar to a password but without the strong password requirements, to encrypt the data. The encrypted data will be binary, so the example code uses a varbinary data type for the creditcardnumber column. You should test your situation to determine the required binary length. The actual encryption is accomplished using the EncryptbyPassPhrase() function. The first param- eter is the passphrase, followed by the data to be encrypted. This example demonstrates encrypting data using the INSERT DML command: CREATE TABLE CCard ( CCardID INT IDENTITY PRIMARY KEY NOT NULL, CustomerID INT NOT NULL, CreditCardNumber VARBINARY(128), Expires CHAR(4) ); INSERT CCard(CustomerID, CreditCardNumber, Expires) VALUES(1,EncryptByPassPhrase(‘Passphrase’, ‘12345678901234567890’), ‘0808’); A normal select query views the encrypted value actually stored in the database: SELECT * FROM CCard WHERE CustomerID = 1; Result (binary value abridged): CCardID CustomerID CreditCardNumber Expires 1 1 0x01000000C8CF68C 0808 To decrypt the credit card data into readable text, use the DecryptByPassPhrase() function and convert the binary result back to a readable format: SELECT CCardID, CustomerID, CONVERT(VARCHAR(20), DecryptByPassPhrase(’Passphrase’, 1199 www.getcoolebook.com Nielsen c51.tex V4 - 07/21/2009 3:41pm Page 1200 Part VII Security CreditCardNumber)), Expires FROM CCard WHERE CustomerID = 1; Result: CCardID CustomerID CardNo Expires 1 1 12345678901234567890 0808 Sure enough, the data decrypted to the same value previously inserted. If the passphrase were incorrect, then the result would have been null. There is one other option to the passphrase encryption method. An authenticator may be added to the encryption to further enhance it. Typically, some internal hard-coded value unknown by the user is used as the authenticator to make it more difficult to decrypt the data if it’s removed from the database. The following code sample adds the authenticator to the passphrase encryption. The code, 1,enablesthe authenticator, and the last parameter is the authenticator phrase: INSERT CCard(CustomerID, CreditCardNumber, Expires) VALUES(3,EncryptbyPassPhrase(’Passphrase’,’12123434565678788989’, 1, ‘hardCoded Authenticator’), ‘0808’); SELECT CCardID, CustomerID, CONVERT(VARCHAR(20),DecryptByPassPhrase(’Passphrase’, CreditCardNumber, 1, ‘hardCoded Authenticator’)), Expires FROM CCard WHERE CustomerID = 3; Result: CCardID CustomerID CardNo Expires 2 3 12123434565678788989 0808 Encrypting with a symmetric key Using a symmetric key provides an actual object for the encryption, rather than just a human-readable passphrase. Symmetric keys can be created within SQL Server using the CREATE DDL command: CREATE SYMMETRIC KEY CCardKey WITH ALGORITHM = TRIPLE_DES ENCRYPTION BY PASSWORD = ‘P@s$wOrD’; Once the keys are created, they are listed in Management Studio’s Object Explorer under the database’s Security ➪ Symmetric Keys node. To view information about the symmetric keys using T-SQL, query the syssymmetric_keys catalog view. Keys are objects and can be altered or dropped like any other SQL Server object. 1200 www.getcoolebook.com Nielsen c51.tex V4 - 07/21/2009 3:41pm Page 1201 Data Cryptography 51 Encryption algorithms The algorithm defines how the data will be encrypted using this key. There are nine possible algorithms: DES, TRIPLE_DES, RC2, RC4, RC4_128, DESX, AES_128, AES_192, and AES_256. They differ in speed and strength. The Data Encryption Standard (DES) algorithm was selected as the official data encryption method for the U.S. government in 1976, but it can be broken by brute force using today’s computers in as little as 24 hours. The triple DES (TRIPLE_DES) algorithm uses a longer key and is considerably stronger. The RC algorithms (such as RC2 and RC4) were invented by Ron Rivest in the mid-eighties. Like the DES algorithm, they too are fairly easy to crack. The Advanced Encryption Standard (AES), also known as Rijndael (pronounced ‘‘Rhine-dahl’’), was approved by the National Institute of Standards and Technology (NIST) in November 2001. The 128, 192, or 256 in the algorithm name identifies the bit size of the key. The strongest algorithm in SQL Server’s toolbox is the AES_256. SQL Server leverages Windows’ encryption algorithms, so if an algorithm isn’t installed on Windows, then SQL Server can’t use it. AES is not supported on Windows XP or Windows 2000. Because the symmetric key might be transported in the open to the client, the key itself can also be encrypted. SQL Server can encrypt the key using one, or multiple, passwords, other keys, or certificates. A key_phrase can be used to seed the generation of the key. A temporary key is valid only for the current session and should be identified with a pound sign (#), similar to temporary tables. Temporary keys can use a GUID to help identify the encrypted data using the indentity_value = ‘passphrase’ option. Using the symmetric key To use the symmetric key, the first step is to open the key. This decrypts the key and makes it available for use by SQL Server: OPEN SYMMETRIC KEY CCardKey DECRYPTION BY PASSWORD = ‘P@s$wOrD’; Using the same CCard table created previously, the next code snippet encrypts the data using the CCardKey key. The EncryptByKey() function accepts the GUID identifier of the key, which can be found using the key_guid() function, and the actual data to be encrypted: INSERT CCard(CustomerID, CreditCardNumber, Expires) VALUES(7,EncryptByKey(Key_GUID(’CCardKey’),’11112222333344445555’), ‘0808’); To decrypt the data, the key must be open. The decryptbykey() function will identify the correct key from the data and perform the decryption: SELECT CCardID, CustomerID, CONVERT(varchar(20), DecryptByKey(CreditCardNumber)) as 1201 www.getcoolebook.com . by encrypting the data stored in the database. SQL Server 2008 can encrypt data inside SQL Server with passwords, keys, or certificates. All editions of SQL Server support data encryption. Introduction. for SQL Server 2008 Microsoft adds transparent data encryption that encrypts the whole database file for theft protection. Also new is extensible key management, which lets SQL Server use third-party. strongest algorithm in SQL Server s toolbox is the AES_256. SQL Server leverages Windows’ encryption algorithms, so if an algorithm isn’t installed on Windows, then SQL Server can’t use it. AES