OLMSession.m 13.9 KB
Newer Older
Chris Ballinger's avatar
Chris Ballinger committed
1
2
3
4
5
6
7
8
9
//
//  OLMSession.m
//  olm
//
//  Created by Chris Ballinger on 4/8/16.
//
//

#import "OLMSession.h"
Chris Ballinger's avatar
Chris Ballinger committed
10
11
#import "OLMUtility.h"
#import "OLMAccount_Private.h"
12
#import "OLMSession_Private.h"
manuroe's avatar
manuroe committed
13
#include "olm/olm.h"
Chris Ballinger's avatar
Chris Ballinger committed
14
15
16

@implementation OLMSession

Chris Ballinger's avatar
Chris Ballinger committed
17
18
19
- (void) dealloc {
    olm_clear_session(_session);
    free(_session);
Chris Ballinger's avatar
Chris Ballinger committed
20
21
}

Chris Ballinger's avatar
Chris Ballinger committed
22
23
24
25
26
27
28
29
30
31
32
33
34
- (BOOL) initializeSessionMemory {
    size_t size = olm_session_size();
    _session = malloc(size);
    NSParameterAssert(_session != nil);
    if (!_session) {
        return NO;
    }
    _session = olm_session(_session);
    NSParameterAssert(_session != nil);
    if (!_session) {
        return NO;
    }
    return YES;
Chris Ballinger's avatar
Chris Ballinger committed
35
36
}

37
- (instancetype) init {
Chris Ballinger's avatar
Chris Ballinger committed
38
39
40
41
42
43
44
45
    self = [super init];
    if (!self) {
        return nil;
    }
    BOOL success = [self initializeSessionMemory];
    if (!success) {
        return nil;
    }
46
47
48
49
50
51
52
53
54
55
56
57
    return self;
}

- (instancetype) initWithAccount:(OLMAccount*)account {
    self = [self init];
    if (!self) {
        return nil;
    }
    NSParameterAssert(account != nil &&  account.account != NULL);
    if (account == nil || account.account == NULL) {
        return nil;
    }
Chris Ballinger's avatar
Chris Ballinger committed
58
59
60
61
    _account = account;
    return self;
}

62
- (instancetype) initOutboundSessionWithAccount:(OLMAccount*)account theirIdentityKey:(NSString*)theirIdentityKey theirOneTimeKey:(NSString*)theirOneTimeKey  error:(NSError**)error {
Chris Ballinger's avatar
Chris Ballinger committed
63
64
65
66
67
68
69
70
71
    self = [self initWithAccount:account];
    if (!self) {
        return nil;
    }
    NSMutableData *random = [OLMUtility randomBytesOfLength:olm_create_outbound_session_random_length(_session)];
    NSData *idKey = [theirIdentityKey dataUsingEncoding:NSUTF8StringEncoding];
    NSData *otKey = [theirOneTimeKey dataUsingEncoding:NSUTF8StringEncoding];
    size_t result = olm_create_outbound_session(_session, account.account, idKey.bytes, idKey.length, otKey.bytes, otKey.length, random.mutableBytes, random.length);
    if (result == olm_error()) {
72
73
74
75
76
77
78
79
80
81
82
83
84
        const char *olm_error = olm_session_last_error(_session);

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

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

Chris Ballinger's avatar
Chris Ballinger committed
85
86
87
88
89
        return nil;
    }
    return self;
}

90
- (instancetype) initInboundSessionWithAccount:(OLMAccount*)account oneTimeKeyMessage:(NSString*)oneTimeKeyMessage error:(NSError**)error {
Chris Ballinger's avatar
Chris Ballinger committed
91
92
93
94
95
96
97
    self = [self initWithAccount:account];
    if (!self) {
        return nil;
    }
    NSMutableData *otk = [NSMutableData dataWithData:[oneTimeKeyMessage dataUsingEncoding:NSUTF8StringEncoding]];
    size_t result = olm_create_inbound_session(_session, account.account, otk.mutableBytes, oneTimeKeyMessage.length);
    if (result == olm_error()) {
98
99
100
101
102
103
104
105
106
107
108
109
110
        const char *olm_error = olm_session_last_error(_session);

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

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

Chris Ballinger's avatar
Chris Ballinger committed
111
112
113
114
115
        return nil;
    }
    return self;
}

