auth_module.c 38.4 KB
Newer Older
Pekka Pessi's avatar
Pekka Pessi committed
1 2 3 4 5 6 7
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2005 Nokia Corporation.
 *
 * Contact: Pekka Pessi <pekka.pessi@nokia.com>
 *
8
 * This library is free software; you can redistribute it and/or
Pekka Pessi's avatar
Pekka Pessi committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

/**@CFILE auth_module.c
 * @brief Authentication verification module
 *
 * The authentication module provides server or proxy-side authentication
 * verification for network elements like registrars, presence servers, and
 * proxies.
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>.
 *
 * @date Created: Wed Apr 11 15:14:03 2001 ppessi
 */

#include "config.h"

#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

49
#include <sofia-sip/auth_digest.h>
50

Pekka Pessi's avatar
Pekka Pessi committed
51 52 53 54 55 56 57 58 59
#include "iptsec_debug.h"

#if HAVE_FUNC
#elif HAVE_FUNCTION
#define __func__ __FUNCTION__
#else
static char const __func__[] = "auth_mod";
#endif

60
#include <sofia-sip/su_debug.h>
Pekka Pessi's avatar
Pekka Pessi committed
61

62 63 64
#include <sofia-sip/su_wait.h>
#include <sofia-sip/su_alloc.h>
#include <sofia-sip/su_tagarg.h>
Pekka Pessi's avatar
Pekka Pessi committed
65

66 67
#include <sofia-sip/base64.h>
#include <sofia-sip/su_md5.h>
Pekka Pessi's avatar
Pekka Pessi committed
68

69 70
#include <sofia-sip/msg_parser.h>
#include <sofia-sip/msg_date.h>
Pekka Pessi's avatar
Pekka Pessi committed
71

72 73
#include "sofia-sip/auth_module.h"
#include "sofia-sip/auth_plugin.h"
Pekka Pessi's avatar
Pekka Pessi committed
74 75 76 77 78

#define APW_HASH(apw) ((apw)->apw_index)

char const auth_internal_server_error[] = "Internal server error";

79
static void auth_call_scheme_destructor(void *);
Pekka Pessi's avatar
Pekka Pessi committed
80 81
static void auth_md5_hmac_key(auth_mod_t *am);

82 83 84
HTABLE_PROTOS_WITH(auth_htable, aht, auth_passwd_t, usize_t, unsigned);
HTABLE_BODIES_WITH(auth_htable, aht, auth_passwd_t, APW_HASH, 
		   usize_t, unsigned);
Pekka Pessi's avatar
Pekka Pessi committed
85

86
/**Allocate an authentication module instance.
Pekka Pessi's avatar
Pekka Pessi committed
87 88
 *
 * The function auth_mod_alloc() allocates an authentication module object.
89
 *
Pekka Pessi's avatar
Pekka Pessi committed
90
 */
91
auth_mod_t *auth_mod_alloc(auth_scheme_t *scheme,
Pekka Pessi's avatar
Pekka Pessi committed
92 93 94 95
			   tag_type_t tag, tag_value_t value, ...)
{
  auth_mod_t *am = NULL;

96
  if ((am = su_home_new(scheme->asch_size))) {
Pekka Pessi's avatar
Pekka Pessi committed
97
    am->am_scheme = scheme;
98
    su_home_destructor(am->am_home, auth_call_scheme_destructor);
Pekka Pessi's avatar
Pekka Pessi committed
99 100 101 102 103
  }

  return am;
}

104
/**Initialize an authentication module instance.
Pekka Pessi's avatar
Pekka Pessi committed
105 106 107
 *
 * The function auth_mod_init_default() initializes an authentication module
 * object used to authenticate the requests.
108
 *
Pekka Pessi's avatar
Pekka Pessi committed
109 110 111 112 113 114
 * @param am
 * @param base
 * @param root
 * @param tag,value,... tagged argument list
 *
 * @TAGS
115 116 117 118 119 120 121 122
 * AUTHTAG_REALM(), AUTHTAG_OPAQUE(), AUTHTAG_DB(), AUTHTAG_QOP(),
 * AUTHTAG_ALGORITHM(), AUTHTAG_EXPIRES(), AUTHTAG_NEXT_EXPIRES(),
 * AUTHTAG_BLACKLIST(), AUTHTAG_FORBIDDEN(), AUTHTAG_ANONYMOUS(),
 * AUTHTAG_FAKE(), AUTHTAG_ALLOW(), AUTHTAG_REMOTE(), and
 * AUTHTAG_MASTER_KEY().
 *
 * @return 0 if successful
 * @return -1 upon an error
Pekka Pessi's avatar
Pekka Pessi committed
123 124 125 126 127 128
 */
