Esempio n. 1
0
    def check_sync(self):
        systemname = pipeopen("/usr/local/sbin/dmidecode -s system-product-name").communicate()[0].strip()
        boardname = pipeopen("/usr/local/sbin/dmidecode -s baseboard-product-name").communicate()[0].strip()
        if "freenas" in systemname.lower() and boardname == "C2750D4I":
            mcinfo = pipeopen("/usr/local/bin/ipmitool mc info").communicate()[0]
            reg = re.search(r"Firmware Revision.*: (\S+)", mcinfo, flags=re.M)
            if not reg:
                return
            fwver = reg.group(1)
            try:
                fwver = [int(i) for i in fwver.split(".")]
            except ValueError:
                logger.warning("Failed to parse BMC firmware version: {}".format(fwver))
                return

            if len(fwver) < 2 or not(fwver[0] == 0 and fwver[1] < 30):
                return

            return Alert(
                "FreeNAS Mini Critical IPMI Firmware Update - Your "
                "Mini has an available IPMI firmware update, please "
                "click <a href=\"%s\" target=\"_blank\">here</a> for "
                "installation instructions",

                "https://support.ixsystems.com/index.php?/Knowledgebase/Article/View/287"
            )
Esempio n. 2
0
def debug(request):
    hostname = GlobalConfiguration.objects.all().order_by('-id')[0].gc_hostname
    dir = "/var/tmp/ixdiagnose"
    dump = "%s/ixdiagnose.tgz" % dir

    opts = ["/usr/local/bin/ixdiagnose", "-d", dir, "-s", "-F"]
    p1 = pipeopen(string.join(opts, ' '), allowfork=True)
    debug = p1.communicate()[0]
    p1.wait()

    with open(dump, "r") as f:
        freenas_dump = f.read().strip()
        f.close()  

    wrapper = FileWrapper(file(dump))
    response = HttpResponse(wrapper, content_type='application/octet-stream')
    response['Content-Length'] = os.path.getsize(dump)
    response['Content-Disposition'] = \
        'attachment; filename=debug-%s-%s.tgz' % (
            hostname.encode('utf-8'),
            time.strftime('%Y%m%d%H%M%S'))

    opts = ["/bin/rm", "-r", "-f", dir]
    p1 = pipeopen(string.join(opts, ' '), allowfork=True)
    p1.wait()

    return response
Esempio n. 3
0
    def run(self):
        alerts = []
        systemname = pipeopen("/usr/local/sbin/dmidecode -s system-product-name").communicate()[0].strip()
        boardname = pipeopen("/usr/local/sbin/dmidecode -s baseboard-product-name").communicate()[0].strip()
        if 'freenas' in systemname.lower() and boardname == 'C2750D4I':
            mcinfo = pipeopen("/usr/local/bin/ipmitool mc info").communicate()[0]
            reg = re.search(r'Firmware Revision.*: (\S+)', mcinfo, flags=re.M)
            if not reg:
                return alerts
            fwver = reg.group(1)
            try:
                fwver = [int(i) for i in fwver.split('.')]
            except ValueError:
                log.warn('Failed to parse BMC firmware version: {}'.format(fwver))
                return alerts

            if len(fwver) < 2 or not(fwver[0] == 0 and fwver[1] < 30):
                return alerts

            alerts.append(
                Alert(
                    Alert.CRIT,
                    _(
                        'FreeNAS Mini Critical IPMI Firmware Update - Your '
                        'Mini has an available IPMI firmware update, please '
                        'click <a href="%s" target="_blank">here</a> for '
                        'installation instructions'
                    ) % 'https://support.ixsystems.com/index.php?/Knowledgebase/Article/View/287',
                )
            )
        return alerts
Esempio n. 4
0
def debug(request):
    hostname = GlobalConfiguration.objects.all().order_by('-id')[0].gc_hostname
    p1 = pipeopen("zfs list -H -o name")
    zfs = p1.communicate()[0]
    zfs = zfs.split()
    dir = "/var/tmp/ixdiagnose"
    for dataset in zfs:
        if dataset.endswith(".system"):
            p1 = pipeopen("zfs list -H -o mountpoint %s" % dataset)
            mntpoint = p1.communicate()[0].strip()
            dir = mntpoint + "/" + "ixdiagnose"
            break
    dump = "%s/ixdiagnose.tgz" % dir

    opts = ["/usr/local/bin/ixdiagnose", "-d", dir, "-s", "-F"]
    p1 = pipeopen(string.join(opts, ' '), allowfork=True)
    p1.communicate()[0]
    p1.wait()

    wrapper = FileWrapper(file(dump))
    response = HttpResponse(wrapper, content_type='application/octet-stream')
    response['Content-Length'] = os.path.getsize(dump)
    response['Content-Disposition'] = \
        'attachment; filename=debug-%s-%s.tgz' % (
            hostname.encode('utf-8'),
            time.strftime('%Y%m%d%H%M%S'))

    opts = ["/bin/rm", "-r", "-f", dir]
    p1 = pipeopen(string.join(opts, ' '), allowfork=True)
    p1.wait()

    return response
