forked from mattn/go-sqlite3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlcipher_test.go
More file actions
282 lines (249 loc) · 9.04 KB
/
Copy pathsqlcipher_test.go
File metadata and controls
282 lines (249 loc) · 9.04 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
// Copyright (C) 2026 OMNILIUM ADVANCED CYBERNETICS SRL. All rights reserved.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
//go:build cgo
// +build cgo
package sqlite3
import (
"database/sql"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
const testKey = "correct horse battery staple"
// openKeyed opens a SQLCipher database at path using key via the _key DSN
// parameter.
func openKeyed(t *testing.T, path, key string) *sql.DB {
t.Helper()
dsn := fmt.Sprintf("file:%s?_key=%s", path, key)
db, err := sql.Open("sqlite3", dsn)
if err != nil {
t.Fatalf("open %q: %v", dsn, err)
}
return db
}
// mustClose closes db and fails the test if Close errors (e.g. a final flush
// failed), which matters before a reopen that asserts persistence.
func mustClose(t *testing.T, db *sql.DB) {
t.Helper()
if err := db.Close(); err != nil {
t.Fatalf("close: %v", err)
}
}
// TestEncryptedRoundTrip writes with the key, closes, and reopens with the same
// key. It locks down the open-order footgun: the key must be applied before the
// connection's first page read, otherwise reopening an existing encrypted file
// fails.
func TestEncryptedRoundTrip(t *testing.T) {
path := filepath.Join(t.TempDir(), "rt.db")
db := openKeyed(t, path, testKey)
if _, err := db.Exec(`CREATE TABLE t(x TEXT); INSERT INTO t VALUES('hello');`); err != nil {
t.Fatalf("write: %v", err)
}
if err := db.Close(); err != nil {
t.Fatalf("close: %v", err)
}
db = openKeyed(t, path, testKey)
defer db.Close()
var got string
if err := db.QueryRow(`SELECT x FROM t`).Scan(&got); err != nil {
t.Fatalf("reopen read: %v", err)
}
if got != "hello" {
t.Fatalf("got %q, want hello", got)
}
}
// TestEncryptedHeaderIsNotPlaintext verifies the file on disk does not begin
// with the plaintext SQLite header, i.e. encryption actually happened.
func TestEncryptedHeaderIsNotPlaintext(t *testing.T) {
path := filepath.Join(t.TempDir(), "hdr.db")
db := openKeyed(t, path, testKey)
if _, err := db.Exec(`CREATE TABLE t(x)`); err != nil {
t.Fatalf("write: %v", err)
}
mustClose(t, db)
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
head := make([]byte, 16)
if _, err := io.ReadFull(f, head); err != nil {
t.Fatal(err)
}
if string(head[:15]) == "SQLite format 3" {
t.Fatalf("file begins with plaintext SQLite header; not encrypted")
}
}
// TestWrongKeyFails verifies that reopening with the wrong key fails on first
// access.
func TestWrongKeyFails(t *testing.T) {
path := filepath.Join(t.TempDir(), "wrong.db")
db := openKeyed(t, path, testKey)
if _, err := db.Exec(`CREATE TABLE t(x)`); err != nil {
t.Fatalf("write: %v", err)
}
mustClose(t, db)
db = openKeyed(t, path, "not the key")
defer db.Close()
if _, err := db.Exec(`SELECT count(*) FROM sqlite_master`); err == nil {
t.Fatalf("expected failure with wrong key, got nil")
}
}
// TestUnkeyedOpenOfEncryptedFails verifies that opening an encrypted file with
// no key at all fails.
func TestUnkeyedOpenOfEncryptedFails(t *testing.T) {
path := filepath.Join(t.TempDir(), "nokey.db")
db := openKeyed(t, path, testKey)
if _, err := db.Exec(`CREATE TABLE t(x)`); err != nil {
t.Fatalf("write: %v", err)
}
mustClose(t, db)
plain, err := sql.Open("sqlite3", "file:"+path)
if err != nil {
t.Fatal(err)
}
defer plain.Close()
if _, err := plain.Exec(`SELECT count(*) FROM sqlite_master`); err == nil {
t.Fatalf("expected failure opening encrypted file without key, got nil")
}
}
// TestCipherTuningParamsAreApplied writes a database with a non-default
// _cipher_page_size and proves the parameter is actually applied: reopening with
// only the key (default page size) must fail, while reopening with the matching
// page size succeeds. This would fail (the no-param reopen would succeed) if the
// cipher-tuning params were silently ignored.
func TestCipherTuningParamsAreApplied(t *testing.T) {
path := filepath.Join(t.TempDir(), "tuned.db")
const pageSize = "8192"
tuned := fmt.Sprintf("file:%s?_key=%s&_cipher_page_size=%s", path, testKey, pageSize)
db, err := sql.Open("sqlite3", tuned)
if err != nil {
t.Fatal(err)
}
if _, err := db.Exec(`CREATE TABLE t(x TEXT); INSERT INTO t VALUES('tuned');`); err != nil {
t.Fatalf("write: %v", err)
}
mustClose(t, db)
// Key alone, default page size: must fail to read.
def := openKeyed(t, path, testKey)
if _, err := def.Exec(`SELECT count(*) FROM sqlite_master`); err == nil {
_ = def.Close()
t.Fatalf("expected failure reopening with default page size, got nil")
}
mustClose(t, def)
// Key plus the matching page size: must read back.
db, err = sql.Open("sqlite3", tuned)
if err != nil {
t.Fatal(err)
}
defer db.Close()
var got string
if err := db.QueryRow(`SELECT x FROM t`).Scan(&got); err != nil {
t.Fatalf("reopen with matching page size: %v", err)
}
if got != "tuned" {
t.Fatalf("got %q, want tuned", got)
}
}
// sqlcipherCLI returns the path to the sqlcipher command-line shell, skipping
// the test if it is not installed.
func sqlcipherCLI(t *testing.T) string {
t.Helper()
p, err := exec.LookPath("sqlcipher")
if err != nil {
t.Skip("sqlcipher CLI not on PATH; skipping interop test")
}
return p
}
// runCLI runs the sqlcipher shell against dbPath, feeding script on stdin, and
// returns its combined output.
func runCLI(t *testing.T, cli, dbPath, script string) (string, error) {
t.Helper()
cmd := exec.Command(cli, dbPath)
cmd.Stdin = strings.NewReader(script)
out, err := cmd.CombinedOutput()
return string(out), err
}
// cliKey renders a key for a PRAGMA key statement in a CLI script, matching the
// driver's quoteKey behaviour.
func cliKey(k string) string {
return "'" + strings.ReplaceAll(k, "'", "''") + "'"
}
// TestInteropDriverWriteCLIRead verifies the sqlcipher CLI can read a database
// the driver wrote, using default cipher settings.
func TestInteropDriverWriteCLIRead(t *testing.T) {
cli := sqlcipherCLI(t)
path := filepath.Join(t.TempDir(), "dw.db")
db := openKeyed(t, path, testKey)
if _, err := db.Exec(`CREATE TABLE t(x TEXT); INSERT INTO t VALUES('interop');`); err != nil {
t.Fatalf("driver write: %v", err)
}
mustClose(t, db)
script := fmt.Sprintf("PRAGMA key=%s;\nSELECT x FROM t;\n", cliKey(testKey))
out, err := runCLI(t, cli, path, script)
if err != nil {
t.Fatalf("cli read: %v (%s)", err, out)
}
if !strings.Contains(out, "interop") {
t.Fatalf("cli output %q missing 'interop'", out)
}
}
// rawKeyHex is a 32-byte SQLCipher raw key (64 hex chars), the KDF-bypass form.
const rawKeyHex = "2dd29ca851e7b56e4697b0e1f08507293d761a05ce4d1b628663f411a8086d99"
// TestInteropRawKeyBypassesKDF proves the documented raw-key DSN form
// (_key=x'<hex>') keys the database by the raw bytes, bypassing the KDF, rather
// than running the hex string through SQLCipher's passphrase KDF. The driver
// writes with the raw key; an independent sqlcipher CLI reads it back via the
// raw-key PRAGMA form (positive), while the CLI opening the SAME file with the
// SAME hex as a passphrase fails to decrypt (negative). The negative is what
// distinguishes a true raw key from a passphrase: a self-round-trip would pass
// even if quoteKey regressed to the passphrase form, but this test would not.
func TestInteropRawKeyBypassesKDF(t *testing.T) {
cli := sqlcipherCLI(t)
path := filepath.Join(t.TempDir(), "raw.db")
dsn := fmt.Sprintf("file:%s?_key=x'%s'", path, rawKeyHex)
db, err := sql.Open("sqlite3", dsn)
if err != nil {
t.Fatalf("open %q: %v", dsn, err)
}
if _, err := db.Exec(`CREATE TABLE t(x TEXT); INSERT INTO t VALUES('rawkey');`); err != nil {
t.Fatalf("driver write: %v", err)
}
mustClose(t, db)
// Positive: the CLI reads it back with the raw-key PRAGMA form.
rawScript := fmt.Sprintf("PRAGMA key=\"x'%s'\";\nSELECT x FROM t;\n", rawKeyHex)
if out, err := runCLI(t, cli, path, rawScript); err != nil || !strings.Contains(out, "rawkey") {
t.Fatalf("cli raw-key read failed: err=%v out=%q", err, out)
}
// Negative: the same hex treated as a passphrase (KDF applied) must NOT
// decrypt the file — proving the driver wrote a raw key, not a passphrase.
passScript := fmt.Sprintf("PRAGMA key=%s;\nSELECT x FROM t;\n", cliKey(rawKeyHex))
if out, err := runCLI(t, cli, path, passScript); err == nil && strings.Contains(out, "rawkey") {
t.Fatalf("hex read as a passphrase decrypted the raw-key db; KDF was not bypassed (out=%q)", out)
}
}
// TestInteropCLIWriteDriverRead verifies the driver can read a database the
// sqlcipher CLI wrote, using default cipher settings.
func TestInteropCLIWriteDriverRead(t *testing.T) {
cli := sqlcipherCLI(t)
path := filepath.Join(t.TempDir(), "cw.db")
script := fmt.Sprintf("PRAGMA key=%s;\nCREATE TABLE t(x TEXT);\nINSERT INTO t VALUES('fromcli');\n", cliKey(testKey))
if out, err := runCLI(t, cli, path, script); err != nil {
t.Fatalf("cli write: %v (%s)", err, out)
}
db := openKeyed(t, path, testKey)
defer db.Close()
var got string
if err := db.QueryRow(`SELECT x FROM t`).Scan(&got); err != nil {
t.Fatalf("driver read: %v", err)
}
if got != "fromcli" {
t.Fatalf("got %q, want fromcli", got)
}
}