nm-crypto-gnutls.c 11.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager Wireless Applet -- Display wireless access points and allow user control
 *
 * Dan Williams <dcbw@redhat.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA.
 *
21
 * Copyright 2007 - 2015 Red Hat, Inc.
22 23
 */

24
#include "nm-default.h"
25

26
#include "nm-crypto-impl.h"
27

28
#include <gnutls/gnutls.h>
29
#include <gnutls/crypto.h>
30 31 32
#include <gnutls/x509.h>
#include <gnutls/pkcs12.h>

33
#include "nm-glib-aux/nm-secret-utils.h"
34
#include "nm-errors.h"
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
/*****************************************************************************/

static gboolean
_get_cipher_info (NMCryptoCipherType cipher,
                  int *out_cipher_mech,
                  guint8 *out_real_iv_len)
{
	static const int cipher_mechs[] = {
		[NM_CRYPTO_CIPHER_DES_EDE3_CBC] = GNUTLS_CIPHER_3DES_CBC,
		[NM_CRYPTO_CIPHER_DES_CBC]      = GNUTLS_CIPHER_DES_CBC,
		[NM_CRYPTO_CIPHER_AES_128_CBC]  = GNUTLS_CIPHER_AES_128_CBC,
		[NM_CRYPTO_CIPHER_AES_192_CBC]  = GNUTLS_CIPHER_AES_192_CBC,
		[NM_CRYPTO_CIPHER_AES_256_CBC]  = GNUTLS_CIPHER_AES_256_CBC,
	};

	g_return_val_if_fail (_NM_INT_NOT_NEGATIVE (cipher) && (gsize) cipher < G_N_ELEMENTS (cipher_mechs), FALSE);

	if (cipher_mechs[cipher] == 0)
		return FALSE;

	NM_SET_OUT (out_cipher_mech, cipher_mechs[cipher]);
	NM_SET_OUT (out_real_iv_len, nm_crypto_cipher_get_info (cipher)->real_iv_len);
	return TRUE;
}

/*****************************************************************************/
62 63

gboolean
64
_nm_crypto_init (GError **error)
65
{
66 67
	static gboolean initialized = FALSE;

68 69 70
	if (initialized)
		return TRUE;

71 72
	if (gnutls_global_init () != 0) {
		gnutls_global_deinit ();
73 74 75
		g_set_error_literal (error, NM_CRYPTO_ERROR,
		                     NM_CRYPTO_ERROR_FAILED,
		                     _("Failed to initialize the crypto engine."));
76 77 78 79 80 81 82
		return FALSE;
	}

	initialized = TRUE;
	return TRUE;
}

83 84
/*****************************************************************************/

85
guint8 *
86
_nmtst_crypto_decrypt (NMCryptoCipherType cipher,
87 88
                       const guint8 *data,
                       gsize data_len,
89 90 91 92
                       const guint8 *iv,
                       gsize iv_len,
                       const guint8 *key,
                       gsize key_len,
93 94
                       gsize *out_len,
                       GError **error)
