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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! An implementation of UEFI spec 8.2 - Variable Services
//!
//! This implementation is a direct implementation / transcription of the UEFI
//! spec, and does not contain any Hyper-V specific features* (i.e: injecting
//! various nvram vars related to secure boot, boot order, etc...).
//!
//! *that isn't _entirely_ true just yet, as there is one bit of code
//! that enforce read-only access to certain Hyper-V specific vars, but if the
//! need arises, those code paths can be refactored.

pub use nvram_services_ext::NvramServicesExt;

use bitfield_struct::bitfield;
use guid::Guid;
use inspect::Inspect;
use mesh::payload::Protobuf;
use std::borrow::Cow;
use thiserror::Error;
use ucs2::Ucs2LeSlice;
use ucs2::Ucs2ParseError;
use uefi_nvram_specvars::signature_list;
use uefi_nvram_specvars::signature_list::ParseSignatureLists;
use uefi_nvram_storage::InspectableNvramStorage;
use uefi_nvram_storage::NextVariable;
use uefi_nvram_storage::NvramStorageError;
use uefi_specs::uefi::common::EfiStatus;
use uefi_specs::uefi::nvram::EfiVariableAttributes;
use uefi_specs::uefi::time::EFI_TIME;
use zerocopy::FromBytes;
use zerocopy::FromZeroes;

#[cfg(feature = "fuzzing")]
pub mod auth_var_crypto;
#[cfg(not(feature = "fuzzing"))]
mod auth_var_crypto;
mod nvram_services_ext;

