added various scripts

This commit is contained in:
Tobias Kessels
2017-09-18 11:47:26 +02:00
parent a1857f4a5b
commit 555d0ef695
25 changed files with 678 additions and 1 deletions

81
certwipe Executable file
View File

@@ -0,0 +1,81 @@
#!/bin/bash
###################Wipe (optional)
DEVICE=${1}
wipedelay=20
#Test for missing packages
if !( dpkg -s hdparm && dpkg -s dialog && dpkg -s dc3dd && dpkg -s util-linux ); then
echo "Wipe-Skript benötigt die folgenden Pakete:"
echo " hdparm" #secure erase
echo " dialog" #abfrage/menu
echo " dc3dd" #klassisches wipen
echo " util-linux" # > rtcwake für den kurzschlaf um die platte 'aufzutauen'
exit 1
fi
#Wenn kein gültiger Datenträger definiert wurde frage nach
if ( [ -z "$DEVICE" ] || [ ! -b "$DEVICE" ] ) ; then
# Liste verfügbarer Geräte erstellen
W=() # Leere Liste
while read -r line; do # mit Einträgen befüllen
dev=$(echo $line | cut -f1 -d" ")
rest=$(echo $line | cut -f2- -d" " | tr -s " ")
W+=("/dev/${dev}" "${rest}")
done < <( lsblk -l -oname,size,model,type | grep -e disk )
#Datenträger Auswahl anzeigen
DEVICE=$(dialog --backtitle "CERTBw - SecureErase" --title "Verfügbare Datenträger" --menu "Welche Platte soll gewipet werden?" 24 80 17 "${W[@]}" 3>&2 2>&1 1>&3)
fi
#Bei Cancel Abbrechen
if [ ! -b "${DEVICE}" ] ; then
echo "==WIPE : Kein gültiges BLOCK-Device ausgewählt."
sleep 1
read -p "Press [ENTER] key for Shell..."
exit 1
fi
#Warnung anzeigen
#Countdown anzeigen
dialog --backtitle "CERTBw - SecureErase" --defaultno --cancel-label "Abbruch" --colors --title "\Z1!WARNUNG!\Zn" --pause "\n\Z1Der Datenträger ${DEVICE} wird vollständig gelöscht!\Zn\n\nDer SecureErase Prozess darf nicht unterbrochen werden da dieser den den Datenträger \Zblocked\ZB und dieser anschließend manuel entriegelt werden müsste.\n\n\nDer Vorgang wird nach ablauf des Countdowns automatisch fortgesetzt.\n\nUm den DiskWipe \Z4abzubrechen\Zn können Sie:\n \Z4\"Abbruch\" auswählen\n \"ESC\" Drücken\n \"STRG + C\" Drücken\n Den Computer ausschalten\Zn" 24 80 ${wipedelay}
if [ "$?" -gt 0 ] ; then
echo "==WIPE : Wipe wurde vom Nutzer abgebrochen."
sleep 1
read -p "Press [ENTER] key for Shell..."
exit 1
fi
#Prüfen ob SecureErase möglich ist
if (hdparm -I ${DEVICE} | grep supported | grep -q erase); then
echo "==WIPE : Secure Erase wird von ${DEVICE} unterstützt"
#Das Gerät bei bedarf unfreezen durch standby
if ( ! (hdparm -I ${DEVICE} | grep not | grep -q frozen)); then
echo "==WIPE : Das Gerät ${DEVICE} ist frozen"
echo "==WIPE : Das Notebook wird nun für 10 Sekunden in den Standby versetzt."
echo "==WIPE : Das Notebook darf nicht ausgeschaltet werden."
sleep 5
rtcwake -s 10 -m mem
echo "==WIPE : Das Notebook ist wieder aufgewacht. Der Status von ${DEVICE} wird überprüft."
fi
if (hdparm -I ${DEVICE} | grep not | grep -q frozen); then
echo "==WIPE : Das Gerät ${DEVICE} ist 'not frozen'"
echo ; echo
echo "==WIPE : Für SecureErase muss vorübergehend ein ATA-Password (certbw) gesetzt werden."
echo "==WIPE : Wenn der SecureErase - Prozess unterbrochen wird ist die Festplatte unbrauchbar bis sie händisch entriegelt wurde."
echo "==WIPE : Das Notebook darf nicht ausgeschaltet werden."
sleep 5
#set ata password
hdparm --user-master u --security-set-pass certbw ${DEVICE}
#issue secure erase command
hdparm --user-master u --security-erase certbw ${DEVICE}
else #Normal löschen weil unfrezze nicht funktioniert hat
echo "==WIPE : Das Gerät konnte nicht aus dem Status 'frozen' geholt werden."
echo "==WIPE : Das Geräte ${DEVICE} wird überschrieben"
/usr/bin/dc3dd wipe=${DEVICE}
fi
else #Normal löschen
echo "==WIPE : Secure Erase wird NICHT unterstützt"
echo "==WIPE : Das Geräte ${DEVICE} wird überschrieben"
/usr/bin/dc3dd wipe=${DEVICE}
fi

