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