Add LICENSE file and Refer to it from the source. Include license material
[metaproxy-moved-to-github.git] / src / filter_auth_simple.cpp
1 /* $Id: filter_auth_simple.cpp,v 1.20 2006-06-10 14:29:12 adam Exp $
2    Copyright (c) 2005-2006, Index Data.
3
4    See the LICENSE file for details
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 (mp::util::database_name_normalize(*i) == 
246             mp::util::database_name_normalize(thing))
247             return true;
248     
249     return false;
250 }
251
252
253 void yf::AuthSimple::process_search(mp::Package &package) const
254 {
255     Z_SearchRequest *req =
256         package.request().get()->u.z3950->u.searchRequest;
257
258     if (m_p->userBySession.count(package.session()) == 0) {
259         // It's a non-authenticated session, so just accept the operation
260         return package.move();
261     }
262
263     std::string user = m_p->userBySession[package.session()];
264     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
265     for (int i = 0; i < req->num_databaseNames; i++) {
266         if (!contains(pdb.dbs, req->databaseNames[i]) &&
267             !contains(pdb.dbs, "*")) {
268             // Make an Search rejection APDU
269             mp::odr odr;
270             Z_APDU *apdu = odr.create_searchResponse(
271                 package.request().get()->u.z3950, 
272                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
273                 req->databaseNames[i]);
274             package.response() = apdu;
275             package.session().close();
276             return;
277         }
278     }
279
280     // All the requested databases are acceptable
281     return package.move();
282 }
283
284
285 void yf::AuthSimple::process_scan(mp::Package &package) const
286 {
287     Z_ScanRequest *req =
288         package.request().get()->u.z3950->u.scanRequest;
289
290     if (m_p->userBySession.count(package.session()) == 0) {
291         // It's a non-authenticated session, so just accept the operation
292         return package.move();
293     }
294
295     std::string user = m_p->userBySession[package.session()];
296     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
297     for (int i = 0; i < req->num_databaseNames; i++) {
298         if (!contains(pdb.dbs, req->databaseNames[i]) &&
299             !contains(pdb.dbs, "*")) {
300             // Make an Scan rejection APDU
301             mp::odr odr;
302             Z_APDU *apdu = odr.create_scanResponse(
303                 package.request().get()->u.z3950, 
304                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
305                 req->databaseNames[i]);
306             package.response() = apdu;
307             package.session().close();
308             return;
309         }
310     }
311
312     // All the requested databases are acceptable
313     return package.move();
314 }
315
316
317 static void reject_init(mp::Package &package, int err, const char *addinfo) { 
318     if (err == 0)
319         err = YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR;
320     // Make an Init rejection APDU
321     Z_GDU *gdu = package.request().get();
322     mp::odr odr;
323     Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, err, addinfo);
324     apdu->u.initResponse->implementationName = "YP2/YAZ";
325     *apdu->u.initResponse->result = 0; // reject
326     package.response() = apdu;
327     package.session().close();
328 }
329
330
331 void yf::AuthSimple::check_targets(mp::Package & package) const
332 {
333     Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
334
335     Z_IdAuthentication *auth = initReq->idAuthentication;
336     // We only get into this method if we are dealing with a session
337     // that has been authenticated using idPass authentication.  So we
338     // know what kind of information is in the Init Request, and we
339     // can trust the username without needing to re-authenticate.
340     assert(auth->which == Z_IdAuthentication_idPass);
341     std::string user = auth->u.idPass->userId;
342     std::list<std::string> authorisedTargets = m_p->targetsByUser[user];
343
344     std::list<std::string> targets;
345     Z_OtherInformation *otherInfo = initReq->otherInfo;
346     mp::util::get_vhost_otherinfo(&otherInfo, 1, targets);
347
348     // Check each of the targets specified in the otherInfo package
349     std::list<std::string>::iterator i;
350
351     i = targets.begin();
352     while (i != targets.end()) {
353         if (contains(authorisedTargets, *i) ||
354             contains(authorisedTargets, "*")) {
355             i++;
356         } else {
357             if (!m_p->discardUnauthorisedTargets)
358                 return reject_init(package,
359                     YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, i->c_str());
360             i = targets.erase(i);
361         }
362     }
363
364     if (targets.size() == 0)
365         return reject_init(package,
366                            YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
367                            // ### It would be better to use the Z-db name
368                            "all databases");
369
370     mp::odr odr;
371     mp::util::set_vhost_otherinfo(&otherInfo, odr, targets);
372     package.move();
373 }
374
375
376 static mp::filter::Base* filter_creator()
377 {
378     return new mp::filter::AuthSimple;
379 }
380
381 extern "C" {
382     struct metaproxy_1_filter_struct metaproxy_1_filter_auth_simple = {
383         0,
384         "auth_simple",
385         filter_creator
386     };
387 }
388
389
390 /*
391  * Local variables:
392  * c-basic-offset: 4
393  * indent-tabs-mode: nil
394  * c-file-style: "stroustrup"
395  * End:
396  * vim: shiftwidth=4 tabstop=8 expandtab
397  */