62
codegrab/flm.py Executable file
View File

@@ -0,0 +1,62 @@
#!/usr/bin/python
import sys
import re
pattern=str(sys.argv[1])
filename=str(sys.argv[2])
shortpattern=""
print("Pattern is '%s'" % pattern)
chars={}
for char in pattern:
if not char in chars:
newchar={}
newchar['char']=char
newchar['count']=pattern.count(char)
newchar['idx']=[m.start() for m in re.finditer(char,pattern)]
#print("Char '%s' occurs %d times in pattern %s" % (c,newchar['count'],newchar['idx']))
chars[char]=newchar
shortpattern=shortpattern + char
try:
f=file(filename,'r')
except:
print("[-] Can't open File %s" % filename)
exit(1)
print(shortpattern)
longest_match_yet=0
while longest_match_yet<len(pattern):
read_a_char=f.read(1)
if read_a_char in shortpattern and read_a_char in chars:
#candidate
for index in chars[read_a_char]['idx']:
#lets see if its long enough
possible_length=len(pattern) - index
if possible_length>longest_match_yet:
sub_pattern=pattern[(index+1):]
match_so_far=read_a_char
offset=f.tell()
# print("Possible new Match starting with %s found at %d" % (read_a_char,offset))
# print("trying to find rest of pattern '%s'" % sub_pattern)
x=1
for char_to_compare in sub_pattern:
next_char=f.read(1)
if not read_a_char:
print("No more Chars to consume in File")
break
# print("comparing %s <> %s (%d)" % (next_char,char_to_compare,x))
if next_char != char_to_compare:
break
match_so_far=match_so_far+next_char
x=x+1
# print("matching endet with %d matching chars (%d)" % (x,longest_match_yet))
if x > longest_match_yet:
#new longest Match
print("found new longest match %s at %d" % (match_so_far,offset))
longest_match_yet=x
f.seek(offset)
if not read_a_char:
print("No more Chars to consume in File")
break

12
codegrab/ips.awk Normal file
View File

@@ -0,0 +1,12 @@
BEGIN{
if (max=="") max=3
cmd="for i in {0..255} | shuf "
while ( ( cmd | getline result ) > 0 ) {
print result
}
}
{
print
for (i=4; i >max ; i-=1)
print $i
}

View File

@@ -1,9 +1,10 @@
import os import os
import sys
import subprocess import subprocess
import re import re
pattern=re.compile("(: )([^;]+)") pattern=re.compile("(: )([^;]+)")
for file in os.listdir("/data/cases/006_exchange/export"): for file in os.listdir(sys.argv[1]):
output=subprocess.check_output(["file","-Ni",file]) output=subprocess.check_output(["file","-Ni",file])
match=pattern.search(output) match=pattern.search(output)
mimetype=re.sub(r"\W","_",match.group(2)) mimetype=re.sub(r"\W","_",match.group(2))

17
csv2dot Executable file
View File

