summaryrefslogtreecommitdiffhomepage
path: root/client/misc.c
blob: 1739535079f8110ea12075b3c7b6ce0304d764fa (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

/*

  Copyright (c) 2009-2014 Samuel Lidén Borell <samuel@kodafritt.se>
 
  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.

*/

#define _BSD_SOURCE 1
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include <stdarg.h>
#include <openssl/sha.h>
#include <openssl/evp.h>

#include "misc.h"

/* Max size is 20 MB */
#define MAX_SANE_DATA_SIZE 20*1024*1024

/**
 * Like sprintf, but allocates and returns a string instead of
 * using a pre-allocated buffer.
 */
char *rasprintf(const char *format, ...) {
    va_list args;
    char *str;
    
    va_start(args, format);
    str = (char*)g_strdup_vprintf((gchar*)format, args);
    va_end(args);
    return str;
}

/**
 * Like rasprintf (above), but appends to an existing string instead of
 * creating a new one. The original string is reallocated as a longer
 * string, which is returned.
 *
 * In case of an error, this function returns NULL and frees str.
 */
char *rasprintf_append(char *str, const char *format, ...) {
    va_list args;
    
    va_start(args, format);
    char *tail = (char*)g_strdup_vprintf((gchar*)format, args);
    va_end(args);
    if (!tail) goto error;
    
    size_t oldlen = strlen(str);
    size_t taillen = strlen(tail);
    if (oldlen > MAX_SANE_DATA_SIZE || taillen > MAX_SANE_DATA_SIZE) goto error;
    
    char *merged = realloc(str, oldlen+taillen+1);
    if (!merged) goto error;
    memcpy(&merged[oldlen], tail, taillen+1);
    free(tail);
    return merged;
  
  error:
    free(tail);
    free(str);
    return NULL;
}

/**
 * This is a modified memset(3) function to cover the
 * problems documented by David Wheeler in:
 * http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/\
 * protect-secrets.html
 * Based on a Bugtraq issue filed by Andy Polyakov this
 * workaround was suggested by Michael Howard
 */
void *guaranteed_memset(void *v, int c, size_t n) {
    volatile char *p=v;
    while (n--) *p++=c;
    return v;
}

// Removes newlines from base64 encoded data
static void removeNewlines(char *s) {
    const char *readp = s;
    char *writep = s;
    
    while (*readp != '\0') {
        if (*readp >= ' ') {
            *writep = *readp;
            writep++;
        }
        readp++;
        
    }
    *writep = '\0';
}

/**
 * Checks if a string is in UTF-8 format. If not it tries to convert it from
 * ISO-88591-1, and free's the UTF-8 string.
 *
 * @returns  An UTF-8 string, or NULL on error.
 */
static char *utf8_or_latin1(char *input, size_t length) {
    // Check for NULL
    if (length != strlen(input)) {
        free(input);
        return NULL;
    }
    
    // Check for invalid unicode
    if (g_utf8_validate(input, length, NULL)) return input;
    
    // Try to convert from ISO-8859-1
    GError *error = NULL;
    gchar *utf8 = g_convert(input, length, "UTF-8", "ISO-8859-1",
                            NULL, NULL, &error);
    free(input);
    
    if (!error) return (char*)utf8;
    
    // Neither valid UTF-8 or ISO-8859-1
    g_error_free(error);
    g_free(utf8);
    return NULL;
}

char *base64_encode(const char *data, int length) {
    if (length == 0) return strdup("");
    
    char *base64 = (char*)g_base64_encode((const guchar*)data, length);
    if (base64) {
        removeNewlines(base64);
    }
    return base64;
}

char *base64_add_linebreaks(const char *encoded) {
    size_t datalen;
    char *data = base64_decode_binary(encoded, &datalen);
    if (!data) return NULL;
    
    size_t enclen = (datalen/3+1)*4 + 4;
    size_t alloclen = enclen + enclen/72 + 1+5;
    char *ret = malloc(alloclen);
    gchar *out = (gchar*)ret;
    
    gint tmp1 = 0, tmp2 = 0;
    size_t bytesout = g_base64_encode_step((guchar*)data, datalen, true,
                                           out, &tmp1, &tmp2);
    out += bytesout;
    bytesout += g_base64_encode_close(true, out, &tmp1, &tmp2);
    ret[bytesout] = '\0';
    
    free(data);
    return ret;
}

char *base64_decode(const char *encoded) {
    gsize length;

    char *temp = (char*)g_base64_decode(encoded, &length);
    if (!temp) goto error;
    
    if (length > MAX_SANE_DATA_SIZE) goto error;
    
    char *result = malloc(length+1);
    if (!result) goto error;
    
    memcpy(result, temp, length);
    result[length] = '\0';
    free(temp);
    
    return utf8_or_latin1(result, length);
  
  error:
    free(temp);
    return NULL;
}

char *base64_decode_binary(const char *encoded, size_t *decodedLength) {
    gsize length;

    char *result = (char*)g_base64_decode(encoded, &length);
    *decodedLength = length;
    
    if (length > MAX_SANE_DATA_SIZE) {
        free(result);
        return NULL;
    }
    
    return result;
}

bool is_canonical_base64(const char *encoded) {
    /* Try to decode */
    gsize length;
    char *decoded = (char*)g_base64_decode(encoded, &length);
    if (!decoded) return false;
    
    /* Recode and verify that it's equal to the encoded data */
    char *recoded = base64_encode(decoded, length);
    bool equal = recoded && !strcmp(recoded, encoded);
    
    free(recoded);
    free(decoded);
    return equal;
}

char *sha_base64(const char *str) {
    unsigned char shasum[SHA256_DIGEST_LENGTH];
    EVP_MD_CTX mdctx;
    const EVP_MD *md;
    unsigned int md_len;
    char *result = NULL;

    md = EVP_sha256();
    EVP_MD_CTX_init(&mdctx);
    
    if (EVP_DigestInit_ex(&mdctx, md, NULL) &&
        EVP_DigestUpdate(&mdctx, str, strlen(str)) &&
        EVP_DigestFinal_ex(&mdctx, shasum, &md_len)) {
        result = base64_encode((const char*)shasum, sizeof(shasum));
    }
    
    EVP_MD_CTX_cleanup(&mdctx);
    return result;
}

bool is_valid_domain_name(const char *domain) {
    static const char allowed[] = "abcdefghijklmnopqrstuvwxyz0123456789-.";
    return (strspn(domain, allowed) == strlen(domain));
}

bool is_valid_ip_address(const char *ip) {
    static const char allowed[] = "0123456789abcdef.[]:";
    return (strspn(ip, allowed) == strlen(ip));
}

bool is_valid_hostname(const char *hostname) {
    return is_valid_domain_name(hostname) || is_valid_ip_address(hostname);
}

bool is_https_url(const char *url) {
    return !strncmp(url, "https://", 8);
}

/**
 * Returns true if the string is at most maxlen bytes,
 * including the null terminator.
 */
bool checkstrlen(const char *s, size_t maxlen) {
    while (maxlen) {
        if (!*s) return true;
        s++; maxlen--;
    }
    return false;
}