age-plugin-yubikey 0.3.1

YubiKey plugin for age clients
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
//! Structs for handling YubiKeys.

use age_core::{
    format::{FileKey, FILE_KEY_BYTES},
    primitives::{aead_decrypt, hkdf},
    secrecy::ExposeSecret,
};
use age_plugin::{identity, Callbacks};
use bech32::{ToBase32, Variant};
use dialoguer::Password;
use log::{debug, warn};
use std::fmt;
use std::io;
use std::iter;
use std::thread::sleep;
use std::time::{Duration, Instant, SystemTime};
use yubikey::{
    certificate::{Certificate, PublicKeyInfo},
    piv::{decrypt_data, AlgorithmId, RetiredSlotId, SlotId},
    reader::{Context, Reader},
    MgmKey, PinPolicy, Serial, TouchPolicy, YubiKey,
};

use crate::{
    error::Error,
    fl,
    format::{RecipientLine, STANZA_KEY_LABEL},
    p256::{Recipient, TAG_BYTES},
    util::{otp_serial_prefix, Metadata},
    IDENTITY_PREFIX,
};

const ONE_SECOND: Duration = Duration::from_secs(1);
const FIFTEEN_SECONDS: Duration = Duration::from_secs(15);

pub(crate) fn is_connected(reader: Reader) -> bool {
    filter_connected(&reader)
}

pub(crate) fn filter_connected(reader: &Reader) -> bool {
    match reader.open() {
        Ok(_) => true,
        Err(e) => {
            use std::error::Error;
            if let Some(pcsc::Error::RemovedCard) =
                e.source().and_then(|inner| inner.downcast_ref())
            {
                warn!(
                    "{}",
                    i18n_embed_fl::fl!(
                        crate::LANGUAGE_LOADER,
                        "warn-yk-not-connected",
                        yubikey_name = reader.name(),
                    )
                );
                false
            } else {
                true
            }
        }
    }
}

pub(crate) fn wait_for_readers() -> Result<Context, Error> {
    // Start a 15-second timer waiting for a YubiKey to be inserted (if necessary).
    let start = SystemTime::now();
    loop {
        let mut readers = Context::open()?;
        if readers.iter()?.any(is_connected) {
            break Ok(readers);
        }

        match SystemTime::now().duration_since(start) {
            Ok(end) if end >= FIFTEEN_SECONDS => return Err(Error::TimedOut),
            _ => sleep(ONE_SECOND),
        }
    }
}

/// Stops `scdaemon` if it is running.
///
/// Returns `true` if `scdaemon` was running and was successfully interrupted (or killed
/// if the platform doesn't support interrupts).
fn stop_scdaemon() -> bool {
    debug!("Sharing violation encountered, looking for scdaemon processes to stop");

    use sysinfo::{
        Process, ProcessExt, ProcessRefreshKind, RefreshKind, Signal, System, SystemExt,
    };

    let mut interrupted = false;

    let sys =
        System::new_with_specifics(RefreshKind::new().with_processes(ProcessRefreshKind::new()));

    for process in sys
        .processes()
        .values()
        .filter(|val: &&Process| ["scdaemon", "scdaemon.exe"].contains(&val.name()))
    {
        if process
            .kill_with(Signal::Interrupt)
            .unwrap_or_else(|| process.kill())
        {
            debug!("Stopped scdaemon (PID {})", process.pid());
            interrupted = true;
        }
    }

    // If we did interrupt `scdaemon`, pause briefly to allow it to exit.
    if interrupted {
        sleep(Duration::from_millis(100));
    }

    interrupted
}

fn open_sesame(
    op: impl Fn() -> Result<YubiKey, yubikey::Error>,
) -> Result<YubiKey, yubikey::Error> {
    op().or_else(|e| match e {
        yubikey::Error::PcscError {
            inner: Some(pcsc::Error::SharingViolation),
        } if stop_scdaemon() => op(),
        _ => Err(e),
    })
}

/// Opens a connection to this reader, returning a `YubiKey` if successful.
///
/// This is equivalent to [`Reader::open`], but additionally handles the presence of
/// `scdaemon` (which can indefinitely hold exclusive access to a YubiKey).
pub(crate) fn open_connection(reader: &Reader) -> Result<YubiKey, yubikey::Error> {
    open_sesame(|| reader.open())
}

