Beispiel #1
0
def getIfFlags(interface):
    """ Get the interface flags of a given interface """
    logging.debugv("functions/linux.py->getIfFlags(interface)", [interface])

    if not interface:
        raise excepts.InterfaceException, "No interface argument was given"

    # set some symbolic constants
    SIOCGIFFLAGS = 0x8913
    null256 = '\0'*256
    active_flags = ""

    # create a socket so we have a handle to query
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    try:
        # call ioctl() to get the flags for the given interface
        result = fcntl.ioctl(s.fileno(), SIOCGIFFLAGS, interface + null256)

        # extract the interface's flags from the return value
        flags, = struct.unpack('H', result[16:18])

        binflags = tools.dec2bin(flags)
        binflags = binflags[::-1]
        i = 0
        for b in binflags:
            if int(b) == 1:
                active_flags += " " + str(inf_flags[i])
            i += 1
        active_flags = active_flags.lstrip()
        return active_flags
    except IOError:
        raise excepts.InterfaceException, "Interface %s was not found" % interface
Beispiel #2
0
    def __init__(self, d):
        # d = dialog object
        logging.debugv("menu/manage.py->__init__(self, d)", [])
        self.d = d

        # c = config object
        self.c = config.Config()
Beispiel #3
0
def setIptables(dev):
    """ Sets loop protection via iptables """
    logging.debugv("functions/linux.py->setIptables(dev)", [dev])
    try:
        runWrapper([locations.IPTABLES, "-A", "OUTPUT", "-p", "TCP", "-m", "physdev", "--physdev-out", dev, "--dport", "1194", "-j", "DROP"], True)
    except:
        logging.error("Setting up loop protection with iptables failed")
Beispiel #4
0
    def setTotalVlans(self):
        """ Edit the amount of VLANs that need to be configured """
        logging.debugv("menu/config.py->setTotalVlans(self)", [])

        title = "\\ZbConfig > Network > VLANs\\n\\ZB"
        subtitle = "Enter the number of vlans you want to use"
        title += subtitle
        vlannum = self.c.getTotalVlans()
        while True:
            output = self.d.inputbox(title, 10, 50, str(vlannum), colors=1)
            if output[0] == 1: return
            else:
                if output[1].isdigit() and str(output[1]) != '0':
                    if vlannum != output[1]:
                        logging.debug("Setting number of vlans to %s" %
                                      str(output[1]))
                        # Make sure vlans are created
                        for i in range(0, int(output[1])):
                            # first entry in dict is 0
                            self.c.getVlan(i)
                            self.changed = True

                    return  # returns to configNetwork()
                else:
                    self.d.msgbox(
                        "Invalid number of VLANs. Enter a valid integer between 1 and 4095",
                        width=60)
        return  # returns to configNetwork()
Beispiel #5
0
    def upgrade(self):
        """ Update the sensor software via APT """
        logging.debugv("menu/config.py->upgrade(self)", [])

        self.d.infobox("Updating sensor...")
        f.aptUpdate()
        f.aptInstall()
Beispiel #6
0
def update():
    """ Update status info to the server """
    logging.debugv("functions/__init__.py->update()", [])

    # Get the main interface, return if no interface has been configured
    try:
        inf = c.getMainIf()
    except excepts.InterfaceException:
        logging.error("Could not find an interface configuration.")
        return

    # Get the localIp
    localIp = getLocalIp()

    ssh = int(sshStatus())
    try:
        mac = getMac(inf)
    except excepts.InterfaceException:
        mac = "00:00:00:00:00:00"

    if c.getAutoUpdate() == "Enabled":
        # Do all the APT stuff
        aptUpdate()
        try:
            sensorDown()
        except:
            allTunnelsDown
            allInfsDown()
            networkUp()

        aptInstall()

    ac = client.update(localIp, ssh, mac, getPackageVersion())
    if ac:
        action(ac)  
Beispiel #7
0
    def setSensorType(self):
        """ Submenu for choosing a sensor type """
        logging.debugv("menu/config.py->setSensorType(self)", [])
        type = self.c.getSensorType()
        choices = [
            ("Normal", "Normal sensor", int(type == "normal")),
            ("Vlan", "VLAN sensor", int(type == "vlan")),
        ]

        title = "\\ZbStart > Configure > Network > Sensor type\\n\\ZBSelect the type of sensor"
        choice = self.d.radiolist(title,
                                  choices=choices,
                                  cancel="Cancel",
                                  ok_label="Ok",
                                  height=20,
                                  colors=1)
        if choice[0] == 1: return
        elif choice[1] == "Normal":
            self.c.netconf['sensortype'] = "normal"
            self.c.resetTrunk()
            self.c.netconf.write()
            self.changed = True
            return  # returns to configNetwork()
        elif choice[1] == "Vlan":
            self.c.netconf['sensortype'] = "vlan"
            self.c.netconf.write()
            self.changed = True
            return  # returns to configNetwork()
        return  # returns to configNetwork()
Beispiel #8
0
def makeRequest(request, args):
    """ Send a request to the tunnel server.  """
    logging.debugv("client.py->makeRequest(request, args)", [request, args])

    serverurl = c.getServerurl()
    user = c.getUser()
    passwd = c.getPasswd()

    if type(args) == type(list()):
        newargs = ""
        for urlarg in args:
            newargs = newargs + "&" + urlarg[0] + "=" + urlarg[1]
        newargs = newargs.lstrip("&")
        url = serverurl + request + "?" + newargs
    else:
        url = serverurl + request + "?" + args

    logging.info("MRQ: Requesting " + url)

    auth_handler = urllib2.HTTPBasicAuthHandler()
    auth_handler.add_password(realm='Certificates', uri=url, user=user, passwd=passwd)
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)

    try:    
        result = urllib2.urlopen(url)
        logging.debug("MRQ: Success")
        return result
    except urllib2.URLError, (strerror):
        msg = "Could not process HTTP request: " + str(strerror)
        logging.error(msg)
        raise excepts.NetworkException, msg
