File: tls_client.c

package info (click to toggle)
cfengine3 3.24.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 37,552 kB
  • sloc: ansic: 163,161; sh: 10,296; python: 2,950; makefile: 1,744; lex: 784; yacc: 633; perl: 211; pascal: 157; xml: 21; sed: 13
file content (379 lines) | stat: -rw-r--r-- 11,022 bytes parent folder | download | duplicates (2)
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
/*
  Copyright 2024 Northern.tech AS

  This file is part of CFEngine 3 - written and maintained by Northern.tech AS.

  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; version 3.

  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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA

  To the extent this program is licensed as part of the Enterprise
  versions of CFEngine, the applicable Commercial Open Source License
  (COSL) may apply to this file if you as a licensee so wish it. See
  included file COSL.txt.
*/


#include <cfnet.h>

#include <openssl/err.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>

#include <logging.h>
#include <misc_lib.h>

#include <tls_client.h>
#include <tls_generic.h>
#include <net.h>                     /* SendTransaction, ReceiveTransaction */
#include <protocol.h>                      /* ParseProtocolVersionNetwork() */
/* TODO move crypto.h to libutils */
#include <crypto.h>                                       /* LoadSecretKeys */

#define MAX_CONNECT_RETRIES 10

extern RSA *PRIVKEY, *PUBKEY;


/**
 * Global SSL context for initiated connections over the TLS protocol. For the
 * agent, they are written only once, *after* the common control bundles have
 * been evaluated. I.e. GenericAgentPostLoadInit() is called
 * after LoadPolicy().
 *
 * 1. Common bundles evaluation: LoadPolicy()->PolicyResolve()
 * 2. Create TLS contexts:       GenericAgentPostLoadInit()->cfnet_init()
 */
static SSL_CTX *SSLCLIENTCONTEXT = NULL;
static X509 *SSLCLIENTCERT = NULL;


bool TLSClientIsInitialized()
{
    return (SSLCLIENTCONTEXT != NULL);
}

/**
 * @warning Make sure you've called CryptoInitialize() first!
 *
 * @TODO if this function is called a second time, it just returns true, and
 * does not do nothing more. What if the settings (e.g. tls_min_version) have
 * changed? This can happen when cf-serverd reloads policy. Fixing this goes
 * much deeper though, as it would require cf-serverd to call
 * GenericAgentDiscoverContext() when reloading policy.
 */
bool TLSClientInitialize(const char *tls_min_version,
                         const char *ciphers)
{
    int ret;
    static bool is_initialised = false;

    if (is_initialised)
    {
        return true;
    }

    if (PRIVKEY == NULL || PUBKEY == NULL)
    {
        /* VERBOSE in case it's a custom, local-only installation. */
        Log(LOG_LEVEL_VERBOSE, "No public/private key pair is loaded,"
            " please create one using cf-key");
        return false;
    }
    if (!TLSGenericInitialize())
    {
        return false;
    }

    SSLCLIENTCONTEXT = SSL_CTX_new(SSLv23_client_method());
    if (SSLCLIENTCONTEXT == NULL)
    {
        Log(LOG_LEVEL_ERR, "SSL_CTX_new: %s",
            TLSErrorString(ERR_get_error()));
        goto err1;
    }

    TLSSetDefaultOptions(SSLCLIENTCONTEXT, tls_min_version);

    if (!TLSSetCipherList(SSLCLIENTCONTEXT, ciphers))
    {
        goto err2;
    }

    /* Create cert into memory and load it into SSL context. */
    SSLCLIENTCERT = TLSGenerateCertFromPrivKey(PRIVKEY);
    if (SSLCLIENTCERT == NULL)
    {
        Log(LOG_LEVEL_ERR,
            "Failed to generate in-memory-certificate from private key");
        goto err2;
    }

    SSL_CTX_use_certificate(SSLCLIENTCONTEXT, SSLCLIENTCERT);

    ret = SSL_CTX_use_RSAPrivateKey(SSLCLIENTCONTEXT, PRIVKEY);
    if (ret != 1)
    {
        Log(LOG_LEVEL_ERR, "Failed to use RSA private key: %s",
            TLSErrorString(ERR_get_error()));
        goto err3;
    }

    /* Verify cert consistency. */
    ret = SSL_CTX_check_private_key(SSLCLIENTCONTEXT);
    if (ret != 1)
    {
        Log(LOG_LEVEL_ERR, "Inconsistent key and TLS cert: %s",
            TLSErrorString(ERR_get_error()));
        goto err3;
    }

    is_initialised = true;
    return true;

  err3:
    X509_free(SSLCLIENTCERT);
    SSLCLIENTCERT = NULL;
  err2:
    SSL_CTX_free(SSLCLIENTCONTEXT);
    SSLCLIENTCONTEXT = NULL;
  err1:
    return false;
}