@@ -0,0 +1,17 @@
#!/bin/bash
header=1
file=test.csv
output="${file}.dot"
delim=,
s_id=6
d_id=8
e_label=11
cat > "${output}" <<EOF
graph a{
node [shape=record]
EOF
#awk -F"${delim}" '{print "\""$6 "\" -> \"" $8 "\"[label=\"" $11"\"]"}' "${file}" >> "${output}"
awk -F"${delim}" '{print "\""$6 "\" -- \"" $8 "\""}' "${file}" >> "${output}"
echo "}" >> "${output}"

12
csv_cols Executable file
View File

@@ -0,0 +1,12 @@
#!/bin/bash
#check if comma or semicolon
if [[ $( grep -c ',' $1 ) -gt $( grep -c ';' $1 ) ]]
then
delim=','
else
delim=';'
fi
#get headings and display them
head -n1 $1 | tr "$delim" "\n" | nl

19
csv_get Executable file
View File

@@ -0,0 +1,19 @@
#!/bin/bash
#check if comma or semicolon
if [[ $( grep -c ',' $1 ) -gt $( grep -c ';' $1 ) ]]
then
delim=','
else
delim=';'
fi
file=$1
shift
#build cut
cut_cmd="cut -d${delim} -f"
#for option in $* ; do
#head -n1 $file | cut -d${delim} -f${option}
#done
cut_cmd="${cut_cmd}$(echo ${*} | tr ' ' ',') ${file}"
#echo ${cut_cmd%,}
$(echo $cut_cmd)

16
depth Executable file
View File

@@ -0,0 +1,16 @@
#!/bin/bash
max=0
open=0
grep -Po "</?div" OFFIZIELLE\ GEWINN...htigung\ und\ letzter\).eml | while read tag; do
if [[ "$tag" == "<div" ]] ; then
(( open++ ))
else
(( open--))
fi
echo "$open - $max"
if [[ $open -gt $max ]] ; then
max=$open
fi
done

24
fuzz.sh Executable file
View File

@@ -0,0 +1,24 @@
#!/bin/bash
pattern='\b(([01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}([01]?\d{1,2}|2[0-4]\d|25[0-5])\b'
#count ips in log
count=$(cat $1 | grep -Po $pattern | sort -u | wc -l)
#create ip_map for translation of IPs
paste <(cat $1 | grep -Po $pattern | sort -u) <(paste <(shuf <(for i in {0..255};do echo $i; done)) <(shuf <(for i in {0..255};do echo $i; done)) <(shuf <(for i in {0..255};do echo $i; done)) <(shuf <(for i in {0..255};do echo $i; done)) | tr "\t" "." | head -n $count) > ${1}.ip_map
#awk script to replace IPs
awk_script='
NR == FNR {
rep[$1] = $2
next
}
{
for (key in rep)
gsub(key, rep[key])
print
}
'
#OUTPUT
cat $1 | awk "$awk_script" ${1}.ip_map -
echo "Lookup-Table is stored in ${1}.ip_map" >&2

15
get_stp.sh Executable file
View File

@@ -0,0 +1,15 @@
#!/bin/bash
interface=${1}
one_stp=$(timeout -k 10 10 tcpdump -vvv -c1 stp -i ${interface} 2>/dev/null)
root_id=$(echo "$one_stp" | grep -Po "(?<=root-id )[^,]*")
bridge_id=$(echo "$one_stp" | grep -Po "(?<=bridge-id )[^,]*" | cut -f1 -d. )
port_id=$(echo "$one_stp" | grep -Po "(?<=bridge-id )[^,]*" | cut -f2 -d. )
echo "connected over $bridge_id at $port_id to $root_id"
echo $one_stp
if [[ $root_id == "80a3.00:1d:71:b9:f0:80" ]]; then
echo "iassc detected"
fi
#bridge-id c0a3.d0:c7:89:94:b4:00.8009
#bridge-id c0a3.d0:c7:89:94:b4:00.8009

18
lpic.sh Executable file
View File

@@ -0,0 +1,18 @@
#!/bin/bash
index=0
cat $@ | hxselect .qtext -s "@TKE@" | tr -d "\n" | tr -s " " | sed -e 's/@TKE@/\n/g' | while read block; do
(( index++ ))
echo "Frage $index"
echo "=================="
frage=$(echo $block | hxnormalize -e | sed -ne '/div class=qtext/,/div class=answer/p' | html2text)
echo $frage
echo "Antworten:"
answ=$(echo $block | hxnormalize -e | hxselect .answers )
echo $answ
echo "Erklärung:"
expl=$(echo $block | hxnormalize -e | hxselect .explanation )
echo $expl
echo "=================="
echo "=================="
done

