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.

util.lib.lua 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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_safe = require "cjson.safe";
  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. self.requireRoomClaim = module:get_option_boolean('asap_require_room_claim', true);
  82. if self.asapKeyServer and not have_async then
  83. module:log("error", "requires a version of Prosody with util.async");
  84. return nil;
  85. end
  86. return self
  87. end
  88. function Util:set_asap_key_server(asapKeyServer)
  89. self.asapKeyServer = asapKeyServer;
  90. end
  91. function Util:set_asap_accepted_issuers(acceptedIssuers)
  92. self.acceptedIssuers = acceptedIssuers;
  93. end
  94. function Util:set_asap_accepted_audiences(acceptedAudiences)
  95. self.acceptedAudiences = acceptedAudiences;
  96. end
  97. function Util:set_asap_require_room_claim(checkRoom)
  98. self.requireRoomClaim = checkRoom;
  99. end
  100. --- Returns the public key by keyID
  101. -- @param keyId the key ID to request
  102. -- @return the public key (the content of requested resource) or nil
  103. function Util:get_public_key(keyId)
  104. local content = cache:get(keyId);
  105. if content == nil then
  106. -- If the key is not found in the cache.
  107. module:log("debug", "Cache miss for key: "..keyId);
  108. local code;
  109. local wait, done = async.waiter();
  110. local function cb(content_, code_, response_, request_)
  111. content, code = content_, code_;
  112. if code == 200 or code == 204 then
  113. cache:set(keyId, content);
  114. end
  115. done();
  116. end
  117. local keyurl = path.join(self.asapKeyServer, hex.to(sha256(keyId))..'.pem');
  118. module:log("debug", "Fetching public key from: "..keyurl);
  119. -- We hash the key ID to work around some legacy behavior and make
  120. -- deployment easier. It also helps prevent directory
  121. -- traversal attacks (although path cleaning could have done this too).
  122. local request = http.request(keyurl, {
  123. headers = http_headers or {},
  124. method = "GET"
  125. }, cb);
  126. -- TODO: Is the done() call racey? Can we cancel this if the request
  127. -- succeedes?
  128. local function cancel()
  129. -- TODO: This check is racey. Not likely to be a problem, but we should
  130. -- still stick a mutex on content / code at some point.
  131. if code == nil then
  132. module:log("warn", "Timeout %s seconds fetching public key from: %s",http_timeout,keyurl);
  133. if http.destroy_request then
  134. http.destroy_request(request);
  135. end
  136. done();
  137. end
  138. end
  139. timer.add_task(http_timeout, cancel);
  140. wait();
  141. if code == 200 or code == 204 then
  142. return content;
  143. end
  144. else
  145. -- If the key is in the cache, use it.
  146. module:log("debug", "Cache hit for key: "..keyId);
  147. return content;
  148. end
  149. return nil;
  150. end
  151. --- Verifies issuer part of token
  152. -- @param 'iss' claim from the token to verify
  153. -- @return nil and error string or true for accepted claim
  154. function Util:verify_issuer(issClaim)
  155. module:log("debug","verify_issuer claim: %s against accepted: %s",issClaim, self.acceptedIssuers);
  156. for i, iss in ipairs(self.acceptedIssuers) do
  157. if issClaim == iss then
  158. --claim matches an accepted issuer so return success
  159. return true;
  160. end
  161. end
  162. --if issClaim not found in acceptedIssuers, fail claim
  163. return nil, "Invalid issuer ('iss' claim)";
  164. end
  165. --- Verifies audience part of token
  166. -- @param 'aud' claim from the token to verify
  167. -- @return nil and error string or true for accepted claim
  168. function Util:verify_audience(audClaim)
  169. module:log("debug","verify_audience claim: %s against accepted: %s",audClaim, self.acceptedAudiences);
  170. for i, aud in ipairs(self.acceptedAudiences) do
  171. if aud == '*' then
  172. --* indicates to accept any audience in the claims so return success
  173. return true;
  174. end
  175. if audClaim == aud then
  176. --claim matches an accepted audience so return success
  177. return true;
  178. end
  179. end
  180. --if issClaim not found in acceptedIssuers, fail claim
  181. return nil, "Invalid audience ('aud' claim)";
  182. end
  183. --- Verifies token
  184. -- @param token the token to verify
  185. -- @param secret the secret to use to verify token
  186. -- @return nil and error or the extracted claims from the token
  187. function Util:verify_token(token, secret)
  188. local claims, err = jwt.decode(token, secret, true);
  189. if claims == nil then
  190. return nil, err;
  191. end
  192. local alg = claims["alg"];
  193. if alg ~= nil and (alg == "none" or alg == "") then
  194. return nil, "'alg' claim must not be empty";
  195. end
  196. local issClaim = claims["iss"];
  197. if issClaim == nil then
  198. return nil, "'iss' claim is missing";
  199. end
  200. --check the issuer against the accepted list
  201. local issCheck, issCheckErr = self:verify_issuer(issClaim);
  202. if issCheck == nil then
  203. return nil, issCheckErr;
  204. end
  205. if self.requireRoomClaim then
  206. local roomClaim = claims["room"];
  207. if roomClaim == nil then
  208. return nil, "'room' claim is missing";
  209. end
  210. end
  211. local audClaim = claims["aud"];
  212. if audClaim == nil then
  213. return nil, "'aud' claim is missing";
  214. end
  215. --check the audience against the accepted list
  216. local audCheck, audCheckErr = self:verify_audience(audClaim);
  217. if audCheck == nil then
  218. return nil, audCheckErr;
  219. end
  220. return claims;
  221. end
  222. --- Verifies token and process needed values to be stored in the session.
  223. -- Token is obtained from session.auth_token.
  224. -- Stores in session the following values:
  225. -- session.jitsi_meet_room - the room name value from the token
  226. -- session.jitsi_meet_domain - the domain name value from the token
  227. -- session.jitsi_meet_context_user - the user details from the token
  228. -- session.jitsi_meet_context_group - the group value from the token
  229. -- session.jitsi_meet_context_features - the features value from the token
  230. -- @param session the current session
  231. -- @return false and error
  232. function Util:process_and_verify_token(session)
  233. if session.auth_token == nil then
  234. if self.allowEmptyToken then
  235. return true;
  236. else
  237. return false, "not-allowed", "token required";
  238. end
  239. end
  240. local pubKey;
  241. if self.asapKeyServer and session.auth_token ~= nil then
  242. local dotFirst = session.auth_token:find("%.");
  243. if not dotFirst then return nil, "Invalid token" end
  244. local header, err = json_safe.decode(basexx.from_url64(session.auth_token:sub(1,dotFirst-1)));
  245. if err then
  246. return false, "not-allowed", "bad token format";
  247. end
  248. local kid = header["kid"];
  249. if kid == nil then
  250. return false, "not-allowed", "'kid' claim is missing";
  251. end
  252. pubKey = self:get_public_key(kid);
  253. if pubKey == nil then
  254. return false, "not-allowed", "could not obtain public key";
  255. end
  256. end
  257. -- now verify the whole token
  258. local claims, msg;
  259. if self.asapKeyServer then
  260. claims, msg = self:verify_token(session.auth_token, pubKey);
  261. else
  262. claims, msg = self:verify_token(session.auth_token, self.appSecret);
  263. end
  264. if claims ~= nil then
  265. -- Binds room name to the session which is later checked on MUC join
  266. session.jitsi_meet_room = claims["room"];
  267. -- Binds domain name to the session
  268. session.jitsi_meet_domain = claims["sub"];
  269. -- Binds the user details to the session if available
  270. if claims["context"] ~= nil then
  271. if claims["context"]["user"] ~= nil then
  272. session.jitsi_meet_context_user = claims["context"]["user"];
  273. end
  274. if claims["context"]["group"] ~= nil then
  275. -- Binds any group details to the session
  276. session.jitsi_meet_context_group = claims["context"]["group"];
  277. end
  278. if claims["context"]["features"] ~= nil then
  279. -- Binds any features details to the session
  280. session.jitsi_meet_context_features = claims["context"]["features"];
  281. end
  282. end
  283. return true;
  284. else
  285. return false, "not-allowed", msg;
  286. end
  287. end
  288. --- Verifies room name and domain if necesarry.
  289. -- Checks configs and if necessary checks the room name extracted from
  290. -- room_address against the one saved in the session when token was verified.
  291. -- Also verifies domain name from token against the domain in the room_address,
  292. -- if enableDomainVerification is enabled.
  293. -- @param session the current session
  294. -- @param room_address the whole room address as received
  295. -- @return returns true in case room was verified or there is no need to verify
  296. -- it and returns false in case verification was processed
  297. -- and was not successful
  298. function Util:verify_room(session, room_address)
  299. if self.allowEmptyToken and session.auth_token == nil then
  300. module:log(
  301. "debug",
  302. "Skipped room token verification - empty tokens are allowed");
  303. return true;
  304. end
  305. -- extract room name using all chars, except the not allowed ones
  306. local room,_,_ = jid.split(room_address);
  307. if room == nil then
  308. log("error",
  309. "Unable to get name of the MUC room ? to: %s", room_address);
  310. return true;
  311. end
  312. local auth_room = session.jitsi_meet_room;
  313. if not self.enableDomainVerification then
  314. -- if auth_room is missing, this means user is anonymous (no token for
  315. -- its domain) we let it through, jicofo is verifying creation domain
  316. if auth_room and room ~= string.lower(auth_room) and auth_room ~= '*' then
  317. return false;
  318. end
  319. return true;
  320. end
  321. local room_address_to_verify = jid.bare(room_address);
  322. local room_node = jid.node(room_address);
  323. -- parses bare room address, for multidomain expected format is:
  324. -- [subdomain]roomName@conference.domain
  325. local target_subdomain, target_room = room_node:match("^%[([^%]]+)%](.+)$");
  326. -- if we have '*' as room name in token, this means all rooms are allowed
  327. -- so we will use the actual name of the room when constructing strings
  328. -- to verify subdomains and domains to simplify checks
  329. local room_to_check;
  330. if auth_room == '*' then
  331. -- authorized for accessing any room assign to room_to_check the actual
  332. -- room name
  333. if target_room ~= nil then
  334. -- we are in multidomain mode and we were able to extract room name
  335. room_to_check = target_room;
  336. else
  337. -- no target_room, room_address_to_verify does not contain subdomain
  338. -- so we get just the node which is the room name
  339. room_to_check = room_node;
  340. end
  341. else
  342. -- no wildcard, so check room against authorized room in token
  343. room_to_check = auth_room;
  344. end
  345. local auth_domain = session.jitsi_meet_domain;
  346. local subdomain_to_check;
  347. if target_subdomain then
  348. if auth_domain == '*' then
  349. -- check for wildcard in JWT claim, allow access if found
  350. subdomain_to_check = target_subdomain;
  351. else
  352. -- no wildcard in JWT claim, so check subdomain against sub in token
  353. subdomain_to_check = auth_domain;
  354. end
  355. -- from this point we depend on muc_domain_base,
  356. -- deny access if option is missing
  357. if not self.muc_domain_base then
  358. module:log("warn", "No 'muc_domain_base' option set, denying access!");
  359. return false;
  360. end
  361. return room_address_to_verify == jid.join(
  362. "["..string.lower(subdomain_to_check).."]"..string.lower(room_to_check), self.muc_domain);
  363. else
  364. if auth_domain == '*' then
  365. -- check for wildcard in JWT claim, allow access if found
  366. subdomain_to_check = self.muc_domain;
  367. else
  368. -- no wildcard in JWT claim, so check subdomain against sub in token
  369. subdomain_to_check = self.muc_domain_prefix.."."..auth_domain;
  370. end
  371. -- we do not have a domain part (multidomain is not enabled)
  372. -- verify with info from the token
  373. return room_address_to_verify == jid.join(
  374. string.lower(room_to_check), string.lower(subdomain_to_check));
  375. end
  376. end
  377. return Util;