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