summaryrefslogtreecommitdiff
path: root/daemon/simple.c
blob: d51e9d965e45d293f32d227edb1613d9256f7a19 (plain)
1
2
3
4
5
6
7
8
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691

/* On some linux this is required to get crypt to show itself */
#define _XOPEN_SOURCE

#include "usuals.h"
#include "httpauthd.h"
#include "defaults.h"
#include "basic.h"
#include "digest.h"
#include "hash.h"
#include "md5.h"

#include <syslog.h>
#include <fcntl.h>
#include <unistd.h>

unsigned char g_simple_secret[DIGEST_SECRET_LEN];

#define SIMPLE_MAXLINE 256
#define BASIC_ESTABLISHED  (void*)1

/* -------------------------------------------------------------------------------
 * Structures
 */

typedef struct simple_context
{
  const char* filename;     /* The file name with the user names */
  const char* realm;        /* The realm for basic authentication */
  const char* domains;      /* Domains for which digest auth is valid */
  int cache_max;            /* Maximum number of connections at once */
  int cache_timeout;

  /* Context ----------------------------------------------------------- */
  hash_t* cache;            /* Some cached records or basic */
}
simple_context_t;

/* The defaults for the context */
static const simple_context_t simple_defaults =
{
  NULL,               /* filename */
  NULL,               /* realm */
  NULL,               /* domains */
  0,                  /* cache_max */
  0,                  /* cache_timeout */
  NULL                /* cache */
};


/* -------------------------------------------------------------------------------
 * Internal Functions
 */

static void free_hash_object(void* arg, void* val)
{
  if(val && val != BASIC_ESTABLISHED)
    free(val);
}

static digest_record_t* get_cached_digest(simple_context_t* ctx, unsigned char* nonce)
{
  digest_record_t* rec;

  ASSERT(ctx && nonce);

  if(ctx->cache_max == 0)
    return NULL;

  ha_lock(NULL);

    rec = (digest_record_t*)hash_get(ctx->cache, nonce);

    /* Just in case it's a basic :) */
    if(rec && rec != BASIC_ESTABLISHED)
      hash_rem(ctx->cache, nonce);

  ha_unlock(NULL);

  ASSERT(!rec || memcmp(nonce, rec->nonce, DIGEST_NONCE_LEN) == 0);
  return rec;
}

static int have_cached_basic(simple_context_t* ctx, unsigned char* key)
{
  int ret = 0;

  ASSERT(ctx && key);

  ha_lock(NULL);

    ret = (hash_get(ctx->cache, key) == BASIC_ESTABLISHED);

  ha_unlock(NULL);

  return ret;
}

static int save_cached_digest(simple_context_t* ctx, digest_record_t* rec)
{
  int r;

  ASSERT(ctx && rec);

  if(ctx->cache_max == 0)
    return HA_FALSE;

  ha_lock(NULL);

    while(hash_count(ctx->cache) >= ctx->cache_max)
      hash_bump(ctx->cache);

    r = hash_set(ctx->cache, rec->nonce, rec);

  ha_unlock(NULL);

  if(!r)
  {
    ha_messagex(LOG_CRIT, "out of memory");
    return HA_ERROR;
  }

  return HA_OK;
}

static int add_cached_basic(simple_context_t* ctx, unsigned char* key)
{
  int r;

  ASSERT(ctx && key);

  if(ctx->cache_max == 0)
    return HA_FALSE;

  ha_lock(NULL);

    while(hash_count(ctx->cache) >= ctx->cache_max)
      hash_bump(ctx->cache);

    r = hash_set(ctx->cache, key, BASIC_ESTABLISHED);

  ha_unlock(NULL);

  if(!r)
  {
    ha_messagex(LOG_CRIT, "out of memory");
    return HA_ERROR;
  }

  return HA_OK;
}

