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
#![deny(warnings)]
#![warn(unused_extern_crates)]
#![deny(clippy::todo)]
#![deny(clippy::unimplemented)]
#![deny(clippy::unwrap_used)]
#![deny(clippy::expect_used)]
#![deny(clippy::panic)]
#![deny(clippy::await_holding_lock)]
#![deny(clippy::needless_pass_by_value)]
#![deny(clippy::trivially_copy_pass_by_ref)]
#![deny(clippy::unreachable)]

use argon2::{Algorithm, Argon2, Params, PasswordHash, Version};
use base64::engine::GeneralPurpose;
use base64::{alphabet, Engine};
use tracing::{debug, error, trace, warn};

use base64::engine::general_purpose;
use base64urlsafedata::Base64UrlSafeData;
use rand::Rng;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::time::{Duration, Instant};

use kanidm_proto::internal::OperationError;
use openssl::error::ErrorStack as OpenSSLErrorStack;
use openssl::hash::{self, MessageDigest};
use openssl::nid::Nid;
use openssl::pkcs5::pbkdf2_hmac;
use openssl::sha::{Sha1, Sha256, Sha512};

use kanidm_hsm_crypto::{HmacKey, Tpm};

pub mod mtls;
pub mod prelude;
pub mod serialise;
pub mod x509_cert;

pub use sha2;

pub type Sha256Digest =
    sha2::digest::generic_array::GenericArray<u8, sha2::digest::typenum::consts::U32>;

// NIST 800-63.b salt should be 112 bits -> 14  8u8.
const PBKDF2_SALT_LEN: usize = 24;

pub const PBKDF2_MIN_NIST_SALT_LEN: usize = 14;

// Min number of rounds for a pbkdf2
pub const PBKDF2_MIN_NIST_COST: usize = 10000;

// 32 * u8 -> 256 bits of out.
const PBKDF2_KEY_LEN: usize = 32;
const PBKDF2_MIN_NIST_KEY_LEN: usize = 32;
const PBKDF2_SHA1_MIN_KEY_LEN: usize = 19;

const DS_SHA_SALT_LEN: usize = 8;
const DS_SHA1_HASH_LEN: usize = 20;
const DS_SHA256_HASH_LEN: usize = 32;
const DS_SHA512_HASH_LEN: usize = 64;

// Taken from the argon2 library and rfc 9106
const ARGON2_VERSION: u32 = 19;
const ARGON2_SALT_LEN: usize = 16;
// 32 * u8 -> 256 bits of out.
const ARGON2_KEY_LEN: usize = 32;
// Default amount of ram we sacrifice per thread
const ARGON2_MIN_RAM_KIB: u32 = 8 * 1024;
const ARGON2_MAX_RAM_KIB: u32 = 64 * 1024;
// Amount of ram to subtract when we do a T cost iter. This
// is because t=2 m=32 == t=3 m=20. So we just step down a little
// to keep the value about the same.
const ARGON2_TCOST_RAM_ITER_KIB: u32 = 12 * 1024;
const ARGON2_MIN_T_COST: u32 = 2;
const ARGON2_MAX_T_COST: u32 = 16;
const ARGON2_MAX_P_COST: u32 = 1;

#[derive(Clone, Debug)]
pub enum CryptoError {
    Hsm,
    HsmContextMissing,
    OpenSSL(u64),
    Md4Disabled,
    Argon2,
    Argon2Version,
    Argon2Parameters,
}

impl From<OpenSSLErrorStack> for CryptoError {
    fn from(ossl_err: OpenSSLErrorStack) -> Self {
        error!(?ossl_err);
        let code = ossl_err.errors().first().map(|e| e.code()).unwrap_or(0);
        #[cfg(not(target_family = "windows"))]
        let result = CryptoError::OpenSSL(code);

        // this is an .into() because on windows it's a u32 not a u64
        #[cfg(target_family = "windows")]
        let result = CryptoError::OpenSSL(code.into());

        result
    }
}

#[allow(clippy::from_over_into)]
impl Into<OperationError> for CryptoError {
    fn into(self) -> OperationError {
        OperationError::CryptographyError
    }
}

#[derive(Serialize, Deserialize, PartialEq, Eq, Clone)]
#[allow(non_camel_case_types)]
pub enum DbPasswordV1 {
    TPM_ARGON2ID {
        m: u32,
        t: u32,
        p: u32,
        v: u32,
        s: Base64UrlSafeData,
        k: Base64UrlSafeData,
    },
    ARGON2ID {
        m: u32,
        t: u32,
        p: u32,
        v: u32,
        s: Base64UrlSafeData,
        k: Base64UrlSafeData,
    },
    PBKDF2(usize, Vec<u8>, Vec<u8>),
    PBKDF2_SHA1(usize, Vec<u8>, Vec<u8>),
    PBKDF2_SHA512(usize, Vec<u8>, Vec<u8>),
    SHA1(Vec<u8>),
    SSHA1(Vec<u8>, Vec<u8>),
    SHA256(Vec<u8>),
    SSHA256(Vec<u8>, Vec<u8>),
    SHA512(Vec<u8>),
    SSHA512(Vec<u8>, Vec<u8>),
    NT_MD4(Vec<u8>),
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub enum ReplPasswordV1 {
    TPM_ARGON2ID {
        m_cost: u32,
        t_cost: u32,
        p_cost: u32,
        version: u32,
        salt: Base64UrlSafeData,
        key: Base64UrlSafeData,
    },
    ARGON2ID {
        m_cost: u32,
        t_cost: u32,
        p_cost: u32,
        version: u32,
        salt: Base64UrlSafeData,
        key: Base64UrlSafeData,
    },
    PBKDF2 {
        cost: usize,
        salt: Base64UrlSafeData,
        hash: Base64UrlSafeData,
    },
    PBKDF2_SHA1 {
        cost: usize,
        salt: Base64UrlSafeData,
        hash: Base64UrlSafeData,
    },
    PBKDF2_SHA512 {
        cost: usize,
        salt: Base64UrlSafeData,
        hash: Base64UrlSafeData,
    },
    SHA1 {
        hash: Base64UrlSafeData,
    },
    SSHA1 {
        salt: Base64UrlSafeData,
        hash: Base64UrlSafeData,
    },
    SHA256 {
        hash: Base64UrlSafeData,
    },
    SSHA256 {
        salt: Base64UrlSafeData,
        hash: Base64UrlSafeData,
    },
    SHA512 {
        hash: Base64UrlSafeData,
    },
    SSHA512 {
        salt: Base64UrlSafeData,
        hash: Base64UrlSafeData,
    },
    NT_MD4 {
        hash: Base64UrlSafeData,
    },
}

impl fmt::Debug for DbPasswordV1 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            DbPasswordV1::TPM_ARGON2ID { .. } => write!(f, "TPM_ARGON2ID"),
            DbPasswordV1::ARGON2ID { .. } => write!(f, "ARGON2ID"),
            DbPasswordV1::PBKDF2(_, _, _) => write!(f, "PBKDF2"),
            DbPasswordV1::PBKDF2_SHA1(_, _, _) => write!(f, "PBKDF2_SHA1"),
            DbPasswordV1::PBKDF2_SHA512(_, _, _) => write!(f, "PBKDF2_SHA512"),
            DbPasswordV1::SHA1(_) => write!(f, "SHA1"),
            DbPasswordV1::SSHA1(_, _) => write!(f, "SSHA1"),
            DbPasswordV1::SHA256(_) => write!(f, "SHA256"),
            DbPasswordV1::SSHA256(_, _) => write!(f, "SSHA256"),
            DbPasswordV1::SHA512(_) => write!(f, "SHA512"),
            DbPasswordV1::SSHA512(_, _) => write!(f, "SSHA512"),
            DbPasswordV1::NT_MD4(_) => write!(f, "NT_MD4"),
        }
    }
}

