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