1 /* $Id: filter_auth_simple.cpp,v 1.21 2006-08-30 12:27:34 adam Exp $
2 Copyright (c) 2005-2006, Index Data.
4 See the LICENSE file for details
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 mp = metaproxy_1;
24 namespace yf = mp::filter;
26 namespace metaproxy_1 {
28 class AuthSimple::Rep {
29 friend class AuthSimple;
30 struct PasswordAndDBs {
32 std::list<std::string> dbs;
34 PasswordAndDBs(std::string pw) : password(pw) {};
35 void addDB(std::string db) { dbs.push_back(db); }
38 bool got_userRegister, got_targetRegister;
39 std::map<std::string, PasswordAndDBs> userRegister;
40 std::map<std::string, std::list<std::string> > targetsByUser;
41 std::map<mp::Session, std::string> userBySession;
42 bool discardUnauthorisedTargets;
43 Rep() { got_userRegister = false;
44 got_targetRegister = false;
45 discardUnauthorisedTargets = false; }
50 yf::AuthSimple::AuthSimple() : m_p(new Rep)
55 yf::AuthSimple::~AuthSimple()
56 { // must have a destructor because of boost::scoped_ptr
60 static void die(std::string s) { throw mp::filter::FilterException(s); }
63 // Read XML config.. Put config info in m_p.
64 void mp::filter::AuthSimple::configure(const xmlNode * ptr)
66 std::string userRegisterName;
67 std::string targetRegisterName;
69 for (ptr = ptr->children; ptr != 0; ptr = ptr->next) {
70 if (ptr->type != XML_ELEMENT_NODE)
72 if (!strcmp((const char *) ptr->name, "userRegister")) {
73 userRegisterName = mp::xml::get_text(ptr);
74 m_p->got_userRegister = true;
75 } else if (!strcmp((const char *) ptr->name, "targetRegister")) {
76 targetRegisterName = mp::xml::get_text(ptr);
77 m_p->got_targetRegister = true;
78 } else if (!strcmp((const char *) ptr->name,
79 "discardUnauthorisedTargets")) {
80 m_p->discardUnauthorisedTargets = true;
82 die("Bad element in auth_simple: <"
83 + std::string((const char *) ptr->name) + ">");
87 if (!m_p->got_userRegister && !m_p->got_targetRegister)
88 die("auth_simple: no user-register or target-register "
89 "filename specified");
91 if (m_p->got_userRegister)
92 config_userRegister(userRegisterName);
93 if (m_p->got_targetRegister)
94 config_targetRegister(targetRegisterName);
98 void mp::filter::AuthSimple::config_userRegister(std::string filename)
100 FILE *fp = fopen(filename.c_str(), "r");
102 die("can't open auth_simple user-register '" + filename + "': " +
106 while (fgets(buf, sizeof buf, fp)) {
107 if (*buf == '\n' || *buf == '#')
109 buf[strlen(buf)-1] = 0;
110 char *passwdp = strchr(buf, ':');
112 die("auth_simple user-register '" + filename + "': " +
113 "no password on line: '" + buf + "'");
115 char *databasesp = strchr(passwdp, ':');
117 die("auth_simple user-register '" + filename + "': " +
118 "no databases on line: '" + buf + ":" + passwdp + "'");
120 yf::AuthSimple::Rep::PasswordAndDBs tmp(passwdp);
121 boost::split(tmp.dbs, databasesp, boost::is_any_of(","));
122 m_p->userRegister[buf] = tmp;
124 if (0) { // debugging
125 printf("Added user '%s' -> password '%s'\n", buf, passwdp);
126 std::list<std::string>::const_iterator i;
127 for (i = tmp.dbs.begin(); i != tmp.dbs.end(); i++) {
128 printf("db '%s'\n", (*i).c_str());
135 // I feel a little bad about the duplication of code between this and
136 // config_userRegister(). But not bad enough to refactor.
138 void mp::filter::AuthSimple::config_targetRegister(std::string filename)
140 FILE *fp = fopen(filename.c_str(), "r");
142 die("can't open auth_simple target-register '" + filename + "': " +
146 while (fgets(buf, sizeof buf, fp)) {
147 if (*buf == '\n' || *buf == '#')
149 buf[strlen(buf)-1] = 0;
150 char *targetsp = strchr(buf, ':');
152 die("auth_simple target-register '" + filename + "': " +
153 "no targets on line: '" + buf + "'");
155 std::list<std::string> tmp;
156 boost::split(tmp, targetsp, boost::is_any_of(","));
157 m_p->targetsByUser[buf] = tmp;
159 if (0) { // debugging
160 printf("Added user '%s' with targets:\n", buf);
161 std::list<std::string>::const_iterator i;
162 for (i = tmp.begin(); i != tmp.end(); i++) {
163 printf("\t%s\n", (*i).c_str());
170 void yf::AuthSimple::process(mp::Package &package) const
172 Z_GDU *gdu = package.request().get();
174 if (!gdu || gdu->which != Z_GDU_Z3950) {
175 // Pass on the package -- This means that authentication is
176 // waived, which may not be the correct thing for non-Z APDUs
177 // as it means that SRW sessions don't demand authentication
178 return package.move();
181 if (m_p->got_userRegister) {
182 switch (gdu->u.z3950->which) {
183 case Z_APDU_initRequest: return process_init(package);
184 case Z_APDU_searchRequest: return process_search(package);
185 case Z_APDU_scanRequest: return process_scan(package);
186 // In theory, we should check database authorisation for
187 // extended services, too (A) the proxy currently does not
188 // implement XS and turns off its negotiation bit; (B) it
189 // would be insanely complex to do as the top-level XS request
190 // structure does not carry a database name, but it is buried
191 // down in some of the possible EXTERNALs used as
192 // taskSpecificParameters; and (C) since many extended
193 // services modify the database, we'd need to more exotic
194 // authorisation database than we want to support.
199 if (m_p->got_targetRegister && gdu->u.z3950->which == Z_APDU_initRequest)
200 return check_targets(package);
202 // Operations other than those listed above do not require authorisation
203 return package.move();
207 static void reject_init(mp::Package &package, int err, const char *addinfo);
210 void yf::AuthSimple::process_init(mp::Package &package) const
212 Z_IdAuthentication *auth =
213 package.request().get()->u.z3950->u.initRequest->idAuthentication;
214 // This is just plain perverted.
217 return reject_init(package, 0, "no credentials supplied");
218 if (auth->which != Z_IdAuthentication_idPass)
219 return reject_init(package, 0,
220 "only idPass authentication is supported");
221 Z_IdPass *idPass = auth->u.idPass;
223 if (m_p->userRegister.count(idPass->userId)) {
224 // groupId is ignored, in accordance with ancient tradition.
225 yf::AuthSimple::Rep::PasswordAndDBs pdbs =
226 m_p->userRegister[idPass->userId];
227 if (pdbs.password == idPass->password) {
228 // Success! Remember who the user is for future reference
230 boost::mutex::scoped_lock lock(m_p->mutex);
231 m_p->userBySession[package.session()] = idPass->userId;
233 return package.move();
237 return reject_init(package, 0, "username/password combination rejected");
241 // I find it unutterable disappointing that I have to provide this
242 static bool contains(std::list<std::string> list, std::string thing) {
243 std::list<std::string>::const_iterator i;
244 for (i = list.begin(); i != list.end(); i++)
245 if (mp::util::database_name_normalize(*i) ==
246 mp::util::database_name_normalize(thing))
253 void yf::AuthSimple::process_search(mp::Package &package) const
255 Z_SearchRequest *req =
256 package.request().get()->u.z3950->u.searchRequest;
258 if (m_p->userBySession.count(package.session()) == 0) {
259 // It's a non-authenticated session, so just accept the operation
260 return package.move();
263 std::string user = m_p->userBySession[package.session()];
264 yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
265 for (int i = 0; i < req->num_databaseNames; i++) {
266 if (!contains(pdb.dbs, req->databaseNames[i]) &&
267 !contains(pdb.dbs, "*")) {
268 // Make an Search rejection APDU
270 Z_APDU *apdu = odr.create_searchResponse(
271 package.request().get()->u.z3950,
272 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
273 req->databaseNames[i]);
274 package.response() = apdu;
275 package.session().close();
280 // All the requested databases are acceptable
281 return package.move();
285 void yf::AuthSimple::process_scan(mp::Package &package) const
288 package.request().get()->u.z3950->u.scanRequest;
290 if (m_p->userBySession.count(package.session()) == 0) {
291 // It's a non-authenticated session, so just accept the operation
292 return package.move();
295 std::string user = m_p->userBySession[package.session()];
296 yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
297 for (int i = 0; i < req->num_databaseNames; i++) {
298 if (!contains(pdb.dbs, req->databaseNames[i]) &&
299 !contains(pdb.dbs, "*")) {
300 // Make an Scan rejection APDU
302 Z_APDU *apdu = odr.create_scanResponse(
303 package.request().get()->u.z3950,
304 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
305 req->databaseNames[i]);
306 package.response() = apdu;
307 package.session().close();
312 // All the requested databases are acceptable
313 return package.move();
317 static void reject_init(mp::Package &package, int err, const char *addinfo) {
319 err = YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR;
320 // Make an Init rejection APDU
321 Z_GDU *gdu = package.request().get();
323 Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, err, addinfo);
324 apdu->u.initResponse->implementationName = "YP2/YAZ";
325 *apdu->u.initResponse->result = 0; // reject
326 package.response() = apdu;
327 package.session().close();
331 void yf::AuthSimple::check_targets(mp::Package & package) const
333 Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
335 Z_IdAuthentication *auth = initReq->idAuthentication;
336 // We only get into this method if we are dealing with a session
337 // that has been authenticated using idPass authentication. So we
338 // know what kind of information is in the Init Request, and we
339 // can trust the username without needing to re-authenticate.
340 assert(auth->which == Z_IdAuthentication_idPass);
341 std::string user = auth->u.idPass->userId;
342 std::list<std::string> authorisedTargets = m_p->targetsByUser[user];
344 std::list<std::string> targets;
345 Z_OtherInformation *otherInfo = initReq->otherInfo;
346 mp::util::get_vhost_otherinfo(otherInfo, targets);
348 // Check each of the targets specified in the otherInfo package
349 std::list<std::string>::iterator i;
352 while (i != targets.end()) {
353 if (contains(authorisedTargets, *i) ||
354 contains(authorisedTargets, "*")) {
357 if (!m_p->discardUnauthorisedTargets)
358 return reject_init(package,
359 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, i->c_str());
360 i = targets.erase(i);
364 if (targets.size() == 0)
365 return reject_init(package,
366 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
367 // ### It would be better to use the Z-db name
371 mp::util::set_vhost_otherinfo(&otherInfo, odr, targets);
376 static mp::filter::Base* filter_creator()
378 return new mp::filter::AuthSimple;
382 struct metaproxy_1_filter_struct metaproxy_1_filter_auth_simple = {
393 * indent-tabs-mode: nil
394 * c-file-style: "stroustrup"
396 * vim: shiftwidth=4 tabstop=8 expandtab