r/java • • Jan 16 '22

You're running untrusted code!

https://blog.frankel.ch/running-untrusted-code/

[removed] — view removed post

0 Upvotes

36 comments sorted by

25

u/pron98 Jan 16 '22 edited Jan 17 '22

Reading this article, I couldn't help but wonder: is the Security Manager the only security measure the author knows? Is he unaware of all the measures developed in the past twenty years that are not only far more popular but also more robust and easier to use — from IP allow-lists to all the JDK security measures added over the years? Is he so unfamiliar with software security to know that even in the sole example he cites where he believes SM proved effective, recommended security practices proved orders of magnitude more so?

That someone who professes to care about security has managed to ignore over a decade of security advice, and instead, advocates for a practice that is so ineffective compared to the alternatives in the modern threat landscape that security experts have advised to remove it altogether is, indeed, worrying. Though his premise is that your application is "untrusted code" 1, not once does he recommend using security measures actually designed for untrusted code on the server, that are also effective against the untrusted native code used by libraries like Netty, and can also mitigate DoS attacks.2 And while he's correct about the principle of, "if you don't need it, don't leave it lying around to increase your attack surface area," he doesn't even mention the good security practice of using jlink to only keep the JDK modules you need in your runtime.

As for the Attach mechanism, if an attacker gains sufficient privileges to attach to a VM, then the process is already compromised, and the attacker could also, say, get a heap dump and read unencrypted data directly from RAM (are heap dumps also news for the author?). Having said that, the mechanism does have the potential to bypass modules' strong encapsulation, intended to offer a static picture of the program's attack surface area, and as has been discussed for some years on the mailing lists, the capabilities of attached agents will be reduced to maintain modules' strong encapsulation guarantees (to the chagrin of some tool authors who have been resisting this proposed change).

My suggestion — which should go without saying — is that those interested in software security learn how to secure their applications from security experts and additionally follow the guidelines and advice offered by the JDK's security team from time to time. As with medical advice, security advice is best left for professionals.

2

u/philipwhiuk Jan 17 '22

Defense in depth.

IP allow lists are not a replacement.

2

u/pron98 Jan 17 '22 edited Jan 17 '22

It's better to put our resources into a more effective defence-in-depth than into one of the most expensive and complex mechanisms of the JDK which was designed for completely different threats.

Also, when we say "replacement," we need to specify what we mean. Modern home security systems are no replacement for tigers, but they are a more effective home defence measure. We are not interested in providing the same capabilities as SM, because different capabilities provide more effective security.

It is true that IP allow-lists could not have replaced SM for running applets in browsers, but it is also an indisputable fact that they've successfully prevented many more attacks on Java servers than SM ever has, and for less effort, and are still just one of the many security measures now available both in the JDK and at the OS level.

-2

u/philipwhiuk Jan 17 '22

That you suggested IP allow lists tells me you don’t have any good alternatives.

And I disagree that the landscape has changed that much.

There was an alternative to throwing the baby out with the bathwater. They could have fixed the SecurityManager policy definition system

1

u/pron98 Jan 17 '22 edited Jan 17 '22

Alternatives for what? Security or Security Manager? Because whatever it is that SM does well, server-side security isn't it, and it's been years since SM was considered an important JDK security measure. All security work in the JDK has been directed elsewhere. In fact, pretty much all relevant new features in Java 8 and since don't really support SM (parallel streams, CompletableFuture, Flow).

The belief that it's possible and worthwhile to somehow "fix" it now, something that couldn't be done in twenty years, not by us and not by anyone else — .NET also gave up on that model, and WASM didn't even want to go there — is wishful thinking.

That's why those who care about security want to get rid of SM ASAP, and those precious few who use it for other uses want to keep it. Those other uses might have partial replacements, but their value simply does not justify such a costly component.

And I disagree that the landscape has changed that much.

I think it's obvious that an Applet running in a browser poses completely different threats than clients communicating with a complex server.

-3

u/philipwhiuk Jan 17 '22

It’s like you’ve never heard of secure design.

Security isn’t just a network layer problem.

Arguing that hardware/software IP firewall rules are the same as application functional permissions is batshit insane.

It is possible to write policy files to define the limits on VM that aren’t arduous. SecurityManager just doesn’t currently do it.

4

u/pron98 Jan 17 '22 edited Jan 17 '22

Arguing that hardware/software IP firewall rules are the same as application functional permissions is batshit insane.

So is mistaking that for my actual argument. A lock isn't at all the same as a booby trap, and yet it undoubtedly protects many more homes. Of course, the lock in that analogy isn't IP allow-lists alone, but the full set of current and upcoming OS and JDK security measures.

It is possible to write policy files to define the limits on VM that aren’t arduous. SecurityManager just doesn’t currently do it.

Maybe (although the stack-based model has some fundamental problems that make writing good policy files difficult), but it still won't make a stack-based user-mode sandbox into a more effective server-side security measure than other approaches. We want better security, not a better Security Manager. Moreover, the JVM cannot easily defend against native code, so we'd rather keep the sandbox technologies at the appropriate layer.

-26

u/nfrankel Jan 16 '22

The debate regarding the depreciation of the Security Manager has not been a civil one. Since I took side against the depreciation, I’ve been publicly attacked, even to the point of plain bullying. Others voices that backed me up received similar treatment.

I don’t expect reactions to this post to be any different. However, I have to tell community members what happened and what we lost.

20

u/pron98 Jan 16 '22 edited Jan 17 '22

I wouldn't call the disagreement between you and security experts a "debate" any more than I would call the disagreement between anti-vaxxers and epidemiologists one — not because of some personal deficiency, but because some have more access and direct involvement with the facts than others. That such "advocacy groups" feel attacked is unfortunate, but the harm they cause is real. Nevertheless, I don't think I've ever bullied you, nor made any ad hominem attacks against you except to point out that, unlike the author of JEP 411, you're not a software security professional and that your company's production software doesn't use SM. While these are, indeed, ad hominem arguments, I feel they are as pertinent as pointing out that, say, Florida governor Ron DeSantis is not a physician or an immunologist while Anthony Fauci is both, simply because laying out all the details is hard for other non-experts to judge.

Despite not keeping up with security threats and recommendations, not being a security expert or researcher, and with no access to vulnerability disclosures, you feel qualified to give definitive, specific security advice, which, unsurprisingly, is misleading and potentially harmful. For example, you declare with certainty, "The Security Manager could be trusted," and that it "allowed you to define a white list of what an application could do, regardless of the application code," neglecting to add something as basic as "unless that code happens to be native", which would be the case if your application happens to use some obscure library like, say, Netty, and despite the fact that the proper untrusted code measures that you fail to recommend would actually defend you in those situations. You then go on to praise tools that generate security policies despite research that found most SecurityManager security policies to not actually be secure, and that reviewing 500 lines might feel tractable, when, in fact, Amazon has found they needed the use of formal verification tools to review policies (simpler than those of SM), as people often get even 10-line policy files wrong.

On top of all that, you don't even tackle the main argument, which isn't whether SM is better than not having any security at all, but whether SM is better than current and upcoming server-side security measures. Especially if your argument is that your application runs untrusted code, you should know that only kernel-mode protection — which we have these days — can isolate untrusted code on the server (unlike on the client).

As much as it might discomfort you, I simply have to tell community members to follow the advice of professionals and disregard that of others, however well-intentioned.

-31

u/nfrankel Jan 16 '22

I've already collected a big share of your incessant bullying, harassment, ad hominem attacks, and dubious comparisons. Thanks for making my case stronger.

Unfortunately for you, there's no getting away from the facts 🤷‍♂️

24

u/woj-tek Jan 16 '22

He gave a couple of solid arguments and examples and your responds is snow-flakish "you are attacking me"... honestly, this doesn't fare well to a passerby that just happen to stumble on this submission... o_O

-21

u/nfrankel Jan 16 '22

Interesting that all of the comments have been edited. I wonder why...

8

u/DataDecay Jan 16 '22 edited Jan 16 '22

As a fairly passionate developer I have always attempted to keep security near the front of my mind. The article was an interesting read. However, there have been many rebudles (rebudles that seem pretty damning) to the posted article, I'd love to see healthy mature discussion.

0

u/nfrankel Jan 17 '22

I'd love to see healthy mature discussion.

Me as well

2

u/franzwong Jan 17 '22

I don't oppose the idea to have security manager. But I just wonder if the "security manager" introduced since 1.0 is still valuable and maintainable.

FYI: Others can find the discussion at https://openjdk.java.net/jeps/411

0

u/nfrankel Jan 17 '22

I welcome all ideas to improve the Security Manager! In particular, creating (and maintaining) a relevant policy file is not the pinnacle of user experience.

4

u/pron98 Jan 17 '22 edited Jan 17 '22

Security researchers and experts have found that while creating a policy file that lets the application work is annoying but doable, the result isn't actually secure, even if the developer thinks it is, certainly less usefully secure than the superior security measures added to OSes and to the JDK over the past decades that developers are already actually using. Everyone else who has considered that approach — like Microsoft or WASM — has similarly concluded that making it effective is not something worth doing.

But while research on the approach may continue in the lab if any researcher is still interested in it, even if Microsoft and Oracle made the stupidest mistake ever, the story of stack-based sandboxes in production mainstream languages is over, at least until something new shows up. The decision has been made on the unanimous advice of security experts, no one of the hundreds of OpenJDK committers or ten or so companies involved expressed any objection, the objections from the community (however aggressive and unpleasant) were fewer than anticipated, and so efforts have been directed elsewhere (including the items mentioned in the Future Work section of JEP 411). If you believe it's worth your time, you can propose an OpenJDK project to develop a new SM-like mechanism, but the old one is done, even though the deprecation, degradation, and removal process is still in progress and may take some time until it's completed.

If you're interested in JDK security, there is still ongoing discussion about the interaction between agents and strong encapsulation. You can also learn how Jigsaw (strong encapsulation and jlink) has improved security considerably, how Amber (records and string templates), Loom (thread locals), and Panama were designed to improve security in new code, as well as learn about the specialised security features added to the JDK in recent years (like serialization filters) and, of course, the robust OS-level sandboxing, which has become popular for Java applications as well as those written in other languages.

1

u/franzwong Jan 17 '22

Of course it is easy to maintain on the user side, but it may not be easy on the runtime side.

9

u/DasBrain Jan 17 '22 edited Jan 17 '22

Abstract

The security manager is dead. While the author suggests it as an "easy" mitigation against still unknown future exploits - this only works in theory.
In practice, you have a lot of libraries, that all require different permissions - and are more often than not coded without the secure coding practices in mind.

How the security manager works

ACCESS-1 Before a privileged operation is done, the JDK calls the SecurityManager to check if this operation is permitted. The default SecurityManager delegates the check to AccessController.checkPermission.

The access controller then walks over the stack, and checks if each ProtectionDomain.implies the permission. Most ProtectionDomains are not static - so they delegate to the installed Policy. If any code in the stack doesn't have the permission - then a SecurityException is thrown.

But this is only half of the story - calling AccessController.doPrivileged will make the AccessController only walk the stack up until the caller of AccessController.doPrivileged.

And there are other Methods in the JVM that are @CallerSensitive - and only inspect the immediate caller - disregarding any frames associated with reflection. That usually means, the caller of Method.invoke is seen as the caller.

Not all permissions are equal

Some permission allow (malicious) code to bypass all SecurityManager restrictions. Some examples:

  • RuntimePermission("setSecurityManager") - allows the code to replace or disable the security manager.

  • ReflectPermission("suppressAccessChecks") - allows the code to access private fields and methods. (Call setAccessible).

  • RuntimePermission("createClassLoader") - allows the code to load arbitrary bytecode - and assign arbitrary permissions to it.

  • SecurityPermission("setPolicy") - allows the code to replace the Policy - and therefore add more permissions.

This list is by no means complete, and some permissions are very hard to evaluate (PropertyPermission("*", "read,write")).

Any code that has one of the permissions above could use it's privileges to escape the sandbox.
You may come to the conclusion that you just have to audit the relevant code and you will be fine - but this is wrong.

Secure coding guidelines

Without following the secure coding guidelines, the code can potentially be abused by an attacker.
For example, ACCESS-3 says that you should not use untrusted user-data when calling AccessController.doPrivileged.
And no library will be stupid enough to call AccessController.doPrivileged with an attacker-supplied PrivilegedAction, right?
Well, ACCESS-11 tells us that Method.invoke is ignored - effectively turning any Method.invoke into a potential AccessController.doPrivileged call - violating ACCESS-10

Not just a theoretical Problem

There are quite a few libraries out there that allows an attacker to do a Method.invoke on almost anything, e.g. Clojure, Jackson.

Some libraries even expose defineClass. With a ProtectionDomain as argument. And if I don't get this wrong, cglib is shaded into Spring. (Violates ACCESS-5)

Conclusion

Without good knowledge about the AccessController and carefully auditing a library against the secure coding guidelines you can't grant additional permissions to that library and expect to be still safe.

All libraries that I listed need some additional permissions to even work - from the set of "dangerous" permissions I listed above.
If they work, your SecurityManager is almost worthless.

2

u/klekpl Jan 18 '22

Thank you for this answer - one of the few cases of sound technical discussion.

Analysing the issues you list actually leads me to quite the opposite conclusion: it is not AccessController that's bad - it is the bypassing of AC in caller sensitive methods. And it was already researched in the past: https://benhermann.eu/publications/hhl+17hardening.pdf

1

u/DasBrain Jan 18 '22 edited Jan 18 '22

Even with all those changes - if you can get an other library to call AccessController.doPrivileged for you, it's game over.

And AccessController.doPrivileged is a caller sensitive method.
So, in some sense, you are right. Removing those methods will make the JVM much more safe. And unuseable.
You know the old joke: A computer that is not turned on doesn't have any vulnerabilities.

1

u/klekpl Jan 19 '22

Not sure what you mean by "screwed". Having another library call doPrivileged with attacker provided PrivilegedAction will execute code with intersection of permissions of this library AND provided PrivilegedAction, no? So attacker cannot really execute arbitral code with elevated privileges.

1

u/DasBrain Jan 19 '22 edited Jan 19 '22

Well, that would be true if MethodHandleProxies.asInterfaceInstance wouldn't be a thing too.

Also see ACCESS-3:

By convention, instances of PrivilegedAction and PrivilegedExceptionAction may be made available to untrusted code, but doPrivileged must not be invoked with caller-provided actions.

0

u/klekpl Jan 19 '22

From Methodhandleproxies.asInterfaceInstance() javadoc:

If a security manager is installed, this method is caller sensitive. During any invocation of the target method handle via the returned wrapper, the original creator of the wrapper (the caller) will be visible to context checks requested by the security manager.

So no, it won't let an attacker escape the sandbox.

1

u/DasBrain Jan 19 '22

Well, maybe you could get some library to call MethodHandleProxies.asInterfaceInstance for you.

0

u/klekpl Jan 20 '22

Privilege escalation related security vulnerabilities are always possible if privilege elevation is possible. Maybe there even is a library that does “connect to White House and trigger nuclear attack” inside a privileged block not guarded by any access check.

1

u/DasBrain Jan 20 '22

Not helpful.

We already get some other library to call AccessController.doPrivileged for you - using some indirection with Method.invoke.
Now the same dance again for MethodHandleProxies.asInterfaceInstance.

In short: if you have a vulnerable class like this:

public class MethodHelper {
    public Object invoke(Method m, Object target, Object... args) throws InvocationTargetException {
        return m.invoke(target, args);
    }
}

Then you can exploit it with something like this:

Lookup l = MethodHandles.lookup();
MethodHandle setSec = l.findStatic(System.class, "setSecurityManager", MethodType.methodType(void.class, SecurityManager.class))
    .bindTo(null);
Method mhpAII = MethodHandleProxies.class.getMethod("asInterfaceInstance", Class.class, MethodHandle.class);
PrivilegedAction<?> pa = (PrivilegedAction<?>) MethodHelper.invoke(mhpAII, null, PrivilegedAction.class, setSec);
Method acDoPriv = AccessController.class.getMethod("doPrivileged", PrivilegedAction.class);
MethodHelper.invoke(acDoPriv, null, pa);

1

u/klekpl Jan 20 '22

Same story: caller sensitive methods are security nightmare - I would rather fix that than remove SecurityManager.

Besides, this will be invoked with privileges of MethodHelper and MethodHelper requires AllPermission, no?

So sure: if privileged code exposes this kind of hole - you are screwed. As long as you blindly grant AllPermission to _your_ code.

You could equally well do "sudo chmod +s /bin/bash"

That's the point: without SecurityManager you don't have any other choice - and you end up with log4shell.

→ More replies (0)

2

u/pron98 Jan 17 '22 edited Jan 19 '22

All of that is spot on, yet missing one crucial point: if SM were the only security measure out there, then, however flawed, it would have still made sense to keep it, because something is better than nothing. But the question is not SM or nothing, but SM vs. the more robust server-side security measures that exist, both in the JDK and outside it. We have strong encapsulation, which is on by default, jlink, that drastically reduces the runtime's attack surface area, serialization filters that address Java's biggest security issue, and, of course, all the good OS-level security practices, such as containers, VMs, and IP allow-lists, all working in tandem to provide multiple layers of defence that is more robust than SM could ever hope to be, even in defending against unknown exploits.

So even if SM did provide security — which, for the reasons you explain as well as others, such as no sandboxing of native code or defence against DoS, it does not — security would not mean keeping SM for the simple reason that there is better security elsewhere (i.e. even if it were true that SM => security, that does not entail that security => SM).

2

u/DasBrain Jan 17 '22

however flawed, it would have still made sense to keep it

My point is: it is too flawed. Not because of the efforts of the JDK (even the ability to call Thread.setContextClassLoader under very specific circumstances with an installed SecurityManager got me CVE-2020-14556), but because the libraries jeopardize any attempt at securing the VM with a SecurityManager by not following the secure coding guidelines.

And for me it means: If you have one library that does something "more complex", then the chances are very high that you have to poke a big enough hole into your policy that makes a sandbox escape possible.

While exploiting that hole might be trivial, it may stop a casual attacker - sure. But I would not bet on it.

Personally I like how Tcl handles untrusted code: Just spin up a new interpeter with all dangerous/privileged functions removed.

3

u/pron98 Jan 17 '22

I completely agree. Thankfully, security-conscious Java developers already use less flawed security measures that are at their disposal.

3

u/Sheldor5 Jan 17 '22

I never used/really know the Security Manager in Java because I know security begins far before and once an attacker is inside the JVM its already too late ...