Get the process privileges from the current process under windows

i want to get the privileges of the current running process with the crate. But unfortunatly windows returns, no matter how big the buffer is, via GetLastError() : "The data area passed to a system call is too small". And the returend buffer is empty.

 unsafe {
            let current_process = GetCurrentProcess();

            let mut token = HANDLE::default();
            let ptoken : *mut HANDLE = &mut token; 

            OpenProcessToken(current_process, TOKEN_QUERY, ptoken);

            let mut token_privileges : *mut TOKEN_PRIVILEGES = std::ptr::null_mut();
            let mut token_privileges_length = 0u32;

            // Call it first with 0 to get the buffer length
                Some(token_privileges as *mut std::ffi::c_void), 
                &mut token_privileges_length as *mut u32

            // Create a buffer
            let mut token_privileges_vec = Vec::<u8>::with_capacity(token_privileges_length as usize);
            token_privileges = token_privileges_vec.as_mut_ptr() as *mut TOKEN_PRIVILEGES;

            // Get the token privileges information
                Some(token_privileges as *mut std::ffi::c_void), 
                &mut token_privileges_length as *mut u32

            let error = GetLastError(); // returns "The data area passed to a system call is too small"

            println!("{:?}", error.to_hresult().message());

            println!("{:?}", token_privileges_vec); // token_privileges_vec is empty

Has anyone an idea what the problem is ? Thanks in advance.

Maybe try passing None instead of Some(token_privileges as *mut std::ffi::c_void) the first time?

I don't think the function is failing, if you check the result it's non-zero which according to the docs means it succeeded. The error you're reading is likely from the first call that intentionally didn't have the right size.

You may want to use

let mut token_privileges_vec = vec![0u8; token_privileges_length as usize];

instead of Vec::with_capacity so you don't have to deal with uninitialized memory, and adjusting the vec's length.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.