util.sasl, util.sasl_cyrus: Updated method:mechanisms() to cache and re-use list...
[prosody.git] / util / sasl_cyrus.lua
1 -- sasl.lua v0.4
2 -- Copyright (C) 2008-2009 Tobias Markmann
3 --
4 --    All rights reserved.
5 --
6 --    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
7 --
8 --        * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
9 --        * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
10 --        * Neither the name of Tobias Markmann nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
11 --
12 --    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13
14 local cyrussasl = require "cyrussasl";
15 local log = require "util.logger".init("sasl_cyrus");
16 local array = require "util.array";
17
18 local tostring = tostring;
19 local pairs, ipairs = pairs, ipairs;
20 local t_insert, t_concat = table.insert, table.concat;
21 local s_match = string.match;
22 local setmetatable = setmetatable
23
24 local keys = keys;
25
26 local print = print
27 local pcall = pcall
28 local s_match, s_gmatch = string.match, string.gmatch
29
30 local sasl_errstring = {
31         -- SASL result codes --
32         [1]   = "another step is needed in authentication";
33         [0]   = "successful result";
34         [-1]  = "generic failure";
35         [-2]  = "memory shortage failure";
36         [-3]  = "overflowed buffer";
37         [-4]  = "mechanism not supported";
38         [-5]  = "bad protocol / cancel";
39         [-6]  = "can't request info until later in exchange";
40         [-7]  = "invalid parameter supplied";
41         [-8]  = "transient failure (e.g., weak key)";
42         [-9]  = "integrity check failed";
43         [-12] = "SASL library not initialized";
44
45         -- client only codes --
46         [2]   = "needs user interaction";
47         [-10] = "server failed mutual authentication step";
48         [-11] = "mechanism doesn't support requested feature";
49
50         -- server only codes --
51         [-13] = "authentication failure";
52         [-14] = "authorization failure";
53         [-15] = "mechanism too weak for this user";
54         [-16] = "encryption needed to use mechanism";
55         [-17] = "One time use of a plaintext password will enable requested mechanism for user";
56         [-18] = "passphrase expired, has to be reset";
57         [-19] = "account disabled";
58         [-20] = "user not found";
59         [-23] = "version mismatch with plug-in";
60         [-24] = "remote authentication server unavailable";
61         [-26] = "user exists, but no verifier for user";
62
63         -- codes for password setting --
64         [-21] = "passphrase locked";
65         [-22] = "requested change was not needed";
66         [-27] = "passphrase is too weak for security policy";
67         [-28] = "user supplied passwords not permitted";
68 };
69 setmetatable(sasl_errstring, { __index = function() return "undefined error!" end });
70
71 module "sasl_cyrus"
72
73 local method = {};
74 method.__index = method;
75 local initialized = false;
76
77 local function init(service_name)
78         if not initialized then
79                 local st, errmsg = pcall(cyrussasl.server_init, service_name);
80                 if st then
81                         initialized = true;
82                 else
83                         log("error", "Failed to initialize Cyrus SASL: %s", errmsg);
84                 end
85         end
86 end
87
88 -- create a new SASL object which can be used to authenticate clients
89 function new(realm, service_name, app_name)
90         local sasl_i = {};
91
92         init(app_name or service_name);
93
94         sasl_i.realm = realm;
95         sasl_i.service_name = service_name;
96
97         local st, ret = pcall(cyrussasl.server_new, service_name, nil, realm, nil, nil)
98         if st then
99                 sasl_i.cyrus = ret;
100         else
101                 log("error", "Creating SASL server connection failed: %s", ret);
102                 return nil;
103         end
104
105         if cyrussasl.set_canon_cb then
106                 local c14n_cb = function (user)
107                         local node = s_match(user, "^([^@]+)");
108                         log("debug", "Canonicalizing username %s to %s", user, node)
109                         return node
110                 end
111                 cyrussasl.set_canon_cb(sasl_i.cyrus, c14n_cb);
112         end
113
114         cyrussasl.setssf(sasl_i.cyrus, 0, 0xffffffff)
115         local s = setmetatable(sasl_i, method);
116         return s;
117 end
118
119 -- get a fresh clone with the same realm, profiles and forbidden mechanisms
120 function method:clean_clone()
121         return new(self.realm, self.service_name)
122 end
123
124 -- set the forbidden mechanisms
125 function method:forbidden( restrict )
126         log("warn", "Called method:forbidden. NOT IMPLEMENTED.")
127         return {}
128 end
129
130 -- get a list of possible SASL mechanims to use
131 function method:mechanisms()
132         local mechanisms = self.mechs;
133         if not mechanisms then
134                 mechanisms = {}
135                 local cyrus_mechs = cyrussasl.listmech(self.cyrus, nil, "", " ", "")
136                 for w in s_gmatch(cyrus_mechs, "[^ ]+") do
137                         mechanisms[w] = true;
138                 end
139                 self.mechs = mechanisms
140         end
141         return mechanisms;
142 end
143
144 -- select a mechanism to use
145 function method:select(mechanism)
146         self.mechanism = mechanism;
147         if not self.mechs then self:mechanisms(); end
148         return self.mechs[mechanism];
149 end
150
151 -- feed new messages to process into the library
152 function method:process(message)
153         local err;
154         local data;
155
156         if self.mechanism then
157                 err, data = cyrussasl.server_start(self.cyrus, self.mechanism, message or "")
158         else
159                 err, data = cyrussasl.server_step(self.cyrus, message or "")
160         end
161
162         self.username = cyrussasl.get_username(self.cyrus)
163
164         if (err == 0) then -- SASL_OK
165            return "success", data
166         elseif (err == 1) then -- SASL_CONTINUE
167            return "challenge", data
168         elseif (err == -4) then -- SASL_NOMECH
169            log("debug", "SASL mechanism not available from remote end")
170            return "failure", "invalid-mechanism", "SASL mechanism not available"
171         elseif (err == -13) then -- SASL_BADAUTH
172            return "failure", "not-authorized", sasl_errstring[err];
173         else
174            log("debug", "Got SASL error condition %d: %s", err, sasl_errstring[err]);
175            return "failure", "undefined-condition", sasl_errstring[err];
176         end
177 end
178
179 return _M;