/// Opens a YubiKey with a specific serial number.
///
/// This is equivalent to [`YubiKey::open_by_serial`], but additionally handles the
/// presence of `scdaemon` (which can indefinitely hold exclusive access to a YubiKey).
fn open_by_serial(serial: Serial) -> Result<YubiKey, yubikey::Error> {
    open_sesame(|| YubiKey::open_by_serial(serial))
}

pub(crate) fn open(serial: Option<Serial>) -> Result<YubiKey, Error> {
    if !Context::open()?.iter()?.any(is_connected) {
        if let Some(serial) = serial {
            eprintln!(
                "{}",
                i18n_embed_fl::fl!(
                    crate::LANGUAGE_LOADER,
                    "open-yk-with-serial",
                    yubikey_serial = serial.to_string(),
                )
            );
        } else {
            eprintln!("{}", fl!("open-yk-without-serial"));
        }
    }
    let mut readers = wait_for_readers()?;
    let mut readers_iter = readers.iter()?.filter(filter_connected);

    // --serial selects the YubiKey to use. If not provided, and more than one YubiKey is
    // connected, an error is returned.
    let yubikey = match (readers_iter.next(), readers_iter.next(), serial) {
        (None, _, _) => unreachable!(),
        (Some(reader), None, None) => open_connection(&reader)?,
        (Some(reader), None, Some(serial)) => {
            let yubikey = open_connection(&reader)?;
            if yubikey.serial() != serial {
                return Err(Error::NoMatchingSerial(serial));
            }
            yubikey
        }
        (Some(a), Some(b), Some(serial)) => {
            let reader = iter::empty()
                .chain(Some(a))
                .chain(Some(b))
                .chain(readers_iter)
                .find(|reader| match open_connection(reader) {
                    Ok(yk) => yk.serial() == serial,
                    _ => false,
                })
                .ok_or(Error::NoMatchingSerial(serial))?;
            open_connection(&reader)?
        }
        (Some(_), Some(_), None) => return Err(Error::MultipleYubiKeys),
    };

    Ok(yubikey)
}

pub(crate) fn manage(yubikey: &mut YubiKey) -> Result<(), Error> {
    const DEFAULT_PIN: &str = "123456";
    const DEFAULT_PUK: &str = "12345678";

    eprintln!();
    let pin = Password::new()
        .with_prompt(i18n_embed_fl::fl!(
            crate::LANGUAGE_LOADER,
            "mgr-enter-pin",
            yubikey_serial = yubikey.serial().to_string(),
            default_pin = DEFAULT_PIN,
        ))
        .interact()?;
    yubikey.verify_pin(pin.as_bytes())?;

    // If the user is using the default PIN, help them to change it.
    if pin == DEFAULT_PIN {
        eprintln!();
        eprintln!("{}", fl!("mgr-change-default-pin"));
        eprintln!();
        let current_puk = Password::new()
            .with_prompt(i18n_embed_fl::fl!(
                crate::LANGUAGE_LOADER,
                "mgr-enter-current-puk",
                default_puk = DEFAULT_PUK,
            ))
            .interact()?;
        let new_pin = Password::new()
            .with_prompt(fl!("mgr-choose-new-pin"))
            .with_confirmation(fl!("mgr-repeat-new-pin"), fl!("mgr-pin-mismatch"))
            .interact()?;
        if new_pin.len() > 8 {
            return Err(Error::InvalidPinLength);
        }
        yubikey.change_puk(current_puk.as_bytes(), new_pin.as_bytes())?;
        yubikey.change_pin(pin.as_bytes(), new_pin.as_bytes())?;
    }

    if let Ok(mgm_key) = MgmKey::get_protected(yubikey) {
        yubikey.authenticate(mgm_key)?;
    } else {
        // Try to authenticate with the default management key.
        yubikey
            .authenticate(MgmKey::default())
            .map_err(|_| Error::CustomManagementKey)?;

        // Migrate to a PIN-protected management key.
        let mgm_key = MgmKey::generate();
        eprintln!();
        eprintln!("{}", fl!("mgr-changing-mgmt-key"));
        eprint!("... ");
        mgm_key.set_protected(yubikey).map_err(|e| {
            eprintln!(
                "{}",
                i18n_embed_fl::fl!(
                    crate::LANGUAGE_LOADER,
                    "mgr-changing-mgmt-key-error",
                    management_key = hex::encode(mgm_key.as_ref()),
                )
            );
            e
        })?;
        eprintln!("{}", fl!("mgr-changing-mgmt-key-success"));
    }

    Ok(())
}