int auth_init_default(auth_mod_t *am,
		      auth_scheme_t *base,
		      su_root_t *root,
		      tag_type_t tag, tag_value_t value, ...)
{
129
  int retval = 0;
Pekka Pessi's avatar
Pekka Pessi committed
130 131 132 133 134 135

  ta_list ta;

  char const *realm = NULL, *opaque = NULL, *db = NULL, *allows = NULL;
  char const *qop = NULL, *algorithm = NULL;
  unsigned expires = 60 * 60, next_expires = 5 * 60;
136
  unsigned max_ncount = 0;
Pekka Pessi's avatar
Pekka Pessi committed
137 138 139 140 141 142 143
  unsigned blacklist = 5;
  int forbidden = 0;
  int anonymous = 0;
  int fake = 0;
  url_string_t const *remote = NULL;
  char const *master_key = "fish";
  char *s;
144

Pekka Pessi's avatar
Pekka Pessi committed
145 146 147 148 149 150 151 152 153 154 155
  ta_start(ta, tag, value);

  /* Authentication stuff */
  tl_gets(ta_args(ta),
	  AUTHTAG_REALM_REF(realm),
	  AUTHTAG_OPAQUE_REF(opaque),
	  AUTHTAG_DB_REF(db),
	  AUTHTAG_QOP_REF(qop),
	  AUTHTAG_ALGORITHM_REF(algorithm),
	  AUTHTAG_EXPIRES_REF(expires),
	  AUTHTAG_NEXT_EXPIRES_REF(next_expires),
156
	  AUTHTAG_MAX_NCOUNT_REF(max_ncount),
Pekka Pessi's avatar
Pekka Pessi committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
	  AUTHTAG_BLACKLIST_REF(blacklist),
	  AUTHTAG_FORBIDDEN_REF(forbidden),
	  AUTHTAG_ANONYMOUS_REF(anonymous),
	  AUTHTAG_FAKE_REF(fake),
	  AUTHTAG_ALLOW_REF(allows),
	  AUTHTAG_REMOTE_REF(remote),
	  AUTHTAG_MASTER_KEY_REF(master_key),
	  TAG_NULL());

  if (!realm) realm = "*";
  if (!allows) allows = "ACK, BYE, CANCEL";

  am->am_realm = su_strdup(am->am_home, realm);
  am->am_opaque = su_strdup(am->am_home, opaque);
  am->am_db = su_strdup(am->am_home, db);
  s = su_strdup(am->am_home, allows);
173
  if (s)
Pekka Pessi's avatar
Pekka Pessi committed
174 175 176
    msg_commalist_d(am->am_home, &s, &am->am_allow, NULL);
  am->am_expires = expires;
  am->am_next_exp = next_expires;
177
  am->am_max_ncount = max_ncount;
Pekka Pessi's avatar
Pekka Pessi committed
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
  am->am_blacklist = blacklist;
  am->am_forbidden = forbidden;
  am->am_anonymous = anonymous;
  am->am_fake = fake;
  am->am_remote = url_hdup(am->am_home, (url_t *)remote);
  am->am_algorithm = algorithm ? su_strdup(am->am_home, algorithm) : "MD5";
  am->am_nextnonce = !algorithm || strcasecmp(algorithm, "MD5") == 0;
  if (next_expires == 0)
    am->am_nextnonce = 0;
  am->am_qop = su_strdup(am->am_home, qop);

  if (master_key) {
    su_md5_t md5[1];

    su_md5_init(md5);
    su_md5_strupdate(md5, master_key);
    su_md5_strupdate(md5, "70P 53KR37");
    su_md5_digest(md5, am->am_master_key);
  }

  auth_md5_hmac_key(am);

200
  /* Make sure that we have something
Pekka Pessi's avatar
Pekka Pessi committed
201
     that can be used to identify credentials */
202
  if (am->am_opaque && strcmp(am->am_opaque, "*") == 0) {
Pekka Pessi's avatar
Pekka Pessi committed
203 204 205 206 207 208
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 255
#endif
    char hostname[HOST_NAME_MAX + 1];
    su_md5_t md5[1];
    uint8_t hmac[6];
209

Pekka Pessi's avatar
Pekka Pessi committed
210
    gethostname(hostname, sizeof hostname);
211

Pekka Pessi's avatar
Pekka Pessi committed
212
    auth_md5_hmac_init(am, md5);
213

Pekka Pessi's avatar
Pekka Pessi committed
214 215 216 217
    su_md5_strupdate(md5, hostname);
    su_md5_update(md5, ":", 1);
    if (am->am_remote)
      url_update(md5, am->am_remote);
218

Pekka Pessi's avatar
Pekka Pessi committed
219
    auth_md5_hmac_digest(am, md5, hmac, sizeof hmac);
220

Pekka Pessi's avatar
Pekka Pessi committed
221
    base64_e(hostname, sizeof hostname, hmac, sizeof hmac);
222

Pekka Pessi's avatar
Pekka Pessi committed
223
    am->am_opaque = su_strdup(am->am_home, hostname);
224 225 226 227 228

    if (!am->am_opaque) {
      retval = -1;
      SU_DEBUG_1(("%s: cannot create unique identifier\n", __func__));
    }
Pekka Pessi's avatar
Pekka Pessi committed
229 230
  }

231 232 233
  if (retval < 0)
    ;
  else if (db) {
Pekka Pessi's avatar
Pekka Pessi committed
234 235 236 237 238 239
    retval = auth_readdb(am);
    if (retval == -1) {
      int err = errno;
      SU_DEBUG_1(("auth-module: %s: %s\n", am->am_db, strerror(err)));
      errno = err;
    }
240 241
  }
  else {
Pekka Pessi's avatar
Pekka Pessi committed
242 243
    retval = auth_htable_resize(am->am_home, am->am_users, 0);
  }
244

Pekka Pessi's avatar
Pekka Pessi committed
245 246 247 248 249 250 251 252
  ta_end(ta);

  return retval;
}

/** Destroy (a reference to) an authentication module. */
void auth_mod_destroy(auth_mod_t *am)
{
253 254 255 256 257 258 259 260
  su_home_unref(am->am_home);
}

/** Call scheme-specific destructor function. */
static void auth_call_scheme_destructor(void *arg)
{
  auth_mod_t *am = arg;
  am->am_scheme->asch_destroy(am);
Pekka Pessi's avatar
Pekka Pessi committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274
}

/** Do-nothing destroy function.
 *
 * The auth_destroy_default() is the default member function called by
 * auth_mod_destroy().
 */
void auth_destroy_default(auth_mod_t *am)
{
}

/** Create a new reference to authentication module. */
auth_mod_t *auth_mod_ref(auth_mod_t *am)
{
275
  return (auth_mod_t *)su_home_ref(am->am_home);
Pekka Pessi's avatar
Pekka Pessi committed
276 277 278 279 280
}

/** Destroy a reference to an authentication module. */
void auth_mod_unref(auth_mod_t *am)
{
281
  su_home_unref(am->am_home);
Pekka Pessi's avatar
Pekka Pessi committed
282 283
}

284
/** Get authenticatin module name. @NEW_1_12_4. */
285 286 287 288
char const *auth_mod_name(auth_mod_t *am)
{
  return am ? am->am_scheme->asch_method : "<nil>";
}
Pekka Pessi's avatar
Pekka Pessi committed
289 290 291 292 293 294

/** Initialize a auth_status_t stucture.
 *
 * @retval NULL upon an error
 * @relates auth_status_t
 */
295
auth_status_t *auth_status_init(void *p, isize_t size)
Pekka Pessi's avatar
Pekka Pessi committed
296
{
297 298
  return auth_status_init_with(p, size, 500, auth_internal_server_error);
}
Pekka Pessi's avatar
Pekka Pessi committed
299

300 301 302 303 304 305
/** Initialize a auth_status_t stucture.
 *
 * @retval NULL upon an error
 * @relates auth_status_t
 */
auth_status_t *auth_status_init_with(void *p,
306
				     isize_t size,
307 308 309 310
				     int status,
				     char const *phrase)
{
  auth_status_t *as;
311

Pekka Pessi's avatar
Pekka Pessi committed
312 313 314
  if (!p || size < (sizeof *as))
    return NULL;

315 316
  if (size > INT_MAX) size = INT_MAX;

Pekka Pessi's avatar
Pekka Pessi committed
317
  as = memset(p, 0, size);
318
  as->as_home->suh_size = (int)size;
Pekka Pessi's avatar
Pekka Pessi committed
319

320
  /* su_home_init(as->as_home); */
Pekka Pessi's avatar
Pekka Pessi committed
321

322
  as->as_status = status, as->as_phrase = phrase;
323

Pekka Pessi's avatar
Pekka Pessi committed
324 325 326 327
  return as;
}

/** Allocate a new auth_status_t structure. @relates auth_status_t */
328

Pekka Pessi's avatar
Pekka Pessi committed
329 330 331 332 333 334 335 336 337 338
auth_status_t *auth_status_new(su_home_t *home)
{
  auth_status_t *as = su_home_clone(home, (sizeof *as));
  if (as) {
    as->as_status = 500;
    as->as_phrase = auth_internal_server_error;
  }
  return as;
}

Pekka Pessi's avatar
Pekka Pessi committed
339 340 341 342 343 344 345 346
/** Create a new reference to an auth_status_t structure.
 * @relates auth_status_t
 */
auth_status_t *auth_status_ref(auth_status_t *as)
{
  return (auth_status_t *)su_home_ref(as->as_home);
}

Pekka Pessi's avatar
Pekka Pessi committed
347 348 349 350
/** Destroy (a reference to) an auth_status_t structure. @relates auth_status_t
 */
void auth_status_unref(auth_status_t *as)
{
Pekka Pessi's avatar
Pekka Pessi committed
351
  su_home_unref(as->as_home);
Pekka Pessi's avatar
Pekka Pessi committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
}

