Search in sources :

Example 51 with Advapi32

use of com.sun.jna.platform.win32.Advapi32 in project jna by java-native-access.

the class Advapi32Util method registryDeleteValue.

/**
	 * Delete a registry value.
	 *
	 * @param root
	 *            Root key.
	 * @param keyPath
	 *            Path to an existing registry key.
	 * @param valueName
	 *            Name of the value to delete.
	 */
public static void registryDeleteValue(HKEY root, String keyPath, String valueName) {
    HKEYByReference phkKey = new HKEYByReference();
    int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, keyPath, 0, WinNT.KEY_READ | WinNT.KEY_WRITE, phkKey);
    if (rc != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(rc);
    }
    try {
        registryDeleteValue(phkKey.getValue(), valueName);
    } finally {
        rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
        if (rc != W32Errors.ERROR_SUCCESS) {
            throw new Win32Exception(rc);
        }
    }
}
Also used : HKEYByReference(com.sun.jna.platform.win32.WinReg.HKEYByReference)

Example 52 with Advapi32

use of com.sun.jna.platform.win32.Advapi32 in project jna by java-native-access.

the class Advapi32Util method convertStringSidToSid.

/**
	 * Convert a string representation of a security identifier (SID) to a
	 * binary format.
	 *
	 * @param sidString
	 *            String SID.
	 * @return SID bytes.
	 */
public static byte[] convertStringSidToSid(String sidString) {
    PSIDByReference pSID = new PSIDByReference();
    if (!Advapi32.INSTANCE.ConvertStringSidToSid(sidString, pSID)) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    PSID value = pSID.getValue();
    try {
        return value.getBytes();
    } finally {
        Kernel32Util.freeLocalMemory(value.getPointer());
    }
}
Also used : PSIDByReference(com.sun.jna.platform.win32.WinNT.PSIDByReference) PSID(com.sun.jna.platform.win32.WinNT.PSID)

Example 53 with Advapi32

use of com.sun.jna.platform.win32.Advapi32 in project jna by java-native-access.

the class Advapi32Util method getFileSecurityDescriptor.

/**
     * Gets a file's Security Descriptor. Convenience wrapper getSecurityDescriptorForObject.
     *
     * @param file
     *         File object containing a path to a file system object.
     * @param getSACL
     *         Get the SACL. See {@link Advapi32#GetNamedSecurityInfo} for process privilege requirements in getting the SACL.
     * @return The file's Security Descriptor in self relative format.
     */
public static SECURITY_DESCRIPTOR_RELATIVE getFileSecurityDescriptor(File file, boolean getSACL) {
    SECURITY_DESCRIPTOR_RELATIVE sdr = null;
    Memory securityDesc = getSecurityDescriptorForObject(file.getAbsolutePath().replaceAll("/", "\\"), AccCtrl.SE_OBJECT_TYPE.SE_FILE_OBJECT, getSACL);
    sdr = new SECURITY_DESCRIPTOR_RELATIVE(securityDesc);
    return sdr;
}
Also used : Memory(com.sun.jna.Memory) SECURITY_DESCRIPTOR_RELATIVE(com.sun.jna.platform.win32.WinNT.SECURITY_DESCRIPTOR_RELATIVE)

Example 54 with Advapi32

use of com.sun.jna.platform.win32.Advapi32 in project jna by java-native-access.

the class Advapi32Util method accessCheck.

/**
     * Checks if the current process has the given permission for the file.
     * @param file the file to check
     * @param permissionToCheck the permission to check for the file
     * @return true if has access, otherwise false
     */
