Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

security: check if shared memory belongs to current user and is only … #43

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions shared_memory_dict/dict.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
import os
import sys
import warnings
from contextlib import contextmanager
Expand Down Expand Up @@ -157,13 +158,32 @@ def _get_or_create_memory_block(
self, name: str, size: int
) -> SharedMemory:
try:
self.check_security(name)
return SharedMemory(name=name)
except FileNotFoundError:
shm = SharedMemory(name=name, create=True, size=size)
data = self._serializer.dumps({})
shm.buf[: len(data)] = data
return shm

def check_security(self, name: str) -> None:
"""Check if shared memory belongs to and is only read+writeable
for the current user"""
if os.name == 'nt':
return

if '/' in name:
raise TypeError('Name must not contain "/".')

shm_file = os.path.join('/dev/shm', name)
stat = os.stat(shm_file)
if (
stat.st_uid != os.getuid()
or stat.st_gid != os.getgid()
or stat.st_mode != 0o100600
):
os.unlink(shm_file)

def _save_memory(self, db: Dict[str, Any]) -> None:
data = self._serializer.dumps(db)
try:
Expand Down