/** Authenticate user.
 *
 * The function auth_mod_method() invokes scheme-specific authentication
 * operation where the user's credentials are checked using scheme-specific
 * method. The authentication result along with an optional challenge header
 * is stored in the @a as structure.
 *
 * @param am           pointer to authentication module object [in]
 * @param as           pointer to authentication status structure [in/out]
 * @param credentials  pointer to a header with user's credentials [in]
 * @param ach          pointer to a structure describing challenge [in]
 *
 * The @a ach structure defines what kind of response and challenge header
 * is returned to the user. For example, a server authentication is
 * implemented with 401 response code and phrase along with WWW-Authenticate
 * header template in the @a ach structure.
 *
 * The auth_mod_method() returns the authentication result in the
372
 * #auth_mod_t @a as structure. The @a as->as_status describes the result
Pekka Pessi's avatar
Pekka Pessi committed
373 374 375
 * as follows:
 * - <i>as->as_status == 0</i> authentication is successful
 * - <i>as->as_status == 100</i> authentication is pending
376
 * - <i>as->as_status >= 400</i> authentication fails,
Pekka Pessi's avatar
Pekka Pessi committed
377
 *   return as_status as an error code to client
378
 *
Pekka Pessi's avatar
Pekka Pessi committed
379 380 381 382 383 384 385 386
 * When the authentication is left pending, the client must set the
 * as_callback pointer in @a as structure to an appropriate callback
 * function. The callback is invoked when the authentication is completed,
 * either successfully or with an error.
 *
 * Note that the authentication module may generate a new challenge each
 * time authentication is used (e.g., Digest using MD5 algorithm). Such a
 * challenge header is stored in the @a as->as_response return-value field.
387
 *
Pekka Pessi's avatar
Pekka Pessi committed
388 389 390 391 392
 * @note The authentication plugin may use the given reference to @a as, @a
 * credentials and @a ach structures until the asynchronous authentication
 * completes. Therefore, they should not be allocated from stack unless
 * application uses strictly synchronous authentication schemes only (Basic
 * and Digest).
393 394
 *
 * @note This function should be called auth_mod_check().
Pekka Pessi's avatar
Pekka Pessi committed
395
 */
396
void auth_mod_verify(auth_mod_t *am,
Pekka Pessi's avatar
Pekka Pessi committed
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
		     auth_status_t *as,
		     msg_auth_t *credentials,
		     auth_challenger_t const *ach)
{
  char const *wildcard, *host;

  if (!am || !as || !ach)
    return;

  wildcard = strchr(am->am_realm, '*');

  host = as->as_domain;

  /* Initialize per-request realm */
  if (as->as_realm)
    ;
413
  else if (!wildcard) {
Pekka Pessi's avatar
Pekka Pessi committed
414
    as->as_realm = am->am_realm;
415 416 417 418
  }
  else if (!host) {
    return;			/* Internal error */
  }
Pekka Pessi's avatar
Pekka Pessi committed
419 420 421 422 423
  else if (strcmp(am->am_realm, "*") == 0) {
    as->as_realm = host;
  }
  else {
    /* Replace * with hostpart */
424
    as->as_realm = su_sprintf(as->as_home, "%.*s%s%s",
Pekka Pessi's avatar
Pekka Pessi committed
425 426 427 428 429 430 431 432
			      (int)(wildcard - am->am_realm), am->am_realm,
			      host,
			      wildcard + 1);
  }

  am->am_scheme->asch_check(am, as, credentials, ach);
}

433
/** Make a challenge header.
Pekka Pessi's avatar
Pekka Pessi committed
434 435 436 437 438 439 440 441 442 443 444 445 446
 *
 * This function invokes plugin-specific member function generating a
 * challenge header. Client uses the challenge header contents when
 * prompting the user for a username and password then generates its
 * credential header using the parameters given in the challenge header.
 *
 * @param am pointer to authentication module object
 * @param as pointer to authentication status structure (return-value)
 * @param ach pointer to a structure describing challenge
 *
 * The auth_mod_challenge() returns the challenge header, appropriate
 * response code and reason phrase in the #auth_status_t structure. The
 * auth_mod_challenge() is currently always synchronous function.
447
 */
Pekka Pessi's avatar
Pekka Pessi committed
448 449 450 451 452 453 454 455 456 457
void auth_mod_challenge(auth_mod_t *am,
			auth_status_t *as,
			auth_challenger_t const *ach)
{
  if (am && as && ach)
    am->am_scheme->asch_challenge(am, as, ach);
}


/** Cancel asynchronous authentication.
458 459
 *
 * The auth_mod_cancel() function cancels a pending authentication.
Pekka Pessi's avatar
Pekka Pessi committed
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
 * Application can reclaim the authentication status, credential and
 * challenger objects by using auth_mod_cancel().
 */
void auth_mod_cancel(auth_mod_t *am, auth_status_t *as)
{
  if (am && as)
    am->am_scheme->asch_cancel(am, as);
}

/** Do-nothing cancel function.
 *
 * The auth_cancel_default() is the default member function called by
 * auth_mod_cancel().
 */
void auth_cancel_default(auth_mod_t *am, auth_status_t *as)
{
}

/* ====================================================================== */
/* Basic authentication scheme */

static void auth_method_basic_x(auth_mod_t *am,
				auth_status_t *as,
				msg_auth_t *au,
				auth_challenger_t const *ach);

486
auth_scheme_t auth_scheme_basic[1] =
Pekka Pessi's avatar
Pekka Pessi committed
487 488 489
  {{
      "Basic",			/* asch_method */
      sizeof (auth_mod_t),	/* asch_size */
490
      auth_init_default,	/* asch_init */
Pekka Pessi's avatar
Pekka Pessi committed
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
      auth_method_basic_x, 	/* asch_check */
      auth_challenge_basic,	/* asch_challenge */
      auth_cancel_default,	/* asch_cancel */
      auth_destroy_default	/* asch_destroy */
  }};

/**Authenticate a request with @b Basic authentication.
 *
 * This function reads user database before authentication, if needed.
 */
static
void auth_method_basic_x(auth_mod_t *am,
			 auth_status_t *as,
			 msg_auth_t *au,
			 auth_challenger_t const *ach)
{
  if (am) {
    auth_readdb_if_needed(am);
    auth_method_basic(am, as, au, ach);
  }
}

513
/** Authenticate a request with @b Basic authentication scheme.
Pekka Pessi's avatar
Pekka Pessi committed
514 515 516 517 518 519 520
 *
 */
void auth_method_basic(auth_mod_t *am,
		       auth_status_t *as,
		       msg_auth_t *au,
		       auth_challenger_t const *ach)
{
521
  char *userpass, buffer[128];
522
  size_t n, upsize;
Pekka Pessi's avatar
Pekka Pessi committed
523 524 525 526 527 528
  char *pass;
  auth_passwd_t *apw;

  if (!as->as_realm)
    return;

529 530
  userpass = buffer, upsize = sizeof buffer;

Pekka Pessi's avatar
Pekka Pessi committed
531
  for (au = auth_mod_credentials(au, "Basic", NULL);
532
       au;
Pekka Pessi's avatar
Pekka Pessi committed
533 534 535
       au = auth_mod_credentials(au->au_next, "Basic", NULL)) {
    if (!au->au_params)
      continue;
536 537
    n = base64_d(userpass, upsize - 1, au->au_params[0]);
    if (n < 0 || n >= INT_MAX)
Pekka Pessi's avatar
Pekka Pessi committed
538
      continue;
539 540 541 542 543 544 545
    if (n >= upsize) {
      upsize = n + 1;
      userpass = realloc(userpass == buffer ? NULL : userpass, upsize);
      if (userpass == NULL)
	continue;
      base64_d(userpass, upsize - 1, au->au_params[0]);
    }
Pekka Pessi's avatar
Pekka Pessi committed
546 547 548 549
    userpass[n] = 0;
    if (!(pass = strchr(userpass, ':')))
      continue;
    *pass++ = '\0';
550
    SU_DEBUG_5(("auth_method_basic: %s => %s:%s\n",
Pekka Pessi's avatar
Pekka Pessi committed
551 552 553 554 555 556 557 558 559
		au->au_params[0], userpass, pass));

    if (!(apw = auth_mod_getpass(am, userpass, as->as_realm)))
      continue;
    if (strcmp(apw->apw_pass, pass))
      continue;

    as->as_user = apw->apw_user;
    as->as_anonymous = apw == am->am_anon_user;
560
    as->as_ident = apw->apw_ident;
Pekka Pessi's avatar
Pekka Pessi committed
561 562 563
    as->as_match = (msg_header_t *)au;
    as->as_status = 0;	/* Successful authentication! */

564
    break;
Pekka Pessi's avatar
Pekka Pessi committed
565 566
  }

567 568 569 570 571 572
  if (userpass != buffer)
    free(userpass);

  if (au)
    return;

Pekka Pessi's avatar
Pekka Pessi committed
573 574 575 576 577
  if (auth_allow_check(am, as))
    auth_challenge_basic(am, as, ach);
}