11
map.awk Normal file
View File

@@ -0,0 +1,11 @@
NR == FNR {
rep[$1] = $2
next
}
{
for (key in rep)
gsub(key, rep[key])
print
}

11
powershell/getscreen.psm1 Normal file
View File

@@ -0,0 +1,11 @@
Function Get-Screen
{
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$size = [Windows.Forms.SystemInformation]::VirtualScreen
$bitmap = new-object Drawing.Bitmap $size.width, $size.height
$graphics = [Drawing.Graphics]::FromImage($bitmap)
$graphics.CopyFromScreen($size.location,[Drawing.Point]::Empty, $size.size)
$graphics.Dispose()
$bitmap.Save($args[0])
$bitmap.Dispose()
}

29
probability.py Normal file
View File

@@ -0,0 +1,29 @@
#!/usr/bin/env python
import sys
import random
from random import shuffle
from collections import Counter
def main():
employees = []
for i in range(0, 19):
employees.append(1)
for i in range(0, 23):
employees.append(0)
count = 0
for i in xrange(1, 1000001):
temp = employees[:]
shuffle(temp)
if Counter(temp[0:11])[1] == 4:
count += 1
print count / 1000000.
if __name__ == '__main__':
main()
sys.exit(0)

30
ps.py Normal file
View File

@@ -0,0 +1,30 @@
import socket as sk
import sys
print(sys.argv)
print(len(sys.argv))
print("Host:" , sys.argv[1])
default=(21,22,23,80,110,111,135,139,389,443,515,631,3306,3389)
def usage():
print("Usage:",sys.argv[0],"<ip> ( [<start_port> - <end_port] | [<port>] ) ")
if (len(sys.argv)==5) and sys.argv[3]=='-':
try:
ports=range(int(sys.argv[2]),int(sys.argv[4]))
except:
usage()
ports=default
elif len(sys.argv)>2:
ports=sys.arv[2:]
else:
ports=default
print("Ports:", ports)
for port in ports:
try:
s=sk.socket(sk.AF_INET,sk.SOCK_STREAM)
s.settimeout(1)
s.connect((sys.argv[1],port))
print('%d:OPEN' % port)
s.close
except: continue

112
ps_.py Normal file
View File

@@ -0,0 +1,112 @@
import psutil
import os
import pwd
import sys
from collections import defaultdict
mypid=os.getpid()
#Check if run as root
white_list_pname = [ "systemd", "kthreadd", "apport-gtk"]
white_list_pid =[]
if (os.geteuid()) != 0:
print("[-] Not Root")
else:
#whitelist this python script and all parents
cursor=psutil.Process()
ende=0
while cursor != None:
white_list_pid.append(cursor.pid)
cursor=cursor.parent()
print(white_list_pid)
mydict = defaultdict(list)
ps_dict = defaultdict(list)
def on_terminate(proc):
print("[+] Terminating Child: %s" % (str(proc)))
def killpid(pid):
parent = psutil.Process(pid)
print(len(parent.children()))
children=parent.children(recursive=True)
for child in children:
try:
child.terminate()
except Exception as e :
print("[-] FAILED - Terminating Child: %s" % (str(child)))
print("[-] ERROR: %s" % str(e))
gone, still_alive = psutil.wait_procs(children, timeout=3, callback=on_terminate)
for child in still_alive:
try:
child.kill()
except Exception as e :
print("[-] FAILED - Terminating Child: %s" % (str(child)))
print("[-] ERROR: %s" % str(e))
else:
print("[+] Terminating Child: %s" % (str(child)))
try:
parent.terminate()
parent.wait(timeout=3)
parent.kill()
except Exception as e:
print("[-] FAILED - Killing Process: %s" % (str(parent)))
print("[-] ERROR: %s" % str(e))
else:
print("[+] Process Killes: %s" % (str(parent)))
def printproc(p: psutil.Process):
return "{0}({1})".format(p.name(),p.pid())
def printchild(p: psutil.Process):
output=printproc(p) + "-"
for c in p.children():
output+=printproc(c)
#Fill ps_dict with processes
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['pid','uids','ppid','name','create_time','terminal','username'])
except psutil.NoSuchProcess:
pass
else:
pid=str(pinfo['pid'])
ps_dict[pid]=pinfo
#Walk ps_dict and fill in missing information
for key in ps_dict:
p=ps_dict[key]
ppid=str(p['ppid'])
if ppid in ps_dict:
pp=ps_dict[ppid]
p['ppname'] = pp['name']
p['ppusername'] = pp['username']
p['ppuids'] = pp['uids']
p['ppcreate_time'] = pp['create_time']
#Kill all escalators
to_kill=[]
for key in ps_dict:
p=ps_dict[key]
if 'ppusername' in p and 'real=0' in str(p['uids']) and p['username'] not in p['ppusername']:
if p['name'] not in white_list_pname:
print("[+] Escalted Process found: %s (%s)" % (str(p['name']),str(p['pid'])))
printchild(psutil.Process(p['pid']))
for pid in to_kill:
if pid not in white_list_pid:
killpid(pid)