Esempio n. 5
0
def smb4_setup():
    statedir = "/var/db/samba4"

    volume, basename = get_samba4_path()
    if volume.is_decrypted() and not os.path.islink(statedir):
        if os.path.exists(statedir):
            try:
                p = pipeopen("/bin/rm -rf '%s'" % statedir)
                p.communicate()

            except:
                olddir = "%s.%s" % (statedir, time.time())
                p = pipeopen("/bin/mv '%s' '%s'" % (statedir, olddir))
                p.communicate()

        samba4_dataset = create_samba4_dataset()
        try:
            os.symlink(samba4_dataset, statedir)
        except Exception as e:
            print >> sys.stderr, "Unable to create symlink '%s' -> '%s' (%s)" % (
                samba4_dataset, statedir, e)

    smb4_mkdir("/var/run/samba")
    smb4_mkdir("/var/db/samba")

    smb4_mkdir("/var/run/samba4")

    smb4_mkdir("/var/log/samba4")
    os.chmod("/var/log/samba4", 0755)

    smb4_mkdir("/var/etc/private")
    os.chmod("/var/etc/private", 0700)

    smb4_unlink("/usr/local/etc/smb.conf")
    smb4_unlink("/usr/local/etc/smb4.conf")
Esempio n. 6
0
def smb4_map_groups():
    cmd = "/usr/local/bin/net groupmap add type=local unixgroup='%s' ntgroup='%s'"

    groupmap = smb4_get_groupmap()
    groups = get_groups()
    for g in groups:
        if not smb4_group_mapped(groupmap, g) and \
            not smb4_groupname_is_username(g):
            pipeopen(cmd % (g, g)).communicate()
Esempio n. 7
0
def debug_run(direc):
    # Be extra safe in case we have left over from previous run
    if os.path.exists(direc):
        opts = ["/bin/rm", "-r", "-f", direc]
        p1 = pipeopen(' '.join(opts), allowfork=True)
        p1.wait()

    opts = ["/usr/local/bin/ixdiagnose", "-d", direc, "-s", "-F"]
    p1 = pipeopen(' '.join(opts), allowfork=True)
    p1.communicate()
Esempio n. 8
0
def do_migration(old_samba4_datasets):
    if len(old_samba4_datasets) > 1:
        return False
    old_samba4_dataset = "/mnt/%s/" % old_samba4_datasets[0]

    try:
        pipeopen("/usr/local/bin/rsync -avz '%s'* '/var/db/samba4/'" % old_samba4_dataset).wait()
        notifier().destroy_zfs_dataset(old_samba4_datasets[0], True)

    except Exception as e:
        print >> sys.stderr, e

    return True
Esempio n. 9
0
def smb4_import_users(client, smb_conf_path, smb4_tdb, exportfile=None):
    f = tempfile.NamedTemporaryFile(mode='w+', dir="/tmp")
    for line in smb4_tdb:
        f.write(line + '\n')
    f.flush()

    args = [
        "/usr/local/bin/pdbedit",
        "-d 0",
        "-i smbpasswd:%s" % f.name,
        "-s %s" % smb_conf_path
    ]

    if exportfile is not None:
        # smb4_unlink(exportfile)
        args.append("-e tdbsam:%s" % exportfile)

    p = pipeopen(' '.join(args))
    pdbedit_out = p.communicate()
    if pdbedit_out and pdbedit_out[0]:
        for line in pdbedit_out[0].split('\n'):
            line = line.strip()
            if not line:
                continue
            print(line)

    f.close()
    smb4_users = get_smb4_users(client)
    for u in smb4_users:
        u = Struct(u)
        smbhash = u.bsdusr_smbhash
        parts = smbhash.split(':')
        user = parts[0]

        flags = "-e"
        if u.bsdusr_locked or u.bsdusr_password_disabled:
            flags = "-d"

        p = pipeopen("/usr/local/bin/smbpasswd %s '%s'" % (flags, user))
        smbpasswd_out = p.communicate()

        if p.returncode != 0:
            print("Failed to disable %s" % user, file=sys.stderr)
            continue

        if smbpasswd_out and smbpasswd_out[0]:
            for line in smbpasswd_out[0].split('\n'):
                line = line.strip()
                if not line:
                    continue
                print(line)
Esempio n. 10
0
def smb4_import_users(client, smb_conf_path, smb4_tdb, exportfile=None):
    (fd, tmpfile) = tempfile.mkstemp(dir="/tmp")
    for line in smb4_tdb:
        os.write(fd, line + '\n')
    os.close(fd)

    args = [
        "/usr/local/bin/pdbedit",
        "-d 0",
        "-i smbpasswd:%s" % tmpfile,
        "-s %s" % smb_conf_path
    ]

    if exportfile is not None:
        # smb4_unlink(exportfile)
        args.append("-e tdbsam:%s" % exportfile)

    p = pipeopen(string.join(args, ' '))
    pdbedit_out = p.communicate()
    if pdbedit_out and pdbedit_out[0]:
        for line in pdbedit_out[0].split('\n'):
            line = line.strip()
            if not line:
                continue
            print line

    os.unlink(tmpfile)
    smb4_users = get_smb4_users(client)
    for u in smb4_users:
        u = Struct(u)
        smbhash = u.bsdusr_smbhash
        parts = smbhash.split(':')
        user = parts[0]

        flags = "-e"
        if u.bsdusr_locked or u.bsdusr_password_disabled:
            flags = "-d"

        p = pipeopen("/usr/local/bin/smbpasswd %s '%s'" % (flags, user))
        smbpasswd_out = p.communicate()

        if p.returncode != 0:
            print >> sys.stderr, "Failed to disable %s" % user
            continue

        if smbpasswd_out and smbpasswd_out[0]:
            for line in smbpasswd_out[0].split('\n'):
                line = line.strip()
                if not line:
                    continue
                print line
