
    Vh][                     p    d dl mZmZmZ eZdZdZd dlZd dl	m
Z
 d dlmZ d Zd Zd	 Zed
k(  r e        yy)    )absolute_importdivisionprint_functionae  
module: ufw
short_description: Manage firewall with UFW
description:
  - Manage firewall with UFW.
author:
  - Aleksey Ovcharenko (@ovcharenko)
  - Jarno Keskikangas (@pyykkis)
  - Ahti Kitsik (@ahtik)
notes:
  - See C(man ufw) for more examples.
  - B(Warning:) Whilst the module itself can be run using concurrent strategies, C(ufw) does not support concurrency, as firewall
    rules are meant to be ordered and parallel executions do not guarantee order. B(Do not use concurrency:) The results are
    unpredictable and the module may fail silently if you do.
requirements:
  - C(ufw) package
extends_documentation_fragment:
  - community.general.attributes
attributes:
  check_mode:
    support: full
  diff_mode:
    support: none
options:
  state:
    description:
      - V(enabled) reloads firewall and enables firewall on boot.
      - V(disabled) unloads firewall and disables firewall on boot.
      - V(reloaded) reloads firewall.
      - V(reset) disables and resets firewall to installation defaults.
    type: str
    choices: [disabled, enabled, reloaded, reset]
  default:
    description:
      - Change the default policy for incoming or outgoing traffic.
    type: str
    choices: [allow, deny, reject]
    aliases: [policy]
  direction:
    description:
      - Select direction for a rule or default policy command. Mutually exclusive with O(interface_in) and O(interface_out).
    type: str
    choices: [in, incoming, out, outgoing, routed]
  logging:
    description:
      - Toggles logging. Logged packets use the LOG_KERN syslog facility.
    type: str
    choices: ['on', 'off', low, medium, high, full]
  insert:
    description:
      - Insert the corresponding rule as rule number NUM.
      - Note that ufw numbers rules starting with 1.
      - If O(delete=true) and a value is provided for O(insert), then O(insert) is ignored.
    type: int
  insert_relative_to:
    description:
      - Allows to interpret the index in O(insert) relative to a position.
      - V(zero) interprets the rule number as an absolute index (that is, 1 is the first rule).
      - V(first-ipv4) interprets the rule number relative to the index of the first IPv4 rule, or relative to the position
        where the first IPv4 rule would be if there is currently none.
      - V(last-ipv4) interprets the rule number relative to the index of the last IPv4 rule, or relative to the position where
        the last IPv4 rule would be if there is currently none.
      - V(first-ipv6) interprets the rule number relative to the index of the first IPv6 rule, or relative to the position
        where the first IPv6 rule would be if there is currently none.
      - V(last-ipv6) interprets the rule number relative to the index of the last IPv6 rule, or relative to the position where
        the last IPv6 rule would be if there is currently none.
    type: str
    choices: [first-ipv4, first-ipv6, last-ipv4, last-ipv6, zero]
    default: zero
  rule:
    description:
      - Add firewall rule.
    type: str
    choices: [allow, deny, limit, reject]
  log:
    description:
      - Log new connections matched to this rule.
    type: bool
    default: false
  from_ip:
    description:
      - Source IP address.
    type: str
    default: any
    aliases: [from, src]
  from_port:
    description:
      - Source port.
    type: str
  to_ip:
    description:
      - Destination IP address.
    type: str
    default: any
    aliases: [dest, to]
  to_port:
    description:
      - Destination port.
    type: str
    aliases: [port]
  proto:
    description:
      - TCP/IP protocol.
      - The value V(vrrp) is supported since community.general 10.3.0.
    type: str
    choices: [any, tcp, udp, ipv6, esp, ah, gre, igmp, vrrp]
    aliases: [protocol]
  name:
    description:
      - Use profile located in C(/etc/ufw/applications.d).
    type: str
    aliases: [app]
  delete:
    description:
      - Delete rule.
      - If O(delete=true) and a value is provided for O(insert), then O(insert) is ignored.
    type: bool
    default: false
  interface:
    description:
      - Specify interface for the rule. The direction (in or out) used for the interface depends on the value of O(direction).
        See O(interface_in) and O(interface_out) for routed rules that needs to supply both an input and output interface.
        Mutually exclusive with O(interface_in) and O(interface_out).
    type: str
    aliases: [if]
  interface_in:
    description:
      - Specify input interface for the rule. This is mutually exclusive with O(direction) and O(interface). However, it is
        compatible with O(interface_out) for routed rules.
    type: str
    aliases: [if_in]
    version_added: '0.2.0'
  interface_out:
    description:
      - Specify output interface for the rule. This is mutually exclusive with O(direction) and O(interface). However, it
        is compatible with O(interface_in) for routed rules.
    type: str
    aliases: [if_out]
    version_added: '0.2.0'
  route:
    description:
      - Apply the rule to routed/forwarded packets.
    type: bool
    default: false
  comment:
    description:
      - Add a comment to the rule. Requires UFW version >=0.35.
    type: str
