certmanager: Support new certificate configuration for non-XMPP services too (fixes...
[prosody.git] / core / certmanager.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 local softreq = require"util.dependencies".softreq;
10 local ssl = softreq"ssl";
11 if not ssl then
12         return {
13                 create_context = function ()
14                         return nil, "LuaSec (required for encryption) was not found";
15                 end;
16                 reload_ssl_config = function () end;
17         }
18 end
19
20 local configmanager = require "core.configmanager";
21 local log = require "util.logger".init("certmanager");
22 local ssl_context = ssl.context or softreq"ssl.context";
23 local ssl_x509 = ssl.x509 or softreq"ssl.x509";
24 local ssl_newcontext = ssl.newcontext;
25 local new_config = require"util.sslconfig".new;
26 local stat = require "lfs".attributes;
27
28 local tostring = tostring;
29 local pairs = pairs;
30 local type = type;
31 local io_open = io.open;
32 local select = select;
33
34 local prosody = prosody;
35 local resolve_path = require"util.paths".resolve_relative_path;
36 local config_path = prosody.paths.config;
37
38 local luasec_major, luasec_minor = ssl._VERSION:match("^(%d+)%.(%d+)");
39 local luasec_version = luasec_major * 100 + luasec_minor;
40 local luasec_has = {
41         -- TODO If LuaSec ever starts exposing these things itself, use that instead
42         cipher_server_preference = luasec_version >= 2;
43         no_ticket = luasec_version >= 4;
44         no_compression = luasec_version >= 5;
45         single_dh_use = luasec_version >= 2;
46         single_ecdh_use = luasec_version >= 2;
47 };
48
49 local _ENV = nil;
50
51 -- Global SSL options if not overridden per-host
52 local global_ssl_config = configmanager.get("*", "ssl");
53
54 local global_certificates = configmanager.get("*", "certificates") or "certs";
55
56 local crt_try = { "", "/%s.crt", "/%s/fullchain.pem", "/%s.pem", };
57 local key_try = { "", "/%s.key", "/%s/privkey.pem",   "/%s.pem", };
58
59 local function find_cert(user_certs, name)
60         local certs = resolve_path(config_path, user_certs or global_certificates);
61         for i = 1, #crt_try do
62                 local crt_path = certs .. crt_try[i]:format(name);
63                 local key_path = certs .. key_try[i]:format(name);
64
65                 if stat(crt_path, "mode") == "file" then
66                         if stat(key_path, "mode") == "file" then
67                                 return { certificate = crt_path, key = key_path };
68                         end
69                         if key_path:sub(-4) == ".crt" then
70                                 key_path = key_path:sub(1, -4) .. "key";
71                                 if stat(key_path, "mode") == "file" then
72                                         return { certificate = crt_path, key = key_path };
73                                 end
74                         end
75                 end
76         end
77 end
78
79 local function find_host_cert(host)
80         if not host then return nil; end
81         return find_cert(configmanager.get(host, "certificate"), host) or find_host_cert(host:match("%.(.+)$"));
82 end
83
84 local function find_service_cert(service, port)
85         local cert_config = configmanager.get("*", service.."_certificate");
86         if type(cert_config) == "table" then
87                 cert_config = cert_config[port] or cert_config.default;
88         end
89         return find_cert(cert_config, service);
90 end
91
92 -- Built-in defaults
93 local core_defaults = {
94         capath = "/etc/ssl/certs";
95         depth = 9;
96         protocol = "tlsv1+";
97         verify = (ssl_x509 and { "peer", "client_once", }) or "none";
98         options = {
99                 cipher_server_preference = luasec_has.cipher_server_preference;
100                 no_ticket = luasec_has.no_ticket;
101                 no_compression = luasec_has.no_compression and configmanager.get("*", "ssl_compression") ~= true;
102                 single_dh_use = luasec_has.single_dh_use;
103                 single_ecdh_use = luasec_has.single_ecdh_use;
104         };
105         verifyext = { "lsec_continue", "lsec_ignore_purpose" };
106         curve = "secp384r1";
107         ciphers = "HIGH+kEDH:HIGH+kEECDH:HIGH:!PSK:!SRP:!3DES:!aNULL";
108 }
109 local path_options = { -- These we pass through resolve_path()
110         key = true, certificate = true, cafile = true, capath = true, dhparam = true
111 }
112
113 if luasec_version < 5 and ssl_x509 then
114         -- COMPAT mw/luasec-hg
115         for i=1,#core_defaults.verifyext do -- Remove lsec_ prefix
116                 core_defaults.verify[#core_defaults.verify+1] = core_defaults.verifyext[i]:sub(6);
117         end
118 end
119
120 local function create_context(host, mode, ...)
121         local cfg = new_config();
122         cfg:apply(core_defaults);
123         cfg:apply(global_ssl_config);
124         local service_name, port = host:match("^(%w+) port (%d+)$");
125         if service_name then
126                 cfg:apply(find_service_cert(service_name, tonumber(port)));
127         else
128                 cfg:apply(find_host_cert(host));
129         end
130         cfg:apply({
131                 mode = mode,
132                 -- We can't read the password interactively when daemonized
133                 password = function() log("error", "Encrypted certificate for %s requires 'ssl' 'password' to be set in config", host); end;
134         });
135
136         for i = select('#', ...), 1, -1 do
137                 cfg:apply(select(i, ...));
138         end
139         local user_ssl_config = cfg:final();
140
141         if mode == "server" then
142                 if not user_ssl_config.key then return nil, "No key present in SSL/TLS configuration for "..host; end
143                 if not user_ssl_config.certificate then return nil, "No certificate present in SSL/TLS configuration for "..host; end
144         end
145
146         for option in pairs(path_options) do
147                 if type(user_ssl_config[option]) == "string" then
148                         user_ssl_config[option] = resolve_path(config_path, user_ssl_config[option]);
149                 else
150                         user_ssl_config[option] = nil;
151                 end
152         end
153
154         -- LuaSec expects dhparam to be a callback that takes two arguments.
155         -- We ignore those because it is mostly used for having a separate
156         -- set of params for EXPORT ciphers, which we don't have by default.
157         if type(user_ssl_config.dhparam) == "string" then
158                 local f, err = io_open(user_ssl_config.dhparam);
159                 if not f then return nil, "Could not open DH parameters: "..err end
160                 local dhparam = f:read("*a");
161                 f:close();
162                 user_ssl_config.dhparam = function() return dhparam; end
163         end
164
165         local ctx, err = ssl_newcontext(user_ssl_config);
166
167         -- COMPAT Older LuaSec ignores the cipher list from the config, so we have to take care
168         -- of it ourselves (W/A for #x)
169         if ctx and user_ssl_config.ciphers then
170                 local success;
171                 success, err = ssl_context.setcipher(ctx, user_ssl_config.ciphers);
172                 if not success then ctx = nil; end
173         end
174
175         if not ctx then
176                 err = err or "invalid ssl config"
177                 local file = err:match("^error loading (.-) %(");
178                 if file then
179                         if file == "private key" then
180                                 file = user_ssl_config.key or "your private key";
181                         elseif file == "certificate" then
182                                 file = user_ssl_config.certificate or "your certificate file";
183                         end
184                         local reason = err:match("%((.+)%)$") or "some reason";
185                         if reason == "Permission denied" then
186                                 reason = "Check that the permissions allow Prosody to read this file.";
187                         elseif reason == "No such file or directory" then
188                                 reason = "Check that the path is correct, and the file exists.";
189                         elseif reason == "system lib" then
190                                 reason = "Previous error (see logs), or other system error.";
191                         elseif reason == "(null)" or not reason then
192                                 reason = "Check that the file exists and the permissions are correct";
193                         else
194                                 reason = "Reason: "..tostring(reason):lower();
195                         end
196                         log("error", "SSL/TLS: Failed to load '%s': %s (for %s)", file, reason, host);
197                 else
198                         log("error", "SSL/TLS: Error initialising for %s: %s", host, err);
199                 end
200         end
201         return ctx, err, user_ssl_config;
202 end
203
204 local function reload_ssl_config()
205         global_ssl_config = configmanager.get("*", "ssl");
206         if luasec_has.no_compression then
207                 core_defaults.options.no_compression = configmanager.get("*", "ssl_compression") ~= true;
208         end
209 end
210
211 prosody.events.add_handler("config-reloaded", reload_ssl_config);
212
213 return {
214         create_context = create_context;
215         reload_ssl_config = reload_ssl_config;
216 };