def view_local_users(request):

  return_dict = {}
  try:
    user_list, err = local_users.get_local_users()
    if err:
      raise Exception(err)
  
    return_dict["user_list"] = user_list
  
    if "action" in request.GET:
      conf = ''
      if request.GET["action"] == "saved":
        conf = "Local user password successfully updated"
      elif request.GET["action"] == "created":
        conf = "Local user successfully created"
      elif request.GET["action"] == "deleted":
        conf = "Local user successfully deleted"
      elif request.GET["action"] == "changed_password":
        conf = "Successfully update password"
      return_dict["conf"] = conf
  
    return django.shortcuts.render_to_response('view_local_users.html', return_dict, context_instance=django.template.context.RequestContext(request))
  except Exception, e:
    return_dict['base_template'] = 'users-groups_base.html'
    return_dict["page_title"] = 'Local users'
    return_dict['tab'] = 'view_local_users_tab'
    return_dict["error"] = 'Error loading local users list'
    return_dict["error_details"] = str(e)
    return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))
def create_ftp_user_dirs(request):
    return_dict = {}
    try:
        config, err = vsftp.get_ftp_config()
        if err:
            raise Exception(err)
        if 'dataset' not in config:
            raise Exception(
                'No home dataset has been configured for the FTP service. Please do that before creating FTP home directories'
            )
        users, err = local_users.get_local_users()
        if err:
            raise Exception(err)
        res, err = vsftp.create_ftp_user_dirs(config['dataset'], users)
        if err:
            raise Exception(err)

        audit.audit("create_ftp_dir", 'Created FTP user directories',
                    request.META)
        return django.http.HttpResponseRedirect(
            '/view_ftp_configuration?ack=dirs_created')

    except Exception, e:
        return_dict['base_template'] = "services_base.html"
        return_dict["page_title"] = 'Create FTP user directories'
        return_dict['tab'] = 'ftp_service_settings'
        return_dict["error"] = 'Error creating FTP user directories '
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
def view_local_users(request):

    return_dict = {}
    try:
        user_list, err = local_users.get_local_users()
        if err:
            raise Exception(err)

        return_dict["user_list"] = user_list

        if "ack" in request.GET:
            if request.GET["ack"] == "saved":
                return_dict[
                    'ack_message'] = "Local user password successfully updated"
            elif request.GET["ack"] == "created":
                return_dict['ack_message'] = "Local user successfully created"
            elif request.GET["ack"] == "deleted":
                return_dict['ack_message'] = "Local user successfully deleted"
            elif request.GET["ack"] == "changed_password":
                return_dict['ack_message'] = "Successfully update password"

        return django.shortcuts.render_to_response(
            'view_local_users.html',
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = 'users-groups_base.html'
        return_dict["page_title"] = 'Local users'
        return_dict['tab'] = 'view_local_users_tab'
        return_dict["error"] = 'Error loading local users list'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
def change_service_status(request):
    return_dict = {}
    try:
        if request.method == "GET":
            raise Exception("Invalid request. Please use the menus")
        if 'service' not in request.POST:
            raise Exception("Invalid request. Please use the menus")
        if 'action' not in request.POST or request.POST['action'] not in [
                'start', 'stop', 'restart', 'enable', 'disable'
        ]:
            raise Exception("Invalid request. Please use the menus")

        service = request.POST['service']
        action = request.POST['action']

        if 'action' == 'start' and service == 'vsftpd':
            #Need to make sure that all local users have their directories created so do it..
            config, err = vsftp.get_ftp_config()
            if err:
                raise Exception(err)
            users, err = local_users.get_local_users()
            if err:
                raise Exception(err)
            ret, err = create_ftp_user_dirs(config['dataset'], users)
            if err:
                raise Exception(err)

        audit_str = "Service status change of %s initiated to %s state." % (
            service, action)
        audit.audit("change_service_status", audit_str, request.META)

        out, err = services_management.change_service_status(service, action)
        if err:
            raise Exception(err)

        if out:
            return django.http.HttpResponseRedirect(
                '/view_services?&service_change_status=%s' % ','.join(out))
        else:
            return django.http.HttpResponseRedirect(
                '/view_services?service_change_status=none')

    except Exception, e:
        return_dict['base_template'] = "services_base.html"
        return_dict["page_title"] = 'Modify system service state'
        return_dict['tab'] = 'view_services_tab'
        return_dict["error"] = 'Error modifying system services state'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
Exemplo n.º 5
0
def _get_user_or_group_list(type):
  ret = None
  try:
    d, err = cifs_common.load_auth_settings()
    if err:
      raise Exception(err)
    if not d:
      raise Exception("Unspecified authentication method. Could not retrieve users")
    elif d["security"] == "users":
      if type and type == "users":
        l, err = local_users.get_local_users()
        if err:
          raise Exception(err)
        if l:
          ret = []
          for ld in l:
            ret.append(ld["username"])
      else:
        l, err = local_users.get_local_groups()
        if err:
          raise Exception(err)
        if l:
          ret = []
          for ld in l:
            ret.append(ld["grpname"])
    elif d["security"] == "ads":
      if type and type == "users":
        ret, err =  cifs_common._get_ad_users_or_groups("users")
        if err:
          raise Exception(err)
      elif type and type == "groups":
        ret, err =  cifs_common._get_ad_users_or_groups("groups")
        if err:
          raise Exception(err)
    else:
      raise Exception("Unsupported authentication method. Could not retrieve users")
  except Exception, e:
    return None, 'Error retrieving user of group list : %s'%str(e)
def modify_dir_owner(request):
  return_dict = {}
  try:
    users, err = local_users.get_local_users()
    if err:
      raise Exception('Error retrieving local user list : %s'%err)
    if not users:
      raise Exception('No local users seem to be created. Please create at least one local user before performing this operation.')

    groups, err = local_users.get_local_groups()
    if err:
      raise Exception('Error retrieving local group list : %s'%err)
    if not groups:
      raise Exception('No local groups seem to be created. Please create at least one local group before performing this operation.')

    if request.method == "GET":
      if 'path' not in request.GET:
        raise Exception('Invalid request. Please use the menus.')
      path = request.GET['path']
      try:
        stat_info = os.stat(path)
      except Exception, e:
        raise Exception('Error accessing specified path : %s'%str(e))
      uid = stat_info.st_uid
      gid = stat_info.st_gid
      user_name = pwd.getpwuid(uid)[0]
      group_name = grp.getgrgid(gid)[0]

      initial = {}
      initial['path'] = path
      initial['uid'] = uid
      initial['gid'] = gid
      initial['user_name'] = user_name
      initial['group_name'] = group_name
      form = folder_management_forms.ModifyOwnershipForm(initial=initial, user_list = users, group_list = groups)
      return_dict["form"] = form
      return django.shortcuts.render_to_response('modify_dir_ownership.html', return_dict, context_instance=django.template.context.RequestContext(request))
    else:
def modify_group_membership(request):
    return_dict = {}
    try:
        if "ack" in request.GET:
            if request.GET["ack"] == "created":
                return_dict['ack_message'] = "Local group successfully created"

        if "grpname" not in request.REQUEST:
            raise Exception("Invalid request. No group name specified.")

        gd, err = local_users.get_local_group(request.REQUEST['grpname'])
        if err or (not gd):
            if err:
                raise Exception(err)
            else:
                raise Exception("Could not retrieve group information")

        print 'gd - ', gd

        user_list, err = local_users.get_local_users()
        if err:
            raise Exception(err)

        print 'user_list', user_list

        users = []
        primary_users = []
        permitted_users = []
        for u in user_list:
            if u['gid'] != gd['gid']:
                permitted_users.append(u)
            else:
                primary_users.append(u['username'])
            if u['username'] in gd['members']:
                users.append(u['username'])
        print 'users', users
        #return_dict['primary_users'] = primary_users

        if request.method == "GET":
            #Return the form
            initial = {}
            initial['grpname'] = request.GET['grpname']
            initial['users'] = users
            form = local_user_forms.ModifyGroupMembershipForm(
                initial=initial, user_list=permitted_users)
            return_dict['form'] = form
            return django.shortcuts.render_to_response(
                "modify_group_membership.html",
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            form = local_user_forms.ModifyGroupMembershipForm(
                request.POST, user_list=permitted_users)
            return_dict["form"] = form
            if form.is_valid():
                cd = form.cleaned_data
                users = cd['users']
                print users

                audit_str = 'Modified group membership for group "%s". ' % cd[
                    'grpname']
                deleted_users = []
                for existing_user in gd['members']:
                    if existing_user not in users and existing_user not in primary_users:
                        deleted_users.append(existing_user)
                        print 'delete user %s' % existing_user
                added_users = []
                for user in users:
                    if user not in gd['members'] and user not in primary_users:
                        added_users.append(user)
                        print 'add user %s' % user
                if added_users:
                    audit_str += 'Added user(s) %s. ' % (','.join(added_users))
                if deleted_users:
                    audit_str += 'Removed user(s) %s.' % (
                        ','.join(deleted_users))
                print audit_str
                #assert False
                ret, err = local_users.set_group_membership(
                    cd['grpname'], cd['users'])
                if err:
                    raise Exception('Error setting group membership: %s' % err)
                #assert False
                audit.audit("set_group_membership", audit_str, request.META)
                url = '/view_local_group?grpname=%s&searchby=grpname&ack=set_membership' % cd[
                    'grpname']
                return django.http.HttpResponseRedirect(url)
            else:
                return django.shortcuts.render_to_response(
                    "modify_group_membership.html",
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))
    except Exception, e:
        return_dict['base_template'] = 'users-groups_base.html'
        return_dict["page_title"] = 'Modify group membership'
        return_dict['tab'] = 'view_local_groups_tab'
        return_dict["error"] = 'Error modifying group membership'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
def configure_ftp(request):
    return_dict = {}
    try:
        config, err = vsftp.get_ftp_config()
        if err:
            raise Exception(err)
        pools, err = zfs.get_pools()
        ds_list = []
        for pool in pools:
            for ds in pool["datasets"]:
                if ds['properties']['type']['value'] == 'filesystem':
                    ds_list.append(ds["name"])
        cert_list, err = certificates.get_certificates()
        if err:
            raise Exception(err)
        cert_name_list = []
        for cert in cert_list:
            cert_name_list.append(cert['name'])
        #print ds_list
        if not ds_list:
            raise Exception(
                'No ZFS datasets available. Please create a dataset before configuring the FTP service.'
            )

        if request.method == 'GET':
            initial = {}
            if config:
                for key in config.keys():
                    initial[key] = config[key]
            form = ftp_management_forms.ConfigureFTPForm(
                datasets=ds_list, cert_names=cert_name_list, initial=initial)
            return_dict['form'] = form
            return django.shortcuts.render_to_response(
                'configure_ftp.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            form = ftp_management_forms.ConfigureFTPForm(
                request.POST, cert_names=cert_name_list, datasets=ds_list)
            return_dict['form'] = form
            if not form.is_valid():
                return django.shortcuts.render_to_response(
                    "configure_ftp.html",
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))
            cd = form.cleaned_data
            ret, err = vsftp.update_ftp_config(cd)
            if err:
                raise Exception(err)
            users, err = local_users.get_local_users()
            if err:
                raise Exception(err)
            ret, err = vsftp.create_ftp_user_dirs(cd['dataset'], users)
            if err:
                raise Exception(err)
            audit_str = 'Updated FTP configuration.'
            if cd['ssl_enabled']:
                audit_str = audit_str + ' SSL enabled with certificate %s' % cd[
                    'cert_name']
            else:
                audit_str = audit_str + ' SSL disabled.'
            ret, err = audit.audit("update_ftp_config", audit_str,
                                   request.META)
            return django.http.HttpResponseRedirect(
                '/view_ftp_configuration?ack=saved')
    except Exception, e:
        return_dict['base_template'] = "services_base.html"
        return_dict["page_title"] = 'Configure FTP service'
        return_dict['tab'] = 'ftp_service_settings'
        return_dict["error"] = 'Error configuring the FTP service '
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
def modify_dir_permissions(request):
  return_dict = {}
  try:
    if not "error" in return_dict:
      if "ack" in request.GET:
        if request.GET["ack"] == "ace_deleted":
          return_dict['ack_message'] = "ACL entry successfully removed"
        elif request.GET["ack"] == "aces_added":
          return_dict['ack_message'] = "ACL entries successfully added"
        elif request.GET["ack"] == "aces_modified":
          return_dict['ack_message'] = "ACL entries successfully modified"
        elif request.GET["ack"] == "created_dir":
          return_dict['ack_message'] = "Directory successfully created"
        elif request.GET["ack"] == "deleted_dir":
          return_dict['ack_message'] = "Directory successfully deleted"
    users, err = local_users.get_local_users()
    if err:
      raise Exception('Error retrieving local user list : %s'%err)
    if not users:
      raise Exception('No local users seem to be created. Please create at least one local user before performing this operation.')

    groups, err = local_users.get_local_groups()
    if err:
      raise Exception('Error retrieving local group list : %s'%err)
    if not groups:
      raise Exception('No local groups seem to be created. Please create at least one local group before performing this operation.')

    pools, err = zfs.get_pools() 
    ds_list = [] 
    for pool in pools:
      for ds in pool["datasets"]:
        if ds['properties']['type']['value'] == 'filesystem':
          ds_list.append(ds["name"])
    if not ds_list:
      raise Exception('No ZFS datasets available. Please create a dataset before creating shares.')

    if 'path' not in request.REQUEST:
      path = "/"+pools[0]["datasets"][0]["name"]
    else:
      path = request.REQUEST['path']
    try:
      stat_info = os.stat(path)
    except Exception, e:
      raise Exception('Error accessing specified path : %s'%str(e))
    uid = stat_info.st_uid
    gid = stat_info.st_gid
    username = pwd.getpwuid(uid)[0]
    grpname = grp.getgrgid(gid)[0]
    return_dict["username"] = username
    return_dict["grpname"] = grpname

    aces, err = acl.get_all_aces(path)
    if err:
      raise Exception(err)
    minimal_aces, err = acl.get_minimal_aces(aces)
    if err:
      raise Exception(err)
    user_aces, err = acl.get_ug_aces(aces, None, 'user')
    if err:
      raise Exception(err)
    group_aces, err = acl.get_ug_aces(aces, None, 'group')
    if err:
      raise Exception(err)

    return_dict['aces'] = aces
    return_dict['minimal_aces'] = minimal_aces
    if user_aces:
      return_dict['user_aces'] = user_aces
    if group_aces:
      return_dict['group_aces'] = group_aces
    
    return_dict['path'] = path
    return_dict["dataset"] = ds_list
    if request.method == "GET":
      # Shd be an edit request
  
      # Set initial form values
      initial = {}
      initial['path'] = path
      initial['owner_read'] = _owner_readable(stat_info)
      initial['owner_write'] = _owner_writeable(stat_info)
      initial['owner_execute'] = _owner_executeable(stat_info)
      initial['group_read'] = _group_readable(stat_info)
      initial['group_write'] = _group_writeable(stat_info)
      initial['group_execute'] = _group_executeable(stat_info)
      initial['other_read'] = _other_readable(stat_info)
      initial['other_write'] = _other_writeable(stat_info)
      initial['other_execute'] = _other_executeable(stat_info)
      if 'dataset' in request.GET:
        initial['dataset'] = request.GET['dataset']
  
      form = folder_management_forms.SetFileOwnerAndPermissionsForm(initial = initial, user_list = users, group_list = groups)
  
      return_dict["form"] = form
      return django.shortcuts.render_to_response('modify_dir_permissions.html', return_dict, context_instance=django.template.context.RequestContext(request))
  
    elif request.method == "POST":
      path = request.POST.get("path")
      # Shd be an save request
      if request.POST.get("action") == "add_folder":
        folder_name = request.POST.get("new_folder_name")
        directory = path +"/"+folder_name
        if not os.path.exists(directory):
          os.makedirs(directory)
          audit_str = "Creating %s" %directory
          audit.audit("modify_dir_owner_permissions", audit_str, request.META)
      elif request.POST.get("action") == "delete_folder":
        delete = "false"
        if len(path.split("/")) > 2:
          delete = "true"
        # Need to also check if the path is a share or not. If share, dont delete again.
        # Checking NFS
        exports,err = nfs.load_exports_list()
        if exports:
          for export in exports: 
            print id(export["path"]),id(path)
            if export["path"] == path:
              delete = "false"
              break
            else: 
              delete = "true"
              
        if delete:
          print delete
          #shutil.rmtree(path,ignore_errors=True)
          audit_str = "Deleting directory %s" %path
          audit.audit("modify_dir_owner_permissions", audit_str, request.META)
        else:
          raise Exception("Cannot delete folder. It is either a dataset of a share")
      else:
        form = common_forms.SetFileOwnerAndPermissionsForm(request.POST, user_list = users, group_list = groups)
        return_dict["form"] = form
        if form.is_valid():
          cd = form.cleaned_data
          ret, err = file_processing.set_dir_ownership_and_permissions(cd)
          if not ret:
            if err:
              raise Exception(err)
            else:
              raise Exception("Error setting directory ownership/permissions.")
  
          audit_str = "Modified directory ownsership/permissions for %s"%cd["path"]
          audit.audit("modify_dir_owner_permissions", audit_str, request.META)
  
      return django.http.HttpResponseRedirect('/modify_dir_permissions/?ack=set_permissions')
  
    else:
      return django.shortcuts.render_to_response('modify_dir_permissions.html', return_dict, context_instance=django.template.context.RequestContext(request))