Beispiel #9
0
 def run(self):
 	logging.debugv("manager.py->run(self)", [])
     logging.info("SURFids manager starting")
     try:
         f.networkUp()
     except excepts.ConfigException, msg:
         logging.warn(msg)
Beispiel #10
0
def update(localip, ssh, mac, pversion):
    """ updates interface @ ids server """
    logging.debugv("client.py->update(localip, ssh, mac, pversion)", [localip, ssh, mac, pversion])

    logging.info("Updating @ IDS server")

    sensorid = c.getSensorID()
    req = "status.php"
    args = urllib.urlencode((
        ('strip_html_escape_keyname', sensorid),
        ('ip_localip', localip),
        ('int_ssh', ssh),
        ('mac_mac', mac),
        ('strip_html_escape_pversion', pversion))
    )

    try:
        x = makeRequest(req, args)
    except excepts.NetworkException:
        logging.warning("Could not sync with server!")
        action = None
    else:
        action = None
        for line in [x.strip() for x in x.readlines()]:
            logging.debug(line)
            if line.startswith("ACTION:"):
                action = line.split()[1]
                logging.debug("Received action: " + action)
    if action:
        return action.lower()
    else:
        return False
Beispiel #11
0
def saveAptOutput(args):
    """ Save apt-get output to the server """
    logging.debugv("client.py->saveAptOutput(args)", [args])

    sensorid = c.getSensorID()
    req = "save_apt.php"
    i = 0
    partargs = []
    # Due to max size limit of URL's, save output 10 lines at a time
    for part in args[:]:
        i = i + 1
        partargs.append(part)
        if i == 10:
            partargs.append(('strip_html_escape_keyname', sensorid))
            logging.debug("WATCHME PARTARGS: %s" % str(partargs))
            partargs = urllib.urlencode(partargs)
            try:
                x = makeRequest(req, partargs)
            except excepts.NetworkException:
                logging.warning("Could not save update info to server!")
            partargs = []
            i = 0

    logging.debug("WATCHME PARTARGS-2: %s" % str(partargs))
    # Save leftover lines if any
    if len(partargs) > 0:
        partargs.append(('strip_html_escape_keyname', sensorid))
        partargs = urllib.urlencode(partargs)
        try:
            x = makeRequest(req, args)
        except excepts.NetworkException:
            logging.warning("Could not save update info to server!")
Beispiel #12
0
 def getBridgeDev(self, interface):
     """ Get the bridge device of a given interface """
     logging.debugv("runtime.py->getBridgeDev(self, interface)", [interface])
     try:
         return self.config['infs'][interface]['bridgedev']
     except KeyError:
         return False
Beispiel #13
0
def bridgify(inf, infConf, bridgeNumber):
    """ Creates and configures a bridge """
    logging.debugv("functions/linux.py->bridgify(inf, infConf, bridgeNumber)",
                   [inf, infConf, bridgeNumber])
    tapdev = addTap(bridgeNumber)
    brdev = addBridge(bridgeNumber, [tapdev, inf])

    pidfile = locations.PID + 'dhcp-' + inf + '.pid'
    if os.access(pidfile, os.R_OK):
        logging.info("Trying to kill DHCP daemon for %s" % inf)
        killDhcp(pidfile)

    ip = False
    if infConf['type'] == "dhcp":
        ifUp(inf)
        # using linux you need to give the bridge itself an IP
        # using openbsd you need to give the interface in the brdige an IP
        ip = ifUpDhcp(brdev)

    elif infConf['type'] == "static":
        ip = ifUpStatic(brdev, infConf['address'], infConf['netmask'])
        # set gateway
        if getGw(inf):
            delGw(inf)
        if infConf['gateway']:
            addGw(infConf['gateway'])
    setIptables(tapdev)

    return (brdev, ip)
Beispiel #14
0
def ipmiSetNet(dict):
    """ Set an IPMI lan property """
    logging.debugv("functions/linux.py->ipmiSetNet(dict)", [str(dict)])

    cmd = [locations.IPMITOOL, "-I", "open", "lan", "set", str(1)]
    cmd += dict
    ipmiWrapper(cmd)
Beispiel #15
0
def bridgify(inf, infConf, bridgeNumber):
    """ Creates and configures a bridge """
    logging.debugv("functions/linux.py->bridgify(inf, infConf, bridgeNumber)", [inf, infConf, bridgeNumber])
    tapdev = addTap(bridgeNumber)
    brdev = addBridge(bridgeNumber, [tapdev, inf])

    pidfile = locations.PID + 'dhcp-' + inf + '.pid'
    if os.access(pidfile, os.R_OK):
        logging.info("Trying to kill DHCP daemon for %s" % inf)
        killDhcp(pidfile)

    ip = False
    if infConf['type'] == "dhcp":
        ifUp(inf)
        # using linux you need to give the bridge itself an IP
        # using openbsd you need to give the interface in the brdige an IP
        ip = ifUpDhcp(brdev)

    elif infConf['type'] == "static":
        ip = ifUpStatic(brdev, infConf['address'], infConf['netmask'])
        # set gateway
        if getGw(inf):
            delGw(inf)
        if infConf['gateway']:
            addGw(infConf['gateway'])
    setIptables(tapdev)

    return (brdev, ip)
