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_firewall_vip6
27short_description: Configure virtual IP for IPv6 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 firewall feature and vip6 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    state:
77        description:
78            - Indicates whether to create or remove the object.
79              This attribute was present already in previous version in a deeper level.
80              It has been moved out to this outer level.
81        type: str
82        required: false
83        choices:
84            - present
85            - absent
86        version_added: 2.9
87    firewall_vip6:
88        description:
89            - Configure virtual IP for IPv6.
90        default: null
91        type: dict
92        suboptions:
93            state:
94                description:
95                    - B(Deprecated)
96                    - Starting with Ansible 2.9 we recommend using the top-level 'state' parameter.
97                    - HORIZONTALLINE
98                    - Indicates whether to create or remove the object.
99                type: str
100                required: false
101                choices:
102                    - present
103                    - absent
104            arp_reply:
105                description:
106                    - Enable to respond to ARP requests for this virtual IP address. Enabled by default.
107                type: str
108                choices:
109                    - disable
110                    - enable
111            color:
112                description:
113                    - Color of icon on the GUI.
114                type: int
115            comment:
116                description:
117                    - Comment.
118                type: str
119            extip:
120                description:
121                    - IP address or address range on the external interface that you want to map to an address or address range on the destination network.
122                type: str
123            extport:
124                description:
125                    - Incoming port number range that you want to map to a port number range on the destination network.
126                type: str
127            http_cookie_age:
128                description:
129                    - Time in minutes that client web browsers should keep a cookie. Default is 60 seconds. 0 = no time limit.
130                type: int
131            http_cookie_domain:
132                description:
133                    - Domain that HTTP cookie persistence should apply to.
134                type: str
135            http_cookie_domain_from_host:
136                description:
137                    - Enable/disable use of HTTP cookie domain from host field in HTTP.
138                type: str
139                choices:
140                    - disable
141                    - enable
142            http_cookie_generation:
143                description:
144                    - Generation of HTTP cookie to be accepted. Changing invalidates all existing cookies.
145                type: int
146            http_cookie_path:
147                description:
148                    - Limit HTTP cookie persistence to the specified path.
149                type: str
150            http_cookie_share:
151                description:
152                    - Control sharing of cookies across virtual servers. same-ip means a cookie from one virtual server can be used by another. Disable stops
153                       cookie sharing.
154                type: str
155                choices:
156                    - disable
157                    - same-ip
158            http_ip_header:
159                description:
160                    - For HTTP multiplexing, enable to add the original client IP address in the XForwarded-For HTTP header.
161                type: str
162                choices:
163                    - enable
164                    - disable
165            http_ip_header_name:
166                description:
167                    - For HTTP multiplexing, enter a custom HTTPS header name. The original client IP address is added to this header. If empty,
168                       X-Forwarded-For is used.
169                type: str
170            http_multiplex:
171                description:
172                    - Enable/disable HTTP multiplexing.
173                type: str
174                choices:
175                    - enable
176                    - disable
177            https_cookie_secure:
178                description:
179                    - Enable/disable verification that inserted HTTPS cookies are secure.
180                type: str
181                choices:
182                    - disable
183                    - enable
184            id:
185                description:
186                    - Custom defined ID.
187                type: int
188            ldb_method:
189                description:
190                    - Method used to distribute sessions to real servers.
191                type: str
192                choices:
193                    - static
194                    - round-robin
195                    - weighted
196                    - least-session
197                    - least-rtt
198                    - first-alive
199                    - http-host
200            mappedip:
201                description:
202                    - Mapped IP address range in the format startIP-endIP.
203                type: str
204            mappedport:
205                description:
206                    - Port number range on the destination network to which the external port number range is mapped.
207                type: str
208            max_embryonic_connections:
209                description:
210                    - Maximum number of incomplete connections.
211                type: int
212            monitor:
213                description:
214                    - Name of the health check monitor to use when polling to determine a virtual server's connectivity status.
215                type: list
216                suboptions:
217                    name:
218                        description:
219                            - Health monitor name. Source firewall.ldb-monitor.name.
220                        required: true
221                        type: str
222            name:
223                description:
224                    - Virtual ip6 name.
225                required: true
226                type: str
227            outlook_web_access:
228                description:
229                    - Enable to add the Front-End-Https header for Microsoft Outlook Web Access.
230                type: str
231                choices:
232                    - disable
233                    - enable
234            persistence:
235                description:
236                    - Configure how to make sure that clients connect to the same server every time they make a request that is part of the same session.
237                type: str
238                choices:
239                    - none
240                    - http-cookie
241                    - ssl-session-id
242            portforward:
243                description:
244                    - Enable port forwarding.
245                type: str
246                choices:
247                    - disable
248                    - enable
249            protocol:
250                description:
251                    - Protocol to use when forwarding packets.
252                type: str
253                choices:
254                    - tcp
255                    - udp
256                    - sctp
257            realservers:
258                description:
259                    - Select the real servers that this server load balancing VIP will distribute traffic to.
260                type: list
261                suboptions:
262                    client_ip:
263                        description:
264                            - Only clients in this IP range can connect to this real server.
265                        type: str
266                    healthcheck:
267                        description:
268                            - Enable to check the responsiveness of the real server before forwarding traffic.
269                        type: str
270                        choices:
271                            - disable
272                            - enable
273                            - vip
274                    holddown_interval:
275                        description:
276                            - Time in seconds that the health check monitor continues to monitor an unresponsive server that should be active.
277                        type: int
278                    http_host:
279                        description:
280                            - HTTP server domain name in HTTP header.
281                        type: str
282                    id:
283                        description:
284                            - Real server ID.
285                        required: true
286                        type: int
287                    ip:
288                        description:
289                            - IPv6 address of the real server.
290                        type: str
291                    max_connections:
292                        description:
293                            - Max number of active connections that can directed to the real server. When reached, sessions are sent to other real servers.
294                        type: int
295                    monitor:
296                        description:
297                            - Name of the health check monitor to use when polling to determine a virtual server's connectivity status. Source firewall
298                              .ldb-monitor.name.
299                        type: str
300                    port:
301                        description:
302                            - Port for communicating with the real server. Required if port forwarding is enabled.
303                        type: int
304                    status:
305                        description:
306                            - Set the status of the real server to active so that it can accept traffic, or on standby or disabled so no traffic is sent.
307                        type: str
308                        choices:
309                            - active
310                            - standby
311                            - disable
312                    weight:
313                        description:
314                            - Weight of the real server. If weighted load balancing is enabled, the server with the highest weight gets more connections.
315                        type: int
316            server_type:
317                description:
318                    - Protocol to be load balanced by the virtual server (also called the server load balance virtual IP).
319                type: str
320                choices:
321                    - http
322                    - https
323                    - imaps
324                    - pop3s
325                    - smtps
326                    - ssl
327                    - tcp
328                    - udp
329                    - ip
330            src_filter:
331                description:
332                    - "Source IP6 filter (x:x:x:x:x:x:x:x/x). Separate addresses with spaces."
333                type: list
334                suboptions:
335                    range:
336                        description:
337                            - Source-filter range.
338                        required: true
339                        type: str
340            ssl_algorithm:
341                description:
342                    - Permitted encryption algorithms for SSL sessions according to encryption strength.
343                type: str
344                choices:
345                    - high
346                    - medium
347                    - low
348                    - custom
349            ssl_certificate:
350                description:
351                    - The name of the SSL certificate to use for SSL acceleration. Source vpn.certificate.local.name.
352                type: str
353            ssl_cipher_suites:
354                description:
355                    - SSL/TLS cipher suites acceptable from a client, ordered by priority.
356                type: list
357                suboptions:
358                    cipher:
359                        description:
360                            - Cipher suite name.
361                        type: str
362                        choices:
363                            - TLS-RSA-WITH-3DES-EDE-CBC-SHA
364                            - TLS-DHE-RSA-WITH-DES-CBC-SHA
365                            - TLS-DHE-DSS-WITH-DES-CBC-SHA
366                    priority:
367                        description:
368                            - SSL/TLS cipher suites priority.
369                        required: true
370                        type: int
371                    versions:
372                        description:
373                            - SSL/TLS versions that the cipher suite can be used with.
374                        type: str
375                        choices:
376                            - ssl-3.0
377                            - tls-1.0
378                            - tls-1.1
379                            - tls-1.2
380            ssl_client_fallback:
381                description:
382                    - Enable/disable support for preventing Downgrade Attacks on client connections (RFC 7507).
383                type: str
384                choices:
385                    - disable
386                    - enable
387            ssl_client_renegotiation:
388                description:
389                    - Allow, deny, or require secure renegotiation of client sessions to comply with RFC 5746.
390                type: str
391                choices:
392                    - allow
393                    - deny
394                    - secure
395            ssl_client_session_state_max:
396                description:
397                    - Maximum number of client to FortiGate SSL session states to keep.
398                type: int
399            ssl_client_session_state_timeout:
400                description:
401                    - Number of minutes to keep client to FortiGate SSL session state.
402                type: int
403            ssl_client_session_state_type:
404                description:
405                    - How to expire SSL sessions for the segment of the SSL connection between the client and the FortiGate.
406                type: str
407                choices:
408                    - disable
409                    - time
410                    - count
411                    - both
412            ssl_dh_bits:
413                description:
414                    - Number of bits to use in the Diffie-Hellman exchange for RSA encryption of SSL sessions.
415                type: str
416                choices:
417                    - 768
418                    - 1024
419                    - 1536
420                    - 2048
421                    - 3072
422                    - 4096
423            ssl_hpkp:
424                description:
425                    - Enable/disable including HPKP header in response.
426                type: str
427                choices:
428                    - disable
429                    - enable
430                    - report-only
431            ssl_hpkp_age:
432                description:
433                    - Number of minutes the web browser should keep HPKP.
434                type: int
435            ssl_hpkp_backup:
436                description:
437                    - Certificate to generate backup HPKP pin from. Source vpn.certificate.local.name vpn.certificate.ca.name.
438                type: str
439            ssl_hpkp_include_subdomains:
440                description:
441                    - Indicate that HPKP header applies to all subdomains.
442                type: str
443                choices:
444                    - disable
445                    - enable
446            ssl_hpkp_primary:
447                description:
448                    - Certificate to generate primary HPKP pin from. Source vpn.certificate.local.name vpn.certificate.ca.name.
449                type: str
450            ssl_hpkp_report_uri:
451                description:
452                    - URL to report HPKP violations to.
453                type: str
454            ssl_hsts:
455                description:
456                    - Enable/disable including HSTS header in response.
457                type: str
458                choices:
459                    - disable
460                    - enable
461            ssl_hsts_age:
462                description:
463                    - Number of seconds the client should honour the HSTS setting.
464                type: int
465            ssl_hsts_include_subdomains:
466                description:
467                    - Indicate that HSTS header applies to all subdomains.
468                type: str
469                choices:
470                    - disable
471                    - enable
472            ssl_http_location_conversion:
473                description:
474                    - Enable to replace HTTP with HTTPS in the reply's Location HTTP header field.
475                type: str
476                choices:
477                    - enable
478                    - disable
479            ssl_http_match_host:
480                description:
481                    - Enable/disable HTTP host matching for location conversion.
482                type: str
483                choices:
484                    - enable
485                    - disable
486            ssl_max_version:
487                description:
488                    - Highest SSL/TLS version acceptable from a client.
489                type: str
490                choices:
491                    - ssl-3.0
492                    - tls-1.0
493                    - tls-1.1
494                    - tls-1.2
495            ssl_min_version:
496                description:
497                    - Lowest SSL/TLS version acceptable from a client.
498                type: str
499                choices:
500                    - ssl-3.0
501                    - tls-1.0
502                    - tls-1.1
503                    - tls-1.2
504            ssl_mode:
505                description:
506                    - Apply SSL offloading between the client and the FortiGate (half) or from the client to the FortiGate and from the FortiGate to the
507                       server (full).
508                type: str
509                choices:
510                    - half
511                    - full
512            ssl_pfs:
513                description:
514                    - Select the cipher suites that can be used for SSL perfect forward secrecy (PFS). Applies to both client and server sessions.
515                type: str
516                choices:
517                    - require
518                    - deny
519                    - allow
520            ssl_send_empty_frags:
521                description:
522                    - Enable/disable sending empty fragments to avoid CBC IV attacks (SSL 3.0 & TLS 1.0 only). May need to be disabled for compatibility with
523                       older systems.
524                type: str
525                choices:
526                    - enable
527                    - disable
528            ssl_server_algorithm:
529                description:
530                    - Permitted encryption algorithms for the server side of SSL full mode sessions according to encryption strength.
531                type: str
532                choices:
533                    - high
534                    - medium
535                    - low
536                    - custom
537                    - client
538            ssl_server_cipher_suites:
539                description:
540                    - SSL/TLS cipher suites to offer to a server, ordered by priority.
541                type: list
542                suboptions:
543                    cipher:
544                        description:
545                            - Cipher suite name.
546                        type: str
547                        choices:
548                            - TLS-RSA-WITH-3DES-EDE-CBC-SHA
549                            - TLS-DHE-RSA-WITH-DES-CBC-SHA
550                            - TLS-DHE-DSS-WITH-DES-CBC-SHA
551                    priority:
552                        description:
553                            - SSL/TLS cipher suites priority.
554                        required: true
555                        type: int
556                    versions:
557                        description:
558                            - SSL/TLS versions that the cipher suite can be used with.
559                        type: str
560                        choices:
561                            - ssl-3.0
562                            - tls-1.0
563                            - tls-1.1
564                            - tls-1.2
565            ssl_server_max_version:
566                description:
567                    - Highest SSL/TLS version acceptable from a server. Use the client setting by default.
568                type: str
569                choices:
570                    - ssl-3.0
571                    - tls-1.0
572                    - tls-1.1
573                    - tls-1.2
574                    - client
575            ssl_server_min_version:
576                description:
577                    - Lowest SSL/TLS version acceptable from a server. Use the client setting by default.
578                type: str
579                choices:
580                    - ssl-3.0
581                    - tls-1.0
582                    - tls-1.1
583                    - tls-1.2
584                    - client
585            ssl_server_session_state_max:
586                description:
587                    - Maximum number of FortiGate to Server SSL session states to keep.
588                type: int
589            ssl_server_session_state_timeout:
590                description:
591                    - Number of minutes to keep FortiGate to Server SSL session state.
592                type: int
593            ssl_server_session_state_type:
594                description:
595                    - How to expire SSL sessions for the segment of the SSL connection between the server and the FortiGate.
596                type: str
597                choices:
598                    - disable
599                    - time
600                    - count
601                    - both
602            type:
603                description:
604                    - Configure a static NAT or server load balance VIP.
605                type: str
606                choices:
607                    - static-nat
608                    - server-load-balance
609            uuid:
610                description:
611                    - Universally Unique Identifier (UUID; automatically assigned but can be manually reset).
612                type: str
613            weblogic_server:
614                description:
615                    - Enable to add an HTTP header to indicate SSL offloading for a WebLogic server.
616                type: str
617                choices:
618                    - disable
619                    - enable
620            websphere_server:
621                description:
622                    - Enable to add an HTTP header to indicate SSL offloading for a WebSphere server.
623                type: str
624                choices:
625                    - disable
626                    - enable
627'''
628
629EXAMPLES = '''
630- hosts: localhost
631  vars:
632   host: "192.168.122.40"
633   username: "admin"
634   password: ""
635   vdom: "root"
636   ssl_verify: "False"
637  tasks:
638  - name: Configure virtual IP for IPv6.
639    fortios_firewall_vip6:
640      host:  "{{ host }}"
641      username: "{{ username }}"
642      password: "{{ password }}"
643      vdom:  "{{ vdom }}"
644      https: "False"
645      state: "present"
646      firewall_vip6:
647        arp_reply: "disable"
648        color: "4"
649        comment: "Comment."
650        extip: "<your_own_value>"
651        extport: "<your_own_value>"
652        http_cookie_age: "8"
653        http_cookie_domain: "<your_own_value>"
654        http_cookie_domain_from_host: "disable"
655        http_cookie_generation: "11"
656        http_cookie_path: "<your_own_value>"
657        http_cookie_share: "disable"
658        http_ip_header: "enable"
659        http_ip_header_name: "<your_own_value>"
660        http_multiplex: "enable"
661        https_cookie_secure: "disable"
662        id:  "18"
663        ldb_method: "static"
664        mappedip: "<your_own_value>"
665        mappedport: "<your_own_value>"
666        max_embryonic_connections: "22"
667        monitor:
668         -
669            name: "default_name_24 (source firewall.ldb-monitor.name)"
670        name: "default_name_25"
671        outlook_web_access: "disable"
672        persistence: "none"
673        portforward: "disable"
674        protocol: "tcp"
675        realservers:
676         -
677            client_ip: "<your_own_value>"
678            healthcheck: "disable"
679            holddown_interval: "33"
680            http_host: "myhostname"
681            id:  "35"
682            ip: "<your_own_value>"
683            max_connections: "37"
684            monitor: "<your_own_value> (source firewall.ldb-monitor.name)"
685            port: "39"
686            status: "active"
687            weight: "41"
688        server_type: "http"
689        src_filter:
690         -
691            range: "<your_own_value>"
692        ssl_algorithm: "high"
693        ssl_certificate: "<your_own_value> (source vpn.certificate.local.name)"
694        ssl_cipher_suites:
695         -
696            cipher: "TLS-RSA-WITH-3DES-EDE-CBC-SHA"
697            priority: "49"
698            versions: "ssl-3.0"
699        ssl_client_fallback: "disable"
700        ssl_client_renegotiation: "allow"
701        ssl_client_session_state_max: "53"
702        ssl_client_session_state_timeout: "54"
703        ssl_client_session_state_type: "disable"
704        ssl_dh_bits: "768"
705        ssl_hpkp: "disable"
706        ssl_hpkp_age: "58"
707        ssl_hpkp_backup: "<your_own_value> (source vpn.certificate.local.name vpn.certificate.ca.name)"
708        ssl_hpkp_include_subdomains: "disable"
709        ssl_hpkp_primary: "<your_own_value> (source vpn.certificate.local.name vpn.certificate.ca.name)"
710        ssl_hpkp_report_uri: "<your_own_value>"
711        ssl_hsts: "disable"
712        ssl_hsts_age: "64"
713        ssl_hsts_include_subdomains: "disable"
714        ssl_http_location_conversion: "enable"
715        ssl_http_match_host: "enable"
716        ssl_max_version: "ssl-3.0"
717        ssl_min_version: "ssl-3.0"
718        ssl_mode: "half"
719        ssl_pfs: "require"
720        ssl_send_empty_frags: "enable"
721        ssl_server_algorithm: "high"
722        ssl_server_cipher_suites:
723         -
724            cipher: "TLS-RSA-WITH-3DES-EDE-CBC-SHA"
725            priority: "76"
726            versions: "ssl-3.0"
727        ssl_server_max_version: "ssl-3.0"
728        ssl_server_min_version: "ssl-3.0"
729        ssl_server_session_state_max: "80"
730        ssl_server_session_state_timeout: "81"
731        ssl_server_session_state_type: "disable"
732        type: "static-nat"
733        uuid: "<your_own_value>"
734        weblogic_server: "disable"
735        websphere_server: "disable"
736'''
737
738RETURN = '''
739build:
740  description: Build number of the fortigate image
741  returned: always
742  type: str
743  sample: '1547'
744http_method:
745  description: Last method used to provision the content into FortiGate
746  returned: always
747  type: str
748  sample: 'PUT'
749http_status:
750  description: Last result given by FortiGate on last operation applied
751  returned: always
752  type: str
753  sample: "200"
754mkey:
755  description: Master key (id) used in the last call to FortiGate
756  returned: success
757  type: str
758  sample: "id"
759name:
760  description: Name of the table used to fulfill the request
761  returned: always
762  type: str
763  sample: "urlfilter"
764path:
765  description: Path of the table used to fulfill the request
766  returned: always
767  type: str
768  sample: "webfilter"
769revision:
770  description: Internal revision number
771  returned: always
772  type: str
773  sample: "17.0.2.10658"
774serial:
775  description: Serial number of the unit
776  returned: always
777  type: str
778  sample: "FGVMEVYYQT3AB5352"
779status:
780  description: Indication of the operation's result
781  returned: always
782  type: str
783  sample: "success"
784vdom:
785  description: Virtual domain used
786  returned: always
787  type: str
788  sample: "root"
789version:
790  description: Version of the FortiGate
791  returned: always
792  type: str
793  sample: "v5.6.3"
794
795'''
796
797from ansible.module_utils.basic import AnsibleModule
798from ansible.module_utils.connection import Connection
799from ansible.module_utils.network.fortios.fortios import FortiOSHandler
800from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG
801
802
803def login(data, fos):
804    host = data['host']
805    username = data['username']
806    password = data['password']
807    ssl_verify = data['ssl_verify']
808
809    fos.debug('on')
810    if 'https' in data and not data['https']:
811        fos.https('off')
812    else:
813        fos.https('on')
814
815    fos.login(host, username, password, verify=ssl_verify)
816
817
818def filter_firewall_vip6_data(json):
819    option_list = ['arp_reply', 'color', 'comment',
820                   'extip', 'extport', 'http_cookie_age',
821                   'http_cookie_domain', 'http_cookie_domain_from_host', 'http_cookie_generation',
822                   'http_cookie_path', 'http_cookie_share', 'http_ip_header',
823                   'http_ip_header_name', 'http_multiplex', 'https_cookie_secure',
824                   'id', 'ldb_method', 'mappedip',
825                   'mappedport', 'max_embryonic_connections', 'monitor',
826                   'name', 'outlook_web_access', 'persistence',
827                   'portforward', 'protocol', 'realservers',
828                   'server_type', 'src_filter', 'ssl_algorithm',
829                   'ssl_certificate', 'ssl_cipher_suites', 'ssl_client_fallback',
830                   'ssl_client_renegotiation', 'ssl_client_session_state_max', 'ssl_client_session_state_timeout',
831                   'ssl_client_session_state_type', 'ssl_dh_bits', 'ssl_hpkp',
832                   'ssl_hpkp_age', 'ssl_hpkp_backup', 'ssl_hpkp_include_subdomains',
833                   'ssl_hpkp_primary', 'ssl_hpkp_report_uri', 'ssl_hsts',
834                   'ssl_hsts_age', 'ssl_hsts_include_subdomains', 'ssl_http_location_conversion',
835                   'ssl_http_match_host', 'ssl_max_version', 'ssl_min_version',
836                   'ssl_mode', 'ssl_pfs', 'ssl_send_empty_frags',
837                   'ssl_server_algorithm', 'ssl_server_cipher_suites', 'ssl_server_max_version',
838                   'ssl_server_min_version', 'ssl_server_session_state_max', 'ssl_server_session_state_timeout',
839                   'ssl_server_session_state_type', 'type', 'uuid',
840                   'weblogic_server', 'websphere_server']
841    dictionary = {}
842
843    for attribute in option_list:
844        if attribute in json and json[attribute] is not None:
845            dictionary[attribute] = json[attribute]
846
847    return dictionary
848
849
850def underscore_to_hyphen(data):
851    if isinstance(data, list):
852        for elem in data:
853            elem = underscore_to_hyphen(elem)
854    elif isinstance(data, dict):
855        new_data = {}
856        for k, v in data.items():
857            new_data[k.replace('_', '-')] = underscore_to_hyphen(v)
858        data = new_data
859
860    return data
861
862
863def firewall_vip6(data, fos):
864    vdom = data['vdom']
865    if 'state' in data and data['state']:
866        state = data['state']
867    elif 'state' in data['firewall_vip6'] and data['firewall_vip6']:
868        state = data['firewall_vip6']['state']
869    else:
870        state = True
871    firewall_vip6_data = data['firewall_vip6']
872    filtered_data = underscore_to_hyphen(filter_firewall_vip6_data(firewall_vip6_data))
873
874    if state == "present":
875        return fos.set('firewall',
876                       'vip6',
877                       data=filtered_data,
878                       vdom=vdom)
879
880    elif state == "absent":
881        return fos.delete('firewall',
882                          'vip6',
883                          mkey=filtered_data['name'],
884                          vdom=vdom)
885
886
887def is_successful_status(status):
888    return status['status'] == "success" or \
889        status['http_method'] == "DELETE" and status['http_status'] == 404
890
891
892def fortios_firewall(data, fos):
893
894    if data['firewall_vip6']:
895        resp = firewall_vip6(data, fos)
896
897    return not is_successful_status(resp), \
898        resp['status'] == "success", \
899        resp
900
901
902def main():
903    fields = {
904        "host": {"required": False, "type": "str"},
905        "username": {"required": False, "type": "str"},
906        "password": {"required": False, "type": "str", "default": "", "no_log": True},
907        "vdom": {"required": False, "type": "str", "default": "root"},
908        "https": {"required": False, "type": "bool", "default": True},
909        "ssl_verify": {"required": False, "type": "bool", "default": True},
910        "state": {"required": False, "type": "str",
911                  "choices": ["present", "absent"]},
912        "firewall_vip6": {
913            "required": False, "type": "dict", "default": None,
914            "options": {
915                "state": {"required": False, "type": "str",
916                          "choices": ["present", "absent"]},
917                "arp_reply": {"required": False, "type": "str",
918                              "choices": ["disable", "enable"]},
919                "color": {"required": False, "type": "int"},
920                "comment": {"required": False, "type": "str"},
921                "extip": {"required": False, "type": "str"},
922                "extport": {"required": False, "type": "str"},
923                "http_cookie_age": {"required": False, "type": "int"},
924                "http_cookie_domain": {"required": False, "type": "str"},
925                "http_cookie_domain_from_host": {"required": False, "type": "str",
926                                                 "choices": ["disable", "enable"]},
927                "http_cookie_generation": {"required": False, "type": "int"},
928                "http_cookie_path": {"required": False, "type": "str"},
929                "http_cookie_share": {"required": False, "type": "str",
930                                      "choices": ["disable", "same-ip"]},
931                "http_ip_header": {"required": False, "type": "str",
932                                   "choices": ["enable", "disable"]},
933                "http_ip_header_name": {"required": False, "type": "str"},
934                "http_multiplex": {"required": False, "type": "str",
935                                   "choices": ["enable", "disable"]},
936                "https_cookie_secure": {"required": False, "type": "str",
937                                        "choices": ["disable", "enable"]},
938                "id": {"required": False, "type": "int"},
939                "ldb_method": {"required": False, "type": "str",
940                               "choices": ["static", "round-robin", "weighted",
941                                           "least-session", "least-rtt", "first-alive",
942                                           "http-host"]},
943                "mappedip": {"required": False, "type": "str"},
944                "mappedport": {"required": False, "type": "str"},
945                "max_embryonic_connections": {"required": False, "type": "int"},
946                "monitor": {"required": False, "type": "list",
947                            "options": {
948                                "name": {"required": True, "type": "str"}
949                            }},
950                "name": {"required": True, "type": "str"},
951                "outlook_web_access": {"required": False, "type": "str",
952                                       "choices": ["disable", "enable"]},
953                "persistence": {"required": False, "type": "str",
954                                "choices": ["none", "http-cookie", "ssl-session-id"]},
955                "portforward": {"required": False, "type": "str",
956                                "choices": ["disable", "enable"]},
957                "protocol": {"required": False, "type": "str",
958                             "choices": ["tcp", "udp", "sctp"]},
959                "realservers": {"required": False, "type": "list",
960                                "options": {
961                                    "client_ip": {"required": False, "type": "str"},
962                                    "healthcheck": {"required": False, "type": "str",
963                                                    "choices": ["disable", "enable", "vip"]},
964                                    "holddown_interval": {"required": False, "type": "int"},
965                                    "http_host": {"required": False, "type": "str"},
966                                    "id": {"required": True, "type": "int"},
967                                    "ip": {"required": False, "type": "str"},
968                                    "max_connections": {"required": False, "type": "int"},
969                                    "monitor": {"required": False, "type": "str"},
970                                    "port": {"required": False, "type": "int"},
971                                    "status": {"required": False, "type": "str",
972                                               "choices": ["active", "standby", "disable"]},
973                                    "weight": {"required": False, "type": "int"}
974                                }},
975                "server_type": {"required": False, "type": "str",
976                                "choices": ["http", "https", "imaps",
977                                            "pop3s", "smtps", "ssl",
978                                            "tcp", "udp", "ip"]},
979                "src_filter": {"required": False, "type": "list",
980                               "options": {
981                                   "range": {"required": True, "type": "str"}
982                               }},
983                "ssl_algorithm": {"required": False, "type": "str",
984                                  "choices": ["high", "medium", "low",
985                                              "custom"]},
986                "ssl_certificate": {"required": False, "type": "str"},
987                "ssl_cipher_suites": {"required": False, "type": "list",
988                                      "options": {
989                                          "cipher": {"required": False, "type": "str",
990                                                     "choices": ["TLS-RSA-WITH-3DES-EDE-CBC-SHA", "TLS-DHE-RSA-WITH-DES-CBC-SHA",
991                                                                 "TLS-DHE-DSS-WITH-DES-CBC-SHA"]},
992                                          "priority": {"required": True, "type": "int"},
993                                          "versions": {"required": False, "type": "str",
994                                                       "choices": ["ssl-3.0", "tls-1.0", "tls-1.1",
995                                                                   "tls-1.2"]}
996                                      }},
997                "ssl_client_fallback": {"required": False, "type": "str",
998                                        "choices": ["disable", "enable"]},
999                "ssl_client_renegotiation": {"required": False, "type": "str",
1000                                             "choices": ["allow", "deny", "secure"]},
1001                "ssl_client_session_state_max": {"required": False, "type": "int"},
1002                "ssl_client_session_state_timeout": {"required": False, "type": "int"},
1003                "ssl_client_session_state_type": {"required": False, "type": "str",
1004                                                  "choices": ["disable", "time", "count",
1005                                                              "both"]},
1006                "ssl_dh_bits": {"required": False, "type": "str",
1007                                "choices": ["768", "1024", "1536",
1008                                            "2048", "3072", "4096"]},
1009                "ssl_hpkp": {"required": False, "type": "str",
1010                             "choices": ["disable", "enable", "report-only"]},
1011                "ssl_hpkp_age": {"required": False, "type": "int"},
1012                "ssl_hpkp_backup": {"required": False, "type": "str"},
1013                "ssl_hpkp_include_subdomains": {"required": False, "type": "str",
1014                                                "choices": ["disable", "enable"]},
1015                "ssl_hpkp_primary": {"required": False, "type": "str"},
1016                "ssl_hpkp_report_uri": {"required": False, "type": "str"},
1017                "ssl_hsts": {"required": False, "type": "str",
1018                             "choices": ["disable", "enable"]},
1019                "ssl_hsts_age": {"required": False, "type": "int"},
1020                "ssl_hsts_include_subdomains": {"required": False, "type": "str",
1021                                                "choices": ["disable", "enable"]},
1022                "ssl_http_location_conversion": {"required": False, "type": "str",
1023                                                 "choices": ["enable", "disable"]},
1024                "ssl_http_match_host": {"required": False, "type": "str",
1025                                        "choices": ["enable", "disable"]},
1026                "ssl_max_version": {"required": False, "type": "str",
1027                                    "choices": ["ssl-3.0", "tls-1.0", "tls-1.1",
1028                                                "tls-1.2"]},
1029                "ssl_min_version": {"required": False, "type": "str",
1030                                    "choices": ["ssl-3.0", "tls-1.0", "tls-1.1",
1031                                                "tls-1.2"]},
1032                "ssl_mode": {"required": False, "type": "str",
1033                             "choices": ["half", "full"]},
1034                "ssl_pfs": {"required": False, "type": "str",
1035                            "choices": ["require", "deny", "allow"]},
1036                "ssl_send_empty_frags": {"required": False, "type": "str",
1037                                         "choices": ["enable", "disable"]},
1038                "ssl_server_algorithm": {"required": False, "type": "str",
1039                                         "choices": ["high", "medium", "low",
1040                                                     "custom", "client"]},
1041                "ssl_server_cipher_suites": {"required": False, "type": "list",
1042                                             "options": {
1043                                                 "cipher": {"required": False, "type": "str",
1044                                                            "choices": ["TLS-RSA-WITH-3DES-EDE-CBC-SHA", "TLS-DHE-RSA-WITH-DES-CBC-SHA",
1045                                                                        "TLS-DHE-DSS-WITH-DES-CBC-SHA"]},
1046                                                 "priority": {"required": True, "type": "int"},
1047                                                 "versions": {"required": False, "type": "str",
1048                                                              "choices": ["ssl-3.0", "tls-1.0", "tls-1.1",
1049                                                                          "tls-1.2"]}
1050                                             }},
1051                "ssl_server_max_version": {"required": False, "type": "str",
1052                                           "choices": ["ssl-3.0", "tls-1.0", "tls-1.1",
1053                                                       "tls-1.2", "client"]},
1054                "ssl_server_min_version": {"required": False, "type": "str",
1055                                           "choices": ["ssl-3.0", "tls-1.0", "tls-1.1",
1056                                                       "tls-1.2", "client"]},
1057                "ssl_server_session_state_max": {"required": False, "type": "int"},
1058                "ssl_server_session_state_timeout": {"required": False, "type": "int"},
1059                "ssl_server_session_state_type": {"required": False, "type": "str",
1060                                                  "choices": ["disable", "time", "count",
1061                                                              "both"]},
1062                "type": {"required": False, "type": "str",
1063                         "choices": ["static-nat", "server-load-balance"]},
1064                "uuid": {"required": False, "type": "str"},
1065                "weblogic_server": {"required": False, "type": "str",
1066                                    "choices": ["disable", "enable"]},
1067                "websphere_server": {"required": False, "type": "str",
1068                                     "choices": ["disable", "enable"]}
1069
1070            }
1071        }
1072    }
1073
1074    module = AnsibleModule(argument_spec=fields,
1075                           supports_check_mode=False)
1076
1077    # legacy_mode refers to using fortiosapi instead of HTTPAPI
1078    legacy_mode = 'host' in module.params and module.params['host'] is not None and \
1079                  'username' in module.params and module.params['username'] is not None and \
1080                  'password' in module.params and module.params['password'] is not None
1081
1082    if not legacy_mode:
1083        if module._socket_path:
1084            connection = Connection(module._socket_path)
1085            fos = FortiOSHandler(connection)
1086
1087            is_error, has_changed, result = fortios_firewall(module.params, fos)
1088        else:
1089            module.fail_json(**FAIL_SOCKET_MSG)
1090    else:
1091        try:
1092            from fortiosapi import FortiOSAPI
1093        except ImportError:
1094            module.fail_json(msg="fortiosapi module is required")
1095
1096        fos = FortiOSAPI()
1097
1098        login(module.params, fos)
1099        is_error, has_changed, result = fortios_firewall(module.params, fos)
1100        fos.logout()
1101
1102    if not is_error:
1103        module.exit_json(changed=has_changed, meta=result)
1104    else:
1105        module.fail_json(msg="Error in repo", meta=result)
1106
1107
1108if __name__ == '__main__':
1109    main()
1110