@codua/codeoutline-win32-x64 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DISTRIBUTION.md +141 -0
- package/bin/xnet.exe +0 -0
- package/build-info.json +1 -1
- package/codeoutline +8 -0
- package/codeoutline.cmd +14 -7
- package/keys/update-ca.crt +20 -0
- package/keys/update-public.pem +9 -0
- package/package.json +1 -1
- package/scripts/codeoutline/command.lua +7 -1
- package/scripts/codeoutline/main.lua +10 -0
- package/scripts/codeoutline/update_sequence.lua +1 -0
- package/scripts/codeoutline/update_worker.lua +20 -0
- package/scripts/codeoutline/updater.lua +72 -0
- package/scripts/codeoutline/version.lua +1 -1
- package/scripts/xupgate/client.lua +135 -0
- package/scripts/xupgate/common.lua +76 -0
- package/scripts/xupgate/http_client.lua +382 -0
- package/scripts/xupgate/http_codec.lua +835 -0
- package/scripts/xupgate/proxy.lua +359 -0
- package/scripts/xupgate/signature.lua +311 -0
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
-- xproxy.lua - outbound proxy tunnels shared by the HTTP clients.
|
|
2
|
+
--
|
|
3
|
+
-- Protocols:
|
|
4
|
+
-- * SOCKS5 / SOCKS5h (RFC 1928 + RFC 1929 user/pass) -- socks5h delegates DNS
|
|
5
|
+
-- to the proxy, which is what we want when the origin is unresolvable
|
|
6
|
+
-- locally (e.g. reaching Google from a restricted network).
|
|
7
|
+
-- * HTTP CONNECT (RFC 7231) -- for HTTPS targets via an HTTP proxy.
|
|
8
|
+
-- Plaintext HTTP via an HTTP proxy is a plain forward proxy (absolute-form
|
|
9
|
+
-- request line, no tunnel); callers handle that case themselves and only use
|
|
10
|
+
-- M.auth_header here.
|
|
11
|
+
--
|
|
12
|
+
-- For HTTPS targets the tunnel carries raw TLS: once the proxy handshake
|
|
13
|
+
-- completes we surrender the plaintext fd (conn:detach) and upgrade it to a
|
|
14
|
+
-- client-mode TLS session with xnet.connect_tls_fd (SNI = real origin host).
|
|
15
|
+
-- The detach + upgrade is ALWAYS deferred to the next tick: detaching inside
|
|
16
|
+
-- the channel's own callback would free the channel the poll loop is mid-walk.
|
|
17
|
+
--
|
|
18
|
+
-- Usage:
|
|
19
|
+
-- local xproxy = require('xupgate.proxy')
|
|
20
|
+
-- local proxy = assert(xproxy.parse('socks5h://127.0.0.1:1080'))
|
|
21
|
+
-- local tun = xproxy.open_tunnel(proxy, host, port, {
|
|
22
|
+
-- on_ready = function(conn, extra)
|
|
23
|
+
-- local c, err = xproxy.attach(conn, extra, handler, {
|
|
24
|
+
-- tls = true, host = host, port = port, verify = true })
|
|
25
|
+
-- end,
|
|
26
|
+
-- on_error = function(msg) end,
|
|
27
|
+
-- })
|
|
28
|
+
-- tun:close('timeout') -- abort while the handshake is still in flight
|
|
29
|
+
|
|
30
|
+
local xutils = require('xutils') -- base64_encode for Basic proxy auth
|
|
31
|
+
|
|
32
|
+
local M = {}
|
|
33
|
+
|
|
34
|
+
local schar = string.char
|
|
35
|
+
local sbyte = string.byte
|
|
36
|
+
|
|
37
|
+
-- Parse "scheme://[user:pass@]host[:port]" into a proxy table, or nil[, err].
|
|
38
|
+
-- nil with no error means "no proxy configured" (nil / empty string).
|
|
39
|
+
function M.parse(s)
|
|
40
|
+
if type(s) ~= 'string' or s == '' then return nil end
|
|
41
|
+
local scheme, rest = s:match('^(%a[%w+.%-]*)://(.+)$')
|
|
42
|
+
if not scheme then
|
|
43
|
+
return nil, 'proxy url needs a scheme (socks5://, socks5h://, http://)'
|
|
44
|
+
end
|
|
45
|
+
scheme = scheme:lower()
|
|
46
|
+
local ptype
|
|
47
|
+
if scheme == 'socks5' or scheme == 'socks' then ptype = 'socks5'
|
|
48
|
+
elseif scheme == 'socks5h' then ptype = 'socks5h'
|
|
49
|
+
elseif scheme == 'http' then ptype = 'http'
|
|
50
|
+
else return nil, 'unsupported proxy scheme: ' .. scheme end
|
|
51
|
+
|
|
52
|
+
local userinfo, hostport = rest:match('^([^@]*)@(.+)$')
|
|
53
|
+
if not hostport then hostport = rest end
|
|
54
|
+
hostport = hostport:match('^([^/]+)') or hostport -- drop any /path
|
|
55
|
+
|
|
56
|
+
local user, pass
|
|
57
|
+
if userinfo and userinfo ~= '' then
|
|
58
|
+
user, pass = userinfo:match('^([^:]*):?(.*)$')
|
|
59
|
+
if pass == '' then pass = nil end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
local host, port
|
|
63
|
+
if hostport:sub(1, 1) == '[' then -- [ipv6]:port
|
|
64
|
+
host, port = hostport:match('^%[([^%]]+)%]:?(%d*)$')
|
|
65
|
+
else
|
|
66
|
+
host, port = hostport:match('^([^:]+):?(%d*)$')
|
|
67
|
+
end
|
|
68
|
+
if not host or host == '' then
|
|
69
|
+
return nil, 'bad proxy host: ' .. tostring(hostport)
|
|
70
|
+
end
|
|
71
|
+
port = tonumber(port) or (ptype == 'http' and 8080 or 1080)
|
|
72
|
+
return { type = ptype, host = host, port = port, user = user, pass = pass }
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
-- Proxy URL with any password masked, safe for logs and UI labels.
|
|
76
|
+
function M.redact(s)
|
|
77
|
+
if type(s) ~= 'string' then return s end
|
|
78
|
+
return (s:gsub('^(%a[%w+.%-]*://[^:@/]*):[^@/]*@', '%1:***@'))
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
-- Value for a Proxy-Authorization header, or nil when the proxy has no creds.
|
|
82
|
+
function M.auth_header(proxy)
|
|
83
|
+
if not proxy or not proxy.user then return nil end
|
|
84
|
+
return 'Basic ' .. xutils.base64_encode((proxy.user or '') .. ':' .. (proxy.pass or ''))
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
local function u16be(n) return schar(math.floor(n / 256) % 256, n % 256) end
|
|
88
|
+
|
|
89
|
+
local function socks5_greeting(proxy)
|
|
90
|
+
-- Offer no-auth, plus user/pass when creds are configured.
|
|
91
|
+
if proxy.user then return schar(0x05, 0x02, 0x00, 0x02) end
|
|
92
|
+
return schar(0x05, 0x01, 0x00)
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
local function socks5_auth_req(user, pass)
|
|
96
|
+
user, pass = user or '', pass or ''
|
|
97
|
+
if #user > 255 or #pass > 255 then return nil, 'socks5 credentials too long' end
|
|
98
|
+
return schar(0x01, #user) .. user .. schar(#pass) .. pass
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
-- CONNECT request. Always sends the host as a domain (ATYP=3) so the proxy
|
|
102
|
+
-- resolves it, EXCEPT for a dotted-quad IPv4 literal (ATYP=1). This makes
|
|
103
|
+
-- socks5 and socks5h behave identically here -- both let the proxy reach hosts
|
|
104
|
+
-- the client can't resolve, which is the whole point.
|
|
105
|
+
local function socks5_connect_req(host, port)
|
|
106
|
+
local a, b, c, d = host:match('^(%d+)%.(%d+)%.(%d+)%.(%d+)$')
|
|
107
|
+
if a and tonumber(a) < 256 and tonumber(b) < 256
|
|
108
|
+
and tonumber(c) < 256 and tonumber(d) < 256 then
|
|
109
|
+
return schar(0x05, 0x01, 0x00, 0x01,
|
|
110
|
+
tonumber(a), tonumber(b), tonumber(c), tonumber(d)) .. u16be(port)
|
|
111
|
+
end
|
|
112
|
+
if #host > 255 then return nil, 'host too long for socks5 (>255)' end
|
|
113
|
+
return schar(0x05, 0x01, 0x00, 0x03, #host) .. host .. u16be(port)
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
local SOCKS5_REP = {
|
|
117
|
+
[1] = 'general failure', [2] = 'connection not allowed', [3] = 'network unreachable',
|
|
118
|
+
[4] = 'host unreachable', [5] = 'connection refused', [6] = 'TTL expired',
|
|
119
|
+
[7] = 'command not supported', [8] = 'address type not supported',
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
-- The deferred hand-off needs a timer on this thread. Bring the pool up on
|
|
123
|
+
-- demand (the thread runner drives it once inited) so callers don't have to.
|
|
124
|
+
-- after(ms, fn) -> timer | nil
|
|
125
|
+
local function after(ms, fn)
|
|
126
|
+
local xt = rawget(_G, 'xtimer')
|
|
127
|
+
if not (type(xt) == 'table' and xt.add and xt.inited) then return nil end
|
|
128
|
+
if not xt.inited() then
|
|
129
|
+
if not xt.init then return nil end
|
|
130
|
+
xt.init(16)
|
|
131
|
+
end
|
|
132
|
+
local ok, t = pcall(xt.add, ms, fn, 1)
|
|
133
|
+
return ok and t or nil
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
-- A proxy that accepts the TCP connection but never answers the handshake
|
|
137
|
+
-- (e.g. a SOCKS client pointed at an HTTP-only port) would otherwise stall the
|
|
138
|
+
-- request forever -- the streaming client has no overall timeout.
|
|
139
|
+
M.HANDSHAKE_TIMEOUT_MS = 15000
|
|
140
|
+
|
|
141
|
+
-- open_tunnel(proxy, host, port, cb[, opts]) -> tunnel
|
|
142
|
+
-- Connects to the proxy and asks it to reach host:port (SOCKS5 CONNECT, or
|
|
143
|
+
-- HTTP CONNECT when proxy.type == 'http'). Exactly one of these fires:
|
|
144
|
+
-- cb.on_ready(conn, extra) -- next tick after the handshake; `conn` is the
|
|
145
|
+
-- live proxy connection, `extra` any bytes the
|
|
146
|
+
-- proxy sent past its reply. Pass both to attach.
|
|
147
|
+
-- cb.on_error(msg)
|
|
148
|
+
-- opts.timeout_ms bounds the proxy connect + handshake (default
|
|
149
|
+
-- M.HANDSHAKE_TIMEOUT_MS; 0 disables).
|
|
150
|
+
-- tunnel.conn is the in-flight proxy connection (nil once handed off);
|
|
151
|
+
-- tunnel:close(reason) aborts silently (no callback).
|
|
152
|
+
-- tunnel:adopt(conn) hands the tunnel the connection attach() returned, so a
|
|
153
|
+
-- caller holding the tunnel as its request handle can still close() the live
|
|
154
|
+
-- stream (and ask is_closed()) after the TCP -> TLS upgrade.
|
|
155
|
+
function M.open_tunnel(proxy, host, port, cb, opts)
|
|
156
|
+
local tun = { done = false }
|
|
157
|
+
local buf, phase = '', (proxy.type == 'http') and 'connect' or 'greet'
|
|
158
|
+
local timer
|
|
159
|
+
|
|
160
|
+
local function stop_timer()
|
|
161
|
+
if timer then timer:del(); timer = nil end
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
local function fail(msg)
|
|
165
|
+
if tun.done then return end
|
|
166
|
+
tun.done = true
|
|
167
|
+
stop_timer()
|
|
168
|
+
local c = tun.conn
|
|
169
|
+
tun.conn = nil
|
|
170
|
+
if c and not c:is_closed() then c:close('proxy_error') end
|
|
171
|
+
if cb.on_error then cb.on_error(msg) end
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
function tun:close(reason)
|
|
175
|
+
local live = self.live
|
|
176
|
+
if live then
|
|
177
|
+
if not live:is_closed() then live:close(reason or 'cancelled') end
|
|
178
|
+
return
|
|
179
|
+
end
|
|
180
|
+
if self.done then return end
|
|
181
|
+
self.done = true
|
|
182
|
+
stop_timer()
|
|
183
|
+
local c = self.conn
|
|
184
|
+
self.conn = nil
|
|
185
|
+
if c and not c:is_closed() then c:close(reason or 'cancelled') end
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
function tun:is_closed()
|
|
189
|
+
if self.live then return self.live:is_closed() end
|
|
190
|
+
return self.done
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
function tun:adopt(conn)
|
|
194
|
+
self.live = conn
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
-- Defer the hand-off out of the channel callback (see header note).
|
|
198
|
+
local function schedule_ready(extra)
|
|
199
|
+
phase = 'done'
|
|
200
|
+
local t = after(0, function()
|
|
201
|
+
if tun.done then return end
|
|
202
|
+
local c = tun.conn
|
|
203
|
+
if not c or c:is_closed() then return fail('proxy tunnel lost') end
|
|
204
|
+
tun.done = true
|
|
205
|
+
stop_timer()
|
|
206
|
+
tun.conn = nil
|
|
207
|
+
cb.on_ready(c, extra or '')
|
|
208
|
+
end)
|
|
209
|
+
if not t then fail('proxy tunnel needs xtimer on this thread') end
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
local h = {}
|
|
213
|
+
|
|
214
|
+
function h.on_connect(conn)
|
|
215
|
+
tun.conn = conn
|
|
216
|
+
local ok, serr
|
|
217
|
+
if proxy.type == 'http' then
|
|
218
|
+
local target = host .. ':' .. port
|
|
219
|
+
local req = { 'CONNECT ' .. target .. ' HTTP/1.1\r\n', 'Host: ' .. target .. '\r\n' }
|
|
220
|
+
local auth = M.auth_header(proxy)
|
|
221
|
+
if auth then req[#req + 1] = 'Proxy-Authorization: ' .. auth .. '\r\n' end
|
|
222
|
+
req[#req + 1] = '\r\n'
|
|
223
|
+
ok, serr = conn:send_raw(table.concat(req))
|
|
224
|
+
else
|
|
225
|
+
ok, serr = conn:send_raw(socks5_greeting(proxy))
|
|
226
|
+
end
|
|
227
|
+
if not ok then fail('proxy handshake send: ' .. tostring(serr)) end
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
local function on_data(conn, data)
|
|
231
|
+
if tun.done or phase == 'done' then return #data end
|
|
232
|
+
buf = buf .. data
|
|
233
|
+
|
|
234
|
+
if proxy.type == 'http' then
|
|
235
|
+
local hdr_end = buf:find('\r\n\r\n', 1, true)
|
|
236
|
+
if not hdr_end then
|
|
237
|
+
if #buf > 64 * 1024 then fail('proxy CONNECT response too large') end
|
|
238
|
+
return #data
|
|
239
|
+
end
|
|
240
|
+
local status = buf:match('^HTTP/%d%.%d%s+(%d%d%d)')
|
|
241
|
+
if not status then fail('proxy CONNECT: malformed response'); return #data end
|
|
242
|
+
if status ~= '200' then fail('proxy CONNECT rejected: HTTP ' .. status); return #data end
|
|
243
|
+
schedule_ready(buf:sub(hdr_end + 4))
|
|
244
|
+
return #data
|
|
245
|
+
end
|
|
246
|
+
|
|
247
|
+
-- SOCKS5 state machine; loop because phases can complete back-to-back.
|
|
248
|
+
while not tun.done do
|
|
249
|
+
if phase == 'greet' then
|
|
250
|
+
if #buf < 2 then break end
|
|
251
|
+
if sbyte(buf, 1) ~= 0x05 then fail('socks5: bad version in method reply'); break end
|
|
252
|
+
local method = sbyte(buf, 2)
|
|
253
|
+
buf = buf:sub(3)
|
|
254
|
+
if method == 0x00 then
|
|
255
|
+
local req, e = socks5_connect_req(host, port)
|
|
256
|
+
if not req then fail('socks5: ' .. e); break end
|
|
257
|
+
conn:send_raw(req); phase = 'reply'
|
|
258
|
+
elseif method == 0x02 then
|
|
259
|
+
if not proxy.user then fail('socks5: proxy requires auth but no credentials given'); break end
|
|
260
|
+
local req, e = socks5_auth_req(proxy.user, proxy.pass)
|
|
261
|
+
if not req then fail('socks5: ' .. e); break end
|
|
262
|
+
conn:send_raw(req); phase = 'auth'
|
|
263
|
+
else
|
|
264
|
+
fail(string.format('socks5: no acceptable auth method (0x%02x)', method)); break
|
|
265
|
+
end
|
|
266
|
+
elseif phase == 'auth' then
|
|
267
|
+
if #buf < 2 then break end
|
|
268
|
+
local status = sbyte(buf, 2)
|
|
269
|
+
buf = buf:sub(3)
|
|
270
|
+
if status ~= 0x00 then fail('socks5: username/password auth rejected'); break end
|
|
271
|
+
local req, e = socks5_connect_req(host, port)
|
|
272
|
+
if not req then fail('socks5: ' .. e); break end
|
|
273
|
+
conn:send_raw(req); phase = 'reply'
|
|
274
|
+
elseif phase == 'reply' then
|
|
275
|
+
if #buf < 4 then break end
|
|
276
|
+
if sbyte(buf, 1) ~= 0x05 then fail('socks5: bad version in connect reply'); break end
|
|
277
|
+
local rep = sbyte(buf, 2)
|
|
278
|
+
if rep ~= 0x00 then
|
|
279
|
+
fail('socks5: connect rejected: ' .. (SOCKS5_REP[rep] or ('rep ' .. rep))); break
|
|
280
|
+
end
|
|
281
|
+
local atyp, total = sbyte(buf, 4), nil
|
|
282
|
+
if atyp == 0x01 then total = 10
|
|
283
|
+
elseif atyp == 0x04 then total = 22
|
|
284
|
+
elseif atyp == 0x03 then
|
|
285
|
+
if #buf < 5 then break end
|
|
286
|
+
total = 7 + sbyte(buf, 5)
|
|
287
|
+
else fail('socks5: unexpected ATYP ' .. tostring(atyp)); break end
|
|
288
|
+
if #buf < total then break end
|
|
289
|
+
schedule_ready(buf:sub(total + 1))
|
|
290
|
+
break
|
|
291
|
+
else
|
|
292
|
+
break
|
|
293
|
+
end
|
|
294
|
+
end
|
|
295
|
+
return #data
|
|
296
|
+
end
|
|
297
|
+
h.on_recv = on_data
|
|
298
|
+
h.on_packet = on_data
|
|
299
|
+
|
|
300
|
+
function h.on_close(_, reason)
|
|
301
|
+
fail('proxy closed before tunnel established (' .. tostring(reason) .. ')')
|
|
302
|
+
end
|
|
303
|
+
|
|
304
|
+
local timeout_ms = (opts and opts.timeout_ms) or M.HANDSHAKE_TIMEOUT_MS
|
|
305
|
+
if timeout_ms > 0 then
|
|
306
|
+
timer = after(timeout_ms, function()
|
|
307
|
+
timer = nil
|
|
308
|
+
fail(string.format('proxy handshake timed out after %dms (%s://%s:%d)',
|
|
309
|
+
timeout_ms, proxy.type, proxy.host, proxy.port))
|
|
310
|
+
end)
|
|
311
|
+
end
|
|
312
|
+
|
|
313
|
+
local conn, cerr = xnet.connect(proxy.host, proxy.port, h)
|
|
314
|
+
if not conn then
|
|
315
|
+
fail('proxy connect failed: ' .. tostring(cerr))
|
|
316
|
+
return tun
|
|
317
|
+
end
|
|
318
|
+
if not tun.done then tun.conn = tun.conn or conn end
|
|
319
|
+
return tun
|
|
320
|
+
end
|
|
321
|
+
|
|
322
|
+
-- attach(conn, extra, handler, opts) -> conn | nil, err
|
|
323
|
+
-- Turn a ready tunnel into the caller's connection. handler.on_connect fires
|
|
324
|
+
-- once the origin is reachable (after the TLS handshake for opts.tls), so the
|
|
325
|
+
-- caller's usual "send the request in on_connect" logic works unchanged.
|
|
326
|
+
-- opts = { tls = bool, host, port, verify, ca_file }
|
|
327
|
+
-- On error the tunnel connection is already closed.
|
|
328
|
+
function M.attach(conn, extra, handler, opts)
|
|
329
|
+
extra = extra or ''
|
|
330
|
+
if opts.tls then
|
|
331
|
+
if #extra > 0 then
|
|
332
|
+
-- Bytes after the proxy reply would corrupt the TLS record stream.
|
|
333
|
+
conn:close('proxy_error')
|
|
334
|
+
return nil, 'proxy sent unexpected data before TLS handshake'
|
|
335
|
+
end
|
|
336
|
+
if not xnet.connect_tls_fd then
|
|
337
|
+
conn:close('no_tls')
|
|
338
|
+
return nil, 'https not supported: xnet built without HTTPS'
|
|
339
|
+
end
|
|
340
|
+
local fd = conn:detach() -- surrender fd; raw channel freed
|
|
341
|
+
if not fd then return nil, 'proxy detach failed' end
|
|
342
|
+
local tls, err = xnet.connect_tls_fd(fd, handler, opts.host, opts.port, {
|
|
343
|
+
verify = opts.verify ~= false,
|
|
344
|
+
ca_file = opts.ca_file,
|
|
345
|
+
server_name = opts.host,
|
|
346
|
+
})
|
|
347
|
+
if not tls then return nil, 'tls upgrade failed: ' .. tostring(err) end
|
|
348
|
+
return tls
|
|
349
|
+
end
|
|
350
|
+
-- Plaintext origin: the raw connection IS the tunnel. Swap in the caller's
|
|
351
|
+
-- handler, replay the on_connect it missed, then any bytes already read.
|
|
352
|
+
conn:set_handler(handler)
|
|
353
|
+
if handler.on_connect then handler.on_connect(conn) end
|
|
354
|
+
local on_data = handler.on_recv or handler.on_packet
|
|
355
|
+
if #extra > 0 and on_data and not conn:is_closed() then on_data(conn, extra) end
|
|
356
|
+
return conn
|
|
357
|
+
end
|
|
358
|
+
|
|
359
|
+
return M
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
-- Public-key arithmetic/parser adapted from xnet2lua xrsa.lua; see XNET2LUA-LICENSE.
|
|
2
|
+
-- Strict RSASSA-PKCS1-v1_5 / SHA-256 verification only.
|
|
3
|
+
local xutils = require('xutils')
|
|
4
|
+
|
|
5
|
+
local M = {}
|
|
6
|
+
local floor, schar, sbyte, ssub = math.floor, string.char, string.byte, string.sub
|
|
7
|
+
-- 24-bit limbs keep multiplication exact in a Lua double.
|
|
8
|
+
local LIMB_BITS = 24
|
|
9
|
+
local BASE = 16777216 -- 2^24
|
|
10
|
+
local HLEN = 20 -- SHA-1 digest length; MySQL's OAEP uses SHA-1
|
|
11
|
+
|
|
12
|
+
-- ---------------------------------------------------------------------------
|
|
13
|
+
-- Bignum primitives
|
|
14
|
+
-- ---------------------------------------------------------------------------
|
|
15
|
+
|
|
16
|
+
-- Big-endian byte string -> limb array of exactly k limbs (k inferred if nil).
|
|
17
|
+
local function bn_from_bytes(s, k)
|
|
18
|
+
local n = #s
|
|
19
|
+
local limbs = {}
|
|
20
|
+
local i = n
|
|
21
|
+
local idx = 1
|
|
22
|
+
while i > 0 do
|
|
23
|
+
local b0 = sbyte(s, i) or 0
|
|
24
|
+
local b1 = (i - 1 >= 1) and sbyte(s, i - 1) or 0
|
|
25
|
+
local b2 = (i - 2 >= 1) and sbyte(s, i - 2) or 0
|
|
26
|
+
limbs[idx] = b0 + b1 * 256 + b2 * 65536
|
|
27
|
+
idx = idx + 1
|
|
28
|
+
i = i - 3
|
|
29
|
+
end
|
|
30
|
+
if #limbs == 0 then limbs[1] = 0 end
|
|
31
|
+
k = k or #limbs
|
|
32
|
+
for j = #limbs + 1, k do limbs[j] = 0 end
|
|
33
|
+
return limbs, k
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
-- Limb array -> big-endian byte string of exactly `len` bytes.
|
|
37
|
+
local function bn_to_bytes(a, k, len)
|
|
38
|
+
local bytes = {}
|
|
39
|
+
for i = 1, k do
|
|
40
|
+
local v = a[i]
|
|
41
|
+
local base = (i - 1) * 3
|
|
42
|
+
bytes[base + 1] = v % 256
|
|
43
|
+
bytes[base + 2] = floor(v / 256) % 256
|
|
44
|
+
bytes[base + 3] = floor(v / 65536) % 256
|
|
45
|
+
end
|
|
46
|
+
local out = {}
|
|
47
|
+
for i = len, 1, -1 do
|
|
48
|
+
out[#out + 1] = schar(bytes[i] or 0)
|
|
49
|
+
end
|
|
50
|
+
return table.concat(out)
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
local function bn_cmp(a, b, k)
|
|
54
|
+
for i = k, 1, -1 do
|
|
55
|
+
local av, bv = a[i] or 0, b[i] or 0
|
|
56
|
+
if av ~= bv then
|
|
57
|
+
if av > bv then return 1 end
|
|
58
|
+
return -1
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
return 0
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
-- a = a - b (requires a >= b when `borrow_in` is 0). Returns the final borrow,
|
|
65
|
+
-- which cancels an overflow limb the caller carried separately.
|
|
66
|
+
local function bn_sub(a, b, k)
|
|
67
|
+
local borrow = 0
|
|
68
|
+
for i = 1, k do
|
|
69
|
+
local v = a[i] - (b[i] or 0) - borrow
|
|
70
|
+
if v < 0 then
|
|
71
|
+
a[i] = v + BASE
|
|
72
|
+
borrow = 1
|
|
73
|
+
else
|
|
74
|
+
a[i] = v
|
|
75
|
+
borrow = 0
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
return borrow
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
-- x = 2x mod n, for x < n. n must have exactly k limbs.
|
|
82
|
+
local function bn_dbl_mod(x, n, k)
|
|
83
|
+
local carry = 0
|
|
84
|
+
for i = 1, k do
|
|
85
|
+
local v = x[i] * 2 + carry
|
|
86
|
+
if v >= BASE then
|
|
87
|
+
x[i] = v - BASE
|
|
88
|
+
carry = 1
|
|
89
|
+
else
|
|
90
|
+
x[i] = v
|
|
91
|
+
carry = 0
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
-- 2x < 2n, so at most one subtraction brings it back below n. When carry is
|
|
95
|
+
-- set the true value is 2^(24k) + x, which is always >= n.
|
|
96
|
+
if carry == 1 or bn_cmp(x, n, k) >= 0 then
|
|
97
|
+
bn_sub(x, n, k)
|
|
98
|
+
end
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
-- -n[1]^-1 mod 2^24, via Newton iteration on the low limb.
|
|
102
|
+
local function mont_n0inv(n0)
|
|
103
|
+
local inv = 1
|
|
104
|
+
for _ = 1, 5 do -- doubles the correct bit count each round: 2^32 > 2^24
|
|
105
|
+
inv = (inv * (2 - (n0 * inv) % BASE)) % BASE
|
|
106
|
+
end
|
|
107
|
+
return (BASE - inv) % BASE
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
-- Montgomery product: (a * b * R^-1) mod n, with R = 2^(24k). CIOS variant.
|
|
111
|
+
local function mont_mul(a, b, ctx)
|
|
112
|
+
local k, n, n0inv = ctx.k, ctx.n, ctx.n0inv
|
|
113
|
+
local t = ctx.scratch
|
|
114
|
+
for i = 1, k + 2 do t[i] = 0 end
|
|
115
|
+
|
|
116
|
+
for i = 1, k do
|
|
117
|
+
local bi = b[i]
|
|
118
|
+
local c = 0
|
|
119
|
+
if bi ~= 0 then
|
|
120
|
+
for j = 1, k do
|
|
121
|
+
local v = t[j] + a[j] * bi + c
|
|
122
|
+
c = floor(v / BASE)
|
|
123
|
+
t[j] = v - c * BASE
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
local v = t[k + 1] + c
|
|
127
|
+
c = floor(v / BASE)
|
|
128
|
+
t[k + 1] = v - c * BASE
|
|
129
|
+
t[k + 2] = t[k + 2] + c
|
|
130
|
+
|
|
131
|
+
local m = (t[1] * n0inv) % BASE
|
|
132
|
+
v = t[1] + m * n[1]
|
|
133
|
+
c = floor(v / BASE)
|
|
134
|
+
for j = 2, k do
|
|
135
|
+
v = t[j] + m * n[j] + c
|
|
136
|
+
c = floor(v / BASE)
|
|
137
|
+
t[j - 1] = v - c * BASE
|
|
138
|
+
end
|
|
139
|
+
v = t[k + 1] + c
|
|
140
|
+
c = floor(v / BASE)
|
|
141
|
+
t[k] = v - c * BASE
|
|
142
|
+
t[k + 1] = t[k + 2] + c
|
|
143
|
+
t[k + 2] = 0
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
local out = {}
|
|
147
|
+
for i = 1, k do out[i] = t[i] end
|
|
148
|
+
if t[k + 1] ~= 0 or bn_cmp(out, n, k) >= 0 then
|
|
149
|
+
bn_sub(out, n, k)
|
|
150
|
+
end
|
|
151
|
+
return out
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
local function mont_ctx(n_bytes)
|
|
155
|
+
local n, k = bn_from_bytes(n_bytes)
|
|
156
|
+
if n[1] % 2 == 0 then
|
|
157
|
+
return nil, 'rsa modulus must be odd'
|
|
158
|
+
end
|
|
159
|
+
local ctx = {
|
|
160
|
+
n = n,
|
|
161
|
+
k = k,
|
|
162
|
+
n0inv = mont_n0inv(n[1]),
|
|
163
|
+
scratch = {},
|
|
164
|
+
}
|
|
165
|
+
-- R^2 mod n by repeated doubling: 2 * 24k doublings from 1. Division-free,
|
|
166
|
+
-- and this runs once per connection, not once per multiply.
|
|
167
|
+
local rr = {}
|
|
168
|
+
for i = 1, k do rr[i] = 0 end
|
|
169
|
+
rr[1] = 1
|
|
170
|
+
for _ = 1, 2 * LIMB_BITS * k do
|
|
171
|
+
bn_dbl_mod(rr, n, k)
|
|
172
|
+
end
|
|
173
|
+
ctx.rr = rr
|
|
174
|
+
return ctx
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
-- m^e mod n, all arguments big-endian byte strings; result is `#n_bytes` long.
|
|
178
|
+
local function mod_exp(m_bytes, e_bytes, n_bytes)
|
|
179
|
+
local ctx, err = mont_ctx(n_bytes)
|
|
180
|
+
if not ctx then return nil, err end
|
|
181
|
+
local k = ctx.k
|
|
182
|
+
|
|
183
|
+
local base = bn_from_bytes(m_bytes, k)
|
|
184
|
+
if bn_cmp(base, ctx.n, k) >= 0 then
|
|
185
|
+
return nil, 'message representative out of range'
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
local one = {}
|
|
189
|
+
for i = 1, k do one[i] = 0 end
|
|
190
|
+
one[1] = 1
|
|
191
|
+
|
|
192
|
+
local base_m = mont_mul(base, ctx.rr, ctx) -- base * R mod n
|
|
193
|
+
local acc = mont_mul(one, ctx.rr, ctx) -- 1 * R mod n
|
|
194
|
+
|
|
195
|
+
-- Square-and-multiply over the bits of e, most significant first. e is the
|
|
196
|
+
-- server's public exponent, so its bit pattern is not a secret.
|
|
197
|
+
local started = false
|
|
198
|
+
for i = 1, #e_bytes do
|
|
199
|
+
local byte = sbyte(e_bytes, i)
|
|
200
|
+
for bit = 7, 0, -1 do
|
|
201
|
+
if started then
|
|
202
|
+
acc = mont_mul(acc, acc, ctx)
|
|
203
|
+
end
|
|
204
|
+
if floor(byte / (2 ^ bit)) % 2 == 1 then
|
|
205
|
+
if started then
|
|
206
|
+
acc = mont_mul(acc, base_m, ctx)
|
|
207
|
+
else
|
|
208
|
+
acc = base_m
|
|
209
|
+
started = true
|
|
210
|
+
end
|
|
211
|
+
end
|
|
212
|
+
end
|
|
213
|
+
end
|
|
214
|
+
if not started then
|
|
215
|
+
return nil, 'rsa exponent is zero'
|
|
216
|
+
end
|
|
217
|
+
|
|
218
|
+
local result = mont_mul(acc, one, ctx) -- out of Montgomery domain
|
|
219
|
+
return bn_to_bytes(result, k, #n_bytes)
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
-- ---------------------------------------------------------------------------
|
|
223
|
+
-- DER / PEM public key parsing
|
|
224
|
+
-- ---------------------------------------------------------------------------
|
|
225
|
+
|
|
226
|
+
-- Reads one ASN.1 TLV at `pos`. Returns tag, contents, next position.
|
|
227
|
+
local function der_read(der, pos)
|
|
228
|
+
local tag = sbyte(der, pos)
|
|
229
|
+
if not tag then return nil, nil, nil, 'truncated DER' end
|
|
230
|
+
pos = pos + 1
|
|
231
|
+
local len = sbyte(der, pos)
|
|
232
|
+
if not len then return nil, nil, nil, 'truncated DER length' end
|
|
233
|
+
pos = pos + 1
|
|
234
|
+
if len >= 128 then
|
|
235
|
+
local count = len - 128
|
|
236
|
+
if count == 0 or count > 4 then return nil, nil, nil, 'bad DER length' end
|
|
237
|
+
len = 0
|
|
238
|
+
for _ = 1, count do
|
|
239
|
+
local b = sbyte(der, pos)
|
|
240
|
+
if not b then return nil, nil, nil, 'truncated DER length' end
|
|
241
|
+
len = len * 256 + b
|
|
242
|
+
pos = pos + 1
|
|
243
|
+
end
|
|
244
|
+
end
|
|
245
|
+
local contents = ssub(der, pos, pos + len - 1)
|
|
246
|
+
if #contents ~= len then return nil, nil, nil, 'truncated DER contents' end
|
|
247
|
+
return tag, contents, pos + len
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
local function der_uint(s)
|
|
251
|
+
-- ASN.1 INTEGERs are signed, so a leading 0x00 guards the sign bit.
|
|
252
|
+
local i = 1
|
|
253
|
+
while i < #s and sbyte(s, i) == 0 do i = i + 1 end
|
|
254
|
+
return ssub(s, i)
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
-- Accepts both "BEGIN PUBLIC KEY" (SubjectPublicKeyInfo, what MySQL sends) and
|
|
258
|
+
-- "BEGIN RSA PUBLIC KEY" (bare PKCS#1). Returns n, e as byte strings.
|
|
259
|
+
function M.parse_public_key(pem)
|
|
260
|
+
if type(pem) ~= 'string' or pem == '' then
|
|
261
|
+
return nil, nil, 'empty public key'
|
|
262
|
+
end
|
|
263
|
+
local body = pem:gsub('%-%-%-%-%-[^%-]*%-%-%-%-%-', ''):gsub('%s', '')
|
|
264
|
+
if body == '' then return nil, nil, 'no base64 body in PEM' end
|
|
265
|
+
local der = xutils.base64_decode(body)
|
|
266
|
+
if not der or der == '' then return nil, nil, 'base64 decode failed' end
|
|
267
|
+
|
|
268
|
+
local tag, contents, _, err = der_read(der, 1)
|
|
269
|
+
if not tag then return nil, nil, err end
|
|
270
|
+
if tag ~= 0x30 then return nil, nil, 'expected DER SEQUENCE' end
|
|
271
|
+
|
|
272
|
+
local inner = contents
|
|
273
|
+
local first_tag, first_contents, next_pos = der_read(inner, 1)
|
|
274
|
+
if not first_tag then return nil, nil, 'malformed public key' end
|
|
275
|
+
|
|
276
|
+
if first_tag == 0x30 then
|
|
277
|
+
-- SubjectPublicKeyInfo: skip AlgorithmIdentifier, unwrap the BIT STRING.
|
|
278
|
+
local bit_tag, bit_contents = der_read(inner, next_pos)
|
|
279
|
+
if bit_tag ~= 0x03 then return nil, nil, 'expected DER BIT STRING' end
|
|
280
|
+
if sbyte(bit_contents, 1) ~= 0 then return nil, nil, 'unexpected BIT STRING padding' end
|
|
281
|
+
local seq_tag, seq_contents = der_read(ssub(bit_contents, 2), 1)
|
|
282
|
+
if seq_tag ~= 0x30 then return nil, nil, 'expected RSAPublicKey SEQUENCE' end
|
|
283
|
+
inner = seq_contents
|
|
284
|
+
first_tag, first_contents, next_pos = der_read(inner, 1)
|
|
285
|
+
end
|
|
286
|
+
|
|
287
|
+
if first_tag ~= 0x02 then return nil, nil, 'expected modulus INTEGER' end
|
|
288
|
+
local e_tag, e_contents = der_read(inner, next_pos)
|
|
289
|
+
if e_tag ~= 0x02 then return nil, nil, 'expected exponent INTEGER' end
|
|
290
|
+
|
|
291
|
+
local n = der_uint(first_contents)
|
|
292
|
+
local e = der_uint(e_contents)
|
|
293
|
+
if #n < 64 then return nil, nil, 'rsa modulus too small' end
|
|
294
|
+
return n, e
|
|
295
|
+
end
|
|
296
|
+
|
|
297
|
+
-- ---------------------------------------------------------------------------
|
|
298
|
+
|
|
299
|
+
function M.verify(pem, message, signature)
|
|
300
|
+
local n, e, err = M.parse_public_key(pem)
|
|
301
|
+
if not n then return false, err end
|
|
302
|
+
if #n < 256 or #n > 512 or e ~= '\1\0\1' then return false, 'RSA 2048-4096 / exponent 65537 required' end
|
|
303
|
+
if type(signature) ~= 'string' or #signature ~= #n then return false, 'invalid signature length' end
|
|
304
|
+
local encoded = mod_exp(signature, e, n)
|
|
305
|
+
if not encoded then return false, 'invalid signature' end
|
|
306
|
+
local prefix = xutils.hex_decode('3031300d060960864801650304020105000420')
|
|
307
|
+
local digest = prefix .. xutils.sha256(message)
|
|
308
|
+
local expected = '\0\1' .. string.rep('\255', #n - #digest - 3) .. '\0' .. digest
|
|
309
|
+
return encoded == expected, encoded == expected and nil or 'signature mismatch'
|
|
310
|
+
end
|
|
311
|
+
return M
|