Beispiel #16
0
    def __init__(self, d):
        # d = dialog object
        logging.debugv("menu/manage.py->__init__(self, d)", [])
        self.d = d

        # c = config object
        self.c = config.Config()
Beispiel #17
0
def suppressDmesg():
    """ Suppress syslog messages from showing on the console
        except panic messages
    """
    logging.debugv("functions/linux.py->suppressDmesg()", [])
    cmd = [locations.DMESG, "-n", "1"]
    runWrapper(cmd)
Beispiel #18
0
    def getConfig(self):
        """ Display the latest configuration from the server """
        logging.debugv("menu/manage.py->getConfig(self)", [])

        config = client.getConfig()
        #functions.saveNetConf(config)
        self.d.msgbox(config, height=20, width=60)
Beispiel #19
0
 def dns(self):
     """ Submenu of network, DNS settings menu """
     logging.debugv("menu/config.py->dns(self)", [])
     (type, prim, sec) = self.c.getDNS()
     choices = [("Type", type)]
     if type == "static":
         choices += [
             ("Primary DNS server", prim),
             ("Secondary DNS server", sec),
         ]
     title = "\\ZbStart > Configure > DNS\\n\\ZBSelect the item you want to configure"
     choice = self.d.menu(title,
                          choices=choices,
                          cancel="Back",
                          ok_label="Edit",
                          colors=1)
     if choice[0] == 1:
         try:
             self.c.validDNSConf()
         except excepts.ConfigException, err:
             self.invalidDNSConfAction()
             return
         else:
             if self.changed:
                 self.c.addRev()
                 f.backupNetConf(self.c.getRev())
                 self.activateChoice()
             return
Beispiel #20
0
 def ping(self):
     """ Send a ping to predefined addresses """
     logging.debugv("menu/manage.py->ping(self)", [])
     self.d.infobox("Sending ping...")
     result = tools.ping(tools.hosts)
     if result: self.d.msgbox("Ping OK")
     else: self.d.msgbox("Ping failed, there is something wrong with your settings or you can't sent ICMP packages")
Beispiel #21
0
    def setTrunkIf(self):
        """ Submenu for choosing the trunk interface """
        logging.debugv("menu/config.py->setTrunkIf(self)", [])

        title = "\\Zb... > Configure > Network > Setup trunk interface\\n\\ZB"
        title += "Select the trunk interface"

        infs = f.ifList()
        choices = [(x, self.c.chkMainInf(x), int(self.c.getTrunkIf() == x))
                   for x in infs]
        choice = self.d.radiolist(title,
                                  choices=choices,
                                  cancel="Back",
                                  ok_label="Ok",
                                  height=20,
                                  colors=1)
        if choice[0] == 1: return  # returns to configNetwork()
        else:
            if choice[1] == self.c.getMainIf():
                self.d.msgbox(
                    "The trunk interface cannot be the same as the main interface!"
                )
            else:
                logging.info("Setting trunk interface to %s" % choice[1])
                self.c.setTrunk(choice[1])
                self.changed = True
        return  # returns to configNetwork()
Beispiel #22
0
def update(localip, ssh, mac, pversion):
    """ updates interface @ ids server """
    logging.debugv("client.py->update(localip, ssh, mac, pversion)",
                   [localip, ssh, mac, pversion])

    logging.info("Updating @ IDS server")

    sensorid = c.getSensorID()
    req = "status.php"
    args = urllib.urlencode(
        (('strip_html_escape_keyname', sensorid), ('ip_localip', localip),
         ('int_ssh', ssh), ('mac_mac', mac), ('strip_html_escape_pversion',
                                              pversion)))

    try:
        x = makeRequest(req, args)
    except excepts.NetworkException:
        logging.warning("Could not sync with server!")
        action = None
    else:
        action = None
        for line in [x.strip() for x in x.readlines()]:
            logging.debug(line)
            if line.startswith("ACTION:"):
                action = line.split()[1]
                logging.debug("Received action: " + action)
    if action:
        return action.lower()
    else:
        return False
Beispiel #23
0
    def adminMenu(self):
        """ Administrator menu """
        logging.debugv("menu/config.py->adminMenu(self)", [])

        title = "\\ZbStart > Network > Admin\\n\\ZB"
        subtitle = "Admin configuration"
        title += subtitle
        choices = [
            ('Serverurl', self.c.getServerurl()),
            ('User', self.c.getUser()),
            ('Passwd', len(self.c.getPasswd()) * '*'),
            ('Update', "Update the sensor via APT"),
            ('AutoUpdate', self.c.getAutoUpdate()),
        ]
        choice = self.d.menu(title, choices=choices, cancel="back", colors=1)

        if choice[0] == 1: return
        elif choice[1] == "Serverurl": self.setServerurl()
        elif choice[1] == "User": self.setUser()
        elif choice[1] == "Passwd": self.setPasswd()
        elif choice[1] == "Update": self.upgrade()
        elif choice[1] == "AutoUpdate":
            if self.c.getAutoUpdate() == "Enabled":
                self.disableAutoUpdate()
            else:
                self.enableAutoUpdate()
        self.adminMenu()
