Skip to content

Commit d4c0962

Browse files
committed
Delay UID change after loop start
Listening to a port < 1024 without `--nosetuid` leads to a permission error. The UID change is done too early: we should first open the port, then change the UID. Fixes #304
1 parent 83168cd commit d4c0962

File tree

1 file changed

+18
-16
lines changed

1 file changed

+18
-16
lines changed

aiosmtpd/main.py

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -217,22 +217,6 @@ def parseargs(args: Optional[Sequence[str]] = None) -> Tuple[ArgumentParser, Nam
217217
def main(args: Optional[Sequence[str]] = None) -> None:
218218
parser, args = parseargs(args=args)
219219

220-
if args.setuid: # pragma: on-win32
221-
if pwd is None:
222-
print(
223-
'Cannot import module "pwd"; try running with -n option.',
224-
file=sys.stderr,
225-
)
226-
sys.exit(1)
227-
nobody = pwd.getpwnam("nobody").pw_uid
228-
try:
229-
os.setuid(nobody)
230-
except PermissionError:
231-
print(
232-
'Cannot setuid "nobody"; try running with -n option.', file=sys.stderr
233-
)
234-
sys.exit(1)
235-
236220
if args.tlscert and args.tlskey:
237221
tls_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
238222
tls_context.check_hostname = False
@@ -279,6 +263,24 @@ def main(args: Optional[Sequence[str]] = None) -> None:
279263
log.debug(f"server_loop = {server_loop}")
280264
log.info("Server is listening on %s:%s", args.host, args.port)
281265

266+
# Change the UID after opening the port. This allows listening on port < 1024 without any
267+
# system tweak.
268+
if args.setuid: # pragma: on-win32
269+
if pwd is None:
270+
print(
271+
'Cannot import module "pwd"; try running with -n option.',
272+
file=sys.stderr,
273+
)
274+
sys.exit(1)
275+
nobody = pwd.getpwnam("nobody").pw_uid
276+
try:
277+
os.setuid(nobody)
278+
except PermissionError:
279+
print(
280+
'Cannot setuid "nobody"; try running with -n option.', file=sys.stderr
281+
)
282+
sys.exit(1)
283+
282284
# Signal handlers are only supported on *nix, so just ignore the failure
283285
# to set this on Windows.
284286
with suppress(NotImplementedError):

0 commit comments

Comments
 (0)