Struct sequoia_openpgp::packet::UserID

source ·
pub struct UserID { /* private fields */ }
Expand description

Holds a UserID packet.

The standard imposes no structure on UserIDs, but suggests to follow RFC 2822. See Section 5.11 of RFC 4880 for details. In practice though, implementations do not follow RFC 2822, or do not even help their users in producing well-formed User IDs. Experience has shown that parsing User IDs using RFC 2822 does not work, so we are taking a more pragmatic approach and define what we call Conventional User IDs.

Using this definition, we provide methods to extract the name, comment, email address, or URI from UserID packets. Furthermore, we provide a way to canonicalize the email address found in a UserID packet. We provide two constructors that create well-formed User IDs from email address, and optional name and comment.

§Conventional User IDs

Informally, conventional User IDs are of the form:

  • First Last (Comment) <name@example.org>

  • First Last <name@example.org>

  • First Last

  • name@example.org <name@example.org>

  • <name@example.org>

  • name@example.org

  • Name (Comment) <scheme://hostname/path>

  • Name (Comment) <mailto:user@example.org>

  • Name <scheme://hostname/path>

  • <scheme://hostname/path>

  • scheme://hostname/path

Names consist of UTF-8 non-control characters and may include punctuation. For instance, the following names are valid:

  • Acme Industries, Inc.
  • Michael O'Brian
  • Smith, John
  • e.e. cummings

(Note: according to RFC 2822 and its successors, all of these would need to be quoted. Conventionally, no implementation quotes names.)

Conventional User IDs are UTF-8. RFC 2822 only covers US-ASCII and allows character set switching using RFC 2047. For example, an RFC 2822 parser would parse:

  • Bj=?utf-8?q?=C3=B6?=rn Bj=?utf-8?q?=C3=B6?=rnson

“Björn Björnson”. Nobody uses this in practice, and, as such, this extension is not supported by this parser.

Comments can include any UTF-8 text except parentheses. Thus, the following is not a valid comment even though the parentheses are balanced:

  • (foo (bar))

§URIs