void TLSDeInitialize()
{
    if (PUBKEY)
    {
        RSA_free(PUBKEY);
        PUBKEY = NULL;
    }

    if (PRIVKEY)
    {
        RSA_free(PRIVKEY);
        PRIVKEY = NULL;
    }

    if (SSLCLIENTCERT != NULL)
    {
        X509_free(SSLCLIENTCERT);
        SSLCLIENTCERT = NULL;
    }

    if (SSLCLIENTCONTEXT != NULL)
    {
        SSL_CTX_free(SSLCLIENTCONTEXT);
        SSLCLIENTCONTEXT = NULL;
    }
}


/**
 * 1. Receive "CFE_v%d" server hello
 * 2. Send two lines: one "CFE_v%d" with the protocol version we wish to have,
 *    and another with id, e.g. "IDENTITY USERNAME=blah".
 * 3. Receive "OK WELCOME"
 *
 * @return > 0: success. #conn_info->type has been updated with the negotiated
 *              protocol version.
 *           0: server denial
 *          -1: error
 */
int TLSClientIdentificationDialog(ConnectionInfo *conn_info,
                                  const char *username)
{
    char line[1024] = "";
    int ret;

    /* Receive CFE_v%d ... That's the first thing the server sends. */
    ret = TLSRecvLines(conn_info->ssl, line, sizeof(line));
    if (ret == -1)
    {
        Log(LOG_LEVEL_ERR, "Connection was hung up during identification! (0)");
        return -1;
    }

    ProtocolVersion wanted_version;
    if (conn_info->protocol == CF_PROTOCOL_UNDEFINED)
    {
        wanted_version = CF_PROTOCOL_LATEST;
    }
    else
    {
        wanted_version = conn_info->protocol;
    }

    const ProtocolVersion received_version = ParseProtocolVersionNetwork(line);

    if (received_version < wanted_version && ProtocolIsTLS(received_version))
    {
        // Downgrade as long as it's still TLS
        wanted_version = received_version;
    }
    else if (ProtocolIsUndefined(received_version)
             || ProtocolIsClassic(received_version))
    {
        Log(LOG_LEVEL_ERR, "Server sent a bad version number! (0a)");
        return -1;
    }

    assert(wanted_version <= received_version); // Server supported version
    assert(ProtocolIsTLS(wanted_version));

    /* Send "CFE_v%d cf-agent version". */
    char version_string[128];
    int len = snprintf(version_string, sizeof(version_string),
                       "CFE_v%d %s %s\n",
                       wanted_version, "cf-agent", VERSION); /* TODO argv[0] */

    ret = TLSSend(conn_info->ssl, version_string, len);
    if (ret != len)
    {
        Log(LOG_LEVEL_ERR, "Connection was hung up during identification! (1)");
        return -1;
    }

    strcpy(line, "IDENTITY");
    size_t line_len = strlen(line);

    if (username != NULL)
    {
        ret = snprintf(&line[line_len], sizeof(line) - line_len,
                       " USERNAME=%s", username);
        if (ret < 0)
        {
            Log(LOG_LEVEL_ERR, "snprintf failed: %s", GetErrorStr());
            return -1;
        }
        else if ((unsigned int) ret >= sizeof(line) - line_len)
        {
            Log(LOG_LEVEL_ERR, "Sending IDENTITY truncated: %s", line);
            return -1;
        }
        line_len += ret;
    }

    /* Overwrite the terminating '\0', we don't need it anyway. */
    line[line_len] = '\n';
    line_len++;

    ret = TLSSend(conn_info->ssl, line, line_len);
    if (ret == -1)
    {
        Log(LOG_LEVEL_ERR,
            "Connection was hung up during identification! (2)");
        return -1;
    }

    /* Server might hang up here, after we sent identification! We
     * must get the "OK WELCOME" message for everything to be OK. */
    static const char OK[] = "OK WELCOME";
    size_t OK_len = sizeof(OK) - 1;
    ret = TLSRecvLines(conn_info->ssl, line, sizeof(line));
    if (ret < 0)
    {
        Log(LOG_LEVEL_ERR,
            "Connection was hung up during identification! (3)");
        return -1;
    }
    else if ((size_t) ret < OK_len || strncmp(line, OK, OK_len) != 0)
    {
        Log(LOG_LEVEL_ERR,
            "Peer did not accept our identity! Responded: %s",
            line);
        return 0;
    }

    /* Before it contained the protocol version we requested from the server,
     * now we put in the value that was negotiated. */
    conn_info->protocol = wanted_version;

    return 1;
}

