«Попытка выполнить несанкционированную операцию» при вызове NamedPipeServerStream.SetAccessControl - PullRequest
0 голосов
/ 06 июня 2018

Я пытаюсь использовать PipeSecurity для обеспечения NamedPipeServerStream.Когда я звоню this.pipeServer.SetAccessControl(pipeSecurity) во фрагменте ниже, я получаю следующее исключение:

Attempted to perform an unauthorized operation.
    at System.Security.AccessControl.Win32.SetSecurityInfo(ResourceType type, String name, SafeHandle handle, SecurityInfos securityInformation, SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl, GenericAcl dacl)
    at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
    at System.Security.AccessControl.NativeObjectSecurity.Persist(SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
    at System.IO.Pipes.PipeSecurity.Persist(SafeHandle handle)

код:

this.pipeServer =
    new NamedPipeServerStream(
        pipeName,
        PipeDirection.InOut,
        1,
        PipeTransmissionMode.Byte,
        PipeOptions.Asynchronous);

PipeSecurity pipeSecurity = new PipeSecurity();

WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);

if (principal.IsInRole(WindowsBuiltInRole.Administrator))
{
    // Allow the Administrators group full access to the pipe.
    pipeSecurity.AddAccessRule(new PipeAccessRule(
        new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Translate(typeof(NTAccount)),
        PipeAccessRights.FullControl, AccessControlType.Allow));
} else {
    // Allow current user read and write access to the pipe.
    pipeSecurity.AddAccessRule(new PipeAccessRule(
        WindowsIdentity.GetCurrent().User,
        PipeAccessRights.ReadWrite, AccessControlType.Allow));
}

this.pipeServer.SetAccessControl(pipeSecurity);

Есть идеи, что я делаю неправильно?

Это происходит в .NET Framework (нацеливание на net451) и .NET Standard 1.6 с использованием пакета nuget System.IO.AccessControl:

https://www.nuget.org/packages/System.IO.Pipes.AccessControl/

Редактировать:

Мне удалось использовать #ifdef для использования следующего конструктора , который работал для .NET Framework:

public NamedPipeServerStream (stringpipeName, направление System.IO.Pipes.Pipe, int maxNumberOfServerInstances, System.IO.Pipes.PipeTransmissionMode параметр передачиMode, параметры System.IO.Pipes.PipeOptions, int inBufferSize, int outBufferSize, System.IO.Pipes.PipeSecurity pipeSecurity)

Однако этот конструктор не существует в .NET Standard.Я пытался использовать эту функцию , которая была добавлена ​​в .NET Core:

PipesAclExtensions.SetAccessControl(PipeStream, PipeSecurity)

Но это выдает то же исключение, что и раньше.

Я создал суть, чтобы показать это .

1 Ответ

0 голосов
/ 27 февраля 2019

У меня просто была та же проблема, и я попытался ее найти.

TL; DR

Текущее состояние (февраль-2019) печально, но факт: он просто не работает с классами, которыеприведено в сегодняшнем стандарте NET.

Ссылки на билеты

Также интересно в этом контекстемеханизм, связанный с * nix

Возможное решение

Можно по-прежнему использовать вызовы нативного API для настройки безопасности по желанию, но это не для слабонервных.В основном необходимо реализовать эти шаги:


PS: По крайней мере, теперь мы можем найти его в коде, где он ударяет по стене.Только представьте, что у вас была эта проблема 20 лет назад ...

...