100
Database Encryption SAP ® Adaptive Server ® Enterprise 16.0

Database Encryption SAP Adaptive Server Enterprise 16infocenter.sybase.com/.../doc/pdf/ase_database_encryption.pdf · 2 SAP Adaptive Server Enterprise. Full Database Encryption As

  • Upload
    lethuy

  • View
    267

  • Download
    1

Embed Size (px)

Citation preview

Database Encryption

SAP® Adaptive Server®

Enterprise 16.0

DOCUMENT ID: DC88886-01-1600-01LAST REVISED: May 2014Copyright © 2014 by SAP AG or an SAP affiliate company. All rights reserved.No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission ofSAP AG. The information contained herein may be changed without prior notice.Some software products marketed by SAP AG and its distributors contain proprietary software components of other softwarevendors. National product specifications may vary.These materials are provided by SAP AG and its affiliated companies ("SAP Group") for informational purposes only,without representation or warranty of any kind, and SAP Group shall not be liable for errors or omissions with respect to thematerials. The only warranties for SAP Group products and services are those that are set forth in the express warrantystatements accompanying such products and services, if any. Nothing herein should be construed as constituting an additionalwarranty.SAP and other SAP products and services mentioned herein as well as their respective logos are trademarks or registeredtrademarks of SAP AG in Germany and other countries. Please see http://www.sap.com/corporate-en/legal/copyright/index.epx#trademark for additional trademark information and notices.

Contents

CHAPTER 1: Overview of Encryption ...........................1Full Database Encryption ......................................................3Column Encryption ................................................................3

CHAPTER 2: Protect Data with Encryption Keys .........5Creating the Database Encryption Key ...............................5

Dropping a Database Encryption Key .............................6Changing a Database Encryption Key ............................7

Creating Column Encryption Keys ......................................7Dropping Column Encryption Keys ...............................11Changing the Column Encryption Key ..........................11

Key Protection ......................................................................12Grant Access to Keys ...................................................12Separate Keys from Data ..............................................12

CHAPTER 3: Key Encryption .......................................15Protect Encryption Keys with the Master Key ..................16Protect Encryption Keys with the System-Encryption

Password ..........................................................................17Protect Keys with User-Specified Passwords ...................18Protect Encryption Keys with Dual Control ......................18

CHAPTER 4: Database-Level Master and DualMaster Keys ...............................................................21

Creating the Master and Dual Master Keys .......................21Creating Master Key Copies .........................................22

Setting Passwords for the Master and Dual Master Keys...........................................................................................23

Database Encryption iii

Altering Passwords and Key Encryption Keys forMaster Key Copies ..........................................................24

Regenerate Master Keys .....................................................25Dropping Master Keys and Key Copies .............................26Recovering the Master Key and Dual Master Key ............26Starting SAP ASE in Unattended Start-Up mode .............27

Configure Unattended Start-Up Mode ..........................27Create the Master Key Start-Up File .............................27How SAP ASE Uses the Master Key Start-Up File .......28

CHAPTER 5: Secure External Passwords andHidden Text ................................................................29

Service Keys ........................................................................29Creating Service Keys ..................................................30Dropping Service Keys .................................................31Modify Service Keys .....................................................32

Changing the syb_extpasswdkey .........................32Changing the syb_syscommkey ..........................33

Service Keys with External Passwords .........................33SSL Passwords ....................................................33LDAP Passwords .................................................34Replication Agent Passwords ..............................34

Service Keys Encrypted with the Master Key ...................35

CHAPTER 6: Database Encryption ..............................37Create an Encrypted Database ...........................................37Encrypt an Existing Database ............................................38Encryption Status and Progress ........................................40Performance Considerations ..............................................40Suspend the Encryption Process ......................................43

The quiesce database Command and Fully EncryptedDatabases ................................................................44

Resume the Encryption Process ........................................44Decrypt an Encrypted Database ........................................44

Contents

iv SAP Adaptive Server Enterprise

Recover Fully Encrypted Databases ..................................45Back Up (Dump) a Fully Encrypted Database ...................45Back Up the Database Encryption Key ..............................46Restore (Load) Backups of Fully Encrypted Databases

...........................................................................................46Loading Behavior of Encrypted Databases ......................46Dropping a Database That is Being Encrypted .................48Mounting and Unmounting a Fully Encrypted Database

...........................................................................................48Archive Databases and Full Encryption ............................48

CHAPTER 7: Column Encryption ................................51Encrypting Columns on New Tables ..................................51

Specifying Encryption on select into .............................52Encrypting Columns in Existing Tables ............................53Index Creation and Constraints on Encrypted Columns

...........................................................................................53Domain Creation and Access Rules on Encrypted

Columns ...........................................................................54Decrypt Permission .............................................................55

Revoking Decryption Permission ..................................56Restrict Decrypt Permission ...............................................56Default Values Returned Instead of Decrypted Data ........57

Defining Decrypt Defaults .............................................57Permissions and Decrypt Default ................................. 59Columns with Decrypt Default Values ...........................59Decrypt Default Columns and Query Qualifications .....60decrypt default and Implicit Grants ...............................61decrypt default and insert, update, and delete

Statements ...............................................................62Removing Decrypt Defaults ..........................................63

Length of Encrypted Columns ...........................................63Encrypted Columns Audits .................................................67

Event Names and Numbers ..........................................67

Contents

Database Encryption v

Passwords Masked in Command Text Auditing ............67Auditing Actions of the Key Custodian ..........................67

Performance Considerations ..............................................68Indexes on Encrypted Columns ....................................68Sort Orders and Encrypted Columns ............................68Joins on Encrypted Columns ........................................69Search Arguments and Encrypted Columns ................70Movement of Encrypted Data as Cipher Text ...............70

Access Encrypted Data .......................................................71Encrypted Columns Process ........................................71Permissions for Decryption ...........................................72Drop Encryption ............................................................72

CHAPTER 8: Role of the Key Custodian .....................73Users, Roles, and Data Access ..........................................74

CHAPTER 9: Key Protection Using User-SpecifiedPasswords ..................................................................77

Change a Key’s Protection Method ....................................78Create Key Copies ...............................................................80Change Passwords on Key Copies ....................................81Access Encrypted Data with a User Password .................82Application Transparency Using Login Passwords on

Key Copies .......................................................................84Login Password Change and Key Copies .........................87Dropping a Key Copy ..........................................................87

CHAPTER 10: Key Recovery from Lost Passwords.....................................................................................89

Loss of Password on Key Copy .........................................89Loss of Login Password .....................................................89Loss of Password on Base Key ..........................................90Key Recovery Commands ..................................................91

Contents

vi SAP Adaptive Server Enterprise

Ownership Change of Encryption Keys ............................92

Contents

Database Encryption vii

Contents

viii SAP Adaptive Server Enterprise

CHAPTER 1 Overview of Encryption

SAP® Adaptive Server® Enterprise (SAP®ASE) authentication and access controlmechanisms ensure that only properly identified and authorized users can access data. Dataencryption further protects sensitive data against theft and security breaches.

Encrypt entire databases, or only columns, depending on your needs.

While both encrypted columns and fully encrypted databases allow you to comply withsecurity and privacy requirements, the different usages may make one feature easier to deploythan the other. Consider using:

• Encrypt columns when you can easily identify which columns contain sensitive data.• Encrypt databases when you must perform range searches over sensitive data columns,

and when you lack the knowledge of the data model and cannot identify sensitive datacolumns (for example, in packaged applications that include thousands of tables). Inaddition, the definition of sensitive data (such as personal information) differs amongdifferent locations (such as states or countries); encrypting an entire database can allowyou to satisfy these various data security requirements.

The SAP ASE encryption feature enables you to encrypt data that is at rest, without changingyour applications. This native support provides the following capabilities:

• Fully encrypt databases• Column-level granularity• Use of a symmetric, National Institute of Standards and Technology (NIST)-approved

algorithm: Advanced Encryption Standard (AES)• Performance optimization• Enforced separation of duties• Fully integrated and automatic key management• Application transparency: no application changes are needed• Data privacy protection from the power of the system administrator

Data encryption and decryption is automatic and transparent. If you have insert or updatepermission on a table, any data you insert or modify is automatically encrypted prior tostorage. Daily tasks are not interrupted.

Selecting decrypted data requires decrypt permission in addition to select permission.decrypt permission can be granted to specific database users, groups, or roles. SAP gives youmore control by providing you with granular access capability to sensitive data. SAP alsoautomatically decrypts selected data for users with decrypt permission.

Encryption keys are stored in the database in encrypted form. You can encrypt an encryptionkey using a key encryption key (KEK) derived from a

Database Encryption 1

• System-level user-supplied password• KEK derived from a user-supplied password (which can be the user’s login password)• Separately created database-level KEK (master key or dual master key)

The password you select reflects your ability to preserve data privacy, even from systemadministrators. You may choose to protect your column encryption key using dual-controlmode to increase the security.

When data is encrypted, it is stored in an encoded form called “cipher text.” Cipher textincreases the length of the encrypted column from a few bytes to 32 extra bytes. Unencrypteddata is stored as plain text.

Column and database encryption uses a symmetric encryption algorithm, which means thatthe same key is used for encryption and decryption. SAP ASE tracks the key that encrypts thedata.

Generally, using data encryption requires these steps:

1. Install the license option ASE_ENCRYPTION. See the SAP ASE Installation Guide.2. The system security officer (SSO) enables encryption in SAP ASE:

sp_configure 'enable encrypted columns', 13. Depending on the method you chose to protect encryption keys, create a database-level

master key or set the system encryption password.4. Create one or more named encryption keys. Consider using passwords to protect data even

from the database administrator.5. Specify the data for encryption.6. Grant decrypt permission to users who must see the data. You may choose to specify a

default plain text value known as a “decrypt default.” The SAP ASE returns this default,instead of the protected data, to users who do not have decrypt permission.

Once you perform these steps, you can run your existing applications against your existingdatabases, tables and columns, but now the data is securely protected against theft and misuse.SAP ASE utilities and other SAP products can process data in encrypted form, protecting yourdata throughout the enterprise. For example, you can:

• Use SAP® Control Center or SAP Central SAP ASE Plug-in to manage encrypted datausing a graphical interface. See the online help.

• Use the bulk copy utility (bcp) to securely copy encrypted data in and out of the server. Seethe Utility Guide.

• Use the SAP ASE migration tool sybmigrate to securely migrate data from one server toanother. See the SAP ASE System Administration Guide.

• Use SAP Replication Server to securely distribute encryption keys and data across serversand platforms. See the Replication Server Administration Guide for information onencryption when replicating.

CHAPTER 1: Overview of Encryption

2 SAP Adaptive Server Enterprise

Full Database EncryptionAs of version 16.0, you can fully encrypt entire databases, providing protection for an entiredatabase.

When you fully encrypt a database, all of its data, indexes, and transaction logs becomeencrypted. This encryption is transparent, so that users can perform operations on tables,indexes, and so on, as usual, without noticing any differences.

Column EncryptionEncrypting columns in SAP ASE is more straightforward than using encryption in the middletier, or in the client application. Use SQL statements to create encryption keys and to specifycolumns for encryption; existing applications continue to run without change.

When you insert or update data in an encrypted column, SAP ASE transparently encrypts thedata immediately before writing the row. When you select from an encrypted column, SAPASE decrypts the data after reading it from the row. Integer and floating point data areencrypted in the following form for all platforms:

• Most significant bit format for integer data• Institute of Electrical and Electronics Engineers (IEEE) floating point standard with MSB

format for floating point data

You can encrypt data on one platform and decrypt it on a different platform, provided that bothplatforms use the same character set.

CHAPTER 1: Overview of Encryption

Database Encryption 3

CHAPTER 1: Overview of Encryption

4 SAP Adaptive Server Enterprise

CHAPTER 2 Protect Data with EncryptionKeys

SAP ASE uses two types of encryption keys and keeps keys encrypted when they are not inuse.

Types of encryption keys:

• Database encryption key (DEK) – the DEK is created in the master database and used toencrypt a database.

• Column encryption key (CEK) – users must have access to the CEK before they can accessencrypted data, but it must be encrypted before you store it on disk or in memory. SAP ASEencrypts the CEK using a key encryption key (KEK) and stores it in encrypted form insysencryptkeys. The KEK also decrypts the CEK, allowing you to access decrypteddata.

Key management includes creating, dropping, and modifying column encryption keys,distributing passwords, creating key copies, and providing for key recovery in the event of alost password.

Creating the Database Encryption KeyThe database encryption key is a 256-bit symmetric key that is created in the master databaseand used to encrypt a database.

Prerequisites

Before you can create a database encryption key (DEK):

• Verify that you have a valid SAP ASE encryption feature license (ASE_ENCRYPTION)• Set the enable encrypted columns configuration parameter• Create a master key and optionally, a dual master key in the master database; these

protect the database encryption key.• Ensure that you have the appropriate privileges:

• If granular permission is enabled, a system permission called manage databaseencryption key is required to create the key.

• If granular permission is disabled, you must have sso_role, keycustodian_role, orcreate encryption key permission.

Database Encryption 5