static int complete_digest_ha1(simple_context_t* ctx, digest_record_t* rec,
                               ha_buffer_t* buf, const char* user, int* code)
{
  FILE* f;
  int found = 0;
  char* t;
  char line[SIMPLE_MAXLINE];

  ASSERT(ctx && rec && buf && user && user[0] && code);

  f = fopen(ctx->filename, "r");
  if(!f)
  {
    ha_message(LOG_ERR, "can't open file for basic auth: %s", ctx->filename);
    *code = HA_SERVER_ERROR;
    return HA_FALSE;
  }

  /*
   * Note: There should be no returns or jumps between
   * this point and the closing of the file below.
   */

  /* Now look through the whole file */
  while(!feof(f))
  {
    fgets(line, SIMPLE_MAXLINE, f);

    if(ferror(f))
    {
      ha_message(LOG_ERR, "error reading basic password file");
      *code = HA_SERVER_ERROR;
      break;
    }

    t = strchr(line, ':');
    if(t)
    {
      /* Split the line */
      *t = 0;
      t++;

      /* Check the user */
      if(strcmp(line, user) == 0)
      {
        /* Now decode the rest of the line and see if it matches up */
        t = ha_bufdechex(buf, t, MD5_LEN);

        if(t != NULL)
        {
          memcpy(rec->ha1, t, MD5_LEN);
          found = 1;
          break;
        }

        else
        {
          if(ha_buferr(buf))
            break;

          ha_messagex(LOG_WARNING, "user '%s' found in file, but password not in digest format", user);
        }
      }
    }

    fclose(f);
  }

  if(ha_buferr(buf))
    return HA_ERROR;

  return found ? HA_FALSE : HA_OK;
}

static int validate_user_password(simple_context_t* ctx, ha_buffer_t* buf,
                                  const char* user, const char* clearpw, int* code)
{
  FILE* f;
  int found = 0;
  char line[SIMPLE_MAXLINE];
  unsigned char ha1[MD5_LEN];
  char* t;
  char* t2;

  ASSERT(ctx && buf && code);
  ASSERT(user && user[0] && clearpw);

  f = fopen(ctx->filename, "r");
  if(!f)
  {
    ha_message(LOG_ERR, "can't open file for basic auth: %s", ctx->filename);
    *code = HA_SERVER_ERROR;
    return HA_FALSE;
  }

  digest_makeha1(ha1, user, ctx->realm, clearpw);

  /*
   * Note: There should be no returns or jumps between
   * this point and the closing of the file below.
   */

  /* Now look through the whole file */
  while(!feof(f))
  {
    fgets(line, SIMPLE_MAXLINE, f);

    if(ferror(f))
    {
      ha_message(LOG_ERR, "error reading basic password file");
      *code = HA_SERVER_ERROR;
      break;
    }

    t = strchr(line, ':');
    if(t)
    {
      /* Split the line */
      *t = 0;
      t++;

      /* Check the user */
      if(strcmp(line, user) == 0)
      {
        /* We can validate against an ha1, so check if it decodes as one */
        t2 = ha_bufdechex(buf, t, MD5_LEN);

        if(t2 && memcmp(ha1, t2, MD5_LEN) == 0)
        {
          memcpy(ha1, t2, MD5_LEN);
          found = 1;
          break;
        }

        /* Otherwise we try a nice crypt style password */
        else
        {
          /* Not sure if crypt is thread safe so we lock */
          ha_lock();

            /* Check the password */
            if(strcmp(crypt(clearpw, t), t) == 0)
              found = 1;

          ha_unlock();

          if(found)
            break;
        }

        if(ha_buferr(buf))
          break;
      }
    }

    fclose(f);
  }

  if(ha_buferr(buf))
    return HA_ERROR;

  return found ? HA_FALSE : HA_OK;
}

static int simple_basic_response(simple_context_t* ctx, const char* header,
                          ha_response_t* resp, ha_buffer_t* buf)
{
  basic_header_t basic;
  int ret = HA_FALSE;
  int found = 0;
  int r;

  ASSERT(buf && header && resp && buf);

  if(basic_parse(header, buf, &basic) == HA_ERROR)
    return HA_ERROR;

  /* Past this point we don't return directly */

  /* Check and see if this connection is in the cache */
  if(have_cached_basic(ctx, basic.key))
  {
    found = 1;
    ret = HA_OK;
    goto finally;
  }

  /* If we have a user name and password */
  if(!basic.user || !basic.user[0] ||
     !basic.password || !basic.password[0])
    goto finally;


  ret = validate_user_password(ctx, buf, basic.user, basic.password, &(resp->code));

finally:

  if(resp->code == HA_SERVER_ACCEPT)
  {
    resp->detail = basic.user;

    /* We put this connection into the successful connections */
    ret = add_cached_basic(ctx, basic.key);
  }

  return ret;
}

