mariadb/sql/password.c
unknown 496741d576 Moved randomize and my_rnd under mysys
Added my_uuid
Added pre-support for PAGE_CHECKSUM
Added syntax for CREATE ... PAGE_CHECKSUM=# TABLE_CHECKSUM=#
Reserved place for page checksums on index, bitmap and block pages
Added index number to header of index pages
Added linked list for free directory entries (speeds up inserts with BLOCK format)
Calculate checksums in original column order (fixes bug with checksum on rows with BLOCK format)
Cleaned up all index handling to use 'info->s->keypage_header' (variable size) as the header for index pages (before this was '2')
Added 0xffffffff to end of index and block data bases and 0xfffffffe at end of bitmap pages when page checksums are not enabled
Added _ma_get_page_used() and _ma_get_used_and_node() to simplify index page header handling
rec_per_key_part is now in double precision
Reserved place in index file for my_guid and nulls_per_key_part
Give error HA_ERR_NEW_FILE if trying to open a Maria file with new, not yet supported extensions

Lots of renames to increase readability:

randomize() -> my_rnd_init()
st_maria_info -> st_maria_handler
st_maria_info -> MARIA_HA
st_maria_isaminfo -> st_maria_info
rand_struct -> my_rand_struct
rec_per_key_rows -> records_at_analyze


client/mysqladmin.cc:
  rand_struct -> my_rrnd_struct
