Skip to content

common/wireaddr: validate port range in separate_address_and_port and torport - #9637

Open
bhuvan-somisetty wants to merge 1 commit into
ElementsProject:masterfrom
bhuvan-somisetty:fix-wireaddr-port-truncation
Open

bhuvan-somisetty wants to merge 1 commit into
ElementsProject:masterfrom
bhuvan-somisetty:fix-wireaddr-port-truncation

Conversation

@bhuvan-somisetty

@bhuvan-somisetty bhuvan-somisetty commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Description

In common/wireaddr.c, separate_address_and_port() as well as torport= parsing in autotor: and statictor: parsed port strings with strtol() and assigned the result directly to u16 port fields, causing integer truncation modulo 65536. Consequently:

  • Out-of-range ports > 65535 (such as 127.0.0.1:65537 or autotor:127.0.0.1/torport=65537) were accepted and silently converted to lower ports (e.g. 1).
  • Negative ports such as 127.0.0.1:-1 or torport=-1 were converted to 65535 and accepted.
  • Signed (+9735) and space-padded ports were accepted by strtol.

This PR fixes separate_address_and_port() and torport= parsing in autotor: / statictor: by:

  1. Parsing port strings with str_to_u64() to enforce strict unsigned decimal digits.
  2. Rejecting ports equal to 0 or greater than UINT16_MAX.
  3. Adding unit tests in common/test/run-ip_port_parsing.c and common/test/run-wireaddr.c covering valid boundaries and invalid ports.

Fixes #9636.

Checklist

Before submitting the PR, ensure the following tasks are completed. If an item is not applicable to your PR, please mark it as checked:

  • The changelog has been updated in the relevant commit(s) according to the guidelines.
  • Tests have been added or modified to reflect the changes.
  • Documentation has been reviewed and updated as needed.
  • Related issues have been listed and linked, including any that this PR closes.
  • Important All PRs must consider how to reverse any persistent changes for tools/lightning-downgrade

Signed-off-by: bhuvan-somisetty somisettybhuvan5@gmail.com

@Andezion Andezion left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice pr, but the same bug still exists in torport= parsing. In common/wireaddr.c at line 675 and common/wireaddr.c at line 703, strtol() is also assigned straight into u16 torservice.port. The port <= 0 check on an unsigned value only catches 0, so autotor:...:/torport=65537 becomes port 1 and torport=-1 becomes 65535

just leaving this for visibility

Comment thread common/wireaddr.c Outdated
u64 p;
if (!str_to_u64(portcolon + 1, strlen(portcolon + 1), &p))
return false;
if (p == 0 || p > 65535)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use UINT16_MAX instead of 65535

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated to UINT16_MAX.

@bhuvan-somisetty
bhuvan-somisetty force-pushed the fix-wireaddr-port-truncation branch from 324ecb6 to 9dab200 Compare October 22, 2026 12:32
@bhuvan-somisetty bhuvan-somisetty changed the title common/wireaddr: validate port range in separate_address_and_port common/wireaddr: validate port range in separate_address_and_port and torport Oct 22, 2026
@bhuvan-somisetty

Copy link
Copy Markdown
Contributor Author

Good catch, thanks! Updated to UINT16_MAX and added the same range checks and unit tests for torport= in autotor and statictor.

sangbida
sangbida previously approved these changes Nov 23, 2026
@sangbida
sangbida force-pushed the fix-wireaddr-port-truncation branch from 9dab200 to d540d32 Compare November 23, 2026 08:21
@sangbida
sangbida enabled auto-merge (rebase) November 23, 2026 08:21
@daywalker90
daywalker90 force-pushed the fix-wireaddr-port-truncation branch from d540d32 to 51db169 Compare November 26, 2026 14:34
@daywalker90

Copy link
Copy Markdown
Collaborator

This change makes tests/test_connection.py::test_websocket fail:

node_factory = <pyln.testing.utils.NodeFactory object at 0x7f6334912dd0>

    def test_websocket(node_factory):
        ws_port = node_factory.get_unused_port()
        port = node_factory.get_unused_port()
>       l1, l2 = node_factory.line_graph(2,
                                         opts=[{'addr': ':' + str(port),
                                                'bind-addr': 'ws:127.0.0.1: ' + str(ws_port),
                                                'dev-allow-localhost': None},
                                               {'dev-allow-localhost': None}],
                                         wait_for_announce=True)