#[derive(Debug, Error)]
pub enum NvramError {
    #[error("storage backend error")]
    NvramStorage(#[source] NvramStorageError),
    #[error("variable name cannot be null/None")]
    NameNull,
    #[error("variable data of non-zero len cannot be null")]
    DataNull,
    #[error("variable name validation failed")]
    NameValidation(#[from] Ucs2ParseError),
    #[error("cannot pass empty string to SetVariable")]
    NameEmpty,
    #[error("attributes include non-spec values")]
    AttributeNonSpec,
    #[error("invalid runtime access")]
    InvalidRuntimeAccess,
    #[error("invalid attr: hardware error records are not supported")]
    UnsupportedHardwareErrorRecord,
    #[error("invalid attr: enhanced authenticated access unsupported")]
    UnsupportedEnhancedAuthAccess,
    #[error("invalid attr: volatile variables unsupported")]
    UnsupportedVolatile,
    #[error("attribute mismatch with existing variable")]
    AttributeMismatch,
    #[error("authenticated variable error")]
    AuthError(#[from] AuthError),
    #[error("updating SetupMode variable")]
    UpdateSetupMode(#[source] NvramStorageError),
    #[error("parsing signature list")]
    SignatureList(#[from] signature_list::ParseError),
}

#[derive(Debug, Error)]
pub enum AuthError {
    #[error("data too short (cannot extract EFI_VARIABLE_AUTHENTICATION_2 header)")]
    NotEnoughHdrData,
    #[error("data too short (cannot extract WIN_CERTIFICATE_UEFI_GUID cert)")]
    NotEnoughCertData,
    #[error("invalid WIN_CERTIFICATE Header")]
    InvalidWinCertHeader,
    #[error("invalid WIN_CERTIFICATE_UEFI_GUID Header")]
    InvalidWinCertUefiGuidHeader,
    #[error("incorrect cert type (must be WIN_CERTIFICATE_UEFI_GUID)")]
    IncorrectCertType,
    #[error("incorrect timestamp values")]
    IncorrectTimestamp,
    #[error("new timestamp is not later than current timestamp")]
    OldTimestamp,

    #[error("current implementation cannot authenticate specified var")]
    UnsupportedAuthVar,

    #[error("could not verify auth var")]
    CryptoError,
    #[cfg(feature = "auth-var-verify-crypto")]
    #[error("error in crypto payload format")]
    CryptoFormat(#[from] auth_var_crypto::FormatError),
}

/// `SetVariable` validation is incredibly tricky, since there are a _lot_ of
/// subtle logic branches that are predicated on the presence (or lack thereof)
/// of various attribute bits.
///
/// In order to make the implementation a bit easier to understand and maintain,
/// we switch from using the full-featured `EfiVariableAttributes` bitflags type
/// to a restricted subset of these flags described by `SupportedAttrs` part-way
/// through SetVariable.
#[bitfield(u32)]
#[derive(PartialEq)]
pub struct SupportedAttrs {
    pub non_volatile: bool,
    pub bootservice_access: bool,
    pub runtime_access: bool,
    pub hardware_error_record: bool,
    _reserved: bool,
    pub time_based_authenticated_write_access: bool,
    #[bits(26)]
    _reserved2: u32,
}

impl SupportedAttrs {
    pub fn contains_unsupported_bits(&self) -> bool {
        u32::from(*self)
            & !u32::from(
                Self::new()
                    .with_non_volatile(true)
                    .with_bootservice_access(true)
                    .with_runtime_access(true)
                    .with_hardware_error_record(true)
                    .with_time_based_authenticated_write_access(true),
            )
            != 0
    }
}

/// Helper struct to collect various properties of a parsed authenticated var
#[cfg_attr(not(feature = "auth-var-verify-crypto"), allow(dead_code))]
#[derive(Debug, Clone, Copy)]
pub struct ParsedAuthVar<'a> {
    pub name: &'a Ucs2LeSlice,
    pub vendor: Guid,
    pub attr: u32,
    pub timestamp: EFI_TIME,
    pub pkcs7_data: &'a [u8],
    pub var_data: &'a [u8],
}

/// Unlike a typical result type, NvramErrors contain _both_ a payload _and_ an
/// error code. Depending on the error code, an optional `NvramError` might be
/// included as well, which provides more context.
///
/// Notably, **this result types cannot be propagated via the `?` operator!**
#[derive(Debug)]
pub struct NvramResult<T>(pub T, pub EfiStatus, pub Option<NvramError>);

impl<T> NvramResult<T> {
    pub fn is_success(&self) -> bool {
        matches!(self.1, EfiStatus::SUCCESS)
    }
}

impl<T> std::fmt::Display for NvramResult<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.2 {
            Some(_) => write!(f, "{:?} (with error context)", self.1),
            None => write!(f, "{:?}", self.1),
        }
    }
}

impl<T> std::error::Error for NvramResult<T>
where
    T: std::fmt::Debug,
{
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.2
            .as_ref()
            .map(|s| s as &(dyn std::error::Error + 'static))
    }
}

#[derive(Clone, Copy, Debug, Protobuf, Inspect)]
enum RuntimeState {
    /// Implementation-specific state, whereby certain read-only and
    /// authenticated variable checks are bypassed.
    ///
    /// Transitions into `Boot` once all pre-boot nvram variables have been
    /// successfully injected.
    PreBoot,
    /// UEFI firmware hasn't called `ExitBootServices`
    Boot,
    /// UEFI firmware has called `ExitBootServices`
    Runtime,
}

impl RuntimeState {
    fn is_pre_boot(&self) -> bool {
        matches!(&self, RuntimeState::PreBoot)
    }

    fn is_boot(&self) -> bool {
        matches!(&self, RuntimeState::Boot)
    }

    fn is_runtime(&self) -> bool {
        matches!(&self, RuntimeState::Runtime)
    }
}

/// An implementation of UEFI spec 8.2 - Variable Services
///
/// This API tries to match the API defined by the UEFI spec 1:1, hence why it
/// doesn't look very "Rust-y".
///
/// If you need to interact with `NvramServices` outside the context of the UEFI
/// device itself, consider importing the [`NvramServicesExt`] trait. This trait
/// provides various helper methods that make it easier to get/set nvram
/// variables, without worrying about the nitty-gritty details of UCS-2 string
/// encoding, pointer sizes/nullness, etc...
///
/// Instead of returning a typical `Result` type, these methods all return a
/// tuple of `(Option<T>, EfiStatus, Option<NvramError>)`, where the `EfiStatus`
/// field should be unconditionally returned to the guest, while the
/// `NvramError` type provides additional context as to what error occurred in
/// OpenVMM (i.e: for logging purposes).
#[derive(Debug, Inspect)]
pub struct NvramSpecServices<S: InspectableNvramStorage> {
    storage: S,
    runtime_state: RuntimeState,
}

impl<S: InspectableNvramStorage> NvramSpecServices<S> {
    /// Construct a new NvramServices instance from an existing storage backend.
    pub fn new(storage: S) -> NvramSpecServices<S> {
        NvramSpecServices {
            storage,
            runtime_state: RuntimeState::PreBoot,
        }
    }

    /// Check if the nvram store is empty.
    pub async fn is_empty(&mut self) -> Result<bool, NvramStorageError> {
        self.storage.is_empty().await
    }

    /// Update "SetupMode" based on the current value of "PK"
    ///
    /// From UEFI spec section 32.3
    ///
    /// While no Platform Key is enrolled, the SetupMode variable shall be equal
    /// to 1. While SetupMode == 1, the platform firmware shall not require
    /// authentication in order to modify the Platform Key, Key Enrollment Key,
    /// OsRecoveryOrder, OsRecovery####, and image security databases.
    ///
    /// After the Platform Key is enrolled, the SetupMode variable shall be
    /// equal to 0. While SetupMode == 0, the platform firmware shall require
    /// authentication in order to modify the Platform Key, Key Enrollment Key,
    /// OsRecoveryOrder, OsRecovery####, and image security databases.
    pub async fn update_setup_mode(&mut self) -> Result<(), NvramStorageError> {
        use uefi_specs::uefi::nvram::vars::PK;
        use uefi_specs::uefi::nvram::vars::SETUP_MODE;

        let (pk_vendor, pk_name) = PK();
        let (setup_mode_vendor, setup_mode_name) = SETUP_MODE();

        let attr = EfiVariableAttributes::DEFAULT_ATTRIBUTES;
        let timestamp = EFI_TIME::new_zeroed();
        let data = match self.storage.get_variable(pk_name, pk_vendor).await? {
            Some(_) => [0x00],
            None => [0x01],
        };

        self.storage
            .set_variable(
                setup_mode_name,
                setup_mode_vendor,
                attr.into(),
                data.to_vec(),
                timestamp,
            )
            .await?;

        Ok(())
    }

    /// Nvram behavior changes after the guest signals that ExitBootServices has
    /// been called (e.g: hiding variables that are only accessible at
    /// boot-time).
    pub fn exit_boot_services(&mut self) {
        assert!(self.runtime_state.is_boot());
        tracing::trace!("NVRAM has entered runtime mode");
        self.runtime_state = RuntimeState::Runtime;
    }

    /// Called when the VM resets to return to the preboot state.
    pub fn reset(&mut self) {
        self.runtime_state = RuntimeState::PreBoot;
    }

    /// Called after injecting any pre-boot nvram vars, transitioning the nvram
    /// store to start accepting calls from guest UEFI.
    pub fn prepare_for_boot(&mut self) {
        assert!(self.runtime_state.is_pre_boot());
        tracing::trace!("NVRAM has entered boot mode");
        self.runtime_state = RuntimeState::Boot;
    }

    async fn get_setup_mode(&mut self) -> Result<bool, NvramStorageError> {
        use uefi_specs::uefi::nvram::vars::SETUP_MODE;

        let (setup_mode_vendor, setup_mode_name) = SETUP_MODE();
        let in_setup_mode = match self
            .storage
            .get_variable(setup_mode_name, setup_mode_vendor)
            .await?
        {
            None => false,
            Some((_, data, _)) => data.first().map(|b| *b == 0x01).unwrap_or(false),
        };

        Ok(in_setup_mode)
    }

    /// Get a variable identified by `name` + `vendor`, returning the variable's
    /// attributes and data.
    ///
    /// - `in_name`
    ///     - (In) Variable name (a null-terminated UTF-16 string, or `None` if
    ///       the guest passed a `nullptr`)
    /// - `in_vendor`
    ///     - (In) Variable vendor guid
    /// - `out_attr`
    ///     - (Out) Variable's attributes
    ///     - _Note:_ According to the UEFI spec: `attr` will be populated on
    ///       both EFI_SUCCESS _and_ when EFI_BUFFER_TOO_SMALL is returned.
    /// - `in_out_data_size`
    ///     - (In) Size of available data buffer (provided by guest)
    ///     - (Out) Size of data to be written into buffer
    ///     - _Note:_ If `data_is_null` is `true`, and `in_out_data_size` is set
    ///       to `0`, `in_out_data_size` will be updated with the size required
    ///       to store the variable.
    /// - `data_is_null`
    ///     - (In) bool indicating if guest passed `nullptr` as the data addr
    pub async fn uefi_get_variable(
        &mut self,
        name: Option<&[u8]>,
        in_vendor: Guid,
        out_attr: &mut u32,
        in_out_data_size: &mut u32,
        data_is_null: bool,
    ) -> NvramResult<Option<Vec<u8>>> {
        let name = match name {
            Some(name) => {
                Ucs2LeSlice::from_slice_with_nul(name).map_err(NvramError::NameValidation)
            }
            None => Err(NvramError::NameNull),
        };

        let name = match name {
            Ok(name) => name,
            Err(e) => return NvramResult(None, EfiStatus::INVALID_PARAMETER, Some(e)),
        };

        tracing::trace!(
            ?in_vendor,
            ?name,
            in_out_data_size,
            data_is_null,
            "Get NVRAM variable",
        );

        let (attr, data) = match self.get_variable_inner(name, in_vendor).await {
            Ok(Some((attr, data, _))) => (attr, data),
            Ok(None) => return NvramResult(None, EfiStatus::NOT_FOUND, None),
            Err((status, err)) => return NvramResult(None, status, err),
        };

        if self.runtime_state.is_runtime() && !attr.runtime_access() {
            // From UEFI spec section 8.2:
            //
            // If EFI_BOOT_SERVICES.ExitBootServices() has already been
            // executed, data variables without the EFI_VARIABLE_RUNTIME_ACCESS
            // attribute set will not be visible to GetVariable() and will
            // return an EFI_NOT_FOUND error.
            return NvramResult(
                None,
                EfiStatus::NOT_FOUND,
                Some(NvramError::InvalidRuntimeAccess),
            );
        }

        *out_attr = attr.into();
        match (*in_out_data_size, data_is_null) {
            (0, true) => *in_out_data_size = data.len() as u32,
            (_, true) => return NvramResult(None, EfiStatus::INVALID_PARAMETER, None),
            (_, false) => {
                let guest_buf_len = *in_out_data_size as usize;
                *in_out_data_size = data.len() as u32;
                if guest_buf_len < data.len() {
                    return NvramResult(None, EfiStatus::BUFFER_TOO_SMALL, None);
                }
            }
        }

        NvramResult(Some(data), EfiStatus::SUCCESS, None)
    }

    async fn get_variable_inner(
        &mut self,
        name: &Ucs2LeSlice,
        vendor: Guid,
    ) -> Result<Option<(SupportedAttrs, Vec<u8>, EFI_TIME)>, (EfiStatus, Option<NvramError>)> {
        match self.storage.get_variable(name, vendor).await {
            Ok(None) => Ok(None),
            Ok(Some((attr, data, timestamp))) => {
                let attr = SupportedAttrs::from(attr);
                assert!(
                    !attr.contains_unsupported_bits(),
                    "underlying storage should only ever contain valid attributes"
                );

                Ok(Some((attr, data, timestamp)))
            }
            Err(e) => {
                let status = match &e {
                    NvramStorageError::Deserialize => EfiStatus::DEVICE_ERROR,
                    _ => panic!("unexpected NvramStorageError from get_variable"),
                };
                Err((status, Some(NvramError::NvramStorage(e))))
            }
        }
    }

    /// Set a variable identified by `name` + `vendor` with the specified `attr`
    /// and `data`
    ///
    /// - `name`
    ///     - (In) Variable name (a null-terminated UTF-16 string, or `None` if
    ///       the guest passed a `nullptr`)
    ///     - _Note:_ `name` must contain one or more character.
    /// - `in_vendor`
    ///     - (In) Variable vendor guid
    /// - `in_attr`
    ///     - (In) Variable's attributes
    /// - `in_data_size`
    ///     - (In) Length of data to be written
    ///     - If len in `0`, and the EFI_VARIABLE_APPEND_WRITE,
    ///       EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS,
    ///       EFI_VARIABLE_ENHANCED_AUTHENTICATED_ACCESS, or
    ///       EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS are not set,
    ///       the variable will be deleted.
    /// - `data`
    ///     - (In) Variable data (or `None` if the guest passed a `nullptr`)
    pub async fn uefi_set_variable(
        &mut self,
        name: Option<&[u8]>,
        in_vendor: Guid,
        in_attr: u32,
        in_data_size: u32,
        data: Option<Vec<u8>>,
    ) -> NvramResult<()> {
        let name = match name {
            Some(name) => {
                Ucs2LeSlice::from_slice_with_nul(name).map_err(NvramError::NameValidation)
            }
            None => Err(NvramError::NameNull),
        };

        let name = match name {
            Ok(name) => name,
            Err(e) => return NvramResult((), EfiStatus::INVALID_PARAMETER, Some(e)),
        };

        if name.as_bytes() == [0, 0] {
            return NvramResult(
                (),
                EfiStatus::INVALID_PARAMETER,
                Some(NvramError::NameEmpty),
            );
        }

        tracing::trace!(
            %in_vendor,
            %name,
            in_attr,
            in_data_size,
            data = if data.is_some() { "Some([..])" } else { "None" },
            "Set NVRAM variable",
        );

        // Perform some basic attribute validation
        let attr = {
            // Validate that set bits correspond to valid attribute flags
            let attr = EfiVariableAttributes::from(in_attr);
            if attr.contains_unsupported_bits() {
                return NvramResult(
                    (),
                    EfiStatus::INVALID_PARAMETER,
                    Some(NvramError::AttributeNonSpec),
                );
            }

            // From UEFI spec section 8.2:
            //
            // Runtime access to a data variable implies boot service access.
            // Attributes that have EFI_VARIABLE_RUNTIME_ACCESS set must also
            // have EFI_VARIABLE_BOOTSERVICE_ACCESS set. The caller is
            // responsible for following this rule.
            if attr.runtime_access() && !attr.bootservice_access() {
                return NvramResult((), EfiStatus::INVALID_PARAMETER, None);
            }

            // From UEFI spec section 8.2:
            //
            // If both the EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
            // and the EFI_VARIABLE_ENHANCED_AUTHENTICATED_ACCESS attribute are
            // set in a SetVariable() call, then the firmware must return
            // EFI_INVALID_PARAMETER.
            if attr.time_based_authenticated_write_access() && attr.enhanced_authenticated_access()
            {
                return NvramResult((), EfiStatus::INVALID_PARAMETER, None);
            }

            attr
        };

        // Report EFI_UNSUPPORTED for any attributes our implementation doesn't
        // support
        {
            if attr.hardware_error_record() {
                return NvramResult(
                    (),
                    EfiStatus::UNSUPPORTED,
                    Some(NvramError::UnsupportedHardwareErrorRecord),
                );
            }

            if attr.enhanced_authenticated_access() {
                return NvramResult(
                    (),
                    EfiStatus::UNSUPPORTED,
                    Some(NvramError::UnsupportedEnhancedAuthAccess),
                );
            }

            // From UEFI spec section 8.2:
            //
            // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is deprecated and should
            // not be used. Platforms should return EFI_UNSUPPORTED if a caller
            // to SetVariable() specifies this attribute.
            if attr.authenticated_write_access() {
                return NvramResult((), EfiStatus::UNSUPPORTED, None);
            }
        }

        // From UEFI spec section 32.3, Figure 32-4
        //
        // There are various nvram variables that determine what part of secure
        // boot flow we are in. These get used later on in validation, but we'll
        // go ahead and fetch them here...
        //
        // TODO: implement logic around AuditMode and DeployedMode
        let in_setup_mode = match self.get_setup_mode().await {
            Ok(val) => val,
            Err(err) => {
                return NvramResult(
                    (),
                    EfiStatus::DEVICE_ERROR,
                    Some(NvramError::NvramStorage(err)),
                )
            }
        };

        // From UEFI spec section 8.2:
        //
        // Once ExitBootServices() is performed, only variables that have
        // EFI_VARIABLE_RUNTIME_ACCESS and EFI_VARIABLE_NON_VOLATILE set can be
        // set with SetVariable(). Variables that have runtime access but that
        // are not nonvolatile are readonly data variables once
        // ExitBootServices() is performed.
        if self.runtime_state.is_runtime() {
            // At first glance, this seems like a pretty straightforward
            // conditional, but unfortunately, we need to consider the
            // interaction with this other clause:
            //
            //   From UEFI spec section 8.2:
            //
            //   If a preexisting variable is rewritten with no access
            //   attributes specified, the variable will be deleted.
            //
            // As such, if neither access attribute is set, we punt this runtime
            // access check to the implementation of the delete operation,
            // whereby it will make sure the variable being deleted has the
            // correct attributes.
            let missing_access_attrs = !(attr.runtime_access() || attr.bootservice_access());

            if !missing_access_attrs {
                if !attr.runtime_access() || !attr.non_volatile() {
                    return NvramResult(
                        (),
                        EfiStatus::INVALID_PARAMETER,
                        Some(NvramError::InvalidRuntimeAccess),
                    );
                }
            }
        }

        // Check if variable being set is read-only from the Guest
        //
        // Note: these checks are bypassed during pre-boot in order to set the
        // vars' initial values.
        if !self.runtime_state.is_pre_boot() {
            use uefi_specs::hyperv::nvram::vars as hyperv_vars;
            use uefi_specs::uefi::nvram::vars as spec_vars;

            // In true UEFI spec fashion, there are always exceptions...
            enum Exception {
                None,
                SetupMode,
                // TODO: add more exception variants as new RO vars are added
            }

            #[rustfmt::skip]
            let read_only_vars = [
                // UEFI Spec - Table 3-1 Global Variables
                //
                // NOTE: Does not implement all of the read-only
                // variables defined by the UEFI spec in section 3.3
                (spec_vars::SECURE_BOOT(), Exception::None),
                (spec_vars::SETUP_MODE(),  Exception::None),
                (spec_vars::KEK(),         Exception::SetupMode),
                (spec_vars::PK(),          Exception::SetupMode),
                (spec_vars::DBDEFAULT(),   Exception::None),
                // Hyper-V also uses some read-only vars that aren't specified
                // in the UEFI spec
                (hyperv_vars::SECURE_BOOT_ENABLE(),              Exception::None),
                (hyperv_vars::CURRENT_POLICY(),                  Exception::None),
                (hyperv_vars::OS_LOADER_INDICATIONS_SUPPORTED(), Exception::None),
            ];

            let is_readonly = read_only_vars.into_iter().any(|(v, exception)| {
                let skip_check = match exception {
                    Exception::None => false,
                    Exception::SetupMode => in_setup_mode,
                };

                // NOTE: The HCL and worker process implementations perform a
                // case-insensitive comparisons here. A better fix would've
                // been to make all comparisons case _sensitive_, rather than
                // introducing bits of case _insensitivity_ around the nvram
                // implementation. Hindsight is 20-20.
                //
                // In OpenVMM, we don't consider nvram variable names as strings
                // with semantic meaning. Instead, they are akin to a
                // bag-of-bytes that _just so happen_ to have a convenient debug
                // representation when printed out at a UCS-2 string.
                //
                // Case-sensitive comparisons has been confirmed correct with
                // the UEFI team, and as such, it may be worthwhile to backport
                // this change into the C++ implementation as well.
                if !skip_check {
                    v == (in_vendor, name)
                } else {
                    false
                }
            });

            if is_readonly {
                return NvramResult((), EfiStatus::WRITE_PROTECTED, None);
            }
        }

        // The behavior of various operations changes depending on whether or
        // not the specified variable already exists, so go ahead and try to
        // fetch it
        let existing_var = match self.get_variable_inner(name, in_vendor).await {
            Ok(v) => v,
            Err((status, err)) => return NvramResult((), status, err),
        };

        let (in_data_size, data, timestamp) = {
            if !attr.time_based_authenticated_write_access() {
                // nothing fancy here, just some regular 'ol data...
                let timestamp = EFI_TIME::new_zeroed();

                (in_data_size, data, timestamp)
            } else {
                // the payload includes an authenticated variable header
                //
                // UEFI spec 8.2.2 - Using the EFI_VARIABLE_AUTHENTICATION_2 descriptor
                use uefi_specs::uefi::nvram::EFI_VARIABLE_AUTHENTICATION_2;
                use uefi_specs::uefi::signing::EFI_CERT_TYPE_PKCS7_GUID;
                use uefi_specs::uefi::signing::WIN_CERTIFICATE_UEFI_GUID;
                use uefi_specs::uefi::signing::WIN_CERT_TYPE_EFI_GUID;

                tracing::trace!(
                    "variable is attempting to use TIME_BASED_AUTHENTICATED_WRITE_ACCESS"
                );

                // data cannot be null
                let data = match data {
                    Some(data) => data,
                    None => {
                        return NvramResult(
                            (),
                            EfiStatus::INVALID_PARAMETER,
                            Some(NvramError::DataNull),
                        )
                    }
                };

                // extract EFI_VARIABLE_AUTHENTICATION_2 header
                let auth_hdr =
                    match EFI_VARIABLE_AUTHENTICATION_2::read_from_prefix(data.as_slice()) {
                        Some(hdr) => hdr,
                        None => {
                            return NvramResult(
                                (),
                                EfiStatus::SECURITY_VIOLATION,
                                Some(NvramError::AuthError(AuthError::NotEnoughHdrData)),
                            )
                        }
                    };
                let timestamp = auth_hdr.timestamp;
                let auth_info = auth_hdr.auth_info;

                // split off the variable-length WIN_CERTIFICATE_UEFI_GUID cert
                // data from the variable length payload
                let (pkcs7_data, var_data) = {
                    let auth_info_offset = size_of_val(&auth_hdr.timestamp);

                    // use the header's length value to extract the
                    // WIN_CERTIFICATE_UEFI_GUID struct + variable length payload
                    if data[auth_info_offset..].len() < (auth_info.header.length as usize) {
                        return NvramResult(
                            (),
                            EfiStatus::SECURITY_VIOLATION,
                            Some(NvramError::AuthError(AuthError::NotEnoughCertData)),
                        );
                    }
                    let (auth_info_hdr_and_cert, var_data) =
                        data[auth_info_offset..].split_at(auth_info.header.length as usize);

                    // ...and then strip off the WIN_CERTIFICATE_UEFI_GUID
                    // struct from the variable length payload
                    let pkcs7_data = match auth_info_hdr_and_cert
                        .get(size_of::<WIN_CERTIFICATE_UEFI_GUID>()..)
                    {
                        Some(data) => data,
                        None => {
                            return NvramResult(
                                (),
                                EfiStatus::SECURITY_VIOLATION,
                                Some(NvramError::AuthError(AuthError::NotEnoughCertData)),
                            );
                        }
                    };

                    (pkcs7_data, var_data)
                };

                // validate WIN_CERTIFICATE header construction
                if auth_info.header.revision != 0x0200 {
                    return NvramResult(
                        (),
                        EfiStatus::SECURITY_VIOLATION,
                        Some(NvramError::AuthError(AuthError::InvalidWinCertHeader)),
                    );
                }

                // validate correct cert type is being used
                if auth_info.header.certificate_type != WIN_CERT_TYPE_EFI_GUID
                    || auth_info.cert_type != EFI_CERT_TYPE_PKCS7_GUID
                {
                    return NvramResult(
                        (),
                        EfiStatus::SECURITY_VIOLATION,
                        Some(NvramError::AuthError(AuthError::IncorrectCertType)),
                    );
                }

                // validate timestamp according to spec
                if timestamp.pad1 != 0
                    || timestamp.nanosecond != 0
                    || timestamp.timezone.0 != 0
                    || u8::from(timestamp.daylight) != 0
                    || timestamp.pad2 != 0
                {
                    return NvramResult(
                        (),
                        EfiStatus::SECURITY_VIOLATION,
                        Some(NvramError::AuthError(AuthError::IncorrectTimestamp)),
                    );
                }

                // if a variable already exists, make sure the timestamp is
                // newer (or in the case of Append, clamp the timestamp to the
                // existing timestamp)
                let orig_timestamp = timestamp; // original value must be used when performing variable auth
                let timestamp = {
                    let mut timestamp = timestamp;
                    if let Some((_, _, existing_timestamp)) = existing_var {
                        let is_newer = (
                            timestamp.year,
                            timestamp.month,
                            timestamp.day,
                            timestamp.hour,
                            timestamp.minute,
                            timestamp.second,
                            timestamp.nanosecond,
                        )
                            .cmp(&(
                                existing_timestamp.year,
                                existing_timestamp.month,
                                existing_timestamp.day,
                                existing_timestamp.hour,
                                existing_timestamp.minute,
                                existing_timestamp.second,
                                existing_timestamp.nanosecond,
                            ))
                            .is_gt();

                        if !is_newer {
                            if !attr.append_write() {
                                return NvramResult(
                                    (),
                                    EfiStatus::SECURITY_VIOLATION,
                                    Some(NvramError::AuthError(AuthError::OldTimestamp)),
                                );
                            } else {
                                timestamp = existing_timestamp
                            }
                        }
                    }
                    timestamp
                };

                // If PK is present, then we need to authenticate the payload with KEK or PK.
                let pk_var = {
                    let (pk_vendor, pk_name) = uefi_specs::uefi::nvram::vars::PK();
                    match self.get_variable_inner(pk_name, pk_vendor).await {
                        Ok(v) => v,
                        Err((status, err)) => return NvramResult((), status, err),
                    }
                };

                // From UEFI spec section 8.2.2:
                //
                // If the variable SetupMode==1, and the variable is a secure
                // boot policy variable, then the firmware implementation shall
                // consider the checks in the following steps 4 and 5 to have
                // passed, and proceed with updating the variable value as
                // outlined below.
                //
                // (our implementation extends this condition to include
                // "is nvram currently in the pre-boot state")
                let bypass_auth = self.runtime_state.is_pre_boot()
                    || (in_setup_mode
                        && uefi_specs::uefi::nvram::is_secure_boot_policy_var(in_vendor, name));

                if pk_var.is_some() && !bypass_auth {
                    tracing::trace!("pk exists, attempting to actually authenticate var...");

                    let parsed_auth_var = ParsedAuthVar {
                        name,
                        vendor: in_vendor,
                        attr: attr.into(),
                        timestamp: orig_timestamp,
                        pkcs7_data,
                        var_data,
                    };

                    // The UEFI spec has several special-cased authenticated vars.
                    // At the moment, our implementation only supports a handful of these cases.
                    enum AuthVarKind {
                        Db,
                        PkKek,
                        Unsupported,
                    }

                    let var_kind = match (in_vendor, name) {
                        v if v == uefi_specs::uefi::nvram::vars::DB() => AuthVarKind::Db,
                        v if v == uefi_specs::uefi::nvram::vars::DBX() => AuthVarKind::Db,
                        v if v == uefi_specs::uefi::nvram::vars::PK() => AuthVarKind::PkKek,
                        v if v == uefi_specs::uefi::nvram::vars::KEK() => AuthVarKind::PkKek,
                        // TODO: add support for:
                        // - dbr, dbt
                        // - OsRecoveryOrder, OsRecovery####
                        // - private auth vars
                        _ => AuthVarKind::Unsupported,
                    };

                    let auth_res = match var_kind {
                        AuthVarKind::Db => {
                            // UEFI Spec - 8.2.2 Using the EFI_VARIABLE_AUTHENTICATION_2 descriptor
                            //
                            // If the variable is the “db”, “dbt”, “dbr”, or “dbx” variable mentioned
                            // in step 3, verify that the signer’s certificate chains to a certificate
                            // in the Key Exchange Key database (or that the signature was made with
                            // the current Platform Key).
                            match self
                                .authenticate_var(
                                    uefi_specs::uefi::nvram::vars::KEK(),
                                    parsed_auth_var,
                                )
                                .await
                            {
                                Ok(res) => Ok(res),
                                // If authentication with KEK fails, then try PK authentication.
                                Err(_) => {
                                    self.authenticate_var(
                                        uefi_specs::uefi::nvram::vars::PK(),
                                        parsed_auth_var,
                                    )
                                    .await
                                }
                            }
                        }
                        AuthVarKind::PkKek => {
                            // UEFI Spec - 8.2.2 Using the EFI_VARIABLE_AUTHENTICATION_2 descriptor
                            //
                            // If the variable is the global PK variable or the global KEK variable,
                            // verify that the signature has been made with the current Platform Key.
                            self.authenticate_var(
                                uefi_specs::uefi::nvram::vars::PK(),
                                parsed_auth_var,
                            )
                            .await
                        }
                        AuthVarKind::Unsupported => {
                            // TODO: the HCL treats this case the same as the `PkKek` case, but that
                            // seems wrong...
                            return NvramResult(
                                (),
                                EfiStatus::SECURITY_VIOLATION,
                                Some(NvramError::AuthError(AuthError::UnsupportedAuthVar)),
                            );
                        }
                    };

                    if let Err((status, err)) = auth_res {
                        return NvramResult((), status, err);
                    }
                }

                // now that everything has been validated, we can strip off the
                // auth header and go on to actually performing the requested
                // operation of the remaining payload.
                let total_auth_hdr_len =
                    size_of_val(&auth_hdr.timestamp) + (auth_info.header.length as usize);

                (
                    in_data_size - total_auth_hdr_len as u32,
                    Some({
                        let mut data = data;
                        data.drain(..total_auth_hdr_len);
                        data
                    }),
                    timestamp,
                )
            }
        };

        // SetVariable is pretty weird, as it overloads a single method to
        // perform a whole bunch of different variable operations, such as
        // removing, updating, appending, and setting variables.
        //
        // Determining which specific operation is being requested requires
        // navigating a hodgepodge of various rules and indicators, such as the
        // length of the data passed in, what attributes are set, etc...
        #[derive(Debug)]
        enum VariableOperation {
            Set,
            Append,
            Delete,
        }

        let op = {
            let is_doing_append = attr.append_write();
            let is_doing_delete = {
                // From UEFI spec section 8.2:
                //
                // If a preexisting variable is rewritten with no access attributes
                // specified, the variable will be deleted.
                let missing_access_attrs = !(attr.runtime_access() || attr.bootservice_access());

                // From UEFI spec section 8.2:
                //
                // Unless the EFI_VARIABLE_APPEND_WRITE,
                // EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS, or
                // EFI_VARIABLE_ENHANCED_AUTHENTICATED_ACCESS attribute is set (see
                // below), using SetVariable() with a DataSize of zero will cause the
                // entire variable to be deleted
                let zero_data_size = in_data_size == 0 && !is_doing_append;

                missing_access_attrs || zero_data_size
            };

            // append takes precedence over delete/set
            if is_doing_append {
                VariableOperation::Append
            } else if is_doing_delete {
                VariableOperation::Delete
            } else {
                VariableOperation::Set
            }
        };

        tracing::trace!(?op, "SetVariable is performing");

        // normalize attr bits (i.e: strip off APPEND_WRITE indicator)
        let attr = attr.with_append_write(false);

        // Drop down to using `SupportedAttrs` instead of
        // `EfiVariableAttributes` to make things easier to follow.
        let attr = SupportedAttrs::from(u32::from(attr));

        let res = match op {
            VariableOperation::Append => {
                // This implementation only supports non-volatile variables.
                // Volatile variables should be handled within UEFI itself.
                if !attr.non_volatile() {
                    return NvramResult(
                        (),
                        EfiStatus::UNSUPPORTED,
                        Some(NvramError::UnsupportedVolatile),
                    );
                }

                // data *might* get modified in the case that it contains an
                // EFI_SIGNATURE_LIST, and duplicates need to get filtered out
                // (hence the use of `mut`)
                let mut data = match (in_data_size, data) {
                    // Appending with zero data will silently do nothing,
                    // regardless if a variable already exists
                    (0, _) => return NvramResult((), EfiStatus::SUCCESS, None),
                    // If data len is non-zero, data cannot be nullptr
                    (_, None) => {
                        return NvramResult((), EfiStatus::SUCCESS, Some(NvramError::DataNull))
                    }
                    (_, Some(data)) => data,
                };

                if let Some((existing_attr, existing_data, _)) = existing_var {
                    // attempting to fetch a boot-time variable at runtime
                    if self.runtime_state.is_runtime() && !existing_attr.runtime_access() {
                        // ...will fail, since the variable "doesn't exist" at runtime
                        return NvramResult(
                            (),
                            EfiStatus::NOT_FOUND,
                            Some(NvramError::InvalidRuntimeAccess),
                        );
                    }

                    // From UEFI spec section 8.2:
                    //
                    // If a preexisting variable is rewritten with different
                    // attributes, SetVariable() shall not modify the variable
                    // and shall return EFI_INVALID_PARAMETER.
                    if attr != existing_attr {
                        return NvramResult(
                            (),
                            EfiStatus::INVALID_PARAMETER,
                            Some(NvramError::AttributeMismatch),
                        );
                    }

                    // From UEFI spec section 8.2:
                    //
                    // For variables with the GUID EFI_IMAGE_SECURITY_DATABASE_GUID
                    // (i.e. where the data buffer is formatted as EFI_SIGNATURE_LIST),
                    // the driver shall not perform an append of EFI_SIGNATURE_DATA
                    // values that are already part of the existing variable value.
                    //
                    // Note: This situation is not considered an error, and shall in itself
                    // not cause a status code other than EFI_SUCCESS to be returned or the
                    // timestamp associated with the variable not to be updated.
                    if attr.time_based_authenticated_write_access() {
                        use signature_list::SignatureDataPayload;

                        let existing_signatures = ParseSignatureLists::new(&existing_data)
                            .collect_signature_set()
                            .expect("existing var must contain valid list of EFI_SIGNATURE_LIST");

                        // NOTE: the Hyper-V implementation filter signature lists in-place. While
                        // that *would* be more efficient, it also makes the code a _lot_ harder to
                        // understand, so in OpenVMM, lets keep things simple and just allocate a new
                        // buffer for the filtered signatures.
                        let filtered_signatures = ParseSignatureLists::new(&data)
                            .collect_signature_lists(|header, sig| {
                                let sig: &[u8] = match sig {
                                    SignatureDataPayload::X509(buf) => buf,
                                    SignatureDataPayload::Sha256(buf) => buf,
                                };

                                !existing_signatures.contains(&(header, Cow::Borrowed(sig)))
                            });

                        // it *is* an error if the provided signature list is malformed
                        let filtered_signatures = match filtered_signatures {
                            Ok(sigs) => sigs,
                            Err(e) => {
                                return NvramResult(
                                    (),
                                    EfiStatus::INVALID_PARAMETER,
                                    Some(NvramError::SignatureList(e)),
                                )
                            }
                        };

                        let mut new_data = Vec::new();
                        for list in filtered_signatures {
                            list.extend_as_spec_signature_list(&mut new_data);
                        }

                        // update data to point at the new signature list we just created
                        data = new_data;
                    }
                }

                // All validation checks have passed, so perform the operation
                match self
                    .storage
                    .append_variable(name, in_vendor, data.to_vec(), timestamp)
                    .await
                {
                    Ok(true) => NvramResult((), EfiStatus::SUCCESS, None),
                    Ok(false) => NvramResult((), EfiStatus::NOT_FOUND, None),
                    Err(e) => {
                        let status = match &e {
                            NvramStorageError::Commit(_) => EfiStatus::DEVICE_ERROR,
                            NvramStorageError::OutOfSpace => EfiStatus::OUT_OF_RESOURCES,
                            NvramStorageError::VariableNameTooLong => EfiStatus::INVALID_PARAMETER,
                            NvramStorageError::VariableDataTooLong => EfiStatus::INVALID_PARAMETER,
                            _ => {
                                panic!("unexpected NvramStorageError from append_variable")
                            }
                        };

                        NvramResult((), status, Some(NvramError::NvramStorage(e)))
                    }
                }
            }
            VariableOperation::Delete => {
                if let Some((existing_attr, _, _)) = existing_var {
                    // attempting to delete an existing boot-time variable at runtime
                    if self.runtime_state.is_runtime() && !existing_attr.runtime_access() {
                        // ...will fail, since the variable "doesn't exist" at runtime
                        return NvramResult(
                            (),
                            EfiStatus::NOT_FOUND,
                            Some(NvramError::InvalidRuntimeAccess),
                        );
                    }
                }

                // All validation checks have passed, so perform the operation
                match self.storage.remove_variable(name, in_vendor).await {
                    Ok(true) => NvramResult((), EfiStatus::SUCCESS, None),
                    Ok(false) => NvramResult((), EfiStatus::NOT_FOUND, None),
                    Err(e) => {
                        let status = match &e {
                            NvramStorageError::Commit(_) => EfiStatus::DEVICE_ERROR,
                            NvramStorageError::OutOfSpace => EfiStatus::OUT_OF_RESOURCES,
                            NvramStorageError::VariableNameTooLong => EfiStatus::INVALID_PARAMETER,
                            NvramStorageError::VariableDataTooLong => EfiStatus::INVALID_PARAMETER,
                            _ => {
                                panic!("unexpected NvramStorageError from remove_variable")
                            }
                        };

                        NvramResult((), status, Some(NvramError::NvramStorage(e)))
                    }
                }
            }
            VariableOperation::Set => {
                // This implementation only supports non-volatile variables.
                // Volatile variables should be handled within UEFI itself.
                //
                // The exceptions are variables that are controlled/injected by the loader.
                // This includes secure boot enablement (volatile by specification),
                // as well as the private Hyper-V OsLoaderIndications and
                // OsLoaderIndicationsSupported variables, which are volatile variables
                // that are injected via the non-volatile store. The dbDefault variable
                // is also an exception.
                if !attr.non_volatile() {
                    use uefi_specs::hyperv::nvram::vars as hyperv_vars;
                    use uefi_specs::uefi::nvram::vars::DBDEFAULT;
                    use uefi_specs::uefi::nvram::vars::SECURE_BOOT;
                    let allowed_volatile = [
                        hyperv_vars::OS_LOADER_INDICATIONS(),
                        hyperv_vars::OS_LOADER_INDICATIONS_SUPPORTED(),
                        DBDEFAULT(),
                        SECURE_BOOT(),
                    ];

                    let is_allowed = allowed_volatile.into_iter().any(|v| v == (in_vendor, name));

                    if !is_allowed {
                        return NvramResult(
                            (),
                            EfiStatus::UNSUPPORTED,
                            Some(NvramError::UnsupportedVolatile),
                        );
                    }
                }

                // if we are doing a variable set, then data cannot be a nullptr
                let data = match data {
                    Some(data) => data,
                    None => {
                        return NvramResult(
                            (),
                            EfiStatus::INVALID_PARAMETER,
                            Some(NvramError::DataNull),
                        )
                    }
                };

                if let Some((existing_attr, _, _)) = existing_var {
                    // attempting to overwrite an existing boot-time variable
                    if self.runtime_state.is_runtime() && !existing_attr.runtime_access() {
                        // This is a weird case, since calling GetVariable would
                        // actually return `EFI_NOT_FOUND` (as the variable is
                        // "hidden" at runtime), implying that it should be
                        // _fine_ to set the variable.
                        //
                        // It seems that unless we have some kind of "runtime
                        // shadow variable" support, it's possible to use
                        // `SetVariable` as a way to check if boot-time
                        // variables _actually_ exist...
                        //
                        // The UEFI folks seem to think this gap is _fine_, as
                        // it doesn't give access to protected data - just the
                        // fact that that the boot time var exists.
                        //
                        // So... while this isn't a _great_ solution, it matches
                        // all existing implementations (both within and outside
                        // Hyper-V)
                        return NvramResult(
                            (),
                            EfiStatus::WRITE_PROTECTED,
                            Some(NvramError::InvalidRuntimeAccess),
                        );
                    }

                    // From UEFI spec section 8.2:
                    //
                    // If a preexisting variable is rewritten with different
                    // attributes, SetVariable() shall not modify the
                    // variable and shall return EFI_INVALID_PARAMETER.
                    if attr != existing_attr {
                        return NvramResult(
                            (),
                            EfiStatus::INVALID_PARAMETER,
                            Some(NvramError::AttributeMismatch),
                        );
                    }
                }

                // All validation checks have passed, so perform the operation
                match self
                    .storage
                    .set_variable(name, in_vendor, attr.into(), data.to_vec(), timestamp)
                    .await
                {
                    Ok(_) => NvramResult((), EfiStatus::SUCCESS, None),
                    Err(e) => {
                        let status = match &e {
                            NvramStorageError::Commit(_) => EfiStatus::DEVICE_ERROR,
                            NvramStorageError::OutOfSpace => EfiStatus::OUT_OF_RESOURCES,
                            NvramStorageError::VariableNameTooLong => EfiStatus::INVALID_PARAMETER,
                            NvramStorageError::VariableDataTooLong => EfiStatus::INVALID_PARAMETER,
                            _ => panic!("unexpected NvramStorageError from set_variable"),
                        };

                        NvramResult((), status, Some(NvramError::NvramStorage(e)))
                    }
                }
            }
        };

        // If we modified the PK variable, we need to update the SetupMode
        // variable accordingly.
        if res.is_success() && (in_vendor, name) == uefi_specs::uefi::nvram::vars::PK() {
            if let Err(e) = self.update_setup_mode().await {
                return NvramResult(
                    (),
                    EfiStatus::DEVICE_ERROR,
                    Some(NvramError::UpdateSetupMode(e)),
                );
            }
        }

        res
    }

    #[cfg(not(feature = "auth-var-verify-crypto"))]
    async fn authenticate_var(
        &mut self,
        // NOTE: Due to a compiler limitation with async fn, 'static bound was removed here
        // https://github.com/rust-lang/rust/issues/63033#issuecomment-521234696
        _: (Guid, &Ucs2LeSlice),
        _: ParsedAuthVar<'_>,
    ) -> Result<(), (EfiStatus, Option<NvramError>)> {
        tracing::warn!("compiled without 'auth-var-verify-crypto' - unconditionally failing auth var validation!");
        Err((EfiStatus::SECURITY_VIOLATION, None))
    }

    /// Authenticate the given variable against the signatures stored in the
    /// specified EFI_SIGNATURE_LIST
    #[cfg(feature = "auth-var-verify-crypto")]
    async fn authenticate_var(
        &mut self,
        // NOTE: Due to a compiler limitation with async fn, 'static bound was removed here
        // https://github.com/rust-lang/rust/issues/63033#issuecomment-521234696
        (key_var_name, key_var_vendor): (Guid, &Ucs2LeSlice),
        auth_var: ParsedAuthVar<'_>,
    ) -> Result<(), (EfiStatus, Option<NvramError>)> {
        let signature_lists = match self
            .get_variable_inner(key_var_vendor, key_var_name)
            .await?
        {
            Some((_, data, _)) => data,
            None => return Err((EfiStatus::SECURITY_VIOLATION, None)),
        };

        // the nitty-gritty of how authentication works is best left to a separate module...
        match auth_var_crypto::authenticate_variable(&signature_lists, auth_var) {
            Ok(true) => Ok(()),
            Ok(false) => Err((
                EfiStatus::SECURITY_VIOLATION,
                Some(NvramError::AuthError(AuthError::CryptoError)),
            )),
            Err(e) if e.key_var_error() => {
                panic!("existing signature list must contain valid data: {}", e)
            }
            // all other errors are due to malformed auth_var data
            Err(e) => Err((
                EfiStatus::SECURITY_VIOLATION,
                Some(NvramError::AuthError(AuthError::CryptoFormat(e))),
            )),
        }
    }

    /// Return the variable immediately following the variable identified by
    /// `name` + `vendor` `key`.
    ///
    /// If `name` is an empty string, the first variable is returned.
    ///
    /// - `name`
    ///     - (In) Variable name (a null-terminated UTF-16 string, or `None` if
    ///       the guest passed a `nullptr`)
    /// - `in_out_name_size`
    ///     - (In) Length of the provided `name`
    ///     - (Out) Length of the next variable name
    ///     - _Note:_ If there is insufficient space in the name buffer to store
    ///       the next variable, `in_out_name_size` will be updated with the
    ///       size required to store the variable.
    /// - `vendor`
    ///     - (In) Variable vendor guid
    pub async fn uefi_get_next_variable(
        &mut self,
        in_out_name_size: &mut u32,
        name: Option<&[u8]>,
        vendor: Guid,
    ) -> NvramResult<Option<(Vec<u8>, Guid)>> {
        let name = match name {
            Some(name) => {
                Ucs2LeSlice::from_slice_with_nul(name).map_err(NvramError::NameValidation)
            }
            None => Err(NvramError::NameNull),
        };

        let name = match name {
            Ok(name) => name,
            Err(e) => return NvramResult(None, EfiStatus::INVALID_PARAMETER, Some(e)),
        };

        tracing::trace!(?vendor, ?name, in_out_name_size, "Next NVRAM variable",);

        // As per UEFI spec: if an empty null-terminated string is passed to
        // GetNextVariable, the first variable should be returned
        let mut res = if name.as_bytes() == [0, 0] {
            self.storage.next_variable(None).await
        } else {
            self.storage.next_variable(Some((name, vendor))).await
        };

        loop {
            match res {
                Ok(NextVariable::EndOfList) => {
                    return NvramResult(None, EfiStatus::NOT_FOUND, None)
                }
                Ok(NextVariable::InvalidKey) => {
                    return NvramResult(None, EfiStatus::INVALID_PARAMETER, None);
                }
                Ok(NextVariable::Exists { name, vendor, attr }) => {
                    let attr = EfiVariableAttributes::from(attr);
                    assert!(
                        !attr.contains_unsupported_bits(),
                        "underlying storage should only ever contain valid attributes"
                    );

                    // From UEFI spec section 8.2:
                    //
                    // Once EFI_BOOT_SERVICES.ExitBootServices() is performed,
                    // variables that are only visible during boot services will
                    // no longer be returned.
                    //
                    // i.e: continue iterating
                    if self.runtime_state.is_runtime() && !attr.runtime_access() {
                        res = self
                            .storage
                            .next_variable(Some((name.as_ref(), vendor)))
                            .await;
                        continue;
                    }

                    let guest_buf_len = *in_out_name_size as usize;
                    *in_out_name_size = name.as_bytes().len() as u32;
                    if guest_buf_len < name.as_bytes().len() {
                        return NvramResult(None, EfiStatus::BUFFER_TOO_SMALL, None);
                    }

                    return NvramResult(
                        Some((name.into_inner(), vendor)),
                        EfiStatus::SUCCESS,
                        None,
                    );
                }
                Err(e) => {
                    let status = match &e {
                        NvramStorageError::Deserialize => EfiStatus::DEVICE_ERROR,
                        _ => panic!("unexpected NvramStorageError from next_variable"),
                    };

                    return NvramResult(None, status, Some(NvramError::NvramStorage(e)));
                }
            }
        }
    }
}

mod save_restore {
    use super::*;
    use vmcore::save_restore::RestoreError;
    use vmcore::save_restore::SaveError;
    use vmcore::save_restore::SaveRestore;

    mod state {
        use mesh::payload::Protobuf;

        #[derive(Protobuf)]
        #[mesh(package = "firmware.uefi.nvram.spec")]
        pub enum SavedRuntimeState {
            #[mesh(1)]
            PreBoot,
            #[mesh(2)]
            Boot,
            #[mesh(3)]
            Runtime,
        }

        #[derive(Protobuf)]
        #[mesh(package = "firmware.uefi.nvram.spec")]
        pub struct SavedState {
            #[mesh(1)]
            pub runtime_state: SavedRuntimeState,
        }
    }

    impl<S: InspectableNvramStorage> SaveRestore for NvramSpecServices<S> {
        type SavedState = state::SavedState;

        fn save(&mut self) -> Result<Self::SavedState, SaveError> {
            Ok(state::SavedState {
                runtime_state: match self.runtime_state {
                    RuntimeState::PreBoot => state::SavedRuntimeState::PreBoot,
                    RuntimeState::Boot => state::SavedRuntimeState::Boot,
                    RuntimeState::Runtime => state::SavedRuntimeState::Runtime,
                },
            })
        }

        fn restore(&mut self, state: Self::SavedState) -> Result<(), RestoreError> {
            let state::SavedState { runtime_state } = state;

            self.runtime_state = match runtime_state {
                state::SavedRuntimeState::PreBoot => RuntimeState::PreBoot,
                state::SavedRuntimeState::Boot => RuntimeState::Boot,
                state::SavedRuntimeState::Runtime => RuntimeState::Runtime,
            };

            Ok(())
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use uefi_nvram_storage::in_memory::InMemoryNvram;
    // TODO: wchz returns UTF-16 strings, _not_ UCS-2 strings. This works fine
    // when using english variable names, but things will _not_ work as expected
    // if one tries to use any particularly "exotic" chars (that cannot be
    // represented in UCS-2).
    use pal_async::async_test;
    use wchar::wchz;
    use zerocopy::AsBytes;

    /// Extension trait around `NvramServices` that makes it easier to use the
    /// API outside the context of the UEFI device
    #[async_trait::async_trait]
    trait NvramServicesTestExt {
        async fn set_test_var(&mut self, name: &[u8], attr: u32, data: &[u8]) -> NvramResult<()>;
        async fn get_test_var(&mut self, name: &[u8]) -> NvramResult<(u32, Option<Vec<u8>>)>;
        async fn get_next_test_var(
            &mut self,
            name: Option<Vec<u8>>,
        ) -> NvramResult<Option<Vec<u8>>>;
    }

    #[async_trait::async_trait]
    impl<S: InspectableNvramStorage> NvramServicesTestExt for NvramSpecServices<S> {
        async fn set_test_var(&mut self, name: &[u8], attr: u32, data: &[u8]) -> NvramResult<()> {
            let vendor = Guid::default();

            self.uefi_set_variable(
                Some(name),
                vendor,
                attr,
                data.len() as u32,
                Some(data.to_vec()),
            )
            .await
        }

        async fn get_test_var(&mut self, name: &[u8]) -> NvramResult<(u32, Option<Vec<u8>>)> {
            let vendor = Guid::default();

            let mut attr = 0;
            let NvramResult(data, status, err) = self
                .uefi_get_variable(Some(name), vendor, &mut attr, &mut 256, false)
                .await;

            NvramResult((attr, data), status, err)
        }

        async fn get_next_test_var(
            &mut self,
            name: Option<Vec<u8>>,
        ) -> NvramResult<Option<Vec<u8>>> {
            let vendor = Guid::default();

            let NvramResult(name_guid, status, err) = self
                .uefi_get_next_variable(&mut 256, name.as_deref(), vendor)
                .await;

            NvramResult(name_guid.map(|(n, _)| n.to_vec()), status, err)
        }
    }

    trait NvramRetTestExt<T> {
        fn unwrap_efi_success(self) -> T;
    }

    impl<T> NvramRetTestExt<T> for NvramResult<T> {
        #[track_caller]
        fn unwrap_efi_success(self) -> T {
            let NvramResult(val, status, err) = self;
            if let Some(err) = err {
                panic!("{}", err)
            }
            assert_eq!(status, EfiStatus::SUCCESS);
            val
        }
    }

    #[async_test]
    async fn runtime_vars() {
        let nvram_storage = InMemoryNvram::new();
        let mut nvram = NvramSpecServices::new(nvram_storage);

        nvram.prepare_for_boot();

        let name1 = wchz!(u16, "var1").as_bytes();
        let name2 = wchz!(u16, "var2").as_bytes();
        let name3 = wchz!(u16, "var3").as_bytes();
        let name4 = wchz!(u16, "var4").as_bytes();

        let dummy_data = b"dummy data".to_vec();

        let runtime_attr = (EfiVariableAttributes::DEFAULT_ATTRIBUTES).into();
        let no_runtime_attr = EfiVariableAttributes::DEFAULT_ATTRIBUTES
            .with_runtime_access(false)
            .into();

        // set some vars
        nvram
            .set_test_var(name1, runtime_attr, &dummy_data)
            .await
            .unwrap_efi_success();
        nvram
            .set_test_var(name2, no_runtime_attr, &dummy_data)
            .await
            .unwrap_efi_success();
        nvram
            .set_test_var(name3, runtime_attr, &dummy_data)
            .await
            .unwrap_efi_success();
        nvram
            .set_test_var(name4, no_runtime_attr, &dummy_data)
            .await
            .unwrap_efi_success();

        // ensure they can all be accessed in pre-runtime environment

        // access them individually
        let (attr, data) = nvram.get_test_var(name1).await.unwrap_efi_success();
        assert_eq!(attr, runtime_attr);
        assert_eq!(data, Some(dummy_data.clone()));

        let (attr, data) = nvram.get_test_var(name2).await.unwrap_efi_success();
        assert_eq!(attr, no_runtime_attr);
        assert_eq!(data, Some(dummy_data.clone()));

        let (attr, data) = nvram.get_test_var(name3).await.unwrap_efi_success();
        assert_eq!(attr, runtime_attr);
        assert_eq!(data, Some(dummy_data.clone()));

        let (attr, data) = nvram.get_test_var(name4).await.unwrap_efi_success();
        assert_eq!(attr, no_runtime_attr);
        assert_eq!(data, Some(dummy_data.clone()));

        // access them sequentially
        let mut name = Some(wchz!(u16, "").as_bytes().into());
        name = nvram.get_next_test_var(name).await.unwrap_efi_success();
        assert_eq!(name, Some(name1.into()));

        name = nvram.get_next_test_var(name).await.unwrap_efi_success();
        assert_eq!(name, Some(name2.into()));

        name = nvram.get_next_test_var(name).await.unwrap_efi_success();
        assert_eq!(name, Some(name3.into()));

        name = nvram.get_next_test_var(name).await.unwrap_efi_success();
        assert_eq!(name, Some(name4.into()));

        let NvramResult(name, status, err) = nvram.get_next_test_var(name).await;
        assert!(name.is_none());
        assert_eq!(status, EfiStatus::NOT_FOUND);
        assert!(err.is_none());

        // ensure vars are hidden once runtime toggle is set
        nvram.exit_boot_services();

        // try to set non-runtime access var
        let NvramResult(_, status, err) = nvram
            .set_test_var(
                wchz!(u16, "non-volatile").as_bytes(),
                no_runtime_attr,
                &dummy_data,
            )
            .await;
        assert_eq!(status, EfiStatus::INVALID_PARAMETER);
        assert!(matches!(err, Some(NvramError::InvalidRuntimeAccess)));

        // access them individually
        let (attr, data) = nvram.get_test_var(name1).await.unwrap_efi_success();
        assert_eq!(attr, runtime_attr);
        assert_eq!(data, Some(dummy_data.clone()));

        let NvramResult((attr, data), status, err) = nvram.get_test_var(name2).await;
        assert_eq!(attr, 0);
        assert_eq!(data, None);
        assert_eq!(status, EfiStatus::NOT_FOUND);
        assert!(matches!(err, Some(NvramError::InvalidRuntimeAccess)));

        let (attr, data) = nvram.get_test_var(name3).await.unwrap_efi_success();
        assert_eq!(attr, runtime_attr);
        assert_eq!(data, Some(dummy_data));

        let NvramResult((attr, data), status, err) = nvram.get_test_var(name4).await;
        assert_eq!(attr, 0);
        assert_eq!(data, None);
        assert_eq!(status, EfiStatus::NOT_FOUND);
        assert!(matches!(err, Some(NvramError::InvalidRuntimeAccess)));

        // access them sequentially
        let mut name = Some(wchz!(u16, "").as_bytes().into());
        name = nvram.get_next_test_var(name).await.unwrap_efi_success();
        assert_eq!(name, Some(name1.into()));

        // DON'T read name2

        name = nvram.get_next_test_var(name).await.unwrap_efi_success();
        assert_eq!(name, Some(name3.into()));

        // DON'T read name4

        let NvramResult(name, status, err) = nvram.get_next_test_var(name).await;
        assert!(name.is_none());
        assert_eq!(status, EfiStatus::NOT_FOUND);
        assert!(err.is_none());
    }
}