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