116
- (instancetype) initInboundSessionWithAccount:(OLMAccount*)account theirIdentityKey:(NSString*)theirIdentityKey oneTimeKeyMessage:(NSString*)oneTimeKeyMessage error:(NSError**)error {
Chris Ballinger's avatar
Chris Ballinger committed
117
118
119
120
121
122
123
124
    self = [self initWithAccount:account];
    if (!self) {
        return nil;
    }
    NSData *idKey = [theirIdentityKey dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableData *otk = [NSMutableData dataWithData:[oneTimeKeyMessage dataUsingEncoding:NSUTF8StringEncoding]];
    size_t result = olm_create_inbound_session_from(_session, account.account, idKey.bytes, idKey.length, otk.mutableBytes, otk.length);
    if (result == olm_error()) {
125
126
127
128
129
130
131
132
133
134
135
136
137
        const char *olm_error = olm_session_last_error(_session);

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

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

Chris Ballinger's avatar
Chris Ballinger committed
138
139
140
141
142
143
144
145
146
147
148
149
150
151
        return nil;
    }
    return self;
}

- (NSString*) sessionIdentifier {
    size_t length = olm_session_id_length(_session);
    NSMutableData *idData = [NSMutableData dataWithLength:length];
    if (!idData) {
        return nil;
    }
    size_t result = olm_session_id(_session, idData.mutableBytes, idData.length);
    if (result == olm_error()) {
        const char *error = olm_session_last_error(_session);
152
        NSLog(@"olm_session_id error: %s", error);
Chris Ballinger's avatar
Chris Ballinger committed
153
154
155
156
157
158
        return nil;
    }
    NSString *idString = [[NSString alloc] initWithData:idData encoding:NSUTF8StringEncoding];
    return idString;
}

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
- (BOOL)matchesInboundSession:(NSString *)oneTimeKeyMessage {
    NSData *otk = [oneTimeKeyMessage dataUsingEncoding:NSUTF8StringEncoding];

    size_t result = olm_matches_inbound_session(_session, otk.bytes, otk.length);
    if (result == 1) {
        return YES;
    }
    else {
        if (result == olm_error()) {
            const char *error = olm_session_last_error(_session);
            NSLog(@"olm_matches_inbound_session error: %s", error);
        }
        return NO;
    }
}

- (BOOL)matchesInboundSessionFrom:(NSString *)theirIdentityKey oneTimeKeyMessage:(NSString *)oneTimeKeyMessage {
    NSData *idKey = [theirIdentityKey dataUsingEncoding:NSUTF8StringEncoding];
    NSData *otk = [oneTimeKeyMessage dataUsingEncoding:NSUTF8StringEncoding];

    size_t result = olm_matches_inbound_session_from(_session,
                                                     idKey.bytes, idKey.length,
                                                     otk.bytes, otk.length);
    if (result == 1) {
        return YES;
    }
    else {
        if (result == olm_error()) {
            const char *error = olm_session_last_error(_session);
            NSLog(@"olm_matches_inbound_session error: %s", error);
        }
        return NO;
    }
}

194
- (OLMMessage*) encryptMessage:(NSString*)message error:(NSError**)error {
Chris Ballinger's avatar
Chris Ballinger committed
195
196
197
198
199
200
201
202
203
204
205
    size_t messageType = olm_encrypt_message_type(_session);
    size_t randomLength = olm_encrypt_random_length(_session);
    NSMutableData *random = [OLMUtility randomBytesOfLength:randomLength];
    NSData *plaintextData = [message dataUsingEncoding:NSUTF8StringEncoding];
    size_t ciphertextLength = olm_encrypt_message_length(_session, plaintextData.length);
    NSMutableData *ciphertext = [NSMutableData dataWithLength:ciphertextLength];
    if (!ciphertext) {
        return nil;
    }
    size_t result = olm_encrypt(_session, plaintextData.bytes, plaintextData.length, random.mutableBytes, random.length, ciphertext.mutableBytes, ciphertext.length);
    if (result == olm_error()) {
206
207
208
209
210
211
212
213
214
215
216
217
218
        const char *olm_error = olm_session_last_error(_session);

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

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

Chris Ballinger's avatar
Chris Ballinger committed
219
220
221
222
223
224
225
        return nil;
    }
    NSString *ciphertextString = [[NSString alloc] initWithData:ciphertext encoding:NSUTF8StringEncoding];
    OLMMessage *encryptedMessage = [[OLMMessage alloc] initWithCiphertext:ciphertextString type:messageType];
    return encryptedMessage;
}

226
- (NSString*) decryptMessage:(OLMMessage*)message error:(NSError**)error {
Chris Ballinger's avatar
Chris Ballinger committed
227
228
229
230
231
232
233
234
    NSParameterAssert(message != nil);
    NSData *messageData = [message.ciphertext dataUsingEncoding:NSUTF8StringEncoding];
    if (!messageData) {
        return nil;
    }
    NSMutableData *mutMessage = messageData.mutableCopy;
    size_t maxPlaintextLength = olm_decrypt_max_plaintext_length(_session, message.type, mutMessage.mutableBytes, mutMessage.length);
    if (maxPlaintextLength == olm_error()) {
235
236
237
238
239
240
241
242
243
244
245
246
247
        const char *olm_error = olm_session_last_error(_session);

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

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

Chris Ballinger's avatar
Chris Ballinger committed
248
249
250
251
252
253
254
        return nil;
    }
    // message buffer is destroyed by olm_decrypt_max_plaintext_length
    mutMessage = messageData.mutableCopy;
    NSMutableData *plaintextData = [NSMutableData dataWithLength:maxPlaintextLength];
    size_t plaintextLength = olm_decrypt(_session, message.type, mutMessage.mutableBytes, mutMessage.length, plaintextData.mutableBytes, plaintextData.length);
    if (plaintextLength == olm_error()) {
255
256
257
258
259
260
261
262
263
264
265
266
267
        const char *olm_error = olm_session_last_error(_session);

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

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

Chris Ballinger's avatar
Chris Ballinger committed
268
269
270
271
272
        return nil;
    }
    plaintextData.length = plaintextLength;
    NSString *plaintext = [[NSString alloc] initWithData:plaintextData encoding:NSUTF8StringEncoding];
    return plaintext;
Chris Ballinger's avatar
Chris Ballinger committed
273
274
}

275
276
277
278
279
280
281
282
283
284
285
286
#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**)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) {
287
            *error = [NSError errorWithDomain:OLMErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey: @"Bad length."}];