/// A reference to an age key stored in a YubiKey.
#[derive(Debug)]
pub struct Stub {
    pub(crate) serial: Serial,
    pub(crate) slot: RetiredSlotId,
    pub(crate) tag: [u8; TAG_BYTES],
    pub(crate) identity_index: usize,
}

impl fmt::Display for Stub {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(
            bech32::encode(
                IDENTITY_PREFIX,
                self.to_bytes().to_base32(),
                Variant::Bech32,
            )
            .expect("HRP is valid")
            .to_uppercase()
            .as_str(),
        )
    }
}

impl PartialEq for Stub {
    fn eq(&self, other: &Self) -> bool {
        self.to_bytes().eq(&other.to_bytes())
    }
}

impl Stub {
    /// Returns a key stub and recipient for this `(Serial, SlotId, PublicKey)` tuple.
    ///
    /// Does not check that the `PublicKey` matches the given `(Serial, SlotId)` tuple;
    /// this is checked at decryption time.
    pub(crate) fn new(serial: Serial, slot: RetiredSlotId, recipient: &Recipient) -> Self {
        Stub {
            serial,
            slot,
            tag: recipient.tag(),
            identity_index: 0,
        }
    }

    pub(crate) fn from_bytes(bytes: &[u8], identity_index: usize) -> Option<Self> {
        if bytes.len() < 9 {
            return None;
        }
        let serial = Serial::from(u32::from_le_bytes(bytes[0..4].try_into().unwrap()));
        let slot: RetiredSlotId = bytes[4].try_into().ok()?;
        Some(Stub {
            serial,
            slot,
            tag: bytes[5..9].try_into().unwrap(),
            identity_index,
        })
    }

    fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(9);
        bytes.extend_from_slice(&self.serial.0.to_le_bytes());
        bytes.push(self.slot.into());
        bytes.extend_from_slice(&self.tag);
        bytes
    }

    pub(crate) fn matches(&self, line: &RecipientLine) -> bool {
        self.tag == line.tag
    }

    /// Returns:
    /// - `Ok(Ok(Some(connection)))` if we successfully connected to this YubiKey.
    /// - `Ok(Ok(None))` if the user told us to skip this YubiKey.
    /// - `Ok(Err(_))` if we encountered an error while trying to connect to the YubiKey.
    /// - `Err(_)` on communication errors with the age client.
    pub(crate) fn connect<E>(
        &self,
        callbacks: &mut dyn Callbacks<E>,
    ) -> io::Result<Result<Option<Connection>, identity::Error>> {
        let mut yubikey = match open_by_serial(self.serial) {
            Ok(yk) => yk,
            Err(yubikey::Error::NotFound) => {
                let mut message = i18n_embed_fl::fl!(
                    crate::LANGUAGE_LOADER,
                    "plugin-insert-yk",
                    yubikey_serial = self.serial.to_string(),
                );

                // If the `confirm` command is available, we loop until either the YubiKey
                // we want is inserted, or the used explicitly skips.
                let yubikey = loop {
                    match callbacks.confirm(
                        &message,
                        &fl!("plugin-yk-is-plugged-in"),
                        Some(&fl!("plugin-skip-this-yk")),
                    )? {
                        // `confirm` command is not available.
                        Err(age_core::plugin::Error::Unsupported) => break None,
                        // User told us to skip this key.
                        Ok(false) => return Ok(Ok(None)),
                        // User said they plugged it in; try it.
                        Ok(true) => match open_by_serial(self.serial) {
                            Ok(yubikey) => break Some(yubikey),
                            Err(yubikey::Error::NotFound) => (),
                            Err(_) => {
                                return Ok(Err(identity::Error::Identity {
                                    index: self.identity_index,
                                    message: i18n_embed_fl::fl!(
                                        crate::LANGUAGE_LOADER,
                                        "plugin-err-yk-opening",
                                        yubikey_serial = self.serial.to_string(),
                                    ),
                                }));
                            }
                        },
                        // We can't communicate with the user.
                        Err(age_core::plugin::Error::Fail) => {
                            return Ok(Err(identity::Error::Identity {
                                index: self.identity_index,
                                message: i18n_embed_fl::fl!(
                                    crate::LANGUAGE_LOADER,
                                    "plugin-err-yk-opening",
                                    yubikey_serial = self.serial.to_string(),
                                ),
                            }))
                        }
                    }

                    // We're going to loop around, meaning that the first attempt failed.
                    // Change the message to indicate this to the user.
                    message = i18n_embed_fl::fl!(
                        crate::LANGUAGE_LOADER,
                        "plugin-insert-yk-retry",
                        yubikey_serial = self.serial.to_string(),
                    );
                };

                if let Some(yk) = yubikey {
                    yk
                } else {
                    // `confirm` is not available; fall back to `message` with a timeout.
                    if callbacks.message(&message)?.is_err() {
                        return Ok(Err(identity::Error::Identity {
                            index: self.identity_index,
                            message: i18n_embed_fl::fl!(
                                crate::LANGUAGE_LOADER,
                                "plugin-err-yk-not-found",
                                yubikey_serial = self.serial.to_string(),
                            ),
                        }));
                    }

                    // Start a 15-second timer waiting for the YubiKey to be inserted
                    let start = SystemTime::now();
                    loop {
                        match open_by_serial(self.serial) {
                            Ok(yubikey) => break yubikey,
                            Err(yubikey::Error::NotFound) => (),
                            Err(_) => {
                                return Ok(Err(identity::Error::Identity {
                                    index: self.identity_index,
                                    message: i18n_embed_fl::fl!(
                                        crate::LANGUAGE_LOADER,
                                        "plugin-err-yk-opening",
                                        yubikey_serial = self.serial.to_string(),
                                    ),
                                }));
                            }
                        }

                        match SystemTime::now().duration_since(start) {
                            Ok(end) if end >= FIFTEEN_SECONDS => {
                                return Ok(Err(identity::Error::Identity {
                                    index: self.identity_index,
                                    message: i18n_embed_fl::fl!(
                                        crate::LANGUAGE_LOADER,
                                        "plugin-err-yk-timed-out",
                                        yubikey_serial = self.serial.to_string(),
                                    ),
                                }))
                            }
                            _ => sleep(ONE_SECOND),
                        }
                    }
                }
            }
            Err(_) => {
                return Ok(Err(identity::Error::Identity {
                    index: self.identity_index,
                    message: i18n_embed_fl::fl!(
                        crate::LANGUAGE_LOADER,
                        "plugin-err-yk-opening",
                        yubikey_serial = self.serial.to_string(),
                    ),
                }))
            }
        };

        // Read the pubkey from the YubiKey slot and check it still matches.
        let (cert, pk) = match Certificate::read(&mut yubikey, SlotId::Retired(self.slot))
            .ok()
            .and_then(|cert| match cert.subject_pki() {
                PublicKeyInfo::EcP256(pubkey) => Recipient::from_encoded(pubkey)
                    .filter(|pk| pk.tag() == self.tag)
                    .map(|pk| (cert, pk)),
                _ => None,
            }) {
            Some(pk) => pk,
            None => {
                return Ok(Err(identity::Error::Identity {
                    index: self.identity_index,
                    message: fl!("plugin-err-yk-stub-mismatch"),
                }))
            }
        };

        Ok(Ok(Some(Connection {
            yubikey,
            cert,
            pk,
            slot: self.slot,
            tag: self.tag,
            identity_index: self.identity_index,
            cached_metadata: None,
            last_touch: None,
        })))
    }
}

pub(crate) struct Connection {
    yubikey: YubiKey,
    cert: Certificate,
    pk: Recipient,
    slot: RetiredSlotId,
    tag: [u8; 4],
    identity_index: usize,
    cached_metadata: Option<Metadata>,
    last_touch: Option<Instant>,
}

impl Connection {
    pub(crate) fn recipient(&self) -> &Recipient {
        &self.pk
    }

