1 /* $Id: filter_auth_simple.cpp,v 1.25 2008-02-20 15:07:51 adam Exp $
2 Copyright (c) 2005-2007, Index Data.
4 This file is part of Metaproxy.
6 Metaproxy is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
11 Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with Metaproxy; see the file LICENSE. If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
25 #include "package.hpp"
27 #include <boost/thread/mutex.hpp>
28 #include <boost/algorithm/string.hpp>
31 #include "filter_auth_simple.hpp"
34 #include <yaz/diagbib1.h>
38 namespace mp = metaproxy_1;
39 namespace yf = mp::filter;
41 namespace metaproxy_1 {
43 class AuthSimple::Rep {
44 friend class AuthSimple;
45 struct PasswordAndDBs {
47 std::list<std::string> dbs;
49 PasswordAndDBs(std::string pw) : password(pw) {};
50 void addDB(std::string db) { dbs.push_back(db); }
53 bool got_userRegister, got_targetRegister;
54 std::map<std::string, PasswordAndDBs> userRegister;
55 std::map<std::string, std::list<std::string> > targetsByUser;
56 std::map<mp::Session, std::string> userBySession;
57 bool discardUnauthorisedTargets;
58 Rep() { got_userRegister = false;
59 got_targetRegister = false;
60 discardUnauthorisedTargets = false; }
65 yf::AuthSimple::AuthSimple() : m_p(new Rep)
70 yf::AuthSimple::~AuthSimple()
71 { // must have a destructor because of boost::scoped_ptr
75 static void die(std::string s) { throw mp::filter::FilterException(s); }
78 // Read XML config.. Put config info in m_p.
79 void mp::filter::AuthSimple::configure(const xmlNode * ptr, bool test_only)
81 std::string userRegisterName;
82 std::string targetRegisterName;
84 for (ptr = ptr->children; ptr != 0; ptr = ptr->next) {
85 if (ptr->type != XML_ELEMENT_NODE)
87 if (!strcmp((const char *) ptr->name, "userRegister")) {
88 userRegisterName = mp::xml::get_text(ptr);
89 m_p->got_userRegister = true;
90 } else if (!strcmp((const char *) ptr->name, "targetRegister")) {
91 targetRegisterName = mp::xml::get_text(ptr);
92 m_p->got_targetRegister = true;
93 } else if (!strcmp((const char *) ptr->name,
94 "discardUnauthorisedTargets")) {
95 m_p->discardUnauthorisedTargets = true;
97 die("Bad element in auth_simple: <"
98 + std::string((const char *) ptr->name) + ">");
102 if (!m_p->got_userRegister && !m_p->got_targetRegister)
103 die("auth_simple: no user-register or target-register "
104 "filename specified");
106 if (m_p->got_userRegister)
107 config_userRegister(userRegisterName);
108 if (m_p->got_targetRegister)
109 config_targetRegister(targetRegisterName);
113 void mp::filter::AuthSimple::config_userRegister(std::string filename)
115 FILE *fp = fopen(filename.c_str(), "r");
117 die("can't open auth_simple user-register '" + filename + "': " +
121 while (fgets(buf, sizeof buf, fp)) {
122 if (*buf == '\n' || *buf == '#')
124 buf[strlen(buf)-1] = 0;
125 char *passwdp = strchr(buf, ':');
127 die("auth_simple user-register '" + filename + "': " +
128 "no password on line: '" + buf + "'");
130 char *databasesp = strchr(passwdp, ':');
132 die("auth_simple user-register '" + filename + "': " +
133 "no databases on line: '" + buf + ":" + passwdp + "'");
135 yf::AuthSimple::Rep::PasswordAndDBs tmp(passwdp);
136 boost::split(tmp.dbs, databasesp, boost::is_any_of(","));
137 m_p->userRegister[buf] = tmp;
139 if (0) { // debugging
140 printf("Added user '%s' -> password '%s'\n", buf, passwdp);
141 std::list<std::string>::const_iterator i;
142 for (i = tmp.dbs.begin(); i != tmp.dbs.end(); i++) {
143 printf("db '%s'\n", (*i).c_str());
150 // I feel a little bad about the duplication of code between this and
151 // config_userRegister(). But not bad enough to refactor.
153 void mp::filter::AuthSimple::config_targetRegister(std::string filename)
155 FILE *fp = fopen(filename.c_str(), "r");
157 die("can't open auth_simple target-register '" + filename + "': " +
161 while (fgets(buf, sizeof buf, fp)) {
162 if (*buf == '\n' || *buf == '#')
164 buf[strlen(buf)-1] = 0;
165 char *targetsp = strchr(buf, ':');
167 die("auth_simple target-register '" + filename + "': " +
168 "no targets on line: '" + buf + "'");
170 std::list<std::string> tmp;
171 boost::split(tmp, targetsp, boost::is_any_of(","));
172 m_p->targetsByUser[buf] = tmp;
174 if (0) { // debugging
175 printf("Added user '%s' with targets:\n", buf);
176 std::list<std::string>::const_iterator i;
177 for (i = tmp.begin(); i != tmp.end(); i++) {
178 printf("\t%s\n", (*i).c_str());
185 void yf::AuthSimple::process(mp::Package &package) const
187 Z_GDU *gdu = package.request().get();
189 if (!gdu || gdu->which != Z_GDU_Z3950) {
190 // Pass on the package -- This means that authentication is
191 // waived, which may not be the correct thing for non-Z APDUs
192 // as it means that SRW sessions don't demand authentication
193 return package.move();
196 if (m_p->got_userRegister) {
197 switch (gdu->u.z3950->which) {
198 case Z_APDU_initRequest: return process_init(package);
199 case Z_APDU_searchRequest: return process_search(package);
200 case Z_APDU_scanRequest: return process_scan(package);
201 // In theory, we should check database authorisation for
202 // extended services, too (A) the proxy currently does not
203 // implement XS and turns off its negotiation bit; (B) it
204 // would be insanely complex to do as the top-level XS request
205 // structure does not carry a database name, but it is buried
206 // down in some of the possible EXTERNALs used as
207 // taskSpecificParameters; and (C) since many extended
208 // services modify the database, we'd need to more exotic
209 // authorisation database than we want to support.
214 if (m_p->got_targetRegister && gdu->u.z3950->which == Z_APDU_initRequest)
215 return check_targets(package);
217 // Operations other than those listed above do not require authorisation
218 return package.move();
222 static void reject_init(mp::Package &package, int err, const char *addinfo);
225 void yf::AuthSimple::process_init(mp::Package &package) const
227 Z_IdAuthentication *auth =
228 package.request().get()->u.z3950->u.initRequest->idAuthentication;
229 // This is just plain perverted.
232 return reject_init(package, 0, "no credentials supplied");
233 if (auth->which != Z_IdAuthentication_idPass)
234 return reject_init(package, 0,
235 "only idPass authentication is supported");
236 Z_IdPass *idPass = auth->u.idPass;
238 if (m_p->userRegister.count(idPass->userId)) {
239 // groupId is ignored, in accordance with ancient tradition.
240 yf::AuthSimple::Rep::PasswordAndDBs pdbs =
241 m_p->userRegister[idPass->userId];
242 if (pdbs.password == idPass->password) {
243 // Success! Remember who the user is for future reference
245 boost::mutex::scoped_lock lock(m_p->mutex);
246 m_p->userBySession[package.session()] = idPass->userId;
248 return package.move();
252 return reject_init(package, 0, "username/password combination rejected");
256 // I find it unutterable disappointing that I have to provide this
257 static bool contains(std::list<std::string> list, std::string thing) {
258 std::list<std::string>::const_iterator i;
259 for (i = list.begin(); i != list.end(); i++)
260 if (mp::util::database_name_normalize(*i) ==
261 mp::util::database_name_normalize(thing))
268 void yf::AuthSimple::process_search(mp::Package &package) const
270 Z_SearchRequest *req =
271 package.request().get()->u.z3950->u.searchRequest;
273 if (m_p->userBySession.count(package.session()) == 0) {
274 // It's a non-authenticated session, so just accept the operation
275 return package.move();
278 std::string user = m_p->userBySession[package.session()];
279 yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
280 for (int i = 0; i < req->num_databaseNames; i++) {
281 if (!contains(pdb.dbs, req->databaseNames[i]) &&
282 !contains(pdb.dbs, "*")) {
283 // Make an Search rejection APDU
285 Z_APDU *apdu = odr.create_searchResponse(
286 package.request().get()->u.z3950,
287 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
288 req->databaseNames[i]);
289 package.response() = apdu;
290 package.session().close();
295 // All the requested databases are acceptable
296 return package.move();
300 void yf::AuthSimple::process_scan(mp::Package &package) const
303 package.request().get()->u.z3950->u.scanRequest;
305 if (m_p->userBySession.count(package.session()) == 0) {
306 // It's a non-authenticated session, so just accept the operation
307 return package.move();
310 std::string user = m_p->userBySession[package.session()];
311 yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
312 for (int i = 0; i < req->num_databaseNames; i++) {
313 if (!contains(pdb.dbs, req->databaseNames[i]) &&
314 !contains(pdb.dbs, "*")) {
315 // Make an Scan rejection APDU
317 Z_APDU *apdu = odr.create_scanResponse(
318 package.request().get()->u.z3950,
319 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
320 req->databaseNames[i]);
321 package.response() = apdu;
322 package.session().close();
327 // All the requested databases are acceptable
328 return package.move();
332 static void reject_init(mp::Package &package, int err, const char *addinfo) {
334 err = YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR;
335 // Make an Init rejection APDU
336 Z_GDU *gdu = package.request().get();
338 Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, err, addinfo);
339 apdu->u.initResponse->implementationName = "YP2/YAZ";
340 *apdu->u.initResponse->result = 0; // reject
341 package.response() = apdu;
342 package.session().close();
346 void yf::AuthSimple::check_targets(mp::Package & package) const
348 Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
350 Z_IdAuthentication *auth = initReq->idAuthentication;
351 // We only get into this method if we are dealing with a session
352 // that has been authenticated using idPass authentication. So we
353 // know what kind of information is in the Init Request, and we
354 // can trust the username without needing to re-authenticate.
355 assert(auth->which == Z_IdAuthentication_idPass);
356 std::string user = auth->u.idPass->userId;
357 std::list<std::string> authorisedTargets = m_p->targetsByUser[user];
359 std::list<std::string> targets;
360 Z_OtherInformation **otherInfo = &initReq->otherInfo;
361 mp::util::remove_vhost_otherinfo(otherInfo, targets);
363 // Check each of the targets specified in the otherInfo package
364 std::list<std::string>::iterator i;
367 while (i != targets.end()) {
368 if (contains(authorisedTargets, *i) ||
369 contains(authorisedTargets, "*")) {
372 if (!m_p->discardUnauthorisedTargets)
373 return reject_init(package,
374 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, i->c_str());
375 i = targets.erase(i);
379 if (targets.size() == 0)
380 return reject_init(package,
381 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
382 // ### It would be better to use the Z-db name
385 mp::util::set_vhost_otherinfo(otherInfo, odr, targets);
390 static mp::filter::Base* filter_creator()
392 return new mp::filter::AuthSimple;
396 struct metaproxy_1_filter_struct metaproxy_1_filter_auth_simple = {
407 * indent-tabs-mode: nil
408 * c-file-style: "stroustrup"
410 * vim: shiftwidth=4 tabstop=8 expandtab