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 // Read XML config.. Put config info in m_p.
76 void mp::filter::AuthSimple::configure(const xmlNode * ptr, bool test_only,
79 std::string userRegisterName;
80 std::string targetRegisterName;
82 for (ptr = ptr->children; ptr != 0; ptr = ptr->next) {
83 if (ptr->type != XML_ELEMENT_NODE)
85 if (!strcmp((const char *) ptr->name, "userRegister")) {
86 userRegisterName = mp::xml::get_text(ptr);
87 m_p->got_userRegister = true;
88 } else if (!strcmp((const char *) ptr->name, "targetRegister")) {
89 targetRegisterName = mp::xml::get_text(ptr);
90 m_p->got_targetRegister = true;
91 } else if (!strcmp((const char *) ptr->name,
92 "discardUnauthorisedTargets")) {
93 m_p->discardUnauthorisedTargets = true;
95 die("Bad element in auth_simple: <"
96 + std::string((const char *) ptr->name) + ">");
100 if (!m_p->got_userRegister && !m_p->got_targetRegister)
101 die("auth_simple: no user-register or target-register "
102 "filename specified");
104 if (m_p->got_userRegister)
105 config_userRegister(userRegisterName);
106 if (m_p->got_targetRegister)
107 config_targetRegister(targetRegisterName);
111 void mp::filter::AuthSimple::config_userRegister(std::string filename)
113 FILE *fp = fopen(filename.c_str(), "r");
115 die("can't open auth_simple user-register '" + filename + "': " +
119 while (fgets(buf, sizeof buf, fp))
121 if (*buf == '\n' || *buf == '#')
123 buf[strlen(buf)-1] = 0;
124 char *passwdp = strchr(buf, ':');
126 die("auth_simple user-register '" + filename + "': " +
127 "no password on line: '" + buf + "'");
129 char *databasesp = strchr(passwdp, ':');
131 die("auth_simple user-register '" + filename + "': " +
132 "no databases on line: '" + buf + ":" + passwdp + "'");
134 yf::AuthSimple::Rep::PasswordAndDBs tmp(passwdp);
135 boost::split(tmp.dbs, databasesp, boost::is_any_of(","));
136 m_p->userRegister[buf] = tmp;
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->result = 0; // reject
340 package.response() = apdu;
341 package.session().close();
345 void yf::AuthSimple::check_targets(mp::Package & package) const
347 Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
349 Z_IdAuthentication *auth = initReq->idAuthentication;
350 // We only get into this method if we are dealing with a session
351 // that has been authenticated using idPass authentication. So we
352 // know what kind of information is in the Init Request, and we
353 // can trust the username without needing to re-authenticate.
354 assert(auth->which == Z_IdAuthentication_idPass);
355 std::string user = auth->u.idPass->userId;
356 std::list<std::string> authorisedTargets = m_p->targetsByUser[user];
358 std::list<std::string> targets;
359 Z_OtherInformation **otherInfo = &initReq->otherInfo;
360 mp::util::remove_vhost_otherinfo(otherInfo, targets);
362 // Check each of the targets specified in the otherInfo package
363 std::list<std::string>::iterator i;
366 while (i != targets.end()) {
367 if (contains(authorisedTargets, *i) ||
368 contains(authorisedTargets, "*")) {
371 if (!m_p->discardUnauthorisedTargets)
372 return reject_init(package,
373 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, i->c_str());
374 i = targets.erase(i);
378 if (targets.size() == 0)
379 return reject_init(package,
380 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
381 // ### It would be better to use the Z-db name
384 mp::util::set_vhost_otherinfo(otherInfo, odr, targets);
389 static mp::filter::Base* filter_creator()
391 return new mp::filter::AuthSimple;
395 struct metaproxy_1_filter_struct metaproxy_1_filter_auth_simple = {
406 * c-file-style: "Stroustrup"
407 * indent-tabs-mode: nil
409 * vim: shiftwidth=4 tabstop=8 expandtab