public static boolean accessCheck(File file, AccessCheckPermission permissionToCheck) {
    Memory securityDescriptorMemoryPointer = getSecurityDescriptorForFile(file.getAbsolutePath().replace('/', '\\'));
    HANDLEByReference openedAccessToken = new HANDLEByReference();
    HANDLEByReference duplicatedToken = new HANDLEByReference();
    Win32Exception err = null;
    try {
        int desireAccess = TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_DUPLICATE | STANDARD_RIGHTS_READ;
        HANDLE hProcess = Kernel32.INSTANCE.GetCurrentProcess();
        if (!Advapi32.INSTANCE.OpenProcessToken(hProcess, desireAccess, openedAccessToken)) {
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        }
        if (!Advapi32.INSTANCE.DuplicateToken(openedAccessToken.getValue(), SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, duplicatedToken)) {
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        }
        GENERIC_MAPPING mapping = new GENERIC_MAPPING();
        mapping.genericRead = new DWORD(FILE_GENERIC_READ);
        mapping.genericWrite = new DWORD(FILE_GENERIC_WRITE);
        mapping.genericExecute = new DWORD(FILE_GENERIC_EXECUTE);
        mapping.genericAll = new DWORD(FILE_ALL_ACCESS);
        DWORDByReference rights = new DWORDByReference(new DWORD(permissionToCheck.getCode()));
        Advapi32.INSTANCE.MapGenericMask(rights, mapping);
        PRIVILEGE_SET privileges = new PRIVILEGE_SET(1);
        privileges.PrivilegeCount = new DWORD(0);
        DWORDByReference privilegeLength = new DWORDByReference(new DWORD(privileges.size()));
        DWORDByReference grantedAccess = new DWORDByReference();
        BOOLByReference result = new BOOLByReference();
        if (!Advapi32.INSTANCE.AccessCheck(securityDescriptorMemoryPointer, duplicatedToken.getValue(), rights.getValue(), mapping, privileges, privilegeLength, grantedAccess, result)) {
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        }
        return result.getValue().booleanValue();
    } catch (Win32Exception e) {
        err = e;
        // re-throw so finally block executed
        throw err;
    } finally {
        try {
            Kernel32Util.closeHandleRefs(openedAccessToken, duplicatedToken);
        } catch (Win32Exception e) {
            if (err == null) {
                err = e;
            } else {
                err.addSuppressed(e);
            }
        }
        if (securityDescriptorMemoryPointer != null) {
            securityDescriptorMemoryPointer.clear();
        }
        if (err != null) {
            throw err;
        }
    }
}
Also used : BOOLByReference(com.sun.jna.platform.win32.WinDef.BOOLByReference) PRIVILEGE_SET(com.sun.jna.platform.win32.WinNT.PRIVILEGE_SET) GENERIC_MAPPING(com.sun.jna.platform.win32.WinNT.GENERIC_MAPPING) DWORDByReference(com.sun.jna.platform.win32.WinDef.DWORDByReference) Memory(com.sun.jna.Memory) DWORD(com.sun.jna.platform.win32.WinDef.DWORD) HANDLEByReference(com.sun.jna.platform.win32.WinNT.HANDLEByReference) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE)

Example 55 with Advapi32

use of com.sun.jna.platform.win32.Advapi32 in project jna by java-native-access.

the class Advapi32Util method backupEncryptedFile.

/**
     * Backup an encrypted file or folder without decrypting it. A file named
     * "bar/sample.text" will be backed-up to "destDir/sample.text". A directory
     * named "bar" will be backed-up to "destDir/bar". This method is NOT
     * recursive. If you have an encrypted directory with encrypted files, this
     * method must be called once for the directory, and once for each encrypted
     * file to be backed-up.
     *
     * @param src
     *         The encrypted file or directory to backup.
     * @param destDir
     *         The directory where the backup will be saved.
     */
