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
// Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use crate::algorithm::structures::SensitiveData;
use crate::constants::algorithm::HashingAlgorithm;
use crate::handles::{AuthHandle, NvIndexHandle, ObjectHandle, TpmHandle};
use crate::nv::storage::{NvAuthorization, NvPublic};
use crate::structures::{
    Auth, Data, Digest, DigestList, HashcheckTicket, MaxBuffer, MaxNvBuffer, Name, Nonce,
    PcrSelectionList, PublicKeyRSA,
};
use crate::tcti::Tcti;
use crate::tss2_esys::*;
use crate::utils::{
    Hierarchy, PcrData, PublicParmsUnion, Signature, TpmaSession, TpmaSessionBuilder, TpmsContext,
};
use crate::{Error, Result, WrapperErrorKind as ErrorKind};
use log::{error, info};
use mbox::MBox;
use std::collections::HashSet;
use std::convert::{TryFrom, TryInto};
use std::ffi::CString;
use std::ptr::{null, null_mut};
/// Safe abstraction over an ESYS_CONTEXT.
///
/// Serves as a low-level abstraction interface to the TPM, providing a thin wrapper around the
/// `unsafe` FFI calls. It is meant for more advanced uses of the TSS where control over all
/// parameters is necessary or important.
///
/// The methods it exposes take the parameters advertised by the specification, with some of the
/// parameters being passed as generated by `bindgen` and others in a more convenient/Rust-efficient
/// way.
///
/// The context also keeps track of all object allocated and deallocated through it and, before
/// being dropped, will attempt to close all outstanding handles. However, care must be taken by
/// the client to not exceed the maximum number of slots available from the RM.
///
/// Code safety-wise, the methods should cover the two kinds of problems that might arise:
/// * in terms of memory safety, all parameters passed down to the TSS are verified and the library
/// stack is then trusted to provide back valid outputs
/// * in terms of thread safety, all methods require a mutable reference to the context object,
/// ensuring that no two threads can use the context at the same time for an operation (barring use
/// of `unsafe` constructs on the client side)
/// More testing and verification will be added to ensure this.
///
/// For most methods, if the wrapped TSS call fails and returns a non-zero `TPM2_RC`, a
/// corresponding `Tss2ResponseCode` will be created and returned as an `Error`. Wherever this is
/// not the case or additional error types can be returned, the method definition should mention
/// it.
#[derive(Debug)]
pub struct Context {
    /// Handle for the ESYS context object owned through an Mbox.
    /// Wrapping the handle in an optional Mbox is done to allow the `Context` to be closed properly when the `Context` structure is dropped.
    esys_context: Option<MBox<ESYS_CONTEXT>>,
    sessions: (ESYS_TR, ESYS_TR, ESYS_TR),
    /// TCTI context handle associated with the ESYS context.
    /// As with the ESYS context, an optional Mbox wrapper allows the context to be deallocated.
    tcti_context: Option<MBox<TSS2_TCTI_CONTEXT>>,
    /// A set of currently open object handles that should be flushed before closing the context.
    open_handles: HashSet<ESYS_TR>,
}

