-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpwhash_argon2.c
More file actions
1116 lines (953 loc) · 28.4 KB
/
pwhash_argon2.c
File metadata and controls
1116 lines (953 loc) · 28.4 KB
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
//
// Created by bernd on 13.02.25.
//
#include "postgres.h"
#include "fmgr.h"
#include "catalog/pg_type_d.h"
#include "utils/builtins.h"
#if PG_VERSION_NUM >= 160000
#include <varatt.h>
#else
#include <postgres.h>
#endif
#include "argon2.h"
#include "pg_pwhash.h"
#include "pwhash_argon2.h"
#ifdef _PWHASH_ARGON2_OSSL_SUPPORT
#include "openssl/core_names.h"
#include "openssl/params.h"
#include "openssl/thread.h"
#include "openssl/kdf.h"
#endif
/* Argon2 default option values */
#define ARGON2_SALT_MAX_LEN 64
#define ARGON2_THREADS 1 /* number of computing threads */
#define ARGON2_MEMORY_LANES 1 /* memory size / lanes, processed in parallel */
/*
* Default number of iterations
*
* RFC 9106 says that this is the recommended setting for value t, see
*
* https://www.rfc-editor.org/rfc/rfc9106.html#name-argon2-algorithm
*
* section 7.4 (Recommendations) for details.
*
* The same applies to ARGON2_MEMORY_COST, which ideally is set to
* (2^31) == 2GiB of memory. But since we might deal with memory constrained
* systems we set it to much lower memory settings.
*/
#define ARGON2_ROUNDS 3
#define ARGON2_MEMORY_COST 4096 /* equals to 4MB of mem */
#define ARGON2_MAGIC_BYTE_ID "$argon2id$"
#define ARGON2_MAGIC_BYTE_D "$argon2d$"
#define ARGON2_MAGIC_BYTE_I "$argon2i$"
/*
* The following are lower and upper limits allowed for settings for hash
* computing. RFC 9106 allows far bigger values for some of these options. But
* we put a far more strict boundary on some of them for practical reasons.
*
* See
*
* https://www.rfc-editor.org/rfc/rfc9106.html#name-argon2-algorithm
*
* for details again.
*/
/* Min threads allwoed for hashing */
#define PWHASH_ARGON2_MIN_THREADS 1
/* Max threads allowed for hashing */
#define PWHASH_ARGON2_MAX_THREADS 1024
/* Min number of lanes */
#define PWHASH_ARGON2_MIN_LANES PWHASH_ARGON2_MIN_THREADS
/* Max number of lanes */
#define PWHASH_ARGON2_MAX_LANES PWHASH_ARGON2_MAX_THREADS
/* Min number for memcost (memory size) */
#define PWHASH_ARGON2_MIN_MEMCOST 8
/*
* Max number for memcost (memory size)
*
* We set this to match MaxAllocSize to match maximum request
* for memory allocations allowed in the backend (as of writing this comment
* around 1G).
*
* We can't rely on palloc() failing here, since allocations might be done
* outside our control in the hashing libraries, so be sure we don't allow
* arbitrary large values.
*/
#define PWHASH_ARGON2_MAX_MEMCOST 0x3fffffff
/* Min number of computation rounds */
#define PWHASH_ARGON2_MIN_ROUNDS 1
/* Max number of computation rounds */
#define PWHASH_ARGON2_MAX_ROUNDS INT_MAX
/* Min size of digest */
#define PWHASH_ARGON2_MIN_HASH_LEN 1
/*
* Max size of digest
*
* Translates to
*/
#define PWHASH_ARGON2_MAX_HASH_LEN 0x00ffffff
/*
* Default Argon2 version
*
* 0x13(19) is the default for OpenSSL and libargon2 backend
*
* Besides that, 0x10(16) might also be specified.
*/
#define ARGON2_DEFAULT_VERSION (unsigned int)0x13
/*
* The output format for the Argon2 digest
*/
typedef enum
{
ARGON2_OUTPUT_BASE64,
ARGON2_OUTPUT_HEX
} argon2_output_format_t;
/*
* Recommended tag length is 256 bits, see
*
* https://docs.openssl.org/3.2/man7/EVP_KDF-ARGON2/#description
*/
#define ARGON2_HASH_LEN 32
static StringInfo
xgen_salt_argon_internal(Datum *options,
int numoptions);
PG_FUNCTION_INFO_V1(pwhash_argon2);
/* Keep that in sync with below options array */
#define NUM_ARGON2_OPTIONS 7
static struct pwhash_option argon2_options[] =
{
{ "threads", "p", INT4OID, PWHASH_ARGON2_MIN_THREADS,
PWHASH_ARGON2_MAX_THREADS, { ._int_value = ARGON2_THREADS } },
{ "lanes", "l", INT4OID, PWHASH_ARGON2_MIN_LANES,
PWHASH_ARGON2_MAX_LANES, { ._int_value = ARGON2_MEMORY_LANES } },
{ "memcost", "m", INT4OID, PWHASH_ARGON2_MIN_MEMCOST,
PWHASH_ARGON2_MAX_MEMCOST, { ._int_value = ARGON2_MEMORY_COST } },
{ "rounds", "t", INT4OID, PWHASH_ARGON2_MIN_ROUNDS,
PWHASH_ARGON2_MAX_ROUNDS, { ._int_value = ARGON2_ROUNDS } },
{ "size", "size", INT4OID, PWHASH_ARGON2_MIN_HASH_LEN,
PWHASH_ARGON2_MAX_HASH_LEN, { ._int_value = ARGON2_HASH_LEN } },
/* Specific parameters to pg_pwhash */
{ "output_format", "output_format", -1, -1,
INT4OID, { ._int_value = ARGON2_OUTPUT_BASE64 } },
/* Default backend should be kept in sync with the GUC pg_pwhash.argon2_backend */
{ "backend", "backend", INT4OID, -1, -1,
{ ._int_value = ARGON2_BACKEND_TYPE_LIBARGON2 } }
};
/* *********************** Forwarded declarations *********************** */
static
void simple_salt_parser_init(struct parse_salt_info *pinfo,
struct pwhash_option *options,
size_t numoptions,
unsigned int argon2_version);
static
void _argon2_apply_options(Datum *options,
size_t numoptions,
int *threads,
int *lanes,
int *memory_cost,
int *rounds,
int *size,
argon2_output_format_t *output_format,
argon2_digest_backend_t *backend,
bool *explicit_backend_option);
/* *********************** Implementation *********************** */
static
void _argon2_apply_options(Datum *options,
size_t numoptions,
int *threads,
int *lanes,
int *memory_cost,
int *rounds,
int *size,
argon2_output_format_t *output_format,
argon2_digest_backend_t *backend,
bool *explicit_backend_option)
{
int i;
/* Set defaults first */
*threads = ARGON2_THREADS;
*lanes = ARGON2_MEMORY_LANES;
*memory_cost = ARGON2_MEMORY_COST;
*rounds = ARGON2_ROUNDS;
*size = ARGON2_HASH_LEN;
*output_format = ARGON2_OUTPUT_BASE64;
*backend = pwhash_get_digest_backend();
*explicit_backend_option = false;
for (i = 0; i < numoptions; i++)
{
char *str = TextDatumGetCString(options[i]);
/* Lookup value separator */
char *sep = strchr(str, '=');
if (sep)
{
struct pwhash_option *opt;
/* Make sure string is null terminated */
*sep++ = '\0';
opt = check_option(str,
argon2_options,
NUM_ARGON2_OPTIONS,
true);
if (opt != NULL)
{
if ((strncmp(opt->name, "threads", strlen(opt->name)) == 0)
&& (strncmp(opt->alias, "p", strlen(opt->alias))) == 0)
{
*threads = pg_strtoint32(sep);
/* Check allowed values for min/max */
pwhash_check_minmax(opt->min,
opt->max,
*threads,
opt->alias);
if (*lanes < *threads)
{
/*
* The number of lanes is currently smaller than the
* specified number of threads. Since argon2 requires this
* at least to be equal, we force lanes to be set to the same
* value than threads.
*
* Don't do this without giving the caller a warning that we do this,
* since the parameter lanes/l influences the final digest generation and
* produces different results depending on this.
*/
ereport(DEBUG1,
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("forcing parameter lanes/l equal to number of threads"),
errhint("This means that the number of lanes(l=%d) must be equal or greater than threads(p=%d)",
*lanes, *threads));
*lanes = *threads;
}
continue;
}
if ((strncmp(opt->name, "lanes", strlen(opt->name)) == 0)
&& (strncmp(opt->alias, "l", strlen(opt->alias))) == 0)
{
*lanes = pg_strtoint32(sep);
pwhash_check_minmax(opt->min,
opt->max,
*lanes,
opt->alias);
/*
* We need to be careful when setting lanes explicitely,
* since there can't be lanes < threads.
*/
if (*lanes < *threads)
{
ereport(ERROR,
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("lanes must be equal or greater than threads, currently lanes(l=%d) < threads(p=%d)",
*lanes, *threads));
}
continue;
}
if ((strncmp(opt->name, "memcost", strlen(opt->name)) == 0)
&& (strncmp(opt->alias, "m", strlen(opt->alias)) == 0))
{
*memory_cost = pg_strtoint32(sep);
pwhash_check_minmax(opt->min,
opt->max,
*memory_cost,
opt->alias);
continue;
}
if ((strncmp(opt->name, "rounds", strlen(opt->name)) == 0)
&& (strncmp(opt->alias, "t", strlen(opt->alias)) == 0))
{
*rounds = pg_strtoint32(sep);
pwhash_check_minmax(opt->min,
opt->max,
*rounds,
opt->alias);
continue;
}
if ((strncmp(opt->name, "size", strlen(opt->name)) == 0)
&& (strncmp(opt->alias, "size", strlen(opt->alias)) == 0))
{
*size = pg_strtoint32(sep);
pwhash_check_minmax(opt->min,
opt->max,
*size,
opt->alias);
continue;
}
if (strncmp(opt->name, "output_format", strlen(opt->name)) == 0)
{
/* We support either "hex" or "base64" (the latter is the
* default */
if (strncmp(sep, "base64", 6) == 0)
{
*output_format = ARGON2_OUTPUT_BASE64;
continue;
}
if (strncmp(sep, "hex", 3) == 0)
{
*output_format = ARGON2_OUTPUT_HEX;
continue;
}
/* Only reached in case of unknown output format */
ereport(ERROR,
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid value for parameter \"output_format\": \"%s\"",
sep));
}
if ((strncmp(opt->name, "backend", strlen(opt->alias)) == 0)
|| (strncmp(opt->alias, "backend", strlen(opt->alias))) == 0)
{
/* Backend option was explicitely requested, make sure we remember */
*explicit_backend_option = true;
if (strncmp(sep, "openssl", 7) == 0)
{
*backend = ARGON2_BACKEND_TYPE_OSSL;
continue;
}
if (strncmp(sep, "libargon2", 9) == 0)
{
*backend = ARGON2_BACKEND_TYPE_LIBARGON2;
continue;
}
/* Only reached in case of unknown backend type */
ereport(ERROR,
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("unsupported backend type \"%s\"",
sep));
}
}
}
}
}
static
void simple_salt_parser_init(struct parse_salt_info *pinfo,
struct pwhash_option *options,
size_t numoptions,
unsigned int argon2_version)
{
pinfo->magic = ARGON2_MAGIC_BYTE_ID;
pinfo->magic_len = strlen(pinfo->magic);
/* Record optional version info for selected argon2 version */
memset(pinfo->algo_info, '\0', PWHASH_ALGO_INFO_LEN + 1);
pg_snprintf(pinfo->algo_info, PWHASH_ALGO_INFO_LEN, "v=%u$",
argon2_version);
pinfo->algo_info_len = strlen(pinfo->algo_info);
pinfo->salt_len_min = ARGON2_SALT_MAX_LEN / 4;
pinfo->salt = NULL;
pinfo->salt_len = 0;
pinfo->opt_str = NULL;
pinfo->num_sect = 0;
pinfo->opt_len = 0;
pinfo->options = options;
pinfo->num_parse_options = numoptions;
}
static StringInfo
xgen_salt_argon_internal(Datum *options,
int numoptions)
{
StringInfo result = makeStringInfo();
bool need_sep = false;
int threads;
int lanes;
int memcost;
int rounds;
int size;
argon2_output_format_t output_format;
argon2_digest_backend_t backend;
bool explicit_backend_option;
_argon2_apply_options(options,
numoptions,
&threads,
&lanes,
&memcost,
&rounds,
&size,
&output_format,
&backend,
&explicit_backend_option);
/*
* NOTE: The option string for argon2 has the following format:
*
* $m=<memcost>,t=<compute rounds>,p=<threads[,data=<data>]
*
* according to
*
* https://passlib.readthedocs.io/en/stable/lib/passlib.hash.argon2.html
*
* We must compose the parameter string in the right order but still
* also support extensions with the lanes/l and size/size parameter.
* Note that the data=<data> parameter is also an extension to the format,
* but we don't implement that currently.
*/
if (lanes != ARGON2_MEMORY_LANES)
{
if (lanes != threads)
{
if (need_sep)
appendStringInfoCharMacro(result, ',');
appendStringInfo(result, "l=%d", lanes);
need_sep = true;
}
}
if (need_sep)
appendStringInfoCharMacro(result, ',');
appendStringInfo(result, "m=%d", memcost);
need_sep = true;
if (need_sep)
appendStringInfoCharMacro(result, ',');
appendStringInfo(result, "t=%d", rounds);
need_sep = true;
if (need_sep)
appendStringInfoCharMacro(result, ',');
appendStringInfo(result, "p=%d", threads);
need_sep = true;
if (size != ARGON2_HASH_LEN)
{
if (need_sep)
appendStringInfoCharMacro(result, ',');
appendStringInfo(result, "size=%d", size);
need_sep = true;
}
if (explicit_backend_option)
{
char *backend_str = (backend == ARGON2_BACKEND_TYPE_OSSL ? "openssl" : "libargon2");
if (need_sep)
appendStringInfoCharMacro(result, ',');
appendStringInfo(result, "backend=%s", backend_str);
need_sep = true;
}
return result;
}
StringInfo xgen_salt_argon2(Datum *options, int numoptions, const char *magic)
{
StringInfo result;
StringInfo buf;
#define ARGON2_DEFAULT_SALT_LEN (ARGON2_SALT_MAX_LEN / 4)
unsigned char salt_buf[ ARGON2_DEFAULT_SALT_LEN + 1 ];
char *salt_encoded;
/*
* Generate random bytes for the salt. We generate a random byte sequence
* of 16 bytes.
*/
result = makeStringInfo();
memset(&salt_buf, '\0', ARGON2_DEFAULT_SALT_LEN + 1);
if (!pg_strong_random(&salt_buf, ARGON2_DEFAULT_SALT_LEN))
{
elog(ERROR, "cannot generate random bytes for salt");
}
/* Remove bytes we don't want */
for (int i = 0; i < ARGON2_DEFAULT_SALT_LEN; i++)
{
if (salt_buf[i] == '\0')
{
salt_buf[i] = 'A';
}
}
/* TODO: Investigate passing the salt as hexsalt to OpenSSL:
* https://docs.openssl.org/1.1.1/man3/EVP_PKEY_CTX_set_scrypt_N/
*/
/* Convert binary string to base64 */
salt_encoded = pwhash_to_base64(salt_buf, ARGON2_DEFAULT_SALT_LEN);
/*
* Prepare preamble. We don't apply the magic string blindly, check it
* before.
*/
if (magic == NULL)
{
ereport(ERROR,
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("cannot generate a valid salt string with undefined magic string"));
}
if (strncmp(magic, ARGON2_MAGIC_BYTE_ID, strlen(ARGON2_MAGIC_BYTE_ID)) == 0)
{
appendStringInfoString(result, ARGON2_MAGIC_BYTE_ID);
}
else if (strncmp(magic, ARGON2_MAGIC_BYTE_D, strlen(ARGON2_MAGIC_BYTE_D)) == 0)
{
appendStringInfoString(result, ARGON2_MAGIC_BYTE_D);
}
else if (strncmp(magic, ARGON2_MAGIC_BYTE_I, strlen(ARGON2_MAGIC_BYTE_I)) == 0)
{
appendStringInfoString(result, ARGON2_MAGIC_BYTE_I);
}
else
{
ereport(ERROR,
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("unsupported magic string for argon2: \"%s\"",
magic));
}
/*
* We need the Argon2 version info. We generate always with the current
* version.
*/
appendStringInfo(result, "v=%u$", ARGON2_DEFAULT_VERSION);
/*
* Create options string
*/
buf = xgen_salt_argon_internal(options,
numoptions);
/* Append options string to the result */
if (buf == NULL)
{
elog(ERROR, "could not generate options string for salt");
}
appendBinaryStringInfo(result, buf->data, buf->len);
pfree(buf->data);
pfree(buf);
/*
* Now the generated salt string.
*/
appendStringInfo(result, "$%s$", salt_encoded);
/* and we're done */
return result;
}
static
text *argon2_internal_libargon2(const char *magic,
const char *pw,
const char *salt,
int threads,
int lanes,
int memcost,
int rounds,
int size,
argon2_output_format_t format,
unsigned int argon2_version)
{
unsigned char *hash = palloc0(size); /* result digest */
text *result = NULL; /* function result, text representation of digest */
argon2_context context;
unsigned char *salt_decoded;
int salt_decoded_len;
int rc; /* argon2 digest return code */
/*
* Decode salt bytes from base64 first.
*
* XXX: It should be safe to cast the string length to int, since we
* can't exceed ARGON2_SALT_MAX_LEN.
*/
salt_decoded = pwhash_from_base64((unsigned char *)salt,
(int)strlen(salt),
&salt_decoded_len);
/*
* Taken from
* https://github.com/P-H-C/phc-winner-argon2
*/
context.out = hash; /* output array, at least HASHLEN in size */
context.outlen = size; /* digest length */
context.pwd = (uint8_t *)pw; /* password array */
context.pwdlen = strlen(pw); /* password length */
context.salt = salt_decoded; /* salt array */
context.saltlen = salt_decoded_len; //strlen((const char *) salt_decoded); /* salt length */
context.secret = NULL;
context.secretlen = 0; /* optional secret data */
context.ad = NULL;
context.adlen = 0; /* optional associated data */
context.t_cost = rounds;
context.m_cost = memcost;
context.lanes = lanes;
context.threads = threads;
context.version = argon2_version; /* algorithm version */
context.allocate_cbk = NULL;
context.free_cbk = NULL; /* custom memory allocation / deallocation functions */
/* by default only internal memory is cleared (pwd is not wiped) */
context.flags = ARGON2_DEFAULT_FLAGS;
/* Create argon2 hash context */
if (strncmp(magic, "ARGON2ID", 8) == 0)
{
rc = argon2id_ctx(&context);
}
else if (strncmp(magic, "ARGON2I", 7) == 0)
{
rc = argon2i_ctx(&context);
}
else if (strncmp(magic, "ARGON2D", 7) == 0)
{
rc = argon2d_ctx(&context);
}
else
{
/* oops, shouldn't happen */
elog(ERROR, "unexpected magic string \"%s\"", magic);
}
if (rc != ARGON2_OK)
{
elog(ERROR, "digest failed: %s", argon2_error_message(rc));
}
switch(format) {
case ARGON2_OUTPUT_BASE64:
{
char *resb64;
size_t encoded_size;
resb64 = pwhash_to_base64(hash, size);
encoded_size = strlen(resb64);
result = (text *) palloc(encoded_size + VARHDRSZ);
SET_VARSIZE(result, encoded_size + VARHDRSZ);
memcpy(VARDATA(result), resb64, encoded_size);
break;
}
case ARGON2_OUTPUT_HEX:
{
text *outputtohex;
outputtohex = palloc(size + VARHDRSZ);
SET_VARSIZE(outputtohex, size + VARHDRSZ);
memcpy(VARDATA(outputtohex), hash, size);
result = DatumGetTextP(DirectFunctionCall2(binary_encode,
PointerGetDatum(outputtohex),
PointerGetDatum(
cstring_to_text(
"hex"))));
break;
}
}
if (unlikely(result == NULL))
{
elog(ERROR, "unrecognized output format");
}
return result;
}
/*
* Hashes the password with the provided options via OpenSSL EVP_KDF_*
* API.
*
* The caller is responsible to provide sane options.
*/
static
text *argon2_internal_ossl(const char *ossl_argon2_name,
const char *pw,
const char *salt,
int threads,
int lanes,
int memcost,
int rounds,
int size,
argon2_output_format_t format,
unsigned int argon2_version)
{
#ifdef _PWHASH_ARGON2_OSSL_SUPPORT
EVP_KDF *ossl_kdf = NULL;
EVP_KDF_CTX *ossl_kdf_ctx = NULL;
text *result = NULL;
unsigned char *output;
OSSL_PARAM parameters[8];
OSSL_PARAM *ptr;
unsigned char *salt_decoded;
int salt_decoded_len;
/* Some initialization */
output = palloc0(size + 1);
/*
* Decode base64 salt string first.
*
* XXX: It should be safe to cast the salt length to int, since
* we can't exceed ARGON2_SALT_MAX_LEN.
*/
salt_decoded = pwhash_from_base64((unsigned char *)salt, strlen(salt), &salt_decoded_len);
/* The following code is taken from OpenSSL KDF documentation for
* ARGON2 and adjusted for our needs, see
*
* man 7 EVP_KDF-ARGON2
*
* for details.
*/
/* According to above manpage, this check is mandatory */
if (OSSL_set_max_threads(NULL, threads) != 1)
{
elog(ERROR, "cannot set OpenSSL threads to %d", threads);
}
ptr = parameters;
*ptr++ = OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_THREADS,
(unsigned int *)&threads);
*ptr++ = OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ITER,
(unsigned int *)&rounds);
*ptr++ = OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ARGON2_LANES,
(unsigned int *)&lanes);
*ptr++ = OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ARGON2_MEMCOST,
(unsigned int *)&memcost);
*ptr++ = OSSL_PARAM_construct_uint(OSSL_KDF_PARAM_ARGON2_VERSION,
(unsigned int *)&argon2_version);
*ptr++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT,
(void *)salt_decoded,
strlen((char *)salt_decoded));
*ptr++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD,
(void *)pw,
strlen ((const char * )pw));
*ptr++ = OSSL_PARAM_construct_end();
if ((ossl_kdf = EVP_KDF_fetch(NULL, ossl_argon2_name, NULL)) == NULL)
{
elog(WARNING, "cannot fetch %s KDF", ossl_argon2_name);
goto err;
}
if ((ossl_kdf_ctx = EVP_KDF_CTX_new(ossl_kdf)) == NULL)
{
elog(WARNING, "cannot create KDF context");
goto err;
}
if (EVP_KDF_derive(ossl_kdf_ctx, output, size, parameters) != 1)
{
elog(WARNING, "cannot derive key");
goto err;
}
/* Seems everything went smooth, prepare the result */
switch(format)
{
case ARGON2_OUTPUT_BASE64:
{
char *resb64;
size_t encoded_size;
resb64 = pwhash_to_base64(output, size);
encoded_size = strlen(resb64);
result = (text *) palloc(encoded_size + VARHDRSZ);
SET_VARSIZE(result, encoded_size + VARHDRSZ);
memcpy(VARDATA(result), resb64, encoded_size);
break;
}
case ARGON2_OUTPUT_HEX:
{
text *outputtohex;
outputtohex = palloc(size + VARHDRSZ);
SET_VARSIZE(outputtohex, size + VARHDRSZ);
memcpy(VARDATA(outputtohex), output, size);
result = DatumGetTextP(DirectFunctionCall2(binary_encode,
PointerGetDatum(outputtohex),
PointerGetDatum(
cstring_to_text(
"hex"))));
break;
}
}
if (unlikely(result == NULL))
{
elog(ERROR, "unrecognized output format");
}
return result;
err:
EVP_KDF_free(ossl_kdf);
EVP_KDF_CTX_free(ossl_kdf_ctx);
OSSL_set_max_threads(NULL, 0);
elog(ERROR, "creating argon2 password hash failed");
#else
ereport(ERROR,
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("openssl backend not available in this version of pg_pwhash"),
errhint("This requires OpenSSL version >= 3.2.0"));
#endif
}
Datum
pwhash_argon2(PG_FUNCTION_ARGS)
{
Datum *options = NULL;
size_t numoptions = 0;
text *hash = NULL;
char *options_buf = NULL;
char *ossl_argon2_name = "ARGON2ID";
unsigned int argon2_version = ARGON2_DEFAULT_VERSION;
struct parse_salt_info pinfo;
char salt_buf[ARGON2_SALT_MAX_LEN + 1];
StringInfo resbuf;
text *result;
text *password;
char *pw_cstr;
text *salt;
char *salt_cstr;
/* Argon2 parameters for hash generation */
int threads;
int lanes;
int memcost;
int rounds;
int size;
argon2_output_format_t output_format;
argon2_digest_backend_t backend;
bool explicit_backend_option;
password = PG_GETARG_TEXT_PP(0);
salt = PG_GETARG_TEXT_PP(1);
memset(&salt_buf, '\0', ARGON2_SALT_MAX_LEN + 1);
salt_cstr = text_to_cstring(salt);
pw_cstr = text_to_cstring(password);
/* Parse input salt string, prepare parser context. */
simple_salt_parser_init(&pinfo, argon2_options, NUM_ARGON2_OPTIONS,
ARGON2_DEFAULT_VERSION);
/*
* Minimum length of salt is
*
* length(magic) + length(algo_info_len)
*
* Note that simple_salt_parser() below performs its own checks, too.
*/
if (strlen(salt_cstr) < (pinfo.magic_len + pinfo.algo_info_len))
{
ereport(ERROR,
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("salt string does not provide enough settings"));
}
/*
* We need the preamble of the salt to figure out the requested
* Argon2 algorithm to use.
*/
if (strncmp(salt_cstr, ARGON2_MAGIC_BYTE_ID, strlen(ARGON2_MAGIC_BYTE_ID)) == 0)
{
pinfo.magic = ARGON2_MAGIC_BYTE_ID;
ossl_argon2_name = "ARGON2ID";
}
else if (strncmp(salt_cstr, ARGON2_MAGIC_BYTE_I, strlen(ARGON2_MAGIC_BYTE_I)) == 0)
{
pinfo.magic = ARGON2_MAGIC_BYTE_I;
ossl_argon2_name = "ARGON2I";
}
else if (strncmp(salt_cstr, ARGON2_MAGIC_BYTE_D, strlen(ARGON2_MAGIC_BYTE_D)) == 0)
{
pinfo.magic = ARGON2_MAGIC_BYTE_D;
ossl_argon2_name = "ARGON2D";
}
else
{
ereport(ERROR,
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("unsupported magic string in salt"));
}
/* Don't forget to adjust pinfo length of magic string */
pinfo.magic_len = strlen(pinfo.magic);
/* Parse the salt string with the now prepared parser context */
simple_salt_parser(&pinfo, salt_cstr);
/*
* Extract requested Argon2 version. If not found, silently assume
* current version.
*
* XXX: According to some sources, the version option is required since the
* Argon2 v1.3 specification. It is tempting to assume that getting
* a salt string without this might indicate to use some older specs,
* but we ignore that fact and work with the current one implemented
* here.
*/
if (strncmp((salt_cstr + pinfo.magic_len), "v=", 2) == 0)
{
/* extract the version number requested */
char *v_ptr = salt_cstr + pinfo.magic_len;
char *version_buf = (char *) palloc0(pinfo.algo_info_len + 1);
char *sep;
/* copy over the version string, but without the trailing $ . */
memcpy(version_buf, v_ptr, pinfo.algo_info_len - 1);
sep = strchr(version_buf, '=');
if (sep)
{
*sep++ = '\0';
argon2_version = (unsigned int)pg_strtoint32(sep);
}
/* Check version number, only 0x10 and 0x13 are currently supported */
if ( (argon2_version != 0x10) && (argon2_version != 0x13) )
{
ereport(ERROR,
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("unsupported argon2 version \"%u\"",
argon2_version),
errhint("Supported versions are 16 and 19(default)"));
}
pfree(version_buf);
}
/* Handle options, if extracted by salt parser */
if (pinfo.opt_len > 0)
{
options_buf = (char *) palloc(pinfo.opt_len + 1);
memset(options_buf, '\0', pinfo.opt_len + 1);
memcpy(options_buf, pinfo.opt_str, pinfo.opt_len);
elog(DEBUG2, "extracted options from salt \"%s\"", options_buf);