1 /* This file is part of Metaproxy.
2 Copyright (C) 2005-2012 Index Data
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
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
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
21 #include <metaproxy/filter.hpp>
22 #include <metaproxy/package.hpp>
24 #include <boost/thread/mutex.hpp>
25 #include <boost/algorithm/string.hpp>
27 #include <metaproxy/util.hpp>
28 #include "filter_auth_simple.hpp"
31 #include <yaz/diagbib1.h>
35 namespace mp = metaproxy_1;
36 namespace yf = mp::filter;
38 namespace metaproxy_1 {
40 class AuthSimple::Rep {
41 friend class AuthSimple;
42 struct PasswordAndDBs {
44 std::list<std::string> dbs;
46 PasswordAndDBs(std::string pw) : password(pw) {};
47 void addDB(std::string db) { dbs.push_back(db); }
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; }
62 yf::AuthSimple::AuthSimple() : m_p(new Rep)
67 yf::AuthSimple::~AuthSimple()
68 { // must have a destructor because of boost::scoped_ptr
72 static void die(std::string s) { throw mp::filter::FilterException(s); }
75 static std::string get_user(Z_InitRequest *initReq, std::string &password)
77 Z_IdAuthentication *auth = initReq->idAuthentication;
84 case Z_IdAuthentication_open:
85 cp = strchr(auth->u.open, '/');
88 user.assign(auth->u.open, cp - auth->u.open);
89 password.assign(cp + 1);
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;
105 // Read XML config.. Put config info in m_p.
106 void mp::filter::AuthSimple::configure(const xmlNode * ptr, bool test_only,
109 std::string userRegisterName;
110 std::string targetRegisterName;
112 for (ptr = ptr->children; ptr != 0; ptr = ptr->next) {
113 if (ptr->type != XML_ELEMENT_NODE)
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;
125 die("Bad element in auth_simple: <"
126 + std::string((const char *) ptr->name) + ">");
130 if (!m_p->got_userRegister && !m_p->got_targetRegister)
131 die("auth_simple: no user-register or target-register "
132 "filename specified");
134 if (m_p->got_userRegister)
135 config_userRegister(userRegisterName);
136 if (m_p->got_targetRegister)
137 config_targetRegister(targetRegisterName);
141 void mp::filter::AuthSimple::config_userRegister(std::string filename)
143 FILE *fp = fopen(filename.c_str(), "r");
145 die("can't open auth_simple user-register '" + filename + "': " +
149 while (fgets(buf, sizeof buf, fp))
151 if (*buf == '\n' || *buf == '#')
153 buf[strlen(buf)-1] = 0;
154 char *passwdp = strchr(buf, ':');
156 die("auth_simple user-register '" + filename + "': " +
157 "no password on line: '" + buf + "'");
159 char *databasesp = strchr(passwdp, ':');
161 die("auth_simple user-register '" + filename + "': " +
162 "no databases on line: '" + buf + ":" + passwdp + "'");
164 yf::AuthSimple::Rep::PasswordAndDBs tmp(passwdp);
165 boost::split(tmp.dbs, databasesp, boost::is_any_of(","));
166 m_p->userRegister[buf] = tmp;
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());
180 // I feel a little bad about the duplication of code between this and
181 // config_userRegister(). But not bad enough to refactor.
183 void mp::filter::AuthSimple::config_targetRegister(std::string filename)
185 FILE *fp = fopen(filename.c_str(), "r");
187 die("can't open auth_simple target-register '" + filename + "': " +
191 while (fgets(buf, sizeof buf, fp)) {
192 if (*buf == '\n' || *buf == '#')
194 buf[strlen(buf)-1] = 0;
195 char *targetsp = strchr(buf, ':');
197 die("auth_simple target-register '" + filename + "': " +
198 "no targets on line: '" + buf + "'");
200 std::list<std::string> tmp;
201 boost::split(tmp, targetsp, boost::is_any_of(","));
202 m_p->targetsByUser[buf] = tmp;
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());
215 void yf::AuthSimple::process(mp::Package &package) const
217 Z_GDU *gdu = package.request().get();
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();
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.
244 if (m_p->got_targetRegister && gdu->u.z3950->which == Z_APDU_initRequest)
245 return check_targets(package);
247 // Operations other than those listed above do not require authorisation
248 return package.move();
252 static void reject_init(mp::Package &package, int err, const char *addinfo);
255 void yf::AuthSimple::process_init(mp::Package &package) const
257 Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
259 std::string password;
260 std::string user = get_user(initReq, password);
262 if (user.length() == 0)
263 return reject_init(package, 0, "no credentials supplied");
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
272 boost::mutex::scoped_lock lock(m_p->mutex);
273 m_p->userBySession[package.session()] = user;
275 return package.move();
279 return reject_init(package, 0, "username/password combination rejected");
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))
295 void yf::AuthSimple::process_search(mp::Package &package) const
297 Z_SearchRequest *req =
298 package.request().get()->u.z3950->u.searchRequest;
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();
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
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();
322 // All the requested databases are acceptable
323 return package.move();
327 void yf::AuthSimple::process_scan(mp::Package &package) const
330 package.request().get()->u.z3950->u.scanRequest;
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();
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
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();
354 // All the requested databases are acceptable
355 return package.move();
359 static void reject_init(mp::Package &package, int err, const char *addinfo) {
361 err = YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR;
362 // Make an Init rejection APDU
363 Z_GDU *gdu = package.request().get();
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();
371 void yf::AuthSimple::check_targets(mp::Package & package) const
373 Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
375 std::string password;
376 std::string user = get_user(initReq, password);
377 std::list<std::string> authorisedTargets = m_p->targetsByUser[user];
379 std::list<std::string> targets;
380 Z_OtherInformation **otherInfo = &initReq->otherInfo;
381 mp::util::remove_vhost_otherinfo(otherInfo, targets);
383 // Check each of the targets specified in the otherInfo package
384 std::list<std::string>::iterator i;
387 while (i != targets.end()) {
388 if (contains(authorisedTargets, *i) ||
389 contains(authorisedTargets, "*")) {
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);
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
405 mp::util::set_vhost_otherinfo(otherInfo, odr, targets);
410 static mp::filter::Base* filter_creator()
412 return new mp::filter::AuthSimple;
416 struct metaproxy_1_filter_struct metaproxy_1_filter_auth_simple = {
427 * c-file-style: "Stroustrup"
428 * indent-tabs-mode: nil
430 * vim: shiftwidth=4 tabstop=8 expandtab