efcore.pg icon indicating copy to clipboard operation
efcore.pg copied to clipboard

Use PGP_SYM_ENCRYPT with EF Core (Using DbCommandInterceptor)

Open sadedil opened this issue 7 years ago • 10 comments

I want to use PGP_SYM_ENCRYPT and PGP_SYM_DECRYPT functionality with Npgsql.EntityFrameworkCore.PostgreSQL library.

I've created a custom DbCommandInterceptor to modify SQL queries on the fly. The functionality what I need differs for usage. For example;


FOR INSERT QUERIES I have to use

INSERT INTO table1 (column1, column2) VALUES (
    PGP_SYM_ENCRYPT('Value1','AES_KEY'),
    PGP_SYM_ENCRYPT('Value2', 'AES_KEY')
);

instead of

INSERT INTO table1 (column1, column2) VALUES ('Value1' 'Value2');

Requirements:

  • Wrap 'Value1' with encryption function

FOR SELECT QUERIES I have to use

SELECT 
    PGP_SYM_DECRYPT(column1::bytea, 'AES_KEY') as column1,
    PGP_SYM_DECRYPT(column2::bytea, 'AES_KEY') as column2
FROM table1 WHERE
    PGP_SYM_DECRYPT(column1::bytea, 'AES_KEY') LIKE ('Value1%');

instead of

SELECT 
    column1,
    column2
FROM table1 WHERE 
    column1 LIKE ('Value1%');

Requirements:

  • For SELECT criteria: Wrap column1 with decryption function
  • For SELECT criteria: Add column1 alias to this function
  • For WHERE criteria: Wrap column1 with decryption function

So my questions are:

  • Is there any other ways to achieve this result without using DbCommandInterceptor? Because it's hard to implement by using Regular Expressions, because i'm not sure the column1 is used in SELECT or WHERE criteria
  • Is there any way to tell EF Core to change schema.column_name expression to my_function(schema.column_name) AS column_name for SELECT queries and my_function2(schema.column_name) for INSERT/UPDATE queries
  • Is there any other suggestion to solve my crypt/decrypt problems.

Thanks,


Versions:

  • Npgsql.EntityFrameworkCore.PostgreSQL v3.0.0
  • EF Core 3.0

sadedil avatar Sep 30 '19 08:09 sadedil

As you say doing string parsing and replacing in an interceptor could be quite error-prone. The proper way for this would be server-side value converters, which isn't yet implemented in EF Core (see https://github.com/aspnet/EntityFrameworkCore/issues/10861) - you can vote for and track that.

In the absence of the above, I'd recommend you consider doing encryption/decryption with value converters - this is a clean solution and easy to implement. Since you seem to want the client to have the encryption key anyway, it doesn't seem to make much difference, and you get the added bonus of transferring your data encrypted over the wire.

Closing as there's nothing here to do in Npgsql, but don't hesitate to post back if you have more questions.

roji avatar Sep 30 '19 09:09 roji

Hi @roji,

Thanks for suggestion, I'll think about the implementing client side value converters.

I have one more question.

Is there any other way to implement encryption/decryption at database level. For example I can install a certificate to app server and all fields automatically encrypted/decrypted during transfer without modifying SQL queries manually?

Or any other way I don't know?

sadedil avatar Sep 30 '19 10:09 sadedil

It really depends exactly what you're looking for.

If you're only looking to encrypt network traffic, using SSL/TLS is the right choice; it transparently operates at the connection level, and there's no need for the application to do anything.

If you're looking for "at-rest encryption", i.e. to have your data encrypted in storage at the server, you can encrypt the entire partition on the server.

See this PostgreSQL page for the various options.

roji avatar Sep 30 '19 10:09 roji

I've read the PostgreSQL Encryption Options page,

Actually best fit to my scenario is "If the system administrator for the server's machine cannot be trusted" so Client-Side Encryption seems fine. Because our country's GDPR like rules says personal informations should be encrypted.

But I have a new problem now. How to search a data in a database column if this column client-side encrypted? For example Name and Surname columns. I should be able to use some operators like Like or ILike.

I'm just writing this to summarize this issue. I'm not waiting more answers.

Thanks for helping @roji.

sadedil avatar Oct 01 '19 06:10 sadedil

You can't search columns if they are encrypted - this is the case regardless of whether you encrypt at the client (e.g. with value converters) or whether you use PGP_SYM_ENCRYPT to encrypt at the server. The moment a column contains encrypted data it can no longer be searched. If you want columns to be searchable you'll have to encrypt at a lower-level, i.e. filesystem/partition encryption.

Note that I'm not a database encryption expert so I may be missing something.

roji avatar Oct 01 '19 07:10 roji

I was thought an sql query like this can solve search problem when db level encryption used (not tried yet). But I'm not sure the spended performance is affordable.

SELECT pgp_sym_decrypt(name, 'AES_KEY')
FROM  table1
WHERE  pgp_sym_decrypt(name, 'AES_KEY') LIKE '%Jane%';

sadedil avatar Oct 01 '19 14:10 sadedil

Right, in that sense you can search, and this is not possible I'd you encrypt client side. Note also that this search will not use an index.

roji avatar Oct 01 '19 20:10 roji

What about keep a copy of this table in memory (at least all searchable columns) with all data decrypted? This is a lack in security?

larini avatar Jun 25 '20 11:06 larini

@larini whether that's a lack of security depends on your precise security requirements... I'm not aware of an option to create an in-memory-only table in PG, plus you'd also need some mechanism for synchronizing the memory copy with the actual disk data, which is bound to be non-trivial.

roji avatar Jun 25 '20 13:06 roji

I have written a DBFunction and a value converter to use the encrypt_iv and decrypt_iv and packed them in a NuGet package, so by doing this you can do native search's grouping etc in the DB it self rather than loading all of the entities in to the EF Core side

Link for the Repo Link for the Nuget

Example Code Can be found in the unit test project.

Some of the example codes

var testObjs2 = await _dbContext.Testings.AsNoTracking().Select(x => new 
            {
                Id = x.Id,
                encrypted = x.encrypted.NpgDecrypt().ToUpper(),
                normal = x.normal
            }).ToListAsync();
var obj = await _dbContext.Testings.AsNoTracking()
.FirstOrDefaultAsync(x => EF.Functions.NpgsqlDecrypt(x.encrypted) == testings.encrypted);
 var obj = await _dbContext.Testings.AsNoTracking()
.FirstOrDefaultAsync(x => x.encrypted.NpgDecrypt() == testings.encrypted);

AltairCA avatar Oct 24 '21 10:10 AltairCA