Esempio n. 11
0
def do_migration(client, old_samba4_datasets):
    if len(old_samba4_datasets) > 1:
        return False
    old_samba4_dataset = "/mnt/%s/" % old_samba4_datasets[0]

    try:
        pipeopen("/usr/local/bin/rsync -avz '%s'* '/var/db/samba4/'" %
                 old_samba4_dataset).wait()
        client.call('notifier.destroy_zfs_dataset', old_samba4_datasets[0], True)

    except Exception as e:
        print(e, file=sys.stderr)

    return True
Esempio n. 12
0
    def __init__(self, *args, **kwargs):
        self.sipcalc = SIPCALC_PATH
        self.args = args
        self.iface = None

        self.sipcalc_args = [self.sipcalc]
        for arg in args:
            self.sipcalc_args.append(str(arg))

        network = kwargs.get('network', None)
        if network:
            self.sipcalc_args.append(str(network))

        iface = kwargs.get('iface', None)
        if iface:
            self.sipcalc_args.append(str(iface))
            self.iface = iface

        p1 = pipeopen(
            string.join(self.sipcalc_args, ' '),
            allowfork=True,
            important=False,
        )
        self.sipcalc_out = p1.communicate()
        if self.sipcalc_out:
            self.sipcalc_out = self.sipcalc_out[0]
            if self.sipcalc_out:
                self.sipcalc_out = self.sipcalc_out.split('\n')
Esempio n. 13
0
    def __init__(self, cmd, func=None, **kwargs):
        log.debug("cmd_pipe.__init__: enter")
        log.debug("cmd_pipe.__init__: cmd = %s", cmd)

        from freenasUI.common.pipesubr import pipeopen

        self.error = None
        self.__pipe = pipeopen(cmd, allowfork=True, important=False)

        self.__stdin = self.__pipe.stdin
        self.__stdout = self.__pipe.stdout
        self.__stderr = self.__pipe.stderr

        self.__out, self.err = self.__pipe.communicate()

        if func is not None:
            for line in self.__out.splitlines():
                line = line.strip()
                func(line, **kwargs)

        for line in self.__out.splitlines():
            log.debug("cmd_pipe.__init__: out = %s", line)
        for line in self.err.splitlines():
            log.debug("cmd_pipe.__init__: err = %s", line)

        if self.__pipe.returncode != 0:
            self.error = 'The command %s failed: "%s"' % \
                             (cmd, self.err or self.__out, )

        self.returncode = self.__pipe.returncode
        log.debug("cmd_pipe.__init__: leave")
Esempio n. 14
0
def set_idmap_rfc2307_secret():
    try:
        ad = ActiveDirectory.objects.all()[0]
    except:
        return False

    domain = None
    idmap = get_idmap_object(ad.ds_type, ad.id, ad.ad_idmap_backend)

    try:
        fad = FreeNAS_ActiveDirectory(flags=FLAGS_DBINIT)
        domain = fad.netbiosname.upper()
    except:
        return False

    args = ["/usr/local/bin/net", "-d 0", "idmap", "secret"]

    net_cmd = "%s '%s' '%s'" % (string.join(args, " "), domain, idmap.idmap_rfc2307_ldap_user_dn_password)

    p = pipeopen(net_cmd, quiet=True)
    net_out = p.communicate()
    if net_out and net_out[0]:
        for line in net_out[0].split("\n"):
            if not line:
                continue
            print line

    ret = True
    if p.returncode != 0:
        print >> sys.stderr, "Failed to set idmap secret!"
        ret = False

    return ret
Esempio n. 15
0
    def _get_storage_tasks(self, cifs_path=None, cifs_home=False):
        p = pipeopen("zfs list -H -o mountpoint,name")
        zfsout = p.communicate()[0].split('\n')
        if p.returncode != 0:
            zfsout = []

        task_list = []
        if cifs_path:
            for line in zfsout:
                try:
                    tasks = [] 
                    zfs_mp, zfs_ds = line.split()
                    if cifs_path == zfs_mp or cifs_path.startswith("%s/" % zfs_mp):
                        if cifs_path == zfs_mp:
                            tasks = Task.objects.filter(task_filesystem=zfs_ds)
                        else: 
                            tasks = Task.objects.filter(Q(task_filesystem=zfs_ds) & Q(task_recursive=True))
                    for t in tasks:
                        task_list.append(t)

                except:
                    pass

        elif cifs_home:
            task_list = Task.objects.filter(Q(task_recursive=True))

        return task_list
Esempio n. 16
0
def debug_SID(str):
    if str:
        print >> sys.stderr, "XXX: %s" % str
    p = pipeopen("/usr/local/bin/net -d 0 getlocalsid")
    out, _ = p.communicate()
    if out:
        print >> sys.stderr, "XXX: %s" % out