a  
- name: Allow everything and enable UFW
  community.general.ufw:
    state: enabled
    policy: allow

- name: Set logging
  community.general.ufw:
    logging: 'on'

# Sometimes it is desirable to let the sender know when traffic is
# being denied, rather than simply ignoring it. In these cases, use
# reject instead of deny. In addition, log rejected connections:
- community.general.ufw:
    rule: reject
    port: auth
    log: true

# ufw supports connection rate limiting, which is useful for protecting
# against brute-force login attacks. ufw will deny connections if an IP
# address has attempted to initiate 6 or more connections in the last
# 30 seconds. See  http://www.debian-administration.org/articles/187
# for details. Typical usage is:
- community.general.ufw:
    rule: limit
    port: ssh
    proto: tcp

# Allow OpenSSH. (Note that as ufw manages its own state, simply removing
# a rule=allow task can leave those ports exposed. Either use delete=true
# or a separate state=reset task)
- community.general.ufw:
    rule: allow
    name: OpenSSH

- name: Delete OpenSSH rule
  community.general.ufw:
    rule: allow
    name: OpenSSH
    delete: true

- name: Deny all access to port 53
  community.general.ufw:
    rule: deny
    port: '53'

- name: Allow port range 60000-61000
  community.general.ufw:
    rule: allow
    port: 60000:61000
    proto: tcp

- name: Allow all access to tcp port 80
  community.general.ufw:
    rule: allow
    port: '80'
    proto: tcp

- name: Allow all access from RFC1918 networks to this host
  community.general.ufw:
    rule: allow
    src: '{{ item }}'
  loop:
    - 10.0.0.0/8
    - 172.16.0.0/12
    - 192.168.0.0/16

- name: Deny access to udp port 514 from host 1.2.3.4 and include a comment
  community.general.ufw:
    rule: deny
    proto: udp
    src: 1.2.3.4
    port: '514'
    comment: Block syslog

- name: Allow incoming access to eth0 from 1.2.3.5 port 5469 to 1.2.3.4 port 5469
  community.general.ufw:
    rule: allow
    interface: eth0
    direction: in
    proto: udp
    src: 1.2.3.5
    from_port: '5469'
    dest: 1.2.3.4
    to_port: '5469'

# Note that IPv6 must be enabled in /etc/default/ufw for IPv6 firewalling to work.
- name: Deny all traffic from the IPv6 2001:db8::/32 to tcp port 25 on this host
  community.general.ufw:
    rule: deny
    proto: tcp
    src: 2001:db8::/32
    port: '25'

- name: Deny all IPv6 traffic to tcp port 20 on this host
  # this should be the first IPv6 rule
  community.general.ufw:
    rule: deny
    proto: tcp
    port: '20'
    to_ip: "::"
    insert: 0
    insert_relative_to: first-ipv6

- name: Deny all IPv4 traffic to tcp port 20 on this host
  # This should be the third to last IPv4 rule
  # (insert: -1 addresses the second to last IPv4 rule;
  #  so the new rule will be inserted before the second
  #  to last IPv4 rule, and will be come the third to last
  #  IPv4 rule.)
  community.general.ufw:
    rule: deny
    proto: tcp
    port: '20'
    to_ip: "::"
    insert: -1
    insert_relative_to: last-ipv4

# Can be used to further restrict a global FORWARD policy set to allow
- name: Deny forwarded/routed traffic from subnet 1.2.3.0/24 to subnet 4.5.6.0/24
  community.general.ufw:
    rule: deny
    route: true
    src: 192.0.2.0/24
    dest: 198.51.100.0/24
