Debian Codegraph @

cmd/age-plugin-batchpass/plugin-batchpass.go

raw symbols SCIP
1 package main
2
3 import (
4 "errors"
5 "flag"
6 "fmt"
7 "io"
8 "log"
9 "os"
10 "runtime/debug"
11 "strconv"
12 "strings"
13
14 "filippo.io/age"
15 "filippo.io/age/plugin"
16 )
17
18 const usage = `age-plugin-batchpass is an age plugin that enables non-interactive
19 passphrase-based encryption and decryption using environment variables.
20
21 WARNING: IN 90% OF CASES, YOU DON'T NEED THIS PLUGIN.
22
23 This functionality is not built into the age CLI because most applications
24 should use native keys instead of scripting passphrase-based encryption.
25
26 Humans are notoriously bad at remembering and generating strong passphrases.
27 age uses scrypt to partially mitigate this, which is necessarily very slow.
28
29 If a computer will be doing the remembering anyway, you can and should use
30 native keys instead. There is no need to manage separate public and private
31 keys, you encrypt directly to the private key:
32
33 $ age-keygen -o key.txt
34 $ age -e -i key.txt file.txt > file.txt.age
35 $ age -d -i key.txt file.txt.age > file.txt
36
37 Likewise, you can store a native identity string in an environment variable
38 or through your CI secrets manager and use it to encrypt and decrypt files
39 non-interactively:
40
41 $ export AGE_SECRET=$(age-keygen)
42 $ age -e -i <(echo "$AGE_SECRET") file.txt > file.txt.age
43 $ age -d -i <(echo "$AGE_SECRET") file.txt.age > file.txt
44
45 The age CLI also natively supports passphrase-encrypted identity files, so you
46 can use that functionality to non-interactively encrypt multiple files such that
47 you will be able to decrypt them later by entering the same passphrase:
48
49 $ age-keygen -pq | age -p -o encrypted-identity.txt
50 Public key: age1pq1cd[... 1950 more characters ...]
51 Enter passphrase (leave empty to autogenerate a secure one):
52 age: using autogenerated passphrase "eternal-erase-keen-suffer-fog-exclude-huge-scorpion-escape-scrub"
53 $ age -r age1pq1cd[... 1950 more characters ...] file.txt > file.txt.age
54 $ age -d -i encrypted-identity.txt file.txt.age > file.txt
55 Enter passphrase for identity file "encrypted-identity.txt":
56
57 Finally, when using this plugin care should be taken not to let the password be
58 persisted in the shell history or leaked to other users on multi-user systems.
59
60 Usage:
61
62 $ AGE_PASSPHRASE=password age -e -j batchpass file.txt > file.txt.age
63
64 $ AGE_PASSPHRASE=password age -d -j batchpass file.txt.age > file.txt
65
66 Alternatively, you can use AGE_PASSPHRASE_FD to read the passphrase from
67 a file descriptor. Trailing newlines are stripped from the file contents.
68
69 When encrypting, you can set AGE_PASSPHRASE_WORK_FACTOR to adjust the scrypt
70 work factor (between 1 and 30, default 18). Higher values are more secure
71 but slower. The age CLI refuses to decrypt files above 22, and so does this
72 plugin unless AGE_PASSPHRASE_MAX_WORK_FACTOR is set to at least the same value.
73
74 When decrypting, you can set AGE_PASSPHRASE_MAX_WORK_FACTOR to change the
75 maximum scrypt work factor accepted (between 1 and 30, default 22). This can
76 be used to avoid very slow decryptions, or to allow slower ones.`
77
78 // Version can be set at link time to override debug.BuildInfo.Main.Version when
79 // building manually without git history. It should look like "v1.2.3".
80 var Version string
81
82 func main() {
83 flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s\n", usage) }
84
85 p, err := plugin.New("batchpass")
86 if err != nil {
87 log.Fatal(err)
88 }
89 p.RegisterFlags(nil)
90
91 versionFlag := flag.Bool("version", false, "print the version")
92 flag.Parse()
93
94 if *versionFlag {
95 if buildInfo, ok := debug.ReadBuildInfo(); ok && Version == "" {
96 Version = buildInfo.Main.Version
97 }
98 fmt.Println(Version)
99 return
100 }
101
102 p.HandleIdentityAsRecipient(func(data []byte) (age.Recipient, error) {
103 if len(data) != 0 {
104 return nil, fmt.Errorf("batchpass identity does not take any payload")
105 }
106 pass, err := passphrase()
107 if err != nil {
108 return nil, err
109 }
110 r, err := age.NewScryptRecipient(pass)
111 if err != nil {
112 return nil, fmt.Errorf("failed to create scrypt recipient: %v", err)
113 }
114 if envWorkFactor := os.Getenv("AGE_PASSPHRASE_WORK_FACTOR"); envWorkFactor != "" {
115 workFactor, err := strconv.Atoi(envWorkFactor)
116 if err != nil {
117 return nil, fmt.Errorf("invalid AGE_PASSPHRASE_WORK_FACTOR: %v", err)
118 }
119 if workFactor > 30 || workFactor < 1 {
120 return nil, fmt.Errorf("AGE_PASSPHRASE_WORK_FACTOR must be between 1 and 30")
121 }
122 r.SetWorkFactor(workFactor)
123 }
124 return r, nil
125 })
126 p.HandleIdentity(func(data []byte) (age.Identity, error) {
127 if len(data) != 0 {
128 return nil, fmt.Errorf("batchpass identity does not take any payload")
129 }
130 pass, err := passphrase()
131 if err != nil {
132 return nil, err
133 }
134 maxWorkFactor := 0
135 if envMaxWorkFactor := os.Getenv("AGE_PASSPHRASE_MAX_WORK_FACTOR"); envMaxWorkFactor != "" {
136 maxWorkFactor, err = strconv.Atoi(envMaxWorkFactor)
137 if err != nil {
138 return nil, fmt.Errorf("invalid AGE_PASSPHRASE_MAX_WORK_FACTOR: %v", err)
139 }
140 if maxWorkFactor > 30 || maxWorkFactor < 1 {
141 return nil, fmt.Errorf("AGE_PASSPHRASE_MAX_WORK_FACTOR must be between 1 and 30")
142 }
143 }
144 return &batchpassIdentity{password: pass, maxWorkFactor: maxWorkFactor}, nil
145 })
146 os.Exit(p.Main())
147 }
148
149 type batchpassIdentity struct {
150 password string
151 maxWorkFactor int
152 }
153
154 func (i *batchpassIdentity) Unwrap(stanzas []*age.Stanza) ([]byte, error) {
155 for _, s := range stanzas {
156 if s.Type == "scrypt" && len(stanzas) != 1 {
157 return nil, errors.New("an scrypt recipient must be the only one")
158 }
159 }
160 if len(stanzas) != 1 || stanzas[0].Type != "scrypt" {
161 // Don't fallback to other identities, this plugin should mostly be used
162 // in isolation, from the CLI.
163 return nil, fmt.Errorf("file is not passphrase-encrypted")
164 }
165 ii, err := age.NewScryptIdentity(i.password)
166 if err != nil {
167 return nil, err
168 }
169 if i.maxWorkFactor != 0 {
170 ii.SetMaxWorkFactor(i.maxWorkFactor)
171 }
172 fileKey, err := ii.Unwrap(stanzas)
173 if errors.Is(err, age.ErrIncorrectIdentity) {
174 // ScryptIdentity returns ErrIncorrectIdentity to make it possible to
175 // try multiple passphrases from the API. If a user is invoking this
176 // plugin, it's safe to say they expect it to be the only mechanism to
177 // decrypt a passphrase-protected file.
178 return nil, fmt.Errorf("incorrect passphrase")
179 }
180 return fileKey, err
181 }
182
183 func passphrase() (string, error) {
184 envPASSPHRASE := os.Getenv("AGE_PASSPHRASE")
185 envFD := os.Getenv("AGE_PASSPHRASE_FD")
186 if envPASSPHRASE != "" && envFD != "" {
187 return "", fmt.Errorf("AGE_PASSPHRASE and AGE_PASSPHRASE_FD are mutually exclusive")
188 }
189 if envPASSPHRASE == "" && envFD == "" {
190 return "", fmt.Errorf("either AGE_PASSPHRASE or AGE_PASSPHRASE_FD must be set")
191 }
192
193 if envPASSPHRASE != "" {
194 return envPASSPHRASE, nil
195 }
196
197 fd, err := strconv.Atoi(envFD)
198 if err != nil {
199 return "", fmt.Errorf("invalid AGE_PASSPHRASE_FD: %v", err)
200 }
201 f := os.NewFile(uintptr(fd), "AGE_PASSPHRASE_FD")
202 if f == nil {
203 return "", fmt.Errorf("failed to open file descriptor %d", fd)
204 }
205 defer f.Close()
206 const maxPassphraseSize = 1024 * 1024 // 1 MiB
207 b, err := io.ReadAll(io.LimitReader(f, maxPassphraseSize+1))
208 if err != nil {
209 return "", fmt.Errorf("failed to read passphrase from fd %d: %v", fd, err)
210 }
211 if len(b) > maxPassphraseSize {
212 return "", fmt.Errorf("passphrase from fd %d is too long", fd)
213 }
214 return strings.TrimRight(string(b), "\r\n"), nil
215 }