summaryrefslogtreecommitdiffhomepage
path: root/src/basicauth.c
blob: 4360a1a0d20a9f13defaea2785fe35e64256dd10 (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
/* tinyproxy - A fast light-weight HTTP proxy
 * This file: Copyright (C) 2016-2017 rofl0r
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "main.h"
#include "basicauth.h"

#include "conns.h"
#include "heap.h"
#include "html-error.h"
#include "log.h"
#include "conf.h"
#include "base64.h"

/*
 * Add entry to the basicauth list
 */
void basicauth_add (vector_t authlist,
	const char *user, const char *pass)
{
	char tmp[256+2];
	char b[BASE64ENC_BYTES((sizeof tmp)-1) + 1];
	int l;
	size_t bl;

        if (user == NULL || pass == NULL) {
                log_message (LOG_WARNING,
                             "Illegal basicauth rule: missing user or pass");
                return;
        }

        l = snprintf(tmp, sizeof tmp, "%s:%s", user, pass);

        if(l >= (ssize_t) sizeof tmp) {
                log_message (LOG_WARNING,
                            "User / pass in basicauth rule too long");
                return;
        }

        base64enc(b, tmp, l);
        bl = BASE64ENC_BYTES(l) + 1;

        if (vector_append(authlist, b, bl) == -ENOMEM) {
                log_message (LOG_ERR,
                             "Unable to allocate memory in basicauth_add()");
                return;
        }

        log_message (LOG_INFO,
                     "Added basic auth user : %s", user);
}

/*
 * Check if a user/password combination (encoded as base64)
 * is in the basicauth list.
 * return 1 on success, 0 on failure.
 */
int basicauth_check (vector_t authlist, const char *authstring)
{
        ssize_t vl, i;
        size_t al, el;
        const char* entry;

        vl = vector_length (authlist);
        if (vl == -EINVAL) return 0;

        al = strlen (authstring);
        for (i = 0; i < vl; i++) {
                entry = vector_getentry (authlist, i, &el);
                if (strncmp (authstring, entry, al) == 0)
                        return 1;
        }
	return 0;
}