Beispiel #24
0
def saveAptOutput(args):
    """ Save apt-get output to the server """
    logging.debugv("client.py->saveAptOutput(args)", [args])

    sensorid = c.getSensorID()
    req = "save_apt.php"
    i = 0
    partargs = []
    # Due to max size limit of URL's, save output 10 lines at a time
    for part in args[:]:
        i = i + 1
        partargs.append(part)
        if i == 10:
            partargs.append(('strip_html_escape_keyname', sensorid))
            logging.debug("WATCHME PARTARGS: %s" % str(partargs))
            partargs = urllib.urlencode(partargs)
            try:
                x = makeRequest(req, partargs)
            except excepts.NetworkException:
                logging.warning("Could not save update info to server!")
            partargs = []
            i = 0

    logging.debug("WATCHME PARTARGS-2: %s" % str(partargs))
    # Save leftover lines if any
    if len(partargs) > 0:
        partargs.append(('strip_html_escape_keyname', sensorid))
        partargs = urllib.urlencode(partargs)
        try:
            x = makeRequest(req, args)
        except excepts.NetworkException:
            logging.warning("Could not save update info to server!")
Beispiel #25
0
    def setIpmi(self):
        """ Submenu for configuring IPMI settings """
        logging.debugv("menu/config.py->setIpmi(self)", [])

        address = self.c.getIpmiAddress()
        netmask = self.c.getIpmiNetmask()
        gwip = self.c.getIpmiGatewayIP()
        gwmac = self.c.getIpmiGatewayMAC()
        vlanid = self.c.getIpmiVlanID()

        choices = [
            ("IP Address", "[%s]" % str(address)),
            ("Netmask", "[%s]" % str(netmask)),
            ("Gateway IP", "[%s]" % str(gwip)),
            ("Gateway MAC", "[%s]" % str(gwmac)),
            ("VLAN ID", "[%s] (optional)" % str(vlanid)),
            ("Users", "IPMI User management..."),
        ]
        choice = self.d.menu("Configure the IPMI interface",
                             choices=choices,
                             cancel="back",
                             width=60)
        if choice[0] == 1: return
        elif choice[1] == "IP Address": self.editIpmiAddress()
        elif choice[1] == "Netmask": self.editIpmiNetmask()
        elif choice[1] == "Gateway IP": self.editIpmiGatewayIP()
        elif choice[1] == "Gateway MAC": self.editIpmiGatewayMAC()
        elif choice[1] == "VLAN ID": self.editIpmiVlanID()
        elif choice[1] == "Users": self.editIpmiUsers()
        self.setIpmi()
Beispiel #26
0
def makeRequest(request, args):
    """ Send a request to the tunnel server.  """
    logging.debugv("client.py->makeRequest(request, args)", [request, args])

    serverurl = c.getServerurl()
    user = c.getUser()
    passwd = c.getPasswd()

    if type(args) == type(list()):
        newargs = ""
        for urlarg in args:
            newargs = newargs + "&" + urlarg[0] + "=" + urlarg[1]
        newargs = newargs.lstrip("&")
        url = serverurl + request + "?" + newargs
    else:
        url = serverurl + request + "?" + args

    logging.info("MRQ: Requesting " + url)

    auth_handler = urllib2.HTTPBasicAuthHandler()
    auth_handler.add_password(realm='Certificates',
                              uri=url,
                              user=user,
                              passwd=passwd)
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)

    try:
        result = urllib2.urlopen(url)
        logging.debug("MRQ: Success")
        return result
    except urllib2.URLError, (strerror):
        msg = "Could not process HTTP request: " + str(strerror)
        logging.error(msg)
        raise excepts.NetworkException, msg
Beispiel #27
0
    def getConfig(self):
        """ Display the latest configuration from the server """
        logging.debugv("menu/manage.py->getConfig(self)", [])

        config = client.getConfig()
        #functions.saveNetConf(config)
        self.d.msgbox(config, height=20, width=60)
Beispiel #28
0
def getIfFlags(interface):
    """ Get the interface flags of a given interface """
    logging.debugv("functions/linux.py->getIfFlags(interface)", [interface])
    # set some symbolic constants
    SIOCGIFFLAGS = 0xc0206911
    null256 = '\0' * 256
    active_flags = ""

    # create a socket so we have a handle to query
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    try:
        # call ioctl() to get the flags for the given interface
        result = fcntl.ioctl(s.fileno(), SIOCGIFFLAGS, interface + null256)

        # extract the interface's flags from the return value
        flags, = struct.unpack('H', result[16:18])

        binflags = tools.dec2bin(flags)
        binflags = binflags[::-1]
        i = 0
        for b in binflags:
            if int(b) == 1:
                active_flags += " " + str(inf_flags[i])
            i += 1
        active_flags = active_flags.lstrip()
        return active_flags
    except IOError:
        raise excepts.InterfaceException, "Interface %s was not found" % interface
Beispiel #29
0
def suppressDmesg():
    """ Suppress syslog messages from showing on the console
        except panic messages
    """
    logging.debugv("functions/linux.py->suppressDmesg()", [])
    cmd = [locations.DMESG, "-n", "1"]
    runWrapper(cmd)
Beispiel #30
0
 def run(self):
     logging.debugv("manager.py->run(self)", [])
     logging.info("SURFids manager starting")
     try:
         f.networkUp()
     except excepts.ConfigException, msg:
         logging.warn(msg)
Beispiel #31
0
def addVlan(interface, vlanid):
    """ Add a vlan config to an interface. Return vlan device name """
    logging.debugv("functions/linux.py->addVlan(interface, vlanid)", [interface, vlanid])
    logging.info("Creating a vlan configuration on %s with vlanid %s" % (interface, vlanid) )
    cmd = ["vconfig", "add", interface, vlanid]
    runWrapper(cmd)
    return "%s.%s" % (interface, vlanid)
