1#!/usr/local/bin/python3.8
2from __future__ import (absolute_import, division, print_function)
3# Copyright 2019-2020 Fortinet, Inc.
4#
5# This program is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
18__metaclass__ = type
19
20ANSIBLE_METADATA = {'status': ['preview'],
21                    'supported_by': 'community',
22                    'metadata_version': '1.1'}
23
24DOCUMENTATION = '''
25---
26module: fortios_webfilter_ftgd_local_rating
27short_description: Configure local FortiGuard Web Filter local ratings in Fortinet's FortiOS and FortiGate.
28description:
29    - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
30      user to set and modify webfilter feature and ftgd_local_rating category.
31      Examples include all parameters and values need to be adjusted to datasources before usage.
32      Tested with FOS v6.0.0
33version_added: "2.10"
34author:
35    - Link Zheng (@chillancezen)
36    - Jie Xue (@JieX19)
37    - Hongbin Lu (@fgtdev-hblu)
38    - Frank Shen (@frankshen01)
39    - Miguel Angel Munoz (@mamunozgonzalez)
40    - Nicolas Thomas (@thomnico)
41notes:
42    - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
43
44requirements:
45    - ansible>=2.9.0
46options:
47    access_token:
48        description:
49            - Token-based authentication.
50              Generated from GUI of Fortigate.
51        type: str
52        required: false
53    enable_log:
54        description:
55            - Enable/Disable logging for task.
56        type: bool
57        required: false
58        default: false
59    vdom:
60        description:
61            - Virtual domain, among those defined previously. A vdom is a
62              virtual instance of the FortiGate that can be configured and
63              used as a different unit.
64        type: str
65        default: root
66
67    state:
68        description:
69            - Indicates whether to create or remove the object.
70        type: str
71        required: true
72        choices:
73            - present
74            - absent
75    webfilter_ftgd_local_rating:
76        description:
77            - Configure local FortiGuard Web Filter local ratings.
78        default: null
79        type: dict
80        suboptions:
81            comment:
82                description:
83                    - Comment.
84                type: str
85            rating:
86                description:
87                    - Local rating.
88                type: str
89            status:
90                description:
91                    - Enable/disable local rating.
92                type: str
93                choices:
94                    - enable
95                    - disable
96            url:
97                description:
98                    - URL to rate locally.
99                required: true
100                type: str
101'''
102
103EXAMPLES = '''
104- hosts: fortigates
105  collections:
106    - fortinet.fortios
107  connection: httpapi
108  vars:
109   vdom: "root"
110   ansible_httpapi_use_ssl: yes
111   ansible_httpapi_validate_certs: no
112   ansible_httpapi_port: 443
113  tasks:
114  - name: Configure local FortiGuard Web Filter local ratings.
115    fortios_webfilter_ftgd_local_rating:
116      vdom:  "{{ vdom }}"
117      state: "present"
118      access_token: "<your_own_value>"
119      webfilter_ftgd_local_rating:
120        comment: "Comment."
121        rating: "<your_own_value>"
122        status: "enable"
123        url: "myurl.com"
124
125'''
126
127RETURN = '''
128build:
129  description: Build number of the fortigate image
130  returned: always
131  type: str
132  sample: '1547'
133http_method:
134  description: Last method used to provision the content into FortiGate
135  returned: always
136  type: str
137  sample: 'PUT'
138http_status:
139  description: Last result given by FortiGate on last operation applied
140  returned: always
141  type: str
142  sample: "200"
143mkey:
144  description: Master key (id) used in the last call to FortiGate
145  returned: success
146  type: str
147  sample: "id"
148name:
149  description: Name of the table used to fulfill the request
150  returned: always
151  type: str
152  sample: "urlfilter"
153path:
154  description: Path of the table used to fulfill the request
155  returned: always
156  type: str
157  sample: "webfilter"
158revision:
159  description: Internal revision number
160  returned: always
161  type: str
162  sample: "17.0.2.10658"
163serial:
164  description: Serial number of the unit
165  returned: always
166  type: str
167  sample: "FGVMEVYYQT3AB5352"
168status:
169  description: Indication of the operation's result
170  returned: always
171  type: str
172  sample: "success"
173vdom:
174  description: Virtual domain used
175  returned: always
176  type: str
177  sample: "root"
178version:
179  description: Version of the FortiGate
180  returned: always
181  type: str
182  sample: "v5.6.3"
183
184'''
185from ansible.module_utils.basic import AnsibleModule
186from ansible.module_utils.connection import Connection
187from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import FortiOSHandler
188from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import check_legacy_fortiosapi
189from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import schema_to_module_spec
190from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import check_schema_versioning
191from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import FAIL_SOCKET_MSG
192from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import is_same_comparison
193from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import serialize
194
195
196def filter_webfilter_ftgd_local_rating_data(json):
197    option_list = ['comment', 'rating', 'status',
198                   'url']
199    dictionary = {}
200
201    for attribute in option_list:
202        if attribute in json and json[attribute] is not None:
203            dictionary[attribute] = json[attribute]
204
205    return dictionary
206
207
208def underscore_to_hyphen(data):
209    if isinstance(data, list):
210        for i, elem in enumerate(data):
211            data[i] = underscore_to_hyphen(elem)
212    elif isinstance(data, dict):
213        new_data = {}
214        for k, v in data.items():
215            new_data[k.replace('_', '-')] = underscore_to_hyphen(v)
216        data = new_data
217
218    return data
219
220
221def webfilter_ftgd_local_rating(data, fos, check_mode=False):
222
223    vdom = data['vdom']
224
225    state = data['state']
226
227    webfilter_ftgd_local_rating_data = data['webfilter_ftgd_local_rating']
228    filtered_data = underscore_to_hyphen(filter_webfilter_ftgd_local_rating_data(webfilter_ftgd_local_rating_data))
229
230    # check_mode starts from here
231    if check_mode:
232        mkey = fos.get_mkey('system', 'interface', filtered_data, vdom=vdom)
233        current_data = fos.get('system', 'interface', vdom=vdom, mkey=mkey)
234        is_existed = current_data and current_data.get('http_status') == 200 \
235            and isinstance(current_data.get('results'), list) \
236            and len(current_data['results']) > 0
237
238        # 2. if it exists and the state is 'present' then compare current settings with desired
239        if state == 'present' or state is True:
240            if mkey is None:
241                return False, True, filtered_data
242
243            # if mkey exists then compare each other
244            # record exits and they're matched or not
245            if is_existed:
246                is_same = is_same_comparison(
247                    serialize(current_data['results'][0]), serialize(filtered_data))
248                return False, not is_same, filtered_data
249
250            # record does not exist
251            return False, True, filtered_data
252
253        if state == 'absent':
254            if mkey is None:
255                return False, False, filtered_data
256
257            if is_existed:
258                return False, True, filtered_data
259            return False, False, filtered_data
260
261        return True, False, {'reason: ': 'Must provide state parameter'}
262
263    if state == "present" or state is True:
264        return fos.set('webfilter',
265                       'ftgd-local-rating',
266                       data=filtered_data,
267                       vdom=vdom)
268
269    elif state == "absent":
270        return fos.delete('webfilter',
271                          'ftgd-local-rating',
272                          mkey=filtered_data['url'],
273                          vdom=vdom)
274    else:
275        fos._module.fail_json(msg='state must be present or absent!')
276
277
278def is_successful_status(status):
279    return status['status'] == "success" or \
280        status['http_method'] == "DELETE" and status['http_status'] == 404
281
282
283def fortios_webfilter(data, fos, check_mode):
284
285    if data['webfilter_ftgd_local_rating']:
286        resp = webfilter_ftgd_local_rating(data, fos, check_mode)
287    else:
288        fos._module.fail_json(msg='missing task body: %s' % ('webfilter_ftgd_local_rating'))
289    if check_mode:
290        return resp
291    return not is_successful_status(resp), \
292        resp['status'] == "success" and \
293        (resp['revision_changed'] if 'revision_changed' in resp else True), \
294        resp
295
296
297versioned_schema = {
298    "type": "list",
299    "children": {
300        "url": {
301            "type": "string",
302            "revisions": {
303                "v6.0.0": True,
304                "v7.0.0": True,
305                "v6.0.5": True,
306                "v6.4.4": True,
307                "v6.4.0": True,
308                "v6.4.1": True,
309                "v6.2.0": True,
310                "v6.2.3": True,
311                "v6.2.5": True,
312                "v6.2.7": True,
313                "v6.0.11": True
314            }
315        },
316        "status": {
317            "type": "string",
318            "options": [
319                {
320                    "value": "enable",
321                    "revisions": {
322                        "v6.0.0": True,
323                        "v7.0.0": True,
324                        "v6.0.5": True,
325                        "v6.4.4": True,
326                        "v6.4.0": True,
327                        "v6.4.1": True,
328                        "v6.2.0": True,
329                        "v6.2.3": True,
330                        "v6.2.5": True,
331                        "v6.2.7": True,
332                        "v6.0.11": True
333                    }
334                },
335                {
336                    "value": "disable",
337                    "revisions": {
338                        "v6.0.0": True,
339                        "v7.0.0": True,
340                        "v6.0.5": True,
341                        "v6.4.4": True,
342                        "v6.4.0": True,
343                        "v6.4.1": True,
344                        "v6.2.0": True,
345                        "v6.2.3": True,
346                        "v6.2.5": True,
347                        "v6.2.7": True,
348                        "v6.0.11": True
349                    }
350                }
351            ],
352            "revisions": {
353                "v6.0.0": True,
354                "v7.0.0": True,
355                "v6.0.5": True,
356                "v6.4.4": True,
357                "v6.4.0": True,
358                "v6.4.1": True,
359                "v6.2.0": True,
360                "v6.2.3": True,
361                "v6.2.5": True,
362                "v6.2.7": True,
363                "v6.0.11": True
364            }
365        },
366        "comment": {
367            "type": "string",
368            "revisions": {
369                "v6.4.4": True,
370                "v7.0.0": True
371            }
372        },
373        "rating": {
374            "type": "string",
375            "revisions": {
376                "v6.0.0": True,
377                "v7.0.0": True,
378                "v6.0.5": True,
379                "v6.4.4": True,
380                "v6.4.0": True,
381                "v6.4.1": True,
382                "v6.2.0": True,
383                "v6.2.3": True,
384                "v6.2.5": True,
385                "v6.2.7": True,
386                "v6.0.11": True
387            }
388        }
389    },
390    "revisions": {
391        "v6.0.0": True,
392        "v7.0.0": True,
393        "v6.0.5": True,
394        "v6.4.4": True,
395        "v6.4.0": True,
396        "v6.4.1": True,
397        "v6.2.0": True,
398        "v6.2.3": True,
399        "v6.2.5": True,
400        "v6.2.7": True,
401        "v6.0.11": True
402    }
403}
404
405
406def main():
407    module_spec = schema_to_module_spec(versioned_schema)
408    mkeyname = 'url'
409    fields = {
410        "access_token": {"required": False, "type": "str", "no_log": True},
411        "enable_log": {"required": False, "type": bool},
412        "vdom": {"required": False, "type": "str", "default": "root"},
413        "state": {"required": True, "type": "str",
414                  "choices": ["present", "absent"]},
415        "webfilter_ftgd_local_rating": {
416            "required": False, "type": "dict", "default": None,
417            "options": {
418            }
419        }
420    }
421    for attribute_name in module_spec['options']:
422        fields["webfilter_ftgd_local_rating"]['options'][attribute_name] = module_spec['options'][attribute_name]
423        if mkeyname and mkeyname == attribute_name:
424            fields["webfilter_ftgd_local_rating"]['options'][attribute_name]['required'] = True
425
426    check_legacy_fortiosapi()
427    module = AnsibleModule(argument_spec=fields,
428                           supports_check_mode=True)
429
430    versions_check_result = None
431    if module._socket_path:
432        connection = Connection(module._socket_path)
433        if 'access_token' in module.params:
434            connection.set_option('access_token', module.params['access_token'])
435
436        if 'enable_log' in module.params:
437            connection.set_option('enable_log', module.params['enable_log'])
438        else:
439            connection.set_option('enable_log', False)
440        fos = FortiOSHandler(connection, module, mkeyname)
441        versions_check_result = check_schema_versioning(fos, versioned_schema, "webfilter_ftgd_local_rating")
442
443        is_error, has_changed, result = fortios_webfilter(module.params, fos, module.check_mode)
444
445    else:
446        module.fail_json(**FAIL_SOCKET_MSG)
447
448    if versions_check_result and versions_check_result['matched'] is False:
449        module.warn("Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv")
450
451    if not is_error:
452        if versions_check_result and versions_check_result['matched'] is False:
453            module.exit_json(changed=has_changed, version_check_warning=versions_check_result, meta=result)
454        else:
455            module.exit_json(changed=has_changed, meta=result)
456    else:
457        if versions_check_result and versions_check_result['matched'] is False:
458            module.fail_json(msg="Error in repo", version_check_warning=versions_check_result, meta=result)
459        else:
460            module.fail_json(msg="Error in repo", meta=result)
461
462
463if __name__ == '__main__':
464    main()
465