#[derive(Debug)]
pub struct CryptoPolicy {
    pub(crate) pbkdf2_cost: usize,
    // https://docs.rs/argon2/0.5.0/argon2/struct.Params.html
    // defaults to 19mb memory, 2 iterations and 1 thread, with a 32byte output.
    pub(crate) argon2id_params: Params,
}

impl CryptoPolicy {
    pub fn minimum() -> Self {
        CryptoPolicy {
            pbkdf2_cost: PBKDF2_MIN_NIST_COST,
            argon2id_params: Params::default(),
        }
    }

    pub fn danger_test_minimum() -> Self {
        CryptoPolicy {
            pbkdf2_cost: 1000,
            argon2id_params: Params::new(
                Params::MIN_M_COST,
                Params::MIN_T_COST,
                Params::MIN_P_COST,
                None,
            )
            .unwrap_or_default(),
        }
    }

    pub fn time_target(target_time: Duration) -> Self {
        const PBKDF2_BENCH_FACTOR: usize = 10;

        let pbkdf2_cost = match Password::bench_pbkdf2(PBKDF2_MIN_NIST_COST * PBKDF2_BENCH_FACTOR) {
            Some(bt) => {
                let ubt = bt.as_nanos() as usize;

                // Get the cost per thousand rounds
                let per_thou = (PBKDF2_MIN_NIST_COST * PBKDF2_BENCH_FACTOR) / 1000;
                let t_per_thou = ubt / per_thou;
                trace!("{:010}µs / 1000 rounds", t_per_thou);

                // Now we need the attacker work in nanos
                let target = target_time.as_nanos() as usize;
                let r = (target / t_per_thou) * 1000;

                trace!("{}µs target time", target);
                trace!("Maybe rounds -> {}", r);

                if r < PBKDF2_MIN_NIST_COST {
                    PBKDF2_MIN_NIST_COST
                } else {
                    r
                }
            }
            None => PBKDF2_MIN_NIST_COST,
        };

        // Argon2id has multiple parameters. These all are about *exchanges* that you can
        // request in how the computation is performed.
        //
        // rfc9106 explains that there are two algorithms stacked here. Argon2i has defences
        // against side-channel timing. Argon2d provides defences for time-memory tradeoffs.
        //
        // We can see how this impacts timings from sources like:
        // https://www.twelve21.io/how-to-choose-the-right-parameters-for-argon2/
        //
        // M =  256 MB, T =    2, d = 8, Time = 0.732 s
        // M =  128 MB, T =    6, d = 8, Time = 0.99 s
        // M =   64 MB, T =   12, d = 8, Time = 0.968 s
        // M =   32 MB, T =   24, d = 8, Time = 0.896 s
        // M =   16 MB, T =   49, d = 8, Time = 0.973 s
        // M =    8 MB, T =   96, d = 8, Time = 0.991 s
        // M =    4 MB, T =  190, d = 8, Time = 0.977 s
        // M =    2 MB, T =  271, d = 8, Time = 0.973 s
        // M =    1 MB, T =  639, d = 8, Time = 0.991 s
        //
        // As we can see, the time taken stays constant, but as ram decreases the amount of
        // CPU work required goes up. In our case, our primary threat is from GPU hashcat
        // cracking. GPU's tend to have many fast cores but very little amounts of fast ram
        // for those cores. So we want to have as much ram as *possible* up to a limit, and
        // then we want to increase iterations.
        //
        // This way a GPU has to expend further GPU time to compensate for the less ram.
        //
        // We also need to balance this against the fact we are a database, and we do have
        // caches. We also don't want to over-use RAM, especially because in the worst case
        // every thread will be operating in argon2id at the same time. That means
        // thread x ram will be used. If we had 8 threads at 64mb of ram, that would require
        // 512mb of ram alone just for hashing. This becomes worse as core counts scale, with
        // 24 core xeons easily reaching 1.5GB in these cases.

        let mut m_cost = ARGON2_MIN_RAM_KIB;
        let mut t_cost = ARGON2_MIN_T_COST;
        let p_cost = ARGON2_MAX_P_COST;

        // Raise memory usage until an acceptable ram amount is reached.
        loop {
            let params = if let Ok(p) = Params::new(m_cost, t_cost, p_cost, None) {
                p
            } else {
                // Unable to proceed.
                error!(
                    ?m_cost,
                    ?t_cost,
                    ?p_cost,
                    "Parameters were not valid for argon2"
                );
                break;
            };

            if let Some(ubt) = Password::bench_argon2id(params) {
                debug!("{}µs - t_cost {} m_cost {}", ubt.as_nanos(), t_cost, m_cost);
                // Parameter adjustment
                if ubt < target_time {
                    if m_cost < ARGON2_MAX_RAM_KIB {
                        // Help narrow in quicker.
                        let m_adjust = if target_time
                            .as_nanos()
                            .checked_div(ubt.as_nanos())
                            .unwrap_or(1)
                            >= 2
                        {
                            // Very far from target, double m_cost.
                            m_cost * 2
                        } else {
                            // Close! Increase in a small step
                            m_cost + 1024
                        };

                        m_cost = if m_adjust > ARGON2_MAX_RAM_KIB {
                            ARGON2_MAX_RAM_KIB
                        } else {
                            m_adjust
                        };
                        continue;
                    } else if t_cost < ARGON2_MAX_T_COST {
                        // t=2 with m = 32MB is about the same as t=3 m=20MB, so we want to start with ram
                        // higher on these iterations. About 12MB appears to be one iteration. We use 8MB
                        // here though, just to give a little window under that for adjustment.
                        //
                        // Similar, once we hit t=4 we just need to have max ram.
                        t_cost += 1;
                        // Halve the ram cost.
                        let m_adjust = m_cost
                            .checked_sub(ARGON2_TCOST_RAM_ITER_KIB)
                            .unwrap_or(ARGON2_MIN_RAM_KIB);

                        // Clamp the value
                        m_cost = m_adjust.clamp(ARGON2_MIN_RAM_KIB, ARGON2_MAX_RAM_KIB);
                        continue;
                    } else {
                        // Unable to proceed, parameters are maxed out.
                        warn!("Argon2 parameters have hit their maximums - this may be a bug!");
                        break;
                    }
                } else {
                    // Found the target time.
                    break;
                }
            } else {
                error!("Unable to perform bench of argon2id, stopping benchmark");
                break;
            }
        }

        let argon2id_params = Params::new(m_cost, t_cost, p_cost, None)
            // fallback
            .unwrap_or_default();

        let p = CryptoPolicy {
            pbkdf2_cost,
            argon2id_params,
        };
        debug!(pbkdf2_cost = %p.pbkdf2_cost, argon2id_m = %p.argon2id_params.m_cost(), argon2id_p = %p.argon2id_params.p_cost(), argon2id_t = %p.argon2id_params.t_cost(), );
        p
    }
}