/** Construct a challenge header for @b Basic authentication scheme. */
578
void auth_challenge_basic(auth_mod_t *am,
Pekka Pessi's avatar
Pekka Pessi committed
579 580 581 582 583
			  auth_status_t *as,
			  auth_challenger_t const *ach)
{
  as->as_status = ach->ach_status;
  as->as_phrase = ach->ach_phrase;
584
  as->as_response = msg_header_format(as->as_home, ach->ach_header,
Pekka Pessi's avatar
Pekka Pessi committed
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
				      "Basic realm=\"%s\"", as->as_realm);
}

/* ====================================================================== */
/* Digest authentication scheme */

static void auth_method_digest_x(auth_mod_t *am,
				 auth_status_t *as,
				 msg_auth_t *au,
				 auth_challenger_t const *ach);

auth_scheme_t auth_scheme_digest[1] =
  {{
      "Digest",			/* asch_method */
      sizeof (auth_mod_t),	/* asch_size */
      auth_init_default,	/* asch_init */
      auth_method_digest_x,	/* asch_check */
      auth_challenge_digest,	/* asch_challenge */
      auth_cancel_default,	/* asch_cancel */
      auth_destroy_default	/* asch_destroy */
  }};

struct nonce {
  msg_time_t issued;
  uint32_t   count;
  uint16_t   nextnonce;
  uint8_t    digest[6];
};

Pekka Pessi's avatar
Pekka Pessi committed
614
#define AUTH_DIGEST_NONCE_LEN (BASE64_MINSIZE(sizeof (struct nonce)) + 1)
Pekka Pessi's avatar
Pekka Pessi committed
615

616
/** Authenticate a request with @b Digest authentication scheme.
Pekka Pessi's avatar
Pekka Pessi committed
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
 *
 * This function reads user database before authentication, if needed.
 */
static
void auth_method_digest_x(auth_mod_t *am,
			  auth_status_t *as,
			  msg_auth_t *au,
			  auth_challenger_t const *ach)
{
  if (am) {
    auth_readdb_if_needed(am);
    auth_method_digest(am, as, au, ach);
  }
}

632
/** Authenticate a request with @b Digest authentication scheme.
Pekka Pessi's avatar
Pekka Pessi committed
633 634 635 636 637 638
 */
void auth_method_digest(auth_mod_t *am,
			auth_status_t *as,
			msg_auth_t *au,
			auth_challenger_t const *ach)
{
Pekka Pessi's avatar
Pekka Pessi committed
639
  as->as_allow = as->as_allow || auth_allow_check(am, as) == 0;
Pekka Pessi's avatar
Pekka Pessi committed
640 641

  if (as->as_realm)
642
    au = auth_digest_credentials(au, as->as_realm, am->am_opaque);
Pekka Pessi's avatar
Pekka Pessi committed
643 644 645 646 647 648 649 650
  else
    au = NULL;

  if (as->as_allow) {
    SU_DEBUG_5(("%s: allow unauthenticated %s\n", __func__, as->as_method));
    as->as_status = 0, as->as_phrase = NULL;
    as->as_match = (msg_header_t *)au;
    return;
651
  }
Pekka Pessi's avatar
Pekka Pessi committed
652 653 654 655 656 657 658 659 660 661 662 663 664 665

  if (au) {
    auth_response_t ar[1] = {{ sizeof(ar) }};
    auth_digest_response_get(as->as_home, ar, au->au_params);
    as->as_match = (msg_header_t *)au;
    auth_check_digest(am, as, ar, ach);
  }
  else {
    /* There was no matching credentials, send challenge */
    SU_DEBUG_5(("%s: no credentials matched\n", __func__));
    auth_challenge_digest(am, as, ach);
  }
}

666
/** Verify digest authentication */
Pekka Pessi's avatar
Pekka Pessi committed
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
void auth_check_digest(auth_mod_t *am,
		       auth_status_t *as,
		       auth_response_t *ar,
		       auth_challenger_t const *ach)
{
  char const *a1;
  auth_hexmd5_t a1buf, response;
  auth_passwd_t *apw;
  char const *phrase;
  msg_time_t now = msg_now();

  if (am == NULL || as == NULL || ar == NULL || ach == NULL) {
    if (as) {
      as->as_status = 500, as->as_phrase = "Internal Server Error";
      as->as_response = NULL;
    }
    return;
  }

  phrase = "Bad authorization";

688
#define PA "Authorization missing "
Pekka Pessi's avatar
Pekka Pessi committed
689

690 691 692 693
  if ((!ar->ar_username && (phrase = PA "username")) ||
      (!ar->ar_nonce && (phrase = PA "nonce")) ||
      (!ar->ar_uri && (phrase = PA "URI")) ||
      (!ar->ar_response && (phrase = PA "response")) ||
694
      /* (!ar->ar_opaque && (phrase = PA "opaque")) || */
Pekka Pessi's avatar
Pekka Pessi committed
695
      /* Check for qop */
696 697
      (ar->ar_qop &&
       ((ar->ar_auth &&
Pekka Pessi's avatar
Pekka Pessi committed
698 699
	 strcasecmp(ar->ar_qop, "auth") &&
	 strcasecmp(ar->ar_qop, "\"auth\"")) ||
700
	(ar->ar_auth_int &&
Pekka Pessi's avatar
Pekka Pessi committed
701
	 strcasecmp(ar->ar_qop, "auth-int") &&
702
	 strcasecmp(ar->ar_qop, "\"auth-int\"")))
Pekka Pessi's avatar
Pekka Pessi committed
703 704 705 706 707 708 709 710
       && (phrase = PA "has invalid qop"))) {
    assert(phrase);
    SU_DEBUG_5(("auth_method_digest: 400 %s\n", phrase));
    as->as_status = 400, as->as_phrase = phrase;
    as->as_response = NULL;
    return;
  }

711
  if (as->as_nonce_issued == 0 /* Already validated nonce */ &&
Pekka Pessi's avatar
Pekka Pessi committed
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
      auth_validate_digest_nonce(am, as, ar, now) < 0) {
    as->as_blacklist = am->am_blacklist;
    auth_challenge_digest(am, as, ach);
    return;
  }

  if (as->as_stale) {
    auth_challenge_digest(am, as, ach);
    return;
  }

  apw = auth_mod_getpass(am, ar->ar_username, ar->ar_realm);

  if (apw && apw->apw_hash)
    a1 = apw->apw_hash;
  else if (apw && apw->apw_pass)
    auth_digest_a1(ar, a1buf, apw->apw_pass), a1 = a1buf;
729
  else
Pekka Pessi's avatar
Pekka Pessi committed
730
    auth_digest_a1(ar, a1buf, "xyzzy"), a1 = a1buf, apw = NULL;
731

Pekka Pessi's avatar
Pekka Pessi committed
732 733
  if (ar->ar_md5sess)
    auth_digest_a1sess(ar, a1buf, a1), a1 = a1buf;
734 735

  auth_digest_response(ar, response, a1,
Pekka Pessi's avatar
Pekka Pessi committed
736 737 738
		       as->as_method, as->as_body, as->as_bodylen);

  if (!apw || strcmp(response, ar->ar_response)) {
739

Pekka Pessi's avatar
Pekka Pessi committed
740 741 742
    if (am->am_forbidden) {
      as->as_status = 403, as->as_phrase = "Forbidden";
      as->as_response = NULL;
743
      as->as_blacklist = am->am_blacklist;
Pekka Pessi's avatar
Pekka Pessi committed
744 745 746 747 748 749 750 751 752 753 754 755 756 757
    }
    else {
      auth_challenge_digest(am, as, ach);
      as->as_blacklist = am->am_blacklist;
    }
    SU_DEBUG_5(("auth_method_digest: response did not match\n"));

    return;
  }

  assert(apw);

  as->as_user = apw->apw_user;
  as->as_anonymous = apw == am->am_anon_user;
758
  as->as_ident = apw->apw_ident;
Pekka Pessi's avatar
Pekka Pessi committed
759 760 761 762 763 764 765 766 767 768 769 770 771 772

  if (am->am_nextnonce || am->am_mutual)
    auth_info_digest(am, as, ach);

  if (am->am_challenge)
    auth_challenge_digest(am, as, ach);

  SU_DEBUG_7(("auth_method_digest: successful authentication\n"));

  as->as_status = 0;	/* Successful authentication! */
  as->as_phrase = "";
}