N)
itemgetter)AnsibleModulec                  :    d} | dz  } t        j                  |       S )Nz1((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}z((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])recompilers    i/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/ufw.pycompile_ipv4_regexpr   *  s     <A	44A::a=    c                      d} | dz  } | dz  } | dz  } | dz  } | dz  } | dz  } | dz  } | d	z  } | d
z  } t        j                  |       S )z
    validation pattern provided by :
    https://stackoverflow.com/questions/53497/regular-expression-that-matches-
    valid-ipv6-addresses#answer-17871737
    zC(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:zC|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}zD(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4})zC{1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]zD{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]zC{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4})zC{0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]zB|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}zC[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}z7[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))r	   r   s    r   compile_ipv6_regexpr   0  s{     	OA	OOA	PPA	OOA	PPA	OOA	OOA	NNA	OOA	CCA::a=r   c                  :  01234567 g d} t        t        d{i dt        dg d      dt        ddgg d	      d
t        dg d      dt        dg d      dt        dd      dt        dd      dt        d      dt        g dd      dt        dg d      dt        ddg      dt        dd g      d!t        dd"g      d#t        dd      d$t        dd%d&d'g(      d)t        d      d*t        dd%d+d,g(      d-t        dd.g      d/t        dd0gg d1	      d2t        dd3g      d4t        d      d5g d6ddgdd!gg| gt        d78      9      6g 0t               4t               5d: }d; }d< }d= 224fd>}25fd?}4fd@}5fdA}d|06fdB	113fdC}167fdD}	6j                  }
| D ci c]  }|
|   s	||
|    }}6j                  dEd5      76j                  dFd5      3 17gdGgg      } |       }d}|j                         D ]o  \  }}7g6j                  dHgg}|dk(  rSdIdJdKdLd}|dMv rd5}6j                  r'|j                  dN      dOk7  }|dPk(  r|s	|dQk(  sW|rZd5}] 1|dRg||   ggz          p|d
k(  r{t        j                  dS|      }|rD|j                  dT      }|j                  dU      }|dVk7  r|dVk(  rd5}n|dWk7  r||k7  rd5}n
|dVk7  rd5}nd5}6j                  r 1||g|ggz          |dk(  r|
d   dXvr6j                  dYZ       6j                  rtd[}t        j                  ||      }|Vi }|j                  dU      |d\<   |j                  dT      |d]<   |j                  d^      |d_<   ||
d   xs d\   }||dPfvsd5}d5} 1||g|g|
d   ggz          |dk(  s|
d   d`vr6j                  daZ       |
d   s|
d   r|
d!   r6j                  dbZ       |j                  6j                  |
d         dg       |j                  6j                  |
d         dg       |
d   |
d   s{|
d   }|dk(  r|
d   }nR6j                  7dcddg      \  }}}t        j                   de      }|j#                         D  cg c]  } |j%                  |       df| v f }!} |!D "#cg c]$  \  }"}#|"s	t'        |"j                  dU            |#f& }!}"}#|!rt)        |!D $#cg c]  \  }$}#|$	 c}#}$      ndg}%t+        dh |!D              }&t+        di |!D              }'|djk(  rdU}(ng|dkk(  r&|&r!t)        |!D $#cg c]
  \  }$}#|#r	|$ c}#}$      ndU}(n<|dlk(  r)|&r$t)        |!D $#cg c]
  \  }$}#|#r	|$ c}#}$      dUz   ndU}(n|dmk(  r	|'r|%n|%dUz   }(|
d   (z   }||%kD  rd }|j                  |d udn|z  g       |j                  |g       |j                  |
d   do|
d   z  g       |j                  |
d   dp|
d   z  g       |j                  |
d   dq|
d   z  g       |j                  |
d!   dr|
d!   z  g       |j                  6j                  |
d#         d#g       dsD ]   \  }})|
|   }|j                  ||)|z  g       "  |	       \  }*}+}|*dgk(  r|+dtk\  s|*dgkD  r|j                  |
d4   du|
d4   z  g        1|      },6j                  st-         |dv|,            }-|-dgkD  r|-t-        |,j#                  d5            k(  r |dw|,      }, ||
d$         s ||
d*         r ||       ||,      k7  s6d5}: ||
d$         s ||
d*         r ||       ||,      k7  scd5}g||,k7  snd5}r 6j                  r6j/                  |0x      S  17gdcgdygg      }.|s |       }/||.k7  xs ||/k7  }6j/                  |0|.j1                         z      S c c}w c c} w c c}#}"w c c}#}$w c c}#}$w c c}#}$w )}N)statedefaultruleloggingr   str)enableddisabledreloadedreset)typechoicesr   policy)allowdenyreject)r   aliasesr   r   )fullhighlowmediumoffon	direction)inincomingoutoutgoingrouteddeleteboolF)r   r   routeinsertint)r   insert_relative_to)zero
first-ipv4	last-ipv4
first-ipv6	last-ipv6r6   )r   r   r   )r    r!   limitr"   	interfaceif)r   r#   interface_inif_ininterface_outif_outlogfrom_ipanyfromsrc)r   r   r#   	from_portto_ipdesttoto_portportprotoprotocol)	ahrD   espipv6tcpudpgreigmpvrrpnameappcommentT)rW   rM   r   )r*   )r<   )argument_specsupports_check_modemutually_exclusiverequired_one_ofrequired_byc                     dj                  |j                  d      D cg c]  }|j                  |       s| c}      S c c}w N T)join
splitlines
startswithpatterncontentlines      r   filter_line_that_not_start_withz-main.<locals>.filter_line_that_not_start_witho  s6    ww););D)A^T__U\E]^__^
   AAc                 T    |j                  d      D cg c]	  }| |v s| c}S c c}w )NT)rc   re   s      r   filter_line_that_containsz'main.<locals>.filter_line_that_containsr  s'    !(!3!3D!9MW_MMMs   	%%c                     dj                  |j                  d      D cg c]  }|j                  |       r| c}      S c c}w r`   )rb   rc   containsre   s      r   filter_line_that_not_containsz+main.<locals>.filter_line_that_not_containsu  s6    ww););D)A`W^I_`aa`rj   c                 z    dj                  |j                  d      D cg c]  } | |      | c}      S c c}w r`   )rb   rc   )
