summaryrefslogtreecommitdiff
path: root/src/gmcerts.c
blob: 57c8d0ebdc39f51dbb436da9e12acac614fcda2d (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
/* Copyright 2020 Jaakko Keränen <jaakko.keranen@iki.fi>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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. */

#include "gmcerts.h"

#include <the_Foundation/file.h>
#include <the_Foundation/mutex.h>
#include <the_Foundation/path.h>
#include <the_Foundation/regexp.h>
#include <the_Foundation/stringhash.h>
#include <the_Foundation/time.h>
#include <ctype.h>

static const char *filename_GmCerts_ = "trusted.txt";

iDeclareClass(TrustEntry)

struct Impl_TrustEntry {
    iObject object;
    iBlock fingerprint;
    iTime validUntil;
};

void init_TrustEntry(iTrustEntry *d, const iBlock *fingerprint, const iDate *until) {
    initCopy_Block(&d->fingerprint, fingerprint);
    init_Time(&d->validUntil, until);
}

void deinit_TrustEntry(iTrustEntry *d) {
    deinit_Block(&d->fingerprint);
}

iDefineObjectConstructionArgs(TrustEntry, (const iBlock *fingerprint, const iDate *until), fingerprint, until)
iDefineClass(TrustEntry)

/*-----------------------------------------------------------------------------------------------*/

struct Impl_GmCerts {
    iMutex mtx;
    iString saveDir;
    iStringHash *trusted;
};

iDefineTypeConstructionArgs(GmCerts, (const char *saveDir), saveDir)

static void save_GmCerts_(const iGmCerts *d) {
    iBeginCollect();
    iFile *f = new_File(collect_String(concatCStr_Path(&d->saveDir, filename_GmCerts_)));
    if (open_File(f, writeOnly_FileMode | text_FileMode)) {
        iString line;
        init_String(&line);
        iConstForEach(StringHash, i, d->trusted) {
            const iTrustEntry *trust = value_StringHashNode(i.value);
            format_String(&line,
                          "%s %ld %s\n",
                          cstr_String(key_StringHashConstIterator(&i)),
                          integralSeconds_Time(&trust->validUntil),
                          cstrCollect_String(hexEncode_Block(&trust->fingerprint)));
            write_File(f, &line.chars);
        }
        deinit_String(&line);
    }
    iRelease(f);
    iEndCollect();
}

static void load_GmCerts_(iGmCerts *d) {
    iFile *f = new_File(collect_String(concatCStr_Path(&d->saveDir, filename_GmCerts_)));
    if (open_File(f, readOnly_FileMode | text_FileMode)) {
        iRegExp *      pattern = new_RegExp("([^\\s]+) ([0-9]+) ([a-z0-9]+)", 0);
        const iRangecc src     = range_Block(collect_Block(readAll_File(f)));
        iRangecc       line    = iNullRange;
        while (nextSplit_Rangecc(&src, "\n", &line)) {
            iRegExpMatch m;
            if (matchRange_RegExp(pattern, line, &m)) {
                const iRangecc domain = capturedRange_RegExpMatch(&m, 1);
                const iRangecc until  = capturedRange_RegExpMatch(&m, 2);
                const iRangecc fp     = capturedRange_RegExpMatch(&m, 3);
                time_t sec;
                sscanf(until.start, "%ld", &sec);
                iDate untilDate;
                initSinceEpoch_Date(&untilDate, sec);
                insert_StringHash(d->trusted,
                                  collect_String(newRange_String(domain)),
                                  new_TrustEntry(collect_Block(hexDecode_Rangecc(fp)),
                                                 &untilDate));
            }
        }
        iRelease(pattern);
    }
    iRelease(f);
}

void init_GmCerts(iGmCerts *d, const char *saveDir) {
    init_Mutex(&d->mtx);
    initCStr_String(&d->saveDir, saveDir);
    d->trusted = new_StringHash();
    load_GmCerts_(d);
}

void deinit_GmCerts(iGmCerts *d) {
    iGuardMutex(&d->mtx, {
        iRelease(d->trusted);
        deinit_String(&d->saveDir);
    });
    deinit_Mutex(&d->mtx);
}

iBool checkTrust_GmCerts(iGmCerts *d, iRangecc domain, const iTlsCertificate *cert) {
    if (!cert) {
        return iFalse;
    }
    if (isExpired_TlsCertificate(cert)) {
        return iFalse;
    }
    if (!verifyDomain_TlsCertificate(cert, domain)) {
        return iFalse;
    }
    /* Good certificate. If not already trusted, add it now. */
    const iString *key = collect_String(newRange_String(domain));
    iDate until;
    validUntil_TlsCertificate(cert, &until);
    iBlock *fingerprint = collect_Block(fingerprint_TlsCertificate(cert));
    lock_Mutex(&d->mtx);
    iTrustEntry *trust = value_StringHash(d->trusted, key);
    if (trust) {
        /* We already have it, check if it matches the one we trust for this domain (if it's
           still valid. */
        iTime now;
        initCurrent_Time(&now);
        if (secondsSince_Time(&trust->validUntil, &now) > 0) {
            /* Trusted cert is still valid. */
            const iBool isTrusted = cmp_Block(fingerprint, &trust->fingerprint) == 0;
            unlock_Mutex(&d->mtx);
            return isTrusted;
        }
        /* Update the trusted cert. */
        init_Time(&trust->validUntil, &until);
        set_Block(&trust->fingerprint, fingerprint);
    }
    else {
        insert_StringHash(d->trusted, key, iClob(new_TrustEntry(fingerprint, &until)));
    }
    save_GmCerts_(d);
    unlock_Mutex(&d->mtx);
    return iTrue;
}