GPL v2.
[metaproxy-moved-to-github.git] / src / filter_auth_simple.cpp
1 /* $Id: filter_auth_simple.cpp,v 1.23 2007-05-09 21:23:09 adam Exp $
2    Copyright (c) 2005-2007, Index Data.
3
4 This file is part of Metaproxy.
5
6 Metaproxy is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
10
11 Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Metaproxy; see the file LICENSE.  If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.
20  */
21
22 #include "config.hpp"
23
24 #include "filter.hpp"
25 #include "package.hpp"
26
27 #include <boost/thread/mutex.hpp>
28 #include <boost/algorithm/string.hpp>
29
30 #include "util.hpp"
31 #include "filter_auth_simple.hpp"
32
33 #include <yaz/zgdu.h>
34 #include <yaz/diagbib1.h>
35 #include <stdio.h>
36 #include <errno.h>
37
38 namespace mp = metaproxy_1;
39 namespace yf = mp::filter;
40
41 namespace metaproxy_1 {
42     namespace filter {
43         class AuthSimple::Rep {
44             friend class AuthSimple;
45             struct PasswordAndDBs {
46                 std::string password;
47                 std::list<std::string> dbs;
48                 PasswordAndDBs() {};
49                 PasswordAndDBs(std::string pw) : password(pw) {};
50                 void addDB(std::string db) { dbs.push_back(db); }
51             };
52             boost::mutex mutex;
53             bool got_userRegister, got_targetRegister;
54             std::map<std::string, PasswordAndDBs> userRegister;
55             std::map<std::string, std::list<std::string> > targetsByUser;
56             std::map<mp::Session, std::string> userBySession;
57             bool discardUnauthorisedTargets;
58             Rep() { got_userRegister = false;
59                     got_targetRegister = false;
60                     discardUnauthorisedTargets = false; }
61         };
62     }
63 }
64
65 yf::AuthSimple::AuthSimple() : m_p(new Rep)
66 {
67     // nothing to do
68 }
69
70 yf::AuthSimple::~AuthSimple()
71 {  // must have a destructor because of boost::scoped_ptr
72 }
73
74
75 static void die(std::string s) { throw mp::filter::FilterException(s); }
76
77
78 // Read XML config.. Put config info in m_p.
79 void mp::filter::AuthSimple::configure(const xmlNode * ptr)
80 {
81     std::string userRegisterName;
82     std::string targetRegisterName;
83
84     for (ptr = ptr->children; ptr != 0; ptr = ptr->next) {
85         if (ptr->type != XML_ELEMENT_NODE)
86             continue;
87         if (!strcmp((const char *) ptr->name, "userRegister")) {
88             userRegisterName = mp::xml::get_text(ptr);
89             m_p->got_userRegister = true;
90         } else if (!strcmp((const char *) ptr->name, "targetRegister")) {
91             targetRegisterName = mp::xml::get_text(ptr);
92             m_p->got_targetRegister = true;
93         } else if (!strcmp((const char *) ptr->name,
94                            "discardUnauthorisedTargets")) {
95             m_p->discardUnauthorisedTargets = true;
96         } else {
97             die("Bad element in auth_simple: <"
98                 + std::string((const char *) ptr->name) + ">");
99         }
100     }
101
102     if (!m_p->got_userRegister && !m_p->got_targetRegister)
103         die("auth_simple: no user-register or target-register "
104             "filename specified");
105
106     if (m_p->got_userRegister)
107         config_userRegister(userRegisterName);
108     if (m_p->got_targetRegister)
109         config_targetRegister(targetRegisterName);
110 }
111
112
113 void mp::filter::AuthSimple::config_userRegister(std::string filename)
114 {
115     FILE *fp = fopen(filename.c_str(), "r");
116     if (fp == 0)
117         die("can't open auth_simple user-register '" + filename + "': " +
118             strerror(errno));
119
120     char buf[1000];
121     while (fgets(buf, sizeof buf, fp)) {
122         if (*buf == '\n' || *buf == '#')
123             continue;
124         buf[strlen(buf)-1] = 0;
125         char *passwdp = strchr(buf, ':');
126         if (passwdp == 0)
127             die("auth_simple user-register '" + filename + "': " +
128                 "no password on line: '" + buf + "'");
129         *passwdp++ = 0;
130         char *databasesp = strchr(passwdp, ':');
131         if (databasesp == 0)
132             die("auth_simple user-register '" + filename + "': " +
133                 "no databases on line: '" + buf + ":" + passwdp + "'");
134         *databasesp++ = 0;
135         yf::AuthSimple::Rep::PasswordAndDBs tmp(passwdp);
136         boost::split(tmp.dbs, databasesp, boost::is_any_of(","));
137         m_p->userRegister[buf] = tmp;
138
139         if (0) {                // debugging
140             printf("Added user '%s' -> password '%s'\n", buf, passwdp);
141             std::list<std::string>::const_iterator i;
142             for (i = tmp.dbs.begin(); i != tmp.dbs.end(); i++) {
143                 printf("db '%s'\n", (*i).c_str());
144             }
145         }
146     }
147 }
148
149
150 // I feel a little bad about the duplication of code between this and
151 // config_userRegister().  But not bad enough to refactor.
152 //
153 void mp::filter::AuthSimple::config_targetRegister(std::string filename)
154 {
155     FILE *fp = fopen(filename.c_str(), "r");
156     if (fp == 0)
157         die("can't open auth_simple target-register '" + filename + "': " +
158             strerror(errno));
159
160     char buf[1000];
161     while (fgets(buf, sizeof buf, fp)) {
162         if (*buf == '\n' || *buf == '#')
163             continue;
164         buf[strlen(buf)-1] = 0;
165         char *targetsp = strchr(buf, ':');
166         if (targetsp == 0)
167             die("auth_simple target-register '" + filename + "': " +
168                 "no targets on line: '" + buf + "'");
169         *targetsp++ = 0;
170         std::list<std::string> tmp;
171         boost::split(tmp, targetsp, boost::is_any_of(","));
172         m_p->targetsByUser[buf] = tmp;
173
174         if (0) {                // debugging
175             printf("Added user '%s' with targets:\n", buf);
176             std::list<std::string>::const_iterator i;
177             for (i = tmp.begin(); i != tmp.end(); i++) {
178                 printf("\t%s\n", (*i).c_str());
179             }
180         }
181     }
182 }
183
184
185 void yf::AuthSimple::process(mp::Package &package) const
186 {
187     Z_GDU *gdu = package.request().get();
188
189     if (!gdu || gdu->which != Z_GDU_Z3950) {
190         // Pass on the package -- This means that authentication is
191         // waived, which may not be the correct thing for non-Z APDUs
192         // as it means that SRW sessions don't demand authentication
193         return package.move();
194     }
195
196     if (m_p->got_userRegister) {
197         switch (gdu->u.z3950->which) {
198         case Z_APDU_initRequest: return process_init(package);
199         case Z_APDU_searchRequest: return process_search(package);
200         case Z_APDU_scanRequest: return process_scan(package);
201             // In theory, we should check database authorisation for
202             // extended services, too (A) the proxy currently does not
203             // implement XS and turns off its negotiation bit; (B) it
204             // would be insanely complex to do as the top-level XS request
205             // structure does not carry a database name, but it is buried
206             // down in some of the possible EXTERNALs used as
207             // taskSpecificParameters; and (C) since many extended
208             // services modify the database, we'd need to more exotic
209             // authorisation database than we want to support.
210         default: break;
211         }
212     }
213
214     if (m_p->got_targetRegister && gdu->u.z3950->which == Z_APDU_initRequest)
215         return check_targets(package);
216
217     // Operations other than those listed above do not require authorisation
218     return package.move();
219 }
220
221
222 static void reject_init(mp::Package &package, int err, const char *addinfo);
223
224
225 void yf::AuthSimple::process_init(mp::Package &package) const
226 {
227     Z_IdAuthentication *auth =
228         package.request().get()->u.z3950->u.initRequest->idAuthentication;
229         // This is just plain perverted.
230
231     if (!auth)
232         return reject_init(package, 0, "no credentials supplied");
233     if (auth->which != Z_IdAuthentication_idPass)
234         return reject_init(package, 0,
235                            "only idPass authentication is supported");
236     Z_IdPass *idPass = auth->u.idPass;
237
238     if (m_p->userRegister.count(idPass->userId)) {
239         // groupId is ignored, in accordance with ancient tradition.
240         yf::AuthSimple::Rep::PasswordAndDBs pdbs =
241             m_p->userRegister[idPass->userId];
242         if (pdbs.password == idPass->password) {
243             // Success!  Remember who the user is for future reference
244             {
245                 boost::mutex::scoped_lock lock(m_p->mutex);
246                 m_p->userBySession[package.session()] = idPass->userId;
247             }
248             return package.move();
249         }
250     }
251
252     return reject_init(package, 0, "username/password combination rejected");
253 }
254
255
256 // I find it unutterable disappointing that I have to provide this
257 static bool contains(std::list<std::string> list, std::string thing) {
258     std::list<std::string>::const_iterator i;
259     for (i = list.begin(); i != list.end(); i++)
260         if (mp::util::database_name_normalize(*i) == 
261             mp::util::database_name_normalize(thing))
262             return true;
263     
264     return false;
265 }
266
267
268 void yf::AuthSimple::process_search(mp::Package &package) const
269 {
270     Z_SearchRequest *req =
271         package.request().get()->u.z3950->u.searchRequest;
272
273     if (m_p->userBySession.count(package.session()) == 0) {
274         // It's a non-authenticated session, so just accept the operation
275         return package.move();
276     }
277
278     std::string user = m_p->userBySession[package.session()];
279     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
280     for (int i = 0; i < req->num_databaseNames; i++) {
281         if (!contains(pdb.dbs, req->databaseNames[i]) &&
282             !contains(pdb.dbs, "*")) {
283             // Make an Search rejection APDU
284             mp::odr odr;
285             Z_APDU *apdu = odr.create_searchResponse(
286                 package.request().get()->u.z3950, 
287                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
288                 req->databaseNames[i]);
289             package.response() = apdu;
290             package.session().close();
291             return;
292         }
293     }
294
295     // All the requested databases are acceptable
296     return package.move();
297 }
298
299
300 void yf::AuthSimple::process_scan(mp::Package &package) const
301 {
302     Z_ScanRequest *req =
303         package.request().get()->u.z3950->u.scanRequest;
304
305     if (m_p->userBySession.count(package.session()) == 0) {
306         // It's a non-authenticated session, so just accept the operation
307         return package.move();
308     }
309
310     std::string user = m_p->userBySession[package.session()];
311     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
312     for (int i = 0; i < req->num_databaseNames; i++) {
313         if (!contains(pdb.dbs, req->databaseNames[i]) &&
314             !contains(pdb.dbs, "*")) {
315             // Make an Scan rejection APDU
316             mp::odr odr;
317             Z_APDU *apdu = odr.create_scanResponse(
318                 package.request().get()->u.z3950, 
319                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
320                 req->databaseNames[i]);
321             package.response() = apdu;
322             package.session().close();
323             return;
324         }
325     }
326
327     // All the requested databases are acceptable
328     return package.move();
329 }
330
331
332 static void reject_init(mp::Package &package, int err, const char *addinfo) { 
333     if (err == 0)
334         err = YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR;
335     // Make an Init rejection APDU
336     Z_GDU *gdu = package.request().get();
337     mp::odr odr;
338     Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, err, addinfo);
339     apdu->u.initResponse->implementationName = "YP2/YAZ";
340     *apdu->u.initResponse->result = 0; // reject
341     package.response() = apdu;
342     package.session().close();
343 }
344
345
346 void yf::AuthSimple::check_targets(mp::Package & package) const
347 {
348     Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
349
350     Z_IdAuthentication *auth = initReq->idAuthentication;
351     // We only get into this method if we are dealing with a session
352     // that has been authenticated using idPass authentication.  So we
353     // know what kind of information is in the Init Request, and we
354     // can trust the username without needing to re-authenticate.
355     assert(auth->which == Z_IdAuthentication_idPass);
356     std::string user = auth->u.idPass->userId;
357     std::list<std::string> authorisedTargets = m_p->targetsByUser[user];
358
359     std::list<std::string> targets;
360     Z_OtherInformation *otherInfo = initReq->otherInfo;
361     mp::util::get_vhost_otherinfo(otherInfo, targets);
362
363     // Check each of the targets specified in the otherInfo package
364     std::list<std::string>::iterator i;
365
366     i = targets.begin();
367     while (i != targets.end()) {
368         if (contains(authorisedTargets, *i) ||
369             contains(authorisedTargets, "*")) {
370             i++;
371         } else {
372             if (!m_p->discardUnauthorisedTargets)
373                 return reject_init(package,
374                     YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, i->c_str());
375             i = targets.erase(i);
376         }
377     }
378
379     if (targets.size() == 0)
380         return reject_init(package,
381                            YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
382                            // ### It would be better to use the Z-db name
383                            "all databases");
384
385     mp::odr odr;
386     mp::util::set_vhost_otherinfo(&otherInfo, odr, targets);
387     package.move();
388 }
389
390
391 static mp::filter::Base* filter_creator()
392 {
393     return new mp::filter::AuthSimple;
394 }
395
396 extern "C" {
397     struct metaproxy_1_filter_struct metaproxy_1_filter_auth_simple = {
398         0,
399         "auth_simple",
400         filter_creator
401     };
402 }
403
404
405 /*
406  * Local variables:
407  * c-basic-offset: 4
408  * indent-tabs-mode: nil
409  * c-file-style: "stroustrup"
410  * End:
411  * vim: shiftwidth=4 tabstop=8 expandtab
412  */