mod_sso.c 33.3 KB
Newer Older
ale's avatar
ale committed
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
/* Copyright (c) 2012 Autistici/Inventati <info@autistici.org>
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <stdio.h>

#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"
#include "http_main.h"
#include "ap_config.h"
#include "apr_strings.h"
//#include "apr_escape.h"

#include "mod_sso.h"

40
41
42
43
44
#if MODULE_MAGIC_NUMBER_MAJOR >= 20100714
#define SSO_REQUIRE_NAME "sso"
#include "mod_auth.h"
#endif

ale's avatar
ale committed
45
46
47
48
49
50
51
52
53
extern module AP_MODULE_DECLARE_DATA sso_module;

typedef struct {
  const char *login_server;
  const char *domain;
  const char *service;

  // Note: public_key is a binary buffer (non zero-terminated).
  const unsigned char *public_key;
54
55
56

  // All known groups.
  apr_array_header_t *groups;
ale's avatar
ale committed
57
58
} modsso_config;

59
60
61
62
typedef struct {
  apr_array_header_t *user_groups;
} modsso_request_notes;

ale's avatar
ale committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
typedef const char *(*CMD_HAND_TYPE) ();

/**
 * Create a modsso_config structure.
 *
 * @param p APR allocation pool.
 * @param s unused.
 * @return a newly allocated modsso_config with default values.
 */
static void *create_modsso_config(apr_pool_t *p, char *s)
{
  // This module's configuration structure.
  modsso_config *newcfg;

  // Allocate memory from the provided pool.
  newcfg = (modsso_config *)apr_palloc(p, sizeof(modsso_config));

  // Set default values.
  newcfg->login_server = NULL;
  newcfg->service = NULL;
  newcfg->domain = NULL;
  newcfg->public_key = NULL;
85
86
  newcfg->groups = NULL;
  
ale's avatar
ale committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
  // Return the created configuration struct.
  return (void *)newcfg;
}

static void *merge_modsso_config(apr_pool_t *p, void *base, void *add)
{
  modsso_config *cbase = (modsso_config *)base;
  modsso_config *cadd = (modsso_config *)add;
  modsso_config *newcfg = 
    (modsso_config *)apr_palloc(p, sizeof(modsso_config));

  newcfg->login_server = cadd->login_server ? cadd->login_server : cbase->login_server;
  newcfg->service = cadd->service ? cadd->service : cbase->service;
  newcfg->domain = cadd->domain ? cadd->domain : cbase->domain;
  newcfg->public_key = cbase->public_key;
  if (cadd->public_key) {
    newcfg->public_key = cadd->public_key;
104
105
106
107
  }

  // Groups are not merged, last takes precedence (if set).
  newcfg->groups = cadd->groups ? cadd->groups : cbase->groups;
ale's avatar
ale committed
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

  return (void *)newcfg;
}

static const char *set_modsso_login_server(cmd_parms *parms,
					   void *mconfig, const char *arg)
{
  modsso_config *s_cfg = (modsso_config *)mconfig;
  s_cfg->login_server = arg;
  return NULL;
}

static const char *set_modsso_service(cmd_parms *parms, void *mconfig, const char *arg)
{
  modsso_config *s_cfg = (modsso_config *)mconfig;
  s_cfg->service = arg;
  return NULL;
}

static const char *set_modsso_domain(cmd_parms *parms, void *mconfig, const char *arg)
{
  modsso_config *s_cfg = (modsso_config *)mconfig;
  s_cfg->domain = arg;
  return NULL;
}

static const char *set_modsso_public_key_file(cmd_parms *parms, void *mconfig, const char *arg)
{
  modsso_config *s_cfg = (modsso_config *)mconfig;
  char buf[128];
  apr_size_t n = sizeof(buf);
  apr_file_t *file;
  int status;

  if (apr_file_open(&file, arg, APR_FOPEN_READ, 0, parms->pool) != APR_SUCCESS) {
    return "Could not open SSOPublicKeyFile";
  }
  status = apr_file_read(file, (void *)buf, &n);
  apr_file_close(file);
  if (status != APR_SUCCESS) {
    return "Could not read contents of SSOPublicKeyFile";
  }

  unsigned char *key = (unsigned char *)apr_palloc(parms->pool, n);
  memcpy(key, buf, n);
  s_cfg->public_key = key;

  return NULL;
}

158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
static apr_array_header_t *parse_commasep_groups(apr_pool_t *pool, const char *commaseplist) {
  apr_array_header_t *arr = apr_array_make(pool, 1, sizeof(const char *));
  char *tokenizerCtx = NULL, *group;
  char *tmp = apr_pstrdup(pool, commaseplist);
  group = apr_strtok(tmp, ",", &tokenizerCtx);
  do {
    *(const char **)apr_array_push(arr) = group;
    group = apr_strtok(NULL, ",", &tokenizerCtx);
  } while (group != NULL);
  return arr;
}

static const char *set_modsso_groups(cmd_parms *parms, void *mconfig, const char *arg)
{
  modsso_config *s_cfg = (modsso_config *)mconfig;
ale's avatar
ale committed
173
  s_cfg->groups = parse_commasep_groups(parms->pool, arg);
174
175
176
  return NULL;
}

ale's avatar
ale committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
static const command_rec mod_sso_cmds[] =
{
  AP_INIT_TAKE1("SSOLoginServer", (CMD_HAND_TYPE) set_modsso_login_server, 
		NULL, OR_ALL,
		"SSOLoginServer (string) URL of the login server."),
  AP_INIT_TAKE1("SSOService", (CMD_HAND_TYPE) set_modsso_service, 
		NULL, OR_ALL,
		"SSOService (string) SSO Service"),
  AP_INIT_TAKE1("SSODomain", (CMD_HAND_TYPE) set_modsso_domain, 
		NULL, OR_ALL,
		"SSODomain (string) SSO Domain"),
  AP_INIT_TAKE1("SSOPublicKeyFile", (CMD_HAND_TYPE) set_modsso_public_key_file, 
		NULL, RSRC_CONF,
		"SSOPublicKeyFile (string) Location of the login server public key"),
191
192
193
  AP_INIT_TAKE1("SSOGroups", (CMD_HAND_TYPE) set_modsso_groups,
                NULL, RSRC_CONF,
                "SSOGroups (string) comma-separated list of all the groups that we might want to check membership for"),
ale's avatar
ale committed
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
  {NULL}
};

/**
 * Send the given text to the client.
 *
 * Creates a response with status 200 OK and a Content-Type of text/html.
 *
 * @param r Pointer to the request_rec structure.
 * @param s Body of the response.
 */
static int http_sendstring(request_rec *r, const char *s) {
  conn_rec *c = r->connection;
  apr_bucket *b;
  apr_bucket_brigade *bb = apr_brigade_create(r->pool, c->bucket_alloc);
  b = apr_bucket_transient_create(s, strlen(s), c->bucket_alloc);
  APR_BRIGADE_INSERT_TAIL(bb, b);
  b = apr_bucket_eos_create(c->bucket_alloc);
  APR_BRIGADE_INSERT_TAIL(bb, b);
  
  ap_set_content_type(r, "text/html");
  if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS)
    return HTTP_INTERNAL_SERVER_ERROR;
  return OK;
}

/**
 * Return a redirect response to the client.
 *
 * @param r Pointer to the request_rec structure.
 * @param location URL to redirect to.
 */
static int http_redirect(request_rec *r, const char *location) {
  apr_table_set(r->headers_out, "Location", location);
  apr_table_setn(r->headers_out, "Cache-Control", "no-cache");
  return HTTP_MOVED_TEMPORARILY;
}

/**
 * Get the full URI of the request_rec's request location.
 *
 * NOTE: the protocol is always forced to https.
 *
 * @param r Pointer to the request_rec structure.
 * @param service_host Host part of the SSO service.
 */
static char *full_uri(request_rec *r, const char *service_host) {
  char *result = apr_pstrcat(r->pool,
                             "https://",
                             service_host,
                             r->uri,
                             NULL);
  if (r->args) {
    result = apr_pstrcat(r->pool,
                         result,
                         "?",
                         r->args,
                         NULL);
  }
  return result;
}

/**
 * Check if a redirection url is valid for our service.
 *
 * Also check for presence of some forbidden characters.
 *
 * @param redir Destination URL of the redirection.
 * @param service SSO service.
 * @return true if the redirection is valid.
 */
static int is_valid_redir(request_rec *r,
                          const char *redir,
                          const char *service) {
  const char *c;
  char *prefix = apr_pstrcat(r->pool,
                             "https://",
                             service,
                             NULL);
  if (strlen(redir) < strlen(prefix)) {
    return 0;
  }
  if (strncmp(redir, prefix, strlen(prefix)) != 0) {
    return 0;
  }
  for (c = redir; *c; c++) {
    if (*c < 32 || *c == ';') 
      return 0;
  }
  return 1;
}

