You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lua_aws.lua 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. --[[
  2. Copyright (c) 2022, Vsevolod Stakhov <vsevolod@rspamd.com>
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ]]--
  13. --[[[
  14. -- @module lua_aws
  15. -- This module contains Amazon AWS utility functions
  16. --]]
  17. local N = "aws"
  18. --local rspamd_logger = require "rspamd_logger"
  19. local ts = (require "tableshape").types
  20. local lua_util = require "lua_util"
  21. local fun = require "fun"
  22. local rspamd_crypto_hash = require "rspamd_cryptobox_hash"
  23. local exports = {}
  24. -- Returns a canonical representation of today date
  25. local function today_canonical()
  26. return os.date('!%Y%m%d')
  27. end
  28. --[[[
  29. -- @function lua_aws.aws_date([date_str])
  30. -- Returns an aws date header corresponding to the specific date
  31. --]]
  32. local function aws_date(date_str)
  33. if not date_str then
  34. date_str = today_canonical()
  35. end
  36. return date_str .. os.date('!T%H%M%SZ')
  37. end
  38. exports.aws_date = aws_date
  39. -- Local cache of the keys to save resources
  40. local cached_keys = {}
  41. local function maybe_get_cached_key(date_str, secret_key, region, service, req_type)
  42. local bucket = cached_keys[tonumber(date_str)]
  43. if not bucket then
  44. return nil
  45. end
  46. local elt = bucket[string.format('%s.%s.%s.%s', secret_key, region, service, req_type)]
  47. if elt then
  48. return elt
  49. end
  50. end
  51. local function save_cached_key(date_str, secret_key, region, service, req_type, key)
  52. local numdate = tonumber(date_str)
  53. -- expire old buckets
  54. for k, _ in pairs(cached_keys) do
  55. if k < numdate then
  56. cached_keys[k] = nil
  57. end
  58. end
  59. local bucket = cached_keys[tonumber(date_str)]
  60. local idx = string.format('%s.%s.%s.%s', secret_key, region, service, req_type)
  61. if not bucket then
  62. cached_keys[tonumber(date_str)] = {
  63. idx = key
  64. }
  65. else
  66. bucket[idx] = key
  67. end
  68. end
  69. --[[[
  70. -- @function lua_aws.aws_signing_key([date_str], secret_key, region, [service='s3'], [req_type='aws4_request'])
  71. -- Returns a signing key for the specific parameters
  72. --]]
  73. local function aws_signing_key(date_str, secret_key, region, service, req_type)
  74. if not date_str then
  75. date_str = today_canonical()
  76. end
  77. if not service then
  78. service = 's3'
  79. end
  80. if not req_type then
  81. req_type = 'aws4_request'
  82. end
  83. assert(type(secret_key) == 'string')
  84. assert(type(region) == 'string')
  85. local maybe_cached = maybe_get_cached_key(date_str, secret_key, region, service, req_type)
  86. if maybe_cached then
  87. return maybe_cached
  88. end
  89. local hmac1 = rspamd_crypto_hash.create_specific_keyed("AWS4" .. secret_key, "sha256", date_str):bin()
  90. local hmac2 = rspamd_crypto_hash.create_specific_keyed(hmac1, "sha256", region):bin()
  91. local hmac3 = rspamd_crypto_hash.create_specific_keyed(hmac2, "sha256", service):bin()
  92. local final_key = rspamd_crypto_hash.create_specific_keyed(hmac3, "sha256", req_type):bin()
  93. save_cached_key(date_str, secret_key, region, service, req_type, final_key)
  94. return final_key
  95. end
  96. exports.aws_signing_key = aws_signing_key
  97. --[[[
  98. -- @function lua_aws.aws_canon_request_hash(method, path, headers_to_sign, hex_hash)
  99. -- Returns a hash + list of headers as required to produce signature afterwards
  100. --]]
  101. local function aws_canon_request_hash(method, uri, headers_to_sign, hex_hash)
  102. assert(type(method) == 'string')
  103. assert(type(uri) == 'string')
  104. assert(type(headers_to_sign) == 'table')
  105. if not hex_hash then
  106. hex_hash = headers_to_sign['x-amz-content-sha256']
  107. end
  108. assert(type(hex_hash) == 'string')
  109. local sha_ctx = rspamd_crypto_hash.create_specific('sha256')
  110. lua_util.debugm(N, 'update signature with the method %s',
  111. method)
  112. sha_ctx:update(method .. '\n')
  113. lua_util.debugm(N, 'update signature with the uri %s',
  114. uri)
  115. sha_ctx:update(uri .. '\n')
  116. -- XXX add query string canonicalisation
  117. sha_ctx:update('\n')
  118. -- Sort auth headers and canonicalise them as requested
  119. local hdr_canon = fun.tomap(fun.map(function(k, v)
  120. return k:lower(), lua_util.str_trim(v)
  121. end, headers_to_sign))
  122. local header_names = lua_util.keys(hdr_canon)
  123. table.sort(header_names)
  124. for _, hn in ipairs(header_names) do
  125. local v = hdr_canon[hn]
  126. lua_util.debugm(N, 'update signature with the header %s, %s',
  127. hn, v)
  128. sha_ctx:update(string.format('%s:%s\n', hn, v))
  129. end
  130. local hdrs_list = table.concat(header_names, ';')
  131. lua_util.debugm(N, 'headers list to sign: %s', hdrs_list)
  132. sha_ctx:update(string.format('\n%s\n%s', hdrs_list, hex_hash))
  133. return sha_ctx:hex(), hdrs_list
  134. end
  135. exports.aws_canon_request_hash = aws_canon_request_hash
  136. local aws_authorization_hdr_args_schema = ts.shape {
  137. date = ts.string + ts['nil'] / today_canonical,
  138. secret_key = ts.string,
  139. method = ts.string + ts['nil'] / function()
  140. return 'GET'
  141. end,
  142. uri = ts.string,
  143. region = ts.string,
  144. service = ts.string + ts['nil'] / function()
  145. return 's3'
  146. end,
  147. req_type = ts.string + ts['nil'] / function()
  148. return 'aws4_request'
  149. end,
  150. headers = ts.map_of(ts.string, ts.string),
  151. key_id = ts.string,
  152. }
  153. --[[[
  154. -- @function lua_aws.aws_authorization_hdr(params)
  155. -- Produces an authorization header as required by AWS
  156. -- Parameters schema is the following:
  157. ts.shape{
  158. date = ts.string + ts['nil'] / today_canonical,
  159. secret_key = ts.string,
  160. method = ts.string + ts['nil'] / function() return 'GET' end,
  161. uri = ts.string,
  162. region = ts.string,
  163. service = ts.string + ts['nil'] / function() return 's3' end,
  164. req_type = ts.string + ts['nil'] / function() return 'aws4_request' end,
  165. headers = ts.map_of(ts.string, ts.string),
  166. key_id = ts.string,
  167. }
  168. --
  169. --]]
  170. local function aws_authorization_hdr(tbl, transformed)
  171. local res, err
  172. if not transformed then
  173. res, err = aws_authorization_hdr_args_schema:transform(tbl)
  174. assert(res, err)
  175. else
  176. res = tbl
  177. end
  178. local signing_key = aws_signing_key(res.date, res.secret_key, res.region, res.service,
  179. res.req_type)
  180. assert(signing_key ~= nil)
  181. local signed_sha, signed_hdrs = aws_canon_request_hash(res.method, res.uri,
  182. res.headers)
  183. if not signed_sha then
  184. return nil
  185. end
  186. local string_to_sign = string.format('AWS4-HMAC-SHA256\n%s\n%s/%s/%s/%s\n%s',
  187. res.headers['x-amz-date'] or aws_date(),
  188. res.date, res.region, res.service, res.req_type,
  189. signed_sha)
  190. lua_util.debugm(N, "string to sign: %s", string_to_sign)
  191. local hmac = rspamd_crypto_hash.create_specific_keyed(signing_key, 'sha256', string_to_sign):hex()
  192. lua_util.debugm(N, "hmac: %s", hmac)
  193. local auth_hdr = string.format('AWS4-HMAC-SHA256 Credential=%s/%s/%s/%s/%s,' ..
  194. 'SignedHeaders=%s,Signature=%s',
  195. res.key_id, res.date, res.region, res.service, res.req_type,
  196. signed_hdrs, hmac)
  197. return auth_hdr
  198. end
  199. exports.aws_authorization_hdr = aws_authorization_hdr
  200. --[[[
  201. -- @function lua_aws.aws_request_enrich(params, content)
  202. -- Produces an authorization header as required by AWS
  203. -- Parameters schema is the following:
  204. ts.shape{
  205. date = ts.string + ts['nil'] / today_canonical,
  206. secret_key = ts.string,
  207. method = ts.string + ts['nil'] / function() return 'GET' end,
  208. uri = ts.string,
  209. region = ts.string,
  210. service = ts.string + ts['nil'] / function() return 's3' end,
  211. req_type = ts.string + ts['nil'] / function() return 'aws4_request' end,
  212. headers = ts.map_of(ts.string, ts.string),
  213. key_id = ts.string,
  214. }
  215. This method returns new/modified in place table of the headers
  216. --
  217. --]]
  218. local function aws_request_enrich(tbl, content)
  219. local res, err = aws_authorization_hdr_args_schema:transform(tbl)
  220. assert(res, err)
  221. local content_sha256 = rspamd_crypto_hash.create_specific('sha256', content):hex()
  222. local hdrs = res.headers
  223. hdrs['x-amz-content-sha256'] = content_sha256
  224. if not hdrs['x-amz-date'] then
  225. hdrs['x-amz-date'] = aws_date(res.date)
  226. end
  227. hdrs['Authorization'] = aws_authorization_hdr(res, true)
  228. return hdrs
  229. end
  230. exports.aws_request_enrich = aws_request_enrich
  231. -- A simple tests according to AWS docs to check sanity
  232. local test_request_hdrs = {
  233. ['Host'] = 'examplebucket.s3.amazonaws.com',
  234. ['x-amz-date'] = '20130524T000000Z',
  235. ['Range'] = 'bytes=0-9',
  236. ['x-amz-content-sha256'] = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
  237. }
  238. assert(aws_canon_request_hash('GET', '/test.txt', test_request_hdrs) ==
  239. '7344ae5b7ee6c3e7e6b0fe0640412a37625d1fbfff95c48bbb2dc43964946972')
  240. assert(aws_authorization_hdr {
  241. date = '20130524',
  242. region = 'us-east-1',
  243. headers = test_request_hdrs,
  244. uri = '/test.txt',
  245. key_id = 'AKIAIOSFODNN7EXAMPLE',
  246. secret_key = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
  247. } == 'AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,' ..
  248. 'SignedHeaders=host;range;x-amz-content-sha256;x-amz-date,' ..
  249. 'Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41')
  250. return exports