1 /*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 2006-2018 The PHP Group                                |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | http://www.php.net/license/3_01.txt                                  |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Andrey Hristov <andrey@php.net>                             |
16   |          Ulf Wendel <uw@php.net>                                     |
17   +----------------------------------------------------------------------+
18 */
19 
20 #include "php.h"
21 #include "mysqlnd.h"
22 #include "mysqlnd_structs.h"
23 #include "mysqlnd_auth.h"
24 #include "mysqlnd_wireprotocol.h"
25 #include "mysqlnd_connection.h"
26 #include "mysqlnd_priv.h"
27 #include "mysqlnd_charset.h"
28 #include "mysqlnd_debug.h"
29 
30 static const char * const mysqlnd_old_passwd  = "mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication. "
31 "Please use an administration tool to reset your password with the command SET PASSWORD = PASSWORD('your_existing_password'). This will "
32 "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 "
33 "flag from your my.cnf file";
34 
35 
36 /* {{{ mysqlnd_run_authentication */
37 enum_func_status
mysqlnd_run_authentication(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_STRING auth_plugin_data,const char * const auth_protocol,unsigned int charset_no,const MYSQLND_SESSION_OPTIONS * const session_options,zend_ulong mysql_flags,zend_bool silent,zend_bool is_change_user)38 mysqlnd_run_authentication(
39 			MYSQLND_CONN_DATA * conn,
40 			const char * const user,
41 			const char * const passwd,
42 			const size_t passwd_len,
43 			const char * const db,
44 			const size_t db_len,
45 			const MYSQLND_STRING auth_plugin_data,
46 			const char * const auth_protocol,
47 			unsigned int charset_no,
48 			const MYSQLND_SESSION_OPTIONS * const session_options,
49 			zend_ulong mysql_flags,
50 			zend_bool silent,
51 			zend_bool is_change_user
52 			)
53 {
54 	enum_func_status ret = FAIL;
55 	zend_bool first_call = TRUE;
56 
57 	char * switch_to_auth_protocol = NULL;
58 	size_t switch_to_auth_protocol_len = 0;
59 	char * requested_protocol = NULL;
60 	zend_uchar * plugin_data;
61 	size_t plugin_data_len;
62 
63 	DBG_ENTER("mysqlnd_run_authentication");
64 
65 	plugin_data_len = auth_plugin_data.l;
66 	plugin_data = mnd_emalloc(plugin_data_len + 1);
67 	if (!plugin_data) {
68 		goto end;
69 	}
70 	memcpy(plugin_data, auth_plugin_data.s, plugin_data_len);
71 	plugin_data[plugin_data_len] = '\0';
72 
73 	requested_protocol = mnd_pestrdup(auth_protocol? auth_protocol : MYSQLND_DEFAULT_AUTH_PROTOCOL, FALSE);
74 	if (!requested_protocol) {
75 		goto end;
76 	}
77 
78 	do {
79 		struct st_mysqlnd_authentication_plugin * auth_plugin = conn->m->fetch_auth_plugin_by_name(requested_protocol);
80 
81 		if (!auth_plugin) {
82 			if (first_call) {
83 				mnd_pefree(requested_protocol, FALSE);
84 				requested_protocol = mnd_pestrdup(MYSQLND_DEFAULT_AUTH_PROTOCOL, FALSE);
85 			} else {
86 				php_error_docref(NULL, E_WARNING, "The server requested authentication method unknown to the client [%s]", requested_protocol);
87 				SET_CLIENT_ERROR(conn->error_info, CR_NOT_IMPLEMENTED, UNKNOWN_SQLSTATE, "The server requested authentication method unknown to the client");
88 				goto end;
89 			}
90 		}
91 
92 		{
93 			zend_uchar * switch_to_auth_protocol_data = NULL;
94 			size_t switch_to_auth_protocol_data_len = 0;
95 			zend_uchar * scrambled_data = NULL;
96 			size_t scrambled_data_len = 0;
97 
98 			switch_to_auth_protocol = NULL;
99 			switch_to_auth_protocol_len = 0;
100 
101 			if (conn->authentication_plugin_data.s) {
102 				mnd_pefree(conn->authentication_plugin_data.s, conn->persistent);
103 				conn->authentication_plugin_data.s = NULL;
104 			}
105 			conn->authentication_plugin_data.l = plugin_data_len;
106 			conn->authentication_plugin_data.s = mnd_pemalloc(conn->authentication_plugin_data.l, conn->persistent);
107 			if (!conn->authentication_plugin_data.s) {
108 				SET_OOM_ERROR(conn->error_info);
109 				goto end;
110 			}
111 			memcpy(conn->authentication_plugin_data.s, plugin_data, plugin_data_len);
112 
113 			DBG_INF_FMT("salt(%d)=[%.*s]", plugin_data_len, plugin_data_len, plugin_data);
114 			/* The data should be allocated with malloc() */
115 			if (auth_plugin) {
116 				scrambled_data =
117 					auth_plugin->methods.get_auth_data(NULL, &scrambled_data_len, conn, user, passwd, passwd_len,
118 													   plugin_data, plugin_data_len, session_options,
119 													   conn->protocol_frame_codec->data, mysql_flags);
120 			}
121 
122 			if (conn->error_info->error_no) {
123 				goto end;
124 			}
125 			if (FALSE == is_change_user) {
126 				ret = mysqlnd_auth_handshake(conn, user, passwd, passwd_len, db, db_len, session_options, mysql_flags,
127 											charset_no,
128 											first_call,
129 											requested_protocol,
130 											scrambled_data, scrambled_data_len,
131 											&switch_to_auth_protocol, &switch_to_auth_protocol_len,
132 											&switch_to_auth_protocol_data, &switch_to_auth_protocol_data_len
133 											);
134 			} else {
135 				ret = mysqlnd_auth_change_user(conn, user, strlen(user), passwd, passwd_len, db, db_len, silent,
136 											   first_call,
137 											   requested_protocol,
138 											   scrambled_data, scrambled_data_len,
139 											   &switch_to_auth_protocol, &switch_to_auth_protocol_len,
140 											   &switch_to_auth_protocol_data, &switch_to_auth_protocol_data_len
141 											  );
142 			}
143 			first_call = FALSE;
144 			free(scrambled_data);
145 
146 			DBG_INF_FMT("switch_to_auth_protocol=%s", switch_to_auth_protocol? switch_to_auth_protocol:"n/a");
147 			if (requested_protocol && switch_to_auth_protocol) {
148 				mnd_efree(requested_protocol);
149 				requested_protocol = switch_to_auth_protocol;
150 			}
151 
152 			if (plugin_data) {
153 				mnd_efree(plugin_data);
154 			}
155 			plugin_data_len = switch_to_auth_protocol_data_len;
156 			plugin_data = switch_to_auth_protocol_data;
157 		}
158 		DBG_INF_FMT("conn->error_info->error_no = %d", conn->error_info->error_no);
159 	} while (ret == FAIL && conn->error_info->error_no == 0 && switch_to_auth_protocol != NULL);
160 
161 	if (ret == PASS) {
162 		DBG_INF_FMT("saving requested_protocol=%s", requested_protocol);
163 		conn->m->set_client_option(conn, MYSQLND_OPT_AUTH_PROTOCOL, requested_protocol);
164 	}
165 end:
166 	if (plugin_data) {
167 		mnd_efree(plugin_data);
168 	}
169 	if (requested_protocol) {
170 		mnd_efree(requested_protocol);
171 	}
172 
173 	DBG_RETURN(ret);
174 }
175 /* }}} */
176 
177 
178 /* {{{ mysqlnd_switch_to_ssl_if_needed */
179 static enum_func_status
mysqlnd_switch_to_ssl_if_needed(MYSQLND_CONN_DATA * conn,unsigned int charset_no,size_t server_capabilities,const MYSQLND_SESSION_OPTIONS * const session_options,zend_ulong mysql_flags)180 mysqlnd_switch_to_ssl_if_needed(MYSQLND_CONN_DATA * conn,
181 								unsigned int charset_no,
182 								size_t server_capabilities,
183 								const MYSQLND_SESSION_OPTIONS * const session_options,
184 								zend_ulong mysql_flags)
185 {
186 	enum_func_status ret = FAIL;
187 	const MYSQLND_CHARSET * charset;
188 	DBG_ENTER("mysqlnd_switch_to_ssl_if_needed");
189 
190 	if (session_options->charset_name && (charset = mysqlnd_find_charset_name(session_options->charset_name))) {
191 		charset_no	= charset->nr;
192 	}
193 
194 	{
195 		size_t client_capabilities = mysql_flags;
196 		ret = conn->run_command(COM_ENABLE_SSL, conn, client_capabilities, server_capabilities, charset_no);
197 	}
198 	DBG_RETURN(ret);
199 }
200 /* }}} */
201 
202 
203 /* {{{ mysqlnd_connect_run_authentication */
204 enum_func_status
mysqlnd_connect_run_authentication(MYSQLND_CONN_DATA * conn,const char * const user,const char * const passwd,const char * const db,size_t db_len,size_t passwd_len,MYSQLND_STRING authentication_plugin_data,const char * const authentication_protocol,const unsigned int charset_no,size_t server_capabilities,const MYSQLND_SESSION_OPTIONS * const session_options,zend_ulong mysql_flags)205 mysqlnd_connect_run_authentication(
206 			MYSQLND_CONN_DATA * conn,
207 			const char * const user,
208 			const char * const passwd,
209 			const char * const db,
210 			size_t db_len,
211 			size_t passwd_len,
212 			MYSQLND_STRING authentication_plugin_data,
213 			const char * const authentication_protocol,
214 			const unsigned int charset_no,
215 			size_t server_capabilities,
216 			const MYSQLND_SESSION_OPTIONS * const session_options,
217 			zend_ulong mysql_flags
218 			)
219 {
220 	enum_func_status ret = FAIL;
221 	DBG_ENTER("mysqlnd_connect_run_authentication");
222 
223 	ret = mysqlnd_switch_to_ssl_if_needed(conn, charset_no, server_capabilities, session_options, mysql_flags);
224 	if (PASS == ret) {
225 		ret = mysqlnd_run_authentication(conn, user, passwd, passwd_len, db, db_len,
226 										 authentication_plugin_data, authentication_protocol,
227 										 charset_no, session_options, mysql_flags, FALSE /*silent*/, FALSE/*is_change*/);
228 	}
229 	DBG_RETURN(ret);
230 }
231 /* }}} */
232 
233 
234 /* {{{ mysqlnd_auth_handshake */
235 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,zend_ulong mysql_flags,unsigned int server_charset_no,zend_bool use_full_blown_auth_packet,const char * const auth_protocol,const zend_uchar * const auth_plugin_data,const size_t auth_plugin_data_len,char ** switch_to_auth_protocol,size_t * switch_to_auth_protocol_len,zend_uchar ** switch_to_auth_protocol_data,size_t * switch_to_auth_protocol_data_len)236 mysqlnd_auth_handshake(MYSQLND_CONN_DATA * conn,
237 							  const char * const user,
238 							  const char * const passwd,
239 							  const size_t passwd_len,
240 							  const char * const db,
241 							  const size_t db_len,
242 							  const MYSQLND_SESSION_OPTIONS * const session_options,
243 							  zend_ulong mysql_flags,
244 							  unsigned int server_charset_no,
245 							  zend_bool use_full_blown_auth_packet,
246 							  const char * const auth_protocol,
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 * switch_to_auth_protocol_len,
251 							  zend_uchar ** switch_to_auth_protocol_data,
252 							  size_t * 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 (FAIL == PACKET_READ(conn, &auth_resp_packet) || auth_resp_packet.response_code >= 0xFE) {
317 		if (auth_resp_packet.response_code == 0xFE) {
318 			/* old authentication with new server  !*/
319 			if (!auth_resp_packet.new_auth_protocol) {
320 				DBG_ERR(mysqlnd_old_passwd);
321 				SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE, mysqlnd_old_passwd);
322 			} else {
323 				*switch_to_auth_protocol = mnd_pestrndup(auth_resp_packet.new_auth_protocol, auth_resp_packet.new_auth_protocol_len, FALSE);
324 				*switch_to_auth_protocol_len = auth_resp_packet.new_auth_protocol_len;
325 				if (auth_resp_packet.new_auth_protocol_data) {
326 					*switch_to_auth_protocol_data_len = auth_resp_packet.new_auth_protocol_data_len;
327 					*switch_to_auth_protocol_data = mnd_emalloc(*switch_to_auth_protocol_data_len);
328 					memcpy(*switch_to_auth_protocol_data, auth_resp_packet.new_auth_protocol_data, *switch_to_auth_protocol_data_len);
329 				} else {
330 					*switch_to_auth_protocol_data = NULL;
331 					*switch_to_auth_protocol_data_len = 0;
332 				}
333 			}
334 		} else if (auth_resp_packet.response_code == 0xFF) {
335 			if (auth_resp_packet.sqlstate[0]) {
336 				strlcpy(conn->error_info->sqlstate, auth_resp_packet.sqlstate, sizeof(conn->error_info->sqlstate));
337 				DBG_ERR_FMT("ERROR:%u [SQLSTATE:%s] %s", auth_resp_packet.error_no, auth_resp_packet.sqlstate, auth_resp_packet.error);
338 			}
339 			SET_CLIENT_ERROR(conn->error_info, auth_resp_packet.error_no, UNKNOWN_SQLSTATE, auth_resp_packet.error);
340 		}
341 		goto end;
342 	}
343 
344 	SET_NEW_MESSAGE(conn->last_message.s, conn->last_message.l, auth_resp_packet.message, auth_resp_packet.message_len);
345 	ret = PASS;
346 end:
347 	PACKET_FREE(&auth_resp_packet);
348 	DBG_RETURN(ret);
349 }
350 /* }}} */
351 
352 
353 /* {{{ mysqlnd_auth_change_user */
354 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 zend_bool silent,zend_bool use_full_blown_auth_packet,const char * const auth_protocol,zend_uchar * auth_plugin_data,size_t auth_plugin_data_len,char ** switch_to_auth_protocol,size_t * switch_to_auth_protocol_len,zend_uchar ** switch_to_auth_protocol_data,size_t * switch_to_auth_protocol_data_len)355 mysqlnd_auth_change_user(MYSQLND_CONN_DATA * const conn,
356 								const char * const user,
357 								const size_t user_len,
358 								const char * const passwd,
359 								const size_t passwd_len,
360 								const char * const db,
361 								const size_t db_len,
362 								const zend_bool silent,
363 								zend_bool use_full_blown_auth_packet,
364 								const char * const auth_protocol,
365 								zend_uchar * auth_plugin_data,
366 								size_t auth_plugin_data_len,
367 								char ** switch_to_auth_protocol,
368 								size_t * switch_to_auth_protocol_len,
369 								zend_uchar ** switch_to_auth_protocol_data,
370 								size_t * switch_to_auth_protocol_data_len
371 								)
372 {
373 	enum_func_status ret = FAIL;
374 	const MYSQLND_CHARSET * old_cs = conn->charset;
375 	MYSQLND_PACKET_CHG_USER_RESPONSE chg_user_resp;
376 
377 	DBG_ENTER("mysqlnd_auth_change_user");
378 
379 	conn->payload_decoder_factory->m.init_change_user_response_packet(&chg_user_resp);
380 
381 	if (use_full_blown_auth_packet != TRUE) {
382 		MYSQLND_PACKET_CHANGE_AUTH_RESPONSE change_auth_resp_packet;
383 
384 		conn->payload_decoder_factory->m.init_change_auth_response_packet(&change_auth_resp_packet);
385 
386 		change_auth_resp_packet.auth_data = auth_plugin_data;
387 		change_auth_resp_packet.auth_data_len = auth_plugin_data_len;
388 
389 		if (!PACKET_WRITE(conn, &change_auth_resp_packet)) {
390 			SET_CONNECTION_STATE(&conn->state, CONN_QUIT_SENT);
391 			SET_CLIENT_ERROR(conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone);
392 			PACKET_FREE(&change_auth_resp_packet);
393 			goto end;
394 		}
395 
396 		PACKET_FREE(&change_auth_resp_packet);
397 	} else {
398 		MYSQLND_PACKET_AUTH auth_packet;
399 
400 		conn->payload_decoder_factory->m.init_auth_packet(&auth_packet);
401 
402 		auth_packet.is_change_user_packet = TRUE;
403 		auth_packet.user		= user;
404 		auth_packet.db			= db;
405 		auth_packet.db_len		= db_len;
406 		auth_packet.silent		= silent;
407 
408 		auth_packet.auth_data = auth_plugin_data;
409 		auth_packet.auth_data_len = auth_plugin_data_len;
410 		auth_packet.auth_plugin_name = auth_protocol;
411 
412         if (conn->server_capabilities & CLIENT_CONNECT_ATTRS) {
413 			auth_packet.connect_attr = conn->options->connect_attr;
414         }
415 
416 		if (conn->m->get_server_version(conn) >= 50123) {
417 			auth_packet.charset_no	= conn->charset->nr;
418 		}
419 
420 		if (!PACKET_WRITE(conn, &auth_packet)) {
421 			SET_CONNECTION_STATE(&conn->state, CONN_QUIT_SENT);
422 			SET_CLIENT_ERROR(conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone);
423 			PACKET_FREE(&auth_packet);
424 			goto end;
425 		}
426 
427 		PACKET_FREE(&auth_packet);
428 	}
429 
430 	ret = PACKET_READ(conn, &chg_user_resp);
431 	COPY_CLIENT_ERROR(conn->error_info, chg_user_resp.error_info);
432 
433 	if (0xFE == chg_user_resp.response_code) {
434 		ret = FAIL;
435 		if (!chg_user_resp.new_auth_protocol) {
436 			DBG_ERR(mysqlnd_old_passwd);
437 			SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE, mysqlnd_old_passwd);
438 		} else {
439 			*switch_to_auth_protocol = mnd_pestrndup(chg_user_resp.new_auth_protocol, chg_user_resp.new_auth_protocol_len, FALSE);
440 			*switch_to_auth_protocol_len = chg_user_resp.new_auth_protocol_len;
441 			if (chg_user_resp.new_auth_protocol_data) {
442 				*switch_to_auth_protocol_data_len = chg_user_resp.new_auth_protocol_data_len;
443 				*switch_to_auth_protocol_data = mnd_emalloc(*switch_to_auth_protocol_data_len);
444 				memcpy(*switch_to_auth_protocol_data, chg_user_resp.new_auth_protocol_data, *switch_to_auth_protocol_data_len);
445 			} else {
446 				*switch_to_auth_protocol_data = NULL;
447 				*switch_to_auth_protocol_data_len = 0;
448 			}
449 		}
450 	}
451 
452 	if (conn->error_info->error_no) {
453 		ret = FAIL;
454 		/*
455 		  COM_CHANGE_USER is broken in 5.1. At least in 5.1.15 and 5.1.14, 5.1.11 is immune.
456 		  bug#25371 mysql_change_user() triggers "packets out of sync"
457 		  When it gets fixed, there should be one more check here
458 		*/
459 		if (conn->m->get_server_version(conn) > 50113L &&conn->m->get_server_version(conn) < 50118L) {
460 			MYSQLND_PACKET_OK redundant_error_packet;
461 
462 			conn->payload_decoder_factory->m.init_ok_packet(&redundant_error_packet);
463 			PACKET_READ(conn, &redundant_error_packet);
464 			PACKET_FREE(&redundant_error_packet);
465 			DBG_INF_FMT("Server is %u, buggy, sends two ERR messages", conn->m->get_server_version(conn));
466 		}
467 	}
468 	if (ret == PASS) {
469 		char * tmp = NULL;
470 		/* if we get conn->username as parameter and then we first free it, then estrndup it, we will crash */
471 		tmp = mnd_pestrndup(user, user_len, conn->persistent);
472 		if (conn->username.s) {
473 			mnd_pefree(conn->username.s, conn->persistent);
474 		}
475 		conn->username.s = tmp;
476 
477 		tmp = mnd_pestrdup(passwd, conn->persistent);
478 		if (conn->password.s) {
479 			mnd_pefree(conn->password.s, conn->persistent);
480 		}
481 		conn->password.s = tmp;
482 
483 		if (conn->last_message.s) {
484 			mnd_efree(conn->last_message.s);
485 			conn->last_message.s = NULL;
486 		}
487 		UPSERT_STATUS_RESET(conn->upsert_status);
488 		/* set charset for old servers */
489 		if (conn->m->get_server_version(conn) < 50123) {
490 			ret = conn->m->set_charset(conn, old_cs->name);
491 		}
492 	} else if (ret == FAIL && chg_user_resp.server_asked_323_auth == TRUE) {
493 		/* old authentication with new server  !*/
494 		DBG_ERR(mysqlnd_old_passwd);
495 		SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE, mysqlnd_old_passwd);
496 	}
497 end:
498 	PACKET_FREE(&chg_user_resp);
499 	DBG_RETURN(ret);
500 }
501 /* }}} */
502 
503 
504 /******************************************* MySQL Native Password ***********************************/
505 
506 #include "ext/standard/sha1.h"
507 
508 /* {{{ php_mysqlnd_crypt */
509 static void
php_mysqlnd_crypt(zend_uchar * buffer,const zend_uchar * s1,const zend_uchar * s2,size_t len)510 php_mysqlnd_crypt(zend_uchar *buffer, const zend_uchar *s1, const zend_uchar *s2, size_t len)
511 {
512 	const zend_uchar *s1_end = s1 + len;
513 	while (s1 < s1_end) {
514 		*buffer++= *s1++ ^ *s2++;
515 	}
516 }
517 /* }}} */
518 
519 
520 /* {{{ 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)521 void php_mysqlnd_scramble(zend_uchar * const buffer, const zend_uchar * const scramble, const zend_uchar * const password, const size_t password_len)
522 {
523 	PHP_SHA1_CTX context;
524 	zend_uchar sha1[SHA1_MAX_LENGTH];
525 	zend_uchar sha2[SHA1_MAX_LENGTH];
526 
527 	/* Phase 1: hash password */
528 	PHP_SHA1Init(&context);
529 	PHP_SHA1Update(&context, password, password_len);
530 	PHP_SHA1Final(sha1, &context);
531 
532 	/* Phase 2: hash sha1 */
533 	PHP_SHA1Init(&context);
534 	PHP_SHA1Update(&context, (zend_uchar*)sha1, SHA1_MAX_LENGTH);
535 	PHP_SHA1Final(sha2, &context);
536 
537 	/* Phase 3: hash scramble + sha2 */
538 	PHP_SHA1Init(&context);
539 	PHP_SHA1Update(&context, scramble, SCRAMBLE_LENGTH);
540 	PHP_SHA1Update(&context, (zend_uchar*)sha2, SHA1_MAX_LENGTH);
541 	PHP_SHA1Final(buffer, &context);
542 
543 	/* let's crypt buffer now */
544 	php_mysqlnd_crypt(buffer, (const zend_uchar *)buffer, (const zend_uchar *)sha1, SHA1_MAX_LENGTH);
545 }
546 /* }}} */
547 
548 
549 /* {{{ mysqlnd_native_auth_get_auth_data */
550 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,size_t auth_plugin_data_len,const MYSQLND_SESSION_OPTIONS * const session_options,const MYSQLND_PFC_DATA * const pfc_data,zend_ulong mysql_flags)551 mysqlnd_native_auth_get_auth_data(struct st_mysqlnd_authentication_plugin * self,
552 								  size_t * auth_data_len,
553 								  MYSQLND_CONN_DATA * conn, const char * const user, const char * const passwd,
554 								  const size_t passwd_len, zend_uchar * auth_plugin_data, size_t auth_plugin_data_len,
555 								  const MYSQLND_SESSION_OPTIONS * const session_options,
556 								  const MYSQLND_PFC_DATA * const pfc_data,
557 								  zend_ulong mysql_flags
558 								 )
559 {
560 	zend_uchar * ret = NULL;
561 	DBG_ENTER("mysqlnd_native_auth_get_auth_data");
562 	*auth_data_len = 0;
563 
564 	/* 5.5.x reports 21 as scramble length because it needs to show the length of the data before the plugin name */
565 	if (auth_plugin_data_len < SCRAMBLE_LENGTH) {
566 		/* mysql_native_password only works with SCRAMBLE_LENGTH scramble */
567 		SET_CLIENT_ERROR(conn->error_info, CR_MALFORMED_PACKET, UNKNOWN_SQLSTATE, "The server sent wrong length for scramble");
568 		DBG_ERR_FMT("The server sent wrong length for scramble %u. Expected %u", auth_plugin_data_len, SCRAMBLE_LENGTH);
569 		DBG_RETURN(NULL);
570 	}
571 
572 	/* copy scrambled pass*/
573 	if (passwd && passwd_len) {
574 		ret = malloc(SCRAMBLE_LENGTH);
575 		*auth_data_len = SCRAMBLE_LENGTH;
576 		/* In 4.1 we use CLIENT_SECURE_CONNECTION and thus the len of the buf should be passed */
577 		php_mysqlnd_scramble((zend_uchar*)ret, auth_plugin_data, (zend_uchar*)passwd, passwd_len);
578 	}
579 	DBG_RETURN(ret);
580 }
581 /* }}} */
582 
583 
584 static struct st_mysqlnd_authentication_plugin mysqlnd_native_auth_plugin =
585 {
586 	{
587 		MYSQLND_PLUGIN_API_VERSION,
588 		"auth_plugin_mysql_native_password",
589 		MYSQLND_VERSION_ID,
590 		PHP_MYSQLND_VERSION,
591 		"PHP License 3.01",
592 		"Andrey Hristov <andrey@php.net>,  Ulf Wendel <uwendel@mysql.com>, Georg Richter <georg@mysql.com>",
593 		{
594 			NULL, /* no statistics , will be filled later if there are some */
595 			NULL, /* no statistics */
596 		},
597 		{
598 			NULL /* plugin shutdown */
599 		}
600 	},
601 	{/* methods */
602 		mysqlnd_native_auth_get_auth_data
603 	}
604 };
605 
606 
607 /******************************************* PAM Authentication ***********************************/
608 
609 /* {{{ mysqlnd_pam_auth_get_auth_data */
610 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,size_t auth_plugin_data_len,const MYSQLND_SESSION_OPTIONS * const session_options,const MYSQLND_PFC_DATA * const pfc_data,zend_ulong mysql_flags)611 mysqlnd_pam_auth_get_auth_data(struct st_mysqlnd_authentication_plugin * self,
612 							   size_t * auth_data_len,
613 							   MYSQLND_CONN_DATA * conn, const char * const user, const char * const passwd,
614 							   const size_t passwd_len, zend_uchar * auth_plugin_data, size_t auth_plugin_data_len,
615 							   const MYSQLND_SESSION_OPTIONS * const session_options,
616 							   const MYSQLND_PFC_DATA * const pfc_data,
617 							   zend_ulong mysql_flags
618 							  )
619 {
620 	zend_uchar * ret = NULL;
621 
622 	/* copy pass*/
623 	if (passwd && passwd_len) {
624 		ret = (zend_uchar*) zend_strndup(passwd, passwd_len);
625 	}
626 	*auth_data_len = passwd_len;
627 
628 	return ret;
629 }
630 /* }}} */
631 
632 
633 static struct st_mysqlnd_authentication_plugin mysqlnd_pam_authentication_plugin =
634 {
635 	{
636 		MYSQLND_PLUGIN_API_VERSION,
637 		"auth_plugin_mysql_clear_password",
638 		MYSQLND_VERSION_ID,
639 		PHP_MYSQLND_VERSION,
640 		"PHP License 3.01",
641 		"Andrey Hristov <andrey@php.net>,  Ulf Wendel <uw@php.net>, Georg Richter <georg@php.net>",
642 		{
643 			NULL, /* no statistics , will be filled later if there are some */
644 			NULL, /* no statistics */
645 		},
646 		{
647 			NULL /* plugin shutdown */
648 		}
649 	},
650 	{/* methods */
651 		mysqlnd_pam_auth_get_auth_data
652 	}
653 };
654 
655 
656 /******************************************* SHA256 Password ***********************************/
657 #ifdef MYSQLND_HAVE_SSL
658 static void
mysqlnd_xor_string(char * dst,const size_t dst_len,const char * xor_str,const size_t xor_str_len)659 mysqlnd_xor_string(char * dst, const size_t dst_len, const char * xor_str, const size_t xor_str_len)
660 {
661 	unsigned int i;
662 	for (i = 0; i <= dst_len; ++i) {
663 		dst[i] ^= xor_str[i % xor_str_len];
664 	}
665 }
666 
667 
668 #include <openssl/rsa.h>
669 #include <openssl/pem.h>
670 #include <openssl/err.h>
671 
672 
673 /* {{{ mysqlnd_sha256_get_rsa_key */
674 static RSA *
mysqlnd_sha256_get_rsa_key(MYSQLND_CONN_DATA * conn,const MYSQLND_SESSION_OPTIONS * const session_options,const MYSQLND_PFC_DATA * const pfc_data)675 mysqlnd_sha256_get_rsa_key(MYSQLND_CONN_DATA * conn,
676 						   const MYSQLND_SESSION_OPTIONS * const session_options,
677 						   const MYSQLND_PFC_DATA * const pfc_data
678 						  )
679 {
680 	RSA * ret = NULL;
681 	const char * fname = (pfc_data->sha256_server_public_key && pfc_data->sha256_server_public_key[0] != '\0')?
682 								pfc_data->sha256_server_public_key:
683 								MYSQLND_G(sha256_server_public_key);
684 	php_stream * stream;
685 	DBG_ENTER("mysqlnd_sha256_get_rsa_key");
686 	DBG_INF_FMT("options_s256_pk=[%s] MYSQLND_G(sha256_server_public_key)=[%s]",
687 				 pfc_data->sha256_server_public_key? pfc_data->sha256_server_public_key:"n/a",
688 				 MYSQLND_G(sha256_server_public_key)? MYSQLND_G(sha256_server_public_key):"n/a");
689 	if (!fname || fname[0] == '\0') {
690 		MYSQLND_PACKET_SHA256_PK_REQUEST pk_req_packet;
691 		MYSQLND_PACKET_SHA256_PK_REQUEST_RESPONSE pk_resp_packet;
692 
693 		do {
694 			DBG_INF("requesting the public key from the server");
695 			conn->payload_decoder_factory->m.init_sha256_pk_request_packet(&pk_req_packet);
696 			conn->payload_decoder_factory->m.init_sha256_pk_request_response_packet(&pk_resp_packet);
697 
698 			if (! PACKET_WRITE(conn, &pk_req_packet)) {
699 				DBG_ERR_FMT("Error while sending public key request packet");
700 				php_error(E_WARNING, "Error while sending public key request packet. PID=%d", getpid());
701 				SET_CONNECTION_STATE(&conn->state, CONN_QUIT_SENT);
702 				break;
703 			}
704 			if (FAIL == PACKET_READ(conn, &pk_resp_packet) || NULL == pk_resp_packet.public_key) {
705 				DBG_ERR_FMT("Error while receiving public key");
706 				php_error(E_WARNING, "Error while receiving public key. PID=%d", getpid());
707 				SET_CONNECTION_STATE(&conn->state, CONN_QUIT_SENT);
708 				break;
709 			}
710 			DBG_INF_FMT("Public key(%d):\n%s", pk_resp_packet.public_key_len, pk_resp_packet.public_key);
711 			/* now extract the public key */
712 			{
713 				BIO * bio = BIO_new_mem_buf(pk_resp_packet.public_key, pk_resp_packet.public_key_len);
714 				ret = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL);
715 				BIO_free(bio);
716 			}
717 		} while (0);
718 		PACKET_FREE(&pk_req_packet);
719 		PACKET_FREE(&pk_resp_packet);
720 
721 		DBG_INF_FMT("ret=%p", ret);
722 		DBG_RETURN(ret);
723 
724 		SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE,
725 			"sha256_server_public_key is not set for the connection or as mysqlnd.sha256_server_public_key");
726 		DBG_ERR("server_public_key is not set");
727 		DBG_RETURN(NULL);
728 	} else {
729 		zend_string * key_str;
730 		DBG_INF_FMT("Key in a file. [%s]", fname);
731 		stream = php_stream_open_wrapper((char *) fname, "rb", REPORT_ERRORS, NULL);
732 
733 		if (stream) {
734 			if ((key_str = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0)) != NULL) {
735 				BIO * bio = BIO_new_mem_buf(ZSTR_VAL(key_str), ZSTR_LEN(key_str));
736 				ret = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL);
737 				BIO_free(bio);
738 				DBG_INF("Successfully loaded");
739 				DBG_INF_FMT("Public key:%*.s", ZSTR_LEN(key_str), ZSTR_VAL(key_str));
740 				zend_string_release_ex(key_str, 0);
741 			}
742 			php_stream_close(stream);
743 		}
744 	}
745 	DBG_RETURN(ret);
746 }
747 /* }}} */
748 
749 
750 /* {{{ mysqlnd_sha256_auth_get_auth_data */
751 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,size_t auth_plugin_data_len,const MYSQLND_SESSION_OPTIONS * const session_options,const MYSQLND_PFC_DATA * const pfc_data,zend_ulong mysql_flags)752 mysqlnd_sha256_auth_get_auth_data(struct st_mysqlnd_authentication_plugin * self,
753 								  size_t * auth_data_len,
754 								  MYSQLND_CONN_DATA * conn, const char * const user, const char * const passwd,
755 								  const size_t passwd_len, zend_uchar * auth_plugin_data, size_t auth_plugin_data_len,
756 								  const MYSQLND_SESSION_OPTIONS * const session_options,
757 								  const MYSQLND_PFC_DATA * const pfc_data,
758 								  zend_ulong mysql_flags
759 								 )
760 {
761 	RSA * server_public_key;
762 	zend_uchar * ret = NULL;
763 	DBG_ENTER("mysqlnd_sha256_auth_get_auth_data");
764 	DBG_INF_FMT("salt(%d)=[%.*s]", auth_plugin_data_len, auth_plugin_data_len, auth_plugin_data);
765 
766 
767 	if (conn->vio->data->ssl) {
768 		DBG_INF("simple clear text under SSL");
769 		/* clear text under SSL */
770 		*auth_data_len = passwd_len;
771 		ret = malloc(passwd_len);
772 		memcpy(ret, passwd, passwd_len);
773 	} else {
774 		*auth_data_len = 0;
775 		server_public_key = mysqlnd_sha256_get_rsa_key(conn, session_options, pfc_data);
776 
777 		if (server_public_key) {
778 			int server_public_key_len;
779 			char xor_str[passwd_len + 1];
780 			memcpy(xor_str, passwd, passwd_len);
781 			xor_str[passwd_len] = '\0';
782 			mysqlnd_xor_string(xor_str, passwd_len, (char *) auth_plugin_data, auth_plugin_data_len);
783 
784 			server_public_key_len = RSA_size(server_public_key);
785 			/*
786 			  Because RSA_PKCS1_OAEP_PADDING is used there is a restriction on the passwd_len.
787 			  RSA_PKCS1_OAEP_PADDING is recommended for new applications. See more here:
788 			  http://www.openssl.org/docs/crypto/RSA_public_encrypt.html
789 			*/
790 			if ((size_t) server_public_key_len - 41 <= passwd_len) {
791 				/* password message is to long */
792 				SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE, "password is too long");
793 				DBG_ERR("password is too long");
794 				DBG_RETURN(NULL);
795 			}
796 
797 			*auth_data_len = server_public_key_len;
798 			ret = malloc(*auth_data_len);
799 			RSA_public_encrypt(passwd_len + 1, (zend_uchar *) xor_str, ret, server_public_key, RSA_PKCS1_OAEP_PADDING);
800 		}
801 	}
802 
803 	DBG_RETURN(ret);
804 }
805 /* }}} */
806 
807 
808 static struct st_mysqlnd_authentication_plugin mysqlnd_sha256_authentication_plugin =
809 {
810 	{
811 		MYSQLND_PLUGIN_API_VERSION,
812 		"auth_plugin_sha256_password",
813 		MYSQLND_VERSION_ID,
814 		PHP_MYSQLND_VERSION,
815 		"PHP License 3.01",
816 		"Andrey Hristov <andrey@php.net>,  Ulf Wendel <uwendel@mysql.com>",
817 		{
818 			NULL, /* no statistics , will be filled later if there are some */
819 			NULL, /* no statistics */
820 		},
821 		{
822 			NULL /* plugin shutdown */
823 		}
824 	},
825 	{/* methods */
826 		mysqlnd_sha256_auth_get_auth_data
827 	}
828 };
829 #endif
830 
831 /* {{{ mysqlnd_register_builtin_authentication_plugins */
832 void
mysqlnd_register_builtin_authentication_plugins(void)833 mysqlnd_register_builtin_authentication_plugins(void)
834 {
835 	mysqlnd_plugin_register_ex((struct st_mysqlnd_plugin_header *) &mysqlnd_native_auth_plugin);
836 	mysqlnd_plugin_register_ex((struct st_mysqlnd_plugin_header *) &mysqlnd_pam_authentication_plugin);
837 #ifdef MYSQLND_HAVE_SSL
838 	mysqlnd_plugin_register_ex((struct st_mysqlnd_plugin_header *) &mysqlnd_sha256_authentication_plugin);
839 #endif
840 }
841 /* }}} */
842 
843 
844 /*
845  * Local variables:
846  * tab-width: 4
847  * c-basic-offset: 4
848  * End:
849  * vim600: noet sw=4 ts=4 fdm=marker
850  * vim<600: noet sw=4 ts=4
851  */
852