-
Notifications
You must be signed in to change notification settings - Fork 11
/
strongbox.go
335 lines (300 loc) · 8.96 KB
/
strongbox.go
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
package main
import (
"bytes"
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/user"
"path/filepath"
"strings"
"filippo.io/age"
"filippo.io/age/armor"
)
var (
version = "dev"
commit = "none"
date = "unknown"
builtBy = "unknown"
// flags
flagDecrypt = flag.Bool("decrypt", false, "Decrypt single resource")
flagGenIdentity = flag.String("gen-identity", "", "Generate a new identity and add it to your strongbox identity file")
flagGenKey = flag.String("gen-key", "", "Generate a new key and add it to your strongbox keyring")
flagGitConfig = flag.Bool("git-config", false, "Configure git for strongbox use")
flagIdentityFile = flag.String("identity-file", "", "strongbox identity file, if not set default '$HOME/.strongbox_identity' will be used")
flagKey = flag.String("key", "", "Private key to use to decrypt")
flagKeyRing = flag.String("keyring", "", "strongbox keyring file path, if not set default '$HOME/.strongbox_keyring' will be used")
flagRecursive = flag.Bool("recursive", false, "Recursively decrypt all files under given folder, must be used with -decrypt flag")
flagClean = flag.String("clean", "", "intended to be called internally by git")
flagSmudge = flag.String("smudge", "", "intended to be called internally by git")
flagDiff = flag.String("diff", "", "intended to be called internally by git")
flagVersion = flag.Bool("version", false, "Strongbox version")
)
func usage() {
fmt.Fprintf(os.Stderr, "Usage:\n\n")
fmt.Fprintf(os.Stderr, "\tstrongbox -git-config\n")
fmt.Fprintf(os.Stderr, "\tstrongbox [-identity-file PATH] -gen-identity IDENTITY_NAME\n")
fmt.Fprintf(os.Stderr, "\tstrongbox [-keyring KEYRING_FILEPATH] -gen-key KEY_NAME\n")
fmt.Fprintf(os.Stderr, "\tstrongbox [-keyring KEYRING_FILEPATH] -decrypt -recursive [-key KEY] [PATH]\n")
fmt.Fprintf(os.Stderr, "\tstrongbox [-keyring KEYRING_FILEPATH] -decrypt -key KEY [PATH]\n")
fmt.Fprintf(os.Stderr, "\tstrongbox -version\n")
fmt.Fprintf(os.Stderr, "\n(age) if -identity-file flag is not set, default '$HOME/.strongbox_identity' will be used\n")
fmt.Fprintf(os.Stderr, "(siv) if -keyring flag is not set default file '$HOME/.strongbox_keyring' or '$STRONGBOX_HOME/.strongbox_keyring' will be used as keyring\n")
os.Exit(2)
}
func main() {
log.SetPrefix("strongbox: ")
log.SetFlags(log.LstdFlags | log.Lshortfile)
flag.Usage = usage
flag.Parse()
if *flagVersion || (flag.NArg() == 1 && flag.Arg(0) == "version") {
fmt.Printf("version=%s commit=%s date=%s builtBy=%s\n", version, commit, date, builtBy)
return
}
if *flagGitConfig {
gitConfig()
return
}
if *flagDiff != "" {
diff(*flagDiff)
return
}
// Set up keyring file name
home := deriveHome()
kr = &fileKeyRing{fileName: filepath.Join(home, ".strongbox_keyring")}
if *flagIdentityFile != "" {
identityFilename = *flagIdentityFile
} else {
identityFilename = filepath.Join(home, defaultIdentityFilename)
}
// if keyring flag is set replace default keyRing
if *flagKeyRing != "" {
kr = &fileKeyRing{fileName: *flagKeyRing}
// verify keyring is valid
if err := kr.Load(); err != nil {
log.Fatalf("unable to load keyring file:%s err:%s", *flagKeyRing, err)
}
}
if *flagGenKey != "" {
genKey(*flagGenKey)
return
}
if *flagDecrypt {
// handle recursive
if *flagRecursive {
var err error
target := flag.Arg(0)
if target == "" {
target, err = os.Getwd()
if err != nil {
log.Fatalf("target path not provided and unable to get cwd err:%s", err)
}
}
// for recursive decryption 'key' flag is optional but if provided
// it should be valid and all encrypted file will be decrypted using it
dk, err := decode([]byte(*flagKey))
if err != nil && *flagKey != "" {
log.Fatalf("Unable to decode given private key %v", err)
}
if err = recursiveDecrypt(target, dk); err != nil {
log.Fatalln(err)
}
return
}
if *flagKey == "" {
log.Fatalf("Must provide a `-key` when using -decrypt")
}
decryptCLI()
return
}
if *flagRecursive {
log.Println("-recursive flag is only supported with -decrypt")
usage()
}
if *flagGenIdentity != "" {
ageGenIdentity(*flagGenIdentity)
return
}
if *flagClean != "" {
clean(os.Stdin, os.Stdout, *flagClean)
return
}
if *flagSmudge != "" {
smudge(os.Stdin, os.Stdout, *flagSmudge)
return
}
}
func deriveHome() string {
// try explicitly set STRONGBOX_HOME
if home := os.Getenv("STRONGBOX_HOME"); home != "" {
return home
}
// try HOME env var
if home := os.Getenv("HOME"); home != "" {
return home
}
// Try user.Current which works in most cases, but may not work with CGO disabled.
u, err := user.Current()
if err == nil && u.HomeDir != "" {
return u.HomeDir
}
log.Fatal("Could not find $STRONGBOX_HOME, $HOME or call os/user.Current(). Please set $STRONGBOX_HOME, $HOME or recompile with CGO enabled")
// not reached
return ""
}
func decryptCLI() {
var fn string
if flag.Arg(0) == "" {
// no file passed, try to read stdin
fn = "/dev/stdin"
} else {
fn = flag.Arg(0)
}
fb, err := os.ReadFile(fn)
if err != nil {
log.Fatalf("Unable to read file to decrypt %v", err)
}
dk, err := decode([]byte(*flagKey))
if err != nil {
log.Fatalf("Unable to decode private key %v", err)
}
out, err := decrypt(fb, dk)
if err != nil {
log.Fatalf("Unable to decrypt %v", err)
}
fmt.Printf("%s", out)
}
func gitConfig() {
args := [][]string{
{"config", "--global", "--replace-all", "filter.strongbox.clean", "strongbox -clean %f"},
{"config", "--global", "--replace-all", "filter.strongbox.smudge", "strongbox -smudge %f"},
{"config", "--global", "--replace-all", "filter.strongbox.required", "true"},
{"config", "--global", "--replace-all", "diff.strongbox.textconv", "strongbox -diff"},
}
for _, command := range args {
cmd := exec.Command("git", command...)
if out, err := cmd.CombinedOutput(); err != nil {
log.Fatal(string(out))
}
}
log.Println("git global configuration updated successfully")
}
func diff(filename string) {
f, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
_, err = io.Copy(os.Stdout, f)
if err != nil {
log.Fatal(err)
}
}
func clean(r io.Reader, w io.Writer, filename string) {
// Read the file, fail on error
in, err := io.ReadAll(r)
if err != nil {
log.Fatal(err)
}
// Check the file is plaintext, if its an encrypted strongbox or age file, copy as is, and exit 0
if bytes.HasPrefix(in, prefix) || strings.HasPrefix(string(in), armor.Header) {
_, err = io.Copy(w, bytes.NewReader(in))
if err != nil {
log.Fatal(err)
}
return
}
// File is plaintext and needs to be encrypted, get the recipient or a
// key, fail on error
recipient, key, err := findRecipients(filename)
if err != nil {
log.Fatal(err)
}
// found recipient file and plaintext differs from HEAD
if recipient != nil {
ageEncrypt(w, recipient, in, filename)
}
if key != nil {
// encrypt the file, fail on error
out, err := encrypt(in, key)
if err != nil {
log.Fatal(err)
}
// write out encrypted file, fail on error
_, err = io.Copy(w, bytes.NewReader(out))
if err != nil {
log.Fatal(err)
}
}
}
// Called by git on `git checkout`
func smudge(r io.Reader, w io.Writer, filename string) {
in, err := io.ReadAll(r)
if err != nil {
log.Fatal(err)
}
if strings.HasPrefix(string(in), armor.Header) {
ageDecrypt(w, in)
return
}
if bytes.HasPrefix(in, prefix) {
key, err := keyLoader(filename)
if err != nil {
// don't log error if its keyNotFound
switch err {
case errKeyNotFound:
default:
log.Println(err)
}
// Couldn't load the key, just copy as is and return
if _, err = io.Copy(w, bytes.NewReader(in)); err != nil {
log.Println(err)
}
return
}
out, err := decrypt(in, key)
if err != nil {
log.Println(err)
out = in
}
if _, err := io.Copy(w, bytes.NewReader(out)); err != nil {
log.Println(err)
}
return
}
// file is a non-siv and non-age file, copy as is and exit
_, err = io.Copy(w, bytes.NewReader(in))
if err != nil {
log.Fatal(err)
}
}
// Finds closest age recipient or siv keyid
func findRecipients(filename string) ([]age.Recipient, []byte, error) {
path := filepath.Dir(filename)
for {
if fi, err := os.Stat(path); err == nil && fi.IsDir() {
ageRecipientFilename := filepath.Join(path, recipientFilename)
// If we found `.strongbox_recipient` - parse it and return
if keyFile, err := os.Stat(ageRecipientFilename); err == nil && !keyFile.IsDir() {
recipients, err := ageFileToRecipient(ageRecipientFilename)
return recipients, nil, err
}
// If we found `strongbox-keyid` - get the corresponding key and return it
keyFilename := filepath.Join(path, ".strongbox-keyid")
if keyFile, err := os.Stat(keyFilename); err == nil && !keyFile.IsDir() {
key, err := sivFileToKey(keyFilename)
return nil, key, err
}
}
if path == "." {
return nil, nil, fmt.Errorf("failed to find recipient or keyid for file %s", filename)
}
path = filepath.Dir(path)
}
}