Esempio n. 17
0
def provision_smb4():
    try:
        dc = DomainController.objects.all()[0]
    except:
        pass

    args = {}
    args['realm'] = dc.dc_realm
    args['domain'] = dc.dc_domain
    args['dns-backend'] = dc.dc_dns_backend
    args['server-role'] = dc.dc_role
    args['function-level'] = dc.dc_forest_level
    args['adminpass'] = dc.dc_passwd
    args['use-ntvfs'] = None
    args['use-rfc2307'] = None

    samba_tool_args = "domain provision"
    for key in args:
        if args[key]:
            samba_tool_args = "%s --%s %s" % (samba_tool_args, key, args[key])
        else:
            samba_tool_args = "%s --%s" % (samba_tool_args, key)

    p = pipeopen("/usr/local/bin/samba-tool %s" % samba_tool_args, quiet=True)
    out = p.communicate()
    if out and out[1]:
        for line in out[1].split('\n'):
            print line

    if p.returncode != 0:
        return False

    return True
Esempio n. 18
0
    def __init__(self, *args, **kwargs):
        self.sipcalc = SIPCALC_PATH
        self.args = args
        self.iface = kwargs.get('iface', None)

        self.sipcalc_args = [self.sipcalc]
        for arg in args:
            self.sipcalc_args.append(str(arg))

        network = kwargs.get('network', None)
        if network:
            self.sipcalc_args.append(str(network))

        if self.iface:
            self.sipcalc_args.append(str(self.iface))

        # If we already have the results of the `sipcalc` shell call
        # then do not do a redudant second call
        # For more explanation see the __new__ method of the `sipcalc_type`
        # class.
        self.sipcalc_out = kwargs.get('sipcalc_out', None)
        if self.sipcalc_out is None:
            p1 = pipeopen(
                ' '.join(self.sipcalc_args),
                allowfork=True,
                important=False,
            )
            self.sipcalc_out = p1.communicate()
            if self.sipcalc_out:
                self.sipcalc_out = self.sipcalc_out[0]
                if self.sipcalc_out:
                    self.sipcalc_out = self.sipcalc_out.split('\n')
Esempio n. 19
0
def smb4_grant_user_rights(user):
    args = [
        "/usr/local/bin/net",
        "-d 0",
        "sam",
        "rights",
        "grant"
    ]

    rights = [
        "SeTakeOwnershipPrivilege",
        "SeBackupPrivilege",
        "SeRestorePrivilege"
    ]

    net_cmd = "%s %s %s" % (
        string.join(args, ' '),
        user,
        string.join(rights, ' ')
    )

    p = pipeopen(net_cmd)
    net_out = p.communicate()
    if net_out and net_out[0]:
        for line in net_out[0].split('\n'):
            if not line:
                continue
            print line

    if p.returncode != 0:
        return False

    return True
def add_ldap_conf(smb4_conf):
    try:
        ldap = LDAP.objects.all()[0]
    except:
        return

    confset1(smb4_conf, "security = user")

    confset2(smb4_conf, "passdb backend = %s",
        "ldapsam:ldaps://%s" % ldap.ldap_hostname if \
        (ldap.ldap_ssl == 'on' or ldap.ldap_ssl == 'start_tls') else
        "ldapsam:ldap://%s" % ldap.ldap_hostname)

    confset2(smb4_conf, "ldap admin dn = %s", ldap.ldap_rootbasedn)

    if ldap.ldap_rootbindpw:
        p = pipeopen("/usr/local/bin/smbpasswd -w '%s'" % ldap.ldap_rootbindpw)
        out = p.communicate()
        if out and out[1]:
            for line in out[1].split('\n'):
                print line

    confset2(smb4_conf, "ldap suffix = %s", ldap.ldap_basedn)
    confset2(smb4_conf, "ldap user suffix = %s", ldap.ldap_usersuffix)
    confset2(smb4_conf, "ldap group suffix = %s", ldap.ldap_groupsuffix)
    confset2(smb4_conf, "ldap machine suffix = %s", ldap.ldap_machinesuffix)
    confset2(smb4_conf, "ldap ssl = %s",
        "start tls" if (ldap.ldap_ssl == 'start_tls') else 'off')

    confset1(smb4_conf, "ldap replication sleep = 1000")
    confset1(smb4_conf, "ldap passwd sync = yes")
    confset1(smb4_conf, "ldapsam:trusted = yes")
    confset1(smb4_conf, "idmap uid = 10000-39999")
    confset1(smb4_conf, "idmap gid = 10000-39999")
Esempio n. 21
0
def is_within_zfs(mountpoint):
    try:
        st = os.stat(mountpoint)
    except:
        return False

    share_dev = st.st_dev
    p = pipeopen("zfs list -H -o mountpoint")
    zfsout = p.communicate()
    if p.returncode != 0:
        return False
    if zfsout:
        zfsout = zfsout[0]

    for mp in zfsout.split('\n'):
        mp = mp.strip()
        if mp == '-':
            continue

        try:
            st = os.stat(mp)
        except:
            continue

        if st.st_dev == share_dev:
            return True

    return False
Esempio n. 22
0
def ping_host(host, ping6=False):
    tseconds = 2

    cmd = "/sbin/ping -q -t %d -o %s" % (tseconds, host)
    if ping6:
        cmd = "/sbin/ping6 -q -o %s -c 1" % host

    p = pipeopen(cmd)

    t = time.time()
    timeout = t + tseconds

    while t <= timeout:
        if p.poll() == 0:
            break

        time.sleep(1)
        t = time.time()

    if p.returncode != 0:
        try:
            p.terminate()
        except:
            pass
        return False

    return True
