Reformat: delete trailing whitespace
[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_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->result = 0; // reject
340     package.response() = apdu;
341     package.session().close();
342 }
343
344
345 void yf::AuthSimple::check_targets(mp::Package & package) const
346 {
347     Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
348
349     Z_IdAuthentication *auth = initReq->idAuthentication;
350     // We only get into this method if we are dealing with a session
351     // that has been authenticated using idPass authentication.  So we
352     // know what kind of information is in the Init Request, and we
353     // can trust the username without needing to re-authenticate.
354     assert(auth->which == Z_IdAuthentication_idPass);
355     std::string user = auth->u.idPass->userId;
356     std::list<std::string> authorisedTargets = m_p->targetsByUser[user];
357
358     std::list<std::string> targets;
359     Z_OtherInformation **otherInfo = &initReq->otherInfo;
360     mp::util::remove_vhost_otherinfo(otherInfo, targets);
361
362     // Check each of the targets specified in the otherInfo package
363     std::list<std::string>::iterator i;
364
365     i = targets.begin();
366     while (i != targets.end()) {
367         if (contains(authorisedTargets, *i) ||
368             contains(authorisedTargets, "*")) {
369             i++;
370         } else {
371             if (!m_p->discardUnauthorisedTargets)
372                 return reject_init(package,
373                     YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, i->c_str());
374             i = targets.erase(i);
375         }
376     }
377
378     if (targets.size() == 0)
379         return reject_init(package,
380                            YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
381                            // ### It would be better to use the Z-db name
382                            "all databases");
383     mp::odr odr;
384     mp::util::set_vhost_otherinfo(otherInfo, odr, targets);
385     package.move();
386 }
387
388
389 static mp::filter::Base* filter_creator()
390 {
391     return new mp::filter::AuthSimple;
392 }
393
394 extern "C" {
395     struct metaproxy_1_filter_struct metaproxy_1_filter_auth_simple = {
396         0,
397         "auth_simple",
398         filter_creator
399     };
400 }
401
402
403 /*
404  * Local variables:
405  * c-basic-offset: 4
406  * c-file-style: "Stroustrup"
407  * indent-tabs-mode: nil
408  * End:
409  * vim: shiftwidth=4 tabstop=8 expandtab
410  */
411