summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/network/fortios/fortios_ipv4_policy.py
blob: 69cb0d6e313ebf9cd8181604e000f2225b01840e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#!/usr/bin/python
#
# Ansible module to manage IPv4 policy objects in fortigate devices
# (c) 2017, Benjamin Jolivot <bjolivot@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible.  If not, see <http://www.gnu.org/licenses/>.
#

ANSIBLE_METADATA = {'metadata_version': '1.0',
                    'status': ['preview'],
                    'supported_by': 'community'}


DOCUMENTATION = """
---
module: fortios_ipv4_policy
version_added: "2.3"
author: "Benjamin Jolivot (@bjolivot)"
short_description: Manage IPv4 policy objects on Fortinet FortiOS firewall devices
description:
  - This module provides management of firewall IPv4 policies on FortiOS devices.
extends_documentation_fragment: fortios
options:
  id:
    description:
      - "Policy ID.
        Warning: policy ID number is different than Policy sequence number.
        The policy ID is the number assigned at policy creation.
        The sequence number represents the order in which the Fortigate will evaluate the rule for policy enforcement,
        and also the order in which rules are listed in the GUI and CLI.
        These two numbers do not necessarily correlate: this module is based off policy ID.
        TIP: policy ID can be viewed in the GUI by adding 'ID' to the display columns"
    required: true
  state:
    description:
      - Specifies if policy I(id) need to be added or deleted.
    choices: ['present', 'absent']
    default: present
  src_intf:
    description:
      - Specifies source interface name.
    default: any
  dst_intf:
    description:
      - Specifies destination interface name.
    default: any
  src_addr:
    description:
      - Specifies source address (or group) object name(s). Required when I(state=present).
  src_addr_negate:
    description:
      - Negate source address param.
    default: false
    choices: ["true", "false"]
  dst_addr:
    description:
      - Specifies destination address (or group) object name(s). Required when I(state=present).
  dst_addr_negate:
    description:
      - Negate destination address param.
    default: false
    choices: ["true", "false"]
  policy_action:
    description:
      - Specifies accept or deny action policy. Required when I(state=present).
    choices: ['accept', 'deny']
    aliases: ['action']
  service:
    description:
      - "Specifies policy service(s), could be a list (ex: ['MAIL','DNS']). Required when I(state=present)."
    aliases:
      - services
  service_negate:
    description:
      - Negate policy service(s) defined in service value.
    default: false
    choices: ["true", "false"]
  schedule:
    description:
      - defines policy schedule.
    default: 'always'
  nat:
    description:
      - Enable or disable Nat.
    default: false
    choices: ["true", "false"]
  fixedport:
    description:
      - Use fixed port for nat.
    default: false
    choices: ["true", "false"]
  poolname:
    description:
      - Specifies NAT pool name.
  av_profile:
    description:
      - Specifies Antivirus profile name.
  webfilter_profile:
    description:
      - Specifies Webfilter profile name.
  ips_sensor:
    description:
      - Specifies IPS Sensor profile name.
  application_list:
    description:
      - Specifies Application Control name.
  comment:
    description:
      - free text to describe policy.
notes:
  - This module requires pyFG library.
"""

EXAMPLES = """
- name: Allow external DNS call
  fortios_ipv4_policy:
    host: 192.168.0.254
    username: admin
    password: password
    id: 42
    srcaddr: internal_network
    dstaddr: all
    service: dns
    nat: True
    state: present
    policy_action: accept

- name: Public Web
  fortios_ipv4_policy:
    host: 192.168.0.254
    username: admin
    password: password
    id: 42
    srcaddr: all
    dstaddr: webservers
    services:
      - http
      - https
    state: present
    policy_action: accept
"""

RETURN = """
firewall_address_config:
  description: full firewall adresses config string
  returned: always
  type: string
change_string:
  description: The commands executed by the module
  returned: only if config changed
  type: string
msg_error_list:
  description: "List of errors returned by CLI (use -vvv for better readability)."
  returned: only when error
  type: string
"""

from ansible.module_utils.fortios import fortios_argument_spec, fortios_required_if
from ansible.module_utils.fortios import backup, AnsibleFortios

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception


def main():
    argument_spec = dict(
        comment                   = dict(type='str'),
        id                        = dict(type='int', required=True),
        src_intf                  = dict(default='any'),
        dst_intf                  = dict(default='any'),
        state                     = dict(choices=['present', 'absent'], default='present'),
        src_addr                  = dict(type='list'),
        dst_addr                  = dict(type='list'),
        src_addr_negate           = dict(type='bool', default=False),
        dst_addr_negate           = dict(type='bool', default=False),
        policy_action             = dict(choices=['accept','deny'], aliases=['action']),
        service                   = dict(aliases=['services'], type='list'),
        service_negate            = dict(type='bool', default=False),
        schedule                  = dict(type='str', default='always'),
        nat                       = dict(type='bool', default=False),
        fixedport                 = dict(type='bool', default=False),
        poolname                  = dict(type='str'),
        av_profile                = dict(type='str'),
        webfilter_profile         = dict(type='str'),
        ips_sensor                = dict(type='str'),
        application_list          = dict(type='str'),
    )

    #merge global required_if & argument_spec from module_utils/fortios.py
    argument_spec.update(fortios_argument_spec)

    ipv4_policy_required_if = [
        ['state', 'present', ['src_addr', 'dst_addr', 'policy_action', 'service']],
    ]

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=fortios_required_if + ipv4_policy_required_if ,
    )

    #init forti object
    fortigate = AnsibleFortios(module)

    #Security policies root path
    config_path = 'firewall policy'

    #test params
    #NAT related
    if not module.params['nat']:
        if module.params['poolname']:
            module.fail_json(msg='Poolname param requires NAT to be true.')
        if module.params['fixedport']:
            module.fail_json(msg='Fixedport param requires NAT to be true.')

    #id must be str(int) for pyFG to work
    policy_id = str(module.params['id'])

    #load config
    fortigate.load_config(config_path)

    #Absent State
    if module.params['state'] == 'absent':
        fortigate.candidate_config[config_path].del_block(policy_id)

    #Present state
    elif module.params['state'] == 'present':
        new_policy = fortigate.get_empty_configuration_block(policy_id, 'edit')

        #src / dest / service / interfaces
        new_policy.set_param('srcintf', '"%s"' % (module.params['src_intf']))
        new_policy.set_param('dstintf', '"%s"' % (module.params['dst_intf']))


        new_policy.set_param('srcaddr', " ".join('"' + item + '"' for item in module.params['src_addr']))
        new_policy.set_param('dstaddr', " ".join('"' + item + '"' for item in module.params['dst_addr']))
        new_policy.set_param('service', " ".join('"' + item + '"' for item in module.params['service']))

        # negate src / dest / service
        if module.params['src_addr_negate']:
            new_policy.set_param('srcaddr-negate', 'enable')
        if module.params['dst_addr_negate']:
            new_policy.set_param('dstaddr-negate', 'enable')
        if module.params['service_negate']:
            new_policy.set_param('service-negate', 'enable')

        # action
        new_policy.set_param('action', '%s' % (module.params['policy_action']))

        # Schedule
        new_policy.set_param('schedule', '%s' % (module.params['schedule']))

        #NAT
        if module.params['nat']:
            new_policy.set_param('nat', 'enable')
            if module.params['fixedport']:
                new_policy.set_param('fixedport', 'enable')
            if module.params['poolname'] is not None:
                new_policy.set_param('ippool', 'enable')
                new_policy.set_param('poolname', '"%s"' % (module.params['poolname']))

        #security profiles:
        if module.params['av_profile'] is not None:
            new_policy.set_param('av-profile', '"%s"' % (module.params['av_profile']))
        if module.params['webfilter_profile'] is not None:
            new_policy.set_param('webfilter-profile', '"%s"' % (module.params['webfilter_profile']))
        if module.params['ips_sensor'] is not None:
            new_policy.set_param('ips-sensor', '"%s"' % (module.params['ips_sensor']))
        if module.params['application_list'] is not None:
            new_policy.set_param('application-list', '"%s"' % (module.params['application_list']))

        # comment
        if module.params['comment'] is not None:
            new_policy.set_param('comment', '"%s"' % (module.params['comment']))

        #add the new policy to the device
        fortigate.add_block(policy_id, new_policy)

    #Apply changes
    fortigate.apply_changes()

if __name__ == '__main__':
    main()