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