Debian Codegraph @

src/auth/SecurityDatabase/LegacyServer.cpp

raw
1 /*
2 * PROGRAM: JRD Access Method
3 * MODULE: LegacyServer.cpp
4 * DESCRIPTION: User information database access
5 *
6 * The contents of this file are subject to the Interbase Public
7 * License Version 1.0 (the "License"); you may not use this file
8 * except in compliance with the License. You may obtain a copy
9 * of the License at http://www.Inprise.com/IPL.html
10 *
11 * Software distributed under the License is distributed on an
12 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
13 * or implied. See the License for the specific language governing
14 * rights and limitations under the License.
15 *
16 * The Original Code was created by Inprise Corporation
17 * and its predecessors. Portions created by Inprise Corporation are
18 * Copyright (C) Inprise Corporation.
19 *
20 * All Rights Reserved.
21 * Contributor(s): ______________________________________.
22 *
23 * 2003.02.02 Dmitry Yemanov: Implemented cached security database connection
24 */
25
26 #include "firebird.h"
27
28 #include "ibase.h"
29 #include "gen/iberror.h"
30 #include "firebird/Interface.h"
31
32 #include "../auth/SecurityDatabase/LegacyServer.h"
33 #include "../auth/SecurityDatabase/LegacyHash.h"
34 #include "../auth/SecDbCache.h"
35 #include "../remote/remot_proto.h"
36 #include "../jrd/constants.h"
37 #include "../common/enc_proto.h"
38 #include "../jrd/status.h"
39 #include "../common/classes/init.h"
40 #include "../common/classes/ClumpletWriter.h"
41
42 #include <string.h>
43
44 #define PLUG_MODULE 1
45
46 using namespace Firebird;
47
48 namespace {
49
50 // BLR to search database for user name record
51
52 const UCHAR PWD_REQUEST[] =
53 {
54 blr_version5,
55 blr_begin,
56 blr_message, 1, 4, 0,
57 blr_long, 0,
58 blr_long, 0,
59 blr_short, 0,
60 blr_text, BLR_WORD(Auth::MAX_LEGACY_PASSWORD_LENGTH + 2),
61 blr_message, 0, 1, 0,
62 blr_cstring, 129, 0,
63 blr_receive, 0,
64 blr_begin,
65 blr_for,
66 blr_rse, 1,
67 blr_relation, 9, 'P', 'L', 'G', '$', 'U', 'S', 'E', 'R', 'S', 0,
68 blr_first,
69 blr_literal, blr_short, 0, 1, 0,
70 blr_boolean,
71 blr_eql,
72 blr_field, 0, 13, 'P', 'L', 'G', '$', 'U', 'S', 'E', 'R', '_', 'N', 'A', 'M', 'E',
73 blr_parameter, 0, 0, 0,
74 blr_end,
75 blr_send, 1,
76 blr_begin,
77 blr_assignment,
78 blr_field, 0, 7, 'P', 'L', 'G', '$', 'G', 'I', 'D',
79 blr_parameter, 1, 0, 0,
80 blr_assignment,
81 blr_field, 0, 7, 'P', 'L', 'G', '$', 'U', 'I', 'D',
82 blr_parameter, 1, 1, 0,
83 blr_assignment,
84 blr_literal, blr_short, 0, 1, 0,
85 blr_parameter, 1, 2, 0,
86 blr_assignment,
87 blr_field, 0, 10, 'P', 'L', 'G', '$', 'P', 'A', 'S', 'S', 'W', 'D',
88 blr_parameter, 1, 3, 0,
89 blr_end,
90 blr_send, 1,
91 blr_assignment,
92 blr_literal, blr_short, 0, 0, 0,
93 blr_parameter, 1, 2, 0,
94 blr_end,
95 blr_end,
96 blr_eoc
97 };
98
99 // Returns data in the following format
100
101 struct user_record
102 {
103 SLONG gid;
104 SLONG uid;
105 SSHORT flag;
106 SCHAR password[Auth::MAX_LEGACY_PASSWORD_LENGTH + 2];
107 };
108
109 typedef char user_name[129];
110
111 // Transaction parameter buffer
112
113 const UCHAR TPB[4] =
114 {
115 isc_tpb_version1,
116 isc_tpb_read,
117 isc_tpb_concurrency,
118 isc_tpb_wait
119 };
120
121 } // anonymous namespace
122
123 namespace Auth {
124
125 GlobalPtr<PluginDatabases> instances;
126
127
128 class SecurityDatabaseServer FB_FINAL :
129 public StdPlugin<IServerImpl<SecurityDatabaseServer, CheckStatusWrapper> >
130 {
131 public:
132 explicit SecurityDatabaseServer(IPluginConfig* p)
133 : iParameter(p)
134 { }
135
136 // IServer implementation
137 int authenticate(CheckStatusWrapper* status, IServerBlock* sBlock,
138 IWriter* writerInterface);
139 void setDbCryptCallback(CheckStatusWrapper*, ICryptKeyCallback*) { } // ignore
140 int release();
141
142 private:
143 RefPtr<IPluginConfig> iParameter;
144 };
145
146
147 class SecurityDatabase : public VSecDb
148 {
149 public:
150 bool lookup(void* inMsg, void* outMsg);
151
152 bool test()
153 {
154 return fb_ping(status, &lookup_db) == FB_SUCCESS;
155 }
156
157 // This 2 are needed to satisfy temporarily different calling requirements
158 static int shutdown(const int, const int, void*)
159 {
160 return instances->shutdown();
161 }
162 static void cleanup()
163 {
164 instances->shutdown();
165 }
166
167 SecurityDatabase(const char* secDbName)
168 : lookup_db(0), lookup_req(0)
169 {
170 prepare(secDbName);
171 }
172
173 private:
174 ISC_STATUS_ARRAY status;
175
176 isc_db_handle lookup_db;
177 isc_req_handle lookup_req;
178
179 ~SecurityDatabase();
180
181 void prepare(const char* secDbName);
182 void checkStatus(const char* callName, ISC_STATUS userError = isc_psw_db_error);
183 };
184
185 /******************************************************************************
186 *
187 * Private interface
188 */
189
190 SecurityDatabase::~SecurityDatabase()
191 {
192 // One can get 'invalid object' errors here cause provider
193 // may get unloaded before authentication plugin
194
195 if (lookup_req)
196 {
197 isc_release_request(status, &lookup_req);
198 if (status[1] != isc_bad_req_handle)
199 checkStatus("isc_release_request", 0);
200 }
201
202 if (lookup_db)
203 {
204 isc_detach_database(status, &lookup_db);
205 if (status[1] != isc_bad_db_handle)
206 checkStatus("isc_detach_database", 0);
207 }
208 }
209
210
211 void SecurityDatabase::prepare(const char* secureDbName)
212 {
213 if (lookup_db)
214 {
215 return;
216 }
217
218 #ifndef PLUG_MODULE
219 fb_shutdown_callback(status, shutdown, fb_shut_preproviders, 0);
220 #endif
221
222 lookup_db = lookup_req = 0;
223
224 // Perhaps build up a dpb
225 ClumpletWriter dpb(ClumpletReader::dpbList, MAX_DPB_SIZE);
226
227 // Attachment is for the security database
228 dpb.insertByte(isc_dpb_sec_attach, TRUE);
229
230 // Attach as SYSDBA
231 dpb.insertString(isc_dpb_trusted_auth, SYSDBA_USER_NAME, fb_strlen(SYSDBA_USER_NAME));
232
233 // Do not use loopback provider
234 dpb.insertString(isc_dpb_config, ParsedList::getNonLoopbackProviders(secureDbName));
235
236 isc_db_handle tempHandle = 0;
237 isc_attach_database(status, 0, secureDbName, &tempHandle,
238 dpb.getBufferLength(), reinterpret_cast<const char*>(dpb.getBuffer()));
239 checkStatus("isc_attach_database", isc_psw_attach);
240 lookup_db = tempHandle;
241
242 isc_compile_request(status, &lookup_db, &lookup_req, sizeof(PWD_REQUEST),
243 reinterpret_cast<const char*>(PWD_REQUEST));
244 if (status[1])
245 {
246 ISC_STATUS_ARRAY localStatus;
247 // ignore status returned in order to keep first error
248 isc_detach_database(localStatus, &lookup_db);
249 }
250
251 checkStatus("isc_compile_request", isc_psw_attach);
252 }
253
254 void SecurityDatabase::checkStatus(const char* callName, ISC_STATUS userError)
255 {
256 if (status[1] == 0)
257 return;
258
259 // suppress throwing errors from destructor which passes userError == 0
260 if (!userError)
261 return;
262
263 Arg::Gds secDbError(userError);
264
265 string message;
266 message.printf("Error in %s() API call when working with legacy security database", callName);
267 secDbError << Arg::Gds(isc_random) << message;
268
269 secDbError << Arg::StatusVector(status);
270 secDbError.raise();
271 }
272
273 bool SecurityDatabase::lookup(void* inMsg, void* outMsg)
274 {
275 isc_tr_handle lookup_trans = 0;
276
277 isc_start_transaction(status, &lookup_trans, 1, &lookup_db, sizeof(TPB), TPB);
278 checkStatus("isc_start_transaction", isc_psw_start_trans);
279
280 isc_start_and_send(status, &lookup_req, &lookup_trans, 0, sizeof(user_name), inMsg, 0);
281 checkStatus("isc_start_and_send");
282
283 bool found = false;
284 while (true)
285 {
286 user_record* user = static_cast<user_record*>(outMsg);
287 isc_receive(status, &lookup_req, 1, sizeof(user_record), user, 0);
288 checkStatus("isc_receive");
289
290 if (!user->flag || status[1])
291 break;
292
293 found = true;
294 }
295
296 isc_rollback_transaction(status, &lookup_trans);
297 checkStatus("isc_rollback_transaction");
298
299 return found;
300 }
301
302
303 /******************************************************************************
304 *
305 * Public interface
306 */
307
308 int SecurityDatabaseServer::authenticate(CheckStatusWrapper* status, IServerBlock* sBlock,
309 IWriter* authBlock)
310 {
311 status->init();
312
313 try
314 {
315 const char* user = sBlock->getLogin();
316 if (!user)
317 {
318 HANDSHAKE_DEBUG(fprintf(stderr, "LegacyServer (nologin) %d\n", IAuth::AUTH_CONTINUE));
319 return IAuth::AUTH_CONTINUE;
320 }
321 string login(user);
322
323 unsigned length;
324 const unsigned char* data = sBlock->getData(&length);
325 if (!(data && length))
326 {
327 HANDSHAKE_DEBUG(fprintf(stderr, "LegacyServer (nopw) %d\n", IAuth::AUTH_MORE_DATA));
328 return IAuth::AUTH_MORE_DATA;
329 }
330
331 bool found = false;
332 char pw1[MAX_LEGACY_PASSWORD_LENGTH + 1];
333 PathName secureDbName;
334 { // instance scope
335 // Get database block from cache
336 CachedSecurityDatabase::Instance instance;
337 instances->getInstance(iParameter, instance);
338
339 secureDbName = instance->secureDbName;
340 if (!instance->secDb)
341 instance->secDb = FB_NEW SecurityDatabase(instance->secureDbName);
342
343 user_name uname; // user name buffer
344 login.copyTo(uname, sizeof uname);
345 user_record user_block; // user record
346 found = instance->secDb->lookup(uname, &user_block);
347 fb_utils::copy_terminate(pw1, user_block.password, MAX_LEGACY_PASSWORD_LENGTH + 1);
348 }
349 if (!found)
350 {
351 HANDSHAKE_DEBUG(fprintf(stderr, "LegacyServer (badlogin) %d\n", IAuth::AUTH_CONTINUE));
352 return IAuth::AUTH_CONTINUE;
353 }
354
355 string storedHash(pw1, MAX_LEGACY_PASSWORD_LENGTH);
356 storedHash.rtrim();
357 storedHash.recalculate_length();
358
359 string passwordEnc;
360 passwordEnc.assign(data, length);
361
362 string newHash;
363 LegacyHash::hash(newHash, login, passwordEnc, storedHash);
364 if (newHash != storedHash)
365 {
366 bool legacyHash = Config::getLegacyHash();
367 if (legacyHash)
368 {
369 newHash.resize(MAX_LEGACY_PASSWORD_LENGTH + 2);
370 ENC_crypt(newHash.begin(), newHash.length(), passwordEnc.c_str(), LEGACY_PASSWORD_SALT);
371 newHash.recalculate_length();
372 newHash.erase(0, 2);
373 legacyHash = newHash == storedHash;
374 }
375 if (!legacyHash)
376 {
377 HANDSHAKE_DEBUG(fprintf(stderr, "LegacyServer (badpw) %d\n", IAuth::AUTH_CONTINUE));
378 return IAuth::AUTH_CONTINUE;
379 }
380 }
381
382 Jrd::FbLocalStatus s;
383 authBlock->add(&s, login.c_str());
384 check(&s);
385 authBlock->setDb(&s, secureDbName.c_str());
386 check(&s);
387 HANDSHAKE_DEBUG(fprintf(stderr, "LegacyServer (OK) %d\n", IAuth::AUTH_SUCCESS));
388 return IAuth::AUTH_SUCCESS;
389 }
390 catch (const Exception& ex)
391 {
392 ex.stuffException(status);
393 HANDSHAKE_DEBUG(fprintf(stderr, "LegacyServer: exception status:\n"));
394 HANDSHAKE_DEBUG(isc_print_status(status->getErrors()));
395 HANDSHAKE_DEBUG(isc_print_status(status->getWarnings()));
396 return IAuth::AUTH_FAILED;
397 }
398 }
399
400 int SecurityDatabaseServer::release()
401 {
402 if (--refCounter == 0)
403 {
404 delete this;
405 return 0;
406 }
407
408 return 1;
409 }
410
411 namespace {
412 SimpleFactory<SecurityDatabaseServer> factory;
413 }
414
415 void registerLegacyServer(IPluginManager* iPlugin)
416 {
417 iPlugin->registerPluginFactory(IPluginManager::TYPE_AUTH_SERVER,
418 "Legacy_Auth", &factory);
419 }
420
421 } // namespace Auth
422
423
424 #ifdef PLUG_MODULE
425
426 extern "C" FB_DLL_EXPORT void FB_PLUGIN_ENTRY_POINT(IMaster* master)
427 {
428 CachedMasterInterface::set(master);
429
430 getUnloadDetector()->setCleanup(Auth::SecurityDatabase::cleanup);
431 Auth::registerLegacyServer(PluginManagerInterfacePtr());
432 getUnloadDetector()->registerMe();
433 }
434
435 #endif // PLUG_MODULE