Example #1
0
    def set_interface(self, interface):
        # Do some basic sanity checking of the fields
        ipa = create_ipaddr(interface.ip4addr)
        if not ipa:
            lg.error('invalid IP address ' + interface.ip4addr)
            return
        ipa = create_ipaddr(interface.ip4mask)
        if not ipa:
            lg.error('invalid IP mask ' + interface.ip4mask)
            return
        ipa = create_ipaddr(interface.ip4bcast)
        if not ipa:
            lg.error('invalid IP mask ' + interface.ip4bcast)
            return
        if interface.ip4gw != "":
            ipa = create_ipaddr(interface.ip4gw)
            if not ipa:
                lg.error('invalid IP gw ' + interface.ip4gw)
                return

        if not self.cfg:
            lg.error('local_config not enabled')
            return False
        try:
            self.cfg.set_interface(interface)
            self.post(
                pyevent(interface_change_event.static_get_name(),
                        interface_change_event(interface)))
        except Exception, e:
            lg.error('unable to set interface ' + interface.name)
Example #2
0
 def set_interface(self, interface):    
     # Do some basic sanity checking of the fields
     ipa = create_ipaddr(interface.ip4addr)
     if not ipa:
         lg.error('invalid IP address '+interface.ip4addr)
         return
     ipa = create_ipaddr(interface.ip4mask)
     if not ipa:
         lg.error('invalid IP mask '+interface.ip4mask)
         return
     ipa = create_ipaddr(interface.ip4bcast)
     if not ipa:
         lg.error('invalid IP mask '+interface.ip4bcast)
         return
     if interface.ip4gw != "":
         ipa = create_ipaddr(interface.ip4gw)
         if not ipa:
             lg.error('invalid IP gw '+interface.ip4gw)
             return
         
     if not self.cfg:
         lg.error('local_config not enabled')
         return False
     try:    
         self.cfg.set_interface(interface) 
         self.post(pyevent(interface_change_event.static_get_name(),
         interface_change_event(interface)))
     except Exception, e:
         lg.error('unable to set interface '+interface.name)
Example #3
0
def convert_to_ipaddr(val):
    if isinstance(val, ipaddr):
        return val.addr
    if isinstance(val, str) or isinstance(val, int) or isinstance(val, long):
        a = create_ipaddr(val)
        if a != None:
            return a.addr
    return None
Example #4
0
def convert_to_ipaddr(val):
    if isinstance(val, ipaddr):
        return val.addr
    if isinstance(val, str) or isinstance(val, int) or isinstance(val, long):
        a = create_ipaddr(val)
        if a != None:
            return a.addr
    return None
Example #5
0
def register_nwaddr_group(name, description, principals, subgroups):
    ips = [ netinet.create_ipaddr(p) for p in principals ]
    n = SEPL_DIRECTORY_NAME + ';'
    sgs = []
    for s in subgroups:
        if ';' not in s:
            sgs.append(n+s)
        else:
            sgs.append(s)
    return __instance__.add_group(Directory.NWADDR_GROUP,
                                  GroupInfo(name, description, ips, sgs))
Example #6
0
def __nwaddr_check__(addr):
    # should check if defined constant here

    if ((isinstance(addr, int) or isinstance(addr, long)) and addr >= 0 and addr <= 0xffffffff) \
            or isinstance(addr, basestring):
        addr = create_ipaddr(addr)
    elif not  isinstance(addr, ipaddr):
        return None

    if addr == None:
        return None

    return c_ntohl(addr.addr)
Example #7
0
def __nwaddr_check__(addr):
    # should check if defined constant here

    if ((isinstance(addr, int) or isinstance(addr, long)) and addr >= 0 and addr <= 0xffffffff) \
            or isinstance(addr, basestring):
        addr = create_ipaddr(addr)
    elif not isinstance(addr, ipaddr):
        return None

    if addr == None:
        return None

    return c_ntohl(addr.addr)
