1 /* $Id: filter_auth_simple.cpp,v 1.15 2006-01-18 14:38:48 mike Exp $
2 Copyright (c) 2005, Index Data.
10 #include "package.hpp"
12 #include <boost/thread/mutex.hpp>
13 #include <boost/algorithm/string.hpp>
16 #include "filter_auth_simple.hpp"
19 #include <yaz/diagbib1.h>
23 namespace yf = yp2::filter;
27 class AuthSimple::Rep {
28 friend class AuthSimple;
29 struct PasswordAndDBs {
31 std::list<std::string> dbs;
33 PasswordAndDBs(std::string pw) : password(pw) {};
34 void addDB(std::string db) { dbs.push_back(db); }
37 bool got_userRegister, got_targetRegister;
38 std::map<std::string, PasswordAndDBs> userRegister;
39 std::map<std::string, std::list<std::string> > targetsByUser;
40 std::map<yp2::Session, std::string> userBySession;
41 bool discardUnauthorisedDBs;
42 Rep() { got_userRegister = false;
43 got_targetRegister = false;
44 discardUnauthorisedDBs = false; }
49 yf::AuthSimple::AuthSimple() : m_p(new Rep)
54 yf::AuthSimple::~AuthSimple()
55 { // must have a destructor because of boost::scoped_ptr
59 static void die(std::string s) { throw yp2::filter::FilterException(s); }
62 // Read XML config.. Put config info in m_p.
63 void yp2::filter::AuthSimple::configure(const xmlNode * ptr)
65 std::string userRegisterName;
66 std::string targetRegisterName;
68 for (ptr = ptr->children; ptr != 0; ptr = ptr->next) {
69 if (ptr->type != XML_ELEMENT_NODE)
71 if (!strcmp((const char *) ptr->name, "userRegister")) {
72 userRegisterName = yp2::xml::get_text(ptr);
73 m_p->got_userRegister = true;
74 } else if (!strcmp((const char *) ptr->name, "targetRegister")) {
75 targetRegisterName = yp2::xml::get_text(ptr);
76 m_p->got_targetRegister = true;
77 } else if (!strcmp((const char *) ptr->name,
78 "discardUnauthorisedDBs")) {
79 m_p->discardUnauthorisedDBs = true;
81 die("Bad element in auth_simple: <"
82 + std::string((const char *) ptr->name) + ">");
86 if (!m_p->got_userRegister && !m_p->got_targetRegister)
87 die("auth_simple: no user-register or target-register "
88 "filename specified");
90 if (m_p->got_userRegister)
91 config_userRegister(userRegisterName);
92 if (m_p->got_targetRegister)
93 config_targetRegister(targetRegisterName);
97 void yp2::filter::AuthSimple::config_userRegister(std::string filename)
99 FILE *fp = fopen(filename.c_str(), "r");
101 die("can't open auth_simple user-register '" + filename + "': " +
105 while (fgets(buf, sizeof buf, fp)) {
106 if (*buf == '\n' || *buf == '#')
108 buf[strlen(buf)-1] = 0;
109 char *passwdp = strchr(buf, ':');
111 die("auth_simple user-register '" + filename + "': " +
112 "no password on line: '" + buf + "'");
114 char *databasesp = strchr(passwdp, ':');
116 die("auth_simple user-register '" + filename + "': " +
117 "no databases on line: '" + buf + ":" + passwdp + "'");
119 yf::AuthSimple::Rep::PasswordAndDBs tmp(passwdp);
120 boost::split(tmp.dbs, databasesp, boost::is_any_of(","));
121 m_p->userRegister[buf] = tmp;
123 if (0) { // debugging
124 printf("Added user '%s' -> password '%s'\n", buf, passwdp);
125 std::list<std::string>::const_iterator i;
126 for (i = tmp.dbs.begin(); i != tmp.dbs.end(); i++) {
127 printf("db '%s'\n", (*i).c_str());
134 // I feel a little bad about the duplication of code between this and
135 // config_userRegister(). But not bad enough to refactor.
137 void yp2::filter::AuthSimple::config_targetRegister(std::string filename)
139 FILE *fp = fopen(filename.c_str(), "r");
141 die("can't open auth_simple target-register '" + filename + "': " +
145 while (fgets(buf, sizeof buf, fp)) {
146 if (*buf == '\n' || *buf == '#')
148 buf[strlen(buf)-1] = 0;
149 char *targetsp = strchr(buf, ':');
151 die("auth_simple target-register '" + filename + "': " +
152 "no targets on line: '" + buf + "'");
154 std::list<std::string> tmp;
155 boost::split(tmp, targetsp, boost::is_any_of(","));
156 m_p->targetsByUser[buf] = tmp;
158 if (0) { // debugging
159 printf("Added user '%s' with targets:\n", buf);
160 std::list<std::string>::const_iterator i;
161 for (i = tmp.begin(); i != tmp.end(); i++) {
162 printf("\t%s\n", (*i).c_str());
169 void yf::AuthSimple::process(yp2::Package &package) const
171 Z_GDU *gdu = package.request().get();
173 if (!gdu || gdu->which != Z_GDU_Z3950) {
174 // Pass on the package -- This means that authentication is
175 // waived, which may not be the correct thing for non-Z APDUs
176 // as it means that SRW sessions don't demand authentication
177 return package.move();
180 if (m_p->got_userRegister) {
181 switch (gdu->u.z3950->which) {
182 case Z_APDU_initRequest: return process_init(package);
183 case Z_APDU_searchRequest: return process_search(package);
184 case Z_APDU_scanRequest: return process_scan(package);
185 // In theory, we should check database authorisation for
186 // extended services, too (A) the proxy currently does not
187 // implement XS and turns off its negotiation bit; (B) it
188 // would be insanely complex to do as the top-level XS request
189 // structure does not carry a database name, but it is buried
190 // down in some of the possible EXTERNALs used as
191 // taskSpecificParameters; and (C) since many extended
192 // services modify the database, we'd need to more exotic
193 // authorisation database than we want to support.
198 if (m_p->got_targetRegister && gdu->u.z3950->which == Z_APDU_initRequest)
199 return check_targets(package);
201 // Operations other than those listed above do not require authorisation
202 return package.move();
206 static void reject_init(yp2::Package &package, int err, const char *addinfo);
209 void yf::AuthSimple::process_init(yp2::Package &package) const
211 Z_IdAuthentication *auth =
212 package.request().get()->u.z3950->u.initRequest->idAuthentication;
213 // This is just plain perverted.
216 return reject_init(package, 0, "no credentials supplied");
217 if (auth->which != Z_IdAuthentication_idPass)
218 return reject_init(package, 0,
219 "only idPass authentication is supported");
220 Z_IdPass *idPass = auth->u.idPass;
222 if (m_p->userRegister.count(idPass->userId)) {
223 // groupId is ignored, in accordance with ancient tradition.
224 yf::AuthSimple::Rep::PasswordAndDBs pdbs =
225 m_p->userRegister[idPass->userId];
226 if (pdbs.password == idPass->password) {
227 // Success! Remember who the user is for future reference
229 boost::mutex::scoped_lock lock(m_p->mutex);
230 m_p->userBySession[package.session()] = idPass->userId;
232 return package.move();
236 return reject_init(package, 0, "username/password combination rejected");
240 // I find it unutterable disappointing that I have to provide this
241 static bool contains(std::list<std::string> list, std::string thing) {
242 std::list<std::string>::const_iterator i;
243 for (i = list.begin(); i != list.end(); i++)
251 void yf::AuthSimple::process_search(yp2::Package &package) const
253 Z_SearchRequest *req =
254 package.request().get()->u.z3950->u.searchRequest;
256 if (m_p->userBySession.count(package.session()) == 0) {
257 // It's a non-authenticated session, so just accept the operation
258 return package.move();
261 std::string user = m_p->userBySession[package.session()];
262 yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
263 for (int i = 0; i < req->num_databaseNames; i++) {
264 if (!contains(pdb.dbs, req->databaseNames[i]) &&
265 !contains(pdb.dbs, "*")) {
266 // Make an Search rejection APDU
268 Z_APDU *apdu = odr.create_searchResponse(
269 package.request().get()->u.z3950,
270 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
271 req->databaseNames[i]);
272 package.response() = apdu;
273 package.session().close();
278 // All the requested databases are acceptable
279 return package.move();
283 void yf::AuthSimple::process_scan(yp2::Package &package) const
286 package.request().get()->u.z3950->u.scanRequest;
288 if (m_p->userBySession.count(package.session()) == 0) {
289 // It's a non-authenticated session, so just accept the operation
290 return package.move();
293 std::string user = m_p->userBySession[package.session()];
294 yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
295 for (int i = 0; i < req->num_databaseNames; i++) {
296 if (!contains(pdb.dbs, req->databaseNames[i]) &&
297 !contains(pdb.dbs, "*")) {
298 // Make an Scan rejection APDU
300 Z_APDU *apdu = odr.create_scanResponse(
301 package.request().get()->u.z3950,
302 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
303 req->databaseNames[i]);
304 package.response() = apdu;
305 package.session().close();
310 // All the requested databases are acceptable
311 return package.move();
315 static void reject_init(yp2::Package &package, int err, const char *addinfo) {
317 err = YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR;
318 // Make an Init rejection APDU
319 Z_GDU *gdu = package.request().get();
321 Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, err, addinfo);
322 apdu->u.initResponse->implementationName = "YP2/YAZ";
323 *apdu->u.initResponse->result = 0; // reject
324 package.response() = apdu;
325 package.session().close();
329 void yf::AuthSimple::check_targets(yp2::Package & package) const
331 Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
333 Z_IdAuthentication *auth = initReq->idAuthentication;
334 // We only get into this method if we are dealing with a session
335 // that has been authenticated using idPass authentication. So we
336 // know what kind of information is in the Init Request, and we
337 // can trust the username without needing to re-authenticate.
338 assert(auth->which == Z_IdAuthentication_idPass);
339 std::string user = auth->u.idPass->userId;
340 std::list<std::string> authorisedTargets = m_p->targetsByUser[user];
342 std::list<std::string> targets;
343 Z_OtherInformation *otherInfo = initReq->otherInfo;
344 yp2::util::get_vhost_otherinfo(&otherInfo, 0, targets);
346 // Check each of the targets specified in the otherInfo package
347 std::list<std::string>::iterator i;
349 printf("pre: got %d targets\n", targets.size());
351 while (i != targets.end()) {
352 printf("pre: considering target '%s'\n", (*i).c_str());
357 while (i != targets.end()) {
358 printf("checking target '%s'\n", (*i).c_str());
359 if (contains(authorisedTargets, *i) ||
360 contains(authorisedTargets, "*")) {
361 printf("target '%s' is ok\n", (*i).c_str());
364 printf("target '%s' sucks\n", (*i).c_str());
365 if (!m_p->discardUnauthorisedDBs)
366 return reject_init(package,
367 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, i->c_str());
368 i = targets.erase(i);
372 printf("post: got %d targets\n", targets.size());
374 while (i != targets.end()) {
375 printf("post: considering target '%s'\n", (*i).c_str());
379 if (targets.size() == 0)
380 return reject_init(package,
381 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
384 // ### This is a no-op if the list has not changed
386 yp2::util::set_vhost_otherinfo(&otherInfo, odr, targets);
391 static yp2::filter::Base* filter_creator()
393 return new yp2::filter::AuthSimple;
397 struct yp2_filter_struct yp2_filter_auth_simple = {
408 * indent-tabs-mode: nil
409 * c-file-style: "stroustrup"
411 * vim: shiftwidth=4 tabstop=8 expandtab