Merge 0.10->trunk
[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 tonumber, tostring = tonumber, 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 = tonumber(luasec_major) * 100 + tonumber(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 key_path:sub(-4) == ".crt" then
67                                 key_path = key_path:sub(1, -4) .. "key";
68                                 if stat(key_path, "mode") == "file" then
69                                         return { certificate = crt_path, key = key_path };
70                                 end
71                         elseif stat(key_path, "mode") == "file" then
72                                 return { certificate = crt_path, key = key_path };
73                         end
74                 end
75         end
76 end
77
78 local function find_host_cert(host)
79         if not host then return nil; end
80         return find_cert(configmanager.get(host, "certificate"), host) or find_host_cert(host:match("%.(.+)$"));
81 end
82
83 local function find_service_cert(service, port)
84         local cert_config = configmanager.get("*", service.."_certificate");
85         if type(cert_config) == "table" then
86                 cert_config = cert_config[port] or cert_config.default;
87         end
88         return find_cert(cert_config, service);
89 end
90
91 -- Built-in defaults
92 local core_defaults = {
93         capath = "/etc/ssl/certs";
94         depth = 9;
95         protocol = "tlsv1+";
96         verify = (ssl_x509 and { "peer", "client_once", }) or "none";
97         options = {
98                 cipher_server_preference = luasec_has.cipher_server_preference;
99                 no_ticket = luasec_has.no_ticket;
100                 no_compression = luasec_has.no_compression and configmanager.get("*", "ssl_compression") ~= true;
101                 single_dh_use = luasec_has.single_dh_use;
102                 single_ecdh_use = luasec_has.single_ecdh_use;
103         };
104         verifyext = { "lsec_continue", "lsec_ignore_purpose" };
105         curve = "secp384r1";
106         ciphers = "HIGH+kEDH:HIGH+kEECDH:HIGH:!PSK:!SRP:!3DES:!aNULL";
107 }
108 local path_options = { -- These we pass through resolve_path()
109         key = true, certificate = true, cafile = true, capath = true, dhparam = true
110 }
111
112 if luasec_version < 5 and ssl_x509 then
113         -- COMPAT mw/luasec-hg
114         for i=1,#core_defaults.verifyext do -- Remove lsec_ prefix
115                 core_defaults.verify[#core_defaults.verify+1] = core_defaults.verifyext[i]:sub(6);
116         end
117 end
118
119 local function create_context(host, mode, ...)
120         local cfg = new_config();
121         cfg:apply(core_defaults);
122         local service_name, port = host:match("^(%w+) port (%d+)$");
123         if service_name then
124                 cfg:apply(find_service_cert(service_name, tonumber(port)));
125         else
126                 cfg:apply(find_host_cert(host));
127         end
128         cfg:apply({
129                 mode = mode,
130                 -- We can't read the password interactively when daemonized
131                 password = function() log("error", "Encrypted certificate for %s requires 'ssl' 'password' to be set in config", host); end;
132         });
133         cfg:apply(global_ssl_config);
134
135         for i = select('#', ...), 1, -1 do
136                 cfg:apply(select(i, ...));
137         end
138         local user_ssl_config = cfg:final();
139
140         if mode == "server" then
141                 if not user_ssl_config.key then return nil, "No key present in SSL/TLS configuration for "..host; end
142                 if not user_ssl_config.certificate then return nil, "No certificate present in SSL/TLS configuration for "..host; end
143         end
144
145         for option in pairs(path_options) do
146                 if type(user_ssl_config[option]) == "string" then
147                         user_ssl_config[option] = resolve_path(config_path, user_ssl_config[option]);
148                 else
149                         user_ssl_config[option] = nil;
150                 end
151         end
152
153         -- LuaSec expects dhparam to be a callback that takes two arguments.
154         -- We ignore those because it is mostly used for having a separate
155         -- set of params for EXPORT ciphers, which we don't have by default.
156         if type(user_ssl_config.dhparam) == "string" then
157                 local f, err = io_open(user_ssl_config.dhparam);
158                 if not f then return nil, "Could not open DH parameters: "..err end
159                 local dhparam = f:read("*a");
160                 f:close();
161                 user_ssl_config.dhparam = function() return dhparam; end
162         end
163
164         local ctx, err = ssl_newcontext(user_ssl_config);
165
166         -- COMPAT Older LuaSec ignores the cipher list from the config, so we have to take care
167         -- of it ourselves (W/A for #x)
168         if ctx and user_ssl_config.ciphers then
169                 local success;
170                 success, err = ssl_context.setcipher(ctx, user_ssl_config.ciphers);
171                 if not success then ctx = nil; end
172         end
173
174         if not ctx then
175                 err = err or "invalid ssl config"
176                 local file = err:match("^error loading (.-) %(");
177                 if file then
178                         if file == "private key" then
179                                 file = user_ssl_config.key or "your private key";
180                         elseif file == "certificate" then
181                                 file = user_ssl_config.certificate or "your certificate file";
182                         end
183                         local reason = err:match("%((.+)%)$") or "some reason";
184                         if reason == "Permission denied" then
185                                 reason = "Check that the permissions allow Prosody to read this file.";
186                         elseif reason == "No such file or directory" then
187                                 reason = "Check that the path is correct, and the file exists.";
188                         elseif reason == "system lib" then
189                                 reason = "Previous error (see logs), or other system error.";
190                         elseif reason == "(null)" or not reason then
191                                 reason = "Check that the file exists and the permissions are correct";
192                         else
193                                 reason = "Reason: "..tostring(reason):lower();
194                         end
195                         log("error", "SSL/TLS: Failed to load '%s': %s (for %s)", file, reason, host);
196                 else
197                         log("error", "SSL/TLS: Error initialising for %s: %s", host, err);
198                 end
199         end
200         return ctx, err, user_ssl_config;
201 end
202
203 local function reload_ssl_config()
204         global_ssl_config = configmanager.get("*", "ssl");
205         if luasec_has.no_compression then
206                 core_defaults.options.no_compression = configmanager.get("*", "ssl_compression") ~= true;
207         end
208 end
209
210 prosody.events.add_handler("config-reloaded", reload_ssl_config);
211
212 return {
213         create_context = create_context;
214         reload_ssl_config = reload_ssl_config;
215 };