Beispiel #32
0
    def run(self):
        """ The main menu """
        logging.debugv("menu/__init__.py->run(self)", [])

        if not self.c.getSensorID() == "Unknown":
            if self.c.getLock() == "Enabled":
                lock.Lock(self.d).run()

        title = "\\ZbStart\\n\\ZB"
        subtitle = "What do you want to do today?"
        title += subtitle
        choice = self.d.menu(title,
            choices=[
                ("Configure", "Configure this sensor"),
                ("Manage", "Start/stop sensor functions"),
                ("Status", "View the status of this sensor"),
                ("Log", "View the logfile of this sensor"),
                #("Update", "Update the sensor scripts"),
                #("Console", "Open a management console"),
                ("About", "Learn more about the SURFids sensor"),
                ("Shutdown", "Shutdown the machine"),
                ("Lock", "Lock the sensor menu"),
            ], nocancel=1, width=60, colors=1)
        #cancel
        if choice[0] == 1: return
        elif choice[1] == "Configure": config.Config(self.d).run()
        elif choice[1] == "Manage": manage.Manage(self.d).run()
        elif choice[1] == "Status": status.Status(self.d).run()
        elif choice[1] == "Log": log.Log(self.d).run()
        elif choice[1] == "Console": console.Console(self.d).run()
        elif choice[1] == "About": about.About(self.d).run()
        elif choice[1] == "Shutdown": manage.Manage(self.d).shutdown()
        elif choice[1] == "Lock": lock.Lock(self.d).run()
        self.run()
Beispiel #33
0
def waitInterfaceLink(interface, server):
    """ Waits for an interface to get ready. Some interfaces need some 
        time before they are able to send/receive packets after coming
        up.
    """
    logging.debugv("functions/linux.py->waitInterfaceLink(interface, server)", [interface, server])
    from time import sleep as time_sleep
    
    cmd = ['ping',  '-I', interface, '-c 1', server]
    timeout = 60
    done = 0

    while (timeout > 0 and not done):
        try:
            runWrapper(cmd)
            done = 1
        except:
            time_sleep(1)
            timeout -= 1
  
    if (timeout == 0):
        msg = "Interface %s did not get a link in 60 seconds" % (interface)
        logging.warning(msg)
    else:
        logging.debug("network device up after %d seconds" % (60-timeout))
Beispiel #34
0
def formatMenuItem(msg, val, valid=True):
    """ Validates a menu item and returns dict for usage in dialog menu """
    logging.debugv("tools.py->formatMenuItem(msg, val, valid)", [msg, val, valid])
    if val == "" or not valid:
        return [(msg, ">>To be configured<<")]
    else:
        return [(msg, val)]
Beispiel #35
0
def allInfsDown():
    """ Bring all the interfaces down """
    logging.debugv("functions/__init__.py->allInfsDown()", [])
    logging.info("Bringing all interfaces down")

    try:
        allTunnelsDown()
    except excepts.NetworkException:
        logging.warning("No network, so can't bring tunnels down")

    # down all interfaces
    for inf in ifList():
        ifDown(inf)

    # remove vlans
    for vlan in vlanList():
        delVlan(vlan)

    # remove all bridges
    for bridge in brList():
        ifDown(bridge)
        delBridge(bridge)

    # remove all tap interfaces
    for tap in tapList():
        delTap(tap)
    
    # kill any remaining DHCP servers
    killAllDhcp()
Beispiel #36
0
def ipmiSetNet(dict):
    """ Set an IPMI lan property """
    logging.debugv("functions/linux.py->ipmiSetNet(dict)", [str(dict)])

    cmd = [locations.IPMITOOL, "-I", "open", "lan", "set", str(1)]
    cmd += dict
    ipmiWrapper(cmd)
Beispiel #37
0
    def setIpmi(self):
        """ Submenu for configuring IPMI settings """
        logging.debugv("menu/config.py->setIpmi(self)", [])

        address = self.c.getIpmiAddress()
        netmask = self.c.getIpmiNetmask()
        gwip = self.c.getIpmiGatewayIP()
        gwmac = self.c.getIpmiGatewayMAC()
        vlanid = self.c.getIpmiVlanID()

        choices = [
                    ("IP Address", "[%s]" % str(address)),
                    ("Netmask", "[%s]" % str(netmask)),
                    ("Gateway IP", "[%s]" % str(gwip)),
                    ("Gateway MAC", "[%s]" % str(gwmac)),
                    ("VLAN ID", "[%s] (optional)" % str(vlanid)),
                    ("Users", "IPMI User management..."),
                ]
        choice = self.d.menu("Configure the IPMI interface", choices=choices, cancel="back", width=60)
        if choice[0] == 1: return
        elif choice[1] == "IP Address": self.editIpmiAddress()
        elif choice[1] == "Netmask": self.editIpmiNetmask()
        elif choice[1] == "Gateway IP": self.editIpmiGatewayIP()
        elif choice[1] == "Gateway MAC": self.editIpmiGatewayMAC()
        elif choice[1] == "VLAN ID": self.editIpmiVlanID()
        elif choice[1] == "Users": self.editIpmiUsers()
        self.setIpmi()