95
{
96 97 98
	gnutls_cipher_hd_t ctx;
	gnutls_datum_t key_dt, iv_dt;
	int err;
99 100 101
	int cipher_mech;
	nm_auto_clear_secret_ptr NMSecretPtr output = { 0 };
	guint8 pad_i, pad_len;
102
	guint8 real_iv_len;
103

104
	if (!_get_cipher_info (cipher, &cipher_mech, &real_iv_len)) {
105
		g_set_error (error, NM_CRYPTO_ERROR,
106
		             NM_CRYPTO_ERROR_UNKNOWN_CIPHER,
107
		             _("Unsupported key cipher for decryption"));
108 109 110
		return NULL;
	}

111 112 113
	if (!_nm_crypto_init (error))
		return NULL;

114 115
	if (iv_len < real_iv_len) {
		g_set_error (error, NM_CRYPTO_ERROR,
116
		             NM_CRYPTO_ERROR_INVALID_DATA,
117 118
		             _("Invalid IV length (must be at least %u)."),
		             (guint) real_iv_len);
119 120 121
		return NULL;
	}

122 123
	output.len = data_len;
	output.bin = g_malloc (data_len);
124

125 126 127 128
	key_dt.data = (unsigned char *) key;
	key_dt.size = key_len;
	iv_dt.data = (unsigned char *) iv;
	iv_dt.size = iv_len;
129

130 131
	err = gnutls_cipher_init (&ctx, cipher_mech, &key_dt, &iv_dt);
	if (err < 0) {
132
		g_set_error (error, NM_CRYPTO_ERROR,
133
		             NM_CRYPTO_ERROR_DECRYPTION_FAILED,
134 135
		             _("Failed to initialize the decryption cipher context: %s (%s)"),
		             gnutls_strerror_name (err), gnutls_strerror (err));
136
		return NULL;
137 138
	}

139 140 141 142
	err = gnutls_cipher_decrypt2 (ctx, data, data_len, output.bin, output.len);

	gnutls_cipher_deinit (ctx);

143
	if (err < 0) {
144
		g_set_error (error, NM_CRYPTO_ERROR,
145
		             NM_CRYPTO_ERROR_DECRYPTION_FAILED,
146 147
		             _("Failed to decrypt the private key: %s (%s)"),
		             gnutls_strerror_name (err), gnutls_strerror (err));
148
		return NULL;
149
	}
150 151 152 153

	pad_len = output.len > 0
	          ? output.bin[output.len - 1]
	          : 0;
154 155

	/* Check if the padding at the end of the decrypted data is valid */
156 157
	if (   pad_len == 0
	    || pad_len > real_iv_len) {
158
		g_set_error (error, NM_CRYPTO_ERROR,
159
		             NM_CRYPTO_ERROR_DECRYPTION_FAILED,
160
		             _("Failed to decrypt the private key: unexpected padding length."));
161
		return NULL;
162 163 164 165 166
	}

	/* Validate tail padding; last byte is the padding size, and all pad bytes
	 * should contain the padding size.
	 */
167 168
	for (pad_i = 1; pad_i <= pad_len; ++pad_i) {
		if (output.bin[data_len - pad_i] != pad_len) {
169
			g_set_error (error, NM_CRYPTO_ERROR,
170
			             NM_CRYPTO_ERROR_DECRYPTION_FAILED,
171
			             _("Failed to decrypt the private key."));
172
			return NULL;
173 174 175
		}
	}

176 177
	*out_len = output.len - pad_len;
	return g_steal_pointer (&output.bin);
178 179
}

180
guint8 *
181
_nmtst_crypto_encrypt (NMCryptoCipherType cipher,
182 183
                       const guint8 *data,
                       gsize data_len,
184 185 186
                       const guint8 *iv,
                       gsize iv_len,
                       const guint8 *key,
187 188 189
                       gsize key_len,
                       gsize *out_len,
                       GError **error)
