Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

util.lib.lua 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. -- Token authentication
  2. -- Copyright (C) 2015 Atlassian
  3. local basexx = require "basexx";
  4. local have_async, async = pcall(require, "util.async");
  5. local hex = require "util.hex";
  6. local jwt = require "luajwtjitsi";
  7. local http = require "net.http";
  8. local jid = require "util.jid";
  9. local json = require "cjson";
  10. local path = require "util.paths";
  11. local sha256 = require "util.hashes".sha256;
  12. local timer = require "util.timer";
  13. local http_timeout = 30;
  14. local http_headers = {
  15. ["User-Agent"] = "Prosody ("..prosody.version.."; "..prosody.platform..")"
  16. };
  17. -- TODO: Figure out a less arbitrary default cache size.
  18. local cacheSize = module:get_option_number("jwt_pubkey_cache_size", 128);
  19. local cache = require"util.cache".new(cacheSize);
  20. local Util = {}
  21. Util.__index = Util
  22. --- Constructs util class for token verifications.
  23. -- Constructor that uses the passed module to extract all the
  24. -- needed configurations.
  25. -- If confuguration is missing returns nil
  26. -- @param module the module in which options to check for configs.
  27. -- @return the new instance or nil
  28. function Util.new(module)
  29. local self = setmetatable({}, Util)
  30. self.appId = module:get_option_string("app_id");
  31. self.appSecret = module:get_option_string("app_secret");
  32. self.asapKeyServer = module:get_option_string("asap_key_server");
  33. self.allowEmptyToken = module:get_option_boolean("allow_empty_token");
  34. --[[
  35. Multidomain can be supported in some deployments. In these deployments
  36. there is a virtual conference muc, which address contains the subdomain
  37. to use. Those deployments are accessible
  38. by URL https://domain/subdomain.
  39. Then the address of the room will be:
  40. roomName@conference.subdomain.domain. This is like a virtual address
  41. where there is only one muc configured by default with address:
  42. conference.domain and the actual presentation of the room in that muc
  43. component is [subdomain]roomName@conference.domain.
  44. These setups relay on configuration 'muc_domain_base' which holds
  45. the main domain and we use it to substract subdomains from the
  46. virtual addresses.
  47. The following confgurations are for multidomain setups and domain name
  48. verification:
  49. --]]
  50. -- optional parameter for custom muc component prefix,
  51. -- defaults to "conference"
  52. self.muc_domain_prefix = module:get_option_string(
  53. "muc_mapper_domain_prefix", "conference");
  54. -- domain base, which is the main domain used in the deployment,
  55. -- the main VirtualHost for the deployment
  56. self.muc_domain_base = module:get_option_string("muc_mapper_domain_base");
  57. -- The "real" MUC domain that we are proxying to
  58. if self.muc_domain_base then
  59. self.muc_domain = module:get_option_string(
  60. "muc_mapper_domain",
  61. self.muc_domain_prefix.."."..self.muc_domain_base);
  62. end
  63. -- whether domain name verification is enabled, by default it is disabled
  64. self.enableDomainVerification = module:get_option_boolean(
  65. "enable_domain_verification", false);
  66. if self.allowEmptyToken == true then
  67. module:log("warn", "WARNING - empty tokens allowed");
  68. end
  69. if self.appId == nil then
  70. module:log("error", "'app_id' must not be empty");
  71. return nil;
  72. end
  73. if self.appSecret == nil and self.asapKeyServer == nil then
  74. module:log("error", "'app_secret' or 'asap_key_server' must be specified");
  75. return nil;
  76. end
  77. --array of accepted issuers: by default only includes our appId
  78. self.acceptedIssuers = module:get_option_array('asap_accepted_issuers',{self.appId})
  79. --array of accepted audiences: by default only includes our appId
  80. self.acceptedAudiences = module:get_option_array('asap_accepted_audiences',{'*'})
  81. if self.asapKeyServer and not have_async then
  82. module:log("error", "requires a version of Prosody with util.async");
  83. return nil;
  84. end
  85. return self
  86. end
  87. --- Returns the public key by keyID
  88. -- @param keyId the key ID to request
  89. -- @return the public key (the content of requested resource) or nil
  90. function Util:get_public_key(keyId,asapKeyServer)
  91. if asapKeyServer == "" then
  92. asapKeyServer = self.asapKeyServer)
  93. end
  94. local content = cache:get(keyId);
  95. if content == nil then
  96. -- If the key is not found in the cache.
  97. module:log("debug", "Cache miss for key: "..keyId);
  98. local code;
  99. local wait, done = async.waiter();
  100. local function cb(content_, code_, response_, request_)
  101. content, code = content_, code_;
  102. if code == 200 or code == 204 then
  103. cache:set(keyId, content);
  104. end
  105. done();
  106. end
  107. local keyurl = path.join(asapKeyServer, hex.to(sha256(keyId))..'.pem');
  108. module:log("debug", "Fetching public key from: "..keyurl);
  109. -- We hash the key ID to work around some legacy behavior and make
  110. -- deployment easier. It also helps prevent directory
  111. -- traversal attacks (although path cleaning could have done this too).
  112. local request = http.request(keyurl, {
  113. headers = http_headers or {},
  114. method = "GET"
  115. }, cb);
  116. -- TODO: Is the done() call racey? Can we cancel this if the request
  117. -- succeedes?
  118. local function cancel()
  119. -- TODO: This check is racey. Not likely to be a problem, but we should
  120. -- still stick a mutex on content / code at some point.
  121. if code == nil then
  122. http.destroy_request(request);
  123. done();
  124. end
  125. end
  126. timer.add_task(http_timeout, cancel);
  127. wait();
  128. if code == 200 or code == 204 then
  129. return content;
  130. end
  131. else
  132. -- If the key is in the cache, use it.
  133. module:log("debug", "Cache hit for key: "..keyId);
  134. return content;
  135. end
  136. return nil;
  137. end
  138. --- Verifies issuer part of token
  139. -- @param 'iss' claim from the token to verify
  140. -- @return nil and error string or true for accepted claim
  141. function Util:verify_issuer(issClaim)
  142. for i, iss in ipairs(self.acceptedIssuers) do
  143. if issClaim == iss then
  144. --claim matches an accepted issuer so return success
  145. return true;
  146. end
  147. end
  148. --if issClaim not found in acceptedIssuers, fail claim
  149. return nil, "Invalid issuer ('iss' claim)";
  150. end
  151. --- Verifies audience part of token
  152. -- @param 'aud' claim from the token to verify
  153. -- @return nil and error string or true for accepted claim
  154. function Util:verify_audience(audClaim)
  155. for i, aud in ipairs(self.acceptedAudiences) do
  156. if aud == '*' then
  157. --* indicates to accept any audience in the claims so return success
  158. return true;
  159. end
  160. if audClaim == aud then
  161. --claim matches an accepted audience so return success
  162. return true;
  163. end
  164. end
  165. --if issClaim not found in acceptedIssuers, fail claim
  166. return nil, "Invalid audience ('aud' claim)";
  167. end
  168. --- Verifies token
  169. -- @param token the token to verify
  170. -- @param secret the secret to use to verify token
  171. -- @return nil and error or the extracted claims from the token
  172. function Util:verify_token(token, secret)
  173. local claims, err = jwt.decode(token, secret, true);
  174. if claims == nil then
  175. return nil, err;
  176. end
  177. local alg = claims["alg"];
  178. if alg ~= nil and (alg == "none" or alg == "") then
  179. return nil, "'alg' claim must not be empty";
  180. end
  181. local issClaim = claims["iss"];
  182. if issClaim == nil then
  183. return nil, "'iss' claim is missing";
  184. end
  185. --check the issuer against the accepted list
  186. local issCheck, issCheckErr = self:verify_issuer(issClaim);
  187. if issCheck == nil then
  188. return nil, issCheckErr;
  189. end
  190. local roomClaim = claims["room"];
  191. if roomClaim == nil then
  192. return nil, "'room' claim is missing";
  193. end
  194. local audClaim = claims["aud"];
  195. if audClaim == nil then
  196. return nil, "'aud' claim is missing";
  197. end
  198. --check the audience against the accepted list
  199. local audCheck, audCheckErr = self:verify_audience(audClaim);
  200. if audCheck == nil then
  201. return nil, audCheckErr;
  202. end
  203. return claims;
  204. end
  205. --- Verifies token and process needed values to be stored in the session.
  206. -- Token is obtained from session.auth_token.
  207. -- Stores in session the following values:
  208. -- session.jitsi_meet_room - the room name value from the token
  209. -- session.jitsi_meet_domain - the domain name value from the token
  210. -- session.jitsi_meet_context_user - the user details from the token
  211. -- session.jitsi_meet_context_group - the group value from the token
  212. -- session.jitsi_meet_context_features - the features value from the token
  213. -- @param session the current session
  214. -- @return false and error
  215. function Util:process_and_verify_token(session)
  216. return self:process_and_verify_token_with_keyserver(session,"")
  217. end
  218. function Util:process_and_verify_token_with_keyserver(session,asapKeyServer)
  219. if asapKeyServer == "" then
  220. asapKeyServer = self.asapKeyServer
  221. end
  222. if session.auth_token == nil then
  223. if self.allowEmptyToken then
  224. return true;
  225. else
  226. return false, "not-allowed", "token required";
  227. end
  228. end
  229. local pubKey;
  230. if asapKeyServer and session.auth_token ~= nil then
  231. local dotFirst = session.auth_token:find("%.");
  232. if not dotFirst then return nil, "Invalid token" end
  233. local header = json.decode(basexx.from_url64(session.auth_token:sub(1,dotFirst-1)));
  234. local kid = header["kid"];
  235. if kid == nil then
  236. return false, "not-allowed", "'kid' claim is missing";
  237. end
  238. pubKey = self:get_public_key(kid,asapKeyServer);
  239. if pubKey == nil then
  240. return false, "not-allowed", "could not obtain public key";
  241. end
  242. end
  243. -- now verify the whole token
  244. local claims, msg;
  245. if asapKeyServer then
  246. claims, msg = self:verify_token(session.auth_token, pubKey);
  247. else
  248. claims, msg = self:verify_token(session.auth_token, self.appSecret);
  249. end
  250. if claims ~= nil then
  251. -- Binds room name to the session which is later checked on MUC join
  252. session.jitsi_meet_room = claims["room"];
  253. -- Binds domain name to the session
  254. session.jitsi_meet_domain = claims["sub"];
  255. -- Binds the user details to the session if available
  256. if claims["context"] ~= nil then
  257. if claims["context"]["user"] ~= nil then
  258. session.jitsi_meet_context_user = claims["context"]["user"];
  259. end
  260. if claims["context"]["group"] ~= nil then
  261. -- Binds any group details to the session
  262. session.jitsi_meet_context_group = claims["context"]["group"];
  263. end
  264. if claims["context"]["features"] ~= nil then
  265. -- Binds any features details to the session
  266. session.jitsi_meet_context_features = claims["context"]["features"];
  267. end
  268. end
  269. return true;
  270. else
  271. return false, "not-allowed", msg;
  272. end
  273. end
  274. --- Verifies room name and domain if necesarry.
  275. -- Checks configs and if necessary checks the room name extracted from
  276. -- room_address against the one saved in the session when token was verified.
  277. -- Also verifies domain name from token against the domain in the room_address,
  278. -- if enableDomainVerification is enabled.
  279. -- @param session the current session
  280. -- @param room_address the whole room address as received
  281. -- @return returns true in case room was verified or there is no need to verify
  282. -- it and returns false in case verification was processed
  283. -- and was not successful
  284. function Util:verify_room(session, room_address)
  285. if self.allowEmptyToken and session.auth_token == nil then
  286. module:log(
  287. "debug",
  288. "Skipped room token verification - empty tokens are allowed");
  289. return true;
  290. end
  291. -- extract room name using all chars, except the not allowed ones
  292. local room,_,_ = jid.split(room_address);
  293. if room == nil then
  294. log("error",
  295. "Unable to get name of the MUC room ? to: %s", room_address);
  296. return true;
  297. end
  298. local auth_room = session.jitsi_meet_room;
  299. if not self.enableDomainVerification then
  300. -- if auth_room is missing, this means user is anonymous (no token for
  301. -- its domain) we let it through, jicofo is verifying creation domain
  302. if auth_room and room ~= string.lower(auth_room) and auth_room ~= '*' then
  303. return false;
  304. end
  305. return true;
  306. end
  307. local room_address_to_verify = jid.bare(room_address);
  308. local room_node = jid.node(room_address);
  309. -- parses bare room address, for multidomain expected format is:
  310. -- [subdomain]roomName@conference.domain
  311. local target_subdomain, target_room = room_node:match("^%[([^%]]+)%](.+)$");
  312. -- if we have '*' as room name in token, this means all rooms are allowed
  313. -- so we will use the actual name of the room when constructing strings
  314. -- to verify subdomains and domains to simplify checks
  315. local room_to_check;
  316. if auth_room == '*' then
  317. -- authorized for accessing any room assign to room_to_check the actual
  318. -- room name
  319. if target_room ~= nil then
  320. -- we are in multidomain mode and we were able to extract room name
  321. room_to_check = target_room;
  322. else
  323. -- no target_room, room_address_to_verify does not contain subdomain
  324. -- so we get just the node which is the room name
  325. room_to_check = room_node;
  326. end
  327. else
  328. -- no wildcard, so check room against authorized room in token
  329. room_to_check = auth_room;
  330. end
  331. local auth_domain = session.jitsi_meet_domain;
  332. local subdomain_to_check;
  333. if target_subdomain then
  334. if auth_domain == '*' then
  335. -- check for wildcard in JWT claim, allow access if found
  336. subdomain_to_check = target_subdomain;
  337. else
  338. -- no wildcard in JWT claim, so check subdomain against sub in token
  339. subdomain_to_check = auth_domain;
  340. end
  341. -- from this point we depend on muc_domain_base,
  342. -- deny access if option is missing
  343. if not self.muc_domain_base then
  344. module:log("warn", "No 'muc_domain_base' option set, denying access!");
  345. return false;
  346. end
  347. return room_address_to_verify == jid.join(
  348. "["..string.lower(subdomain_to_check).."]"..string.lower(room_to_check), self.muc_domain);
  349. else
  350. if auth_domain == '*' then
  351. -- check for wildcard in JWT claim, allow access if found
  352. subdomain_to_check = self.muc_domain;
  353. else
  354. -- no wildcard in JWT claim, so check subdomain against sub in token
  355. subdomain_to_check = self.muc_domain_prefix.."."..auth_domain;
  356. end
  357. -- we do not have a domain part (multidomain is not enabled)
  358. -- verify with info from the token
  359. return room_address_to_verify == jid.join(
  360. string.lower(room_to_check), string.lower(subdomain_to_check));
  361. end
  362. end
  363. return Util;