1
wei
2021-01-21 62d098cb78296feaa6f786a20748921338db838c
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
//
// MQTTSSLSecurityPolicyDecoder.m
// MQTTClient.framework
//
// Copyright © 2013-2017, Christoph Krey. All rights reserved.
//
 
#import "MQTTSSLSecurityPolicyDecoder.h"
 
#import "MQTTLog.h"
 
@interface MQTTSSLSecurityPolicyDecoder()
@property (nonatomic) BOOL securityPolicyApplied;
 
@end
 
@implementation MQTTSSLSecurityPolicyDecoder
 
- (instancetype)init {
    self = [super init];
    self.securityPolicy = nil;
    self.securityDomain = nil;
    
    return self;
}
 
- (BOOL)applySSLSecurityPolicy:(NSStream *)readStream withEvent:(NSStreamEvent)eventCode{
    if (!self.securityPolicy) {
        return YES;
    }
 
    if (self.securityPolicyApplied) {
        return YES;
    }
 
    SecTrustRef serverTrust = (__bridge SecTrustRef) [readStream propertyForKey: (__bridge NSString *)kCFStreamPropertySSLPeerTrust];
    if (!serverTrust) {
        return NO;
    }
 
    self.securityPolicyApplied = [self.securityPolicy evaluateServerTrust:serverTrust forDomain:self.securityDomain];
    return self.securityPolicyApplied;
}
 
- (void)stream:(NSStream *)sender handleEvent:(NSStreamEvent)eventCode {    
    if (eventCode & NSStreamEventHasBytesAvailable) {
        DDLogVerbose(@"[MQTTCFSocketDecoder] NSStreamEventHasBytesAvailable");
        if (![self applySSLSecurityPolicy:sender withEvent:eventCode]){
            self.state = MQTTCFSocketDecoderStateError;
            self.error = [NSError errorWithDomain:@"MQTT"
                                             code:errSSLXCertChainInvalid
                                         userInfo:@{NSLocalizedDescriptionKey: @"Unable to apply security policy, the SSL connection is insecure!"}];
            [self.delegate decoder:self didFailWithError:self.error];
            return;
        }
    }
    [super stream:sender handleEvent:eventCode];
}
 
@end