190
{
191 192 193
	gnutls_cipher_hd_t ctx;
	gnutls_datum_t key_dt, iv_dt;
	int err;
194
	int cipher_mech;
195 196 197 198 199
	nm_auto_clear_secret_ptr NMSecretPtr output = { 0 };
	nm_auto_clear_secret_ptr NMSecretPtr padded_buf = { 0 };
	gsize i, pad_len;

	nm_assert (iv_len);
200

201 202
	if (   cipher == NM_CRYPTO_CIPHER_DES_CBC
	    || !_get_cipher_info (cipher, &cipher_mech, NULL)) {
203
		g_set_error (error, NM_CRYPTO_ERROR,
204
		             NM_CRYPTO_ERROR_UNKNOWN_CIPHER,
205
		             _("Unsupported key cipher for encryption"));
206 207 208
		return NULL;
	}

209 210 211
	if (!_nm_crypto_init (error))
		return NULL;

212 213 214 215
	key_dt.data = (unsigned char *) key;
	key_dt.size = key_len;
	iv_dt.data = (unsigned char *) iv;
	iv_dt.size = iv_len;
216

217 218
	err = gnutls_cipher_init (&ctx, cipher_mech, &key_dt, &iv_dt);
	if (err < 0) {
219
		g_set_error (error, NM_CRYPTO_ERROR,
220
		             NM_CRYPTO_ERROR_ENCRYPTION_FAILED,
221 222
		             _("Failed to initialize the encryption cipher context: %s (%s)"),
		             gnutls_strerror_name (err), gnutls_strerror (err));
223
		return NULL;
224 225
	}

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
	/* If data_len % ivlen == 0, then we add another complete block
	 * onto the end so that the decrypter knows there's padding.
	 */
	pad_len = iv_len - (data_len % iv_len);

	padded_buf.len = data_len + pad_len;
	padded_buf.bin = g_malloc (padded_buf.len);
	memcpy (padded_buf.bin, data, data_len);
	for (i = 0; i < pad_len; i++)
		padded_buf.bin[data_len + i] = (guint8) (pad_len & 0xFF);

	output.len = padded_buf.len;
	output.bin = g_malloc (output.len);

	err = gnutls_cipher_encrypt2 (ctx, padded_buf.bin, padded_buf.len, output.bin, output.len);

	gnutls_cipher_deinit (ctx);

244
	if (err < 0) {
245
		g_set_error (error, NM_CRYPTO_ERROR,
246
		             NM_CRYPTO_ERROR_ENCRYPTION_FAILED,
247 248
		             _("Failed to encrypt the data: %s (%s)"),
		             gnutls_strerror_name (err), gnutls_strerror (err));
249
		return NULL;
250 251
	}

252 253
	*out_len = output.len;
	return g_steal_pointer (&output.bin);
254 255
}

256
gboolean
257
_nm_crypto_verify_x509 (const guint8 *data,
258 259
                        gsize len,
                        GError **error)
260 261 262 263 264
{
	gnutls_x509_crt_t der;
	gnutls_datum_t dt;
	int err;

265
	if (!_nm_crypto_init (error))
266
		return FALSE;
267

268 269 270
	err = gnutls_x509_crt_init (&der);
	if (err < 0) {
		g_set_error (error, NM_CRYPTO_ERROR,
271
		             NM_CRYPTO_ERROR_INVALID_DATA,
272 273
		             _("Error initializing certificate data: %s"),
		             gnutls_strerror (err));
274
		return FALSE;
275 276 277 278 279 280 281 282
	}

	/* Try DER first */
	dt.data = (unsigned char *) data;
	dt.size = len;
	err = gnutls_x509_crt_import (der, &dt, GNUTLS_X509_FMT_DER);
	if (err == GNUTLS_E_SUCCESS) {
		gnutls_x509_crt_deinit (der);
283
		return TRUE;
284 285 286 287 288 289
	}

	/* And PEM next */
	err = gnutls_x509_crt_import (der, &dt, GNUTLS_X509_FMT_PEM);
	gnutls_x509_crt_deinit (der);
	if (err == GNUTLS_E_SUCCESS)
290
		return TRUE;
291 292

	g_set_error (error, NM_CRYPTO_ERROR,
293
	             NM_CRYPTO_ERROR_INVALID_DATA,
294 295
	             _("Couldn't decode certificate: %s"),
	             gnutls_strerror (err));
296
	return FALSE;
297 298 299
}

gboolean
300 301 302 303
_nm_crypto_verify_pkcs12 (const guint8 *data,
                          gsize data_len,
                          const char *password,
                          GError **error)
