-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcolumn_encrypt--3.1.sql
More file actions
2297 lines (1990 loc) · 70 KB
/
Copy pathcolumn_encrypt--3.1.sql
File metadata and controls
2297 lines (1990 loc) · 70 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* share/extension/column_encrypt--3.1.sql */
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION column_encrypt" to load this file. \quit
SET check_function_bodies TO off;
/*
* Create encrypted types
*/
CREATE TYPE encrypted_bytea;
CREATE TYPE encrypted_text;
/*
* input function for encrypted bytea
*/
CREATE FUNCTION col_enc_bytea_in(cstring) RETURNS encrypted_bytea
LANGUAGE c STABLE STRICT
AS 'column_encrypt', 'col_enc_bytea_in';
/*
* Output function for encrypted bytea
*/
CREATE FUNCTION col_enc_bytea_out(encrypted_bytea) RETURNS cstring
LANGUAGE c STABLE STRICT
AS 'column_encrypt', 'col_enc_bytea_out';
/*
* Define recv function for encrypted bytea
*/
CREATE FUNCTION col_enc_recv_bytea(internal) RETURNS encrypted_bytea
LANGUAGE c IMMUTABLE STRICT
AS 'column_encrypt', 'col_enc_recv';
/*
* Define send function for encrypted bytea
*/
CREATE FUNCTION col_enc_send_bytea(encrypted_bytea) RETURNS bytea
LANGUAGE c IMMUTABLE STRICT
AS 'column_encrypt', 'col_enc_send';
/*
* Define encrypted_bytea data type
*/
CREATE TYPE encrypted_bytea (
INTERNALLENGTH = variable,
INPUT = col_enc_bytea_in,
OUTPUT = col_enc_bytea_out,
RECEIVE = col_enc_recv_bytea,
SEND = col_enc_send_bytea,
ALIGNMENT = int4,
STORAGE = extended
);
/*
* Input function for encrypted_text
*/
CREATE FUNCTION col_enc_text_in(cstring) RETURNS encrypted_text
LANGUAGE c STABLE STRICT
AS 'column_encrypt', 'col_enc_text_in';
/*
* Output function for encrypted_text
*/
CREATE FUNCTION col_enc_text_out(encrypted_text) RETURNS cstring
LANGUAGE c STABLE STRICT
AS 'column_encrypt', 'col_enc_text_out';
/*
* Define recv function for encrypted text
*/
CREATE FUNCTION col_enc_recv_text(internal) RETURNS encrypted_text
LANGUAGE c IMMUTABLE STRICT
AS 'column_encrypt', 'col_enc_recv';
/*
* Define send function for encrypted text
*/
CREATE FUNCTION col_enc_send_text(encrypted_text) RETURNS bytea
LANGUAGE c IMMUTABLE STRICT
AS 'column_encrypt', 'col_enc_send';
/*
* Define encrypted text data type
*/
CREATE TYPE encrypted_text (
INTERNALLENGTH = variable,
INPUT = col_enc_text_in,
OUTPUT = col_enc_text_out,
RECEIVE = col_enc_recv_text,
SEND = col_enc_send_text,
CATEGORY = 'S',
ALIGNMENT = int4,
STORAGE = extended
);
/*
* index operator for encrypted binary type
*/
CREATE FUNCTION col_enc_comp_eq_bytea(encrypted_bytea, encrypted_bytea) RETURNS boolean
LANGUAGE c STABLE STRICT
AS 'column_encrypt', 'col_enc_comp_eq_bytea';
/*
* index operator for encrypted text type
*/
CREATE FUNCTION col_enc_comp_eq_text(encrypted_text, encrypted_text) RETURNS boolean
LANGUAGE c STABLE STRICT
AS 'column_encrypt', 'col_enc_comp_eq_text';
/*
* define index operator for encrypted
* text
*/
CREATE OPERATOR = (
PROCEDURE = col_enc_comp_eq_text,
LEFTARG = encrypted_text,
RIGHTARG = encrypted_text,
RESTRICT = eqsel,
JOIN = eqjoinsel
);
/*
* define index operator for encrypted
* bytea
*/
CREATE OPERATOR = (
PROCEDURE = col_enc_comp_eq_bytea,
LEFTARG = encrypted_bytea,
RIGHTARG = encrypted_bytea,
RESTRICT = eqsel,
JOIN = eqjoinsel
);
/*
* Hash function for encrypted bytea
*/
CREATE FUNCTION enc_hash_encbytea(encrypted_bytea) RETURNS integer
LANGUAGE c STABLE STRICT
AS 'column_encrypt', 'enc_hash_encrted_data';
/*
* hash function for encrypted text
*/
CREATE FUNCTION enc_hash_enctext(encrypted_text) RETURNS integer
LANGUAGE c STABLE STRICT
AS 'column_encrypt', 'enc_hash_encrted_data';
CREATE FUNCTION enc_key_version(encrypted_text) RETURNS integer
LANGUAGE c IMMUTABLE STRICT
AS 'column_encrypt', 'enc_key_version_text';
CREATE FUNCTION enc_key_version(encrypted_bytea) RETURNS integer
LANGUAGE c IMMUTABLE STRICT
AS 'column_encrypt', 'enc_key_version_bytea';
CREATE FUNCTION loaded_cipher_key_versions() RETURNS integer[]
LANGUAGE c STABLE
AS 'column_encrypt', 'enc_loaded_key_versions';
/*
* define hash index for encrypted binary
*/
CREATE OPERATOR FAMILY hash_bytea_enc_ops USING hash;
CREATE OPERATOR CLASS hash_bytea_enc_ops
DEFAULT FOR TYPE encrypted_bytea USING hash FAMILY hash_bytea_enc_ops AS
OPERATOR 1 =(encrypted_bytea,encrypted_bytea) ,
FUNCTION 1 (encrypted_bytea, encrypted_bytea) enc_hash_encbytea(encrypted_bytea);
/*
* define hash index for encrypted text
*/
CREATE OPERATOR FAMILY hash_text_enc_ops USING hash;
CREATE OPERATOR CLASS hash_text_enc_ops
DEFAULT FOR TYPE encrypted_text USING hash FAMILY hash_text_enc_ops AS
OPERATOR 1 =(encrypted_text,encrypted_text) ,
FUNCTION 1 (encrypted_text, encrypted_text) enc_hash_enctext(encrypted_text);
/*
* Define cast functions for encrypted type column
*/
CREATE FUNCTION enctext(boolean) RETURNS encrypted_text
LANGUAGE c STRICT
AS 'column_encrypt', 'bool_enc_text';
CREATE FUNCTION enctext(character) RETURNS encrypted_text
LANGUAGE c STABLE STRICT
AS 'column_encrypt', 'enc_text_trim';
CREATE FUNCTION enctext(inet) RETURNS encrypted_text
LANGUAGE c STABLE STRICT
AS 'column_encrypt', 'inet_enc_text';
CREATE FUNCTION enctext(xml) RETURNS encrypted_text
LANGUAGE c STABLE STRICT
AS 'column_encrypt', 'xml_enc_text';
CREATE FUNCTION regclass(encrypted_text) RETURNS regclass
LANGUAGE c STABLE STRICT
AS 'column_encrypt', 'enc_text_regclass';
/*
* encrypted text -> text
*/
CREATE CAST (encrypted_text AS text)
WITH INOUT AS IMPLICIT;
/*
* text -> encrypted text
*/
CREATE CAST (text AS encrypted_text)
WITH INOUT AS IMPLICIT;
/*
* boolean -> encrypted text
*/
CREATE CAST (boolean AS encrypted_text)
WITH FUNCTION enctext(boolean)
AS ASSIGNMENT;
/*
* character -> encrypted text
*/
CREATE CAST (character AS encrypted_text)
WITH FUNCTION enctext(character)
AS ASSIGNMENT;
/*
* cidr -> encrypted text
*/
CREATE CAST (cidr AS encrypted_text)
WITH FUNCTION enctext(inet)
AS ASSIGNMENT;
/*
* inet -> encrypted text
*/
CREATE CAST (inet AS encrypted_text)
WITH FUNCTION enctext(inet)
AS ASSIGNMENT;
/*
* xml -> encrypted text
*/
CREATE CAST (xml AS encrypted_text)
WITH FUNCTION enctext(xml)
AS ASSIGNMENT;
/*
* encrypted text -> regclass
*/
CREATE CAST (encrypted_text AS regclass)
WITH FUNCTION regclass(encrypted_text)
AS ASSIGNMENT;
/*
* binary -> encrypted binary
*/
CREATE CAST (encrypted_bytea AS bytea)
WITH INOUT
AS IMPLICIT;
/*
* encrypted binary -> binary
*/
CREATE CAST (bytea AS encrypted_bytea)
WITH INOUT
AS ASSIGNMENT;
/*
* define table for managing encryption key
*/
CREATE TABLE cipher_key_table (
key_version integer PRIMARY KEY CHECK (key_version > 0 AND key_version <= 32767),
wrapped_key bytea NOT NULL,
algorithm text NOT NULL,
key_state text NOT NULL DEFAULT 'pending'
CHECK (key_state IN ('pending', 'active', 'retired', 'revoked')),
created_at timestamptz NOT NULL DEFAULT now(),
state_changed_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz DEFAULT NULL,
description text DEFAULT NULL,
last_used_at timestamptz DEFAULT NULL,
use_count bigint NOT NULL DEFAULT 0
);
CREATE INDEX cipher_key_table_algo_idx ON cipher_key_table(algorithm);
CREATE UNIQUE INDEX cipher_key_table_single_active_idx
ON cipher_key_table ((1))
WHERE key_state = 'active';
/*
* Audit log table for key management operations
*/
CREATE TABLE cipher_key_audit_log (
id bigserial PRIMARY KEY,
operation text NOT NULL,
key_version integer,
performed_by name NOT NULL DEFAULT session_user,
performed_at timestamptz NOT NULL DEFAULT now(),
details jsonb DEFAULT NULL
);
CREATE INDEX cipher_key_audit_log_key_version_idx ON cipher_key_audit_log(key_version);
CREATE INDEX cipher_key_audit_log_performed_at_idx ON cipher_key_audit_log(performed_at);
REVOKE ALL ON TABLE cipher_key_audit_log FROM PUBLIC;
ALTER TABLE cipher_key_audit_log ENABLE ROW LEVEL SECURITY;
CREATE POLICY cipher_key_audit_log_superuser_only ON cipher_key_audit_log
FOR ALL
TO PUBLIC
USING (false)
WITH CHECK (false);
/* Restrict access to cipher_key_table: only superusers can read it */
REVOKE ALL ON TABLE cipher_key_table FROM PUBLIC;
ALTER TABLE cipher_key_table ENABLE ROW LEVEL SECURITY;
/* Only superusers (who bypass RLS) can query this table directly */
CREATE POLICY cipher_key_table_superuser_only ON cipher_key_table
FOR ALL
TO PUBLIC
USING (false)
WITH CHECK (false);
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'column_encrypt_admin') THEN
EXECUTE 'CREATE ROLE column_encrypt_admin NOLOGIN';
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'column_encrypt_runtime') THEN
EXECUTE 'CREATE ROLE column_encrypt_runtime NOLOGIN';
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'column_encrypt_reader') THEN
EXECUTE 'CREATE ROLE column_encrypt_reader NOLOGIN';
END IF;
END;
$$;
/*
* Function descriptions:
* 1. cipher_key_disable_log:
* Function for log redaction of INSERT/UPDATE/DELETE/function calls
* Arguments - No arguments
* Returns - boolean (true/false)
*
* 2. cipher_key_enable_log:
* Function for enabling the logging of statements in postgresql logs
* Arguments - No Argument
* Returns - boolean (true/false)
*
* 3. cipher_key_reencrypt_data:
* Function to change the key and re-encrypt the encrypted column data
* Arguments - re-encrypt specified data periodically using encryption
* key which is specified custom parameter
* @return true if re-encryption is successfully done
*/
--
-- Name: cipher_key_disable_log(); Type: FUNCTION; Schema: public; Owner: enterprisedb
--
CREATE FUNCTION cipher_key_disable_log() RETURNS boolean
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO public
AS $$
BEGIN
SET track_activities = off;
RETURN TRUE;
END;
$$;
--
-- Name: cipher_key_enable_log(); Type: FUNCTION; Schema: public; Owner: enterprisedb
--
CREATE FUNCTION cipher_key_enable_log() RETURNS boolean
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO public
AS $$
BEGIN
SET track_activities = DEFAULT;
RETURN TRUE;
END;
$$;
--
-- Name: register_cipher_key(text, text, text, integer, boolean); Type: FUNCTION;
-- Args: cipher_key, cipher_algorithm, master_passphrase (Key Encryption Key), key_version, make_active
--
CREATE FUNCTION register_cipher_key(
cipher_key text,
cipher_algorithm text,
master_passphrase text,
p_key_version integer,
p_make_active boolean,
p_expires_at timestamptz DEFAULT NULL,
p_description text DEFAULT NULL
) RETURNS integer
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO public
AS $$
BEGIN
/* mask pg_stat_activity's query */
PERFORM pgstat_actv_mask();
IF cipher_key IS NULL OR cipher_key = '' THEN
RAISE EXCEPTION 'EDB-ENC0002 new cipher key is invalid';
END IF;
/* DEK must be at least 16 bytes for AES-128 security */
IF octet_length(cipher_key) < 16 THEN
RAISE EXCEPTION 'EDB-ENC0049 cipher key must be at least 16 bytes for cryptographic strength';
END IF;
IF master_passphrase IS NULL OR master_passphrase = '' THEN
RAISE EXCEPTION 'EDB-ENC0037 master passphrase is invalid';
END IF;
/* validate encryption algorithm — only aes is supported */
IF cipher_algorithm != 'aes' THEN
RAISE EXCEPTION 'EDB-ENC0003 invalid cipher algorithm "%", only "aes" is supported', cipher_algorithm;
END IF;
IF p_key_version IS NULL OR p_key_version <= 0 THEN
RAISE EXCEPTION 'EDB-ENC0043 key version must be a positive integer';
END IF;
IF p_key_version > 32767 THEN
RAISE EXCEPTION 'EDB-ENC0052 key version must not exceed 32767 (ciphertext header limit)';
END IF;
/* validate expiration is in the future if provided */
IF p_expires_at IS NOT NULL AND p_expires_at <= now() THEN
RAISE EXCEPTION 'EDB-ENC0050 expiration time must be in the future';
END IF;
LOCK TABLE cipher_key_table IN EXCLUSIVE MODE;
IF EXISTS (
SELECT 1
FROM cipher_key_table
WHERE key_version = p_key_version
) THEN
RAISE EXCEPTION 'EDB-ENC0044 key version % is already registered', p_key_version;
END IF;
IF p_make_active THEN
UPDATE cipher_key_table
SET key_state = 'retired',
state_changed_at = now()
WHERE key_state = 'active';
END IF;
INSERT INTO cipher_key_table(key_version, wrapped_key, algorithm, key_state, state_changed_at, expires_at, description)
VALUES(
p_key_version,
pgp_sym_encrypt(cipher_key, master_passphrase, 'cipher-algo=aes256, s2k-mode=3'),
cipher_algorithm,
CASE WHEN p_make_active THEN 'active' ELSE 'pending' END,
now(),
p_expires_at,
p_description
);
/* Log the operation (non-fatal if logging fails) */
BEGIN
INSERT INTO cipher_key_audit_log(operation, key_version, details)
VALUES(
'register',
p_key_version,
jsonb_build_object(
'make_active', p_make_active,
'expires_at', p_expires_at,
'description', p_description
)
);
EXCEPTION
WHEN OTHERS THEN
/* Audit logging failure should not prevent key registration */
NULL;
END;
RETURN p_key_version;
END;
$$;
CREATE FUNCTION register_cipher_key(text, text, text) RETURNS integer
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO public
AS $$
BEGIN
RETURN register_cipher_key(
$1,
$2,
$3,
current_setting('encrypt.key_version')::integer,
true
);
END;
$$;
--
-- Name: enc_rm_key(); Type: FUNCTION; Schema: public; Owner: enterprisedb
--
CREATE FUNCTION enc_rm_key() RETURNS boolean
LANGUAGE c STRICT
AS 'column_encrypt', 'enc_rm_key';
--
-- Name: enc_rm_prv_key(); Type: FUNCTION; Schema: public; Owner: enterprisedb
--
CREATE FUNCTION enc_rm_prv_key() RETURNS boolean
LANGUAGE c STRICT
AS 'column_encrypt', 'enc_rm_prv_key';
--
-- Name: enc_store_key(text, text); Type: FUNCTION; Schema: public; Owner: enterprisedb
--
CREATE FUNCTION enc_store_key(text, text) RETURNS boolean
LANGUAGE c STRICT
AS 'column_encrypt', 'enc_store_key';
--
-- Name: enc_store_prv_key(text, text); Type: FUNCTION; Schema: public; Owner: enterprisedb
--
CREATE FUNCTION enc_store_prv_key(text, text) RETURNS boolean
LANGUAGE c STRICT
AS 'column_encrypt', 'enc_store_prv_key';
--
-- Name: pgstat_actv_mask(); Type: FUNCTION; Schema: public; Owner: enterprisedb
--
CREATE FUNCTION pgstat_actv_mask() RETURNS void
LANGUAGE c STABLE STRICT
AS 'column_encrypt', 'pgstat_actv_mask';
--
-- Name: load_key(text); Type: FUNCTION; Schema: public; Owner: enterprisedb
--
CREATE FUNCTION load_key(text) RETURNS boolean
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO public
AS $_$
DECLARE
cipher_key ALIAS FOR $1;
f_key_num INTEGER; /* number of active keys */
old_key_version text;
v_key_version integer;
BEGIN
/* mask pg_stat_activity's query */
PERFORM pgstat_actv_mask();
old_key_version := current_setting('encrypt.key_version', true);
/* drop all key information in memory */
PERFORM enc_rm_key();
IF cipher_key IS NOT NULL THEN
SELECT count(*) INTO f_key_num
FROM cipher_key_table
WHERE key_state = 'active';
IF f_key_num = 0 THEN
RETURN FALSE;
ELSIF f_key_num > 1 THEN
RAISE EXCEPTION 'EDB-ENC0045 more than one active key exists in cipher_key_table';
END IF;
BEGIN
SELECT key_version INTO v_key_version
FROM cipher_key_table
WHERE key_state = 'active';
PERFORM set_config('encrypt.key_version', v_key_version::text, false);
PERFORM enc_store_key(pgp_sym_decrypt(wrapped_key, cipher_key), algorithm)
FROM cipher_key_table
WHERE key_state = 'active';
/* Update usage statistics */
UPDATE cipher_key_table
SET last_used_at = now(),
use_count = use_count + 1
WHERE key_version = v_key_version;
EXCEPTION
WHEN OTHERS THEN
PERFORM enc_rm_key();
IF old_key_version IS NOT NULL THEN
PERFORM set_config('encrypt.key_version', old_key_version, false);
END IF;
RAISE EXCEPTION 'EDB-ENC0012 cipher key is not correct';
END;
END IF;
RETURN TRUE;
END;
$_$;
CREATE FUNCTION load_key_by_version(text, integer) RETURNS boolean
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO public
AS $$
DECLARE
master_passphrase ALIAS FOR $1;
requested_version ALIAS FOR $2;
old_key_version text;
BEGIN
IF requested_version IS NULL OR requested_version <= 0 THEN
RAISE EXCEPTION 'EDB-ENC0043 key version must be a positive integer';
END IF;
IF NOT EXISTS (
SELECT 1
FROM cipher_key_table
WHERE key_version = requested_version
AND key_state <> 'revoked'
) THEN
RETURN FALSE;
END IF;
old_key_version := current_setting('encrypt.key_version', true);
PERFORM pgstat_actv_mask();
BEGIN
PERFORM set_config('encrypt.key_version', requested_version::text, false);
PERFORM enc_store_key(pgp_sym_decrypt(wrapped_key, master_passphrase), algorithm)
FROM cipher_key_table
WHERE key_version = requested_version
AND key_state <> 'revoked';
IF NOT FOUND THEN
IF old_key_version IS NOT NULL THEN
PERFORM set_config('encrypt.key_version', old_key_version, false);
END IF;
RETURN FALSE;
END IF;
/* Update usage statistics */
UPDATE cipher_key_table
SET last_used_at = now(),
use_count = use_count + 1
WHERE key_version = requested_version;
IF old_key_version IS NOT NULL THEN
PERFORM set_config('encrypt.key_version', old_key_version, false);
END IF;
EXCEPTION
WHEN OTHERS THEN
IF old_key_version IS NOT NULL THEN
PERFORM set_config('encrypt.key_version', old_key_version, false);
END IF;
RAISE EXCEPTION 'EDB-ENC0012 cipher key is not correct';
END;
RETURN TRUE;
END;
$$;
--
-- Name: rm_key_details(); Type: FUNCTION; Schema: public; Owner: enterprisedb
--
CREATE FUNCTION rm_key_details() RETURNS boolean
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO public
AS $$
BEGIN
RETURN enc_rm_key();
END;
$$;
CREATE FUNCTION activate_cipher_key(integer) RETURNS boolean
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO public
AS $$
DECLARE
requested_version ALIAS FOR $1;
old_key_version text;
old_active_version integer;
BEGIN
IF NOT EXISTS (
SELECT 1
FROM cipher_key_table
WHERE key_version = requested_version
AND key_state <> 'revoked'
) THEN
RETURN FALSE;
END IF;
/* Check if key is expired */
IF EXISTS (
SELECT 1
FROM cipher_key_table
WHERE key_version = requested_version
AND expires_at IS NOT NULL
AND expires_at <= now()
) THEN
RAISE EXCEPTION 'EDB-ENC0051 cannot activate expired key version %', requested_version;
END IF;
old_key_version := current_setting('encrypt.key_version', true);
/* Get current active version for audit log */
SELECT key_version INTO old_active_version
FROM cipher_key_table
WHERE key_state = 'active';
BEGIN
UPDATE cipher_key_table
SET key_state = CASE
WHEN key_version = requested_version THEN 'active'
WHEN key_state = 'active' THEN 'retired'
ELSE key_state
END,
state_changed_at = CASE
WHEN key_version = requested_version OR key_state = 'active' THEN now()
ELSE state_changed_at
END
WHERE key_state <> 'revoked';
PERFORM set_config('encrypt.key_version', requested_version::text, false);
EXCEPTION
WHEN OTHERS THEN
IF old_key_version IS NOT NULL THEN
PERFORM set_config('encrypt.key_version', old_key_version, false);
END IF;
RAISE;
END;
/* Log the operation (non-fatal if logging fails) */
BEGIN
INSERT INTO cipher_key_audit_log(operation, key_version, details)
VALUES(
'activate',
requested_version,
jsonb_build_object('previous_active_version', old_active_version)
);
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
RETURN TRUE;
END;
$$;
CREATE FUNCTION revoke_cipher_key(integer) RETURNS boolean
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO public
AS $$
DECLARE
requested_version ALIAS FOR $1;
old_state text;
BEGIN
/* Get current state for audit log */
SELECT key_state INTO old_state
FROM cipher_key_table
WHERE key_version = requested_version;
UPDATE cipher_key_table
SET key_state = 'revoked',
state_changed_at = now()
WHERE key_version = requested_version;
IF FOUND THEN
/* Log the operation (non-fatal if logging fails) */
BEGIN
INSERT INTO cipher_key_audit_log(operation, key_version, details)
VALUES(
'revoke',
requested_version,
jsonb_build_object('previous_state', old_state)
);
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
END IF;
RETURN FOUND;
END;
$$;
CREATE FUNCTION cipher_key_versions()
RETURNS TABLE (
key_version integer,
algorithm text,
key_state text,
created_at timestamptz,
state_changed_at timestamptz,
expires_at timestamptz,
is_expired boolean,
description text,
last_used_at timestamptz,
use_count bigint
)
LANGUAGE sql SECURITY DEFINER
SET search_path TO public
AS $$
SELECT c.key_version, c.algorithm, c.key_state, c.created_at, c.state_changed_at,
c.expires_at,
(c.expires_at IS NOT NULL AND c.expires_at <= now()) AS is_expired,
c.description,
c.last_used_at,
c.use_count
FROM cipher_key_table AS c
ORDER BY c.key_version;
$$;
/*
* Function to check for and report expired keys
*/
CREATE FUNCTION cipher_key_check_expired()
RETURNS TABLE (
key_version integer,
key_state text,
expires_at timestamptz,
expired_since interval
)
LANGUAGE sql SECURITY DEFINER
SET search_path TO public
AS $$
SELECT c.key_version, c.key_state, c.expires_at,
(now() - c.expires_at) AS expired_since
FROM cipher_key_table AS c
WHERE c.expires_at IS NOT NULL
AND c.expires_at <= now()
AND c.key_state NOT IN ('revoked')
ORDER BY c.expires_at;
$$;
/*
* Function to view audit log (for admins)
*/
CREATE FUNCTION cipher_key_audit_log_view(
p_limit integer DEFAULT 100,
p_key_version integer DEFAULT NULL
)
RETURNS TABLE (
id bigint,
operation text,
key_version integer,
performed_by name,
performed_at timestamptz,
details jsonb
)
LANGUAGE sql SECURITY DEFINER
SET search_path TO public
AS $$
SELECT l.id, l.operation, l.key_version, l.performed_by, l.performed_at, l.details
FROM cipher_key_audit_log AS l
WHERE (p_key_version IS NULL OR l.key_version = p_key_version)
ORDER BY l.performed_at DESC
LIMIT p_limit;
$$;
CREATE FUNCTION column_encrypt_blind_index_text(text, text) RETURNS text
LANGUAGE sql IMMUTABLE STRICT
AS $$
SELECT encode(
hmac(
convert_to($1, 'UTF8'),
convert_to($2, 'UTF8'),
'sha256'
),
'hex'
);
$$;
CREATE FUNCTION column_encrypt_blind_index_bytea(bytea, text) RETURNS text
LANGUAGE sql IMMUTABLE STRICT
AS $$
SELECT encode(
hmac(
$1,
convert_to($2, 'UTF8'),
'sha256'
),
'hex'
);
$$;
--
-- Name: cipher_key_reencrypt_data(text, text, text); Type: FUNCTION
-- Args: schema_name, table_name, column_name
-- Re-encrypts all values in the specified encrypted column using the current key.
-- Requires: the relevant ciphertext versions to be loaded in the session keyring
-- (for example via load_key_by_version()), and encrypt.key_version set to the
-- destination version to be written into new ciphertext headers.
-- Returns: number of rows re-encrypted.
--
CREATE FUNCTION cipher_key_reencrypt_data(text, text, text) RETURNS bigint
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO public
AS $_$
DECLARE
p_schema ALIAS FOR $1;
p_table ALIAS FOR $2;
p_column ALIAS FOR $3;
v_sql TEXT;
v_count BIGINT;
v_col_type TEXT;
BEGIN
/* Mask pg_stat_activity */
PERFORM pgstat_actv_mask();
/* Encryption must be enabled for re-encryption to work */
IF current_setting('encrypt.enable') <> 'on' THEN
RAISE EXCEPTION 'EDB-ENC0048 encrypt.enable must be on for data re-encryption';
END IF;
/* Validate the schema/table/column names to prevent SQL injection */
IF p_schema !~ '^[a-zA-Z_][a-zA-Z0-9_]*$' OR
p_table !~ '^[a-zA-Z_][a-zA-Z0-9_]*$' OR
p_column !~ '^[a-zA-Z_][a-zA-Z0-9_]*$' THEN
RAISE EXCEPTION 'EDB-ENC0041 invalid schema/table/column name';
END IF;
SELECT format_type(a.atttypid, a.atttypmod)
INTO v_col_type
FROM pg_attribute a
JOIN pg_class c
ON c.oid = a.attrelid
JOIN pg_namespace n
ON n.oid = c.relnamespace
WHERE n.nspname = p_schema
AND c.relname = p_table
AND a.attname = p_column
AND a.attnum > 0
AND NOT a.attisdropped;