~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000-2006 MySQL AB
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6
7
   This program is distributed in the hope that it will be useful,
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
   GNU General Public License for more details.
11
12
   You should have received a copy of the GNU General Public License
13
   along with this program; if not, write to the Free Software
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
16
/* password checking routines */
17
/*****************************************************************************
18
  The main idea is that no password are sent between client & server on
19
  connection and that no password are saved in mysql in a decodable form.
20
21
  On connection a random string is generated and sent to the client.
22
  The client generates a new string with a random generator inited with
23
  the hash values from the password and the sent string.
24
  This 'check' string is sent to the server where it is compared with
25
  a string generated from the stored hash_value of the password and the
26
  random string.
27
28
  The password is saved (in user.password) by using the PASSWORD() function in
29
  mysql.
30
31
  This is .c file because it's used in libmysqlclient, which is entirely in C.
32
  (we need it to be portable to a variety of systems).
33
  Example:
34
    update user set password=PASSWORD("hello") where user="test"
35
  This saves a hashed number as a string in the password field.
36
37
  The new authentication is performed in following manner:
38
39
  SERVER:  public_seed=create_random_string()
40
           send(public_seed)
41
42
  CLIENT:  recv(public_seed)
43
           hash_stage1=sha1("password")
44
           hash_stage2=sha1(hash_stage1)
45
           reply=xor(hash_stage1, sha1(public_seed,hash_stage2)
46
47
           // this three steps are done in scramble() 
48
49
           send(reply)
50
51
     
52
  SERVER:  recv(reply)
53
           hash_stage1=xor(reply, sha1(public_seed,hash_stage2))
54
           candidate_hash2=sha1(hash_stage1)
55
           check(candidate_hash2==hash_stage2)
56
57
           // this three steps are done in check_scramble()
58
59
*****************************************************************************/
60
61
#include <my_global.h>
62
#include <my_sys.h>
63
#include <m_string.h>
64
#include <sha1.h>
65
#include "mysql.h"
66
67
/************ MySQL 3.23-4.0 authentication routines: untouched ***********/
68
69
/*
70
  New (MySQL 3.21+) random generation structure initialization
71
  SYNOPSIS
72
    randominit()
73
    rand_st    OUT  Structure to initialize
74
    seed1      IN   First initialization parameter
75
    seed2      IN   Second initialization parameter
76
*/
77
78
void randominit(struct rand_struct *rand_st, ulong seed1, ulong seed2)
79
{                                               /* For mysql 3.21.# */
80
#ifdef HAVE_purify
81
  bzero((char*) rand_st,sizeof(*rand_st));      /* Avoid UMC varnings */
82
#endif
83
  rand_st->max_value= 0x3FFFFFFFL;
84
  rand_st->max_value_dbl=(double) rand_st->max_value;
85
  rand_st->seed1=seed1%rand_st->max_value ;
86
  rand_st->seed2=seed2%rand_st->max_value;
87
}
88
89
90
/*
91
    Generate random number.
92
  SYNOPSIS
93
    my_rnd()
94
    rand_st    INOUT  Structure used for number generation
95
  RETURN VALUE
96
    generated pseudo random number
97
*/
98
99
double my_rnd(struct rand_struct *rand_st)
100
{
101
  rand_st->seed1=(rand_st->seed1*3+rand_st->seed2) % rand_st->max_value;
102
  rand_st->seed2=(rand_st->seed1+rand_st->seed2+33) % rand_st->max_value;
103
  return (((double) rand_st->seed1)/rand_st->max_value_dbl);
104
}
105
106
107
/*
108
    Generate binary hash from raw text string 
109
    Used for Pre-4.1 password handling
110
  SYNOPSIS
111
    hash_password()
112
    result       OUT store hash in this location
113
    password     IN  plain text password to build hash
114
    password_len IN  password length (password may be not null-terminated)
115
*/
116
117
void hash_password(ulong *result, const char *password, uint password_len)
118
{
119
  register ulong nr=1345345333L, add=7, nr2=0x12345671L;
120
  ulong tmp;
121
  const char *password_end= password + password_len;
122
  for (; password < password_end; password++)
123
  {
124
    if (*password == ' ' || *password == '\t')
125
      continue;                                 /* skip space in password */
126
    tmp= (ulong) (uchar) *password;
127
    nr^= (((nr & 63)+add)*tmp)+ (nr << 8);
128
    nr2+=(nr2 << 8) ^ nr;
129
    add+=tmp;
130
  }
131
  result[0]=nr & (((ulong) 1L << 31) -1L); /* Don't use sign bit (str2int) */;
132
  result[1]=nr2 & (((ulong) 1L << 31) -1L);
133
}
134
135
136
/*
137
    Create password to be stored in user database from raw string
138
    Used for pre-4.1 password handling
139
  SYNOPSIS
140
    make_scrambled_password_323()
141
    to        OUT store scrambled password here
142
    password  IN  user-supplied password
143
*/
144
145
void make_scrambled_password_323(char *to, const char *password)
146
{
147
  ulong hash_res[2];
148
  hash_password(hash_res, password, (uint) strlen(password));
149
  sprintf(to, "%08lx%08lx", hash_res[0], hash_res[1]);
150
}
151
152
153
/*
154
    Scramble string with password.
155
    Used in pre 4.1 authentication phase.
156
  SYNOPSIS
157
    scramble_323()
158
    to       OUT Store scrambled message here. Buffer must be at least
159
                 SCRAMBLE_LENGTH_323+1 bytes long
160
    message  IN  Message to scramble. Message must be at least
161
                 SRAMBLE_LENGTH_323 bytes long.
162
    password IN  Password to use while scrambling
163
*/
164
165
void scramble_323(char *to, const char *message, const char *password)
166
{
167
  struct rand_struct rand_st;
168
  ulong hash_pass[2], hash_message[2];
169
170
  if (password && password[0])
171
  {
172
    char extra, *to_start=to;
173
    const char *message_end= message + SCRAMBLE_LENGTH_323;
174
    hash_password(hash_pass,password, (uint) strlen(password));
175
    hash_password(hash_message, message, SCRAMBLE_LENGTH_323);
176
    randominit(&rand_st,hash_pass[0] ^ hash_message[0],
177
               hash_pass[1] ^ hash_message[1]);
178
    for (; message < message_end; message++)
179
      *to++= (char) (floor(my_rnd(&rand_st)*31)+64);
180
    extra=(char) (floor(my_rnd(&rand_st)*31));
181
    while (to_start != to)
182
      *(to_start++)^=extra;
183
  }
184
  *to= 0;
185
}
186
187
188
/*
189
    Check scrambled message
190
    Used in pre 4.1 password handling
191
  SYNOPSIS
192
    check_scramble_323()
193
    scrambled  scrambled message to check.
194
    message    original random message which was used for scrambling; must
195
               be exactly SCRAMBLED_LENGTH_323 bytes long and
196
               NULL-terminated.
197
    hash_pass  password which should be used for scrambling
198
    All params are IN.
199
200
  RETURN VALUE
201
    0 - password correct
202
   !0 - password invalid
203
*/
204
205
my_bool
206
check_scramble_323(const char *scrambled, const char *message,
207
                   ulong *hash_pass)