/**
 * Read the value of a cookie.
 *
 * @param r Pointer to the request_rec structure.
 * @param cookie_name Name of the cookie to retrieve.
 * @return the cookie value, or an empty string if no cookie was found.
 */
static char *get_cookie(request_rec *r, const char *cookie_name) {
294
295
  char *rv = NULL, *cookies, *cookie, *tokenizerCtx = NULL;
  int cookie_name_len = strlen(cookie_name);
296
  
ale's avatar
ale committed
297
298
  const char *cookies_c = apr_table_get(r->headers_in, "Cookie");
  if (cookies_c == NULL) {
299
    return NULL;
ale's avatar
ale committed
300
  }
301

302
303
304
305
  // Make a copy of the Cookie header so that we can modify it
  // (tokenization is destructive).
  cookies = apr_pstrdup(r->pool, cookies_c);
  cookie = apr_strtok(cookies, ";", &tokenizerCtx);
306
307
308
309
310
311
  do {
    while (cookie != NULL && *cookie == ' ')
      cookie++;
    if (strncmp(cookie, cookie_name, cookie_name_len) == 0) {
      cookie += (cookie_name_len + 1);
      rv = apr_pstrdup(r->pool, cookie);
ale's avatar
ale committed
312
313
      break;
    }
314
315
316
    cookie = apr_strtok(NULL, ";", &tokenizerCtx);
  } while (cookie != NULL);
  return rv;
ale's avatar
ale committed
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
}

char *get_cookie_name(request_rec *r) {
  char *cookie_name;
  const char *auth_name = ap_auth_name(r);
  if (auth_name) {
    cookie_name = apr_pstrcat(r->pool,
                              "SSO_",
                              auth_name,
                              NULL);
  } else {
    cookie_name = "SSO";
  }
  return cookie_name;
}

// Parse the service spec
static int parse_service(request_rec *r,
                         modsso_config *s_cfg,
                         const char **service,
                         const char **service_host, 
                         const char **service_path) {
  char *svc;

  // Make sure the service ends with a slash.
  if (s_cfg->service != NULL && s_cfg->service[strlen(s_cfg->service) - 1] != '/') {
    svc = apr_pstrcat(r->pool, s_cfg->service, "/", NULL);
  } else {
    svc = apr_pstrdup(r->pool, s_cfg->service);
  }

  *service = apr_pstrdup(r->pool, svc);

  // If a service name is configured (including the host), we
  // just split it on the first slash.
  if (svc[0] != '/') {
    char *slash = strchr(svc, '/');
    if (slash) {
      *slash++ = '\0';
    }
    *service_host = apr_pstrdup(r->pool, svc);
    *service_path = apr_pstrcat(r->pool, "/", slash, NULL);
    return 0;
  }

  // A relative or empty service name means we have to autodetect
  // the host (and port) part.
  *service_path = apr_pstrdup(r->pool, svc);

  const char *host_hdr = apr_table_get(r->headers_in, "Host");
  if (!host_hdr) {
    if (!r->server->defn_name) {
      *service = "error";
      ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
		   "sso: SSOService could not be determined");
      return -1;
    }
    *service_host = r->server->defn_name;
    int port = ap_get_server_port(r);
    if (port > 0 && port != 80 && port != 443) {
      *service_host = apr_pstrcat(r->pool, *service_host, ":", apr_ltoa(r->pool, port), NULL);
    }
  } else {
    *service_host = host_hdr;
  }
  *service = apr_pstrcat(r->pool, *service_host, *service_path, NULL);
  ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
               "sso: SSOService automatically determined: %s", *service);
  return 0;
}

static int check_config(request_rec *r, modsso_config *s_cfg)
{
  if (!s_cfg->login_server) {
    ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
                 "sso: SSOLoginServer is not defined!");
    return 0;
  }
  if (!s_cfg->service) {
    ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
                 "sso: SSOService is not defined!");
    return 0;
  }
  if (!s_cfg->domain) {
    ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
                 "sso: SSODomain is not defined!");
    return 0;
  }
  if (!s_cfg->public_key) {
    ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
                 "sso: SSOPublicKeyFile is not defined!");
    return 0;
  }
  return 1;
}