/** Construct a challenge header for @b Digest authentication scheme. */
773
void auth_challenge_digest(auth_mod_t *am,
Pekka Pessi's avatar
Pekka Pessi committed
774 775 776 777 778 779 780 781 782 783 784
			   auth_status_t *as,
			   auth_challenger_t const *ach)
{
  char const *u, *d;
  char nonce[AUTH_DIGEST_NONCE_LEN];

  auth_generate_digest_nonce(am, nonce, sizeof nonce, 0, msg_now());

  u = as->as_uri;
  d = as->as_pdomain;

785 786
  as->as_response =
    msg_header_format(as->as_home, ach->ach_header,
Pekka Pessi's avatar
Pekka Pessi committed
787 788 789 790 791
		      "Digest"
		      " realm=\"%s\","
		      "%s%s%s"
		      "%s%s%s"
		      " nonce=\"%s\","
792
		      "%s%s%s"
Pekka Pessi's avatar
Pekka Pessi committed
793
		      "%s"	/* stale */
794
		      " algorithm=%s"
Pekka Pessi's avatar
Pekka Pessi committed
795
		      "%s%s%s",
796 797 798 799
		      as->as_realm,
		      u ? " uri=\"" : "", u ? u : "", u ? "\"," : "",
		      d ? " domain=\"" : "", d ? d : "", d ? "\"," : "",
		      nonce,
800 801 802
		      am->am_opaque ? " opaque=\"" : "",
		      am->am_opaque ? am->am_opaque : "",
		      am->am_opaque ? "\"," : "",
Pekka Pessi's avatar
Pekka Pessi committed
803 804 805 806 807 808 809 810 811 812 813 814 815
		      as->as_stale ? " stale=true," : "",
		      am->am_algorithm,
		      am->am_qop ? ", qop=\"" : "",
		      am->am_qop ? am->am_qop : "",
		      am->am_qop ? "\"" : "");

  if (!as->as_response)
    as->as_status = 500, as->as_phrase = auth_internal_server_error;
  else
    as->as_status = ach->ach_status, as->as_phrase = ach->ach_phrase;
}

/** Construct a info header for @b Digest authentication scheme. */
816
void auth_info_digest(auth_mod_t *am,
Pekka Pessi's avatar
Pekka Pessi committed
817 818 819 820 821 822 823 824 825 826 827
		      auth_status_t *as,
		      auth_challenger_t const *ach)
{
  if (!ach->ach_info)
    return;

  if (am->am_nextnonce) {
    char nonce[AUTH_DIGEST_NONCE_LEN];

    auth_generate_digest_nonce(am, nonce, sizeof nonce, 1, msg_now());

828
    as->as_info =
Pekka Pessi's avatar
Pekka Pessi committed
829 830 831 832 833 834 835 836
      msg_header_format(as->as_home, ach->ach_info, "nextnonce=\"%s\"", nonce);
  }
}


/* ====================================================================== */
/* Password database */

837
su_inline void
Pekka Pessi's avatar
Pekka Pessi committed
838 839 840 841 842 843 844 845
auth_htable_append_local(auth_htable_t *pr, auth_passwd_t *apw);

/** Get an passwd entry for user. */
auth_passwd_t *auth_mod_getpass(auth_mod_t *am,
				char const *user,
				char const *realm)
{
  auth_passwd_t *apw, **slot;
846
  unsigned hash;
Pekka Pessi's avatar
Pekka Pessi committed
847 848 849

  if (am == NULL || user == NULL)
    return NULL;
850

851
  hash = msg_hash_string(user);
852

853
  for (slot = auth_htable_hash(am->am_users, hash);
Pekka Pessi's avatar
Pekka Pessi committed
854 855
       (apw = *slot);
       slot = auth_htable_next(am->am_users, slot)) {
856
    if (hash != apw->apw_index)
Pekka Pessi's avatar
Pekka Pessi committed
857 858 859 860 861 862 863
      continue;
    if (strcmp(user, apw->apw_user))
      continue;
    if (realm && apw->apw_realm[0] && strcmp(realm, apw->apw_realm))
      continue;
    break;			/* Found it */
  }
864

Pekka Pessi's avatar
Pekka Pessi committed
865 866 867 868 869 870 871 872 873
  return apw;
}

/** Add a password entry. */
auth_passwd_t *auth_mod_addpass(auth_mod_t *am,
				char const *user,
				char const *realm)
{
  auth_passwd_t *apw, **slot;
874
  unsigned index;
Pekka Pessi's avatar
Pekka Pessi committed
875 876 877

  if (am == NULL || user == NULL)
    return NULL;
878

Pekka Pessi's avatar
Pekka Pessi committed
879
  index = msg_hash_string(user);
880

Pekka Pessi's avatar
Pekka Pessi committed
881 882 883 884 885 886 887 888 889 890 891 892 893 894
  for (slot = auth_htable_hash(am->am_users, index);
       (apw = *slot);
       slot = auth_htable_next(am->am_users, slot)) {
    if (index != apw->apw_index)
      continue;
    if (strcmp(user, apw->apw_user))
      continue;
    if (realm && strcmp(realm, apw->apw_realm))
      continue;
    break;			/* Found it */
  }

  if (realm == NULL)
    realm = "";
895

Pekka Pessi's avatar
Pekka Pessi committed
896 897
  if (!apw) {
    size_t ulen = strlen(user) + 1, rlen = strlen(realm) + 1;
898 899 900
    size_t size = sizeof *apw + ulen + rlen;

    apw = su_alloc(am->am_home, size);
Pekka Pessi's avatar
Pekka Pessi committed
901 902 903 904 905 906 907 908 909 910 911 912

    if (apw) {
      memset(apw, 0, sizeof *apw);
      apw->apw_index = index;
      apw->apw_user = memcpy((char *)(apw + 1), user, ulen);
      apw->apw_realm = memcpy((char *)apw->apw_user + ulen, realm, rlen);

      if (!auth_htable_is_full(am->am_users)) {
	*slot = apw, am->am_users->aht_used++;
      } else {
	if (auth_htable_resize(am->am_home, am->am_users, 0) < 0)
	  su_free(am->am_home, apw), apw = NULL;
913
	else
Pekka Pessi's avatar
Pekka Pessi committed
914 915 916 917 918 919 920 921
	  auth_htable_append(am->am_users, apw);
      }
    }
  }

  return apw;
}