208
{
209
  struct rand_struct rand_st;
210
  ulong hash_message[2];
211
  char buff[16],*to,extra;                      /* Big enough for check */
212
  const char *pos;
213
214
  hash_password(hash_message, message, SCRAMBLE_LENGTH_323);
215
  randominit(&rand_st,hash_pass[0] ^ hash_message[0],
216
             hash_pass[1] ^ hash_message[1]);
217
  to=buff;
218
  DBUG_ASSERT(sizeof(buff) > SCRAMBLE_LENGTH_323);
219
  for (pos=scrambled ; *pos && to < buff+sizeof(buff) ; pos++)
220
    *to++=(char) (floor(my_rnd(&rand_st)*31)+64);
221
  if (pos-scrambled != SCRAMBLE_LENGTH_323)
222
    return 1;
223
  extra=(char) (floor(my_rnd(&rand_st)*31));
224
  to=buff;
225
  while (*scrambled)
226
  {
227
    if (*scrambled++ != (char) (*to++ ^ extra))
228
      return 1;                                 /* Wrong password */
229
  }
230
  return 0;
231
}
232
233
static inline uint8 char_val(uint8 X)
234
{
235
  return (uint) (X >= '0' && X <= '9' ? X-'0' :
236
      X >= 'A' && X <= 'Z' ? X-'A'+10 : X-'a'+10);
237
}
238
239
240
/*
241
    Convert password from hex string (as stored in mysql.user) to binary form.
242
  SYNOPSIS
243
    get_salt_from_password_323()
244
    res       OUT store salt here 
245
    password  IN  password string as stored in mysql.user
246
  NOTE
247
    This function does not have length check for passwords. It will just crash
248
    Password hashes in old format must have length divisible by 8
249
*/
250
251
void get_salt_from_password_323(ulong *res, const char *password)
252
{
253
  res[0]= res[1]= 0;
254
  if (password)
255
  {
256
    while (*password)
257
    {
258
      ulong val=0;
259
      uint i;
260
      for (i=0 ; i < 8 ; i++)
261
        val=(val << 4)+char_val(*password++);
262
      *res++=val;
263
    }
264
  }
265
}
266
267
268
/*
269
    Convert scrambled password from binary form to asciiz hex string.
270
  SYNOPSIS
271
    make_password_from_salt_323()
272
    to    OUT store resulting string password here, at least 17 bytes 
273
    salt  IN  password in salt format, 2 ulongs 
274
*/
275
276
void make_password_from_salt_323(char *to, const ulong *salt)
277
{
278
  sprintf(to,"%08lx%08lx", salt[0], salt[1]);
279
}
280
281
282
/*
283
     **************** MySQL 4.1.1 authentication routines *************
284
*/
285
286
/*
287
    Generate string of printable random characters of requested length
288
  SYNOPSIS
289
    create_random_string()
290
    to       OUT   buffer for generation; must be at least length+1 bytes
291
                   long; result string is always null-terminated
292
    length   IN    how many random characters to put in buffer
293
    rand_st  INOUT structure used for number generation
294
*/
295
296
void create_random_string(char *to, uint length, struct rand_struct *rand_st)
297
{
298
  char *end= to + length;
299
  /* Use pointer arithmetics as it is faster way to do so. */
300
  for (; to < end; to++)
301
    *to= (char) (my_rnd(rand_st)*94+33);
302
  *to= '\0';
303
}
304
305
306
/* Character to use as version identifier for version 4.1 */
307
308
#define PVERSION41_CHAR '*'
309
310
311
/*
312
    Convert given octet sequence to asciiz string of hex characters;
313
    str..str+len and 'to' may not overlap.
314
  SYNOPSIS
315
    octet2hex()
316
    buf       OUT output buffer. Must be at least 2*len+1 bytes
317
    str, len  IN  the beginning and the length of the input string
318
319
  RETURN
320
    buf+len*2
321
*/
322
323
char *octet2hex(char *to, const char *str, uint len)
324
{
325
  const char *str_end= str + len; 
326
  for (; str != str_end; ++str)
327
  {
328
    *to++= _dig_vec_upper[((uchar) *str) >> 4];
329
    *to++= _dig_vec_upper[((uchar) *str) & 0x0F];
330
  }
331
  *to= '\0';
332
  return to;
333
}
334
335
336
/*
337
    Convert given asciiz string of hex (0..9 a..f) characters to octet
338
    sequence.
339
  SYNOPSIS
340
    hex2octet()
341
    to        OUT buffer to place result; must be at least len/2 bytes
342
    str, len  IN  begin, length for character string; str and to may not
343
                  overlap; len % 2 == 0
344
*/ 
345
346
static void
347
hex2octet(uint8 *to, const char *str, uint len)
348
{
349
  const char *str_end= str + len;
350
  while (str < str_end)
351
  {
352
    register char tmp= char_val(*str++);
353
    *to++= (tmp << 4) | char_val(*str++);
354
  }
355
}
356
357
358
/*
359
    Encrypt/Decrypt function used for password encryption in authentication.
360
    Simple XOR is used here but it is OK as we crypt random strings. Note,
361
    that XOR(s1, XOR(s1, s2)) == s2, XOR(s1, s2) == XOR(s2, s1)
362
  SYNOPSIS
363
    my_crypt()
364
    to      OUT buffer to hold crypted string; must be at least len bytes
365
                long; to and s1 (or s2) may be the same.
366
    s1, s2  IN  input strings (of equal length)
367
    len     IN  length of s1 and s2
368
*/
369
370
static void
371
my_crypt(char *to, const uchar *s1, const uchar *s2, uint len)
372
{
373
  const uint8 *s1_end= s1 + len;
374
  while (s1 < s1_end)
375
    *to++= *s1++ ^ *s2++;
376
}
377
378
379
/*
380
    MySQL 4.1.1 password hashing: SHA conversion (see RFC 2289, 3174) twice
381
    applied to the password string, and then produced octet sequence is
382
    converted to hex string.
383
    The result of this function is used as return value from PASSWORD() and
384
    is stored in the database.
385
  SYNOPSIS
386
    make_scrambled_password()
387
    buf       OUT buffer of size 2*SHA1_HASH_SIZE + 2 to store hex string
388
    password  IN  NULL-terminated password string
389
*/
390
391
void
392
make_scrambled_password(char *to, const char *password)
393
{
394
  SHA1_CONTEXT sha1_context;
395
  uint8 hash_stage2[SHA1_HASH_SIZE];
396
397
  mysql_sha1_reset(&sha1_context);
398
  /* stage 1: hash password */
399
  mysql_sha1_input(&sha1_context, (uint8 *) password, (uint) strlen(password));
400
  mysql_sha1_result(&sha1_context, (uint8 *) to);
401
  /* stage 2: hash stage1 output */
402
  mysql_sha1_reset(&sha1_context);
403
  mysql_sha1_input(&sha1_context, (uint8 *) to, SHA1_HASH_SIZE);
404
  /* separate buffer is used to pass 'to' in octet2hex */
405
  mysql_sha1_result(&sha1_context, hash_stage2);
406
  /* convert hash_stage2 to hex string */
407
  *to++= PVERSION41_CHAR;
408
  octet2hex(to, (const char*) hash_stage2, SHA1_HASH_SIZE);
409
}
410
  
