DeserializationFirewallImpl.java
22.1 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
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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* javax.annotation.Nullable
* org.apache.felix.scr.annotations.Activate
* org.apache.felix.scr.annotations.Component
* org.apache.felix.scr.annotations.Deactivate
* org.apache.felix.scr.annotations.Property
* org.apache.felix.scr.annotations.Reference
* org.apache.felix.scr.annotations.ReferenceCardinality
* org.apache.felix.scr.annotations.ReferencePolicy
* org.apache.felix.scr.annotations.Service
* org.apache.sling.commons.osgi.PropertiesUtil
* org.apache.sling.hc.util.FormattingResultLog
* org.apache.sling.settings.SlingSettingsService
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.adobe.cq.deserfw.impl;
import com.adobe.cq.deserfw.api.AttachAPIResolver;
import com.adobe.cq.deserfw.impl.intapi.DeserializationFirewallStatus;
import com.adobe.cq.deserfw.impl.util.AgentJarResolver;
import com.adobe.cq.sercheck.util.CannedObject;
import com.adobe.cq.sercheck.util.DeserializationTester;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.hc.util.FormattingResultLog;
import org.apache.sling.settings.SlingSettingsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Service(value={DeserializationFirewallStatus.class})
@Component(immediate=1, metatype=1, label="Deserialization Firewall Configuration")
@Reference(name="attachApiResolver", referenceInterface=AttachAPIResolver.class, cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE, policy=ReferencePolicy.DYNAMIC)
public class DeserializationFirewallImpl
implements DeserializationFirewallStatus {
private static final String CLASS_ORG_KANTEGA_NOTSOSERIAL_NOT_SO_SERIAL_AGENT = "org.kantega.notsoserial.NotSoSerialAgent";
private static final String METHOD_IS_LOADED = "isLoaded";
private static final String CLASS_ORG_KANTEGA_NOTSOSERIAL_OPTIONS = "org.kantega.notsoserial.Options";
private static final String METHOD_SET_WHITE_LIST = "setWhiteList";
private static final String METHOD_SET_BLACK_LIST = "setBlackList";
private static final String METHOD_GET_NOT_SO_SERIAL = "getNotSoSerial";
private static final String METHOD_GET_INSTANCE = "getInstance";
private static final String METHOD_SET_DETAIL_WRITER = "setDetailWriter";
private static final String METHOD_SET_TRACE_WRITER = "setTraceWriter";
static final String[] WHITELIST_DEFAULT = new String[]{"[", "com.adobe.", "com.day.", "com.google.api.client.auth.oauth2.", "com.scene7.", "java.", "javax.", "oracle.sql.", "org.apache.jackrabbit.", "org.apache.sling."};
@Property(label="Whitelisted classes or package prefixes", value={"[", "com.adobe.", "com.day.", "com.google.api.client.auth.oauth2.", "com.scene7.", "java.", "javax.", "oracle.sql.", "org.apache.jackrabbit.", "org.apache.sling."}, cardinality=Integer.MAX_VALUE, description="List of whitelisted classes/package prefixes, or a single empty entry for blacklist only checking")
public static final String WHITELIST = "firewall.deserialization.whitelist";
static final String[] BLACKLIST_DEFAULT = new String[]{"org.apache.commons.collections.functors.InvokerTransformer", "org.apache.commons.collections4.functors.InvokerTransformer", "org.apache.commons.collections.functors.InstantiateTransformer", "org.apache.commons.collections4.functors.InstantiateTransformer", "org.apache.xalan.internal.xsltc.trax.TemplatesImpl", "org.codehaus.groovy.runtime.ConvertedClosure", "org.codehaus.groovy.runtime.MethodClosure", "org.springframework.beans.factory.ObjectFactory", "org.springframework.core.SerializableTypeWrapper$MethodInvokeTypeProvider", "com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl"};
@Property(label="Blacklisted classes or package prefixes", value={"org.apache.commons.collections.functors.InvokerTransformer", "org.apache.commons.collections4.functors.InvokerTransformer", "org.apache.commons.collections.functors.InstantiateTransformer", "org.apache.commons.collections4.functors.InstantiateTransformer", "org.apache.xalan.internal.xsltc.trax.TemplatesImpl", "org.codehaus.groovy.runtime.ConvertedClosure", "org.codehaus.groovy.runtime.MethodClosure", "org.springframework.beans.factory.ObjectFactory", "org.springframework.core.SerializableTypeWrapper$MethodInvokeTypeProvider", "com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl"}, cardinality=Integer.MAX_VALUE, description="List of blacklisted classes/prefixes")
public static final String BLACKLIST = "firewall.deserialization.blacklist";
public static final String CLASS_NAME_ONLY = "class-name-only";
public static final String FULL_STACK = "full-stack";
public static final String NONE = "none";
@Property(label="Diagnostic logging", value={"class-name-only"}, description="Level of diagnostic information to be added to logging. Options are none, class-name-only, or full-stack")
public static final String DIAGNOSTICS = "firewall.deserialization.diagnostics";
private String agentFolderRelativePath = "opt/notsoserial";
private File agentJarFolder = null;
private static final Logger log = LoggerFactory.getLogger(DeserializationFirewallImpl.class);
private List<AttachAPIResolver> apiResolvers = Collections.synchronizedList(new ArrayList());
private Class<?> vmClass = null;
private Object jvm;
@Reference
private SlingSettingsService slingSettingsService;
void setAgentFolderRelativePath(String agentFolderRelativePath) {
this.agentFolderRelativePath = agentFolderRelativePath;
}
void setSlingSettingsService(SlingSettingsService slingSettingsService) {
this.slingSettingsService = slingSettingsService;
}
public void bindAttachAPIResolver(AttachAPIResolver resolver) {
this.apiResolvers.add(resolver);
}
public void unbindAttachAPIResolver(AttachAPIResolver resolver) {
this.apiResolvers.remove(resolver);
}
private Set<String> getConfiguredList(Map<String, Object> properties, String propertyName, String[] defaultValues) {
HashSet<String> configuredList = new HashSet<String>();
String[] values = PropertiesUtil.toStringArray((Object)properties.get(propertyName), (String[])defaultValues);
if (values == null) {
return configuredList;
}
for (String name : values) {
if (name == null || name.trim().length() == 0) continue;
configuredList.add(name.trim());
}
return configuredList;
}
@Activate
public void setup(Map<String, Object> properties) {
this.agentJarFolder = new File(this.slingSettingsService.getSlingHomePath(), this.agentFolderRelativePath);
Set<String> configuredBlacklist = this.getConfiguredList(properties, "firewall.deserialization.blacklist", BLACKLIST_DEFAULT);
Set<String> configuredWhitelist = this.getConfiguredList(properties, "firewall.deserialization.whitelist", WHITELIST_DEFAULT);
String diagnosticLevel = PropertiesUtil.toString((Object)properties.get("firewall.deserialization.diagnostics"), (String)"class-name-only");
boolean agentPreLoaded = this.isFirewallLoaded(null);
if (agentPreLoaded) {
log.info("Java Deserialization Agent detected as preloaded.");
} else if (!this.dynamicallyLoadAgent()) {
return;
}
this.configureAgent(configuredBlacklist, configuredWhitelist, diagnosticLevel);
if (!this.isFirewallFunctional(null)) {
log.warn("Agent not detected as loaded after applying configuration. Your system may be in an unsecure state.");
}
if (!agentPreLoaded) {
log.info("Java Deserialization Agent dynamically loaded.");
}
}
private void configureAgent(Set<String> blacklist, Set<String> whitelist, String diagnosticLevel) {
if (!this.isFirewallLoaded(null)) {
log.warn("configureAgent called while agent was not noted as loaded");
}
try {
Class optionsClass = ClassLoader.getSystemClassLoader().loadClass("org.kantega.notsoserial.Options");
Object optionsInstance = optionsClass.getMethod("getInstance", new Class[0]).invoke(null, new Object[0]);
Object notSoSerialInstance = optionsClass.getMethod("getNotSoSerial", new Class[0]).invoke(optionsInstance, new Object[0]);
Class notSoSerialClass = notSoSerialInstance.getClass();
notSoSerialClass.getMethod("setBlackList", Set.class).invoke(notSoSerialInstance, blacklist);
notSoSerialClass.getMethod("setWhiteList", Set.class).invoke(notSoSerialInstance, whitelist);
if ("full-stack".equals(diagnosticLevel)) {
notSoSerialClass.getMethod("setTraceWriter", PrintWriter.class).invoke(notSoSerialInstance, new LoggingWriter());
notSoSerialClass.getMethod("setDetailWriter", PrintWriter.class).invoke(notSoSerialInstance, new Object[]{null});
} else if ("class-name-only".equals(diagnosticLevel)) {
notSoSerialClass.getMethod("setTraceWriter", PrintWriter.class).invoke(notSoSerialInstance, new Object[]{null});
notSoSerialClass.getMethod("setDetailWriter", PrintWriter.class).invoke(notSoSerialInstance, new LoggingWriter());
} else {
notSoSerialClass.getMethod("setTraceWriter", PrintWriter.class).invoke(notSoSerialInstance, new Object[]{null});
notSoSerialClass.getMethod("setDetailWriter", PrintWriter.class).invoke(notSoSerialInstance, new Object[]{null});
}
}
catch (Exception e) {
log.warn("Unable to configure agent. Agent may remain in it's default configuration. See nested exception", (Throwable)e);
}
if (!this.isFirewallFunctional(null)) {
log.warn("Agent not detected as loaded after applying configuration. Your system may be in an unsecure state.");
}
}
private File getAgentJarFile() throws LoadingException {
try {
return new File(AgentJarResolver.getAgentPath(this.agentJarFolder));
}
catch (IOException ioe) {
throw new LoadingException(this, "Exception loading agent jar from " + this.agentJarFolder.getAbsolutePath(), ioe);
}
}
private boolean dynamicallyLoadAgent() {
try {
try {
Method attachMethod;
Method loadAgentMethod;
File agentJar = this.getAgentJarFile();
if (agentJar == null) {
throw new LoadingException(this, "Deserialization Agent jar not found under " + this.agentJarFolder.getAbsolutePath());
}
log.info("Selected agent jar file {}", (Object)agentJar.getAbsolutePath());
String name = ManagementFactory.getRuntimeMXBean().getName();
if (name.indexOf("@") < 1) {
throw new LoadingException(this, "PID not in the expected format {PID}@ in " + name);
}
String pid = name.substring(0, name.indexOf("@"));
this.configureVMClass();
if (this.vmClass == null) {
throw new LoadingException(this, "Unable to load Attach API");
}
try {
attachMethod = this.vmClass.getMethod("attach", String.class);
}
catch (NoSuchMethodException nsme) {
throw new LoadingException(this, "Unable to get attach method from Attach API class " + this.vmClass.getCanonicalName());
}
try {
loadAgentMethod = this.vmClass.getMethod("loadAgent", String.class);
}
catch (NoSuchMethodException nsme) {
throw new LoadingException(this, "Unable to get loadAgent method from Attach API class " + this.vmClass.getCanonicalName());
}
this.jvm = attachMethod.invoke(null, pid);
if (this.jvm == null) {
throw new LoadingException(this, "Unable to obtain JVM from attach method");
}
loadAgentMethod.invoke(this.jvm, agentJar.getAbsolutePath());
if (!this.isFirewallLoaded(null)) {
throw new LoadingException(this, "Agent not detected as loaded using sample test cases");
}
return true;
}
catch (Throwable t) {
if (t instanceof LoadingException) {
throw (LoadingException)t;
}
log.error("Unexpected error loading deserialization agent. See nested exception.", t);
throw new LoadingException(this, "Unexpected error loading agent");
}
}
catch (LoadingException le) {
log.error(le.getMessage() + ". Unable to dynamically load deserialization protection agent. Please review the AEM Java Deserialization Firewall documentation to load the agent via java command line arguments.");
return false;
}
}
@Override
public boolean isFirewallLoaded(@Nullable FormattingResultLog logEntry) {
try {
block8 : {
Class optionsClass = ClassLoader.getSystemClassLoader().loadClass("org.kantega.notsoserial.NotSoSerialAgent");
if (optionsClass == null) {
return false;
}
try {
Object loaded = optionsClass.getMethod("isLoaded", new Class[0]).invoke(null, new Object[0]);
if (loaded != null && loaded instanceof Boolean) {
return (Boolean)loaded;
}
}
catch (NoSuchMethodException nsme) {
log.error("Unable to load method {} of class {}", (Object)"isLoaded", (Object)optionsClass.getName());
if (logEntry == null) break block8;
logEntry.healthCheckError("Unable to load method {} of class {}", new Object[]{"isLoaded", optionsClass.getName()});
}
}
return false;
}
catch (ClassNotFoundException cnfe) {
return false;
}
catch (Throwable e) {
if (logEntry != null) {
logEntry.healthCheckError("An unexpected problem was raised while testing to see if the agent was loaded", new Object[]{e});
}
log.error("An unexpected problem was raised while testing to see if the agent was loaded", e);
return false;
}
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
@Override
public boolean isFirewallFunctional(@Nullable FormattingResultLog logEntry) {
block16 : {
try {
CannedObject[] arr$ = CannedObject.TEST_CASES;
int len$ = arr$.length;
int i$ = 0;
while (i$ < len$) {
CannedObject cannedObject = arr$[i$];
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(cannedObject.data));
try {
new DeserializationTester().readObjectFrom(ois);
if (cannedObject.deserializationShouldFail) {
if (logEntry != null) {
logEntry.healthCheckError("Deserialization of {} should have failed, however it was successful", new Object[]{cannedObject.className});
}
boolean bl = false;
return bl;
}
}
catch (Exception e) {
if (cannedObject.deserializationShouldFail && UnsupportedOperationException.class.getName().equals(e.getClass().getName())) {
boolean bl = true;
return bl;
}
if (!(e instanceof ClassNotFoundException)) {
throw e;
}
if (logEntry != null) {
logEntry.healthCheckError("Deserialization of {} should have failed, however it was successful", new Object[]{cannedObject.className});
}
boolean bl = false;
return bl;
}
finally {
ois.close();
}
++i$;
}
return false;
}
catch (Exception ioe) {
log.warn("Unexpected exception while testing agent capabilities", (Throwable)ioe);
if (logEntry == null) break block16;
logEntry.healthCheckError("Unexpected exception while testing agent capabilities", new Object[]{ioe});
}
}
return false;
}
@Override
public boolean isVMClassReady(@Nullable FormattingResultLog logEntry) {
if (this.vmClass == null) {
if (this.isFirewallLoaded(logEntry)) {
logEntry.info("Agent preloaded. VM Class not required", new Object[0]);
return true;
}
if (logEntry != null) {
StringBuilder sb = new StringBuilder("{");
for (int i = 0; i < this.apiResolvers.size(); ++i) {
sb.append(this.apiResolvers.get(i).getClass().getName());
if (i + 1 >= this.apiResolvers.size()) continue;
sb.append(",");
}
sb.append("}");
logEntry.healthCheckError("VM Class could not be found using resolvers: {}", new Object[]{sb.toString()});
}
return false;
}
logEntry.info("VM Class {} is prepared", new Object[]{this.vmClass.getName()});
return true;
}
private void configureVMClass() {
if (this.vmClass != null) {
return;
}
if (this.apiResolvers.isEmpty()) {
log.error("No AttachAPIResolver services found, cannot attach the agent");
return;
}
for (AttachAPIResolver resolver : this.apiResolvers) {
try {
log.debug("Trying AttachAPIResolver: {}", (Object)resolver);
this.vmClass = (Class)AccessController.doPrivileged(new PrivilegedResolver(resolver));
}
catch (PrivilegedActionException e) {
log.warn("Unexpected exception during doPrivileged", (Throwable)e);
continue;
}
if (this.vmClass == null) continue;
log.info("Using {} provided by {}", this.vmClass, (Object)resolver);
return;
}
}
@Deactivate
public void teardown() {
if (this.jvm != null && this.vmClass != null) {
try {
Method detachMethod;
try {
detachMethod = this.vmClass.getMethod("detach", new Class[0]);
}
catch (NoSuchMethodException nsme) {
log.warn("Unable to get detach method, Deserialization Firewall not unloaded");
return;
}
detachMethod.invoke(this.jvm, new Object[0]);
}
catch (Exception e) {
log.warn("Unable to detatch JVM, Deserialization Firewall not unloaded", (Throwable)e);
return;
}
}
this.jvm = null;
this.vmClass = null;
}
protected void bindSlingSettingsService(SlingSettingsService slingSettingsService) {
this.slingSettingsService = slingSettingsService;
}
protected void unbindSlingSettingsService(SlingSettingsService slingSettingsService) {
if (this.slingSettingsService == slingSettingsService) {
this.slingSettingsService = null;
}
}
private static class LoggingWriter
extends PrintWriter {
public LoggingWriter() {
super(System.out, true);
}
@Override
public void println(String line) {
if (!line.contains(this.getClass().getName())) {
return;
}
log.info(line);
}
}
private class LoadingException
extends Exception {
final /* synthetic */ DeserializationFirewallImpl this$0;
LoadingException(DeserializationFirewallImpl deserializationFirewallImpl, String message) {
this.this$0 = deserializationFirewallImpl;
super(message);
}
LoadingException(DeserializationFirewallImpl deserializationFirewallImpl, String message, Throwable cause) {
this.this$0 = deserializationFirewallImpl;
super(message, cause);
}
}
private static final class PrivilegedResolver
implements PrivilegedExceptionAction<Class<?>> {
final AttachAPIResolver resolver;
PrivilegedResolver(AttachAPIResolver resolver) {
this.resolver = resolver;
}
@Override
public Class<?> run() {
return this.resolver.getAttachAPIClass();
}
}
}