impl Context {
    /// Create a new ESYS context based on the desired TCTI
    ///
    /// # Safety
    /// * the client is responsible for ensuring that the context can be initialized safely,
    /// threading-wise
    ///
    /// # Errors
    /// * if either `Tss2_TctiLdr_Initiialize` or `Esys_Initialize` fail, a corresponding
    /// Tss2ResponseCode will be returned
    pub unsafe fn new(tcti: Tcti) -> Result<Self> {
        let mut esys_context = null_mut();
        let mut tcti_context = null_mut();

        let tcti_name_conf = CString::try_from(tcti)?; // should never panic

        let ret = Tss2_TctiLdr_Initialize(tcti_name_conf.as_ptr(), &mut tcti_context);
        let ret = Error::from_tss_rc(ret);
        if !ret.is_success() {
            error!("Error when creating a TCTI context: {}.", ret);
            return Err(ret);
        }
        let mut tcti_context = Some(MBox::from_raw(tcti_context));

        let ret = Esys_Initialize(
            &mut esys_context,
            tcti_context.as_mut().unwrap().as_mut_ptr(), // will not panic as per how tcti_context is initialised
            null_mut(),
        );
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            let esys_context = Some(MBox::from_raw(esys_context));
            let context = Context {
                esys_context,
                sessions: (ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE),
                tcti_context,
                open_handles: HashSet::new(),
            };
            Ok(context)
        } else {
            error!("Error when creating a new context: {}.", ret);
            Err(ret)
        }
    }

    /// Start new authentication session and return the handle.
    ///
    /// The caller nonce is passed as a slice and converted by the method in a TSS digest
    /// structure.
    ///
    /// # Constraints
    /// * nonce must be at most 64 elements long
    ///
    /// # Errors
    /// * if the `nonce` is larger than allowed, a `WrongSizeParam` wrapper error is returned
    // TODO: Fix when compacting the arguments into a struct
    #[allow(clippy::too_many_arguments)]
    pub fn start_auth_session(
        &mut self,
        tpm_key: ESYS_TR,
        bind: ESYS_TR,
        nonce: Option<&Nonce>,
        session_type: TPM2_SE,
        symmetric: TPMT_SYM_DEF,
        auth_hash: TPMI_ALG_HASH,
    ) -> Result<ESYS_TR> {
        let nonce_ptr: *const TPM2B_NONCE = match nonce {
            Some(val) => &TPM2B_NONCE::try_from(val.clone())?,
            None => null(),
        };

        let mut sess = ESYS_TR_NONE;

        let ret = unsafe {
            Esys_StartAuthSession(
                self.mut_context(),
                tpm_key,
                bind,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                nonce_ptr,
                session_type,
                &symmetric,
                auth_hash,
                &mut sess,
            )
        };

        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            let _ = self.open_handles.insert(sess);
            Ok(sess)
        } else {
            error!("Error when creating a session: {}.", ret);
            Err(ret)
        }
    }

    pub fn set_sessions(&mut self, session_handles: (ESYS_TR, ESYS_TR, ESYS_TR)) {
        self.sessions = session_handles;
    }

    pub fn sessions(&self) -> (ESYS_TR, ESYS_TR, ESYS_TR) {
        self.sessions
    }

    /// Get current capability information about the TPM.
    pub fn get_capabilities(
        &mut self,
        capability: TPM2_CAP,
        property: u32,
        property_count: u32,
    ) -> Result<(TPMS_CAPABILITY_DATA, bool)> {
        let mut outcapabilitydata = null_mut();
        let mut outmoredata: u8 = 0;

        let ret = unsafe {
            Esys_GetCapability(
                self.mut_context(),
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                capability,
                property,
                property_count,
                &mut outmoredata,
                &mut outcapabilitydata,
            )
        };
        let moredata = if outmoredata == 0 {
            false
        } else if outmoredata == 1 {
            true
        } else {
            return Err(Error::WrapperError(ErrorKind::WrongValueFromTpm));
        };
        let capabilitydata = unsafe { MBox::from_raw(outcapabilitydata) };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            Ok((*capabilitydata, moredata))
        } else {
            Err(ret)
        }
    }

    /// Create a primary key and return the handle.
    ///
    /// The authentication value, initial data, outside info and creation PCRs are passed as slices
    /// which are then converted by the method into TSS native structures.
    ///
    /// # Constraints
    /// * `outside_info` must be at most 64 elements long
    /// * `creation_pcrs` must be at most 16 elements long
    /// * `auth_value` must be at most 64 elements long
    /// * `initial_data` must be at most 256 elements long
    ///
    /// # Errors
    /// * if either of the slices is larger than the maximum size of the native objects, a
    /// `WrongParamSize` wrapper error is returned
    // TODO: Fix when compacting the arguments into a struct
    #[allow(clippy::too_many_arguments)]
    pub fn create_primary_key(
        &mut self,
        primary_handle: ESYS_TR,
        public: &TPM2B_PUBLIC,
        auth_value: Option<&Auth>,
        initial_data: Option<&SensitiveData>,
        outside_info: Option<&Data>,
        creation_pcrs: &[TPMS_PCR_SELECTION],
    ) -> Result<ESYS_TR> {
        let sensitive_create = TPM2B_SENSITIVE_CREATE {
            size: std::mem::size_of::<TPMS_SENSITIVE_CREATE>()
                .try_into()
                .unwrap(),
            sensitive: TPMS_SENSITIVE_CREATE {
                userAuth: TPM2B_AUTH::try_from(auth_value.cloned().unwrap_or_default())?,
                data: TPM2B_SENSITIVE_DATA::try_from(initial_data.cloned().unwrap_or_default())?,
            },
        };

        if creation_pcrs.len() > 16 {
            return Err(Error::local_error(ErrorKind::WrongParamSize));
        }

        let mut creation_pcrs_buffer = [Default::default(); 16];
        creation_pcrs_buffer[..creation_pcrs.len()]
            .clone_from_slice(&creation_pcrs[..creation_pcrs.len()]);
        let creation_pcrs = TPML_PCR_SELECTION {
            count: creation_pcrs.len().try_into().unwrap(), // will not fail given the len checks above
            pcrSelections: creation_pcrs_buffer,
        };

        let mut outpublic = null_mut();
        let mut creation_data = null_mut();
        let mut creation_hash = null_mut();
        let mut creation_ticket = null_mut();
        let mut prim_key_handle = ESYS_TR_NONE;

        let ret = unsafe {
            Esys_CreatePrimary(
                self.mut_context(),
                primary_handle,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &sensitive_create,
                public,
                &TPM2B_DATA::try_from(outside_info.cloned().unwrap_or_default())?,
                &creation_pcrs,
                &mut prim_key_handle,
                &mut outpublic,
                &mut creation_data,
                &mut creation_hash,
                &mut creation_ticket,
            )
        };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            unsafe {
                let _ = MBox::from_raw(outpublic);
                let _ = MBox::from_raw(creation_data);
                let _ = MBox::from_raw(creation_hash);
                let _ = MBox::from_raw(creation_ticket);
            }
            let _ = self.open_handles.insert(prim_key_handle);
            Ok(prim_key_handle)
        } else {
            error!("Error in creating primary key: {}.", ret);
            Err(ret)
        }
    }

    /// Create a key and return the handle.
    ///
    /// The authentication value, initial data, outside info and creation PCRs are passed as slices
    /// which are then converted by the method into TSS native structures.
    ///
    /// # Constraints
    /// * `outside_info` must be at most 64 elements long
    /// * `creation_pcrs` must be at most 16 elements long
    /// * `auth_value` must be at most 64 elements long
    /// * `initial_data` must be at most 256 elements long
    ///
    /// # Errors
    /// * if either of the slices is larger than the maximum size of the native objects, a
    /// `WrongParamSize` wrapper error is returned
    // TODO: Fix when compacting the arguments into a struct
    #[allow(clippy::too_many_arguments)]
    pub fn create_key(
        &mut self,
        parent_handle: ESYS_TR,
        public: &TPM2B_PUBLIC,
        auth_value: Option<&Auth>,
        initial_data: Option<&SensitiveData>,
        outside_info: Option<&Data>,
        creation_pcrs: &[TPMS_PCR_SELECTION],
    ) -> Result<(TPM2B_PRIVATE, TPM2B_PUBLIC)> {
        let sensitive_create = TPM2B_SENSITIVE_CREATE {
            size: std::mem::size_of::<TPMS_SENSITIVE_CREATE>()
                .try_into()
                .unwrap(), // will not fail on targets of at least 16 bits
            sensitive: TPMS_SENSITIVE_CREATE {
                userAuth: TPM2B_AUTH::try_from(auth_value.cloned().unwrap_or_default())?,
                data: TPM2B_SENSITIVE_DATA::try_from(initial_data.cloned().unwrap_or_default())?,
            },
        };

        if creation_pcrs.len() > 16 {
            return Err(Error::local_error(ErrorKind::WrongParamSize));
        }
        let mut creation_pcrs_buffer = [Default::default(); 16];
        creation_pcrs_buffer[..creation_pcrs.len()]
            .clone_from_slice(&creation_pcrs[..creation_pcrs.len()]);
        let creation_pcrs = TPML_PCR_SELECTION {
            count: creation_pcrs.len().try_into().unwrap(), // will not fail given the len checks above
            pcrSelections: creation_pcrs_buffer,
        };

        let mut outpublic = null_mut();
        let mut outprivate = null_mut();
        let mut creation_data = null_mut();
        let mut digest = null_mut();
        let mut creation = null_mut();

        let ret = unsafe {
            Esys_Create(
                self.mut_context(),
                parent_handle,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &sensitive_create,
                public,
                &TPM2B_DATA::try_from(outside_info.cloned().unwrap_or_default())?,
                &creation_pcrs,
                &mut outprivate,
                &mut outpublic,
                &mut creation_data,
                &mut digest,
                &mut creation,
            )
        };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            let outprivate = unsafe { MBox::from_raw(outprivate) };
            let outpublic = unsafe { MBox::from_raw(outpublic) };
            unsafe {
                let _ = MBox::from_raw(creation_data);
                let _ = MBox::from_raw(digest);
                let _ = MBox::from_raw(creation);
            }
            Ok((*outprivate, *outpublic))
        } else {
            error!("Error in creating derived key: {}.", ret);
            Err(ret)
        }
    }

    /// Unseal and return data from a Sealed Data Object
    pub fn unseal(&mut self, item_handle: ESYS_TR) -> Result<SensitiveData> {
        let mut out_data = null_mut();

        let ret = unsafe {
            Esys_Unseal(
                self.mut_context(),
                item_handle,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &mut out_data,
            )
        };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            let out_data = unsafe { MBox::from_raw(out_data) };
            Ok(SensitiveData::try_from(*out_data)?)
        } else {
            error!("Error in unsealing: {}.", ret);
            Err(ret)
        }
    }

    /// Load a previously generated key back into the TPM and return its new handle.
    pub fn load(
        &mut self,
        parent_handle: ESYS_TR,
        private: TPM2B_PRIVATE,
        public: TPM2B_PUBLIC,
    ) -> Result<ESYS_TR> {
        let mut handle = ESYS_TR_NONE;
        let ret = unsafe {
            Esys_Load(
                self.mut_context(),
                parent_handle,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &private,
                &public,
                &mut handle,
            )
        };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            let _ = self.open_handles.insert(handle);
            Ok(handle)
        } else {
            error!("Error in loading: {}.", ret);
            Err(ret)
        }
    }

    /// Sign a digest with a key present in the TPM and return the signature.
    ///
    /// The digest is passed as a slice, converted by the method to a TSS digest structure.
    ///
    /// # Constraints
    /// * `digest` must be at most 64 elements long
    ///
    /// # Errors
    /// * if the digest provided is too long, a `WrongParamSize` wrapper error will be returned
    pub fn sign(
        &mut self,
        key_handle: ESYS_TR,
        digest: &Digest,
        scheme: TPMT_SIG_SCHEME,
        validation: &TPMT_TK_HASHCHECK,
    ) -> Result<Signature> {
        let mut signature = null_mut();
        let tss_digest = TPM2B_DIGEST::try_from(digest.clone())?;
        let ret = unsafe {
            Esys_Sign(
                self.mut_context(),
                key_handle,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &tss_digest,
                &scheme,
                validation,
                &mut signature,
            )
        };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            let signature = unsafe { MBox::from_raw(signature) };
            Ok(unsafe { Signature::try_from(*signature)? })
        } else {
            error!("Error in loading: {}.", ret);
            Err(ret)
        }
    }

    /// Verify if a signature was generated by signing a given digest with a key in the TPM.
    ///
    /// The digest is passed as a sliice and converted by the method to a TSS digest structure.
    ///
    /// # Constraints
    /// * `digest` must be at most 64 elements long
    ///
    /// # Errors
    /// * if the digest provided is too long, a `WrongParamSize` wrapper error will be returned
    pub fn verify_signature(
        &mut self,
        key_handle: ESYS_TR,
        digest: &Digest,
        signature: &TPMT_SIGNATURE,
    ) -> Result<TPMT_TK_VERIFIED> {
        let mut validation = null_mut();
        let tss_digest = TPM2B_DIGEST::try_from(digest.clone())?;
        let ret = unsafe {
            Esys_VerifySignature(
                self.mut_context(),
                key_handle,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &tss_digest,
                signature,
                &mut validation,
            )
        };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            let validation = unsafe { MBox::from_raw(validation) };
            Ok(*validation)
        } else {
            error!("Error in loading: {}.", ret);
            Err(ret)
        }
    }

    /// Perform an asymmetric RSA encryption.
    pub fn rsa_encrypt(
        &mut self,
        key_handle: ESYS_TR,
        message: PublicKeyRSA,
        in_scheme: &TPMT_RSA_DECRYPT,
        label: Data,
    ) -> Result<PublicKeyRSA> {
        let tss_message = TPM2B_PUBLIC_KEY_RSA::try_from(message)?;
        let tss_label = TPM2B_DATA::try_from(label)?;
        let mut out_data = null_mut();
        let ret = unsafe {
            Esys_RSA_Encrypt(
                self.mut_context(),
                key_handle,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &tss_message,
                in_scheme,
                &tss_label,
                &mut out_data,
            )
        };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            let data = unsafe { PublicKeyRSA::try_from(*out_data)? };
            Ok(data)
        } else {
            Err(ret)
        }
    }

    /// Perform an asymmetric RSA decryption.
    pub fn rsa_decrypt(
        &mut self,
        key_handle: ESYS_TR,
        cipher_text: PublicKeyRSA,
        in_scheme: &TPMT_RSA_DECRYPT,
        label: Data,
    ) -> Result<PublicKeyRSA> {
        let tss_cipher_text = TPM2B_PUBLIC_KEY_RSA::try_from(cipher_text)?;
        let tss_label = TPM2B_DATA::try_from(label)?;
        let mut message = null_mut();
        let ret = unsafe {
            Esys_RSA_Decrypt(
                self.mut_context(),
                key_handle,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &tss_cipher_text,
                in_scheme,
                &tss_label,
                &mut message,
            )
        };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            let data = unsafe { PublicKeyRSA::try_from(*message)? };
            Ok(data)
        } else {
            Err(ret)
        }
    }

    /// Load an external key into the TPM and return its new handle.
    pub fn load_external(
        &mut self,
        private: &TPM2B_SENSITIVE,
        public: &TPM2B_PUBLIC,
        hierarchy: Hierarchy,
    ) -> Result<ESYS_TR> {
        let mut key_handle = ESYS_TR_NONE;
        let ret = unsafe {
            Esys_LoadExternal(
                self.mut_context(),
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                private,
                public,
                hierarchy.rh(),
                &mut key_handle,
            )
        };

        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            let _ = self.open_handles.insert(key_handle);
            Ok(key_handle)
        } else {
            error!("Error in loading: {}.", ret);
            Err(ret)
        }
    }

    /// Load the public part of an external key and return its new handle.
    pub fn load_external_public(
        &mut self,
        public: &TPM2B_PUBLIC,
        hierarchy: Hierarchy,
    ) -> Result<ESYS_TR> {
        let mut key_handle = ESYS_TR_NONE;
        let ret = unsafe {
            Esys_LoadExternal(
                self.mut_context(),
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                null(),
                public,
                hierarchy.rh(),
                &mut key_handle,
            )
        };

        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            let _ = self.open_handles.insert(key_handle);
            Ok(key_handle)
        } else {
            error!("Error in loading: {}.", ret);
            Err(ret)
        }
    }

    /// Read the public part of a key currently in the TPM and return it.
    pub fn read_public(&mut self, key_handle: ESYS_TR) -> Result<TPM2B_PUBLIC> {
        let mut public = null_mut();
        let mut name = null_mut();
        let mut qualified_name = null_mut();
        let ret = unsafe {
            Esys_ReadPublic(
                self.mut_context(),
                key_handle,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &mut public,
                &mut name,
                &mut qualified_name,
            )
        };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            unsafe {
                let _ = MBox::from_raw(name);
                let _ = MBox::from_raw(qualified_name);
            }
            let public = unsafe { MBox::<TPM2B_PUBLIC>::from_raw(public) };
            Ok(*public)
        } else {
            error!("Error in loading: {}.", ret);
            Err(ret)
        }
    }

    /// Flush the context of an object from the TPM.
    pub fn flush_context(&mut self, handle: ESYS_TR) -> Result<()> {
        let ret = unsafe { Esys_FlushContext(self.mut_context(), handle) };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            let _ = self.open_handles.remove(&handle);
            Ok(())
        } else {
            error!("Error in flushing context: {}.", ret);
            Err(ret)
        }
    }

    /// Save the context of an object from the TPM and return it.
    ///
    /// # Errors
    /// * if conversion from `TPMS_CONTEXT` to `TpmsContext` fails, a `WrongParamSize` error will
    /// be returned
    pub fn context_save(&mut self, handle: ESYS_TR) -> Result<TpmsContext> {
        let mut context = null_mut();
        let ret = unsafe { Esys_ContextSave(self.mut_context(), handle, &mut context) };

        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            let context = unsafe { MBox::<TPMS_CONTEXT>::from_raw(context) };
            Ok((*context).try_into()?)
        } else {
            error!("Error in saving context: {}.", ret);
            Err(ret)
        }
    }

    /// Load a previously saved context into the TPM and return the object handle.
    ///
    /// # Errors
    /// * if conversion from `TpmsContext` to the native `TPMS_CONTEXT` fails, a `WrongParamSize`
    /// error will be returned
    pub fn context_load(&mut self, context: TpmsContext) -> Result<ESYS_TR> {
        let mut handle = ESYS_TR_NONE;
        let ret = unsafe {
            Esys_ContextLoad(
                self.mut_context(),
                &TPMS_CONTEXT::try_from(context)?,
                &mut handle,
            )
        };

        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            let _ = self.open_handles.insert(handle);
            Ok(handle)
        } else {
            error!("Error in loading context: {}.", ret);
            Err(ret)
        }
    }

    /// Reads the value of a PCR slot associated with
    /// a specific hashing algorithm
    ///
    /// # Constraints
    /// * If the selection contains more pcr values then 16 (number of
    /// elements in TPML_DIGEST). Then not all values will be read. The
    /// Selection in the return value will indicate what values that have
    /// been read.
    ///
    /// # Errors
    /// * Several different errors can occur if conversion of return
    ///   data fails.
    pub fn pcr_read(
        &mut self,
        pcr_selection_list: &PcrSelectionList,
    ) -> Result<(u32, PcrSelectionList, PcrData)> {
        let mut pcr_update_counter: u32 = 0;
        let mut tss_pcr_selection_list_out_ptr = null_mut();
        let mut tss_digest_ptr = null_mut();
        let ret = unsafe {
            Esys_PCR_Read(
                self.mut_context(),
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &pcr_selection_list.clone().into(),
                &mut pcr_update_counter,
                &mut tss_pcr_selection_list_out_ptr,
                &mut tss_digest_ptr,
            )
        };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            let tss_pcr_selection_list_out =
                unsafe { MBox::<TPML_PCR_SELECTION>::from_raw(tss_pcr_selection_list_out_ptr) };
            let tss_digest = unsafe { MBox::<TPML_DIGEST>::from_raw(tss_digest_ptr) };
            Ok((
                pcr_update_counter,
                PcrSelectionList::try_from(*tss_pcr_selection_list_out)?,
                PcrData::new(tss_pcr_selection_list_out.as_ref(), tss_digest.as_ref())?,
            ))
        } else {
            error!("Error in creating derived key: {}.", ret);
            Err(ret)
        }
    }

    /// Generate a quote on the selected PCRs
    ///
    /// # Constraints
    /// * `qualifying_data` must be at most 64 elements long
    ///
    /// # Errors
    /// * if the qualifying data provided is too long, a `WrongParamSize` wrapper error will be returned
    pub fn quote(
        &mut self,
        signing_key_handle: ESYS_TR,
        qualifying_data: &Data,
        signing_scheme: TPMT_SIG_SCHEME,
        pcr_selection_list: PcrSelectionList,
    ) -> Result<(TPM2B_ATTEST, Signature)> {
        let mut quoted = null_mut();
        let mut signature = null_mut();
        let tss_qualifying_data = TPM2B_DATA::try_from(qualifying_data.clone())?;
        let ret = unsafe {
            Esys_Quote(
                self.mut_context(),
                signing_key_handle,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &tss_qualifying_data,
                &signing_scheme,
                &pcr_selection_list.into(),
                &mut quoted,
                &mut signature,
            )
        };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            let quoted = unsafe { MBox::<TPM2B_ATTEST>::from_raw(quoted) };
            let signature = unsafe { MBox::from_raw(signature) };
            Ok((*quoted, unsafe { Signature::try_from(*signature)? }))
        } else {
            error!("Error in quoting PCR: {}", ret);
            Err(ret)
        }
    }
    /// Cause conditional gating of a policy based on PCR.
    ///
    /// The TPM will use the hash algorithm of the policy_session
    /// to calculate a digest from the values of the pcr slots
    /// specified in the pcr_selections.
    /// This is then compared to pcr_policy_digest if they match then
    /// the policyDigest of the policy session is extended.
    ///
    /// # Constraints
    /// * `pcr_policy_digest` must be at most 64 elements long
    ///
    /// # Errors
    /// * if the pcr policy digest provided is too long, a `WrongParamSize` wrapper error will be returned
    ///
    /// See:
    /// "Trusted Platform Module Library",
    /// "Part 3: Commands"
    /// "Family “2.0”
    /// Level 00 Revision 01.59
    /// Section: 23.7 TPM2_PolicyPCR
    pub fn policy_pcr(
        &mut self,
        policy_session: ESYS_TR,
        pcr_policy_digest: &Digest,
        pcr_selection_list: PcrSelectionList,
    ) -> Result<()> {
        let pcr_digest = TPM2B_DIGEST::try_from(pcr_policy_digest.clone())?;
        let ret = unsafe {
            Esys_PolicyPCR(
                self.mut_context(),
                policy_session,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &pcr_digest,
                &pcr_selection_list.into(),
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    /// Cause conditional gating of a policy based on an OR'd condition.
    ///
    /// The TPM will ensure that the current policy digest equals at least
    /// one of the digests.
    /// If this is the case, the policyDigest of the policy session is replaced
    /// by the value of the different hashes.
    ///
    /// # Constraints
    /// * `hash_list` must be at least 2 and at most 8 elements long
    ///
    /// # Errors
    /// * if the hash list provided is too short or too long, a `WrongParamSize` wrapper error will be returned
    pub fn policy_or(&mut self, policy_session: ESYS_TR, digest_list: DigestList) -> Result<()> {
        let digest_list = TPML_DIGEST::try_from(digest_list)?;

        let ret = unsafe {
            Esys_PolicyOR(
                self.mut_context(),
                policy_session,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &digest_list,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    /// Cause conditional gating of a policy based on locality.
    ///
    /// The TPM will ensure that the current policy can only complete in the specified
    /// locality (extended) or any of the specified localities (non-extended).
    pub fn policy_locality(
        &mut self,
        policy_session: ESYS_TR,
        locality: TPMA_LOCALITY,
    ) -> Result<()> {
        let ret = unsafe {
            Esys_PolicyLocality(
                self.mut_context(),
                policy_session,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                locality,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    /// Cause conditional gating of a policy based on command code of authorized command.
    ///
    /// The TPM will ensure that the current policy can only be used to complete the command
    /// indicated by code.
    pub fn policy_command_code(&mut self, policy_session: ESYS_TR, code: TPM2_CC) -> Result<()> {
        let ret = unsafe {
            Esys_PolicyCommandCode(
                self.mut_context(),
                policy_session,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                code,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    /// Cause conditional gating of a policy based on physical presence.
    ///
    /// The TPM will ensure that the current policy can only complete when physical
    /// presence is asserted. The way this is done is implementation-specific.
    pub fn policy_physical_presence(&mut self, policy_session: ESYS_TR) -> Result<()> {
        let ret = unsafe {
            Esys_PolicyPhysicalPresence(
                self.mut_context(),
                policy_session,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    /// Cause conditional gating of a policy based on command parameters.
    ///
    /// The TPM will ensure that the current policy can only be used to authorize
    /// a command where the parameters are hashed into cp_hash_a.
    pub fn policy_cp_hash(&mut self, policy_session: ESYS_TR, cp_hash_a: &Digest) -> Result<()> {
        let cp_hash_a = TPM2B_DIGEST::try_from(cp_hash_a.clone())?;
        let ret = unsafe {
            Esys_PolicyCpHash(
                self.mut_context(),
                policy_session,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &cp_hash_a,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    /// Cause conditional gating of a policy based on name hash.
    ///
    /// The TPM will ensure that the current policy can only be used to authorize
    /// a command acting on an object whose name hashes to name_hash.
    pub fn policy_name_hash(&mut self, policy_session: ESYS_TR, name_hash: &Digest) -> Result<()> {
        let name_hash = TPM2B_DIGEST::try_from(name_hash.clone())?;
        let ret = unsafe {
            Esys_PolicyNameHash(
                self.mut_context(),
                policy_session,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &name_hash,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    /// Cause conditional gating of a policy based on authValue.
    ///
    /// The TPM will ensure that the current policy requires the user to know the authValue
    /// used when creating the object.
    pub fn policy_auth_value(&mut self, policy_session: ESYS_TR) -> Result<()> {
        let ret = unsafe {
            Esys_PolicyAuthValue(
                self.mut_context(),
                policy_session,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    /// Cause conditional gating of a policy based on password.
    ///
    /// The TPM will ensure that the current policy requires the user to know the password
    /// used when creating the object.
    pub fn policy_password(&mut self, policy_session: ESYS_TR) -> Result<()> {
        let ret = unsafe {
            Esys_PolicyPassword(
                self.mut_context(),
                policy_session,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    /// Cause conditional gating of a policy based on NV written state.
    ///
    /// The TPM will ensure that the NV index that is used has a specific written state.
    pub fn policy_nv_written(&mut self, policy_session: ESYS_TR, written_set: bool) -> Result<()> {
        let ret = unsafe {
            Esys_PolicyNvWritten(
                self.mut_context(),
                policy_session,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                if written_set { 1 } else { 0 },
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    /// Cause conditional gating of a policy based on an authorized policy
    ///
    /// The TPM will ensure that the current policy digest is correctly signed
    /// by the ticket in check_ticket and that check_ticket is signed by the key
    /// named in key_sign.
    /// If this is the case, the policyDigest of the policy session is replaced
    /// by the value of the key_sign and policy_ref values.
    pub fn policy_authorize(
        &mut self,
        policy_session: ESYS_TR,
        approved_policy: &Digest,
        policy_ref: &Nonce,
        key_sign: &Name,
        check_ticket: TPMT_TK_VERIFIED,
    ) -> Result<()> {
        let tss_approved_policy = TPM2B_DIGEST::try_from(approved_policy.clone())?;
        let tss_policy_ref = TPM2B_NONCE::try_from(policy_ref.clone())?;
        let tss_key_sign = TPM2B_NAME::try_from(key_sign.clone())?;
        let ret = unsafe {
            Esys_PolicyAuthorize(
                self.mut_context(),
                policy_session,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &tss_approved_policy,
                &tss_policy_ref,
                &tss_key_sign,
                &check_ticket,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    // TODO: Should we really keep `num_bytes` as `u16`?
    /// Get a number of random bytes from the TPM and return them.
    ///
    /// # Errors
    /// * if converting `num_bytes` to `u16` fails, a `WrongParamSize` will be returned
    pub fn get_random(&mut self, num_bytes: usize) -> Result<Digest> {
        let mut buffer = null_mut();
        let ret = unsafe {
            Esys_GetRandom(
                self.mut_context(),
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                num_bytes
                    .try_into()
                    .map_err(|_| Error::local_error(ErrorKind::WrongParamSize))?,
                &mut buffer,
            )
        };

        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            let buffer = unsafe { MBox::from_raw(buffer) };
            let mut random = buffer.buffer.to_vec();
            random.truncate(buffer.size.try_into().unwrap()); // should not panic given the TryInto above
            Ok(Digest::try_from(random)?)
        } else {
            error!("Error in flushing context: {}.", ret);
            Err(ret)
        }
    }

    /// Test if the given parameters are supported by the TPM.
    ///
    /// # Errors
    /// * if any of the public parameters is not compatible with the TPM,
    /// an `Err` containing the specific unmarshalling error will be returned.
    pub fn test_parms(&mut self, parms: PublicParmsUnion) -> Result<()> {
        let public_parms = TPMT_PUBLIC_PARMS {
            type_: parms.object_type(),
            parameters: parms.into(),
        };
        let ret = unsafe {
            Esys_TestParms(
                self.mut_context(),
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &public_parms,
            )
        };

        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            error!("Error while testing parameters: {}.", ret);
            Err(ret)
        }
    }

    /// Function for invoking TPM2_Hash command.
    ///
    pub fn hash(
        &mut self,
        data: &MaxBuffer,
        hashing_algorithm: HashingAlgorithm,
        hierarchy: Hierarchy,
    ) -> Result<(Digest, HashcheckTicket)> {
        let in_data = TPM2B_MAX_BUFFER::try_from(data.clone())?;
        let mut out_hash_ptr = null_mut();
        let mut validation_ptr = null_mut();
        let ret = unsafe {
            Esys_Hash(
                self.mut_context(),
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &in_data,
                hashing_algorithm.into(),
                hierarchy.rh(),
                &mut out_hash_ptr,
                &mut validation_ptr,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            let out_hash = unsafe { MBox::<TPM2B_DIGEST>::from_raw(out_hash_ptr) };
            let validation = unsafe { MBox::<TPMT_TK_HASHCHECK>::from_raw(validation_ptr) };
            Ok((
                Digest::try_from(*out_hash)?,
                HashcheckTicket::try_from(*validation)?,
            ))
        } else {
            error!("Error failed to peform hash operation: {}.", ret);
            Err(ret)
        }
    }

    /// Function for retriving the current policy digest for
    /// the session.
    pub fn policy_get_digest(&mut self, policy_session: ESYS_TR) -> Result<Digest> {
        let mut policy_digest_ptr = null_mut();
        let ret = unsafe {
            Esys_PolicyGetDigest(
                self.mut_context(),
                policy_session,
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &mut policy_digest_ptr,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            let policy_digest = unsafe { MBox::<TPM2B_DIGEST>::from_raw(policy_digest_ptr) };
            Ok(Digest::try_from(*policy_digest)?)
        } else {
            error!(
                "Error failed to peform policy get digest operation: {}.",
                ret
            );
            Err(ret)
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    /// TPM Resource Section
    ///////////////////////////////////////////////////////////////////////////

    /// Set the authentication value for a given object handle in the ESYS context.
    ///
    /// # Constraints
    /// * `auth_value` must be at most 64 elements long
    ///
    /// # Errors
    /// * if `auth_value` is larger than the limit, a `WrongParamSize` wrapper error is returned
    pub fn tr_set_auth(&mut self, object_handle: ObjectHandle, auth: &Auth) -> Result<()> {
        let tss_auth = TPM2B_AUTH::try_from(auth.clone())?;
        let ret = unsafe { Esys_TR_SetAuth(self.mut_context(), object_handle.into(), &tss_auth) };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    /// Retrieve the name of an object from the object handle
    pub fn tr_get_name(&mut self, object_handle: ObjectHandle) -> Result<Name> {
        let mut name = null_mut();
        let ret = unsafe { Esys_TR_GetName(self.mut_context(), object_handle.into(), &mut name) };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            let tss_name = unsafe { MBox::<TPM2B_NAME>::from_raw(name) };
            Ok(Name::try_from(*tss_name)?)
        } else {
            error!("Error in getting name: {}.", ret);
            Err(ret)
        }
    }

    /// Set the given attributes on a given session.
    pub fn tr_sess_set_attributes(
        &mut self,
        handle: ESYS_TR,
        attributes: TpmaSession,
    ) -> Result<()> {
        let ret = unsafe {
            Esys_TRSess_SetAttributes(
                self.mut_context(),
                handle,
                attributes.flags(),
                attributes.mask(),
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    /// Get session attribute flags.
    pub fn tr_sess_get_attributes(&mut self, object_handle: ObjectHandle) -> Result<TpmaSession> {
        let mut flags: TPMA_SESSION = 0;
        let ret = unsafe {
            Esys_TRSess_GetAttributes(self.mut_context(), object_handle.into(), &mut flags)
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(TpmaSessionBuilder::new().with_flag(flags).build())
        } else {
            Err(ret)
        }
    }

    /// Used to construct an esys object from the resources inside the TPM.
    pub fn tr_from_tpm_public(&mut self, tpm_handle: TpmHandle) -> Result<ObjectHandle> {
        let mut tss_esys_object_handle: ESYS_TR = ESYS_TR_NONE;
        let ret = unsafe {
            Esys_TR_FromTPMPublic(
                self.mut_context(),
                tpm_handle.into(),
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &mut tss_esys_object_handle,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(ObjectHandle::from(tss_esys_object_handle))
        } else {
            Err(ret)
        }
    }

    pub fn tr_close(&mut self, object_handle: &mut ObjectHandle) -> Result<()> {
        let mut tss_esys_object_handle: ESYS_TR = (*object_handle).into();
        let ret = unsafe { Esys_TR_Close(self.mut_context(), &mut tss_esys_object_handle) };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            *object_handle = ObjectHandle::from(tss_esys_object_handle);
            Ok(())
        } else {
            Err(ret)
        }
    }
    ///////////////////////////////////////////////////////////////////////////
    /// TPM Non Volatile Section
    ///////////////////////////////////////////////////////////////////////////

    /// NV Define Space
    ///
    /// Allocates an index in the non volatile
    /// storage.
    pub fn nv_define_space(
        &mut self,
        nv_authorization: NvAuthorization,
        auth: Option<&Auth>,
        public_info: &NvPublic,
    ) -> Result<NvIndexHandle> {
        let tss_auth = TPM2B_AUTH::try_from(auth.cloned().unwrap_or_default())?;
        let tss_nv_public = TPM2B_NV_PUBLIC::try_from(public_info.clone())?;
        let mut object_identifier: ESYS_TR = ESYS_TR_NONE;
        let ret = unsafe {
            Esys_NV_DefineSpace(
                self.mut_context(),
                nv_authorization.into(),
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &tss_auth,
                &tss_nv_public,
                &mut object_identifier,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(NvIndexHandle::from(object_identifier))
        } else {
            Err(ret)
        }
    }

    /// NV Undefine Space
    ///
    /// Deletes an index in the non volatile
    /// storage.
    pub fn nv_undefine_space(
        &mut self,
        nv_authorization: NvAuthorization,
        nv_index_handle: NvIndexHandle,
    ) -> Result<()> {
        let ret = unsafe {
            Esys_NV_UndefineSpace(
                self.mut_context(),
                nv_authorization.into(),
                nv_index_handle.into(),
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
            )
        };

        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }

    /// NV Read Public
    ///
    /// Reads the public part of an nv index.
    ///
    pub fn nv_read_public(&mut self, nv_index_handle: NvIndexHandle) -> Result<(NvPublic, Name)> {
        let mut tss_nv_public_ptr = null_mut();
        let mut tss_nv_name_ptr = null_mut();
        let ret = unsafe {
            Esys_NV_ReadPublic(
                self.mut_context(),
                nv_index_handle.into(),
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &mut tss_nv_public_ptr,
                &mut tss_nv_name_ptr,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            let tss_nv_public = unsafe { MBox::<TPM2B_NV_PUBLIC>::from_raw(tss_nv_public_ptr) };
            let tss_nv_name = unsafe { MBox::<TPM2B_NAME>::from_raw(tss_nv_name_ptr) };
            Ok((
                NvPublic::try_from(*tss_nv_public)?,
                Name::try_from(*tss_nv_name)?,
            ))
        } else {
            Err(ret)
        }
    }

    /// NV Read
    ///
    /// Reads data from the nv index.
    pub fn nv_read(
        &mut self,
        auth_handle: AuthHandle,
        nv_index_handle: NvIndexHandle,
        size: u16,
        offset: u16,
    ) -> Result<MaxNvBuffer> {
        let mut tss_max_nv_buffer_ptr = null_mut();
        let ret = unsafe {
            Esys_NV_Read(
                self.mut_context(),
                auth_handle.into(),
                nv_index_handle.into(),
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                size,
                offset,
                &mut tss_max_nv_buffer_ptr,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            let tss_max_nv_buffer =
                unsafe { MBox::<TPM2B_MAX_NV_BUFFER>::from_raw(tss_max_nv_buffer_ptr) };
            Ok(MaxNvBuffer::try_from(*tss_max_nv_buffer)?)
        } else {
            Err(ret)
        }
    }

    /// NV Write
    ///
    /// Writes data to an nv index.
    pub fn nv_write(
        &mut self,
        auth_handle: AuthHandle,
        nv_index_handle: NvIndexHandle,
        data: &MaxNvBuffer,
        offset: u16,
    ) -> Result<()> {
        let ret = unsafe {
            Esys_NV_Write(
                self.mut_context(),
                auth_handle.into(),
                nv_index_handle.into(),
                self.sessions.0,
                self.sessions.1,
                self.sessions.2,
                &data.clone().try_into()?,
                offset,
            )
        };
        let ret = Error::from_tss_rc(ret);
        if ret.is_success() {
            Ok(())
        } else {
            Err(ret)
        }
    }
    ///////////////////////////////////////////////////////////////////////////
    /// Private Methods Section
    ///////////////////////////////////////////////////////////////////////////

    /// Returns a mutable reference to the native ESYS context handle.
    fn mut_context(&mut self) -> *mut ESYS_CONTEXT {
        self.esys_context.as_mut().unwrap().as_mut_ptr() // will only fail if called from Drop after .take()
    }
}

impl Drop for Context {
    fn drop(&mut self) {
        info!("Closing context.");

        // Flush the open handles.
        self.open_handles.clone().iter().for_each(|handle| {
            info!("Flushing handle {}", *handle);
            if let Err(e) = self.flush_context(*handle) {
                error!("Error when dropping the context: {}.", e);
            }
        });

        let esys_context = self.esys_context.take().unwrap(); // should not fail based on how the context is initialised/used
        let tcti_context = self.tcti_context.take().unwrap(); // should not fail based on how the context is initialised/used

        // Close the TCTI context.
        unsafe { Tss2_TctiLdr_Finalize(&mut tcti_context.into_raw()) };

        // Close the context.
        unsafe { Esys_Finalize(&mut esys_context.into_raw()) };
        info!("Context closed.");
    }
}