// Why PBKDF2? Rust's bcrypt has a number of hardcodings like max pw len of 72
// I don't really feel like adding in so many restrictions, so I'll use
// pbkdf2 in openssl because it doesn't have the same limits.
#[derive(Clone, Debug, PartialEq)]
#[allow(non_camel_case_types)]
enum Kdf {
    TPM_ARGON2ID {
        m_cost: u32,
        t_cost: u32,
        p_cost: u32,
        version: u32,
        salt: Vec<u8>,
        key: Vec<u8>,
    },
    //
    ARGON2ID {
        m_cost: u32,
        t_cost: u32,
        p_cost: u32,
        version: u32,
        salt: Vec<u8>,
        key: Vec<u8>,
    },
    //     cost, salt,   hash
    PBKDF2(usize, Vec<u8>, Vec<u8>),

    // Imported types, will upgrade to the above.
    //         cost,   salt,    hash
    PBKDF2_SHA1(usize, Vec<u8>, Vec<u8>),
    //           cost,   salt,    hash
    PBKDF2_SHA512(usize, Vec<u8>, Vec<u8>),
    //      salt     hash
    SHA1(Vec<u8>),
    SSHA1(Vec<u8>, Vec<u8>),
    SHA256(Vec<u8>),
    SSHA256(Vec<u8>, Vec<u8>),
    SHA512(Vec<u8>),
    SSHA512(Vec<u8>, Vec<u8>),
    //     hash
    NT_MD4(Vec<u8>),
}

#[derive(Clone, Debug, PartialEq)]
pub struct Password {
    material: Kdf,
}

impl TryFrom<DbPasswordV1> for Password {
    type Error = ();

    fn try_from(value: DbPasswordV1) -> Result<Self, Self::Error> {
        match value {
            DbPasswordV1::TPM_ARGON2ID { m, t, p, v, s, k } => Ok(Password {
                material: Kdf::TPM_ARGON2ID {
                    m_cost: m,
                    t_cost: t,
                    p_cost: p,
                    version: v,
                    salt: s.into(),
                    key: k.into(),
                },
            }),
            DbPasswordV1::ARGON2ID { m, t, p, v, s, k } => Ok(Password {
                material: Kdf::ARGON2ID {
                    m_cost: m,
                    t_cost: t,
                    p_cost: p,
                    version: v,
                    salt: s.into(),
                    key: k.into(),
                },
            }),
            DbPasswordV1::PBKDF2(c, s, h) => Ok(Password {
                material: Kdf::PBKDF2(c, s, h),
            }),
            DbPasswordV1::PBKDF2_SHA1(c, s, h) => Ok(Password {
                material: Kdf::PBKDF2_SHA1(c, s, h),
            }),
            DbPasswordV1::PBKDF2_SHA512(c, s, h) => Ok(Password {
                material: Kdf::PBKDF2_SHA512(c, s, h),
            }),
            DbPasswordV1::SHA1(h) => Ok(Password {
                material: Kdf::SHA1(h),
            }),
            DbPasswordV1::SSHA1(s, h) => Ok(Password {
                material: Kdf::SSHA1(s, h),
            }),
            DbPasswordV1::SHA256(h) => Ok(Password {
                material: Kdf::SHA256(h),
            }),
            DbPasswordV1::SSHA256(s, h) => Ok(Password {
                material: Kdf::SSHA256(s, h),
            }),
            DbPasswordV1::SHA512(h) => Ok(Password {
                material: Kdf::SHA512(h),
            }),
            DbPasswordV1::SSHA512(s, h) => Ok(Password {
                material: Kdf::SSHA512(s, h),
            }),
            DbPasswordV1::NT_MD4(h) => Ok(Password {
                material: Kdf::NT_MD4(h),
            }),
        }
    }
}

impl TryFrom<&ReplPasswordV1> for Password {
    type Error = ();

    fn try_from(value: &ReplPasswordV1) -> Result<Self, Self::Error> {
        match value {
            ReplPasswordV1::TPM_ARGON2ID {
                m_cost,
                t_cost,
                p_cost,
                version,
                salt,
                key,
            } => Ok(Password {
                material: Kdf::TPM_ARGON2ID {
                    m_cost: *m_cost,
                    t_cost: *t_cost,
                    p_cost: *p_cost,
                    version: *version,
                    salt: salt.to_vec(),
                    key: key.to_vec(),
                },
            }),
            ReplPasswordV1::ARGON2ID {
                m_cost,
                t_cost,
                p_cost,
                version,
                salt,
                key,
            } => Ok(Password {
                material: Kdf::ARGON2ID {
                    m_cost: *m_cost,
                    t_cost: *t_cost,
                    p_cost: *p_cost,
                    version: *version,
                    salt: salt.to_vec(),
                    key: key.to_vec(),
                },
            }),
            ReplPasswordV1::PBKDF2 { cost, salt, hash } => Ok(Password {
                material: Kdf::PBKDF2(*cost, salt.to_vec(), hash.to_vec()),
            }),
            ReplPasswordV1::PBKDF2_SHA1 { cost, salt, hash } => Ok(Password {
                material: Kdf::PBKDF2_SHA1(*cost, salt.to_vec(), hash.to_vec()),
            }),
            ReplPasswordV1::PBKDF2_SHA512 { cost, salt, hash } => Ok(Password {
                material: Kdf::PBKDF2_SHA512(*cost, salt.to_vec(), hash.to_vec()),
            }),
            ReplPasswordV1::SHA1 { hash } => Ok(Password {
                material: Kdf::SHA1(hash.to_vec()),
            }),
            ReplPasswordV1::SSHA1 { salt, hash } => Ok(Password {
                material: Kdf::SSHA1(salt.to_vec(), hash.to_vec()),
            }),
            ReplPasswordV1::SHA256 { hash } => Ok(Password {
                material: Kdf::SHA256(hash.to_vec()),
            }),
            ReplPasswordV1::SSHA256 { salt, hash } => Ok(Password {
                material: Kdf::SSHA256(salt.to_vec(), hash.to_vec()),
            }),
            ReplPasswordV1::SHA512 { hash } => Ok(Password {
                material: Kdf::SHA512(hash.to_vec()),
            }),
            ReplPasswordV1::SSHA512 { salt, hash } => Ok(Password {
                material: Kdf::SSHA512(salt.to_vec(), hash.to_vec()),
            }),
            ReplPasswordV1::NT_MD4 { hash } => Ok(Password {
                material: Kdf::NT_MD4(hash.to_vec()),
            }),
        }
    }
}

// OpenLDAP based their PBKDF2 implementation on passlib from python, that uses a
// non-standard base64 altchar set and padding that is not supported by
// anything else in the world. To manage this, we only ever encode to base64 with
// no pad but we have to remap ab64 to b64. This function allows b64 standard with
// padding to pass, and remaps ab64 to b64 standard with padding.
macro_rules! ab64_to_b64 {
    ($ab64:expr) => {{
        let mut s = $ab64.replace(".", "+");
        match s.len() & 3 {
            0 => {
                // Do nothing
            }
            1 => {
                // One is invalid, do nothing, we'll error in base64
            }
            2 => s.push_str("=="),
            3 => s.push_str("="),
            _ => unreachable!(),
        }
        s
    }};
}

impl TryFrom<&str> for Password {
    type Error = ();

    // As we may add more algos, we keep the match algo single for later.
    #[allow(clippy::single_match)]
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        // There is probably a more efficient way to try this given different types?

