File: pool_ssl.c

package info (click to toggle)
pgpool2 3.3.4-1~bpo70%2B1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy-backports
  • size: 9,196 kB
  • sloc: ansic: 59,850; sh: 12,893; yacc: 10,787; lex: 4,637; sql: 743; makefile: 481; java: 469; php: 125; ruby: 98; asm: 5
file content (339 lines) | stat: -rw-r--r-- 8,573 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
/* -*-pgsql-c-*- */
/*
 * $Header$
 *
 * pgpool: a language independent connection pool server for PostgreSQL
 * written by Tatsuo Ishii
 *
 * Copyright (c) 2003-2013	PgPool Global Development Group
 *
 * Permission to use, copy, modify, and distribute this software and
 * its documentation for any purpose and without fee is hereby
 * granted, provided that the above copyright notice appear in all
 * copies and that both that copyright notice and this permission
 * notice appear in supporting documentation, and that the name of the
 * author not be used in advertising or publicity pertaining to
 * distribution of the software without specific, written prior
 * permission. The author makes no representations about the
 * suitability of this software for any purpose.  It is provided "as
 * is" without express or implied warranty.
 *
 * pool_ssl.c: ssl negotiation functions
 *
 */

#include <string.h>

#include "config.h"
#include "pool.h"
#include "pool_stream.h"
#include "pool_config.h"

#ifdef USE_SSL

#define SSL_RETURN_VOID_IF(cond, msg) \
	do { \
		if ( (cond) ) { \
			perror_ssl( (msg) ); \
			return; \
		} \
	} while (0);

#define SSL_RETURN_ERROR_IF(cond, msg) \
	do { \
		if ( (cond) ) { \
			perror_ssl( (msg) ); \
			return -1; \
		} \
	} while (0);

#include <arpa/inet.h> /* for htonl() */

/* Major/minor codes to negotiate SSL prior to startup packet */
#define NEGOTIATE_SSL_CODE ( 1234<<16 | 5679 )

/* enum flag for differentiating server->client vs client->server SSL */
enum ssl_conn_type { ssl_conn_clientserver, ssl_conn_serverclient };

/* perform per-connection ssl initialization.  returns nonzero on error */
static int init_ssl_ctx(POOL_CONNECTION *cp, enum ssl_conn_type conntype);

/* OpenSSL error message */
static void perror_ssl(const char *context);

/* attempt to negotiate a secure connection */
void pool_ssl_negotiate_clientserver(POOL_CONNECTION *cp) {
	int ssl_packet[2] = { htonl(sizeof(int)*2), htonl(NEGOTIATE_SSL_CODE) };
	char server_response;

	cp->ssl_active = -1;

	if ( (!pool_config->ssl) || init_ssl_ctx(cp, ssl_conn_clientserver))
		return;

	pool_debug("pool_ssl: sending client->server SSL request");
	pool_write_and_flush(cp, ssl_packet, sizeof(int)*2);

	if (pool_read(cp, &server_response, 1) < 0)
	{
		pool_error("pool_ssl_negotiate_clientserver: pool_read failed");
		return;
	}

	pool_debug("pool_ssl: client->server SSL response: %c", server_response);

	switch (server_response) {
		case 'S':
			SSL_set_fd(cp->ssl, cp->fd);
			SSL_RETURN_VOID_IF( (SSL_connect(cp->ssl) < 0),
			                    "SSL_connect");
			cp->ssl_active = 1;
			break;
		case 'N':
			/*
			 * If backend does not support SSL but pgpool does, we get this.
			 * i.e. This is normal.
			 */
			pool_debug("pool_ssl: server doesn't want to talk SSL");
			break;
		default:
			pool_error("pool_ssl: unhandled response: %c", server_response);
			break;
	}
}


/* attempt to negotiate a secure connection */
void pool_ssl_negotiate_serverclient(POOL_CONNECTION *cp) {

	cp->ssl_active = -1;

	if ( (!pool_config->ssl) || init_ssl_ctx(cp, ssl_conn_serverclient)) {
		/* write back an "SSL reject" response before returning */
		pool_write_and_flush(cp, "N", 1);
	} else {
		/* write back an "SSL accept" response */
		pool_write_and_flush(cp, "S", 1);

		SSL_set_fd(cp->ssl, cp->fd);
		SSL_RETURN_VOID_IF( (SSL_accept(cp->ssl) < 0), "SSL_accept");
		cp->ssl_active = 1;
	}
}

void pool_ssl_close(POOL_CONNECTION *cp) {
	if (cp->ssl) { 
		SSL_shutdown(cp->ssl); 
		SSL_free(cp->ssl); 
	} 

	if (cp->ssl_ctx) 
		SSL_CTX_free(cp->ssl_ctx);
}

int pool_ssl_read(POOL_CONNECTION *cp, void *buf, int size) {
	int n;
	int err;

 retry:
	errno = 0;
	n = SSL_read(cp->ssl, buf, size);
	err = SSL_get_error(cp->ssl, n);

	switch (err)
	{
		case SSL_ERROR_NONE:
			break;
		case SSL_ERROR_WANT_READ:
		case SSL_ERROR_WANT_WRITE:

			/*
			 * Returning 0 here would cause caller to wait for read-ready,
			 * which is not correct since what SSL wants is wait for
			 * write-ready.  The former could get us stuck in an infinite
			 * wait, so don't risk it; busy-loop instead.
			 */
			goto retry;

		case SSL_ERROR_SYSCALL:
			if (n == -1)
			{
				pool_error("SSL_read error: %d", err);
			}
			else
			{
				pool_error("SSL_read error: EOF detected");
				n = -1;
			}
			break;

		case SSL_ERROR_SSL:
		case SSL_ERROR_ZERO_RETURN:
			perror_ssl("SSL_read");
			n = -1;
			break;
		default:
			pool_error("pool_ssl_read: unrecognized error code: %d", err);
			/*
			 * We assume that the connection is broken. Returns 0
			 * rather than -1 in this case because -1 triggers
			 * unwanted failover in the caller (pool_read).
			 */
			n = 0;
			break;
	}

	return n;
}

