603c5864091a27b143f1d3c1e03b8c214ecc8129
[m6w6/libmemcached] / libmemcached / sasl.cc
1 /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
2 *
3 * Libmemcached library
4 *
5 * Copyright (C) 2011 Data Differential, http://datadifferential.com/
6 * Copyright (C) 2006-2009 Brian Aker All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
10 * met:
11 *
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * * Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following disclaimer
17 * in the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * * The names of its contributors may not be used to endorse or
21 * promote products derived from this software without specific prior
22 * written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 *
36 */
37
38 #include <libmemcached/common.h>
39 #include <cassert>
40
41 #if defined(LIBMEMCACHED_WITH_SASL_SUPPORT) && LIBMEMCACHED_WITH_SASL_SUPPORT
42
43 #if defined(HAVE_LIBSASL) && HAVE_LIBSASL
44 #include <sasl/sasl.h>
45 #endif
46
47 #include <pthread.h>
48
49 void memcached_set_sasl_callbacks(memcached_st *ptr,
50 const sasl_callback_t *callbacks)
51 {
52 ptr->sasl.callbacks= const_cast<sasl_callback_t *>(callbacks);
53 ptr->sasl.is_allocated= false;
54 }
55
56 sasl_callback_t *memcached_get_sasl_callbacks(memcached_st *ptr)
57 {
58 return ptr->sasl.callbacks;
59 }
60
61 /**
62 * Resolve the names for both ends of a connection
63 * @param fd socket to check
64 * @param laddr local address (out)
65 * @param raddr remote address (out)
66 * @return true on success false otherwise (errno contains more info)
67 */
68 static memcached_return_t resolve_names(memcached_server_st& server, char *laddr, size_t laddr_length, char *raddr, size_t raddr_length)
69 {
70 char host[NI_MAXHOST];
71 char port[NI_MAXSERV];
72 struct sockaddr_storage saddr;
73 socklen_t salen= sizeof(saddr);
74
75 if (getsockname(server.fd, (struct sockaddr *)&saddr, &salen) < 0)
76 {
77 return memcached_set_errno(server, MEMCACHED_ERRNO, MEMCACHED_AT);
78 }
79
80 if (getnameinfo((struct sockaddr *)&saddr, salen, host, sizeof(host), port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV) < 0)
81 {
82 return MEMCACHED_HOST_LOOKUP_FAILURE;
83 }
84
85 (void)snprintf(laddr, laddr_length, "%s;%s", host, port);
86 salen= sizeof(saddr);
87
88 if (getpeername(server.fd, (struct sockaddr *)&saddr, &salen) < 0)
89 {
90 return memcached_set_errno(server, MEMCACHED_ERRNO, MEMCACHED_AT);
91 }
92
93 if (getnameinfo((struct sockaddr *)&saddr, salen, host, sizeof(host),
94 port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV) < 0)
95 {
96 return memcached_set_error(server, MEMCACHED_HOST_LOOKUP_FAILURE, MEMCACHED_AT);
97 }
98
99 (void)snprintf(raddr, raddr_length, "%s;%s", host, port);
100
101 return MEMCACHED_SUCCESS;
102 }
103
104 extern "C" {
105
106 static void sasl_shutdown_function()
107 {
108 sasl_done();
109 }
110
111 static volatile int sasl_startup_state= SASL_OK;
112 pthread_mutex_t sasl_startup_state_LOCK= PTHREAD_MUTEX_INITIALIZER;
113 static pthread_once_t sasl_startup_once= PTHREAD_ONCE_INIT;
114 static void sasl_startup_function(void)
115 {
116 sasl_startup_state= sasl_client_init(NULL);
117
118 if (sasl_startup_state == SASL_OK)
119 {
120 (void)atexit(sasl_shutdown_function);
121 }
122 }
123
124 } // extern "C"
125
126 memcached_return_t memcached_sasl_authenticate_connection(memcached_server_st *server)
127 {
128 if (LIBMEMCACHED_WITH_SASL_SUPPORT == 0)
129 {
130 return MEMCACHED_NOT_SUPPORTED;
131 }
132
133 if (server == NULL)
134 {
135 return MEMCACHED_INVALID_ARGUMENTS;
136 }
137
138 /* SANITY CHECK: SASL can only be used with the binary protocol */
139 if (memcached_is_binary(server->root) == false)
140 {
141 return memcached_set_error(*server, MEMCACHED_INVALID_ARGUMENTS, MEMCACHED_AT,
142 memcached_literal_param("memcached_sasl_authenticate_connection() is not supported via the ASCII protocol"));
143 }
144
145 /* Try to get the supported mech from the server. Servers without SASL
146 * support will return UNKNOWN COMMAND, so we can just treat that
147 * as authenticated
148 */
149 protocol_binary_request_no_extras request= { };
150
151 initialize_binary_request(ptr, request.message.header);
152
153 request.message.header.request.opcode= PROTOCOL_BINARY_CMD_SASL_LIST_MECHS;
154
155 if (memcached_io_write(server, request.bytes,
156 sizeof(request.bytes), 1) != sizeof(request.bytes))
157 {
158 return MEMCACHED_WRITE_FAILURE;
159 }
160
161 memcached_server_response_increment(server);
162
163 char mech[MEMCACHED_MAX_BUFFER];
164 memcached_return_t rc= memcached_response(server, mech, sizeof(mech), NULL);
165 if (memcached_failed(rc))
166 {
167 if (rc == MEMCACHED_PROTOCOL_ERROR)
168 {
169 /* If the server doesn't support SASL it will return PROTOCOL_ERROR.
170 * This error may also be returned for other errors, but let's assume
171 * that the server don't support SASL and treat it as success and
172 * let the client fail with the next operation if the error was
173 * caused by another problem....
174 */
175 rc= MEMCACHED_SUCCESS;
176 }
177
178 return rc;
179 }
180
181 /* set ip addresses */
182 char laddr[NI_MAXHOST + NI_MAXSERV];
183 char raddr[NI_MAXHOST + NI_MAXSERV];
184
185 if (memcached_failed(rc= resolve_names(*server, laddr, sizeof(laddr), raddr, sizeof(raddr))))
186 {
187 return rc;
188 }
189
190 int pthread_error;
191 if ((pthread_error= pthread_once(&sasl_startup_once, sasl_startup_function)) != 0)
192 {
193 return memcached_set_errno(*server, pthread_error, MEMCACHED_AT);
194 }
195
196 (void)pthread_mutex_lock(&sasl_startup_state_LOCK);
197 if (sasl_startup_state != SASL_OK)
198 {
199 const char *sasl_error_msg= sasl_errstring(sasl_startup_state, NULL, NULL);
200 return memcached_set_error(*server, MEMCACHED_AUTH_PROBLEM, MEMCACHED_AT,
201 memcached_string_make_from_cstr(sasl_error_msg));
202 }
203 (void)pthread_mutex_unlock(&sasl_startup_state_LOCK);
204
205 sasl_conn_t *conn;
206 int ret;
207 if ((ret= sasl_client_new("memcached", server->hostname, laddr, raddr, server->root->sasl.callbacks, 0, &conn) ) != SASL_OK)
208 {
209 const char *sasl_error_msg= sasl_errstring(ret, NULL, NULL);
210
211 sasl_dispose(&conn);
212
213 return memcached_set_error(*server, MEMCACHED_AUTH_PROBLEM, MEMCACHED_AT,
214 memcached_string_make_from_cstr(sasl_error_msg));
215 }
216
217 const char *data;
218 const char *chosenmech;
219 unsigned int len;
220 ret= sasl_client_start(conn, mech, NULL, &data, &len, &chosenmech);
221 if (ret != SASL_OK and ret != SASL_CONTINUE)
222 {
223 const char *sasl_error_msg= sasl_errstring(ret, NULL, NULL);
224
225 sasl_dispose(&conn);
226
227 return memcached_set_error(*server, MEMCACHED_AUTH_PROBLEM, MEMCACHED_AT,
228 memcached_string_make_from_cstr(sasl_error_msg));
229 }
230 uint16_t keylen= (uint16_t)strlen(chosenmech);
231 request.message.header.request.opcode= PROTOCOL_BINARY_CMD_SASL_AUTH;
232 request.message.header.request.keylen= htons(keylen);
233 request.message.header.request.bodylen= htonl(len + keylen);
234
235 do {
236 /* send the packet */
237
238 libmemcached_io_vector_st vector[]=
239 {
240 { request.bytes, sizeof(request.bytes) },
241 { chosenmech, keylen },
242 { data, len }
243 };
244
245 if (memcached_io_writev(server, vector, 3, true) == false)
246 {
247 rc= MEMCACHED_WRITE_FAILURE;
248 break;
249 }
250 memcached_server_response_increment(server);
251
252 /* read the response */
253 rc= memcached_response(server, NULL, 0, NULL);
254 if (rc != MEMCACHED_AUTH_CONTINUE)
255 {
256 break;
257 }
258
259 ret= sasl_client_step(conn, memcached_result_value(&server->root->result),
260 (unsigned int)memcached_result_length(&server->root->result),
261 NULL, &data, &len);
262
263 if (ret != SASL_OK && ret != SASL_CONTINUE)
264 {
265 rc= MEMCACHED_AUTH_PROBLEM;
266 break;
267 }
268
269 request.message.header.request.opcode= PROTOCOL_BINARY_CMD_SASL_STEP;
270 request.message.header.request.bodylen= htonl(len + keylen);
271 } while (true);
272
273 /* Release resources */
274 sasl_dispose(&conn);
275
276 return memcached_set_error(*server, rc, MEMCACHED_AT);
277 }
278
279 static int get_username(void *context, int id, const char **result, unsigned int *len)
280 {
281 if (!context || !result || (id != SASL_CB_USER && id != SASL_CB_AUTHNAME))
282 {
283 return SASL_BADPARAM;
284 }
285
286 *result= (char *)context;
287 if (len)
288 {
289 *len= (unsigned int)strlen(*result);
290 }
291
292 return SASL_OK;
293 }
294
295 static int get_password(sasl_conn_t *conn, void *context, int id,
296 sasl_secret_t **psecret)
297 {
298 if (!conn || ! psecret || id != SASL_CB_PASS)
299 {
300 return SASL_BADPARAM;
301 }
302
303 *psecret= (sasl_secret_t *)context;
304
305 return SASL_OK;
306 }
307
308 memcached_return_t memcached_set_sasl_auth_data(memcached_st *ptr,
309 const char *username,
310 const char *password)
311 {
312 if (LIBMEMCACHED_WITH_SASL_SUPPORT == 0)
313 {
314 return MEMCACHED_NOT_SUPPORTED;
315 }
316
317 if (ptr == NULL or username == NULL or password == NULL)
318 {
319 return MEMCACHED_INVALID_ARGUMENTS;
320 }
321
322 memcached_return_t ret;
323 if (memcached_failed(ret= memcached_behavior_set(ptr, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 1)))
324 {
325 return memcached_set_error(*ptr, ret, MEMCACHED_AT, memcached_literal_param("Unable change to binary protocol which is required for SASL."));
326 }
327
328 memcached_destroy_sasl_auth_data(ptr);
329
330 sasl_callback_t *callbacks= libmemcached_xcalloc(ptr, 4, sasl_callback_t);
331 size_t password_length= strlen(password);
332 size_t username_length= strlen(username);
333 char *name= (char *)libmemcached_malloc(ptr, username_length +1);
334 sasl_secret_t *secret= (sasl_secret_t*)libmemcached_malloc(ptr, password_length +1 + sizeof(sasl_secret_t));
335
336 if (callbacks == NULL or name == NULL or secret == NULL)
337 {
338 libmemcached_free(ptr, callbacks);
339 libmemcached_free(ptr, name);
340 libmemcached_free(ptr, secret);
341 return memcached_set_error(*ptr, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT);
342 }
343
344 secret->len= password_length;
345 memcpy(secret->data, password, password_length);
346 secret->data[password_length]= 0;
347
348 callbacks[0].id= SASL_CB_USER;
349 callbacks[0].proc= (int (*)())get_username;
350 callbacks[0].context= strncpy(name, username, username_length +1);
351 callbacks[1].id= SASL_CB_AUTHNAME;
352 callbacks[1].proc= (int (*)())get_username;
353 callbacks[1].context= name;
354 callbacks[2].id= SASL_CB_PASS;
355 callbacks[2].proc= (int (*)())get_password;
356 callbacks[2].context= secret;
357 callbacks[3].id= SASL_CB_LIST_END;
358
359 ptr->sasl.callbacks= callbacks;
360 ptr->sasl.is_allocated= true;
361
362 return MEMCACHED_SUCCESS;
363 }
364
365 memcached_return_t memcached_destroy_sasl_auth_data(memcached_st *ptr)
366 {
367 if (LIBMEMCACHED_WITH_SASL_SUPPORT == 0)
368 {
369 return MEMCACHED_NOT_SUPPORTED;
370 }
371
372 if (ptr == NULL)
373 {
374 return MEMCACHED_INVALID_ARGUMENTS;
375 }
376
377 if (ptr->sasl.callbacks == NULL)
378 {
379 return MEMCACHED_SUCCESS;
380 }
381
382 if (ptr->sasl.is_allocated)
383 {
384 libmemcached_free(ptr, ptr->sasl.callbacks[0].context);
385 libmemcached_free(ptr, ptr->sasl.callbacks[2].context);
386 libmemcached_free(ptr, (void*)ptr->sasl.callbacks);
387 ptr->sasl.is_allocated= false;
388 }
389
390 ptr->sasl.callbacks= NULL;
391
392 return MEMCACHED_SUCCESS;
393 }
394
395 memcached_return_t memcached_clone_sasl(memcached_st *clone, const memcached_st *source)
396 {
397 if (LIBMEMCACHED_WITH_SASL_SUPPORT == 0)
398 {
399 return MEMCACHED_NOT_SUPPORTED;
400 }
401
402 if (clone == NULL or source == NULL)
403 {
404 return MEMCACHED_INVALID_ARGUMENTS;
405 }
406
407 if (source->sasl.callbacks == NULL)
408 {
409 return MEMCACHED_SUCCESS;
410 }
411
412 /* Hopefully we are using our own callback mechanisms.. */
413 if (source->sasl.callbacks[0].id == SASL_CB_USER &&
414 source->sasl.callbacks[0].proc == (int (*)())get_username &&
415 source->sasl.callbacks[1].id == SASL_CB_AUTHNAME &&
416 source->sasl.callbacks[1].proc == (int (*)())get_username &&
417 source->sasl.callbacks[2].id == SASL_CB_PASS &&
418 source->sasl.callbacks[2].proc == (int (*)())get_password &&
419 source->sasl.callbacks[3].id == SASL_CB_LIST_END)
420 {
421 sasl_secret_t *secret= (sasl_secret_t *)source->sasl.callbacks[2].context;
422 return memcached_set_sasl_auth_data(clone,
423 (const char*)source->sasl.callbacks[0].context,
424 (const char*)secret->data);
425 }
426
427 /*
428 * But we're not. It may work if we know what the user tries to pass
429 * into the list, but if we don't know the ID we don't know how to handle
430 * the context...
431 */
432 ptrdiff_t total= 0;
433
434 while (source->sasl.callbacks[total].id != SASL_CB_LIST_END)
435 {
436 switch (source->sasl.callbacks[total].id)
437 {
438 case SASL_CB_USER:
439 case SASL_CB_AUTHNAME:
440 case SASL_CB_PASS:
441 break;
442 default:
443 /* I don't know how to deal with this... */
444 return MEMCACHED_NOT_SUPPORTED;
445 }
446
447 ++total;
448 }
449
450 sasl_callback_t *callbacks= libmemcached_xcalloc(clone, total +1, sasl_callback_t);
451 if (callbacks == NULL)
452 {
453 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
454 }
455 memcpy(callbacks, source->sasl.callbacks, (total + 1) * sizeof(sasl_callback_t));
456
457 /* Now update the context... */
458 for (ptrdiff_t x= 0; x < total; ++x)
459 {
460 if (callbacks[x].id == SASL_CB_USER || callbacks[x].id == SASL_CB_AUTHNAME)
461 {
462 callbacks[x].context= (sasl_callback_t*)libmemcached_malloc(clone, strlen((const char*)source->sasl.callbacks[x].context));
463
464 if (callbacks[x].context == NULL)
465 {
466 /* Failed to allocate memory, clean up previously allocated memory */
467 for (ptrdiff_t y= 0; y < x; ++y)
468 {
469 libmemcached_free(clone, clone->sasl.callbacks[y].context);
470 }
471
472 libmemcached_free(clone, callbacks);
473 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
474 }
475 strncpy((char*)callbacks[x].context, (const char*)source->sasl.callbacks[x].context, sizeof(callbacks[x].context));
476 }
477 else
478 {
479 sasl_secret_t *src= (sasl_secret_t *)source->sasl.callbacks[x].context;
480 sasl_secret_t *n= (sasl_secret_t*)libmemcached_malloc(clone, src->len + 1 + sizeof(*n));
481 if (n == NULL)
482 {
483 /* Failed to allocate memory, clean up previously allocated memory */
484 for (ptrdiff_t y= 0; y < x; ++y)
485 {
486 libmemcached_free(clone, clone->sasl.callbacks[y].context);
487 }
488
489 libmemcached_free(clone, callbacks);
490 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
491 }
492 memcpy(n, src, src->len + 1 + sizeof(*n));
493 callbacks[x].context= n;
494 }
495 }
496
497 clone->sasl.callbacks= callbacks;
498 clone->sasl.is_allocated= true;
499
500 return MEMCACHED_SUCCESS;
501 }
502
503 #else
504
505 void memcached_set_sasl_callbacks(memcached_st *, const sasl_callback_t *)
506 {
507 }
508
509 sasl_callback_t *memcached_get_sasl_callbacks(memcached_st *)
510 {
511 return NULL;
512 }
513
514 memcached_return_t memcached_set_sasl_auth_data(memcached_st *, const char *, const char *)
515 {
516 return MEMCACHED_NOT_SUPPORTED;
517 }
518
519 memcached_return_t memcached_clone_sasl(memcached_st *, const memcached_st *)
520 {
521 return MEMCACHED_NOT_SUPPORTED;
522 }
523
524 #endif