This repository has been archived by the owner on Oct 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathMYDecoder.m
406 lines (330 loc) · 11.6 KB
/
MYDecoder.m
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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//
// MYDecoder.m
// MYCrypto
//
// Created by Jens Alfke on 1/16/08.
// Copyright 2008 Jens Alfke. All rights reserved.
//
#import "MYDecoder.h"
#import "MYCrypto_Private.h"
#import "Test.h"
#import "MYErrorUtils.h"
@interface MYSigner ()
- (id) initWithDecoder: (CMSDecoderRef)decoder index: (size_t)index policy: (CFTypeRef)policy;
@end
@implementation MYDecoder
- (id) initWithData: (NSData*)data error: (NSError**)outError
{
self = [self init];
if( self ) {
[self addData: data];
[self finish];
if (outError)
*outError = self.error;
if( _error ) {
return nil;
}
}
return self;
}
- (id) init
{
self = [super init];
if (self != nil) {
OSStatus err = CMSDecoderCreate(&_decoder);
if( err ) {
self = nil;
}
}
return self;
}
- (void) dealloc
{
if( _decoder ) CFRelease(_decoder);
if (_policy) CFRelease(_policy);
}
- (BOOL) addData: (NSData*)data
{
Assert(data);
return !_error && checksave( CMSDecoderUpdateMessage(_decoder, data.bytes, data.length) );
}
- (BOOL) finish
{
return !_error && checksave( CMSDecoderFinalizeMessage(_decoder) );
}
- (NSError*) error
{
if( _error )
return MYError(_error, NSOSStatusErrorDomain,
@"%@", MYErrorName(NSOSStatusErrorDomain,_error));
else
return nil;
}
- (BOOL) useKeychain: (MYKeychain*)keychain
{
return !_error && checksave( CMSDecoderSetSearchKeychain(_decoder, keychain.keychainRef) );
}
- (SecPolicyRef) policy
{
return _policy;
}
- (void)setPolicy:(SecPolicyRef)policy
{
if (policy != _policy) {
if (_policy) CFRelease(_policy);
if (policy) CFRetain(policy);
_policy = policy;
}
}
- (NSData*) _dataFromFunction: (OSStatus (*)(CMSDecoderRef,CFDataRef*))function
{
CFDataRef data=NULL;
if( checksave( (*function)(_decoder, &data) ) )
return (NSData*)CFBridgingRelease(data);
else
return nil;
}
- (NSData*) detachedContent
{
return [self _dataFromFunction: &CMSDecoderCopyDetachedContent];
}
- (void) setDetachedContent: (NSData*)detachedContent
{
if( ! _error )
checksave( CMSDecoderSetDetachedContent(_decoder, (__bridge CFDataRef)detachedContent) );
}
- (CSSM_OID) contentType
{
NSData *data = [self _dataFromFunction: &CMSDecoderCopyEncapsulatedContentType];
return (CSSM_OID){data.length,(uint8*)data.bytes}; // safe since data is autoreleased
}
- (NSData*) content
{
return [self _dataFromFunction: &CMSDecoderCopyContent];
}
- (BOOL) isSigned
{
size_t n;
return checksave( CMSDecoderGetNumSigners(_decoder, &n) ) && n > 0;
}
- (BOOL) isEncrypted
{
Boolean isEncrypted;
return check(CMSDecoderIsContentEncrypted(_decoder,&isEncrypted), @"CMSDecoderIsContentEncrypted")
&& isEncrypted;
}
- (NSArray*) signers
{
size_t n;
if( ! checksave( CMSDecoderGetNumSigners(_decoder, &n) ) )
return nil;
NSMutableArray *signers = [NSMutableArray arrayWithCapacity: n];
for( size_t i=0; i<n; i++ ) {
MYSigner *signer = [[MYSigner alloc] initWithDecoder: _decoder
index: i
policy: _policy];
[signers addObject: signer];
}
return signers;
}
- (NSArray*) certificates
{
CFArrayRef certRefs = NULL;
if( ! checksave( CMSDecoderCopyAllCerts(_decoder, &certRefs) ) || ! certRefs )
return nil;
CFIndex n = CFArrayGetCount(certRefs);
NSMutableArray *certs = [NSMutableArray arrayWithCapacity: n];
for( CFIndex i=0; i<n; i++ ) {
SecCertificateRef certRef = (SecCertificateRef) CFArrayGetValueAtIndex(certRefs, i);
[certs addObject: [MYCertificate certificateWithCertificateRef: certRef]];
}
CFRelease(certRefs);
return certs;
}
- (NSString*) dump
{
static const char * kStatusNames[kCMSSignerInvalidIndex+1] = {
"kCMSSignerUnsigned", "kCMSSignerValid", "kCMSSignerNeedsDetachedContent",
"kCMSSignerInvalidSignature","kCMSSignerInvalidCert","kCMSSignerInvalidIndex"};
CSSM_OID contentType = self.contentType;
NSMutableString *s = [NSMutableString stringWithFormat: @"%@<%p>:\n"
"\tcontentType = %@ (\"%@\")\n"
"\tcontent = %u bytes\n"
"\tsigned=%i, encrypted=%i\n"
"\tpolicy=%@\n"
"\t%u certificates\n"
"\tsigners =\n",
self.class, self,
OIDAsString(contentType), @"??"/*nameOfOID(&contentType)*/,
(unsigned)self.content.length,
self.isSigned,self.isEncrypted,
MYPolicyGetName(_policy),
(unsigned)self.certificates.count];
for( MYSigner *signer in self.signers ) {
CMSSignerStatus status = signer.status;
const char *statusName = (status<=kCMSSignerInvalidIndex) ?kStatusNames[status] :"??";
[s appendFormat:@"\t\t- status = %s\n"
"\t\t verifyResult = %@\n"
"\t\t trust = %@\n"
"\t\t cert = %@\n",
statusName,
(signer.verifyResult ?MYErrorName(NSOSStatusErrorDomain,signer.verifyResult)
:@"OK"),
MYTrustDescribe(signer.trust),
signer.certificate];
}
return s;
}
@end
#pragma mark -
@implementation MYSigner : NSObject
#define kUncheckedStatus ((CMSSignerStatus)-1)
- (id) initWithDecoder: (CMSDecoderRef)decoder index: (size_t)index policy: (CFTypeRef)policy
{
self = [super init];
if( self ) {
CFRetain(decoder);
_decoder = decoder;
_index = index;
if(policy) _policy = CFRetain(policy);
_status = kUncheckedStatus;
}
return self;
}
- (void) dealloc
{
if(_decoder) CFRelease(_decoder);
if(_policy) CFRelease(_policy);
if(_trust) CFRelease(_trust);
}
- (void) _getInfo {
if (_status == kUncheckedStatus) {
if( !check(CMSDecoderCopySignerStatus(_decoder, _index, _policy, (_policy!=nil),
&_status, &_trust, &_verifyResult),
@"CMSDecoderCopySignerStatus"))
_status = kMYSignerStatusCheckFailed;
}
}
- (CMSSignerStatus) status
{
[self _getInfo];
return _status;
}
- (OSStatus) verifyResult
{
[self _getInfo];
return _verifyResult;
}
- (SecTrustRef) trust
{
[self _getInfo];
return _trust;
}
- (NSString*) emailAddress
{
// Don't let caller see the addr if they haven't checked validity & the signature's invalid:
if (_status==kUncheckedStatus && self.status != kCMSSignerValid)
return nil;
CFStringRef email=NULL;
if( CMSDecoderCopySignerEmailAddress(_decoder, _index, &email) == noErr )
return (NSString*)CFBridgingRelease(email);
return nil;
}
- (MYCertificate *) certificate
{
// Don't let caller see the cert if they haven't checked validity & the signature's invalid:
if (_status==kUncheckedStatus && self.status != kCMSSignerValid)
return nil;
SecCertificateRef certRef=NULL;
OSStatus err = CMSDecoderCopySignerCert(_decoder, _index, &certRef);
if( err == noErr )
return [MYCertificate certificateWithCertificateRef: certRef];
else {
Warn(@"CMSDecoderCopySignerCert returned err %ld", (long)err);
return nil;
}
}
- (NSString*) description
{
NSMutableString *desc = [NSMutableString stringWithFormat: @"%@[st=%i", self.class,(int)self.status];
int verify = self.verifyResult;
if( verify )
[desc appendFormat: @"; verify error %i",verify];
else {
MYCertificate *cert = self.certificate;
if( cert )
[desc appendFormat: @"; %@",cert.commonName];
}
[desc appendString: @"]"];
return desc;
}
@end
#pragma mark -
#pragma mark TEST CASE:
#if DEBUG
#import "MYEncoder.h"
#import "MYIdentity.h"
static void TestRoundTrip( NSString *title, NSData *source, MYIdentity *signer, MYCertificate *recipient )
{
Log(@"Testing MYEncoder/Decoder %@...",title);
NSError *error;
NSData *encoded = [MYEncoder encodeData: source signer: signer recipient: recipient error: &error];
CAssertNil(error);
CAssert([encoded length]);
Log(@"MYEncoder encoded %lu bytes into %lu bytes", source.length,encoded.length);
Log(@"Decoding...");
MYDecoder *d = [[MYDecoder alloc] init];
d.policy = [MYCertificate X509Policy];
[d addData: encoded];
[d finish];
CAssertNil(d.error);
Log(@"%@", d.dump);
CAssert(d.content);
CAssert([d.content isEqual: source]);
CAssertNil(d.detachedContent);
CAssertEq(d.isSigned,(signer!=nil));
CAssertEq(d.isEncrypted,(recipient!=nil));
if( signer ) {
CAssert(d.certificates.count >= 1); // may include extra parent certs
CAssertEq(d.signers.count,1U);
MYSigner *outSigner = (d.signers)[0];
CAssertEq(outSigner.status,(CMSSignerStatus)kCMSSignerValid);
CAssertEq(outSigner.verifyResult,noErr);
CAssert([outSigner.certificate isEqualToCertificate: signer]);
} else {
CAssertEq(d.certificates.count, 0U);
CAssertEq(d.signers.count,0U);
}
}
TestCase(MYDecoder) {
RequireTestCase(MYEncoder);
MYIdentity *me = [MYIdentity preferredIdentityForName: @"MYCryptoTest"];
CAssert(me,@"No default identity has been set up in the Keychain");
Log(@"Using %@", me);
NSData *source = [NSData dataWithContentsOfFile: @"/Library/Desktop Pictures/Nature/Ladybug.jpg"];
if (!source)
source = [NSData dataWithContentsOfFile: @"/Library/Desktop Pictures/Nature/Zen Garden.jpg"];
CAssert(source, @"Oops, can't load desktop pic used by MYDecoder test-case");
TestRoundTrip(@"signing", source, me, nil);
TestRoundTrip(@"encryption", source, nil, me);
TestRoundTrip(@"signing+encryption", source, me, me);
}
#endif //DEBUG
/*
Copyright (c) 2009, Jens Alfke <jens@mooseyard.com>. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRI-
BUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/