~drizzle-trunk/drizzle/development

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
239
240
/* -*- 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 "drizzled/configmake.h"
#include "drizzled/plugin/authentication.h"
#include "drizzled/security_context.h"
#include "drizzled/util/convert.h"
#include "drizzled/algorithm/sha1.h"

using namespace std;
using namespace drizzled;

namespace auth_file
{

static char* users_file= NULL;
static const char DEFAULT_USERS_FILE[]= SYSCONFDIR "/drizzle.users";

class AuthFile: public plugin::Authentication
{
public:

  AuthFile(string name_arg);

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

  /**
   * 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(void);

private:

  /**
   * Base class method to check authentication for a user.
   */
  bool authenticate(const SecurityContext &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;

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

AuthFile::AuthFile(string name_arg):
  plugin::Authentication(name_arg),
  error(),
  users()
{
}

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

bool AuthFile::loadFile(void)
{
  ifstream file(users_file);

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

  while (!file.eof())
  {
    string line;
    getline(file, line);

    /* Ignore blank lines and lines starting with '#'. */
    if (line == "" || 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);
    }

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

  file.close();
  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 SecurityContext &sctx, const string &password)
{
  map<string, string>::const_iterator user = users.find(sctx.getUser());
  if (user == users.end())
    return false;

  if (sctx.getPasswordType() == SecurityContext::MYSQL_HASH)
    return verifyMySQLHash(user->second, sctx.getPasswordContext(), password);

  if (password == user->second)
    return true;

  return false;
}

static int init(plugin::Context &context)
{
  AuthFile *auth_file = new AuthFile("auth_file");
  if (!auth_file->loadFile())
  {
    errmsg_printf(ERRMSG_LVL_ERROR, _("Could not load auth file: %s\n"),
                  auth_file->getError().c_str());
    delete auth_file;
    return 1;
  }

  context.add(auth_file);
  return 0;
}

static DRIZZLE_SYSVAR_STR(users,
                          users_file,
                          PLUGIN_VAR_READONLY,
                          N_("File to load for usernames and passwords"),
                          NULL, /* check func */
                          NULL, /* update func*/
                          DEFAULT_USERS_FILE /* default */);

static drizzle_sys_var* sys_variables[]=
{
  DRIZZLE_SYSVAR(users),
  NULL
};

} /* namespace auth_file */

DRIZZLE_PLUGIN(auth_file::init, auth_file::sys_variables);