File: mod_auth_pgsql.c

package info (click to toggle)
libapache2-mod-auth-pgsql 2.0.3-6.1
  • links: PTS, VCS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, sid, stretch
  • size: 388 kB
  • ctags: 365
  • sloc: ansic: 3,261; makefile: 22
file content (1058 lines) | stat: -rw-r--r-- 32,260 bytes parent folder | download
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
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
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
/* =====================================================================
 * Copyright (c) 1996 Vidya Media Ventures, Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of this source code or a derived source code must
 *    retain the above copyright notice, this list of conditions and the
 *    following disclaimer. 
 *
 * 2. Redistributions of this module or a derived module in binary form
 *    must reproduce the above copyright notice, this list of conditions
 *    and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY VIDYA MEDIA VENTURES, INC. ``AS IS'' AND 
 * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL VIDYA MEDIA VENTURES, INC.
 * OR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This software is a contribution to and makes use of the Apache HTTP
 * server which is written, maintained and copywritten by the Apache Group.
 * See http://www.apache.org/ for more information.
 *
 * This software makes use of libpq which an interface to the PostgreSQL
 * database.  PostgreSQL is copyright (c) 1994 by the Regents of the
 * University of California.  As of this writing, more information on
 * PostgreSQL can be found at http://www.postgresSQL.org/
 *
 */

/*
 * 
 * PostgreSQL authentication
 *
 *
 * Needs libpq-fe.h and libpq.a
 *
 * Outline:
 *
 * - Authentication
 *   One database, and one (or two) tables.  One table holds the username and
 *   the encryped (or plain) password.  The other table holds the username and the names
 *   of the group to which the user belongs.  It is possible to have username,
 *   groupname and password in the same table.
 * - Access Logging
 *   Every authentication access is logged in the same database of the 
 *   authentication table, but in different table.
 *   User name and date of the request are logged.
 *   As option, it can log password, ip address, request line.
 *
 * Module Directives:  See html documentation
 * 
 * Changelog: See html documentation
 *
 * see http://www.postgreSQL.org/
 *
 *
 *
 *		Homepage	http://www.giuseppetanzilli.it/mod_auth_pgsql/
 *
 *		Latest sources  http://www.giuseppetanzilli.it/mod_auth_pgsql/dist/
 *
 *		Maintainer:
 *		Giuseppe Tanzilli
 *			info@giuseppetanzilli.it
 *			g.tanzilli@gruppocsf.com		
 *
 *		Original source: 
 * 		Adam Sussman (asussman@vidya.com) Feb, 1996
 *		Matthias Eckermann
 *		eckerman@lrz.uni-muenchen.de
 *
 */


#define 	AUTH_PGSQL_VERSION		"2.0.3"

#include "apr_hooks.h"
#include "apr.h"
#include "apr_lib.h"
#include "apr_strings.h"
#include "apr_buckets.h"
#include "apr_md5.h"
#include "apr_network_io.h"
#include "apr_pools.h"
#include "apr_uri.h"
#include "apr_date.h"
#include "apr_fnmatch.h"
#define APR_WANT_STRFUNC
#include "apr_want.h"

#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "http_main.h"
#include "http_protocol.h"
#include "http_request.h"
#include "util_script.h"

#include "mod_auth.h"

#ifdef WIN32
#define crypt apr_password_validate
#else
#include <unistd.h>
#endif
#include "libpq-fe.h"

#if (MODULE_MAGIC_NUMBER_MAJOR < 20020628)
#error  Apache 2.0.40 required
#endif

/*
** uncomment the following line if you're having problem. The debug messages
** will be written to the server error log.
** WARNING: we log sensitive data, do not use on production systems
*/

/* #define DEBUG_AUTH_PGSQL 1 */



#ifndef MAX_STRING_LEN
#define MAX_STRING_LEN 8192
#endif

/* Cache table size */
#ifndef MAX_TABLE_LEN
#define MAX_TABLE_LEN 50
#endif

#define AUTH_PG_HASH_TYPE_CRYPT 	1
#define AUTH_PG_HASH_TYPE_MD5   	2
#define AUTH_PG_HASH_TYPE_BASE64	3


typedef struct {
	const char *dir;
	const char *auth_pg_host;
	const char *auth_pg_database;
	const char *auth_pg_port;
	const char *auth_pg_options;
	const char *auth_pg_user;
	const char *auth_pg_charset;
	const char *auth_pg_pwd;
	const char *auth_pg_pwd_table;
	const char *auth_pg_uname_field;
	const char *auth_pg_pwd_field;
	const char *auth_pg_grp_table;
	const char *auth_pg_grp_group_field;
	const char *auth_pg_grp_user_field;
	const char *auth_pg_pwd_whereclause;
	const char *auth_pg_grp_whereclause;

	int auth_pg_nopasswd;
	int auth_pg_authoritative;
	int auth_pg_lowercaseuid;
	int auth_pg_uppercaseuid;
	int auth_pg_pwdignorecase;
	int auth_pg_encrypted;
	int auth_pg_hash_type;
	int auth_pg_cache_passwords;

	const char *auth_pg_log_table;
	const char *auth_pg_log_addrs_field;
	const char *auth_pg_log_uname_field;
	const char *auth_pg_log_pwd_field;
	const char *auth_pg_log_date_field;
	const char *auth_pg_log_uri_field;

	apr_table_t *cache_pass_table;

} pg_auth_config_rec;

