metaproxy  1.21.0
filter_auth_simple.cpp
Go to the documentation of this file.
1 /* This file is part of Metaproxy.
2  Copyright (C) Index Data
3 
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
7 version.
8 
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
12 for more details.
13 
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
17 */
18 
19 #include "config.hpp"
20 
21 #include <metaproxy/filter.hpp>
22 #include <metaproxy/package.hpp>
23 
24 #include <boost/thread/mutex.hpp>
25 
26 #include <metaproxy/util.hpp>
27 #include "filter_auth_simple.hpp"
28 #include <fstream>
29 #include <yaz/zgdu.h>
30 #include <yaz/diagbib1.h>
31 #include <yaz/tpath.h>
32 #include <stdio.h>
33 #include <errno.h>
34 
35 namespace mp = metaproxy_1;
36 namespace yf = mp::filter;
37 
38 namespace metaproxy_1 {
39  namespace filter {
41  friend class AuthSimple;
42  struct PasswordAndDBs {
43  std::string password;
44  std::list<std::string> dbs;
46  PasswordAndDBs(std::string pw) : password(pw) {};
47  void addDB(std::string db) { dbs.push_back(db); }
48  };
49  boost::mutex mutex;
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;
55  Rep() { got_userRegister = false;
56  got_targetRegister = false;
58  };
59  }
60 }
61 
62 yf::AuthSimple::AuthSimple() : m_p(new Rep)
63 {
64  // nothing to do
65 }
66 
67 yf::AuthSimple::~AuthSimple()
68 { // must have a destructor because of boost::scoped_ptr
69 }
70 
71 
72 static void die(std::string s) { throw mp::filter::FilterException(s); }
73 
74 
75 static std::string get_user(Z_InitRequest *initReq, std::string &password)
76 {
77  Z_IdAuthentication *auth = initReq->idAuthentication;
78  std::string user;
79  if (auth)
80  {
81  const char *cp;
82  switch (auth->which)
83  {
84  case Z_IdAuthentication_open:
85  cp = strchr(auth->u.open, '/');
86  if (cp)
87  {
88  user.assign(auth->u.open, cp - auth->u.open);
89  password.assign(cp + 1);
90  }
91  else
92  user = auth->u.open;
93  break;
94  case Z_IdAuthentication_idPass:
95  if (auth->u.idPass->userId)
96  user = auth->u.idPass->userId;
97  if (auth->u.idPass->password)
98  password = auth->u.idPass->password;
99  break;
100  }
101  }
102  return user;
103 }
104 
105 // Read XML config.. Put config info in m_p.
106 void mp::filter::AuthSimple::configure(const xmlNode * ptr, bool test_only,
107  const char *path)
108 {
109  std::string userRegisterName;
110  std::string targetRegisterName;
111 
112  for (ptr = ptr->children; ptr != 0; ptr = ptr->next) {
113  if (ptr->type != XML_ELEMENT_NODE)
114  continue;
115  if (!strcmp((const char *) ptr->name, "userRegister")) {
116  userRegisterName = mp::xml::get_text(ptr);
117  m_p->got_userRegister = true;
118  } else if (!strcmp((const char *) ptr->name, "targetRegister")) {
119  targetRegisterName = mp::xml::get_text(ptr);
120  m_p->got_targetRegister = true;
121  } else if (!strcmp((const char *) ptr->name,
122  "discardUnauthorisedTargets")) {
123  m_p->discardUnauthorisedTargets = true;
124  } else {
125  die("Bad element in auth_simple: <"
126  + std::string((const char *) ptr->name) + ">");
127  }
128  }
129 
130  if (!m_p->got_userRegister && !m_p->got_targetRegister)
131  die("auth_simple: no user-register or target-register "
132  "filename specified");
133 
134  if (m_p->got_userRegister)
135  config_userRegister(userRegisterName, path);
136  if (m_p->got_targetRegister)
137  config_targetRegister(targetRegisterName, path);
138 }
139 
140 static void split_db(std::list<std::string> &dbs,
141  const char *databasesp)
142 {
143  const char *cp;
144  while ((cp = strchr(databasesp, ',')))
145  {
146  dbs.push_back(std::string(databasesp, cp - databasesp));
147  databasesp = cp + 1;
148  }
149  dbs.push_back(std::string(databasesp));
150 }
151 
152 void mp::filter::AuthSimple::config_userRegister(std::string filename,
153  const char *path)
154 {
155  char fullpath[1024];
156  if (!yaz_filepath_resolve(filename.c_str(), path, 0, fullpath))
157  die("Could not open " + filename);
158 
159  std::ifstream fp(fullpath);
160  if (!fp.is_open())
161  die("Could not open " + filename);
162 
163  while (!fp.eof())
164  {
165  char buf[1000];
166  fp.getline(buf, sizeof buf);
167  if (*buf == '\0' || *buf == '#')
168  continue;
169  char *passwdp = strchr(buf, ':');
170  if (passwdp == 0)
171  die("auth_simple user-register '" + filename + "': " +
172  "no password on line: '" + buf + "'");
173  *passwdp++ = 0;
174  char *databasesp = strchr(passwdp, ':');
175  if (databasesp == 0)
176  die("auth_simple user-register '" + filename + "': " +
177  "no databases on line: '" + buf + ":" + passwdp + "'");
178  *databasesp++ = 0;
179  yf::AuthSimple::Rep::PasswordAndDBs tmp(passwdp);
180  split_db(tmp.dbs, databasesp);
181  m_p->userRegister[buf] = tmp;
182 
183  if (0)
184  { // debugging
185  printf("Added user '%s' -> password '%s'\n", buf, passwdp);
186  std::list<std::string>::const_iterator i;
187  for (i = tmp.dbs.begin(); i != tmp.dbs.end(); i++)
188  printf("db '%s'\n", (*i).c_str());
189  }
190  }
191 }
192 
193 
194 // I feel a little bad about the duplication of code between this and
195 // config_userRegister(). But not bad enough to refactor.
196 //
197 void mp::filter::AuthSimple::config_targetRegister(std::string filename,
198  const char *path)
199 {
200  char fullpath[1024];
201  if (!yaz_filepath_resolve(filename.c_str(), path, 0, fullpath))
202  die("Could not open " + filename);
203  std::ifstream fp(fullpath);
204  if (!fp.is_open())
205  die("Could not open " + filename);
206 
207  while (!fp.eof()) {
208  char buf[1000];
209  fp.getline(buf, sizeof buf);
210  if (*buf == '\0' || *buf == '#')
211  continue;
212  char *targetsp = strchr(buf, ':');
213  if (targetsp == 0)
214  die("auth_simple target-register '" + filename + "': " +
215  "no targets on line: '" + buf + "'");
216  *targetsp++ = 0;
217  std::list<std::string> tmp;
218  split_db(tmp, targetsp);
219  m_p->targetsByUser[buf] = tmp;
220 
221  if (0) { // debugging
222  printf("Added user '%s' with targets:\n", buf);
223  std::list<std::string>::const_iterator i;
224  for (i = tmp.begin(); i != tmp.end(); i++) {
225  printf("\t%s\n", (*i).c_str());
226  }
227  }
228  }
229 }
230 
231 
232 void yf::AuthSimple::process(mp::Package &package) const
233 {
234  Z_GDU *gdu = package.request().get();
235 
236  if (!gdu || gdu->which != Z_GDU_Z3950) {
237  // Pass on the package -- This means that authentication is
238  // waived, which may not be the correct thing for non-Z APDUs
239  // as it means that SRW sessions don't demand authentication
240  return package.move();
241  }
242 
243  if (m_p->got_userRegister) {
244  switch (gdu->u.z3950->which) {
245  case Z_APDU_initRequest: return process_init(package);
246  case Z_APDU_searchRequest: return process_search(package);
247  case Z_APDU_scanRequest: return process_scan(package);
248  // In theory, we should check database authorisation for
249  // extended services, too (A) the proxy currently does not
250  // implement XS and turns off its negotiation bit; (B) it
251  // would be insanely complex to do as the top-level XS request
252  // structure does not carry a database name, but it is buried
253  // down in some of the possible EXTERNALs used as
254  // taskSpecificParameters; and (C) since many extended
255  // services modify the database, we'd need to more exotic
256  // authorisation database than we want to support.
257  default: break;
258  }
259  }
260 
261  if (m_p->got_targetRegister && gdu->u.z3950->which == Z_APDU_initRequest)
262  return check_targets(package);
263 
264  // Operations other than those listed above do not require authorisation
265  return package.move();
266 }
267 
268 
269 static void reject_init(mp::Package &package, int err, const char *addinfo);
270 
271 
272 void yf::AuthSimple::process_init(mp::Package &package) const
273 {
274  Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
275 
276  std::string password;
277  std::string user = get_user(initReq, password);
278 
279  if (user.length() == 0)
280  return reject_init(package, 0, "no credentials supplied");
281 
282  if (m_p->userRegister.count(user)) {
283  // groupId is ignored, in accordance with ancient tradition.
284  yf::AuthSimple::Rep::PasswordAndDBs pdbs =
285  m_p->userRegister[user];
286  if (pdbs.password == password) {
287  // Success! Remember who the user is for future reference
288  {
289  boost::mutex::scoped_lock lock(m_p->mutex);
290  m_p->userBySession[package.session()] = user;
291  }
292  return package.move();
293  }
294  }
295 
296  return reject_init(package, 0, "username/password combination rejected");
297 }
298 
299 
300 // I find it unutterable disappointing that I have to provide this
301 static bool contains(std::list<std::string> list, std::string thing) {
302  std::list<std::string>::const_iterator i;
303  for (i = list.begin(); i != list.end(); i++)
304  if (mp::util::database_name_normalize(*i) ==
305  mp::util::database_name_normalize(thing))
306  return true;
307 
308  return false;
309 }
310 
311 
312 void yf::AuthSimple::process_search(mp::Package &package) const
313 {
314  Z_SearchRequest *req =
315  package.request().get()->u.z3950->u.searchRequest;
316 
317  if (m_p->userBySession.count(package.session()) == 0) {
318  // It's a non-authenticated session, so just accept the operation
319  return package.move();
320  }
321 
322  std::string user = m_p->userBySession[package.session()];
323  yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
324  for (int i = 0; i < req->num_databaseNames; i++) {
325  if (!contains(pdb.dbs, req->databaseNames[i]) &&
326  !contains(pdb.dbs, "*")) {
327  // Make an Search rejection APDU
328  mp::odr odr;
329  Z_APDU *apdu = odr.create_searchResponse(
330  package.request().get()->u.z3950,
331  YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
332  req->databaseNames[i]);
333  package.response() = apdu;
334  package.session().close();
335  return;
336  }
337  }
338 
339  // All the requested databases are acceptable
340  return package.move();
341 }
342 
343 
344 void yf::AuthSimple::process_scan(mp::Package &package) const
345 {
346  Z_ScanRequest *req =
347  package.request().get()->u.z3950->u.scanRequest;
348 
349  if (m_p->userBySession.count(package.session()) == 0) {
350  // It's a non-authenticated session, so just accept the operation
351  return package.move();
352  }
353 
354  std::string user = m_p->userBySession[package.session()];
355  yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
356  for (int i = 0; i < req->num_databaseNames; i++) {
357  if (!contains(pdb.dbs, req->databaseNames[i]) &&
358  !contains(pdb.dbs, "*")) {
359  // Make an Scan rejection APDU
360  mp::odr odr;
361  Z_APDU *apdu = odr.create_scanResponse(
362  package.request().get()->u.z3950,
363  YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
364  req->databaseNames[i]);
365  package.response() = apdu;
366  package.session().close();
367  return;
368  }
369  }
370 
371  // All the requested databases are acceptable
372  return package.move();
373 }
374 
375 
376 static void reject_init(mp::Package &package, int err, const char *addinfo) {
377  if (err == 0)
378  err = YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR;
379  // Make an Init rejection APDU
380  Z_GDU *gdu = package.request().get();
381  mp::odr odr;
382  Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, err, addinfo);
383  *apdu->u.initResponse->result = 0; // reject
384  package.response() = apdu;
385  package.session().close();
386 }
387 
388 void yf::AuthSimple::check_targets(mp::Package & package) const
389 {
390  Z_InitRequest *initReq = package.request().get()->u.z3950->u.initRequest;
391 
392  std::string password;
393  std::string user = get_user(initReq, password);
394  std::list<std::string> authorisedTargets = m_p->targetsByUser[user];
395 
396  std::list<std::string> targets;
397  Z_OtherInformation **otherInfo = &initReq->otherInfo;
398  mp::util::remove_vhost_otherinfo(otherInfo, targets);
399 
400  // Check each of the targets specified in the otherInfo package
401  std::list<std::string>::iterator i;
402 
403  i = targets.begin();
404  while (i != targets.end()) {
405  if (contains(authorisedTargets, *i) ||
406  contains(authorisedTargets, "*")) {
407  i++;
408  } else {
409  if (!m_p->discardUnauthorisedTargets)
410  return reject_init(package,
411  YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, i->c_str());
412  i = targets.erase(i);
413  }
414  }
415 
416  if (targets.size() == 0)
417  return reject_init(package,
418  YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
419  // ### It would be better to use the Z-db name
420  "all databases");
421  mp::odr odr;
422  mp::util::set_vhost_otherinfo(otherInfo, odr, targets);
423  package.move();
424 }
425 
426 
427 static mp::filter::Base* filter_creator()
428 {
429  return new mp::filter::AuthSimple;
430 }
431 
432 extern "C" {
433  struct metaproxy_1_filter_struct metaproxy_1_filter_auth_simple = {
434  0,
435  "auth_simple",
437  };
438 }
439 
440 
441 /*
442  * Local variables:
443  * c-basic-offset: 4
444  * c-file-style: "Stroustrup"
445  * indent-tabs-mode: nil
446  * End:
447  * vim: shiftwidth=4 tabstop=8 expandtab
448  */
449 
std::map< mp::Session, std::string > userBySession
std::map< std::string, std::list< std::string > > targetsByUser
std::map< std::string, PasswordAndDBs > userRegister
static void split_db(std::list< std::string > &dbs, const char *databasesp)
static bool contains(std::list< std::string > list, std::string thing)
static void die(std::string s)
static mp::filter::Base * filter_creator()
struct metaproxy_1_filter_struct metaproxy_1_filter_auth_simple
static std::string get_user(Z_InitRequest *initReq, std::string &password)
static void reject_init(mp::Package &package, int err, const char *addinfo)