1#!/usr/bin/python
2from __future__ import (absolute_import, division, print_function)
3# Copyright 2019 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_log_syslogd_override_setting
27short_description: Override settings for remote syslog server 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 log_syslogd feature and override_setting category.
31      Examples include all parameters and values need to be adjusted to datasources before usage.
32      Tested with FOS v6.0.5
33version_added: "2.8"
34author:
35    - Miguel Angel Munoz (@mamunozgonzalez)
36    - Nicolas Thomas (@thomnico)
37notes:
38    - Requires fortiosapi library developed by Fortinet
39    - Run as a local_action in your playbook
40requirements:
41    - fortiosapi>=0.9.8
42options:
43    host:
44        description:
45            - FortiOS or FortiGate IP address.
46        type: str
47        required: false
48    username:
49        description:
50            - FortiOS or FortiGate username.
51        type: str
52        required: false
53    password:
54        description:
55            - FortiOS or FortiGate password.
56        type: str
57        default: ""
58    vdom:
59        description:
60            - Virtual domain, among those defined previously. A vdom is a
61              virtual instance of the FortiGate that can be configured and
62              used as a different unit.
63        type: str
64        default: root
65    https:
66        description:
67            - Indicates if the requests towards FortiGate must use HTTPS protocol.
68        type: bool
69        default: true
70    ssl_verify:
71        description:
72            - Ensures FortiGate certificate must be verified by a proper CA.
73        type: bool
74        default: true
75        version_added: 2.9
76    log_syslogd_override_setting:
77        description:
78            - Override settings for remote syslog server.
79        default: null
80        type: dict
81        suboptions:
82            certificate:
83                description:
84                    - Certificate used to communicate with Syslog server. Source certificate.local.name.
85                type: str
86            custom_field_name:
87                description:
88                    - Custom field name for CEF format logging.
89                type: list
90                suboptions:
91                    custom:
92                        description:
93                            - Field custom name.
94                        type: str
95                    id:
96                        description:
97                            - Entry ID.
98                        required: true
99                        type: int
100                    name:
101                        description:
102                            - Field name.
103                        type: str
104            enc_algorithm:
105                description:
106                    - Enable/disable reliable syslogging with TLS encryption.
107                type: str
108                choices:
109                    - high-medium
110                    - high
111                    - low
112                    - disable
113            facility:
114                description:
115                    - Remote syslog facility.
116                type: str
117                choices:
118                    - kernel
119                    - user
120                    - mail
121                    - daemon
122                    - auth
123                    - syslog
124                    - lpr
125                    - news
126                    - uucp
127                    - cron
128                    - authpriv
129                    - ftp
130                    - ntp
131                    - audit
132                    - alert
133                    - clock
134                    - local0
135                    - local1
136                    - local2
137                    - local3
138                    - local4
139                    - local5
140                    - local6
141                    - local7
142            format:
143                description:
144                    - Log format.
145                type: str
146                choices:
147                    - default
148                    - csv
149                    - cef
150            mode:
151                description:
152                    - Remote syslog logging over UDP/Reliable TCP.
153                type: str
154                choices:
155                    - udp
156                    - legacy-reliable
157                    - reliable
158            override:
159                description:
160                    - Enable/disable override syslog settings.
161                type: str
162                choices:
163                    - enable
164                    - disable
165            port:
166                description:
167                    - Server listen port.
168                type: int
169            server:
170                description:
171                    - Address of remote syslog server.
172                type: str
173            source_ip:
174                description:
175                    - Source IP address of syslog.
176                type: str
177            ssl_min_proto_version:
178                description:
179                    - Minimum supported protocol version for SSL/TLS connections .
180                type: str
181                choices:
182                    - default
183                    - SSLv3
184                    - TLSv1
185                    - TLSv1-1
186                    - TLSv1-2
187            status:
188                description:
189                    - Enable/disable remote syslog logging.
190                type: str
191                choices:
192                    - enable
193                    - disable
194'''
195
196EXAMPLES = '''
197- hosts: localhost
198  vars:
199   host: "192.168.122.40"
200   username: "admin"
201   password: ""
202   vdom: "root"
203   ssl_verify: "False"
204  tasks:
205  - name: Override settings for remote syslog server.
206    fortios_log_syslogd_override_setting:
207      host:  "{{ host }}"
208      username: "{{ username }}"
209      password: "{{ password }}"
210      vdom:  "{{ vdom }}"
211      https: "False"
212      log_syslogd_override_setting:
213        certificate: "<your_own_value> (source certificate.local.name)"
214        custom_field_name:
215         -
216            custom: "<your_own_value>"
217            id:  "6"
218            name: "default_name_7"
219        enc_algorithm: "high-medium"
220        facility: "kernel"
221        format: "default"
222        mode: "udp"
223        override: "enable"
224        port: "13"
225        server: "192.168.100.40"
226        source_ip: "84.230.14.43"
227        ssl_min_proto_version: "default"
228        status: "enable"
229'''
230
231RETURN = '''
232build:
233  description: Build number of the fortigate image
234  returned: always
235  type: str
236  sample: '1547'
237http_method:
238  description: Last method used to provision the content into FortiGate
239  returned: always
240  type: str
241  sample: 'PUT'
242http_status:
243  description: Last result given by FortiGate on last operation applied
244  returned: always
245  type: str
246  sample: "200"
247mkey:
248  description: Master key (id) used in the last call to FortiGate
249  returned: success
250  type: str
251  sample: "id"
252name:
253  description: Name of the table used to fulfill the request
254  returned: always
255  type: str
256  sample: "urlfilter"
257path:
258  description: Path of the table used to fulfill the request
259  returned: always
260  type: str
261  sample: "webfilter"
262revision:
263  description: Internal revision number
264  returned: always
265  type: str
266  sample: "17.0.2.10658"
267serial:
268  description: Serial number of the unit
269  returned: always
270  type: str
271  sample: "FGVMEVYYQT3AB5352"
272status:
273  description: Indication of the operation's result
274  returned: always
275  type: str
276  sample: "success"
277vdom:
278  description: Virtual domain used
279  returned: always
280  type: str
281  sample: "root"
282version:
283  description: Version of the FortiGate
284  returned: always
285  type: str
286  sample: "v5.6.3"
287
288'''
289
290from ansible.module_utils.basic import AnsibleModule
291from ansible.module_utils.connection import Connection
292from ansible.module_utils.network.fortios.fortios import FortiOSHandler
293from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG
294
295
296def login(data, fos):
297    host = data['host']
298    username = data['username']
299    password = data['password']
300    ssl_verify = data['ssl_verify']
301
302    fos.debug('on')
303    if 'https' in data and not data['https']:
304        fos.https('off')
305    else:
306        fos.https('on')
307
308    fos.login(host, username, password, verify=ssl_verify)
309
310
311def filter_log_syslogd_override_setting_data(json):
312    option_list = ['certificate', 'custom_field_name', 'enc_algorithm',
313                   'facility', 'format', 'mode',
314                   'override', 'port', 'server',
315                   'source_ip', 'ssl_min_proto_version', 'status']
316    dictionary = {}
317
318    for attribute in option_list:
319        if attribute in json and json[attribute] is not None:
320            dictionary[attribute] = json[attribute]
321
322    return dictionary
323
324
325def underscore_to_hyphen(data):
326    if isinstance(data, list):
327        for elem in data:
328            elem = underscore_to_hyphen(elem)
329    elif isinstance(data, dict):
330        new_data = {}
331        for k, v in data.items():
332            new_data[k.replace('_', '-')] = underscore_to_hyphen(v)
333        data = new_data
334
335    return data
336
337
338def log_syslogd_override_setting(data, fos):
339    vdom = data['vdom']
340    log_syslogd_override_setting_data = data['log_syslogd_override_setting']
341    filtered_data = underscore_to_hyphen(filter_log_syslogd_override_setting_data(log_syslogd_override_setting_data))
342
343    return fos.set('log.syslogd',
344                   'override-setting',
345                   data=filtered_data,
346                   vdom=vdom)
347
348
349def is_successful_status(status):
350    return status['status'] == "success" or \
351        status['http_method'] == "DELETE" and status['http_status'] == 404
352
353
354def fortios_log_syslogd(data, fos):
355
356    if data['log_syslogd_override_setting']:
357        resp = log_syslogd_override_setting(data, fos)
358
359    return not is_successful_status(resp), \
360        resp['status'] == "success", \
361        resp
362
363
364def main():
365    fields = {
366        "host": {"required": False, "type": "str"},
367        "username": {"required": False, "type": "str"},
368        "password": {"required": False, "type": "str", "default": "", "no_log": True},
369        "vdom": {"required": False, "type": "str", "default": "root"},
370        "https": {"required": False, "type": "bool", "default": True},
371        "ssl_verify": {"required": False, "type": "bool", "default": True},
372        "log_syslogd_override_setting": {
373            "required": False, "type": "dict", "default": None,
374            "options": {
375                "certificate": {"required": False, "type": "str"},
376                "custom_field_name": {"required": False, "type": "list",
377                                      "options": {
378                                          "custom": {"required": False, "type": "str"},
379                                          "id": {"required": True, "type": "int"},
380                                          "name": {"required": False, "type": "str"}
381                                      }},
382                "enc_algorithm": {"required": False, "type": "str",
383                                  "choices": ["high-medium", "high", "low",
384                                              "disable"]},
385                "facility": {"required": False, "type": "str",
386                             "choices": ["kernel", "user", "mail",
387                                         "daemon", "auth", "syslog",
388                                         "lpr", "news", "uucp",
389                                         "cron", "authpriv", "ftp",
390                                         "ntp", "audit", "alert",
391                                         "clock", "local0", "local1",
392                                         "local2", "local3", "local4",
393                                         "local5", "local6", "local7"]},
394                "format": {"required": False, "type": "str",
395                           "choices": ["default", "csv", "cef"]},
396                "mode": {"required": False, "type": "str",
397                         "choices": ["udp", "legacy-reliable", "reliable"]},
398                "override": {"required": False, "type": "str",
399                             "choices": ["enable", "disable"]},
400                "port": {"required": False, "type": "int"},
401                "server": {"required": False, "type": "str"},
402                "source_ip": {"required": False, "type": "str"},
403                "ssl_min_proto_version": {"required": False, "type": "str",
404                                          "choices": ["default", "SSLv3", "TLSv1",
405                                                      "TLSv1-1", "TLSv1-2"]},
406                "status": {"required": False, "type": "str",
407                           "choices": ["enable", "disable"]}
408
409            }
410        }
411    }
412
413    module = AnsibleModule(argument_spec=fields,
414                           supports_check_mode=False)
415
416    # legacy_mode refers to using fortiosapi instead of HTTPAPI
417    legacy_mode = 'host' in module.params and module.params['host'] is not None and \
418                  'username' in module.params and module.params['username'] is not None and \
419                  'password' in module.params and module.params['password'] is not None
420
421    if not legacy_mode:
422        if module._socket_path:
423            connection = Connection(module._socket_path)
424            fos = FortiOSHandler(connection)
425
426            is_error, has_changed, result = fortios_log_syslogd(module.params, fos)
427        else:
428            module.fail_json(**FAIL_SOCKET_MSG)
429    else:
430        try:
431            from fortiosapi import FortiOSAPI
432        except ImportError:
433            module.fail_json(msg="fortiosapi module is required")
434
435        fos = FortiOSAPI()
436
437        login(module.params, fos)
438        is_error, has_changed, result = fortios_log_syslogd(module.params, fos)
439        fos.logout()
440
441    if not is_error:
442        module.exit_json(changed=has_changed, meta=result)
443    else:
444        module.fail_json(msg="Error in repo", meta=result)
445
446
447if __name__ == '__main__':
448    main()
449