/**
 * Apache method handler for mod_sso.
 *
 * @param r Pointer to the request_rec structure.
 */
static int mod_sso_method_handler(request_rec *r)
{
  const char *uri, *type, *sso_cookie_name;
  const char *service = NULL, *service_host = NULL,
    *service_path = NULL;
  char *sso_logout_path, *sso_login_path;

  // Get the module configuration
  modsso_config *s_cfg = (modsso_config *)
     ap_get_module_config(r->per_dir_config, &sso_module);
  uri = r->uri;

430
431
  ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
      "sso: handler \"%s\"", r->handler);
432

ale's avatar
ale committed
433
434
435
  // Return immediately if there's nothing to do (check the AuthType)
  type = ap_auth_type(r);
  if (!type || strcasecmp(type, "SSO") != 0) {
436
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
437
       "sso: invalid authentication type \"%s\"", type);
ale's avatar
ale committed
438
439
440
441
442
    return DECLINED;
  }

  sso_cookie_name = get_cookie_name(r);

443
444
445
  ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
     "sso: cookie_name \"%s\"", sso_cookie_name);

ale's avatar
ale committed
446
447
448
449
450
451
452
453
  // Check if the required parameters are defined.
  if (!check_config(r, s_cfg)) {
    return HTTP_INTERNAL_SERVER_ERROR;
  }

  // Parse the service into host/path (guess it if not specified).
  if (parse_service(r, s_cfg, &service, &service_host, &service_path) != 0) {
    ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
454
455
       "sso: could not parse service \"%s\"",
       s_cfg->service);
ale's avatar
ale committed
456
457
458
459
460
    return HTTP_BAD_REQUEST;
  }

  // Handle /sso_logout
  sso_logout_path = apr_pstrcat(r->pool, service_path, "sso_logout", NULL);
461
462
  ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
   "sso: logout? \"%s\" \"%s\"", sso_logout_path, uri);
ale's avatar
ale committed
463
464
465
466
467
468
469
  if (!strcmp(uri, sso_logout_path)) {
    modsso_del_cookie(r, sso_cookie_name);
    return http_sendstring(r, "OK");
  }

  // Handle /sso_login
  sso_login_path = apr_pstrcat(r->pool, service_path, "sso_login", NULL);
470
471
  ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
   "sso: login? \"%s\" \"%s\"", sso_login_path, uri);
ale's avatar
ale committed
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
  if (!strcmp(uri, sso_login_path)) {
    struct modsso_params params;
    char *redir;

    if (!r->args) {
      ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
		   "sso: invalid sso_login request (no query args)");
      return HTTP_BAD_REQUEST;
    }

    // Parse query params
    if (modsso_parse_query_string(r->pool, r->args, &params) < 0) {
      ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
                   "sso: invalid parameters for sso_login: %s",
                   r->args);
      return HTTP_BAD_REQUEST;
    }

    modsso_set_cookie(r, sso_cookie_name, params.t, service_path);
    
    redir = modsso_url_decode(r->pool, params.d);
    if (!is_valid_redir(r, redir, service)) {
      ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
                   "sso: invalid redirect to %s", redir);
      return HTTP_BAD_REQUEST;
    } else {
      return http_redirect(r, redir);
    }
  }

  return DECLINED;
}

struct modsso_auth_req {
  apr_array_header_t *groups;
  apr_array_header_t *users;
  int any_user;
};

511
#if MODULE_MAGIC_NUMBER_MAJOR < 20100714
ale's avatar
ale committed
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
static int array_contains(apr_array_header_t *arr, const char *s)
{
  int i;
  if (arr == NULL) {
    return 0;
  }
  for (i = 0; i < arr->nelts; i++) {
    if (!strcmp(s, ((const char **)arr->elts)[i])) {
      return 1;
    }
  }
  return 0;
}

/*
 * Parse the authorization requirements. The following 'require' directives
 * are understood:
 *
 *    require valid-user        Any authenticated user (the default).
 *    require group <name>      Members of this group are allowed in.
 *    require user <name>       This particular user is allowed in.
 *
 * No 'require' directive is equivalent to 'require valid-user'.
 */
static void mod_sso_parse_requirements(request_rec *r,
                                       struct modsso_auth_req *auth)
{
  const apr_array_header_t *reqs_arr = ap_requires(r);
  require_line *reqs;
  int i, m;

  auth->groups = auth->users = NULL;
  auth->any_user = 0;

  if (!reqs_arr) {
    return;
  }

