xref: /PHP-8.1/ext/mysqlnd/mysqlnd_auth.c (revision 509906b2)
1 /*
2   +----------------------------------------------------------------------+
3   | Copyright (c) The PHP Group                                          |
4   +----------------------------------------------------------------------+
5   | This source file is subject to version 3.01 of the PHP license,      |
6   | that is bundled with this package in the file LICENSE, and is        |
7   | available through the world-wide-web at the following url:           |
8   | https://www.php.net/license/3_01.txt                                 |
9   | If you did not receive a copy of the PHP license and are unable to   |
10   | obtain it through the world-wide-web, please send a note to          |
11   | license@php.net so we can mail you a copy immediately.               |
12   +----------------------------------------------------------------------+
13   | Authors: Andrey Hristov <andrey@php.net>                             |
14   |          Ulf Wendel <uw@php.net>                                     |
15   +----------------------------------------------------------------------+
16 */
17 
18 #include "php.h"
19 #include "mysqlnd.h"
20 #include "mysqlnd_structs.h"
21 #include "mysqlnd_auth.h"
22 #include "mysqlnd_wireprotocol.h"
23 #include "mysqlnd_connection.h"
24 #include "mysqlnd_priv.h"
25 #include "mysqlnd_charset.h"
26 #include "mysqlnd_debug.h"
27 
28 static const char * const mysqlnd_old_passwd  = "mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication. "
29 "Please use an administration tool to reset your password with the command SET PASSWORD = PASSWORD('your_existing_password'). This will "
30 "store a new, and more secure, hash value in mysql.user. If this user is used in other scripts executed by PHP 5.2 or earlier you might need to remove the old-passwords "
31 "flag from your my.cnf file";
32 
33 
34 /* {{{ mysqlnd_run_authentication */
35 enum_func_status
mysqlnd_run_authentication(MYSQLND_CONN_DATA * const conn,const char * const user,const char * const passwd,const size_t passwd_len,const char * const db,const size_t db_len,const MYSQLND_STRING auth_plugin_data,const char * const auth_protocol,const unsigned int charset_no,const MYSQLND_SESSION_OPTIONS * const session_options,const zend_ulong mysql_flags,const bool silent,const bool is_change_user)36 mysqlnd_run_authentication(
37 			MYSQLND_CONN_DATA * const conn,
38 			const char * const user,
39 			const char * const passwd,
40 			const size_t passwd_len,
41 			const char * const db,
42 			const size_t db_len,
43 			const MYSQLND_STRING auth_plugin_data,
44 			const char * const auth_protocol,
45 			const unsigned int charset_no,
46 			const MYSQLND_SESSION_OPTIONS * const session_options,
47 			const zend_ulong mysql_flags,
48 			const bool silent,
49 			const bool is_change_user
50 			)
51 {
52 	enum_func_status ret = FAIL;
53 	bool first_call = TRUE;
54 
55 	char * switch_to_auth_protocol = NULL;
56 	size_t switch_to_auth_protocol_len = 0;
57 	char * requested_protocol = NULL;
58 	zend_uchar * plugin_data;
59 	size_t plugin_data_len;
60 
61 	DBG_ENTER("mysqlnd_run_authentication");
62 
63 	plugin_data_len = auth_plugin_data.l;
64 	plugin_data = mnd_emalloc(plugin_data_len + 1);
65 	if (!plugin_data) {
66 		goto end;
67 	}
68 	memcpy(plugin_data, auth_plugin_data.s, plugin_data_len);
69 	plugin_data[plugin_data_len] = '\0';
70 
71 	requested_protocol = mnd_pestrdup(auth_protocol? auth_protocol : MYSQLND_DEFAULT_AUTH_PROTOCOL, FALSE);
72 	if (!requested_protocol) {
73 		goto end;
74 	}
75 
76 	do {
77 		struct st_mysqlnd_authentication_plugin * auth_plugin = conn->m->fetch_auth_plugin_by_name(requested_protocol);
78 
79 		if (!auth_plugin) {
80 			if (first_call) {
81 				mnd_pefree(requested_protocol, FALSE);
82 				requested_protocol = mnd_pestrdup(MYSQLND_DEFAULT_AUTH_PROTOCOL, FALSE);
83 			} else {
84 				char * msg;
85 				mnd_sprintf(&msg, 0, "The server requested authentication method unknown to the client [%s]", requested_protocol);
86 				SET_CLIENT_ERROR(conn->error_info, CR_NOT_IMPLEMENTED, UNKNOWN_SQLSTATE, msg);
87 				mnd_sprintf_free(msg);
88 				goto end;
89 			}
90 		}
91 
92 
93 		{
94 			zend_uchar * switch_to_auth_protocol_data = NULL;
95 			size_t switch_to_auth_protocol_data_len = 0;
96 			zend_uchar * scrambled_data = NULL;
97 			size_t scrambled_data_len = 0;
98 
99 			switch_to_auth_protocol = NULL;
100 			switch_to_auth_protocol_len = 0;
101 
102 			mysqlnd_set_persistent_string(&conn->authentication_plugin_data, NULL, 0, conn->persistent);
103 			conn->authentication_plugin_data.l = plugin_data_len;
104 			conn->authentication_plugin_data.s = mnd_pemalloc(conn->authentication_plugin_data.l, conn->persistent);
105 			memcpy(conn->authentication_plugin_data.s, plugin_data, plugin_data_len);
106 
107 			DBG_INF_FMT("salt(%zu)=[%.*s]", plugin_data_len, (int) plugin_data_len, plugin_data);
108 			/* The data should be allocated with malloc() */
109 			if (auth_plugin) {
110 				scrambled_data = auth_plugin->methods.get_auth_data(
111 					NULL, &scrambled_data_len, conn, user, passwd,
112 					passwd_len, plugin_data, plugin_data_len,
113 					session_options, conn->protocol_frame_codec->data,
114 					mysql_flags);
115 			}
116 
117 			if (conn->error_info->error_no) {
118 				goto end;
119 			}
120 			if (FALSE == is_change_user) {
121 				ret = mysqlnd_auth_handshake(conn, user, passwd, passwd_len, db, db_len, session_options, mysql_flags,
122 											charset_no,
123 											first_call,
124 											requested_protocol,
125 											auth_plugin, plugin_data, plugin_data_len,
126 											scrambled_data, scrambled_data_len,
127 											&switch_to_auth_protocol, &switch_to_auth_protocol_len,
128 											&switch_to_auth_protocol_data, &switch_to_auth_protocol_data_len
129 											);
130 			} else {
131 				ret = mysqlnd_auth_change_user(conn, user, strlen(user), passwd, passwd_len, db, db_len, silent,
132 											   first_call,
133 											   requested_protocol,
134 											   auth_plugin, plugin_data, plugin_data_len,
135 											   scrambled_data, scrambled_data_len,
136 											   &switch_to_auth_protocol, &switch_to_auth_protocol_len,
137 											   &switch_to_auth_protocol_data, &switch_to_auth_protocol_data_len
138 											  );
139 			}
140 			first_call = FALSE;
141 			free(scrambled_data);
142 
143 			DBG_INF_FMT("switch_to_auth_protocol=%s", switch_to_auth_protocol? switch_to_auth_protocol:"n/a");
144 			if (requested_protocol && switch_to_auth_protocol) {
145 				mnd_efree(requested_protocol);
146 				requested_protocol = switch_to_auth_protocol;
147 			}
148 
149 			if (plugin_data) {
150 				mnd_efree(plugin_data);
151 			}
152 			plugin_data_len = switch_to_auth_protocol_data_len;
153 			plugin_data = switch_to_auth_protocol_data;
154 		}
155 		DBG_INF_FMT("conn->error_info->error_no = %d", conn->error_info->error_no);
156 	} while (ret == FAIL && conn->error_info->error_no == 0 && switch_to_auth_protocol != NULL);
157 
158 	if (ret == PASS) {
159 		DBG_INF_FMT("saving requested_protocol=%s", requested_protocol);
160 		conn->m->set_client_option(conn, MYSQLND_OPT_AUTH_PROTOCOL, requested_protocol);
161 	}
162 end:
163 	if (plugin_data) {
164 		mnd_efree(plugin_data);
165 	}
166 	if (requested_protocol) {
167 		mnd_efree(requested_protocol);
168 	}
169 
170 	DBG_RETURN(ret);
171 }
172 /* }}} */
173 
174 
175 /* {{{ mysqlnd_switch_to_ssl_if_needed */
176 static enum_func_status
mysqlnd_switch_to_ssl_if_needed(MYSQLND_CONN_DATA * const conn,unsigned int charset_no,const size_t server_capabilities,const MYSQLND_SESSION_OPTIONS * const session_options,const zend_ulong mysql_flags)177 mysqlnd_switch_to_ssl_if_needed(MYSQLND_CONN_DATA * const conn,
178 								unsigned int charset_no,
179 								const size_t server_capabilities,
180 								const MYSQLND_SESSION_OPTIONS * const session_options,
181 								const zend_ulong mysql_flags)
182 {
183 	enum_func_status ret = FAIL;
184 	const MYSQLND_CHARSET * charset;
185 	DBG_ENTER("mysqlnd_switch_to_ssl_if_needed");
186 
187 	if (session_options->charset_name && (charset = mysqlnd_find_charset_name(session_options->charset_name))) {
188 		charset_no = charset->nr;
189 	}
190 
191 	{
192 		const size_t client_capabilities = mysql_flags;
193 		ret = conn->command->enable_ssl(conn, client_capabilities, server_capabilities, charset_no);
194 	}
195 	DBG_RETURN(ret);
196 }
197 /* }}} */
198 
199 
200 /* {{{ mysqlnd_connect_run_authentication */
201 enum_func_status
mysqlnd_connect_run_authentication(MYSQLND_CONN_DATA * const conn,const char * const user,const char * const passwd,const char * const db,const size_t db_len,const size_t passwd_len,const MYSQLND_STRING authentication_plugin_data,const char * const authentication_protocol,const unsigned int charset_no,const size_t server_capabilities,const MYSQLND_SESSION_OPTIONS * const session_options,const zend_ulong mysql_flags)202 mysqlnd_connect_run_authentication(
203 			MYSQLND_CONN_DATA * const conn,
204 			const char * const user,
205 			const char * const passwd,
206 			const char * const db,
207 			const size_t db_len,
208 			const size_t passwd_len,
209 			const MYSQLND_STRING authentication_plugin_data,
210 			const char * const authentication_protocol,
211 			const unsigned int charset_no,
212 			const size_t server_capabilities,
213 			const MYSQLND_SESSION_OPTIONS * const session_options,
214 			const zend_ulong mysql_flags
215 			)
216 {
217 	enum_func_status ret = FAIL;
218 	DBG_ENTER("mysqlnd_connect_run_authentication");
219 
220 	ret = mysqlnd_switch_to_ssl_if_needed(conn, charset_no, server_capabilities, session_options, mysql_flags);
221 	if (PASS == ret) {
222 		ret = mysqlnd_run_authentication(conn, user, passwd, passwd_len, db, db_len,
223 										 authentication_plugin_data, authentication_protocol,
224 										 charset_no, session_options, mysql_flags, FALSE /*silent*/, FALSE/*is_change*/);
225 	}
226 	DBG_RETURN(ret);
227 }
228 /* }}} */
229 
230 
231 /* {{{ mysqlnd_auth_handshake */
232 enum_func_status
mysqlnd_auth_handshake(MYSQLND_CONN_DATA * conn,const char * const user,const char * const passwd,const size_t passwd_len,const char * const db,const size_t db_len,const MYSQLND_SESSION_OPTIONS * const session_options,const zend_ulong mysql_flags,const unsigned int server_charset_no,const bool use_full_blown_auth_packet,const char * const auth_protocol,struct st_mysqlnd_authentication_plugin * auth_plugin,const zend_uchar * const orig_auth_plugin_data,const size_t orig_auth_plugin_data_len,const zend_uchar * const auth_plugin_data,const size_t auth_plugin_data_len,char ** switch_to_auth_protocol,size_t * const switch_to_auth_protocol_len,zend_uchar ** switch_to_auth_protocol_data,size_t * const switch_to_auth_protocol_data_len)233 mysqlnd_auth_handshake(MYSQLND_CONN_DATA * conn,
234 							  const char * const user,
235 							  const char * const passwd,
236 							  const size_t passwd_len,
237 							  const char * const db,
238 							  const size_t db_len,
239 							  const MYSQLND_SESSION_OPTIONS * const session_options,
240 							  const zend_ulong mysql_flags,
241 							  const unsigned int server_charset_no,
242 							  const bool use_full_blown_auth_packet,
243 							  const char * const auth_protocol,
244 							  struct st_mysqlnd_authentication_plugin * auth_plugin,
245 							  const zend_uchar * const orig_auth_plugin_data,
246 							  const size_t orig_auth_plugin_data_len,
247 							  const zend_uchar * const auth_plugin_data,
248 							  const size_t auth_plugin_data_len,
249 							  char ** switch_to_auth_protocol,
250 							  size_t * const switch_to_auth_protocol_len,
251 							  zend_uchar ** switch_to_auth_protocol_data,
252 							  size_t * const switch_to_auth_protocol_data_len
253 							 )
254 {
255 	enum_func_status ret = FAIL;
256 	const MYSQLND_CHARSET * charset = NULL;
257 	MYSQLND_PACKET_AUTH_RESPONSE auth_resp_packet;
258 
259 	DBG_ENTER("mysqlnd_auth_handshake");
260 
261 	conn->payload_decoder_factory->m.init_auth_response_packet(&auth_resp_packet);
262 
263 	if (use_full_blown_auth_packet != TRUE) {
264 		MYSQLND_PACKET_CHANGE_AUTH_RESPONSE change_auth_resp_packet;
265 
266 		conn->payload_decoder_factory->m.init_change_auth_response_packet(&change_auth_resp_packet);
267 
268 		change_auth_resp_packet.auth_data = auth_plugin_data;
269 		change_auth_resp_packet.auth_data_len = auth_plugin_data_len;
270 
271 		if (!PACKET_WRITE(conn, &change_auth_resp_packet)) {
272 			SET_CONNECTION_STATE(&conn->state, CONN_QUIT_SENT);
273 			SET_CLIENT_ERROR(conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone);
274 			PACKET_FREE(&change_auth_resp_packet);
275 			goto end;
276 		}
277 		PACKET_FREE(&change_auth_resp_packet);
278 	} else {
279 		MYSQLND_PACKET_AUTH auth_packet;
280 
281 		conn->payload_decoder_factory->m.init_auth_packet(&auth_packet);
282 
283 		auth_packet.client_flags = mysql_flags;
284 		auth_packet.max_packet_size = session_options->max_allowed_packet;
285 		if (session_options->charset_name && (charset = mysqlnd_find_charset_name(session_options->charset_name))) {
286 			auth_packet.charset_no	= charset->nr;
287 		} else {
288 			auth_packet.charset_no	= server_charset_no;
289 		}
290 
291 		auth_packet.send_auth_data = TRUE;
292 		auth_packet.user		= user;
293 		auth_packet.db			= db;
294 		auth_packet.db_len		= db_len;
295 
296 		auth_packet.auth_data = auth_plugin_data;
297 		auth_packet.auth_data_len = auth_plugin_data_len;
298 		auth_packet.auth_plugin_name = auth_protocol;
299 
300 		if (conn->server_capabilities & CLIENT_CONNECT_ATTRS) {
301 			auth_packet.connect_attr = conn->options->connect_attr;
302 		}
303 
304 		if (!PACKET_WRITE(conn, &auth_packet)) {
305 			PACKET_FREE(&auth_packet);
306 			goto end;
307 		}
308 
309 		if (use_full_blown_auth_packet == TRUE) {
310 			conn->charset = mysqlnd_find_charset_nr(auth_packet.charset_no);
311 		}
312 
313 		PACKET_FREE(&auth_packet);
314 	}
315 
316 	if (auth_plugin && auth_plugin->methods.handle_server_response) {
317 		if (FAIL == auth_plugin->methods.handle_server_response(auth_plugin, conn,
318 				orig_auth_plugin_data, orig_auth_plugin_data_len, passwd, passwd_len,
319 				switch_to_auth_protocol, switch_to_auth_protocol_len,
320 				switch_to_auth_protocol_data, switch_to_auth_protocol_data_len)) {
321 			goto end;
322 		}
323 	}
324 
325 	if (FAIL == PACKET_READ(conn, &auth_resp_packet) || auth_resp_packet.response_code >= 0xFE) {
326 		if (auth_resp_packet.response_code == 0xFE) {
327 			/* old authentication with new server  !*/
328 			if (!auth_resp_packet.new_auth_protocol) {
329 				DBG_ERR(mysqlnd_old_passwd);
330 				SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE, mysqlnd_old_passwd);
331 			} else {
332 				*switch_to_auth_protocol = mnd_pestrndup(auth_resp_packet.new_auth_protocol, auth_resp_packet.new_auth_protocol_len, FALSE);
333 				*switch_to_auth_protocol_len = auth_resp_packet.new_auth_protocol_len;
334 				if (auth_resp_packet.new_auth_protocol_data) {
335 					*switch_to_auth_protocol_data_len = auth_resp_packet.new_auth_protocol_data_len;
336 					*switch_to_auth_protocol_data = mnd_emalloc(*switch_to_auth_protocol_data_len);
337 					memcpy(*switch_to_auth_protocol_data, auth_resp_packet.new_auth_protocol_data, *switch_to_auth_protocol_data_len);
338 				} else {
339 					*switch_to_auth_protocol_data = NULL;
340 					*switch_to_auth_protocol_data_len = 0;
341 				}
342 			}
343 		} else if (auth_resp_packet.response_code == 0xFF) {
344 			if (auth_resp_packet.sqlstate[0]) {
345 				strlcpy(conn->error_info->sqlstate, auth_resp_packet.sqlstate, sizeof(conn->error_info->sqlstate));
346 				DBG_ERR_FMT("ERROR:%u [SQLSTATE:%s] %s", auth_resp_packet.error_no, auth_resp_packet.sqlstate, auth_resp_packet.error);
347 			}
348 			SET_CLIENT_ERROR(conn->error_info, auth_resp_packet.error_no, UNKNOWN_SQLSTATE, auth_resp_packet.error);
349 		}
350 		goto end;
351 	}
352 
353 	mysqlnd_set_string(&conn->last_message, auth_resp_packet.message, auth_resp_packet.message_len);
354 	ret = PASS;
355 end:
356 	PACKET_FREE(&auth_resp_packet);
357 	DBG_RETURN(ret);
358 }
359 /* }}} */
360 
361 
362 /* {{{ mysqlnd_auth_change_user */
363 enum_func_status
mysqlnd_auth_change_user(MYSQLND_CONN_DATA * const conn,const char * const user,const size_t user_len,const char * const passwd,const size_t passwd_len,const char * const db,const size_t db_len,const bool silent,const bool use_full_blown_auth_packet,const char * const auth_protocol,struct st_mysqlnd_authentication_plugin * auth_plugin,const zend_uchar * const orig_auth_plugin_data,const size_t orig_auth_plugin_data_len,const zend_uchar * const auth_plugin_data,const size_t auth_plugin_data_len,char ** switch_to_auth_protocol,size_t * const switch_to_auth_protocol_len,zend_uchar ** switch_to_auth_protocol_data,size_t * const switch_to_auth_protocol_data_len)364 mysqlnd_auth_change_user(MYSQLND_CONN_DATA * const conn,
365 								const char * const user,
366 								const size_t user_len,
367 								const char * const passwd,
368 								const size_t passwd_len,
369 								const char * const db,
370 								const size_t db_len,
371 								const bool silent,
372 								const bool use_full_blown_auth_packet,
373 								const char * const auth_protocol,
374 								struct st_mysqlnd_authentication_plugin * auth_plugin,
375 								const zend_uchar * const orig_auth_plugin_data,
376 								const size_t orig_auth_plugin_data_len,
377 								const zend_uchar * const auth_plugin_data,
378 								const size_t auth_plugin_data_len,
379 								char ** switch_to_auth_protocol,
380 								size_t * const switch_to_auth_protocol_len,
381 								zend_uchar ** switch_to_auth_protocol_data,
382 								size_t * const switch_to_auth_protocol_data_len
383 								)
384 {
385 	enum_func_status ret = FAIL;
386 	const MYSQLND_CHARSET * old_cs = conn->charset;
387 	MYSQLND_PACKET_CHG_USER_RESPONSE chg_user_resp;
388 
389 	DBG_ENTER("mysqlnd_auth_change_user");
390 
391 	conn->payload_decoder_factory->m.init_change_user_response_packet(&chg_user_resp);
392 
393 	if (use_full_blown_auth_packet != TRUE) {
394 		MYSQLND_PACKET_CHANGE_AUTH_RESPONSE change_auth_resp_packet;
395 
396 		conn->payload_decoder_factory->m.init_change_auth_response_packet(&change_auth_resp_packet);
397 
398 		change_auth_resp_packet.auth_data = auth_plugin_data;
399 		change_auth_resp_packet.auth_data_len = auth_plugin_data_len;
400 
401 		if (!PACKET_WRITE(conn, &change_auth_resp_packet)) {
402 			SET_CONNECTION_STATE(&conn->state, CONN_QUIT_SENT);
403 			SET_CLIENT_ERROR(conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone);
404 			PACKET_FREE(&change_auth_resp_packet);
405 			goto end;
406 		}
407 
408 		PACKET_FREE(&change_auth_resp_packet);
409 	} else {
410 		MYSQLND_PACKET_AUTH auth_packet;
411 
412 		conn->payload_decoder_factory->m.init_auth_packet(&auth_packet);
413 
414 		auth_packet.is_change_user_packet = TRUE;
415 		auth_packet.user		= user;
416 		auth_packet.db			= db;
417 		auth_packet.db_len		= db_len;
418 		auth_packet.silent		= silent;
419 
420 		auth_packet.auth_data = auth_plugin_data;
421 		auth_packet.auth_data_len = auth_plugin_data_len;
422 		auth_packet.auth_plugin_name = auth_protocol;
423 
424 		if (conn->server_capabilities & CLIENT_CONNECT_ATTRS) {
425 			auth_packet.connect_attr = conn->options->connect_attr;
426 		}
427 
428 		if (conn->m->get_server_version(conn) >= 50123) {
429 			auth_packet.charset_no	= conn->charset->nr;
430 		}
431 
432 		if (!PACKET_WRITE(conn, &auth_packet)) {
433 			SET_CONNECTION_STATE(&conn->state, CONN_QUIT_SENT);
434 			SET_CLIENT_ERROR(conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone);
435 			PACKET_FREE(&auth_packet);
436 			goto end;
437 		}
438 
439 		PACKET_FREE(&auth_packet);
440 	}
441 
442 	if (auth_plugin && auth_plugin->methods.handle_server_response) {
443 		if (FAIL == auth_plugin->methods.handle_server_response(auth_plugin, conn,
444 				orig_auth_plugin_data, orig_auth_plugin_data_len, passwd, passwd_len,
445 				switch_to_auth_protocol, switch_to_auth_protocol_len,
446 				switch_to_auth_protocol_data, switch_to_auth_protocol_data_len)) {
447 			goto end;
448 		}
449 	}
450 
451 	ret = PACKET_READ(conn, &chg_user_resp);
452 	COPY_CLIENT_ERROR(conn->error_info, chg_user_resp.error_info);
453 
454 	if (0xFE == chg_user_resp.response_code) {
455 		ret = FAIL;
456 		if (!chg_user_resp.new_auth_protocol) {
457 			DBG_ERR(mysqlnd_old_passwd);
458 			SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE, mysqlnd_old_passwd);
459 		} else {
460 			*switch_to_auth_protocol = mnd_pestrndup(chg_user_resp.new_auth_protocol, chg_user_resp.new_auth_protocol_len, FALSE);
461 			*switch_to_auth_protocol_len = chg_user_resp.new_auth_protocol_len;
462 			if (chg_user_resp.new_auth_protocol_data) {
463 				*switch_to_auth_protocol_data_len = chg_user_resp.new_auth_protocol_data_len;
464 				*switch_to_auth_protocol_data = mnd_emalloc(*switch_to_auth_protocol_data_len);
465 				memcpy(*switch_to_auth_protocol_data, chg_user_resp.new_auth_protocol_data, *switch_to_auth_protocol_data_len);
466 			} else {
467 				*switch_to_auth_protocol_data = NULL;
468 				*switch_to_auth_protocol_data_len = 0;
469 			}
470 		}
471 	}
472 
473 	if (conn->error_info->error_no) {
474 		ret = FAIL;
475 		/*
476 		  COM_CHANGE_USER is broken in 5.1. At least in 5.1.15 and 5.1.14, 5.1.11 is immune.
477 		  bug#25371 mysql_change_user() triggers "packets out of sync"
478 		  When it gets fixed, there should be one more check here
479 		*/
480 		if (conn->m->get_server_version(conn) > 50113L &&conn->m->get_server_version(conn) < 50118L) {
481 			MYSQLND_PACKET_OK redundant_error_packet;
482 
483 			conn->payload_decoder_factory->m.init_ok_packet(&redundant_error_packet);
484 			PACKET_READ(conn, &redundant_error_packet);
485 			PACKET_FREE(&redundant_error_packet);
486 			DBG_INF_FMT("Server is " ZEND_ULONG_FMT ", buggy, sends two ERR messages", conn->m->get_server_version(conn));
487 		}
488 	}
489 	if (ret == PASS) {
490 		ZEND_ASSERT(conn->username.s != user && conn->password.s != passwd);
491 		mysqlnd_set_persistent_string(&conn->username, user, user_len, conn->persistent);
492 		mysqlnd_set_persistent_string(&conn->password, passwd, passwd_len, conn->persistent);
493 
494 		mysqlnd_set_string(&conn->last_message, NULL, 0);
495 		UPSERT_STATUS_RESET(conn->upsert_status);
496 		/* set charset for old servers */
497 		if (conn->m->get_server_version(conn) < 50123) {
498 			ret = conn->m->set_charset(conn, old_cs->name);
499 		}
500 	} else if (ret == FAIL && chg_user_resp.server_asked_323_auth == TRUE) {
501 		/* old authentication with new server  !*/
502 		DBG_ERR(mysqlnd_old_passwd);
503 		SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE, mysqlnd_old_passwd);
504 	}
505 end:
506 	PACKET_FREE(&chg_user_resp);
507 	DBG_RETURN(ret);
508 }
509 /* }}} */
510 
511 
512 /******************************************* MySQL Native Password ***********************************/
513 
514 #include "ext/standard/sha1.h"
515 
516 /* {{{ php_mysqlnd_crypt */
517 static void
php_mysqlnd_crypt(zend_uchar * buffer,const zend_uchar * s1,const zend_uchar * s2,size_t len)518 php_mysqlnd_crypt(zend_uchar *buffer, const zend_uchar *s1, const zend_uchar *s2, size_t len)
519 {
520 	const zend_uchar *s1_end = s1 + len;
521 	while (s1 < s1_end) {
522 		*buffer++= *s1++ ^ *s2++;
523 	}
524 }
525 /* }}} */
526 
527 
528 /* {{{ php_mysqlnd_scramble */
php_mysqlnd_scramble(zend_uchar * const buffer,const zend_uchar * const scramble,const zend_uchar * const password,const size_t password_len)529 void php_mysqlnd_scramble(zend_uchar * const buffer, const zend_uchar * const scramble, const zend_uchar * const password, const size_t password_len)
530 {
531 	PHP_SHA1_CTX context;
532 	zend_uchar sha1[SHA1_MAX_LENGTH];
533 	zend_uchar sha2[SHA1_MAX_LENGTH];
534 
535 	/* Phase 1: hash password */
536 	PHP_SHA1Init(&context);
537 	PHP_SHA1Update(&context, password, password_len);
538 	PHP_SHA1Final(sha1, &context);
539 
540 	/* Phase 2: hash sha1 */
541 	PHP_SHA1Init(&context);
542 	PHP_SHA1Update(&context, (zend_uchar*)sha1, SHA1_MAX_LENGTH);
543 	PHP_SHA1Final(sha2, &context);
544 
545 	/* Phase 3: hash scramble + sha2 */
546 	PHP_SHA1Init(&context);
547 	PHP_SHA1Update(&context, scramble, SCRAMBLE_LENGTH);
548 	PHP_SHA1Update(&context, (zend_uchar*)sha2, SHA1_MAX_LENGTH);
549 	PHP_SHA1Final(buffer, &context);
550 
551 	/* let's crypt buffer now */
552 	php_mysqlnd_crypt(buffer, (const zend_uchar *)buffer, (const zend_uchar *)sha1, SHA1_MAX_LENGTH);
553 }
554 /* }}} */
555 
556 
557 /* {{{ mysqlnd_native_auth_get_auth_data */
558 static zend_uchar *
mysqlnd_native_auth_get_auth_data(struct st_mysqlnd_authentication_plugin * self,size_t * auth_data_len,MYSQLND_CONN_DATA * conn,const char * const user,const char * const passwd,const size_t passwd_len,zend_uchar * auth_plugin_data,const size_t auth_plugin_data_len,const MYSQLND_SESSION_OPTIONS * const session_options,const MYSQLND_PFC_DATA * const pfc_data,const zend_ulong mysql_flags)559 mysqlnd_native_auth_get_auth_data(struct st_mysqlnd_authentication_plugin * self,
560 								  size_t * auth_data_len,
561 								  MYSQLND_CONN_DATA * conn, const char * const user, const char * const passwd,
562 								  const size_t passwd_len, zend_uchar * auth_plugin_data, const size_t auth_plugin_data_len,
563 								  const MYSQLND_SESSION_OPTIONS * const session_options,
564 								  const MYSQLND_PFC_DATA * const pfc_data,
565 								  const zend_ulong mysql_flags
566 								 )
567 {
568 	zend_uchar * ret = NULL;
569 	DBG_ENTER("mysqlnd_native_auth_get_auth_data");
570 	*auth_data_len = 0;
571 
572 	/* 5.5.x reports 21 as scramble length because it needs to show the length of the data before the plugin name */
573 	if (auth_plugin_data_len < SCRAMBLE_LENGTH) {
574 		/* mysql_native_password only works with SCRAMBLE_LENGTH scramble */
575 		SET_CLIENT_ERROR(conn->error_info, CR_MALFORMED_PACKET, UNKNOWN_SQLSTATE, "The server sent wrong length for scramble");
576 		DBG_ERR_FMT("The server sent wrong length for scramble %zu. Expected %u", auth_plugin_data_len, SCRAMBLE_LENGTH);
577 		DBG_RETURN(NULL);
578 	}
579 
580 	/* copy scrambled pass*/
581 	if (passwd && passwd_len) {
582 		ret = malloc(SCRAMBLE_LENGTH);
583 		*auth_data_len = SCRAMBLE_LENGTH;
584 		/* In 4.1 we use CLIENT_SECURE_CONNECTION and thus the len of the buf should be passed */
585 		php_mysqlnd_scramble((zend_uchar*)ret, auth_plugin_data, (zend_uchar*)passwd, passwd_len);
586 	}
587 	DBG_RETURN(ret);
588 }
589 /* }}} */
590 
591 
592 static struct st_mysqlnd_authentication_plugin mysqlnd_native_auth_plugin =
593 {
594 	{
595 		MYSQLND_PLUGIN_API_VERSION,
596 		"auth_plugin_mysql_native_password",
597 		MYSQLND_VERSION_ID,
598 		PHP_MYSQLND_VERSION,
599 		"PHP License 3.01",
600 		"Andrey Hristov <andrey@php.net>,  Ulf Wendel <uwendel@mysql.com>, Georg Richter <georg@mysql.com>",
601 		{
602 			NULL, /* no statistics , will be filled later if there are some */
603 			NULL, /* no statistics */
604 		},
605 		{
606 			NULL /* plugin shutdown */
607 		}
608 	},
609 	{/* methods */
610 		mysqlnd_native_auth_get_auth_data,
611 		NULL
612 	}
613 };
614 
615 
616 /******************************************* PAM Authentication ***********************************/
617 
618 /* {{{ mysqlnd_pam_auth_get_auth_data */
619 static zend_uchar *
mysqlnd_pam_auth_get_auth_data(struct st_mysqlnd_authentication_plugin * self,size_t * auth_data_len,MYSQLND_CONN_DATA * conn,const char * const user,const char * const passwd,const size_t passwd_len,zend_uchar * auth_plugin_data,const size_t auth_plugin_data_len,const MYSQLND_SESSION_OPTIONS * const session_options,const MYSQLND_PFC_DATA * const pfc_data,const zend_ulong mysql_flags)620 mysqlnd_pam_auth_get_auth_data(struct st_mysqlnd_authentication_plugin * self,
621 							   size_t * auth_data_len,
622 							   MYSQLND_CONN_DATA * conn, const char * const user, const char * const passwd,
623 							   const size_t passwd_len, zend_uchar * auth_plugin_data, const size_t auth_plugin_data_len,
624 							   const MYSQLND_SESSION_OPTIONS * const session_options,
625 							   const MYSQLND_PFC_DATA * const pfc_data,
626 							   const zend_ulong mysql_flags
627 							  )
628 {
629 	zend_uchar * ret = NULL;
630 
631 	/* copy pass*/
632 	if (passwd && passwd_len) {
633 		ret = (zend_uchar*) zend_strndup(passwd, passwd_len);
634 	}
635 	/*
636 	  Trailing null required. bug#78680
637 	  https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_connection_phase_authentication_methods_clear_text_password.html
638 	*/
639 	*auth_data_len = passwd_len + 1;
640 
641 	return ret;
642 }
643 /* }}} */
644 
645 
646 static struct st_mysqlnd_authentication_plugin mysqlnd_pam_authentication_plugin =
647 {
648 	{
649 		MYSQLND_PLUGIN_API_VERSION,
650 		"auth_plugin_mysql_clear_password",
651 		MYSQLND_VERSION_ID,
652 		PHP_MYSQLND_VERSION,
653 		"PHP License 3.01",
654 		"Andrey Hristov <andrey@php.net>,  Ulf Wendel <uw@php.net>, Georg Richter <georg@php.net>",
655 		{
656 			NULL, /* no statistics , will be filled later if there are some */
657 			NULL, /* no statistics */
658 		},
659 		{
660 			NULL /* plugin shutdown */
661 		}
662 	},
663 	{/* methods */
664 		mysqlnd_pam_auth_get_auth_data,
665 		NULL
666 	}
667 };
668 
669 
670 /******************************************* SHA256 Password ***********************************/
671 #ifdef MYSQLND_HAVE_SSL
672 static void
mysqlnd_xor_string(char * dst,const size_t dst_len,const char * xor_str,const size_t xor_str_len)673 mysqlnd_xor_string(char * dst, const size_t dst_len, const char * xor_str, const size_t xor_str_len)
674 {
675 	unsigned int i;
676 	for (i = 0; i <= dst_len; ++i) {
677 		dst[i] ^= xor_str[i % xor_str_len];
678 	}
679 }
680 
681 #ifndef PHP_WIN32
682 
683 #include <openssl/rsa.h>
684 #include <openssl/pem.h>
685 #include <openssl/err.h>
686 
687 typedef EVP_PKEY * mysqlnd_rsa_t;
688 
689 /* {{{ mysqlnd_sha256_get_rsa_from_pem */
690 static mysqlnd_rsa_t
mysqlnd_sha256_get_rsa_from_pem(const char * buf,size_t len)691 mysqlnd_sha256_get_rsa_from_pem(const char *buf, size_t len)
692 {
693 	BIO *bio = BIO_new_mem_buf(buf, len);
694 	EVP_PKEY *ret = PEM_read_bio_PUBKEY(bio, NULL, NULL, NULL);
695 	BIO_free(bio);
696 	return ret;
697 }
698 /* }}} */
699 
700 /* {{{ mysqlnd_sha256_public_encrypt */
701 static zend_uchar *
mysqlnd_sha256_public_encrypt(MYSQLND_CONN_DATA * conn,mysqlnd_rsa_t server_public_key,size_t passwd_len,size_t * auth_data_len,char * xor_str)702 mysqlnd_sha256_public_encrypt(MYSQLND_CONN_DATA * conn, mysqlnd_rsa_t server_public_key, size_t passwd_len, size_t * auth_data_len, char *xor_str)
703 {
704 	zend_uchar * ret = NULL;
705 	size_t server_public_key_len = (size_t) EVP_PKEY_size(server_public_key);
706 
707 	DBG_ENTER("mysqlnd_sha256_public_encrypt");
708 	/*
709 		Because RSA_PKCS1_OAEP_PADDING is used there is a restriction on the passwd_len.
710 		RSA_PKCS1_OAEP_PADDING is recommended for new applications. See more here:
711 		http://www.openssl.org/docs/crypto/RSA_public_encrypt.html
712 	*/
713 	if (server_public_key_len <= passwd_len + 41) {
714 		/* password message is to long */
715 		EVP_PKEY_free(server_public_key);
716 		SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE, "password is too long");
717 		DBG_ERR("password is too long");
718 		DBG_RETURN(NULL);
719 	}
720 
721 	*auth_data_len = server_public_key_len;
722 	ret = malloc(*auth_data_len);
723 	EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(server_public_key, NULL);
724 	if (!ctx || EVP_PKEY_encrypt_init(ctx) <= 0 ||
725 			EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0 ||
726 			EVP_PKEY_encrypt(ctx, ret, &server_public_key_len, (zend_uchar *) xor_str, passwd_len + 1) <= 0) {
727 		DBG_ERR("encrypt failed");
728 		free(ret);
729 		ret = NULL;
730 	}
731 	EVP_PKEY_CTX_free(ctx);
732 	EVP_PKEY_free(server_public_key);
733 	DBG_RETURN(ret);
734 }
735 /* }}} */
736 
737 #else
738 
739 #include <wincrypt.h>
740 #include <bcrypt.h>
741 
742 typedef HANDLE mysqlnd_rsa_t;
743 
744 /* {{{ mysqlnd_sha256_get_rsa_from_pem */
745 static mysqlnd_rsa_t
mysqlnd_sha256_get_rsa_from_pem(const char * buf,size_t len)746 mysqlnd_sha256_get_rsa_from_pem(const char *buf, size_t len)
747 {
748 	BCRYPT_KEY_HANDLE ret = 0;
749 	LPSTR der_buf = NULL;
750 	DWORD der_len;
751 	CERT_PUBLIC_KEY_INFO *key_info = NULL;
752 	DWORD key_info_len;
753 	ALLOCA_FLAG(use_heap);
754 
755 	if (!CryptStringToBinaryA(buf, len, CRYPT_STRING_BASE64HEADER, NULL, &der_len, NULL, NULL)) {
756 		goto finish;
757 	}
758 	der_buf = do_alloca(der_len, use_heap);
759 	if (!CryptStringToBinaryA(buf, len, CRYPT_STRING_BASE64HEADER, der_buf, &der_len, NULL, NULL)) {
760 		goto finish;
761 	}
762 	if (!CryptDecodeObjectEx(X509_ASN_ENCODING, X509_PUBLIC_KEY_INFO, der_buf, der_len, CRYPT_ENCODE_ALLOC_FLAG, NULL, &key_info, &key_info_len)) {
763 		goto finish;
764 	}
765 	if (!CryptImportPublicKeyInfoEx2(X509_ASN_ENCODING, key_info, CRYPT_OID_INFO_PUBKEY_ENCRYPT_KEY_FLAG, NULL, &ret)) {
766 		goto finish;
767 	}
768 
769 finish:
770 	if (key_info) {
771 		LocalFree(key_info);
772 	}
773 	if (der_buf) {
774 		free_alloca(der_buf, use_heap);
775 	}
776 	return (mysqlnd_rsa_t) ret;
777 }
778 /* }}} */
779 
780 /* {{{ mysqlnd_sha256_public_encrypt */
781 static zend_uchar *
mysqlnd_sha256_public_encrypt(MYSQLND_CONN_DATA * conn,mysqlnd_rsa_t server_public_key,size_t passwd_len,size_t * auth_data_len,char * xor_str)782 mysqlnd_sha256_public_encrypt(MYSQLND_CONN_DATA * conn, mysqlnd_rsa_t server_public_key, size_t passwd_len, size_t * auth_data_len, char *xor_str)
783 {
784 	zend_uchar * ret = NULL;
785 	DWORD server_public_key_len = passwd_len;
786 	BCRYPT_OAEP_PADDING_INFO padding_info;
787 
788 	DBG_ENTER("mysqlnd_sha256_public_encrypt");
789 
790 	ZeroMemory(&padding_info, sizeof padding_info);
791 	padding_info.pszAlgId = BCRYPT_SHA1_ALGORITHM;
792 	if (BCryptEncrypt((BCRYPT_KEY_HANDLE) server_public_key, xor_str, passwd_len + 1, &padding_info,
793 			NULL, 0, NULL, 0, &server_public_key_len, BCRYPT_PAD_OAEP)) {
794 		DBG_RETURN(0);
795 	}
796 
797 	/*
798 		Because RSA_PKCS1_OAEP_PADDING is used there is a restriction on the passwd_len.
799 		RSA_PKCS1_OAEP_PADDING is recommended for new applications. See more here:
800 		http://www.openssl.org/docs/crypto/RSA_public_encrypt.html
801 	*/
802 	if ((size_t) server_public_key_len <= passwd_len + 41) {
803 		/* password message is to long */
804 		BCryptDestroyKey((BCRYPT_KEY_HANDLE) server_public_key);
805 		SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE, "password is too long");
806 		DBG_ERR("password is too long");
807 		DBG_RETURN(0);
808 	}
809 
810 	*auth_data_len = server_public_key_len;
811 	ret = malloc(*auth_data_len);
812 	if (BCryptEncrypt((BCRYPT_KEY_HANDLE) server_public_key, xor_str, passwd_len + 1, &padding_info,
813 			NULL, 0, ret, server_public_key_len, &server_public_key_len, BCRYPT_PAD_OAEP)) {
814 		BCryptDestroyKey((BCRYPT_KEY_HANDLE) server_public_key);
815 		DBG_RETURN(0);
816 	}
817 	BCryptDestroyKey((BCRYPT_KEY_HANDLE) server_public_key);
818 	DBG_RETURN(ret);
819 }
820 /* }}} */
821 
822 #endif
823 
824 /* {{{ mysqlnd_sha256_get_rsa_key */
825 static mysqlnd_rsa_t
mysqlnd_sha256_get_rsa_key(MYSQLND_CONN_DATA * conn,const MYSQLND_SESSION_OPTIONS * const session_options,const MYSQLND_PFC_DATA * const pfc_data)826 mysqlnd_sha256_get_rsa_key(MYSQLND_CONN_DATA * conn,
827 						   const MYSQLND_SESSION_OPTIONS * const session_options,
828 						   const MYSQLND_PFC_DATA * const pfc_data
829 						  )
830 {
831 	mysqlnd_rsa_t ret = NULL;
832 	const char * fname = (pfc_data->sha256_server_public_key && pfc_data->sha256_server_public_key[0] != '\0')?
833 								pfc_data->sha256_server_public_key:
834 								MYSQLND_G(sha256_server_public_key);
835 	php_stream * stream;
836 	DBG_ENTER("mysqlnd_sha256_get_rsa_key");
837 	DBG_INF_FMT("options_s256_pk=[%s] MYSQLND_G(sha256_server_public_key)=[%s]",
838 				 pfc_data->sha256_server_public_key? pfc_data->sha256_server_public_key:"n/a",
839 				 MYSQLND_G(sha256_server_public_key)? MYSQLND_G(sha256_server_public_key):"n/a");
840 	if (!fname || fname[0] == '\0') {
841 		MYSQLND_PACKET_SHA256_PK_REQUEST pk_req_packet;
842 		MYSQLND_PACKET_SHA256_PK_REQUEST_RESPONSE pk_resp_packet;
843 
844 		do {
845 			DBG_INF("requesting the public key from the server");
846 			conn->payload_decoder_factory->m.init_sha256_pk_request_packet(&pk_req_packet);
847 			conn->payload_decoder_factory->m.init_sha256_pk_request_response_packet(&pk_resp_packet);
848 
849 			if (! PACKET_WRITE(conn, &pk_req_packet)) {
850 				DBG_ERR_FMT("Error while sending public key request packet");
851 				php_error(E_WARNING, "Error while sending public key request packet. PID=%d", getpid());
852 				SET_CONNECTION_STATE(&conn->state, CONN_QUIT_SENT);
853 				break;
854 			}
855 			if (FAIL == PACKET_READ(conn, &pk_resp_packet) || NULL == pk_resp_packet.public_key) {
856 				DBG_ERR_FMT("Error while receiving public key");
857 				php_error(E_WARNING, "Error while receiving public key. PID=%d", getpid());
858 				SET_CONNECTION_STATE(&conn->state, CONN_QUIT_SENT);
859 				break;
860 			}
861 			DBG_INF_FMT("Public key(%zu):\n%s", pk_resp_packet.public_key_len, pk_resp_packet.public_key);
862 			/* now extract the public key */
863 			ret = mysqlnd_sha256_get_rsa_from_pem((const char *) pk_resp_packet.public_key, pk_resp_packet.public_key_len);
864 		} while (0);
865 		PACKET_FREE(&pk_req_packet);
866 		PACKET_FREE(&pk_resp_packet);
867 
868 		DBG_INF_FMT("ret=%p", ret);
869 		DBG_RETURN(ret);
870 
871 		SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE,
872 			"sha256_server_public_key is not set for the connection or as mysqlnd.sha256_server_public_key");
873 		DBG_ERR("server_public_key is not set");
874 		DBG_RETURN(NULL);
875 	} else {
876 		zend_string * key_str;
877 		DBG_INF_FMT("Key in a file. [%s]", fname);
878 		stream = php_stream_open_wrapper((char *) fname, "rb", REPORT_ERRORS, NULL);
879 
880 		if (stream) {
881 			if ((key_str = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0)) != NULL) {
882 				ret = mysqlnd_sha256_get_rsa_from_pem(ZSTR_VAL(key_str), ZSTR_LEN(key_str));
883 				DBG_INF("Successfully loaded");
884 				DBG_INF_FMT("Public key:%*.s", (int) ZSTR_LEN(key_str), ZSTR_VAL(key_str));
885 				zend_string_release_ex(key_str, 0);
886 			}
887 			php_stream_close(stream);
888 		}
889 	}
890 	DBG_RETURN(ret);
891 }
892 /* }}} */
893 
894 
895 /* {{{ mysqlnd_sha256_auth_get_auth_data */
896 static zend_uchar *
mysqlnd_sha256_auth_get_auth_data(struct st_mysqlnd_authentication_plugin * self,size_t * auth_data_len,MYSQLND_CONN_DATA * conn,const char * const user,const char * const passwd,const size_t passwd_len,zend_uchar * auth_plugin_data,const size_t auth_plugin_data_len,const MYSQLND_SESSION_OPTIONS * const session_options,const MYSQLND_PFC_DATA * const pfc_data,const zend_ulong mysql_flags)897 mysqlnd_sha256_auth_get_auth_data(struct st_mysqlnd_authentication_plugin * self,
898 								  size_t * auth_data_len,
899 								  MYSQLND_CONN_DATA * conn, const char * const user, const char * const passwd,
900 								  const size_t passwd_len, zend_uchar * auth_plugin_data, const size_t auth_plugin_data_len,
901 								  const MYSQLND_SESSION_OPTIONS * const session_options,
902 								  const MYSQLND_PFC_DATA * const pfc_data,
903 								  const zend_ulong mysql_flags
904 								 )
905 {
906 	mysqlnd_rsa_t server_public_key;
907 	zend_uchar * ret = NULL;
908 	DBG_ENTER("mysqlnd_sha256_auth_get_auth_data");
909 	DBG_INF_FMT("salt(%zu)=[%.*s]", auth_plugin_data_len, (int) auth_plugin_data_len, auth_plugin_data);
910 
911 
912 	if (conn->vio->data->ssl) {
913 		DBG_INF("simple clear text under SSL");
914 		/* clear text under SSL */
915 		/* NUL termination byte required: https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_connection_phase_authentication_methods_clear_text_password.html
916 		 * (this is similar to bug #78680, but now as GH-11440) */
917 		*auth_data_len = passwd_len + 1;
918 		ret = malloc(passwd_len + 1);
919 		memcpy(ret, passwd, passwd_len);
920 		ret[passwd_len] = '\0';
921 	} else {
922 		*auth_data_len = 0;
923 		server_public_key = mysqlnd_sha256_get_rsa_key(conn, session_options, pfc_data);
924 
925 		if (server_public_key) {
926 			ALLOCA_FLAG(use_heap);
927 			char *xor_str = do_alloca(passwd_len + 1, use_heap);
928 			memcpy(xor_str, passwd, passwd_len);
929 			xor_str[passwd_len] = '\0';
930 			/* https://dev.mysql.com/doc/dev/mysql-server/latest/page_caching_sha2_authentication_exchanges.html
931 			 * This tells us that the nonce is 20 (==SCRAMBLE_LENGTH) bytes long.
932 			 * In a 5.5+ server we might get additional scramble data in php_mysqlnd_greet_read, not used by this authentication method. */
933 			mysqlnd_xor_string(xor_str, passwd_len, (char *) auth_plugin_data, SCRAMBLE_LENGTH);
934 			ret = mysqlnd_sha256_public_encrypt(conn, server_public_key, passwd_len, auth_data_len, xor_str);
935 			free_alloca(xor_str, use_heap);
936 		}
937 	}
938 
939 	DBG_RETURN(ret);
940 }
941 /* }}} */
942 
943 
944 static struct st_mysqlnd_authentication_plugin mysqlnd_sha256_authentication_plugin =
945 {
946 	{
947 		MYSQLND_PLUGIN_API_VERSION,
948 		"auth_plugin_sha256_password",
949 		MYSQLND_VERSION_ID,
950 		PHP_MYSQLND_VERSION,
951 		"PHP License 3.01",
952 		"Andrey Hristov <andrey@php.net>,  Ulf Wendel <uwendel@mysql.com>",
953 		{
954 			NULL, /* no statistics , will be filled later if there are some */
955 			NULL, /* no statistics */
956 		},
957 		{
958 			NULL /* plugin shutdown */
959 		}
960 	},
961 	{/* methods */
962 		mysqlnd_sha256_auth_get_auth_data,
963 		NULL
964 	}
965 };
966 #endif
967 
968 /*************************************** CACHING SHA2 Password *******************************/
969 #ifdef MYSQLND_HAVE_SSL
970 
971 #undef L64
972 
973 #include "ext/hash/php_hash.h"
974 #include "ext/hash/php_hash_sha.h"
975 
976 #define SHA256_LENGTH 32
977 
978 /* {{{ php_mysqlnd_scramble_sha2 */
php_mysqlnd_scramble_sha2(zend_uchar * const buffer,const zend_uchar * const scramble,const zend_uchar * const password,const size_t password_len)979 void php_mysqlnd_scramble_sha2(zend_uchar * const buffer, const zend_uchar * const scramble, const zend_uchar * const password, const size_t password_len)
980 {
981 	PHP_SHA256_CTX context;
982 	zend_uchar sha1[SHA256_LENGTH];
983 	zend_uchar sha2[SHA256_LENGTH];
984 
985 	/* Phase 1: hash password */
986 	PHP_SHA256Init(&context);
987 	PHP_SHA256Update(&context, password, password_len);
988 	PHP_SHA256Final(sha1, &context);
989 
990 	/* Phase 2: hash sha1 */
991 	PHP_SHA256Init(&context);
992 	PHP_SHA256Update(&context, (zend_uchar*)sha1, SHA256_LENGTH);
993 	PHP_SHA256Final(sha2, &context);
994 
995 	/* Phase 3: hash scramble + sha2 */
996 	PHP_SHA256Init(&context);
997 	PHP_SHA256Update(&context, (zend_uchar*)sha2, SHA256_LENGTH);
998 	PHP_SHA256Update(&context, scramble, SCRAMBLE_LENGTH);
999 	PHP_SHA256Final(buffer, &context);
1000 
1001 	/* let's crypt buffer now */
1002 	php_mysqlnd_crypt(buffer, (const zend_uchar *)sha1, (const zend_uchar *)buffer, SHA256_LENGTH);
1003 }
1004 /* }}} */
1005 
1006 #ifndef PHP_WIN32
1007 
1008 /* {{{ mysqlnd_caching_sha2_public_encrypt */
1009 static size_t
mysqlnd_caching_sha2_public_encrypt(MYSQLND_CONN_DATA * conn,mysqlnd_rsa_t server_public_key,size_t passwd_len,unsigned char ** crypted,char * xor_str)1010 mysqlnd_caching_sha2_public_encrypt(MYSQLND_CONN_DATA * conn, mysqlnd_rsa_t server_public_key, size_t passwd_len, unsigned char **crypted, char *xor_str)
1011 {
1012 	size_t server_public_key_len = (size_t) EVP_PKEY_size(server_public_key);
1013 
1014 	DBG_ENTER("mysqlnd_caching_sha2_public_encrypt");
1015 	/*
1016 		Because RSA_PKCS1_OAEP_PADDING is used there is a restriction on the passwd_len.
1017 		RSA_PKCS1_OAEP_PADDING is recommended for new applications. See more here:
1018 		http://www.openssl.org/docs/crypto/RSA_public_encrypt.html
1019 	*/
1020 	if (server_public_key_len <= passwd_len + 41) {
1021 		/* password message is to long */
1022 		EVP_PKEY_free(server_public_key);
1023 		SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE, "password is too long");
1024 		DBG_ERR("password is too long");
1025 		DBG_RETURN(0);
1026 	}
1027 
1028 	*crypted = emalloc(server_public_key_len);
1029 	EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(server_public_key, NULL);
1030 	if (!ctx || EVP_PKEY_encrypt_init(ctx) <= 0 ||
1031 			EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0 ||
1032 			EVP_PKEY_encrypt(ctx, *crypted, &server_public_key_len, (zend_uchar *) xor_str, passwd_len + 1) <= 0) {
1033 		DBG_ERR("encrypt failed");
1034 		server_public_key_len = 0;
1035 	}
1036 	EVP_PKEY_CTX_free(ctx);
1037 	EVP_PKEY_free(server_public_key);
1038 	DBG_RETURN(server_public_key_len);
1039 }
1040 /* }}} */
1041 
1042 #else
1043 
1044 /* {{{ mysqlnd_caching_sha2_public_encrypt */
1045 static size_t
mysqlnd_caching_sha2_public_encrypt(MYSQLND_CONN_DATA * conn,mysqlnd_rsa_t server_public_key,size_t passwd_len,unsigned char ** crypted,char * xor_str)1046 mysqlnd_caching_sha2_public_encrypt(MYSQLND_CONN_DATA * conn, mysqlnd_rsa_t server_public_key, size_t passwd_len, unsigned char **crypted, char *xor_str)
1047 {
1048 	DWORD server_public_key_len = passwd_len;
1049 	BCRYPT_OAEP_PADDING_INFO padding_info;
1050 
1051 	DBG_ENTER("mysqlnd_caching_sha2_public_encrypt");
1052 
1053 	ZeroMemory(&padding_info, sizeof padding_info);
1054 	padding_info.pszAlgId = BCRYPT_SHA1_ALGORITHM;
1055 	if (BCryptEncrypt((BCRYPT_KEY_HANDLE) server_public_key, xor_str, passwd_len + 1, &padding_info,
1056 			NULL, 0, NULL, 0, &server_public_key_len, BCRYPT_PAD_OAEP)) {
1057 		DBG_RETURN(0);
1058 	}
1059 
1060 	/*
1061 		Because RSA_PKCS1_OAEP_PADDING is used there is a restriction on the passwd_len.
1062 		RSA_PKCS1_OAEP_PADDING is recommended for new applications. See more here:
1063 		http://www.openssl.org/docs/crypto/RSA_public_encrypt.html
1064 	*/
1065 	if ((size_t) server_public_key_len <= passwd_len + 41) {
1066 		/* password message is to long */
1067 		BCryptDestroyKey((BCRYPT_KEY_HANDLE) server_public_key);
1068 		SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE, "password is too long");
1069 		DBG_ERR("password is too long");
1070 		DBG_RETURN(0);
1071 	}
1072 
1073 	*crypted = emalloc(server_public_key_len);
1074 	if (BCryptEncrypt((BCRYPT_KEY_HANDLE) server_public_key, xor_str, passwd_len + 1, &padding_info,
1075 			NULL, 0, *crypted, server_public_key_len, &server_public_key_len, BCRYPT_PAD_OAEP)) {
1076 		BCryptDestroyKey((BCRYPT_KEY_HANDLE) server_public_key);
1077 		DBG_RETURN(0);
1078 	}
1079 	BCryptDestroyKey((BCRYPT_KEY_HANDLE) server_public_key);
1080 	DBG_RETURN(server_public_key_len);
1081 }
1082 /* }}} */
1083 
1084 #endif
1085 
1086 /* {{{ mysqlnd_native_auth_get_auth_data */
1087 static zend_uchar *
mysqlnd_caching_sha2_get_auth_data(struct st_mysqlnd_authentication_plugin * self,size_t * auth_data_len,MYSQLND_CONN_DATA * conn,const char * const user,const char * const passwd,const size_t passwd_len,zend_uchar * auth_plugin_data,const size_t auth_plugin_data_len,const MYSQLND_SESSION_OPTIONS * const session_options,const MYSQLND_PFC_DATA * const pfc_data,const zend_ulong mysql_flags)1088 mysqlnd_caching_sha2_get_auth_data(struct st_mysqlnd_authentication_plugin * self,
1089 								   size_t * auth_data_len,
1090 							 	   MYSQLND_CONN_DATA * conn, const char * const user, const char * const passwd,
1091 								   const size_t passwd_len, zend_uchar * auth_plugin_data, const size_t auth_plugin_data_len,
1092 								   const MYSQLND_SESSION_OPTIONS * const session_options,
1093 								   const MYSQLND_PFC_DATA * const pfc_data,
1094 								   const zend_ulong mysql_flags
1095 								  )
1096 {
1097 	zend_uchar * ret = NULL;
1098 	DBG_ENTER("mysqlnd_caching_sha2_get_auth_data");
1099 	DBG_INF_FMT("salt(%zu)=[%.*s]", auth_plugin_data_len, (int) auth_plugin_data_len, auth_plugin_data);
1100 	*auth_data_len = 0;
1101 
1102 	if (auth_plugin_data_len < SCRAMBLE_LENGTH) {
1103 		SET_CLIENT_ERROR(conn->error_info, CR_MALFORMED_PACKET, UNKNOWN_SQLSTATE, "The server sent wrong length for scramble");
1104 		DBG_ERR_FMT("The server sent wrong length for scramble %zu. Expected %u", auth_plugin_data_len, SCRAMBLE_LENGTH);
1105 		DBG_RETURN(NULL);
1106 	}
1107 
1108 	DBG_INF("First auth step: send hashed password");
1109 	/* copy scrambled pass*/
1110 	if (passwd && passwd_len) {
1111 		ret = malloc(SHA256_LENGTH + 1);
1112 		*auth_data_len = SHA256_LENGTH;
1113 		php_mysqlnd_scramble_sha2((zend_uchar*)ret, auth_plugin_data, (zend_uchar*)passwd, passwd_len);
1114 		ret[SHA256_LENGTH] = '\0';
1115 		DBG_INF_FMT("hash(%zu)=[%.*s]", *auth_data_len, (int) *auth_data_len, ret);
1116 	}
1117 
1118 	DBG_RETURN(ret);
1119 }
1120 /* }}} */
1121 
1122 static mysqlnd_rsa_t
mysqlnd_caching_sha2_get_key(MYSQLND_CONN_DATA * conn)1123 mysqlnd_caching_sha2_get_key(MYSQLND_CONN_DATA *conn)
1124 {
1125 	mysqlnd_rsa_t ret = NULL;
1126 	const MYSQLND_PFC_DATA * const pfc_data = conn->protocol_frame_codec->data;
1127 	const char * fname = (pfc_data->sha256_server_public_key && pfc_data->sha256_server_public_key[0] != '\0')?
1128 								pfc_data->sha256_server_public_key:
1129 								MYSQLND_G(sha256_server_public_key);
1130 	php_stream * stream;
1131 	DBG_ENTER("mysqlnd_cached_sha2_get_key");
1132 	DBG_INF_FMT("options_s256_pk=[%s] MYSQLND_G(sha256_server_public_key)=[%s]",
1133 				 pfc_data->sha256_server_public_key? pfc_data->sha256_server_public_key:"n/a",
1134 				 MYSQLND_G(sha256_server_public_key)? MYSQLND_G(sha256_server_public_key):"n/a");
1135 	if (!fname || fname[0] == '\0') {
1136 		MYSQLND_PACKET_CACHED_SHA2_RESULT req_packet;
1137 		MYSQLND_PACKET_SHA256_PK_REQUEST_RESPONSE pk_resp_packet;
1138 
1139 		do {
1140 			DBG_INF("requesting the public key from the server");
1141 			conn->payload_decoder_factory->m.init_cached_sha2_result_packet(&req_packet);
1142 			conn->payload_decoder_factory->m.init_sha256_pk_request_response_packet(&pk_resp_packet);
1143 			req_packet.request = 1;
1144 
1145 			if (! PACKET_WRITE(conn, &req_packet)) {
1146 				DBG_ERR_FMT("Error while sending public key request packet");
1147 				php_error(E_WARNING, "Error while sending public key request packet. PID=%d", getpid());
1148 				SET_CONNECTION_STATE(&conn->state, CONN_QUIT_SENT);
1149 				break;
1150 			}
1151 			if (FAIL == PACKET_READ(conn, &pk_resp_packet) || NULL == pk_resp_packet.public_key) {
1152 				DBG_ERR_FMT("Error while receiving public key");
1153 				php_error(E_WARNING, "Error while receiving public key. PID=%d", getpid());
1154 				SET_CONNECTION_STATE(&conn->state, CONN_QUIT_SENT);
1155 				break;
1156 			}
1157 			DBG_INF_FMT("Public key(%zu):\n%s", pk_resp_packet.public_key_len, pk_resp_packet.public_key);
1158 			/* now extract the public key */
1159 			ret = mysqlnd_sha256_get_rsa_from_pem((const char *) pk_resp_packet.public_key, pk_resp_packet.public_key_len);
1160 		} while (0);
1161 		PACKET_FREE(&req_packet);
1162 		PACKET_FREE(&pk_resp_packet);
1163 
1164 		DBG_INF_FMT("ret=%p", ret);
1165 		DBG_RETURN(ret);
1166 
1167 		SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE,
1168 			"caching_sha2_server_public_key is not set for the connection or as mysqlnd.sha256_server_public_key");
1169 		DBG_ERR("server_public_key is not set");
1170 		DBG_RETURN(NULL);
1171 	} else {
1172 		zend_string * key_str;
1173 		DBG_INF_FMT("Key in a file. [%s]", fname);
1174 		stream = php_stream_open_wrapper((char *) fname, "rb", REPORT_ERRORS, NULL);
1175 
1176 		if (stream) {
1177 			if ((key_str = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0)) != NULL) {
1178 				ret = mysqlnd_sha256_get_rsa_from_pem(ZSTR_VAL(key_str), ZSTR_LEN(key_str));
1179 				DBG_INF("Successfully loaded");
1180 				DBG_INF_FMT("Public key: %*.s", (int) ZSTR_LEN(key_str), ZSTR_VAL(key_str));
1181 				zend_string_release(key_str);
1182 			}
1183 			php_stream_close(stream);
1184 		}
1185 	}
1186 	DBG_RETURN(ret);
1187 
1188 }
1189 
1190 
1191 /* {{{ mysqlnd_caching_sha2_get_and_use_key */
1192 static size_t
mysqlnd_caching_sha2_get_and_use_key(MYSQLND_CONN_DATA * conn,const zend_uchar * auth_plugin_data,const size_t auth_plugin_data_len,unsigned char ** crypted,const char * const passwd,const size_t passwd_len)1193 mysqlnd_caching_sha2_get_and_use_key(MYSQLND_CONN_DATA *conn,
1194 		const zend_uchar * auth_plugin_data, const size_t auth_plugin_data_len,
1195 		unsigned char **crypted,
1196 		const char * const passwd,
1197 		const size_t passwd_len)
1198 {
1199 	mysqlnd_rsa_t server_public_key = mysqlnd_caching_sha2_get_key(conn);
1200 
1201 	DBG_ENTER("mysqlnd_caching_sha2_get_and_use_key(");
1202 
1203 	if (server_public_key) {
1204 		int server_public_key_len;
1205 		ALLOCA_FLAG(use_heap)
1206 		char *xor_str = do_alloca(passwd_len + 1, use_heap);
1207 		memcpy(xor_str, passwd, passwd_len);
1208 		xor_str[passwd_len] = '\0';
1209 		mysqlnd_xor_string(xor_str, passwd_len, (char *) auth_plugin_data, SCRAMBLE_LENGTH);
1210 		server_public_key_len = mysqlnd_caching_sha2_public_encrypt(conn, server_public_key, passwd_len, crypted, xor_str);
1211 		free_alloca(xor_str, use_heap);
1212 		DBG_RETURN(server_public_key_len);
1213 	}
1214 	DBG_RETURN(0);
1215 }
1216 /* }}} */
1217 
is_secure_transport(MYSQLND_CONN_DATA * conn)1218 static int is_secure_transport(MYSQLND_CONN_DATA *conn) {
1219 	if (conn->vio->data->ssl) {
1220 		return 1;
1221 	}
1222 
1223 	return strcmp(conn->vio->data->stream->ops->label, "unix_socket") == 0;
1224 }
1225 
1226 /* {{{ mysqlnd_caching_sha2_handle_server_response */
1227 static enum_func_status
mysqlnd_caching_sha2_handle_server_response(struct st_mysqlnd_authentication_plugin * self,MYSQLND_CONN_DATA * conn,const zend_uchar * auth_plugin_data,const size_t auth_plugin_data_len,const char * const passwd,const size_t passwd_len,char ** new_auth_protocol,size_t * new_auth_protocol_len,zend_uchar ** new_auth_protocol_data,size_t * new_auth_protocol_data_len)1228 mysqlnd_caching_sha2_handle_server_response(struct st_mysqlnd_authentication_plugin *self,
1229 		MYSQLND_CONN_DATA * conn,
1230 		const zend_uchar * auth_plugin_data, const size_t auth_plugin_data_len,
1231 		const char * const passwd,
1232 		const size_t passwd_len,
1233 		char **new_auth_protocol, size_t *new_auth_protocol_len,
1234 		zend_uchar **new_auth_protocol_data, size_t *new_auth_protocol_data_len
1235 		)
1236 {
1237 	DBG_ENTER("mysqlnd_caching_sha2_handle_server_response");
1238 	MYSQLND_PACKET_CACHED_SHA2_RESULT result_packet;
1239 
1240 	if (passwd_len == 0) {
1241 		DBG_INF("empty password fast path");
1242 		DBG_RETURN(PASS);
1243 	}
1244 
1245 	conn->payload_decoder_factory->m.init_cached_sha2_result_packet(&result_packet);
1246 	if (FAIL == PACKET_READ(conn, &result_packet)) {
1247 		DBG_RETURN(PASS);
1248 	}
1249 
1250 	switch (result_packet.response_code) {
1251 		case 0xFF:
1252 			if (result_packet.sqlstate[0]) {
1253 				strlcpy(conn->error_info->sqlstate, result_packet.sqlstate, sizeof(conn->error_info->sqlstate));
1254 				DBG_ERR_FMT("ERROR:%u [SQLSTATE:%s] %s", result_packet.error_no, result_packet.sqlstate, result_packet.error);
1255 			}
1256 			SET_CLIENT_ERROR(conn->error_info, result_packet.error_no, UNKNOWN_SQLSTATE, result_packet.error);
1257 			DBG_RETURN(FAIL);
1258 		case 0xFE:
1259 			DBG_INF("auth switch response");
1260 			*new_auth_protocol = result_packet.new_auth_protocol;
1261 			*new_auth_protocol_len = result_packet.new_auth_protocol_len;
1262 			*new_auth_protocol_data = result_packet.new_auth_protocol_data;
1263 			*new_auth_protocol_data_len = result_packet.new_auth_protocol_data_len;
1264 			DBG_RETURN(FAIL);
1265 		case 3:
1266 			DBG_INF("fast path succeeded");
1267 			DBG_RETURN(PASS);
1268 		case 4:
1269 			if (is_secure_transport(conn)) {
1270 				DBG_INF("fast path failed, doing full auth via secure transport");
1271 				result_packet.password = (zend_uchar *)passwd;
1272 				result_packet.password_len = passwd_len + 1;
1273 				PACKET_WRITE(conn, &result_packet);
1274 			} else {
1275 				DBG_INF("fast path failed, doing full auth via insecure transport");
1276 				result_packet.password_len = mysqlnd_caching_sha2_get_and_use_key(conn, auth_plugin_data, auth_plugin_data_len, &result_packet.password, passwd, passwd_len);
1277 				PACKET_WRITE(conn, &result_packet);
1278 				efree(result_packet.password);
1279 			}
1280 			DBG_RETURN(PASS);
1281 		case 2:
1282 			// The server tried to send a key, which we didn't expect
1283 			// fall-through
1284 		default: {
1285 			char * msg;
1286 			mnd_sprintf(&msg, 0, "Unexpected server response while doing caching_sha2 auth: %i", result_packet.response_code);
1287 			SET_CLIENT_ERROR(conn->error_info, CR_NOT_IMPLEMENTED, UNKNOWN_SQLSTATE, msg);
1288 			mnd_sprintf_free(msg);
1289 		}
1290 	}
1291 
1292 	DBG_RETURN(PASS);
1293 }
1294 /* }}} */
1295 
1296 static struct st_mysqlnd_authentication_plugin mysqlnd_caching_sha2_auth_plugin =
1297 {
1298 	{
1299 		MYSQLND_PLUGIN_API_VERSION,
1300 		"auth_plugin_caching_sha2_password",
1301 		MYSQLND_VERSION_ID,
1302 		PHP_MYSQLND_VERSION,
1303 		"PHP License 3.01",
1304 		"Johannes Schlüter <johannes.schlueter@php.net>",
1305 		{
1306 			NULL, /* no statistics , will be filled later if there are some */
1307 			NULL, /* no statistics */
1308 		},
1309 		{
1310 			NULL /* plugin shutdown */
1311 		}
1312 	},
1313 	{/* methods */
1314 		mysqlnd_caching_sha2_get_auth_data,
1315 		mysqlnd_caching_sha2_handle_server_response
1316 	}
1317 };
1318 #endif
1319 
1320 
1321 /* {{{ mysqlnd_register_builtin_authentication_plugins */
1322 void
mysqlnd_register_builtin_authentication_plugins(void)1323 mysqlnd_register_builtin_authentication_plugins(void)
1324 {
1325 	mysqlnd_plugin_register_ex((struct st_mysqlnd_plugin_header *) &mysqlnd_native_auth_plugin);
1326 	mysqlnd_plugin_register_ex((struct st_mysqlnd_plugin_header *) &mysqlnd_pam_authentication_plugin);
1327 #ifdef MYSQLND_HAVE_SSL
1328 	mysqlnd_plugin_register_ex((struct st_mysqlnd_plugin_header *) &mysqlnd_caching_sha2_auth_plugin);
1329 	mysqlnd_plugin_register_ex((struct st_mysqlnd_plugin_header *) &mysqlnd_sha256_authentication_plugin);
1330 #endif
1331 }
1332 /* }}} */
1333