Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4558bad

Browse files
committed
Issue #12856: Ensure child processes do not inherit the parent's random seed for filename generation in the tempfile module.
Patch by Brian Harring.
1 parent fd9ebd4 commit 4558bad

3 files changed

Lines changed: 43 additions & 2 deletions

File tree

Lib/tempfile.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,8 +112,13 @@ class _RandomNameSequence:
112112

113113
characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
114114

115-
def __init__(self):
116-
self.rng = _Random()
115+
@property
116+
def rng(self):
117+
cur_pid = _os.getpid()
118+
if cur_pid != getattr(self, '_rng_pid', None):
119+
self._rng = _Random()
120+
self._rng_pid = cur_pid
121+
return self._rng
117122

118123
def __iter__(self):
119124
return self

Lib/test/test_tempfile.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# tempfile.py unit tests.
22
import tempfile
33
import os
4+
import signal
45
import sys
56
import re
67
import warnings
@@ -135,6 +136,37 @@ def supports_iter(self):
135136
except:
136137
self.failOnException("iteration")
137138

139+
@unittest.skipUnless(hasattr(os, 'fork'),
140+
"os.fork is required for this test")
141+
def test_process_awareness(self):
142+
# ensure that the random source differs between
143+
# child and parent.
144+
read_fd, write_fd = os.pipe()
145+
pid = None
146+
try:
147+
pid = os.fork()
148+
if not pid:
149+
os.close(read_fd)
150+
os.write(write_fd, next(self.r).encode("ascii"))
151+
os.close(write_fd)
152+
# bypass the normal exit handlers- leave those to
153+
# the parent.
154+
os._exit(0)
155+
parent_value = next(self.r)
156+
child_value = os.read(read_fd, len(parent_value)).decode("ascii")
157+
finally:
158+
if pid:
159+
# best effort to ensure the process can't bleed out
160+
# via any bugs above
161+
try:
162+
os.kill(pid, signal.SIGKILL)
163+
except EnvironmentError:
164+
pass
165+
os.close(read_fd)
166+
os.close(write_fd)
167+
self.assertNotEqual(child_value, parent_value)
168+
169+
138170
test_classes.append(test__RandomNameSequence)
139171

140172

Misc/NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,10 @@ Core and Builtins
8383
Library
8484
-------
8585

86+
- Issue #12856: Ensure child processes do not inherit the parent's random
87+
seed for filename generation in the tempfile module. Patch by Brian
88+
Harring.
89+
8690
- Issue #13458: Fix a memory leak in the ssl module when decoding a
8791
certificate with a subjectAltName. Patch by Robert Xiao.
8892

0 commit comments

Comments
 (0)