288
289
290
291
292
293
294
295
296
        }
        return nil;
    }
    NSMutableData *pickle = [serializedData dataUsingEncoding:NSUTF8StringEncoding].mutableCopy;
    size_t result = olm_unpickle_session(_session, key.bytes, key.length, pickle.mutableBytes, pickle.length);
    if (result == olm_error()) {
        const char *olm_error = olm_session_last_error(_session);
        NSString *errorString = [NSString stringWithUTF8String:olm_error];
        if (error && errorString) {
297
            *error = [NSError errorWithDomain:OLMErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey: errorString}];
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
        }
        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_session_length(_session);
    NSMutableData *pickled = [NSMutableData dataWithLength:length];
    size_t result = olm_pickle_session(_session, key.bytes, key.length, pickled.mutableBytes, pickled.length);
    if (result == olm_error()) {
        const char *olm_error = olm_session_last_error(_session);
        NSString *errorString = [NSString stringWithUTF8String:olm_error];
        if (error && errorString) {
314
            *error = [NSError errorWithDomain:OLMErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey: errorString}];
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
        }
        return nil;
    }
    NSString *pickleString = [[NSString alloc] initWithData:pickled encoding:NSUTF8StringEncoding];
    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];
    }
    
    NSParameterAssert(error == nil);
    NSParameterAssert(self != nil);
    if (!self) {
        return nil;
    }
    
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    NSData *key = [OLMUtility randomBytesOfLength:32];
    NSError *error = nil;
    NSString *pickle = [self serializeDataWithKey:key error:&error];
    NSParameterAssert(pickle.length > 0 && error == nil);
    
    [encoder encodeObject:pickle forKey:@"pickle"];
    [encoder encodeObject:key forKey:@"key"];
    [encoder encodeObject:@"1" forKey:@"version"];
}

Chris Ballinger's avatar
Chris Ballinger committed
362
@end