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 aio-libs#304
  • Loading branch information
nim-odoo committed Mar 7, 2023
1 parent 83168cd commit be6e707
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
1 change: 1 addition & 0 deletions aiosmtpd/docs/NEWS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Fixed/Improved
--------------
* All Controllers now have more rationale design, as they are now composited from a Base + a Mixin
* A whole bunch of annotations
* Delay UID change after loop start (Closes #304)


1.4.4.post2 (2023-01-19)
Expand Down
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 be6e707

Please sign in to comment.