4a84a402a6a21b32d49c6df528922e90106ff1fc
[asterisk/asterisk.git] / res / res_pjsip_authenticator_digest.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Mark Michelson <mmichelson@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 #include "asterisk.h"
20
21 #include <pjsip.h>
22
23 #include "asterisk/res_pjsip.h"
24 #include "asterisk/logger.h"
25 #include "asterisk/module.h"
26 #include "asterisk/strings.h"
27
28 /*** MODULEINFO
29         <depend>pjproject</depend>
30         <depend>res_pjsip</depend>
31         <support_level>core</support_level>
32  ***/
33
34 AO2_GLOBAL_OBJ_STATIC(entity_id);
35
36 /*!
37  * \brief Determine if authentication is required
38  *
39  * Authentication is required if the endpoint has at least one auth
40  * section specified
41  */
42 static int digest_requires_authentication(struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata)
43 {
44         return AST_VECTOR_SIZE(&endpoint->inbound_auths) > 0;
45 }
46
47 static void auth_store_cleanup(void *data)
48 {
49         struct ast_sip_auth **auth = data;
50
51         ao2_cleanup(*auth);
52         ast_free(data);
53 }
54
55 /*!
56  * \brief Thread-local storage for \ref ast_sip_auth
57  *
58  * The PJSIP authentication API is a bit annoying. When you set
59  * up an authentication server, you specify a lookup callback to
60  * call into when verifying incoming credentials. The problem
61  * with this callback is that it only gives you the realm and
62  * authentication username. In 2.0.5, there is a new version of
63  * the callback you can use that gives the pjsip_rx_data in
64  * addition.
65  *
66  * Unfortunately, the data we actually \b need is the
67  * \ref ast_sip_auth we are currently observing. So we have two
68  * choices:
69  * 1) Use the current PJSIP API and use thread-local storage
70  * to temporarily store our SIP authentication information. Then
71  * in the callback, we can retrieve the authentication info and
72  * use as needed. Given our threading model, this is safe.
73  * 2) Use the 2.0.5 API and temporarily store the authentication
74  * information in the rdata's endpoint_info. Then in the callback,
75  * we can retrieve the authentication info from the rdata.
76  *
77  * I've chosen option 1 since it does not require backporting
78  * any APIs from future versions of PJSIP, plus I feel the
79  * thread-local option is a bit cleaner.
80  */
81 AST_THREADSTORAGE_CUSTOM(auth_store, NULL, auth_store_cleanup);
82
83 /*!
84  * \brief Store authentication information in thread-local storage
85  */
86 static int store_auth(struct ast_sip_auth *auth)
87 {
88         struct ast_sip_auth **pointing;
89         pointing = ast_threadstorage_get(&auth_store, sizeof(pointing));
90         if (!pointing || *pointing) {
91                 return -1;
92         }
93
94         ao2_ref(auth, +1);
95         *pointing = auth;
96         return 0;
97 }
98
99 /*!
100  * \brief Remove authentication information from thread-local storage
101  */
102 static int remove_auth(void)
103 {
104         struct ast_sip_auth **pointing;
105         pointing = ast_threadstorage_get(&auth_store, sizeof(pointing));
106         if (!pointing) {
107                 return -1;
108         }
109
110         ao2_cleanup(*pointing);
111         *pointing = NULL;
112         return 0;
113 }
114
115 /*!
116  * \brief Retrieve authentication information from thread-local storage
117  */
118 static struct ast_sip_auth *get_auth(void)
119 {
120         struct ast_sip_auth **auth;
121         auth = ast_threadstorage_get(&auth_store, sizeof(auth));
122         if (auth && *auth) {
123                 ao2_ref(*auth, +1);
124                 return *auth;
125         }
126         return NULL;
127 }
128
129 /*!
130  * \brief Lookup callback for authentication verification
131  *
132  * This function is called when we call pjsip_auth_srv_verify(). It
133  * expects us to verify that the realm and account name from the
134  * Authorization header is correct. We are then supposed to supply
135  * a password or MD5 sum of credentials.
136  *
137  * \param pool A memory pool we can use for allocations
138  * \param realm The realm from the Authorization header
139  * \param acc_name the user from the Authorization header
140  * \param[out] info The credentials we need to fill in
141  * \retval PJ_SUCCESS Successful authentication
142  * \retval other Unsuccessful
143  */
144 static pj_status_t digest_lookup(pj_pool_t *pool, const pj_str_t *realm,
145                 const pj_str_t *acc_name, pjsip_cred_info *info)
146 {
147         RAII_VAR(struct ast_sip_auth *, auth, get_auth(), ao2_cleanup);
148         if (!auth) {
149                 return PJSIP_SC_FORBIDDEN;
150         }
151
152         if (auth->type == AST_SIP_AUTH_TYPE_ARTIFICIAL) {
153                 return PJSIP_SC_FORBIDDEN;
154         }
155
156         if (pj_strcmp2(realm, auth->realm)) {
157                 return PJSIP_SC_FORBIDDEN;
158         }
159         if (pj_strcmp2(acc_name, auth->auth_user)) {
160                 return PJSIP_SC_FORBIDDEN;
161         }
162
163         pj_strdup2(pool, &info->realm, auth->realm);
164         pj_strdup2(pool, &info->username, auth->auth_user);
165
166         switch (auth->type) {
167         case AST_SIP_AUTH_TYPE_USER_PASS:
168                 pj_strdup2(pool, &info->data, auth->auth_pass);
169                 info->data_type = PJSIP_CRED_DATA_PLAIN_PASSWD;
170                 break;
171         case AST_SIP_AUTH_TYPE_MD5:
172                 pj_strdup2(pool, &info->data, auth->md5_creds);
173                 info->data_type = PJSIP_CRED_DATA_DIGEST;
174                 break;
175         default:
176                 return PJSIP_SC_FORBIDDEN;
177         }
178         return PJ_SUCCESS;
179 }
180
181 /*!
182  * \brief Calculate a nonce
183  *
184  * We use this in order to create authentication challenges. We also use this in order
185  * to verify that an incoming request with credentials could be in response to one
186  * of our challenges.
187  *
188  * The nonce is calculated from a timestamp, the source IP address, the source port, a
189  * unique ID for us, and the realm. This helps to ensure that the incoming request
190  * is from the same source that the nonce was calculated for. Including the realm
191  * ensures that multiple challenges to the same request have different nonces.
192  *
193  * \param A UNIX timestamp expressed as a string
194  * \param rdata The incoming request
195  * \param realm The realm for which authentication should occur
196  */
197 static int build_nonce(struct ast_str **nonce, const char *timestamp, const pjsip_rx_data *rdata, const char *realm)
198 {
199         struct ast_str *str = ast_str_alloca(256);
200         RAII_VAR(char *, eid, ao2_global_obj_ref(entity_id), ao2_cleanup);
201         char hash[32];
202
203         ast_str_append(&str, 0, "%s", timestamp);
204         ast_str_append(&str, 0, ":%s", rdata->pkt_info.src_name);
205         ast_str_append(&str, 0, ":%d", rdata->pkt_info.src_port);
206         ast_str_append(&str, 0, ":%s", eid);
207         ast_str_append(&str, 0, ":%s", realm);
208         ast_md5_hash(hash, ast_str_buffer(str));
209
210         ast_str_append(nonce, 0, "%s/%s", timestamp, hash);
211         return 0;
212 }
213
214 /*!
215  * \brief Ensure that a nonce on an incoming request is sane.
216  *
217  * The nonce in an incoming Authorization header needs to pass some scrutiny in order
218  * for us to consider accepting it. What we do is re-build a nonce based on request
219  * data and a realm and see if it matches the nonce they sent us.
220  * \param candidate The nonce on an incoming request
221  * \param rdata The incoming request
222  * \param auth The auth credentials we are trying to match against.
223  * \retval 0 Nonce does not pass validity checks
224  * \retval 1 Nonce passes validity check
225  */
226 static int check_nonce(const char *candidate, const pjsip_rx_data *rdata, const struct ast_sip_auth *auth)
227 {
228         char *copy = ast_strdupa(candidate);
229         char *timestamp = strsep(&copy, "/");
230         int timestamp_int;
231         time_t now = time(NULL);
232         struct ast_str *calculated = ast_str_alloca(64);
233
234         if (!copy) {
235                 /* Clearly a bad nonce! */
236                 return 0;
237         }
238
239         if (sscanf(timestamp, "%30d", &timestamp_int) != 1) {
240                 return 0;
241         }
242
243         if ((int) now - timestamp_int > auth->nonce_lifetime) {
244                 return 0;
245         }
246
247         build_nonce(&calculated, timestamp, rdata, auth->realm);
248         ast_debug(3, "Calculated nonce %s. Actual nonce is %s\n", ast_str_buffer(calculated), candidate);
249         if (strcmp(ast_str_buffer(calculated), candidate)) {
250                 return 0;
251         }
252         return 1;
253 }
254
255 static int find_challenge(const pjsip_rx_data *rdata, const struct ast_sip_auth *auth)
256 {
257         struct pjsip_authorization_hdr *auth_hdr = (pjsip_authorization_hdr *) &rdata->msg_info.msg->hdr;
258         int challenge_found = 0;
259         char nonce[64];
260
261         while ((auth_hdr = (pjsip_authorization_hdr *) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_AUTHORIZATION, auth_hdr->next))) {
262                 ast_copy_pj_str(nonce, &auth_hdr->credential.digest.nonce, sizeof(nonce));
263                 if (check_nonce(nonce, rdata, auth) && !pj_strcmp2(&auth_hdr->credential.digest.realm, auth->realm)) {
264                         challenge_found = 1;
265                         break;
266                 }
267         }
268
269         return challenge_found;
270 }
271
272 /*!
273  * \brief Common code for initializing a pjsip_auth_srv
274  */
275 static void setup_auth_srv(pj_pool_t *pool, pjsip_auth_srv *auth_server, const char *realm)
276 {
277         pj_str_t realm_str;
278         pj_cstr(&realm_str, realm);
279
280         pjsip_auth_srv_init(pool, auth_server, &realm_str, digest_lookup, 0);
281 }
282
283 /*!
284  * \brief Result of digest verification
285  */
286 enum digest_verify_result {
287         /*! Authentication credentials incorrect */
288         AUTH_FAIL,
289         /*! Authentication credentials correct */
290         AUTH_SUCCESS,
291         /*! Authentication credentials correct but nonce mismatch */
292         AUTH_STALE,
293         /*! Authentication credentials were not provided */
294         AUTH_NOAUTH,
295 };
296
297 /*!
298  * \brief astobj2 callback for verifying incoming credentials
299  *
300  * \param auth The ast_sip_auth to check against
301  * \param rdata The incoming request
302  * \param pool A pool to use for the auth server
303  * \return CMP_MATCH on successful authentication
304  * \return 0 on failed authentication
305  */
306 static int verify(struct ast_sip_auth *auth, pjsip_rx_data *rdata, pj_pool_t *pool)
307 {
308         pj_status_t authed;
309         int response_code;
310         pjsip_auth_srv auth_server;
311         int stale = 0;
312
313         if (!find_challenge(rdata, auth)) {
314                 /* Couldn't find a challenge with a sane nonce.
315                  * Nonce mismatch may just be due to staleness.
316                  */
317                 stale = 1;
318         }
319
320         setup_auth_srv(pool, &auth_server, auth->realm);
321
322         store_auth(auth);
323
324         authed = pjsip_auth_srv_verify(&auth_server, rdata, &response_code);
325
326         remove_auth();
327
328         if (authed == PJ_SUCCESS) {
329                 if (stale) {
330                         return AUTH_STALE;
331                 } else {
332                         return AUTH_SUCCESS;
333                 }
334         }
335
336         if (authed == PJSIP_EAUTHNOAUTH) {
337                 return AUTH_NOAUTH;
338         }
339
340         return AUTH_FAIL;
341 }
342
343 /*!
344  * \brief astobj2 callback for adding digest challenges to responses
345  *
346  * \param realm An auth's realm to build a challenge from
347  * \param tdata The response to add the challenge to
348  * \param rdata The request the challenge is in response to
349  * \param is_stale Indicates whether nonce on incoming request was stale
350  */
351 static void challenge(const char *realm, pjsip_tx_data *tdata, const pjsip_rx_data *rdata, int is_stale)
352 {
353         pj_str_t qop;
354         pj_str_t pj_nonce;
355         pjsip_auth_srv auth_server;
356         struct ast_str *nonce = ast_str_alloca(256);
357         char time_buf[32];
358         time_t timestamp = time(NULL);
359         snprintf(time_buf, sizeof(time_buf), "%d", (int) timestamp);
360
361         build_nonce(&nonce, time_buf, rdata, realm);
362
363         setup_auth_srv(tdata->pool, &auth_server, realm);
364
365         pj_cstr(&pj_nonce, ast_str_buffer(nonce));
366         pj_cstr(&qop, "auth");
367         pjsip_auth_srv_challenge(&auth_server, &qop, &pj_nonce, NULL, is_stale ? PJ_TRUE : PJ_FALSE, tdata);
368 }
369
370 /*!
371  * \brief Check authentication using Digest scheme
372  *
373  * This function will check an incoming message against configured authentication
374  * options. If \b any of the incoming Authorization headers result in successful
375  * authentication, then authentication is considered successful.
376  *
377  * \see ast_sip_check_authentication
378  */
379 static enum ast_sip_check_auth_result digest_check_auth(struct ast_sip_endpoint *endpoint,
380                 pjsip_rx_data *rdata, pjsip_tx_data *tdata)
381 {
382         struct ast_sip_auth **auths;
383         enum digest_verify_result *verify_res;
384         enum ast_sip_check_auth_result res;
385         int i;
386         int failures = 0;
387         size_t auth_size;
388
389         RAII_VAR(struct ast_sip_endpoint *, artificial_endpoint,
390                  ast_sip_get_artificial_endpoint(), ao2_cleanup);
391
392         auth_size = AST_VECTOR_SIZE(&endpoint->inbound_auths);
393
394         auths = ast_alloca(auth_size * sizeof(*auths));
395         verify_res = ast_alloca(auth_size * sizeof(*verify_res));
396
397         if (!auths) {
398                 return AST_SIP_AUTHENTICATION_ERROR;
399         }
400
401         if (endpoint == artificial_endpoint) {
402                 auths[0] = ast_sip_get_artificial_auth();
403         } else if (ast_sip_retrieve_auths(&endpoint->inbound_auths, auths)) {
404                 res = AST_SIP_AUTHENTICATION_ERROR;
405                 goto cleanup;
406         }
407
408         for (i = 0; i < auth_size; ++i) {
409                 if (ast_strlen_zero(auths[i]->realm)) {
410                         ast_string_field_set(auths[i], realm, "asterisk");
411                 }
412                 verify_res[i] = verify(auths[i], rdata, tdata->pool);
413                 if (verify_res[i] == AUTH_SUCCESS) {
414                         res = AST_SIP_AUTHENTICATION_SUCCESS;
415                         goto cleanup;
416                 }
417                 if (verify_res[i] == AUTH_FAIL) {
418                         failures++;
419                 }
420         }
421
422         for (i = 0; i < auth_size; ++i) {
423                 challenge(auths[i]->realm, tdata, rdata, verify_res[i] == AUTH_STALE);
424         }
425
426         if (failures == auth_size) {
427                 res = AST_SIP_AUTHENTICATION_FAILED;
428         } else {
429                 res = AST_SIP_AUTHENTICATION_CHALLENGE;
430         }
431
432 cleanup:
433         ast_sip_cleanup_auths(auths, auth_size);
434         return res;
435 }
436
437 static struct ast_sip_authenticator digest_authenticator = {
438         .requires_authentication = digest_requires_authentication,
439         .check_authentication = digest_check_auth,
440 };
441
442 static int build_entity_id(void)
443 {
444         RAII_VAR(struct ast_uuid *, uu, ast_uuid_generate(), ast_free_ptr);
445         RAII_VAR(char *, eid, ao2_alloc(AST_UUID_STR_LEN, NULL), ao2_cleanup);
446
447         if (!uu || !eid) {
448                 return -1;
449         }
450
451         ast_uuid_to_str(uu, eid, AST_UUID_STR_LEN);
452         ao2_global_obj_replace_unref(entity_id, eid);
453         return 0;
454 }
455
456 static int reload_module(void)
457 {
458         if (build_entity_id()) {
459                 return -1;
460         }
461         return 0;
462 }
463
464 static int load_module(void)
465 {
466         if (build_entity_id()) {
467                 return AST_MODULE_LOAD_DECLINE;
468         }
469         if (ast_sip_register_authenticator(&digest_authenticator)) {
470                 ao2_global_obj_release(entity_id);
471                 return AST_MODULE_LOAD_DECLINE;
472         }
473         return AST_MODULE_LOAD_SUCCESS;
474 }
475
476 static int unload_module(void)
477 {
478         ast_sip_unregister_authenticator(&digest_authenticator);
479         ao2_global_obj_release(entity_id);
480         return 0;
481 }
482
483 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP authentication resource",
484                 .load = load_module,
485                 .unload = unload_module,
486                 .reload = reload_module,
487                 .load_pri = AST_MODPRI_CHANNEL_DEPEND,
488 );