Minimal security steps for brand new servers.
    Installs system updates, creates new user (with sudo privileges) for future
    usage, and disables root login via SSH.
541216
def secure(new_user=env.user):
    
    run("apt-get update -q")
    run("apt-get upgrade -y -q")
    run("adduser --gecos '' %s" % new_user)
    run("usermod -G sudo %s" % new_user)
    run("sed -i 's:RootLogin yes:RootLogin no:' /etc/ssh/sshd_config")
    run("service ssh restart")
    print(green("Security steps completed. Log in to the server as '%s' from "
                "now on." % new_user, bold=True))
648995
def create_authserver(self, domainid, data):
        """"""
        return self.api_call(
            ENDPOINTS['authservers']['new'],
            dict(domainid=domainid),
            body=data)
176853
def create_user
      @admin = Admin.new(administrator_params)
      @admin.access_level = 'admin'
      @admin.overlord = 'Y'
      
      respond_to do |format|
        if @admin.save
          Setting.save_data({setup_complete: 'Y'})
          clear_cache
          session[:setup_complete] = true
          format.html { redirect_to admin_path, notice: I18n.t("controllers.admin.setup.general.success") }
        else
          format.html { render action: "administrator" }
        end
      end

    end
1310361
public function onCreating()
    {
        // Send out email
        if (Request::has('_send_email')) {
            $this->sendCreateEmail();
        }

        // Make them active
        $this->active = 1;

        // If the current user can't grant permissions, make the new admin
        // have the same role as themselves.  Admins created from the CLI (like as
        // part of a migration) won't be logged in.
        if (($admin = app('decoy.user'))
            && !app('decoy.user')->can('grant', 'admins')) {
            $this->role = $admin->role;

        // Otherwise, give the admin a default role if none was defined
        } elseif (empty($this->role)) {
            $this->role = 'admin';
        }
    }
551162
def cli(env, identifier, enable, permission, from_user):
    """"""
    mgr = SoftLayer.UserManager(env.client)
    user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
    result = False
    if from_user:
        from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username')
        result = mgr.permissions_from_user(user_id, from_user_id)
    elif enable:
        result = mgr.add_permissions(user_id, permission)
    else:
        result = mgr.remove_permissions(user_id, permission)

    if result:
        click.secho("Permissions updated successfully: %s" % ", ".join(permission), fg='green')
    else:
        click.secho("Failed to update permissions: %s" % ", ".join(permission), fg='red')
72034
def add_ec2_user(guestfs)
      @log.debug "Adding ec2-user user..."

      # We need to add ec2-user only when it doesn't exists
      #
      # https://issues.jboss.org/browse/BGBUILD-313
      unless guestfs.fgrep("ec2-user", "/etc/passwd").empty?
        @log.debug("ec2-user already exists, skipping.")
        return
      end

      guestfs.sh("useradd ec2-user")
      guestfs.sh("echo -e 'ec2-user\tALL=(ALL)\tNOPASSWD: ALL' >> /etc/sudoers")

      @log.debug "User ec2-user added."
    end
458767
def create(self):
        """"""

        self.before_create()

        puts(green('Creating app context'))
        tdir = os.path.dirname(__file__)

        # Ensure the app context user exists
        user_ensure(self.user, home='/home/' + self.user)
        dir_ensure('/home/%s/.ssh' % self.user)

        t = '/home/%s/.ssh/authorized_keys'
        app_authorized_keys = t % env.user
        ctx_authorized_keys = t % self.user

        # Ensure the app user has the same authorized_keys as the admin user
        if file_exists(app_authorized_keys) and \
           not file_exists(ctx_authorized_keys):
            sudo('cp %s %s' % (app_authorized_keys, ctx_authorized_keys))
            file_attribs(ctx_authorized_keys, mode=755,
                         owner=self.user, group=self.user)

        # Actions to be performed with the app context user
        with settings(user=self.user):
            # Make sure the dot files exist
            # This is mostly necessary for virtualenvwrapper to work properly
            for f in ['bashrc', 'bash_profile', 'profile']:
                lfn = os.path.join(tdir, 'templates', '%s.tmpl' % f)
                contents = file_local_read(lfn) % self.__dict__
                rfn = '/home/%s/.%s' % (self.user, f)
                file_ensure(rfn, owner=self.user, group=self.user)
                file_update(rfn, lambda _: contents)

            # Make sure the sites folder exists
            dir_ensure('/home/%s/sites' % self.user)

            # Make sure the app's required folders exist
            for d in [self.root_dir, self.releases_dir, self.etc_dir,
                      self.log_dir, self.run_dir, self.shared_dir]:
                dir_ensure(d)

            # Create the virtualenv
            run('mkvirtualenv ' + self.name)

        self.after_create()