304 305 306 307 308 309 310
{
	gnutls_pkcs12_t p12;
	gnutls_datum_t dt;
	int err;

	g_return_val_if_fail (data != NULL, FALSE);

311
	if (!_nm_crypto_init (error))
312 313
		return FALSE;

314 315
	dt.data = (unsigned char *) data;
	dt.size = data_len;
316 317 318 319

	err = gnutls_pkcs12_init (&p12);
	if (err < 0) {
		g_set_error (error, NM_CRYPTO_ERROR,
320
		             NM_CRYPTO_ERROR_FAILED,
321 322 323 324 325 326 327 328 329 330 331 332
		             _("Couldn't initialize PKCS#12 decoder: %s"),
		             gnutls_strerror (err));
		return FALSE;
	}

	/* DER first */
	err = gnutls_pkcs12_import (p12, &dt, GNUTLS_X509_FMT_DER, 0);
	if (err < 0) {
		/* PEM next */
		err = gnutls_pkcs12_import (p12, &dt, GNUTLS_X509_FMT_PEM, 0);
		if (err < 0) {
			g_set_error (error, NM_CRYPTO_ERROR,
333
			             NM_CRYPTO_ERROR_INVALID_DATA,
334 335
			             _("Couldn't decode PKCS#12 file: %s"),
			             gnutls_strerror (err));
336 337
			gnutls_pkcs12_deinit (p12);
			return FALSE;
338 339 340 341
		}
	}

	err = gnutls_pkcs12_verify_mac (p12, password);
342 343 344 345

	gnutls_pkcs12_deinit (p12);

	if (err != GNUTLS_E_SUCCESS) {
346
		g_set_error (error, NM_CRYPTO_ERROR,
347
		             NM_CRYPTO_ERROR_DECRYPTION_FAILED,
348 349
		             _("Couldn't verify PKCS#12 file: %s"),
		             gnutls_strerror (err));
350
		return FALSE;
351 352
	}

353
	return TRUE;
354 355 356
}

gboolean
357 358 359 360 361
_nm_crypto_verify_pkcs8 (const guint8 *data,
                         gsize data_len,
                         gboolean is_encrypted,
                         const char *password,
                         GError **error)
362 363 364 365 366 367 368
{
	gnutls_x509_privkey_t p8;
	gnutls_datum_t dt;
	int err;

	g_return_val_if_fail (data != NULL, FALSE);

369
	if (!_nm_crypto_init (error))
370 371
		return FALSE;

372 373 374
	err = gnutls_x509_privkey_init (&p8);
	if (err < 0) {
		g_set_error (error, NM_CRYPTO_ERROR,
375
		             NM_CRYPTO_ERROR_FAILED,
376 377 378 379 380
		             _("Couldn't initialize PKCS#8 decoder: %s"),
		             gnutls_strerror (err));
		return FALSE;
	}

381 382 383
	dt.data = (unsigned char *) data;
	dt.size = data_len;

384 385 386 387 388
	err = gnutls_x509_privkey_import_pkcs8 (p8,
	                                        &dt,
	                                        GNUTLS_X509_FMT_DER,
	                                        is_encrypted ? password : NULL,
	                                        is_encrypted ? 0 : GNUTLS_PKCS_PLAIN);
389

390 391 392 393
	gnutls_x509_privkey_deinit (p8);

	if (err < 0) {
		if (err == GNUTLS_E_UNKNOWN_CIPHER_TYPE) {
394
			/* HACK: gnutls < 3.5.4 doesn't support all the cipher types that openssl
395 396 397 398 399 400 401
			 * can use with PKCS#8, so if we encounter one, we have to assume
			 * the given password works.  gnutls needs to unsuckify, apparently.
			 * Specifically, by default openssl uses pbeWithMD5AndDES-CBC
			 * which gnutls does not support.
			 */
		} else {
			g_set_error (error, NM_CRYPTO_ERROR,
402
			             NM_CRYPTO_ERROR_INVALID_DATA,
403 404 405 406 407 408 409 410 411 412
			             _("Couldn't decode PKCS#8 file: %s"),
			             gnutls_strerror (err));
			return FALSE;
		}
	}

	return TRUE;
}

gboolean
413
_nm_crypto_randomize (void *buffer, gsize buffer_len, GError **error)
414
{
415
	if (!_nm_crypto_init (error))
416 417
		return FALSE;

418
	gnutls_rnd (GNUTLS_RND_RANDOM, buffer, buffer_len);
419 420
	return TRUE;
}