-
Notifications
You must be signed in to change notification settings - Fork 30
/
ServerCallbackSupport.java
500 lines (428 loc) · 22.2 KB
/
ServerCallbackSupport.java
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
/*
* Copyright (c) 2007, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package ee.jakarta.tck.authentication.test.basic.sam;
import ee.jakarta.tck.authentication.test.basic.sam.util.BASE64Decoder;
import ee.jakarta.tck.authentication.test.basic.servlet.JASPICData;
import ee.jakarta.tck.authentication.test.common.logging.server.TSLogger;
import jakarta.security.auth.message.MessageInfo;
import jakarta.security.auth.message.callback.CallerPrincipalCallback;
import jakarta.security.auth.message.callback.GroupPrincipalCallback;
import jakarta.security.auth.message.callback.PasswordValidationCallback;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.Principal;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
*
* @author Raja Perumal
*/
public class ServerCallbackSupport {
private static TSLogger logger = null;
private static CallbackHandler callbackHandler = null;
private static String profile = null;
private static final String runtimeType = "ServerRuntime";
private static MessageInfo messageInfo = null;
private static Subject clientSubject = null;
private static Subject serverSubject = null;
// user corresponds to ts.jte user property (e.g. "j2ee")
private static String user = System.getProperty("j2eelogin.name");
// password corresponds to ts.jte password property (e.g. "j2ee")
private static String passwd = System.getProperty("j2eelogin.password");
/** Creates a new instance of ServerCallbackSupport */
public ServerCallbackSupport(TSLogger tsLogger, CallbackHandler cbkHandler, String profile) {
logger = tsLogger;
callbackHandler = cbkHandler;
this.profile = profile;
}
public ServerCallbackSupport(TSLogger tsLogger, CallbackHandler cbkHandler, String profile, MessageInfo msgInfo, Subject clientSubj, Subject serverSubj) {
logger = tsLogger;
callbackHandler = cbkHandler;
this.profile = profile;
this.messageInfo = msgInfo;
this.clientSubject = clientSubj;
this.serverSubject = serverSubj;
}
public boolean verify() {
try {
CallerPrincipalCallbackSupport();
GroupPrincipalCallbackSupport();
PasswordValidationCallbackSupport();
return true;
} catch (Exception e) {
return false;
}
}
public boolean verifyCPCCallback() {
boolean bval = CallerPrincipalCallbackSupport();
logMsg("verifyCPCCallback returning " + Boolean.toString(bval));
return bval;
}
public boolean verifyGPCCallback() {
boolean bval = GroupPrincipalCallbackSupport();
logMsg("verifyGPCCallback returning " + Boolean.toString(bval));
return bval;
}
public boolean verifyPVCCallback() {
boolean bval = PasswordValidationCallbackSupport();
logMsg("verifyPVCCallback returning " + Boolean.toString(bval));
return bval;
}
private boolean CallerPrincipalCallbackSupport() {
boolean bval = false;
HttpServletRequest request = null;
try {
request = (HttpServletRequest) messageInfo.getRequestMessage();
} catch (Exception ex) {
}
if (callbackHandler != null) {
try {
// note: we should be able to have a subject that has NO
// principals for the case of optional authen. Which means
// we should not have to explicitly set the principal here.
// however, for the case of mandatory authen, we will want
// to create a CPC using a username as opposed to a null principal.
CallerPrincipalCallback callerPrincipalCallback = null;
if (profile.equals(JASPICData.LAYER_SERVLET)) {
Principal principal = null;
if (messageInfo != null) {
HttpServletRequest req = (HttpServletRequest) messageInfo.getRequestMessage();
String username = getServletUsername(req);
String principalName = getPrincipalNameFromSubject(clientSubject);
String nameToLog = null;
// better to call cbh with a null principal when the policy is Not
// mandatory
// and with a legitimate principal when the policy is mandatory
// (unless testing send-failure or send-continue - which we are
// not!)
boolean bIsMandatory = isServletAuthMandatory(messageInfo);
if (bIsMandatory) {
logMsg("CallerPrincipalCallbackSupport() Authentication mandatory");
if (username != null) {
logMsg("CallerPrincipalCallbackSupport() auth mandatory, username != null");
callerPrincipalCallback = new CallerPrincipalCallback(clientSubject, username);
nameToLog = username;
} else if (principalName != null) {
logMsg("CallerPrincipalCallbackSupport() auth mandatory, principalName != null");
callerPrincipalCallback = new CallerPrincipalCallback(clientSubject, principalName);
nameToLog = principalName;
} else {
logMsg("CallerPrincipalCallbackSupport() auth mandatory, username and principalName both == null");
}
} else {
logMsg("CallerPrincipalCallbackSupport() Authentication NOT mandatory");
callerPrincipalCallback = new CallerPrincipalCallback(clientSubject, (Principal) null);
}
// now for some simple invocations to ensure we can call the API's
// these lines serve no other purpose than to validate we can
// invoke the api's in order to satisfy the javadoc assertions of:
// JSR-196:JAVADOC:32, JSR-196:JAVADOC:33, JSR-196:JAVADOC:34
String cpcbkName = callerPrincipalCallback.getName();
Principal cpcbkPrin = callerPrincipalCallback.getPrincipal();
Subject cpcbkSubj = callerPrincipalCallback.getSubject();
String msg = "CallerPrincipalCallback called for profile=" + profile;
if (request != null) {
String servletPath = request.getContextPath() + request.getServletPath();
msg += " for servletPath=" + servletPath;
} else {
msg += " messageInfo contained null request";
}
logMsg(msg);
// this helps test JASPIC:SPEC:103
if (clientSubject == null) {
msg += " subject=null";
} else {
msg += " subject=non-null";
}
msg += " principal set = " + nameToLog;
logMsg(msg);
} else {
// uses a null principal
callerPrincipalCallback = new CallerPrincipalCallback(clientSubject, principal);
}
} else {
// should not get into here.
logMsg("WARNING: ServerCallbackSupport.CallerPrincipalCallbackSupport() - profile != servlet.");
Subject subject = new Subject();
callerPrincipalCallback = new CallerPrincipalCallback(subject, (Principal) null);
}
Callback[] callbacks = new Callback[] { callerPrincipalCallback };
callbackHandler.handle(callbacks);
logMsg("CallbackHandler supports CallerPrincipalCallback");
bval = true; // if here assume successful authen
} catch (UnsupportedCallbackException usce) {
logMsg("CallbackHandler failed to support CallerPrincipalCallback :" + usce.getMessage());
usce.printStackTrace();
} catch (Exception ex) {
// failed CPC authentication for unknown reason
String servletPath = "";
if (request != null) {
servletPath = request.getContextPath() + request.getServletPath();
} else {
servletPath = "WARNING: can't determine servletpath";
}
logMsg("CPC Exception failure for servletPath=" + servletPath);
ex.printStackTrace();
}
} else {
String msg = "CallerPrincipalCallback has a null callbackHandler";
msg += " profile=" + profile;
if (profile.equals(JASPICData.LAYER_SERVLET) && (messageInfo != null)) {
// HttpServletRequest request =
// (HttpServletRequest)messageInfo.getRequestMessage();
if (request != null) {
String servletPath = request.getContextPath() + request.getServletPath();
msg += " for servletPath=" + servletPath;
} else {
msg += " messageInfo contained null request";
}
logMsg(msg);
if (clientSubject == null) {
msg += " subject=null";
} else {
msg += " subject=non-null";
}
String principalConcatString = getPrincipalNameFromSubject(clientSubject);
msg += " principal set = " + principalConcatString;
}
logMsg(msg);
}
return bval;
}
/*
* This is a convenience method. It is used to help pull out the username from the request. This method will only pull
* out a username if there was a client side servlet request made where Basic auth was used. This will only succeed if:
* 1. We have a ServletRequest that was populated correctly 2. The client side used BASE64Encoder() to encode user/pwd
* info 3. The user/pwd info were encoded in a format similar to the the following: String authData =
* username+":"+password BASE64Encode.encode(authData.getBytes())
*
* This returns just the decoded username.
*
*/
private String getServletUsername(HttpServletRequest req) {
String username = null;
String authorization = req.getHeader("authorization");
BASE64Decoder decoder = new BASE64Decoder();
if ((authorization != null) && (authorization.startsWith("Basic "))) {
try {
String authStr = authorization.substring(6).trim();
String value = new String(decoder.decodeBuffer(authStr));
logMsg("decoded (request) authorization string of: " + value);
// at this point value should be in the form of <username>:<pwd>
if (value != null) {
username = value.substring(0, value.indexOf(":"));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return username;
}
/*
* Convenience method to get our context info. (This currently only works for servlet profile since thats all we need it
* for at this point.)
*
*/
private String getServletContext(MessageInfo mInfo, String profile) {
String sContext = "";
if (profile.equals(JASPICData.LAYER_SERVLET) && (mInfo != null)) {
HttpServletRequest req = (HttpServletRequest) mInfo.getRequestMessage();
if (req != null) {
sContext = req.getContextPath() + req.getServletPath();
}
}
logger.log(Level.INFO, "getServletContext() returning " + sContext);
return sContext;
}
/*
* This is a convenience method that is used to determine if Authentication is mandatory. Based on the answer, there are
* certain requirements that will need to be met wrt setting of principals.
*/
private boolean isServletAuthMandatory(MessageInfo msgInfo) {
boolean bval = false;
Map map = msgInfo.getMap();
// lets pull out some context info that we can use to help uniquely
// identify the source of this request
HttpServletRequest request = (HttpServletRequest) msgInfo.getRequestMessage();
String servletName = request.getServletPath();
// see assertion JASPI:SPEC:306 for details on this
// jsr-196 states the following key must exist for servlet profile
String strKey = "jakarta.security.auth.message.MessagePolicy.isMandatory";
String msg;
if (map != null) {
String keyVal = (String) map.get(strKey);
msg = "isServletAuthMandatory() called with attrs: ";
msg += " layer=" + JASPICData.LAYER_SERVLET;
msg += " servletName=" + servletName;
msg += " key=" + strKey;
if (keyVal == null) {
msg += " value=NULL";
bval = false; // assume false if we cant determine
} else if (Boolean.valueOf(keyVal).booleanValue() == true) {
msg += " value=Valid";
bval = true;
} else {
// assume false
msg += " value=false";
bval = false;
}
logger.log(Level.FINE, msg);
} else {
msg = "FAILURE: No map in MessageInfo thus no key=" + strKey;
logger.log(Level.SEVERE, msg);
}
return bval;
}
public String getPrincipalNameFromSubject(Subject sub) {
Principal principal = null;
if (sub == null) {
return null;
}
String concatPrincipalName = "";
Set principalSet = sub.getPrincipals();
Iterator iterator = principalSet.iterator();
while (iterator.hasNext()) {
principal = (Principal) iterator.next();
concatPrincipalName += principal.getName();
}
return concatPrincipalName;
}
private boolean GroupPrincipalCallbackSupport() {
boolean bval = false;
;
boolean isAuthMandatory = false;
String strServletContext = "";
String principalName = "";
if (callbackHandler != null) {
try {
// note: we should be able to have a subject that has NO
// principals for the case of optional authen. Which means
// we should not have to explicitly set the principal here.
// however, for the case of mandatory authen, we will want
// to create a CPC using a username as opposed to a null principal.
Subject subject = clientSubject != null? clientSubject : new Subject();
String strArray[] = { "Administrator" };
GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(subject, strArray);
CallerPrincipalCallback callerPrincipalCallback = null;
if (profile.equals(JASPICData.LAYER_SERVLET)) {
if (messageInfo != null) {
HttpServletRequest req = (HttpServletRequest) messageInfo.getRequestMessage();
String username = getServletUsername(req);
principalName = getPrincipalNameFromSubject(clientSubject);
strServletContext = req.getServletPath();
// better to call cbh with a null principal when the policy is Not
// mandatory
// and with a legitimate principal when the policy is mandatory
// (unless testing send-failure or send-continue - which we are
// not!)
boolean bIsMandatory = isServletAuthMandatory(messageInfo);
if (bIsMandatory) {
isAuthMandatory = true;
debug("GroupPrincipalCallbackSupport() Authentication mandatory");
if (username != null) {
debug("GroupPrincipalCallbackSupport() auth mandatory, username != null");
callerPrincipalCallback = new CallerPrincipalCallback(clientSubject, username);
} else if (principalName != null) {
debug("GroupPrincipalCallbackSupport() auth mandatory, principalName != null");
callerPrincipalCallback = new CallerPrincipalCallback(clientSubject, principalName);
} else {
logMsg("GroupPrincipalCallbackSupport() auth mandatory, username and principalName both == null");
}
} else {
debug("GroupPrincipalCallbackSupport() Authentication NOT mandatory");
callerPrincipalCallback = new CallerPrincipalCallback(subject, (Principal) null);
}
} else {
// uses a null principal
debug("GroupPrincipalCallbackSupport(): messageInfo == null, using null principal");
callerPrincipalCallback = new CallerPrincipalCallback(clientSubject, (Principal) null);
}
} else {
// if here, we were erroneously called by non-servlet profile
debug("WARNING: ServerCallbackSupport.CallerPrincipalCallbackSupport() - profile != servlet.");
callerPrincipalCallback = new CallerPrincipalCallback(subject, (Principal) null);
}
Callback[] callbacks = new Callback[] { groupPrincipalCallback, callerPrincipalCallback };
callbackHandler.handle(callbacks);
// this string will be searched for on client side
String theMessage = "GroupPrincipalCallbackSupport():";
theMessage += " successfully called callbackHandler.handle(callbacks)";
theMessage += " for servlet: " + strServletContext;
theMessage += " with isServletAuthMandatory = " + isAuthMandatory;
logMsg(theMessage);
logMsg("CallbackHandler supports GroupPrincipalCallback");
bval = true; // if here assume successful authen
} catch (UnsupportedCallbackException usce) {
logMsg("CallbackHandler failed to support GroupPrincipalCallback :" + usce.getMessage());
usce.printStackTrace();
} catch (IOException ioe) {
logMsg("CallbackHandler failed to support GroupPrincipalCallback :" + ioe.getMessage());
ioe.printStackTrace();
}
}
return bval;
}
private boolean PasswordValidationCallbackSupport() {
boolean bval = false;
if (callbackHandler != null) {
try {
Subject subject = new Subject();
String username = user; // e.g. "j2ee";
char[] password = passwd.toCharArray(); // e.g. {'j','2','e','e'};
PasswordValidationCallback passwordValidationCallback = new PasswordValidationCallback(subject, username, password);
CallerPrincipalCallback cpc = new CallerPrincipalCallback(subject, (Principal) null);
Callback[] callbacks = new Callback[] { passwordValidationCallback, cpc };
callbackHandler.handle(callbacks);
Subject returnedSubject = passwordValidationCallback.getSubject();
boolean result = passwordValidationCallback.getResult();
String userName = passwordValidationCallback.getUsername();
char[] returnedPassword = passwordValidationCallback.getPassword();
passwordValidationCallback.clearPassword();
// logMsg("PasswordValidation callback returned subject
// ="+returnedSubject);
// logMsg("PasswordValidation callback returned password
// ="+returnedPassword);
logMsg("PasswordValidation callback returned result =" + result);
logMsg("CallbackHandler supports PasswordValidationCallback");
bval = result;
} catch (UnsupportedCallbackException usce) {
logMsg("CallbackHandler failed to support PasswordValidationCallback :" + usce.getMessage());
usce.printStackTrace();
} catch (IOException ioe) {
logMsg("CallbackHandler failed to support PasswordValidationCallback :" + ioe.getMessage());
ioe.printStackTrace();
}
}
return bval;
}
public void logMsg(String str) {
if (logger != null) {
logger.log(Level.INFO, "In " + profile + " : " + runtimeType + " " + str);
} else {
System.out.println("*** TSLogger Not Initialized properly ***");
System.out.println("*** TSSVLogMessage : ***" + str);
}
}
public void debug(String str) {
System.out.println(str);
}
}