- Remove From My Forums
-
Question
-
I am using WIndows 2008 with maximum UAC enabled(Always Notify me…). I am starting Porcess A with Standard user token. Then trying to open Process B (Started with admin token) using process id. I just need the process handle.I have the following
code to open process B. It fails and returns ACCESS_DENIED during this operation.HANDLE hProcess=OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE,pid);
I tried to adjust token privilege using following code. But AdjustTokenPrivileges() returns True But gives error ERROR_NOT_ALL_ASSIGNED. Also i cannot open Process B.
// Setting process access rights HANDLE hToken = NULL; TOKEN_PRIVILEGES tokenPriv; LUID luidDebug; if( FALSE != OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_READ, &hToken )) { if( FALSE != LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &luidDebug )) { tokenPriv.PrivilegeCount = 1; tokenPriv.Privileges[0].Luid = luidDebug; tokenPriv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if( FALSE != AdjustTokenPrivileges( hToken, FALSE, &tokenPriv, 0, NULL, NULL)) { } } }
Could anyone help me in this?I want it to work regardless Process A and Process B UAC level.
Thanks, Renjith V R
Answers
-
On 1/11/2013 8:27 AM, Renjith V Ramachandran wrote:
I am using WIndows 2008 with maximum UAC enabled(Always Notify me…). I am starting Porcess A with Standard user token. Then trying to open Process B (Started with admin token) using process id. I just need the process handle.I have the following code to
open process B. It fails and returns ACCESS_DENIED during this operation.HANDLE hProcess=OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE,pid);
Well, the whole point of UAC is precisely to prevent access from non-admin processes to admin ones. Especially when the former wants to read the memory of the latter.
I tried to adjust token privilege using following code. But AdjustTokenPrivileges() returns True But gives error ERROR_NOT_ALL_ASSIGNED.
If the low-privilege process could just grab any access rights it wants, that would totally defeat the purpose of UAC, wouldn’t it?
Could anyone help me in this?I want it to work regardless Process A and Process B UAC level.
I’m afraid you are sadly out of luck. If what you want were possible, it would be a security vulnerability.
Igor Tandetnik
-
Marked as answer by
Wednesday, January 23, 2013 11:46 AM
-
Marked as answer by
-
There is another way. Use PROCESS_QUERY_LIMITED_INFORMATION for OpenProcess().
Thanks, Renjith V R
-
Marked as answer by
Renjith V Ramachandran
Monday, January 14, 2013 10:27 AM
-
Marked as answer by
Содержание
- Устраняем ошибку 5 при доступе к данным
- Способ 1: Запуск с привилегиями администратора
- Способ 2: Открытие доступа к каталогам
- Способ 3: «Командная строка»
- Способ 4: Устранение проблем с Виндовс
- Заключение
- Вопросы и ответы
В некоторых ситуациях пользователи операционной системы Виндовс 10 могут столкнуться с проблемой, когда попытка открыть файл, папку или программу приводит к появлению ошибки с кодом 5 и текстом «Отказано в доступе». Также она нередко возникает при попытке запуска или перезапуска служб. Далее мы расскажем о причинах появления этого сбоя и предложим методы его устранения.
Устраняем ошибку 5 при доступе к данным
В большинстве случаев источником ошибки являются проблемы с правами на чтение и запись данных в текущей пользовательской «учётке». Также подобное сообщение появляется при сбоях в ОС, повреждении её компонентов или записей реестра.
Способ 1: Запуск с привилегиями администратора
Если открытие исполняемого файла программы, игры либо инсталлятора приложения приводит к появлению рассматриваемой ошибки, следует попробовать запустить его от имени администратора.
- Убедитесь, что у текущей учётной записи нужные права есть. Если это не так, предоставьте или получите их.
Урок: Получение прав администратора на Windows 10
- Перейдите к проблемному файлу. Выделите его, нажмите правую кнопку мыши и выберите в меню пункт «Запуск от имени администратора».
- Появится всплывающее окно с запросом на разрешение, щёлкните в нём «Да».
Далее приложение или инсталлятор должны запуститься нормально.
Способ 2: Открытие доступа к каталогам
Вторая причина проблемы, которую мы сегодня рассматриваем – неполадки с правами доступа к отдельному каталогу или диску. Предоставление нужных прав покажем на примере системного диска.
Внимание! Процедура может нарушить работу компьютера, поэтому рекомендуем создать точку восстановления!
Урок: Точка восстановления в Windows 10
- Откройте «Этот компьютер», найдите в нём системный накопитель и кликните по нему ПКМ, затем выберите в меню пункт «Свойства».
- Откройте вкладку «Безопасность». Нажмите на кнопку «Изменить» под блоком «Группы и пользователи».
Далее кликните «Добавить».
- В следующем окне обратитесь к блоку «Введите имена…». Наберите на клавиатуре слово
Все
, после чего щёлкните «Проверить имена».
Если появилось окошко «Имя не найдено», попробуйте в графе «Введите имя объекта» вписать слово
All
либо имя текущей учётной записи, после чего воспользуйтесь кнопкой «ОК». - Вернувшись к утилите разрешений, убедитесь, что выделена добавленная на предыдущем шаге группа. Далее в разделе «Разрешения для группы…» отметьте все пункты в столбце «Разрешить».
- Далее последовательно щёлкните «Применить» и «ОК», после чего перезагрузите компьютер.
Предоставление прав на чтение и запись системного носителя одновременно устраняет ошибку 5 как для исполняемых файлов, так и для служб, однако данная процедура небезопасна для работоспособности системы.
Способ 3: «Командная строка»
Рассматриваемая проблема может касаться только той или иной службы Виндовс. В этом случае можно воспользоваться средством «Командная строка».
- Откройте «Поиск», в котором начните вводить запрос
командная строка
. Выделите найденное приложение и нажмите на ссылку «Запуск от имени администратора» в правой части окна. - Последовательно введите в интерфейсе следующие команды:
net localgroup Администраторы /add networkservice
net localgroup Администраторы /add localservice
Обратите внимание! Пользователям Windows 10 с английской локализацией системы необходимо вводить Administrators вместо Администраторы!
- Закрывайте окно программы и перезагружайте ПК или ноутбук.
Данный метод безопаснее предыдущего, но и применим только при отказе в доступе для служб.
Способ 4: Устранение проблем с Виндовс
Если применение всех вышеприведённых методов не принесло результата, скорее всего источником проблемы являются неполадки в самой ОС.
- Первым делом проверьте обновления – возможно, в одном из недавно установленных присутствуют баги. Если же, напротив, вы давно не обновляли систему, попробуйте загрузить актуальные апдейты.
Урок: Как установить и как удалить обновления Windows 10
- Проверьте параметры антивируса – возможно, в нём активен строгий режим контроля, который не разрешает манипуляции с данными. Также стоит попробовать временно отключить защитное ПО.
Урок: Как отключить антивирус
Если же вы по каким-то причинам вообще не пользуетесь защитой от вирусов, рекомендуем ознакомиться со статьей по борьбе с ними — возможно, ваш компьютер стал жертвой заражения.
Подробнее: Борьба с компьютерными вирусами
- Дополнительно следует проверить работоспособность системных составляющих в целом и реестра в частности.
Подробнее:
Проверка и восстановление системных файлов в Windows 10
Восстановление реестра в Windows 10
Описанные выше рекомендации должны помочь в устранении проблемы.
Заключение
Мы рассмотрели варианты решения проблемы, при которой в Виндовс 10 появляется ошибка с кодом 5 и текстом «Отказано в доступе». Как видим, возникает она по разным причинам, из-за чего нет универсального метода устранения.
Еще статьи по данной теме:
Помогла ли Вам статья?
|
Authenticator Code |
Thread Tools |
Access Denied (Error 5) when using OpenProcess() |
|
#1 |
synestra n00bie Join Date: Oct 2015
Reputation: 10 |
Access Denied (Error 5) when using OpenProcess() «System.ComponentModel.Win32Exception: Access is denied», this error is appearing while I am attempting to do two things: while attempting this (Code block 1): Code: _class = new Proc(Process.GetProcessesByName("procname")[0]); then in the class Proc whats happening is Code: public Proc(Process _SelectedProcess) { Process = _SelectedProcess; } public Process Process { get { return SelectedProcess; } set { SelectedProcess = value; if (SelectedProcess != null) { Process.EnterDebugMode(); _Reader = new Win32_Memory(value.Handle, value.MainModule.BaseAddress.ToInt32(), value.Id); } } } sometimes this passes without any exception for no apparent reason as far as I see. Note: it never passes in windows 7, I’m using windows 10 and sometimes it happens that the function works but if it does pass, the next time I need to use OpenProcess() outside of the Process class, I almost always get the exception, and if i do, then afterwards it fails executing code block 1 if I try to do so again. this (code block 2) also gets the same access denied error, and sometimes doesnt… Code: if (_Reader.ReadInt(_addr) == 1) _Reader.Write(_addr, 0); public bool Write(int address, long value) { hProc = OpenProcess(ProcessAccessFlags.VMWrite, false, ID); byte[] val = BitConverter.GetBytes(value); bool worked = WriteProcessMemory(hProc, new IntPtr(address), val, (uint)val.LongLength, 0); CloseHandle(hProc); return worked; } the access flags: Code: [Flags] public enum ProcessAccessFlags : uint { All = 0x001F0FFF, Terminate = 0x00000001, CreateThread = 0x00000002, VMOperation = 0x00000008, VMRead = 0x00000010, VMWrite = 0x00000020, DupHandle = 0x00000040, SetInformation = 0x00000200, QueryInformation = 0x00000400, Synchronize = 0x00100000 } the imports: Code: [DllImport("kernel32.dll")] private static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, int unused); also worth noting that sometimes all of this code gets executed without ANY error and will work for as long as I do not reopen this application or if i do not restart the targeted application. this happens only on windows 10 (sometimes it works, sometimes it doesn’t) on windows 7 ive also tested and it never worked, everytime I opened it I always got error code 5 access is denied besides my own program, I’ve also tried cheat engine on this process and it also got access denied, as well as artmoney pro and olydbg — all of them got access denied when using the OpenProcess() function |
synestra is offline |
|
#2 |
|||||||||||
evolution536 Hacked the universe Join Date: Dec 2012 Location: The Netherlands
Reputation: 61216 Recognitions (2)
(3) Points: 99,141, Level: 45 Level up: 68%, 1,859 Points needed Activity: 6.1% Last Achievements |
Code: Process.EnterDebugMode(); Are you sure you need this? To write to an arbitrary user process running on your system, you should not. If you write to a protected process you do. I’d leave it out if I were you, but if you so desire to use it, you need to run your application as Administrator for it to work. As for your OpenProcess line on code block 2, line 4, I am quoting an error on MSDN. WriteProcessMemory also needs operation access, because it calls the memory block protection routine before writing. Quote:
hProcess [in] |
|||||||||||
evolution536 is offline |
|
#3 |
synestra n00bie
Join Date: Oct 2015
Reputation: 10 |
Quote:
Originally Posted by evolution536 Code: Process.EnterDebugMode(); Are you sure you need this? To write to an arbitrary user process running on your system, you should not. If you write to a protected process you do. I’d leave it out if I were you, but if you so desire to use it, you need to run your application as Administrator for it to work. As for your OpenProcess line on code block 2, line 4, I am quoting an error on MSDN. WriteProcessMemory also needs operation access, because it calls the memory block protection routine before writing. Yeah I removed that line, nothing changed. I tried it now by combining Operation and Write, but I still got the same error. Also worth mentioning that this game has GG on it, probably should have said this earlier, my bad. |
synestra is offline |
|
#4 |
|||||||||||
voidptr God-Like Join Date: Jun 2015
Reputation: 3490 Recognitions Points: 8,191, Level: 10 Level up: 54%, 509 Points needed Activity: 0% |
Quote:
Originally Posted by synestra Yeah I removed that line, nothing changed. I tried it now by combining Operation and Write, but I still got the same error. Also worth mentioning that this game has GG on it, probably should have said this earlier, my bad. GameGuard with prevent you from getting on open handle to the game if I recall correctly. You’re likely going to attack it from a different angle. I believe Fyyre has quite a bit of information posted around the web on attacking GG. EDIT: As I suspected it does indeed operate in ring0, https://www.unknowncheats.me/wiki/GameGuard. |
|||||||||||
voidptr is offline |
|
#5 |
synestra n00bie
Join Date: Oct 2015
Reputation: 10 |
Quote:
Originally Posted by voidptr GameGuard with prevent you from getting on open handle to the game if I recall correctly. You’re likely going to attack it from a different angle. I believe Fyyre has quite a bit of information posted around the web on attacking GG. EDIT: As I suspected it does indeed operate in ring0, https://www.unknowncheats.me/wiki/GameGuard. Thanks, I suppose this will be a lot harder than I anticipated. |
synestra is offline |
Similar Threads |
||||
Thread | Thread Starter | Forum | Replies | Last Post |
[Help] DebugActiveProcess fails with «Access denied» | Jabberw0ck | C and C++ | 15 | 23rd December 2013 07:26 AM |
[Help] CreateRemoteThread: access denied (w. debug privileges+PROCESS_ALL_ACCESS) | -=Freekee=- | Programming for Beginners | 5 | 5th March 2012 06:52 PM |
Any ideas what to do if OpenProcess fails? | rain | General Programming and Reversing | 10 | 28th June 2010 02:31 AM |
Saves folder: access denied | DOTHEHOKEYPOKEY | America’s Army Operations 2.x | 15 | 19th November 2005 04:40 AM |
[Help] PB Access Denied | Mr.AIMBOT | Battlefield 1942 | 0 | 10th June 2004 10:21 PM |
Tags |
access, denied, error |
«
Previous Thread
|
Next Thread
»
Forum Jump |
All times are GMT. The time now is 02:56 PM.
Contact Us —
Toggle Dark Theme
Terms of Use Information Privacy Policy Information
Copyright ©2000-2023, Unknowncheats� UKCS #312436
no new posts
This problem happens with users who tries to terminate a process from the Task Manager. Once you select the process and click the End Task button, you will see an error message telling you that the operation could not be completed. Most of the users who faced this issue had problems with running games or other applications. These users couldn’t run the applications either because they were getting the error “Program is already opened” or because they saw multiple instances of the same app in the task manager. This isn’t specific to these cases though, you might see this message while trying to terminate a hung app or an unwanted app. In all of these cases, this Access is denied error will appear once your try to eliminate the process.
The reason behind this issue isn’t clear but the most likely contenders are either a Windows (Windows Update) bug or corrupted application files. Windows updates are known to introduce weird bugs in the Windows so this might be caused by a Windows bug. In this scenario there isn’t a lot that you can do. But, if the problem is with a specific third party application then the issue might be a corrupted file. These cases are usually resolved after a reinstall.
Method 1: Try Command Prompt
The easiest solution for this is to use the command prompt to terminate a process. There are certain commands that can be used to do the same thing i.e. terminate process. Here are the steps for stopping processes
- Press Windows key once
- Type command prompt in the Start Search box
- Right click Command Prompt from the search results and select Run as administrator
- Type taskkill /im process-name /f and press Enter. You can get the process name by right clicking the process you want to kill (from the Task Manager) and selecting Details. This will open the Details tab with your process already selected. Simply look at the name of the process and type it in the process-name.
You can run this command for all types of processes and see if this works for you.
Method 2: Enter Safe Mode and Reinstall
If the problem occurs when you try to terminate a third party application process then try to uninstall and reinstall the application to see if that resolves the issue.
Here are the steps for getting into the Safe Mode and then reinstalling the application
Note: Make sure you have the application installer downloaded on the system before getting into the Safe Mode.
- Hold Windows key and press R
- Type msconfig and press Enter
- Select Boot tab
- Check the option Safe Boot in the Boot options section
- Select the option Minimal under the Safe Boot option
- Click Ok
- Windows will ask you to restart. Click Restart
- Once the system restarts, you will be in the Safe Mode. Uninstall the problematic application. Hold Windows key and press R
- Type appwiz.cpl and press Enter
- Locate the application and select it
- Click Uninstall and follow the on-screen instructions
- Now, reinstall the application by running its installer
- Once the application is installed, you need to turn off the Safe Mode option.
- Hold Windows key and press R
- Type msconfig and press Enter
- Select Boot tab
- Uncheck the option Safe Boot in the Boot options section
- Click Ok
- Windows will ask you to restart. Click Restart
Your computer should start in normal mode. Check if the problem is resolved or not.
Method 3: Use Process Hacker
Process Hacker is a free tool that is designed to monitor system resources, debug software and detect malware. However, we are only concerned with its ability to monitor the running applications. Process Hacker is considered as an alternative of Task Manager and Process Explorer. This means that it can terminate the processes just like Task Manager.
Using Process Hacker to terminate the processes has worked for a lot of users. So, here are the steps for downloading and using the Process Hacker to stop a process
- Click here and click the Installer button to download the Process Hacker
- Once downloaded, install the Process Hacker and run it
- Process Hacker will show you a list of running applications. Simply right click the problematic application and select Terminate
- Click Terminate to confirm
Repeat these steps for all the applications you want to terminate (the ones that Task Manager couldn’t). If the Process Hacker can’t terminate then there isn’t much that you can do here.
Method 4: Process Explorer
Process Explorer is another free tool that can be used to explore the processes running on your system. This tool gives a detailed view and allows the editing of permissions as well. If Process Hacker didn’t work then you try Process Explorer to see if this helps you in terminating the application or not. Follow the steps given below
- Click here and select the link Download Process Explorer. This will download a zip file for you
- You will need a compression program to unzip the contents of the downloaded file. Use Winzip or WinRAR.
- Double click the downloaded zip file
- Double click procexp.exe or procexp64.exe to open the Process Explorer
- Once the Process Explorer starts, it will give you a detailed list of programs running on your system. Locate and double click the problematic application
- Click the Security Tab
- Click Permissions
- Click Advanced
- Select your account from the list
- Click Edit
- Check the options Full Control, Read and Write
- Click show advanced permissions
- Make sure the option Terminate is checked
- Click Ok and click Ok again
- Click Ok for all other Windows
- Now, when you are back at the Process Explorer, right click the problematic program and select Kill Process
This should solve the issue. If you are still having issues then do the following:
- Click on the File option (from Process Explorer) and select Show Details for All Processes.
- Click Yes if it asks for permissions
- Process Explorer will restart now. Once the Process Explorer is restarted, right click the problematic application and select Kill Process. This should solve the issue.
Method 5: Use WMIC
WMIC stands for Windows Management Instrumentation Console. This utility can be used to terminate the process as well. You can use WMIC and its commands to terminate processes from the command prompt. Some users found this to be helpful in getting rid of the problematic application. Here are the steps for using WMIC commands.
- Press Windows key once
- Type command prompt in the Start Search box
- Right click Command Prompt from the search results and select Run as administrator
- Type wmic process where name=’myprocessname.exe’ delete and press Enter. You can get the process name by right clicking the process you want to kill (from the Task Manager) and selecting Details. This will open the Details tab with your process already selected. Simply look at the name of the process and type it in the myprocessname.exe (don’t remove the quotes).
This should resolve the issue for you.
Method 6: Reboot
If nothing else worked then this is your only choice. There are some processes that cannot be terminated especially if you are dealing with the system processes. This isn’t a solution but this is the option you are left with. A simple reboot will usually resolve the issue and you will be able to use the application normal once the restart is done.a
Kevin Arrows
Kevin is a dynamic and self-motivated information technology professional, with a Thorough knowledge of all facets pertaining to network infrastructure design, implementation and administration. Superior record of delivering simultaneous large-scale mission critical projects on time and under budget.