  reqs = (require_line *)reqs_arr->elts;
  m = r->method_number;
  for (i = 0; i < reqs_arr->nelts; i++) {
    const char *t, *w;
    if (!(reqs[i].method_mask & (AP_METHOD_BIT << m)))
      continue;
    t = reqs[i].requirement;
    w = ap_getword_white(r->pool, &t);
    if (!strcmp(w, "group")) {
      const char *group_name = ap_getword_conf(r->pool, &t);
      ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
                   "required group '%s'", group_name);
      if (auth->groups == NULL) {
        auth->groups = apr_array_make(r->pool, 1, sizeof(const char *));
      }
      *(const char **)apr_array_push(auth->groups) = group_name;
    } else if (!strcmp(w, "user")) {
      const char *user_name = ap_getword_conf(r->pool, &t);
      if (auth->users == NULL) {
        auth->users = apr_array_make(r->pool, 1, sizeof(const char *));
      }
      *(const char **)apr_array_push(auth->users) = user_name;
      auth->any_user = 0;
    } else if (!strcmp(w, "valid-user")) {
      auth->any_user = 1;
    } else {
      ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
		   "unknown require directive '%s'", w);
    }
  }

  /* We need to make the groups array compatible with what
   * sso_validate_ticket expects: a NULL-terminated char ** array. To do
   * so, just add a NULL at the end of it.
   */
  if (auth->groups != NULL) {
    *(const char **)apr_array_push(auth->groups) = NULL;
  }
}
589
#endif
ale's avatar
ale committed
590
591
592

static char *encode_groups(apr_pool_t *p, apr_array_header_t *groups)
{
ale's avatar
ale committed
593
 /**
ale's avatar
ale committed
594
595
596
  apr_array_header_t *arr = apr_array_make(p, (groups->nelts - 1) * 2 - 1, sizeof(const char *));
  int i;

ale's avatar
ale committed
597
  for (i = 0; i < groups->nelts; i++) {
ale's avatar
ale committed
598
599
600
601
602
603
    if (i > 0) {
      *(const char **)apr_array_push(arr) = ",";
    }
    *(const char **)apr_array_push(arr) = ((const char **)groups->elts)[i];
  }
  return apr_array_pstrcat(p, arr, 0);
ale's avatar
ale committed
604
605
 **/
  return apr_array_pstrcat(p, groups, ',');
ale's avatar
ale committed
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
}

static int redirect_to_login_server(request_rec *r,
                                    const char *login_server,
                                    const char *service_host,
                                    const char *service,
                                    apr_array_header_t *groups)
{
  char *dest, *login_url;
  dest = full_uri(r, service_host);
  login_url = apr_pstrcat(r->pool,
                          "https://", login_server,
                          "/?s=",
                          modsso_url_encode(r->pool, service),
                          "&d=",
                          modsso_url_encode(r->pool, dest),
                          NULL);
  if (!apr_is_empty_array(groups)) {
    login_url = apr_pstrcat(r->pool,
                            login_url,
                            "&g=",
                            encode_groups(r->pool, groups),
                            NULL);
  }
  ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
               "sso: unauthorized access to %s", dest);
632
633
  ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
               "sso: redirecting to %s", login_url);
ale's avatar
ale committed
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
  return http_redirect(r, login_url);
}

static char *pkey_to_string(const unsigned char *pkey, char *buf) {
  static const char *hex = "0123456789ABCDEF";
  char *o = buf;
  int i;
  for (i = 0; i < 32; i++) {
    unsigned char c = *pkey++;
    *o++ = hex[(c & 0xf0) >> 4];
    *o++ = hex[c & 0x0f];
  }
  *o = '\0';
  return buf;
}

/**
 * Apache authentication handler for mod_sso.
 *
 * @param r Pointer to the request_rec structure.
 */
