-
-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathmormot.db.raw.sqlite3.static.pas
1330 lines (1198 loc) · 55.6 KB
/
mormot.db.raw.sqlite3.static.pas
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
/// Database Framework Low-Level Statically Linked SQLite3 Engine
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.db.raw.sqlite3.static;
{
*****************************************************************************
Statically linked SQLite3 3.46.1 engine with optional AES encryption
- TSqlite3LibraryStatic Implementation
- Encryption-Related Functions
Just include this unit in your uses clause, and the mormot.db.raw.sqlite3
sqlite3 global variable will be filled with linked .o/.obj API entries -
ensure you downloaded latest https://synopse.info/files/mormot2static.7z
or https://synopse.info/files/mormot2static.tgz
If the platform is not supported yet, fallback loading a system library.
To patch and compile the official SQlite3 amalgamation file, follow the
instruction from the res/static/sqlite3 folder.
*****************************************************************************
}
interface
{$I ..\mormot.defines.inc}
{$ifdef NOSQLITE3STATIC} // conditional defined -> auto-load local .dll/.so
uses
sysutils,
mormot.core.base,
mormot.core.os,
mormot.db.raw.sqlite3;
implementation
procedure DoInitialization;
begin
FreeAndNil(sqlite3);
try
sqlite3 := TSqlite3LibraryDynamic.Create(SQLITE_LIBRARY_DEFAULT_NAME);
sqlite3.ForceToUseSharedMemoryManager; // faster process
except
on E: Exception do
DisplayFatalError(SQLITE_LIBRARY_DEFAULT_NAME + ' initialization failed',
RawUtf8(E.ClassName + ': ' + E.Message));
end;
end;
initialization
DoInitialization;
{$else NOSTATIC}
uses
sysutils,
classes,
mormot.core.base,
mormot.core.os,
mormot.core.data,
mormot.core.unicode,
mormot.core.text,
mormot.crypt.core, // for our AES encryption
mormot.crypt.secure,
mormot.lib.static,
mormot.db.raw.sqlite3;
{ ************ TSqlite3LibraryStatic Implementation }
type
/// access class to the static .obj/.o SQLite3 engine
// - the intialization section of this unit calls:
// ! sqlite3 := TSqlite3LibraryStatic.Create;
// therefore, adding mormot.db.raw.sqlite3.static to your uses clause is enough
// to use the statically linked SQLite3 engine with mormot.db.raw.sqlite3
TSqlite3LibraryStatic = class(TSqlite3Library)
public
/// fill the internal API reference s with the static .obj engine
constructor Create; override;
/// unload the static library
destructor Destroy; override;
/// calls ForceToUseSharedMemoryManager after SQlite3 is loaded
procedure BeforeInitialization; override;
/// validates EXPECTED_SQLITE3_VERSION after SQlite3 is initialized
procedure AfterInitialization; override;
end;
const
/// the exact version expected by the current state of this unit
// - an error message is generated via DisplayFatalError() if the statically
// linked sqlite3.o(bj) does not match this expected value
EXPECTED_SQLITE3_VERSION = '3.46.1';
/// the github release tag associated with this EXPECTED_SQLITE3_VERSION
// - to be used if you don't want the latest version of sqlite3, but the very
// same binaries expected by this unit, in one of its previous version
// - you could download the static for this exact mORMot source revision e.g. as
// https://github.com/synopse/mORMot2/releases/download/2.3.stable/mormot2static.7z
// https://github.com/synopse/mORMot2/releases/download/2.3.stable/mormot2static.tgz
EXPECTED_RELEASE_TAG = '2.3.stable';
/// where to download the latest available static binaries, including SQLite3
{$ifdef OSWINDOWS}
EXPECTED_STATIC_DOWNLOAD = 'https://synopse.info/files/mormot2static.7z';
{$else}
EXPECTED_STATIC_DOWNLOAD = 'https://synopse.info/files/mormot2static.tgz';
{$endif OSWINDOWS}
{ ************ Encryption-Related Functions }
/// use this procedure to change the password for an existing SQLite3 database file
// - convenient and faster alternative to the sqlite3.rekey() API call
// - conversion is done in-place at file level, with no SQL nor BTree pages
// involved, therefore it can process very big files with best possible speed
// - the OldPassWord must be correct, otherwise the resulting file will be corrupted
// - any password can be '' to mark no encryption as input or output
// - password will use AES-128 (see ForceSQLite3AesCtr) after PBKDF2 SHAKE_128
// with rounds=1000 or a JSON (extended) serialized TSynSignerParams object like
// ${algo:"saSha512",secret:"StrongPassword",salt:"FixedSalt",rounds:10000}
// - please note that this encryption is compatible only with SQlite3 files made
// with this mormot.db.raw.sqlite3.static unit (not external/official/wxsqlite3 dll)
// - implementation is NOT compatible with the official SQLite Encryption Extension
// (SEE) file format, not the wxsqlite3 extension, but is (much) faster thanks
// to our mormot.crypt.core AES-NI enabled unit
// - if the key is not correct, a ESqlite3Exception will be raised with
// 'database disk image is malformed' (SQLITE_CORRUPT) at database opening
// - see also IsSQLite3File/IsSQLite3FileEncrypted functions
// - warning: this encryption is NOT compatible with our previous (<1.18.4413)
// cyphered format, which was much less safe (simple XOR on fixed tables), and
// was not working on any database size, making unclean patches to the official
// sqlite3.c amalgamation file, so is deprecated and unsupported any longer -
// see OldSqlEncryptTablePassWordToPlain() to convert your existing databases
function ChangeSqlEncryptTablePassWord(const FileName: TFileName;
const OldPassWord, NewPassword: RawUtf8): boolean;
/// this function may be used to create a plain database file from an existing
// one encrypted with our old/deprecated/unsupported format (<1.18.4413)
// - then call ChangeSqlEncryptTablePassWord() to convert to the new safer format
procedure OldSqlEncryptTablePassWordToPlain(const FileName: TFileName;
const OldPassWord: RawUtf8);
/// could be used to detect a database in old/deprecated/unsupported format (<1.18.4413)
// - to call OldSqlEncryptTablePassWordToPlain + ChangeSqlEncryptTablePassWord
// and switch to the new format
function IsOldSqlEncryptTable(const FileName: TFileName): boolean;
var
/// global flag to use initial AES encryption scheme
// - IV derivation was hardened in revision 1.18.4607 - set TRUE to this
// global constant to use the former implementation (theoritically slightly
// less resistant to brute force attacks) and convert existing databases
ForceSQLite3LegacyAes: boolean;
/// global flag to use AES-CTR instead of AES-OFB encryption
// - on x86_64 our optimized asm is 2.5GB/s for CTR instead of 770MB/s for OFB
// - enabled in PUREMORMOT2 mode, since performance is better on x86_64 (or OpenSSL)
// - set ForceSQLite3AesCtr := true for compatibility reasons with mORMot 1
ForceSQLite3AesCtr: boolean {$ifdef PUREMORMOT2} = true {$endif};
implementation
{$ifdef ISDELPHI}
{$ifdef OSWINDOWS}
uses
Windows; // statically linked Delphi .obj requires the Windows API
{$endif OSWINDOWS}
{$endif ISDELPHI}
{ ************ TSqlite3LibraryStatic Implementation }
// ---------------- link raw .o .obj files
// see res/static/libsqlite3 for patched source and build instructions
{$ifdef FPC} // FPC expects .o linking
{$ifdef OSWINDOWS}
{$ifdef CPUINTEL}
{$ifdef CPU64}
{$L ..\..\static\x86_64-win64\sqlite3.o}
{$else}
{$L ..\..\static\i386-win32\sqlite3.o}
{$endif CPU64}
{$else}
'unsupported yet'
{$endif CPUINTEL}
{$endif OSWINDOWS}
{$ifdef OSDARWIN}
{$ifdef CPUAARCH64}
{$L ..\..\static\aarch64-darwin\sqlite3.o}
{$endif CPUAARCH64}
{$ifdef CPUX86}
{$linklib ..\..\static\i386-darwin\libsqlite3.a}
{$endif CPUX86}
{$ifdef CPUX64}
{$linklib ..\..\static\x86_64-darwin\libsqlite3.a}
{$endif CPUX64}
{$endif OSDARWIN}
{$ifdef OSANDROID}
{$ifdef CPUAARCH64}
{$L ..\..\static\aarch64-android\sqlite3.o}
{$endif CPUAARCH64}
{$ifdef CPUARM}
{$L ..\..\static\arm-android\sqlite3.o}
{$endif CPUARM}
{$ifdef CPUX86}
{$L ..\..\static\i386-android\sqlite3.o}
{$endif CPUX86}
{$ifdef CPUX64}
{$L ..\..\static\x86_64-android\sqlite3.o}
// x86_64-linux-android-ld.bfd: final link failed
// (Nonrepresentable section on output)
{$endif CPUX64}
{$endif OSANDROID}
{$ifdef OSFREEBSD}
{$ifdef CPUX86}
{$L ..\..\static\i386-freebsd\sqlite3.o}
{$endif CPUX86}
{$ifdef CPUX64}
{$L ..\..\static\x86_64-freebsd\sqlite3.o}
{$endif CPUX64}
{$endif OSFREEBSD}
{$ifdef OSOPENBSD}
{$ifdef CPUX86}
{$L ..\..\static\i386-openbsd\sqlite3.o}
{$endif CPUX86}
{$ifdef CPUX64}
{$L ..\..\static\x86_64-openbsd\sqlite3.o}
{$endif CPUX64}
{$endif OSOPENBSD}
{$ifdef OSLINUX}
{$ifdef CPUAARCH64}
{$L ..\..\static\aarch64-linux\sqlite3.o}
{$linklib ..\..\static\aarch64-linux\libgcc.a}
{$endif CPUAARCH64}
{$ifdef CPUARM}
{$L ..\..\static\arm-linux\sqlite3.o}
{$linklib ..\..\static\arm-linux\libgcc.a}
{$endif CPUARM}
{$ifdef CPUX86}
{$L ..\..\static\i386-linux\sqlite3.o}
{$endif CPUX86}
{$ifdef CPUX64}
{$L ..\..\static\x86_64-linux\sqlite3.o}
{$endif CPUX64}
{$endif OSLINUX}
{$else FPC} // Delphi static linking has diverse expectations
// Delphi has a diverse linking strategy, since $linklib doesn't exist :(
{$ifdef OSWINDOWS}
{$ifdef CPU64}
// compiled with C++ Builder 10.3 Community Edition bcc64
{$L ..\..\static\delphi\sqlite3.o}
{$else}
// compiled with the free Borland C++ Compiler 5.5
{$L ..\..\static\delphi\sqlite3.obj}
{$endif CPU64}
{$endif OSWINDOWS}
// those functions will be called only under Delphi + Win32/Win64
// - FPC will use explicit public name exports from mormot.lib.static
// but Delphi requires the exports to be defined in this very same unit
function malloc(size: PtrInt): pointer; cdecl;
begin
GetMem(result, size);
end;
procedure free(P: pointer); cdecl;
begin
FreeMem(P);
end;
function realloc(P: pointer; Size: PtrInt): pointer; cdecl;
begin
ReallocMem(P, Size);
result := P;
end;
function rename(oldname, newname: PUtf8Char): integer; cdecl;
begin
result := libc_rename(oldname, newname);
end;
{$ifdef OSWINDOWS}
{$ifdef CPU32} // Delphi Win32 will link static C++ Builder sqlite3.obj
// we then implement all needed C++ Builder runtime functions in pure pascal:
function _ftol: Int64;
// C++ Builder float to integer (Int64) conversion
asm
jmp System.@Trunc // FST(0) -> EDX:EAX, as expected by BCC32 compiler
end;
function _ftoul: Int64;
// C++ Builder float to integer (Int64) conversion
asm
jmp System.@Trunc // FST(0) -> EDX:EAX, as expected by BCC32 compiler
end;
var
__turbofloat: word; { not used, but must be present for linking }
// C++ Builder and Delphi share the same low level Int64 _ll*() functions:
procedure _lldiv;
asm
jmp System.@_lldiv
end;
procedure _lludiv;
asm
jmp System.@_lludiv
end;
procedure _llmod;
asm
jmp System.@_llmod
end;
procedure _llmul;
asm
jmp System.@_llmul
end;
procedure _llumod;
asm
jmp System.@_llumod
end;
procedure _llshl;
asm
jmp System.@_llshl
end;
procedure _llshr;
asm
// need this code for Borland/CodeGear default System.pas
shrd eax, edx, cl
sar edx, cl
cmp cl, 32
jl @done
cmp cl, 64
jge @sign
mov eax, edx
sar edx, 31
ret
@sign: sar edx, 31
mov eax, edx
@done:
end;
procedure _llushr;
asm
jmp System.@_llushr
end;
function log(const val: double): double; cdecl;
asm
fld qword ptr val
fldln2
fxch
fyl2x
end;
function fabs(x: double): double; cdecl; // needed since 3.44.2
begin
result := abs(x);
end;
function strchr(p: PAnsiChar; chr: AnsiChar): PAnsiChar; cdecl;
begin // needed since 3.46.1
result := nil;
if p <> nil then
while p^ <> chr do
if p^ = #0 then
exit // not found
else
inc(p);
result := p;
end;
{$endif CPU32}
function memchr(p: pointer; chr: byte; n: PtrInt): PAnsiChar; cdecl;
var
i: PtrInt;
begin // needed since 3.46.1
result := p;
if p = nil then
exit;
i := ByteScanIndex(p, n, chr); // use SSE2
if i >= 0 then
inc(result, i)
else
result := nil; // not found
end;
{$endif OSWINDOWS}
function memset(P: pointer; B: integer; count: integer): pointer; cdecl;
// a fast full pascal version of the standard C library function
begin
FillCharFast(P^, count, B);
result := P;
end;
function memmove(dest, source: pointer; count: integer): pointer; cdecl;
// a fast full pascal version of the standard C library function
begin
MoveFast(source^, dest^, count); // move() is overlapping-friendly
result := dest;
end;
function memcpy(dest, source: pointer; count: integer): pointer; cdecl;
// a fast full pascal version of the standard C library function
begin
MoveFast(source^, dest^, count);
result := dest;
end;
function strlen(p: PUtf8Char): integer; cdecl;
// a fast full pascal version of the standard C library function
begin
// called only by some obscure FTS3 functions (normal code use dedicated functions)
result := mormot.core.base.StrLen(p);
end;
function strcmp(p1, p2: PUtf8Char): integer; cdecl;
// a fast full pascal version of the standard C library function
begin
// called only by some obscure FTS3 functions (normal code use dedicated functions)
result := mormot.core.base.StrComp(p1, p2);
end;
function strcspn(str, reject: PUtf8Char): integer; cdecl;
begin
// called e.g. during LIKE process
result := mormot.core.unicode.strcspn(str, reject);
end;
function strspn(str, reject: PUtf8Char): integer; cdecl;
begin
// appeared with SQlite 3.44.2
result := mormot.core.unicode.strspn(str, reject);
end;
function strrchr(s: PUtf8Char; c: AnsiChar): PUtf8Char; cdecl;
begin
// simple full pascal version of the standard C library function
result := nil;
if s <> nil then
while s^ <> #0 do
begin
if s^ = c then
result := s;
inc(s);
end;
end;
function memcmp(p1, p2: pByte; Size: PtrInt): integer; cdecl;
begin
result := libc_memcmp(p1, p2, Size);
end;
function strncmp(p1, p2: PByte; Size: PtrInt): integer; cdecl;
begin
result := libc_strncmp(p1, p2, Size);
end;
procedure qsort(baseP: PByte; NElem, Width: PtrInt; comparF: qsort_compare_func); cdecl;
begin
libc_qsort(baseP, NElem, Width, comparF);
end;
{$ifdef OSWINDOWS}
var
{ as standard C library documentation states:
Statically allocated buffer, shared by the functions gmtime() and localtime().
Each call of these functions overwrites the content of this structure.
-> this buffer is shared, but SQlite3 will protect it with a mutex :) }
atm: time_t;
function localtime(t: PCardinal): pointer; cdecl;
begin
localtime32_s(t^, atm);
result := @atm;
end;
function _beginthreadex(security: pointer; stksize: dword;
start, arg: pointer; flags: dword; var threadid: dword): THandle; cdecl;
external _CLIB;
procedure _endthreadex(exitcode: dword); cdecl;
external _CLIB;
{$ifdef CPU64}
// Delphi Win64 will link its own static sqlite3.o (diverse from FPC's)
function _log(x: double): double; export; // to link LLVM bcc64 compiler
begin
result := ln(x);
end;
function log(x: double): double; export; // to link old non-LLVM bcc64 compiler
begin
result := ln(x);
end;
procedure __chkstk;
begin
end;
procedure __faststorefence;
asm
.noframe
mfence;
end;
var
_finf: double = 1.0 / 0.0; // compiles to some double infinity constant
_fltused: Int64 = 0; // to link old non-LLVM bcc64 compiler
{$endif CPU64}
{$endif OSWINDOWS}
{$endif FPC}
{ ************ Encryption-Related Functions }
{
Our SQlite3 static files includes a SQLite3MultipleCiphers VFS for encryption.
See https://github.com/synopse/mORMot2/tree/master/res/static/libsqlite3
The SQLite3 source is not patched to implement the VFS itself (it is not
mandatory), but is patched to add some key-related high-level features - see
https://utelle.github.io/SQLite3MultipleCiphers/docs/architecture/arch_patch
VFS codecext.c and sqlite3mc.c redirect to those external functions below.
Encryption is done in CodecAESProcess() using AES-CTR or AES-OFB. It uses mORMot
optimized asm, which is faster than OpenSSL on x86_64 (our main server target).
Each page is encrypted with an IV derived from its page number using AES. By
default with mORMot a page size is 4KB. No overhead is used for IV or HMAC
storage. The first bytes of the files are not encrypted, because it is mandatory
for proper work with most SQLite3 tools. This is what all other libraries do,
including the official (but not free) SSE extension from SQLite3 authors - see
https://utelle.github.io/SQLite3MultipleCiphers/docs/ciphers/cipher_legacy_mode
Key derivation from password is done in CodecGenerateKey() using PBKDF2 safe
iterative key derivation over the SHA-3 (SHAKE_128) algorithm, reduced into
128-bit. There is no benefit of using AES-256 in practice, because a 128-bit
password using a 80-character alphabet (i.e. very strong computerized password)
already require at least 21 chars, which is very unlikely in practice.
It uses 1000 rounds by default, and you can customize the password derivation
using overridden parameters in JSON format instead of the plain password,
following TSynSignerParams fields.
}
const
CODEC_PBKDF2_SALT = 'J6CuDftfPr22FnYn';
// statically allocated TAes in lib/static/libsqlite3/sqlite3mc.c
KEYLENGTH = 300;
procedure CodecGenerateKey(var aes: TAes;
userPassword: pointer; passwordLength: integer);
var
s: TSynSigner;
k: THash512Rec;
begin
if SizeOf(TAes) > KEYLENGTH then
ESqlite3Exception.RaiseUtf8('CodecGenerateKey: TAes=%', [SizeOf(TAes)]);
// userPassword may be TSynSignerParams JSON content
s.Pbkdf2(userPassword, passwordLength, k, CODEC_PBKDF2_SALT);
s.AssignTo(k, aes, {encrypt=}true);
end;
function CodecGetReadKey(codec: pointer): PAes; cdecl; external;
function CodecGetWriteKey(codec: pointer): PAes; cdecl; external;
procedure CodecGenerateReadKey(codec: pointer;
userPassword: PUtf8Char; passwordLength: integer); cdecl;
{$ifdef FPC}public name _PREFIX + 'CodecGenerateReadKey';{$endif} export;
begin
CodecGenerateKey(CodecGetReadKey(codec)^, userPassword, passwordLength);
end;
procedure CodecGenerateWriteKey(codec: pointer;
userPassword: PUtf8Char; passwordLength: integer); cdecl;
{$ifdef FPC}public name _PREFIX + 'CodecGenerateWriteKey';{$endif} export;
begin
CodecGenerateKey(CodecGetWriteKey(codec)^, userPassword, passwordLength);
end;
procedure CodecAesProcess(page: cardinal; data: PUtf8Char; len: integer;
aes: PAes; encrypt: boolean);
var
plain: Int64; // bytes 16..23 should always be unencrypted
iv: THash128Rec; // is genuine and AES-protected (since not random)
begin
if (len and AesBlockMod <> 0) or
(len <= 0) or
(integer(page) <= 0) then
ESqlite3Exception.RaiseUtf8(
'Unexpected CodecAesProcess(page=%,len=%)', [page, len]);
iv.c0 := page xor 668265263; // prime-based initialization
iv.c1 := page * 2654435761;
iv.c2 := page * 2246822519;
iv.c3 := page * 3266489917;
if not ForceSQLite3LegacyAes then
aes^.Encrypt(iv.b); // avoid potential brute force attack
len := len shr AesBlockShift;
if page = 1 then
// ensure header bytes 16..23 are stored unencrypted in the first page
if (PInt64(data)^ = SQLITE_FILE_HEADER128.lo) and
(data[21] = #64) and
(data[22] = #32) and
(data[23] = #32) then
if encrypt then
begin
plain := PInt64(data + 16)^;
if ForceSQLite3AesCtr then
aes^.DoBlocksCtr(@iv.b, data + 16, data + 16, len - 1)
else
aes^.DoBlocksOfb(@iv.b, data + 16, data + 16, len - 1);
// 8..15 are encrypted bytes 16..23
PInt64(data + 8)^ := PInt64(data + 16)^;
PInt64(data + 16)^ := plain;
end
else
begin
PInt64(data + 16)^ := PInt64(data + 8)^;
if ForceSQLite3AesCtr then
aes^.DoBlocksCtr(@iv.b, data + 16, data + 16, len - 1)
else
aes^.DoBlocksOfb(@iv.b, data + 16, data + 16, len - 1);
if (data[21] = #64) and
(data[22] = #32) and
(data[23] = #32) then
PHash128(data)^ := SQLITE_FILE_HEADER128.b
else
FillZero(PHash128(data)^); // report incorrect password
end
else
FillZero(PHash128(data)^)
else
// whole page encryption if not the first one
if ForceSQLite3AesCtr then
aes^.DoBlocksCtr(@iv.b, data, data, len) // fastest on x86_64 SSE4.1
else
aes^.DoBlocksOfb(@iv.b, data, data, len);
end;
function CodecEncrypt(codec: pointer; page: integer; data: PUtf8Char;
len, useWriteKey: integer): integer; cdecl;
{$ifdef FPC}public name _PREFIX + 'CodecEncrypt';{$endif} export;
begin
if useWriteKey = 1 then
CodecAesProcess(page, data, len, CodecGetWriteKey(codec), true)
else
CodecAesProcess(page, data, len, CodecGetReadKey(codec), true);
result := SQLITE_OK;
end;
function CodecDecrypt(codec: pointer; page: integer;
data: PUtf8Char; len: integer): integer; cdecl;
{$ifdef FPC}public name _PREFIX + 'CodecDecrypt';{$endif} export;
begin
CodecAesProcess(page, data, len, CodecGetReadKey(codec), false);
result := SQLITE_OK;
end;
function CodecTerm(codec: pointer): integer; cdecl;
{$ifdef FPC}public name _PREFIX + 'CodecTerm';{$endif} export;
begin
CodecGetReadKey(codec)^.Done;
CodecGetWriteKey(codec)^.Done;
result := SQLITE_OK;
end;
function ChangeSqlEncryptTablePassWord(const FileName: TFileName;
const OldPassWord, NewPassword: RawUtf8): boolean;
var
F: THandle;
bufsize, page, pagesize, pagecount, n, p, max: cardinal;
head: THash256Rec;
buf: PUtf8Char;
temp: RawByteString;
size, posi: Int64;
old, new: TAes;
begin
result := false;
if OldPassWord = NewPassword then
exit;
F := FileOpen(FileName, fmOpenReadWrite);
if ValidHandle(F) then
try
if OldPassWord <> '' then
CodecGenerateKey(old, pointer(OldPassWord), length(OldPassWord));
if NewPassword <> '' then
CodecGenerateKey(new, pointer(NewPassword), length(NewPassword));
size := FileSize(F);
if FileRead(F, head, SizeOf(head)) <> SizeOf(head) then
exit;
if size > 4 shl 20 then // use up to 4MB of R/decrypt/encrypt/W buffer
bufsize := 4 shl 20
else
bufsize := size;
pagesize := cardinal(head.b[16]) shl 8 + head.b[17];
pagecount := size div pagesize;
if (pagesize < 1024) or
(pagesize and AesBlockMod <> 0) or
(pagesize > bufsize) or
(QWord(pagecount) * pagesize <> size) or
(head.d0 <> SQLITE_FILE_HEADER128.Lo) or
((head.d1 = SQLITE_FILE_HEADER128.Hi) <> (OldPassWord = '')) then
exit;
FileSeek64(F, 0);
FastNewRawByteString(temp, bufsize);
posi := 0;
page := 1;
while page <= pagecount do
begin
n := bufsize div pagesize;
max := pagecount - page + 1;
if n > max then
n := max;
buf := pointer(temp);
if not FileReadAll(F, buf, pagesize * n) then
exit; // stop on any read error
for p := 0 to n - 1 do
begin
if OldPassWord <> '' then
begin
CodecAesProcess(page + p, buf, pagesize, @old, false);
if (p = 0) and
(page = 1) and
(PInteger(buf)^ = 0) then
exit; // OldPassword is obviously incorrect
end;
if NewPassword <> '' then
CodecAesProcess(page + p, buf, pagesize, @new, true);
inc(buf, pagesize);
end;
FileSeek64(F, posi); // update in-place where we just read
if not FileWriteAll(F, pointer(temp), pagesize * n) then
exit;
inc(posi, pagesize * n);
inc(page, n);
end;
result := true;
finally
FileClose(F);
if OldPassWord <> '' then
old.Done;
if NewPassword <> '' then
new.Done;
end;
end;
function IsOldSqlEncryptTable(const FileName: TFileName): boolean;
var
hdr: array[0..2047] of byte;
begin
result := BufferFromFile(FileName, @hdr, SizeOf(hdr)) and
IsEqual(PHash128(@hdr)^, SQLITE_FILE_HEADER128.b) and
// see https://www.sqlite.org/fileformat.html (4 in bigendian = 1024 bytes)
(PWord(@hdr[16])^ = 4) and
// B-tree leaf Type to be either 5 (interior) 10 (index) or 13 (table)
not (hdr[1024] in [5, 10, 13]);
end;
const
OLDENCRYPTTABLESIZE = $4000;
procedure CreateSqlEncryptTableBytes(const PassWord: RawUtf8; Table: PByteArray);
// very fast table (private key) computation from a given password
// - execution speed and code size was the goal here: can be easily broken
// - the new encryption scheme is both safer and more performant
var
i, j, k, L: integer;
begin
L := length(PassWord) - 1;
j := 0;
k := integer(L * ord(PassWord[1])) + 134775813; // initial value, prime based
for i := 0 to OLDENCRYPTTABLESIZE - 1 do
begin
Table^[i] := (ord(PassWord[j + 1])) xor byte(k);
k := integer(k * 3 + i); // fast prime-based pseudo random generator
if j = L then
j := 0
else
inc(j);
end;
end;
procedure XorOffset(P: PByte; Index, Count: cardinal; SqlEncryptTable: PByteArray);
var
len: cardinal;
begin
// deprecated fast and simple Cypher using Index (= offset in file)
if Count > 0 then
repeat
Index := Index and (OLDENCRYPTTABLESIZE - 1);
len := OLDENCRYPTTABLESIZE - Index;
if len > Count then
len := Count;
XorMemory(pointer(P), @SqlEncryptTable^[Index], len);
inc(P, len);
inc(Index, len);
dec(Count, len);
until Count = 0;
end;
procedure OldSqlEncryptTablePassWordToPlain(const FileName: TFileName;
const OldPassWord: RawUtf8);
var
F: THandle;
R: integer;
buf: array[word] of byte; // temp buffer for read/write (64KB seems enough)
size, posi: Int64;
oldtable: array[0..OLDENCRYPTTABLESIZE - 1] of byte; // 2x16KB tables
begin
F := FileOpen(FileName, fmOpenReadWrite);
if not ValidHandle(F) then
exit;
size := FileSize(F);
if size <= 1024 then
begin
FileClose(F); // file is to small to be modified
exit;
end;
if OldPassWord <> '' then
CreateSqlEncryptTableBytes(OldPassWord, @oldtable);
posi := 1024; // don't change first page, which is uncrypted
FileSeek64(F, 1024);
while posi < size do
begin
R := FileRead(F, buf, SizeOf(buf)); // read buffer
if R < 0 then
break; // stop on any read error
if OldPassWord <> '' then
XorOffset(@buf, posi, R, @oldtable); // uncrypt with oldtable key
FileSeek64(F, posi); // update in-place where we just read
if not FileWriteAll(F, @buf, R) then // update buffer
break;
inc(posi, cardinal(R));
end;
FileClose(F);
end;
function sqlite3_initialize: integer; cdecl; external;
function sqlite3_shutdown: integer; cdecl; external;
function sqlite3_open(filename: PUtf8Char; var DB: TSqlite3DB): integer; cdecl; external;
function sqlite3_open_v2(filename: PUtf8Char; var DB: TSqlite3DB; flags: integer;
vfs: PUtf8Char): integer; cdecl; external;
function sqlite3_close(DB: TSqlite3DB): integer; cdecl; external;
function sqlite3_key(DB: TSqlite3DB; key: pointer; keyLen: integer): integer; cdecl; external;
function sqlite3_rekey(DB: TSqlite3DB; key: pointer; keyLen: integer): integer; cdecl; external;
function sqlite3_create_function(DB: TSqlite3DB; FunctionName: PUtf8Char;
nArg, eTextRep: integer; pApp: pointer; xFunc, xStep: TSqlFunctionFunc;
xFinal: TSqlFunctionFinal): integer; cdecl; external;
function sqlite3_create_function_v2(DB: TSqlite3DB; FunctionName: PUtf8Char;
nArg, eTextRep: integer; pApp: pointer; xFunc, xStep: TSqlFunctionFunc;
xFinal: TSqlFunctionFinal; xDestroy: TSqlDestroyPtr): integer; cdecl; external;
function sqlite3_create_window_function(DB: TSqlite3DB; FunctionName: PUtf8Char;
nArg, eTextRep: integer; pApp: pointer; xStep: TSqlFunctionFunc;
xFinal, xValue: TSqlFunctionFinal; xInverse: TSqlFunctionFunc;
xDestroy: TSqlDestroyPtr): integer; cdecl; external;
procedure sqlite3_set_auxdata(Context: TSqlite3FunctionContext; N: integer;
Value: pointer; DestroyPtr: TSqlDestroyPtr); cdecl; external;
function sqlite3_get_auxdata(Context: TSqlite3FunctionContext; N: integer): pointer; cdecl; external;
function sqlite3_create_collation(DB: TSqlite3DB; CollationName: PUtf8Char;
StringEncoding: integer; CollateParam: pointer; cmp: TSqlCollateFunc): integer; cdecl; external;
function sqlite3_libversion: PUtf8Char; cdecl; external;
function sqlite3_libversion_number: integer; cdecl; external;
function sqlite3_sourceid: PUtf8Char; cdecl; external;
function sqlite3_threadsafe: integer; cdecl; external;
function sqlite3_errcode(DB: TSqlite3DB): integer; cdecl; external;
function sqlite3_extended_errcode(DB: TSqlite3DB): integer; cdecl; external;
function sqlite3_errmsg(DB: TSqlite3DB): PUtf8Char; cdecl; external;
function sqlite3_errstr(Code: integer): PUtf8Char; cdecl; external;
function sqlite3_system_errno(DB: TSqlite3DB): integer; cdecl; external;
function sqlite3_extended_result_codes(DB: TSqlite3DB; OnOff: integer): integer; cdecl; external;
function sqlite3_complete(SQL: PUtf8Char): integer; cdecl; external;
function sqlite3_keyword_count: integer; cdecl; external;
function sqlite3_keyword_name(Nth: integer; var Identifier: PUtf8Char;
L: PInteger): integer; cdecl; external;
function sqlite3_keyword_check(Identifier: PUtf8Char; L: integer): integer; cdecl; external;
function sqlite3_txn_state(DB: TSqlite3DB; SchemaName: PUtf8Char): integer; cdecl; external;
function sqlite3_create_collation_v2(DB: TSqlite3DB; CollationName: PUtf8Char;
StringEncoding: integer; CollateParam: pointer; cmp: TSqlCollateFunc;
DestroyPtr: TSqlDestroyPtr): integer; cdecl; external;
function sqlite3_collation_needed(DB: TSqlite3DB; CollateParam: pointer;
Callback: TSqlCollationNeededCallback): integer; cdecl; external;
function sqlite3_last_insert_rowid(DB: TSqlite3DB): Int64; cdecl; external;
procedure sqlite3_set_last_insert_rowid(DB: TSqlite3DB; R: Int64); cdecl; external;
function sqlite3_busy_timeout(DB: TSqlite3DB; Milliseconds: integer): integer; cdecl; external;
function sqlite3_busy_handler(DB: TSqlite3DB;
CallbackPtr: TSqlBusyHandler; user: pointer): integer; cdecl; external;
function sqlite3_prepare_v2(DB: TSqlite3DB; SQL: PUtf8Char; SQL_bytes: integer;
var S: TSqlite3Statement; var SQLtail: PUtf8Char): integer; cdecl; external;
function sqlite3_prepare_v3(DB: TSqlite3DB; SQL: PUtf8Char; SQL_bytes: integer;
prepFlags: cardinal; var S: TSqlite3Statement; var SQLtail: PUtf8Char): integer; cdecl; external;
function sqlite3_finalize(S: TSqlite3Statement): integer; cdecl; external;
function sqlite3_exec(DB: TSqlite3DB; SQL: PUtf8Char; Callback: TSqlExecCallback;
UserData: pointer; var ErrorMsg: PUtf8Char): integer; cdecl; external;
function sqlite3_next_stmt(DB: TSqlite3DB; S: TSqlite3Statement): TSqlite3Statement; cdecl; external;
function sqlite3_reset(S: TSqlite3Statement): integer; cdecl; external;
procedure sqlite3_interrupt(DB: TSqlite3DB); cdecl; external;
procedure sqlite3_progress_handler(DB: TSqlite3DB; N: integer; Callback: TSqlProgressCallback;
UserData: pointer); cdecl; external;
function sqlite3_stmt_busy(S: TSqlite3Statement): integer; cdecl; external;
function sqlite3_stmt_isexplain(S: TSqlite3Statement): integer; cdecl; external;
function sqlite3_stmt_readonly(S: TSqlite3Statement): integer; cdecl; external;
function sqlite3_stmt_scanstatus(S: TSqlite3Statement; idx: integer; iScanStatusOp: integer;
pOut: pointer): integer; cdecl; external;
procedure sqlite3_stmt_scanstatus_reset(S: TSqlite3Statement); cdecl; external;
function sqlite3_stmt_status(S: TSqlite3Statement; Operation: integer;
resetFlag: integer): integer; cdecl; external;
function sqlite3_db_handle(S: TSqlite3Statement): TSqlite3DB; cdecl; external;
function sqlite3_sql(S: TSqlite3Statement): PUtf8Char; cdecl; external;
function sqlite3_expanded_sql(S: TSqlite3Statement): PUtf8Char; cdecl; external;
function sqlite3_normalized_sql(S: TSqlite3Statement): PUtf8Char; cdecl; external;
function sqlite3_step(S: TSqlite3Statement): integer; cdecl; external;
function sqlite3_table_column_metadata(DB: TSqlite3DB; zDbName, zTableName, zColumnName: PUtf8Char;
var pzDataType, pzCollSeq: PUtf8Char;
out pNotNull, pPrimaryKey, pAutoinc: integer): integer; cdecl; external;
function sqlite3_column_count(S: TSqlite3Statement): integer; cdecl; external;
function sqlite3_column_type(S: TSqlite3Statement; Col: integer): integer; cdecl; external;
function sqlite3_column_decltype(S: TSqlite3Statement; Col: integer): PUtf8Char; cdecl; external;
function sqlite3_column_name(S: TSqlite3Statement; Col: integer): PUtf8Char; cdecl; external;
function sqlite3_column_database_name(S: TSqlite3Statement; Col: integer): PUtf8Char; cdecl; external;
function sqlite3_column_table_name(S: TSqlite3Statement; Col: integer): PUtf8Char; cdecl; external;
function sqlite3_column_origin_name(S: TSqlite3Statement; Col: integer): PUtf8Char; cdecl; external;
function sqlite3_column_bytes(S: TSqlite3Statement; Col: integer): integer; cdecl; external;
function sqlite3_column_value(S: TSqlite3Statement; Col: integer): TSqlite3Value; cdecl; external;
function sqlite3_column_double(S: TSqlite3Statement; Col: integer): double; cdecl; external;
function sqlite3_column_int(S: TSqlite3Statement; Col: integer): integer; cdecl; external;
function sqlite3_column_int64(S: TSqlite3Statement; Col: integer): int64; cdecl; external;
function sqlite3_column_text(S: TSqlite3Statement; Col: integer): PUtf8Char; cdecl; external;
function sqlite3_column_text16(S: TSqlite3Statement; Col: integer): PWideChar; cdecl; external;
function sqlite3_column_blob(S: TSqlite3Statement; Col: integer): PUtf8Char; cdecl; external;
function sqlite3_value_type(Value: TSqlite3Value): integer; cdecl; external;
function sqlite3_value_subtype(Value: TSqlite3Value): cardinal; cdecl; external;
function sqlite3_value_numeric_type(Value: TSqlite3Value): integer; cdecl; external;
function sqlite3_value_nochange(Value: TSqlite3Value): integer; cdecl; external;
function sqlite3_value_frombind(Value: TSqlite3Value): integer; cdecl; external;
function sqlite3_value_bytes(Value: TSqlite3Value): integer; cdecl; external;
function sqlite3_value_dup(Value: TSqlite3Value): TSqlite3Value; cdecl; external;
procedure sqlite3_value_free(Value: TSqlite3Value); cdecl; external;
function sqlite3_value_pointer(Value: TSqlite3Value; Typ: PUtf8Char): pointer; cdecl; external;
function sqlite3_value_double(Value: TSqlite3Value): double; cdecl; external;
function sqlite3_value_int64(Value: TSqlite3Value): Int64; cdecl; external;
function sqlite3_value_text(Value: TSqlite3Value): PUtf8Char; cdecl; external;
function sqlite3_value_blob(Value: TSqlite3Value): pointer; cdecl; external;
procedure sqlite3_result_pointer(Context: TSqlite3FunctionContext; Value: pointer;
Typ: PUtf8Char; DestroyPtr: TSqlDestroyPtr); cdecl; external;
procedure sqlite3_result_null(Context: TSqlite3FunctionContext); cdecl; external;
procedure sqlite3_result_int64(Context: TSqlite3FunctionContext; Value: Int64); cdecl; external;
procedure sqlite3_result_double(Context: TSqlite3FunctionContext; Value: double); cdecl; external;
procedure sqlite3_result_blob(Context: TSqlite3FunctionContext; Value: pointer;
Value_bytes: integer = 0; DestroyPtr: TSqlDestroyPtr = SQLITE_TRANSIENT); cdecl; external;
procedure sqlite3_result_zeroblob(Context: TSqlite3FunctionContext; Value_bytes: integer); cdecl; external;
procedure sqlite3_result_text(Context: TSqlite3FunctionContext; Value: PUtf8Char;
Value_bytes: integer = -1; DestroyPtr: TSqlDestroyPtr = SQLITE_TRANSIENT); cdecl; external;
procedure sqlite3_result_value(Context: TSqlite3FunctionContext; Value: TSqlite3Value); cdecl; external;
procedure sqlite3_result_subtype(Context: TSqlite3FunctionContext; Value: cardinal); cdecl; external;
procedure sqlite3_result_error(Context: TSqlite3FunctionContext; Msg: PUtf8Char;
MsgLen: integer = -1); cdecl; external;
function sqlite3_user_data(Context: TSqlite3FunctionContext): pointer; cdecl; external;
function sqlite3_context_db_handle(Context: TSqlite3FunctionContext): TSqlite3DB; cdecl; external;
function sqlite3_aggregate_context(Context: TSqlite3FunctionContext; nBytes: integer): pointer; cdecl; external;
function sqlite3_bind_text(S: TSqlite3Statement; Param: integer;Text: PUtf8Char;
Text_bytes: integer = -1; DestroyPtr: TSqlDestroyPtr = SQLITE_TRANSIENT): integer;cdecl; external;
function sqlite3_bind_blob(S: TSqlite3Statement; Param: integer; Buf: pointer; Buf_bytes: integer;
DestroyPtr: TSqlDestroyPtr = SQLITE_TRANSIENT): integer; cdecl; external;
function sqlite3_bind_zeroblob(S: TSqlite3Statement; Param: integer; Size: integer): integer; cdecl; external;
function sqlite3_bind_double(S: TSqlite3Statement; Param: integer; Value: double): integer; cdecl; external;