Beispiel #38
0
 def showAll(self):
     """ Show the entire log file """
     logging.debugv("menu/log.py->showAll(self)", [])
     if os.access(locations.LOGFILE, os.R_OK):
         return self.d.textbox(locations.LOGFILE, width=70, height=20, no_collapse=1, colors=1)
     else:
         return self.d.msgbox("No logfile present")
Beispiel #39
0
    def run(self):
        """ Submenu showing the different log overviews """
        logging.debugv("menu/log.py->run(self)", [])
        choices=[
                ("All", "Show everything"),
                ("Error", "Filter on error messages"),
                ("Warning", "Filter on warning messages"),
                ("Info", "Filter on info messages"),
                ("Debug", "Filter on debug messages"),
                ("Debugv", "Filter on debugv messages"),
                ("Manual", "Manually enter a search keyword"),
                ("Update", "Show the update log"),
                ("Dump", "Show the latest exception dump"),
            ]

        title = "\\ZbStart > Log\\n\\ZB"
        subtitle = "Which log overview do you want to see?"
        title += subtitle
        choice = self.d.menu(title, choices=choices, cancel="Back", colors=1, menu_height=11, height=17)

        # cancel
        if choice[0] == 1: return
        elif choice[1] == "All": self.showAll()
        elif choice[1] == "Error": self.showFilter(" ERROR ")
        elif choice[1] == "Warning": self.showFilter(" WARN ")
        elif choice[1] == "Info": self.showFilter(" INFO ")
        elif choice[1] == "Debug": self.showFilter(" DEBUG ")
        elif choice[1] == "Debugv": self.showFilter(" DEBUGVV{0,1} ")
        elif choice[1] == "Manual": self.manual()
        elif choice[1] == "Update": self.showUpdateLog()
        elif choice[1] == "Dump": self.errorDump()
        self.run()
Beispiel #40
0
 def showUpdateLog(self):
     """ Show the update log """
     logging.debugv("menu/log.py->showUpdateLog(self)", [])
     if os.access(locations.UPDATELOG, os.R_OK):
         return self.d.textbox(locations.UPDATELOG, width=70, height=20, no_collapse=1, colors=1)
     else:
         return self.d.msgbox("No update logfile present")
Beispiel #41
0
def update():
    """ Update status info to the server """
    logging.debugv("functions/__init__.py->update()", [])

    # Get the main interface, return if no interface has been configured
    try:
        inf = c.getMainIf()
    except excepts.InterfaceException:
        logging.error("Could not find an interface configuration.")
        return

    # Get the localIp
    localIp = getLocalIp()

    ssh = int(sshStatus())
    try:
        mac = getMac(inf)
    except excepts.InterfaceException:
        mac = "00:00:00:00:00:00"

    if c.getAutoUpdate() == "Enabled":
        # Do all the APT stuff
        aptUpdate()
        try:
            sensorDown()
        except:
            allTunnelsDown
            allInfsDown()
            networkUp()

        aptInstall()

    ac = client.update(localIp, ssh, mac, getPackageVersion())
    if ac:
        action(ac)
Beispiel #42
0
    def adminMenu(self):
        """ Administrator menu """
        logging.debugv("menu/config.py->adminMenu(self)", [])

        title = "\\ZbStart > Network > Admin\\n\\ZB"
        subtitle = "Admin configuration"
        title += subtitle
        choices=[
                ('Serverurl', self.c.getServerurl()),
                ('User', self.c.getUser()),
                ('Passwd', len(self.c.getPasswd())*'*'),
                ('Update', "Update the sensor via APT"),
                ('AutoUpdate', self.c.getAutoUpdate()),
            ]
        choice = self.d.menu(title, choices=choices, cancel="back", colors=1)

        if choice[0] == 1: return
        elif choice[1] == "Serverurl": self.setServerurl()
        elif choice[1] == "User": self.setUser()
        elif choice[1] == "Passwd": self.setPasswd()
        elif choice[1] == "Update": self.upgrade()
        elif choice[1] == "AutoUpdate":
            if self.c.getAutoUpdate() == "Enabled":
                self.disableAutoUpdate()
            else:
                self.enableAutoUpdate()
        self.adminMenu()
Beispiel #43
0
def waitInterfaceLink(interface, server):
    """ Waits for an interface to get ready. Some interfaces need some 
        time before they are able to send/receive packets after coming
        up.
    """
    logging.debugv("functions/linux.py->waitInterfaceLink(interface, server)",
                   [interface, server])
    from time import sleep as time_sleep

    cmd = ['ping', '-I', interface, '-c 1', server]
    timeout = 60
    done = 0

    while (timeout > 0 and not done):
        try:
            runWrapper(cmd)
            done = 1
        except:
            time_sleep(1)
            timeout -= 1

    if (timeout == 0):
        msg = "Interface %s did not get a link in 60 seconds" % (interface)
        logging.warning(msg)
    else:
        logging.debug("network device up after %d seconds" % (60 - timeout))
