#!/bin/bash
# Author: Itay Levy
# Source: https://github.com/levyitay/AddSecurityExceptionAndroid
# Adopted to be used in android-pentest-tool

sessionDir=$1
apkToolPath=$2
networkXmlPath=$3

# launch in a separate terminal window
if [ ! -t 1 ]; then
    gnome-terminal -x bash -c "$0 $sessionDir $apkToolPath $networkXmlPath; bash"
    exit
fi

cd /tmp/

if [ ! -f ~/.android/debug.keystore ]; then
  if [ ! -d ~/.android ]; then
    mkdir ~/.android
  fi
  echo "No debug keystore was found, creating new one..."
  keytool -genkey -v -keystore ~/.android/debug.keystore -storepass android -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000
fi
debugKeystore=~/.android/debug.keystore

fullfile=$sessionDir/original.apk
filename=$(basename "$fullfile")
extension="${filename##*.}"
filename="${filename%.*}"
new="_trust_all.apk"
newFileName=$filename$new
tmpDir=/tmp/$filename

java -jar $apkToolPath d -f -o $tmpDir $fullfile

if [ ! -d "$tmpDir/res/xml" ]; then
	mkdir $tmpDir/res/xml
fi

cp $networkXmlPath $tmpDir/res/xml/.
if ! grep -q "networkSecurityConfig" $tmpDir/AndroidManifest.xml; then
  sed -E "s/(<application.*)(>)/\1 android\:networkSecurityConfig=\"@xml\/network_security_config\" \2 /" $tmpDir/AndroidManifest.xml > $tmpDir/AndroidManifest.xml.new
  mv $tmpDir/AndroidManifest.xml.new $tmpDir/AndroidManifest.xml
fi


java -jar $apkToolPath empty-framework-dir --force $tmpDir
echo "Building new APK $newFileName"
java -jar $apkToolPath b -o $sessionDir/$newFileName $tmpDir
jarsigner -verbose -keystore $debugKeystore -storepass android -keypass android $sessionDir/$newFileName androiddebugkey
