Mysql源码学习――用户认证原理与实现_MySQL
bitsCN.com
前几节跟踪了Connection Manager和Thread Manager,在连接的过程中,还有一个身份认证的过程,就是大家所熟悉的
验证用户名和密码的过程,我们平时做一个系统的时候,很多时候都会涉及到身份验证。今天我们就来看下Mysql是如何进
行验证的。(注意是登录,不是登陆^_^)
一、用户认证原理
我们在应用程序中实现验证的方式基本上都是创建一张用户表,里面至少包含username和password两个字段,
password基本上都是加密后进行存储的。作为数据库,对用户的限制较多,不是像我说的仅仅只有username和password
这么简单了。首先粗略的讲下访问控制。
信息系统中,访问控制分为自主访问控制(DAC)和强制访问控制(MAC)。具体到DBMS,自主访问控制就是我们所熟悉
的GRANT,REVOKE,大多数数据库都支持自助的访问控制。强制访问控制就是ORACLE中的LABEL,只有很少的一些系统支持MAC。
严格来说,登录并不属于访问控制机制,而应该属于用户身份识别和认证。在Mysql中,将登录和DAC的相关接口都实现在了
sql_acl.cc中(其实说登录是用户拥有的一种权限也未尝不可,正如ORACLE中的CREATE SESSION,不过登录并不仅仅是一种权
限,还包含很多其他的属性),从文件名大家可以看出来,ACL即ACCESS CONTROL LIST,访问控制列表,这是实现访问控制的
基本方法。下图是Mysql的整个访问控制的流程。
Mysql中用户管理模块的信息存储在系统表mysql.User中,这个表不仅仅存放了授权用户的基本信息,还存放一些权限
信息。我们首先大概看一下这个表的结构。
+-----------------------+-----------------------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------+-----------------------------------+------+-----+---------+-------+
| Host | char(60) | NO | PRI | | |
| User | char(16) | NO | PRI | | |
| Password | char(41) | NO | | | |
| Select_priv | enum('N','Y') | NO | | N | |
| Insert_priv | enum('N','Y') | NO | | N | |
| Update_priv | enum('N','Y') | NO | | N | |
| Delete_priv | enum('N','Y') | NO | | N | |
| Create_priv | enum('N','Y') | NO | | N | |
| Drop_priv | enum('N','Y') | NO | | N | |
| Reload_priv | enum('N','Y') | NO | | N | |
| Shutdown_priv | enum('N','Y') | NO | | N | |
| Process_priv | enum('N','Y') | NO | | N | |
| File_priv | enum('N','Y') | NO | | N | |
| Grant_priv | enum('N','Y') | NO | | N | |
| References_priv | enum('N','Y') | NO | | N | |
| Index_priv | enum('N','Y') | NO | | N | |
| Alter_priv | enum('N','Y') | NO | | N | |
| Show_db_priv | enum('N','Y') | NO | | N | |
| Super_priv | enum('N','Y') | NO | | N | |
| Create_tmp_table_priv | enum('N','Y') | NO | | N | |
| Lock_tables_priv | enum('N','Y') | NO | | N | |
| Execute_priv | enum('N','Y') | NO | | N | |
| Repl_slave_priv | enum('N','Y') | NO | | N | |
| Repl_client_priv | enum('N','Y') | NO | | N | |
| Create_view_priv | enum('N','Y') | NO | | N | |
| Show_view_priv | enum('N','Y') | NO | | N | |
| Create_routine_priv | enum('N','Y') | NO | | N | |
| Alter_routine_priv | enum('N','Y') | NO | | N | |
| Create_user_priv | enum('N','Y') | NO | | N | |
| Event_priv | enum('N','Y') | NO | | N | |
| Trigger_priv | enum('N','Y') | NO | | N | |
| ssl_type | enum('','ANY','X509','SPECIFIED') | NO | | | |
| ssl_cipher | blob | NO | | NULL | |
| x509_issuer | blob | NO | | NULL | |
| x509_subject | blob | NO | | NULL | |
| max_questions | int(11) unsigned | NO | | 0 | |
| max_updates | int(11) unsigned | NO | | 0 | |
| max_connections | int(11) unsigned | NO | | 0 | |
| max_user_connections | int(11) unsigned | NO | | 0 | |
+-----------------------+-----------------------------------+------+-----+---------+-------+
39 rows in set (0.01 sec)
这个表包含了39个字段,对于我们登录来说,应该主要是使用前三个字段,即Host,User,Password。
mysql> select Host,User,Password from user;
+-----------+------+----------+
| Host | User | Password |
+-----------+------+----------+
| localhost | root | |
| 127.0.0.1 | root | |
| localhost | | |
+-----------+------+----------+
3 rows in set (0.00 sec)
这里比我们预想的只需要用户名和密码的方式有所出入,多了一个Host字段,这个字段起到什么作用呢?!原来Mysql的登录认证不仅需要验证用户名和密码,还需要验证连接的主机地址,这样也是为了提高安全性吧。那如果我想一个用户在任何地址都可以进行登录岂不是要设置很多地址?Mysql提供了通配符,可以设置Host字段为*,这就代表可以匹配任何Host。具体看下这三行的意思,这三行的密码均为空。针对root用户,不需要输入密码,客户端的地址为本机。第三行的用户名为空,Host为localhost,说明本地的任何用户均可以进行登录,即使是个不存在的用户也可以登录成功,但是仅限于登录,没有其他相关的权限,无法进行实际操作。
二、源码跟踪
在Connection Manager中提到了login_connection函数用于检查用户名和密码等相关信息,其源码如下(重点的函数代码
会着色):
static bool login_connection(THD *thd)
{
NET *net= &thd->net;
int error;
DBUG_ENTER("login_connection");
DBUG_PRINT("info", ("login_connection called by thread %lu",
thd->thread_id));
/* Use "connect_timeout" value during connection phase */
my_net_set_read_timeout(net, connect_timeout);
my_net_set_write_timeout(net, connect_timeout);
error= check_connection(thd); //此处是验证的具体函数
net_end_statement(thd);
if (error)
{ // Wrong permissions
#ifdef __NT__
if (vio_type(net->vio) == VIO_TYPE_NAMEDPIPE)
my_sleep(1000); /* must wait after eof() */
#endif
statistic_increment(aborted_connects,&LOCK_status);
DBUG_RETURN(1);
}
/* Connect completed, set read/write timeouts back to default */
my_net_set_read_timeout(net, thd->variables.net_read_timeout);
my_net_set_write_timeout(net, thd->variables.net_write_timeout);
DBUG_RETURN(0);
}
此函数主要是功能是调用函数check_connection进行用户认证,由于函数check_connection过长,对其进行简化,如下所示:
static int check_connection(THD *thd)
{
uint connect_errors= 0;
NET *net= &thd->net;
ulong pkt_len= 0;
char *end;
DBUG_PRINT("info",
("New connection received on %s", vio_description(net->vio)));
#ifdef SIGNAL_WITH_VIO_CLOSE
thd->set_active_vio(net->vio);
#endif
if (!thd->main_security_ctx.host) // If TCP/IP connection
{
char ip[30];
if (vio_peer_addr(net->vio, ip, &thd->peer_port))
{
my_error(ER_BAD_HOST_ERROR, MYF(0), thd->main_security_ctx.host_or_ip);
return 1;
}
if (!(thd->main_security_ctx.ip= my_strdup(ip,MYF(MY_WME))))
return 1; /* The error is set by my_strdup(). */
thd->main_security_ctx.host_or_ip= thd->main_security_ctx.ip;
vio_in_addr(net->vio,&thd->remote.sin_addr);
if (!(specialflag & SPECIAL_NO_RESOLVE))
{
vio_in_addr(net->vio,&thd->remote.sin_addr);
thd->main_security_ctx.host=
ip_to_hostname(&thd->remote.sin_addr, &connect_errors);
/* Cut very long hostnames to avoid possible overflows */
if (thd->main_security_ctx.host)
{
if (thd->main_security_ctx.host != my_localhost)
thd->main_security_ctx.host[min(strlen(thd->main_security_ctx.host),
HOSTNAME_LENGTH)]= 0;
thd->main_security_ctx.host_or_ip= thd->main_security_ctx.host;
}
if (connect_errors > max_connect_errors)
{
my_error(ER_HOST_IS_BLOCKED, MYF(0), thd->main_security_ctx.host_or_ip);
return 1;
}
}
...
if (acl_check_host(thd->main_security_ctx.host, thd->main_security_ctx.ip))//此处验证主机名或IP是否存在
{
my_error(ER_HOST_NOT_PRIVILEGED, MYF(0),
thd->main_security_ctx.host_or_ip);
return 1;
}
}
else /* Hostname given means that the connection was on a socket */
{
...
}
vio_keepalive(net->vio, TRUE);
...
char *user= end;
char *passwd= strend(user)+1;
uint user_len= passwd - user - 1;
char *db= passwd;
char db_buff[NAME_LEN + 1]; // buffer to store db in utf8
char user_buff[USERNAME_LENGTH + 1]; // buffer to store user in utf8
uint dummy_errors;
uint passwd_len= thd->client_capabilities & CLIENT_SECURE_CONNECTION ?
(uchar)(*passwd++) : strlen(passwd);
db= thd->client_capabilities & CLIENT_CONNECT_WITH_DB ?
db + passwd_len + 1 : 0;
uint db_len= db ? strlen(db) : 0;
if (passwd + passwd_len + db_len > (char *)net->read_pos + pkt_len)
{
inc_host_errors(&thd->remote.sin_addr);
my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.host_or_ip);
return 1;
}
...
/* If username starts and ends in "'", chop them off */
if (user_len > 1 && user[0] == '/'' && user[user_len - 1] == '/'')
{
user[user_len-1]= 0;
user++;
user_len-= 2;
}
if (thd->main_security_ctx.user)
x_free(thd->main_security_ctx.user);
if (!(thd->main_security_ctx.user= my_strdup(user, MYF(MY_WME))))
return 1; /* The error is set by my_strdup(). */
return check_user(thd, COM_CONNECT, passwd, passwd_len, db, TRUE);//验证用户名和密码
}
上面的源码主要做了如下几件事情:
获取客户端的IP和主机名
acl_check_host函数验证USER表中是否存在相应的IP或HOST,如果不存在直接报错
获取用户名和密码
check_user函数验证用户名和密码(不输入用户名默认为ODBC),如果系统表中不存在匹配的报错返回
获取用户的权限列表,验证用户的相关属性是否合法,如连接数是否超过上限,连接是否超时,操作是否超过限制等信息,如果不合法,则报错返回。
由于在一个认证的过程中涉及到的东西比较多,各个方面吧,我不能一一跟踪,只能大概了解其中的实现流程,捡重点进行
跟踪,有兴趣的童鞋自己具体跟踪吧
题外话:
Mysql中权限系统表都是在系统启动时,载入内存的(当然User表也是这样),一般情况下,不需要进行频繁的授权和回收
操作,这中情况下,权限表基本保持不变,将其在系统启动的时候载入内存的好处自然是快速的进行权限判断,减少磁盘的I/O,
你懂的^_^。有好处自然有坏处,就是在频繁进行授权和回收相关操作时,权限表需要重新载入内存,Mysql为了避免这种情况,
在手册中已经说的很清楚了,授权和回收只会反应到磁盘中,内存的数据字典信息是不会改变的,如果想立即生效,需要调用
FLUSH PRIVILEGES系统函数,这个系统函数的工作应该就是对权限系统表的RELOAD。
下篇进入实质性的介绍,通过跟踪一个建表语句,来学习Mysql是如何存储表的元数据的,即frm格式文件的剖析。
<script></script>
PS.最近工作比较清闲,却迷失了方向,一会想看OS的实现,一会想看逆向,一会又想看计算机组成原理,哎,转专业的学生伤
不起啊,计算机很神奇,我很迷茫…
摘自 心中无码
bitsCN.com
Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



