-
Notifications
You must be signed in to change notification settings - Fork 347
/
Copy pathiOSBroker.cs
443 lines (372 loc) · 19 KB
/
iOSBroker.cs
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.Identity.Client.Core;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Utils;
using UIKit;
using Foundation;
using System;
using CoreFoundation;
using Microsoft.Identity.Client.OAuth2;
using Microsoft.Identity.Client.Internal.Broker;
using Microsoft.Identity.Client.UI;
using Microsoft.Identity.Client.PlatformsCommon.Interfaces;
using System.Globalization;
using Security;
using Microsoft.Identity.Client.Internal.Requests;
using Microsoft.Identity.Client.ApiConfig.Parameters;
using Microsoft.Identity.Client.Internal;
using System.Linq;
using Microsoft.Identity.Client.Http;
using Microsoft.Identity.Client.Cache;
using Microsoft.Identity.Client.Instance.Discovery;
namespace Microsoft.Identity.Client.Platforms.iOS
{
/// <summary>
/// Handles requests which invoke the broker. This is only for mobile (iOS and Android) scenarios.
/// </summary>
internal class iOSBroker : NSObject, IBroker
{
private static SemaphoreSlim s_brokerResponseReady = null;
private static NSUrl s_brokerResponse = null;
private readonly ILoggerAdapter _logger;
private readonly ICryptographyManager _cryptoManager;
private readonly CoreUIParent _uIParent;
private string _brokerRequestNonce;
private bool _brokerV3Installed = false;
public bool IsPopSupported => false;
public iOSBroker(ILoggerAdapter logger, ICryptographyManager cryptoManager, CoreUIParent uIParent)
{
_logger = logger;
_cryptoManager = cryptoManager;
_uIParent = uIParent;
}
public bool IsBrokerInstalledAndInvokable(AuthorityType authorityType)
{
using (_logger.LogMethodDuration())
{
if (_uIParent?.CallerViewController == null)
{
_logger.Error(iOSBrokerConstants.CallerViewControllerIsNullCannotInvokeBroker);
throw new MsalClientException(MsalError.UIViewControllerRequiredForiOSBroker, MsalErrorMessage.UIViewControllerIsRequiredToInvokeiOSBroker);
}
bool canStartBroker = false;
_uIParent.CallerViewController.InvokeOnMainThread(() =>
{
if (IsBrokerInstalled(BrokerParameter.UriSchemeBrokerV3))
{
_logger.Info(iOSBrokerConstants.iOSBrokerv3Installed);
_brokerV3Installed = true;
canStartBroker = true;
}
});
if (!canStartBroker)
{
_uIParent.CallerViewController.InvokeOnMainThread(() =>
{
if (IsBrokerInstalled(BrokerParameter.UriSchemeBrokerV2))
{
_logger.Info(iOSBrokerConstants.iOSBrokerv2Installed);
canStartBroker = true;
}
});
}
if (!canStartBroker)
{
_logger.Info(iOSBrokerConstants.CanInvokeBrokerReturnsFalseMessage);
}
return canStartBroker;
}
}
public async Task<MsalTokenResponse> AcquireTokenInteractiveAsync(
AuthenticationRequestParameters authenticationRequestParameters,
AcquireTokenInteractiveParameters acquireTokenInteractiveParameters)
{
ValidateRedirectUri(authenticationRequestParameters.RedirectUri);
AuthenticationContinuationHelper.LastRequestLogger = _logger;
using (_logger.LogMethodDuration())
{
Dictionary<string, string> brokerRequest = CreateBrokerRequestDictionary(
authenticationRequestParameters,
acquireTokenInteractiveParameters);
await InvokeIosBrokerAsync(brokerRequest).ConfigureAwait(false);
return ProcessBrokerResponse();
}
}
private void ValidateRedirectUri(Uri redirectUri)
{
string bundleId = NSBundle.MainBundle.BundleIdentifier;
RedirectUriHelper.ValidateIosBrokerRedirectUri(redirectUri, bundleId, _logger);
}
private Dictionary<string, string> CreateBrokerRequestDictionary(
AuthenticationRequestParameters authenticationRequestParameters,
AcquireTokenInteractiveParameters acquireTokenInteractiveParameters)
{
var brokerRequest = new Dictionary<string, string>(16);
brokerRequest.Add(BrokerParameter.Authority, authenticationRequestParameters.Authority.AuthorityInfo.CanonicalAuthority.ToString());
string scopes = EnumerableExtensions.AsSingleString(authenticationRequestParameters.Scope);
brokerRequest.Add(BrokerParameter.Scope, scopes);
brokerRequest.Add(BrokerParameter.ClientId, authenticationRequestParameters.AppConfig.ClientId);
brokerRequest.Add(BrokerParameter.CorrelationId, authenticationRequestParameters.RequestContext.CorrelationId.ToString());
brokerRequest.Add(BrokerParameter.ClientVersion, MsalIdHelper.GetMsalVersion());
// EnrollmentId and MamResource values will be present in the keychain after the device is registered and enrolled.
var realEnrollmentId = IntuneEnrollmentIdHelper.GetRawEnrollmentId();
brokerRequest.Add(BrokerParameter.IntuneEnrollmentIds, realEnrollmentId ?? string.Empty);
var intuneMamResource = IntuneEnrollmentIdHelper.GetRawMamResources();
brokerRequest.Add(BrokerParameter.IntuneMamResource, intuneMamResource ?? string.Empty);
// this needs to be case sensitive because the AppBundle is case sensitive
brokerRequest.Add(
BrokerParameter.RedirectUri,
authenticationRequestParameters.RedirectUri.OriginalString);
if (authenticationRequestParameters.ExtraQueryParameters?.Any() == true)
{
string extraQP = string.Join("&", authenticationRequestParameters.ExtraQueryParameters.Select(x => x.Key + "=" + x.Value));
brokerRequest.Add(BrokerParameter.ExtraQp, extraQP);
}
if (authenticationRequestParameters.RequestContext.ServiceBundle.Config.ClientCapabilities?.Any() == true)
{
var capabilities = String.Join(',', authenticationRequestParameters.RequestContext.ServiceBundle.Config.ClientCapabilities);
brokerRequest.Add(BrokerParameter.ClientCapabilities, capabilities);
}
brokerRequest.Add(BrokerParameter.Username, authenticationRequestParameters.Account?.Username ?? string.Empty);
brokerRequest.Add(BrokerParameter.ExtraOidcScopes, BrokerParameter.OidcScopesValue);
var prompt = acquireTokenInteractiveParameters.Prompt;
if (prompt == Prompt.NoPrompt || prompt == Prompt.NotSpecified)
{
brokerRequest.Add(BrokerParameter.Prompt, Prompt.SelectAccount.PromptValue);
}
else
{
brokerRequest.Add(BrokerParameter.Prompt, acquireTokenInteractiveParameters.Prompt.PromptValue);
}
if (!string.IsNullOrEmpty(authenticationRequestParameters.Claims))
{
brokerRequest.Add(BrokerParameter.Claims, authenticationRequestParameters.Claims);
}
AddCommunicationParams(brokerRequest);
return brokerRequest;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Interoperability", "CA1422:Validate platform compatibility", Justification = "<Pending>")]
public void HandleInstallUrl(string appLink)
{
DispatchQueue.MainQueue.DispatchAsync(() => UIApplication.SharedApplication.OpenUrl(new NSUrl(appLink)));
throw new MsalClientException(
MsalError.BrokerApplicationRequired,
MsalErrorMessage.BrokerApplicationRequired);
}
private void AddCommunicationParams(Dictionary<string, string> brokerRequest)
{
string encodedBrokerKey = Base64UrlHelpers.Encode(BrokerKeyHelper.GetOrCreateBrokerKey(_logger));
brokerRequest[iOSBrokerConstants.BrokerKey] = encodedBrokerKey;
brokerRequest[iOSBrokerConstants.MsgProtocolVer] = BrokerParameter.MsgProtocolVersion3;
if (_brokerV3Installed)
{
_brokerRequestNonce = Guid.NewGuid().ToString();
brokerRequest[iOSBrokerConstants.BrokerNonce] = _brokerRequestNonce;
string applicationToken = TryReadBrokerApplicationTokenFromKeychain(brokerRequest);
if (!string.IsNullOrEmpty(applicationToken))
{
brokerRequest[iOSBrokerConstants.ApplicationToken] = applicationToken;
}
}
}
private async Task InvokeIosBrokerAsync(Dictionary<string, string> brokerPayload)
{
s_brokerResponseReady = new SemaphoreSlim(0);
string paramsAsQuery = brokerPayload.ToQueryParameter();
_logger.Info(() => iOSBrokerConstants.InvokeTheIosBroker);
NSUrl url = new NSUrl(iOSBrokerConstants.InvokeV2Broker + paramsAsQuery);
_logger.VerbosePii(
() => iOSBrokerConstants.BrokerPayloadPii + paramsAsQuery,
() => iOSBrokerConstants.BrokerPayloadNoPii + brokerPayload.Count);
DispatchQueue.MainQueue.DispatchAsync(() => UIApplication.SharedApplication.OpenUrl(url, new UIApplicationOpenUrlOptions(), null));
using (_logger.LogBlockDuration("waiting for broker response"))
{
await s_brokerResponseReady.WaitAsync().ConfigureAwait(false);
}
}
private MsalTokenResponse ProcessBrokerResponse()
{
using (_logger.LogMethodDuration())
{
string[] keyValuePairs = s_brokerResponse.Query.Split('&');
Dictionary<string, string> responseDictionary = new Dictionary<string, string>(StringComparer.InvariantCulture);
foreach (string pair in keyValuePairs)
{
string[] keyValue = pair.Split('=');
responseDictionary[keyValue[0]] = CoreHelpers.UrlDecode(keyValue[1]);
if (responseDictionary[keyValue[0]].Equals("(null)", StringComparison.OrdinalIgnoreCase)
&& keyValue[0].Equals(iOSBrokerConstants.Code, StringComparison.OrdinalIgnoreCase))
{
responseDictionary[iOSBrokerConstants.Error] = iOSBrokerConstants.BrokerError;
_logger.VerbosePii(
() => iOSBrokerConstants.BrokerResponseValuesPii + keyValue.ToString(),
() => iOSBrokerConstants.BrokerResponseContainsError);
}
}
_logger.Verbose(() => iOSBrokerConstants.ProcessBrokerResponse + responseDictionary.Count);
return ResultFromBrokerResponse(responseDictionary);
}
}
private MsalTokenResponse ResultFromBrokerResponse(Dictionary<string, string> responseDictionary)
{
MsalTokenResponse brokerTokenResponse;
string expectedHash = responseDictionary[iOSBrokerConstants.ExpectedHash];
string encryptedResponse = responseDictionary[iOSBrokerConstants.EncryptedResponsed];
string decryptedResponse = BrokerKeyHelper.DecryptBrokerResponse(encryptedResponse, _logger);
string responseActualHash = _cryptoManager.CreateSha256Hash(decryptedResponse);
byte[] rawHash = Convert.FromBase64String(responseActualHash);
string hash = BitConverter.ToString(rawHash);
if (expectedHash.Equals(hash.Replace("-", ""), StringComparison.OrdinalIgnoreCase))
{
responseDictionary = CoreHelpers.ParseKeyValueList(decryptedResponse, '&', false, null);
if (!ValidateBrokerResponseNonceWithRequestNonce(responseDictionary))
{
return new MsalTokenResponse
{
Error = MsalError.BrokerNonceMismatch,
ErrorDescription = MsalErrorMessage.BrokerNonceMismatch
};
}
if (responseDictionary.ContainsKey(iOSBrokerConstants.ApplicationToken))
{
TryWriteBrokerApplicationTokenToKeychain(
responseDictionary[BrokerResponseConst.ClientId],
responseDictionary[iOSBrokerConstants.ApplicationToken]);
}
brokerTokenResponse = MsalTokenResponse.CreateFromiOSBrokerResponse(responseDictionary);
if (responseDictionary.TryGetValue(BrokerResponseConst.BrokerErrorCode, out string errCode))
{
if(errCode == BrokerResponseConst.iOSBrokerUserCancellationErrorCode)
{
responseDictionary[BrokerResponseConst.BrokerErrorCode] = MsalError.AuthenticationCanceledError;
}
else if (errCode == BrokerResponseConst.iOSBrokerProtectionPoliciesRequiredErrorCode)
{
responseDictionary[BrokerResponseConst.BrokerErrorCode] = MsalError.ProtectionPolicyRequired;
}
}
}
else
{
brokerTokenResponse = new MsalTokenResponse
{
Error = MsalError.BrokerResponseHashMismatch,
ErrorDescription = MsalErrorMessage.BrokerResponseHashMismatch
};
}
return brokerTokenResponse;
}
private bool IsBrokerInstalled(string brokerUriScheme)
{
return UIApplication.SharedApplication.CanOpenUrl(new NSUrl(brokerUriScheme));
}
private bool ValidateBrokerResponseNonceWithRequestNonce(Dictionary<string, string> brokerResponseDictionary)
{
if (_brokerV3Installed)
{
string brokerResponseNonce = brokerResponseDictionary[BrokerResponseConst.iOSBrokerNonce];
bool ok = string.Equals(
brokerResponseNonce,
_brokerRequestNonce,
StringComparison.InvariantCultureIgnoreCase);
if (!ok)
{
_logger.Error(
string.Format(
CultureInfo.CurrentCulture,
"Nonce check failed! Broker response nonce is: {0}, \nBroker request nonce is: {1}",
brokerResponseNonce,
_brokerRequestNonce));
}
return ok;
}
return true;
}
private void TryWriteBrokerApplicationTokenToKeychain(string clientId, string applicationToken)
{
iOSTokenCacheAccessor iOSTokenCacheAccessor = new iOSTokenCacheAccessor();
try
{
SecStatusCode secStatusCode = iOSTokenCacheAccessor.SaveBrokerApplicationToken(clientId, applicationToken);
_logger.Info(() => string.Format(
CultureInfo.CurrentCulture,
iOSBrokerConstants.AttemptToSaveBrokerApplicationToken + "SecStatusCode: {0}",
secStatusCode));
}
catch (Exception ex)
{
throw new MsalClientException(
MsalError.WritingApplicationTokenToKeychainFailed,
MsalErrorMessage.WritingApplicationTokenToKeychainFailed + ex.Message);
}
}
private string TryReadBrokerApplicationTokenFromKeychain(Dictionary<string, string> brokerPayload)
{
iOSTokenCacheAccessor iOSTokenCacheAccessor = new iOSTokenCacheAccessor();
try
{
SecStatusCode secStatusCode = iOSTokenCacheAccessor.TryGetBrokerApplicationToken(brokerPayload[BrokerParameter.ClientId], out string appToken);
_logger.Info(() => string.Format(
CultureInfo.CurrentCulture,
iOSBrokerConstants.SecStatusCodeFromTryGetBrokerApplicationToken + "SecStatusCode: {0}",
secStatusCode));
return appToken;
}
catch (Exception ex)
{
throw new MsalClientException(
MsalError.ReadingApplicationTokenFromKeychainFailed,
MsalErrorMessage.ReadingApplicationTokenFromKeychainFailed + ex.Message);
}
}
public static void SetBrokerResponse(NSUrl responseUrl)
{
s_brokerResponse = responseUrl;
s_brokerResponseReady?.Release();
}
public IReadOnlyDictionary<string, string> GetSsoPolicyHeaders()
{
return CollectionHelpers.GetEmptyDictionary<string, string>();
}
#region Silent Flow - not supported
/// <summary>
/// iOS broker does not handle silent flow
/// </summary>
public Task RemoveAccountAsync(ApplicationConfiguration applicationConfiguration, IAccount account)
{
return Task.Delay(0); // nop
}
/// <summary>
/// iOS broker does not handle silent flow
/// </summary>
public Task<IReadOnlyList<IAccount>> GetAccountsAsync(
string clientID,
string redirectUri,
AuthorityInfo authorityInfo,
ICacheSessionManager cacheSessionManager,
IInstanceDiscoveryManager instanceDiscoveryManager)
{
return Task.FromResult(CollectionHelpers.GetEmptyReadOnlyList<IAccount>()); // nop
}
/// <summary>
/// iOS broker does not handle silent flow
/// </summary>
public Task<MsalTokenResponse> AcquireTokenSilentAsync(AuthenticationRequestParameters authenticationRequestParameters, AcquireTokenSilentParameters acquireTokenSilentParameters)
{
return Task.FromResult<MsalTokenResponse>(null); // nop
}
public Task<MsalTokenResponse> AcquireTokenSilentDefaultUserAsync(AuthenticationRequestParameters authenticationRequestParameters, AcquireTokenSilentParameters acquireTokenSilentParameters)
{
return Task.FromResult<MsalTokenResponse>(null); // nop
}
public Task<MsalTokenResponse> AcquireTokenByUsernamePasswordAsync(AuthenticationRequestParameters authenticationRequestParameters, AcquireTokenByUsernamePasswordParameters acquireTokenByUsernamePasswordParameters)
{
return Task.FromResult<MsalTokenResponse>(null); // nop
}
#endregion
}
}