def set_corefile_sysctl(corepath):
    res = False
    p = pipeopen("/sbin/sysctl kern.corefile='%s'" % corepath)
    p.communicate()
    if p.returncode == 0:
        res = True

    return res
def dataset_exists(dataset):
    res = False
    p = pipeopen("/sbin/zfs list -H '%s'" % dataset)
    p.communicate()
    if p.returncode == 0:
        res = True

    return res
Esempio n. 25
0
def debug_SID(str):
    if str:
        print >> sys.stderr, "XXX: %s" % str
    p = pipeopen("/usr/local/bin/net -d 0 getlocalsid")
    out = p.communicate()
    if out and out[0]:
        time.sleep(1)
        print >> sys.stderr, "XXX: %s" % out[0]
Esempio n. 26
0
def smb4_groupname_is_username(group):
    cmd = "/usr/bin/getent passwd '%s'" % group

    p = pipeopen(cmd)
    p.communicate()
    if p.returncode == 0:
        return True

    return False
Esempio n. 27
0
    def jt_instances(self):
        template = self.jt_name
        instances = 0

        jc = JailsConfiguration.objects.all()
        if not jc.exists():
            return 0
        jc = jc[0]

        tdir = os.path.realpath("%s/.warden-template-%s" % (jc.jc_path, template))
        if not os.path.exists(tdir):
            return 0

        p = pipeopen("/sbin/zfs list -H -o name '%s'" % tdir)
        zfsout = p.communicate()
        if p.returncode != 0:
            return 0
        if not zfsout:
            return 0

        template_dataset = zfsout[0].strip()
        for metadir in glob.iglob("%s/.*.meta" % jc.jc_path):
            metadir = metadir.split('/')[-1]
            jail = re.sub('\.meta|\.', '', metadir)
            rp = os.path.realpath("%s/%s" % (jc.jc_path, jail))

            p = pipeopen("/sbin/zfs get -H origin '%s'" % rp)
            zfsout = p.communicate()
            if p.returncode != 0:
                continue
            if not zfsout:
                continue

            zfsout = zfsout[0]
            parts = zfsout.split('\t')
            if len(parts) < 3:
                continue

            snapshot = parts[2].strip()
            dataset = snapshot.replace('@clean', '')
            if template_dataset == dataset:
                instances += 1

        return instances
Esempio n. 28
0
def debug(request):
    hostname = GlobalConfiguration.objects.all().order_by('-id')[0].gc_hostname
    p1 = pipeopen("zfs list -H -o name")
    zfs = p1.communicate()[0]
    zfs = zfs.split()
    direc = "/var/tmp/ixdiagnose"
    mntpt = '/var/tmp'
    systemdataset, volume, basename = notifier().system_dataset_settings()
    if basename:
        mntpoint = '/mnt/%s' % basename
        if os.path.exists(mntpoint):
            direc = '%s/ixdiagnose' % mntpoint
            mntpt = mntpoint
    dump = "%s/ixdiagnose.tgz" % direc

    with mntlock(mntpt=mntpt):

        # Be extra safe in case we have left over from previous run
        if os.path.exists(direc):
            opts = ["/bin/rm", "-r", "-f", direc]
            p1 = pipeopen(' '.join(opts), allowfork=True)
            p1.wait()

        opts = ["/usr/local/bin/ixdiagnose", "-d", direc, "-s", "-F"]
        p1 = pipeopen(' '.join(opts), allowfork=True)
        p1.communicate()

        wrapper = FileWrapper(file(dump))
        response = StreamingHttpResponse(
            wrapper,
            content_type='application/octet-stream',
        )
        response['Content-Length'] = os.path.getsize(dump)
        response['Content-Disposition'] = \
            'attachment; filename=debug-%s-%s.tgz' % (
                hostname.encode('utf-8'),
                time.strftime('%Y%m%d%H%M%S'))

        opts = ["/bin/rm", "-r", "-f", direc]
        p1 = pipeopen(' '.join(opts), allowfork=True)
        p1.wait()

        return response
Esempio n. 29
0
def get_sysctl(name):
    p = pipeopen("/sbin/sysctl -n '%s'" % name)
    out = p.communicate()
    if p.returncode != 0:
        return None
    try:
        out = out[0].strip()
    except:
        pass
    return out
Esempio n. 30
0
    def check_sync(self):
        systemname = pipeopen("/usr/local/sbin/dmidecode -s system-product-name").communicate()[0].strip()
        boardname = pipeopen("/usr/local/sbin/dmidecode -s baseboard-product-name").communicate()[0].strip()
        if "freenas" in systemname.lower() and boardname == "C2750D4I":
            mcinfo = pipeopen("/usr/local/bin/ipmitool mc info").communicate()[0]
            reg = re.search(r"Firmware Revision.*: (\S+)", mcinfo, flags=re.M)
            if not reg:
                return
            fwver = reg.group(1)
            try:
                fwver = [int(i) for i in fwver.split(".")]
            except ValueError:
                logger.warning("Failed to parse BMC firmware version: {}".format(fwver))
                return

            if len(fwver) < 2 or not(fwver[0] == 0 and fwver[1] < 30):
                return

            return Alert(FreeNASBMCAlertClass)