        // test django - algo$salt$hash
        let django_pbkdf: Vec<&str> = value.split('$').collect();
        if django_pbkdf.len() == 4 {
            let algo = django_pbkdf[0];
            let cost = django_pbkdf[1];
            let salt = django_pbkdf[2];
            let hash = django_pbkdf[3];
            match algo {
                "pbkdf2_sha256" => {
                    let c = cost.parse::<usize>().map_err(|_| ())?;
                    let s: Vec<_> = salt.as_bytes().to_vec();
                    let h = general_purpose::STANDARD.decode(hash).map_err(|_| ())?;
                    if h.len() < PBKDF2_MIN_NIST_KEY_LEN {
                        return Err(());
                    }
                    return Ok(Password {
                        material: Kdf::PBKDF2(c, s, h),
                    });
                }
                _ => {}
            }
        }

        if value.starts_with("ipaNTHash: ") {
            let nt_md4 = match value.split_once(' ') {
                Some((_, v)) => v,
                None => {
                    return Err(());
                }
            };

            // Great work.
            let h = base64::engine::general_purpose::URL_SAFE_NO_PAD
                .decode(nt_md4)
                .or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(nt_md4))
                .map_err(|_| ())?;

            return Ok(Password {
                material: Kdf::NT_MD4(h),
            });
        }

        if value.starts_with("sambaNTPassword: ") {
            let nt_md4 = match value.split_once(' ') {
                Some((_, v)) => v,
                None => {
                    return Err(());
                }
            };

            let h = hex::decode(nt_md4).map_err(|_| ())?;
            return Ok(Password {
                material: Kdf::NT_MD4(h),
            });
        }

        // Test 389ds formats

        if let Some(ds_ssha1) = value.strip_prefix("{SHA}") {
            let h = general_purpose::STANDARD.decode(ds_ssha1).map_err(|_| ())?;
            if h.len() != DS_SHA1_HASH_LEN {
                return Err(());
            }
            return Ok(Password {
                material: Kdf::SHA1(h.to_vec()),
            });
        }

        if let Some(ds_ssha1) = value.strip_prefix("{SSHA}") {
            let sh = general_purpose::STANDARD.decode(ds_ssha1).map_err(|_| ())?;
            let (h, s) = sh.split_at(DS_SHA1_HASH_LEN);
            if s.len() != DS_SHA_SALT_LEN {
                return Err(());
            }
            return Ok(Password {
                material: Kdf::SSHA1(s.to_vec(), h.to_vec()),
            });
        }

        if let Some(ds_ssha256) = value.strip_prefix("{SHA256}") {
            let h = general_purpose::STANDARD
                .decode(ds_ssha256)
                .map_err(|_| ())?;
            if h.len() != DS_SHA256_HASH_LEN {
                return Err(());
            }
            return Ok(Password {
                material: Kdf::SHA256(h.to_vec()),
            });
        }

        if let Some(ds_ssha256) = value.strip_prefix("{SSHA256}") {
            let sh = general_purpose::STANDARD
                .decode(ds_ssha256)
                .map_err(|_| ())?;
            let (h, s) = sh.split_at(DS_SHA256_HASH_LEN);
            if s.len() != DS_SHA_SALT_LEN {
                return Err(());
            }
            return Ok(Password {
                material: Kdf::SSHA256(s.to_vec(), h.to_vec()),
            });
        }

        if let Some(ds_ssha512) = value.strip_prefix("{SHA512}") {
            let h = general_purpose::STANDARD
                .decode(ds_ssha512)
                .map_err(|_| ())?;
            if h.len() != DS_SHA512_HASH_LEN {
                return Err(());
            }
            return Ok(Password {
                material: Kdf::SHA512(h.to_vec()),
            });
        }

        if let Some(ds_ssha512) = value.strip_prefix("{SSHA512}") {
            let sh = general_purpose::STANDARD
                .decode(ds_ssha512)
                .map_err(|_| ())?;
            let (h, s) = sh.split_at(DS_SHA512_HASH_LEN);
            if s.len() != DS_SHA_SALT_LEN {
                return Err(());
            }
            return Ok(Password {
                material: Kdf::SSHA512(s.to_vec(), h.to_vec()),
            });
        }

        // Test for OpenLDAP formats
        if value.starts_with("{PBKDF2}")
            || value.starts_with("{PBKDF2-SHA1}")
            || value.starts_with("{PBKDF2-SHA256}")
            || value.starts_with("{PBKDF2-SHA512}")
        {
            let ol_pbkdf2 = match value.split_once('}') {
                Some((_, v)) => v,
                None => {
                    return Err(());
                }
            };

            let ol_pbkdf: Vec<&str> = ol_pbkdf2.split('$').collect();
            if ol_pbkdf.len() == 3 {
                let cost = ol_pbkdf[0];
                let salt = ol_pbkdf[1];
                let hash = ol_pbkdf[2];

                let c = cost.parse::<usize>().map_err(|_| ())?;

                let s = ab64_to_b64!(salt);
                let base64_decoder_config = general_purpose::GeneralPurposeConfig::new()
                    .with_decode_allow_trailing_bits(true);
                let base64_decoder =
                    GeneralPurpose::new(&alphabet::STANDARD, base64_decoder_config);
                let s = base64_decoder.decode(s).map_err(|e| {
                    error!(?e, "Invalid base64 in oldap pbkdf2-sha1");
                })?;

                let h = ab64_to_b64!(hash);
                let h = base64_decoder.decode(h).map_err(|e| {
                    error!(?e, "Invalid base64 in oldap pbkdf2-sha1");
                })?;

                // This is just sha1 in a trenchcoat.
                if value.strip_prefix("{PBKDF2}").is_some()
                    || value.strip_prefix("{PBKDF2-SHA1}").is_some()
                {
                    if h.len() < PBKDF2_SHA1_MIN_KEY_LEN {
                        return Err(());
                    }
                    return Ok(Password {
                        material: Kdf::PBKDF2_SHA1(c, s, h),
                    });
                }

                if value.strip_prefix("{PBKDF2-SHA256}").is_some() {
                    if h.len() < PBKDF2_MIN_NIST_KEY_LEN {
                        return Err(());
                    }
                    return Ok(Password {
                        material: Kdf::PBKDF2(c, s, h),
                    });
                }

                if value.strip_prefix("{PBKDF2-SHA512}").is_some() {
                    if h.len() < PBKDF2_MIN_NIST_KEY_LEN {
                        return Err(());
                    }
                    return Ok(Password {
                        material: Kdf::PBKDF2_SHA512(c, s, h),
                    });
                }

                // Should be no way to get here!
                return Err(());
            } else {
                warn!("oldap pbkdf2 found but invalid number of elements?");
            }
        }

        if let Some(argon2_phc) = value.strip_prefix("{ARGON2}") {
            match PasswordHash::try_from(argon2_phc) {
                Ok(PasswordHash {
                    algorithm,
                    version,
                    params,
                    salt,
                    hash,
                }) => {
                    if algorithm.as_str() != "argon2id" {
                        error!(alg = %algorithm.as_str(), "Only argon2id is supported");
                        return Err(());
                    }

                    let version = version.unwrap_or(ARGON2_VERSION);
                    let version: Version = version.try_into().map_err(|_| {
                        error!("Failed to convert {} to valid argon2id version", version);
                    })?;

                    let m_cost = params.get_decimal("m").ok_or_else(|| {
                        error!("Failed to access m_cost parameter");
                    })?;

                    let t_cost = params.get_decimal("t").ok_or_else(|| {
                        error!("Failed to access t_cost parameter");
                    })?;

                    let p_cost = params.get_decimal("p").ok_or_else(|| {
                        error!("Failed to access p_cost parameter");
                    })?;

                    let salt = salt
                        .and_then(|s| {
                            let mut salt_arr = [0u8; 64];
                            s.decode_b64(&mut salt_arr)
                                .ok()
                                .map(|salt_bytes| salt_bytes.to_owned())
                        })
                        .ok_or_else(|| {
                            error!("Failed to access salt");
                        })?;

                    error!(?salt);

                    let key = hash.map(|h| h.as_bytes().into()).ok_or_else(|| {
                        error!("Failed to access key");
                    })?;

                    return Ok(Password {
                        material: Kdf::ARGON2ID {
                            m_cost,
                            t_cost,
                            p_cost,
                            version: version as u32,
                            salt,
                            key,
                        },
                    });
                }
                Err(e) => {
                    error!(?e, "Invalid argon2 phc string");
                    return Err(());
                }
            }
        }

        // Nothing matched to this point.
        Err(())
    }
}