godog's avatar
godog committed
655
#if MODULE_MAGIC_NUMBER_MAJOR >= 20100714
656
static int mod_sso_check_access_ex(request_rec *r)
godog's avatar
godog committed
657
{
658
  const char *type, *uri;
godog's avatar
godog committed
659
  const char *sso_login_path, *sso_logout_path;
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
692
693
  const char *service = NULL, *service_host = NULL,
    *service_path = NULL;
  modsso_config *s_cfg = (modsso_config *)
    ap_get_module_config(r->per_dir_config, &sso_module);

  type = ap_auth_type(r);
  if (type == NULL || apr_strnatcasecmp(type, "sso") != 0) {
    return DECLINED;
  }

  // Check if the required parameters are defined.
  if (!check_config(r, s_cfg)) {
    return HTTP_INTERNAL_SERVER_ERROR;
  }

  uri = r->uri;

  if (parse_service(r, s_cfg, &service, &service_host, &service_path) != 0) {
    ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
         "sso (check_access_ex): could not parse service (cfg->service=%s)",
         s_cfg->service);
    return HTTP_BAD_REQUEST;
  }

  // Everyone is allowed access to /sso_login and /sso_logout
  sso_logout_path = apr_pstrcat(r->pool, service_path, "sso_logout", NULL);
  sso_login_path = apr_pstrcat(r->pool, service_path, "sso_login", NULL);
  if (!strcmp(uri, sso_logout_path) || !strcmp(uri, sso_login_path)) {
    return OK;
  }

  return DECLINED;
}

ale's avatar
ale committed
694
695
696
697
698
699
700
701
702
703
704
static char *parse_ticket_groups(apr_pool_t *pool, char **groups) {
  apr_array_header_t *arr = apr_array_make(pool, 1, sizeof(char *));
  if (groups) {
    while (*groups) {
      *(char **)apr_array_push(arr) = apr_pstrdup(pool, *groups);
      groups++;
    }
  }
  return apr_array_pstrcat(pool, arr, ',');
}

705
706
707
static int mod_sso_check_user_id(request_rec *r)
{
  const char *type, *sso_cookie_name, *sso_cookie;
godog's avatar
godog committed
708
709
710
711
712
  const char *service = NULL, *service_host = NULL,
    *service_path = NULL;
  int retval, err, do_redirect = 1;
  modsso_config *s_cfg = (modsso_config *)
    ap_get_module_config(r->per_dir_config, &sso_module);
ale's avatar
ale committed
713
  //apr_array_header_t *sso_validate_groups = NULL;
godog's avatar
godog committed
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731

  type = ap_auth_type(r);
  if (type == NULL || apr_strnatcasecmp(type, "sso") != 0) {
    return DECLINED;
  }

  // If this is a sub-request, pass existing credentials, if any.
  if (!ap_is_initial_req(r)) {
    if (r->main != NULL) {
      r->user = r->main->user;
    } else if (r->prev != NULL) {
      r->user = r->prev->user;
    }
    if (r->user != NULL) {
      return OK;
    }
  }

732
733
734
  ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
       "sso (check_user_id): handler '%s' uri '%s'", r->handler, r->uri);

godog's avatar
godog committed
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
  sso_cookie_name = get_cookie_name(r);

  // Check if the required parameters are defined.
  if (!check_config(r, s_cfg)) {
    return HTTP_INTERNAL_SERVER_ERROR;
  }

  if (parse_service(r, s_cfg, &service, &service_host, &service_path) != 0) {
    ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
         "sso (check_user_id): could not parse service (cfg->service=%s)",
         s_cfg->service);
    return HTTP_BAD_REQUEST;
  }

  // Test for valid cookie
  sso_cookie = get_cookie(r, sso_cookie_name);
  if (sso_cookie != NULL) {
    sso_ticket_t t;

    // Print some debugging information about the service
    {
      char pkeybuf[512];
      const char *host_hdr = apr_table_get(r->headers_in, "Host");
      if (!host_hdr) {
        host_hdr = "null";
      }
      ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
         "sso request: uri=%s, service=%s, orig=%s, host=%s, tkt=%s, pkey=%s",
         r->uri, service, s_cfg->service, host_hdr, sso_cookie,
         pkey_to_string(s_cfg->public_key, pkeybuf));
    }

    err = sso_ticket_open(&t, sso_cookie, s_cfg->public_key);
    if (err != SSO_OK) {
      ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
                   "sso: ticket decoding error: %s", sso_strerror(err));
    } else {
ale's avatar
ale committed
772
773
774
775
776
      // TODO: remove this so as to skip group membership check in sso_validate.
      /* if (s_cfg->groups != NULL) { */
      /*   sso_validate_groups = apr_array_copy(r->pool, s_cfg->groups); */
      /*   *(const char **)apr_array_push(sso_validate_groups) = NULL; */
      /* } */
777
778

      err = sso_validate(t, s_cfg->service, s_cfg->domain,
ale's avatar
ale committed
779
780
                         //apr_is_empty_array(s_cfg->groups) ? NULL : (const char **)sso_validate_groups
                         NULL);
godog's avatar
godog committed
781
782
783
784
      if (err != SSO_OK) {
        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
                     "sso: validation error: %s", sso_strerror(err));
      } else {
ale's avatar
ale committed
785
        apr_table_setn(r->notes, "SSO_GROUPS", parse_ticket_groups(r->pool, t->groups));
786
787
788
789
790
791
792
        apr_table_setn(r->subprocess_env, "SSO_SERVICE",
                       apr_pstrdup(r->pool, service));
        r->user = apr_pstrdup(r->pool, t->user);
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
                     "sso: authorized user '%s'",
                     r->user);
        retval = OK;