Esempio n. 31
0
 def get_identifiers(self):
     ids = []
     proc = pipeopen("/sbin/ifconfig -l", important=False, logger=log)
     ifaces = proc.communicate()[0].strip('\n').split(' ')
     for entry in glob.glob('%s/interface-*' % self._base_path):
         ident = entry.rsplit('-', 1)[-1]
         if ident not in ifaces:
             continue
         if re.match(r'(usbus|ipfw|pfsync|pflog|carp)', ident):
             continue
         if os.path.exists(os.path.join(entry, 'if_octets.rrd')):
             ids.append(ident)
     ids.sort(key=RRDBase._sort_disks)
     return ids
Esempio n. 32
0
def smb4_set_domain_SID(SID):
    if not SID:
        return False

    p = pipeopen("/usr/local/bin/net -d 0 setdomainsid %s" % SID)
    net_out = p.communicate()
    if p.returncode != 0:
        log.error('Failed to setlocalsid with the following error: {0}'.format(
            net_out[1]))
        return False
    if not net_out:
        return False

    return True
Esempio n. 33
0
    def __init__(self):
        from freenasUI.common.pipesubr import pipeopen

        self.__charsets = []

        p = pipeopen("/usr/bin/iconv -l")
        out, _ = p.communicate()
        if out:
            lines = out.split('\n')
            for line in lines:
                if not line:
                    continue
                parts = line.split()
                self.__charsets.append(parts[0])
Esempio n. 34
0
def tasks_json(request, dataset=None):
    tasks = []

    p = pipeopen("zfs list -H -o mountpoint,name")
    zfsout = p.communicate()[0].split('\n')
    if p.returncode != 0:
        zfsout = []

    task_list = []
    if dataset:
        mp = '/mnt/' + dataset
        for line in zfsout:
            if not line:
                continue

            try:
                zfs_mp, zfs_ds = line.split('\t')
                if mp == zfs_mp or mp.startswith("/%s/" % zfs_mp):
                    if mp == zfs_mp:
                        task_list = models.Task.objects.filter(
                            task_dataset=zfs_ds
                        )
                    else:
                        task_list = models.Task.objects.filter(
                            Q(task_dataset=zfs_ds) &
                            Q(task_recursive=True)
                        )
                    break
            except Exception:
                pass

    else:
        task_list = models.Task.objects.order_by("task_dataset").all()

    for task in task_list:
        t = {}
        for f in models.Task._meta.get_fields():
            if f.many_to_one or f.related_model:
                continue
            try:
                t[f.name] = str(getattr(task, f.name))
            except Exception:
                pass
        t['str'] = str(task)
        tasks.append(t)

    return HttpResponse(
        json.dumps(tasks),
        content_type='application/json'
    )
Esempio n. 35
0
def import_users(smb_conf_path, importfile, exportfile=None):
    args = [
        "/usr/local/bin/pdbedit", "-d 0",
        "-i smbpasswd:%s" % importfile,
        "-s %s" % smb_conf_path
    ]

    if exportfile != None:
        args.append("-e %s" % exportfile)

    p = pipeopen(string.join(args, ' '))
    pdbedit_out = p.communicate()
    if pdbedit_out and pdbedit_out[1]:
        for line in pdbedit_out[1].split('\n'):
            print line
Esempio n. 36
0
def index(request):
    try:
        email = Email.objects.order_by("-id")[0]
        if email:
            email = email.em_fromemail
    except:
        email = None

    try:
        ticket = models.Support.objects.order_by("-id")[0]
    except IndexError:
        ticket = models.Support.objects.create()

    if request.method == "POST":
        form = forms.SupportForm(request.POST, email=email)
        if form.is_valid():
            error = None
            support_info = {
                'support_issue': request.POST['support_issue'],
                'support_description': request.POST['support_description'],
                'support_type': request.POST['support_type'],
                'support_email': request.POST['support_email']
            }

            try:
                f = NamedTemporaryFile(delete=False)
                f.write(simplejson.dumps(support_info))
                f.close()

                args = ["/usr/local/bin/ixdiagnose", "-t", f.name]
                p1 = pipeopen(string.join(args, ' '), allowfork=True)
                p1.communicate()

            except Exception as e:
                error = e

            os.unlink(f.name)

            if not error:
                return JsonResp(request,
                                message=_("Support request successfully sent"))
            else:
                return JsonResp(request, error=True, message=error)

    else:
        form = forms.SupportForm(email=email)

    return render(request, "support/index.html", {'form': form})
Esempio n. 37
0
def set_ldap_password(client):
    try:
        ldap = Struct(client.call('datastore.query', 'directoryservice.LDAP', None, {'get': True}))
    except:
        return

    if ldap.ldap_bindpw:
        p = pipeopen("/usr/local/bin/smbpasswd -w '%s'" % (
            ldap.ldap_bindpw,
        ), quiet=True)
        out = p.communicate()
        if out and out[1]:
            for line in out[1].split('\n'):
                if not line:
                    continue
                print(line)