impl Password {
    fn bench_pbkdf2(pbkdf2_cost: usize) -> Option<Duration> {
        let mut rng = rand::thread_rng();
        let salt: Vec<u8> = (0..PBKDF2_SALT_LEN).map(|_| rng.gen()).collect();
        let input: Vec<u8> = (0..PBKDF2_SALT_LEN).map(|_| rng.gen()).collect();
        // This is 512 bits of output
        let mut key: Vec<u8> = (0..PBKDF2_KEY_LEN).map(|_| 0).collect();

        let start = Instant::now();
        pbkdf2_hmac(
            input.as_slice(),
            salt.as_slice(),
            pbkdf2_cost,
            MessageDigest::sha256(),
            key.as_mut_slice(),
        )
        .ok()?;
        let end = Instant::now();

        end.checked_duration_since(start)
    }

    fn bench_argon2id(params: Params) -> Option<Duration> {
        let mut rng = rand::thread_rng();
        let salt: Vec<u8> = (0..ARGON2_SALT_LEN).map(|_| rng.gen()).collect();
        let input: Vec<u8> = (0..ARGON2_SALT_LEN).map(|_| rng.gen()).collect();
        let mut key: Vec<u8> = (0..ARGON2_KEY_LEN).map(|_| 0).collect();

        let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);

        let start = Instant::now();
        argon
            .hash_password_into(input.as_slice(), salt.as_slice(), key.as_mut_slice())
            .ok()?;
        let end = Instant::now();

