mod_register: Use util.cache to limit the number of per-ip throttles kept
[prosody.git] / plugins / mod_register.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
10 local st = require "util.stanza";
11 local dataform_new = require "util.dataforms".new;
12 local usermanager_user_exists = require "core.usermanager".user_exists;
13 local usermanager_create_user = require "core.usermanager".create_user;
14 local usermanager_set_password = require "core.usermanager".set_password;
15 local usermanager_delete_user = require "core.usermanager".delete_user;
16 local nodeprep = require "util.encodings".stringprep.nodeprep;
17 local jid_bare = require "util.jid".bare;
18 local create_throttle = require "util.throttle".create;
19 local new_cache = require "util.cache".new;
20
21 local compat = module:get_option_boolean("registration_compat", true);
22 local allow_registration = module:get_option_boolean("allow_registration", false);
23 local additional_fields = module:get_option("additional_registration_fields", {});
24
25 local account_details = module:open_store("account_details");
26
27 local field_map = {
28         username = { name = "username", type = "text-single", label = "Username", required = true };
29         password = { name = "password", type = "text-private", label = "Password", required = true };
30         nick = { name = "nick", type = "text-single", label = "Nickname" };
31         name = { name = "name", type = "text-single", label = "Full Name" };
32         first = { name = "first", type = "text-single", label = "Given Name" };
33         last = { name = "last", type = "text-single", label = "Family Name" };
34         email = { name = "email", type = "text-single", label = "Email" };
35         address = { name = "address", type = "text-single", label = "Street" };
36         city = { name = "city", type = "text-single", label = "City" };
37         state = { name = "state", type = "text-single", label = "State" };
38         zip = { name = "zip", type = "text-single", label = "Postal code" };
39         phone = { name = "phone", type = "text-single", label = "Telephone number" };
40         url = { name = "url", type = "text-single", label = "Webpage" };
41         date = { name = "date", type = "text-single", label = "Birth date" };
42 };
43
44 local registration_form = dataform_new{
45         title = "Creating a new account";
46         instructions = "Choose a username and password for use with this service.";
47
48         field_map.username;
49         field_map.password;
50 };
51
52 local registration_query = st.stanza("query", {xmlns = "jabber:iq:register"})
53         :tag("instructions"):text("Choose a username and password for use with this service."):up()
54         :tag("username"):up()
55         :tag("password"):up();
56
57 for _, field in ipairs(additional_fields) do
58         if type(field) == "table" then
59                 registration_form[#registration_form + 1] = field;
60         else
61                 if field:match("%+$") then
62                         field = field:sub(1, #field - 1);
63                         field_map[field].required = true;
64                 end
65
66                 registration_form[#registration_form + 1] = field_map[field];
67                 registration_query:tag(field):up();
68         end
69 end
70 registration_query:add_child(registration_form:form());
71
72 module:add_feature("jabber:iq:register");
73
74 local register_stream_feature = st.stanza("register", {xmlns="http://jabber.org/features/iq-register"}):up();
75 module:hook("stream-features", function(event)
76         local session, features = event.origin, event.features;
77
78         -- Advertise registration to unauthorized clients only.
79         if not(allow_registration) or session.type ~= "c2s_unauthed" then
80                 return
81         end
82
83         features:add_child(register_stream_feature);
84 end);
85
86 local function handle_registration_stanza(event)
87         local session, stanza = event.origin, event.stanza;
88         local log = session.log or module._log;
89
90         local query = stanza.tags[1];
91         if stanza.attr.type == "get" then
92                 local reply = st.reply(stanza);
93                 reply:tag("query", {xmlns = "jabber:iq:register"})
94                         :tag("registered"):up()
95                         :tag("username"):text(session.username):up()
96                         :tag("password"):up();
97                 session.send(reply);
98         else -- stanza.attr.type == "set"
99                 if query.tags[1] and query.tags[1].name == "remove" then
100                         local username, host = session.username, session.host;
101
102                         -- This one weird trick sends a reply to this stanza before the user is deleted
103                         local old_session_close = session.close;
104                         session.close = function(session, ...)
105                                 session.send(st.reply(stanza));
106                                 return old_session_close(session, ...);
107                         end
108
109                         local ok, err = usermanager_delete_user(username, host);
110
111                         if not ok then
112                                 log("debug", "Removing user account %s@%s failed: %s", username, host, err);
113                                 session.close = old_session_close;
114                                 session.send(st.error_reply(stanza, "cancel", "service-unavailable", err));
115                                 return true;
116                         end
117
118                         log("info", "User removed their account: %s@%s", username, host);
119                         module:fire_event("user-deregistered", { username = username, host = host, source = "mod_register", session = session });
120                 else
121                         local username = nodeprep(query:get_child_text("username"));
122                         local password = query:get_child_text("password");
123                         if username and password then
124                                 if username == session.username then
125                                         if usermanager_set_password(username, password, session.host) then
126                                                 session.send(st.reply(stanza));
127                                         else
128                                                 -- TODO unable to write file, file may be locked, etc, what's the correct error?
129                                                 session.send(st.error_reply(stanza, "wait", "internal-server-error"));
130                                         end
131                                 else
132                                         session.send(st.error_reply(stanza, "modify", "bad-request"));
133                                 end
134                         else
135                                 session.send(st.error_reply(stanza, "modify", "bad-request"));
136                         end
137                 end
138         end
139         return true;
140 end
141
142 module:hook("iq/self/jabber:iq:register:query", handle_registration_stanza);
143 if compat then
144         module:hook("iq/host/jabber:iq:register:query", function (event)
145                 local session, stanza = event.origin, event.stanza;
146                 if session.type == "c2s" and jid_bare(stanza.attr.to) == session.host then
147                         return handle_registration_stanza(event);
148                 end
149         end);
150 end
151
152 local function parse_response(query)
153         local form = query:get_child("x", "jabber:x:data");
154         if form then
155                 return registration_form:data(form);
156         else
157                 local data = {};
158                 local errors = {};
159                 for _, field in ipairs(registration_form) do
160                         local name, required = field.name, field.required;
161                         if field_map[name] then
162                                 data[name] = query:get_child_text(name);
163                                 if (not data[name] or #data[name] == 0) and required then
164                                         errors[name] = "Required value missing";
165                                 end
166                         end
167                 end
168                 if next(errors) then
169                         return data, errors;
170                 end
171                 return data;
172         end
173 end
174
175 local min_seconds_between_registrations = module:get_option_number("min_seconds_between_registrations");
176 local whitelist_only = module:get_option_boolean("whitelist_registration_only");
177 local whitelisted_ips = module:get_option_set("registration_whitelist", { "127.0.0.1" })._items;
178 local blacklisted_ips = module:get_option_set("registration_blacklist", {})._items;
179
180 local throttle_max = module:get_option_number("registration_throttle_max", min_seconds_between_registrations and 1);
181 local throttle_period = module:get_option_number("registration_throttle_period", min_seconds_between_registrations);
182 local throttle_cache_size = module:get_option_number("registration_throttle_cache_size", 100);
183
184 local throttle_cache = new_cache(throttle_cache_size);
185
186 local function check_throttle(ip)
187         if not throttle_max then return true end
188         local throttle = throttle_cache:get(ip);
189         if not throttle then
190                 throttle = create_throttle(throttle_max, throttle_period);
191         end
192         throttle_cache:set(ip, throttle);
193         return throttle:poll(1);
194 end
195
196 module:hook("stanza/iq/jabber:iq:register:query", function(event)
197         local session, stanza = event.origin, event.stanza;
198         local log = session.log or module._log;
199
200         if not(allow_registration) or session.type ~= "c2s_unauthed" then
201                 session.send(st.error_reply(stanza, "cancel", "service-unavailable"));
202         else
203                 local query = stanza.tags[1];
204                 if stanza.attr.type == "get" then
205                         local reply = st.reply(stanza);
206                         reply:add_child(registration_query);
207                         session.send(reply);
208                 elseif stanza.attr.type == "set" then
209                         if query.tags[1] and query.tags[1].name == "remove" then
210                                 session.send(st.error_reply(stanza, "auth", "registration-required"));
211                         else
212                                 local data, errors = parse_response(query);
213                                 if errors then
214                                         session.send(st.error_reply(stanza, "modify", "not-acceptable"));
215                                 else
216                                         -- Check that the user is not blacklisted or registering too often
217                                         if not session.ip then
218                                                 log("debug", "User's IP not known; can't apply blacklist/whitelist");
219                                         elseif blacklisted_ips[session.ip] or (whitelist_only and not whitelisted_ips[session.ip]) then
220                                                 session.send(st.error_reply(stanza, "cancel", "not-acceptable", "You are not allowed to register an account."));
221                                                 return true;
222                                         elseif min_seconds_between_registrations and not whitelisted_ips[session.ip] then
223                                                 if check_throttle(session.ip) then
224                                                         session.send(st.error_reply(stanza, "wait", "not-acceptable"));
225                                                         return true;
226                                                 end
227                                         end
228                                         local username, password = nodeprep(data.username), data.password;
229                                         data.username, data.password = nil, nil;
230                                         local host = module.host;
231                                         if not username or username == "" then
232                                                 session.send(st.error_reply(stanza, "modify", "not-acceptable", "The requested username is invalid."));
233                                                 return true;
234                                         end
235                                         local user = { username = username , host = host, allowed = true }
236                                         module:fire_event("user-registering", user);
237                                         if not user.allowed then
238                                                 session.send(st.error_reply(stanza, "modify", "not-acceptable", "The requested username is forbidden."));
239                                         elseif usermanager_user_exists(username, host) then
240                                                 session.send(st.error_reply(stanza, "cancel", "conflict", "The requested username already exists."));
241                                         else
242                                                 -- TODO unable to write file, file may be locked, etc, what's the correct error?
243                                                 local error_reply = st.error_reply(stanza, "wait", "internal-server-error", "Failed to write data to disk.");
244                                                 if usermanager_create_user(username, password, host) then
245                                                         if next(data) and not account_details:set(username, data) then
246                                                                 usermanager_delete_user(username, host);
247                                                                 session.send(error_reply);
248                                                                 return true;
249                                                         end
250                                                         session.send(st.reply(stanza)); -- user created!
251                                                         log("info", "User account created: %s@%s", username, host);
252                                                         module:fire_event("user-registered", {
253                                                                 username = username, host = host, source = "mod_register",
254                                                                 session = session });
255                                                 else
256                                                         session.send(error_reply);
257                                                 end
258                                         end
259                                 end
260                         end
261                 end
262         end
263         return true;
264 end);