This file is indexed.

/usr/lib/python2.7/dist-packages/neutron_fwaas/services/firewall/plugins/cisco/cisco_fwaas_plugin.py is in python-neutron-fwaas 1:8.0.0-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# Copyright 2015 Cisco Systems, Inc.  All rights reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
#

from neutron.api.v2 import attributes as attr
from neutron.common import rpc as n_rpc
from neutron import context as neutron_context
from neutron import manager
from neutron.plugins.common import constants as const
from neutron_lib import constants as l3_const
from oslo_config import cfg
from oslo_log import helpers as log_helpers
from oslo_log import log as logging
import oslo_messaging

from neutron_fwaas._i18n import _LW
from neutron_fwaas.db.cisco import cisco_fwaas_db as csrfw_db
import neutron_fwaas.extensions
from neutron_fwaas.extensions.cisco import csr_firewall_insertion as csr_ext
from neutron_fwaas.services.firewall import fwaas_plugin as ref_fw_plugin

LOG = logging.getLogger(__name__)


class FirewallCallbacks(object):

    target = oslo_messaging.Target(version='1.0')

    def __init__(self, plugin):
        super(FirewallCallbacks, self).__init__()
        self.plugin = plugin

    @log_helpers.log_method_call
    def set_firewall_status(self, context, firewall_id, status,
                            status_data=None, **kwargs):
        """Agent uses this to set a firewall's status."""
        with context.session.begin(subtransactions=True):
            fw_db = self.plugin._get_firewall(context, firewall_id)
            # ignore changing status if firewall expects to be deleted
            # That case means that while some pending operation has been
            # performed on the backend, neutron server received delete request
            # and changed firewall status to const.PENDING_DELETE
            if status == const.ERROR:
                fw_db.status = const.ERROR
                return False
            if fw_db.status == const.PENDING_DELETE:
                LOG.debug("Firewall %(fw_id)s in PENDING_DELETE state, "
                          "not changing to %(status)s",
                          {'fw_id': firewall_id, 'status': status})
                return False
            if status in (const.ACTIVE, const.INACTIVE):
                fw_db.status = status
                csrfw = self.plugin.lookup_firewall_csr_association(context,
                    firewall_id)
                _fw = {'id': csrfw['fw_id'], 'port_id': csrfw['port_id'],
                       'direction': csrfw['direction'],
                       'acl_id': status_data['acl_id']}
                self.plugin.update_firewall_csr_association(context,
                    firewall_id, _fw)
            else:
                fw_db.status = const.ERROR

    @log_helpers.log_method_call
    def firewall_deleted(self, context, firewall_id, **kwargs):
        """Agent uses this to indicate firewall is deleted."""
        with context.session.begin(subtransactions=True):
            fw_db = self.plugin._get_firewall(context, firewall_id)
            # allow to delete firewalls in ERROR state
            if fw_db.status in (const.PENDING_DELETE, const.ERROR):
                self.plugin.delete_db_firewall_object(context, firewall_id)
                return True
            LOG.warning(_LW('Firewall %(fw)s unexpectedly deleted by agent, '
                            'status was %(status)s'),
                        {'fw': firewall_id, 'status': fw_db.status})
            fw_db.status = const.ERROR
        return False

    @log_helpers.log_method_call
    def get_firewalls_for_tenant(self, context, **kwargs):
        """Agent uses this to get all firewalls and rules for a tenant."""
        fw_list = []
        for fw in self.plugin.get_firewalls(context):
            fw_with_rules = (
                self.plugin._make_firewall_dict_with_rules(context, fw['id']))
            csrfw = self.plugin.lookup_firewall_csr_association(context,
                fw['id'])
            router_id = csrfw['router_id']
            fw_with_rules['vendor_ext'] = self.plugin._get_hosting_info(
                context, csrfw['port_id'], router_id, csrfw['direction'])
            fw_with_rules['vendor_ext']['acl_id'] = csrfw['acl_id']
            fw_list.append(fw_with_rules)
        return fw_list

    @log_helpers.log_method_call
    def get_firewalls_for_tenant_without_rules(self, context, **kwargs):
        """Agent uses this to get all firewalls for a tenant."""
        return [fw for fw in self.plugin.get_firewalls(context)]

    @log_helpers.log_method_call
    def get_tenants_with_firewalls(self, context, **kwargs):
        """Agent uses this to get all tenants that have firewalls."""
        ctx = neutron_context.get_admin_context()
        fw_list = self.plugin.get_firewalls(ctx)
        return list(set(fw['tenant_id'] for fw in fw_list))


class FirewallAgentApi(object):
    """Plugin side of plugin to agent RPC API."""

    def __init__(self, topic, host):
        self.host = host
        target = oslo_messaging.Target(topic=topic, version='1.0')
        self.client = n_rpc.get_client(target)

    def create_firewall(self, context, firewall):
        cctxt = self.client.prepare(fanout=True)
        cctxt.cast(context, 'create_firewall', firewall=firewall,
                   host=self.host)

    def update_firewall(self, context, firewall):
        cctxt = self.client.prepare(fanout=True)
        cctxt.cast(context, 'update_firewall', firewall=firewall,
                   host=self.host)

    def delete_firewall(self, context, firewall):
        cctxt = self.client.prepare(fanout=True)
        cctxt.cast(context, 'delete_firewall', firewall=firewall,
                   host=self.host)