        end.checked_duration_since(start)
    }

    pub fn new_pbkdf2(policy: &CryptoPolicy, cleartext: &str) -> Result<Self, CryptoError> {
        let pbkdf2_cost = policy.pbkdf2_cost;
        let mut rng = rand::thread_rng();
        let salt: Vec<u8> = (0..PBKDF2_SALT_LEN).map(|_| rng.gen()).collect();
        let mut key: Vec<u8> = (0..PBKDF2_KEY_LEN).map(|_| 0).collect();

        pbkdf2_hmac(
            cleartext.as_bytes(),
            salt.as_slice(),
            pbkdf2_cost,
            MessageDigest::sha256(),
            key.as_mut_slice(),
        )
        .map(|()| {
            // Turn key to a vec.
            Kdf::PBKDF2(pbkdf2_cost, salt, key)
        })
        .map(|material| Password { material })
        .map_err(|e| e.into())
    }

    pub fn new_argon2id(policy: &CryptoPolicy, cleartext: &str) -> Result<Self, CryptoError> {
        let version = Version::V0x13;

        let argon = Argon2::new(Algorithm::Argon2id, version, policy.argon2id_params.clone());

        let mut rng = rand::thread_rng();
        let salt: Vec<u8> = (0..ARGON2_SALT_LEN).map(|_| rng.gen()).collect();
        let mut key: Vec<u8> = (0..ARGON2_KEY_LEN).map(|_| 0).collect();

        argon
            .hash_password_into(cleartext.as_bytes(), salt.as_slice(), key.as_mut_slice())
            .map(|()| Kdf::ARGON2ID {
                m_cost: policy.argon2id_params.m_cost(),
                t_cost: policy.argon2id_params.t_cost(),
                p_cost: policy.argon2id_params.p_cost(),
                version: version as u32,
                salt,
                key,
            })
            .map_err(|_| CryptoError::Argon2)
            .map(|material| Password { material })
    }

    pub fn new_argon2id_hsm(
        policy: &CryptoPolicy,
        cleartext: &str,
        hsm: &mut dyn Tpm,
        hmac_key: &HmacKey,
    ) -> Result<Self, CryptoError> {
        let version = Version::V0x13;

        let argon = Argon2::new(Algorithm::Argon2id, version, policy.argon2id_params.clone());

        let mut rng = rand::thread_rng();
        let salt: Vec<u8> = (0..ARGON2_SALT_LEN).map(|_| rng.gen()).collect();
        let mut check_key: Vec<u8> = (0..ARGON2_KEY_LEN).map(|_| 0).collect();

        argon
            .hash_password_into(
                cleartext.as_bytes(),
                salt.as_slice(),
                check_key.as_mut_slice(),
            )
            .map_err(|_| CryptoError::Argon2)
            .and_then(|()| {
                hsm.hmac(hmac_key, &check_key).map_err(|err| {
                    error!(?err, "hsm error");
                    CryptoError::Hsm
                })
            })
            .map(|key| Kdf::TPM_ARGON2ID {
                m_cost: policy.argon2id_params.m_cost(),
                t_cost: policy.argon2id_params.t_cost(),
                p_cost: policy.argon2id_params.p_cost(),
                version: version as u32,
                salt,
                key,
            })
            .map(|material| Password { material })
    }

    #[inline]
    pub fn new(policy: &CryptoPolicy, cleartext: &str) -> Result<Self, CryptoError> {
        Self::new_argon2id(policy, cleartext)
    }

    pub fn verify(&self, cleartext: &str) -> Result<bool, CryptoError> {
        self.verify_ctx(cleartext, None)
    }

    pub fn verify_ctx(
        &self,
        cleartext: &str,
        hsm: Option<(&mut dyn Tpm, &HmacKey)>,
    ) -> Result<bool, CryptoError> {
        match (&self.material, hsm) {
            (
                Kdf::TPM_ARGON2ID {
                    m_cost,
                    t_cost,
                    p_cost,
                    version,
                    salt,
                    key,
                },
                Some((hsm, hmac_key)),
            ) => {
                let version: Version = (*version).try_into().map_err(|_| {
                    error!("Failed to convert {} to valid argon2id version", version);
                    CryptoError::Argon2Version
                })?;

                let key_len = key.len();

                let params =
                    Params::new(*m_cost, *t_cost, *p_cost, Some(key_len)).map_err(|e| {
                        error!(err = ?e, "invalid argon2id parameters");
                        CryptoError::Argon2Parameters
                    })?;

                let argon = Argon2::new(Algorithm::Argon2id, version, params);
                let mut check_key: Vec<u8> = (0..key_len).map(|_| 0).collect();

                argon
                    .hash_password_into(
                        cleartext.as_bytes(),
                        salt.as_slice(),
                        check_key.as_mut_slice(),
                    )
                    .map_err(|e| {
                        error!(err = ?e, "unable to perform argon2id hash");
                        CryptoError::Argon2
                    })
                    .and_then(|()| {
                        hsm.hmac(hmac_key, &check_key).map_err(|err| {
                            error!(?err, "hsm error");
                            CryptoError::Hsm
                        })
                    })
                    .map(|hmac_key| {
                        // Actually compare the outputs.
                        &hmac_key == key
                    })
            }
            (Kdf::TPM_ARGON2ID { .. }, None) => {
                error!("Unable to validate password - not hsm context available");
                Err(CryptoError::HsmContextMissing)
            }
            (
                Kdf::ARGON2ID {
                    m_cost,
                    t_cost,
                    p_cost,
                    version,
                    salt,
                    key,
                },
                _,
            ) => {
                let version: Version = (*version).try_into().map_err(|_| {
                    error!("Failed to convert {} to valid argon2id version", version);
                    CryptoError::Argon2Version
                })?;

                let key_len = key.len();

                let params =
                    Params::new(*m_cost, *t_cost, *p_cost, Some(key_len)).map_err(|e| {
                        error!(err = ?e, "invalid argon2id parameters");
                        CryptoError::Argon2Parameters
                    })?;

                let argon = Argon2::new(Algorithm::Argon2id, version, params);
                let mut check_key: Vec<u8> = (0..key_len).map(|_| 0).collect();

                argon
                    .hash_password_into(
                        cleartext.as_bytes(),
                        salt.as_slice(),
                        check_key.as_mut_slice(),
                    )
                    .map_err(|e| {
                        error!(err = ?e, "unable to perform argon2id hash");
                        CryptoError::Argon2
                    })
                    .map(|()| {
                        // Actually compare the outputs.
                        &check_key == key
                    })
            }
            (Kdf::PBKDF2(cost, salt, key), _) => {
                // We have to get the number of bits to derive from our stored hash
                // as some imported hash types may have variable lengths
                let key_len = key.len();
                debug_assert!(key_len >= PBKDF2_MIN_NIST_KEY_LEN);
                let mut chal_key: Vec<u8> = (0..key_len).map(|_| 0).collect();
                pbkdf2_hmac(
                    cleartext.as_bytes(),
                    salt.as_slice(),
                    *cost,
                    MessageDigest::sha256(),
                    chal_key.as_mut_slice(),
                )
                .map(|()| {
                    // Actually compare the outputs.
                    &chal_key == key
                })
                .map_err(|e| e.into())
            }
            (Kdf::PBKDF2_SHA1(cost, salt, key), _) => {
                let key_len = key.len();
                debug_assert!(key_len >= PBKDF2_SHA1_MIN_KEY_LEN);
                let mut chal_key: Vec<u8> = (0..key_len).map(|_| 0).collect();
                pbkdf2_hmac(
                    cleartext.as_bytes(),
                    salt.as_slice(),
                    *cost,
                    MessageDigest::sha1(),
                    chal_key.as_mut_slice(),
                )
                .map(|()| {
                    // Actually compare the outputs.
                    &chal_key == key
                })
                .map_err(|e| e.into())
            }
            (Kdf::PBKDF2_SHA512(cost, salt, key), _) => {
                let key_len = key.len();
                debug_assert!(key_len >= PBKDF2_MIN_NIST_KEY_LEN);
                let mut chal_key: Vec<u8> = (0..key_len).map(|_| 0).collect();
                pbkdf2_hmac(
                    cleartext.as_bytes(),
                    salt.as_slice(),
                    *cost,
                    MessageDigest::sha512(),
                    chal_key.as_mut_slice(),
                )
                .map(|()| {
                    // Actually compare the outputs.
                    &chal_key == key
                })
                .map_err(|e| e.into())
            }
            (Kdf::SHA1(key), _) => {
                let mut hasher = Sha1::new();
                hasher.update(cleartext.as_bytes());
                let r = hasher.finish();
                Ok(key == &(r.to_vec()))
            }
            (Kdf::SSHA1(salt, key), _) => {
                let mut hasher = Sha1::new();
                hasher.update(cleartext.as_bytes());
                hasher.update(salt);
                let r = hasher.finish();
                Ok(key == &(r.to_vec()))
            }
            (Kdf::SHA256(key), _) => {
                let mut hasher = Sha256::new();
                hasher.update(cleartext.as_bytes());
                let r = hasher.finish();
                Ok(key == &(r.to_vec()))
            }
            (Kdf::SSHA256(salt, key), _) => {
                let mut hasher = Sha256::new();
                hasher.update(cleartext.as_bytes());
                hasher.update(salt);
                let r = hasher.finish();
                Ok(key == &(r.to_vec()))
            }
            (Kdf::SHA512(key), _) => {
                let mut hasher = Sha512::new();
                hasher.update(cleartext.as_bytes());
                let r = hasher.finish();
                Ok(key == &(r.to_vec()))
            }
            (Kdf::SSHA512(salt, key), _) => {
                let mut hasher = Sha512::new();
                hasher.update(cleartext.as_bytes());
                hasher.update(salt);
                let r = hasher.finish();
                Ok(key == &(r.to_vec()))
            }
            (Kdf::NT_MD4(key), _) => {
                // We need to get the cleartext to utf16le for reasons.
                let clear_utf16le: Vec<u8> = cleartext
                    .encode_utf16()
                    .map(|c| c.to_le_bytes())
                    .flat_map(|i| i.into_iter())
                    .collect();

                let dgst = MessageDigest::from_nid(Nid::MD4).ok_or_else(|| {
                    error!("Unable to access MD4 - fips mode may be enabled, or you may need to activate the legacy provider.");
                    error!("For more details, see https://wiki.openssl.org/index.php/OpenSSL_3.0#Providers");
                    CryptoError::Md4Disabled
                })?;

                hash::hash(dgst, &clear_utf16le)
                    .map_err(|e| {
                        debug!(?e);
                        error!("Unable to digest MD4 - fips mode may be enabled, or you may need to activate the legacy provider.");
                        error!("For more details, see https://wiki.openssl.org/index.php/OpenSSL_3.0#Providers");
                        CryptoError::Md4Disabled
                    })
                    .map(|chal_key| chal_key.as_ref() == key)
            }
        }
    }

    pub fn to_dbpasswordv1(&self) -> DbPasswordV1 {
        match &self.material {
            Kdf::TPM_ARGON2ID {
                m_cost,
                t_cost,
                p_cost,
                version,
                salt,
                key,
            } => DbPasswordV1::TPM_ARGON2ID {
                m: *m_cost,
                t: *t_cost,
                p: *p_cost,
                v: *version,
                s: salt.clone().into(),
                k: key.clone().into(),
            },
            Kdf::ARGON2ID {
                m_cost,
                t_cost,
                p_cost,
                version,
                salt,
                key,
            } => DbPasswordV1::ARGON2ID {
                m: *m_cost,
                t: *t_cost,
                p: *p_cost,
                v: *version,
                s: salt.clone().into(),
                k: key.clone().into(),
            },
            Kdf::PBKDF2(cost, salt, hash) => {
                DbPasswordV1::PBKDF2(*cost, salt.clone(), hash.clone())
            }
            Kdf::PBKDF2_SHA1(cost, salt, hash) => {
                DbPasswordV1::PBKDF2_SHA1(*cost, salt.clone(), hash.clone())
            }
            Kdf::PBKDF2_SHA512(cost, salt, hash) => {
                DbPasswordV1::PBKDF2_SHA512(*cost, salt.clone(), hash.clone())
            }
            Kdf::SHA1(hash) => DbPasswordV1::SHA1(hash.clone()),
            Kdf::SSHA1(salt, hash) => DbPasswordV1::SSHA1(salt.clone(), hash.clone()),
            Kdf::SHA256(hash) => DbPasswordV1::SHA256(hash.clone()),
            Kdf::SSHA256(salt, hash) => DbPasswordV1::SSHA256(salt.clone(), hash.clone()),
            Kdf::SHA512(hash) => DbPasswordV1::SHA512(hash.clone()),
            Kdf::SSHA512(salt, hash) => DbPasswordV1::SSHA512(salt.clone(), hash.clone()),
            Kdf::NT_MD4(hash) => DbPasswordV1::NT_MD4(hash.clone()),
        }
    }

    pub fn to_repl_v1(&self) -> ReplPasswordV1 {
        match &self.material {
            Kdf::TPM_ARGON2ID {
                m_cost,
                t_cost,
                p_cost,
                version,
                salt,
                key,
            } => ReplPasswordV1::TPM_ARGON2ID {
                m_cost: *m_cost,
                t_cost: *t_cost,
                p_cost: *p_cost,
                version: *version,
                salt: salt.clone().into(),
                key: key.clone().into(),
            },
            Kdf::ARGON2ID {
                m_cost,
                t_cost,
                p_cost,
                version,
                salt,
                key,
            } => ReplPasswordV1::ARGON2ID {
                m_cost: *m_cost,
                t_cost: *t_cost,
                p_cost: *p_cost,
                version: *version,
                salt: salt.clone().into(),
                key: key.clone().into(),
            },
            Kdf::PBKDF2(cost, salt, hash) => ReplPasswordV1::PBKDF2 {
                cost: *cost,
                salt: salt.clone().into(),
                hash: hash.clone().into(),
            },
            Kdf::PBKDF2_SHA1(cost, salt, hash) => ReplPasswordV1::PBKDF2_SHA1 {
                cost: *cost,
                salt: salt.clone().into(),
                hash: hash.clone().into(),
            },
            Kdf::PBKDF2_SHA512(cost, salt, hash) => ReplPasswordV1::PBKDF2_SHA512 {
                cost: *cost,
                salt: salt.clone().into(),
                hash: hash.clone().into(),
            },
            Kdf::SHA1(hash) => ReplPasswordV1::SHA1 {
                hash: hash.clone().into(),
            },
            Kdf::SSHA1(salt, hash) => ReplPasswordV1::SSHA1 {
                salt: salt.clone().into(),
                hash: hash.clone().into(),
            },
            Kdf::SHA256(hash) => ReplPasswordV1::SHA256 {
                hash: hash.clone().into(),
            },
            Kdf::SSHA256(salt, hash) => ReplPasswordV1::SSHA256 {
                salt: salt.clone().into(),
                hash: hash.clone().into(),
            },
            Kdf::SHA512(hash) => ReplPasswordV1::SHA512 {
                hash: hash.clone().into(),
            },
            Kdf::SSHA512(salt, hash) => ReplPasswordV1::SSHA512 {
                salt: salt.clone().into(),
                hash: hash.clone().into(),
            },
            Kdf::NT_MD4(hash) => ReplPasswordV1::NT_MD4 {
                hash: hash.clone().into(),
            },
        }
    }

    pub fn requires_upgrade(&self) -> bool {
        match &self.material {
            Kdf::ARGON2ID {
                m_cost,
                t_cost,
                p_cost,
                version,
                salt,
                key,
            } => {
                *version < ARGON2_VERSION ||
                salt.len() < ARGON2_SALT_LEN ||
                key.len() < ARGON2_KEY_LEN ||
                // Can't multi-thread
                *p_cost > ARGON2_MAX_P_COST ||
                // Likely too long on cpu time.
                *t_cost > ARGON2_MAX_T_COST ||
                // Too much ram
                *m_cost > ARGON2_MAX_RAM_KIB
            }
            // Only used in unixd today
            Kdf::TPM_ARGON2ID { .. } => false,
            // All now upgraded to argon2id
            Kdf::PBKDF2(_, _, _)
            | Kdf::PBKDF2_SHA512(_, _, _)
            | Kdf::PBKDF2_SHA1(_, _, _)
            | Kdf::SHA1(_)
            | Kdf::SSHA1(_, _)
            | Kdf::SHA256(_)
            | Kdf::SSHA256(_, _)
            | Kdf::SHA512(_)
            | Kdf::SSHA512(_, _)
            | Kdf::NT_MD4(_) => true,
        }
    }
}