static PGconn *pg_conn;

static apr_pool_t *auth_pgsql_pool = NULL;
static apr_pool_t *auth_pgsql_pool_base64 = NULL;

module AP_MODULE_DECLARE_DATA auth_pgsql_module;


static int pg_log_auth_user(request_rec * r, pg_auth_config_rec * sec, 
		const char *user, const char *sent_pw);
static char *do_pg_query(request_rec * r, char *query, 
		pg_auth_config_rec * sec);

static void *create_pg_auth_dir_config(apr_pool_t * p, char *d)
{
	pg_auth_config_rec *new_rec;

#ifdef DEBUG_AUTH_PGSQL
	ap_log_perror(APLOG_MARK, APLOG_WARNING, 0, p,
				  "[mod_auth_pgsql.c] - going to configure directory \"%s\" ",
				  d);
#endif							/* DEBUG_AUTH_PGSQL */

	new_rec = apr_pcalloc(p, sizeof(pg_auth_config_rec));
	if (new_rec == NULL)
		return NULL;

	if (auth_pgsql_pool == NULL)
		apr_pool_create_ex(&auth_pgsql_pool, NULL, NULL, NULL);
	if (auth_pgsql_pool == NULL)
		return NULL;
	/* sane defaults */
	if (d != NULL)
		new_rec->dir = apr_pstrdup(p, d);
	else
		new_rec->dir = NULL;
	new_rec->auth_pg_host = NULL;
	new_rec->auth_pg_database = NULL;
	new_rec->auth_pg_port = NULL;
	new_rec->auth_pg_options = NULL;
	new_rec->auth_pg_user = NULL;
	new_rec->auth_pg_charset = NULL;
	new_rec->auth_pg_pwd = NULL;
	new_rec->auth_pg_pwd_table = NULL;
	new_rec->auth_pg_uname_field = NULL;
	new_rec->auth_pg_pwd_field = NULL;
	new_rec->auth_pg_grp_table = NULL;
	new_rec->auth_pg_grp_user_field = NULL;
	new_rec->auth_pg_grp_group_field = NULL;
	new_rec->auth_pg_pwd_whereclause = NULL;
	new_rec->auth_pg_grp_whereclause = NULL;

	new_rec->auth_pg_nopasswd = 0;
	new_rec->auth_pg_authoritative = 1;
	new_rec->auth_pg_lowercaseuid = 0;
	new_rec->auth_pg_uppercaseuid = 0;
	new_rec->auth_pg_pwdignorecase = 0;
	new_rec->auth_pg_encrypted = 1;
	new_rec->auth_pg_hash_type = AUTH_PG_HASH_TYPE_CRYPT;
	new_rec->auth_pg_cache_passwords = 0;

	new_rec->auth_pg_log_table = NULL;
	new_rec->auth_pg_log_addrs_field = NULL;
	new_rec->auth_pg_log_uname_field = NULL;
	new_rec->auth_pg_log_pwd_field = NULL;
	new_rec->auth_pg_log_date_field = NULL;
	new_rec->auth_pg_log_uri_field = NULL;

	/* make a per directory cache table */
	new_rec->cache_pass_table =
		apr_table_make(auth_pgsql_pool, MAX_TABLE_LEN);
	if (new_rec->cache_pass_table == NULL)
		return NULL;

#ifdef DEBUG_AUTH_PGSQL
	ap_log_perror(APLOG_MARK, APLOG_WARNING, 0, p,
				  "[mod_auth_pgsql.c] - configured directory \"%s\" ", d);
#endif							/* DEBUG_AUTH_PGSQL */

	return new_rec;
}


static const char *pg_set_hash_type(cmd_parms * cmd, void *mconfig,
			 const char *hash_type)
{
	pg_auth_config_rec *sec = mconfig;

	if (!strcasecmp(hash_type, "MD5"))
		sec->auth_pg_hash_type = AUTH_PG_HASH_TYPE_MD5;
	else if (!strcasecmp(hash_type, "CRYPT"))
		sec->auth_pg_hash_type = AUTH_PG_HASH_TYPE_CRYPT;
	else if (!strcasecmp(hash_type, "BASE64"))
		sec->auth_pg_hash_type = AUTH_PG_HASH_TYPE_BASE64;
	else
		return apr_pstrcat(cmd->pool,
						   "Invalid hash type for Auth_PG_hash_type: ",
						   hash_type, NULL);
	return NULL;
}