static int simple_digest_challenge(simple_context_t* ctx, ha_response_t* resp,
                            ha_buffer_t* buf, int stale)
{
  unsigned char nonce[DIGEST_NONCE_LEN];
  const char* header;

  ASSERT(ctx && resp && buf);

  /* Generate an nonce */
  digest_makenonce(nonce, g_simple_secret, NULL);

  /* Now generate a message to send */
  header = digest_challenge(buf, nonce, ctx->realm, ctx->domains, stale);

  if(!header)
    return HA_ERROR;

  /* And append it nicely */
  resp->code = HA_SERVER_DECLINE;
  ha_addheader(resp, "WWW-Authenticate", header);

  return HA_OK;
}

static int simple_digest_response(simple_context_t* ctx, const char* header,
                           const char* method, const char* uri,
                           ha_response_t* resp, ha_buffer_t* buf)
{
  unsigned char nonce[DIGEST_NONCE_LEN];
  digest_header_t dg;
  digest_record_t* rec = NULL;
  const char* t;
  time_t expiry;
  int ret = HA_FALSE;
  int stale = 0;
  int r;

  ASSERT(ctx && header && method && uri && resp && buf);

  /* We use this below to send a default response */
  resp->code = -1;

  if(digest_parse(header, buf, &dg, nonce) == HA_ERROR)
    return HA_ERROR;

  r = digest_checknonce(nonce, g_simple_secret, &expiry);
  if(r != HA_OK)
  {
    if(r == HA_FALSE)
      ha_messagex(LOG_WARNING, "digest response contains invalid nonce");

    ret = r;
    goto finally;
  }

  rec = get_cached_digest(ctx, nonce);

  /* Check to see if we're stale */
  if((expiry + ctx->cache_timeout) <= time(NULL))
  {
    stale = 1;
    goto finally;
  }

  if(!rec)
  {
    /*
     * If we're valid but don't have a record in the
     * cache then complete the record properly.
     */

    rec = digest_makerec(nonce, dg.username);
    if(!rec)
    {
      ret = HA_ERROR;
      goto finally;
    }

    r = complete_digest_ha1(ctx, rec, buf, dg.username, &(resp->code));
    if(r != HA_OK)
    {
      ret = r;
      goto finally;
    }
  }

  /* Increment our nonce count */
  rec->nc++;

  ret = digest_check(ctx->realm, method, uri, buf, &dg, rec);

  if(ret == HA_OK)
  {
    resp->code = HA_SERVER_ACCEPT;
    resp->detail = dg.username;

    /* Figure out if we need a new nonce */
    if((expiry + (ctx->cache_timeout - (ctx->cache_timeout / 8))) < time(NULL))
    {
      digest_makenonce(nonce, g_simple_secret, NULL);
      stale = 1;
    }

    t = digest_respond(buf, &dg, rec, stale ? nonce : NULL);
    if(!t)
    {
      ret = HA_ERROR;
      goto finally;
    }

    if(t[0])
      ha_addheader(resp, "Authentication-Info", t);

    /* Put the connection into the cache */
    if(save_cached_digest(ctx, rec) == HA_ERROR)
      ret = HA_ERROR;
    else
      rec = NULL;
  }

finally:

  /* If the record wasn't stored away then free it */
  if(rec)
    free(rec);

  /* If nobody above responded then challenge the client again */
  if(resp->code == -1)
    return simple_digest_challenge(ctx, resp, buf, stale);

  return ret;
}


/* -------------------------------------------------------------------------------
 * Handler Functions
 */

int simple_config(ha_context_t* context, const char* name, const char* value)
{
  simple_context_t* ctx = (simple_context_t*)(context->data);

  ASSERT(name && name[0] && value && value[0]);

  if(strcmp(name, "passwordfile") == 0)
  {
    ctx->filename = value;
    return HA_OK;
  }

  else if(strcmp(name, "realm") == 0)
  {
    ctx->realm = value;
    return HA_OK;
  }

  else if(strcmp(name, "digestdomains") == 0)
  {
    ctx->domains = value;
    return HA_OK;
  }

  return HA_FALSE;
}