499204
def init(opts):
    '''
    
    '''
    try:
        DETAILS['server'] = SSHConnection(host=__opts__['proxy']['host'],
                                          username=__opts__['proxy']['username'],
                                          password=__opts__['proxy']['password'])
        out, err = DETAILS['server'].sendline('help')
        DETAILS['initialized'] = True

    except TerminalException as e:
        log.error(e)
        return False
1335076
def ssh(
            self, machine, *,
            username=None, command=None, boot_only=False, discovered=False,
            wait=300):
        """"""
        start_time = time.monotonic()
        with utils.Spinner() as context:
            context.msg = colorized(
                "{autoblue}Determining{/autoblue} best IP for %s" % (
                    machine.hostname))
            ip_addresses = self.get_ip_addresses(
                machine, boot_only=boot_only, discovered=discovered)
            if len(ip_addresses) > 0:
                pingable_ips = self._async_get_sshable_ips(ip_addresses)
                while (len(pingable_ips) == 0 and
                        (time.monotonic() - start_time) < wait):
                    time.sleep(5)
                    pingable_ips = self._async_get_sshable_ips(ip_addresses)
                if len(pingable_ips) == 0:
                    raise CommandError(
                        "No IP addresses on %s can be reached." % (
                            machine.hostname))
                else:
                    ip = pingable_ips[0]
            else:
                raise CommandError(
                    "%s has no IP addresses." % machine.hostname)

            if username is None:
                context.msg = colorized(
                    "{autoblue}Determining{/autoblue} SSH username on %s" % (
                        machine.hostname))
                username = self._determine_username(ip)
                while (username is None and
                        (time.monotonic() - start_time) < wait):
                    username = self._determine_username(ip)
                if username is None:
                    raise CommandError(
                        "Failed to determine the username for SSH.")

            conn_str = "%s@%s" % (username, ip)
            args = [
                "ssh",
                "-o", "UserKnownHostsFile=/dev/null",
                "-o", "StrictHostKeyChecking=no",
                conn_str
            ]

            context.msg = colorized(
                "{automagenta}Waiting{/automagenta} for SSH on %s" % (
                    machine.hostname))
            check_args = args + ["echo"]
            connectable = self._check_ssh(*check_args)
            while not connectable and (time.monotonic() - start_time) < wait:
                time.sleep(5)
                connectable = self._check_ssh(*check_args)
            if not connectable:
                raise CommandError(
                    "SSH never started on %s using IP %s." % (
                        machine.hostname, ip))

        if command is not None:
            args.append(command)
        ssh = subprocess.Popen(
            args, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
        ssh.wait()
        return ssh.returncode
147140
def enable_root_f5(host)
      for tries in 1..10
        begin
          #This command is problematic as the F5 is not always done loading
          if host.exec(Command.new("modify sys db systemauth.disablerootlogin value false"), :acceptable_exit_codes => [0,1]).exit_code == 0 \
              and host.exec(Command.new("modify sys global-settings gui-setup disabled"), :acceptable_exit_codes => [0,1]).exit_code == 0 \
              and host.exec(Command.new("save sys config"), :acceptable_exit_codes => [0,1]).exit_code == 0
            backoff_sleep(tries)
            break
          elsif tries == 10
            raise "Instance was unable to be configured"
          end
        rescue Beaker::Host::CommandFailure => e
          @logger.debug("Instance not yet configured (#{e})")
        end
        backoff_sleep(tries)
      end
      host['user'] = 'admin'
      sha256 = Digest::SHA256.new
      password = sha256.hexdigest((1..50).map{(rand(86)+40).chr}.join.gsub(/\\/,'\&\&')) + 'password!'
      # disabling password policy to account for the enforcement level set
      # and the generated password is sometimes too `01070366:3: Bad password (admin): BAD PASSWORD: \
      # it is too simplistic/systematic`
      host.exec(Command.new('modify auth password-policy policy-enforcement disabled'))
      host.exec(Command.new("modify auth user admin password #{password}"))
      @logger.notify("f5: Configured admin password to be #{password}")
      host.close
      host['ssh'] = {:password => password}
    end
1317192
def create_admin(app, appbuilder, username, firstname, lastname, email, password):
    
    auth_type = {
        c.AUTH_DB: "Database Authentications",
        c.AUTH_OID: "OpenID Authentication",
        c.AUTH_LDAP: "LDAP Authentication",
        c.AUTH_REMOTE_USER: "WebServer REMOTE_USER Authentication",
        c.AUTH_OAUTH: "OAuth Authentication",
    }
    _appbuilder = import_application(app, appbuilder)
    click.echo(
        click.style(
            "Recognized {0}.".format(
                auth_type.get(_appbuilder.sm.auth_type, "No Auth method")
            ),
            fg="green",
        )
    )
    role_admin = _appbuilder.sm.find_role(_appbuilder.sm.auth_role_admin)
    user = _appbuilder.sm.add_user(
        username, firstname, lastname, email, role_admin, password
    )
    if user:
        click.echo(click.style("Admin User {0} created.".format(username), fg="green"))
    else:
        click.echo(click.style("No user created an error occured", fg="red"))
1148776
private void updateServerStart(UpdateServerHeartbeat update)
  {
    // internal communication is non-ssl
    boolean isSSL = false;
    
    ServerHeartbeat server = _root.createServer(update.getAddress(),
                                                update.getPort(),
                                                isSSL,
                                                0,
                                                getCluster());
    
    server.setDisplayName(update.getDisplayName());
    //server.setMachineHash(serverUpdate.getMachineHash());

    updateServer(server, update);
    
    if (server.getRack() != null) {
      server.getRack().update();
    }
  }
1144723
def create
      @user = User.new(user_params.except(:user_roles))
      authorize! :create, @user
      build_user_roles(params)

      if @user.save
        redirect_to @user,
                    notice: "User was successfully created."
      else
        render :new
      end
    end
529733
def root_password(self, server_id, password):
        '''
        
        '''
        nt_ks = self.compute_conn
        nt_ks.servers.change_password(server_id, password)
1361380
def need_deployment():
    '''
    
    '''
    if os.path.exists(OPTIONS.saltdir):
        shutil.rmtree(OPTIONS.saltdir)
    old_umask = os.umask(0o077)  # pylint: disable=blacklisted-function
    try:
        os.makedirs(OPTIONS.saltdir)
    finally:
        os.umask(old_umask)  # pylint: disable=blacklisted-function
    # Verify perms on saltdir
    if not is_windows():
        euid = os.geteuid()
        dstat = os.stat(OPTIONS.saltdir)
        if dstat.st_uid != euid:
            # Attack detected, try again
            need_deployment()
        if dstat.st_mode != 16832:
            # Attack detected
            need_deployment()
        # If SUDOing then also give the super user group write permissions
        sudo_gid = os.environ.get('SUDO_GID')
        if sudo_gid:
            try:
                os.chown(OPTIONS.saltdir, -1, int(sudo_gid))
                stt = os.stat(OPTIONS.saltdir)
                os.chmod(OPTIONS.saltdir, stt.st_mode | stat.S_IWGRP | stat.S_IRGRP | stat.S_IXGRP)
            except OSError:
                sys.stdout.write('\n\nUnable to set permissions on thin directory.\nIf sudo_user is set '
                                 'and is not root, be certain the user is in the same group\nas the login user')
                sys.exit(1)

    # Delimiter emitted on stdout *only* to indicate shim message to master.
    sys.stdout.write("{0}\ndeploy\n".format(OPTIONS.delimiter))
    sys.exit(EX_THIN_DEPLOY)
1123604
def setupnode(overwrite=False):
    
    if not port_is_open():
        if not skip_disable_root():
            disable_root()
        port_changed = change_ssh_port()
    #avoid trying to take shortcuts if setupnode did not finish 
    #on previous execution
    if server_state('setupnode-incomplete'):
        env.overwrite=True
    else: set_server_state('setupnode-incomplete')
    upload_ssh_key()
    restrict_ssh()
    add_repositories()
    upgrade_packages()
    setup_ufw()
    uninstall_packages()
    install_packages()

    upload_etc()
    post_install_package()
    setup_ufw_rules()
    set_timezone()
    set_server_state('setupnode-incomplete',delete=True)
    #stop and start webservers - and reload nginx
    for s in webserver_list():
        stop_webserver(s)
        start_webserver(s)
1201685
def new
      # Before displaying the login form, make sure an external auth system shouldn't be used.
      auth_url = ::Incline::UserManager.begin_external_authentication(request)
      redirect_to auth_url unless auth_url.blank?
    end