static const char *pg_set_authoritative_flag(cmd_parms * cmd,
		  pg_auth_config_rec * sec, const int arg)
{
	sec->auth_pg_authoritative = arg;
	return NULL;
}

static const char *pg_set_lowercaseuid_flag(cmd_parms * cmd, void *sec,
											const int arg)
{
	((pg_auth_config_rec *) sec)->auth_pg_lowercaseuid = arg;
	((pg_auth_config_rec *) sec)->auth_pg_uppercaseuid = 0;
	return NULL;
}

static const char *pg_set_uppercaseuid_flag(cmd_parms * cmd, void *sec,
											int arg)
{
	((pg_auth_config_rec *) sec)->auth_pg_uppercaseuid = arg;
	((pg_auth_config_rec *) sec)->auth_pg_lowercaseuid = 0;
	return NULL;
}


static const command_rec pg_auth_cmds[] = {
	AP_INIT_TAKE1("Auth_PG_host", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec, auth_pg_host),
				  OR_AUTHCFG,
				  "the host name of the postgreSQL server."),
	AP_INIT_TAKE1("Auth_PG_database", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_database), OR_AUTHCFG,
				  "the name of the database that contains authorization information."),
	AP_INIT_TAKE1("Auth_PG_port", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec, auth_pg_port),
				  OR_AUTHCFG,
				  "the port the postmaster is running on."),
	AP_INIT_TAKE1("Auth_PG_options", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_options), OR_AUTHCFG,
				  "an options string to be sent to the postgres backed process."),
	AP_INIT_TAKE1("Auth_PG_user", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec, auth_pg_user),
				  OR_AUTHCFG,
				  "user name connect as"),
	AP_INIT_TAKE1("Auth_PG_charset", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec, auth_pg_charset),
				  OR_AUTHCFG,
				  "charset to use for connection"),
	AP_INIT_TAKE1("Auth_PG_pwd", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec, auth_pg_pwd),
				  OR_AUTHCFG,
				  "password to connect"),
	AP_INIT_TAKE1("Auth_PG_pwd_table", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_pwd_table), OR_AUTHCFG,
				  "the name of the table containing username/password tuples."),
	AP_INIT_TAKE1("Auth_PG_pwd_field", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_pwd_field), OR_AUTHCFG,
				  "the name of the password field."),
	AP_INIT_TAKE1("Auth_PG_uid_field", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_uname_field), OR_AUTHCFG,
				  "the name of the user-id field."),
	AP_INIT_TAKE1("Auth_PG_grp_table", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_grp_table), OR_AUTHCFG,
				  "the name of the table containing username/group tuples."),
	AP_INIT_TAKE1("Auth_PG_grp_group_field", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_grp_group_field),
				  OR_AUTHCFG,
				  "the name of the group-name field."),
	AP_INIT_TAKE1("Auth_PG_grp_user_field", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_grp_user_field),
				  OR_AUTHCFG,
				  "the name of the group-name field."),
	AP_INIT_FLAG("Auth_PG_nopasswd", ap_set_flag_slot,
				 (void *) APR_OFFSETOF(pg_auth_config_rec,
									   auth_pg_nopasswd),
				 OR_AUTHCFG,
				 "'on' or 'off'"),
	AP_INIT_FLAG("Auth_PG_encrypted", ap_set_flag_slot,
				 (void *) APR_OFFSETOF(pg_auth_config_rec,
									   auth_pg_encrypted),
				 OR_AUTHCFG,
				 "'on' or 'off'"),
	AP_INIT_TAKE1("Auth_PG_hash_type", pg_set_hash_type, NULL, OR_AUTHCFG,
				  "password hash type (CRYPT|MD5|BASE64)."),
	AP_INIT_FLAG("Auth_PG_cache_passwords", ap_set_flag_slot,
				 (void *) APR_OFFSETOF(pg_auth_config_rec,
									   auth_pg_cache_passwords),
				 OR_AUTHCFG,
				 "'on' or 'off'"),
	AP_INIT_FLAG("Auth_PG_authoritative", ap_set_flag_slot,
				 (void *) APR_OFFSETOF(pg_auth_config_rec,
									   auth_pg_authoritative), OR_AUTHCFG,
				 "'on' or 'off'"),
	AP_INIT_FLAG("Auth_PG_lowercase_uid", pg_set_lowercaseuid_flag, NULL,
				 OR_AUTHCFG,
				 "'on' or 'off'"),
	AP_INIT_FLAG("Auth_PG_uppercase_uid", pg_set_uppercaseuid_flag, NULL,
				 OR_AUTHCFG,
				 "'on' or 'off'"),
	AP_INIT_FLAG("Auth_PG_pwd_ignore_case", ap_set_flag_slot,
				 (void *) APR_OFFSETOF(pg_auth_config_rec,
									   auth_pg_pwdignorecase), OR_AUTHCFG,
				 "'on' or 'off'"),
	AP_INIT_TAKE1("Auth_PG_grp_whereclause", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_grp_whereclause),
				  OR_AUTHCFG,
				  "an SQL fragement that can be attached to the end of a where clause."),
	AP_INIT_TAKE1("Auth_PG_pwd_whereclause", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_pwd_whereclause),
				  OR_AUTHCFG,
				  "an SQL fragement that can be attached to the end of a where clause."),
	AP_INIT_TAKE1("Auth_PG_log_table", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_log_table),
				  OR_AUTHCFG,
				  "the name of the table containing log tuples."),
	AP_INIT_TAKE1("Auth_PG_log_addrs_field", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_log_addrs_field),
				  OR_AUTHCFG,
				  "the name of the field containing addrs in the log table (type char)."),
	AP_INIT_TAKE1("Auth_PG_log_uname_field", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_log_uname_field),
				  OR_AUTHCFG,
				  "the name of the field containing username in the log table (type char)."),
	AP_INIT_TAKE1("Auth_PG_log_pwd_field", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_log_pwd_field),
				  OR_AUTHCFG,
				  "the name of the field containing password in the log table (type char)."),
	AP_INIT_TAKE1("Auth_PG_log_date_field", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_log_date_field),
				  OR_AUTHCFG,
				  "the name of the field containing date in the log table (type char)."),
	AP_INIT_TAKE1("Auth_PG_log_uri_field", ap_set_string_slot,
				  (void *) APR_OFFSETOF(pg_auth_config_rec,
										auth_pg_log_uri_field),
				  OR_AUTHCFG,
				  "the name of the field containing uri (Object fetched) in the log table (type char)."),
	{NULL}
};


