1 /* This file is part of Metaproxy.
2 Copyright (C) 2005-2011 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)
78 std::string userRegisterName;
79 std::string targetRegisterName;
81 for (ptr = ptr->children; ptr != 0; ptr = ptr->next) {
82 if (ptr->type != XML_ELEMENT_NODE)
84 if (!strcmp((const char *) ptr->name, "userRegister")) {
85 userRegisterName = mp::xml::get_text(ptr);
86 m_p->got_userRegister = true;
87 } else if (!strcmp((const char *) ptr->name, "targetRegister")) {
88 targetRegisterName = mp::xml::get_text(ptr);
89 m_p->got_targetRegister = true;
90 } else if (!strcmp((const char *) ptr->name,
91 "discardUnauthorisedTargets")) {
92 m_p->discardUnauthorisedTargets = true;
94 die("Bad element in auth_simple: <"
95 + std::string((const char *) ptr->name) + ">");
99 if (!m_p->got_userRegister && !m_p->got_targetRegister)
100 die("auth_simple: no user-register or target-register "
101 "filename specified");
103 if (m_p->got_userRegister)
104 config_userRegister(userRegisterName);
105 if (m_p->got_targetRegister)
106 config_targetRegister(targetRegisterName);
110 void mp::filter::AuthSimple::config_userRegister(std::string filename)
112 FILE *fp = fopen(filename.c_str(), "r");
114 die("can't open auth_simple user-register '" + filename + "': " +
118 while (fgets(buf, sizeof buf, fp))
120 if (*buf == '\n' || *buf == '#')
122 buf[strlen(buf)-1] = 0;
123 char *passwdp = strchr(buf, ':');
125 die("auth_simple user-register '" + filename + "': " +
126 "no password on line: '" + buf + "'");
128 char *databasesp = strchr(passwdp, ':');
130 die("auth_simple user-register '" + filename + "': " +
131 "no databases on line: '" + buf + ":" + passwdp + "'");
133 yf::AuthSimple::Rep::PasswordAndDBs tmp(passwdp);
134 boost::split(tmp.dbs, databasesp, boost::is_any_of(","));
135 m_p->userRegister[buf] = tmp;
139 printf("Added user '%s' -> password '%s'\n", buf, passwdp);
140 std::list<std::string>::const_iterator i;
141 for (i = tmp.dbs.begin(); i != tmp.dbs.end(); i++)
142 printf("db '%s'\n", (*i).c_str());
149 // I feel a little bad about the duplication of code between this and
150 // config_userRegister(). But not bad enough to refactor.
152 void mp::filter::AuthSimple::config_targetRegister(std::string filename)
154 FILE *fp = fopen(filename.c_str(), "r");
156 die("can't open auth_simple target-register '" + filename + "': " +
160 while (fgets(buf, sizeof buf, fp)) {
161 if (*buf == '\n' || *buf == '#')
163 buf[strlen(buf)-1] = 0;
164 char *targetsp = strchr(buf, ':');
166 die("auth_simple target-register '" + filename + "': " +
167 "no targets on line: '" + buf + "'");
169 std::list<std::string> tmp;
170 boost::split(tmp, targetsp, boost::is_any_of(","));
171 m_p->targetsByUser[buf] = tmp;
173 if (0) { // debugging
174 printf("Added user '%s' with targets:\n", buf);
175 std::list<std::string>::const_iterator i;
176 for (i = tmp.begin(); i != tmp.end(); i++) {
177 printf("\t%s\n", (*i).c_str());
184 void yf::AuthSimple::process(mp::Package &package) const
186 Z_GDU *gdu = package.request().get();
188 if (!gdu || gdu->which != Z_GDU_Z3950) {
189 // Pass on the package -- This means that authentication is
190 // waived, which may not be the correct thing for non-Z APDUs
191 // as it means that SRW sessions don't demand authentication
192 return package.move();
195 if (m_p->got_userRegister) {
196 switch (gdu->u.z3950->which) {
197 case Z_APDU_initRequest: return process_init(package);
198 case Z_APDU_searchRequest: return process_search(package);
199 case Z_APDU_scanRequest: return process_scan(package);
200 // In theory, we should check database authorisation for
201 // extended services, too (A) the proxy currently does not
202 // implement XS and turns off its negotiation bit; (B) it
203 // would be insanely complex to do as the top-level XS request
204 // structure does not carry a database name, but it is buried
205 // down in some of the possible EXTERNALs used as
206 // taskSpecificParameters; and (C) since many extended
207 // services modify the database, we'd need to more exotic
208 // authorisation database than we want to support.
213 if (m_p->got_targetRegister && gdu->u.z3950->which == Z_APDU_initRequest)
214 return check_targets(package);
216 // Operations other than those listed above do not require authorisation
217 return package.move();
221 static void reject_init(mp::Package &package, int err, const char *addinfo);
224 void yf::AuthSimple::process_init(mp::Package &package) const
226 Z_IdAuthentication *auth =
227 package.request().get()->u.z3950->u.initRequest->idAuthentication;
228 // This is just plain perverted.
231 return reject_init(package, 0, "no credentials supplied");
232 if (auth->which != Z_IdAuthentication_idPass)
233 return reject_init(package, 0,
234 "only idPass authentication is supported");
235 Z_IdPass *idPass = auth->u.idPass;
237 if (m_p->userRegister.count(idPass->userId)) {
238 // groupId is ignored, in accordance with ancient tradition.
239 yf::AuthSimple::Rep::PasswordAndDBs pdbs =
240 m_p->userRegister[idPass->userId];
241 if (pdbs.password == idPass->password) {
242 // Success! Remember who the user is for future reference
244 boost::mutex::scoped_lock lock(m_p->mutex);
245 m_p->userBySession[package.session()] = idPass->userId;
247 return package.move();
251 return reject_init(package, 0, "username/password combination rejected");
255 // I find it unutterable disappointing that I have to provide this
256 static bool contains(std::list<std::string> list, std::string thing) {
257 std::list<std::string>::const_iterator i;
258 for (i = list.begin(); i != list.end(); i++)
259 if (mp::util::database_name_normalize(*i) ==
260 mp::util::database_name_normalize(thing))
267 void yf::AuthSimple::process_search(mp::Package &package) const
269 Z_SearchRequest *req =
270 package.request().get()->u.z3950->u.searchRequest;
272 if (m_p->userBySession.count(package.session()) == 0) {
273 // It's a non-authenticated session, so just accept the operation
274 return package.move();
277 std::string user = m_p->userBySession[package.session()];
278 yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
279 for (int i = 0; i < req->num_databaseNames; i++) {
280 if (!contains(pdb.dbs, req->databaseNames[i]) &&
281 !contains(pdb.dbs, "*")) {
282 // Make an Search rejection APDU
284 Z_APDU *apdu = odr.create_searchResponse(
285 package.request().get()->u.z3950,
286 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
287 req->databaseNames[i]);
288 package.response() = apdu;
289 package.session().close();
294 // All the requested databases are acceptable
295 return package.move();
299 void yf::AuthSimple::process_scan(mp::Package &package) const
302 package.request().get()->u.z3950->u.scanRequest;
304 if (m_p->userBySession.count(package.session()) == 0) {
305 // It's a non-authenticated session, so just accept the operation
306 return package.move();
309 std::string user = m_p->userBySession[package.session()];
310 yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
311 for (int i = 0; i < req->num_databaseNames; i++) {
312 if (!contains(pdb.dbs, req->databaseNames[i]) &&
313 !contains(pdb.dbs, "*")) {
314 // Make an Scan rejection APDU
316 Z_APDU *apdu = odr.create_scanResponse(
317 package.request().get()->u.z3950,
318 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
319 req->databaseNames[i]);
320 package.response() = apdu;
321 package.session().close();
326 // All the requested databases are acceptable
327 return package.move();
331 static void reject_init(mp::Package &package, int err, const char *addinfo) {
333 err = YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR;
334 // Make an Init rejection APDU
335 Z_GDU *gdu = package.request().get();
337 Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, err, addinfo);
338 *apdu->u.initResponse->result = 0; // reject
339 package.response() = apdu;
340 package.session().close();
344 void yf::AuthSimple::check_targets(mp::Package & package) const
346 Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
348 Z_IdAuthentication *auth = initReq->idAuthentication;
349 // We only get into this method if we are dealing with a session
350 // that has been authenticated using idPass authentication. So we
351 // know what kind of information is in the Init Request, and we
352 // can trust the username without needing to re-authenticate.
353 assert(auth->which == Z_IdAuthentication_idPass);
354 std::string user = auth->u.idPass->userId;
355 std::list<std::string> authorisedTargets = m_p->targetsByUser[user];
357 std::list<std::string> targets;
358 Z_OtherInformation **otherInfo = &initReq->otherInfo;
359 mp::util::remove_vhost_otherinfo(otherInfo, targets);
361 // Check each of the targets specified in the otherInfo package
362 std::list<std::string>::iterator i;
365 while (i != targets.end()) {
366 if (contains(authorisedTargets, *i) ||
367 contains(authorisedTargets, "*")) {
370 if (!m_p->discardUnauthorisedTargets)
371 return reject_init(package,
372 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, i->c_str());
373 i = targets.erase(i);
377 if (targets.size() == 0)
378 return reject_init(package,
379 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
380 // ### It would be better to use the Z-db name
383 mp::util::set_vhost_otherinfo(otherInfo, odr, targets);
388 static mp::filter::Base* filter_creator()
390 return new mp::filter::AuthSimple;
394 struct metaproxy_1_filter_struct metaproxy_1_filter_auth_simple = {
405 * c-file-style: "Stroustrup"
406 * indent-tabs-mode: nil
408 * vim: shiftwidth=4 tabstop=8 expandtab