2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2013, Digium, Inc.
6 * Mark Michelson <mmichelson@digium.com>
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.
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.
23 #include "asterisk/res_pjsip.h"
24 #include "asterisk/logger.h"
25 #include "asterisk/module.h"
26 #include "asterisk/strings.h"
29 <depend>pjproject</depend>
30 <depend>res_pjsip</depend>
31 <support_level>core</support_level>
34 AO2_GLOBAL_OBJ_STATIC(entity_id);
37 * \brief Determine if authentication is required
39 * Authentication is required if the endpoint has at least one auth
42 static int digest_requires_authentication(struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata)
44 return AST_VECTOR_SIZE(&endpoint->inbound_auths) > 0;
47 static void auth_store_cleanup(void *data)
49 struct ast_sip_auth **auth = data;
56 * \brief Thread-local storage for \ref ast_sip_auth
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
66 * Unfortunately, the data we actually \b need is the
67 * \ref ast_sip_auth we are currently observing. So we have two
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.
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.
81 AST_THREADSTORAGE_CUSTOM(auth_store, NULL, auth_store_cleanup);
84 * \brief Store authentication information in thread-local storage
86 static int store_auth(struct ast_sip_auth *auth)
88 struct ast_sip_auth **pointing;
89 pointing = ast_threadstorage_get(&auth_store, sizeof(pointing));
90 if (!pointing || *pointing) {
100 * \brief Remove authentication information from thread-local storage
102 static int remove_auth(void)
104 struct ast_sip_auth **pointing;
105 pointing = ast_threadstorage_get(&auth_store, sizeof(pointing));
110 ao2_cleanup(*pointing);
116 * \brief Retrieve authentication information from thread-local storage
118 static struct ast_sip_auth *get_auth(void)
120 struct ast_sip_auth **auth;
121 auth = ast_threadstorage_get(&auth_store, sizeof(auth));
130 * \brief Lookup callback for authentication verification
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.
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
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)
147 RAII_VAR(struct ast_sip_auth *, auth, get_auth(), ao2_cleanup);
149 return PJSIP_SC_FORBIDDEN;
152 if (auth->type == AST_SIP_AUTH_TYPE_ARTIFICIAL) {
153 return PJSIP_SC_FORBIDDEN;
156 if (pj_strcmp2(realm, auth->realm)) {
157 return PJSIP_SC_FORBIDDEN;
159 if (pj_strcmp2(acc_name, auth->auth_user)) {
160 return PJSIP_SC_FORBIDDEN;
163 pj_strdup2(pool, &info->realm, auth->realm);
164 pj_strdup2(pool, &info->username, auth->auth_user);
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;
171 case AST_SIP_AUTH_TYPE_MD5:
172 pj_strdup2(pool, &info->data, auth->md5_creds);
173 info->data_type = PJSIP_CRED_DATA_DIGEST;
176 return PJSIP_SC_FORBIDDEN;
182 * \brief Calculate a nonce
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
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.
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
197 static int build_nonce(struct ast_str **nonce, const char *timestamp, const pjsip_rx_data *rdata, const char *realm)
199 struct ast_str *str = ast_str_alloca(256);
200 RAII_VAR(char *, eid, ao2_global_obj_ref(entity_id), ao2_cleanup);
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));
210 ast_str_append(nonce, 0, "%s/%s", timestamp, hash);
215 * \brief Ensure that a nonce on an incoming request is sane.
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
226 static int check_nonce(const char *candidate, const pjsip_rx_data *rdata, const struct ast_sip_auth *auth)
228 char *copy = ast_strdupa(candidate);
229 char *timestamp = strsep(©, "/");
231 time_t now = time(NULL);
232 struct ast_str *calculated = ast_str_alloca(64);
235 /* Clearly a bad nonce! */
239 if (sscanf(timestamp, "%30d", ×tamp_int) != 1) {
243 if ((int) now - timestamp_int > auth->nonce_lifetime) {
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)) {
255 static int find_challenge(const pjsip_rx_data *rdata, const struct ast_sip_auth *auth)
257 struct pjsip_authorization_hdr *auth_hdr = (pjsip_authorization_hdr *) &rdata->msg_info.msg->hdr;
258 int challenge_found = 0;
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)) {
269 return challenge_found;
273 * \brief Common code for initializing a pjsip_auth_srv
275 static void setup_auth_srv(pj_pool_t *pool, pjsip_auth_srv *auth_server, const char *realm)
278 pj_cstr(&realm_str, realm);
280 pjsip_auth_srv_init(pool, auth_server, &realm_str, digest_lookup, 0);
284 * \brief Result of digest verification
286 enum digest_verify_result {
287 /*! Authentication credentials incorrect */
289 /*! Authentication credentials correct */
291 /*! Authentication credentials correct but nonce mismatch */
293 /*! Authentication credentials were not provided */
298 * \brief astobj2 callback for verifying incoming credentials
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
306 static int verify(struct ast_sip_auth *auth, pjsip_rx_data *rdata, pj_pool_t *pool)
310 pjsip_auth_srv auth_server;
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.
320 setup_auth_srv(pool, &auth_server, auth->realm);
324 authed = pjsip_auth_srv_verify(&auth_server, rdata, &response_code);
328 if (authed == PJ_SUCCESS) {
336 if (authed == PJSIP_EAUTHNOAUTH) {
344 * \brief astobj2 callback for adding digest challenges to responses
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
351 static void challenge(const char *realm, pjsip_tx_data *tdata, const pjsip_rx_data *rdata, int is_stale)
355 pjsip_auth_srv auth_server;
356 struct ast_str *nonce = ast_str_alloca(256);
358 time_t timestamp = time(NULL);
359 snprintf(time_buf, sizeof(time_buf), "%d", (int) timestamp);
361 build_nonce(&nonce, time_buf, rdata, realm);
363 setup_auth_srv(tdata->pool, &auth_server, realm);
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);
371 * \brief Check authentication using Digest scheme
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.
377 * \see ast_sip_check_authentication
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)
382 struct ast_sip_auth **auths;
383 enum digest_verify_result *verify_res;
384 enum ast_sip_check_auth_result res;
389 RAII_VAR(struct ast_sip_endpoint *, artificial_endpoint,
390 ast_sip_get_artificial_endpoint(), ao2_cleanup);
392 auth_size = AST_VECTOR_SIZE(&endpoint->inbound_auths);
394 auths = ast_alloca(auth_size * sizeof(*auths));
395 verify_res = ast_alloca(auth_size * sizeof(*verify_res));
398 return AST_SIP_AUTHENTICATION_ERROR;
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;
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");
412 verify_res[i] = verify(auths[i], rdata, tdata->pool);
413 if (verify_res[i] == AUTH_SUCCESS) {
414 res = AST_SIP_AUTHENTICATION_SUCCESS;
417 if (verify_res[i] == AUTH_FAIL) {
422 for (i = 0; i < auth_size; ++i) {
423 challenge(auths[i]->realm, tdata, rdata, verify_res[i] == AUTH_STALE);
426 if (failures == auth_size) {
427 res = AST_SIP_AUTHENTICATION_FAILED;
429 res = AST_SIP_AUTHENTICATION_CHALLENGE;
433 ast_sip_cleanup_auths(auths, auth_size);
437 static struct ast_sip_authenticator digest_authenticator = {
438 .requires_authentication = digest_requires_authentication,
439 .check_authentication = digest_check_auth,
442 static int build_entity_id(void)
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);
451 ast_uuid_to_str(uu, eid, AST_UUID_STR_LEN);
452 ao2_global_obj_replace_unref(entity_id, eid);
456 static int reload_module(void)
458 if (build_entity_id()) {
464 static int load_module(void)
466 if (build_entity_id()) {
467 return AST_MODULE_LOAD_DECLINE;
469 if (ast_sip_register_authenticator(&digest_authenticator)) {
470 ao2_global_obj_release(entity_id);
471 return AST_MODULE_LOAD_DECLINE;
473 return AST_MODULE_LOAD_SUCCESS;
476 static int unload_module(void)
478 ast_sip_unregister_authenticator(&digest_authenticator);
479 ao2_global_obj_release(entity_id);
483 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP authentication resource",
485 .unload = unload_module,
486 .reload = reload_module,
487 .load_pri = AST_MODPRI_CHANNEL_DEPEND,