18
read.py Normal file
View File

@@ -0,0 +1,18 @@
#!/usr/bin/python3
import fileinput
import sys
import os
files=set()
for param in sys.argv[1:]:
if os.path.isfile(str(param)):
# print(param,"is file")
files.add(param)
# else:
# print(param,"NOT a file")
print("all files:", files)
files.add("-")
for line in fileinput.input(files if len(files)>0 else "-"):
print(fileinput.filename(),":",line)

4
reset_screens.sh Executable file
View File

@@ -0,0 +1,4 @@
#!/bin/bash
xrandr --output DVI-I-1 --mode 1920x1080 --rotate left --pos 0x0
xrandr --output DP-2 --primary --mode 2560x1440 --pos 1080x350
xrandr --output DP-3 --mode 2560x1440 --pos 3640x350

11
rootshell.c Normal file
View File

@@ -0,0 +1,11 @@
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
setuid(0);
system("/bin/bash");
return 0;
}

17
search.py Normal file
View File

@@ -0,0 +1,17 @@
import math
x=1
notfound=1
while notfound:
silber=math.pow(x,2)
ungerade=math.floor(silber/16.)%2
rest=silber%16
# print str(silber) + " " + str(ungerade)
if ungerade == 1 and rest>1 and rest<9:
print "rest passt"
print x
print silber
print rest
print 16-rest
notfound=0
x+=1

6
share.sh Executable file
View File

@@ -0,0 +1,6 @@
#!/bin/bash
#ifconfig eth1 10.10.10.1/24
sysctl -w net.ipv4.conf.all.forwarding=1
iptables -t nat -F
iptables -t nat -A POSTROUTING -o eno1 -j MASQUERADE

28
vba_chr_decode.py Normal file
View File

@@ -0,0 +1,28 @@
#!/usr/bin/python
#
# Decode VBA Macro based on chr() obfuscation
# Xavier Mertens <xavier@rootshell.be>
#
import re
import sys
import argparse
def do_chr(m):
if m.group(0):
return eval(re.sub(r'[cC][hH][rR][wW\$]*\(([\d\+\-\s.]*)\)',r'chr(int(\1))', m.group(0)))
return ""
for line in sys.stdin.readlines():
line = re.sub(r'[cC][hH][rR][wW\$]*\(([\d+\+\-\s\.]*)\)', do_chr, line)
line = re.sub(" & ", "", line)
print line.rstrip()
exit
if __name__ == '__main__':
main()
def mname(self, arg):
do_chr(1);
pass

22
watchgrowth.sh Executable file
View File

