auth_simple: allow both idPass and open auth
[metaproxy-moved-to-github.git] / src / filter_auth_simple.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 2005-2012 Index Data
3
4 Metaproxy is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17 */
18
19 #include "config.hpp"
20
21 #include <metaproxy/filter.hpp>
22 #include <metaproxy/package.hpp>
23
24 #include <boost/thread/mutex.hpp>
25 #include <boost/algorithm/string.hpp>
26
27 #include <metaproxy/util.hpp>
28 #include "filter_auth_simple.hpp"
29
30 #include <yaz/zgdu.h>
31 #include <yaz/diagbib1.h>
32 #include <stdio.h>
33 #include <errno.h>
34
35 namespace mp = metaproxy_1;
36 namespace yf = mp::filter;
37
38 namespace metaproxy_1 {
39     namespace filter {
40         class AuthSimple::Rep {
41             friend class AuthSimple;
42             struct PasswordAndDBs {
43                 std::string password;
44                 std::list<std::string> dbs;
45                 PasswordAndDBs() {};
46                 PasswordAndDBs(std::string pw) : password(pw) {};
47                 void addDB(std::string db) { dbs.push_back(db); }
48             };
49             boost::mutex mutex;
50             bool got_userRegister, got_targetRegister;
51             std::map<std::string, PasswordAndDBs> userRegister;
52             std::map<std::string, std::list<std::string> > targetsByUser;
53             std::map<mp::Session, std::string> userBySession;
54             bool discardUnauthorisedTargets;
55             Rep() { got_userRegister = false;
56                     got_targetRegister = false;
57                     discardUnauthorisedTargets = false; }
58         };
59     }
60 }
61
62 yf::AuthSimple::AuthSimple() : m_p(new Rep)
63 {
64     // nothing to do
65 }
66
67 yf::AuthSimple::~AuthSimple()
68 {  // must have a destructor because of boost::scoped_ptr
69 }
70
71
72 static void die(std::string s) { throw mp::filter::FilterException(s); }
73
74
75 // Read XML config.. Put config info in m_p.
76 void mp::filter::AuthSimple::configure(const xmlNode * ptr, bool test_only,
77                                        const char *path)
78 {
79     std::string userRegisterName;
80     std::string targetRegisterName;
81
82     for (ptr = ptr->children; ptr != 0; ptr = ptr->next) {
83         if (ptr->type != XML_ELEMENT_NODE)
84             continue;
85         if (!strcmp((const char *) ptr->name, "userRegister")) {
86             userRegisterName = mp::xml::get_text(ptr);
87             m_p->got_userRegister = true;
88         } else if (!strcmp((const char *) ptr->name, "targetRegister")) {
89             targetRegisterName = mp::xml::get_text(ptr);
90             m_p->got_targetRegister = true;
91         } else if (!strcmp((const char *) ptr->name,
92                            "discardUnauthorisedTargets")) {
93             m_p->discardUnauthorisedTargets = true;
94         } else {
95             die("Bad element in auth_simple: <"
96                 + std::string((const char *) ptr->name) + ">");
97         }
98     }
99
100     if (!m_p->got_userRegister && !m_p->got_targetRegister)
101         die("auth_simple: no user-register or target-register "
102             "filename specified");
103
104     if (m_p->got_userRegister)
105         config_userRegister(userRegisterName);
106     if (m_p->got_targetRegister)
107         config_targetRegister(targetRegisterName);
108 }
109
110
111 void mp::filter::AuthSimple::config_userRegister(std::string filename)
112 {
113     FILE *fp = fopen(filename.c_str(), "r");
114     if (fp == 0)
115         die("can't open auth_simple user-register '" + filename + "': " +
116             strerror(errno));
117
118     char buf[1000];
119     while (fgets(buf, sizeof buf, fp))
120     {
121         if (*buf == '\n' || *buf == '#')
122             continue;
123         buf[strlen(buf)-1] = 0;
124         char *passwdp = strchr(buf, ':');
125         if (passwdp == 0)
126             die("auth_simple user-register '" + filename + "': " +
127                 "no password on line: '" + buf + "'");
128         *passwdp++ = 0;
129         char *databasesp = strchr(passwdp, ':');
130         if (databasesp == 0)
131             die("auth_simple user-register '" + filename + "': " +
132                 "no databases on line: '" + buf + ":" + passwdp + "'");
133         *databasesp++ = 0;
134         yf::AuthSimple::Rep::PasswordAndDBs tmp(passwdp);
135         boost::split(tmp.dbs, databasesp, boost::is_any_of(","));
136         m_p->userRegister[buf] = tmp;
137
138         if (0)
139         {                // 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     fclose(fp);
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_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
228
229     std::string password;
230     std::string user = get_user(initReq, password);
231
232     if (user.length() == 0)
233         return reject_init(package, 0, "no credentials supplied");
234
235     if (m_p->userRegister.count(user)) {
236         // groupId is ignored, in accordance with ancient tradition.
237         yf::AuthSimple::Rep::PasswordAndDBs pdbs =
238             m_p->userRegister[user];
239         if (pdbs.password == password) {
240             // Success!  Remember who the user is for future reference
241             {
242                 boost::mutex::scoped_lock lock(m_p->mutex);
243                 m_p->userBySession[package.session()] = user;
244             }
245             return package.move();
246         }
247     }
248
249     return reject_init(package, 0, "username/password combination rejected");
250 }
251
252
253 // I find it unutterable disappointing that I have to provide this
254 static bool contains(std::list<std::string> list, std::string thing) {
255     std::list<std::string>::const_iterator i;
256     for (i = list.begin(); i != list.end(); i++)
257         if (mp::util::database_name_normalize(*i) ==
258             mp::util::database_name_normalize(thing))
259             return true;
260
261     return false;
262 }
263
264
265 void yf::AuthSimple::process_search(mp::Package &package) const
266 {
267     Z_SearchRequest *req =
268         package.request().get()->u.z3950->u.searchRequest;
269
270     if (m_p->userBySession.count(package.session()) == 0) {
271         // It's a non-authenticated session, so just accept the operation
272         return package.move();
273     }
274
275     std::string user = m_p->userBySession[package.session()];
276     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
277     for (int i = 0; i < req->num_databaseNames; i++) {
278         if (!contains(pdb.dbs, req->databaseNames[i]) &&
279             !contains(pdb.dbs, "*")) {
280             // Make an Search rejection APDU
281             mp::odr odr;
282             Z_APDU *apdu = odr.create_searchResponse(
283                 package.request().get()->u.z3950,
284                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
285                 req->databaseNames[i]);
286             package.response() = apdu;
287             package.session().close();
288             return;
289         }
290     }
291
292     // All the requested databases are acceptable
293     return package.move();
294 }
295
296
297 void yf::AuthSimple::process_scan(mp::Package &package) const
298 {
299     Z_ScanRequest *req =
300         package.request().get()->u.z3950->u.scanRequest;
301
302     if (m_p->userBySession.count(package.session()) == 0) {
303         // It's a non-authenticated session, so just accept the operation
304         return package.move();
305     }
306
307     std::string user = m_p->userBySession[package.session()];
308     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
309     for (int i = 0; i < req->num_databaseNames; i++) {
310         if (!contains(pdb.dbs, req->databaseNames[i]) &&
311             !contains(pdb.dbs, "*")) {
312             // Make an Scan rejection APDU
313             mp::odr odr;
314             Z_APDU *apdu = odr.create_scanResponse(
315                 package.request().get()->u.z3950,
316                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
317                 req->databaseNames[i]);
318             package.response() = apdu;
319             package.session().close();
320             return;
321         }
322     }
323
324     // All the requested databases are acceptable
325     return package.move();
326 }
327
328
329 static void reject_init(mp::Package &package, int err, const char *addinfo) {
330     if (err == 0)
331         err = YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR;
332     // Make an Init rejection APDU
333     Z_GDU *gdu = package.request().get();
334     mp::odr odr;
335     Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, err, addinfo);
336     *apdu->u.initResponse->result = 0; // reject
337     package.response() = apdu;
338     package.session().close();
339 }
340
341 std::string yf::AuthSimple::get_user(Z_InitRequest *initReq,
342                                      std::string &password) const
343 {
344     Z_IdAuthentication *auth = initReq->idAuthentication;
345     std::string user;
346     if (auth)
347     {
348         const char *cp;
349         switch (auth->which)
350         {
351         case Z_IdAuthentication_open:
352             cp = strchr(auth->u.open, '/');
353             if (cp)
354             {
355                 user.assign(auth->u.open, cp - auth->u.open);
356                 password.assign(cp + 1);
357             }
358             else
359                 user = auth->u.open;
360             break;
361         case Z_IdAuthentication_idPass:
362             if (auth->u.idPass->userId)
363                 user = auth->u.idPass->userId;
364             if (auth->u.idPass->password)
365                 password = auth->u.idPass->password;
366             break;
367         }
368     }
369     return user;
370 }
371
372 void yf::AuthSimple::check_targets(mp::Package & package) const
373 {
374     Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
375
376     std::string password;
377     std::string user = get_user(initReq, password);
378     std::list<std::string> authorisedTargets = m_p->targetsByUser[user];
379
380     std::list<std::string> targets;
381     Z_OtherInformation **otherInfo = &initReq->otherInfo;
382     mp::util::remove_vhost_otherinfo(otherInfo, targets);
383
384     // Check each of the targets specified in the otherInfo package
385     std::list<std::string>::iterator i;
386
387     i = targets.begin();
388     while (i != targets.end()) {
389         if (contains(authorisedTargets, *i) ||
390             contains(authorisedTargets, "*")) {
391             i++;
392         } else {
393             if (!m_p->discardUnauthorisedTargets)
394                 return reject_init(package,
395                     YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, i->c_str());
396             i = targets.erase(i);
397         }
398     }
399
400     if (targets.size() == 0)
401         return reject_init(package,
402                            YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
403                            // ### It would be better to use the Z-db name
404                            "all databases");
405     mp::odr odr;
406     mp::util::set_vhost_otherinfo(otherInfo, odr, targets);
407     package.move();
408 }
409
410
411 static mp::filter::Base* filter_creator()
412 {
413     return new mp::filter::AuthSimple;
414 }
415
416 extern "C" {
417     struct metaproxy_1_filter_struct metaproxy_1_filter_auth_simple = {
418         0,
419         "auth_simple",
420         filter_creator
421     };
422 }
423
424
425 /*
426  * Local variables:
427  * c-basic-offset: 4
428  * c-file-style: "Stroustrup"
429  * indent-tabs-mode: nil
430  * End:
431  * vim: shiftwidth=4 tabstop=8 expandtab
432  */
433