diff --git a/content/plugins.yaml b/content/plugins.yaml index e5bb694..49018ef 100644 --- a/content/plugins.yaml +++ b/content/plugins.yaml @@ -559,9 +559,10 @@ plugins: ruby: { name: encryption_return_unverified_data, required: "No", default: "false", example: "false" } adminUtility: ruby: "Plugins::Encryption::KeyManagementUtility" - # The trigger SQL below is a copy of the files in the Ruby wrapper repo, which its integration - # tests install: spec/integration/host/src/test/resources/sql/kms_encryption_trigger_pg.sql and - # kms_encryption_trigger_mysql.sql. Keep the two identical; change the files first. + # The trigger SQL lives in the Ruby wrapper repo, which installs it in its integration tests: + # lib/aws_advanced_ruby_driver_wrapper/plugins/kms_encryption/sql/trigger_pg.sql and + # trigger_mysql.sql. This page links to those files rather than copying them. When a file + # changes, bump the version in its database comment and add a row to "Updating the trigger SQL". serverSideEnforcement: | ## Enforce encryption in the database @@ -571,67 +572,24 @@ plugins: verify that a value carries a valid integrity tag without holding the data key. + The trigger SQL is maintained in the wrapper repository: + + - PostgreSQL: [`trigger_pg.sql`](https://github.com/aws/aws-advanced-ruby-driver-wrapper/blob/main/lib/aws_advanced_ruby_driver_wrapper/plugins/kms_encryption/sql/trigger_pg.sql) + - MySQL: [`trigger_mysql.sql`](https://github.com/aws/aws-advanced-ruby-driver-wrapper/blob/main/lib/aws_advanced_ruby_driver_wrapper/plugins/kms_encryption/sql/trigger_mysql.sql) + + Run the file for your engine once per database, then add a trigger for every + encrypted column as shown below. The SQL is updated from time to time; see + [Updating the trigger SQL](#updating-the-trigger-sql). + ### PostgreSQL - ```sql - -- pgcrypto provides hmac(). If it is already installed in a schema other than public, - -- replace public in public.hmac below with that schema. - CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public; - - -- Replace 'encrypt' below if encryption_metadata_schema is set to something else. - -- A trigger runs with the search_path of the session that fires it. Pinning it to pg_catalog - -- stops a session from putting its own functions or operators, such as hmac() or <>, ahead of - -- the built-in ones to get a plaintext value past this check. - CREATE OR REPLACE FUNCTION enforce_encrypted_column() RETURNS trigger - SET search_path = pg_catalog, pg_temp - AS $$ - DECLARE - col_name text := TG_ARGV[0]; - col_value bytea; - hmac_key bytea; - cache_key text := 'hmac_key.' || TG_TABLE_NAME || '.' || col_name; - unchanged boolean; - BEGIN - -- An UPDATE that leaves the encrypted value as it was is not re-checked; see - -- "Updates after a key rotation". - IF TG_OP = 'UPDATE' THEN - EXECUTE format('SELECT ($1).%I IS NOT DISTINCT FROM ($2).%I', col_name, col_name) - INTO unchanged USING NEW, OLD; - IF unchanged THEN - RETURN NEW; - END IF; - END IF; - - EXECUTE format('SELECT ($1).%I', col_name) INTO col_value USING NEW; - IF col_value IS NULL THEN - RETURN NEW; - END IF; - - -- A setting cached by an earlier transaction reads back as '' rather than being - -- undefined, so an empty value is treated as not cached. - hmac_key := decode(NULLIF(current_setting(cache_key, true), ''), 'hex'); - IF hmac_key IS NULL THEN - SELECT ks.hmac_key INTO hmac_key - FROM encrypt.encryption_metadata em - JOIN encrypt.key_storage ks ON em.key_id = ks.id - WHERE em.table_name = TG_TABLE_NAME AND em.column_name = col_name; - - IF hmac_key IS NULL THEN - RAISE EXCEPTION 'No HMAC key is configured for %.%', TG_TABLE_NAME, col_name; - END IF; - - PERFORM set_config(cache_key, encode(hmac_key, 'hex'), true); - END IF; - - IF length(col_value) < 65 - OR substring(col_value from 1 for 32) <> public.hmac(substring(col_value from 33), hmac_key, 'sha256'::text) THEN - RAISE EXCEPTION 'Column %.% does not carry a valid HMAC tag (plaintext or tampered value)', TG_TABLE_NAME, col_name; - END IF; - - RETURN NEW; - END; - $$ LANGUAGE plpgsql; - ``` + Run [`trigger_pg.sql`](https://github.com/aws/aws-advanced-ruby-driver-wrapper/blob/main/lib/aws_advanced_ruby_driver_wrapper/plugins/kms_encryption/sql/trigger_pg.sql). It installs the `pgcrypto` + extension if it is not already installed, and creates the + `enforce_encrypted_column()` trigger function. The function reads the + metadata tables as `encrypt.encryption_metadata` and `encrypt.key_storage`: + replace `encrypt` if `encryption_metadata_schema` is set to something else. If + `pgcrypto` is already installed in a schema other than `public`, replace + `public` in `public.hmac` with that schema. Then create a trigger for every column that you want to encrypt: @@ -647,136 +605,27 @@ plugins: FOR EACH ROW EXECUTE FUNCTION enforce_encrypted_column('dob'); ``` - The HMAC key is cached for the length of the transaction rather than the - session, so that a key rotation takes effect immediately. Widen it to the - session with `set_config(..., false)` if the per-transaction metadata lookup - costs more than the rotation delay is worth. - ### MySQL - MySQL has no built-in HMAC function, so the equivalent builds HMAC-SHA256 out - of `SHA2()`. Create the two functions and the two validation procedures once per - schema, then add a `BEFORE INSERT` and a `BEFORE UPDATE` trigger per encrypted - column. Replace `SCHEMA_NAME` with the value of `encryption_metadata_schema` - (`encrypt` by default). Requires MySQL 5.7+ / MariaDB 10.2+ for `SHA2()`. On - Aurora/RDS MySQL, creating the functions may require the cluster parameter - `log_bin_trust_function_creators` to be set to `1`. + MySQL has no built-in HMAC function, so + [`trigger_mysql.sql`](https://github.com/aws/aws-advanced-ruby-driver-wrapper/blob/main/lib/aws_advanced_ruby_driver_wrapper/plugins/kms_encryption/sql/trigger_mysql.sql) builds HMAC-SHA256 out of + `SHA2()`. Run it once per schema to create the two functions and the two + validation procedures, then add a `BEFORE INSERT` and a `BEFORE UPDATE` + trigger per encrypted column. Replace `SCHEMA_NAME` in the file with the value + of `encryption_metadata_schema` (`encrypt` by default). Requires MySQL 5.7+ / + MariaDB 10.2+ for `SHA2()`. On Aurora/RDS MySQL, creating the functions may + require the cluster parameter `log_bin_trust_function_creators` to be set to + `1`. :::note - The SQL below uses `DELIMITER`, which is a command of the `mysql` command-line - client rather than SQL. To run it through a driver, a Rails migration, or any - other tool that sends one statement at a time, leave out the `DELIMITER` - lines and send each `DROP`, `CREATE FUNCTION`, `CREATE PROCEDURE` and - `CREATE TRIGGER` statement on its own, without its trailing `$$`. + The file and the trigger SQL below use `DELIMITER`, which is a command of the + `mysql` command-line client rather than SQL. To run them through a driver, a + Rails migration, or any other tool that sends one statement at a time, leave + out the `DELIMITER` lines and send each `DROP`, `CREATE FUNCTION`, + `CREATE PROCEDURE` and `CREATE TRIGGER` statement on its own, without its + trailing `$$`. ::: - ```sql - DELIMITER $$ - - -- HMAC-SHA256 built from SHA2(), which MySQL has no native HMAC for. - DROP FUNCTION IF EXISTS hmac_sha256$$ - CREATE FUNCTION hmac_sha256( - message VARBINARY(65535), - key_data VARBINARY(64) - ) - RETURNS VARBINARY(32) - DETERMINISTIC - NO SQL - BEGIN - DECLARE block_size INT DEFAULT 64; -- SHA-256 block size - DECLARE key_padded VARBINARY(64); - DECLARE ipad VARBINARY(64); - DECLARE opad VARBINARY(64); - DECLARE i INT DEFAULT 1; - DECLARE key_byte INT; - - -- Reduce an over-long key to its hash, then zero-pad the key to the block size. - IF LENGTH(key_data) > block_size THEN - SET key_padded = CONCAT(UNHEX(SHA2(key_data, 256)), REPEAT(X'00', block_size - 32)); - ELSE - SET key_padded = CONCAT(key_data, REPEAT(X'00', block_size - LENGTH(key_data))); - END IF; - - -- ipad = key XOR 0x36 per byte, opad = key XOR 0x5C per byte, one raw byte at a time. - SET ipad = X''; - SET opad = X''; - WHILE i <= block_size DO - SET key_byte = ASCII(SUBSTRING(key_padded, i, 1)); - SET ipad = CONCAT(ipad, UNHEX(LPAD(HEX(key_byte ^ 0x36), 2, '0'))); - SET opad = CONCAT(opad, UNHEX(LPAD(HEX(key_byte ^ 0x5C), 2, '0'))); - SET i = i + 1; - END WHILE; - - RETURN UNHEX(SHA2(CONCAT(opad, UNHEX(SHA2(CONCAT(ipad, message), 256))), 256)); - END$$ - - -- Verifies that a stored value carries a valid HMAC for the given HMAC key. - DROP FUNCTION IF EXISTS verify_encrypted_data_hmac$$ - CREATE FUNCTION verify_encrypted_data_hmac( - data VARBINARY(65535), - hmac_key VARBINARY(32) - ) - RETURNS BOOLEAN - DETERMINISTIC - NO SQL - BEGIN - -- Minimum payload: 32 (HMAC) + 4 (key id) + 1 (type) + 12 (IV) + 0 (ciphertext) + 16 (GCM tag) = 65. - IF data IS NULL OR LENGTH(data) < 65 THEN - RETURN FALSE; - END IF; - - RETURN SUBSTRING(data, 1, 32) = hmac_sha256(SUBSTRING(data, 33), hmac_key); - END$$ - - -- Called from a BEFORE INSERT trigger (and by the BEFORE UPDATE procedure) to reject a value that is - -- not a valid kms_encryption payload. Replace SCHEMA_NAME with encryption_metadata_schema. - DROP PROCEDURE IF EXISTS validate_encrypted_data_hmac_before_insert$$ - CREATE PROCEDURE validate_encrypted_data_hmac_before_insert( - IN p_table_name VARCHAR(64), - IN p_column_name VARCHAR(64), - IN column_value VARBINARY(65535) - ) - BEGIN - DECLARE v_hmac_key VARBINARY(32); - - IF column_value IS NOT NULL THEN - SELECT ks.hmac_key INTO v_hmac_key - FROM SCHEMA_NAME.encryption_metadata em - JOIN SCHEMA_NAME.key_storage ks ON em.key_id = ks.id - WHERE em.table_name = p_table_name - AND em.column_name = p_column_name - LIMIT 1; - - IF v_hmac_key IS NULL THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'No HMAC key is configured for the encrypted column'; - END IF; - - IF NOT verify_encrypted_data_hmac(column_value, v_hmac_key) THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'Column does not carry a valid HMAC tag (plaintext or tampered value)'; - END IF; - END IF; - END$$ - - -- Called from a BEFORE UPDATE trigger. An UPDATE that leaves the value as it was is not - -- re-checked; see "Updates after a key rotation". - DROP PROCEDURE IF EXISTS validate_encrypted_data_hmac_before_update$$ - CREATE PROCEDURE validate_encrypted_data_hmac_before_update( - IN p_table_name VARCHAR(64), - IN p_column_name VARCHAR(64), - IN new_value VARBINARY(65535), - IN old_value VARBINARY(65535) - ) - BEGIN - IF NOT (new_value <=> old_value) THEN - CALL validate_encrypted_data_hmac_before_insert(p_table_name, p_column_name, new_value); - END IF; - END$$ - - DELIMITER ; - ``` - Then create a pair of triggers for every column that you want to encrypt. For example, on `users.ssn`: @@ -828,6 +677,39 @@ plugins: `INSERT`, or an `UPDATE` that changes the encrypted column - is still checked, and must carry the current key's tag. The plugin always writes new values with the current key, so its writes pass. + + ### Updating the trigger SQL + + The trigger SQL changes from time to time, independently of the wrapper + version. A database keeps the version it was set up with until the file is + run again, so re-run the file for your engine when a newer version is listed + below. Re-running it replaces the functions and procedures without changing + any data, and the per-column triggers keep working without being re-created. + On MySQL the file drops and re-creates each routine, so a write to an + encrypted column can fail in the moment between the two: re-run it while + writes are quiet. + + Each file records its version in a database comment. To check the version a + database has: + + ```sql + -- PostgreSQL + SELECT obj_description('enforce_encrypted_column'::regproc, 'pg_proc'); + ``` + + ```sql + -- MySQL, in the schema the procedures were created in + SELECT ROUTINE_COMMENT FROM information_schema.ROUTINES + WHERE ROUTINE_SCHEMA = DATABASE() + AND ROUTINE_NAME = 'validate_encrypted_data_hmac_before_insert'; + ``` + + An empty result means the SQL was installed before versions were recorded. + + | Engine | Version | Change | If your database has an earlier version | + |---|---|---|---| + | PostgreSQL | v2 | Reads the column's HMAC key from `key_storage` for every row. | Re-run `trigger_pg.sql`. An empty result is an earlier version. | + | MySQL | v1 | Records the version. The SQL is otherwise unchanged. | No action needed. An empty result is equivalent to v1. | hardening: | ## Hardening the deployment diff --git a/site/docs-ruby/using-plugins/kms-encryption.md b/site/docs-ruby/using-plugins/kms-encryption.md index cd9bd07..bfd83ad 100644 --- a/site/docs-ruby/using-plugins/kms-encryption.md +++ b/site/docs-ruby/using-plugins/kms-encryption.md @@ -530,67 +530,24 @@ that signs each value is stored unencrypted in `key_storage`: the server can verify that a value carries a valid integrity tag without holding the data key. +The trigger SQL is maintained in the wrapper repository: + +- PostgreSQL: [`trigger_pg.sql`](https://github.com/aws/aws-advanced-ruby-driver-wrapper/blob/main/lib/aws_advanced_ruby_driver_wrapper/plugins/kms_encryption/sql/trigger_pg.sql) +- MySQL: [`trigger_mysql.sql`](https://github.com/aws/aws-advanced-ruby-driver-wrapper/blob/main/lib/aws_advanced_ruby_driver_wrapper/plugins/kms_encryption/sql/trigger_mysql.sql) + +Run the file for your engine once per database, then add a trigger for every +encrypted column as shown below. The SQL is updated from time to time; see +[Updating the trigger SQL](#updating-the-trigger-sql). + ### PostgreSQL -```sql --- pgcrypto provides hmac(). If it is already installed in a schema other than public, --- replace public in public.hmac below with that schema. -CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public; - --- Replace 'encrypt' below if encryption_metadata_schema is set to something else. --- A trigger runs with the search_path of the session that fires it. Pinning it to pg_catalog --- stops a session from putting its own functions or operators, such as hmac() or <>, ahead of --- the built-in ones to get a plaintext value past this check. -CREATE OR REPLACE FUNCTION enforce_encrypted_column() RETURNS trigger -SET search_path = pg_catalog, pg_temp -AS $$ -DECLARE - col_name text := TG_ARGV[0]; - col_value bytea; - hmac_key bytea; - cache_key text := 'hmac_key.' || TG_TABLE_NAME || '.' || col_name; - unchanged boolean; -BEGIN - -- An UPDATE that leaves the encrypted value as it was is not re-checked; see - -- "Updates after a key rotation". - IF TG_OP = 'UPDATE' THEN - EXECUTE format('SELECT ($1).%I IS NOT DISTINCT FROM ($2).%I', col_name, col_name) - INTO unchanged USING NEW, OLD; - IF unchanged THEN - RETURN NEW; - END IF; - END IF; - - EXECUTE format('SELECT ($1).%I', col_name) INTO col_value USING NEW; - IF col_value IS NULL THEN - RETURN NEW; - END IF; - - -- A setting cached by an earlier transaction reads back as '' rather than being - -- undefined, so an empty value is treated as not cached. - hmac_key := decode(NULLIF(current_setting(cache_key, true), ''), 'hex'); - IF hmac_key IS NULL THEN - SELECT ks.hmac_key INTO hmac_key - FROM encrypt.encryption_metadata em - JOIN encrypt.key_storage ks ON em.key_id = ks.id - WHERE em.table_name = TG_TABLE_NAME AND em.column_name = col_name; - - IF hmac_key IS NULL THEN - RAISE EXCEPTION 'No HMAC key is configured for %.%', TG_TABLE_NAME, col_name; - END IF; - - PERFORM set_config(cache_key, encode(hmac_key, 'hex'), true); - END IF; - - IF length(col_value) < 65 - OR substring(col_value from 1 for 32) <> public.hmac(substring(col_value from 33), hmac_key, 'sha256'::text) THEN - RAISE EXCEPTION 'Column %.% does not carry a valid HMAC tag (plaintext or tampered value)', TG_TABLE_NAME, col_name; - END IF; - - RETURN NEW; -END; -$$ LANGUAGE plpgsql; -``` +Run [`trigger_pg.sql`](https://github.com/aws/aws-advanced-ruby-driver-wrapper/blob/main/lib/aws_advanced_ruby_driver_wrapper/plugins/kms_encryption/sql/trigger_pg.sql). It installs the `pgcrypto` +extension if it is not already installed, and creates the +`enforce_encrypted_column()` trigger function. The function reads the +metadata tables as `encrypt.encryption_metadata` and `encrypt.key_storage`: +replace `encrypt` if `encryption_metadata_schema` is set to something else. If +`pgcrypto` is already installed in a schema other than `public`, replace +`public` in `public.hmac` with that schema. Then create a trigger for every column that you want to encrypt: @@ -606,136 +563,27 @@ BEFORE INSERT OR UPDATE ON users FOR EACH ROW EXECUTE FUNCTION enforce_encrypted_column('dob'); ``` -The HMAC key is cached for the length of the transaction rather than the -session, so that a key rotation takes effect immediately. Widen it to the -session with `set_config(..., false)` if the per-transaction metadata lookup -costs more than the rotation delay is worth. - ### MySQL -MySQL has no built-in HMAC function, so the equivalent builds HMAC-SHA256 out -of `SHA2()`. Create the two functions and the two validation procedures once per -schema, then add a `BEFORE INSERT` and a `BEFORE UPDATE` trigger per encrypted -column. Replace `SCHEMA_NAME` with the value of `encryption_metadata_schema` -(`encrypt` by default). Requires MySQL 5.7+ / MariaDB 10.2+ for `SHA2()`. On -Aurora/RDS MySQL, creating the functions may require the cluster parameter -`log_bin_trust_function_creators` to be set to `1`. +MySQL has no built-in HMAC function, so +[`trigger_mysql.sql`](https://github.com/aws/aws-advanced-ruby-driver-wrapper/blob/main/lib/aws_advanced_ruby_driver_wrapper/plugins/kms_encryption/sql/trigger_mysql.sql) builds HMAC-SHA256 out of +`SHA2()`. Run it once per schema to create the two functions and the two +validation procedures, then add a `BEFORE INSERT` and a `BEFORE UPDATE` +trigger per encrypted column. Replace `SCHEMA_NAME` in the file with the value +of `encryption_metadata_schema` (`encrypt` by default). Requires MySQL 5.7+ / +MariaDB 10.2+ for `SHA2()`. On Aurora/RDS MySQL, creating the functions may +require the cluster parameter `log_bin_trust_function_creators` to be set to +`1`. :::note -The SQL below uses `DELIMITER`, which is a command of the `mysql` command-line -client rather than SQL. To run it through a driver, a Rails migration, or any -other tool that sends one statement at a time, leave out the `DELIMITER` -lines and send each `DROP`, `CREATE FUNCTION`, `CREATE PROCEDURE` and -`CREATE TRIGGER` statement on its own, without its trailing `$$`. +The file and the trigger SQL below use `DELIMITER`, which is a command of the +`mysql` command-line client rather than SQL. To run them through a driver, a +Rails migration, or any other tool that sends one statement at a time, leave +out the `DELIMITER` lines and send each `DROP`, `CREATE FUNCTION`, +`CREATE PROCEDURE` and `CREATE TRIGGER` statement on its own, without its +trailing `$$`. ::: -```sql -DELIMITER $$ - --- HMAC-SHA256 built from SHA2(), which MySQL has no native HMAC for. -DROP FUNCTION IF EXISTS hmac_sha256$$ -CREATE FUNCTION hmac_sha256( - message VARBINARY(65535), - key_data VARBINARY(64) -) -RETURNS VARBINARY(32) -DETERMINISTIC -NO SQL -BEGIN - DECLARE block_size INT DEFAULT 64; -- SHA-256 block size - DECLARE key_padded VARBINARY(64); - DECLARE ipad VARBINARY(64); - DECLARE opad VARBINARY(64); - DECLARE i INT DEFAULT 1; - DECLARE key_byte INT; - - -- Reduce an over-long key to its hash, then zero-pad the key to the block size. - IF LENGTH(key_data) > block_size THEN - SET key_padded = CONCAT(UNHEX(SHA2(key_data, 256)), REPEAT(X'00', block_size - 32)); - ELSE - SET key_padded = CONCAT(key_data, REPEAT(X'00', block_size - LENGTH(key_data))); - END IF; - - -- ipad = key XOR 0x36 per byte, opad = key XOR 0x5C per byte, one raw byte at a time. - SET ipad = X''; - SET opad = X''; - WHILE i <= block_size DO - SET key_byte = ASCII(SUBSTRING(key_padded, i, 1)); - SET ipad = CONCAT(ipad, UNHEX(LPAD(HEX(key_byte ^ 0x36), 2, '0'))); - SET opad = CONCAT(opad, UNHEX(LPAD(HEX(key_byte ^ 0x5C), 2, '0'))); - SET i = i + 1; - END WHILE; - - RETURN UNHEX(SHA2(CONCAT(opad, UNHEX(SHA2(CONCAT(ipad, message), 256))), 256)); -END$$ - --- Verifies that a stored value carries a valid HMAC for the given HMAC key. -DROP FUNCTION IF EXISTS verify_encrypted_data_hmac$$ -CREATE FUNCTION verify_encrypted_data_hmac( - data VARBINARY(65535), - hmac_key VARBINARY(32) -) -RETURNS BOOLEAN -DETERMINISTIC -NO SQL -BEGIN - -- Minimum payload: 32 (HMAC) + 4 (key id) + 1 (type) + 12 (IV) + 0 (ciphertext) + 16 (GCM tag) = 65. - IF data IS NULL OR LENGTH(data) < 65 THEN - RETURN FALSE; - END IF; - - RETURN SUBSTRING(data, 1, 32) = hmac_sha256(SUBSTRING(data, 33), hmac_key); -END$$ - --- Called from a BEFORE INSERT trigger (and by the BEFORE UPDATE procedure) to reject a value that is --- not a valid kms_encryption payload. Replace SCHEMA_NAME with encryption_metadata_schema. -DROP PROCEDURE IF EXISTS validate_encrypted_data_hmac_before_insert$$ -CREATE PROCEDURE validate_encrypted_data_hmac_before_insert( - IN p_table_name VARCHAR(64), - IN p_column_name VARCHAR(64), - IN column_value VARBINARY(65535) -) -BEGIN - DECLARE v_hmac_key VARBINARY(32); - - IF column_value IS NOT NULL THEN - SELECT ks.hmac_key INTO v_hmac_key - FROM SCHEMA_NAME.encryption_metadata em - JOIN SCHEMA_NAME.key_storage ks ON em.key_id = ks.id - WHERE em.table_name = p_table_name - AND em.column_name = p_column_name - LIMIT 1; - - IF v_hmac_key IS NULL THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'No HMAC key is configured for the encrypted column'; - END IF; - - IF NOT verify_encrypted_data_hmac(column_value, v_hmac_key) THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'Column does not carry a valid HMAC tag (plaintext or tampered value)'; - END IF; - END IF; -END$$ - --- Called from a BEFORE UPDATE trigger. An UPDATE that leaves the value as it was is not --- re-checked; see "Updates after a key rotation". -DROP PROCEDURE IF EXISTS validate_encrypted_data_hmac_before_update$$ -CREATE PROCEDURE validate_encrypted_data_hmac_before_update( - IN p_table_name VARCHAR(64), - IN p_column_name VARCHAR(64), - IN new_value VARBINARY(65535), - IN old_value VARBINARY(65535) -) -BEGIN - IF NOT (new_value <=> old_value) THEN - CALL validate_encrypted_data_hmac_before_insert(p_table_name, p_column_name, new_value); - END IF; -END$$ - -DELIMITER ; -``` - Then create a pair of triggers for every column that you want to encrypt. For example, on `users.ssn`: @@ -788,6 +636,39 @@ encrypted values were re-encrypted. A value that is new to the row - an checked, and must carry the current key's tag. The plugin always writes new values with the current key, so its writes pass. +### Updating the trigger SQL + +The trigger SQL changes from time to time, independently of the wrapper +version. A database keeps the version it was set up with until the file is +run again, so re-run the file for your engine when a newer version is listed +below. Re-running it replaces the functions and procedures without changing +any data, and the per-column triggers keep working without being re-created. +On MySQL the file drops and re-creates each routine, so a write to an +encrypted column can fail in the moment between the two: re-run it while +writes are quiet. + +Each file records its version in a database comment. To check the version a +database has: + +```sql +-- PostgreSQL +SELECT obj_description('enforce_encrypted_column'::regproc, 'pg_proc'); +``` + +```sql +-- MySQL, in the schema the procedures were created in +SELECT ROUTINE_COMMENT FROM information_schema.ROUTINES + WHERE ROUTINE_SCHEMA = DATABASE() + AND ROUTINE_NAME = 'validate_encrypted_data_hmac_before_insert'; +``` + +An empty result means the SQL was installed before versions were recorded. + +| Engine | Version | Change | If your database has an earlier version | +|---|---|---|---| +| PostgreSQL | v2 | Reads the column's HMAC key from `key_storage` for every row. | Re-run `trigger_pg.sql`. An empty result is an earlier version. | +| MySQL | v1 | Records the version. The SQL is otherwise unchanged. | No action needed. An empty result is equivalent to v1. | + ## Hardening the deployment