-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtcle.c
1882 lines (1568 loc) · 50.2 KB
/
tcle.c
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
/*----------------------------------------------------------------------------
*
* Transparent Cell-Level Encryption
*
* Portions Copyright (c) 2020, Julien Tachoires
* Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* This extension implements a new Table Acces Method that extends core Heap AM
* and applies tuples AES 256 bits CBC encryption / decryption on the fly when
* column's type matches ENCRYPT_TEXT, ENCRYPT_NUMERIC or ENCRYPT_TIMESTAMPTZ.
*
* TCLE extension provides a lighweight key management system (KMS) based on
* 2-tier architecture: 1 master key per database, 1 table key per user table.
* Table keys are stored encrypted with database master key in a dedicated
* table.
*
* IDENTIFICATION
* tcle.c
*
*----------------------------------------------------------------------------
*/
#include "postgres.h"
#include "miscadmin.h"
#include "port.h"
#include "pgstat.h"
#include "access/genam.h"
#include "access/heapam.h"
#if (PG_VERSION_NUM >= 130000)
#include "access/heaptoast.h"
#endif
#include "access/rewriteheap.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/index.h"
#include "catalog/namespace.h"
#include "catalog/pg_am.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_type.h"
#include "common/sha2.h"
#include "commands/dbcommands.h"
#include "commands/extension.h"
#include "commands/progress.h"
#include "libpq/pqformat.h"
#include "miscadmin.h"
#include "storage/ipc.h"
#include "storage/lmgr.h"
#include "storage/bufmgr.h"
#include "storage/smgr.h"
#include "storage/proc.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgrprotos.h"
#include "utils/memutils.h"
#include "utils/numeric.h"
#include "utils/syscache.h"
#include "tcleheap.h"
#include "aes.h"
#include "kms.h"
#include "utils.h"
PG_MODULE_MAGIC;
/* Number of encryptable data types */
#define N_ENCRYPT_TYPES 3
#define IS_ENCRYPTABLE_TYPE(OID, ARRAY) \
(OID == ARRAY[0] || OID == ARRAY[1] || OID == ARRAY[2])
/*
* CommandCryptState* struct are used to store in a htab (local to backend) a
* flag or transient key related to current command. The flag will be use to
* disable encryption / decryption for some utility statements like VACUUM FULL
* or CLUSTER.
*/
typedef struct CommandCryptStateKey {
LocalTransactionId lxid; /* Local Transaction ID */
} CommandCryptStateKey;
typedef struct CommandCryptStateEntry {
CommandCryptStateKey key;
int8 flag;
unsigned char *transient_key;
} CommandCryptStateEntry;
/* Array of encryptable data type names currently implemented */
static const char *encrypt_types[N_ENCRYPT_TYPES] = {"encrypt_text",
"encrypt_numeric",
"encrypt_timestamptz"};
/* Saved hook values in case of unload */
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
static ProcessUtility_hook_type prev_ProcessUtility = NULL;
/* Link to shared memory and globals variables */
static ShmemKMSMasterKeysLock *shmmasterkeyslock = NULL;
static ShmemKMSKeyCache *shmkeycache = NULL;
static HTAB *shmmasterkeys = NULL;
static HTAB *command_crypt_state = NULL;
extern Datum encrypt_text_in(PG_FUNCTION_ARGS);
extern Datum encrypt_text_out(PG_FUNCTION_ARGS);
extern Datum tcle_set_passphrase(PG_FUNCTION_ARGS);
extern Datum tcle_change_passphrase(PG_FUNCTION_ARGS);
static bool RelationAMIsTcleam(Oid relid);
static HeapTuple EncryptDecryptHeapTuple(HeapTuple tuple, TupleDesc tupleDesc,
Oid tableId, int8 flag,
unsigned char *table_key,
Oid *type_oids);
static void LoadTableKey(Oid databaseId, Oid tableId,
unsigned char **table_keyPtr);
static void get_encrypt_type_oids(Oid **oidsPtr);
static void command_crypt_state_init(void);
static void command_crypt_state_set(LocalTransactionId lxid, int8 flag,
unsigned char *tkey);
static void command_crypt_state_rm(LocalTransactionId lxid);
static void command_crypt_state_mcb(void *arg);
static bool ShouldEncryptDecryptTTS(void);
static void SetNotEncryptDecryptTTS(void);
static void RemoveCommandCryptState(void);
static void BuildCommandTransientKey(void);
static bool GetCommandTransientKey(unsigned char **tkeyPtr);
void _PG_init(void);
void _PG_fini(void);
/* Hook function */
static void tcle_shmem_startup(void);
#if (PG_VERSION_NUM >= 130000)
static void tcle_ProcessUtility(PlannedStmt *pstmt,
const char *queryString,
ProcessUtilityContext context,
ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest,
QueryCompletion *qc);
#elif (PG_VERSION_NUM >= 120000)
static void tcle_ProcessUtility(PlannedStmt *pstmt,
const char *queryString,
ProcessUtilityContext context,
ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest,
char *qc);
#endif
PG_FUNCTION_INFO_V1(tcleam_handler);
PG_FUNCTION_INFO_V1(encrypt_text_in);
PG_FUNCTION_INFO_V1(encrypt_text_recv);
PG_FUNCTION_INFO_V1(encrypt_timestamptz_in);
PG_FUNCTION_INFO_V1(encrypt_timestamptz_out);
PG_FUNCTION_INFO_V1(encrypt_timestamptz_recv);
PG_FUNCTION_INFO_V1(encrypt_timestamptz_send);
PG_FUNCTION_INFO_V1(tcle_set_passphrase);
PG_FUNCTION_INFO_V1(tcle_change_passphrase);
void
_PG_init(void)
{
/*
* Ensures TCLE library has been loaded via shared_preload_libraries.
*/
if (!process_shared_preload_libraries_in_progress)
ereport(ERROR,
(errmsg("tcle must be loaded via shared_preload_libraries")));
RequestNamedLWLockTranche("tcle", 2);
/* Install hooks. */
prev_shmem_startup_hook = shmem_startup_hook;
prev_ProcessUtility = ProcessUtility_hook;
shmem_startup_hook = tcle_shmem_startup;
ProcessUtility_hook = tcle_ProcessUtility;
}
void
_PG_fini(void)
{
/* Uninstall hooks. */
shmem_startup_hook = prev_shmem_startup_hook;
ProcessUtility_hook = prev_ProcessUtility;
}
static void
tcle_shmem_startup(void)
{
bool found;
HASHCTL info;
if (prev_shmem_startup_hook)
prev_shmem_startup_hook();
/* Reset in case this is a restart within the postmaster */
shmmasterkeyslock = NULL;
shmkeycache = NULL;
/* Create or attach to the shared memory state */
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
/* Master keys htab lock */
shmmasterkeyslock = ShmemInitStruct("tcle master keys htable lock",
sizeof(shmmasterkeyslock),
&found);
if (!found)
{
shmmasterkeyslock->lock = &(GetNamedLWLockTranche("tcle")[0].lock);
}
memset(&info, 0, sizeof(info));
info.keysize = sizeof(KMSMasterKeysHashKey);
info.entrysize = sizeof(KMSMasterKeysEntry);
shmmasterkeys = ShmemInitHash("tcle master keys",
KMS_MAX_DATABASES,
KMS_MAX_DATABASES,
&info,
HASH_ELEM | HASH_BLOBS);
shmkeycache = ShmemInitStruct("tcle key cache",
sizeof(ShmemKMSKeyCache),
&found);
if (!found)
{
shmkeycache->lock = &(GetNamedLWLockTranche("tcle")[1].lock);
shmkeycache->position = 0;
shmkeycache->n_entries = 0;
}
LWLockRelease(AddinShmemInitLock);
ereport(LOG, (errmsg("tcle: extension loaded")));
}
/*
* Cache lookup function to check that relation access method is "tcleam"
*/
bool
RelationAMIsTcleam(Oid relid)
{
Form_pg_class classform;
Form_pg_am aform;
HeapTuple tuple_rel, tuple_am;
tuple_rel = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
if (!HeapTupleIsValid(tuple_rel))
ereport(ERROR,
(errmsg("tcle: cache lookup failed for relation %u", relid)));
classform = (Form_pg_class) GETSTRUCT(tuple_rel);
ReleaseSysCache(tuple_rel);
if (!classform->relam)
return false;
tuple_am = SearchSysCache1(AMOID, ObjectIdGetDatum(classform->relam));
if (!HeapTupleIsValid(tuple_am))
ereport(ERROR,
(errmsg("tcle: cache lookup failed for access method %u",
classform->relam)));
aform = (Form_pg_am) GETSTRUCT(tuple_am);
ReleaseSysCache(tuple_am);
return (strcmp(NameStr(aform->amname), "tcleam") == 0);
}
/*
* ProcessUtility hook function in charge of triggering KMS actions when some
* DDL related to tables using tcleam AM are executed. In some cases, like
* removing or renaming, we must gather informations before the DDL is really
* executed by standard_ProcessUtility(). In other cases, like table creation,
* we must do it after.
*/
void
#if (PG_VERSION_NUM >= 130000)
tcle_ProcessUtility(PlannedStmt *pstmt,
const char *queryString,
ProcessUtilityContext context,
ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest,
QueryCompletion *qc)
#elif (PG_VERSION_NUM >= 120000)
tcle_ProcessUtility(PlannedStmt *pstmt,
const char *queryString,
ProcessUtilityContext context,
ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest,
char *qc)
#endif
{
Node *parsetree = pstmt->utilityStmt;
List *actions = NIL;
switch (nodeTag(parsetree))
{
case T_DropStmt:
{
/*
* Handle DROP TABLE and DROP SCHEMA
*/
DropStmt *stmt;
ListCell *cell;
stmt = (DropStmt *) parsetree;
if (stmt->removeType == OBJECT_TABLE)
{
/*
* Handler DROP TABLE. In this case, we can take a look at
* table AM.
*/
foreach(cell, stmt->objects)
{
RangeVar *rel;
KMSKeyAction *kkact;
rel = makeRangeVarFromNameList((List *) lfirst(cell));
kkact = RelationGetKMSKeyAction(rel);
if (!OidIsValid(kkact->relid)
|| !RelationAMIsTcleam(kkact->relid))
{
pfree(kkact);
continue;
}
kkact->action_tag = AT_DEL_KEY;
actions = lappend(actions, kkact);
}
}
else if(stmt->removeType == OBJECT_SCHEMA)
{
/*
* Handle DROP SCHEMA .. CASCADE. No deep inspection here, just
* keep a track of schema name, we'll see later if some keys
* must be removed.
*/
foreach(cell, stmt->objects)
{
Node *object = lfirst(cell);
KMSKeyAction *kkact = new_kkact();
kkact->nspname = strdup(((Value *) object)->val.str);
kkact->action_tag = AT_DEL_NSP_KEY;
actions = lappend(actions, kkact);
}
}
break;
}
case T_AlterObjectSchemaStmt:
{
/*
* Handle ALTER TABLE .. SET SCHEMA
*/
AlterObjectSchemaStmt *stmt;
stmt = (AlterObjectSchemaStmt *) parsetree;
if (stmt->objectType == OBJECT_TABLE)
{
KMSKeyAction *kkact;
kkact = RelationGetKMSKeyAction(stmt->relation);
if (!OidIsValid(kkact->relid)
|| !RelationAMIsTcleam(kkact->relid))
{
pfree(kkact);
break;
}
kkact->new_nspname = strdup(stmt->newschema);
kkact->action_tag = AT_MOV_KEY;
actions = lappend(actions, kkact);
}
break;
}
case T_RenameStmt:
{
/*
* Handle ALTER TABLE .. RENAME TO ..
*/
RenameStmt *stmt;
stmt = (RenameStmt *) parsetree;
if (stmt->renameType == OBJECT_TABLE)
{
KMSKeyAction *kkact;
kkact = RelationGetKMSKeyAction(stmt->relation);
if (!OidIsValid(kkact->relid)
|| !RelationAMIsTcleam(kkact->relid))
{
pfree(kkact);
break;
}
kkact->new_relname = strdup(stmt->newname);
kkact->action_tag = AT_MOV_KEY;
actions = lappend(actions, kkact);
}
break;
}
case T_CreateTableAsStmt:
{
/*
* CREATE TABLE .. AS is a special case because we must generate
* and store in memory a transient AES key right before the DDL is
* executed by standard_ProcessUtility().
*/
CreateTableAsStmt *stmt;
stmt = (CreateTableAsStmt *) parsetree;
if (stmt->into->accessMethod
&& strcmp(stmt->into->accessMethod, "tcleam") == 0)
BuildCommandTransientKey();
break;
}
case T_DropdbStmt:
{
/*
* Handler DROP DATABASE. In this case, we just have to remove the
* key from shmem htab if exists.
*/
DropdbStmt *stmt;
Oid dbid;
stmt = (DropdbStmt *) parsetree;
/*
* Get database oid by its name and let standard_ProcessUtility()
* handle the error if not exists or the user is not the owner.
*/
dbid = get_database_oid(stmt->dbname, true);
if (!OidIsValid(dbid))
break;
if (!pg_database_ownercheck(dbid, GetUserId()))
break;
/*
* Remove the entry from master keys htab if exists.
*/
RemoveDatabaseMasterKey(shmmasterkeyslock, shmmasterkeys, dbid);
break;
}
default:
{
break;
}
}
if (prev_ProcessUtility)
prev_ProcessUtility(pstmt, queryString, context, params, queryEnv,
dest, qc);
else
standard_ProcessUtility(pstmt, queryString, context, params, queryEnv,
dest, qc);
switch (nodeTag(parsetree))
{
case T_CreateStmt:
{
/*
* Handle CREATE TABLE
*/
CreateStmt *stmt;
KMSKeyAction *kkact;
stmt = (CreateStmt *) parsetree;
kkact = RelationGetKMSKeyAction(stmt->relation);
if (!OidIsValid(kkact->relid)
|| !RelationAMIsTcleam(kkact->relid))
{
pfree(kkact);
break;
}
kkact->action_tag = AT_ADD_KEY;
actions = lappend(actions, kkact);
break;
}
case T_RenameStmt:
{
/*
* Handle ALTER SCHEMA .. RENAME TO ..
*/
RenameStmt *stmt;
stmt = (RenameStmt *) parsetree;
if (stmt->renameType == OBJECT_SCHEMA)
{
KMSKeyAction *kkact = new_kkact();
kkact->nspname = strdup(stmt->subname);
kkact->new_nspname = strdup(stmt->newname);
kkact->action_tag = AT_MOV_NSP_KEY;
actions = lappend(actions, kkact);
}
break;
}
case T_CreateTableAsStmt:
{
/*
* End of CREATE TABLE .. AS special case: we have now to build a
* new KMSKeyAction and push the action to further add the
* transient key in KMS table.
*/
CreateTableAsStmt *stmt;
KMSKeyAction *kkact;
stmt = (CreateTableAsStmt *) parsetree;
if (!stmt->into->accessMethod
|| strcmp(stmt->into->accessMethod, "tcleam") != 0)
break;
kkact = RelationGetKMSKeyAction(stmt->into->rel);
kkact->action_tag = AT_ADD_CTAS_KEY;
kkact->ctas_key = (unsigned char *) palloc(AES_KEYLEN);
if (!GetCommandTransientKey(&(kkact->ctas_key)))
{
/*
* CTAS but no transient key found ?
* This case should not happen but we handle it just in case.
*/
pfree(kkact->ctas_key);
pfree(kkact);
ereport(ERROR, (errmsg("tcle: transient key not found")));
}
RemoveCommandCryptState();
actions = lappend(actions, kkact);
break;
}
default:
{
break;
}
}
if (actions != NIL)
{
unsigned char *master_key;
master_key = (unsigned char *) palloc(AES_KEYLEN);
/* Get master key from shared memory */
if (!GetDatabaseMasterKey(shmmasterkeyslock, shmmasterkeys,
MyDatabaseId, &master_key))
ereport(ERROR,
(errmsg("tcle: master key not found for this database")));
/* Apply KMS changes */
ApplyKMSKeyActions(actions, master_key);
list_free(actions);
}
}
/*
* encrypt_text type input function.
*/
Datum
encrypt_text_in(PG_FUNCTION_ARGS)
{
char *inputText = PG_GETARG_CSTRING(0);
if (strlen(inputText) > 2048)
ereport(ERROR,
(errmsg("tcle: value too long for type encrypt_text, maximum "
"allowed size is 2048 bytes")));
PG_RETURN_TEXT_P(cstring_to_text(inputText));
}
/*
* Converts external binary format to encrypt_text
*/
Datum
encrypt_text_recv(PG_FUNCTION_ARGS)
{
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
text *result;
char *str;
int nbytes;
str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
if (nbytes > 2048)
{
pfree(str);
ereport(ERROR,
(errmsg("tcle: value too long for type encrypt_text, maximum "
"allowed size is 2048 bytes")));
}
result = cstring_to_text_with_len(str, nbytes);
pfree(str);
PG_RETURN_TEXT_P(result);
}
/*
* encrypt_timestamptz type input function.
*
* Internal representation is Numeric because we need to use variable length
* types when encrypting. Variable length types like Numeric allow us to have
* extra bytes to store AES IV and padding.
*/
Datum
encrypt_timestamptz_in(PG_FUNCTION_ARGS)
{
Datum tstz = timestamptz_in(fcinfo);
return DirectFunctionCall1(int8_numeric, DatumGetTimestampTz(tstz));
}
/*
* encrypt_timestamptz type output function.
*/
Datum
encrypt_timestamptz_out(PG_FUNCTION_ARGS)
{
Numeric num_tstz = PG_GETARG_NUMERIC(0);
Datum int64_tstz;
int64_tstz = DirectFunctionCall1(numeric_int8, NumericGetDatum(num_tstz));
return DirectFunctionCall1(timestamptz_out, int64_tstz);
}
/*
* Converts external binary format to encrypt_timestamptz
*/
Datum
encrypt_timestamptz_recv(PG_FUNCTION_ARGS)
{
Datum tstz = timestamptz_recv(fcinfo);
return DirectFunctionCall1(int8_numeric, DatumGetTimestampTz(tstz));
}
/*
* Converts encrypt_timestamptz to external binary format
*/
Datum
encrypt_timestamptz_send(PG_FUNCTION_ARGS)
{
Numeric num_tstz = PG_GETARG_NUMERIC(0);
Datum int64_tstz;
int64_tstz = DirectFunctionCall1(numeric_int8, NumericGetDatum(num_tstz));
return DirectFunctionCall1(timestamptz_send, int64_tstz);
}
/*
* Unsecure (the passphrase could leak in logs) and temporary user function to
* set a master key using a passphrase.
* Master key is the result of hashing the passphrase with sha256.
*/
Datum
tcle_set_passphrase(PG_FUNCTION_ARGS)
{
char *passphrase = PG_GETARG_CSTRING(0);
pg_sha256_ctx ctx;
unsigned char buf[PG_SHA256_DIGEST_LENGTH];
unsigned char master_key[AES_KEYLEN];
/*
* ACL check against database: only the owner or a superuser can set a
* database master key.
*/
if (!pg_database_ownercheck(MyDatabaseId, GetUserId()))
ereport(ERROR,
(errmsg("tcle: only database owner and superusers are allowed "
"to set the master key")));
if (strlen(passphrase) == 0)
ereport(ERROR, (errmsg("tcle: passphrase should not be empty")));
/* Compute sha256 hash of the passphrase */
pg_sha256_init(&ctx);
pg_sha256_update(&ctx, (unsigned char *) VARDATA_ANY(passphrase),
VARSIZE_ANY_EXHDR(passphrase));
pg_sha256_final(&ctx, buf);
memcpy(&master_key, buf, sizeof(buf));
/*
* We have to check if another master key is in use for this database,
* meaning: we have table keys in tcle_table_keys encrypted with another
* master key. If this is the case, we don't allow to set a new master
* key.
*/
if (!CheckKMSMasterKey(master_key))
ereport(ERROR,
(errmsg("tcle: wrong passphrase")));
/*
* Remove previous master key from shmem if any. This can ben done safely
* because we're sure at this point that this key is not really in use.
*/
RemoveDatabaseMasterKey(shmmasterkeyslock, shmmasterkeys, MyDatabaseId);
/* Add the brand new master key in shmem */
AddDatabaseMasterKey(shmmasterkeyslock, shmmasterkeys, MyDatabaseId,
master_key);
PG_RETURN_BOOL(true);
}
/*
* Unsecure (the passphrase could leak in logs) and temporary user function to
* change a master key using a passphrase.
*/
Datum
tcle_change_passphrase(PG_FUNCTION_ARGS)
{
char *passphrase = PG_GETARG_CSTRING(0);
char *new_passphrase = PG_GETARG_CSTRING(1);
pg_sha256_ctx ctx;
unsigned char buf[PG_SHA256_DIGEST_LENGTH];
unsigned char master_key[AES_KEYLEN],
new_master_key[AES_KEYLEN];
unsigned char *shmem_master_key;
shmem_master_key = (unsigned char *) palloc(AES_KEYLEN);
/*
* Master key rotation could not run in a transaction block because the
* shmem update part is not atomic and cannot be rollback'd.
*/
PreventInTransactionBlock(true, "tcle: master key rotation");
/*
* ACL check against database: only the owner or a superuser can change a
* database master key.
*/
if (!pg_database_ownercheck(MyDatabaseId, GetUserId()))
ereport(ERROR,
(errmsg("tcle: only database owner and superusers are allowed "
"to change the master key")));
if (strlen(passphrase) == 0)
ereport(ERROR, (errmsg("tcle: passphrase should not be empty")));
if (strlen(new_passphrase) == 0)
ereport(ERROR, (errmsg("tcle: new passphrase should not be empty")));
/*
* Derivate master key from the passphrase by computing passphrase sha256
* sum.
*/
pg_sha256_init(&ctx);
pg_sha256_update(&ctx, (unsigned char *) VARDATA_ANY(passphrase),
VARSIZE_ANY_EXHDR(passphrase));
pg_sha256_final(&ctx, buf);
memcpy(&master_key, buf, sizeof(buf));
/*
* We have to check if the given passphrase corresponds to the current
* master key.
*/
if (GetDatabaseMasterKey(shmmasterkeyslock, shmmasterkeys, MyDatabaseId,
&shmem_master_key))
{
if (memcmp(shmem_master_key, master_key, AES_KEYLEN) != 0)
ereport(ERROR,
(errmsg("tcle: wrong passphrase")));
}
if (!CheckKMSMasterKey(master_key))
ereport(ERROR,
(errmsg("tcle: wrong passphrase")));
/* Key derivation for the new passphrase this time */
memset(buf, 0, PG_SHA256_DIGEST_LENGTH);
pg_sha256_init(&ctx);
pg_sha256_update(&ctx, (unsigned char *) VARDATA_ANY(new_passphrase),
VARSIZE_ANY_EXHDR(new_passphrase));
pg_sha256_final(&ctx, buf);
memcpy(&new_master_key, buf, sizeof(buf));
/*
* Let's continue with master key rotation. We need to first hold an
* exclusive lock on the master key residing in shmem, then apply table key
* reencryption with the new master key, update the master key residing in
* shmem, finally, release master key LWLock.
*/
LWLockAcquire(shmmasterkeyslock->lock, LW_EXCLUSIVE);
/* Apply table keys reencryption */
ChangeKMSMasterKey(master_key, new_master_key);
/* Update master key in shmem */
UpdateDatabaseMasterKey(shmmasterkeys, MyDatabaseId, new_master_key);
LWLockRelease(shmmasterkeyslock->lock);
pfree(shmem_master_key);
PG_RETURN_BOOL(true);
}
/*
* Load encryptable types Oids into input array.
*/
static void
get_encrypt_type_oids(Oid ** oidsPtr)
{
Oid namespaceId;
Oid extensionId;
extensionId = get_extension_oid("tcle", false);
namespaceId = get_extension_schema(extensionId);
for (int i = 0; i < N_ENCRYPT_TYPES; i++)
{
(*oidsPtr)[i] = GetSysCacheOid2(TYPENAMENSP, Anum_pg_type_oid,
PointerGetDatum(encrypt_types[i]),
ObjectIdGetDatum(namespaceId));
}
}
/*
* Encrypt / decrypt tuple attributes from a TupleTableSlot.
*/
static void
EncryptDecryptTupleTableSlot(TupleTableSlot *slot, int8 flag, Oid tableId)
{
/* Number of attributes (columns) */
int natts;
bool found_encrypt_type = false;
/* Variables for tuple manipulation */
HeapTuple tuple, new_tuple;
bool shouldFreeTuple;
unsigned char *table_key;
Oid *type_oids;
BufferHeapTupleTableSlot *bslot;
MemoryContext oldContext;
bool materialize;
if (!ShouldEncryptDecryptTTS())
return;
/* Get encryptable data types Oids */
type_oids = (Oid *) palloc(N_ENCRYPT_TYPES * sizeof(Oid));
get_encrypt_type_oids(&type_oids);
natts = slot->tts_tupleDescriptor->natts;
/*
* Quick attributes list lookup to see if any value should be encrypted /
* decrypted later. We need to know maximum number of attributes we will
* later update in heap to allocate memory for replvals, replnuls and
* replcols.
*/
for (int i=0; i < natts; i++)
{
Form_pg_attribute att = TupleDescAttr(slot->tts_tupleDescriptor, i);
if (IS_ENCRYPTABLE_TYPE(att->atttypid, type_oids))
{
found_encrypt_type = true;
break;
}
}
if (!found_encrypt_type)
{
/* No encryptable data ? Just exit. */
pfree(type_oids);
return;
}
/*
* If tableId argument is not a valid Oid, let's consider that TTS contains
* the right table id.
*/
if (!OidIsValid(tableId))
tableId = slot->tts_tableOid;
/* Load table's key */
table_key = (unsigned char *) palloc(AES_KEYLEN);
LoadTableKey(MyDatabaseId, tableId, &table_key);
/* Do not materialize if we're dealing with virtual tuple */
materialize = (slot->tts_ops != &TTSOpsVirtual);
/* Fetch tuple from the slot */
bslot = (BufferHeapTupleTableSlot *) slot;
tuple = ExecFetchSlotHeapTuple(slot, materialize, &shouldFreeTuple);
/* Tuple encryption / decryption */
new_tuple = EncryptDecryptHeapTuple(tuple, slot->tts_tupleDescriptor,
tableId, flag, table_key, type_oids);
if (slot->tts_ops == &TTSOpsVirtual)
{
/*
* Virtual tuples (coming from CTAS) should not be materialized and can
* be stored with ExecForceStoreHeapTuple() as is.
*/
ExecForceStoreHeapTuple(new_tuple, slot, true);
}
else if (slot->tts_ops == &TTSOpsBufferHeapTuple)
{
/* The Slot has been materialized, so we can free the buffer tuple */
heap_freetuple(bslot->base.tuple);
/* Tuple duplication into TTS memory context */
oldContext = MemoryContextSwitchTo(slot->tts_mcxt);
bslot->base.tuple = heap_copytuple(new_tuple);
MemoryContextSwitchTo(oldContext);
/* Copy ctid, and flag the TTS */
slot->tts_tid = new_tuple->t_self;
slot->tts_flags |= TTS_FLAG_SHOULDFREE;
heap_freetuple(new_tuple);
}
else
ereport(ERROR, (errmsg("tcle: unsupported type of TTS")));
if (shouldFreeTuple)
heap_freetuple(tuple);
pfree(table_key);
pfree(type_oids);
}
/*
* Shared memory lookup for table's key. If not found then we have to load
* the master key and fetch table's cipher key from KMS table and finally
* push the table's key in shared memory.
*/
static void
LoadTableKey(Oid databaseId, Oid tableId, unsigned char **table_keyPtr)
{
unsigned char *master_key;
bytea *table_cipher_key;
/* Cache lookup first */
if (CacheGetRelationKey(shmkeycache, databaseId, tableId, table_keyPtr))
return;
/* Try to get table's key from KMS table */
table_cipher_key = (bytea *) palloc(AES_IVLEN + AES_KEYLEN + AES_BLOCKLEN);
if (!GetKMSCipherKey(tableId, &table_cipher_key))
{
pfree(table_cipher_key);
/* If not found in KMS, maybe we have a transient key ? */
if (GetCommandTransientKey(table_keyPtr))
{
/* If found, we put it into the cache */
CacheAddRelationKey(shmkeycache, databaseId, tableId,
*table_keyPtr);
return;
}
else
ereport(ERROR, (errmsg("tcle: could not find table's key")));
}
/*
* At this point we've found table's cipher key in KMS table, now we have
* to decrypt it with the master key and put it in cache.
*/
master_key = (unsigned char *) palloc(AES_KEYLEN);
/* Get master key from shared memory */
if (!GetDatabaseMasterKey(shmmasterkeyslock, shmmasterkeys, databaseId,
&master_key))
{
pfree(table_cipher_key);
pfree(master_key);
ereport(ERROR,