match_funcrg   rh   s      r   filter_line_that_match_funcz)main.<locals>.filter_line_that_match_funcx  s5    ww););D)AbZPTEUEabccbs   88c                 *     j                   |       S Nsearch)rg   rr   ipv4_regexps    r   filter_line_that_contains_ipv4z,main.<locals>.filter_line_that_contains_ipv4{      *;+=+=wGGr   c                 *     j                   |       S rt   ru   )rg   rr   ipv6_regexps    r   filter_line_that_contains_ipv6z,main.<locals>.filter_line_that_contains_ipv6~  ry   r   c                 *    j                  |       d uS rt   match)iprw   s    r   is_starting_by_ipv4z!main.<locals>.is_starting_by_ipv4        $D00r   c                 *    j                  |       d uS rt   r~   )r   r{   s    r   is_starting_by_ipv6z!main.<locals>.is_starting_by_ipv6  r   r   c           
         dj                  t        t        d      t        t        d      |                   } j	                  |        j                  | ddi      \  }}}|dk7  r|sj                  |xs |       |S )N r   LANGC)environ_update)msgcommands)rb   mapr   filterappendrun_command	fail_json)cmdignore_errorrcr-   errcmdsmodules        r   executezmain.<locals>.execute  sw    hhs:b>6*Q-+EFGC++C+NS#7<d;
r   c                  z    g d} gdgdgg}|j                  | D cg c]  }|g c}        |d      S c c}w )N)z/lib/ufw/user.rulesz/lib/ufw/user6.rulesz/etc/ufw/user.rulesz/etc/ufw/user6.rulesz/var/lib/ufw/user.rulesz/var/lib/ufw/user6.rulesz-hz'^### tuple'T)r   )extend)user_rules_filesr   fr   grep_bins      r   get_current_ruleszmain.<locals>.get_current_rules  sL    8 zD6N#34

!12AQC23s.. 3s   
8c                      	gdgg      } | j                  d      D cg c]  }|j                         dk7  s| }}t        |      dk(  rj                  dd|        t	        j
                  d|d         }|j                  dd|        t        |j                  d            }t        |j                  d	            }d}|j                  d
      t        |j                  d
            }|||fS c c}w )zU
        Returns the major and minor version of ufw installed on the system.
        z	--version
ra   r   zFailed to get ufw version.)r   r   r-   z!^ufw.+(\d+)\.(\d+)(?:\.(\d+))?.*$         )splitstriplenr   r
   rv   r4   group)