When using Win11 system, sometimes you will encounter a prompt that requires you to enter the administrator username and password. This article will discuss how to deal with this situation. Method 1: 1. Click [Windows Logo], then press [Shift+Restart] to enter safe mode; or enter safe mode this way: click the Start menu and select Settings. Select "Update and Security"; select "Restart Now" in "Recovery"; after restarting and entering the options, select - Troubleshoot - Advanced Options - Startup Settings -&mdash

In the early days of social media, you could change your profile name multiple times, but now changing your name on any social media app comes with its own set of restrictions. If you've been wanting to change your display name or username on Instagram, the post below will explain how often you can change them, how to do it, and what you can do when you can't change your name on the platform . How to change display name and username on Instagram? Instagram offers two places for your name - your display name and your username, and luckily you can change both easily in the mobile app. The display name is what you would normally enter true

OOBE or out-of-box experience is a process designed for users to guide them through the various stages of post-installation steps. This includes rights and agreement pages, login pages, WiFi or network connection options, etc. If you receive any OOBEKeyboard, OOBELOCAL, or OOBEREGION issues, you will not be able to proceed to the final installation steps. Don't worry. There are some simple fixes you can use to resolve this issue. Workarounds - Before you do anything else, try these normal solutions - 1. When you get an error prompt, go ahead and click on the "Try Again" prompt. Keep trying at least 7 to 8 more times. 2. Check network connectivity. If you are using an Ethernet connection or Wi-Fi

