pgbackrest.git / summary / log / commit / refs

commit    92d0a5ed7bccf05cad33e2d5bd3def2e4ccdd54e
Author:   David Steele <david@pgbackrest.org>
Commit:   GitHub <noreply@github.com>
Date:     Mon Oct 26 14:16:41 2026 +0000

    Require a generated repository passphrase for new format 6 stanzas.
    
    stanza-create now refuses to create an encrypted stanza at repository format 6 or higher unless repo-cipher-pass looks generated. A random passphrase of 256 bits matches the AES-256 key it derives, so a short or human-chosen passphrase is the weak link in an otherwise strong scheme. The error suggests generating one with openssl rand -base64 32.
    
    A passphrase looks generated when it is hex, base64, or unpadded base64url that decodes to at least 256 bits, the decoded bytes are not all text, and they contain at least 16 distinct byte values and at least 16 distinct differences between adjacent bytes. The last two rule out repeated values, sequences, and short repeating patterns. 32 random bytes fail these checks with a probability of about 10^-14. A weak secret that was hashed or encoded some other way can still pass. Hex and base64url are accepted because some key management services generate keys in those encodings, and decoding base64url is now supported.
    
    The check only applies when a stanza is created. A stanza migrated to format 6 keeps the passphrase it already has, since changing it would mean rewriting the info files. The passphrase is never decoded for use: the key is still derived from its text at every format.
    
    stanza-create also refuses the example passphrase from the documentation at every repository format. The prior example has been copied into third-party guides and GitHub issues. A configuration copied from the user guide gets format 5 by default, where the generated check does not apply. The check matches the first 43 characters of the prior example. The new example is the same 43 characters followed by = and decodes to 256 bits. Like the generated check, it only applies when a stanza is created.
    
    The user guide installs a generated passphrase and shows the example in its place. A new display attribute on backrest-config-option sets the value shown in the rendered configuration while the element text is still the value installed.
    
    The user guide now suggests openssl rand -base64 32 for both formats and the repo-cipher-pass reference describes the format 6 requirements.


doc/lib/command/render/execute.py | 22 ++++ doc/xml/reference.xml | 4 +- doc/xml/release/2020s/2027/2.61.0.xml | 4 + doc/xml/release/contributor.xml | 4 + doc/xml/user-guide.xml | 8 +- src/command/stanza/create.c | 122 +++++++++++++++++++++ src/common/encode.c | 117 ++++++++++++++++++-- test/src/module/command/helpTest.c | 8 ++ test/src/module/command/stanzaTest.c | 111 ++++++++++++++++++- test/src/module/common/encodeTest.c | 52 ++++++++- test/src/module/doc/command/render/execute_test.py | 15 ++- 11 files changed, 446 insertions(+), 21 deletions(-) diff --git a/doc/lib/command/render/execute.py b/doc/lib/command/render/execute.py index 65f1d94f1..125ca5be7 100644 --- a/doc/lib/command/render/execute.py +++ b/doc/lib/command/render/execute.py @@ -80,6 +80,7 @@ class DocExecute(DocRender): self.host_map = {} self.config_map = {} + self.config_display_map = {} # Values shown in place of the installed values, by host, file, section, and option self.pg_config_map = {} self.config_show_map = {} # Each configuration file as the document last showed it, which a change is marked against @@ -293,6 +294,11 @@ class DocExecute(DocRender): if option.text is not None and option.text.strip() != "": entry["value"] = self._replace(option.text) + display = xml_node_attribute(option, "display") + + if display is not None: + entry["display"] = self._replace(display) + name = self._replace(xml_node_attribute(option, "key", True)) if backrest: @@ -381,11 +387,14 @@ class DocExecute(DocRender): raise ToolError("cannot configure backrest on host %s because the host does not exist" % host_name) file_map = self.config_map.setdefault(host_name, {}) + display_file_map = self.config_display_map.setdefault(host_name, {}) if xml_node_attribute(config, "reset") == "y": file_map.pop(key["file"], None) + display_file_map.pop(key["file"], None) section_map = file_map.setdefault(key["file"], {}) + display_map = display_file_map.setdefault(key["file"], {}) for option in xml_node_child_list(config, "backrest-config-option"): option_section = self._replace(xml_node_attribute(option, "section", True)) @@ -414,6 +423,14 @@ class DocExecute(DocRender): log(DEBUG, " " * (depth + 1) + "set %s->%s = %s" % (option_section, name, value)) + # Value shown in place of the installed value + display = xml_node_attribute(option, "display") + + if display is None or value is None or value == "": + display_map.get(option_section, {}).pop(name, None) + else: + display_map.setdefault(option_section, {})[name] = self._replace(display) + path_local = os.path.join(self.manifest.path_doc, "output/pgbackrest.conf") file_write(path_local, ini_render(section_map)) @@ -428,6 +445,11 @@ class DocExecute(DocRender): if _CONFIG_SECTION_GLOBAL in clean and len(clean[_CONFIG_SECTION_GLOBAL]) == 0: del clean[_CONFIG_SECTION_GLOBAL] + # Replace each installed value that has a display value + for option_section, display_option_map in display_map.items(): + for name, display in display_option_map.items(): + clean[option_section][name] = display + result = ini_render(clean) return result if result.strip() != "" else None diff --git a/doc/xml/reference.xml b/doc/xml/reference.xml index 5659cb7b3..3fbe7334b 100644 --- a/doc/xml/reference.xml +++ b/doc/xml/reference.xml @@ -1456,10 +1456,12 @@ <text> <p>Passphrase used to encrypt/decrypt files of the repository.</p> + <p>A stanza created at <br-option>repo-format</br-option> 6 or higher requires a passphrase generated from at least 256 random bits, e.g. with <code>openssl rand -base64 32</code>. The passphrase must be hex, base64, or unpadded base64url that decodes to at least 256 bits, the decoded bytes must not all be text, and they must contain at least 16 distinct values and at least 16 distinct differences between adjacent bytes. The last two rule out repeated values, sequences, and short repeating patterns.</p> + <admonition type="note">When run without the <br-option>stanza</br-option> option the <cmd>info</cmd> command reads encryption settings only from the <setting>global</setting> section. If encryption settings are configured per stanza, run the <cmd>info</cmd> command with the <br-option>stanza</br-option> option to read an encrypted stanza.</admonition> </text> - <example>zWaf6XtpjIVZC5444yXB+cgFDFl7MxGlgkZSaoPvTGirhPygu4jOKOXf9LO4vjfO</example> + <example>zWaf6XtpjIVZC5444yXB+cgFDFl7MxGlgkZSaoPvTGi=</example> </config-key> <config-key id="repo-cipher-rotate" name="Repository Cipher Rotation"> diff --git a/doc/xml/release/2020s/2027/2.61.0.xml b/doc/xml/release/2020s/2027/2.61.0.xml index 59f2edee4..a840eed73 100644 --- a/doc/xml/release/2020s/2027/2.61.0.xml +++ b/doc/xml/release/2020s/2027/2.61.0.xml @@ -9,11 +9,15 @@ <github-pull-request id="2881"/> </commit> <commit subject="Index the base64 and hex decode tables with unsigned bytes."/> + <commit subject="Require a generated repository passphrase for new format 6 stanzas."> + <github-pull-request id="2880"/> + </commit> <release-item-contributor-list> <release-item-contributor id="david.steele"/> <release-item-reviewer id="douglas.j.hunley"/> <release-item-reviewer id="stefan.fercot"/> + <release-item-reviewer id="baptiste.arnoux"/> </release-item-contributor-list> <p>Repository encryption key rotation.</p> diff --git a/doc/xml/release/contributor.xml b/doc/xml/release/contributor.xml index 4714f2ce2..36858f5b2 100644 --- a/doc/xml/release/contributor.xml +++ b/doc/xml/release/contributor.xml @@ -170,6 +170,10 @@ <contributor-id type="github">avinashvallarapu</contributor-id> </contributor> +<contributor id="baptiste.arnoux"> + <contributor-name-display>Baptiste Arnoux</contributor-name-display> +</contributor> + <contributor id="bastian.wegge"> <contributor-name-display>Bastian Wegge</contributor-name-display> <contributor-id type="github">bastianwegge</contributor-id> diff --git a/doc/xml/user-guide.xml b/doc/xml/user-guide.xml index eca6da6f5..567c7fa51 100644 --- a/doc/xml/user-guide.xml +++ b/doc/xml/user-guide.xml @@ -84,7 +84,9 @@ <variable key="backrest-repo-path">/var/lib/pgbackrest</variable> <variable key="backrest-repo-cipher-type">aes-256-cbc</variable> - <variable key="backrest-repo-cipher-pass">zWaf6XtpjIVZC5444yXB+cgFDFl7MxGlgkZSaoPvTGirhPygu4jOKOXf9LO4vjfO</variable> + <variable key="backrest-repo-cipher-pass">6Y2m6+6mgf7Z8qboYyEIk48keXTx2Sjs3X1/7SFSRMk=</variable> + <!-- Passphrase shown in place of the installed passphrase. stanza-create rejects a passphrase that begins with CIPHER_PASS_EXAMPLE_PREFIX in src/command/stanza/create.c. --> + <variable key="backrest-repo-cipher-pass-display">zWaf6XtpjIVZC5444yXB+cgFDFl7MxGlgkZSaoPvTGi=</variable> <variable key="br-bin">/usr/bin/pgbackrest</variable> <variable key="br-user">pgbackrest</variable> <variable key="br-group">{[br-user]}</variable> @@ -1412,13 +1414,13 @@ <p>The repository will be configured with a cipher type and key to demonstrate encryption. Encryption is always performed client-side even if the repository type (e.g. <proper>S3</proper> or other object store) supports encryption.</p> - <p>It is important to use a long, random passphrase for the cipher key. A good way to generate one is to run: <code>openssl rand -base64 48</code>.</p> + <p>It is important to use a long, random passphrase for the cipher key. A good way to generate one is to run: <code>openssl rand -base64 32</code>.</p> <backrest-config host="{[host-pg1]}" file="{[backrest-config-demo]}"> <title>Configure <backrest/> repository encryption</title> <backrest-config-option section="global" key="repo1-cipher-type">{[backrest-repo-cipher-type]}</backrest-config-option> - <backrest-config-option section="global" key="repo1-cipher-pass">{[backrest-repo-cipher-pass]}</backrest-config-option> + <backrest-config-option section="global" key="repo1-cipher-pass" display="{[backrest-repo-cipher-pass-display]}">{[backrest-repo-cipher-pass]}</backrest-config-option> </backrest-config> <admonition type="note">Encryption settings are placed in the <id>[global]</id> section, above, so the <cmd>info</cmd> command can read all stanzas. Without the <br-option>stanza</br-option> option the <cmd>info</cmd> command reads encryption settings only from the <id>[global]</id> section, so encryption settings configured per stanza require the <br-option>stanza</br-option> option to read an encrypted stanza.</admonition> diff --git a/src/command/stanza/create.c b/src/command/stanza/create.c index 2883a7cdb..3eddf76c8 100644 --- a/src/command/stanza/create.c +++ b/src/command/stanza/create.c @@ -13,6 +13,7 @@ Stanza Create Command #include "command/stanza/common.h" #include "command/stanza/create.h" #include "common/debug.h" +#include "common/encode.h" #include "common/format/format.h" #include "common/log.h" #include "common/memContext.h" @@ -25,6 +26,102 @@ Stanza Create Command #include "protocol/helper.h" #include "storage/helper.h" +/*********************************************************************************************************************************** +Does the passphrase look randomly generated? It must be hex, base64, or unpadded base64url that decodes to at least 256 bits, the +decoded bytes must not all be text, and there must be enough distinct byte values and enough distinct differences between adjacent +bytes. Too few distinct differences means repeated values, a sequence, or a short repeating pattern. 32 random bytes are all text +with a probability of about 10^-14 and have fewer than 16 distinct values or differences with a probability of about 10^-15. The +passphrase could still be a weak secret that was hashed or encoded some other way, which we can't detect. +***********************************************************************************************************************************/ +// Bytes the key must decode to, i.e. 256 bits +#define CIPHER_PASS_GENERATED_SIZE_MIN 32 + +// Distinct byte values and distinct differences between adjacent bytes the key must contain +#define CIPHER_PASS_GENERATED_DISTINCT_MIN 16 + +// Prefix of the passphrase examples in the documentation +#define CIPHER_PASS_EXAMPLE_PREFIX "zWaf6XtpjIVZC5444yXB+cgFDFl7MxGlgkZSaoPvTGi" + +// Encodings to try in order. A hex passphrase may also be valid base64. +static const EncodingType cipherPassGeneratedEncoding[] = {encodingHex, encodingBase64, encodingBase64Url}; + +static bool +cipherPassGenerated(const CipherSpec *const cipherSpec) +{ + FUNCTION_TEST_BEGIN(); + FUNCTION_TEST_PARAM(CIPHER_SPEC, cipherSpec); + FUNCTION_TEST_END(); + + ASSERT(cipherSpec != NULL); + ASSERT(cipherSpecType(cipherSpec) != cipherTypeNone); + + bool result = false; + + MEM_CONTEXT_TEMP_BEGIN() + { + const String *const pass = strNewBuf(cipherSpecPass(cipherSpec)); + const Buffer *key = NULL; + + // Decode with the first encoding the passphrase is valid in + for (unsigned int encodingIdx = 0; encodingIdx < LENGTH_OF(cipherPassGeneratedEncoding) && key == NULL; encodingIdx++) + { + TRY_BEGIN() + { + key = bufNewDecode(cipherPassGeneratedEncoding[encodingIdx], pass); + } + // The passphrase is not valid in this encoding + CATCH(FormatError) + { + } + TRY_END(); + } + + if (key != NULL && bufUsed(key) >= CIPHER_PASS_GENERATED_SIZE_MIN) + { + bool text = true; + bool byteFound[256] = {false}; + unsigned int byteDistinct = 0; + bool deltaFound[256] = {false}; + unsigned int deltaDistinct = 0; + + for (size_t keyIdx = 0; keyIdx < bufUsed(key); keyIdx++) + { + const uint8_t byte = bufPtrConst(key)[keyIdx]; + + // A byte that is neither printable ASCII nor a tab, LF, or CR means the key is not text + if ((byte < ' ' || byte > '~') && byte != '\t' && byte != '\n' && byte != '\r') + text = false; + + // Count each byte value the first time it is seen + if (!byteFound[byte]) + { + byteFound[byte] = true; + byteDistinct++; + } + + // Count each difference from the prior byte the first time it is seen + if (keyIdx > 0) + { + const uint8_t delta = (uint8_t)(byte - bufPtrConst(key)[keyIdx - 1]); + + if (!deltaFound[delta]) + { + deltaFound[delta] = true; + deltaDistinct++; + } + } + } + + result = + !text && byteDistinct >= CIPHER_PASS_GENERATED_DISTINCT_MIN && + deltaDistinct >= CIPHER_PASS_GENERATED_DISTINCT_MIN; + } + } + MEM_CONTEXT_TEMP_END(); + + FUNCTION_TEST_RETURN(BOOL, result); +} + /**********************************************************************************************************************************/ FN_EXTERN void cmdStanzaCreate(void) @@ -79,6 +176,31 @@ cmdStanzaCreate(void) // Format for the new stanza const unsigned int format = cfgOptionIdxUInt(cfgOptRepoFormat, repoIdx); + // Check the passphrase of a new encrypted stanza + if (cfgOptionIdxStrId(cfgOptRepoCipherType, repoIdx) != cipherTypeNone) + { + // Error when the passphrase is a documentation example + if (strBeginsWithZ(cfgOptionIdxStr(cfgOptRepoCipherPass, repoIdx), CIPHER_PASS_EXAMPLE_PREFIX)) + { + THROW_FMT( + OptionInvalidValueError, + "option '%s' must not be the example passphrase from the documentation\n" + "HINT: generate a passphrase with 'openssl rand -base64 32'.", + cfgOptionIdxName(cfgOptRepoCipherPass, repoIdx)); + } + + // Format >= 6 requires the passphrase to look generated + if (format >= REPOSITORY_FORMAT_6 && !cipherPassGenerated(cfgCipherSpecMainIdx(repoIdx))) + { + THROW_FMT( + OptionInvalidValueError, + "option '%s' must be at least 256 random bits encoded as hex, base64, or base64url to create a stanza" + " at repository format " STRINGIFY(REPOSITORY_FORMAT_6) " or higher\n" + "HINT: generate a passphrase with 'openssl rand -base64 32'.", + cfgOptionIdxName(cfgOptRepoCipherPass, repoIdx)); + } + } + // If the repo is encrypted, generate a cipher passphrase for encrypting archive files. Format >= 6 adds it by // rotating to the first key id and earlier formats store it as the default key with no id. const CipherSpec *const cipherSpecArchive = cipherSpecGen(cfgOptionIdxStrId(cfgOptRepoCipherType, repoIdx), format); diff --git a/src/common/encode.c b/src/common/encode.c index 1e84fd379..82a3ac82e 100644 --- a/src/common/encode.c +++ b/src/common/encode.c @@ -220,7 +220,7 @@ decodeToBinSizeBase64(const char *const source) } /*********************************************************************************************************************************** -Base64Url encoding +Base64Url encoding/decoding ***********************************************************************************************************************************/ VR_NON_STRING static const char encodeBase64LookupUrl[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; @@ -289,6 +289,107 @@ encodeToStrSizeBase64Url(const size_t sourceSize) FUNCTION_TEST_RETURN(SIZE, sourceSize / 3 * 4 + (sourceSize % 3 == 0 ? 0 : sourceSize % 3 + 1)); } +/**********************************************************************************************************************************/ +static const int8_t decodeBase64LookupUrl[256] = +{ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, + -1, 0, 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, -1, -1, -1, -1, 63, + -1, 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, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +}; + +static void +decodeToBinValidateBase64Url(const char *const source) +{ + FUNCTION_TEST_BEGIN(); + FUNCTION_TEST_PARAM(STRINGZ, source); + FUNCTION_TEST_END(); + + // A final group without padding has two or three characters + const size_t sourceSize = strlen(source); + + if (sourceSize % 4 == 1) + THROW_FMT(FormatError, "base64url size %zu is not valid", sourceSize); + + // Error on any invalid characters + for (unsigned int sourceIdx = 0; sourceIdx < sourceSize; sourceIdx++) + { + if (decodeBase64LookupUrl[(uint8_t)source[sourceIdx]] == -1) + THROW_FMT(FormatError, "base64url invalid character found at position %u", sourceIdx); + } + + FUNCTION_TEST_RETURN_VOID(); +} + +/**********************************************************************************************************************************/ +static void +decodeToBinBase64Url(const char *const source, uint8_t *const destination) +{ + FUNCTION_TEST_BEGIN(); + FUNCTION_TEST_PARAM(STRINGZ, source); + FUNCTION_TEST_PARAM_P(BYTEDATA, destination); + FUNCTION_TEST_END(); + + // Validate encoded string + decodeToBinValidateBase64Url(source); + + const size_t sourceSize = strlen(source); + size_t destinationIdx = 0; + + // Decode the binary data from four characters to three bytes + for (size_t sourceIdx = 0; sourceIdx < sourceSize; sourceIdx += 4) + { + // Look up the value of each character in the group + const size_t groupSize = sourceSize - sourceIdx < 4 ? sourceSize - sourceIdx : 4; + uint8_t value[4] = {0}; + + for (size_t valueIdx = 0; valueIdx < groupSize; valueIdx++) + value[valueIdx] = (uint8_t)decodeBase64LookupUrl[(uint8_t)source[sourceIdx + valueIdx]]; + + // First byte is always present + destination[destinationIdx++] = (uint8_t)(value[0] << 2 | value[1] >> 4); + + // Second byte is present when the group has three or more characters + if (groupSize > 2) + destination[destinationIdx++] = (uint8_t)(value[1] << 4 | value[2] >> 2); + + // Third byte is present when the group has four characters + if (groupSize > 3) + destination[destinationIdx++] = (uint8_t)(value[2] << 6 | value[3]); + } + + FUNCTION_TEST_RETURN_VOID(); +} + +/**********************************************************************************************************************************/ +static size_t +decodeToBinSizeBase64Url(const char *const source) +{ + FUNCTION_TEST_BEGIN(); + FUNCTION_TEST_PARAM(STRINGZ, source); + FUNCTION_TEST_END(); + + // Validate encoded string + decodeToBinValidateBase64Url(source); + + // Three bytes are decoded from each 4 character group, two bytes from 3 characters, and one byte from 2 characters + const size_t sourceSize = strlen(source); + + FUNCTION_TEST_RETURN(SIZE, sourceSize / 4 * 3 + (sourceSize % 4 == 0 ? 0 : sourceSize % 4 - 1)); +} + /*********************************************************************************************************************************** Hex encoding/decoding ***********************************************************************************************************************************/ @@ -504,12 +605,13 @@ decodeToBin(const EncodingType type, const char *const source, uint8_t *const de decodeToBinBase64(source, destination); break; + case encodingBase64Url: + decodeToBinBase64Url(source, destination); + break; + case encodingHex: decodeToBinHex(source, destination); break; - - default: - ASSERT_MSG("unsupported"); } FUNCTION_TEST_RETURN_VOID(); @@ -534,12 +636,13 @@ decodeToBinSize(const EncodingType type, const char *const source) destinationSize = decodeToBinSizeBase64(source); break; + case encodingBase64Url: + destinationSize = decodeToBinSizeBase64Url(source); + break; + case encodingHex: destinationSize = decodeToBinSizeHex(source); break; - - default: - ASSERT_MSG("unsupported"); } FUNCTION_TEST_RETURN(SIZE, destinationSize); diff --git a/test/src/module/command/helpTest.c b/test/src/module/command/helpTest.c index d31535552..313dd1a7e 100644 --- a/test/src/module/command/helpTest.c +++ b/test/src/module/command/helpTest.c @@ -504,6 +504,14 @@ testRun(void) "\n" "Passphrase used to encrypt/decrypt files of the repository.\n" "\n" + "A stanza created at repo-format 6 or higher requires a passphrase generated\n" + "from at least 256 random bits, e.g. with openssl rand -base64 32. The\n" + "passphrase must be hex, base64, or unpadded base64url that decodes to at least\n" + "256 bits, the decoded bytes must not all be text, and they must contain at\n" + "least 16 distinct values and at least 16 distinct differences between adjacent\n" + "bytes. The last two rule out repeated values, sequences, and short repeating\n" + "patterns.\n" + "\n" "NOTE: When run without the stanza option the info command reads encryption\n" "settings only from the global section. If encryption settings are configured\n" "per stanza, run the info command with the stanza option to read an encrypted\n" diff --git a/test/src/module/command/stanzaTest.c b/test/src/module/command/stanzaTest.c index b50768d8a..6db4ccad2 100644 --- a/test/src/module/command/stanzaTest.c +++ b/test/src/module/command/stanzaTest.c @@ -12,6 +12,12 @@ Test Stanza Commands #include "harness/postgres.h" #include "harness/pq.h" +/*********************************************************************************************************************************** +Test data +***********************************************************************************************************************************/ +// Passphrase generated with openssl rand -base64 32, as required to create a stanza at format 6 +#define TEST_CIPHER_PASS_FMT6 "SOb5SRNoVLdVRtr2K3lr/oDmocARh2c+SObK6H8CtFY=" + /*********************************************************************************************************************************** Test Run ***********************************************************************************************************************************/ @@ -112,13 +118,96 @@ testRun(void) storageGetP(storageNewReadP(storageHrn, STRDEF("test.info")))), true, "test and stanza backup info files are equal"); + // ------------------------------------------------------------------------------------------------------------------------- + TEST_TITLE("stanza-create at format 6 requires a passphrase that looks generated"); + + argList = strLstDup(argListBase); + hrnCfgArgKeyRawZ(argList, cfgOptRepoPath, 4, TEST_PATH "/repo4"); + hrnCfgArgKeyRawStrId(argList, cfgOptRepoCipherType, 4, cipherTypeAes256Cbc); + hrnCfgArgKeyRawZ(argList, cfgOptRepoFormat, 4, "6"); + + #define TEST_CIPHER_PASS_FMT6_ERROR \ + "option 'repo4-cipher-pass' must be at least 256 random bits encoded as hex, base64, or base64url to create a" \ + " stanza at repository format 6 or higher\n" \ + "HINT: generate a passphrase with 'openssl rand -base64 32'." + + #define TEST_CIPHER_PASS_FMT6_LOG \ + "P00 INFO: stanza-create for stanza 'db' on repo1\n" \ + "P00 INFO: stanza 'db' already exists on repo1 and is valid\n" \ + "P00 INFO: stanza-create for stanza 'db' on repo4" + + // Valid base64 that is less than 256 bits + hrnCfgEnvKeyRawZ(cfgOptRepoCipherPass, 4, "SOb5SRNoVLdVRtr2K3lr/oDmocARh2c+SObK6H8CtA=="); + HRN_CFG_LOAD(cfgCmdStanzaCreate, argList); + + TEST_ERROR(cmdStanzaCreate(), OptionInvalidValueError, TEST_CIPHER_PASS_FMT6_ERROR); + TEST_RESULT_LOG(TEST_CIPHER_PASS_FMT6_LOG); + + // Hex that is less than 256 bits + hrnCfgEnvKeyRawZ(cfgOptRepoCipherPass, 4, "48e6f949136854b75546daf62b796bfe80e6a1c01187673e"); + HRN_CFG_LOAD(cfgCmdStanzaCreate, argList); + + TEST_ERROR(cmdStanzaCreate(), OptionInvalidValueError, TEST_CIPHER_PASS_FMT6_ERROR); + TEST_RESULT_LOG(TEST_CIPHER_PASS_FMT6_LOG); + + // Not base64 + hrnCfgEnvKeyRawZ(cfgOptRepoCipherPass, 4, "not base64"); + HRN_CFG_LOAD(cfgCmdStanzaCreate, argList); + + TEST_ERROR(cmdStanzaCreate(), OptionInvalidValueError, TEST_CIPHER_PASS_FMT6_ERROR); + TEST_RESULT_LOG(TEST_CIPHER_PASS_FMT6_LOG); + + // Text + hrnCfgEnvKeyRawZ(cfgOptRepoCipherPass, 4, "Y29ycmVjdAlob3JzZQ0KYmF0dGVyeSBzdGFwbGUgYW5kIG1vcmUgdGV4dA=="); + HRN_CFG_LOAD(cfgCmdStanzaCreate, argList); + + TEST_ERROR(cmdStanzaCreate(), OptionInvalidValueError, TEST_CIPHER_PASS_FMT6_ERROR); + TEST_RESULT_LOG(TEST_CIPHER_PASS_FMT6_LOG); + + // Too few distinct bytes + hrnCfgEnvKeyRawZ(cfgOptRepoCipherPass, 4, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="); + HRN_CFG_LOAD(cfgCmdStanzaCreate, argList); + + TEST_ERROR(cmdStanzaCreate(), OptionInvalidValueError, TEST_CIPHER_PASS_FMT6_ERROR); + TEST_RESULT_LOG(TEST_CIPHER_PASS_FMT6_LOG); + + // Too few distinct differences + hrnCfgEnvKeyRawZ(cfgOptRepoCipherPass, 4, "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="); + HRN_CFG_LOAD(cfgCmdStanzaCreate, argList); + + TEST_ERROR(cmdStanzaCreate(), OptionInvalidValueError, TEST_CIPHER_PASS_FMT6_ERROR); + TEST_RESULT_LOG(TEST_CIPHER_PASS_FMT6_LOG); + + // Prior documentation example + hrnCfgEnvKeyRawZ(cfgOptRepoCipherPass, 4, "zWaf6XtpjIVZC5444yXB+cgFDFl7MxGlgkZSaoPvTGirhPygu4jOKOXf9LO4vjfO"); + HRN_CFG_LOAD(cfgCmdStanzaCreate, argList); + + TEST_ERROR( + cmdStanzaCreate(), OptionInvalidValueError, + "option 'repo4-cipher-pass' must not be the example passphrase from the documentation\n" + "HINT: generate a passphrase with 'openssl rand -base64 32'."); + TEST_RESULT_LOG(TEST_CIPHER_PASS_FMT6_LOG); + + // base64url without padding + TEST_RESULT_BOOL( + cipherPassGenerated(cipherSpecNewP(cipherTypeAes256Cbc, BUFSTRDEF("SOb5SRNoVLdVRtr2K3lr_oDmocARh2c-SObK6H8CtFY"))), + true, "base64url without padding"); + + // Hex + TEST_RESULT_BOOL( + cipherPassGenerated( + cipherSpecNewP(cipherTypeAes256Cbc, BUFSTRDEF("48e6f949136854b75546daf62b796bfe80e6a1c01187673e48e6cae87f02b456"))), + true, "hex"); + + TEST_RESULT_BOOL(storagePathExistsP(storageTest, STRDEF("repo4")), false, "nothing created"); + // ------------------------------------------------------------------------------------------------------------------------- TEST_TITLE("cmdStanzaCreate success - multi-repo and encryption"); argList = strLstDup(argListBase); hrnCfgArgKeyRawZ(argList, cfgOptRepoPath, 2, TEST_PATH "/repo2"); hrnCfgArgKeyRawStrId(argList, cfgOptRepoCipherType, 2, cipherTypeAes256Cbc); - hrnCfgEnvKeyRawZ(cfgOptRepoCipherPass, 2, "12345678"); + hrnCfgEnvKeyRawZ(cfgOptRepoCipherPass, 2, "zWaf6XtpjIVZC5444yXB+cgFDFl7MxGlgkZSaoPvTGi="); hrnCfgArgKeyRawZ(argList, cfgOptRepoPath, 3, TEST_PATH "/repo3"); hrnCfgArgKeyRawZ(argList, cfgOptRepoFormat, 3, "6"); // Request a format for repo1 as well, where the stanza already exists @@ -126,7 +215,19 @@ testRun(void) hrnCfgArgKeyRawZ(argList, cfgOptRepoPath, 4, TEST_PATH "/repo4"); hrnCfgArgKeyRawStrId(argList, cfgOptRepoCipherType, 4, cipherTypeAes256Cbc); hrnCfgArgKeyRawZ(argList, cfgOptRepoFormat, 4, "6"); - hrnCfgEnvKeyRawZ(cfgOptRepoCipherPass, 4, "87654321"); + hrnCfgEnvKeyRawZ(cfgOptRepoCipherPass, 4, TEST_CIPHER_PASS_FMT6); + HRN_CFG_LOAD(cfgCmdStanzaCreate, argList); + + TEST_ERROR( + cmdStanzaCreate(), OptionInvalidValueError, + "option 'repo2-cipher-pass' must not be the example passphrase from the documentation\n" + "HINT: generate a passphrase with 'openssl rand -base64 32'."); + TEST_RESULT_LOG( + "P00 INFO: stanza-create for stanza 'db' on repo1\n" + "P00 INFO: stanza 'db' already exists on repo1 and is valid\n" + "P00 INFO: stanza-create for stanza 'db' on repo2"); + + hrnCfgEnvKeyRawZ(cfgOptRepoCipherPass, 2, "12345678"); HRN_CFG_LOAD(cfgCmdStanzaCreate, argList); const time_t timeCreate = time(NULL); @@ -191,7 +292,8 @@ testRun(void) TEST_ASSIGN( infoArchive, infoArchiveLoadFile( - storageRepoIdx(3), INFO_ARCHIVE_PATH_FILE_STR, cipherSpecNewP(cipherTypeAes256Cbc, BUFSTRDEF("87654321"))), + storageRepoIdx(3), INFO_ARCHIVE_PATH_FILE_STR, + cipherSpecNewP(cipherTypeAes256Cbc, BUFSTRDEF(TEST_CIPHER_PASS_FMT6))), "load archive info from encrypted repo4"); const CipherSpecMap *const cipherSpecMapCreate = infoArchiveCipherSpecMap(infoArchive); @@ -212,7 +314,8 @@ testRun(void) TEST_ASSIGN( infoBackup, infoBackupLoadFile( - storageRepoIdx(3), INFO_BACKUP_PATH_FILE_STR, cipherSpecNewP(cipherTypeAes256Cbc, BUFSTRDEF("87654321"))), + storageRepoIdx(3), INFO_BACKUP_PATH_FILE_STR, + cipherSpecNewP(cipherTypeAes256Cbc, BUFSTRDEF(TEST_CIPHER_PASS_FMT6))), "load backup info from encrypted repo4"); TEST_RESULT_UINT(cipherSpecType(infoBackupCipherSpec(infoBackup)), cipherTypeAes256Cbc, "cipher sub set"); diff --git a/test/src/module/common/encodeTest.c b/test/src/module/common/encodeTest.c index 9c5b6341f..54090b7ab 100644 --- a/test/src/module/common/encodeTest.c +++ b/test/src/module/common/encodeTest.c @@ -149,12 +149,58 @@ testRun(void) encodeToStrSize(encodingBase64Url, strlen((const char *)encode) + 1), strlen(destinationEncode), "check size"); // ------------------------------------------------------------------------------------------------------------------------- - TEST_TITLE("decode unsupported"); + TEST_TITLE("decode"); uint8_t destinationDecode[256]; - TEST_ERROR(decodeToBinSize(encodingBase64Url, "c3"), AssertError, "unsupported"); - TEST_ERROR(decodeToBin(encodingBase64Url, "c3", destinationDecode), AssertError, "unsupported"); + memset(destinationDecode, 0xFF, sizeof(destinationDecode)); + const char *decode = "c3RyaW5nX3RvX2VuY29kZQ0KAA"; + decodeToBin(encodingBase64Url, decode, destinationDecode); + TEST_RESULT_Z((char *)destinationDecode, (const char *)encode, "full string with \\r\\n and null decode"); + TEST_RESULT_INT(destinationDecode[strlen((const char *)encode) + 1], 0xFF, "check for overrun"); + TEST_RESULT_UINT(decodeToBinSize(encodingBase64Url, decode), strlen((const char *)encode) + 1, "check size"); + + memset(destinationDecode, 0xFF, sizeof(destinationDecode)); + decode = "c3RyaW5nX3RvX2VuY29kZQ0K"; + decodeToBin(encodingBase64Url, decode, destinationDecode); + TEST_RESULT_INT(memcmp(destinationDecode, encode, strlen((const char *)encode)), 0, "full string with \\r\\n decode"); + TEST_RESULT_INT(destinationDecode[strlen((const char *)encode)], 0xFF, "check for overrun"); + TEST_RESULT_UINT(decodeToBinSize(encodingBase64Url, decode), strlen((const char *)encode), "check size"); + + memset(destinationDecode, 0xFF, sizeof(destinationDecode)); + decode = "c3Q"; + decodeToBin(encodingBase64Url, decode, destinationDecode); + TEST_RESULT_INT(memcmp(destinationDecode, encode, 2), 0, "2 character decode"); + TEST_RESULT_INT(destinationDecode[2], 0xFF, "check for overrun"); + TEST_RESULT_UINT(decodeToBinSize(encodingBase64Url, decode), 2, "check size"); + + memset(destinationDecode, 0xFF, sizeof(destinationDecode)); + decode = "cw"; + decodeToBin(encodingBase64Url, decode, destinationDecode); + TEST_RESULT_INT(memcmp(destinationDecode, encode, 1), 0, "1 character decode"); + TEST_RESULT_INT(destinationDecode[1], 0xFF, "check for overrun"); + TEST_RESULT_UINT(decodeToBinSize(encodingBase64Url, decode), 1, "check size"); + + memset(destinationDecode, 0xFF, sizeof(destinationDecode)); + decode = ""; + decodeToBin(encodingBase64Url, decode, destinationDecode); + TEST_RESULT_INT(destinationDecode[0], 0xFF, "check for overrun"); + TEST_RESULT_UINT(decodeToBinSize(encodingBase64Url, decode), 0, "check zero size"); + + decode = "-_-_"; + decodeToBin(encodingBase64Url, decode, destinationDecode); + TEST_RESULT_INT(memcmp(destinationDecode, "\xfb\xff\xbf", 3), 0, "url characters decode"); + + TEST_ERROR(decodeToBin(encodingBase64Url, "c3Ryc", destinationDecode), FormatError, "base64url size 5 is not valid"); + TEST_ERROR( + decodeToBin(encodingBase64Url, "cw==", destinationDecode), FormatError, + "base64url invalid character found at position 2"); + TEST_ERROR( + decodeToBin(encodingBase64Url, "c+/", destinationDecode), FormatError, + "base64url invalid character found at position 1"); + TEST_ERROR( + decodeToBin(encodingBase64Url, "c\xc3\xa9", destinationDecode), FormatError, + "base64url invalid character found at position 1"); } // ***************************************************************************************************************************** diff --git a/test/src/module/doc/command/render/execute_test.py b/test/src/module/doc/command/render/execute_test.py index cb72c2392..036971571 100644 --- a/test/src/module/doc/command/render/execute_test.py +++ b/test/src/module/doc/command/render/execute_test.py @@ -512,6 +512,7 @@ def test_backrest_config(): config = _doc( """<backrest-config host="repo" file="/etc/pgbackrest.conf"><title>Configure</title> <backrest-config-option section="global" key="repo1-path">/var/lib/pgbackrest</backrest-config-option> + <backrest-config-option section="global" key="repo1-cipher-pass" display="shown">installed</backrest-config-option> <backrest-config-option section="global" key="log-level-stderr">off</backrest-config-option> <backrest-config-option section="global" key="pg1-path" multi="y">/pg1</backrest-config-option> <backrest-config-option section="global" key="pg1-path" multi="y">/pg2</backrest-config-option> @@ -531,12 +532,16 @@ def test_backrest_config(): ("add", "[global]"), ("add", "pg1-path=/pg1"), ("add", "pg1-path=/pg2"), + ("add", "repo1-cipher-pass=shown"), ("add", "repo1-path=/var/lib/pgbackrest"), ], ) - # The file that is installed on the host has everything in it - assert_in("log-level-stderr=off", file_read(os.path.join(path, "output/pgbackrest.conf"))) + # The file that is installed on the host has everything in it and the installed values + installed = file_read(os.path.join(path, "output/pgbackrest.conf")) + + assert_in("log-level-stderr=off", installed) + assert_in("repo1-cipher-pass=installed", installed) # A later section adds to what is already there and only what it added is marked config = _doc( @@ -556,6 +561,7 @@ def test_backrest_config(): ("same", "[global]"), ("same", "pg1-path=/pg1"), ("same", "pg1-path=/pg2"), + ("same", "repo1-cipher-pass=shown"), ("same", "repo1-path=/var/lib/pgbackrest"), ], ) @@ -758,13 +764,16 @@ def test_config_key(): """<backrest-config host="repo" file="/etc/x" reset="y"><title>C</title> <backrest-config-option section="global" key="a">1</backrest-config-option> <backrest-config-option section="global" key="b" remove="y"/> + <backrest-config-option section="global" key="c" display="shown">3</backrest-config-option> </backrest-config>""" ) ) assert_equal(key["host"], "repo") assert_true(key["reset"]) - assert_equal(key["option"], {"global": {"a": {"value": "1"}, "b": {"remove": True}}}) + assert_equal( + key["option"], {"global": {"a": {"value": "1"}, "b": {"remove": True}, "c": {"value": "3", "display": "shown"}}} + ) # A PostgreSQL option has no section of its own, since the file has none key = render.config_key( [parent: 01c269c922ec]