include/maria.h:
  st_maria_info -> MARIA_HA
  st_maria_isaminfo -> st_maria_info
  Changed analyze statistics to be of double precission
  Changed offset to field to be 32bits instead of 64 (safe as a record without blobs can't be that big)
include/my_base.h:
  Added HA_OPTION_PAGE_CHECKSUM & HA_CREATE_PAGE_CHECKSUM
  Fixed comments
  Added HA_ERR_NEW_FILE
include/my_sys.h:
  Added prototypes and structures for my_uuid() and my_rnd()
include/myisamchk.h:
  Changed some buffers to size_t
  Added possibility to have key statistics with double precission
include/mysql_com.h:
  Move rand functions to mysys
libmysql/Makefile.shared:
  Added my_rnd
mysql-test/r/maria.result:
  Updated results
mysql-test/t/maria.test:
  More tests for checksum
mysys/Makefile.am:
  Added my_rnd.c and my_uuid.c
server-tools/instance-manager/listener.cc:
  Fixed include order (my_global.h should always be first)
server-tools/instance-manager/mysql_connection.cc:
  Fixed include order (my_global.h should always be first)
  Use my_rnd_init()
server-tools/instance-manager/mysql_connection.h:
  rand_struct -> my_rand_struct
sql/handler.h:
  Added flag for page checksums
sql/item_func.cc:
  Use new my_rnd() interface
sql/item_func.h:
  Use new my_rnd() interface
sql/item_strfunc.cc:
  Use new my_rnd() interface
sql/lex.h:
  Added PAGE_CHECKSUM and TABLE_CHECKSUM
sql/mysql_priv.h:
  Use new my_rnd() interface
sql/mysqld.cc:
  Use new my_rnd() interface
sql/password.c:
  Move my_rnd() to mysys
  Use new my_rnd() interface
sql/sql_class.cc:
  Use new my_rnd() interface
sql/sql_class.h:
  Use new my_rnd() interface
sql/sql_crypt.cc:
  Use new my_rnd() interface
sql/sql_crypt.h:
  Use new my_rnd() interface
sql/sql_show.cc:
  Simpler handling of ha_choice_values
  Added PAGE_CHECKSUM
sql/sql_table.cc:
  Enable correct checksum handling (for now) if not running in compatible mode
sql/sql_yacc.yy:
  Added table option PAGE_CHECKSUM
  Added future compatible table option TABLE_CHECKSUM (alias for CHECKSUM)
  Added 'choice' target to simplify code
sql/table.cc:
  Store flag for PAGE_CHECKSUM
sql/table.h:
  Added support for PAGE_CHECKSUM
storage/maria/ha_maria.cc:
  Remove protection for incompatbile frm and MAI
  (Slow, not needed test)
  Rec_per_key is now in double
  Remember row type for table
  Give warning if one Maria uses another row type than requested
  Removed some old ASK_MONTY entries (added comments instead)
  Added handling of PAGE_CHECKSUM flags
storage/maria/ma_bitmap.c:
  Added page checksums to bitmap pages
  Added special bitmap marker for bitmap pages
  (Used to find bugs when running without page checksums)
storage/maria/ma_blockrec.c:
  Added a free-link list over directory entries. This makes insert of small rows faster as we don't
  have to scan the whole directory to find a not used entry.
  Moved SANITY_CHECKS to maria_def.h
  Simplify code by introducing dir_entry_pos()
  Added support for PAGE_CHECKSUM
storage/maria/ma_blockrec.h:
  Added DIR_FREE_SIZE (linked list of free directory entries)
  Added PAGE_CHECKSUM
  Added 'dir_entry_pos()'
storage/maria/ma_check.c:
  Check that index pages has correct index number
  Calculate rec_per_key with double precission
  Simplify code by using '_ma_get_used_and_node()'
  Check free directory list
  Remove wrong end \n from messages
  maria_data_on_page() -> _ma_get_page_used()
  maria_putint() -> _ma_store_page_used()
  rec_per_key_rows -> records_at_analyze
storage/maria/ma_checksum.c:
  Calculate checksum in original column order
storage/maria/ma_create.c:
  Store original column order in index file
  Reserve place for nulls_per_key_part (future)
  Added support for PAGE_CHECKSUM
storage/maria/ma_dbug.c:
  Fixed wrong debug output of key of type 'ulong'
storage/maria/ma_delete.c:
  maria_data_on_page() -> _ma_get_used_and_node()
  maria_data_on_page() -> _ma_get_page_used()
  maria_putint() -> _ma_store_page_used()
  Added page header (index key number) to all index pages
  Reserved page for checksum on index pages
  Use keypage_header
storage/maria/ma_ft_update.c:
  maria_putint() -> _ma_store_page_used()
  Store key number at start of page
storage/maria/ma_loghandler.h:
  st_maria_info -> MARIA_HA
storage/maria/ma_open.c:
  rec_per_key is now in double precission
  Added 'nulls_per_key_part'
  Added 'extra_options' (flags for future)
  Added support for PAGE_CHECKSUM
  Give error HA_ERR_NEW_FILE when using unsupported maria extensions
  Added comments
  Add maria_uuid to index file
  Added functions to store and read column_nr map.
  Changed some functions to return my_bool instead of uint
storage/maria/ma_page.c:
  Added checks that pages has correct key nr
  Store 0xffffffff in checksum position if page checksums are not enabled
  Moved key-page-delete link to take into account keypage header
storage/maria/ma_preload.c:
  Remove old MyISAM dependent code
  When scanning pages, only add pages to page cache for the requested index
storage/maria/ma_range.c:
  maria_data_on_page() -> _ma_get_used_and_node()
  Use keypage_header
storage/maria/ma_rt_index.c:
  Fixed indentation
storage/maria/ma_rt_index.h:
  Added support for dynamic index page header
  Reserved place for PAGE_CHECKSUM
storage/maria/ma_rt_key.c:
  Fixed indentation
  maria_data_on_page() -> _ma_get_page_used()
  maria_putint() -> maria_store_page_used()
storage/maria/ma_rt_mbr.c:
  Fixed indentation
storage/maria/ma_rt_split.c:
  Fixed indentation
  maria_data_on_page () -> _ma_get_page_used()
storage/maria/ma_rt_test.c:
  Fixed indentation
storage/maria/ma_search.c:
  Remove support of using -1 as 'last used index' to _ma_check_index()
  maria_data_on_page() -> _ma_get_page_used()
  maria_data_on_page() -> _ma_get_used_and_node()
  Use keypage_header
storage/maria/ma_sort.c:
  Changed some buffers to size_t
  Changed rec_per_key_part to double
storage/maria/ma_static.c:
  Removed NEAR
  Added maria_uuid
storage/maria/ma_test2.c:
  Moevd testflag == 2 to correct place
  Remove test of reading with index number -1 (not supported anymore)
storage/maria/ma_test_recovery.expected:
  Updated results
storage/maria/ma_test_recovery:
  Changed tmp table names so that one can run maria_chk on them
storage/maria/ma_write.c:
  Fixed indentation
  Use keypage_header
  Store index number on index pages
  maria_putint() -> _ma_store_page_used()
  maria_data_on_page() -> ma_get_used_and_node()
  maria_data_on_page() -> _ma_get_page_used()
  Added PAGE_CHECKSUM
  Added Maria handler to some functions
  Removed some not needed casts
storage/maria/maria_chk.c:
  Added error handling for HA_ERR_NEW_FILE
  Added information about page checksums
  rec_per_key_part changed to double
  maria_data_on_page() -> _ma_get_page_used()
  Use keypage_header
storage/maria/maria_def.h:
  Added IDENTICAL_PAGES_AFTER_RECOVERY and SANITY_CHECKS
  Changed rec_per_key_part to double
  Added nulls_per_key_part
  rec_per_key_rows -> records_at_analyze
  st_maria_info -> MARIA_HA
  Reserve place for new statistics variables, uuid, checksums per page etc.
  Removed NEAR tags
  Changed some prototypes to use my_bool and size_t
storage/maria/maria_pack.c:
  st_maria_info -> MARIA_HA
  Fixed indentation
storage/myisam/mi_dbug.c:
  Fix wrong debug output for ULONG
mysys/my_rnd.c:
  New BitKeeper file ``mysys/my_rnd.c''
mysys/my_uuid.c:
  New BitKeeper file ``mysys/my_uuid.c''
2007-10-09 21:09:50 +03:00

496 lines
15 KiB
C

/* Copyright (C) 2000-2006 MySQL AB
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* password checking routines */
/*****************************************************************************
The main idea is that no password are sent between client & server on
connection and that no password are saved in mysql in a decodable form.
On connection a random string is generated and sent to the client.
The client generates a new string with a random generator inited with
the hash values from the password and the sent string.
This 'check' string is sent to the server where it is compared with
a string generated from the stored hash_value of the password and the
random string.
The password is saved (in user.password) by using the PASSWORD() function in
mysql.
This is .c file because it's used in libmysqlclient, which is entirely in C.
(we need it to be portable to a variety of systems).
Example:
update user set password=PASSWORD("hello") where user="test"
This saves a hashed number as a string in the password field.
The new authentication is performed in following manner:
SERVER: public_seed=create_random_string()
send(public_seed)
CLIENT: recv(public_seed)
hash_stage1=sha1("password")
hash_stage2=sha1(hash_stage1)
reply=xor(hash_stage1, sha1(public_seed,hash_stage2)
// this three steps are done in scramble()
send(reply)
SERVER: recv(reply)
hash_stage1=xor(reply, sha1(public_seed,hash_stage2))
candidate_hash2=sha1(hash_stage1)
check(candidate_hash2==hash_stage2)
// this three steps are done in check_scramble()
*****************************************************************************/
#include <my_global.h>
#include <my_sys.h>
#include <m_string.h>
#include <sha1.h>
#include "mysql.h"
/************ MySQL 3.23-4.0 authentication routines: untouched ***********/
/*
New (MySQL 3.21+) random generation structure initialization
SYNOPSIS
my_rnd_init()
rand_st OUT Structure to initialize
seed1 IN First initialization parameter
seed2 IN Second initialization parameter
*/
/*
Generate binary hash from raw text string
Used for Pre-4.1 password handling
SYNOPSIS
hash_password()
result OUT store hash in this location
password IN plain text password to build hash
password_len IN password length (password may be not null-terminated)
*/
void hash_password(ulong *result, const char *password, uint password_len)
{
register ulong nr=1345345333L, add=7, nr2=0x12345671L;
ulong tmp;
const char *password_end= password + password_len;
for (; password < password_end; password++)
{
if (*password == ' ' || *password == '\t')
continue; /* skip space in password */
tmp= (ulong) (uchar) *password;
nr^= (((nr & 63)+add)*tmp)+ (nr << 8);
nr2+=(nr2 << 8) ^ nr;
add+=tmp;
}
result[0]=nr & (((ulong) 1L << 31) -1L); /* Don't use sign bit (str2int) */;
result[1]=nr2 & (((ulong) 1L << 31) -1L);
}
/*
Create password to be stored in user database from raw string
Used for pre-4.1 password handling
SYNOPSIS
make_scrambled_password_323()
to OUT store scrambled password here
password IN user-supplied password
*/
void make_scrambled_password_323(char *to, const char *password)
{
ulong hash_res[2];
hash_password(hash_res, password, (uint) strlen(password));
sprintf(to, "%08lx%08lx", hash_res[0], hash_res[1]);
}
/*
Scramble string with password.
Used in pre 4.1 authentication phase.
SYNOPSIS
scramble_323()
to OUT Store scrambled message here. Buffer must be at least
SCRAMBLE_LENGTH_323+1 bytes long
message IN Message to scramble. Message must be at least
SRAMBLE_LENGTH_323 bytes long.
password IN Password to use while scrambling
*/
void scramble_323(char *to, const char *message, const char *password)
{
struct my_rnd_struct rand_st;
ulong hash_pass[2], hash_message[2];
if (password && password[0])
{
char extra, *to_start=to;
const char *message_end= message + SCRAMBLE_LENGTH_323;
hash_password(hash_pass,password, (uint) strlen(password));
hash_password(hash_message, message, SCRAMBLE_LENGTH_323);
my_rnd_init(&rand_st,hash_pass[0] ^ hash_message[0],
hash_pass[1] ^ hash_message[1]);
for (; message < message_end; message++)
*to++= (char) (floor(my_rnd(&rand_st)*31)+64);
extra=(char) (floor(my_rnd(&rand_st)*31));
while (to_start != to)
*(to_start++)^=extra;
}
*to= 0;
}
/*
Check scrambled message
Used in pre 4.1 password handling
SYNOPSIS
check_scramble_323()
scrambled scrambled message to check.
message original random message which was used for scrambling; must
be exactly SCRAMBLED_LENGTH_323 bytes long and
NULL-terminated.
hash_pass password which should be used for scrambling
All params are IN.
RETURN VALUE
0 - password correct
!0 - password invalid
*/
my_bool
check_scramble_323(const char *scrambled, const char *message,
ulong *hash_pass)
{
struct my_rnd_struct rand_st;
ulong hash_message[2];
char buff[16],*to,extra; /* Big enough for check */
const char *pos;
hash_password(hash_message, message, SCRAMBLE_LENGTH_323);
my_rnd_init(&rand_st,hash_pass[0] ^ hash_message[0],
hash_pass[1] ^ hash_message[1]);
to=buff;
DBUG_ASSERT(sizeof(buff) > SCRAMBLE_LENGTH_323);
for (pos=scrambled ; *pos && to < buff+sizeof(buff) ; pos++)
*to++=(char) (floor(my_rnd(&rand_st)*31)+64);
if (pos-scrambled != SCRAMBLE_LENGTH_323)
return 1;
extra=(char) (floor(my_rnd(&rand_st)*31));
to=buff;
while (*scrambled)
{
if (*scrambled++ != (char) (*to++ ^ extra))
return 1; /* Wrong password */
}
return 0;
}
static inline uint8 char_val(uint8 X)
{
return (uint) (X >= '0' && X <= '9' ? X-'0' :
X >= 'A' && X <= 'Z' ? X-'A'+10 : X-'a'+10);
}
/*
Convert password from hex string (as stored in mysql.user) to binary form.
SYNOPSIS
get_salt_from_password_323()
res OUT store salt here
password IN password string as stored in mysql.user
NOTE
This function does not have length check for passwords. It will just crash
Password hashes in old format must have length divisible by 8
*/
void get_salt_from_password_323(ulong *res, const char *password)
{
res[0]= res[1]= 0;
if (password)
{
while (*password)
{
ulong val=0;
uint i;
for (i=0 ; i < 8 ; i++)
val=(val << 4)+char_val(*password++);
*res++=val;
}
}
}
/*
Convert scrambled password from binary form to asciiz hex string.
SYNOPSIS
make_password_from_salt_323()
to OUT store resulting string password here, at least 17 bytes
salt IN password in salt format, 2 ulongs
*/
void make_password_from_salt_323(char *to, const ulong *salt)
{
sprintf(to,"%08lx%08lx", salt[0], salt[1]);
}
/*
**************** MySQL 4.1.1 authentication routines *************
*/
/*
Generate string of printable random characters of requested length
SYNOPSIS
create_random_string()
to OUT buffer for generation; must be at least length+1 bytes
long; result string is always null-terminated
length IN how many random characters to put in buffer
rand_st INOUT structure used for number generation
*/
void create_random_string(char *to, uint length,
struct my_rnd_struct *rand_st)
{
char *end= to + length;
/* Use pointer arithmetics as it is faster way to do so. */
for (; to < end; to++)
*to= (char) (my_rnd(rand_st)*94+33);
*to= '\0';
}
/* Character to use as version identifier for version 4.1 */
#define PVERSION41_CHAR '*'
/*
Convert given octet sequence to asciiz string of hex characters;
str..str+len and 'to' may not overlap.
SYNOPSIS
octet2hex()
buf OUT output buffer. Must be at least 2*len+1 bytes
str, len IN the beginning and the length of the input string
RETURN
buf+len*2
*/
char *octet2hex(char *to, const char *str, uint len)
{
const char *str_end= str + len;
for (; str != str_end; ++str)
{
*to++= _dig_vec_upper[((uchar) *str) >> 4];
*to++= _dig_vec_upper[((uchar) *str) & 0x0F];
}
*to= '\0';
return to;
}
/*
Convert given asciiz string of hex (0..9 a..f) characters to octet
sequence.
SYNOPSIS
hex2octet()
to OUT buffer to place result; must be at least len/2 bytes
str, len IN begin, length for character string; str and to may not
overlap; len % 2 == 0
*/
static void
hex2octet(uint8 *to, const char *str, uint len)
{
const char *str_end= str + len;
while (str < str_end)
{
register char tmp= char_val(*str++);
*to++= (tmp << 4) | char_val(*str++);
}
}
/*
Encrypt/Decrypt function used for password encryption in authentication.
Simple XOR is used here but it is OK as we crypt random strings. Note,
that XOR(s1, XOR(s1, s2)) == s2, XOR(s1, s2) == XOR(s2, s1)
SYNOPSIS
my_crypt()
to OUT buffer to hold crypted string; must be at least len bytes
long; to and s1 (or s2) may be the same.
s1, s2 IN input strings (of equal length)
len IN length of s1 and s2
*/
static void
my_crypt(char *to, const uchar *s1, const uchar *s2, uint len)
{
const uint8 *s1_end= s1 + len;
while (s1 < s1_end)
*to++= *s1++ ^ *s2++;
}
/*
MySQL 4.1.1 password hashing: SHA conversion (see RFC 2289, 3174) twice
applied to the password string, and then produced octet sequence is
converted to hex string.
The result of this function is used as return value from PASSWORD() and
is stored in the database.
SYNOPSIS
make_scrambled_password()
buf OUT buffer of size 2*SHA1_HASH_SIZE + 2 to store hex string
password IN NULL-terminated password string
*/
void
make_scrambled_password(char *to, const char *password)
{
SHA1_CONTEXT sha1_context;
uint8 hash_stage2[SHA1_HASH_SIZE];
mysql_sha1_reset(&sha1_context);
/* stage 1: hash password */
mysql_sha1_input(&sha1_context, (uint8 *) password, (uint) strlen(password));
mysql_sha1_result(&sha1_context, (uint8 *) to);
/* stage 2: hash stage1 output */
mysql_sha1_reset(&sha1_context);
mysql_sha1_input(&sha1_context, (uint8 *) to, SHA1_HASH_SIZE);
/* separate buffer is used to pass 'to' in octet2hex */
mysql_sha1_result(&sha1_context, hash_stage2);
/* convert hash_stage2 to hex string */
*to++= PVERSION41_CHAR;
octet2hex(to, (const char*) hash_stage2, SHA1_HASH_SIZE);
}
/*
Produce an obscure octet sequence from password and random
string, recieved from the server. This sequence corresponds to the
password, but password can not be easily restored from it. The sequence
is then sent to the server for validation. Trailing zero is not stored
in the buf as it is not needed.
This function is used by client to create authenticated reply to the
server's greeting.
SYNOPSIS
scramble()
buf OUT store scrambled string here. The buf must be at least
SHA1_HASH_SIZE bytes long.
message IN random message, must be exactly SCRAMBLE_LENGTH long and
NULL-terminated.
password IN users' password
*/
void
scramble(char *to, const char *message, const char *password)
{
SHA1_CONTEXT sha1_context;
uint8 hash_stage1[SHA1_HASH_SIZE];
uint8 hash_stage2[SHA1_HASH_SIZE];
mysql_sha1_reset(&sha1_context);
/* stage 1: hash password */
mysql_sha1_input(&sha1_context, (uint8 *) password, (uint) strlen(password));
mysql_sha1_result(&sha1_context, hash_stage1);
/* stage 2: hash stage 1; note that hash_stage2 is stored in the database */
mysql_sha1_reset(&sha1_context);
mysql_sha1_input(&sha1_context, hash_stage1, SHA1_HASH_SIZE);
mysql_sha1_result(&sha1_context, hash_stage2);
/* create crypt string as sha1(message, hash_stage2) */;
mysql_sha1_reset(&sha1_context);
mysql_sha1_input(&sha1_context, (const uint8 *) message, SCRAMBLE_LENGTH);
mysql_sha1_input(&sha1_context, hash_stage2, SHA1_HASH_SIZE);
/* xor allows 'from' and 'to' overlap: lets take advantage of it */
mysql_sha1_result(&sha1_context, (uint8 *) to);
my_crypt(to, (const uchar *) to, hash_stage1, SCRAMBLE_LENGTH);
}
/*
Check that scrambled message corresponds to the password; the function
is used by server to check that recieved reply is authentic.
This function does not check lengths of given strings: message must be
null-terminated, reply and hash_stage2 must be at least SHA1_HASH_SIZE
long (if not, something fishy is going on).
SYNOPSIS
check_scramble()
scramble clients' reply, presumably produced by scramble()
message original random string, previously sent to client
(presumably second argument of scramble()), must be
exactly SCRAMBLE_LENGTH long and NULL-terminated.
hash_stage2 hex2octet-decoded database entry
All params are IN.
RETURN VALUE
0 password is correct
!0 password is invalid
*/
my_bool
check_scramble(const char *scramble_arg, const char *message,
const uint8 *hash_stage2)
{
SHA1_CONTEXT sha1_context;
uint8 buf[SHA1_HASH_SIZE];
uint8 hash_stage2_reassured[SHA1_HASH_SIZE];
mysql_sha1_reset(&sha1_context);
/* create key to encrypt scramble */
mysql_sha1_input(&sha1_context, (const uint8 *) message, SCRAMBLE_LENGTH);
mysql_sha1_input(&sha1_context, hash_stage2, SHA1_HASH_SIZE);
mysql_sha1_result(&sha1_context, buf);
/* encrypt scramble */
my_crypt((char *) buf, buf, (const uchar *) scramble_arg, SCRAMBLE_LENGTH);
/* now buf supposedly contains hash_stage1: so we can get hash_stage2 */
mysql_sha1_reset(&sha1_context);
mysql_sha1_input(&sha1_context, buf, SHA1_HASH_SIZE);
mysql_sha1_result(&sha1_context, hash_stage2_reassured);
return memcmp(hash_stage2, hash_stage2_reassured, SHA1_HASH_SIZE);
}
/*
Convert scrambled password from asciiz hex string to binary form.
SYNOPSIS
get_salt_from_password()
res OUT buf to hold password. Must be at least SHA1_HASH_SIZE
bytes long.
password IN 4.1.1 version value of user.password
*/
void get_salt_from_password(uint8 *hash_stage2, const char *password)
{
hex2octet(hash_stage2, password+1 /* skip '*' */, SHA1_HASH_SIZE * 2);
}
/*
Convert scrambled password from binary form to asciiz hex string.
SYNOPSIS
make_password_from_salt()
to OUT store resulting string here, 2*SHA1_HASH_SIZE+2 bytes
salt IN password in salt format
*/
void make_password_from_salt(char *to, const uint8 *hash_stage2)
{
*to++= PVERSION41_CHAR;
octet2hex(to, (const char*) hash_stage2, SHA1_HASH_SIZE);
}