tests/test_connection.py:4329: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
contrib/pyln-testing/pyln/testing/utils.py:2102: in line_graph
    nodes = self.get_nodes(num_nodes, opts=opts)
contrib/pyln-testing/pyln/testing/utils.py:1972: in get_nodes
    return [j.result() for j in jobs]
contrib/pyln-testing/pyln/testing/utils.py:1972: in <listcomp>
    return [j.result() for j in jobs]
/opt/hostedtoolcache/Python/3.10.22/x64/lib/python3.10/concurrent/futures/_base.py:458: in result
    return self.__get_result()
/opt/hostedtoolcache/Python/3.10.22/x64/lib/python3.10/concurrent/futures/_base.py:403: in __get_result
    raise self._exception
/opt/hostedtoolcache/Python/3.10.22/x64/lib/python3.10/concurrent/futures/thread.py:58: in run
    result = self.fn(*self.args, **self.kwargs)
contrib/pyln-testing/pyln/testing/utils.py:2034: in get_node
    node.start(wait_for_bitcoind_sync)
contrib/pyln-testing/pyln/testing/utils.py:1349: in start
    self.daemon.start(stderr_redir=stderr_redir)
contrib/pyln-testing/pyln/testing/utils.py:977: in start
    self.wait_for_log("Server started with public key")
contrib/pyln-testing/pyln/testing/utils.py:553: in wait_for_log
    return self.wait_for_logs([regex], timeout)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <pyln.testing.utils.LightningD object at 0x7f6334de82e0>
regexs = ['Server started with public key'], timeout = 180

    def wait_for_logs(self, regexs, timeout=TIMEOUT):
        """Look for `regexs` in the logs.
    
        The logs contain tailed stdout of the process. We look for each regex
        in `regexs`, starting from `logsearch_start` which normally is the
        position of the last found entry of a previous wait-for logs call.
        The ordering inside `regexs` doesn't matter.
    
        We fail if the timeout is exceeded or if the underlying process
        exits before all the `regexs` were found.
    
        If timeout is None, no time-out is applied.
        """
        logging.debug("Waiting for {} in the logs".format(regexs))
        exs = [re.compile(r) for r in regexs]
        start_time = time.time()
        while True:
            if self.logsearch_start >= len(self.logs):
                if not self.logs_catchup():
                    time.sleep(0.25)
    
                if timeout is not None and time.time() > start_time + timeout:
                    print("Time-out: can't find {} in logs".format(exs))
                    for r in exs:
                        if self.is_in_log(r):
                            print("({} was previously in logs!)".format(r))
>                   raise TimeoutError('Unable to find "{}" in logs.'.format(exs))
E                   TimeoutError: Unable to find "[re.compile('Server started with public key')]" in logs.

contrib/pyln-testing/pyln/testing/utils.py:534: TimeoutError

… torport

`separate_address_and_port()` and `torport=` parsing in `autotor:` and
`statictor:` used `strtol()` and assigned the result directly to `u16`
port fields. This caused integer truncation modulo 65536, silently
accepting out-of-range ports (>65535), negative ports, and signed ports.

Use `str_to_u64()` to parse strict unsigned decimal digits and reject
ports equal to 0 or greater than `UINT16_MAX`.

Changelog-Fixed: common/wireaddr: reject out-of-range (>65535) and negative ports in separate_address_and_port and torport
Fixes: ElementsProject#9636
Signed-off-by: bhuvan-somisetty <somisettybhuvan5@gmail.com>
auto-merge was automatically disabled November 28, 2026 20:15

Head branch was pushed to by a user without write access

@bhuvan-somisetty
bhuvan-somisetty force-pushed the fix-wireaddr-port-truncation branch from 51db169 to 5842d47 Compare November 28, 2026 20:15
@bhuvan-somisetty

Copy link
Copy Markdown
Contributor Author

Good catch, thank you! Updated separate_address_and_port to allow leading whitespace after the colon so formats like ws:127.0.0.1: <port> work as expected.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

common/wireaddr: separate_address_and_port truncates out-of-range port numbers and accepts negative/signed ports

4 participants