TaskUse the create encryption key command in the master database to create a databaseencryption key. The syntax is:create encryption key keyname [for algorithm] for database encryption [with {[master key] [key_length 256] [init_vector random] [[no] dual_control]}

where:• keyname – must be unique in the user's table, view, and procedure name space in the

master database.

• for algorithm – specifies the algorithm. Currently, the only supported algorithm isAdvanced Encryption Standard (AES).

• for database encryption – explicitly specifies that you are creating anencryption key to encrypt an entire database, rather than a column.

• master key – is required for full database encryption. SAP ASE returns an error if themaster key does not already exist.

• key_length 256 – is the size, in bits, of the key you are creating. The only valid lengthfor a database encryption key is 256; SAP ASE returns an error message if you use anyother size.

• init_vector random – is required for full database encryption. If you specifyinit_vector null, as you can for creating a column encryption key, SAP ASEreturns an error.

• [no] dual control – indicates whether the database encryption key must beencrypted using dual controls. By default, dual control is not configured.

This example creates a database encryption key that is protected by the master key:sp_configure 'enable encrypted columns', 1create encryption key master with passwd "testpassword"set encryption passwd 'testpassword' for key mastercreate encryption key dbkey for database encryption

Dropping a Database Encryption KeyTo drop the database encryption key, use the drop encryption key command. This commanddeletes the database encryption key from the sysencryptkeys table in the masterdatabase.

The syntax is:drop encryption key key_name

Note: This command fails if the database encryption key you are dropping is still being used toencrypt a database.

CHAPTER 2: Protect Data with Encryption Keys

6 SAP Adaptive Server Enterprise

Changing a Database Encryption KeyTo change the manner in which a database encryption key is protected, as well as who itsowner is, use the alter encryption key command.

You cannot regenerate a database encryption key for a database.

• To change a database encryption key:1. Decrypt the database protected by the database encryption key.2. Drop, and re-create the database encryption key.

Note: You cannot convert a column encryption key into a database encryption key. SAPASE displays an error message if you alter a different type of encryption key into adatabase encryption key using the for database encryption option.

• To simply change the way a database encryption key is protected, rather than change thedatabase encryption key altogether, use this syntax:alter encryption key key_namefor database encryptionmodify encryption with {[master key] [[no] dual_control}

• To change the owner of a database encryption key:alter encryption key [[database.][owner].]dek_name modify owner user_name

The permission to run this option is the same as the permission for alter encryption key.

Creating Column Encryption KeysA column encryption key must exist before a table owner can mark a column for encryption ona new or existing table.

When you set up keys for the first time, consider:

• Key owner or custodian assignment – the system security officer (SSO) must grant createencryption key permission to create keys. By default, the sso_role and thekeycustodian_role have create encryption key permission.

• Whether keys should be created in a separate key database – SAP recommends that you usea separate database for keys, especially if keys are encrypted by the system encryptionpassword.

• The number of keys needed – you can create a separate key for each encrypted column, oryou can use the same key to encrypt columns across multiple tables. From a performancestandpoint, encrypted columns that join with equivalent columns in other tables shouldshare the same key. For security purposes, unrelated columns should use different keys.

Column encryption in SAP ASE uses the Advanced Encryption Standard (AES) symmetrickey encryption algorithm, with available key sizes of 128, 192, and 256 bits. Random-keygeneration and cryptographic functionality is provided by the FIPS 140-2 compliant modules.

CHAPTER 2: Protect Data with Encryption Keys

Database Encryption 7

To securely protect key values, SAP ASE uses a 256-bit key-encrypting key (KEK), whichmay be a master key, or an internal key derived from either the system encryption password ora user-specified password.

SAP ASE encrypts the new key (the column encryption key) and stores the result insysencryptkeys.

By default, SAP ASE creates 256-bit key-encryption keys. For compatibility with versionsearlier than 15.7, it uses a 128-bit key if the KEK is derived from the system encryptionpassword.

The syntax is:

create encryption key [[database.][owner].]keyname [as default] [for algorithm] [with {[key_length num_bits] [{passwd 'passwd_phrase' | passwd system_encr_passwd | master key}] [init_vector {null | random}] [pad {null | random}] [[no] dual_control] }]

where:

• keyname – must be unique in the user’s table, view, and procedure name space in thecurrent database. Specify the database name if the key is in another database, and specifythe owner’s name if more than one key of that name exists in the database. The defaultvalue for owner is the current user, and the default value for database is the currentdatabase. Only the system security officer can create keys for other users.

Note: You cannot create temporary key names that start with “#”.

• as default – allows the system security officer or key custodian to create a database defaultkey for encryption. This enables the table creator to specify encryption without using akeyname on create table, alter table, and select into. SAP ASE uses the default key fromthe same database. The default key may be changed.

• for algorithm – Advanced Encryption Standard (AES) is the only algorithm supported.AES supports key sizes of 128, 192, and 256 bits, and a block size of 16 bytes. The blocksize is the number of bytes in an encryption unit. Large data is subdivided for encryption.

• keylength num_bits – the size, in bits, of the key to be created. For AES, valid key lengthsare 128, 192, and 256 bits. The default keylength is 128 bits.

• passwd password_phrase – indicates to ASE to protect the CEK using the user passwordpassword_phrase, which can be a quoted alphanumeric string up to 255 bytes in length.

• passwd system_encr_passwd – indicates to ASE to protect the CEK using the systemencryption password.

• master key – indicates to ASE to protect the CEK using the master key. By default, SAPASE uses the master key (if it exists) to protect column encryption keys.

CHAPTER 2: Protect Data with Encryption Keys

8 SAP Adaptive Server Enterprise

• init_vector

• random – specifies use of an initialization vector during encryption. When aninitialization vector is used by the encryption algorithm, the cipher text of two identicalpieces of plain text are different, which prevents detection of data patterns. Using aninitialization vector can add to the security of your data.Use of an initialization vector implies using a cipher-block chaining (CBC) mode ofencryption, where each block of data is combined with the previous block beforeencryption, with the first block being combined with the initialization vector.However, initialization vectors have some performance implications. You can createindexes and optimize joins and searches only on columns where the encryption keydoes not specify an initialization vector.

• null – omits the use of an initialization vector when encrypting. This makes the columnsuitable for supporting an index.The default is to use an initialization vector, that is, init_vector random.Setting init_vector null implies the electronic codebook (ECB) mode, where eachblock of data is encrypted independently.To encrypt one column using an initialization vector and another column without usingan initialization vector, create two separate keys—one that specifies use of aninitialization vector and another that specifies no initialization vector.

• pad

• null – the default, omits random padding of data.You cannot use padding if the column must support an index.

• random – data is automatically padded with random bytes before encryption. You canuse padding instead of an initialization vector to randomize the cipher text. Padding issuitable only for columns whose plain text length is less than half the block length. Forthe AES algorithm the block length is 16 bytes.

• dual control – indicates whether the new key must be encrypted using dual control. Bydefault, dual control is not configured.

ExamplesThese examples use various encryption attributes when creating a column encryption key, andmany assume you have already created the master key or set the system encryption password.

• Example 1 – specifies a 256-bit key called “safe_key” as the database default key. Becausethe key does not specify a password, SAP ASE uses the database-level master key as theKEK for safe_key. If there is no master key, SAP ASE uses the system encryptionpassword:create encryption key safe_key as default for AES with keylength 256

Only the system security officer or a user with the keycustodian_role can create a defaultkey.

• Example 2 – creates a 128-bit key called “salary_key” for encrypting columns usingrandom padding:

CHAPTER 2: Protect Data with Encryption Keys

Database Encryption 9

create encryption key salary_key for AES with init_vector null pad random

• Example 3 – creates a 192-bit key named “mykey” for encrypting columns using aninitialization vector:create encryption key mykey for AES with keylength 192 init_vector random

• Example 4 – creates a key protected by a user-specified password:create encryption key key1 with passwd 'Worlds1Biggest6Secret'

If a key is protected by a user-specified password, that password must be entered a columnencrypted by the key can be accessed.

• Example 5 – creates a key protected by dual-control:create encryption key dualprotectedkeywith passwd "Pass4Tomorrow"dual_control

Key “dualprotectedkey” is protected by the master key and a user password (in dualcontrol). To access the key, you must enter both the user password for the key and thepassword for the master key.

PermissionsThe sso_role and keycustodian_role implicitly have permission to create encryption keys.The system security officer or the key custodian uses this syntax to grant create encryptionkey permissions to others:grant create encryption key to user_name | role_name | group_name

For example:grant create encryption key to key_admin_role

To revoke key creation permission, use:revoke create encryption key {to | from} user_name | role_name | group_name

Note: grant all does not grant create encryption key permission to the user. It must beexplicitly granted by the system security officer.

See also• Chapter 8, Role of the Key Custodian on page 73

• Chapter 4, Database-Level Master and Dual Master Keys on page 21

• Key Protection on page 12

• Performance Considerations on page 68

• Dropping Column Encryption Keys on page 11

CHAPTER 2: Protect Data with Encryption Keys

10 SAP Adaptive Server Enterprise

Dropping Column Encryption KeysColumn encryption key owners can drop their own keys. The system security officer can dropany key.

Prerequisites

A key can be dropped only if there are no encrypted columns in any database that use thekey.

Task

To drop an encryption key, use:

drop encryption key [[database.][owner].]keyname

For example, this drops an encryption key named cc_key:

drop encryption key cust.dbo.cc_key

When executing drop encryption key, SAP ASE does not check for encrypted columns indatabases that are suspect, archived, offline, not recovered, or currently being loaded. In any ofthese cases, the command issues a warning message that names the unavailable database, butdoes not fail. When the database is brought online, any tables with columns that wereencrypted with the dropped key are unusable. To restore the key, the system administratormust load a dump of the dropped key’s database that precedes when the key was dropped.

The system security officer can use sp_encryption to identify all the columns encrypted with agiven key.

See also• Creating Column Encryption Keys on page 7• Chapter 8, Role of the Key Custodian on page 73• Chapter 4, Database-Level Master and Dual Master Keys on page 21• Key Protection on page 12• Performance Considerations on page 68

Changing the Column Encryption KeyPeriodically change the keys used to encrypt columns and databases.

Create a new key using create encryption key, then use alter table...modify to encrypt thecolumn with the new key.

In the following example, assume that the “creditcard” column is already encrypted. The altertable command decrypts and reencrypts the credit card value for every row of customer usingcc_key_new.

create encryption key cc_key_new for AES

CHAPTER 2: Protect Data with Encryption Keys

Database Encryption 11

alter table customer modify creditcard encrypt with cc_key_new

Key ProtectionThe key administrator must decide where keys are stored, when they should be renewed, andwhich owners can use a given key to encrypt data.

See also• Creating Column Encryption Keys on page 7

• Dropping Column Encryption Keys on page 11

Grant Access to KeysThe key owner or a user with the sso_role must grant select permission on a key beforeanother user can specify the key in the create table, alter table, and select into statements.

The key owner can be the system security officer, the key custodian or, for non-default keys,any user with create encryption key permission. Key owners should grant select permissionon keys as needed.

This example allows users with db_admin_role to use the encryption key named “safe_key”when specifying encryption on create table, alter table, and select into statements:grant select on safe_key to db_admin_role

Note: Users who process encrypted columns through insert, update, delete, and select do notneed select permission on the encryption key.

Separate Keys from DataWhen you specify a data for encryption, you can use a named key from the same database orfrom a different database. Encrypting with a key from a different database provides a securityadvantage because, in the event of the theft of a database dump, it protects against access toboth keys and encrypted data.

Administrators can also protect each database dump with a different password, makingunauthorized access even more difficult.

Encrypting with a key from a different database needs special care to avoid data and keyintegrity problems in distributed systems. Carefully coordinate database dumps and loads. Ifyou use a named key from a different database, SAP recommends that, when you dump adatabase that contains:

• Encrypted columns, you also dump the database where the key was created. You must dothis if new keys have been added since the last dump.

• An encryption key, dump all databases containing columns encrypted with that key. Thiskeeps encrypted data in sync with the available keys.

CHAPTER 2: Protect Data with Encryption Keys

12 SAP Adaptive Server Enterprise

If you do not specify a named key, the data is automatically encrypted with the default keyfrom the same database. The system security officer or the key custodian can usesp_encryption to identify the columns encrypted with a given key.

CHAPTER 2: Protect Data with Encryption Keys

Database Encryption 13

CHAPTER 2: Protect Data with Encryption Keys

14 SAP Adaptive Server Enterprise

CHAPTER 3 Key Encryption

There are two keys between the user and the data: the database-encryption key (DEK) orcolumn-encryption key (CEK) and the key-encryption key (KEK). The DEK and CEKencrypts data and users must have access to it before they can access encrypted data.

It cannot be stored on disk in an unencrypted form. Instead, SAP ASE uses a KEK, or 2 KEKsin dual control, to encrypt the DEK or CEK when you create or alter an encryption key. TheKEK also decrypts the DEK or CEK before you can access decrypted data. DEKs and CEKsare stored in encrypted form in sysencryptkeys.

The KEK is a master key, created separately by the system security officer or key custodian, isan internally derived key from the system encryption password, a user-specified password, ora login password, depending on how you specify the key’s encryption with the create and alterencryption key statements. Both the system encryption password and the master key arestored in encrypted form.

The following figure describes how to create and store a column encryption key for a createencryption key statement. The KEK is derived from a password and the KEK and the rawCEK are fed into the encryption function to produce an encrypted CEK.

Figure 1: Create an Encryption Key

The following figure describes how the KEK is used during a DML operation to decrypt theCEK. The raw CEK is then used to encrypt or decrypt data.

Database Encryption 15

Figure 2: Accessing a CEK to Encrypt or Decrypt on DML Statement

Protect Encryption Keys with the Master KeyThe master key is a database-level key that is created by a user with the sso_role orkeycustodian_role, and is used as a KEK for user-created encryption keys. Once created, themaster key replaces the system encryption password as the default KEK for user-created keys.

Although SAP ASE supports using the system encryption password, for compatibility withversions earlier than 15.7, SAP recommends that you use the master key.

You can use the master key with the dual master key to create a composite key that providesdual control and split knowledge for all user-created keys. You can also create a composite keyby using the master key with a DEK's or CEK’s explicit password.

Using a master key simplifies the administration of encrypted data because:

• Managing passwords for keys is restricted to setting the password for the master key.• You need not specify passwords on create and alter encryption key statements.• Allows for password distribution and recovery from lost column encryption key

passwords.• Access control over encrypted data is enforced through decrypt permission on the data.• You need not make any changes to the application.

The syntax for creating a master key is:create encryption key master [for AES] with passwd char_literal

See the Reference Manual: Commands.

See also• Restrict Decrypt Permission on page 56

CHAPTER 3: Key Encryption

16 SAP Adaptive Server Enterprise

Protect Encryption Keys with the System-EncryptionPassword

The system encryption password is a database-specific password, and is the secondary defaultencryption method for the DEK or CEK.

SAP ASE uses the system encryption password to encrypt keys created in a specified databasewithout an explicit password clause. Once the system security officer or key custodian has seta system encryption password, you need not specify this password to process encryptedcolumns. SAP ASE internally accesses the system encryption password when it needs toencrypt or decrypt column encryption keys.

The system security officer or key custodian uses sp_encryption to set the system encryptionpassword. The system password is specific to the database using sp_encryption.sp_encryption system_encr_passwd, password

password can be as many as 255 bytes in length.

Set a system encryption password only in the database where encryption keys are created.

The system encryption password protects your encryption keys. Choose long and complexsystem encryption passwords. Longer passwords are harder to guess or crack by brute force.Include uppercase and lowercase letters, numbers, and special characters in the systemencryption password. SAP recommends that the system encryption password be at least 16bytes in length.

SAP ASE enforces compliance of the system encryption password with the minimumpassword length and check password for digit configuration parameters.

Change the system password by using sp_encryption and supplying the old password:sp_encryption system_encr_passwd, password [ , old_password]

Periodically change the system encryption password, especially when an administrator whoknows the system encryption password leaves the company. When the system password ischanged, SAP ASE automatically reencrypts all keys in the database with the new password.Encrypted data is unaffected when the system password is changed, in other words, it is notdecrypted and reencrypted.

You can u-set the system encryption password by supplying “null” as the argument forpassword and supplying the value for old_password. Unset the system password only if youhave dropped all the encryption keys in that database that were encrypted by the systemencryption password.

The encrypted password value is stored in the sysattributes system table in thatdatabase. Additionally, the encrypted database feature introduces 43, a new systtributes

CHAPTER 3: Key Encryption

Database Encryption 17

class that signifies full database encryption. For every storage allocation of the database thatundergoes encryption, SAP ASE inserts a row in sysattributes with these values:

Column Name Value

class 43

object dbid (database ID)

object_info1 Starting logical page ID

object_info2 Ending logical page ID

int_value Last encrypted logical page ID on one storage allocation

This row is removed when SAP ASE finishes encrypting the database.

Protect Keys with User-Specified PasswordsYou can limit the power of the system administrator or database owner to access private datawhen you specify passwords on keys using create encryption key or alter encryption key.

If keys have explicit passwords, users must have, before they can decrypt data:

• decrypt permission on the data• The encryption key’s password

Users must also know the password to run DML commands that encrypt data.

See also• Chapter 9, Key Protection Using User-Specified Passwords on page 77

Protect Encryption Keys with Dual ControlYou can secure encryption keys with dual control using the create encryption key command.

If you specify create encryption key with dual_control, but do not specify a user password,the encryption key is protected by the master key and the dual master key.

If you specify with dual_control and include a user-specific password, the encryption key isprotected by the master key and the user password.

• Example 1 – protects CEK “Reallysecret” with both the master and dual master keys andfails, unless both keys exist in the database:create encryption key Reallysecret with init_vector random dual_control

• Example 2 – encrypts CEK “k3” with both the master key and user password“Whybother”:

CHAPTER 3: Key Encryption

18 SAP Adaptive Server Enterprise

create encryption key k3 with passwd 'Whybother' dual_control

See also• Change a Key’s Protection Method on page 78

CHAPTER 3: Key Encryption

Database Encryption 19

CHAPTER 3: Key Encryption

20 SAP Adaptive Server Enterprise

CHAPTER 4 Database-Level Master and DualMaster Keys

SAP ASE allows users to create database-level encryption keys called the master key and thedual master key. These keys both act as key encryption keys, and are used to protect other keys,such as column and database encryption keys, and service keys.

The master key and the dual master key must have different owners. You can providepasswords for the master keys using either isql, or through a server-private file that isaccessible only by the SAP ASE. The passwords to these keys are not stored in the database.

See also• Creating Column Encryption Keys on page 7

• Dropping Column Encryption Keys on page 11

Creating the Master and Dual Master KeysOnce created, master keys become the default protection method for encryption keys. A dualmaster key is required only for dual control of column and database encryption keys.

Prerequisites

Only users with sso_role or keycustodian_role can create the master key and dual master key.There can only be one master and one dual master key for a database.

Task

To create the master and dual master keys use:create encryption key [dual] master [for AES] with passwd char_literal

where:

• master and dual master refer to database-level keys used to encrypt other keys within thedatabase in which they are defined. These keys are not used to encrypt data. The master keyis named internally as sybencrmasterkey in sysobjects, and the dual master keyis named internally as sybencrdualmasterkey in sysobjects.

• with passwd must be followed by a character string password that adheres tosp_passwordpolicy.

See the Reference Manual: Commands.

Database Encryption 21

• Example 1 – creates master key in database tdb1:

use database tdb1create encryption key master with passwd'unforgetablethatswhatyouare'

• Example 2 – creates a dual master key in database tdb1:

use database tb1create encryption key dual master with passwd 'dualunforgettable'

• Example 3 – generates an error because you cannot use a master key as a columnencryption key:create table t2 (c1 int encrypt with master)

To change the password of a master key or dual master key, use:alter encryption key [dual] master with passwd <char_literal> modify encryption with passwd <char_literal>

Creating Master Key CopiesUsers or master key owners with sso_role or keycustodian_role can create copies for masterkeys.

You may need to:

• Provide access to the master key or dual master key for unattended start-up of the SAPASE. Such a key copy is referred to as the automatic_startup copy.

• Support recovery of the master keys should their passwords be lost. Such a key copy isreferred to as the recovery copy.

• Allow a user other than the base key owner to set up encryption passwords for the master ordual master key. This key copy is referred to as a regular copy.

To add master key copies in a database, use:alter encryption key [dual] master with passwd char_string add encryption {with passwd char_string for user user_name [ for recovery ] | [ for automatic_startup ] }

where:

• char_string – (first reference) specifies the password that currently encrypts the base copyof the master or dual master key.

• char_string – (second reference) specifies the password for the regular or recovery copy. Itmust not be used for automatic_startup copies.

• for user – indicates the user to whom the regular or recovery copy must be assigned. Do notuse this parameter to enter a password for automatic_startup copies.

CHAPTER 4: Database-Level Master and Dual Master Keys

22 SAP Adaptive Server Enterprise

• for recovery – indicates that the key copy is to be used to recover the master key in case thepassword is lost.

• for automatic_startup – indicates that the key copy is to be used to access the master ordual master key after the server is restarted with automatic master key access enabled.

• Example 1 – master key owner creates a key copy for Mary:alter encryption key master with passwd 'unforgettablethatswhatur' add encryption with passwd 'just4now' for user mary

• Example 2 – dual master key owner Smith creates a key copy for automatic_startup with:alter encryption key dual master with passwd 'Never4Getable' add encryption for automatic_startup

See also• Chapter 10, Key Recovery from Lost Passwords on page 89

Setting Passwords for the Master and Dual Master KeysThe base key owner, or a user who owns a regular key copy, can set the password for the masterand dual master keys. Passwords must be set before master keys can be used.

To set passwords for master keys, you can either use the:

• set encryption passwd command• Use the unattended start-up feature• (Master key only) the dataserver command

The set encryption command is:set encryption passwd char_literal for key [dual] master

where:

• char_literal – if the user is the key owner, this is the password that currently encrypts thebase copy of the master or dual master key. If the user is not the key owner, this is thepassword that currently encrypts the user’s copy of the key.

Example – sets the password “MasterSecret” for the master key in database tdb1:

use tdb1set encryption passwd 'MasterSecret' for key master

SAP ASE sets the password in the server memory for the database in which the master or dualmaster key is defined, and also records the identity of the user setting the password. Once set,the password is available for all access to the master key in the database.

CHAPTER 4: Database-Level Master and Dual Master Keys

Database Encryption 23

Altering Passwords and Key Encryption Keys for MasterKey Copies

Users who own master key copies can change the passwords for their key copies.

To change the password for key copies:alter encryption key [dual] master with passwd char_string modify encryption {with passwd char_string [for recovery] | for automatic_startup}

where:

• char_string – (first instance) If the user is the key owner, this is the password that currentlyencrypts the base copy of the master or dual master key. If the user is not the key owner, thisis the password that currently encrypts the user’s copy of the key.

• char_string – (second reference) specifies the new password for the regular or recoverycopy. Do not use this parameter to enter a password for automatic_startup copies.

• for automatic_startup – generate a new KEK and use it to create a new automatic_startupkey copy.

If neither for recovery nor for automatic startup is specified, and the command is issued bythe key owner, SAP ASE alters the base key copy password. If the command is not issued bythe key owner, SAP ASE alters the password of the base key copy only if the current user hassso_role or keycustodian_role.

• Example 1 – master key owner “Jones” creates a key copy for “Mary” using:alter encryption key master with passwd 'unforgettablethatswhatyouare' add encryption with passwd 'just4now' for user Mary

• Example 2 – “Mary” changes the password for her copy using:alter encryption key master with passwd 'just4now' modify encryption with passwd 'maryspasswd'

• Example 3 – master key owner “John” changes the password for the base key using:alter encryption key master with passwd 'unforgettablethatswhatyouare' modify encryption with passwd 'notunforgettable'

Users with sso_role or keycustodian_role can modify the automatic_startup key copies tochange their key encryption keys. For example, such a user with knowledge of the master keypassword, can change the key encryption key of the automatic_startup key copy using:

CHAPTER 4: Database-Level Master and Dual Master Keys

24 SAP Adaptive Server Enterprise

alter encryption key master with passwd 'unforgettablethatswhatyouare' modify encryption for automatic_startup

The SAP ASE:

• Decrypts the base master key with a key encryption key derived from the password.• Creates a new master key encryption key and replaces the old key in the master key start-up

file with this new key.• Creates a new automatic_startup key copy by encrypting the master key using the new

master key encryption key, and replacing the old automatic_startup key copy insysencryptkeys with this new copy.

Regenerate Master KeysPeriodically change the master and dual master keys. However, each time you change themaster and dual master keys, you must also reencrypt all column and database encryption keysusing the new master and dual master keys.

To automate this process, SAP ASE uses the regenerate key option which replaces the masteror dual master key values with the new values, and reencrypts all column and databaseencryption keys that are currently encrypted by the master or dual master keys beingregenerated:alter encryption key [dual] master with passwd char_string regenerate key [with passwd char_string]

When regenerate key command is executed, SAP ASE:

• Validates that the supplied password decrypts the base master or dual master key.• Creates a new master or dual master key.• Decrypts all column and database encryption keys that are encrypted either solely or

partially by the master or dual master key. SAP ASE reencrypts them using the new masteror dual master key.

• Replaces the base master or dual master key with the new key encrypted by the secondpassword. If the second password is not supplied, SAP ASE uses the currently configuredpassword to encrypt the new key.

• Drops the regular key copies. The master key owner must re-create regular key copies fordesignated users using alter encryption key.

• Drops the key recovery copy. The master key owner must add a new recovery key copyusing alter encryption key, and inform the recovery key owners of the new password.

• Replaces the automatic_startup copy with a new key copy created by encrypting the newmaster key with a new randomly generated master key encryption key. SAP ASE writes thenew master key encryption key into the master key start-up file.

CHAPTER 4: Database-Level Master and Dual Master Keys

Database Encryption 25

Dropping Master Keys and Key CopiesA user with sso_role or keycustodian_role can drop a master or dual master key provided thatthere are no other column or database encryption keys that are currently encrypted using thatmaster or dual master key.

To drop a master or a dual master key, use:drop encryption key [dual] master

When a master or dual master key is dropped, SAP ASE:

• Drops the master or dual master key, and its key copies. All regular key copies, theautomatic_startup key copy, and recovery key copies are deleted from the database.

• Deletes the master key encryption keys from the master keystart-upfile, if anautomatic_startup key copy exists.

To delete only the regular key copy, use:alter encryption key [dual] master drop encryption for user username

To delete only the recovery key copy, use:alter encryption key [dual] master drop encryption for recovery

To delete only the automatic_startup key copy, use:alter encryption key [dual] master drop encryption for automatic_startup

Recovering the Master Key and Dual Master KeyA user with sso_role or keycustodian_role can recover the master or dual master key.

To recover the master or dual master key:alter encryption key [dual] master with passwd char_string recover encryption with passwd char_string

where the first reference to passwd is the password to the recovery key copy and the secondreference to passwd is the new password for the base key.

CHAPTER 4: Database-Level Master and Dual Master Keys

26 SAP Adaptive Server Enterprise

Starting SAP ASE in Unattended Start-Up modeUse unattended start-up mode to allow access to the master keys when the password holdersare unavailable.

1. Enable the automatic master key access configuration parameter.

2. (Optional) set the master key start-up file path and name. Otherwise, SAP ASE uses thedefault file path and name.

3. Add automatic_startup copies for the master keys or dual master keys for databases forwhich you intend to have unattended start-up.

Configure Unattended Start-Up ModeIn unattended start-up mode, SAP ASE accesses master keys, even if their passwords are notpresent in server memory, by reading and decrypting the master key encryption keys from themaster key start-up file.

Users with sso_role can configure SAP ASE to use unattended start-up mode by setting:sp_configure ‘automatic master key access’, 1

To use unattended start-up mode, you must also create automatic_startup key copies for themaster key and dual master key in the database.

Create the Master Key Start-Up FileWhen automatic master key access is enabled, SAP ASE reads in the key encryption keysfrom the master key start-up file.

If the master key start-up file does not exist, SAP ASE creates a master key start-up file, butdoes not write the key encryption key values to the file until automatic_startup key copieseither of the master or dual master keys are created

When automatic master key access is disabled, SAP ASE drops the key encryption keys formaster and dual master keys from the server memory. SAP ASE does not erase the keyencryption key values from the master key start-up file.

A user with the sso_role can specify the master key start-up file path and name using:sp_encryption mkey_startup_file [, {new_path | default_location | null}] [, {sync_with_mem | sync_with_qrm}]

where:

• new_path – specifies the location and name of the master key start-up file. new_path is notsupported in standalone SAP ASE Cluster Edition installations.

CHAPTER 4: Database-Level Master and Dual Master Keys

Database Encryption 27

• default_location – sets the master key start-up file to the default path and name:$SYBASE_ASE/security/ase_encrcols_mk_<servername>.dat.default_location is not supported in standalone SAP ASE Cluster Edition installations.

• null – displays the current master key start-up file path and name.• sync_with_mem – writes the master key encryption keys existing in server memory to the

master key start-up file, if configuration option automatic master key access is enabled.sync_with_mem is not supported in standalone SAP ASE Cluster Edition installations.

• sync_with_qrm – (Available only with standalone Cluster Edition installations) updatesthe key copy in the local master key start-up file with the copy on the quorum device.

How SAP ASE Uses the Master Key Start-Up FileSAP ASE reads the master and dual master key encryption keys from the master key start-upfile into the server memory.

If:

• The server is started with automatic master key access enabled, or• automatic master key access is enabled while the server is running.

If:

• An automatic_startup key copy of the master or dual master key is created, SAP ASEwrites the master or dual master key encryption keys to the file.

• The key encryption key of the automatic_startup key copy of the master or dual masterkey is altered, SAP ASE writes the new master or dual master key encryption keys to thefile.

• An automatic_startup key copy is dropped, SAP ASE deletes the corresponding record inthe file.

• A database is dropped, SAP ASE deletes all records belonging to the dropped database.• A master or dual master key is dropped, SAP ASE deletes the corresponding record.• A new master key start-up file is specified using sp_encryption mkey_startup_file, SAP

ASE synchronizes the server memory with the contents of the new file.

Once a master key encryption key is in memory, the master key can be accessed through theautomatic_startup copy even if the master key password is not set.

CHAPTER 4: Database-Level Master and Dual Master Keys

28 SAP Adaptive Server Enterprise

CHAPTER 5 Secure External Passwords andHidden Text

SAP ASE provides strong encryption for external login passwords and hidden text, using theAES-256 symmetric encryption algorithm.

You may choose strong encryption for external passwords to:

• Replication Agents – replicated databases.• CIS – remote descriptors and logins.• Job Scheduler – Job Scheduler Agent.• RTMS – real-time messaging.• Secure Sockets Layer (SSL) and Lightweight Directory Access Protocol (LDAP) – SSL

and LDAP access accounts. Passwords are administered using stored proceduressp_ldapadmin and sp_ssladmin can be secured.

Objects that have SQL text stored in syscomments, such as stored procedures, user-definedfunctions and computed columns can be optionally encrypted with strong encryption usingsp_hidetext.

Note: Encrypting external passwords and hidden text requires the ASE_ENCRYPTIONlicense.

Service KeysService keys are 256-bit, persistent encryption keys used to strongly encrypt external loginpasswords and hidden text, and are stored in sysencryptkeys.

Encrypt service keys using either:

• A static key – is the default key encryption key for service keys, and can be used if nomaster key has been created in the current database. With this method, SAP ASE can useservice keys after an unattended start-up.

• The master key – provides stronger protection than a static key. SAP ASE requires thepassword to decrypt the database-specific master key.

The database objects that describe these service keys include:

• syb_extpasswdkey – identifies service key for encryption of external login passwords insysattributes. Only one syb_extpasswdkey exists for any database. When thesyb_extpasswdkey is changed, all data encrypted using the key is reencrypted using thenew key.

Database Encryption 29

Although external login passwords are generally stored in the master database, RepAgentstores this information in replicate databases.

• syb_syscommkey_dddddd – identifies service key for encryption of hidden text insyscomments, where “dddddd” is a global identifier generated by SAP ASE to uniquelyidentify the key. The global identifier is included with the name to distinguish names whenthere are many syb_syscommkey keys associated with the same object. The globalidentifier distinguishes the key, on both the local database and in the replicate database.Strong encryption of hidden text requires a service key in each database wheresp_hidetext is executed to hide SQL text. When a new service key is created, anyexisting service key in the database persists until explicitly dropped, and any hidden text isnot reencrypted until you reissue sp_hidetext.

Note: The system encryption password does not encrypt service keys.

During an upgrade to version 15.7 or later, procedural objects are recompiled from source.Connected users are restricted in what they can do until the master key password is entered fordatabases where strong encryption of hidden text is enabled, and service key is protected bymaster key.

An authorized user must set the master key password on such databases using:use mydbgoset encryption passwd password for key mastergo

Creating Service KeysA user with sso_role or keycustodian_role can create a service key and becomes the owner ofthe key.

Prerequisites

To create service keys:

• An ASE_ENCRYPTION license is required.• The enable encrypted columns configuration parameter must be set.• The user creating the service key must have sso_role or keycustodian_role.• The master key must be created before the service key, if you are protecting service keys

with the master key.

Task

Use:create encryption key [syb_extpasswdkey | syb_syscommkey] [ with { static key | master key }]

By default, the static key encrypts the keys. To use the master key, use the with master keyparameter.

CHAPTER 5: Secure External Passwords and Hidden Text

30 SAP Adaptive Server Enterprise

When a syb_extpasswdkey is created, all external passwords in sysattributes arereencrypted with the new key using strong encryption.

When a syb_syscommkey is created, any subsequent execution of sp_hidetext uses thenew key with strong encryption. sp_hidetext must be executed on an existing databaseobject for the object to be encrypted with the new key. Because reencrypting hidden text mayinvolve very large amounts of data, database administrators should defer executingsp_hidetext to times when there is low system demand.

Note: You cannot use dual control with service keys.

Dropping Service Keysdrop encryption key ensures that there are no remaining references to the encryption key, andthen deletes it. You cannot drop a nonexistent syb_extpasswdkey orsyb_syscommkey_dddddd. To ensure that you delete all hidden text keys, use sp_encryptionto identify all existing keys.

PrerequisitesUsers must have a keycustodian_role or sso_role to delete an unused service key.

Task

Note: If your ASE_ENCRYPTION license has expired, encrypted data is no longer available,and you cannot execute the drop encryption key command. Contact SAP Technical Supportto obtain a temporary license.

To delete an unused service key for external logins, use:drop encryption key syb_extpasswdkey with password encryption downgrade

When with password encryption downgrade is specified, SAP ASE resets external loginpasswords with the algorithm used in versions earlier then 15.7. The Replication Agentpassword, and the CIS and RTMS external login passwords are reset to an invalid value. Theadministrator must manually reenter the passwords, after the key is dropped, to resume usageof the corresponding services.

To delete an unused single service key for hidden text, use:drop encryption key syb_syscommkey_dddddd

SAP ASE checks if there are any references to the specified key _dddddd, and drops the key ifno references are found.

Because syb_syscommkey_dddddd indicates a single key, you cannot specifysyb_syscommkey_dddddd with the with text encryption downgrade parameter.

To delete multiple keys:drop encryption key syb_syscommkey with text encryption downgrade

CHAPTER 5: Secure External Passwords and Hidden Text

Database Encryption 31

• If you specify with text encryption downgrade, you cannot specify a single service keywith syb_syscommkey_dddddd, only with syb_syscommkey.

• Without the “dddddd” suffix for the syb_syscommkey, SAP ASE reencrypts all thehidden text in syscomments with the algorithm used in versions earlier than 15.7, anddrops all syb_syscommkey_dddddd keys.

Modify Service KeysYou can regenerate syb_extpasswdkey or change its protection encryption from master key tostatic key, or vice versa. You cannot regenerate syb_syscommkey.

Changing the syb_extpasswdkeyYou can change syb_extpasswdkey from static to dynamic.

Change the syb_extpasswdkey using:alter encryption key syb_extpasswdkey [ with { static key | master key} ] { regenerate key [ with { static key | master key } ] | modify encryption [ with { static key | master key } ] }

where:

• The first instance of with {static key | master key} is optional and represents how thesyb_extpasswdkey is currently encrypted.

• The second instance of with {static key | master key} allows the administrator to changethe encryption on the regenerated key from static to dynamic, or vice versa. If you omit thisparameter, the regenerated key remains encrypted as it was before issuing this command.

• The third instance of with {static key | master key} changes the protection on the existingkey to use the static key or the master key as specified. If you omit this parameter, bydefault, the static key is used.

1. Creates a new service key for the external login passwords.

2. Reencrypts the passwords in sysattributes using the new key.

3. Drops the old key.

For example:

• Create a service key for external login passwords and encrypt all external login passwordswith the service key protected by the static key:create encryption key syb_extpasswdkey

• Regenerate the service key for external login passwords, leaving the new service keyprotected by the static key and reencrypting all external passwords encrypted by the oldservice key:alter encryption key syb_extpasswdkey regenerate key

• Change the protection of the service key to be encrypted by the master key. The service keydoes not change, and external login passwords are not reencrypted:

CHAPTER 5: Secure External Passwords and Hidden Text

32 SAP Adaptive Server Enterprise

alter encryption key syb_extpasswdkey modify encryption with master key

Note: Before issuing this command, ensure that the master key password has already beenentered by the master key owner.

Changing the syb_syscommkeyTo change the syb_syscommkey, create a new key and use sp_hidetext to reencrypt withthe new key.

For example:

• Example 1 – Create a new hidden text encryption key and encrypt all SQL text objects inthe syscomments table with the newly created key:

create encryption key syb_syscommkeygosp_hidetextgo

Note: When a new syb_syscommkey is created, it becomes the default key used bysp_hidetext in that database.

• Example 2 – Create a new hidden text encryption key, encrypt the text of a specific storedprocedure in syscomments with the newly created key, and protect the key with themaster key:create encryption key syb_syscommkey with master_keygosp_hidetext sp_mysprocgo

In this example, all other hidden text rows in syscomments remain encrypted with theprevious encryption key.

Service Keys with External PasswordsService keys decrypt the private-key password for network listeners using SSL. The private-key password initializes the SSL certificate.

SSL PasswordsHow SSL listeners start depends on if the service keys are encrypted by master key andwhether the master key is available.

If the service keys are encrypted by the master key and the master key is unavailable:

• When only SSL listeners are specified in the interfaces file, no user can log in to enter themaster key or dual master key password. The SAP ASE shuts down because it cannot startany listeners.

• When both SSL and non-SSL listeners are specified in the interfaces file, the non-SSLlistener can accept login requests. The SSL listeners are blocked until the master key

CHAPTER 5: Secure External Passwords and Hidden Text

Database Encryption 33

password is entered manually by an authorized user after connecting to the SAP ASE on anon-SSL listener port using:use mastergoset encryption passwd password for key mastergo

When the master key password is correctly entered, SAP ASE wakes the SSL listenerprocesses and they begin to accept incoming login requests.

LDAP PasswordsService keys are required to decrypt the password for LDAP administration accounts whenSAP ASE authenticates users during the LDAP user authentication process. Untilauthentication is complete, users cannot log in using LDAP.

An authorized user that can authenticate locally using SAP ASE authentication can manuallyenter the master key password using:use mastergoset encryption passwd password for key mastergo

See the Security Administration Guide.

Replication Agent PasswordsService keys decrypt passwords that initiate connections by Replication Agents on userdatabases. Agents that are configured to start automatically are blocked until an authorizeduser enters the master key password manually, if the service key is encrypted by a master key.

If a service key is in a user database that is replicated, the service key is also available on thereplicate database because the sysencryptkeys table that stores the encryption keys isalso replicated. The master key is also stored in the sysencryptkeys table that isreplicated, and also available on the replicate database. Because they are encrypted, servicekeys remain protected during the replication process.

After the SAP ASE has been started, an authorized user can connect and set the master keypassword for each database using:use mydbgoset encryption passwd password for key mastergo

A Replication Agent that is waiting for the master key password can be identified by the statusvalue “passwd sleep”:sp_whogofid spid status loginame origname hostname blk_spid dbname tempdbname cmd block_xloid

CHAPTER 5: Secure External Passwords and Hidden Text

34 SAP Adaptive Server Enterprise

--- ---- ----------- ------ -------- -------- ------------ ---------- --------- -----------0 38 passwd sleep NULL NULL NULL 0tdb4 tempdb REP AGENT 0

Service Keys Encrypted with the Master KeyIf your service keys are encrypted with the master key, the master key’s password must beentered into SAP ASE, either automatically or manually, depending on how you specify themaster key.

If you do not use automatic master key access, you typically enter the master key’s passwordwith set encryption passwd. However, if a service key is required to decrypt the private keypassword for network listeners during start-up, you can supply the master key at the commandline, or through a command line prompt.

Use the dataserver . . . -- master_key_password parameter to prompt for a master keypassword during SAP ASE start-up. The user issuing the -- master_key_password parametermust know the master key password for the master database and have physical access to theconsole and keyboard to enter the password.

If you do not include a password, -- master_key_password prompts for password at thecommand line. For example:dataserver --master_key_passwd -dd_master -eerrorlogmaster_key_passwd:_

The password characters do not appear, and the password is not validated until later in the SAPASE start-up sequence.

If you include the password with the -- master_key_password parameter:dataserver --master_key_passwd=mysecret -dd_master -eerrorlog

The password, mysecret, is blanked out in memory after it is read and used. However, theclear password is visible until the memory is blanked out.

If you enter the incorrect password, attempts to use service keys fail, and SAP ASE servicesthat require the service keys remain unavailable. After the server has started, an authorizeduser can connect and set the master key password in the master database with:use mastergoset encryption passwd password for key mastergo

If you have configured only SSL listeners and you enter the wrong password, SAP ASE shutsdown because it cannot start any listeners.

SAP recommends that you do not use passwords at the command line because the passwordsare visible:

CHAPTER 5: Secure External Passwords and Hidden Text

Database Encryption 35

• In memory that can be seen with the UNIX ps command• In memory, on an unattended terminal screen, or on disk in command history buffers and

files• On the screen

SAP encourages customer sites to prompt for passwords to avoid these vulnerabilities whenusing attended start-up.

CHAPTER 5: Secure External Passwords and Hidden Text

36 SAP Adaptive Server Enterprise

CHAPTER 6 Database Encryption

Encrypt databases when you must perform range searches over sensitive data columns, andwhen you lack the knowledge of the data model and cannot identify sensitive data columns.

Create an Encrypted DatabaseTo create a fully encrypted database, use the create database command.

Specify whether to encrypt a database when you create it, and data inserted into the database isautomatically encrypted. The size of the database does not change when it is encrypted, and allstorage access functions work identically whether a database is encrypted or not. The types ofdatabases that support encryption are:

• Normal user database• Temporary database• Archive database

You cannot encrypt an in-memory database.

To create an encrypted database, use:create [temporary] database database_name encrypt with key_name

Where:

• database_name is the name of the encrypted database you are creating.• key_name is the name of the database encryption key.

To create an encrypted archive database, use:create archive database database_name encrypt with key_name

Where:

• database_name is the name of the archive database you are creating• key_name is the same key that you used to encrypt the database that was backed up. SAP

ASE verifies that key_name matches during the database load. If it does not match, therestoration fails.

ExampleCreates an encrypted database called demodb with data on device demodev and log ondevice demologdev, using an encryption key called dbkey:

Database Encryption 37

create database demodb on demodev log on demologdev encrypt with dbkey

UsageThere is no special permission to use the encrypt with option of the create databasecommand. Users however, need select permission on the database encryption key to be able toreference it as the key_name.

Encrypt an Existing DatabaseYou can encrypt an unencrypted database using the alter database command.

Depending on the size of the database, encryption might can take a while. For this reason, thecommand returns as soon as the database is marked for encryption. Encryption occurs in thebackground and the process is transparent to users. To check on the status and progress ofdatabase encryption, run the sp_helpdb system procedure, the dbencryption_status() built-infunction, or the SAP Control Center user interface. Keep in mind:

• Database encryption occurs while the database is online. This means the database isaccessible by other users while it is being encrypted, and does not require you to put it intosingle-user mode.

• The encryption process does not interrupt any user queries, updates, or insert operations onthe database.

• You can suspend and resume database encryption, so that you can resume encrypting thedatabase after restarting SAP ASE.

• The encryption operation is executed page by page.• You cannot alter archive databases for encryption and decryption.• SAP ASE records the encryption progress of a database and provides utilities to report its

status.

Restrictions:

• You cannot encrypt the master, model, dbccdb, and dbccalt databases.• You cannot decrypt a database that is in the process of being encrypted, or encrypt a

database that is being decrypted.• You cannot unmount a database while it is in the process of being encrypted.• You cannot load another database on top of a database that is being encrypted.• Do not execute commands that shrink database size when the database is being encrypted.

The syntax is:alter database database_name{encrypt with key_name [parallel degree_of_parallelism]| resume encryption [parallel degree_of_parallelism]| suspend encryption}

where:

CHAPTER 6: Database Encryption

38 SAP Adaptive Server Enterprise

• encrypt with key_name instructs SAP ASE to encrypt the database usingkey_name.Specifically, the command retrieves the corresponding key ID from thesysencryptkeys system table in the master database and set the encrkeyidcolumn in its related sysdatabases row.

SAP ASE fails to run alter database and displays an error message if the database isalready:• Encrypted with another key.• Being encrypted.If you run this command on a partially encrypted database that is not currently beingencrypted, SAP ASE treats the command as if you specified the resume encryptionoption, as long as the key name is the same as the previously specified key.

• parallel degree_of_parallelism determines how many worker threads toinitiate for the task.Create a thread for each database storage virtual device, as long as the number is equal to orfewer than "number of worker processes" configuration. Thedegree_of_parallelism number should be no larger than the number of database devicesbecause additional worker threads do not improve encryption performance. If you do notspecify degree_of_parallelism, SAP ASE internally defines the value based on the numberof online engines, as well as how the database is distributed across various devices.

• resume encryption resumes the encryption process from the page where encryptionwas previously suspended.The command fails if:• There is an encryption process already running in SAP ASE.• Encryption was never started on the database.• The encryption process already completed.You can use parallel degree_of_parallelism with resume encrypt.

• suspend encryption terminates all encryption worker threads that are encryptingdata. SAP ASE records the progress of encryption so that resume encryption canrestart encryption where the previous encryption process stopped. SAP ASE ignores thiscommand if there is no encryption in progress.

This example alters an existing database called existdb for encryption using an encryptionkey called dbkey:

alter database existdb encrypt with dbkey

The example does not specify the parallel degree, leaving it up to SAP ASE to determine howmany worker threads should be initiated to encrypt existdb in parallel.

In addition to the parallel degree, another major factor that affects database encryptionperformance is the buffer pool size. A sufficient buffer cache and appropriate size of bufferpool enable SAP ASE to load a large chunk of pages into memory for every disk read, performencryption, and write them back.

CHAPTER 6: Database Encryption

Database Encryption 39

The following example shows the steps you can take to configure both the buffer cache andbuffer pool size for a database called demodb that will be encrypted:

1. Create a specific data cache for demodb:

sp_cacheconfig demodb_cache, '10M'

This creates a named buffer cache called demodb_cache with 10MB of space fordatabase pages.

2. Create the specific size of buffer pool . The buffer pool size should be 8 times of databasepage size. For example, the database page size is 2K by default, therefore the buffer poolssize should be 8 x 2 = 16K:sp_poolconfig demodb_cache, '10M' , '16k'

This creates a 10MB buffer pool of buffers with a size that is 16K in the named cache calleddemodb_cache.

3. Bind the database to the buffer cache:sp_bindcache demodb_cache, demo_db

Encryption Status and ProgressTo obtain information on whether a database is encrypted or not, as well as how far along theencryption process has gone on a database being encrypted, use the sp_helpdb systemprocedure or the dbencryption_status built-in function.

• sp_helpdb – the syntax is the following, where database_name is the name of thedatabase:sp_helpdb database_name

• dbencryption_status – use status to get information on whether a database is encrypted,and progress to find out how far along the encryption process has gone:• select dbencryption_status(“status”, db_id(“existdb”))• select dbencryption_status(“progress”, db_id(“existdb”))

Performance ConsiderationsWhen an existing database is being encrypted, it is still kept online. Take performance issuesinto consideration to mitigate the impact on user access to the database, as well as general SAPASE response time.

Factors to take into account for good database encryption performance include:

• The number of SAP ASE engines on a multiprocessor machine• The number of disks the database is stored across• The buffer pool size associated with the database

Specifying the parallel degree value in alter database for encryption or, decryption,essentially tells SAP ASE how many worker threads to initiate when executing the operation.

CHAPTER 6: Database Encryption

40 SAP Adaptive Server Enterprise

Since worker threads run concurrently, it is better when they are distributed across multipleCPUs. At the same time, it is better to avoid overwhelming CPU resources, since this couldreduce the general response time from SAP ASE. For this reason, take the number of SAPASE engines into consideration when deciding on the parallel degree value.

Device I/O is a major bottleneck during database encryption. SAP ASE can tackle this fromtwo angles:

• If every separate device is assigned a worker thread, device I/O can be carried outindependently and concurrently for best throughput. Therefore parallel degree shouldconsider the number of disks the database is stored across.

• Performance will benefit if a big chunk of pages can be processed for every device read/write. The database must be online while the encryption/decryption is in progress. For thisreason, instead of allocating a proprietary buffer, existing buffer manager mechanism hasto be leveraged to solve synchronization problem. In this respect, you can create sufficientbuffer cache and large I/O size of buffer pool to help SAP ASE improve its encryptionperformance.

This example shows how to configure both the buffer cache and pool size to fully encrypt adatabase called demodb, which has its data and log distributed across 11 devices:

> select dbid, segmap, lstart, size, vstart, vdevno from sysusages where dbid=db_id('demodb')

dbid segmap lstart size vstart vdevno------ ------ ---------- ---------- ----------- ----------- 4 3 0 92160 0 1 4 4 92160 30720 0 2 4 3 122880 184320 92160 1 4 4 307200 61440 30720 2 4 3 368640 419840 276480 1 4 4 788480 61440 92160 2 4 3 849920 122880 696320 1 4 4 972800 153600 153600 2 4 3 1126400 819200 819200 1 4 3 1945600 1638400 0 3 4 3 3584000 1638400 0 4 4 3 5222400 1638400 0 5 4 3 6860800 1638400 0 6 4 3 8499200 1638400 0 7 4 3 10137600 1638400 0 8 4 3 11776000 1638400 0 9 4 3 13414400 1638400 0 10 4 3 15052800 1638400 0 11 4 4 16691200 204800 307200 2

1. Configure buffer cache and buffer pool size:a. Create a specific data cache for demodb:

sp_cacheconfig demodb_cache, '100M'

CHAPTER 6: Database Encryption

Database Encryption 41

This creates a buffer cache named demodb_cache that has 100MB of space fordatabase pages.

b. Create the specific size of buffer pool, where the buffer pool size is 8 times the size ofthe database page size:sp_poolconfig demodb_cache, '100M' , '16k'

Since the default database page size is 2K, the buffer pool size should be 8 X 2 =16KB.This creates a 100MB buffer pool with 16K buffers in the named cachedemodb_cache.

c. Bind the database to the buffer cache:sp_bindcache demodb_cache, demo_db

This binds the database demo_db to the created buffer cache demodb_cache.

2. Determine what parallel degree to use. In this example, there are 8 SAP ASE enginesconfigured:[Thread Pool:syb_default_pool]

Number of threads = 8The maximum number of worker thread should not exceed 8.In the meantime, with SAP ASE using 11 database devices, it needs, at most, 11 workerthreads to perform device I/O in parallel. Since 11 worker threads would strain the eightengines, the parallel degree should be set to 8. However to allow SAP ASE to maintain itsresponse time and perform other operations, avoid occupying all of its CPU resources byselecting a parallel degree of 6.a. Make sure sufficient worker threads are configured:

sp_configure 'number of worker processes', 6b. Alter database demodb for encryption:

alter database demodb encrypt with dbkey parallel degree 6

sp_who shows 6 worker threads:>sp_whofid spid status loginame origname hostname blk_spid dbname tempdbname cmd block_xloid threadpool------ -------- ---------------- ---------…… 0 16 sleeping NULL NULL NULL 0 master master DB ENCRYPTION CONTROLLER 0 NULL 16 1 sleeping NULL NULL NULL 0 master master WORKER PROCESS 0 NULL 16 17 sleeping NULL NULL NULL 0 master

CHAPTER 6: Database Encryption

42 SAP Adaptive Server Enterprise

master WORKER PROCESS 0 NULL……

sp_helpdb can report the encryption progress and status:1> sp_helpdb demodb2> goname db_size owner dbid created durability lobcomplvl inrowlen status-------- ---------- ------ ----- ------------- ---------- ---------- -------- ----------------demodb 33000.0 MB sa 4 Sept 27, 2013 full 0 NULL encryption in progress: 18%

You can also use the dbencryption_status function to get encryption status andprogress:1> select dbencryption_status("status", db_id('demodb'))2> go-----------21> select dbencryption_status("progress", db_id('demodb'))2> go-----------21

This shows that 21 percent of database pages has been encrypted.You can also use dbencryption_status to find the progress on a specific fragment:1> select dbencryption_status("progress", db_id('demodb'), 92160)2> go-----------83

This shows that 83 percent of pages in the fragment with a logical page start of 92160has been encrypted.

Encrypted databases consume more buffers for encryption and decryption than nonencrypteddatabases. If clean buffers are unavailable because of encryption and decryption:

• Increase the buffer pool size and the buffer pool wash• Configure housekeeper free write percent to a value that allows the housekeeper task to

wash buffers more frequently

Suspend the Encryption ProcessTo stop encrypting a database in the process of being encrypted, use the suspend encryptoption of the alter database command.

alter database database_name suspend encryption

CHAPTER 6: Database Encryption

Database Encryption 43

The quiesce database Command and Fully Encrypted DatabasesWhen you run the quiesce database command on a database that is being encrypted, SAPASE puts the encryption process on hold.

You need not run the suspend encryption option of alter database after you runquiesce database; quiesce database automatically suspends the I/O operation on thedatabase.

After the quiesce mode is released, the task of encrypting (or decrypting) resumesautomatically; you need not run the resume encryption option in the alter database.

Resume the Encryption ProcessTo resume encrypting a database that had its encryption process interrupted or suspended, usethe resume encryption option of the alter database command.

alter database database_name resume encryption [parallel degree_of_parallelism]

Decrypt an Encrypted DatabaseTo decrypt a fully encrypted database, use the alter database command.

The syntax is:alter database database_name {decrypt [with key_name] [parallel degree_of_parallelism]| resume decryption [parallel degree_of_parallelism]| suspend decryption}

where:

• database_name – is the name of the fully encrypted database you want to decrypt.• key_name – (optional) is the same database encryption key you used to encrypt the

database. If you specify a different key name, the command fails and SAP ASE displays anerror message.

• resume decryption – resumes the decryption process for the database in which anearlier decryption process has been suspended. SAP ASE ignores this command if thedatabase_name is already completely decrypted.

• parallel degree_of_parallelism – specifies how many worker threads toinitiate for the task.

• suspend decryption – terminates the decryption process. SAP ASE records wherethe process was stopped, so that resume decrypt can restart the decryption process atthe correct place in the database.

You must have select permission on the database's key_name to use this command.

CHAPTER 6: Database Encryption

44 SAP Adaptive Server Enterprise

Recover Fully Encrypted DatabasesIf SAP ASE cannot retrieve the database encryption key during start-up because the master ordual master key is unavailable, SAP ASE ignores the encrypted database.

SAP ASE needs access to the database encryption key to know what to do with fully encrypteddatabases. The database encryption key itself is also encrypted, and is decrypted by the masterkey.

To connect to the server after you restart SAP ASE, the password holder for the master or dualmaster key can set the encryption password:set encryption passwd for key [dual] master

This allows the master key to decrypt the database encryption key, at which point the databaseencryption key can bring the fully encrypted database online:online database encrypted_database_name

Database recovery then occurs as the server comes back online.

You can also set up an automatic recovery; see Starting Adaptive Server in Unattended Start-Up Mode in the Encrypted Columns Users Guide.

Back Up (Dump) a Fully Encrypted DatabaseBacking up a fully encrypted database is the same as for normal, unencrypted databases, sincethe encryption process is performed transparently.

To load a back-up dump of an encrypted database, it must use the same encryption key that wasused to encrypt the dump.

The database encryption key is stored in the master database, outside of the database you arebacking up. For this reason, the backup process is not automatically applied to the databaseencryption key when you execute the dump database command; you must independentlyback up the database encryption key and the master key separately from the database backup.

To back up the key values, either:

• Use the ddlgen utility to generate a DDL statement, or;• Back them up directly.

CHAPTER 6: Database Encryption

Database Encryption 45

Back Up the Database Encryption KeyTo resume recoverability, you must back up the database encryption key, the master or dualmaster key, and the encrypted database.

This example uses the ddlgen utility to generate SQL statements on database encryption keys:ddlgen -Usa -P -Sserver -TEK -Nmaster.owner.dek_name

The syntax is similar when generating SQL statements for the [dual] master key.

Restore (Load) Backups of Fully Encrypted DatabasesRestore a fully encrypted database as you would a normal, unencrypted database.

Before you can load an encrypted database dump:

1. Restore the master key and database encryption key.2. Create the target database for encryption using the same database encryption key you used

for the database you are loading.

Use this command to restore your encrypted database, where database_name is the name ofthe encrypted database you are restoring:load database database_name

Note: You cannot use the verification option (load database database_namewith verify only = full) with encrypted databases. When you specify this option,Backup Server reads all rows and checks that the row formats are valid. Since Backup Servercannot understand encrypted text, the command fails and Backup Server displays an errormessage.

When you perform load database to restore an encrypted database, SAP ASE verifies that thetaget database:

• Is an encrypted database. If it is not, SAP ASE displays an error message and the loaddatabase command fails.

• Has the correct database encryption key. If the database encryption key does not match,SAP ASE displays an error message.

Loading Behavior of Encrypted DatabasesLoading behavior differs, depending on the encryption status of both the target database andthe database or transaction log being restored.

CHAPTER 6: Database Encryption

46 SAP Adaptive Server Enterprise

Loading Be-havior

UnencryptedTarget Data-base

EncryptedTarget Data-base

Partially En-crypted Tar-get Database

Partially De-crypted Tar-get Database

Unencrypted Da-tabase Dump

Allowed. Allowed only ifusing the withoverrideclause. Dump se-curity status is re-flected in targetdatabase.

Allowed only ifusing the withoverrideclause. Dump sta-tus is reflected intarget database.

Allowed only ifusing the withoverrideclause. Dump se-curity status is re-flected.

UnencryptedTransactionDump

Allowed. Allowed. Marksthe target data-base as partiallyencrypted.

Allowed. The tar-get database re-tains its status aspartially encryp-ted.

Allowed. The tar-get database re-tains its status aspartially encryp-ted.

Encrypted Data-base Dump

Not allowed. Allowed. Allowed. Dumpsecurity status isreflected in thetarget database.

Allowed only ifusing the withoverrideclause. Dump se-curity status is re-flected in the tar-get database.

Encrypted Trans-action Dump

Not allowed. Allowed. Allowed. The tar-get database re-tains its status aspartially encryp-ted.

Not allowed.

Partially Encryp-ted DatabaseDump

Not allowed. Allowed. Dumpsecurity status isreflected in thetarget database.

Allowed. The tar-get database re-tains its status aspartially encryp-ted.

Allowed only ifusing the withoverrideclause. Dump sta-tus is reflected inthe target data-base.

Partially Encryp-ted TransactionDump

Not allowed. Allowed. Dumpsecurity status isreflected in thetarget database.

Allowed. The tar-get database re-tains its status aspartially encryp-ted.

Not allowed.

CHAPTER 6: Database Encryption

Database Encryption 47

Loading Be-havior

UnencryptedTarget Data-base

EncryptedTarget Data-base

Partially En-crypted Tar-get Database

Partially De-crypted Tar-get Database

Partially Decryp-ted DatabaseDump

Not allowed. Allowed only ifusing the withoverrideclause. Dumpstatus is reflectedin the target data-base.

Allowed only ifusing the withoverrideclause. Dump se-curity status is re-flected in the tar-get database.

Allowed. The tar-get database re-tains its status aspartially decryp-ted.

Partially Decryp-ted TransactionDump

Not allowed. Not allowed. Not allowed. Allowed. The tar-get database re-tains its status aspartially decryp-ted.

Dropping a Database That is Being EncryptedWhen you execute the drop database command on a database that is being encrypted ordecrypted, drop database terminates the encryption/decryption process, searches thesysattributes system table, cleans up all the progress information, and then drops thedatabase.

Mounting and Unmounting a Fully Encrypted DatabaseYou cannot mount a database that is being encrypted or decrypted; you also cannot mount anencrypted database.

Do not use the umount database command on an encrypted database; the command fails andSAP ASE displays a message similar to:Could not unmount encrypted database 'mydatabase'.

To unmount an encrypted database, decrypt it first.

Archive Databases and Full EncryptionArchive databases are read-only. The encryption syntax indicates that an archive database canload an encrypted database dump.

As with database backups and loads, restore the master key and database encryption key, andassociate the DEK with the archive database.

CHAPTER 6: Database Encryption

48 SAP Adaptive Server Enterprise

To dump or load a fully encrypted archive database, perform the same steps as with normaldatabases.

To create an archive database, use:create archive database database_name encrypt with key_name

where:

• database_name is the name of the archive database you are creating• key_name is the same key that you used to encrypt the database that was backed up

(dumped). SAP ASE verifies that key_name matches during the database dump. If it doesnot match, the restoration fails.

Unlike normal databases, an archive database provides a modified page section that storespage modification or allocation information due to redos/undos and transaction loadingoperations. When you encrypt an archive database, encrypt the data in the modified pagesection as well, using the database encryption key from the archive database.

There is no special permission to use the encrypt with option of the create archivedatabase command. Users however, need select permission on the database encryption key toreference it as the key_name.

CHAPTER 6: Database Encryption

Database Encryption 49

CHAPTER 6: Database Encryption

50 SAP Adaptive Server Enterprise

CHAPTER 7 Column Encryption

Certain datatypes can be encrypted.

You can encrypt:

• int, smallint, tinyint• unsigned int, unsigned smallint, unsigned tinyint• bigint, unsigned bigint• decimal and numeric• float4 and float8• money, smallmoney• date, time, smalldatetime, datetime• char and varchar• unichar, univarchar• binary and varbinary• bit

Encrypting Columns on New TablesTo encrypt columns in a new table, use the encrypt column qualifier on the create tablestatement.

The following partial syntax for create table includes only clauses that are specific toencryption. See the Reference Manual: Commands for the complete syntax.create table table_name(column_name. . .

[constraint_specification][encrypt [with [database.[owner].]keyname]][, next_column_specification . . .])

• keyname – identifies a key created using create encryption key. The creator of the tablemust have select permission on keyname. If keyname is not supplied, SAP ASE looks for adefault key created using the as default clause on the create encryption key.

Note: You cannot encrypt a computed column, and an encrypted column cannot appear in anexpression that defines a computed column. You cannot specify an encrypted column in thepartition_clause of a table.

The following example creates two keys: a database default key, and another key (cc_key)which you must name in the create table command. Both keys use default values for length

Database Encryption 51

and an initialization vector. The ssn column in the employee table is encrypted using thedefault key, and the creditcard column in the customer table is encrypted withcc_key:

create encryption key new_key as default for AEScreate encryption key cc_key

create table employee_table (ssn char(15) encrypt, ename char(50), ...))

create table customer (creditcard char(20) encrypt with cc_key, cc_name char(50), ...)

This example creates key k1, which uses nondefault values for the initialization vector andrandom pad. The employee esalary column is padded with random data before encryption:

create encryption key k1 init_vector null pad randomcreate table employee (eid int, esalary money encrypt with k1, ...)

Specifying Encryption on select intoBy default, select into creates a target table without encryption, even if the source table hasone or more encrypted columns.

To encrypt any column in the target table, you must qualify the target column with the encryptclause, as shown:select [all|distinct] column_list into table_name [(colname encrypt [with [[database.][owner].]keyname] [, colname encrypt [with[[database.][owner].]keyname]])] from table_name | view_name

You can encrypt a specific column in the target table even if the data was not encrypted in thesource table. If the column in the source table is encrypted with the same key specified for thetarget column, SAP ASE optimizes processing by bypassing the decryption step on the sourcetable and the encryption step on the target table.

The rules for specifying encryption on a target table are the same as those for encryptionspecified on create table in regard to:

• Allowable datatypes on the columns to be encrypted• The use of the database default key when the keyname is omitted• The requirement for select permission on the key used to encrypt the target columns.

The following example selects the encrypted column creditcard from thedaily_xacts table and stores it in encrypted form in the #bigspenders temporarytable:select creditcard, custid, sum(amount) into #bigspenders (creditcard encrypt with cust.dbo.new_cc_key) from daily_xacts group by creditcard having sum(amount) > $5000

CHAPTER 7: Column Encryption

52 SAP Adaptive Server Enterprise

Note: select into requires column-level permissions, including decrypt, on the source table.

Encrypting Columns in Existing TablesTo encrypt columns in existing tables, use the modify column option on the alter tablestatement with the encrypt clause.

The syntax is:

alter table table_name modify column_name [encrypt [with [[database.][owner].]keyname]]

where keyname identifies a key created using create encryption key. The creator of the tablemust have select permission on keyname. If keyname is not supplied, SAP ASE looks for adefault key created using the as default clause on the create encryption key.

See the Reference Manual: Commands.

There are restrictions for modifying encrypted columns:

• You cannot modify a column for encryption or decryption on which you have created atrigger. You must:1. Drop the trigger.2. Encrypt or decrypt the column.3. Re-create the trigger.

• You cannot change an existing encrypted column, modify a column for encryption ordecryption on a table, or modify the type of an encrypted column if that column is a key in aclustered or placement index. You must:1. Drop the index.2. Alter the table/modify the type of column.3. Re-create the index.

You can alter the encryption property on a column at the same time you alter other attributes.You can also add an encrypted column using alter table.

For example:alter table customer modify custid null encrypt with cc_key alter table customer add address varchar(50) encrypt with cc_key

Index Creation and Constraints on Encrypted ColumnsYou can create an index on an encrypted column if the encryption key has been specifiedwithout any initialization vector or random padding.

An error occurs if you execute create index on an encrypted column that has an initializationvector or random padding. Indexes on encrypted columns are generally useful for equality and

CHAPTER 7: Column Encryption

Database Encryption 53

nonequality matches. However, indexes are not useful for matching case-insensitive data, orfor range searches of any data.

Note: You cannot use an encrypted column in an expression for a functional index.

In the following example, cc_key specifies encryption without using an initialization vectoror padding. This allows an index to be built on any column encrypted with cc_key:

create encryption key cc_key with init_vector null

create table customer(custid int, creditcard varchar(16) encrypt with cc_key)

create index cust_idx on customer(creditcard)

You can encrypt a column that is declared as a primary or unique key.

You can define referential integrity constraints on encrypted columns when:

• Both referencing and referenced columns are encrypted with the same key.• The key used to encrypt the columns specifies init_vector null and pad random has not

been specified.

Referential integrity checks are efficient because they are performed on cipher text values.

In this example, ssn_key encrypts the ssn column in both the primary and foreign tables:

create encryption key ssn_key for AES with init_vector nullcreate table user_info (ssn char(9) primary key encrypt with ssn_key, uname char(50), uaddr char(100))create table tax_detail (ssn char(9) references user_info encrypt with ssn_key, return_info text)

Domain Creation and Access Rules on Encrypted ColumnsYou can create domain rules, check constraints, or access rules on encrypted columns.However, decrypt permission is required on an encrypted column when it is used in target list,where clause, and so on.

This example creates the rule_creditcard rule on the creditcard column, whichhas a domain rule defined:create encryption key cc_key with init_vector null

create table customer(custid int, creditcard varchar(16) encrypt with cc_key)

create rule rule_creditcardas @value like '%[0-9]'sp_bindrule rule_creditcard, creditcard

CHAPTER 7: Column Encryption

54 SAP Adaptive Server Enterprise

bcp in -C bypasses the domain rule or check constraint for encrypted columns because SAPASE uses fast bcp with bcp in -C. bcp out -C generates error number 2929 if an access ruleexists on the encrypted column. SAP ASE bypasses the rule or constraint for insert andupdate statements when you replicate encrypted columns with domain rules or checkconstraints. SAP ASE also generates error number 2929 when you replicate encryptedcolumns with access rules for update, delete, or select statements.

Decrypt PermissionUsers must have decrypt permission to select plain text data from an encrypted column, or tosearch or join on an encrypted column.

The table owner or a user with the sso_role uses grant decrypt to grant explicit permissionto decrypt one or more columns in a table to other users, groups, and roles. Decrypt permissionmay be implicitly granted when a procedure or view owner grants:

• exec permission on a stored procedure or user-defined function that selects from anencrypted column where the owner of the procedure or function also owns the tablecontaining the encrypted column

• decrypt permission on a view column that selects from an encrypted column where theowner of the view also owns the table

In both cases, decrypt permission need not be granted on the encrypted column in the basetable.

The syntax is:

grant decrypt on [owner.] table [( column[{,column}])] to user| group | role [with grant option]

Granting decrypt permission at the table or view level grants decrypt permission on allencrypted columns in the table.

To grant decrypt permission on all encrypted columns in the customer table, enter:

grant decrypt on customer to accounts_role

The following example shows the implicit decrypt permission of user2 on the ssn columnof the base table “employee”. user1 sets up the employee table and the employee_viewas follows:create table employee (ssn varchar(12)encrypt, dept_id int, start_date date, salary money)

create view emp_salary as select ssn, salary from employee

grant select, decrypt on emp_salary to user2

CHAPTER 7: Column Encryption

Database Encryption 55

user2 has access to decrypted Social Security Numbers when selecting from theemp_salary view:

select * from emp_salary

Note: grant all on a table or view does not grant decrypt permission. Decrypt permission mustbe granted separately.

Users with only select permission on an encrypted column can still process encrypted columnsas cipher text through the bulk copy command. Additionally, if an encrypted column specifiesa decrypt default value, the column can be named in a select target list or in a where clause byusers who do not have permission to decrypt data.

See also• Restrict Decrypt Permission on page 56• Default Values Returned Instead of Decrypted Data on page 57

Revoking Decryption Permissionrevoke decrypt on revokes a user's decryption permission.

The syntax is:

revoke decrypt on [ owner] table[( column[ {,column}])] from user | group | role

For example:revoke decrypt on customer from public

Restrict Decrypt PermissionRestrict access to private data from the database owner by setting the restricted decryptpermission configuration parameter.

SAP ASE protects data privacy from the powers of the administrator even if you use the masterkey or system encryption password for key protection. If you prefer to avoid passwordmanagement and use the master key or the system encryption password to protect encryptionkeys, you can restrict access to private data from the database owner by setting the restricteddecrypt permission configuration parameter. System security officers (SSOs) can use thisparameter to control which users have decrypt permission. Once restricted decryptpermission is enabled, the SSO is the only user who receives implicit decrypt permission andwho has implicit privilege to grant that permission to others. The SSO determines which usersreceive decrypt permission, or delegates this job to another user by granting decryptpermission with the with grant option. Table owners do not automatically have decryptpermission on their tables.

Users with execute permission on stored procedures or user-defined functions do not haveimplicit permission to decrypt data selected by the procedure or function. Users with decrypt

CHAPTER 7: Column Encryption

56 SAP Adaptive Server Enterprise

permission on a view column do not have implicit permission to decrypt data selected by theview.

Note: Users with aliases continue to inherit all decrypt permissions of the user to whom theyare aliased. set proxy/set user statements continue to allow the administrator or databaseowner the decrypt permissions of the user whose identity is assumed by this command.

If you are using restricted decrypt permission, you can assign the privileges for creating thetask’s schema and managing keys as follows:

• System security officer – configures restricted decrypt permission, creates encryptionkeys, grants select permission on keys to the database owner, and grants decryptpermission to the end user.

• Database owner – creates the schema and loads data.

See also• Protect Encryption Keys with the Master Key on page 16

• Decrypt Permission on page 55

Default Values Returned Instead of Decrypted DataWhen users who are not permitted to see confidential data run queries against encryptedcolumns, they see the decrypt defaults instead of the decrypted data. Decrypt defaults allowlegacy applications and reports to run without error, even for users who are not permitted to seeconfidential data.

See also• Decrypt Permission on page 55

Defining Decrypt DefaultsThe decrypt_default parameter for create table and alter table allows an encrypted column toreturn a user-defined value when a user without decrypt permission attempts to selectinformation from the encrypted column.

Doing so avoids error message 10330:Decrypt permission denied on object <table_name>, database <database name>, owner <owner name>

Using decrypt defaults on encrypted columns allows existing reports to run to completionwithout error, and allows users to continue seeing the information that is not encrypted. Forexample, if the customer table contains the encrypted column creditcard, you candesign the table schema so that:select * from customer

CHAPTER 7: Column Encryption

Database Encryption 57

Returns the value “****************” instead of returning the credit card data to userswho lack decrypt permission.

Add a decrypt default on a new column with create table. The partial syntax for create tableis:create table table_name (column_name datatype [[encrypt [with keyname]] [decrypt_default value]], ....)

• decrypt_default – specifies that this column returns a default value on a select statementfor users who do not have decrypt permissions.

• value – is the value SAP ASE returns on select statements instead of the decrypted value. Aconstant-valued expression cannot reference a database column but it can include a user-defined function which itself references tables and columns. The value can be NULL onnullable columns only, and the value must be convertible into the column’s datatype.

For example, the ssnum column for table t2 returns “?????????” when a user withoutdecrypt permissions selects it:create table t2 (ssnum char(11) encrypt decrypt_default '???????????', ...)

To add encryption and a decrypt default value to an existing column not previously encrypted,use:alter table table_name modify column_name [type] [[encrypt [with keyname]] [decrypt_default value]], …

This example modifies the emp table to encrypt the ssn column and specifies decrypt default:

alter table emp modify ssn encrypt with key1 decrypt_default '000-00-0000'

To add a decrypt default to an existing encrypted column or change the decrypt default valueon a column that already has a decrypt default, use:alter table table_name replace column_name decrypt_default value

This example adds a decrypt default to the salary column, which is already encrypted:

alter table employee replace salary decrypt_default $0.00

This example replaces the previous decrypt_default value with a new value and uses auser-defined function (UDF) to generate the default value:alter table employee replace salary decrypt_default dbo.mask_salary()

To remove a decrypt default from an encrypted column without removing the encryptionproperty, use:alter table table_name replace column_name drop decrypt_default

This example removes the decrypt default for salary without removing the encryptionproperty:

CHAPTER 7: Column Encryption

58 SAP Adaptive Server Enterprise

alter table employee replace salary drop decrypt_default

Permissions and Decrypt DefaultYou must grant decrypt permission on encrypted columns before users or roles can select orsearch on encrypted data in those columns. If an encrypted column has a decrypt defaultattribute, users without decrypt permission can run queries that select or search on thesecolumns, but the plain text data is not displayed and is not used for searching.

In this example, the owner of table emp allows users with the hr_role to view emp.ssn.Because the ssn column has a decrypt default, users who have only select permission on empand who do not have the hr_role see the decrypt_default value only and not the actualdecrypted data.create table emp (name char(50), ssn (char(11) encrypt decrypt_default '000-00-000', ...)grant select permission on table emp to publicgrant decrypt on emp(ssn) to hr_role

If you have the hr_role and select from this table, you see the values for ssn:

select name, ssn from empname ssn------------------------------ ------------Joe Cool 123-45-6789Tinna Salt 321-54-9879

If you do not have the hr_role and select from the table, you see the decrypt default:select name, ssn from empname ssn------------------------------ -----------Joe Cool 000-00-0000Tinna Salt 000-00-0000

order by clauses have no effect on the result set if you do not have the hr_role for this table.

Columns with Decrypt Default ValuesThere are no restrictions on how you use columns with decrypt default in a query. You can usethem in a target list expression, where clause, order by, group by, or subquery.

Although expressions on the decrypt default constant value may not have a practical use,placing a decrypt default on a column does not impose any syntactic restrictions on use of thecolumn in a Transact-SQL statement.

This example uses a select statement on a column with a decrypt default value in the targetlist:create table emp_benefits (col1 name char(30), salary float encrypt decrypt_default -99.99)

CHAPTER 7: Column Encryption

Database Encryption 59

select salary/12 as monthly_salary from emp_benefits where name = 'Bill Smith'

When you perform the select statement against this table, but do not have decrypt permission,you see:

monthly_salary---------------------8.332500

When SAP ASE returns a column’s decrypt default value on a select into command, thisdecrypt default value is inserted into the target table. However, the target column does notinherit the decrypt default property. You must use alter table to specify a decrypt default on thetarget table.

Use sp_checksource to view decrypt default source text defined on encrypted columns.

Decrypt Default Columns and Query QualificationsIf you use a column with the decrypt default property in a where clause, the qualificationevaluates to false if you do not have decrypt permission.

These examples use the emp table described above. Only users with the hr_role have decryptpermission on ssn.

• If you have the hr_role and issue the following query, SAP ASE returns one row.select name from emp where ssn = '123-456-7890'name------------------------------ Joe Cool

• If you do not have the hr_role, SAP ASE returns no rows:select name from emp where ssn = '123-456-7890'name------------------------------ (0 rows affected)

• If you have the hr_role and include an or statement on a nonencrypted column, SAP ASEreturns the appropriate rows:select name from emp where ssn = '123-456-7890' orname like 'Tinna%'name------------------------------ Joe CoolTinna Salt

• If you do not have the hr_role and issue the same command, SAP ASE returns only onerow:select name from emp where ssn = '123-456-7890' or name like 'Tinna%'

CHAPTER 7: Column Encryption

60 SAP Adaptive Server Enterprise

name------------------------------ Tinna Salt

In this case, the qualification against the encrypted column with the decrypt defaultproperty evaluates to false, but the qualification against the nonencrypted columnsucceeds.If you do not have decrypt permission on an encrypted column, and you issue a group bystatement on this column with a decrypt default, SAP ASE groups by the decrypt defaultconstant value.

See also• Encrypted Columns Process on page 71

decrypt default and Implicit GrantsIf you do not have explicit or implicit permission on a table, SAP ASE returns the decryptdefault value.

In this example (using the emp table), the database owner creates the p_emp procedure whichselects from the emp table that he or she owns:

create procedure p_emp as select name, ssn from emp grant exec on p_emp to corp_role

Because you have the corp_role, you have implicit select and decrypt permission on empexec p_empname ssn------------------------------ ------------Tinna Salt 123-45-6789Joe Cool 321-54-9879

If the emp table and p_emp stored procedure have been created by different users, you musthave select permission on emp to avoid permissions errors. If you have select permission butnot decrypt permission, SAP ASE returns the decrypt default value of emp.ssn.

In this next example, “joe,” who does not own the database, creates the v_emp view, whichselects from the emp table. Any permissions granted on the view are not implicitly applied tothe base table.create view v_emp as select name, ssn from emp grant select on v_emp to emp_rolegrant select on emp to emp_rolegrant decrypt on v_emp to emp_role

Although you have the emp_role, when you issue:select * from joe.v_emp

CHAPTER 7: Column Encryption

Database Encryption 61

SAP ASE returns the following because decrypt permission on dbo.emp.ssn has not beengranted to the emp_role, and there is no implicit grant to emp_role on dbo.emp.ssn:

name ssn-------------------------- ---------------Tinna Salt 000-00-0000Joe Cool 000-00-0000

decrypt default and insert, update, and delete StatementsThe decrypt default parameter does not affect target lists of insert and update statements. Ifyou use a column with a decrypt default value in the where clause of an update or deletestatement, SAP ASE may not update or delete any rows.

For example, when using the emp table and permissions from the previous examples, if you donot have the hr_role and issue the following query, SAP ASE does not delete the user’s name:

delete emp where ssn = '123-45-6789'(0 rows affected)

Decrypt default attributes may indirectly affect inserting and updating data into anapplication, particularly one with a graphical user interface (GUI) process:

1. Selects data.2. Allow a user to update any of the data.3. Applies the changed row back to the same or a different table.

If the user does not have decrypt permission on the encrypted columns, the applicationretrieves the decrypt default value and may automatically write the unchanged decrypt defaultvalue back to the table. To avoid overwriting valid data with decrypt default values, use a checkconstraint to prevent these values from being automatically applied. For example:create table customer (name char(30)),cc_num int check (cc_num != -1) encrypt decrypt_default -1

If the user does not have decrypt permission on cc_num and selects data from thecustomer table, this data appears:

name cc_num-------------------- ------------Paul Jones -1Mick Watts -1

However, if the user changes a name and updates the database, and the application attempts toupdate all fields from the values displayed, the default value for cc_num causes SAP ASE toissue error 548:

"Check constraint violation occurred, dbname =<dbname>, table name = <table_name>, constraint name =<internal_constraint _name>"

Setting a check constraint protects the integrity of the data. For a better solution, you can filterthese updates when you write the application’s logic.

CHAPTER 7: Column Encryption

62 SAP Adaptive Server Enterprise

Removing Decrypt DefaultsMultiple commands allow you to remove decrypt defaults.

Remove the decrypt default using any of these commands:

• drop table

• alter table .. modify .. drop col

• alter table .. modify .. decrypt

• alter table .. replace .. drop decrypt_default

For example, to remove the decrypt default attribute from the ssn column, enter:

alter table emp replace ssn drop decrypt_default

If you do not have the hr_role and select from the emp table after the table owner removed thedecrypt default, SAP ASE returns error message 10330.

Length of Encrypted ColumnsDuring create table, alter table, and select into operations, SAP ASE calculates themaximum internal length of the encrypted column. To make decisions on schemaarrangements and page sizes, the database owner must know the maximum length of theencrypted columns.

AES is a block-cipher algorithm. The length of encrypted data for block-cipher algorithms is amultiple of the block size of the encryption algorithm. For AES, the block size is 128 bits, or 16bytes. Therefore, encrypted columns occupy a minimum of 16 bytes with additional spacefor:

• The initialization vector. If used, the initialization vector adds 16 bytes to each encryptedcolumn. By default, the encryption process uses an initialization vector. Specifyinit_vector null on create encryption key to omit the initialization vector.

• The length of the plain text data. If the column type is char, varchar, binary, orvarbinary, the data is prefixed with 2 bytes before encryption. These 2 bytes denote thelength of the plain text data. No extra space is used by the encrypted column unless theadditional 2 bytes result in the cipher text occupying an extra block.

• A sentinel byte, which is a byte appended to the cipher text to safeguard against thedatabase system trimming trailing zeros.

CHAPTER 7: Column Encryption

Database Encryption 63

Table 1. Datatype Length for Encrypted Columns

User-speci-fied columntype

Inputdatalength

Encryp-ted col-umntype

Maxi-mum en-crypteddatalength(no initvector)

Actualencryp-ted datalength(no initvector)

Maxi-mum en-crypteddatalength(with initvector)

Actualencryp-ted datalength(with initvector)

bigint 8 varbi-nary

17 17 33 33

unsignedbigint

8 varbi-nary

17 17 33 33

tinyint,smallint,or int (signedor unsigned)

1, 2, or 4 varbi-nary

17 17 33 33

tinyint,smallint,or int (signedor unsigned)

0 (null) varbi-nary

17 0 33 0

float,float(4),real

4 varbi-nary

17 17 33 33

float,float(4),real

0 (null) varbi-nary

17 0 33 0

float(8),double

8 varbi-nary

17 17 33 33

float(8),double

0 (null) varbi-nary

17 0 33 0

numer-ic(10,2)

3 varbi-nary

17 17 33 33

numeric(38,2)

18 varbi-nary

33 33 49 49

numeric(38,2)

0 (null) varbi-nary

33 0 49 0

CHAPTER 7: Column Encryption

64 SAP Adaptive Server Enterprise

User-speci-fied columntype

Inputdatalength

Encryp-ted col-umntype

Maxi-mum en-crypteddatalength(no initvector)

Actualencryp-ted datalength(no initvector)

Maxi-mum en-crypteddatalength(with initvector)

Actualencryp-ted datalength(with initvector)

char, var-char (100)

1 varbi-nary

113 17 129 33

char, var-char(100)

14 varbi-nary

113 17 129 33

char, var-char(100)

15 varbi-nary

113 33 129 49

char, var-char(100)

31 varbi-nary

113 49 129 65

char, var-char(100)

0 (null) varbi-nary

113 0 129 0

binary,varbina-ry(100)

1 varbi-nary

113 17 129 33

binary,varbina-ry(100)

14 varbi-nary

113 17 129 33

binary,varbina-ry(100)

15 varbi-nary

113 33 129 49

binary,varbina-ry(100)

31 varbi-nary

113 49 129 65

binary,varbina-ry(100)

0 (null) varbi-nary

113 0 65 0

uni-char(10)

2 (1uni-charcharac-ter)

varbi-nary

33 17 49 33

CHAPTER 7: Column Encryption

Database Encryption 65

User-speci-fied columntype

Inputdatalength

Encryp-ted col-umntype

Maxi-mum en-crypteddatalength(no initvector)

Actualencryp-ted datalength(no initvector)

Maxi-mum en-crypteddatalength(with initvector)

Actualencryp-ted datalength(with initvector)

uni-char(10)

20 (10uni-charcharac-ters)

varbi-nary

33 33 49 49

univarch-ar(20)

20 (10uni-charcharac-ters)

varbi-nary

49 33 65 49

date 4 varbi-nary

17 17 33 33

time 4 varbi-nary

17 17 33 33

time null varbi-nary

17 0 33 0

smalldate-time

4 varbi-nary

17 17 33 33

datetime 8 varbi-nary

17 17 33 33

smallmoney 4 varbi-nary

17 17 33 33

money 8 varbi-nary

17 17 33 33

money null varbi-nary

17 0 33 0

bit 1 varbi-nary

17 17 33 33

Note:

CHAPTER 7: Column Encryption

66 SAP Adaptive Server Enterprise

• The timestamp datatype is not supported by SAP ASE.

• char and binary are treated as variable-length datatypes and are stripped of blanks andzero padding before encryption. Any blank or zero padding is applied when the data isdecrypted.

• The column length on disk increases for encrypted columns, but the increases are invisibleto tools and commands. For example, sp_help shows only the original size.

Encrypted Columns AuditsYou can perform and manage encrypted column audits.

See Auditing in the Security Administration Guide.

Event Names and NumbersYou can query the audit trail for specific audit events.

Use audit_event_name with event id as a parameter.audit_event_name(event_id)

See Auditing in the Security Administration Guide for values that appear in the event columnof sysaudits.

Passwords Masked in Command Text AuditingPasswords are masked in audit records.

For example, if the SSO has enabled command text auditing (that is, auditing all actions of aparticular user) for user “alan” in database db1:

sp_audit "cmdtext", "alan", "db1", "on"

And “alan” issues this command:

create encryption key key1 with passwd "bigsecret"

SAP ASE writes the following SQL text to the extrainfo column of the audit table:

"create encryption key key1 with passwd "xxxxxx"

Auditing Actions of the Key CustodianYou can audit all actions in which the keycustodian_role is active.

The syntax is:sp_audit "all", "keycustodian_role", "all", "on"

CHAPTER 7: Column Encryption

Database Encryption 67

Performance ConsiderationsEncryption is a resource-intensive operation that may introduce a performance overhead toyour application in terms of CPU usage and the elapsed time of commands that use encryptedcolumns.

The amount of overhead depends on the number of CPUs and SAP ASE engines, the load onthe system, the number of concurrent sessions accessing the encrypted data, and the number ofencrypted columns referenced in a query. The encryption key size and the length of theencrypted data are also factors. In general, the larger the key size and the wider the data, thehigher the CPU usage in the encryption operation.

The elapsed time depends on whether the SAP ASE optimizer can make use of an encryptedcolumn.

See also• Creating Column Encryption Keys on page 7• Dropping Column Encryption Keys on page 11• Encrypted Columns Process on page 71

Indexes on Encrypted ColumnsYou can create an index on an encrypted column if the column’s encryption key does notspecify the use of an initialization vector or random padding.

Using an initialization vector or random padding results in identical data being encrypting todifferent patterns of cipher text, which prevents an index from enforcing uniqueness and fromperforming equality matching of data in cipher text form.

Indexes on encrypted data are useful for equality and nonequality matching of data but not fordata ordering, range searches, or finding minimum and maximum values. If SAP ASE isperforming an order-dependent search on an encrypted column, it cannot execute an indexedlookup on encrypted data. Instead, the encrypted column in each row must be decrypted andthen searched. This slows data processing.

Sort Orders and Encrypted ColumnsIf you use a case-insensitive sort order, SAP ASE cannot use an index on an encrypted charor varchar column when performing a join with another column or a search based on aconstant value. This is also true of an accent-insensitive sort order.

For example, For example, in a case-insensitive search, the string abc matches all strings inthe following range: abc, Abc, ABc, ABC, AbC, aBC, aBc, abC. SAP ASE must compareabc against this range of values. By contrast, a case-sensitive comparison of the string abc tothe column data matches only identical column values, that is, columns containing abc. Themain difference between case-insensitive and case-sensitive column lookups is that case-

CHAPTER 7: Column Encryption

68 SAP Adaptive Server Enterprise

insensitive matching requires SAP ASE to perform a range search whereas case-sensitivematching requires an equality search.

An index on a nonencrypted character column orders the data according to the defined sortorder. For encrypted columns, the index orders the data according to the cipher text values,which bears no relationship to the ordering of plain text values. Therefore, an index on anencrypted column is useful only for equality and non-equality matching and not for searchinga range of values. abc and Abc encrypt to different cipher text values and are not storedadjacently in an index.

When SAP ASE uses an index on an encrypted column, it compares column data in cipher textform. For case sensitive data, you do not want abc to match Abc, and the cipher text join orsearch based on equality matching works well. SAP ASE can join columns based on ciphertext values and can efficiently match where clause values. In this example, the maidennamecolumn is encrypted:

select account_id from customer where cname = 'Peter Jones' and maidenname = 'McCarthy'

Providing that maidenname has been encrypted without use of an initialization vector orrandom padding, SAP ASE encrypts McCarthy and performs a cipher text search ofmaidenname. If there is an index on maidenname, the search uses of the index.

Joins on Encrypted ColumnsSAP ASE optimizes the joining of two encrypted columns by performing cipher textcomparisons under certain circumstances.

• The joining columns have the same datatype. For cipher text comparisons, char andvarchar are considered to be the same datatypes, as are binary and varbinary.

• For int and float types, the columns have the same length. For numeric anddecimal types, the columns must have the same precision and scale.

• The joining columns are encrypted with the same key.• The joining columns are not part of an expression. For example, you cannot perform a

cipher text join on a join where t.encr_col1 = s.encr_col1 +1.• The encryption key was created with init_vector and pad set to NULL.• The join operator is ‘=’ or ‘<>’.• The data uses the default sort order.

This example sets a schema to join on cipher text:create encryption key new_cc_key for AES with init_vector NULLcreate table customer (custid int, creditcard char(16) encrypt with new_cc_key)create table daily_xacts (cust_id int, creditcard char(16) encrypt with new_cc_key, amount money........)

CHAPTER 7: Column Encryption

Database Encryption 69

You can also set up indexes on the joining columns:create index cust_cc on customer(creditcard)create index daily_cc on daily_xacts(creditcard)

SAP ASE executes the following select statement to total a customer’s daily charges on acredit card without decrypting the creditcard column in either the customer or thedaily_xacts table.

select sum(d.amount) from daily_xacts d, customer c where d.creditcard = c.creditcard and c.custid = 17936

Search Arguments and Encrypted ColumnsFor equality and nonequality comparison of an encrypted column to a constant value, SAPASE optimizes the column scan by encrypting the constant value once, rather than decryptingthe encrypted column for each row of the table.

For example:select sum(d.amount) from daily_xacts d where creditcard = '123-456-7890'

SAP ASE cannot use an index to perform a range search on an encrypted column; it mustdecrypt each row before performing data comparisons. If a query contains other predicates,SAP ASE selects the most efficient join order, which often leaves searches against encryptedcolumns until last, on the smallest data set.

If your query has more than one range search without a useful index, write the query so that therange search against the encrypted column is last. This example which searches for the SocialSecurity Numbers of taxpayers earning more than $100,000 in Rhode Island positions thezipcode column before the range search of the encrypted adjusted gross income column:

select ss_num from taxpayers where zipcode like '02%' and agi_enc > 100000

Referential Integrity SearchesReferential integrity probes match at the cipher text level if both the following are true:

• The datatypes of the primary key and foreign key match according to the rules describedabove.

• The encryption of the primary and foreign keys meets the key requirements for joiningcolumns.

Movement of Encrypted Data as Cipher TextAs much as possible, SAP ASE optimizes the copying of encrypted data by copying ciphertext instead of decrypting and reencrypting data. This applies to select into commands, bulkcopying, and replication.

CHAPTER 7: Column Encryption

70 SAP Adaptive Server Enterprise

Access Encrypted DataSAP ASE automatically performs encryption and decryption when you process data inencrypted columns. SAP ASE encrypts data when you update or insert data into an encryptedcolumn, and decrypts data when you select it or use it in a where clause.

Encrypted Columns ProcessWhen you issue a select, insert, update, or delete command against an encrypted column,SAP ASE automatically encrypts or decrypts the data using the encryption key associatedwith the encrypted column.

• When you issue an insert or update on an encrypted column:• If you do not have insert or update permission on the encrypted column, the command

fails.• If the column is encrypted by a key with a user-specified password, SAP ASE expects

the password to be available. If the user-specified password has not been set, thecommand fails.

• SAP ASE decrypts the encryption key.• SAP ASE encrypts the data using the column’s encryption key.• SAP ASE inserts the varbinary cipher text data into the table.

• After the insert or update, SAP ASE clears the memory holding the plain text. At theend of the statement, it clears the memory holding the raw encryption keys.

• When you issue a select command on data from an encrypted column:• The command fails if you do not have select permission on the encrypted column.• If the encryption key is associated with a column encrypted with a user-specified

password, SAP ASE expects the password to be available. If the user-specifiedpassword has not been set, the select statement fails. Otherwise, SAP ASE decryptsthe encryption key.

• The decryption of the selected data succeeds if you have decrypt permission on thecolumn, and SAP ASE returns plain text data to the user.

• If a decrypt default has been declared on the encrypted column and if you do not havedecrypt permission on the column, SAP ASE returns the decrypt default value.

• When you include encrypted columns in a where clause:• If you do not have decrypt permission on the column, and the column includes a

decrypt default, the where clause predicate evaluates to false.• When possible, SAP ASE makes the comparison without decrypting the data if:

• The where clause joins an encrypted column with another column encrypted by thesame key without use of an initialization vector or random pad

• The column data is being matched with an equality or an inequality condition to aconstant value

CHAPTER 7: Column Encryption

Database Encryption 71

See also• Access Encrypted Data with a User Password on page 82

• Decrypt Default Columns and Query Qualifications on page 60

• Performance Considerations on page 68

Permissions for DecryptionTo see or process decrypted data, users must have certain permissions.

User must have:

• select and decrypt permissions on the column used in the target list and in where, having,order by, group by, and other such clauses

• A password used to encrypt the key if you use the passwd password_phrase clause withthe create or alter encryption key commands.

Configuring SAP ASE for restricted decrypt permission restricts implicit decryptpermissions. You must explicitly grant table owners decrypt permission to enable them toselect from an encrypted column on tables that they own. execute permission on a storedprocedure or select permission on a view does not implicitly grant users decrypt permissionon the underlying encrypted data through an ownership chain. The user must also have explicitdecrypt permission on the base table.

Drop EncryptionIf you are a table owner, you can use alter table with the decrypt option to drop encryption on acolumn.

For example, to drop encryption on the creditcard column in the customer table, enter:

alter table customer modify creditcard decrypt

If the creditcard column was encrypted by a key with an explicit user password, youwould need to set that password first.

CHAPTER 7: Column Encryption

72 SAP Adaptive Server Enterprise

CHAPTER 8 Role of the Key Custodian

The key custodian, who must be assigned the keycustodian_role, maintains encryption keys.Using the keycustodian_role role allows you to separate the duties for administeringconfidential data by ensuring that no administrator has implicit access to data.

This figure illustrates that the database owner, as the schema owner, controls permissions foraccessing the data, but has no access without knowledge of the key’s password. The keycustodian, however, administers keys and their passwords, but has no permissions on the data.Only the qualified end user, with permissions on the data and knowledge of the encryptionkey's password, can access the data.

The system administrator and database owner do not have implicit key managementresponsibilities. SAP ASE provides the system role keycustodian_role so that the SSO neednot assume all encryption responsibility. The key custodian owns the encryption keys, butshould have no explicit or implicit permissions on the data. The database owner grants usersaccess to data through column permissions, and the key custodian allows users access to thekey’s password. keycustodian_role is automatically granted to sso_role and can be grantedby a user with the sso_role.

The key custodian can:

Database Encryption 73

• Create and alter encryption keys.• Assign as the database default key a key he or she owns, as long as he or she also owns the

current default key, if one exists.• Set up key copies for designated users, allowing each user access to the key through a

chosen password or a login password.• Share key encryption passwords with end users.• Grant schema owners select access to encryption keys on keys owned by the key custodian.• Create the master key or set the system encryption password.• Recover encryption keys.• Drop his or her own encryption keys.• Change ownership of keys he or she owns.

You can have multiple key custodians, who each own a set of keys. The key custodian grantsthe schema owner permission to use the keys on create table, alter table, and select into, andmay disclose the key password to privileged users or allow users to associate key copies with apersonal password or a login password. The key custodian can work with a “key recoverer” torecover keys in the event of a lost password or disaster. If the key custodian leaves thecompany, the SSO can use the alter encryption key command to change key ownership to anew key custodian.

See also• Creating Column Encryption Keys on page 7

• Dropping Column Encryption Keys on page 11

Users, Roles, and Data AccessUser-specified passwords on encryption keys ensure that data privacy is protected from thesystem administrator.

• The key custodian can own the keys, but not see the data.• The database owner can own the schema, but not the data.• A user can see and process the data because of:

• Key access, granted by the key custodian• Data access, granted by the table owner

CHAPTER 8: Role of the Key Custodian

74 SAP Adaptive Server Enterprise

Role Can CreateEncryptionKey?

Can Use Key in aSchema Defini-tion?

Can Decrypt EncryptedData?

sso_role Yes No, requires createtable permission

No. User with role may haveknowledge of password, but re-quires select permission on table(SSO has implicit decrypt permis-sion).

sa_role No, requires cre-ate encryptionkey permission

Yes, but must begranted select per-mission on the key

No, requires knowledge of pass-word

keycustodian_role Yes No, requires createtable permission

No. User with role may haveknowledge of password, but re-quires decrypt and select permis-sion.

database owner orschema owner

No, requires cre-ate encryptionkey permission

Yes, but must begranted select per-mission on the key

No, requires knowledge of pass-word.

User No No Yes, but must be granted decryptor select permission and haveknowledge of key’s password.

CHAPTER 8: Role of the Key Custodian

Database Encryption 75

CHAPTER 8: Role of the Key Custodian

76 SAP Adaptive Server Enterprise

CHAPTER 9 Key Protection Using User-Specified Passwords

Use create encryption key to associate a password with a key.

The syntax is:

create encryption key [[db.][owner].]keyname [as default] [for algorithm_name] [with {[keylength num_bits] [passwd 'password_phrase'] [init_vector {NULL | random}] [pad {NULL | random}]}]

where password_phrase is a quoted alphanumeric string of up to 255 bytes in length that SAPASE uses to generate thekey encryption key (KEK).

SAP ASE does not save the user-specified password. It saves a string of validating bytesknown as the “salt” in sysencryptkeys.eksalt, which allows SAP ASE to recognizewhether a password used on a subsequent encryption or decryption operation is legitimate fora key. You must supply the password to SAP ASE before you can access any column encryptedby keyname.

When you create an encryption key, its entry in the sysencryptkeys table is known as thebase key. For some users and applications, the base key, encrypted by either the master key, thesystem encryption password, or an explicit password, is sufficient. Any explicit password isshared among users requiring access to the key. Additionally, you can create key copies fordifferent users and applications. Each key copy can be encrypted by an individual passwordand is stored as a separate row in sysencryptkeys. An encryption key is alwaysrepresented by one base key and zero or more key copies.

This example shows how to use passwords on keys, and the key custodian’s function in settingup encryption. The password on the key is shared among all users who have a business need toprocess encrypted data.

1. Key custodian “razi” creates an encryption key:create encryption key key1 with passwd 'Worlds1Biggest6Secret'

2. “razi” distributes the password to all users who need access to encrypted data.3. Each user enters the password before processing tables with encrypted columns:

set encryption passwd 'Worlds1Biggest6Secret' for key razi.key1

4. If the key is compromised because an unauthorized user gained access to the password,“razi” alters the key to change the password.

Database Encryption 77

See also• Protect Keys with User-Specified Passwords on page 18

Change a Key’s Protection MethodYou can use the alter encryption key command to change the protection method for anencryption key.

The syntax is:

alter encryption key [[database.database][owner].] keyname [with {passwd {'old_passwd' | system_encr_passwd | login_passwd} | master key}] modify encryption [with [{passwd {'old_passwd' | system_encr_passwd | login_passwd} | master key}] [[no] dual_control]]

where:

• keyname – identifies a column encryption key.• with passwd 'old_password' – specifies the user-defined password previously specified to

encrypt the base key or the key copy with a create encryption key or alter encryption keystatement. The password can be up to 255 bytes long. If you do not specify with passwd onthe base key, the default is the master key or the system encryption password.

• with passwd 'new_password' – specifies the new password SAP ASE uses to encrypt thecolumn encryption key or key copy. The password can be up to 255 bytes long. If you donot specify with passwd and you are encrypting the base key, the default issystem_encr_passwd.

• system_encr_passwd – is the default encryption password. You cannot modify the basekey to be encrypted with the system encryption password if one or more key copies alreadyexist. This restriction prevents the key custodian from inadvertently exposing anencryption key to access by an administrator after the key custodian has set up the key forrestricted use by individual users. You cannot modify key copies to encrypt using thesystem encryption password.

• login_passwd – is the login password of the current session. You cannot modify the basekey to use login_password for encryption. A user can modify his own key copy to encryptwith his login password.

• master key – in the first instance indicates that the current encryption uses the master key.In the second instance, it indicates that the KEK or CEK must be re-encrypted with themaster key.

Example 1: In this example, the key custodian alters the base key because the password wascompromised or a user who knew the password left the company.

1. Key custodian “razi” creates an encryption key:

CHAPTER 9: Key Protection Using User-Specified Passwords

78 SAP Adaptive Server Enterprise

create encryption key key1 with passwd 'MotherOfSecrets'

2. “razi” shares the password on the base key with “joe” and “bill”, who need to process theencrypted data (no key copies are involved).

3. “joe” leaves the company.4. “razi” alters the password on the encryption key and then shares it with “bill”, and “pete”,

who replaceses “joe.” The data does not need to be reencrypted because the underlying keyhas not changed, just the way the key is protected. The following statement decrypts key1using the old password and reencrypts it with the new password:alter encryption key key1 with passwd 'MotherOfSecrets' modify encryption with passwd 'FatherOfSecrets'

Example 2: Use the master key to encrypt an existing CEK “k2”:alter encryption key k2 with passwd 'goodbye' modify encryption with master key

Example 3: Re-encrypt an existing CEK “k3” that is currently encrypted by the master key, touse dual control:alter encryption key k3 modify encryption with master key dual_control

Note: You can omit with master key in this example to achieve the same encryption.

Example 4: Re-encrypt an existing CEK “k4” that is currently encrypted by the master key andpassword “k4_password”, to remove dual control. The CEK and all its key copies arecontrolled by a single key derived from “k4_new_password”:alter encryption key k4 with passwd 'k4_password' modify encryption with passwd 'k4_new_password' no dual_control

Example 5: Encrypt an existing CEK “k5” that is currently encrypted by the master key, fordual control encrypted by the master key and password “k5_password”:alter encryption key k5 modify encryption with passwd 'k5_password' dual_control

Example 6: Encrypt a CEK for dual control by the master key and password “k6_password”:create encryption key k6 with passwd 'k6_password' dual_control

CHAPTER 9: Key Protection Using User-Specified Passwords

Database Encryption 79

For user “ned”, encrypt his existing key copy of CEK “k6” that is currently encrypted withdual control by the master key and password “k6_password”, for dual control by the masterkey and password “k6_ned_password”:alter encryption key k6 with passwd 'k6_password' add encryption with passwd 'k6_ned_password' for user ned

Note: User “ned” cannot change the dual control property of his key copy.

Example 7: Encrypt a CEK “k7” currently encrypted by the master and dual master key, to usethe system encryption password:alter encryption key k7 modify encryption with passwd system_encr_passwd no dual control

See also• Protect Encryption Keys with Dual Control on page 18

Create Key CopiesThe key custodian may need to make a copy of the key temporarily available to anadministrator or an operator who must load data into encrypted columns or databases.Because this operator does not otherwise have permission to access encrypted data, he or sheshould not have permanent access to a key.

You can make key copies available to individual users as follows:

• The key custodian uses create encryption key to create a key with a user-definedpassword. This key is known as the base key.

• The key custodian uses alter encryption key to assign a copy of the base key to anindividual user with an individual password.

This syntax shows how to add a key encrypted using an explicit password for a designateduser:alter encryption key [database.[ owner ].]key with passwd 'base_key_password' add encryption with passwd 'key_copy_password' for user_name ''

where:

• base_key_password – is the password used to encrypt the base key, and may be knownonly by the key custodian. The password can be upto 255 bytes in length. SAP ASE usesthe first password to decrypt the base column-encryption key.

CHAPTER 9: Key Protection Using User-Specified Passwords

80 SAP Adaptive Server Enterprise

• key_copy_password – the password used to encrypt the key copy. The password cannot belonger than 255 bytes. SAP ASE makes a copy of the decrypted base key, encrypts it with akey encryption key derived from the key_copy_password, and saves the encrypted basekey copy as a new row in sysencryptkeys.

• user_name – identifies the user for whom the key copy is made. For a given key,sysencryptkeys includes a row for each user who has a copy of the key, identified bytheir user ID (uid).

• The key custodian adds as many key copies as there are users who require access through aprivate password.

• Users can alter their copy of the encryption key to encrypt it with a different password.

The following example illustrates how to set up and use key copies with an encrypted column:

1. Key custodian “razi” creates the base encryption key with a user-specified password:create encryption key key1 with passwd 'WorldsBiggestSecret'

2. “razi” grants select permission on key1 to database owner for schema creation:

grant select on key key1 to dbo3. database owner creates schema and grants table and column-level access to “bill”:

create table employee (empname char(50), emp_salary money encrypt with razi.key1, emp_address varchar(200)) grant select on employee to bill grant decrypt on employee(emp_salary) to bill

4. Key custodian creates a key copy for “bill” and gives “bill” the password to his key copy.Only the key custodian and “bill” know this password.alter encryption key key1 with passwd 'WorldsBiggestSecret' add encryption with passwd 'justforBill' for user 'bill'

5. When “bill” accesses employee.emp_salary, he first supplies his password:

set encryption passwd 'justforBill' for key razi.key1 select empname, emp_salary from dbo.employee

When SAP ASE accesses the key for the user, it looks up that user’s key copy. If no copy existsfor a given user, SAP ASE assumes the user intends to access the base key.

Change Passwords on Key CopiesOnce a user has been assigned a key copy, he or she can use alter encryption key to modify thekey copy’s password.

This example shows how a user assigned a key copy alters the copy to access data through hisor her personal password:

• Key custodian “razi” sets up a key copy on an existing key for “bill” and encrypts it with atemporary password:

CHAPTER 9: Key Protection Using User-Specified Passwords

Database Encryption 81

alter encryption key key1 with passwd 'MotherOfSecrets' add encryption with passwd 'just4bill' for user bill

• “razi” sends “bill” his password for access to data through key1.• “bill” assigns a private password to his key copy:

alter encryption key razi.key1 with passwd 'just4bill' modify encryption with passwd 'billswifesname'

Only “bill” can change the password on his key copy. When “bill” enters the commandabove, SAP ASE verifies that a key copy exists for “bill”. If no key copy exists for “bill”,SAP ASE assumes the user is attempting to modify the password on the base key andissues an error message:Only the owner of object '<keyname>' or a user with sso_role can run this command.You cannot create key copies for user “guest” for login association.

Access Encrypted Data with a User PasswordYou must supply the encryption key’s password to encrypt or decrypt data on an insert,update, delete, select, alter table, or select into statement.

If the system encryption password protects the encryption key, you need not supply the systemencryption password because SAP ASE can already access it. Similarly, if your key copy isencrypted with your login password, SAP ASE can access this password while you remainlogged in to the server. For keys encrypted with an explicit password, you must set thepassword in your session before executing any command that encrypts or decrypts anencrypted column with this syntax:

set encryption passwd 'password_phrase' for {key | column} {keyname | column_name}

where:• password_phrase – is the explicit password specified with the create encryption key or

alter encryption key command to protect the key.• key – indicates that SAP ASE uses this password to decrypt the key when accessing any

column encrypted by the named key• keyname – may be supplied as a fully qualified name. For example:

[[database.][owner].]keyname• column – specifies that SAP ASE use this password only in the context of encrypting or

decrypting the named column. End users do not necessarily know the name of the key thatencrypts a given column.

• column_name – name of the column on which you are setting an encryption password.Supply column_name as:[[ database.][ owner ]. ]table_name.column_name

Each user who requires access to a key encrypted by an explicit password must supply thepassword. SAP ASE saves the password in encrypted form in the user session's internal

CHAPTER 9: Key Protection Using User-Specified Passwords

82 SAP Adaptive Server Enterprise

context. SAP ASE removes the key from memory at the end of the session by overwriting thememory with zeros.

This example illustrates how SAP ASE determines the password when it must encrypt ordecrypt data. It assumes that the ssn column in the employee and payroll tables is encryptedwith key1, as shown in these simplified schema creation statements:

create encryption key key1 with passwd "Ynot387"create table employee (ssn char (11) encrypt with key1, ename char(50))create table payroll (ssn char(11) encrypt with key1, base_salary float)

1. The key custodian shares the password required to access employee.ssn with “susan”.He does not need to disclose the name of the key to do this.

2. If “susan” has select and decrypt permission on employee, she can select employee datausing the password given to her for employee.ssn:

set encryption passwd "Ynot387" for column employee.ssn select ename from employee where ssn = '111-22-3456'ename-----------------------Priscilla Kramnik

3. If “susan” attempts to select data from payroll without specifying the password forpayroll.ssn, the following select fails (even if “susan” has select and decryptpermission on payroll):

select base_salary from payroll where ssn = '111-22-3456'You cannot execute 'SELECT' command because the user encryption passwordhas not been set.

To avoid this error, “susan” must first enter:set encryption passwd "Ynot387" for column payroll.ssn

The key custodian may choose to share passwords on a column-name basis and not on a key-name basis to avoid users hard-coding key names in application code, which can make itdifficult for the database owner to change the keys used to encrypt the data. However, if onekey is used to encrypt several columns, it may be convenient to enter the password once. Forexample:set encryption passwd "Ynot387" for key key1select base_salary from payroll p, employee e where p.ssn = e.ssn and e.ename = "Priscilla Kramnik"

If one key is used to encrypt several columns and the user is setting a password for the column,the user needs to set password for all the columns they want to process. For example:set encryption passwd 'Ynot387' for column payroll.ssnset encryption passwd 'Ynot387' for column employee.ssnselect base_salary from payroll p, employee e

CHAPTER 9: Key Protection Using User-Specified Passwords

Database Encryption 83

where p.ssn = e.ssn and e.ename = 'Priscilla Kramnik'

If a password is set for a column and then set at the key level for the key that encrypts thecolumn, SAP ASE discards the password associated with the column and retains the passwordat the key level. If two successive entries for the same key or column are entered, SAP ASEretains only the latest. For example:

1. If a user mistypes the password for the column employee.ssn as “Unot387” instead ofthe correct “Ynot387”:set encryption passwd "Unot387" for column employee.snn

2. And then the user reenters the correct password, SAP ASE retains only the second entry:set encryption passwd "Ynot387" for column employee.ssn

3. If the user now enters the same password at the key level, SAP ASE retains only this lastentry:set encryption passwd "Ynot387" for key key1

4. If the user now enters the same password at the column level, SAP ASE discards this entrybecause it already has this password at the key level:set encryption passwd "Ynot387" for column payroll.ssn

If a stored procedure or a trigger references data encrypted by a user specified password, youmust set the encryption password before executing the procedure or the statement that fires thetrigger.

Note: SAP recommends that you do not place the set encryption passwd statement inside atrigger or procedure; this could lead to unintentional exposure of the password throughsp_helptext. Additionally, hard-coded passwords require you to change the procedure ortrigger when a password is changed.

See also• Encrypted Columns Process on page 71

Application Transparency Using Login Passwords on KeyCopies

The key custodian can set up key copies for encryption using a user’s login password, andthereby providing ease of use, better security, lower overhead, and application transparency.

• Ease of use – users whose login password is associated with a key can access encrypteddata without supplying a password.

CHAPTER 9: Key Protection Using User-Specified Passwords

84 SAP Adaptive Server Enterprise

• Better security – users have fewer passwords to track, and are less likely to write themdown.

• Lower administrative overhead for key custodian – the key custodian need not manuallydistribute temporary passwords to each user who requires key access through a privatepassword.

• Application transparency – applications need not prompt for a password to processencrypted data. Existing applications can take advantage of the measures to protect dataprivacy from the power of the administrator.

To encrypt a key copy with a user’s login password, use:alter encryption key [[database.][owner].]keyname with passwd 'base_key_password' add encryption for user 'user_name' for login_association

where login_association tells SAP ASE to create a key copy for the named user, which it laterencrypts with the user's login password. Encrypting a key copy with a login passwordrequires:

1. Using alter encryption key, the key custodian creates a key copy for each user whorequires key access via a login password. SAP ASE attaches information to the key copy tosecurely associate the key copy with a given user. The identifying information and key aretemporarily encrypted using a key derived from the master key or—if no master key exists—the system encryption password. The key copy is saved in sysencryptkeys.

2. When a user processes data requiring a key lookup, SAP ASE notes that a copy of theencryption key identified for this user is ready for login password association. Using themaster key or the system encryption password to decrypt the information in the key copy,SAP ASE validates the user information associated with the key copy against the user’slogin credentials, and encrypts the key copy with a KEK derived from the user’s loginpassword, which has been supplied to the session.

When adding a key copy with alter encryption key key for login_association, the master keyor the system encryption password must be available for encryption of the key copy. Thesystem encryption password must still be available for SAP ASE to decrypt the key copy whenthe user logs in. After SAP ASE has reencrypted the key copy with the user’s login password,the system encryption password is no longer required.

Note: You must use the default SAP ASE authentication method with syslogins to accesskey copies using a login password. User authentication through external services such asLDAP or Kerberos results in an error accessing the key if the user’s key copies were added forlogin association.

The following example encrypts a user’s copy of the encryption key, key1, with the user’slogin password:

1. Key custodian “razi” creates an encryption key:create encryption key key1 for AES with passwd 'MotherofSecrets'

CHAPTER 9: Key Protection Using User-Specified Passwords

Database Encryption 85

2. “razi” creates a copy of key1 for user “bill”, initially encrypted with the master key or thesystem encryption password, but eventually to be encrypted by “bill”’s login password:alter encryption key key1 with passwd 'MotherofSecrets' add encryption for user 'bill' for login_association

3. SAP ASE uses the master key or the system encryption password to encrypt a combinationof the key and information identifying the key copy for “bill”, and stores the result insysencryptkeys.

4. “bill” logs in to SAP ASE and processes data, requiring the use of key1. For example, ifemp.ssn is encrypted by key1:

select * from emp

SAP ASE recognizes that it must encrypt “bill”’s copy of key1 with his login password.SAP ASE uses the master key or the system encryption password to decrypt the key valuedata saved in step 4. It validates the information against the current login credentials, thenencrypts key1's key value with a KEK generated from “bill”’s login password.

5. During future logins when “bill” processes columns encrypted by key1, SAP ASEaccesses key1 directly by decrypting it with “bill”’s login password, which is available toSAP ASE through “bill”’s internal session context.Users who are aliased to “bill” cannot access the data encrypted by key1 because theirown login passwords cannot decrypt key1.

6. When “bill” loses authority to process confidential data, the key custodian drops “bill”’saccess to the key:alter encryption key key1 drop encryption for user 'bill'

A user can encrypt a key copy directly with a login password with alter encryption key usingthe with passwd login_passwd clause. However, the disadvantages of using this method overthe login association are:

• The key custodian must communicate the key copy’s first assigned password to the user.• The user must issue alter encryption key to reencrypt the key copy with a login password.

For example:

• “razi” adds a key copy for user “bill” encrypted by an explicit password:alter encryption key key1 with passwd 'MotherofSecrets' add encryption with passwd 'just4bill' for user bill

• “razi” shares the key copy's password with “bill”.• “bill” decides to encrypt his key copy with his login password for his own convenience:

CHAPTER 9: Key Protection Using User-Specified Passwords

86 SAP Adaptive Server Enterprise

alter encryption key key1 with passwd "just4bill" modify encryption with passwd login_passwd

• Now, when “bill” processes encrypted columns, SAP ASE accesses “bill”’s key copythrough his login password.

Login Password Change and Key CopiesIf you hold a key copy encrypted by a login password on one or more keys, you need notmodify the key copies after you change your login password. alter login decrypts your keycopies with your old login password and reencrypts them using the new login password.

If the SSO uses alter login to change your password, alter login drops your key copies. Thisprevents an administrator from gaining access to a key through a known password. After amandatory password change of this kind, the key custodian must use alter encryption key toadd a key copy for login_association for the user whose password is changed. alter loginignores offline databases and, for keys stored in offline databases, the key custodian followsthe steps for recovering a lost key copy password when the database comes back online.

The key custodian may also need to perform these steps when a user’s password is changedafter the server is started using the -p flag. If the SSO, who uses the -p flag also has access tokeys through key copies encrypted with his or her login password, then the key custodian mustdrop and re-create the SSO’s key copies.

See also• Loss of Login Password on page 89

Dropping a Key CopyWhen a user changes jobs or leaves the company, the key custodian should drop the user’s keycopy.

The syntax is:alter encryption key keyname drop encryption for user user_name

For example, if user “bill” leaves the company, the key owner can prevent “bill”’s access tokey1 by dropping his key copy:

alter encryption key key1 drop encryption for user bill

SAP ASE does not require a password for this command because no key decryption isrequired.

drop encryption key drops the base key and all its copies.

CHAPTER 9: Key Protection Using User-Specified Passwords

Database Encryption 87

CHAPTER 9: Key Protection Using User-Specified Passwords

88 SAP Adaptive Server Enterprise

CHAPTER 10 Key Recovery from LostPasswords

Key custodians can recover keys and lost passwords, and manage the ownership of encryptionkeys.

See also• Creating Master Key Copies on page 22

Loss of Password on Key CopyIf a user loses a password for the encryption key, the key custodian must drop the user’s copyof the encryption key and issue to the user another copy of the encryption key with a newpassword.

In this example, the key custodian assigned a copy of key1 to “bill”, and “bill” changed hispassword on key1 to a password known only to him. After losing his password, “bill”requests a new key copy from the key custodian.

1. The key custodian deletes Bill’s copy of the key:alter encryption key key1 drop encryption for user bill

2. The key custodian makes a new copy of key1 for user “bill” and gives “bill” the password:

alter encryption key key1 with passwd 'MotherofSecrets' add encryption with passwd 'over2bill' for user bill

3. “bill” automatically has permission to alter his own copy of key1:

alter encryption key key1 with passwd 'over2bill' modify encryption with passwd 'billsnupasswd'

Loss of Login PasswordIf a user who has key copies encrypted by his or her login password loses that password, thekey custodian can recover access for the user.

For example, if the user “bill”, who has key copies encrypted by his login password, loses hislogin password, you can recover his access to encryption keys with these steps:

Database Encryption 89

1. The SSO uses alter login to issue “bill” a new login password. SAP ASE drops any keycopies assigned to “bill” for login association or key copies already encrypted by “bill”’slogin password.

2. The key custodian follows the regular procedure for setting up key encryption by loginassociation. He verifies that the master key or the system encryption password was set, andcreates a key copy for “bill":alter encryption key k1 with passwd 'masterofsecrets' add encryption for bill for login_association

This step assumes the key custodian still knows the base key’s password. If the key’sencryption password is unknown, the key custodian must first follow the key recoveryprocedure.

3. The next time “bill” accesses data encrypted by k1, SAP ASE reencrypts the key copy for"bill" using the new login password for “bill”. For example, if emp_salary is encryptedby key k1, the following statement automatically reencrypts the key copy for “bill” withhis login password:select emp_salary from emp where name like 'Prisicilla%'

See also• Login Password Change and Key Copies on page 87

Loss of Password on Base KeyKey custodians can use key recovery if the base key password is lost. Key recovery is vitalbecause, without the password, the key custodian cannot change the key’s password or addkey copies.

If all users share access to data through the base key and a user forgets the password, he or shecan get the password from another user or the key custodian. If no one remembers thepassword, all access to the data is lost. Because of this, SAP ASE recommends that you backup keys by creating a copy of the base key that you can use for recovery. This copy is called thekey recovery copy.

The key custodian should:

• Appoint one user as the key recoverer. The key recoverer's responsibility is to rememberthe password to the key recovery copy.

• Make a copy of the base key for the key recoverer. Every key that requires recovery after adisaster must have a key recovery copy.

CHAPTER 10: Key Recovery from Lost Passwords

90 SAP Adaptive Server Enterprise

Key Recovery CommandsSAP ASE does not allow access to data through the recovery key copy. A key recovery copyexists only to provide a backup for accessing the base key.

Set up a recovery key copy using:

alter encryption key keyname with passwd base_key_passwd add encryption with passwd recovery_passwd for user key_recovery_user for recovery

where:

• base_key_passwd – is the password the key custodian assigned to the base key.• recovery_passwd – is the password used to protect the key recovery copy.• key_recovery_user – user assigned the responsibility for remembering a password for key

recovery.

After setting the key recovery copy, the key custodian shares the password with the keyrecovery user, who can alter the password using:alter encryption key keyname with passwd old_recovery_passwd modify encryption with passwd new_recovery_passwd for recovery

During key recovery, the key recovery user tells the key custodian the password of the keyrecovery copy. The key custodian restores access to the base key using:

alter encryption key keyname with passwd recovery_key_passwd recover encryption with passwd new_base_key_passwd

where:

• recovery_key_passwd – is the password associated with the key recovery copy, sharedwith the key custodian by the recovery key user. SAP ASE uses the recovery_key_passwdto decrypt the key recovery copy to access the raw key.

• new_base_key_passwd – is the password used to encrypt the raw key. SAP ASE updatesthe base key row in sysencryptkeys with the result.

This example shows how to set up the recovery key copy and use it for key recovery afterlosing a password:

1. The key custodian creates a new encryption key protected by a password.create encryption key key1 for AES passwd 'loseitl8ter'

2. The key custodian adds a encryption key recovery copy for key1 for “charlie”.

alter encryption key key1 with passwd 'loseitl8ter' add encryption with passwd 'temppasswd'

CHAPTER 10: Key Recovery from Lost Passwords

Database Encryption 91

for user charlie for recovery

3. “charlie” assigns a different password to the recovery copy and saves this password in alocked drawer:alter encryption key key1 with passwd 'temppasswd' modify encryption with passwd 'finditl8ter' for recovery

4. If the key custodian loses the password for base key, he can obtain the password from“charlie” and recover the base key from the recovery copy using:alter encryption key key1 with passwd 'finditl8ter' recover encryption with passwd 'newpasswd'

The key custodian now shares access to key1 with other users by sharing the base key’spassword, or by dropping and adding key copies where changes in personnel have occurred.

Ownership Change of Encryption KeysThe SSO can transfer key ownership to a named user. Changing ownership may occur in thenormal course of business, or as part of key recovery.

This command, when executed by the SSO, transfers key ownership to a named user:alter encryption key [[database.][owner].]keyname modify owner user_name

where user_name is the name of the new key owner. This user must already be a user in thedatabase where the key was created.

For example, if “razi” is the key custodian, and owns the key encr_key, but is being replacedby a new key custodian named “tinnap”, change the key ownership using:alter encryption key encr_key modify owner tinnap

Only the SSO or the key owner can run this command. If the new owner already has a copy ofthe key, you see:A copy of key encr_key already exists for user tinnap

A user who already has a regular key copy or a recovery key copy cannot become the newowner of the key. SAP ASE does not allow a key copy to be made for a key owner.

If the previous key owner had granted any permissions on the key, the granter user ID insysprotects system table is changed to the user ID of the new owner of the key. Theownership change is effective immediately; the new owner need not log in again for the changeto take effect.

CHAPTER 10: Key Recovery from Lost Passwords

92 SAP Adaptive Server Enterprise