How to share memory between services and user processes?

一个人想着一个人 提交于 2019-11-29 00:03:00
Michael

The simplest way would be to have your service create the shared memory and specify a DACL in CreateFileMapping that grants regular users read access to the shared memory.

Normal users don't have the create global privilege, but services can have this privilege. If you must have your users create the shared memory and then have the service probe it, you could have an IPC scheme where your user code sends a message to the service containing the file mapping handle, and the service would then call DuplicateHandle to get a reference to it. This would require your service to run with the debug privilege.

The simplest way to create a DACL is to use ConvertStringSecurityDescriptorToSecurityDescriptor, which takes a string in a format called SDDL specifying the ACL.

Writing Secure Code contains an excellent chapter on creating DACL's with SDDL.

// Error handling removed for brevity
SECURITY_ATTRIBUTES attributes;
ZeroMemory(&attributes, sizeof(attributes));
attributes.nLength = sizeof(attributes);
ConvertStringSecurityDescriptorToSecurityDescriptor(
         L"D:P(A;OICI;GA;;;SY)(A;OICI;GA;;;BA)(A;OICI;GR;;;IU)",
         SDDL_REVISION_1,
         &attributes.lpSecurityDescriptor,
         NULL);

CreateFileMapping(INVALID_HANDLE_VALUE, &attributes,
              PAGE_READWRITE, sizeHigh, sizeLow, L"Global\\MyObject");

LocalFree(attributes.lpSecurityDescriptor);

"D:P(A;OICI;GA;;;SY)(A;OICI;GA;;;BA)(A;OICI;GR;;;IU)" specifies the DACL. D:P means this is a DACL (instead of a SACL . . . you'd rarely use SACL's) followed by several ACE strings which control who gets access. Each one is A (allow) and allows for object and contains inheritance (OICI). The first to grant all access (GA - grant all) to System (SY) and Administrators (BA, built-in administratos). The last grants read (GR) to interactive users (IU), which are users actually logged on to a session.

Once this is done, normal users should be able to call OpenFileMapping to get a handle to the shared mapping, and be able to map it into their process. Since normal users have limited rights on the object, they'll have to be sure to open it and map it for read-access only.

If users need write-acccess, you'd replace GR with GWGR. Note that this isn't secure - a limited user would then be able to modify the shared memory while your service is reading and trying to parse information, resulting in a crash of your service.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!