int pool_ssl_write(POOL_CONNECTION *cp, const void *buf, int size)
{
	int n;
	int err;

retry:
	errno = 0;
	n = SSL_write(cp->ssl, buf, size);
	err = SSL_get_error(cp->ssl, n);
	switch (err)
	{
		case SSL_ERROR_NONE:
			break;

		case SSL_ERROR_WANT_READ:
		case SSL_ERROR_WANT_WRITE:
			goto retry;

		case SSL_ERROR_SYSCALL:
			if (n == -1)
			{
				pool_error("SSL_write error: %d", err);
			}
			else
			{
				pool_error("SSL_write error: EOF detected");
				n = -1;
			}
			break;

		case SSL_ERROR_SSL:
		case SSL_ERROR_ZERO_RETURN:
			perror_ssl("SSL_write");
			n = -1;
			break;

		default:
			pool_error("pool_ssl_write: unrecognized error code: %d", err);
			/*
			 * We assume that the connection is broken.
			 */
			n = -1;
			break;
	}
	return n;
}

static int init_ssl_ctx(POOL_CONNECTION *cp, enum ssl_conn_type conntype) {
	int error = 0;
	char *cacert = NULL, *cacert_dir = NULL;

	/* initialize SSL members */
	cp->ssl_ctx = SSL_CTX_new(TLSv1_method());
	SSL_RETURN_ERROR_IF( (! cp->ssl_ctx), "SSL_CTX_new" );

	if ( conntype == ssl_conn_serverclient) {
		error = SSL_CTX_use_certificate_file(cp->ssl_ctx,
		                                     pool_config->ssl_cert,
		                                     SSL_FILETYPE_PEM);
		SSL_RETURN_ERROR_IF( (error <= 0), "Loading SSL certificate");

		error = SSL_CTX_use_PrivateKey_file(cp->ssl_ctx,
		                                    pool_config->ssl_key,
		                                    SSL_FILETYPE_PEM);
		SSL_RETURN_ERROR_IF( (error <= 0), "Loading SSL private key");
	} else {
		/* set extra verification if ssl_ca_cert or ssl_ca_cert_dir are set */
		if (strlen(pool_config->ssl_ca_cert))
			cacert = pool_config->ssl_ca_cert;
		if (strlen(pool_config->ssl_ca_cert_dir))
			cacert_dir = pool_config->ssl_ca_cert_dir;
    
		if ( cacert || cacert_dir ) {
			error = (!SSL_CTX_load_verify_locations(cp->ssl_ctx,
			                                        cacert,
			                                        cacert_dir));
			SSL_RETURN_ERROR_IF(error, "SSL verification setup");
			SSL_CTX_set_verify(cp->ssl_ctx, SSL_VERIFY_PEER, NULL);
		}
	}

	cp->ssl = SSL_new(cp->ssl_ctx);
	SSL_RETURN_ERROR_IF( (! cp->ssl), "SSL_new");

	return 0;
}

static void perror_ssl(const char *context) {
	unsigned long err;
	static const char *no_err_reason = "no SSL error reported";
	const char *reason;

	err = ERR_get_error();
	if (! err) {
		reason = no_err_reason;
	} else {
		reason = ERR_reason_error_string(err);
	}

	if (reason != NULL) {
		pool_error("pool_ssl: %s: %s", context, reason);
	} else {
		pool_error("pool_ssl: %s: Unknown SSL error %lu", context, err);
	}
}

/*
 * Return true if SSL layer has any pending data in buffer
 */
bool pool_ssl_pending(POOL_CONNECTION *cp)
{
	if (cp->ssl_active > 0 && SSL_pending(cp->ssl) > 0)
		return true;
	return false;
}

#else /* USE_SSL: wrap / no-op ssl functionality if it's not available */

void pool_ssl_negotiate_serverclient(POOL_CONNECTION *cp) {
	pool_debug("pool_ssl: SSL requested but SSL support is not available");
	pool_write_and_flush(cp, "N", 1);
	cp->ssl_active = -1;
}

void pool_ssl_negotiate_clientserver(POOL_CONNECTION *cp) {
	pool_debug("pool_ssl: SSL requested but SSL support is not available");
	cp->ssl_active = -1;
}

void pool_ssl_close(POOL_CONNECTION *cp) { return; }

int pool_ssl_read(POOL_CONNECTION *cp, void *buf, int size) {
	pool_error("pool_ssl: SSL i/o called but SSL support is not available");
	notice_backend_error(cp->db_node_id);
	child_exit(1);
	return -1; /* never reached */
}

int pool_ssl_write(POOL_CONNECTION *cp, const void *buf, int size) {
	pool_error("pool_ssl: SSL i/o called but SSL support is not available");
	notice_backend_error(cp->db_node_id);
	child_exit(1);
	return -1; /* never reached */
}

bool pool_ssl_pending(POOL_CONNECTION *cp)
{
	return false;
}

#endif /* USE_SSL */