static char pg_errstr[MAX_STRING_LEN];
		 /* global errno to be able to handle config/sql 
		  * failures separately
		  */

static char *auth_pg_md5(const char *pw)
{
	unsigned char digest[APR_MD5_DIGESTSIZE];
	static unsigned char md5hash[APR_MD5_DIGESTSIZE * 2 + 1];
	int i;

	apr_md5(digest, (const unsigned char *) pw, strlen(pw));

	for (i = 0; i < APR_MD5_DIGESTSIZE; i++)
		apr_snprintf((char *) &md5hash[i + i], 3, "%02x", digest[i]);

	md5hash[APR_MD5_DIGESTSIZE * 2] = '\0';
	return (char *) md5hash;
}


static char *auth_pg_base64(const char *pw)
{
	if (auth_pgsql_pool_base64 == NULL)
		apr_pool_create_ex(&auth_pgsql_pool_base64, NULL, NULL, NULL);
	if (auth_pgsql_pool == NULL)
		return NULL;

	/* NOTE: ap_pbase64encode is no change arg2. so removable const. */
	return ap_pbase64encode(auth_pgsql_pool, (char *)pw);
}


PGconn *pg_connect(pg_auth_config_rec *sec)
{
	PGconn *conn;

	conn = PQsetdbLogin(sec->auth_pg_host, sec->auth_pg_port,
		sec->auth_pg_options, NULL, sec->auth_pg_database,
		sec->auth_pg_user, sec->auth_pg_pwd);
	if (PQstatus(conn) != CONNECTION_OK) {
		PQreset(conn);
		apr_snprintf(pg_errstr, MAX_STRING_LEN,
					 "mod_auth_pgsql database connection error resetting %s",
					 PQerrorMessage(conn));
		if (PQstatus(conn) != CONNECTION_OK) {
			apr_snprintf(pg_errstr, MAX_STRING_LEN,
						 "mod_auth_pgsql database connection error reset failed %s",
						 PQerrorMessage(conn));
			PQfinish(conn);
			conn = NULL;
			return NULL;
		}
	}
	return conn;
}


static size_t pg_check_string(char *to, const char *from, size_t length, request_rec * r, pg_auth_config_rec *sec)
{
	int error;

	if (!pg_conn) {
		if (!(pg_conn = pg_connect(sec))) {
			ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "[mod_auth_pgsql.c] - cannot connect to database");
			ap_note_basic_auth_failure(r);
			return -1;
		}
	}

	PQescapeStringConn(pg_conn, to, from, length, &error);

	if (error) {
		ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "[mod_auth_pgsql.c] - cannot escape string");
		ap_note_basic_auth_failure(r);
		return -1;
	}

	return 0;
}


/* Do a query and return the (0,0) value.  The query is assumed to be
 * a select.
 */
char *do_pg_query(request_rec * r, char *query, pg_auth_config_rec * sec)
{
	PGresult *pg_result;
	char *val;
	char *result = NULL;

	pg_errstr[0] = '\0';

#ifdef DEBUG_AUTH_PGSQL
	ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
	  "[mod_auth_pgsql.c] - do_pg_query - going to connect database \"%s\" ",
	  sec->auth_pg_database);
