Repository navigation
Add iptables helpers for future drivers #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| # Copyright (C) 2026 Vates SAS | ||
| # | ||
| # This program is free software: you can redistribute it and/or modify | ||
| # it under the terms of the GNU General Public License as published by | ||
| # the Free Software Foundation, either version 3 of the License, or | ||
| # (at your option) any later version. | ||
| # This program is distributed in the hope that it will be useful, | ||
| # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
|
Millefeuille42 marked this conversation as resolved.
|
||
| # GNU General Public License for more details. | ||
| # | ||
| # You should have received a copy of the GNU General Public License | ||
| # along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
|
Millefeuille42 marked this conversation as resolved.
|
||
|
|
||
| from xcp_storage.typing import Final | ||
|
|
||
| # ============================================================================== | ||
| # Attributes that depend on the execution environment. | ||
| # Its primary purpose is to decouple the storage logic from the underlying | ||
| # host's specificities (OS, firewall rules, ...). | ||
| # ============================================================================== | ||
|
|
||
| DEFAULT_FIREWALL_INPUT_CHAIN: Final = "xapi-INPUT" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| # Copyright (C) 2026 Vates SAS | ||
| # | ||
| # This program is free software: you can redistribute it and/or modify | ||
| # it under the terms of the GNU General Public License as published by | ||
| # the Free Software Foundation, either version 3 of the License, or | ||
| # (at your option) any later version. | ||
| # This program is distributed in the hope that it will be useful, | ||
| # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| # GNU General Public License for more details. | ||
| # | ||
| # You should have received a copy of the GNU General Public License | ||
| # along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
|
|
||
| import logging | ||
| import logging.handlers | ||
| import sys | ||
| from types import TracebackType | ||
|
|
||
| from xcp_storage.typing import ( | ||
| Final, | ||
| List, | ||
| Optional, | ||
| Type, | ||
| ) | ||
|
Millefeuille42 marked this conversation as resolved.
|
||
|
|
||
| # ============================================================================== | ||
|
|
||
| _LOG_LEVEL: Final = logging.DEBUG | ||
|
|
||
| _LOG_TO_STDERR: Final = True | ||
| _LOG_TO_JOURNAL: Final = False | ||
|
|
||
| # `LOG_LOCAL2` is mapped to "/var/log/SMlog". | ||
| _LOG_SYSLOG_FACILITY: Final = logging.handlers.SysLogHandler.LOG_LOCAL2 | ||
|
|
||
| _DEFAULT_LOGGER_NAME: Final = "core" | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| def _configure_logger() -> None: | ||
| _LOGGER.setLevel(_LOG_LEVEL) | ||
|
|
||
| handlers: List[logging.Handler] = [] | ||
|
|
||
| if _LOG_TO_JOURNAL: | ||
| handlers.append(logging.handlers.SysLogHandler( | ||
| address="/dev/log", | ||
| facility=_LOG_SYSLOG_FACILITY | ||
| )) | ||
|
|
||
| if _LOG_TO_STDERR: | ||
| handlers.append(logging.StreamHandler(sys.stderr)) | ||
|
|
||
| formatter = logging.Formatter("XCP-storage: [%(process)d] - %(name)s - %(levelname)s - %(message)s") | ||
| for handler in handlers: | ||
| handler.setLevel(_LOG_LEVEL) | ||
| handler.setFormatter(formatter) | ||
| _LOGGER.addHandler(handler) | ||
|
|
||
| def _excepthook( | ||
| exception_type: Type[BaseException], | ||
| exception_value: BaseException, | ||
| exception_traceback: Optional[TracebackType] | ||
| ) -> None: | ||
| if not issubclass(exception_type, KeyboardInterrupt): | ||
| _LOGGER.error("Unhandled exception.", exc_info=(exception_type, exception_value, exception_traceback)) | ||
| sys.__excepthook__(exception_type, exception_value, exception_traceback) | ||
| sys.excepthook = _excepthook | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| _LOGGER: Final = logging.getLogger() | ||
| _configure_logger() | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| def get_logger(name: Optional[str] = None) -> logging.Logger: | ||
| return logging.getLogger(name or _DEFAULT_LOGGER_NAME) | ||
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| # Copyright (C) 2026 Vates SAS | ||
| # | ||
| # This program is free software: you can redistribute it and/or modify | ||
| # it under the terms of the GNU General Public License as published by | ||
| # the Free Software Foundation, either version 3 of the License, or | ||
| # (at your option) any later version. | ||
| # This program is distributed in the hope that it will be useful, | ||
| # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| # GNU General Public License for more details. | ||
| # | ||
| # You should have received a copy of the GNU General Public License | ||
| # along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
|
|
||
| from xcp_storage.config.platform import DEFAULT_FIREWALL_INPUT_CHAIN | ||
| from xcp_storage.utils.process import CommandError, run_command | ||
|
|
||
| from xcp_storage.typing import ( | ||
| Final, | ||
| List, | ||
| Optional, | ||
| Tuple, | ||
| ) | ||
|
|
||
| # ============================================================================== | ||
|
|
||
| _MAIN_FIREWALL_INPUT_CHAIN: Final = "INPUT" | ||
|
|
||
| _EXEC_PATH_IPTABLES: Final = "/usr/sbin/iptables" | ||
| _EXEC_PATH_SERVICE: Final = "/usr/sbin/service" | ||
|
|
||
| _PROTOCOL_TCP: Final = "tcp" | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| class IptablesError(Exception): | ||
| def __init__(self, message: str, code: Optional[int] = None) -> None: | ||
| super().__init__(message) | ||
| self.code = code | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| def _save_iptables_changes() -> None: | ||
| try: | ||
| run_command([_EXEC_PATH_SERVICE, "iptables", "save"], expected_ret_code=0) | ||
| except CommandError as e: | ||
| raise IptablesError(f"Failed to save iptables changes: `{e.reason}`.", e.code) from None | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| def has_iptables_rule(rule: List[str]) -> bool: | ||
| try: | ||
| _stdout, _stderr, ret_code = run_command([_EXEC_PATH_IPTABLES, "-C"] + rule, simple=False) | ||
| return not ret_code | ||
| except CommandError as e: | ||
| raise IptablesError(e.reason, e.code) from None | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| def _update_iptables_ports(protocol: str, str_ports: str, *, open_ports: bool, stateful: bool, chain: str) -> None: | ||
| # 1. Check if the rule is present. | ||
| rule = [chain, "-p", protocol] | ||
| if stateful: | ||
| rule += ["-m", "conntrack", "--ctstate", "NEW", "-m", protocol] | ||
| rule += ["--dport", str_ports, "-j", "ACCEPT"] | ||
|
|
||
| if open_ports == has_iptables_rule(rule): | ||
| return | ||
|
|
||
| # 2. Open or close. | ||
| if open_ports: | ||
| try: | ||
| _stdout, _stderr, ret_code = run_command([_EXEC_PATH_IPTABLES, "-N", chain], simple=False) | ||
| if not ret_code: | ||
| # Create chain if necessary. | ||
| run_command([_EXEC_PATH_IPTABLES, "-A", chain, "-j", "RETURN"], expected_ret_code=0) | ||
| run_command([_EXEC_PATH_IPTABLES, "-I", _MAIN_FIREWALL_INPUT_CHAIN, "-j", chain], expected_ret_code=0) | ||
| # Create rule. | ||
| run_command([_EXEC_PATH_IPTABLES, "-I"] + rule, expected_ret_code=0) | ||
| except CommandError as e: | ||
| raise IptablesError( | ||
| f"Failed to open {protocol.upper()} port(s): `{e.reason}`.", e.code | ||
| ) from None | ||
| else: | ||
| try: | ||
| run_command([_EXEC_PATH_IPTABLES, "-D"] + rule, expected_ret_code=0) | ||
| except CommandError as e: | ||
| raise IptablesError( | ||
| f"Failed to close {protocol.upper()} port(s): `{e.reason}`.", e.code | ||
| ) from None | ||
|
|
||
| # 3. Save. | ||
| _save_iptables_changes() | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| # Open/close TCP port using stateless or stateful rule. | ||
| # | ||
| # /!\ When opening or closing TCP ports using stateful rules, be aware of the Linux `conntrack` mechanism: | ||
| # it maintains a state database of all network connections (TCP, UDP, ...) passing through a machine. | ||
| # This is important for packet filtering, but there is a limitation: | ||
| # The kernel sets a maximum limit `nf_conntrack_max` based on available RAM. | ||
| # If this limit is reached, the system will log: | ||
| # `nf_conntrack: table full, dropping packets` | ||
| # and and start rejecting incoming/outgoing traffic... | ||
| # | ||
| # Even after a connection is closed, the kernel retains the entry in the table for a long period, | ||
| # 120 seconds for TCP. | ||
| # | ||
| # So it's important to avoid `conntrack` for specific case like DRBD protocol. | ||
| # For it, that's important to allow packets to pass even when the connection tracking table | ||
| # ran full temporarily because short-lived connections are the primary cause of table exhaustion | ||
| # AND because we can have this scenario with DRBD. | ||
|
|
||
| def update_iptables_tcp_port( | ||
| port: int, | ||
| *, | ||
| open_port: bool, | ||
| stateful: bool = True, | ||
| chain: str = DEFAULT_FIREWALL_INPUT_CHAIN | ||
| ) -> None: | ||
| _update_iptables_ports( | ||
| _PROTOCOL_TCP, | ||
| str(port), | ||
| open_ports=open_port, | ||
| stateful=stateful, | ||
| chain=chain | ||
| ) | ||
|
|
||
| def update_iptables_tcp_port_range( | ||
| ports: Tuple[int, int], | ||
| *, | ||
| open_ports: bool, | ||
| stateful: bool = True, | ||
| chain: str = DEFAULT_FIREWALL_INPUT_CHAIN | ||
| ) -> None: | ||
| _update_iptables_ports( | ||
| _PROTOCOL_TCP, | ||
| f"{ports[0]}:{ports[1]}", | ||
| open_ports=open_ports, | ||
| stateful=stateful, | ||
| chain=chain | ||
| ) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.