Example #8
0
    def desc_stats_in_handler(self, dpid, desc):
	lg.warn('############### desc_stats_in_handler ###############\n')
        self.dp_desc_stats[dpid] = desc
        ip = self.ctxt.get_switch_ip(dpid)
        self.dp_desc_stats[dpid]["ip"] = str(create_ipaddr(c_htonl(ip)))

	r.set('dp_desc_stats:' + str(dpid) + ':mfr_desc', self.dp_desc_stats[dpid]['mfr_desc'])
	r.set('dp_desc_stats:' + str(dpid) + ':hw_desc', self.dp_desc_stats[dpid]['hw_desc'])
	r.set('dp_desc_stats:' + str(dpid) + ':sw_desc', self.dp_desc_stats[dpid]['sw_desc'])
	r.set('dp_desc_stats:' + str(dpid) + ':serial_num', self.dp_desc_stats[dpid]['serial_num'])
	r.set('dp_desc_stats:' + str(dpid) + ':dp_desc', self.dp_desc_stats[dpid]['dp_desc'])

	print 'dp_desc_stats:' + str(dpid) + ':mrf_desc'
	print "dp_desc_stats[",dpid,"].mfr_desc = ", r.get('dp_desc_stats:' + str(dpid) + ':mfr_desc')
	print "dp_desc_stats[",dpid,"].hw_desc = ", r.get('dp_desc_stats:' + str(dpid) + ':hw_desc')
	print "dp_desc_stats[",dpid,"].sw_desc = ", r.get('dp_desc_stats:' + str(dpid) + ':sw_desc')
	print "dp_desc_stats[",dpid,"].serial_num= ", r.get('dp_desc_stats:' + str(dpid) + ':serial_num')
	print "dp_desc_stats[",dpid,"].dp_desc = ", r.get('dp_desc_stats:' + str(dpid) + ':dp_desc')
Example #9
0
def nwaddr_check(addr, translate=False):
    # should check if defined constant here

    if isinstance(addr, unicode):
        addr = addr.encode('utf-8')

    if ((isinstance(addr, int) or isinstance(addr, long)) and addr >= 0 and addr <= U32_MAX) \
            or isinstance(addr, str):
        addr = create_ipaddr(addr)
    elif not isinstance(addr, ipaddr):
        return defer.succeed(None)

    if addr is None:
        return defer.succeed(None)

    if translate:
        return addr.addr
    return defer.succeed(unicode(str(addr)))
Example #10
0
 def desc_stats_in_handler(self, dpid, desc):
     self.dp_desc_stats[dpid] = desc
     ip = self.ctxt.get_switch_ip(dpid)
     self.dp_desc_stats[dpid]["ip"] = str(create_ipaddr(c_htonl(ip)))
Example #11
0
    def emit(self):
        """
        Return an ISC DHCP daemon compliant main configuration file.
        """
        conf = "## Generated automatically from NOX database.\n" + \
            "## Use NOX to regenerate.\n\n"

        def conv(key, values):
            values = list(values)
            values = map(lambda v: v.value, values)

            if key.find('option_') == 0:
                # only 'options' require quotes around their string
                # parameters
                def quote(s):
                    #if isinstance(s, basestring): s = '"' + s + '"'
                    return s

                values = map(quote, values)

            values = map(lambda s: str(s), values)
            return ', '.join(values)

        for key in self.globals.keys():
            if key == 'option_domain-name':
                conf += '%s "%s";\n' % (key.replace('option_', 'option '),
                                        conv(key, self.globals[key]))
            else:
                conf += '%s %s;\n' % (key.replace('option_', 'option '),
                                      conv(key, self.globals[key]))

        conf += '\n'
            
        conf += "# Configured subnets:\n"
        subnets_configured = {}
        for subnet_id in self.subnets.keys():
            subnet = self.subnets[subnet_id]
            
            options = ''
            for key in subnet.keys():
                if key == 'subnet' or key == 'netmask' or \
                        key == 'range-start': continue

                if key == 'range-end':
                    # Range gets a special treatment
                    options += '  range %s %s;\n' % \
                        (conv('range', subnet['range-start']), 
                         conv('range', subnet['range-end']))
                elif key == 'option_domain-name':
                    options += '  %s "%s";\n' % \
                        (key.replace('option_', 'option '),
                         conv(key, subnet[key]))
                else:
                    options += '  %s %s;\n' % \
                        (key.replace('option_', 'option '),
                         conv(key, subnet[key]))

            ip = create_ipaddr(str(subnet['subnet'][0]))
            netmask = create_ipaddr(str(subnet['netmask'][0]))
            subnets_configured[ip & netmask] = True;

            conf += ("subnet %s netmask %s {\n" + options + \
                         "}\n") % (ip & netmask, netmask)

        conf += "# Stub entries for local network interfaces not above:\n"
        for interface in self.cfg.get_interfaces():
            ip = create_ipaddr(interface.ip4addr)
            netmask = create_ipaddr(interface.ip4mask)
            
            if not subnets_configured.has_key(ip & netmask) and \
                    not (ip & netmask) == create_ipaddr('127.0.0.0') and \
                    not (ip & netmask) == create_ipaddr('0.0.0.0'):
                conf += "subnet %s netmask %s { }\n" % (ip & netmask, netmask)
            
        conf += '\n'
            
        i = 0
        for hostname in self.fixedaddresses.keys():
            fixedaddress = self.fixedaddresses[hostname]

            addresses = map(lambda v: v.value, fixedaddress['ip4addr'])

            conf += ("# host '%s_%s'\nhost %s {\n  hardware ethernet %s;\n  fixed-address %s;\n}\n") % \
                (fixedaddress['directory'][0], 
                 fixedaddress['hostname'][0], 
                 'host_%d' % i,
                 fixedaddress['hwaddr'][0],
                 ', '.join(addresses))
            i += 1

        return conf