922 923
static ssize_t readfile(su_home_t *, FILE *,
			void **contents, int add_trailing_lf);
Pekka Pessi's avatar
Pekka Pessi committed
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
static int auth_readdb_internal(auth_mod_t *am, int always);

/** Read authentication database */
int auth_readdb(auth_mod_t *am)
{
  return auth_readdb_internal(am, 1);
}

/** Read authentication database only when needed */
int auth_readdb_if_needed(auth_mod_t *am)
{
  struct stat st[1];

  if (!am->am_stat || !am->am_db)
    return 0;

  if (stat(am->am_db, st) != -1 &&
      st->st_dev == am->am_stat->st_dev &&
      st->st_ino == am->am_stat->st_ino &&
943 944
      st->st_size == am->am_stat->st_size &&
      memcmp(&st->st_mtime, &am->am_stat->st_mtime,
Pekka Pessi's avatar
Pekka Pessi committed
945
	     (sizeof st->st_mtime)) == 0)
946 947
    /* Nothing has changed or passwd file is removed */
    return 0;
Pekka Pessi's avatar
Pekka Pessi committed
948 949 950 951 952 953 954 955

  return auth_readdb_internal(am, 0);
}

#if HAVE_FLOCK
#include <sys/file.h>
#endif

956 957
/* This is just a magic value */
#define auth_apw_local ((void *)(intptr_t)auth_readdb_internal)
Pekka Pessi's avatar
Pekka Pessi committed
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973

/** Read authentication database */
static
int auth_readdb_internal(auth_mod_t *am, int always)
{
  FILE *f;
  char *data, *s;
  size_t len, i, n, N;
  auth_passwd_t *apw;

  if (!am->am_stat)
    am->am_stat = su_zalloc(am->am_home, sizeof (*am->am_stat));

  f = fopen(am->am_db, "rb");

  if (f) {
Pekka Pessi's avatar
Pekka Pessi committed
974
    void *buffer = NULL;
Pekka Pessi's avatar
Pekka Pessi committed
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
    auth_passwd_t *fresh = NULL;

#if HAVE_FLOCK
    int locked;

    /* Obtain shared lock on the database file */
    if (flock(fileno(f), LOCK_SH | (always ? 0 : LOCK_NB)) == 0) {
      locked = 1;
    } else {
      locked = 0;

      if (errno == ENOLCK) {
	;
      }
      else if (errno == EWOULDBLOCK) {
	SU_DEBUG_3(("auth(%s): user file \"%s\" is busy, trying again later\n",
		    am->am_scheme->asch_method, am->am_db));
	fclose(f);
	return always ? -1 : 0;
994 995
      }
      else {
996 997
	SU_DEBUG_3(("auth(%s): flock(\"%s\"): %s (%u)\n",
		    am->am_scheme->asch_method, am->am_db,
998
		    strerror(errno), errno));
Pekka Pessi's avatar
Pekka Pessi committed
999 1000 1001
	fclose(f);
	return always ? -1 : 0;
      }
1002
    }
Pekka Pessi's avatar
Pekka Pessi committed
1003 1004 1005 1006 1007 1008 1009 1010 1011
#endif
    if (am->am_stat)
      stat(am->am_db, am->am_stat); /* too bad if this fails */

    len = readfile(am->am_home, f, &buffer, 1);

#if HAVE_FLOCK
    /* Release shared lock on the database file */
    if (locked && flock(fileno(f), LOCK_UN) == -1) {
1012
      SU_DEBUG_0(("auth(%s): un-flock(\"%s\"): %s (%u)\n",
Pekka Pessi's avatar
Pekka Pessi committed
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
		  am->am_scheme->asch_method, am->am_db, strerror(errno), errno));
      fclose(f);
      return -1;
    }
#endif

    fclose(f);

    if (len < 0)
      return -1;

    /* Count number of entries in new buffer */
    for (i = am->am_anonymous, s = data = buffer;
1026
	 s < data + len;
Pekka Pessi's avatar
Pekka Pessi committed
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
	 s += n + strspn(s + n, "\r\n")) {
      n = strcspn(s, "\r\n");
      if (*s != '#' && *s != '\n' && *s != '\r')
	i++;
    }

    N = i, i = 0;

    if (N > 0) {
      if (auth_htable_resize(am->am_home, am->am_users, N) < 0 ||
	  !(fresh = su_zalloc(am->am_home, sizeof(*fresh) * N))) {
	su_free(am->am_home, buffer);
	return -1;
      }
    }

    if (am->am_anonymous) {
      assert(i < N);
1045

Pekka Pessi's avatar
Pekka Pessi committed
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
      apw = fresh + i++;

      apw->apw_index = msg_hash_string("anonymous");
      apw->apw_user = "anonymous";
      apw->apw_pass = "";
      apw->apw_realm = "";

      am->am_anon_user = apw;

      if (auth_htable_is_full(am->am_users))
	auth_htable_resize(am->am_home, am->am_users, 0);

      auth_htable_append_local(am->am_users, apw);
    }

1061 1062
    apw = NULL;

Pekka Pessi's avatar
Pekka Pessi committed
1063 1064 1065
    for (data = buffer, s = data;
	 s < data + len && i < N;
	 s += n + strspn(s + n, "\r\n")) {
1066
      char *user, *pass, *realm, *ident;
Pekka Pessi's avatar
Pekka Pessi committed
1067 1068 1069 1070

      n = strcspn(s, "\r\n");
      if (*s == '#')
	continue;
1071

Pekka Pessi's avatar
Pekka Pessi committed
1072 1073 1074 1075 1076 1077
      user = s;
      s[n++] = '\0';
      if (!(pass = strchr(user, ':')))
	continue;

      *pass++ = '\0';
1078
      if (!*pass || !*user)
Pekka Pessi's avatar
Pekka Pessi committed
1079
	continue;
1080 1081 1082 1083

      realm = ""; ident = "";

      if ((realm = strchr(pass, ':'))) {
Pekka Pessi's avatar
Pekka Pessi committed
1084
	*realm++ = '\0';
1085 1086 1087
	if ((ident = strchr(realm, ':')))
	  *ident++ = '\0';
      }
Pekka Pessi's avatar
Pekka Pessi committed
1088 1089 1090 1091 1092

      apw = fresh + i++;

      apw->apw_index = msg_hash_string(user);
      apw->apw_user = user;
1093
      apw->apw_ident = ident;
Pekka Pessi's avatar
Pekka Pessi committed
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123

      /* Check for htdigest format */
      if (span_hexdigit(realm) == 32 && realm[32] == '\0') {
	apw->apw_realm = pass;
	apw->apw_hash = realm;
      } else {
	apw->apw_pass = pass;
	apw->apw_realm = realm;
      }

      if (auth_htable_is_full(am->am_users))
	auth_htable_resize(am->am_home, am->am_users, 0);

      auth_htable_append_local(am->am_users, apw);
    }

    assert(i <= N);
    N = i;

    /* Remove from hash those entries that were read from old passwd file */
    for (i = 0; i < am->am_local_count; i++) {
      if (am->am_locals[i].apw_type == auth_apw_local)
	auth_htable_remove(am->am_users, &am->am_locals[i]);
    }

    if (am->am_locals)
      su_free(am->am_home, am->am_locals); /* Free old entries */
    if (am->am_buffer)
      su_free(am->am_home, am->am_buffer); /* Free old passwd file contents */

1124 1125 1126
    SU_DEBUG_5(("auth(%s): read %u entries from \"%s\"\n",
		am->am_scheme->asch_method, (unsigned)N, am->am_db));

Pekka Pessi's avatar
Pekka Pessi committed
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    am->am_locals = fresh;
    am->am_local_count = N;
    am->am_buffer = buffer;

    return 0;
  }

  return -1;
}