@@ -0,0 +1,22 @@
#!/bin/bash
old_size=$(du -b "${1}" | cut -f1)
while true; do
sleep 1
new_size=$(du -b "${1}" | cut -f1)
size_diff=$(( ${new_size} - ${old_size} ))
old_size=${new_size}
#speed=$(( ${size_diff} / (1024*1024) ))
progress=""
if [[ $# -eq 2 ]] ; then
total=${2}
progress_p=$(echo "2 k ${new_size} ${total} 100 / / p" | dc)
progress="${progress_p} %"
fi
speed=$(echo "2 k ${size_diff} 1024 1024 * / p" | dc)
echo "${progress} - ${speed} MB/s"
done

101
wipe.sh Normal file
View File

@@ -0,0 +1,101 @@
#!/bin/bash
#disabling Kernellogging to Console
echo '2 4 1 7' > /proc/sys/kernel/printk
#rechnet die eine centrierierte fensterposition aus anhand von bildschirm- & fenstergröße
# 'mitte 50'
function mitte(){
cols=$(tput cols)
mitte=$(echo $(( $cols / 2 - $1 / 2 )) )
echo $mitte
}
#zeigt eine infomeldung für x-Sekunden an
# 'info text 5'
function info(){
text=${1}
text_len=$(( ${#1} + 4 ))
timeout=${2}
dialog --backtitle "CERTBw - Zero-Wipe" --infobox "$text" 3 $text_len; sleep $timeout
}
#zeigt überischt von datenträgern an und fragt ab welcher gewipet werden soll
function ask_4_device(){
[ -e /tmp/devicelist ] || rm /tmp/devicelist
lsblk -o NAME,SIZE,TYPE,FSTYPE | tail -n+2 | tr -cd ',.\n [:alnum:]' | awk '{printf "%-5s%6s %s (%s) \n" , $1,$2,$3,$4}' | sed -e "s/()//g" >/tmp/devicelist
devlines=$(( $(cat /tmp/devicelist | wc -l) + 2 ))
dialog --backtitle "CERTBw - Zero-Wipe" --begin 2 $(mitte 30) --title "Available Devices" --progressbox $devlines 30 --and-widget --stdout --inputbox 'Welche Platte soll gewipet werden?' 7 60 '/dev/sda' < /tmp/devicelist
result=${?}
return $result
}
#prüft den rückgabewert des vorangegangenen 'dialog' fensters auf abbruch und startet das menu neu
function check_result(){
result=${?}
if ([ $result = 1 ] || [ $result = 255 ]); then
info 'CANCELED' 1
menu
exit 0
fi
}
#kopiert Nullen auf das Angegebene Gerät und zeitg den Fortschritt mit 'dialog' an
function wipe(){
#anlegen von named pipes für den Datenstrom und Statusmeldungen
mkfifo data
mkfifo status
size_512=$(blockdev --getsz $1)
size=$((512 * ${size_512}))
echo "wiping Disk $1:"
(while read -r line
do
#Zusammenfassen von Informationen für das Dialogfenster in ein 'dialog' kompatibles Format
split=$(echo $line | tr -d "%[]=<>" | xargs)
space=$(echo "$split" | cut -f1 -d" ")
time=$(echo "$split" | cut -f2 -d" ")
rate=$(echo "$split" | cut -f3 -d" ")
prozent=$(echo "$split" | cut -f4 -d" ")
eta=$(echo "$split" | cut -f6 -d" ")
echo "XXX"
echo $prozent
echo "Wiped $space in $time so far. ($rate)"
echo "ETA : $eta"
echo "XXX"
done < <(pv -f -s $size /dev/zero 1>data 2>status | dd bs=1M iflag=fullblock oflag=nocache if=data of=$1 2>/dev/null | stdbuf -oL tr "\r" "\n" <status) ) | dialog --backtitle "CERTBw - Zero-Wipe" --title "Wiping $1" --gauge "Please wait" 7 70 0
rm data
rm status
}
function menu(){
menu=$(dialog --stdout --backtitle "CERTBw - Zero-Wipe" --title "Wiping Complete" --menu "Action:" 0 0 5 1 Reboot 2 Poweroff 3 Verify 4 Re-Wipe 5 Shell)
case "$menu" in
1) info "REBOOTING" 1; reboot
exit 0
;;
2) info "SHUTTING DOWN" 1; poweroff
exit 0
;;
3) info "Verify - Not yet implemented" 3
menu
;;
4) /etc/wipe.sh
exit 0
;;
5) exit 0
;;
*) info 'CANCELED' 1
exit 0
;;
esac
}
##simpler ablauf
drive=$(ask_4_device)
check_result
wipe $drive
menu
exit 0