411
412
/*
413
    Produce an obscure octet sequence from password and random
414
    string, recieved from the server. This sequence corresponds to the
415
    password, but password can not be easily restored from it. The sequence
416
    is then sent to the server for validation. Trailing zero is not stored
417
    in the buf as it is not needed.
418
    This function is used by client to create authenticated reply to the
419
    server's greeting.
420
  SYNOPSIS
421
    scramble()
422
    buf       OUT store scrambled string here. The buf must be at least 
423
                  SHA1_HASH_SIZE bytes long. 
424
    message   IN  random message, must be exactly SCRAMBLE_LENGTH long and 
425
                  NULL-terminated.
426
    password  IN  users' password 
427
*/
428
429
void
430
scramble(char *to, const char *message, const char *password)
431
{
432
  SHA1_CONTEXT sha1_context;
433
  uint8 hash_stage1[SHA1_HASH_SIZE];
434
  uint8 hash_stage2[SHA1_HASH_SIZE];
435
436
  mysql_sha1_reset(&sha1_context);
437
  /* stage 1: hash password */
438
  mysql_sha1_input(&sha1_context, (uint8 *) password, (uint) strlen(password));
439
  mysql_sha1_result(&sha1_context, hash_stage1);
440
  /* stage 2: hash stage 1; note that hash_stage2 is stored in the database */
441
  mysql_sha1_reset(&sha1_context);
442
  mysql_sha1_input(&sha1_context, hash_stage1, SHA1_HASH_SIZE);
443
  mysql_sha1_result(&sha1_context, hash_stage2);
444
  /* create crypt string as sha1(message, hash_stage2) */;
445
  mysql_sha1_reset(&sha1_context);
446
  mysql_sha1_input(&sha1_context, (const uint8 *) message, SCRAMBLE_LENGTH);
447
  mysql_sha1_input(&sha1_context, hash_stage2, SHA1_HASH_SIZE);
448
  /* xor allows 'from' and 'to' overlap: lets take advantage of it */
449
  mysql_sha1_result(&sha1_context, (uint8 *) to);
450
  my_crypt(to, (const uchar *) to, hash_stage1, SCRAMBLE_LENGTH);
451
}
452
453
454
/*
455
    Check that scrambled message corresponds to the password; the function
456
    is used by server to check that recieved reply is authentic.
457
    This function does not check lengths of given strings: message must be
458
    null-terminated, reply and hash_stage2 must be at least SHA1_HASH_SIZE
459
    long (if not, something fishy is going on).
460
  SYNOPSIS
461
    check_scramble()
462
    scramble     clients' reply, presumably produced by scramble()
463
    message      original random string, previously sent to client
464
                 (presumably second argument of scramble()), must be 
465
                 exactly SCRAMBLE_LENGTH long and NULL-terminated.
466
    hash_stage2  hex2octet-decoded database entry
467
    All params are IN.
468
469
  RETURN VALUE
470
    0  password is correct
471
    !0  password is invalid
472
*/
473
474
my_bool
475
check_scramble(const char *scramble_arg, const char *message,
476
               const uint8 *hash_stage2)