#endif							/* DEBUG_AUTH_PGSQL */

	if (!pg_conn) {
		if (!(pg_conn = pg_connect(sec))) {
			ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "[mod_auth_pgsql.c] - cannot connect to database");
			ap_note_basic_auth_failure(r);
			return NULL;
		}
	}
#ifdef DEBUG_AUTH_PGSQL
	ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
				  "[mod_auth_pgsql.c] - do_pg_query - going to execute query \"%s\" ",
				  query);
#endif							/* DEBUG_AUTH_PGSQL */

	if (sec->auth_pg_charset) {
		const char *check;

		PQsetClientEncoding(pg_conn, sec->auth_pg_charset);

		check = pg_encoding_to_char(PQclientEncoding(pg_conn));

		if (!check || strcmp(sec->auth_pg_charset, check)) {
			apr_snprintf(pg_errstr, MAX_STRING_LEN,
						 "mod_auth_pgsql database character set encoding %s",
						 check);
			PQfinish(pg_conn);
			pg_conn = NULL;
			return NULL;
		}
	}

	pg_result = PQexec(pg_conn, query);

	if (pg_result == NULL) {
		apr_snprintf(pg_errstr, MAX_STRING_LEN,
					 "PGSQL 2: %s -- Query: %s ",
					 PQerrorMessage(pg_conn), query);
		PQfinish(pg_conn);
		pg_conn = NULL;
		return NULL;
	}

	if (PQresultStatus(pg_result) == PGRES_EMPTY_QUERY) {
		PQclear(pg_result);
		pg_result = NULL;
		PQfinish(pg_conn);
		pg_conn = NULL;
		return NULL;
	}

	if (PQresultStatus(pg_result) != PGRES_TUPLES_OK) {
		apr_snprintf(pg_errstr, MAX_STRING_LEN, "PGSQL 3: %s -- Query: %s",
					 PQerrorMessage(pg_conn), query);
		PQclear(pg_result);
		pg_result = NULL;
		PQfinish(pg_conn);
		pg_conn = NULL;
		return NULL;
	}

	if (PQntuples(pg_result) == 1) {
		val = PQgetvalue(pg_result, 0, 0);
		if (val == NULL) {
			apr_snprintf(pg_errstr, MAX_STRING_LEN, "PGSQL 4: %s",
						 PQerrorMessage(pg_conn));
			PQclear(pg_result);
			pg_result = NULL;
			PQfinish(pg_conn);
			pg_conn = NULL;
			return NULL;
		}

		if (!(result = (char *) apr_pcalloc(r->pool, strlen(val) + 1))) {
			apr_snprintf(pg_errstr, MAX_STRING_LEN,
						 "Could not get memory for Postgres query.");
			PQclear(pg_result);
			pg_result = NULL;
			PQfinish(pg_conn);
			pg_conn = NULL;
			return NULL;
		}

		strcpy(result, val);
	}

	/* ignore errors here ! */
	PQclear(pg_result);
	pg_result = NULL;
	PQfinish(pg_conn);
	pg_conn = NULL;
	return result;
}

char *get_pg_pw(request_rec * r, const char *user, pg_auth_config_rec * sec)
{
	char query[MAX_STRING_LEN];
	char *safe_user;
	int n;

	safe_user = apr_palloc(r->pool, 1 + 2 * strlen(user));
	pg_check_string(safe_user, user, strlen(user), r, sec);

#ifdef DEBUG_AUTH_PGSQL
	ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
				  "[mod_auth_pgsql.c] - get_pg_pw - going to retrieve password for user \"%s\" from database",
				  user);
#endif							/* DEBUG_AUTH_PGSQL */

	if ((!sec->auth_pg_pwd_table) ||
		(!sec->auth_pg_pwd_field) || (!sec->auth_pg_uname_field)) {
		apr_snprintf(pg_errstr, MAX_STRING_LEN,
					 "PG: Missing parameters for password lookup: %s%s%s",
					 (sec->auth_pg_pwd_table ? "" : "Password table "),
					 (sec->
					  auth_pg_pwd_field ? "" : "Password field name "),
					 (sec->
					  auth_pg_uname_field ? "" : "UserID field name "));
		return NULL;
	};

	if (sec->auth_pg_lowercaseuid) {
		/* and force it to lowercase */
		n = 0;
		while (safe_user[n] && n < (MAX_STRING_LEN - 1)) {
			if (isupper(safe_user[n])) {
				safe_user[n] = tolower(safe_user[n]);
			}
			n++;
		}
	}

	if (sec->auth_pg_uppercaseuid) {
		/* and force it to uppercase */
		n = 0;
		while (safe_user[n] && n < (MAX_STRING_LEN - 1)) {
			if (islower(safe_user[n])) {
				safe_user[n] = toupper(safe_user[n]);
			}
			n++;
		}
	}

	n = apr_snprintf(query, MAX_STRING_LEN,
					 "select %s from %s where %s='%s' %s",
					 sec->auth_pg_pwd_field, sec->auth_pg_pwd_table,
					 sec->auth_pg_uname_field, safe_user,
					 sec->auth_pg_pwd_whereclause ? sec->
					 auth_pg_pwd_whereclause : "");

	if (n < 0 || n > MAX_STRING_LEN) {
		apr_snprintf(pg_errstr, MAX_STRING_LEN,
					 "PG: Detected SQL-truncation attack. Auth aborted.");
		return NULL;
	}
	return do_pg_query(r, query, sec);
}

