Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement support of encrypted elements in configuration file #50986

Merged
merged 40 commits into from Jul 26, 2023

Conversation

rvasin
Copy link
Contributor

@rvasin rvasin commented Jun 14, 2023

Closes #48291

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

Implement support of encrypted elements in configuration file
Added possibility to use encrypted text in leaf elements of configuration file. The text is encrypted using encryption codecs from <encryption_codecs> section.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

@rvasin

This comment was marked as outdated.

@rschu1ze rschu1ze self-assigned this Jun 14, 2023
@rschu1ze rschu1ze added the can be tested Allows running workflows for external contributors label Jun 14, 2023
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-feature Pull request with new product feature label Jun 14, 2023
@robot-ch-test-poll1
Copy link
Contributor

robot-ch-test-poll1 commented Jun 14, 2023

This is an automated comment for commit 0af869f with description of existing statuses. It's updated for the latest CI running
The full report is available here
The overall status of the commit is 🟢 success

Check nameDescriptionStatus
AST fuzzerRuns randomly generated queries to catch program errors. The build type is optionally given in parenthesis. If it fails, ask a maintainer for help🟢 success
CI runningA meta-check that indicates the running CI. Normally, it's in success or pending state. The failed status indicates some problems with the PR🟢 success
ClickHouse build checkBuilds ClickHouse in various configurations for use in further steps. You have to fix the builds that fail. Build logs often has enough information to fix the error, but you might have to reproduce the failure locally. The cmake options can be found in the build log, grepping for cmake. Use these options and follow the general build process🟢 success
Compatibility checkChecks that clickhouse binary runs on distributions with old libc versions. If it fails, ask a maintainer for help🟢 success
Docker image for serversThe check to build and optionally push the mentioned image to docker hub🟢 success
Docs CheckBuilds and tests the documentation🟢 success
Fast testNormally this is the first check that is ran for a PR. It builds ClickHouse and runs most of stateless functional tests, omitting some. If it fails, further checks are not started until it is fixed. Look at the report to see which tests fail, then reproduce the failure locally as described here🟢 success
Flaky testsChecks if new added or modified tests are flaky by running them repeatedly, in parallel, with more randomization. Functional tests are run 100 times with address sanitizer, and additional randomization of thread scheduling. Integrational tests are run up to 10 times. If at least once a new test has failed, or was too long, this check will be red. We don't allow flaky tests, read the doc🟢 success
Install packagesChecks that the built packages are installable in a clear environment🟢 success
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests🟢 success
Mergeable CheckChecks if all other necessary checks are successful🟢 success
Performance ComparisonMeasure changes in query performance. The performance test report is described in detail here. In square brackets are the optional part/total tests🟢 success
Push to DockerhubThe check for building and pushing the CI related docker images to docker hub🟢 success
SQLancerFuzzing tests that detect logical bugs with SQLancer tool🟢 success
SqllogicRun clickhouse on the sqllogic test set against sqlite and checks that all statements are passed🟢 success
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc🟢 success
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc🟢 success
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors🟢 success
Style CheckRuns a set of checks to keep the code style clean. If some of tests failed, see the related log from the report🟢 success
Unit testsRuns the unit tests for different release types🟢 success
Upgrade checkRuns stress tests on server version from last release and then tries to upgrade it to the version from the PR. It checks if the new server can successfully startup without any errors, crashes or sanitizer asserts🟢 success

@rvasin

This comment was marked as outdated.

@rschu1ze

This comment was marked as outdated.

@rvasin

This comment was marked as outdated.

@rvasin

This comment was marked as outdated.

@rvasin

This comment was marked as outdated.

