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 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
use crate::Result;
use crate::cert::prelude::*;
use crate::packet::{header::BodyLength, key, Signature, Tag};
use crate::seal;
use crate::serialize::{
PacketRef,
Marshal, MarshalInto,
NetLength,
generic_serialize_into, generic_export_into,
};
impl Cert {
/// Serializes or exports the Cert.
///
/// If `export` is true, then non-exportable signatures are not
/// written, and components without any exportable binding
/// signature or revocation are not exported.
///
/// The signatures are ordered from authenticated and most
/// important to not authenticated and most likely to be abused.
/// The order is:
///
/// - Self revocations first. They are authenticated and the
/// most important information.
/// - Self signatures. They are authenticated.
/// - Other signatures. They are not authenticated at this point.
/// - Other revocations. They are not authenticated, and likely
/// not well supported in other implementations, hence the
/// least reliable way of revoking keys and therefore least
/// useful and most likely to be abused.
fn serialize_common(&self, o: &mut dyn std::io::Write, export: bool)
-> Result<()>
{
let primary = self.primary_key();
PacketRef::PublicKey(primary.key())
.serialize(o)?;
// Writes a signature if it is exportable or `! export`.
let serialize_sig =
|o: &mut dyn std::io::Write, sig: &Signature| -> Result<()>
{
if export {
if sig.exportable().is_ok() {
PacketRef::Signature(sig).export(o)?;
}
} else {
PacketRef::Signature(sig).serialize(o)?;
}
Ok(())
};
for s in primary.signatures() {
serialize_sig(o, s)?;
}
for u in self.userids() {
if export && ! u.self_signatures().chain(u.self_revocations()).any(
|s| s.exportable().is_ok())
{
// No exportable selfsig on this component, skip it.
continue;
}
PacketRef::UserID(u.userid()).serialize(o)?;
for s in u.signatures() {
serialize_sig(o, s)?;
}
}
for u in self.user_attributes() {
if export && ! u.self_signatures().chain(u.self_revocations()).any(
|s| s.exportable().is_ok())
{
// No exportable selfsig on this component, skip it.
continue;
}
PacketRef::UserAttribute(u.user_attribute()).serialize(o)?;
for s in u.signatures() {
serialize_sig(o, s)?;
}
}
for k in self.subkeys() {
if export && ! k.self_signatures().chain(k.self_revocations()).any(
|s| s.exportable().is_ok())
{
// No exportable selfsig on this component, skip it.
continue;
}
PacketRef::PublicSubkey(k.key()).serialize(o)?;
for s in k.signatures() {
serialize_sig(o, s)?;
}
}
for u in self.unknowns() {
if export && ! u.certifications().any(
|s| s.exportable().is_ok())
{
// No exportable selfsig on this component, skip it.
continue;
}
PacketRef::Unknown(u.unknown()).serialize(o)?;
for s in u.signatures() {
serialize_sig(o, s)?;
}
}
for s in self.bad_signatures() {
serialize_sig(o, s)?;
}
Ok(())
}
}
impl crate::serialize::Serialize for Cert {}
impl seal::Sealed for Cert {}
impl Marshal for Cert {
fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
self.serialize_common(o, false)
}
fn export(&self, o: &mut dyn std::io::Write) -> Result<()> {
self.serialize_common(o, true)
}
}
impl crate::serialize::SerializeInto for Cert {}
impl MarshalInto for Cert {
fn serialized_len(&self) -> usize {
let mut l = 0;
let primary = self.primary_key();
l += PacketRef::PublicKey(primary.key()).serialized_len();
for s in primary.signatures() {
l += PacketRef::Signature(s).serialized_len();
}
for u in self.userids() {
l += PacketRef::UserID(u.userid()).serialized_len();
for s in u.signatures() {
l += PacketRef::Signature(s).serialized_len();
}
}
for u in self.user_attributes() {
l += PacketRef::UserAttribute(u.user_attribute()).serialized_len();
for s in u.signatures() {
l += PacketRef::Signature(s).serialized_len();
}
}
for k in self.subkeys() {
l += PacketRef::PublicSubkey(k.key()).serialized_len();
for s in k.signatures() {
l += PacketRef::Signature(s).serialized_len();
}
}
for u in self.unknowns() {
l += PacketRef::Unknown(u.unknown()).serialized_len();
for s in u.signatures() {
l += PacketRef::Signature(s).serialized_len();
}
}
for s in self.bad_signatures() {
l += PacketRef::Signature(s).serialized_len();
}
l
}
fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
generic_serialize_into(self, self.serialized_len(), buf)
}
fn export_into(&self, buf: &mut [u8]) -> Result<usize> {
generic_export_into(self, self.serialized_len(), buf)
}
}
impl Cert {
/// Derive a [`TSK`] object from this key.
///
/// This object writes out secret keys during serialization.
///
/// [`TSK`]: crate::serialize::TSK
pub fn as_tsk(&self) -> TSK {
TSK::new(self)
}
}
/// A reference to a `Cert` that allows serialization of secret keys.
///
/// To avoid accidental leakage, secret keys are not serialized when a
/// serializing a [`Cert`]. To serialize [`Cert`]s with secret keys,
/// use [`Cert::as_tsk()`] to create a `TSK`, which is a shim on top
/// of the `Cert`, and serialize this.
///
/// [`Cert`]: crate::cert::Cert
/// [`Cert::as_tsk()`]: crate::cert::Cert::as_tsk()
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp::{*, cert::*, parse::Parse, serialize::Serialize};
/// # fn main() -> Result<()> {
/// let (cert, _) = CertBuilder::new().generate()?;
/// assert!(cert.is_tsk());
///
/// let mut buf = Vec::new();
/// cert.as_tsk().serialize(&mut buf)?;
///
/// let cert_ = Cert::from_bytes(&buf)?;
/// assert!(cert_.is_tsk());
/// assert_eq!(cert, cert_);
/// # Ok(()) }
/// ```
pub struct TSK<'a> {
pub(crate) cert: &'a Cert,
filter: Box<dyn Fn(&'a key::UnspecifiedSecret) -> bool + 'a>,
emit_stubs: bool,
}
impl PartialEq for TSK<'_> {
fn eq(&self, other: &Self) -> bool {
// First, compare the certs. If they are not equal, then the
// TSK's cannot possibly be equal.
if self.cert != other.cert {
return false;
}
// Second, consider all the keys.
for (a, b) in self.cert.keys()
.zip(other.cert.keys())
{
match (a.has_secret()
&& (self.filter)(a.key().parts_as_secret().expect("has secret")),
b.has_secret()
&& (other.filter)(b.key().parts_as_secret().expect("has_secret")))
{
// Both have secrets. Compare secrets.
(true, true) => if a.optional_secret() != b.optional_secret() {
return false;
},
// No secrets. Equal iff both or neither emit stubs.
(false, false) => if self.emit_stubs != other.emit_stubs {
return false;
},
// Otherwise, they differ.
_ => return false,
}
}
// Everything matched.
true
}
}
impl<'a> TSK<'a> {
/// Creates a new view for the given `Cert`.
fn new(cert: &'a Cert) -> Self {
Self {
cert,
filter: Box::new(|_| true),
emit_stubs: false,
}
}
/// Filters which secret keys to export using the given predicate.
///
/// Note that the given filter replaces any existing filter.
///
/// # Examples
///
/// This example demonstrates how to create a TSK with a detached
/// primary secret key.
///
/// ```
/// # use sequoia_openpgp::{*, cert::*, parse::Parse, serialize::Serialize};
/// use sequoia_openpgp::policy::StandardPolicy;
///
/// # fn main() -> Result<()> {
/// let p = &StandardPolicy::new();
///
/// let (cert, _) = CertBuilder::new().add_signing_subkey().generate()?;
/// assert_eq!(cert.keys().with_policy(p, None).alive().revoked(false).secret().count(), 2);
///
/// // Only write out the subkey's secret.
/// let mut buf = Vec::new();
/// cert.as_tsk()
/// .set_filter(|k| k.fingerprint() != cert.fingerprint())
/// .serialize(&mut buf)?;
///
/// let cert_ = Cert::from_bytes(&buf)?;
/// assert!(! cert_.primary_key().has_secret());
/// assert_eq!(cert_.keys().with_policy(p, None).alive().revoked(false).secret().count(), 1);
/// # Ok(()) }
/// ```
pub fn set_filter<P>(mut self, predicate: P) -> Self
where P: 'a + Fn(&'a key::UnspecifiedSecret) -> bool
{
self.filter = Box::new(predicate);
self
}
/// Changes `TSK` to emit secret key stubs.
///
/// If [`TSK::set_filter`] is used to selectively export secret
/// keys, or if the cert contains both keys without secret key
/// material and with secret key material, then are two ways to
/// serialize this cert. Neither is sanctioned by the OpenPGP
/// standard.
///
/// The default way is to simply emit public key packets when no
/// secret key material is available. While straight forward,
/// this may be in violation of [Section 11.2 of RFC 4880].
///
/// The alternative is to emit a secret key packet with a
/// placeholder secret key value. GnuPG uses this variant with a
/// private [`S2K`] format. If interoperability with GnuPG is a
/// concern, use this variant.
///
/// See [this test] for support in other implementations.
///
/// [`TSK::set_filter`]: TSK::set_filter()
/// [Section 11.2 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-11.2
/// [`S2K`]: super::crypto::S2K
/// [this test]: https://tests.sequoia-pgp.org/#Detached_primary_key
///
/// # Examples
///
/// This example demonstrates how to create a TSK with a detached
/// primary secret key, serializing it using secret key stubs.
///
/// ```
/// # fn main() -> sequoia_openpgp::Result<()> {
/// # use std::convert::TryFrom;
/// use sequoia_openpgp as openpgp;
/// use openpgp::packet::key::*;
/// # use openpgp::{types::*, crypto::S2K};
/// # use openpgp::{*, cert::*, parse::Parse, serialize::Serialize};
///
/// let p = &openpgp::policy::StandardPolicy::new();
///
/// let (cert, _) = CertBuilder::new().add_signing_subkey().generate()?;
/// assert_eq!(cert.keys().with_policy(p, None)
/// .alive().revoked(false).unencrypted_secret().count(), 2);
///
/// // Only write out the subkey's secret, the primary key is "detached".
/// let mut buf = Vec::new();
/// cert.as_tsk()
/// .set_filter(|k| k.fingerprint() != cert.fingerprint())
/// .emit_secret_key_stubs(true)
/// .serialize(&mut buf)?;
///
/// # let pp = PacketPile::from_bytes(&buf)?;
/// # assert_eq!(pp.path_ref(&[0]).unwrap().kind(),
/// # Some(packet::Tag::SecretKey));
/// let cert_ = Cert::from_bytes(&buf)?;
/// // The primary key has an "encrypted" stub.
/// assert!(cert_.primary_key().has_secret());
/// assert_eq!(cert_.keys().with_policy(p, None)
/// .alive().revoked(false).unencrypted_secret().count(), 1);
/// # if let Some(SecretKeyMaterial::Encrypted(sec)) =
/// # cert_.primary_key().optional_secret()
/// # {
/// # assert_eq!(sec.algo(), SymmetricAlgorithm::Unencrypted);
/// # if let S2K::Private { tag, .. } = sec.s2k() {
/// # assert_eq!(*tag, 101);
/// # } else {
/// # panic!("expected proprietary S2K type");
/// # }
/// # } else {
/// # panic!("expected ''encrypted'' secret key stub");
/// # }
/// # Ok(()) }
/// ```
pub fn emit_secret_key_stubs(mut self, emit_stubs: bool) -> Self {
self.emit_stubs = emit_stubs;
self
}
/// Serializes or exports the Cert.
///
/// If `export` is true, then non-exportable signatures are not
/// written, and components without any exportable binding
/// signature or revocation are not exported.
fn serialize_common(&self, o: &mut dyn std::io::Write, export: bool)
-> Result<()>
{
// Writes a signature if it is exportable or `! export`.
let serialize_sig =
|o: &mut dyn std::io::Write, sig: &Signature| -> Result<()>
{
if export {
if sig.exportable().is_ok() {
PacketRef::Signature(sig).export(o)?;
}
} else {
PacketRef::Signature(sig).serialize(o)?;
}
Ok(())
};
// Serializes public or secret key depending on the filter.
let serialize_key =
|o: &mut dyn std::io::Write, key: &'a key::UnspecifiedSecret,
tag_public, tag_secret|
{
let tag = if key.has_secret() && (self.filter)(key) {
tag_secret
} else {
tag_public
};
if self.emit_stubs && (tag == Tag::PublicKey
|| tag == Tag::PublicSubkey) {
// Emit a GnuPG-style secret key stub.
let stub = crate::crypto::S2K::Private {
tag: 101,
parameters: Some(vec![
0, // "hash algo"
0x47, // 'G'
0x4e, // 'N'
0x55, // 'U'
1 // "mode"
].into()),
};
let key_with_stub = key.clone()
.add_secret(key::SecretKeyMaterial::Encrypted(
key::Encrypted::new(
stub, 0.into(),
// Mirrors more closely what GnuPG 2.1
// does (oddly, GnuPG 1.4 emits 0xfe
// here).
Some(crate::crypto::mpi::SecretKeyChecksum::Sum16),
vec![].into()))).0;
return match tag {
Tag::PublicKey =>
crate::Packet::SecretKey(key_with_stub.into())
.serialize(o),
Tag::PublicSubkey =>
crate::Packet::SecretSubkey(key_with_stub.into())
.serialize(o),
_ => unreachable!(),
};
}
match tag {
Tag::PublicKey =>
PacketRef::PublicKey(key.into()).serialize(o),
Tag::PublicSubkey =>
PacketRef::PublicSubkey(key.into()).serialize(o),
Tag::SecretKey =>
PacketRef::SecretKey(key.into()).serialize(o),
Tag::SecretSubkey =>
PacketRef::SecretSubkey(key.into()).serialize(o),
_ => unreachable!(),
}
};
let primary = self.cert.primary_key();
serialize_key(o, primary.key().into(),
Tag::PublicKey, Tag::SecretKey)?;
for s in primary.signatures() {
serialize_sig(o, s)?;
}
for u in self.cert.userids() {
if export && ! u.self_signatures().chain(u.self_revocations()).any(
|s| s.exportable().is_ok())
{
// No exportable selfsig on this component, skip it.
continue;
}
PacketRef::UserID(u.userid()).serialize(o)?;
for s in u.signatures() {
serialize_sig(o, s)?;
}
}
for u in self.cert.user_attributes() {
if export && ! u.self_signatures().chain(u.self_revocations()).any(
|s| s.exportable().is_ok())
{
// No exportable selfsig on this component, skip it.
continue;
}
PacketRef::UserAttribute(u.user_attribute()).serialize(o)?;
for s in u.signatures() {
serialize_sig(o, s)?;
}
}
for k in self.cert.subkeys() {
if export && ! k.self_signatures().chain(k.self_revocations()).any(
|s| s.exportable().is_ok())
{
// No exportable selfsig on this component, skip it.
continue;
}
serialize_key(o, k.key().into(),
Tag::PublicSubkey, Tag::SecretSubkey)?;
for s in k.signatures() {
serialize_sig(o, s)?;
}
}
for u in self.cert.unknowns() {
if export && ! u.certifications().any(
|s| s.exportable().is_ok())
{
// No exportable selfsig on this component, skip it.
continue;
}
PacketRef::Unknown(u.unknown()).serialize(o)?;
for s in u.signatures() {
serialize_sig(o, s)?;
}
}
for s in self.cert.bad_signatures() {
serialize_sig(o, s)?;
}
Ok(())
}
}
impl<'a> crate::serialize::Serialize for TSK<'a> {}
impl<'a> seal::Sealed for TSK<'a> {}
impl<'a> Marshal for TSK<'a> {
fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
self.serialize_common(o, false)
}
fn export(&self, o: &mut dyn std::io::Write) -> Result<()> {
self.serialize_common(o, true)
}
}
impl<'a> crate::serialize::SerializeInto for TSK<'a> {}
impl<'a> MarshalInto for TSK<'a> {
fn serialized_len(&self) -> usize {
let mut l = 0;
// Serializes public or secret key depending on the filter.
let serialized_len_key
= |key: &'a key::UnspecifiedSecret, tag_public, tag_secret|
{
let tag = if key.has_secret() && (self.filter)(key) {
tag_secret
} else {
tag_public
};
if self.emit_stubs && (tag == Tag::PublicKey
|| tag == Tag::PublicSubkey) {
// Emit a GnuPG-style secret key stub. The stub
// extends the public key by 8 bytes.
let l = key.parts_as_public().net_len() + 8;
return 1 // CTB
+ BodyLength::Full(l as u32).serialized_len()
+ l;
}
let packet = match tag {
Tag::PublicKey => PacketRef::PublicKey(key.into()),
Tag::PublicSubkey => PacketRef::PublicSubkey(key.into()),
Tag::SecretKey => PacketRef::SecretKey(key.into()),
Tag::SecretSubkey => PacketRef::SecretSubkey(key.into()),
_ => unreachable!(),
};
packet.serialized_len()
};
let primary = self.cert.primary_key();
l += serialized_len_key(primary.key().into(),
Tag::PublicKey, Tag::SecretKey);
for s in primary.signatures() {
l += PacketRef::Signature(s).serialized_len();
}
for u in self.cert.userids() {
l += PacketRef::UserID(u.userid()).serialized_len();
for s in u.signatures() {
l += PacketRef::Signature(s).serialized_len();
}
}
for u in self.cert.user_attributes() {
l += PacketRef::UserAttribute(u.user_attribute()).serialized_len();
for s in u.signatures() {
l += PacketRef::Signature(s).serialized_len();
}
}
for k in self.cert.subkeys() {
l += serialized_len_key(k.key().into(),
Tag::PublicSubkey, Tag::SecretSubkey);
for s in k.signatures() {
l += PacketRef::Signature(s).serialized_len();
}
}
for u in self.cert.unknowns() {
l += PacketRef::Unknown(u.unknown()).serialized_len();
for s in u.signatures() {
l += PacketRef::Signature(s).serialized_len();
}
}
for s in self.cert.bad_signatures() {
l += PacketRef::Signature(s).serialized_len();
}
l
}
fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
generic_serialize_into(self, self.serialized_len(), buf)
}
fn export_into(&self, buf: &mut [u8]) -> Result<usize> {
generic_export_into(self, self.serialized_len(), buf)
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::vec_truncate;
use crate::parse::Parse;
use crate::packet::key;
use crate::policy::StandardPolicy as P;
/// Demonstrates that public keys and all components are
/// serialized.
#[test]
fn roundtrip_cert() {
for test in crate::tests::CERTS {
let cert = match Cert::from_bytes(test.bytes) {
Ok(t) => t,
Err(_) => continue,
};
assert!(! cert.is_tsk());
let buf = cert.as_tsk().to_vec().unwrap();
let cert_ = Cert::from_bytes(&buf).unwrap();
assert_eq!(cert, cert_, "roundtripping {}.pgp failed", test);
}
}
/// Demonstrates that secret keys and all components are
/// serialized.
#[test]
fn roundtrip_tsk() {
for test in crate::tests::TSKS {
let cert = Cert::from_bytes(test.bytes).unwrap();
assert!(cert.is_tsk());
let mut buf = Vec::new();
cert.as_tsk().serialize(&mut buf).unwrap();
let cert_ = Cert::from_bytes(&buf).unwrap();
assert_eq!(cert, cert_, "roundtripping {}-private.pgp failed", test);
// This time, use a trivial filter.
let mut buf = Vec::new();
cert.as_tsk().set_filter(|_| true).serialize(&mut buf).unwrap();
let cert_ = Cert::from_bytes(&buf).unwrap();
assert_eq!(cert, cert_, "roundtripping {}-private.pgp failed", test);
}
}
/// Demonstrates that TSK::serialize() with the right filter
/// reduces to Cert::serialize().
#[test]
fn reduce_to_cert_serialize() {
for test in crate::tests::TSKS {
let cert = Cert::from_bytes(test.bytes).unwrap();
assert!(cert.is_tsk());
// First, use Cert::serialize().
let mut buf_cert = Vec::new();
cert.serialize(&mut buf_cert).unwrap();
// When serializing using TSK::serialize, filter out all
// secret keys.
let mut buf_tsk = Vec::new();
cert.as_tsk().set_filter(|_| false).serialize(&mut buf_tsk).unwrap();
// Check for equality.
let cert_ = Cert::from_bytes(&buf_cert).unwrap();
let tsk_ = Cert::from_bytes(&buf_tsk).unwrap();
assert_eq!(cert_, tsk_,
"reducing failed on {}-private.pgp: not Cert::eq",
test);
// Check for identinty.
assert_eq!(buf_cert, buf_tsk,
"reducing failed on {}-private.pgp: serialized identity",
test);
}
}
#[test]
fn export() {
use crate::Packet;
use crate::cert::prelude::*;
use crate::types::{Curve, KeyFlags, SignatureType};
use crate::packet::{
signature, UserID, user_attribute::{UserAttribute, Subpacket},
key::Key4,
};
let p = &P::new();
let (cert, _) = CertBuilder::new().generate().unwrap();
let mut keypair = cert.primary_key().key().clone().parts_into_secret()
.unwrap().into_keypair().unwrap();
let key: key::SecretSubkey =
Key4::generate_ecc(false, Curve::Cv25519).unwrap().into();
let key_binding = key.bind(
&mut keypair, &cert,
signature::SignatureBuilder::new(SignatureType::SubkeyBinding)
.set_key_flags(
KeyFlags::empty().set_transport_encryption())
.unwrap()
.set_exportable_certification(false).unwrap()).unwrap();
let uid = UserID::from("foo");
let uid_binding = uid.bind(
&mut keypair, &cert,
signature::SignatureBuilder::from(
cert.primary_key().with_policy(p, None).unwrap()
.direct_key_signature().unwrap().clone())
.set_type(SignatureType::PositiveCertification)
.preserve_signature_creation_time().unwrap()
.set_exportable_certification(false).unwrap()).unwrap();
let ua = UserAttribute::new(&[
Subpacket::Unknown(2, b"foo".to_vec().into_boxed_slice()),
]).unwrap();
let ua_binding = ua.bind(
&mut keypair, &cert,
signature::SignatureBuilder::from(
cert.primary_key().with_policy(p, None).unwrap()
.direct_key_signature().unwrap().clone())
.set_type(SignatureType::PositiveCertification)
.preserve_signature_creation_time().unwrap()
.set_exportable_certification(false).unwrap()).unwrap();
let cert = cert.insert_packets(vec![
Packet::SecretSubkey(key), key_binding.into(),
uid.into(), uid_binding.into(),
ua.into(), ua_binding.into(),
]).unwrap();
assert_eq!(cert.subkeys().count(), 1);
cert.subkeys().next().unwrap().binding_signature(p, None).unwrap();
assert_eq!(cert.userids().count(), 1);
assert!(cert.userids().with_policy(p, None).next().is_some());
assert_eq!(cert.user_attributes().count(), 1);
assert!(cert.user_attributes().with_policy(p, None).next().is_some());
// The binding signature is not exportable, so when we export
// and re-parse, we expect the userid to be gone.
let mut buf = Vec::new();
cert.export(&mut buf).unwrap();
let cert_ = Cert::from_bytes(&buf).unwrap();
assert_eq!(cert_.subkeys().count(), 0);
assert_eq!(cert_.userids().count(), 0);
assert_eq!(cert_.user_attributes().count(), 0);
let mut buf = vec![0; cert.serialized_len()];
let l = cert.export_into(&mut buf).unwrap();
vec_truncate(&mut buf, l);
let cert_ = Cert::from_bytes(&buf).unwrap();
assert_eq!(cert_.subkeys().count(), 0);
assert_eq!(cert_.userids().count(), 0);
assert_eq!(cert_.user_attributes().count(), 0);
let cert_ = Cert::from_bytes(&cert.export_to_vec().unwrap()).unwrap();
assert_eq!(cert_.subkeys().count(), 0);
assert_eq!(cert_.userids().count(), 0);
assert_eq!(cert_.user_attributes().count(), 0);
// Same, this time using the armor encoder.
let mut buf = Vec::new();
cert.armored().export(&mut buf).unwrap();
let cert_ = Cert::from_bytes(&buf).unwrap();
assert_eq!(cert_.subkeys().count(), 0);
assert_eq!(cert_.userids().count(), 0);
assert_eq!(cert_.user_attributes().count(), 0);
let mut buf = vec![0; cert.serialized_len()];
let l = cert.armored().export_into(&mut buf).unwrap();
vec_truncate(&mut buf, l);
let cert_ = Cert::from_bytes(&buf).unwrap();
assert_eq!(cert_.subkeys().count(), 0);
assert_eq!(cert_.userids().count(), 0);
assert_eq!(cert_.user_attributes().count(), 0);
let cert_ =
Cert::from_bytes(&cert.armored().export_to_vec().unwrap()).unwrap();
assert_eq!(cert_.subkeys().count(), 0);
assert_eq!(cert_.userids().count(), 0);
assert_eq!(cert_.user_attributes().count(), 0);
// Same, this time as TSKs.
let mut buf = Vec::new();
cert.as_tsk().export(&mut buf).unwrap();
let cert_ = Cert::from_bytes(&buf).unwrap();
assert_eq!(cert_.subkeys().count(), 0);
assert_eq!(cert_.userids().count(), 0);
assert_eq!(cert_.user_attributes().count(), 0);
let mut buf = vec![0; cert.serialized_len()];
let l = cert.as_tsk().export_into(&mut buf).unwrap();
vec_truncate(&mut buf, l);
let cert_ = Cert::from_bytes(&buf).unwrap();
assert_eq!(cert_.subkeys().count(), 0);
assert_eq!(cert_.userids().count(), 0);
assert_eq!(cert_.user_attributes().count(), 0);
let cert_ =
Cert::from_bytes(&cert.as_tsk().export_to_vec().unwrap()).unwrap();
assert_eq!(cert_.subkeys().count(), 0);
assert_eq!(cert_.userids().count(), 0);
assert_eq!(cert_.user_attributes().count(), 0);
}
/// Tests that GnuPG-style stubs are preserved when roundtripping.
#[test]
fn issue_613() -> Result<()> {
use crate::packet::key::*;
use crate::{types::*, crypto::S2K};
use crate::{*, cert::*, parse::Parse};
let p = &crate::policy::StandardPolicy::new();
let (cert, _) = CertBuilder::new().add_signing_subkey().generate()?;
assert_eq!(cert.keys().with_policy(p, None)
.alive().revoked(false).unencrypted_secret().count(), 2);
// Only write out the subkey's secret, the primary key is "detached".
let buf = cert.as_tsk()
.set_filter(|k| k.fingerprint() != cert.fingerprint())
.emit_secret_key_stubs(true)
.to_vec()?;
// Try parsing it.
let cert_ = Cert::from_bytes(&buf)?;
// The primary key has an "encrypted" stub.
assert!(cert_.primary_key().has_secret());
assert_eq!(cert_.keys().with_policy(p, None)
.alive().revoked(false).unencrypted_secret().count(), 1);
if let Some(SecretKeyMaterial::Encrypted(sec)) =
cert_.primary_key().optional_secret()
{
assert_eq!(sec.algo(), SymmetricAlgorithm::Unencrypted);
if let S2K::Private { tag, .. } = sec.s2k() {
assert_eq!(*tag, 101);
} else {
panic!("expected proprietary S2K type");
}
} else {
panic!("expected ''encrypted'' secret key stub");
}
// When roundtripping such a key, the stub should be preserved.
let buf_ = cert_.as_tsk().to_vec()?;
assert_eq!(buf, buf_);
Ok(())
}
/// Checks partial equality of certificates and TSKs.
#[test]
fn issue_701() -> Result<()> {
let cert_0 = Cert::from_bytes(crate::tests::key("testy.pgp"))?;
let cert_1 = Cert::from_bytes(crate::tests::key("testy.pgp"))?;
let tsk_0 = Cert::from_bytes(crate::tests::key("testy-private.pgp"))?;
let tsk_1 = Cert::from_bytes(crate::tests::key("testy-private.pgp"))?;
// We define equality by equality of the serialized form.
// This macro checks that.
macro_rules! check {
($a: expr, $b: expr, $expectation: expr) => {{
let a = $a;
let b = $b;
let serialized_eq = a.to_vec()? == b.to_vec()?;
let eq = a == b;
assert_eq!(serialized_eq, eq);
assert_eq!(eq, $expectation);
}};
}
// Equal as certs, because equality is defined by equality of
// the serialized form, and serializing a cert never writes
// out any secrets.
check!(&cert_0, &cert_1, true);
check!(&cert_0, &tsk_0, true);
// Filters out secrets.
let no_secrets = |_| false;
// TSK's equality.
check!(tsk_0.as_tsk(), tsk_1.as_tsk(), true);
// Without secrets.
check!(tsk_0.as_tsk().set_filter(no_secrets),
tsk_1.as_tsk().set_filter(no_secrets),
true);
// Still equal if one uses stubs and the other one does not if
// every key has a secret, i.e. stubs are not in fact used.
check!(
tsk_0.as_tsk().emit_secret_key_stubs(true),
tsk_1.as_tsk(),
true);
// No longer equal if one actually emits stubs.
check!(
tsk_0.as_tsk().emit_secret_key_stubs(true).set_filter(no_secrets),
tsk_1.as_tsk(),
false);
// Certs are not equal to TSKs, because here the secrets are
// written out when serialized.
check!(cert_0.as_tsk(), tsk_0.as_tsk(), false);
// Equal, if we filter out the secrets.
check!(cert_0.as_tsk(),
tsk_0.as_tsk().set_filter(no_secrets),
true);
Ok(())
}
}