static char *get_pg_grp(request_rec * r, char *group, char *user,
				 pg_auth_config_rec * sec)
{
	char query[MAX_STRING_LEN];
	char *safe_user;
	char *safe_group;
	int n;

	safe_user = apr_palloc(r->pool, 1 + 2 * strlen(user));
	safe_group = apr_palloc(r->pool, 1 + 2 * strlen(group));

#ifdef DEBUG_AUTH_PGSQL
	ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
				  "[mod_auth_pgsql.c] - get_pg_grp - going to retrieve group for user \"%s\" from database",
				  user);
#endif							/* DEBUG_AUTH_PGSQL */

	query[0] = '\0';
	pg_check_string(safe_user, user, strlen(user), r, sec);
	pg_check_string(safe_group, group, strlen(group), r, sec);

	if ((!sec->auth_pg_grp_table) ||
		(!sec->auth_pg_grp_group_field) || (!sec->auth_pg_grp_user_field))
	{
		apr_snprintf(pg_errstr, MAX_STRING_LEN,
					 "PG: Missing parameters for password lookup: %s%s%s",
					 (sec->auth_pg_grp_table ? "" : "Group table name"),
					 (sec->
					  auth_pg_grp_group_field ? "" :
					  "GroupID field name "),
					 (sec->
					  auth_pg_grp_user_field ? "" :
					  "Group table user field name "));
		return NULL;
	};

	if (sec->auth_pg_lowercaseuid) {
		/* and force it to lowercase */
		n = 0;
		while (safe_user[n] && n < (MAX_STRING_LEN - 1)) {
			if (isupper(safe_user[n])) {
				safe_user[n] = tolower(safe_user[n]);
			}
			n++;
		}
	}

	if (sec->auth_pg_uppercaseuid) {
		/* and force it to uppercase */
		n = 0;
		while (safe_user[n] && n < (MAX_STRING_LEN - 1)) {
			if (islower(safe_user[n])) {
				safe_user[n] = toupper(safe_user[n]);
			}
			n++;
		}
	}


	n = apr_snprintf(query, MAX_STRING_LEN,
					 "select %s from %s where %s='%s' and %s='%s' %s",
					 sec->auth_pg_grp_group_field, sec->auth_pg_grp_table,
					 sec->auth_pg_grp_user_field, safe_user,
					 sec->auth_pg_grp_group_field, safe_group,
					 sec->auth_pg_grp_whereclause ? sec->
					 auth_pg_grp_whereclause : "");

	if (n < 0 || n > MAX_STRING_LEN) {
		apr_snprintf(pg_errstr, MAX_STRING_LEN,
					 "PG: Detected SQL-truncation attack. Auth aborted.");
		return NULL;
	}

	return do_pg_query(r, query, sec);
}

/* Process authentication request from Apache*/
static authn_status check_password(request_rec *r, const char *user,
                                   const char *password)
{
	
	pg_auth_config_rec *sec =
		(pg_auth_config_rec *) ap_get_module_config(r->per_dir_config,
													&auth_pgsql_module);
	const char *val = NULL;
	const char *sent_pw;
	const char *real_pw;
	authn_status auth_res;
	
	sent_pw = password;


#ifdef DEBUG_AUTH_PGSQL
	ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
				  "[mod_auth_pgsql.c] - pg_authenticate_basic_user - going to auth user \"%s\" pass \"%s\" uri \"%s\"",
				  user, sent_pw, r->unparsed_uri);
