package com.widgetworkbench.cheerpj; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * CheerpJ-only shim for Java 11 UnixSystem.getUnixInfo(). * * The browser does not have an OS account. This class intentionally supplies * an unprivileged synthetic Unix identity ONLY for the JDK OS-name lookup. * It does not authenticate a MES user and must never be used for access control. * It can be called from the CheerpJ jaas.js native implementation without * modifying or repackaging vendor JARs. */ public final class JaasIdentityBridge { public static final String VIRTUAL_USER = "cheerpj-client"; private static final long VIRTUAL_UID = 65534L; private JaasIdentityBridge() { } /** Set the four instance fields the native OpenJDK Unix.c normally sets. */ public static String populate(Object unixSystem) { if (unixSystem == null || !"com.sun.security.auth.module.UnixSystem".equals(unixSystem.getClass().getName())) { throw new IllegalArgumentException("Expected an OpenJDK UnixSystem instance"); } try { setField(unixSystem, "username", VIRTUAL_USER); setField(unixSystem, "uid", VIRTUAL_UID); setField(unixSystem, "gid", VIRTUAL_UID); setField(unixSystem, "groups", new long[0]); Method nameGetter = unixSystem.getClass().getMethod("getUsername"); Object result = nameGetter.invoke(unixSystem); if (!VIRTUAL_USER.equals(result)) { throw new IllegalStateException("UnixSystem username was not populated"); } return VIRTUAL_USER; } catch (ReflectiveOperationException ex) { throw new IllegalStateException("Cannot populate virtual UnixSystem identity", ex); } } private static void setField(Object target, String name, Object value) throws ReflectiveOperationException { Field field = target.getClass().getDeclaredField(name); // On a Java 11+ module with an open package, normal reflection is enough. // On standard JDKs jdk.security.auth exports but does not open the package; // use the JDK-provided Unsafe implementation to set exactly these fields. try { if (field.trySetAccessible()) { field.set(target, value); return; } } catch (SecurityException ex) { // Try the explicitly scoped fallback below. } Class unsafeType = Class.forName("sun.misc.Unsafe"); Field theUnsafe = unsafeType.getDeclaredField("theUnsafe"); if (!theUnsafe.trySetAccessible()) { throw new IllegalStateException("Unsafe unavailable in this Java runtime"); } Object unsafe = theUnsafe.get(null); long offset = ((Number) unsafeType.getMethod("objectFieldOffset", Field.class) .invoke(unsafe, field)).longValue(); if (field.getType() == long.class) { unsafeType.getMethod("putLong", Object.class, long.class, long.class) .invoke(unsafe, target, offset, ((Number) value).longValue()); } else { unsafeType.getMethod("putObject", Object.class, long.class, Object.class) .invoke(unsafe, target, offset, value); } } }