Merge 0.7->trunk
[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 module "sasl_cyrus"
31
32 local method = {};
33 method.__index = method;
34 local initialized = false;
35
36 local function init(service_name)
37         if not initialized then
38                 local st, errmsg = pcall(cyrussasl.server_init, service_name);
39                 if st then
40                         initialized = true;
41                 else
42                         log("error", "Failed to initialize Cyrus SASL: %s", errmsg);
43                 end
44         end
45 end
46
47 -- create a new SASL object which can be used to authenticate clients
48 function new(realm, service_name, app_name)
49         local sasl_i = {};
50
51         init(app_name or service_name);
52
53         sasl_i.realm = realm;
54         sasl_i.service_name = service_name;
55
56         local st, ret = pcall(cyrussasl.server_new, service_name, nil, realm, nil, nil)
57         if st then
58                 sasl_i.cyrus = ret;
59         else
60                 log("error", "Creating SASL server connection failed: %s", ret);
61                 return nil;
62         end
63
64         if cyrussasl.set_canon_cb then
65                 local c14n_cb = function (user)
66                         local node = s_match(user, "^([^@]+)");
67                         log("debug", "Canonicalizing username %s to %s", user, node)
68                         return node
69                 end
70                 cyrussasl.set_canon_cb(sasl_i.cyrus, c14n_cb);
71         end
72
73         cyrussasl.setssf(sasl_i.cyrus, 0, 0xffffffff)
74         local s = setmetatable(sasl_i, method);
75         return s;
76 end
77
78 -- get a fresh clone with the same realm, profiles and forbidden mechanisms
79 function method:clean_clone()
80         return new(self.realm, self.service_name)
81 end
82
83 -- set the forbidden mechanisms
84 function method:forbidden( restrict )
85         log("warn", "Called method:forbidden. NOT IMPLEMENTED.")
86         return {}
87 end
88
89 -- get a list of possible SASL mechanims to use
90 function method:mechanisms()
91         local mechanisms = {}
92         local cyrus_mechs = cyrussasl.listmech(self.cyrus, nil, "", " ", "")
93         for w in s_gmatch(cyrus_mechs, "[^ ]+") do
94                 mechanisms[w] = true;
95         end
96         self.mechs = mechanisms
97         return array.collect(keys(mechanisms));
98 end
99
100 -- select a mechanism to use
101 function method:select(mechanism)
102         self.mechanism = mechanism;
103         if not self.mechs then self:mechanisms(); end
104         return self.mechs[mechanism];
105 end
106
107 -- feed new messages to process into the library
108 function method:process(message)
109         local err;
110         local data;
111
112         if self.mechanism then
113                 err, data = cyrussasl.server_start(self.cyrus, self.mechanism, message or "")
114         else
115                 err, data = cyrussasl.server_step(self.cyrus, message or "")
116         end
117
118         self.username = cyrussasl.get_username(self.cyrus)
119
120         if (err == 0) then -- SASL_OK
121            return "success", data
122         elseif (err == 1) then -- SASL_CONTINUE
123            return "challenge", data
124         elseif (err == -4) then -- SASL_NOMECH
125            log("debug", "SASL mechanism not available from remote end")
126            return "failure", "invalid-mechanism", "SASL mechanism not available"
127         elseif (err == -13) then -- SASL_BADAUTH
128            return "failure", "not-authorized", cyrussasl.get_message( self.cyrus )
129         else
130            log("debug", "Got SASL error condition %d", err)
131            return "failure", "undefined-condition", cyrussasl.get_message( self.cyrus )
132         end
133 end
134
135 return _M;