#endif							/* DEBUG_AUTH_PGSQL */

	/* if *password* checking is configured in any way, i.e. then
	 * handle it, if not decline and leave it to the next in line..  
	 * We do not check on dbase, group, userid or host name, as it is
	 * perfectly possible to only do group control and leave
	 * user control to the next guy in line.
	 */
	if ((!sec->auth_pg_pwd_table) && (!sec->auth_pg_pwd_field)) {
		ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
					  "[mod_auth_pgsql.c] - missing configuration parameters");
		return AUTH_GENERAL_ERROR;
	}
	pg_errstr[0] = '\0';

	if (!pg_conn) {
		if (!(pg_conn = pg_connect(sec))) {
			ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "[mod_auth_pgsql.c] - cannot connect to database");
			ap_note_basic_auth_failure(r);
			return HTTP_UNAUTHORIZED;
		}
	}

	if (sec->auth_pg_cache_passwords
		&& (!apr_is_empty_table(sec->cache_pass_table))) {
		val = (char *) apr_table_get(sec->cache_pass_table, user);

		if (val)
			real_pw = val;
		else
			real_pw = get_pg_pw(r, user, sec);
	} else
		real_pw = get_pg_pw(r, user, sec);

	if (!real_pw) {
		if (pg_errstr[0]) {
			auth_res = AUTH_GENERAL_ERROR;
		} else {
				/* force error and access denied */
				apr_snprintf(pg_errstr, MAX_STRING_LEN,
							 "mod_auth_pgsql: Password for user %s not found (PG-Authoritative)",
							 user);
			auth_res = AUTH_USER_NOT_FOUND;
		}
		ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "[mod_auth_pgsql.c] - ERROR - %s", pg_errstr);
		return auth_res;
	}

	/* allow no password, if the flag is set and the password
	 * is empty. But be sure to log this.
	 */
	if ((sec->auth_pg_nopasswd) && (!strlen(real_pw))) {
		apr_snprintf(pg_errstr, MAX_STRING_LEN,
					 "[mod_auth_pgsql.c] - Empty password accepted for user \"%s\"",
					 user);
		ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "[mod_auth_pgsql.c] - ERROR - %s", pg_errstr);
		pg_log_auth_user(r, sec, user, sent_pw);
		return AUTH_GRANTED;
	};

	/* if the flag is off however, keep that kind of stuff at
	 * an arms length.
	 */
	if ((!strlen(real_pw)) || (!strlen(sent_pw))) {
		apr_snprintf(pg_errstr, MAX_STRING_LEN,
					 "[mod_auth_pgsql.c] - Empty password rejected for user \"%s\"",
					 user);
		ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "[mod_auth_pgsql.c] - ERROR - %s", pg_errstr);
		return AUTH_DENIED;
	};

	if (sec->auth_pg_encrypted)
		switch (sec->auth_pg_hash_type) {
		case AUTH_PG_HASH_TYPE_MD5:
			sent_pw = auth_pg_md5(sent_pw);
			break;
		case AUTH_PG_HASH_TYPE_CRYPT:
			sent_pw = (char *) crypt(sent_pw, real_pw);
			break;
		case AUTH_PG_HASH_TYPE_BASE64:
			sent_pw = auth_pg_base64(sent_pw);
			break;
		}


	if ((sec->auth_pg_hash_type == AUTH_PG_HASH_TYPE_MD5
		 || sec->auth_pg_pwdignorecase != 0) ? strcasecmp(real_pw,
														  sent_pw) :
		strcmp(real_pw, sent_pw))

		if ((sec->auth_pg_hash_type == AUTH_PG_HASH_TYPE_MD5
			 || sec->auth_pg_hash_type == AUTH_PG_HASH_TYPE_BASE64
			 || sec->auth_pg_pwdignorecase)
			? strcasecmp(real_pw, sent_pw) : strcmp(real_pw, sent_pw)) {
			apr_snprintf(pg_errstr, MAX_STRING_LEN,
						 "PG user %s: password mismatch", user);
			ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "[mod_auth_pgsql.c] - ERROR - %s", pg_errstr);
			return AUTH_DENIED;
		}

	/*  store password in the cache */
	if (sec->auth_pg_cache_passwords && !val && sec->cache_pass_table) {
		if ((apr_table_elts(sec->cache_pass_table))->nelts >=
			MAX_TABLE_LEN) {
			apr_table_clear(sec->cache_pass_table);
		}
		apr_table_set(sec->cache_pass_table, user, real_pw);
	}

	pg_log_auth_user(r, sec, user, sent_pw);
	return AUTH_GRANTED;
}