Example #12
0
class policyws(Component):
    def __init__(self, ctxt):
        Component.__init__(self, ctxt)
        self.cur_policy_table = 'current_policy'
        self.rule_table = 'policy_rules'
        self.policy = None
        self.v1 = None

    def install(self):
        self.policy = self.resolve(str(sepl.policy.PyPolicyComponent))
        self.v1 = self.resolve(str(webservice.webservice)).get_version("1")

        self.v1.register_request(
            protocolsws.get_protocols, "GET",
            (webservice.WSPathStaticString('protocols'), ),
            "Get the set of currently defined protocol.")

        self.v1.register_request(protocolsws.get_protocol, "GET",
                                 (webservice.WSPathStaticString('protocols'),
                                  protocolsws.WSPathExistProtocolIdent()),
                                 "Get a protocol's definition.")

        self.v1.register_request(protocolsws.modify_protocol, "PUT",
                                 (webservice.WSPathStaticString('protocols'),
                                  protocolsws.WSPathProtocolIdent()),
                                 "Modify/create a protocol's definition.")

        self.v1.register_request(protocolsws.delete_protocol, "DELETE",
                                 (webservice.WSPathStaticString('protocols'),
                                  protocolsws.WSPathExistProtocolIdent()),
                                 "Delete a protocol's definition.")

        self.v1.register_request(self.get_policy_names, "GET",
                                 (webservice.WSPathStaticString('policy'),
                                  webservice.WSPathStaticString('names')),
                                 "Get name mappings.")

        self.v1.register_request(self.get_policy, "GET",
                                 (webservice.WSPathStaticString('policy'), ),
                                 "Get installed policy id.")

        self.v1.register_request(self.get_stats, "GET", (
            webservice.WSPathStaticString('policy'),
            webservice.WSPathStaticString('stats'),
        ), "Get basic policy stats.")

        self.v1.register_request(
            self.reset_stats, "DELETE", (
                webservice.WSPathStaticString('policy'),
                webservice.WSPathStaticString('stats'),
            ), "Reset all policy stats; returns stats "
            "prior to delete")

        self.v1.register_request(self.get_rule, "GET",
                                 (webservice.WSPathStaticString('policy'),
                                  WSPathExistingPolicyId(self.policy),
                                  webservice.WSPathStaticString('rule'),
                                  WSPathExistingRuleId(self.policy)),
                                 "Get rule id's defintion.")
        # disabled since we need .../rule/<rule id>/<other_stuff>
        # we may want to move this under ../<rule id>/attribute/...
        #self.v1.register_request(self.get_rule_param, "GET",
        #                         (webservice.WSPathStaticString('policy'),
        #                          WSPathExistingPolicyId(self.policy),
        #                          webservice.WSPathStaticString('rule'),
        #                          WSPathExistingRuleId(self.policy),
        #                          WSPathRuleParam()),
        #                         "Get rule id's parameter value.")
        self.v1.register_request(self.get_rules, "GET",
                                 (webservice.WSPathStaticString('policy'),
                                  WSPathExistingPolicyId(self.policy),
                                  webservice.WSPathStaticString('rules')),
                                 "Get policy id's rules.")
        self.v1.register_request(self.get_rule_stats, "GET",
                                 (webservice.WSPathStaticString('policy'),
                                  WSPathExistingPolicyId(self.policy),
                                  webservice.WSPathStaticString('rule'),
                                  WSPathExistingRuleId(self.policy),
                                  webservice.WSPathStaticString('stats')),
                                 "Get rule id's enforcement stats.")
        self.v1.register_request(self.put_rule, "PUT",
                                 (webservice.WSPathStaticString('policy'),
                                  WSPathExistingPolicyId(self.policy),
                                  webservice.WSPathStaticString('rule'),
                                  WSPathExistingRuleId(self.policy)),
                                 "Modify a rule's attributes or definition.")
        self.v1.register_request(self.put_record_rule_senders, "PUT",
                                 (webservice.WSPathStaticString('policy'),
                                  WSPathExistingPolicyId(self.policy),
                                  webservice.WSPathStaticString('rule'),
                                  WSPathExistingRuleId(self.policy),
                                  webservice.WSPathStaticString('stats')),
                                 "Configure stats collection for a rule.")
        self.v1.register_request(self.put_analysis, "PUT",
                                 (webservice.WSPathStaticString('policy'),
                                  WSPathExistingPolicyId(self.policy),
                                  webservice.WSPathStaticString('analysis'),
                                  webservice.WSPathStaticString('rules')),
                                 "Analyze a new policy relative to another.")
        self.v1.register_request(self.delete_rule, "DELETE",
                                 (webservice.WSPathStaticString('policy'),
                                  WSPathExistingPolicyId(self.policy),
                                  webservice.WSPathStaticString('rule'),
                                  WSPathExistingRuleId(self.policy)),
                                 "Delete a rule by id.")
        self.v1.register_request(self.post_rules, "POST",
                                 (webservice.WSPathStaticString('policy'), ),
                                 "Post a new policy.")

    def err(self, failure, request, fn_name, msg):
        lg.error('%s: %s' % (fn_name, str(failure)))
        if isinstance(failure.value, DirectoryException) \
                and (failure.value.code == DirectoryException.COMMUNICATION_ERROR \
                or failure.value.code == DirectoryException.REMOTE_ERROR):
            msg = failure.value.message
        if isinstance(msg, str):
            msg = unicode(msg, 'utf-8')
        return webservice.internalError(request, msg)

    def badReq(self, failure, request, fn_name):
        lg.error('%s: %s' % (fn_name, str(failure)))
        msg = failure.value.message
        if isinstance(msg, str):
            msg = unicode(msg, 'utf-8')
        return webservice.badRequest(request, msg)

    def get_policy_names(self, request, data):
        try:
            content = web_arg_utils.flatten_args(request.args)
            keys = ['inport', 'dpsrc', 'dlsrc', 'dldst', 'nwsrc', 'nwdst']
            for key in keys:
                if not content.has_key(key):
                    return webservice.badRequest(
                        request, "Must include '%s' argument." % key)
            try:
                dp = create_datapathid_from_host(long(content['dpsrc']))
                if dp == None:
                    return webservice.badRequest(request,
                                                 "Invalid datapath ID.")
            except ValueError, e:
                return webservice.badRequest(request, "Invalid datapath.")
            try:
                port = int(content['inport'])
            except ValueError, e:
                return webservice.badRequest(request, "Invalid inport.")

            dlsrc = create_eaddr(content['dlsrc'])
            dldst = create_eaddr(content['dldst'])
            if dlsrc == None or dldst == None:
                return webservice.badRequest(request, "Invalid MAC address.")
            nwsrc = create_ipaddr(content['nwsrc'])
            nwdst = create_ipaddr(content['nwdst'])
            if nwsrc == None or nwdst == None:
                return webservice.badRequest(request, "Invalid IP address.")

            def cb(names):
                try:
                    request.write(simplejson.dumps(names))
                    request.finish()
                except Exception, e:
                    self.err(Failure(), request, "get_names",
                             "Could not retrieve name mappings.")
Example #13
0
        else:
            dlsrc = create_eaddr(self.dlsrc)
        if dlsrc == None:
            mako_args["name_err"] = "Invalid dlsrc."
            return self.render_tmpl(request, "policydebug.mako", args=mako_args)

        if self.dldst == '':
            dldst = create_eaddr(0)
        else:
            dldst = create_eaddr(self.dldst)
        if dldst == None:
            mako_args["name_err"] = "Invalid dldst."
            return self.render_tmpl(request, "policydebug.mako", args=mako_args)

        if self.nwsrc == '':
            nwsrc = create_ipaddr(0)
        else: 
            nwsrc = create_ipaddr(self.nwsrc)
        if nwsrc == None:
            mako_args["name_err"] = "Invalid nwsrc."
            return self.render_tmpl(request, "policydebug.mako", args=mako_args)

        if self.nwdst == '':
            nwdst = create_ipaddr(0)
        else:
            nwdst = create_ipaddr(self.nwdst)
        if nwdst == None:
            mako_args["name_err"] = "Invalid nwdst."
            return self.render_tmpl(request, "policydebug.mako", args=mako_args)

        def cb(names):