Esempio n. 38
0
def smb4_grant_rights():
    args = [
        "/usr/local/bin/pdbedit",
        "-L"
    ]

    p = pipeopen(string.join(args, ' '))
    pdbedit_out = p.communicate()
    if pdbedit_out and pdbedit_out[0]:
        for line in pdbedit_out[0].split('\n'):
            if not line:
                continue

            parts = line.split(':')
            user = parts[0]
            smb4_grant_user_rights(user)
Esempio n. 39
0
def log_db_locked():
    """
    Log the processes with the database file open for write.
    """
    proc = pipeopen('fuser /data/freenas-v1.db',
                    stderr=subprocess.STDOUT,
                    quiet=True)
    output = proc.communicate()[0]
    log.debug('Processes with database file open:')
    for pid, flags in re.findall(r'\b(\d+)([a-z]+)\b', output):
        if 'w' not in flags:
            continue
        try:
            proc = psutil.Process(int(pid))
            log.debug(f'PID {pid}: {" ".join(proc.cmdline())}')
        except Exception as e:
            pass
Esempio n. 40
0
    def get_kerberos_principal_from_cache(self):
        principal = None

        p = pipeopen("klist")
        klist_out = p.communicate()
        if p.returncode != 0:
            return None

        klist_out = klist_out[0]
        lines = klist_out.splitlines()
        for line in lines:
            line = line.strip()
            if line.startswith("Principal"):
                parts = line.split(':')
                if len(parts) > 1:
                    principal = parts[1].strip()

        return principal
Esempio n. 41
0
def debug(request):
    """Save freenas-debug output to DEBUG_TEMP"""
    if request.method == "POST":
        form = forms.DebugForm(request.POST)
        if form.is_valid():
            opts = ["/usr/local/bin/freenas-debug"]
            opts += form.get_options()
            p1 = pipeopen(string.join(opts, ' '), allowfork=True)
            debug = p1.communicate()[0]
            with open(DEBUG_TEMP, 'w') as f:
                f.write(debug)
            return render(request, 'system/debug.html')
    else:
        form = forms.DebugForm()

    return render(request, 'system/debug_form.html', {
        'form': form,
    })
Esempio n. 42
0
def set_idmap_rfc2307_secret(client):
    try:
        ad = Struct(client.call('datastore.query', 'directoryservice.ActiveDirectory', None, {'get': True}))
        ad.ds_type = 1  # FIXME: DS_TYPE_ACTIVEDIRECTORY = 1
    except:
        return False

    domain = None
    # FIXME: ad ds_type, extend model
    idmap = Struct(client.call('notifier.ds_get_idmap_object', ad.ds_type, ad.id, ad.ad_idmap_backend))

    try:
        fad = Struct(client.call('notifier.directoryservice', 'AD'))
        domain = fad.netbiosname.upper()
    except:
        return False

    args = [
        "/usr/local/bin/net",
        "-d 0",
        "idmap",
        "secret"
    ]

    net_cmd = "%s '%s' '%s'" % (
        ' '.join(args),
        domain,
        idmap.idmap_rfc2307_ldap_user_dn_password
    )

    p = pipeopen(net_cmd, quiet=True)
    net_out = p.communicate()
    if net_out and net_out[0]:
        for line in net_out[0].split('\n'):
            if not line:
                continue
            print(line)

    ret = True
    if p.returncode != 0:
        print("Failed to set idmap secret!", file=sys.stderr)
        ret = False

    return ret
Esempio n. 43
0
def get_warden_template_abi_version(template_path):
    abi_version = None

    sysctl_path = "%s/sbin/sysctl" % template_path
    p = pipeopen("file -b '%s'" % sysctl_path, important=False)
    out = p.communicate()
    if p.returncode != 0:
        return None

    try:
        out = out[0]
        parts = out.split(',')
        out = parts[4].split()
        abi_version = "%s-RELEASE" % out[2]

    except:
        pass

    return abi_version
Esempio n. 44
0
def smb4_get_system_SID():
    SID = None

    p = pipeopen("/usr/local/bin/net getlocalsid")
    net_out = p.communicate()
    if p.returncode != 0:
        return None
    if not net_out:
        return None

    net_out = net_out[0]

    parts = net_out.split()
    try:
        SID = parts[5]
    except:
        SID = None

    return SID
Esempio n. 45
0
def smb4_grant_user_rights(user):
    args = ["/usr/local/bin/net", "sam", "rights", "grant"]

    rights = [
        "SeTakeOwnershipPrivilege", "SeBackupPrivilege", "SeRestorePrivilege"
    ]

    net_cmd = "%s %s %s" % (string.join(args,
                                        ' '), user, string.join(rights, ' '))

    p = pipeopen(net_cmd)
    net_out = p.communicate()
    if net_out and net_out[0]:
        for line in net_out[0].split('\n'):
            print line

    if p.returncode != 0:
        return False

    return True
