Debian Codegraph @

lualib/rspamadm/secretbox.lua

raw
1 local rspamd_util = require 'rspamd_util'
2 local rspamd_text = require 'rspamd_text'
3 local argparse = require 'argparse'
4
5 local parser = argparse()
6 :name "secretbox"
7 :description "Encrypt/decrypt given text with given key and nonce"
8 :help_description_margin(32)
9 :command_target('command')
10 :require_command(true)
11
12 parser:mutex(
13 parser:flag '-R --raw'
14 :description('Encrypted text(and nonce if it is there) will be given in raw'),
15 parser:flag '-H --hex'
16 :description('Encrypted text(and nonce if it is there) will be given in hex'),
17 parser:flag '-b --base32'
18 :description('Encrypted text(and nonce if it is there) will be given in base32'),
19 parser:flag '-B --base64'
20 :description('Encrypted text(and nonce if it is there) will be given in base64')
21 )
22
23 local decrypt = parser:command 'decrypt'
24 :description 'Decrypt text with given key and nonce'
25
26 decrypt:option "-t --text"
27 :description("Encrypted text")
28 :argname("<text>")
29 decrypt:option "-k --key"
30 :description("Key used to encrypt text")
31 :argname("<key>")
32 decrypt:option "-n --nonce"
33 :description("Nonce used to encrypt text")
34 :argname("<nonce>")
35 :default(nil)
36
37 local encrypt = parser:command 'encrypt'
38 :description 'Encrypt text with given key'
39
40 encrypt:option "-t --text"
41 :description("Text to encrypt")
42 :argname("<text>")
43 encrypt:option "-k --key"
44 :description("Key to encrypt text")
45 :argname("<key>")
46 encrypt:option "-n --nonce"
47 :description("Nonce to encrypt text")
48 :argname("<nonce>")
49 :default(nil)
50
51 local keygen = parser:command 'keygen'
52 :description 'Generate symmetric key'
53
54 keygen:option "-l --length"
55 :description("Key length in bytes (default 32)")
56 :argname("<length>")
57 :default("32")
58
59 local function set_up_encoding(args, type, text)
60 local function fromhex(str)
61 return (str:gsub('..', function(cc)
62 return string.char(tonumber(cc, 16))
63 end))
64 end
65
66 local function tohex(str)
67 return (str:gsub('.', function(c)
68 return string.format('%02X', string.byte(c))
69 end))
70 end
71
72 local output = text
73
74 if type == 'encode' then
75 if args.hex then
76 output = tohex(text)
77 elseif args.base32 then
78 output = rspamd_util.encode_base32(text)
79 elseif args.base64 then
80 output = rspamd_util.encode_base64(text)
81 end
82 elseif type == 'decode' then
83 if args.hex then
84 output = fromhex(text)
85 elseif args.base32 then
86 output = rspamd_util.decode_base32(text)
87 elseif args.base64 then
88 output = rspamd_util.decode_base64(text)
89 else
90 -- Autodetect input encoding when no explicit flags are provided
91 if text and #text > 0 then
92 -- If input contains non-ASCII bytes, treat as raw to avoid corruption
93 if not text:match('^[%g%s]+$') then
94 return text
95 end
96
97 local cand = text:gsub('%s+', '')
98 -- Prefer hex if it looks like hex (even length)
99 if cand:match('^%x+$') and (#cand % 2 == 0) then
100 output = fromhex(cand)
101 else
102 -- Try base64 (standard and urlsafe characters)
103 if cand:match('^[A-Za-z0-9+/=_-]+$') and (#cand % 4 == 0) then
104 local b64 = rspamd_util.decode_base64(cand)
105 if b64 and b64 ~= '' then
106 output = b64
107 else
108 -- Try base32 (check charset and length multiple of 8)
109 local up = cand:upper()
110 if up:match('^[A-Z2-7=]+$') and (#up % 8 == 0) then
111 local b32 = rspamd_util.decode_base32(cand)
112 if b32 and b32 ~= '' then
113 output = b32
114 end
115 end
116 end
117 else
118 -- Try base32 directly if base64 pattern doesn't match
119 local up = cand:upper()
120 if up:match('^[A-Z2-7=]+$') and (#up % 8 == 0) then
121 local b32 = rspamd_util.decode_base32(cand)
122 if b32 and b32 ~= '' then
123 output = b32
124 end
125 end
126 end
127 end
128 end
129 end
130 end
131
132 return output
133 end
134
135 local function read_all_stdin()
136 local data = io.read('*a')
137 if not data then return '' end
138 return data
139 end
140
141 local function get_text_input(args)
142 if args.text == nil or args.text == '-' then
143 return read_all_stdin()
144 end
145 return args.text
146 end
147
148 local function write_output(args, text)
149 if args.hex or args.base32 or args.base64 then
150 print(set_up_encoding(args, 'encode', text))
151 else
152 io.write(text)
153 end
154 end
155
156 -- Auto-detect key encoding (hex or base64) and return raw bytes string
157 local function decode_key_auto(key_str)
158 if not key_str or key_str == '' then return key_str end
159
160 local function fromhex(str)
161 return (str:gsub('..', function(cc)
162 return string.char(tonumber(cc, 16))
163 end))
164 end
165
166 -- hex: only [0-9A-Fa-f], even length, and long enough to likely be a key (>=32 bytes)
167 if key_str:match('^%x+$') and (#key_str % 2 == 0) and (#key_str >= 64) then
168 return fromhex(key_str)
169 end
170
171 -- base64: only valid charset, length multiple of 4, and long enough (>= 44 for 32 bytes)
172 if key_str:match('^[A-Za-z0-9+/=]+$') and (#key_str % 4 == 0) and (#key_str >= 44) then
173 local decoded = rspamd_util.decode_base64(key_str)
174 if decoded and decoded ~= '' then
175 return decoded
176 end
177 end
178
179 -- fallback: treat as raw
180 return key_str
181 end
182
183 local function decryption_handler(args)
184 local rspamd_secretbox = require 'rspamd_cryptobox_secretbox'
185 local key = decode_key_auto(args.key)
186 local box = rspamd_secretbox.create(key)
187
188 local plaintext = nil
189 local input_text = get_text_input(args)
190 if (args.nonce ~= nil) then
191 local decoded_text = set_up_encoding(args, 'decode', input_text)
192 local decoded_nonce = set_up_encoding(args, 'decode', tostring(args.nonce))
193
194 local ok, out = box:decrypt(decoded_text, decoded_nonce)
195 if ok then plaintext = out end
196 else
197 local text_with_nonce = set_up_encoding(args, 'decode', input_text)
198 local nonce, text
199 if type(text_with_nonce) == 'userdata' then
200 nonce = text_with_nonce:sub(1, 24)
201 text = text_with_nonce:sub(25)
202 else
203 local s = tostring(text_with_nonce)
204 nonce = string.sub(s, 1, 24)
205 text = string.sub(s, 25)
206 end
207
208 local ok, out = box:decrypt(text, nonce)
209 if ok then plaintext = out end
210 end
211
212 if plaintext ~= nil then
213 -- Plaintext must be printed as-is to preserve legacy semantics
214 print(tostring(plaintext))
215 else
216 print('The decryption failed. Please check the correctness of the arguments given.')
217 end
218 end
219
220 local function encryption_handler(args)
221 local rspamd_secretbox = require 'rspamd_cryptobox_secretbox'
222 local key = decode_key_auto(args.key)
223 local box = rspamd_secretbox.create(key)
224
225 local combined
226 local input_text = get_text_input(args)
227 if args.nonce ~= nil then
228 local decoded_nonce = set_up_encoding(args, 'decode', tostring(args.nonce))
229 local ct = box:encrypt(input_text, decoded_nonce)
230 combined = tostring(decoded_nonce) .. tostring(ct)
231 else
232 local ct, nonce = box:encrypt(input_text)
233 combined = tostring(nonce) .. tostring(ct)
234 end
235
236 if combined ~= nil then
237 write_output(args, tostring(combined))
238 else
239 print('The encryption failed. Please check the correctness of the arguments given.')
240 end
241 end
242
243 local function keygen_handler(args)
244 local len = tonumber(args.length) or 32
245 if len <= 0 then len = 32 end
246
247 local key = rspamd_text.randombytes(len)
248 local raw = key:str()
249
250 if not (args.hex or args.base32 or args.base64 or args.raw) then
251 -- default to base64 for key output if not specified
252 print(rspamd_util.encode_base64(raw))
253 else
254 print(set_up_encoding(args, 'encode', raw))
255 end
256 end
257
258 local command_handlers = {
259 decrypt = decryption_handler,
260 encrypt = encryption_handler,
261 keygen = keygen_handler,
262 }
263
264 local function handler(args)
265 local cmd_opts = parser:parse(args)
266
267 local f = command_handlers[cmd_opts.command]
268 if not f then
269 parser:error(string.format("command isn't implemented: %s",
270 cmd_opts.command))
271 end
272 f(cmd_opts)
273 end
274
275
276 return {
277 name = 'secret_box',
278 aliases = { 'secretbox', 'secret_box' },
279 handler = handler,
280 description = parser._description
281 }