]> git.proxmox.com Git - proxmox-backup.git/commitdiff
move pbs_tools::ticket to pbs_ticket
authorWolfgang Bumiller <w.bumiller@proxmox.com>
Tue, 13 Dec 2022 12:55:16 +0000 (13:55 +0100)
committerWolfgang Bumiller <w.bumiller@proxmox.com>
Tue, 13 Dec 2022 12:58:09 +0000 (13:58 +0100)
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
13 files changed:
Cargo.toml
pbs-client/Cargo.toml
pbs-client/src/http_client.rs
pbs-ticket/Cargo.toml [new file with mode: 0644]
pbs-ticket/src/lib.rs [new file with mode: 0644]
pbs-tools/Cargo.toml
pbs-tools/src/lib.rs
pbs-tools/src/ticket.rs [deleted file]
src/api2/access/mod.rs
src/api2/access/openid.rs
src/api2/node/mod.rs
src/client_helpers.rs
src/server/auth.rs

index 6fce247d0ac4a7878ee75997b0f3a14ee2537e38..16f4822cbb896b7927002306551db3d7673f886d 100644 (file)
@@ -37,6 +37,7 @@ members = [
     "pbs-key-config",
     "pbs-pxar-fuse",
     "pbs-tape",
+    "pbs-ticket",
     "pbs-tools",
 
     "proxmox-backup-banner",
@@ -93,6 +94,7 @@ pbs-fuse-loop = { path = "pbs-fuse-loop" }
 pbs-key-config = { path = "pbs-key-config" }
 pbs-pxar-fuse = { path = "pbs-pxar-fuse" }
 pbs-tape = { path = "pbs-tape" }
+pbs-ticket = { path = "pbs-ticket" }
 pbs-tools = { path = "pbs-tools" }
 proxmox-rrd = { path = "proxmox-rrd" }
 
@@ -229,6 +231,7 @@ pbs-config.workspace = true
 pbs-datastore.workspace = true
 pbs-key-config.workspace = true
 pbs-tape.workspace = true
+pbs-ticket.workspace = true
 pbs-tools.workspace = true
 proxmox-rrd.workspace = true
 
index 02d33854e503492064e13b1ed348233965dc61e5..4bae79d69739bad65ee0845f68d8128228ad2a42 100644 (file)
@@ -48,4 +48,5 @@ pxar.workspace = true
 pbs-api-types.workspace = true
 pbs-buildcfg.workspace = true
 pbs-datastore.workspace = true
+pbs-ticket.workspace = true
 pbs-tools.workspace = true
index c78d08f30c89442df8d91c44d089c8bd43d5893b..c86b19254e5a55943eca7a4d5eb36d6ff2656a0f 100644 (file)
@@ -28,7 +28,6 @@ use proxmox_http::ProxyConfig;
 
 use pbs_api_types::percent_encoding::DEFAULT_ENCODE_SET;
 use pbs_api_types::{Authid, RateLimitConfig, Userid};
-use pbs_tools::ticket;
 
 use super::pipe_to_stream::PipeToSendStream;
 use super::PROXMOX_BACKUP_TCP_KEEPALIVE_TIME;
@@ -250,7 +249,7 @@ fn store_ticket_info(
 
     let mut new_data = json!({});
 
-    let ticket_lifetime = ticket::TICKET_LIFETIME - 60;
+    let ticket_lifetime = pbs_ticket::TICKET_LIFETIME - 60;
 
     let empty = serde_json::map::Map::new();
     for (server, info) in data.as_object().unwrap_or(&empty) {
@@ -281,7 +280,7 @@ fn load_ticket_info(prefix: &str, server: &str, userid: &Userid) -> Option<(Stri
     let path = base.place_runtime_file("tickets").ok()?;
     let data = file_get_json(&path, None).ok()?;
     let now = proxmox_time::epoch_i64();
-    let ticket_lifetime = ticket::TICKET_LIFETIME - 60;
+    let ticket_lifetime = pbs_ticket::TICKET_LIFETIME - 60;
     let uinfo = data[server][userid.as_str()].as_object()?;
     let timestamp = uinfo["timestamp"].as_i64()?;
     let age = now - timestamp;
diff --git a/pbs-ticket/Cargo.toml b/pbs-ticket/Cargo.toml
new file mode 100644 (file)
index 0000000..afe99b9
--- /dev/null
@@ -0,0 +1,14 @@
+[package]
+name = "pbs-ticket"
+version = "0.1.0"
+authors.workspace = true
+edition.workspace = true
+description = "pbs ticket handling"
+
+[dependencies]
+anyhow.workspace = true
+base64.workspace = true
+openssl.workspace = true
+percent-encoding.workspace = true
+
+proxmox-time.workspace = true
diff --git a/pbs-ticket/src/lib.rs b/pbs-ticket/src/lib.rs
new file mode 100644 (file)
index 0000000..fcb88ff
--- /dev/null
@@ -0,0 +1,332 @@
+//! Generate and verify Authentication tickets
+
+use std::borrow::Cow;
+use std::io;
+use std::marker::PhantomData;
+
+use anyhow::{bail, format_err, Error};
+use openssl::hash::MessageDigest;
+use openssl::pkey::{HasPublic, PKey, Private};
+use openssl::sign::{Signer, Verifier};
+use percent_encoding::{percent_decode_str, percent_encode, AsciiSet};
+
+pub const TICKET_LIFETIME: i64 = 3600 * 2; // 2 hours
+
+pub const TERM_PREFIX: &str = "PBSTERM";
+
+/// Stringified ticket data must not contain colons...
+const TICKET_ASCIISET: &AsciiSet = &percent_encoding::CONTROLS.add(b':');
+
+/// An empty type implementing [`ToString`] and [`FromStr`](std::str::FromStr), used for tickets
+/// with no data.
+pub struct Empty;
+
+impl ToString for Empty {
+    fn to_string(&self) -> String {
+        String::new()
+    }
+}
+
+impl std::str::FromStr for Empty {
+    type Err = Error;
+
+    fn from_str(s: &str) -> Result<Self, Error> {
+        if !s.is_empty() {
+            bail!("unexpected ticket data, should be empty");
+        }
+        Ok(Empty)
+    }
+}
+
+/// An API ticket consists of a ticket type (prefix), type-dependent data, optional additional
+/// authenticaztion data, a timestamp and a signature. We store these values in the form
+/// `<prefix>:<stringified data>:<timestamp>::<signature>`.
+///
+/// The signature is made over the string consisting of prefix, data, timestamp and aad joined
+/// together by colons. If there is no additional authentication data it will be skipped together
+/// with the colon separating it from the timestamp.
+pub struct Ticket<T>
+where
+    T: ToString + std::str::FromStr,
+{
+    prefix: Cow<'static, str>,
+    data: String,
+    time: i64,
+    signature: Option<Vec<u8>>,
+    _type_marker: PhantomData<fn() -> T>,
+}
+
+impl<T> Ticket<T>
+where
+    T: ToString + std::str::FromStr,
+    <T as std::str::FromStr>::Err: std::fmt::Debug,
+{
+    /// Prepare a new ticket for signing.
+    pub fn new(prefix: &'static str, data: &T) -> Result<Self, Error> {
+        Ok(Self {
+            prefix: Cow::Borrowed(prefix),
+            data: data.to_string(),
+            time: proxmox_time::epoch_i64(),
+            signature: None,
+            _type_marker: PhantomData,
+        })
+    }
+
+    /// Get the ticket prefix.
+    pub fn prefix(&self) -> &str {
+        &self.prefix
+    }
+
+    /// Get the ticket's time stamp in seconds since the unix epoch.
+    pub fn time(&self) -> i64 {
+        self.time
+    }
+
+    /// Get the raw string data contained in the ticket. The `verify` method will call `parse()`
+    /// this in the end, so using this method directly is discouraged as it does not verify the
+    /// signature.
+    pub fn raw_data(&self) -> &str {
+        &self.data
+    }
+
+    /// Serialize the ticket into a writer.
+    ///
+    /// This only writes a string. We use `io::write` instead of `fmt::Write` so we can reuse the
+    /// same function for openssl's `Verify`, which only implements `io::Write`.
+    fn write_data(&self, f: &mut dyn io::Write) -> Result<(), Error> {
+        write!(
+            f,
+            "{}:{}:{:08X}",
+            percent_encode(self.prefix.as_bytes(), TICKET_ASCIISET),
+            percent_encode(self.data.as_bytes(), TICKET_ASCIISET),
+            self.time,
+        )
+        .map_err(Error::from)
+    }
+
+    /// Write additional authentication data to the verifier.
+    fn write_aad(f: &mut dyn io::Write, aad: Option<&str>) -> Result<(), Error> {
+        if let Some(aad) = aad {
+            write!(f, ":{}", percent_encode(aad.as_bytes(), TICKET_ASCIISET))?;
+        }
+        Ok(())
+    }
+
+    /// Change the ticket's time, used mostly for testing.
+    #[cfg(test)]
+    fn change_time(&mut self, time: i64) -> &mut Self {
+        self.time = time;
+        self
+    }
+
+    /// Sign the ticket.
+    pub fn sign(&mut self, keypair: &PKey<Private>, aad: Option<&str>) -> Result<String, Error> {
+        let mut output = Vec::<u8>::new();
+        let mut signer = Signer::new(MessageDigest::sha256(), keypair)
+            .map_err(|err| format_err!("openssl error creating signer for ticket: {}", err))?;
+
+        self.write_data(&mut output)
+            .map_err(|err| format_err!("error creating ticket: {}", err))?;
+
+        signer
+            .update(&output)
+            .map_err(Error::from)
+            .and_then(|()| Self::write_aad(&mut signer, aad))
+            .map_err(|err| format_err!("error signing ticket: {}", err))?;
+
+        // See `Self::write_data` for why this is safe
+        let mut output = unsafe { String::from_utf8_unchecked(output) };
+
+        let signature = signer
+            .sign_to_vec()
+            .map_err(|err| format_err!("error finishing ticket signature: {}", err))?;
+
+        use std::fmt::Write;
+        write!(
+            &mut output,
+            "::{}",
+            base64::encode_config(&signature, base64::STANDARD_NO_PAD),
+        )?;
+
+        self.signature = Some(signature);
+
+        Ok(output)
+    }
+
+    /// `verify` with an additional time frame parameter, not usually required since we always use
+    /// the same time frame.
+    pub fn verify_with_time_frame<P: HasPublic>(
+        &self,
+        keypair: &PKey<P>,
+        prefix: &str,
+        aad: Option<&str>,
+        time_frame: std::ops::Range<i64>,
+    ) -> Result<T, Error> {
+        if self.prefix != prefix {
+            bail!("ticket with invalid prefix");
+        }
+
+        let signature = match self.signature.as_ref() {
+            Some(sig) => sig,
+            None => bail!("invalid ticket without signature"),
+        };
+
+        let age = proxmox_time::epoch_i64() - self.time;
+        if age < time_frame.start {
+            bail!("invalid ticket - timestamp newer than expected");
+        }
+        if age > time_frame.end {
+            bail!("invalid ticket - expired");
+        }
+
+        let mut verifier = Verifier::new(MessageDigest::sha256(), keypair)?;
+
+        self.write_data(&mut verifier)
+            .and_then(|()| Self::write_aad(&mut verifier, aad))
+            .map_err(|err| format_err!("error verifying ticket: {}", err))?;
+
+        let is_valid: bool = verifier
+            .verify(signature)
+            .map_err(|err| format_err!("openssl error verifying ticket: {}", err))?;
+
+        if !is_valid {
+            bail!("ticket with invalid signature");
+        }
+
+        self.data
+            .parse()
+            .map_err(|err| format_err!("failed to parse contained ticket data: {:?}", err))
+    }
+
+    /// Verify the ticket with the provided key pair. The additional authentication data needs to
+    /// match the one used when generating the ticket, and the ticket's age must fall into the time
+    /// frame.
+    pub fn verify<P: HasPublic>(
+        &self,
+        keypair: &PKey<P>,
+        prefix: &str,
+        aad: Option<&str>,
+    ) -> Result<T, Error> {
+        self.verify_with_time_frame(keypair, prefix, aad, -300..TICKET_LIFETIME)
+    }
+
+    /// Parse a ticket string.
+    pub fn parse(ticket: &str) -> Result<Self, Error> {
+        let mut parts = ticket.splitn(4, ':');
+
+        let prefix = percent_decode_str(
+            parts
+                .next()
+                .ok_or_else(|| format_err!("ticket without prefix"))?,
+        )
+        .decode_utf8()
+        .map_err(|err| format_err!("invalid ticket, error decoding prefix: {}", err))?;
+
+        let data = percent_decode_str(
+            parts
+                .next()
+                .ok_or_else(|| format_err!("ticket without data"))?,
+        )
+        .decode_utf8()
+        .map_err(|err| format_err!("invalid ticket, error decoding data: {}", err))?;
+
+        let time = i64::from_str_radix(
+            parts
+                .next()
+                .ok_or_else(|| format_err!("ticket without timestamp"))?,
+            16,
+        )
+        .map_err(|err| format_err!("ticket with bad timestamp: {}", err))?;
+
+        let remainder = parts
+            .next()
+            .ok_or_else(|| format_err!("ticket without signature"))?;
+        // <prefix>:<data>:<time>::signature - the 4th `.next()` swallows the first colon in the
+        // double-colon!
+        if !remainder.starts_with(':') {
+            bail!("ticket without signature separator");
+        }
+        let signature = base64::decode_config(&remainder[1..], base64::STANDARD_NO_PAD)
+            .map_err(|err| format_err!("ticket with bad signature: {}", err))?;
+
+        Ok(Self {
+            prefix: Cow::Owned(prefix.into_owned()),
+            data: data.into_owned(),
+            time,
+            signature: Some(signature),
+            _type_marker: PhantomData,
+        })
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use std::convert::Infallible;
+    use std::fmt;
+
+    use openssl::pkey::{PKey, Private};
+
+    use super::Ticket;
+
+    #[derive(Debug, Eq, PartialEq)]
+    struct Testid(String);
+
+    impl std::str::FromStr for Testid {
+        type Err = Infallible;
+
+        fn from_str(s: &str) -> Result<Self, Infallible> {
+            Ok(Self(s.to_string()))
+        }
+    }
+
+    impl fmt::Display for Testid {
+        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+            write!(f, "{}", self.0)
+        }
+    }
+
+    fn simple_test<F>(key: &PKey<Private>, aad: Option<&str>, modify: F)
+    where
+        F: FnOnce(&mut Ticket<Testid>) -> bool,
+    {
+        let userid = Testid("root".to_string());
+
+        let mut ticket = Ticket::new("PREFIX", &userid).expect("failed to create Ticket struct");
+        let should_work = modify(&mut ticket);
+        let ticket = ticket.sign(key, aad).expect("failed to sign test ticket");
+
+        let parsed =
+            Ticket::<Testid>::parse(&ticket).expect("failed to parse generated test ticket");
+        if should_work {
+            let check: Testid = parsed
+                .verify(key, "PREFIX", aad)
+                .expect("failed to verify test ticket");
+
+            assert_eq!(userid, check);
+        } else {
+            parsed
+                .verify(key, "PREFIX", aad)
+                .expect_err("failed to verify test ticket");
+        }
+    }
+
+    #[test]
+    fn test_tickets() {
+        // first we need keys, for testing we use small keys for speed...
+        let rsa =
+            openssl::rsa::Rsa::generate(1024).expect("failed to generate RSA key for testing");
+        let key = openssl::pkey::PKey::<openssl::pkey::Private>::from_rsa(rsa)
+            .expect("failed to create PKey for RSA key");
+
+        simple_test(&key, Some("secret aad data"), |_| true);
+        simple_test(&key, None, |_| true);
+        simple_test(&key, None, |t| {
+            t.change_time(0);
+            false
+        });
+        simple_test(&key, None, |t| {
+            t.change_time(proxmox_time::epoch_i64() + 0x1000_0000);
+            false
+        });
+    }
+}
index 45467a85a42680932a58c010acec9e7781626b2c..611327344450b16a253db50d267e494080262233 100644 (file)
@@ -22,7 +22,6 @@ log.workspace = true
 nix.workspace = true
 nom.workspace = true
 openssl.workspace = true
-percent-encoding.workspace = true
 regex.workspace = true
 serde_json.workspace = true
 # rt-multi-thread is required for block_in_place
index aded6a01b3fa44fc783c63b6657b647d100e592a..bee5c1c0bfb92675d6f347203250ec70f5ba8572 100644 (file)
@@ -5,7 +5,6 @@ pub mod json;
 pub mod lru_cache;
 pub mod nom;
 pub mod sha;
-pub mod ticket;
 
 pub mod async_lru_cache;
 
diff --git a/pbs-tools/src/ticket.rs b/pbs-tools/src/ticket.rs
deleted file mode 100644 (file)
index fcb88ff..0000000
+++ /dev/null
@@ -1,332 +0,0 @@
-//! Generate and verify Authentication tickets
-
-use std::borrow::Cow;
-use std::io;
-use std::marker::PhantomData;
-
-use anyhow::{bail, format_err, Error};
-use openssl::hash::MessageDigest;
-use openssl::pkey::{HasPublic, PKey, Private};
-use openssl::sign::{Signer, Verifier};
-use percent_encoding::{percent_decode_str, percent_encode, AsciiSet};
-
-pub const TICKET_LIFETIME: i64 = 3600 * 2; // 2 hours
-
-pub const TERM_PREFIX: &str = "PBSTERM";
-
-/// Stringified ticket data must not contain colons...
-const TICKET_ASCIISET: &AsciiSet = &percent_encoding::CONTROLS.add(b':');
-
-/// An empty type implementing [`ToString`] and [`FromStr`](std::str::FromStr), used for tickets
-/// with no data.
-pub struct Empty;
-
-impl ToString for Empty {
-    fn to_string(&self) -> String {
-        String::new()
-    }
-}
-
-impl std::str::FromStr for Empty {
-    type Err = Error;
-
-    fn from_str(s: &str) -> Result<Self, Error> {
-        if !s.is_empty() {
-            bail!("unexpected ticket data, should be empty");
-        }
-        Ok(Empty)
-    }
-}
-
-/// An API ticket consists of a ticket type (prefix), type-dependent data, optional additional
-/// authenticaztion data, a timestamp and a signature. We store these values in the form
-/// `<prefix>:<stringified data>:<timestamp>::<signature>`.
-///
-/// The signature is made over the string consisting of prefix, data, timestamp and aad joined
-/// together by colons. If there is no additional authentication data it will be skipped together
-/// with the colon separating it from the timestamp.
-pub struct Ticket<T>
-where
-    T: ToString + std::str::FromStr,
-{
-    prefix: Cow<'static, str>,
-    data: String,
-    time: i64,
-    signature: Option<Vec<u8>>,
-    _type_marker: PhantomData<fn() -> T>,
-}
-
-impl<T> Ticket<T>
-where
-    T: ToString + std::str::FromStr,
-    <T as std::str::FromStr>::Err: std::fmt::Debug,
-{
-    /// Prepare a new ticket for signing.
-    pub fn new(prefix: &'static str, data: &T) -> Result<Self, Error> {
-        Ok(Self {
-            prefix: Cow::Borrowed(prefix),
-            data: data.to_string(),
-            time: proxmox_time::epoch_i64(),
-            signature: None,
-            _type_marker: PhantomData,
-        })
-    }
-
-    /// Get the ticket prefix.
-    pub fn prefix(&self) -> &str {
-        &self.prefix
-    }
-
-    /// Get the ticket's time stamp in seconds since the unix epoch.
-    pub fn time(&self) -> i64 {
-        self.time
-    }
-
-    /// Get the raw string data contained in the ticket. The `verify` method will call `parse()`
-    /// this in the end, so using this method directly is discouraged as it does not verify the
-    /// signature.
-    pub fn raw_data(&self) -> &str {
-        &self.data
-    }
-
-    /// Serialize the ticket into a writer.
-    ///
-    /// This only writes a string. We use `io::write` instead of `fmt::Write` so we can reuse the
-    /// same function for openssl's `Verify`, which only implements `io::Write`.
-    fn write_data(&self, f: &mut dyn io::Write) -> Result<(), Error> {
-        write!(
-            f,
-            "{}:{}:{:08X}",
-            percent_encode(self.prefix.as_bytes(), TICKET_ASCIISET),
-            percent_encode(self.data.as_bytes(), TICKET_ASCIISET),
-            self.time,
-        )
-        .map_err(Error::from)
-    }
-
-    /// Write additional authentication data to the verifier.
-    fn write_aad(f: &mut dyn io::Write, aad: Option<&str>) -> Result<(), Error> {
-        if let Some(aad) = aad {
-            write!(f, ":{}", percent_encode(aad.as_bytes(), TICKET_ASCIISET))?;
-        }
-        Ok(())
-    }
-
-    /// Change the ticket's time, used mostly for testing.
-    #[cfg(test)]
-    fn change_time(&mut self, time: i64) -> &mut Self {
-        self.time = time;
-        self
-    }
-
-    /// Sign the ticket.
-    pub fn sign(&mut self, keypair: &PKey<Private>, aad: Option<&str>) -> Result<String, Error> {
-        let mut output = Vec::<u8>::new();
-        let mut signer = Signer::new(MessageDigest::sha256(), keypair)
-            .map_err(|err| format_err!("openssl error creating signer for ticket: {}", err))?;
-
-        self.write_data(&mut output)
-            .map_err(|err| format_err!("error creating ticket: {}", err))?;
-
-        signer
-            .update(&output)
-            .map_err(Error::from)
-            .and_then(|()| Self::write_aad(&mut signer, aad))
-            .map_err(|err| format_err!("error signing ticket: {}", err))?;
-
-        // See `Self::write_data` for why this is safe
-        let mut output = unsafe { String::from_utf8_unchecked(output) };
-
-        let signature = signer
-            .sign_to_vec()
-            .map_err(|err| format_err!("error finishing ticket signature: {}", err))?;
-
-        use std::fmt::Write;
-        write!(
-            &mut output,
-            "::{}",
-            base64::encode_config(&signature, base64::STANDARD_NO_PAD),
-        )?;
-
-        self.signature = Some(signature);
-
-        Ok(output)
-    }
-
-    /// `verify` with an additional time frame parameter, not usually required since we always use
-    /// the same time frame.
-    pub fn verify_with_time_frame<P: HasPublic>(
-        &self,
-        keypair: &PKey<P>,
-        prefix: &str,
-        aad: Option<&str>,
-        time_frame: std::ops::Range<i64>,
-    ) -> Result<T, Error> {
-        if self.prefix != prefix {
-            bail!("ticket with invalid prefix");
-        }
-
-        let signature = match self.signature.as_ref() {
-            Some(sig) => sig,
-            None => bail!("invalid ticket without signature"),
-        };
-
-        let age = proxmox_time::epoch_i64() - self.time;
-        if age < time_frame.start {
-            bail!("invalid ticket - timestamp newer than expected");
-        }
-        if age > time_frame.end {
-            bail!("invalid ticket - expired");
-        }
-
-        let mut verifier = Verifier::new(MessageDigest::sha256(), keypair)?;
-
-        self.write_data(&mut verifier)
-            .and_then(|()| Self::write_aad(&mut verifier, aad))
-            .map_err(|err| format_err!("error verifying ticket: {}", err))?;
-
-        let is_valid: bool = verifier
-            .verify(signature)
-            .map_err(|err| format_err!("openssl error verifying ticket: {}", err))?;
-
-        if !is_valid {
-            bail!("ticket with invalid signature");
-        }
-
-        self.data
-            .parse()
-            .map_err(|err| format_err!("failed to parse contained ticket data: {:?}", err))
-    }
-
-    /// Verify the ticket with the provided key pair. The additional authentication data needs to
-    /// match the one used when generating the ticket, and the ticket's age must fall into the time
-    /// frame.
-    pub fn verify<P: HasPublic>(
-        &self,
-        keypair: &PKey<P>,
-        prefix: &str,
-        aad: Option<&str>,
-    ) -> Result<T, Error> {
-        self.verify_with_time_frame(keypair, prefix, aad, -300..TICKET_LIFETIME)
-    }
-
-    /// Parse a ticket string.
-    pub fn parse(ticket: &str) -> Result<Self, Error> {
-        let mut parts = ticket.splitn(4, ':');
-
-        let prefix = percent_decode_str(
-            parts
-                .next()
-                .ok_or_else(|| format_err!("ticket without prefix"))?,
-        )
-        .decode_utf8()
-        .map_err(|err| format_err!("invalid ticket, error decoding prefix: {}", err))?;
-
-        let data = percent_decode_str(
-            parts
-                .next()
-                .ok_or_else(|| format_err!("ticket without data"))?,
-        )
-        .decode_utf8()
-        .map_err(|err| format_err!("invalid ticket, error decoding data: {}", err))?;
-
-        let time = i64::from_str_radix(
-            parts
-                .next()
-                .ok_or_else(|| format_err!("ticket without timestamp"))?,
-            16,
-        )
-        .map_err(|err| format_err!("ticket with bad timestamp: {}", err))?;
-
-        let remainder = parts
-            .next()
-            .ok_or_else(|| format_err!("ticket without signature"))?;
-        // <prefix>:<data>:<time>::signature - the 4th `.next()` swallows the first colon in the
-        // double-colon!
-        if !remainder.starts_with(':') {
-            bail!("ticket without signature separator");
-        }
-        let signature = base64::decode_config(&remainder[1..], base64::STANDARD_NO_PAD)
-            .map_err(|err| format_err!("ticket with bad signature: {}", err))?;
-
-        Ok(Self {
-            prefix: Cow::Owned(prefix.into_owned()),
-            data: data.into_owned(),
-            time,
-            signature: Some(signature),
-            _type_marker: PhantomData,
-        })
-    }
-}
-
-#[cfg(test)]
-mod test {
-    use std::convert::Infallible;
-    use std::fmt;
-
-    use openssl::pkey::{PKey, Private};
-
-    use super::Ticket;
-
-    #[derive(Debug, Eq, PartialEq)]
-    struct Testid(String);
-
-    impl std::str::FromStr for Testid {
-        type Err = Infallible;
-
-        fn from_str(s: &str) -> Result<Self, Infallible> {
-            Ok(Self(s.to_string()))
-        }
-    }
-
-    impl fmt::Display for Testid {
-        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-            write!(f, "{}", self.0)
-        }
-    }
-
-    fn simple_test<F>(key: &PKey<Private>, aad: Option<&str>, modify: F)
-    where
-        F: FnOnce(&mut Ticket<Testid>) -> bool,
-    {
-        let userid = Testid("root".to_string());
-
-        let mut ticket = Ticket::new("PREFIX", &userid).expect("failed to create Ticket struct");
-        let should_work = modify(&mut ticket);
-        let ticket = ticket.sign(key, aad).expect("failed to sign test ticket");
-
-        let parsed =
-            Ticket::<Testid>::parse(&ticket).expect("failed to parse generated test ticket");
-        if should_work {
-            let check: Testid = parsed
-                .verify(key, "PREFIX", aad)
-                .expect("failed to verify test ticket");
-
-            assert_eq!(userid, check);
-        } else {
-            parsed
-                .verify(key, "PREFIX", aad)
-                .expect_err("failed to verify test ticket");
-        }
-    }
-
-    #[test]
-    fn test_tickets() {
-        // first we need keys, for testing we use small keys for speed...
-        let rsa =
-            openssl::rsa::Rsa::generate(1024).expect("failed to generate RSA key for testing");
-        let key = openssl::pkey::PKey::<openssl::pkey::Private>::from_rsa(rsa)
-            .expect("failed to create PKey for RSA key");
-
-        simple_test(&key, Some("secret aad data"), |_| true);
-        simple_test(&key, None, |_| true);
-        simple_test(&key, None, |t| {
-            t.change_time(0);
-            false
-        });
-        simple_test(&key, None, |t| {
-            t.change_time(proxmox_time::epoch_i64() + 0x1000_0000);
-            false
-        });
-    }
-}
index 017362695502e23f800be9f2211f52c4ce0e2ebb..9274b782699ff543bf530dd593b780f4826f5554 100644 (file)
@@ -18,7 +18,7 @@ use pbs_api_types::{
 };
 use pbs_config::acl::AclTreeNode;
 use pbs_config::CachedUserInfo;
-use pbs_tools::ticket::{self, Empty, Ticket};
+use pbs_ticket::{Empty, Ticket};
 
 use crate::auth_helpers::*;
 use crate::config::tfa::TfaChallenge;
@@ -84,7 +84,7 @@ fn authenticate_user(
         if let Ok(Empty) = Ticket::parse(password).and_then(|ticket| {
             ticket.verify(
                 public_auth_key(),
-                ticket::TERM_PREFIX,
+                pbs_ticket::TERM_PREFIX,
                 Some(&crate::tools::ticket::term_aad(userid, &path, port)),
             )
         }) {
index c6d59de01826540353e7099bc36451f21c4b8c2d..095726fd171e8dc7394ef9224f5fd106122cf012 100644 (file)
@@ -15,7 +15,7 @@ use pbs_api_types::{
     OPENID_DEFAILT_SCOPE_LIST, REALM_ID_SCHEMA,
 };
 use pbs_buildcfg::PROXMOX_BACKUP_RUN_DIR_M;
-use pbs_tools::ticket::Ticket;
+use pbs_ticket::Ticket;
 
 use pbs_config::open_backup_lockfile;
 use pbs_config::CachedUserInfo;
index 5859567e27a8816045230f4eef0a232a3c162d5f..763e6ea9ea901a9675de5b5775069242472e550c 100644 (file)
@@ -25,7 +25,7 @@ use proxmox_schema::*;
 use proxmox_rest_server::WorkerTask;
 
 use pbs_api_types::{Authid, NODE_SCHEMA, PRIV_SYS_CONSOLE};
-use pbs_tools::ticket::{self, Empty, Ticket};
+use pbs_ticket::{Empty, Ticket};
 
 use crate::auth_helpers::private_auth_key;
 use crate::tools;
@@ -119,7 +119,7 @@ async fn termproxy(cmd: Option<String>, rpcenv: &mut dyn RpcEnvironment) -> Resu
     let listener = TcpListener::bind("localhost:0")?;
     let port = listener.local_addr()?.port();
 
-    let ticket = Ticket::new(ticket::TERM_PREFIX, &Empty)?.sign(
+    let ticket = Ticket::new(pbs_ticket::TERM_PREFIX, &Empty)?.sign(
         private_auth_key(),
         Some(&tools::ticket::term_aad(userid, path, port)),
     )?;
@@ -292,7 +292,7 @@ fn upgrade_to_websocket(
         // will be checked again by termproxy
         Ticket::<Empty>::parse(ticket)?.verify(
             crate::auth_helpers::public_auth_key(),
-            ticket::TERM_PREFIX,
+            pbs_ticket::TERM_PREFIX,
             Some(&tools::ticket::term_aad(userid, "/system", port)),
         )?;
 
index 18a4b4117b7679c5e1b0bd13b2f1e3ed55b91c39..4dc7f052981aa84c1a6689a05ee4870a88a3f2b4 100644 (file)
@@ -2,7 +2,7 @@ use anyhow::Error;
 
 use pbs_api_types::{Authid, Userid};
 use pbs_client::{HttpClient, HttpClientOptions};
-use pbs_tools::ticket::Ticket;
+use pbs_ticket::Ticket;
 
 use crate::auth_helpers::private_auth_key;
 
index 04bc4185a3e3af0f16d5b46f27fd2d9a9385ec6f..e9ed9585174c15d744338078d2e5008194574512 100644 (file)
@@ -6,7 +6,7 @@ use proxmox_router::UserInformation;
 
 use pbs_api_types::{Authid, Userid};
 use pbs_config::{token_shadow, CachedUserInfo};
-use pbs_tools::ticket::{self, Ticket};
+use pbs_ticket::Ticket;
 use proxmox_rest_server::{extract_cookie, AuthError};
 
 use crate::auth_helpers::*;
@@ -61,7 +61,7 @@ pub async fn check_pbs_auth(
     match auth_data {
         Some(AuthData::User(user_auth_data)) => {
             let ticket = user_auth_data.ticket.clone();
-            let ticket_lifetime = ticket::TICKET_LIFETIME;
+            let ticket_lifetime = pbs_ticket::TICKET_LIFETIME;
 
             let userid: Userid = Ticket::<super::ticket::ApiTicket>::parse(&ticket)?
                 .verify_with_time_frame(public_auth_key(), "PBS", None, -300..ticket_lifetime)?