OLMInboundGroupSession.m 11.9 KB
Newer Older
1
2
/*
 Copyright 2016 OpenMarket Ltd
manuroe's avatar
manuroe committed
3
 Copyright 2016 Vector Creations Ltd
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

#import "OLMInboundGroupSession.h"

#import "OLMUtility.h"
#include "olm/olm.h"
22
#import "OLMKit.h"
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

@interface OLMInboundGroupSession ()
{
    OlmInboundGroupSession *session;
}
@end


@implementation OLMInboundGroupSession

- (void)dealloc {
    olm_clear_inbound_group_session(session);
    free(session);
}

- (instancetype)init {
    self = [super init];
    if (self)
    {
        session = malloc(olm_inbound_group_session_size());
        if (session) {
            session = olm_inbound_group_session(session);
        }

        if (!session) {
            return nil;
        }
    }
    return self;
}

54
- (instancetype)initInboundGroupSessionWithSessionKey:(NSString *)sessionKey error:(NSError**)error {
55
56
57
58
59
    self = [self init];
    if (self) {
        NSData *sessionKeyData = [sessionKey dataUsingEncoding:NSUTF8StringEncoding];
        size_t result = olm_init_inbound_group_session(session, sessionKeyData.bytes, sessionKeyData.length);
        if (result == olm_error())   {
60
61
62
63
64
65
66
67
68
            const char *olm_error = olm_inbound_group_session_last_error(session);

            NSString *errorString = [NSString stringWithUTF8String:olm_error];
            NSLog(@"olm_init_inbound_group_session error: %@", errorString);

            if (error && olm_error && errorString) {
                *error = [NSError errorWithDomain:OLMErrorDomain
                                             code:0
                                         userInfo:@{
69
70
                                                    NSLocalizedDescriptionKey: errorString,
                                                    NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"olm_init_inbound_group_session error: %@", errorString]
71
72
73
                                                    }];
            }

74
75
76
77
78
79
            return nil;
        }
    }
    return self;
}

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
- (instancetype)initInboundGroupSessionWithImportedSession:(NSString *)sessionKey error:(NSError *__autoreleasing *)error
{
    self = [self init];
    if (self) {
        NSData *sessionKeyData = [sessionKey dataUsingEncoding:NSUTF8StringEncoding];
        size_t result = olm_import_inbound_group_session(session, sessionKeyData.bytes, sessionKeyData.length);
        if (result == olm_error())   {
            const char *olm_error = olm_inbound_group_session_last_error(session);

            NSString *errorString = [NSString stringWithUTF8String:olm_error];
            NSLog(@"olm_import_inbound_group_session error: %@", errorString);

            if (error && olm_error && errorString) {
                *error = [NSError errorWithDomain:OLMErrorDomain
                                             code:0
                                         userInfo:@{
                                                    NSLocalizedDescriptionKey: errorString,
                                                    NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"olm_import_inbound_group_session error: %@", errorString]
                                                    }];
            }

            return nil;
        }
    }
    return self;
}

107
108
109
110
111
112
113
114
115
- (NSString *)sessionIdentifier {
    size_t length = olm_inbound_group_session_id_length(session);
    NSMutableData *idData = [NSMutableData dataWithLength:length];
    if (!idData) {
        return nil;
    }
    size_t result = olm_inbound_group_session_id(session, idData.mutableBytes, idData.length);
    if (result == olm_error()) {
        const char *error = olm_inbound_group_session_last_error(session);
116
        NSLog(@"olm_inbound_group_session_id error: %s", error);
117
118
119
120
121
122
        return nil;
    }
    NSString *idString = [[NSString alloc] initWithData:idData encoding:NSUTF8StringEncoding];
    return idString;
}

123
- (NSString *)decryptMessage:(NSString *)message messageIndex:(NSUInteger*)messageIndex error:(NSError**)error
124
125
126
127
128
129
130
131
132
{
    NSParameterAssert(message != nil);
    NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding];
    if (!messageData) {
        return nil;
    }
    NSMutableData *mutMessage = messageData.mutableCopy;
    size_t maxPlaintextLength = olm_group_decrypt_max_plaintext_length(session, mutMessage.mutableBytes, mutMessage.length);
    if (maxPlaintextLength == olm_error()) {
133
134
135
136
137
138
139
140
141
        const char *olm_error = olm_inbound_group_session_last_error(session);

        NSString *errorString = [NSString stringWithUTF8String:olm_error];
        NSLog(@"olm_group_decrypt_max_plaintext_length error: %@", errorString);

        if (error && olm_error && errorString) {
            *error = [NSError errorWithDomain:OLMErrorDomain
                                         code:0
                                     userInfo:@{
142
143
                                                NSLocalizedDescriptionKey: errorString,
                                                NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"olm_group_decrypt_max_plaintext_length error: %@", errorString]
144
145
146
                                                }];
        }
        
147
148
149
150
151
        return nil;
    }
    // message buffer is destroyed by olm_group_decrypt_max_plaintext_length
    mutMessage = messageData.mutableCopy;
    NSMutableData *plaintextData = [NSMutableData dataWithLength:maxPlaintextLength];
152
153
154

    uint32_t message_index;
    size_t plaintextLength = olm_group_decrypt(session, mutMessage.mutableBytes, mutMessage.length, plaintextData.mutableBytes, plaintextData.length, &message_index);
155
    if (plaintextLength == olm_error()) {
156
157
158
159
160
161
162
163
164
        const char *olm_error = olm_inbound_group_session_last_error(session);

        NSString *errorString = [NSString stringWithUTF8String:olm_error];
        NSLog(@"olm_group_decrypt error: %@", errorString);

        if (error && olm_error && errorString) {
            *error = [NSError errorWithDomain:OLMErrorDomain
                                         code:0
                                     userInfo:@{
165
166
                                                NSLocalizedDescriptionKey: errorString,
                                                NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"olm_group_decrypt error: %@", errorString]
167
168
169
                                                }];
        }

170
171
172
173
        return nil;
    }
    plaintextData.length = plaintextLength;
    NSString *plaintext = [[NSString alloc] initWithData:plaintextData encoding:NSUTF8StringEncoding];
manuroe's avatar
manuroe committed
174
    [plaintextData resetBytesInRange:NSMakeRange(0, plaintextData.length)];
175
176
177
178
179
180

    if (messageIndex)
    {
        *messageIndex = message_index;
    }

181
182
183
    return plaintext;
}

184
185
186
187
188
189
190
191
192
193
- (NSUInteger)firstKnownIndex
{
    return olm_inbound_group_session_first_known_index(session);
}

- (BOOL)isVerified
{
    return (0 != olm_inbound_group_session_is_verified(session));
}

194
- (NSString*)exportSessionAtMessageIndex:(NSUInteger)messageIndex error:(NSError**)error;
195
196
197
{
    size_t length = olm_export_inbound_group_session_length(session);
    NSMutableData *key = [NSMutableData dataWithLength:length];
manuroe's avatar
manuroe committed
198
    size_t result = olm_export_inbound_group_session(session, key.mutableBytes, key.length, (uint32_t)messageIndex);
199
200
201
202
203
204
205
206
207
    if (result == olm_error()) {
        const char *olm_error = olm_inbound_group_session_last_error(session);
        NSString *errorString = [NSString stringWithUTF8String:olm_error];
        if (error && errorString) {
            *error = [NSError errorWithDomain:OLMErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey: errorString}];
        }
        return nil;
    }
    NSString *keyString = [[NSString alloc] initWithData:key encoding:NSUTF8StringEncoding];
208
    [key resetBytesInRange:NSMakeRange(0, key.length)];
209
210
211
    return keyString;
}

212
213
214
215
216
217
218
219
220
221
222
223
224

#pragma mark OLMSerializable

/** Initializes from encrypted serialized data. Will throw error if invalid key or invalid base64. */
- (instancetype) initWithSerializedData:(NSString *)serializedData key:(NSData *)key error:(NSError *__autoreleasing *)error {
    self = [self init];
    if (!self) {
        return nil;
    }
    NSParameterAssert(key.length > 0);
    NSParameterAssert(serializedData.length > 0);
    if (key.length == 0 || serializedData.length == 0) {
        if (error) {
225
            *error = [NSError errorWithDomain:OLMErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey: @"Bad length."}];
226
227
228
229
230
        }
        return nil;
    }
    NSMutableData *pickle = [serializedData dataUsingEncoding:NSUTF8StringEncoding].mutableCopy;
    size_t result = olm_unpickle_inbound_group_session(session, key.bytes, key.length, pickle.mutableBytes, pickle.length);
