Skip to content

Commit

Permalink
Delay UID change after loop start
Browse files Browse the repository at this point in the history
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
  • Loading branch information
nim-odoo committed Feb 9, 2023
1 parent 83168cd commit d4c0962
Showing 1 changed file with 18 additions and 16 deletions.
34 changes: 18 additions & 16 deletions aiosmtpd/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,22 +217,6 @@ def parseargs(args: Optional[Sequence[str]] = None) -> Tuple[ArgumentParser, Nam
def main(args: Optional[Sequence[str]] = None) -> None:
parser, args = parseargs(args=args)

if args.setuid: # pragma: on-win32
if pwd is None:
print(
'Cannot import module "pwd"; try running with -n option.',
file=sys.stderr,
)
sys.exit(1)
nobody = pwd.getpwnam("nobody").pw_uid
try:
os.setuid(nobody)
except PermissionError:
print(
'Cannot setuid "nobody"; try running with -n option.', file=sys.stderr
)
sys.exit(1)

if args.tlscert and args.tlskey:
tls_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
tls_context.check_hostname = False
Expand Down Expand Up @@ -279,6 +263,24 @@ def main(args: Optional[Sequence[str]] = None) -> None:
log.debug(f"server_loop = {server_loop}")
log.info("Server is listening on %s:%s", args.host, args.port)

# Change the UID after opening the port. This allows listening on port < 1024 without any
# system tweak.
if args.setuid: # pragma: on-win32
if pwd is None:
print(
'Cannot import module "pwd"; try running with -n option.',
file=sys.stderr,
)
sys.exit(1)
nobody = pwd.getpwnam("nobody").pw_uid
try:
os.setuid(nobody)
except PermissionError:
print(
'Cannot setuid "nobody"; try running with -n option.', file=sys.stderr
)
sys.exit(1)

# Signal handlers are only supported on *nix, so just ignore the failure
# to set this on Windows.
with suppress(NotImplementedError):
Expand Down

0 comments on commit d4c0962

Please sign in to comment.