Beispiel #44
0
    def popupVlanConfig(self, type, vlanIndex, vlanID):
        """ Dialog window to input IP addresses for a VLAN configuration """
        logging.debugv("menu/config.py->popupIfConfig(self, type, vlanIndex, vlanID)", [type, vlanIndex, vlanID])

        vlanConf = self.c.getVlan(vlanIndex)
        savedInput = vlanConf[type]

        if type == "tunnel":
            title = "\\Zb... > Network > VLAN %s > Local IP\\n\\ZB" % str(vlanID)
            subtitle = "Enter the IP address of the VLAN interface"
        elif type == "netmask":
            title = "\\Zb... > Network > VLAN %s > Subnet mask\\n\\ZB" % str(vlanID)
            subtitle = "Enter the subnet mask address of the local interface"
        elif type == "gateway":
            title = "\\Zb... > Network > VLAN %s > Gateway\\n\\ZB" % str(vlanID)
            subtitle = "Enter the gateway address of the local interface"
        elif type == "broadcast":
            title = "\\Zb... > Network > VLAN %s > Broadcast\\n\\ZB" % str(vlanID)
            subtitle = "Enter the broadcast address of the local interface"
        title += subtitle

        while True:
            output = self.d.inputbox(title, 10, 50, savedInput, colors=1, ok_label="Ok")
            if output[0]: return
            if t.ipv4check(output[1]):
                address = output[1]
                logging.info("Setting %s for %s to %s" % (type, vlanID, output[1]))
                self.changed = True
                self.c.setVlanProp(vlanIndex, type, output[1])
                self.changed = True
                return                  # returns to setVlanConfig()
            else:
                self.d.msgbox("Please enter a valid address")
Beispiel #45
0
    def setTotalVlans(self):
        """ Edit the amount of VLANs that need to be configured """
        logging.debugv("menu/config.py->setTotalVlans(self)", [])

        title = "\\ZbConfig > Network > VLANs\\n\\ZB"
        subtitle = "Enter the number of vlans you want to use"
        title += subtitle
        vlannum = self.c.getTotalVlans()
        while True:
            output = self.d.inputbox(title, 10, 50, str(vlannum), colors=1)
            if output[0] == 1: return
            else:
                if output[1].isdigit() and str(output[1]) != '0':
                    if vlannum != output[1]:
                        logging.debug("Setting number of vlans to %s" % str(output[1]))
                        # Make sure vlans are created
                        for i in range(0, int(output[1])):
                            # first entry in dict is 0
                            self.c.getVlan(i)
                            self.changed = True

                    return              # returns to configNetwork()
                else:
                    self.d.msgbox("Invalid number of VLANs. Enter a valid integer between 1 and 4095", width=60)
        return                          # returns to configNetwork()
Beispiel #46
0
    def setVlanType(self, vlanIndex, vlanID):
        """ Submenu for setting the type of an VLAN interface """
        logging.debugv("menu/config.py->setVlanType(self, vlanIndex, vlanID)", [vlanIndex, vlanID])
        title = "\\Zb... > Network > VLAN %s > Type\\n\\ZB" % str(vlanID)
        subtitle = "Set the type of configuration for this VLAN interface"
        title += subtitle
        vlanConf = self.c.getVlan(vlanIndex)
        vlanType = vlanConf["type"]

        choices = [
                    ("DHCP", "Automatic configuration by DHCP", int(vlanType=="dhcp")),
                    ("Static", "Static configuration", int(vlanType=="static")),
                    ("Disabled", "Disable this interface", int(vlanType=="disabled")),
                ]
        choice = self.d.radiolist(title, choices=choices, ok_label="Ok", height=20, colors=1)
        if choice[0] == 1: return
        elif choice[1] == "DHCP":
            self.c.setVlanProp(vlanIndex, "type", "dhcp")
            self.c.netconf.write()
            self.changed = True
            return                  # returns to setVlanConfig()
        elif choice[1] == "Static":
            self.c.setVlanProp(vlanIndex, "type", "static")
            self.c.netconf.write()
            self.changed = True
            return                  # returns to setVlanConfig()
        elif choice[1] == "Disabled":
            self.c.setVlanProp(vlanIndex, "type", "disabled")
            self.c.netconf.write()
            self.changed = True
            return                  # returns to setVlanConfig()
        return                      # returns to setVlanConfig()
Beispiel #47
0
    def setVlanID(self, vlanIndex):
        """ Submenu for setting the ID of a VLAN interface """
        logging.debugv("menu/config.py->setVlanID(self, vlanIndex)", [vlanIndex])

        vlanConf = self.c.getVlan(vlanIndex)
        vlanID = vlanConf["vlanid"]

        if vlanID == "":
            title = "\\Zb... > Network > VLAN Unknown-%s > VLAN ID\\n\\ZB" % str(vlanIndex)
        else:
            title = "\\Zb... > Network > VLAN %s > VLAN ID\\n\\ZB" % str(vlanID)
        subtitle = "Set the VLAN ID for this VLAN interface"
        title += subtitle

        while True:
            output = self.d.inputbox(title, 10, 50, vlanID, colors=1, ok_label="Ok")
            if output[0]: return
            else:
                if output[1].isdigit() and str(output[1]) != '0':
                    vlanID = output[1]
                    if not self.c.chkVlanID(vlanID, vlanIndex):
                        self.c.setVlanProp(vlanIndex, "vlanid", output[1])
                        self.changed = True
                        return                  # returns to setVlanConfig()
                    else:
                        self.d.msgbox("VLAN ID already in use!")
                else:
                    self.d.msgbox("Please enter a valid integer between 0 and 4095!")
Beispiel #48
0
    def run(self):
        """ Submenu showing the different status overviews """
        logging.debugv("menu/status.py->run(self)", [])
        choices = [
            ("Sensor", "General information about the sensor"),
            ("Netconf", "Network configuration info"),
            ("Interfaces", "Interface information"),
            ("Debug", "Debugger"),
        ]
        if f.ipmiStatus():
            choices += [("IPMI", "IPMI information")]

        title = "\\ZbStart > Status\\n\\ZB"
        subtitle = "Which status overview do you want to see?"
        title += subtitle
        choice = self.d.menu(title, choices=choices, cancel="Back", colors=1)

        # cancel
        if choice[0] == 1:
            return
        elif choice[1] == "Sensor":
            self.sensor()
        elif choice[1] == "Netconf":
            self.netconf()
        elif choice[1] == "Interfaces":
            self.interfaces()
        elif choice[1] == "Debug":
            pdb.set_trace()
        elif choice[1] == "IPMI":
            self.ipmi()
        self.run()