int simple_init(ha_context_t* context)
{
  /* Global initialization */
  if(!context)
  {
    return ha_genrandom(g_simple_secret, DIGEST_SECRET_LEN);
  }

  /* Context specific initialization */
  else
  {
    simple_context_t* ctx = (simple_context_t*)(context->data);
    int fd;

    ASSERT(ctx);

    /* Make sure there are some types of authentication we can do */
    if(!(context->types & (HA_TYPE_BASIC | HA_TYPE_DIGEST)))
    {
      ha_messagex(LOG_ERR, "Simple module configured, but does not implement any "
                           "configured authentication type.");
      return HA_ERROR;
    }


    /* Check to make sure the file exists */
    if(!ctx->filename)
    {
      ha_messagex(LOG_ERR, "Basic configuration incomplete. "
                           "Must have a PasswordFile configured.");
      return HA_ERROR;
    }

    fd = open(ctx->filename, O_RDONLY);
    if(fd == -1)
    {
      ha_message(LOG_ERR, "can't open file for simple authentication: %s", ctx->filename);
      return HA_ERROR;
    }

    close(fd);

    ASSERT(!ctx->cache);

    /* The cache for digest records and basic */
    if(!(ctx->cache = hash_create(MD5_LEN, free_hash_object, NULL)))
    {
      ha_messagex(LOG_CRIT, "out of memory");
      return HA_ERROR;
    }

    /* Copy some settings over for easy access */
    ctx->cache_max = context->cache_max;
    ctx->cache_timeout = context->cache_timeout;

  }

  return HA_OK;
}

void simple_destroy(ha_context_t* context)
{
  /* Per context destroy */
  if(context)
  {
    /* Note: We don't need to be thread safe here anymore */
    simple_context_t* ctx = (simple_context_t*)(context->data);

    if(ctx->cache)
      hash_free(ctx->cache);
  }
}

int simple_process(ha_context_t* context, ha_request_t* req,
                 ha_response_t* resp, ha_buffer_t* buf)
{
  simple_context_t* ctx = (simple_context_t*)(context->data);
  const char* header;
  int ret = HA_FALSE;
  int found = 0;
  basic_header_t basic;

  ASSERT(context && req && resp && buf);
  ASSERT(req->args[AUTH_ARG_METHOD]);
  ASSERT(req->args[AUTH_ARG_URI]);

  ha_lock(NULL);

    /* Purge the cache */
    hash_purge(ctx->cache, time(NULL) - ctx->cache_timeout);

  ha_unlock(NULL);


  /* We use this below to detect whether to send a default response */
  resp->code = -1;


  /* Check the headers and see if we got a response thingy */
  if(context->types & HA_TYPE_DIGEST)
  {
    header = ha_getheader(req, "Authorization", HA_PREFIX_DIGEST);
    if(header)
    {
      ret = simple_digest_response(ctx, header, req->args[AUTH_ARG_METHOD],
                            req->args[AUTH_ARG_URI], resp, buf);
      if(ret == HA_ERROR)
        return ret;
    }
  }

  /* Or a basic authentication */
  if(!header && context->types & HA_TYPE_BASIC)
  {
    header = ha_getheader(req, "Authorization", HA_PREFIX_BASIC);
    if(header)
    {
      ret = simple_basic_response(ctx, header, resp, buf);
      if(ret == HA_ERROR)
        return ret;
    }
  }


  /* Send a default response if that's what we need */
  if(resp->code == -1)
  {
    resp->code = HA_SERVER_DECLINE;

    if(context->types & HA_TYPE_DIGEST)
    {
      ret = simple_digest_challenge(ctx, resp, buf, 0);
      if(ret == HA_ERROR)
        return ret;
    }

    if(context->types & HA_TYPE_BASIC)
    {
      ha_bufmcat(buf, "BASIC realm=\"", ctx->realm , "\"", NULL);

      if(ha_buferr(buf))
        return HA_ERROR;

      ha_addheader(resp, "WWW-Authenticate", ha_bufdata(buf));
    }
  }

  return ret;
}


/* -------------------------------------------------------------------------------
 * Handler Definition
 */

ha_handler_t simple_handler =
{
  "SIMPLE",                /* The type */
  simple_init,             /* Initialization function */
  simple_destroy,          /* Uninitialization routine */
  simple_config,           /* Config routine */
  simple_process,          /* Processing routine */
  &simple_defaults,        /* A default context */
  sizeof(simple_context_t) /* Size of the context */
};