#[cfg(test)]
mod tests {
    use kanidm_hsm_crypto::soft::SoftTpm;
    use kanidm_hsm_crypto::AuthValue;
    use std::convert::TryFrom;

    use crate::*;

    #[test]
    fn test_credential_simple() {
        let p = CryptoPolicy::minimum();
        let c = Password::new(&p, "password").unwrap();
        assert!(c.verify("password").unwrap());
        assert!(!c.verify("password1").unwrap());
        assert!(!c.verify("Password1").unwrap());
        assert!(!c.verify("It Works!").unwrap());
        assert!(!c.verify("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap());
    }

    #[test]
    fn test_password_pbkdf2() {
        let p = CryptoPolicy::minimum();
        let c = Password::new_pbkdf2(&p, "password").unwrap();
        assert!(c.verify("password").unwrap());
        assert!(!c.verify("password1").unwrap());
        assert!(!c.verify("Password1").unwrap());
    }

    #[test]
    fn test_password_argon2id() {
        let p = CryptoPolicy::minimum();
        let c = Password::new_argon2id(&p, "password").unwrap();
        assert!(c.verify("password").unwrap());
        assert!(!c.verify("password1").unwrap());
        assert!(!c.verify("Password1").unwrap());
    }

    #[test]
    fn test_password_from_invalid() {
        assert!(Password::try_from("password").is_err())
    }

    #[test]
    fn test_password_from_django_pbkdf2_sha256() {
        let im_pw = "pbkdf2_sha256$36000$xIEozuZVAoYm$uW1b35DUKyhvQAf1mBqMvoBDcqSD06juzyO/nmyV0+w=";
        let password = "eicieY7ahchaoCh0eeTa";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        assert!(r.verify(password).unwrap_or(false));
    }

    #[test]
    fn test_password_from_ds_sha1() {
        let im_pw = "{SHA}W6ph5Mm5Pz8GgiULbPgzG37mj9g=";
        let password = "password";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        // Known weak, require upgrade.
        assert!(r.requires_upgrade());
        assert!(r.verify(password).unwrap_or(false));
    }

    #[test]
    fn test_password_from_ds_ssha1() {
        let im_pw = "{SSHA}EyzbBiP4u4zxOrLpKTORI/RX3HC6TCTJtnVOCQ==";
        let password = "password";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        // Known weak, require upgrade.
        assert!(r.requires_upgrade());
        assert!(r.verify(password).unwrap_or(false));
    }

    #[test]
    fn test_password_from_ds_sha256() {
        let im_pw = "{SHA256}XohImNooBHFR0OVvjcYpJ3NgPQ1qq73WKhHvch0VQtg=";
        let password = "password";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        // Known weak, require upgrade.
        assert!(r.requires_upgrade());
        assert!(r.verify(password).unwrap_or(false));
    }

    #[test]
    fn test_password_from_ds_ssha256() {
        let im_pw = "{SSHA256}luYWfFJOZgxySTsJXHgIaCYww4yMpu6yest69j/wO5n5OycuHFV/GQ==";
        let password = "password";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        // Known weak, require upgrade.
        assert!(r.requires_upgrade());
        assert!(r.verify(password).unwrap_or(false));
    }

    #[test]
    fn test_password_from_ds_sha512() {
        let im_pw = "{SHA512}sQnzu7wkTrgkQZF+0G1hi5AI3Qmzvv0bXgc5THBqi7mAsdd4Xll27ASbRt9fEyavWi6m0QP9B8lThf+rDKy8hg==";
        let password = "password";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        // Known weak, require upgrade.
        assert!(r.requires_upgrade());
        assert!(r.verify(password).unwrap_or(false));
    }

    #[test]
    fn test_password_from_ds_ssha512() {
        let im_pw = "{SSHA512}JwrSUHkI7FTAfHRVR6KoFlSN0E3dmaQWARjZ+/UsShYlENOqDtFVU77HJLLrY2MuSp0jve52+pwtdVl2QUAHukQ0XUf5LDtM";
        let password = "password";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        // Known weak, require upgrade.
        assert!(r.requires_upgrade());
        assert!(r.verify(password).unwrap_or(false));
    }

    // Can be generated with:
    // slappasswd -s password -o module-load=/usr/lib64/openldap/pw-argon2.so -h {ARGON2}

    #[test]
    fn test_password_from_openldap_pkbdf2() {
        let im_pw = "{PBKDF2}10000$IlfapjA351LuDSwYC0IQ8Q$saHqQTuYnjJN/tmAndT.8mJt.6w";
        let password = "password";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        assert!(r.requires_upgrade());
        assert!(r.verify(password).unwrap_or(false));
    }

    #[test]
    fn test_password_from_openldap_pkbdf2_sha1() {
        let im_pw = "{PBKDF2-SHA1}10000$ZBEH6B07rgQpJSikyvMU2w$TAA03a5IYkz1QlPsbJKvUsTqNV";
        let password = "password";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        assert!(r.requires_upgrade());
        assert!(r.verify(password).unwrap_or(false));
    }

    #[test]
    fn test_password_from_openldap_pkbdf2_sha256() {
        let im_pw = "{PBKDF2-SHA256}10000$henZGfPWw79Cs8ORDeVNrQ$1dTJy73v6n3bnTmTZFghxHXHLsAzKaAy8SksDfZBPIw";
        let password = "password";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        assert!(r.requires_upgrade());
        assert!(r.verify(password).unwrap_or(false));
    }

    #[test]
    fn test_password_from_openldap_pkbdf2_sha512() {
        let im_pw = "{PBKDF2-SHA512}10000$Je1Uw19Bfv5lArzZ6V3EPw$g4T/1sqBUYWl9o93MVnyQ/8zKGSkPbKaXXsT8WmysXQJhWy8MRP2JFudSL.N9RklQYgDPxPjnfum/F2f/TrppA";
        let password = "password";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        assert!(r.requires_upgrade());
        assert!(r.verify(password).unwrap_or(false));
    }

    // Not supported in openssl, may need an external crate.
    #[test]
    fn test_password_from_openldap_argon2() {
        sketching::test_init();
        let im_pw = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$IyTQMsvzB2JHDiWx8fq7Ew$VhYOA7AL0kbRXI5g2kOyyp8St1epkNj7WZyUY4pAIQQ";
        let password = "password";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        assert!(!r.requires_upgrade());
        assert!(r.verify(password).unwrap_or(false));
    }

    /*
     * wbrown - 20221104 - I tried to programmatically enable the legacy provider, but
     * it consistently "did nothing at all", meaning we have to rely on users to enable
     * this for this test.
     */

    /*
    #[cfg(openssl3)]
    fn setup_openssl_legacy_provider() -> openssl::lib_ctx::LibCtx {
        let ctx = openssl::lib_ctx::LibCtx::new()
            .expect("Failed to create new library context");

        openssl::provider::Provider::load(Some(&ctx), "legacy")
            .expect("Failed to setup provider.");

        eprintln!("setup legacy provider maybe??");

        ctx
    }
    */

    #[test]
    fn test_password_from_ipa_nt_hash() {
        sketching::test_init();
        // Base64 no pad
        let im_pw = "ipaNTHash: iEb36u6PsRetBr3YMLdYbA";
        let password = "password";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        assert!(r.requires_upgrade());

        match r.verify(password) {
            Ok(r) => assert!(r),
            Err(_) =>
            {
                #[allow(clippy::panic)]
                if cfg!(openssl3) {
                    warn!("To run this test, enable the legacy provider.");
                } else {
                    panic!("openssl3 not enabled");
                }
            }
        }

        let im_pw = "ipaNTHash: pS43DjQLcUYhaNF_cd_Vhw==";
        Password::try_from(im_pw).expect("Failed to parse");
    }

    #[test]
    fn test_password_from_samba_nt_hash() {
        sketching::test_init();
        // Base64 no pad
        let im_pw = "sambaNTPassword: 8846F7EAEE8FB117AD06BDD830B7586C";
        let password = "password";
        let r = Password::try_from(im_pw).expect("Failed to parse");
        assert!(r.requires_upgrade());
        match r.verify(password) {
            Ok(r) => assert!(r),
            Err(_) =>
            {
                #[allow(clippy::panic)]
                if cfg!(openssl3) {
                    warn!("To run this test, enable the legacy provider.");
                } else {
                    panic!("OpenSSL3 feature not enabled")
                }
            }
        }
    }

    #[test]
    fn test_password_argon2id_hsm_bind() {
        sketching::test_init();

        let mut hsm: Box<dyn Tpm> = Box::new(SoftTpm::new());

        let auth_value = AuthValue::ephemeral().unwrap();

        let loadable_machine_key = hsm.machine_key_create(&auth_value).unwrap();
        let machine_key = hsm
            .machine_key_load(&auth_value, &loadable_machine_key)
            .unwrap();

        let loadable_hmac_key = hsm.hmac_key_create(&machine_key).unwrap();
        let key = hsm.hmac_key_load(&machine_key, &loadable_hmac_key).unwrap();

        let ctx: &mut dyn Tpm = &mut *hsm;

        let p = CryptoPolicy::minimum();
        let c = Password::new_argon2id_hsm(&p, "password", ctx, &key).unwrap();

        assert!(matches!(
            c.verify("password"),
            Err(CryptoError::HsmContextMissing)
        ));

        // Assert it fails without the hmac
        let dup = match &c.material {
            Kdf::TPM_ARGON2ID {
                m_cost,
                t_cost,
                p_cost,
                version,
                salt,
                key,
            } => Password {
                material: Kdf::ARGON2ID {
                    m_cost: *m_cost,
                    t_cost: *t_cost,
                    p_cost: *p_cost,
                    version: *version,
                    salt: salt.clone(),
                    key: key.clone(),
                },
            },
            #[allow(clippy::unreachable)]
            _ => unreachable!(),
        };

        assert!(!dup.verify("password").unwrap());

        assert!(c.verify_ctx("password", Some((ctx, &key))).unwrap());
        assert!(!c.verify_ctx("password1", Some((ctx, &key))).unwrap());
        assert!(!c.verify_ctx("Password1", Some((ctx, &key))).unwrap());
    }
}