@@ -755,6 +843,11 @@ void ConfigProcessor::savePreprocessedConfig(const LoadedConfig & loaded_config,
{
LOG_WARNING(log, "Couldn't save preprocessed config to {}: {}", preprocessed_path, e.displayText());
}

#if USE_SSL
if (fs::path(preprocessed_path).filename() == "config.xml")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SIlly question, but will this work with yaml configuration files?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The question is interesting.

I am trying to figure it out. It seems that in current code it cannot work with yaml files.
But we can add support of yaml if needed.

In the integration test we have:
tests/integration/test_config_decryption/configs/config.xml

<clickhouse>
    <encryption_codecs>
        <aes_128_gcm_siv>
            <key_hex>00112233445566778899aabbccddeeff</key_hex>
        </aes_128_gcm_siv>
        <aes_256_gcm_siv>
            <key_hex>00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff</key_hex>
        </aes_256_gcm_siv>
    </encryption_codecs>
    <max_table_size_to_drop encryption_codec="AES_128_GCM_SIV">96260000000B0000000000E8FE3C087CED2205A5071078B29FD5C3B97F824911DED3217E980C</max_table_size_to_drop>
    <max_partition_size_to_drop encryption_codec="AES_256_GCM_SIV">97260000000B0000000000BFFF70C4DA718754C1DA0E2F25FF9246D4783F7FFEC4089EC1CC14</max_partition_size_to_drop>
</clickhouse>

I used ymltoxml to convert it into yaml by command:

ymltoxml -i config.xml -o config.yaml

I got:

clickhouse:
  encryption_codecs:
    aes_128_gcm_siv:
      key_hex: 00112233445566778899aabbccddeeff
    aes_256_gcm_siv:
      key_hex: 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff
  max_table_size_to_drop:
    '@encryption_codec': AES_128_GCM_SIV
    '#text': 96260000000B0000000000E8FE3C087CED2205A5071078B29FD5C3B97F824911DED3217E980C
  max_partition_size_to_drop:
    '@encryption_codec': AES_256_GCM_SIV
    '#text': 97260000000B0000000000BFFF70C4DA718754C1DA0E2F25FF9246D4783F7FFEC4089EC1CC14

The problem is that attributes via @ as supported by ClickHouse. See the example of usage here.

But text nodes via #text are not supported yet. See implementation of YAML parser:

bool is_attribute = (key.starts_with(YAML_ATTRIBUTE_PREFIX) && value_node.IsScalar());

So we could implement support of #text in YAMLParser.cpp.

Copy link
Contributor Author

@rvasin rvasin Jul 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rschu1ze
OK. I added support of text nodes in YAMLParser.cpp. Thus YAML configs can be decrypted too. Also I added a test for YAML configs decryption into my integration test.

In short I see there is no a single/standard approach about attributes and text nodes in YAML.

Consider the fragment of XML config:

  <max_table_size_to_drop encryption_codec="AES_128_GCM_SIV">96260000000B0000000000E8FE3C087CED2205A5071078B29FD5C3B97F824911DED3217E980C</max_table_size_to_drop>

In this fragment:

  • max_table_size_to_drop is an element node.
  • encryption_codec is an attribute node.
  • 96260000000B0000000000E8FE3C087CED2205A5071078B29FD5C3B97F824911DED3217E980C is a text node.

I tried different online tools they convert XML to YAML differently.

https://www.site24x7.com/tools/xml-to-yaml.html

  max_table_size_to_drop:
    "-encryption_codec": AES_128_GCM_SIV
    "#text": 96260000000B0000000000E8FE3C087CED2205A5071078B29FD5C3B97F824911DED3217E980C

https://www.atatus.com/tools/xml-to-yaml

    max_table_size_to_drop: 
      encryption_codec: "AES_128_GCM_SIV"
      $t: "96260000000B0000000000E8FE3C087CED2205A5071078B29FD5C3B97F824911DED3217E980C"

https://beautifytools.com/xml-to-yaml-converter.php

 max_table_size_to_drop: 
  _encryption_codec: AES_128_GCM_SIV
  __text: 96260000000B0000000000E8FE3C087CED2205A5071078B29FD5C3B97F824911DED3217E980C
  toString: 

https://www.anyjson.in/xml-to-yaml

  max_partition_size_to_drop:
    '#text': 97260000000B0000000000BFFF70C4DA718754C1DA0E2F25FF9246D4783F7FFEC4089EC1CC14
    '@encryption_codec': AES_256_GCM_S

This last result is the same as produced by mentioned about ymltoxml module.
And as far as we already represent attributes as nodes starting with @ I implemented support of text nodes as #text.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

About the XML/YAML relationship: The authoritative guide (at least as far as I see) is https://clickhouse.com/docs/en/operations/configuration-files . It says about XML attributes:

If you want to write an attribute for a Sequence or Map node, you should use a @ prefix before the attribute key. Note, that @ is reserved by YAML standard, so you should also to wrap it into double quotes:

map:
  "@attr1": value1
  "@attr2": value2
  key: 123

which is close to the last of your examples but not 100% the same. Could you make your YAML test check this syntax?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For this code key is not the text node. But it's the element subnode. Because it's "translated" into this code according to documentation:

<map attr1="value1" attr2="value2">
    <key>123</key>
</map>

While we need it to be translated into:

<map attr1="value1" attr2="value2">
123
</map>

According to the documentation probably the sequence can do it the way we need it:

seq:
  - "@attr1": value1
  - "@attr2": value2
  - 123
<seq attr1="value1" attr2="value2">123</seq>

BTW in my correction of YAMLParser.cpp there no exception throwing for the case when several #text are specified. For example this way:

  max_table_size_to_drop:
    '#text': SOMETHING1
    '@encryption_codec': AES_128_GCM_SIV
    '#text': SOMETHING2
  1. Should we ignore it?
  2. Or should we throw an exception when we see #text the second time in config?
  3. Or should we silently replace old value SOMETHING1 by new value SOMETHING2 when parsing?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, according to the docs, the YAML would need to contain a sequence of the form

seq:
  - "@attr1": value1
  - "@attr2": value2
  - 123

instead of a map.

Should we ignore it?
Or should we throw an exception when we see #text the second time in config?
Or should we silently replace old value SOMETHING1 by new value SOMETHING2 when parsing?

Assuming the user writes ClickHouse-specific YAML instead of YAML generated by the XML-to-YAML translators, do we need any modifications in the YAML parser at all or does the existing code work out of the box? (if it doesn't then the docs currently lie).

Besides that, I propose to implement the same behavior which exists in XML if the same tag appears multiple times, e.g.

<some_param>42</some_param>
<some_param>53</some_param>

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rschu1ze I think the documentation is incorrect about usage the sequence with YAML.
I tried the following:

If config.yaml file has:

encryption_codecs:
  aes_128_gcm_siv:
    key_hex: 00112233445566778899aabbccddeeff
  aes_256_gcm_siv:
    key_hex: 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff
max_table_size_to_drop:
  - '@encryption_codec': AES_128_GCM_SIV
  - 96260000000B0000000000E8FE3C087CED2205A5071078B29FD5C3B97F824911DED3217E980C
max_partition_size_to_drop:
  - 97260000000B0000000000BFFF70C4DA718754C1DA0E2F25FF9246D4783F7FFEC4089EC1CC14
  - '@encryption_codec': AES_256_GCM_SIV

Then it created config-preprocessed.xml with contents:

    <encryption_codecs>
        <aes_128_gcm_siv>
            <key_hex>00112233445566778899aabbccddeeff</key_hex>
        </aes_128_gcm_siv>
        <aes_256_gcm_siv>
            <key_hex>00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff</key_hex>
        </aes_256_gcm_siv>
    </encryption_codecs>
    <max_table_size_to_drop encryption_codec="AES_128_GCM_SIV"/>
    <max_table_size_to_drop>96260000000B0000000000E8FE3C087CED2205A5071078B29FD5C3B97F824911DED3217E980C</max_table_size_to_drop>
    <max_partition_size_to_drop>97260000000B0000000000BFFF70C4DA718754C1DA0E2F25FF9246D4783F7FFEC4089EC1CC14</max_partition_size_to_drop>
    <max_partition_size_to_drop encryption_codec="AES_256_GCM_SIV"/>

You see it's not just about the encryption elements this is the way YAMLParser.cpp works in master. Thus we cannot use the sequences.

What do we do then?

Copy link
Contributor Author

@rvasin rvasin Jul 21, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now I implemented it this way (the way number two from above's list): YAMLParser will throw an exception if it find second text node for an element node.

src/Common/Config/ConfigProcessor.cpp Outdated Show resolved Hide resolved
@rvasin
Copy link
Contributor Author

rvasin commented Jul 17, 2023

@alexey-milovidov

@santrancisco started reviewing this PR, and there are some questions.

1. It does not help to have encryption keys in config, because they will be exposed in the preprocessed config - similar to the way how the values are exposed in the absence of encryption. It defeats the purpose of encryption.

Our company's security analysts and architect had series of meetings with security analysts of our existing clients and prospects (potential clients). They all admit that exposing encryption keys in preprocessed config is OK for them. They validate/approve this solution and they may start using ClickHouse with this feature.

2. If the main problem is the exposure of values in the preprocessed config, we can solve it differently - introduce a `hidden` attribute, that will prevent writing the subtree into the preprocessed config.

During our meetings with clients and protects we showed our technical papers representing many different combinations of usage from_env, from_zk, include_from, incl for secrets like passwords and encryption keys.
Our security analysts and security analysts from our clients confirm that saving passwords using from_env, from_zk is insecure. It's not sufficient for them.

Therefore introducing the hidden attribute means that you still save the secrets using, for example, from_env. Which is insecure according to their security requirements.

@rschu1ze We consider hidden attribute not as orthogonal feature but as complementary feature to this PR.
So it may be using in combination with our encryption. So with our PR we encrypt secrets like passwords but with hidden attribute we put it on the encryption keys (which are itself are stored using from_env). Overall it will be more secure.

You may create a new issue "Implement hidden attribute" and assign it to me. I may start working on it from the next Monday (according to our schedules).

One technical note about technical implementation of the hidden attribute: in the source code I saw that in some cases the configuration parameters may be loaded directly from the preprocesssed config. If we don't have "rendered" encryption keys in the preprocessed config because usage of the hidden attribute how they will be loaded in this case? So usage of the hidden attribute is also not ideal solution which can be used for 100% cases. But it may be used for most common use cases. We may surround it by IF/ELSE logic carefully.

3. If we solve the problem this way, is there any point in encryption?

This PR is not the ideal solution which definitely/finally solves the encryption problem. But this PR is the new step which improves the security to such level that our prospects may start using ClickHouse with solution proposed in this PR.

@aosorgin
Copy link

@alexey-milovidov @rschu1ze As @rvasin wrote above, this PR is the first step to make storing of sensitive information more secure. It allows to store encrypted data and encryption keys in different places while "hidden" fields are stored in the single "original" configuration file. The second step will be moving encrypted keys from configuration file to the separate files (probably stored in another storage). And these keys will not be stored in the preprocessed files as well as encrypted configuration fields. By the way, "hidden" fields can be the solution for the this second step.

@santrancisco
Copy link
Contributor

Hi all, I'm a bit late to this but as per @alexey-milovidov comment above, it does feel redundant when we have both encryption key and the encrypted value in the preprocessed, however, as per @rvasin 's comment above, I also agree that the "hidden" feature can be complimentary to this if you want to use from_env + hidden for the AES key itself.

With that note, I just want to point out that environment variable is only a "so so" solution... at the end of the day, in *nix land, /proc/{pid}/environ is also a file (but the good thing about it is by default it has 500 (-r--------) permission) that root or the service account used to execute clickhouse server itself can access to it. This ultimately means that if an attacker with root privilege on the box (RCE+privilege escalation or internal malicious user), they will get to the AES key but at this point, adding themself an user into config would have been a walk in the park anyway.

If an attacker manage to find a local file inclusion inside ClickHouse (eg: user able to exploit file table function and somehow bypass the restriction put in place to narrow access to only user_files folder), the attacker would then pull off this attack under Clickhouse service account context and thus can also access this environment variable by reading from /proc/self/environ

While this is more obscure and harder to get to, it is still possible - A good thing is it would protect ClickHouse from other users on the machine with no root privilege and helps with security compliance :)

Perhaps in the future, beside from_env , we could have something like from_tpm / from_hsm, from_kms that would basically move the decryption outside of ClickHouse altogether and so the decrypted value only ever lives in memory...

Overall, I agree, it's a step forward that may enable us with more options to secure these values in the future.

@rschu1ze
Copy link
Member

You may create a new issue "Implement hidden attribute" and assign it to me. I may start working on it from the next Monday (according to our schedules).

Good. I opened #52207 for preprocessed config with hidden parts (but GitHub somehow won't let me assign @rvasin to it).

No further objections from my side against this PR, let's fix the review comments, then I'll happily merge.

@rvasin
Copy link
Contributor Author

rvasin commented Jul 17, 2023

Good. I opened #52207 for preprocessed config with hidden parts (but GitHub somehow won't let me assign @rvasin to it).

This is how GitHub works: in order to assign someone the person should write a comment in the issue. So I wrote the comment. You may try to assign me now.

No further objections from my side against this PR, let's fix the review comments, then I'll happily merge.

I am working on all the comments. I will try to fix all the remaining questions today.

@rschu1ze rschu1ze merged commit d4737ca into ClickHouse:master Jul 26, 2023
282 checks passed
rschu1ze added a commit to rschu1ze/ClickHouse that referenced this pull request Jul 26, 2023
…n file"

Cf. PR ClickHouse#50986

- rename XML attribute "encryption_codec" to "encrypted_by"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
can be tested Allows running workflows for external contributors pr-feature Pull request with new product feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Support encrypted passwords in interserver_http_credentials section
6 participants