| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
# Copyright: (c) 2019, Sebastiaan Mannem (@sebasmannem) <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
from __future__ import absolute_import, division, print_function |
| 7 |
|
| 8 |
''' |
| 9 |
This module is used to manage postgres pg_hba files with Ansible. |
| 10 |
''' |
| 11 |
|
| 12 |
__metaclass__ = type |
| 13 |
|
| 14 |
DOCUMENTATION = r''' |
| 15 |
--- |
| 16 |
module: postgresql_pg_hba |
| 17 |
short_description: Add, remove or modify a rule in a pg_hba file |
| 18 |
description: |
| 19 |
- The fundamental function of the module is to create, or delete lines in pg_hba files. |
| 20 |
- The lines in the file should be in a typical pg_hba form and lines should be unique per key (type, databases, users, source). |
| 21 |
If they are not unique and the SID is 'the one to change', only one for I(state=present) or |
| 22 |
none for I(state=absent) of the SID's will remain. |
| 23 |
extends_documentation_fragment: files |
| 24 |
options: |
| 25 |
address: |
| 26 |
description: |
| 27 |
- The source address/net where the connections could come from. |
| 28 |
- Will not be used for entries of I(type)=C(local). |
| 29 |
- You can also use keywords C(all), C(samehost), and C(samenet). |
| 30 |
default: samehost |
| 31 |
type: str |
| 32 |
aliases: [ source, src ] |
| 33 |
backup: |
| 34 |
description: |
| 35 |
- If set, create a backup of the C(pg_hba) file before it is modified. |
| 36 |
The location of the backup is returned in the (backup) variable by this module. |
| 37 |
default: false |
| 38 |
type: bool |
| 39 |
backup_file: |
| 40 |
description: |
| 41 |
- Write backup to a specific backupfile rather than a temp file. |
| 42 |
type: str |
| 43 |
create: |
| 44 |
description: |
| 45 |
- Create an C(pg_hba) file if none exists. |
| 46 |
- When set to false, an error is raised when the C(pg_hba) file doesn't exist. |
| 47 |
default: false |
| 48 |
type: bool |
| 49 |
contype: |
| 50 |
description: |
| 51 |
- Type of the rule. If not set, C(postgresql_pg_hba) will only return contents. |
| 52 |
type: str |
| 53 |
choices: [ local, host, hostnossl, hostssl, hostgssenc, hostnogssenc ] |
| 54 |
comment: |
| 55 |
description: |
| 56 |
- A comment that will be placed in the same line behind the rule. See also the I(keep_comments_at_rules) parameter. |
| 57 |
type: str |
| 58 |
version_added: '1.5.0' |
| 59 |
databases: |
| 60 |
description: |
| 61 |
- Databases this line applies to. |
| 62 |
default: all |
| 63 |
type: str |
| 64 |
dest: |
| 65 |
description: |
| 66 |
- Path to C(pg_hba) file to modify. |
| 67 |
type: path |
| 68 |
required: true |
| 69 |
method: |
| 70 |
description: |
| 71 |
- Authentication method to be used. |
| 72 |
type: str |
| 73 |
choices: [ cert, gss, ident, krb5, ldap, md5, pam, password, peer, radius, reject, scram-sha-256 , sspi, trust ] |
| 74 |
default: md5 |
| 75 |
netmask: |
| 76 |
description: |
| 77 |
- The netmask of the source address. |
| 78 |
type: str |
| 79 |
options: |
| 80 |
description: |
| 81 |
- Additional options for the authentication I(method). |
| 82 |
type: str |
| 83 |
overwrite: |
| 84 |
description: |
| 85 |
- Remove all existing rules before adding rules. (Like I(state=absent) for all pre-existing rules.) |
| 86 |
- Ignores all errors in the existing file. |
| 87 |
type: bool |
| 88 |
default: false |
| 89 |
keep_comments_at_rules: |
| 90 |
description: |
| 91 |
- This option has been deprecated and doesn't do anything. The module behaves as if this is C(true). |
| 92 |
type: bool |
| 93 |
default: true |
| 94 |
version_added: '1.5.0' |
| 95 |
rules: |
| 96 |
description: |
| 97 |
- A list of objects, specifying rules for the pg_hba.conf. Use this to manage multiple rules at once. |
| 98 |
- "Each object can have the following keys (the 'rule-specific arguments'), which are treated the same as if they were arguments of this module:" |
| 99 |
- C(address), C(comment), C(contype), C(databases), C(method), C(netmask), C(options), C(state), C(users) |
| 100 |
- See also C(rules_behavior). |
| 101 |
type: list |
| 102 |
elements: dict |
| 103 |
rules_behavior: |
| 104 |
description: |
| 105 |
- "Configure how the I(rules) argument works together with the rule-specific arguments outside the I(rules) argument." |
| 106 |
- See I(rules) for the complete list of rule-specific arguments. |
| 107 |
- When set to C(conflict), fail if I(rules) and, for example, I(address) are set. |
| 108 |
- If C(combine), the normal rule-specific arguments are not defining a rule, but are used as defaults for the arguments in the I(rules) argument. |
| 109 |
- Is used only when I(rules) is specified, ignored otherwise. |
| 110 |
type: str |
| 111 |
choices: [ conflict, combine ] |
| 112 |
default: conflict |
| 113 |
sort_rules: |
| 114 |
description: |
| 115 |
- Sorts the rules in the file only if a change is required. It will sort the rules so more specific rules are at |
| 116 |
the top. For example, a rule matching a single host will be before a rule that matches an ip-range. |
| 117 |
- The order of rules is important, as they are evaluated top-down and the first one that matches is used. |
| 118 |
This means changing the order of rules in the file can change how your instance behaves. |
| 119 |
- Will sort comments to the top, includes to the bottom and remove empty lines. |
| 120 |
- I would advise to turn this off when managing a file that receives manual changes, as well or if the order |
| 121 |
you specify your rules in is important. |
| 122 |
type: bool |
| 123 |
default: true |
| 124 |
version_added: '3.11.0' |
| 125 |
state: |
| 126 |
description: |
| 127 |
- The lines will be added/modified when C(state=present) and removed when C(state=absent). |
| 128 |
type: str |
| 129 |
default: present |
| 130 |
choices: [ absent, present ] |
| 131 |
users: |
| 132 |
description: |
| 133 |
- Users this line applies to. |
| 134 |
type: str |
| 135 |
default: all |
| 136 |
|
| 137 |
notes: |
| 138 |
- The default authentication assumes that on the host, you are either logging in as or |
| 139 |
sudo'ing to an account with appropriate permissions to read and modify the file. |
| 140 |
- This module also returns the pg_hba info. You can use this module to only retrieve it by only specifying I(dest). |
| 141 |
The info can be found in the returned data under key pg_hba, being a list, containing a dict per rule. |
| 142 |
- This module will sort resulting C(pg_hba) files if a rule change is required. |
| 143 |
This could give unexpected results with manual created hba files, if it was improperly sorted. |
| 144 |
For example a rule was created for a net first and for a ip in that net range next. |
| 145 |
In that situation, the 'ip specific rule' will never hit, it is in the C(pg_hba) file obsolete. |
| 146 |
After the C(pg_hba) file is rewritten by the M(community.postgresql.postgresql_pg_hba) module, the ip specific rule will be sorted above the range rule. |
| 147 |
And then it will hit, which will give unexpected results. |
| 148 |
|
| 149 |
seealso: |
| 150 |
- name: PostgreSQL pg_hba.conf file reference |
| 151 |
description: Complete reference of the PostgreSQL pg_hba.conf file documentation. |
| 152 |
link: https://www.postgresql.org/docs/current/auth-pg-hba-conf.html |
| 153 |
|
| 154 |
requirements: |
| 155 |
- ipaddress |
| 156 |
|
| 157 |
attributes: |
| 158 |
check_mode: |
| 159 |
support: full |
| 160 |
description: Can run in check_mode and return changed status prediction without modifying target |
| 161 |
diff_mode: |
| 162 |
support: full |
| 163 |
description: Will return details on what has changed (or possibly needs changing in check_mode), when in diff mode |
| 164 |
|
| 165 |
author: |
| 166 |
- Sebastiaan Mannem (@sebasmannem) |
| 167 |
- Felix Hamme (@betanummeric) |
| 168 |
- Thomas Ziegler (@toydarian) |
| 169 |
''' |
| 170 |
|
| 171 |
EXAMPLES = ''' |
| 172 |
- name: Grant users joe and simon access to databases sales and logistics from ipv6 localhost ::1/128 using peer authentication |
| 173 |
community.postgresql.postgresql_pg_hba: |
| 174 |
dest: /var/lib/postgres/data/pg_hba.conf |
| 175 |
contype: host |
| 176 |
users: joe,simon |
| 177 |
source: ::1 |
| 178 |
databases: sales,logistics |
| 179 |
method: peer |
| 180 |
create: true |
| 181 |
|
| 182 |
- name: Grant user replication from network 192.168.0.100/24 access for replication with client cert authentication |
| 183 |
community.postgresql.postgresql_pg_hba: |
| 184 |
dest: /var/lib/postgres/data/pg_hba.conf |
| 185 |
contype: host |
| 186 |
users: replication |
| 187 |
source: 192.168.0.100/24 |
| 188 |
databases: replication |
| 189 |
method: cert |
| 190 |
|
| 191 |
- name: Revoke access from local user mary on database mydb |
| 192 |
community.postgresql.postgresql_pg_hba: |
| 193 |
dest: /var/lib/postgres/data/pg_hba.conf |
| 194 |
contype: local |
| 195 |
users: mary |
| 196 |
databases: mydb |
| 197 |
state: absent |
| 198 |
|
| 199 |
- name: Grant some_user access to some_db, comment that and keep other rule-specific comments attached to their rules |
| 200 |
community.postgresql.postgresql_pg_hba: |
| 201 |
dest: /var/lib/postgres/data/pg_hba.conf |
| 202 |
contype: host |
| 203 |
users: some_user |
| 204 |
databases: some_db |
| 205 |
method: md5 |
| 206 |
source: ::/0 |
| 207 |
keep_comments_at_rules: true |
| 208 |
comment: "this rule is an example" |
| 209 |
|
| 210 |
- name: Replace everything with a new set of rules |
| 211 |
community.postgresql.postgresql_pg_hba: |
| 212 |
dest: /var/lib/postgres/data/pg_hba.conf |
| 213 |
overwrite: true # remove preexisting rules |
| 214 |
|
| 215 |
# custom defaults |
| 216 |
rules_behavior: combine |
| 217 |
contype: hostssl |
| 218 |
address: 2001:db8::/64 |
| 219 |
comment: added in bulk |
| 220 |
|
| 221 |
rules: |
| 222 |
- users: user1 |
| 223 |
databases: db1 |
| 224 |
# contype, address and comment come from custom default |
| 225 |
- users: user2 |
| 226 |
databases: db2 |
| 227 |
comment: added with love # overwrite custom default for this rule |
| 228 |
# contype and address come from custom default |
| 229 |
- users: user3 |
| 230 |
databases: db3 |
| 231 |
# contype, address and comment come from custom default |
| 232 |
''' |
| 233 |
|
| 234 |
RETURN = r''' |
| 235 |
msgs: |
| 236 |
description: List of textual messages what was done. |
| 237 |
returned: success |
| 238 |
type: list |
| 239 |
sample: |
| 240 |
"msgs": [ |
| 241 |
"Removing", |
| 242 |
"Changed", |
| 243 |
"Writing" |
| 244 |
] |
| 245 |
backup_file: |
| 246 |
description: File that the original pg_hba file was backed up to. |
| 247 |
returned: changed |
| 248 |
type: str |
| 249 |
sample: /tmp/pg_hba_jxobj_p |
| 250 |
pg_hba: |
| 251 |
description: List of the pg_hba rules as they are configured in the specified hba file. |
| 252 |
returned: success |
| 253 |
type: list |
| 254 |
sample: |
| 255 |
"pg_hba": [ |
| 256 |
{ |
| 257 |
"db": "all", |
| 258 |
"method": "md5", |
| 259 |
"src": "samehost", |
| 260 |
"type": "host", |
| 261 |
"usr": "all" |
| 262 |
} |
| 263 |
] |
| 264 |
pg_hba_string: |
| 265 |
description: The string in the pg_hba file after the module finished. |
| 266 |
returned: success |
| 267 |
type: str |
| 268 |
sample: "local\tall\tall\tpeer" |
| 269 |
''' |
| 270 |
|
| 271 |
import copy |
| 272 |
import os |
| 273 |
import re |
| 274 |
import traceback |
| 275 |
import time |
| 276 |
|
| 277 |
IPADDRESS_IMP_ERR = None |
| 278 |
try: |
| 279 |
import ipaddress |
| 280 |
except ImportError: |
| 281 |
IPADDRESS_IMP_ERR = traceback.format_exc() |
| 282 |
|
| 283 |
import shutil |
| 284 |
import tempfile |
| 285 |
|
| 286 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 287 |
|
| 288 |
# from ansible.module_utils.postgres import postgres_common_argument_spec |
| 289 |
|
| 290 |
PG_HBA_METHODS = ["trust", "reject", "md5", "password", "gss", "sspi", "krb5", "ident", "peer", |
| 291 |
"ldap", "radius", "cert", "pam", "scram-sha-256"] |
| 292 |
PG_HBA_TYPES = ["local", "host", "hostssl", "hostnossl", "hostgssenc", "hostnogssenc"] |
| 293 |
PG_HBA_HDR = ['type', 'db', 'usr', 'src', 'mask', 'method', 'options'] |
| 294 |
PG_HBA_REQUIRED_FIELDS = ['contype', 'databases', 'users', 'method'] |
| 295 |
|
| 296 |
RULE_KEYS = ['contype', 'databases', 'users', 'address', 'netmask', 'method', 'options',] |
| 297 |
PG_HBA_HDR_MAP = dict(zip(RULE_KEYS, PG_HBA_HDR)) |
| 298 |
PG_HBA_HDR_NOMAP = dict(zip(RULE_KEYS, RULE_KEYS)) |
| 299 |
|
| 300 |
WHITESPACES_RE = re.compile(r'\s+') |
| 301 |
TOKEN_SPLIT_RE = re.compile(r'(?<=[\s"#])') |
| 302 |
WHITESPACE_QUOTE_OR_COMMENT_RE = re.compile(r'[\s"#]') |
| 303 |
ONLY_SPACES_RE = re.compile(r"^\s+$") |
| 304 |
OPTION_RE = re.compile(r"([^=]+)=(.+)") |
| 305 |
IPV4_ADDR_RE = re.compile(r'^"?((\d{1,3}\.){3}\d{1,3})(/(\d{1,2}))?"?$') |
| 306 |
# this regex allows for some invalid IPv6 addresses like ':::', but I honestly don't care |
| 307 |
IPV6_ADDR_RE = re.compile(r'^"?([a-f0-9]*:[a-f0-9:]*:[a-f0-9]*)(/(\d{1,3}))?"?$') |
| 308 |
|
| 309 |
|
| 310 |
class PgHbaError(Exception): |
| 311 |
""" |
| 312 |
This exception is raised when parsing the pg_hba file ends in an error. |
| 313 |
""" |
| 314 |
|
| 315 |
|
| 316 |
class PgHbaRuleError(PgHbaError): |
| 317 |
""" |
| 318 |
This exception is raised when parsing the pg_hba file ends in an error. |
| 319 |
""" |
| 320 |
|
| 321 |
|
| 322 |
class PgHbaRuleChanged(PgHbaRuleError): |
| 323 |
""" |
| 324 |
This exception is raised when a new parsed rule is a changed version of an existing rule. |
| 325 |
""" |
| 326 |
|
| 327 |
|
| 328 |
class PgHbaValueError(PgHbaError): |
| 329 |
""" |
| 330 |
This exception is raised when a new parsed rule is a changed version of an existing rule. |
| 331 |
""" |
| 332 |
|
| 333 |
|
| 334 |
class PgHbaRuleValueError(PgHbaRuleError): |
| 335 |
""" |
| 336 |
This exception is raised when a new parsed rule is a changed version of an existing rule. |
| 337 |
""" |
| 338 |
|
| 339 |
|
| 340 |
class TokenizerException(Exception): |
| 341 |
""" |
| 342 |
This exception is raised when a string can't be tokenized |
| 343 |
""" |
| 344 |
|
| 345 |
|
| 346 |
def parse_hba_file(input_string): |
| 347 |
""" |
| 348 |
This function parses a complete pg_hba.conf file into a list of tuples where each tuple represents a rule in the |
| 349 |
file. |
| 350 |
:param input_string: The whole string in the pg_hba.conf file (not just a single line) |
| 351 |
:return: A list of Rule objects that represents the contents of the input string. |
| 352 |
""" |
| 353 |
rules = [] |
| 354 |
line_iter = iter(input_string.split("\n")) |
| 355 |
line = next(line_iter, None) |
| 356 |
this_line_nr = 1 |
| 357 |
next_line_nr = 1 |
| 358 |
while line is not None: |
| 359 |
# if that line continues, we just glue the next line onto the end until it ends |
| 360 |
# we can and have to do that, as continuation even applies within comments and quoted strings [sic] |
| 361 |
# https://www.postgresql.org/docs/current/auth-pg-hba-conf.html#AUTH-PG-HBA-CONF |
| 362 |
comment = None |
| 363 |
while line.endswith("\\"): |
| 364 |
next_line_nr += 1 |
| 365 |
cont_line = next(line_iter, None) |
| 366 |
if cont_line is None: |
| 367 |
# we got a line continuation, but there was no more line |
| 368 |
raise PgHbaRuleError("The last line ended with a '\\' (line continuation).") |
| 369 |
line += "\n" + cont_line # add the newline so we don't lose that information |
| 370 |
# handle comment-only lines |
| 371 |
if line.strip().startswith('#'): |
| 372 |
parsed_line = "COMMENT" |
| 373 |
comment = line |
| 374 |
# handle empty lines |
| 375 |
elif not line.strip(): |
| 376 |
parsed_line = "EMPTY" |
| 377 |
# handle "normal" lines |
| 378 |
else: |
| 379 |
# remove continuation tokens |
| 380 |
sanitized_line = line.replace("\\\n", "") |
| 381 |
try: |
| 382 |
tokens = tokenize(sanitized_line) |
| 383 |
except TokenizerException as e: |
| 384 |
raise TokenizerException("Error in line {0}: {1}".format(this_line_nr, e.args[0])) |
| 385 |
parsed_line = tokens |
| 386 |
# a comment would always be the last token |
| 387 |
if parsed_line[-1].startswith("#"): |
| 388 |
comment = parsed_line[-1] |
| 389 |
parsed_line = parsed_line[:-1] |
| 390 |
# create Rule |
| 391 |
rules.append({"tokens": parsed_line, "line": line, "comment": comment, "line_nr": this_line_nr}) |
| 392 |
line = next(line_iter, None) |
| 393 |
this_line_nr = next_line_nr + 1 |
| 394 |
next_line_nr = this_line_nr |
| 395 |
return rules |
| 396 |
|
| 397 |
|
| 398 |
def rule_list_from_hba_file(input_string): |
| 399 |
""" |
| 400 |
Takes an input string which could come from a file, runs it through parse_hba_file and the creates a list of |
| 401 |
rule objects. |
| 402 |
:param input_string: The string to parse |
| 403 |
:return: A list of rule-objects created from the input string |
| 404 |
""" |
| 405 |
rule_list = [] |
| 406 |
for rule in parse_hba_file(input_string): |
| 407 |
rule_list.append(PgHbaRule(**rule)) |
| 408 |
return rule_list |
| 409 |
|
| 410 |
|
| 411 |
def tokenize(string): |
| 412 |
""" |
| 413 |
This function tokenizes a string respecting quotes. It needs to be fed a complete string where all quotes are |
| 414 |
properly closed (there needs to be an even amount of `"`) otherwise it raises an exception. |
| 415 |
You can, for example use this to tokenize a full line of a pg_hba-file (make sure to handle any escaped newlines) |
| 416 |
or a string of options. |
| 417 |
:param string: A string to tokenize |
| 418 |
:return: The tokenized string as a list of strings |
| 419 |
""" |
| 420 |
|
| 421 |
# We need to do this charade for splitting to be compatible with Python 3.6 which has been EOL for three years |
| 422 |
# at the time of writing. If you come across this after support for Python 3.6 has been dropped, please replace |
| 423 |
# WHITESPACE_OR_QUOTE_RE in the beginning of the file with `TOKEN_SPLIT_RE = re.compile(r'(?<=[\s"#])')` |
| 424 |
# and the next 8 lines (including bare_tokens.append) with `bare_tokens = TOKEN_SPLIT_RE.split(string)` |
| 425 |
bare_tokens = [] |
| 426 |
lastpos = 0 |
| 427 |
nextmatch = WHITESPACE_QUOTE_OR_COMMENT_RE.search(string) |
| 428 |
while nextmatch: |
| 429 |
bare_tokens.append(string[lastpos:nextmatch.end()]) |
| 430 |
lastpos = nextmatch.end() |
| 431 |
nextmatch = WHITESPACE_QUOTE_OR_COMMENT_RE.search(string, lastpos) |
| 432 |
bare_tokens.append(string[lastpos:]) |
| 433 |
|
| 434 |
tokens = [] |
| 435 |
state = "START" |
| 436 |
current_symbol = "" |
| 437 |
|
| 438 |
for token in bare_tokens: |
| 439 |
|
| 440 |
# if the previous token ended a quoted string, we need to decide how to continue |
| 441 |
if state == "QUOTE_END": |
| 442 |
state = "START" |
| 443 |
# if the token consists of only spaces, we know for sure this symbol is finished |
| 444 |
if token == "" or not token.strip(): |
| 445 |
tokens.append(current_symbol.strip()) |
| 446 |
current_symbol = "" |
| 447 |
continue |
| 448 |
# otherwise it might continue with more characters or even another quote |
| 449 |
|
| 450 |
if token == "": |
| 451 |
continue |
| 452 |
|
| 453 |
# we either start a new symbol or continue after a finished quote |
| 454 |
if state == "START": |
| 455 |
# outside of quotes, whitespaces are ignored |
| 456 |
if not token.strip(): |
| 457 |
continue |
| 458 |
|
| 459 |
current_symbol += token |
| 460 |
# we use endswith here, to correctly handle strings like 'somekey="somevalue"' |
| 461 |
# if there was a space before it, the quote will be alone, so that is not an issue |
| 462 |
if token.endswith("\""): |
| 463 |
state = "QUOTE" |
| 464 |
elif token.endswith("#"): |
| 465 |
# handle edge-case of a comment having no space before the #-symbol like "... md5#some comment" |
| 466 |
if not token.startswith("#"): |
| 467 |
current_symbol = current_symbol[:-1] |
| 468 |
tokens.append(current_symbol.strip()) |
| 469 |
current_symbol = "#" |
| 470 |
state = "COMMENT" |
| 471 |
else: |
| 472 |
tokens.append(current_symbol.strip()) |
| 473 |
current_symbol = "" |
| 474 |
|
| 475 |
elif state == "COMMENT": |
| 476 |
current_symbol += token |
| 477 |
|
| 478 |
# if we are inside a quoted string we consume and append tokens until the quoted string ends |
| 479 |
elif state == "QUOTE": |
| 480 |
current_symbol += token |
| 481 |
if token.endswith("\""): |
| 482 |
state = "QUOTE_END" |
| 483 |
|
| 484 |
if state == "COMMENT": |
| 485 |
tokens.append(current_symbol) |
| 486 |
elif state == "QUOTE": |
| 487 |
raise TokenizerException("Unterminated quote") |
| 488 |
|
| 489 |
return tokens |
| 490 |
|
| 491 |
|
| 492 |
def from_rule_list(rule_list): |
| 493 |
""" |
| 494 |
Creates a list of Rule objects from a list of dicts. |
| 495 |
:param rule_list: A list of dicts where each item in the list represents a rule |
| 496 |
:return: A list of Rule objects created from the items in the list |
| 497 |
""" |
| 498 |
rules = [] |
| 499 |
for rule in rule_list: |
| 500 |
if rule == {}: |
| 501 |
rules.append(PgHbaRule(tokens="EMPTY", line='')) |
| 502 |
elif not rule['contype'] and rule['comment']: |
| 503 |
rules.append(PgHbaRule(tokens="COMMENT", comment=rule['comment'])) |
| 504 |
else: |
| 505 |
rules.append(PgHbaRule(rule_dict=rule)) |
| 506 |
return rules |
| 507 |
|
| 508 |
|
| 509 |
class PgHbaRule: |
| 510 |
""" |
| 511 |
This class represents one rule as defined in a line in a PgHbaFile. |
| 512 |
""" |
| 513 |
|
| 514 |
def __init__(self, tokens=None, rule_dict=None, line=None, comment=None, line_nr=0): |
| 515 |
""" |
| 516 |
Creates a new PgHbaRule object, either from a list of tokens or a dictionary of fields. It will validate the |
| 517 |
input and raise an exception if the rule is invalid. It will also decide if a rule is special in a sense that |
| 518 |
it only contains a comment, is an include or an empty line. |
| 519 |
Either tokens or rule_dict may be not None. |
| 520 |
:param tokens: A list of tokens to create the rule from (mutually exclusive with rule_dict) |
| 521 |
:param rule_dict: A dictionary representing the rule (mutually exclusive with tokens) |
| 522 |
:param line: The line this rule was created from (if it was parsed from a file, None is fine) |
| 523 |
:param comment: A comment associated with that rule |
| 524 |
""" |
| 525 |
self._type = None |
| 526 |
self._database = None |
| 527 |
self._user = None |
| 528 |
self._address = None |
| 529 |
self._mask = None |
| 530 |
self._auth_method = None |
| 531 |
self._auth_options = None |
| 532 |
|
| 533 |
self._address_type = None |
| 534 |
self._prefix_len = None |
| 535 |
|
| 536 |
# includes, comment-only lines and empty lines are special |
| 537 |
self._is_special = False |
| 538 |
self._line = line |
| 539 |
self._line_nr = line_nr |
| 540 |
# normalize comment so we can safely compare it if we have to |
| 541 |
if comment: |
| 542 |
self._comment = comment.strip() |
| 543 |
self._comment = '#' + self._comment if not self._comment.startswith('#') else self._comment |
| 544 |
else: |
| 545 |
self._comment = comment |
| 546 |
|
| 547 |
if (tokens is None and rule_dict is None) or (tokens is not None and rule_dict is not None): |
| 548 |
raise PgHbaRuleError( |
| 549 |
"Exactly one of 'tokens' and 'rule_dict' needs to be specified when creating a Rule-object") |
| 550 |
|
| 551 |
# parse tokens into a rule |
| 552 |
if tokens is not None: |
| 553 |
try: |
| 554 |
self._from_tokens(tokens) |
| 555 |
except PgHbaError as e: |
| 556 |
if line_nr: |
| 557 |
raise e.__class__("Error in line {0}: {1}".format(line_nr, e.args[0])) |
| 558 |
else: |
| 559 |
raise e |
| 560 |
elif rule_dict is not None: |
| 561 |
self._from_rule_dict(rule_dict) |
| 562 |
|
| 563 |
# construct the line from the comment if there is no line, but a comment |
| 564 |
if self._is_special and not line and comment: |
| 565 |
self._line = self._comment |
| 566 |
|
| 567 |
@property |
| 568 |
def line_nr(self): |
| 569 |
return self._line_nr |
| 570 |
|
| 571 |
@property |
| 572 |
def line(self): |
| 573 |
return self._line |
| 574 |
|
| 575 |
@property |
| 576 |
def is_special(self): |
| 577 |
return self._is_special |
| 578 |
|
| 579 |
@property |
| 580 |
def comment(self): |
| 581 |
return self._comment |
| 582 |
|
| 583 |
@property |
| 584 |
def type(self): |
| 585 |
return self._type |
| 586 |
|
| 587 |
@property |
| 588 |
def user(self): |
| 589 |
return self._user |
| 590 |
|
| 591 |
@property |
| 592 |
def database(self): |
| 593 |
return self._database |
| 594 |
|
| 595 |
@property |
| 596 |
def address(self): |
| 597 |
return self._address |
| 598 |
|
| 599 |
@property |
| 600 |
def netmask(self): |
| 601 |
return self._mask |
| 602 |
|
| 603 |
@property |
| 604 |
def method(self): |
| 605 |
return self._auth_method |
| 606 |
|
| 607 |
@property |
| 608 |
def options(self): |
| 609 |
return copy.copy(self._auth_options) |
| 610 |
|
| 611 |
@property |
| 612 |
def source(self): |
| 613 |
""" |
| 614 |
This method is used to get the source of a rule as an ipaddress object if possible. |
| 615 |
""" |
| 616 |
if self._type == "local": |
| 617 |
return "" |
| 618 |
if self._address_type == "hostname": |
| 619 |
return self._address |
| 620 |
else: |
| 621 |
return ipaddress.ip_network("{0}/{1}".format(self._address, self._prefix_len), strict=False) |
| 622 |
|
| 623 |
@property |
| 624 |
def source_type(self): |
| 625 |
return self._address_type |
| 626 |
|
| 627 |
def __eq__(self, other): |
| 628 |
""" |
| 629 |
Rules are considered "equal" if they have the same key, as in type, user, database and source. |
| 630 |
Special rules are equal if they are identical |
| 631 |
""" |
| 632 |
# comments are only compared if they are not attached to a rule |
| 633 |
if self.is_special and other.is_special: |
| 634 |
if self.comment and other.comment: |
| 635 |
return self.comment == other.comment |
| 636 |
return self.line == other.line |
| 637 |
|
| 638 |
# normal rules are equal if they key matches |
| 639 |
return (self._type == other.type |
| 640 |
and self._user == other.user |
| 641 |
and self._database == other.database |
| 642 |
and self.source == other.source) |
| 643 |
|
| 644 |
def __lt__(self, other): |
| 645 |
"""This function helps sorted to decide how to sort. |
| 646 |
|
| 647 |
It just checks itself against the other and decides on some key values |
| 648 |
if it should be sorted higher or lower in the list. |
| 649 |
The way it works: |
| 650 |
For networks, every 1 in 'netmask in binary' makes the subnet more specific. |
| 651 |
Therefore, I chose to use prefix as the weight. |
| 652 |
So a single IP (/32) should have twice the weight of a /16 network. |
| 653 |
To keep everything in the same weight scale, |
| 654 |
- for ipv6, we use a weight scale of 0 (all possible ipv6 addresses) to 128 (single ip) |
| 655 |
- for ipv4, we use a weight scale of 0 (all possible ipv4 addresses) to 128 (single ip) |
| 656 |
Therefore for ipv4, we use prefixlen (0-32) * 4 for weight, |
| 657 |
which corresponds to ipv6 (0-128). |
| 658 |
""" |
| 659 |
|
| 660 |
if self.is_special and other.is_special: |
| 661 |
myweight = self.special_weight() |
| 662 |
hisweight = other.special_weight() |
| 663 |
if myweight != hisweight: |
| 664 |
return myweight < hisweight |
| 665 |
else: |
| 666 |
# if both have a line number, don't change the initial order |
| 667 |
if self._line_nr and other.line_nr: |
| 668 |
return self._line_nr < other.line_nr |
| 669 |
# if neither has a line number, order alphabetically |
| 670 |
elif not self._line_nr and not other.line_nr: |
| 671 |
return self.line < other.line |
| 672 |
# if only one of the rules has a line number, that one is sorted before the other |
| 673 |
# like that, new full-line comments are always added after existing ones |
| 674 |
else: |
| 675 |
return self.line_nr > other.line_nr |
| 676 |
|
| 677 |
# comments go before anything else, includes go last |
| 678 |
if self.is_special and not other.is_special: |
| 679 |
# this line is less than the other if it is not an include and a (full-line) comment |
| 680 |
return (not self._line.startswith("include")) and bool(self._comment) |
| 681 |
if not self.is_special and other.is_special: |
| 682 |
# this line is less than the other if the other is an include and not a comment |
| 683 |
return other.line.startswith("include") and (not bool(other.comment)) |
| 684 |
|
| 685 |
myweight = self.source_weight() |
| 686 |
hisweight = other.source_weight() |
| 687 |
if myweight != hisweight: |
| 688 |
return myweight > hisweight |
| 689 |
|
| 690 |
myweight = self.db_weight() |
| 691 |
hisweight = other.db_weight() |
| 692 |
if myweight != hisweight: |
| 693 |
return myweight < hisweight |
| 694 |
|
| 695 |
myweight = self.user_weight() |
| 696 |
hisweight = other.user_weight() |
| 697 |
if myweight != hisweight: |
| 698 |
return myweight < hisweight |
| 699 |
|
| 700 |
myweight = self.source_type_weight() |
| 701 |
hisweight = other.source_type_weight() |
| 702 |
if myweight != hisweight: |
| 703 |
return myweight > hisweight |
| 704 |
elif self.source != other.source: |
| 705 |
return self.source < other.source |
| 706 |
|
| 707 |
# When all else fails, just compare the rendered lines |
| 708 |
return self.serialize() < other.serialize() |
| 709 |
|
| 710 |
def __str__(self): |
| 711 |
return self.serialize() |
| 712 |
|
| 713 |
def __copy__(self): |
| 714 |
return PgHbaRule(rule_dict=self.to_dict(), line=self._line, comment=self._comment) |
| 715 |
|
| 716 |
def source_weight(self): |
| 717 |
"""Report the weight of this source net. |
| 718 |
|
| 719 |
Basically this is the netmask, where IPv4 is normalized to IPv6 |
| 720 |
(IPv4/32 has the same weight as IPv6/128). |
| 721 |
""" |
| 722 |
|
| 723 |
if self._type == "local": |
| 724 |
return 130 |
| 725 |
|
| 726 |
if self._address_type == "IPv4": |
| 727 |
return self._prefix_len * 4 |
| 728 |
elif self._address_type == "IPv6": |
| 729 |
return self._prefix_len |
| 730 |
else: |
| 731 |
# You can also write all to match any IP address, |
| 732 |
# samehost to match any of the server's own IP addresses, |
| 733 |
# or samenet to match any address in any subnet that the server is connected to. |
| 734 |
if self._address == 'all': |
| 735 |
# (all is considered the full range of all ips, which has a weight of 0) |
| 736 |
return 0 |
| 737 |
if self._address == 'samehost': |
| 738 |
# (sort samehost second after local) |
| 739 |
return 129 |
| 740 |
if self._address == 'samenet': |
| 741 |
# Might write some fancy code to determine all prefix's |
| 742 |
# from all interfaces and find a sane value for this one. |
| 743 |
# For now, let's assume IPv4/24 or IPv6/96 (both have weight 96). |
| 744 |
return 96 |
| 745 |
if self._address.startswith('.'): |
| 746 |
# suffix matching (domain name), let's assume a very large scale |
| 747 |
# and therefore a very low weight IPv4/16 or IPv6/64 (both have weight 64). |
| 748 |
return 64 |
| 749 |
# hostname, let's assume only one host matches, which is |
| 750 |
# IPv4/32 or IPv6/128 (both have weight 128) |
| 751 |
return 128 |
| 752 |
|
| 753 |
def source_type_weight(self): |
| 754 |
"""Give a weight on the type of this source. |
| 755 |
|
| 756 |
Basically make sure that IPv6Networks are sorted higher than IPv4Networks. |
| 757 |
This is a 'when all else fails' solution in __lt__. |
| 758 |
""" |
| 759 |
if self._type == 'local': |
| 760 |
return 3 |
| 761 |
|
| 762 |
sourceobj = self.source |
| 763 |
if isinstance(sourceobj, ipaddress.IPv4Network): |
| 764 |
return 2 |
| 765 |
if isinstance(sourceobj, ipaddress.IPv6Network): |
| 766 |
return 1 |
| 767 |
if isinstance(sourceobj, str): |
| 768 |
return 0 |
| 769 |
raise PgHbaValueError('This source {0} is of an unknown type...'.format(sourceobj)) |
| 770 |
|
| 771 |
def db_weight(self): |
| 772 |
"""Report the weight of the database. |
| 773 |
|
| 774 |
Normally, just 1, but for replication this is 0, and for 'all', this is more than 2. |
| 775 |
""" |
| 776 |
if self._database.startswith("\""): |
| 777 |
# keywords lose their special meaning if quoted |
| 778 |
return 3 |
| 779 |
db_list = self._database.split(',') |
| 780 |
if "all" in db_list: |
| 781 |
return 100000 |
| 782 |
if self._database == 'replication': |
| 783 |
return 0 |
| 784 |
if self._database in ['samerole', 'samegroup']: |
| 785 |
return 2 |
| 786 |
return 3 + len(db_list) |
| 787 |
|
| 788 |
def user_weight(self): |
| 789 |
"""Report weight when comparing users.""" |
| 790 |
if self._user.startswith("\""): |
| 791 |
# keywords lose their special meaning if quoted |
| 792 |
return 1 |
| 793 |
user_list = self._user.split(',') |
| 794 |
if "all" in user_list: |
| 795 |
# if "all" is in the list, we sort it to the bottom |
| 796 |
return 100000 |
| 797 |
return 1 + len(user_list) |
| 798 |
|
| 799 |
def special_weight(self): |
| 800 |
"""Determines the weight to sort special lines""" |
| 801 |
if self.comment: |
| 802 |
return 1 |
| 803 |
if self._line.startswith("include"): |
| 804 |
return 90 |
| 805 |
|
| 806 |
return 99 # only empty lines |
| 807 |
|
| 808 |
def to_dict(self, header_map=None): |
| 809 |
if header_map is None: |
| 810 |
header_map = PG_HBA_HDR_NOMAP |
| 811 |
if self._is_special: |
| 812 |
if not self._comment: |
| 813 |
return {} |
| 814 |
else: |
| 815 |
return {'comment': self._comment} |
| 816 |
|
| 817 |
ret_dict = {header_map['contype']: self._type, |
| 818 |
header_map['databases']: self._database, |
| 819 |
header_map['users']: self._user, |
| 820 |
header_map['method']: self._auth_method} |
| 821 |
if self._address: |
| 822 |
ret_dict[header_map['address']] = str(self.source) |
| 823 |
if self._auth_options: |
| 824 |
# we might want to change the return-type to a dict at some point, but right now we return a string |
| 825 |
# to not introduce breaking changes |
| 826 |
# ret_dict[header_map['options']] = copy.copy(self._auth_options) |
| 827 |
ret_dict[header_map['options']] = self._serialize_auth_options(delimiter=" ") |
| 828 |
# we haven't included the comment before, should we? |
| 829 |
# if self._comment: |
| 830 |
# ret_dict['comment'] = self._comment |
| 831 |
return ret_dict |
| 832 |
|
| 833 |
def is_identical(self, other): |
| 834 |
"""Rules are identical if they share the same key, method and options""" |
| 835 |
return (self == other |
| 836 |
and self._auth_method == other.method |
| 837 |
and self._auth_options == other.options) |
| 838 |
|
| 839 |
def serialize(self, delimiter="\t", use_line=True, with_comment=True): |
| 840 |
""" |
| 841 |
Serializes a rule into a string that can be placed in a pg_hba.conf file. If `line` is not None (mostly if this |
| 842 |
rule has been parsed from a pg_hba.conf file previously) and use_line is True, this returns the line this rule |
| 843 |
was originally parsed from. Otherwise, it creates a line from the rule. |
| 844 |
:param delimiter: The character to use to separate the fields |
| 845 |
:param use_line: Use the line this rule was parsed from, if it exists |
| 846 |
:param with_comment: Include comment when serializing |
| 847 |
:return: A string from the rule that can be used in a pg_hba.conf file |
| 848 |
""" |
| 849 |
if self._line and use_line: |
| 850 |
return self._line |
| 851 |
|
| 852 |
if self._is_special: |
| 853 |
if not self._comment: |
| 854 |
return self._line if self._line else "" |
| 855 |
else: |
| 856 |
return self._comment if self._comment.startswith("#") else "#{0}".format(self._comment) |
| 857 |
|
| 858 |
rule = self._type + delimiter + self._database + delimiter + self._user + delimiter |
| 859 |
if self._type != "local": |
| 860 |
rule += str(self.source) + delimiter |
| 861 |
rule += self._auth_method |
| 862 |
|
| 863 |
if self._auth_options: |
| 864 |
rule += delimiter + self._serialize_auth_options(delimiter=" ") |
| 865 |
|
| 866 |
if self._comment and with_comment: |
| 867 |
if self._comment.startswith("#"): |
| 868 |
rule += delimiter + self.comment |
| 869 |
else: |
| 870 |
rule += delimiter + "#" + self._comment |
| 871 |
|
| 872 |
return rule |
| 873 |
|
| 874 |
def key(self): |
| 875 |
""" |
| 876 |
This method can be used to get the key from a rule. |
| 877 |
""" |
| 878 |
if self._type == 'local': |
| 879 |
source = 'local' |
| 880 |
else: |
| 881 |
source = str(self.source) |
| 882 |
return source, self._database, self._user, self._type |
| 883 |
|
| 884 |
def _serialize_auth_options(self, delimiter): |
| 885 |
options = [] |
| 886 |
for key in sorted(self._auth_options.keys()): |
| 887 |
options.append(key + "=" + self._auth_options[key]) |
| 888 |
return delimiter.join(options) |
| 889 |
|
| 890 |
def _from_tokens(self, symbols): |
| 891 |
# empty lines, full line comments and includes are special |
| 892 |
if symbols == "EMPTY" or symbols == "COMMENT" or symbols[0].startswith("include"): |
| 893 |
self._is_special = True |
| 894 |
return |
| 895 |
|
| 896 |
if len(symbols) < 4: |
| 897 |
raise PgHbaRuleError("The rule has too few symbols") |
| 898 |
|
| 899 |
self._type = _strip_quotes(symbols[0]) |
| 900 |
if self._type not in PG_HBA_TYPES: |
| 901 |
raise PgHbaRuleValueError("Found an unknown connection-type {0}".format(symbols[0])) |
| 902 |
|
| 903 |
# don't strip quotes from database or user, as they have a special meaning there [sic] |
| 904 |
# > Quoting one of the keywords in a database, user, or address field (e.g., all or replication) makes the word |
| 905 |
# > lose its special meaning, and just match a database, user, or host with that name. |
| 906 |
self._database = handle_db_and_user_strings(symbols[1]) |
| 907 |
self._user = handle_db_and_user_strings(symbols[2]) |
| 908 |
|
| 909 |
if self._type == "local": |
| 910 |
method_token = 3 |
| 911 |
else: |
| 912 |
self._address, self._address_type, self._prefix_len = handle_address_field(symbols[3]) |
| 913 |
# it is an IP, but without a CIDR suffix, so we expect a netmask in the next token |
| 914 |
if self._address_type.startswith("IP") and self._prefix_len == -1: |
| 915 |
self._mask, mask_type, self._prefix_len = handle_netmask_field(symbols[4], raise_not_valid=False) |
| 916 |
if mask_type == "invalid": |
| 917 |
raise PgHbaRuleError("The rule either needs a hostname, full CIDR or an IP-address and a netmask") |
| 918 |
if mask_type != self._address_type: |
| 919 |
raise PgHbaRuleError("Can't mix IPv4 and IPv6 netmasks and addresses") |
| 920 |
if len(symbols) < 6: |
| 921 |
raise PgHbaRuleError("The rule has too few symbols") |
| 922 |
method_token = 5 # the method should be after the netmask |
| 923 |
# if it is anything but a bare IP address, we expect the method on index 4 |
| 924 |
else: |
| 925 |
if len(symbols) < 5: |
| 926 |
raise PgHbaRuleError("The rule has too few symbols") |
| 927 |
method_token = 4 |
| 928 |
|
| 929 |
self._auth_method = _strip_quotes(symbols[method_token]) |
| 930 |
if self._auth_method not in PG_HBA_METHODS: |
| 931 |
raise PgHbaRuleValueError("Found an unknown method: {0}".format(symbols[method_token])) |
| 932 |
|
| 933 |
# if there is anything after the method, that must be options |
| 934 |
if len(symbols) > method_token + 1: |
| 935 |
self._auth_options = parse_auth_options(symbols[method_token + 1:]) |
| 936 |
|
| 937 |
def _from_rule_dict(self, rule_dict): |
| 938 |
# handle special cases |
| 939 |
if not rule_dict or len(rule_dict) == 1 and "comment" in rule_dict: |
| 940 |
self._is_special = True |
| 941 |
if "comment" in rule_dict and rule_dict["comment"]: |
| 942 |
self._comment = rule_dict['comment'].strip() |
| 943 |
# if the rule is special, we are done now |
| 944 |
if self._is_special: |
| 945 |
return |
| 946 |
|
| 947 |
# make sure each rule includes all required fields |
| 948 |
for field in PG_HBA_REQUIRED_FIELDS: |
| 949 |
if field not in rule_dict: |
| 950 |
raise PgHbaRuleError("All rules need to contain '{0}'".format(field)) |
| 951 |
|
| 952 |
# verify contype and set databases and users |
| 953 |
self._type = _strip_quotes(rule_dict["contype"]) |
| 954 |
if self._type not in PG_HBA_TYPES: |
| 955 |
raise PgHbaRuleValueError("Unknown type {0}".format(self._type)) |
| 956 |
self._database = rule_dict["databases"] |
| 957 |
self._user = rule_dict["users"] |
| 958 |
|
| 959 |
# verify address and netmask if the contype isn't "local" |
| 960 |
if self._type != "local": |
| 961 |
if "address" not in rule_dict: |
| 962 |
raise PgHbaRuleError("If the contype isn't 'local', the rule needs to contain an address") |
| 963 |
self._address, self._address_type, self._prefix_len = handle_address_field(rule_dict["address"]) |
| 964 |
# verify the netmask if there is one |
| 965 |
if "netmask" in rule_dict and rule_dict['netmask']: |
| 966 |
if (self._address_type.startswith("IP") and self._prefix_len > -1) or self._address_type == "hostname": |
| 967 |
raise PgHbaRuleError("Rule can't contain a netmask if address is a full CIDR or hostname") |
| 968 |
self._mask, mask_type, self._prefix_len = handle_netmask_field(rule_dict["netmask"]) |
| 969 |
if mask_type != self._address_type: |
| 970 |
raise PgHbaRuleError("Can't mix IPv4 and IPv6 netmasks and addresses") |
| 971 |
else: |
| 972 |
if self._address_type.startswith("IP") and self._prefix_len == -1: |
| 973 |
raise PgHbaRuleError("If the address is a bare ip-address without a CIDR suffix, " |
| 974 |
"the rule needs to contain a netmask") |
| 975 |
# we ignore address / netmask when contype is 'local' |
| 976 |
|
| 977 |
# verify the method |
| 978 |
self._auth_method = _strip_quotes(rule_dict["method"]) |
| 979 |
if self._auth_method not in PG_HBA_METHODS: |
| 980 |
raise PgHbaRuleValueError("Unknown method {0}".format(self._auth_method)) |
| 981 |
|
| 982 |
if "options" in rule_dict and rule_dict["options"]: |
| 983 |
if isinstance(rule_dict["options"], dict): |
| 984 |
self._auth_options = copy.deepcopy(rule_dict['options']) |
| 985 |
elif isinstance(rule_dict["options"], str): |
| 986 |
self._auth_options = parse_auth_options(tokenize(rule_dict["options"])) |
| 987 |
elif isinstance(rule_dict["options"], list): |
| 988 |
self._auth_options = parse_auth_options(rule_dict["options"]) |
| 989 |
else: |
| 990 |
raise PgHbaValueError( |
| 991 |
"Invalid type {} for options, needs to be either dict, list or str" |
| 992 |
.format(type(rule_dict["options"]))) |
| 993 |
|
| 994 |
|
| 995 |
def _strip_quotes(string): |
| 996 |
if not string: |
| 997 |
return string |
| 998 |
return string[1:-1] if string.startswith("\"") else string |
| 999 |
|
| 1000 |
|
| 1001 |
def parse_auth_options(options): |
| 1002 |
""" |
| 1003 |
Parses a list of strings into a dict. Each input-string needs to be in the format key=value, if that isn't the case |
| 1004 |
it raises an exception. If the same key is used twice, an exception is raised, as well. |
| 1005 |
:param options: A list of strings, where each string is an option |
| 1006 |
:return: A dict mapping str -> str where the key is the part before the first "=" in the input and the value is the |
| 1007 |
rest |
| 1008 |
""" |
| 1009 |
option_dict = {} |
| 1010 |
for option in options: |
| 1011 |
split_option = OPTION_RE.match(_strip_quotes(option)) |
| 1012 |
if not split_option: |
| 1013 |
raise PgHbaRuleValueError( |
| 1014 |
"Found invalid option '{}'. Options need to be in the format 'key=value'".format(option)) |
| 1015 |
if split_option.group(1) in option_dict.keys(): |
| 1016 |
raise PgHbaRuleValueError( |
| 1017 |
"The rule contains two options with the same key ('{0}')".format(split_option.group(1))) |
| 1018 |
option_dict[split_option.group(1)] = split_option.group(2) |
| 1019 |
|
| 1020 |
return option_dict |
| 1021 |
|
| 1022 |
|
| 1023 |
def handle_db_and_user_strings(string): |
| 1024 |
""" |
| 1025 |
Sorts a comma-delimited string of dbs or users alphabetically but returns quoted strings or regexes as-is. |
| 1026 |
:param string: The string to work with |
| 1027 |
:return: The new string |
| 1028 |
""" |
| 1029 |
# if the string is quoted or a regex, we return it unaltered |
| 1030 |
if "\"" in string or string.startswith("/"): |
| 1031 |
return string |
| 1032 |
# we sort the dbs/users alphabetically |
| 1033 |
else: |
| 1034 |
return ",".join(sorted(string.split(","))) |
| 1035 |
|
| 1036 |
|
| 1037 |
def handle_address_field(address): |
| 1038 |
""" |
| 1039 |
Parses and address field and does some basic validation. Will detect IPv4 and IPv6 addresses and networks. |
| 1040 |
Otherwise, assumes it is a hostname and checks for basic invalid characters, but doesn't do a full validation. |
| 1041 |
Will raise an exception if the network has host bits set or is an invalid range in another way. |
| 1042 |
:param address: The address to process |
| 1043 |
:return: A tuple of (address, type, suffix) where type is "IPv4", "IPv6" or "hostname" and suffix is the size of the |
| 1044 |
network if the address is an IP address. If it is a keyword (like "samehost", we still return "hostname" as type) |
| 1045 |
""" |
| 1046 |
suffix = -1 |
| 1047 |
|
| 1048 |
try: |
| 1049 |
# try to parse it to a network |
| 1050 |
ret_addr = ipaddress.ip_network(address, strict=True) |
| 1051 |
ret_type = "IPv" + str(ret_addr.version) |
| 1052 |
if "/" in address: |
| 1053 |
# if it contains a slash, it is a network |
| 1054 |
suffix = ret_addr.prefixlen |
| 1055 |
ret_addr = str(ret_addr.network_address) |
| 1056 |
except ValueError as e: |
| 1057 |
# it is a network, but has host bits set |
| 1058 |
if "has host bits set" in e.args[0]: |
| 1059 |
raise PgHbaValueError("{0} has host bits set".format(address)) |
| 1060 |
# it might be a quoted address or network |
| 1061 |
if address.startswith("\""): |
| 1062 |
ret_addr, ret_type, suffix = handle_address_field(_strip_quotes(address)) |
| 1063 |
# if it was a quoted address, we return it without quotes |
| 1064 |
if ret_type != "hostname": |
| 1065 |
return ret_addr, ret_type, suffix |
| 1066 |
# not a valid network or address, may be a hostname or keyword |
| 1067 |
if re.search(r'[:\\/@+ ]', address) or IPV4_ADDR_RE.match(address): |
| 1068 |
raise PgHbaValueError( |
| 1069 |
"The string '{0}' is neither a valid IP address, network, hostname or keyword".format(address)) |
| 1070 |
else: |
| 1071 |
ret_addr = address |
| 1072 |
ret_type = "hostname" |
| 1073 |
|
| 1074 |
return ret_addr, ret_type, suffix |
| 1075 |
|
| 1076 |
|
| 1077 |
def handle_netmask_field(netmask, raise_not_valid=True): |
| 1078 |
""" |
| 1079 |
Processes a netmask-field and validates it. Will raise an exception if the netmask is a valid IP address, but the |
| 1080 |
binary representation has at least one zero before a one. |
| 1081 |
:param netmask: The netmask to process |
| 1082 |
:param raise_not_valid: If True, an exception is raised if the netmask is not a valid IP address |
| 1083 |
:return: A tuple of (netmask, type, length) where type is "IPv4" or "IPv6" and length is the size of the network |
| 1084 |
if `raise_not_valid` is `False` and the netmask is not a valid IP address, the type-field is "invalid" |
| 1085 |
""" |
| 1086 |
mask = _strip_quotes(netmask) |
| 1087 |
|
| 1088 |
try: |
| 1089 |
mask_as_ip = ipaddress.ip_address(u'{0}'.format(mask)) |
| 1090 |
binvalue = "{0:b}".format(int(mask_as_ip)) |
| 1091 |
if '01' in binvalue: |
| 1092 |
raise PgHbaValueError('IP mask {0} is invalid (binary value has 1 after 0)'.format(mask)) |
| 1093 |
return mask, "IPv" + str(mask_as_ip.version), binvalue.count('1') |
| 1094 |
except ValueError: |
| 1095 |
if raise_not_valid: |
| 1096 |
raise PgHbaValueError("The string '{0}' is not a valid netmask".format(mask)) |
| 1097 |
else: |
| 1098 |
return "", "invalid", -1 |
| 1099 |
|
| 1100 |
|
| 1101 |
def _from_file(file_path): |
| 1102 |
"""Load the rules from a file""" |
| 1103 |
if not os.path.isfile(file_path): |
| 1104 |
return [] |
| 1105 |
with open(file_path, 'r') as file: |
| 1106 |
return rule_list_from_hba_file(file.read()) |
| 1107 |
|
| 1108 |
|
| 1109 |
def write_hba_file(file_path, rule_string, create, module, file_args, diff): |
| 1110 |
""" |
| 1111 |
Writes a set of rules to a file |
| 1112 |
:param file_path: The path to the file to write |
| 1113 |
:param rule_string: The rules rendered into a string to write |
| 1114 |
:param create: If `True` the file will be created if it doesn't exist |
| 1115 |
:param module: The module-object |
| 1116 |
:param file_args: Arguments for the destination file |
| 1117 |
:param diff: Diff to add changes to |
| 1118 |
""" |
| 1119 |
if not (os.path.isfile(file_path) or create): |
| 1120 |
raise module.fail_json(msg="pg_hba file '{0}' doesn't exist. " |
| 1121 |
"Use the create option to autocreate.".format(file_path)) |
| 1122 |
|
| 1123 |
tmpfile = None |
| 1124 |
try: |
| 1125 |
tmpfile = tempfile.NamedTemporaryFile(mode='w', delete=False) |
| 1126 |
tmpfile.write(rule_string) |
| 1127 |
tmpfile.close() |
| 1128 |
try: |
| 1129 |
shutil.copy(tmpfile.name, file_path) |
| 1130 |
except (IOError, OSError) as e: |
| 1131 |
module.fail_json(msg='Failed to write file:\n{0}'.format(e)) |
| 1132 |
finally: |
| 1133 |
# try to remove the temporary file if something goes wrong |
| 1134 |
if tmpfile and os.path.isfile(tmpfile.name): |
| 1135 |
os.unlink(tmpfile.name) |
| 1136 |
|
| 1137 |
module.set_fs_attributes_if_different(file_args, True, diff, expand=False) |
| 1138 |
|
| 1139 |
|
| 1140 |
def render_rule_list(rule_list, delimiter="\t"): |
| 1141 |
""" |
| 1142 |
Turns a list of rules into a string to write into the hba-file |
| 1143 |
:param rule_list: The list of rules to render |
| 1144 |
:param delimiter: The character or sequence used to separate fields |
| 1145 |
:return: A valid string for a pg_hba file |
| 1146 |
""" |
| 1147 |
return "\n".join([r.serialize(delimiter) for r in rule_list]) |
| 1148 |
|
| 1149 |
|
| 1150 |
def rule_list_to_dict_list(rule_list, header_map=None): |
| 1151 |
dict_list = [] |
| 1152 |
for rule in rule_list: |
| 1153 |
if not rule.is_special: |
| 1154 |
dict_list.append(rule.to_dict(header_map=header_map)) |
| 1155 |
return dict_list |
| 1156 |
|
| 1157 |
|
| 1158 |
def search_rule(rules, rule): |
| 1159 |
""" |
| 1160 |
Search a list of rules for a specific key |
| 1161 |
:param rules: The list of rules to search |
| 1162 |
:param rule: The rule to search for, only the key is taken into consideration |
| 1163 |
:return: The index of the rule in the list or `-1` if it wasn't found |
| 1164 |
""" |
| 1165 |
if not rules: |
| 1166 |
return -1 |
| 1167 |
for i in range(0, len(rules)): |
| 1168 |
if rules[i] == rule: |
| 1169 |
return i |
| 1170 |
return -1 |
| 1171 |
|
| 1172 |
|
| 1173 |
def update_rules(new_rules, existing_rules, prepend_rules=False): |
| 1174 |
""" |
| 1175 |
Updates existing rules with new rules. The existing rules are updated in place. |
| 1176 |
This method exists to extract this part of the logic for better testability. |
| 1177 |
:param new_rules: A list of new rules for updating the existing ones |
| 1178 |
:param existing_rules: The list of rules to update |
| 1179 |
:param prepend_rules: Add new rules to the top instead of in the end |
| 1180 |
:return: changed, msgs, diff_before, diff_after |
| 1181 |
""" |
| 1182 |
changed = False |
| 1183 |
msgs = [] |
| 1184 |
diff_after = [] |
| 1185 |
diff_before = [] |
| 1186 |
|
| 1187 |
for rule in new_rules: |
| 1188 |
if 'contype' in rule and rule['contype']: |
| 1189 |
rule['databases'] = handle_db_and_user_strings(rule['databases']) |
| 1190 |
rule['users'] = handle_db_and_user_strings(rule['users']) |
| 1191 |
pg_hba_rule = PgHbaRule(rule_dict=rule) |
| 1192 |
else: |
| 1193 |
if 'comment' in rule: |
| 1194 |
pg_hba_rule = PgHbaRule(tokens="COMMENT", comment=rule['comment']) |
| 1195 |
else: |
| 1196 |
continue |
| 1197 |
index = search_rule(existing_rules, pg_hba_rule) |
| 1198 |
|
| 1199 |
# append rule if it doesn't exist |
| 1200 |
if rule['state'] == "present" and index == -1: |
| 1201 |
msgs.append('Adding rule {0}'.format(pg_hba_rule)) |
| 1202 |
diff_after.append(str(pg_hba_rule)) |
| 1203 |
if prepend_rules: |
| 1204 |
existing_rules.insert(0, pg_hba_rule) |
| 1205 |
else: |
| 1206 |
existing_rules.append(pg_hba_rule) |
| 1207 |
changed = True |
| 1208 |
# update rule if it exists but is not correct |
| 1209 |
elif rule['state'] == "present" and index > -1: |
| 1210 |
if not existing_rules[index].is_identical(pg_hba_rule): |
| 1211 |
msgs.append('Updating rule {0}'.format(pg_hba_rule)) |
| 1212 |
diff_before.append(str(existing_rules[index])) |
| 1213 |
diff_after.append(str(pg_hba_rule)) |
| 1214 |
existing_rules[index] = pg_hba_rule |
| 1215 |
changed = True |
| 1216 |
# delete rule if it exists |
| 1217 |
elif rule['state'] == "absent" and index > -1: |
| 1218 |
msgs.append('Removing rule {0}'.format(pg_hba_rule)) |
| 1219 |
diff_before.append(str(existing_rules[index])) |
| 1220 |
del existing_rules[index] |
| 1221 |
changed = True |
| 1222 |
|
| 1223 |
return changed, msgs, diff_before, diff_after |
| 1224 |
|
| 1225 |
|
| 1226 |
def sort_rules(rules): |
| 1227 |
""" |
| 1228 |
Sorts a list of rules in place. |
| 1229 |
:param rules: A list of rules to sort |
| 1230 |
""" |
| 1231 |
# remove blank lines before sorting |
| 1232 |
index_lst = list(range(0, len(rules))) |
| 1233 |
index_lst.reverse() |
| 1234 |
for i in index_lst: |
| 1235 |
if rules[i].is_special and not rules[i].line and not rules[i].comment: |
| 1236 |
del rules[i] |
| 1237 |
rules.sort() |
| 1238 |
|
| 1239 |
|
| 1240 |
def rules_are_identical(rule_list_one, rule_list_two): |
| 1241 |
""" |
| 1242 |
Compares two lists of rules and returns True if the rules in them are identical and in the same order, returns |
| 1243 |
False otherwise. |
| 1244 |
:param rule_list_one: One of the lists |
| 1245 |
:param rule_list_two: The other list |
| 1246 |
:return: True if the two lists consist of identical rules in the same order |
| 1247 |
""" |
| 1248 |
|
| 1249 |
# if the lists have different lengths, they are not identical |
| 1250 |
if len(rule_list_one) != len(rule_list_two): |
| 1251 |
return False |
| 1252 |
|
| 1253 |
for i in range(0, len(rule_list_one)): |
| 1254 |
# if any rule is not identical to the rule in the same list at the same index, the lists are not identical |
| 1255 |
if not rule_list_one[i].is_identical(rule_list_two[i]): |
| 1256 |
return False |
| 1257 |
|
| 1258 |
# if we didn't find a mismatch, the lists are identical |
| 1259 |
return True |
| 1260 |
|
| 1261 |
|
| 1262 |
def main(): |
| 1263 |
""" |
| 1264 |
This function is the main function of this module |
| 1265 |
""" |
| 1266 |
# argument_spec = postgres_common_argument_spec() |
| 1267 |
argument_spec = dict() |
| 1268 |
argument_spec.update( |
| 1269 |
address=dict(type='str', default='samehost', aliases=['source', 'src']), |
| 1270 |
backup=dict(type='bool', default=False), |
| 1271 |
# FIXME this should be removed and we should use standard methods |
| 1272 |
backup_file=dict(type='str'), |
| 1273 |
contype=dict(type='str', default=None, choices=PG_HBA_TYPES), |
| 1274 |
comment=dict(type='str', default=None), |
| 1275 |
create=dict(type='bool', default=False), |
| 1276 |
databases=dict(type='str', default='all'), |
| 1277 |
dest=dict(type='path', required=True), |
| 1278 |
method=dict(type='str', default='md5', choices=PG_HBA_METHODS), |
| 1279 |
netmask=dict(type='str'), |
| 1280 |
# TODO this can probably be changed to dict without breaking |
| 1281 |
options=dict(type='str'), |
| 1282 |
# DEPRECATED, does nothing |
| 1283 |
keep_comments_at_rules=dict(type='bool', |
| 1284 |
default=True, |
| 1285 |
removed_in_version="5.0.0", |
| 1286 |
removed_from_collection="community.postgresql"), |
| 1287 |
state=dict(type='str', default="present", choices=["absent", "present"]), |
| 1288 |
users=dict(type='str', default='all'), |
| 1289 |
rules=dict(type='list', elements='dict'), |
| 1290 |
rules_behavior=dict(type='str', default='conflict', choices=['combine', 'conflict']), |
| 1291 |
overwrite=dict(type='bool', default=False), |
| 1292 |
sort_rules=dict(type='bool', default=True), |
| 1293 |
) |
| 1294 |
module = AnsibleModule( |
| 1295 |
argument_spec=argument_spec, |
| 1296 |
add_file_common_args=True, |
| 1297 |
supports_check_mode=True |
| 1298 |
) |
| 1299 |
if IPADDRESS_IMP_ERR is not None: |
| 1300 |
module.fail_json(msg=missing_required_lib('ipaddress'), exception=IPADDRESS_IMP_ERR) |
| 1301 |
|
| 1302 |
create = bool(module.params["create"] or module.check_mode) |
| 1303 |
if module.check_mode: |
| 1304 |
backup = False |
| 1305 |
backup_file = "" |
| 1306 |
else: |
| 1307 |
backup = module.params['backup'] |
| 1308 |
backup_file = module.params['backup_file'] |
| 1309 |
dest = module.params["dest"] |
| 1310 |
rules = module.params["rules"] |
| 1311 |
rules_behavior = module.params["rules_behavior"] |
| 1312 |
overwrite = module.params["overwrite"] |
| 1313 |
sorted_rules = module.params["sort_rules"] |
| 1314 |
|
| 1315 |
ret = {'msgs': []} |
| 1316 |
diff = {'before': {'file': dest, 'pg_hba': []}, |
| 1317 |
'after': {'file': dest, 'pg_hba': []}} |
| 1318 |
pg_hba_rules = [] |
| 1319 |
try: |
| 1320 |
pg_hba_rules = _from_file(dest) |
| 1321 |
except (PgHbaError, TokenizerException) as error: |
| 1322 |
# if overwrite is true, we don't care that we can't parse the file and just start with an empty one |
| 1323 |
if not overwrite: |
| 1324 |
module.fail_json(msg='Error reading file:\n{0}'.format(error)) |
| 1325 |
|
| 1326 |
rule_keys = [ |
| 1327 |
'address', |
| 1328 |
'comment', |
| 1329 |
'contype', |
| 1330 |
'databases', |
| 1331 |
'method', |
| 1332 |
'netmask', |
| 1333 |
'options', |
| 1334 |
'state', |
| 1335 |
'users' |
| 1336 |
] |
| 1337 |
new_rules = [] |
| 1338 |
if rules is None or not rules: |
| 1339 |
# if both of those aren't set, we just read the rules from the file |
| 1340 |
if not module.params['contype'] and not module.params['comment']: |
| 1341 |
new_rules = [] |
| 1342 |
else: |
| 1343 |
single_rule = dict() |
| 1344 |
for key in rule_keys: |
| 1345 |
single_rule[key] = module.params[key] |
| 1346 |
new_rules = [single_rule] |
| 1347 |
else: |
| 1348 |
if rules_behavior == 'conflict': |
| 1349 |
# it's ok if the module default is set |
| 1350 |
used_rule_keys = [key for key in rule_keys if module.params[key] != argument_spec[key].get('default', None)] |
| 1351 |
if len(used_rule_keys) > 0: |
| 1352 |
module.fail_json(msg='conflict: either argument "rules_behavior" needs to be changed or "rules" must' |
| 1353 |
' not be set or {0} must not be set'.format(used_rule_keys)) |
| 1354 |
|
| 1355 |
for index, rule in enumerate(rules): |
| 1356 |
# alias handling |
| 1357 |
address_keys = [key for key in rule.keys() if key in ('address', 'source', 'src')] |
| 1358 |
if len(address_keys) > 1: |
| 1359 |
module.fail_json(msg='rule number {0} of the "rules" argument ({1}) uses ambiguous settings: ' |
| 1360 |
'{2} are aliases, only one is allowed'.format(index, address_keys, rule)) |
| 1361 |
if len(address_keys) == 1: |
| 1362 |
address = rule[address_keys[0]] |
| 1363 |
del rule[address_keys[0]] |
| 1364 |
rule['address'] = address |
| 1365 |
|
| 1366 |
for key in rule_keys: |
| 1367 |
if key not in rule: |
| 1368 |
if rules_behavior == 'combine': |
| 1369 |
# use user-supplied defaults or module defaults |
| 1370 |
rule[key] = module.params[key] |
| 1371 |
else: |
| 1372 |
# use module defaults |
| 1373 |
rule[key] = argument_spec[key].get('default', None) |
| 1374 |
|
| 1375 |
new_rules.append(rule) |
| 1376 |
# TODO |
| 1377 |
# we split users and databases delimited with ',', but pg_hba.conf can handle them with commas, |
| 1378 |
# so in the future we might want to just put them in as one line |
| 1379 |
rules = [] |
| 1380 |
for rule in new_rules: |
| 1381 |
databases = rule['databases'] if rule['databases'].startswith("\"") else rule['databases'].split(",") |
| 1382 |
users = rule['users'] if rule['users'].startswith("\"") else rule["users"].split(",") |
| 1383 |
for database in databases: |
| 1384 |
for user in users: |
| 1385 |
if len(tokenize(database)) != 1: |
| 1386 |
module.fail_json(msg="Invalid string for database: {0}".format(database)) |
| 1387 |
if len(tokenize(user)) != 1: |
| 1388 |
module.fail_json(msg="Invalid string for users: {0}".format(user)) |
| 1389 |
new_rule = copy.deepcopy(rule) |
| 1390 |
new_rule['databases'] = database |
| 1391 |
new_rule['users'] = user |
| 1392 |
rules.append(new_rule) |
| 1393 |
|
| 1394 |
changed = False |
| 1395 |
try: |
| 1396 |
if overwrite: |
| 1397 |
new_rules = from_rule_list(rules) |
| 1398 |
# if sorting is turned on, we need to compare the sorted list |
| 1399 |
if sorted_rules: |
| 1400 |
sort_rules(new_rules) |
| 1401 |
# compare the new rules to existing rules, if they are not identical, we overwrite everything |
| 1402 |
changed = not rules_are_identical(new_rules, pg_hba_rules) |
| 1403 |
if changed: |
| 1404 |
pg_hba_rules = new_rules |
| 1405 |
else: |
| 1406 |
changed, msgs, diff_before, diff_after = update_rules(rules, pg_hba_rules) |
| 1407 |
ret['msgs'] += msgs |
| 1408 |
diff['before']['pg_hba'] += diff_before |
| 1409 |
diff['after']['pg_hba'] += diff_after |
| 1410 |
except (PgHbaError, TokenizerException) as error: |
| 1411 |
module.fail_json(msg='Error modifying rules:\n{0}'.format(error)) |
| 1412 |
|
| 1413 |
ret['changed'] = changed |
| 1414 |
if not changed: |
| 1415 |
hba_string = render_rule_list(pg_hba_rules) |
| 1416 |
else: |
| 1417 |
if sorted_rules: |
| 1418 |
sort_rules(pg_hba_rules) |
| 1419 |
hba_string = render_rule_list(pg_hba_rules) |
| 1420 |
ret['msgs'].append('Changed') |
| 1421 |
# file_args = None |
| 1422 |
file_args = module.load_file_common_arguments(module.params) |
| 1423 |
if not module.check_mode: |
| 1424 |
if backup and os.path.exists(dest): |
| 1425 |
ret['msgs'].append('Creating Backup') |
| 1426 |
backup_file_args = module.load_file_common_arguments(module.params) |
| 1427 |
if not backup_file: |
| 1428 |
ext = time.strftime("%Y-%m-%d@%H:%M:%S~", time.localtime(time.time())) |
| 1429 |
backup_file = '%s.%s.%s' % (dest, os.getpid(), ext) |
| 1430 |
try: |
| 1431 |
shutil.copy(dest, backup_file) |
| 1432 |
except (IOError, OSError) as e: |
| 1433 |
module.fail_json(msg='Failed to create backup:\n{0}'.format(e)) |
| 1434 |
backup_file_args['path'] = backup_file |
| 1435 |
module.set_fs_attributes_if_different(backup_file_args, True, diff, expand=False) |
| 1436 |
ret['backup_file'] = backup_file |
| 1437 |
|
| 1438 |
ret['msgs'].append('Writing') |
| 1439 |
write_hba_file(dest, hba_string, create, module, file_args, diff) |
| 1440 |
ret['diff'] = diff |
| 1441 |
elif not os.path.isfile(dest) and not create: |
| 1442 |
module.warn("The file '{}' doesn't exist and `create` is `false`. This will cause the module to fail" |
| 1443 |
"when not running in check-mode. Set `create: true` to prevent this and create the file." |
| 1444 |
.format(dest)) |
| 1445 |
|
| 1446 |
ret['pg_hba_string'] = hba_string |
| 1447 |
ret['pg_hba'] = rule_list_to_dict_list(pg_hba_rules, header_map=PG_HBA_HDR_MAP) |
| 1448 |
module.exit_json(**ret) |
| 1449 |
|
| 1450 |
|
| 1451 |
if __name__ == '__main__': |
| 1452 |
main() |