ObjOpenSSL  Check-in [a64206ee2e]

Overview
Comment:Adjust to ObjFW changes
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: a64206ee2e56904b91ea70519a7019bb13cd749a419e90f4463c5dee4d018d16
User & Date: js on 2021-04-25 20:41:45
Other Links: manifest | tags
Context
2021-11-06
00:15
Adjust to ObjFW changes check-in: 8957076139 user: js tags: trunk
2021-04-25
20:41
Adjust to ObjFW changes check-in: a64206ee2e user: js tags: trunk
2021-04-03
20:16
Adjust to ObjFW coding style check-in: e5b470a14c user: js tags: trunk
Changes

Modified src/SSLSocket.m from [7d89379347] to [6562bd487a].

1
2
3
4
5
6
7
8
9
10
/*
 * Copyright (c) 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020
 *     Jonathan Schleifer <js@nil.im>
 * Copyright (c) 2011, Florian Zeitz <florob@babelmonkeys.de>
 * Copyright (c) 2011, Jos Kuijpers <jos@kuijpersvof.nl>
 *
 * https://fossil.nil.im/objopenssl
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above

|
|







1
2
3
4
5
6
7
8
9
10
/*
 * Copyright (c) 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020,
 *               2021, Jonathan Schleifer <js@nil.im>
 * Copyright (c) 2011, Florian Zeitz <florob@babelmonkeys.de>
 * Copyright (c) 2011, Jos Kuijpers <jos@kuijpersvof.nl>
 *
 * https://fossil.nil.im/objopenssl
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
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
#include <openssl/ssl.h>
#include <openssl/x509v3.h>

#if defined(__clang__)
# pragma clang diagnostic pop
#endif

#import <ObjFW/OFThread.h>
#import <ObjFW/OFHTTPRequest.h>
#import <ObjFW/OFData.h>
#import <ObjFW/OFLocale.h>

#import <ObjFW/OFAcceptFailedException.h>
#import <ObjFW/OFInitializationFailedException.h>
#import <ObjFW/OFInvalidArgumentException.h>
#import <ObjFW/OFNotOpenException.h>
#import <ObjFW/OFOutOfRangeException.h>
#import <ObjFW/OFReadFailedException.h>
#import <ObjFW/OFWriteFailedException.h>

#import <ObjFW/macros.h>
#import <ObjFW/mutex.h>

#import "SSLSocket.h"
#import "X509Certificate.h"

#import "SSLConnectionFailedException.h"
#import "SSLInvalidCertificateException.h"

#ifndef INVALID_SOCKET
# define INVALID_SOCKET -1
#endif

static SSL_CTX *ctx;
static of_mutex_t *ssl_mutexes;

static unsigned long
threadID(void)
{
	return (unsigned long)(uintptr_t)[OFThread currentThread];
}

static void
lockingCallback(int mode, int n, const char *file, int line)
{
	/*
	 * This function must handle up to CRYPTO_num_locks() mutexes.
	 * It must set the n-th lock if mode & CRYPTO_LOCK,
	 * release it otherwise.
	 */
	if (mode & CRYPTO_LOCK)
		of_mutex_lock(&ssl_mutexes[n]);
	else
		of_mutex_unlock(&ssl_mutexes[n]);
}

@interface SSLSocket ()
- (void)SSL_startTLSWithExpectedHost: (OFString *)host port: (uint16_t)port;
- (void)SSL_super_close;
@end








|
<
<
<
<
<
<
<
<
<
<
<
<
<
<












|
















|

|







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
#include <openssl/ssl.h>
#include <openssl/x509v3.h>

#if defined(__clang__)
# pragma clang diagnostic pop
#endif

#import <ObjFW/ObjFW.h>















#import "SSLSocket.h"
#import "X509Certificate.h"

#import "SSLConnectionFailedException.h"
#import "SSLInvalidCertificateException.h"

#ifndef INVALID_SOCKET
# define INVALID_SOCKET -1
#endif

static SSL_CTX *ctx;
static OFPlainMutex *SSLMutexes;

static unsigned long
threadID(void)
{
	return (unsigned long)(uintptr_t)[OFThread currentThread];
}