/* Send the authentication to the log table */
int
pg_log_auth_user(request_rec * r, pg_auth_config_rec * sec, const char *user,
				 const char *sent_pw)
{
	char sql[MAX_STRING_LEN];
	char *s;
	int n;
	char fields[MAX_STRING_LEN];
	char values[MAX_STRING_LEN];
	char *safe_user;
	char *safe_pw;
	char *safe_req;
	char ts[MAX_STRING_LEN];	/* time in string format */
	apr_time_exp_t t;			/* time of request start */
	apr_size_t retsize;

	safe_user = apr_palloc(r->pool, 1 + 2 * strlen(user));
	safe_pw = apr_palloc(r->pool, 1 + 2 * strlen(sent_pw));
	safe_req = apr_palloc(r->pool, 1 + 2 * strlen(r->the_request));

	/* we do not want to process internal redirect  */
	if (!ap_is_initial_req(r))
		return DECLINED;
	if ((!sec->auth_pg_log_table) || (!sec->auth_pg_log_uname_field) || (!sec->auth_pg_log_date_field)) {	// At least table name, username and date field are specified
		// send error message and exit 
		return DECLINED;
	}

	/* AUD: MAX_STRING_LEN probably isn't always correct */
	pg_check_string(safe_user, user, strlen(user), r, sec);
	pg_check_string(safe_pw, sent_pw, strlen(sent_pw), r, sec);
	pg_check_string(safe_req, r->the_request, strlen(r->the_request), r, sec);


	if (sec->auth_pg_lowercaseuid) {
		/* and force it to lowercase */
		n = 0;
		while (safe_user[n] && n < (MAX_STRING_LEN - 1)) {
			if (isupper(safe_user[n])) {
				safe_user[n] = tolower(safe_user[n]);
			}
			n++;
		}
	}

	if (sec->auth_pg_uppercaseuid) {
		/* and force it to uppercase */
		n = 0;
		while (safe_user[n] && n < (MAX_STRING_LEN - 1)) {
			if (islower(safe_user[n])) {
				safe_user[n] = toupper(safe_user[n]);
			}
			n++;
		}
	}


	/* time field format  */
	apr_time_exp_lt(&t, r->request_time);
	apr_strftime(ts, &retsize, 100, "%Y-%m-%d %H:%M:%S", &t);



	/* SQL Statement, required fields: Username, Date */
	apr_snprintf(fields, MAX_STRING_LEN, "%s,%s",
				 sec->auth_pg_log_uname_field,
				 sec->auth_pg_log_date_field);
	apr_snprintf(values, MAX_STRING_LEN, "'%s','%s'", safe_user, ts);

	/* Optional parameters */
	if (sec->auth_pg_log_addrs_field) {	/* IP Address field */
		apr_snprintf(sql, MAX_STRING_LEN, ", %s",
					 sec->auth_pg_log_addrs_field);
		strncat(fields, sql, MAX_STRING_LEN - strlen(fields) - 1);
		apr_snprintf(sql, MAX_STRING_LEN, ", '%s'",
					 r->connection->client_ip);
		strncat(values, sql, MAX_STRING_LEN - strlen(values) - 1);
	}
	if (sec->auth_pg_log_pwd_field) {	/* Password field , clear WARNING */
		apr_snprintf(sql, MAX_STRING_LEN, ", %s",
					 sec->auth_pg_log_pwd_field);
		strncat(fields, sql, MAX_STRING_LEN - strlen(fields) - 1);
		apr_snprintf(sql, MAX_STRING_LEN, ", '%s'", safe_pw);
		strncat(values, sql, MAX_STRING_LEN - strlen(values) - 1);
	}
	if (sec->auth_pg_log_uri_field) {	/* request string */
		apr_snprintf(sql, MAX_STRING_LEN, ", %s",
					 sec->auth_pg_log_uri_field);
		strncat(fields, sql, MAX_STRING_LEN - strlen(fields) - 1);
		apr_snprintf(sql, MAX_STRING_LEN, ", '%s'", safe_req);
		strncat(values, sql, MAX_STRING_LEN - strlen(values) - 1);
	}

	apr_snprintf(sql, MAX_STRING_LEN, "insert into %s (%s) values(%s) ; ",
				 sec->auth_pg_log_table, fields, values);

	s = do_pg_query(r, sql, sec);
	return (0);
}

static int
pg_auth_init_handler(apr_pool_t * p, apr_pool_t * plog, apr_pool_t * ptemp,
					 server_rec * s)
{
#ifdef DEBUG_AUTH_PGSQL
	ap_log_perror(APLOG_MARK, APLOG_WARNING, 0, p,
				  "[mod_auth_pgsql.c] - pg_auth_init_handler -  ");
#endif							/* DEBUG_AUTH_PGSQL */

	ap_add_version_component(p, "mod_auth_pgsql/" AUTH_PGSQL_VERSION);
	return OK;
}

/* Init the module private memory pool, used for the per directory cache tables */
static void *pg_auth_server_config(apr_pool_t * p, server_rec * s)
{
#ifdef DEBUG_AUTH_PGSQL
	ap_log_perror(APLOG_MARK, APLOG_WARNING, 0, p,
				  "[mod_auth_pgsql.c] - pg_auth_server_config -  ");
#endif							/* DEBUG_AUTH_PGSQL */

	if (auth_pgsql_pool == NULL)
		apr_pool_create_ex(&auth_pgsql_pool, NULL, NULL, NULL);

	return OK;
}


static const authn_provider authn_pgsql_provider =
{
    &check_password,
    NULL,
};

static void register_hooks(apr_pool_t * p)
{
	ap_hook_post_config(pg_auth_init_handler, NULL, NULL, APR_HOOK_MIDDLE);

	ap_register_auth_provider(p, AUTHN_PROVIDER_GROUP, "pgsql",
								AUTHN_PROVIDER_VERSION,
								&authn_pgsql_provider, AP_AUTH_INTERNAL_PER_CONF);
};

AP_DECLARE_MODULE(auth_pgsql) = {
	STANDARD20_MODULE_STUFF,
	create_pg_auth_dir_config,	/* dir config creater */
	NULL,						/* dir merger --- default is to override */
	pg_auth_server_config,		/* server config */
	NULL,						/* merge server config */
	pg_auth_cmds,				/* command table */
	register_hooks				/* Apache2 register hooks */
};