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