static void
lockingCallback(int mode, int n, const char *file, int line)
{
	/*
	 * This function must handle up to CRYPTO_num_locks() mutexes.
	 * It must set the n-th lock if mode & CRYPTO_LOCK,
	 * release it otherwise.
	 */
	if (mode & CRYPTO_LOCK)
		OFEnsure(OFPlainMutexLock(&SSLMutexes[n]) == 0);
	else
		OFEnsure(OFPlainMutexUnlock(&SSLMutexes[n]) == 0);
}

@interface SSLSocket ()
- (void)SSL_startTLSWithExpectedHost: (OFString *)host port: (uint16_t)port;
- (void)SSL_super_close;
@end

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
@synthesize privateKeyFile = _privateKeyFile;
@synthesize privateKeyPassphrase = _privateKeyPassphrase;
@synthesize verifiesCertificates = _verifiesCertificates;
@synthesize requestsClientCertificates = _requestsClientCertificates;

+ (void)load
{
	of_tls_socket_class = self;
}

+ (void)initialize
{
	int m;

	if (self != [SSLSocket class])
		return;

	CRYPTO_set_id_callback(&threadID);
	/* OpenSSL >= 1.1 defines the line above to a nop */
	(void)threadID;

	/* Generate number of mutexes needed */
	m = CRYPTO_num_locks();
	ssl_mutexes = malloc(m * sizeof(of_mutex_t));
	for (m--; m >= 0; m--)
		of_mutex_new(&ssl_mutexes[m]);

	CRYPTO_set_locking_callback(&lockingCallback);
	/* OpenSSL >= 1.1 defines the line above to a nop */
	(void)lockingCallback;

	SSL_library_init();








|















|

|







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
@synthesize privateKeyFile = _privateKeyFile;
@synthesize privateKeyPassphrase = _privateKeyPassphrase;
@synthesize verifiesCertificates = _verifiesCertificates;
@synthesize requestsClientCertificates = _requestsClientCertificates;

+ (void)load
{
	OFTLSSocketClass = self;
}

+ (void)initialize
{
	int m;

	if (self != [SSLSocket class])
		return;

	CRYPTO_set_id_callback(&threadID);
	/* OpenSSL >= 1.1 defines the line above to a nop */
	(void)threadID;

	/* Generate number of mutexes needed */
	m = CRYPTO_num_locks();
	SSLMutexes = OFAllocMemory(m, sizeof(OFPlainMutex));
	for (m--; m >= 0; m--)
		OFEnsure(OFPlainMutexNew(&SSLMutexes[m]) == 0);

	CRYPTO_set_locking_callback(&lockingCallback);
	/* OpenSSL >= 1.1 defines the line above to a nop */
	(void)lockingCallback;

	SSL_library_init();

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

	if (SSL_ != NULL)
		SSL_free(SSL_);
}

- (void)SSL_startTLSWithExpectedHost: (OFString *)host port: (uint16_t)port
{
	of_string_encoding_t encoding;

	if ((_SSL = SSL_new(ctx)) == NULL || SSL_set_fd(_SSL, _socket) != 1) {
		unsigned long error = ERR_get_error();

		[super close];

		@throw [SSLConnectionFailedException
		    exceptionWithHost: host
				 port: port
			       socket: self
			     SSLError: error];
	}

	if (SSL_set_tlsext_host_name(_SSL, host.UTF8String) != 1) {
		unsigned long error = ERR_get_error();

		[self close];








|






|
<
|
|
|







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

	if (SSL_ != NULL)
		SSL_free(SSL_);
}

- (void)SSL_startTLSWithExpectedHost: (OFString *)host port: (uint16_t)port
{
	OFStringEncoding encoding;

	if ((_SSL = SSL_new(ctx)) == NULL || SSL_set_fd(_SSL, _socket) != 1) {
		unsigned long error = ERR_get_error();

		[super close];

		@throw [SSLConnectionFailedException exceptionWithHost: host

								  port: port
								socket: self
							      SSLError: error];
	}

	if (SSL_set_tlsext_host_name(_SSL, host.UTF8String) != 1) {
		unsigned long error = ERR_get_error();

		[self close];

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
- (void)startTLSWithExpectedHost: (OFString *)host
{
	[self SSL_startTLSWithExpectedHost: host port: 0];
}

- (void)asyncConnectToHost: (OFString *)host
		      port: (uint16_t)port
	       runLoopMode: (of_run_loop_mode_t)runLoopMode
{
	void *pool = objc_autoreleasePoolPush();

	[[[SSLSocket_ConnectDelegate alloc]
	    initWithSocket: self
		      host: host
		      port: port
		  delegate: _delegate] autorelease];
	[super asyncConnectToHost: host port: port runLoopMode: runLoopMode];

	objc_autoreleasePoolPop(pool);
}

#ifdef OF_HAVE_BLOCKS
- (void)asyncConnectToHost: (OFString *)host
		      port: (uint16_t)port
	       runLoopMode: (of_run_loop_mode_t)runLoopMode
		     block: (of_tcp_socket_async_connect_block_t)block
{
	[super asyncConnectToHost: host
			     port: port
		      runLoopMode: runLoopMode
			    block: ^ (id exception) {
		if (exception == nil) {
			@try {







|
















|
|







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
- (void)startTLSWithExpectedHost: (OFString *)host
{
	[self SSL_startTLSWithExpectedHost: host port: 0];
}

- (void)asyncConnectToHost: (OFString *)host
		      port: (uint16_t)port
	       runLoopMode: (OFRunLoopMode)runLoopMode
{
	void *pool = objc_autoreleasePoolPush();

	[[[SSLSocket_ConnectDelegate alloc]
	    initWithSocket: self
		      host: host
		      port: port
		  delegate: _delegate] autorelease];
	[super asyncConnectToHost: host port: port runLoopMode: runLoopMode];

	objc_autoreleasePoolPop(pool);
}

#ifdef OF_HAVE_BLOCKS
- (void)asyncConnectToHost: (OFString *)host
		      port: (uint16_t)port
	       runLoopMode: (OFRunLoopMode)runLoopMode
		     block: (OFTCPSocketAsyncConnectBlock)block
{
	[super asyncConnectToHost: host
			     port: port
		      runLoopMode: runLoopMode
			    block: ^ (id exception) {
		if (exception == nil) {
			@try {
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
	}];
}
#endif

- (instancetype)accept
{
	SSLSocket *client = (SSLSocket *)[super accept];
	of_string_encoding_t encoding;

	if ((client->_SSL = SSL_new(ctx)) == NULL ||
	    !SSL_set_fd(client->_SSL, client->_socket)) {
		[client SSL_super_close];
		/* FIXME: Get a proper errno */
		@throw [OFAcceptFailedException exceptionWithSocket: self
							      errNo: 0];







|







374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
	}];
}
#endif

- (instancetype)accept
{
	SSLSocket *client = (SSLSocket *)[super accept];
	OFStringEncoding encoding;

	if ((client->_SSL = SSL_new(ctx)) == NULL ||
	    !SSL_set_fd(client->_SSL, client->_socket)) {
		[client SSL_super_close];
		/* FIXME: Get a proper errno */
		@throw [OFAcceptFailedException exceptionWithSocket: self
							      errNo: 0];

Modified src/X509Certificate.m from [adabc1fce4] to [f6177e4bd6].

1
2
3
4
5
6
7
8
9
10
/*
 * Copyright (c) 2011, Florian Zeitz <florob@babelmonkeys.de>
 * Copyright (c) 2011, 2012, 2013, 2015, Jonathan Schleifer <js@nil.im>
 *
 * https://fossil.nil.im/objopenssl
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice is present in all copies.
 *


|







1
2
3
4
5
6
7
8
9
10
/*
 * Copyright (c) 2011, Florian Zeitz <florob@babelmonkeys.de>
 * Copyright (c) 2011, 2012, 2013, 2015, 2021, Jonathan Schleifer <js@nil.im>
 *
 * https://fossil.nil.im/objopenssl
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice is present in all copies.
 *
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
}

- (instancetype)initWithX509Struct: (X509 *)certificate
{
	self = [super init];

	@try {
		_certificate = X509_dup(certificate);
		if (_certificate == NULL)
			@throw [OFInitializationFailedException
			    exceptionWithClass: self.class];
	} @catch (id e) {
		[self release];
		@throw e;
	}








|
<







94
95
96
97
98
99
100
101

102
103
104
105
106
107
108
}

- (instancetype)initWithX509Struct: (X509 *)certificate
{
	self = [super init];

	@try {
		if ((_certificate = X509_dup(certificate)) == NULL)

			@throw [OFInitializationFailedException
			    exceptionWithClass: self.class];
	} @catch (id e) {
		[self release];
		@throw e;
	}

328
329
330
331
332
333
334
335
336
337
338
339
340
341
342

	service = [service stringByAppendingString: @"."];
	serviceLength = service.length;

	for (OFString *name in assertedNames) {
		if ([name hasPrefix: service]) {
			OFString *asserted;
			asserted = [name substringWithRange: of_range(
			    serviceLength, name.length - serviceLength)];
			if ([self X509_isAssertedDomain: asserted
					    equalDomain: domain]) {
				objc_autoreleasePoolPop(pool);
				return true;
			}
		}







|







327
328
329
330
331
332
333
334
335
336
337
338
339
340
341

	service = [service stringByAppendingString: @"."];
	serviceLength = service.length;

	for (OFString *name in assertedNames) {
		if ([name hasPrefix: service]) {
			OFString *asserted;
			asserted = [name substringWithRange: OFRangeMake(
			    serviceLength, name.length - serviceLength)];
			if ([self X509_isAssertedDomain: asserted
					    equalDomain: domain]) {
				objc_autoreleasePoolPop(pool);
				return true;
			}
		}
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
380
381
382
	 * left-most label and matches only the left-most label with it.
	 * E.g. *.example.com matches foo.example.com,
	 * but not foo.bar.example.com
	 */

	size_t firstDot;

	if ([asserted caseInsensitiveCompare: domain] == OF_ORDERED_SAME)
		return true;

	if (![asserted hasPrefix: @"*."])
		return false;

	asserted = [asserted substringWithRange:
	    of_range(2, asserted.length - 2)];

	firstDot = [domain rangeOfString: @"."].location;
	if (firstDot == OF_NOT_FOUND)
		return false;

	domain = [domain substringWithRange:
	    of_range(firstDot + 1, domain.length - firstDot - 1)];

	if ([asserted caseInsensitiveCompare: domain] == 0)
		return true;

	return false;
}








|






|


|



|







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
380
381
	 * left-most label and matches only the left-most label with it.
	 * E.g. *.example.com matches foo.example.com,
	 * but not foo.bar.example.com
	 */

	size_t firstDot;

	if ([asserted caseInsensitiveCompare: domain] == OFOrderedSame)
		return true;

	if (![asserted hasPrefix: @"*."])
		return false;

	asserted = [asserted substringWithRange:
	    OFRangeMake(2, asserted.length - 2)];

	firstDot = [domain rangeOfString: @"."].location;
	if (firstDot == OFNotFound)
		return false;

	domain = [domain substringWithRange:
	    OFRangeMake(firstDot + 1, domain.length - firstDot - 1)];

	if ([asserted caseInsensitiveCompare: domain] == 0)
		return true;

	return false;
}

408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
}


- (X509OID *)X509_stringFromASN1Object: (ASN1_OBJECT *)object
{
	X509OID *ret;
	int length, bufferLength = 256;
	char *buffer = of_alloc(1, bufferLength);

	@try {
		while ((length = OBJ_obj2txt(buffer, bufferLength, object,
		    1)) > bufferLength) {
			bufferLength = length;
			buffer = of_realloc(buffer, 1, bufferLength);
		}

		ret = [[[X509OID alloc]
		    initWithUTF8String: buffer] autorelease];
	} @finally {
		free(buffer);
	}

	return ret;
}

- (OFString *)X509_stringFromASN1String: (ASN1_STRING *)str
{







|





|





|







407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
}


- (X509OID *)X509_stringFromASN1Object: (ASN1_OBJECT *)object
{
	X509OID *ret;
	int length, bufferLength = 256;
	char *buffer = OFAllocMemory(1, bufferLength);

	@try {
		while ((length = OBJ_obj2txt(buffer, bufferLength, object,
		    1)) > bufferLength) {
			bufferLength = length;
			buffer = OFResizeMemory(buffer, 1, bufferLength);
		}

		ret = [[[X509OID alloc]
		    initWithUTF8String: buffer] autorelease];
	} @finally {
		OFFreeMemory(buffer);
	}

	return ret;
}

- (OFString *)X509_stringFromASN1String: (ASN1_STRING *)str
{