← 中文资源

简体中文版本

Files 属主与符号链接探测

动敏感文件前先验身份:Files.getOwner 读属主 UserPrincipal,NOFOLLOW_LINKS 拒绝被符号链接调包,isReadable 通过才继续敏感操作。

阅读英文原文

实现说明

Files 属主与符号链接探测可以归结为类 OwnershipProbe。

使用要点

  • 直接运行文件,输出会带上标签,比如 owner =、is symlink =、readable =——输出的每一行都能指回产生它的那次调用。

常见问题

运行「Files 属主与符号链接探测」会打印什么?

整个文件跑完,输出行以 owner =、is symlink =、readable = 这类前缀开头。

核心语句

UserPrincipal owner = Files.getOwner(secret, LinkOption.NOFOLLOW_LINKS);
Path secret = Files.createTempFile("credentials-", ".txt");
Files.writeString(secret, "token=change-me");

代码示例

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.attribute.UserPrincipal;

public class OwnershipProbe {

    public static void main(String[] args) throws IOException {
        Path secret = Files.createTempFile("credentials-", ".txt");
        Files.writeString(secret, "token=change-me");

        // NOFOLLOW_LINKS:不解析符号链接,防止路径被链接调包
        UserPrincipal owner = Files.getOwner(secret, LinkOption.NOFOLLOW_LINKS);
        System.out.println("owner = " + owner.getName());
        System.out.println("is symlink = " + Files.isSymbolicLink(secret));

        // 探测通过后再做敏感操作
        System.out.println("readable = " + Files.isReadable(secret));
        Files.deleteIfExists(secret);
    }
}