all lists on lists.proxmox.com
 help / color / mirror / Atom feed
* [pbs-devel] [PATCH backup v3 1/2] pbs-client: read credentials from $CREDENTIALS_DIRECTORY
@ 2025-03-26 10:51 Maximiliano Sandoval
  2025-03-26 10:51 ` [pbs-devel] [PATCH backup v3 2/2] pbs-client: make get_secret_from_env private Maximiliano Sandoval
                   ` (2 more replies)
  0 siblings, 3 replies; 4+ messages in thread
From: Maximiliano Sandoval @ 2025-03-26 10:51 UTC (permalink / raw)
  To: pbs-devel

Allows to load credentials passed down by systemd. A possible use-case
is safely storing the server's password in a file encrypted by the
systems TPM, e.g. via

```
systemd-ask-password -n | systemd-creds encrypt --name=proxmox-backup-client.password - my-api-token.cred
```

which then can be used via

```
systemd-run --pipe --wait --property=LoadCredentialEncrypted=proxmox-backup-client.password:my-api-token.cred \
proxmox-backup-client ...
```

or from inside a service.

Signed-off-by: Maximiliano Sandoval <m.sandoval@proxmox.com>
---

Differences from v2:
 - Rename credentials to `proxmox-backup-client.{encryption-,}password`

Differences from v1:
 - Report errors on get_credential instead of returning None
 - Make get_secret_from_env private
 - Add a bit of logging
 - Simplify helpers

 pbs-client/src/tools/key_source.rs |  4 +-
 pbs-client/src/tools/mod.rs        | 80 +++++++++++++++++++++++++++++-
 2 files changed, 80 insertions(+), 4 deletions(-)

