1 /* This file is part of Metaproxy.
2 Copyright (C) 2005-2013 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>
26 #include <metaproxy/util.hpp>
27 #include "filter_auth_simple.hpp"
30 #include <yaz/diagbib1.h>
34 namespace mp = metaproxy_1;
35 namespace yf = mp::filter;
37 namespace metaproxy_1 {
39 class AuthSimple::Rep {
40 friend class AuthSimple;
41 struct PasswordAndDBs {
43 std::list<std::string> dbs;
45 PasswordAndDBs(std::string pw) : password(pw) {};
46 void addDB(std::string db) { dbs.push_back(db); }
49 bool got_userRegister, got_targetRegister;
50 std::map<std::string, PasswordAndDBs> userRegister;
51 std::map<std::string, std::list<std::string> > targetsByUser;
52 std::map<mp::Session, std::string> userBySession;
53 bool discardUnauthorisedTargets;
54 Rep() { got_userRegister = false;
55 got_targetRegister = false;
56 discardUnauthorisedTargets = false; }
61 yf::AuthSimple::AuthSimple() : m_p(new Rep)
66 yf::AuthSimple::~AuthSimple()
67 { // must have a destructor because of boost::scoped_ptr
71 static void die(std::string s) { throw mp::filter::FilterException(s); }
74 static std::string get_user(Z_InitRequest *initReq, std::string &password)
76 Z_IdAuthentication *auth = initReq->idAuthentication;
83 case Z_IdAuthentication_open:
84 cp = strchr(auth->u.open, '/');
87 user.assign(auth->u.open, cp - auth->u.open);
88 password.assign(cp + 1);
93 case Z_IdAuthentication_idPass:
94 if (auth->u.idPass->userId)
95 user = auth->u.idPass->userId;
96 if (auth->u.idPass->password)
97 password = auth->u.idPass->password;
104 // Read XML config.. Put config info in m_p.
105 void mp::filter::AuthSimple::configure(const xmlNode * ptr, bool test_only,
108 std::string userRegisterName;
109 std::string targetRegisterName;
111 for (ptr = ptr->children; ptr != 0; ptr = ptr->next) {
112 if (ptr->type != XML_ELEMENT_NODE)
114 if (!strcmp((const char *) ptr->name, "userRegister")) {
115 userRegisterName = mp::xml::get_text(ptr);
116 m_p->got_userRegister = true;
117 } else if (!strcmp((const char *) ptr->name, "targetRegister")) {
118 targetRegisterName = mp::xml::get_text(ptr);
119 m_p->got_targetRegister = true;
120 } else if (!strcmp((const char *) ptr->name,
121 "discardUnauthorisedTargets")) {
122 m_p->discardUnauthorisedTargets = true;
124 die("Bad element in auth_simple: <"
125 + std::string((const char *) ptr->name) + ">");
129 if (!m_p->got_userRegister && !m_p->got_targetRegister)
130 die("auth_simple: no user-register or target-register "
131 "filename specified");
133 if (m_p->got_userRegister)
134 config_userRegister(userRegisterName);
135 if (m_p->got_targetRegister)
136 config_targetRegister(targetRegisterName);
139 static void split_db(std::list<std::string> &dbs,
140 const char *databasesp)
143 while ((cp = strchr(databasesp, ',')))
145 dbs.push_back(std::string(databasesp, cp - databasesp));
148 dbs.push_back(std::string(databasesp));
151 void mp::filter::AuthSimple::config_userRegister(std::string filename)
153 FILE *fp = fopen(filename.c_str(), "r");
155 die("can't open auth_simple user-register '" + filename + "': " +
159 while (fgets(buf, sizeof buf, fp))
161 if (*buf == '\n' || *buf == '#')
163 buf[strlen(buf)-1] = 0;
164 char *passwdp = strchr(buf, ':');
166 die("auth_simple user-register '" + filename + "': " +
167 "no password on line: '" + buf + "'");
169 char *databasesp = strchr(passwdp, ':');
171 die("auth_simple user-register '" + filename + "': " +
172 "no databases on line: '" + buf + ":" + passwdp + "'");
174 yf::AuthSimple::Rep::PasswordAndDBs tmp(passwdp);
175 split_db(tmp.dbs, databasesp);
176 m_p->userRegister[buf] = tmp;
180 printf("Added user '%s' -> password '%s'\n", buf, passwdp);
181 std::list<std::string>::const_iterator i;
182 for (i = tmp.dbs.begin(); i != tmp.dbs.end(); i++)
183 printf("db '%s'\n", (*i).c_str());
190 // I feel a little bad about the duplication of code between this and
191 // config_userRegister(). But not bad enough to refactor.
193 void mp::filter::AuthSimple::config_targetRegister(std::string filename)
195 FILE *fp = fopen(filename.c_str(), "r");
197 die("can't open auth_simple target-register '" + filename + "': " +
201 while (fgets(buf, sizeof buf, fp)) {
202 if (*buf == '\n' || *buf == '#')
204 buf[strlen(buf)-1] = 0;
205 char *targetsp = strchr(buf, ':');
207 die("auth_simple target-register '" + filename + "': " +
208 "no targets on line: '" + buf + "'");
210 std::list<std::string> tmp;
211 split_db(tmp, targetsp);
212 m_p->targetsByUser[buf] = tmp;
214 if (0) { // debugging
215 printf("Added user '%s' with targets:\n", buf);
216 std::list<std::string>::const_iterator i;
217 for (i = tmp.begin(); i != tmp.end(); i++) {
218 printf("\t%s\n", (*i).c_str());
225 void yf::AuthSimple::process(mp::Package &package) const
227 Z_GDU *gdu = package.request().get();
229 if (!gdu || gdu->which != Z_GDU_Z3950) {
230 // Pass on the package -- This means that authentication is
231 // waived, which may not be the correct thing for non-Z APDUs
232 // as it means that SRW sessions don't demand authentication
233 return package.move();
236 if (m_p->got_userRegister) {
237 switch (gdu->u.z3950->which) {
238 case Z_APDU_initRequest: return process_init(package);
239 case Z_APDU_searchRequest: return process_search(package);
240 case Z_APDU_scanRequest: return process_scan(package);
241 // In theory, we should check database authorisation for
242 // extended services, too (A) the proxy currently does not
243 // implement XS and turns off its negotiation bit; (B) it
244 // would be insanely complex to do as the top-level XS request
245 // structure does not carry a database name, but it is buried
246 // down in some of the possible EXTERNALs used as
247 // taskSpecificParameters; and (C) since many extended
248 // services modify the database, we'd need to more exotic
249 // authorisation database than we want to support.
254 if (m_p->got_targetRegister && gdu->u.z3950->which == Z_APDU_initRequest)
255 return check_targets(package);
257 // Operations other than those listed above do not require authorisation
258 return package.move();
262 static void reject_init(mp::Package &package, int err, const char *addinfo);
265 void yf::AuthSimple::process_init(mp::Package &package) const
267 Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
269 std::string password;
270 std::string user = get_user(initReq, password);
272 if (user.length() == 0)
273 return reject_init(package, 0, "no credentials supplied");
275 if (m_p->userRegister.count(user)) {
276 // groupId is ignored, in accordance with ancient tradition.
277 yf::AuthSimple::Rep::PasswordAndDBs pdbs =
278 m_p->userRegister[user];
279 if (pdbs.password == password) {
280 // Success! Remember who the user is for future reference
282 boost::mutex::scoped_lock lock(m_p->mutex);
283 m_p->userBySession[package.session()] = user;
285 return package.move();
289 return reject_init(package, 0, "username/password combination rejected");
293 // I find it unutterable disappointing that I have to provide this
294 static bool contains(std::list<std::string> list, std::string thing) {
295 std::list<std::string>::const_iterator i;
296 for (i = list.begin(); i != list.end(); i++)
297 if (mp::util::database_name_normalize(*i) ==
298 mp::util::database_name_normalize(thing))
305 void yf::AuthSimple::process_search(mp::Package &package) const
307 Z_SearchRequest *req =
308 package.request().get()->u.z3950->u.searchRequest;
310 if (m_p->userBySession.count(package.session()) == 0) {
311 // It's a non-authenticated session, so just accept the operation
312 return package.move();
315 std::string user = m_p->userBySession[package.session()];
316 yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
317 for (int i = 0; i < req->num_databaseNames; i++) {
318 if (!contains(pdb.dbs, req->databaseNames[i]) &&
319 !contains(pdb.dbs, "*")) {
320 // Make an Search rejection APDU
322 Z_APDU *apdu = odr.create_searchResponse(
323 package.request().get()->u.z3950,
324 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
325 req->databaseNames[i]);
326 package.response() = apdu;
327 package.session().close();
332 // All the requested databases are acceptable
333 return package.move();
337 void yf::AuthSimple::process_scan(mp::Package &package) const
340 package.request().get()->u.z3950->u.scanRequest;
342 if (m_p->userBySession.count(package.session()) == 0) {
343 // It's a non-authenticated session, so just accept the operation
344 return package.move();
347 std::string user = m_p->userBySession[package.session()];
348 yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
349 for (int i = 0; i < req->num_databaseNames; i++) {
350 if (!contains(pdb.dbs, req->databaseNames[i]) &&
351 !contains(pdb.dbs, "*")) {
352 // Make an Scan rejection APDU
354 Z_APDU *apdu = odr.create_scanResponse(
355 package.request().get()->u.z3950,
356 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
357 req->databaseNames[i]);
358 package.response() = apdu;
359 package.session().close();
364 // All the requested databases are acceptable
365 return package.move();
369 static void reject_init(mp::Package &package, int err, const char *addinfo) {
371 err = YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR;
372 // Make an Init rejection APDU
373 Z_GDU *gdu = package.request().get();
375 Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, err, addinfo);
376 *apdu->u.initResponse->result = 0; // reject
377 package.response() = apdu;
378 package.session().close();
381 void yf::AuthSimple::check_targets(mp::Package & package) const
383 Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
385 std::string password;
386 std::string user = get_user(initReq, password);
387 std::list<std::string> authorisedTargets = m_p->targetsByUser[user];
389 std::list<std::string> targets;
390 Z_OtherInformation **otherInfo = &initReq->otherInfo;
391 mp::util::remove_vhost_otherinfo(otherInfo, targets);
393 // Check each of the targets specified in the otherInfo package
394 std::list<std::string>::iterator i;
397 while (i != targets.end()) {
398 if (contains(authorisedTargets, *i) ||
399 contains(authorisedTargets, "*")) {
402 if (!m_p->discardUnauthorisedTargets)
403 return reject_init(package,
404 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, i->c_str());
405 i = targets.erase(i);
409 if (targets.size() == 0)
410 return reject_init(package,
411 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
412 // ### It would be better to use the Z-db name
415 mp::util::set_vhost_otherinfo(otherInfo, odr, targets);
420 static mp::filter::Base* filter_creator()
422 return new mp::filter::AuthSimple;
426 struct metaproxy_1_filter_struct metaproxy_1_filter_auth_simple = {
437 * c-file-style: "Stroustrup"
438 * indent-tabs-mode: nil
440 * vim: shiftwidth=4 tabstop=8 expandtab