~ubuntu-branches/ubuntu/saucy/drizzle/saucy-proposed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Copyright (C) 2010 Eric Day
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <config.h>

#include <fstream>
#include <map>
#include <string>
#include <iostream>

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>

#include <drizzled/configmake.h>
#include <drizzled/plugin/authentication.h>
#include <drizzled/identifier.h>
#include <drizzled/util/convert.h>
#include <drizzled/algorithm/sha1.h>
#include <drizzled/module/option_map.h>

namespace po= boost::program_options;
namespace fs= boost::filesystem;

using namespace std;
using namespace drizzled;

namespace auth_file {

static const fs::path DEFAULT_USERS_FILE= SYSCONFDIR "/drizzle.users";

class AuthFile : public plugin::Authentication
{
public:
  AuthFile(fs::path users_file_arg);

  /**
   * Retrieve the last error encountered in the class.
   */
  const string& getError() const;

  /**
   * Load the users file into a map cache.
   *
   * @return True on success, false on error. If false is returned an error
   *  is set and can be retrieved with getError().
   */
  bool loadFile();

private:

  /**
   * Base class method to check authentication for a user.
   */
  bool authenticate(const identifier::User &sctx, const string &password);

  /**
   * Verify the local and remote scrambled password match using the MySQL
   * hashing algorithm.
   *
   * @param[in] password Plain text password that is stored locally.
   * @param[in] scramble_bytes The random bytes that the server sent to the
   *  client for scrambling the password.
   * @param[in] scrambled_password The result of the client scrambling the
   *  password remotely.
   * @return True if the password matched, false if not.
   */
  bool verifyMySQLHash(const string &password,
                       const string &scramble_bytes,
                       const string &scrambled_password);

  string error;
  const fs::path users_file;

  /**
   * Cache or username:password entries from the file.
   */
  typedef std::map<string, string> users_t;
  users_t users;
};

AuthFile::AuthFile(fs::path users_file_arg) :
  plugin::Authentication("auth_file"),
  users_file(users_file_arg)
{
}

const string& AuthFile::getError() const
{
  return error;
}

bool AuthFile::loadFile()
{
  ifstream file(users_file.string().c_str());

  if (!file.is_open())
  {
    error = "Could not open users file: " + users_file.string();
    return false;
  }

  string line;
  while (getline(file, line))
  {
    /* Ignore blank lines and lines starting with '#'. */
    if (line.empty() || line[line.find_first_not_of(" \t")] == '#')
      continue;

    string username;
    string password;
    size_t password_offset = line.find(":");
    if (password_offset == string::npos)
      username = line;
    else
    {
      username = string(line, 0, password_offset);
      password = string(line, password_offset + 1);
    }

    if (not users.insert(pair<string, string>(username, password)).second)
    {
      error = "Duplicate entry found in users file: " + username;
      return false;
    }
  }
  return true;
}

bool AuthFile::verifyMySQLHash(const string &password,
                               const string &scramble_bytes,
                               const string &scrambled_password)
{
  if (scramble_bytes.size() != SHA1_DIGEST_LENGTH || scrambled_password.size() != SHA1_DIGEST_LENGTH)
  {
    return false;
  }

  SHA1_CTX ctx;
  uint8_t local_scrambled_password[SHA1_DIGEST_LENGTH];
  uint8_t temp_hash[SHA1_DIGEST_LENGTH];
  uint8_t scrambled_password_check[SHA1_DIGEST_LENGTH];

  /* Generate the double SHA1 hash for the password stored locally first. */
  SHA1Init(&ctx);
  SHA1Update(&ctx, reinterpret_cast<const uint8_t *>(password.c_str()), password.size());
  SHA1Final(temp_hash, &ctx);

  SHA1Init(&ctx);
  SHA1Update(&ctx, temp_hash, SHA1_DIGEST_LENGTH);
  SHA1Final(local_scrambled_password, &ctx);

  /* Hash the scramble that was sent to client with the local password. */
  SHA1Init(&ctx);
  SHA1Update(&ctx, reinterpret_cast<const uint8_t*>(scramble_bytes.c_str()), SHA1_DIGEST_LENGTH);
  SHA1Update(&ctx, local_scrambled_password, SHA1_DIGEST_LENGTH);
  SHA1Final(temp_hash, &ctx);

  /* Next, XOR the result with what the client sent to get the original
     single-hashed password. */
  for (int x= 0; x < SHA1_DIGEST_LENGTH; x++)
    temp_hash[x]= temp_hash[x] ^ scrambled_password[x];

  /* Hash this result once more to get the double-hashed password again. */
  SHA1Init(&ctx);
  SHA1Update(&ctx, temp_hash, SHA1_DIGEST_LENGTH);
  SHA1Final(scrambled_password_check, &ctx);

  /* These should match for a successful auth. */
  return memcmp(local_scrambled_password, scrambled_password_check, SHA1_DIGEST_LENGTH) == 0;
}

bool AuthFile::authenticate(const identifier::User &sctx, const string &password)
{
  string* user= find_ptr(users, sctx.username());
  if (not user)
    return false;
  return sctx.getPasswordType() == identifier::User::MYSQL_HASH
    ? verifyMySQLHash(*user, sctx.getPasswordContext(), password)
    : password == *user;
}

static int init(module::Context &context)
{
  const module::option_map &vm= context.getOptions();

  AuthFile *auth_file = new AuthFile(fs::path(vm["users"].as<string>()));
  if (not auth_file->loadFile())
  {
    errmsg_printf(error::ERROR, _("Could not load auth file: %s\n"), auth_file->getError().c_str());
    delete auth_file;
    return 1;
  }

  context.add(auth_file);
  context.registerVariable(new sys_var_const_string_val("users", vm["users"].as<string>()));

  return 0;
}


static void init_options(drizzled::module::option_context &context)
{
  context("users", 
          po::value<string>()->default_value(DEFAULT_USERS_FILE.string()),
          N_("File to load for usernames and passwords"));
}

} /* namespace auth_file */

DRIZZLE_DECLARE_PLUGIN
{
  DRIZZLE_VERSION_ID,
  "auth_file",
  "0.1",
  "Eric Day",
  N_("Authentication against a plain text file"),
  PLUGIN_LICENSE_GPL,
  auth_file::init,
  NULL,
  auth_file::init_options
}
DRIZZLE_DECLARE_PLUGIN_END;