Esempio n. 46
0
def main():
    smb_conf_path = "/usr/local/etc/smb4.conf"

    smb4_tdb = []
    smb4_conf = []
    smb4_shares = []

    smb4_setup()

    old_samba4_datasets = get_old_samba4_datasets()
    if migration_available(old_samba4_datasets):
        do_migration(old_samba4_datasets)

    generate_smb4_tdb(smb4_tdb)
    generate_smb4_conf(smb4_conf)
    generate_smb4_shares(smb4_shares)

    role = get_server_role()
    if role == 'dc' and not smb4_domain_provisioned():
        provision_smb4()

    with open(smb_conf_path, "w") as f:
        for line in smb4_conf:
            f.write(line + '\n')
        for line in smb4_shares:
            f.write(line + '\n')
        f.close()

    (fd, tmpfile) = tempfile.mkstemp(dir="/tmp")
    for line in smb4_tdb:
        os.write(fd, line + '\n')
    os.close(fd)

    if role != 'dc':
        p = pipeopen("/usr/local/bin/pdbedit -d 0 -i smbpasswd:%s -e %s -s %s" % (
            tmpfile, "tdbsam:/var/etc/private/passdb.tdb", smb_conf_path))
        out = p.communicate()
        if out and out[1]:
            for line in out[1].split('\n'):
                print line
        os.unlink(tmpfile)
Esempio n. 47
0
    def __init__(self, *args, **kwargs):
        self.sipcalc = SIPCALC_PATH
        self.args = args
        self.iface = kwargs.get('iface', None)

        self.sipcalc_args = [self.sipcalc]
        for arg in args:
            self.sipcalc_args.append(str(arg))

        network = kwargs.get('network', None)
        if network:
            self.sipcalc_args.append(str(network))

        if self.iface:
            iface = netif.get_interface(self.iface)
            for addr in iface.addresses:
                if addr.af != netif.AddressFamily.INET:
                    continue
                self.sipcalc_args.append(
                    str(
                        ipaddress.IPv4Interface(
                            unicode('{}/{}'.format(str(addr.address),
                                                   str(addr.netmask))))))

        # If we already have the results of the `sipcalc` shell call
        # then do not do a redudant second call
        # For more explanation see the __new__ method of the `sipcalc_type`
        # class.
        self.sipcalc_out = kwargs.get('sipcalc_out', None)
        if self.sipcalc_out is None:
            p1 = pipeopen(
                string.join(self.sipcalc_args, ' '),
                allowfork=True,
                important=False,
            )
            self.sipcalc_out = p1.communicate()
            if self.sipcalc_out:
                self.sipcalc_out = self.sipcalc_out[0]
                if self.sipcalc_out:
                    self.sipcalc_out = self.sipcalc_out.split('\n')
Esempio n. 48
0
def add_ldap_conf(smb4_conf):
    try:
        ldap = LDAP.objects.all()[0]
    except:
        return

    confset1(smb4_conf, "security = user")

    confset2(
        smb4_conf,
        "passdb backend = %s",
        "ldapsam:ldaps://%s" % ldap.ldap_hostname if \
        (ldap.ldap_ssl == 'on' or ldap.ldap_ssl == 'start_tls') else
        "ldapsam:ldap://%s" % ldap.ldap_hostname
    )

    confset2(smb4_conf, "ldap admin dn = %s", ldap.ldap_rootbasedn)

    if ldap.ldap_rootbindpw:
        p = pipeopen("/usr/local/bin/smbpasswd -w '%s'" % ldap.ldap_rootbindpw)
        out = p.communicate()
        if out and out[1]:
            for line in out[1].split('\n'):
                print line

    confset2(smb4_conf, "ldap suffix = %s", ldap.ldap_basedn)
    confset2(smb4_conf, "ldap user suffix = %s", ldap.ldap_usersuffix)
    confset2(smb4_conf, "ldap group suffix = %s", ldap.ldap_groupsuffix)
    confset2(smb4_conf, "ldap machine suffix = %s", ldap.ldap_machinesuffix)
    confset2(
        smb4_conf,
        "ldap ssl = %s",
        "start tls" if (ldap.ldap_ssl == 'start_tls') else 'off'
    )

    confset1(smb4_conf, "ldap replication sleep = 1000")
    confset1(smb4_conf, "ldap passwd sync = yes")
    confset1(smb4_conf, "ldapsam:trusted = yes")
    confset1(smb4_conf, "idmap uid = 10000-39999")
    confset1(smb4_conf, "idmap gid = 10000-39999")
Esempio n. 49
0
def get_warden_template_abi_arch(template_path):
    abi_arch = None

    sysctl_path = "%s/sbin/sysctl" % template_path
    p = pipeopen("file -b '%s'" % sysctl_path, important=False)
    out = p.communicate()
    if p.returncode != 0:
        return None

    try:
        out = out[0]
        parts = out.split(',')
        out = parts[0].split()
        if out[1] == '64-bit':
            abi_arch = 'x64'
        else:
            abi_arch = 'x86'

    except:
        pass

    return abi_arch
Esempio n. 50
0
    def samba_tool(self, cmd, args, nonargs=None, quiet=False, buf=None):
        samba_tool_args = cmd

        if args:
            for key in args:
                if args[key]:
                    samba_tool_args = "%s --%s '%s'" % (samba_tool_args, key, args[key])
                else:
                    samba_tool_args = "%s --%s" % (samba_tool_args, key)

        if nonargs:
            for key in nonargs:
                samba_tool_args = "%s '%s'" % (samba_tool_args, key)

        p = pipeopen("%s %s" % (self.samba_tool_path, samba_tool_args), quiet=quiet)
        out = p.communicate()
        if buf is not None:
            buf.append(out)

        if p.returncode != 0:
            return False

        return True