drizzle
C++ MySQL-protocol-compatible database server
Loading...
Searching...
No Matches
auth_schema.cc
1/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2 * vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3 *
4 * Copyright 2011 Daniel Nichter
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; version 2 of the License.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20#include <config.h>
21#include <drizzled/identifier.h>
22#include <drizzled/util/convert.h>
24#include <drizzled/execute.h>
25#include <drizzled/sql/result_set.h>
26#include <drizzled/plugin/listen.h>
27#include <drizzled/plugin/client.h>
28#include <drizzled/catalog/local.h>
29#include "auth_schema.h"
30
31namespace drizzle_plugin {
32namespace auth_schema {
33
34AuthSchema::AuthSchema(bool enabled) :
35 plugin::Authentication("auth_schema"),
36 sysvar_enabled(enabled)
37{
38 int error;
39 PCRE2_SIZE erroffset;
40 _ident_re= pcre2_compile(
41 reinterpret_cast<PCRE2_SPTR>("^`[^`]+`"),
42 PCRE2_ZERO_TERMINATED,
43 0,
44 &error,
45 &erroffset,
46 NULL);
47}
48
49bool AuthSchema::setTable(const string &table)
50{
51 if (table.empty())
52 {
53 errmsg_printf(error::ERROR, _("auth_schema table cannot be an empty string"));
54 return true; // error
55 }
56
57 if (table.find(".") == string::npos)
58 {
59 errmsg_printf(error::ERROR, _("auth_schema must be schema-qualified"));
60 return true; // error
61 }
62
63 sysvar_table= escapeQuoteAuthTable(table);
64
65 return false; // success
66}
67
68bool AuthSchema::verifyMySQLPassword(const string &real_password,
69 const string &scramble_bytes,
70 const string &client_password)
71{
72 if (scramble_bytes.size() != SHA1_DIGEST_LENGTH
73 || client_password.size() != SHA1_DIGEST_LENGTH)
74 return false;
75
76 uint8_t real_password_hash[SHA1_DIGEST_LENGTH];
77 drizzled_hex_to_string(
78 reinterpret_cast<char *>(real_password_hash),
79 real_password.c_str(),
80 SHA1_DIGEST_LENGTH * 2);
81
82 /* Hash the scramble that was sent to client with the local password. */
83 SHA1_CTX ctx;
84 uint8_t temp_hash[SHA1_DIGEST_LENGTH];
85 SHA1Init(&ctx);
86 SHA1Update(&ctx, reinterpret_cast<const uint8_t*>(scramble_bytes.c_str()), SHA1_DIGEST_LENGTH);
87 SHA1Update(&ctx, real_password_hash, SHA1_DIGEST_LENGTH);
88 SHA1Final(temp_hash, &ctx);
89
90 /* Next, XOR the result with what the client sent to get the original
91 single-hashed password. */
92 for (int x= 0; x < SHA1_DIGEST_LENGTH; x++)
93 temp_hash[x]= temp_hash[x] ^ client_password[x];
94
95 /* Hash this result once more to get the double-hashed password again. */
96 uint8_t client_password_hash[SHA1_DIGEST_LENGTH];
97 SHA1Init(&ctx);
98 SHA1Update(&ctx, temp_hash, SHA1_DIGEST_LENGTH);
99 SHA1Final(client_password_hash, &ctx);
100
101 /* These should match for a successful auth. */
102 return memcmp(real_password_hash, client_password_hash, SHA1_DIGEST_LENGTH) == 0;
103}
104
105bool AuthSchema::authenticate(const identifier::User &sctx, const string &password)
106{
107 // If plugin is disabled, deny everyone.
108 if (not sysvar_enabled)
109 return false;
110
111 // Plugin only works with MySQL hash passwords, so client needs
112 // to connect with --protocol mysql-plugin-auth.
113 if (sctx.getPasswordType() != identifier::User::MYSQL_HASH)
114 return false;
115
116 // Anonymous users are not allowed.
117 string user= escapeString(sctx.username());
118 if (user.empty())
119 return false;
120
121 // Create an internal session for ourself the first time we're called.
122 // I don't know why but doing this in the constructor crashes Drizzle
123 if (not _session)
124 {
125 _session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
126 identifier::user::mptr user_id= identifier::User::make_shared();
127 user_id->setUser("auth_schema");
128 _session->setUser(user_id);
129 }
130
131 // Create an execute a SQL statement to select the user from the auth table.
132 // Execute wraps the SQL to run within a transaction.
133 string sql= "SELECT password FROM " + sysvar_table + " WHERE user='" + user + "' LIMIT 1;";
134 Execute execute(*(_session.get()), true);
135 sql::ResultSet result_set(1);
136 execute.run(sql, result_set);
137 sql::Exception exception= result_set.getException();
138 drizzled::error_t err= exception.getErrorCode();
139 if ((err != EE_OK) && (err != ER_EMPTY_QUERY))
140 {
141 errmsg_printf(error::ERROR,
142 _("Error querying authentication schema: %s (error code %d. Query: %s"),
143 exception.getErrorMessage().c_str(), exception.getErrorCode(), sql.c_str());
144 return false;
145 }
146
147 // If there's a result and it's not null, verify the password from
148 // the client against the real password from the auth table.
149 if (result_set.next() and not result_set.isNull(0))
150 {
151 string real_password= result_set.getString(0);
152 // Return true if auth succeeds, else return false.
153 return verifyMySQLPassword(
154 real_password,
155 sctx.getPasswordContext(),
156 password);
157 }
158
159 // User doesn't exist in auth table; auth fails.
160 return false;
161}
162
163string AuthSchema::escapeQuoteAuthTable(const string &table)
164{
165 int pos= table.find(".");
166 string quoted_schema= escapeQuoteIdentifier(table.substr(0, pos));
167 string quoted_table= escapeQuoteIdentifier(table.substr(pos + 1, table.length() - pos));
168 return quoted_schema + "." + quoted_table;
169}
170
171string AuthSchema::escapeQuoteIdentifier(const string &input)
172{
173 if (input.empty())
174 return "``";
175
180 if (_ident_re != NULL)
181 {
182 pcre2_match_data *match_data= pcre2_match_data_create_from_pattern(_ident_re, NULL);
183 if (match_data != NULL)
184 {
185 int match_result= pcre2_match(
186 _ident_re, reinterpret_cast<PCRE2_SPTR>(input.c_str()),
187 input.length(), 0, 0, match_data, NULL);
188 pcre2_match_data_free(match_data);
189 if (match_result >= 0)
190 return input;
191 }
192 }
193
194 const char *pos= input.c_str();
195 const char *end= input.c_str()+input.length();
196 string ident= "`";
197
198 for (; pos != end ; pos++)
199 {
200 switch (*pos) {
201 case '`':
202 ident.push_back('\\');
203 ident.push_back('`');
204 break;
205 case '\\':
206 ident.push_back('\\');
207 ident.push_back('\\');
208 break;
209 default:
210 ident.push_back(*pos);
211 break;
212 }
213 }
214
215 ident.push_back('`');
216
217 return ident;
218}
219
220string AuthSchema::escapeString(const string &input)
221{
222 if (input.empty())
223 return input;
224
225 const char *pos= input.c_str();
226 const char *end= input.c_str()+input.length();
227 string res;
228
229 for (; pos != end ; pos++)
230 {
231 switch (*pos) {
232 case 0:
233 res.push_back('\\');
234 res.push_back('0');
235 break;
236 case '\n':
237 res.push_back('\\');
238 res.push_back('n');
239 break;
240 case '\r':
241 res.push_back('\\');
242 res.push_back('r');
243 break;
244 case '\\':
245 res.push_back('\\');
246 res.push_back('\\');
247 break;
248 case '\'':
249 res.push_back('\\');
250 res.push_back('\'');
251 break;
252 default:
253 res.push_back(*pos);
254 break;
255 }
256 }
257
258 return res;
259}
260
261AuthSchema::~AuthSchema()
262{
263 if (_ident_re != NULL)
264 pcre2_code_free(_ident_re);
265}
266
267} /* end namespace drizzle_plugin::auth_schema */
268} /* end namespace drizzle_plugin */
bool setTable(const string &table)
Set the authentication table.
Session::shared_ptr _session
Internal session for querying auth table.
string escapeQuoteAuthTable(const string &table)
Split, escape, and quote the auth table name.
string escapeString(const string &input)
Escape a string for use as a single-quoted string value.
bool authenticate(const identifier::User &sctx, const string &password)
string escapeQuoteIdentifier(const string &input)
Escape and quote an identifier.
bool verifyMySQLPassword(const string &real_password, const string &scramble_bytes, const string &client_password)
Verify that the client password matches the real password.
A set of Session members describing the current authenticated user.
static plugin::Client * getNullClient()
Definition listen.cc:184
SHA1 Declarations.