p9y: bsd
[m6w6/libmemcached] / src / libmemcached / sasl.cc
1 /*
2 +--------------------------------------------------------------------+
3 | libmemcached - C/C++ Client Library for memcached |
4 +--------------------------------------------------------------------+
5 | Redistribution and use in source and binary forms, with or without |
6 | modification, are permitted under the terms of the BSD license. |
7 | You should have received a copy of the license in a bundled file |
8 | named LICENSE; in case you did not receive a copy you can review |
9 | the terms online at: https://opensource.org/licenses/BSD-3-Clause |
10 +--------------------------------------------------------------------+
11 | Copyright (c) 2006-2014 Brian Aker https://datadifferential.com/ |
12 | Copyright (c) 2020 Michael Wallner <mike@php.net> |
13 +--------------------------------------------------------------------+
14 */
15
16 #include "libmemcached/common.h"
17
18 #include <cassert>
19 #include <atomic>
20
21 #if defined(LIBMEMCACHED_WITH_SASL_SUPPORT) && LIBMEMCACHED_WITH_SASL_SUPPORT
22
23 # if defined(HAVE_LIBSASL) && HAVE_LIBSASL
24 # include <sasl/sasl.h>
25 # endif
26
27 # define CAST_SASL_CB(cb) reinterpret_cast<int (*)()>(reinterpret_cast<intptr_t>(cb))
28
29 # include <pthread.h>
30
31 void memcached_set_sasl_callbacks(memcached_st *shell, const sasl_callback_t *callbacks) {
32 Memcached *self = memcached2Memcached(shell);
33 if (self) {
34 self->sasl.callbacks = const_cast<sasl_callback_t *>(callbacks);
35 self->sasl.is_allocated = false;
36 }
37 }
38
39 sasl_callback_t *memcached_get_sasl_callbacks(memcached_st *shell) {
40 Memcached *self = memcached2Memcached(shell);
41 if (self) {
42 return self->sasl.callbacks;
43 }
44
45 return NULL;
46 }
47
48 /**
49 * Resolve the names for both ends of a connection
50 * @param fd socket to check
51 * @param laddr local address (out)
52 * @param raddr remote address (out)
53 * @return true on success false otherwise (errno contains more info)
54 */
55 static memcached_return_t resolve_names(memcached_instance_st &server, char *laddr,
56 size_t laddr_length, char *raddr, size_t raddr_length) {
57 char host[MEMCACHED_NI_MAXHOST];
58 char port[MEMCACHED_NI_MAXSERV];
59 struct sockaddr_storage saddr;
60 socklen_t salen = sizeof(saddr);
61
62 if (getsockname(server.fd, (struct sockaddr *) &saddr, &salen) < 0) {
63 return memcached_set_error(server, MEMCACHED_HOST_LOOKUP_FAILURE, MEMCACHED_AT);
64 }
65
66 if (getnameinfo((struct sockaddr *) &saddr, salen, host, sizeof(host), port, sizeof(port),
67 NI_NUMERICHOST | NI_NUMERICSERV)
68 < 0)
69 {
70 return memcached_set_error(server, MEMCACHED_HOST_LOOKUP_FAILURE, MEMCACHED_AT);
71 }
72
73 (void) snprintf(laddr, laddr_length, "%s;%s", host, port);
74 salen = sizeof(saddr);
75
76 if (getpeername(server.fd, (struct sockaddr *) &saddr, &salen) < 0) {
77 return memcached_set_error(server, MEMCACHED_HOST_LOOKUP_FAILURE, MEMCACHED_AT);
78 }
79
80 if (getnameinfo((struct sockaddr *) &saddr, salen, host, sizeof(host), port, sizeof(port),
81 NI_NUMERICHOST | NI_NUMERICSERV)
82 < 0)
83 {
84 return memcached_set_error(server, MEMCACHED_HOST_LOOKUP_FAILURE, MEMCACHED_AT);
85 }
86
87 (void) snprintf(raddr, raddr_length, "%s;%s", host, port);
88
89 return MEMCACHED_SUCCESS;
90 }
91
92 extern "C" {
93
94 static void sasl_shutdown_function() {
95 sasl_done();
96 }
97
98 static std::atomic<int> sasl_startup_state(SASL_OK);
99 static pthread_mutex_t sasl_startup_state_LOCK = PTHREAD_MUTEX_INITIALIZER;
100 static pthread_once_t sasl_startup_once = PTHREAD_ONCE_INIT;
101 static void sasl_startup_function(void) {
102 sasl_startup_state = sasl_client_init(NULL);
103
104 if (sasl_startup_state == SASL_OK) {
105 (void) atexit(sasl_shutdown_function);
106 }
107 }
108
109 } // extern "C"
110
111 memcached_return_t memcached_sasl_authenticate_connection(memcached_instance_st *server) {
112 if (LIBMEMCACHED_WITH_SASL_SUPPORT == 0) {
113 return MEMCACHED_NOT_SUPPORTED;
114 }
115
116 if (server == NULL) {
117 return MEMCACHED_INVALID_ARGUMENTS;
118 }
119
120 /* SANITY CHECK: SASL can only be used with the binary protocol */
121 if (memcached_is_binary(server->root) == false) {
122 return memcached_set_error(
123 *server, MEMCACHED_INVALID_ARGUMENTS, MEMCACHED_AT,
124 memcached_literal_param(
125 "memcached_sasl_authenticate_connection() is not supported via the ASCII protocol"));
126 }
127
128 /* Try to get the supported mech from the server. Servers without SASL
129 * support will return UNKNOWN COMMAND, so we can just treat that
130 * as authenticated
131 */
132 protocol_binary_request_no_extras request = {};
133
134 initialize_binary_request(server, request.message.header);
135
136 request.message.header.request.opcode = PROTOCOL_BINARY_CMD_SASL_LIST_MECHS;
137
138 if (memcached_io_write(server, request.bytes, sizeof(request.bytes), true)
139 != sizeof(request.bytes)) {
140 return MEMCACHED_WRITE_FAILURE;
141 }
142 assert_msg(server->fd != INVALID_SOCKET, "Programmer error, invalid socket");
143
144 memcached_server_response_increment(server);
145
146 char mech[MEMCACHED_MAX_BUFFER] = {0};
147 memcached_return_t rc = memcached_response(server, mech, sizeof(mech) - 1, NULL);
148 if (memcached_failed(rc)) {
149 if (rc == MEMCACHED_PROTOCOL_ERROR) {
150 /* If the server doesn't support SASL it will return PROTOCOL_ERROR.
151 * This error may also be returned for other errors, but let's assume
152 * that the server don't support SASL and treat it as success and
153 * let the client fail with the next operation if the error was
154 * caused by another problem....
155 */
156 rc = MEMCACHED_SUCCESS;
157 }
158
159 return rc;
160 }
161 assert_msg(server->fd != INVALID_SOCKET, "Programmer error, invalid socket");
162
163 /* set ip addresses */
164 char laddr[MEMCACHED_NI_MAXHOST + MEMCACHED_NI_MAXSERV];
165 char raddr[MEMCACHED_NI_MAXHOST + MEMCACHED_NI_MAXSERV];
166
167 if (memcached_failed(rc = resolve_names(*server, laddr, sizeof(laddr), raddr, sizeof(raddr)))) {
168 return rc;
169 }
170
171 int pthread_error;
172 if ((pthread_error = pthread_once(&sasl_startup_once, sasl_startup_function))) {
173 return memcached_set_errno(*server, pthread_error, MEMCACHED_AT);
174 }
175
176 (void) pthread_mutex_lock(&sasl_startup_state_LOCK);
177 if (sasl_startup_state != SASL_OK) {
178 const char *sasl_error_msg = sasl_errstring(sasl_startup_state, NULL, NULL);
179 return memcached_set_error(*server, MEMCACHED_AUTH_PROBLEM, MEMCACHED_AT,
180 memcached_string_make_from_cstr(sasl_error_msg));
181 }
182 (void) pthread_mutex_unlock(&sasl_startup_state_LOCK);
183
184 sasl_conn_t *conn;
185 int ret;
186 if ((ret = sasl_client_new("memcached", server->_hostname, laddr, raddr,
187 server->root->sasl.callbacks, 0, &conn))
188 != SASL_OK)
189 {
190 const char *sasl_error_msg = sasl_errstring(ret, NULL, NULL);
191
192 sasl_dispose(&conn);
193
194 return memcached_set_error(*server, MEMCACHED_AUTH_PROBLEM, MEMCACHED_AT,
195 memcached_string_make_from_cstr(sasl_error_msg));
196 }
197
198 const char *data;
199 const char *chosenmech;
200 unsigned int len;
201 ret = sasl_client_start(conn, mech, NULL, &data, &len, &chosenmech);
202 if (ret != SASL_OK and ret != SASL_CONTINUE) {
203 const char *sasl_error_msg = sasl_errstring(ret, NULL, NULL);
204
205 sasl_dispose(&conn);
206
207 return memcached_set_error(*server, MEMCACHED_AUTH_PROBLEM, MEMCACHED_AT,
208 memcached_string_make_from_cstr(sasl_error_msg));
209 }
210 uint16_t keylen = (uint16_t) strlen(chosenmech);
211 request.message.header.request.opcode = PROTOCOL_BINARY_CMD_SASL_AUTH;
212 request.message.header.request.keylen = htons(keylen);
213 request.message.header.request.bodylen = htonl(len + keylen);
214
215 do {
216 /* send the packet */
217
218 libmemcached_io_vector_st vector[] = {
219 {request.bytes, sizeof(request.bytes)}, {chosenmech, keylen}, {data, len}};
220
221 assert_msg(server->fd != INVALID_SOCKET, "Programmer error, invalid socket");
222 if (memcached_io_writev(server, vector, 3, true) == false) {
223 rc = MEMCACHED_WRITE_FAILURE;
224 break;
225 }
226 assert_msg(server->fd != INVALID_SOCKET, "Programmer error, invalid socket");
227 memcached_server_response_increment(server);
228
229 /* read the response */
230 assert_msg(server->fd != INVALID_SOCKET, "Programmer error, invalid socket");
231 rc = memcached_response(server, NULL, 0, NULL);
232 if (rc != MEMCACHED_AUTH_CONTINUE) {
233 break;
234 }
235 assert_msg(server->fd != INVALID_SOCKET, "Programmer error, invalid socket");
236
237 ret = sasl_client_step(conn, memcached_result_value(&server->root->result),
238 (unsigned int) memcached_result_length(&server->root->result), NULL,
239 &data, &len);
240
241 if (ret != SASL_OK && ret != SASL_CONTINUE) {
242 rc = MEMCACHED_AUTH_PROBLEM;
243 break;
244 }
245
246 request.message.header.request.opcode = PROTOCOL_BINARY_CMD_SASL_STEP;
247 request.message.header.request.bodylen = htonl(len + keylen);
248 } while (true);
249
250 /* Release resources */
251 sasl_dispose(&conn);
252
253 return memcached_set_error(*server, rc, MEMCACHED_AT);
254 }
255
256 static int get_username(void *context, int id, const char **result, unsigned int *len) {
257 if (!context || !result || (id != SASL_CB_USER && id != SASL_CB_AUTHNAME)) {
258 return SASL_BADPARAM;
259 }
260
261 *result = (char *) context;
262 if (len) {
263 *len = (unsigned int) strlen(*result);
264 }
265
266 return SASL_OK;
267 }
268
269 static int get_password(sasl_conn_t *conn, void *context, int id, sasl_secret_t **psecret) {
270 if (!conn || !psecret || id != SASL_CB_PASS) {
271 return SASL_BADPARAM;
272 }
273
274 *psecret = (sasl_secret_t *) context;
275
276 return SASL_OK;
277 }
278
279 memcached_return_t memcached_set_sasl_auth_data(memcached_st *shell, const char *username,
280 const char *password) {
281 Memcached *ptr = memcached2Memcached(shell);
282 if (LIBMEMCACHED_WITH_SASL_SUPPORT == 0) {
283 return MEMCACHED_NOT_SUPPORTED;
284 }
285
286 if (ptr == NULL or username == NULL or password == NULL) {
287 return MEMCACHED_INVALID_ARGUMENTS;
288 }
289
290 memcached_return_t ret;
291 if (memcached_failed(ret = memcached_behavior_set(ptr, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 1))) {
292 return memcached_set_error(
293 *ptr, ret, MEMCACHED_AT,
294 memcached_literal_param("Unable change to binary protocol which is required for SASL."));
295 }
296
297 memcached_destroy_sasl_auth_data(ptr);
298
299 sasl_callback_t *callbacks = libmemcached_xcalloc(ptr, 4, sasl_callback_t);
300 size_t password_length = strlen(password);
301 size_t username_length = strlen(username);
302 char *name = (char *) libmemcached_malloc(ptr, username_length + 1);
303 sasl_secret_t *secret =
304 (sasl_secret_t *) libmemcached_malloc(ptr, password_length + 1 + sizeof(sasl_secret_t));
305
306 if (callbacks == NULL or name == NULL or secret == NULL) {
307 libmemcached_free(ptr, callbacks);
308 libmemcached_free(ptr, name);
309 libmemcached_free(ptr, secret);
310 return memcached_set_error(*ptr, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT);
311 }
312
313 secret->len = password_length;
314 memcpy(secret->data, password, password_length);
315 secret->data[password_length] = 0;
316
317 callbacks[0].id = SASL_CB_USER;
318 callbacks[0].proc = CAST_SASL_CB(get_username);
319 callbacks[0].context = strncpy(name, username, username_length + 1);
320 callbacks[1].id = SASL_CB_AUTHNAME;
321 callbacks[1].proc = CAST_SASL_CB(get_username);
322 callbacks[1].context = name;
323 callbacks[2].id = SASL_CB_PASS;
324 callbacks[2].proc = CAST_SASL_CB(get_password);
325 callbacks[2].context = secret;
326 callbacks[3].id = SASL_CB_LIST_END;
327
328 ptr->sasl.callbacks = callbacks;
329 ptr->sasl.is_allocated = true;
330
331 return MEMCACHED_SUCCESS;
332 }
333
334 memcached_return_t memcached_destroy_sasl_auth_data(memcached_st *shell) {
335 if (LIBMEMCACHED_WITH_SASL_SUPPORT == 0) {
336 return MEMCACHED_NOT_SUPPORTED;
337 }
338
339 Memcached *ptr = memcached2Memcached(shell);
340 if (ptr == NULL) {
341 return MEMCACHED_INVALID_ARGUMENTS;
342 }
343
344 if (ptr->sasl.callbacks == NULL) {
345 return MEMCACHED_SUCCESS;
346 }
347
348 if (ptr->sasl.is_allocated) {
349 libmemcached_free(ptr, ptr->sasl.callbacks[0].context);
350 libmemcached_free(ptr, ptr->sasl.callbacks[2].context);
351 libmemcached_free(ptr, (void *) ptr->sasl.callbacks);
352 ptr->sasl.is_allocated = false;
353 }
354
355 ptr->sasl.callbacks = NULL;
356
357 return MEMCACHED_SUCCESS;
358 }
359
360 memcached_return_t memcached_clone_sasl(memcached_st *clone, const memcached_st *source) {
361 if (LIBMEMCACHED_WITH_SASL_SUPPORT == 0) {
362 return MEMCACHED_NOT_SUPPORTED;
363 }
364
365 if (clone == NULL or source == NULL) {
366 return MEMCACHED_INVALID_ARGUMENTS;
367 }
368
369 if (source->sasl.callbacks == NULL) {
370 return MEMCACHED_SUCCESS;
371 }
372
373 /* Hopefully we are using our own callback mechanisms.. */
374 if (source->sasl.callbacks[0].id == SASL_CB_USER
375 && source->sasl.callbacks[0].proc == CAST_SASL_CB(get_username)
376 && source->sasl.callbacks[1].id == SASL_CB_AUTHNAME
377 && source->sasl.callbacks[1].proc == CAST_SASL_CB(get_username)
378 && source->sasl.callbacks[2].id == SASL_CB_PASS
379 && source->sasl.callbacks[2].proc == CAST_SASL_CB(get_password)
380 && source->sasl.callbacks[3].id == SASL_CB_LIST_END)
381 {
382 sasl_secret_t *secret = (sasl_secret_t *) source->sasl.callbacks[2].context;
383 return memcached_set_sasl_auth_data(clone, (const char *) source->sasl.callbacks[0].context,
384 (const char *) secret->data);
385 }
386
387 /*
388 * But we're not. It may work if we know what the user tries to pass
389 * into the list, but if we don't know the ID we don't know how to handle
390 * the context...
391 */
392 ptrdiff_t total = 0;
393
394 while (source->sasl.callbacks[total].id != SASL_CB_LIST_END) {
395 switch (source->sasl.callbacks[total].id) {
396 case SASL_CB_USER:
397 case SASL_CB_AUTHNAME:
398 case SASL_CB_PASS:
399 break;
400 default:
401 /* I don't know how to deal with this... */
402 return MEMCACHED_NOT_SUPPORTED;
403 }
404
405 ++total;
406 }
407
408 sasl_callback_t *callbacks = libmemcached_xcalloc(clone, total + 1, sasl_callback_t);
409 if (callbacks == NULL) {
410 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
411 }
412 memcpy(callbacks, source->sasl.callbacks, (total + 1) * sizeof(sasl_callback_t));
413
414 /* Now update the context... */
415 for (ptrdiff_t x = 0; x < total; ++x) {
416 if (callbacks[x].id == SASL_CB_USER || callbacks[x].id == SASL_CB_AUTHNAME) {
417 callbacks[x].context = (sasl_callback_t *) libmemcached_malloc(
418 clone, strlen((const char *) source->sasl.callbacks[x].context));
419
420 if (callbacks[x].context == NULL) {
421 /* Failed to allocate memory, clean up previously allocated memory */
422 for (ptrdiff_t y = 0; y < x; ++y) {
423 libmemcached_free(clone, clone->sasl.callbacks[y].context);
424 }
425
426 libmemcached_free(clone, callbacks);
427 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
428 }
429 strncpy((char *) callbacks[x].context, (const char *) source->sasl.callbacks[x].context,
430 sizeof(callbacks[x].context));
431 } else {
432 sasl_secret_t *src = (sasl_secret_t *) source->sasl.callbacks[x].context;
433 sasl_secret_t *n = (sasl_secret_t *) libmemcached_malloc(clone, src->len + 1 + sizeof(*n));
434 if (n == NULL) {
435 /* Failed to allocate memory, clean up previously allocated memory */
436 for (ptrdiff_t y = 0; y < x; ++y) {
437 libmemcached_free(clone, clone->sasl.callbacks[y].context);
438 }
439
440 libmemcached_free(clone, callbacks);
441 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
442 }
443 memcpy(n, src, src->len + 1 + sizeof(*n));
444 callbacks[x].context = n;
445 }
446 }
447
448 clone->sasl.callbacks = callbacks;
449 clone->sasl.is_allocated = true;
450
451 return MEMCACHED_SUCCESS;
452 }
453
454 #else
455
456 void memcached_set_sasl_callbacks(memcached_st *, const sasl_callback_t *) {}
457
458 sasl_callback_t *memcached_get_sasl_callbacks(memcached_st *) {
459 return NULL;
460 }
461
462 memcached_return_t memcached_set_sasl_auth_data(memcached_st *, const char *, const char *) {
463 return MEMCACHED_NOT_SUPPORTED;
464 }
465
466 memcached_return_t memcached_clone_sasl(memcached_st *, const memcached_st *) {
467 return MEMCACHED_NOT_SUPPORTED;
468 }
469
470 memcached_return_t memcached_destroy_sasl_auth_data(memcached_st *) {
471 return MEMCACHED_NOT_SUPPORTED;
472 }
473
474 memcached_return_t memcached_sasl_authenticate_connection(memcached_instance_st *) {
475 return MEMCACHED_NOT_SUPPORTED;
476 }
477
478 #endif