-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
684 lines (529 loc) · 22.1 KB
/
index.js
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
#!/usr/bin/env node --harmony
/**
* Module dependencies.
*/
var Q = require('q');
var jws = require('jws');
var request = require('request');
var prompt = require('prompt');
var Url = require('url');
var crypto = require('crypto');
var qs = require('querystring');
var program = require('commander');
var fs = require('fs');
var os = require('os');
var aadGraph = require('./graph');
var colors = require('colors');
var cliff = require('cliff');
var AuthenticationContext = require('adal-node').AuthenticationContext;
var tokenFileName = 'aadappheck.json';
var domain = 'https://graph.windows.net';
var authorityUrl = 'https://login.windows.net/common';
var resource = '00000002-0000-0000-c000-000000000000';
var clientId = 'f4c23407-9821-405f-912b-e07ea6a29f7b';
var redirectUri = 'http://localhost/appcheck';
var templateAuthzUrl = authorityUrl +
'/oauth2/authorize?response_type=code&client_id=' +
clientId +
'&redirect_uri=' +
redirectUri +
'&state=<state>&resource=' +
resource;
var templateAuthzUrlWOState = authorityUrl +
'/oauth2/authorize?response_type=code&client_id=<clientId>' +
'&redirect_uri=<redirectUri>' +
'&resource=' +
resource;
//The actual global administrator role name....
var companyAdministratorDisplayName = 'Company Administrator';
function createLoginUrl(){
var deferred = Q.defer();
crypto.randomBytes(48, function(ex, buf) {
var token = buf.toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
program.authState = token;
var loginUrl = templateAuthzUrl.replace('<state>', token);
deferred.resolve(loginUrl);
});
return deferred.promise;
}
function getToken(){
var homeDir = os.tmpdir();
var file = homeDir + tokenFileName;
var deferred = Q.defer();
fs.stat(file, function(err, stats){
if(err){
deferred.reject(err);
}else{
var token = fs.readFileSync(file, 'utf8');
deferred.resolve(JSON.parse(token));
}
});
return deferred.promise;
}
program
.version('0.0.1')
.command('login')
.description('Login to analyze your apps')
.action(function (){
createLoginUrl().then(function(url){
console.log('Please paste following URL into your browser:'.green);
console.log('============================================'.yellow);
console.log(url);
console.log('============================================'.yellow);
console.log('If necessary login and consent to the appcheck application. When you get a 404... Not Found....'.green);
console.log('Copy the URL from your browser and paste below. It should look something like: localhost/appcheck?code='.green);
console.log('============================================'.yellow);
prompt.start();
prompt.get(['url'], function(err, result){
var authorizationCodeUrl = result.url;
var authUrl = Url.parse(authorizationCodeUrl, true);
if(program.authState != authUrl.query.state){
console.log('State did not match. Somthing is fishy...Aborting. You are not logged in.'.red);
return;
}
var authenticationContext = new AuthenticationContext(authorityUrl);
authenticationContext.acquireTokenWithAuthorizationCode(
authUrl.query.code,
redirectUri,
resource,
clientId,
'',
function(err, response) {
var errorMessage = '';
if (err) {
errorMessage = 'error: ' + err.message + '\n';
console.log(errorMessage);
return;
}
var homeDir = os.tmpdir();
var file = homeDir + tokenFileName;
fs.writeFileSync(file, JSON.stringify(response));
console.log('Great success you are logged in'.green);
}
);
});
});
});
program
.version('0.0.1')
.command('loginDumpToken')
.description('Login to your app and dump the resulting token to the console')
.option('-a, --appId <appId>', 'Your application or client Id')
.option('-r, --redirectUri <redirectUri>', 'The redirect URI registered with you app')
.option('-s, --secret [secret]', 'The secret for your web app or if you prefer confidential client')
.option('-R, --resource [resource]', 'The resource id or ids that your web application would like to access')
.action(function (options){
var urlBase = authorityUrl +
'/oauth2/authorize?response_type=code&client_id=<clientId>' +
'&redirect_uri=<redirectUri>' +
'&resource=<resource>'
urlBase = urlBase.replace('<clientId>', options.appId);
urlBase = urlBase.replace('<redirectUri>', options.redirectUri);
if(options.resource){
resource = options.resource;
}
var secret = '';
if(options.secret){
secret = options.secret;
}
urlBase = urlBase.replace('<resource>', resource);
console.log('Please paste following URL into your browser:'.green);
console.log('============================================'.yellow);
console.log(urlBase);
console.log('============================================'.yellow);
console.log('If necessary login and consent to the appcheck application. When you get a 404... Not Found....'.green);
console.log('Copy the resulting URL from your browser and paste below'.green);
console.log('Note: The browser will redirect if there is something to redirect to... so stop your web server.'.green);
console.log('============================================'.yellow);
prompt.start();
prompt.get(['url'], function(err, result){
var authorizationCodeUrl = result.url;
var authUrl = Url.parse(authorizationCodeUrl, true);
var authenticationContext = new AuthenticationContext(authorityUrl);
authenticationContext.acquireTokenWithAuthorizationCode(
authUrl.query.code,
options.redirectUri,
resource,
options.appId,
secret,
function(err, response) {
var errorMessage = '';
if (err) {
errorMessage = 'error: ' + err.message + '\n';
console.log(errorMessage);
return;
}
opts = {};
var decoded = jws.decode(response.accessToken, opts);
if(!decoded){
console.log('Error decoding your access token.'.red);
return;
}
console.log('Here is the content of your access token'.green);
console.log(cliff.inspect(decoded.payload));
}
);
});
});
program
.command('logout')
.description('Logout and delete tokens')
.action(function(){
getToken().then(function(token){
var homeDir = os.tmpdir();
var file = homeDir + tokenFileName;
fs.unlinkSync(file);
console.log('Great success you are logged out.'.green);
}).catch(function(err){
console.log('You are not even logged in yet... slow your roll'.green);
});
});
program
.command('dump')
.description('dump current state')
.action(function (){
getToken().then(function(token){
console.log(cliff.inspect(token));
}).catch(function(err){
console.log('Nothing to dump'.green);
});
});
program
.command('export')
.description('exports an application to json')
.option('-a, --appId [appId]', 'Your application or client Id')
.option('-n, --appName [appName]', 'You application name')
.action(function(options){
getToken().then(function(token){
var graph = new aadGraph.graph({'domain': domain });
var params = {};
params.tenantId = token.tenantId;
params.Authorization = 'Bearer ' + token.accessToken;
params['$filter'] = "appId eq '" + options.appId + "'";
params['apiVersion'] = "1.6";
graph.GetApplications(params).then(function(result){
console.log(cliff.inspect(result.body.value));
}).catch(function(err){
console.log(err);
console.log('We were not able to find that app that you were looking for'.red);
});
}).catch(function(err){
console.log('This command requires you to login. Usage: aadappcheck login'.red);
});
});
function GetSPOAuth2PermissionGrants(graph, token, spObjectId, adminConsent){
var params = {};
params.tenantId = token.tenantId;
params.spObjectId = spObjectId;
params.Authorization = 'Bearer ' + token.accessToken;
params.apiVersion = "1.6";
return graph.GetServicePrincipalOAuth2PermissionGrants(params);
}
function GetUserOAuth2PermissionGrants(graph, token){
var params = {};
params.tenantId = token.tenantId;
params.userId = token.userId;
params.Authorization = 'Bearer ' + token.accessToken;
params.apiVersion = "1.6";
return graph.GetUserOAuth2PermissionGrants(params);
}
function GetApplication(graph, token, appId){
var params = {};
params.tenantId = token.tenantId;
params.Authorization = 'Bearer ' + token.accessToken;
params['$filter'] = "appId eq '" + appId+ "'";
params['apiVersion'] = "1.6";
return graph.GetApplications(params);
}
function GetServicePrincipal(graph, token, appId){
var params = {};
params.Authorization = 'Bearer ' + token.accessToken;
params.tenantId = token.tenantId;
params.apiVersion = '1.6';
params['$filter'] = "appId eq '" + appId + "'";
return graph.GetServicePrincipals(params);
}
function GetUser(graph, token){
var params = {};
params.userId = token.userId;
params.tenantId = token.tenantId;
params.Authorization = 'Bearer ' + token.accessToken;
params.apiVersion = '1.6';
return graph.GetUser(params);
}
function GetDirectoryRoles(graph, token){
var params = {};
params.tenantId = token.tenantId;
params.Authorization = 'Bearer ' + token.accessToken;
params.apiVersion = '1.6';
// I want to do this... but no... this filter isn't supported
//params['$filter'] = "displayName eq 'Company Administrator'";
return graph.GetDirectoryRoles(params);
}
function GetUserMembership(graph, token, directoryRoleOrGroupId){
var params = {};
params.tenantId = token.tenantId;
params.userId = token.userId;
params.Authorization = 'Bearer ' + token.accessToken;
params.apiVersion = "1.6";
params['$filter'] = "objectId eq '" + directoryRoleOrGroupId + "'";
return graph.GetUserMemberships(params);
}
function filterIsApp(spObjectId){
return function(value){
return value.clientId == spObjectId;
}
}
function filterIsUser(userObjectId){
return function(value){
return value.principalId == userObjectId;
}
}
function filterIsAdminConsented(value){
return value.consentType == "AllPrincipals";
}
function filterIsGlobalAdmin(value){
return value.displayName === "Company Administrator";
}
function filterIsAdminOAuth2Permission(value){
return value.type === "Admin";
}
function filterIsUserOAuth2Permission(value){
return value.type === "User";
}
function filterIsAppGrant(appId){
return function(value){
return value.resourceId === appId;
}
}
function checkPermissions(grant){
return function logArrayElements(element, index, array) {
var role = "User";
if(grant.consentType === "AllPrincipals"){
role = "Admin";
}
//console.log(grant);
if(grant.scope.indexOf(element.value) != -1){
console.log((role + " granted: " + element.value + " type: " + element.type + "consentable permission").green);
}else{
console.log((role + " did not grant: " + element.value + " type: " + element.type + "consentable permission").red);
}
}
}
program
.command('healthcheck')
.description('Get an overview of the app and your consent information relative to the app.')
.option('-a, --appId <appId>', 'Your application or client Id')
.action(function(options){
getToken().then(function(token){
var graph = new aadGraph.graph({'domain': domain });
var appObject = null;
var spObject = null;
var userObject = null;
var directoryRoles = null;
var grants = null;
var adminObjectId = null;
var userIsAdmin = false;
var resourceApps = [];
var getObjectCalls = [GetApplication(graph, token, options.appId),
GetUser(graph, token),
GetServicePrincipal(graph, token, options.appId),
GetDirectoryRoles(graph, token)];
Q.allSettled(getObjectCalls).spread(function(application, user, servicePrincipal, dirRoles){
//App Object
if(application.state === "fulfilled"){
if(application.value.body.value.length == 0){
console.log('Application object not found'.yellow);
}else{
appObject = application.value.body.value[0];
console.log('Here is the application object'.green);
console.log(cliff.inspect(appObject));
}
}
//User Object
if(user.state === "fulfilled"){
userObject = user.value.body;
console.log('We found you as well.'.green);
}
//Service Principal
if(servicePrincipal.state === "fulfilled"){
if(servicePrincipal.value.body.value.length == 0){
console.log('Service principal not found'.yellow);
}else{
spObject = servicePrincipal.value.body.value[0];
console.log('Here is the service princpal object'.green);
console.log(cliff.inspect(spObject));
}
}
if(dirRoles.state === "fulfilled"){
//These shoudl always be found... add error handling later if it looks like it's ncessary
directoryRoles = dirRoles.value.body.value;
}else{
console.log(directoryRoles.reason);
}
}).then(function(){
//Additional Requests based on availability/state of the app/sp
var additionalRequests = [];
if(directoryRoles){
//Let's see if the currnet user is an administrator...
var adminRole = directoryRoles.filter(filterIsGlobalAdmin);
adminObjectId = adminRole[0].objectId;
additionalRequests.push(GetUserMembership(graph, token, adminObjectId));
}
if(spObject){
additionalRequests.push(GetSPOAuth2PermissionGrants(graph, token, spObject.objectId, true));
}
if(appObject){
//let's get the SPs for the app publishing required resources (The apps publishing the APIs were going to call)
for (var i = 0; i < appObject.requiredResourceAccess.length; i++) {
additionalRequests.push(GetServicePrincipal(graph, token, appObject.requiredResourceAccess[i].resourceAppId));
};
}
//***** SHOULD ADD A DIRECTORY ROLE CHECK FOR THE CURRENT USER
Q.allSettled(additionalRequests).spread(function(){
var resourceAppIndex = 1;
var arg2 = arguments[0];
if(arg2.state === "fulfilled"){
if(arg2.value.body.value.length === 1){
userIsAdmin = true;
}else{
userIsAdmin = false;
}
}
if(spObject){
var arg1 = arguments[1];
if(arg1.state === "fulfilled"){
grants = arg1.value.body.value;
}
resourceAppIndex = 2;
}
if(userIsAdmin){
console.log('You are an admin'.green);
}else{
console.log('Nope, you are not an admin');
}
console.log('Here are the apps that your app said that it required access to:'.green);
for (var n = resourceAppIndex; n < arguments.length; n++) {
if(arguments[i].state === "fulfilled"){
var rApp = arguments[n].value.body.value[0];
console.log(rApp.displayName);
resourceApps.push(rApp);
}
};
}).then(function(){
var userGrants = null;
var adminGrants = null;
if(grants){
userGrants = grants.filter(filterIsUser(userObject.objectId));
console.log('Here are the oAuth2Permissions you granted this app'.green);
console.log(cliff.inspect(userGrants));
adminGrants = grants.filter(filterIsAdminConsented);
console.log('Here are the oAuth2Permissions you or another admin consented to onbehalf of all users'.green);
console.log(cliff.inspect(adminGrants));
}
if(resourceApps.length > 0){
var adminPermissions;
var userPermissions;
//Missing admin grants...
console.log('Checking that permissions requested have been granted'.green);
for (var x = 0; x < resourceApps.length; x++) {
var rApp = resourceApps[x];
console.log(rApp.displayName);
adminPermissions = rApp.oauth2Permissions.filter(filterIsAdminOAuth2Permission);
userPermissions = rApp.oauth2Permissions.filter(filterIsUserOAuth2Permission);
if(adminGrants){
var adminGrant = adminGrants.filter(filterIsAppGrant(rApp.objectId));
if(adminGrant[0]){
adminPermissions.forEach(checkPermissions(adminGrant[0]));
userPermissions.forEach(checkPermissions(adminGrant[0]));
}else{
console.log(('No admin permissions granted for app: ' + rApp.displayName + ": ID: " + rApp.appId).red);
console.log('The following admin only consent permissions are requested by the app:'.green);
adminPermissions.forEach(function(element){
console.log("Requested: " + element.value + " type: " + element.type + " consentable permission");
})
}
}
if(userGrants){
var userGrant = userGrants.filter(filterIsAppGrant(rApp.objectId));
if(userGrant[0]){
userPermissions.forEach(checkPermissions(userGrant[0]));
}else{
console.log(('No user permissions granted for app: ' + rApp.displayName + ": ID: " + rApp.appId).red);
console.log('The following user consent permissions are requested by the app:'.green);
userPermissions.forEach(function(element){
console.log("Requested: " + element.value + " type: " + element.type + " consentable permission");
})
}
}
};
}
}).catch(function(err){
console.log(err);
});
});
}).catch(function(err){
console.log(err);
console.log('This command requires you to login. Usage: aadappcheck login'.red);
return;
});
});
program
.command('authZUris')
.description('Write common authorization request URL variants to the console')
.option('-a, --appId [appId]', 'Your application or client Id')
.option('-r, --redirectUri [redirectUri]', 'The redirect URI registered with you app')
.action(function(options){
var urlBase = '';
if(options.redirectUri){
urlBase = templateAuthzUrlWOState.replace('<redirectUri>', options.redirectUri);
}else{
//Let's default to this app
urlBase = templateAuthzUrlWOState.replace('<redirectUri>', redirectUri);
console.log('You did not supply a redirect URI. The redirect URI of appcheck will be used instead.'.yellow);
}
if(options.appId){
urlBase = urlBase.replace('<clientId>', options.appId);
}else{
urlBase = urlBase.replace('<clientId>', clientId);
console.log('You did not supply and app/client id. The client id of appcheck will be used instead.'.yellow);
}
console.log('The following are useful variants of authorization requests for your application.');
console.log('Note: The state parameter which is recommend as been left out.');
console.log('');
console.log('=================================================='.yellow);
console.log('BASIC:'.green);
console.log('=================================================='.yellow);
console.log(urlBase);
console.log('');
console.log('=================================================='.yellow);
console.log('PROMPT CONSENT or RECONSENT (if permissions for the app have changed -> &prompt=consent)'.green);
console.log('=================================================='.yellow);
console.log(urlBase + '&prompt=consent');
console.log('');
console.log('=================================================='.yellow);
console.log('PROMPT FOR ADMIN CONSENT or RECONSENT (if permissions for the app have changed) &prompt=admin_consent'.green);
console.log('=================================================='.yellow);
console.log(urlBase + '&prompt=admin_consent');
console.log('');
console.log('=================================================='.yellow);
console.log('REQUIRE USER Authentication &prompt=login'.green);
console.log('=================================================='.yellow);
console.log(urlBase + '&prompt=login');
console.log('');
console.log('=================================================='.yellow);
console.log('ONLY WORK ACCOUNTS PLEASE &msafed=0'.green);
console.log('=================================================='.yellow);
console.log(urlBase + '&msafed=0');
console.log('');
console.log('=================================================='.yellow);
console.log('TELL AAD the UserName to pre-fill &login_hint=[username]'.green);
console.log('=================================================='.yellow);
console.log(urlBase + '&login_hint=someuser');
console.log('');
console.log('=================================================='.yellow);
console.log('TELL AAD the domain of the user &domain_hint=[microsoft.com]'.green);
console.log('=================================================='.yellow);
console.log(urlBase + '&domain_hint=microsoft.com');
});
program.parse(process.argv);