Beispiel #49
0
    def run(self):
        """ submenu of main to for network configuration """
        logging.debugv("menu/config.py->run(self)", [])
        choices=[
                ("Network", "Configure network..."),
            ]

        if f.ipmiStatus():
            choices += [
                ("IPMI", "Configure IPMI...")
                ]

        choices += [
                ("DNS", "Nameservers settings..."),
                ("Admin", "Administrator menu..."),
                ('AutoStart', self.c.getAutoStart()),
                ('Loglevel', self.c.getLogLevel() ),
            ]

        title = "\\ZbStart > Configure\\n\\ZBSelect the item you want to configure"
        choice = self.d.menu(title, choices=choices, cancel="Back", menu_height=10, colors=1, width=60)

        # cancel 
        if choice[0] == 1: return
        elif choice[1] == "Network": self.configNetwork()
        elif choice[1] == "IPMI": self.setIpmi()
        elif choice[1] == "DNS": self.dns()
        elif choice[1] == "Admin": self.chkAdmin()
        elif choice[1] == "Loglevel": self.setLogLevel()
        elif choice[1] == "AutoStart":
            if self.c.getAutoStart() == "Enabled":
                self.disableAutoStart()
            else:
                self.enableAutoStart()
        self.run()
Beispiel #50
0
def allInfsDown():
    """ Bring all the interfaces down """
    logging.debugv("functions/__init__.py->allInfsDown()", [])
    logging.info("Bringing all interfaces down")

    try:
        allTunnelsDown()
    except excepts.NetworkException:
        logging.warning("No network, so can't bring tunnels down")

    # down all interfaces
    for inf in ifList():
        ifDown(inf)

    # remove vlans
    for vlan in vlanList():
        delVlan(vlan)

    # remove all bridges
    for bridge in brList():
        ifDown(bridge)
        delBridge(bridge)

    # remove all tap interfaces
    for tap in tapList():
        delTap(tap)

    # kill any remaining DHCP servers
    killAllDhcp()
Beispiel #51
0
 def upgrade(self):
     """ Update the sensor software via APT """
     logging.debugv("menu/config.py->upgrade(self)", [])
     
     self.d.infobox("Updating sensor...")
     f.aptUpdate()
     f.aptInstall()
Beispiel #52
0
 def sensorStatus(self):
     """ return the status of the surfids tunnel configuration """
     logging.debugv("runtime.py->sensorStatus(self)", [])
     if not self.networkStatus(): return False
     if self.config['status'].get('sensor') == "enabled":
         return True
     return False
Beispiel #53
0
 def delVlan(self, interface, vlandev):
     """ remove vlan interface from runtime db """
     logging.debugv("runtime.py->delVlan(self, interface, vlandev)",
                    [interface, vlandev])
     self.checkVlan(interface, vlandev)
     self.config['infs'][interface]['vlans'].pop(vlandev)
     self.config.write()
Beispiel #54
0
 def sensorUp(self):
     """ run this after all surfids tunnels are started """
     logging.debugv("runtime.py->sensorUp(self)", [])
     logging.info("setting runtime tunnel status to up")
     if not self.networkStatus():
         raise excepts.NetworkException("network not up")
     self.config['status']['sensor'] = "enabled"
     self.config.write()
Beispiel #55
0
 def getBridgeDev(self, interface):
     """ Get the bridge device of a given interface """
     logging.debugv("runtime.py->getBridgeDev(self, interface)",
                    [interface])
     try:
         return self.config['infs'][interface]['bridgedev']
     except KeyError:
         return False
Beispiel #56
0
 def setVlan(self, interface, vlandev, key, value):
     """ set the property of a vlan """
     logging.debugv(
         "runtime.py->setVlan(self, interface, vlandev, key, value)",
         [interface, vlandev, key, value])
     self.checkVlan(interface, vlandev)
     self.config['infs'][interface]['vlans'][vlandev][key] = value
     self.config.write()
Beispiel #57
0
 def checkVlan(self, interface, vlandev):
     """ checks if vlan is in runtime db """
     logging.debugv("runtime.py->checkVlan(self, interface, vlandev)",
                    [interface, vlandev])
     self.chkInf(interface)
     if not self.config['infs'][interface]['vlans'].has_key(vlandev):
         raise InterfaceException, "vlan not found: %s,%s" % (interface,
                                                              vlandev)
Beispiel #58
0
 def __init__(self):
     logging.debugv("runtime.py->__init__(self)", [])
     self.__dict__ = self.__shared_state
     self.config = configobj.ConfigObj(locations.INTERFACES)
     if not self.config.has_key('infs'): self.config['infs'] = {}
     if not self.config.has_key('status'): self.config['status'] = {}
     if not self.config.has_key('net'): self.config['net'] = {}
     self.config.write()
Beispiel #59
0
def sensorUp():
    """ Brings all interfaces up _and_ brings up tunnels """
    logging.debugv("functions/__init__.py->sensorUp()", [])

    try:
        c.validNetConf()
    except excepts.ConfigException, e:
        raise excepts.ConfigException, "Invalid network configuration:\n %s" % str(e)