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