The URI parser recognizes URIs using a regular expression similar to the one recommended in RFC 3986 with the following extensions and restrictions:

  • UTF-8 characters are in the range \u{80}-\u{10ffff} are allowed wherever percent-encoded characters are allowed (i.e., everywhere but the schema).

  • The scheme component and its trailing : are required.

  • The URI must have an authority component (//domain) or a path component (/path/to/resource).

  • Although the RFC does not allow it, in practice, the [ and ] characters are allowed wherever percent-encoded characters are allowed (i.e., everywhere but the schema).

URIs are neither normalized nor interpreted. For instance, dot segments are not removed, escape sequences are not decoded, etc.

Note: the recommended regular expression is less strict than the grammar. For instance, a percent encoded character must consist of three characters: the percent character followed by two hex digits. The parser that we use does not enforce this either.

§Formal Grammar

Formally, the following grammar is used to decompose a User ID:

  WS                 = 0x20 (space character)

  comment-specials   = "<" / ">" /   ; RFC 2822 specials - "(" and ")"
                       "[" / "]" /
                       ":" / ";" /
                       "@" / "\" /
                       "," / "." /
                       DQUOTE

  atext-specials     = "(" / ")" /   ; RFC 2822 specials - "<" and ">".
                       "[" / "]" /
                       ":" / ";" /
                       "@" / "\" /
                       "," / "." /
                       DQUOTE

  atext              = ALPHA / DIGIT /   ; Any character except controls,
                       "!" / "#" /       ;  SP, and specials.
                       "$" / "%" /       ;  Used for atoms
                       "&" / "'" /
                       "*" / "+" /
                       "-" / "/" /
                       "=" / "?" /
                       "^" / "_" /
                       "`" / "{" /
                       "|" / "}" /
                       "~" /
                       \u{80}-\u{10ffff} ; Non-ascii, non-control UTF-8

  dot_atom_text      = 1*atext *("." *atext)

  name-char-start    = atext / atext-specials

  name-char-rest     = atext / atext-specials / WS

  name               = name-char-start *name-char-rest

  comment-char       = atext / comment-specials / WS

  comment-content    = *comment-char

  comment            = "(" *WS comment-content *WS ")"

  addr-spec          = dot-atom-text "@" dot-atom-text

  uri                = See [RFC 3986] and the note on URIs above.

  pgp-uid-convention = addr-spec /
                       uri /
                       *WS [name] *WS [comment] *WS "<" addr-spec ">" /
                       *WS [name] *WS [comment] *WS "<" uri ">" /
                       *WS name *WS [comment] *WS

Implementations§

source§

impl UserID

source

pub const fn from_static_bytes(u: &'static [u8]) -> Self

Returns a User ID.

This is equivalent to using UserID::from, but the function is constant, and the slice must have a static lifetime.

§Examples
use sequoia_openpgp::packet::UserID;

const TRUST_ROOT_USERID: UserID
    = UserID::from_static_bytes(b"Local Trust Root");
source§

impl UserID

source

pub fn hash_algo_security(&self) -> HashAlgoSecurity

The security requirements of the hash algorithm for self-signatures.

A cryptographic hash algorithm usually has three security properties: pre-image resistance, second pre-image resistance, and collision resistance. If an attacker can influence the signed data, then the hash algorithm needs to have both second pre-image resistance, and collision resistance. If not, second pre-image resistance is sufficient.

In general, an attacker may be able to influence third-party signatures. But direct key signatures, and binding signatures are only over data fully determined by signer. And, an attacker’s control over self signatures over User IDs is limited due to their structure.

In the case of self signatures over User IDs, an attacker may be able to control the content of the User ID packet. However, unlike an image, there is no easy way to hide large amounts of arbitrary data (e.g., the 512 bytes needed by the SHA-1 is a Shambles attack) from the user. Further, normal User IDs are short and encoded using UTF-8.

These observations can be used to extend the life of a hash algorithm after its collision resistance has been partially compromised, but not completely broken. Specifically for the case of User IDs, we relax the requirement for strong collision resistance for self signatures over User IDs if:

  • The User ID is at most 96 bytes long,
  • It contains valid UTF-8, and
  • It doesn’t contain a UTF-8 control character (this includes the NUL byte).

For more details, please refer to the documentation for HashAlgoSecurity.

source

pub fn from_address<O, S>(name: O, comment: O, email: S) -> Result<Self>
where S: AsRef<str>, O: Into<Option<S>>,

Constructs a User ID.

This does a basic check and any necessary escaping to form a conventional User ID.

Only the address is required. If a comment is supplied, then a name is also required.

If you already have a User ID value, then you can just use UserID::from().

assert_eq!(UserID::from_address(
               "John Smith".into(),
               None,
               "boat@example.org")?.value(),
           &b"John Smith <boat@example.org>"[..]);

assert_eq!(UserID::from_address(
               "John Smith",
               "Who is Advok?",
               "boat@example.org")?.value(),
           &b"John Smith (Who is Advok?) <boat@example.org>"[..]);
source

pub fn from_unchecked_address<O, S>( name: O, comment: O, address: S, ) -> Result<Self>
where S: AsRef<str>, O: Into<Option<S>>,

Constructs a User ID.

This does a basic check and any necessary escaping to form a conventional User ID modulo the address, which is not checked.

This is useful when you want to specify a URI instead of an email address.

If you already have a User ID value, then you can just use UserID::from().

assert_eq!(UserID::from_unchecked_address(
               "NAS".into(),
               None, "ssh://host.example.org")?.value(),
           &b"NAS <ssh://host.example.org>"[..]);
source

pub fn value(&self) -> &[u8]

Gets the user ID packet’s value.

This returns the raw, uninterpreted value. See UserID::name, UserID::email, UserID::email_normalized, UserID::uri, and UserID::comment for how to extract parts of conventional User IDs.

source

pub fn name2(&self) -> Result<Option<&str>>

Parses the User ID according to de facto conventions, and returns the name component, if any.

See conventional User ID for more information.

source

pub fn name(&self) -> Result<Option<String>>

👎Deprecated: Use UserID::name2

Parses the User ID according to de facto conventions, and returns the name component, if any.

Like UserID::name2, but heap-allocates.

source

pub fn comment2(&self) -> Result<Option<&str>>

Parses the User ID according to de facto conventions, and returns the comment field, if any.

See conventional User ID for more information.

source

pub fn comment(&self) -> Result<Option<String>>

👎Deprecated: Use UserID::comment2

Parses the User ID according to de facto conventions, and returns the comment field, if any.

Like UserID::comment2, but heap-allocates.

source

pub fn email2(&self) -> Result<Option<&str>>

Parses the User ID according to de facto conventions, and returns the email address, if any.

See conventional User ID for more information.

source

pub fn email(&self) -> Result<Option<String>>

👎Deprecated: Use UserID::email2

Parses the User ID according to de facto conventions, and returns the email address, if any.

Like UserID::email2, but heap-allocates.

source

pub fn uri2(&self) -> Result<Option<&str>>

Parses the User ID according to de facto conventions, and returns the URI, if any.

See conventional User ID for more information.

source

pub fn uri(&self) -> Result<Option<String>>

👎Deprecated: Use UserID::uri2

Parses the User ID according to de facto conventions, and returns the URI, if any.

Like UserID::uri2, but heap-allocates.

source

pub fn email_normalized(&self) -> Result<Option<String>>

Returns a normalized version of the UserID’s email address.

Normalized email addresses are primarily needed when email addresses are compared.

Note: normalized email addresses are still valid email addresses.

This function normalizes an email address by doing puny-code normalization on the domain, and lowercasing the local part in the so-called empty locale.

Note: this normalization procedure is the same as the normalization procedure recommended by Autocrypt.

source§

impl UserID

source

pub fn bind( &self, signer: &mut dyn Signer, cert: &Cert, signature: SignatureBuilder, ) -> Result<Signature>

Creates a binding signature.

The signature binds this User ID to cert. signer will be used to create a signature using signature as builder. Thehash_algo defaults to SHA512, creation_time to the current time.

This function adds a creation time subpacket, a issuer fingerprint subpacket, and a issuer subpacket to the signature.

§Examples

This example demonstrates how to bind this User ID to a Cert. Note that in general, the CertBuilder is a better way to add User IDs to a Cert.

// Generate a Cert, and create a keypair from the primary key.
let (cert, _) = CertBuilder::new().generate()?;
let mut keypair = cert.primary_key().key().clone()
    .parts_into_secret()?.into_keypair()?;
assert_eq!(cert.userids().len(), 0);

// Generate a User ID and a binding signature.
let userid = UserID::from("test@example.org");
let builder =
    signature::SignatureBuilder::new(SignatureType::PositiveCertification);
let binding = userid.bind(&mut keypair, &cert, builder)?;

// Now merge the User ID and binding signature into the Cert.
let cert = cert.insert_packets(vec![Packet::from(userid),
                                   binding.into()])?;

// Check that we have a User ID.
assert_eq!(cert.userids().len(), 1);
source

pub fn certify<S, H, T>( &self, signer: &mut dyn Signer, cert: &Cert, signature_type: S, hash_algo: H, creation_time: T, ) -> Result<Signature>

Returns a certification for the User ID.

The signature binds this User ID to cert. signer will be used to create a certification signature of type signature_type. signature_type defaults to SignatureType::GenericCertification, hash_algo to SHA512, creation_time to the current time.

This function adds a creation time subpacket, a issuer fingerprint subpacket, and a issuer subpacket to the signature.

§Errors

Returns Error::InvalidArgument if signature_type is not one of SignatureType::{Generic, Persona, Casual, Positive}Certification

§Examples

This example demonstrates how to certify a User ID.

// Generate a Cert, and create a keypair from the primary key.
let (alice, _) = CertBuilder::new()
    .set_primary_key_flags(KeyFlags::empty().set_certification())
    .add_userid("alice@example.org")
    .generate()?;
let mut keypair = alice.primary_key().key().clone()
    .parts_into_secret()?.into_keypair()?;

// Generate a Cert for Bob.
let (bob, _) = CertBuilder::new()
    .set_primary_key_flags(KeyFlags::empty().set_certification())
    .add_userid("bob@example.org")
    .generate()?;

// Alice now certifies the binding between `bob@example.org` and `bob`.
let certification =
    bob.userids().nth(0).unwrap()
    .certify(&mut keypair, &bob, SignatureType::PositiveCertification,
             None, None)?;

// `certification` can now be used, e.g. by merging it into `bob`.
let bob = bob.insert_packets(certification)?;

// Check that we have a certification on the User ID.
assert_eq!(bob.userids().nth(0).unwrap()
           .certifications().count(), 1);

Trait Implementations§

source§

impl Any<UserID> for Packet

source§

fn downcast(self) -> Result<UserID, Packet>

Attempts to downcast to T, returning the packet if it fails. Read more
source§

fn downcast_ref(&self) -> Option<&UserID>

Attempts to downcast to &T, returning None if it fails. Read more
source§

fn downcast_mut(&mut self) -> Option<&mut UserID>

Attempts to downcast to &mut T, returning None if it fails. Read more
source§

impl Clone for UserID

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for UserID

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for UserID

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl From<&[u8]> for UserID

source§

fn from(u: &[u8]) -> Self

Converts to this type from the input type.
source§

impl<'a> From<&'a str> for UserID

source§

fn from(u: &'a str) -> Self

Converts to this type from the input type.
source§

impl<'a> From<Cow<'a, str>> for UserID

source§

fn from(u: Cow<'a, str>) -> Self

Converts to this type from the input type.
source§

impl From<String> for UserID

source§

fn from(u: String) -> Self

Converts to this type from the input type.
source§

impl From<UserID> for Packet

source§

fn from(s: UserID) -> Self

Converts to this type from the input type.
source§

impl From<Vec<u8>> for UserID

source§

fn from(u: Vec<u8>) -> Self

Converts to this type from the input type.
source§

impl Hash for UserID

source§

fn hash(&self, hash: &mut dyn Digest)

Updates the given hash with this object.
source§

impl Hash for UserID

source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl IntoIterator for UserID

Implement IntoIterator so that cert::insert_packets(sig) just works.

§

type Item = UserID

The type of the elements being iterated over.
§

type IntoIter = Once<UserID>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl Marshal for UserID

source§

fn serialize(&self, o: &mut dyn Write) -> Result<()>

Writes a serialized version of the object to o.
source§

fn export(&self, o: &mut dyn Write) -> Result<()>

Exports a serialized version of the object to o. Read more
source§

impl MarshalInto for UserID

source§

fn serialized_len(&self) -> usize

Computes the maximal length of the serialized representation. Read more
source§

fn serialize_into(&self, buf: &mut [u8]) -> Result<usize>

Serializes into the given buffer. Read more
source§

fn to_vec(&self) -> Result<Vec<u8>>

Serializes the packet to a vector.
source§

fn export_into(&self, buf: &mut [u8]) -> Result<usize>

Exports into the given buffer. Read more
source§

fn export_to_vec(&self) -> Result<Vec<u8>>

Exports to a vector. Read more
source§

impl Ord for UserID

source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
source§

impl<'a> Parse<'a, UserID> for UserID

source§

fn from_buffered_reader<R>(reader: R) -> Result<Self>
where R: BufferedReader<Cookie> + 'a,

Reads from the given buffered reader.
source§

fn from_reader<R: 'a + Read + Send + Sync>(reader: R) -> Result<Self>

Reads from the given reader.
source§

fn from_bytes<D: AsRef<[u8]> + ?Sized + Send + Sync>( data: &'a D, ) -> Result<Self>

Reads from the given slice. Read more
source§

fn from_file<P: AsRef<Path>>(path: P) -> Result<T>

Reads from the given file. Read more
source§

impl PartialEq for UserID

source§

fn eq(&self, other: &UserID) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd for UserID

source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl Eq for UserID

Auto Trait Implementations§

§

impl !Freeze for UserID

§

impl RefUnwindSafe for UserID

§

impl Send for UserID

§

impl Sync for UserID

§

impl Unpin for UserID

§

impl UnwindSafe for UserID

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

default unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> DynClone for T
where T: Clone,

source§

fn __clone_box(&self, _: Private) -> *mut ()

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> ErasedDestructor for T
where T: 'static,

source§

impl<T> MaybeSendSync for T