/** Append to hash, remove existing user */
1138
su_inline void
1139
auth_htable_append_local(auth_htable_t *aht, auth_passwd_t *apw)
Pekka Pessi's avatar
Pekka Pessi committed
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
{
  auth_passwd_t **slot;

  apw->apw_type = auth_apw_local;

  /* Append to hash */
  for (slot = auth_htable_hash(aht, apw->apw_index);
       *slot;
       slot = auth_htable_next(aht, slot)) {
    if (strcmp((*slot)->apw_user, apw->apw_user) == 0) {
      if ((*slot)->apw_type == auth_apw_local) {
1151
	(*slot)->apw_type = NULL;
Pekka Pessi's avatar
Pekka Pessi committed
1152 1153 1154 1155
	assert(aht->aht_used > 0); aht->aht_used--;
	apw->apw_extended = (*slot)->apw_extended;
	*slot = NULL;
	break;
1156 1157
      }
      else {
Pekka Pessi's avatar
Pekka Pessi committed
1158 1159 1160 1161 1162 1163 1164 1165 1166
	/* We insert local before external entry */
	auth_passwd_t *swap = apw;
	apw = *slot;
	*slot = swap;
      }
    }
  }

  aht->aht_used++; assert(aht->aht_used <= aht->aht_size);
1167

Pekka Pessi's avatar
Pekka Pessi committed
1168 1169 1170
  *slot = apw;
}

1171
static
1172 1173 1174 1175
ssize_t readfile(su_home_t *home,
		 FILE *f,
		 void **contents,
		 int add_trailing_lf)
Pekka Pessi's avatar
Pekka Pessi committed
1176 1177 1178 1179
{
  /* Read in whole (binary!) file */
  char *buffer = NULL;
  long size;
1180
  size_t len;
1181

Pekka Pessi's avatar
Pekka Pessi committed
1182 1183 1184 1185
  /* Read whole file in */
  if (fseek(f, 0, SEEK_END) < 0 ||
      (size = ftell(f)) < 0 ||
      fseek(f, 0, SEEK_SET) < 0 ||
1186 1187
      (long)(len = (size_t)size) != size ||
      size + 2 > SSIZE_MAX) {
1188
    SU_DEBUG_1(("%s: unable to determine file size (%s)\n",
Pekka Pessi's avatar
Pekka Pessi committed
1189 1190 1191 1192 1193
		__func__, strerror(errno)));
    return -1;
  }

  if (!(buffer = su_alloc(home, len + 2)) ||
1194
      fread(buffer, 1, len, f) != len) {
Pekka Pessi's avatar
Pekka Pessi committed
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
    SU_DEBUG_1(("%s: unable to read file (%s)\n", __func__, strerror(errno)));
    if (buffer)
      su_free(home, buffer);
    return -1;
  }

  if (add_trailing_lf) {
    /* Make sure that the buffer has trailing newline */
    if (len == 0 || buffer[len - 1] != '\n')
      buffer[len++] = '\n';
  }

  buffer[len] = '\0';
  *contents = buffer;

  return len;
}

/* ====================================================================== */
/* Helper functions */

1216
/** Check if request method is on always-allowed list.
1217 1218 1219 1220
 *
 * @return 0 if allowed
 * @return 1 otherwise
 */
Pekka Pessi's avatar
Pekka Pessi committed
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
int auth_allow_check(auth_mod_t *am, auth_status_t *as)
{
  char const *method = as->as_method;
  int i;

  if (method && strcmp(method, "ACK") == 0) /* Hack */
    return as->as_status = 0;

  if (!method || !am->am_allow)
    return 1;

1232 1233 1234
  if (am->am_allow[0] && strcmp(am->am_allow[0], "*") == 0)
    return as->as_status = 0;

Pekka Pessi's avatar
Pekka Pessi committed
1235 1236 1237 1238 1239 1240 1241 1242
  for (i = 0; am->am_allow[i]; i++)
    if (strcmp(am->am_allow[i], method) == 0)
      return as->as_status = 0;

  return 1;
}

/** Find a credential header with matching scheme and realm. */
1243
msg_auth_t *auth_mod_credentials(msg_auth_t *auth,
Pekka Pessi's avatar
Pekka Pessi committed
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
				 char const *scheme,
				 char const *realm)
{
  char const *arealm;

  for (;auth; auth = auth->au_next) {
    if (strcasecmp(auth->au_scheme, scheme))
      continue;

    if (!realm)
      return auth;

1256
    arealm = msg_header_find_param(auth->au_common, "realm=");
Pekka Pessi's avatar
Pekka Pessi committed
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282

    if (!arealm)
      continue;

    if (arealm[0] == '"') {
      /* Compare quoted arealm with unquoted realm */
      int i, j;
      for (i = 1, j = 0; arealm[i] != 0; i++, j++) {
	if (arealm[i] == '"' && realm[j] == 0)
	  return auth;

	if (arealm[i] == '\\' && arealm[i + 1] != '\0')
	  i++;

	if (arealm[i] != realm[j])
	  break;
      }
    } else {
      if (strcmp(arealm, realm) == 0)
	return auth;
    }
  }

  return NULL;
}

1283
/** Find a Digest credential header with matching realm and opaque. */
1284
msg_auth_t *auth_digest_credentials(msg_auth_t *auth,
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
				    char const *realm,
				    char const *opaque)
{
  char const *arealm, *aopaque;

  for (;auth; auth = auth->au_next) {
    if (strcasecmp(auth->au_scheme, "Digest"))
      continue;

    if (realm) {
      int cmp = 1;

1297
      arealm = msg_header_find_param(auth->au_common, "realm=");
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
      if (!arealm)
	continue;

      if (arealm[0] == '"') {
	/* Compare quoted arealm with unquoted realm */
	int i, j;
	for (i = 1, j = 0, cmp = 1; arealm[i] != 0; i++, j++) {
	  if (arealm[i] == '"' && realm[j] == 0) {
	    cmp = 0;
	    break;
	  }

	  if (arealm[i] == '\\' && arealm[i + 1] != '\0')
	    i++;

	  if (arealm[i] != realm[j])
	    break;
	}
1316
      }
1317
      else {
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
	cmp = strcmp(arealm, realm);
      }

      if (cmp)
	continue;
    }

    if (opaque) {
      int cmp = 1;

1328
      aopaque = msg_header_find_param(auth->au_common, "opaque=");
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
      if (!aopaque)
	continue;

      if (aopaque[0] == '"') {
	/* Compare quoted aopaque with unquoted opaque */
	int i, j;
	for (i = 1, j = 0, cmp = 1; aopaque[i] != 0; i++, j++) {
	  if (aopaque[i] == '"' && opaque[j] == 0) {
	    cmp = 0;
	    break;
	  }

	  if (aopaque[i] == '\\' && aopaque[i + 1] != '\0')
	    i++;

	  if (aopaque[i] != opaque[j])
	    break;
	}
      } else {
	cmp = strcmp(aopaque, opaque);
      }

      if (cmp)
	continue;
    }

    return auth;
  }

  return NULL;
}