class CSRFirewallPlugin(ref_fw_plugin.FirewallPlugin,
                        csrfw_db.CiscoFirewall_db_mixin):

    """Implementation of the Neutron Firewall Service Plugin.

    This class implements the Cisco CSR FWaaS Service Plugin,
    inherits from the fwaas ref plugin as no changes are made
    to handling fwaas policy and rules. The CRUD methods are
    overridden to provide for the specific implementation. The
    basic fwaas db is managed thru the firewall_db.Firewall_db_mixin.
    The backend specific associations are captured in the new table,
    csrfw_db.CiscoFirewall_db_mixin.
    """
    supported_extension_aliases = ["fwaas", "csrfirewallinsertion"]

    def __init__(self):
        """Do the initialization for the firewall service plugin here."""

        ext_path = neutron_fwaas.extensions.__path__[0] + '/cisco'
        if ext_path not in cfg.CONF.api_extensions_path.split(':'):
            cfg.CONF.set_override('api_extensions_path',
                              cfg.CONF.api_extensions_path + ':' + ext_path)

        self.endpoints = [FirewallCallbacks(self)]

        self.conn = n_rpc.create_connection()
        self.conn.create_consumer(
            'CISCO_FW_PLUGIN', self.endpoints, fanout=False)
        self.conn.consume_in_threads()

        self.agent_rpc = FirewallAgentApi(
            'CISCO_FW',
            cfg.CONF.host
        )

    def _rpc_update_firewall(self, context, firewall_id):
        status_update = {"firewall": {"status": const.PENDING_UPDATE}}
        fw = super(ref_fw_plugin.FirewallPlugin, self).update_firewall(
            context, firewall_id, status_update)
        if fw:
            fw_with_rules = (
                self._make_firewall_dict_with_rules(context,
                                                    firewall_id))
            csrfw = self.lookup_firewall_csr_association(context, firewall_id)
            fw_with_rules['vendor_ext'] = self._get_hosting_info(context,
                csrfw['port_id'], csrfw['router_id'], csrfw['direction'])
            fw_with_rules['vendor_ext']['acl_id'] = csrfw['acl_id']
            LOG.debug("Update of Rule or policy: fw_with_rules: %s",
                fw_with_rules)
            self.agent_rpc.update_firewall(context, fw_with_rules)

    @log_helpers.log_method_call
    def _validate_fw_port_and_get_router_id(self, context, tenant_id, port_id):
        # port validation with router plugin
        l3_plugin = manager.NeutronManager.get_service_plugins().get(
            const.L3_ROUTER_NAT)
        ctx = neutron_context.get_admin_context()
        routers = l3_plugin.get_routers(ctx)
        router_ids = [
            router['id']
            for router in routers
            if router['tenant_id'] == tenant_id]
        port_db = self._core_plugin._get_port(context, port_id)
        if not (port_db['device_id'] in router_ids and
                port_db['device_owner'] == l3_const.DEVICE_OWNER_ROUTER_INTF):
            raise csr_ext.InvalidInterfaceForCSRFW(port_id=port_id)
        return port_db['device_id']

    def _map_csr_device_info_for_agent(self, hosting_device):
        return {'host_mngt_ip': hosting_device['management_ip_address'],
                'host_usr_nm': hosting_device['credentials']['username'],
                'host_usr_pw': hosting_device['credentials']['password']}

    def _get_service_insertion_points(self, context, interfaces, port_id,
            direction):
        insertion_point = dict()
        hosting_info = dict()
        for interface in interfaces:
            if interface['id'] == port_id:
                hosting_info = interface['hosting_info']
        if not hosting_info:
            raise csr_ext.InvalidRouterHostingInfoForCSRFW(port_id=port_id)
        insertion_point['port'] = {'id': port_id,
            'hosting_info': hosting_info}
        insertion_point['direction'] = direction
        return [insertion_point]

    def _get_hosting_info(self, context, port_id, router_id, direction):
        l3_plugin = manager.NeutronManager.get_service_plugins().get(
            const.L3_ROUTER_NAT)
        ctx = neutron_context.get_admin_context()
        routers = l3_plugin.get_sync_data_ext(ctx)
        for router in routers:
            if router['id'] == router_id:
                vendor_ext = self._map_csr_device_info_for_agent(
                    router['hosting_device'])
                vendor_ext['if_list'] = self._get_service_insertion_points(
                    context, router['_interfaces'], port_id, direction)
                return vendor_ext
        # TODO(sridar): we may need to raise an excp - check backlogging

    @log_helpers.log_method_call
    def create_firewall(self, context, firewall):
        port_id = firewall['firewall'].pop('port_id', None)
        direction = firewall['firewall'].pop('direction', None)

        if port_id == attr.ATTR_NOT_SPECIFIED:
            LOG.debug("create_firewall() called")
            port_id = None
            router_id = None
        else:
            # TODO(sridar): add check to see if the new port-id does not have
            # any associated firewall.
            router_id = self._validate_fw_port_and_get_router_id(context,
                firewall['firewall']['tenant_id'], port_id)

        if direction == attr.ATTR_NOT_SPECIFIED:
            direction = None

        firewall['firewall']['status'] = const.PENDING_CREATE
        fw = super(ref_fw_plugin.FirewallPlugin, self).create_firewall(
            context, firewall)
        fw_with_rules = (
            self._make_firewall_dict_with_rules(context, fw['id']))

        if not port_id and not direction:
            return fw

        # Add entry into firewall associations table
        _fw = {'id': fw['id'], 'port_id': port_id,
            'direction': direction, 'router_id': router_id, 'acl_id': None}
        self.add_firewall_csr_association(context, _fw)

        if port_id and direction:
            fw_with_rules['vendor_ext'] = self._get_hosting_info(context,
                port_id, router_id, direction)
            fw_with_rules['vendor_ext']['acl_id'] = None

            self.agent_rpc.create_firewall(context, fw_with_rules)
        return fw

    @log_helpers.log_method_call
    def update_firewall(self, context, fwid, firewall):
        self._ensure_update_firewall(context, fwid)
        csrfw = self.lookup_firewall_csr_association(context, fwid)

        port_id = firewall['firewall'].pop('port_id', None)
        direction = firewall['firewall'].pop('direction', None)

        _fw = {'id': fwid}

        if port_id:
            tenant_id = self.get_firewall(context, fwid)['tenant_id']
            router_id = self._validate_fw_port_and_get_router_id(context,
                tenant_id, port_id)
            if csrfw and csrfw['port_id']:
                # TODO(sridar): add check to see if the new port_id does not
                # have any associated firewall.

                # we only support a different port if associated
                # with the same router
                if router_id != csrfw['router_id']:
                    raise csr_ext.InvalidRouterAssociationForCSRFW(
                        port_id=port_id)
            _fw['port_id'] = port_id
            _fw['router_id'] = router_id
        else:
            _fw['port_id'] = csrfw['port_id'] if csrfw else None
            _fw['router_id'] = csrfw['router_id'] if csrfw else None

        if direction:
            _fw['direction'] = direction
        else:
            _fw['direction'] = csrfw['direction'] if csrfw else None

        _fw['acl_id'] = csrfw['acl_id'] if csrfw else None

        self.update_firewall_csr_association(context, fwid, _fw)

        firewall['firewall']['status'] = const.PENDING_UPDATE

        fw = super(ref_fw_plugin.FirewallPlugin, self).update_firewall(
            context, fwid, firewall)
        fw_with_rules = (
            self._make_firewall_dict_with_rules(context, fw['id']))

        if _fw['port_id'] and _fw['direction']:

            fw_with_rules['vendor_ext'] = self._get_hosting_info(context,
                port_id, csrfw['router_id'], direction)
            fw_with_rules['vendor_ext']['acl_id'] = csrfw['acl_id']
            LOG.debug("CSR Plugin update: fw_with_rules: %s", fw_with_rules)
            self.agent_rpc.update_firewall(context, fw_with_rules)
        return fw

    @log_helpers.log_method_call
    def delete_firewall(self, context, fwid):
        self._ensure_update_firewall(context, fwid)

        status_update = {"firewall": {"status": const.PENDING_DELETE}}
        fw = super(ref_fw_plugin.FirewallPlugin, self).update_firewall(
            context, fwid, status_update)

        # given that we are not in a PENDING_CREATE we should have
        # an acl_id - since it is not present something bad has happened
        # on the backend and no sense in sending a msg to the agent.
        # Clean up ...
        csrfw = self.lookup_firewall_csr_association(context, fwid)
        if not csrfw or not csrfw['acl_id']:
            self.delete_db_firewall_object(context, fwid)
            return

        fw_with_rules = (
            self._make_firewall_dict_with_rules(context, fw['id']))

        fw_with_rules['vendor_ext'] = self._get_hosting_info(context,
            csrfw['port_id'], csrfw['router_id'], csrfw['direction'])
        fw_with_rules['vendor_ext']['acl_id'] = csrfw['acl_id']

        self.agent_rpc.delete_firewall(context, fw_with_rules)

    @log_helpers.log_method_call
    def get_firewall(self, context, fwid, fields=None):
        res = super(ref_fw_plugin.FirewallPlugin, self).get_firewall(
                        context, fwid, fields)
        csrfw = self.lookup_firewall_csr_association(context, res['id'])
        if not csrfw:
            return res
        res['port_id'] = csrfw['port_id']
        res['direction'] = csrfw['direction']
        res['router_id'] = csrfw['router_id']
        return res