231
    [pickle resetBytesInRange:NSMakeRange(0, pickle.length)];
232
233
234
235
    if (result == olm_error()) {
        const char *olm_error = olm_inbound_group_session_last_error(session);
        NSString *errorString = [NSString stringWithUTF8String:olm_error];
        if (error && errorString) {
236
            *error = [NSError errorWithDomain:OLMErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey: errorString}];
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
        }
        return nil;
    }
    return self;
}

/** Serializes and encrypts object data, outputs base64 blob */
- (NSString*) serializeDataWithKey:(NSData*)key error:(NSError**)error {
    NSParameterAssert(key.length > 0);
    size_t length = olm_pickle_inbound_group_session_length(session);
    NSMutableData *pickled = [NSMutableData dataWithLength:length];
    size_t result = olm_pickle_inbound_group_session(session, key.bytes, key.length, pickled.mutableBytes, pickled.length);
    if (result == olm_error()) {
        const char *olm_error = olm_inbound_group_session_last_error(session);
        NSString *errorString = [NSString stringWithUTF8String:olm_error];
        if (error && errorString) {
253
            *error = [NSError errorWithDomain:OLMErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey: errorString}];
254
255
256
257
        }
        return nil;
    }
    NSString *pickleString = [[NSString alloc] initWithData:pickled encoding:NSUTF8StringEncoding];
