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