#!/usr/bin/python2 -O
# vim: fileencoding=utf-8
#
# The Qubes OS Project, https://www.qubes-os.org/
#
# Copyright (C) 2010  Joanna Rutkowska <joanna@invisiblethingslab.com>
# Copyright (C) 2013-2016  Marek Marczykowski-Górecki
#                               <marmarek@invisiblethingslab.com>
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
import base64
import datetime
import qubes.ext
import qubes.vm.qubesvm
import qubes.vm.appvm
import qubes.vm.templatevm
import qubes.utils

yum_proxy_ip = '10.137.255.254'
yum_proxy_port = '8082'


class R3Compatibility(qubes.ext.Extension):
    '''Maintain VM interface compatibility with R3.0 and R3.1.
    At lease where possible.
    '''

    features_to_services = {
        'services/ntpd': 'ntpd',
        'check-updates': 'qubes-update-check',
        'dvm': 'qubes-dvm',

    }

    # noinspection PyUnusedLocal
    @qubes.ext.handler('domain-qdb-create')
    def on_domain_qdb_create(self, vm, event):
        """
        :param vm: VM on which QubesDB entries were just created
        :type vm: qubes.vm.qubesvm.QubesVM
        """
        # /qubes-vm-type: AppVM, NetVM, ProxyVM, TemplateVM
        if isinstance(vm, qubes.vm.templatevm.TemplateVM):
            vmtype = 'TemplateVM'
        elif vm.netvm is not None and vm.provides_network:
            vmtype = 'ProxyVM'
        elif vm.netvm is None and vm.provides_network:
            vmtype = 'NetVM'
        else:
            vmtype = 'AppVM'
        vm.qdb.write('/qubes-vm-type', vmtype)

        # /qubes-vm-updateable
        vm.qdb.write('/qubes-vm-updateable', str(vm.updateable))

        # /qubes-base-template
        try:
            if vm.template:
                vm.qdb.write('/qubes-base-template', str(vm.template))
            else:
                vm.qdb.write('/qubes-base-template', '')
        except AttributeError:
            vm.qdb.write('/qubes-base-template', '')

        # /qubes-debug-mode: 0, 1
        vm.qdb.write('/qubes-debug-mode', str(int(vm.debug)))

        # /qubes-timezone
        timezone = vm.qdb.read('/timezone')
        if timezone:
            vm.qdb.write('/qubes-timezone', timezone)

        # /qubes-vm-persistence
        persistence = vm.qdb.read('/persistence')
        if persistence:
            vm.qdb.write('/qubes-vm-persistence', persistence)

        # /qubes-random-seed
        # write a new one, to make sure it wouldn't be reused/leaked
        vm.qdb.write('/qubes-random-seed',
            base64.b64encode(qubes.utils.urandom(64)))

        # /qubes-keyboard
        # not needed for now - the old one is still present

        # Networking
        if vm.provides_network:
            # '/qubes-netvm-network' value is only checked for being non empty
            vm.qdb.write('/qubes-netvm-network', vm.gateway)
            vm.qdb.write('/qubes-netvm-netmask', vm.netmask)
            vm.qdb.write('/qubes-netvm-gateway', vm.gateway)
            vm.qdb.write('/qubes-netvm-primary-dns', vm.dns[0])
            vm.qdb.write('/qubes-netvm-secondary-dns', vm.dns[1])

        if vm.netvm is not None:
            vm.qdb.write('/qubes-ip', vm.ip)
            vm.qdb.write('/qubes-netmask', vm.netvm.netmask)
            vm.qdb.write('/qubes-gateway', vm.netvm.gateway)
            vm.qdb.write('/qubes-primary-dns', vm.dns[0])
            vm.qdb.write('/qubes-secondary-dns', vm.dns[1])

        vm.qdb.write("/qubes-iptables-error", '')
        self.write_iptables_qubesdb_entry(vm)

        self.write_services(vm)

    # FIXME use event after creating Xen domain object, but before "resume"
    @qubes.ext.handler('domain-start')
    def on_domain_started(self, vm, event, **kwargs):
        if vm.netvm:
            self.write_iptables_qubesdb_entry(vm.netvm)

    @qubes.ext.handler('firewall-changed')
    def on_firewall_changed(self, vm, event):
        if vm.is_running() and vm.netvm:
            self.write_iptables_qubesdb_entry(vm.netvm)

    def write_iptables_qubesdb_entry(self, firewallvm):
        firewallvm.qdb.rm("/qubes-iptables-domainrules/")
        iptables = "# Generated by Qubes Core on {0}\n".format(
            datetime.datetime.now().ctime())
        iptables += "*filter\n"
        iptables += ":INPUT DROP [0:0]\n"
        iptables += ":FORWARD DROP [0:0]\n"
        iptables += ":OUTPUT ACCEPT [0:0]\n"

        # Strict INPUT rules
        iptables += "-A INPUT -i vif+ -p udp -m udp --dport 68 -j DROP\n"
        iptables += "-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED " \
                    "-j ACCEPT\n"
        iptables += "-A INPUT -p icmp -j ACCEPT\n"
        iptables += "-A INPUT -i lo -j ACCEPT\n"
        iptables += "-A INPUT -j REJECT --reject-with icmp-host-prohibited\n"

        iptables += "-A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED " \
                    "-j ACCEPT\n"
        # Deny inter-VMs networking
        iptables += "-A FORWARD -i vif+ -o vif+ -j DROP\n"
        iptables += "COMMIT\n"
        firewallvm.qdb.write("/qubes-iptables-header", iptables)

        for vm in firewallvm.connected_vms:
            iptables = "*filter\n"
            conf = vm.get_firewall_conf()

            xid = vm.xid
            if xid < 0:  # VM not active ATM
                continue

            ip = vm.ip
            if ip is None:
                continue

            # Anti-spoof rules are added by vif-script (vif-route-qubes),
            # here we trust IP address

            accept_action = "ACCEPT"
            reject_action = "REJECT --reject-with icmp-host-prohibited"

            if conf["allow"]:
                default_action = accept_action
                rules_action = reject_action
            else:
                default_action = reject_action
                rules_action = accept_action

            for rule in conf["rules"]:
                iptables += "-A FORWARD -s {0} -d {1}".format(
                    ip, rule["address"])
                if rule["netmask"] != 32:
                    iptables += "/{0}".format(rule["netmask"])

                if rule["proto"] is not None and rule["proto"] != "any":
                    iptables += " -p {0}".format(rule["proto"])
                    if rule["portBegin"] is not None and rule["portBegin"] > 0:
                        iptables += " --dport {0}".format(rule["portBegin"])
                        if rule["portEnd"] is not None and \
                                rule["portEnd"] > rule["portBegin"]:
                            iptables += ":{0}".format(rule["portEnd"])

                iptables += " -j {0}\n".format(rules_action)

            if conf["allowDns"] and firewallvm.netvm is not None:
                # PREROUTING does DNAT to NetVM DNSes, so we need self.netvm.
                # properties
                iptables += "-A FORWARD -s {0} -p udp -d {1} --dport 53 -j " \
                            "ACCEPT\n".format(ip, vm.dns[0])
                iptables += "-A FORWARD -s {0} -p udp -d {1} --dport 53 -j " \
                            "ACCEPT\n".format(ip, vm.dns[1])
                iptables += "-A FORWARD -s {0} -p tcp -d {1} --dport 53 -j " \
                            "ACCEPT\n".format(ip, vm.dns[0])
                iptables += "-A FORWARD -s {0} -p tcp -d {1} --dport 53 -j " \
                            "ACCEPT\n".format(ip, vm.dns[1])
            if conf["allowIcmp"]:
                iptables += "-A FORWARD -s {0} -p icmp -j ACCEPT\n".format(ip)
            if conf["allowYumProxy"]:
                iptables += \
                    "-A FORWARD -s {0} -p tcp -d {1} --dport {2} -j ACCEPT\n".\
                        format(ip, yum_proxy_ip, yum_proxy_port)
            else:
                iptables += \
                    "-A FORWARD -s {0} -p tcp -d {1} --dport {2} -j DROP\n".\
                        format(ip, yum_proxy_ip, yum_proxy_port)

            iptables += "-A FORWARD -s {0} -j {1}\n".format(ip, default_action)
            iptables += "COMMIT\n"
            firewallvm.qdb.write("/qubes-iptables-domainrules/" + str(xid),
                iptables)
        # no need for ending -A FORWARD -j DROP, cause default action is DROP

        firewallvm.qdb.write("/qubes-iptables", 'reload')

    def write_services(self, vm):
        for feature, value in vm.features.items():
            service = self.features_to_services.get(feature, feature)
            # forcefully convert to '0' or '1'
            vm.qdb.write('/qubes-service/{}'.format(service),
                str(int(bool(value))))
        if 'updates-proxy-setup' in vm.features.keys():
            vm.qdb.write('/qubes-service/{}'.format('yum-proxy-setup'),
                str(int(bool(vm.features['updates-proxy-setup']))))