-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathitem_strfunc.cc
5632 lines (4821 loc) · 177 KB
/
item_strfunc.cc
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
/*
Copyright (c) 2000, 2024, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
@file sql/item_strfunc.cc
@brief
This file defines all string Items (e.g. CONCAT).
*/
#include "sql/item_strfunc.h"
#include <fcntl.h>
#include <algorithm>
#include <atomic>
#include <climits>
#include <cmath> // std::isfinite
#include <cstddef> // size_t
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include <vector> // vector
#include <openssl/sha.h> // SHA256_DIGEST_LENGTH
#include <zconf.h>
#include <zlib.h>
#include "base64.h" // base64_encode_max_arg_length
#include "decimal.h"
#include "dig_vec.h"
#include "field_types.h" // MYSQL_TYPE_BIT
#include "lex_string.h" // LEX_CSTRING
#include "m_string.h"
#include "my_aes.h" // MY_AES_IV_SIZE
#include "my_alloc.h" // MEM_ROOT
#include "my_byteorder.h"
#include "my_checksum.h" // my_checksum
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_dir.h" // For my_stat
#include "my_io.h"
#include "my_md5.h" // MD5_HASH_SIZE
#include "my_md5_size.h"
#include "my_rnd.h" // my_rand_buffer
#include "my_sqlcommand.h"
#include "my_stacktrace.h"
#include "my_sys.h"
#include "my_systime.h"
#include "myisampack.h"
#include "mysql/components/services/bits/my_io_bits.h" // File
#include "mysql/components/services/log_builtins.h" // LogErr
#include "mysql/my_loglevel.h" // WARNING_LEVEL
#include "mysql/mysql_lex_string.h" // MYSQL_LEX_CSTRING
#include "mysql/psi/mysql_file.h"
#include "mysql/psi/mysql_mutex.h"
#include "mysql/strings/dtoa.h"
#include "mysql/strings/int2str.h"
#include "mysql/strings/m_ctype.h" // is_supported_parser_charset
#include "mysqld_error.h"
#include "mysys_err.h"
#include "nulls.h"
#include "sha1.h" // SHA1_HASH_SIZE
#include "sha2.h"
#include "sql-common/my_decimal.h"
#include "sql/auth/auth_acls.h"
#include "sql/auth/auth_common.h" // check_password_policy
#include "sql/auth/sql_security_ctx.h"
#include "sql/current_thd.h" // current_thd
#include "sql/dd/dd_event.h" // dd::get_old_interval_type
#include "sql/dd/dd_table.h" // is_encrypted
#include "sql/dd/info_schema/metadata.h" // dd::info_schema::get_I_S_view...
#include "sql/dd/info_schema/table_stats.h"
#include "sql/dd/info_schema/tablespace_stats.h"
#include "sql/dd/properties.h" // dd::Properties
#include "sql/dd/string_type.h"
#include "sql/dd/types/event.h" // dd::Event::enum_interval_field
#include "sql/dd_sql_view.h" // push_view_warning_or_error
#include "sql/derror.h" // ER_THD
#include "sql/error_handler.h" // Internal_error_handler
#include "sql/events.h" // Events::reconstruct_interval_expression
#include "sql/filesort.h"
#include "sql/handler.h"
#include "sql/mysqld.h" // binary_keyword etc
#include "sql/parse_tree_node_base.h" // Parse_context
#include "sql/resourcegroups/resource_group_mgr.h" // num_vcpus
#include "sql/rpl_gtid.h"
#include "sql/sort_param.h"
#include "sql/sql_class.h" // THD
#include "sql/sql_digest.h" // get_max_digest_length
#include "sql/sql_digest_stream.h" // sql_digest_state
#include "sql/sql_error.h"
#include "sql/sql_lex.h"
#include "sql/sql_locale.h" // my_locale_by_name
#include "sql/sql_show.h" // grant_types
#include "sql/strfunc.h"
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/val_int_compare.h" // Integer_value
#include "sql_string.h" // needs_conversion
#include "string_with_len.h"
#include "strxmov.h"
#include "template_utils.h"
#include "typelib.h"
#include "unhex.h"
#include "vector-common/vector_conversion.h" // from_string_to_vector, from_vector_to_string
extern uint *my_aes_opmode_key_sizes;
using std::max;
using std::min;
using std::string;
using std::vector;
/*
For the Items which have only val_str_ascii() method
and don't have their own "native" val_str(),
we provide a "wrapper" method to convert from ASCII
to Item character set when it's necessary.
Conversion happens only in case of "tricky" Item character set (e.g. UCS2).
Normally conversion does not happen, and val_str_ascii() is immediately
returned instead.
*/
String *Item_str_func::val_str_from_val_str_ascii(String *str, String *str2) {
assert(fixed);
if (my_charset_is_ascii_based(collation.collation)) {
String *res = val_str_ascii(str);
if (res) res->set_charset(collation.collation);
return res;
}
assert(str != str2);
uint errors;
String *res = val_str_ascii(str);
if (!res) return nullptr;
if ((null_value = str2->copy(res->ptr(), res->length(), &my_charset_latin1,
collation.collation, &errors)))
return nullptr;
return str2;
}
bool Item_str_func::fix_fields(THD *thd, Item **ref) {
bool res = Item_func::fix_fields(thd, ref);
/*
In Item_str_func::check_well_formed_result() we may set null_value
flag on the same condition as in test() below.
*/
set_nullable(is_nullable() || thd->is_strict_mode());
return res;
}
my_decimal *Item_str_func::val_decimal(my_decimal *decimal_value) {
assert(fixed);
char buff[64];
String *res, tmp(buff, sizeof(buff), &my_charset_bin);
res = val_str(&tmp);
if (!res) return nullptr;
(void)str2my_decimal(E_DEC_FATAL_ERROR, res->ptr(), res->length(),
res->charset(), decimal_value);
return decimal_value;
}
String *Item_func_md5::val_str_ascii(String *str) {
assert(fixed);
String *sptr = args[0]->val_str(str);
str->set_charset(&my_charset_bin);
if (sptr) {
uchar digest[MD5_HASH_SIZE] = {0};
null_value = false;
const int retval =
compute_md5_hash((char *)digest, sptr->ptr(), sptr->length());
if (retval == 1) {
push_warning_printf(current_thd, Sql_condition::SL_WARNING,
ER_DA_SSL_FIPS_MODE_ERROR,
ER_THD(current_thd, ER_DA_SSL_FIPS_MODE_ERROR),
"FIPS mode ON/STRICT: MD5 digest is not supported.");
}
if (str->alloc(32)) // Ensure that memory is free
{
null_value = true;
return nullptr;
}
array_to_hex(str->ptr(), digest, MD5_HASH_SIZE);
str->length((uint)32);
return str;
}
null_value = true;
return nullptr;
}
/*
The MD5()/SHA() functions treat their parameter as being a case sensitive.
Thus we set binary collation on it so different instances of MD5() will be
compared properly.
*/
static CHARSET_INFO *get_checksum_charset(const char *csname) {
CHARSET_INFO *cs = get_charset_by_csname(csname, MY_CS_BINSORT, MYF(0));
if (!cs) {
// Charset has no binary collation: use my_charset_bin.
cs = &my_charset_bin;
}
return cs;
}
bool Item_func_md5::resolve_type(THD *thd) {
if (param_type_is_default(thd, 0, -1)) return true;
CHARSET_INFO *cs = get_checksum_charset(args[0]->collation.collation->csname);
args[0]->collation.set(cs, DERIVATION_COERCIBLE);
set_data_type_string(32, default_charset());
return false;
}
String *Item_func_sha::val_str_ascii(String *str) {
assert(fixed);
String *sptr = args[0]->val_str(str);
str->set_charset(&my_charset_bin);
if (sptr) /* If we got value different from NULL */
{
/* Temporary buffer to store 160bit digest */
uint8 digest[SHA1_HASH_SIZE];
compute_sha1_hash(digest, sptr->ptr(), sptr->length());
/* Ensure that memory is free */
if (!(str->alloc(SHA1_HASH_SIZE * 2))) {
array_to_hex(str->ptr(), digest, SHA1_HASH_SIZE);
str->length((uint)SHA1_HASH_SIZE * 2);
null_value = false;
return str;
}
}
null_value = true;
return nullptr;
}
bool Item_func_sha::resolve_type(THD *thd) {
if (param_type_is_default(thd, 0, 1)) return true;
CHARSET_INFO *cs = get_checksum_charset(args[0]->collation.collation->csname);
args[0]->collation.set(cs, DERIVATION_COERCIBLE);
// size of hex representation of hash
set_data_type_string(SHA1_HASH_SIZE * 2, default_charset());
return false;
}
/*
SHA2(str, hash_length)
The second argument indicates the desired bit length of the
result, which must have a value of 224, 256, 384, 512, or 0
(which is equivalent to 256).
*/
String *Item_func_sha2::val_str_ascii(String *str) {
assert(fixed);
unsigned char digest_buf[SHA512_DIGEST_LENGTH];
uint digest_length = 0;
String *input_string = args[0]->val_str(str);
str->set_charset(&my_charset_bin);
if (input_string == nullptr) {
null_value = true;
return (String *)nullptr;
}
null_value = args[0]->null_value;
if (null_value) return nullptr;
const unsigned char *input_ptr =
pointer_cast<const unsigned char *>(input_string->ptr());
size_t input_len = input_string->length();
longlong hash_length = args[1]->val_int();
null_value = args[1]->null_value;
// Give error message in switch below.
if (null_value) hash_length = -1;
switch (hash_length) {
#ifndef OPENSSL_NO_SHA512
case 512:
digest_length = SHA512_DIGEST_LENGTH;
SHA_EVP512(input_ptr, input_len, digest_buf);
break;
case 384:
digest_length = SHA384_DIGEST_LENGTH;
SHA_EVP384(input_ptr, input_len, digest_buf);
break;
#endif
#ifndef OPENSSL_NO_SHA256
case 224:
digest_length = SHA224_DIGEST_LENGTH;
SHA_EVP224(input_ptr, input_len, digest_buf);
break;
case 256:
case 0: // SHA-256 is the default
digest_length = SHA256_DIGEST_LENGTH;
SHA_EVP256(input_ptr, input_len, digest_buf);
break;
#endif
default:
// For const values we have already warned in resolve_type().
if (!args[1]->const_item())
push_warning_printf(
current_thd, Sql_condition::SL_WARNING,
ER_WRONG_PARAMETERS_TO_NATIVE_FCT,
ER_THD(current_thd, ER_WRONG_PARAMETERS_TO_NATIVE_FCT), "sha2");
null_value = true;
return nullptr;
}
/*
Since we're subverting the usual String methods, we must make sure that
the destination has space for the bytes we're about to write.
*/
str->mem_realloc(digest_length * 2 + 1); /* Each byte as two nybbles */
/* Convert the large number to a string-hex representation. */
array_to_hex(str->ptr(), digest_buf, digest_length);
/* We poked raw bytes in. We must inform the the String of its length. */
str->length(digest_length * 2); /* Each byte as two nybbles */
null_value = false;
return str;
}
bool Item_func_sha2::resolve_type(THD *thd) {
if (param_type_is_default(thd, 0, 1)) return true;
if (param_type_is_default(thd, 1, 2, MYSQL_TYPE_LONGLONG)) return true;
set_nullable(true);
longlong sha_variant;
if (args[1]->const_item() && args[1]->may_eval_const_item(thd)) {
sha_variant = args[1]->val_int();
// Give error message in switch below.
if (args[1]->null_value) sha_variant = -1;
} else {
sha_variant = 512;
}
switch (sha_variant) {
#ifndef OPENSSL_NO_SHA512
case 512:
set_data_type_string(SHA512_DIGEST_LENGTH * 2, default_charset());
break;
case 384:
set_data_type_string(SHA384_DIGEST_LENGTH * 2, default_charset());
break;
#endif
#ifndef OPENSSL_NO_SHA256
case 256:
case 0: // SHA-256 is the default
set_data_type_string(SHA256_DIGEST_LENGTH * 2, default_charset());
break;
#endif
case 224:
set_data_type_string(SHA224_DIGEST_LENGTH * 2, default_charset());
break;
default:
set_data_type_string(SHA256_DIGEST_LENGTH * 2, default_charset());
push_warning_printf(
thd, Sql_condition::SL_WARNING, ER_WRONG_PARAMETERS_TO_NATIVE_FCT,
ER_THD(thd, ER_WRONG_PARAMETERS_TO_NATIVE_FCT), "sha2");
}
CHARSET_INFO *cs = get_checksum_charset(args[0]->collation.collation->csname);
args[0]->collation.set(cs, DERIVATION_COERCIBLE);
return false;
}
/* Implementation of AES encryption routines */
/** Helper class to retrieve KDF options for aes_encrypt/aes_decrypt. */
const int max_kdf_option_size{256};
const int max_kdf_iterations_size{65535};
const int min_kdf_iterations_size{1000};
static bool parse_kdf_option(String *kdf_option_value, string &kdf_option,
bool *error_generated,
const size_t max_size_allowed) {
/*
For large KDF option value, KDF option value will be set as nullptr by
function callers.
It gives warning: Warning | 1301 | Result of repeat() was
larger than max_allowed_packet (16777216) - truncated Here arg_count >
KDF option value as nullptr will be treated as invalid KDF option value.
*/
if (kdf_option_value == nullptr) {
my_error(ER_AES_INVALID_KDF_OPTION_SIZE, MYF(0), max_size_allowed);
*error_generated = true;
return false;
}
if (kdf_option_value->length() > (max_size_allowed - 1)) {
my_error(ER_AES_INVALID_KDF_OPTION_SIZE, MYF(0), max_size_allowed);
*error_generated = true;
return false;
}
kdf_option = to_string(*kdf_option_value);
return true;
}
/**
Validate the options and retrieve the KDF options value.
@param arg_count number of parameters passed to the function
@param args array of arguments passed to the function
@param func_name the name of the function (for errors)
@param [out] error_generated set to true if error was generated.
@param [out] result retrieved KDF option values
*/
static void retrieve_kdf_options(uint arg_count, Item **args,
const char *func_name, bool *error_generated,
vector<string> &result) {
*error_generated = false;
if (arg_count < 4) {
return;
}
char tmp_option_buff[max_kdf_option_size]{'\0'};
String tmp_option_value(tmp_option_buff, sizeof(tmp_option_buff),
system_charset_info);
String *kdf_option_value = args[3]->val_str(&tmp_option_value);
// KDF funtion name
string kdf_option;
if (!parse_kdf_option(kdf_option_value, kdf_option, error_generated,
max_kdf_option_size)) {
return;
}
// KDF function name should be valid
#if OPENSSL_VERSION_NUMBER < 0x10100000L
if (kdf_option == "pbkdf2_hmac") {
#else
if (kdf_option == "hkdf" || kdf_option == "pbkdf2_hmac") {
#endif
result.push_back(kdf_option);
} else {
my_error(ER_AES_INVALID_KDF_NAME, MYF(0), func_name);
*error_generated = true;
return;
}
kdf_option_value = nullptr;
if (arg_count > 4) {
kdf_option_value = args[4]->val_str(&tmp_option_value);
} else {
return;
}
// For hkdf and pbkdf2_hmac option 1 is salt
if (!parse_kdf_option(kdf_option_value, kdf_option, error_generated,
max_kdf_option_size)) {
return;
}
result.push_back(kdf_option);
kdf_option_value = nullptr;
if (arg_count > 5) {
kdf_option_value = args[5]->val_str(&tmp_option_value);
} else {
return;
}
// For hkdf option 2 is info
// For pbkdf2_hmac option 2 is iterations
size_t max_size_allowed = max_kdf_option_size;
if (result[0] == "pbkdf2_hmac") {
// 4 bytes for integer (65535).
max_size_allowed = 6;
}
if (!parse_kdf_option(kdf_option_value, kdf_option, error_generated,
max_size_allowed)) {
return;
}
result.push_back(kdf_option);
if ((result[0] == "pbkdf2_hmac") && (result.size() > 2)) {
const int iter = atoi(result[2].c_str());
if (iter < min_kdf_iterations_size || iter > max_kdf_iterations_size) {
*error_generated = true;
my_error(ER_AES_INVALID_KDF_ITERATIONS, MYF(0), func_name);
}
}
}
/** helper class to process an IV argument to aes_encrypt/aes_decrypt */
class iv_argument {
char iv_buff[MY_AES_IV_SIZE + 1]; // +1 to cater for the terminating NULL
String tmp_iv_value;
public:
iv_argument() : tmp_iv_value(iv_buff, sizeof(iv_buff), system_charset_info) {}
/**
Validate the arguments and retrieve the IV value.
Processes a 3d optional IV argument to an Item_func function.
Contains all the necessary stack buffers etc.
@param aes_opmode the encryption mode
@param arg_count number of parameters passed to the function
@param args array of arguments passed to the function
@param func_name the name of the function (for errors)
@param thd the current thread (for errors)
@param [out] error_generated set to true if error was generated.
@return a pointer to the retrieved validated IV or NULL
*/
const unsigned char *retrieve_iv_ptr(enum my_aes_opmode aes_opmode,
uint arg_count, Item **args,
const char *func_name, THD *thd,
bool *error_generated) {
const unsigned char *iv_str = nullptr;
*error_generated = false;
if (my_aes_needs_iv(aes_opmode)) {
/* we only enforce the need for IV */
if (arg_count > 2) {
String *iv = args[2]->val_str(&tmp_iv_value);
if (!iv || iv->length() < MY_AES_IV_SIZE) {
my_error(ER_AES_INVALID_IV, MYF(0), func_name,
(long long)MY_AES_IV_SIZE);
*error_generated = true;
return nullptr;
}
iv_str = (unsigned char *)iv->ptr();
} else {
my_error(ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT, MYF(0), func_name);
*error_generated = true;
return nullptr;
}
} else {
if (arg_count == 3) {
push_warning_printf(thd, Sql_condition::SL_WARNING, WARN_OPTION_IGNORED,
ER_THD(thd, WARN_OPTION_IGNORED), "IV");
}
}
return iv_str;
}
};
void Item_func_aes_encrypt::create_op_context() {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ctx = &stack_ctx;
#else
ctx = EVP_CIPHER_CTX_new();
#endif
}
void Item_func_aes_encrypt::destroy_op_context() {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
EVP_CIPHER_CTX_free(ctx);
#endif
}
bool Item_func_aes_encrypt::do_itemize(Parse_context *pc, Item **res) {
if (skip_itemize(res)) return false;
if (super::do_itemize(pc, res)) return true;
/* Unsafe for SBR since result depends on a session variable */
pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
/* Not safe to cache either */
pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
return false;
}
String *Item_func_aes_encrypt::val_str(String *str) {
assert(fixed);
char key_buff[80]{'\0'};
String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
THD *thd = current_thd;
iv_argument iv_arg;
DBUG_TRACE;
String *sptr = args[0]->val_str(str); // String to encrypt
if (sptr == nullptr) return error_str();
String *key = args[1]->val_str(&tmp_key_value); // key
if (key == nullptr) return error_str();
const auto aes_opmode =
static_cast<my_aes_opmode>(thd->variables.my_aes_mode);
assert(aes_opmode <= MY_AES_END);
const unsigned char *iv_str = iv_arg.retrieve_iv_ptr(
aes_opmode, arg_count, args, func_name(), thd, &null_value);
if (null_value) return error_str();
vector<string> kdf_options;
retrieve_kdf_options(arg_count, args, func_name(), &null_value, kdf_options);
if (null_value) return error_str();
// Calculate result length
const int aes_length = my_aes_get_size(sptr->length(), aes_opmode);
tmp_value.set_charset(&my_charset_bin);
const uint rkey_size = my_aes_opmode_key_sizes[aes_opmode] / 8;
const uint key_size = key->length();
if ((key_size > rkey_size) && kdf_options.empty()) {
push_warning_printf(thd, Sql_condition::SL_WARNING, WARN_AES_KEY_SIZE,
ER_THD(thd, WARN_AES_KEY_SIZE), rkey_size);
}
if (tmp_value.alloc(aes_length)) return error_str();
// Finally encrypt directly to allocated buffer.
const int length = my_aes_encrypt(
ctx, pointer_cast<unsigned char *>(sptr->ptr()), sptr->length(),
pointer_cast<unsigned char *>(tmp_value.ptr()),
pointer_cast<unsigned char *>(key->ptr()), key->length(), aes_opmode,
iv_str, true, kdf_options.empty() ? nullptr : &kdf_options);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
EVP_CIPHER_CTX_cleanup(ctx);
#else /* OPENSSL_VERSION_NUMBER < 0x10100000L */
EVP_CIPHER_CTX_reset(ctx);
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
if (length == aes_length) {
// We got the expected result length
tmp_value.length(static_cast<size_t>(aes_length));
return &tmp_value;
}
return error_str();
}
bool Item_func_aes_encrypt::resolve_type(THD *thd) {
if (Item_str_func::resolve_type(thd)) return true;
const ulong aes_opmode = thd->variables.my_aes_mode;
assert(aes_opmode <= MY_AES_END);
set_data_type_string(static_cast<ulonglong>(
my_aes_get_size(args[0]->max_length, (enum my_aes_opmode)aes_opmode)));
return false;
}
void Item_func_aes_decrypt::create_op_context() {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ctx = &stack_ctx;
#else
ctx = EVP_CIPHER_CTX_new();
#endif
}
void Item_func_aes_decrypt::destroy_op_context() {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
EVP_CIPHER_CTX_free(ctx);
#endif
}
bool Item_func_aes_decrypt::do_itemize(Parse_context *pc, Item **res) {
if (skip_itemize(res)) return false;
if (super::do_itemize(pc, res)) return true;
/* Unsafe for SBR since result depends on a session variable */
pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
/* Not safe to cache either */
pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
return false;
}
String *Item_func_aes_decrypt::val_str(String *str) {
assert(fixed);
char key_buff[80];
String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
THD *thd = current_thd;
iv_argument iv_arg;
DBUG_TRACE;
String *sptr = args[0]->val_str(str); // String to decrypt
if (sptr == nullptr) return error_str();
String *key = args[1]->val_str(&tmp_key_value); // Key
if (key == nullptr) return error_str();
const my_aes_opmode aes_opmode =
static_cast<my_aes_opmode>(thd->variables.my_aes_mode);
assert(aes_opmode <= MY_AES_END);
const unsigned char *iv_str = iv_arg.retrieve_iv_ptr(
aes_opmode, arg_count, args, func_name(), thd, &null_value);
if (null_value) return error_str();
str_value.set_charset(&my_charset_bin);
if (str_value.alloc(sptr->length())) return error_str();
// Finally decrypt directly to allocated buffer.
vector<string> kdf_options;
retrieve_kdf_options(arg_count, args, func_name(), &null_value, kdf_options);
if (null_value) {
return error_str();
}
const int length = my_aes_decrypt(
ctx, pointer_cast<unsigned char *>(sptr->ptr()), sptr->length(),
pointer_cast<unsigned char *>(str_value.ptr()),
pointer_cast<unsigned char *>(key->ptr()), key->length(), aes_opmode,
iv_str, true, (kdf_options.size() > 0) ? &kdf_options : nullptr);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
EVP_CIPHER_CTX_cleanup(ctx);
#else /* OPENSSL_VERSION_NUMBER < 0x10100000L */
EVP_CIPHER_CTX_reset(ctx);
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
if (length >= 0) // if we got correct data data
{
str_value.length((uint)length);
return &str_value;
}
return error_str();
}
bool Item_func_aes_decrypt::resolve_type(THD *thd) {
if (Item_str_func::resolve_type(thd)) return true;
if (reject_vector_args()) return true;
set_data_type_string(args[0]->max_char_length());
set_nullable(true);
return false;
}
bool Item_func_random_bytes::do_itemize(Parse_context *pc, Item **res) {
if (skip_itemize(res)) return false;
if (super::do_itemize(pc, res)) return true;
/* it is unsafe for SBR since it uses crypto random from the ssl library */
pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
/* Not safe to cache either */
pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_RAND);
return false;
}
/*
Artificially limited to 1k to avoid excessive memory usage.
The SSL lib supports up to INT_MAX.
*/
const ulonglong Item_func_random_bytes::MAX_RANDOM_BYTES_BUFFER = 1024ULL;
bool Item_func_random_bytes::resolve_type(THD *thd) {
if (param_type_is_default(thd, 0, 1, MYSQL_TYPE_LONGLONG)) return true;
if (reject_vector_args()) return true;
set_data_type_string(MAX_RANDOM_BYTES_BUFFER, &my_charset_bin);
return false;
}
String *Item_func_random_bytes::val_str(String *) {
assert(fixed);
const ulonglong n_bytes = args[0]->val_uint();
null_value = args[0]->null_value;
if (null_value) return nullptr;
if (current_thd->is_error()) return error_str();
str_value.set_charset(&my_charset_bin);
if (n_bytes == 0 || n_bytes > MAX_RANDOM_BYTES_BUFFER) {
my_error(ER_DATA_OUT_OF_RANGE, MYF(0), "length", func_name());
return error_str();
}
if (str_value.alloc(n_bytes)) {
return error_str();
}
str_value.set_charset(&my_charset_bin);
if (my_rand_buffer((unsigned char *)str_value.ptr(), n_bytes)) {
my_error(ER_ERROR_WHEN_EXECUTING_COMMAND, MYF(0), func_name(),
"SSL library can't generate random bytes");
return error_str();
}
str_value.length(n_bytes);
return &str_value;
}
bool Item_func_to_base64::resolve_type(THD *thd) {
if (Item_str_func::resolve_type(thd)) return true;
collation.set(default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII);
if (args[0]->max_length > (uint)base64_encode_max_arg_length()) {
set_nullable(true);
set_data_type_string((ulonglong)base64_encode_max_arg_length());
} else {
const uint64 length =
base64_needed_encoded_length((uint64)args[0]->max_length);
assert(length > 0);
set_data_type_string((ulonglong)length - 1);
set_nullable(args[0]->is_nullable() ||
max_length > thd->variables.max_allowed_packet);
}
return false;
}
String *Item_func_to_base64::val_str_ascii(String *str) {
String *res = args[0]->val_str(str);
if (res == nullptr) return error_str();
if (res->length() > base64_encode_max_arg_length()) return null_return_str();
const uint64 length = base64_needed_encoded_length(res->length());
if (length > current_thd->variables.max_allowed_packet)
return push_packet_overflow_warning(current_thd, func_name());
if (tmp_value.alloc(length)) return error_str();
base64_encode(res->ptr(), res->length(), tmp_value.ptr());
assert(length > 0);
tmp_value.length(length - 1); // Without trailing '\0'
null_value = false;
return &tmp_value;
}
bool Item_func_from_base64::resolve_type(THD *thd) {
if (Item_str_func::resolve_type(thd)) return true;
if (reject_vector_args()) return true;
if (args[0]->max_length > (uint)base64_decode_max_arg_length()) {
set_data_type_string(ulonglong(base64_decode_max_arg_length()));
} else {
const uint64 length =
base64_needed_decoded_length((uint64)args[0]->max_length);
set_data_type_string(ulonglong(length));
}
set_nullable(true); // Can be NULL, e.g. in case of badly formed input string
return false;
}
String *Item_func_from_base64::val_str(String *str) {
String *res = args[0]->val_str_ascii(str);
if (res == nullptr) return error_str();
if (res->length() > base64_decode_max_arg_length()) return null_return_str();
const uint64 length = base64_needed_decoded_length(res->length());
if (length > current_thd->variables.max_allowed_packet)
return push_packet_overflow_warning(current_thd, func_name());
if (tmp_value.alloc(length)) return error_str();
const char *end_ptr;
const int64 decoded_length =
base64_decode(res->ptr(), res->length(), tmp_value.ptr(), &end_ptr, 0);
if (decoded_length < 0 || end_ptr < res->ptr() + res->length()) {
return null_return_str();
}
tmp_value.length(decoded_length);
null_value = false;
return &tmp_value;
}
namespace {
/**
Because it's not possible to disentangle the state of the parser from the
THD, we have to destructively modify the current THD object in order to
parse. This class backs up and restores members that are modified in
Item_func_statement_digest::val_str_ascii. It also sports its own
Query_arena and LEX objects, which are used during parsing.
*/
class Thd_parse_modifier {
public:
Thd_parse_modifier(THD *thd, uchar *token_buffer)
: m_thd(thd),
m_arena(&m_mem_root, Query_arena::STMT_REGULAR_EXECUTION),
m_backed_up_lex(thd->lex),
m_saved_parser_state(thd->m_parser_state),
m_saved_digest(thd->m_digest),
m_cs(thd->variables.character_set_client) {
thd->m_digest = &m_digest_state;
m_digest_state.reset(token_buffer, get_max_digest_length());
m_arena.set_query_arena(*thd);
thd->lex = &m_lex;
lex_start(thd);
}
~Thd_parse_modifier() {
lex_end(&m_lex);
m_thd->lex = m_backed_up_lex;
m_thd->set_query_arena(m_arena);
m_thd->m_parser_state = m_saved_parser_state;
m_thd->m_digest = m_saved_digest;
m_thd->variables.character_set_client = m_cs;
m_thd->update_charset();
}
private:
THD *m_thd;
MEM_ROOT m_mem_root;
Query_arena m_arena;
LEX *m_backed_up_lex;
LEX m_lex;
sql_digest_state m_digest_state;
Parser_state *m_saved_parser_state;
sql_digest_state *m_saved_digest;
const CHARSET_INFO *m_cs;
};
/**
Error handler that wraps parse error messages, removes details and silences
warnings.
We don't want statement_digest() to raise warnings about deprecated syntax
or semantic problems. This is likely not interesting to the
caller. Therefore this handler issues a blanket silencing of all warnings.
The reason we want to anonymize parse errors is to avoid leaking information
in error messages that may be unintentionally visible to users of an
application. For instance an application may in error insert an expression
instead of a string:
SELECT statement_digest( (SELECT * FROM( SELECT user() ) t) );
The parser would normally raise an error saying:
You have an error in your SQL syntax; /.../ near 'root\@localhost'
thus leaking data from the `user` table. Therefore, the errors are in this
not disclosed.
*/
class Parse_error_anonymizer : public Internal_error_handler {
public:
Parse_error_anonymizer(THD *thd, Item *arg) : m_thd(thd), m_arg(arg) {
thd->push_internal_handler(this);
}
bool handle_condition(THD *, uint, const char *,
Sql_condition::enum_severity_level *level,
const char *message) override {
// Silence warnings.
if (*level == Sql_condition::SL_WARNING) return true;
// We pretend we're not here if already inside a call to handle_condition().
if (is_handling) return false;
is_handling = true;
if (m_arg->basic_const_item())
// Ok, it's a literal, we can print the whole error message.
my_error(ER_PARSE_ERROR_IN_DIGEST_FN, MYF(0), message);
else
// The argument is an expression, potentially from malicious use, let's
// not disclose anything.
my_error(ER_UNDISCLOSED_PARSE_ERROR_IN_DIGEST_FN, MYF(0));
is_handling = false;
return true;
}
~Parse_error_anonymizer() override { m_thd->pop_internal_handler(); }
private:
THD *m_thd;
Item *m_arg;
/// This avoids infinite recursion through my_error().
bool is_handling = false;
};
/**
Parses a string and fills the token buffer.
The parser function THD::sql_parser() is called directly instead of
parse_sql(), as the latter assumes that it is called with the intent to record
the statement in performance_schema and later execute it, neither of which is
called for here. In fact we hardly need the parser to calculate a digest,
since it is calculated from the token stream. There are only some corner cases
where `NULL` is sometimes a literal and sometimes an operator, as in
`IS NULL`, `IS NOT NULL`.
@param thd Session object used by the parser.
@param statement_expr The expression that evaluates to something that
can be parsed. Needed for error messages in case we don't want to disclose
what it evaluates to.