1.1.1.1 Login method for the Internet authentication system: 1. Search for the campus network wireless signal and connect; 2. Open the browser and select "Self-Service" on the pop-up authentication interface; 3. Enter the user name and initial password to log in; 4. Complete Personal information and set a strong password.

Nowadays, many Windows users who love games have entered the Steam client and can search, download and play any good games. However, many users' profiles may have the exact same name, making it difficult to find a profile or even link a Steam profile to other third-party accounts or join Steam forums to share content. The profile is assigned a unique 17-digit id, which remains the same and cannot be changed by the user at any time, whereas the username or custom URL can. Regardless, some users don't know their Steamid, and it's important to know this. If you don't know how to find your account's Steamid, don't panic. In this article

JWT (JSONWebToken) is a lightweight authentication and authorization mechanism that uses JSON objects as security tokens to securely transmit user identity information between multiple systems. ThinkPHP6 is an efficient and flexible MVC framework based on PHP language. It provides many useful tools and functions, including JWT authentication mechanism. In this article, we will introduce how to use ThinkPHP6 for JWT authentication to ensure the security and reliability of web applications

How to fill in the user name of Railway 12306? You can fill in the user name in Railway 12306 APP, but most friends don’t know how to fill in the user name of Railway 12306. Next is the graphic tutorial on how to fill in the user name of Railway 12306 brought by the editor. , interested users come and take a look! Railway 12306 usage tutorial How to fill in the Railway 12306 username 1. First open the Railway 12306 APP and click [Register] at the bottom of the main page; 2. Then on the registration function page, enter the user name, password, confirmation password, etc.; 3. Finally enter Once completed, you can fill in the user registration.

The wifi username refers to the administrative username of the wireless router. This username, the IP address of the router, and the default administrative password are usually printed on the bottom of the wireless router and can also be found in the manual of the wireless router; the default administrative user of most routers The name is both admin, and the management password is also admin.