godog's avatar
godog committed
793
        do_redirect = 0;
794
      }
ale's avatar
ale committed
795
      sso_ticket_free(t);
godog's avatar
godog committed
796
797
798
799
800
801
802
803
    }
  }

  if (!do_redirect) {
    return retval;
  }

  // Redirect to login server
804
  return redirect_to_login_server(r, s_cfg->login_server, service_host, service, s_cfg->groups);
godog's avatar
godog committed
805
806
}
#else
ale's avatar
ale committed
807
static int mod_sso_check_user_id(request_rec *r)
ale's avatar
ale committed
808
809
810
811
812
813
814
815
816
817
818
{
  const char *type, *sso_cookie_name, *sso_cookie, *uri;
  const char *sso_login_path, *sso_logout_path;
  const char *service = NULL, *service_host = NULL,
    *service_path = NULL;
  struct modsso_auth_req auth;
  int retval, err, do_redirect = 1;
  modsso_config *s_cfg = (modsso_config *)
    ap_get_module_config(r->per_dir_config, &sso_module);

  type = ap_auth_type(r);
ale's avatar
ale committed
819
  if (type == NULL || apr_strnatcasecmp(type, "sso") != 0) {
ale's avatar
ale committed
820
821
822
    return DECLINED;
  }

ale's avatar
ale committed
823
824
825
826
827
828
829
830
831
832
833
834
  // If this is a sub-request, pass existing credentials, if any.
  if (!ap_is_initial_req(r)) {
    if (r->main != NULL) {
      r->user = r->main->user;
    } else if (r->prev != NULL) {
      r->user = r->prev->user;
    }
    if (r->user != NULL) {
      return OK;
    }
  }

ale's avatar
ale committed
835
836
837
838
839
840
841
842
843
844
845
  sso_cookie_name = get_cookie_name(r);

  // Check if the required parameters are defined.
  if (!check_config(r, s_cfg)) {
    return HTTP_INTERNAL_SERVER_ERROR;
  }

  uri = r->uri;

  if (parse_service(r, s_cfg, &service, &service_host, &service_path) != 0) {
    ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
ale's avatar
ale committed
846
		 "sso (check_user_id): could not parse service (cfg->service=%s)",
ale's avatar
ale committed
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
		 s_cfg->service);
    return HTTP_BAD_REQUEST;
  }

  // Everyone is allowed access to /sso_login and /sso_logout
  sso_logout_path = apr_pstrcat(r->pool, service_path, "sso_logout", NULL);
  sso_login_path = apr_pstrcat(r->pool, service_path, "sso_login", NULL);
  if (!strcmp(uri, sso_logout_path) || !strcmp(uri, sso_login_path)) {
    return OK;
  }

  mod_sso_parse_requirements(r, &auth);

  // Test for valid cookie
  sso_cookie = get_cookie(r, sso_cookie_name);
  if (sso_cookie != NULL) {
    sso_ticket_t t;

    // Print some debugging information about the service
    {
      char pkeybuf[512];
      const char *host_hdr = apr_table_get(r->headers_in, "Host");
      if (!host_hdr) {
	host_hdr = "null";
      }
      ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
		   "sso request: uri=%s, service=%s, orig=%s, host=%s, tkt=%s, pkey=%s",
		   r->uri, service, s_cfg->service, host_hdr, sso_cookie,
		   pkey_to_string(s_cfg->public_key, pkeybuf));
    }

    err = sso_ticket_open(&t, sso_cookie, s_cfg->public_key);
    if (err != SSO_OK) {
      ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
                   "sso: ticket decoding error: %s", sso_strerror(err));
    } else {
      err = sso_validate(t, s_cfg->service, s_cfg->domain, apr_is_empty_array(auth.groups) ? NULL : (const char **)auth.groups->elts);
      if (err != SSO_OK) {
        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
                     "sso: validation error: %s", sso_strerror(err));
      } else {
        // Check user authorization lists. Group membership has
	// already been verified by sso_validate.
        if (auth.any_user || (!apr_is_empty_array(auth.users) && array_contains(auth.users, t->user)) || !apr_is_empty_array(auth.groups)) {
          // Success.
          apr_table_setn(r->subprocess_env, "SSO_SERVICE", 
                         apr_pstrdup(r->pool, service));
          r->user = apr_pstrdup(r->pool, t->user);
          ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
                       "sso: authorized user '%s'", r->user);
          retval = OK;
        } else {
          ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
                       "sso: unauthorized user '%s'", t->user);
          retval = HTTP_UNAUTHORIZED;
        }
        do_redirect = 0;
      }	

      sso_ticket_free(t);
    }
  }

  if (!do_redirect) {
    return retval;
  }

  // Redirect to login server
  return redirect_to_login_server(r, s_cfg->login_server, service_host, service, auth.groups);
}
godog's avatar
godog committed
917
#endif /* apache 2.2 */
ale's avatar
ale committed
918
919
920
921

