Skip to content

Commit

Permalink
Add logging for hostname canonicalization feature
Browse files Browse the repository at this point in the history
  • Loading branch information
ronf committed Dec 1, 2024
1 parent 743966d commit 6ecb91e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
25 changes: 22 additions & 3 deletions asyncssh/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,18 +281,27 @@ async def _canonicalize_host(loop: asyncio.AbstractEventLoop,

host = options.host

if not options.canonicalize_hostname or not options.canonical_domains or \
host.count('.') > options.canonicalize_max_dots:
if not options.canonicalize_hostname or not options.canonical_domains:
logger.info('Host canonicalization disabled')
return None

if host.count('.') > options.canonicalize_max_dots:
logger.info('Host canonicalization skipped due to max dots')
return None

try:
ipaddress.ip_address(host)
except ValueError:
pass
else:
logger.info('Hostname canonicalization skipped on IP address')
return None

logger.debug1('Beginning hostname canonicalization')

for domain in options.canonical_domains:
logger.debug1(' Checking domain %s', domain)

canon_host = f'{host}.{domain}'

try:
Expand All @@ -303,18 +312,28 @@ async def _canonicalize_host(loop: asyncio.AbstractEventLoop,

cname = addrinfo[0][3]

if cname:
if cname and cname != canon_host:
logger.debug1(' Checking CNAME rules for hostname %s '
'with CNAME %s', canon_host, cname)

for patterns in options.canonicalize_permitted_cnames:
host_pat, cname_pat = map(WildcardPatternList, patterns)

if host_pat.matches(canon_host) and cname_pat.matches(cname):
logger.info('Hostname canonicalization to CNAME '
'applied: %s -> %s', options.host, cname)
return cname

logger.info('Hostname canonicalization applied: %s -> %s',
options.host, canon_host)

return canon_host

if not options.canonicalize_fallback_local:
logger.info('Hostname canonicalization failed (fallback disabled)')
raise OSError(f'Unable to canonicalize hostname "{host}"')

logger.info('Hostname canonicalization failed, using local resolver')
return None


Expand Down
10 changes: 10 additions & 0 deletions tests/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -2693,6 +2693,16 @@ async def test_canonicalize(self):
canonical_domains=['test']) as conn:
self.assertEqual(conn.get_extra_info('host'), 'testhost.test')

@asynctest
async def test_canonicalize_max_dots(self):
"""Test hostname canonicalization exceeding max_dots"""

async with self.connect('testhost.test', known_hosts=None,
canonicalize_hostname=True,
canonicalize_max_dots=0,
canonical_domains=['test']) as conn:
self.assertEqual(conn.get_extra_info('host'), 'testhost.test')

@asynctest
async def test_canonicalize_ip_address(self):
"""Test hostname canonicalization with IP address"""
Expand Down

0 comments on commit 6ecb91e

Please sign in to comment.