/**
 * We directly initiate a TLS handshake with the server. If the server is old
 * version (does not speak TLS) the connection will be denied.
 * @note the socket file descriptor in #conn_info must be connected and *not*
 *       non-blocking
 * @return -1 in case of error
 */
int TLSTry(ConnectionInfo *conn_info)
{
    assert(conn_info != NULL);

    if (PRIVKEY == NULL || PUBKEY == NULL)
    {
        Log(LOG_LEVEL_ERR, "No public/private key pair is loaded,"
            " please create one using cf-key");
        return -1;
    }
    assert(SSLCLIENTCONTEXT != NULL);

    conn_info->ssl = SSL_new(SSLCLIENTCONTEXT);
    if (conn_info->ssl == NULL)
    {
        Log(LOG_LEVEL_ERR, "SSL_new: %s",
            TLSErrorString(ERR_get_error()));
        return -1;
    }

    /* Pass conn_info inside the ssl struct for TLSVerifyCallback(). */
    SSL_set_ex_data(conn_info->ssl, CONNECTIONINFO_SSL_IDX, conn_info);

    /* Initiate the TLS handshake over the already open TCP socket. */
    SSL_set_fd(conn_info->ssl, conn_info->sd);

    bool connected = false;
    bool should_retry = true;
    int remaining_tries = MAX_CONNECT_RETRIES;
    int ret;
    while (!connected && should_retry)
    {
        ret = SSL_connect(conn_info->ssl);
        /* 1 means connected, 0 means shut down, <0 means error
         * (see man:SSL_connect(3)) */
        connected = (ret == 1);
        if (ret == 0)
        {
            should_retry = false;
        }
        else if (ret < 0)
        {
            int code = TLSLogError(conn_info->ssl, LOG_LEVEL_VERBOSE,
                                   "Attempt to establish TLS connection failed", ret);
            /* see man:SSL_connect(3) */
            should_retry = ((remaining_tries > 0) &&
                            ((code == SSL_ERROR_WANT_READ) || (code == SSL_ERROR_WANT_WRITE)));
        }
        if (!connected && should_retry)
        {
            sleep(1);
            remaining_tries--;
        }
    }
    if (!connected)
    {
        TLSLogError(conn_info->ssl, LOG_LEVEL_ERR,
                    "Failed to establish TLS connection", ret);
        return -1;
    }

    Log(LOG_LEVEL_VERBOSE, "TLS version negotiated: %8s; Cipher: %s,%s",
        SSL_get_version(conn_info->ssl),
        SSL_get_cipher_name(conn_info->ssl),
        SSL_get_cipher_version(conn_info->ssl));
    Log(LOG_LEVEL_VERBOSE, "TLS session established, checking trust...");

    return 0;
}