/
EjbCorbaServant.java
530 lines (481 loc) · 24 KB
/
EjbCorbaServant.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
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
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.iiop;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.security.AccessController;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.HashMap;
import java.util.Map;
import javax.ejb.EJBMetaData;
import javax.ejb.HomeHandle;
import javax.management.MBeanException;
import javax.transaction.Status;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ejb3.component.stateful.StatefulSessionComponent;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.iiop.csiv2.SASCurrent;
import org.jboss.as.naming.context.NamespaceContextSelector;
import org.jboss.ejb.client.SessionID;
import org.jboss.ejb.iiop.HandleImplIIOP;
import org.jboss.invocation.InterceptorContext;
import org.jboss.marshalling.InputStreamByteInput;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.MarshallingConfiguration;
import org.jboss.marshalling.Unmarshaller;
import org.jboss.security.SecurityContext;
import org.jboss.security.SecurityContextAssociation;
import org.jboss.security.SecurityContextFactory;
import org.omg.CORBA.BAD_OPERATION;
import org.omg.CORBA.InterfaceDef;
import org.omg.CORBA.ORB;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.CORBA.portable.InputStream;
import org.omg.CORBA.portable.InvokeHandler;
import org.omg.CORBA.portable.OutputStream;
import org.omg.CORBA.portable.ResponseHandler;
import org.omg.PortableServer.Current;
import org.omg.PortableServer.CurrentPackage.NoContext;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.Servant;
import org.wildfly.iiop.openjdk.rmi.RmiIdlUtil;
import org.wildfly.iiop.openjdk.rmi.marshal.strategy.SkeletonStrategy;
import org.wildfly.security.auth.principal.NamePrincipal;
import org.wildfly.security.auth.server.RealmUnavailableException;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.auth.server.ServerAuthenticationContext;
import org.wildfly.security.evidence.PasswordGuessEvidence;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* CORBA servant class for the <code>EJBObject</code>s of a given bean. An
* instance of this class "implements" the bean's set of <code>EJBObject</code>
* instances by forwarding to the bean container all IIOP invocations on any
* of the bean's <code>EJBObject</code>s.
*
* @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a>
* @author Stuart Douglas
*/
public class EjbCorbaServant extends Servant implements InvokeHandler, LocalIIOPInvoker {
/**
* The injected component view
*/
private final ComponentView componentView;
/**
* The ORB
*/
private final ORB orb;
/**
* Thread-local <code>Current</code> object from which we get the target oid
* in an incoming IIOP request.
*/
private final Current poaCurrent;
/**
* Mapping from bean methods to <code>SkeletonStrategy</code> instances.
*/
private final Map<String, SkeletonStrategy> methodInvokerMap;
/**
* CORBA repository ids of the RMI-IDL interfaces implemented by the bean
* (<code>EJBObject</code> instance).
*/
private final String[] repositoryIds;
/**
* CORBA reference to an IR object representing the bean's remote interface.
*/
private final InterfaceDef interfaceDef;
/**
* The security domain for CORBA invocations
*/
private final String legacySecurityDomain;
/**
* The Elytron security domain for CORBA invocations
*/
private final SecurityDomain securityDomain;
/**
* If true this is the servant for an EJBHome object
*/
private final boolean home;
/**
* <code>HomeHandle</code> for the <code>EJBHome</code>
* implemented by this servant.
*/
private volatile HomeHandle homeHandle = null;
/**
* The metadata for this
*/
private volatile EJBMetaData ejbMetaData;
/**
* A reference to the SASCurrent, or null if the SAS interceptors are not
* installed.
*/
private final SASCurrent sasCurrent;
/**
* A reference to the InboundTransactionCurrent, or null if OTS interceptors
* are not installed.
*/
private final org.jboss.iiop.tm.InboundTransactionCurrent inboundTxCurrent;
/**
* The transaction manager
*/
private final TransactionManager transactionManager;
/**
* Used for serializing EJB id's
*/
private final MarshallerFactory factory;
private final MarshallingConfiguration configuration;
/**
* The EJB's deployment class loader
*/
private final ClassLoader classLoader;
/**
* Constructs an <code>EjbObjectCorbaServant></code>.
*/
public EjbCorbaServant(final Current poaCurrent, final Map<String, SkeletonStrategy> methodInvokerMap, final String[] repositoryIds,
final InterfaceDef interfaceDef, final ORB orb, final ComponentView componentView, final MarshallerFactory factory,
final MarshallingConfiguration configuration, final TransactionManager transactionManager, final ClassLoader classLoader,
final boolean home, final String legacySecurityDomain, final SecurityDomain securityDomain) {
this.poaCurrent = poaCurrent;
this.methodInvokerMap = methodInvokerMap;
this.repositoryIds = repositoryIds;
this.interfaceDef = interfaceDef;
this.orb = orb;
this.componentView = componentView;
this.factory = factory;
this.configuration = configuration;
this.transactionManager = transactionManager;
this.classLoader = classLoader;
this.home = home;
this.legacySecurityDomain = legacySecurityDomain;
this.securityDomain = securityDomain;
SASCurrent sasCurrent;
try {
sasCurrent = (SASCurrent) this.orb.resolve_initial_references("SASCurrent");
} catch (InvalidName invalidName) {
sasCurrent = null;
}
this.sasCurrent = sasCurrent;
org.jboss.iiop.tm.InboundTransactionCurrent inboundTxCurrent;
try {
inboundTxCurrent = (org.jboss.iiop.tm.InboundTransactionCurrent) this.orb.resolve_initial_references(org.jboss.iiop.tm.InboundTransactionCurrent.NAME);
} catch (InvalidName invalidName) {
inboundTxCurrent = null;
}
this.inboundTxCurrent = inboundTxCurrent;
}
/**
* Returns an IR object describing the bean's remote interface.
*/
public org.omg.CORBA.Object _get_interface_def() {
if (interfaceDef != null)
return interfaceDef;
else
return super._get_interface_def();
}
/**
* Returns an array with the CORBA repository ids of the RMI-IDL interfaces
* implemented by this servant's <code>EJBObject</code>s.
*/
public String[] _all_interfaces(POA poa, byte[] objectId) {
return repositoryIds.clone();
}
/**
* Receives IIOP requests to this servant's <code>EJBObject</code>s
* and forwards them to the bean container, through the JBoss
* <code>MBean</code> server.
*/
public OutputStream _invoke(final String opName, final InputStream in, final ResponseHandler handler) {
EjbLogger.ROOT_LOGGER.tracef("EJBObject invocation: %s", opName);
SkeletonStrategy op = methodInvokerMap.get(opName);
if (op == null) {
EjbLogger.ROOT_LOGGER.debugf("Unable to find opname '%s' valid operations:%s", opName, methodInvokerMap.keySet());
throw new BAD_OPERATION(opName);
}
final NamespaceContextSelector selector = componentView.getComponent().getNamespaceContextSelector();
final ClassLoader oldCl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
NamespaceContextSelector.pushCurrentSelector(selector);
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
org.omg.CORBA_2_3.portable.OutputStream out;
try {
Object retVal;
if (!home && opName.equals("_get_handle")) {
retVal = new HandleImplIIOP(orb.object_to_string(_this_object()));
} else if (home && opName.equals("_get_homeHandle")) {
retVal = homeHandle;
} else if (home && opName.equals("_get_EJBMetaData")) {
retVal = ejbMetaData;
} else {
Transaction tx = null;
if (inboundTxCurrent != null)
tx = inboundTxCurrent.getCurrentTransaction();
if (tx != null) {
transactionManager.resume(tx);
}
try {
Principal identityPrincipal = null;
Principal principal = null;
Object credential = null;
if (this.sasCurrent != null) {
final byte[] incomingIdentity = this.sasCurrent.get_incoming_principal_name();
//we have an identity token, which is a trust based mechanism
if (incomingIdentity != null && incomingIdentity.length > 0) {
String name = new String(incomingIdentity, StandardCharsets.UTF_8);
int domainIndex = name.indexOf('@');
if (domainIndex > 0)
name = name.substring(0, domainIndex);
identityPrincipal = new NamePrincipal(name);
}
final byte[] incomingUsername = this.sasCurrent.get_incoming_username();
if (incomingUsername != null && incomingUsername.length > 0) {
final byte[] incomingPassword = this.sasCurrent.get_incoming_password();
String name = new String(incomingUsername, StandardCharsets.UTF_8);
int domainIndex = name.indexOf('@');
if (domainIndex > 0) {
name = name.substring(0, domainIndex);
}
principal = new NamePrincipal(name);
credential = new String(incomingPassword, StandardCharsets.UTF_8).toCharArray();
}
}
final Object[] params = op.readParams((org.omg.CORBA_2_3.portable.InputStream) in);
if (!this.home && opName.equals("isIdentical") && params.length == 1) {
//handle isIdentical specially
Object val = params[0];
retVal = val instanceof org.omg.CORBA.Object && handleIsIdentical((org.omg.CORBA.Object) val);
} else {
if (this.securityDomain != null) {
// an elytron security domain is available: authenticate and authorize the client before invoking the component.
SecurityIdentity identity = this.securityDomain.getAnonymousSecurityIdentity();
if (identityPrincipal != null) {
// we have an identity token principal - check if the TLS identity, if available,
// has permission to run as the identity token principal.
// TODO use the TLS identity when that becomes available to us.
// no TLS identity found, check if an initial context token was also sent. If it was,
// authenticate the incoming username/password and check if the resulting identity has
// permission to run as the identity token principal.
if (principal != null) {
SecurityIdentity authenticatedIdentity = this.authenticate(principal, (char[]) credential);
identity = authenticatedIdentity.createRunAsIdentity(identityPrincipal.getName(), true);
} else {
// no TLS nor initial context token found - check if the anonymous identity has
// permission to run as the identity principal.
identity = this.securityDomain.getAnonymousSecurityIdentity().createRunAsIdentity(identityPrincipal.getName(), true);
}
} else if (principal != null) {
// we have an initial context token containing a username/password pair.
identity = this.authenticate(principal, (char[]) credential);
}
final InterceptorContext interceptorContext = new InterceptorContext();
this.prepareInterceptorContext(op, params, interceptorContext);
try {
retVal = identity.runAs((PrivilegedExceptionAction<Object>) () -> this.componentView.invoke(interceptorContext));
} catch (PrivilegedActionException e) {
throw e.getCause();
}
} else {
// legacy security behavior: setup the security context if a SASCurrent is available and invoke the component.
// One of the EJB security interceptors will authenticate and authorize the client.
SecurityContext legacyContext = null;
if (this.legacySecurityDomain != null && (identityPrincipal != null || principal != null)) {
// we don't have any real way to establish trust in identity based auth so we just use
// the SASCurrent as a credential, and a custom legacy login module can make a decision for us.
final Object finalCredential = identityPrincipal != null ? this.sasCurrent : credential;
final Principal finalPrincipal = identityPrincipal != null ? identityPrincipal : principal;
if (WildFlySecurityManager.isChecking()) {
legacyContext = AccessController.doPrivileged((PrivilegedExceptionAction<SecurityContext>) () -> {
SecurityContext sc = SecurityContextFactory.createSecurityContext(this.legacySecurityDomain);
sc.getUtil().createSubjectInfo(finalPrincipal, finalCredential, null);
return sc;
});
} else {
legacyContext = SecurityContextFactory.createSecurityContext(this.legacySecurityDomain);
legacyContext.getUtil().createSubjectInfo(finalPrincipal, finalCredential, null);
}
}
if (legacyContext != null) {
setSecurityContextOnAssociation(legacyContext);
}
try {
final InterceptorContext interceptorContext = new InterceptorContext();
if (legacyContext != null) {
interceptorContext.putPrivateData(SecurityContext.class, legacyContext);
}
prepareInterceptorContext(op, params, interceptorContext);
retVal = this.componentView.invoke(interceptorContext);
} finally {
if (legacyContext != null) {
clearSecurityContextOnAssociation();
}
}
}
}
} finally {
if (tx != null) {
if (this.transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION) {
this.transactionManager.suspend();
}
}
}
}
out = (org.omg.CORBA_2_3.portable.OutputStream)
handler.createReply();
if (op.isNonVoid()) {
op.writeRetval(out, retVal);
}
} catch (Throwable e) {
EjbLogger.ROOT_LOGGER.trace("Exception in EJBObject invocation", e);
if (e instanceof MBeanException) {
e = ((MBeanException) e).getTargetException();
}
RmiIdlUtil.rethrowIfCorbaSystemException(e);
out = (org.omg.CORBA_2_3.portable.OutputStream)
handler.createExceptionReply();
op.writeException(out, e);
}
return out;
} finally {
NamespaceContextSelector.popCurrentSelector();
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldCl);
}
}
private void prepareInterceptorContext(final SkeletonStrategy op, final Object[] params, final InterceptorContext interceptorContext) throws IOException, ClassNotFoundException {
if (!home) {
if (componentView.getComponent() instanceof StatefulSessionComponent) {
final SessionID sessionID = (SessionID) unmarshalIdentifier();
interceptorContext.putPrivateData(SessionID.class, sessionID);
}
}
interceptorContext.setContextData(new HashMap<>());
interceptorContext.setParameters(params);
interceptorContext.setMethod(op.getMethod());
interceptorContext.putPrivateData(ComponentView.class, componentView);
interceptorContext.putPrivateData(Component.class, componentView.getComponent());
}
private boolean handleIsIdentical(final org.omg.CORBA.Object val) throws RemoteException {
//TODO: is this correct?
return orb.object_to_string(_this_object()).equals(orb.object_to_string(val));
}
private Object unmarshalIdentifier() throws IOException, ClassNotFoundException {
final Object id;
try {
final byte[] idData = poaCurrent.get_object_id();
final Unmarshaller unmarshaller = factory.createUnmarshaller(configuration);
unmarshaller.start(new InputStreamByteInput(new ByteArrayInputStream(idData)));
id = unmarshaller.readObject();
unmarshaller.finish();
} catch (NoContext noContext) {
throw new RuntimeException(noContext);
}
return id;
}
// Implementation of the interface LocalIIOPInvoker ------------------------
/**
* Receives intra-VM invocations on this servant's <code>EJBObject</code>s
* and forwards them to the bean container, through the JBoss
* <code>MBean</code>
* server.
*/
public Object invoke(String opName,
Object[] arguments,
Transaction tx,
Principal identity,
Object credential)
throws Exception {
EjbLogger.ROOT_LOGGER.tracef("EJBObject local invocation: %s", opName);
SkeletonStrategy op = methodInvokerMap.get(opName);
if (op == null) {
throw new BAD_OPERATION(opName);
}
if (tx != null) {
transactionManager.resume(tx);
}
try {
final InterceptorContext interceptorContext = new InterceptorContext();
prepareInterceptorContext(op, arguments, interceptorContext);
return componentView.invoke(interceptorContext);
} finally {
if (tx != null) {
if (transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION) {
transactionManager.suspend();
}
}
}
}
public void setHomeHandle(final HomeHandle homeHandle) {
this.homeHandle = homeHandle;
}
public void setEjbMetaData(final EJBMetaData ejbMetaData) {
this.ejbMetaData = ejbMetaData;
}
private static void setSecurityContextOnAssociation(final SecurityContext sc) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
SecurityContextAssociation.setSecurityContext(sc);
return null;
});
}
private static void clearSecurityContextOnAssociation() {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
SecurityContextAssociation.clearSecurityContext();
return null;
});
}
/**
* Authenticate the user with the given credential against the configured Elytron security domain.
*
* @param principal the principal representing the user being authenticated.
* @param credential the credential used as evidence to verify the user's identity.
* @return the authenticated and authorized {@link SecurityIdentity}.
* @throws Exception if an error occurs while authenticating the user.
*/
private SecurityIdentity authenticate(final Principal principal, final char[] credential) throws Exception {
final ServerAuthenticationContext context = this.securityDomain.createNewAuthenticationContext();
final PasswordGuessEvidence evidence = new PasswordGuessEvidence(credential != null ? credential : null);
try {
context.setAuthenticationPrincipal(principal);
if (context.verifyEvidence(evidence)) {
if (context.authorize()) {
context.succeed();
return context.getAuthorizedIdentity();
} else {
context.fail();
throw new SecurityException("Authorization failed");
}
} else {
context.fail();
throw new SecurityException("Authentication failed");
}
} catch (IllegalArgumentException | IllegalStateException | RealmUnavailableException e) {
context.fail();
throw e;
} finally {
evidence.destroy();
}
}
}