Exemplo n.º 10
0
def set_file_owner_and_permissions(request):
  return_dict = {}
  try:
    if 'path' not in request.REQUEST:
      raise Exception('Path not specified')
    path = request.REQUEST['path']

    users, err = local_users.get_local_users()
    if err:
      raise Exception('Error retrieving local user list : %s'%err)
    if not users:
      raise Exception('No local users seem to be created. Please create at least one local user before performing this operation.')

    groups, err = local_users.get_local_groups()
    if err:
      raise Exception('Error retrieving local group list : %s'%err)
    if not groups:
      raise Exception('No local groups seem to be created. Please create at least one local group before performing this operation.')

    try:
      stat_info = os.stat(path)
    except Exception, e:
      raise Exception('Error accessing specified path : %s'%str(e))
    uid = stat_info.st_uid
    gid = stat_info.st_gid
    username = pwd.getpwuid(uid)[0]
    grpname = grp.getgrgid(gid)[0]
    return_dict["username"] = username
    return_dict["grpname"] = grpname


    if request.method == "GET":
      # Shd be an edit request
  
      # Set initial form values
      initial = {}
      initial['path'] = path
      initial['owner_read'] = _owner_readable(stat_info)
      initial['owner_write'] = _owner_writeable(stat_info)
      initial['owner_execute'] = _owner_executeable(stat_info)
      initial['group_read'] = _group_readable(stat_info)
      initial['group_write'] = _group_writeable(stat_info)
      initial['group_execute'] = _group_executeable(stat_info)
      initial['other_read'] = _other_readable(stat_info)
      initial['other_write'] = _other_writeable(stat_info)
      initial['other_execute'] = _other_executeable(stat_info)
  
      form = common_forms.SetFileOwnerAndPermissionsForm(initial = initial, user_list = users, group_list = groups)
  
      return_dict["form"] = form
      return django.shortcuts.render_to_response('set_file_owner_and_permissions.html', return_dict, context_instance=django.template.context.RequestContext(request))
  
    else:
  
      # Shd be an save request
      form = common_forms.SetFileOwnerAndPermissionsForm(request.POST, user_list = users, group_list = groups)
      return_dict["form"] = form
      if form.is_valid():
        cd = form.cleaned_data
        ret, err = file_processing.set_dir_ownership_and_permissions(cd)
        if not ret:
          if err:
            raise Exception(err)
          else:
            raise Exception("Error setting directory ownership/permissions.")
  
        audit_str = "Modified directory ownsership/permissions for %s"%cd["path"]
        audit.audit("modify_dir_owner_permissions", audit_str, request.META["REMOTE_ADDR"])
  
        return django.http.HttpResponseRedirect('/view_zfs_pools?action=set_permissions')
  
      else:
        #Invalid form
        return django.shortcuts.render_to_response('set_file_owner_and_permissions.html', return_dict, context_instance=django.template.context.RequestContext(request))