477
{
478
  SHA1_CONTEXT sha1_context;
479
  uint8 buf[SHA1_HASH_SIZE];
480
  uint8 hash_stage2_reassured[SHA1_HASH_SIZE];
481
482
  mysql_sha1_reset(&sha1_context);
483
  /* create key to encrypt scramble */
484
  mysql_sha1_input(&sha1_context, (const uint8 *) message, SCRAMBLE_LENGTH);
485
  mysql_sha1_input(&sha1_context, hash_stage2, SHA1_HASH_SIZE);
486
  mysql_sha1_result(&sha1_context, buf);
487
  /* encrypt scramble */
488
    my_crypt((char *) buf, buf, (const uchar *) scramble_arg, SCRAMBLE_LENGTH);
489
  /* now buf supposedly contains hash_stage1: so we can get hash_stage2 */
490
  mysql_sha1_reset(&sha1_context);
491
  mysql_sha1_input(&sha1_context, buf, SHA1_HASH_SIZE);
492
  mysql_sha1_result(&sha1_context, hash_stage2_reassured);
493
  return memcmp(hash_stage2, hash_stage2_reassured, SHA1_HASH_SIZE);
494
}
495
496
497
/*
498
  Convert scrambled password from asciiz hex string to binary form.
499
500
  SYNOPSIS
501
    get_salt_from_password()
502
    res       OUT buf to hold password. Must be at least SHA1_HASH_SIZE
503
                  bytes long.
504
    password  IN  4.1.1 version value of user.password
505
*/
506
    
507
void get_salt_from_password(uint8 *hash_stage2, const char *password)
508
{
509
  hex2octet(hash_stage2, password+1 /* skip '*' */, SHA1_HASH_SIZE * 2);
510
}
511
512
/*
513
    Convert scrambled password from binary form to asciiz hex string.
514
  SYNOPSIS
515
    make_password_from_salt()
516
    to    OUT store resulting string here, 2*SHA1_HASH_SIZE+2 bytes 
517
    salt  IN  password in salt format
518
*/
519
520
void make_password_from_salt(char *to, const uint8 *hash_stage2)
521
{
522
  *to++= PVERSION41_CHAR;
523
  octet2hex(to, (const char*) hash_stage2, SHA1_HASH_SIZE);
524
}