/** 
 * Apache authorization check callback for mod_sso.
 */
ale's avatar
ale committed
922
#if MODULE_MAGIC_NUMBER_MAJOR >= 20100714
923
static authz_status sso_check_authorization(request_rec *r, const char *require_args, const void *parsed_require_args)
ale's avatar
ale committed
924
{
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
  const char *uri, *type;
  const char *service = NULL, *service_host = NULL,
    *service_path = NULL;
  char *sso_logout_path, *sso_login_path;
  modsso_config *s_cfg;

  // We already did everything in mod_sso_check_user_id(),
  // so just succeed (if SSO is active).
  type = ap_auth_type(r);
  if (type && !strcasecmp(type, "SSO") && r->user) {
    return OK;
  }

  // XXX check groups via e.g. 'Require sso-groups' or 'Require valid-group'
  s_cfg = (modsso_config *)
    ap_get_module_config(r->per_dir_config, &sso_module);
  uri = r->uri;
  if (parse_service(r, s_cfg, &service, &service_host, &service_path) != 0) {
    ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
		 "sso (auth_checker): could not parse service \"%s\"",
		 s_cfg->service);
    return HTTP_BAD_REQUEST;
  }
ale's avatar
ale committed
948

949
950
951
952
953
  sso_logout_path = apr_pstrcat(r->pool, service_path, "sso_logout", NULL);
  sso_login_path = apr_pstrcat(r->pool, service_path, "sso_login", NULL);
  if (!strcmp(uri, sso_logout_path) || !strcmp(uri, sso_login_path)) {
    return OK;
  }
ale's avatar
ale committed
954

955
  return DECLINED;
ale's avatar
ale committed
956
}
ale's avatar
ale committed
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996

static authz_status group_check_authorization(request_rec *r, const char *require_args, const void *parsed_require_args) {
  const ap_expr_info_t *expr = parsed_require_args;
  const char *err = NULL;
  const char *group_str, *require, *w, *t;
  apr_array_header_t *user_groups = NULL;
  int i;
  
  // Retrieve the comma-separated group list from r->notes.
  group_str = apr_table_get(r->notes, "SSO_GROUPS");
  if (!group_str) {
    return DECLINED;
  }
  user_groups = parse_commasep_groups(r->pool, group_str);

  require = ap_expr_str_exec(r, expr, &err);
  if (err) {
    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02592)
                  "mod_sso authorize: require group: Can't "
                  "evaluate require expression: %s", err);
    return AUTHZ_DENIED;
  }

  ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
       "sso (check_group): user '%s' user_groups '%s'", r->user, group_str);

  t = require;
  while ((w = ap_getword_conf(r->pool, &t)) && w[0]) {
    // Check if w is in user_groups.
    for (i = 0; i < user_groups->nelts; i++) {
      char *el = APR_ARRAY_IDX(user_groups, i, char *);
      if (!strcasecmp(w, el)) {
        return AUTHZ_GRANTED;
      }
    }
  }
  
  return DECLINED;
}

ale's avatar
ale committed
997
#else
ale's avatar
ale committed
998
999
1000
static int mod_sso_auth_checker(request_rec *r)
{
  const char *uri, *type;
For faster browsing, not all history is shown. View entire blame