    pub(crate) fn request_pin_if_necessary<E>(
        &mut self,
        callbacks: &mut dyn Callbacks<E>,
    ) -> io::Result<Result<(), identity::Error>> {
        // Check if we can skip requesting a PIN.
        if self.cached_metadata.is_none() {
            let (_, cert) = x509_parser::parse_x509_certificate(self.cert.as_ref()).unwrap();
            self.cached_metadata =
                match Metadata::extract(&mut self.yubikey, self.slot, &cert, true) {
                    None => {
                        return Ok(Err(identity::Error::Identity {
                            index: self.identity_index,
                            message: fl!("plugin-err-yk-invalid-pin-policy"),
                        }))
                    }
                    metadata => metadata,
                };
        }
        if let Some(PinPolicy::Never) = self.cached_metadata.as_ref().and_then(|m| m.pin_policy) {
            return Ok(Ok(()));
        }

        // The policy requires a PIN, so request it.
        // Note that we can't distinguish between PinPolicy::Once and PinPolicy::Always
        // because this plugin is ephemeral, so we always request the PIN.
        let enter_pin_msg = i18n_embed_fl::fl!(
            crate::LANGUAGE_LOADER,
            "plugin-enter-pin",
            yubikey_serial = self.yubikey.serial().to_string(),
        );
        let mut message = enter_pin_msg.clone();
        let pin = loop {
            message = match callbacks.request_secret(&message)? {
                Ok(pin) => match pin.expose_secret().len() {
                    // A PIN must be between 6 and 8 characters.
                    6..=8 => break pin,
                    // If the string is 44 bytes and starts with the YubiKey's serial
                    // encoded as 12-byte modhex, the user probably touched the YubiKey
                    // early and "typed" an OTP.
                    44 if pin
                        .expose_secret()
                        .starts_with(&otp_serial_prefix(self.yubikey.serial())) =>
                    {
                        format!("{} {}", fl!("plugin-err-accidental-touch"), enter_pin_msg)
                    }
                    // Otherwise, the PIN is either too short or too long.
                    0..=5 => format!("{} {}", fl!("plugin-err-pin-too-short"), enter_pin_msg),
                    _ => format!("{} {}", fl!("plugin-err-pin-too-long"), enter_pin_msg),
                },
                Err(_) => {
                    return Ok(Err(identity::Error::Identity {
                        index: self.identity_index,
                        message: i18n_embed_fl::fl!(
                            crate::LANGUAGE_LOADER,
                            "plugin-err-pin-required",
                            yubikey_serial = self.yubikey.serial().to_string(),
                        ),
                    }))
                }
            };
        };
        if let Err(e) = self.yubikey.verify_pin(pin.expose_secret().as_bytes()) {
            return Ok(Err(identity::Error::Identity {
                index: self.identity_index,
                message: format!("{:?}", Error::YubiKey(e)),
            }));
        }
        Ok(Ok(()))
    }

    pub(crate) fn unwrap_file_key(&mut self, line: &RecipientLine) -> Result<FileKey, ()> {
        assert_eq!(self.tag, line.tag);

        // Check if the touch policy requires a touch.
        let needs_touch = match (
            self.cached_metadata.as_ref().and_then(|m| m.touch_policy),
            self.last_touch,
        ) {
            (Some(TouchPolicy::Always), _) | (Some(TouchPolicy::Cached), None) => true,
            (Some(TouchPolicy::Cached), Some(last)) if last.elapsed() >= FIFTEEN_SECONDS => true,
            _ => false,
        };

        // The YubiKey API for performing scalar multiplication takes the point in its
        // uncompressed SEC-1 encoding.
        let shared_secret = match decrypt_data(
            &mut self.yubikey,
            line.epk_bytes.decompress().as_bytes(),
            AlgorithmId::EccP256,
            SlotId::Retired(self.slot),
        ) {
            Ok(res) => res,
            Err(_) => return Err(()),
        };

        // If we requested a touch and reached here, the user touched the YubiKey.
        if needs_touch {
            if let Some(TouchPolicy::Cached) =
                self.cached_metadata.as_ref().and_then(|m| m.touch_policy)
            {
                self.last_touch = Some(Instant::now());
            }
        }

        let mut salt = vec![];
        salt.extend_from_slice(line.epk_bytes.as_bytes());
        salt.extend_from_slice(self.pk.to_encoded().as_bytes());

        let enc_key = hkdf(&salt, STANZA_KEY_LABEL, shared_secret.as_ref());

        // A failure to decrypt is fatal, because we assume that we won't
        // encounter 32-bit collisions on the key tag embedded in the header.
        match aead_decrypt(&enc_key, FILE_KEY_BYTES, &line.encrypted_file_key) {
            Ok(pt) => Ok(TryInto::<[u8; FILE_KEY_BYTES]>::try_into(&pt[..])
                .unwrap()
                .into()),
            Err(_) => Err(()),
        }
    }
}

#[cfg(test)]
mod tests {
    use yubikey::{piv::RetiredSlotId, Serial};

    use super::Stub;

    #[test]
    fn stub_round_trip() {
        let stub = Stub {
            serial: Serial::from(42),
            slot: RetiredSlotId::R1,
            tag: [7; 4],
            identity_index: 0,
        };

        let encoded = stub.to_bytes();
        assert_eq!(Stub::from_bytes(&[], 0), None);
        assert_eq!(Stub::from_bytes(&encoded, 0), Some(stub));
        assert_eq!(Stub::from_bytes(&encoded[..encoded.len() - 1], 0), None);
    }
}