XMPPSCRAMSHA1Authentication.m
10.7 KB
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
//
// XMPPSCRAMSHA1Authentication.m
// iPhoneXMPP
//
// Created by David Chiles on 3/21/14.
//
//
#import "XMPPSCRAMSHA1Authentication.h"
#import "XMPP.h"
#import "XMPPLogging.h"
#import "XMPPStream.h"
#import "XMPPInternal.h"
#import "NSData+XMPP.h"
#import "XMPPStringPrep.h"
#import <CommonCrypto/CommonKeyDerivation.h>
#if ! __has_feature(objc_arc)
#warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
#endif
// Log levels: off, error, warn, info, verbose
#if DEBUG
static const int xmppLogLevel = XMPP_LOG_LEVEL_INFO; // | XMPP_LOG_FLAG_TRACE;
#else
static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN;
#endif
@interface XMPPSCRAMSHA1Authentication ()
{
#if __has_feature(objc_arc_weak)
__weak XMPPStream *xmppStream;
#else
__unsafe_unretained XMPPStream *xmppStream;
#endif
}
@property (nonatomic) BOOL awaitingChallenge;
@property (nonatomic, strong) NSString *username;
@property (nonatomic, strong) NSString *password;
@property (nonatomic, strong) NSString *clientNonce;
@property (nonatomic, strong) NSString *combinedNonce;
@property (nonatomic, strong) NSString *salt;
@property (nonatomic, strong) NSNumber *count;
@property (nonatomic, strong) NSString *serverMessage1;
@property (nonatomic, strong) NSString *clientFirstMessageBare;
@property (nonatomic, strong) NSData *serverSignatureData;
@property (nonatomic, strong) NSData *clientProofData;
@property (nonatomic) CCHmacAlgorithm hashAlgorithm;
@end
///////////RFC5802 http://tools.ietf.org/html/rfc5802 //////////////
//Channel binding not yet supported
@implementation XMPPSCRAMSHA1Authentication
+ (NSString *)mechanismName
{
return @"SCRAM-SHA-1";
}
- (id)initWithStream:(XMPPStream *)stream password:(NSString *)password
{
return [self initWithStream:stream username:nil password:password];
}
- (id)initWithStream:(XMPPStream *)stream username:(NSString *)username password:(NSString *)password
{
if ((self = [super init])) {
xmppStream = stream;
if (username)
{
_username = username;
}
else
{
_username = [XMPPStringPrep prepNode:[xmppStream.myJID user]];
}
_password = [XMPPStringPrep prepPassword:password];
_hashAlgorithm = kCCHmacAlgSHA1;
}
return self;
}
- (BOOL)start:(NSError **)errPtr
{
XMPPLogTrace();
if(self.username.length || self.password.length) {
NSXMLElement *auth = [NSXMLElement elementWithName:@"auth" xmlns:@"urn:ietf:params:xml:ns:xmpp-sasl"];
[auth addAttributeWithName:@"mechanism" stringValue:@"SCRAM-SHA-1"];
[auth setStringValue:[self clientMessage1]];
[xmppStream sendAuthElement:auth];
self.awaitingChallenge = YES;
return YES;
}
else {
return NO;
}
}
- (XMPPHandleAuthResponse)handleAuth1:(NSXMLElement *)authResponse
{
XMPPLogTrace();
// We're expecting a challenge response.
// If we get anything else we're going to assume it's some kind of failure response.
if (![[authResponse name] isEqualToString:@"challenge"])
{
return XMPP_AUTH_FAIL;
}
NSDictionary *auth = [self dictionaryFromChallenge:authResponse];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
self.combinedNonce = auth[@"r"];
self.salt = auth[@"s"];
self.count = [numberFormatter numberFromString:auth[@"i"]];
//We have all the necessary information to calculate client proof and server signature
if ([self calculateProofs]) {
NSXMLElement *response = [NSXMLElement elementWithName:@"response" xmlns:@"urn:ietf:params:xml:ns:xmpp-sasl"];
[response setStringValue:[self clientMessage2]];
[xmppStream sendAuthElement:response];
self.awaitingChallenge = NO;
return XMPP_AUTH_CONTINUE;
}
else {
return XMPP_AUTH_FAIL;
}
}
- (XMPPHandleAuthResponse)handleAuth2:(NSXMLElement *)authResponse
{
XMPPLogTrace();
NSDictionary *auth = [self dictionaryFromChallenge:authResponse];
if ([[authResponse name] isEqual:@"success"]) {
NSString *receivedServerSignature = auth[@"v"];
if([self.serverSignatureData isEqualToData:[[receivedServerSignature dataUsingEncoding:NSUTF8StringEncoding] xmpp_base64Decoded]]){
return XMPP_AUTH_SUCCESS;
}
else {
return XMPP_AUTH_FAIL;
}
}
else {
return XMPP_AUTH_FAIL;
}
}
- (XMPPHandleAuthResponse)handleAuth:(NSXMLElement *)auth
{
XMPPLogTrace();
if (self.awaitingChallenge) {
return [self handleAuth1:auth];
}
else {
return [self handleAuth2:auth];
}
}
- (NSString *)clientMessage1
{
self.clientNonce = [XMPPStream generateUUID];
self.clientFirstMessageBare = [NSString stringWithFormat:@"n=%@,r=%@",self.username,self.clientNonce];
NSData *message1Data = [[NSString stringWithFormat:@"n,,%@",self.clientFirstMessageBare] dataUsingEncoding:NSUTF8StringEncoding];
return [message1Data xmpp_base64Encoded];
}
- (NSString *)clientMessage2
{
NSString *clientProofString = [self.clientProofData xmpp_base64Encoded];
NSData *message2Data = [[NSString stringWithFormat:@"c=biws,r=%@,p=%@",self.combinedNonce,clientProofString] dataUsingEncoding:NSUTF8StringEncoding];
return [message2Data xmpp_base64Encoded];
}
- (BOOL)calculateProofs
{
//Check to see that we have a password, salt and iteration count above 4096 (from RFC5802)
if (!self.password.length || !self.salt.length || self.count.unsignedIntegerValue < 4096) {
return NO;
}
NSData *passwordData = [self.password dataUsingEncoding:NSUTF8StringEncoding];
NSData *saltData = [[self.salt dataUsingEncoding:NSUTF8StringEncoding] xmpp_base64Decoded];
NSData *saltedPasswordData = [self HashWithAlgorithm:self.hashAlgorithm password:passwordData salt:saltData iterations:[self.count unsignedIntValue]];
NSData *clientKeyData = [self HashWithAlgorithm:self.hashAlgorithm data:[@"Client Key" dataUsingEncoding:NSUTF8StringEncoding] key:saltedPasswordData];
NSData *serverKeyData = [self HashWithAlgorithm:self.hashAlgorithm data:[@"Server Key" dataUsingEncoding:NSUTF8StringEncoding] key:saltedPasswordData];
NSData *storedKeyData = [clientKeyData xmpp_sha1Digest];
NSData *authMessageData = [[NSString stringWithFormat:@"%@,%@,c=biws,r=%@",self.clientFirstMessageBare,self.serverMessage1,self.combinedNonce] dataUsingEncoding:NSUTF8StringEncoding];
NSData *clientSignatureData = [self HashWithAlgorithm:self.hashAlgorithm data:authMessageData key:storedKeyData];
self.serverSignatureData = [self HashWithAlgorithm:self.hashAlgorithm data:authMessageData key:serverKeyData];
self.clientProofData = [self xorData:clientKeyData withData:clientSignatureData];
//check to see that we caclulated some client proof and server signature
if (self.clientProofData && self.serverSignatureData) {
return YES;
}
else {
return NO;
}
}
- (NSData *)HashWithAlgorithm:(CCHmacAlgorithm) algorithm password:(NSData *)passwordData salt:(NSData *)saltData iterations:(NSUInteger)rounds
{
NSMutableData *mutableSaltData = [saltData mutableCopy];
UInt8 zeroHex= 0x00;
UInt8 oneHex= 0x01;
NSData *zeroData = [[NSData alloc] initWithBytes:&zeroHex length:sizeof(zeroHex)];
NSData *oneData = [[NSData alloc] initWithBytes:&oneHex length:sizeof(oneHex)];
[mutableSaltData appendData:zeroData];
[mutableSaltData appendData:zeroData];
[mutableSaltData appendData:zeroData];
[mutableSaltData appendData:oneData];
NSData *result = [self HashWithAlgorithm:algorithm data:mutableSaltData key:passwordData];
NSData *previous = [result copy];
for (int i = 1; i < rounds; i++) {
previous = [self HashWithAlgorithm:algorithm data:previous key:passwordData];
result = [self xorData:result withData:previous];
}
return result;
}
- (NSData *)HashWithAlgorithm:(CCHmacAlgorithm) algorithm data:(NSData *)data key:(NSData *)key
{
unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];
CCHmac(algorithm, [key bytes], [key length], [data bytes], [data length], cHMAC);
return [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
}
- (NSData *)xorData:(NSData *)data1 withData:(NSData *)data2
{
NSMutableData *result = data1.mutableCopy;
char *dataPtr = (char *)result.mutableBytes;
char *keyData = (char *)data2.bytes;
char *keyPtr = keyData;
int keyIndex = 0;
for (int x = 0; x < data1.length; x++) {
*dataPtr = *dataPtr ^ *keyPtr;
dataPtr++;
keyPtr++;
if (++keyIndex == data2.length) {
keyIndex = 0;
keyPtr = keyData;
}
}
return result;
}
- (NSDictionary *)dictionaryFromChallenge:(NSXMLElement *)challenge
{
// The value of the challenge stanza is base 64 encoded.
// Once "decoded", it's just a string of key=value pairs separated by commas.
NSData *base64Data = [[challenge stringValue] dataUsingEncoding:NSASCIIStringEncoding];
NSData *decodedData = [base64Data xmpp_base64Decoded];
self.serverMessage1 = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
XMPPLogVerbose(@"%@: Decoded challenge: %@", THIS_FILE, self.serverMessage1);
NSArray *components = [self.serverMessage1 componentsSeparatedByString:@","];
NSMutableDictionary *auth = [NSMutableDictionary dictionaryWithCapacity:5];
for (NSString *component in components)
{
NSRange separator = [component rangeOfString:@"="];
if (separator.location != NSNotFound)
{
NSMutableString *key = [[component substringToIndex:separator.location] mutableCopy];
NSMutableString *value = [[component substringFromIndex:separator.location+1] mutableCopy];
if(key) CFStringTrimWhitespace((__bridge CFMutableStringRef)key);
if(value) CFStringTrimWhitespace((__bridge CFMutableStringRef)value);
if ([value hasPrefix:@"\""] && [value hasSuffix:@"\""] && [value length] > 2)
{
// Strip quotes from value
[value deleteCharactersInRange:NSMakeRange(0, 1)];
[value deleteCharactersInRange:NSMakeRange([value length]-1, 1)];
}
if(key && value)
{
auth[key] = value;
}
}
}
return auth;
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation XMPPStream (XMPPSCRAMSHA1Authentication)
- (BOOL)supportsSCRAMSHA1Authentication
{
return [self supportsAuthenticationMechanism:[XMPPSCRAMSHA1Authentication mechanismName]];
}
@end