diff --git a/pbs-client/src/tools/key_source.rs b/pbs-client/src/tools/key_source.rs
index 7968e0c2a..94b86e8b6 100644
--- a/pbs-client/src/tools/key_source.rs
+++ b/pbs-client/src/tools/key_source.rs
@@ -345,8 +345,8 @@ pub(crate) unsafe fn set_test_default_master_pubkey(value: Result<Option<Vec<u8>
 pub fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
     // fixme: implement other input methods
 
-    if let Some(password) = super::get_secret_from_env("PBS_ENCRYPTION_PASSWORD")? {
-        return Ok(password.as_bytes().to_vec());
+    if let Some(password) = super::get_encryption_password()? {
+        return Ok(password);
     }
 
     // If we're on a TTY, query the user for a password
diff --git a/pbs-client/src/tools/mod.rs b/pbs-client/src/tools/mod.rs
index 8068dc004..d231ab567 100644
--- a/pbs-client/src/tools/mod.rs
+++ b/pbs-client/src/tools/mod.rs
@@ -28,6 +28,16 @@ pub mod key_source;
 
 const ENV_VAR_PBS_FINGERPRINT: &str = "PBS_FINGERPRINT";
 const ENV_VAR_PBS_PASSWORD: &str = "PBS_PASSWORD";
+const ENV_VAR_PBS_ENCRYPTION_PASSWORD: &str = "PBS_ENCRYPTION_PASSWORD";
+
+/// Directory with system [credential]s. See systemd-creds(1).
+///
+/// [credential]: https://systemd.io/CREDENTIALS/
+const ENV_VAR_CREDENTIALS_DIRECTORY: &str = "CREDENTIALS_DIRECTORY";
+/// Credential name of the encryption password.
+const CRED_PBS_ENCRYPTION_PASSWORD: &str = "proxmox-backup-client.encryption-password";
+/// Credential name of the the password.
+const CRED_PBS_PASSWORD: &str = "proxmox-backup-client.password";
 
 pub const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.")
     .format(&BACKUP_REPO_URL)
@@ -40,6 +50,30 @@ pub const CHUNK_SIZE_SCHEMA: Schema = IntegerSchema::new("Chunk size in KB. Must
     .default(4096)
     .schema();
 
+/// Retrieves a secret stored in a [credential] provided by systemd.
+///
+/// Returns `Ok(None)` if the credential does not exist.
+///
+/// [credential]: https://systemd.io/CREDENTIALS/
+fn get_credential(cred_name: &str) -> std::io::Result<Option<Vec<u8>>> {
+    let Some(creds_dir) = std::env::var_os(ENV_VAR_CREDENTIALS_DIRECTORY) else {
+        return Ok(None);
+    };
+    let path = std::path::Path::new(&creds_dir).join(cred_name);
+
+    proxmox_log::debug!("attempting to use credential {cred_name} from {creds_dir:?}",);
+    // We read the whole contents without a BufRead. As per systemd-creds(1):
+    // Credentials are limited-size binary or textual objects.
+    match std::fs::read(&path) {
+        Ok(bytes) => Ok(Some(bytes)),
+        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
+            proxmox_log::debug!("no {cred_name} credential found in {creds_dir:?}");
+            Ok(None)
+        }
+        Err(err) => Err(err),
+    }
+}
+
 /// Helper to read a secret through a environment variable (ENV).
 ///
 /// Tries the following variable names in order and returns the value
@@ -118,6 +152,48 @@ pub fn get_secret_from_env(base_name: &str) -> Result<Option<String>, Error> {
     Ok(None)
 }
 
+/// Gets the backup server's password.
+///
+/// Looks for a password in the `PBS_PASSWORD` environment variable, if there
+/// isn't one it reads the `proxmox-backup-client.password` [credential].
+///
+/// Returns `Ok(None)` if neither the environment variable or credentials are
+/// present.
+///
+/// [credential]: https://systemd.io/CREDENTIALS/
+pub fn get_password() -> Result<Option<String>, Error> {
+    if let Some(password) = get_secret_from_env(ENV_VAR_PBS_PASSWORD)? {
+        Ok(Some(password))
+    } else if let Some(password) = get_credential(CRED_PBS_PASSWORD)? {
+        String::from_utf8(password)
+            .map(Option::Some)
+            .map_err(|_err| format_err!("non-utf8 password credential"))
+    } else {
+        Ok(None)
+    }
+}
+
+/// Gets an encryption password.
+///
+///
+/// Looks for a password in the `PBS_ENCRYPTION_PASSWORD` environment variable,
+/// if there isn't one it reads the `proxmox-backup-client.encryption-password`
+/// [credential].
+///
+/// Returns `Ok(None)` if neither the environment variable or credentials are
+/// present.
+///
+/// [credential]: https://systemd.io/CREDENTIALS/
+pub fn get_encryption_password() -> Result<Option<Vec<u8>>, Error> {
+    if let Some(password) = get_secret_from_env(ENV_VAR_PBS_ENCRYPTION_PASSWORD)? {
+        Ok(Some(password.into_bytes()))
+    } else if let Some(password) = get_credential(CRED_PBS_ENCRYPTION_PASSWORD)? {
+        Ok(Some(password))
+    } else {
+        Ok(None)
+    }
+}
+
 pub fn get_default_repository() -> Option<String> {
     std::env::var("PBS_REPOSITORY").ok()
 }
@@ -181,7 +257,7 @@ fn connect_do(
 ) -> Result<HttpClient, Error> {
     let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
 
-    let password = get_secret_from_env(ENV_VAR_PBS_PASSWORD)?;
+    let password = get_password()?;
     let options = HttpClientOptions::new_interactive(password, fingerprint).rate_limit(rate_limit);
 
     HttpClient::new(server, port, auth_id, options)
@@ -190,7 +266,7 @@ fn connect_do(
 /// like get, but simply ignore errors and return Null instead
 pub async fn try_get(repo: &BackupRepository, url: &str) -> Value {
     let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
-    let password = get_secret_from_env(ENV_VAR_PBS_PASSWORD).unwrap_or(None);
+    let password = get_password().unwrap_or(None);
 
     // ticket cache, but no questions asked
     let options = HttpClientOptions::new_interactive(password, fingerprint).interactive(false);
-- 
2.39.5



_______________________________________________
pbs-devel mailing list
pbs-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/pbs-devel


^ permalink raw reply	[flat|nested] 4+ messages in thread

* [pbs-devel] [PATCH backup v3 2/2] pbs-client: make get_secret_from_env private
  2025-03-26 10:51 [pbs-devel] [PATCH backup v3 1/2] pbs-client: read credentials from $CREDENTIALS_DIRECTORY Maximiliano Sandoval
@ 2025-03-26 10:51 ` Maximiliano Sandoval
  2025-03-26 11:06 ` [pbs-devel] [PATCH backup v3 1/2] pbs-client: read credentials from $CREDENTIALS_DIRECTORY Thomas Lamprecht
  2025-03-26 12:00 ` [pbs-devel] applied-series: " Wolfgang Bumiller
  2 siblings, 0 replies; 4+ messages in thread
From: Maximiliano Sandoval @ 2025-03-26 10:51 UTC (permalink / raw)
  To: pbs-devel

Since we are exposing functions now to get the password and encryption
password this should be private.

Signed-off-by: Maximiliano Sandoval <m.sandoval@proxmox.com>
---
 pbs-client/src/tools/mod.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/pbs-client/src/tools/mod.rs b/pbs-client/src/tools/mod.rs
index d231ab567..3b19df390 100644
--- a/pbs-client/src/tools/mod.rs
+++ b/pbs-client/src/tools/mod.rs
@@ -85,7 +85,7 @@ fn get_credential(cred_name: &str) -> std::io::Result<Option<Vec<u8>>> {
 /// BASE_NAME_CMD => read the secret from specified command first line of output on stdout
 ///
 /// Only return the first line of data (without CRLF).
-pub fn get_secret_from_env(base_name: &str) -> Result<Option<String>, Error> {
+fn get_secret_from_env(base_name: &str) -> Result<Option<String>, Error> {
     let firstline = |data: String| -> String {
         match data.lines().next() {
             Some(line) => line.to_string(),
-- 
2.39.5



_______________________________________________
pbs-devel mailing list
pbs-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/pbs-devel


^ permalink raw reply	[flat|nested] 4+ messages in thread

* Re: [pbs-devel] [PATCH backup v3 1/2] pbs-client: read credentials from $CREDENTIALS_DIRECTORY
  2025-03-26 10:51 [pbs-devel] [PATCH backup v3 1/2] pbs-client: read credentials from $CREDENTIALS_DIRECTORY Maximiliano Sandoval
  2025-03-26 10:51 ` [pbs-devel] [PATCH backup v3 2/2] pbs-client: make get_secret_from_env private Maximiliano Sandoval
@ 2025-03-26 11:06 ` Thomas Lamprecht
  2025-03-26 12:00 ` [pbs-devel] applied-series: " Wolfgang Bumiller
  2 siblings, 0 replies; 4+ messages in thread
From: Thomas Lamprecht @ 2025-03-26 11:06 UTC (permalink / raw)
  To: Proxmox Backup Server development discussion, Maximiliano Sandoval

Am 26.03.25 um 11:51 schrieb Maximiliano Sandoval:
> Allows to load credentials passed down by systemd. A possible use-case
> is safely storing the server's password in a file encrypted by the
> systems TPM, e.g. via
> 
> ```
> systemd-ask-password -n | systemd-creds encrypt --name=proxmox-backup-client.password - my-api-token.cred
> ```
> 
> which then can be used via
> 
> ```
> systemd-run --pipe --wait --property=LoadCredentialEncrypted=proxmox-backup-client.password:my-api-token.cred \
> proxmox-backup-client ...
> ```
> 
> or from inside a service.


I lightly skimmed over the code, looks alright to me (feel free to apply
@Wolfgang), but I'm missing a patch for the documentation so that users
can know about this possibility – can be followed up though.



_______________________________________________
pbs-devel mailing list
pbs-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/pbs-devel

^ permalink raw reply	[flat|nested] 4+ messages in thread

* [pbs-devel] applied-series: [PATCH backup v3 1/2] pbs-client: read credentials from $CREDENTIALS_DIRECTORY
  2025-03-26 10:51 [pbs-devel] [PATCH backup v3 1/2] pbs-client: read credentials from $CREDENTIALS_DIRECTORY Maximiliano Sandoval
  2025-03-26 10:51 ` [pbs-devel] [PATCH backup v3 2/2] pbs-client: make get_secret_from_env private Maximiliano Sandoval
  2025-03-26 11:06 ` [pbs-devel] [PATCH backup v3 1/2] pbs-client: read credentials from $CREDENTIALS_DIRECTORY Thomas Lamprecht
@ 2025-03-26 12:00 ` Wolfgang Bumiller
  2 siblings, 0 replies; 4+ messages in thread
From: Wolfgang Bumiller @ 2025-03-26 12:00 UTC (permalink / raw)
  To: Maximiliano Sandoval; +Cc: pbs-devel

applied series, thanks

As Thomas said: doc patches would be good.

I also agree with what Jörg said, the following additional credentials
should be added as well:
  - proxmox-backup-client.repository (=PBS_REPOSITORY)
  - proxmox-backup-client.fingerprint (=PBS_FINGERPRINT)


_______________________________________________
pbs-devel mailing list
pbs-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/pbs-devel


^ permalink raw reply	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2025-03-26 12:00 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2025-03-26 10:51 [pbs-devel] [PATCH backup v3 1/2] pbs-client: read credentials from $CREDENTIALS_DIRECTORY Maximiliano Sandoval
2025-03-26 10:51 ` [pbs-devel] [PATCH backup v3 2/2] pbs-client: make get_secret_from_env private Maximiliano Sandoval
2025-03-26 11:06 ` [pbs-devel] [PATCH backup v3 1/2] pbs-client: read credentials from $CREDENTIALS_DIRECTORY Thomas Lamprecht
2025-03-26 12:00 ` [pbs-devel] applied-series: " Wolfgang Bumiller

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal