Home Operation and Maintenance Safety What is the security sandbox mechanism for Java applications?

What is the security sandbox mechanism for Java applications?

May 16, 2023 pm 06:26 PM
java

If you often read the source code, you will find that there is a piece of code similar to the following in the Java source code.

class File {<br/>  // 判断一个磁盘文件是否存在<br/>  public boolean exists() {<br/>    SecurityManager security = System.getSecurityManager();<br/>    if (security != null) {<br/>      security.checkRead(path);<br/>    }<br/>    ...<br/>  }<br/>}<br/>
Copy after login


This is obviously a security check code, checking whether you have access Disk path permissions, why does the Java language need such security checking code? Let’s look at the source code of the connect function of the client socket. It needs to check whether the user has permission to connect to a certain network address.

class Socket {<br/>  public void connect(SocketAddress endpoint, int timeout) {<br/>    ...<br/>    SecurityManager security = System.getSecurityManager();<br/>    if (security != null) {<br/>       if (epoint.isUnresolved())<br/>          security.checkConnect(epoint.getHostName(), port);<br/>       else<br/>          security.checkConnect(addr.getHostAddress(), port);<br/>       }<br/>    }<br/>    ...<br/>  }<br/>}<br/>
Copy after login


Let’s look at the source code of the server socket. It will check Port listening permission

class ServerSocket {<br/>  public void bind(SocketAddress endpoint, int backlog) {<br/>    ...<br/>    SecurityManager security = System.getSecurityManager();<br/>    if (security != null)<br/>       security.checkListen(epoint.getPort());<br/>    ...<br/>  }<br/>}<br/>
Copy after login


It seems that all method calls related to IO operations require security checks. It seems that the permission checks related to IO operations are understandable, and user processes cannot access all IO resources at will. But even environment variables are not allowed to be read at will, and the restriction is not all environment variables, but a specific environment variable. Is this security check a bit too much?

class System {<br/>  public static String getenv(String name) {<br/>    SecurityManager sm = getSecurityManager();<br/>    if (sm != null) {<br/>       sm.checkPermission(new RuntimePermission("getenv."+name));<br/>    }<br/>    return ProcessEnvironment.getenv(name);<br/>  }<br/>}<br/>
Copy after login


This is because Java's security check manager and the operating system's permission check are not the same concept. Java writes not only server-side applications, it can also run on the browser as a client. (Applet), it can also run on a mobile phone in the form of an app (J2ME). The JVM will use different security strategies for different platforms. Usually, the restrictions on Applets are very strict, and Applets are generally not allowed to operate local files. Before performing specific IO operations, once Java's security check passes, the operating system will still perform a permission check.

We usually do not open the security checker by default when running java programs locally. We need to execute the jvm parameters to open it

$ java -Djava.security.manager xxx<br/>$ java -Djava.security.manager -DDjava.security.policy="${policypath}"<br/>
Copy after login


Because the security restrictions can be customized, it is also You need to provide a specific security policy file path. The default policy file path is JAVA_HOME/jre/lib/security/java.policy. Let’s take a look at what is written in this file

// 内置扩展库授权规则<br/>// 表示 JAVA_HOME/jre/lib/ext/ 目录下的类库可以全权访问任意资源<br/>// 包含 javax.swing.*, javax.xml.*, javax.crypto.* 等等<br/>grant codeBase "file:${{java.ext.dirs}}/*" {<br/> permission java.security.AllPermission;<br/>};<br/><br/>// 其它类库授权规则<br/>grant {<br/> // 允许线程调用自己的 stop 方法自杀<br/> permission java.lang.RuntimePermission "stopThread";<br/> // 允许程序监听 localhost 的随机可用端口,不允许随意订制端口<br/> permission java.net.SocketPermission "localhost:0", "listen";<br/> // 限制获取系统属性,下面一系列的配置都是只允许读部分内置属性<br/> permission java.util.PropertyPermission "java.version", "read";<br/> permission java.util.PropertyPermission "java.vendor", "read";<br/> permission java.util.PropertyPermission "java.vendor.url", "read";<br/> permission java.util.PropertyPermission "java.class.version", "read";<br/> permission java.util.PropertyPermission "os.name", "read";<br/> permission java.util.PropertyPermission "os.version", "read";<br/> permission java.util.PropertyPermission "os.arch", "read";<br/> permission java.util.PropertyPermission "file.separator", "read";<br/> permission java.util.PropertyPermission "path.separator", "read";<br/> permission java.util.PropertyPermission "line.separator", "read";<br/> permission java.util.PropertyPermission "java.specification.version", "read";<br/> permission java.util.PropertyPermission "java.specification.vendor", "read";<br/> permission java.util.PropertyPermission "java.specification.name", "read";<br/> permission java.util.PropertyPermission "java.vm.specification.version", "read";<br/> permission java.util.PropertyPermission "java.vm.specification.vendor", "read";<br/> permission java.util.PropertyPermission "java.vm.specification.name", "read";<br/> permission java.util.PropertyPermission "java.vm.version", "read";<br/> permission java.util.PropertyPermission "java.vm.vendor", "read";<br/> permission java.util.PropertyPermission "java.vm.name", "read";<br/>};<br/>
Copy after login


grant If the codeBase parameter is provided, the permission rules are configured for the specific class library. If codeBase is not specified, the rules are configured for all other class libraries.

If the security check fails, a java.security.AccessControlException exception will be thrown. Even if the security check passes, the operating system's permission check may fail, in which case other types of exceptions will be thrown.

If you follow the rules configured above, the JVM using the default security policy will not be able to access local files because the authorization rules use a whitelist. If you need to access local files, you can add the following rules

permission java.io.FilePermission "/etc/passwd", "read";<br/>permission java.io.FilePermission "/etc/shadow", "read,write";<br/>permission java.io.FilePermission "/xyz", "read,write,delete";<br/>// 允许读所有文件<br/>permission java.io.FilePermission "*", "read";<br/>
Copy after login


The configuration parameters of Permission exactly correspond to its constructor parameters

public FilePermission(String path, String actions) {<br/>  super(path);<br/>  init(getMask(actions));<br/>}<br/>
Copy after login


Java default security rules are divided into several Large modules, each module has its own configuration parameters

What is the security sandbox mechanism for Java applications?

where AllPermission means opening all permissions. There is also an uninvited guest, HibernatePermission, which is not a built-in permission module. It is customized by the Hibernate framework, which means that security rules support custom extensions. To extend is easy, just write a Permission subclass and implement its four abstract methods.

abstract class Permission {<br/>  // 权限名称,对于文件来说就是文件名,对于套接字来说就是套接字地址<br/>  // 它的意义是子类可定制的<br/>  private String name;<br/>  // 当前权限对象是否隐含了 other 权限<br/>  // 比如 AllPermission 的这个方法总是返回 true<br/>  public abstract boolean implies(Permission other);<br/>  // equals 和 hashcode 用于权限比较<br/>  public abstract boolean equals(Object obj);<br/>  public abstract int hashCode();<br/>  // 权限选项 read,write,xxx<br/>  public abstract String getActions();<br/>}<br/><br/>class CustomPermission extends Permission {<br/>  private String actions;<br/>  CustomPermission(string name, string actions) {<br/>    super(name)<br/>    this.actions = actions;<br/>  }<br/>  ...<br/>}<br/>
Copy after login


When the JVM starts, the permission rules defined in the profile will be loaded into the permission pool. The user program uses the permission pool in a specific API method to determine whether it contains the permission to call this API. Eventually, it will It is implemented by calling the implies method of each permission object in the permission pool to determine whether it has the specified permission.

class CustomAPI {<br/>  public void someMethod() {<br/>    SecurityManager sec = System.getSecurityManager();<br/>    if(sec != null) {<br/>      sec.CheckPermission(new CustomPermission("xname", "xactions"));<br/>    }<br/>    ...<br/>  }<br/>}<br/>
Copy after login


Enabling security check will reduce the execution efficiency of the program. If there are too many permission rules defined in the profile, the check efficiency will be very slow. When using it, pay attention to the security check and use it sparingly. .

There are many security checkpoints in the sandbox. Here are some common scenarios

  1. File operation

  2. Socket Operations

  3. Threads and Thread Groups

  4. Class Loader Control

  5. Reflection Control

  6. Thread stack information acquisition

  7. Network proxy control

  8. Cookie read and write control

If your server program has security checks turned on, you need to open a lot of security settings in the policy configuration file, which is very cumbersome, and if you configure too many configurations, the performance of the checks will also suffer a certain loss. This is somewhat similar to Android application permission settings. A series of application sub-permissions need to be listed in the configuration file of each Android application. However, it seems that there is no need to turn on security checks when writing server-side programs in Java.

The above is the detailed content of What is the security sandbox mechanism for Java applications?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles