Software /
code /
prosody
File
plugins/mod_authz_internal.lua @ 13652:a08065207ef0
net.server_epoll: Call :shutdown() on TLS sockets when supported
Comment from Matthew:
This fixes a potential issue where the Prosody process gets blocked on sockets
waiting for them to close. Unlike non-TLS sockets, closing a TLS socket sends
layer 7 data, and this can cause problems for sockets which are in the process
of being cleaned up.
This depends on LuaSec changes which are not yet upstream.
From Martijn's original email:
So first my analysis of luasec. in ssl.c the socket is put into blocking
mode right before calling SSL_shutdown() inside meth_destroy(). My best
guess to why this is is because meth_destroy is linked to the __close
and __gc methods, which can't exactly be called multiple times and
luasec does want to make sure that a tls session is shutdown as clean
as possible.
I can't say I disagree with this reasoning and don't want to change this
behaviour. My solution to this without changing the current behaviour is
to introduce a shutdown() method. I am aware that this overlaps in a
conflicting way with tcp's shutdown method, but it stays close to the
OpenSSL name. This method calls SSL_shutdown() in the current
(non)blocking mode of the underlying socket and returns a boolean
whether or not the shutdown is completed (matching SSL_shutdown()'s 0
or 1 return values), and returns the familiar ssl_ioerror() strings on
error with a false for completion. This error can then be used to
determine if we have wantread/wantwrite to finalize things. Once
meth_shutdown() has been called once a shutdown flag will be set, which
indicates to meth_destroy() that the SSL_shutdown() has been handled
by the application and it shouldn't be needed to set the socket to
blocking mode. I've left the SSL_shutdown() call in the
LSEC_STATE_CONNECTED to prevent TOCTOU if the application reaches a
timeout for the shutdown code, which might allow SSL_shutdown() to
clean up anyway at the last possible moment.
Another thing I've changed to luasec is the call to socket_setblocking()
right before calling close(2) in socket_destroy() in usocket.c.
According to the latest POSIX[0]:
Note that the requirement for close() on a socket to block for up to
the current linger interval is not conditional on the O_NONBLOCK
setting.
Which I read to mean that removing O_NONBLOCK on the socket before close
doesn't impact the behaviour and only causes noise in system call
tracers. I didn't touch the windows bits of this, since I don't do
windows.
For the prosody side of things I've made the TLS shutdown bits resemble
interface:onwritable(), and put it under a combined guard of self._tls
and self.conn.shutdown. The self._tls bit is there to prevent getting
stuck on this condition, and self.conn.shutdown is there to prevent the
code being called by instances where the patched luasec isn't deployed.
The destroy() method can be called from various places and is read by
me as the "we give up" error path. To accommodate for these unexpected
entrypoints I've added a single call to self.conn:shutdown() to prevent
the socket being put into blocking mode. I have no expectations that
there is any other use here. Same as previous, the self.conn.shutdown
check is there to make sure it's not called on unpatched luasec
deployments and self._tls is there to make sure we don't call shutdown()
on tcp sockets.
I wouldn't recommend logging of the conn:shutdown() error inside
close(), since a lot of clients simply close the connection before
SSL_shutdown() is done.
author | Martijn van Duren <martijn@openbsd.org> |
---|---|
date | Thu, 06 Feb 2025 15:04:38 +0000 |
parent | 13621:eb676b6f05e3 |
child | 13678:acb87cc2d48b |
line wrap: on
line source
local array = require "prosody.util.array"; local it = require "prosody.util.iterators"; local set = require "prosody.util.set"; local jid_split, jid_bare, jid_host = import("prosody.util.jid", "split", "bare", "host"); local normalize = require "prosody.util.jid".prep; local roles = require "prosody.util.roles"; local config_global_admin_jids = module:context("*"):get_option_set("admins", {}) / normalize; local config_admin_jids = module:get_option_inherited_set("admins", {}) / normalize; local host = module.host; local host_suffix = module:get_option_string("parent_host", (host:gsub("^[^%.]+%.", ""))); local hosts = prosody.hosts; local is_anon_host = module:get_option_string("authentication") == "anonymous"; local default_user_role = module:get_option_string("default_user_role", is_anon_host and "prosody:guest" or "prosody:registered"); local is_component = hosts[host].type == "component"; local host_user_role, server_user_role, public_user_role; if is_component then host_user_role = module:get_option_string("host_user_role", "prosody:registered"); server_user_role = module:get_option_string("server_user_role", "prosody:guest"); public_user_role = module:get_option_string("public_user_role", "prosody:guest"); end local role_store = module:open_store("account_roles"); local role_map_store = module:open_store("account_roles", "map"); local role_registry = {}; function register_role(role) if role_registry[role.name] ~= nil then return error("A role '"..role.name.."' is already registered"); end if not roles.is_role(role) then -- Convert table syntax to real role object for i, inherited_role in ipairs(role.inherits or {}) do if type(inherited_role) == "string" then role.inherits[i] = assert(role_registry[inherited_role], "The named role '"..inherited_role.."' is not registered"); end end if not role.permissions then role.permissions = {}; end for _, allow_permission in ipairs(role.allow or {}) do role.permissions[allow_permission] = true; end for _, deny_permission in ipairs(role.deny or {}) do role.permissions[deny_permission] = false; end role = roles.new(role); end role_registry[role.name] = role; end -- Default roles -- For untrusted guest/anonymous users register_role { name = "prosody:guest"; priority = 15; }; -- For e.g. self-registered accounts register_role { name = "prosody:registered"; priority = 25; inherits = { "prosody:guest" }; }; -- For trusted/provisioned accounts register_role { name = "prosody:member"; priority = 35; inherits = { "prosody:registered" }; }; -- For administrators, e.g. of a host register_role { name = "prosody:admin"; priority = 50; inherits = { "prosody:member" }; }; -- For server operators (full access) register_role { name = "prosody:operator"; priority = 75; inherits = { "prosody:admin" }; }; -- Process custom roles from config local custom_roles = module:get_option_array("custom_roles", {}); for n, role_config in ipairs(custom_roles) do local ok, err = pcall(register_role, role_config); if not ok then module:log("error", "Error registering custom role %s: %s", role_config.name or tostring(n), err); end end -- Process custom permissions from config local config_add_perms = module:get_option("add_permissions", {}); local config_remove_perms = module:get_option("remove_permissions", {}); for role_name, added_permissions in pairs(config_add_perms) do if not role_registry[role_name] then module:log("error", "Cannot add permissions to unknown role '%s'", role_name); else for _, permission in ipairs(added_permissions) do role_registry[role_name]:set_permission(permission, true, true); end end end for role_name, removed_permissions in pairs(config_remove_perms) do if not role_registry[role_name] then module:log("error", "Cannot remove permissions from unknown role '%s'", role_name); else for _, permission in ipairs(removed_permissions) do role_registry[role_name]:set_permission(permission, false, true); end end end -- Public API -- Get the primary role of a user function get_user_role(user) local bare_jid = user.."@"..host; -- Check config first if config_global_admin_jids:contains(bare_jid) then return role_registry["prosody:operator"]; elseif config_admin_jids:contains(bare_jid) then return role_registry["prosody:admin"]; end -- Check storage local stored_roles, err = role_store:get(user); if not stored_roles then if err then -- Unable to fetch role, fail return nil, err; end -- No role set, use default role return role_registry[default_user_role]; end if stored_roles._default == nil then -- No primary role explicitly set, return default return role_registry[default_user_role]; end local primary_stored_role = role_registry[stored_roles._default]; if not primary_stored_role then return nil, "unknown-role"; end return primary_stored_role; end -- Set the primary role of a user function set_user_role(user, role_name) local role = role_registry[role_name]; if not role then return error("Cannot assign default user an unknown role: "..tostring(role_name)); end local keys_update = { _default = role_name; -- Primary role cannot be secondary role [role_name] = role_map_store.remove; }; if role_name == default_user_role then -- Don't store default keys_update._default = role_map_store.remove; end local ok, err = role_map_store:set_keys(user, keys_update); if not ok then return nil, err; end return role; end function add_user_secondary_role(user, role_name) if not role_registry[role_name] then return error("Cannot assign default user an unknown role: "..tostring(role_name)); end role_map_store:set(user, role_name, true); end function remove_user_secondary_role(user, role_name) role_map_store:set(user, role_name, nil); end function get_user_secondary_roles(user) local stored_roles, err = role_store:get(user); if not stored_roles then if err then -- Unable to fetch role, fail return nil, err; end -- No role set return {}; end stored_roles._default = nil; for role_name in pairs(stored_roles) do stored_roles[role_name] = role_registry[role_name]; end return stored_roles; end function user_can_assume_role(user, role_name) local primary_role = get_user_role(user); if primary_role and primary_role.name == role_name then return true; end local secondary_roles = get_user_secondary_roles(user); if secondary_roles and secondary_roles[role_name] then return true; end return false; end -- This function is *expensive* function get_users_with_role(role_name) local function role_filter(username, default_role) --luacheck: ignore 212/username return default_role == role_name; end local primary_role_users = set.new(it.to_array(it.filter(role_filter, pairs(role_map_store:get_all("_default") or {})))); local secondary_role_users = set.new(it.to_array(it.keys(role_map_store:get_all(role_name) or {}))); local config_set; if role_name == "prosody:admin" then config_set = config_admin_jids; elseif role_name == "prosody:operator" then config_set = config_global_admin_jids; end if config_set then local config_admin_users = config_set / function (admin_jid) local j_node, j_host = jid_split(admin_jid); if j_host == host then return j_node; end end; return it.to_array(config_admin_users + primary_role_users + secondary_role_users); end return it.to_array(primary_role_users + secondary_role_users); end function get_jid_role(jid) local bare_jid = jid_bare(jid); if config_global_admin_jids:contains(bare_jid) then return role_registry["prosody:operator"]; elseif config_admin_jids:contains(bare_jid) then return role_registry["prosody:admin"]; elseif is_component then local user_host = jid_host(bare_jid); if host_user_role and user_host == host_suffix then return role_registry[host_user_role]; elseif server_user_role and hosts[user_host] then return role_registry[server_user_role]; elseif public_user_role then return role_registry[public_user_role]; end end return nil; end function set_jid_role(jid, role_name) -- luacheck: ignore 212 return false, "not-implemented"; end function get_jids_with_role(role_name) -- Fetch role users from storage local storage_role_jids = array.map(get_users_with_role(role_name), function (username) return username.."@"..host; end); if role_name == "prosody:admin" then return it.to_array(config_admin_jids + set.new(storage_role_jids)); elseif role_name == "prosody:operator" then return it.to_array(config_global_admin_jids + set.new(storage_role_jids)); end return storage_role_jids; end function add_default_permission(role_name, action, policy) local role = role_registry[role_name]; if not role then module:log("warn", "Attempt to add default permission for unknown role: %s", role_name); return nil, "no-such-role"; end if policy == nil then policy = true; end module:log("debug", "Adding policy %s for permission %s on role %s", policy, action, role_name); return role:set_permission(action, policy); end function get_role_by_name(role_name) return assert(role_registry[role_name], role_name); end function get_all_roles() return role_registry; end -- COMPAT: Migrate from 0.12 role storage local function do_migration(migrate_host) local old_role_store = assert(module:context(migrate_host):open_store("roles")); local new_role_store = assert(module:context(migrate_host):open_store("account_roles")); local migrated, failed, skipped = 0, 0, 0; -- Iterate all users for username in assert(old_role_store:users()) do local old_roles = it.to_array(it.filter(function (k) return k:sub(1,1) ~= "_"; end, it.keys(old_role_store:get(username)))); if #old_roles == 1 then local ok, err = new_role_store:set(username, { _default = old_roles[1]; }); if ok then migrated = migrated + 1; else failed = failed + 1; print("EE: Failed to store new role info for '"..username.."': "..err); end else print("WW: User '"..username.."' has multiple roles and cannot be automatically migrated"); skipped = skipped + 1; end end return migrated, failed, skipped; end function module.command(arg) if arg[1] == "migrate" then table.remove(arg, 1); local migrate_host = arg[1]; if not migrate_host or not prosody.hosts[migrate_host] then print("EE: Please supply a valid host to migrate to the new role storage"); return 1; end -- Initialize storage layer require "prosody.core.storagemanager".initialize_host(migrate_host); print("II: Migrating roles..."); local migrated, failed, skipped = do_migration(migrate_host); print(("II: %d migrated, %d failed, %d skipped"):format(migrated, failed, skipped)); return (failed + skipped == 0) and 0 or 1; else print("EE: Unknown command: "..(arg[1] or "<none given>")); print(" Hint: try 'migrate'?"); end end