Pekka Pessi's avatar
Pekka Pessi committed
1361 1362 1363 1364 1365 1366 1367 1368
/** Generate nonce parameter.
 *
 * @param am pointer to authentication module object
 * @param buffer string buffer for nonce [OUT]
 * @param bsize size of buffer [IN]
 * @param nextnonce true if this is a "nextnonce" [IN]
 * @param now  current time [IN]
 */
1369 1370 1371 1372 1373
isize_t auth_generate_digest_nonce(auth_mod_t *am,
				   char buffer[],
				   size_t bsize,
				   int nextnonce,
				   msg_time_t now)
Pekka Pessi's avatar
Pekka Pessi committed
1374 1375
{
  struct nonce nonce[1] = {{ 0 }};
1376
  su_md5_t md5[1];
Pekka Pessi's avatar
Pekka Pessi committed
1377 1378 1379 1380 1381 1382

  am->am_count += 3730029547U;	/* 3730029547 is a prime */

  nonce->issued = now;
  nonce->count = am->am_count;
  nonce->nextnonce = nextnonce != 0;
1383

Pekka Pessi's avatar
Pekka Pessi committed
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
  /* Calculate HMAC of nonce data */
  auth_md5_hmac_init(am, md5);
  su_md5_update(md5, nonce, offsetof(struct nonce, digest));
  auth_md5_hmac_digest(am, md5, nonce->digest, sizeof nonce->digest);

  return base64_e(buffer, bsize, nonce, sizeof(nonce));
}


/** Validate nonce parameter.
 *
 * @param am   pointer to authentication module object
 * @param as   authentication status structure [OUT]
 * @param ar   decoded authentication response from client [IN]
 * @param now  current time [IN]
 */
1400
int auth_validate_digest_nonce(auth_mod_t *am,
Pekka Pessi's avatar
Pekka Pessi committed
1401 1402 1403 1404 1405
			       auth_status_t *as,
			       auth_response_t *ar,
			       msg_time_t now)
{
  struct nonce nonce[1] = {{ 0 }};
1406
  su_md5_t md5[1];
Pekka Pessi's avatar
Pekka Pessi committed
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
  uint8_t hmac[sizeof nonce->digest];
  unsigned expires;

  /* Check nonce */
  if (!ar->ar_nonce) {
    SU_DEBUG_5(("auth_method_digest: no nonce\n"));
    return -1;
  }
  if (base64_d((void*)nonce, (sizeof nonce), ar->ar_nonce) != (sizeof nonce)) {
    SU_DEBUG_5(("auth_method_digest: too short nonce\n"));
    return -1;
  }

  /* Calculate HMAC over decoded nonce data */
  auth_md5_hmac_init(am, md5);
  su_md5_update(md5, nonce, offsetof(struct nonce, digest));
  auth_md5_hmac_digest(am, md5, hmac, sizeof hmac);

  if (memcmp(nonce->digest, hmac, sizeof nonce->digest)) {
    SU_DEBUG_5(("auth_method_digest: bad nonce\n"));
    return -1;
  }

  as->as_nonce_issued = nonce->issued;
  as->as_nextnonce = nonce->nextnonce != 0;

  expires = nonce->nextnonce ? am->am_next_exp : am->am_expires;

1435
  if (nonce->issued > now ||
Pekka Pessi's avatar
Pekka Pessi committed
1436 1437 1438 1439 1440 1441 1442
      (expires && nonce->issued + expires < now)) {
    SU_DEBUG_5(("auth_method_digest: nonce expired %lu seconds ago "
		"(lifetime %u)\n",
		now - (nonce->issued + expires), expires));
    as->as_stale = 1;
  }

1443
  if (am->am_max_ncount && ar->ar_nc) {
1444
    unsigned long nc = strtoul(ar->ar_nc, NULL, 10);
1445 1446 1447 1448 1449 1450 1451 1452

    if (nc == 0 || nc > am->am_max_ncount) {
      SU_DEBUG_5(("auth_method_digest: nonce used %s times, max %u\n",
		  ar->ar_nc, am->am_max_ncount));
      as->as_stale = 1;
    }
  }

Pekka Pessi's avatar
Pekka Pessi committed
1453 1454 1455 1456 1457
  /* We should also check cnonce, nc... */

  return 0;
}

1458

Pekka Pessi's avatar
Pekka Pessi committed
1459 1460 1461 1462 1463
/* ====================================================================== */
/* HMAC routines */
static
void auth_md5_hmac_key(auth_mod_t *am)
{
1464
  size_t i;
Pekka Pessi's avatar
Pekka Pessi committed
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
  uint8_t ipad[SU_MD5_DIGEST_SIZE];
  uint8_t opad[SU_MD5_DIGEST_SIZE];

  assert(SU_MD5_DIGEST_SIZE == sizeof am->am_master_key);

  /* Derive HMAC ipad and opad from master key */
  for (i = 0; i < sizeof am->am_master_key; i++) {
    ipad[i] = am->am_master_key[i] ^ 0x36;
    opad[i] = am->am_master_key[i] ^ 0x5C;
  }

  /* Pre-calculate sum of ipad */
  su_md5_init(&am->am_hmac_ipad);
  su_md5_update(&am->am_hmac_ipad, ipad, sizeof ipad);

  /* Pre-calculate sum of opad */
  su_md5_init(&am->am_hmac_opad);
  su_md5_update(&am->am_hmac_opad, opad, sizeof opad);
}

void auth_md5_hmac_init(auth_mod_t *am, struct su_md5_t *imd5)
{
  *imd5 = am->am_hmac_ipad;
}

1490
void auth_md5_hmac_digest(auth_mod_t *am, struct su_md5_t *imd5,
Pekka Pessi's avatar
Pekka Pessi committed
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
			  void *hmac, size_t size)
{
  uint8_t digest[SU_MD5_DIGEST_SIZE];
  su_md5_t omd5[1];

  /* inner sum */
  su_md5_digest(imd5, digest);

  *omd5 = am->am_hmac_opad;
  su_md5_update(omd5, digest, sizeof *digest);

  /* outer sum */
  if (size == sizeof digest) {
1504
    su_md5_digest(omd5, hmac);
Pekka Pessi's avatar
Pekka Pessi committed
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
  }
  else {
    su_md5_digest(omd5, digest);

    if (size > sizeof digest) {
      memset((char *)hmac + (sizeof digest), 0, size - sizeof digest);
      size = sizeof digest;
    }

    memcpy(hmac, digest, size);
  }
}

/* ====================================================================== */
/* Compatibility interface */

Pekka Pessi's avatar
Pekka Pessi committed
1521
void auth_mod_method(auth_mod_t *am,
1522 1523 1524 1525 1526 1527 1528
		     auth_status_t *as,
		     msg_auth_t *credentials,
		     auth_challenger_t const *ach)
{
  auth_mod_verify(am, as, credentials, ach);
}

Pekka Pessi's avatar
Pekka Pessi committed
1529 1530 1531 1532 1533
void auth_mod_check_client(auth_mod_t *am,
			   auth_status_t *as,
			   msg_auth_t *credentials,
			   auth_challenger_t const *ach)
{
1534
  auth_mod_verify(am, as, credentials, ach);
Pekka Pessi's avatar
Pekka Pessi committed
1535 1536 1537 1538 1539 1540 1541
}


void auth_mod_challenge_client(auth_mod_t *am,
			       auth_status_t *as,
			       auth_challenger_t const *ach)
{
Pekka Pessi's avatar
Pekka Pessi committed
1542
  auth_mod_challenge(am, as, ach);
Pekka Pessi's avatar
Pekka Pessi committed
1543
}