public static void backupEncryptedFile(File src, File destDir) {
    if (!destDir.isDirectory()) {
        throw new IllegalArgumentException("destDir must be a directory.");
    }
    // Open the file for export (backup)
    ULONG readFlag = new ULONG(0);
    // Import (restore) file
    ULONG writeFlag = new ULONG(CREATE_FOR_IMPORT);
    if (src.isDirectory()) {
        writeFlag.setValue(CREATE_FOR_IMPORT | CREATE_FOR_DIR);
    }
    // open encrypted file for export
    String srcFileName = src.getAbsolutePath();
    PointerByReference pvContext = new PointerByReference();
    if (Advapi32.INSTANCE.OpenEncryptedFileRaw(srcFileName, readFlag, pvContext) != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    // read encrypted file
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    FE_EXPORT_FUNC pfExportCallback = new FE_EXPORT_FUNC() {

        @Override
        public DWORD callback(Pointer pbData, Pointer pvCallbackContext, ULONG ulLength) {
            byte[] arr = pbData.getByteArray(0, ulLength.intValue());
            try {
                outputStream.write(arr);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return new DWORD(W32Errors.ERROR_SUCCESS);
        }
    };
    if (Advapi32.INSTANCE.ReadEncryptedFileRaw(pfExportCallback, null, pvContext.getValue()) != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    // close
    try {
        outputStream.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Advapi32.INSTANCE.CloseEncryptedFileRaw(pvContext.getValue());
    // open file for import
    String destFileName = destDir.getAbsolutePath() + File.separator + src.getName();
    pvContext = new PointerByReference();
    if (Advapi32.INSTANCE.OpenEncryptedFileRaw(destFileName, writeFlag, pvContext) != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    // write encrypted file
    final IntByReference elementsReadWrapper = new IntByReference(0);
    FE_IMPORT_FUNC pfImportCallback = new FE_IMPORT_FUNC() {

        @Override
        public DWORD callback(Pointer pbData, Pointer pvCallbackContext, ULONGByReference ulLength) {
            int elementsRead = elementsReadWrapper.getValue();
            int remainingElements = outputStream.size() - elementsRead;
            int length = Math.min(remainingElements, ulLength.getValue().intValue());
            pbData.write(0, outputStream.toByteArray(), elementsRead, length);
            elementsReadWrapper.setValue(elementsRead + length);
            ulLength.setValue(new ULONG(length));
            return new DWORD(W32Errors.ERROR_SUCCESS);
        }
    };
    if (Advapi32.INSTANCE.WriteEncryptedFileRaw(pfImportCallback, null, pvContext.getValue()) != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    // close
    Advapi32.INSTANCE.CloseEncryptedFileRaw(pvContext.getValue());
}
Also used : ULONG(com.sun.jna.platform.win32.WinDef.ULONG) IntByReference(com.sun.jna.ptr.IntByReference) DWORD(com.sun.jna.platform.win32.WinDef.DWORD) Pointer(com.sun.jna.Pointer) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ULONGByReference(com.sun.jna.platform.win32.WinDef.ULONGByReference) PointerByReference(com.sun.jna.ptr.PointerByReference) FE_EXPORT_FUNC(com.sun.jna.platform.win32.WinBase.FE_EXPORT_FUNC) FE_IMPORT_FUNC(com.sun.jna.platform.win32.WinBase.FE_IMPORT_FUNC)

Aggregations

IntByReference (com.sun.jna.ptr.IntByReference)51 SC_HANDLE (com.sun.jna.platform.win32.Winsvc.SC_HANDLE)39 HANDLE (com.sun.jna.platform.win32.WinNT.HANDLE)31 HKEYByReference (com.sun.jna.platform.win32.WinReg.HKEYByReference)31 HANDLEByReference (com.sun.jna.platform.win32.WinNT.HANDLEByReference)23 PSID (com.sun.jna.platform.win32.WinNT.PSID)20 PointerByReference (com.sun.jna.ptr.PointerByReference)20 Advapi32 (com.sun.jna.platform.win32.Advapi32)15 DWORD (com.sun.jna.platform.win32.WinDef.DWORD)15 File (java.io.File)15 Memory (com.sun.jna.Memory)13 HKEY (com.sun.jna.platform.win32.WinReg.HKEY)13 PSIDByReference (com.sun.jna.platform.win32.WinNT.PSIDByReference)10 DWORDByReference (com.sun.jna.platform.win32.WinDef.DWORDByReference)9 ACL (com.sun.jna.platform.win32.WinNT.ACL)9 SECURITY_DESCRIPTOR (com.sun.jna.platform.win32.WinNT.SECURITY_DESCRIPTOR)7 Pointer (com.sun.jna.Pointer)6 ACCESS_ALLOWED_ACE (com.sun.jna.platform.win32.WinNT.ACCESS_ALLOWED_ACE)6 GENERIC_MAPPING (com.sun.jna.platform.win32.WinNT.GENERIC_MAPPING)6 BOOLByReference (com.sun.jna.platform.win32.WinDef.BOOLByReference)5