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