• Changelog
  • Social Media
  • Support
  • About
  • Contact

CK’s Technology News

  • Combining AFWall and IPFire

    November 15th, 2016

    This is a test for IPFire and and not finished, I will upload the finished version on GitHub fully documented.

    Once finished you will be quickly able to block entire ASN ranges.

    #!/bin/bash
    #
    # Beta version
    # ToDo
    # Comment
    # Upload on GitHub
    # Fix IPv6 among other stuff in v1.1+
    #
    customnetworks=/var/ipfire/fwhosts/customnetworks
    customgroups=/var/ipfire/fwhosts/customgroups
    
    auto_remark="entry by asn_ipfire.sh"
    
    iptable_path="/sbin/iptables"
    afwall_path="/system/bin/iptables"
    
    file_network="network_list.txt"
    file_network_raw="$file_network"
    file_iptable="iptable_rules.txt"
    file_afwall="afwall_rules.txt"
    file_asn="asn_list.txt"
    
    
    getASNfromCOMPANY=(gather_ASN0 gather_ASN1)
    getNETfromASN=(gather_NET1)
    
    local_asn_file="local_asn_list.txt"
    local_net_file="local_net_list.txt"
    
    	gather_ASN0() {	if [[ -f $local_asn_file ]]; then cat $local_asn_file | grep -i " $1 " | grep -Eo 'AS[0-9]+' ; fi; }
    	gather_ASN1() {	curl --silent "https://www.ultratools.com/tools/asnInfoResult?domainName=$1" | grep -Eo 'AS[0-9]+' | uniq; }
    	gather_ASN2() { curl --silent "http://cidr-report.org/as2.0/autnums.html" | grep -i " $1 " | grep -Eo 'AS[0-9]+'; }
    	gather_ASN3() { curl --silent "http://www.bgplookingglass.com/list-of-autonomous-system-numbers" | sed 's/<br /\n/g' | grep -i " $1 " | grep -Eo 'AS[0-9]+'; }
    	gather_NET0() {	if [[ -f $local_net_file ]]; then cat $local_net_file | grep -i " $1 " | grep -Eo '([0-9.]+){4}/[0-9]+' | sort -u ; fi; }
    	gather_NET1() { curl --silent "https://stat.ripe.net/data/announced-prefixes/data.json?preferred_version=1.1&resource=$1" | grep -Eo '([0-9.]+){4}/[0-9]+' | sort -u ; }
    
    	cdr2mask()
    	{
    		set -- $(( 5 - ($1 / 8) )) 255 255 255 255 $(( (255 << (8 - ($1 % 8))) & 255 )) 0 0 0
    		[ $1 -gt 1 ] && shift $1 || shift
    		echo ${1-0}.${2-0}.${3-0}.${4-0}
    	}
    
    	get_firstIP() {	echo $1 | sed -e 's/\//\./' | awk -F"." '{ printf "%d", $1*2^24+$2*2^16+$3*2^8+$4 }'; }
    	get_IPrange() { echo $1 | awk -F"/" '{ printf "%d", 2^(32-$2)}'; }
    	get_lastIP() { echo $1 | sed -e 's/\//\./' | awk -F"." '{ printf "%d", $1*2^24+$2*2^16+$3*2^8+$4+2^(32-$5)}'; }
    
    	range2netmask () {
    		declare range=$1
    		declare range2=0
    		declare i=0
    		while [[ $range -gt `echo 2^$i | bc` ]]; do i=$[i+1]; done
    		if [[ $range -eq `echo 2^$i | bc` ]]; then
    			result="$result $[32-i]"
    		else
    			i=$[i-1]
    			range2=$[$range - `echo 2^$i | bc`]
    			result="$result $[32-i]"
    			range2netmask $range2
    		fi
    	}
    
    	dec2ip() {
    		ip1=`echo $1 | awk '{ printf "%i", $1 / (2^24) }'`
    		ip2=`echo $1 $ip1 | awk '{ printf "%i", ($1-$2*(2^24)) / (2^16) }'`
    		ip3=`echo $1 $ip1 $ip2 | awk '{ printf "%i", ($1-$2*(2^24)-$3*(2^16)) / (2^8) }'`
    		ip4=`echo $1 $ip1 $ip2 $ip3 | awk '{ printf "%i", $1-$2*(2^24)-$3*(2^16)-$4*(2^8) }'`
    		echo "$ip1.$ip2.$ip3.$ip4"
    	}
    
    	rm_redundantIP() {
    		declare -a array1=("${!1}")
    		declare -a array2=()
    		declare maxIP=0
    		declare n=0
    		for net in ${array1[@]}; do
    			lastIP=`get_lastIP $net`
    			if [[ $lastIP -gt $maxIP ]]; then
    				array2[$n]=$net
    				maxIP=$lastIP
    				n=$[n+1]
    			fi
    		done
    
    		for net in ${array2[@]}; do
    			if [ $net ]; then echo ${net}; fi
    		done
    	}
    
    	rm_adjacentIP() {
    		declare -a array1=("${!1}")
    		declare -a array2=()
    		declare oldlastIP=0
    		declare n=0
    		declare d=1
    		declare range=0
    
    		for net in ${array1[@]}; do
    			firstIP=`get_firstIP $net`
    			netmask=`get_IPrange $net`
    			lastIP=`get_lastIP $net`
    
    			if [ $firstIP -eq $oldlastIP ]; then
    				d=$[d+1]
    				if [ $d -eq 2 ]; then
    					range=`get_IPrange ${array2[$[n-1]]}`
    				fi
    				range=$[$range + $netmask]
    			elif [ $d -gt 1 ]; then
    				newfirstIP=`get_firstIP ${array2[$[n-d]]}`
    				result=""
    				range2netmask $range
    
    				for dicr in $result; do
    					array2[$[n-d]]=`dec2ip $newfirstIP`"/"$dicr
    					newfirstIP=`get_lastIP ${array2[$[n-d]]}`
    					d=$[d-1]
    				done
    				while [ $d -gt 0 ]; do
    					array2[$[n-d]]=""
    					d=$[d-1]
    				done
    				d=1
    			fi
    			array2[$n]=$net
    			oldlastIP=$lastIP
    			n=$[n+1]
    		done
    
    		for net in ${array2[@]} ; do
    			if [ $net ]; then echo ${net}; fi
    		done
    	}
    
    	addNetworks() {
    		if [ ! $1 ]; then
    			# Get highest number from existing objects in [customnetworks|customgroups]
    			if [[ -f $customnetworks ]]; then
    				network_object_number=$(cat $customnetworks | cut -f1 -d',' | awk '{for(i=1;i<=NF;i++) if($i>maxval) maxval=$i;}; END { print maxval;}')
    			else
    				echo "File $customnetworks not found. Check your IPFire installation."
    				exit 0
    			fi
    			if [[ -f $customgroups ]]; then
    				group_object_number=$(cat $customgroups | cut -f1 -d',' | awk '{for(i=1;i<=NF;i++) if($i>maxval) maxval=$i;}; END { print maxval;}')
    			else
    				echo "File $customgroups not found. Check your IPFire installation."
    				exit 0
    			fi
    			network_object_number=$[network_object_number +1]
    			group_object_number=$[group_object_number +1]
    		fi
    		for company in ${company_array[@]}; do
    			declare asn_array=()
    			declare asn_list=()
    			echo "---[Get all $company ASNs]---"
    			for asn_gather in ${getASNfromCOMPANY[@]}; do
    				asn_array=(`$asn_gather $company`)
    				asn_list=(`echo ${asn_list[@]} ${asn_array[@]} | sed 's/ /\n/g' | sort -u -tS -n -k2,2`)
    			done
    			if [ ! $asn_list ]; then
    				echo "---[No ASN found for $company]---"
    			else
    				declare net_array=()
    				declare net_list=()
    				for asn in ${asn_list[@]}; do
    					echo "---[Get $company networks for $asn]---"
    					for net_gather in ${getNETfromASN[@]}; do
    						net_array=(`$net_gather $asn`)
    						net_list=(`echo ${net_list[@]} ${net_array[@]} | sed 's/ /\n/g' | sort -u`)
    					done
    				done
    				if [ ! $net_list ]; then
    					echo "---[No networks found for $company]---"
    				else
    					echo "---[Remove adjacent and overlapping netblocks]---"
    					before=${#net_list[@]}
    					IFS=$'\n' net_list=($(echo "${net_list[*]//\//.}" | sort -t. -n -k1,1 -k2,2 -k3,3 -k4,4 -k5,5 | awk -F"." '{ printf "%d.%d.%d.%d/%d\n", $1, $2, $3, $4, $5 }'))
    					unset IFS
    					if [ "$1" != "network_raw" ]; then
    						net_list=(`rm_redundantIP net_list[@]`)
    						net_list=(`rm_adjacentIP net_list[@]`)
    					fi
    					after=${#net_list[@]}
    
    					echo "---[Creating objects for $company networks]---"
    					case "$1" in
    						"--asn") {
    							printf "### Company: ${company} ###\n" >> $output_file
    							for net in ${asn_list[@]}; do
    								printf "${net}\n" >> $output_file
    							done
    						};;
    						--network|--network_raw) {
    							printf "### Company: ${company} ###\n" >> $output_file
    							for net in ${net_list[@]}; do
    								printf "${net}\n" >> $output_file
    							done
    						};;
    						--iptable) {
    							printf "## Company: ${company}\n" >> $output_file
    							for net in ${net_list[@]}; do
    								printf "${iptable_path} -A OUTPUT -d ${net} -j REJECT\n" >> $output_file
    							done
    						};;
    						--afwall) {
    							printf "## Company: ${company}\n" >> $output_file
    							for net in ${net_list[@]}; do
    								printf "${afwall_path} -A \"afwall\" -d ${net} -j REJECT\n" >> $output_file
    							done
    						};;
    						*) {
    							counter=1
    							for net in ${net_list[@]}; do
    								# Seperate IP and netmask
    								ip=${net%/*}
    								if [ "$ip" != "0.0.0.0" ]; then
    									netmask=${net#*/}
    									printf "$network_object_number,$company-Network Nr.$counter,$ip,$(cdr2mask $netmask),$auto_remark\n" >> $customnetworks
    									printf "$group_object_number,$company,$auto_remark,$company-Network Nr.$counter,Custom Network\n" >> $customgroups
    									network_object_number=$[$network_object_number +1]
    									group_object_number=$[$group_object_number +1]
    									counter=$[$counter +1]
    								fi
    							done
    						};;
    					esac
    				fi
    			fi
    		done
    	}
    
    	cleanupNetworks() {
    		for ipfire_file in $customnetworks $customgroups; do
    			if [[ -f $ipfire_file ]]; then
    				if [[ ${company_array[0]} == "ALL" ]]; then
    					echo "---[Removing $company objects from $ipfire_file ]---"
    					sed -i "/,$auto_remark/Id" $ipfire_file;
    				else
    					for company in ${company_array[@]}; do
    					echo "---[Removing $company objects from $ipfire_file ]---"
    						sed -i "/$company.*$auto_remark/Id" $ipfire_file;
    					done
    				fi
    			fi
    		done
    	}
    
    	print_help() {
    		echo "Usage: asn_ipfire.sh [OPTION] [COMPANYs | -f FILE]"
    		echo "Add or remove networks to IPFire firewall Groups: Networks & Host Groups"
    		echo
    		echo "Options:"
    		echo "  -a, --add         Add new company networks"
    		echo "  -r, --remove      Remove company networks from customnetworks & customgroups"
    		echo "                    COMPANY='ALL' to remove all entries done by this script"
    		echo "  -f, --file FILE   Get company list from FILE"
    		echo "  -l, --list        List entries done by this script"
    		echo "      --renumber    Renumber lines of customnetworks & customgroups files"
    		echo "  -h, --help        Show this help"
    		echo
    		echo "Create special output files (Non-IPFire-Mode):"
    		echo "  --network        Create FILE '$file_network' with networks"
    		echo "  --network_raw    dito, but networks not consolidated"
    		echo "  --asn            Create FILE '$file_asn' with ASNs only"
    		echo "  --iptable        Create FILE '$file_iptable' with iptable rules"
    		echo "  --afwall         Create FILE '$file_afwall' with afwall rules"
    		echo
    	}
    
    
    company_array=()
    mode=""
    helptext="Usage: asn_ipfire.sh [OPTION] [COMPANYs | -f FILE] \nTry 'asn_ipfire.sh --help' for more information."
    
    if [[ $# -eq 0 ]]; then	echo -e $helptext; exit 0; fi
    if [[ $# -gt 4 ]]; then	echo -e "Too many arguments.\n"$helptext; exit 0; fi
    
    while [[ $# > 0 ]] ; do
    	case $1 in
    		-f | --file) {
    			if [[ -f $2 ]]; then
    				company_array_from_file=(`sed 's/[,]/ /g; s/[\/]//g' <<< cat $2`)
    				shift
    			else
    				echo "File not found."
    				echo -e $helptext
    				exit 0
    			fi
    		};;
    		-a|--add | -r|--remove | --asn | --network | --network_raw | --iptable | --afwall) {
    			if [[ $mode ]]; then
    				echo -e "Too many arguments.\n"$helptext
    				exit 0
    			else
    				mode=$1
    			fi
    			if [[ $2 && ${2:0:1} != "-" ]]; then
    				company_array_from_arg=(`sed 's/[,]/ /g; s/[\/]//g' <<< $2`)
    				shift
    			fi
    		};;
    		-l|--list | --renumber | -v|--version | -h|--help ) {
    			if [[ $mode || $2 ]]; then
    				echo -e "Too many arguments.\n"$helptext
    				exit 0
    			else
    				mode=$1
    			fi
    		};;
    		*) {
    			echo -e "Unknown argument.\n"$helptext
    			exit 0
    		};;
    	esac
    	shift
    done
    
    company_array=(`echo ${company_array_from_file[@]} ${company_array_from_arg[@]} | sed 's/ /\n/g' | sort -uf`)
    
    case $mode in
    
    	-a|--add | -r|--remove) {
    		if [ ! $company_array ]; then
    			echo "No company names found. Nothing done!"
    			echo "Try 'asn_ipfire.sh --help' for more information."
    			exit 0
    		fi
    		cleanupNetworks
    		if [[ $mode == "-a" || $mode == "--add" ]]; then
    			addNetworks
    		fi
    		/etc/init.d/firewall restart
    		echo "---[All done!]---"
    	};;
    
    	-l|--list) {
    		if [[ -f $customnetworks ]]; then
    			# Show companies from customnetworks
    			echo "Company names in "$customnetworks":"
    			cat $customnetworks | grep "$auto_remark" | grep -Eo '[a-Z]*-Network Nr' | sort -u | sed 's/-Network Nr//'
    		else
    			echo "File $customnetworks not found."
    		fi
    		if [[ -f $customgroups ]]; then
    			# Show companies from customgroups
    			echo "Company names in "$customgroups":"
    			cat $customgroups | grep "$auto_remark" | grep -Eo '[a-Z]*-Network Nr' | sort -u | sed 's/-Network Nr//'
    		else
    			echo "File $customgroups not found."
    		fi
    	};;
    
    	--renumber) {
    		if [[ -f $customnetworks ]]; then
    			sed -i '/^$/d;=' $customnetworks
    			sed -i 'N;s/\n[0-9]\+//' $customnetworks
    			echo "File $customnetworks renumbered."
    		else
    			echo "File $customnetworks not found."
    		fi
    		if [[ -f $customgroups ]]; then
    			sed -i '/^$/d;=' $customgroups
    			sed -i 'N;s/\n[0-9]\+//' $customgroups
    			echo "File $customgroups renumbered."
    		else
    			echo "File $customgroups not found."
    		fi
    	};;
    
    	--asn | --network | --network_raw | --iptable | --afwall ) {
    		output_file="file_"${mode:2}
    		output_file="${!output_file}"
    
    		if [ $company_array ]; then
    			touch $output_file > $output_file
    			addNetworks	$mode
    			echo "---[All done!]---"
    		else
    			echo "No company names found. Nothing done!"
    			echo "Try 'asn_ipfire.sh --help' for more information."
    		fi
    	};;
    
    	-v|--version) echo $revision;;
    
    	-h|--help) print_help;;
    
    	*) echo -e $helptext;;
    
    esac
    
    exit 0

    Update

    This troll accuses me to copy my own work. Someone who stole the Instant Messenger chart from Wikipedia, I also never heard of maloe. Possible a Kuketz donater which he likes to help and defend.

    I never deal with threats against my work or me as person. This Mike clown also never wrote jack-shit on my script.

    No one contacted me or tried to discuss anything with me, they threatens me and I do not need to give credit to others for my own work.

    I wrote parts of AFWall+ and practical the whole Wiki myself. If you want to spread lies on behalf of my back, actually check real facts and maybe contact me and do not send your goons or you own alt accounts on an issue ticket, how about that. Well abusing issue tickets seems to be a thing.

    Advertisement
  • Launchon stole my script, re-GPLed it, edited his XDA thread countless times and afterwards uploaded my work on GitHub, claiming it is his

    February 27th, 2016

    Nutshell

    • My original script by me was uploaded 12 hours before he posted it on XDA, there is also a time delay between USA and Germany. He simply ignore the fact, claiming clocks are the same around the world, this is not the case.
    • I btw removed nothing from my own code, as he wrongfully claims because all code was written by myself. There is no screenshot, commit or anything except that this Launchon clown afterwards uploaded my work in one of his GitHub repo. Pointless effort because he never wrote much before not afterwards on GitHub. He has like not even 100 commits, properly stolen from other people.
    • Launchon not even mention all things and claims he invented the whole script, he edited his XDA thread countless times and spread lies via verbal attack on XDA (later on GitHub) he added pretty quickly a license and uploaded it onto GitHub, missing the point that there are time-zone differences between me and him and that I posted it already first in the Android-Hilfe.de forum. After a GitHub Staff warned him, he quickly posted another .md file, with countless edits. Apparently I am more interesting than, what he calls his own work, which is nothing but stolen from me.
    • An Android-Hilfe Mod contacted me 1 day later after Launchon took my stuff and countless XDA thread edits later to clear the situation with me. I showed him my link to a private and public gist, he refused to accept it as legit and I left the forum on my own terms, I did not got banned or something because I do not support forums that went against their own members. I was years long member in this forum without any problems at all. I mean I do not care because the forum, same like XDA went to a place for trolls, and I am not the only one who says that.
    • A GitHub Staff had to edit and intervene into Lanchon repository dealing with his nonsense accusation, which is still misinformation btw. Lanchon was never really active on GitHub, which shows what troll action this was. He got punished accordingly and warned, and maybe he created or used an alt account to continue trolling as comment. After that, his GitHub went blank and nothing was ever been uploaded after that, while my script is still maintained. Android simply evolved and I wrote an more useful app out from it.
    • Lanchon is a attention seeking person who cries a lot about everything, if you check his commits, then you see he clearly is a troll.

    Misinformation he spreads

    No XDA mod contacted me, only the German Mod, which I explained in-depth above.

    Launchon edited and re-GPLed, what he calls, his script, and then edited the topic as well as his scripts many times. He has no prove because of that, XDA also has no revisions history. The timestamp proves me right. Just a reminder that copyright is about who created it first and not who edited or uploading it first.

    My account was not terminated and no one took over anything at all. I said that the Mod can remove the content if he wants to do that. I personally do not cared much here.

    I added clear prove on several sites showing that Launchon re-GPLed my code, he says this is nonsense, shows his character. He knows nothing about respect, copyright and edits everything afterwards.

    He posts prove himself, nothing there was stolen nor is anything in english. This was captured before he started editing and smearing my name, my script and my stuff.

    He even said he has no version 1 of his file, because that would show the reality, that he removed my name and changed the file. This was actually 12 and not 6 hours before.

    If there is a demand, I post the Mod discussion in public. I have absolute nothing to worry about nor to hide here.

    Links he posted as so-called proof never worked in the first place.

    He uploaded and edited all his threads afterwards.

    Uploaded my version later.

    His log file which he posted here is pretty much irrelevant, it does not show any code or any license nor the script itself. That is also no prove at all, not sure why he mentioned it in his outcry. He never put any effort in, what he calls his script, as you can see here, his stopped entirely his work after I stopped uploading my script. He was more busy editing his threads and smearing my name.

    Update – Launchons prove link points to nothing. Of course, I would believe the one who accuses me, how do we know, even if there were files that they are not manipulated anyway. Calls it fiasco. Well actually stealing my files and then pretend you are the one with the damage, nice move.
    All links point to nothing or only his log file, no actual script tho. You stole my script and uploaded the output, this is what it proves. His entire proof is – you are delusional -.

    Random bogus claims from Launchon

    He claims I stole another project. Never heard of it nor is there anything to back that up. You stole my stuff and re-GPLed it then claim you deliberately left out the license, ridiculous, why should anyone do that and cry afterwards like a child.

    Conclusion

    Lanchon is someone who stole my script, edited all of his posts except the one with an useless log file and then re-licensed my work under GPL claiming I would steal his work when there is absolute no proof at all, the web-machine link shows the thread looked entirely different and there was no plagiarism involved, he simply violated my license and later uploaded my stuff on a GitHub repo to make it look that he is the owner. He never worked on the script nor had any interest at all, I never heard of him before nor afterwards. He calls me a troll, someone who has not even 100 commits and outcries whenever he thinks someone did injustice to him, this is cringe.

    Update

    He never contacted me, wrote me an eMail, instead he cried several times my name on GitHub. And I never responded because I do not deal with trolls.

    More people stole my work and I never out cried like this.

    My work was btw originally done in 2014 and not in 2016.

    See here. This was the first public and final version, after the work from 2014.
    From my actual Mega Drive. The flasher version never work so I provided a script only version.

    I clearly showed that. I am now 30 years on the internet and I survived lots of troll attempts, this is just another one from someone no one cares about.

    He continues to edit his stuff and smear my name

    Update 2

    I debunked all accusations from trolls here and re-published the article with typo fixes. I would not cry so loud when I steal my own name from others. But what can you expect from a nobody, right, nothing.

    Facts is more people stealing my work without permission or mirroring it and I do not cry at all, I mention it maybe once, but that is it. I do not seek attention and I never did, I do my work, if people steal it then this is it, I always work harder and I showed that so many times.

    Update 3

    He calls me troll, but acts like a child. Outcry is his Trademark.

    Commit, bashes his own platform of choice. Like a troll.
    I busted claustromanic stealing himself btw. He and his girlfriend tried to smear my name, created and abused GitHub issue ticket, which was closed by an GitHub staff due to misinformation and harassment. I hope more people see this, supporting such clowns.
    He insults me and calls it censorship. He got warned via eMail by an GitHub staff. Yet he continued and created an entire .md file to spread misinformation in his outcry.
    This is made-up like the rest, I was not banned at all, my public profile is hidden because I dared to say something against cheater. See here.
    When you have no argument, sure as hell everything I said is and was a lie, what a child.
    There never was CP to begin with, this is also made-up. I highly doubt he can code any hello world. GitHub Bot wrongfully flagged an .onion domain. As of today, the .onion domain is public visible via Google search and there is no CP. The story is something I leaked to show that GitHub actually makes mistakes, something you yourself claim above, but you call it censorship.
    The troll and liar are you my friend, on behalf of my back and my reputation. Kuketz is debunked as liar among his community in another Blog post.

    Remember that I helped the user who back stabbed me. This is pathetic, this is what you get if you are kind, back stabbing from people that are not even coder or useful. Just alt-accounts.

  • Repitter solution for I9100 partition space problem

    December 6th, 2015

    After 2 months of tests I publish my first but unfinished script to handle the known partition problematic with the Samsung Galaxy S2 phones.

    I plan to release the full working solution in a few months or if I have more time.

    #!/sbin/sh
    
    if [ "$1" != "CHEF-KOCH-test" ]; then
        out="/proc/self/fd/$2"
        zip="$3"
        print() {
            local s="$1"
            if [ -z "$s" ]; then s=" "; fi
            >$out echo "ui_print $s"
            >$out echo "ui_print"
        }
        print
        set -o pipefail
        /sbin/sh "$0" "CHEF-KOCH-test" "$zip" 2>&1 | (
            while read line; do print "$line"; done
        )
        code="$?"
        print
        if [ "$code" -eq "0" ]; then
            print "[OK]";
        else
            print "[ERROR $code]";
        fi
        print
        exit "$code"
    fi
    shift
    
    #!/sbin/sh
    
    # CHEF-KOCH REPIT
    
    set -e
    
    deviceName="i9100"
    
    sdev=/sys/devices/platform/dw_mmc/mmc_host/mmc0/mmc0:0001/block/mmcblk0
    spar=$sdev/mmcblk0p
    
    ddev=/dev/block/mmcblk0
    dpar=/dev/block/mmcblk0p
    
    tdir=/tmp/CHEF-KOCH-pitter
    tchunk=$tdir/chunk.tmp
    
    tpar=$tdir/part-info/p
    
    # disk area to use for movable partitions:
    heapStart=344064
    heapEnd=30769152
    
    # minimum partition size: 8 MB
    minParSize=$(( 8 * 1024 * 2 ))
    
    fatal() {
        >&2 echo "FATAL:" "$@"
        exit 1
    }
    
    warning() {
        >&2 echo "WARNING:" "$@"
    }
    
    info() {
        echo "info:" "$@"
    }
    
    checkTool() {
        info "checking tool: $1"
        if [ -z "$(which "$1")" ]; then
            fatal "required tool missing: $1"
        fi
    }
    
    runParted() {
        parted -s $ddev unit s "$@"
    }
    
    rereadParTable() {
        info "rereading partition table"
        sync
        blockdev --flushbufs $ddev
        blockdev --rereadpt $ddev
        sleep 0.5
    }
    
    parStart() {
        cat ${1}$2/start
    }
    
    parSize() {
        cat ${1}$2/size
    }
    
    parEnd() {
        echo $(( $(parStart $@) + $(parSize $@) ))
    }
    
    parName() {
        echo -n "partition #$1 /$(cat ${tpar}$1/mname) ($(cat ${tpar}$1/pname))"
    }
    
    initPar() {
    
        local n=$1
    
        mkdir -p ${tpar}$n
        echo -n $2 >${tpar}$n/pname
        echo -n $3 >${tpar}$n/mname
        if [ $(( $(parStart $spar $n) <= 0 )) -ne 0 ]; then
            fatal "$(parName $n): invalid start"
        fi
        if [ $(( $(parSize $spar $n) <= 0 )) -ne 0 ]; then
            fatal "$(parName $n): invalid size"
        fi
    
    }
    
    initParNew() {
    
        local n=$1
        local size="$2"
        local content="$3"
        local fs="$4"
        local defaultFs="$5"
    
        if [ -z "$size" ]; then
            fatal "$(parName $n): undefined new size"
        fi
        if [ -z "$content" ]; then
            fatal "$(parName $n): undefined content policy"
        fi
        if [ -z "$fs" ]; then
            fs=$defaultFs
        fi
    
        # size granularity: MB
        # size unit: GB
        local granularity=2048
        local unit=1024
        case "$size" in
            same)
                size=$(parSize $spar $n)
                ;;
            min)
                size=$minParSize
                ;;
            max)
                size=0
                ;;
            *)
                size=$(awk "BEGIN {print int(($size) * $unit + 0.5)}")
                size=$(( ($size) * $granularity ))
                if [ $(( $size < minParSize )) -ne 0 ]; then
                    fatal "$(parName $n): invalid new size"
                fi
                ;;
        esac    
    
        case "$content" in
            keep)
                ;;
            wipe)
                ;;
            *)
                fatal "$(parName $n): invalid content policy"
                ;;
        esac    
    
        case "$fs" in
            ext4)
                ;;
            vfat)
                ;;
            *)
                fatal "$(parName $n): invalid file system type"
                ;;
        esac    
    
        echo -n $size >${tpar}$n/size
        echo -n $content >${tpar}$n/content
        echo -n $fs >${tpar}$n/fs
    
    }
    
    setup() {
    
        rm -rf $tdir
    
        checkTool parted
        checkTool blockdev
        checkTool awk
    
        echo "unmounting all partitions"
    
        local n
        for n in $(seq 1 50); do
            if grep -q "^${dpar}$n " /proc/mounts;then
                #info "unmounting $(parName $n)"
                umount ${dpar}$n
            fi
        done
    
        # rereadParTable requires everything unmounted
        rereadParTable
    
        echo "checking existing partition layout"
    
        for n in $(seq 9 12); do
            if [ ! -e ${spar}$n ]; then
                fatal "missing partition #$n"
            fi
        done
    
        if [ -e ${spar}$(( 12 + 1 )) ]; then
            fatal "unexpected partition #$(( 12 + 1 ))"
        fi
    
        initPar  8 MODEM     modem
        initPar  9 FACTORYFS system
        initPar 10 DATAFS    data
        initPar 11 UMS       sdcard
        initPar 12 HIDDEN    preload
    
        if [ $(( $(parEnd $spar 8) != $heapStart )) -ne 0 ]; then
            fatal "$(parName 8): unexpected end: $(parEnd $spar 8)"
        fi
        
        local pn
        local gap
        for n in $(seq 9 12); do
            pn=$(( $n - 1 ))
            gap=$(( $(parStart $spar $n) - $(parEnd $spar $pn) ))
            if [ $(( gap < 0 )) -ne 0 ]; then
                fatal "layout reversal between $(parName $pn) and $(parName $n)"
            fi
            if [ $(( gap > 0 )) -ne 0 ]; then
                warning "unallocated space between $(parName $pn) and $(parName $n)"
            fi
        done
        gap=$(( heapEnd - $(parEnd $spar 12) ))
        if [ $(( gap < 0 )) -ne 0 ]; then
            warning "the existing partition layout uses more space than expected"
        fi
        if [ $(( gap > 0 )) -ne 0 ]; then
            warning "the existing partition layout has unused space at the end of the disk"
        fi
    
        echo "checking new partition layout"
    
        initParNew  9  "$system_size"  "$system_content"  "$system_fs" ext4
        initParNew 10    "$data_size"    "$data_content"    "$data_fs" ext4
        initParNew 11  "$sdcard_size"  "$sdcard_content"  "$sdcard_fs" vfat
        initParNew 12 "$preload_size" "$preload_content" "$preload_fs" ext4
    
        local totalSize=$(( $heapEnd - $heapStart ))
        for n in $(seq 9 12); do
            totalSize=$(( totalSize - $(parSize $tpar $n) ))
        done
        local maxPar
        for n in $(seq 9 12); do
            if [ "$(parSize $tpar $n)" -eq "0" ]; then
                if [ -n "$maxPar" ]; then
                    fatal "more than one partition has its size set to 'max'"
                fi
                maxPar=$n
                if [ $(( $totalSize < minParSize )) -ne 0 ]; then
                    fatal "$(parName $n): invalid new size"
                fi
                echo -n $totalSize >${tpar}$n/size
            fi
        done
    
        echo -n $heapStart >${tpar}9/start
        for n in $(seq 10 12); do
            echo -n $(parEnd $tpar $(( $n - 1 ))) >${tpar}$n/start
        done
    
        gap=$(( $heapEnd - $(parEnd $tpar 12) ))
        if [ $(( gap < 0 )) -ne 0 ]; then
            fatal "the new partition layout requires more space than available"
        fi
        if [ $(( gap > 0 )) -ne 0 ]; then
            warning "the new partition layout has unused space at the end of the disk"
        fi
    
    }
    
    ### general
    
    processParRecreate() {
        local n=$1
        local dev=$2
        local oldStart=$3
        local oldSize=$4
        local newStart=$5
        local newSize=$6
        if [ $(( newStart != oldStart || newSize != oldSize )) -ne 0 ]; then
            info "deleting the partition"
            runParted rm $n
            info "recreating the partition"
            runParted mkpart primary $newStart $(( $newStart + $newSize - 1 ))
            info "naming the partition"
            runParted name $n $(cat ${tpar}$n/pname)
            rereadParTable
        fi
    }
    
    moveDataChunk() {
        local n=$1
        local oldStart=$2
        local newStart=$3
        local size=$4
        echo "----- moving $(( size / (1024 * 2) )) MB chunk: $(( oldStart / (1024 * 2) )) MB -> $(( newStart / (1024 * 2) )) MB"
        # WARNING: dd has a dangerous 4GB wraparound bug!!!
        #dd if=$ddev of=$tchunk bs=512 skip=$oldStart count=$size
        #dd if=$tchunk of=$ddev bs=512 seek=$newStart count=$size
        info "creating temporary partition to read chunk at device offset $(( oldStart / (1024 * 2) )) MB"
        runParted mkpart primary $oldStart $(( $oldStart + $size - 1 ))
        rereadParTable
        info "reading data"
        dd if=${dpar}$n of=$tchunk bs=1M
        info "deleting the temporary partition"
        runParted rm $n
        info "creating temporary partition to write chunk at device offset $(( newStart / (1024 * 2) )) MB"
        runParted mkpart primary $newStart $(( $newStart + $size - 1 ))
        rereadParTable
        info "writing data"
        dd if=$tchunk of=${dpar}$n bs=1M
        info "deleting the temporary partition"
        runParted rm $n
        #rereadParTable
        rm -f $tchunk
        echo
    }
    
    moveData() {
        local pn=$1
        local oldStart=$2
        local newStart=$3
        local size=$4
        # chunk size: 256 MB
        local chunk=$(( 256 * 1024 * 2 ))
        local n
        local m
        if [ $(( newStart < oldStart )) -ne 0 ]; then
            info "moving data towards the beginning of the disk"
            echo
            m=0
            for n in $(seq -- 0 $chunk $(( size - chunk - 1 )) ); do
                moveDataChunk $pn $(( oldStart + n )) $(( newStart + n )) $chunk
                m=$(( $n + chunk ))
            done
            moveDataChunk $pn $(( oldStart + m )) $(( newStart + m )) $(( size - m ))
        fi
        if [ $(( newStart > oldStart )) -ne 0 ]; then
            info "moving data towards the end of the disk"
            echo
            m=$size
            for n in $(seq -- $(( size - chunk )) $(( - chunk )) 1); do
                moveDataChunk $pn $(( oldStart + n )) $(( newStart + n )) $chunk
                m=$n
            done
            moveDataChunk $pn $oldStart $newStart $m
        fi
    }
    
    processParMove() {
        local n=$1
        local oldStart=$2
        local newStart=$3
        local size=$4
        if [ $(( newStart != oldStart )) -ne 0 ]; then
    #rereadParTable
    #echo "##### calculating MD5 hash of partition"
    #md5sum ${dpar}$n
            #info "ensure no access if move is interrupted by deleting the partition"
            info "deleting the partition to workaround dd's 4GB wraparound bug"
            runParted rm $n
            #rereadParTable
            moveData $n $oldStart $newStart $size
            #info "recreating the partition"
            info "recreating the final partition"
            runParted mkpart primary $newStart $(( $newStart + $size - 1 ))
            info "naming the partition"
            runParted name $n $(cat ${tpar}$n/pname)
            rereadParTable
    #echo "##### calculating MD5 hash of partition"
    #md5sum ${dpar}$n
        fi
    }
    
    ### ext4
    
    processPar_ext4_wipe_dry() {
        local n=$1
        local dev=$2
        local oldStart=$3
        local oldSize=$4
        local newStart=$5
        local newSize=$6
        info "will format the partition in ext4 and trim it"
        checkTool mke2fs
    }
    
    processPar_ext4_wipe_wet() {
        local n=$1
        local dev=$2
        local oldStart=$3
        local oldSize=$4
        local newStart=$5
        local newSize=$6
        processParRecreate $@
        info "formatting the partition in ext4 and trimming it"
        mke2fs -q -t ext4 -E discard $dev
    }
    
    processPar_ext4_keep_dry() {
        local n=$1
        local dev=$2
        local oldStart=$3
        local oldSize=$4
        local newStart=$5
        local newSize=$6
        if [ $(( newStart != oldStart )) -ne 0 ]; then
            info "will move the ext4 partition"
            warning "moving a big ext4 partition can take a very long time"
            echo "(it requires copying the complete partition, including its free space)"
            checkTool dd
        fi
        if [ $(( newSize != oldSize )) -ne 0 ]; then
            info "will resize the ext4 partition"
            checkTool resize2fs
        fi
        checkTool e2fsck
        info "checking and trimming the file system"
        e2fsck -fp -E discard $dev
    }
    
    processPar_ext4_keep_wet() {
        local n=$1
        local dev=$2
        local oldStart=$3
        local oldSize=$4
        local newStart=$5
        local newSize=$6
        local moveSize=$oldSize
        if [ $(( newSize < oldSize )) -ne 0 ]; then
            info "shrinking the ext4 file system"
            resize2fs -f $dev ${newSize}s
            info "shrinking the partition entry"
            processParRecreate $n $dev $oldStart $oldSize $oldStart $newSize
            info "checking and trimming the file system"
            e2fsck -fp -E discard $dev
            moveSize=$newSize
        fi
        if [ $(( newStart != oldStart )) -ne 0 ]; then
            info "moving the partition"
            # this should work but does not!
            #runParted move $n $newStart $(( $newStart + $moveSize - 1 ))
            #rereadParTable
            # so we manually dd data around
            processParMove $n $oldStart $newStart $moveSize
            info "checking and trimming the file system"
            e2fsck -fp -E discard $dev
        fi
        if [ $(( newSize > oldSize )) -ne 0 ]; then
            info "enlarging the partition entry"
            processParRecreate $n $dev $newStart $oldSize $newStart $newSize
            info "enlarging the ext4 file system"
            resize2fs -f $dev ${newSize}s
            info "checking and trimming the file system"
            e2fsck -fp -E discard $dev
        fi
    }
    
    ### vfat
    
    processPar_vfat_wipe_dry() {
        local n=$1
        local dev=$2
        local oldStart=$3
        local oldSize=$4
        local newStart=$5
        local newSize=$6
        info "will format the partition in vfat"
        checkTool mkfs.vfat
    }
    
    processPar_vfat_wipe_wet() {
        local n=$1
        local dev=$2
        local oldStart=$3
        local oldSize=$4
        local newStart=$5
        local newSize=$6
        processParRecreate $@
        info "formatting the partition in vfat"
        mkfs.vfat $dev
    }
    
    processPar_vfat_keep_dry() {
        local n=$1
        local dev=$2
        local oldStart=$3
        local oldSize=$4
        local newStart=$5
        local newSize=$6
        if [ $(( newStart != oldStart || newSize != oldSize )) -ne 0 ]; then
            info "will move/resize the vfat partition"
        fi
        checkTool dosfsck
        info "checking the file system"
        dosfsck -pV $dev
    }
    
    processPar_vfat_keep_wet() {
        local n=$1
        local dev=$2
        local oldStart=$3
        local oldSize=$4
        local newStart=$5
        local newSize=$6
        if [ $(( newStart != oldStart || newSize != oldSize )) -ne 0 ]; then
            info "moving/resizing the vfat partition"
            runParted resize $n $newStart $(( $newStart + $newSize - 1 ))
            rereadParTable
            info "checking the file system"
            dosfsck -pV $dev
        fi
    }
    
    ### main
    
    processPar() {
        echo "*****  processing $(parName $1)"
        eval processPar_$(cat ${tpar}$1/fs)_$(cat ${tpar}$1/content)_$mode $1 ${dpar}$1 $(parStart $spar $1) $(parSize $spar $1) $(parStart $tpar $1) $(parSize $tpar $1)
    }
    
    processParList() {
        local rest=${@:2}
        echo "analyzing $(parName $1)"
        if [ -z "$rest" ]; then
            processPar $1
        else
            if [ $(( $(parEnd $tpar $1) > $(parStart $spar $2) )) -ne 0 ]; then
                info "$(parName $1) will expand into disk area of $(parName $2)"
                info "deferring processing of $(parName $1)"
                processParList $rest
                processPar $1
            else
                processPar $1
                processParList $rest
            fi
        fi
    }
    
    checkDevice() {
        case ":$(getprop ro.product.device):$(getprop ro.build.product):" in
            *:galaxys2:*) ;;
            *:i9100:*) ;;
            *:GT-I9100:*) ;;
            *:GT-I9100M:*) ;;
            *:GT-I9100P:*) ;;
            *:GT-I9100T:*) ;;
            *:SC-02C:*) ;;
            *)
                fatal "this package is for '$deviceName' devices (this device is '$(getprop ro.product.device)')"
                ;;
        esac
    }
    
    main() {
        echo " ####################################"
        echo "  CHEF-KOCH REPIT"
        echo "  A Data-Sparing Repartitioning Tool"
        echo "  Copyright 2016, CHEF-KOCH"
        echo "  Device: $deviceName"
        echo " ####################################"
        echo
        checkDevice
        echo "=====  PREPARATION  ====="
        setup
        echo
        echo "=====  DRY-RUN  ====="
        mode=dry
        processParList $(seq 9 12)
        echo
        echo "=====  EXECUTION  ====="
        mode=wet
        processParList $(seq 9 12)
        info "flushing buffers"
        sync
        blockdev --flushbufs $ddev
        sleep 3
        echo
        echo "=====  SUCCESS  ====="
        #echo
    }
    
    stockLayout() {
    
        # Stock partition layout for i9100
    
        system_size=0.5
        data_size=2
        #sdcard_size=11.5078
        sdcard_size=max
        preload_size=0.5
    
        #system_fs=ext4
        #data_fs=ext4
        #sdcard_fs=vfat
        #preload_fs=ext4
    
    }
    
    defaultToKeepData() {
        system_content=keep
        data_content=keep
        sdcard_content=keep
        preload_content=keep
    }
    
    # <partition>_size: <fractional size in GB>|min|max|same
    # <partition>_content: keep|wipe
    # <partition>_fs: ext4|vfat
    
    stockLayout
    
    defaultToKeepData
    
    preload_content=wipe
    
    main "$@"
    

    Update

    Months later a XDA troll seriously accuses me of stealing my own script. Beyond anything but sad.

    I decided to make this public to avoid misinformation.

  • Welcome to my new Blog

    December 4th, 2012

    Welcome
    Greetings earthlings! 🤭

    Hello and welcome to my first Blog post – sounds like a boring intro?! Right, let’s skip it and let me introduce myself!

    My Blog focus will always be:

    • Technology
    • Windows
    • Android
    • Linux
    • Security
    • Pentesting

    I’m in general a person who is highly interested in every technology related topic 🤓 but I prefer to write about Windows and Android because I like both systems and I think the community deserves some quality related articles. (more…)

←Previous Page
1 … 82 83 84

Proudly powered by WordPress

Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
 

Loading Comments...
 

You must be logged in to post a comment.

    • Follow Following
      • CK’s Technology News
      • Join 70 other followers
      • Already have a WordPress.com account? Log in now.
      • CK’s Technology News
      • Edit Site
      • Follow Following
      • Sign up
      • Log in
      • Report this content
      • View site in Reader
      • Manage subscriptions
      • Collapse this bar