Commit b8f3169f authored by Dominika Liberda's avatar Dominika Liberda 💽

Initial commit, importing from tarball

parents
### GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates the
terms and conditions of version 3 of the GNU General Public License,
supplemented by the additional permissions listed below.
#### 0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the
GNU General Public License.
"The Library" refers to a covered work governed by this License, other
than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
#### 1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
#### 2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
- a) under this License, provided that you make a good faith effort
to ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
- b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
#### 3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a
header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
- a) Give prominent notice with each copy of the object code that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the object code with a copy of the GNU GPL and this
license document.
#### 4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken
together, effectively do not restrict modification of the portions of
the Library contained in the Combined Work and reverse engineering for
debugging such modifications, if you also do each of the following:
- a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the Combined Work with a copy of the GNU GPL and this
license document.
- c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
- d) Do one of the following:
- 0) Convey the Minimal Corresponding Source under the terms of
this License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
- 1) Use a suitable shared library mechanism for linking with
the Library. A suitable mechanism is one that (a) uses at run
time a copy of the Library already present on the user's
computer system, and (b) will operate properly with a modified
version of the Library that is interface-compatible with the
Linked Version.
- e) Provide Installation Information, but only if you would
otherwise be required to provide such information under section 6
of the GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the Application
with a modified version of the Linked Version. (If you use option
4d0, the Installation Information must accompany the Minimal
Corresponding Source and Corresponding Application Code. If you
use option 4d1, you must provide the Installation Information in
the manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.)
#### 5. Combined Libraries.
You may place library facilities that are a work based on the Library
side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
- a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities, conveyed under the terms of this License.
- b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
#### 6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
as you received it specifies that a certain numbered version of the
GNU Lesser General Public License "or any later version" applies to
it, you have the option of following the terms and conditions either
of that published version or of any later version published by the
Free Software Foundation. If the Library as you received it does not
specify a version number of the GNU Lesser General Public License, you
may choose any version of the GNU Lesser General Public License ever
published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
# HTTP.sh
Node.js, but `| sed s/Node/HTTP/;s/js/sh/`.
Launch with `./http.sh`. Does not need root priviliges ~~- in fact, DO NOT run it as superuser~~ unless you're running it on ports lower than 1024. If you're running on 80 and 443, superuser is more or less mandatory, but THIS MAY BE UNSAFE.
To prevent running malicious scripts, by default only scripts with extension `.shs` can be run by the server, but this can be changed in the config. Also, cfg[index] ignores this. SHS stands for Shell Server.
Originally made for Junction Stupidhack 2020; Created by @redsPL, @selfisekai and @ptrcnull.
## Dependencies
- Bash or 100% compatible shell
- [Ncat](https://nmap.org/ncat)
- pkill
- mktemp
- dd (for accounts, multipart/form-data and websockets)
- sha1sum, sha256sum (for accounts and simple auth)
- curl (for some demos)
## Known faults
- can't change the HTTP status code from Shell Server scripts. This could theoretically be done with custom vhost configs and some `if` statements, but this would be a rather nasty solution to that problem.
- `$post_multipart` doesn't keep original names - could be fixed by parsing individual headers from the multipart request instead of skipping them all
## Directory structure (incomplete)
- config
- master.sh: main config file, loaded with every request
- localhost:1337: example vhost file, loaded if `Host: ...` equals its name
- src
- server source files and modules (e.g. `ws.sh`)
- response
- files corresponding to specific HTTP status codes
- listing.sh (code 210) is actually HTTP 200, but triggered in a directory with autoindex turned on and without a valid `index.shs` file
- templates
- section templates go here
- webroot
- place your files **here**
- secret
- users/passwords go here
- storage
- random data storage for shs apps
## Variables that we think are cool!
- $post_data - array, contains data from urlencoded POSTs
- $post_multipart - array, contains URIs to uploaded files from multipart/form-data POSTs
- $get_data - array, contains data from GETs
- $cfg - array, contains config values (from master.sh and vhost configs)
- $r - array, contains data generated from the request - URI, URL and that kinda stuff.
cfg[title]='Laura is cute :3'
declare -A cfg
cfg[port]=1337
cfg[root]='webroot/'
cfg[index]='index.shs'
cfg[autoindex]=true
cfg[auth_required]=false
cfg[auth_realm]="Laura is cute <3"
cfg[ssl]=true
cfg[ssl_port]=8443
cfg[ssl_cert]=''
cfg[ssl_key]=''
cfg[extension]='shs'
cfg[extra_headers]='server: HTTP.sh/0.9'
cfg[title]='ddd defies development'
#!/bin/bash
trap ctrl_c INT
function ctrl_c() {
pkill -P $$
echo -e "Killed all remaining processes.\nHave a great day!!"
}
source config/master.sh
echo "HTTP.sh"
if [[ ${cfg[ssl]} == true ]]; then
echo "listening on port ${cfg[port]} (HTTP) and ${cfg[ssl_port]} (HTTPS)"
ncat -l -p ${cfg[port]} -c ./src/server.sh -k &
if [[ ${cfg[ssl_key]} != '' && ${cfg[ssl_cert]} != '' ]]; then
ncat -l -p ${cfg[ssl_port]} -c ./src/server.sh -k --ssl --ssl-cert ${cfg[ssl_cert]} --ssl-key ${cfg[ssl_key]}
else
ncat -l -p ${cfg[ssl_port]} -c ./src/server.sh -k --ssl
fi
else
echo "listening on port ${cfg[port]} (HTTP)"
ncat -l -p ${cfg[port]} -c ./src/server.sh -k
fi
#!/bin/bash
# account.sh - account and session mgmt
# register(username, password)
function register() {
local username=$(echo -ne $(printf "$1" | sed -E "s/ /_/g;s/\:/\-/g;s/\%/\\x/g"))
if [[ $(grep "$username:" secret/users.dat) != '' ]]; then
reason="This user already exists!"
return 1
fi
local salt=$(dd if=/dev/urandom bs=256 count=1 | sha1sum | cut -c 1-16)
local hash=$(echo -n $2$salt | sha256sum | cut -c 1-64)
local token=$(dd if=/dev/urandom bs=32 count=1 | sha1sum | cut -c 1-40)
set_cookie "sh_session" $token
set_cookie "username" $username
echo "$username:$hash:$salt:$token" >> secret/users.dat
}
# login(username, password)
function login() {
local username=$(echo -ne $(echo "$1" | sed -E 's/%/\\x/g'))
echo $1 $username > /dev/stderr
IFS=':'
local user=($(grep "$username:" secret/users.dat))
unset IFS
if [[ $(echo -n $2${user[2]} | sha256sum | cut -c 1-64 ) == ${user[1]} ]]; then
set_cookie "sh_session" ${user[3]}
set_cookie "username" $username
return 0
else
remove_cookie "sh_session"
remove_cookie "username"
reason="Invalid credentials!!11"
return 1
fi
}
# login_simple(base64)
function login_simple() {
local data=$(echo $3 | base64 -d)
echo $3 > /dev/stderr
local password=$(echo $data | sed -E 's/^(.*)\://')
local login=$(echo $data | sed -E 's/\:(.*)$//')
IFS=':'
local user=($(grep "$login:" secret/users.dat))
unset IFS
if [[ $(echo -n $password${user[2]} | sha256sum | cut -c 1-64 ) == ${user[1]} ]]; then
r[authorized]=true
echo "nay" > /dev/stderr
else
r[authorized]=false
fi
}
# logout()
function logout() {
remove_cookie "sh_session"
remove_cookie "username"
}
# session_verify(session)
function session_verify() {
if [[ $(grep ":$1" secret/users.dat) != '' && $1 != '' ]]; then
return 0
else
return 1
fi
}
# session_get_username(session)
function session_get_username() {
IFS=':'
local data=($(grep ":$1" secret/users.dat))
unset IFS
echo ${data[0]}
}
#!/bin/bash
# mime.sh - determine what Content-Type should be passed on
#
# Common HTML files (.html/.htm) -> text/html
# Shell Server Scripts (.shs) -> leaves without any content type, TBD by the browser
# CSS files (.css) -> text/css
# Text files (mimetype starting with 'text/') -> text/plain (fixes XSS in pastebin)
# All else -> pass real mimetype
function get_mime() {
local file=$@
local mime=$(file --mime-type -b $file)
echo $file $mime > /dev/stderr
if [[ $file == *".htm" || $file == *".html" ]]; then
content_type="text/html"
return 0
elif [[ $file == *".shs" ]]; then
content_type=""
return 0
elif [[ $file == *".css" ]]; then
content_type="text/css"
elif [[ $mime == "text/"* ]]; then
content_type="text/plain"
else
content_type="$mime"
fi
}
#!/bin/bash
# misc.sh - miscellaneous functions
# set_cookie(cookie_name, cookie_content)
function set_cookie() {
r[headers]+="Set-Cookie: $1=$2\r\n"
}
# remove_cookie(cookie_name)
function remove_cookie() {
r[headers]+="Set-Cookie: $1=; Expires=Sat, 02 Apr 2005 20:37:00 GMT\r\n"
}
# header(header, header...)
function header() {
for i in "$@"; do
r[headers]+="$i\r\n"
done
}
echo "HTTP/1.1 101 Web Socket Protocol Handshake
Connection: Upgrade
Upgrade: WebSocket
${cfg[extra_headers]}"
if [[ ${r[websocket_key]} != '' ]]; then
accept=$(echo -ne $(printf "${r[websocket_key]}""258EAFA5-E914-47DA-95CA-C5AB0DC85B11" | sha1sum | sed 's/ //g;s/-//g;s/.\{2\}/\\x&/g') | base64)
echo "Sec-WebSocket-Accept: "$accept
fi
printf "\r\n\r\n"
#echo "Laura is cute <3"
#WebSocket-Location: ws://localhost:1337/
#WebSocket-Origin: http://localhost:1337/\r\n\r\n "
source ./src/ws.sh
#input=''
#while read -N 1 chr; do
# input=$input$chr
# if [[ $chr == "\r" ]]; then
# break
# fi
#done
exit 0
#while true; do
# read test
# echo $test
# sleep 1
#done
printf "HTTP/1.0 200 OK
${cfg[extra_headers]}\r\n"
get_mime ${r[uri]}
[[ $content_type != '' ]] && printf "content-type: $content_type\r\n"
if [[ ${r[uri]} =~ \.${cfg[extension]}$ ]]; then
temp=$(mktemp)
source "${r[uri]}" > $temp
[[ ${r[headers]} != '' ]] && printf "${r[headers]}\r\n\r\n" || printf "\r\n"
cat $temp
rm $temp
else
printf "\r\n"
cat "${r[uri]}"
fi
printf "HTTP/1.0 401 Unauthorized
WWW-Authenticate: Basic realm=\"${cfg[auth_realm]}\"
${cfg[extra_headers]}\r\n"
printf "HTTP/1.0 403 Forbidden
${cfg[extra_headers]}\r\n\r\n"
source templates/head.sh
echo "<h1>403: You've been naughty</h1>"
printf "HTTP/1.0 404 Not Found
${cfg[extra_headers]}\r\n\r\n"
source templates/head.sh
echo "<h1>404 Not Found</h1>"
printf "HTTP/1.0 200 OK
${cfg[extra_headers]}\r\n\r\n"
source templates/head.sh
printf "<h1>Index of $([[ ${r[url]} == '' ]] && echo '/' || echo ${r[url]})</h1>"
if [[ ${cookies[username]} != '' ]]; then
echo "Logged in as ${cookies[username]}"
fi
printf "<table>
<tr>
<th>File</th>
<th>Size</th>
<th>Date</th>
</tr>
<tr>
<td><a href='../'>..</a></td><td></td><td></td>
</tr>"
IFS=$'\n'
for i in $(ls ${r[uri]}); do
unset IFS
stats=($(ls -hld "${r[uri]}/$i")) # -hld stands for Half-Life Dedicated
if [[ -d ${r[uri]}'/'$i ]]; then
printf "<tr><td><a href='$(echo -ne ${r[url]})/$i/'>$i</a></td><td>&lt;DIR&gt;</td><td>${stats[5]} ${stats[6]} ${stats[7]}</td></tr>"
else
printf "<tr><td><a href='$(echo -ne ${r[url]})/$i'>$i</a></td><td>${stats[4]}B</td><td>${stats[5]} ${stats[6]} ${stats[7]}</td></tr>"
fi
done
printf "</table><p><i>HTTP.sh server on ${r[host]}</i></p><p>laura is cute</p>"
#!/bin/bash
source config/master.sh
source src/mime.sh
source src/misc.sh
source src/account.sh
declare -A r # current request / response
declare -A meta # metadata for templates
declare -A cookies # cookies!
r[status]=210 # Mommy always said that I was special
post_length=0
post=false
get=false
while read param; do
if [[ $param == $'\015' ]]; then
break
elif [[ $param == *"Content-Length:"* ]]; then
r[content_length]=$(echo -n $param | sed 's/Content-Length: //;s/\r//')
elif [[ $param == *"Content-Type:"* ]]; then
r[content_type]=$(echo -n $param | sed 's/Content-Type: //;s/\r//')
if [[ ${r[content_type]} == *"multipart/form-data"* ]]; then
tmpdir=$(mktemp -d)
fi
if [[ ${r[content_type]} == *"boundary="* ]]; then
r[content_boundary]=$(echo -n ${r[content_type]} | sed -E 's/(.*)boundary=//;s/\r//;s/ //')
fi
elif [[ $param == *"Host:"* ]]; then
r[host]=$(printf "$param" | sed 's/Host: //;s/\r//')
r[host_portless]=$(echo ${r[host]} | sed -E 's/:(.*)$//')
if [[ -f "config/${r[host]}" ]]; then
source "config/${r[host]}"
elif [[ -f "config/${r[host_portless]}" ]]; then
source "config/${r[host_portless]}"
fi
elif [[ $param == *"Upgrade:"* && $(printf "$param" | sed 's/Upgrade: //;s/\r//') == "websocket" ]]; then
r[status]=101
elif [[ $param == *"Sec-WebSocket-Key:"* ]]; then
r[websocket_key]=$(printf "$param" | sed 's/Sec-WebSocket-Key: //;s/\r//')
elif [[ $param == *"Authorization: Basic"* ]]; then
login_simple $param
elif [[ $param == *"Cookie: "* ]]; then
for i in $(echo $param | sed -E 's/Cookie: //;s/\;//g;s/%/\\x/g'); do
name=$(echo $i | sed -E 's/\=(.*)$//')
value=$(echo $i | sed -E 's/^(.*)\=//')
cookies[$name]=$(echo -e $value)
done
elif [[ $param == *"GET "* ]]; then
r[url]=$(echo -ne "$(echo -n $param | sed -E 's/GET //;s/HTTP\/[0-9]+\.[0-9]+//;s/ //g;s/\%/\\x/g;s/\/*\r//g;s/\/\/*/\//g')")
data=$(echo ${r[url]} | sed -E 's/^(.*)\?//;s/\&/ /g')
if [[ $data != ${r[url]} ]]; then
declare -A get_data
for i in $data; do
name=$(echo $i | sed -E 's/\=(.*)$//')
value=$(echo $i | sed "s/$name\=//")
get_data[$name]=$value
done
fi
elif [[ $param == *"POST "* ]]; then
r[url]=$(echo -ne "$(echo -n $param | sed -E 's/POST //;s/HTTP\/[0-9]+\.[0-9]+//;s/ //g;s/\%/\\x/g;s/\/*\r//g;s/\/\/*/\//g')")
r[post]=true
# below shamelessly copied from GET, should be moved to a function
data=$(echo ${r[url]} | sed -E 's/^(.*)\?//;s/\&/ /g')
if [[ $data != ${r[url]} ]]; then
declare -A get_data
for i in $data; do
name=$(echo $i | sed -E 's/\=(.*)$//')
value=$(echo $i | sed "s/$name\=//")
get_data[$name]=$value
done
fi
fi
done
r[uri]=$(realpath ${cfg[root]}$(echo ${r[url]} | sed -E 's/\?(.*)$//'))
[[ -d "${r[uri]}/" ]] && pwd="${r[uri]}" || pwd=$(dirname "${r[uri]}")
# shitty logging
echo "-------------" >> log
echo $(date) >> log
echo "URL: ${r[url]}, GET_data: ${get_data[@]}, POST_data: ${post_data[@]}, POST_multipart: ${post_multipart[@]}" >> log
echo ${r[uri]} > /dev/stderr
if [[ ${r[status]} != 101 ]]; then
if [[ -a ${r[uri]} && ! -r ${r[uri]} ]]; then
r[status]=403
elif [[ "$(echo -n ${r[uri]})" != "$(realpath ${cfg[root]})"* ]]; then
r[status]=403
elif [[ -f ${r[uri]} ]]; then
r[status]=200
elif [[ -d ${r[uri]} ]]; then
for name in ${cfg[index]}; do
if [[ -f "${r[uri]}/$name" ]]; then
r[uri]="${r[uri]}/$name"
r[status]=200
fi
done
else
r[status]=404
fi
fi
if [[ ${cfg[auth_required]} == true && ${r[authorized]} != true ]]; then
echo "Auth failed." >> log
r[status]=401
fi
if [[ ${r[post]} == true && ${r[status]} == 200 ]]; then
# This whole ordeal is here to prevent passing binary data as a variable.
# I could have done it as an array, but this solution works, and it's
# speedy enough so I don't care.
if [[ $tmpdir ]]; then
declare post_multipart
tmpfile=$(mktemp -p $tmpdir)
dd iflag=fullblock of=$tmpfile ibs=${r[content_length]} count=1 obs=1M
delimeter_len=$(echo -n "$content_boundary"$'\015' | wc -c)
boundaries_list=$(echo -ne $(grep $tmpfile -ao -e ${r[content_boundary]} --byte-offset | sed -E 's/:(.*)//g') | sed -E 's/ [0-9]+$//')
for i in $boundaries_list; do
tmpout=$(mktemp -p $tmpdir)
dd iflag=fullblock if=$tmpfile ibs=$(($i+$delimeter_len)) obs=1M skip=1 | while true; do
read line
if [[ $line == $'\015' ]]; then
cat - > $tmpout
break
fi
done
length=$(grep $tmpout --byte-offset -ae ${r[content_boundary]} | sed -E 's/:(.*)//' | head -n 1)
outfile=$(mktemp -p $tmpdir)
post_multipart+=($outfile)
dd iflag=fullblock if=$tmpout ibs=$length count=1 obs=1M of=$outfile
rm $tmpout
done
rm $tmpfile
else
read -N ${r[content_length]} data
declare -A post_data