Close previously opened ports on port config change

When the charm config option `port` is changed,
the previously opened port is not closed.

This leads to leaks of open ports (potential security
issue), and long ports field on status after tests:

Test:

    $ juju config ceph-radosgw port=1111
    $ juju config ceph-radosgw port=2222
    $ juju config ceph-radosgw port=3333

    $ juju status ceph-radosgw
    ...
    Unit Workload Agent Machine Public address Ports Message
    ceph-radosgw/1* blocked idle 3 10.5.2.210
    80/tcp,1111/tcp,2222/tcp,3333/tcp Missing relations: mon
    ...

    $ juju run --unit ceph-radosgw/1 'opened-ports'
    80/tcp
    1111/tcp
    2222/tcp
    3333/tcp

Patched:

    $ juju run --unit ceph-radosgw/1 'opened-ports'
    80/tcp
    1111/tcp
    1234/tcp
    2222/tcp
    3333/tcp
    33331/tcp
    33332/tcp
    33334/tcp

    $ juju config ceph-radosgw port=33335

    $ juju run --unit ceph-radosgw/1 'opened-ports'
    33335/tcp

    $ juju status ceph-radosgw
    ...
    Unit             Workload  Agent  Machine  Public address  Ports
    Message
    ceph-radosgw/1*  blocked   idle   3        10.5.2.210      33335/tcp
    Missing relations: mon

    @ unit log
    2021-03-24 13:20:51 INFO juju-log Closed port 80 in favor of port 33335
    2021-03-24 13:20:51 INFO juju-log Closed port 1111 in favor of port 33335
    2021-03-24 13:20:51 INFO juju-log Closed port 1234 in favor of port 33335
    2021-03-24 13:20:51 INFO juju-log Closed port 2222 in favor of port 33335
    2021-03-24 13:20:52 INFO juju-log Closed port 3333 in favor of port 33335
    2021-03-24 13:20:52 INFO juju-log Closed port 33331 in favor of port 33335
    2021-03-24 13:20:52 INFO juju-log Closed port 33332 in favor of port 33335
    2021-03-24 13:20:52 INFO juju-log Closed port 33334 in favor of port 33335

Signed-off-by: Mauricio Faria de Oliveira <mfo@canonical.com>
Closes-bug: #1921131
Change-Id: I5ac4b66137faffee82ae0f1e13718f21274f1f56
This commit is contained in:
Mauricio Faria de Oliveira 2021-03-24 10:26:49 -03:00
parent 5ab45ee5d5
commit c97fced794
2 changed files with 11 additions and 1 deletions

View File

@ -32,6 +32,8 @@ from charmhelpers.core.hookenv import (
related_units,
config,
open_port,
opened_ports,
close_port,
relation_set,
log,
DEBUG,
@ -247,7 +249,14 @@ def config_changed():
update_nrpe_config()
open_port(port=listen_port())
port = listen_port()
open_port(port)
for opened_port in opened_ports():
opened_port_number = opened_port.split('/')[0]
if opened_port_number != port:
close_port(opened_port_number)
log('Closed port %s in favor of port %s' %
(opened_port_number, port))
_config_changed()

View File

@ -40,6 +40,7 @@ TO_PATCH = [
'listen_port',
'log',
'open_port',
'opened_ports',
'os',
'relation_ids',
'relation_set',