258
    [pickled resetBytesInRange:NSMakeRange(0, pickled.length)];
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    return pickleString;
}

#pragma mark NSSecureCoding

+ (BOOL) supportsSecureCoding {
    return YES;
}

#pragma mark NSCoding

- (id)initWithCoder:(NSCoder *)decoder {
    NSString *version = [decoder decodeObjectOfClass:[NSString class] forKey:@"version"];

    NSError *error = nil;

    if ([version isEqualToString:@"1"]) {
        NSString *pickle = [decoder decodeObjectOfClass:[NSString class] forKey:@"pickle"];
        NSData *key = [decoder decodeObjectOfClass:[NSData class] forKey:@"key"];

        self = [self initWithSerializedData:pickle key:key error:&error];
    }
281
282
283
284
285
286
287
288
    else if ([version isEqualToString:@"2"]) {
        NSString *pickle = [decoder decodeObjectOfClass:[NSString class] forKey:@"pickle"];
        NSData *key = OLMKit.sharedInstance.pickleKeyDelegate.pickleKey;
        NSParameterAssert(key);
        
        self = [self initWithSerializedData:pickle key:key error:&error];
    }
    
289
290
291
292
293
294
295
296
297
298
    NSParameterAssert(error == nil);
    NSParameterAssert(self != nil);
    if (!self) {
        return nil;
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
299
300
301
302
303
304
305
306
307
308
309
310
    NSData *key = OLMKit.sharedInstance.pickleKeyDelegate.pickleKey;
    if (key)
    {
        [encoder encodeObject:@"2" forKey:@"version"];
    }
    else
    {
        key = [OLMUtility randomBytesOfLength:32];
        [encoder encodeObject:key forKey:@"key"];
        [encoder encodeObject:@"1" forKey:@"version"];
    }
    
311
312
313
    NSError *error = nil;
    NSString *pickle = [self serializeDataWithKey:key error:&error];
    NSParameterAssert(pickle.length > 0 && error == nil);
314
    
315
316
317
318
    [encoder encodeObject:pickle forKey:@"pickle"];
}

@end