r-   xlinesmatchesmajorminorrevr   r   ufw_bins
          r   ufw_versionzmain.<locals>.ufw_version  s     y;-01IIdO?qqwwyB??u:?!=!M))@%(K?!=!M GMM!$%GMM!$%=='gmmA&'CeS   @s
   C7C7ufwgrepzstatus verbosez	--dry-runenabledisablereloadr   )r   r   z activer   r   r   z-fz#Logging: (on|off)(?: \(([a-z]+)\))?r   r   r(   r)   )r.   r,   r/   NznFor default, direction must be one of "outgoing", "incoming" and "routed", or direction must not be specified.)r   ztDefault: (deny|allow|reject) \(incoming\), (deny|allow|reject) \(outgoing\), (deny|allow|reject|disabled) \(routed\)r,   r.   r   r/   )r+   r-   NzWFor rules, direction must be one of "in" and "out", or direction must not be specified.z;Only route rules can combine interface_in and interface_outstatusnumberedz^\[ *([0-9]+)\] z(v6)r   c              3   (   K   | ]
  \  }}|   y wrt    .0norQ   s      r   	<genexpr>zmain.<locals>.<genexpr>  s     "D
Tt8"Ds   c              3   &   K   | ]	  \  }}|  y wrt   r   r   s      r   r   zmain.<locals>.<genexpr>  s     "@JR4"@s   r7   r8   r9   r:   z	insert %sz%szon %szin on %sz	out on %s))rC   zfrom %s)rG   port %s)rH   zto %s)rK   r   )rM   zproto %s)rW   zapp '%s'#   zcomment '%s'Skippingz	### tuple)changedr   verbose)r   r   r   r   )F)r   dictr   r   paramsget_bin_pathitems
check_modefindr
   rv   r   r   r   booleanr   r   rc   r   r4   maxrD   r   	exit_jsonrstrip)8command_keysri   rl   ro   rx   r|   r   r   r   r   r   keyr   	pre_state	pre_rulesr   commandvaluer   statesufw_enabledextractcurrent_levelcurrent_on_off_valueregexpcurrent_default_valuesvrelative_to_cmd	insert_todummynumbered_statenumbered_line_rerh   r   matcherrQ   r   last_numberhas_ipv4has_ipv6relative_totemplate	ufw_major	ufw_minor	rules_drynb_skipping_line
post_state
post_rulesr   r   rr   r   rw   r{   r   r   s8                                                   @@@@@@@@r   mainr   C  su	   :L 
E+WX
ehZA\]
 e-[\
 /^_	

 VU3
 FE2
 U#
  $,jtz{
 5*NO
 v6
 57)<
 EH:>
 &%0
 eUVUOL
 &
  E564.I!
" efX6#
$ EJ<  BC  D%
& 55'2'
( e$)
, !(.)/*	
 '%
?"FH D%'K%'K`NbdHH11	/!. ]]F,8HSF3KVC[ HHH !!%.G""640H '%5$678I!#IG %NN, B'%y6,,k:;g!)y"*W>F --  'nnY72=Z'KUi=OXc"Gvu778	!ii F	RG 'a 0'.}}Q'7$E>+u4"&$5M+A"&)U2"G$$y5'223	!k"*RR    &V   W   Q))FI6&-/*9@q9I*:69@q9I*:67>}}Q7G*84.vk/B/PjQA
 33"&"Gy5'F;4G3HIIJk"*==  %~ '?vn'=&BY   &B  C JJvg7ABJJvh'78(CDh+F84D"()=">"f, &x 0I5;5G5GRZ\fHg5h2UNE')zz2E'F$XfXqXqXstPT.44T:FdNKtEtRWc[bc'--"23T:cEcGL#E&Bjr4r&B"CRSK""De"DDH""@%"@@H&,6&'(K7W_c*R*2tT2*R&Sef(L8[cc*R*2tT2*R&SVW&Wij(K75=k;QR? &x 0; >I ;. %)	

IT1;3JKLJJwJJ{+TF;4G-GHIJJ{+Wvk7J-JKLJJ~.
VN=S0STUJJ/vo?V1VWXJJve}5u=>$Q 8h s

E8u#567	8 +6-'Iy%Q9?y1}

F9-~y@Q/QRSI  #&'@Y'W#X (1,1ASI]I]^bIcEd1d ?Y WI*6)+<=ATU[\cUdAe9)DHfgpHqq&*G,VI->?CVW]^eWfCg9)DHfgpHqq&*G"i/"&EB'J $??wi(i[AB
*,J J.LI4KG$JDUDUDWXXs Ir uc&B +S*Rs<   
_;_;/` 
``
`
`(`
``__main__)
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESr
   operatorr   ansible.module_utils.basicr   r   r   r   __name__r   r   r   <module>r      sV    A @Tl}~ 
  4&NYb zF r   