lshell(1)

NAME
lshell - Limited Shell

SYNOPSIS
lshell [OPTIONS]
lshell policy-show [OPTIONS]
lshell harden-init [OPTIONS]

DESCRIPTION
lshell provides a limited shell configured per user via a configuration file. You can also use lshell within scripts by adding the appropriate shebang (#!/usr/bin/lshell) to your script file. Coupled with ssh's authorized_keys or with /etc/shells and /etc/passwd , it is straightforward to restrict a user's access to a limited set of commands.

OPTIONS

--config <FILE>
    Specify configuration file

--log <DIR>
    Specify the log directory

--<param> <value>
    where <param> is any configuration file parameter

-h, --help
    Show help message

--version
    Show version

policy-show
    Run admin diagnostics mode. Use with:

    --user <NAME>
        target username

    --group <NAME>
        target group (repeatable)

    --command <CMD>
        command to evaluate against final policy

    --json
        print diagnostics as JSON

harden-init
    Generate a hardened baseline configuration profile. Use with:

    --list-templates
        list available hardened templates

    --profile <NAME>
        template name (sftp-only, rsync-backup, deploy-minimal, readonly-support)

    --group <NAME>
        add scoped [grp:<name>] section (repeatable)

    --user <NAME>
        add scoped [user:<name>] section (repeatable)

    --output <FILE>
        write rendered config to file (default: /etc/lshell.d/<profile>.conf)

    --stdout
        print rendered config to stdout

    --dry-run
        render and run sanity checks without writing files

    --explain
        print profile hardening rationale

CONFIGURATION
You can configure lshell through its configuration file:

    On Linux -> /etc/lshell.conf
    On *BSD  -> /usr/{pkg,local}/etc/lshell.conf

The configuration is dynamically reloaded. This means you can edit the configuration and all connected users will automatically load it. In case you are using multiple configuration files (see include_dir), you will need to refresh the main configuration's timestamp, in order to reload the configuration:

    touch /path/to/lshell.conf

lshell configuration has 4 types of sections:

    [global]   -> lshell system configuration (only 1)
    [default]  -> lshell default user configuration (only 1)
    [foo]      -> UNIX username "foo" specific configuration
    [grp:bar]  -> UNIX groupname "bar" specific configuration

Preference loading priority:

    1- User configuration
    2- Group configuration
    3- Default configuration

  [global]

logpath
    config path (default is /var/log/lshell/)

loglevel
    0, 1, 2, 3 or 4 (0: no logs -> 4: logs everything)

logfilename
    - set to syslog in order to log to syslog
    - set log file name, e.g. %u-%y%m%d (i.e foo-20091009.log): %u -> username
    %d -> day [1..31]
    %m -> month [1..12]
    %y -> year [00..99]
    %h -> time [00:00..23:59]

syslogname
    in case you are using syslog, set your logname (default: lshell)

include_dir
    include a directory containing multiple configuration files. These files can only contain default/user/group configuration. The global configuration will only be loaded from the default configuration file. This variable will be expanded (e.g. /path/*.conf).

path_noexec
    set path to sudo noexec library. This path is usually autodetected, only set this variable to use alternate path. If set and the shared object is not found, lshell will exit immediately. Otherwise, please check your logs to verify that a standard path is detected. while this should not be a common practice, setting this variable to an empty string will disable LD_PRELOAD prepend of the commands. This is done at your own risk, as lshell becomes easily breached using some commands like find(1) using the -exec flag.

  [default] and/or [username] and/or [grp:groupname]

aliases
    command aliases list (similar to bash's alias directive)

allowed
    A list of allowed commands, or set to 'all' to allow all commands in the user's PATH.
    - If a command is specified without arguments (e.g., 'echo'), the command is allowed to run with any arguments.
    - If a command is specified with exact arguments (e.g., 'echo asd'), only that specific command with those arguments will be allowed.
    - Local executables must be explicitly listed with a relative path (e.g., './deploy.sh').
    - To allow all commands in the user's PATH, use the value 'all'.
if sudo(8) is installed and sudo_noexec.so is available, it will be loaded before running every command, preventing it from running further commands itself. If not available, beware of commands like vim/find/more/etc. that will allow users to execute code (e.g. /bin/sh) from within the application, thus easily escaping lshell. See variable 'path_noexec' to use an alternative path to library.

allowed_shell_escape
    a list of the allowed commands that are permitted to execute other programs (e.g. shell scripts with exec(3)). Setting this variable to 'all' is NOT allowed. Warning: do not put here any command that can execute arbitrary commands (e.g. find, vim, xargs). Important: commands defined in 'allowed_shell_escape' override their definition in the 'allowed' variable.

allowed_file_extensions
    a list of allowed file extensions that can be provided in the command line. If a list of allowed extensions is provided, all other file extensions will be disallowed.

allowed_cmd_path
    a list of paths; all executable files inside these paths are allowed

disable_exit
    disable user exit, this could be useful when lshell is spawned from another non-restricted shell (e.g. bash)

env_path
    update the environment variable $PATH of the user (optional)

env_vars
    set environment variables (optional)

env_vars_files
    specify a list of files containing environment variables (optional)

forbidden
    a list of forbidden characters or commands

history_file
    set the history filename. A wildcard can be used:
    %u -> username (e.g. '/home/%u/.lhistory')

history_size
    set the maximum size (in lines) of the history file

home_path (deprecated)
    set the home folder of your user. If not specified, the home directory is set to the $HOME environment variable. This variable will be removed in the next version of lshell, please use your system's tools to set a user's home directory. A wildcard can be used:
    %u -> username (e.g. '/home/%u')

intro
    set the introduction to print at login

messages
    optional dictionary used to customize user-facing shell messages. Unsupported keys and unsupported placeholders are rejected during configuration parsing.
    unknown_syntax: {command}
    forbidden_generic: {messagetype}, {command}
    forbidden_command: {command}
    forbidden_path: {command}
    forbidden_character: {command}
    forbidden_control_char: {command}
    forbidden_command_over_ssh: {message}, {command}
    forbidden_scp_over_ssh: {message}
    warning_remaining: {remaining}, {violation_label}
    session_terminated: no placeholders
    incident_reported: no placeholders

login_script
    define the script to run at user login. This script is executed in a child shell process, so shell state changes there (for example umask) do not persist in the lshell parent process.

passwd
    password of specific user (default is empty)

path
    list of path to restrict the user geographically. It is possible to use wildcards (e.g. '/var/log/ap*').

prompt
    set the user's prompt format (default: username)
    %u -> username
    %h -> hostname

prompt_short
    set how the current directory is rendered in the prompt path segment. Accepted values are 0, 1, or 2 (default: 0).
    0 -> show path relative to home when inside home (e.g. ~/projects/api), and absolute path when outside home (e.g. /var/log)
    1 -> show only basename of current directory (e.g. api)
    2 -> show full absolute path of current directory (e.g. /home/user/projects/api)
    note -> if $LPS1 is set, prompt_short is ignored and $LPS1 fully controls prompt rendering
    validation -> values outside 0/1/2 are rejected during configuration parsing

LPS1
    LShell supports prompt customization using the $LPS1 environment variable, similar to $PS1 in bash. If $LPS1 is defined, it takes precedence over prompt and allows for dynamic prompt customization using placeholders. Available placeholders need to be prepended with a backslash (\) and include:
    u -> username of the current user
    h -> short hostname (up to first dot)
    H -> full hostname
    w -> current working directory, with home directory replaced by ~
    W -> basename of the current directory
    $ -> prompt symbol (# for root, $ otherwise)
    t -> current time in HH:MM:SS (24-hour format)
    T -> current time in HH:MM:SS (12-hour format)
    A -> current time in HH:MM (24-hour format, without seconds)
    @ -> current time in HH:MM AM/PM format
    d -> current date in Weekday Month Day format (e.g., Mon Mar 01)

overssh list of command allowed to execute over ssh (e.g. rsync, rdiff-backup, scp, etc.)

scp allow or forbid the use of scp connection - set to 1 or 0

scpforce
    force files sent through scp to a specific directory

scp_download
    set to 0 to forbid scp downloads (default is 1)

scp_upload
    set to 0 to forbid scp uploads (default is 1)

sftp
    allow or forbid the use of sftp connection - set to 1 or 0. WARNING: This option will not work if you are using OpenSSH's internal-sftp service (e.g. when configured in chroot)

sudo_commands
    a list of the allowed commands that can be used with sudo(8). If set to 'all', all the 'allowed' commands will be accessible through sudo(8). It is possible to use the -u sudo flag in order to run a command as a different user than the default root.

timer
    a value in seconds for the session timer

max_sessions_per_user
    maximum concurrent lshell sessions for the same user. Set to 0 to disable this limit (default).

max_background_jobs
    maximum active background jobs (&) allowed in one lshell session. Set to 0 to disable this limit (default).

command_timeout
    wall-clock timeout in seconds applied per executed command. Commands exceeding this timeout are terminated and reported as denied by runtime containment. Set to 0 to disable this limit (default).

max_processes
    maximum processes per spawned command via RLIMIT_NPROC. Set to 0 to disable this limit (default). Best practice: keep command_timeout enabled whenever max_processes is strict (especially 1).

umask
    set process umask for the lshell session. Value must be octal (0000 to 0777), for example 0002.
    0002 -> files 664 / directories 775
    0022 -> files 644 / directories 755
    0077 -> files 600 / directories 700

strict
    logging strictness. If set to 1, any unknown command is considered as forbidden, and user's warning counter is decreased. If set to 0, command is considered as unknown, and user is only warned (i.e. *** unknown syntax)

warning_counter
    number of warnings when user enters a forbidden value before getting exited from lshell. Set to -1 to disable the counter, and just warn the user.

winscp
    enable support for WinSCP with scp mode (NOT sftp) When enabled, the following parameters will be overridden:
    scp_upload: 1 (uses scp(1) from within session)
    scp_download: 1 (uses scp(1) from within session)
    scpforce: ignored (uses scp(1) from within session)
    forbidden: -[';']
    allowed: +['scp', 'env', 'pwd', 'groups', 'unset', 'unalias']

policy_commands
    enable/disable policy introspection builtins. If set to 1 (default), users can run policy-show, policy-path, policy-sudo (and aliases lpath, lsudo). If set to 0, these commands are hidden.

BEST PRACTICES

Least privilege
    Prefer explicit allow-lists in allowed and avoid using 'all' unless strictly required.

Shell escape control
    Keep allowed_shell_escape minimal and do not include tools that execute arbitrary commands (for example: find, vim, xargs).

Extension policy
    Use allowed_file_extensions when users should handle only known file types.

Warning policy
    Keep warning_counter enabled and consider strict=1 for stronger enforcement in high-assurance environments.

Validate before rollout
    Use lshell policy-show to review final merged policy and command decisions before assigning a profile to users.

ACCESSIBILITY

Prompt readability
    Use a readable text prompt format (for example %u@%h) as the default.

Color usage
    If using ANSI colors in prompt or $LPS1, avoid color-only meaning so the prompt remains understandable in monochrome or low-contrast terminals.

Message clarity
    When customizing messages, keep phrasing concise and actionable so users understand how to recover from denied commands.

SHELL BUILTIN COMMANDS
Here is the set of commands that are always available with lshell:

cd  change directory

clear
    clears the terminal

export
    name of exported shell variable. Disabled by default, enable it by adding it to allowed commands.

help, ?
    print the list of allowed commands

history
    print the commands history

policy-show [command]
    show resolved policy values. If a command is provided, also show allow/deny decision.

policy-path
    lists all allowed and forbidden path

policy-sudo
    lists all sudo allowed commands

lpath
    alias for policy-path

lsudo
    alias for policy-sudo

jobs
    list background jobs

fg  bring job to foreground

bg  resume job in background (not currently supported)

exit, quit
    exit lshell

EXAMPLES

$ lshell
    Tries to run lshell using default ${PREFIX}/etc/lshell.conf as configuration file. If it fails a warning is printed and lshell is interrupted. lshell options are loaded from the configuration file

$ lshell --config /path/to/myconf.file --log /path/to/mylog.log
    This will override the default options specified for configuration and/or log file

$ lshell --config /path/to/myconf.file --umask 0077
    Runs lshell with a private session umask; new files default to 600 and directories to 700.

$ lshell harden-init --profile sftp-only --group sftpusers --user alice --output /etc/lshell.d/sftp-only.conf
    Generate a hardened scoped include file for a specific group and user directly from CLI flags:

    # /etc/lshell.d/sftp-only.conf
    [grp:sftpusers]
    allowed         : ['pwd','ls','cd']
    allowed_shell_escape : []
    forbidden       : [';','&','|','`','>','<','$(','${']
    warning_counter : 2
    strict          : 1
    scp             : 0
    scp_upload      : 0
    scp_download    : 0
    sftp            : 1
    overssh         : []
    [user:alice]
    allowed         : ['pwd','ls','cd']
    warning_counter : 1

$ ./test_script.lsh
    If you include lshell in a script with the shebang (e.g. #!/usr/bin/lshell) and use the `.lsh` extension:

    #!/usr/bin/lshell
    echo "Hello World!"
    Ensure the script has a .lsh extension to indicate it is intended for lshell. This allows for limited shell commands to be executed within the script while maintaining restrictions.

USE CASE
The primary goal of lshell is to create shell accounts with ssh access and restrict their environment to a couple of needed commands. In this example, User 'foo' and user 'bar' both belong to the 'users' UNIX group:

User foo:
     - must be able to access /usr and /var but not /usr/local
     - can use all commands in PATH except 'su'
     - has a warning counter set to 5
     - has his home path set to '/home/users'

User bar:
     - must be able to access /etc and /usr but not /usr/local
     - is allowed default commands plus 'ping' minus 'ls'
     - strictness is set to 1 (meaning he is not allowed to type an unknown command)
In this case, my configuration file will look something like this:

    # CONFIGURATION START
    [global]
    logpath         : /var/log/lshell/
    loglevel        : 2
    [default]
    allowed         : ['ls','pwd']
    forbidden       : [';', '&', '|']
    warning_counter : 2
    messages        : {
                      'unknown_syntax': 'lshell: unknown syntax: {command}',
                      'forbidden_generic': 'lshell: forbidden {messagetype}: "{command}"',
                      'forbidden_command': 'lshell: forbidden command: "{command}"',
                      'forbidden_path': 'lshell: forbidden path: "{command}"',
                      'forbidden_character': 'lshell: forbidden character: "{command}"',
                      'forbidden_control_char': 'lshell: forbidden control char: "{command}"',
                      'forbidden_command_over_ssh': 'lshell: forbidden {message}: "{command}"',
                      'forbidden_scp_over_ssh': 'lshell: forbidden {message}',
                      'warning_remaining': 'lshell: warning: {remaining} {violation_label} remaining before session termination',
                      'session_terminated': 'lshell: session terminated: warning limit exceeded',
                      'incident_reported': 'lshell: This incident has been reported.'
                      }
    timer           : 0
    path            : ['/etc', '/usr']
    env_path        : ':/sbin:/usr/bin/'
    scp             : 1 # or 0
    sftp            : 1 # or 0
    overssh         : ['rsync','ls']
    aliases         : {'ls':'ls --color=auto','ll':'ls -l'}
    [grp:users]
    warning_counter : 5
    overssh         : - ['ls']
    [foo]
    allowed         : 'all' - ['su']
    path            : ['/var', '/usr'] - ['/usr/local']
    home_path       : '/home/users'
    [bar]
    allowed         : + ['ping'] - ['ls']
    path            : - ['/usr/local']
    strict          : 1
    scpforce        : '/home/bar/uploads/'
    # CONFIGURATION END

NOTES

In order to log a user's warnings into the logging directory (default /var/log/lshell/), you must first create the folder (if it does not exist yet) and chown it to lshell group:

    # addgroup --system lshell
    # mkdir /var/log/lshell
    # chown :lshell /var/log/lshell
    # chmod 770 /var/log/lshell

then add the user to the lshell group:

    # usermod -aG lshell user_name

In order to set lshell as default shell for a user:

    On Linux:
    # chsh -s /usr/bin/lshell user_name
    On *BSD:
    # chsh -s /usr/{pkg,local}/bin/lshell user_name

AUTHOR
Currently maintained by Ignace Mouzannar <ghantoos@ghantoos.org>