Debian Codegraph @

lualib/rspamadm/keypair.lua

raw
1 --[[
2 Copyright (c) 2022, Vsevolod Stakhov <[email protected]>
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 ]]--
16
17 local argparse = require "argparse"
18 local rspamd_keypair = require "rspamd_cryptobox_keypair"
19 local rspamd_pubkey = require "rspamd_cryptobox_pubkey"
20 local rspamd_signature = require "rspamd_cryptobox_signature"
21 local rspamd_crypto = require "rspamd_cryptobox"
22 local rspamd_util = require "rspamd_util"
23 local ucl = require "ucl"
24 local logger = require "rspamd_logger"
25
26 -- Define command line options
27 local parser = argparse()
28 :name "rspamadm keypair"
29 :description "Manages keypairs for Rspamd"
30 :help_description_margin(30)
31 :command_target("command")
32 :require_command(false)
33
34 -- Generate subcommand
35 local generate = parser:command "generate gen g"
36 :description "Creates a new keypair"
37 generate:flag "-s --sign"
38 :description "Generates a sign keypair instead of the encryption one"
39 generate:flag "-n --nist"
40 :description "Uses nist encryption algorithm"
41 generate:option "-o --output"
42 :description "Write keypair to file"
43 :argname "<file>"
44 generate:mutex(
45 generate:flag "-j --json"
46 :description "Output JSON instead of UCL",
47 generate:flag "-u --ucl"
48 :description "Output UCL"
49 :default(true)
50 )
51 generate:option "--name"
52 :description "Adds name extension"
53 :argname "<name>"
54
55 -- Sign subcommand
56
57 local sign = parser:command "sign sig s"
58 :description "Signs a file using keypair"
59 sign:option "-k --keypair"
60 :description "Keypair to use"
61 :argname "<file>"
62 sign:option "-s --suffix"
63 :description "Suffix for signature"
64 :argname "<suffix>"
65 :default("sig")
66 sign:argument "file"
67 :description "File to sign"
68 :argname "<file>"
69 :args "*"
70
71 -- Verify subcommand
72
73 local verify = parser:command "verify ver v"
74 :description "Verifies a file using keypair or a public key"
75 verify:mutex(
76 verify:option "-p --pubkey"
77 :description "Load pubkey from the specified file"
78 :argname "<file>",
79 verify:option "-P --pubstring"
80 :description "Load pubkey from the base32 encoded string"
81 :argname "<base32>",
82 verify:option "-k --keypair"
83 :description "Get pubkey from the keypair file"
84 :argname "<file>"
85 )
86 verify:argument "file"
87 :description "File to verify"
88 :argname "<file>"
89 :args "*"
90 verify:flag "-n --nist"
91 :description "Uses nistp curves (P256)"
92 verify:option "-s --suffix"
93 :description "Suffix for signature"
94 :argname "<suffix>"
95 :default("sig")
96
97 -- Encrypt subcommand
98
99 local encrypt = parser:command "encrypt crypt enc e"
100 :description "Encrypts a file using keypair (or a pubkey)"
101 encrypt:mutex(
102 encrypt:option "-p --pubkey"
103 :description "Load pubkey from the specified file"
104 :argname "<file>",
105 encrypt:option "-P --pubstring"
106 :description "Load pubkey from the base32 encoded string"
107 :argname "<base32>",
108 encrypt:option "-k --keypair"
109 :description "Get pubkey from the keypair file"
110 :argname "<file>"
111 )
112 encrypt:option "-s --suffix"
113 :description "Suffix for encrypted file"
114 :argname "<suffix>"
115 :default("enc")
116 encrypt:argument "file"
117 :description "File to encrypt"
118 :argname "<file>"
119 :args "*"
120 encrypt:flag "-r --rm"
121 :description "Remove unencrypted file"
122 encrypt:flag "-f --force"
123 :description "Remove destination file if it exists"
124
125 -- Decrypt subcommand
126
127 local decrypt = parser:command "decrypt dec d"
128 :description "Decrypts a file using keypair"
129 decrypt:option "-k --keypair"
130 :description "Get pubkey from the keypair file"
131 :argname "<file>"
132 decrypt:flag "-S --keep-suffix"
133 :description "Preserve suffix for decrypted file (overwrite encrypted)"
134 decrypt:argument "file"
135 :description "File to encrypt"
136 :argname "<file>"
137 :args "*"
138 decrypt:flag "-f --force"
139 :description "Remove destination file if it exists (implied with -S)"
140 decrypt:flag "-r --rm"
141 :description "Remove encrypted file"
142
143 -- Default command is generate, so duplicate options to be compatible
144
145 parser:flag "-s --sign"
146 :description "Generates a sign keypair instead of the encryption one"
147 parser:flag "-n --nist"
148 :description "Uses nistp curves (P256)"
149 parser:mutex(
150 parser:flag "-j --json"
151 :description "Output JSON instead of UCL",
152 parser:flag "-u --ucl"
153 :description "Output UCL"
154 :default(true)
155 )
156 parser:option "-o --output"
157 :description "Write keypair to file"
158 :argname "<file>"
159
160 local function fatal(...)
161 logger.errx(...)
162 os.exit(1)
163 end
164
165 local function ask_yes_no(greet, default)
166 local def_str
167 if default then
168 greet = greet .. "[Y/n]: "
169 def_str = "yes"
170 else
171 greet = greet .. "[y/N]: "
172 def_str = "no"
173 end
174
175 local reply = rspamd_util.readline(greet)
176
177 if not reply then
178 os.exit(0)
179 end
180 if #reply == 0 then
181 reply = def_str
182 end
183 reply = reply:lower()
184 if reply == 'y' or reply == 'yes' then
185 return true
186 end
187
188 return false
189 end
190
191 local function generate_handler(opts)
192 local mode = 'encryption'
193 if opts.sign then
194 mode = 'sign'
195 end
196 local alg = 'curve25519'
197 if opts.nist then
198 alg = 'nist'
199 end
200 -- TODO: probably, do it in a more safe way
201 local kp = rspamd_keypair.create(mode, alg):totable()
202
203 if opts.name then
204 kp.keypair.extensions = {
205 name = opts.name
206 }
207 end
208
209 local format = 'ucl'
210
211 if opts.json then
212 format = 'json'
213 end
214
215 if opts.output then
216 local out = io.open(opts.output, 'w')
217 if not out then
218 fatal('cannot open output to write: ' .. opts.output)
219 end
220 out:write(ucl.to_format(kp, format))
221 out:close()
222 else
223 io.write(ucl.to_format(kp, format))
224 end
225 end
226
227 local function sign_handler(opts)
228 if opts.file then
229 if type(opts.file) == 'string' then
230 opts.file = { opts.file }
231 end
232 else
233 parser:error('no files to sign')
234 end
235 if not opts.keypair then
236 parser:error("no keypair specified")
237 end
238
239 local ucl_parser = ucl.parser()
240 local res, err = ucl_parser:parse_file(opts.keypair)
241
242 if not res then
243 fatal(string.format('cannot load %s: %s', opts.keypair, err))
244 end
245
246 local kp = rspamd_keypair.load(ucl_parser:get_object())
247
248 if not kp then
249 fatal("cannot load keypair: " .. opts.keypair)
250 end
251
252 for _, fname in ipairs(opts.file) do
253 local sig = rspamd_crypto.sign_file(kp, fname)
254
255 if not sig then
256 fatal(string.format("cannot sign %s\n", fname))
257 end
258
259 local out = string.format('%s.%s', fname, opts.suffix or 'sig')
260 local of = io.open(out, 'w')
261 if not of then
262 fatal('cannot open output to write: ' .. out)
263 end
264 of:write(sig:bin())
265 of:close()
266 io.write(string.format('signed %s -> %s (%s)\n', fname, out, sig:hex()))
267 end
268 end
269
270 local function verify_handler(opts)
271 if opts.file then
272 if type(opts.file) == 'string' then
273 opts.file = { opts.file }
274 end
275 else
276 parser:error('no files to verify')
277 end
278
279 local pk
280 local alg = 'curve25519'
281
282 if opts.keypair then
283 local ucl_parser = ucl.parser()
284 local res, err = ucl_parser:parse_file(opts.keypair)
285
286 if not res then
287 fatal(string.format('cannot load %s: %s', opts.keypair, err))
288 end
289
290 local kp = rspamd_keypair.load(ucl_parser:get_object())
291
292 if not kp then
293 fatal("cannot load keypair: " .. opts.keypair)
294 end
295
296 pk = kp:pk()
297 alg = kp:alg()
298 elseif opts.pubkey then
299 if opts.nist then
300 alg = 'nist'
301 end
302 pk = rspamd_pubkey.load(opts.pubkey, 'sign', alg)
303 elseif opts.pubstr then
304 if opts.nist then
305 alg = 'nist'
306 end
307 pk = rspamd_pubkey.create(opts.pubstr, 'sign', alg)
308 end
309
310 if not pk then
311 fatal("cannot create pubkey")
312 end
313
314 local valid = true
315
316 for _, fname in ipairs(opts.file) do
317
318 local sig_fname = string.format('%s.%s', fname, opts.suffix or 'sig')
319 local sig = rspamd_signature.load(sig_fname, alg)
320
321 if not sig then
322 fatal(string.format("cannot load signature for %s -> %s",
323 fname, sig_fname))
324 end
325
326 if rspamd_crypto.verify_file(pk, sig, fname, alg) then
327 io.write(string.format('verified %s -> %s (%s)\n', fname, sig_fname, sig:hex()))
328 else
329 valid = false
330 io.write(string.format('FAILED to verify %s -> %s (%s)\n', fname,
331 sig_fname, sig:hex()))
332 end
333 end
334
335 if not valid then
336 os.exit(1)
337 end
338 end
339
340 local function encrypt_handler(opts)
341 if opts.file then
342 if type(opts.file) == 'string' then
343 opts.file = { opts.file }
344 end
345 else
346 parser:error('no files to sign')
347 end
348
349 local pk
350 local alg = 'curve25519'
351
352 if opts.keypair then
353 local ucl_parser = ucl.parser()
354 local res, err = ucl_parser:parse_file(opts.keypair)
355
356 if not res then
357 fatal(string.format('cannot load %s: %s', opts.keypair, err))
358 end
359
360 local kp = rspamd_keypair.load(ucl_parser:get_object())
361
362 if not kp then
363 fatal("cannot load keypair: " .. opts.keypair)
364 end
365
366 pk = kp:pk()
367 alg = kp:alg()
368 elseif opts.pubkey then
369 if opts.nist then
370 alg = 'nist'
371 end
372 pk = rspamd_pubkey.load(opts.pubkey, 'sign', alg)
373 elseif opts.pubstr then
374 if opts.nist then
375 alg = 'nist'
376 end
377 pk = rspamd_pubkey.create(opts.pubstr, 'sign', alg)
378 end
379
380 if not pk then
381 fatal("cannot load keypair: " .. opts.keypair)
382 end
383
384 for _, fname in ipairs(opts.file) do
385 local enc = rspamd_crypto.encrypt_file(pk, fname, alg)
386
387 if not enc then
388 fatal(string.format("cannot encrypt %s\n", fname))
389 end
390
391 local out
392 if opts.suffix and #opts.suffix > 0 then
393 out = string.format('%s.%s', fname, opts.suffix)
394 else
395 out = string.format('%s', fname)
396 end
397
398 if rspamd_util.file_exists(out) then
399 if opts.force or ask_yes_no(string.format('File %s already exists, overwrite?',
400 out), true) then
401 os.remove(out)
402 else
403 os.exit(1)
404 end
405 end
406
407 enc:save_in_file(out)
408
409 if opts.rm then
410 os.remove(fname)
411 io.write(string.format('encrypted %s (deleted) -> %s\n', fname, out))
412 else
413 io.write(string.format('encrypted %s -> %s\n', fname, out))
414 end
415 end
416 end
417
418 local function decrypt_handler(opts)
419 if opts.file then
420 if type(opts.file) == 'string' then
421 opts.file = { opts.file }
422 end
423 else
424 parser:error('no files to decrypt')
425 end
426 if not opts.keypair then
427 parser:error("no keypair specified")
428 end
429
430 local ucl_parser = ucl.parser()
431 local res, err = ucl_parser:parse_file(opts.keypair)
432
433 if not res then
434 fatal(string.format('cannot load %s: %s', opts.keypair, err))
435 end
436
437 local kp = rspamd_keypair.load(ucl_parser:get_object())
438
439 if not kp then
440 fatal("cannot load keypair: " .. opts.keypair)
441 end
442
443 for _, fname in ipairs(opts.file) do
444 local decrypted = rspamd_crypto.decrypt_file(kp, fname)
445
446 if not decrypted then
447 fatal(string.format("cannot decrypt %s\n", fname))
448 end
449
450 local out
451 if not opts['keep-suffix'] then
452 -- Strip the last suffix
453 out = fname:match("^(.+)%..+$")
454 else
455 out = fname
456 end
457
458 local removed = false
459
460 if rspamd_util.file_exists(out) then
461 if (opts.force or opts['keep-suffix'])
462 or ask_yes_no(string.format('File %s already exists, overwrite?', out), true) then
463 os.remove(out)
464 removed = true
465 else
466 os.exit(1)
467 end
468 end
469
470 if opts.rm then
471 os.remove(fname)
472 removed = true
473 end
474
475 if removed then
476 io.write(string.format('decrypted %s (removed) -> %s\n', fname, out))
477 else
478 io.write(string.format('decrypted %s -> %s\n', fname, out))
479 end
480 end
481 end
482
483 local function handler(args)
484 local opts = parser:parse(args)
485
486 local command = opts.command or "generate"
487
488 if command == 'generate' then
489 generate_handler(opts)
490 elseif command == 'sign' then
491 sign_handler(opts)
492 elseif command == 'verify' then
493 verify_handler(opts)
494 elseif command == 'encrypt' then
495 encrypt_handler(opts)
496 elseif command == 'decrypt' then
497 decrypt_handler(opts)
498 else
499 parser:error('command %s is not implemented', command)
500 end
501 end
502
503 return {
504 name = 'keypair',
505 aliases = { 'kp', 'key' },
506 handler = handler,
507 description = parser._description
508 }